1/* 2 * Copyright (c) 2023 Huawei Device Co., Ltd. 3 * Licensed under the Apache License, Version 2.0 (the "License"); 4 * you may not use this file except in compliance with the License. 5 * You may obtain a copy of the License at 6 * 7 * http://www.apache.org/licenses/LICENSE-2.0 8 * 9 * Unless required by applicable law or agreed to in writing, software 10 * distributed under the License is distributed on an "AS IS" BASIS, 11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 * See the License for the specific language governing permissions and 13 * limitations under the License. 14 */ 15 16import common from '@ohos.app.ability.common'; 17import http from '@ohos.net.http'; 18import { FileModel } from './model/FileModel'; 19import { logger } from '../utils/Logger'; 20import { urlUtils } from '../utils/UrlUtils'; 21 22const TAG: string = 'RequestFiles'; 23const FILE_LENGTH: number = 2; 24 25class Request { 26 async requestFiles() { 27 let httpRequest = http.createHttp(); 28 let files: Array<FileModel> = []; 29 let context: common.UIAbilityContext = getContext(this) as common.UIAbilityContext; 30 let url = await urlUtils.getUrl(context); 31 let header: Record<string, string> = { 32 'Content-Type': 'text/plain' 33 } 34 try { 35 let requestOption: http.HttpRequestOptions = { 36 method: http.RequestMethod.GET, 37 header: header 38 } 39 let response = await httpRequest.request(url + '/?tpl=list&folders-filter=&recursive', requestOption); 40 logger.info(TAG, `data = ${JSON.stringify(response)}`); 41 let result: string = response.result.toString(); 42 logger.info(TAG, `Result = ${result}`); 43 44 let tempFiles = result.split('\r\n'); 45 for (let i = 0; i < tempFiles.length; i++) { 46 let splitFiles = tempFiles[i].split('//')[1].split('/'); 47 logger.info(TAG, `splitFiles = ${JSON.stringify(splitFiles)}`); 48 if (splitFiles.length === FILE_LENGTH) { // 代表是根目录下的文件 49 let name = splitFiles.pop(); 50 if (name) { 51 files.push(new FileModel(name, false, [tempFiles[i]])); 52 } 53 } else { // 文件夹 54 let folderName = splitFiles[1]; 55 if (files.length === 0) { 56 files.push(new FileModel(folderName, true, [])); 57 } else { 58 let index = 0; 59 while (index < files.length) { 60 if (files[index].name === folderName) { 61 files[index].files.push(tempFiles[i]); 62 break; 63 } 64 index++; 65 } 66 if (index === files.length) { 67 files.push(new FileModel(folderName, true, [])); 68 } 69 } 70 } 71 } 72 files = files.sort((a: FileModel, b: FileModel) => { 73 if (a.isFolder && b.isFolder) { 74 return a.name.localeCompare(b.name); 75 } else if (a.isFolder && b.isFolder === false) { 76 return -1; 77 } else { 78 return 1; 79 } 80 }) 81 logger.info(TAG, `files = ${JSON.stringify(files)}`); 82 return files; 83 } catch (err) { 84 logger.info(TAG, `error: ${JSON.stringify(err)}`); 85 httpRequest.destroy(); 86 return []; 87 } 88 } 89} 90 91export const requestFiles = new Request();