@nger/fk-upload 1.0.8 → 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,66 @@
1
+ import { Injector } from '@nger/core';
2
+ import { RabbitMqService } from '@nger/rabbitmq';
3
+ import { Client } from '@nger/redis';
4
+ import { Db } from '@nger/typeorm';
5
+ import { Observable } from 'rxjs';
6
+ import { WsService } from '@nger/ws';
7
+ export interface DownloadTask {
8
+ filename: string;
9
+ path: string;
10
+ size: number;
11
+ url: string;
12
+ totalSize: number;
13
+ }
14
+ export interface UploadTask {
15
+ filename: string;
16
+ path: string;
17
+ uploadUrl: string;
18
+ start: number;
19
+ end: number;
20
+ total: number;
21
+ cookies: string;
22
+ aid: number;
23
+ folderId: number;
24
+ fileMd5: string;
25
+ index: number;
26
+ splitSize: number;
27
+ totalChunks: number;
28
+ complete: boolean;
29
+ topicId: number;
30
+ }
31
+ import { ScheduleService } from '@nger/schedule';
32
+ import { W7DataSource } from '@nger/w7';
33
+ export interface EffectTask {
34
+ filename: string;
35
+ uploadUrl: string;
36
+ topicId: number;
37
+ }
38
+ export interface ScheduleTask {
39
+ name: string;
40
+ rule: string;
41
+ }
42
+ export declare class TaskService {
43
+ private rabbit;
44
+ private redis;
45
+ private db;
46
+ private ws;
47
+ private schedule;
48
+ private w7;
49
+ private injector;
50
+ constructor(rabbit: RabbitMqService, redis: Client, db: Db, ws: WsService, schedule: ScheduleService, w7: W7DataSource, injector: Injector);
51
+ addDownloadTask(task: DownloadTask): Promise<void>;
52
+ addUploadTask(task: UploadTask): Promise<void>;
53
+ beginUploadTask(filename: string): Promise<void>;
54
+ addEffectTask(task: EffectTask): Promise<void>;
55
+ addScheduleTask(task: ScheduleTask): Promise<void>;
56
+ createDownLoadTask(url: string, fkLoginId: number, topicId: number): Promise<void>;
57
+ receiveScheduleTask(): Promise<void>;
58
+ receiveEffectTask(): Promise<void>;
59
+ receiveUploadTask(): Promise<void>;
60
+ receiveDownloadTask(): Promise<void>;
61
+ private getUploadInfourl;
62
+ private encodeURIComponent;
63
+ private getUploadUrl;
64
+ startUploadTask(filename: string): Promise<void>;
65
+ download(task: DownloadTask): Observable<DownloadTask>;
66
+ }
@@ -0,0 +1,451 @@
1
+ "use strict";
2
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
3
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
5
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
6
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
7
+ };
8
+ var __metadata = (this && this.__metadata) || function (k, v) {
9
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
10
+ };
11
+ var __importDefault = (this && this.__importDefault) || function (mod) {
12
+ return (mod && mod.__esModule) ? mod : { "default": mod };
13
+ };
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ exports.TaskService = void 0;
16
+ const core_1 = require("@nger/core");
17
+ const rabbitmq_1 = require("@nger/rabbitmq");
18
+ const redis_1 = require("@nger/redis");
19
+ const typeorm_1 = require("@nger/typeorm");
20
+ const fs_extra_1 = require("fs-extra");
21
+ const entities_1 = require("../entities");
22
+ const request_1 = require("request");
23
+ const rxjs_1 = require("rxjs");
24
+ const ws_1 = require("@nger/ws");
25
+ const md5_file_1 = __importDefault(require("md5-file"));
26
+ const typeorm_2 = require("typeorm");
27
+ const cids_1 = __importDefault(require("cids"));
28
+ const multihashing_async_1 = __importDefault(require("multihashing-async"));
29
+ const form_data_1 = __importDefault(require("form-data"));
30
+ const axios_1 = __importDefault(require("axios"));
31
+ const schedule_1 = require("@nger/schedule");
32
+ const w7_1 = require("@nger/w7");
33
+ const path_1 = require("path");
34
+ let TaskService = class TaskService {
35
+ rabbit;
36
+ redis;
37
+ db;
38
+ ws;
39
+ schedule;
40
+ w7;
41
+ injector;
42
+ constructor(rabbit, redis, db, ws, schedule, w7, injector) {
43
+ this.rabbit = rabbit;
44
+ this.redis = redis;
45
+ this.db = db;
46
+ this.ws = ws;
47
+ this.schedule = schedule;
48
+ this.w7 = w7;
49
+ this.injector = injector;
50
+ }
51
+ async addDownloadTask(task) {
52
+ const content = Buffer.from(JSON.stringify(task));
53
+ await this.rabbit.send('@nger/fk-upload/download-task', content);
54
+ }
55
+ async addUploadTask(task) {
56
+ const content = Buffer.from(JSON.stringify(task));
57
+ await this.rabbit.send('@nger/fk-upload/upload-task', content);
58
+ }
59
+ async beginUploadTask(filename) {
60
+ this.redis.set(filename, `0`);
61
+ }
62
+ async addEffectTask(task) {
63
+ const content = Buffer.from(JSON.stringify(task));
64
+ await this.rabbit.send('@nger/fk-upload/effect-task', content);
65
+ }
66
+ async addScheduleTask(task) {
67
+ const content = Buffer.from(JSON.stringify(task));
68
+ await this.rabbit.send('@nger/fk-upload/schedule-task', content);
69
+ }
70
+ async createDownLoadTask(url, fkLoginId, topicId) {
71
+ const hash = await (0, multihashing_async_1.default)(Buffer.from(url), 'sha1', 16);
72
+ const cid = new cids_1.default(1, 'raw', hash, 'base64');
73
+ const filename = cid.toString('base64');
74
+ const _url = new URL(url);
75
+ const filePath = _url.pathname;
76
+ const ext = (0, path_1.extname)(filePath);
77
+ const task = new entities_1.FkDownloadTaskEntity();
78
+ const root = this.injector.get(core_1.APP_ROOT);
79
+ (0, fs_extra_1.ensureDirSync)((0, path_1.join)(root, 'attachments/fk-upload'));
80
+ const path = (0, path_1.join)(root, 'attachments/fk-upload', encodeURIComponent(filename));
81
+ task.filename = filename + ext;
82
+ task.url = url;
83
+ task.loginId = fkLoginId;
84
+ task.totalSize = 0;
85
+ task.path = path;
86
+ task.status = 0;
87
+ task.size = 0;
88
+ task.topicId = topicId;
89
+ await this.db.manager.save(task);
90
+ return this.addDownloadTask(task);
91
+ }
92
+ async receiveScheduleTask() {
93
+ const obs = await this.rabbit.receive(`@nger/fk-upload/schedule-task`);
94
+ obs.subscribe({
95
+ next: ([data, complete, fail]) => {
96
+ const task = JSON.parse(data);
97
+ this.redis.get(`setting`, (err, reply) => {
98
+ if (err) {
99
+ fail();
100
+ }
101
+ else {
102
+ if (reply) {
103
+ const setting = JSON.parse(reply);
104
+ if (task.name === setting.name) {
105
+ this.schedule.scheduleJob(task.name, task.rule, async (time) => {
106
+ const accounts = await this.db.manager.find(entities_1.FkLoginEntity, {});
107
+ const w7Usernames = accounts.map(account => account.w7Username);
108
+ const users = await this.w7.manager.find(w7_1.W7UsersEntity, { where: { username: (0, typeorm_2.In)(w7Usernames) } });
109
+ const uids = users.map(user => user.uid);
110
+ const uniAccounts = await this.w7.manager.find(w7_1.W7UniAccountEntity, { where: { createUid: (0, typeorm_2.In)(uids) } });
111
+ const uniacids = uniAccounts.map(a => a.uniacid);
112
+ const tasks = await this.db.manager.find(entities_1.FkDownloadTaskEntity, { select: ['topicId'] });
113
+ const ids = tasks.map(task => task.topicId);
114
+ const topics = await this.w7.manager.find(w7_1.W7ChatTopicEntity, { where: { uniacid: (0, typeorm_2.In)(uniacids), id: (0, typeorm_2.Not)((0, typeorm_2.In)(ids)) } });
115
+ topics.map(topic => {
116
+ if (topic.thirdUrl) {
117
+ const uniacid = topic.uniacid;
118
+ const account = uniAccounts.find(a => a.uniacid === uniacid);
119
+ const user = users.find(u => u.uid === account.createUid);
120
+ const login = accounts.find(a => a.w7Username === user.username);
121
+ this.createDownLoadTask(topic.thirdUrl, login.fkLoginId, topic.id);
122
+ }
123
+ });
124
+ });
125
+ }
126
+ else {
127
+ complete();
128
+ }
129
+ }
130
+ else {
131
+ complete();
132
+ }
133
+ }
134
+ });
135
+ }
136
+ });
137
+ }
138
+ async receiveEffectTask() {
139
+ const obs = await this.rabbit.receive(`@nger/fk-upload/effect-task`);
140
+ obs.subscribe({
141
+ next: async ([data, complete, fail]) => {
142
+ const task = JSON.parse(data);
143
+ if (task.topicId) {
144
+ this.w7.manager.update(w7_1.W7ChatTopicEntity, task.topicId, { thirdUrl: task.uploadUrl }).then(() => complete()).catch(() => fail());
145
+ }
146
+ else {
147
+ complete();
148
+ }
149
+ }
150
+ });
151
+ }
152
+ async receiveUploadTask() {
153
+ const obs = await this.rabbit.receive(`@nger/fk-upload/upload-task`);
154
+ obs.subscribe({
155
+ next: async ([data, complete, fail]) => {
156
+ const task = JSON.parse(data);
157
+ this.redis.get(task.filename, async (err, reply) => {
158
+ if (err)
159
+ return fail();
160
+ if (reply) {
161
+ const taskIndex = Number(reply); // next
162
+ const isComplete = task.complete && task.index === taskIndex;
163
+ const isShouldRunning = isComplete || (!isComplete && task.index == taskIndex);
164
+ if (isShouldRunning) {
165
+ // should handler
166
+ const fileStream = (0, fs_extra_1.createReadStream)(task.path, { start: task.start, end: task.end });
167
+ const formdata = new form_data_1.default();
168
+ formdata.append('ctrl', fileStream);
169
+ formdata.append('isFreeVer', 'false');
170
+ formdata.append('aid', `${task.aid}`);
171
+ formdata.append('folderId', `${task.folderId}`);
172
+ formdata.append('fileName', task.filename);
173
+ formdata.append(`totalSize`, `${task.total}`);
174
+ formdata.append(`fileMd5`, task.fileMd5);
175
+ formdata.append('index', `${task.index}`);
176
+ formdata.append('chunkSize', `${task.splitSize}`);
177
+ formdata.append('totalChunks', `${task.totalChunks}`);
178
+ formdata.append(`complete`, `${task.complete}`);
179
+ const bssInfo = {
180
+ fromSite: true, siteId: 0, groupId: 0, fileSizeLimit: 1024
181
+ };
182
+ formdata.append('bssInfo', JSON.stringify(bssInfo));
183
+ const headers = formdata.getHeaders();
184
+ const uploadResult = await axios_1.default.post(task.uploadUrl, formdata, {
185
+ headers: {
186
+ ...headers,
187
+ Cookie: task.cookies
188
+ }
189
+ }).then(res => res.data);
190
+ if (uploadResult.code === 200) {
191
+ const data = uploadResult.data;
192
+ this.ws.send({
193
+ action: `@nger/fk-upload/uploading`,
194
+ data: {
195
+ uploadSize: task.end,
196
+ filename: task.filename,
197
+ total: task.total
198
+ }
199
+ });
200
+ this.redis.set(task.filename, `${task.index + 1}`);
201
+ if (data) {
202
+ const downUrl = data.downUrl;
203
+ if (downUrl) {
204
+ this.redis.del(task.filename);
205
+ this.ws.send({
206
+ action: `@nger/fk-upload/uploading`,
207
+ data: {
208
+ uploadSize: task.end,
209
+ filename: task.filename,
210
+ total: task.total,
211
+ uploadUrl: `https://` + downUrl
212
+ }
213
+ });
214
+ this.addEffectTask({
215
+ filename: task.filename,
216
+ uploadUrl: `https://` + downUrl,
217
+ topicId: task.topicId
218
+ });
219
+ this.db.manager.update(entities_1.FkDownloadTaskEntity, task.filename, {
220
+ status: 2,
221
+ uploadUrl: `https://` + downUrl,
222
+ uploadSize: task.total
223
+ }).then(() => complete()).catch(() => fail());
224
+ }
225
+ else {
226
+ this.db.manager.update(entities_1.FkDownloadTaskEntity, task.filename, {
227
+ uploadSize: task.end
228
+ }).then(() => complete()).catch(() => fail());
229
+ }
230
+ }
231
+ else {
232
+ fail();
233
+ }
234
+ }
235
+ else {
236
+ fail();
237
+ }
238
+ }
239
+ else {
240
+ fail();
241
+ }
242
+ }
243
+ else {
244
+ return complete();
245
+ }
246
+ });
247
+ }
248
+ });
249
+ }
250
+ async receiveDownloadTask() {
251
+ const obs = await this.rabbit.receive(`@nger/fk-upload/download-task`);
252
+ obs.subscribe({
253
+ next: async ([data, complete, fail]) => {
254
+ const task = JSON.parse(data);
255
+ const download = await this.db.manager.findOne(entities_1.FkDownloadTaskEntity, { where: { filename: task.filename } });
256
+ if (download) {
257
+ let total = 0;
258
+ download.url = decodeURIComponent(download.url);
259
+ this.download(download).pipe((0, rxjs_1.throttleTime)(1000), (0, rxjs_1.switchMap)(async (res) => {
260
+ const size = res.size;
261
+ total = res.totalSize;
262
+ this.ws.send({
263
+ action: `@nger/fk-upload/downloading`,
264
+ data: { total, size, filename: res.filename }
265
+ });
266
+ await this.db.manager.update(entities_1.FkDownloadTaskEntity, download.filename, { size: size, totalSize: total });
267
+ return res;
268
+ })).subscribe({
269
+ next: (task) => { },
270
+ complete: async () => {
271
+ const md5 = await (0, md5_file_1.default)(task.path);
272
+ this.db.manager.update(entities_1.FkDownloadTaskEntity, download.filename, { status: 1, size: total, fileMd5: md5 }).then(async () => {
273
+ this.ws.send({
274
+ action: `@nger/fk-upload/downloading`,
275
+ data: { total, size: total, filename: download.filename }
276
+ });
277
+ this.redis.del(task.filename);
278
+ await this.startUploadTask(task.filename);
279
+ complete();
280
+ }).catch(() => fail());
281
+ },
282
+ error: () => {
283
+ fail();
284
+ }
285
+ });
286
+ }
287
+ }
288
+ });
289
+ }
290
+ getUploadInfourl(token) {
291
+ return `https://${token.url}/${token.visitType}/${token.app}/advance/info?cmd=${token.cmd}&token=${token.token}`;
292
+ }
293
+ encodeURIComponent(data) {
294
+ return Object.keys(data).map(key => {
295
+ const value = Reflect.get(data, key);
296
+ return `${key}=${encodeURIComponent(value)}`;
297
+ }).join('&');
298
+ }
299
+ getUploadUrl(token, forceDirect = true) {
300
+ if (forceDirect) {
301
+ return `https://${token.url}/${token.visitType}/${token.app}/upload?cmd=${token.cmd}&token=${token.token}`;
302
+ }
303
+ else {
304
+ return `https://${token.url}/${token.visitType}/${token.app}/advance?cmd=${token.cmd}&token=${token.token}`;
305
+ }
306
+ }
307
+ async startUploadTask(filename) {
308
+ const task = await this.db.manager.findOne(entities_1.FkDownloadTaskEntity, { where: { filename } });
309
+ if (task && task.status === 1) {
310
+ const loginEntity = await this.db.manager.findOne(entities_1.FkLoginEntity, { where: { fkLoginId: task.loginId } });
311
+ const cookies = await this.db.manager.find(entities_1.FkLoginCookieEntity, { where: { fkLoginId: task.loginId } });
312
+ const cookie = cookies.map(cookie => `${cookie.key}=${cookie.value}`).join(';');
313
+ // 00 take token
314
+ const url = `https://i.vip.webportal.top/`;
315
+ const iVipWebPortal = await axios_1.default.get(url, {
316
+ headers: {
317
+ Cookie: cookie
318
+ }
319
+ }).then(res => res.data);
320
+ const items = iVipWebPortal.match(/<meta id='_TOKEN' value='(.*?)'\/>/);
321
+ let token = ``;
322
+ if (items && items.length === 2) {
323
+ token = items[1];
324
+ }
325
+ if (token.length > 0) {
326
+ // 01
327
+ const url = `https://smr00.vip.webportal.top/cn/api/manage/advanceUpload/genAccessKey?_v=1651232099799&_TOKEN=${token}`;
328
+ const accessKey = await axios_1.default.get(url).then(res => res.data);
329
+ if (accessKey.success) {
330
+ const accessTokenString = decode(accessKey.accessKey);
331
+ if (accessTokenString) {
332
+ const accessToken = JSON.parse(accessTokenString);
333
+ const uploadInfoUrl = this.getUploadInfourl(accessToken);
334
+ const bssInfo = {
335
+ fromSite: true, siteId: 0, groupId: 0, fileSizeLimit: 1024
336
+ };
337
+ const info = await axios_1.default.post(uploadInfoUrl, this.encodeURIComponent({
338
+ fileMd5: task.fileMd5,
339
+ fileSize: task.totalSize,
340
+ isFreeVer: false,
341
+ aid: loginEntity.aid,
342
+ folderId: loginEntity.uploadGroupId,
343
+ bssInfo: JSON.stringify(bssInfo),
344
+ fileName: task.filename
345
+ }), { headers: { cookie: cookie } }).then(res => res.data);
346
+ if (info.code === 200) {
347
+ const data = info.data;
348
+ const { delayTime, splitSize, uploadedSize } = data;
349
+ const uploadUrl = this.getUploadUrl(accessToken, false);
350
+ const totalChunks = Math.ceil((task.totalSize) / splitSize);
351
+ let start = 0;
352
+ let index = 0;
353
+ let complete = false;
354
+ this.beginUploadTask(task.filename);
355
+ do {
356
+ const maxEndSize = start + splitSize;
357
+ if (index >= totalChunks - 1 || maxEndSize >= task.totalSize) {
358
+ complete = true;
359
+ }
360
+ const endSize = maxEndSize > task.totalSize ? task.totalSize : maxEndSize;
361
+ await this.addUploadTask({
362
+ filename: task.filename,
363
+ path: task.path,
364
+ uploadUrl: uploadUrl,
365
+ cookies: cookie,
366
+ aid: loginEntity?.aid || 0,
367
+ folderId: loginEntity?.uploadGroupId || 0,
368
+ start,
369
+ end: endSize,
370
+ total: task.totalSize,
371
+ index,
372
+ fileMd5: task.fileMd5,
373
+ totalChunks: totalChunks,
374
+ splitSize,
375
+ complete,
376
+ topicId: task.topicId
377
+ });
378
+ index = index + 1;
379
+ start = endSize;
380
+ } while (!complete);
381
+ }
382
+ }
383
+ }
384
+ }
385
+ }
386
+ }
387
+ download(task) {
388
+ console.log(`download ${task.url}`);
389
+ return new rxjs_1.Observable((sub) => {
390
+ // go on
391
+ task.size = 0;
392
+ let length = task.size;
393
+ const writeStream = (0, fs_extra_1.createWriteStream)(task.path, { start: task.size });
394
+ const req = (0, request_1.get)(task.url, {
395
+ headers: {
396
+ 'Content-Type': 'application/octet-stream'
397
+ }
398
+ });
399
+ req.on('data', (buf) => {
400
+ length = length + buf.length;
401
+ task.size = length;
402
+ writeStream.write(buf, (err) => {
403
+ if (err)
404
+ sub.error(err);
405
+ });
406
+ sub.next(task);
407
+ });
408
+ req.on('end', () => {
409
+ sub.complete();
410
+ writeStream.end();
411
+ });
412
+ req.on('response', (resp) => {
413
+ const headers = resp.headers;
414
+ task.totalSize = Number(Reflect.get(headers, 'content-length'));
415
+ sub.next(task);
416
+ });
417
+ });
418
+ }
419
+ };
420
+ TaskService = __decorate([
421
+ (0, core_1.Injectable)(),
422
+ __metadata("design:paramtypes", [rabbitmq_1.RabbitMqService,
423
+ redis_1.Client,
424
+ typeorm_1.Db,
425
+ ws_1.WsService,
426
+ schedule_1.ScheduleService,
427
+ w7_1.W7DataSource,
428
+ core_1.Injector])
429
+ ], TaskService);
430
+ exports.TaskService = TaskService;
431
+ function decode(base64Str) {
432
+ if (!base64Str)
433
+ return;
434
+ const t = base64Str.replace(/_/g, "/").replace(/-/g, "+");
435
+ const f = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
436
+ let l = 0;
437
+ let p = 0;
438
+ let h = [];
439
+ do {
440
+ const o = f.indexOf(t.charAt(l++));
441
+ const u = f.indexOf(t.charAt(l++));
442
+ const a = f.indexOf(t.charAt(l++));
443
+ const c = f.indexOf(t.charAt(l++));
444
+ const s = o << 18 | u << 12 | a << 6 | c;
445
+ const e = s >> 16 & 255;
446
+ const r = s >> 8 & 255;
447
+ const n = 255 & s;
448
+ h[p++] = 64 === a ? String.fromCharCode(e) : 64 === c ? String.fromCharCode(e, r) : String.fromCharCode(e, r, n);
449
+ } while (l < t.length);
450
+ return h.join('');
451
+ }
@@ -1,20 +1,12 @@
1
- import { FkDownloadTaskEntity } from '../entities';
2
1
  import { Db } from '@nger/typeorm';
3
- import { Observable } from 'rxjs';
4
2
  import { Injector } from '@nger/core';
3
+ import { WsService } from '@nger/ws';
4
+ import { TaskService } from './task.service';
5
5
  export declare class UploadService {
6
6
  private db;
7
7
  private injector;
8
+ get ws(): WsService;
9
+ get task(): TaskService;
8
10
  constructor(db: Db, injector: Injector);
9
- createDownLoadTask(url: string, fkLoginId: number): Promise<import("rxjs").Subscription>;
10
- getUploadUrl(token: any, forceDirect?: boolean): string;
11
- getUploadInfourl(token: any): string;
12
- encodeURIComponent(data: any): string;
13
- createUplaodTask(filename: string): Promise<{
14
- msg: string;
15
- } | undefined>;
16
- createObservable(url: string): Promise<{
17
- listen: Observable<FkDownloadTaskEntity>;
18
- filename: string;
19
- }>;
11
+ continueTask(filename: string): Promise<void>;
20
12
  }