-
-
Notifications
You must be signed in to change notification settings - Fork 300
/
fileTokenStore.ts
203 lines (176 loc) · 5.03 KB
/
fileTokenStore.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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
/*
* This file is part of WPPConnect.
*
* WPPConnect is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* WPPConnect is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with WPPConnect. If not, see <https://www.gnu.org/licenses/>.
*/
/// <reference types="node" />
import * as fs from 'fs';
import * as path from 'path';
import sanitize from 'sanitize-filename';
import { defaultLogger } from '../utils/logger';
import { isValidSessionToken } from './isValidSessionToken';
import { SessionToken, TokenStore } from './types';
export interface FileTokenStoreOptions {
/**
* Decode function to parse token file (Default `JSON.parse`) {@link defaultFileTokenStoreOptions}
* @default `JSON.parse`
*/
decodeFunction: (text: string) => any;
/**
* Encode function to save tokens (Default `JSON.stringify`)
* @default `JSON.stringify`
*/
encodeFunction: (data: any) => string;
/**
* Encoding used to read and save files
* @default 'utf8'
*/
encoding: BufferEncoding;
/**
* @default '.data.json'
*/
fileExtension: string;
/**
* Folder path to store tokens
* @default './tokens'
*/
path: string;
}
export const defaultFileTokenStoreOptions: FileTokenStoreOptions = {
decodeFunction: JSON.parse,
encodeFunction: JSON.stringify,
encoding: 'utf8',
fileExtension: '.data.json',
path: './tokens',
};
/**
* Token Store using file
*
* ```typescript
* // Example of typescript with FileTokenStore
* import * as wppconnect from '@wppconnect-team/wppconnect';
*
* const myTokenStore = new wppconnect.tokenStore.FileTokenStore({
* // decodeFunction: JSON.parse,
* // encodeFunction: JSON.stringify,
* // encoding: 'utf8',
* // fileExtension: '.my.ext',
* // path: './a_custom_path',
* });
*
* wppconnect.create({
* session: 'mySession',
* tokenStore: myTokenStore,
* });
*
* wppconnect.create({
* session: 'otherSession',
* tokenStore: myTokenStore,
* });
* ```
*/
export class FileTokenStore implements TokenStore {
protected options: FileTokenStoreOptions;
constructor(options: Partial<FileTokenStoreOptions> = {}) {
this.options = Object.assign(
{},
defaultFileTokenStoreOptions,
options
) as FileTokenStoreOptions;
}
/**
* Resolve the path of file
* @param sessionName Name of session
* @returns Full path of token file
*/
protected resolverPath(sessionName: string): string {
const filename = sanitize(sessionName) + this.options.fileExtension;
return path.resolve(process.cwd(), path.join(this.options.path, filename));
}
public async getToken(
sessionName: string
): Promise<SessionToken | undefined> {
const filePath = this.resolverPath(sessionName);
if (!fs.existsSync(filePath)) {
return undefined;
}
const text = await fs.promises
.readFile(filePath, {
encoding: this.options.encoding,
})
.catch(() => null);
if (!text) {
return undefined;
}
try {
return this.options.decodeFunction(text);
} catch (error) {
defaultLogger.debug(error);
return undefined;
}
}
public async setToken(
sessionName: string,
tokenData: SessionToken | null
): Promise<boolean> {
if (!tokenData || !isValidSessionToken(tokenData)) {
return false;
}
if (!fs.existsSync(this.options.path)) {
await fs.promises.mkdir(this.options.path, { recursive: true });
}
const filePath = this.resolverPath(sessionName);
try {
const text = this.options.encodeFunction(tokenData);
await fs.promises.writeFile(filePath, text, {
encoding: this.options.encoding,
});
return true;
} catch (error) {
defaultLogger.debug(error);
return false;
}
}
public async removeToken(sessionName: string): Promise<boolean> {
const filePath = this.resolverPath(sessionName);
if (!fs.existsSync(filePath)) {
return false;
}
try {
await fs.promises.unlink(filePath);
return true;
} catch (error) {
defaultLogger.debug(error);
return false;
}
}
public async listTokens(): Promise<string[]> {
if (!fs.existsSync(this.options.path)) {
return [];
}
try {
let files = await fs.promises.readdir(this.options.path);
// Only sessions with same fileExtension
files = files.filter((file) => file.endsWith(this.options.fileExtension));
// Return name only
files = files.map((file) =>
path.basename(file, this.options.fileExtension)
);
return files;
} catch (error) {
defaultLogger.debug(error);
return [];
}
}
}