From 7c07211356497ed36119d32943c46cb2e268b30f Mon Sep 17 00:00:00 2001 From: Derrick Hammer Date: Fri, 23 Jun 2023 03:29:14 -0400 Subject: [PATCH] feat: implement initial download method --- src/download.ts | 42 +++++++++++++++++++++++++++++++++++++++++- 1 file changed, 41 insertions(+), 1 deletion(-) diff --git a/src/download.ts b/src/download.ts index 6dd67ca..d1b909b 100644 --- a/src/download.ts +++ b/src/download.ts @@ -1 +1,41 @@ -export function downloadObject(cid: string) {} +import { getActivePortals } from "#portal.js"; +import { ErrTuple } from "#types.js"; +import { decodeCid, getVerifiableStream } from "@lumeweb/libportal"; + +const NO_PORTALS_ERROR = [null, "no active portals"] as ErrTuple; + +export async function downloadObject(cid: string): Promise { + const activePortals = getActivePortals(); + + if (!activePortals.size) { + return NO_PORTALS_ERROR; + } + + for (const portal of activePortals) { + if (!(await portal.isLoggedIn())) { + try { + await portal.register(); + } catch { + continue; + } + + await portal.login(); + } + + let stream, proof; + + try { + stream = await portal.downloadFile(cid); + proof = await portal.downloadProof(cid); + } catch { + continue; + } + + return [ + await getVerifiableStream(decodeCid(cid).hash, proof, stream), + null, + ]; + } + + return NO_PORTALS_ERROR; +}