@holochain-open-dev/file-storage 0.300.0-dev.0 → 0.300.0-rc

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,8 +1,8 @@
1
- import type { AppAgentClient } from "@holochain/client";
1
+ import type { AppClient } from "@holochain/client";
2
2
  import { EntryHash } from "@holochain/client";
3
3
  import { FileMetadata } from "./types";
4
4
  export declare class FileStorageClient {
5
- client: AppAgentClient;
5
+ client: AppClient;
6
6
  roleName: string;
7
7
  zomeName: string;
8
8
  /**
@@ -10,7 +10,7 @@ export declare class FileStorageClient {
10
10
  * @param roleName
11
11
  * @param zomeName the zome name of the file_storage zome in the given cell
12
12
  */
13
- constructor(client: AppAgentClient, roleName: string, zomeName?: string);
13
+ constructor(client: AppClient, roleName: string, zomeName?: string);
14
14
  /**
15
15
  * Upload a file to the file_storage zome, splitting it into chunks
16
16
  *
@@ -1 +1 @@
1
- {"version":3,"file":"file-storage-client.js","sourceRoot":"","sources":["../src/file-storage-client.ts"],"names":[],"mappings":"AAOA,MAAM,OAAO,iBAAiB;IAC5B;;;;OAIG;IACH,YACS,MAAsB,EACtB,QAAgB,EAChB,WAAmB,cAAc;QAFjC,WAAM,GAAN,MAAM,CAAgB;QACtB,aAAQ,GAAR,QAAQ,CAAQ;QAChB,aAAQ,GAAR,QAAQ,CAAyB;IACvC,CAAC;IAEJ;;;;;OAKG;IACH,KAAK,CAAC,UAAU,CACd,IAAU,EACV,aAEiE,SAAS,EAC1E,YAAoB,GAAG,GAAG,IAAI;QAE9B,MAAM,KAAK,GAAG,IAAI,CAAC,UAAU,CAAC,IAAI,EAAE,SAAS,CAAC,CAAC;QAC/C,MAAM,cAAc,GAAG,KAAK,CAAC,MAAM,CAAC;QACpC,MAAM,aAAa,GAAG,KAAK,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC;QAEpC,IAAI,cAAc,GAAG,CAAC,CAAC;QAEvB,MAAM,eAAe,GAAG,GAAG,EAAE;Y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ACxB,SAAS,EAAE,IAAI,CAAC,QAAQ;YACxB,OAAO;YACP,OAAO;SACR,CAAC;QACF,OAAO,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC;IACnC,CAAC;CACF","sourcesContent":["import type {\n AppAgentCallZomeRequest,\n AppAgentClient,\n} from \"@holochain/client\";\nimport { EntryHash } from \"@holochain/client\";\nimport { FileMetadata } from \"./types\";\n\nexport class FileStorageClient {\n /**\n * @param client connection to the holochain backend\n * @param roleName\n * @param zomeName the zome name of the file_storage zome in the given cell\n */\n constructor(\n public client: AppAgentClient,\n public roleName: string,\n public zomeName: string = \"file_storage\"\n ) {}\n\n /**\n * Upload a file to the file_storage zome, splitting it into chunks\n *\n * @param file file to split and upload\n * @param chunkSize chunk size to split the file, default 256 KB\n */\n async uploadFile(\n file: File,\n onProgress:\n | undefined\n | ((percentatgeProgress: number, bytesSent: number) => void) = undefined,\n chunkSize: number = 256 * 1024\n ): Promise<EntryHash> {\n const blobs = this._splitFile(file, chunkSize);\n const numberOfChunks = blobs.length;\n const bytesPerChunk = blobs[0].size;\n\n let uploadedChunks = 0;\n\n const onChunkUploaded = () => {\n if (onProgress) {\n uploadedChunks++;\n onProgress(\n ((uploadedChunks + 1) * 1.0) / numberOfChunks,\n bytesPerChunk * (uploadedChunks + 1)\n );\n }\n };\n\n const chunksHashes: Array<EntryHash> = await Promise.all(\n blobs.map(async (blob) => {\n const chunkHash = await this._createChunk(blob);\n\n onChunkUploaded();\n return chunkHash;\n })\n );\n\n const fileToCreate = {\n name: file.name,\n size: file.size,\n file_type: file.type,\n last_modified: file.lastModified * 1000,\n chunks_hashes: chunksHashes,\n };\n const hash = await this._callZome(\"create_file_metadata\", fileToCreate);\n\n return hash;\n }\n\n /**\n * Downloads the whole file with the given hash\n * @param fileHash\n */\n async downloadFile(fileHash: EntryHash): Promise<File> {\n const metadata = await this.getFileMetadata(fileHash);\n\n const fetchChunksPromises = metadata.chunks_hashes.map((hash) =>\n this.fetchChunk(hash)\n );\n\n const chunks = await Promise.all(fetchChunksPromises);\n\n const file = new File(chunks, metadata.name, {\n lastModified: Math.floor(metadata.last_modifed / 1000),\n type: metadata.file_type,\n });\n\n return file;\n }\n\n /**\n * Gets only the metadata of the file with the given hash\n * This is specially useful if you want to fetch the chunks one by one\n * @param fileHash the hash of the file\n */\n async getFileMetadata(fileHash: EntryHash): Promise<FileMetadata> {\n return await this._callZome(\"get_file_metadata\", fileHash);\n }\n\n /**\n * Fetch the chunk identified with the given hash\n * This is useful if used with the chunk hashes received with `getFileMetadata`\n * @param fileChunkHash\n */\n async fetchChunk(fileChunkHash: EntryHash): Promise<Blob> {\n const bytes = await this._callZome(\"get_file_chunk\", fileChunkHash);\n\n return new Blob([new Uint8Array(bytes)]);\n }\n\n /** Private helpers */\n\n private _splitFile(file: File, chunkSize: number): Blob[] {\n let offset = 0;\n const chunks: Blob[] = [];\n\n while (file.size > offset) {\n const chunk = file.slice(offset, offset + chunkSize);\n offset += chunkSize;\n chunks.push(chunk);\n }\n\n return chunks;\n }\n\n private async _createChunk(chunk: Blob): Promise<EntryHash> {\n const bytes = await chunk.arrayBuffer();\n\n return this._callZome(\"create_file_chunk\", new Uint8Array(bytes));\n }\n\n private _callZome(fn_name: string, payload: any) {\n const req: AppAgentCallZomeRequest = {\n role_name: this.roleName,\n zome_name: this.zomeName,\n fn_name,\n payload,\n };\n return this.client.callZome(req);\n }\n}\n"]}
1
+ {"version":3,"file":"file-storage-client.js","sourceRoot":"","sources":["../src/file-storage-client.ts"],"names":[],"mappings":"AAIA,MAAM,OAAO,iBAAiB;IAC5B;;;;OAIG;IACH,YACS,MAAiB,EACjB,QAAgB,EAChB,WAAmB,cAAc;QAFjC,WAAM,GAAN,MAAM,CAAW;QACjB,aAAQ,GAAR,QAAQ,CAAQ;QAChB,aAAQ,GAAR,QAAQ,CAAyB;IACvC,CAAC;IAEJ;;;;;OAKG;IACH,KAAK,CAAC,UAAU,CACd,IAAU,EACV,aAEiE,SAA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AC;IAEO,KAAK,CAAC,YAAY,CAAC,KAAW;QACpC,MAAM,KAAK,GAAG,MAAM,KAAK,CAAC,WAAW,EAAE,CAAC;QAExC,OAAO,IAAI,CAAC,SAAS,CAAC,mBAAmB,EAAE,IAAI,UAAU,CAAC,KAAK,CAAC,CAAC,CAAC;IACpE,CAAC;IAEO,SAAS,CAAC,OAAe,EAAE,OAAY;QAC7C,MAAM,GAAG,GAAuB;YAC9B,SAAS,EAAE,IAAI,CAAC,QAAQ;YACxB,SAAS,EAAE,IAAI,CAAC,QAAQ;YACxB,OAAO;YACP,OAAO;SACR,CAAC;QACF,OAAO,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC;IACnC,CAAC;CACF","sourcesContent":["import type { AppCallZomeRequest, AppClient } from \"@holochain/client\";\nimport { EntryHash } from \"@holochain/client\";\nimport { FileMetadata } from \"./types\";\n\nexport class FileStorageClient {\n /**\n * @param client connection to the holochain backend\n * @param roleName\n * @param zomeName the zome name of the file_storage zome in the given cell\n */\n constructor(\n public client: AppClient,\n public roleName: string,\n public zomeName: string = \"file_storage\"\n ) {}\n\n /**\n * Upload a file to the file_storage zome, splitting it into chunks\n *\n * @param file file to split and upload\n * @param chunkSize chunk size to split the file, default 256 KB\n */\n async uploadFile(\n file: File,\n onProgress:\n | undefined\n | ((percentatgeProgress: number, bytesSent: number) => void) = undefined,\n chunkSize: number = 256 * 1024\n ): Promise<EntryHash> {\n const blobs = this._splitFile(file, chunkSize);\n const numberOfChunks = blobs.length;\n const bytesPerChunk = blobs[0].size;\n\n let uploadedChunks = 0;\n\n const onChunkUploaded = () => {\n if (onProgress) {\n uploadedChunks++;\n onProgress(\n ((uploadedChunks + 1) * 1.0) / numberOfChunks,\n bytesPerChunk * (uploadedChunks + 1)\n );\n }\n };\n\n const chunksHashes: Array<EntryHash> = await Promise.all(\n blobs.map(async (blob) => {\n const chunkHash = await this._createChunk(blob);\n\n onChunkUploaded();\n return chunkHash;\n })\n );\n\n const fileToCreate = {\n name: file.name,\n size: file.size,\n file_type: file.type,\n last_modified: file.lastModified * 1000,\n chunks_hashes: chunksHashes,\n };\n const hash = await this._callZome(\"create_file_metadata\", fileToCreate);\n\n return hash;\n }\n\n /**\n * Downloads the whole file with the given hash\n * @param fileHash\n */\n async downloadFile(fileHash: EntryHash): Promise<File> {\n const metadata = await this.getFileMetadata(fileHash);\n\n const fetchChunksPromises = metadata.chunks_hashes.map((hash) =>\n this.fetchChunk(hash)\n );\n\n const chunks = await Promise.all(fetchChunksPromises);\n\n const file = new File(chunks, metadata.name, {\n lastModified: Math.floor(metadata.last_modifed / 1000),\n type: metadata.file_type,\n });\n\n return file;\n }\n\n /**\n * Gets only the metadata of the file with the given hash\n * This is specially useful if you want to fetch the chunks one by one\n * @param fileHash the hash of the file\n */\n async getFileMetadata(fileHash: EntryHash): Promise<FileMetadata> {\n return await this._callZome(\"get_file_metadata\", fileHash);\n }\n\n /**\n * Fetch the chunk identified with the given hash\n * This is useful if used with the chunk hashes received with `getFileMetadata`\n * @param fileChunkHash\n */\n async fetchChunk(fileChunkHash: EntryHash): Promise<Blob> {\n const bytes = await this._callZome(\"get_file_chunk\", fileChunkHash);\n\n return new Blob([new Uint8Array(bytes)]);\n }\n\n /** Private helpers */\n\n private _splitFile(file: File, chunkSize: number): Blob[] {\n let offset = 0;\n const chunks: Blob[] = [];\n\n while (file.size > offset) {\n const chunk = file.slice(offset, offset + chunkSize);\n offset += chunkSize;\n chunks.push(chunk);\n }\n\n return chunks;\n }\n\n private async _createChunk(chunk: Blob): Promise<EntryHash> {\n const bytes = await chunk.arrayBuffer();\n\n return this._callZome(\"create_file_chunk\", new Uint8Array(bytes));\n }\n\n private _callZome(fn_name: string, payload: any) {\n const req: AppCallZomeRequest = {\n role_name: this.roleName,\n zome_name: this.zomeName,\n fn_name,\n payload,\n };\n return this.client.callZome(req);\n }\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@holochain-open-dev/file-storage",
3
- "version": "0.300.0-dev.0",
3
+ "version": "0.300.0-rc",
4
4
  "description": "File storage utilities to store and retrieve files in a holochain DHT",
5
5
  "author": "guillem.cordoba@gmail.com",
6
6
  "license": "MIT",
@@ -10,18 +10,19 @@
10
10
  ".": "./dist/index.js",
11
11
  "./dist/*": "./dist/*"
12
12
  },
13
- "files": ["dist"],
13
+ "files": ["dist", "src"],
14
14
  "scripts": {
15
15
  "start": "vite --clearScreen false --port $UI_PORT",
16
16
  "build": "npm run lint && tsc",
17
17
  "lint": "eslint --ext .ts,.html src --ignore-path .gitignore",
18
18
  "analyze": "cem analyze --litelement --exclude dist",
19
- "format": "eslint --ext .ts,.html src --fix --ignore-path .gitignore"
19
+ "format": "eslint --ext .ts,.html src --fix --ignore-path .gitignore",
20
+ "prepare": "tsc"
20
21
  },
21
22
  "dependencies": {
22
- "@holochain-open-dev/elements": "^0.300.0-dev.0",
23
- "@holochain-open-dev/utils": "^0.300.0-dev.0",
24
- "@holochain/client": "^0.17.0-dev.7",
23
+ "@holochain-open-dev/elements": "^0.300.0-rc",
24
+ "@holochain-open-dev/utils": "^0.300.0-rc",
25
+ "@holochain/client": "^0.17.0-rc",
25
26
  "@lit-labs/task": "^2.0.0",
26
27
  "@lit/context": "^1.0.0",
27
28
  "@lit/localize": "^0.12.0",
package/src/context.ts ADDED
@@ -0,0 +1,6 @@
1
+ import { createContext } from "@lit/context";
2
+ import { FileStorageClient } from "./file-storage-client";
3
+
4
+ export const fileStorageClientContext = createContext<FileStorageClient>(
5
+ "hc_zome_file_storage/file-storage-client"
6
+ );
@@ -0,0 +1,23 @@
1
+ import { css, html, LitElement } from "lit";
2
+ import { provide } from "@lit/context";
3
+ import { property, customElement } from "lit/decorators.js";
4
+
5
+ import { fileStorageClientContext } from "../context.js";
6
+ import { FileStorageClient } from "../file-storage-client.js";
7
+
8
+ @customElement("file-storage-context")
9
+ export class FileStorageContext extends LitElement {
10
+ @provide({ context: fileStorageClientContext })
11
+ @property({ type: Object })
12
+ client!: FileStorageClient;
13
+
14
+ render() {
15
+ return html`<slot></slot>`;
16
+ }
17
+
18
+ static styles = css`
19
+ :host {
20
+ display: contents;
21
+ }
22
+ `;
23
+ }
@@ -0,0 +1,93 @@
1
+ import { css, html, LitElement } from "lit";
2
+ import { property, customElement } from "lit/decorators.js";
3
+ import { hashProperty, sharedStyles } from "@holochain-open-dev/elements";
4
+ import { consume } from "@lit/context";
5
+
6
+ import "@shoelace-style/shoelace/dist/components/skeleton/skeleton.js";
7
+ import "@holochain-open-dev/elements/dist/elements/display-error.js";
8
+
9
+ import { EntryHash } from "@holochain/client";
10
+ import { Task } from "@lit-labs/task";
11
+ import { fromUint8Array } from "js-base64";
12
+ import { localized, msg } from "@lit/localize";
13
+
14
+ import { FileStorageClient } from "../file-storage-client";
15
+ import { fileStorageClientContext } from "../context";
16
+ import { getImage, storeImage } from "../local-storage";
17
+
18
+ /**
19
+ * @fires file-uploaded - Fired after having uploaded the file
20
+ * @csspart dropzone - Style the dropzone itself
21
+ */
22
+ @localized()
23
+ @customElement("show-image")
24
+ export class ShowImage extends LitElement {
25
+ /** Public attributes */
26
+
27
+ /**
28
+ * REQUIRED. The hash of the image to be rendered
29
+ */
30
+ @property(hashProperty("image-hash")) imageHash!: EntryHash;
31
+
32
+ /**
33
+ * @internal
34
+ */
35
+ @consume({ context: fileStorageClientContext })
36
+ client!: FileStorageClient;
37
+
38
+ /**
39
+ * @internal
40
+ */
41
+ _renderImage = new Task(
42
+ this,
43
+ async ([fileHash]) => {
44
+ const image = await getImage(fileHash);
45
+ if (image) {
46
+ return image;
47
+ }
48
+
49
+ const file = await this.client.downloadFile(fileHash);
50
+ const data = await file.arrayBuffer();
51
+
52
+ const imageB64 = `data:${file.type};base64,${fromUint8Array(
53
+ new Uint8Array(data)
54
+ )}`;
55
+
56
+ storeImage(fileHash, imageB64);
57
+
58
+ return imageB64;
59
+ },
60
+ () => [this.imageHash]
61
+ );
62
+
63
+ renderImage(data: string) {
64
+ return html`<div style="flex:1"><img src="${data}" style="object-fit: cover; overflow: hidden; width: 100%; height: 100%"></img></div>`;
65
+ }
66
+
67
+ render() {
68
+ return this._renderImage.render({
69
+ complete: (d) => this.renderImage(d),
70
+ pending: () =>
71
+ html`<sl-skeleton
72
+ style="flex: 1; --border-radius: 0"
73
+ effect="pulse"
74
+ ></sl-skeleton> `,
75
+ error: (e: any) =>
76
+ html`<display-error
77
+ .headline=${msg("Error fetching the image")}
78
+ .error=${e}
79
+ ></display-error>`,
80
+ });
81
+ }
82
+
83
+ static get styles() {
84
+ return [
85
+ sharedStyles,
86
+ css`
87
+ :host {
88
+ display: flex;
89
+ }
90
+ `,
91
+ ];
92
+ }
93
+ }
@@ -0,0 +1,154 @@
1
+ import { css, html } from "lit";
2
+ import { customElement, property, query } from "lit/decorators.js";
3
+
4
+ import { DropzoneElement, DropzoneOptions } from "@scoped-elements/dropzone";
5
+ import { consume } from "@lit/context";
6
+ import {
7
+ FormField,
8
+ FormFieldController,
9
+ sharedStyles,
10
+ } from "@holochain-open-dev/elements";
11
+ import { localized } from "@lit/localize";
12
+
13
+ import { FileStorageClient } from "../file-storage-client.js";
14
+ import { fileStorageClientContext } from "../context.js";
15
+ import { HolochainDropzone } from "../holochain-dropzone.js";
16
+ import { EntryHash } from "@holochain/client";
17
+
18
+ /**
19
+ * @fires file-uploaded - Fired after having uploaded the file
20
+ * @csspart dropzone - Style the dropzone itself
21
+ */
22
+ @localized()
23
+ @customElement("upload-files")
24
+ export class UploadFiles extends DropzoneElement implements FormField {
25
+ /**
26
+ * The name of the field if this element is used inside a form
27
+ * Required only if the element is used inside a form
28
+ */
29
+ @property()
30
+ name!: string;
31
+
32
+ /**
33
+ * Whether this field is required if this element is used inside a form
34
+ */
35
+ @property()
36
+ required = false;
37
+
38
+ /**
39
+ * Whether this field is disabled if this element is used inside a form
40
+ */
41
+ @property()
42
+ disabled = false;
43
+
44
+ /**
45
+ * The default value that this element will take if it is resetted in a form
46
+ */
47
+ @property()
48
+ defaultValue!: EntryHash | Array<EntryHash>;
49
+
50
+ /** Public attributes */
51
+
52
+ /**
53
+ * Whether this element should allow only file to be uploaded
54
+ */
55
+ @property({ type: Boolean, attribute: "one-file" }) oneFile = false;
56
+
57
+ /**
58
+ * The type of files accepted by this element
59
+ * Learn how to use this here: https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/accept
60
+ */
61
+ @property({ type: String, attribute: "accepted-files" }) acceptedFiles:
62
+ | string
63
+ | undefined = undefined;
64
+
65
+ /**
66
+ * @internal
67
+ */
68
+ @consume({ context: fileStorageClientContext })
69
+ _client!: FileStorageClient;
70
+
71
+ /**
72
+ * @internal
73
+ */
74
+ _controller = new FormFieldController(this);
75
+
76
+ async firstUpdated() {
77
+ super.firstUpdated();
78
+
79
+ this.reset();
80
+ }
81
+
82
+ async reset() {
83
+ this.clear();
84
+ if (this.defaultValue) {
85
+ if (Array.isArray(this.defaultValue)) {
86
+ for (const fileHash of this.defaultValue) {
87
+ const image = await this._client.downloadFile(fileHash);
88
+ this.dropzone.addFile(image as any);
89
+ }
90
+ } else {
91
+ const image = await this._client.downloadFile(this.defaultValue);
92
+ this.dropzone.addFile(image as any);
93
+ }
94
+ }
95
+ }
96
+
97
+ /**
98
+ * @internal
99
+ */
100
+ get value() {
101
+ if (this.oneFile)
102
+ return this.dropzone.files[0]
103
+ ? (this.dropzone.files[0] as any).hash
104
+ : undefined;
105
+ return this.dropzone.files.map((file) => (file as any).hash);
106
+ }
107
+
108
+ /**
109
+ * @internal
110
+ */
111
+ @query("#hidden-input")
112
+ private _input!: HTMLInputElement;
113
+
114
+ reportValidity() {
115
+ const invalid = this.required !== false && this.value === undefined;
116
+ if (invalid) {
117
+ this._input.setCustomValidity(`Uploading a file is required`);
118
+ this._input.reportValidity();
119
+ }
120
+
121
+ return !invalid;
122
+ }
123
+
124
+ buildDropzone(dropzoneElement: HTMLElement, options: DropzoneOptions) {
125
+ return new HolochainDropzone(
126
+ dropzoneElement,
127
+ this._client,
128
+ options
129
+ ) as any as Dropzone;
130
+ }
131
+
132
+ render() {
133
+ return html`
134
+ <div style="position: relative; flex: 1; display: flex">
135
+ <input
136
+ id="hidden-input"
137
+ style="width:0; height: 0; position: absolute; z-index: -1; left: 50%; top: 20%"
138
+ />
139
+ ${super.render()}
140
+ </div>
141
+ `;
142
+ }
143
+ static get styles() {
144
+ return [
145
+ DropzoneElement.styles,
146
+ sharedStyles,
147
+ css`
148
+ :host {
149
+ display: flex;
150
+ }
151
+ `,
152
+ ];
153
+ }
154
+ }
@@ -0,0 +1,138 @@
1
+ import type { AppCallZomeRequest, AppClient } from "@holochain/client";
2
+ import { EntryHash } from "@holochain/client";
3
+ import { FileMetadata } from "./types";
4
+
5
+ export class FileStorageClient {
6
+ /**
7
+ * @param client connection to the holochain backend
8
+ * @param roleName
9
+ * @param zomeName the zome name of the file_storage zome in the given cell
10
+ */
11
+ constructor(
12
+ public client: AppClient,
13
+ public roleName: string,
14
+ public zomeName: string = "file_storage"
15
+ ) {}
16
+
17
+ /**
18
+ * Upload a file to the file_storage zome, splitting it into chunks
19
+ *
20
+ * @param file file to split and upload
21
+ * @param chunkSize chunk size to split the file, default 256 KB
22
+ */
23
+ async uploadFile(
24
+ file: File,
25
+ onProgress:
26
+ | undefined
27
+ | ((percentatgeProgress: number, bytesSent: number) => void) = undefined,
28
+ chunkSize: number = 256 * 1024
29
+ ): Promise<EntryHash> {
30
+ const blobs = this._splitFile(file, chunkSize);
31
+ const numberOfChunks = blobs.length;
32
+ const bytesPerChunk = blobs[0].size;
33
+
34
+ let uploadedChunks = 0;
35
+
36
+ const onChunkUploaded = () => {
37
+ if (onProgress) {
38
+ uploadedChunks++;
39
+ onProgress(
40
+ ((uploadedChunks + 1) * 1.0) / numberOfChunks,
41
+ bytesPerChunk * (uploadedChunks + 1)
42
+ );
43
+ }
44
+ };
45
+
46
+ const chunksHashes: Array<EntryHash> = await Promise.all(
47
+ blobs.map(async (blob) => {
48
+ const chunkHash = await this._createChunk(blob);
49
+
50
+ onChunkUploaded();
51
+ return chunkHash;
52
+ })
53
+ );
54
+
55
+ const fileToCreate = {
56
+ name: file.name,
57
+ size: file.size,
58
+ file_type: file.type,
59
+ last_modified: file.lastModified * 1000,
60
+ chunks_hashes: chunksHashes,
61
+ };
62
+ const hash = await this._callZome("create_file_metadata", fileToCreate);
63
+
64
+ return hash;
65
+ }
66
+
67
+ /**
68
+ * Downloads the whole file with the given hash
69
+ * @param fileHash
70
+ */
71
+ async downloadFile(fileHash: EntryHash): Promise<File> {
72
+ const metadata = await this.getFileMetadata(fileHash);
73
+
74
+ const fetchChunksPromises = metadata.chunks_hashes.map((hash) =>
75
+ this.fetchChunk(hash)
76
+ );
77
+
78
+ const chunks = await Promise.all(fetchChunksPromises);
79
+
80
+ const file = new File(chunks, metadata.name, {
81
+ lastModified: Math.floor(metadata.last_modifed / 1000),
82
+ type: metadata.file_type,
83
+ });
84
+
85
+ return file;
86
+ }
87
+
88
+ /**
89
+ * Gets only the metadata of the file with the given hash
90
+ * This is specially useful if you want to fetch the chunks one by one
91
+ * @param fileHash the hash of the file
92
+ */
93
+ async getFileMetadata(fileHash: EntryHash): Promise<FileMetadata> {
94
+ return await this._callZome("get_file_metadata", fileHash);
95
+ }
96
+
97
+ /**
98
+ * Fetch the chunk identified with the given hash
99
+ * This is useful if used with the chunk hashes received with `getFileMetadata`
100
+ * @param fileChunkHash
101
+ */
102
+ async fetchChunk(fileChunkHash: EntryHash): Promise<Blob> {
103
+ const bytes = await this._callZome("get_file_chunk", fileChunkHash);
104
+
105
+ return new Blob([new Uint8Array(bytes)]);
106
+ }
107
+
108
+ /** Private helpers */
109
+
110
+ private _splitFile(file: File, chunkSize: number): Blob[] {
111
+ let offset = 0;
112
+ const chunks: Blob[] = [];
113
+
114
+ while (file.size > offset) {
115
+ const chunk = file.slice(offset, offset + chunkSize);
116
+ offset += chunkSize;
117
+ chunks.push(chunk);
118
+ }
119
+
120
+ return chunks;
121
+ }
122
+
123
+ private async _createChunk(chunk: Blob): Promise<EntryHash> {
124
+ const bytes = await chunk.arrayBuffer();
125
+
126
+ return this._callZome("create_file_chunk", new Uint8Array(bytes));
127
+ }
128
+
129
+ private _callZome(fn_name: string, payload: any) {
130
+ const req: AppCallZomeRequest = {
131
+ role_name: this.roleName,
132
+ zome_name: this.zomeName,
133
+ fn_name,
134
+ payload,
135
+ };
136
+ return this.client.callZome(req);
137
+ }
138
+ }
@@ -0,0 +1,41 @@
1
+ import { Dropzone, DropzoneOptions } from "@scoped-elements/dropzone";
2
+ import { FileStorageClient } from "./file-storage-client";
3
+
4
+ export class HolochainDropzone extends Dropzone {
5
+ fileStorageClient: FileStorageClient;
6
+ constructor(
7
+ el: HTMLElement,
8
+ fileStorageClient: FileStorageClient,
9
+ options: DropzoneOptions
10
+ ) {
11
+ options.url = "https://holochain.org/"; // just to bypass the check.
12
+ super(el, options);
13
+ this.fileStorageClient = fileStorageClient;
14
+ }
15
+
16
+ uploadFiles(files: Dropzone.DropzoneFile[]) {
17
+ this._uploadFilesToHolochain(files);
18
+ }
19
+
20
+ async _uploadFilesToHolochain(
21
+ dropzoneFiles: Dropzone.DropzoneFile[]
22
+ ): Promise<void> {
23
+ for (const file of dropzoneFiles) {
24
+ try {
25
+ this.emit("sending", file, undefined, undefined);
26
+ const hash = await this.fileStorageClient.uploadFile(
27
+ file,
28
+ (percentatge, bytesSent) => {
29
+ this.emit("uploadprogress", file, percentatge * 100, bytesSent);
30
+ }
31
+ );
32
+ this.emit("success", file, undefined);
33
+ (file as any).hash = hash;
34
+ this.emit("complete", file);
35
+ } catch (e) {
36
+ console.error(e);
37
+ this.emit("error", file, e as any);
38
+ }
39
+ }
40
+ }
41
+ }
package/src/index.ts ADDED
@@ -0,0 +1,4 @@
1
+ export * from "./file-storage-client.js";
2
+ export * from "./holochain-dropzone.js";
3
+ export * from "./types.js";
4
+ export * from "./context.js";
@@ -0,0 +1,45 @@
1
+ import { encodeHashToBase64, EntryHash } from "@holochain/client";
2
+ import { createStore, del, entries, get, set } from "idb-keyval";
3
+
4
+ const store = createStore("HC_ZOME_FILE_STORAGE", "IMAGES");
5
+
6
+ interface CachedImage {
7
+ image: string;
8
+ lastRead: number;
9
+ }
10
+
11
+ export async function storeImage(imageHash: EntryHash, image: string) {
12
+ await set(
13
+ imageHash,
14
+ {
15
+ image,
16
+ lastRead: Date.now(),
17
+ },
18
+ store
19
+ );
20
+ clearOldItems();
21
+ }
22
+
23
+ export async function getImage(
24
+ imageHash: EntryHash
25
+ ): Promise<string | undefined> {
26
+ const image: CachedImage | undefined = await get(imageHash, store);
27
+
28
+ if (!image) return undefined;
29
+
30
+ storeImage(imageHash, image.image);
31
+
32
+ return image.image;
33
+ }
34
+
35
+ const IMAGE_CLEAR_MS = 7 * 24 * 60 * 60 * 1000; // 3 days
36
+
37
+ async function clearOldItems() {
38
+ const images = await entries<EntryHash, CachedImage>(store);
39
+
40
+ for (const [imageHash, image] of images) {
41
+ if (Date.now() - image.lastRead > IMAGE_CLEAR_MS) {
42
+ await del(imageHash, store);
43
+ }
44
+ }
45
+ }
package/src/mocks.ts ADDED
@@ -0,0 +1,37 @@
1
+ import {
2
+ EntryHashMap,
3
+ ZomeMock,
4
+ hash,
5
+ HashType,
6
+ } from "@holochain-open-dev/utils";
7
+ import { HoloHash } from "@holochain/client";
8
+ import { FileMetadata } from "./types";
9
+
10
+ export class FileStorageZomeMock extends ZomeMock {
11
+ metadata = new EntryHashMap();
12
+ chunks = new EntryHashMap();
13
+
14
+ create_file_metadata(fileMetadata: FileMetadata) {
15
+ const newId = hash(fileMetadata, HashType.ENTRY);
16
+
17
+ this.metadata.set(newId, fileMetadata);
18
+
19
+ return newId;
20
+ }
21
+
22
+ get_file_metadata(fileHash: HoloHash) {
23
+ return this.metadata.get(fileHash);
24
+ }
25
+
26
+ create_file_chunk(fileChunk: Uint8Array) {
27
+ const newId = hash(fileChunk, HashType.ENTRY);
28
+
29
+ this.chunks.set(newId, fileChunk);
30
+
31
+ return newId;
32
+ }
33
+
34
+ get_file_chunk(fileChunkHash: HoloHash) {
35
+ return this.chunks.get(fileChunkHash);
36
+ }
37
+ }
package/src/types.ts ADDED
@@ -0,0 +1,9 @@
1
+ import { EntryHash } from "@holochain/client";
2
+
3
+ export interface FileMetadata {
4
+ name: string;
5
+ last_modifed: number;
6
+ size: number;
7
+ file_type: string;
8
+ chunks_hashes: Array<EntryHash>;
9
+ }