diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..f1cd7627dbf124dde6caa78a70e6ac308a0e4c03 --- /dev/null +++ b/.gitignore @@ -0,0 +1,13 @@ +/node_modules +/oh_modules +/local.properties +/oh-package-lock.json5 +/.idea +**/build +/.hvigor +.cxx +/.clangd +/.clang-format +/.clang-tidy +**/.test +/.appanalyzer \ No newline at end of file diff --git a/AppScope/app.json5 b/AppScope/app.json5 new file mode 100644 index 0000000000000000000000000000000000000000..718e1e8082d31b48d561daca7b8ef7431695c54e --- /dev/null +++ b/AppScope/app.json5 @@ -0,0 +1,10 @@ +{ + "app": { + "bundleName": "com.example.rcpfiletransfer", + "vendor": "example", + "versionCode": 1000000, + "versionName": "1.0.0", + "icon": "$media:app_icon", + "label": "$string:app_name" + } +} diff --git a/AppScope/resources/base/element/string.json b/AppScope/resources/base/element/string.json new file mode 100644 index 0000000000000000000000000000000000000000..bc2c433cf5f6969f072e2cb410864c64583969fe --- /dev/null +++ b/AppScope/resources/base/element/string.json @@ -0,0 +1,8 @@ +{ + "string": [ + { + "name": "app_name", + "value": "RcpFileTransfer" + } + ] +} diff --git a/AppScope/resources/base/media/app_icon.png b/AppScope/resources/base/media/app_icon.png new file mode 100644 index 0000000000000000000000000000000000000000..a39445dc87828b76fed6d2ec470dd455c45319e3 Binary files /dev/null and b/AppScope/resources/base/media/app_icon.png differ diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..338e5b0bc22082e0ffcc7121c2ed3897a3ddccb0 --- /dev/null +++ b/LICENSE @@ -0,0 +1,78 @@ + Copyright (c) 2024 Huawei Device Co., Ltd. All rights reserved. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +Apache License, Version 2.0 +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + +"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. + +"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. + +"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. + +"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. + +"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. + +"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. + +"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). + +"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. + +"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." + +"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. + +2. Grant of Copyright License. + +Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. + +Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. + +4. Redistribution. + +You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: +1.You must give any other recipients of the Work or Derivative Works a copy of this License; and +2.You must cause any modified files to carry prominent notices stating that You changed the files; and +3.You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and +4.If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. + +You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. + +5. Submission of Contributions. + +Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. + +6. Trademarks. + +This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. + +Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. + +In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. + +While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS \ No newline at end of file diff --git a/README.en.md b/README.en.md deleted file mode 100644 index f3b134a60952cca54f5476cc97af92f3a14fdaf3..0000000000000000000000000000000000000000 --- a/README.en.md +++ /dev/null @@ -1,36 +0,0 @@ -# RcpFileTransfer - -#### Description -{**When you're done, you can delete the content in this README and update the file with details for others getting started with your repository**} - -#### Software Architecture -Software architecture description - -#### Installation - -1. xxxx -2. xxxx -3. xxxx - -#### Instructions - -1. xxxx -2. xxxx -3. xxxx - -#### Contribution - -1. Fork the repository -2. Create Feat_xxx branch -3. Commit your code -4. Create Pull Request - - -#### Gitee Feature - -1. You can use Readme\_XXX.md to support different languages, such as Readme\_en.md, Readme\_zh.md -2. Gitee blog [blog.gitee.com](https://blog.gitee.com) -3. Explore open source project [https://gitee.com/explore](https://gitee.com/explore) -4. The most valuable open source project [GVP](https://gitee.com/gvp) -5. The manual of Gitee [https://gitee.com/help](https://gitee.com/help) -6. The most popular members [https://gitee.com/gitee-stars/](https://gitee.com/gitee-stars/) diff --git a/README.md b/README.md index 85b1bce0c71080d3a300b2ef68118202933a0e79..87560bf0b4322f1c90686843658c0cebb3baf32d 100644 --- a/README.md +++ b/README.md @@ -1,39 +1,71 @@ -# RcpFileTransfer +## 基于RCP实现文件上传下载功能 -#### 介绍 -{**以下是 Gitee 平台说明,您可以替换此简介** -Gitee 是 OSCHINA 推出的基于 Git 的代码托管平台(同时支持 SVN)。专为开发者提供稳定、高效、安全的云端软件开发协作平台 -无论是个人、团队、或是企业,都能够用 Gitee 实现代码托管、项目管理、协作开发。企业项目请看 [https://gitee.com/enterprises](https://gitee.com/enterprises)} +### 介绍 -#### 软件架构 -软件架构说明 +本示例基于Remote Communication Kit远场通信服务,使用post、fetch、downloadToFile等方法实现相册的文件上传下载、文件分片下载、断点续传、后台文件上传下载功能。为开发者提供基于RCP上传下载各种场景的开发指导。 +### 效果预览 -#### 安装教程 +![](./screenshots/devices/home.png) -1. xxxx -2. xxxx -3. xxxx +使用说明: +1. 相册图片上传与下载:页面展示文件服务器中的图片列表,选中某个文件,点击下载,下载成功后在相册查看。点击上传拉起相册,选择图片后上传,上传成功更新列表。 +2. 文件断点续传:选中某个文件,点击下载,按钮变为暂停,再点击下载开始继续下载。 +3. 其他页面交互逻辑与1相同。 -#### 使用说明 +### 工程目录 -1. xxxx -2. xxxx -3. xxxx +``` +├──entry/src/main/ets/ +│ ├──components +│ │ ├──CustomList.ets // 自定义列表组件 +│ │ ├──ProgressButton.ets // 带进度显示的按钮组件 +│ │ └──SelectionList.ets // 选择列表组件 +│ ├──entryability +│ │ └──EntryAbility.ets // 程序入口类 +│ ├──constants +│ │ └──Constants.ets // 常量文件 +│ ├──pages +│ │ ├──AlbumImageTrasfer.ets // 相册图片上传下载页面 +│ │ ├──BackgroundFileTransfer.ets // 后台文件上传下载页面 +│ │ ├──ChunkedFileTransfer.ets // 文件分片下载页面 +│ │ ├──Index.ets // 应用首页 +│ │ └──ResumableFileTransfer.ets // 断点续传页面 +│ ├──service +│ │ ├──Env.ets // 服务端环境配置文件 +│ │ ├──FileRequest.ets // 文件上传下载请求接口模块 +│ │ ├──Formatter.ets // 服务端与客户端数据格式化模块 +│ │ ├──Interceptor.ets // 请求拦截相关类 +│ │ └──Model.ets // 服务端与客户端数据类型定义 +│ └──utils +│ ├──CommonUtil.ets // 常用工具函数模块 +│ ├──LocalFileUtil.ets // 本地文件工具函数模块 +│ └──Logger.ets // 日志类 +└──entry/src/main/resources // 应用静态资源目录 +``` -#### 参与贡献 +### 具体实现 -1. Fork 本仓库 -2. 新建 Feat_xxx 分支 -3. 提交代码 -4. 新建 Pull Request +1. 使用[Remote Communication Kit](https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V5/remote-communication-rcp-V5)相关能力。 +2. 参考链接:基于RCP的文件上传下载开发实践 +### 相关权限 -#### 特技 +- ohos.permission.INTERNET:允许应用在上传下载场景中访问网络 +- ohos.permission.GET_NETWORK_INFO:允许应用获取数据网络信息 +- ohos.permission.KEEP_BACKGROUND_RUNNING: 允许Service Ability在后台持续运行 + +### 依赖 + +[文件服务器配置](./service/README.md)。 + +### 约束与限制 + +1.本示例仅支持标准系统上运行,支持设备:华为手机。 + +2.HarmonyOS系统:HarmonyOS 5.0.0 Release及以上。 + +3.DevEco Studio版本:DevEco Studio 5.0.0 Release及以上。 + +4.HarmonyOS SDK版本:HarmonyOS 5.0.0 Release SDK及以上。 -1. 使用 Readme\_XXX.md 来支持不同的语言,例如 Readme\_en.md, Readme\_zh.md -2. Gitee 官方博客 [blog.gitee.com](https://blog.gitee.com) -3. 你可以 [https://gitee.com/explore](https://gitee.com/explore) 这个地址来了解 Gitee 上的优秀开源项目 -4. [GVP](https://gitee.com/gvp) 全称是 Gitee 最有价值开源项目,是综合评定出的优秀开源项目 -5. Gitee 官方提供的使用手册 [https://gitee.com/help](https://gitee.com/help) -6. Gitee 封面人物是一档用来展示 Gitee 会员风采的栏目 [https://gitee.com/gitee-stars/](https://gitee.com/gitee-stars/) diff --git a/build-profile.json5 b/build-profile.json5 new file mode 100644 index 0000000000000000000000000000000000000000..1e69556b3411622cb2e87a87389653bb34f1b148 --- /dev/null +++ b/build-profile.json5 @@ -0,0 +1,41 @@ +{ + "app": { + "signingConfigs": [], + "products": [ + { + "name": "default", + "signingConfig": "default", + "compatibleSdkVersion": "5.0.0(12)", + "runtimeOS": "HarmonyOS", + "buildOption": { + "strictMode": { + "caseSensitiveCheck": true, + "useNormalizedOHMUrl": true + } + } + } + ], + "buildModeSet": [ + { + "name": "debug", + }, + { + "name": "release" + } + ] + }, + "modules": [ + { + "name": "entry", + "srcPath": "./entry", + "targets": [ + { + "name": "default", + "applyToProducts": [ + "default" + ] + } + ] + } + ] +} \ No newline at end of file diff --git a/entry/.gitignore b/entry/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..4a5abcd51f4c33c8d5adb418053e284d1f80ea10 --- /dev/null +++ b/entry/.gitignore @@ -0,0 +1,9 @@ +/node_modules +/oh_modules +/.preview +/build +/.cxx +/.test +/oh-package-lock.json5 +/obfuscation-rules.txt +/consumer-rules.txt \ No newline at end of file diff --git a/entry/build-profile.json5 b/entry/build-profile.json5 new file mode 100644 index 0000000000000000000000000000000000000000..4d611879c7913fb0610c686e2399258ab3a6dad1 --- /dev/null +++ b/entry/build-profile.json5 @@ -0,0 +1,28 @@ +{ + "apiType": "stageMode", + "buildOption": { + }, + "buildOptionSet": [ + { + "name": "release", + "arkOptions": { + "obfuscation": { + "ruleOptions": { + "enable": false, + "files": [ + "./obfuscation-rules.txt" + ] + } + } + } + }, + ], + "targets": [ + { + "name": "default" + }, + { + "name": "ohosTest", + } + ] +} \ No newline at end of file diff --git a/entry/hvigorfile.ts b/entry/hvigorfile.ts new file mode 100644 index 0000000000000000000000000000000000000000..c6edcd90486dd5a853cf7d34c8647f08414ca7a3 --- /dev/null +++ b/entry/hvigorfile.ts @@ -0,0 +1,6 @@ +import { hapTasks } from '@ohos/hvigor-ohos-plugin'; + +export default { + system: hapTasks, /* Built-in plugin of Hvigor. It cannot be modified. */ + plugins:[] /* Custom plugin to extend the functionality of Hvigor. */ +} diff --git a/entry/oh-package.json5 b/entry/oh-package.json5 new file mode 100644 index 0000000000000000000000000000000000000000..a4b80802638272809b86ef3ead22e9a949d7c1b3 --- /dev/null +++ b/entry/oh-package.json5 @@ -0,0 +1,9 @@ +{ + "name": "default", + "version": "1.0.0", + "description": "Please describe the basic information.", + "main": "", + "author": "", + "license": "", + "dependencies": {} +} \ No newline at end of file diff --git a/entry/src/main/ets/components/CustomList.ets b/entry/src/main/ets/components/CustomList.ets new file mode 100644 index 0000000000000000000000000000000000000000..c6f2379f1141afb96b7e4440e848fa046bd83327 --- /dev/null +++ b/entry/src/main/ets/components/CustomList.ets @@ -0,0 +1,73 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 ("the License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export interface CustomListItem { + id: string + title: ResourceStr + image?: ResourceStr +} + +@Component +export struct CustomList { + @Prop data: CustomListItem[] = []; + private onRowClick: (item: CustomListItem) => void = () => {}; + + @BuilderParam + operateButton: (item: CustomListItem) => void; + + build() { + Scroll() { + Column() { + ForEach(this.data, (item: CustomListItem, index) => { + if (index !== 0) { + Divider() + .color('#0D000000') + .strokeWidth(0.5) + } + Row() { + if (item.image) { + Image(item.image) + .width(24) + .height(24) + .margin({ right: 5 }) + } + Text(item.title) + .fontWeight(FontWeight.Medium) + .layoutWeight(1) + Blank() + if (this.operateButton) { + this.operateButton(item) + } else { + Image($r('app.media.arrow_right')) + .width(24) + .height(24) + .opacity(0.6) + } + } + .width('100%') + .padding({ top: 12, bottom: 12 }) + .onClick(() => { this.onRowClick(item) }) + }, ((item: CustomListItem) => item.id)) + } + } + .width('100%') + .constraintSize({ maxHeight: '100%' }) + .backgroundColor(Color.White) + .borderRadius(20) + .margin({ top: 16, bottom: 28 }) + .padding({ left: 12, right: 12 }) + .scrollBar(BarState.Off) + } +} \ No newline at end of file diff --git a/entry/src/main/ets/components/ProgressButton.ets b/entry/src/main/ets/components/ProgressButton.ets new file mode 100644 index 0000000000000000000000000000000000000000..35ec43bc0fd788ae9ddb0a6db87aba74c0df533e --- /dev/null +++ b/entry/src/main/ets/components/ProgressButton.ets @@ -0,0 +1,49 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 ("the License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +@Component +export struct ProgressBtn { + @Prop progress: number = 0; + @Prop text: ResourceStr = ''; + @Prop buttonHeight: number = 40; + + build() { + Stack({ alignContent: Alignment.End }) { + if (this.progress) { + Progress({ + value: this.progress, + total: 100, + type: ProgressType.Capsule + }) + .height('100%') + .width('100%') + Row() { + Text(this.text) + .fontSize(14) + } + .width('100%') + .justifyContent(FlexAlign.Center) + Text(`${this.progress}%`) + .fontSize(12) + .padding(5) + } else { + Button(this.text) + .width('100%') + .height('100%') + } + } + .height(this.buttonHeight) + } +} \ No newline at end of file diff --git a/entry/src/main/ets/components/SelectionList.ets b/entry/src/main/ets/components/SelectionList.ets new file mode 100644 index 0000000000000000000000000000000000000000..d4908555c71f564f9364b833c4d5e014403ceb03 --- /dev/null +++ b/entry/src/main/ets/components/SelectionList.ets @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 ("the License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { CustomList, CustomListItem } from './CustomList'; + +@Component +export struct SelectionList { + @Prop data: CustomListItem[] = []; + @Link selectedRowId: string; + private beforeRowChange: (row: CustomListItem) => Promise = () => Promise.resolve(true); + + @LocalBuilder + operationButtonBuilder(row: CustomListItem) { + Radio({ + value: row.id, + group: 'rowRadio', + }) + .checked(this.selectedRowId === row.id) + .hitTestBehavior(HitTestMode.None) + } + + onRowClick: (row: CustomListItem) => void = row => { + this.beforeRowChange(row).then(isContinue => { + if (!isContinue) return; + this.selectedRowId = row.id; + }); + } + + build() { + CustomList({ + data: this.data, + onRowClick: this.onRowClick, + operateButton: this.operationButtonBuilder + }) + } +} \ No newline at end of file diff --git a/entry/src/main/ets/constants/Constants.ets b/entry/src/main/ets/constants/Constants.ets new file mode 100644 index 0000000000000000000000000000000000000000..bf994126bfdd441d07c7bda611fe79d832244d09 --- /dev/null +++ b/entry/src/main/ets/constants/Constants.ets @@ -0,0 +1,43 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 ("the License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export interface Route { + title: ResourceStr + children?: Route[] + to?: string +}; + +export const ROUTES: Route[] = [ + { + title: $r('app.string.album_image_transfer'), + to: 'AlbumImageTransfer' + }, + { + title: $r('app.string.chunked_file_transfer'), + to: 'ChunkedFileTransfer' + }, + { + title: $r('app.string.resumable_file_transfer'), + to: 'ResumableFileTransfer' + }, + { + title: $r('app.string.background_file_transfer'), + to: 'BackgroundFileTransfer' + } +]; + +export const imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'tiff', 'webp', 'svg']; + +export const videoExtensions = ['mp4', 'avi', 'mov', 'mkv', 'wmv', 'flv', 'webm', 'mpeg', 'mpg']; \ No newline at end of file diff --git a/entry/src/main/ets/entryability/EntryAbility.ets b/entry/src/main/ets/entryability/EntryAbility.ets new file mode 100644 index 0000000000000000000000000000000000000000..6d1c0031993f3125a16c3980c921c2aafa11283f --- /dev/null +++ b/entry/src/main/ets/entryability/EntryAbility.ets @@ -0,0 +1,56 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 ("the License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { AbilityConstant, UIAbility, Want } from '@kit.AbilityKit'; +import { hilog } from '@kit.PerformanceAnalysisKit'; +import { window } from '@kit.ArkUI'; + +export default class EntryAbility extends UIAbility { + onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void { + hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onCreate'); + } + + onDestroy(): void { + hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onDestroy'); + } + + onWindowStageCreate(windowStage: window.WindowStage): void { + // Main window is created, set main page for this ability + hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageCreate'); + + windowStage.loadContent('pages/Index', (err) => { + if (err.code) { + hilog.error(0x0000, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err) ?? ''); + return; + } + hilog.info(0x0000, 'testTag', 'Succeeded in loading the content.'); + }); + } + + onWindowStageDestroy(): void { + // Main window is destroyed, release UI related resources + hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageDestroy'); + } + + onForeground(): void { + // Ability has brought to foreground + hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onForeground'); + } + + onBackground(): void { + // Ability has back to background + hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onBackground'); + } +} diff --git a/entry/src/main/ets/pages/AlbumImageTransfer.ets b/entry/src/main/ets/pages/AlbumImageTransfer.ets new file mode 100644 index 0000000000000000000000000000000000000000..8d400804f5518622690022205b0ba20a6bd9c86c --- /dev/null +++ b/entry/src/main/ets/pages/AlbumImageTransfer.ets @@ -0,0 +1,127 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 ("the License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { rcp } from '@kit.RemoteCommunicationKit'; +import { fileIo } from '@kit.CoreFileKit'; +import { CustomListItem } from '../components/CustomList'; +import { SelectionList } from '../components/SelectionList'; +import { download, getFileList, upload } from '../service/FileRequest'; +import { File } from '../service/Model'; +import { saveImageToAlbum, selectImagesFromAlbum } from '../utils/LocalFileUtil'; +import { ProgressBtn } from '../components/ProgressButton'; +import { getProgressPercent, showErrorMessage, showSuccessMessage } from '../utils/CommonUtil'; +import { Logger } from '../utils/Logger'; + +@Component +export struct AlbumImageTransfer { + @Consume navPageInfos: NavPathStack; + @State imageList: File[] = []; + @State selectedRowId: string = ''; + @State downloadProgress: number = 0; + @State uploadProgress: number = 0; + + aboutToAppear(): void { + this.setFileList(); + } + + async setFileList() { + this.imageList = await getFileList(); + } + + onUploadProgress: rcp.OnUploadProgress = (totalSize, uploadedSize) => { + this.uploadProgress = getProgressPercent(totalSize, uploadedSize); + } + + onDownloadProgress: rcp.OnDownloadProgress = (totalSize, downloadedSize) => { + this.downloadProgress = getProgressPercent(totalSize, downloadedSize); + } + + async downloadToFile() { + const image = this.imageList.find(image => image.id === this.selectedRowId); + if (!image) return; + const httpEventsHandler: rcp.HttpEventsHandler = { + onDownloadProgress: this.onDownloadProgress + }; + try { + const filePath = await download(image.name, httpEventsHandler); + await saveImageToAlbum(filePath); + showSuccessMessage('Succeed in downloading to album'); + fileIo.unlink(filePath); + } catch (err) { + showErrorMessage(`Failed to save to album, ${err.message || err.data}`); + Logger.error(err.message || JSON.stringify(err.data)); + } finally { + this.selectedRowId = ''; + this.downloadProgress = 0; + } + } + + async upload() { + try { + const sandboxPaths = await selectImagesFromAlbum(); + const filePath = sandboxPaths[0]; + if (!filePath) return; + const httpEventsHandler: rcp.HttpEventsHandler = { + onUploadProgress: this.onUploadProgress, + }; + await upload(filePath, httpEventsHandler); + showSuccessMessage('succeed in uploading from album'); + this.setFileList(); + fileIo.unlink(filePath); + this.uploadProgress = 0; + } catch (err) { + Logger.error(`Failed to select images from album, ${err.message}`); + showErrorMessage(err.message); + } + } + + getCustomListData(): CustomListItem[] { + return this.imageList.map(image => { + const item: CustomListItem = { + id: image.id.toString(), + title: image.name, + image: $r('app.media.ic_public_picture') + }; + return item; + }); + } + + build() { + NavDestination() { + Column() { + Column() { + SelectionList({ + data: this.getCustomListData(), + selectedRowId: this.selectedRowId + }) + } + .layoutWeight(1) + ProgressBtn({ + progress: this.downloadProgress, + text: $r('app.string.button_text_download_album') + }) + .margin({ bottom: 10 }) + .onClick(() => this.downloadToFile()) + ProgressBtn({ + progress: this.uploadProgress, + text: $r('app.string.button_text_upload_album') + }) + .onClick(() => this.upload()) + } + .padding({ left: 16, right: 16, bottom: 16 }) + } + .backgroundColor('#F1F3F5') + } +} \ No newline at end of file diff --git a/entry/src/main/ets/pages/BackgroundFileTransfer.ets b/entry/src/main/ets/pages/BackgroundFileTransfer.ets new file mode 100644 index 0000000000000000000000000000000000000000..538ee1e69876f16a37d2a4575731b45b072bfb2b --- /dev/null +++ b/entry/src/main/ets/pages/BackgroundFileTransfer.ets @@ -0,0 +1,176 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 ("the License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { rcp } from '@kit.RemoteCommunicationKit'; +import { fileIo } from '@kit.CoreFileKit'; +import { Want, wantAgent } from '@kit.AbilityKit'; +import { backgroundTaskManager } from '@kit.BackgroundTasksKit'; +import { CustomListItem } from '../components/CustomList'; +import { SelectionList } from '../components/SelectionList'; +import { download, getFileList, upload } from '../service/FileRequest'; +import { File } from '../service/Model'; +import { copyFileSync, getAlbumAsset, selectImagesFromAlbum } from '../utils/LocalFileUtil'; +import { ProgressBtn } from '../components/ProgressButton'; +import { getProgressPercent, showErrorMessage, showSuccessMessage } from '../utils/CommonUtil'; +import { Logger } from '../utils/Logger'; + +@Component +export struct BackgroundFileTransfer { + @Consume navPageInfos: NavPathStack; + @State imageList: File[] = []; + @State selectedRowId: string = ''; + @State downloadProgress: number = 0; + @State uploadProgress: number = 0; + + aboutToAppear(): void { + this.setFileList(); + } + + async setFileList() { + this.imageList = await getFileList(); + } + + onUploadProgress: rcp.OnUploadProgress = (totalSize, uploadedSize) => { + this.uploadProgress = getProgressPercent(totalSize, uploadedSize); + } + + onDownloadProgress: rcp.OnDownloadProgress = (totalSize, downloadedSize) => { + this.downloadProgress = getProgressPercent(totalSize, downloadedSize); + } + + downloadToFile: () => Promise = async () => { + const image = this.imageList.find(image => image.id === this.selectedRowId); + if (!image) return; + const httpEventsHandler: rcp.HttpEventsHandler = { + onDownloadProgress: this.onDownloadProgress + }; + try { + const fileNameExtension = image.name.split('.').pop() || 'png' + const destPath = await getAlbumAsset(fileNameExtension) + const srcPath = await download(image.name, httpEventsHandler); + copyFileSync(srcPath, destPath) + showSuccessMessage('Succeed in downloading to album'); + fileIo.unlink(srcPath); + } catch (err) { + showErrorMessage(`Failed to save to album, ${err.message || err.data}`); + Logger.error(err.message || JSON.stringify(err.data)); + } finally { + this.selectedRowId = ''; + this.downloadProgress = 0; + } + } + + upload: () => Promise = async () => { + try { + const sandboxPaths = await selectImagesFromAlbum(); + const filePath = sandboxPaths[0]; + if (!filePath) return; + const httpEventsHandler: rcp.HttpEventsHandler = { + onUploadProgress: this.onUploadProgress, + }; + await upload(filePath, httpEventsHandler); + showSuccessMessage('succeed in uploading from album'); + this.setFileList(); + fileIo.unlink(filePath); + this.uploadProgress = 0; + } catch (err) { + Logger.error(`Failed to select images from album, ${err.message}`); + showErrorMessage(err.message); + } + } + + getWantAgentInfo() { + const want: Want = { + bundleName: 'com.example.rcpfiletransfer', + abilityName: 'EntryAbility' + }; + const wantAgentInfo: wantAgent.WantAgentInfo = { + wants: [want], + actionType: wantAgent.OperationType.START_ABILITY, + requestCode: 0, + actionFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] + }; + return wantAgentInfo; + } + + // DocsCode 1 + async startBackgroundTask(task: () => Promise) { + try { + const wantAgentObj = await wantAgent.getWantAgent(this.getWantAgentInfo()); + await backgroundTaskManager.startBackgroundRunning( + getContext(this), + backgroundTaskManager.BackgroundMode.DATA_TRANSFER, + wantAgentObj + ); + task().finally(() => { + backgroundTaskManager.stopBackgroundRunning(getContext(this)); + }); + } catch (err) { + Logger.error('Failed to start background task', JSON.stringify(err)); + showErrorMessage('A background task is running'); + } + } + // DocsCode 1 + + getCustomListData(): CustomListItem[] { + return this.imageList.map(image => { + const item: CustomListItem = { + id: image.id.toString(), + title: image.name, + image: $r('app.media.ic_public_picture') + }; + return item; + }); + } + + build() { + NavDestination() { + Column() { + Column() { + SelectionList({ + data: this.getCustomListData(), + selectedRowId: this.selectedRowId + }) + } + .layoutWeight(1) + if (this.downloadProgress) { + ProgressBtn({ + progress: this.downloadProgress, + text: $r('app.string.button_text_download') + }) + } else { + SaveButton() + .height(40) + .width('100%') + .onClick(async (event: ClickEvent, result: SaveButtonOnClickResult) => { + if (result === SaveButtonOnClickResult.SUCCESS) { + this.startBackgroundTask(this.downloadToFile) + } + }) + } + ProgressBtn({ + progress: this.uploadProgress, + text: $r('app.string.button_text_upload_album') + }) + .margin({ top: 10 }) + .onClick(() => { + this.startBackgroundTask(this.upload) + }) + } + .padding({ left: 16, right: 16, bottom: 16 }) + } + .backgroundColor('#F1F3F5') + } +} \ No newline at end of file diff --git a/entry/src/main/ets/pages/ChunkedFileTransfer.ets b/entry/src/main/ets/pages/ChunkedFileTransfer.ets new file mode 100644 index 0000000000000000000000000000000000000000..5d86444625974a7236b9a8fc3ad90a214c5834a8 --- /dev/null +++ b/entry/src/main/ets/pages/ChunkedFileTransfer.ets @@ -0,0 +1,95 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 ("the License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { rcp } from '@kit.RemoteCommunicationKit'; +import { fileIo } from '@kit.CoreFileKit'; +import { CustomListItem } from '../components/CustomList'; +import { SelectionList } from '../components/SelectionList'; +import { chunkedDownload, getFileList } from '../service/FileRequest'; +import { File } from '../service/Model'; +import { saveImageToAlbum } from '../utils/LocalFileUtil'; +import { ProgressBtn } from '../components/ProgressButton'; +import { getProgressPercent, showErrorMessage, showSuccessMessage } from '../utils/CommonUtil'; +import { Logger } from '../utils/Logger'; + +@Component +export struct ChunkedFileTransfer { + @Consume navPageInfos: NavPathStack; + @State fileList: File[] = []; + @State selectedRowId: string = ''; + @State downloadProgress: number = 0; + + aboutToAppear(): void { + this.setFileList(); + } + + async setFileList() { + this.fileList = await getFileList(); + } + + onDownloadProgress: rcp.OnDownloadProgress = (totalSize, downloadedSize) => { + this.downloadProgress = getProgressPercent(totalSize, downloadedSize); + } + + async downloadToFile() { + const file = this.fileList.find(image => image.id === this.selectedRowId); + if (!file) return; + let filePath = ''; + try { + filePath = await chunkedDownload(file.name, this.onDownloadProgress); + await saveImageToAlbum(filePath); + showSuccessMessage('Succeed in downloading to album'); + } catch (err) { + showErrorMessage('Failed to save to album'); + Logger.error(err.message); + } finally { + fileIo.unlink(filePath); + this.selectedRowId = ''; + this.downloadProgress = 0; + } + } + + getCustomListData(): CustomListItem[] { + return this.fileList.map(file => { + const item: CustomListItem = { + id: file.id.toString(), + title: file.name, + image: $r('app.media.ic_public_picture') + }; + return item; + }); + } + + build() { + NavDestination() { + Column() { + Column() { + SelectionList({ + data: this.getCustomListData(), + selectedRowId: this.selectedRowId + }) + } + .layoutWeight(1) + ProgressBtn({ + progress: this.downloadProgress, + text: $r('app.string.button_text_download_chunked') + }) + .onClick(() => this.downloadToFile()) + } + .padding({ left: 16, right: 16, bottom: 16 }) + } + .backgroundColor('#F1F3F5') + } +} \ No newline at end of file diff --git a/entry/src/main/ets/pages/Index.ets b/entry/src/main/ets/pages/Index.ets new file mode 100644 index 0000000000000000000000000000000000000000..d743ce9c7e27268432ce9029e3545bbb6f634099 --- /dev/null +++ b/entry/src/main/ets/pages/Index.ets @@ -0,0 +1,90 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 ("the License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { CustomList, CustomListItem } from '../components/CustomList'; +import { Route, ROUTES } from '../constants/Constants'; +import { AlbumImageTransfer } from './AlbumImageTransfer'; +import { BackgroundFileTransfer } from './BackgroundFileTransfer'; +import { ChunkedFileTransfer } from './ChunkedFileTransfer'; +import { ResumableFileTransfer } from './ResumableFileTransfer'; + +@Entry +@Component +struct Index { + @Provide navPageInfos: NavPathStack = new NavPathStack(); + + go(route: Route) { + if (!route.to) { + return; + } + this.navPageInfos.pushPath({ + name: route.to, + param: route.title + }); + } + + getCustomListData(): CustomListItem[] { + return ROUTES.map((route, index) => { + const item: CustomListItem = { + id: index.toString(), + title: route.title + } + return item + }) + } + + onRowClick(row: CustomListItem) { + const index = Number(row.id) + const route = ROUTES[index] + this.go(route) + } + + @Builder + NavPageMap(name: string) { + if (name === 'AlbumImageTransfer') { + AlbumImageTransfer(); + } else if (name === 'ChunkedFileTransfer') { + ChunkedFileTransfer() + } else if (name === 'ResumableFileTransfer') { + ResumableFileTransfer() + } else if (name === 'BackgroundFileTransfer') { + BackgroundFileTransfer() + } + } + + build() { + Navigation(this.navPageInfos) { + Column() { + Text($r('app.string.title')) + .fontWeight(FontWeight.Bold) + .fontSize(30) + .fontColor('#E6000000') + .width('100%') + .height(140) + CustomList({ + data: this.getCustomListData(), + onRowClick: row => { this.onRowClick(row) } + }) + } + .width('100%') + .height('100%') + .padding(16) + } + .hideToolBar(true) + .mode(NavigationMode.Stack) + .navDestination(this.NavPageMap) + .backgroundColor('#F1F3F5') + } +} \ No newline at end of file diff --git a/entry/src/main/ets/pages/ResumableFileTransfer.ets b/entry/src/main/ets/pages/ResumableFileTransfer.ets new file mode 100644 index 0000000000000000000000000000000000000000..292e85c7a0eb80584c5f1085b7fc3bf8ecc419ac --- /dev/null +++ b/entry/src/main/ets/pages/ResumableFileTransfer.ets @@ -0,0 +1,138 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 ("the License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { rcp } from '@kit.RemoteCommunicationKit'; +import { fileIo } from '@kit.CoreFileKit'; +import { promptAction } from '@kit.ArkUI'; +import { CustomListItem } from '../components/CustomList'; +import { SelectionList } from '../components/SelectionList'; +import { DownloadStatus, getFileList, ResumableDownloadManager } from '../service/FileRequest'; +import { File } from '../service/Model'; +import { getSandboxPath, saveImageToAlbum } from '../utils/LocalFileUtil'; +import { ProgressBtn } from '../components/ProgressButton'; +import { getProgressPercent, showErrorMessage, showSuccessMessage } from '../utils/CommonUtil'; +import { Logger } from '../utils/Logger'; + +@Component +export struct ResumableFileTransfer { + @Consume navPageInfos: NavPathStack; + @State fileList: File[] = []; + @State selectedRowId: string = ''; + @State progress: number = 0; + @State isDownloading: boolean = false; + @State resumableDownloadManager: ResumableDownloadManager | null = null; + + aboutToAppear(): void { + this.setFileList(); + } + + async setFileList() { + this.fileList = await getFileList(); + } + + onDownloadedProgress: rcp.OnDownloadProgress = (totalSize, downloadedSize) => { + this.progress = getProgressPercent(totalSize, downloadedSize); + } + + async downloadToFile() { + const file = this.fileList.find(file => file.id === this.selectedRowId); + if (!file) return; + const filePath = getSandboxPath(file.name); + this.resumableDownloadManager = this.resumableDownloadManager || + new ResumableDownloadManager(file.name, filePath, this.onDownloadedProgress); + try { + await this.resumableDownloadManager.start(); + if (this.resumableDownloadManager?.status === DownloadStatus.COMPLETED) { + await saveImageToAlbum(filePath); + showSuccessMessage('Succeed in downloading'); + fileIo.unlink(filePath); + this.resetStates(); + } + } catch (err) { + this.resetStates(); + Logger.error(err.message || err.data); + showErrorMessage(err.message || err.data); + } + } + + resetStates() { + this.resumableDownloadManager = null; + this.progress = 0; + this.isDownloading = false; + this.selectedRowId = ''; + } + + getCustomListData(): CustomListItem[] { + return this.fileList.map(file => { + const item: CustomListItem = { + id: file.id.toString(), + title: file.name, + image: $r('app.media.ic_public_picture') + }; + return item; + }); + } + + beforeRowChange: (row: CustomListItem) => Promise = async () => { + if (!this.resumableDownloadManager) return true; + const res = await promptAction.showDialog({ + message: 'Downloading file...Cancel?', + buttons: [ + { + text: 'cancel', + color: '#000000' + }, + { + text: 'confirm', + color: '#0A59F7' + } + ] + }); + if (res.index === 0) return false; + this.resumableDownloadManager?.pause(); + this.resetStates(); + return true; + } + + build() { + NavDestination() { + Column() { + Column() { + SelectionList({ + data: this.getCustomListData(), + selectedRowId: this.selectedRowId, + beforeRowChange: this.beforeRowChange + }) + } + .layoutWeight(1) + ProgressBtn({ + progress: this.progress, + text: this.isDownloading ? $r('app.string.button_text_pause') : $r('app.string.button_text_download') + }) + .enabled(!!this.selectedRowId) + .onClick(() => { + if (this.isDownloading) { + this.resumableDownloadManager?.pause() + } else { + this.downloadToFile() + } + this.isDownloading = !this.isDownloading + }) + } + .padding({ left: 16, right: 16, bottom: 16 }) + } + .backgroundColor('#F1F3F5') + } +} \ No newline at end of file diff --git a/entry/src/main/ets/service/Env.ets b/entry/src/main/ets/service/Env.ets new file mode 100644 index 0000000000000000000000000000000000000000..537a727ae1507414d41c0714675ac663b1352164 --- /dev/null +++ b/entry/src/main/ets/service/Env.ets @@ -0,0 +1,17 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 ("the License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// Please replace this BASE_URL with the address of the HFS server by yourself. +export const BASE_URL = 'http://192.168.43.4'; diff --git a/entry/src/main/ets/service/FileRequest.ets b/entry/src/main/ets/service/FileRequest.ets new file mode 100644 index 0000000000000000000000000000000000000000..f7052d09d140b30ee6a829e22edacfb56043e980 --- /dev/null +++ b/entry/src/main/ets/service/FileRequest.ets @@ -0,0 +1,191 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 ("the License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { rcp } from '@kit.RemoteCommunicationKit'; +import { fileIo } from '@kit.CoreFileKit'; +import { BASE_URL } from './Env'; +import { File, FileListResponse } from './Model'; +import { fileListFormatter } from './Formatter'; +import { StatusCodeInterceptor } from './Interceptor'; +import { getChunkRanges } from '../utils/CommonUtil'; +import { getSandboxPath } from '../utils/LocalFileUtil'; +import { imageExtensions, videoExtensions } from '../constants/Constants'; + +// DocsCode 1 +function genSessionConfig(httpEventsHandler?: rcp.HttpEventsHandler) { + const config: rcp.SessionConfiguration = { + baseAddress: BASE_URL, + interceptors: [new StatusCodeInterceptor()], + requestConfiguration: { + tracing: { httpEventsHandler }, + transfer: { + timeout: { + connectMs: 1000 * 60 * 20, + transferMs: 1000 * 60 * 20 + } + } + } + }; + return config; +} +// DocsCode 1 + +export function getFileList(): Promise { + const session = rcp.createSession(genSessionConfig()); + return session.get('~/api/get_file_list').then((res: rcp.Response) => { + const fileListRes: FileListResponse = res.toJSON() as FileListResponse; + const fileList: File[] = fileListFormatter(fileListRes); + return fileList.filter(file => { + const extension = file.name.split('.').pop() || ''; + return imageExtensions.includes(extension) || videoExtensions.includes(extension); + }); + }).finally(() => { + session.close(); + }); +} + +// DocsCode 4 +export function getFileSize(fileName: string): Promise { + const session = rcp.createSession(genSessionConfig()); + return session.head(`/${fileName}`).then(res => { + const contentLength = res.headers['content-length']; + return contentLength ? Number(contentLength): 0; + }).finally(() => { + session.close(); + }); +} +// DocsCode 4 + +// DocsCode 2 +export function download(fileName: string, httpEventsHandler: rcp.HttpEventsHandler) { + const destPath = getSandboxPath(fileName); + const rcpSession = rcp.createSession(genSessionConfig(httpEventsHandler)); + const downloadTo: rcp.DownloadToFile = { + kind: 'file', + file: destPath + }; + return rcpSession.downloadToFile(`/${fileName}`, downloadTo) + .then(() => destPath) + .finally(() => { + rcpSession.close(); + }); +} +// DocsCode 2 + +// DocsCode 3 +export function upload(srcPath: string, httpEventsHandler: rcp.HttpEventsHandler) { + const session = rcp.createSession(genSessionConfig(httpEventsHandler)); + const formData = new rcp.MultipartForm({ + file: { + contentOrPath: srcPath + } + }); + return session.post('/', formData).finally(() => { + session.close(); + }); +} +// DocsCode 3 + +export async function chunkedDownload( + fileName: string, + onProgress: rcp.OnDownloadProgress, + chunkSize: number = 1024 * 60 +) { + const filePath = getSandboxPath(fileName); + const file = fileIo.openSync(filePath, fileIo.OpenMode.WRITE_ONLY | fileIo.OpenMode.CREATE); + const totalSize = await getFileSize(fileName); + const session = rcp.createSession(genSessionConfig()); + let downloaded: number = 0; + for (const range of getChunkRanges(totalSize, chunkSize)) { + const request = new rcp.Request(`/${fileName}`); + const from = range[0]; + const to = range[1]; + request.transferRange = { from, to }; + const response = await session.fetch(request); + fileIo.writeSync(file.fd, response.body, { offset: from }); + downloaded += (to - from + 1); + onProgress(totalSize, downloaded); + } + fileIo.closeSync(file); + return filePath; +} + +export enum DownloadStatus { + READY, + DOWNLOADING, + PAUSED, + COMPLETED +} + +export class ResumableDownloadManager { + chunkSize: number = 1024 * 60; + totalSize: number = 0; + downloadedSize: number = 0; + session: rcp.Session = rcp.createSession(genSessionConfig()); + url: string; + file: fileIo.File; + onProgress: rcp.OnDownloadProgress; + currentRequest: rcp.Request | null = null; + status: DownloadStatus = DownloadStatus.READY; + + constructor(url: string, filePath: string, onProgress: rcp.OnDownloadProgress,) { + this.url = url; + this.file = fileIo.openSync(filePath, fileIo.OpenMode.WRITE_ONLY | fileIo.OpenMode.CREATE); + this.onProgress = onProgress; + } + + // DocsCode 5 + async downloadChunk(from: number, to: number) { + const request = new rcp.Request(this.url); + request.transferRange = { from, to }; + this.currentRequest = request; + try { + const response = await this.session.fetch(request); + fileIo.writeSync(this.file.fd, response.body, { offset: from }); + const chunkSize = to - from + 1; + this.downloadedSize += chunkSize; + this.onProgress(this.totalSize, this.downloadedSize); + } catch (err) { + // cancel request is not handle as an exception + if (err.code === 1007900992) return; + throw new Error(err.message || err.data); + } + } + // DocsCode 5 + + // DocsCode 6 + async start() { + this.status = DownloadStatus.DOWNLOADING; + this.totalSize = this.totalSize || await getFileSize(this.url); + while (this.downloadedSize < this.totalSize) { + const from = this.downloadedSize; + const to = Math.min(from + this.chunkSize - 1, this.totalSize - 1); + await this.downloadChunk(from, to); + if ((this.status as DownloadStatus) === DownloadStatus.PAUSED) break; + } + if (this.downloadedSize === this.totalSize) { + this.session.close(); + this.status = DownloadStatus.COMPLETED; + } + } + // DocsCode 6 + + // DocsCode 7 + pause() { + this.status = DownloadStatus.PAUSED; + this.session.cancel(this.currentRequest); + } + // DocsCode 7 +} \ No newline at end of file diff --git a/entry/src/main/ets/service/Formatter.ets b/entry/src/main/ets/service/Formatter.ets new file mode 100644 index 0000000000000000000000000000000000000000..4d02c587b5239d8aff98f76bebc8778c4ee3ed80 --- /dev/null +++ b/entry/src/main/ets/service/Formatter.ets @@ -0,0 +1,32 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 ("the License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { File, FileListResponse } from './Model'; + +function getTime(timeStr: string) { + return new Date(timeStr).getTime(); +} + +export function fileListFormatter(fileListRes: FileListResponse): File[] { + return fileListRes.list.filter(fileRes => fileRes.s) + .sort((a, b) => getTime(b.m) - getTime(a.m)) + .map(fileRes => { + const file: File = { + id: fileRes.n, + name: fileRes.n + }; + return file; + }); +} \ No newline at end of file diff --git a/entry/src/main/ets/service/Interceptor.ets b/entry/src/main/ets/service/Interceptor.ets new file mode 100644 index 0000000000000000000000000000000000000000..37527b5be3b08d54fd3d3be2d1ea2aa07b36a32c --- /dev/null +++ b/entry/src/main/ets/service/Interceptor.ets @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 ("the License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { rcp } from '@kit.RemoteCommunicationKit'; +import { BusinessError } from '@kit.BasicServicesKit'; +import { showErrorMessage } from '../utils/CommonUtil'; +import { Logger } from '../utils/Logger'; + +// DocsCode 1 +export class StatusCodeInterceptor implements rcp.Interceptor { + async intercept(context: rcp.RequestContext, next: rcp.RequestHandler): Promise { + const url = context.request.url; + return new Promise((resolve, reject) => { + next.handle(context).then((res: rcp.Response) => { + if ([200, 206].includes(res.statusCode)) { + resolve(res); + } else { + const message = `Failed to ${url}: statusCode is ${res.statusCode}, message is ${res.toString()}`; + Logger.error(message); + showErrorMessage(message); + reject(new Error(message)); + } + }).catch((err: BusinessError) => { + Logger.error(`Failed to ${url}: Code is ${err.code}, message is ${err.data}`); + reject(err); + // cancel request don't show err message prompt. + if (err.code === 1007900992) return; + showErrorMessage(JSON.stringify(err.data)); + }); + }); + } +} +// DocsCode 1 \ No newline at end of file diff --git a/entry/src/main/ets/service/Model.ets b/entry/src/main/ets/service/Model.ets new file mode 100644 index 0000000000000000000000000000000000000000..47c8588df637d324f53e0b32b2993aed728ebbb4 --- /dev/null +++ b/entry/src/main/ets/service/Model.ets @@ -0,0 +1,43 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 ("the License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * Represents a file or folder response from the server. + * @interface + */ +interface FileResponse { + /** The name of the file or folder. */ + n: string, + + /** The upload time of the file or folder. */ + m: string, + + /** The size for the file. */ + s?: number +} + +export interface FileListResponse { + 'can_archive': boolean + 'can_upload': boolean + 'can_delete': boolean + 'can_overwrite': boolean + 'can_comment': boolean + list: FileResponse[] +} + +export interface File { + id: string + name: string +} \ No newline at end of file diff --git a/entry/src/main/ets/utils/CommonUtil.ets b/entry/src/main/ets/utils/CommonUtil.ets new file mode 100644 index 0000000000000000000000000000000000000000..90437b9abdf1762071a971e3e808e3ab3d271f82 --- /dev/null +++ b/entry/src/main/ets/utils/CommonUtil.ets @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 ("the License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { promptAction } from '@kit.ArkUI'; + +export function getChunkRanges(totalSize: number, chunkSize: number): number[][] { + const chunkCount = Math.ceil(totalSize / chunkSize); + return Array.from({ length: chunkCount }, (_: undefined, index) => { + const start = index * chunkSize; + const end = Math.min(start + chunkSize - 1, totalSize - 1); + return [start, end]; + }); +} + +export function getProgressPercent(totalSize: number, transferredSize: number) { + return Number((transferredSize / totalSize * 100).toFixed(2)); +} + +export function showSuccessMessage(message: string) { + promptAction.showToast({ + message: message, + duration: 2000 + }); +} + +export function showErrorMessage(errMessage: string) { + promptAction.showToast({ + message: errMessage, + backgroundColor: 'rgba(232, 64, 38, 0.15)', + textColor: '#E84026', + duration: 3000 + }); +} \ No newline at end of file diff --git a/entry/src/main/ets/utils/LocalFileUtil.ets b/entry/src/main/ets/utils/LocalFileUtil.ets new file mode 100644 index 0000000000000000000000000000000000000000..af9323c5a42b6f90f81ac2ccdecec0cbf9ed9d4d --- /dev/null +++ b/entry/src/main/ets/utils/LocalFileUtil.ets @@ -0,0 +1,77 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 ("the License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { fileIo, fileUri } from '@kit.CoreFileKit'; +import { photoAccessHelper } from '@kit.MediaLibraryKit'; +import { imageExtensions } from '../constants/Constants'; + +export function getSandboxPath(path: string) { + return `${getContext().filesDir}/${path}`; +} + +export function copyFileSync(srcPath: string, destPath: string) { + const srcFile = fileIo.openSync(srcPath, fileIo.OpenMode.READ_ONLY); + const destFile = fileIo.openSync(destPath, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE); + fileIo.copyFileSync(srcFile.fd, destFile.fd); + fileIo.closeSync(srcFile); + fileIo.closeSync(destFile); +} + +function getPhotoType(fileNameExtension: string) { + return imageExtensions.includes(fileNameExtension) ? + photoAccessHelper.PhotoType.IMAGE : + photoAccessHelper.PhotoType.VIDEO; +} + +export async function getAlbumAsset(fileNameExtension: string) { + const phAccessHelper = photoAccessHelper.getPhotoAccessHelper(getContext()); + return await phAccessHelper.createAsset(getPhotoType(fileNameExtension), fileNameExtension); +} + +// DocsCode 1 +export async function saveImageToAlbum(sandboxPath: string) { + const phAccessHelper = photoAccessHelper.getPhotoAccessHelper(getContext()); + const fileNameExtension = sandboxPath.split('.').pop() || 'png'; + const photoCreationConfig: photoAccessHelper.PhotoCreationConfig = { + fileNameExtension, + photoType: getPhotoType(fileNameExtension), + }; + const uri: string = fileUri.getUriFromPath(sandboxPath); + const desFileUris: string[] = await phAccessHelper.showAssetsCreationDialog([uri], [photoCreationConfig]); + const filePath = desFileUris[0]; + if (!filePath) throw new Error('photo assets permission denied'); + copyFileSync(sandboxPath, filePath); + return filePath; +} +// DocsCode 1 + +// DocsCode 2 +export async function selectImagesFromAlbum(maxNumber: number = 1): Promise { + const photoPicker = new photoAccessHelper.PhotoViewPicker(); + const photoSelectOptions: photoAccessHelper.PhotoSelectOptions = { + MIMEType: photoAccessHelper.PhotoViewMIMETypes.IMAGE_VIDEO_TYPE, + maxSelectNumber: maxNumber + }; + return photoPicker.select(photoSelectOptions).then((photoSelectResult: photoAccessHelper.PhotoSelectResult) => { + const filePaths = photoSelectResult.photoUris; + return filePaths.map(filePath => { + const imageName = filePath.split('/').pop() || ''; + const sandboxPath = getSandboxPath(imageName); + copyFileSync(filePath, sandboxPath); + return sandboxPath; + }); + }); +} +// DocsCode 2 \ No newline at end of file diff --git a/entry/src/main/ets/utils/Logger.ets b/entry/src/main/ets/utils/Logger.ets new file mode 100644 index 0000000000000000000000000000000000000000..92c1f754a58e62930b60a5a70e2eea31e37fd4fa --- /dev/null +++ b/entry/src/main/ets/utils/Logger.ets @@ -0,0 +1,38 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use Logger file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { hilog } from '@kit.PerformanceAnalysisKit'; + +export class Logger { + private static domain: number = 0xFF00; + private static prefix: string = 'rcpTransfer'; + private static format: string = '%{public}s, %{public}s'; + + static debug(...args: string[]): void { + hilog.debug(Logger.domain, Logger.prefix, Logger.format, args); + } + + static info(...args: string[]): void { + hilog.info(Logger.domain, Logger.prefix, Logger.format, args); + } + + static warn(...args: string[]): void { + hilog.warn(Logger.domain, Logger.prefix, Logger.format, args); + } + + static error(...args: string[]): void { + hilog.error(Logger.domain, Logger.prefix, Logger.format, args); + } +} \ No newline at end of file diff --git a/entry/src/main/module.json5 b/entry/src/main/module.json5 new file mode 100644 index 0000000000000000000000000000000000000000..a1b8946485caad06aea04370ad3c438461dedf2a --- /dev/null +++ b/entry/src/main/module.json5 @@ -0,0 +1,71 @@ +{ + "module": { + "name": "entry", + "type": "entry", + "description": "$string:module_desc", + "mainElement": "EntryAbility", + "deviceTypes": [ + "phone" + ], + "deliveryWithInstall": true, + "installationFree": false, + "pages": "$profile:main_pages", + "abilities": [ + { + "name": "EntryAbility", + "srcEntry": "./ets/entryability/EntryAbility.ets", + "description": "$string:EntryAbility_desc", + "icon": "$media:layered_image", + "label": "$string:EntryAbility_label", + "startWindowIcon": "$media:startIcon", + "startWindowBackground": "$color:start_window_background", + "exported": true, + "skills": [ + { + "entities": [ + "entity.system.home" + ], + "actions": [ + "action.system.home" + ] + } + ], + "backgroundModes": [ + "dataTransfer" + ] + } + ], + "requestPermissions": [ + { + "name": "ohos.permission.INTERNET", + "reason": "$string:reason_internet", + "usedScene": { + "abilities": [ + "EntryAbility" + ], + "when": "always" + } + }, + { + "name": "ohos.permission.GET_NETWORK_INFO", + "reason": "$string:reason_network", + "usedScene": { + "abilities": [ + "EntryAbility" + ], + "when": "always" + } + }, + { + "name": "ohos.permission.KEEP_BACKGROUND_RUNNING", + "reason": "$string:reason_background", + "usedScene": { + "abilities": [ + "EntryAbility" + ], + "when": "always" + } + } + ] + } +} \ No newline at end of file diff --git a/entry/src/main/resources/base/element/color.json b/entry/src/main/resources/base/element/color.json new file mode 100644 index 0000000000000000000000000000000000000000..3c712962da3c2751c2b9ddb53559afcbd2b54a02 --- /dev/null +++ b/entry/src/main/resources/base/element/color.json @@ -0,0 +1,8 @@ +{ + "color": [ + { + "name": "start_window_background", + "value": "#FFFFFF" + } + ] +} \ No newline at end of file diff --git a/entry/src/main/resources/base/element/string.json b/entry/src/main/resources/base/element/string.json new file mode 100644 index 0000000000000000000000000000000000000000..7757b686154c113087648073f2aab72f3a025546 --- /dev/null +++ b/entry/src/main/resources/base/element/string.json @@ -0,0 +1,68 @@ +{ + "string": [ + { + "name": "module_desc", + "value": "module description" + }, + { + "name": "EntryAbility_desc", + "value": "description" + }, + { + "name": "EntryAbility_label", + "value": "基于RCP文件上传与下载" + }, + { + "name": "title", + "value": "基于RCP文件上传与下载" + }, + { + "name": "album_image_transfer", + "value": "相册图片上传与下载" + }, + { + "name": "chunked_file_transfer", + "value": "文件分片下载" + }, + { + "name": "resumable_file_transfer", + "value": "断点续传" + }, + { + "name": "background_file_transfer", + "value": "后台文件上传下载" + }, + { + "name": "button_text_download_album", + "value": "下载到相册" + }, + { + "name": "button_text_upload_album", + "value": "从相册上传" + }, + { + "name": "button_text_download", + "value": "下载" + }, + { + "name": "button_text_download_chunked", + "value": "分片下载" + }, + { + "name": "button_text_pause", + "value": "暂停" + }, + { + "name": "reason_background", + "value": "允许Service Ability在后台持续运行" + }, + { + "name": "reason_internet", + "value": "允许应用在上传下载场景中访问网络" + }, + { + "name": "reason_network", + "value": "允许应用获取数据网络信息" + } + ] +} \ No newline at end of file diff --git a/entry/src/main/resources/base/media/arrow_right.svg b/entry/src/main/resources/base/media/arrow_right.svg new file mode 100644 index 0000000000000000000000000000000000000000..0ddab9a995f5954c12452f90583f1fc572f00b51 --- /dev/null +++ b/entry/src/main/resources/base/media/arrow_right.svg @@ -0,0 +1,17 @@ + + + + Public/ic_public_arrow_right + Created with Sketch. + + + + + + + + + + \ No newline at end of file diff --git a/entry/src/main/resources/base/media/background.png b/entry/src/main/resources/base/media/background.png new file mode 100644 index 0000000000000000000000000000000000000000..f939c9fa8cc8914832e602198745f592a0dfa34d Binary files /dev/null and b/entry/src/main/resources/base/media/background.png differ diff --git a/entry/src/main/resources/base/media/foreground.png b/entry/src/main/resources/base/media/foreground.png new file mode 100644 index 0000000000000000000000000000000000000000..4483ddad1f079e1089d685bd204ee1cfe1d01902 Binary files /dev/null and b/entry/src/main/resources/base/media/foreground.png differ diff --git a/entry/src/main/resources/base/media/ic_public_picture.svg b/entry/src/main/resources/base/media/ic_public_picture.svg new file mode 100644 index 0000000000000000000000000000000000000000..dd45ecfe06b0b1f8ef96f66287a41e873e71fef5 --- /dev/null +++ b/entry/src/main/resources/base/media/ic_public_picture.svg @@ -0,0 +1,13 @@ + + + Public/ic_public_picture + + + + + + + + + + \ No newline at end of file diff --git a/entry/src/main/resources/base/media/layered_image.json b/entry/src/main/resources/base/media/layered_image.json new file mode 100644 index 0000000000000000000000000000000000000000..fb49920440fb4d246c82f9ada275e26123a2136a --- /dev/null +++ b/entry/src/main/resources/base/media/layered_image.json @@ -0,0 +1,7 @@ +{ + "layered-image": + { + "background" : "$media:background", + "foreground" : "$media:foreground" + } +} \ No newline at end of file diff --git a/entry/src/main/resources/base/media/startIcon.png b/entry/src/main/resources/base/media/startIcon.png new file mode 100644 index 0000000000000000000000000000000000000000..205ad8b5a8a42e8762fbe4899b8e5e31ce822b8b Binary files /dev/null and b/entry/src/main/resources/base/media/startIcon.png differ diff --git a/entry/src/main/resources/base/profile/main_pages.json b/entry/src/main/resources/base/profile/main_pages.json new file mode 100644 index 0000000000000000000000000000000000000000..1898d94f58d6128ab712be2c68acc7c98e9ab9ce --- /dev/null +++ b/entry/src/main/resources/base/profile/main_pages.json @@ -0,0 +1,5 @@ +{ + "src": [ + "pages/Index" + ] +} diff --git a/entry/src/main/resources/en_US/element/string.json b/entry/src/main/resources/en_US/element/string.json new file mode 100644 index 0000000000000000000000000000000000000000..ebf6be41d07002a035d14cea6830637ac10b526f --- /dev/null +++ b/entry/src/main/resources/en_US/element/string.json @@ -0,0 +1,67 @@ +{ + "string": [ + { + "name": "module_desc", + "value": "module description" + }, + { + "name": "EntryAbility_desc", + "value": "description" + }, + { + "name": "EntryAbility_label", + "value": "基于RCP文件上传与下载" + }, + { + "name": "title", + "value": "基于RCP文件上传与下载" + }, + { + "name": "album_image_transfer", + "value": "相册图片上传与下载" + }, + { + "name": "chunked_file_transfer", + "value": "文件分片下载" + }, + { + "name": "resumable_file_transfer", + "value": "断点续传" + }, + { + "name": "background_file_transfer", + "value": "后台文件上传下载" + }, + { + "name": "button_text_download_album", + "value": "下载到相册" + }, + { + "name": "button_text_upload_album", + "value": "从相册上传" + }, + { + "name": "button_text_download", + "value": "下载" + }, + { + "name": "button_text_download_chunked", + "value": "分片下载" + }, + { + "name": "button_text_pause", + "value": "暂停" + },{ + "name": "reason_background", + "value": "允许Service Ability在后台持续运行" + }, + { + "name": "reason_internet", + "value": "允许应用在上传下载场景中访问网络" + }, + { + "name": "reason_network", + "value": "允许应用获取数据网络信息" + } + ] +} \ No newline at end of file diff --git a/entry/src/main/resources/zh_CN/element/string.json b/entry/src/main/resources/zh_CN/element/string.json new file mode 100644 index 0000000000000000000000000000000000000000..ebf6be41d07002a035d14cea6830637ac10b526f --- /dev/null +++ b/entry/src/main/resources/zh_CN/element/string.json @@ -0,0 +1,67 @@ +{ + "string": [ + { + "name": "module_desc", + "value": "module description" + }, + { + "name": "EntryAbility_desc", + "value": "description" + }, + { + "name": "EntryAbility_label", + "value": "基于RCP文件上传与下载" + }, + { + "name": "title", + "value": "基于RCP文件上传与下载" + }, + { + "name": "album_image_transfer", + "value": "相册图片上传与下载" + }, + { + "name": "chunked_file_transfer", + "value": "文件分片下载" + }, + { + "name": "resumable_file_transfer", + "value": "断点续传" + }, + { + "name": "background_file_transfer", + "value": "后台文件上传下载" + }, + { + "name": "button_text_download_album", + "value": "下载到相册" + }, + { + "name": "button_text_upload_album", + "value": "从相册上传" + }, + { + "name": "button_text_download", + "value": "下载" + }, + { + "name": "button_text_download_chunked", + "value": "分片下载" + }, + { + "name": "button_text_pause", + "value": "暂停" + },{ + "name": "reason_background", + "value": "允许Service Ability在后台持续运行" + }, + { + "name": "reason_internet", + "value": "允许应用在上传下载场景中访问网络" + }, + { + "name": "reason_network", + "value": "允许应用获取数据网络信息" + } + ] +} \ No newline at end of file diff --git a/hvigor/hvigor-config.json5 b/hvigor/hvigor-config.json5 new file mode 100644 index 0000000000000000000000000000000000000000..06b2783670a348f95533b352c1ceda909a842bbc --- /dev/null +++ b/hvigor/hvigor-config.json5 @@ -0,0 +1,22 @@ +{ + "modelVersion": "5.0.0", + "dependencies": { + }, + "execution": { + // "analyze": "normal", /* Define the build analyze mode. Value: [ "normal" | "advanced" | false ]. Default: "normal" */ + // "daemon": true, /* Enable daemon compilation. Value: [ true | false ]. Default: true */ + // "incremental": true, /* Enable incremental compilation. Value: [ true | false ]. Default: true */ + // "parallel": true, /* Enable parallel compilation. Value: [ true | false ]. Default: true */ + // "typeCheck": false, /* Enable typeCheck. Value: [ true | false ]. Default: false */ + }, + "logging": { + // "level": "info" /* Define the log level. Value: [ "debug" | "info" | "warn" | "error" ]. Default: "info" */ + }, + "debugging": { + // "stacktrace": false /* Disable stacktrace compilation. Value: [ true | false ]. Default: false */ + }, + "nodeOptions": { + // "maxOldSpaceSize": 8192 /* Enable nodeOptions maxOldSpaceSize compilation. Unit M. Used for the daemon process. Default: 8192*/ + // "exposeGC": true /* Enable to trigger garbage collection explicitly. Default: true*/ + } +} diff --git a/hvigorfile.ts b/hvigorfile.ts new file mode 100644 index 0000000000000000000000000000000000000000..f3cb9f1a87a81687554a76283af8df27d8bda775 --- /dev/null +++ b/hvigorfile.ts @@ -0,0 +1,6 @@ +import { appTasks } from '@ohos/hvigor-ohos-plugin'; + +export default { + system: appTasks, /* Built-in plugin of Hvigor. It cannot be modified. */ + plugins:[] /* Custom plugin to extend the functionality of Hvigor. */ +} diff --git a/oh-package.json5 b/oh-package.json5 new file mode 100644 index 0000000000000000000000000000000000000000..0cec98259052cc175d04dbcf61780de4bc9785f4 --- /dev/null +++ b/oh-package.json5 @@ -0,0 +1,7 @@ +{ + "modelVersion": "5.0.0", + "description": "Please describe the basic information.", + "dependencies": { + }, + "devDependencies": {} +} diff --git a/screenshots/devices/home.png b/screenshots/devices/home.png new file mode 100644 index 0000000000000000000000000000000000000000..cc0a4e16e99bd562da96f4dd1922a47f33c31550 Binary files /dev/null and b/screenshots/devices/home.png differ diff --git a/service/README.md b/service/README.md new file mode 100644 index 0000000000000000000000000000000000000000..2d27df24ee2972e2a64de66129b4d2ebba7cb5c9 --- /dev/null +++ b/service/README.md @@ -0,0 +1,24 @@ +## 文件服务器使用说明 + +### 服务器配置: + +1.测试设备和电脑连接同一个局域网。 + +2.电脑解压本目录下hfs压缩包,打开`hfs.exe`可执行文件。 + +3.hfs管理页面配置(http://localhost/~/admin), 执行hfs.exe文件浏览器自动弹出: + +1. 选择左侧Shared files菜单 +2. disk source中绑定本地文件存储的文件夹 +3. 设置所有权限为Anyone +4点击保存save按钮 + +![](./images/img.png) + +4.设置[Env.ets](../entry/src/main/ets/service/Env.ets)文件中的BASE_URL为上图中序号4处链接。 + +5、按照顺序操作1-4步骤后,即可运行测试上传下载任务。 + +## 相关依赖 + +[基于RCP的文件上传下载](..)应用依赖本服务。 \ No newline at end of file diff --git a/service/hfs-windows-x64-0.54.0.zip b/service/hfs-windows-x64-0.54.0.zip new file mode 100644 index 0000000000000000000000000000000000000000..4620f622ea07871bd18c0213bbe8da4120cd1b8f Binary files /dev/null and b/service/hfs-windows-x64-0.54.0.zip differ diff --git a/service/images/img.png b/service/images/img.png new file mode 100644 index 0000000000000000000000000000000000000000..d5c81d7f3b18ebde5e0986b60fda393c70023511 Binary files /dev/null and b/service/images/img.png differ