2024-09-25 13:37:32 -05:00
|
|
|
import { getServersFromServerListEvent, USER_BLOSSOM_SERVER_LIST_KIND } from "blossom-client-sdk";
|
|
|
|
|
|
|
|
import { BLOSSOM_SERVERS, MAX_FILE_SIZE } from "./env.js";
|
|
|
|
import { makeRequestWithAbort } from "./helpers/http.js";
|
2024-09-26 12:48:13 -05:00
|
|
|
import pool from "./nostr.js";
|
2024-09-25 13:37:32 -05:00
|
|
|
|
2024-09-26 12:48:13 -05:00
|
|
|
export async function getUserBlossomServers(pubkey: string, relays: string[]) {
|
|
|
|
const blossomServersEvent = await pool.get(relays, { kinds: [USER_BLOSSOM_SERVER_LIST_KIND], authors: [pubkey] });
|
2024-09-25 13:37:32 -05:00
|
|
|
|
2024-09-26 08:51:32 -05:00
|
|
|
return blossomServersEvent ? getServersFromServerListEvent(blossomServersEvent).map((u) => u.toString()) : undefined;
|
2024-09-25 13:37:32 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
// TODO: download the file to /tmp and verify it
|
|
|
|
export async function downloadFile(sha256: string, servers = BLOSSOM_SERVERS) {
|
|
|
|
for (const server of servers) {
|
|
|
|
try {
|
|
|
|
const { response } = await makeRequestWithAbort(new URL(sha256, server));
|
|
|
|
|
2024-10-04 12:31:19 -05:00
|
|
|
try {
|
|
|
|
if (!response.statusCode) throw new Error("Missing headers or status code");
|
|
|
|
|
|
|
|
const size = response.headers["content-length"];
|
|
|
|
if (size && parseInt(size) > MAX_FILE_SIZE) throw new Error("File too large");
|
2024-09-25 13:37:32 -05:00
|
|
|
|
2024-10-04 12:31:19 -05:00
|
|
|
if (response.statusCode >= 200 && response.statusCode < 300) {
|
|
|
|
return response;
|
|
|
|
} else throw new Error("Request failed");
|
|
|
|
} catch (error) {
|
2024-09-25 13:37:32 -05:00
|
|
|
// Consume response data to free up memory
|
|
|
|
response.resume();
|
|
|
|
}
|
|
|
|
} catch (error) {
|
|
|
|
// ignore error, try next server
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|