• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1/*
2 * Copyright (c) 2023 Shenzhen Kaihong Digital Industry Development 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 from '@ohos.worker';
17import fs from '@ohos.file.fs';
18import { Logger, sleep } from '../common/Common';
19import { BusinessError } from '@ohos.base';
20
21const CONTENT = 'hello world';
22const TAG: string = '[ConcurrentModule].[MyWorker]';
23const FILE_NUM: number = 200; // 预制200 1m以下的小文件
24const FILE_NUMBER: number = 9; // 文件1-9命名时加上0
25const LIST_FILE_TWO: number = 2; // 显示拷贝成功后的第二个文件名
26const SLEEP_TIME: number = 100; // 睡眠时间
27
28let workerInstance: worker.ThreadWorker | null = null;
29let fileFlag: boolean = false;
30
31export default class MyFile {
32  public baseDir: string | undefined = '';
33  public filesCount: number = 0;
34  private flag: boolean = false;
35  public realFileNames: Array<string> = [];
36
37  constructor() {
38    this.baseDir = AppStorage.Get('sanBoxFileDir');
39  }
40
41  readyFileToFileFs(): void {
42    let fileFsDir = this.baseDir + '/fileFs';
43    try {
44      if (!fs.accessSync(fileFsDir)) {
45        fs.mkdirSync(fileFsDir);
46      }
47      Logger.info(TAG, 'readyFileToFileFs successful');
48    } catch (e) {
49      Logger.error(TAG, `readyFileToFileFs has failed for: {message: ${(e as BusinessError).message}, code: ${(e as BusinessError).code}}`);
50    }
51  }
52
53  // worker file
54  readyFilesToWorker(): void {
55    let content = CONTENT + CONTENT + new Date() + '\n';
56    let workerDir = this.baseDir + '/workerDir';
57
58    try {
59      if (!fs.accessSync(workerDir)) {
60        fs.mkdirSync(workerDir);
61      }
62      Logger.info(TAG, 'readyFilesToWorker dpath = ' + workerDir);
63      for (let i = 0; i < FILE_NUM; i++) {
64        let myFile = '';
65        if (i < FILE_NUMBER) {
66          myFile = workerDir + `/TestFile0${i + 1}.txt`;
67        } else {
68          myFile = workerDir + `/TestFile${i + 1}.txt`;
69        }
70        Logger.info(TAG, 'readyFilesToWorker myFile = ' + myFile);
71        let file = fs.openSync(myFile, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE);
72        fs.writeSync(file.fd, content);
73        fs.closeSync(file);
74      }
75      Logger.info(TAG, 'readyFilesToWorker successful');
76    } catch (e) {
77      Logger.error(TAG, `readyFilesToWorker has failed for: {message: ${(e as BusinessError).message}, code: ${(e as BusinessError).code}}`);
78    }
79  }
80
81  async workToCopyFiles(files: Array<string>, filePath: string): Promise<void> {
82    try {
83      Logger.info(TAG, 'WorkCreator start to create worker');
84      let destPath = filePath;
85      Logger.info(TAG, 'Workerets destPath ' + destPath);
86      if (!fs.accessSync(destPath)) {
87        fs.mkdirSync(destPath);
88      }
89      if (fs.accessSync(destPath)) {
90        fs.listFile(destPath).then((filenames) => {
91          Logger.info(TAG, 'listFile succeed');
92          for (let i = 0; i < filenames.length; i++) {
93            Logger.info(TAG, 'Workerets fileName: ' + filenames[i]);
94          }
95        }).catch((err: BusinessError) => {
96          Logger.info(TAG, 'list file failed with error message: ' + err.message + ', error code: ' + err.code);
97        });
98      }
99      if (files !== null) {
100        this.realFileNames.length = 0;
101        for (let i = 0; i < files.length; i++) {
102          if (files[i] === 'deletedTag') {
103            continue;
104          }
105          this.realFileNames.push(files[i]);
106        }
107      }
108      let count = this.realFileNames.length;
109      for (let j = 0; j < count; j++) {
110        Logger.info(TAG, 'workToCopyFiles this.realFileNames = ' + this.realFileNames[j]);
111      }
112      workerInstance = new worker.ThreadWorker('entry/ets/workers/WorkerCopy.ts');
113      if (this.realFileNames !== null) {
114        let srcPath = this.baseDir + '/workerDir';
115        workerInstance.postMessage({
116          srcDir: srcPath,
117          destDir: destPath,
118          fileNames: this.realFileNames
119        });
120      }
121
122      workerInstance.onexit = (code): void => {
123        Logger.info(TAG, `workerInstance::onexit has been exit ${code}`);
124      };
125      workerInstance.onerror = (err): void => {
126        Logger.info(TAG, `workerInstance::onerror has errors: ${JSON.stringify(err)}`);
127      };
128      workerInstance.onmessageerror = (event): void => {
129        Logger.info(TAG, `workerInstance::onmessageerror has errors: ${JSON.stringify(event)}`);
130      };
131      workerInstance.onmessage = (message): void => {
132        Logger.info(TAG, `workerInstance::onmessage receive data: ${JSON.stringify(message.data)}`);
133        if (message.data.hasOwnProperty('count')) {
134          Logger.info(TAG, `workerInstance::onmessage receive data length = ${message.data.count}`);
135          this.filesCount = message.data.count;
136          fileFlag = message.data.strFlag;
137          this.flag = true;
138          let fileName1: string | null = null;
139          let fileName2: string | null = null;
140          for (let i: number = 0; i < message.data.listFileNames.length; i++) {
141            Logger.info(TAG, `Worker workerInstance::onmessage receive listFileNames: ${message.data.listFileNames[i]}`);
142          }
143          if (message.data.listFileNames[0] !== undefined && message.data.listFileNames[1] !== undefined && message.data.listFileNames[LIST_FILE_TWO] === undefined) {
144            fileName1 = message.data.listFileNames[0] + '、';
145            fileName2 = message.data.listFileNames[1];
146          } else if (message.data.listFileNames[0] !== undefined && message.data.listFileNames[1] === undefined) {
147            fileName1 = message.data.listFileNames[0];
148            fileName2 = '';
149          } else {
150            fileName1 = message.data.listFileNames[0] + '、';
151            let copyFileLog: string | undefined = AppStorage.Get('copyFileLog5');
152            fileName2 = message.data.listFileNames[1] + copyFileLog;
153          }
154          AppStorage.SetOrCreate('fileListName1', fileName1);
155          AppStorage.SetOrCreate('fileListName2', fileName2);
156          let copyFileLog3: string | undefined = AppStorage.Get('copyFileLog3');
157          let copyFileLog4: string | undefined = AppStorage.Get('copyFileLog4');
158          let copyFileLog = '2、' + fileName1 + fileName2 + copyFileLog3 + 'copy' + copyFileLog4;
159          if (fileName1 !== 'undefined、') {
160            AppStorage.SetOrCreate('copyFileShowLog', copyFileLog);
161          } else {
162            AppStorage.SetOrCreate('copyFileShowLog', $r('app.string.workerLogChooseFile'));
163          }
164          Logger.info(TAG, `Worker workerInstance::onmessage receive count: ${JSON.stringify(this.filesCount)}`);
165        }
166        if (this.filesCount !== 0) {
167          AppStorage.SetOrCreate('fileNumber', JSON.stringify(this.filesCount));
168        } else {
169          AppStorage.SetOrCreate('fileNumber', '0');
170          AppStorage.SetOrCreate('fileListName1', '');
171          AppStorage.SetOrCreate('fileListName2', '');
172        }
173        Logger.info(TAG, 'workerInstance::onmessage Finish to process data from WorkerCopy.ts');
174        workerInstance?.terminate();
175      };
176      while (!fileFlag) {
177        await sleep(SLEEP_TIME);
178      }
179    } catch (e) {
180      Logger.error(TAG, `Worker WorkCreator error package: message: ${(e as BusinessError).message}, code: ${(e as BusinessError).code}`);
181    }
182  }
183
184  deleteCopyFile(filePath: string): void {
185    Logger.info(TAG, 'deleteCopyFile destCopyFilePath = ' + filePath);
186    try {
187      if (fs.accessSync(filePath)) {
188        let isDirectory = fs.statSync(filePath).isDirectory();
189        if (isDirectory) {
190          fs.rmdirSync(filePath);
191          fs.mkdirSync(filePath);
192        }
193      }
194    } catch (e) {
195      Logger.error(TAG, `delete workerCopyFile error package: message: ${(e as BusinessError).message}, code: ${(e as BusinessError).code}`);
196    }
197  }
198}