-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
102 lines (100 loc) · 2.74 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
import {
deleteObject,
getBytes,
getMetadata,
ref,
uploadBytes,
type FirebaseStorage,
} from 'firebase/storage';
import { createWriteStream, openAsBlob } from 'node:fs';
export { initializeApp } from 'firebase/app';
export { getStorage } from 'firebase/storage';
/**
* @class FirebaseStorageStore
* @param {Object} options - Options for the store
* @param {FirebaseStorage} options.firebaseStorage - A Firebase Storage instance
* @param {string} options.sessionPath - Path inside the storage bucket to store the session files
* @returns {FirebaseStorageStore}
* @example
* import { Client, RemoteAuth } from 'whatsapp-web.js';
* const client = new Client({
* authStrategy: new RemoteAuth({
* store: new FirebaseStorageStore({
* firebaseStorage: getStorage(app),
* sessionPath: 'sessions-whatsapp-web.js', // save in a sub-directory
* }),
* backupSyncIntervalMs: 600000, // 10 minutes
* }),
* ... // other options
* });
*/
export class FirebaseStorageStore {
public fbStorage: FirebaseStorage;
public sessionPath?: string;
constructor({
firebaseStorage,
sessionPath,
}: {
firebaseStorage: FirebaseStorage;
sessionPath?: string;
}) {
this.fbStorage = firebaseStorage;
this.sessionPath = sessionPath;
}
async sessionExists(options: { session: string }): Promise<boolean> {
try {
await getMetadata(
ref(
this.fbStorage,
this.sessionPath
? `${this.sessionPath.replace(/\\/g, '/')}/${options.session}.zip`
: `${options.session}.zip`,
),
);
return true;
} catch (error) {
return false;
}
}
async save(options: { session: string }): Promise<void> {
await uploadBytes(
ref(
this.fbStorage,
this.sessionPath
? `${this.sessionPath.replace(/\\/g, '/')}/${options.session}.zip`
: `${options.session}.zip`,
),
await openAsBlob(`${options.session}.zip`),
{
contentType: 'application/zip',
},
);
}
async extract(options: { session: string; path: string }): Promise<void> {
createWriteStream(options.path, {
autoClose: true,
encoding: 'binary',
}).write(
Buffer.from(
await getBytes(
ref(
this.fbStorage,
this.sessionPath
? `${this.sessionPath.replace(/\\/g, '/')}/${options.session}.zip`
: `${options.session}.zip`,
),
),
),
);
}
async delete(options: { session: string }): Promise<void> {
return deleteObject(
ref(
this.fbStorage,
this.sessionPath
? `${this.sessionPath.replace(/\\/g, '/')}/${options.session}.zip`
: `${options.session}.zip`,
),
);
}
}