blob: 95b35831609ef6d6444859466f179e38d7e83e03 [file] [log] [blame]
Adrià Vilanova Martínez7f1e8ea2022-10-14 15:50:11 +02001import {arrayBufferToBase64} from './common.js';
2import * as pb from './proto/main_pb.js';
3
4export const kWorkflowsDataKey = 'workflowsData';
5
6export default class WorkflowsStorage {
7 static getAll(asProtobuf = false) {
8 return new Promise(res => {
9 chrome.storage.local.get(kWorkflowsDataKey, items => {
10 const workflows = items[kWorkflowsDataKey];
11 if (!Array.isArray(workflows)) return res([]);
12 if (!asProtobuf) return res(workflows);
13
14 workflows.map(w => {
15 w.proto = pb.workflows.Workflow.deserializeBinary(w?.data);
16 delete w.data;
17 });
18 return res(workflows);
19 });
20 });
21 }
22
23 static get(uuid, asProtobuf = false) {
24 return this.getAll(asProtobuf).then(workflows => {
25 for (const w of workflows) {
26 if (w.uuid == uuid) return w;
27 }
28 return null;
29 });
30 }
31
32 static exists(uuid) {
33 return this.get(uuid).then(w => w !== null);
34 }
35
36 static addRaw(base64Workflow) {
37 const w = {
38 uuid: self.crypto.randomUUID(),
39 data: base64Workflow,
40 };
41 return this.getAll().then(workflows => {
42 workflows.push(w);
43 const items = {};
44 items[kWorkflowsDataKey] = workflows;
45 chrome.storage.local.set(items);
46 });
47 }
48
49 static add(workflow) {
Adrià Vilanova Martínez8803b6c2022-10-17 00:36:38 +020050 return this._proto2Base64(workflow).then(data => {
Adrià Vilanova Martínez7f1e8ea2022-10-14 15:50:11 +020051 return this.addRaw(data);
52 });
53 }
54
Adrià Vilanova Martínez8803b6c2022-10-17 00:36:38 +020055 static updateRaw(uuid, base64Workflow) {
56 return this.getAll().then(workflows => {
57 workflows.map(w => {
58 if (w.uuid !== uuid) return w;
59 w.data = base64Workflow;
60 return w;
61 });
62 const items = {};
63 items[kWorkflowsDataKey] = workflows;
64 chrome.storage.local.set(items);
65 });
66 }
67
68 static update(uuid, workflow) {
69 return this._proto2Base64(workflow).then(data => {
70 return this.updateRaw(uuid, data);
71 });
72 }
73
Adrià Vilanova Martínez7f1e8ea2022-10-14 15:50:11 +020074 static remove(uuid) {
75 return this.getAll().then(workflows => {
76 const items = {};
77 items[kWorkflowsDataKey] = workflows.filter(w => w.uuid != uuid);
78 chrome.storage.local.set(items);
79 });
80 }
Adrià Vilanova Martínez8803b6c2022-10-17 00:36:38 +020081
82 static _proto2Base64(workflow) {
83 const binaryWorkflow = workflow.serializeBinary();
84 return arrayBufferToBase64(binaryWorkflow);
85 }
Adrià Vilanova Martínez7f1e8ea2022-10-14 15:50:11 +020086}