Skip to content

Commit

Permalink
Merge pull request #146 from StarfilesFileSharing/alpha
Browse files Browse the repository at this point in the history
Alpha
  • Loading branch information
QuixThe2nd authored Nov 4, 2024
2 parents 73b00b5 + f24c37d commit 8fec946
Show file tree
Hide file tree
Showing 5 changed files with 37 additions and 58 deletions.
2 changes: 1 addition & 1 deletion deno.jsonc
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@starfiles/hydrafiles",
"version": "0.7.33",
"version": "0.7.34",
"description": "The (P2P) web privacy layer.",
"main": "src/hydrafiles.ts",
"exports": {
Expand Down
10 changes: 10 additions & 0 deletions src/file.ts
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,11 @@ export class FileDB {
this._client = client;
}

/**
* Initializes an instance of FileDB.
* @returns {FileDB} A new instance of FileDB.
* @default
*/
static async init(client: Hydrafiles): Promise<FileDB> {
await client.fs.mkdir("files");

Expand Down Expand Up @@ -390,6 +395,11 @@ class File implements FileAttributes {
}
}

/**
* Initializes an instance of File.
* @returns {File} A new instance of File.
* @default
*/
static async init(values: Partial<FileAttributes>, client: Hydrafiles, vote = false): Promise<File | false> {
if (!values.hash && values.id) {
const files = await client.fileDB.select({ key: "id", value: values.id });
Expand Down
15 changes: 15 additions & 0 deletions src/rpc/peers/http.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,11 @@ export class PeerDB {
this._client = client;
}

/**
* Initializes an instance of PeerDB.
* @returns {PeerDB} A new instance of PeerDB.
* @default
*/
static async init(client: Hydrafiles): Promise<PeerDB> {
const peerDB = new PeerDB(client);

Expand Down Expand Up @@ -329,6 +334,11 @@ export class HTTPPeer implements PeerAttributes {
this.updatedAt = values.updatedAt;
}

/**
* Initializes an instance of HTTPPeer.
* @returns {HTTPPeer} A new instance of HTTPPeer.
* @default
*/
static async init(values: Partial<PeerAttributes>, db: PeerDB): Promise<HTTPPeer> {
if (values.host === undefined) throw new Error("Hash is required");
const peerAttributes: PeerAttributes = {
Expand Down Expand Up @@ -366,6 +376,11 @@ export default class HTTPClient {
this._db = db;
}

/**
* Initializes an instance of HTTPClient.
* @returns {HTTPClient} A new instance of HTTPClient.
* @default
*/
public static async init(client: Hydrafiles): Promise<HTTPClient> {
const db = await PeerDB.init(client);
const peers = new HTTPClient(client, db);
Expand Down
5 changes: 5 additions & 0 deletions src/rpc/peers/rtc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,11 @@ class RTCClient {
this.seenMessages = new Set();
}

/**
* Initializes an instance of RTCClient.
* @returns {RTCClient} A new instance of RTCClient.
* @default
*/
static async init(client: Hydrafiles): Promise<RTCClient> {
const webRTC = new RTCClient(client);
const peers = await client.rpcClient.http.getPeers(true);
Expand Down
63 changes: 6 additions & 57 deletions src/utils.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { crypto } from "jsr:@std/crypto";
// import { crypto } from "jsr:@std/crypto";
import { encodeHex } from "jsr:@std/encoding/hex";
import type Hydrafiles from "./hydrafiles.ts";
import { join } from "https://deno.land/[email protected]/path/mod.ts";
Expand All @@ -20,6 +20,9 @@ class Utils {
static isIp = (host: string): boolean => /^https?:\/\/(?:\d+\.){3}\d+(?::\d+)?$/.test(host);
static isPrivateIP = (ip: string): boolean => /^https?:\/\/(?:10\.|(?:172\.(?:1[6-9]|2\d|3[0-1]))\.|192\.168\.|169\.254\.|127\.|224\.0\.0\.|255\.255\.255\.255)/.test(ip);
static interfere = (signalStrength: number): number => signalStrength >= 95 ? this.getRandomNumber(90, 100) : Math.ceil(signalStrength * (1 - (this.getRandomNumber(0, 10) / 100)));
remainingStorage = async (): Promise<number> => this._client.config.maxCache - await this.calculateUsedStorage();
static createNonNegativeNumber = (n: number): NonNegativeNumber => (Number.isInteger(n) && n >= 0 ? n : 0) as NonNegativeNumber;

hasSufficientMemory = async (fileSize: number): Promise<boolean> => {
if (typeof window !== "undefined") return true;
const os = await import("https://deno.land/[email protected]/node/os.ts");
Expand All @@ -36,23 +39,6 @@ class Utils {
),
]);

static promiseWrapper = <T>(promise: Promise<T>): { promise: Promise<T>; isFulfilled: boolean } => {
let isFulfilled = false;
const wrappedPromise = promise
.then((value: T) => {
isFulfilled = true;
return value;
})
.catch((error: unknown) => {
isFulfilled = true;
throw error;
});
return {
promise: wrappedPromise,
isFulfilled,
};
};

static estimateHops = (signalStrength: number): { hop: number | null; certainty: number } => {
const hopData = [
{ hop: 1, min: 90, avg: 95 },
Expand Down Expand Up @@ -100,8 +86,6 @@ class Utils {
};
};

remainingStorage = async (): Promise<number> => this._client.config.maxCache - await this.calculateUsedStorage();

calculateUsedStorage = async (): Promise<number> => {
if (typeof window !== "undefined") return 0;
const filesPath = "files/";
Expand Down Expand Up @@ -220,6 +204,7 @@ class Utils {
["verify"],
);
}

static async exportPublicKey(key: CryptoKey): Promise<{ x: string; y: string }> {
const jwk = await crypto.subtle.exportKey("jwk", key);
return { x: jwk.x as string, y: jwk.y as string }; // Return both x and y
Expand Down Expand Up @@ -284,47 +269,11 @@ class Utils {
data,
);
}
static extractBufferSection(buffer: Uint8Array, start: number, end: number): Uint8Array {
if (start < 0 || end >= buffer.length || start > end) throw new RangeError("Invalid start or end range.");
return buffer.subarray(start, end + 1);
}
static async parallelAsync(promises: (() => Promise<void>)[], processes = 4): Promise<void> {
let completed = 0;
const runningPromises: Promise<void>[] = [];
for (let i = 0; i < promises.length; i++) {
const promise = promises[i]();
if (i - completed > processes) {
await Promise.race(runningPromises);
completed++;
}
runningPromises.push(promise);
}
await Promise.all(runningPromises);
}
static createNonNegativeNumber(n: number): NonNegativeNumber {
return (Number.isInteger(n) && n >= 0 ? n : 0) as NonNegativeNumber;
}

static sha256(hash: string): Sha256 {
if (!/^[a-f0-9]{64}$/.test(hash)) throw new Error("Invalid sha256 provided");
return hash as Sha256;
}
static async streamToUint8Array(readableStream: ReadableStream): Promise<Uint8Array> {
const reader = readableStream.getReader();
const chunks = [];
while (true) {
const { done, value } = await reader.read();
if (done) break;
chunks.push(value);
}
const totalLength = chunks.reduce((acc, chunk) => acc + chunk.length, 0);
const result = new Uint8Array(totalLength);
let position = 0;
for (const chunk of chunks) {
result.set(chunk, position);
position += chunk.length;
}
return result;
}
}

export default Utils;

0 comments on commit 8fec946

Please sign in to comment.