cloud189-sdk 1.0.9-beta.0 → 1.0.9

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.
@@ -0,0 +1,59 @@
1
+ import { Got } from 'got';
2
+ import { RefreshTokenSession, TokenSession, CacheQuery, QRCodeData, QRCodeStatusResponse, QRLoginOptions } from './types';
3
+ /**
4
+ * @public
5
+ */
6
+ export declare class CloudAuthClient {
7
+ #private;
8
+ readonly authRequest: Got;
9
+ constructor();
10
+ /**
11
+ * 获取加密参数
12
+ * @returns
13
+ */
14
+ getEncrypt(): Promise<{
15
+ data: {
16
+ pubKey: string;
17
+ pre: string;
18
+ };
19
+ }>;
20
+ getLoginForm(): Promise<CacheQuery>;
21
+ getSessionForPC(param: {
22
+ redirectURL?: string;
23
+ accessToken?: string;
24
+ }): Promise<TokenSession>;
25
+ /**
26
+ * 用户名密码登录
27
+ * */
28
+ loginByPassword(username: string, password: string): Promise<TokenSession>;
29
+ /**
30
+ * token登录
31
+ */
32
+ loginByAccessToken(accessToken: string): Promise<TokenSession>;
33
+ /**
34
+ * sso登录
35
+ */
36
+ loginBySsoCooike(cookie: string): Promise<TokenSession>;
37
+ /**
38
+ * 刷新token
39
+ */
40
+ refreshToken(refreshToken: string): Promise<RefreshTokenSession>;
41
+ /**
42
+ * Get QR code data for scanning login
43
+ * @returns QR code data including uuid for display
44
+ */
45
+ getQRCode(): Promise<QRCodeData>;
46
+ /**
47
+ * Check QR code scan status
48
+ * @param qrData - QR code data from getQRCode
49
+ * @returns status and redirectUrl on success
50
+ */
51
+ checkQRCodeStatus(qrData: QRCodeData): Promise<QRCodeStatusResponse>;
52
+ /**
53
+ * QR code login with polling
54
+ * @param onQRReady - callback invoked with QR code URL for display
55
+ * @param options - polling interval and timeout
56
+ * @returns token session
57
+ */
58
+ loginByQRCode(onQRReady: (qrUrl: string) => void, options?: QRLoginOptions): Promise<TokenSession>;
59
+ }
@@ -0,0 +1,249 @@
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 __importDefault = (this && this.__importDefault) || function (mod) {
8
+ return (mod && mod.__esModule) ? mod : { "default": mod };
9
+ };
10
+ var _CloudAuthClient_builLoginForm;
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.CloudAuthClient = void 0;
13
+ const got_1 = __importDefault(require("got"));
14
+ const log_1 = require("./log");
15
+ const const_1 = require("./const");
16
+ const types_1 = require("./types");
17
+ const util_1 = require("./util");
18
+ const hook_1 = require("./hook");
19
+ /**
20
+ * @public
21
+ */
22
+ class CloudAuthClient {
23
+ constructor() {
24
+ _CloudAuthClient_builLoginForm.set(this, (encrypt, appConf, username, password) => {
25
+ const usernameEncrypt = (0, util_1.rsaEncrypt)(encrypt.pubKey, username);
26
+ const passwordEncrypt = (0, util_1.rsaEncrypt)(encrypt.pubKey, password);
27
+ const data = {
28
+ appKey: const_1.AppID,
29
+ accountType: const_1.AccountType,
30
+ // mailSuffix: '@189.cn',
31
+ validateCode: '',
32
+ captchaToken: appConf.captchaToken,
33
+ dynamicCheck: 'FALSE',
34
+ clientType: '1',
35
+ cb_SaveName: '3',
36
+ isOauth2: false,
37
+ returnUrl: const_1.ReturnURL,
38
+ paramId: appConf.paramId,
39
+ userName: `${encrypt.pre}${usernameEncrypt}`,
40
+ password: `${encrypt.pre}${passwordEncrypt}`
41
+ };
42
+ return data;
43
+ });
44
+ this.authRequest = got_1.default.extend({
45
+ headers: {
46
+ 'User-Agent': const_1.UserAgent,
47
+ Accept: 'application/json;charset=UTF-8'
48
+ },
49
+ hooks: {
50
+ afterResponse: [hook_1.logHook, hook_1.checkErrorHook]
51
+ }
52
+ });
53
+ }
54
+ /**
55
+ * 获取加密参数
56
+ * @returns
57
+ */
58
+ getEncrypt() {
59
+ return this.authRequest.post(`${const_1.AUTH_URL}/api/logbox/config/encryptConf.do`).json();
60
+ }
61
+ async getLoginForm() {
62
+ const res = await this.authRequest
63
+ .get(`${const_1.WEB_URL}/api/portal/unifyLoginForPC.action`, {
64
+ searchParams: {
65
+ appId: const_1.AppID,
66
+ clientType: const_1.ClientType,
67
+ returnURL: const_1.ReturnURL,
68
+ timeStamp: Date.now()
69
+ }
70
+ })
71
+ .text();
72
+ if (res) {
73
+ const captchaToken = res.match(`'captchaToken' value='(.+?)'`)[1];
74
+ const lt = res.match(`lt = "(.+?)"`)[1];
75
+ const paramId = res.match(`paramId = "(.+?)"`)[1];
76
+ const reqId = res.match(`reqId = "(.+?)"`)[1];
77
+ return { captchaToken, lt, paramId, reqId };
78
+ }
79
+ return null;
80
+ }
81
+ async getSessionForPC(param) {
82
+ const params = Object.assign(Object.assign({ appId: const_1.AppID }, (0, const_1.clientSuffix)()), param);
83
+ const res = await this.authRequest
84
+ .post(`${const_1.API_URL}/getSessionForPC.action`, {
85
+ searchParams: params
86
+ })
87
+ .json();
88
+ return res;
89
+ }
90
+ /**
91
+ * 用户名密码登录
92
+ * */
93
+ async loginByPassword(username, password) {
94
+ log_1.logger.debug('loginByPassword...');
95
+ try {
96
+ const res = await Promise.all([
97
+ //1.获取公钥
98
+ this.getEncrypt(),
99
+ //2.获取登录参数
100
+ this.getLoginForm()
101
+ ]);
102
+ const encrypt = res[0].data;
103
+ const appConf = res[1];
104
+ const data = __classPrivateFieldGet(this, _CloudAuthClient_builLoginForm, "f").call(this, encrypt, appConf, username, password);
105
+ const loginRes = await this.authRequest
106
+ .post(`${const_1.AUTH_URL}/api/logbox/oauth2/loginSubmit.do`, {
107
+ headers: {
108
+ Referer: const_1.AUTH_URL,
109
+ lt: appConf.lt,
110
+ REQID: appConf.reqId
111
+ },
112
+ form: data
113
+ })
114
+ .json();
115
+ return await this.getSessionForPC({ redirectURL: loginRes.toUrl });
116
+ }
117
+ catch (e) {
118
+ log_1.logger.error(e);
119
+ throw e;
120
+ }
121
+ }
122
+ /**
123
+ * token登录
124
+ */
125
+ async loginByAccessToken(accessToken) {
126
+ log_1.logger.debug('loginByAccessToken...');
127
+ return await this.getSessionForPC({ accessToken });
128
+ }
129
+ /**
130
+ * sso登录
131
+ */
132
+ async loginBySsoCooike(cookie) {
133
+ log_1.logger.debug('loginBySsoCooike...');
134
+ const res = await this.authRequest.get(`${const_1.WEB_URL}/api/portal/unifyLoginForPC.action`, {
135
+ searchParams: {
136
+ appId: const_1.AppID,
137
+ clientType: const_1.ClientType,
138
+ returnURL: const_1.ReturnURL,
139
+ timeStamp: Date.now()
140
+ }
141
+ });
142
+ const redirect = await this.authRequest(res.url, {
143
+ headers: {
144
+ Cookie: `SSON=${cookie}`
145
+ }
146
+ });
147
+ return await this.getSessionForPC({ redirectURL: redirect.url });
148
+ }
149
+ /**
150
+ * 刷新token
151
+ */
152
+ refreshToken(refreshToken) {
153
+ return this.authRequest
154
+ .post(`${const_1.AUTH_URL}/api/oauth2/refreshToken.do`, {
155
+ form: {
156
+ clientId: const_1.AppID,
157
+ refreshToken,
158
+ grantType: 'refresh_token',
159
+ format: 'json'
160
+ }
161
+ })
162
+ .json();
163
+ }
164
+ /**
165
+ * Get QR code data for scanning login
166
+ * @returns QR code data including uuid for display
167
+ */
168
+ async getQRCode() {
169
+ log_1.logger.debug('getQRCode...');
170
+ const loginForm = await this.getLoginForm();
171
+ const uuidRes = await this.authRequest
172
+ .post(`${const_1.AUTH_URL}/api/logbox/oauth2/getUUID.do`, {
173
+ headers: {
174
+ Referer: const_1.AUTH_URL
175
+ },
176
+ form: { appId: const_1.AppID }
177
+ })
178
+ .json();
179
+ if (!uuidRes.uuid || !uuidRes.encryuuid) {
180
+ throw new Error('Failed to get QR code UUID');
181
+ }
182
+ return {
183
+ uuid: uuidRes.uuid,
184
+ encryuuid: uuidRes.encryuuid,
185
+ reqId: loginForm.reqId,
186
+ lt: loginForm.lt,
187
+ paramId: loginForm.paramId
188
+ };
189
+ }
190
+ /**
191
+ * Check QR code scan status
192
+ * @param qrData - QR code data from getQRCode
193
+ * @returns status and redirectUrl on success
194
+ */
195
+ async checkQRCodeStatus(qrData) {
196
+ const now = new Date();
197
+ const pad = (n, len = 2) => String(n).padStart(len, '0');
198
+ const date = `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())}` +
199
+ `${pad(now.getHours())}:${pad(now.getMinutes())}:${pad(now.getSeconds())}.${pad(now.getMilliseconds(), 3)}`;
200
+ return this.authRequest
201
+ .post(`${const_1.AUTH_URL}/api/logbox/oauth2/qrcodeLoginState.do`, {
202
+ headers: {
203
+ Referer: const_1.AUTH_URL,
204
+ Reqid: qrData.reqId,
205
+ lt: qrData.lt
206
+ },
207
+ form: {
208
+ appId: const_1.AppID,
209
+ clientType: const_1.ClientType,
210
+ returnUrl: const_1.ReturnURL,
211
+ paramId: qrData.paramId,
212
+ uuid: qrData.uuid,
213
+ encryuuid: qrData.encryuuid,
214
+ date,
215
+ timeStamp: Date.now()
216
+ }
217
+ })
218
+ .json();
219
+ }
220
+ /**
221
+ * QR code login with polling
222
+ * @param onQRReady - callback invoked with QR code URL for display
223
+ * @param options - polling interval and timeout
224
+ * @returns token session
225
+ */
226
+ async loginByQRCode(onQRReady, options) {
227
+ var _a, _b;
228
+ log_1.logger.debug('loginByQRCode...');
229
+ const pollInterval = (_a = options === null || options === void 0 ? void 0 : options.pollInterval) !== null && _a !== void 0 ? _a : 3000;
230
+ const timeout = (_b = options === null || options === void 0 ? void 0 : options.timeout) !== null && _b !== void 0 ? _b : 120000;
231
+ const qrData = await this.getQRCode();
232
+ onQRReady(qrData.uuid);
233
+ const deadline = Date.now() + timeout;
234
+ while (Date.now() < deadline) {
235
+ const res = await this.checkQRCodeStatus(qrData);
236
+ if (res.status === types_1.QRCodeStatus.SUCCESS) {
237
+ log_1.logger.debug('QR code login success, getting session...');
238
+ return await this.getSessionForPC({ redirectURL: res.redirectUrl });
239
+ }
240
+ if (res.status === types_1.QRCodeStatus.EXPIRED) {
241
+ throw new Error('QR code expired');
242
+ }
243
+ await new Promise((resolve) => setTimeout(resolve, pollInterval));
244
+ }
245
+ throw new Error('QR code login timeout');
246
+ }
247
+ }
248
+ exports.CloudAuthClient = CloudAuthClient;
249
+ _CloudAuthClient_builLoginForm = new WeakMap();
@@ -0,0 +1,165 @@
1
+ import { Got } from 'got';
2
+ import { UserSignResponse, UserSizeInfoResponse, FamilyListResponse, FamilyUserSignResponse, ConfigurationOptions, ClientSession, PageQuery, FileListResponse, RsaKey, UploadInitResponse, UploadCommitResponse, CreateFolderRequest, UploadCallbacks, RenameFolderRequest, CreateBatchTaskRequest, CreateFamilyBatchTaskRequest, CreateFamilyFolderRequest, RenameFamilyFolderRequest, CommitMultiFamilyUploadRequest, CommitMultiUploadRequest, initMultiUploadRequest, initMultiFamilyUploadRequest } from './types';
3
+ import { CloudAuthClient } from './CloudAuthClient';
4
+ import { Store } from './store';
5
+ /**
6
+ * 天翼网盘客户端
7
+ * @public
8
+ */
9
+ export declare class CloudClient {
10
+ #private;
11
+ username: string;
12
+ password: string;
13
+ ssonCookie: string;
14
+ tokenStore: Store;
15
+ readonly request: Got;
16
+ readonly authClient: CloudAuthClient;
17
+ readonly session: ClientSession;
18
+ private rsaKey;
19
+ private sessionKeyPromise;
20
+ private accessTokenPromise;
21
+ private generateRsaKeyPromise;
22
+ private onQRCodeReady?;
23
+ private qrLoginOptions?;
24
+ constructor(_options: ConfigurationOptions);
25
+ getSession(): Promise<import("./types").TokenSession>;
26
+ /**
27
+ * 获取 sessionKey
28
+ * @returns sessionKey
29
+ */
30
+ getSessionKey(): Promise<string>;
31
+ /**
32
+ * 获取 accessToken
33
+ * @returns accessToken
34
+ */
35
+ getAccessToken(): Promise<string>;
36
+ /**
37
+ * 获取 RSA key
38
+ * @returns RSAKey
39
+ */
40
+ generateRsaKey(): Promise<RsaKey>;
41
+ /**
42
+ * 获取用户网盘存储容量信息
43
+ * @returns 账号容量结果
44
+ */
45
+ getUserSizeInfo(): Promise<UserSizeInfoResponse>;
46
+ /**
47
+ * 个人签到任务
48
+ * @returns 签到结果
49
+ */
50
+ userSign(): Promise<UserSignResponse>;
51
+ /**
52
+ * 获取家庭信息
53
+ * @returns 家庭列表信息
54
+ */
55
+ getFamilyList(): Promise<FamilyListResponse>;
56
+ /**
57
+ * 家庭签到任务
58
+ * @param familyId - 家庭id
59
+ * @returns 签到结果
60
+ * @deprecated 已无效
61
+ */
62
+ familyUserSign(familyId: string): Promise<FamilyUserSignResponse>;
63
+ /**
64
+ * 获取文件列表
65
+ * @param pageQuery - 查询参数
66
+ * @returns
67
+ */
68
+ getListFiles(pageQuery?: PageQuery, familyId?: string): Promise<FileListResponse>;
69
+ /**
70
+ * 创建文件夹
71
+ * @param createFolderRequest - 创建文件夹请求
72
+ * @returns
73
+ */
74
+ createFolder(createFolderRequest: CreateFolderRequest | CreateFamilyFolderRequest): Promise<{
75
+ id: string;
76
+ name: string;
77
+ parentId: string;
78
+ }>;
79
+ /**
80
+ * 重命名文件夹
81
+ * @param renameFolderRequest - 重名文件夹请求
82
+ * @returns
83
+ */
84
+ renameFolder(renameFolderRequest: RenameFolderRequest | RenameFamilyFolderRequest): import("got/dist/source").CancelableRequest<unknown>;
85
+ /**
86
+ * 初始化上传
87
+ * @param initMultiUploadRequest - 初始化请求
88
+ * @returns
89
+ */
90
+ initMultiUpload(initMultiUploadRequest: initMultiUploadRequest | initMultiFamilyUploadRequest): Promise<UploadInitResponse>;
91
+ /**
92
+ * 提交上传
93
+ * @param commitMultiUploadRequest - 提交请求
94
+ * @returns
95
+ */
96
+ commitMultiUpload(commitMultiUploadRequest: CommitMultiUploadRequest | CommitMultiFamilyUploadRequest): import("got/dist/source").CancelableRequest<UploadCommitResponse>;
97
+ /**
98
+ * 检测秒传
99
+ * @param params - 检查参数
100
+ * @returns
101
+ */
102
+ checkTransSecond(params: {
103
+ fileMd5: string;
104
+ sliceMd5: string;
105
+ uploadFileId: string;
106
+ familyId?: number;
107
+ }): import("got/dist/source").CancelableRequest<UploadInitResponse>;
108
+ /**
109
+ * 文件上传
110
+ * @param param - 上传参数
111
+ * @param callbacks - 上传回调
112
+ * @returns
113
+ */
114
+ upload(param: {
115
+ parentFolderId: string;
116
+ filePath: string;
117
+ familyId?: string;
118
+ }, callbacks?: UploadCallbacks): Promise<{
119
+ fileDataExists: number;
120
+ file: {
121
+ userFileId: string;
122
+ fileName: string;
123
+ fileSize: number;
124
+ fileMd5: string;
125
+ createDate: string;
126
+ rev: number;
127
+ userId: number;
128
+ };
129
+ code: string;
130
+ }>;
131
+ /**
132
+ * 检测任务状态
133
+ * @param type - 任务类型
134
+ * @param taskId - 任务Id
135
+ * @param maxAttempts - 重试次数
136
+ * @param interval - 重试间隔
137
+ * @returns
138
+ */
139
+ checkTaskStatus(type: string, taskId: string, maxAttempts?: number, interval?: number): Promise<{
140
+ successedFileIdList?: number[];
141
+ taskId: string;
142
+ taskStatus: number;
143
+ }>;
144
+ /**
145
+ * 创建任务
146
+ * @param createBatchTaskRequest - 创建任务参数
147
+ * @returns
148
+ */
149
+ createBatchTask(createBatchTaskRequest: CreateBatchTaskRequest | CreateFamilyBatchTaskRequest): Promise<{
150
+ successedFileIdList?: number[];
151
+ taskId: string;
152
+ taskStatus: number;
153
+ }>;
154
+ /**
155
+ * 获取文件下载路径
156
+ * @param params - 文件参数
157
+ * @returns
158
+ */
159
+ getFileDownloadUrl(params: {
160
+ fileId: string;
161
+ familyId?: string;
162
+ }): import("got/dist/source").CancelableRequest<{
163
+ fileDownloadUrl: string;
164
+ }>;
165
+ }