From b1680c39b354df2542a051edd1a79550a717a57b Mon Sep 17 00:00:00 2001 From: tycrek Date: Sat, 16 Oct 2021 22:32:36 -0600 Subject: [PATCH] Added `skynet.ts` with functions for uploading and downloading --- src/skynet.ts | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 src/skynet.ts diff --git a/src/skynet.ts b/src/skynet.ts new file mode 100644 index 0000000..e5e8bd5 --- /dev/null +++ b/src/skynet.ts @@ -0,0 +1,37 @@ +import { FileData } from "./definitions"; +import fs, { ReadStream } from 'fs-extra'; +import { path } from './utils'; +const { SkynetClient } = require('@skynetlabs/skynet-nodejs'); + +function getFullPath(fileData: FileData) { + return path('share', '.skynet', `${fileData.randomId}${fileData.ext}`.replace(/sia\:\/\//gi, '')); +} + +// Create the SkyNet client +export const Skynet = new SkynetClient(); + +export function SkynetUpload(path: string): Promise { + return new Promise(async (resolve, reject) => { + try { + const skylink = await Skynet.uploadFile(path); + resolve(skylink); + } catch (error) { + reject(error); + } + }); +} + +export function SkynetDownload(fileData: FileData): Promise { + return new Promise((resolve: Function, reject) => + fs.ensureDir(path('share', '.skynet')) + .then(async () => { + await Skynet.downloadFile(getFullPath(fileData), fileData.randomId); + return fs.createReadStream(getFullPath(fileData)) + }) + .then((stream) => resolve(stream)) + .catch(reject)); +} + +export function SkynetDelete(fileData: FileData) { + return fs.remove(getFullPath(fileData)); +}