cloud189-sdk 1.0.7 → 1.0.9-beta.0

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.
package/README.md CHANGED
@@ -49,3 +49,7 @@ console.log(info)
49
49
  ```
50
50
 
51
51
  ## [API 文档](https://cloud.189.whaledev.cn/)
52
+
53
+ ## Star History
54
+
55
+ [![Star History Chart](https://api.star-history.com/svg?repos=wes-lin/cloud189-sdk&type=Date)](https://www.star-history.com/#wes-lin/cloud189-sdk&Date)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cloud189-sdk",
3
- "version": "1.0.7",
3
+ "version": "1.0.9-beta.0",
4
4
  "description": "基于node.js的第三方天翼云盘SDK",
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",
@@ -10,7 +10,7 @@
10
10
  "!__tests__"
11
11
  ],
12
12
  "scripts": {
13
- "start": "node ./example/app.js",
13
+ "start": "ts-node ./example/app.ts",
14
14
  "build": "tsc",
15
15
  "docs:build": "npm run build && cd docs && npm run build",
16
16
  "docs:dev": "npm run build && cd docs && npm run dev",
@@ -1,89 +0,0 @@
1
- import { Got } from 'got';
2
- import { UserSignResponse, UserSizeInfoResponse, FamilyListResponse, FamilyUserSignResponse, ConfigurationOptions, ClientSession, RefreshTokenSession, TokenSession, CacheQuery } from './types';
3
- import { Store } from './store';
4
- /**
5
- * @public
6
- */
7
- export declare class CloudAuthClient {
8
- #private;
9
- readonly request: Got;
10
- constructor();
11
- /**
12
- * 获取加密参数
13
- * @returns
14
- */
15
- getEncrypt(): Promise<{
16
- data: {
17
- pubKey: string;
18
- pre: string;
19
- };
20
- }>;
21
- getLoginForm(): Promise<CacheQuery>;
22
- getSessionForPC(param: {
23
- redirectURL?: string;
24
- accessToken?: string;
25
- }): Promise<TokenSession>;
26
- /**
27
- * 用户名密码登录
28
- * */
29
- loginByPassword(username: string, password: string): Promise<TokenSession>;
30
- /**
31
- * token登录
32
- */
33
- loginByAccessToken(accessToken: string): Promise<TokenSession>;
34
- /**
35
- * sso登录
36
- */
37
- loginBySsoCooike(cookie: string): Promise<TokenSession>;
38
- /**
39
- * 刷新token
40
- */
41
- refreshToken(refreshToken: string): Promise<RefreshTokenSession>;
42
- }
43
- /**
44
- * 天翼网盘客户端
45
- * @public
46
- */
47
- export declare class CloudClient {
48
- #private;
49
- username: string;
50
- password: string;
51
- ssonCookie: string;
52
- tokenStore: Store;
53
- readonly request: Got;
54
- readonly authClient: CloudAuthClient;
55
- readonly session: ClientSession;
56
- constructor(_options: ConfigurationOptions);
57
- getSession(): Promise<TokenSession>;
58
- /**
59
- * 获取 sessionKey
60
- * @returns sessionKey
61
- */
62
- getSessionKey(): Promise<string>;
63
- /**
64
- * 获取 accessToken
65
- * @returns accessToken
66
- */
67
- getAccessToken(): Promise<string>;
68
- /**
69
- * 获取用户网盘存储容量信息
70
- * @returns 账号容量结果
71
- */
72
- getUserSizeInfo(): Promise<UserSizeInfoResponse>;
73
- /**
74
- * 个人签到任务
75
- * @returns 签到结果
76
- */
77
- userSign(): Promise<UserSignResponse>;
78
- /**
79
- * 获取家庭信息
80
- * @returns 家庭列表信息
81
- */
82
- getFamilyList(): Promise<FamilyListResponse>;
83
- /**
84
- * 家庭签到任务
85
- * @param familyId - 家庭id
86
- * @returns 签到结果
87
- */
88
- familyUserSign(familyId: number): Promise<FamilyUserSignResponse>;
89
- }
@@ -1,407 +0,0 @@
1
- "use strict";
2
- var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
3
- if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
4
- if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
5
- return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
6
- };
7
- var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
8
- if (kind === "m") throw new TypeError("Private method is not writable");
9
- if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
10
- if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
11
- return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
12
- };
13
- var __importDefault = (this && this.__importDefault) || function (mod) {
14
- return (mod && mod.__esModule) ? mod : { "default": mod };
15
- };
16
- var _CloudAuthClient_builLoginForm, _CloudClient_instances, _CloudClient_sessionKeyPromise, _CloudClient_accessTokenPromise, _CloudClient_valid, _CloudClient_getAccessTokenBySsKey;
17
- Object.defineProperty(exports, "__esModule", { value: true });
18
- exports.CloudClient = exports.CloudAuthClient = void 0;
19
- const url_1 = __importDefault(require("url"));
20
- const got_1 = __importDefault(require("got"));
21
- const log_1 = require("./log");
22
- const util_1 = require("./util");
23
- const const_1 = require("./const");
24
- const store_1 = require("./store");
25
- const error_1 = require("./error");
26
- const config = {
27
- clientId: '538135150693412',
28
- model: 'KB2000',
29
- version: '9.0.6'
30
- };
31
- /**
32
- * @public
33
- */
34
- class CloudAuthClient {
35
- constructor() {
36
- _CloudAuthClient_builLoginForm.set(this, (encrypt, appConf, username, password) => {
37
- const keyData = `-----BEGIN PUBLIC KEY-----\n${encrypt.pubKey}\n-----END PUBLIC KEY-----`;
38
- const usernameEncrypt = (0, util_1.rsaEncrypt)(keyData, username);
39
- const passwordEncrypt = (0, util_1.rsaEncrypt)(keyData, password);
40
- const data = {
41
- appKey: const_1.AppID,
42
- accountType: const_1.AccountType,
43
- // mailSuffix: '@189.cn',
44
- validateCode: '',
45
- captchaToken: appConf.captchaToken,
46
- dynamicCheck: 'FALSE',
47
- clientType: '1',
48
- cb_SaveName: '3',
49
- isOauth2: false,
50
- returnUrl: const_1.ReturnURL,
51
- paramId: appConf.paramId,
52
- userName: `${encrypt.pre}${usernameEncrypt}`,
53
- password: `${encrypt.pre}${passwordEncrypt}`
54
- };
55
- return data;
56
- });
57
- this.request = got_1.default.extend({
58
- headers: {
59
- 'User-Agent': const_1.UserAgent,
60
- Accept: 'application/json;charset=UTF-8'
61
- },
62
- hooks: {
63
- afterResponse: [
64
- async (response, retryWithMergedOptions) => {
65
- log_1.logger.debug(`url: ${response.requestUrl}, response: ${response.body})}`);
66
- (0, error_1.checkError)(response.body.toString());
67
- return response;
68
- }
69
- ]
70
- }
71
- });
72
- }
73
- /**
74
- * 获取加密参数
75
- * @returns
76
- */
77
- getEncrypt() {
78
- return this.request.post(`${const_1.AUTH_URL}/api/logbox/config/encryptConf.do`).json();
79
- }
80
- async getLoginForm() {
81
- const res = await this.request
82
- .get(`${const_1.WEB_URL}/api/portal/unifyLoginForPC.action`, {
83
- searchParams: {
84
- appId: const_1.AppID,
85
- clientType: const_1.ClientType,
86
- returnURL: const_1.ReturnURL,
87
- timeStamp: Date.now()
88
- }
89
- })
90
- .text();
91
- if (res) {
92
- const captchaToken = res.match(`'captchaToken' value='(.+?)'`)[1];
93
- const lt = res.match(`lt = "(.+?)"`)[1];
94
- const paramId = res.match(`paramId = "(.+?)"`)[1];
95
- const reqId = res.match(`reqId = "(.+?)"`)[1];
96
- return { captchaToken, lt, paramId, reqId };
97
- }
98
- return null;
99
- }
100
- async getSessionForPC(param) {
101
- const params = Object.assign(Object.assign({ appId: const_1.AppID }, (0, const_1.clientSuffix)()), param);
102
- const res = await this.request
103
- .post(`${const_1.API_URL}/getSessionForPC.action`, {
104
- searchParams: params
105
- })
106
- .json();
107
- return res;
108
- }
109
- /**
110
- * 用户名密码登录
111
- * */
112
- async loginByPassword(username, password) {
113
- log_1.logger.debug('loginByPassword...');
114
- try {
115
- const res = await Promise.all([
116
- //1.获取公钥
117
- this.getEncrypt(),
118
- //2.获取登录参数
119
- this.getLoginForm()
120
- ]);
121
- const encrypt = res[0].data;
122
- const appConf = res[1];
123
- const data = __classPrivateFieldGet(this, _CloudAuthClient_builLoginForm, "f").call(this, encrypt, appConf, username, password);
124
- const loginRes = await this.request
125
- .post(`${const_1.AUTH_URL}/api/logbox/oauth2/loginSubmit.do`, {
126
- headers: {
127
- Referer: const_1.AUTH_URL,
128
- lt: appConf.lt,
129
- REQID: appConf.reqId
130
- },
131
- form: data
132
- })
133
- .json();
134
- return await this.getSessionForPC({ redirectURL: loginRes.toUrl });
135
- }
136
- catch (e) {
137
- log_1.logger.error(e);
138
- throw e;
139
- }
140
- }
141
- /**
142
- * token登录
143
- */
144
- async loginByAccessToken(accessToken) {
145
- log_1.logger.debug('loginByAccessToken...');
146
- return await this.getSessionForPC({ accessToken });
147
- }
148
- /**
149
- * sso登录
150
- */
151
- async loginBySsoCooike(cookie) {
152
- log_1.logger.debug('loginBySsoCooike...');
153
- const res = await this.request.get(`${const_1.WEB_URL}/api/portal/unifyLoginForPC.action`, {
154
- searchParams: {
155
- appId: const_1.AppID,
156
- clientType: const_1.ClientType,
157
- returnURL: const_1.ReturnURL,
158
- timeStamp: Date.now()
159
- }
160
- });
161
- const redirect = await this.request(res.url, {
162
- headers: {
163
- Cookie: `SSON=${cookie}`
164
- }
165
- });
166
- return await this.getSessionForPC({ redirectURL: redirect.url });
167
- }
168
- /**
169
- * 刷新token
170
- */
171
- refreshToken(refreshToken) {
172
- return this.request
173
- .post(`${const_1.AUTH_URL}/api/oauth2/refreshToken.do`, {
174
- form: {
175
- clientId: const_1.AppID,
176
- refreshToken,
177
- grantType: 'refresh_token',
178
- format: 'json'
179
- }
180
- })
181
- .json();
182
- }
183
- }
184
- exports.CloudAuthClient = CloudAuthClient;
185
- _CloudAuthClient_builLoginForm = new WeakMap();
186
- /**
187
- * 天翼网盘客户端
188
- * @public
189
- */
190
- class CloudClient {
191
- constructor(_options) {
192
- _CloudClient_instances.add(this);
193
- _CloudClient_sessionKeyPromise.set(this, void 0);
194
- _CloudClient_accessTokenPromise.set(this, void 0);
195
- _CloudClient_valid.set(this, (options) => {
196
- if (!options.token && (!options.username || !options.password)) {
197
- log_1.logger.error('valid');
198
- throw new Error('Please provide username and password or token !');
199
- }
200
- });
201
- __classPrivateFieldGet(this, _CloudClient_valid, "f").call(this, _options);
202
- this.username = _options.username;
203
- this.password = _options.password;
204
- this.ssonCookie = _options.ssonCookie;
205
- this.tokenStore = _options.token || new store_1.MemoryStore();
206
- this.authClient = new CloudAuthClient();
207
- this.session = {
208
- accessToken: '',
209
- sessionKey: ''
210
- };
211
- this.request = got_1.default.extend({
212
- retry: {
213
- limit: 5
214
- },
215
- headers: {
216
- 'User-Agent': const_1.UserAgent,
217
- Referer: `${const_1.WEB_URL}/web/main/`,
218
- Accept: 'application/json;charset=UTF-8'
219
- },
220
- hooks: {
221
- beforeRequest: [
222
- async (options) => {
223
- if (options.url.href.includes(const_1.API_URL)) {
224
- const accessToken = await this.getAccessToken();
225
- const { query } = url_1.default.parse(options.url.toString(), true);
226
- const time = String(Date.now());
227
- const signature = (0, util_1.getSignature)(Object.assign(Object.assign({}, (options.method === 'GET' ? query : options.json)), { Timestamp: time, AccessToken: accessToken }));
228
- options.headers['Sign-Type'] = '1';
229
- options.headers['Signature'] = signature;
230
- options.headers['Timestamp'] = time;
231
- options.headers['Accesstoken'] = accessToken;
232
- }
233
- else if (options.url.href.includes(const_1.WEB_URL)) {
234
- const urlObj = new URL(options.url);
235
- if (options.url.href.includes('/open')) {
236
- const time = String(Date.now());
237
- const appkey = '600100422';
238
- const signature = (0, util_1.getSignature)(Object.assign(Object.assign({}, (options.method === 'GET' ? urlObj.searchParams : options.json)), { Timestamp: time, AppKey: appkey }));
239
- options.headers['Sign-Type'] = '1';
240
- options.headers['Signature'] = signature;
241
- options.headers['Timestamp'] = time;
242
- options.headers['AppKey'] = appkey;
243
- }
244
- const sessionKey = await this.getSessionKey();
245
- urlObj.searchParams.set('sessionKey', sessionKey);
246
- options.url = urlObj;
247
- }
248
- }
249
- ],
250
- afterResponse: [
251
- async (response, retryWithMergedOptions) => {
252
- log_1.logger.debug(`url: ${response.requestUrl}, response: ${response.body}`);
253
- if (response.statusCode === 400) {
254
- const { errorCode, errorMsg } = JSON.parse(response.body.toString());
255
- if (errorCode === 'InvalidAccessToken') {
256
- log_1.logger.debug('InvalidAccessToken retry...');
257
- log_1.logger.debug('Refresh AccessToken');
258
- this.session.accessToken = '';
259
- return retryWithMergedOptions({});
260
- }
261
- else if (errorCode === 'InvalidSessionKey') {
262
- log_1.logger.debug('InvalidSessionKey retry...');
263
- log_1.logger.debug('Refresh InvalidSessionKey');
264
- this.session.sessionKey = '';
265
- return retryWithMergedOptions({});
266
- }
267
- }
268
- return response;
269
- }
270
- ]
271
- }
272
- });
273
- }
274
- async getSession() {
275
- const { accessToken, expiresIn, refreshToken } = await this.tokenStore.get();
276
- if (accessToken && expiresIn && expiresIn > Date.now()) {
277
- try {
278
- return await this.authClient.loginByAccessToken(accessToken);
279
- }
280
- catch (e) {
281
- log_1.logger.error(e);
282
- }
283
- }
284
- if (refreshToken) {
285
- try {
286
- const refreshTokenSession = await this.authClient.refreshToken(refreshToken);
287
- await this.tokenStore.update({
288
- accessToken: refreshTokenSession.accessToken,
289
- refreshToken: refreshTokenSession.refreshToken,
290
- expiresIn: new Date(Date.now() + refreshTokenSession.expiresIn * 1000).getTime()
291
- });
292
- return await this.authClient.loginByAccessToken(refreshTokenSession.accessToken);
293
- }
294
- catch (e) {
295
- log_1.logger.error(e);
296
- }
297
- }
298
- if (this.ssonCookie) {
299
- try {
300
- const loginToken = await this.authClient.loginBySsoCooike(this.ssonCookie);
301
- await this.tokenStore.update({
302
- accessToken: loginToken.accessToken,
303
- refreshToken: loginToken.refreshToken,
304
- expiresIn: new Date(Date.now() + 6 * 24 * 60 * 60 * 1000).getTime()
305
- });
306
- return loginToken;
307
- }
308
- catch (e) {
309
- log_1.logger.error(e);
310
- }
311
- }
312
- if (this.username && this.password) {
313
- try {
314
- const loginToken = await this.authClient.loginByPassword(this.username, this.password);
315
- await this.tokenStore.update({
316
- accessToken: loginToken.accessToken,
317
- refreshToken: loginToken.refreshToken,
318
- expiresIn: new Date(Date.now() + 6 * 24 * 60 * 60 * 1000).getTime()
319
- });
320
- return loginToken;
321
- }
322
- catch (e) {
323
- log_1.logger.error(e);
324
- }
325
- }
326
- throw new Error('Can not get session.');
327
- }
328
- /**
329
- * 获取 sessionKey
330
- * @returns sessionKey
331
- */
332
- async getSessionKey() {
333
- if (this.session.sessionKey) {
334
- return this.session.sessionKey;
335
- }
336
- if (!__classPrivateFieldGet(this, _CloudClient_sessionKeyPromise, "f")) {
337
- __classPrivateFieldSet(this, _CloudClient_sessionKeyPromise, this.getSession()
338
- .then((result) => {
339
- this.session.sessionKey = result.sessionKey;
340
- return result;
341
- })
342
- .finally(() => {
343
- __classPrivateFieldSet(this, _CloudClient_sessionKeyPromise, null, "f");
344
- }), "f");
345
- }
346
- const result = await __classPrivateFieldGet(this, _CloudClient_sessionKeyPromise, "f");
347
- return result.sessionKey;
348
- }
349
- /**
350
- * 获取 accessToken
351
- * @returns accessToken
352
- */
353
- async getAccessToken() {
354
- if (this.session.accessToken) {
355
- return this.session.accessToken;
356
- }
357
- if (!__classPrivateFieldGet(this, _CloudClient_accessTokenPromise, "f")) {
358
- __classPrivateFieldSet(this, _CloudClient_accessTokenPromise, __classPrivateFieldGet(this, _CloudClient_instances, "m", _CloudClient_getAccessTokenBySsKey).call(this)
359
- .then((result) => {
360
- this.session.accessToken = result.accessToken;
361
- return result;
362
- })
363
- .finally(() => {
364
- __classPrivateFieldSet(this, _CloudClient_accessTokenPromise, null, "f");
365
- }), "f");
366
- }
367
- const result = await __classPrivateFieldGet(this, _CloudClient_accessTokenPromise, "f");
368
- return result.accessToken;
369
- }
370
- /**
371
- * 获取用户网盘存储容量信息
372
- * @returns 账号容量结果
373
- */
374
- getUserSizeInfo() {
375
- return this.request.get(`${const_1.WEB_URL}/api/portal/getUserSizeInfo.action`).json();
376
- }
377
- /**
378
- * 个人签到任务
379
- * @returns 签到结果
380
- */
381
- userSign() {
382
- return this.request
383
- .get(`${const_1.WEB_URL}/mkt/userSign.action?rand=${new Date().getTime()}&clientType=TELEANDROID&version=${config.version}&model=${config.model}`)
384
- .json();
385
- }
386
- /**
387
- * 获取家庭信息
388
- * @returns 家庭列表信息
389
- */
390
- getFamilyList() {
391
- return this.request.get(`${const_1.API_URL}/open/family/manage/getFamilyList.action`).json();
392
- }
393
- /**
394
- * 家庭签到任务
395
- * @param familyId - 家庭id
396
- * @returns 签到结果
397
- */
398
- familyUserSign(familyId) {
399
- return this.request
400
- .get(`${const_1.API_URL}/open/family/manage/exeFamilyUserSign.action?familyId=${familyId}`)
401
- .json();
402
- }
403
- }
404
- exports.CloudClient = CloudClient;
405
- _CloudClient_sessionKeyPromise = new WeakMap(), _CloudClient_accessTokenPromise = new WeakMap(), _CloudClient_valid = new WeakMap(), _CloudClient_instances = new WeakSet(), _CloudClient_getAccessTokenBySsKey = function _CloudClient_getAccessTokenBySsKey() {
406
- return this.request.get(`${const_1.WEB_URL}/api/open/oauth2/getAccessTokenBySsKey.action`).json();
407
- };
package/dist/const.d.ts DELETED
@@ -1,14 +0,0 @@
1
- export declare const WEB_URL = "https://cloud.189.cn";
2
- export declare const AUTH_URL = "https://open.e.189.cn";
3
- export declare const API_URL = "https://api.cloud.189.cn";
4
- export declare const AccountType = "02";
5
- export declare const AppID = "8025431004";
6
- export declare const ClientType = "10020";
7
- export declare const ReturnURL = "https://m.cloud.189.cn/zhuanti/2020/loginErrorPc/index.html";
8
- export declare const UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36";
9
- export declare const clientSuffix: () => {
10
- clientType: string;
11
- version: string;
12
- channelId: string;
13
- rand: number;
14
- };
package/dist/const.js DELETED
@@ -1,19 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.clientSuffix = exports.UserAgent = exports.ReturnURL = exports.ClientType = exports.AppID = exports.AccountType = exports.API_URL = exports.AUTH_URL = exports.WEB_URL = void 0;
4
- exports.WEB_URL = 'https://cloud.189.cn';
5
- exports.AUTH_URL = 'https://open.e.189.cn';
6
- exports.API_URL = 'https://api.cloud.189.cn';
7
- exports.AccountType = '02';
8
- exports.AppID = '8025431004';
9
- exports.ClientType = '10020';
10
- exports.ReturnURL = 'https://m.cloud.189.cn/zhuanti/2020/loginErrorPc/index.html';
11
- exports.UserAgent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36';
12
- const Version = '6.2', PC = 'TELEPC', ChannelID = 'web_cloud.189.cn';
13
- const clientSuffix = () => ({
14
- clientType: PC,
15
- version: Version,
16
- channelId: ChannelID,
17
- rand: Date.now()
18
- });
19
- exports.clientSuffix = clientSuffix;
package/dist/error.d.ts DELETED
@@ -1,5 +0,0 @@
1
- export declare class InvalidRefreshTokenError extends Error {
2
- }
3
- export declare class AuthApiError extends Error {
4
- }
5
- export declare const checkError: (response: any) => void;
package/dist/error.js DELETED
@@ -1,30 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.checkError = exports.AuthApiError = exports.InvalidRefreshTokenError = void 0;
4
- class InvalidRefreshTokenError extends Error {
5
- }
6
- exports.InvalidRefreshTokenError = InvalidRefreshTokenError;
7
- class AuthApiError extends Error {
8
- }
9
- exports.AuthApiError = AuthApiError;
10
- const checkError = (response) => {
11
- let res;
12
- try {
13
- res = JSON.parse(response);
14
- }
15
- catch (e) {
16
- return;
17
- }
18
- // auth
19
- if ('result' in res && 'msg' in res) {
20
- switch (res.result) {
21
- case 0:
22
- return;
23
- case -117:
24
- throw new InvalidRefreshTokenError(res.msg);
25
- default:
26
- throw new AuthApiError(res.msg);
27
- }
28
- }
29
- };
30
- exports.checkError = checkError;
package/dist/index.d.ts DELETED
@@ -1,4 +0,0 @@
1
- export * from './CloudClient';
2
- export * from './types';
3
- export * from './store';
4
- export * from './log';
package/dist/index.js DELETED
@@ -1,20 +0,0 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
- for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
- };
16
- Object.defineProperty(exports, "__esModule", { value: true });
17
- __exportStar(require("./CloudClient"), exports);
18
- __exportStar(require("./types"), exports);
19
- __exportStar(require("./store"), exports);
20
- __exportStar(require("./log"), exports);
package/dist/log.d.ts DELETED
@@ -1,7 +0,0 @@
1
- import { Logger } from '@netdrive-sdk/log';
2
- /**
3
- * 日志记录
4
- * @public
5
- */
6
- declare const logger: Logger;
7
- export { logger };
package/dist/log.js DELETED
@@ -1,10 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.logger = void 0;
4
- const log_1 = require("@netdrive-sdk/log");
5
- /**
6
- * 日志记录
7
- * @public
8
- */
9
- const logger = new log_1.Logger();
10
- exports.logger = logger;
@@ -1,15 +0,0 @@
1
- import { MemoryStore } from './memstore';
2
- /**
3
- * @public
4
- */
5
- export declare class FileTokenStore extends MemoryStore {
6
- #private;
7
- filePath: string;
8
- constructor(filePath: string);
9
- private ensureTokenDirectory;
10
- update(token: {
11
- accessToken: string;
12
- refreshToken?: string;
13
- expiresIn?: number;
14
- }): Promise<void>;
15
- }
@@ -1,89 +0,0 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
- Object.defineProperty(o, "default", { enumerable: true, value: v });
15
- }) : function(o, v) {
16
- o["default"] = v;
17
- });
18
- var __importStar = (this && this.__importStar) || function (mod) {
19
- if (mod && mod.__esModule) return mod;
20
- var result = {};
21
- if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
- __setModuleDefault(result, mod);
23
- return result;
24
- };
25
- var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
26
- if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
27
- if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
28
- return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
29
- };
30
- var __importDefault = (this && this.__importDefault) || function (mod) {
31
- return (mod && mod.__esModule) ? mod : { "default": mod };
32
- };
33
- var _FileTokenStore_instances, _FileTokenStore_loadFromFile, _FileTokenStore_saveToFile;
34
- Object.defineProperty(exports, "__esModule", { value: true });
35
- exports.FileTokenStore = void 0;
36
- const fs = __importStar(require("node:fs"));
37
- const promisesFs = __importStar(require("node:fs/promises"));
38
- const path_1 = __importDefault(require("path"));
39
- const memstore_1 = require("./memstore");
40
- /**
41
- * @public
42
- */
43
- class FileTokenStore extends memstore_1.MemoryStore {
44
- constructor(filePath) {
45
- super();
46
- _FileTokenStore_instances.add(this);
47
- this.filePath = filePath;
48
- if (!filePath) {
49
- throw new Error('Unknown file for read/write token');
50
- }
51
- this.ensureTokenDirectory(filePath);
52
- const dataJson = __classPrivateFieldGet(this, _FileTokenStore_instances, "m", _FileTokenStore_loadFromFile).call(this, filePath);
53
- if (dataJson) {
54
- super.update(dataJson);
55
- }
56
- }
57
- ensureTokenDirectory(filePath) {
58
- const dir = path_1.default.dirname(filePath);
59
- if (!fs.existsSync(dir)) {
60
- fs.mkdirSync(dir, { recursive: true });
61
- }
62
- }
63
- update(token) {
64
- super.update(token);
65
- return __classPrivateFieldGet(this, _FileTokenStore_instances, "m", _FileTokenStore_saveToFile).call(this, this.filePath, this.store);
66
- }
67
- }
68
- exports.FileTokenStore = FileTokenStore;
69
- _FileTokenStore_instances = new WeakSet(), _FileTokenStore_loadFromFile = function _FileTokenStore_loadFromFile(filePath) {
70
- let data = null;
71
- if (fs.existsSync(filePath)) {
72
- data = fs.readFileSync(filePath, {
73
- encoding: 'utf-8'
74
- });
75
- }
76
- if (data) {
77
- try {
78
- return JSON.parse(data);
79
- }
80
- catch (e) {
81
- throw new Error(`Could not parse token file ${filePath}. Please ensure it is not corrupted.`);
82
- }
83
- }
84
- return null;
85
- }, _FileTokenStore_saveToFile = function _FileTokenStore_saveToFile(filePath, data) {
86
- return promisesFs.writeFile(filePath, JSON.stringify(data), {
87
- encoding: 'utf-8'
88
- });
89
- };
@@ -1,3 +0,0 @@
1
- export * from './store';
2
- export * from './memstore';
3
- export * from './file-token-store';
@@ -1,19 +0,0 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
- for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
- };
16
- Object.defineProperty(exports, "__esModule", { value: true });
17
- __exportStar(require("./store"), exports);
18
- __exportStar(require("./memstore"), exports);
19
- __exportStar(require("./file-token-store"), exports);
@@ -1,22 +0,0 @@
1
- import { Store } from './store';
2
- /**
3
- * @public
4
- */
5
- export declare class MemoryStore extends Store {
6
- store: {
7
- accessToken: string;
8
- refreshToken: string;
9
- expiresIn: number;
10
- };
11
- constructor();
12
- get(): {
13
- accessToken: string;
14
- refreshToken: string;
15
- expiresIn: number;
16
- };
17
- update(token: {
18
- accessToken: string;
19
- refreshToken?: string;
20
- expiresIn?: number;
21
- }): void;
22
- }
@@ -1,29 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.MemoryStore = void 0;
4
- const store_1 = require("./store");
5
- /**
6
- * @public
7
- */
8
- class MemoryStore extends store_1.Store {
9
- constructor() {
10
- super();
11
- this.store = {
12
- accessToken: '',
13
- refreshToken: '',
14
- expiresIn: 0
15
- };
16
- }
17
- get() {
18
- return this.store;
19
- }
20
- update(token) {
21
- var _a, _b;
22
- this.store = {
23
- accessToken: token.accessToken,
24
- refreshToken: (_a = token.refreshToken) !== null && _a !== void 0 ? _a : this.store.refreshToken,
25
- expiresIn: (_b = token.expiresIn) !== null && _b !== void 0 ? _b : this.store.expiresIn
26
- };
27
- }
28
- }
29
- exports.MemoryStore = MemoryStore;
@@ -1,20 +0,0 @@
1
- /**
2
- * @public
3
- */
4
- export declare abstract class Store {
5
- constructor();
6
- abstract get(): {
7
- accessToken: string;
8
- refreshToken: string;
9
- expiresIn: number;
10
- } | Promise<{
11
- accessToken: string;
12
- refreshToken: string;
13
- expiresIn: number;
14
- }>;
15
- abstract update(token: {
16
- accessToken: string;
17
- refreshToken?: string;
18
- expiresIn?: number;
19
- }): void | Promise<void>;
20
- }
@@ -1,10 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.Store = void 0;
4
- /**
5
- * @public
6
- */
7
- class Store {
8
- constructor() { }
9
- }
10
- exports.Store = Store;
package/dist/types.d.ts DELETED
@@ -1,178 +0,0 @@
1
- import { Store } from './store';
2
- /**
3
- * 账户家庭信息
4
- * @public
5
- */
6
- export interface FamilyListResponse {
7
- familyInfoResp: [
8
- {
9
- /**
10
- * 家庭id
11
- */
12
- familyId: number;
13
- /**
14
- * 家庭名称
15
- */
16
- remarkName: string;
17
- /**
18
- * 类型
19
- */
20
- type: number;
21
- /**
22
- * 用户角色 如果是1 表明当前账户是该账户的主家庭 否则当前账户是其他家庭的成员账户
23
- */
24
- userRole: number;
25
- }
26
- ];
27
- }
28
- /**
29
- * accessToken 结果
30
- * @public
31
- */
32
- export interface AccessTokenResponse {
33
- /**
34
- * accessToken
35
- */
36
- accessToken: string;
37
- /**
38
- * accessToken 的有效期 单位秒
39
- */
40
- expiresIn: number;
41
- }
42
- /**
43
- * 家庭签到任务结果
44
- * @public
45
- */
46
- export interface FamilyUserSignResponse {
47
- /**
48
- * 签到的奖励容量 单位MB
49
- */
50
- bonusSpace: number;
51
- /**
52
- * 签到的家庭id
53
- */
54
- signFamilyId: number;
55
- /**
56
- * 签到的状态
57
- */
58
- signStatus: number;
59
- /**
60
- * 签到的时间
61
- */
62
- signTime: string;
63
- /**
64
- * 签到的用户
65
- */
66
- userId: string;
67
- }
68
- /**
69
- * 容量信息
70
- * @public
71
- */
72
- export interface CapacityInfo {
73
- /**
74
- * 总空间 单位KB
75
- */
76
- totalSize: number;
77
- /**
78
- * 已使用空间 单位KB
79
- */
80
- usedSize: number;
81
- /**
82
- * 剩余空间 单位KB
83
- */
84
- freeSize: number;
85
- }
86
- /**
87
- * 账户容量信息
88
- * @public
89
- */
90
- export interface UserSizeInfoResponse {
91
- /**
92
- * 个人容量信息
93
- */
94
- cloudCapacityInfo: CapacityInfo;
95
- /**
96
- * 家庭容量信息
97
- */
98
- familyCapacityInfo: CapacityInfo;
99
- }
100
- /**
101
- * 个人签到结果
102
- * @public
103
- */
104
- export interface UserSignResponse {
105
- /**
106
- * 是否已经签到过
107
- */
108
- isSign: boolean;
109
- /**
110
- * 签到获取的容量奖励 单位MB
111
- */
112
- netdiskBonus: number;
113
- }
114
- /**
115
- * 个人任务执行结果
116
- * @public
117
- */
118
- export interface UserTaskResponse {
119
- /**
120
- * 错误码
121
- */
122
- errorCode: string;
123
- /**
124
- * 奖励容量 单位MB
125
- */
126
- prizeName: string;
127
- }
128
- /**
129
- * @public
130
- */
131
- export interface CacheQuery {
132
- captchaToken: string;
133
- reqId: string;
134
- lt: string;
135
- paramId: string;
136
- }
137
- /**
138
- * 客户端初始化参数
139
- * @public
140
- */
141
- export interface ConfigurationOptions {
142
- /** 登录名 */
143
- username?: string;
144
- /** 密码 */
145
- password?: string;
146
- /** token */
147
- token?: Store;
148
- ssonCookie?: string;
149
- }
150
- /**
151
- * @public
152
- * accessToken 有效期7天,可以通过refreshToken取新的accessToken
153
- */
154
- export interface TokenSession {
155
- res_code: number;
156
- res_message: string;
157
- accessToken: string;
158
- familySessionKey: string;
159
- familySessionSecret: string;
160
- refreshToken: string;
161
- loginName: string;
162
- sessionKey: string;
163
- }
164
- /**
165
- * @public
166
- */
167
- export interface RefreshTokenSession {
168
- expiresIn: number;
169
- accessToken: string;
170
- refreshToken: string;
171
- }
172
- /**
173
- * @public
174
- */
175
- export interface ClientSession {
176
- accessToken: string;
177
- sessionKey: string;
178
- }
package/dist/types.js DELETED
@@ -1,2 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
package/dist/util.d.ts DELETED
@@ -1,3 +0,0 @@
1
- export declare const sortParameter: (data: any) => string;
2
- export declare const getSignature: (data: any) => string;
3
- export declare const rsaEncrypt: (publicKey: string, origData: string) => string;
package/dist/util.js DELETED
@@ -1,29 +0,0 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.rsaEncrypt = exports.getSignature = exports.sortParameter = void 0;
7
- const crypto_1 = __importDefault(require("crypto"));
8
- const sortParameter = (data) => {
9
- if (!data) {
10
- return '';
11
- }
12
- const e = Object.entries(data).map((t) => t.join('='));
13
- e.sort((a, b) => (a > b ? 1 : a < b ? -1 : 0));
14
- return e.join('&');
15
- };
16
- exports.sortParameter = sortParameter;
17
- const getSignature = (data) => {
18
- const parameter = (0, exports.sortParameter)(data);
19
- return crypto_1.default.createHash('md5').update(parameter).digest('hex');
20
- };
21
- exports.getSignature = getSignature;
22
- const rsaEncrypt = (publicKey, origData) => {
23
- const encryptedData = crypto_1.default.publicEncrypt({
24
- key: publicKey,
25
- padding: crypto_1.default.constants.RSA_PKCS1_PADDING
26
- }, Buffer.from(origData));
27
- return encryptedData.toString('hex').toUpperCase();
28
- };
29
- exports.rsaEncrypt = rsaEncrypt;