diff --git a/bundle.json b/bundle.json index ab34a9cc7fdb1b02661b94bb8d5d8f859dd15062..8d2e75611380e1e9fabf8851c6fb4857ef9d4ff0 100644 --- a/bundle.json +++ b/bundle.json @@ -12,22 +12,49 @@ "component": { "name": "file_api", "subsystem": "filemanagement", - "syscap": [], + "syscap": [ + "SystemCapability.FileManagement.File.FileIO", + "SystemCapability.FileManagement.File.Environment", + "SystemCapability.FileManagement.File.DistributedFile" + ], "features": [], "adapted_system_type": ["standard"], "rom": "", "ram": "", "deps": { "components": [ + "ability_base", "ability_manager", + "appexecfwk_base", + "appexecfwk_core", + "want", "libhilog", + "ipc_core", "ace_napi", "samgr_proxy" + ], + "third_party": [ + "e2fsprogs" ] }, "build": { - "sub_component": [ + "group_type": { + "base_group": [], + "fwk_group": [ "//foundation/filemanagement/file_api/interfaces/kits/js:build_kits_js" + ], + "service_group": [] + }, + "inner_kits": [ + { + "name": "//foundation/filemanagement/file_api/interfaces/kits/native:remote_uri_native", + "header": { + "header_files": [ + "remote_uri.h" + ], + "header_base": "//foundation/filemanagement/file_api/interfaces/kits/native/remote_uri" + } + } ] } } diff --git a/file_api.gni b/file_api.gni index 039aa4ed611572e20e9e0e5bdd7ba56437096a5f..578420983e86aec805404979c1c332c2e4316ab1 100644 --- a/file_api.gni +++ b/file_api.gni @@ -11,5 +11,5 @@ # See the License for the specific language governing permissions and # limitations under the License. -aafwk_kits_path = "//foundation/ability/ability_runtime/frameworks/kits" -aafwk_path = "//foundation/ability/ability_runtime" +aafwk_kits_path = "//foundation/ability/ability_runtime" +aafwk_path = "${aafwk_kits_path}/frameworks/kits" diff --git a/interfaces/kits/js/napi/@ohos.document.d.ts b/interfaces/kits/js/@ohos.document.d.ts similarity index 97% rename from interfaces/kits/js/napi/@ohos.document.d.ts rename to interfaces/kits/js/@ohos.document.d.ts index 88df1e0cfde75ca6f7ae55ea9ea1645e0ba2b3be..1333942fe64968a00d2c1895f5815ccee37d40d1 100644 --- a/interfaces/kits/js/napi/@ohos.document.d.ts +++ b/interfaces/kits/js/@ohos.document.d.ts @@ -1,63 +1,63 @@ -/* - * Copyright (c) 2021 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 { AsyncCallback } from './basic' - -export default document; - -/** - * document - * @syscap SystemCapability.FileManagement.UserFileService - * @since 6 - * @import import document from '@ohos.document'; - * @permission N/A - */ -declare namespace document { - export { choose }; - export { show }; -} - -/** - * choose. - * - * @note N/A - * @syscap SystemCapability.FileManagement.UserFileService - * @since 6 - * @permission N/A - * @function choose - * @param {string} type - type. - * @param {AsyncCallback} [callback] - callback. - * @returns {void | Promise} no callback return Promise otherwise return void - * @throws {TypedError} Parameter check failed - */ -declare function choose(types?: string[]): Promise; -declare function choose(callback: AsyncCallback): void; -declare function choose(types: string[], callback: AsyncCallback): void; - -/** - * show. - * - * @note N/A - * @syscap SystemCapability.FileManagement.UserFileService - * @since 6 - * @permission N/A - * @function show - * @param {string} uri - uri. - * @param {string} type - type. - * @param {AsyncCallback} [callback] - callback. - * @returns {void | Promise} no callback return Promise otherwise return void - * @throws {TypedError} Parameter check failed - */ -declare function show(uri: string, type: string): Promise; +/* + * Copyright (c) 2021 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 { AsyncCallback } from './basic' + +export default document; + +/** + * document + * @syscap SystemCapability.FileManagement.UserFileService + * @since 6 + * @import import document from '@ohos.document'; + * @permission N/A + */ +declare namespace document { + export { choose }; + export { show }; +} + +/** + * choose. + * + * @note N/A + * @syscap SystemCapability.FileManagement.UserFileService + * @since 6 + * @permission N/A + * @function choose + * @param {string} type - type. + * @param {AsyncCallback} [callback] - callback. + * @returns {void | Promise} no callback return Promise otherwise return void + * @throws {TypedError} Parameter check failed + */ +declare function choose(types?: string[]): Promise; +declare function choose(callback: AsyncCallback): void; +declare function choose(types: string[], callback: AsyncCallback): void; + +/** + * show. + * + * @note N/A + * @syscap SystemCapability.FileManagement.UserFileService + * @since 6 + * @permission N/A + * @function show + * @param {string} uri - uri. + * @param {string} type - type. + * @param {AsyncCallback} [callback] - callback. + * @returns {void | Promise} no callback return Promise otherwise return void + * @throws {TypedError} Parameter check failed + */ +declare function show(uri: string, type: string): Promise; declare function show(uri: string, type: string, callback: AsyncCallback): void; \ No newline at end of file diff --git a/interfaces/kits/js/napi/@ohos.environment.d.ts b/interfaces/kits/js/@ohos.environment.d.ts similarity index 96% rename from interfaces/kits/js/napi/@ohos.environment.d.ts rename to interfaces/kits/js/@ohos.environment.d.ts index 4ecb978046047db3a38db777c70b537bc8d6b874..0d29e0241bc85cce3ce6a5e3bd41b867c074896c 100644 --- a/interfaces/kits/js/napi/@ohos.environment.d.ts +++ b/interfaces/kits/js/@ohos.environment.d.ts @@ -1,41 +1,41 @@ -/* -* Copyright (C) 2021 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 {AsyncCallback, Callback} from "./basic"; - -/** - * Provides Environment APIs. - * - * @since 8 - * @syscap SystemCapability.FileManagement.File.Environment - */ -declare namespace Environment { - /** - * Get the user data path. - * - * @since 8 - */ - function getStorageDataDir(callback: AsyncCallback): void; - function getStorageDataDir(): Promise; - /** - * Get the User storage path. - * - * @since 8 - */ - function getUserDataDir(callback: AsyncCallback): void; - function getUserDataDir(): Promise; -} - -export default Environment; +/* +* Copyright (C) 2021 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 {AsyncCallback, Callback} from "./basic"; + +/** + * Provides Environment APIs. + * + * @since 8 + * @syscap SystemCapability.FileManagement.File.Environment + */ +declare namespace Environment { + /** + * Get the user data path. + * + * @since 8 + */ + function getStorageDataDir(callback: AsyncCallback): void; + function getStorageDataDir(): Promise; + /** + * Get the User storage path. + * + * @since 8 + */ + function getUserDataDir(callback: AsyncCallback): void; + function getUserDataDir(): Promise; +} + +export default Environment; diff --git a/interfaces/kits/js/napi/@ohos.statfs.d.ts b/interfaces/kits/js/@ohos.statfs.d.ts similarity index 96% rename from interfaces/kits/js/napi/@ohos.statfs.d.ts rename to interfaces/kits/js/@ohos.statfs.d.ts index 4a83f02b8e37d08348623e359707ad84a93daa99..2c714685c2823ede5c590ed733b5c247acd53699 100644 --- a/interfaces/kits/js/napi/@ohos.statfs.d.ts +++ b/interfaces/kits/js/@ohos.statfs.d.ts @@ -1,41 +1,42 @@ -/* -* Copyright (C) 2021 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 {AsyncCallback, Callback} from "./basic"; - -/** - * Provides filesystem statistics APIs - * - * @since 8 - * @syscap SystemCapability.FileManagement.File.FileIO - */ -declare namespace Statfs { - /** - * Get the number of free bytes on the specified path. - * - * @since 8 - */ - function getFreeBytes(path: string, callback: AsyncCallback): void; - function getFreeBytes(path: string): Promise; - /** - * Get the total number of bytes of the specified path. - * - * @since 8 - */ - function getTotalBytes(path: string, callback: AsyncCallback): void; - function getTotalBytes(path: string): Promise; -} - -export default Statfs; +/* +* Copyright (C) 2021 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 {AsyncCallback, Callback} from "./basic"; + +/** + * Provides filesystem statistics APIs + * + * @since 8 + * @syscap SystemCapability.FileManagement.File.FileIO + */ +declare namespace Statfs { + /** + * Get the number of free bytes on the specified path. + * + * @since 8 + */ + function getFreeBytes(path: string, callback: AsyncCallback): void; + function getFreeBytes(path: string): Promise; + /** + * Get the total number of bytes of the specified path. + * + * @since 8 + */ + function getTotalBytes(path: string, callback: AsyncCallback): void; + function getTotalBytes(path: string): Promise; + /** +} + +export default Statfs; diff --git a/interfaces/kits/js/BUILD.gn b/interfaces/kits/js/BUILD.gn index 9325a4b00b0ab8dbb0f63fecd32700f0976555cb..2125650d07796a100cdef2066dc18d7c7413b521 100644 --- a/interfaces/kits/js/BUILD.gn +++ b/interfaces/kits/js/BUILD.gn @@ -1,4 +1,4 @@ -# Copyright (c) 2021 Huawei Device Co., Ltd. +# Copyright (c) 2021-2022 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 @@ -32,14 +32,15 @@ ohos_shared_library("fileio") { relative_install_dir = "module" include_dirs = [ - "//foundation/arkui/napi/interfaces/kits", - "//foundation/filemanagement/file_api/interfaces/kits/js/src/common/file_helper", - "//foundation/filemanagement/file_api/interfaces/kits/js/src/common/napi", - "//foundation/filemanagement/file_api/interfaces/kits/js/src/common/napi/n_async", "//third_party/node/src", + "//foundation/arkui/napi/interfaces/kits", "//third_party/bounds_checking_function/include", "//third_party/libuv/include", "//third_party/openssl/include", + "//foundation/filemanagement/file_api/interfaces/kits/js/src/common/napi", + "//foundation/filemanagement/file_api/interfaces/kits/js/src/common/napi/n_async", + "//foundation/filemanagement/file_api/interfaces/kits/js/src/common/file_helper", + "//foundation/filemanagement/file_api/interfaces/kits/native/remote_uri", ] sources = file_common_src @@ -48,6 +49,7 @@ ohos_shared_library("fileio") { "src/mod_fileio/class_constants/constants.cpp", "src/mod_fileio/class_dir/dir_n_exporter.cpp", "src/mod_fileio/class_dirent/dirent_n_exporter.cpp", + "src/mod_fileio/class_randomaccessfile/randomaccessfile_n_exporter.cpp", "src/mod_fileio/class_stat/stat_n_exporter.cpp", "src/mod_fileio/class_stream/flush.cpp", "src/mod_fileio/class_stream/stream_n_exporter.cpp", @@ -58,6 +60,7 @@ ohos_shared_library("fileio") { "src/mod_fileio/properties/chown.cpp", "src/mod_fileio/properties/close.cpp", "src/mod_fileio/properties/copy_file.cpp", + "src/mod_fileio/properties/create_randomaccessfile.cpp", "src/mod_fileio/properties/create_stream.cpp", "src/mod_fileio/properties/fchmod.cpp", "src/mod_fileio/properties/fchown.cpp", @@ -76,9 +79,11 @@ ohos_shared_library("fileio") { "src/mod_fileio/properties/open_dir.cpp", "src/mod_fileio/properties/posix_fallocate.cpp", "src/mod_fileio/properties/prop_n_exporter.cpp", + "src/mod_fileio/properties/read_dir.cpp", "src/mod_fileio/properties/read_text.cpp", "src/mod_fileio/properties/rename.cpp", "src/mod_fileio/properties/rmdir.cpp", + "src/mod_fileio/properties/rmdirent.cpp", "src/mod_fileio/properties/stat.cpp", "src/mod_fileio/properties/symlink.cpp", "src/mod_fileio/properties/truncate.cpp", @@ -87,6 +92,7 @@ ohos_shared_library("fileio") { deps = [ "//foundation/arkui/napi:ace_napi", + "//foundation/filemanagement/file_api/interfaces/kits/native:remote_uri_native", "//third_party/bounds_checking_function:libsec_static", "//third_party/openssl:libcrypto_static", ] @@ -101,12 +107,12 @@ ohos_shared_library("file") { relative_install_dir = "module" include_dirs = [ + "//third_party/node/src", "//foundation/arkui/napi/interfaces/kits", + "//third_party/bounds_checking_function/include", "//foundation/filemanagement/file_api/interfaces/kits/js/src/common/napi", "//foundation/filemanagement/file_api/interfaces/kits/js/src/common/napi/n_async", "//foundation/filemanagement/file_api/interfaces/kits/js/src/common/file_helper", - "//third_party/node/src", - "//third_party/bounds_checking_function/include", ] sources = file_common_src @@ -118,15 +124,12 @@ ohos_shared_library("file") { ] deps = [ - "${aafwk_kits_path}/ability/native:abilitykit_native", + "${aafwk_kits_path}/frameworks/native/ability/native:abilitykit_native", "//foundation/arkui/napi:ace_napi", "//third_party/bounds_checking_function:libsec_static", ] - external_deps = [ - "eventhandler:libeventhandler", - "hiviewdfx_hilog_native:libhilog", - ] + external_deps = [ "hiviewdfx_hilog_native:libhilog" ] } ohos_shared_library("statfs") { @@ -155,9 +158,9 @@ ohos_shared_library("environment") { relative_install_dir = "module" include_dirs = [ + "//third_party/node/src", "//foundation/arkui/napi/interfaces/kits", "//foundation/filemanagement/file_api/interfaces/kits/js/src/common/napi/n_async", - "//third_party/node/src", ] sources = [ @@ -209,9 +212,9 @@ ohos_shared_library("document") { relative_install_dir = "module" include_dirs = [ + "//third_party/node/src", "//foundation/arkui/napi/interfaces/kits", "//foundation/filemanagement/file_api/interfaces/kits/js/src/common/napi/n_async", - "//third_party/node/src", ] sources = [ diff --git a/interfaces/kits/js/napi/@ohos.fileio.d.ts b/interfaces/kits/js/napi/@ohos.fileio.d.ts deleted file mode 100644 index d074897db66b2d0b83bb97b2901da646653e741e..0000000000000000000000000000000000000000 --- a/interfaces/kits/js/napi/@ohos.fileio.d.ts +++ /dev/null @@ -1,1548 +0,0 @@ -/* - * Copyright (c) 2021 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 { AsyncCallback } from './basic' - -export default fileIO; - -/** - * fileio - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 6 - * @import import fileio from '@ohos.fileio'; - * @permission N/A - */ -declare namespace fileIO { - export { access }; - export { accessSync }; - export { chmod }; - export { chmodSync }; - export { chown }; - export { chownSync }; - export { close }; - export { closeSync }; - export { copyFile }; - export { copyFileSync }; - export { createStream }; - export { createStreamSync }; - export { createWatcher }; - export { fchmod }; - export { fchmodSync }; - export { fchown }; - export { fchownSync }; - export { fdatasync }; - export { fdatasyncSync }; - export { fdopenStream }; - export { fdopenStreamSync }; - export { fstat }; - export { fstatSync }; - export { fsync }; - export { fsyncSync }; - export { ftruncate }; - export { ftruncateSync }; - export { hash }; - export { lchown }; - export { lchownSync }; - export { lstat }; - export { lstatSync }; - export { mkdir }; - export { mkdirSync }; - export { mkdtemp }; - export { mkdtempSync }; - export { open }; - export { openSync }; - export { opendir }; - export { opendirSync }; - export { read }; - export { readSync }; - export { readText }; - export { readTextSync }; - export { rename }; - export { renameSync }; - export { rmdir }; - export { rmdirSync }; - export { stat }; - export { statSync }; - export { symlink }; - export { symlinkSync }; - export { truncate }; - export { truncateSync }; - export { unlink }; - export { unlinkSync }; - export { write }; - export { writeSync }; - export { Dir }; - export { Dirent }; - export { ReadOut }; - export { Stat }; - export { Stream }; - export { Watcher }; -} - -/** - * access. - * - * @note N/A - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 6 - * @permission N/A - * @function access - * @param {string} path - path. - * @param {number} [mode = 0] - mode. - * @param {AsyncCallback} [callback] - callback. - * @returns {void | Promise} no callback return Promise otherwise return void - * @throws {TypedError} Parameter check failed - */ -declare function access(path: string, mode?: number): Promise; -declare function access(path: string, callback: AsyncCallback): void; -declare function access(path: string, mode: number, callback: AsyncCallback): void; -/** - * accessSync. - * - * @note N/A - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 6 - * @permission N/A - * @function accessSync - * @param {string} path - path. - * @param {number} [mode = 0] - mode. - * @returns {void} access success - * @throws {TypedError | Error} access fail - */ -declare function accessSync(path: string, mode?: number): void; -/** - * close. - * - * @note N/A - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 7 - * @permission N/A - * @function close - * @param {number} fd - fd. - * @param {AsyncCallback} [callback] - callback. - * @returns {void | Promise} no callback return Promise otherwise return void - * @throws {TypedError} Parameter check failed - */ -declare function close(fd: number): Promise; -declare function close(fd: number, callback: AsyncCallback): void; -/** - * closeSync. - * - * @note N/A - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 6 - * @permission N/A - * @function closeSync - * @param {number} fd - fd. - * @returns {void} close success - * @throws {TypedError | Error} close fail - */ -declare function closeSync(fd: number): void; -/** - * copyFile. - * - * @note N/A - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 6 - * @permission N/A - * @function copyFile - * @param {string | number} src - src. - * @param {string | number} dest - dest. - * @param {number} [mode = 0] - mode. - * @param {AsyncCallback} [callback] - callback. - * @returns {void | Promise} no callback return Promise otherwise return void - * @throws {TypedError} Parameter check failed - */ -declare function copyFile(src: string | number, dest: string | number, mode?: number): Promise; -declare function copyFile(src: string | number, dest: string | number, callback: AsyncCallback): void; -declare function copyFile(src: string | number, dest: string | number, mode: number, callback: AsyncCallback): void; -/** - * copyFileSync. - * - * @note N/A - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 6 - * @permission N/A - * @function copyFileSync - * @param {string | number} src - src. - * @param {string | number} dest - dest. - * @param {number} [mode = 0] - mode. - * @returns {void} copyFile success - * @throws {TypedError | Error} copyFile fail - */ -declare function copyFileSync(src: string | number, dest: string | number, mode?: number): void; -/** - * createStream. - * - * @note N/A - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 7 - * @permission N/A - * @function createStream - * @param {string} path - path. - * @param {string} mode - mode. - * @param {AsyncCallback} [callback] - callback. - * @returns {void | Promise} no callback return Promise otherwise return Stream - * @throws {TypedError} Parameter check failed - */ -declare function createStream(path: string, mode: string): Promise; -declare function createStream(path: string, mode: string, callback: AsyncCallback): void; -/** - * createStreamSync. - * - * @note N/A - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 7 - * @permission N/A - * @function createStreamSync - * @param {string} path - path. - * @param {string} mode - mode. - * @returns {Stream} createStream - * @throws {TypedError} Parameter check failed - */ -declare function createStreamSync(path: string, mode: string): Stream; -/** - * chown. - * - * @note N/A - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 7 - * @permission N/A - * @function appendFile - * @param {string} path - path. - * @param {number} uid - mode. - * @param {number} gid - mode. - * @param {AsyncCallback} [callback] - callback. - * @returns {void | Promise} no callback return Promise otherwise return void - * @throws {TypedError} Parameter check failed - */ -declare function chown(path: string, uid: number, gid: number): Promise; -declare function chown(path: string, uid: number, gid: number, callback: AsyncCallback): void; -/** - * chownSync. - * - * @note N/A - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 7 - * @permission N/A - * @function appendFile - * @param {string} path - path. - * @param {number} uid - mode. - * @param {number} gid - mode. - * @returns {void} chown success - * @throws {TypedError | Error} chown fail - */ -declare function chownSync(path: string, uid: number, gid: number): void; -/** - * chmod. - * - * @note N/A - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 7 - * @permission N/A - * @function chmod - * @param {string} path - path. - * @param {number} mode - mode. - * @param {AsyncCallback} [callback] - callback. - * @returns {void | Promise} no callback return Promise otherwise return void - * @throws {TypedError} Parameter check failed - */ -declare function chmod(path: string, mode: number): Promise; -declare function chmod(path: string, mode: number, callback: AsyncCallback): void; -/** - * chmodSync. - * - * @note N/A - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 7 - * @permission N/A - * @function chmodSync - * @param {string} path - path. - * @param {number} mode - mode. - * @returns {void} chmod success - * @throws {TypedError | Error} chmod fail - */ -declare function chmodSync(path: string, mode: number): void; -/** - * ftruncate. - * - * @note N/A - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 7 - * @permission N/A - * @function ftruncate - * @param {number} fd - fd. - * @param {number} [len = 0] - len. - * @param {AsyncCallback} [callback] - callback. - * @returns {void | Promise} no callback return Promise otherwise return void - * @throws {TypedError} Parameter check failed - */ -declare function ftruncate(fd: number, len?: number): Promise; -declare function ftruncate(fd: number, callback: AsyncCallback): void; -declare function ftruncate(fd: number, len: number, callback: AsyncCallback): void; -/** - * ftruncateSync. - * - * @note N/A - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 7 - * @permission N/A - * @function ftruncateSync - * @param {number} fd - fd. - * @param {number} [len = 0] - len. - * @returns {void} ftruncate success - * @throws {TypedError | Error} ftruncate fail - */ -declare function ftruncateSync(fd: number, len?: number): void; -/** - * fsync. - * - * @note N/A - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 7 - * @permission N/A - * @function fsync - * @param {number} fd - fd. - * @param {AsyncCallback} [callback] - callback. - * @returns {void | Promise} no callback return Promise otherwise return void - * @throws {TypedError} Parameter check failed - */ -declare function fsync(fd: number): Promise; -declare function fsync(fd: number, callback: AsyncCallback): void; -/** - * fsyncSync. - * - * @note N/A - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 7 - * @permission N/A - * @function fsyncSync - * @param {number} fd - fd. - * @returns {void} fsync success - * @throws {TypedError | Error} fsync fail - */ -declare function fsyncSync(fd: number): void; -/** - * fstat. - * - * @note N/A - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 7 - * @permission N/A - * @function fstat - * @param {number} fd - fd. - * @returns {Stat} - * @throws {TypedError | Error} fstat fail - */ -declare function fstat(fd: number): Promise; -declare function fstat(fd: number, callback: AsyncCallback): void; -/** - * fstatSync. - * - * @note N/A - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 7 - * @permission N/A - * @function fstatSync - * @param {number} fd - fd. - * @returns {Stat} - * @throws {TypedError | Error} fstat fail - */ -declare function fstatSync(fd: number): Stat; -/** - * fdatasync. - * - * @note N/A - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 7 - * @permission N/A - * @function fdatasync - * @param {number} fd - fd. - * @param {AsyncCallback} [callback] - callback. - * @returns {void | Promise} no callback return Promise otherwise return void - * @throws {TypedError} Parameter check failed - */ -declare function fdatasync(fd: number): Promise; -declare function fdatasync(fd: number, callback: AsyncCallback): void; -/** - * fdatasyncSync. - * - * @note N/A - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 7 - * @permission N/A - * @function fdatasyncSync - * @param {number} fd - fd. - * @returns {void} fdatasync success - * @throws {TypedError | Error} fdatasync fail - */ -declare function fdatasyncSync(fd: number): void; -/** - * fchown. - * - * @note N/A - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 7 - * @permission N/A - * @function fchown - * @param {number} fd - fd. - * @param {number} uid - uid. - * @param {number} gid - gid. - * @param {AsyncCallback} [callback] - callback. - * @returns {void | Promise} no callback return Promise otherwise return void - * @throws {TypedError} Parameter check failed - */ -declare function fchown(fd: number, uid: number, gid: number): Promise; -declare function fchown(fd: number, uid: number, gid: number, callback: AsyncCallback): void; -/** - * fchownSync. - * - * @note N/A - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 7 - * @permission N/A - * @function fchownSync - * @param {number} fd - fd. - * @param {number} uid - uid. - * @param {number} gid - gid. - * @returns {void} fchown success - * @throws {TypedError | Error} fchown fail - */ -declare function fchownSync(fd: number, uid: number, gid: number): void; -/** - * fchmod. - * - * @note N/A - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 7 - * @permission N/A - * @function fchmod - * @param {number} fd - fd. - * @param {number} mode - mode. - * @param {AsyncCallback} [callback] - callback. - * @returns {void | Promise} no callback return Promise otherwise return void - * @throws {TypedError} Parameter check failed - */ -declare function fchmod(fd: number, mode: number): Promise; -declare function fchmod(fd: number, mode: number, callback: AsyncCallback): void; -/** - * fchmodSync. - * - * @note N/A - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 7 - * @permission N/A - * @function fchmodSync - * @param {number} fd - fd. - * @param {number} mode - mode. - * @returns {void} fchmod success - * @throws {TypedError | Error} fchmod fail - */ -declare function fchmodSync(fd: number, mode: number): void; -/** - * fdopenStream. - * @note N/A - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 7 - * @permission N/A - * @function fdopenStream - * @param {number} fd - fd. - * @param {string} mode - mode. - * @param {AsyncCallback} [callback] - callback. - * @returns {void | Promise} no callback return Promise otherwise return void - * @throws {TypedError} Parameter check failed - */ -declare function fdopenStream(fd: number, mode: string): Promise; -declare function fdopenStream(fd: number, mode: string, callback: AsyncCallback): void; -/** - * fdopenStreamSync. - * @note N/A - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 7 - * @permission N/A - * @function fdopenStreamSync - * @param {number} fd - fd. - * @param {string} mode - mode. - * @returns {Stream} open stream from fd - * @throws {TypedError | Error} open fail - */ -declare function fdopenStreamSync(fd: number, mode: string): Stream; - /** - * hash. - * @static - * @note N/A - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 6 - * @permission N/A - * @function hash - * @param {string} path - path. - * @param {string} algorithm - algorithm md5 sha1 sha256. - * @param {AsyncCallback} [callback] - callback. - * @returns {void | Promise} no callback return Promise otherwise return void - * @throws {TypedError} Parameter check failed - */ -declare function hash(path: string, algorithm: string): Promise; -declare function hash(path: string, algorithm: string, callback: AsyncCallback): void; -/** - * lchown. - * - * @note N/A - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 7 - * @permission N/A - * @function lchown - * @param {string} path - path. - * @param {number} uid - uid. - * @param {number} gid - gid. - * @param {AsyncCallback} [callback] - callback. - * @returns {void | Promise} no callback return Promise otherwise return void - * @throws {TypedError} Parameter check failed - */ -declare function lchown(path: string, uid: number, gid: number): Promise; -declare function lchown(path: string, uid: number, gid: number, callback: AsyncCallback): void; -/** - * lchownSync. - * - * @note N/A - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 7 - * @permission N/A - * @function lchownSync - * @param {string} path - path. - * @param {number} uid - uid. - * @param {number} gid - gid. - * @returns {void} lchown success - * @throws {TypedError | Error} lchown fail - */ -declare function lchownSync(path: string, uid: number, gid: number): void; -/** - * lstat. - * - * @note N/A - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 7 - * @permission N/A - * @function lstat - * @param {string} path - path. - * @param {AsyncCallback} [callback] - callback. - * @returns {void | Promise} no callback return Promise otherwise return void - * @throws {TypedError} Parameter check failed - */ -declare function lstat(path: string): Promise; -declare function lstat(path: string, callback: AsyncCallback): void; -/** - * lstatSync. - * - * @note N/A - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 7 - * @permission N/A - * @function lstatSync - * @param {string} path - path. - * @returns {Stat} lstat success - * @throws {TypedError | Error} lstat fail - */ -declare function lstatSync(path: string): Stat; -/** - * mkdir. - * - * @note N/A - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 6 - * @permission N/A - * @function mkdir - * @param {string} path - path. - * @param {number} [mode = 0o775] - path. - * @param {AsyncCallback} [callback] - callback. - * @returns {void | Promise} no callback return Promise otherwise return void - * @throws {TypedError} Parameter check failed - */ -declare function mkdir(path: string, mode?: number): Promise; -declare function mkdir(path: string, callback: AsyncCallback): void; -declare function mkdir(path: string, mode: number, callback: AsyncCallback): void; -/** - * mkdirSync. - * - * @note N/A - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 6 - * @permission N/A - * @function mkdirSync - * @param {string} path - path. - * @param {number} [mode = 0o775] - path. - * @returns {void} mkdir success - * @throws {TypedError | Error} mkdir fail - */ -declare function mkdirSync(path: string, mode?: number): void; -/** - * mkdtemp. - * - * @note N/A - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 7 - * @permission N/A - * @function mkdtemp - * @param {string} prefix - dir prefix. - * @param {AsyncCallback} [callback] - callback. - * @returns {void | Promise} no callback return Promise otherwise return void - * @throws {TypedError} Parameter check failed - */ -declare function mkdtemp(prefix: string): Promise; -declare function mkdtemp(prefix: string, callback: AsyncCallback): void; -/** - * mkdtempSync. - * - * @note N/A - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 7 - * @permission N/A - * @function mkdtempSync - * @param {string} prefix - dir prefix. - * @returns {string} directory name - * @throws {TypedError | Error} mkdtemp fail - */ -declare function mkdtempSync(prefix: string): string; -/** - * open. - * - * @note N/A - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 7 - * @permission N/A - * @function open - * @param {string} path - path. - * @param {number} [flags = 0] - flags. - * @param {number} [mode = 0o666] - mode. - * @param {AsyncCallback} [callback] - callback. - * @returns {void | Promise} no callback return Promise otherwise return void - * @throws {TypedError} Parameter check failed - */ -declare function open(path: string, flags?: number, mode?: number): Promise; -declare function open(path: string, callback: AsyncCallback): void; -declare function open(path: string, flags: number, callback: AsyncCallback): void; -declare function open(path: string, flags: number, mode: number, callback: AsyncCallback): void; -/** - * openSync. - * - * @note N/A - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 6 - * @permission N/A - * @function openSync - * @param {string} path - path. - * @param {number} [flags = 0] - flags. - * @param {number} [mode = 0o666] - mode. - * @returns {number} open fd - * @throws {TypedError | Error} open fail - */ -declare function openSync(path: string, flags?: number, mode?: number): number; -/** - * opendir. - * - * @note N/A - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 6 - * @permission N/A - * @function opendir - * @param {string} path - directory name. - * @param {AsyncCallback} [callback] - callback. - * @returns {void | Promise} no callback return Promise otherwise return void - * @throws {TypedError} Parameter check failed - */ -declare function opendir(path: string): Promise; -declare function opendir(path: string, callback: AsyncCallback): void; -/** - * opendirSync. - * - * @param {string} path - directory name. - * @returns {Dir} opendir Dir Object - * @throws {TypedError | Error} opendir fail - */ -declare function opendirSync(path: string): Dir; -/** - * readText. - * - * @note N/A - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 7 - * @permission N/A - * @function readText - * @param {string} filePath - file path. - * @param {Object} [options] - options. - * @param {number} [options.offset = 0] - offset in bytes. - * @param {number} [options.length = -1] - length in bytes. - * @param {number} [options.encoding = 'utf-8'] - encoding. - * @param {AsyncCallback} [callback] - callback. - * @returns {void | Promise} no callback return Promise otherwise return void - * @throws {TypedError} Parameter check failed - */ -declare function readText(filePath: string, options?: { - position?: number; - length?: number; - encoding?: string; -}): Promise; -declare function readText(filePath: string, options: { - position?: number; - length?: number; - encoding?: string; -}, callback: AsyncCallback): void; - -/** - * readTextSync. - * - * @note N/A - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 7 - * @permission N/A - * @function readTextSync - * @param {string} filePath - file path. - * @param {Object} [options] - options. - * @param {number} [options.offset = 0] - offset in bytes. - * @param {number} [options.length = -1] - length in bytes. - * @param {number} [options.encoding = 'utf-8'] - encoding. - * @returns {string} readout result - * @throws {TypedError} Parameter check failed - */ -declare function readTextSync(filePath: string, options?: { - position?: number; - length?: number; - encoding?: string; -}): string; - -/** - * read. - * - * @note N/A - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 6 - * @permission N/A - * @function read - * @param {number} fd - file descriptor. - * @param {ArrayBuffer} buffer - file descriptor. - * @param {Object} [options] - options. - * @param {number} [options.offset = 0] - offset. - * @param {number} [options.length = -1] - length. - * @param {number} [options.position = -1] - position. - * @param {AsyncCallback} [callback] - callback. - * @returns {void | Promise} no callback return Promise otherwise return void - * @throws {TypedError} Parameter check failed - */ -declare function read(fd: number, buffer: ArrayBuffer, options?: { - offset?: number; - length?: number; - position?: number; -}): Promise -declare function read(fd: number, buffer: ArrayBuffer, callback: AsyncCallback): void; -declare function read(fd: number, buffer: ArrayBuffer, options: { - offset?: number; - length?: number; - position?: number; -}, callback: AsyncCallback): void; -/** - * readSync. - * - * @note N/A - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 6 - * @permission N/A - * @function readSync - * @param {number} fd - file descriptor. - * @param {ArrayBuffer} buffer - file descriptor. - * @param {Object} [options] - options. - * @param {number} [options.offset = 0] - offset. - * @param {number} [options.length = -1] - length. - * @param {number} [options.position = -1] - position. - * @returns {number} number of bytesRead - * @throws {TypedError | Error} read fail - */ -declare function readSync(fd: number, buffer: ArrayBuffer, options?: { - offset?: number; - length?: number; - position?: number; -}): number; -/** - * rename. - * - * @note N/A - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 7 - * @permission N/A - * @function rename - * @param {string} oldPath - oldPath. - * @param {string} newPath - newPath. - * @param {AsyncCallback} [callback] - callback. - * @returns {void | Promise} no callback return Promise otherwise return void - * @throws {TypedError} Parameter check failed - */ -declare function rename(oldPath: string, newPath: string): Promise; -declare function rename(oldPath: string, newPath: string, callback: AsyncCallback): void; -/** - * renameSync. - * - * @note N/A - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 7 - * @permission N/A - * @function renameSync - * @param {string} oldPath - oldPath. - * @param {string} newPath - newPath. - * @returns {void} rename success - * @throws {TypedError | Error} rename fail - */ -declare function renameSync(oldPath: string, newPath: string): void; -/** - * rmdir. - * - * @note N/A - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 7 - * @permission N/A - * @function rmdir - * @param {string} path - path. - * @param {AsyncCallback} [callback] - callback. - * @returns {void | Promise} no callback return Promise otherwise return void - * @throws {TypedError} Parameter check failed - */ -declare function rmdir(path: string): Promise; -declare function rmdir(path: string, callback: AsyncCallback): void; -/** - * rmdirSync. - * - * @note N/A - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 7 - * @permission N/A - * @function rmdirSync - * @param {string} path - path. - * @returns {void} rmdir success - * @throws {TypedError | Error} rmdir fail - */ -declare function rmdirSync(path: string): void; -/** - * stat. - * @static - * @note N/A - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 6 - * @permission N/A - * @param {string} path - path. - * @param {AsyncCallback} [callback] - callback. - * @returns {void | Promise} no callback return Promise otherwise return void - * @throws {TypedError} Parameter check failed - */ -declare function stat(path: string): Promise; -declare function stat(path: string, callback: AsyncCallback): void; -/** - * statSync. - * @static - * @note N/A - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 6 - * @permission N/A - * @param {string} path - path. - * @returns {Stat} stat success - * @throws {TypedError | Error} stat fail - */ -declare function statSync(path: string): Stat; -/** - * symlink. - * - * @note N/A - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 7 - * @permission N/A - * @function symlink - * @param {string} target - target. - * @param {string} srcPath - srcPath. - * @param {AsyncCallback} [callback] - callback. - * @returns {void | Promise} no callback return Promise otherwise return void - * @throws {TypedError} Parameter check failed - */ -declare function symlink(target: string, srcPath: string): Promise; -declare function symlink(target: string, srcPath: string, callback: AsyncCallback): void; -/** - * symlinkSync. - * - * @note N/A - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 7 - * @permission N/A - * @function symlinkSync - * @param {string} target - target. - * @param {string} srcPath - srcPath. - * @returns {void} symlink success - * @throws {TypedError | Error} symlink fail - */ - declare function symlinkSync(target: string, srcPath: string): void; - /** - * truncate. - * - * @note N/A - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 7 - * @permission N/A - * @function truncate - * @param {string} path - path. - * @param {number} [len = 0] - len. - * @param {AsyncCallback} [callback] - callback. - * @returns {void | Promise} no callback return Promise otherwise return void - * @throws {TypedError} Parameter check failed - */ -declare function truncate(path: string, len?: number): Promise; -declare function truncate(path: string, callback: AsyncCallback): void; -declare function truncate(path: string, len: number, callback: AsyncCallback): void; -/** - * truncateSync. - * - * @note N/A - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 7 - * @permission N/A - * @function truncateSync - * @param {string} path - path. - * @param {number} [len = 0] - len. - * @returns {void} truncate success - * @throws {TypedError | Error} truncate fail - */ -declare function truncateSync(path: string, len?: number): void; -/** - * unlink. - * - * @note N/A - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 6 - * @permission N/A - * @function unlink - * @param {string} path - path. - * @param {AsyncCallback} [callback] - callback. - * @returns {void | Promise} no callback return Promise otherwise return void - * @throws {TypedError} Parameter check failed - */ -declare function unlink(path: string): Promise; -declare function unlink(path: string, callback: AsyncCallback): void; -/** - * unlinkSync. - * - * @note N/A - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 6 - * @permission N/A - * @function unlinkSync - * @param {string} path - path. - * @returns {void} unlink success - * @throws {TypedError | Error} unlink fail - */ -declare function unlinkSync(path: string): void; -/** - * write. - * - * @note N/A - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 6 - * @permission N/A - * @function write - * @param {number} fd - file descriptor. - * @param {ArrayBuffer | string} buffer - file descriptor. - * @param {Object} [options] - options. - * @param {number} [options.offset = 0] - offset(bytes) ignored when buffer is string. - * @param {number} [options.length = -1] - length(bytes) ignored when buffer is string. - * @param {number} [options.position = -1] - position(bytes) where start to write < 0 use read, else use pread. - * @param {string} [options.encoding = 'utf-8'] - encoding. - * @param {AsyncCallback} [callback] - callback. - * @returns {void | Promise} no callback return Promise otherwise return void - * @throws {TypedError | RangeError} Parameter check failed - */ -declare function write(fd: number, buffer: ArrayBuffer | string, options?: { - offset?: number; - length?: number; - position?: number; - encoding?: string; -}): Promise; -declare function write(fd: number, buffer: ArrayBuffer | string, callback: AsyncCallback): void; -declare function write(fd: number, buffer: ArrayBuffer | string, options: { - offset?: number; - length?: number; - position?: number; - encoding?: string; -}, callback: AsyncCallback): void; -/** - * writeSync. - * - * @note N/A - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 6 - * @permission N/A - * @function writeSync - * @param {number} fd - file descriptor. - * @param {ArrayBuffer | string} buffer - file descriptor. - * @param {Object} [options] - options. - * @param {number} [options.offset = 0] - offset(bytes) ignored when buffer is string. - * @param {number} [options.length = -1] - length(bytes) ignored when buffer is string. - * @param {number} [options.position = -1] - position(bytes) where start to write < 0 use read, else use pread. - * @param {string} [options.encoding = 'utf-8'] - encoding. - * @returns {number} on success number of bytesRead - * @throws {TypedError | RangeError | Error} write fail - */ -declare function writeSync(fd: number, buffer: ArrayBuffer | string, options?: { - offset?: number; - length?: number; - position?: number; - encoding?: string; -}): number; - -/** - * createWatcher. - * - * @note N/A - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 7 - * @permission N/A - * @function createWatcher - * @param {string} filename - filename. - * @param {number} events - events(depends on OS & filesystem) events = 1 rename events =2 change. - * @param {AsyncCallback} [callback] - callback. - * @returns {Watcher} watch success - * @throws {TypedError | Error} watch fail - */ -declare function createWatcher(filename: string, events: number, callback: AsyncCallback): Watcher; -/** - * Dir - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 6 - * @permission N/A - */ -declare interface Dir { - /** - * read. - * - * @note N/A - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 6 - * @permission N/A - * @function read - * @param {AsyncCallback} [callback] - callback. - * @returns {void | Promise} no callback return Promise otherwise return void - * @throws {TypedError} Parameter check failed if read to end, Error.msg = "NoMore" - */ - read(): Promise; - read(callback: AsyncCallback): void; - /** - * readSync. - * @note N/A - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 6 - * @permission N/A - * @function readSync - * @returns {Dirent} Dirent Object - * @throws {TypedError | Error} read fail if read to end, Error.msg = "NoMore" - */ - readSync(): Dirent; - /** - * close. - * @note N/A - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 7 - * @permission N/A - * @function close - * @param {AsyncCallback} [callback] - callback. - * @returns {void | Promise} close success - * @throws {TypedError | Error} close fail - */ - close(): Promise; - close(callback: AsyncCallback): void; - /** - * closeSync. - * @note N/A - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 6 - * @permission N/A - * @function closeSync - * @returns {void} close success - * @throws {TypedError | Error} close fail - */ - closeSync(): void; -} - -/** - * Dirent - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 6 - * @permission N/A - */ -declare interface Dirent { - /** - * @type {string} - * @readonly - * @note N/A - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 6 - * @permission N/A - */ - readonly name: string; - /** - * isBlockDevice. - * @note N/A - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 6 - * @permission N/A - * @returns {boolean} is or not - */ - isBlockDevice(): boolean; - /** - * isCharacterDevice. - * @note N/A - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 6 - * @permission N/A - * @returns {boolean} is or not - */ - isCharacterDevice(): boolean; - /** - * isDirectory. - * @note N/A - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 6 - * @permission N/A - * @returns {boolean} is or not - */ - isDirectory(): boolean; - /** - * isFIFO. - * @note N/A - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 6 - * @permission N/A - * @returns {boolean} is or not - */ - isFIFO(): boolean; - /** - * isFile. - * @note N/A - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 6 - * @permission N/A - * @returns {boolean} is or not - */ - isFile(): boolean; - /** - * isSocket. - * @note N/A - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 6 - * @permission N/A - * @returns {boolean} is or not - */ - isSocket(): boolean; - /** - * isSymbolicLink. - * @note N/A - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 6 - * @permission N/A - * @returns {boolean} is or not - */ - isSymbolicLink(): boolean; -} - -/** - * Stat - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 6 - * @permission N/A - */ -declare interface Stat { - /** - * @type {number} - * @note N/A - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 6 - * @permission N/A - * @readonly - */ - readonly dev: number; - /** - * @type {number} - * @note N/A - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 6 - * @permission N/A - * @readonly - */ - readonly ino: number; - /** - * @type {number} - * @note N/A - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 6 - * @permission N/A - * @readonly - */ - readonly mode: number; - /** - * @type {number} - * @note N/A - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 6 - * @permission N/A - * @readonly - */ - readonly nlink: number; - /** - * @type {number} - * @note N/A - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 6 - * @permission N/A - * @readonly - */ - readonly uid: number; - /** - * @type {number} - * @note N/A - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 6 - * @permission N/A - * @readonly - */ - readonly gid: number; - /** - * @type {number} - * @note N/A - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 6 - * @permission N/A - * @readonly - */ - readonly rdev: number; - /** - * @type {number} - * @note N/A - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 6 - * @permission N/A - * @readonly - */ - readonly size: number; - /** - * @type {number} - * @note N/A - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 6 - * @permission N/A - * @readonly - */ - readonly blocks: number; - /** - * @type {number} - * @note N/A - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 6 - * @permission N/A - * @readonly - */ - readonly atime: number; - /** - * @type {number} - * @note N/A - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 6 - * @permission N/A - * @readonly - */ - readonly mtime: number; - /** - * @type {number} - * @note N/A - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 6 - * @permission N/A - * @readonly - */ - readonly ctime: number; - /** - * isBlockDevice. - * @note N/A - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 6 - * @permission N/A - * @returns {boolean} is or not - */ - isBlockDevice(): boolean; - /** - * isCharacterDevice. - * @note N/A - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 6 - * @permission N/A - * @returns {boolean} is or not - */ - isCharacterDevice(): boolean; - /** - * isDirectory. - * @note N/A - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 6 - * @permission N/A - * @returns {boolean} is or not - */ - isDirectory(): boolean; - /** - * isFIFO. - * @note N/A - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 6 - * @permission N/A - * @returns {boolean} is or not - */ - isFIFO(): boolean; - /** - * isFile. - * @note N/A - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 6 - * @permission N/A - * @returns {boolean} is or not - */ - isFile(): boolean; - /** - * isSocket. - * @note N/A - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 6 - * @permission N/A - * @returns {boolean} is or not - */ - isSocket(): boolean; - /** - * isSymbolicLink. - * @note N/A - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 6 - * @permission N/A - * @returns {boolean} is or not - */ - isSymbolicLink(): boolean; -} - -/** - * Stream - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 6 - * @permission N/A - */ -declare interface Stream { - /** - * close. - * - * @note N/A - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 7 - * @permission N/A - * @param {AsyncCallback} [callback] - callback. - * @returns {void | Promise} close success - * @throws {TypedError | Error} close fail - */ - close(): Promise; - close(callback: AsyncCallback): void; - /** - * closeSync. - * - * @note N/A - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 6 - * @permission N/A - * @returns {void} close success - * @throws {TypedError | Error} close fail - */ - closeSync(): void; - /** - * flush. - * - * @note N/A - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 7 - * @permission N/A - * @param {AsyncCallback} [callback] - callback. - * @returns {void | Promise} no callback return Promise otherwise return void - * @throws {TypedError} Parameter check failed - */ - flush(): Promise; - flush(callback: AsyncCallback): void; - /** - * flushSync. - * - * @note N/A - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 7 - * @permission N/A - * @returns {void} flush success - * @throws {Error} flush fail - */ - flushSync(): void; - /** - * write. - * - * @note N/A - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 7 - * @permission N/A - * @param {ArrayBuffer | string} buffer - file description. - * @param {Object} [options] - options. - * @param {number} [options.offset = 0] - offset(bytes) ignored when buffer is string. - * @param {number} [options.length = -1] - length(bytes) ignored when buffer is string. - * @param {number} [options.position = -1] - position(bytes) where start to write < 0 use read, else use pread. - * @param {string} [options.encoding = 'utf-8'] - encoding. - * @param {AsyncCallback} [callback] - callback. - * @returns {void | Promise} no callback return Promise otherwise return void - * @throws {TypedError} Parameter check failed - */ - write(buffer: ArrayBuffer | string, options?: { - offset?: number; - length?: number; - position?: number; - encoding?: string; - }): Promise; - write(buffer: ArrayBuffer | string, callback: AsyncCallback): void; - write(buffer: ArrayBuffer | string, options: { - offset?: number; - length?: number; - position?: number; - encoding?: string; - }, callback: AsyncCallback): void; - /** - * writeSync. - * - * @note N/A - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 7 - * @permission N/A - * @param {ArrayBuffer | string} buffer - file description. - * @param {Object} [options] - options. - * @param {number} [options.offset = 0] - offset(bytes) ignored when buffer is string. - * @param {number} [options.length = -1] - length(bytes) ignored when buffer is string. - * @param {number} [options.position = -1] - position(bytes) where start to write < 0 use read, else use pread. - * @param {string} [options.encoding = 'utf-8'] - encoding. - * @returns {number} on success number of bytes written - * @throws {TypedError | Error} write fail - */ - writeSync(buffer: ArrayBuffer | string, options?: { - offset?: number; - length?: number; - position?: number; - encoding?: string; - }): number; - /** - * read. - * - * @note N/A - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 7 - * @permission N/A - * @param {ArrayBuffer} buffer - file description. - * @param {Object} [options] - options. - * @param {number} [options.offset = 0] - offset. - * @param {number} [options.length = -1] - length. - * @param {AsyncCallback} [callback] - callback. - * @returns {void | Promise} no callback return Promise otherwise return void - * @throws {TypedError} Parameter check failed - */ - read(buffer: ArrayBuffer, options?: { - position?: number; - offset?: number; - length?: number; - }): Promise; - read(buffer: ArrayBuffer, callback: AsyncCallback): void; - read(buffer: ArrayBuffer, options: { - position?: number; - offset?: number; - length?: number; - }, callback: AsyncCallback): void; - /** - * readSync. - * - * @note N/A - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 7 - * @permission N/A - * @param {ArrayBuffer} buffer - file description. - * @param {Object} [options] - options. - * @param {number} [options.offset = 0] - offset. - * @param {number} [options.length = -1] - length. - * @returns {number} number of bytesRead - * @throws {TypedError | Error} read fail - */ - readSync(buffer: ArrayBuffer, options?: { - position?: number; - offset?: number; - length?: number; - }): number; -} - -/** - * ReadOut - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 6 - * @permission N/A - */ -declare interface ReadOut { - /** - * @type {number} - * @note N/A - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 6 - * @permission N/A - * @readonly - */ - bytesRead: number; - /** - * @type {number} - * @note N/A - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 6 - * @permission N/A - * @readonly - */ - offset: number; - /** - * @type {ArrayBuffer} - * @note N/A - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 6 - * @permission N/A - * @readonly - */ - buffer: ArrayBuffer; -} - -/** - * Watcher - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 7 - * @permission N/A - */ -declare interface Watcher { - /** - * stop. - * - * @note N/A - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 7 - * @permission N/A - * @param {AsyncCallback} [callback] - callback. - * @returns {void | Promise} stop success - * @throws {TypedError | Error} stop fail - */ - stop(): Promise; - stop(callback: AsyncCallback): void; -} \ No newline at end of file diff --git a/interfaces/kits/js/napi/@ohos.securityLabel.d.ts b/interfaces/kits/js/napi/@ohos.securityLabel.d.ts deleted file mode 100644 index 8e3b8629f1ec97cf9089ef6eeb12f4d134b48739..0000000000000000000000000000000000000000 --- a/interfaces/kits/js/napi/@ohos.securityLabel.d.ts +++ /dev/null @@ -1,59 +0,0 @@ -/* -* Copyright (C) 2021 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 {AsyncCallback, Callback} from "./basic"; - -/** - * Provides securityLabel APIs - * - * @since 9 - * @syscap SystemCapability.FileManagement.File.FileIO - */ - -declare namespace securityLabel { - - type dataLevel = 's0'|'s1'|'s2'|'s3'|'s4'; - /** - * set the SecurityLabel. - * - * @since 9 - */ - function setSecurityLabel(path:string, type:dataLevel, callback: AsyncCallback): void; - function setSecurityLabel(path:string, type:dataLevel): Promise; - - /** - * set the SecurityLabelSync. - * - * @since 9 - */ - function setSecurityLabelSync(path:string, type:dataLevel): void; - - /** - * get the SecurityLabel. - * - * @since 9 - */ - function getSecurityLabel(path:string, callback: AsyncCallback): void; - function getSecurityLabel(path:string): Promise; - - /** - * get the SecurityLabelSync. - * - * @since 9 - */ - function getSecurityLabelSync(path:string): string; -} - -export default securityLabel; \ No newline at end of file diff --git a/interfaces/kits/js/napi/@system.file.d.ts b/interfaces/kits/js/napi/@system.file.d.ts deleted file mode 100644 index 9bd26a69d357ab1ce62b1b475c878890c04ca67b..0000000000000000000000000000000000000000 --- a/interfaces/kits/js/napi/@system.file.d.ts +++ /dev/null @@ -1,752 +0,0 @@ -/* - * Copyright (c) 2020 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 FileResponse { - /** - * File URI. - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 3 - */ - uri: string; - - /** - * File size, in bytes. - * If type is dir, the length value is fixed to 0. - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 3 - */ - length: number; - - /** - * Timestamp when the file is stored, which is the number of milliseconds elapsed since 1970/01/01 00:00:00. - * For lite wearables, the value is fixed to 0, because this parameter is restricted by the underlying file system. - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 3 - */ - lastModifiedTime: number; - - /** - * File type. The values are as follows: - * dir: directory - * file: file - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 3 - */ - type: "dir" | "file"; - - /** - * File list. When the recursive value is true and the type is dir, the file information under the subdirectory will be returned. - * Otherwise, no value will be returned. - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 3 - */ - subFiles?: Array; -} - -/** - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 3 - */ -export interface FileMoveOption { - /** - * URI of the file to move. - * Restricted by the underlying file system of lite wearables, the value must meet the following requirements: - * 1. The URI cannot contain special characters such as \/"*+,:;<=>?[]|\x7F. - * 2. The maximum number of characters allowed is 128. - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 3 - */ - srcUri: string; - - /** - * URI of the file moved to the target location. - * Restricted by the underlying file system of lite wearables, the value must meet the following requirements: - * 1. The URI cannot contain special characters such as \/"*+,:;<=>?[]|\x7F. - * 2. The maximum number of characters allowed is 128. - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 3 - */ - dstUri: string; - - /** - * Called when the source file is moved to the specified location successfully. - * This function returns the URI of the file moved to the target location. - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 3 - */ - success?: (uri: string) => void; - - /** - * Called when moving fails. - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 3 - */ - fail?: (data: string, code: number) => void; - - /** - * Called when the execution is completed. - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 3 - */ - complete?: () => void; -} - -/** - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 3 - */ -export interface FileListResponse { - /** - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 3 - */ - fileList: Array; -} - -/** - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 3 - */ -export interface FileListOption { - /** - * URI of the directory. - * Restricted by the underlying file system of lite wearables, the value must meet the following requirements: - * 1. The URI cannot contain special characters such as \/"*+,:;<=>?[]|\x7F. - * 2. The maximum number of characters allowed is 128. - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 3 - */ - uri: string; - - /** - * Called when the list is obtained successfully. - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 3 - */ - success?: (data: FileListResponse) => void; - - /** - * Called when the list fails to be obtained. - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 3 - */ - fail?: (data: string, code: number) => void; - - /** - * Called when the execution is completed. - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 3 - */ - complete?: () => void; -} - -export interface FileCopyOption { - /** - * URI of the file to copy. - * Restricted by the underlying file system of lite wearables, the value must meet the following requirements: - * 1. The URI cannot contain special characters such as \/"*+,:;<=>?[]|\x7F. - * 2. The maximum number of characters allowed is 128. - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 3 - */ - srcUri: string; - - /** - * URI of the file moved to the target location. - * Restricted by the underlying file system of lite wearables, the value must meet the following requirements: - * 1. The URI cannot contain special characters such as \/"*+,:;<=>?[]|\x7F. - * 2. The maximum number of characters allowed is 128. - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 3 - */ - dstUri: string; - - /** - * Called when the copy file is saved successful. - * This function returns the URI of the file saved to the target location. - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 3 - */ - success?: (uri: string) => void; - - /** - * Called when the copy or save operation fails. - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 3 - */ - fail?: (data: string, code: number) => void; - - /** - * Called when the execution is completed. - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 3 - */ - complete?: () => void; -} - -export interface FileGetOption { - /** - * File URI, which cannot be an application resource path. - * Restricted by the underlying file system of lite wearables, the value must meet the following requirements: - * 1. The URI cannot contain special characters such as \/"*+,:;<=>?[]|\x7F. - * 2. The maximum number of characters allowed is 128. - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 3 - */ - uri: string; - - /** - * Whether to recursively obtain the file list under a subdirectory. - * The default value is false. - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 3 - */ - recursive?: boolean; - - /** - * Called when file information is obtained successfully. - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 3 - */ - success?: (file: FileResponse) => void; - - /** - * Called when file information fails to be obtained. - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 3 - */ - fail?: (data: string, code: number) => void; - - /** - * Called when the execution is completed. - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 3 - */ - complete?: () => void; -} - -export interface FileDeleteOption { - /** - * URI of the file to be deleted, which cannot be an application resource path. - * Restricted by the underlying file system of lite wearables, the value must meet the following requirements: - * 1. The URI cannot contain special characters such as \/"*+,:;<=>?[]|\x7F. - * 2. The maximum number of characters allowed is 128. - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 3 - */ - uri: string; - - /** - * Called when local files are deleted successfully. - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 3 - */ - success?: () => void; - - /** - * Called when the deletion fails. - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 3 - */ - fail?: (data: string, code: number) => void; - - /** - * Called when the execution is completed. - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 3 - */ - complete?: () => void; -} - -/** - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 3 - */ -export interface FileWriteTextOption { - /** - * URI of a local file. If it does not exist, a file will be created. - * Restricted by the underlying file system of lite wearables, the value must meet the following requirements: - * 1. The URI cannot contain special characters such as \/"*+,:;<=>?[]|\x7F. - * 2. The maximum number of characters allowed is 128. - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 3 - */ - uri: string; - - /** - * Character string to write into the local file. - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 3 - */ - text: string; - - /** - * Encoding format. The default format is UTF-8. - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 3 - */ - encoding?: string; - - /** - * Whether to enable the append mode. The default value is false. - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 3 - */ - append?: boolean; - - /** - * Called when texts are written into a file successfully. - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 3 - */ - success?: () => void; - - /** - * Called when texts fail to be written into a file. - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 3 - */ - fail?: (data: string, code: number) => void; - - /** - * Called when the execution is completed. - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 3 - */ - complete?: () => void; -} - -/** - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 3 - */ -export interface FileReadTextResponse { - /** - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 3 - */ - text: string; -} - -export interface FileReadTextOption { - /** - * URI of a local file. - * Restricted by the underlying file system of lite wearables, the value must meet the following requirements: - * 1. The URI cannot contain special characters such as \/"*+,:;<=>?[]|\x7F. - * 2. The maximum number of characters allowed is 128. - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 3 - */ - uri: string; - - /** - * Encoding format. The default format is UTF-8. - * Currently, only UTF-8 is supported. - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 3 - */ - encoding?: string; - - /** - * Position where the reading starts. - * The default value is the start position of the file. - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 3 - */ - position?: number; - - /** - * Position where the reading starts. - * The default value is the start position of the file. - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 3 - */ - length?: number; - - /** - * Called when texts are read successfully. - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 3 - */ - success?: (data: FileReadTextResponse) => void; - - /** - * Called when texts fail to be read. - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 3 - */ - fail?: (data: string, code: number) => void; - - /** - * Called when the execution is completed. - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 3 - */ - complete?: () => void; -} - -/** - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 3 - */ -export interface FileWriteArrayBufferOption { - /** - * URI of a local file. If it does not exist, a file will be created. - * Restricted by the underlying file system of lite wearables, the value must meet the following requirements: - * 1. The URI cannot contain special characters such as \/"*+,:;<=>?[]|\x7F. - * 2. The maximum number of characters allowed is 128. - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 3 - */ - uri: string; - - /** - * Buffer from which the data is derived. - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 3 - */ - buffer: Uint8Array; - - /** - * Offset to the position where the writing starts. The default value is 0. - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 3 - */ - position?: number; - - /** - * Whether to enable the append mode. - * The default value is false. If the value is true, the position parameter will become invalid. - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 3 - */ - append?: boolean; - - /** - * Called when data from a buffer is written into a file successfully. - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 3 - */ - success?: () => void; - - /** - * Called when data from a buffer fails to be written into a file. - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 3 - */ - fail?: (data: string, code: number) => void; - - /** - * Called when the execution is completed. - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 3 - */ - complete?: () => void; -} - -/** - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 3 - */ -export interface FileReadArrayBufferResponse { - /** - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 3 - */ - buffer: Uint8Array; -} - -/** - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 3 - */ -export interface FileReadArrayBufferOption { - /** - * URI of a local file. - * Restricted by the underlying file system of lite wearables, the value must meet the following requirements: - * 1. The URI cannot contain special characters such as \/"*+,:;<=>?[]|\x7F. - * 2. The maximum number of characters allowed is 128. - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 3 - */ - uri: string; - - /** - * Position where the reading starts. - * The default value is the start position of the file. - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 3 - */ - position?: number; - - /** - * Length of the content to read. - * If this parameter is not set, all content of the file will be read. - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 3 - */ - length?: number; - - /** - * Called when the buffer data is read successfully. - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 3 - */ - success?: (data: FileReadArrayBufferResponse) => void; - - /** - * Called when the buffer data fails to be read. - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 3 - */ - fail?: (data: string, code: number) => void; - - /** - * Called when the execution is completed. - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 3 - */ - complete?: () => void; -} - -/** - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 3 - */ -export interface FileAccessOption { - /** - * URI of the directory or file. - * Restricted by the underlying file system of lite wearables, the value must meet the following requirements: - * 1. The URI cannot contain special characters such as \/"*+,:;<=>?[]|\x7F. - * 2. The maximum number of characters allowed is 128. - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 3 - */ - uri: string; - - /** - * Called when the check result is obtained successfully. - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 3 - */ - success?: () => void; - - /** - * Called when the check fails. - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 3 - */ - fail?: (data: string, code: number) => void; - - /** - * Called when the execution is completed. - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 3 - */ - complete?: () => void; -} - -/** - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 3 - */ -export interface FileMkdirOption { - /** - * URI of the directory. - * Restricted by the underlying file system of lite wearables, the value must meet the following requirements: - * 1. The URI cannot contain special characters such as \/"*+,:;<=>?[]|\x7F. - * 2. The maximum number of characters allowed is 128. - * 3. A maximum of five recursions are allowed for creating the directory. - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 3 - */ - uri: string; - - /** - * Whether to create the directory after creating its upper-level directory recursively. - * The default value is false. - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 3 - */ - recursive?: boolean; - - /** - * Called when the directory is created successfully. - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 3 - */ - success?: () => void; - - /** - * Called when the creation fails. - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 3 - */ - fail?: (data: string, code: number) => void; - - /** - * Called when the execution is completed. - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 3 - */ - complete?: () => void; -} - -/** - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 3 - */ -export interface FileRmdirOption { - /** - * URI of the directory. - * Restricted by the underlying file system of lite wearables, the value must meet the following requirements: - * 1. The URI cannot contain special characters such as \/"*+,:;<=>?[]|\x7F. - * 2. The maximum number of characters allowed is 128. - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 3 - */ - uri: string; - - /** - * Whether to delete files and subdirectories recursively. - * The default value is false. - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 3 - */ - recursive?: boolean; - - /** - * Called when the directory is deleted successfully. - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 3 - */ - success?: () => void; - - /** - * Called when the deletion fails. - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 3 - */ - fail?: (data: string, code: number) => void; - - /** - * Called when the execution is completed. - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 3 - */ - complete?: () => void; -} - -/** - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 3 - */ -export default class File { - /** - * Moves the source file to a specified location. - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 3 - * @param options Options. - */ - static move(options: FileMoveOption): void; - - /** - * Copies a source file and save the copy to a specified location. - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 3 - * @param options Options. - */ - static copy(options: FileCopyOption): void; - - /** - * Obtains the list of files in a specified directory. - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 3 - * @param options Options. - */ - static list(options: FileListOption): void; - - /** - * Obtains information about a local file. - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 3 - * @param options Options. - */ - static get(options: FileGetOption): void; - - /** - * Deletes local files. - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 3 - * @param options Options. - */ - static delete(options: FileDeleteOption): void; - - /** - * Writes texts into a file. - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 3 - * @param options Options. - */ - static writeText(options: FileWriteTextOption): void; - - /** - * Reads texts from a file. - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 3 - * @param options Options. - */ - static readText(options: FileReadTextOption): void; - - /** - * Writes data from a buffer into a file. - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 3 - * @param options Options. - */ - static writeArrayBuffer(options: FileWriteArrayBufferOption): void; - - /** - * Reads buffer data from a file. - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 3 - * @param options Options. - */ - static readArrayBuffer(options: FileReadArrayBufferOption): void; - - /** - * Checks whether a file or directory exists. - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 3 - * @param options Options. - */ - static access(options: FileAccessOption): void; - - /** - * Creates a directory. - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 3 - * @param options Options. - */ - static mkdir(options: FileMkdirOption): void; - - /** - * Deletes a directory. - * @syscap SystemCapability.FileManagement.File.FileIO - * @since 3 - * @param options Options. - */ - static rmdir(options: FileRmdirOption): void; -} diff --git a/interfaces/kits/js/src/common/ability_helper.cpp b/interfaces/kits/js/src/common/ability_helper.cpp index 1d9e1e09d5da0771695c745150039d7cff101e96..6d8a922929fc3863647261b89dc34915edc9216b 100644 --- a/interfaces/kits/js/src/common/ability_helper.cpp +++ b/interfaces/kits/js/src/common/ability_helper.cpp @@ -29,6 +29,7 @@ Ability* AbilityHelper::GetJsAbility(napi_env env) { napi_value global = nullptr; napi_value abilityContext = nullptr; + napi_status status = napi_get_global(env, &global); if (status != napi_ok || global == nullptr) { HILOGE("Cannot get global instance for %{public}d", status); @@ -43,9 +44,8 @@ Ability* AbilityHelper::GetJsAbility(napi_env env) Ability *ability = nullptr; status = napi_get_value_external(env, abilityContext, (void **)&ability); - if (status != napi_ok) { + if (status != napi_ok || ability == nullptr) { HILOGE("Get ability form property failed for %{public}d", status); - return nullptr; } return ability; diff --git a/interfaces/kits/js/src/common/ability_helper.h b/interfaces/kits/js/src/common/ability_helper.h index d23285184d16bfebd9cb57a1eb65c5e2a370cec9..ba48c4f3b9ac2d0ac9e93e76b2d059db72644395 100644 --- a/interfaces/kits/js/src/common/ability_helper.h +++ b/interfaces/kits/js/src/common/ability_helper.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2022 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 @@ -13,8 +13,8 @@ * limitations under the License. */ -#ifndef INTERFACES_KITS_JS_SRC_COMMON_ABILITY_HELPER_H -#define INTERFACES_KITS_JS_SRC_COMMON_ABILITY_HELPER_H +#ifndef INTERFACES_KITS_NAPI_COMMON_ABILITY_HELPER_H +#define INTERFACES_KITS_NAPI_COMMON_ABILITY_HELPER_H #include "ability.h" @@ -25,4 +25,4 @@ struct AbilityHelper { }; } // namespace DistributedFS } // namespace OHOS -#endif // INTERFACES_KITS_JS_SRC_COMMON_ABILITY_HELPER_H \ No newline at end of file +#endif \ No newline at end of file diff --git a/interfaces/kits/js/src/common/file_filter.h b/interfaces/kits/js/src/common/file_filter.h new file mode 100644 index 0000000000000000000000000000000000000000..694b6f0d20f78718753955e42f1e80c5b942dfbd --- /dev/null +++ b/interfaces/kits/js/src/common/file_filter.h @@ -0,0 +1,174 @@ +/* + * Copyright (C) 2022 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. + */ +#ifndef FILE_FILTER_H +#define FILE_FILTER_H + +#include +#include + +#include "parcel.h" + +namespace OHOS { +namespace DistributedFS { +class FileFilter : public Parcelable { +public: + FileFilter() = default; + ~FileFilter() = default; + + FileFilter(std::vector suffix, std::vector displayName, + std::vector mimeType, int64_t fileSizeOver, + double lastModifiedAfter, bool excludeMedia, bool hasFilter) + : suffix_(suffix), displayName_(displayName), mimeType_(mimeType), fileSizeOver_(fileSizeOver), + lastModifiedAfter_(lastModifiedAfter), excludeMedia_(excludeMedia), hasFilter_(hasFilter) {} + explicit FileFilter(std::vector suffix): suffix_(suffix) {} + FileFilter(const FileFilter &filter) = default; + FileFilter &operator=(const FileFilter& filter) = default; + + void SetSuffix(const std::vector &suffix) + { + suffix_ = suffix; + } + + std::vector GetSuffix() const + { + return suffix_; + } + + void SetDisplayName(const std::vector &displayName) + { + displayName_ = displayName; + } + + std::vector GetDisplayName() const + { + return displayName_; + } + + void SetMimeType(const std::vector &mimeType) + { + mimeType_ = mimeType; + } + + std::vector GetMimeType() const + { + return mimeType_; + } + + void SetFileSizeOver(const int64_t &fileSizeOver) + { + fileSizeOver_ = fileSizeOver; + } + + int64_t GetFileSizeOver() const + { + return fileSizeOver_; + } + + void SetLastModifiedAfter(const double &lastModifiedAfter) + { + lastModifiedAfter_ = lastModifiedAfter; + } + + double GetLastModifiedAfter() const + { + return lastModifiedAfter_; + } + + void SetExcludeMedia(const bool &excludeMedia) + { + excludeMedia_ = excludeMedia; + } + + bool GetExcludeMedia() const + { + return excludeMedia_; + } + + void SetHasFilter(const bool &hasFilter) + { + hasFilter_ = hasFilter; + } + + bool GetHasFilter() const + { + return hasFilter_; + } + + bool Marshalling(Parcel &parcel) const + { + if (!parcel.WriteStringVector(suffix_)) { + return false; + } + if (!parcel.WriteStringVector(displayName_)) { + return false; + } + if (!parcel.WriteStringVector(mimeType_)) { + return false; + } + if (!parcel.WriteInt64(fileSizeOver_)) { + return false; + } + if (!parcel.WriteDouble(lastModifiedAfter_)) { + return false; + } + if (!parcel.WriteBool(excludeMedia_)) { + return false; + } + if (!parcel.WriteBool(hasFilter_)) { + return false; + } + return true; + } + + static FileFilter* Unmarshalling(Parcel &parcel) + { + auto obj = new (std::nothrow) FileFilter(); + if (obj != nullptr && !obj->ReadFromParcel(parcel)) { + delete obj; + obj = nullptr; + } + return obj; + } + + bool ReadFromParcel(Parcel &parcel) + { + if (!parcel.ReadStringVector(&suffix_)) { + return false; + } + if (!parcel.ReadStringVector(&displayName_)) { + return false; + } + if (!parcel.ReadStringVector(&mimeType_)) { + return false; + } + fileSizeOver_ = parcel.ReadInt64(); + lastModifiedAfter_ = parcel.ReadDouble(); + excludeMedia_ = parcel.ReadBool(); + hasFilter_ = parcel.ReadBool(); + return true; + } + +private: + std::vector suffix_ = std::vector(); + std::vector displayName_ = std::vector(); + std::vector mimeType_ = std::vector(); + int64_t fileSizeOver_ = 0; + double lastModifiedAfter_ = 0; + bool excludeMedia_ = false; + bool hasFilter_ = false; +}; +} // namespace DistributedFS +} // namespace OHOS +#endif // FILE_FILTER_H \ No newline at end of file diff --git a/interfaces/kits/js/src/common/file_helper/fd_guard.cpp b/interfaces/kits/js/src/common/file_helper/fd_guard.cpp index 6959b45a52f534f468561ff090199b2e3c5f8735..54b9ff63873ce5995f87e7f1d0ede8d2ac7a39c4 100644 --- a/interfaces/kits/js/src/common/file_helper/fd_guard.cpp +++ b/interfaces/kits/js/src/common/file_helper/fd_guard.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2022 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 diff --git a/interfaces/kits/js/src/common/file_helper/fd_guard.h b/interfaces/kits/js/src/common/file_helper/fd_guard.h index 07c27b19d46a21d9e11eb999877be70306671699..f59d633d79462258bf8fcc2b9a01d22fab73b348 100644 --- a/interfaces/kits/js/src/common/file_helper/fd_guard.h +++ b/interfaces/kits/js/src/common/file_helper/fd_guard.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2022 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 diff --git a/interfaces/kits/js/src/common/file_helper/hash_file.cpp b/interfaces/kits/js/src/common/file_helper/hash_file.cpp index 2bd54cc657cafbf6dbb1c3bb026eee2b118a118a..3df095d9edb7ca96e6bd2298e8e8c3ca92e53410 100644 --- a/interfaces/kits/js/src/common/file_helper/hash_file.cpp +++ b/interfaces/kits/js/src/common/file_helper/hash_file.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2022 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 diff --git a/interfaces/kits/js/src/common/file_helper/hash_file.h b/interfaces/kits/js/src/common/file_helper/hash_file.h index 81d68a2e4c3e1a3028c7569785706f97c9db02dc..d9b79a5f784cdd8e35f690665a960f08cba1fbc0 100644 --- a/interfaces/kits/js/src/common/file_helper/hash_file.h +++ b/interfaces/kits/js/src/common/file_helper/hash_file.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2022 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 diff --git a/interfaces/kits/js/src/common/log.h b/interfaces/kits/js/src/common/log.h index 48eb794a145f22d6c76a30a57268eb52b69023df..a5f3bce41f4d0c5e018a75b0c0e60cb81aea2da9 100644 --- a/interfaces/kits/js/src/common/log.h +++ b/interfaces/kits/js/src/common/log.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2022 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 @@ -13,8 +13,8 @@ * limitations under the License. */ -#ifndef INTERFACES_KITS_JS_SRC_COMMON_LOG_H -#define INTERFACES_KITS_JS_SRC_COMMON_LOG_H +#ifndef INTERFACES_KITS_NAPI_COMMON_LOG_H +#define INTERFACES_KITS_NAPI_COMMON_LOG_H #include #include @@ -28,7 +28,7 @@ namespace OHOS { namespace DistributedFS { #ifndef FILE_SUBSYSTEM_DEBUG_LOCAL static constexpr int FILEIO_DOMAIN_ID = 0; -static constexpr OHOS::HiviewDFX::HiLogLabel FILEIO_LABEL = { LOG_CORE, FILEIO_DOMAIN_ID, "distributedfilejs" }; +static constexpr OHOS::HiviewDFX::HiLogLabel FILEIO_LABEL = { LOG_CORE, FILEIO_DOMAIN_ID, "file_api" }; #ifdef HILOGD #undef HILOGD @@ -89,4 +89,4 @@ static constexpr OHOS::HiviewDFX::HiLogLabel FILEIO_LABEL = { LOG_CORE, FILEIO_D #endif } // namespace DistributedFS } // namespace OHOS -#endif // INTERFACES_KITS_JS_SRC_COMMON_LOG_H \ No newline at end of file +#endif \ No newline at end of file diff --git a/interfaces/kits/js/src/common/napi/n_async/n_async_context.h b/interfaces/kits/js/src/common/napi/n_async/n_async_context.h index 87339bbdddfdc837b658e60e7026f2bc10e6bdc7..725fead81d79ae1fa9e42f985f045170159866b0 100644 --- a/interfaces/kits/js/src/common/napi/n_async/n_async_context.h +++ b/interfaces/kits/js/src/common/napi/n_async/n_async_context.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2022 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 diff --git a/interfaces/kits/js/src/common/napi/n_async/n_async_work_callback.cpp b/interfaces/kits/js/src/common/napi/n_async/n_async_work_callback.cpp index 0cca524128405cfc371c7071833efcc7b0a0a737..41793ceefeb451b17301e8245cc5812cda68ff14 100644 --- a/interfaces/kits/js/src/common/napi/n_async/n_async_work_callback.cpp +++ b/interfaces/kits/js/src/common/napi/n_async/n_async_work_callback.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2022 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 @@ -14,7 +14,20 @@ */ #include "n_async_work_callback.h" + +#include + +#include +#include +#include +#include +#include + #include "../../log.h" +#include "../../uni_error.h" +#include "js_native_api.h" +#include "n_ref.h" +#include "node_api.h" namespace OHOS { namespace DistributedFS { @@ -41,7 +54,6 @@ static void CallbackComplete(napi_env env, napi_status status, void *data) if (ctx == nullptr) { return; } - if (ctx->cbComplete_ != nullptr) { ctx->res_ = ctx->cbComplete_(env, ctx->err_); ctx->cbComplete_ = nullptr; @@ -62,7 +74,6 @@ static void CallbackComplete(napi_env env, napi_status status, void *data) if (stat != napi_ok) { HILOGE("Failed to call function for %{public}d", stat); } - napi_close_handle_scope(env, scope); napi_delete_async_work(env, ctx->awork_); delete ctx; @@ -77,7 +88,9 @@ NVal NAsyncWorkCallback::Schedule(string procedureName, NContextCBExec cbExec, N ctx_->cbExec_ = move(cbExec); ctx_->cbComplete_ = move(cbComplete); + napi_value resource = NVal::CreateUTF8String(env_, procedureName).val_; + napi_status status = napi_create_async_work(env_, nullptr, resource, CallbackExecute, CallbackComplete, ctx_, &ctx_->awork_); if (status != napi_ok) { diff --git a/interfaces/kits/js/src/common/napi/n_async/n_async_work_callback.h b/interfaces/kits/js/src/common/napi/n_async/n_async_work_callback.h index 9bc6d5f3d7b7125e50fda9baedb4d70f2b397003..0268326e8517b37c94d38d42e6df4f2f377b6ce3 100644 --- a/interfaces/kits/js/src/common/napi/n_async/n_async_work_callback.h +++ b/interfaces/kits/js/src/common/napi/n_async/n_async_work_callback.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2022 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 @@ -16,6 +16,11 @@ #ifndef N_ASYNC_WORK_CALLBACK_H #define N_ASYNC_WORK_CALLBACK_H +#include + +#include "../n_val.h" +#include "js_native_api_types.h" +#include "n_async_context.h" #include "n_async_work_factory.h" namespace OHOS { diff --git a/interfaces/kits/js/src/common/napi/n_async/n_async_work_factory.h b/interfaces/kits/js/src/common/napi/n_async/n_async_work_factory.h index 7b115469843ef99ff60846485da30de80e478d1b..dd267585b56db384b6743f59f4b09d1e7a098153 100644 --- a/interfaces/kits/js/src/common/napi/n_async/n_async_work_factory.h +++ b/interfaces/kits/js/src/common/napi/n_async/n_async_work_factory.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2022 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 diff --git a/interfaces/kits/js/src/common/napi/n_async/n_async_work_promise.cpp b/interfaces/kits/js/src/common/napi/n_async/n_async_work_promise.cpp index cd4a7ed082f4c166b28b5e3d576351989aea8bfe..213e51b171fcd2fa60e1e492e078be2a3280bc2f 100644 --- a/interfaces/kits/js/src/common/napi/n_async/n_async_work_promise.cpp +++ b/interfaces/kits/js/src/common/napi/n_async/n_async_work_promise.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2022 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 @@ -14,7 +14,16 @@ */ #include "n_async_work_promise.h" + +#include +#include +#include +#include + #include "../../log.h" +#include "../../uni_error.h" +#include "js_native_api.h" +#include "node_api.h" namespace OHOS { namespace DistributedFS { @@ -39,11 +48,9 @@ static void PromiseOnComplete(napi_env env, napi_status status, void *data) if (ctx == nullptr) { return; } - if (ctx->cbComplete_ != nullptr) { ctx->res_ = ctx->cbComplete_(env, ctx->err_); } - if (!ctx->res_.TypeIsError(true)) { napi_status status = napi_resolve_deferred(env, ctx->deferred_, ctx->res_.val_); if (status != napi_ok) { @@ -55,7 +62,6 @@ static void PromiseOnComplete(napi_env env, napi_status status, void *data) HILOGE("Internal BUG, cannot reject promise for %{public}d", status); } } - ctx->deferred_ = nullptr; napi_delete_async_work(env, ctx->awork_); delete ctx; diff --git a/interfaces/kits/js/src/common/napi/n_async/n_async_work_promise.h b/interfaces/kits/js/src/common/napi/n_async/n_async_work_promise.h index 8a049de65e913edaeb99a297acefacf6a1a6d4a0..ed882f7c799a5cfe90c66428d7b12510fe3a9790 100644 --- a/interfaces/kits/js/src/common/napi/n_async/n_async_work_promise.h +++ b/interfaces/kits/js/src/common/napi/n_async/n_async_work_promise.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2022 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 @@ -16,6 +16,11 @@ #ifndef N_ASYNC_WORK_PROMISE_H #define N_ASYNC_WORK_PROMISE_H +#include + +#include "../n_val.h" +#include "js_native_api_types.h" +#include "n_async_context.h" #include "n_async_work_factory.h" namespace OHOS { diff --git a/interfaces/kits/js/src/common/napi/n_async/n_ref.cpp b/interfaces/kits/js/src/common/napi/n_async/n_ref.cpp index 8b78ac9c8462575d69240e68e3c7efdd5a080b8d..67095842492f6622a53ec0426f2301a50d4a66d6 100644 --- a/interfaces/kits/js/src/common/napi/n_async/n_ref.cpp +++ b/interfaces/kits/js/src/common/napi/n_async/n_ref.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2022 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 @@ -15,6 +15,9 @@ #include "n_ref.h" +#include "../n_val.h" +#include "js_native_api.h" + namespace OHOS { namespace DistributedFS { NRef::NRef() {} diff --git a/interfaces/kits/js/src/common/napi/n_async/n_ref.h b/interfaces/kits/js/src/common/napi/n_async/n_ref.h index a9f166cfc50cc5f2e6920711c4a57da2ba0db4ed..3bbdc0f2ede45a8ae040d9cc2e546b91d74c3754 100644 --- a/interfaces/kits/js/src/common/napi/n_async/n_ref.h +++ b/interfaces/kits/js/src/common/napi/n_async/n_ref.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2022 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 @@ -17,6 +17,7 @@ #define N_REF_H #include "../n_val.h" +#include "js_native_api_types.h" namespace OHOS { namespace DistributedFS { diff --git a/interfaces/kits/js/src/common/napi/n_class.cpp b/interfaces/kits/js/src/common/napi/n_class.cpp index 482bd7807b9f5be54b74bf9c38cd57c6253a46a8..277028d0cfe34361891ee47df41878ec55ff85e7 100644 --- a/interfaces/kits/js/src/common/napi/n_class.cpp +++ b/interfaces/kits/js/src/common/napi/n_class.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2022 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 @@ -66,7 +66,6 @@ bool NClass::SaveClass(napi_env env, string className, napi_value exClass) } else { HILOGE("INNER BUG. Cannot ref class constructor %{public}s because of %{public}d", className.c_str(), res); } - return res == napi_ok; } @@ -74,6 +73,7 @@ napi_value NClass::InstantiateClass(napi_env env, const string& className, const { NClass &nClass = NClass::GetInstance(); lock_guard(nClass.exClassMapLock); + auto it = nClass.exClassMap.find(className); if (it == nClass.exClassMap.end()) { HILOGE("Class %{public}s hasn't been saved yet", className.c_str()); @@ -93,7 +93,6 @@ napi_value NClass::InstantiateClass(napi_env env, const string& className, const HILOGE("INNER BUG. Cannot instantiate the class %{public}s because of %{public}d", className.c_str(), status); return nullptr; } - return instance; } } // namespace DistributedFS diff --git a/interfaces/kits/js/src/common/napi/n_class.h b/interfaces/kits/js/src/common/napi/n_class.h index 13a194ade3728777444816f0c451c1a1a26f7e8f..4acbd94ce93f38490c22da0b2a992490f8ff6903 100644 --- a/interfaces/kits/js/src/common/napi/n_class.h +++ b/interfaces/kits/js/src/common/napi/n_class.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2022 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 @@ -13,14 +13,13 @@ * limitations under the License. */ -#ifndef INTERFACES_KITS_JS_SRC_COMMON_NAPI_N_CLASS_H -#define INTERFACES_KITS_JS_SRC_COMMON_NAPI_N_CLASS_H - -#include "uni_header.h" +#ifndef INTERFACES_KITS_NAPI_COMMON_NAPI_N_CLASS_H +#define INTERFACES_KITS_NAPI_COMMON_NAPI_N_CLASS_H #include #include "../log.h" +#include "uni_header.h" namespace OHOS { namespace DistributedFS { @@ -76,4 +75,4 @@ private: }; } // namespace DistributedFS } // namespace OHOS -#endif // INTERFACES_KITS_JS_SRC_COMMON_NAPI_N_CLASS_H \ No newline at end of file +#endif \ No newline at end of file diff --git a/interfaces/kits/js/src/common/napi/n_exporter.h b/interfaces/kits/js/src/common/napi/n_exporter.h index 11d2fd7c9c79b726521490a1dc3ea74f645b9fda..758d3ee512c63089e6aaa8a236e292b4bb0b6d60 100644 --- a/interfaces/kits/js/src/common/napi/n_exporter.h +++ b/interfaces/kits/js/src/common/napi/n_exporter.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2022 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 @@ -13,8 +13,8 @@ * limitations under the License. */ -#ifndef INTERFACES_KITS_JS_SRC_COMMON_NAPI_N_EXPORTER_H -#define INTERFACES_KITS_JS_SRC_COMMON_NAPI_N_EXPORTER_H +#ifndef INTERFACES_KITS_NAPI_COMMON_NAPI_N_EXPORTER_H +#define INTERFACES_KITS_NAPI_COMMON_NAPI_N_EXPORTER_H #include "n_val.h" @@ -33,4 +33,4 @@ protected: }; } // namespace DistributedFS } // namespace OHOS -#endif // INTERFACES_KITS_JS_SRC_COMMON_NAPI_N_EXPORTER_H \ No newline at end of file +#endif \ No newline at end of file diff --git a/interfaces/kits/js/src/common/napi/n_func_arg.cpp b/interfaces/kits/js/src/common/napi/n_func_arg.cpp index aa2cc60c758337a8a1fa9eb799732713b22c8c5f..a860aae96d2adee45567d496fd73d9813a030b29 100644 --- a/interfaces/kits/js/src/common/napi/n_func_arg.cpp +++ b/interfaces/kits/js/src/common/napi/n_func_arg.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2022 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 @@ -15,6 +15,7 @@ #include "n_func_arg.h" +#include "js_native_api.h" #include "../log.h" namespace OHOS { @@ -59,6 +60,7 @@ bool NFuncArg::InitArgs(std::function argcChecker) { SetArgc(0); argv_.reset(); + size_t argc; napi_value thisVar; napi_status status = napi_get_cb_info(env_, info_, &argc, nullptr, &thisVar, nullptr); @@ -66,7 +68,6 @@ bool NFuncArg::InitArgs(std::function argcChecker) HILOGE("Cannot get num of func args for %{public}d", status); return false; } - if (argc) { argv_ = make_unique(argc); status = napi_get_cb_info(env_, info_, &argc, argv_.get(), &thisVar, nullptr); @@ -75,9 +76,9 @@ bool NFuncArg::InitArgs(std::function argcChecker) return false; } } - SetArgc(argc); SetThisVar(thisVar); + return argcChecker(); } diff --git a/interfaces/kits/js/src/common/napi/n_func_arg.h b/interfaces/kits/js/src/common/napi/n_func_arg.h index 1192094e289a87fc180df49c713516d3661ac0f5..2cb8019a4435f719f8944e0ddb716bfc8b76824d 100644 --- a/interfaces/kits/js/src/common/napi/n_func_arg.h +++ b/interfaces/kits/js/src/common/napi/n_func_arg.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2022 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 @@ -13,10 +13,14 @@ * limitations under the License. */ -#ifndef INTERFACES_KITS_JS_SRC_COMMON_NAPI_N_FUNC_ARG_H -#define INTERFACES_KITS_JS_SRC_COMMON_NAPI_N_FUNC_ARG_H +#ifndef INTERFACES_KITS_NAPI_COMMON_NAPI_N_FUNC_ARG_H +#define INTERFACES_KITS_NAPI_COMMON_NAPI_N_FUNC_ARG_H -#include "uni_header.h" +#include +#include + +#include "node_api.h" +#include "js_native_api_types.h" namespace OHOS { namespace DistributedFS { @@ -64,4 +68,4 @@ private: }; } // namespace DistributedFS } // namespace OHOS -#endif // INTERFACES_KITS_JS_SRC_COMMON_NAPI_N_FUNC_ARG_H \ No newline at end of file +#endif \ No newline at end of file diff --git a/interfaces/kits/js/src/common/napi/n_val.cpp b/interfaces/kits/js/src/common/napi/n_val.cpp index d5bfbf42f27c6de61dd4f473f82dc69cdd3d51e9..d1f6dfe225851bea0250168ccfb419ff512a615d 100644 --- a/interfaces/kits/js/src/common/napi/n_val.cpp +++ b/interfaces/kits/js/src/common/napi/n_val.cpp @@ -16,9 +16,10 @@ #include "n_val.h" #include +#include #include "../log.h" -#include "../uni_error.h" +#include "js_native_api.h" namespace OHOS { namespace DistributedFS { @@ -36,13 +37,12 @@ bool NVal::TypeIs(napi_valuetype expType) const if (!*this) { return false; } - napi_valuetype valueType; napi_typeof(env_, val_, &valueType); + if (expType != valueType) { return false; } - return true; } @@ -124,6 +124,36 @@ tuple NVal::ToInt64() const return make_tuple(status == napi_ok, res); } +tuple NVal::ToDouble() const +{ + double res = 0; + napi_status status = napi_get_value_double(env_, val_, &res); + return make_tuple(status == napi_ok, res); +} + +tuple NVal::ToUint64() const +{ + uint64_t res = 0; + bool lossless = false; + napi_status status = napi_get_value_bigint_uint64(env_, val_, &res, &lossless); + return make_tuple(status == napi_ok, res, lossless); +} + +tuple, uint32_t> NVal::ToStringArray() +{ + napi_status status; + uint32_t size; + status = napi_get_array_length(env_, val_, &size); + vector stringArray; + napi_value result; + for (uint32_t i = 0; i < size; i++) { + status = napi_get_element(env_, val_, i, &result); + auto [succ, str, ignore] = NVal(env_, result).ToUTF8String(); + stringArray.push_back(string(str.get())); + } + return make_tuple(status == napi_ok, stringArray, size); +} + tuple NVal::ToArraybuffer() const { void *buf = nullptr; @@ -159,13 +189,11 @@ NVal NVal::GetProp(string propName) const if (!HasProp(propName)) { return { env_, nullptr }; } - napi_value prop = nullptr; napi_status status = napi_get_named_property(env_, val_, propName.c_str(), &prop); if (status != napi_ok) { return { env_, nullptr }; } - return NVal(env_, prop); } @@ -175,13 +203,11 @@ bool NVal::AddProp(vector &&propVec) const HILOGE("INNER BUG. Prop should only be added to objects"); return false; } - napi_status status = napi_define_properties(env_, val_, propVec.size(), propVec.data()); if (status != napi_ok) { HILOGE("INNER BUG. Cannot define properties because of %{public}d", status); return false; } - return true; } @@ -197,7 +223,6 @@ bool NVal::AddProp(string propName, napi_value val) const HILOGE("INNER BUG. Cannot set named property because of %{public}d", status); return false; } - return true; } @@ -265,6 +290,18 @@ NVal NVal::CreateUint8Array(napi_env env, void *buf, size_t bufLen) return { env, output_array }; } +NVal NVal::CreateArrayString(napi_env env, vector strs) +{ + napi_value res = nullptr; + napi_create_array(env, &res); + for (size_t i = 0; i < strs.size(); i++) { + napi_value filename; + napi_create_string_utf8(env, strs[i].c_str(), strs[i].length(), &filename); + napi_set_element(env, res, i, filename); + } + return {env, res}; +} + tuple NVal::CreateArrayBuffer(napi_env env, size_t len) { napi_value val; diff --git a/interfaces/kits/js/src/common/napi/n_val.h b/interfaces/kits/js/src/common/napi/n_val.h index 9d46fca4a1b95ed769f01984c15f232ae8f0de24..19d015c10a254c2cfc5e698bf5860b513d91023e 100644 --- a/interfaces/kits/js/src/common/napi/n_val.h +++ b/interfaces/kits/js/src/common/napi/n_val.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2022 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 @@ -16,8 +16,14 @@ #ifndef N_VAL_H #define N_VAL_H -#include "sys/types.h" -#include "uni_header.h" +#include +#include +#include +#include + +#include "node_api.h" +#include "js_native_api_types.h" +#include "napi/native_node_api.h" namespace OHOS { namespace DistributedFS { @@ -46,6 +52,9 @@ public: std::tuple ToInt64() const; std::tuple ToArraybuffer() const; std::tuple ToTypedArray() const; + std::tuple, uint32_t> ToStringArray(); + std::tuple ToUint64() const; + std::tuple ToDouble() const; /* Static helpers to create js objects */ static NVal CreateUndefined(napi_env env); @@ -56,6 +65,7 @@ public: static NVal CreateUTF8String(napi_env env, std::string str); static NVal CreateUTF8String(napi_env env, const char* str, ssize_t len); static NVal CreateUint8Array(napi_env env, void *buf, size_t bufLen); + static NVal CreateArrayString(napi_env env, std::vector strs); static std::tuple CreateArrayBuffer(napi_env env, size_t len); /* SHOULD ONLY BE USED FOR OBJECT */ bool HasProp(std::string propName) const; diff --git a/interfaces/kits/js/src/common/napi/uni_header.h b/interfaces/kits/js/src/common/napi/uni_header.h index 2b316842c3c8e5114bba987ca5147d7d17e0ca00..b22698decef4df075543c7b2893a476550f8b118 100644 --- a/interfaces/kits/js/src/common/napi/uni_header.h +++ b/interfaces/kits/js/src/common/napi/uni_header.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2022 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 @@ -13,8 +13,8 @@ * limitations under the License. */ -#ifndef INTERFACES_KITS_JS_SRC_COMMON_NAPI_UNI_HEADER_H -#define INTERFACES_KITS_JS_SRC_COMMON_NAPI_UNI_HEADER_H +#ifndef N_UNI_HEADER_H +#define N_UNI_HEADER_H #ifdef FILE_SUBSYSTEM_DEBUG_LOCAL #include @@ -22,4 +22,4 @@ #include "napi/native_api.h" #include "napi/native_node_api.h" #endif -#endif // INTERFACES_KITS_JS_SRC_COMMON_NAPI_UNI_HEADER_H \ No newline at end of file +#endif \ No newline at end of file diff --git a/interfaces/kits/js/src/common/uni_error.cpp b/interfaces/kits/js/src/common/uni_error.cpp index fb7493c8268a38f669e8eaaf6d3542f41813b822..8be97a7aa4639372afb38beb1062382b5ffe0a43 100644 --- a/interfaces/kits/js/src/common/uni_error.cpp +++ b/interfaces/kits/js/src/common/uni_error.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2022 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 @@ -15,9 +15,10 @@ #include "uni_error.h" -#include +#include #include +#include "js_native_api.h" #include "log.h" #include "napi/n_val.h" @@ -41,7 +42,6 @@ int UniError::GetErrno(ErrCodeSystem cs) if (errno_ == ERRNO_NOERR) { return ERRNO_NOERR; } - if (cs == codingSystem_) { return errno_; } @@ -82,7 +82,11 @@ napi_value UniError::GetNapiErr(napi_env env) napi_value UniError::GetNapiErr(napi_env env, string errMsg) { - napi_value code = NVal::CreateUTF8String(env, to_string(GetErrno(codingSystem_))).val_; + int errCode = GetErrno(codingSystem_); + if (errCode == ERRNO_NOERR) { + return nullptr; + } + napi_value code = NVal::CreateUTF8String(env, to_string(errCode)).val_; napi_value msg = NVal::CreateUTF8String(env, errMsg).val_; napi_value res = nullptr; diff --git a/interfaces/kits/js/src/common/uni_error.h b/interfaces/kits/js/src/common/uni_error.h index 883756b73e63f16104e63fc5ba8d1d148b8ea38a..43712991c5f449530f6075592ba682768e058a7d 100644 --- a/interfaces/kits/js/src/common/uni_error.h +++ b/interfaces/kits/js/src/common/uni_error.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2022 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 @@ -13,10 +13,13 @@ * limitations under the License. */ -#ifndef INTERFACES_KITS_JS_SRC_COMMON_UNI_ERROR_H -#define INTERFACES_KITS_JS_SRC_COMMON_UNI_ERROR_H +#ifndef INTERFACES_KITS_NAPI_COMMON_UNI_ERROR_H +#define INTERFACES_KITS_NAPI_COMMON_UNI_ERROR_H -#include "napi/uni_header.h" +#include + +#include "node_api.h" +#include "js_native_api_types.h" namespace OHOS { namespace DistributedFS { @@ -61,4 +64,4 @@ private: }; } // namespace DistributedFS } // namespace OHOS -#endif // INTERFACES_KITS_JS_SRC_COMMON_UNI_ERROR_H \ No newline at end of file +#endif \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_document/document_n_exporter.cpp b/interfaces/kits/js/src/mod_document/document_n_exporter.cpp index a23741bc796a91bd97accd0fe451aa6ebe8ffed6..eb38f35e96e660d649e53d2066dd68207a7a0ab6 100644 --- a/interfaces/kits/js/src/mod_document/document_n_exporter.cpp +++ b/interfaces/kits/js/src/mod_document/document_n_exporter.cpp @@ -15,15 +15,10 @@ #include "document_n_exporter.h" -#include -#include +#include -#include "../common/napi/n_async/n_async_work_callback.h" -#include "../common/napi/n_async/n_async_work_promise.h" -#include "../common/napi/n_class.h" -#include "../common/napi/n_func_arg.h" -#include "../common/napi/n_val.h" #include "../common/uni_error.h" +#include "napi/native_node_api.h" namespace OHOS { namespace DistributedFS { diff --git a/interfaces/kits/js/src/mod_document/document_n_exporter.h b/interfaces/kits/js/src/mod_document/document_n_exporter.h index 653e1e6c7b2017863358e6ed8ab7bd1bffa9afb0..f6159e53750fc5dde6f246eeb371c1207def1141 100644 --- a/interfaces/kits/js/src/mod_document/document_n_exporter.h +++ b/interfaces/kits/js/src/mod_document/document_n_exporter.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2022 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 @@ -16,7 +16,8 @@ #ifndef DOCUMENT_N_EXPORTER_H #define DOCUMENT_N_EXPORTER_H -#include "../common/napi/n_exporter.h" +#include "node_api.h" +#include "js_native_api_types.h" namespace OHOS { namespace DistributedFS { diff --git a/interfaces/kits/js/src/mod_document/document_napi.cpp b/interfaces/kits/js/src/mod_document/document_napi.cpp index 81d08a34ec625cca780533f254efb52fd42ffb82..cd8a0861f0d13be3edccdc57b91b7349bfc9dd22 100644 --- a/interfaces/kits/js/src/mod_document/document_napi.cpp +++ b/interfaces/kits/js/src/mod_document/document_napi.cpp @@ -16,8 +16,11 @@ #include "document_napi.h" #include "document_n_exporter.h" +#include "js_native_api.h" +#include "js_native_api_types.h" #include "napi/native_api.h" -#include "napi/native_node_api.h" +#include "napi/native_common.h" +#include "node_api.h" namespace OHOS { namespace DistributedFS { diff --git a/interfaces/kits/js/src/mod_document/document_napi.h b/interfaces/kits/js/src/mod_document/document_napi.h index 80cdd7c8b85539fcef210b5a522c0abe79102028..bf9242086fd2c4e7b959f76050dbe8ba06298cd7 100644 --- a/interfaces/kits/js/src/mod_document/document_napi.h +++ b/interfaces/kits/js/src/mod_document/document_napi.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2022 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 diff --git a/interfaces/kits/js/src/mod_environment/environment_n_exporter.cpp b/interfaces/kits/js/src/mod_environment/environment_n_exporter.cpp index 780bdc2bc80e5fcc3c985fca78076eebb6357652..1f0b520d9b3e165c78562798d9529270ebe9fa05 100644 --- a/interfaces/kits/js/src/mod_environment/environment_n_exporter.cpp +++ b/interfaces/kits/js/src/mod_environment/environment_n_exporter.cpp @@ -17,18 +17,20 @@ #include -#include "../common/napi/n_async/n_async_work_callback.h" -#include "../common/napi/n_async/n_async_work_promise.h" #include "../common/napi/n_class.h" #include "../common/napi/n_func_arg.h" #include "../common/napi/n_val.h" #include "../common/uni_error.h" +#include "../common/napi/n_async/n_async_work_callback.h" +#include "../common/napi/n_async/n_async_work_promise.h" + namespace OHOS { namespace DistributedFS { namespace ModuleEnvironment { namespace { const std::string STORAGE_DATA_PATH = "/data"; + const std::string USER_DATA_PATH = "/data/storage/0"; } napi_value GetStorageDataDir(napi_env env, napi_callback_info info) { @@ -48,14 +50,15 @@ napi_value GetStorageDataDir(napi_env env, napi_callback_info info) return NVal::CreateUTF8String(env, STORAGE_DATA_PATH); }; - static const std::string procedureName = "GetStorageDataDir"; + std::string procedureName = "GetStorageDataDir"; NVal thisVar(env, funcArg.GetThisVar()); if (funcArg.GetArgc() == NARG_CNT::ZERO) { return NAsyncWorkPromise(env, thisVar).Schedule(procedureName, cbExec, cbComplete).val_; + } else { + NVal cb(env, funcArg[NARG_POS::FIRST]); + return NAsyncWorkCallback(env, thisVar, cb).Schedule(procedureName, cbExec, cbComplete).val_; } - - NVal cb(env, funcArg[NARG_POS::FIRST]); - return NAsyncWorkCallback(env, thisVar, cb).Schedule(procedureName, cbExec, cbComplete).val_; + return NVal::CreateUndefined(env).val_; } int GetUserId() @@ -83,14 +86,15 @@ napi_value GetUserDataDir(napi_env env, napi_callback_info info) return NVal::CreateUTF8String(env, *userDataPath); }; - static const std::string procedureName = "GetUserDataDir"; + std::string procedureName = "GetUserDataDir"; NVal thisVar(env, funcArg.GetThisVar()); if (funcArg.GetArgc() == NARG_CNT::ZERO) { return NAsyncWorkPromise(env, thisVar).Schedule(procedureName, cbExec, cbComplete).val_; + } else { + NVal cb(env, funcArg[NARG_POS::FIRST]); + return NAsyncWorkCallback(env, thisVar, cb).Schedule(procedureName, cbExec, cbComplete).val_; } - - NVal cb(env, funcArg[NARG_POS::FIRST]); - return NAsyncWorkCallback(env, thisVar, cb).Schedule(procedureName, cbExec, cbComplete).val_; + return NVal::CreateUndefined(env).val_; } } // namespace ModuleEnvironment } // namespace DistributedFS diff --git a/interfaces/kits/js/src/mod_environment/environment_n_exporter.h b/interfaces/kits/js/src/mod_environment/environment_n_exporter.h index 1b46a7b96924b89f17d889df4f1436be00dd2a53..cd610e5a7335f04c97a422ae863b2998340a2403 100644 --- a/interfaces/kits/js/src/mod_environment/environment_n_exporter.h +++ b/interfaces/kits/js/src/mod_environment/environment_n_exporter.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2022 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 diff --git a/interfaces/kits/js/src/mod_environment/environment_napi.cpp b/interfaces/kits/js/src/mod_environment/environment_napi.cpp index f6ec658a4fa60d99183e649250c0ee3a5446e5c0..670dd4e78af0548043910a1c6393c54875fa6db3 100644 --- a/interfaces/kits/js/src/mod_environment/environment_napi.cpp +++ b/interfaces/kits/js/src/mod_environment/environment_napi.cpp @@ -13,9 +13,13 @@ * limitations under the License. */ +#include "environment_napi.h" + #include "environment_n_exporter.h" -#include "napi/native_api.h" -#include "napi/native_node_api.h" +#include "js_native_api.h" +#include "js_native_api_types.h" +#include "napi/native_common.h" +#include "node_api.h" namespace OHOS { namespace DistributedFS { diff --git a/interfaces/kits/js/src/mod_environment/environment_napi.h b/interfaces/kits/js/src/mod_environment/environment_napi.h new file mode 100644 index 0000000000000000000000000000000000000000..3903f8c459972711b8aa0e709657f324522871c6 --- /dev/null +++ b/interfaces/kits/js/src/mod_environment/environment_napi.h @@ -0,0 +1,25 @@ +/* + * Copyright (c) 2021-2022 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. + */ + +#ifndef ENVIRONMENT_NAPI_H +#define ENVIRONMENT_NAPI_H + +namespace OHOS { +namespace DistributedFS { +namespace ModuleEnvironment { +} // namespace ModuleEnvironment +} // namespace DistributedFS +} // namespace OHOS +#endif // ENVIRONMENT_NAPI_H \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_file/class_file/file_n_exporter.cpp b/interfaces/kits/js/src/mod_file/class_file/file_n_exporter.cpp index 9633bbbbe2cce80cf33f7414b5e63881e83db69d..76f6f4880cfe191ee722a354e2bf7974bb34695a 100644 --- a/interfaces/kits/js/src/mod_file/class_file/file_n_exporter.cpp +++ b/interfaces/kits/js/src/mod_file/class_file/file_n_exporter.cpp @@ -32,7 +32,6 @@ #include "../../common/ability_helper.h" #include "../../common/file_helper/fd_guard.h" -#include "../../common/log.h" #include "../../common/napi/n_class.h" #include "../../common/napi/n_func_arg.h" #include "../../common/napi/n_val.h" @@ -43,19 +42,17 @@ namespace OHOS { namespace DistributedFS { namespace ModuleFile { using namespace std; -namespace { - constexpr int SUCCESS = 0; - constexpr int FAILED = -1; - constexpr int PARAMS_NUMBER_TWO = 2; - constexpr int URI_PARAMER_ERROR = 202; - constexpr int FILE_IO_ERROR = 300; - constexpr int FILE_PATH_ERROR = 301; - constexpr int DIR_FAULT_PERM = 0775; - constexpr int SPLIT_ZERO = 0; - static const string TYPE_FILE = "file"; - static const string TYPE_DIR = "dir"; - static const string ENCODING_UTF8 = "utf-8"; -} + +constexpr int SUCCESS = 0; +constexpr int FAILED = -1; +constexpr int URI_PARAMER_ERROR = 202; +constexpr int FILE_IO_ERROR = 300; +constexpr int FILE_PATH_ERROR = 301; +constexpr int DIR_FAULT_PERM = 0775; +constexpr int SPLITE_ZERO = 0; +const string TYPE_FILE = "file"; +const string TYPE_DIR = "dir"; +const string ENCODING_UTF8 = "utf-8"; void CallBackSuccess(napi_env env, napi_ref successFuncRef, int32_t count, napi_value obj) { @@ -72,7 +69,7 @@ void CallBackSuccess(napi_env env, napi_ref successFuncRef, int32_t count, napi_ void CallBackError(napi_env env, napi_ref failFuncRef, string errorProp, int errorCode) { - napi_value argvFail[PARAMS_NUMBER_TWO] = { 0 }; + napi_value argvFail[2] = { 0 }; napi_value results = nullptr; napi_value failFunc = nullptr; napi_value global = nullptr; @@ -99,54 +96,41 @@ void CallComplete(napi_env env, napi_ref completeFuncRef) napi_call_function(env, global, completeFunc, COMMON_NUM::ZERO, nullptr, &results); } -vector SplitString(const string &path) +bool CheckUri(napi_env env, string &path) { + constexpr int spilteOne = 1; + constexpr int spilteTwo = 2; + constexpr int spilteThree = 3; + string pathOrigin = path; vector uriSplit; + string pattern = "/"; if (path == "") { - HILOGE("Parameter path is empty"); - return uriSplit; + return false; } - - string pattern = "/"; - string pathTmp = path + pattern; + string pathTmp = pathOrigin + pattern; size_t pos = pathTmp.find(pattern); while (pos != pathTmp.npos) { - string temp = pathTmp.substr(SPLIT_ZERO, pos); + string temp = pathTmp.substr(SPLITE_ZERO, pos); uriSplit.push_back(temp); pathTmp = pathTmp.substr(pos + 1, pathTmp.size()); pos = pathTmp.find(pattern); } - - return uriSplit; -} - -bool CheckUri(napi_env env, string &path) -{ - constexpr int splitOne = 1; - constexpr int splitTwo = 2; - constexpr int splitThree = 3; - vector uriSplit = SplitString(path); - if (uriSplit[SPLIT_ZERO] != "internal:" || uriSplit[splitOne] != "" || uriSplit.size() <= splitThree) { - HILOGE("Illegal URI address"); + if (uriSplit[SPLITE_ZERO] != "internal:" || uriSplit[spilteOne] != "" || uriSplit.size() <= spilteThree) { return false; } - AppExecFwk::Ability *ability = AbilityHelper::GetJsAbility(env); if (!ability) { - HILOGE("JS ability object address is empty"); return false; } - auto abilityContext = ability->GetAbilityContext(); - if (abilityContext && uriSplit[splitTwo] == "app") { + if (abilityContext && uriSplit[spilteTwo] == "app") { path = abilityContext->GetFilesDir(); - } else if (abilityContext && uriSplit[splitTwo] == "cache") { + } else if (abilityContext && uriSplit[spilteTwo] == "cache") { path = abilityContext->GetCacheDir(); } else { - HILOGE("Failed to get URI path"); return false; } - for (size_t i = splitThree; i < uriSplit.size(); ++i) { + for (size_t i = spilteThree; i < uriSplit.size(); ++i) { path = path + "/" + uriSplit[i]; } return true; @@ -165,7 +149,17 @@ int GetRealPath(string &path) string UriToAbsolute(string path) { stack uriResult; - vector uriSplit = SplitString(path); + vector uriSplit; + string pattern = "/"; + + string pathTmp = path + pattern; + size_t pos = pathTmp.find(pattern); + while (pos != pathTmp.npos) { + string temp = pathTmp.substr(SPLITE_ZERO, pos); + uriSplit.push_back(temp); + pathTmp = pathTmp.substr(pos + 1, pathTmp.size()); + pos = pathTmp.find(pattern); + } for (auto urisp : uriSplit) { if (urisp == "." || urisp == "") { continue; @@ -183,12 +177,11 @@ string UriToAbsolute(string path) return path; } -bool GetFileNames(const string &path, vector &filenames, bool rec, bool isList) +bool GetFileNames(string path, vector &filenames, bool rec, bool isList) { DIR *pDir; struct dirent *ptr = nullptr; if (!(pDir = opendir(path.c_str()))) { - HILOGE("open a directory %{public}s failed", path.c_str()); return false; } while ((ptr = readdir(pDir)) != nullptr) { @@ -213,14 +206,12 @@ bool Mkdirs(string path) if (path[i] == '/') { path[i] = '\0'; if (access(path.c_str(), 0) != 0 && mkdir(path.c_str(), DIR_FAULT_PERM) == FAILED) { - HILOGE("create a directory %{public}s failed", path.c_str()); return false; } path[i] = '/'; } } if (path.length() <= 0 || access(path.c_str(), 0) == 0 || mkdir(path.c_str(), DIR_FAULT_PERM) == FAILED) { - HILOGE("path is empty, or access failed, or create a directory failed"); return false; } return true; @@ -231,7 +222,6 @@ bool Rmdirs(string path) DIR *pDir; struct dirent *ptr = nullptr; if (!(pDir = opendir(path.c_str()))) { - HILOGE("open a directory %{public}s failed", path.c_str()); return false; } while ((ptr = readdir(pDir)) != nullptr) { @@ -246,7 +236,6 @@ bool Rmdirs(string path) } closedir(pDir); if (rmdir(path.c_str()) != 0) { - HILOGE("delete a directory %{public}s failed", path.c_str()); return false; } return true; @@ -254,10 +243,6 @@ bool Rmdirs(string path) string ConvertUri(string path, string originPath, string originUri) { - if (originPath.length() > path.length()) { - return "error"; - } - if (path.find(originPath) != path.npos) { if (originUri[originUri.length() - 1] == '/') { originUri = originUri.substr(0, originUri.length() - 1); @@ -266,7 +251,6 @@ string ConvertUri(string path, string originPath, string originUri) } else { return "error"; } - return path; } @@ -969,21 +953,12 @@ napi_value FileNExporter::Mkdir(napi_env env, napi_callback_info info) }; tie(succ, asyncCallbackInfo->callback[COMMON_NUM::ZERO], asyncCallbackInfo->callback[COMMON_NUM::ONE], asyncCallbackInfo->callback[COMMON_NUM::TWO]) = CommonFunc::GetCallbackHandles(env, funcArg[NARG_POS::FIRST]); - if (!succ) { - HILOGE("Unpacking napi callback failed"); - } unique_ptr uri; tie(succ, uri, ignore) = NVal(env, funcArg[NARG_POS::FIRST]).GetProp("uri").ToUTF8String(); - if (!succ) { - HILOGE("Unpacking parameters uri failed"); - } bool recursive = false; tie(succ, recursive) = NVal(env, funcArg[NARG_POS::FIRST]).GetProp("recursive").ToBool(); - if (!succ) { - HILOGE("Unpacking parameters recursive failed"); - } string path = (uri == nullptr) ? "" : uri.get(); if (!CheckUri(env, path)) { @@ -1015,21 +990,12 @@ napi_value FileNExporter::Rmdir(napi_env env, napi_callback_info info) }; tie(succ, asyncCallbackInfo->callback[COMMON_NUM::ZERO], asyncCallbackInfo->callback[COMMON_NUM::ONE], asyncCallbackInfo->callback[COMMON_NUM::TWO]) = CommonFunc::GetCallbackHandles(env, funcArg[NARG_POS::FIRST]); - if (!succ) { - HILOGE("Unpacking napi callback failed"); - } unique_ptr uri; tie(succ, uri, ignore) = NVal(env, funcArg[NARG_POS::FIRST]).GetProp("uri").ToUTF8String(); - if (!succ) { - HILOGE("Unpacking parameters uri failed"); - } bool recursive = false; tie(succ, recursive) = NVal(env, funcArg[NARG_POS::FIRST]).GetProp("recursive").ToBool(); - if (!succ) { - HILOGE("Unpacking parameters recursive failed"); - } string path = (uri == nullptr) ? "" : uri.get(); if (!CheckUri(env, path)) { @@ -1062,22 +1028,11 @@ napi_value FileNExporter::Get(napi_env env, napi_callback_info info) bool succ = false; tie(succ, asyncCallbackInfo->callback[COMMON_NUM::ZERO], asyncCallbackInfo->callback[COMMON_NUM::ONE], asyncCallbackInfo->callback[COMMON_NUM::TWO]) = CommonFunc::GetCallbackHandles(env, funcArg[NARG_POS::FIRST]); - if (!succ) { - HILOGE("Unpacking napi callback failed"); - } - unique_ptr uri = nullptr; tie(succ, uri, ignore) = NVal(env, funcArg[NARG_POS::FIRST]).GetProp("uri").ToUTF8String(); - if (!succ) { - HILOGE("Unpacking parameters uri failed"); - } bool recursive = false; tie(succ, recursive) = NVal(env, funcArg[NARG_POS::FIRST]).GetProp("recursive").ToBool(); - if (!succ) { - HILOGE("Unpacking parameters recursive failed"); - } - string path = (uri == nullptr) ? "" : uri.get(); asyncCallbackInfo->originUri = path; if (!CheckUri(env, path)) { @@ -1110,15 +1065,9 @@ napi_value FileNExporter::List(napi_env env, napi_callback_info info) bool succ = false; tie(succ, asyncCallbackInfo->callback[COMMON_NUM::ZERO], asyncCallbackInfo->callback[COMMON_NUM::ONE], asyncCallbackInfo->callback[COMMON_NUM::TWO]) = CommonFunc::GetCallbackHandles(env, funcArg[NARG_POS::FIRST]); - if (!succ) { - HILOGE("Unpacking napi callback failed"); - } unique_ptr uri = nullptr; tie(succ, uri, ignore) = NVal(env, funcArg[NARG_POS::FIRST]).GetProp("uri").ToUTF8String(); - if (!succ) { - HILOGE("Unpacking parameters uri failed"); - } string path = (uri == nullptr) ? "" : uri.get(); asyncCallbackInfo->originUri = path; @@ -1151,21 +1100,10 @@ napi_value FileNExporter::Copy(napi_env env, napi_callback_info info) }; tie(succ, asyncCallbackInfo->callback[COMMON_NUM::ZERO], asyncCallbackInfo->callback[COMMON_NUM::ONE], asyncCallbackInfo->callback[COMMON_NUM::TWO]) = CommonFunc::GetCallbackHandles(env, funcArg[NARG_POS::FIRST]); - if (!succ) { - HILOGE("Unpacking napi callback failed"); - } unique_ptr srcUri, dstUri; tie(succ, srcUri, ignore) = NVal(env, funcArg[NARG_POS::FIRST]).GetProp("srcUri").ToUTF8String(); - if (!succ) { - HILOGE("Unpacking parameters srcUri failed"); - } - tie(succ, dstUri, ignore) = NVal(env, funcArg[NARG_POS::FIRST]).GetProp("dstUri").ToUTF8String(); - if (!succ) { - HILOGE("Unpacking parameters dstUri failed"); - } - string srcPath = ((srcUri == nullptr) ? "" : (srcUri.get())); string dstPath = ((dstUri == nullptr) ? "" : (dstUri.get())); asyncCallbackInfo->originDst = dstPath; @@ -1198,20 +1136,10 @@ napi_value FileNExporter::Move(napi_env env, napi_callback_info info) }; tie(succ, asyncCallbackInfo->callback[COMMON_NUM::ZERO], asyncCallbackInfo->callback[COMMON_NUM::ONE], asyncCallbackInfo->callback[COMMON_NUM::TWO]) = CommonFunc::GetCallbackHandles(env, funcArg[NARG_POS::FIRST]); - if (!succ) { - HILOGE("Unpacking napi callback failed"); - } unique_ptr srcUri, dstUri; tie(succ, srcUri, ignore) = NVal(env, funcArg[NARG_POS::FIRST]).GetProp("srcUri").ToUTF8String(); - if (!succ) { - HILOGE("Unpacking parameters srcUri failed"); - } - tie(succ, dstUri, ignore) = NVal(env, funcArg[NARG_POS::FIRST]).GetProp("dstUri").ToUTF8String(); - if (!succ) { - HILOGE("Unpacking parameters dstUri failed"); - } string srcPath = ((srcUri == nullptr) ? "" : (srcUri.get())); string dstPath = ((dstUri == nullptr) ? "" : (dstUri.get())); @@ -1245,15 +1173,9 @@ napi_value FileNExporter::Delete(napi_env env, napi_callback_info info) }; tie(succ, asyncCallbackInfo->callback[COMMON_NUM::ZERO], asyncCallbackInfo->callback[COMMON_NUM::ONE], asyncCallbackInfo->callback[COMMON_NUM::TWO]) = CommonFunc::GetCallbackHandles(env, funcArg[NARG_POS::FIRST]); - if (!succ) { - HILOGE("Unpacking napi callback failed"); - } unique_ptr uri; tie(succ, uri, ignore) = NVal(env, funcArg[NARG_POS::FIRST]).GetProp("uri").ToUTF8String(); - if (!succ) { - HILOGE("Unpacking parameters uri failed"); - } string path = (uri == nullptr) ? "" : uri.get(); if (!CheckUri(env, path)) { @@ -1285,15 +1207,9 @@ napi_value FileNExporter::Access(napi_env env, napi_callback_info info) }; tie(succ, asyncCallbackInfo->callback[COMMON_NUM::ZERO], asyncCallbackInfo->callback[COMMON_NUM::ONE], asyncCallbackInfo->callback[COMMON_NUM::TWO]) = CommonFunc::GetCallbackHandles(env, funcArg[NARG_POS::FIRST]); - if (!succ) { - HILOGE("Unpacking napi callback failed"); - } unique_ptr uri; tie(succ, uri, ignore) = NVal(env, funcArg[NARG_POS::FIRST]).GetProp("uri").ToUTF8String(); - if (!succ) { - HILOGE("Unpacking parameters uri failed"); - } string path = (uri == nullptr) ? "" : uri.get(); if (!CheckUri(env, path)) { @@ -1324,31 +1240,14 @@ napi_value FileNExporter::WriteText(napi_env env, napi_callback_info info) bool succ = false; tie(succ, asyncCallbackInfo->callback[COMMON_NUM::ZERO], asyncCallbackInfo->callback[COMMON_NUM::ONE], asyncCallbackInfo->callback[COMMON_NUM::TWO]) = CommonFunc::GetCallbackHandles(env, funcArg[NARG_POS::FIRST]); - if (!succ) { - HILOGE("Unpacking napi callback failed"); - } unique_ptr uri, text, encoding; tie(succ, uri, ignore) = NVal(env, funcArg[NARG_POS::FIRST]).GetProp("uri").ToUTF8String(); - if (!succ) { - HILOGE("Unpacking parameters uri failed"); - } - tie(succ, text, ignore) = NVal(env, funcArg[NARG_POS::FIRST]).GetProp("text").ToUTF8String(); - if (!succ) { - HILOGE("Unpacking parameters text failed"); - } - tie(succ, encoding, ignore) = NVal(env, funcArg[NARG_POS::FIRST]).GetProp("encoding").ToUTF8String(); - if (!succ) { - HILOGE("Unpacking parameters encoding failed"); - } bool append = false; tie(succ, append) = NVal(env, funcArg[NARG_POS::FIRST]).GetProp("append").ToBool(); - if (!succ) { - HILOGE("Unpacking parameters append failed"); - } string path = (uri == nullptr) ? "" : uri.get(); string encode = (encoding == nullptr) ? ENCODING_UTF8 : encoding.get(); @@ -1390,27 +1289,15 @@ napi_value FileNExporter::WriteArrayBuffer(napi_env env, napi_callback_info info }; tie(succ, asyncCallbackInfo->callback[COMMON_NUM::ZERO], asyncCallbackInfo->callback[COMMON_NUM::ONE], asyncCallbackInfo->callback[COMMON_NUM::TWO]) = CommonFunc::GetCallbackHandles(env, funcArg[NARG_POS::FIRST]); - if (!succ) { - HILOGE("Unpacking napi callback failed"); - } unique_ptr uri; tie(succ, uri, ignore) = NVal(env, funcArg[NARG_POS::FIRST]).GetProp("uri").ToUTF8String(); - if (!succ) { - HILOGE("Unpacking parameters uri failed"); - } int32_t position = 0; tie(succ, position) = NVal(env, funcArg[NARG_POS::FIRST]).GetProp("position").ToInt32(); - if (!succ) { - HILOGE("Unpacking parameters position failed"); - } bool append = false; tie(succ, append) = NVal(env, funcArg[NARG_POS::FIRST]).GetProp("append").ToBool(); - if (!succ) { - HILOGE("Unpacking parameters append failed"); - } void *buffer = nullptr; size_t bufLength = 0; @@ -1454,20 +1341,10 @@ napi_value FileNExporter::ReadText(napi_env env, napi_callback_info info) }; tie(succ, asyncCallbackInfo->callback[COMMON_NUM::ZERO], asyncCallbackInfo->callback[COMMON_NUM::ONE], asyncCallbackInfo->callback[COMMON_NUM::TWO]) = CommonFunc::GetCallbackHandles(env, funcArg[NARG_POS::FIRST]); - if (!succ) { - HILOGE("Unpacking napi callback failed"); - } unique_ptr uri, encoding; tie(succ, uri, ignore) = NVal(env, funcArg[NARG_POS::FIRST]).GetProp("uri").ToUTF8String(); - if (!succ) { - HILOGE("Unpacking parameters uri failed"); - } - tie(succ, encoding, ignore) = NVal(env, funcArg[NARG_POS::FIRST]).GetProp("encoding").ToUTF8String(); - if (!succ) { - HILOGE("Unpacking parameters encoding failed"); - } string path = (uri == nullptr) ? "" : uri.get(); string encode = (encoding == nullptr) ? ENCODING_UTF8 : encoding.get(); @@ -1506,27 +1383,15 @@ napi_value FileNExporter::ReadArrayBuffer(napi_env env, napi_callback_info info) bool succ = false; tie(succ, asyncCallbackInfo->callback[COMMON_NUM::ZERO], asyncCallbackInfo->callback[COMMON_NUM::ONE], asyncCallbackInfo->callback[COMMON_NUM::TWO]) = CommonFunc::GetCallbackHandles(env, funcArg[NARG_POS::FIRST]); - if (!succ) { - HILOGE("Unpacking napi callback failed"); - } unique_ptr uri; tie(succ, uri, ignore) = NVal(env, funcArg[NARG_POS::FIRST]).GetProp("uri").ToUTF8String(); - if (!succ) { - HILOGE("Unpacking parameters uri failed"); - } int position = 0; tie(succ, position) = NVal(env, funcArg[NARG_POS::FIRST]).GetProp("position").ToInt32(); - if (!succ) { - HILOGE("Unpacking parameters position failed"); - } int length = 0; tie(succ, length) = NVal(env, funcArg[NARG_POS::FIRST]).GetProp("length").ToInt32(); - if (!succ) { - HILOGE("Unpacking parameters length failed"); - } string path = (uri == nullptr) ? "" : uri.get(); if (!CheckUri(env, path)) { diff --git a/interfaces/kits/js/src/mod_file/class_file/file_n_exporter.h b/interfaces/kits/js/src/mod_file/class_file/file_n_exporter.h index b9760b8a5c75ee115c0bc81e3f16e46339401a74..e94ed1f48b81b34b5310cb4feb9bf43a572fc15d 100644 --- a/interfaces/kits/js/src/mod_file/class_file/file_n_exporter.h +++ b/interfaces/kits/js/src/mod_file/class_file/file_n_exporter.h @@ -13,18 +13,13 @@ * limitations under the License. */ -#ifndef INTERFACES_KITS_JS_SRC_MOD_FILE_CLASS_FILE_FILE_N_EXPORTER_H -#define INTERFACES_KITS_JS_SRC_MOD_FILE_CLASS_FILE_FILE_N_EXPORTER_H +#pragma once #include "../../common/napi/n_exporter.h" namespace OHOS { namespace DistributedFS { namespace ModuleFile { -namespace { - constexpr int32_t PARAMS_NUMBER_THREE = 3; - constexpr int32_t DEFAULT_RESULT = -100; -} enum COMMON_NUM { ZERO = 0, ONE = 1, @@ -43,40 +38,40 @@ struct FileInfo { struct AsyncAccessCallbackInfo { napi_env env = nullptr; napi_async_work asyncWork = nullptr; - napi_ref callback[PARAMS_NUMBER_THREE] = { 0 }; + napi_ref callback[3] = { 0 }; std::string url = ""; int errorType = -1; - int result = DEFAULT_RESULT; + int result = -100; }; struct AsyncMkdirCallbackInfo { napi_env env = nullptr; napi_async_work asyncWork = nullptr; - napi_ref callback[PARAMS_NUMBER_THREE] = { 0 }; + napi_ref callback[3] = { 0 }; bool recursive = false; std::string url = ""; - int result = DEFAULT_RESULT; + int result = -100; int errorType = -1; }; struct AsyncRmdirCallbackInfo { napi_env env = nullptr; napi_async_work asyncWork = nullptr; - napi_ref callback[PARAMS_NUMBER_THREE] = { 0 }; + napi_ref callback[3] = { 0 }; bool recursive = false; std::string url = ""; - int result = DEFAULT_RESULT; + int result = -100; int errorType = -1; }; struct AsyncGetCallbackInfo { napi_env env = nullptr; napi_async_work asyncWork = nullptr; - napi_ref callback[PARAMS_NUMBER_THREE] = { 0 }; + napi_ref callback[3] = { 0 }; bool recursive = false; std::string url = ""; std::string originUri = ""; - int result = DEFAULT_RESULT; + int result = -100; int errorType = -1; int32_t length = 0; int64_t lastMT = 0; @@ -87,11 +82,11 @@ struct AsyncGetCallbackInfo { struct AsyncListCallbackInfo { napi_env env = nullptr; napi_async_work asyncWork = nullptr; - napi_ref callback[PARAMS_NUMBER_THREE] = { 0 }; + napi_ref callback[3] = { 0 }; bool recursive = false; std::string url = ""; std::string originUri = ""; - int result = DEFAULT_RESULT; + int result = -100; int errorType = -1; std::vector fileList; }; @@ -99,52 +94,52 @@ struct AsyncListCallbackInfo { struct AsyncCopyCallbackInfo { napi_env env = nullptr; napi_async_work asyncWork = nullptr; - napi_ref callback[PARAMS_NUMBER_THREE] = { 0 }; + napi_ref callback[3] = { 0 }; std::string url = ""; std::string urlDst = ""; std::string originDst = ""; - int result = DEFAULT_RESULT; + int result = -100; int errorType = -1; }; struct AsyncMoveCallbackInfo { napi_env env = nullptr; napi_async_work asyncWork = nullptr; - napi_ref callback[PARAMS_NUMBER_THREE] = { 0 }; + napi_ref callback[3] = { 0 }; std::string url = ""; std::string urlDst = ""; std::string originDst = ""; - int result = DEFAULT_RESULT; + int result = -100; int errorType = -1; }; struct AsyncDeleteCallbackInfo { napi_env env = nullptr; napi_async_work asyncWork = nullptr; - napi_ref callback[PARAMS_NUMBER_THREE] = { 0 }; + napi_ref callback[3] = { 0 }; std::string url = ""; - int result = DEFAULT_RESULT; + int result = -100; int errorType = -1; }; struct AsyncWriteCallbackInfo { napi_env env = nullptr; napi_async_work asyncWork = nullptr; - napi_ref callback[PARAMS_NUMBER_THREE] = { 0 }; + napi_ref callback[3] = { 0 }; std::string url = ""; std::string text = ""; bool append = false; - int result = DEFAULT_RESULT; + int result = -100; int errorType = -1; }; struct AsyncWriteBufferCallbackInfo { napi_env env = nullptr; napi_async_work asyncWork = nullptr; - napi_ref callback[PARAMS_NUMBER_THREE] = { 0 }; + napi_ref callback[3] = { 0 }; std::string url = ""; bool append = false; - int result = DEFAULT_RESULT; + int result = -100; int errorType = -1; int32_t length = 0; int32_t position = 0; @@ -155,9 +150,9 @@ struct AsyncWriteBufferCallbackInfo { struct AsyncReadCallbackInfo { napi_env env = nullptr; napi_async_work asyncWork = nullptr; - napi_ref callback[PARAMS_NUMBER_THREE] = { 0 }; + napi_ref callback[3] = { 0 }; std::string url = ""; - int result = DEFAULT_RESULT; + int result = -100; int errorType = -1; std::string contents = ""; }; @@ -165,11 +160,11 @@ struct AsyncReadCallbackInfo { struct AsyncReadBufferCallbackInfo { napi_env env = nullptr; napi_async_work asyncWork = nullptr; - napi_ref callback[PARAMS_NUMBER_THREE] = { 0 }; + napi_ref callback[3] = { 0 }; std::string url = ""; int length = 0; int position = 0; - int result = DEFAULT_RESULT; + int result = -100; int errorType = -1; int32_t len = 0; std::string contents = ""; @@ -201,4 +196,3 @@ public: } // namespace ModuleFile } // namespace DistributedFS } // namespace OHOS -#endif // INTERFACES_KITS_JS_SRC_MOD_FILE_CLASS_FILE_FILE_N_EXPORTER_H diff --git a/interfaces/kits/js/src/mod_file/common_func.cpp b/interfaces/kits/js/src/mod_file/common_func.cpp index 4a9fa3d399a5552adb98a1ff64d32c852a96ad7e..87d58faefdd9c0dbd84ed1d68c4168a858ba8eb3 100644 --- a/interfaces/kits/js/src/mod_file/common_func.cpp +++ b/interfaces/kits/js/src/mod_file/common_func.cpp @@ -30,9 +30,9 @@ tuple CommonFunc::GetCallbackHandles(napi_en napi_ref successHandle = nullptr; napi_ref failHandle = nullptr; napi_ref completeHandle = nullptr; - const string success = "success"; - const string fail = "fail"; - const string complete = "complete"; + string success = "success"; + string fail = "fail"; + string complete = "complete"; successProp = prop.GetProp(success).val_; if (successProp != nullptr) { diff --git a/interfaces/kits/js/src/mod_file/common_func.h b/interfaces/kits/js/src/mod_file/common_func.h index 207411602e2346198b7edc1aae12e0ae06f0f160..54bf732514def886a3c870ca9e96f33e683ad05e 100644 --- a/interfaces/kits/js/src/mod_file/common_func.h +++ b/interfaces/kits/js/src/mod_file/common_func.h @@ -13,14 +13,17 @@ * limitations under the License. */ -#ifndef INTERFACES_KITS_JS_SRC_MOD_FILE_COMMON_FUNC_H -#define INTERFACES_KITS_JS_SRC_MOD_FILE_COMMON_FUNC_H +#pragma once #include "../common/napi/n_val.h" namespace OHOS { namespace DistributedFS { namespace ModuleFile { +const std::string FUNC_PROP_SUCCESS = "success"; +const std::string FUNC_PROP_FAIL = "fail"; +const std::string FUNC_PROP_COMPLETE = "complete"; + struct CommonFunc { static std::tuple GetCallbackHandles(napi_env env, napi_value object); @@ -28,4 +31,3 @@ struct CommonFunc { } // namespace ModuleFile } // namespace DistributedFS } // namespace OHOS -#endif // INTERFACES_KITS_JS_SRC_MOD_FILE_COMMON_FUNC_H diff --git a/interfaces/kits/js/src/mod_file/module.cpp b/interfaces/kits/js/src/mod_file/module.cpp index 6defa937f97fcb345b47afdeddd7957dbbadf02c..483abc53bbd8658d7100d6c0867a93769c501ff7 100644 --- a/interfaces/kits/js/src/mod_file/module.cpp +++ b/interfaces/kits/js/src/mod_file/module.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2022 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 diff --git a/interfaces/kits/js/src/mod_fileio/class_constants/constants.cpp b/interfaces/kits/js/src/mod_fileio/class_constants/constants.cpp index 162b4360af56b52cdf63ae16c8f2037355b934c2..551baf242608fb7d65a9cce36c383ea95aee303b 100644 --- a/interfaces/kits/js/src/mod_fileio/class_constants/constants.cpp +++ b/interfaces/kits/js/src/mod_fileio/class_constants/constants.cpp @@ -14,7 +14,6 @@ */ #include "constants.h" - #include #include #include @@ -23,8 +22,8 @@ #include #include #include - #include "securec.h" + #include "../../common/log.h" #include "../../common/napi/n_class.h" #include "../../common/napi/n_func_arg.h" @@ -50,79 +49,78 @@ bool Constants::Export() { // access napi_value F_OK_ = nullptr; - napi_create_int32(exports_.env_, 0, &F_OK_); // 0 F_OK + napi_create_int32(exports_.env_, F_OK, &F_OK_); // 0 F_OK napi_value R_OK_ = nullptr; - napi_create_int32(exports_.env_, 4, &R_OK_); // 4 R_OK + napi_create_int32(exports_.env_, R_OK, &R_OK_); // 4 R_OK napi_value W_OK_ = nullptr; - napi_create_int32(exports_.env_, 2, &W_OK_); // 2 W_OK + napi_create_int32(exports_.env_, W_OK, &W_OK_); // 2 W_OK napi_value X_OK_ = nullptr; - napi_create_int32(exports_.env_, 1, &X_OK_); // 1 X_OK - + napi_create_int32(exports_.env_, X_OK, &X_OK_); // 1 X_OK // open napi_value O_RDONLY_ = nullptr; - napi_create_int32(exports_.env_, 0, &O_RDONLY_); // 0 O_RDONLY + napi_create_int32(exports_.env_, O_RDONLY, &O_RDONLY_); // 0 O_RDONLY napi_value O_WRONLY_ = nullptr; - napi_create_int32(exports_.env_, 1, &O_WRONLY_); // 1 O_WRONLY + napi_create_int32(exports_.env_, O_WRONLY, &O_WRONLY_); // 1 O_WRONLY napi_value O_RDWR_ = nullptr; - napi_create_int32(exports_.env_, 2, &O_RDWR_); // 2 O_RDWR + napi_create_int32(exports_.env_, O_RDWR, &O_RDWR_); // 2 O_RDWR napi_value O_CREAT_ = nullptr; - napi_create_int32(exports_.env_, 0o100, &O_CREAT_); // 0o100 O_CREAT + napi_create_int32(exports_.env_, O_CREAT, &O_CREAT_); // 0o100 O_CREAT napi_value O_EXCL_ = nullptr; - napi_create_int32(exports_.env_, 0o200, &O_EXCL_); // 0o200 O_EXCL + napi_create_int32(exports_.env_, O_EXCL, &O_EXCL_); // 0o200 O_EXCL napi_value O_TRUNC_ = nullptr; - napi_create_int32(exports_.env_, 0o1000, &O_TRUNC_); // 0o1000 O_TRUNC + napi_create_int32(exports_.env_, O_TRUNC, &O_TRUNC_); // 0o1000 O_TRUNC napi_value O_APPEND_ = nullptr; - napi_create_int32(exports_.env_, 0o2000, &O_APPEND_); // 0o2000 O_APPEND + napi_create_int32(exports_.env_, O_APPEND, &O_APPEND_); // 0o2000 O_APPEND napi_value O_NONBLOCK_ = nullptr; - napi_create_int32(exports_.env_, 0o4000, &O_NONBLOCK_); // 0o4000 O_NONBLOCK + napi_create_int32(exports_.env_, O_NONBLOCK, &O_NONBLOCK_); // 0o4000 O_NONBLOCK napi_value O_DIRECTORY_ = nullptr; - napi_create_int32(exports_.env_, 0o200000, &O_DIRECTORY_); // 0o200000 O_DIRECTORY + napi_create_int32(exports_.env_, O_DIRECTORY, &O_DIRECTORY_); // 0o200000 O_DIRECTORY napi_value O_NOFOLLOW_ = nullptr; - napi_create_int32(exports_.env_, 0o400000, &O_NOFOLLOW_); // 0o400000 O_NOFOLLOW + napi_create_int32(exports_.env_, O_NOFOLLOW, &O_NOFOLLOW_); // 0o400000 O_NOFOLLOW napi_value O_SYNC_ = nullptr; - napi_create_int32(exports_.env_, 0o4010000, &O_SYNC_); // 0o4010000 O_SYNC + napi_create_int32(exports_.env_, O_SYNC, &O_SYNC_); // 0o4010000 O_SYNC // stat napi_value S_IFMT_ = nullptr; - napi_create_int32(exports_.env_, 0o170000, &S_IFMT_); // 0o170000 S_IFMT + napi_create_int32(exports_.env_, S_IFMT, &S_IFMT_); // 0o170000 S_IFMT napi_value S_IFSOCK_ = nullptr; - napi_create_int32(exports_.env_, 0o140000, &S_IFSOCK_); // 0o140000 S_IFSOCK + napi_create_int32(exports_.env_, S_IFSOCK, &S_IFSOCK_); // 0o140000 S_IFSOCK napi_value S_IFLNK_ = nullptr; - napi_create_int32(exports_.env_, 0o120000, &S_IFLNK_); // 0o120000 S_IFLNK + napi_create_int32(exports_.env_, S_IFLNK, &S_IFLNK_); // 0o120000 S_IFLNK napi_value S_IFREG_ = nullptr; - napi_create_int32(exports_.env_, 0o100000, &S_IFREG_); // 0o100000 S_IFREG + napi_create_int32(exports_.env_, S_IFREG, &S_IFREG_); // 0o100000 S_IFREG napi_value S_IFBLK_ = nullptr; - napi_create_int32(exports_.env_, 0o060000, &S_IFBLK_); // 0o060000 S_IFBLK + napi_create_int32(exports_.env_, S_IFBLK, &S_IFBLK_); // 0o060000 S_IFBLK napi_value S_IFDIR_ = nullptr; - napi_create_int32(exports_.env_, 0o040000, &S_IFDIR_); // 0o040000 S_IFDIR + napi_create_int32(exports_.env_, S_IFDIR, &S_IFDIR_); // 0o040000 S_IFDIR napi_value S_IFCHR_ = nullptr; - napi_create_int32(exports_.env_, 0o020000, &S_IFCHR_); // 0o020000 S_IFCHR + napi_create_int32(exports_.env_, S_IFCHR, &S_IFCHR_); // 0o020000 S_IFCHR napi_value S_IFIFO_ = nullptr; - napi_create_int32(exports_.env_, 0o010000, &S_IFIFO_); // 0o010000 S_IFIFO + napi_create_int32(exports_.env_, S_IFIFO, &S_IFIFO_); // 0o010000 S_IFIFO napi_value S_IRWXU_ = nullptr; - napi_create_int32(exports_.env_, 0o0700, &S_IRWXU_); // 0o0700 S_IRWXU + napi_create_int32(exports_.env_, S_IRWXU, &S_IRWXU_); // 0o0700 S_IRWXU napi_value S_IRUSR_ = nullptr; - napi_create_int32(exports_.env_, 0o0400, &S_IRUSR_); // 0o0400 S_IRUSR + napi_create_int32(exports_.env_, S_IRUSR, &S_IRUSR_); // 0o0400 S_IRUSR napi_value S_IWUSR_ = nullptr; - napi_create_int32(exports_.env_, 0o0200, &S_IWUSR_); // 0o0200 S_IWUSR + napi_create_int32(exports_.env_, S_IWUSR, &S_IWUSR_); // 0o0200 S_IWUSR napi_value S_IXUSR_ = nullptr; - napi_create_int32(exports_.env_, 0o0100, &S_IXUSR_); // 0o0100 S_IXUSR + napi_create_int32(exports_.env_, S_IXUSR, &S_IXUSR_); // 0o0100 S_IXUSR napi_value S_IRWXG_ = nullptr; - napi_create_int32(exports_.env_, 0o0070, &S_IRWXG_); // 0o0070 S_IRWXG + napi_create_int32(exports_.env_, S_IRWXG, &S_IRWXG_); // 0o0070 S_IRWXG napi_value S_IRGRP_ = nullptr; - napi_create_int32(exports_.env_, 0o0040, &S_IRGRP_); // 0o0040 S_IRGRP + napi_create_int32(exports_.env_, S_IRGRP, &S_IRGRP_); // 0o0040 S_IRGRP napi_value S_IWGRP_ = nullptr; - napi_create_int32(exports_.env_, 0o0020, &S_IWGRP_); // 0o0020 S_IWGRP + napi_create_int32(exports_.env_, S_IWGRP, &S_IWGRP_); // 0o0020 S_IWGRP napi_value S_IXGRP_ = nullptr; - napi_create_int32(exports_.env_, 0o0010, &S_IXGRP_); // 0o0010 S_IXGRP + napi_create_int32(exports_.env_, S_IXGRP, &S_IXGRP_); // 0o0010 S_IXGRP napi_value S_IRWXO_ = nullptr; - napi_create_int32(exports_.env_, 0o0007, &S_IRWXO_); // 0o0007 S_IRWXO + napi_create_int32(exports_.env_, S_IRWXO, &S_IRWXO_); // 0o0007 S_IRWXO napi_value S_IROTH_ = nullptr; - napi_create_int32(exports_.env_, 0o0004, &S_IROTH_); // 0o0004 S_IROTH + napi_create_int32(exports_.env_, S_IROTH, &S_IROTH_); // 0o0004 S_IROTH napi_value S_IWOTH_ = nullptr; - napi_create_int32(exports_.env_, 0o0002, &S_IWOTH_); // 0o0002 S_IWOTH + napi_create_int32(exports_.env_, S_IWOTH, &S_IWOTH_); // 0o0002 S_IWOTH napi_value S_IXOTH_ = nullptr; - napi_create_int32(exports_.env_, 0o0001, &S_IXOTH_); // 0o0001 S_IXOTH + napi_create_int32(exports_.env_, S_IXOTH, &S_IXOTH_); // 0o0001 S_IXOTH vector props = { NVal::DeclareNapiStaticProperty("F_OK", F_OK_), diff --git a/interfaces/kits/js/src/mod_fileio/class_constants/constants.h b/interfaces/kits/js/src/mod_fileio/class_constants/constants.h index 59da2b0bf163f856963990cedf983721269e9a13..3bc0fb668a351f1c770c634d02c70ecea27cff5a 100644 --- a/interfaces/kits/js/src/mod_fileio/class_constants/constants.h +++ b/interfaces/kits/js/src/mod_fileio/class_constants/constants.h @@ -13,8 +13,8 @@ * limitations under the License. */ -#ifndef INTERFACES_KITS_JS_SRC_MOD_FILEIO_CLASS_CONSTANTS_CONSTANTS_H -#define INTERFACES_KITS_JS_SRC_MOD_FILEIO_CLASS_CONSTANTS_CONSTANTS_H +#ifndef INTERFACES_KITS1_BAD_JS_SRC_MOD_FILEIO_CLASS_CONSTANTS_CONSTANTS_H +#define INTERFACES_KITS1_BAD_JS_SRC_MOD_FILEIO_CLASS_CONSTANTS_CONSTANTS_H #include "../../common/napi/n_exporter.h" @@ -23,7 +23,7 @@ namespace DistributedFS { namespace ModuleFileIO { class Constants final : public NExporter { public: - inline static const std::string className_ = "Constants"; + inline static const std::string className_ = "constants"; bool Export() override; std::string GetClassName() override; diff --git a/interfaces/kits/js/src/mod_fileio/class_dir/dir_entity.h b/interfaces/kits/js/src/mod_fileio/class_dir/dir_entity.h index ca5e77040fb5e5f9f69f0ad25e199939ce4680db..37f0cccbb5cfbcef84dac60542ca8c0e1108280a 100644 --- a/interfaces/kits/js/src/mod_fileio/class_dir/dir_entity.h +++ b/interfaces/kits/js/src/mod_fileio/class_dir/dir_entity.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2022 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 @@ -24,7 +24,7 @@ namespace DistributedFS { namespace ModuleFileIO { struct DirEntity { std::mutex lock_; - std::unique_ptr> dir_ = { nullptr, closedir }; + std::unique_ptr > dir_ = { nullptr, closedir }; }; } // namespace ModuleFileIO } // namespace DistributedFS diff --git a/interfaces/kits/js/src/mod_fileio/class_dir/dir_n_exporter.cpp b/interfaces/kits/js/src/mod_fileio/class_dir/dir_n_exporter.cpp index bbc53799dfb739ced5c8eebdd098e598562dcd0c..feb5241d49ab14ba0a5b831d844e2a1599ca0cb9 100644 --- a/interfaces/kits/js/src/mod_fileio/class_dir/dir_n_exporter.cpp +++ b/interfaces/kits/js/src/mod_fileio/class_dir/dir_n_exporter.cpp @@ -20,9 +20,8 @@ #include #include #include - -#include "dir_entity.h" #include "securec.h" + #include "../../common/napi/n_async/n_async_work_callback.h" #include "../../common/napi/n_async/n_async_work_promise.h" #include "../../common/napi/n_class.h" @@ -30,6 +29,7 @@ #include "../class_dirent/dirent_entity.h" #include "../class_dirent/dirent_n_exporter.h" #include "../common_func.h" +#include "dir_entity.h" namespace OHOS { namespace DistributedFS { @@ -73,12 +73,12 @@ napi_value DirNExporter::Close(napi_env env, napi_callback_info info) } auto dirEntity = NClass::GetEntityOf(env, funcArg.GetThisVar()); - if (dirEntity == nullptr) { + if (!dirEntity) { UniError(EIO).ThrowErr(env, "Cannot get entity of Dir"); return nullptr; } - if (dirEntity->dir_ == nullptr) { + if (!dirEntity || !dirEntity->dir_) { UniError(EBADF).ThrowErr(env, "Dir has been closed yet"); return nullptr; } @@ -101,13 +101,13 @@ napi_value DirNExporter::Close(napi_env env, napi_callback_info info) }; NVal thisVar(env, funcArg.GetThisVar()); - static const string procedureName = "fileioDirClose"; + string procedureName = "fileioDirClose"; if (funcArg.GetArgc() == NARG_CNT::ZERO) { return NAsyncWorkPromise(env, thisVar).Schedule(procedureName, cbExec, cbCompl).val_; + } else { + NVal cb(env, funcArg[NARG_POS::FIRST]); + return NAsyncWorkCallback(env, thisVar, cb).Schedule(procedureName, cbExec, cbCompl).val_; } - - NVal cb(env, funcArg[NARG_POS::FIRST]); - return NAsyncWorkCallback(env, thisVar, cb).Schedule(procedureName, cbExec, cbCompl).val_; } struct DirReadArgs { @@ -122,7 +122,7 @@ struct DirReadArgs { explicit DirReadArgs(NVal obj) : thisptrRef_(obj) {} }; -static NVal DoReadComplete(napi_env env, UniError err, shared_ptr arg) +static NVal DoReadCompile(napi_env env, UniError err, shared_ptr arg) { if (err) { return { env, err.GetNapiErr(env) }; @@ -137,7 +137,7 @@ static NVal DoReadComplete(napi_env env, UniError err, shared_ptr a } if (strlen(arg->dirRes.d_name) == 0) { - return { env, nullptr }; + return { env, NVal::CreateUndefined(env).val_ }; } else { direntEntity->dirent_ = arg->dirRes; return { env, objDirent }; @@ -165,9 +165,6 @@ napi_value DirNExporter::Read(napi_env env, napi_callback_info info) } DIR *dir = dirEntity->dir_.get(); - if (dir == nullptr) { - return nullptr; - } auto arg = make_shared(NVal(env, funcArg.GetThisVar())); auto cbExec = [arg, dir, dirEntity](napi_env env) -> UniError { struct dirent tmpDirent; @@ -192,15 +189,14 @@ napi_value DirNExporter::Read(napi_env env, napi_callback_info info) return UniError(ERRNO_NOERR); }; auto cbCompl = [arg](napi_env env, UniError err) -> NVal { - return DoReadComplete(env, err, arg); + return DoReadCompile(env, err, arg); }; NVal thisVar(env, funcArg.GetThisVar()); - const string procedureName = "fileioDirRead"; if (funcArg.GetArgc() == NARG_CNT::ZERO) { - return NAsyncWorkPromise(env, thisVar).Schedule(procedureName, cbExec, cbCompl).val_; + return NAsyncWorkPromise(env, thisVar).Schedule("fileioDirRead", cbExec, cbCompl).val_; } else { NVal cb(env, funcArg[NARG_POS::FIRST]); - return NAsyncWorkCallback(env, thisVar, cb).Schedule(procedureName, cbExec, cbCompl).val_; + return NAsyncWorkCallback(env, thisVar, cb).Schedule("fileioDirRead", cbExec, cbCompl).val_; } } @@ -253,6 +249,161 @@ napi_value DirNExporter::ReadSync(napi_env env, napi_callback_info info) return objDirent; } +struct DirListFileArgs { + vector dirents; + explicit DirListFileArgs() + { + dirents = vector(); + } + ~DirListFileArgs() = default; +}; + +static DirEntity *CheckDirEntity(napi_env env, napi_value dir_entity) +{ + auto dirEntity = NClass::GetEntityOf(env, dir_entity); + if (!dirEntity) { + UniError(EIO).ThrowErr(env, "Cannot get entity of Dir"); + return nullptr; + } + + if (!dirEntity || !dirEntity->dir_) { + UniError(EBADF).ThrowErr(env, "Dir has been closed yet"); + return nullptr; + } + return dirEntity; +} + +static tuple ParseJsListNum(napi_env env, napi_value listNumFromJs) +{ + auto [succ, listNum] = NVal(env, listNumFromJs).ToInt32(); + return {succ, listNum}; +} + +static napi_value DoListFileVector2NV(napi_env env, vector dirents) +{ + napi_value res = nullptr; + napi_create_array(env, &res); + for (size_t i = 0; i < dirents.size(); i++) { + napi_value objDirent = NClass::InstantiateClass(env, DirentNExporter::className_, {}); + if (!objDirent) { + UniError(EINVAL).ThrowErr(env); + return nullptr; + } + auto direntEntity = NClass::GetEntityOf(env, objDirent); + if (!direntEntity) { + UniError(EINVAL).ThrowErr(env); + return nullptr; + } + direntEntity->dirent_ = dirents[i]; + napi_set_element(env, res, i, objDirent); + } + return res; +} + +static NVal DoListFileCompile(napi_env env, UniError err, shared_ptr arg) +{ + if (err) { + return { env, err.GetNapiErr(env) }; + } else { + return { env, DoListFileVector2NV(env, arg->dirents) }; + } +} + +napi_value DirNExporter::ListFile(napi_env env, napi_callback_info info) +{ + NFuncArg funcArg(env, info); + if (!funcArg.InitArgs(NARG_CNT::ONE, NARG_CNT::TWO)) { + UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); + return nullptr; + } + auto dirEntity = CheckDirEntity(env, funcArg.GetThisVar()); + if (!dirEntity) { + return nullptr; + } + auto [succ, num] = ParseJsListNum(env, funcArg[NARG_POS::FIRST]); + if (!succ) { + UniError(EINVAL).ThrowErr(env, "Invalid listNum"); + return nullptr; + } + + DIR *dir = dirEntity->dir_.get(); + auto arg = make_shared(); + int listNum = num; + auto cbExec = [arg, dir, dirEntity, listNum](napi_env env) -> UniError { + lock_guard(dirEntity->lock_); + errno = 0; + dirent *res = nullptr; + int listCount = 0; + do { + res = readdir(dir); + if (res == nullptr && errno) { + return UniError(errno); + } else if (res == nullptr) { + return UniError(ERRNO_NOERR); + } else if (string(res->d_name) == "." || string(res->d_name) == "..") { + continue; + } else { + arg->dirents.push_back(*res); + listCount++; + } + } while (listCount < listNum || listNum == 0); + return UniError(ERRNO_NOERR); + }; + auto cbCompl = [arg](napi_env env, UniError err) -> NVal { + return DoListFileCompile(env, err, arg); + }; + NVal thisVar(env, funcArg.GetThisVar()); + + if (funcArg.GetArgc() == NARG_CNT::ONE) { + return NAsyncWorkPromise(env, thisVar).Schedule(listfileProcedureName, cbExec, cbCompl).val_; + } else { + NVal cb(env, funcArg[NARG_POS::SECOND]); + return NAsyncWorkCallback(env, thisVar, cb).Schedule(listfileProcedureName, cbExec, cbCompl).val_; + } +} + +napi_value DirNExporter::ListFileSync(napi_env env, napi_callback_info info) +{ + NFuncArg funcArg(env, info); + if (!funcArg.InitArgs(NARG_CNT::ONE)) { + UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); + return nullptr; + } + auto dirEntity = CheckDirEntity(env, funcArg.GetThisVar()); + if (!dirEntity) { + return nullptr; + } + auto [succ, listNum] = ParseJsListNum(env, funcArg[NARG_POS::FIRST]); + if (!succ) { + UniError(EINVAL).ThrowErr(env, "Invalid listNum"); + return nullptr; + } + + vector dirents; + { + lock_guard(dirEntity->lock_); + errno = 0; + dirent *res = nullptr; + int listCount = 0; + auto dir = dirEntity->dir_.get(); + do { + res = readdir(dir); + if (res == nullptr && errno) { + UniError(errno).ThrowErr(env); + return nullptr; + } else if (res == nullptr) { + break; + } else if (string(res->d_name) == "." || string(res->d_name) == "..") { + continue; + } else { + dirents.push_back(*res); + listCount++; + } + } while (listCount < listNum || listNum == 0); + } + return DoListFileVector2NV(env, dirents); +} + napi_value DirNExporter::Constructor(napi_env env, napi_callback_info info) { NFuncArg funcArg(env, info); @@ -274,11 +425,14 @@ bool DirNExporter::Export() vector props = { NVal::DeclareNapiFunction("readSync", ReadSync), NVal::DeclareNapiFunction("closeSync", CloseSync), + NVal::DeclareNapiFunction("listfileSync", ListFileSync), NVal::DeclareNapiFunction("read", Read), NVal::DeclareNapiFunction("close", Close), + NVal::DeclareNapiFunction("listfile", ListFile), }; string className = GetClassName(); + bool succ = false; napi_value classValue = nullptr; tie(succ, classValue) = NClass::DefineClass(exports_.env_, className, DirNExporter::Constructor, std::move(props)); diff --git a/interfaces/kits/js/src/mod_fileio/class_dir/dir_n_exporter.h b/interfaces/kits/js/src/mod_fileio/class_dir/dir_n_exporter.h index 156ef5578fbd96560b99346b509a74611f986555..f338d483aa2a538adc2ea4084bd830459a36587b 100644 --- a/interfaces/kits/js/src/mod_fileio/class_dir/dir_n_exporter.h +++ b/interfaces/kits/js/src/mod_fileio/class_dir/dir_n_exporter.h @@ -13,8 +13,8 @@ * limitations under the License. */ -#ifndef INTERFACES_KITS_JS_SRC_MOD_FILEIO_CLASS_DIR_DIR_N_EXPORTER_H -#define INTERFACES_KITS_JS_SRC_MOD_FILEIO_CLASS_DIR_DIR_N_EXPORTER_H +#ifndef INTERFACES_KITS1_BAD_JS_SRC_MOD_FILEIO_CLASS_DIR_DIR_N_EXPORTER_H +#define INTERFACES_KITS1_BAD_JS_SRC_MOD_FILEIO_CLASS_DIR_DIR_N_EXPORTER_H #include @@ -34,11 +34,14 @@ public: static napi_value CloseSync(napi_env env, napi_callback_info info); static napi_value ReadSync(napi_env env, napi_callback_info info); + static napi_value ListFileSync(napi_env env, napi_callback_info info); static napi_value Read(napi_env env, napi_callback_info info); static napi_value Close(napi_env env, napi_callback_info info); + static napi_value ListFile(napi_env env, napi_callback_info info); DirNExporter(napi_env env, napi_value exports); ~DirNExporter() override; }; +const std::string listfileProcedureName = "fileioDirListFile"; } // namespace ModuleFileIO } // namespace DistributedFS } // namespace OHOS diff --git a/interfaces/kits/js/src/mod_fileio/class_dirent/dirent_entity.h b/interfaces/kits/js/src/mod_fileio/class_dirent/dirent_entity.h index d92fa69a2276f6d05a5c258300c07edb9c6a390e..e96db6f1917429de6a4c928e7220e44f46da12ab 100644 --- a/interfaces/kits/js/src/mod_fileio/class_dirent/dirent_entity.h +++ b/interfaces/kits/js/src/mod_fileio/class_dirent/dirent_entity.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2022 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 diff --git a/interfaces/kits/js/src/mod_fileio/class_dirent/dirent_n_exporter.cpp b/interfaces/kits/js/src/mod_fileio/class_dirent/dirent_n_exporter.cpp index 9961eeb209046d866445faac578c622f2fda9284..a235da4e759740806baab671d447276a5a7bba3f 100644 --- a/interfaces/kits/js/src/mod_fileio/class_dirent/dirent_n_exporter.cpp +++ b/interfaces/kits/js/src/mod_fileio/class_dirent/dirent_n_exporter.cpp @@ -22,6 +22,7 @@ #include #include "securec.h" + #include "../../common/log.h" #include "../../common/napi/n_class.h" #include "../../common/napi/n_func_arg.h" @@ -114,9 +115,7 @@ napi_value DirentNExporter::Constructor(napi_env env, napi_callback_info info) auto direntEntity = make_unique(); if (!NClass::SetEntityFor(env, funcArg.GetThisVar(), move(direntEntity))) { - stringstream ss; - ss << "INNER BUG. Failed to wrap entity for obj dirent"; - UniError(EIO).ThrowErr(env, ss.str()); + UniError(EIO).ThrowErr(env, "INNER BUG. Failed to wrap entity for obj dirent"); return nullptr; } return funcArg.GetThisVar(); @@ -137,6 +136,7 @@ bool DirentNExporter::Export() }; string className = GetClassName(); + bool succ = false; napi_value classValue = nullptr; tie(succ, classValue) = NClass::DefineClass(exports_.env_, diff --git a/interfaces/kits/js/src/mod_fileio/class_dirent/dirent_n_exporter.h b/interfaces/kits/js/src/mod_fileio/class_dirent/dirent_n_exporter.h index 0f60629e09429656f044da1090fa5974c116b994..15745255df7ed1381712ee52c626357376747b46 100644 --- a/interfaces/kits/js/src/mod_fileio/class_dirent/dirent_n_exporter.h +++ b/interfaces/kits/js/src/mod_fileio/class_dirent/dirent_n_exporter.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2022 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 diff --git a/interfaces/kits/js/src/mod_fileio/class_randomaccessfile/randomaccessfile_entity.h b/interfaces/kits/js/src/mod_fileio/class_randomaccessfile/randomaccessfile_entity.h new file mode 100644 index 0000000000000000000000000000000000000000..2a7dceae98975f8fa21ca8de984b6fbcf5f53685 --- /dev/null +++ b/interfaces/kits/js/src/mod_fileio/class_randomaccessfile/randomaccessfile_entity.h @@ -0,0 +1,33 @@ +/* + * Copyright (c) 2022 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. + */ + +#ifndef INTERFACES_KITS_JS_SRC_MOD_FILEIO_CLASS_RANDOMACCESSFILE_RANDOMACCESSFILE_ENTITY_H +#define INTERFACES_KITS_JS_SRC_MOD_FILEIO_CLASS_RANDOMACCESSFILE_RANDOMACCESSFILE_ENTITY_H + +#include + +#include "../../common/file_helper/fd_guard.h" + +namespace OHOS { +namespace DistributedFS { +namespace ModuleFileIO { +struct RandomAccessFileEntity { + std::unique_ptr fd_ = { nullptr }; + size_t fpointer; +}; +} // namespace ModuleFileIO +} // namespace DistributedFS +} // namespace OHOS +#endif \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fileio/class_randomaccessfile/randomaccessfile_n_exporter.cpp b/interfaces/kits/js/src/mod_fileio/class_randomaccessfile/randomaccessfile_n_exporter.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e27a1fed9bdc2bfca324ab90361bf6d58db0b194 --- /dev/null +++ b/interfaces/kits/js/src/mod_fileio/class_randomaccessfile/randomaccessfile_n_exporter.cpp @@ -0,0 +1,416 @@ +/* + * Copyright (c) 2022 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. + */ + +#include "randomaccessfile_n_exporter.h" + +#include +#include +#include +#include +#include +#include + +#include "../../common/log.h" +#include "../../common/napi/n_async/n_async_work_callback.h" +#include "../../common/napi/n_async/n_async_work_promise.h" +#include "../../common/napi/n_class.h" +#include "../../common/napi/n_func_arg.h" +#include "../../common/uni_error.h" +#include "../common_func.h" +#include "randomaccessfile_entity.h" + +namespace OHOS { +namespace DistributedFS { +namespace ModuleFileIO { +using namespace std; + +static RandomAccessFileEntity *GetRAFEntity(napi_env env, napi_value raf_entity) +{ + auto rafEntity = NClass::GetEntityOf(env, raf_entity); + if (!rafEntity) { + UniError(EINVAL).ThrowErr(env, "Cannot get entity of RandomAccessFile"); + return nullptr; + } + if (!rafEntity->fd_) { + UniError(EINVAL).ThrowErr(env, "RandomAccessFile has been closed yet"); + return nullptr; + } + return rafEntity; +} + +static tuple ParseJsFP(napi_env env, napi_value FPFromJs) +{ + auto [succ, fp] = NVal(env, FPFromJs).ToInt32(); + return { succ, fp }; +} + +static tuple GetRAFReadArg(napi_env env, + napi_value ReadBuf, napi_value option) +{ + bool succ = false, hasPos = false; + void *buf = nullptr; + size_t len, pos, offset; + tie(succ, buf, len, hasPos, pos, offset) = CommonFunc::GetReadArg(env, ReadBuf, option); + if (!succ) { + return { false, nullptr, 0, false, 0, 0 }; + } + return { succ, buf, len, hasPos, pos, offset }; +} + +static tuple GetRAFWriteArg(napi_env env, + napi_value WriteBuf, napi_value option) +{ + bool succ = false, hasPos = false; + void *buf = nullptr; + size_t len, pos; + tie(succ, ignore, buf, len, hasPos, pos) = CommonFunc::GetWriteArg(env, WriteBuf, option); + if (!succ) { + return { false, nullptr, 0, false, 0 }; + } + return { succ, buf, len, hasPos, pos }; +} + +static size_t DoReadRAF(napi_env env, void* buf, size_t len, int fd, size_t pos) +{ + uv_loop_s *loop = nullptr; + uv_fs_t read_req; + napi_get_uv_event_loop(env, &loop); + uv_buf_t iov = uv_buf_init((char *)buf, len); + size_t ret = uv_fs_read(loop, &read_req, fd, &iov, 1, pos, NULL); + uv_fs_req_cleanup(&read_req); + return ret; +} + +static size_t DoWriteRAF(napi_env env, void* buf, size_t len, int fd, size_t pos) +{ + uv_loop_s *loop = nullptr; + uv_fs_t write_req; + napi_get_uv_event_loop(env, &loop); + uv_buf_t iov = uv_buf_init((char *)buf, len); + size_t ret = uv_fs_write(loop, &write_req, fd, &iov, 1, pos, NULL); + uv_fs_req_cleanup(&write_req); + return ret; +} + +napi_value RandomAccessFileNExporter::GetFD(napi_env env, napi_callback_info info) +{ + NFuncArg funcArg(env, info); + if (!funcArg.InitArgs(NARG_CNT::ZERO)) { + UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); + return nullptr; + } + auto rafEntity = GetRAFEntity(env, funcArg.GetThisVar()); + if (!rafEntity) { + return nullptr; + } + return NVal::CreateInt32(env, rafEntity->fd_.get()->GetFD()).val_; +} + +napi_value RandomAccessFileNExporter::GetFPointer(napi_env env, napi_callback_info info) +{ + NFuncArg funcArg(env, info); + if (!funcArg.InitArgs(NARG_CNT::ZERO)) { + UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); + return nullptr; + } + auto rafEntity = GetRAFEntity(env, funcArg.GetThisVar()); + if (!rafEntity) { + return nullptr; + } + return NVal::CreateInt64(env, rafEntity->fpointer).val_; +} + +napi_value RandomAccessFileNExporter::SetFilePointerSync(napi_env env, napi_callback_info info) +{ + NFuncArg funcArg(env, info); + if (!funcArg.InitArgs(NARG_CNT::ONE)) { + UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); + return nullptr; + } + auto rafEntity = GetRAFEntity(env, funcArg.GetThisVar()); + if (!rafEntity) { + return nullptr; + } + auto [succ, fp] = ParseJsFP(env, funcArg[NARG_POS::FIRST]); + if (!succ) { + UniError(EINVAL).ThrowErr(env, "Invalid fpointer"); + } + rafEntity->fpointer = fp; + return NVal::CreateUndefined(env).val_; +} + +napi_value RandomAccessFileNExporter::ReadSync(napi_env env, napi_callback_info info) +{ + NFuncArg funcArg(env, info); + if (!funcArg.InitArgs(NARG_CNT::ONE, NARG_CNT::TWO)) { + UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); + return nullptr; + } + auto rafEntity = GetRAFEntity(env, funcArg.GetThisVar()); + if (!rafEntity) { + return nullptr; + } + auto [succ, buf, len, hasPos, pos, ignore] = + GetRAFReadArg(env, funcArg[NARG_POS::FIRST], funcArg[NARG_POS::SECOND]); + if (!succ) { + UniError(EINVAL).ThrowErr(env, "Invalid buffer/options"); + } + ssize_t actLen = DoReadRAF(env, buf, len, rafEntity->fd_.get()->GetFD(), rafEntity->fpointer + pos); + if (actLen < 0) { + UniError(errno).ThrowErr(env); + return nullptr; + } + rafEntity->fpointer += actLen; + return NVal::CreateInt64(env, actLen).val_; +} + +struct AsyncIOReadArg { + ssize_t lenRead { 0 }; + int offset { 0 }; + NRef refReadBuf; + + explicit AsyncIOReadArg(NVal jsReadBuf) : refReadBuf(jsReadBuf) {} + ~AsyncIOReadArg() = default; +}; + +napi_value RandomAccessFileNExporter::Read(napi_env env, napi_callback_info info) +{ + NFuncArg funcArg(env, info); + if (!funcArg.InitArgs(NARG_CNT::ONE, NARG_CNT::THREE)) { + UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); + return nullptr; + } + auto rafEntity = GetRAFEntity(env, funcArg.GetThisVar()); + if (!rafEntity) { + return nullptr; + } + bool succ = false, hasPos = false; + size_t len, pos, offset; + void* buf = nullptr; + tie(succ, buf, len, hasPos, pos, offset) = GetRAFReadArg(env, funcArg[NARG_POS::FIRST], funcArg[NARG_POS::SECOND]); + if (!succ) { + UniError(EINVAL).ThrowErr(env, "Invalid buffer/options"); + return nullptr; + } + + auto arg = make_shared(NVal(env, funcArg[NARG_POS::FIRST])); + auto cbExec = [arg, buf, len, hasPos, pos, offset, rafEntity](napi_env env) -> UniError { + ssize_t actLen = DoReadRAF(env, buf, len, rafEntity->fd_.get()->GetFD(), rafEntity->fpointer + pos); + if (actLen < 0) { + return UniError(errno); + } + arg->lenRead = actLen; + arg->offset = offset; + rafEntity->fpointer += actLen; + return UniError(ERRNO_NOERR); + }; + + auto cbCompl = [arg](napi_env env, UniError err) -> NVal { + if (err) { + return { env, err.GetNapiErr(env) }; + } + NVal obj = NVal::CreateObject(env); + obj.AddProp( + { NVal::DeclareNapiProperty("bytesRead", NVal::CreateInt64(env, arg->lenRead).val_), + NVal::DeclareNapiProperty("buffer", arg->refReadBuf.Deref(env).val_), + NVal::DeclareNapiProperty("offset", NVal::CreateInt64(env, arg->offset).val_) + }); + return { obj }; + }; + + NVal thisVar(env, funcArg.GetThisVar()); + if (funcArg.GetArgc() == NARG_CNT::ONE || (funcArg.GetArgc() == NARG_CNT::TWO && + !NVal(env, funcArg[NARG_POS::SECOND]).TypeIs(napi_function))) { + return NAsyncWorkPromise(env, thisVar).Schedule(readProcedureName, cbExec, cbCompl).val_; + } else { + int cbIdx = ((funcArg.GetArgc() == NARG_CNT::TWO) ? NARG_POS::SECOND : NARG_POS::THIRD); + NVal cb(env, funcArg[cbIdx]); + return NAsyncWorkCallback(env, thisVar, cb).Schedule(readProcedureName, cbExec, cbCompl).val_; + } + return NVal::CreateUndefined(env).val_; +} + +napi_value RandomAccessFileNExporter::WriteSync(napi_env env, napi_callback_info info) +{ + NFuncArg funcArg(env, info); + if (!funcArg.InitArgs(NARG_CNT::ONE, NARG_CNT::TWO)) { + UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); + return nullptr; + } + + auto rafEntity = GetRAFEntity(env, funcArg.GetThisVar()); + if (!rafEntity) { + return nullptr; + } + + bool succ = false, hasPos = false; + void *buf = nullptr; + size_t len, pos; + tie(succ, buf, len, hasPos, pos) = GetRAFWriteArg(env, funcArg[NARG_POS::FIRST], funcArg[NARG_POS::SECOND]); + if (!succ) { + UniError(EINVAL).ThrowErr(env, "Invalid buffer/options"); + return nullptr; + } + if (hasPos) { + pos = rafEntity->fpointer + pos; + } else { + pos = rafEntity->fpointer; + } + ssize_t writeLen = DoWriteRAF(env, buf, len, rafEntity->fd_.get()->GetFD(), pos); + if (writeLen < 0) { + UniError(errno).ThrowErr(env); + return nullptr; + } + rafEntity->fpointer += writeLen; + return NVal::CreateInt64(env, writeLen).val_; +} + +struct AsyncIOWriteArg { + NRef refWriteArrayBuf_; + size_t actLen = 0; + explicit AsyncIOWriteArg(NVal refWriteArrayBuf) : refWriteArrayBuf_(refWriteArrayBuf) {} + ~AsyncIOWriteArg() = default; +}; + +napi_value RandomAccessFileNExporter::Write(napi_env env, napi_callback_info info) +{ + NFuncArg funcArg(env, info); + if (!funcArg.InitArgs(NARG_CNT::ONE, NARG_CNT::THREE)) { + UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); + return nullptr; + } + + auto rafEntity = GetRAFEntity(env, funcArg.GetThisVar()); + if (!rafEntity) { + return nullptr; + } + bool succ = false, hasPos = false; + void *buf = nullptr; + size_t len, pos; + tie(succ, buf, len, hasPos, pos) = GetRAFWriteArg(env, funcArg[NARG_POS::FIRST], funcArg[NARG_POS::SECOND]); + if (!succ) { + UniError(EINVAL).ThrowErr(env, "Invalid buffer/options"); + return nullptr; + } + if (hasPos) { + pos = rafEntity->fpointer + pos; + } else { + pos = rafEntity->fpointer; + } + + auto arg = make_shared(NVal(env, funcArg[NARG_POS::FIRST])); + auto cbExec = [arg, buf, len, fd = rafEntity->fd_.get()->GetFD(), pos, rafEntity](napi_env env) -> UniError { + size_t writeLen = DoWriteRAF(env, buf, len, fd, pos); + if (writeLen < 0) { + return UniError(errno); + } + arg->actLen = writeLen; + rafEntity->fpointer += writeLen; + return UniError(ERRNO_NOERR); + }; + + auto cbCompl = [arg](napi_env env, UniError err) -> NVal { + if (err) { + return { env, err.GetNapiErr(env) }; + } else { + return { NVal::CreateInt64(env, arg->actLen) }; + } + }; + + NVal thisVar(env, funcArg.GetThisVar()); + if (funcArg.GetArgc() == NARG_CNT::ONE || (funcArg.GetArgc() == NARG_CNT::TWO && + !NVal(env, funcArg[NARG_POS::SECOND]).TypeIs(napi_function))) { + return NAsyncWorkPromise(env, thisVar).Schedule(writeProcedureName, cbExec, cbCompl).val_; + } else { + int cbIdx = ((funcArg.GetArgc() == NARG_CNT::TWO) ? NARG_POS::SECOND : NARG_POS::THIRD); + NVal cb(env, funcArg[cbIdx]); + return NAsyncWorkCallback(env, thisVar, cb).Schedule(writeProcedureName, cbExec, cbCompl).val_; + } + return NVal::CreateUndefined(env).val_; +} + +napi_value RandomAccessFileNExporter::CloseSync(napi_env env, napi_callback_info info) +{ + NFuncArg funcArg(env, info); + if (!funcArg.InitArgs(NARG_CNT::ZERO)) { + UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); + return nullptr; + } + auto rafEntity = GetRAFEntity(env, funcArg.GetThisVar()); + if (!rafEntity) { + return nullptr; + } + rafEntity->fd_.reset(); + return NVal::CreateUndefined(env).val_; +} + +napi_value RandomAccessFileNExporter::Constructor(napi_env env, napi_callback_info info) +{ + NFuncArg funcArg(env, info); + if (!funcArg.InitArgs(NARG_CNT::ZERO)) { + UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); + return nullptr; + } + + auto rafEntity = make_unique(); + if (!NClass::SetEntityFor(env, funcArg.GetThisVar(), move(rafEntity))) { + UniError(EIO).ThrowErr(env, "INNER BUG. Failed to wrap entity for obj RandomAccessFile"); + return nullptr; + } + return funcArg.GetThisVar(); +} + +bool RandomAccessFileNExporter::Export() +{ + vector props = { + NVal::DeclareNapiFunction("read", Read), + NVal::DeclareNapiFunction("readSync", ReadSync), + NVal::DeclareNapiFunction("write", Write), + NVal::DeclareNapiFunction("writeSync", WriteSync), + NVal::DeclareNapiFunction("setFilePointerSync", SetFilePointerSync), + NVal::DeclareNapiFunction("closeSync", CloseSync), + NVal::DeclareNapiGetter("fd", GetFD), + NVal::DeclareNapiGetter("fpointer", GetFPointer), + }; + + string className = GetClassName(); + bool succ = false; + napi_value classValue = nullptr; + tie(succ, classValue) = NClass::DefineClass(exports_.env_, className, + RandomAccessFileNExporter::Constructor, move(props)); + if (!succ) { + UniError(EIO).ThrowErr(exports_.env_, "INNER BUG. Failed to define class"); + return false; + } + succ = NClass::SaveClass(exports_.env_, className, classValue); + if (!succ) { + UniError(EIO).ThrowErr(exports_.env_, "INNER BUG. Failed to save class"); + return false; + } + + return exports_.AddProp(className, classValue); +} + +string RandomAccessFileNExporter::GetClassName() +{ + return RandomAccessFileNExporter::className_; +} + +RandomAccessFileNExporter::RandomAccessFileNExporter(napi_env env, napi_value exports) : NExporter(env, exports) {} + +RandomAccessFileNExporter::~RandomAccessFileNExporter() {} +} // namespace ModuleFileIO +} // namespace DistributedFS +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fileio/class_randomaccessfile/randomaccessfile_n_exporter.h b/interfaces/kits/js/src/mod_fileio/class_randomaccessfile/randomaccessfile_n_exporter.h new file mode 100644 index 0000000000000000000000000000000000000000..bd89a1b9c9d581bbff8a1bae84f1d481b5753e23 --- /dev/null +++ b/interfaces/kits/js/src/mod_fileio/class_randomaccessfile/randomaccessfile_n_exporter.h @@ -0,0 +1,52 @@ +/* + * Copyright (c) 2022 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. + */ + +#ifndef INTERFACES_KITS_JS_SRC_MOD_FILEIO_CLASS_RANDOMACCESSFILE_RANDOMACCESSFILE_N_EXPORTER_H +#define INTERFACES_KITS_JS_SRC_MOD_FILEIO_CLASS_RANDOMACCESSFILE_RANDOMACCESSFILE_N_EXPORTER_H + +#include "../../common/napi/n_exporter.h" + +namespace OHOS { +namespace DistributedFS { +namespace ModuleFileIO { +class RandomAccessFileNExporter final : public NExporter { +public: + inline static const std::string className_ = "RandomAccessFile"; + + bool Export() override; + std::string GetClassName() override; + + static napi_value Constructor(napi_env env, napi_callback_info cbinfo); + + static napi_value SetFilePointerSync(napi_env env, napi_callback_info cbinfo); + static napi_value WriteSync(napi_env env, napi_callback_info cbinfo); + static napi_value ReadSync(napi_env env, napi_callback_info cbinfo); + static napi_value CloseSync(napi_env env, napi_callback_info cbinfo); + + static napi_value Write(napi_env env, napi_callback_info cbinfo); + static napi_value Read(napi_env env, napi_callback_info cbinfo); + + static napi_value GetFD(napi_env env, napi_callback_info cbinfo); + static napi_value GetFPointer(napi_env env, napi_callback_info cbinfo); + + RandomAccessFileNExporter(napi_env env, napi_value exports); + ~RandomAccessFileNExporter() override; +}; +const std::string readProcedureName = "FileIORandomAccessFileRead"; +const std::string writeProcedureName = "FileIORandomAccessFileWrite"; +} // namespace ModuleFileIO +} // namespace DistributedFS +} // namespace OHOS +#endif \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fileio/class_stat/stat_entity.h b/interfaces/kits/js/src/mod_fileio/class_stat/stat_entity.h index a82c30f75045c77dbeb05fbf65bc501e6d3a7c31..97be8f1f4cef97761c302b2bebd22f3eacbd3c5e 100644 --- a/interfaces/kits/js/src/mod_fileio/class_stat/stat_entity.h +++ b/interfaces/kits/js/src/mod_fileio/class_stat/stat_entity.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2022 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 diff --git a/interfaces/kits/js/src/mod_fileio/class_stat/stat_n_exporter.cpp b/interfaces/kits/js/src/mod_fileio/class_stat/stat_n_exporter.cpp index 85295fc4ea279fbec7ee13dabc76c3c984b1fde1..bf940fd87b38ff33dbdce10730c7c27188869d19 100644 --- a/interfaces/kits/js/src/mod_fileio/class_stat/stat_n_exporter.cpp +++ b/interfaces/kits/js/src/mod_fileio/class_stat/stat_n_exporter.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2022 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 @@ -14,6 +14,8 @@ */ #include "stat_n_exporter.h" +#include "../../common/napi/n_async/n_async_work_callback.h" +#include "../../common/napi/n_async/n_async_work_promise.h" #include #include @@ -22,9 +24,8 @@ #include #include "securec.h" + #include "../../common/log.h" -#include "../../common/napi/n_async/n_async_work_callback.h" -#include "../../common/napi/n_async/n_async_work_promise.h" #include "../../common/napi/n_class.h" #include "../../common/napi/n_func_arg.h" #include "../../common/uni_error.h" @@ -305,9 +306,7 @@ napi_value StatNExporter::Constructor(napi_env env, napi_callback_info info) unique_ptr statEntity = make_unique(); if (!NClass::SetEntityFor(env, funcArg.GetThisVar(), move(statEntity))) { - stringstream ss; - ss << "INNER BUG. Failed to wrap entity for obj stat"; - UniError(EIO).ThrowErr(env, ss.str()); + UniError(EIO).ThrowErr(env, "INNER BUG. Failed to wrap entity for obj stat"); return nullptr; } return funcArg.GetThisVar(); diff --git a/interfaces/kits/js/src/mod_fileio/class_stat/stat_n_exporter.h b/interfaces/kits/js/src/mod_fileio/class_stat/stat_n_exporter.h index 4304856649cc81f9e6b455207e98a3f1dc6b208b..eeece11b54a0b02ef2b69d34cab54247abd2a50a 100644 --- a/interfaces/kits/js/src/mod_fileio/class_stat/stat_n_exporter.h +++ b/interfaces/kits/js/src/mod_fileio/class_stat/stat_n_exporter.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2022 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 diff --git a/interfaces/kits/js/src/mod_fileio/class_stream/flush.cpp b/interfaces/kits/js/src/mod_fileio/class_stream/flush.cpp index 590b47e95eea7e25a8e5c85fa91c23764ca2300c..a4b985a83d62dfc9af5b1a8d5bd00d7716a78bf4 100644 --- a/interfaces/kits/js/src/mod_fileio/class_stream/flush.cpp +++ b/interfaces/kits/js/src/mod_fileio/class_stream/flush.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2022 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 diff --git a/interfaces/kits/js/src/mod_fileio/class_stream/flush.h b/interfaces/kits/js/src/mod_fileio/class_stream/flush.h index c616571b3f8c3435cbb0ea2bd336661f18bff024..fb305b228a9570ca4d6a8937a9c0f53d720ca5c8 100644 --- a/interfaces/kits/js/src/mod_fileio/class_stream/flush.h +++ b/interfaces/kits/js/src/mod_fileio/class_stream/flush.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2022 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 diff --git a/interfaces/kits/js/src/mod_fileio/class_stream/stream_entity.h b/interfaces/kits/js/src/mod_fileio/class_stream/stream_entity.h index 1c010e0152f224dbfd129bf1f3351f0f79cdb081..534f6108b3307c62c8e5571c003b92ce7fa4cd01 100644 --- a/interfaces/kits/js/src/mod_fileio/class_stream/stream_entity.h +++ b/interfaces/kits/js/src/mod_fileio/class_stream/stream_entity.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2022 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 diff --git a/interfaces/kits/js/src/mod_fileio/class_stream/stream_n_exporter.cpp b/interfaces/kits/js/src/mod_fileio/class_stream/stream_n_exporter.cpp index cdcbf78feb2096f1ee0b9e8a2a2a73e2ca8d2742..c9c4923ad7830676e6becd0348c496ba5accade1 100644 --- a/interfaces/kits/js/src/mod_fileio/class_stream/stream_n_exporter.cpp +++ b/interfaces/kits/js/src/mod_fileio/class_stream/stream_n_exporter.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2022 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 @@ -342,6 +342,7 @@ napi_value StreamNExporter::Close(napi_env env, napi_callback_info info) napi_value StreamNExporter::Constructor(napi_env env, napi_callback_info info) { NFuncArg funcArg(env, info); + if (!funcArg.InitArgs(NARG_CNT::ZERO)) { UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); return nullptr; @@ -349,9 +350,7 @@ napi_value StreamNExporter::Constructor(napi_env env, napi_callback_info info) unique_ptr streamEntity = make_unique(); if (!NClass::SetEntityFor(env, funcArg.GetThisVar(), move(streamEntity))) { - stringstream ss; - ss << "INNER BUG. Failed to wrap entity for obj stat"; - UniError(EIO).ThrowErr(env, ss.str()); + UniError(EIO).ThrowErr(env, "INNER BUG. Failed to wrap entity for obj stream"); return nullptr; } return funcArg.GetThisVar(); diff --git a/interfaces/kits/js/src/mod_fileio/class_stream/stream_n_exporter.h b/interfaces/kits/js/src/mod_fileio/class_stream/stream_n_exporter.h index 3cfe4d2d204f21f3481e4518094bae338f7bede8..794aca11b879bcc15151e675472629598fc05c77 100644 --- a/interfaces/kits/js/src/mod_fileio/class_stream/stream_n_exporter.h +++ b/interfaces/kits/js/src/mod_fileio/class_stream/stream_n_exporter.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2022 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 diff --git a/interfaces/kits/js/src/mod_fileio/class_watcher/watcher_entity.h b/interfaces/kits/js/src/mod_fileio/class_watcher/watcher_entity.h index ce604ee6b042eb0159ba61ad0bd1fd0251c9ebbb..06135f155387a9222f87d90e680ca425054c85d8 100644 --- a/interfaces/kits/js/src/mod_fileio/class_watcher/watcher_entity.h +++ b/interfaces/kits/js/src/mod_fileio/class_watcher/watcher_entity.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2022 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 @@ -16,8 +16,6 @@ #ifndef INTERFACES_KITS_JS_SRC_MOD_FILEIO_CLASS_WATCHER_WATCHER_ENTITY_H #define INTERFACES_KITS_JS_SRC_MOD_FILEIO_CLASS_WATCHER_WATCHER_ENTITY_H -#include - #include "../../common/napi/uni_header.h" namespace OHOS { @@ -27,10 +25,6 @@ class WatcherHandleDeleter { public: void operator()(uv_fs_event_t *ptr) { - if (ptr == nullptr) { - return; - } - uv_fs_event_stop(ptr); uv_handle_t *handle = reinterpret_cast(ptr); uv_close(handle, [](uv_handle_t *handle) { delete handle; }); diff --git a/interfaces/kits/js/src/mod_fileio/class_watcher/watcher_n_exporter.cpp b/interfaces/kits/js/src/mod_fileio/class_watcher/watcher_n_exporter.cpp index f6c456ed1a23f58e07cb35190fe20a7eb63e007d..a4e27d4f38db3895fa6a6eab783d02d7c72813c5 100644 --- a/interfaces/kits/js/src/mod_fileio/class_watcher/watcher_n_exporter.cpp +++ b/interfaces/kits/js/src/mod_fileio/class_watcher/watcher_n_exporter.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2022 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 @@ -19,6 +19,9 @@ #include #include #include +#include + +#include "securec.h" #include "../../common/log.h" #include "../../common/napi/n_async/n_async_work_callback.h" @@ -26,7 +29,6 @@ #include "../../common/napi/n_class.h" #include "../../common/napi/n_func_arg.h" #include "../../common/uni_error.h" -#include "securec.h" #include "watcher_entity.h" namespace OHOS { @@ -44,10 +46,9 @@ napi_value WatcherNExporter::Constructor(napi_env env, napi_callback_info info) unique_ptr watcherEntity = make_unique(); if (!NClass::SetEntityFor(env, funcArg.GetThisVar(), move(watcherEntity))) { - UniError(EIO).ThrowErr(env, "INNER BUG. Failed to wrap entity for obj stat"); + UniError(EIO).ThrowErr(env, "INNER BUG. Failed to wrap entity for obj watcher"); return nullptr; } - return funcArg.GetThisVar(); } @@ -95,7 +96,7 @@ napi_value WatcherNExporter::Stop(napi_env env, napi_callback_info info) return { NVal::CreateUndefined(env) }; }; - const string procedureName = "FileIOCreaterWatcher"; + string procedureName = "FileIOCreaterWatcher"; NVal thisVar(env, funcArg.GetThisVar()); if (funcArg.GetArgc() == NARG_CNT::ZERO) { return NAsyncWorkPromise(env, thisVar).Schedule(procedureName, cbExec, cbCompl).val_; @@ -113,16 +114,17 @@ bool WatcherNExporter::Export() }; string className = GetClassName(); - auto [resDefineClass, classValue) = NClass::DefineClass(exports_.env_, + bool succ = false; + napi_value classValue = nullptr; + tie(succ, classValue) = NClass::DefineClass(exports_.env_, className, WatcherNExporter::Constructor, std::move(props)); - if (!resDefineClass) { + if (!succ) { UniError(EIO).ThrowErr(exports_.env_, "INNER BUG. Failed to define class"); return false; } - - bool succ = NClass::SaveClass(exports_.env_, className, classValue); + succ = NClass::SaveClass(exports_.env_, className, classValue); if (!succ) { UniError(EIO).ThrowErr(exports_.env_, "INNER BUG. Failed to save class"); return false; diff --git a/interfaces/kits/js/src/mod_fileio/class_watcher/watcher_n_exporter.h b/interfaces/kits/js/src/mod_fileio/class_watcher/watcher_n_exporter.h index 3d3502b7babfd5d7c3037cb51d1aee7e1ffa845a..bd539d5fde100ea120cdf9d3a4e7347d892276d2 100644 --- a/interfaces/kits/js/src/mod_fileio/class_watcher/watcher_n_exporter.h +++ b/interfaces/kits/js/src/mod_fileio/class_watcher/watcher_n_exporter.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2022 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 @@ -16,6 +16,8 @@ #ifndef INTERFACES_KITS_JS_SRC_MOD_FILEIO_CLASS_WATCHER_WATCHER_N_EXPORTER_H #define INTERFACES_KITS_JS_SRC_MOD_FILEIO_CLASS_WATCHER_WATCHER_N_EXPORTER_H +#include + #include "../../common/napi/n_exporter.h" namespace OHOS { diff --git a/interfaces/kits/js/src/mod_fileio/common_func.cpp b/interfaces/kits/js/src/mod_fileio/common_func.cpp index d8d8e857708f67597853021d73f28d3d0f1740b8..fa985fc056ae37bf197e6c96a1e6f1ffff1b727a 100644 --- a/interfaces/kits/js/src/mod_fileio/common_func.cpp +++ b/interfaces/kits/js/src/mod_fileio/common_func.cpp @@ -59,6 +59,7 @@ static tuple GetActualLen(napi_env env, int64_t bufLen, int64_t bu { bool succ = false; int64_t retLen; + if (op.HasProp("length")) { int64_t opLength; tie(succ, opLength) = op.GetProp("length").ToInt64(); @@ -66,72 +67,109 @@ static tuple GetActualLen(napi_env env, int64_t bufLen, int64_t bu UniError(EINVAL).ThrowErr(env, "Invalid option.length, expect integer"); return { false, 0 }; } - if (opLength < 0) { - retLen = (bufLen > bufOff) ? bufLen - bufOff : 0; - } else if ((bufLen > opLength) && (bufOff > bufLen - opLength)) { + retLen = bufLen - bufOff; + } else if (opLength + bufOff > bufLen) { UniError(EINVAL).ThrowErr(env, "Invalid option.length, buffer limit exceeded"); return { false, 0 }; } else { retLen = opLength; } } else { - retLen = (bufLen > bufOff) ? bufLen - bufOff : 0; + retLen = bufLen - bufOff; } return { true, retLen }; } +int CommonFunc::ConvertJsFlags(int &flags) +{ + static constexpr int USR_O_RDONLY = 00; + static constexpr int USR_O_WRONLY = 01; + static constexpr int USR_O_RDWR = 02; + static constexpr int USR_O_CREAT = 0100; + static constexpr int USR_O_EXCL = 0200; + static constexpr int USR_O_TRUNC = 01000; + static constexpr int USR_O_APPEND = 02000; + static constexpr int USR_O_NONBLOCK = 04000; + static constexpr int USR_O_DIRECTORY = 0200000; + static constexpr int USR_O_NOFOLLOW = 0400000; + static constexpr int USR_O_SYNC = 04010000; + + int flagsABI = 0; + flagsABI |= ((flags & USR_O_RDONLY) == USR_O_RDONLY) ? O_RDONLY : 0; + flagsABI |= ((flags & USR_O_WRONLY) == USR_O_WRONLY) ? O_WRONLY : 0; + flagsABI |= ((flags & USR_O_RDWR) == USR_O_RDWR) ? O_RDWR : 0; + flagsABI |= ((flags & USR_O_CREAT) == USR_O_CREAT) ? O_CREAT : 0; + flagsABI |= ((flags & USR_O_EXCL) == USR_O_EXCL) ? O_EXCL : 0; + flagsABI |= ((flags & USR_O_TRUNC) == USR_O_TRUNC) ? O_TRUNC : 0; + flagsABI |= ((flags & USR_O_APPEND) == USR_O_APPEND) ? O_APPEND : 0; + flagsABI |= ((flags & USR_O_NONBLOCK) == USR_O_NONBLOCK) ? O_NONBLOCK : 0; + flagsABI |= ((flags & USR_O_DIRECTORY) == USR_O_DIRECTORY) ? O_DIRECTORY : 0; + flagsABI |= ((flags & USR_O_NOFOLLOW) == USR_O_NOFOLLOW) ? O_NOFOLLOW : 0; + flagsABI |= ((flags & USR_O_SYNC) == USR_O_SYNC) ? O_SYNC : 0; + flags = flagsABI; + return flagsABI; +} + tuple, unique_ptr> CommonFunc::GetCopyPathArg(napi_env env, napi_value srcPath, napi_value dstPath) { - auto [succ, src, unuse] = NVal(env, srcPath).ToUTF8String(); + bool succ = false; + unique_ptr src; + tie(succ, src, ignore) = NVal(env, srcPath).ToUTF8String(); if (!succ) { return { false, nullptr, nullptr }; } - tie(res, dest, useless) = NVal(env, dstPath).ToUTF8String(); - if (!res) { + unique_ptr dest; + tie(succ, dest, ignore) = NVal(env, dstPath).ToUTF8String(); + if (!succ) { return { false, nullptr, nullptr }; } - - return make_tuple(true, move(src), move(dest)); + return make_tuple(succ, move(src), move(dest)); } tuple CommonFunc::GetReadArg(napi_env env, napi_value readBuf, napi_value option) { + bool succ = false; + void *retBuf = nullptr; + int64_t retLen; bool posAssigned = false; - int64_t position = 0; + int64_t position; + NVal txt(env, readBuf); - auto [resToArraybuffer, buf, bufLen] = txt.ToArraybuffer(); - if (!resToArraybuffer) { + void *buf = nullptr; + int64_t bufLen; + int offset = 0; + tie(succ, buf, bufLen) = txt.ToArraybuffer(); + if (!succ) { UniError(EINVAL).ThrowErr(env, "Invalid read buffer, expect arraybuffer"); - return { false, nullptr, 0, posAssigned, position, 0 }; + return { false, nullptr, 0, posAssigned, position, offset }; } NVal op = NVal(env, option); - auto [resGetActualBuf, retBuf, offset] = GetActualBuf(env, buf, bufLen, op); - if (!resGetActualBuf) { - return { false, nullptr, 0, posAssigned, position, 0 }; + tie(succ, retBuf, offset) = GetActualBuf(env, buf, bufLen, op); + if (!succ) { + return { false, nullptr, 0, posAssigned, position, offset }; } int64_t bufOff = static_cast(retBuf) - static_cast(buf); - auto [resGetActualLen, retLen] = GetActualLen(env, bufLen, bufOff, op); - if (!resGetActualLen) { - return { false, nullptr, 0, posAssigned, position, 0 }; + tie(succ, retLen) = GetActualLen(env, bufLen, bufOff, op); + if (!succ) { + return { false, nullptr, 0, posAssigned, position, offset }; } if (op.HasProp("position")) { - auto [resGetProp, pos] = op.GetProp("position").ToInt64(); - if (resGetProp && pos >= 0) { + tie(succ, position) = op.GetProp("position").ToInt64(); + if (succ && position >= 0) { posAssigned = true; - position = pos; } else { UniError(EINVAL).ThrowErr(env, "option.position shall be positive number"); - return { false, nullptr, 0, posAssigned, position, 0 }; + return { false, nullptr, 0, posAssigned, position, offset }; } } @@ -145,16 +183,16 @@ static tuple, int64_t> DecodeString(napi_env env, NVal return { false, nullptr, 0 }; } + bool succ = false; if (!encoding) { return jsStr.ToUTF8String(); } unique_ptr encodingBuf; - auto [resToUTF8String, encodingBuf, unuse] = encoding.ToUTF8String(); - if (!resToUTF8String) { + tie(succ, encodingBuf, ignore) = encoding.ToUTF8String(); + if (!succ) { return { false, nullptr, 0 }; } - string encodingStr(encodingBuf.release()); if (encodingStr == "utf-8") { return jsStr.ToUTF8String(); @@ -165,42 +203,50 @@ static tuple, int64_t> DecodeString(napi_env env, NVal } } +// Is everything ok? Do we need to free memory? What's the three args required by fwrite? Where to start writing? tuple, void *, int64_t, bool, int64_t> CommonFunc::GetWriteArg(napi_env env, napi_value argWBuf, napi_value argOption) { + void *retBuf = nullptr; + int64_t retLen; bool hasPos = false; - int64_t retPos = 0; + int64_t retPos; + + /* To get write buffer */ bool succ = false; void *buf = nullptr; + int64_t bufLen; NVal op(env, argOption); NVal jsBuffer(env, argWBuf); - auto [resDecodeString, bufferGuard, bufLen] = DecodeString(env, jsBuffer, op.GetProp("encoding")); - if (!resDecodeString) { + unique_ptr bufferGuard; + tie(succ, bufferGuard, bufLen) = DecodeString(env, jsBuffer, op.GetProp("encoding")); + if (!succ) { tie(succ, buf, bufLen) = NVal(env, argWBuf).ToArraybuffer(); if (!succ) { UniError(EINVAL).ThrowErr(env, "Illegal write buffer or encoding"); - return { false, nullptr, nullptr, 0, false, 0 }; + return { false, nullptr, nullptr, 0, hasPos, retPos }; } } else { buf = bufferGuard.get(); } - auto [resGetActualBuf, retBuf, unused] = GetActualBuf(env, buf, bufLen, op); - if (!resGetActualBuf) { - return { false, nullptr, nullptr, 0, false, 0 }; + tie(succ, retBuf, ignore) = GetActualBuf(env, buf, bufLen, op); + if (!succ) { + return { false, nullptr, nullptr, 0, hasPos, retPos }; } int64_t bufOff = static_cast(retBuf) - static_cast(buf); - auto [resGetActualLen, retLen] = GetActualLen(env, bufLen, bufOff, op); - if (!resGetActualLen) { - return { false, nullptr, nullptr, 0, false, 0 }; + tie(succ, retLen) = GetActualLen(env, bufLen, bufOff, op); + if (!succ) { + return { false, nullptr, nullptr, 0, hasPos, retPos }; } /* To parse options - Where to begin writing */ if (op.HasProp("position")) { - auto [resGetProp, position] = op.GetProp("position").ToInt32(); - if (!resGetProp || position < 0) { + int32_t position = 0; + tie(succ, position) = op.GetProp("position").ToInt32(); + if (!succ || position < 0) { UniError(EINVAL).ThrowErr(env, "option.position shall be positive number"); return { false, nullptr, nullptr, 0, hasPos, retPos }; } @@ -209,7 +255,6 @@ tuple, void *, int64_t, bool, int64_t> CommonFunc::GetW } else { retPos = INVALID_POSITION; } - return { true, move(bufferGuard), retBuf, retLen, hasPos, retPos }; } } // namespace ModuleFileIO diff --git a/interfaces/kits/js/src/mod_fileio/common_func.h b/interfaces/kits/js/src/mod_fileio/common_func.h index f968bb40bc22cbcfbf4eaf5660b41e63ece5d70b..a8aff6739c2a4c756896cceef8198561786afecc 100644 --- a/interfaces/kits/js/src/mod_fileio/common_func.h +++ b/interfaces/kits/js/src/mod_fileio/common_func.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2022 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 @@ -24,9 +24,10 @@ namespace ModuleFileIO { constexpr int64_t INVALID_POSITION = std::numeric_limits::max(); struct CommonFunc { + static int ConvertJsFlags(int &flags); static std::tuple GetReadArg(napi_env env, - napi_value readBuf, - napi_value option); + napi_value readBuf, + napi_value option); static std::tuple, void *, int64_t, bool, int64_t> GetWriteArg(napi_env env, napi_value argWBuf, napi_value argOption); diff --git a/interfaces/kits/js/src/mod_fileio/module.cpp b/interfaces/kits/js/src/mod_fileio/module.cpp index 51bd91fd03f73edb66e6f11f8baf9335e6633b5f..b26592acb850f6dab3a0cae722cf4d1e66adcd5d 100644 --- a/interfaces/kits/js/src/mod_fileio/module.cpp +++ b/interfaces/kits/js/src/mod_fileio/module.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2022 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 @@ -20,6 +20,7 @@ #include "class_constants/constants.h" #include "class_dir/dir_n_exporter.h" #include "class_dirent/dirent_n_exporter.h" +#include "class_randomaccessfile/randomaccessfile_n_exporter.h" #include "class_stat/stat_n_exporter.h" #include "class_stream/stream_n_exporter.h" #include "class_watcher/watcher_n_exporter.h" @@ -36,6 +37,7 @@ static napi_value Export(napi_env env, napi_value exports) products.emplace_back(make_unique(env, exports)); products.emplace_back(make_unique(env, exports)); products.emplace_back(make_unique(env, exports)); + products.emplace_back(make_unique(env, exports)); products.emplace_back(make_unique(env, exports)); products.emplace_back(make_unique(env, exports)); products.emplace_back(make_unique(env, exports)); diff --git a/interfaces/kits/js/src/mod_fileio/properties/chmod.cpp b/interfaces/kits/js/src/mod_fileio/properties/chmod.cpp index 3bc5a6364f2b7c4c977d71c1ff7a8f1dac429b0b..4508f51ceed57476aed1246c5669fd458ae1c99e 100644 --- a/interfaces/kits/js/src/mod_fileio/properties/chmod.cpp +++ b/interfaces/kits/js/src/mod_fileio/properties/chmod.cpp @@ -14,16 +14,13 @@ */ #include "chmod.h" - #include #include #include #include - #include "../../common/napi/n_async/n_async_work_callback.h" #include "../../common/napi/n_async/n_async_work_promise.h" #include "../../common/napi/n_func_arg.h" - namespace OHOS { namespace DistributedFS { namespace ModuleFileIO { @@ -32,19 +29,23 @@ using namespace std; napi_value Chmod::Sync(napi_env env, napi_callback_info info) { NFuncArg funcArg(env, info); + if (!funcArg.InitArgs(NARG_CNT::TWO)) { UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); return nullptr; } - auto [resGetFirstArg, path, unused] = NVal(env, funcArg[NARG_POS::FIRST]).ToUTF8String(); - if (!resGetFirstArg) { + bool succ = false; + unique_ptr path; + tie(succ, path, ignore) = NVal(env, funcArg[NARG_POS::FIRST]).ToUTF8String(); + if (!succ) { UniError(EINVAL).ThrowErr(env, "Invalid path"); return nullptr; } - auto [resGetSecondArg, mode] = NVal(env, funcArg[NARG_POS::SECOND]).ToInt32(); - if (!resGetSecondArg) { + int mode; + tie(succ, mode) = NVal(env, funcArg[NARG_POS::SECOND]).ToInt32(); + if (!succ) { UniError(EINVAL).ThrowErr(env, "Invalid mode"); return nullptr; } @@ -52,31 +53,36 @@ napi_value Chmod::Sync(napi_env env, napi_callback_info info) if (chmod(path.get(), mode) == -1) { UniError(errno).ThrowErr(env); return nullptr; - } - + } return NVal::CreateUndefined(env).val_; } napi_value Chmod::Async(napi_env env, napi_callback_info info) { NFuncArg funcArg(env, info); + if (!funcArg.InitArgs(NARG_CNT::TWO, NARG_CNT::THREE)) { UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); return nullptr; } - auto [resGetFirstArg, tmp, unused] = NVal(env, funcArg[NARG_POS::FIRST]).ToUTF8String(); - if (!resGetFirstArg) { + string path; + unique_ptr tmp; + bool succ = false; + tie(succ, tmp, ignore) = NVal(env, funcArg[NARG_POS::FIRST]).ToUTF8String(); + if (!succ) { UniError(EINVAL).ThrowErr(env, "Invalid path"); return nullptr; } - auto [resGetSecondArg, mode] = NVal(env, funcArg[NARG_POS::SECOND]).ToInt32(); - if (!resGetSecondArg) { + path = tmp.get(); + int mode; + size_t argc = funcArg.GetArgc(); + tie(succ, mode) = NVal(env, funcArg[NARG_POS::SECOND]).ToInt32(); + if (!succ) { UniError(EINVAL).ThrowErr(env, "Invalid mode"); } - string path = tmp.get(); auto cbExec = [path, mode](napi_env env) -> UniError { if (chmod(path.c_str(), mode) == -1) { return UniError(errno); @@ -84,23 +90,22 @@ napi_value Chmod::Async(napi_env env, napi_callback_info info) return UniError(ERRNO_NOERR); } }; - auto cbComplete = [](napi_env env, UniError err) -> NVal { if (err) { return { env, err.GetNapiErr(env) }; } return { NVal::CreateUndefined(env) }; }; - - size_t argc = funcArg.GetArgc(); NVal thisVar(env, funcArg.GetThisVar()); - const string procedureName = "FileIOChmod"; + + string procedureName = "FileIOChmod"; if (argc == NARG_CNT::TWO) { return NAsyncWorkPromise(env, thisVar).Schedule(procedureName, cbExec, cbComplete).val_; } else { NVal cb(env, funcArg[NARG_POS::THIRD]); return NAsyncWorkCallback(env, thisVar, cb).Schedule(procedureName, cbExec, cbComplete).val_; } + return nullptr; } } // namespace ModuleFileIO } // namespace DistributedFS diff --git a/interfaces/kits/js/src/mod_fileio/properties/chmod.h b/interfaces/kits/js/src/mod_fileio/properties/chmod.h index 825289198b788ae310362e2850ff1e508e4dfe4f..7dec11e2421273d64b7562c9c442b3a0c6942bd5 100644 --- a/interfaces/kits/js/src/mod_fileio/properties/chmod.h +++ b/interfaces/kits/js/src/mod_fileio/properties/chmod.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2022 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 diff --git a/interfaces/kits/js/src/mod_fileio/properties/chown.cpp b/interfaces/kits/js/src/mod_fileio/properties/chown.cpp index f6b4fff5afffb2e2d1f246cb80a44d374af01fe4..843e5914a27463acaa066b3e89cb624046166b0e 100644 --- a/interfaces/kits/js/src/mod_fileio/properties/chown.cpp +++ b/interfaces/kits/js/src/mod_fileio/properties/chown.cpp @@ -22,7 +22,6 @@ #include "../../common/napi/n_async/n_async_work_callback.h" #include "../../common/napi/n_async/n_async_work_promise.h" #include "../../common/napi/n_func_arg.h" - namespace OHOS { namespace DistributedFS { namespace ModuleFileIO { @@ -30,37 +29,45 @@ using namespace std; static tuple GetChownArg(napi_env env, const NFuncArg &funcArg) { - auto [resGetFirstArg, path, unused] = NVal(env, funcArg[NARG_POS::FIRST]).ToUTF8String(); - if (!resGetFirstArg) { + bool succ = false; + unique_ptr path; + tie(succ, path, ignore) = NVal(env, funcArg[NARG_POS::FIRST]).ToUTF8String(); + if (!succ) { UniError(EINVAL).ThrowErr(env, "Invalid path"); return { false, "", -1, -1 }; } - auto [resGetSecondArg, owner] = NVal(env, funcArg[NARG_POS::SECOND]).ToInt32(); - if (!resGetSecondArg) { + int owner; + tie(succ, owner) = NVal(env, funcArg[NARG_POS::SECOND]).ToInt32(); + if (!succ) { UniError(EINVAL).ThrowErr(env, "Invalid owner"); return { false, "", -1, -1 }; } - auto [resGetThirdArg, group] = NVal(env, funcArg[NARG_POS::THIRD]).ToInt32(); - if (!resGetThirdArg) { + int group; + tie(succ, group) = NVal(env, funcArg[NARG_POS::THIRD]).ToInt32(); + if (!succ) { UniError(EINVAL).ThrowErr(env, "Invalid group"); return { false, "", -1, -1 }; } - return { succ, path.get(), owner, group }; } napi_value Chown::Sync(napi_env env, napi_callback_info info) { NFuncArg funcArg(env, info); + if (!funcArg.InitArgs(NARG_CNT::THREE)) { UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); return nullptr; } - auto [resGetChownArg, path, owner, group] = GetChownArg(env, funcArg); - if (!resGetChownArg) { + bool succ = false; + int owner; + int group; + string path; + tie(succ, path, owner, group) = GetChownArg(env, funcArg); + if (!succ) { return nullptr; } @@ -80,8 +87,12 @@ napi_value Chown::Async(napi_env env, napi_callback_info info) return nullptr; } - auto [resGetChownArg, path, owner, group] = GetChownArg(env, funcArg); - if (!resGetChownArg) { + bool succ = false; + int owner; + int group; + string path; + tie(succ, path, owner, group) = GetChownArg(env, funcArg); + if (!succ) { return nullptr; } @@ -100,7 +111,7 @@ napi_value Chown::Async(napi_env env, napi_callback_info info) return { NVal::CreateUndefined(env) }; }; - const string procedureName = "FileIOChown"; + string procedureName = "FileIOChown"; NVal thisVar(env, funcArg.GetThisVar()); if (funcArg.GetArgc() == NARG_CNT::THREE) { return NAsyncWorkPromise(env, thisVar).Schedule(procedureName, cbExec, cbCompl).val_; diff --git a/interfaces/kits/js/src/mod_fileio/properties/chown.h b/interfaces/kits/js/src/mod_fileio/properties/chown.h index 5ac00ec2fa502fa6f1bb70227a6e28c8f12dcf0b..c6f9fbbdf6ddb50ee3c26cf6cfe352e7b7002198 100644 --- a/interfaces/kits/js/src/mod_fileio/properties/chown.h +++ b/interfaces/kits/js/src/mod_fileio/properties/chown.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2022 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 diff --git a/interfaces/kits/js/src/mod_fileio/properties/close.cpp b/interfaces/kits/js/src/mod_fileio/properties/close.cpp index 44a7cf3915d5d57ce81d3580f2c25d8375d684b5..8bde27cf5fb9df7872b5e6c31932f9c7bc33e35e 100644 --- a/interfaces/kits/js/src/mod_fileio/properties/close.cpp +++ b/interfaces/kits/js/src/mod_fileio/properties/close.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2022 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 @@ -35,8 +35,10 @@ napi_value Close::Sync(napi_env env, napi_callback_info info) return nullptr; } - auto [resGetFirstArg, fd] = NVal(env, funcArg[NARG_POS::FIRST]).ToInt32(); - if (!resGetFirstArg) { + bool succ = false; + int fd; + tie(succ, fd) = NVal(env, funcArg[NARG_POS::FIRST]).ToInt32(); + if (!succ) { UniError(EINVAL).ThrowErr(env, "Invalid fd"); return nullptr; } @@ -56,9 +58,10 @@ napi_value Close::Async(napi_env env, napi_callback_info info) UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); return nullptr; } - - auto [resGetFirstArg, fd] = NVal(env, funcArg[NARG_POS::FIRST]).ToInt32(); - if (!resGetFirstArg) { + bool succ = false; + int fd; + tie(succ, fd) = NVal(env, funcArg[NARG_POS::FIRST]).ToInt32(); + if (!succ) { UniError(EINVAL).ThrowErr(env, "Invalid fd"); return nullptr; } @@ -71,7 +74,6 @@ napi_value Close::Async(napi_env env, napi_callback_info info) return UniError(ERRNO_NOERR); } }; - auto cbComplete = [](napi_env env, UniError err) -> NVal { if (err) { return { env, err.GetNapiErr(env) }; @@ -79,8 +81,7 @@ napi_value Close::Async(napi_env env, napi_callback_info info) return NVal::CreateUndefined(env); } }; - - const string procedureName = "FileIOClose"; + string procedureName = "FileIOClose"; size_t argc = funcArg.GetArgc(); NVal thisVar(env, funcArg.GetThisVar()); if (argc == NARG_CNT::ONE) { diff --git a/interfaces/kits/js/src/mod_fileio/properties/close.h b/interfaces/kits/js/src/mod_fileio/properties/close.h index 6d6a3964682a2e10c6f29306fea72a396b9544a0..47a58c86a464f215e257d6d15477093714948bb1 100644 --- a/interfaces/kits/js/src/mod_fileio/properties/close.h +++ b/interfaces/kits/js/src/mod_fileio/properties/close.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2022 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 diff --git a/interfaces/kits/js/src/mod_fileio/properties/copy_file.cpp b/interfaces/kits/js/src/mod_fileio/properties/copy_file.cpp index 30f2cc90dd68a63bc5fa11164121d3fcf278f17d..d29069c03513a9209edb7aea9392711aa6ade1c8 100644 --- a/interfaces/kits/js/src/mod_fileio/properties/copy_file.cpp +++ b/interfaces/kits/js/src/mod_fileio/properties/copy_file.cpp @@ -33,10 +33,6 @@ namespace DistributedFS { namespace ModuleFileIO { using namespace std; -namespace { -constexpr int COPY_BLOCK_SIZE = 4096; -} - struct FileInfo { bool isPath = false; unique_ptr path; @@ -50,11 +46,9 @@ static UniError CopyFileCore(FileInfo &srcFile, FileInfo &destFile) srcFile.fdg.SetFD(open(srcFile.path.get(), O_RDONLY), true); res = errno; } - if (!srcFile.fdg) { return UniError(res); } - struct stat statbf; if (fstat(srcFile.fdg.GetFD(), &statbf) == -1) { return UniError(errno); @@ -64,14 +58,14 @@ static UniError CopyFileCore(FileInfo &srcFile, FileInfo &destFile) destFile.fdg.SetFD(open(destFile.path.get(), O_WRONLY | O_CREAT, statbf.st_mode), true); res = errno; } - if (!destFile.fdg) { return UniError(res); } - auto copyBuf = make_unique(COPY_BLOCK_SIZE); + int block = 4096; + auto copyBuf = make_unique(block); do { - ssize_t readSize = read(srcFile.fdg.GetFD(), copyBuf.get(), COPY_BLOCK_SIZE); + ssize_t readSize = read(srcFile.fdg.GetFD(), copyBuf.get(), block); if (readSize == -1) { return UniError(errno); } else if (readSize == 0) { @@ -81,7 +75,7 @@ static UniError CopyFileCore(FileInfo &srcFile, FileInfo &destFile) if (writeSize != readSize) { return UniError(errno); } - if (readSize != COPY_BLOCK_SIZE) { + if (readSize != block) { break; } } while (true); @@ -101,14 +95,12 @@ static tuple ParseJsModeAndProm(napi_env env, const NFuncArg &f } else if (funcArg.GetArgc() == NARG_CNT::FOUR) { hasMode = true; } - if (hasMode) { tie(succ, mode) = NVal(env, funcArg[NARG_POS::THIRD]).ToInt32(); if (!succ) { return {false, mode, promise}; } } - return {true, mode, promise}; } @@ -142,7 +134,7 @@ napi_value CopyFile::Sync(napi_env env, napi_callback_info info) return nullptr; } - auto [succMode, mode, unused] = ParseJsModeAndProm(env, funcArg); + auto [succMode, mode, ignore] = ParseJsModeAndProm(env, funcArg); if (!succMode) { UniError(EINVAL).ThrowErr(env, "Invalid mode"); return nullptr; @@ -150,6 +142,11 @@ napi_value CopyFile::Sync(napi_env env, napi_callback_info info) auto err = CopyFileCore(src, dest); if (err) { + if (err.GetErrno(ERR_CODE_SYSTEM_POSIX) == ENAMETOOLONG) { + UniError(EINVAL).ThrowErr(env, "Filename too long"); + return nullptr; + } + err.ThrowErr(env); return nullptr; } @@ -192,12 +189,15 @@ napi_value CopyFile::Async(napi_env env, napi_callback_info info) auto cbCompl = [](napi_env env, UniError err) -> NVal { if (err) { + if (err.GetErrno(ERR_CODE_SYSTEM_POSIX) == ENAMETOOLONG) { + return {env, err.GetNapiErr(env, "Filename too long")}; + } return {env, err.GetNapiErr(env)}; } return {NVal::CreateUndefined(env)}; }; - const string procedureName = "FileIOCopyFile"; + string procedureName = "FileIOCopyFile"; NVal thisVar(env, funcArg.GetThisVar()); if (funcArg.GetArgc() == NARG_CNT::TWO || promise) { return NAsyncWorkPromise(env, thisVar).Schedule(procedureName, cbExec, cbCompl).val_; diff --git a/interfaces/kits/js/src/mod_fileio/properties/copy_file.h b/interfaces/kits/js/src/mod_fileio/properties/copy_file.h index bef01ef1e7a6d0ee54ad37903525210be32e9d98..cdb8df62c030f19410604f6e439d6241259dd9b3 100644 --- a/interfaces/kits/js/src/mod_fileio/properties/copy_file.h +++ b/interfaces/kits/js/src/mod_fileio/properties/copy_file.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2022 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 diff --git a/interfaces/kits/js/src/mod_fileio/properties/create_randomaccessfile.cpp b/interfaces/kits/js/src/mod_fileio/properties/create_randomaccessfile.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8fa4fbaa701aac4a32025e37c8c3b72dd89abcbc --- /dev/null +++ b/interfaces/kits/js/src/mod_fileio/properties/create_randomaccessfile.cpp @@ -0,0 +1,213 @@ +/* + * Copyright (c) 2022 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. + */ +#include "create_randomaccessfile.h" + +#include +#include +#include +#include +#include +#include + +#include "../../common/log.h" +#include "../../common/napi/n_async/n_async_work_callback.h" +#include "../../common/napi/n_async/n_async_work_promise.h" +#include "../../common/napi/n_class.h" +#include "../../common/napi/n_func_arg.h" +#include "../../common/uni_error.h" +#include "../common_func.h" + +#include "../class_randomaccessfile/randomaccessfile_entity.h" +#include "../class_randomaccessfile/randomaccessfile_n_exporter.h" + +namespace OHOS { +namespace DistributedFS { +namespace ModuleFileIO { +using namespace std; + +struct FileInfo { + bool isPath = false; + unique_ptr path; + FDGuard fdg; +}; + +static bool CheckFilePath(napi_env env, string path) +{ + if (access(path.c_str(), 0) == 0) { + struct stat fileStat; + int ret = stat(path.c_str(), &fileStat); + if (ret != 0) { + UniError(errno).ThrowErr(env, "Cannot stat filepath"); + return false; + } + if ((fileStat.st_mode & S_IFMT) != S_IFREG) { + UniError(EINVAL).ThrowErr(env, "Invalid filepath"); + return false; + } + } + return true; +} + +static tuple ParseJsFileAndFP(napi_env env, napi_value pathOrFdFromJsArg, napi_value FPFromJs) +{ + auto [succ, fp] = NVal(env, FPFromJs).ToInt32(); + if (succ) { + auto [isPath, path, ignore] = NVal(env, pathOrFdFromJsArg).ToUTF8String(); + if (isPath) { + if (CheckFilePath(env, string(path.get()))) { + return { true, FileInfo { true, move(path), {} }, fp }; + } + return { false, FileInfo { false, {}, {} }, -1 }; + } + auto [isFd, fd] = NVal(env, pathOrFdFromJsArg).ToInt32(); + if (isFd) { + if (fd < 0) { + UniError(EINVAL).ThrowErr(env, "Invalid fd"); + return { false, FileInfo { false, {}, {} }, -1 }; + } + return { true, FileInfo { false, {}, { fd, false } }, fp }; + } + UniError(EINVAL).ThrowErr(env, "The first argument requires filepath/fd"); + } + UniError(EINVAL).ThrowErr(env, "Invalid fp"); + return { false, FileInfo { false, {}, {} }, -1 }; +}; + +static tuple GetJsFlags(napi_env env, const NFuncArg &funcArg, FileInfo &fileInfo) +{ + int flags = O_RDONLY; + bool succ = false; + if (fileInfo.isPath) { + if (funcArg.GetArgc() >= NARG_CNT::THREE && !NVal(env, funcArg[NARG_POS::THIRD]).TypeIs(napi_function)) { + tie(succ, flags) = NVal(env, funcArg[NARG_POS::THIRD]).ToInt32(); + if (!succ) { + UniError(EINVAL).ThrowErr(env, "Invalid flags"); + return { false, flags }; + } + (void)CommonFunc::ConvertJsFlags(flags); + } + } + return { true, flags }; +} + +static NVal InstantiateRandomAccessFile(napi_env env, int fd, size_t fp) +{ + napi_value objRAF = NClass::InstantiateClass(env, RandomAccessFileNExporter::className_, {}); + if (!objRAF) { + UniError(EIO).ThrowErr(env, "Cannot instantiate randomaccessfile"); + return NVal(); + } + + auto rafEntity = NClass::GetEntityOf(env, objRAF); + if (!rafEntity) { + UniError(EIO).ThrowErr(env, "Cannot instantiate randomaccessfile because of void entity"); + return NVal(); + } + auto fdg = make_unique(fd); + rafEntity->fd_.swap(fdg); + rafEntity->fpointer = fp; + return { env, objRAF }; +} + +napi_value CreateRandomAccessFile::Sync(napi_env env, napi_callback_info info) +{ + NFuncArg funcArg(env, info); + if (!funcArg.InitArgs(NARG_CNT::TWO, NARG_CNT::THREE)) { + UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); + return nullptr; + } + auto [succ, fileInfo, fp] = ParseJsFileAndFP(env, funcArg[NARG_POS::FIRST], funcArg[NARG_POS::SECOND]); + if (!succ) { + return nullptr; + } + + if (fileInfo.isPath) { + auto [succFlags, flags] = GetJsFlags(env, funcArg, fileInfo); + if (!succFlags) { + return nullptr; + } + uv_loop_s *loop = nullptr; + napi_get_uv_event_loop(env, &loop); + uv_fs_t open_req; + int ret = uv_fs_open(loop, &open_req, fileInfo.path.get(), flags, S_IRUSR | + S_IWUSR | S_IRGRP | S_IWGRP, NULL); + if (ret < 0) { + UniError(errno).ThrowErr(env); + return nullptr; + } + fileInfo.fdg.SetFD(open_req.result, false); + uv_fs_req_cleanup(&open_req); + } + return InstantiateRandomAccessFile(env, fileInfo.fdg.GetFD(), fp).val_; +} + +struct AsyncCreateRandomAccessFileArg { + int fd; + size_t fp; +}; + +napi_value CreateRandomAccessFile::Async(napi_env env, napi_callback_info info) +{ + NFuncArg funcArg(env, info); + if (!funcArg.InitArgs(NARG_CNT::TWO, NARG_CNT::FOUR)) { + UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); + return nullptr; + } + auto [succ, fileInfo, fp] = ParseJsFileAndFP(env, funcArg[NARG_POS::FIRST], funcArg[NARG_POS::SECOND]); + if (!succ) { + return nullptr; + } + auto [succFlags, flags] = GetJsFlags(env, funcArg, fileInfo); + if (!succFlags) { + return nullptr; + } + auto arg = make_shared(); + auto cbExec = [arg, fileInfo = make_shared(move(fileInfo)), fp = fp, flags = + flags](napi_env env) -> UniError { + if (fileInfo->isPath) { + uv_loop_s *loop = nullptr; + napi_get_uv_event_loop(env, &loop); + uv_fs_t open_req; + int ret = uv_fs_open(loop, &open_req, fileInfo->path.get(), flags, S_IRUSR | + S_IWUSR | S_IRGRP | S_IWGRP, NULL); + if (ret < 0) { + return UniError(errno); + } + fileInfo->fdg.SetFD(open_req.result, false); + uv_fs_req_cleanup(&open_req); + } + arg->fd = fileInfo->fdg.GetFD(); + arg->fp = fp; + return UniError(ERRNO_NOERR); + }; + auto cbCompl = [arg](napi_env env, UniError err) -> NVal { + if (err) { + return { env, err.GetNapiErr(env) }; + } + return InstantiateRandomAccessFile(env, arg->fd, arg->fp); + }; + NVal thisVar(env, funcArg.GetThisVar()); + if (funcArg.GetArgc() == NARG_CNT::TWO || (funcArg.GetArgc() == NARG_CNT::THREE && + NVal(env, funcArg[NARG_POS::THIRD]).TypeIs(napi_number))) { + return NAsyncWorkPromise(env, thisVar).Schedule(createRAFProcedureName, cbExec, cbCompl).val_; + } else { + int cbIdx = ((funcArg.GetArgc() == NARG_CNT::FOUR) ? NARG_POS::FOURTH : NARG_POS::THIRD); + NVal cb(env, funcArg[cbIdx]); + return NAsyncWorkCallback(env, thisVar, cb).Schedule(createRAFProcedureName, cbExec, cbCompl).val_; + } +} +} // namespace ModuleFileIO +} // namespace DistributedFS +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fileio/properties/create_randomaccessfile.h b/interfaces/kits/js/src/mod_fileio/properties/create_randomaccessfile.h new file mode 100644 index 0000000000000000000000000000000000000000..f4a9b36bad948ea71a3070f7da973396fa6ff6b7 --- /dev/null +++ b/interfaces/kits/js/src/mod_fileio/properties/create_randomaccessfile.h @@ -0,0 +1,33 @@ +/* + * Copyright (c) 2022 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. + */ + +#ifndef INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_CREATE_RANDOMACCESSFILE_H +#define INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_CREATE_RANDOMACCESSFILE_H + +#include "../../common/napi/uni_header.h" + +namespace OHOS { +namespace DistributedFS { +namespace ModuleFileIO { +class CreateRandomAccessFile final { +public: + static napi_value Async(napi_env env, napi_callback_info info); + static napi_value Sync(napi_env env, napi_callback_info info); +}; +const std::string createRAFProcedureName = "FileIOCreateRandomAccessFile"; +} // namespace ModuleFileIO +} // namespace DistributedFS +} // namespace OHOS +#endif \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fileio/properties/create_stream.cpp b/interfaces/kits/js/src/mod_fileio/properties/create_stream.cpp index df19686d80e9e159948c5efdfc13863a1741cd53..c46979be9cd37153f4bdad4fc77a6cf15d8e8c46 100644 --- a/interfaces/kits/js/src/mod_fileio/properties/create_stream.cpp +++ b/interfaces/kits/js/src/mod_fileio/properties/create_stream.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2022 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 @@ -12,7 +12,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - #include "create_stream.h" #include @@ -53,14 +52,17 @@ static NVal InstantiateStream(napi_env env, unique_ptr static tuple GetCreateStreamArgs(napi_env env, const NFuncArg &funcArg) { - auto [resGetFirstArg, path, unused] = NVal(env, funcArg[NARG_POS::FIRST]).ToUTF8String(); - if (!resGetFirstArg) { + bool succ = false; + unique_ptr path; + tie(succ, path, ignore) = NVal(env, funcArg[NARG_POS::FIRST]).ToUTF8String(); + if (!succ) { UniError(EINVAL).ThrowErr(env, "Invalid path"); return { false, "", "" }; } - tie(resGetSecondArg, mode, useless) = NVal(env, funcArg[NARG_POS::SECOND]).ToUTF8String(); - if (!resGetSecondArg) { + unique_ptr mode; + tie(succ, mode, ignore) = NVal(env, funcArg[NARG_POS::SECOND]).ToUTF8String(); + if (!succ) { UniError(EINVAL).ThrowErr(env, "Invalid mode"); return { false, "", "" }; } @@ -76,8 +78,11 @@ napi_value CreateStream::Sync(napi_env env, napi_callback_info info) return nullptr; } - auto [resGetCreateStreamArgs, argPath, argMode) = GetCreateStreamArgs(env, funcArg); - if (!resGetCreateStreamArgs) { + bool succ = false; + string argPath; + string argMode; + tie(succ, argPath, argMode) = GetCreateStreamArgs(env, funcArg); + if (!succ) { return nullptr; } @@ -86,7 +91,6 @@ napi_value CreateStream::Sync(napi_env env, napi_callback_info info) UniError(errno).ThrowErr(env); return nullptr; } - return InstantiateStream(env, move(fp)).val_; } @@ -102,8 +106,11 @@ napi_value CreateStream::Async(napi_env env, napi_callback_info info) return nullptr; } - auto [resGetCreateStreamArgs, argPath, argMode] = GetCreateStreamArgs(env, funcArg); - if (!resGetCreateStreamArgs) { + bool succ = false; + string argPath; + string argMode; + tie(succ, argPath, argMode) = GetCreateStreamArgs(env, funcArg); + if (!succ) { return nullptr; } @@ -116,7 +123,6 @@ napi_value CreateStream::Async(napi_env env, napi_callback_info info) return UniError(ERRNO_NOERR); } }; - auto cbCompl = [arg](napi_env env, UniError err) -> NVal { if (err) { return { env, err.GetNapiErr(env) }; @@ -124,7 +130,7 @@ napi_value CreateStream::Async(napi_env env, napi_callback_info info) return InstantiateStream(env, move(arg->fp)); }; - const string procedureName = "FileIOCreateStream"; + string procedureName = "FileIOCreateStream"; NVal thisVar(env, funcArg.GetThisVar()); if (funcArg.GetArgc() == NARG_CNT::TWO) { return NAsyncWorkPromise(env, thisVar).Schedule(procedureName, cbExec, cbCompl).val_; diff --git a/interfaces/kits/js/src/mod_fileio/properties/create_stream.h b/interfaces/kits/js/src/mod_fileio/properties/create_stream.h index 7c58fa744a9dbb7a0e85d3c7e7258b4695c8c13c..50927a19c2aa5610bc3352e66938ee21057dc559 100644 --- a/interfaces/kits/js/src/mod_fileio/properties/create_stream.h +++ b/interfaces/kits/js/src/mod_fileio/properties/create_stream.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2022 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 diff --git a/interfaces/kits/js/src/mod_fileio/properties/fchmod.cpp b/interfaces/kits/js/src/mod_fileio/properties/fchmod.cpp index fe2dcbcfba5083dfc743b667c013264b544316a1..602fadeabce31a49f88ac29b11d46ae125b1b36a 100644 --- a/interfaces/kits/js/src/mod_fileio/properties/fchmod.cpp +++ b/interfaces/kits/js/src/mod_fileio/properties/fchmod.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2022 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 @@ -31,19 +31,23 @@ using namespace std; napi_value Fchmod::Sync(napi_env env, napi_callback_info info) { NFuncArg funcArg(env, info); + if (!funcArg.InitArgs(NARG_CNT::TWO)) { UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); return nullptr; } - auto [resGetFirstArg, fd] = NVal(env, funcArg[NARG_POS::FIRST]).ToInt32(); - if (!resGetFirstArg) { + bool succ = false; + int fd; + tie(succ, fd) = NVal(env, funcArg[NARG_POS::FIRST]).ToInt32(); + if (!succ) { UniError(EINVAL).ThrowErr(env, "Invalid fd"); return nullptr; } - auto [resGetSecondArg, mode] = NVal(env, funcArg[NARG_POS::SECOND]).ToInt32(); - if (!resGetSecondArg) { + int mode; + tie(succ, mode) = NVal(env, funcArg[NARG_POS::SECOND]).ToInt32(); + if (!succ) { UniError(EINVAL).ThrowErr(env, "Invalid mode"); return nullptr; } @@ -66,14 +70,18 @@ napi_value Fchmod::Async(napi_env env, napi_callback_info info) return nullptr; } - auto [resGetFirstArg, fd] = NVal(env, funcArg[NARG_POS::FIRST]).ToInt32(); - if (!resGetFirstArg) { + size_t argc = funcArg.GetArgc(); + bool succ = false; + int fd; + tie(succ, fd) = NVal(env, funcArg[NARG_POS::FIRST]).ToInt32(); + if (!succ) { UniError(EINVAL).ThrowErr(env, "Invalid fd"); return nullptr; } - auto [resGetSecondArg, mode] = NVal(env, funcArg[NARG_POS::SECOND]).ToInt32(); - if (!resGetSecondArg) { + int mode; + tie(succ, mode) = NVal(env, funcArg[NARG_POS::SECOND]).ToInt32(); + if (!succ) { UniError(EINVAL).ThrowErr(env, "Invalid owner"); } @@ -93,9 +101,8 @@ napi_value Fchmod::Async(napi_env env, napi_callback_info info) return { NVal::CreateUndefined(env) }; }; - const string procedureName = "FileIOFchmod"; + string procedureName = "FileIOFchmod"; NVal thisVar(env, funcArg.GetThisVar()); - size_t argc = funcArg.GetArgc(); if (argc == NARG_CNT::TWO) { return NAsyncWorkPromise(env, thisVar).Schedule(procedureName, cbExec, cbComplCallback).val_; } else { diff --git a/interfaces/kits/js/src/mod_fileio/properties/fchmod.h b/interfaces/kits/js/src/mod_fileio/properties/fchmod.h index eb7711822870984742d1190bedfb61200768b2d6..09ad627a93bf1e4294224fe82de67046380584ec 100644 --- a/interfaces/kits/js/src/mod_fileio/properties/fchmod.h +++ b/interfaces/kits/js/src/mod_fileio/properties/fchmod.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2022 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 diff --git a/interfaces/kits/js/src/mod_fileio/properties/fchown.cpp b/interfaces/kits/js/src/mod_fileio/properties/fchown.cpp index e2576eea74ea2bf043adf718cac6688db2325f99..9bee492c3c7cee56dd93782245521c3b298798ed 100644 --- a/interfaces/kits/js/src/mod_fileio/properties/fchown.cpp +++ b/interfaces/kits/js/src/mod_fileio/properties/fchown.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2022 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 @@ -35,19 +35,23 @@ napi_value Fchown::Sync(napi_env env, napi_callback_info info) return nullptr; } - auto [resGetFirstArg, fd] = NVal(env, funcArg[NARG_POS::FIRST]).ToInt32(); - if (!resGetFirstArg) { + bool succ = false; + int fd; + tie(succ, fd) = NVal(env, funcArg[NARG_POS::FIRST]).ToInt32(); + if (!succ) { UniError(EINVAL).ThrowErr(env, "Invalid fd"); return nullptr; } - auto [resGetSecondArg, owner] = NVal(env, funcArg[NARG_POS::SECOND]).ToInt32(); - if (!resGetSecondArg) { + int owner; + tie(succ, owner) = NVal(env, funcArg[NARG_POS::SECOND]).ToInt32(); + if (!succ) { UniError(EINVAL).ThrowErr(env, "Invalid owner"); } - auto [resGetThirdArg, group] = NVal(env, funcArg[NARG_POS::THIRD]).ToInt32(); - if (!resGetThirdArg) { + int group; + tie(succ, group) = NVal(env, funcArg[NARG_POS::THIRD]).ToInt32(); + if (!succ) { UniError(EINVAL).ThrowErr(env, "Invalid group"); } @@ -68,19 +72,24 @@ napi_value Fchown::Async(napi_env env, napi_callback_info info) return nullptr; } - auto [resGetFirstArg, fd] = NVal(env, funcArg[NARG_POS::FIRST]).ToInt32(); - if (!resGetFirstArg) { + size_t argc = funcArg.GetArgc(); + bool succ = false; + int fd; + tie(succ, fd) = NVal(env, funcArg[NARG_POS::FIRST]).ToInt32(); + if (!succ) { UniError(EINVAL).ThrowErr(env, "Invalid fd"); return nullptr; } - auto [resGetSecondArg, owner] = NVal(env, funcArg[NARG_POS::SECOND]).ToInt32(); - if (!resGetSecondArg) { + int owner; + tie(succ, owner) = NVal(env, funcArg[NARG_POS::SECOND]).ToInt32(); + if (!succ) { UniError(EINVAL).ThrowErr(env, "Invalid owner"); } - auto (resGetThirdArg, group] = NVal(env, funcArg[NARG_POS::THIRD]).ToInt32(); - if (!resGetThirdArg) { + int group; + tie(succ, group) = NVal(env, funcArg[NARG_POS::THIRD]).ToInt32(); + if (!succ) { UniError(EINVAL).ThrowErr(env, "Invalid group"); } @@ -100,9 +109,9 @@ napi_value Fchown::Async(napi_env env, napi_callback_info info) return { NVal::CreateUndefined(env) }; }; - const string procedureName = "FileIOFchown"; + string procedureName = "FileIOFchown"; NVal thisVar(env, funcArg.GetThisVar()); - if (funcArg.GetArgc() == NARG_CNT::THREE) { + if (argc == NARG_CNT::THREE) { return NAsyncWorkPromise(env, thisVar).Schedule(procedureName, cbExec, cbComplCallback).val_; } else { NVal cb(env, funcArg[NARG_POS::FOURTH]); diff --git a/interfaces/kits/js/src/mod_fileio/properties/fchown.h b/interfaces/kits/js/src/mod_fileio/properties/fchown.h index 7439f2e542f346eeb6f8c9affaca8f3a8705e752..6e623a018ecd3c1e235feb23e4617f17f42770d9 100644 --- a/interfaces/kits/js/src/mod_fileio/properties/fchown.h +++ b/interfaces/kits/js/src/mod_fileio/properties/fchown.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2022 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 diff --git a/interfaces/kits/js/src/mod_fileio/properties/fdatasync.cpp b/interfaces/kits/js/src/mod_fileio/properties/fdatasync.cpp index 8c7c739120e6d36351913a494756a59b99c0b359..e9b9389871e3f87d2480e5bca4ecdb06a9ad43d6 100644 --- a/interfaces/kits/js/src/mod_fileio/properties/fdatasync.cpp +++ b/interfaces/kits/js/src/mod_fileio/properties/fdatasync.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2022 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 @@ -31,13 +31,16 @@ using namespace std; napi_value Fdatasync::Sync(napi_env env, napi_callback_info info) { NFuncArg funcArg(env, info); + if (!funcArg.InitArgs(NARG_CNT::ONE)) { UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); return nullptr; } - auto [resGetFirstArg, fd] = NVal(env, funcArg[NARG_POS::FIRST]).ToInt32(); - if (!resGetFirstArg) { + bool succ = false; + int fd; + tie(succ, fd) = NVal(env, funcArg[NARG_POS::FIRST]).ToInt32(); + if (!succ) { UniError(EINVAL).ThrowErr(env, "Invalid fd"); return nullptr; } @@ -60,8 +63,11 @@ napi_value Fdatasync::Async(napi_env env, napi_callback_info info) return nullptr; } - auto [resGetFirstArg, fd] = NVal(env, funcArg[NARG_POS::FIRST]).ToInt32(); - if (!resGetFirstArg) { + size_t argc = funcArg.GetArgc(); + bool succ = false; + int fd; + tie(succ, fd) = NVal(env, funcArg[NARG_POS::FIRST]).ToInt32(); + if (!succ) { UniError(EINVAL).ThrowErr(env, "Invalid fd"); return nullptr; } @@ -82,9 +88,9 @@ napi_value Fdatasync::Async(napi_env env, napi_callback_info info) return { NVal::CreateUndefined(env) }; }; - const string procedureName = "FileIOFdatasync"; + string procedureName = "FileIOFdatasync"; NVal thisVar(env, funcArg.GetThisVar()); - if (funcArg.GetArgc() == NARG_CNT::ONE) { + if (argc == NARG_CNT::ONE) { return NAsyncWorkPromise(env, thisVar).Schedule(procedureName, cbExec, cbComplCallback).val_; } else { NVal cb(env, funcArg[NARG_POS::SECOND]); diff --git a/interfaces/kits/js/src/mod_fileio/properties/fdatasync.h b/interfaces/kits/js/src/mod_fileio/properties/fdatasync.h index f10fcbde3a1faa694680ef8ce97aaba17824e65f..70a79b85ee2d552a940d62902a9e485b592275f1 100644 --- a/interfaces/kits/js/src/mod_fileio/properties/fdatasync.h +++ b/interfaces/kits/js/src/mod_fileio/properties/fdatasync.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2022 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 diff --git a/interfaces/kits/js/src/mod_fileio/properties/fdopen_stream.cpp b/interfaces/kits/js/src/mod_fileio/properties/fdopen_stream.cpp index dddce67daf690b23481358a86bf908e899a06901..a2f23b09471168f638777f6a8eca4c98f1ebe9b6 100644 --- a/interfaces/kits/js/src/mod_fileio/properties/fdopen_stream.cpp +++ b/interfaces/kits/js/src/mod_fileio/properties/fdopen_stream.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2022 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 @@ -51,31 +51,38 @@ static NVal InstantiateStream(napi_env env, unique_ptr static tuple GetFdopenStreamArgs(napi_env env, const NFuncArg &funcArg) { - auto [resGetFirstArg, fd] = NVal(env, funcArg[NARG_POS::FIRST]).ToInt32(); - if (!resGetFirstArg) { + bool succ = false; + int fd; + tie(succ, fd) = NVal(env, funcArg[NARG_POS::FIRST]).ToInt32(); + if (!succ) { UniError(EINVAL).ThrowErr(env, "Arg fd is required to be type integer"); return { false, -1, "" }; } - auto [resGetSecondArg, mode, unused] = NVal(env, funcArg[NARG_POS::SECOND]).ToUTF8String(); - if (!resGetSecondArg) { + unique_ptr mode; + tie(succ, mode, ignore) = NVal(env, funcArg[NARG_POS::SECOND]).ToUTF8String(); + if (!succ) { UniError(EINVAL).ThrowErr(env, "Arg mode is required to be type string"); return { false, -1, "" }; } - return { true, fd, mode.get() }; } napi_value FdopenStream::Sync(napi_env env, napi_callback_info info) { NFuncArg funcArg(env, info); + if (!funcArg.InitArgs(NARG_CNT::TWO)) { UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); return nullptr; } - auto [resGetFdopenStreamArgs, fd, mode] = GetFdopenStreamArgs(env, funcArg); - if (!resGetFdopenStreamArgs) { + bool succ = false; + int fd; + string mode; + + tie(succ, fd, mode) = GetFdopenStreamArgs(env, funcArg); + if (!succ) { return nullptr; } @@ -100,8 +107,11 @@ napi_value FdopenStream::Async(napi_env env, napi_callback_info info) return nullptr; } - auto [resGetFdopenStreamArgs, fd, mode] = GetFdopenStreamArgs(env, funcArg); - if (!resGetFdopenStreamArgs) { + bool success = false; + int fd; + string mode; + tie(success, fd, mode) = GetFdopenStreamArgs(env, funcArg); + if (!success) { return nullptr; } @@ -122,7 +132,7 @@ napi_value FdopenStream::Async(napi_env env, napi_callback_info info) return InstantiateStream(env, move(arg->fp)); }; - const string procedureName = "FileIOFdopenStream"; + string procedureName = "FileIOFdopenStream"; NVal thisVar(env, funcArg.GetThisVar()); if (funcArg.GetArgc() == NARG_CNT::TWO) { return NAsyncWorkPromise(env, thisVar).Schedule(procedureName, cbExec, cbCompl).val_; diff --git a/interfaces/kits/js/src/mod_fileio/properties/fdopen_stream.h b/interfaces/kits/js/src/mod_fileio/properties/fdopen_stream.h index 195369eceec8a73a7278380675ae64be6a358626..3969abcee5cdbb06885faef99b7d6492c00ffa53 100644 --- a/interfaces/kits/js/src/mod_fileio/properties/fdopen_stream.h +++ b/interfaces/kits/js/src/mod_fileio/properties/fdopen_stream.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2022 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 diff --git a/interfaces/kits/js/src/mod_fileio/properties/fstat.cpp b/interfaces/kits/js/src/mod_fileio/properties/fstat.cpp index 34e01a1b2602486e1d1f8afb14b5268a5ddb52c3..2c6a2bbf8370bc1df268d6cc07aa4a35698adab7 100644 --- a/interfaces/kits/js/src/mod_fileio/properties/fstat.cpp +++ b/interfaces/kits/js/src/mod_fileio/properties/fstat.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2022 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 @@ -40,8 +40,11 @@ napi_value Fstat::Sync(napi_env env, napi_callback_info info) return nullptr; } - auto [resGetFirstArg, fd] = NVal(env, funcArg[NARG_POS::FIRST]).ToInt32(); - if (!resGetFirstArg) { + bool succ = false; + + int fd; + tie(succ, fd) = NVal(env, funcArg[NARG_POS::FIRST]).ToInt32(); + if (!succ) { UniError(EINVAL).ThrowErr(env, "Invalid fd"); return nullptr; } @@ -63,8 +66,8 @@ napi_value Fstat::Sync(napi_env env, napi_callback_info info) UniError(EINVAL).ThrowErr(env, "Cannot get the entity of objStat"); return nullptr; } - statEntity->stat_ = buf; + return objStat; } @@ -80,8 +83,10 @@ napi_value Fstat::Async(napi_env env, napi_callback_info info) return nullptr; } - auto [resGetFirstArg, fd] = NVal(env, funcArg[NARG_POS::FIRST]).ToInt32(); - if (!resGetFirstArg) { + bool succ = false; + int fd; + tie(succ, fd) = NVal(env, funcArg[NARG_POS::FIRST]).ToInt32(); + if (!succ) { UniError(EINVAL).ThrowErr(env, "Invalid fd"); return nullptr; } @@ -94,7 +99,6 @@ napi_value Fstat::Async(napi_env env, napi_callback_info info) return UniError(ERRNO_NOERR); } }; - auto cbCompl = [arg](napi_env env, UniError err) -> NVal { if (err) { return { env, err.GetNapiErr(env) }; @@ -110,9 +114,8 @@ napi_value Fstat::Async(napi_env env, napi_callback_info info) statEntity->stat_ = arg->stat_; return { env, objStat }; }; - NVal thisVar(env, funcArg.GetThisVar()); - const string procedureName = "fileIOFstat"; + string procedureName = "fileIOFstat"; if (funcArg.GetArgc() == NARG_CNT::ONE) { return NAsyncWorkPromise(env, thisVar).Schedule(procedureName, cbExec, cbCompl).val_; } else { diff --git a/interfaces/kits/js/src/mod_fileio/properties/fstat.h b/interfaces/kits/js/src/mod_fileio/properties/fstat.h index 27395df81e9d5802c873d5c7be42b066fc254640..f52a6a3e71772d28b4662cb28ecee155e4d00105 100644 --- a/interfaces/kits/js/src/mod_fileio/properties/fstat.h +++ b/interfaces/kits/js/src/mod_fileio/properties/fstat.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2022 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 diff --git a/interfaces/kits/js/src/mod_fileio/properties/fsync.cpp b/interfaces/kits/js/src/mod_fileio/properties/fsync.cpp index aa25b2e6ce550e098ae88a38096755ec4da94b6e..c3f6276aea8cab058042ef76237096cea2253014 100644 --- a/interfaces/kits/js/src/mod_fileio/properties/fsync.cpp +++ b/interfaces/kits/js/src/mod_fileio/properties/fsync.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2022 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 @@ -22,7 +22,6 @@ #include "../../common/napi/n_async/n_async_work_callback.h" #include "../../common/napi/n_async/n_async_work_promise.h" #include "../../common/napi/n_func_arg.h" - namespace OHOS { namespace DistributedFS { namespace ModuleFileIO { @@ -31,13 +30,16 @@ using namespace std; napi_value Fsync::Sync(napi_env env, napi_callback_info info) { NFuncArg funcArg(env, info); + if (!funcArg.InitArgs(NARG_CNT::ONE)) { UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); return nullptr; } - auto [resGetFirstArg, fd] = NVal(env, funcArg[NARG_POS::FIRST]).ToInt32(); - if (!resGetFirstArg) { + bool succ = false; + int fd; + tie(succ, fd) = NVal(env, funcArg[NARG_POS::FIRST]).ToInt32(); + if (!succ) { UniError(EINVAL).ThrowErr(env, "Invalid fd"); return nullptr; } @@ -46,20 +48,22 @@ napi_value Fsync::Sync(napi_env env, napi_callback_info info) UniError(errno).ThrowErr(env); return nullptr; } - return NVal::CreateUndefined(env).val_; } napi_value Fsync::Async(napi_env env, napi_callback_info info) { NFuncArg funcArg(env, info); + if (!funcArg.InitArgs(NARG_CNT::ONE, NARG_CNT::TWO)) { UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); return nullptr; } - auto [resGetFirstArg, fd] = NVal(env, funcArg[NARG_POS::FIRST]).ToInt32(); - if (!resGetFirstArg) { + bool succ = false; + int fd; + tie(succ, fd) = NVal(env, funcArg[NARG_POS::FIRST]).ToInt32(); + if (!succ) { UniError(EINVAL).ThrowErr(env, "Invalid fd"); return nullptr; } @@ -71,7 +75,6 @@ napi_value Fsync::Async(napi_env env, napi_callback_info info) return UniError(ERRNO_NOERR); } }; - auto cbComplete = [](napi_env env, UniError err) -> NVal { if (err) { return { env, err.GetNapiErr(env) }; @@ -79,8 +82,7 @@ napi_value Fsync::Async(napi_env env, napi_callback_info info) return NVal::CreateUndefined(env); } }; - - const string procedureName = "FileIOFsync"; + string procedureName = "FileIOFsync"; size_t argc = funcArg.GetArgc(); NVal thisVar(env, funcArg.GetThisVar()); if (argc == NARG_CNT::ONE) { diff --git a/interfaces/kits/js/src/mod_fileio/properties/fsync.h b/interfaces/kits/js/src/mod_fileio/properties/fsync.h index 0e2a54e040fd05388608de6d0bc3a38ad264c868..9e50de49076eea650adc70ca5abb3869724ce600 100644 --- a/interfaces/kits/js/src/mod_fileio/properties/fsync.h +++ b/interfaces/kits/js/src/mod_fileio/properties/fsync.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2022 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 diff --git a/interfaces/kits/js/src/mod_fileio/properties/ftruncate.cpp b/interfaces/kits/js/src/mod_fileio/properties/ftruncate.cpp index d325a8d0edd23408066993daec7fd6d14a3a576b..66e09988d828b0e9d0dca51af7875953cf265a9d 100644 --- a/interfaces/kits/js/src/mod_fileio/properties/ftruncate.cpp +++ b/interfaces/kits/js/src/mod_fileio/properties/ftruncate.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2022 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 @@ -36,14 +36,18 @@ napi_value Ftruncate::Sync(napi_env env, napi_callback_info info) return nullptr; } - auto [resGetFirstArg, fd] = NVal(env, funcArg[NARG_POS::FIRST]).ToInt32(); - if (!resGetFirstArg) { + bool succ = false; + + int fd; + tie(succ, fd) = NVal(env, funcArg[NARG_POS::FIRST]).ToInt32(); + if (!succ) { UniError(EINVAL).ThrowErr(env, "Invalid fd"); return nullptr; } + size_t argc = funcArg.GetArgc(); int ret = -1; - if (funcArg.GetArgc() == NARG_CNT::ONE) { + if (argc == NARG_CNT::ONE) { ret = ftruncate(fd, 0); } else { int len; @@ -62,7 +66,6 @@ napi_value Ftruncate::Sync(napi_env env, napi_callback_info info) return NVal::CreateUndefined(env).val_; } - napi_value Ftruncate::Async(napi_env env, napi_callback_info info) { NFuncArg funcArg(env, info); @@ -70,22 +73,21 @@ napi_value Ftruncate::Async(napi_env env, napi_callback_info info) UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); return nullptr; } - - auto [resGetFirstArg, fd] = NVal(env, funcArg[NARG_POS::FIRST]).ToInt32(); - if (!resGetFirstArg) { + bool succ = false; + int fd; + int len = 0; + tie(succ, fd) = NVal(env, funcArg[NARG_POS::FIRST]).ToInt32(); + if (!succ) { UniError(EINVAL).ThrowErr(env, "Invalid fd"); return nullptr; } - - int len = 0; size_t argc = funcArg.GetArgc(); if (argc > NARG_CNT::ONE) { - auto [resGetSecondArg, length] = NVal(env, funcArg[NARG_POS::SECOND]).ToInt32(); - if (!resGetSecondArg) { + tie(succ, len) = NVal(env, funcArg[NARG_POS::SECOND]).ToInt32(); + if (!succ) { UniError(EINVAL).ThrowErr(env, "Invalid len"); return nullptr; } - len = length; } auto cbExec = [fd, len](napi_env env) -> UniError { @@ -96,7 +98,6 @@ napi_value Ftruncate::Async(napi_env env, napi_callback_info info) return UniError(ERRNO_NOERR); } }; - auto cbComplete = [](napi_env env, UniError err) -> NVal { if (err) { return { env, err.GetNapiErr(env) }; @@ -104,8 +105,7 @@ napi_value Ftruncate::Async(napi_env env, napi_callback_info info) return NVal::CreateUndefined(env); } }; - - const string procedureName = "fileIOFtruncate"; + string procedureName = "fileIOFtruncate"; NVal thisVar(env, funcArg.GetThisVar()); if (argc == NARG_CNT::ONE || (argc == NARG_CNT::TWO && NVal(env, funcArg[NARG_POS::SECOND]).TypeIs(napi_number))) { return NAsyncWorkPromise(env, thisVar).Schedule(procedureName, cbExec, cbComplete).val_; diff --git a/interfaces/kits/js/src/mod_fileio/properties/ftruncate.h b/interfaces/kits/js/src/mod_fileio/properties/ftruncate.h index f9d076efc337ce69f6ea7d804d07a580964b1c91..f25d600166196b6b6c8ba44a9f1d1512574a5840 100644 --- a/interfaces/kits/js/src/mod_fileio/properties/ftruncate.h +++ b/interfaces/kits/js/src/mod_fileio/properties/ftruncate.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2022 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 diff --git a/interfaces/kits/js/src/mod_fileio/properties/hash.cpp b/interfaces/kits/js/src/mod_fileio/properties/hash.cpp index 35d4c11d89f1cb82b83d6cae74c5399bf7e2a2cf..3540cada09b9ced447fe9bf9fc5fb30dbadc6c25 100644 --- a/interfaces/kits/js/src/mod_fileio/properties/hash.cpp +++ b/interfaces/kits/js/src/mod_fileio/properties/hash.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2022 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 @@ -16,7 +16,6 @@ #include "hash.h" #include -#include #include #include "../../common/file_helper/hash_file.h" @@ -35,11 +34,11 @@ enum HASH_ALGORITHM_TYPE { static HASH_ALGORITHM_TYPE GetHashAlgorithm(const unique_ptr &alg, const size_t algLen) { - if (algLen == string_view("md5").length() && string_view(alg.get()).compare("md5") == 0) { + if (algLen == ((sizeof("md5") - 1)) && !strncmp(alg.get(), "md5", algLen)) { return HASH_ALGORITHM_TYPE_MD5; - } else if (algLen == string_view("sha1").length() && string_view(alg.get()).compare("sha1") == 0) { + } else if (algLen == ((sizeof("sha1") - 1)) && !strncmp(alg.get(), "sha1", algLen)) { return HASH_ALGORITHM_TYPE_SHA1; - } else if (algLen == string_view("sha256").length() && string_view(alg.get()).compare("sha256") == 0) { + } else if (algLen == ((sizeof("sha256") - 1)) && !strncmp(alg.get(), "sha256", algLen)) { return HASH_ALGORITHM_TYPE_SHA256; } else { return HASH_ALGORITHM_TYPE_UNSUPPORTED; @@ -49,14 +48,18 @@ static HASH_ALGORITHM_TYPE GetHashAlgorithm(const unique_ptr &alg, const static tuple, HASH_ALGORITHM_TYPE, bool> GetHashArgs(napi_env env, const NFuncArg &funcArg) { bool isPromise = false; - auto [resGetFirstArg, path, unused] = NVal(env, funcArg[NARG_POS::FIRST]).ToUTF8String(); - if (!resGetFirstArg) { + bool succ = false; + unique_ptr path; + tie(succ, path, ignore) = NVal(env, funcArg[NARG_POS::FIRST]).ToUTF8String(); + if (!succ) { UniError(EINVAL).ThrowErr(env, "Invalid path"); return { false, nullptr, HASH_ALGORITHM_TYPE_UNSUPPORTED, isPromise }; } - auto [resGetSecondArg, alg, algLen] = NVal(env, funcArg[NARG_POS::SECOND]).ToUTF8String(); - if (!resGetSecondArg) { + unique_ptr alg; + size_t algLen; + tie(succ, alg, algLen) = NVal(env, funcArg[NARG_POS::SECOND]).ToUTF8String(); + if (!succ) { UniError(EINVAL).ThrowErr(env, "Invalid algorithm"); return { false, nullptr, HASH_ALGORITHM_TYPE_UNSUPPORTED, isPromise }; } @@ -84,13 +87,17 @@ napi_value Hash::Async(napi_env env, napi_callback_info info) return nullptr; } - auto [succ, fpath, algType, isPromise] = GetHashArgs(env, funcArg); + bool succ = false; + unique_ptr fpath; + HASH_ALGORITHM_TYPE algType; + bool isPromise = false; + tie(succ, fpath, algType, isPromise) = GetHashArgs(env, funcArg); if (!succ) { return nullptr; } auto arg = make_shared(); - auto cbExec = [fpath = string(fpath.release()), arg, algType = algType](napi_env env) -> UniError { + auto cbExec = [fpath = string(fpath.release()), arg, algType](napi_env env) -> UniError { int ret = EIO; string &res = *arg; if (algType == HASH_ALGORITHM_TYPE_MD5) { @@ -110,8 +117,7 @@ napi_value Hash::Async(napi_env env, napi_callback_info info) return { NVal::CreateUTF8String(env, *arg) }; }; - - const string procedureName = "FileIOHash"; + string procedureName = "FileIOHash"; NVal thisVar(env, funcArg.GetThisVar()); if (isPromise) { return NAsyncWorkPromise(env, thisVar).Schedule(procedureName, cbExec, cbComplete).val_; diff --git a/interfaces/kits/js/src/mod_fileio/properties/hash.h b/interfaces/kits/js/src/mod_fileio/properties/hash.h index 8aca34ce1315691044ee8e86d9605a104a8c07d1..0b838b22dd03a362b8a000763e65b2d36217145f 100644 --- a/interfaces/kits/js/src/mod_fileio/properties/hash.h +++ b/interfaces/kits/js/src/mod_fileio/properties/hash.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2022 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 diff --git a/interfaces/kits/js/src/mod_fileio/properties/lchown.cpp b/interfaces/kits/js/src/mod_fileio/properties/lchown.cpp index fe3511ee54999a6013e0ed834de7260cfaac6334..b0a5a318d862f454195b6a87bff9bc83e60d096c 100644 --- a/interfaces/kits/js/src/mod_fileio/properties/lchown.cpp +++ b/interfaces/kits/js/src/mod_fileio/properties/lchown.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2022 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 @@ -29,37 +29,45 @@ using namespace std; static tuple GetLchownArg(napi_env env, const NFuncArg &funcArg) { - auto [resGetFirstArg, path, unused] = NVal(env, funcArg[NARG_POS::FIRST]).ToUTF8String(); - if (!resGetFirstArg) { + bool succ = false; + unique_ptr path; + tie(succ, path, ignore) = NVal(env, funcArg[NARG_POS::FIRST]).ToUTF8String(); + if (!succ) { UniError(EINVAL).ThrowErr(env, "Invalid path"); return { false, "", -1, -1 }; } - auto [resGetSecondArg, owner] = NVal(env, funcArg[NARG_POS::SECOND]).ToInt32(); - if (!resGetSecondArg) { + int owner; + tie(succ, owner) = NVal(env, funcArg[NARG_POS::SECOND]).ToInt32(); + if (!succ) { UniError(EINVAL).ThrowErr(env, "Invalid owner"); return { false, "", -1, -1 }; } - auto [resGetThirdArg, group] = NVal(env, funcArg[NARG_POS::THIRD]).ToInt32(); - if (!resGetThirdArg) { + int group; + tie(succ, group) = NVal(env, funcArg[NARG_POS::THIRD]).ToInt32(); + if (!succ) { UniError(EINVAL).ThrowErr(env, "Invalid group"); return { false, "", -1, -1 }; } - - return { true, path.get(), owner, group }; + return { succ, path.get(), owner, group }; } napi_value Lchown::Sync(napi_env env, napi_callback_info info) { NFuncArg funcArg(env, info); + if (!funcArg.InitArgs(NARG_CNT::THREE)) { UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); return nullptr; } - auto [resGetLchownArg, path, owner, group] = GetLchownArg(env, funcArg); - if (!resGetLchownArg) { + bool succ = false; + int owner; + int group; + string path; + tie(succ, path, owner, group) = GetLchownArg(env, funcArg); + if (!succ) { return nullptr; } @@ -79,12 +87,16 @@ napi_value Lchown::Async(napi_env env, napi_callback_info info) return nullptr; } - auto [resGetLchownArg, path, owner, group] = GetLchownArg(env, funcArg); - if (!resGetLchownArg) { + bool succ = false; + int owner; + int group; + string path; + tie(succ, path, owner, group) = GetLchownArg(env, funcArg); + if (!succ) { return nullptr; } - auto cbExec = [path = path, owner = owner, group = group](napi_env env) -> UniError { + auto cbExec = [path, owner, group](napi_env env) -> UniError { if (lchown(path.c_str(), owner, group) == -1) { return UniError(errno); } else { @@ -99,7 +111,7 @@ napi_value Lchown::Async(napi_env env, napi_callback_info info) return { NVal::CreateUndefined(env) }; }; - const string procedureName = "FileIOLchown"; + string procedureName = "FileIOLchown"; NVal thisVar(env, funcArg.GetThisVar()); if (funcArg.GetArgc() == NARG_CNT::THREE) { return NAsyncWorkPromise(env, thisVar).Schedule(procedureName, cbExec, cbCompl).val_; diff --git a/interfaces/kits/js/src/mod_fileio/properties/lchown.h b/interfaces/kits/js/src/mod_fileio/properties/lchown.h index c13ad09673d250a4185c7b6ca36cbb0fef0896be..99198be56cc8de588662b1239c27bb47f405de39 100644 --- a/interfaces/kits/js/src/mod_fileio/properties/lchown.h +++ b/interfaces/kits/js/src/mod_fileio/properties/lchown.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2022 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 diff --git a/interfaces/kits/js/src/mod_fileio/properties/link.cpp b/interfaces/kits/js/src/mod_fileio/properties/link.cpp index c631dec53bd08d24c482de0cd9d64fb727962ca4..557a1acc62c7ff835e8f63048f02ae46260065d6 100644 --- a/interfaces/kits/js/src/mod_fileio/properties/link.cpp +++ b/interfaces/kits/js/src/mod_fileio/properties/link.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2022 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 @@ -30,18 +30,20 @@ using namespace std; static tuple GetLinkArg(napi_env env, const NFuncArg &funcArg) { - auto [resGetFirstArg, src, unused] = NVal(env, funcArg[NARG_POS::FIRST]).ToUTF8String(); - if (!resGetFirstArg) { + bool succ = false; + unique_ptr src; + tie(succ, src, ignore) = NVal(env, funcArg[NARG_POS::FIRST]).ToUTF8String(); + if (!succ) { UniError(EINVAL).ThrowErr(env, "Invalid src"); return { false, "", "" }; } - auto [resGetSecondArg, dest, useless] = NVal(env, funcArg[NARG_POS::SECOND]).ToUTF8String(); - if (!resGetSecondArg) { + unique_ptr dest; + tie(succ, dest, ignore) = NVal(env, funcArg[NARG_POS::SECOND]).ToUTF8String(); + if (!succ) { UniError(EINVAL).ThrowErr(env, "Invalid dest"); return { false, "", "" }; } - return { true, src.get(), dest.get() }; } @@ -53,29 +55,34 @@ napi_value Link::Sync(napi_env env, napi_callback_info info) return nullptr; } - auto [resGetLinkArg, oldPath, newPath] = GetLinkArg(env, funcArg); - if (!resGetLinkArg) { + bool succ = false; + string oldPath; + string newPath; + tie(succ, oldPath, newPath) = GetLinkArg(env, funcArg); + if (!succ) { return nullptr; } - if (link(oldPath.c_str(), newPath.c_str()) == -1) { UniError(errno).ThrowErr(env); return nullptr; } - return NVal::CreateUndefined(env).val_; } napi_value Link::Async(napi_env env, napi_callback_info info) { NFuncArg funcArg(env, info); + if (!funcArg.InitArgs(NARG_CNT::TWO, NARG_CNT::THREE)) { UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); return nullptr; } - auto [resGetLinkArg, oldPath, newPath] = GetLinkArg(env, funcArg); - if (!resGetLinkArg) { + bool succ = false; + string oldPath; + string newPath; + tie(succ, oldPath, newPath) = GetLinkArg(env, funcArg); + if (!succ) { return nullptr; } @@ -95,7 +102,7 @@ napi_value Link::Async(napi_env env, napi_callback_info info) return { NVal::CreateUndefined(env) }; }; - const string procedureName = "FileIOLink"; + string procedureName = "FileIOLink"; NVal thisVar(env, funcArg.GetThisVar()); size_t argc = funcArg.GetArgc(); if (argc == NARG_CNT::TWO) { diff --git a/interfaces/kits/js/src/mod_fileio/properties/link.h b/interfaces/kits/js/src/mod_fileio/properties/link.h index f287a24e75023561a4227eab08be337b337ded7e..7afd0d7f45b49245c0469c33e48646b94c6299a7 100644 --- a/interfaces/kits/js/src/mod_fileio/properties/link.h +++ b/interfaces/kits/js/src/mod_fileio/properties/link.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2022 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 diff --git a/interfaces/kits/js/src/mod_fileio/properties/lseek.cpp b/interfaces/kits/js/src/mod_fileio/properties/lseek.cpp index 11ecc64b4a77618348d2ddf686e030b6e6a448b2..66958c5b4d7ac3f2927bb4556eae8959c35a81f1 100644 --- a/interfaces/kits/js/src/mod_fileio/properties/lseek.cpp +++ b/interfaces/kits/js/src/mod_fileio/properties/lseek.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2022 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 @@ -27,25 +27,29 @@ using namespace std; static tuple GetLseekArg(napi_env env, const NFuncArg &funcArg) { - auto [resGetFirstArg, fd] = NVal(env, funcArg[NARG_POS::FIRST]).ToInt32(); - if (!resGetFirstArg) { + bool succ = false; + int fd; + tie(succ, fd) = NVal(env, funcArg[NARG_POS::FIRST]).ToInt32(); + if (!succ) { UniError(EINVAL).ThrowErr(env, "Invalid fd"); return { false, -1, -1, -1 }; } - auto [resGetSecondArg, offset] = NVal(env, funcArg[NARG_POS::SECOND]).ToInt32(); - if (!resGetSecondArg) { + int offset; + tie(succ, offset) = NVal(env, funcArg[NARG_POS::SECOND]).ToInt32(); + if (!succ) { UniError(EINVAL).ThrowErr(env, "Invalid offset"); return { false, -1, -1, -1 }; } - auto [resGetThirdArg, whence] = NVal(env, funcArg[NARG_POS::THIRD]).ToInt32(); - if (!resGetThirdArg) { + int whence; + tie(succ, whence) = NVal(env, funcArg[NARG_POS::THIRD]).ToInt32(); + if (!succ) { UniError(EINVAL).ThrowErr(env, "Invalid whence"); return { false, -1, -1, -1 }; } - return { true, fd, offset, whence }; + return { succ, fd, offset, whence }; } napi_value Lseek::Sync(napi_env env, napi_callback_info info) @@ -56,8 +60,12 @@ napi_value Lseek::Sync(napi_env env, napi_callback_info info) return nullptr; } - auto [resGetLseekArg, fd, offset, whence] = GetLseekArg(env, funcArg); - if (!resGetLseekArg) { + bool succ = false; + int fd; + int offset; + int whence; + tie(succ, fd, offset, whence) = GetLseekArg(env, funcArg); + if (!succ) { return nullptr; } @@ -78,13 +86,18 @@ napi_value Lseek::Async(napi_env env, napi_callback_info info) return nullptr; } - auto [resGetLseekArg, fd, offset, whence] = GetLseekArg(env, funcArg); - if (!resGetLseekArg) { + size_t argc = funcArg.GetArgc(); + bool succ = false; + int fd; + int offset; + int whence; + tie(succ, fd, offset, whence) = GetLseekArg(env, funcArg); + if (!succ) { return nullptr; } auto arg = make_shared(); - auto cbExec = [fd = fd, offset = offset, whence = whence, arg](napi_env env) -> UniError { + auto cbExec = [fd, offset, whence, arg](napi_env env) -> UniError { int ret = lseek(fd, offset, whence); *arg = ret; if (ret == -1) { @@ -101,8 +114,7 @@ napi_value Lseek::Async(napi_env env, napi_callback_info info) return { NVal::CreateInt64(env, *arg) }; }; - size_t argc = funcArg.GetArgc(); - const string procedureName = "FileIOLseek"; + string procedureName = "FileIOLseek"; NVal thisVar(env, funcArg.GetThisVar()); if (argc == NARG_CNT::THREE) { return NAsyncWorkPromise(env, thisVar).Schedule(procedureName, cbExec, cbComplCallback).val_; diff --git a/interfaces/kits/js/src/mod_fileio/properties/lseek.h b/interfaces/kits/js/src/mod_fileio/properties/lseek.h index b8ffb861cb7b6daa8193e42dd1fee4d659c1d018..c7822ec7a0792a20f9bc1410e53084bd34ab509b 100644 --- a/interfaces/kits/js/src/mod_fileio/properties/lseek.h +++ b/interfaces/kits/js/src/mod_fileio/properties/lseek.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2022 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 diff --git a/interfaces/kits/js/src/mod_fileio/properties/lstat.cpp b/interfaces/kits/js/src/mod_fileio/properties/lstat.cpp index 9945fb8e85cdc0d98f08da475660da93d814770b..3e2d2417045acc51900cdc73d092877b9b56b0d8 100644 --- a/interfaces/kits/js/src/mod_fileio/properties/lstat.cpp +++ b/interfaces/kits/js/src/mod_fileio/properties/lstat.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2022 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 @@ -40,8 +40,10 @@ napi_value Lstat::Sync(napi_env env, napi_callback_info info) return nullptr; } - auto [resGetFirstArg, pathPtr, ignore] = NVal(env, funcArg[NARG_POS::FIRST]).ToUTF8String(); - if (!resGetFirstArg) { + bool succ = false; + unique_ptr pathPtr; + tie(succ, pathPtr, ignore) = NVal(env, funcArg[NARG_POS::FIRST]).ToUTF8String(); + if (!succ) { UniError(EINVAL).ThrowErr(env, "The first argument requires type string"); return nullptr; } @@ -78,14 +80,16 @@ napi_value Lstat::Async(napi_env env, napi_callback_info info) UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); return nullptr; } - - auto [resGetFirstArg, tmp, unused] = NVal(env, funcArg[NARG_POS::FIRST]).ToUTF8String(); - if (!resGetFirstArg) { + string path; + unique_ptr tmp; + bool succ = false; + tie(succ, tmp, ignore) = NVal(env, funcArg[NARG_POS::FIRST]).ToUTF8String(); + if (!succ) { UniError(EINVAL).ThrowErr(env, "Invalid path"); return nullptr; } + path = tmp.get(); - string path = tmp.get(); auto arg = make_shared(); auto cbExec = [arg, path](napi_env env) -> UniError { if (lstat(path.c_str(), &arg->stat_)) { @@ -94,7 +98,6 @@ napi_value Lstat::Async(napi_env env, napi_callback_info info) return UniError(ERRNO_NOERR); } }; - auto cbCompl = [arg](napi_env env, UniError err) -> NVal { if (err) { return { env, err.GetNapiErr(env) }; @@ -110,9 +113,8 @@ napi_value Lstat::Async(napi_env env, napi_callback_info info) statEntity->stat_ = arg->stat_; return { env, objStat }; }; - NVal thisVar(env, funcArg.GetThisVar()); - const string procedureName = "FileIOLstat"; + string procedureName = "fileIOLstat"; if (funcArg.GetArgc() == NARG_CNT::ONE) { return NAsyncWorkPromise(env, thisVar).Schedule(procedureName, cbExec, cbCompl).val_; } else { diff --git a/interfaces/kits/js/src/mod_fileio/properties/lstat.h b/interfaces/kits/js/src/mod_fileio/properties/lstat.h index 6bd24beff996b5bfc26c1caec660f5c57cd8e242..f91730026aa4095a000273d509d551505f1f6e9e 100644 --- a/interfaces/kits/js/src/mod_fileio/properties/lstat.h +++ b/interfaces/kits/js/src/mod_fileio/properties/lstat.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2022 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 diff --git a/interfaces/kits/js/src/mod_fileio/properties/mkdtemp.cpp b/interfaces/kits/js/src/mod_fileio/properties/mkdtemp.cpp index 48dc15eebe0675102d937ac6bd5c8a956e1a6d5d..6faee34b54f2f1070b608e82f780aceef7e41531 100644 --- a/interfaces/kits/js/src/mod_fileio/properties/mkdtemp.cpp +++ b/interfaces/kits/js/src/mod_fileio/properties/mkdtemp.cpp @@ -18,6 +18,7 @@ #include "../../common/napi/n_async/n_async_work_callback.h" #include "../../common/napi/n_async/n_async_work_promise.h" #include "../../common/napi/n_func_arg.h" + namespace OHOS { namespace DistributedFS { namespace ModuleFileIO { @@ -30,19 +31,20 @@ napi_value Mkdtemp::Sync(napi_env env, napi_callback_info info) return nullptr; } - auto [resGetFirstArg, tmp, unused] = NVal(env, funcArg[NARG_POS::FIRST]).ToUTF8String(); - if (!resGetFirstArg) { + unique_ptr tmp; + bool succ = false; + tie(succ, tmp, ignore) = NVal(env, funcArg[NARG_POS::FIRST]).ToUTF8String(); + if (!succ) { UniError(EINVAL).ThrowErr(env, "Invalid path"); return nullptr; } - string path = tmp.get(); - if (mkdtemp(const_cast(path.c_str())) == nullptr) { + if (mkdtemp(tmp.get()) == nullptr) { UniError(errno).ThrowErr(env); return nullptr; } - return NVal::CreateUTF8String(env, path).val_; + return NVal::CreateUTF8String(env, tmp.get()).val_; } napi_value Mkdtemp::Async(napi_env env, napi_callback_info info) @@ -53,8 +55,10 @@ napi_value Mkdtemp::Async(napi_env env, napi_callback_info info) return nullptr; } - auto [resGetFirstArg, tmp, unused] = NVal(env, funcArg[NARG_POS::FIRST]).ToUTF8String(); - if (!resGetFirstArg) { + unique_ptr tmp; + bool succ = false; + tie(succ, tmp, ignore) = NVal(env, funcArg[NARG_POS::FIRST]).ToUTF8String(); + if (!succ) { UniError(EINVAL).ThrowErr(env, "Invalid path"); return nullptr; } @@ -69,7 +73,6 @@ napi_value Mkdtemp::Async(napi_env env, napi_callback_info info) return UniError(ERRNO_NOERR); } }; - auto cbComplete = [arg](napi_env env, UniError err) -> NVal { if (err) { return { env, err.GetNapiErr(env) }; @@ -77,8 +80,7 @@ napi_value Mkdtemp::Async(napi_env env, napi_callback_info info) return NVal::CreateUTF8String(env, *arg); } }; - - const string procedureName = "FileIOmkdtemp"; + string procedureName = "FileIOmkdtemp"; size_t argc = funcArg.GetArgc(); NVal thisVar(env, funcArg.GetThisVar()); if (argc == NARG_CNT::ONE) { diff --git a/interfaces/kits/js/src/mod_fileio/properties/mkdtemp.h b/interfaces/kits/js/src/mod_fileio/properties/mkdtemp.h index de9a7aed1df9d29d2737ea623ce7059ce388a93d..00b29f23776717931a27299d38eef6e2f997edf9 100644 --- a/interfaces/kits/js/src/mod_fileio/properties/mkdtemp.h +++ b/interfaces/kits/js/src/mod_fileio/properties/mkdtemp.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2022 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 diff --git a/interfaces/kits/js/src/mod_fileio/properties/open.cpp b/interfaces/kits/js/src/mod_fileio/properties/open.cpp index 1dfe4cbf4264e4463c80afe714ac7e71abf1f754..266c130d9df964144610ba5e25ffbd1ea7d2b059 100644 --- a/interfaces/kits/js/src/mod_fileio/properties/open.cpp +++ b/interfaces/kits/js/src/mod_fileio/properties/open.cpp @@ -18,10 +18,12 @@ #include #include #include +#include "remote_uri.h" #include "../../common/napi/n_async/n_async_work_callback.h" #include "../../common/napi/n_async/n_async_work_promise.h" #include "../../common/napi/n_func_arg.h" + namespace OHOS { namespace DistributedFS { namespace ModuleFileIO { @@ -41,18 +43,20 @@ int AdaptToAbi(int &flags) static constexpr int USR_O_NOFOLLOW = 0400000; static constexpr int USR_O_SYNC = 04010000; - flags |= ((flags & USR_O_RDONLY) == USR_O_RDONLY) ? O_RDONLY : 0; - flags |= ((flags & USR_O_WRONLY) == USR_O_WRONLY) ? O_WRONLY : 0; - flags |= ((flags & USR_O_RDWR) == USR_O_RDWR) ? O_RDWR : 0; - flags |= ((flags & USR_O_CREAT) == USR_O_CREAT) ? O_CREAT : 0; - flags |= ((flags & USR_O_EXCL) == USR_O_EXCL) ? O_EXCL : 0; - flags |= ((flags & USR_O_TRUNC) == USR_O_TRUNC) ? O_TRUNC : 0; - flags |= ((flags & USR_O_APPEND) == USR_O_APPEND) ? O_APPEND : 0; - flags |= ((flags & USR_O_NONBLOCK) == USR_O_NONBLOCK) ? O_NONBLOCK : 0; - flags |= ((flags & USR_O_DIRECTORY) == USR_O_DIRECTORY) ? O_DIRECTORY : 0; - flags |= ((flags & USR_O_NOFOLLOW) == USR_O_NOFOLLOW) ? O_NOFOLLOW : 0; - flags |= ((flags & USR_O_SYNC) == USR_O_SYNC) ? O_SYNC : 0; - return flags; + int flagsABI = 0; + flagsABI |= ((flags & USR_O_RDONLY) == USR_O_RDONLY) ? O_RDONLY : 0; + flagsABI |= ((flags & USR_O_WRONLY) == USR_O_WRONLY) ? O_WRONLY : 0; + flagsABI |= ((flags & USR_O_RDWR) == USR_O_RDWR) ? O_RDWR : 0; + flagsABI |= ((flags & USR_O_CREAT) == USR_O_CREAT) ? O_CREAT : 0; + flagsABI |= ((flags & USR_O_EXCL) == USR_O_EXCL) ? O_EXCL : 0; + flagsABI |= ((flags & USR_O_TRUNC) == USR_O_TRUNC) ? O_TRUNC : 0; + flagsABI |= ((flags & USR_O_APPEND) == USR_O_APPEND) ? O_APPEND : 0; + flagsABI |= ((flags & USR_O_NONBLOCK) == USR_O_NONBLOCK) ? O_NONBLOCK : 0; + flagsABI |= ((flags & USR_O_DIRECTORY) == USR_O_DIRECTORY) ? O_DIRECTORY : 0; + flagsABI |= ((flags & USR_O_NOFOLLOW) == USR_O_NOFOLLOW) ? O_NOFOLLOW : 0; + flagsABI |= ((flags & USR_O_SYNC) == USR_O_SYNC) ? O_SYNC : 0; + flags = flagsABI; + return flagsABI; } napi_value Open::Sync(napi_env env, napi_callback_info info) @@ -63,24 +67,28 @@ napi_value Open::Sync(napi_env env, napi_callback_info info) return nullptr; } - auto [resGetFirstArg, path, unused] = NVal(env, funcArg[NARG_POS::FIRST]).ToUTF8String(); - if (!resGetFirstArg) { + bool succ = false; + unique_ptr path; + tie(succ, path, ignore) = NVal(env, funcArg[NARG_POS::FIRST]).ToUTF8String(); + if (!succ) { UniError(EINVAL).ThrowErr(env, "Invalid path"); return nullptr; } int flags = O_RDONLY; if (funcArg.GetArgc() >= NARG_CNT::TWO) { - auto [resGetSecondArg, flg] = NVal(env, funcArg[NARG_POS::SECOND]).ToInt32(); - if (!resGetSecondArg) { + tie(succ, flags) = NVal(env, funcArg[NARG_POS::SECOND]).ToInt32(); + if (!succ) { UniError(EINVAL).ThrowErr(env, "Invalid flags"); return nullptr; } - flags = flg; } - (void)AdaptToAbi(flags); int fd = -1; + if (ModuleRemoteUri::RemoteUri::IsRemoteUri(path.get(), fd, flags)) { + return NVal::CreateInt64(env, fd).val_; + } + size_t argc = funcArg.GetArgc(); if (argc != NARG_CNT::THREE) { size_t flagsFirst { flags }; @@ -90,8 +98,9 @@ napi_value Open::Sync(napi_env env, napi_callback_info info) } fd = open(path.get(), flags); } else { - auto [resGetThirdArg, mode] = NVal(env, funcArg.GetArg(NARG_POS::THIRD)).ToInt32(); - if (!resGetThirdArg) { + int mode; + tie(succ, mode) = NVal(env, funcArg.GetArg(NARG_POS::THIRD)).ToInt32(); + if (!succ) { UniError(EINVAL).ThrowErr(env, "Invalid mode"); return nullptr; } @@ -99,6 +108,10 @@ napi_value Open::Sync(napi_env env, napi_callback_info info) } if (fd == -1) { + if (errno == ENAMETOOLONG) { + UniError(errno).ThrowErr(env, "Filename too long"); + return nullptr; + } UniError(errno).ThrowErr(env); return nullptr; } @@ -108,9 +121,12 @@ napi_value Open::Sync(napi_env env, napi_callback_info info) static UniError DoOpenExec(const std::string& path, const int flags, const int mode, shared_ptr arg) { - int ret = open(path.c_str(), flags, mode); - *arg = ret; - if (ret == -1) { + int fd = -1; + if (!ModuleRemoteUri::RemoteUri::IsRemoteUri(path, fd, flags)) { + fd = open(path.c_str(), flags, mode); + } + *arg = fd; + if (fd == -1) { return UniError(errno); } else { return UniError(ERRNO_NOERR); @@ -125,42 +141,43 @@ napi_value Open::Async(napi_env env, napi_callback_info info) return nullptr; } - auto [resGetFirstArg, path, unused] = NVal(env, funcArg[NARG_POS::FIRST]).ToUTF8String(); - if (!resGetFirstArg) { + auto [succ, path, unuse] = NVal(env, funcArg[NARG_POS::FIRST]).ToUTF8String(); + if (!succ) { UniError(EINVAL).ThrowErr(env, "Invalid path"); return nullptr; } int flags = O_RDONLY; - size_t argc = funcArg.GetArgc(); - if (argc >= NARG_CNT::TWO && !NVal(env, funcArg[NARG_POS::SECOND]).TypeIs(napi_function)) { - auto [resGetSecondArg, flg] = NVal(env, funcArg[NARG_POS::SECOND]).ToInt32(); - if (!resGetSecondArg) { + if (funcArg.GetArgc() >= NARG_CNT::TWO && !NVal(env, funcArg[NARG_POS::SECOND]).TypeIs(napi_function)) { + tie(succ, flags) = NVal(env, funcArg[NARG_POS::SECOND]).ToInt32(); + if (!succ) { UniError(EINVAL).ThrowErr(env, "Invalid flags"); return nullptr; } - flags = flg; + (void)AdaptToAbi(flags); } int mode = 0; + size_t argc = funcArg.GetArgc(); if (argc == NARG_CNT::FOUR || (argc == NARG_CNT::THREE && NVal(env, funcArg[NARG_POS::THIRD]).TypeIs(napi_number))) { - auto [resGetThirdArg, modes] = NVal(env, funcArg[NARG_POS::THIRD]).ToInt32(); - if (!resGetThirdArg) { + tie(succ, mode) = NVal(env, funcArg[NARG_POS::THIRD]).ToInt32(); + if (!succ) { UniError(EINVAL).ThrowErr(env, "Invalid mode"); return nullptr; } - mode = modes; } - (void)AdaptToAbi(flags); auto arg = make_shared(); - auto cbExec = [path = string(path.get()), flags = flags, mode = mode, arg](napi_env env) -> UniError { + auto cbExec = [path = string(path.get()), flags, mode, arg](napi_env env) -> UniError { return DoOpenExec(path, flags, mode, arg); }; auto cbComplCallback = [arg](napi_env env, UniError err) -> NVal { if (err) { + if (err.GetErrno(ERR_CODE_SYSTEM_POSIX) == ENAMETOOLONG) { + return {env, err.GetNapiErr(env, "Filename too long")}; + } return { env, err.GetNapiErr(env) }; } return { NVal::CreateInt64(env, *arg) }; @@ -171,8 +188,7 @@ napi_value Open::Async(napi_env env, napi_callback_info info) (argc == NARG_CNT::THREE && (NVal(env, funcArg[NARG_POS::THIRD]).TypeIs(napi_number)))) { return NAsyncWorkPromise(env, thisVar).Schedule("FileIOOpen", cbExec, cbComplCallback).val_; } else { - size_t cbIdx = argc - 1; - NVal cb(env, funcArg[cbIdx]); + NVal cb(env, funcArg[argc - 1]); return NAsyncWorkCallback(env, thisVar, cb).Schedule("FileIOOpen", cbExec, cbComplCallback).val_; } } diff --git a/interfaces/kits/js/src/mod_fileio/properties/open.h b/interfaces/kits/js/src/mod_fileio/properties/open.h index f6b6d718cb0f58c91b30071ac11a87459fc8f765..8caa9fdb6397d340a8c1d70e9e79fdaeeacc0408 100644 --- a/interfaces/kits/js/src/mod_fileio/properties/open.h +++ b/interfaces/kits/js/src/mod_fileio/properties/open.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2022 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 diff --git a/interfaces/kits/js/src/mod_fileio/properties/open_dir.cpp b/interfaces/kits/js/src/mod_fileio/properties/open_dir.cpp index f038733c1e30bd12817f1c7971765e49165a2da9..0a7f7fa3a71481b0a8f85b0110dcda94aeb4f80a 100644 --- a/interfaces/kits/js/src/mod_fileio/properties/open_dir.cpp +++ b/interfaces/kits/js/src/mod_fileio/properties/open_dir.cpp @@ -39,30 +39,31 @@ napi_value OpenDir::Sync(napi_env env, napi_callback_info info) return nullptr; } - auto [resGetFirstArg, path, unused] = NVal(env, funcArg[NARG_POS::FIRST]).ToUTF8String(); - if (!resGetFirstArg) { + bool succ = false; + unique_ptr path; + tie(succ, path, ignore) = NVal(env, funcArg[NARG_POS::FIRST]).ToUTF8String(); + if (!succ) { UniError(EINVAL).ThrowErr(env, "Invalid path"); return nullptr; } std::unique_ptr> dir = { opendir(path.get()), closedir }; - if (dir == nullptr) { + if (!dir) { UniError(errno).ThrowErr(env); return nullptr; } napi_value objDir = NClass::InstantiateClass(env, DirNExporter::className_, {}); - if (objDir == nullptr) { + if (!objDir) { UniError(EINVAL).ThrowErr(env, "Cannot instantiate class DirSync"); return nullptr; } auto dirEntity = NClass::GetEntityOf(env, objDir); - if (dirEntity == nullptr) { + if (!dirEntity) { UniError(EINVAL).ThrowErr(env, "Cannot get the entity of objDir"); return nullptr; } - dirEntity->dir_.swap(dir); return objDir; } @@ -81,14 +82,16 @@ napi_value OpenDir::Async(napi_env env, napi_callback_info info) UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); return nullptr; } - - auto [resGetFirstArg, tmp, unused] = NVal(env, funcArg[NARG_POS::FIRST]).ToUTF8String(); - if (!resGetFirstArg) { + string path; + unique_ptr tmp; + bool succ = false; + tie(succ, tmp, ignore) = NVal(env, funcArg[NARG_POS::FIRST]).ToUTF8String(); + if (!succ) { UniError(EINVAL).ThrowErr(env, "Invalid path"); return nullptr; } - string path = tmp.get(); + path = tmp.get(); auto arg = make_shared(NVal(env, funcArg.GetThisVar())); auto cbExec = [arg, path](napi_env env) -> UniError { DIR *dir = nullptr; @@ -99,7 +102,6 @@ napi_value OpenDir::Async(napi_env env, napi_callback_info info) arg->dir = dir; return UniError(ERRNO_NOERR); }; - auto cbCompl = [arg](napi_env env, UniError err) -> NVal { if (err) { return { env, err.GetNapiErr(env) }; diff --git a/interfaces/kits/js/src/mod_fileio/properties/open_dir.h b/interfaces/kits/js/src/mod_fileio/properties/open_dir.h index e2e07d3b068ca8b5f40d7c98b0eef91a0abcf57d..bfc954d6b04ff05f7a1a7dc71defd6047d8652c0 100644 --- a/interfaces/kits/js/src/mod_fileio/properties/open_dir.h +++ b/interfaces/kits/js/src/mod_fileio/properties/open_dir.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2022 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 diff --git a/interfaces/kits/js/src/mod_fileio/properties/posix_fallocate.cpp b/interfaces/kits/js/src/mod_fileio/properties/posix_fallocate.cpp index fe9694d36c184b224afee82d73bef29cb7c921c5..0a324beafe5c5c17a3cd57019ba9c3b8ae0e9633 100644 --- a/interfaces/kits/js/src/mod_fileio/properties/posix_fallocate.cpp +++ b/interfaces/kits/js/src/mod_fileio/properties/posix_fallocate.cpp @@ -29,25 +29,26 @@ using namespace std; static tuple GetPosixFallocateArg(napi_env env, const NFuncArg &funcArg) { - auto [resGetFirstArg, fd] = NVal(env, funcArg[NARG_POS::FIRST]).ToInt32(); - if (!resGetFirstArg) { + bool succ = false; + int fd; + tie(succ, fd) = NVal(env, funcArg[NARG_POS::FIRST]).ToInt32(); + if (!succ) { UniError(EINVAL).ThrowErr(env, "Invalid fd"); return { false, -1, -1, -1 }; } - - auto [resGetSecondArg, offset] = NVal(env, funcArg[NARG_POS::SECOND]).ToInt32(); - if (!resGetSecondArg) { + int offset; + tie(succ, offset) = NVal(env, funcArg[NARG_POS::SECOND]).ToInt32(); + if (!succ) { UniError(EINVAL).ThrowErr(env, "Invalid offset"); return { false, -1, -1, -1 }; } - - auto [resGetThirdArg, len] = NVal(env, funcArg[NARG_POS::THIRD]).ToInt32(); - if (!resGetThirdArg) { + int len; + tie(succ, len) = NVal(env, funcArg[NARG_POS::THIRD]).ToInt32(); + if (!succ) { UniError(EINVAL).ThrowErr(env, "Invalid len"); return { false, -1, -1, -1 }; } - - return { true, fd, offset, len }; + return { succ, fd, offset, len }; } napi_value PosixFallocate::Sync(napi_env env, napi_callback_info info) @@ -57,18 +58,19 @@ napi_value PosixFallocate::Sync(napi_env env, napi_callback_info info) UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); return nullptr; } - - auto [resGetPosixFallocateArg, fd, offset, len] = GetPosixFallocateArg(env, funcArg); - if (!resGetPosixFallocateArg) { + bool succ = false; + int fd; + int offset; + int len; + tie(succ, fd, offset, len) = GetPosixFallocateArg(env, funcArg); + if (!succ) { return nullptr; } - int ret = posix_fallocate(fd, offset, len); if (ret == -1) { UniError(errno).ThrowErr(env); return nullptr; } - return NVal::CreateUndefined(env).val_; } @@ -79,29 +81,29 @@ napi_value PosixFallocate::Async(napi_env env, napi_callback_info info) UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); return nullptr; } - - auto [resGetPosixFallocateArg, fd, offset, len] = GetPosixFallocateArg(env, funcArg); - if (!resGetPosixFallocateArg) { + bool succ = false; + int fd; + int offset; + int len; + tie(succ, fd, offset, len) = GetPosixFallocateArg(env, funcArg); + if (!succ) { return nullptr; } - - auto cbExec = [fd = fd, offset = offset, len = len](napi_env env) -> UniError { + auto cbExec = [fd, offset, len](napi_env env) -> UniError { if (posix_fallocate(fd, offset, len) == -1) { return UniError(errno); } else { return UniError(ERRNO_NOERR); } }; - auto cbCompl = [](napi_env env, UniError err) -> NVal { if (err) { return { env, err.GetNapiErr(env) }; } return { NVal::CreateUndefined(env) }; }; - NVal thisVar(env, funcArg.GetThisVar()); - const string procedureName = "fileioPosixFallocate"; + string procedureName = "fileioPosixFallocate"; size_t argc = funcArg.GetArgc(); if (argc == NARG_CNT::THREE) { return NAsyncWorkPromise(env, thisVar).Schedule(procedureName, cbExec, cbCompl).val_; @@ -109,7 +111,6 @@ napi_value PosixFallocate::Async(napi_env env, napi_callback_info info) NVal cb(env, funcArg[NARG_POS::FOURTH]); return NAsyncWorkCallback(env, thisVar, cb).Schedule(procedureName, cbExec, cbCompl).val_; } - return NVal::CreateUndefined(env).val_; } } // namespace ModuleFileIO diff --git a/interfaces/kits/js/src/mod_fileio/properties/posix_fallocate.h b/interfaces/kits/js/src/mod_fileio/properties/posix_fallocate.h index c26c70465bb28497c41c39f884f78d85f40f4bcf..32e2507a5b461dea646c4e9dae65d21c82deae36 100644 --- a/interfaces/kits/js/src/mod_fileio/properties/posix_fallocate.h +++ b/interfaces/kits/js/src/mod_fileio/properties/posix_fallocate.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2022 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 diff --git a/interfaces/kits/js/src/mod_fileio/properties/prop_n_exporter.cpp b/interfaces/kits/js/src/mod_fileio/properties/prop_n_exporter.cpp index fc2b21be78148527d5fe6e6f5b84bdec76cc3898..b44d67cfc5ff928856c647143bd1ee8af91691ae 100644 --- a/interfaces/kits/js/src/mod_fileio/properties/prop_n_exporter.cpp +++ b/interfaces/kits/js/src/mod_fileio/properties/prop_n_exporter.cpp @@ -15,7 +15,10 @@ #include "prop_n_exporter.h" +#include +#include #include +#include #include #include "../common_func.h" @@ -23,6 +26,7 @@ #include "chown.h" #include "close.h" #include "copy_file.h" +#include "create_randomaccessfile.h" #include "create_stream.h" #include "fchmod.h" #include "fchown.h" @@ -40,9 +44,11 @@ #include "open.h" #include "open_dir.h" #include "posix_fallocate.h" +#include "read_dir.h" #include "read_text.h" #include "rename.h" #include "rmdir.h" +#include "rmdirent.h" #include "stat.h" #include "symlink.h" #include "truncate.h" @@ -52,19 +58,20 @@ namespace OHOS { namespace DistributedFS { namespace ModuleFileIO { using namespace std; -namespace { - static constexpr int MODE_RUO_RWX = 0750; -} + napi_value PropNExporter::AccessSync(napi_env env, napi_callback_info info) { NFuncArg funcArg(env, info); + if (!funcArg.InitArgs(NARG_CNT::ONE, NARG_CNT::TWO)) { UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); return nullptr; } - auto [resGetFirstArg, path, unused] = NVal(env, funcArg[NARG_POS::FIRST]).ToUTF8String(); - if (!resGetFirstArg) { + bool succ = false; + unique_ptr path; + tie(succ, path, ignore) = NVal(env, funcArg[NARG_POS::FIRST]).ToUTF8String(); + if (!succ) { UniError(EINVAL).ThrowErr(env, "Invalid path"); return nullptr; } @@ -74,14 +81,14 @@ napi_value PropNExporter::AccessSync(napi_env env, napi_callback_info info) if (argc == NARG_CNT::ONE) { ret = access(path.get(), 0); } else { - auto [resGetSecondArg, mode] = NVal(env, funcArg[NARG_POS::SECOND]).ToInt32(); - if (!resGetSecondArg) { + int mode; + tie(succ, mode) = NVal(env, funcArg[NARG_POS::SECOND]).ToInt32(); + if (!succ) { UniError(EINVAL).ThrowErr(env, "Invalid mode"); return nullptr; } ret = access(path.get(), mode); } - if (ret == -1) { UniError(errno).ThrowErr(env); return nullptr; @@ -92,8 +99,10 @@ napi_value PropNExporter::AccessSync(napi_env env, napi_callback_info info) static tuple GetAccessArgs(napi_env env, const NFuncArg &funcArg) { - auto [resGetFirstArg, path, unused] = NVal(env, funcArg[NARG_POS::FIRST]).ToUTF8String(); - if (!resGetFirstArg) { + bool succ = false; + unique_ptr path; + tie(succ, path, ignore) = NVal(env, funcArg[NARG_POS::FIRST]).ToUTF8String(); + if (!succ) { UniError(EINVAL).ThrowErr(env, "Invalid path"); return { false, nullptr, 0, false }; } @@ -119,12 +128,11 @@ static tuple GetAccessArgs(napi_env env, const NFuncArg int mode = 0; if (hasMode) { - auto [resGetSecondArg, modes] = NVal(env, funcArg[NARG_POS::SECOND]).ToInt32(); - if (!resGetSecondArg) { + tie(succ, mode) = NVal(env, funcArg[NARG_POS::SECOND]).ToInt32(); + if (!succ) { UniError(EINVAL).ThrowErr(env, "Invalid mode"); return { false, nullptr, 0, false }; } - mode = modes; } return { true, path.get(), mode, promise }; @@ -142,11 +150,16 @@ napi_value PropNExporter::Access(napi_env env, napi_callback_info info) return nullptr; } - auto [resGetAccessArgs, path, mode, promise] = GetAccessArgs(env, funcArg); - if (!resGetAccessArgs) { + string path; + bool succ = false; + bool promise = false; + int mode; + tie(succ, path, mode, promise) = GetAccessArgs(env, funcArg); + if (!succ) { UniError(EINVAL).ThrowErr(env, "Invalid path"); return nullptr; } + size_t argc = funcArg.GetArgc(); auto cbExec = [path = move(path), mode](napi_env env) -> UniError { int ret = access(path.c_str(), mode); @@ -164,33 +177,38 @@ napi_value PropNExporter::Access(napi_env env, napi_callback_info info) return NVal::CreateUndefined(env); } }; - - const string procedureName = "FileIOAccess"; + string procedureName = "FileIOAccess"; NVal thisVar(env, funcArg.GetThisVar()); if (promise) { return NAsyncWorkPromise(env, thisVar).Schedule(procedureName, cbExec, cbComplete).val_; } else { - int cbInd = ((funcArg.GetArgc() == NARG_CNT::TWO) ? NARG_POS::SECOND : NARG_POS::THIRD); + int cbInd = ((argc == NARG_CNT::TWO) ? NARG_POS::SECOND : NARG_POS::THIRD); NVal cb(env, funcArg[cbInd]); return NAsyncWorkCallback(env, thisVar, cb).Schedule(procedureName, cbExec, cbComplete).val_; } + + return NVal::CreateUndefined(env).val_; } napi_value PropNExporter::Unlink(napi_env env, napi_callback_info info) { NFuncArg funcArg(env, info); + if (!funcArg.InitArgs(NARG_CNT::ONE, NARG_CNT::TWO)) { UniError(EINVAL).ThrowErr(env, "Number of Arguments Unmatched"); return nullptr; } - auto [resGetFirstArg, tmp, unused] = NVal(env, funcArg[NARG_POS::FIRST]).ToUTF8String(); - if (!resGetFirstArg) { + string path; + unique_ptr tmp; + bool succ = false; + tie(succ, tmp, ignore) = NVal(env, funcArg[NARG_POS::FIRST]).ToUTF8String(); + if (!succ) { UniError(EINVAL).ThrowErr(env, "invalid path"); return nullptr; } + path = tmp.get(); - string path = tmp.get(); auto cbExec = [path](napi_env env) -> UniError { if (unlink(path.c_str()) == -1) { return UniError(errno); @@ -198,7 +216,6 @@ napi_value PropNExporter::Unlink(napi_env env, napi_callback_info info) return UniError(ERRNO_NOERR); } }; - auto cbCompl = [](napi_env env, UniError err) -> NVal { if (err) { return { env, err.GetNapiErr(env) }; @@ -207,14 +224,13 @@ napi_value PropNExporter::Unlink(napi_env env, napi_callback_info info) }; NVal thisVar(env, funcArg.GetThisVar()); - const string procedureName = "FileIOStreamUnlink"; + string procedureName = "FileIOStreamUnlink"; if (funcArg.GetArgc() == NARG_CNT::ONE) { return NAsyncWorkPromise(env, thisVar).Schedule(procedureName, cbExec, cbCompl).val_; } else { NVal cb(env, funcArg[NARG_POS::SECOND]); return NAsyncWorkCallback(env, thisVar, cb).Schedule(procedureName, cbExec, cbCompl).val_; } - return NVal::CreateUndefined(env).val_; } @@ -226,30 +242,31 @@ napi_value PropNExporter::Mkdir(napi_env env, napi_callback_info info) return nullptr; } - auto [resGetFirstArg, tmp, unused] = NVal(env, funcArg[NARG_POS::FIRST]).ToUTF8String(); - if (!resGetFirstArg) { + string path; + unique_ptr tmp; + bool succ = false; + tie(succ, tmp, ignore) = NVal(env, funcArg[NARG_POS::FIRST]).ToUTF8String(); + if (!succ) { UniError(EINVAL).ThrowErr(env, "Invalid path"); return nullptr; } - - string path = tmp.get(); + path = tmp.get(); int mode = 0775; size_t argc = funcArg.GetArgc(); if ((argc == NARG_CNT::TWO && NVal(env, funcArg[NARG_POS::SECOND]).TypeIs(napi_number)) || argc == NARG_CNT::THREE) { - auto [resGetSecondArg, modes] = NVal(env, funcArg[NARG_POS::SECOND]).ToInt32(); - if (!resGetSecondArg) { + tie(succ, mode) = NVal(env, funcArg[NARG_POS::SECOND]).ToInt32(); + if (!succ) { UniError(EINVAL).ThrowErr(env, "Invalid mode"); return nullptr; } - mode = modes; } - auto cbExec = [path, mode](napi_env env) -> UniError { if (mkdir(path.c_str(), mode) == -1) { return UniError(errno); + } else { + return UniError(ERRNO_NOERR); } - return UniError(ERRNO_NOERR); }; auto cbCompl = [](napi_env env, UniError err) -> NVal { @@ -258,9 +275,8 @@ napi_value PropNExporter::Mkdir(napi_env env, napi_callback_info info) } return { NVal::CreateUndefined(env) }; }; - NVal thisVar(env, funcArg.GetThisVar()); - const string procedureName = "fileioMkdir"; + string procedureName = "fileioMkdir"; if ((argc == NARG_CNT::TWO && NVal(env, funcArg[NARG_POS::SECOND]).TypeIs(napi_number)) || argc == NARG_CNT::ONE) { return NAsyncWorkPromise(env, thisVar).Schedule(procedureName, cbExec, cbCompl).val_; } else { @@ -268,18 +284,23 @@ napi_value PropNExporter::Mkdir(napi_env env, napi_callback_info info) NVal cb(env, funcArg[cbIdx]); return NAsyncWorkCallback(env, thisVar, cb).Schedule(procedureName, cbExec, cbCompl).val_; } + + return nullptr; } napi_value PropNExporter::MkdirSync(napi_env env, napi_callback_info info) { NFuncArg funcArg(env, info); + if (!funcArg.InitArgs(NARG_CNT::ONE, NARG_CNT::TWO)) { UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); return nullptr; } - auto [resGetFirstArg, path, unused] = NVal(env, funcArg[NARG_POS::FIRST]).ToUTF8String(); - if (!resGetFirstArg) { + bool succ = false; + unique_ptr path; + tie(succ, path, ignore) = NVal(env, funcArg[NARG_POS::FIRST]).ToUTF8String(); + if (!succ) { UniError(EINVAL).ThrowErr(env, "Invalid path"); return nullptr; } @@ -287,10 +308,11 @@ napi_value PropNExporter::MkdirSync(napi_env env, napi_callback_info info) int ret = -1; size_t argc = funcArg.GetArgc(); if (argc == NARG_CNT::ONE) { - ret = mkdir(path.get(), MODE_RUO_RWX); + ret = mkdir(path.get(), 0775); } else { - auto [resGetSecondArg, mode] = NVal(env, funcArg[NARG_POS::SECOND]).ToInt32(); - if (!resGetSecondArg) { + int mode; + tie(succ, mode) = NVal(env, funcArg[NARG_POS::SECOND]).ToInt32(); + if (!succ) { UniError(EINVAL).ThrowErr(env, "Invalid mode"); return nullptr; } @@ -309,19 +331,23 @@ napi_value PropNExporter::MkdirSync(napi_env env, napi_callback_info info) napi_value PropNExporter::FchmodSync(napi_env env, napi_callback_info info) { NFuncArg funcArg(env, info); + if (!funcArg.InitArgs(NARG_CNT::TWO)) { UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); return nullptr; } - auto [resGetFirstArg, fd] = NVal(env, funcArg[NARG_POS::FIRST]).ToInt32(); - if (!resGetFirstArg) { + bool succ = false; + int fd; + tie(succ, fd) = NVal(env, funcArg[NARG_POS::FIRST]).ToInt32(); + if (!succ) { UniError(EINVAL).ThrowErr(env, "Invalid fd"); return nullptr; } - auto [resGetSecondArg, mode] = NVal(env, funcArg[NARG_POS::SECOND]).ToInt32(); - if (!resGetSecondArg) { + int mode; + tie(succ, mode) = NVal(env, funcArg[NARG_POS::SECOND]).ToInt32(); + if (!succ) { UniError(EINVAL).ThrowErr(env, "Invalid mode"); return nullptr; } @@ -338,24 +364,30 @@ napi_value PropNExporter::FchmodSync(napi_env env, napi_callback_info info) napi_value PropNExporter::FchownSync(napi_env env, napi_callback_info info) { NFuncArg funcArg(env, info); + if (!funcArg.InitArgs(NARG_CNT::THREE)) { UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); return nullptr; } - auto [resGetFirstArg, fd] = NVal(env, funcArg[NARG_POS::FIRST]).ToInt32(); - if (!resGetFirstArg) { + bool succ = false; + + int fd; + tie(succ, fd) = NVal(env, funcArg[NARG_POS::FIRST]).ToInt32(); + if (!succ) { UniError(EINVAL).ThrowErr(env, "Invalid fd"); return nullptr; } - auto [resGetSecondArg, owner] = NVal(env, funcArg[NARG_POS::SECOND]).ToInt32(); - if (!resGetSecondArg) { + int owner; + tie(succ, owner) = NVal(env, funcArg[NARG_POS::SECOND]).ToInt32(); + if (!succ) { UniError(EINVAL).ThrowErr(env, "Invalid owner"); } - auto [resGetThirdArg, group] = NVal(env, funcArg[NARG_POS::THIRD]).ToInt32(); - if (!resGetThirdArg) { + int group; + tie(succ, group) = NVal(env, funcArg[NARG_POS::THIRD]).ToInt32(); + if (!succ) { UniError(EINVAL).ThrowErr(env, "Invalid group"); } @@ -371,20 +403,28 @@ napi_value PropNExporter::FchownSync(napi_env env, napi_callback_info info) napi_value PropNExporter::ReadSync(napi_env env, napi_callback_info info) { NFuncArg funcArg(env, info); + if (!funcArg.InitArgs(NARG_CNT::TWO, NARG_CNT::THREE)) { UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); return nullptr; } - auto [resGetFirstArg, fd] = NVal(env, funcArg[NARG_POS::FIRST]).ToInt32(); - if (!resGetFirstArg) { + bool succ = false; + + int fd; + tie(succ, fd) = NVal(env, funcArg[NARG_POS::FIRST]).ToInt32(); + if (!succ) { UniError(EINVAL).ThrowErr(env, "Invalid fd"); return nullptr; } - auto [resGetReadArg, buf, len, hasPos, pos, unused] = + void *buf = nullptr; + int64_t len; + bool hasPos = false; + int64_t pos; + tie(succ, buf, len, hasPos, pos, ignore) = CommonFunc::GetReadArg(env, funcArg[NARG_POS::SECOND], funcArg[NARG_POS::THIRD]); - if (!resGetReadArg) { + if (!succ) { return nullptr; } @@ -394,7 +434,6 @@ napi_value PropNExporter::ReadSync(napi_env env, napi_callback_info info) } else { actLen = read(fd, buf, len); } - if (actLen == -1) { UniError(errno).ThrowErr(env); return nullptr; @@ -420,15 +459,22 @@ napi_value PropNExporter::Read(napi_env env, napi_callback_info info) return nullptr; } - auto [resGetFirstArg, fd] = NVal(env, funcArg[NARG_POS::FIRST]).ToInt32(); - if (!resGetFirstArg) { + bool succ = false; + void *buf = nullptr; + int64_t len; + int fd; + bool hasPos = false; + int64_t pos; + int offset; + tie(succ, fd) = NVal(env, funcArg[NARG_POS::FIRST]).ToInt32(); + if (!succ) { UniError(EINVAL).ThrowErr(env, "Invalid fd"); return nullptr; } - auto [resGetReadArg, buf, len, hasPos, pos, offset] = + tie(succ, buf, len, hasPos, pos, offset) = CommonFunc::GetReadArg(env, funcArg[NARG_POS::SECOND], funcArg[NARG_POS::THIRD]); - if (!resGetReadArg) { + if (!succ) { UniError(EINVAL).ThrowErr(env, "Failed GetReadArg"); return nullptr; } @@ -441,7 +487,6 @@ napi_value PropNExporter::Read(napi_env env, napi_callback_info info) } else { actLen = read(fd, buf, len); } - if (actLen == -1) { return UniError(errno); } else { @@ -473,7 +518,6 @@ napi_value PropNExporter::Read(napi_env env, napi_callback_info info) hasOp = true; } } - if (argc == NARG_CNT::TWO || (argc == NARG_CNT::THREE && hasOp)) { return NAsyncWorkPromise(env, thisVar).Schedule("FileIORead", cbExec, cbCompl).val_; } else { @@ -481,6 +525,8 @@ napi_value PropNExporter::Read(napi_env env, napi_callback_info info) NVal cb(env, funcArg[cbIdx]); return NAsyncWorkCallback(env, thisVar, cb).Schedule("FileIORead", cbExec, cbCompl).val_; } + + return NVal::CreateUndefined(env).val_; } UniError PropNExporter::WriteExec(shared_ptr arg, void *buf, size_t len, int fd, size_t position) @@ -493,9 +539,9 @@ UniError PropNExporter::WriteExec(shared_ptr arg, void *buf, si if (arg->actLen == -1) { return UniError(errno); + } else { + return UniError(ERRNO_NOERR); } - - return UniError(ERRNO_NOERR); } napi_value PropNExporter::Write(napi_env env, napi_callback_info info) @@ -506,15 +552,22 @@ napi_value PropNExporter::Write(napi_env env, napi_callback_info info) return nullptr; } - auto [resGetFirstArg, fd] = NVal(env, funcArg[NARG_POS::FIRST]).ToInt32(); - if (!resGetFirstArg) { + bool succ = false; + int fd; + tie(succ, fd) = NVal(env, funcArg[NARG_POS::FIRST]).ToInt32(); + if (!succ) { UniError(EINVAL).ThrowErr(env, "Invalid fd"); return nullptr; } - auto [resGetWriteArg, bufGuard, buf, len, hasPos, position] = + unique_ptr bufGuard; + void *buf = nullptr; + size_t len; + size_t position; + bool hasPos = false; + tie(succ, bufGuard, buf, len, hasPos, position) = CommonFunc::GetWriteArg(env, funcArg[NARG_POS::SECOND], funcArg[NARG_POS::THIRD]); - if (!resGetWriteArgresGetWriteArg) { + if (!succ) { UniError(EINVAL).ThrowErr(env, "Failed GetWriteArg"); return nullptr; } @@ -525,7 +578,6 @@ napi_value PropNExporter::Write(napi_env env, napi_callback_info info) } else { arg = make_shared(NVal(env, funcArg[NARG_POS::SECOND])); } - auto cbExec = [arg, buf, len, fd, position](napi_env env) -> UniError { return WriteExec(arg, buf, len, fd, position); }; @@ -533,8 +585,9 @@ napi_value PropNExporter::Write(napi_env env, napi_callback_info info) auto cbCompl = [arg](napi_env env, UniError err) -> NVal { if (err) { return { env, err.GetNapiErr(env) }; + } else { + return { NVal::CreateInt64(env, arg->actLen) }; } - return { NVal::CreateInt64(env, arg->actLen) }; }; NVal thisVar(env, funcArg.GetThisVar()); @@ -554,18 +607,23 @@ napi_value PropNExporter::Write(napi_env env, napi_callback_info info) NVal cb(env, funcArg[cbIdx]); return NAsyncWorkCallback(env, thisVar, cb).Schedule("FileIOWrite", cbExec, cbCompl).val_; } + + return NVal::CreateUndefined(env).val_; } napi_value PropNExporter::UnlinkSync(napi_env env, napi_callback_info info) { NFuncArg funcArg(env, info); + if (!funcArg.InitArgs(NARG_CNT::ONE)) { UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); return nullptr; } - auto [resGetFirstArg, path, unused] = NVal(env, funcArg[NARG_POS::FIRST]).ToUTF8String(); - if (!resGetFirstArg) { + bool succ = false; + unique_ptr path; + tie(succ, path, ignore) = NVal(env, funcArg[NARG_POS::FIRST]).ToUTF8String(); + if (!succ) { UniError(EINVAL).ThrowErr(env, "Invalid path"); return nullptr; } @@ -586,15 +644,22 @@ napi_value PropNExporter::WriteSync(napi_env env, napi_callback_info info) return nullptr; } - auto [resGetFirstArg, fd] = NVal(env, funcArg[NARG_POS::FIRST]).ToInt32(); - if (!resGetFirstArg) { + bool succ = false; + int fd; + tie(succ, fd) = NVal(env, funcArg[NARG_POS::FIRST]).ToInt32(); + if (!succ) { UniError(EINVAL).ThrowErr(env, "Invalid fd"); return nullptr; } - auto [resGetWriteArg, bufGuard, buf, len, hasPos, position] = + void *buf = nullptr; + size_t len; + size_t position; + unique_ptr bufGuard; + bool hasPos = false; + tie(succ, bufGuard, buf, len, hasPos, position) = CommonFunc::GetWriteArg(env, funcArg[NARG_POS::SECOND], funcArg[NARG_POS::THIRD]); - if (!resGetWriteArg) { + if (!succ) { return nullptr; } @@ -626,6 +691,8 @@ bool PropNExporter::Export() NVal::DeclareNapiFunction("closeSync", Close::Sync), NVal::DeclareNapiFunction("copyFile", CopyFile::Async), NVal::DeclareNapiFunction("copyFileSync", CopyFile::Sync), + NVal::DeclareNapiFunction("createRandomAccessFile", CreateRandomAccessFile::Async), + NVal::DeclareNapiFunction("createRandomAccessFileSync", CreateRandomAccessFile::Sync), NVal::DeclareNapiFunction("createStream", CreateStream::Async), NVal::DeclareNapiFunction("createStreamSync", CreateStream::Sync), NVal::DeclareNapiFunction("createWatcher", Watcher::CreateWatcher), @@ -657,9 +724,11 @@ bool PropNExporter::Export() NVal::DeclareNapiFunction("mkdtemp", Mkdtemp::Async), NVal::DeclareNapiFunction("mkdtempSync", Mkdtemp::Sync), NVal::DeclareNapiFunction("open", Open::Async), + NVal::DeclareNapiFunction("openSync", Open::Sync), NVal::DeclareNapiFunction("opendir", OpenDir::Async), NVal::DeclareNapiFunction("opendirSync", OpenDir::Sync), - NVal::DeclareNapiFunction("openSync", Open::Sync), + NVal::DeclareNapiFunction("readdir", ReadDir::Async), + NVal::DeclareNapiFunction("readdirSync", ReadDir::Sync), NVal::DeclareNapiFunction("posixFallocate", PosixFallocate::Async), NVal::DeclareNapiFunction("posixFallocateSync", PosixFallocate::Sync), NVal::DeclareNapiFunction("read", Read), @@ -668,8 +737,8 @@ bool PropNExporter::Export() NVal::DeclareNapiFunction("readTextSync", ReadText::Sync), NVal::DeclareNapiFunction("rename", Rename::Async), NVal::DeclareNapiFunction("renameSync", Rename::Sync), - NVal::DeclareNapiFunction("rmdir", Rmdir::Async), - NVal::DeclareNapiFunction("rmdirSync", Rmdir::Sync), + NVal::DeclareNapiFunction("rmdir", Rmdirent::Async), + NVal::DeclareNapiFunction("rmdirSync", Rmdirent::Sync), NVal::DeclareNapiFunction("stat", Stat::Async), NVal::DeclareNapiFunction("statSync", Stat::Sync), NVal::DeclareNapiFunction("symlink", Symlink::Async), @@ -689,6 +758,8 @@ string PropNExporter::GetClassName() } PropNExporter::PropNExporter(napi_env env, napi_value exports) : NExporter(env, exports) {} + +PropNExporter::~PropNExporter() {} } // namespace ModuleFileIO } // namespace DistributedFS } // namespace OHOS diff --git a/interfaces/kits/js/src/mod_fileio/properties/prop_n_exporter.h b/interfaces/kits/js/src/mod_fileio/properties/prop_n_exporter.h index d42aa4b57b7785285e50ec57a5e6d594c943373f..51d3b72d43c5144b7c6b6cf7d83bfcc7073f8b51 100644 --- a/interfaces/kits/js/src/mod_fileio/properties/prop_n_exporter.h +++ b/interfaces/kits/js/src/mod_fileio/properties/prop_n_exporter.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2022 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 @@ -58,7 +58,7 @@ public: std::string GetClassName() override; PropNExporter(napi_env env, napi_value exports); - ~PropNExporter() = default; + ~PropNExporter() override; }; } // namespace ModuleFileIO } // namespace DistributedFS diff --git a/interfaces/kits/js/src/mod_fileio/properties/read_dir.cpp b/interfaces/kits/js/src/mod_fileio/properties/read_dir.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ef9f615335535f868a6b94f54e2aae47c0179852 --- /dev/null +++ b/interfaces/kits/js/src/mod_fileio/properties/read_dir.cpp @@ -0,0 +1,131 @@ +/* + * Copyright (c) 2022 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. + */ + +#include "read_dir.h" + +#include +#include +#include +#include + +#include "../../common/napi/n_async/n_async_work_callback.h" +#include "../../common/napi/n_async/n_async_work_promise.h" +#include "../../common/napi/n_class.h" +#include "../../common/napi/n_func_arg.h" +#include "../../common/napi/n_val.h" +#include "../../common/uni_error.h" + +namespace OHOS { +namespace DistributedFS { +namespace ModuleFileIO { +using namespace std; + +static tuple> ParseJsPath(napi_env env, napi_value pathFromJs) +{ + auto [succ, path, ignore] = NVal(env, pathFromJs).ToUTF8String(); + return {succ, move(path)}; +} + +static bool VerifyFilePath(char* path) +{ + return strcmp(path, ".") != 0 && strcmp(path, "..") != 0; +} + +napi_value ReadDir::Sync(napi_env env, napi_callback_info info) +{ + NFuncArg funcArg(env, info); + if (!funcArg.InitArgs(NARG_CNT::ONE)) { + return nullptr; + } + auto [succ, path] = ParseJsPath(env, funcArg[NARG_POS::FIRST]); + if (!succ) { + UniError(EINVAL).ThrowErr(env, "Invalid path"); + return nullptr; + } + unique_ptr> dir = { opendir(path.get()), closedir }; + if (!dir) { + UniError(errno).ThrowErr(env); + return nullptr; + } + vector dirFiles; + struct dirent* entry = readdir(dir.get()); + while (entry) { + if (VerifyFilePath(entry->d_name)) { + dirFiles.push_back(entry->d_name); + } + entry = readdir(dir.get()); + } + return NVal::CreateArrayString(env, dirFiles).val_; +} + +struct ReadDirArgs { + vector dirFiles; + explicit ReadDirArgs() + { + dirFiles = vector(); + } + ~ReadDirArgs() = default; +}; + +napi_value ReadDir::Async(napi_env env, napi_callback_info info) +{ + NFuncArg funcArg(env, info); + if (!funcArg.InitArgs(NARG_CNT::ONE, NARG_CNT::TWO)) { + UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); + return nullptr; + } + string path; + auto [succ, tmp] = ParseJsPath(env, funcArg[NARG_POS::FIRST]); + if (!succ) { + UniError(EINVAL).ThrowErr(env, "Invalid path"); + return nullptr; + } + path = tmp.get(); + auto arg = make_shared(); + auto cbExec = [arg, path](napi_env env) -> UniError { + unique_ptr> dir = { opendir(path.c_str()), closedir }; + if (!dir) { + return UniError(errno); + } + struct dirent* entry = readdir(dir.get()); + vector dirnames; + while (entry) { + if (VerifyFilePath(entry->d_name)) { + dirnames.push_back(entry->d_name); + } + entry = readdir(dir.get()); + } + arg->dirFiles = dirnames; + return UniError(ERRNO_NOERR); + }; + auto cbCompl = [arg](napi_env env, UniError err) -> NVal { + if (err) { + return { env, err.GetNapiErr(env) }; + } else { + return NVal::CreateArrayString(env, arg->dirFiles); + } + }; + + NVal thisVar(env, funcArg.GetThisVar()); + if (funcArg.GetArgc() == NARG_CNT::ONE) { + return NAsyncWorkPromise(env, thisVar).Schedule(readdirProcedureName, cbExec, cbCompl).val_; + } else { + NVal cb(env, funcArg[NARG_POS::SECOND]); + return NAsyncWorkCallback(env, thisVar, cb).Schedule(readdirProcedureName, cbExec, cbCompl).val_; + } +} +} // namespace ModuleFileIO +} // namespace DistributedFS +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fileio/properties/read_dir.h b/interfaces/kits/js/src/mod_fileio/properties/read_dir.h new file mode 100644 index 0000000000000000000000000000000000000000..e08fdcbfddbdb82b8117879ec2eb5ef6cd56c828 --- /dev/null +++ b/interfaces/kits/js/src/mod_fileio/properties/read_dir.h @@ -0,0 +1,33 @@ +/* + * Copyright (c) 2022 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. + */ + +#ifndef INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_READ_DIR_H +#define INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_READ_DIR_H + +#include "../../common/napi/uni_header.h" + +namespace OHOS { +namespace DistributedFS { +namespace ModuleFileIO { +class ReadDir final { +public: + static napi_value Async(napi_env env, napi_callback_info info); + static napi_value Sync(napi_env env, napi_callback_info info); +}; +const std::string readdirProcedureName = "fileIOReadDir"; +} // namespace ModuleFileIO +} // namespace DistributedFS +} // namespace OHOS +#endif \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fileio/properties/read_text.cpp b/interfaces/kits/js/src/mod_fileio/properties/read_text.cpp index 33122763292ea470fdc6a7db3c1defd67d37a0a5..ec052f81dd919d7224d5c1102b9fcb4fbaf2333a 100644 --- a/interfaces/kits/js/src/mod_fileio/properties/read_text.cpp +++ b/interfaces/kits/js/src/mod_fileio/properties/read_text.cpp @@ -39,7 +39,6 @@ static tuple, bool> GetReadText bool hasOp = false; bool hasLen = false; unique_ptr encoding; - if (op.HasProp("position")) { tie(succ, position) = op.GetProp("position").ToInt32(); if (!succ) { @@ -47,7 +46,6 @@ static tuple, bool> GetReadText } hasOp = true; } - if (op.HasProp("length")) { tie(succ, len) = op.GetProp("length").ToInt32(); if (!succ) { @@ -56,15 +54,13 @@ static tuple, bool> GetReadText hasOp = true; hasLen = true; } - if (op.HasProp("encoding")) { - auto [succ, encoding, unuse] = op.GetProp("encoding").ToUTF8String(); + tie(succ, encoding, ignore) = op.GetProp("encoding").ToUTF8String(); if (!succ) { return { false, position, hasLen, len, nullptr, hasOp }; } hasOp = true; } - return { true, position, hasLen, len, move(encoding), hasOp }; } @@ -75,33 +71,34 @@ napi_value ReadText::Sync(napi_env env, napi_callback_info info) UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); return nullptr; } - - auto [resGetFirstArg, path, unused] = NVal(env, funcArg[NARG_POS::FIRST]).ToUTF8String(); - if (!resGetFirstArg) { + unique_ptr path; + bool succ = false; + FDGuard sfd; + tie(succ, path, ignore) = NVal(env, funcArg[NARG_POS::FIRST]).ToUTF8String(); + if (!succ) { UniError(EINVAL).ThrowErr(env, "Invalid path"); return nullptr; } - - auto [resGetReadTextArg, position, hasLen, len, encoding, useless] = GetReadTextArg(env, funcArg[NARG_POS::SECOND]); - if (!resGetReadTextArg) { + ssize_t position = 0; + ssize_t len = 0; + unique_ptr encoding; + bool hasLen = false; + tie(succ, position, hasLen, len, encoding, ignore) = GetReadTextArg(env, funcArg[NARG_POS::SECOND]); + if (!succ) { UniError(EINVAL).ThrowErr(env, "Invalid option"); return nullptr; } - struct stat statbf; int ret; - FDGuard sfd; sfd.SetFD(open(path.get(), O_RDONLY)); if ((!sfd) || (fstat(sfd.GetFD(), &statbf) == -1)) { UniError(errno).ThrowErr(env); return nullptr; } - if (position > statbf.st_size) { UniError(EINVAL).ThrowErr(env, "Invalid position"); return nullptr; } - len = !hasLen ? statbf.st_size : len; len = ((len < statbf.st_size) ? len : statbf.st_size); std::unique_ptr readbuf = std::make_unique(len + 1); @@ -109,18 +106,15 @@ napi_value ReadText::Sync(napi_env env, napi_callback_info info) UniError(EINVAL).ThrowErr(env, "file is too large"); return nullptr; } - if (memset_s(readbuf.get(), len + 1, 0, len + 1) != EOK) { UniError(errno).ThrowErr(env, "dfs mem error"); return nullptr; } - ret = position > 0 ? pread(sfd.GetFD(), readbuf.get(), len, position) : read(sfd.GetFD(), readbuf.get(), len); if (ret == -1) { UniError(EINVAL).ThrowErr(env, "Invalid read file"); return nullptr; } - return NVal::CreateUTF8String(env, readbuf.get(), ret).val_; } @@ -138,31 +132,25 @@ UniError ReadText::AsyncExec(const std::string &path, std::shared_ptr statbf.st_size) { return UniError(EINVAL); } - if (!hasLen) { arg->len = statbf.st_size; } - arg->len = ((arg->len < statbf.st_size) ? arg->len : statbf.st_size); arg->buf = std::make_unique(arg->len); if (arg->buf == nullptr) { return UniError(ENOMEM); } - if (position > 0) { arg->len = pread(sfd.GetFD(), arg->buf.get(), arg->len, position); } else { arg->len = read(sfd.GetFD(), arg->buf.get(), arg->len); } - if (arg->len == -1) { return UniError(EINVAL); } @@ -177,29 +165,30 @@ napi_value ReadText::Async(napi_env env, napi_callback_info info) UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); return nullptr; } - - auto [resGetFirstArg, path, unused] = NVal(env, funcArg[NARG_POS::FIRST]).ToUTF8String(); - if (!resGetFirstArg) { + unique_ptr path; + bool succ = false; + tie(succ, path, ignore) = NVal(env, funcArg[NARG_POS::FIRST]).ToUTF8String(); + if (!succ) { UniError(EINVAL).ThrowErr(env, "Invalid path"); return nullptr; } - - auto [resGetSecondArg, position, hasLen, len, encoding, hasOp] = GetReadTextArg(env, funcArg[NARG_POS::SECOND]); - if (!resGetSecondArg) { + ssize_t position; + ssize_t len; + unique_ptr encoding; + bool hasOp = false; + bool hasLen = false; + tie(succ, position, hasLen, len, encoding, hasOp) = GetReadTextArg(env, funcArg[NARG_POS::SECOND]); + if (!succ) { UniError(EINVAL).ThrowErr(env, "Invalid option"); return nullptr; } - auto arg = make_shared(NVal(env, funcArg.GetThisVar())); if (arg == nullptr) { return nullptr; } - - auto cbExec = - [path = string(path.get()), arg, position = position, hasLen = hasLen, len = len](napi_env env) -> UniError { + auto cbExec = [path = string(path.get()), arg, position, hasLen, len](napi_env env) -> UniError { return AsyncExec(path, arg, position, hasLen, len); }; - auto cbComplete = [arg](napi_env env, UniError err) -> NVal { if (err) { return { env, err.GetNapiErr(env) }; @@ -207,7 +196,6 @@ napi_value ReadText::Async(napi_env env, napi_callback_info info) return NVal::CreateUTF8String(env, arg->buf.get(), arg->len); } }; - size_t argc = funcArg.GetArgc(); NVal thisVar(env, funcArg.GetThisVar()); if (argc == NARG_CNT::ONE || (argc == NARG_CNT::TWO && hasOp)) { diff --git a/interfaces/kits/js/src/mod_fileio/properties/read_text.h b/interfaces/kits/js/src/mod_fileio/properties/read_text.h index 8821437732bc7ef7235a5785b4e5bce5346f5aec..c3f7427df204bf1fc97f6c3f3f0a4c2d1aaead7c 100644 --- a/interfaces/kits/js/src/mod_fileio/properties/read_text.h +++ b/interfaces/kits/js/src/mod_fileio/properties/read_text.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2022 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 diff --git a/interfaces/kits/js/src/mod_fileio/properties/rename.cpp b/interfaces/kits/js/src/mod_fileio/properties/rename.cpp index afb19cedc759e72536b3b7b5174be3c3f0b783c4..3abe6c68d16cd30d6835f192b514362037bc3b8c 100644 --- a/interfaces/kits/js/src/mod_fileio/properties/rename.cpp +++ b/interfaces/kits/js/src/mod_fileio/properties/rename.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2022 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 @@ -31,19 +31,23 @@ using namespace std; napi_value Rename::Sync(napi_env env, napi_callback_info info) { NFuncArg funcArg(env, info); + if (!funcArg.InitArgs(NARG_CNT::TWO)) { UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); return nullptr; } - auto [resGetFirstArg, src, unused] = NVal(env, funcArg[NARG_POS::FIRST]).ToUTF8String(); - if (!resGetFirstArg) { + bool succ = false; + unique_ptr src; + tie(succ, src, ignore) = NVal(env, funcArg[NARG_POS::FIRST]).ToUTF8String(); + if (!succ) { UniError(EINVAL).ThrowErr(env, "Invalid src"); return nullptr; } - auto [resGetSecondArg, dest, useless] = NVal(env, funcArg[NARG_POS::SECOND]).ToUTF8String(); - if (!resGetSecondArg) { + unique_ptr dest; + tie(succ, dest, ignore) = NVal(env, funcArg[NARG_POS::SECOND]).ToUTF8String(); + if (!succ) { UniError(EINVAL).ThrowErr(env, "Invalid dest"); return nullptr; } @@ -64,14 +68,18 @@ napi_value Rename::Async(napi_env env, napi_callback_info info) return nullptr; } - auto [resGetFirstArg, src, unused] = NVal(env, funcArg[NARG_POS::FIRST]).ToUTF8String(); - if (!resGetFirstArg) { + string path; + bool succ = false; + unique_ptr src; + tie(succ, src, ignore) = NVal(env, funcArg[NARG_POS::FIRST]).ToUTF8String(); + if (!succ) { UniError(EINVAL).ThrowErr(env, "Invalid src"); return nullptr; } - auto [resGetSecondArg, dest, useless] = NVal(env, funcArg[NARG_POS::SECOND]).ToUTF8String(); - if (!resGetSecondArg) { + unique_ptr dest; + tie(succ, dest, ignore) = NVal(env, funcArg[NARG_POS::SECOND]).ToUTF8String(); + if (!succ) { UniError(EINVAL).ThrowErr(env, "Invalid dest"); return nullptr; } @@ -92,7 +100,7 @@ napi_value Rename::Async(napi_env env, napi_callback_info info) return { NVal::CreateUndefined(env) }; }; - const string procedureName = "FileIORename"; + string procedureName = "FileIORename"; NVal thisVar(env, funcArg.GetThisVar()); size_t argc = funcArg.GetArgc(); if (argc == NARG_CNT::TWO) { diff --git a/interfaces/kits/js/src/mod_fileio/properties/rename.h b/interfaces/kits/js/src/mod_fileio/properties/rename.h index 0333170a66be1f5666ae5f17de6856d0bbf4e81c..0712c7263fd5562cae609116163fe9488586f5df 100644 --- a/interfaces/kits/js/src/mod_fileio/properties/rename.h +++ b/interfaces/kits/js/src/mod_fileio/properties/rename.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2022 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 diff --git a/interfaces/kits/js/src/mod_fileio/properties/rmdir.cpp b/interfaces/kits/js/src/mod_fileio/properties/rmdir.cpp index fcce9f3d5add18ec47ffaf71b5e8b3803106d3d3..46d8267a982cde56d5b976fdb55634a4e237b628 100644 --- a/interfaces/kits/js/src/mod_fileio/properties/rmdir.cpp +++ b/interfaces/kits/js/src/mod_fileio/properties/rmdir.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2022 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 @@ -29,13 +29,16 @@ using namespace std; napi_value Rmdir::Sync(napi_env env, napi_callback_info info) { NFuncArg funcArg(env, info); + if (!funcArg.InitArgs(NARG_CNT::ONE)) { UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); return nullptr; } - auto [resGetFirstArg, path, unused] = NVal(env, funcArg[NARG_POS::FIRST]).ToUTF8String(); - if (!resGetFirstArg) { + bool succ = false; + unique_ptr path; + tie(succ, path, ignore) = NVal(env, funcArg[NARG_POS::FIRST]).ToUTF8String(); + if (!succ) { UniError(EINVAL).ThrowErr(env, "Invalid path"); return nullptr; } @@ -56,8 +59,10 @@ napi_value Rmdir::Async(napi_env env, napi_callback_info info) return nullptr; } - auto [resGetFirstArg, path, unused] = NVal(env, funcArg[NARG_POS::FIRST]).ToUTF8String(); - if (!resGetFirstArg) { + bool succ = false; + unique_ptr path; + tie(succ, path, ignore) = NVal(env, funcArg[NARG_POS::FIRST]).ToUTF8String(); + if (!succ) { UniError(EINVAL).ThrowErr(env, "Invalid path"); return nullptr; } @@ -70,7 +75,6 @@ napi_value Rmdir::Async(napi_env env, napi_callback_info info) return UniError(ERRNO_NOERR); } }; - auto cbCompl = [](napi_env env, UniError err) -> NVal { if (err) { return { env, err.GetNapiErr(env) }; @@ -78,8 +82,7 @@ napi_value Rmdir::Async(napi_env env, napi_callback_info info) return NVal::CreateUndefined(env); } }; - - const string procedureName = "FileIORmdir"; + string procedureName = "FileIORmdir"; NVal thisVar(env, funcArg.GetThisVar()); size_t argc = funcArg.GetArgc(); if (argc == NARG_CNT::ONE) { diff --git a/interfaces/kits/js/src/mod_fileio/properties/rmdir.h b/interfaces/kits/js/src/mod_fileio/properties/rmdir.h index 6e6e7bffeeda510f10ff9a79a5d08a8d7b830c4c..369ea83a4ba0d037bfc48c11f3d66a67243d9bba 100644 --- a/interfaces/kits/js/src/mod_fileio/properties/rmdir.h +++ b/interfaces/kits/js/src/mod_fileio/properties/rmdir.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2022 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 diff --git a/interfaces/kits/js/src/mod_fileio/properties/rmdirent.cpp b/interfaces/kits/js/src/mod_fileio/properties/rmdirent.cpp new file mode 100644 index 0000000000000000000000000000000000000000..66dd48e58ad5565925a3944aaa72fb9b1144adea --- /dev/null +++ b/interfaces/kits/js/src/mod_fileio/properties/rmdirent.cpp @@ -0,0 +1,142 @@ +/* + * Copyright (c) 2022 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. + */ + +#include "rmdirent.h" + +#include +#include +#include +#include +#include +#include + +#include "../../common/napi/n_async/n_async_work_callback.h" +#include "../../common/napi/n_async/n_async_work_promise.h" +#include "../../common/napi/n_func_arg.h" + +namespace OHOS { +namespace DistributedFS { +namespace ModuleFileIO { +using namespace std; + +static tuple> ParseJsPath(napi_env env, napi_value pathFromJs) +{ + auto [succ, path, ignore] = NVal(env, pathFromJs).ToUTF8String(); + return {succ, move(path)}; +} + +static UniError rmdirent(napi_env env, string path) +{ + if (rmdir(path.c_str()) == 0) { + return UniError(ERRNO_NOERR); + } + auto dir = opendir(path.c_str()); + if (!dir) { + return UniError(errno); + } + struct dirent* entry = readdir(dir); + while (entry) { + if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) { + entry = readdir(dir); + continue; + } + struct stat fileInformation; + string filePath = path + '/'; + filePath.insert(filePath.length(), entry->d_name); + if (stat(filePath.c_str(), &fileInformation) != 0) { + closedir(dir); + return UniError(errno); + } + if ((fileInformation.st_mode & S_IFMT) == S_IFDIR) { + auto err = rmdirent(env, filePath); + if (err) { + closedir(dir); + return err; + } + } else { + if (unlink(filePath.c_str()) != 0) { + closedir(dir); + return UniError(errno); + } + } + entry = readdir(dir); + } + closedir(dir); + if (rmdir(path.c_str()) != 0) { + return UniError(errno); + } + return UniError(ERRNO_NOERR); +} + +napi_value Rmdirent::Sync(napi_env env, napi_callback_info info) +{ + NFuncArg funcArg(env, info); + + if (!funcArg.InitArgs(NARG_CNT::ONE)) { + UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); + return nullptr; + } + + auto [succ, path] = ParseJsPath(env, funcArg[NARG_POS::FIRST]); + if (!succ) { + UniError(EINVAL).ThrowErr(env, "Invalid path"); + return nullptr; + } + + auto err = rmdirent(env, string(path.get())); + if (err) { + err.ThrowErr(env); + return nullptr; + } + return NVal::CreateUndefined(env).val_; +} + +napi_value Rmdirent::Async(napi_env env, napi_callback_info info) +{ + NFuncArg funcArg(env, info); + if (!funcArg.InitArgs(NARG_CNT::ONE, NARG_CNT::TWO)) { + UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); + return nullptr; + } + + auto [succ, path] = ParseJsPath(env, funcArg[NARG_POS::FIRST]); + if (!succ) { + UniError(EINVAL).ThrowErr(env, "Invalid path"); + return nullptr; + } + + auto cbExec = [path = string(path.get())](napi_env env) -> UniError { + return rmdirent(env, path); + }; + auto cbCompl = [](napi_env env, UniError err) -> NVal { + if (err) { + return { env, err.GetNapiErr(env) }; + } else { + return NVal::CreateUndefined(env); + } + }; + + NVal thisVar(env, funcArg.GetThisVar()); + size_t argc = funcArg.GetArgc(); + if (argc == NARG_CNT::ONE) { + return NAsyncWorkPromise(env, thisVar).Schedule(rmdirProcedureName, cbExec, cbCompl).val_; + } else { + NVal cb(env, funcArg[NARG_POS::SECOND]); + return NAsyncWorkCallback(env, thisVar, cb).Schedule(rmdirProcedureName, cbExec, cbCompl).val_; + } +} +} // namespace ModuleFileIO +} // namespace DistributedFS +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fileio/properties/rmdirent.h b/interfaces/kits/js/src/mod_fileio/properties/rmdirent.h new file mode 100644 index 0000000000000000000000000000000000000000..b63e528d1cf3ddff2a0323910d1848ec48589cea --- /dev/null +++ b/interfaces/kits/js/src/mod_fileio/properties/rmdirent.h @@ -0,0 +1,33 @@ +/* + * Copyright (c) 2022 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. + */ + +#ifndef INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_RMDIRENT_H +#define INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_RMDIRENT_H + +#include "../../common/napi/n_val.h" + +namespace OHOS { +namespace DistributedFS { +namespace ModuleFileIO { +class Rmdirent final { +public: + static napi_value Sync(napi_env env, napi_callback_info info); + static napi_value Async(napi_env env, napi_callback_info info); +}; +const std::string rmdirProcedureName = "FileIORmDirent"; +} // namespace ModuleFileIO +} // namespace DistributedFS +} // namespace OHOS +#endif \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fileio/properties/stat.cpp b/interfaces/kits/js/src/mod_fileio/properties/stat.cpp index 26cded63e7f0b65f08f5930b4974c8f16958c88d..aa7f9b1823645f7cd65cf281b1caa0a295d28df2 100644 --- a/interfaces/kits/js/src/mod_fileio/properties/stat.cpp +++ b/interfaces/kits/js/src/mod_fileio/properties/stat.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2022 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 @@ -40,8 +40,10 @@ napi_value Stat::Sync(napi_env env, napi_callback_info info) return nullptr; } - aut [resGetFirstArg, pathPtr, unused] = NVal(env, funcArg[NARG_POS::FIRST]).ToUTF8String(); - if (!resGetFirstArg) { + bool succ = false; + unique_ptr pathPtr; + tie(succ, pathPtr, ignore) = NVal(env, funcArg[NARG_POS::FIRST]).ToUTF8String(); + if (!succ) { UniError(EINVAL).ThrowErr(env, "The first argument requires type string"); return nullptr; } @@ -78,14 +80,16 @@ napi_value Stat::Async(napi_env env, napi_callback_info info) UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); return nullptr; } - - auto [resGetFirstArg, tmp, unuse] = NVal(env, funcArg[NARG_POS::FIRST]).ToUTF8String(); - if (!resGetFirstArg) { + string path; + unique_ptr tmp; + bool succ = false; + tie(succ, tmp, ignore) = NVal(env, funcArg[NARG_POS::FIRST]).ToUTF8String(); + if (!succ) { UniError(EINVAL).ThrowErr(env, "Invalid path"); return nullptr; } + path = tmp.get(); - string path = tmp.get(); auto arg = make_shared(); auto cbExec = [arg, path](napi_env env) -> UniError { if (stat(path.c_str(), &arg->stat_)) { @@ -94,28 +98,23 @@ napi_value Stat::Async(napi_env env, napi_callback_info info) return UniError(ERRNO_NOERR); } }; - auto cbCompl = [arg](napi_env env, UniError err) -> NVal { if (err) { return { env, err.GetNapiErr(env) }; } - napi_value objStat = NClass::InstantiateClass(env, StatNExporter::className_, {}); if (!objStat) { return { env, UniError(EIO).GetNapiErr(env) }; } - auto statEntity = NClass::GetEntityOf(env, objStat); if (!statEntity) { return { env, UniError(EIO).GetNapiErr(env) }; } - statEntity->stat_ = arg->stat_; return { env, objStat }; }; - NVal thisVar(env, funcArg.GetThisVar()); - const string procedureName = "fileioStatStat"; + string procedureName = "fileioStatStat"; if (funcArg.GetArgc() == NARG_CNT::ONE) { return NAsyncWorkPromise(env, thisVar).Schedule(procedureName, cbExec, cbCompl).val_; } else { diff --git a/interfaces/kits/js/src/mod_fileio/properties/stat.h b/interfaces/kits/js/src/mod_fileio/properties/stat.h index 8b16373e9b313c97cbfb9c3c21c06cf521edb82f..e53cafec408e6926ca1750fa0c79412803a73853 100644 --- a/interfaces/kits/js/src/mod_fileio/properties/stat.h +++ b/interfaces/kits/js/src/mod_fileio/properties/stat.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2022 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 diff --git a/interfaces/kits/js/src/mod_fileio/properties/symlink.cpp b/interfaces/kits/js/src/mod_fileio/properties/symlink.cpp index 98d4739455e0e36689b8b145bea92da6a1b70f05..e9e3d634569f7f3ce3f59f8a109c7599b1c93d15 100644 --- a/interfaces/kits/js/src/mod_fileio/properties/symlink.cpp +++ b/interfaces/kits/js/src/mod_fileio/properties/symlink.cpp @@ -29,18 +29,20 @@ using namespace std; static tuple GetSymlinkArg(napi_env env, const NFuncArg &funcArg) { - auto [resGetFirstArg, src, unused] = NVal(env, funcArg[NARG_POS::FIRST]).ToUTF8String(); - if (!resGetFirstArg) { + bool succ = false; + unique_ptr src; + tie(succ, src, ignore) = NVal(env, funcArg[NARG_POS::FIRST]).ToUTF8String(); + if (!succ) { UniError(EINVAL).ThrowErr(env, "Invalid src"); return { false, "", "" }; } - auto [resGetSecondArg, dest, useless] = NVal(env, funcArg[NARG_POS::SECOND]).ToUTF8String(); - if (!resGetSecondArg) { + unique_ptr dest; + tie(succ, dest, ignore) = NVal(env, funcArg[NARG_POS::SECOND]).ToUTF8String(); + if (!succ) { UniError(EINVAL).ThrowErr(env, "Invalid dest"); return { false, "", "" }; } - return { true, src.get(), dest.get() }; } @@ -52,8 +54,11 @@ napi_value Symlink::Sync(napi_env env, napi_callback_info info) return nullptr; } - auto [resGetSymlinkArg, oldPath, newPath] = GetSymlinkArg(env, funcArg); - if (!resGetSymlinkArg) { + bool succ = false; + string oldPath; + string newPath; + tie(succ, oldPath, newPath) = GetSymlinkArg(env, funcArg); + if (!succ) { return nullptr; } @@ -61,7 +66,6 @@ napi_value Symlink::Sync(napi_env env, napi_callback_info info) UniError(errno).ThrowErr(env); return nullptr; } - return NVal::CreateUndefined(env).val_; } @@ -73,8 +77,11 @@ napi_value Symlink::Async(napi_env env, napi_callback_info info) return nullptr; } - auto [resGetSymlinkArg, oldPath, newPath] = GetSymlinkArg(env, funcArg); - if (!resGetSymlinkArg) { + bool succ = false; + string oldPath; + string newPath; + tie(succ, oldPath, newPath) = GetSymlinkArg(env, funcArg); + if (!succ) { return nullptr; } @@ -94,7 +101,7 @@ napi_value Symlink::Async(napi_env env, napi_callback_info info) return { NVal::CreateUndefined(env) }; }; - const string procedureName = "FileIOsymLink"; + string procedureName = "FileIOsymLink"; NVal thisVar(env, funcArg.GetThisVar()); size_t argc = funcArg.GetArgc(); if (argc == NARG_CNT::TWO) { diff --git a/interfaces/kits/js/src/mod_fileio/properties/symlink.h b/interfaces/kits/js/src/mod_fileio/properties/symlink.h index b770a27e874c3392e3ae46e112a6342140ed06f7..f42bb861c1da8ac786e1028b93c8d4165e5d8474 100644 --- a/interfaces/kits/js/src/mod_fileio/properties/symlink.h +++ b/interfaces/kits/js/src/mod_fileio/properties/symlink.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2022 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 diff --git a/interfaces/kits/js/src/mod_fileio/properties/truncate.cpp b/interfaces/kits/js/src/mod_fileio/properties/truncate.cpp index b86f59279632123a08b8e0aa2b764ff5e9982515..30e67e492e29823a1cecbc4337c54fc135ce99d5 100644 --- a/interfaces/kits/js/src/mod_fileio/properties/truncate.cpp +++ b/interfaces/kits/js/src/mod_fileio/properties/truncate.cpp @@ -27,13 +27,16 @@ using namespace std; napi_value Truncate::Sync(napi_env env, napi_callback_info info) { NFuncArg funcArg(env, info); + if (!funcArg.InitArgs(NARG_CNT::ONE, NARG_CNT::TWO)) { UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); return nullptr; } - auto [resGetFirstArg, path, unused] = NVal(env, funcArg[NARG_POS::FIRST]).ToUTF8String(); - if (!resGetFirstArg) { + bool succ = false; + unique_ptr path; + tie(succ, path, ignore) = NVal(env, funcArg[NARG_POS::FIRST]).ToUTF8String(); + if (!succ) { UniError(EINVAL).ThrowErr(env, "Invalid path"); return nullptr; } @@ -42,8 +45,9 @@ napi_value Truncate::Sync(napi_env env, napi_callback_info info) if (funcArg.GetArgc() == NARG_CNT::ONE) { ret = truncate(path.get(), 0); } else { - auto [resGetSecondArg, len] = NVal(env, funcArg[NARG_POS::SECOND]).ToInt32(); - if (!resGetSecondArg) { + int len; + tie(succ, len) = NVal(env, funcArg[NARG_POS::SECOND]).ToInt32(); + if (!succ) { UniError(EINVAL).ThrowErr(env, "Invalid len"); } ret = truncate(path.get(), len); @@ -53,7 +57,6 @@ napi_value Truncate::Sync(napi_env env, napi_callback_info info) UniError(errno).ThrowErr(env); return nullptr; } - return NVal::CreateUndefined(env).val_; } @@ -64,24 +67,22 @@ napi_value Truncate::Async(napi_env env, napi_callback_info info) UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); return nullptr; } - - auto [resGetFirstArg, path, unused] = NVal(env, funcArg[NARG_POS::FIRST]).ToUTF8String(); - if (!resGetFirstArg) { + bool succ = false; + unique_ptr path; + int len = 0; + tie(succ, path, ignore) = NVal(env, funcArg[NARG_POS::FIRST]).ToUTF8String(); + if (!succ) { UniError(EINVAL).ThrowErr(env, "Invalid path"); return nullptr; } - - int len = 0; size_t argc = funcArg.GetArgc(); if (argc > NARG_CNT::ONE) { - auto [resGetSecondArg, length] = NVal(env, funcArg[NARG_POS::SECOND]).ToInt32(); - if (!resGetSecondArg) { + tie(succ, len) = NVal(env, funcArg[NARG_POS::SECOND]).ToInt32(); + if (!succ) { UniError(EINVAL).ThrowErr(env, "Invalid len"); return nullptr; } - len = length; } - auto cbExec = [path = string(path.get()), len](napi_env env) -> UniError { int ret = truncate(path.c_str(), len); if (ret == -1) { @@ -90,7 +91,6 @@ napi_value Truncate::Async(napi_env env, napi_callback_info info) return UniError(ERRNO_NOERR); } }; - auto cbCompl = [](napi_env env, UniError err) -> NVal { if (err) { return { env, err.GetNapiErr(env) }; @@ -100,7 +100,7 @@ napi_value Truncate::Async(napi_env env, napi_callback_info info) }; NVal thisVar(env, funcArg.GetThisVar()); - const string procedureName = "FileIOTruncate"; + string procedureName = "fileIOTruncate"; if (argc == NARG_CNT::ONE || (argc == NARG_CNT::TWO && NVal(env, funcArg[NARG_POS::SECOND]).TypeIs(napi_number))) { return NAsyncWorkPromise(env, thisVar).Schedule(procedureName, cbExec, cbCompl).val_; } else { diff --git a/interfaces/kits/js/src/mod_fileio/properties/truncate.h b/interfaces/kits/js/src/mod_fileio/properties/truncate.h index b4f32e0264947345ea5803bec3148181aabf347f..6f5f1852749a61ad3dc2cc763d996d8d024c5fcb 100644 --- a/interfaces/kits/js/src/mod_fileio/properties/truncate.h +++ b/interfaces/kits/js/src/mod_fileio/properties/truncate.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2022 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 diff --git a/interfaces/kits/js/src/mod_fileio/properties/watcher.cpp b/interfaces/kits/js/src/mod_fileio/properties/watcher.cpp index b822f9a3c6461034cb62979578c32354e451d672..6731cc1650ef0d6d0d6e20551905573c5b76097f 100644 --- a/interfaces/kits/js/src/mod_fileio/properties/watcher.cpp +++ b/interfaces/kits/js/src/mod_fileio/properties/watcher.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2022 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 @@ -60,13 +60,16 @@ napi_value Watcher::CreateWatcher(napi_env env, napi_callback_info info) return nullptr; } - auto [succGetPath, filename, unused] = NVal(env, funcArg[NARG_POS::FIRST]).ToUTF8String(); + bool succGetPath = false; + unique_ptr filename; + tie(succGetPath, filename, ignore) = NVal(env, funcArg[NARG_POS::FIRST]).ToUTF8String(); if (!succGetPath) { UniError(EINVAL).ThrowErr(env, "Invalid filename"); return nullptr; } - - auto [succGetEvent, event] = NVal(env, funcArg[NARG_POS::SECOND]).ToInt32(); + bool succGetEvent = false; + int event; + tie(succGetEvent, event) = NVal(env, funcArg[NARG_POS::SECOND]).ToInt32(); if (!succGetEvent) { UniError(EINVAL).ThrowErr(env, "Invalid event"); return nullptr; @@ -89,13 +92,11 @@ napi_value Watcher::CreateWatcher(napi_env env, napi_callback_info info) UniError(EINVAL).ThrowErr(env, "objWatcher create failed"); return nullptr; } - auto watcherEntity = NClass::GetEntityOf(env, objWatcher); if (!watcherEntity) { UniError(EINVAL).ThrowErr(env, "watcherEntity get failed"); return nullptr; } - watcherEntity->fsEventReq_ = std::move(fsEventReq); watcherEntity->data_ = std::move(data); diff --git a/interfaces/kits/js/src/mod_fileio/properties/watcher.h b/interfaces/kits/js/src/mod_fileio/properties/watcher.h index 45c100cb21057e0a0711212df5ec9846985aebaf..c73d043a40ab94a1045f0eb4369352f5cd9f6920 100644 --- a/interfaces/kits/js/src/mod_fileio/properties/watcher.h +++ b/interfaces/kits/js/src/mod_fileio/properties/watcher.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2022 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 diff --git a/interfaces/kits/js/src/mod_securitylabel/security_label.h b/interfaces/kits/js/src/mod_securitylabel/security_label.h index 77b4c50f16f5c390cd62a2d45e1e68120f59211d..693579092f6a4cb84a8c8aebc258b359fc4c427c 100644 --- a/interfaces/kits/js/src/mod_securitylabel/security_label.h +++ b/interfaces/kits/js/src/mod_securitylabel/security_label.h @@ -13,8 +13,8 @@ * limitations under the License. */ -#ifndef SECURITY_LABEL_H -#define SECURITY_LABEL_H +#ifndef FOUNDATION_FILEMANAGEMENT_FILEAPI_INTERFACES_INNERKITS_SECURITY_LABEL_H +#define FOUNDATION_FILEMANAGEMENT_FILEAPI_INTERFACES_INNERKITS_SECURITY_LABEL_H #include #include @@ -25,11 +25,11 @@ namespace OHOS { namespace DistributedFS { namespace ModuleSecurityLabel { +const char XATTR_KEY[] = {"user.security"}; +const std::string DEFAULT_DATA_LEVEL = "s3"; +const std::set DATA_LEVEL = {"s0", "s1", "s2", "s3", "s4"}; class SecurityLabel { public: - static const char XATTR_KEY[] {"user.security"}; - static const std::string DEFAULT_DATA_LEVEL = "s3"; - static const std::set DATA_LEVEL = {"s0", "s1", "s2", "s3", "s4"}; static bool SetSecurityLabel(const std::string &path, const std::string &dataLevel) { if (DATA_LEVEL.count(dataLevel) != 1) { @@ -43,7 +43,7 @@ public: static std::string GetSecurityLabel(const std::string &path) { - auto xattrValueSize = getxattr(path.c_str(), XATTR_KEY, NULL, 0); + auto xattrValueSize = getxattr(path.c_str(), XATTR_KEY, nullptr, 0); if (xattrValueSize == -1 || errno == ENOTSUP) { return ""; } diff --git a/interfaces/kits/js/src/mod_securitylabel/securitylabel_n_exporter.cpp b/interfaces/kits/js/src/mod_securitylabel/securitylabel_n_exporter.cpp index 1e0ac78f6267c3b7d9df52da13d246b7b8acaa93..b0ceb35fe4471caf737965a5f46248cd89aa51f0 100644 --- a/interfaces/kits/js/src/mod_securitylabel/securitylabel_n_exporter.cpp +++ b/interfaces/kits/js/src/mod_securitylabel/securitylabel_n_exporter.cpp @@ -15,7 +15,6 @@ #include "securitylabel_n_exporter.h" -#include #include #include "../common/napi/n_class.h" @@ -26,6 +25,10 @@ #include "n_async_work_promise.h" #include "security_label.h" + +#include + + namespace OHOS { namespace DistributedFS { namespace ModuleSecurityLabel { @@ -73,7 +76,7 @@ napi_value SetSecurityLabel(napi_env env, napi_callback_info info) return NVal::CreateUndefined(env); } }; - static const std::string procedureName = "SetSecurityLabel"; + std::string procedureName = "SetSecurityLabel"; NVal thisVar(env, funcArg.GetThisVar()); if (funcArg.GetArgc() == static_cast(NARG_CNT::TWO)) { return NAsyncWorkPromise(env, thisVar).Schedule(procedureName, cbExec, cbComplete).val_; @@ -102,24 +105,21 @@ napi_value SetSecurityLabelSync(napi_env env, napi_callback_info info) UniError(EINVAL).ThrowErr(env, "Invalid path"); return nullptr; } - tie(succ, dataLevel, std::ignore) = NVal(env, funcArg[static_cast(NARG_POS::SECOND)]).ToUTF8String(); if (!succ) { UniError(EINVAL).ThrowErr(env, "Invalid dataLevel"); return nullptr; } - if (DATA_LEVEL.find(dataLevel.get()) == DATA_LEVEL.end()) { UniError(EINVAL).ThrowErr(env, "Invalid Argument of dataLevelEnum"); return nullptr; } - bool ret = SecurityLabel::SetSecurityLabel(path.get(), dataLevel.get()); if (!ret) { return UniError(-1).GetNapiErr(env); + } else { + return NVal::CreateUndefined(env).val_; } - - return NVal::CreateUndefined(env).val_; } napi_value GetSecurityLabel(napi_env env, napi_callback_info info) @@ -150,7 +150,7 @@ napi_value GetSecurityLabel(napi_env env, napi_callback_info info) return { NVal::CreateUTF8String(env, *result) }; }; - static const std::string procedureName = "GetSecurityLabel"; + std::string procedureName = "GetSecurityLabel"; NVal thisVar(env, funcArg.GetThisVar()); if (funcArg.GetArgc() == static_cast(NARG_CNT::ONE)) { return NAsyncWorkPromise(env, thisVar).Schedule(procedureName, cbExec, cbComplete).val_; @@ -178,9 +178,9 @@ napi_value GetSecurityLabelSync(napi_env env, napi_callback_info info) UniError(EINVAL).ThrowErr(env, "Invalid path"); return nullptr; } - - std::string result = SecurityLabel::GetSecurityLabel(path.get()); - return NVal::CreateUTF8String(env, result).val_; + auto result = std::make_shared(); + *result = SecurityLabel::GetSecurityLabel(path.get()); + return NVal::CreateUTF8String(env, *result).val_; } } // namespace ModuleSecurityLabel } // namespace DistributedFS diff --git a/interfaces/kits/js/src/mod_securitylabel/securitylabel_n_exporter.h b/interfaces/kits/js/src/mod_securitylabel/securitylabel_n_exporter.h index 39748659bd7bed3029563304c48650e8228ae6b7..46ca38ce8aefaeabd53d85249daacce01785a31c 100644 --- a/interfaces/kits/js/src/mod_securitylabel/securitylabel_n_exporter.h +++ b/interfaces/kits/js/src/mod_securitylabel/securitylabel_n_exporter.h @@ -18,6 +18,7 @@ #include "../common/napi/n_exporter.h" + namespace OHOS { namespace DistributedFS { namespace ModuleSecurityLabel { diff --git a/interfaces/kits/js/src/mod_securitylabel/securitylabel_napi.cpp b/interfaces/kits/js/src/mod_securitylabel/securitylabel_napi.cpp index 48df4ce3801ca3338819189a99a58588d063525c..f81a892c9e66d056d6119a36bc84f2b088c940e2 100644 --- a/interfaces/kits/js/src/mod_securitylabel/securitylabel_napi.cpp +++ b/interfaces/kits/js/src/mod_securitylabel/securitylabel_napi.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2022 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 @@ -17,6 +17,7 @@ #include "napi/native_node_api.h" #include "securitylabel_n_exporter.h" +#include "securitylabel_napi.h" namespace OHOS { namespace DistributedFS { diff --git a/interfaces/kits/js/src/mod_securitylabel/securitylabel_napi.h b/interfaces/kits/js/src/mod_securitylabel/securitylabel_napi.h new file mode 100644 index 0000000000000000000000000000000000000000..e5ec0b5c7ed68707367f391f0e2340decbfba123 --- /dev/null +++ b/interfaces/kits/js/src/mod_securitylabel/securitylabel_napi.h @@ -0,0 +1,27 @@ +/* + * Copyright (c) 2021-2022 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. + */ + +#ifndef SECURITYLABEL_NAPI_H +#define SECURITYLABEL_NAPI_H + +#include "napi/native_api.h" + +namespace OHOS { +namespace DistributedFS { +namespace ModuleSecurityLabel { +} // namespace ModuleSecurityLabel +} // namespace DistributedFS +} // namespace OHOS +#endif // SECURITYLABEL_NAPI_H \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_statfs/statfs_n_exporter.cpp b/interfaces/kits/js/src/mod_statfs/statfs_n_exporter.cpp index 066e1b601f83f10504cf5daa6d27b40a45b5601e..f19a5a85952c6a25c889a66e150d638cb6012c1b 100644 --- a/interfaces/kits/js/src/mod_statfs/statfs_n_exporter.cpp +++ b/interfaces/kits/js/src/mod_statfs/statfs_n_exporter.cpp @@ -85,12 +85,11 @@ napi_value GetFrSize(napi_env env, napi_callback_info info) return NVal::CreateInt64(env, *resultSize); }; - static const std::string procedureName = "GetFrSize"; + std::string procedureName = "GetFrSize"; NVal thisVar(env, funcArg.GetThisVar()); if (funcArg.GetArgc() == NARG_CNT::ONE) { return NAsyncWorkPromise(env, thisVar).Schedule(procedureName, cbExec, cbComplete).val_; } - NVal cb(env, funcArg[NARG_POS::SECOND]); return NAsyncWorkCallback(env, thisVar, cb).Schedule(procedureName, cbExec, cbComplete).val_; } @@ -154,12 +153,11 @@ napi_value GetBSize(napi_env env, napi_callback_info info) return NVal::CreateInt64(env, *resultSize); }; - static const std::string procedureName = "GetBSize"; + std::string procedureName = "GetBSize"; NVal thisVar(env, funcArg.GetThisVar()); if (funcArg.GetArgc() == NARG_CNT::ONE) { return NAsyncWorkPromise(env, thisVar).Schedule(procedureName, cbExec, cbComplete).val_; } - NVal cb(env, funcArg[NARG_POS::SECOND]); return NAsyncWorkCallback(env, thisVar, cb).Schedule(procedureName, cbExec, cbComplete).val_; } @@ -223,12 +221,11 @@ napi_value GetBAvail(napi_env env, napi_callback_info info) return NVal::CreateInt64(env, *resultSize); }; - static const std::string procedureName = "GetBAvail"; + std::string procedureName = "GetBAvail"; NVal thisVar(env, funcArg.GetThisVar()); if (funcArg.GetArgc() == NARG_CNT::ONE) { return NAsyncWorkPromise(env, thisVar).Schedule(procedureName, cbExec, cbComplete).val_; } - NVal cb(env, funcArg[NARG_POS::SECOND]); return NAsyncWorkCallback(env, thisVar, cb).Schedule(procedureName, cbExec, cbComplete).val_; } @@ -292,12 +289,11 @@ napi_value GetBlocks(napi_env env, napi_callback_info info) return NVal::CreateInt64(env, *resultSize); }; - static const std::string procedureName = "GetBlocks"; + std::string procedureName = "GetBlocks"; NVal thisVar(env, funcArg.GetThisVar()); if (funcArg.GetArgc() == NARG_CNT::ONE) { return NAsyncWorkPromise(env, thisVar).Schedule(procedureName, cbExec, cbComplete).val_; } - NVal cb(env, funcArg[NARG_POS::SECOND]); return NAsyncWorkCallback(env, thisVar, cb).Schedule(procedureName, cbExec, cbComplete).val_; } @@ -361,12 +357,11 @@ napi_value GetBFree(napi_env env, napi_callback_info info) return NVal::CreateInt64(env, *resultSize); }; - static const std::string procedureName = "GetBFree"; + std::string procedureName = "GetBFree"; NVal thisVar(env, funcArg.GetThisVar()); if (funcArg.GetArgc() == NARG_CNT::ONE) { return NAsyncWorkPromise(env, thisVar).Schedule(procedureName, cbExec, cbComplete).val_; } - NVal cb(env, funcArg[NARG_POS::SECOND]); return NAsyncWorkCallback(env, thisVar, cb).Schedule(procedureName, cbExec, cbComplete).val_; } @@ -394,7 +389,7 @@ napi_value GetFreeBytesSync(napi_env env, napi_callback_info info) return nullptr; } unsigned long long freeSize = static_cast(diskInfo.f_bsize) * - static_cast(diskInfo.f_bfree); + static_cast(diskInfo.f_bavail); return NVal::CreateInt64(env, freeSize).val_; } @@ -423,7 +418,7 @@ napi_value GetFreeBytes(napi_env env, napi_callback_info info) return NError(errno); } *resultSize = static_cast(diskInfo.f_bsize) * - static_cast(diskInfo.f_bfree); + static_cast(diskInfo.f_bavail); return NError(ERRNO_NOERR); }; auto cbComplete = [resultSize](napi_env env, NError err) -> NVal { @@ -433,12 +428,11 @@ napi_value GetFreeBytes(napi_env env, napi_callback_info info) return NVal::CreateInt64(env, *resultSize); }; - static const std::string procedureName = "GetFreeBytes"; + std::string procedureName = "GetFreeBytes"; NVal thisVar(env, funcArg.GetThisVar()); if (funcArg.GetArgc() == NARG_CNT::ONE) { return NAsyncWorkPromise(env, thisVar).Schedule(procedureName, cbExec, cbComplete).val_; } - NVal cb(env, funcArg[NARG_POS::SECOND]); return NAsyncWorkCallback(env, thisVar, cb).Schedule(procedureName, cbExec, cbComplete).val_; } @@ -505,12 +499,11 @@ napi_value GetTotalBytes(napi_env env, napi_callback_info info) return { NVal::CreateInt64(env, *resultSize) }; }; - static const std::string procedureName = "GetTotalBytes"; + std::string procedureName = "GetTotalBytes"; NVal thisVar(env, funcArg.GetThisVar()); if (funcArg.GetArgc() == NARG_CNT::ONE) { return NAsyncWorkPromise(env, thisVar).Schedule(procedureName, cbExec, cbComplete).val_; } - NVal cb(env, funcArg[NARG_POS::SECOND]); return NAsyncWorkCallback(env, thisVar, cb).Schedule(procedureName, cbExec, cbComplete).val_; } diff --git a/interfaces/kits/js/src/mod_statfs/statfs_n_exporter.h b/interfaces/kits/js/src/mod_statfs/statfs_n_exporter.h index dd25b1724926781155cab9fd431acff1d11309bf..864183b72d188407757f2e60da0ea56a86042445 100644 --- a/interfaces/kits/js/src/mod_statfs/statfs_n_exporter.h +++ b/interfaces/kits/js/src/mod_statfs/statfs_n_exporter.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2022 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 diff --git a/interfaces/kits/js/src/mod_statfs/statfs_napi.cpp b/interfaces/kits/js/src/mod_statfs/statfs_napi.cpp index 2c0f27dc2674bd5e3b381ae0dd3c5e7f87e14109..bfd958f34ac96b17c4c92e3218fa40ab85ad1e8b 100644 --- a/interfaces/kits/js/src/mod_statfs/statfs_napi.cpp +++ b/interfaces/kits/js/src/mod_statfs/statfs_napi.cpp @@ -14,6 +14,7 @@ */ #include "statfs_n_exporter.h" +#include "statfs_napi.h" namespace OHOS { namespace DistributedFS { diff --git a/interfaces/kits/js/src/mod_statfs/statfs_napi.h b/interfaces/kits/js/src/mod_statfs/statfs_napi.h new file mode 100644 index 0000000000000000000000000000000000000000..fed9e114f326341e10e22f7013743b0830c5ca9a --- /dev/null +++ b/interfaces/kits/js/src/mod_statfs/statfs_napi.h @@ -0,0 +1,27 @@ +/* + * Copyright (c) 2021-2022 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. + */ + +#ifndef STATFS_NAPI_H +#define STATFS_NAPI_H + +#include "filemgmt_libn.h" + +namespace OHOS { +namespace DistributedFS { +namespace ModuleStatfs { +} // namespace ModuleStatfs +} // namespace DistributedFS +} // namespace OHOS +#endif // STATFS_NAPI_H \ No newline at end of file diff --git a/interfaces/kits/napi/BUILD.gn b/interfaces/kits/napi/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..9904e359ab9ec57e2c0a9b5e31595c7cd59c11b0 --- /dev/null +++ b/interfaces/kits/napi/BUILD.gn @@ -0,0 +1,137 @@ +# Copyright (c) 2021-2022 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("//build/ohos.gni") +import("//foundation/filemanagement/file_api/file_api.gni") + +common_src = [ + "common/napi/n_class.cpp", + "common/napi/n_func_arg.cpp", + "common/napi/n_val.cpp", + "common/uni_error.cpp", + "common/ability_helper.cpp", + "common/common_func.cpp", +] + +ohos_shared_library("fileshare") { + relative_install_dir = "module" + + include_dirs = [ + "//third_party/node/src", + "//foundation/arkui/napi/interfaces/kits", + "//third_party/bounds_checking_function/include", + ] + + sources = common_src + sources += [ + "file_share_ability/file_share_exporter.cpp", + "file_share_ability/module.cpp", + ] + + deps = [ + "${ability_runtime_path}/frameworks/native/ability/native:abilitykit_native", + "//foundation/arkui/napi:ace_napi", + "//third_party/bounds_checking_function:libsec_static", + ] + + external_deps = [ + "ability_base:want", + "ability_runtime:ability_manager", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] + subsystem_name = "filemanagement" + part_name = "storage_standard" +} + +ohos_shared_library("devicesmgr") { + relative_install_dir = "module" + + include_dirs = [ + "//third_party/node/src", + "//foundation/arkui/napi/interfaces/kits", + "//third_party/bounds_checking_function/include", + "//utils/system/safwk/native/include", + ] + + sources = common_src + sources += [ + "device_storage_manager/device_sm_exporter.cpp", + "device_storage_manager/module.cpp", + ] + + deps = [ + "${ability_runtime_path}/frameworks/native/ability/native:abilitykit_native", + "//foundation/arkui/napi:ace_napi", + "//third_party/bounds_checking_function:libsec_static", + ] + + external_deps = [ + "ability_base:want", + "ability_runtime:ability_manager", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + "safwk:system_ability_fwk", + "samgr:samgr_proxy", + ] + subsystem_name = "filemanagement" + part_name = "storage_standard" +} + +ohos_shared_library("filepicker") { + relative_install_dir = "module" + + include_dirs = [ + "//third_party/node/src", + "//foundation/arkui/napi/interfaces/kits", + "//third_party/bounds_checking_function/include", + "//utils/system/safwk/native/include", + ] + + sources = common_src + sources += [ + "file_picker_service/file_picker_exporter.cpp", + "file_picker_service/module.cpp", + ] + + deps = [ + "${ability_runtime_path}/frameworks/native/ability/native:abilitykit_native", + "//foundation/arkui/napi:ace_napi", + "//foundation/systemabilitymgr/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", + "//third_party/bounds_checking_function:libsec_static", + ] + + external_deps = [ + "ability_base:want", + "ability_runtime:ability_manager", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + "safwk:system_ability_fwk", + ] + subsystem_name = "filemanagement" + part_name = "storage_standard" +} + +group("build_kits_napi") { + deps = [ + ":devicesmgr", + ":filepicker", + ":fileshare", + ] +} diff --git a/interfaces/kits/napi/common/ability_helper.cpp b/interfaces/kits/napi/common/ability_helper.cpp new file mode 100644 index 0000000000000000000000000000000000000000..515dfb18dad0ebe4a19e42e548eed129a934c84c --- /dev/null +++ b/interfaces/kits/napi/common/ability_helper.cpp @@ -0,0 +1,54 @@ +/* + * Copyright (c) 2021-2022 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. + */ + +#include "ability_helper.h" + +#include "log.h" +#include "napi/n_func_arg.h" +#include "napi/uni_header.h" + +namespace OHOS { +namespace DistributedFS { +using namespace std; +using OHOS::AppExecFwk::Ability; +using OHOS::AppExecFwk::AbilityContext; + +Ability* AbilityHelper::GetJsAbility(napi_env env) +{ + napi_value global = nullptr; + napi_value abilityContext = nullptr; + + napi_status status = napi_get_global(env, &global); + if (status != napi_ok || global == nullptr) { + HILOGE("Cannot get global instance for %{public}d", status); + return nullptr; + } + + status = napi_get_named_property(env, global, "ability", &abilityContext); + if (status != napi_ok || abilityContext == nullptr) { + HILOGE("Cannot get ability context for %{public}d", status); + return nullptr; + } + + Ability *ability = nullptr; + status = napi_get_value_external(env, abilityContext, (void **)&ability); + if (status != napi_ok || ability == nullptr) { + HILOGE("Get ability form property failed for %{public}d", status); + } + + return ability; +} +} // namespace DistributedFS +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/napi/common/ability_helper.h b/interfaces/kits/napi/common/ability_helper.h new file mode 100644 index 0000000000000000000000000000000000000000..41a8bde70e05b47877aaed1d39b8b4c4d3545f8c --- /dev/null +++ b/interfaces/kits/napi/common/ability_helper.h @@ -0,0 +1,29 @@ +/* + * Copyright (c) 2021-2022 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. + */ + +#ifndef INTERFACES_KITS_NAPI_COMMON_ABILITY_HELPER_H +#define INTERFACES_KITS_NAPI_COMMON_ABILITY_HELPER_H + +#include "../common/napi/uni_header.h" +#include "ability.h" + +namespace OHOS { +namespace DistributedFS { +struct AbilityHelper { + static AppExecFwk::Ability *GetJsAbility(napi_env env); +}; +} // namespace DistributedFS +} // namespace OHOS +#endif \ No newline at end of file diff --git a/interfaces/kits/napi/common/common_func.cpp b/interfaces/kits/napi/common/common_func.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f132f6f071cd9dcbc4e3913757bb00f86cf87b47 --- /dev/null +++ b/interfaces/kits/napi/common/common_func.cpp @@ -0,0 +1,57 @@ +/* + * Copyright (c) 2021-2022 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. + */ + +#include "common_func.h" + +#include "napi/n_func_arg.h" + +namespace OHOS { +namespace DistributedFS { +using namespace std; + +tuple CommonFunc::GetCallbackHandles(napi_env env, napi_value object) +{ + bool succ = false; + NVal prop = NVal(env, object); + napi_value successProp, failProp, completeProp; + napi_ref successHandle = nullptr; + napi_ref failHandle = nullptr; + napi_ref completeHandle = nullptr; + string success = "success"; + string fail = "fail"; + string complete = "complete"; + + successProp = prop.GetProp(success).val_; + if (successProp != nullptr) { + napi_create_reference(env, successProp, 1, &successHandle); + succ = true; + } + + failProp = prop.GetProp(fail).val_; + if (succ && failProp != nullptr) { + napi_create_reference(env, failProp, 1, &failHandle); + succ = true; + } + + completeProp = prop.GetProp(complete).val_; + if (succ && completeProp != nullptr) { + napi_create_reference(env, completeProp, 1, &completeHandle); + succ = true; + } + + return { succ, successHandle, failHandle, completeHandle }; +} +} // namespace DistributedFS +} // namespace OHOS diff --git a/interfaces/kits/napi/common/common_func.h b/interfaces/kits/napi/common/common_func.h new file mode 100644 index 0000000000000000000000000000000000000000..2d84bc801fbb586e2340a8e5350ed064b72787fd --- /dev/null +++ b/interfaces/kits/napi/common/common_func.h @@ -0,0 +1,34 @@ +/* + * Copyright (c) 2021-2022 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. + */ + +#ifndef INTERFACES_KITS_NAPI_COMMON_COMMON_FUNC_H +#define INTERFACES_KITS_NAPI_COMMON_COMMON_FUNC_H + +#include +#include "napi/uni_header.h" + +namespace OHOS { +namespace DistributedFS { +const std::string FUNC_PROP_SUCCESS = "success"; +const std::string FUNC_PROP_FAIL = "fail"; +const std::string FUNC_PROP_COMPLETE = "complete"; + +struct CommonFunc { + static std::tuple GetCallbackHandles(napi_env env, + napi_value object); +}; +} // namespace DistributedFS +} // namespace OHOS +#endif \ No newline at end of file diff --git a/interfaces/kits/napi/common/log.h b/interfaces/kits/napi/common/log.h new file mode 100644 index 0000000000000000000000000000000000000000..a5f3bce41f4d0c5e018a75b0c0e60cb81aea2da9 --- /dev/null +++ b/interfaces/kits/napi/common/log.h @@ -0,0 +1,92 @@ +/* + * Copyright (c) 2021-2022 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. + */ + +#ifndef INTERFACES_KITS_NAPI_COMMON_LOG_H +#define INTERFACES_KITS_NAPI_COMMON_LOG_H + +#include +#include +#include + +#ifndef FILE_SUBSYSTEM_DEBUG_LOCAL +#include "hilog/log.h" +#endif + +namespace OHOS { +namespace DistributedFS { +#ifndef FILE_SUBSYSTEM_DEBUG_LOCAL +static constexpr int FILEIO_DOMAIN_ID = 0; +static constexpr OHOS::HiviewDFX::HiLogLabel FILEIO_LABEL = { LOG_CORE, FILEIO_DOMAIN_ID, "file_api" }; + +#ifdef HILOGD +#undef HILOGD +#endif + +#ifdef HILOGF +#undef HILOGF +#endif + +#ifdef HILOGE +#undef HILOGE +#endif + +#ifdef HILOGW +#undef HILOGW +#endif + +#ifdef HILOGI +#undef HILOGI +#endif + +#define HILOGD(fmt, ...) \ + (void)OHOS::HiviewDFX::HiLog::Debug(OHOS::DistributedFS::FILEIO_LABEL, "%{public}s: " fmt, __func__, ##__VA_ARGS__) +#define HILOGI(fmt, ...) \ + (void)OHOS::HiviewDFX::HiLog::Info(OHOS::DistributedFS::FILEIO_LABEL, "%{public}s: " fmt, __func__, ##__VA_ARGS__) +#define HILOGW(fmt, ...) \ + (void)OHOS::HiviewDFX::HiLog::Warn(OHOS::DistributedFS::FILEIO_LABEL, "%{public}s: " fmt, __func__, ##__VA_ARGS__) +#define HILOGE(fmt, ...) \ + (void)OHOS::HiviewDFX::HiLog::Error(OHOS::DistributedFS::FILEIO_LABEL, "%{public}s: " fmt, __func__, ##__VA_ARGS__) +#define HILOGF(fmt, ...) \ + (void)OHOS::HiviewDFX::HiLog::Fatal(OHOS::DistributedFS::FILEIO_LABEL, "%{public}s: " fmt, __func__, ##__VA_ARGS__) + +#else + +#define PCLOG(fmt, ...) \ + do { \ + const std::vector filter = { \ + "{public}", \ + "{private}", \ + }; \ + std::string str____(fmt); \ + for (auto &&pattern : filter) { \ + size_t pos = 0; \ + while (std::string::npos != (pos = str____.find(pattern))) { \ + str____.erase(pos, pattern.length()); \ + } \ + } \ + str____ += "\n"; \ + printf(str____.c_str(), ##__VA_ARGS__); \ + } while (0) \ + +#define HILOGD(fmt, ...) PCLOG("%{public}s: " fmt, __func__, ##__VA_ARGS__) +#define HILOGI(fmt, ...) PCLOG("%{public}s: " fmt, __func__, ##__VA_ARGS__) +#define HILOGW(fmt, ...) PCLOG("%{public}s: " fmt, __func__, ##__VA_ARGS__) +#define HILOGE(fmt, ...) PCLOG("%{public}s: " fmt, __func__, ##__VA_ARGS__) +#define HILOGF(fmt, ...) PCLOG("%{public}s: " fmt, __func__, ##__VA_ARGS__) + +#endif +} // namespace DistributedFS +} // namespace OHOS +#endif \ No newline at end of file diff --git a/interfaces/kits/napi/common/napi/n_class.cpp b/interfaces/kits/napi/common/napi/n_class.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3ac651b11635cef97ee07975257e61a8970f42f9 --- /dev/null +++ b/interfaces/kits/napi/common/napi/n_class.cpp @@ -0,0 +1,100 @@ +/* + * Copyright (c) 2021-2022 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. + */ + +#include "n_class.h" + +#include +#include + +#include "../log.h" + +namespace OHOS { +namespace DistributedFS { +using namespace std; +NClass &NClass::GetInstance() +{ + static NClass nClass; + return nClass; +} + +tuple NClass::DefineClass( + napi_env env, + string className, + napi_callback constructor, + vector &&properties) +{ + napi_value classVal = nullptr; + napi_status stat = napi_define_class(env, + className.c_str(), + className.length(), + constructor, + nullptr, + properties.size(), + properties.data(), + &classVal); + if (stat != napi_ok) { + HILOGE("INNER BUG. Cannot define class %{public}s because of %{public}d", className.c_str(), stat); + } + return { stat == napi_ok, classVal }; +} + +bool NClass::SaveClass(napi_env env, string className, napi_value exClass) +{ + NClass &nClass = NClass::GetInstance(); + lock_guard(nClass.exClassMapLock); + + if (nClass.exClassMap.find(className) != nClass.exClassMap.end()) { + return true; + } + + napi_ref constructor; + napi_status res = napi_create_reference(env, exClass, 1, &constructor); + if (res == napi_ok) { + nClass.exClassMap.insert ({ className, constructor }); + HILOGI("Class %{public}s has been saved", className.c_str()); + } else { + HILOGE("INNER BUG. Cannot ref class constructor %{public}s because of %{public}d", className.c_str(), res); + } + return res == napi_ok; +} + +napi_value NClass::InstantiateClass(napi_env env, const string& className, const vector& args) +{ + NClass &nClass = NClass::GetInstance(); + lock_guard(nClass.exClassMapLock); + + auto it = nClass.exClassMap.find(className); + if (it == nClass.exClassMap.end()) { + HILOGE("Class %{public}s hasn't been saved yet", className.c_str()); + return nullptr; + } + + napi_value cons = nullptr; + napi_status status = napi_get_reference_value(env, it->second, &cons); + if (status != napi_ok) { + HILOGE("INNER BUG. Cannot deref class %{public}s because of %{public}d", className.c_str(), status); + return nullptr; + } + + napi_value instance = nullptr; + status = napi_new_instance(env, cons, args.size(), args.data(), &instance); + if (status != napi_ok) { + HILOGE("INNER BUG. Cannot instantiate the class %{public}s because of %{public}d", className.c_str(), status); + return nullptr; + } + return instance; +} +} // namespace DistributedFS +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/napi/common/napi/n_class.h b/interfaces/kits/napi/common/napi/n_class.h new file mode 100644 index 0000000000000000000000000000000000000000..8ae7a990b5a94aa78732e4066c10ae7e746ffa35 --- /dev/null +++ b/interfaces/kits/napi/common/napi/n_class.h @@ -0,0 +1,81 @@ +/* + * Copyright (c) 2021-2022 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. + */ + +#ifndef INTERFACES_KITS_NAPI_COMMON_NAPI_N_CLASS_H +#define INTERFACES_KITS_NAPI_COMMON_NAPI_N_CLASS_H + +#include "uni_header.h" + +#include +#include +#include + +#include "../log.h" + +namespace OHOS { +namespace DistributedFS { +class NClass final { +public: + NClass(const NClass &) = delete; + NClass &operator = (const NClass &) = delete; + static NClass &GetInstance(); + + static std::tuple DefineClass(napi_env env, + std::string className, + napi_callback constructor, + std::vector &&properties); + static bool SaveClass(napi_env env, std::string className, napi_value exClass); + static napi_value InstantiateClass(napi_env env, const std::string& className, const std::vector& args); + + template static T *GetEntityOf(napi_env env, napi_value objStat) + { + if (!env || !objStat) { + HILOGE("Empty input: env %d, obj %d", env == nullptr, objStat == nullptr); + return nullptr; + } + T *t = nullptr; + napi_status status = napi_unwrap(env, objStat, (void **)&t); + if (status != napi_ok) { + HILOGE("Cannot umwarp for pointer: %d", status); + return nullptr; + } + return t; + } + + template static bool SetEntityFor(napi_env env, napi_value obj, std::unique_ptr entity) + { + napi_status status = napi_wrap( + env, + obj, + entity.get(), + [](napi_env env, void *data, void *hint) { + auto entity = static_cast(data); + delete entity; + }, + nullptr, + nullptr); + entity.release(); + return status == napi_ok; + } + +private: + NClass() = default; + ~NClass() = default; + std::map exClassMap; + std::mutex exClassMapLock; +}; +} // namespace DistributedFS +} // namespace OHOS +#endif \ No newline at end of file diff --git a/interfaces/kits/napi/common/napi/n_exporter.h b/interfaces/kits/napi/common/napi/n_exporter.h new file mode 100644 index 0000000000000000000000000000000000000000..fdd36c07f4d3183b7841342b3d242372f9e026bb --- /dev/null +++ b/interfaces/kits/napi/common/napi/n_exporter.h @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2021-2022 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. + */ + +#ifndef INTERFACES_KITS_NAPI_COMMON_NAPI_N_EXPORTER_H +#define INTERFACES_KITS_NAPI_COMMON_NAPI_N_EXPORTER_H + +#include "uni_header.h" + +#include + +#include "n_val.h" + +namespace OHOS { +namespace DistributedFS { +class NExporter { +public: + NExporter(napi_env env, napi_value exports) : exports_(env, exports) {}; + virtual ~NExporter() = default; + + virtual bool Export() = 0; + virtual std::string GetClassName() = 0; + +protected: + NVal exports_; +}; +} // namespace DistributedFS +} // namespace OHOS +#endif \ No newline at end of file diff --git a/interfaces/kits/napi/common/napi/n_func_arg.cpp b/interfaces/kits/napi/common/napi/n_func_arg.cpp new file mode 100644 index 0000000000000000000000000000000000000000..cfa4e4753b9034a4c0e0bedb7fc53f1c588c08e1 --- /dev/null +++ b/interfaces/kits/napi/common/napi/n_func_arg.cpp @@ -0,0 +1,107 @@ +/* + * Copyright (c) 2021-2022 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. + */ + +#include "n_func_arg.h" + +#include "../log.h" + +namespace OHOS { +namespace DistributedFS { +using namespace std; + +NFuncArg::NFuncArg(napi_env env, napi_callback_info info) : env_(env), info_(info) {} + +NFuncArg::~NFuncArg() {} + +void NFuncArg::SetArgc(size_t argc) +{ + argc_ = argc; +} +void NFuncArg::SetThisVar(napi_value thisVar) +{ + thisVar_ = thisVar; +} + +size_t NFuncArg::GetArgc(void) const +{ + return argc_; +} + +napi_value NFuncArg::GetThisVar(void) const +{ + return thisVar_; +} + +napi_value NFuncArg::GetArg(size_t argPos) const +{ + return (argPos < GetArgc()) ? argv_[argPos] : nullptr; +} + +napi_value NFuncArg::operator[](size_t argPos) const +{ + return GetArg(argPos); +} + +bool NFuncArg::InitArgs(std::function argcChecker) +{ + SetArgc(0); + argv_.reset(); + + size_t argc; + napi_value thisVar; + napi_status status = napi_get_cb_info(env_, info_, &argc, nullptr, &thisVar, nullptr); + if (status != napi_ok) { + HILOGE("Cannot get num of func args for %{public}d", status); + return false; + } + if (argc) { + argv_ = make_unique(argc); + status = napi_get_cb_info(env_, info_, &argc, argv_.get(), &thisVar, nullptr); + if (status != napi_ok) { + HILOGE("Cannot get func args for %{public}d", status); + return false; + } + } + SetArgc(argc); + SetThisVar(thisVar); + + return argcChecker(); +} + +bool NFuncArg::InitArgs(size_t argc) +{ + return InitArgs([argc, this]() { + size_t realArgc = GetArgc(); + if (argc != realArgc) { + HILOGE("Num of args recved eq %zu while expecting %{public}zu", realArgc, argc); + return false; + } + return true; + }); +} + +bool NFuncArg::InitArgs(size_t minArgc, size_t maxArgc) +{ + return InitArgs([minArgc, maxArgc, this]() { + size_t realArgc = GetArgc(); + if (minArgc > realArgc || maxArgc < realArgc) { + HILOGE("Num of args recved eq %zu while expecting %{public}zu ~ %{public}zu", realArgc, minArgc, maxArgc); + return false; + } + return true; + }); +} +} // namespace DistributedFS +} // namespace OHOS diff --git a/interfaces/kits/napi/common/napi/n_func_arg.h b/interfaces/kits/napi/common/napi/n_func_arg.h new file mode 100644 index 0000000000000000000000000000000000000000..17bac2cd73319912d2554e393b1cc5aa19b69aa8 --- /dev/null +++ b/interfaces/kits/napi/common/napi/n_func_arg.h @@ -0,0 +1,69 @@ +/* + * Copyright (c) 2021-2022 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. + */ + +#ifndef INTERFACES_KITS_NAPI_COMMON_NAPI_N_FUNC_ARG_H +#define INTERFACES_KITS_NAPI_COMMON_NAPI_N_FUNC_ARG_H + +#include + +#include "uni_header.h" + +namespace OHOS { +namespace DistributedFS { +enum NARG_CNT { + ZERO = 0, + ONE = 1, + TWO = 2, + THREE = 3, + FOUR = 4, +}; + +enum NARG_POS { + FIRST = 0, + SECOND = 1, + THIRD = 2, + FOURTH = 3, +}; + +class NFuncArg final { +public: + NFuncArg(napi_env env, napi_callback_info info); + virtual ~NFuncArg(); + + bool InitArgs(size_t argc); + bool InitArgs(size_t minArgc, size_t maxArgc); + + size_t GetArgc() const; + napi_value GetThisVar() const; + + napi_value operator[](size_t idx) const; + napi_value GetArg(size_t argPos) const; + +private: + napi_env env_ = nullptr; + napi_callback_info info_ = nullptr; + + size_t argc_ = 0; + std::unique_ptr argv_ = { nullptr }; + napi_value thisVar_ = nullptr; + + bool InitArgs(std::function argcChecker); + + void SetArgc(size_t argc); + void SetThisVar(napi_value thisVar); +}; +} // namespace DistributedFS +} // namespace OHOS +#endif \ No newline at end of file diff --git a/interfaces/kits/napi/common/napi/n_val.cpp b/interfaces/kits/napi/common/napi/n_val.cpp new file mode 100644 index 0000000000000000000000000000000000000000..010673fa342e207d5cac97d0720781e698e61eca --- /dev/null +++ b/interfaces/kits/napi/common/napi/n_val.cpp @@ -0,0 +1,280 @@ +/* + * Copyright (c) 2021-2022 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. + */ + +#include "n_val.h" + +#include +#include + +#include "../log.h" +#include "../uni_error.h" + +namespace OHOS { +namespace DistributedFS { +using namespace std; + +NVal::NVal(napi_env nEnv, napi_value nVal = nullptr) : env_(nEnv), val_(nVal) {} + +NVal::operator bool() const +{ + return env_ && val_; +} + +bool NVal::TypeIs(napi_valuetype expType) const +{ + if (!*this) { + return false; + } + + napi_valuetype valueType; + napi_typeof(env_, val_, &valueType); + + if (expType != valueType) { + return false; + } + return true; +} + +tuple, size_t> NVal::ToUTF8String() const +{ + size_t strLen = 0; + napi_status status = napi_get_value_string_utf8(env_, val_, nullptr, -1, &strLen); + if (status != napi_ok) { + return { false, nullptr, 0 }; + } + + size_t bufLen = strLen + 1; + unique_ptr str = make_unique(bufLen); + status = napi_get_value_string_utf8(env_, val_, str.get(), bufLen, &strLen); + return make_tuple(status == napi_ok, move(str), strLen); +} + +tuple, size_t> NVal::ToUTF16String() const +{ +#ifdef FILE_SUBSYSTEM_DEBUG_LOCAL + size_t strLen = 0; + napi_status status = napi_get_value_string_utf16(env_, val_, nullptr, -1, &strLen); + if (status != napi_ok) { + return { false, nullptr, 0 }; + } + + auto str = make_unique(++strLen); + status = napi_get_value_string_utf16(env_, val_, str.get(), strLen, nullptr); + if (status != napi_ok) { + return { false, nullptr, 0 }; + } + + strLen = reinterpret_cast(str.get() + strLen) - reinterpret_cast(str.get()); + auto strRet = unique_ptr(reinterpret_cast(str.release())); + return { true, move(strRet), strLen }; +#else + // Note that quickjs doesn't support utf16 + return ToUTF8String(); +#endif +} + +tuple NVal::ToPointer() const +{ + void *res = nullptr; + napi_status status = napi_get_value_external(env_, val_, &res); + return make_tuple(status == napi_ok, res); +} + +tuple NVal::ToBool() const +{ + bool flag = false; + napi_status status = napi_get_value_bool(env_, val_, &flag); + return make_tuple(status == napi_ok, flag); +} + +tuple NVal::ToInt32() const +{ + int32_t res = 0; + napi_status status = napi_get_value_int32(env_, val_, &res); + return make_tuple(status == napi_ok, res); +} + +tuple NVal::ToInt64() const +{ + int64_t res = 0; + napi_status status = napi_get_value_int64(env_, val_, &res); + return make_tuple(status == napi_ok, res); +} + +tuple NVal::ToArraybuffer() const +{ + void *buf = nullptr; + size_t bufLen = 0; + bool status = napi_get_arraybuffer_info(env_, val_, &buf, &bufLen); + return make_tuple(status == napi_ok, buf, bufLen); +} + +tuple NVal::ToTypedArray() const +{ + napi_typedarray_type type; + napi_value inArrayBuffer = nullptr; + size_t byteOffset; + size_t length; + void *data = nullptr; + napi_status status = + napi_get_typedarray_info(env_, val_, &type, &length, (void **)&data, &inArrayBuffer, &byteOffset); + return make_tuple(status == napi_ok, data, length); +} + +bool NVal::HasProp(string propName) const +{ + bool res = false; + + if (!env_ || !val_ || !TypeIs(napi_object)) + return false; + napi_status status = napi_has_named_property(env_, val_, propName.c_str(), &res); + return (status == napi_ok) && res; +} + +NVal NVal::GetProp(string propName) const +{ + if (!HasProp(propName)) { + return { env_, nullptr }; + } + napi_value prop = nullptr; + napi_status status = napi_get_named_property(env_, val_, propName.c_str(), &prop); + if (status != napi_ok) { + return { env_, nullptr }; + } + return NVal(env_, prop); +} + +bool NVal::AddProp(vector &&propVec) const +{ + if (!TypeIs(napi_valuetype::napi_object)) { + HILOGE("INNER BUG. Prop should only be added to objects"); + return false; + } + napi_status status = napi_define_properties(env_, val_, propVec.size(), propVec.data()); + if (status != napi_ok) { + HILOGE("INNER BUG. Cannot define properties because of %{public}d", status); + return false; + } + return true; +} + +bool NVal::AddProp(string propName, napi_value val) const +{ + if (!TypeIs(napi_valuetype::napi_object) || HasProp(propName)) { + HILOGE("INNER BUG. Prop should only be added to objects"); + return false; + } + + napi_status status = napi_set_named_property(env_, val_, propName.c_str(), val); + if (status != napi_ok) { + HILOGE("INNER BUG. Cannot set named property because of %{public}d", status); + return false; + } + return true; +} + +NVal NVal::CreateUndefined(napi_env env) +{ + napi_value res = nullptr; + napi_get_undefined(env, &res); + return { env, res }; +} + +NVal NVal::CreateInt64(napi_env env, int64_t val) +{ + napi_value res = nullptr; + napi_create_int64(env, val, &res); + return { env, res }; +} + +NVal NVal::CreateInt32(napi_env env, int32_t val) +{ + napi_value res = nullptr; + napi_create_int32(env, val, &res); + return { env, res }; +} + +NVal NVal::CreateObject(napi_env env) +{ + napi_value res = nullptr; + napi_create_object(env, &res); + return { env, res }; +} + +NVal NVal::CreateBool(napi_env env, bool val) +{ + napi_value res = nullptr; + napi_get_boolean(env, val, &res); + return { env, res }; +} + +NVal NVal::CreateUTF8String(napi_env env, std::string str) +{ + napi_value res = nullptr; + napi_create_string_utf8(env, str.c_str(), str.length(), &res); + return { env, res }; +} + +NVal NVal::CreateUint8Array(napi_env env, void *buf, size_t bufLen) +{ + napi_value outputBuffer = nullptr; + napi_create_external_arraybuffer( + env, + buf, + bufLen, + [](napi_env env, void *finalize_data, void *finalize_hint) { free(finalize_data); }, + NULL, + &outputBuffer); + napi_value outputArray = nullptr; + napi_create_typedarray(env, napi_uint8_array, bufLen, outputBuffer, 0, &outputArray); + return { env, outputArray }; +} + +napi_property_descriptor NVal::DeclareNapiProperty(const char *name, napi_value val) +{ + return { (name), nullptr, nullptr, nullptr, nullptr, val, napi_default, nullptr }; +} + +napi_property_descriptor NVal::DeclareNapiStaticProperty(const char *name, napi_value val) +{ + return { (name), nullptr, nullptr, nullptr, nullptr, val, napi_static, nullptr }; +} + +napi_property_descriptor NVal::DeclareNapiFunction(const char *name, napi_callback func) +{ + return { (name), nullptr, (func), nullptr, nullptr, nullptr, napi_default, nullptr }; +} + +napi_property_descriptor NVal::DeclareNapiStaticFunction(const char *name, napi_callback func) +{ + return { (name), nullptr, (func), nullptr, nullptr, nullptr, napi_static, nullptr }; +} + +napi_property_descriptor NVal::DeclareNapiGetter(const char *name, napi_callback getter) +{ + return { (name), nullptr, nullptr, (getter), nullptr, nullptr, napi_default, nullptr }; +} + +napi_property_descriptor NVal::DeclareNapiSetter(const char *name, napi_callback setter) +{ + return { (name), nullptr, nullptr, nullptr, (setter), nullptr, napi_default, nullptr }; +} + +napi_property_descriptor NVal::DeclareNapiGetterSetter(const char *name, napi_callback getter, napi_callback setter) +{ + return { (name), nullptr, nullptr, (getter), (setter), nullptr, napi_default, nullptr }; +} +} // namespace DistributedFS +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/napi/common/napi/n_val.h b/interfaces/kits/napi/common/napi/n_val.h new file mode 100644 index 0000000000000000000000000000000000000000..654c382f98ba236f8273402c9e38d0dccf7a04d9 --- /dev/null +++ b/interfaces/kits/napi/common/napi/n_val.h @@ -0,0 +1,79 @@ +/* + * Copyright (c) 2021-2022 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. + */ + +#ifndef INTERFACES_KITS_NAPI_COMMON_NAPI_N_VAL_H +#define INTERFACES_KITS_NAPI_COMMON_NAPI_N_VAL_H + +#include +#include + +#include "uni_header.h" + +namespace OHOS { +namespace DistributedFS { +class NVal final { +public: + NVal() = default; + NVal(napi_env nEnv, napi_value nVal); + NVal(const NVal &) = default; + NVal &operator = (const NVal &) = default; + virtual ~NVal() = default; + + // NOTE! env_ and val_ is LIKELY to be null + napi_env env_ = nullptr; + napi_value val_ = nullptr; + + explicit operator bool() const; + bool TypeIs(napi_valuetype expType) const; + + /* SHOULD ONLY BE USED FOR EXPECTED TYPE */ + std::tuple, size_t> ToUTF8String() const; + std::tuple, size_t> ToUTF16String() const; + std::tuple ToPointer() const; + std::tuple ToBool() const; + std::tuple ToInt32() const; + std::tuple ToInt64() const; + std::tuple ToArraybuffer() const; + std::tuple ToTypedArray() const; + + /* Static helpers to create js objects */ + static NVal CreateUndefined(napi_env env); + static NVal CreateInt64(napi_env env, int64_t val); + static NVal CreateInt32(napi_env env, int32_t val); + static NVal CreateObject(napi_env env); + static NVal CreateBool(napi_env env, bool val); + static NVal CreateUTF8String(napi_env env, std::string str); + static NVal CreateUint8Array(napi_env env, void *buf, size_t bufLen); + + /* SHOULD ONLY BE USED FOR OBJECT */ + bool HasProp(std::string propName) const; + NVal GetProp(std::string propName) const; + bool AddProp(std::vector &&propVec) const; + bool AddProp(std::string propName, napi_value nVal) const; + + /* Static helpers to create prop of js objects */ + static napi_property_descriptor DeclareNapiProperty(const char *name, napi_value val); + static napi_property_descriptor DeclareNapiStaticProperty(const char *name, napi_value val); + static napi_property_descriptor DeclareNapiFunction(const char *name, napi_callback func); + static napi_property_descriptor DeclareNapiStaticFunction(const char *name, napi_callback func); + static napi_property_descriptor DeclareNapiGetter(const char *name, napi_callback getter); + static napi_property_descriptor DeclareNapiSetter(const char *name, napi_callback setter); + static inline napi_property_descriptor DeclareNapiGetterSetter(const char *name, + napi_callback getter, + napi_callback setter); +}; +} // namespace DistributedFS +} // namespace OHOS +#endif \ No newline at end of file diff --git a/interfaces/kits/napi/common/napi/uni_header.h b/interfaces/kits/napi/common/napi/uni_header.h new file mode 100644 index 0000000000000000000000000000000000000000..c0f1a6d685ac461068d21ddfbd326d2a7e62348c --- /dev/null +++ b/interfaces/kits/napi/common/napi/uni_header.h @@ -0,0 +1,25 @@ +/* + * Copyright (c) 2021-2022 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. + */ + +#ifndef INTERFACES_KITS_NAPI_COMMON_NAPI_UNI_HEADER_H +#define INTERFACES_KITS_NAPI_COMMON_NAPI_UNI_HEADER_H + +#ifdef FILE_SUBSYSTEM_DEBUG_LOCAL +#include +#else +#include "napi/native_api.h" +#include "napi/native_node_api.h" +#endif +#endif \ No newline at end of file diff --git a/interfaces/kits/napi/common/uni_error.cpp b/interfaces/kits/napi/common/uni_error.cpp new file mode 100644 index 0000000000000000000000000000000000000000..bd63210cdf6f30280e2af08c628c3acebb54cfa9 --- /dev/null +++ b/interfaces/kits/napi/common/uni_error.cpp @@ -0,0 +1,118 @@ +/* + * Copyright (c) 2021-2022 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. + */ + +#include "uni_error.h" + +#include +#include + +#include "log.h" +#include "napi/n_val.h" + +namespace OHOS { +namespace DistributedFS { +using namespace std; + +UniError::UniError() {} + +UniError::UniError(ELegacy eLegacy) : errno_(eLegacy), codingSystem_(ERR_CODE_SYSTEM_LEGACY) {} + +UniError::UniError(int ePosix) : errno_(ePosix), codingSystem_(ERR_CODE_SYSTEM_POSIX) {} + +UniError::operator bool() const +{ + return errno_ != ERRNO_NOERR; +} + +int UniError::GetErrno(ErrCodeSystem cs) +{ + if (errno_ == ERRNO_NOERR) { + return ERRNO_NOERR; + } + if (cs == codingSystem_) { + return errno_; + } + + if (cs == ERR_CODE_SYSTEM_POSIX) { + // Note that we should support more codes here + return EINVAL; + } + + // Note that this shall be done properly + return ELEGACY_INVAL; +} + +void UniError::SetErrno(ELegacy eLegacy) +{ + errno_ = eLegacy; + codingSystem_ = ERR_CODE_SYSTEM_LEGACY; +} + +void UniError::SetErrno(int ePosix) +{ + errno_ = ePosix; + codingSystem_ = ERR_CODE_SYSTEM_POSIX; +} + +std::string UniError::GetDefaultErrstr() +{ + if (codingSystem_ != ERR_CODE_SYSTEM_POSIX && codingSystem_ != ERR_CODE_SYSTEM_LEGACY) { + return "BUG: Curious coding system"; + } + return strerror(GetErrno(ERR_CODE_SYSTEM_POSIX)); +} + +napi_value UniError::GetNapiErr(napi_env env) +{ + return GetNapiErr(env, GetDefaultErrstr()); +} + +napi_value UniError::GetNapiErr(napi_env env, string errMsg) +{ + napi_value code = NVal::CreateUTF8String(env, to_string(GetErrno(codingSystem_))).val_; + napi_value msg = NVal::CreateUTF8String(env, errMsg).val_; + + napi_value res = nullptr; + napi_status createRes = napi_create_error(env, code, msg, &res); + if (createRes) { + HILOGE("Failed to create an exception, msg = %{public}s", errMsg.c_str()); + } + return res; +} + +void UniError::ThrowErr(napi_env env) +{ + string msg = GetDefaultErrstr(); + napi_value tmp = nullptr; + napi_get_and_clear_last_exception(env, &tmp); + // Note that ace engine cannot throw errors created by napi_create_error so far + napi_status throwStatus = napi_throw_error(env, nullptr, msg.c_str()); + if (throwStatus != napi_ok) { + HILOGE("Failed to throw an exception, %{public}d, code = %{public}s", throwStatus, msg.c_str()); + } +} + +void UniError::ThrowErr(napi_env env, string errMsg) +{ + napi_value tmp = nullptr; + napi_get_and_clear_last_exception(env, &tmp); + // Note that ace engine cannot throw errors created by napi_create_error so far + napi_status throwStatus = napi_throw_error(env, nullptr, errMsg.c_str()); + if (throwStatus != napi_ok) { + HILOGE("Failed to throw an exception, %{public}d, code = %{public}s", throwStatus, errMsg.c_str()); + } +} +} // namespace DistributedFS +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/napi/common/uni_error.h b/interfaces/kits/napi/common/uni_error.h new file mode 100644 index 0000000000000000000000000000000000000000..ae66424fb29cddac78fe11ab4fb5fa20113ba78e --- /dev/null +++ b/interfaces/kits/napi/common/uni_error.h @@ -0,0 +1,60 @@ +/* + * Copyright (c) 2021-2022 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. + */ + +#ifndef INTERFACES_KITS_NAPI_COMMON_UNI_ERROR_H +#define INTERFACES_KITS_NAPI_COMMON_UNI_ERROR_H + +namespace OHOS { +namespace DistributedFS { +enum ELegacy { + ELEGACY_INVAL = 202, + ELEGACY_IO = 300, + ELEGACY_NOENT = 301, +}; + +enum ErrCodeSystem { + ERR_CODE_SYSTEM_LEGACY, + ERR_CODE_SYSTEM_POSIX, +}; + +class UniError { +public: + UniError(); + explicit UniError(ELegacy eLegacy); + explicit UniError(int ePosix); + UniError(const UniError &) = default; + ~UniError() = default; + + UniError &operator = (const UniError &) = default; + + explicit operator bool() const; + + void SetErrno(ELegacy eLegacy); + void SetErrno(int ePosix); + int GetErrno(ErrCodeSystem cs); + + std::string GetDefaultErrstr(); + napi_value GetNapiErr(napi_env env); + napi_value GetNapiErr(napi_env env, std::string errMsg); + void ThrowErr(napi_env env); + void ThrowErr(napi_env env, std::string errMsg); + +private: + int errno_ = ERRNO_NOERR; + ErrCodeSystem codingSystem_ = ERR_CODE_SYSTEM_POSIX; +}; +} // namespace DistributedFS +} // namespace OHOS +#endif \ No newline at end of file diff --git a/interfaces/kits/napi/device_storage_manager/device_sm_exporter.cpp b/interfaces/kits/napi/device_storage_manager/device_sm_exporter.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3d26d37e97d74823e9b92d42e5c996ee14a41d5e --- /dev/null +++ b/interfaces/kits/napi/device_storage_manager/device_sm_exporter.cpp @@ -0,0 +1,1017 @@ +/* + * Copyright (c) 2021-2022 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. + */ + +#include "device_sm_exporter.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "../common/ability_helper.h" +#include "../common/common_func.h" +#include "../common/napi/n_class.h" +#include "../common/napi/n_func_arg.h" +#include "../common/napi/n_val.h" +#include "../common/uni_error.h" +#include "device_storage_manager.h" + +using Uri = OHOS::Uri; +using namespace std; +namespace OHOS { +namespace DistributedFS { +namespace ModuleDSMExpoter { +enum COMMON_NUM { + ZERO = 0, + ONE = 1, + TWO = 2, + THREE = 3, +}; +const int ERROR = 300; +const int NULL_ERROR = 202; + +static void ForeachVomInfos(std::vector> &infos, + napi_env &env, + napi_value &getvolumenapi, + int32_t &userId) +{ + int32_t i = 0; + + for (auto vomInfo : infos) { + NVal objv = NVal::CreateObject(env); + objv.AddProp("mId", NVal::CreateUTF8String(env, vomInfo->GetId()).val_); + objv.AddProp("mDiskId", NVal::CreateUTF8String(env, vomInfo->GetDiskId()).val_); + objv.AddProp("mPartGuid", NVal::CreateUTF8String(env, vomInfo->GetPartGuid()).val_); + objv.AddProp("mFsUuid", NVal::CreateUTF8String(env, vomInfo->GetFsUuid()).val_); + objv.AddProp("mType", NVal::CreateInt64(env, vomInfo->GetType()).val_); + objv.AddProp("mMountFlags", NVal::CreateInt64(env, vomInfo->GetMountFlags()).val_); + objv.AddProp("mMountUserId", NVal::CreateInt64(env, vomInfo->GetMountUserId()).val_); + objv.AddProp("mState", NVal::CreateInt64(env, vomInfo->GetState()).val_); + objv.AddProp("mPath", NVal::CreateUTF8String(env, vomInfo->GetPath()).val_); + objv.AddProp("mInternalPath", NVal::CreateUTF8String(env, vomInfo->GetInternalPath()).val_); + objv.AddProp("mFsLabel", NVal::CreateUTF8String(env, vomInfo->GetFsLabel()).val_); + objv.AddProp("IsEmulated", NVal::CreateBool(env, vomInfo->IsEmulated()).val_); + objv.AddProp("IsPrimaryEmulatedForUser", + NVal::CreateBool(env, vomInfo->IsPrimaryEmulatedForUser(userId)).val_); + objv.AddProp("IsRemovable", NVal::CreateBool(env, vomInfo->IsRemovable(userId)).val_); + objv.AddProp("IsPrimary", NVal::CreateBool(env, vomInfo->IsPrimary()).val_); + objv.AddProp("Description", NVal::CreateUTF8String(env, vomInfo->GetDescription()).val_); + objv.AddProp("IsVisibleForUser", NVal::CreateBool(env, vomInfo->IsVisibleForUser(userId)).val_); + + napi_set_property(env, getvolumenapi, NVal::CreateInt32(env, i).val_, objv.val_); + i++; + } +} + +static void ForeachDsmInfos(std::vector> &infos, + napi_env &env, + napi_value &diaknapi) +{ + int32_t i = 0; + + for (auto dsmInfo : infos) { + NVal objt = NVal::CreateObject(env); + objt.AddProp("mId", NVal::CreateUTF8String(env, dsmInfo->GetId()).val_); + objt.AddProp("mSysPath", NVal::CreateUTF8String(env, dsmInfo->GetSysPath()).val_); + objt.AddProp("mSize", NVal::CreateInt64(env, dsmInfo->GetSize()).val_); + objt.AddProp("mLabel", NVal::CreateUTF8String(env, dsmInfo->GetLabel()).val_); + objt.AddProp("mFlags", NVal::CreateInt64(env, dsmInfo->GetFlags()).val_); + objt.AddProp("IsUsb", NVal::CreateBool(env, dsmInfo->IsUsb()).val_); + objt.AddProp("IsSd", NVal::CreateBool(env, dsmInfo->IsSd()).val_); + objt.AddProp("IsAdoptable", NVal::CreateBool(env, dsmInfo->IsAdoptable()).val_); + objt.AddProp("Description", NVal::CreateUTF8String(env, dsmInfo->GetDescription()).val_); + + napi_set_property(env, diaknapi, NVal::CreateInt32(env, i).val_, objt.val_); + i++; + } +} + +void CallBackSuccess(napi_env env, napi_ref successFuncRef, int32_t count, napi_value obj) +{ + napi_value results = nullptr; + napi_value successFunc = nullptr; + napi_value global = nullptr; + napi_get_global(env, &global); + napi_get_reference_value(env, successFuncRef, &successFunc); + if (successFunc == nullptr) { + return; + } + napi_call_function(env, global, successFunc, count, &obj, &results); +} +void CallBackError(napi_env env, napi_ref failFuncRef, string errorProp, int errorCode) +{ + napi_value argvFail[2] = { 0 }; + napi_value results = nullptr; + napi_value failFunc = nullptr; + napi_value global = nullptr; + napi_get_global(env, &global); + argvFail[0] = NVal::CreateUTF8String(env, errorProp).val_; + argvFail[1] = NVal::CreateInt32(env, errorCode).val_; + napi_get_reference_value(env, failFuncRef, &failFunc); + if (failFunc == nullptr) { + return; + } + napi_call_function(env, global, failFunc, COMMON_NUM::TWO, argvFail, &results); +} +void CallComplete(napi_env env, napi_ref completeFuncRef) +{ + napi_value completeFunc = nullptr; + napi_value results = nullptr; + napi_value global = nullptr; + napi_get_global(env, &global); + napi_get_reference_value(env, completeFuncRef, &completeFunc); + if (completeFunc == nullptr) { + return; + } + napi_call_function(env, global, completeFunc, COMMON_NUM::ZERO, nullptr, &results); +} + +std::shared_ptr dsm = DelayedSingleton::GetInstance(); +int32_t userId; +napi_value VolumesToNapi(napi_env env, std::vector> infos) +{ + napi_value getvolumenapi; + napi_create_array(env, &getvolumenapi); + ForeachVomInfos(infos, env, getvolumenapi, userId); + return getvolumenapi; +} + +void PriVolToEmuVol(napi_env env, NVal a, std::shared_ptr &emuVol) +{ + bool succ = false; + + unique_ptr id = nullptr; + tie(succ, id, ignore) = a.GetProp("mId").ToUTF8String(); + string cId = (id == nullptr) ? "" : id.get(); + emuVol->SetId(cId); + + unique_ptr diskId = nullptr; + tie(succ, diskId, ignore) = a.GetProp("mDiskId").ToUTF8String(); + emuVol->SetDiskId((diskId == nullptr) ? "" : diskId.get()); + + int64_t type = 0; + tie(succ, type) = a.GetProp("mType").ToInt64(); + emuVol->SetType(type); + + unique_ptr partGuid = nullptr; + tie(succ, partGuid, ignore) = a.GetProp("mPartGuid").ToUTF8String(); + emuVol->SetPartGuid((partGuid == nullptr) ? "" : partGuid.get()); + + int64_t mountFlags = 0; + tie(succ, mountFlags) = a.GetProp("mMountFlags").ToInt64(); + emuVol->SetMountFlags(mountFlags); + + int64_t mountUserId = 0; + tie(succ, mountUserId) = a.GetProp("mMountUserId").ToInt64(); + emuVol->SetMountUserId(mountUserId); + + unique_ptr path = nullptr; + tie(succ, path, ignore) = a.GetProp("mPath").ToUTF8String(); + emuVol->SetPath((path == nullptr) ? "" : path.get()); + + unique_ptr internalPath = nullptr; + tie(succ, internalPath, ignore) = a.GetProp("mInternalPath").ToUTF8String(); + emuVol->SetInternalPath((internalPath == nullptr) ? "" : internalPath.get()); + + unique_ptr fsType = nullptr; + tie(succ, fsType, ignore) = a.GetProp("mFsType").ToUTF8String(); + emuVol->SetFsUuid((fsType == nullptr) ? "" : fsType.get()); + + unique_ptr fsUuid = nullptr; + tie(succ, fsUuid, ignore) = a.GetProp("mFsUuid").ToUTF8String(); + emuVol->SetFsUuid((fsUuid == nullptr) ? "" : fsUuid.get()); + + unique_ptr fsLabel = nullptr; + tie(succ, fsLabel, ignore) = a.GetProp("mFsLabel").ToUTF8String(); + string tId = (fsLabel == nullptr) ? "" : fsLabel.get(); + emuVol->SetFsLabel(tId); + + int64_t state = 0; + tie(succ, state) = a.GetProp("mState").ToInt64(); + emuVol->SetState(state); +} + +void EmuVolToPriVol(napi_env env, NVal a, std::shared_ptr &priVol) +{ + bool succ = false; + + unique_ptr id = nullptr; + tie(succ, id, ignore) = a.GetProp("mId").ToUTF8String(); + string cId = (id == nullptr) ? "" : id.get(); + priVol->SetId(cId); + + unique_ptr diskId = nullptr; + tie(succ, diskId, ignore) = a.GetProp("mDiskId").ToUTF8String(); + priVol->SetDiskId((diskId == nullptr) ? "" : diskId.get()); + + int64_t type = 0; + tie(succ, type) = a.GetProp("mType").ToInt64(); + priVol->SetType(type); + + unique_ptr partGuid = nullptr; + tie(succ, partGuid, ignore) = a.GetProp("mPartGuid").ToUTF8String(); + priVol->SetPartGuid((partGuid == nullptr) ? "" : partGuid.get()); + + int64_t mountFlags = 0; + tie(succ, mountFlags) = a.GetProp("mMountFlags").ToInt64(); + priVol->SetMountFlags(mountFlags); + + int64_t mountUserId = 0; + tie(succ, mountUserId) = a.GetProp("mMountUserId").ToInt64(); + priVol->SetMountUserId(mountUserId); + + unique_ptr path = nullptr; + tie(succ, path, ignore) = a.GetProp("mPath").ToUTF8String(); + priVol->SetPath((path == nullptr) ? "" : path.get()); + + unique_ptr internalPath = nullptr; + tie(succ, internalPath, ignore) = a.GetProp("mInternalPath").ToUTF8String(); + priVol->SetInternalPath((internalPath == nullptr) ? "" : internalPath.get()); + + unique_ptr fsType = nullptr; + tie(succ, fsType, ignore) = a.GetProp("mFsType").ToUTF8String(); + priVol->SetFsUuid((fsType == nullptr) ? "" : fsType.get()); + + unique_ptr fsUuid = nullptr; + tie(succ, fsUuid, ignore) = a.GetProp("mFsUuid").ToUTF8String(); + priVol->SetFsUuid((fsUuid == nullptr) ? "" : fsUuid.get()); + + unique_ptr fsLabel = nullptr; + tie(succ, fsLabel, ignore) = a.GetProp("mFsLabel").ToUTF8String(); + string tId = (fsLabel == nullptr) ? "" : fsLabel.get(); + priVol->SetFsLabel(tId); + + int64_t state = 0; + tie(succ, state) = a.GetProp("mState").ToInt64(); + priVol->SetState(state); +} + +void VolToDesCription(napi_env env, NVal a, std::shared_ptr &vol) +{ + bool succ = false; + + unique_ptr id = nullptr; + tie(succ, id, ignore) = a.GetProp("mId").ToUTF8String(); + string cId = (id == nullptr) ? "" : id.get(); + vol->SetId(cId); + + unique_ptr diskId = nullptr; + tie(succ, diskId, ignore) = a.GetProp("mDiskId").ToUTF8String(); + vol->SetDiskId((diskId == nullptr) ? "" : diskId.get()); + + int64_t type = 0; + tie(succ, type) = a.GetProp("mType").ToInt64(); + vol->SetType(type); + + unique_ptr partGuid = nullptr; + tie(succ, partGuid, ignore) = a.GetProp("mPartGuid").ToUTF8String(); + vol->SetPartGuid((partGuid == nullptr) ? "" : partGuid.get()); + + int64_t mountFlags = 0; + tie(succ, mountFlags) = a.GetProp("mMountFlags").ToInt64(); + vol->SetMountFlags(mountFlags); + + int64_t mountUserId = 0; + tie(succ, mountUserId) = a.GetProp("mMountUserId").ToInt64(); + vol->SetMountUserId(mountUserId); + + unique_ptr path = nullptr; + tie(succ, path, ignore) = a.GetProp("mPath").ToUTF8String(); + vol->SetPath((path == nullptr) ? "" : path.get()); + + unique_ptr internalPath = nullptr; + tie(succ, internalPath, ignore) = a.GetProp("mInternalPath").ToUTF8String(); + vol->SetInternalPath((internalPath == nullptr) ? "" : internalPath.get()); + + unique_ptr fsType = nullptr; + tie(succ, fsType, ignore) = a.GetProp("mFsType").ToUTF8String(); + vol->SetFsUuid((fsType == nullptr) ? "" : fsType.get()); + + unique_ptr fsUuid = nullptr; + tie(succ, fsUuid, ignore) = a.GetProp("mFsUuid").ToUTF8String(); + vol->SetFsUuid((fsUuid == nullptr) ? "" : fsUuid.get()); + + unique_ptr fsLabel = nullptr; + tie(succ, fsLabel, ignore) = a.GetProp("mFsLabel").ToUTF8String(); + string tId = (fsLabel == nullptr) ? "" : fsLabel.get(); + vol->SetFsLabel(tId); + + int64_t state = 0; + tie(succ, state) = a.GetProp("mState").ToInt64(); + vol->SetState(state); +} + +napi_value DeviceSMExporter::Mount(napi_env env, napi_callback_info info) +{ + NFuncArg funcArg(env, info); + if (!funcArg.InitArgs(NARG_CNT::ONE)) { + UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); + return nullptr; + } + bool succ = false; + napi_ref napiSuccFun, napiCompFun, napiFailFun; + tie(succ, napiSuccFun, napiFailFun, napiCompFun) = + CommonFunc::GetCallbackHandles(env, funcArg[NARG_POS::FIRST]); + + unique_ptr deviceId = nullptr; + tie(succ, deviceId, ignore) = NVal(env, funcArg[NARG_POS::FIRST]).GetProp("volId").ToUTF8String(); + + std::string mvId = (deviceId == nullptr) ? "" : deviceId.get(); + if (mvId == "") { + CallBackError(env, napiFailFun, "Mount incoming parameter is null", NULL_ERROR); + CallComplete(env, napiCompFun); + napi_delete_reference(env, napiSuccFun); + napi_delete_reference(env, napiFailFun); + napi_delete_reference(env, napiCompFun); + return nullptr; + } + + bool s = dsm->Mount(mvId); + if (s) { + CallBackSuccess(env, napiSuccFun, COMMON_NUM::ZERO, nullptr); + } else { + CallBackError(env, napiFailFun, "Mount return value error", ERROR); + } + CallComplete(env, napiCompFun); + napi_delete_reference(env, napiSuccFun); + napi_delete_reference(env, napiFailFun); + napi_delete_reference(env, napiCompFun); + return NVal::CreateUndefined(env).val_; +} + +napi_value DeviceSMExporter::UnMount(napi_env env, napi_callback_info info) +{ + NFuncArg funcArg(env, info); + if (!funcArg.InitArgs(NARG_CNT::ONE)) { + UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); + return nullptr; + } + bool succ = false; + napi_ref napiSuccFun, napiCompFun, napiFailFun; + tie(succ, napiSuccFun, napiFailFun, napiCompFun) = + CommonFunc::GetCallbackHandles(env, funcArg[NARG_POS::FIRST]); + + unique_ptr deviceId = nullptr; + tie(succ, deviceId, ignore) = NVal(env, funcArg[NARG_POS::FIRST]).GetProp("volId").ToUTF8String(); + + std::string mvId = (deviceId == nullptr) ? "" : deviceId.get(); + if (mvId == "") { + CallBackError(env, napiFailFun, "UnMount incoming parameter is null", NULL_ERROR); + CallComplete(env, napiCompFun); + napi_delete_reference(env, napiSuccFun); + napi_delete_reference(env, napiFailFun); + napi_delete_reference(env, napiCompFun); + return nullptr; + } + + bool s = dsm->UnMount(mvId); + if (s) { + CallBackSuccess(env, napiSuccFun, COMMON_NUM::ZERO, nullptr); + } else { + CallBackError(env, napiFailFun, "UnMount return value error", ERROR); + } + + CallComplete(env, napiCompFun); + napi_delete_reference(env, napiSuccFun); + napi_delete_reference(env, napiFailFun); + napi_delete_reference(env, napiCompFun); + return NVal::CreateUndefined(env).val_; +} + +napi_value DeviceSMExporter::Format(napi_env env, napi_callback_info info) +{ + NFuncArg funcArg(env, info); + if (!funcArg.InitArgs(NARG_CNT::ONE)) { + UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); + return nullptr; + } + bool succ = false; + napi_ref napiSuccFun, napiCompFun, napiFailFun; + tie(succ, napiSuccFun, napiFailFun, napiCompFun) = + CommonFunc::GetCallbackHandles(env, funcArg[NARG_POS::FIRST]); + + unique_ptr deviceId = nullptr; + tie(succ, deviceId, ignore) = NVal(env, funcArg[NARG_POS::FIRST]).GetProp("volId").ToUTF8String(); + + std::string mvId = (deviceId == nullptr) ? "" : deviceId.get(); + if (mvId == "") { + CallBackError(env, napiFailFun, "Format incoming parameter is null", NULL_ERROR); + CallComplete(env, napiCompFun); + napi_delete_reference(env, napiSuccFun); + napi_delete_reference(env, napiFailFun); + napi_delete_reference(env, napiCompFun); + return nullptr; + } + + bool s = dsm->Format(mvId); + if (s) { + CallBackSuccess(env, napiSuccFun, COMMON_NUM::ZERO, nullptr); + } else { + CallBackError(env, napiFailFun, "Format fail", ERROR); + } + + CallComplete(env, napiCompFun); + napi_delete_reference(env, napiSuccFun); + napi_delete_reference(env, napiFailFun); + napi_delete_reference(env, napiCompFun); + return NVal::CreateUndefined(env).val_; +} + +napi_value DeviceSMExporter::IsEncrypted(napi_env env, napi_callback_info info) +{ + NFuncArg funcArg(env, info); + if (!funcArg.InitArgs(NARG_CNT::ONE)) { + UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); + return nullptr; + } + bool succ = false; + napi_ref napiSuccFun, napiCompFun, napiFailFun; + tie(succ, napiSuccFun, napiFailFun, napiCompFun) = + CommonFunc::GetCallbackHandles(env, funcArg[NARG_POS::FIRST]); + + unique_ptr devfilePath = nullptr; + tie(succ, devfilePath, ignore) = NVal(env, funcArg[NARG_POS::FIRST]).GetProp("filePath").ToUTF8String(); + + std::string mFilePath = (devfilePath == nullptr) ? "" : devfilePath.get(); + if (mFilePath == "") { + CallBackError(env, napiFailFun, "IsEncrypted incoming parameter is null", NULL_ERROR); + CallComplete(env, napiCompFun); + napi_delete_reference(env, napiSuccFun); + napi_delete_reference(env, napiFailFun); + napi_delete_reference(env, napiCompFun); + return nullptr; + } + + bool s = dsm->IsEncrypted(mFilePath); + if (s) { + CallBackSuccess(env, napiSuccFun, COMMON_NUM::ZERO, nullptr); + } else { + CallBackError(env, napiFailFun, "Not A Encrypted Path", ERROR); + } + + CallComplete(env, napiCompFun); + napi_delete_reference(env, napiSuccFun); + napi_delete_reference(env, napiFailFun); + napi_delete_reference(env, napiCompFun); + return NVal::CreateUndefined(env).val_; +} +napi_value DeviceSMExporter::PartitionPublic(napi_env env, napi_callback_info info) +{ + NFuncArg funcArg(env, info); + if (!funcArg.InitArgs(NARG_CNT::ONE)) { + UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); + return nullptr; + } + bool succ = false; + napi_ref napiSuccFun, napiCompFun, napiFailFun; + tie(succ, napiSuccFun, napiFailFun, napiCompFun) = + CommonFunc::GetCallbackHandles(env, funcArg[NARG_POS::FIRST]); + + unique_ptr deviceId = nullptr; + tie(succ, deviceId, ignore) = NVal(env, funcArg[NARG_POS::FIRST]).GetProp("diskId").ToUTF8String(); + + std::string dsId = (deviceId == nullptr) ? "" : deviceId.get(); + if (dsId == "") { + CallBackError(env, napiFailFun, "PartitionPublic incoming parameter is null", NULL_ERROR); + CallComplete(env, napiCompFun); + napi_delete_reference(env, napiSuccFun); + napi_delete_reference(env, napiFailFun); + napi_delete_reference(env, napiCompFun); + return nullptr; + } + + bool s = dsm->PartitionPublic(dsId); + if (s) { + CallBackSuccess(env, napiSuccFun, COMMON_NUM::ZERO, nullptr); + } else { + CallBackError(env, napiFailFun, "PartitionPublic fail", ERROR); + } + + CallComplete(env, napiCompFun); + napi_delete_reference(env, napiSuccFun); + napi_delete_reference(env, napiFailFun); + napi_delete_reference(env, napiCompFun); + return NVal::CreateUndefined(env).val_; +} + +napi_value DeviceSMExporter::PartitionPrivate(napi_env env, napi_callback_info info) +{ + NFuncArg funcArg(env, info); + if (!funcArg.InitArgs(NARG_CNT::ONE)) { + UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); + return nullptr; + } + bool succ = false; + napi_ref napiSuccFun, napiCompFun, napiFailFun; + tie(succ, napiSuccFun, napiFailFun, napiCompFun) = + CommonFunc::GetCallbackHandles(env, funcArg[NARG_POS::FIRST]); + + unique_ptr deviceId = nullptr; + tie(succ, deviceId, ignore) = NVal(env, funcArg[NARG_POS::FIRST]).GetProp("diskId").ToUTF8String(); + + std::string dsId = (deviceId == nullptr) ? "" : deviceId.get(); + if (dsId == "") { + CallBackError(env, napiFailFun, "PartitionPrivate incoming parameter is null", NULL_ERROR); + CallComplete(env, napiCompFun); + napi_delete_reference(env, napiSuccFun); + napi_delete_reference(env, napiFailFun); + napi_delete_reference(env, napiCompFun); + return nullptr; + } + + bool s = dsm->PartitionPrivate(dsId); + if (s) { + CallBackSuccess(env, napiSuccFun, COMMON_NUM::ZERO, nullptr); + } else { + CallBackError(env, napiFailFun, "PartitionPrivate fail", ERROR); + } + + CallComplete(env, napiCompFun); + napi_delete_reference(env, napiSuccFun); + napi_delete_reference(env, napiFailFun); + napi_delete_reference(env, napiCompFun); + return NVal::CreateUndefined(env).val_; +} + +napi_value DeviceSMExporter::GetVolumes(napi_env env, napi_callback_info info) +{ + NFuncArg funcArg(env, info); + if (!funcArg.InitArgs(NARG_CNT::ONE)) { + UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); + return nullptr; + } + bool succ = false; + napi_ref napiSuccFun, napiCompFun, napiFailFun; + tie(succ, napiSuccFun, napiFailFun, napiCompFun) = + CommonFunc::GetCallbackHandles(env, funcArg[NARG_POS::FIRST]); + + std::vector> infos; + bool ret = dsm->GetVolumes(infos); + if (ret) { + napi_value getvolumenapi = VolumesToNapi(env, infos); + + NVal objc = NVal::CreateObject(env); + objc.AddProp("volumeInfos", getvolumenapi); + CallBackSuccess(env, napiSuccFun, COMMON_NUM::ONE, objc.val_); + } else { + CallBackError(env, napiFailFun, "getvolume not exist", ERROR); + } + + CallComplete(env, napiCompFun); + napi_delete_reference(env, napiSuccFun); + napi_delete_reference(env, napiFailFun); + napi_delete_reference(env, napiCompFun); + return NVal::CreateUndefined(env).val_; +} + +napi_value DeviceSMExporter::GetDisks(napi_env env, napi_callback_info info) +{ + NFuncArg funcArg(env, info); + if (!funcArg.InitArgs(NARG_CNT::ONE)) { + UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); + return nullptr; + } + bool succ = false; + napi_ref napiSuccFun, napiCompFun, napiFailFun; + tie(succ, napiSuccFun, napiFailFun, napiCompFun) = + CommonFunc::GetCallbackHandles(env, funcArg[NARG_POS::FIRST]); + + std::vector> infos; + bool ret = dsm->GetDisks(infos); + if (ret) { + napi_value diaknapi; + napi_create_array(env, &diaknapi); + ForeachDsmInfos(infos, env, diaknapi); + NVal objn = NVal::CreateObject(env); + objn.AddProp("diskInfos", diaknapi); + CallBackSuccess(env, napiSuccFun, COMMON_NUM::ONE, objn.val_); + } else { + CallBackError(env, napiFailFun, "disk not exist", ERROR); + } + + CallComplete(env, napiCompFun); + napi_delete_reference(env, napiSuccFun); + napi_delete_reference(env, napiFailFun); + napi_delete_reference(env, napiCompFun); + return NVal::CreateUndefined(env).val_; +} + +napi_value DeviceSMExporter::SetPrimaryStorageUuid(napi_env env, napi_callback_info info) +{ + NFuncArg funcArg(env, info); + if (!funcArg.InitArgs(NARG_CNT::ONE)) { + UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); + return nullptr; + } + bool succ = false; + napi_ref napiSuccFun, napiCompFun, napiFailFun; + tie(succ, napiSuccFun, napiFailFun, napiCompFun) = + CommonFunc::GetCallbackHandles(env, funcArg[NARG_POS::FIRST]); + + unique_ptr deviceId = nullptr; + tie(succ, deviceId, ignore) = NVal(env, funcArg[NARG_POS::FIRST]).GetProp("volumeUuid").ToUTF8String(); + std::string vuId = (deviceId == nullptr) ? "" : deviceId.get(); + if (vuId == "") { + CallBackError(env, napiFailFun, "SetPrimaryStorageUuid incoming parameter is null", NULL_ERROR); + CallComplete(env, napiCompFun); + napi_delete_reference(env, napiSuccFun); + napi_delete_reference(env, napiFailFun); + napi_delete_reference(env, napiCompFun); + return nullptr; + } + + bool s = dsm->SetPrimaryStorageUuid(vuId); + if (s) { + CallBackSuccess(env, napiSuccFun, COMMON_NUM::ZERO, nullptr); + } else { + CallBackError(env, napiFailFun, "SetPrimaryStorageUuid fail", ERROR); + } + + CallComplete(env, napiCompFun); + napi_delete_reference(env, napiSuccFun); + napi_delete_reference(env, napiFailFun); + napi_delete_reference(env, napiCompFun); + return NVal::CreateUndefined(env).val_; +} + +napi_value DeviceSMExporter::FindVolumeById(napi_env env, napi_callback_info info) +{ + NFuncArg funcArg(env, info); + if (!funcArg.InitArgs(NARG_CNT::ONE)) { + UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); + return nullptr; + } + bool succ = false; + napi_ref napiSuccFun, napiCompFun, napiFailFun; + tie(succ, napiSuccFun, napiFailFun, napiCompFun) = + CommonFunc::GetCallbackHandles(env, funcArg[NARG_POS::FIRST]); + + unique_ptr deviceId = nullptr; + tie(succ, deviceId, ignore) = NVal(env, funcArg[NARG_POS::FIRST]).GetProp("volId").ToUTF8String(); + + std::string mvId = (deviceId == nullptr) ? "" : deviceId.get(); + if (mvId == "") { + CallBackError(env, napiFailFun, "FindVolumeById incoming parameter is null", NULL_ERROR); + CallComplete(env, napiCompFun); + napi_delete_reference(env, napiSuccFun); + napi_delete_reference(env, napiFailFun); + napi_delete_reference(env, napiCompFun); + return nullptr; + } + + std::shared_ptr vol; + bool ret = dsm->FindVolumeById(vol, mvId); + if (ret) { + napi_value getvolumenapi; + napi_create_array(env, &getvolumenapi); + std::vector> infos; + dsm->GetVolumes(infos); + ForeachVomInfos(infos, env, getvolumenapi, userId); + NVal objc = NVal::CreateObject(env); + objc.AddProp("volumeInfos", getvolumenapi); + CallBackSuccess(env, napiSuccFun, COMMON_NUM::ONE, objc.val_); + } else { + CallBackError(env, napiFailFun, "FindVolumeById not exist", ERROR); + } + + CallComplete(env, napiCompFun); + napi_delete_reference(env, napiSuccFun); + napi_delete_reference(env, napiFailFun); + napi_delete_reference(env, napiCompFun); + return NVal::CreateUndefined(env).val_; +} + +napi_value DeviceSMExporter::FindVolumeByUuid(napi_env env, napi_callback_info info) +{ + NFuncArg funcArg(env, info); + if (!funcArg.InitArgs(NARG_CNT::ONE)) { + UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); + return nullptr; + } + bool succ = false; + napi_ref napiSuccFun, napiCompFun, napiFailFun; + tie(succ, napiSuccFun, napiFailFun, napiCompFun) = + CommonFunc::GetCallbackHandles(env, funcArg[NARG_POS::FIRST]); + + unique_ptr deviceId = nullptr; + tie(succ, deviceId, ignore) = NVal(env, funcArg[NARG_POS::FIRST]).GetProp("volumeUuid").ToUTF8String(); + + std::string mvmId = (deviceId == nullptr) ? "" : deviceId.get(); + if (mvmId == "") { + CallBackError(env, napiFailFun, "FindVolumeByUuid incoming parameter is null", NULL_ERROR); + CallComplete(env, napiCompFun); + napi_delete_reference(env, napiSuccFun); + napi_delete_reference(env, napiFailFun); + napi_delete_reference(env, napiCompFun); + return nullptr; + } + + std::shared_ptr vol; + if (dsm->FindVolumeByUuid(vol, mvmId)) { + napi_value getvolumenapi; + napi_create_array(env, &getvolumenapi); + std::vector> infos; + dsm->GetVolumes(infos); + ForeachVomInfos(infos, env, getvolumenapi, userId); + NVal objc = NVal::CreateObject(env); + objc.AddProp("volumeInfos", getvolumenapi); + CallBackSuccess(env, napiSuccFun, COMMON_NUM::ONE, objc.val_); + } else { + CallBackError(env, napiFailFun, "FindVolumeByUuid not exist", ERROR); + } + + CallComplete(env, napiCompFun); + napi_delete_reference(env, napiSuccFun); + napi_delete_reference(env, napiFailFun); + napi_delete_reference(env, napiCompFun); + return NVal::CreateUndefined(env).val_; +} + +napi_value DeviceSMExporter::FindDiskById(napi_env env, napi_callback_info info) +{ + NFuncArg funcArg(env, info); + if (!funcArg.InitArgs(NARG_CNT::ONE)) { + UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); + return nullptr; + } + bool succ = false; + napi_ref napiSuccFun, napiCompFun, napiFailFun; + tie(succ, napiSuccFun, napiFailFun, napiCompFun) = + CommonFunc::GetCallbackHandles(env, funcArg[NARG_POS::FIRST]); + + unique_ptr deviceId = nullptr; + tie(succ, deviceId, ignore) = NVal(env, funcArg[NARG_POS::FIRST]).GetProp("diskId").ToUTF8String(); + + std::string dsId = (deviceId == nullptr) ? "" : deviceId.get(); + if (dsId == "") { + CallBackError(env, napiFailFun, "FindDiskById incoming parameter is null", NULL_ERROR); + CallComplete(env, napiCompFun); + napi_delete_reference(env, napiSuccFun); + napi_delete_reference(env, napiFailFun); + napi_delete_reference(env, napiCompFun); + return nullptr; + } + + std::shared_ptr disk; + if (dsm->FindDiskById(disk, dsId)) { + napi_value diaknapi; + napi_create_array(env, &diaknapi); + std::vector> infos; + dsm->GetDisks(infos); + ForeachDsmInfos(infos, env, diaknapi); + NVal objn = NVal::CreateObject(env); + objn.AddProp("diskInfos", diaknapi); + CallBackSuccess(env, napiSuccFun, COMMON_NUM::ONE, objn.val_); + } else { + CallBackError(env, napiFailFun, "FindDiskById not exist", ERROR); + } + + CallComplete(env, napiCompFun); + napi_delete_reference(env, napiSuccFun); + napi_delete_reference(env, napiFailFun); + napi_delete_reference(env, napiCompFun); + return NVal::CreateUndefined(env).val_; +} + +napi_value DeviceSMExporter::GetPrimaryStorageUuid(napi_env env, napi_callback_info info) +{ + NFuncArg funcArg(env, info); + if (!funcArg.InitArgs(NARG_CNT::ONE)) { + UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); + return nullptr; + } + bool succ = false; + napi_ref napiSuccFun, napiCompFun, napiFailFun; + tie(succ, napiSuccFun, napiFailFun, napiCompFun) = + CommonFunc::GetCallbackHandles(env, funcArg[NARG_POS::FIRST]); + + std::string primaryUuid; + bool s = dsm->GetPrimaryStorageUuid(primaryUuid); + if (s) { + NVal obj = NVal::CreateObject(env); + obj.AddProp("primaryUuid", NVal::CreateUTF8String(env, primaryUuid).val_); + CallBackSuccess(env, napiSuccFun, COMMON_NUM::ONE, obj.val_); + } else { + CallBackError(env, napiFailFun, "GetPrimaryStorageUuid return value error", ERROR); + } + + CallComplete(env, napiCompFun); + napi_delete_reference(env, napiSuccFun); + napi_delete_reference(env, napiFailFun); + napi_delete_reference(env, napiCompFun); + return NVal::CreateUndefined(env).val_; +} + +napi_value DeviceSMExporter::FindPrivateForEmulate(napi_env env, napi_callback_info info) +{ + NFuncArg funcArg(env, info); + if (!funcArg.InitArgs(NARG_CNT::ONE)) { + UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); + return nullptr; + } + bool succ = false; + napi_ref napiSuccFun, napiCompFun, napiFailFun; + tie(succ, napiSuccFun, napiFailFun, napiCompFun) = + CommonFunc::GetCallbackHandles(env, funcArg[NARG_POS::FIRST]); + + std::shared_ptr emuVol = std::make_shared(); + + NVal a = NVal(env, funcArg[NARG_POS::FIRST]).GetProp("emuVol"); + if (a.TypeIs(napi_object)) { + } else if (a.TypeIs(napi_undefined)) { + } else if (a.TypeIs(napi_null)) { + } + + PriVolToEmuVol(env, a, emuVol); + std::shared_ptr priVol; + bool ret = dsm->FindPrivateForEmulate(priVol, emuVol); + if (ret) { + napi_value getvolumenapi; + napi_create_array(env, &getvolumenapi); + std::vector> infos; + dsm->GetVolumes(infos); + ForeachVomInfos(infos, env, getvolumenapi, userId); + NVal objc = NVal::CreateObject(env); + objc.AddProp("volumeInfos", getvolumenapi); + CallBackSuccess(env, napiSuccFun, COMMON_NUM::ONE, objc.val_); + } else { + CallBackError(env, napiFailFun, "FindPrivateForEmulate not exist", ERROR); + } + + CallComplete(env, napiCompFun); + napi_delete_reference(env, napiSuccFun); + napi_delete_reference(env, napiFailFun); + napi_delete_reference(env, napiCompFun); + return NVal::CreateUndefined(env).val_; +} + +napi_value DeviceSMExporter::FindEmulateForPrivate(napi_env env, napi_callback_info info) +{ + NFuncArg funcArg(env, info); + if (!funcArg.InitArgs(NARG_CNT::ONE)) { + UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); + return nullptr; + } + bool succ = false; + napi_ref napiSuccFun, napiCompFun, napiFailFun; + tie(succ, napiSuccFun, napiFailFun, napiCompFun) = + CommonFunc::GetCallbackHandles(env, funcArg[NARG_POS::FIRST]); + + std::shared_ptr priVol = std::make_shared(); + + NVal a = NVal(env, funcArg[NARG_POS::FIRST]).GetProp("priVol"); + if (a.TypeIs(napi_object)) { + } else if (a.TypeIs(napi_undefined)) { + } else if (a.TypeIs(napi_null)) { + } + + EmuVolToPriVol(env, a, priVol); + std::shared_ptr emuVol; + bool ret = dsm->FindEmulateForPrivate(emuVol, priVol); + if (ret) { + napi_value getvolumenapi; + napi_create_array(env, &getvolumenapi); + std::vector> infos; + dsm->GetVolumes(infos); + ForeachVomInfos(infos, env, getvolumenapi, userId); + NVal objc = NVal::CreateObject(env); + objc.AddProp("volumeInfos", getvolumenapi); + CallBackSuccess(env, napiSuccFun, COMMON_NUM::ONE, objc.val_); + } else { + CallBackError(env, napiFailFun, "FindEmulateForPrivate not exist", ERROR); + } + + CallComplete(env, napiCompFun); + napi_delete_reference(env, napiSuccFun); + napi_delete_reference(env, napiFailFun); + napi_delete_reference(env, napiCompFun); + return NVal::CreateUndefined(env).val_; +} + +napi_value DeviceSMExporter::GetBestVolumeDescription(napi_env env, napi_callback_info info) +{ + NFuncArg funcArg(env, info); + if (!funcArg.InitArgs(NARG_CNT::ONE)) { + UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); + return nullptr; + } + bool succ = false; + napi_ref napiSuccFun, napiCompFun, napiFailFun; + tie(succ, napiSuccFun, napiFailFun, napiCompFun) = + CommonFunc::GetCallbackHandles(env, funcArg[NARG_POS::FIRST]); + + std::shared_ptr vol = std::make_shared(); + + NVal a = NVal(env, funcArg[NARG_POS::FIRST]).GetProp("vol"); + if (a.TypeIs(napi_object)) { + } else if (a.TypeIs(napi_undefined)) { + } else if (a.TypeIs(napi_null)) { + } + + VolToDesCription(env, a, vol); + + std::string desCription; + bool s = dsm->GetBestVolumeDescription(vol, desCription); + if (s) { + NVal obj = NVal::CreateObject(env); + obj.AddProp("desCription", NVal::CreateUTF8String(env, vol->GetDescription()).val_); + CallBackSuccess(env, napiSuccFun, COMMON_NUM::ONE, obj.val_); + } else { + CallBackError(env, napiFailFun, "GetBestVolumeDescription return value error", ERROR); + } + + CallComplete(env, napiCompFun); + napi_delete_reference(env, napiSuccFun); + napi_delete_reference(env, napiFailFun); + napi_delete_reference(env, napiCompFun); + return NVal::CreateUndefined(env).val_; +} + +napi_value DeviceSMExporter::GetWritableVolumes(napi_env env, napi_callback_info info) +{ + NFuncArg funcArg(env, info); + if (!funcArg.InitArgs(NARG_CNT::ONE)) { + UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); + return nullptr; + } + bool succ = false; + napi_ref napiSuccFun, napiCompFun, napiFailFun; + tie(succ, napiSuccFun, napiFailFun, napiCompFun) = + CommonFunc::GetCallbackHandles(env, funcArg[NARG_POS::FIRST]); + + std::vector> infos; + bool ret = dsm->GetWritableVolumes(infos); + if (ret) { + napi_value getvolumenapi; + napi_create_array(env, &getvolumenapi); + ForeachVomInfos(infos, env, getvolumenapi, userId); + NVal objc = NVal::CreateObject(env); + objc.AddProp("volumeInfos", getvolumenapi); + CallBackSuccess(env, napiSuccFun, COMMON_NUM::ONE, objc.val_); + } else { + CallBackError(env, napiFailFun, "GetWritableVolumes not exist", ERROR); + } + + CallComplete(env, napiCompFun); + napi_delete_reference(env, napiSuccFun); + napi_delete_reference(env, napiFailFun); + napi_delete_reference(env, napiCompFun); + return NVal::CreateUndefined(env).val_; +} + +bool DeviceSMExporter::Export() +{ + return exports_.AddProp({ + NVal::DeclareNapiFunction("mount", Mount), + NVal::DeclareNapiFunction("unMount", UnMount), + NVal::DeclareNapiFunction("format", Format), + NVal::DeclareNapiFunction("partitionPublic", PartitionPublic), + NVal::DeclareNapiFunction("partitionPrivate", PartitionPrivate), + NVal::DeclareNapiFunction("getVolumes", GetVolumes), + NVal::DeclareNapiFunction("getDisks", GetDisks), + NVal::DeclareNapiFunction("setPrimaryStorageUuid", SetPrimaryStorageUuid), + NVal::DeclareNapiFunction("findVolumeById", FindVolumeById), + NVal::DeclareNapiFunction("findVolumeByUuid", FindVolumeByUuid), + NVal::DeclareNapiFunction("findDiskById", FindDiskById), + NVal::DeclareNapiFunction("getPrimaryStorageUuid", GetPrimaryStorageUuid), + NVal::DeclareNapiFunction("findPrivateForEmulate", FindPrivateForEmulate), + NVal::DeclareNapiFunction("findEmulateForPrivate", FindEmulateForPrivate), + NVal::DeclareNapiFunction("getWritableVolumes", GetWritableVolumes), + NVal::DeclareNapiFunction("getBestVolumeDescription", GetBestVolumeDescription), + NVal::DeclareNapiFunction("isEncrypted", IsEncrypted), + }); +} + +string DeviceSMExporter::GetClassName() +{ + return DeviceSMExporter::className_; +} + +DeviceSMExporter::DeviceSMExporter(napi_env env, napi_value exports) + : NExporter(env, exports) +{} + +DeviceSMExporter::~DeviceSMExporter() {} +} // namespace ModuleDSMExpoter +} // namespace DistributedFS +} // namespace OHOS diff --git a/interfaces/kits/napi/device_storage_manager/device_sm_exporter.h b/interfaces/kits/napi/device_storage_manager/device_sm_exporter.h new file mode 100644 index 0000000000000000000000000000000000000000..b40f49611b2a2a5959b423ed8d97e013013f4c99 --- /dev/null +++ b/interfaces/kits/napi/device_storage_manager/device_sm_exporter.h @@ -0,0 +1,56 @@ +/* + * Copyright (c) 2021-2022 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. + */ +#ifndef STORAGE_DISKMGR_INTERFACE_KITS_NAPI_DSM_DEVICE_SM_EXPORTER_H +#define STORAGE_DISKMGR_INTERFACE_KITS_NAPI_DSM_DEVICE_SM_EXPORTER_H + +#pragma once + +#include "../common/napi/n_exporter.h" + +namespace OHOS { +namespace DistributedFS { +namespace ModuleDSMExpoter { +class DeviceSMExporter final : public NExporter { +public: + inline static const std::string className_ = "DeviceSMgr"; + static napi_value Mount(napi_env env, napi_callback_info info); + static napi_value UnMount(napi_env env, napi_callback_info info); + static napi_value Format(napi_env env, napi_callback_info info); + static napi_value PartitionPublic(napi_env env, napi_callback_info info); + static napi_value PartitionPrivate(napi_env env, napi_callback_info info); + static napi_value GetVolumes(napi_env env, napi_callback_info info); + static napi_value GetDisks(napi_env env, napi_callback_info info); + static napi_value SetPrimaryStorageUuid(napi_env env, napi_callback_info info); + static napi_value FindVolumeById(napi_env env, napi_callback_info info); + static napi_value FindVolumeByUuid(napi_env env, napi_callback_info info); + static napi_value FindDiskById(napi_env env, napi_callback_info info); + static napi_value GetPrimaryStorageUuid(napi_env env, napi_callback_info info); + static napi_value FindPrivateForEmulate(napi_env env, napi_callback_info info); + static napi_value FindEmulateForPrivate(napi_env env, napi_callback_info info); + static napi_value GetWritableVolumes(napi_env env, napi_callback_info info); + static napi_value GetBestVolumeDescription(napi_env env, napi_callback_info info); + static napi_value IsEncrypted(napi_env env, napi_callback_info info); + bool Export() override; + + std::string GetClassName() override; + + DeviceSMExporter(napi_env env, napi_value exports); + ~DeviceSMExporter() override; +}; +} // namespace ModuleDSMExpoter +} // namespace DistributedFS +} // namespace OHOS + +#endif // STORAGE_DISKMGR_INTERFACE_KITS_NAPI_DSM_DEVICE_SM_EXPORTER_H \ No newline at end of file diff --git a/interfaces/kits/napi/device_storage_manager/module.cpp b/interfaces/kits/napi/device_storage_manager/module.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b07529b55b4d333981f64cd1415859a95fabda29 --- /dev/null +++ b/interfaces/kits/napi/device_storage_manager/module.cpp @@ -0,0 +1,47 @@ +/* + * Copyright (c) 2021-2022 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. + */ +#include "module.h" + +#include +#include + +#include "../common/log.h" +#include "device_sm_exporter.h" + +using namespace std; + +namespace OHOS { +namespace DistributedFS { +namespace ModuleDSMExpoter { +static napi_value Export(napi_env env, napi_value exports) +{ + std::vector> products; + products.emplace_back(make_unique(env, exports)); + + for (auto && product : products) { + if (!product->Export()) { + HILOGE("INNER BUG. Failed to export class %{public}s for module file", product->GetClassName().c_str()); + return nullptr; + } else { + HILOGE("Class %{public}s for module file has been exported", product->GetClassName().c_str()); + } + } + return exports; +} + +NAPI_MODULE(devicesmgr, Export) +} // namespace ModuleFile +} // namespace DistributedFS +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/napi/device_storage_manager/module.h b/interfaces/kits/napi/device_storage_manager/module.h new file mode 100644 index 0000000000000000000000000000000000000000..5709fd8f06c701bcd058ee042c01c7b48aab825d --- /dev/null +++ b/interfaces/kits/napi/device_storage_manager/module.h @@ -0,0 +1,18 @@ +/* + * Copyright (c) 2021-2022 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. + */ +#ifndef STORAGE_DISKMGR_INTERFACE_KITS_NAPI_DSM_MODULE_H +#define STORAGE_DISKMGR_INTERFACE_KITS_NAPI_DSM_MODULE_H + +#endif // STORAGE_DISKMGR_INTERFACE_KITS_NAPI_DSM_MODULE_H \ No newline at end of file diff --git a/interfaces/kits/napi/file_picker_service/file_picker_exporter.cpp b/interfaces/kits/napi/file_picker_service/file_picker_exporter.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7837eb2789250f5921956b96275e6ee86c643751 --- /dev/null +++ b/interfaces/kits/napi/file_picker_service/file_picker_exporter.cpp @@ -0,0 +1,478 @@ +/* + * Copyright (c) 2021-2022 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. + */ +#include "file_picker_exporter.h" + +#include +#include +#include +#include + +#include "../common/ability_helper.h" +#include "../common/common_func.h" +#include "../common/napi/n_class.h" +#include "../common/napi/n_func_arg.h" +#include "../common/napi/n_val.h" +#include "../common/uni_error.h" +#include "file_info.h" +#include "root_info.h" +#include "storage_ability.h" +#include "uri.h" + +using Uri = OHOS::Uri; +using namespace std; +namespace OHOS { +namespace DistributedFS { +namespace ModuleFPExpoter { +enum COMMON_NUM { + ZERO = 0, + ONE = 1, + TWO = 2, + THREE = 3, +}; + +enum ERROR_CODE { + SUCCESS_CODE = 200, + OTHER_ARGUMENT_ERROR = 202, + FILE_IO_ERROR = 300, + FILE_PATH_ERROR = 301, + URI_PARAMER_ERROR = 302, +}; + +void CallBackSuccess(napi_env env, napi_ref successFuncRef, int32_t count, napi_value obj) +{ + napi_value results = nullptr; + napi_value successFunc = nullptr; + napi_value global = nullptr; + napi_get_global(env, &global); + napi_get_reference_value(env, successFuncRef, &successFunc); + if (successFunc == nullptr) { + return; + } + napi_call_function(env, global, successFunc, count, &obj, &results); +} + +void CallBackError(napi_env env, napi_ref failFuncRef, string errorProp, int errorCode) +{ + napi_value argvFail[2] = { 0 }; + napi_value results = nullptr; + napi_value failFunc = nullptr; + napi_value global = nullptr; + napi_get_global(env, &global); + argvFail[0] = NVal::CreateUTF8String(env, errorProp).val_; + argvFail[1] = NVal::CreateInt32(env, errorCode).val_; + napi_get_reference_value(env, failFuncRef, &failFunc); + if (failFunc == nullptr) { + return; + } + napi_call_function(env, global, failFunc, COMMON_NUM::TWO, argvFail, &results); +} + +void CallComplete(napi_env env, napi_ref completeFuncRef) +{ + napi_value completeFunc = nullptr; + napi_value results = nullptr; + napi_value global = nullptr; + napi_get_global(env, &global); + napi_get_reference_value(env, completeFuncRef, &completeFunc); + if (completeFunc == nullptr) { + return; + } + napi_call_function(env, global, completeFunc, COMMON_NUM::ZERO, nullptr, &results); +} + +void SaveFileExec(napi_env env, void *data) +{ + auto *asyncInfo = (SaveFileAsyncInfo *)data; + unique_ptr point; + vector result; + Uri uriObj(asyncInfo->dstPath); + asyncInfo->err = point->SaveFiles(uriObj, asyncInfo->srcPath, result); + asyncInfo->saveFileList.assign(result.begin(), result.end()); +} + +void SaveFileComp(napi_env env, napi_status status, void *data) +{ + auto *asyncInfo = (SaveFileAsyncInfo *)data; + if (asyncInfo->err == ERROR_CODE::SUCCESS_CODE) { + napi_value saveListNapi; + napi_create_array(env, &saveListNapi); + int32_t i = 0; + for (auto saveInfo : asyncInfo->saveFileList) { + NVal objt = NVal::CreateObject(env); + objt.AddProp("srcUri", NVal::CreateUTF8String(env, saveInfo.srcUri).val_); + objt.AddProp("dstUri", NVal::CreateUTF8String(env, saveInfo.dstUri).val_); + objt.AddProp("status", NVal::CreateBool(env, saveInfo.status).val_); + + napi_set_property(env, saveListNapi, NVal::CreateInt32(env, i).val_, objt.val_); + i = i + 1; + } + NVal objn = NVal::CreateObject(env); + objn.AddProp("saveFileList", saveListNapi); + CallBackSuccess(env, asyncInfo->callback[COMMON_NUM::ZERO], COMMON_NUM::ONE, objn.val_); + } else { + CallBackError(env, asyncInfo->callback[COMMON_NUM::ONE], "SaveFile fail", asyncInfo->err); + } + CallComplete(env, asyncInfo->callback[COMMON_NUM::TWO]); + napi_delete_reference(env, asyncInfo->callback[COMMON_NUM::ZERO]); + napi_delete_reference(env, asyncInfo->callback[COMMON_NUM::ONE]); + napi_delete_reference(env, asyncInfo->callback[COMMON_NUM::TWO]); + napi_delete_async_work(env, asyncInfo->asyncWork); + delete asyncInfo; +} + +void SearchFileExec(napi_env env, void *data) +{ + auto asyncInfo = (SearchFileAsyncInfo *)data; + unique_ptr point; + vector result; + Uri uriObj(asyncInfo->path); + asyncInfo->err = point->SearchFiles(uriObj, asyncInfo->name, result); + asyncInfo->fileInfoList.assign(result.begin(), result.end()); +} + +void SearchFileComp(napi_env env, napi_status status, void *data) +{ + auto asyncInfo = (SearchFileAsyncInfo *)data; + if (asyncInfo->err == ERROR_CODE::SUCCESS_CODE) { + napi_value fileListNapi; + napi_create_array(env, &fileListNapi); + int32_t i = 0; + for (auto fileInfo : asyncInfo->fileInfoList) { + NVal objt = NVal::CreateObject(env); + objt.AddProp("uri", NVal::CreateUTF8String(env, fileInfo.fileUri).val_); + objt.AddProp("name", NVal::CreateUTF8String(env, fileInfo.fileName).val_); + + objt.AddProp("lastModifiedTime", NVal::CreateInt64(env, fileInfo.lastUseTime).val_); + objt.AddProp("length", NVal::CreateInt32(env, fileInfo.fileSize).val_); + objt.AddProp("num", NVal::CreateInt32(env, fileInfo.dirNum).val_); + string type = (fileInfo.typeDir == 1) ? "dir" : "file"; + objt.AddProp("type", NVal::CreateUTF8String(env, type).val_); + objt.AddProp("suffix", NVal::CreateUTF8String(env, fileInfo.mimeType).val_); + + napi_set_property(env, fileListNapi, NVal::CreateInt32(env, i).val_, objt.val_); + i = i + 1; + } + NVal objn = NVal::CreateObject(env); + objn.AddProp("fileList", fileListNapi); + CallBackSuccess(env, asyncInfo->callback[COMMON_NUM::ZERO], COMMON_NUM::ONE, objn.val_); + } else { + CallBackError(env, asyncInfo->callback[COMMON_NUM::ONE], "SearchFile fail", asyncInfo->err); + } + CallComplete(env, asyncInfo->callback[COMMON_NUM::TWO]); + napi_delete_reference(env, asyncInfo->callback[COMMON_NUM::ZERO]); + napi_delete_reference(env, asyncInfo->callback[COMMON_NUM::ONE]); + napi_delete_reference(env, asyncInfo->callback[COMMON_NUM::TWO]); + napi_delete_async_work(env, asyncInfo->asyncWork); + delete asyncInfo; +} + +void ListExec(napi_env env, void *data) +{ + auto asyncInfo = (ListAsyncInfo *)data; + unique_ptr point; + vector result; + Uri uriObj(asyncInfo->path); + asyncInfo->err = point->QueryFiles(uriObj, result); + asyncInfo->fileInfoList.assign(result.begin(), result.end()); +} + +void ListComp(napi_env env, napi_status status, void *data) +{ + auto asyncInfo = (ListAsyncInfo *)data; + if (asyncInfo->err == ERROR_CODE::SUCCESS_CODE) { + napi_value fileListNapi; + napi_create_array(env, &fileListNapi); + int32_t i = 0; + for (auto fileInfo : asyncInfo->fileInfoList) { + NVal objt = NVal::CreateObject(env); + objt.AddProp("uri", NVal::CreateUTF8String(env, fileInfo.fileUri).val_); + objt.AddProp("name", NVal::CreateUTF8String(env, fileInfo.fileName).val_); + + objt.AddProp("lastModifiedTime", NVal::CreateInt64(env, fileInfo.lastUseTime).val_); + objt.AddProp("length", NVal::CreateInt32(env, fileInfo.fileSize).val_); + objt.AddProp("num", NVal::CreateInt32(env, fileInfo.dirNum).val_); + string type = (fileInfo.typeDir == 1) ? "dir" : "file"; + objt.AddProp("type", NVal::CreateUTF8String(env, type).val_); + objt.AddProp("suffix", NVal::CreateUTF8String(env, fileInfo.mimeType).val_); + + napi_set_property(env, fileListNapi, NVal::CreateInt32(env, i).val_, objt.val_); + i = i + 1; + } + NVal objn = NVal::CreateObject(env); + objn.AddProp("fileList", fileListNapi); + CallBackSuccess(env, asyncInfo->callback[COMMON_NUM::ZERO], COMMON_NUM::ONE, objn.val_); + } else { + CallBackError(env, asyncInfo->callback[COMMON_NUM::ONE], "List fail", asyncInfo->err); + } + CallComplete(env, asyncInfo->callback[COMMON_NUM::TWO]); + napi_delete_reference(env, asyncInfo->callback[COMMON_NUM::ZERO]); + napi_delete_reference(env, asyncInfo->callback[COMMON_NUM::ONE]); + napi_delete_reference(env, asyncInfo->callback[COMMON_NUM::TWO]); + napi_delete_async_work(env, asyncInfo->asyncWork); + delete asyncInfo; +} + +void GetDeviceInfoExec(napi_env env, void *data) +{ + auto asyncInfo = (GetDeviceAsyncInfo *)data; + unique_ptr point; + vector result; + asyncInfo->err = point->QueryDeviceInfo(result); + asyncInfo->deviceInfoList.assign(result.begin(), result.end()); +} + +void GetDeviceInfoComp(napi_env env, napi_status status, void *data) +{ + auto asyncInfo = (GetDeviceAsyncInfo *)data; + if (asyncInfo->err == ERROR_CODE::SUCCESS_CODE) { + napi_value deviceListNapi; + napi_create_array(env, &deviceListNapi); + int32_t i = 0; + for (auto deviceInfo : asyncInfo->deviceInfoList) { + NVal objt = NVal::CreateObject(env); + objt.AddProp("uri", NVal::CreateUTF8String(env, deviceInfo.path).val_); + objt.AddProp("deviceID", NVal::CreateUTF8String(env, deviceInfo.deviceId).val_); + + objt.AddProp("mountID", NVal::CreateInt32(env, deviceInfo.mountFlags).val_); + objt.AddProp("diskID", NVal::CreateUTF8String(env, deviceInfo.diskId).val_); + + napi_set_property(env, deviceListNapi, NVal::CreateInt32(env, i).val_, objt.val_); + i = i + 1; + } + NVal objn = NVal::CreateObject(env); + objn.AddProp("deviceList", deviceListNapi); + CallBackSuccess(env, asyncInfo->callback[COMMON_NUM::ZERO], COMMON_NUM::ONE, objn.val_); + } else { + CallBackError(env, asyncInfo->callback[COMMON_NUM::ONE], "GetDeviceInfo fail", asyncInfo->err); + } + CallComplete(env, asyncInfo->callback[COMMON_NUM::TWO]); + napi_delete_reference(env, asyncInfo->callback[COMMON_NUM::ZERO]); + napi_delete_reference(env, asyncInfo->callback[COMMON_NUM::ONE]); + napi_delete_reference(env, asyncInfo->callback[COMMON_NUM::TWO]); + napi_delete_async_work(env, asyncInfo->asyncWork); + delete asyncInfo; +} + +napi_value FilePickerExporter::Mkdir(napi_env env, napi_callback_info info) +{ + NFuncArg funcArg(env, info); + if (!funcArg.InitArgs(NARG_CNT::ONE)) { + UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); + return nullptr; + } + + auto *asyncInfo = new MkdirAsyncInfo; + bool succ = false; + tie(succ, asyncInfo->callback[COMMON_NUM::ZERO], asyncInfo->callback[COMMON_NUM::ONE], + asyncInfo->callback[COMMON_NUM::TWO]) = CommonFunc::GetCallbackHandles(env, funcArg[NARG_POS::FIRST]); + + unique_ptr uri = nullptr; + tie(succ, uri, ignore) = NVal(env, funcArg[NARG_POS::FIRST]).GetProp("uri").ToUTF8String(); + + asyncInfo->path = (uri == nullptr) ? "" : uri.get(); + + if (asyncInfo->path == "") { + CallBackError(env, asyncInfo->callback[COMMON_NUM::ONE], "uri cannot be empty", + ERROR_CODE::URI_PARAMER_ERROR); + delete asyncInfo; + return nullptr; + } + + napi_create_async_work( + env, nullptr, NVal::CreateUTF8String(env, "Mkdir").val_, + [](napi_env env, void *data) { + auto *asyncInfo = (MkdirAsyncInfo *)data; + unique_ptr point; + Uri uriObj(asyncInfo->path); + asyncInfo->err = point->CreateDir(uriObj); + }, + [](napi_env env, napi_status status, void *data) { + auto *asyncInfo = (MkdirAsyncInfo *)data; + if (asyncInfo->err == ERROR_CODE::SUCCESS_CODE) { + CallBackSuccess(env, asyncInfo->callback[COMMON_NUM::ZERO], 0, nullptr); + } else { + CallBackError(env, asyncInfo->callback[COMMON_NUM::ONE], "Mkdir fail", asyncInfo->err); + } + CallComplete(env, asyncInfo->callback[COMMON_NUM::TWO]); + napi_delete_reference(env, asyncInfo->callback[COMMON_NUM::ZERO]); + napi_delete_reference(env, asyncInfo->callback[COMMON_NUM::ONE]); + napi_delete_reference(env, asyncInfo->callback[COMMON_NUM::TWO]); + napi_delete_async_work(env, asyncInfo->asyncWork); + delete asyncInfo; + }, + (void *)asyncInfo, &asyncInfo->asyncWork); + napi_queue_async_work(env, asyncInfo->asyncWork); + + return NVal::CreateUndefined(env).val_; +} + +napi_value FilePickerExporter::SaveFile(napi_env env, napi_callback_info info) +{ + NFuncArg funcArg(env, info); + if (!funcArg.InitArgs(NARG_CNT::ONE)) { + UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); + return nullptr; + } + + auto *asyncInfo = new SaveFileAsyncInfo; + + bool succ = false; + tie(succ, asyncInfo->callback[COMMON_NUM::ZERO], asyncInfo->callback[COMMON_NUM::ONE], + asyncInfo->callback[COMMON_NUM::TWO]) = CommonFunc::GetCallbackHandles(env, funcArg[NARG_POS::FIRST]); + + unique_ptr dstUri = nullptr; + tie(succ, dstUri, ignore) = NVal(env, funcArg[NARG_POS::FIRST]).GetProp("dstUri").ToUTF8String(); + + uint32_t srcLen = 0; + vector srcPath; + NVal srcNapi = NVal(env, funcArg[NARG_POS::FIRST]).GetProp("srcUri"); + napi_get_array_length(env, srcNapi.val_, &srcLen); + for (uint32_t i = 0; i < srcLen; ++i) { + napi_value srcElementNapi; + unique_ptr srcElement = nullptr; + napi_get_element(env, srcNapi.val_, i, &srcElementNapi); + tie(succ, srcElement, ignore) = NVal(env, srcElementNapi).ToUTF8String(); + string path = (srcElement == nullptr) ? "" : srcElement.get(); + srcPath.emplace_back(path); + } + + asyncInfo->srcPath.assign(srcPath.begin(), srcPath.end()); + asyncInfo->dstPath = (dstUri == nullptr) ? "" : dstUri.get(); + asyncInfo->srcLen = srcLen; + + if (asyncInfo->dstPath == "" || asyncInfo->srcPath.empty()) { + CallBackError(env, asyncInfo->callback[COMMON_NUM::ONE], "dstUri or srcUri cannot be empty", + ERROR_CODE::URI_PARAMER_ERROR); + delete asyncInfo; + return nullptr; + } + + napi_create_async_work(env, nullptr, NVal::CreateUTF8String(env, "SaveFile").val_, SaveFileExec, + SaveFileComp, (void *)asyncInfo, &asyncInfo->asyncWork); + napi_queue_async_work(env, asyncInfo->asyncWork); + + return NVal::CreateUndefined(env).val_; +} + +napi_value FilePickerExporter::SearchFile(napi_env env, napi_callback_info info) +{ + NFuncArg funcArg(env, info); + if (!funcArg.InitArgs(NARG_CNT::ONE)) { + UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); + return nullptr; + } + + auto *asyncInfo = new SearchFileAsyncInfo; + bool succ = false; + tie(succ, asyncInfo->callback[COMMON_NUM::ZERO], asyncInfo->callback[COMMON_NUM::ONE], + asyncInfo->callback[COMMON_NUM::TWO]) = CommonFunc::GetCallbackHandles(env, funcArg[NARG_POS::FIRST]); + + unique_ptr uri = nullptr; + tie(succ, uri, ignore) = NVal(env, funcArg[NARG_POS::FIRST]).GetProp("uri").ToUTF8String(); + + unique_ptr name = nullptr; + tie(succ, name, ignore) = NVal(env, funcArg[NARG_POS::FIRST]).GetProp("name").ToUTF8String(); + + asyncInfo->path = (uri == nullptr) ? "" : uri.get(); + asyncInfo->name = (name == nullptr) ? "" : name.get(); + + if (asyncInfo->path == "") { + CallBackError(env, asyncInfo->callback[COMMON_NUM::ONE], "uri cannot be empty", + ERROR_CODE::URI_PARAMER_ERROR); + delete asyncInfo; + return nullptr; + } + + napi_create_async_work(env, nullptr, NVal::CreateUTF8String(env, "SearchFile").val_, SearchFileExec, + SearchFileComp, (void *)asyncInfo, &asyncInfo->asyncWork); + napi_queue_async_work(env, asyncInfo->asyncWork); + + return NVal::CreateUndefined(env).val_; +} + +napi_value FilePickerExporter::List(napi_env env, napi_callback_info info) +{ + NFuncArg funcArg(env, info); + if (!funcArg.InitArgs(NARG_CNT::ONE)) { + UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); + return nullptr; + } + + auto *asyncInfo = new ListAsyncInfo; + + bool succ = false; + tie(succ, asyncInfo->callback[COMMON_NUM::ZERO], asyncInfo->callback[COMMON_NUM::ONE], + asyncInfo->callback[COMMON_NUM::TWO]) = CommonFunc::GetCallbackHandles(env, funcArg[NARG_POS::FIRST]); + + unique_ptr uri = nullptr; + tie(succ, uri, ignore) = NVal(env, funcArg[NARG_POS::FIRST]).GetProp("uri").ToUTF8String(); + + asyncInfo->path = (uri == nullptr) ? "" : uri.get(); + if (asyncInfo->path == "") { + CallBackError(env, asyncInfo->callback[COMMON_NUM::ONE], "uri cannot be empty", + ERROR_CODE::URI_PARAMER_ERROR); + delete asyncInfo; + return nullptr; + } + + napi_create_async_work(env, nullptr, NVal::CreateUTF8String(env, "List").val_, ListExec, ListComp, + (void *)asyncInfo, &asyncInfo->asyncWork); + napi_queue_async_work(env, asyncInfo->asyncWork); + + return NVal::CreateUndefined(env).val_; +} + +napi_value FilePickerExporter::GetDeviceInfo(napi_env env, napi_callback_info info) +{ + NFuncArg funcArg(env, info); + if (!funcArg.InitArgs(NARG_CNT::ONE)) { + UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); + return nullptr; + } + + auto *asyncInfo = new GetDeviceAsyncInfo; + + bool succ = false; + tie(succ, asyncInfo->callback[COMMON_NUM::ZERO], asyncInfo->callback[COMMON_NUM::ONE], + asyncInfo->callback[COMMON_NUM::TWO]) = CommonFunc::GetCallbackHandles(env, funcArg[NARG_POS::FIRST]); + + napi_create_async_work(env, nullptr, NVal::CreateUTF8String(env, "GetDeviceInfo").val_, GetDeviceInfoExec, + GetDeviceInfoComp, (void *)asyncInfo, &asyncInfo->asyncWork); + napi_queue_async_work(env, asyncInfo->asyncWork); + + return NVal::CreateUndefined(env).val_; +} + +bool FilePickerExporter::Export() +{ + return exports_.AddProp( + { NVal::DeclareNapiFunction("mkdir", Mkdir), NVal::DeclareNapiFunction("saveFile", SaveFile), + NVal::DeclareNapiFunction("searchFile", SearchFile), NVal::DeclareNapiFunction("list", List), + NVal::DeclareNapiFunction("getDeviceInfo", GetDeviceInfo) }); +} + +string FilePickerExporter::GetClassName() +{ + return FilePickerExporter::className_; +} + +FilePickerExporter::FilePickerExporter(napi_env env, napi_value exports) + : NExporter(env, exports) +{} + +FilePickerExporter::~FilePickerExporter() {} +} // namespace ModuleFPExpoter +} // namespace DistributedFS +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/napi/file_picker_service/file_picker_exporter.h b/interfaces/kits/napi/file_picker_service/file_picker_exporter.h new file mode 100644 index 0000000000000000000000000000000000000000..5b75bc26bf008fd68371d51abc36d2871c696a76 --- /dev/null +++ b/interfaces/kits/napi/file_picker_service/file_picker_exporter.h @@ -0,0 +1,96 @@ +/* + * Copyright (c) 2021-2022 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. + */ +#ifndef STORAGE_DISKMGR_INTERFACE_KITS_NAPI_DSM_FILE_PICKER_EXPORTER_H +#define STORAGE_DISKMGR_INTERFACE_KITS_NAPI_DSM_FILE_PICKER_EXPORTER_H + +#pragma once + +#include "ability.h" + +#include "../common/napi/n_exporter.h" +#include "file_info.h" +#include "root_info.h" +#include "storage_ability.h" + +namespace OHOS { +namespace DistributedFS { +namespace ModuleFPExpoter { +struct MkdirAsyncInfo { + napi_async_work asyncWork = nullptr; + napi_deferred defer = nullptr; + napi_ref callback[3] = { nullptr }; + std::string path = ""; + int err = 0; +}; + +struct SaveFileAsyncInfo { + napi_async_work asyncWork = nullptr; + napi_deferred defer = nullptr; + napi_ref callback[3] = { nullptr }; + std::string dstPath = ""; + size_t srcLen = 0; + int err = 0; + std::vector srcPath; + std::vector saveFileList; +}; + +struct SearchFileAsyncInfo { + napi_async_work asyncWork = nullptr; + napi_deferred defer = nullptr; + napi_ref callback[3] = { nullptr }; + std::string path = ""; + std::string name = ""; + int err = 0; + std::vector fileInfoList; +}; + +struct ListAsyncInfo { + napi_async_work asyncWork = nullptr; + napi_deferred defer = nullptr; + napi_ref callback[3] = { nullptr }; + std::string path = ""; + int err = 0; + std::vector fileInfoList; +}; + +struct GetDeviceAsyncInfo { + napi_async_work asyncWork = nullptr; + napi_deferred defer = nullptr; + napi_ref callback[3] = { nullptr }; + int err = 0; + std::vector deviceInfoList; +}; + +class FilePickerExporter final : public NExporter { +public: + inline static const std::string className_ = "FilePicker"; + static napi_value Mkdir(napi_env env, napi_callback_info info); + static napi_value SaveFile(napi_env env, napi_callback_info info); + static napi_value SearchFile(napi_env env, napi_callback_info info); + static napi_value List(napi_env env, napi_callback_info info); + static napi_value GetDeviceInfo(napi_env env, napi_callback_info info); + + bool Export() override; + + std::string GetClassName() override; + + FilePickerExporter(napi_env env, napi_value exports); + ~FilePickerExporter() override; +}; +} // namespace ModuleFMSExpoter +} // namespace DistributedFS +} // namespace OHOS + +#endif // STORAGE_DISKMGR_INTERFACE_KITS_NAPI_DSM_FILE_PICKER_EXPORTER_H \ No newline at end of file diff --git a/interfaces/kits/napi/file_picker_service/module.cpp b/interfaces/kits/napi/file_picker_service/module.cpp new file mode 100644 index 0000000000000000000000000000000000000000..2e70b09171b2be8aa21cdbcec6d811fc9400485c --- /dev/null +++ b/interfaces/kits/napi/file_picker_service/module.cpp @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2021-2022 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. + */ +#include "module.h" + +#include +#include + +#include "../common/log.h" +#include "file_picker_exporter.h" + +using namespace std; + +namespace OHOS { +namespace DistributedFS { +namespace ModuleFPExpoter { +static napi_value Export(napi_env env, napi_value exports) +{ + std::vector> products; + products.emplace_back(make_unique(env, exports)); + + for (auto &&product : products) { + if (!product->Export()) { + HILOGE("INNER BUG. Failed to export class %{public}s for module filepicker", + product->GetClassName().c_str()); + return nullptr; + } else { + HILOGE("Class %{public}s for module file has been exported", product->GetClassName().c_str()); + } + } + return exports; +} + +NAPI_MODULE(filepicker, Export) +} // namespace ModuleFMSExpoter +} // namespace DistributedFS +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/napi/file_picker_service/module.h b/interfaces/kits/napi/file_picker_service/module.h new file mode 100644 index 0000000000000000000000000000000000000000..cb43d859f4dd60a171c15726498572e7afc5f39a --- /dev/null +++ b/interfaces/kits/napi/file_picker_service/module.h @@ -0,0 +1,18 @@ +/* + * Copyright (c) 2021-2022 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. + */ +#ifndef STORAGE_DISKMGR_INTERFACE_KITS_NAPI_FPS_MODULE_H +#define STORAGE_DISKMGR_INTERFACE_KITS_NAPI_FPS_MODULE_H + +#endif // STORAGE_DISKMGR_INTERFACE_KITS_NAPI_FPS_MODULE_H \ No newline at end of file diff --git a/interfaces/kits/napi/file_share_ability/file_share_exporter.cpp b/interfaces/kits/napi/file_share_ability/file_share_exporter.cpp new file mode 100644 index 0000000000000000000000000000000000000000..191b87d901969436e49b587b37be6d7b1a3095ee --- /dev/null +++ b/interfaces/kits/napi/file_share_ability/file_share_exporter.cpp @@ -0,0 +1,278 @@ +/* + * Copyright (c) 2021-2022 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. + */ + +#include "file_share_exporter.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "../common/ability_helper.h" +#include "../common/common_func.h" +#include "../common/napi/n_class.h" +#include "../common/napi/n_func_arg.h" +#include "../common/napi/n_val.h" +#include "../common/uni_error.h" +#include "file_share_ability.h" +#include "uri.h" + +using Uri = OHOS::Uri; +using namespace std; +namespace OHOS { +namespace DistributedFS { +namespace ModuleFMSExpoter { +const int OTHER_ARGUMENT_ERROR = 202; +const int URI_PARAMER_ERROR = 302; +const int FILE_IO_ERROR = 300; +const int FILE_PATH_ERROR = 301; +const int SUCCESS = 0; +const int FAILED = -1; +enum COMMON_NUM { + ZERO = 0, + ONE = 1, + TWO = 2, + THREE = 3, +}; + +void CallBackSuccess(napi_env env, napi_ref successFuncRef, int32_t count, napi_value obj) +{ + napi_value results = nullptr; + napi_value successFunc = nullptr; + napi_value global = nullptr; + napi_get_global(env, &global); + napi_get_reference_value(env, successFuncRef, &successFunc); + if (successFunc == nullptr) { + return; + } + napi_call_function(env, global, successFunc, count, &obj, &results); +} + +void CallBackError(napi_env env, napi_ref failFuncRef, string errorProp, int errorCode) +{ + napi_value argvFail[2] = { 0 }; + napi_value results = nullptr; + napi_value failFunc = nullptr; + napi_value global = nullptr; + napi_get_global(env, &global); + argvFail[0] = NVal::CreateUTF8String(env, errorProp).val_; + argvFail[1] = NVal::CreateInt32(env, errorCode).val_; + napi_get_reference_value(env, failFuncRef, &failFunc); + if (failFunc == nullptr) { + return; + } + napi_call_function(env, global, failFunc, COMMON_NUM::TWO, argvFail, &results); +} + +void CallComplete(napi_env env, napi_ref completeFuncRef) +{ + napi_value completeFunc = nullptr; + napi_value results = nullptr; + napi_value global = nullptr; + napi_get_global(env, &global); + napi_get_reference_value(env, completeFuncRef, &completeFunc); + if (completeFunc == nullptr) { + return; + } + napi_call_function(env, global, completeFunc, COMMON_NUM::ZERO, nullptr, &results); +} + +bool CheckUri(AppExecFwk::Ability *ability, napi_env env, string &path) +{ + string pathOrigin = path; + vector uriSplit; + string pattern = "/"; + if (path == "") { + return false; + } + string pathTmp = pathOrigin + pattern; + size_t pos = pathTmp.find(pattern); + while (pos != pathTmp.npos) { + string temp = pathTmp.substr(COMMON_NUM::ZERO, pos); + uriSplit.push_back(temp); + pathTmp = pathTmp.substr(pos + 1, pathTmp.size()); + pos = pathTmp.find(pattern); + } + if (uriSplit[COMMON_NUM::ZERO] != "internal:" || uriSplit[COMMON_NUM::ONE] != "" || + uriSplit.size() <= COMMON_NUM::TWO) { + return false; + } + if (uriSplit[COMMON_NUM::TWO] == "app") { + path = ability->GetDataDir(); + } else if (uriSplit[COMMON_NUM::TWO] == "cache") { + path = ability->GetCacheDir(); + } else { + return false; + } + for (size_t i = COMMON_NUM::THREE; i < uriSplit.size(); ++i) { + path = path + "/" + uriSplit[i]; + } + return true; +} + +int GetRealPath(string &path) +{ + unique_ptr absPath = make_unique(PATH_MAX + 1); + if (realpath(path.c_str(), absPath.get()) == nullptr) { + return errno; + } + path = absPath.get(); + return SUCCESS; +} + +void CallbackUriResult(napi_env env, napi_ref napiFailFun, napi_ref napiSuccFun, string uriRet) +{ + if (uriRet == "") { + CallBackError(env, napiFailFun, "error: fuzzyFileToUri failed", FILE_IO_ERROR); + } else if (uriRet == "ERROR_AUTHORITY") { + CallBackError(env, napiFailFun, "error: authority is not exist", OTHER_ARGUMENT_ERROR); + } else if (uriRet == "ERROR_JSON_CONFIG") { + CallBackError(env, napiFailFun, "error: invalid json config", FILE_IO_ERROR); + } else { + CallBackSuccess(env, napiSuccFun, COMMON_NUM::ONE, NVal::CreateUTF8String(env, uriRet).val_); + } +} + +int CheckArgumentsError(napi_env env, napi_ref napiFailFun, string deviceIdStr, string authorityStr) +{ + if (deviceIdStr == "" || authorityStr == "") { + CallBackError(env, napiFailFun, "error: illegal arguments", OTHER_ARGUMENT_ERROR); + return FAILED; + } + return SUCCESS; +} + +int CheckUriError(napi_env env, napi_ref napiFailFun, AppExecFwk::Ability *ability, int checkPathResult, string path) +{ + if (!checkPathResult) { + CallBackError(env, napiFailFun, "error: illegal uri", URI_PARAMER_ERROR); + return FAILED; + } else if (path.find(ability->GetDataDir()) != 0 && path.find(ability->GetCacheDir()) != 0) { + CallBackError(env, napiFailFun, "error: uri cannot out of this package", URI_PARAMER_ERROR); + return FAILED; + } + return SUCCESS; +} + +int CheckFilePathError(napi_env env, napi_ref napiFailFun, int realPathResult) +{ + if (realPathResult == ENOENT) { + CallBackError(env, napiFailFun, "error: file or directory not exist", FILE_PATH_ERROR); + return FAILED; + } + return SUCCESS; +} + +int CheckIOError(napi_env env, napi_ref napiFailFun, int realPathResult, string path) +{ + struct stat buf; + if (realPathResult != SUCCESS) { + CallBackError(env, napiFailFun, "error: invalid uri", FILE_IO_ERROR); + return FAILED; + } else if (stat(path.c_str(), &buf) != SUCCESS || (buf.st_mode & S_IFMT) != S_IFREG) { + CallBackError(env, napiFailFun, "error: uri cannot be a directory", FILE_IO_ERROR); + return FAILED; + } + return SUCCESS; +} + +napi_value FileShareExporter::FuzzyFileToUri(napi_env env, napi_callback_info info) +{ + NFuncArg funcArg(env, info); + if (!funcArg.InitArgs(NARG_CNT::ONE)) { + UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); + return nullptr; + } + bool succ = false; + napi_ref napiSuccFun, napiCompFun, napiFailFun; + tie(succ, napiSuccFun, napiFailFun, napiCompFun) = + CommonFunc::GetCallbackHandles(env, funcArg[NARG_POS::FIRST]); + + unique_ptr uri = nullptr; + tie(succ, uri, ignore) = NVal(env, funcArg[NARG_POS::FIRST]).GetProp("uri").ToUTF8String(); + + unique_ptr deviceId = nullptr; + tie(succ, deviceId, ignore) = NVal(env, funcArg[NARG_POS::FIRST]).GetProp("deviceId").ToUTF8String(); + + unique_ptr authority = nullptr; + tie(succ, authority, ignore) = NVal(env, funcArg[NARG_POS::FIRST]).GetProp("authority").ToUTF8String(); + + unique_ptr displayname = nullptr; + tie(succ, displayname, ignore) = + NVal(env, funcArg[NARG_POS::FIRST]).GetProp("displayName").ToUTF8String(); + string path = (uri == nullptr) ? "" : uri.get(); + string deviceIdStr = (deviceId == nullptr) ? "" : deviceId.get(); + string authorityStr = (authority == nullptr) ? "" : authority.get(); + string displaynameStr = (displayname == nullptr) ? "" : displayname.get(); + + AppExecFwk::Ability *ability = AbilityHelper::GetJsAbility(env); + if (ability == nullptr) { + return nullptr; + } + bool checkPathResult = CheckUri(ability, env, path); + int realPathResult = GetRealPath(path); + if (CheckArgumentsError(env, napiFailFun, deviceIdStr, authorityStr) == FAILED || + CheckUriError(env, napiFailFun, ability, checkPathResult, path) == FAILED || + CheckFilePathError(env, napiFailFun, realPathResult) == FAILED || + CheckIOError(env, napiFailFun, realPathResult, path) == FAILED) { + CallComplete(env, napiCompFun); + napi_delete_reference(env, napiSuccFun); + napi_delete_reference(env, napiFailFun); + napi_delete_reference(env, napiCompFun); + return nullptr; + } + + Uri uriObj(""); + uriObj = FileManager::FileShareAbility::FuzzyFileToUri(ability, deviceIdStr, authorityStr, path, displaynameStr); + + string uriRet = uriObj.ToString(); + CallbackUriResult(env, napiFailFun, napiSuccFun, uriRet); + + CallComplete(env, napiCompFun); + napi_delete_reference(env, napiSuccFun); + napi_delete_reference(env, napiFailFun); + napi_delete_reference(env, napiCompFun); + return NVal::CreateUndefined(env).val_; +} + +bool FileShareExporter::Export() +{ + return exports_.AddProp({ + NVal::DeclareNapiFunction("fuzzyFileToUri", FuzzyFileToUri), + }); +} + +string FileShareExporter::GetClassName() +{ + return FileShareExporter::className_; +} + +FileShareExporter::FileShareExporter(napi_env env, napi_value exports) + : NExporter(env, exports) +{} + +FileShareExporter::~FileShareExporter() {} +} // namespace ModuleFMSExpoter +} // namespace DistributedFS +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/napi/file_share_ability/file_share_exporter.h b/interfaces/kits/napi/file_share_ability/file_share_exporter.h new file mode 100644 index 0000000000000000000000000000000000000000..593653625fd9126c8532e11d9cce243241960f3e --- /dev/null +++ b/interfaces/kits/napi/file_share_ability/file_share_exporter.h @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2021-2022 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. + */ +#ifndef STORAGE_DISKMGR_INTERFACE_KITS_NAPI_DSM_FILE_SHARE_EXPORTER_H +#define STORAGE_DISKMGR_INTERFACE_KITS_NAPI_DSM_FILE_SHARE_EXPORTER_H + +#pragma once + +#include "../common/napi/n_exporter.h" + +namespace OHOS { +namespace DistributedFS { +namespace ModuleFMSExpoter { +class FileShareExporter final : public NExporter { +public: + inline static const std::string className_ = "FileShare"; + static napi_value FuzzyFileToUri(napi_env env, napi_callback_info info); + + bool Export() override; + + std::string GetClassName() override; + + FileShareExporter(napi_env env, napi_value exports); + ~FileShareExporter() override; +}; +} // namespace ModuleFMSExpoter +} // namespace DistributedFS +} // namespace OHOS + +#endif // STORAGE_DISKMGR_INTERFACE_KITS_NAPI_DSM_FILE_SHARE_EXPORTER_H \ No newline at end of file diff --git a/interfaces/kits/napi/file_share_ability/module.cpp b/interfaces/kits/napi/file_share_ability/module.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1980fe8ea270b348d4d4b321c50ff9cabb017556 --- /dev/null +++ b/interfaces/kits/napi/file_share_ability/module.cpp @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2021-2022 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. + */ +#include "module.h" + +#include +#include + +#include "../common/log.h" +#include "file_share_exporter.h" + +using namespace std; + +namespace OHOS { +namespace DistributedFS { +namespace ModuleFMSExpoter { +static napi_value Export(napi_env env, napi_value exports) +{ + std::vector> products; + products.emplace_back(make_unique(env, exports)); + + for (auto &&product : products) { + if (!product->Export()) { + HILOGE("INNER BUG. Failed to export class %{public}s for module file", + product->GetClassName().c_str()); + return nullptr; + } else { + HILOGE("Class %{public}s for module file has been exported", product->GetClassName().c_str()); + } + } + return exports; +} + +NAPI_MODULE(fileshare, Export) +} // namespace ModuleFMSExpoter +} // namespace DistributedFS +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/napi/file_share_ability/module.h b/interfaces/kits/napi/file_share_ability/module.h new file mode 100644 index 0000000000000000000000000000000000000000..037ab199739d3c32ae26d30cd5ddc98e7cd39ee4 --- /dev/null +++ b/interfaces/kits/napi/file_share_ability/module.h @@ -0,0 +1,18 @@ +/* + * Copyright (c) 2021-2022 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. + */ +#ifndef STORAGE_DISKMGR_INTERFACE_KITS_NAPI_FSA_MODULE_H +#define STORAGE_DISKMGR_INTERFACE_KITS_NAPI_FSA_MODULE_H + +#endif // STORAGE_DISKMGR_INTERFACE_KITS_NAPI_FSA_MODULE_H \ No newline at end of file diff --git a/interfaces/kits/native/BUILD.gn b/interfaces/kits/native/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..b700811c7cfa55a02193c7390d128ae2e9eddd00 --- /dev/null +++ b/interfaces/kits/native/BUILD.gn @@ -0,0 +1,43 @@ +# Copyright (c) 2022 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("//build/ohos.gni") + +config("remote_uri_config") { + visibility = [ ":*" ] + include_dirs = [ + "include", + "//utils/system/safwk/native/include", + "//commonlibrary/c_utils/base/include", + "//foundation/filemanagement/file_api/interfaces/kits/native/remote_uri", + ] +} + +ohos_shared_library("remote_uri_native") { + sources = [ "//foundation/filemanagement/file_api/interfaces/kits/native/remote_uri/remote_uri.cpp" ] + + public_configs = [ ":remote_uri_config" ] + + external_deps = [ + "access_token:libaccesstoken_sdk", + "c_utils:utils", + "ipc:ipc_core", + ] + + part_name = "file_api" + subsystem_name = "filemanagement" +} + +group("build_kits_native") { + deps = [ ":remote_uri_native" ] +} diff --git a/interfaces/kits/native/remote_uri/remote_uri.cpp b/interfaces/kits/native/remote_uri/remote_uri.cpp new file mode 100644 index 0000000000000000000000000000000000000000..11757682927d46b74c7823f40a272ea257fd0c1c --- /dev/null +++ b/interfaces/kits/native/remote_uri/remote_uri.cpp @@ -0,0 +1,90 @@ +/* + * Copyright (c) 2022 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. + */ + +#include "remote_uri.h" +#include +#include +#include +#include +#include "accesstoken_kit.h" +#include "ipc_skeleton.h" +#include "hap_token_info.h" + +namespace OHOS { +namespace DistributedFS { +namespace ModuleRemoteUri { +namespace { + const std::string FRAGMENT_TAG = "#"; + const std::string FD_TAG = "="; + const std::string REMOTE_URI_TAG = "fdFromBinder"; + const std::string SCHEME_TAG = ":"; + const std::string SCHEME = "datashare"; +} + +static std::string GetCallingPkgName() +{ + uint32_t pid = IPCSkeleton::GetCallingTokenID(); + Security::AccessToken::HapTokenInfo tokenInfo = Security::AccessToken::HapTokenInfo(); + Security::AccessToken::AccessTokenKit::GetHapTokenInfo(pid, tokenInfo); + return tokenInfo.bundleName; +} + +bool RemoteUri::IsRemoteUri(const std::string& path, int &fd, const int& flags) +{ + std::string::size_type posDatashare = path.find(SCHEME_TAG); + std::string::size_type posFragment = path.find(FRAGMENT_TAG); + std::string::size_type posFd = path.find(FD_TAG); + if (posDatashare == std::string::npos || posFragment == std::string::npos || + posFd == std::string::npos) { + return false; + } + + std::string scheme = path.substr(0, posDatashare); + if (scheme != SCHEME) { + return false; + } + + std::string fragment = path.substr(posFragment + 1, REMOTE_URI_TAG.size()); + if (fragment == REMOTE_URI_TAG) { + std::string fdStr = path.substr(posFd + 1); + fd = atoi(fdStr.c_str()); + if (fd < 0 || flags != O_RDONLY) { + fd = -1; + } + return true; + } + return false; +} + +int RemoteUri::ConvertUri(const int &fd, std::string &remoteUri) +{ + if (fd < 0) { + return EINVAL; + } + std::string pkgName = GetCallingPkgName(); + remoteUri = SCHEME + ":///" + pkgName + "/" + FRAGMENT_TAG + + REMOTE_URI_TAG + FD_TAG + std::to_string(fd); + return 0; +} + +int RemoteUri::OpenRemoteUri(const std::string &remoteUri) +{ + int fd = -1; + IsRemoteUri(remoteUri, fd); + return fd; +} +} // namespace ModuleRemoteUri +} // namespace DistributedFS +} // namespace OHOS diff --git a/interfaces/kits/native/remote_uri/remote_uri.h b/interfaces/kits/native/remote_uri/remote_uri.h new file mode 100644 index 0000000000000000000000000000000000000000..abf5d5ffa2a95d85ab526108c62a1d41dc546298 --- /dev/null +++ b/interfaces/kits/native/remote_uri/remote_uri.h @@ -0,0 +1,37 @@ +/* + * Copyright (c) 2022 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. + */ + +#ifndef REMOTE_URI_H +#define REMOTE_URI_H + +#include +#include + +namespace OHOS { +namespace DistributedFS { +namespace ModuleRemoteUri { +class RemoteUri { +public: + RemoteUri() {} + static bool IsRemoteUri(const std::string& path, int &fd, const int& flags = O_RDONLY); + static int ConvertUri(const int &fd, std::string &remoteUri); + static int OpenRemoteUri(const std::string &remoteUri); + ~RemoteUri() {} +}; +} // namespace ModuleRemoteUri +} // namespace DistributedFS +} // namespace OHOS + +#endif \ No newline at end of file diff --git a/interfaces/kits/native/storage_service/BUILD.gn b/interfaces/kits/native/storage_service/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..bfc356b56fc7e46569c26a11ef22f2ed3c05f129 --- /dev/null +++ b/interfaces/kits/native/storage_service/BUILD.gn @@ -0,0 +1,37 @@ +# Copyright (c) 2021-2022 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("//build/ohos.gni") + +ohos_shared_library("ss_crypto_api") { + sources = [ "ss_crypto_api.cpp" ] + include_dirs = [ + "include", + "//foundation/systemabilitymgr/samgr/interfaces/innerkits/samgr_proxy/include", + "//third_party/openssl/include/openssl", + "//base/security/huks/interfaces/innerkits/huks_standard/main/include", + "//utils/system/safwk/native/include", + "//third_party/json/include", + "//commonlibrary/c_utils/base/include", + "//third_party/openssl/include", + ] + external_deps = [ + "ability_base:want", + "c_utils:utils", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + "safwk:system_ability_fwk", + "samgr:samgr_proxy", + ] + subsystem_name = "filemanagement" +} diff --git a/interfaces/kits/native/storage_service/ss_crypto_api.cpp b/interfaces/kits/native/storage_service/ss_crypto_api.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a3bd4a939384052e92f1cfb88429261eb7313aae --- /dev/null +++ b/interfaces/kits/native/storage_service/ss_crypto_api.cpp @@ -0,0 +1,224 @@ +/* + * Copyright (c) 2021-2022 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. + */ +#include "ss_crypto_api.h" + +#include +#include + +#include "fbe_crypto.h" +#include "istorage_service.h" +#include "storage_hilog.h" +#include "storage_service_proxy.h" + +namespace OHOS { +const int SCA_ERR_NONE = 0; + +sptr g_cryptoProxy = nullptr; + +bool GetCryptoProxy() +{ + if (g_cryptoProxy != nullptr) { + return true; + } + SSLOG_E("SS_request::Connect start"); + if (g_cryptoProxy == nullptr) { + auto sam = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + if (sam == nullptr) { + SSLOG_E("SS_request::Connect samgr == nullptr"); + return false; + } + auto object = sam->GetSystemAbility(STORAGE_SERVICE_ID); + if (object == nullptr) { + SSLOG_E("SS_request::Connect object == nullptr"); + return false; + } + g_cryptoProxy = iface_cast(object); + if (g_cryptoProxy == nullptr) { + SSLOG_E("SS_request::Connect service == nullptr"); + return false; + } + } + SSLOG_E("DeviceStorageManager::Connect end"); + return true; +} + +int32_t SsCryptoEnable() +{ + SSLOG_I("CryptoEnable starting....(from gby)"); + if (g_cryptoProxy == nullptr) { + SSLOG_E("The mSsProxy is null..(from gby)"); + return SCA_ERR_NONE; + } + g_cryptoProxy->CryptoEnable(); + SSLOG_I("CryptoEnable end....(from gby)"); + return 0; +} + +int32_t SsCryptoInitialize() +{ + SSLOG_I("CryptoInitialize starting....(from gby)"); + if (g_cryptoProxy == nullptr) { + SSLOG_E("The mSsProxy is null.."); + return SCA_ERR_NONE; + } + g_cryptoProxy->CryptoInitialize(); + SSLOG_I("CryptoInitialize end....(from gby)"); + return 0; +} + +int32_t SsCryptoCreateKey(int32_t userId) +{ + SSLOG_I("CryptoCreateKey starting....(from gby)"); + if (g_cryptoProxy == nullptr) { + SSLOG_E("The mSsProxy is null.."); + return SCA_ERR_NONE; + } + if (userId <= 0) { + SSLOG_E("The input userId is illegal"); + return SCA_ERR_NONE; + } + g_cryptoProxy->CryptoCreateKey(userId); + SSLOG_I("CryptoCreateKey end....(from gby)"); + return 0; +} + +int32_t SsCryptoDeleteKey(int32_t userId) +{ + SSLOG_I("CryptoDeleteKey starting....(from gby)"); + if (g_cryptoProxy == nullptr) { + SSLOG_E("The mSsProxy is null.."); + return SCA_ERR_NONE; + } + if (userId <= 0) { + SSLOG_E("The input userId is illegal"); + return SCA_ERR_NONE; + } + g_cryptoProxy->CryptoDeleteKey(userId); + SSLOG_I("CryptoDeleteKey end....(from gby)"); + return 0; +} + +int32_t SsCryptoAddAuthKey(int32_t userId, const std::string &token, const std::string &secret) +{ + SSLOG_I("CryptoAddAuthKey starting....(from gby)"); + if (g_cryptoProxy == nullptr) { + SSLOG_E("The mSsProxy is null.."); + return SCA_ERR_NONE; + } + if (userId <= 0) { + SSLOG_E("The input userId is illegal"); + return SCA_ERR_NONE; + } + g_cryptoProxy->CryptoAddAuthKey(userId, token, secret); + SSLOG_I("CryptoAddAuthKey end....(from gby)"); + return 0; +} + +int32_t SsCryptoDelAuthKey(int32_t userId, const std::string &token, const std::string &secret) +{ + SSLOG_I("CryptoDelAuthKey starting....(from gby)"); + if (g_cryptoProxy == nullptr) { + SSLOG_E("The mSsProxy is null.."); + return SCA_ERR_NONE; + } + if (userId <= 0) { + SSLOG_E("The input userId is illegal"); + return SCA_ERR_NONE; + } + g_cryptoProxy->CryptoDelAuthKey(userId, token, secret); + SSLOG_I("CryptoDelAuthKey end....(from gby)"); + return 0; +} + +int32_t SsCryptoUnlockKey(int32_t userId, const std::string &token, const std::string &secret) +{ + SSLOG_I("CryptoUnlockKey starting....(from gby)"); + if (g_cryptoProxy == nullptr) { + SSLOG_E("The mSsProxy is null.."); + return SCA_ERR_NONE; + } + if (userId <= 0) { + SSLOG_E("The input userId is illegal"); + return SCA_ERR_NONE; + } + g_cryptoProxy->CryptoUnlockKey(userId, token, secret); + SSLOG_I("CryptoUnlockKey end....(from gby)"); + return 0; +} + +int32_t SsCryptoLockKey(int32_t userId) +{ + SSLOG_I("CryptoLockKey starting....(from gby)"); + if (g_cryptoProxy == nullptr) { + SSLOG_E("The mSsProxy is null.."); + return SCA_ERR_NONE; + } + if (userId <= 0) { + SSLOG_E("The input userId is illegal"); + return SCA_ERR_NONE; + } + g_cryptoProxy->CryptoLockKey(userId); + SSLOG_I("CryptoLockKey end....(from gby)"); + return 0; +} + +int32_t SsCryptoUpdateAuthKey(int32_t userId, const std::string &token, const std::string secret) +{ + SSLOG_I("CryptoUpdateAuthKey starting....(from gby)"); + if (g_cryptoProxy == nullptr) { + SSLOG_E("The mSsProxy is null.."); + return SCA_ERR_NONE; + } + if (userId <= 0) { + SSLOG_E("The input userId is illegal"); + return SCA_ERR_NONE; + } + g_cryptoProxy->CryptoUpdateAuthKey(userId, token, secret); + SSLOG_I("CryptoUpdateAuthKey end....(from gby)"); + return 0; +} + +int32_t SsCryptoInitUserSpace(const std::string &uuid, int32_t userid, int32_t flag) +{ + SSLOG_I("CryptoCreatePaths starting....(from gby)"); + if (g_cryptoProxy == nullptr) { + SSLOG_E("The mSsProxy is null.."); + return SCA_ERR_NONE; + } + if (userid <= 0) { + SSLOG_E("The input userId is illegal"); + return SCA_ERR_NONE; + } + g_cryptoProxy->CryptoInitUserSpace(uuid, userid, flag); + SSLOG_I("CryptoCreatePaths end....(from gby)"); + return 0; +} + +int32_t SsCryptoRemoveUserSpace(const std::string &uuid, int32_t userid, int32_t flag) +{ + SSLOG_I("CryptoRemovePaths starting....(from gby)"); + if (g_cryptoProxy == nullptr) { + SSLOG_E("The mSsProxy is null.."); + return SCA_ERR_NONE; + } + if (userid <= 0) { + SSLOG_E("The input userId is illegal"); + return SCA_ERR_NONE; + } + g_cryptoProxy->CryptoRemoveUserSpace(uuid, userid, flag); + SSLOG_I("CryptoRemovePaths end....(from gby)"); + return 0; +} +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/native/storage_service/ss_crypto_api.h b/interfaces/kits/native/storage_service/ss_crypto_api.h new file mode 100644 index 0000000000000000000000000000000000000000..79ca3e7570f196cbc3549ed22e823f1095ba6fb7 --- /dev/null +++ b/interfaces/kits/native/storage_service/ss_crypto_api.h @@ -0,0 +1,18 @@ +/* + * Copyright (c) 2021-2022 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. + */ +#ifndef STORAGE_DISKMGR_INTERFACE_KITS_NATIVE_SS_CRYPTO_API_H +#define STORAGE_DISKMGR_INTERFACE_KITS_NATIVE_SS_CRYPTO_API_H + +#endif // STORAGE_DISKMGR_INTERFACE_KITS_NATIVE_SS_CRYPTO_API_H \ No newline at end of file diff --git a/utils/filemgmt_libn/include/filemgmt_libn.h b/utils/filemgmt_libn/include/filemgmt_libn.h index 28b1a8e856ef381ba9c5f58df8a34f824e584cac..01ac9396d193f84e8488f0a5910cd206546bbf61 100644 --- a/utils/filemgmt_libn/include/filemgmt_libn.h +++ b/utils/filemgmt_libn/include/filemgmt_libn.h @@ -18,6 +18,7 @@ #include "n_async_work_callback.h" #include "n_async_work_promise.h" +#include "n_class.h" #include "n_error.h" #include "n_exporter.h" #include "n_func_arg.h" diff --git a/utils/filemgmt_libn/include/n_async/n_async_context.h b/utils/filemgmt_libn/include/n_async/n_async_context.h index 2d0b206aab93238a54fa22554a977bac56a379a3..fb092495548b8f05b35087afe38a25c19c35bdb0 100644 --- a/utils/filemgmt_libn/include/n_async/n_async_context.h +++ b/utils/filemgmt_libn/include/n_async/n_async_context.h @@ -57,6 +57,18 @@ public: NAsyncContextCallback(NVal thisPtr, NVal cb) : NAsyncContext(thisPtr), cb_(cb) {} ~NAsyncContextCallback() = default; }; + +class NAsyncContextLegacy : public NAsyncContext { +public: + NRef cbSucc_; + NRef cbFail_; + NRef cbFinal_; + NAsyncContextLegacy(NVal thisPtr, NVal cbSucc, NVal cbFail, NVal cbFinal) + : NAsyncContext(thisPtr), cbSucc_(cbSucc), cbFail_(cbFail), cbFinal_(cbFinal) + { + } + ~NAsyncContextLegacy() = default; +}; } // namespace LibN } // namespace FileManagement } // namespace OHOS diff --git a/utils/filemgmt_libn/include/n_async/n_async_work_callback.h b/utils/filemgmt_libn/include/n_async/n_async_work_callback.h index 66af8fbf898c0866876ae8a373e989180b3a7be0..938a2d7099bd06ebdcb4450a0f274fba92967a2e 100644 --- a/utils/filemgmt_libn/include/n_async/n_async_work_callback.h +++ b/utils/filemgmt_libn/include/n_async/n_async_work_callback.h @@ -25,6 +25,7 @@ class NAsyncWorkCallback : public NAsyncWork { public: NAsyncWorkCallback(napi_env env, NVal thisPtr, NVal cb); ~NAsyncWorkCallback() = default; + NVal Schedule(std::string procedureName, NContextCBExec cbExec, NContextCBComplete cbComplete) final; private: diff --git a/utils/filemgmt_libn/include/n_async/n_async_work_promise.h b/utils/filemgmt_libn/include/n_async/n_async_work_promise.h index da8bc723ee64a5a4ee147facfb5e6f398ee4118b..8f67f0c18a6ec329f2a75e3e4c8ab6fb315035fb 100644 --- a/utils/filemgmt_libn/include/n_async/n_async_work_promise.h +++ b/utils/filemgmt_libn/include/n_async/n_async_work_promise.h @@ -16,7 +16,13 @@ #ifndef FILEMGMT_LIBN_N_ASYNC_WORK_PROMISE_H #define FILEMGMT_LIBN_N_ASYNC_WORK_PROMISE_H +#include + +#include "node_api.h" +#include "js_native_api_types.h" +#include "n_async_context.h" #include "n_async_work.h" +#include "n_val.h" namespace OHOS { namespace FileManagement { @@ -25,6 +31,7 @@ class NAsyncWorkPromise : public NAsyncWork { public: NAsyncWorkPromise(napi_env env, NVal thisPtr); ~NAsyncWorkPromise() = default; + NVal Schedule(std::string procedureName, NContextCBExec cbExec, NContextCBComplete cbComplete) final; private: diff --git a/utils/filemgmt_libn/include/n_async/n_ref.h b/utils/filemgmt_libn/include/n_async/n_ref.h index 83cc6a666671fb30f9252649376c7f5e600f39c4..f78e1aca443b0dad6dfb2ccfba3a78e088cf7960 100644 --- a/utils/filemgmt_libn/include/n_async/n_ref.h +++ b/utils/filemgmt_libn/include/n_async/n_ref.h @@ -16,6 +16,8 @@ #ifndef FILEMGMT_LIBN_N_REF_H #define FILEMGMT_LIBN_N_REF_H +#include "node_api.h" +#include "js_native_api_types.h" #include "n_val.h" namespace OHOS { @@ -26,6 +28,7 @@ public: NRef(); NRef(NVal val); ~NRef(); + explicit operator bool() const; NVal Deref(napi_env env); diff --git a/utils/filemgmt_libn/include/n_class.h b/utils/filemgmt_libn/include/n_class.h index b4ec8c75a5cd791821e1abf213328ce8fe80e466..36254df57cf287b83f64159cf9dba64cbd18eb47 100644 --- a/utils/filemgmt_libn/include/n_class.h +++ b/utils/filemgmt_libn/include/n_class.h @@ -31,8 +31,9 @@ namespace FileManagement { namespace LibN { class NClass final { public: - NClass(const NClass&) = delete; - NClass &operator=(const NClass&) = delete; + NClass(const NClass &) = delete; + NClass &operator=(const NClass &) = delete; + static std::tuple DefineClass(napi_env env, std::string className, napi_callback constructor, diff --git a/utils/filemgmt_libn/include/n_error.h b/utils/filemgmt_libn/include/n_error.h index 82343d36715d30f58d70e29ff0b4b73f669280fd..0241fcc60df47dd545e9a647d423b9fbe1bc1b49 100644 --- a/utils/filemgmt_libn/include/n_error.h +++ b/utils/filemgmt_libn/include/n_error.h @@ -33,8 +33,11 @@ public: NError(int ePosix); NError(std::function()> errGen); ~NError() = default; + explicit operator bool() const; + napi_value GetNapiErr(napi_env env); + void ThrowErr(napi_env env); void ThrowErr(napi_env env, std::string errMsg); diff --git a/utils/filemgmt_libn/include/n_exporter.h b/utils/filemgmt_libn/include/n_exporter.h index 2734dc0c24b27e2ad4ed96b766b58621b151cc49..ec64e7aa219a1fd9aa42d182beea794567dccc70 100644 --- a/utils/filemgmt_libn/include/n_exporter.h +++ b/utils/filemgmt_libn/include/n_exporter.h @@ -30,6 +30,7 @@ class NExporter { public: NExporter(napi_env env, napi_value exports) : exports_(env, exports) {}; virtual ~NExporter() = default; + virtual bool Export() = 0; virtual std::string GetClassName() = 0; diff --git a/utils/filemgmt_libn/include/n_func_arg.h b/utils/filemgmt_libn/include/n_func_arg.h index a51b92475844e9c55630c34ff27a113941f742aa..271ad7a956c7b6907a661dde555c344307c8b8d7 100644 --- a/utils/filemgmt_libn/include/n_func_arg.h +++ b/utils/filemgmt_libn/include/n_func_arg.h @@ -28,17 +28,17 @@ namespace FileManagement { namespace LibN { enum NARG_CNT { ZERO = 0, - ONE, - TWO, - THREE, - FOUR, + ONE = 1, + TWO = 2, + THREE = 3, + FOUR = 4, }; enum NARG_POS { FIRST = 0, - SECOND, - THIRD, - FOURTH, + SECOND = 1, + THIRD = 2, + FOURTH = 3, }; class NFuncArg final { @@ -48,19 +48,23 @@ public: bool InitArgs(size_t argc); bool InitArgs(size_t minArgc, size_t maxArgc); + size_t GetArgc() const; napi_value GetThisVar() const; + napi_value operator[](size_t idx) const; napi_value GetArg(size_t argPos) const; private: napi_env env_ = nullptr; napi_callback_info info_ = nullptr; + size_t argc_ = 0; std::unique_ptr argv_ = {nullptr}; napi_value thisVar_ = nullptr; bool InitArgs(std::function argcChecker); + void SetArgc(size_t argc); void SetThisVar(napi_value thisVar); }; diff --git a/utils/filemgmt_libn/include/n_val.h b/utils/filemgmt_libn/include/n_val.h index 29f9597c06b9d82d2d80e8821234a36c5f7448fb..8b053f22b8d8ed9390bdd2b1259eac9655c4909e 100644 --- a/utils/filemgmt_libn/include/n_val.h +++ b/utils/filemgmt_libn/include/n_val.h @@ -34,7 +34,7 @@ public: NVal &operator=(const NVal &) = default; virtual ~NVal() = default; - /* NOTE! env_ and val_ is LIKELY to be null */ + // NOTE! env_ and val_ is LIKELY to be null napi_env env_ = nullptr; napi_value val_ = nullptr; @@ -51,6 +51,8 @@ public: std::tuple ToInt64() const; std::tuple ToArraybuffer() const; std::tuple ToTypedArray() const; + std::tuple, uint32_t> ToStringArray(); + std::tuple ToDouble() const; /* Static helpers to create js objects */ static NVal CreateUndefined(napi_env env); @@ -62,7 +64,6 @@ public: static NVal CreateUTF8String(napi_env env, const char *str, ssize_t len); static NVal CreateUint8Array(napi_env env, void *buf, size_t bufLen); static std::tuple CreateArrayBuffer(napi_env env, size_t len); - /* SHOULD ONLY BE USED FOR OBJECT */ bool HasProp(std::string propName) const; NVal GetProp(std::string propName) const; diff --git a/utils/filemgmt_libn/src/n_async/n_async_work_callback.cpp b/utils/filemgmt_libn/src/n_async/n_async_work_callback.cpp index 291d183d4798144d7b7e66c41f65c7eb22d6d8a3..f688e8daec3734a335b00444b34804f7579f95db 100644 --- a/utils/filemgmt_libn/src/n_async/n_async_work_callback.cpp +++ b/utils/filemgmt_libn/src/n_async/n_async_work_callback.cpp @@ -31,8 +31,6 @@ static void CallbackExecute(napi_env env, void *data) auto ctx = static_cast(data); if (ctx != nullptr && ctx->cbExec_ != nullptr) { ctx->err_ = ctx->cbExec_(); - } else { - HILOGE("Callback execute function, This pointer or function address is empty."); } } @@ -42,7 +40,6 @@ static void CallbackComplete(napi_env env, napi_status status, void *data) napi_open_handle_scope(env, &scope); auto ctx = static_cast(data); if (ctx == nullptr) { - HILOGE("This pointer address is empty"); return; } if (ctx->cbComplete_ != nullptr) { @@ -73,7 +70,7 @@ static void CallbackComplete(napi_env env, napi_status status, void *data) NVal NAsyncWorkCallback::Schedule(string procedureName, NContextCBExec cbExec, NContextCBComplete cbComplete) { if (!ctx_->cb_ || !ctx_->cb_.Deref(env_).TypeIs(napi_function)) { - NError(EINVAL).ThrowErr(env_, "The callback should be a function"); + NError(EINVAL).ThrowErr(env_, "The callback shall be a function"); return NVal(); } diff --git a/utils/filemgmt_libn/src/n_async/n_async_work_promise.cpp b/utils/filemgmt_libn/src/n_async/n_async_work_promise.cpp index 443c450efd521541549d5cfe136235f714c94765..979debf167869c3d66617f8caed3f6ca92fbf71a 100644 --- a/utils/filemgmt_libn/src/n_async/n_async_work_promise.cpp +++ b/utils/filemgmt_libn/src/n_async/n_async_work_promise.cpp @@ -14,7 +14,16 @@ */ #include "n_async_work_promise.h" + +#include +#include +#include +#include + #include "filemgmt_libhilog.h" +#include "js_native_api.h" +#include "n_error.h" +#include "node_api.h" namespace OHOS { namespace FileManagement { diff --git a/utils/filemgmt_libn/src/n_async/n_ref.cpp b/utils/filemgmt_libn/src/n_async/n_ref.cpp index bd5ebc900d645131e24dd36c71b14bf87a0bcadc..4e63a0444854089b221e6822cd7213b3d6f79b66 100644 --- a/utils/filemgmt_libn/src/n_async/n_ref.cpp +++ b/utils/filemgmt_libn/src/n_async/n_ref.cpp @@ -14,6 +14,7 @@ */ #include "n_ref.h" +#include "js_native_api.h" namespace OHOS { namespace FileManagement { diff --git a/utils/filemgmt_libn/src/n_class.cpp b/utils/filemgmt_libn/src/n_class.cpp index b8a76bd68d3675bdf72c321ebd02140394365085..7036fb619ef3ffe03c7aba91745662e11274468e 100644 --- a/utils/filemgmt_libn/src/n_class.cpp +++ b/utils/filemgmt_libn/src/n_class.cpp @@ -38,7 +38,6 @@ tuple NClass::DefineClass(napi_env env, if (stat != napi_ok) { HILOGE("INNER BUG. Cannot define class %{public}s because of %{public}d", className.c_str(), stat); } - return {stat == napi_ok, classVal}; } @@ -54,12 +53,11 @@ bool NClass::SaveClass(napi_env env, string className, napi_value exClass) napi_ref constructor; napi_status res = napi_create_reference(env, exClass, 1, &constructor); if (res == napi_ok) { - nClass.exClassMap.insert({className, constructor}); + nClass.exClassMap.insert( {className, constructor}); HILOGI("Class %{public}s has been saved", className.c_str()); } else { HILOGE("INNER BUG. Cannot ref class constructor %{public}s because of %{public}d", className.c_str(), res); } - return res == napi_ok; } @@ -87,7 +85,6 @@ napi_value NClass::InstantiateClass(napi_env env, const string& className, const HILOGE("INNER BUG. Cannot instantiate the class %{public}s because of %{public}d", className.c_str(), status); return nullptr; } - return instance; } } // namespace LibN diff --git a/utils/filemgmt_libn/src/n_val.cpp b/utils/filemgmt_libn/src/n_val.cpp index 2ac3b941d12a701f2e978ffc5aa29cc613b24af5..12358cecdaee7006c6ebbe6e0b3153394adcae91 100644 --- a/utils/filemgmt_libn/src/n_val.cpp +++ b/utils/filemgmt_libn/src/n_val.cpp @@ -124,6 +124,28 @@ tuple NVal::ToInt64() const return make_tuple(status == napi_ok, res); } +tuple NVal::ToDouble() const +{ + double res = 0; + napi_status status = napi_get_value_double(env_, val_, &res); + return make_tuple(status == napi_ok, res); +} + +tuple, uint32_t> NVal::ToStringArray() +{ + napi_status status; + uint32_t size; + status = napi_get_array_length(env_, val_, &size); + vector stringArray; + napi_value result; + for (uint32_t i = 0; i < size; i++) { + status = napi_get_element(env_, val_, i, &result); + auto [succ, str, ignore] = NVal(env_, result).ToUTF8String(); + stringArray.push_back(string(str.get())); + } + return make_tuple(status == napi_ok, stringArray, size); +} + tuple NVal::ToArraybuffer() const { void *buf = nullptr; @@ -148,10 +170,8 @@ bool NVal::HasProp(string propName) const { bool res = false; - if (!env_ || !val_ || !TypeIs(napi_object)) { + if (!env_ || !val_ || !TypeIs(napi_object)) return false; - } - napi_status status = napi_has_named_property(env_, val_, propName.c_str(), &res); return (status == napi_ok) && res; } @@ -161,7 +181,6 @@ NVal NVal::GetProp(string propName) const if (!HasProp(propName)) { return {env_, nullptr}; } - napi_value prop = nullptr; napi_status status = napi_get_named_property(env_, val_, propName.c_str(), &prop); if (status != napi_ok) { @@ -176,7 +195,6 @@ bool NVal::AddProp(vector &&propVec) const HILOGE("INNER BUG. Prop should only be added to objects"); return false; } - napi_status status = napi_define_properties(env_, val_, propVec.size(), propVec.data()); if (status != napi_ok) { HILOGE("INNER BUG. Cannot define properties because of %{public}d", status);