• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1/*
2 * Copyright (c) 2023 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 *     http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16import worker, { MessageEvents } from '@ohos.worker';
17import zlib from '@ohos.zlib';
18import request from '@ohos.request';
19import type common from '@ohos.app.ability.common';
20import Logger from '../../utils/Logger';
21
22let workerPort = worker.workerPort;
23
24workerPort.onmessage = (e: MessageEvents): void => {
25  Logger.info('workerPort onmessage start');
26  // worker线程向主线程发送信息
27  let context: common.UIAbilityContext = e.data.context;
28  // 获取设备本地路径
29  let filesDir: string = context.filesDir;
30  // 获取当前时间戳
31  let time: number = new Date().getTime();
32  // 初始化压缩文件的文件路径
33  let inFilePath: string = `${filesDir}/${time.toString()}.zip`;
34  // 初始化媒体下载路径
35  let mediaDataUrl: string = e.data.mediaData;
36  // 截取主要片段
37  let urlPart: string = mediaDataUrl.split('.')[1];
38  // 以'/'分割
39  let length: number = urlPart.split('/').length;
40  // 获取文件名称
41  let fileName: string = urlPart.split('/')[length - 1];
42  Logger.info(`fileName:${JSON.stringify(fileName)}`);
43  // 解压的配置参数
44  let options: zlib.Options = {
45    level: zlib.CompressLevel.COMPRESS_LEVEL_DEFAULT_COMPRESSION
46  };
47  // 对图片、视频的路径进行处理
48  Logger.info(`workerPort media filePath ${inFilePath}`);
49  // 执行下载操作
50  request.downloadFile(context, {
51    url: mediaDataUrl,
52    filePath: inFilePath
53
54  }).then((downloadTask) => {
55    downloadTask.on('progress', (receivedSize: number, totalSize: number) => {
56      Logger.info(`receivedSize:${receivedSize},totalSize:${totalSize}`);
57    });
58    downloadTask.on('complete', () => {
59      // 下载完成之后执行解压操作
60      zlib.decompressFile(inFilePath, filesDir, options).then(() => {
61        let videoPath: string = `${filesDir}/${fileName}.mp4`;
62        workerPort.postMessage({ isComplete: true, filePath: videoPath });
63        Logger.info('complete end');
64      });
65    });
66    downloadTask.on('fail', () => {
67      Logger.info('download fail');
68    });
69  }).catch((err) => {
70    Logger.info(`Invoke downloadTask failed, code is ${err.code}, message is ${err.message}`);
71  });
72};