index.uts 6.8 KB
Newer Older
DCloud-yyl's avatar
DCloud-yyl 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221
import {
    API_SAVE_FILE,
    API_GET_SAVED_FILE_LIST,
    API_GET_SAVED_FILE_INFO,
    API_REMOVE_SAVED_FILE,
    API_GET_FILE_INFO
} from '../protocol.uts'
import {
    SaveFile,
    SaveFileOptions,
    SaveFileSuccess,
    SaveFileFail,
    GetSavedFileList,
    GetSavedFileListOptions,
    SavedFileListItem,
    GetSavedFileListSuccess,
    GetSavedFileListFail,
    GetSavedFileInfo,
    GetSavedFileInfoOptions,
    GetSavedFileInfoSuccess,
    GetSavedFileInfoFail,
    RemoveSavedFile,
    RemoveSavedFileOptions,
    RemoveSavedFileSuccess,
    RemoveSavedFileFail,
    GetFileInfo,
    GetFileInfoOptions,
    GetFileInfoSuccess,
    GetFileInfoFail
} from '../interface.uts'
import {
    getEnv,
    getRealPath,
} from '@dcloudio/uni-runtime'
import fs from '@ohos.file.fs'
import { ListFileOptions } from '@ohos.file.fs'
import Hash from '@ohos.file.hash';

export {
    SaveFile,
    SaveFileOptions,
    SaveFileSuccess,
    SaveFileFail,
    GetSavedFileList,
    SavedFileListItem,
    GetSavedFileListOptions,
    GetSavedFileListSuccess,
    GetSavedFileListFail,
    GetSavedFileInfo,
    GetSavedFileInfoOptions,
    GetSavedFileInfoSuccess,
    GetSavedFileInfoFail,
    RemoveSavedFile,
    RemoveSavedFileOptions,
    RemoveSavedFileSuccess,
    RemoveSavedFileFail,
    GetFileInfo,
    GetFileInfoOptions,
    GetFileInfoSuccess,
    GetFileInfoFail
}

function getSavedDir(appId: string) {
    return getEnv().USER_DATA_PATH + '/' + appId + '/saved'
}

let savedIndex: [string, number] = ['0', 0]
function getSavedFileName(filePath: string) {
    const ext = filePath.split('/').pop()?.split('.').slice(1).join('.')
    let fileName = Date.now() + ''
    if (savedIndex[0] === fileName) {
        savedIndex[1]++
        if (savedIndex[1] > 0) {
            fileName += '-' + savedIndex[1]
        }
    } else {
        savedIndex[0] = fileName
        savedIndex[1] = 0
    }
    if (ext) {
        fileName += '.' + ext
    }
    return fileName
}

function getFsPath(filePath: string) {
    filePath = getRealPath(filePath) as string
    if (!/^file:/.test(filePath)) {
        return filePath 
    }
    const rawPath = filePath.replace(/^file:\/\//, '')
    if (rawPath[0] === '/') {
        return rawPath
    }
    return filePath
}

export const saveFile: SaveFile = defineAsyncApi<SaveFileOptions, SaveFileSuccess>(
    API_SAVE_FILE,
    function (options: SaveFileOptions, exec: ApiExecutor<SaveFileSuccess>) {
        const tempFilePath = getRealPath(options.tempFilePath) as string;
        const savedPath = getSavedDir(APP_ID)
        if (!fs.accessSync(savedPath)) {
            fs.mkdirSync(savedPath, true)
        }
        let srcFile: fs.File
        try {
            srcFile = fs.openSync(tempFilePath, fs.OpenMode.READ_ONLY)
        } catch (error) {
            exec.reject((error as Error).message)
            return
        }
        const savedFilePath = savedPath + '/' + getSavedFileName(tempFilePath);
        fs.copyFile(srcFile.fd, savedFilePath, (err) => {
            fs.closeSync(srcFile)
            if (err) {
                exec.reject(err.message)
            } else {
                exec.resolve({
                    savedFilePath: 'file://' + savedFilePath
                } as SaveFileSuccess)
            }
        })
    }
) as SaveFile

export const getSavedFileList: GetSavedFileList = defineAsyncApi<GetSavedFileListOptions, GetSavedFileListSuccess>(
    API_GET_SAVED_FILE_LIST,
    function (options: GetSavedFileListOptions, exec: ApiExecutor<GetSavedFileListSuccess>) {
        const savedPath = getSavedDir(APP_ID)
        if (!fs.accessSync(savedPath)) {
            exec.resolve({
                fileList: []
            } as GetSavedFileListSuccess)
        }
        fs.listFile(savedPath, {} as ListFileOptions, (err, fileList) => {
            if (err) {
                exec.reject(err.message)
            } else {
                exec.resolve({
                    fileList: fileList.map((filePath: string) => {
                        const fullPath = savedPath + '/' + filePath
                        const stat = fs.statSync(fullPath)
                        if (!stat.isFile()) {
                            return null
                        }
                        return {
                            filePath: 'file://' + fullPath,
                            size: stat.size,
                            createTime: stat.ctime
                        } as SavedFileListItem
                    }).filter((item) => !!item)
                } as GetSavedFileListSuccess)
            }
        })
    }
) as GetSavedFileList

export const getSavedFileInfo: GetSavedFileInfo = defineAsyncApi<GetSavedFileInfoOptions, GetSavedFileInfoSuccess>(
    API_GET_SAVED_FILE_INFO,
    function (options: GetSavedFileInfoOptions, exec: ApiExecutor<GetSavedFileInfoSuccess>) {
        const savedFilePath = getFsPath(options.filePath);
        if (!fs.accessSync(savedFilePath)) {
            exec.reject('file not exist')
            return
        }
        const stat = fs.statSync(savedFilePath)
        if (!stat.isFile()) {
            exec.reject('file not exist')
        }
        exec.resolve({
            size: stat.size,
            createTime: stat.ctime
        } as GetSavedFileInfoSuccess)
    }
) as GetSavedFileInfo

export const removeSavedFile: RemoveSavedFile = defineAsyncApi<RemoveSavedFileOptions, RemoveSavedFileSuccess>(
    API_REMOVE_SAVED_FILE,
    function (options: RemoveSavedFileOptions, exec: ApiExecutor<RemoveSavedFileSuccess>) {
        const savedFilePath = getFsPath(options.filePath);
        if (!fs.accessSync(savedFilePath)) {
            exec.reject('file not exist')
            return
        }
        fs.unlink(savedFilePath, (err) => {
            if (err) {
                exec.reject(err.message)
            } else {
                exec.resolve()
            }
        })
    }
) as RemoveSavedFile

const SupportedHashAlgorithm = ['md5', 'sha1']
export const getFileInfo: GetFileInfo = defineAsyncApi<GetFileInfoOptions, GetFileInfoSuccess>(
    API_GET_FILE_INFO,
    function (options: GetFileInfoOptions, exec: ApiExecutor<GetFileInfoSuccess>) {
        const filePath = getFsPath(options.filePath);
        const digestAlgorithm = options.digestAlgorithm && SupportedHashAlgorithm.includes(options.digestAlgorithm) ? options.digestAlgorithm : 'md5'
        if (!fs.accessSync(filePath)) {
            exec.reject('file not exist')
            return
        }
        const stat = fs.statSync(filePath)
        if (!stat.isFile()) {
            exec.reject('file not exist')
        }
        Hash.hash(filePath, digestAlgorithm, (err, hash) => {
            if (err) {
                exec.reject(err.message)
            } else {
                exec.resolve({
                    size: stat.size,
                    digest: hash
                } as GetFileInfoSuccess)
            }
        })
    }
) as GetFileInfo