• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1/*
2 * Copyright (c) 2024 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 { common } from '@kit.AbilityKit';
17import { hilog } from '@kit.PerformanceAnalysisKit';
18import { preferences } from '@kit.ArkData';
19import { promptAction } from '@kit.ArkUI';
20import { zlib } from '@kit.BasicServicesKit';
21import fileio from '@ohos.fileio';
22import { AddDialog } from '../common/AddDialog';
23import { ZipLibSource } from '../model/DataSource';
24import { router } from '@kit.ArkUI';
25
26const DOMAIN = 0xF811;
27const BUNDLE = 'ZipLib_';
28const TAG: string = '[ZipLibDecompressionPage]';
29let fileList: preferences.Preferences;
30
31@Entry
32@Component
33struct ZipLibDecompressionPage {
34  @State isInserted: boolean = false;
35  @State files: ZipLibSource = new ZipLibSource([]);
36  @State fileName: string = '';
37  @State fileContent: string = '';
38  private path: string = '';
39  private title: Resource = $r('app.string.MainAbility_label');
40  private dialogController: CustomDialogController = new CustomDialogController({
41    builder: AddDialog({
42      fileName: this.fileName,
43      fileContent: this.fileContent,
44      isInserted: this.isInserted,
45      createFile: async (isInserted: boolean, fileName: string, fileContent: string) => {
46        hilog.info(DOMAIN, TAG, BUNDLE + `enter the createFile`);
47        this.fileName = `${fileName}.txt`;
48        let isDuplication = this.files.fileData.includes(this.fileName);
49        hilog.info(DOMAIN, TAG, BUNDLE + `isInserted = ${isInserted}  isDuplication = ${isDuplication}`);
50        if (!isInserted || isDuplication) {
51          return;
52        }
53        let fd = fileio.openSync(`${this.path}/${this.fileName}`, 0o100 | 0o2, 0o666);
54        let number = fileio.writeSync(fd, fileContent);
55        hilog.info(DOMAIN, TAG, BUNDLE + `fd = ${fd} number = ${number}`);
56        this.files.pushData(this.fileName);
57        hilog.info(DOMAIN, TAG, BUNDLE + `this.files = ${JSON.stringify(this.files.fileData)}`);
58        await fileList.put('fileName', JSON.stringify(this.files.fileData));
59        await fileList.flush();
60      }
61    }),
62    autoCancel: true,
63    alignment: DialogAlignment.Default
64  })
65
66  async aboutToAppear() {
67    fileList = await preferences.getPreferences(getContext(this), 'fileList');
68    let ctx = getContext(this) as common.Context;
69    this.path = ctx.filesDir;
70    let value = await fileList.get('fileName', '');
71    this.files.fileData = JSON.parse(`${value}`);
72    this.files.notifyDataReload();
73  }
74
75  async zipHandler(path: string, fileName: string): Promise<void> {
76    let zipFile = `${path}/${fileName}`;
77    hilog.debug(DOMAIN, TAG, BUNDLE + `zipFile = ${zipFile}`);
78    let tempName = fileName.split('.');
79    let newName = `${tempName[0]}.zip`;
80    let zipOutFile = `${this.path}/${newName}`;
81    hilog.debug(DOMAIN, TAG, BUNDLE + `zipOutFile = ${zipOutFile}`);
82
83    let options: zlib.Options = {
84      level: zlib.CompressLevel.COMPRESS_LEVEL_DEFAULT_COMPRESSION,
85      memLevel: zlib.MemLevel.MEM_LEVEL_DEFAULT,
86      strategy: zlib.CompressStrategy.COMPRESS_STRATEGY_DEFAULT_STRATEGY
87    }
88    if (this.files.fileData.includes(newName)) {
89      promptAction.showToast({
90        message: $r('app.string.warning_failed'),
91        bottom: '11%'
92      });
93      return;
94    }
95    try {
96      zlib.compressFile(zipFile, zipOutFile, options).then(data => {
97        hilog.info(DOMAIN, TAG, BUNDLE + `data = ${JSON.stringify(data)}`);
98        promptAction.showToast({
99          message: $r('app.string.tip_complete'),
100          bottom: '11%'
101        });
102        this.files.pushData(`${newName}`);
103      })
104    } catch {
105      promptAction.showToast({
106        message: $r('app.string.warning_failure'),
107        bottom: '11%'
108      });
109    }
110    await fileList.put('fileName', JSON.stringify(this.files.fileData));
111    await fileList.flush();
112  }
113
114  async unzipHandler(path: string, fileName: string): Promise<void> {
115    let zipFile = `${path}/${fileName}`;
116    hilog.info(DOMAIN, TAG, BUNDLE + `zipFile = ${zipFile}`);
117    let tempName = fileName.split('.');
118    let newName = tempName[0];
119    let zipOutFile = `${this.path}/${newName}`;
120    hilog.info(DOMAIN, TAG, BUNDLE + `zipOutFile = ${zipOutFile}`);
121    if (this.files.fileData.includes(newName)) {
122      promptAction.showToast({
123        message: $r('app.string.warning_failed'),
124        bottom: '11%'
125      });
126      return;
127    }
128    let options: zlib.Options = {
129      level: zlib.CompressLevel.COMPRESS_LEVEL_DEFAULT_COMPRESSION,
130      memLevel: zlib.MemLevel.MEM_LEVEL_DEFAULT,
131      strategy: zlib.CompressStrategy.COMPRESS_STRATEGY_DEFAULT_STRATEGY
132    }
133
134    zlib.decompressFile(zipFile, zipOutFile, options).then(data => {
135      hilog.info(DOMAIN, TAG, BUNDLE + `data = ${JSON.stringify(data)}`);
136    })
137    promptAction.showToast({
138      message: $r('app.string.tip_complete'),
139      bottom: '11%'
140    });
141    this.files.pushData(`${newName}`);
142    await fileList.put('fileName', JSON.stringify(this.files.fileData));
143    await fileList.flush();
144  }
145
146  build() {
147    Flex({ direction: FlexDirection.Column, justifyContent: FlexAlign.Start, alignItems: ItemAlign.Center }) {
148      Column() {
149        Row() {
150          Row() {
151            Image($r('app.media.icon_back'))
152              .size({ height: '71%' })
153              .objectFit(ImageFit.Contain)
154              .onClick(() => {
155                router.pushUrl({
156                  url: 'pages/Index'
157                });
158              })
159            Text(this.title)
160              .fontSize(20)
161              .margin({ left: 8 })
162              .fontWeight(FontWeight.Bold)
163          }
164
165          Image($r('app.media.add'))
166            .size({ height: '71%' })
167            .id('addFileBtn')
168            .objectFit(ImageFit.Contain)
169            .onClick(() => {
170              this.dialogController.open();
171            })
172        }
173        .justifyContent(FlexAlign.SpaceBetween)
174        .width('91%')
175        .height('7.8%')
176        .backgroundColor($r('app.color.backGrounding'))
177
178        Flex({ direction: FlexDirection.Column, justifyContent: FlexAlign.Start, alignItems: ItemAlign.Center }) {
179          List({ initialIndex: 0 }) {
180            LazyForEach(this.files, (item: string, index: number) => {
181              ListItem() {
182                Row() {
183                  Row() {
184                    Image(item.includes('.zip') ? $r('app.media.zip') : $r('app.media.file'))
185                      .size({ height: '66.7%' })
186                      .objectFit(ImageFit.Contain)
187                    Column() {
188                      Text(item)
189                        .width('50%')
190                        .fontSize(16)
191                        .margin({ left: 16 })
192                    }
193                  }
194
195                  Row() {
196                    Button(item.includes('.zip') ? $r('app.string.unzip') : $r('app.string.zip'))
197                      .fontSize(12)
198                      .fontFamily('HarmonyHeiTi')
199                      .fontWeight(500)
200                      .fontColor($r('app.color.text_white_color'))
201                      .width('100%')
202                      .height('100%')
203                      .onClick(() => {
204                        item.includes('.zip') ? this.unzipHandler(this.path, item) : this.zipHandler(this.path, item);
205                      })
206                      .id('compress_' + index)
207                      .borderRadius(14)
208                      .backgroundColor($r('app.color.button_color'))
209                  }
210                  .width('22%')
211                  .height('50%')
212                }
213                .justifyContent(FlexAlign.SpaceBetween)
214                .padding({ right: 12, left: 12 })
215                .width('100%')
216                .height('14.2%')
217                .borderRadius(20)
218                .backgroundColor($r('app.color.start_window_background'))
219              }
220              .margin({ bottom: 12 })
221            }, (item: string) => item)
222          }
223          .margin({ top: 8 })
224          .height('68.7%')
225          .width('91%')
226          .backgroundColor($r('app.color.index_bg'))
227        }
228        .height('100%')
229        .width('100%')
230      }
231      .height('100%')
232      .width('100%')
233      .backgroundColor($r('app.color.index_bg'))
234    }
235  }
236}
237