From 2a7f186e761d5131535a65d1773f644a9e612644 Mon Sep 17 00:00:00 2001 From: haonan Date: Wed, 6 Jul 2022 16:23:24 +0800 Subject: [PATCH 1/7] =?UTF-8?q?distributedfile=E4=BB=93=E8=BF=81=E7=A7=BB?= =?UTF-8?q?=E5=88=B0file=5Fapi?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: haonan --- .gitattributes | 15 + LICENSE | 351 ++-- README.md | 316 +++- README_zh.md | 285 ++- bundle.json | 43 + ...istributed-file-subsystem-architecture.png | Bin 0 -> 35168 bytes ...7\346\236\266\346\236\204\345\233\276.png" | Bin 0 -> 33139 bytes file_api_aafwk.gni | 15 + interfaces/innerkits/include/security_label.h | 72 +- interfaces/kits/js/BUILD.gn | 248 +++ interfaces/kits/js/napi/@ohos.document.d.ts | 63 + .../kits/js/napi/@ohos.environment.d.ts | 41 + interfaces/kits/js/napi/@ohos.fileio.d.ts | 1548 +++++++++++++++++ .../kits/js/napi/@ohos.securityLabel.d.ts | 59 + interfaces/kits/js/napi/@ohos.statfs.d.ts | 41 + interfaces/kits/js/napi/@system.file.d.ts | 752 ++++++++ .../kits/js/src/common/ability_helper.cpp | 2 +- .../kits/js/src/common/ability_helper.h | 7 +- .../js/src/common/file_helper/fd_guard.cpp | 75 + .../kits/js/src/common/file_helper/fd_guard.h | 47 + .../js/src/common/file_helper/hash_file.cpp | 106 ++ .../js/src/common/file_helper/hash_file.h | 32 + interfaces/kits/js/src/common/log.h | 12 +- .../src/common/napi/n_async/n_async_context.h | 4 +- .../napi/n_async/n_async_work_callback.cpp | 4 +- .../napi/n_async/n_async_work_callback.h | 2 +- .../napi/n_async/n_async_work_promise.cpp | 2 +- .../napi/n_async/n_async_work_promise.h | 2 +- .../kits/js/src/common/napi/n_class.cpp | 6 +- interfaces/kits/js/src/common/napi/n_class.h | 13 +- .../kits/js/src/common/napi/n_exporter.h | 11 +- .../kits/js/src/common/napi/n_func_arg.cpp | 5 +- .../kits/js/src/common/napi/n_func_arg.h | 12 +- interfaces/kits/js/src/common/napi/n_val.cpp | 17 +- interfaces/kits/js/src/common/napi/n_val.h | 4 +- .../kits/js/src/common/napi/uni_header.h | 6 +- interfaces/kits/js/src/common/uni_error.cpp | 4 +- interfaces/kits/js/src/common/uni_error.h | 10 +- .../src/mod_document/document_n_exporter.cpp | 2 + .../environment_n_exporter.cpp | 101 ++ .../mod_environment/environment_n_exporter.h | 29 + .../src/mod_environment/environment_napi.cpp | 41 + .../js/src/mod_environment/environment_napi.h | 27 + .../mod_file/class_file/file_n_exporter.cpp | 1323 ++++++++++++++ .../src/mod_file/class_file/file_n_exporter.h | 198 +++ .../kits/js/src/mod_file/common_func.cpp | 59 + interfaces/kits/js/src/mod_file/common_func.h | 33 + interfaces/kits/js/src/mod_file/module.cpp | 46 + .../mod_fileio/class_constants/constants.cpp | 189 ++ .../mod_fileio/class_constants/constants.h | 38 + .../js/src/mod_fileio/class_dir/dir_entity.h | 32 + .../mod_fileio/class_dir/dir_n_exporter.cpp | 308 ++++ .../src/mod_fileio/class_dir/dir_n_exporter.h | 45 + .../mod_fileio/class_dirent/dirent_entity.h | 30 + .../class_dirent/dirent_n_exporter.cpp | 172 ++ .../class_dirent/dirent_n_exporter.h | 49 + .../src/mod_fileio/class_stat/stat_entity.h | 30 + .../mod_fileio/class_stat/stat_n_exporter.cpp | 370 ++++ .../mod_fileio/class_stat/stat_n_exporter.h | 61 + .../js/src/mod_fileio/class_stream/flush.cpp | 101 ++ .../js/src/mod_fileio/class_stream/flush.h | 32 + .../mod_fileio/class_stream/stream_entity.h | 28 + .../class_stream/stream_n_exporter.cpp | 401 +++++ .../class_stream/stream_n_exporter.h | 48 + .../mod_fileio/class_watcher/watcher_entity.h | 47 + .../class_watcher/watcher_n_exporter.cpp | 148 ++ .../class_watcher/watcher_n_exporter.h | 43 + .../kits/js/src/mod_fileio/common_func.cpp | 232 +++ .../kits/js/src/mod_fileio/common_func.h | 40 + interfaces/kits/js/src/mod_fileio/module.cpp | 58 + .../js/src/mod_fileio/properties/chmod.cpp | 112 ++ .../kits/js/src/mod_fileio/properties/chmod.h | 32 + .../js/src/mod_fileio/properties/chown.cpp | 126 ++ .../kits/js/src/mod_fileio/properties/chown.h | 32 + .../js/src/mod_fileio/properties/close.cpp | 96 + .../kits/js/src/mod_fileio/properties/close.h | 32 + .../src/mod_fileio/properties/copy_file.cpp | 203 +++ .../js/src/mod_fileio/properties/copy_file.h | 32 + .../mod_fileio/properties/create_stream.cpp | 144 ++ .../src/mod_fileio/properties/create_stream.h | 32 + .../js/src/mod_fileio/properties/fchmod.cpp | 115 ++ .../js/src/mod_fileio/properties/fchmod.h | 32 + .../js/src/mod_fileio/properties/fchown.cpp | 123 ++ .../js/src/mod_fileio/properties/fchown.h | 32 + .../src/mod_fileio/properties/fdatasync.cpp | 102 ++ .../js/src/mod_fileio/properties/fdatasync.h | 32 + .../mod_fileio/properties/fdopen_stream.cpp | 146 ++ .../src/mod_fileio/properties/fdopen_stream.h | 32 + .../js/src/mod_fileio/properties/fstat.cpp | 128 ++ .../kits/js/src/mod_fileio/properties/fstat.h | 32 + .../js/src/mod_fileio/properties/fsync.cpp | 97 ++ .../kits/js/src/mod_fileio/properties/fsync.h | 32 + .../src/mod_fileio/properties/ftruncate.cpp | 119 ++ .../js/src/mod_fileio/properties/ftruncate.h | 32 + .../js/src/mod_fileio/properties/hash.cpp | 131 ++ .../kits/js/src/mod_fileio/properties/hash.h | 34 + .../js/src/mod_fileio/properties/lchown.cpp | 125 ++ .../js/src/mod_fileio/properties/lchown.h | 32 + .../js/src/mod_fileio/properties/link.cpp | 117 ++ .../kits/js/src/mod_fileio/properties/link.h | 32 + .../js/src/mod_fileio/properties/lseek.cpp | 128 ++ .../kits/js/src/mod_fileio/properties/lseek.h | 32 + .../js/src/mod_fileio/properties/lstat.cpp | 127 ++ .../kits/js/src/mod_fileio/properties/lstat.h | 32 + .../js/src/mod_fileio/properties/mkdtemp.cpp | 92 + .../js/src/mod_fileio/properties/mkdtemp.h | 32 + .../js/src/mod_fileio/properties/open.cpp | 148 ++ .../kits/js/src/mod_fileio/properties/open.h | 32 + .../js/src/mod_fileio/properties/open_dir.cpp | 137 ++ .../js/src/mod_fileio/properties/open_dir.h | 32 + .../mod_fileio/properties/posix_fallocate.cpp | 118 ++ .../mod_fileio/properties/posix_fallocate.h | 32 + .../mod_fileio/properties/prop_n_exporter.cpp | 758 ++++++++ .../mod_fileio/properties/prop_n_exporter.h | 66 + .../src/mod_fileio/properties/read_text.cpp | 211 +++ .../js/src/mod_fileio/properties/read_text.h | 44 + .../js/src/mod_fileio/properties/rename.cpp | 115 ++ .../js/src/mod_fileio/properties/rename.h | 31 + .../js/src/mod_fileio/properties/rmdir.cpp | 97 ++ .../kits/js/src/mod_fileio/properties/rmdir.h | 32 + .../js/src/mod_fileio/properties/stat.cpp | 127 ++ .../kits/js/src/mod_fileio/properties/stat.h | 32 + .../js/src/mod_fileio/properties/symlink.cpp | 116 ++ .../js/src/mod_fileio/properties/symlink.h | 32 + .../js/src/mod_fileio/properties/truncate.cpp | 113 ++ .../js/src/mod_fileio/properties/truncate.h | 35 + .../js/src/mod_fileio/properties/watcher.cpp | 107 ++ .../js/src/mod_fileio/properties/watcher.h | 35 + .../js/src/mod_securitylabel/security_label.h | 75 + .../securitylabel_n_exporter.cpp | 187 ++ .../securitylabel_n_exporter.h | 32 + .../mod_securitylabel/securitylabel_napi.cpp | 43 + .../mod_securitylabel/securitylabel_napi.h | 27 + .../js/src/mod_statfs/statfs_n_exporter.cpp | 162 +- .../js/src/mod_statfs/statfs_n_exporter.h | 2 +- .../kits/js/src/mod_statfs/statfs_napi.cpp | 5 +- .../kits/js/src/mod_statfs/statfs_napi.h | 2 +- interfaces/kits/napi/BUILD.gn | 138 ++ .../kits/napi/common/ability_helper.cpp | 54 + interfaces/kits/napi/common/ability_helper.h | 29 + interfaces/kits/napi/common/common_func.cpp | 57 + interfaces/kits/napi/common/common_func.h | 34 + interfaces/kits/napi/common/log.h | 92 + interfaces/kits/napi/common/napi/n_class.cpp | 100 ++ interfaces/kits/napi/common/napi/n_class.h | 81 + interfaces/kits/napi/common/napi/n_exporter.h | 40 + .../kits/napi/common/napi/n_func_arg.cpp | 107 ++ interfaces/kits/napi/common/napi/n_func_arg.h | 69 + interfaces/kits/napi/common/napi/n_val.cpp | 280 +++ interfaces/kits/napi/common/napi/n_val.h | 79 + interfaces/kits/napi/common/napi/uni_header.h | 25 + interfaces/kits/napi/common/uni_error.cpp | 118 ++ interfaces/kits/napi/common/uni_error.h | 60 + .../device_sm_exporter.cpp | 1017 +++++++++++ .../device_sm_exporter.h | 56 + .../napi/device_storage_manager/module.cpp | 47 + .../kits/napi/device_storage_manager/module.h | 18 + .../file_picker_exporter.cpp | 478 +++++ .../file_picker_exporter.h | 96 + .../kits/napi/file_picker_service/module.cpp | 48 + .../kits/napi/file_picker_service/module.h | 18 + .../file_share_exporter.cpp | 278 +++ .../file_share_ability/file_share_exporter.h | 41 + .../kits/napi/file_share_ability/module.cpp | 48 + .../kits/napi/file_share_ability/module.h | 18 + .../kits/native/storage_service/BUILD.gn | 37 + .../native/storage_service/ss_crypto_api.cpp | 224 +++ .../native/storage_service/ss_crypto_api.h | 18 + utils/filemgmt_libhilog/BUILD.gn | 29 + utils/filemgmt_libhilog/filemgmt_libhilog.h | 52 + utils/filemgmt_libn/BUILD.gn | 44 + utils/filemgmt_libn/include/filemgmt_libn.h | 25 + .../include/n_async/n_async_context.h | 75 + .../include/n_async/n_async_work.h | 36 + .../include/n_async/n_async_work_callback.h | 38 + .../include/n_async/n_async_work_promise.h | 38 + utils/filemgmt_libn/include/n_async/n_ref.h | 41 + utils/filemgmt_libn/include/n_class.h | 83 + utils/filemgmt_libn/include/n_error.h | 52 + utils/filemgmt_libn/include/n_exporter.h | 44 + utils/filemgmt_libn/include/n_func_arg.h | 75 + utils/filemgmt_libn/include/n_napi.h | 26 + utils/filemgmt_libn/include/n_val.h | 85 + .../src/n_async/n_async_work_callback.cpp | 100 ++ .../src/n_async/n_async_work_promise.cpp | 93 + utils/filemgmt_libn/src/n_async/n_ref.cpp | 55 + utils/filemgmt_libn/src/n_class.cpp | 92 + utils/filemgmt_libn/src/n_error.cpp | 72 + utils/filemgmt_libn/src/n_func_arg.cpp | 110 ++ utils/filemgmt_libn/src/n_val.cpp | 303 ++++ 190 files changed, 19348 insertions(+), 412 deletions(-) create mode 100644 .gitattributes create mode 100644 bundle.json create mode 100644 figures/distributed-file-subsystem-architecture.png create mode 100644 "figures/\345\210\206\345\270\203\345\274\217\346\226\207\344\273\266\345\255\220\347\263\273\347\273\237\346\236\266\346\236\204\345\233\276.png" create mode 100644 file_api_aafwk.gni create mode 100644 interfaces/kits/js/BUILD.gn create mode 100644 interfaces/kits/js/napi/@ohos.document.d.ts create mode 100644 interfaces/kits/js/napi/@ohos.environment.d.ts create mode 100644 interfaces/kits/js/napi/@ohos.fileio.d.ts create mode 100644 interfaces/kits/js/napi/@ohos.securityLabel.d.ts create mode 100644 interfaces/kits/js/napi/@ohos.statfs.d.ts create mode 100644 interfaces/kits/js/napi/@system.file.d.ts create mode 100644 interfaces/kits/js/src/common/file_helper/fd_guard.cpp create mode 100644 interfaces/kits/js/src/common/file_helper/fd_guard.h create mode 100644 interfaces/kits/js/src/common/file_helper/hash_file.cpp create mode 100644 interfaces/kits/js/src/common/file_helper/hash_file.h create mode 100644 interfaces/kits/js/src/mod_environment/environment_n_exporter.cpp create mode 100644 interfaces/kits/js/src/mod_environment/environment_n_exporter.h create mode 100644 interfaces/kits/js/src/mod_environment/environment_napi.cpp create mode 100644 interfaces/kits/js/src/mod_environment/environment_napi.h create mode 100644 interfaces/kits/js/src/mod_file/class_file/file_n_exporter.cpp create mode 100644 interfaces/kits/js/src/mod_file/class_file/file_n_exporter.h create mode 100644 interfaces/kits/js/src/mod_file/common_func.cpp create mode 100644 interfaces/kits/js/src/mod_file/common_func.h create mode 100644 interfaces/kits/js/src/mod_file/module.cpp create mode 100644 interfaces/kits/js/src/mod_fileio/class_constants/constants.cpp create mode 100644 interfaces/kits/js/src/mod_fileio/class_constants/constants.h create mode 100644 interfaces/kits/js/src/mod_fileio/class_dir/dir_entity.h create mode 100644 interfaces/kits/js/src/mod_fileio/class_dir/dir_n_exporter.cpp create mode 100644 interfaces/kits/js/src/mod_fileio/class_dir/dir_n_exporter.h create mode 100644 interfaces/kits/js/src/mod_fileio/class_dirent/dirent_entity.h create mode 100644 interfaces/kits/js/src/mod_fileio/class_dirent/dirent_n_exporter.cpp create mode 100644 interfaces/kits/js/src/mod_fileio/class_dirent/dirent_n_exporter.h create mode 100644 interfaces/kits/js/src/mod_fileio/class_stat/stat_entity.h create mode 100644 interfaces/kits/js/src/mod_fileio/class_stat/stat_n_exporter.cpp create mode 100644 interfaces/kits/js/src/mod_fileio/class_stat/stat_n_exporter.h create mode 100644 interfaces/kits/js/src/mod_fileio/class_stream/flush.cpp create mode 100644 interfaces/kits/js/src/mod_fileio/class_stream/flush.h create mode 100644 interfaces/kits/js/src/mod_fileio/class_stream/stream_entity.h create mode 100644 interfaces/kits/js/src/mod_fileio/class_stream/stream_n_exporter.cpp create mode 100644 interfaces/kits/js/src/mod_fileio/class_stream/stream_n_exporter.h create mode 100644 interfaces/kits/js/src/mod_fileio/class_watcher/watcher_entity.h create mode 100644 interfaces/kits/js/src/mod_fileio/class_watcher/watcher_n_exporter.cpp create mode 100644 interfaces/kits/js/src/mod_fileio/class_watcher/watcher_n_exporter.h create mode 100644 interfaces/kits/js/src/mod_fileio/common_func.cpp create mode 100644 interfaces/kits/js/src/mod_fileio/common_func.h create mode 100644 interfaces/kits/js/src/mod_fileio/module.cpp create mode 100644 interfaces/kits/js/src/mod_fileio/properties/chmod.cpp create mode 100644 interfaces/kits/js/src/mod_fileio/properties/chmod.h create mode 100644 interfaces/kits/js/src/mod_fileio/properties/chown.cpp create mode 100644 interfaces/kits/js/src/mod_fileio/properties/chown.h create mode 100644 interfaces/kits/js/src/mod_fileio/properties/close.cpp create mode 100644 interfaces/kits/js/src/mod_fileio/properties/close.h create mode 100644 interfaces/kits/js/src/mod_fileio/properties/copy_file.cpp create mode 100644 interfaces/kits/js/src/mod_fileio/properties/copy_file.h create mode 100644 interfaces/kits/js/src/mod_fileio/properties/create_stream.cpp create mode 100644 interfaces/kits/js/src/mod_fileio/properties/create_stream.h create mode 100644 interfaces/kits/js/src/mod_fileio/properties/fchmod.cpp create mode 100644 interfaces/kits/js/src/mod_fileio/properties/fchmod.h create mode 100644 interfaces/kits/js/src/mod_fileio/properties/fchown.cpp create mode 100644 interfaces/kits/js/src/mod_fileio/properties/fchown.h create mode 100644 interfaces/kits/js/src/mod_fileio/properties/fdatasync.cpp create mode 100644 interfaces/kits/js/src/mod_fileio/properties/fdatasync.h create mode 100644 interfaces/kits/js/src/mod_fileio/properties/fdopen_stream.cpp create mode 100644 interfaces/kits/js/src/mod_fileio/properties/fdopen_stream.h create mode 100644 interfaces/kits/js/src/mod_fileio/properties/fstat.cpp create mode 100644 interfaces/kits/js/src/mod_fileio/properties/fstat.h create mode 100644 interfaces/kits/js/src/mod_fileio/properties/fsync.cpp create mode 100644 interfaces/kits/js/src/mod_fileio/properties/fsync.h create mode 100644 interfaces/kits/js/src/mod_fileio/properties/ftruncate.cpp create mode 100644 interfaces/kits/js/src/mod_fileio/properties/ftruncate.h create mode 100644 interfaces/kits/js/src/mod_fileio/properties/hash.cpp create mode 100644 interfaces/kits/js/src/mod_fileio/properties/hash.h create mode 100644 interfaces/kits/js/src/mod_fileio/properties/lchown.cpp create mode 100644 interfaces/kits/js/src/mod_fileio/properties/lchown.h create mode 100644 interfaces/kits/js/src/mod_fileio/properties/link.cpp create mode 100644 interfaces/kits/js/src/mod_fileio/properties/link.h create mode 100644 interfaces/kits/js/src/mod_fileio/properties/lseek.cpp create mode 100644 interfaces/kits/js/src/mod_fileio/properties/lseek.h create mode 100644 interfaces/kits/js/src/mod_fileio/properties/lstat.cpp create mode 100644 interfaces/kits/js/src/mod_fileio/properties/lstat.h create mode 100644 interfaces/kits/js/src/mod_fileio/properties/mkdtemp.cpp create mode 100644 interfaces/kits/js/src/mod_fileio/properties/mkdtemp.h create mode 100644 interfaces/kits/js/src/mod_fileio/properties/open.cpp create mode 100644 interfaces/kits/js/src/mod_fileio/properties/open.h create mode 100644 interfaces/kits/js/src/mod_fileio/properties/open_dir.cpp create mode 100644 interfaces/kits/js/src/mod_fileio/properties/open_dir.h create mode 100644 interfaces/kits/js/src/mod_fileio/properties/posix_fallocate.cpp create mode 100644 interfaces/kits/js/src/mod_fileio/properties/posix_fallocate.h create mode 100644 interfaces/kits/js/src/mod_fileio/properties/prop_n_exporter.cpp create mode 100644 interfaces/kits/js/src/mod_fileio/properties/prop_n_exporter.h create mode 100644 interfaces/kits/js/src/mod_fileio/properties/read_text.cpp create mode 100644 interfaces/kits/js/src/mod_fileio/properties/read_text.h create mode 100644 interfaces/kits/js/src/mod_fileio/properties/rename.cpp create mode 100644 interfaces/kits/js/src/mod_fileio/properties/rename.h create mode 100644 interfaces/kits/js/src/mod_fileio/properties/rmdir.cpp create mode 100644 interfaces/kits/js/src/mod_fileio/properties/rmdir.h create mode 100644 interfaces/kits/js/src/mod_fileio/properties/stat.cpp create mode 100644 interfaces/kits/js/src/mod_fileio/properties/stat.h create mode 100644 interfaces/kits/js/src/mod_fileio/properties/symlink.cpp create mode 100644 interfaces/kits/js/src/mod_fileio/properties/symlink.h create mode 100644 interfaces/kits/js/src/mod_fileio/properties/truncate.cpp create mode 100644 interfaces/kits/js/src/mod_fileio/properties/truncate.h create mode 100644 interfaces/kits/js/src/mod_fileio/properties/watcher.cpp create mode 100644 interfaces/kits/js/src/mod_fileio/properties/watcher.h create mode 100644 interfaces/kits/js/src/mod_securitylabel/security_label.h create mode 100644 interfaces/kits/js/src/mod_securitylabel/securitylabel_n_exporter.cpp create mode 100644 interfaces/kits/js/src/mod_securitylabel/securitylabel_n_exporter.h create mode 100644 interfaces/kits/js/src/mod_securitylabel/securitylabel_napi.cpp create mode 100644 interfaces/kits/js/src/mod_securitylabel/securitylabel_napi.h create mode 100644 interfaces/kits/napi/BUILD.gn create mode 100644 interfaces/kits/napi/common/ability_helper.cpp create mode 100644 interfaces/kits/napi/common/ability_helper.h create mode 100644 interfaces/kits/napi/common/common_func.cpp create mode 100644 interfaces/kits/napi/common/common_func.h create mode 100644 interfaces/kits/napi/common/log.h create mode 100644 interfaces/kits/napi/common/napi/n_class.cpp create mode 100644 interfaces/kits/napi/common/napi/n_class.h create mode 100644 interfaces/kits/napi/common/napi/n_exporter.h create mode 100644 interfaces/kits/napi/common/napi/n_func_arg.cpp create mode 100644 interfaces/kits/napi/common/napi/n_func_arg.h create mode 100644 interfaces/kits/napi/common/napi/n_val.cpp create mode 100644 interfaces/kits/napi/common/napi/n_val.h create mode 100644 interfaces/kits/napi/common/napi/uni_header.h create mode 100644 interfaces/kits/napi/common/uni_error.cpp create mode 100644 interfaces/kits/napi/common/uni_error.h create mode 100644 interfaces/kits/napi/device_storage_manager/device_sm_exporter.cpp create mode 100644 interfaces/kits/napi/device_storage_manager/device_sm_exporter.h create mode 100644 interfaces/kits/napi/device_storage_manager/module.cpp create mode 100644 interfaces/kits/napi/device_storage_manager/module.h create mode 100644 interfaces/kits/napi/file_picker_service/file_picker_exporter.cpp create mode 100644 interfaces/kits/napi/file_picker_service/file_picker_exporter.h create mode 100644 interfaces/kits/napi/file_picker_service/module.cpp create mode 100644 interfaces/kits/napi/file_picker_service/module.h create mode 100644 interfaces/kits/napi/file_share_ability/file_share_exporter.cpp create mode 100644 interfaces/kits/napi/file_share_ability/file_share_exporter.h create mode 100644 interfaces/kits/napi/file_share_ability/module.cpp create mode 100644 interfaces/kits/napi/file_share_ability/module.h create mode 100644 interfaces/kits/native/storage_service/BUILD.gn create mode 100644 interfaces/kits/native/storage_service/ss_crypto_api.cpp create mode 100644 interfaces/kits/native/storage_service/ss_crypto_api.h create mode 100644 utils/filemgmt_libhilog/BUILD.gn create mode 100644 utils/filemgmt_libhilog/filemgmt_libhilog.h create mode 100644 utils/filemgmt_libn/BUILD.gn create mode 100644 utils/filemgmt_libn/include/filemgmt_libn.h create mode 100644 utils/filemgmt_libn/include/n_async/n_async_context.h create mode 100644 utils/filemgmt_libn/include/n_async/n_async_work.h create mode 100644 utils/filemgmt_libn/include/n_async/n_async_work_callback.h create mode 100644 utils/filemgmt_libn/include/n_async/n_async_work_promise.h create mode 100644 utils/filemgmt_libn/include/n_async/n_ref.h create mode 100644 utils/filemgmt_libn/include/n_class.h create mode 100644 utils/filemgmt_libn/include/n_error.h create mode 100644 utils/filemgmt_libn/include/n_exporter.h create mode 100644 utils/filemgmt_libn/include/n_func_arg.h create mode 100644 utils/filemgmt_libn/include/n_napi.h create mode 100644 utils/filemgmt_libn/include/n_val.h create mode 100644 utils/filemgmt_libn/src/n_async/n_async_work_callback.cpp create mode 100644 utils/filemgmt_libn/src/n_async/n_async_work_promise.cpp create mode 100644 utils/filemgmt_libn/src/n_async/n_ref.cpp create mode 100644 utils/filemgmt_libn/src/n_class.cpp create mode 100644 utils/filemgmt_libn/src/n_error.cpp create mode 100644 utils/filemgmt_libn/src/n_func_arg.cpp create mode 100644 utils/filemgmt_libn/src/n_val.cpp diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 000000000..c403f9c09 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,15 @@ +*.tgz filter=lfs diff=lfs merge=lfs -text +*.trp filter=lfs diff=lfs merge=lfs -text +*.apk filter=lfs diff=lfs merge=lfs -text +*.jar filter=lfs diff=lfs merge=lfs -text +*.mp4 filter=lfs diff=lfs merge=lfs -text +*.zip filter=lfs diff=lfs merge=lfs -text +*.asm filter=lfs diff=lfs merge=lfs -text +*.8svn filter=lfs diff=lfs merge=lfs -text +*.9svn filter=lfs diff=lfs merge=lfs -text +*.dylib filter=lfs diff=lfs merge=lfs -text +*.exe filter=lfs diff=lfs merge=lfs -text +*.a filter=lfs diff=lfs merge=lfs -text +*.so filter=lfs diff=lfs merge=lfs -text +*.bin filter=lfs diff=lfs merge=lfs -text +*.dll filter=lfs diff=lfs merge=lfs -text diff --git a/LICENSE b/LICENSE index 4947287f7..21254fc75 100644 --- a/LICENSE +++ b/LICENSE @@ -1,177 +1,176 @@ - - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + END OF TERMS AND CONDITIONS \ No newline at end of file diff --git a/README.md b/README.md index 76562969b..78daa51a4 100644 --- a/README.md +++ b/README.md @@ -1,36 +1,280 @@ -# storage_app_file_manager - -#### Description -{**When you're done, you can delete the content in this README and update the file with details for others getting started with your repository**} - -#### Software Architecture -Software architecture description - -#### Installation - -1. xxxx -2. xxxx -3. xxxx - -#### Instructions - -1. xxxx -2. xxxx -3. xxxx - -#### Contribution - -1. Fork the repository -2. Create Feat_xxx branch -3. Commit your code -4. Create Pull Request - - -#### Gitee Feature - -1. You can use Readme\_XXX.md to support different languages, such as Readme\_en.md, Readme\_zh.md -2. Gitee blog [blog.gitee.com](https://blog.gitee.com) -3. Explore open source project [https://gitee.com/explore](https://gitee.com/explore) -4. The most valuable open source project [GVP](https://gitee.com/gvp) -5. The manual of Gitee [https://gitee.com/help](https://gitee.com/help) -6. The most popular members [https://gitee.com/gitee-stars/](https://gitee.com/gitee-stars/) +# Distributed File + +- [Introduction](#section104mcpsimp) + - [Architecture](#section110mcpsimp) + +- [Directory Structure](#section113mcpsimp) +- [Constraints](#section117mcpsimp) +- [Usage](#section125mcpsimp) + - [Available APIs](#section127mcpsimp) + - [Usage Guidelines](#section149mcpsimp) + +- [Repositories Involved](#section178mcpsimp) + +## Introduction + +Currently, the Distributed File subsystem provides apps with JavaScript APIs for I/O capabilities, including APIs for managing files and directories, obtaining file information, reading and writing data streams of files, and receiving URIs rather than absolute paths. + +### Architecture + +Currently, the Distributed File subsystem provides only local JavaScript file APIs for apps through the FileIO and File modules. The Distributed File subsystem uses LibN to abstract APIs at the NAPI layer, providing basic capabilities such as the basic type system, memory management, and general programming models for the subsystem. This subsystem depends on the engine layer of the JS application development framework to provide the capability of converting JavaScript APIs into C++ code, depends on the application framework to provide app-related directories, and depends on the GLIBC runtimes to provide I/O capabilities. + +**Figure 1** Distributed File subsystem architecture +![](figures/distributed-file-subsystem-architecture.png "distributed-file-subsystem-architecture") + +## Directory Structure + +``` +foundation/distributeddatamgr/distributedfile +└── interfaces # APIs + └── kits # APIs exposed externally +``` + +## Constraints + +Constraints on local I/O APIs: + +- Only UTF-8/16 encoding is supported. +- The URIs cannot include external storage directories. + +## Usage + +### Available APIs + +Currently, the Distributed File subsystem provides APIs for accessing local files and directories. The following table describes the API types classified by function. + +**Table 1** API types + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

API Type

+

Function

+

Related Module

+

Example API (Class Name.Method Name)

+

Basic file API

+

Creates, modifies, and accesses files, and changes file permissions based on the specified absolute paths or file descriptors.

+

@OHOS.distributedfile.fileio

+

accessSync

+

chownSync

+

chmodSync

+

Basic directory API

+

Reads directories and determines file types based on the specified absolute paths.

+

@OHOS.distributedfile.fileio

+

Dir.openDirSync

+

Basic statistical API

+

Collects basic statistics including the file size, access permission, and modification time based on the specified absolute paths.

+

@OHOS.distributedfile.fileio

+

Stat.statSync

+

Streaming file API

+

Reads and writes data streams of files based on the specified absolute paths or file descriptors.

+

@OHOS.distributedfile.fileio

+

Stream.createStreamSync

+

Stream.fdopenStreamSync

+

Sandbox file API

+

Provides a subset or a combination of the capabilities provided by the basic file, directory, and statistical APIs based on the specified URIs.

+

@system.file

+

move

+

copy

+

list

+
+ +The URIs used in sandbox file APIs are classified into three types, as described in the following table. + +**Table 2** URI types + + + + + + + + + + + + + + + + + + + + + + + + +

Directory Type

+

Prefix

+

Access Visibility

+

Description

+

Temporary directory

+

internal://cache/

+

Current app only

+

Readable and writable, and can be cleared at any time. This directory is usually used for temporary downloads or caches.

+

Private directory of an app

+

internal://app/

+

Current app only

+

Deleted when the app is uninstalled.

+

External storage

+

internal://share/

+

All apps

+

Deleted when the app is uninstalled. Other apps with granted permissions can read and write files in this directory.

+
+ +### Usage Guidelines + +The I/O APIs provided by the Distributed File subsystem can be classified into the following types based on the programming model: + +- Synchronous programming model + + APIs whose names contain **Sync** are implemented as a synchronous model. When a synchronous API is called, the calling process waits until a value is returned. + + The following example opens a file stream in read-only mode, attempts to read the first 4096 bytes, converts them into a UTF-8-encoded string, and then closes the file stream: + + ``` + import fileio from '@OHOS.distributedfile.fileio'; + + try { + var ss = fileio.Stream.createStreamSync("tmp", "r") + buf = new ArrayBuffer(4096) + ss.readSync(buf) + console.log(String.fromCharCode.apply(null, new Uint8Array(buf))) + ss.closeSync() + } + catch (e) { + console.log(e); + } + ``` + + +- Asynchronous programming model: Promise + + In the **@OHOS.distributedfile.fileio** module, the APIs whose names do not contain **Sync** and to which a callback is not passed as their input parameter are implemented as the Promise asynchronous model. The Promise asynchronous model is one of the OHOS standard asynchronous models. When an asynchronous API using the Promise model is called, the API returns a Promise object while executing the concerned task asynchronously. The Promise object represents the asynchronous operation result. When there is more than one result, the results are returned as properties of the Promise object. + + In the following example, a Promise chain is used to open a file stream in read-only mode, attempt to read the first 4096 bytes of the file, display the length of the content read, and then close the file: + + ``` + import fileio from '@OHOS.distributedfile.fileio'; + + try { + let openedStream + fileio.Stream.createStream("test.txt", "r") + .then(function (ss) { + openedStream = ss; + return ss.read(new ArrayBuffer(4096)) + }) + .then(function (res) { + console.log(res.bytesRead); + console.log(String.fromCharCode.apply(null, new Uint8Array(res.buffer))) + return openedStream.close() + }) + .then(function (undefined) { + console.log("Stream is closed") + }) + .catch(function (e) { + console.log(e) + }) + } catch (e) { + console.log(e) + } + ``` + + +- Asynchronous programming model: Callback + + In the **@OHOS.distributedfile.fileio** module, the APIs whose names do not contain **Sync** and to which a callback is directly passed as their input parameter are implemented as the callback asynchronous model. The callback asynchronous model is also one of the OHOS standard asynchronous models. When an asynchronous API with a callback passed is called, the API executes the concerned task asynchronously and returns the execution result as the input parameters of the registered callback. The first parameter is of the **undefined** or **Error** type, indicating that the execution succeeds or fails, respectively. + + The following example creates a file stream asynchronously, reads the first 4096 bytes of the file asynchronously in the callback invoked when the file stream is created, and then closes the file asynchronously in the callback invoked when the file is read: + + ``` + import fileio from '@OHOS.distributedfile.fileio'; + + try { + fileio.Stream.createStream("./testdir/test_stream.txt", "r", function (err, ss) { + if (!err) { + ss.read(new ArrayBuffer(4096), {}, function (err, buf, readLen) { + if (!err) { + console.log('readLen: ' + readLen) + console.log('data: ' + String.fromCharCode.apply(null, new Uint8Array(buf))) + } else { + console.log('Cannot read from the stream ' + err) + } + ss.close(function (err) { + console.log(`Stream is ${err ? 'not' : ''}closed`) + }); + }) + } else { + console.log('Cannot open the stream ' + err) + } + }) + } catch (e) { + console.log(e) + } + ``` + + +- Asynchronous programming model: Legacy + + All APIs in the **@system.file** module are implemented as the legacy asynchronous model. When calling such an API, you need to implement three callbacks \(including **success**, **fail**, and **complete**\) to be invoked when the execution is successful, fails, or is complete, respectively. If the input parameters are correct, the API calls the **success** or **fail** callback based on whether the asynchronous task is successful after the task execution is complete, and finally calls the **complete** callback. + + The following example asynchronously checks whether the file pointed to by the specified URI exists and provides three callbacks to print the check result: + + ``` + import file from '@system.file' + + file.access({ + uri: 'internal://app/test.txt', + success: function() { + console.log('call access success.'); + }, + fail: function(data, code) { + console.error('call fail callback fail, code: ' + code + ', data: ' + data); + }, + complete: function () { + console.log('call access finally.'); + } + }); + + console.log("file access tested done") + ``` + + +## Repositories Involved + +**Distributed File subsystem** + +distributeddatamgr_distributedfile + diff --git a/README_zh.md b/README_zh.md index 25fb3eb92..362301a66 100644 --- a/README_zh.md +++ b/README_zh.md @@ -1,28 +1,281 @@ -# 文件访问接口 +# 分布式文件子系统 -## 简介 +- [简介](#section104mcpsimp) + - [系统架构](#section110mcpsimp) +- [目录结构](#section113mcpsimp) +- [约束](#section117mcpsimp) +- [说明](#section125mcpsimp) + - [接口说明](#section127mcpsimp) + - [使用说明](#section149mcpsimp) +- [相关仓](#section178mcpsimp) -提供目录与文件管理能力,即目录和文件的访问操作接口,包括以下内容: +## 简介 -1. 提供基础文件操作的同步和异步接口 -2. 提供目录操作的异步接口 -3. 提供流式相关操作的文件接口 -4. 提供statfs接口能力 -5. 提供目录环境相关配置接口 -6. 提供本地系统扩展接口能力 +分布式文件子系统当前向应用程序提供用于的 IO 的 JS 接口。其具体包括用于管理文件的基本文件接口,用于管理目录的基本目录接口,用于获取文件信息的统计接口,用于流式读写文件的流式接口,以及接收 URI 而非绝对路径的沙盒接口。 -## 目录 +### 系统架构 + +当前分布式文件子系统仅面向应用提供本地 JS 文件接口,这些接口分别通过 FileIO 模块以及 File 模块提供。架构上,分布式文件子系统实现了自研的 LibN,其抽象了 NAPI 层接口,向分布式文件子系统提供包括基本类型系统、内存管理、通用编程模型在内的基本能力。本系统对外依赖 JS 开发框架提供将 JS 接口转换为 C++ 代码的能力,依赖用户程序框架提供应用相关目录,依赖 GLIBC Runtimes 提供 IO 能力。 + +**图 1** 分布式文件子系统架构图 +![](figures/分布式文件子系统架构图.png "分布式文件子系统架构图") + +## 目录结构 ``` -interfaces # 接口代码 - └── kits # 对外JS接口代码 -LICENSE # 证书文件 +foundation/distributeddatamgr/distributedfile +├── figures # 仓库图床 +└── interfaces # 接口代码 + └── kits # 对外接口代码 ``` -## 说明 +## 约束 + +本地 IO 接口 + +- 目前仅支持 UTF-8/16 编码; +- 目前 URI 暂不支持外部存储目录; + +## 说明 + +### 接口说明 + +当前分布式文件子系统开放本地文件目录访问接口,按照功能,其可划分为如下几种类型: + +**表 1** 接口类型表 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

接口类型

+

接口用途

+

相关模块

+

接口示例(类名.方法名)

+

基本文件接口

+

需要用户提供绝对路径或文件描述符(fd),提供创建、修改及访问文件,或修改文件权限的能力

+

@OHOS.distributedfile.fileio

+

accessSync

+

chownSync

+

chmodSync

+

基本目录接口

+

需要用户提供绝对路径,提供读取目录及判断文件类型的能力

+

@OHOS.distributedfile.fileio

+

Dir.openDirSync

+

基本Stat接口

+

需要用户提供绝对路径,提供包括文件大小、访问权限、修改时间在内的基本统计信息

+

@OHOS.distributedfile.fileio

+

Stat.statSync

+

流式文件接口

+

需要用户提供绝对路径或文件描述符,提供流式读写文件的能力

+

@OHOS.distributedfile.fileio

+

Stream.createStreamSync

+

Stream.fdopenStreamSync

+

沙盒文件接口

+

需要用户提供 URI,提供基本文件接口、基本目录接口及基本统计接口能力的子集能力,或这些能力的组合能力

+

@system.file

+

move

+

copy

+

list

+
+ +其中,沙盒文件接口所使用的 URI 具体可划分为三种类型: + +**表 2** URI类型表 + + + + + + + + + + + + + + + + + + + + + + + + +

目录类型

+

路径前缀

+

访问可见性

+

说明

+

临时目录

+

internal://cache/

+

仅本应用可见

+

可读写,随时可能清除,不保证持久性。一般用作下载临时目录或缓存目录。

+

应用私有目录

+

internal://app/

+

仅本应用可见

+

随应用卸载删除。

+

外部存储

+

internal://share/

+

所有应用可见

+

随应用卸载删除。其他应用在有相应权限的情况下可读写此目录下的文件。

+
+ +### 使用说明 + +当前分布式文件子系统所提供的 IO 接口,按照编程模型,可划分为如下几种类型: + +- 同步编程模型 + + 名称包含 Sync 的接口实现为同步模型。用户在调用这些接口的时候,将同步等待,直至执行完成,执行结果以函数返回值的形式返回。 + + 下例以只读的方式打开一个文件流,接着试图读取其中前 4096 个字节并将之转换为 UTF-8 编码的字符串,最后关闭该文件流。 + + ``` + import fileio from '@OHOS.distributedfile.fileio'; + + try { + var ss = fileio.Stream.createStreamSync("tmp", "r") + buf = new ArrayBuffer(4096) + ss.readSync(buf) + console.log(String.fromCharCode.apply(null, new Uint8Array(buf))) + ss.closeSync() + } + catch (e) { + console.log(e); + } + ``` + + +- 异步编程模型:Promise + + @OHOS.distributedfile.fileio 模块中,名称不含 Sync 的接口,在不提供最后一个函数型参数 callback 的时候,即实现为 Promsie 异步模型。Promise 异步模型是 OHOS 标准异步模型之一。用户在调用这些接口的时候,接口实现将异步执行任务,同时返回一个 promise 对象,其代表异步操作的结果。在返回的结果的个数超过一个时,其以对象属性的形式返回。 + + 下例通过 Promise 链依次完成:以只读方式打开文件流、尝试读取文件前 4096 个字节、显示读取内容的长度,最后关闭文件。 + + ``` + import fileio from '@OHOS.distributedfile.fileio'; + + try { + let openedStream + fileio.Stream.createStream("test.txt", "r") + .then(function (ss) { + openedStream = ss; + return ss.read(new ArrayBuffer(4096)) + }) + .then(function (res) { + console.log(res.bytesRead); + console.log(String.fromCharCode.apply(null, new Uint8Array(res.buffer))) + return openedStream.close() + }) + .then(function (undefined) { + console.log("Stream is closed") + }) + .catch(function (e) { + console.log(e) + }) + } catch (e) { + console.log(e) + } + ``` + + +- 异步编程模型:Callback + + @OHOS.distributedfile.fileio 模块中,名字不含 Sync 的接口,在提供最后一个函数性参数 callback 的时候,即实现为 Callback 异步模型。Callback 异步模型是 OHOS 标准异步模型之一。用户在调用这些接口的时候,接口实现将异步执行任务。任务执行结果以参数的形式提供给用户注册的回调函数。这些参数的第一个是 Error 或 undefined 类型,分别表示执行出错与正常。 + + 下例异步创建文件流,并在文件流的回调函数中异步读取文件的前 4096 字节,接着在读取文件的回调函数中异步关闭文件。 + + ``` + import fileio from '@OHOS.distributedfile.fileio'; + + try { + fileio.Stream.createStream("./testdir/test_stream.txt", "r", function (err, ss) { + if (!err) { + ss.read(new ArrayBuffer(4096), {}, function (err, buf, readLen) { + if (!err) { + console.log('readLen: ' + readLen) + console.log('data: ' + String.fromCharCode.apply(null, new Uint8Array(buf))) + } else { + console.log('Cannot read from the stream ' + err) + } + ss.close(function (err) { + console.log(`Stream is ${err ? 'not' : ''}closed`) + }); + }) + } else { + console.log('Cannot open the stream ' + err) + } + }) + } catch (e) { + console.log(e) + } + ``` + + +- 异步编程模型:Legacy + + @system.file 模块中的所有接口都实现为 Legacy 异步模型。用户在调用这些接口的时候,需要提供 success、fail 及 complete 三个回调。在正确提供参数的情况下,当异步任务完成后,接口会根据是否成功,分别调用 success 回调或 fail 回调,并最终调用 complete 回调。 + + 下例异步判断 URI 所指向的文件是否存在,并相应提供三个回调用于打印判断结果。 + + ``` + import file from '@system.file' + + file.access({ + uri: 'internal://app/test.txt', + success: function() { + console.log('call access success.'); + }, + fail: function(data, code) { + console.error('call fail callback fail, code: ' + code + ', data: ' + data); + }, + complete: function () { + console.log('call access finally.'); + } + }); + + console.log("file access tested done") + ``` + + +## 相关仓 + +**分布式文件** -### 接口说明 +distributeddatamgr_distributedfile -[statfs接口](https://gitee.com/openharmony/docs/tree/master/zh-cn/application-dev/reference/apis/js-apis-statfs.md) diff --git a/bundle.json b/bundle.json new file mode 100644 index 000000000..b4606e68d --- /dev/null +++ b/bundle.json @@ -0,0 +1,43 @@ +{ + "name": "file_api", + "description": "provides the application with JS interfaces for IO", + "version": "3.1", + "license": "Apache License 2.0", + "publishAs": "code-segment", + "segment": { + "destPath": "foundation/filemanagement/file_api" + }, + "dirs": {}, + "scripts": {}, + "component": { + "name": "file_api", + "subsystem": "filemanagement", + "syscap": [], + "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": [ + "//foundation/filemanagement/file_api/interfaces/kits/js:build_kits_js", + "//third_party/e2fsprogs:e2fsprogs" + ] + } + } + } \ No newline at end of file diff --git a/figures/distributed-file-subsystem-architecture.png b/figures/distributed-file-subsystem-architecture.png new file mode 100644 index 0000000000000000000000000000000000000000..d36a4b1bca8f27ebe38b448dc6169de767811d27 GIT binary patch literal 35168 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 literal 0 HcmV?d00001 diff --git a/file_api_aafwk.gni b/file_api_aafwk.gni new file mode 100644 index 000000000..b2fc6d3ac --- /dev/null +++ b/file_api_aafwk.gni @@ -0,0 +1,15 @@ +# 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. + +aafwk_kits_path = "//foundation/ability/ability_runtime/frameworks/kits" +aafwk_path = "//foundation/ability/ability_runtime" diff --git a/interfaces/innerkits/include/security_label.h b/interfaces/innerkits/include/security_label.h index 3727c9a61..07f2c7343 100644 --- a/interfaces/innerkits/include/security_label.h +++ b/interfaces/innerkits/include/security_label.h @@ -1,37 +1,37 @@ -/* - * 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. - */ - -#ifndef FOUNDATION_FILEMANAGEMENT_FILEAPI_INTERFACES_INNERKITS_SECURITY_LABEL_H -#define FOUNDATION_FILEMANAGEMENT_FILEAPI_INTERFACES_INNERKITS_SECURITY_LABEL_H - -#include - -namespace OHOS { -namespace FileIO { -class SecurityLabel { -public: - static bool SetSecurityLabel(std::string path, std::string dataLevel) - { - return true; - } - static std::string GetSecurityLabel(std::string path) - { - return "data.security.level"; - }; -}; -} // namespace FileIO -} // namespace OHOS - +/* + * 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. + */ + +#ifndef FOUNDATION_FILEMANAGEMENT_FILEAPI_INTERFACES_INNERKITS_SECURITY_LABEL_H +#define FOUNDATION_FILEMANAGEMENT_FILEAPI_INTERFACES_INNERKITS_SECURITY_LABEL_H + +#include + +namespace OHOS { +namespace FileIO { +class SecurityLabel { +public: + static bool SetSecurityLabel(std::string path, std::string dataLevel) + { + return true; + } + static std::string GetSecurityLabel(std::string path) + { + return "data.security.level"; + }; +}; +} // namespace FileIO +} // namespace OHOS + #endif \ No newline at end of file diff --git a/interfaces/kits/js/BUILD.gn b/interfaces/kits/js/BUILD.gn new file mode 100644 index 000000000..084f8d5e5 --- /dev/null +++ b/interfaces/kits/js/BUILD.gn @@ -0,0 +1,248 @@ +# 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("//build/ohos.gni") +import( + "//foundation/filemanagement/file_api/file_api_aafwk.gni") + +file_common_src = [ + "src/common/file_helper/fd_guard.cpp", + "src/common/napi/n_async/n_async_work_callback.cpp", + "src/common/napi/n_async/n_async_work_promise.cpp", + "src/common/napi/n_async/n_ref.cpp", + "src/common/napi/n_class.cpp", + "src/common/napi/n_func_arg.cpp", + "src/common/napi/n_val.cpp", + "src/common/uni_error.cpp", +] + +ohos_shared_library("fileio") { + subsystem_name = "filemanagement" + part_name = "file_api" + + relative_install_dir = "module" + + include_dirs = [ + "//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", + ] + + sources = file_common_src + sources += [ + "src/common/file_helper/hash_file.cpp", + "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_stat/stat_n_exporter.cpp", + "src/mod_fileio/class_stream/flush.cpp", + "src/mod_fileio/class_stream/stream_n_exporter.cpp", + "src/mod_fileio/class_watcher/watcher_n_exporter.cpp", + "src/mod_fileio/common_func.cpp", + "src/mod_fileio/module.cpp", + "src/mod_fileio/properties/chmod.cpp", + "src/mod_fileio/properties/chown.cpp", + "src/mod_fileio/properties/close.cpp", + "src/mod_fileio/properties/copy_file.cpp", + "src/mod_fileio/properties/create_stream.cpp", + "src/mod_fileio/properties/fchmod.cpp", + "src/mod_fileio/properties/fchown.cpp", + "src/mod_fileio/properties/fdatasync.cpp", + "src/mod_fileio/properties/fdopen_stream.cpp", + "src/mod_fileio/properties/fstat.cpp", + "src/mod_fileio/properties/fsync.cpp", + "src/mod_fileio/properties/ftruncate.cpp", + "src/mod_fileio/properties/hash.cpp", + "src/mod_fileio/properties/lchown.cpp", + "src/mod_fileio/properties/link.cpp", + "src/mod_fileio/properties/lseek.cpp", + "src/mod_fileio/properties/lstat.cpp", + "src/mod_fileio/properties/mkdtemp.cpp", + "src/mod_fileio/properties/open.cpp", + "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_text.cpp", + "src/mod_fileio/properties/rename.cpp", + "src/mod_fileio/properties/rmdir.cpp", + "src/mod_fileio/properties/stat.cpp", + "src/mod_fileio/properties/symlink.cpp", + "src/mod_fileio/properties/truncate.cpp", + "src/mod_fileio/properties/watcher.cpp", + ] + + deps = [ + "//foundation/arkui/napi:ace_napi", + "//third_party/bounds_checking_function:libsec_static", + "//third_party/openssl:libcrypto_static", + ] + + external_deps = [ "hiviewdfx_hilog_native:libhilog" ] +} + +ohos_shared_library("file") { + subsystem_name = "filemanagement" + part_name = "file_api" + + 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", + ] + + sources = file_common_src + sources += [ + "src/common/ability_helper.cpp", + "src/mod_file/class_file/file_n_exporter.cpp", + "src/mod_file/common_func.cpp", + "src/mod_file/module.cpp", + ] + + deps = [ + "${aafwk_kits_path}/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", + "eventhandler:libeventhandler", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] +} + +ohos_shared_library("statfs") { + subsystem_name = "filemanagement" + part_name = "file_api" + + relative_install_dir = "module" + + sources = [ + "src/mod_statfs/statfs_n_exporter.cpp", + "src/mod_statfs/statfs_napi.cpp", + ] + + deps = [ + "//foundation/filemanagement/file_api/utils/filemgmt_libhilog", + "//foundation/filemanagement/file_api/utils/filemgmt_libn", + ] + + external_deps = [ "hiviewdfx_hilog_native:libhilog" ] +} + +ohos_shared_library("environment") { + subsystem_name = "filemanagement" + part_name = "file_api" + + 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", + ] + + sources = [ + "src/common/napi/n_async/n_async_work_callback.cpp", + "src/common/napi/n_async/n_async_work_promise.cpp", + "src/common/napi/n_async/n_ref.cpp", + "src/common/napi/n_func_arg.cpp", + "src/common/napi/n_val.cpp", + "src/common/uni_error.cpp", + "src/mod_environment/environment_n_exporter.cpp", + "src/mod_environment/environment_napi.cpp", + ] + + deps = [ "//foundation/arkui/napi:ace_napi" ] + + external_deps = [ "hiviewdfx_hilog_native:libhilog" ] +} + +ohos_shared_library("securitylabel") { + subsystem_name = "filemanagement" + part_name = "file_api" + + relative_install_dir = "module" + + cflags = [ "-Wno-format" ] + + include_dirs = [ + "//foundation/arkui/napi/interfaces/kits", + "//foundation/arkui/ace_engine/frameworks/base/utils", + "//foundation/arkui/ace_engine/frameworks", + "//foundation/filemanagement/file_api/interfaces/kits/js/src/common/napi/n_async", + ] + + sources = file_common_src + sources += [ + "src/mod_securitylabel/securitylabel_n_exporter.cpp", + "src/mod_securitylabel/securitylabel_napi.cpp", + ] + + deps = [ "//foundation/arkui/napi:ace_napi" ] + + external_deps = [ "hiviewdfx_hilog_native:libhilog" ] +} + +ohos_shared_library("document") { + subsystem_name = "filemanagement" + part_name = "file_api" + + 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", + ] + + sources = [ + "src/common/napi/n_async/n_async_work_callback.cpp", + "src/common/napi/n_async/n_async_work_promise.cpp", + "src/common/napi/n_async/n_ref.cpp", + "src/common/napi/n_func_arg.cpp", + "src/common/napi/n_val.cpp", + "src/common/uni_error.cpp", + "src/mod_document/document_n_exporter.cpp", + "src/mod_document/document_napi.cpp", + ] + + deps = [ "//foundation/arkui/napi:ace_napi" ] + + external_deps = [ "hiviewdfx_hilog_native:libhilog" ] +} + +group("build_kits_js") { + deps = [ + ":document", + ":environment", + ":file", + ":fileio", + ":securitylabel", + ":statfs", + ] +} diff --git a/interfaces/kits/js/napi/@ohos.document.d.ts b/interfaces/kits/js/napi/@ohos.document.d.ts new file mode 100644 index 000000000..88df1e0cf --- /dev/null +++ b/interfaces/kits/js/napi/@ohos.document.d.ts @@ -0,0 +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; +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/napi/@ohos.environment.d.ts new file mode 100644 index 000000000..4ecb97804 --- /dev/null +++ b/interfaces/kits/js/napi/@ohos.environment.d.ts @@ -0,0 +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; diff --git a/interfaces/kits/js/napi/@ohos.fileio.d.ts b/interfaces/kits/js/napi/@ohos.fileio.d.ts new file mode 100644 index 000000000..d074897db --- /dev/null +++ b/interfaces/kits/js/napi/@ohos.fileio.d.ts @@ -0,0 +1,1548 @@ +/* + * 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 new file mode 100644 index 000000000..85c06ad2a --- /dev/null +++ b/interfaces/kits/js/napi/@ohos.securityLabel.d.ts @@ -0,0 +1,59 @@ +/* +* 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/@ohos.statfs.d.ts b/interfaces/kits/js/napi/@ohos.statfs.d.ts new file mode 100644 index 000000000..4a83f02b8 --- /dev/null +++ b/interfaces/kits/js/napi/@ohos.statfs.d.ts @@ -0,0 +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 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/napi/@system.file.d.ts b/interfaces/kits/js/napi/@system.file.d.ts new file mode 100644 index 000000000..9bd26a69d --- /dev/null +++ b/interfaces/kits/js/napi/@system.file.d.ts @@ -0,0 +1,752 @@ +/* + * 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 c5aae1548..595bee685 100644 --- a/interfaces/kits/js/src/common/ability_helper.cpp +++ b/interfaces/kits/js/src/common/ability_helper.cpp @@ -29,7 +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); diff --git a/interfaces/kits/js/src/common/ability_helper.h b/interfaces/kits/js/src/common/ability_helper.h index e998027c0..36c69cb77 100644 --- a/interfaces/kits/js/src/common/ability_helper.h +++ b/interfaces/kits/js/src/common/ability_helper.h @@ -13,9 +13,9 @@ * limitations under the License. */ -#pragma once +#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 { @@ -24,4 +24,5 @@ struct AbilityHelper { static AppExecFwk::Ability *GetJsAbility(napi_env env); }; } // namespace DistributedFS -} // namespace OHOS \ No newline at end of file +} // namespace OHOS +#endif \ 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 new file mode 100644 index 000000000..6959b45a5 --- /dev/null +++ b/interfaces/kits/js/src/common/file_helper/fd_guard.cpp @@ -0,0 +1,75 @@ +/* + * 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. + */ + +#include "fd_guard.h" + +#include + +#include "../log.h" + +namespace OHOS { +namespace DistributedFS { +FDGuard::FDGuard(int fd) : fd_(fd) {} + +FDGuard::FDGuard(int fd, bool autoClose) : fd_(fd), autoClose_(autoClose) {} + +FDGuard::FDGuard(FDGuard &&fdg) : fd_(fdg.fd_), autoClose_(fdg.autoClose_) +{ + fdg.fd_ = -1; +} + +FDGuard &FDGuard::operator=(FDGuard &&fdg) +{ + if (this == &fdg) { + return *this; + } + this->fd_ = fdg.fd_; + this->autoClose_ = fdg.autoClose_; + fdg.fd_ = -1; + return *this; +} + +FDGuard::~FDGuard() +{ + if (fd_ >= 0 && fd_ <= STDERR_FILENO) { + HILOGI("~FDGuard, fd_ = %{public}d", fd_); + } + if (fd_ >= 0 && autoClose_) { + close(fd_); + } +} + +FDGuard::operator bool() const +{ + return fd_ >= 0; +} + +int FDGuard::GetFD() const +{ + return fd_; +} + +void FDGuard::SetFD(int fd, bool autoClose) +{ + fd_ = fd; + autoClose_ = autoClose; +} + +void FDGuard::ClearFD() +{ + fd_ = -1; +} +} // namespace DistributedFS +} // namespace OHOS diff --git a/interfaces/kits/js/src/common/file_helper/fd_guard.h b/interfaces/kits/js/src/common/file_helper/fd_guard.h new file mode 100644 index 000000000..07c27b19d --- /dev/null +++ b/interfaces/kits/js/src/common/file_helper/fd_guard.h @@ -0,0 +1,47 @@ +/* + * 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. + */ + +#ifndef FD_GUARD_H +#define FD_GUARD_H + +namespace OHOS { +namespace DistributedFS { +class FDGuard final { +public: + FDGuard() = default; + explicit FDGuard(int fd); + FDGuard(int fd, bool autoClose); + + FDGuard(const FDGuard &fdg) = delete; + FDGuard &operator=(const FDGuard &fdg) = delete; + + FDGuard(FDGuard &&fdg); + FDGuard &operator=(FDGuard &&fdg); + + operator bool() const; + + ~FDGuard(); + + int GetFD() const; + void SetFD(int fd, bool autoClose = true); + void ClearFD(); + +private: + int fd_ = -1; + bool autoClose_ = true; +}; +} // namespace DistributedFS +} // namespace OHOS +#endif \ No newline at end of file diff --git a/interfaces/kits/js/src/common/file_helper/hash_file.cpp b/interfaces/kits/js/src/common/file_helper/hash_file.cpp new file mode 100644 index 000000000..2bd54cc65 --- /dev/null +++ b/interfaces/kits/js/src/common/file_helper/hash_file.cpp @@ -0,0 +1,106 @@ +/* + * 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. + */ + +#include "hash_file.h" + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace OHOS { +namespace DistributedFS { +using namespace std; + +static tuple HashFinal(int err, const unique_ptr &hashBuf, size_t hashLen) +{ + if (err) { + return { err, "" }; + } + + stringstream ss; + for (size_t i = 0; i < hashLen; ++i) { + const int hexPerByte = 2; + ss << std::uppercase << std::setfill('0') << std::setw(hexPerByte) << std::hex << + static_cast(hashBuf[i]); + } + + return { err, ss.str() }; +} + +static int ForEachFileSegment(const string &fpath, function executor) +{ + unique_ptr filp = { fopen(fpath.c_str(), "r"), fclose }; + if (!filp) { + return errno; + } + + const size_t pageSize { getpagesize() }; + auto buf = make_unique(pageSize); + size_t actLen; + do { + actLen = fread(buf.get(), 1, pageSize, filp.get()); + if (actLen > 0) { + executor(buf.get(), actLen); + } + } while (actLen == pageSize); + + return ferror(filp.get()) ? errno : 0; +} + +tuple HashFile::HashWithMD5(const string &fpath) +{ + auto res = make_unique(MD5_DIGEST_LENGTH); + MD5_CTX ctx; + MD5_Init(&ctx); + auto md5Update = [ctx = &ctx](char *buf, size_t len) { + MD5_Update(ctx, buf, len); + }; + int err = ForEachFileSegment(fpath, md5Update); + MD5_Final(res.get(), &ctx); + return HashFinal(err, res, MD5_DIGEST_LENGTH); +} + +tuple HashFile::HashWithSHA1(const string &fpath) +{ + auto res = make_unique(SHA_DIGEST_LENGTH); + SHA_CTX ctx; + SHA1_Init(&ctx); + auto sha1Update = [ctx = &ctx](char *buf, size_t len) { + SHA1_Update(ctx, buf, len); + }; + int err = ForEachFileSegment(fpath, sha1Update); + SHA1_Final(res.get(), &ctx); + return HashFinal(err, res, SHA_DIGEST_LENGTH); +} + +tuple HashFile::HashWithSHA256(const string &fpath) +{ + auto res = make_unique(SHA256_DIGEST_LENGTH); + SHA256_CTX ctx; + SHA256_Init(&ctx); + auto sha256Update = [ctx = &ctx](char *buf, size_t len) { + SHA256_Update(ctx, buf, len); + }; + int err = ForEachFileSegment(fpath, sha256Update); + SHA256_Final(res.get(), &ctx); + return HashFinal(err, res, SHA256_DIGEST_LENGTH); +} +} // namespace DistributedFS +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/js/src/common/file_helper/hash_file.h b/interfaces/kits/js/src/common/file_helper/hash_file.h new file mode 100644 index 000000000..81d68a2e4 --- /dev/null +++ b/interfaces/kits/js/src/common/file_helper/hash_file.h @@ -0,0 +1,32 @@ +/* + * 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. + */ + +#ifndef HASH_FILE_H +#define HASH_FILE_H + +#include +#include + +namespace OHOS { +namespace DistributedFS { +class HashFile { +public: + static std::tuple HashWithMD5(const std::string &fpath); + static std::tuple HashWithSHA1(const std::string &fpath); + static std::tuple HashWithSHA256(const std::string &fpath); +}; +} // namespace DistributedFS +} // namespace OHOS +#endif \ No newline at end of file diff --git a/interfaces/kits/js/src/common/log.h b/interfaces/kits/js/src/common/log.h index 32a09a751..412b5f6cf 100644 --- a/interfaces/kits/js/src/common/log.h +++ b/interfaces/kits/js/src/common/log.h @@ -13,19 +13,20 @@ * limitations under the License. */ -#pragma once +#ifndef INTERFACES_KITS_NAPI_COMMON_LOG_H +#define INTERFACES_KITS_NAPI_COMMON_LOG_H #include #include #include -#ifndef FILE_SUBSYSTEM_DEV_ON_PC +#ifndef FILE_SUBSYSTEM_DEBUG_LOCAL #include "hilog/log.h" #endif namespace OHOS { namespace DistributedFS { -#ifndef FILE_SUBSYSTEM_DEV_ON_PC +#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" }; @@ -77,7 +78,7 @@ static constexpr OHOS::HiviewDFX::HiLogLabel FILEIO_LABEL = { LOG_CORE, FILEIO_D } \ str____ += "\n"; \ printf(str____.c_str(), ##__VA_ARGS__); \ - } while (0); + } while (0) \ #define HILOGD(fmt, ...) PCLOG("%{public}s: " fmt, __func__, ##__VA_ARGS__) #define HILOGI(fmt, ...) PCLOG("%{public}s: " fmt, __func__, ##__VA_ARGS__) @@ -87,4 +88,5 @@ static constexpr OHOS::HiviewDFX::HiLogLabel FILEIO_LABEL = { LOG_CORE, FILEIO_D #endif } // namespace DistributedFS -} // namespace OHOS \ No newline at end of file +} // namespace OHOS +#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 7c45ce20a..87339bbdd 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 @@ -16,8 +16,6 @@ #ifndef N_ASYNC_CONTEXT_H #define N_ASYNC_CONTEXT_H -#include - #include "../../uni_error.h" #include "../n_val.h" #include "n_ref.h" @@ -43,7 +41,7 @@ public: class NAsyncContextPromise : public NAsyncContext { public: - napi_deferred deferred_; + napi_deferred deferred_ = nullptr; explicit NAsyncContextPromise(NVal thisPtr) : NAsyncContext(thisPtr) {} ~NAsyncContextPromise() = default; }; 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 6b6d0b70a..8c3af6149 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 @@ -69,7 +69,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)) { - UniError(EINVAL).ThrowErr(env_, "The callback shall be a funciton"); + UniError(EINVAL).ThrowErr(env_, "The callback shall be a function"); return NVal(); } @@ -91,7 +91,7 @@ NVal NAsyncWorkCallback::Schedule(string procedureName, NContextCBExec cbExec, N return NVal(); } - ctx_ = nullptr; // The ownership of ctx_ has been transfered + ctx_ = nullptr; // The ownership of ctx_ has been transferred return NVal::CreateUndefined(env_); } } // namespace DistributedFS 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 7b7f190c8..9bc6d5f3d 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 @@ -26,7 +26,7 @@ public: ~NAsyncWorkCallback() = default; NVal Schedule(std::string procedureName, NContextCBExec cbExec, NContextCBComplete cbComplete) final; - NAsyncWorkCallback(const NAsyncWorkCallback&) = delete; + private: NAsyncContextCallback *ctx_ = nullptr; }; 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 3809c1a4b..f0ef6df49 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 @@ -84,7 +84,7 @@ NVal NAsyncWorkPromise::Schedule(string procedureName, NContextCBExec cbExec, NC return NVal(); } - ctx_ = nullptr; // The ownership of ctx_ has been transfered + ctx_ = nullptr; // The ownership of ctx_ has been transferred return { env_, result }; } } // namespace DistributedFS 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 f2406913f..8a049de65 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 @@ -26,7 +26,7 @@ public: ~NAsyncWorkPromise() = default; NVal Schedule(std::string procedureName, NContextCBExec cbExec, NContextCBComplete cbComplete) final; - NAsyncWorkPromise(const NAsyncWorkPromise&) = delete; + private: NAsyncContextPromise *ctx_; }; diff --git a/interfaces/kits/js/src/common/napi/n_class.cpp b/interfaces/kits/js/src/common/napi/n_class.cpp index 0e9028b02..dbda702d0 100644 --- a/interfaces/kits/js/src/common/napi/n_class.cpp +++ b/interfaces/kits/js/src/common/napi/n_class.cpp @@ -25,7 +25,7 @@ namespace DistributedFS { using namespace std; NClass &NClass::GetInstance() { - static NClass nClass; + static thread_local NClass nClass; return nClass; } @@ -69,7 +69,7 @@ bool NClass::SaveClass(napi_env env, string className, napi_value exClass) return res == napi_ok; } -napi_value NClass::InstantiateClass(napi_env env, string className, vector args) +napi_value NClass::InstantiateClass(napi_env env, const string& className, const vector& args) { NClass &nClass = NClass::GetInstance(); lock_guard(nClass.exClassMapLock); @@ -96,4 +96,4 @@ napi_value NClass::InstantiateClass(napi_env env, string className, vector -#include -#include -#include -#include -#include #include "../log.h" @@ -39,7 +35,7 @@ public: 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, std::string className, std::vector args); + 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) { @@ -79,4 +75,5 @@ private: std::mutex exClassMapLock; }; } // namespace DistributedFS -} // namespace OHOS \ No newline at end of file +} // namespace OHOS +#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 2ade0c076..db5563f7b 100644 --- a/interfaces/kits/js/src/common/napi/n_exporter.h +++ b/interfaces/kits/js/src/common/napi/n_exporter.h @@ -13,12 +13,8 @@ * limitations under the License. */ -#pragma once - -#include "uni_header.h" - -#include -#include +#ifndef INTERFACES_KITS_NAPI_COMMON_NAPI_N_EXPORTER_H +#define INTERFACES_KITS_NAPI_COMMON_NAPI_N_EXPORTER_H #include "n_val.h" @@ -36,4 +32,5 @@ protected: NVal exports_; }; } // namespace DistributedFS -} // namespace OHOS \ No newline at end of file +} // namespace OHOS +#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 123ef8d0a..1a3d6d8dd 100644 --- a/interfaces/kits/js/src/common/napi/n_func_arg.cpp +++ b/interfaces/kits/js/src/common/napi/n_func_arg.cpp @@ -15,11 +15,7 @@ #include "n_func_arg.h" -#include -#include - #include "../log.h" -#include "../uni_error.h" namespace OHOS { namespace DistributedFS { @@ -33,6 +29,7 @@ void NFuncArg::SetArgc(size_t argc) { argc_ = argc; } + void NFuncArg::SetThisVar(napi_value thisVar) { thisVar_ = thisVar; 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 7ff5b2942..e0d2a17de 100644 --- a/interfaces/kits/js/src/common/napi/n_func_arg.h +++ b/interfaces/kits/js/src/common/napi/n_func_arg.h @@ -13,14 +13,9 @@ * limitations under the License. */ -#pragma once +#ifndef INTERFACES_KITS_NAPI_COMMON_NAPI_N_FUNC_ARG_H +#define INTERFACES_KITS_NAPI_COMMON_NAPI_N_FUNC_ARG_H -#include -#include -#include -#include - -#include "n_val.h" #include "uni_header.h" namespace OHOS { @@ -68,4 +63,5 @@ private: void SetThisVar(napi_value thisVar); }; } // namespace DistributedFS -} // namespace OHOS \ No newline at end of file +} // namespace OHOS +#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 6a234449d..433320840 100644 --- a/interfaces/kits/js/src/common/napi/n_val.cpp +++ b/interfaces/kits/js/src/common/napi/n_val.cpp @@ -73,7 +73,7 @@ tuple, size_t> NVal::ToUTF8String() const tuple, size_t> NVal::ToUTF16String() const { -#ifdef FILE_SUBSYSTEM_DEV_ON_PC +#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) { @@ -237,6 +237,13 @@ NVal NVal::CreateUTF8String(napi_env env, std::string str) return { env, res }; } +NVal NVal::CreateUTF8String(napi_env env, const char* str, ssize_t len) +{ + napi_value res = nullptr; + napi_create_string_utf8(env, str, len, &res); + return { env, res }; +} + NVal NVal::CreateUint8Array(napi_env env, void *buf, size_t bufLen) { napi_value output_buffer = nullptr; @@ -252,6 +259,14 @@ NVal NVal::CreateUint8Array(napi_env env, void *buf, size_t bufLen) return { env, output_array }; } +tuple NVal::CreateArrayBuffer(napi_env env, size_t len) +{ + napi_value val; + void *buf = nullptr; + napi_create_arraybuffer(env, len, &buf, &val); + return { { env, val }, { buf } }; +} + napi_property_descriptor NVal::DeclareNapiProperty(const char *name, napi_value val) { return { (name), nullptr, nullptr, nullptr, nullptr, val, napi_default, nullptr }; diff --git a/interfaces/kits/js/src/common/napi/n_val.h b/interfaces/kits/js/src/common/napi/n_val.h index c772b9c5e..9d46fca4a 100644 --- a/interfaces/kits/js/src/common/napi/n_val.h +++ b/interfaces/kits/js/src/common/napi/n_val.h @@ -16,6 +16,7 @@ #ifndef N_VAL_H #define N_VAL_H +#include "sys/types.h" #include "uni_header.h" namespace OHOS { @@ -53,8 +54,9 @@ public: 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 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/interfaces/kits/js/src/common/napi/uni_header.h b/interfaces/kits/js/src/common/napi/uni_header.h index a79d4e1ed..081621198 100644 --- a/interfaces/kits/js/src/common/napi/uni_header.h +++ b/interfaces/kits/js/src/common/napi/uni_header.h @@ -13,11 +13,13 @@ * limitations under the License. */ -#pragma once +#ifndef N_UNI_HEADER_H +#define N_UNI_HEADER_H -#ifdef FILE_SUBSYSTEM_DEV_ON_PC +#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/js/src/common/uni_error.cpp b/interfaces/kits/js/src/common/uni_error.cpp index 010aa3dad..295b28654 100644 --- a/interfaces/kits/js/src/common/uni_error.cpp +++ b/interfaces/kits/js/src/common/uni_error.cpp @@ -97,7 +97,7 @@ 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 thow errors created by napi_create_error so far + // 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()); @@ -108,7 +108,7 @@ 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 thow errors created by napi_create_error so far + // 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()); diff --git a/interfaces/kits/js/src/common/uni_error.h b/interfaces/kits/js/src/common/uni_error.h index a4183986d..e1a2d8663 100644 --- a/interfaces/kits/js/src/common/uni_error.h +++ b/interfaces/kits/js/src/common/uni_error.h @@ -13,10 +13,8 @@ * limitations under the License. */ -#pragma once - -#include -#include +#ifndef INTERFACES_KITS_NAPI_COMMON_UNI_ERROR_H +#define INTERFACES_KITS_NAPI_COMMON_UNI_ERROR_H #include "napi/uni_header.h" @@ -40,6 +38,7 @@ public: UniError(); explicit UniError(ELegacy eLegacy); explicit UniError(int ePosix); + UniError(const UniError &) = default; ~UniError() = default; UniError &operator = (const UniError &) = default; @@ -61,4 +60,5 @@ private: ErrCodeSystem codingSystem_ = ERR_CODE_SYSTEM_POSIX; }; } // namespace DistributedFS -} // namespace OHOS \ No newline at end of file +} // namespace OHOS +#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 eacc54f8d..d2257d5a9 100644 --- a/interfaces/kits/js/src/mod_document/document_n_exporter.cpp +++ b/interfaces/kits/js/src/mod_document/document_n_exporter.cpp @@ -32,11 +32,13 @@ namespace ModuleDocument { napi_value Choose(napi_env env, napi_callback_info info) { UniError(EINVAL).ThrowErr(env, "error"); + return nullptr; } napi_value Show(napi_env env, napi_callback_info info) { UniError(EINVAL).ThrowErr(env, "error"); + return nullptr; } } // namespace ModuleDocument } // namespace DistributedFS diff --git a/interfaces/kits/js/src/mod_environment/environment_n_exporter.cpp b/interfaces/kits/js/src/mod_environment/environment_n_exporter.cpp new file mode 100644 index 000000000..a702f8b49 --- /dev/null +++ b/interfaces/kits/js/src/mod_environment/environment_n_exporter.cpp @@ -0,0 +1,101 @@ +/* + * 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. + */ + +#include "environment_n_exporter.h" + +#include + +#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) +{ + NFuncArg funcArg(env, info); + if (!funcArg.InitArgs(NARG_CNT::ZERO, NARG_CNT::ONE)) { + UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); + return nullptr; + } + + auto cbExec = [](napi_env env) -> UniError { + return UniError(ERRNO_NOERR); + }; + auto cbComplete = [](napi_env env, UniError err) -> NVal { + if (err) { + return { env, err.GetNapiErr(env) }; + } + return NVal::CreateUTF8String(env, STORAGE_DATA_PATH); + }; + + 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_; + } + return NVal::CreateUndefined(env).val_; +} + +int GetUserId() +{ + return 0; +} + +napi_value GetUserDataDir(napi_env env, napi_callback_info info) +{ + NFuncArg funcArg(env, info); + if (!funcArg.InitArgs(NARG_CNT::ZERO, NARG_CNT::ONE)) { + UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); + return nullptr; + } + + auto userDataPath = std::make_shared(); + auto cbExec = [userDataPath](napi_env env) -> UniError { + (*userDataPath).append("/storage/media/").append(std::to_string(GetUserId())).append("/local"); + return UniError(ERRNO_NOERR); + }; + auto cbComplete = [userDataPath](napi_env env, UniError err) -> NVal { + if (err) { + return { env, err.GetNapiErr(env) }; + } + return NVal::CreateUTF8String(env, *userDataPath); + }; + + 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_; + } + return NVal::CreateUndefined(env).val_; +} +} // namespace ModuleEnvironment +} // namespace DistributedFS +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_environment/environment_n_exporter.h b/interfaces/kits/js/src/mod_environment/environment_n_exporter.h new file mode 100644 index 000000000..1b46a7b96 --- /dev/null +++ b/interfaces/kits/js/src/mod_environment/environment_n_exporter.h @@ -0,0 +1,29 @@ +/* + * 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. + */ + +#ifndef ENVIRONMENT_N_EXPORTER_H +#define ENVIRONMENT_N_EXPORTER_H + +#include "../common/napi/n_exporter.h" + +namespace OHOS { +namespace DistributedFS { +namespace ModuleEnvironment { +napi_value GetStorageDataDir(napi_env env, napi_callback_info info); +napi_value GetUserDataDir(napi_env env, napi_callback_info info); +} // namespace ModuleEnvironment +} // namespace DistributedFS +} // namespace OHOS +#endif // ENVIRONMENT_N_EXPORTER_H \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_environment/environment_napi.cpp b/interfaces/kits/js/src/mod_environment/environment_napi.cpp new file mode 100644 index 000000000..67c338bad --- /dev/null +++ b/interfaces/kits/js/src/mod_environment/environment_napi.cpp @@ -0,0 +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. + */ + +#include "environment_napi.h" +#include "environment_n_exporter.h" + +#include "napi/native_api.h" +#include "napi/native_node_api.h" + +namespace OHOS { +namespace DistributedFS { +namespace ModuleEnvironment { +/*********************************************** + * Module export and register + ***********************************************/ +napi_value EnvironmentExport(napi_env env, napi_value exports) +{ + static napi_property_descriptor desc[] = { + DECLARE_NAPI_FUNCTION("getStorageDataDir", GetStorageDataDir), + DECLARE_NAPI_FUNCTION("getUserDataDir", GetUserDataDir), + }; + NAPI_CALL(env, napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc)); + return exports; +} + +NAPI_MODULE(environment, EnvironmentExport) +} // namespace ModuleEnvironment +} // namespace DistributedFS +} // namespace OHOS \ No newline at end of file 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 000000000..dd259e0aa --- /dev/null +++ b/interfaces/kits/js/src/mod_environment/environment_napi.h @@ -0,0 +1,27 @@ +/* + * 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. + */ + +#ifndef ENVIRONMENT_NAPI_H +#define ENVIRONMENT_NAPI_H + +#include "napi/native_api.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 new file mode 100644 index 000000000..842fd80b7 --- /dev/null +++ b/interfaces/kits/js/src/mod_file/class_file/file_n_exporter.cpp @@ -0,0 +1,1323 @@ +/* + * 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. + */ + +#include "file_n_exporter.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "../../common/ability_helper.h" +#include "../../common/file_helper/fd_guard.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_func.h" + +namespace OHOS { +namespace DistributedFS { +namespace ModuleFile { +using namespace std; + +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) +{ + 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(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 == "") { + return false; + } + string pathTmp = pathOrigin + 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); + } + if (uriSplit[SPLITE_ZERO] != "internal:" || uriSplit[spilteOne] != "" || uriSplit.size() <= spilteThree) { + return false; + } + AppExecFwk::Ability *ability = AbilityHelper::GetJsAbility(env); + if (!ability) { + return false; + } + auto abilityContext = ability->GetAbilityContext(); + if (abilityContext && uriSplit[spilteTwo] == "app") { + path = abilityContext->GetFilesDir(); + } else if (abilityContext && uriSplit[spilteTwo] == "cache") { + path = abilityContext->GetCacheDir(); + } else { + return false; + } + for (size_t i = spilteThree; 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 0; +} + +string UriToAbsolute(string path) +{ + stack uriResult; + 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; + } else if (urisp == ".." && !uriResult.empty()) { + uriResult.pop(); + } else { + uriResult.push(urisp); + } + } + path = ""; + while (!uriResult.empty()) { + path = "/" + uriResult.top() + path; + uriResult.pop(); + } + return path; +} + +bool GetFileNames(string path, vector &filenames, bool rec, bool isList) +{ + DIR *pDir; + struct dirent *ptr = nullptr; + if (!(pDir = opendir(path.c_str()))) { + return false; + } + while ((ptr = readdir(pDir)) != nullptr) { + if (strcmp(ptr->d_name, ".") != 0 && strcmp(ptr->d_name, "..") != 0) { + if (isList) { + filenames.push_back(path + "/" + ptr->d_name); + } else if (ptr->d_type == DT_DIR && rec && + GetFileNames(path + "/" + ptr->d_name, filenames, rec, isList) == false) { + break; + } else if (ptr->d_type == DT_REG) { + filenames.push_back(path + "/" + ptr->d_name); + } + } + } + closedir(pDir); + return true; +} + +bool Mkdirs(string path) +{ + for (size_t i = 1; i < path.length(); ++i) { + if (path[i] == '/') { + path[i] = '\0'; + if (access(path.c_str(), 0) != 0 && mkdir(path.c_str(), DIR_FAULT_PERM) == FAILED) { + return false; + } + path[i] = '/'; + } + } + if (path.length() <= 0 || access(path.c_str(), 0) == 0 || mkdir(path.c_str(), DIR_FAULT_PERM) == FAILED) { + return false; + } + return true; +} + +bool Rmdirs(string path) +{ + DIR *pDir; + struct dirent *ptr = nullptr; + if (!(pDir = opendir(path.c_str()))) { + return false; + } + while ((ptr = readdir(pDir)) != nullptr) { + if (strcmp(ptr->d_name, ".") != 0 && strcmp(ptr->d_name, "..") != 0) { + if ((ptr->d_type == DT_DIR && Rmdirs(path + "/" + ptr->d_name)) || + remove((path + "/" + ptr->d_name).c_str()) == 0) { + } else { + closedir(pDir); + return false; + } + } + } + closedir(pDir); + if (rmdir(path.c_str()) != 0) { + return false; + } + return true; +} + +string ConvertUri(string path, string originPath, string originUri) +{ + if (path.find(originPath) != path.npos) { + if (originUri[originUri.length() - 1] == '/') { + originUri = originUri.substr(0, originUri.length() - 1); + } + path.replace(0, originPath.length(), originUri); + } else { + return "error"; + } + return path; +} + +void MkdirExec(napi_env env, void *data) +{ + auto *asyncCallbackInfo = (AsyncMkdirCallbackInfo *)data; + string path = asyncCallbackInfo->url; + asyncCallbackInfo->result = FAILED; + asyncCallbackInfo->errorType = FILE_IO_ERROR; + if (GetRealPath(path) == ENOENT) { + path = UriToAbsolute(path); + if (asyncCallbackInfo->recursive && Mkdirs(path)) { + asyncCallbackInfo->result = SUCCESS; + } else if (mkdir((char *)path.c_str(), DIR_FAULT_PERM) != FAILED) { + asyncCallbackInfo->result = SUCCESS; + } + } +} + +void MkdirComp(napi_env env, napi_status status, void *data) +{ + auto *asyncCallbackInfo = (AsyncMkdirCallbackInfo *)data; + + if (asyncCallbackInfo->result == SUCCESS) { + CallBackSuccess(env, asyncCallbackInfo->callback[COMMON_NUM::ZERO], COMMON_NUM::ZERO, nullptr); + } else if (asyncCallbackInfo->result == FAILED) { + CallBackError(env, asyncCallbackInfo->callback[COMMON_NUM::ONE], "make directory failed", FILE_IO_ERROR); + } + CallComplete(env, asyncCallbackInfo->callback[COMMON_NUM::TWO]); + napi_delete_reference(env, asyncCallbackInfo->callback[COMMON_NUM::ZERO]); + napi_delete_reference(env, asyncCallbackInfo->callback[COMMON_NUM::ONE]); + napi_delete_reference(env, asyncCallbackInfo->callback[COMMON_NUM::TWO]); + napi_delete_async_work(env, asyncCallbackInfo->asyncWork); + delete asyncCallbackInfo; +} + +void RmdirExec(napi_env env, void *data) +{ + auto *asyncCallbackInfo = (AsyncRmdirCallbackInfo *)data; + string path = asyncCallbackInfo->url; + asyncCallbackInfo->result = FAILED; + asyncCallbackInfo->errorType = FILE_IO_ERROR; + int statPath = GetRealPath(path); + if (statPath == COMMON_NUM::ZERO) { + if (asyncCallbackInfo->recursive && Rmdirs(path)) { + asyncCallbackInfo->result = SUCCESS; + } else if (remove((char *)path.c_str()) != FAILED) { + asyncCallbackInfo->result = SUCCESS; + } + } else if (statPath == ENOENT) { + asyncCallbackInfo->errorType = FILE_PATH_ERROR; + } +} + +void RmdirComp(napi_env env, napi_status status, void *data) +{ + auto *asyncCallbackInfo = (AsyncRmdirCallbackInfo *)data; + if (asyncCallbackInfo->result == SUCCESS) { + CallBackSuccess(env, asyncCallbackInfo->callback[COMMON_NUM::ZERO], COMMON_NUM::ZERO, nullptr); + } else if (asyncCallbackInfo->errorType == FILE_IO_ERROR) { + CallBackError(env, asyncCallbackInfo->callback[COMMON_NUM::ONE], "remove directory failed", FILE_IO_ERROR); + } else if (asyncCallbackInfo->errorType == FILE_PATH_ERROR) { + CallBackError(env, asyncCallbackInfo->callback[COMMON_NUM::ONE], "file not exist", FILE_PATH_ERROR); + } + CallComplete(env, asyncCallbackInfo->callback[COMMON_NUM::TWO]); + napi_delete_reference(env, asyncCallbackInfo->callback[COMMON_NUM::ZERO]); + napi_delete_reference(env, asyncCallbackInfo->callback[COMMON_NUM::ONE]); + napi_delete_reference(env, asyncCallbackInfo->callback[COMMON_NUM::TWO]); + napi_delete_async_work(env, asyncCallbackInfo->asyncWork); + delete asyncCallbackInfo; +} + +void GetExec(napi_env env, void *data) +{ + auto *asyncCallbackInfo = (AsyncGetCallbackInfo *)data; + string path = asyncCallbackInfo->url; + asyncCallbackInfo->result = FAILED; + asyncCallbackInfo->errorType = FILE_IO_ERROR; + struct stat buf; + int statPath = GetRealPath(path); + if (statPath == COMMON_NUM::ZERO && stat((char *)path.c_str(), &buf) == COMMON_NUM::ZERO) { + asyncCallbackInfo->length = buf.st_size; + asyncCallbackInfo->lastMT = buf.st_mtime * COMMON_NUM::THOUSAND + + (int64_t)((buf.st_mtim).tv_nsec / COMMON_NUM::MILLION); + asyncCallbackInfo->url = path; + std::vector subFiles; + bool rec = asyncCallbackInfo->recursive; + if ((buf.st_mode & S_IFMT) == S_IFDIR && GetFileNames(path, subFiles, rec, false)) { + (asyncCallbackInfo->subFiles).assign(subFiles.begin(), subFiles.end()); + asyncCallbackInfo->type = TYPE_DIR; + asyncCallbackInfo->result = SUCCESS; + } else if ((buf.st_mode & S_IFMT) == S_IFREG) { + asyncCallbackInfo->type = TYPE_FILE; + asyncCallbackInfo->result = SUCCESS; + } + } else if (statPath == ENOENT) { + asyncCallbackInfo->errorType = FILE_PATH_ERROR; + } +} + +void GetComp(napi_env env, napi_status status, void *data) +{ + auto *asyncCallbackInfo = (AsyncGetCallbackInfo *)data; + if (asyncCallbackInfo->result == SUCCESS) { + napi_value subFilesNapi = nullptr; + napi_create_array(env, &subFilesNapi); + int32_t i = 0; + for (auto filename : asyncCallbackInfo->subFiles) { + napi_set_property( + env, subFilesNapi, NVal::CreateInt32(env, i).val_, + NVal::CreateUTF8String( + env, ConvertUri(filename, asyncCallbackInfo->url, asyncCallbackInfo->originUri).c_str()) + .val_); + i = i + 1; + } + NVal objn = NVal::CreateObject(env); + objn.AddProp("lastModifiedTime", NVal::CreateInt64(env, asyncCallbackInfo->lastMT).val_); + objn.AddProp("length", NVal::CreateInt32(env, asyncCallbackInfo->length).val_); + objn.AddProp("uri", NVal::CreateUTF8String(env, asyncCallbackInfo->originUri).val_); + objn.AddProp("type", NVal::CreateUTF8String(env, asyncCallbackInfo->type).val_); + objn.AddProp("subFiles", subFilesNapi); + + CallBackSuccess(env, asyncCallbackInfo->callback[COMMON_NUM::ZERO], COMMON_NUM::ONE, objn.val_); + } else if (asyncCallbackInfo->errorType == FILE_PATH_ERROR) { + CallBackError(env, asyncCallbackInfo->callback[COMMON_NUM::ONE], "file not exist", FILE_PATH_ERROR); + } else if (asyncCallbackInfo->errorType == FILE_IO_ERROR) { + CallBackError(env, asyncCallbackInfo->callback[COMMON_NUM::ONE], "get file failed", FILE_IO_ERROR); + } + CallComplete(env, asyncCallbackInfo->callback[COMMON_NUM::TWO]); + napi_delete_reference(env, asyncCallbackInfo->callback[COMMON_NUM::ZERO]); + napi_delete_reference(env, asyncCallbackInfo->callback[COMMON_NUM::ONE]); + napi_delete_reference(env, asyncCallbackInfo->callback[COMMON_NUM::TWO]); + napi_delete_async_work(env, asyncCallbackInfo->asyncWork); + delete asyncCallbackInfo; +} + +void ListExec(napi_env env, void *data) +{ + auto *asyncCallbackInfo = (AsyncListCallbackInfo *)data; + string path = asyncCallbackInfo->url; + asyncCallbackInfo->result = FAILED; + std::vector fileNames; + struct stat buf; + int statPath = GetRealPath(path); + if (statPath == ENOENT) { + asyncCallbackInfo->errorType = FILE_PATH_ERROR; + } else if (statPath != COMMON_NUM::ZERO || stat((char *)path.c_str(), &buf) != COMMON_NUM::ZERO) { + asyncCallbackInfo->errorType = FILE_IO_ERROR; + } else if ((buf.st_mode & S_IFMT) == S_IFREG) { + asyncCallbackInfo->result = SUCCESS; + } else { + asyncCallbackInfo->url = path; + bool getStat = GetFileNames(path, fileNames, false, true); + if (!getStat) { + asyncCallbackInfo->errorType = FILE_IO_ERROR; + } else { + vector fileList; + for (auto ph : fileNames) { + struct stat tmp; + int r = stat(ph.c_str(), &tmp); + FileInfo fi; + if (r == 0 && S_ISDIR(tmp.st_mode)) { + fi.type = TYPE_DIR; + } else if (r == 0 && (tmp.st_mode & S_IFMT) == S_IFREG) { + fi.type = TYPE_FILE; + } + fi.length = tmp.st_size; + fi.lastModifiedTime = tmp.st_mtime * COMMON_NUM::THOUSAND + + (int64_t)((tmp.st_mtim).tv_nsec / COMMON_NUM::MILLION); + fi.uri = ph; + fileList.push_back(fi); + } + (asyncCallbackInfo->fileList).assign(fileList.begin(), fileList.end()); + asyncCallbackInfo->result = SUCCESS; + } + } +} + +void ListComp(napi_env env, napi_status status, void *data) +{ + auto *asyncCallbackInfo = (AsyncListCallbackInfo *)data; + if (asyncCallbackInfo->result == SUCCESS) { + napi_value fileListNapi; + napi_create_array(env, &fileListNapi); + int32_t i = 0; + for (auto fileInfo : asyncCallbackInfo->fileList) { + NVal objt = NVal::CreateObject(env); + objt.AddProp("lastModifiedTime", NVal::CreateInt64(env, fileInfo.lastModifiedTime).val_); + objt.AddProp("length", NVal::CreateInt32(env, fileInfo.length).val_); + string uriTojs = ConvertUri(fileInfo.uri, asyncCallbackInfo->url, asyncCallbackInfo->originUri); + objt.AddProp("uri", NVal::CreateUTF8String(env, uriTojs).val_); + objt.AddProp("type", NVal::CreateUTF8String(env, fileInfo.type).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, asyncCallbackInfo->callback[COMMON_NUM::ZERO], COMMON_NUM::ONE, objn.val_); + } else if (asyncCallbackInfo->errorType == FILE_PATH_ERROR) { + CallBackError(env, asyncCallbackInfo->callback[COMMON_NUM::ONE], "file not exist", FILE_PATH_ERROR); + } else if (asyncCallbackInfo->errorType == FILE_IO_ERROR) { + CallBackError(env, asyncCallbackInfo->callback[COMMON_NUM::ONE], "list file failed", FILE_IO_ERROR); + } + CallComplete(env, asyncCallbackInfo->callback[COMMON_NUM::TWO]); + napi_delete_reference(env, asyncCallbackInfo->callback[COMMON_NUM::ZERO]); + napi_delete_reference(env, asyncCallbackInfo->callback[COMMON_NUM::ONE]); + napi_delete_reference(env, asyncCallbackInfo->callback[COMMON_NUM::TWO]); + napi_delete_async_work(env, asyncCallbackInfo->asyncWork); + delete asyncCallbackInfo; +} + +void CopyExec(napi_env env, void *data) +{ + auto *asyncCallbackInfo = (AsyncCopyCallbackInfo *)data; + string path = asyncCallbackInfo->url; + string pathDst = asyncCallbackInfo->urlDst; + asyncCallbackInfo->result = FAILED; + asyncCallbackInfo->errorType = FILE_IO_ERROR; + int statPath = GetRealPath(path); + int statDst = GetRealPath(pathDst); + if (statPath == COMMON_NUM::ZERO && statDst == ENOENT) { + pathDst = UriToAbsolute(pathDst); + struct stat statbf; + FDGuard sfd; + FDGuard ofd; + sfd.SetFD(open((char *)path.c_str(), O_RDONLY)); + int res = stat((char *)path.c_str(), &statbf); + ofd.SetFD(open((char *)pathDst.c_str(), O_WRONLY | O_CREAT, statbf.st_mode)); + if (sfd.GetFD() != FAILED && ofd.GetFD() != FAILED && res != FAILED && + sendfile(ofd.GetFD(), sfd.GetFD(), nullptr, statbf.st_size) != FAILED) { + asyncCallbackInfo->result = SUCCESS; + } + if (asyncCallbackInfo->result == FAILED) { + remove((char *)pathDst.c_str()); + } + } else if (statPath == ENOENT) { + asyncCallbackInfo->errorType = FILE_PATH_ERROR; + } +} + +void CopyComp(napi_env env, napi_status status, void *data) +{ + auto *asyncCallbackInfo = (AsyncCopyCallbackInfo *)data; + if (asyncCallbackInfo->result == SUCCESS) { + CallBackSuccess(env, asyncCallbackInfo->callback[COMMON_NUM::ZERO], COMMON_NUM::ONE, + NVal::CreateUTF8String(env, asyncCallbackInfo->originDst).val_); + } else if (asyncCallbackInfo->errorType == FILE_IO_ERROR) { + CallBackError(env, asyncCallbackInfo->callback[COMMON_NUM::ONE], "copy file failed", FILE_IO_ERROR); + } else if (asyncCallbackInfo->errorType == FILE_PATH_ERROR) { + CallBackError(env, asyncCallbackInfo->callback[COMMON_NUM::ONE], "file not exist", FILE_PATH_ERROR); + } + CallComplete(env, asyncCallbackInfo->callback[COMMON_NUM::TWO]); + napi_delete_reference(env, asyncCallbackInfo->callback[COMMON_NUM::ZERO]); + napi_delete_reference(env, asyncCallbackInfo->callback[COMMON_NUM::ONE]); + napi_delete_reference(env, asyncCallbackInfo->callback[COMMON_NUM::TWO]); + napi_delete_async_work(env, asyncCallbackInfo->asyncWork); + delete asyncCallbackInfo; +} + +void MoveExec(napi_env env, void *data) +{ + auto *asyncCallbackInfo = (AsyncMoveCallbackInfo *)data; + string path = asyncCallbackInfo->url; + string pathDst = asyncCallbackInfo->urlDst; + asyncCallbackInfo->result = FAILED; + asyncCallbackInfo->errorType = FILE_IO_ERROR; + int statPath = GetRealPath(path); + int statDst = GetRealPath(pathDst); + if (statPath == COMMON_NUM::ZERO && statDst == ENOENT) { + pathDst = UriToAbsolute(pathDst); + struct stat statbf; + FDGuard sfd; + FDGuard ofd; + sfd.SetFD(open((char *)path.c_str(), O_RDONLY)); + int res = stat((char *)path.c_str(), &statbf); + ofd.SetFD(open((char *)pathDst.c_str(), O_WRONLY | O_CREAT, statbf.st_mode)); + if (sfd.GetFD() != FAILED && ofd.GetFD() != FAILED && res != FAILED && + sendfile(ofd.GetFD(), sfd.GetFD(), nullptr, statbf.st_size) != FAILED) { + asyncCallbackInfo->result = SUCCESS; + remove((char *)path.c_str()); + } + if (asyncCallbackInfo->result == FAILED) { + asyncCallbackInfo->errorType = FILE_IO_ERROR; + remove((char *)pathDst.c_str()); + } + } else if (statPath == ENOENT) { + asyncCallbackInfo->errorType = FILE_PATH_ERROR; + } +} + +void MoveComp(napi_env env, napi_status status, void *data) +{ + auto *asyncCallbackInfo = (AsyncMoveCallbackInfo *)data; + if (asyncCallbackInfo->result == SUCCESS) { + CallBackSuccess(env, asyncCallbackInfo->callback[COMMON_NUM::ZERO], COMMON_NUM::ONE, + NVal::CreateUTF8String(env, asyncCallbackInfo->originDst).val_); + } else if (asyncCallbackInfo->errorType == FILE_IO_ERROR) { + CallBackError(env, asyncCallbackInfo->callback[COMMON_NUM::ONE], "move file failed", FILE_IO_ERROR); + } else if (asyncCallbackInfo->errorType == FILE_PATH_ERROR) { + CallBackError(env, asyncCallbackInfo->callback[COMMON_NUM::ONE], "file not exist", FILE_PATH_ERROR); + } + CallComplete(env, asyncCallbackInfo->callback[COMMON_NUM::TWO]); + napi_delete_reference(env, asyncCallbackInfo->callback[COMMON_NUM::ZERO]); + napi_delete_reference(env, asyncCallbackInfo->callback[COMMON_NUM::ONE]); + napi_delete_reference(env, asyncCallbackInfo->callback[COMMON_NUM::TWO]); + napi_delete_async_work(env, asyncCallbackInfo->asyncWork); + delete asyncCallbackInfo; +} + +void DeleteExec(napi_env env, void *data) +{ + auto *asyncCallbackInfo = (AsyncDeleteCallbackInfo *)data; + string path = asyncCallbackInfo->url; + asyncCallbackInfo->result = FAILED; + int statPath = GetRealPath(path); + if (statPath == ENOENT) { + asyncCallbackInfo->errorType = FILE_PATH_ERROR; + } else if (statPath == COMMON_NUM::ZERO && remove((char *)path.c_str()) != FAILED) { + asyncCallbackInfo->result = SUCCESS; + } else { + asyncCallbackInfo->errorType = FILE_IO_ERROR; + } +} + +void DeleteComp(napi_env env, napi_status status, void *data) +{ + auto *asyncCallbackInfo = (AsyncDeleteCallbackInfo *)data; + if (asyncCallbackInfo->result == SUCCESS) { + CallBackSuccess(env, asyncCallbackInfo->callback[COMMON_NUM::ZERO], COMMON_NUM::ZERO, nullptr); + } else if (asyncCallbackInfo->errorType == FILE_IO_ERROR) { + CallBackError(env, asyncCallbackInfo->callback[COMMON_NUM::ONE], "delete file failed", FILE_IO_ERROR); + } else if (asyncCallbackInfo->errorType == FILE_PATH_ERROR) { + CallBackError(env, asyncCallbackInfo->callback[COMMON_NUM::ONE], "file not exist", FILE_PATH_ERROR); + } + CallComplete(env, asyncCallbackInfo->callback[COMMON_NUM::TWO]); + napi_delete_reference(env, asyncCallbackInfo->callback[COMMON_NUM::ZERO]); + napi_delete_reference(env, asyncCallbackInfo->callback[COMMON_NUM::ONE]); + napi_delete_reference(env, asyncCallbackInfo->callback[COMMON_NUM::TWO]); + napi_delete_async_work(env, asyncCallbackInfo->asyncWork); + delete asyncCallbackInfo; +} + +void AccessExec(napi_env env, void *data) +{ + auto *asyncCallbackInfo = (AsyncAccessCallbackInfo *)data; + string path = asyncCallbackInfo->url; + asyncCallbackInfo->result = FAILED; + int statPath = GetRealPath(path); + if (statPath == ENOENT) { + asyncCallbackInfo->errorType = FILE_PATH_ERROR; + } else if (statPath == COMMON_NUM::ZERO) { + asyncCallbackInfo->result = SUCCESS; + } else { + asyncCallbackInfo->errorType = FILE_IO_ERROR; + } +} + +void AccessComp(napi_env env, napi_status status, void *data) +{ + auto *asyncCallbackInfo = (AsyncAccessCallbackInfo *)data; + if (asyncCallbackInfo->result == SUCCESS) { + CallBackSuccess(env, asyncCallbackInfo->callback[COMMON_NUM::ZERO], COMMON_NUM::ZERO, nullptr); + } else if (asyncCallbackInfo->errorType == FILE_IO_ERROR) { + CallBackError(env, asyncCallbackInfo->callback[COMMON_NUM::ONE], "access file failed", FILE_IO_ERROR); + } else if (asyncCallbackInfo->errorType == FILE_PATH_ERROR) { + CallBackError(env, asyncCallbackInfo->callback[COMMON_NUM::ONE], "file not exist", FILE_PATH_ERROR); + } + CallComplete(env, asyncCallbackInfo->callback[COMMON_NUM::TWO]); + napi_delete_reference(env, asyncCallbackInfo->callback[COMMON_NUM::ZERO]); + napi_delete_reference(env, asyncCallbackInfo->callback[COMMON_NUM::ONE]); + napi_delete_reference(env, asyncCallbackInfo->callback[COMMON_NUM::TWO]); + napi_delete_async_work(env, asyncCallbackInfo->asyncWork); + delete asyncCallbackInfo; +} + +void WriteTextExec(napi_env env, void *data) +{ + auto *asyncCallbackInfo = (AsyncWriteCallbackInfo *)data; + string path = asyncCallbackInfo->url; + string text = asyncCallbackInfo->text; + asyncCallbackInfo->result = FAILED; + asyncCallbackInfo->errorType = FILE_IO_ERROR; + int fd = -1; + int statPath = GetRealPath(path); + if (statPath == COMMON_NUM::ZERO || statPath == ENOENT) { + if (asyncCallbackInfo->append) { + fd = open(path.c_str(), O_WRONLY | O_APPEND | O_CREAT, S_IRUSR | S_IWUSR); + } else { + fd = open(path.c_str(), O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR); + } + if (fd != FAILED) { + if (write(fd, text.c_str(), text.length()) != FAILED) { + asyncCallbackInfo->result = SUCCESS; + } + close(fd); + } + } +} + +void WriteTextComp(napi_env env, napi_status status, void *data) +{ + auto *asyncCallbackInfo = (AsyncWriteCallbackInfo *)data; + if (asyncCallbackInfo->result == SUCCESS) { + CallBackSuccess(env, asyncCallbackInfo->callback[COMMON_NUM::ZERO], COMMON_NUM::ZERO, nullptr); + } else if (asyncCallbackInfo->errorType == FILE_IO_ERROR) { + CallBackError(env, asyncCallbackInfo->callback[COMMON_NUM::ONE], "write file failed", FILE_IO_ERROR); + } + CallComplete(env, asyncCallbackInfo->callback[COMMON_NUM::TWO]); + napi_delete_reference(env, asyncCallbackInfo->callback[COMMON_NUM::ZERO]); + napi_delete_reference(env, asyncCallbackInfo->callback[COMMON_NUM::ONE]); + napi_delete_reference(env, asyncCallbackInfo->callback[COMMON_NUM::TWO]); + napi_delete_async_work(env, asyncCallbackInfo->asyncWork); + delete asyncCallbackInfo; +} + +void WriteArrayBufferExec(napi_env env, void *data) +{ + auto *asyncCallbackInfo = (AsyncWriteBufferCallbackInfo *)data; + string path = asyncCallbackInfo->url; + asyncCallbackInfo->result = FAILED; + asyncCallbackInfo->errorType = FILE_IO_ERROR; + int fd = -1; + int statPath = GetRealPath(path); + if (statPath == COMMON_NUM::ZERO || statPath == ENOENT) { + if (asyncCallbackInfo->append) { + fd = open(path.c_str(), O_WRONLY | O_APPEND | O_CREAT, S_IRUSR | S_IWUSR); + if (fd == FAILED) { + return; + } + } else { + fd = open(path.c_str(), O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR); + if (fd == FAILED) { + return; + } + lseek(fd, asyncCallbackInfo->position, SEEK_CUR); + } + if (write(fd, asyncCallbackInfo->buf, asyncCallbackInfo->length) != FAILED) { + asyncCallbackInfo->result = SUCCESS; + } + close(fd); + } +} + +void WriteArrayBufferComp(napi_env env, napi_status status, void *data) +{ + auto *asyncCallbackInfo = (AsyncWriteBufferCallbackInfo *)data; + if (asyncCallbackInfo->result == SUCCESS) { + CallBackSuccess(env, asyncCallbackInfo->callback[COMMON_NUM::ZERO], COMMON_NUM::ZERO, nullptr); + } else if (asyncCallbackInfo->errorType == FILE_IO_ERROR) { + CallBackError(env, asyncCallbackInfo->callback[COMMON_NUM::ONE], "write file failed", FILE_IO_ERROR); + } + CallComplete(env, asyncCallbackInfo->callback[COMMON_NUM::TWO]); + napi_delete_reference(env, asyncCallbackInfo->callback[COMMON_NUM::ZERO]); + napi_delete_reference(env, asyncCallbackInfo->callback[COMMON_NUM::ONE]); + napi_delete_reference(env, asyncCallbackInfo->callback[COMMON_NUM::TWO]); + napi_delete_reference(env, asyncCallbackInfo->bufferAddress); + napi_delete_async_work(env, asyncCallbackInfo->asyncWork); + delete asyncCallbackInfo; +} + +void ReadTextExec(napi_env env, void *data) +{ + auto *asyncCallbackInfo = (AsyncReadCallbackInfo *)data; + string path = asyncCallbackInfo->url; + asyncCallbackInfo->result = FAILED; + asyncCallbackInfo->errorType = FILE_IO_ERROR; + int statPath = GetRealPath(path); + if (statPath == COMMON_NUM::ZERO) { + FDGuard fdg; + fdg.SetFD(open(path.c_str(), O_RDONLY)); + struct stat buf; + int result = stat((char *)path.c_str(), &buf); + if (fdg.GetFD() != FAILED && result != FAILED) { + auto buffer = std::make_unique(buf.st_size + 1); + if (buffer == nullptr) { + UniError(ENOMEM).ThrowErr(env); + return; + } + if (read(fdg.GetFD(), buffer.get(), buf.st_size) != FAILED) { + asyncCallbackInfo->result = SUCCESS; + asyncCallbackInfo->contents = std::string(buffer.get()); + } + } + } else if (statPath == ENOENT) { + asyncCallbackInfo->errorType = FILE_PATH_ERROR; + } +} + +void ReadTextComp(napi_env env, napi_status status, void *data) +{ + auto *asyncCallbackInfo = (AsyncReadCallbackInfo *)data; + if (asyncCallbackInfo->result == SUCCESS) { + NVal objn = NVal::CreateObject(env); + objn.AddProp("text", NVal::CreateUTF8String(env, asyncCallbackInfo->contents).val_); + CallBackSuccess(env, asyncCallbackInfo->callback[COMMON_NUM::ZERO], COMMON_NUM::ONE, objn.val_); + } else if (asyncCallbackInfo->errorType == FILE_IO_ERROR) { + CallBackError(env, asyncCallbackInfo->callback[COMMON_NUM::ONE], "read file failed", FILE_IO_ERROR); + } else if (asyncCallbackInfo->errorType == FILE_PATH_ERROR) { + CallBackError(env, asyncCallbackInfo->callback[COMMON_NUM::ONE], "file not exist", FILE_PATH_ERROR); + } + CallComplete(env, asyncCallbackInfo->callback[COMMON_NUM::TWO]); + napi_delete_reference(env, asyncCallbackInfo->callback[COMMON_NUM::ZERO]); + napi_delete_reference(env, asyncCallbackInfo->callback[COMMON_NUM::ONE]); + napi_delete_reference(env, asyncCallbackInfo->callback[COMMON_NUM::TWO]); + napi_delete_async_work(env, asyncCallbackInfo->asyncWork); + delete asyncCallbackInfo; +} + +void ReadArrayBufferExec(napi_env env, void *data) +{ + auto *asyncCallbackInfo = (AsyncReadBufferCallbackInfo *)data; + string path = asyncCallbackInfo->url; + asyncCallbackInfo->result = FAILED; + asyncCallbackInfo->errorType = FILE_IO_ERROR; + int statPath = GetRealPath(path); + if (statPath == COMMON_NUM::ZERO) { + FDGuard fdg; + fdg.SetFD(open(path.c_str(), O_RDONLY)); + struct stat buf; + int result = stat((char *)path.c_str(), &buf); + if (fdg.GetFD() != FAILED && result != FAILED) { + int32_t begin = (buf.st_size < asyncCallbackInfo->position) ? buf.st_size : asyncCallbackInfo->position; + int32_t len = + (asyncCallbackInfo->length == COMMON_NUM::ZERO) ? (buf.st_size - begin) : asyncCallbackInfo->length; + auto buffer = std::make_unique(len + 1); + if (buffer == nullptr) { + UniError(ENOMEM).ThrowErr(env); + return; + } + lseek(fdg.GetFD(), begin, SEEK_CUR); + if (read(fdg.GetFD(), buffer.get(), len) != FAILED) { + asyncCallbackInfo->result = SUCCESS; + asyncCallbackInfo->len = len; + asyncCallbackInfo->contents = std::string(buffer.get()); + } + } + } else if (statPath == ENOENT) { + asyncCallbackInfo->errorType = FILE_PATH_ERROR; + } +} + +void ReadArrayBufferComp(napi_env env, napi_status status, void *data) +{ + auto *asyncCallbackInfo = (AsyncReadBufferCallbackInfo *)data; + if (asyncCallbackInfo->result == SUCCESS) { + napi_value typeArr = nullptr; + napi_create_array(env, &typeArr); + for (int32_t i = 0; i < asyncCallbackInfo->len; ++i) { + napi_set_property(env, typeArr, NVal::CreateInt32(env, i).val_, + NVal::CreateInt32(env, (int32_t)(asyncCallbackInfo->contents)[i]).val_); + } + NVal objn = NVal::CreateObject(env); + objn.AddProp("buffer", typeArr); + CallBackSuccess(env, asyncCallbackInfo->callback[COMMON_NUM::ZERO], COMMON_NUM::ONE, objn.val_); + } else if (asyncCallbackInfo->errorType == FILE_IO_ERROR) { + CallBackError(env, asyncCallbackInfo->callback[COMMON_NUM::ONE], "read file failed", FILE_IO_ERROR); + } else if (asyncCallbackInfo->errorType == FILE_PATH_ERROR) { + CallBackError(env, asyncCallbackInfo->callback[COMMON_NUM::ONE], "file not exist", FILE_PATH_ERROR); + } + CallComplete(env, asyncCallbackInfo->callback[COMMON_NUM::TWO]); + napi_delete_reference(env, asyncCallbackInfo->callback[COMMON_NUM::ZERO]); + napi_delete_reference(env, asyncCallbackInfo->callback[COMMON_NUM::ONE]); + napi_delete_reference(env, asyncCallbackInfo->callback[COMMON_NUM::TWO]); + napi_delete_async_work(env, asyncCallbackInfo->asyncWork); + delete asyncCallbackInfo; +} + +napi_value FileNExporter::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; + } + bool succ = false; + auto *asyncCallbackInfo = new AsyncMkdirCallbackInfo { + .env = env, + .asyncWork = nullptr, + }; + tie(succ, asyncCallbackInfo->callback[COMMON_NUM::ZERO], asyncCallbackInfo->callback[COMMON_NUM::ONE], + asyncCallbackInfo->callback[COMMON_NUM::TWO]) = CommonFunc::GetCallbackHandles(env, funcArg[NARG_POS::FIRST]); + + unique_ptr uri; + tie(succ, uri, ignore) = NVal(env, funcArg[NARG_POS::FIRST]).GetProp("uri").ToUTF8String(); + + bool recursive = false; + tie(succ, recursive) = NVal(env, funcArg[NARG_POS::FIRST]).GetProp("recursive").ToBool(); + + string path = (uri == nullptr) ? "" : uri.get(); + if (!CheckUri(env, path)) { + CallBackError(env, asyncCallbackInfo->callback[COMMON_NUM::ONE], "illegal uri", URI_PARAMER_ERROR); + CallComplete(env, asyncCallbackInfo->callback[COMMON_NUM::TWO]); + delete asyncCallbackInfo; + return nullptr; + } + asyncCallbackInfo->recursive = recursive; + asyncCallbackInfo->url = path; + + napi_create_async_work(env, nullptr, NVal::CreateUTF8String(env, "ResourceName").val_, MkdirExec, MkdirComp, + (void *)asyncCallbackInfo, &asyncCallbackInfo->asyncWork); + napi_queue_async_work(env, asyncCallbackInfo->asyncWork); + return NVal::CreateUndefined(env).val_; +} + +napi_value FileNExporter::Rmdir(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; + auto *asyncCallbackInfo = new AsyncRmdirCallbackInfo { + .env = env, + .asyncWork = nullptr, + }; + tie(succ, asyncCallbackInfo->callback[COMMON_NUM::ZERO], asyncCallbackInfo->callback[COMMON_NUM::ONE], + asyncCallbackInfo->callback[COMMON_NUM::TWO]) = CommonFunc::GetCallbackHandles(env, funcArg[NARG_POS::FIRST]); + + unique_ptr uri; + tie(succ, uri, ignore) = NVal(env, funcArg[NARG_POS::FIRST]).GetProp("uri").ToUTF8String(); + + bool recursive = false; + tie(succ, recursive) = NVal(env, funcArg[NARG_POS::FIRST]).GetProp("recursive").ToBool(); + + string path = (uri == nullptr) ? "" : uri.get(); + if (!CheckUri(env, path)) { + CallBackError(env, asyncCallbackInfo->callback[COMMON_NUM::ONE], "illegal uri", URI_PARAMER_ERROR); + CallComplete(env, asyncCallbackInfo->callback[COMMON_NUM::TWO]); + delete asyncCallbackInfo; + return nullptr; + } + asyncCallbackInfo->recursive = recursive; + asyncCallbackInfo->url = path; + + napi_create_async_work(env, nullptr, NVal::CreateUTF8String(env, "ResourceName").val_, RmdirExec, RmdirComp, + (void *)asyncCallbackInfo, &asyncCallbackInfo->asyncWork); + napi_queue_async_work(env, asyncCallbackInfo->asyncWork); + + return NVal::CreateUndefined(env).val_; +} + +napi_value FileNExporter::Get(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 *asyncCallbackInfo = new AsyncGetCallbackInfo { + .env = env, + .asyncWork = nullptr, + }; + 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]); + unique_ptr uri = nullptr; + tie(succ, uri, ignore) = NVal(env, funcArg[NARG_POS::FIRST]).GetProp("uri").ToUTF8String(); + + bool recursive = false; + tie(succ, recursive) = NVal(env, funcArg[NARG_POS::FIRST]).GetProp("recursive").ToBool(); + string path = (uri == nullptr) ? "" : uri.get(); + asyncCallbackInfo->originUri = path; + if (!CheckUri(env, path)) { + CallBackError(env, asyncCallbackInfo->callback[COMMON_NUM::ONE], "illegal uri", URI_PARAMER_ERROR); + CallComplete(env, asyncCallbackInfo->callback[COMMON_NUM::TWO]); + delete asyncCallbackInfo; + return nullptr; + } + asyncCallbackInfo->recursive = recursive; + asyncCallbackInfo->url = path; + + napi_create_async_work(env, nullptr, NVal::CreateUTF8String(env, "ResourceName").val_, GetExec, GetComp, + (void *)asyncCallbackInfo, &asyncCallbackInfo->asyncWork); + napi_queue_async_work(env, asyncCallbackInfo->asyncWork); + + return NVal::CreateUndefined(env).val_; +} + +napi_value FileNExporter::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 *asyncCallbackInfo = new AsyncListCallbackInfo { + .env = env, + .asyncWork = nullptr, + }; + 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]); + + unique_ptr uri = nullptr; + tie(succ, uri, ignore) = NVal(env, funcArg[NARG_POS::FIRST]).GetProp("uri").ToUTF8String(); + + string path = (uri == nullptr) ? "" : uri.get(); + asyncCallbackInfo->originUri = path; + if (!CheckUri(env, path)) { + CallBackError(env, asyncCallbackInfo->callback[COMMON_NUM::ONE], "illegal uri", URI_PARAMER_ERROR); + CallComplete(env, asyncCallbackInfo->callback[COMMON_NUM::TWO]); + delete asyncCallbackInfo; + return nullptr; + } + asyncCallbackInfo->url = path; + + napi_create_async_work(env, nullptr, NVal::CreateUTF8String(env, "ResourceName").val_, ListExec, ListComp, + (void *)asyncCallbackInfo, &asyncCallbackInfo->asyncWork); + napi_queue_async_work(env, asyncCallbackInfo->asyncWork); + + return NVal::CreateUndefined(env).val_; +} + +napi_value FileNExporter::Copy(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; + auto *asyncCallbackInfo = new AsyncCopyCallbackInfo { + .env = env, + .asyncWork = nullptr, + }; + tie(succ, asyncCallbackInfo->callback[COMMON_NUM::ZERO], asyncCallbackInfo->callback[COMMON_NUM::ONE], + asyncCallbackInfo->callback[COMMON_NUM::TWO]) = CommonFunc::GetCallbackHandles(env, funcArg[NARG_POS::FIRST]); + + unique_ptr srcUri, dstUri; + tie(succ, srcUri, ignore) = NVal(env, funcArg[NARG_POS::FIRST]).GetProp("srcUri").ToUTF8String(); + tie(succ, dstUri, ignore) = NVal(env, funcArg[NARG_POS::FIRST]).GetProp("dstUri").ToUTF8String(); + string srcPath = ((srcUri == nullptr) ? "" : (srcUri.get())); + string dstPath = ((dstUri == nullptr) ? "" : (dstUri.get())); + asyncCallbackInfo->originDst = dstPath; + if (!CheckUri(env, srcPath) || !CheckUri(env, dstPath)) { + CallBackError(env, asyncCallbackInfo->callback[COMMON_NUM::ONE], "illegal uri", URI_PARAMER_ERROR); + CallComplete(env, asyncCallbackInfo->callback[COMMON_NUM::TWO]); + delete asyncCallbackInfo; + return nullptr; + } + asyncCallbackInfo->url = srcPath; + asyncCallbackInfo->urlDst = dstPath; + + napi_create_async_work(env, nullptr, NVal::CreateUTF8String(env, "ResourceName").val_, CopyExec, CopyComp, + (void *)asyncCallbackInfo, &asyncCallbackInfo->asyncWork); + napi_queue_async_work(env, asyncCallbackInfo->asyncWork); + return NVal::CreateUndefined(env).val_; +} + +napi_value FileNExporter::Move(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; + auto *asyncCallbackInfo = new AsyncMoveCallbackInfo { + .env = env, + .asyncWork = nullptr, + }; + tie(succ, asyncCallbackInfo->callback[COMMON_NUM::ZERO], asyncCallbackInfo->callback[COMMON_NUM::ONE], + asyncCallbackInfo->callback[COMMON_NUM::TWO]) = CommonFunc::GetCallbackHandles(env, funcArg[NARG_POS::FIRST]); + + unique_ptr srcUri, dstUri; + tie(succ, srcUri, ignore) = NVal(env, funcArg[NARG_POS::FIRST]).GetProp("srcUri").ToUTF8String(); + tie(succ, dstUri, ignore) = NVal(env, funcArg[NARG_POS::FIRST]).GetProp("dstUri").ToUTF8String(); + + string srcPath = ((srcUri == nullptr) ? "" : (srcUri.get())); + string dstPath = ((dstUri == nullptr) ? "" : (dstUri.get())); + asyncCallbackInfo->originDst = dstPath; + if (!CheckUri(env, srcPath) || !CheckUri(env, dstPath)) { + CallBackError(env, asyncCallbackInfo->callback[COMMON_NUM::ONE], "illegal uri", URI_PARAMER_ERROR); + CallComplete(env, asyncCallbackInfo->callback[COMMON_NUM::TWO]); + delete asyncCallbackInfo; + return nullptr; + } + asyncCallbackInfo->url = srcPath; + asyncCallbackInfo->urlDst = dstPath; + + napi_create_async_work(env, nullptr, NVal::CreateUTF8String(env, "ResourceName").val_, MoveExec, MoveComp, + (void *)asyncCallbackInfo, &asyncCallbackInfo->asyncWork); + napi_queue_async_work(env, asyncCallbackInfo->asyncWork); + return NVal::CreateUndefined(env).val_; +} + +napi_value FileNExporter::Delete(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; + auto *asyncCallbackInfo = new AsyncDeleteCallbackInfo { + .env = env, + .asyncWork = nullptr, + }; + tie(succ, asyncCallbackInfo->callback[COMMON_NUM::ZERO], asyncCallbackInfo->callback[COMMON_NUM::ONE], + asyncCallbackInfo->callback[COMMON_NUM::TWO]) = CommonFunc::GetCallbackHandles(env, funcArg[NARG_POS::FIRST]); + + unique_ptr uri; + tie(succ, uri, ignore) = NVal(env, funcArg[NARG_POS::FIRST]).GetProp("uri").ToUTF8String(); + + string path = (uri == nullptr) ? "" : uri.get(); + if (!CheckUri(env, path)) { + CallBackError(env, asyncCallbackInfo->callback[COMMON_NUM::ONE], "illegal uri", URI_PARAMER_ERROR); + CallComplete(env, asyncCallbackInfo->callback[COMMON_NUM::TWO]); + delete asyncCallbackInfo; + return nullptr; + } + asyncCallbackInfo->url = path; + + napi_create_async_work(env, nullptr, NVal::CreateUTF8String(env, "ResourceName").val_, DeleteExec, DeleteComp, + (void *)asyncCallbackInfo, &asyncCallbackInfo->asyncWork); + napi_queue_async_work(env, asyncCallbackInfo->asyncWork); + + return NVal::CreateUndefined(env).val_; +} + +napi_value FileNExporter::Access(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; + AsyncAccessCallbackInfo *asyncCallbackInfo = new AsyncAccessCallbackInfo { + .env = env, + .asyncWork = nullptr, + }; + tie(succ, asyncCallbackInfo->callback[COMMON_NUM::ZERO], asyncCallbackInfo->callback[COMMON_NUM::ONE], + asyncCallbackInfo->callback[COMMON_NUM::TWO]) = CommonFunc::GetCallbackHandles(env, funcArg[NARG_POS::FIRST]); + + unique_ptr uri; + tie(succ, uri, ignore) = NVal(env, funcArg[NARG_POS::FIRST]).GetProp("uri").ToUTF8String(); + + string path = (uri == nullptr) ? "" : uri.get(); + if (!CheckUri(env, path)) { + CallBackError(env, asyncCallbackInfo->callback[COMMON_NUM::ONE], "illegal uri", URI_PARAMER_ERROR); + CallComplete(env, asyncCallbackInfo->callback[COMMON_NUM::TWO]); + delete asyncCallbackInfo; + return nullptr; + } + asyncCallbackInfo->url = path; + + napi_create_async_work(env, nullptr, NVal::CreateUTF8String(env, "ResourceName").val_, AccessExec, AccessComp, + (void *)asyncCallbackInfo, &asyncCallbackInfo->asyncWork); + napi_queue_async_work(env, asyncCallbackInfo->asyncWork); + return NVal::CreateUndefined(env).val_; +} + +napi_value FileNExporter::WriteText(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 *asyncCallbackInfo = new AsyncWriteCallbackInfo { + .env = env, + .asyncWork = nullptr, + }; + 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]); + + unique_ptr uri, text, encoding; + tie(succ, uri, ignore) = NVal(env, funcArg[NARG_POS::FIRST]).GetProp("uri").ToUTF8String(); + tie(succ, text, ignore) = NVal(env, funcArg[NARG_POS::FIRST]).GetProp("text").ToUTF8String(); + tie(succ, encoding, ignore) = NVal(env, funcArg[NARG_POS::FIRST]).GetProp("encoding").ToUTF8String(); + + bool append = false; + tie(succ, append) = NVal(env, funcArg[NARG_POS::FIRST]).GetProp("append").ToBool(); + + string path = (uri == nullptr) ? "" : uri.get(); + string encode = (encoding == nullptr) ? ENCODING_UTF8 : encoding.get(); + transform(encode.begin(), encode.end(), encode.begin(), ::tolower); + if (!CheckUri(env, path)) { + CallBackError(env, asyncCallbackInfo->callback[COMMON_NUM::ONE], "illegal uri", URI_PARAMER_ERROR); + CallComplete(env, asyncCallbackInfo->callback[COMMON_NUM::TWO]); + delete asyncCallbackInfo; + return nullptr; + } + if (encode != ENCODING_UTF8) { + CallBackError(env, asyncCallbackInfo->callback[COMMON_NUM::ONE], "write file failed", FILE_IO_ERROR); + CallComplete(env, asyncCallbackInfo->callback[COMMON_NUM::TWO]); + delete asyncCallbackInfo; + return nullptr; + } + string content = text.get(); + asyncCallbackInfo->url = path; + asyncCallbackInfo->text = content; + asyncCallbackInfo->append = append; + + napi_create_async_work(env, nullptr, NVal::CreateUTF8String(env, "ResourceName").val_, WriteTextExec, WriteTextComp, + (void *)asyncCallbackInfo, &asyncCallbackInfo->asyncWork); + napi_queue_async_work(env, asyncCallbackInfo->asyncWork); + return NVal::CreateUndefined(env).val_; +} + +napi_value FileNExporter::WriteArrayBuffer(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; + auto *asyncCallbackInfo = new AsyncWriteBufferCallbackInfo { + .env = env, + .asyncWork = nullptr, + }; + tie(succ, asyncCallbackInfo->callback[COMMON_NUM::ZERO], asyncCallbackInfo->callback[COMMON_NUM::ONE], + asyncCallbackInfo->callback[COMMON_NUM::TWO]) = CommonFunc::GetCallbackHandles(env, funcArg[NARG_POS::FIRST]); + + unique_ptr uri; + tie(succ, uri, ignore) = NVal(env, funcArg[NARG_POS::FIRST]).GetProp("uri").ToUTF8String(); + + int32_t position = 0; + tie(succ, position) = NVal(env, funcArg[NARG_POS::FIRST]).GetProp("position").ToInt32(); + + bool append = false; + tie(succ, append) = NVal(env, funcArg[NARG_POS::FIRST]).GetProp("append").ToBool(); + + void *buffer = nullptr; + size_t bufLength = 0; + napi_ref bufferRef = nullptr; + NVal bufNapi = NVal(env, funcArg[NARG_POS::FIRST]).GetProp("buffer"); + tie(succ, buffer, bufLength) = bufNapi.ToTypedArray(); + napi_create_reference(env, bufNapi.val_, 1, &bufferRef); + + string path = (uri == nullptr) ? "" : uri.get(); + if (!CheckUri(env, path)) { + CallBackError(env, asyncCallbackInfo->callback[COMMON_NUM::ONE], "illegal uri", URI_PARAMER_ERROR); + CallComplete(env, asyncCallbackInfo->callback[COMMON_NUM::TWO]); + delete asyncCallbackInfo; + return nullptr; + } + int32_t bufLen { bufLength }; + asyncCallbackInfo->url = path; + asyncCallbackInfo->position = position; + asyncCallbackInfo->append = append; + asyncCallbackInfo->buf = buffer; + asyncCallbackInfo->length = bufLen; + asyncCallbackInfo->bufferAddress = bufferRef; + + napi_create_async_work(env, nullptr, NVal::CreateUTF8String(env, "ResourceName").val_, WriteArrayBufferExec, + WriteArrayBufferComp, (void *)asyncCallbackInfo, &asyncCallbackInfo->asyncWork); + napi_queue_async_work(env, asyncCallbackInfo->asyncWork); + return NVal::CreateUndefined(env).val_; +} + +napi_value FileNExporter::ReadText(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; + auto *asyncCallbackInfo = new AsyncReadCallbackInfo { + .env = env, + .asyncWork = nullptr, + }; + tie(succ, asyncCallbackInfo->callback[COMMON_NUM::ZERO], asyncCallbackInfo->callback[COMMON_NUM::ONE], + asyncCallbackInfo->callback[COMMON_NUM::TWO]) = CommonFunc::GetCallbackHandles(env, funcArg[NARG_POS::FIRST]); + + unique_ptr uri, encoding; + tie(succ, uri, ignore) = NVal(env, funcArg[NARG_POS::FIRST]).GetProp("uri").ToUTF8String(); + tie(succ, encoding, ignore) = NVal(env, funcArg[NARG_POS::FIRST]).GetProp("encoding").ToUTF8String(); + + string path = (uri == nullptr) ? "" : uri.get(); + string encode = (encoding == nullptr) ? ENCODING_UTF8 : encoding.get(); + transform(encode.begin(), encode.end(), encode.begin(), ::tolower); + if (!CheckUri(env, path)) { + CallBackError(env, asyncCallbackInfo->callback[COMMON_NUM::ONE], "illegal uri", URI_PARAMER_ERROR); + CallComplete(env, asyncCallbackInfo->callback[COMMON_NUM::TWO]); + delete asyncCallbackInfo; + return nullptr; + } + if (encode != ENCODING_UTF8) { + CallBackError(env, asyncCallbackInfo->callback[COMMON_NUM::ONE], "read file failed", FILE_IO_ERROR); + CallComplete(env, asyncCallbackInfo->callback[COMMON_NUM::TWO]); + delete asyncCallbackInfo; + return nullptr; + } + asyncCallbackInfo->url = path; + + napi_create_async_work(env, nullptr, NVal::CreateUTF8String(env, "ResourceName").val_, ReadTextExec, ReadTextComp, + (void *)asyncCallbackInfo, &asyncCallbackInfo->asyncWork); + napi_queue_async_work(env, asyncCallbackInfo->asyncWork); + return NVal::CreateUndefined(env).val_; +} + +napi_value FileNExporter::ReadArrayBuffer(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 *asyncCallbackInfo = new AsyncReadBufferCallbackInfo { + .env = env, + .asyncWork = nullptr, + }; + 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]); + + unique_ptr uri; + tie(succ, uri, ignore) = NVal(env, funcArg[NARG_POS::FIRST]).GetProp("uri").ToUTF8String(); + + int position = 0; + tie(succ, position) = NVal(env, funcArg[NARG_POS::FIRST]).GetProp("position").ToInt32(); + + int length = 0; + tie(succ, length) = NVal(env, funcArg[NARG_POS::FIRST]).GetProp("length").ToInt32(); + + string path = (uri == nullptr) ? "" : uri.get(); + if (!CheckUri(env, path)) { + CallBackError(env, asyncCallbackInfo->callback[COMMON_NUM::ONE], "illegal uri", URI_PARAMER_ERROR); + CallComplete(env, asyncCallbackInfo->callback[COMMON_NUM::TWO]); + delete asyncCallbackInfo; + return nullptr; + } + asyncCallbackInfo->url = path; + asyncCallbackInfo->length = length; + asyncCallbackInfo->position = position; + + napi_create_async_work(env, nullptr, NVal::CreateUTF8String(env, "ResourceName").val_, ReadArrayBufferExec, + ReadArrayBufferComp, (void *)asyncCallbackInfo, &asyncCallbackInfo->asyncWork); + napi_queue_async_work(env, asyncCallbackInfo->asyncWork); + return NVal::CreateUndefined(env).val_; +} + +bool FileNExporter::Export() +{ + return exports_.AddProp({ + NVal::DeclareNapiFunction("mkdir", Mkdir), + NVal::DeclareNapiFunction("rmdir", Rmdir), + NVal::DeclareNapiFunction("get", Get), + NVal::DeclareNapiFunction("list", List), + NVal::DeclareNapiFunction("copy", Copy), + NVal::DeclareNapiFunction("move", Move), + NVal::DeclareNapiFunction("delete", Delete), + NVal::DeclareNapiFunction("access", Access), + NVal::DeclareNapiFunction("writeText", WriteText), + NVal::DeclareNapiFunction("writeArrayBuffer", WriteArrayBuffer), + NVal::DeclareNapiFunction("readText", ReadText), + NVal::DeclareNapiFunction("readArrayBuffer", ReadArrayBuffer), + }); +} + +string FileNExporter::GetClassName() +{ + return FileNExporter::className_; +} + +FileNExporter::FileNExporter(napi_env env, napi_value exports) + : NExporter(env, exports) +{} + +FileNExporter::~FileNExporter() {} +} // namespace ModuleFile +} // namespace DistributedFS +} // namespace OHOS \ No newline at end of file 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 new file mode 100644 index 000000000..050f2779b --- /dev/null +++ b/interfaces/kits/js/src/mod_file/class_file/file_n_exporter.h @@ -0,0 +1,198 @@ +/* + * 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. + */ + +#pragma once + +#include "../../common/napi/n_exporter.h" + +namespace OHOS { +namespace DistributedFS { +namespace ModuleFile { +enum COMMON_NUM { + ZERO = 0, + ONE = 1, + TWO = 2, + THOUSAND = 1000, + MILLION = 1000000, +}; + +struct FileInfo { + int32_t length = 0; + int64_t lastModifiedTime = 0; + std::string type = ""; + std::string uri = ""; +}; + +struct AsyncAccessCallbackInfo { + napi_env env = nullptr; + napi_async_work asyncWork = nullptr; + napi_ref callback[3] = { 0 }; + std::string url = ""; + int errorType = -1; + int result = -100; +}; + +struct AsyncMkdirCallbackInfo { + napi_env env = nullptr; + napi_async_work asyncWork = nullptr; + napi_ref callback[3] = { 0 }; + bool recursive = false; + std::string url = ""; + int result = -100; + int errorType = -1; +}; + +struct AsyncRmdirCallbackInfo { + napi_env env = nullptr; + napi_async_work asyncWork = nullptr; + napi_ref callback[3] = { 0 }; + bool recursive = false; + std::string url = ""; + int result = -100; + int errorType = -1; +}; + +struct AsyncGetCallbackInfo { + napi_env env = nullptr; + napi_async_work asyncWork = nullptr; + napi_ref callback[3] = { 0 }; + bool recursive = false; + std::string url = ""; + std::string originUri = ""; + int result = -100; + int errorType = -1; + int32_t length = 0; + int64_t lastMT = 0; + std::string type = ""; + std::vector subFiles; +}; + +struct AsyncListCallbackInfo { + napi_env env = nullptr; + napi_async_work asyncWork = nullptr; + napi_ref callback[3] = { 0 }; + bool recursive = false; + std::string url = ""; + std::string originUri = ""; + int result = -100; + int errorType = -1; + std::vector fileList; +}; + +struct AsyncCopyCallbackInfo { + napi_env env = nullptr; + napi_async_work asyncWork = nullptr; + napi_ref callback[3] = { 0 }; + std::string url = ""; + std::string urlDst = ""; + std::string originDst = ""; + int result = -100; + int errorType = -1; +}; + +struct AsyncMoveCallbackInfo { + napi_env env = nullptr; + napi_async_work asyncWork = nullptr; + napi_ref callback[3] = { 0 }; + std::string url = ""; + std::string urlDst = ""; + std::string originDst = ""; + int result = -100; + int errorType = -1; +}; + +struct AsyncDeleteCallbackInfo { + napi_env env = nullptr; + napi_async_work asyncWork = nullptr; + napi_ref callback[3] = { 0 }; + std::string url = ""; + int result = -100; + int errorType = -1; +}; + +struct AsyncWriteCallbackInfo { + napi_env env = nullptr; + napi_async_work asyncWork = nullptr; + napi_ref callback[3] = { 0 }; + std::string url = ""; + std::string text = ""; + bool append = false; + int result = -100; + int errorType = -1; +}; + +struct AsyncWriteBufferCallbackInfo { + napi_env env = nullptr; + napi_async_work asyncWork = nullptr; + napi_ref callback[3] = { 0 }; + std::string url = ""; + bool append = false; + int result = -100; + int errorType = -1; + int32_t length = 0; + int32_t position = 0; + void* buf = nullptr; + napi_ref bufferAddress = nullptr; +}; + +struct AsyncReadCallbackInfo { + napi_env env = nullptr; + napi_async_work asyncWork = nullptr; + napi_ref callback[3] = { 0 }; + std::string url = ""; + int result = -100; + int errorType = -1; + std::string contents = ""; +}; + +struct AsyncReadBufferCallbackInfo { + napi_env env = nullptr; + napi_async_work asyncWork = nullptr; + napi_ref callback[3] = { 0 }; + std::string url = ""; + int length = 0; + int position = 0; + int result = -100; + int errorType = -1; + int32_t len = 0; + std::string contents = ""; +}; + +class FileNExporter final : public NExporter { +public: + inline static const std::string className_ = "File"; + static napi_value Mkdir(napi_env env, napi_callback_info info); + static napi_value Rmdir(napi_env env, napi_callback_info info); + static napi_value Get(napi_env env, napi_callback_info info); + static napi_value List(napi_env env, napi_callback_info info); + static napi_value Copy(napi_env env, napi_callback_info info); + static napi_value Move(napi_env env, napi_callback_info info); + static napi_value Delete(napi_env env, napi_callback_info info); + static napi_value Access(napi_env env, napi_callback_info info); + static napi_value WriteText(napi_env env, napi_callback_info info); + static napi_value WriteArrayBuffer(napi_env env, napi_callback_info info); + static napi_value ReadText(napi_env env, napi_callback_info info); + static napi_value ReadArrayBuffer(napi_env env, napi_callback_info info); + + bool Export() override; + + std::string GetClassName() override; + + FileNExporter(napi_env env, napi_value exports); + ~FileNExporter() override; +}; +} // namespace ModuleFile +} // namespace DistributedFS +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_file/common_func.cpp b/interfaces/kits/js/src/mod_file/common_func.cpp new file mode 100644 index 000000000..71b76d325 --- /dev/null +++ b/interfaces/kits/js/src/mod_file/common_func.cpp @@ -0,0 +1,59 @@ +/* + * 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. + */ + +#include "common_func.h" + +#include "../common/napi/n_func_arg.h" + +namespace OHOS { +namespace DistributedFS { +namespace ModuleFile { +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 ModuleFile +} // namespace DistributedFS +} // namespace OHOS diff --git a/interfaces/kits/js/src/mod_file/common_func.h b/interfaces/kits/js/src/mod_file/common_func.h new file mode 100644 index 000000000..19924c507 --- /dev/null +++ b/interfaces/kits/js/src/mod_file/common_func.h @@ -0,0 +1,33 @@ +/* + * 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. + */ + +#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); +}; +} // namespace ModuleFile +} // namespace DistributedFS +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_file/module.cpp b/interfaces/kits/js/src/mod_file/module.cpp new file mode 100644 index 000000000..6defa937f --- /dev/null +++ b/interfaces/kits/js/src/mod_file/module.cpp @@ -0,0 +1,46 @@ +/* + * 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. + */ + +#include +#include + +#include "../common/log.h" +#include "class_file/file_n_exporter.h" + +using namespace std; + +namespace OHOS { +namespace DistributedFS { +namespace ModuleFile { +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(file, Export) +} // namespace ModuleFile +} // namespace DistributedFS +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fileio/class_constants/constants.cpp b/interfaces/kits/js/src/mod_fileio/class_constants/constants.cpp new file mode 100644 index 000000000..0cde079cf --- /dev/null +++ b/interfaces/kits/js/src/mod_fileio/class_constants/constants.cpp @@ -0,0 +1,189 @@ +/* + * 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. + */ + +#include "constants.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include "securec.h" + +#include "../../common/log.h" +#include "../../common/napi/n_class.h" +#include "../../common/napi/n_func_arg.h" +#include "../../common/uni_error.h" + +namespace OHOS { +namespace DistributedFS { +namespace ModuleFileIO { +using namespace std; + +napi_value Constants::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; + } + return funcArg.GetThisVar(); +} + +bool Constants::Export() +{ + // access + napi_value F_OK_ = nullptr; + napi_create_int32(exports_.env_, F_OK, &F_OK_); // 0 F_OK + napi_value R_OK_ = nullptr; + napi_create_int32(exports_.env_, R_OK, &R_OK_); // 4 R_OK + napi_value W_OK_ = nullptr; + napi_create_int32(exports_.env_, W_OK, &W_OK_); // 2 W_OK + napi_value X_OK_ = nullptr; + napi_create_int32(exports_.env_, X_OK, &X_OK_); // 1 X_OK + // open + napi_value O_RDONLY_ = nullptr; + napi_create_int32(exports_.env_, O_RDONLY, &O_RDONLY_); // 0 O_RDONLY + napi_value O_WRONLY_ = nullptr; + napi_create_int32(exports_.env_, O_WRONLY, &O_WRONLY_); // 1 O_WRONLY + napi_value O_RDWR_ = nullptr; + napi_create_int32(exports_.env_, O_RDWR, &O_RDWR_); // 2 O_RDWR + napi_value O_CREAT_ = nullptr; + napi_create_int32(exports_.env_, O_CREAT, &O_CREAT_); // 0o100 O_CREAT + napi_value O_EXCL_ = nullptr; + napi_create_int32(exports_.env_, O_EXCL, &O_EXCL_); // 0o200 O_EXCL + napi_value O_TRUNC_ = nullptr; + napi_create_int32(exports_.env_, O_TRUNC, &O_TRUNC_); // 0o1000 O_TRUNC + napi_value O_APPEND_ = nullptr; + napi_create_int32(exports_.env_, O_APPEND, &O_APPEND_); // 0o2000 O_APPEND + napi_value O_NONBLOCK_ = nullptr; + napi_create_int32(exports_.env_, O_NONBLOCK, &O_NONBLOCK_); // 0o4000 O_NONBLOCK + napi_value O_DIRECTORY_ = nullptr; + napi_create_int32(exports_.env_, O_DIRECTORY, &O_DIRECTORY_); // 0o200000 O_DIRECTORY + napi_value O_NOFOLLOW_ = nullptr; + napi_create_int32(exports_.env_, O_NOFOLLOW, &O_NOFOLLOW_); // 0o400000 O_NOFOLLOW + napi_value O_SYNC_ = nullptr; + napi_create_int32(exports_.env_, O_SYNC, &O_SYNC_); // 0o4010000 O_SYNC + + // stat + napi_value S_IFMT_ = nullptr; + napi_create_int32(exports_.env_, S_IFMT, &S_IFMT_); // 0o170000 S_IFMT + napi_value S_IFSOCK_ = nullptr; + napi_create_int32(exports_.env_, S_IFSOCK, &S_IFSOCK_); // 0o140000 S_IFSOCK + napi_value S_IFLNK_ = nullptr; + napi_create_int32(exports_.env_, S_IFLNK, &S_IFLNK_); // 0o120000 S_IFLNK + napi_value S_IFREG_ = nullptr; + napi_create_int32(exports_.env_, S_IFREG, &S_IFREG_); // 0o100000 S_IFREG + napi_value S_IFBLK_ = nullptr; + napi_create_int32(exports_.env_, S_IFBLK, &S_IFBLK_); // 0o060000 S_IFBLK + napi_value S_IFDIR_ = nullptr; + napi_create_int32(exports_.env_, S_IFDIR, &S_IFDIR_); // 0o040000 S_IFDIR + napi_value S_IFCHR_ = nullptr; + napi_create_int32(exports_.env_, S_IFCHR, &S_IFCHR_); // 0o020000 S_IFCHR + napi_value S_IFIFO_ = nullptr; + napi_create_int32(exports_.env_, S_IFIFO, &S_IFIFO_); // 0o010000 S_IFIFO + napi_value S_IRWXU_ = nullptr; + napi_create_int32(exports_.env_, S_IRWXU, &S_IRWXU_); // 0o0700 S_IRWXU + napi_value S_IRUSR_ = nullptr; + napi_create_int32(exports_.env_, S_IRUSR, &S_IRUSR_); // 0o0400 S_IRUSR + napi_value S_IWUSR_ = nullptr; + napi_create_int32(exports_.env_, S_IWUSR, &S_IWUSR_); // 0o0200 S_IWUSR + napi_value S_IXUSR_ = nullptr; + napi_create_int32(exports_.env_, S_IXUSR, &S_IXUSR_); // 0o0100 S_IXUSR + napi_value S_IRWXG_ = nullptr; + napi_create_int32(exports_.env_, S_IRWXG, &S_IRWXG_); // 0o0070 S_IRWXG + napi_value S_IRGRP_ = nullptr; + napi_create_int32(exports_.env_, S_IRGRP, &S_IRGRP_); // 0o0040 S_IRGRP + napi_value S_IWGRP_ = nullptr; + napi_create_int32(exports_.env_, S_IWGRP, &S_IWGRP_); // 0o0020 S_IWGRP + napi_value S_IXGRP_ = nullptr; + napi_create_int32(exports_.env_, S_IXGRP, &S_IXGRP_); // 0o0010 S_IXGRP + napi_value S_IRWXO_ = nullptr; + napi_create_int32(exports_.env_, S_IRWXO, &S_IRWXO_); // 0o0007 S_IRWXO + napi_value S_IROTH_ = nullptr; + napi_create_int32(exports_.env_, S_IROTH, &S_IROTH_); // 0o0004 S_IROTH + napi_value S_IWOTH_ = nullptr; + napi_create_int32(exports_.env_, S_IWOTH, &S_IWOTH_); // 0o0002 S_IWOTH + napi_value S_IXOTH_ = nullptr; + napi_create_int32(exports_.env_, S_IXOTH, &S_IXOTH_); // 0o0001 S_IXOTH + + vector props = { + NVal::DeclareNapiStaticProperty("F_OK", F_OK_), + NVal::DeclareNapiStaticProperty("R_OK", R_OK_), + NVal::DeclareNapiStaticProperty("W_OK", W_OK_), + NVal::DeclareNapiStaticProperty("X_OK", X_OK_), + NVal::DeclareNapiStaticProperty("O_RDONLY", O_RDONLY_), + NVal::DeclareNapiStaticProperty("O_WRONLY", O_WRONLY_), + NVal::DeclareNapiStaticProperty("O_RDWR", O_RDWR_), + NVal::DeclareNapiStaticProperty("O_CREAT", O_CREAT_), + NVal::DeclareNapiStaticProperty("O_EXCL", O_EXCL_), + NVal::DeclareNapiStaticProperty("O_TRUNC", O_TRUNC_), + NVal::DeclareNapiStaticProperty("O_APPEND", O_APPEND_), + NVal::DeclareNapiStaticProperty("O_NONBLOCK", O_NONBLOCK_), + NVal::DeclareNapiStaticProperty("O_DIRECTORY", O_DIRECTORY_), + NVal::DeclareNapiStaticProperty("O_NOFOLLOW", O_NOFOLLOW_), + NVal::DeclareNapiStaticProperty("O_SYNC", O_SYNC_), + NVal::DeclareNapiStaticProperty("S_IFMT", S_IFMT_), + NVal::DeclareNapiStaticProperty("S_IFSOCK", S_IFSOCK_), + NVal::DeclareNapiStaticProperty("S_IFLNK", S_IFLNK_), + NVal::DeclareNapiStaticProperty("S_IFREG", S_IFREG_), + NVal::DeclareNapiStaticProperty("S_IFBLK", S_IFBLK_), + NVal::DeclareNapiStaticProperty("S_IFDIR", S_IFDIR_), + NVal::DeclareNapiStaticProperty("S_IFCHR", S_IFCHR_), + NVal::DeclareNapiStaticProperty("S_IFIFO", S_IFIFO_), + NVal::DeclareNapiStaticProperty("S_IRWXU", S_IRWXU_), + NVal::DeclareNapiStaticProperty("S_IRUSR", S_IRUSR_), + NVal::DeclareNapiStaticProperty("S_IWUSR", S_IWUSR_), + NVal::DeclareNapiStaticProperty("S_IXUSR", S_IXUSR_), + NVal::DeclareNapiStaticProperty("S_IRWXG", S_IRWXG_), + NVal::DeclareNapiStaticProperty("S_IRGRP", S_IRGRP_), + NVal::DeclareNapiStaticProperty("S_IWGRP", S_IWGRP_), + NVal::DeclareNapiStaticProperty("S_IXGRP", S_IXGRP_), + NVal::DeclareNapiStaticProperty("S_IRWXO", S_IRWXO_), + NVal::DeclareNapiStaticProperty("S_IROTH", S_IROTH_), + NVal::DeclareNapiStaticProperty("S_IWOTH", S_IWOTH_), + NVal::DeclareNapiStaticProperty("S_IXOTH", S_IXOTH_), + }; + + string className = GetClassName(); + bool succ = false; + napi_value classValue = nullptr; + tie(succ, classValue) = NClass::DefineClass(exports_.env_, className, Constants::Constructor, std::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 Constants::GetClassName() +{ + return Constants::className_; +} + +Constants::Constants(napi_env env, napi_value exports) : NExporter(env, exports) {} +Constants::~Constants() {} +} // namespace ModuleFileIO +} // namespace DistributedFS +} // namespace OHOS diff --git a/interfaces/kits/js/src/mod_fileio/class_constants/constants.h b/interfaces/kits/js/src/mod_fileio/class_constants/constants.h new file mode 100644 index 000000000..63033a7ce --- /dev/null +++ b/interfaces/kits/js/src/mod_fileio/class_constants/constants.h @@ -0,0 +1,38 @@ +/* + * 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. + */ + +#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" + +namespace OHOS { +namespace DistributedFS { +namespace ModuleFileIO { +class Constants final : public NExporter { +public: + inline static const std::string className_ = "constants"; + bool Export() override; + std::string GetClassName() override; + + static napi_value Constructor(napi_env env, napi_callback_info info); + + Constants(napi_env env, napi_value exports); + ~Constants() override; +}; +} // namespace ModuleFileIO +} // namespace DistributedFS +} // namespace OHOS +#endif \ No newline at end of file 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 new file mode 100644 index 000000000..b6b2eb78a --- /dev/null +++ b/interfaces/kits/js/src/mod_fileio/class_dir/dir_entity.h @@ -0,0 +1,32 @@ +/* + * 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. + */ + +#ifndef INTERFACES_KITS_JS_SRC_MOD_FILEIO_CLASS_DIR_DIR_ENTITY_H +#define INTERFACES_KITS_JS_SRC_MOD_FILEIO_CLASS_DIR_DIR_ENTITY_H + +#include +#include + +namespace OHOS { +namespace DistributedFS { +namespace ModuleFileIO { +struct DirEntity { + std::mutex lock_; + std::unique_ptr > dir_ = { nullptr, closedir }; +}; +} // namespace ModuleFileIO +} // namespace DistributedFS +} // namespace OHOS +#endif // INTERFACES_KITS_JS_SRC_MOD_FILEIO_CLASS_DIR_DIR_ENTITY_H \ No newline at end of file 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 new file mode 100644 index 000000000..03b048083 --- /dev/null +++ b/interfaces/kits/js/src/mod_fileio/class_dir/dir_n_exporter.cpp @@ -0,0 +1,308 @@ +/* + * 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. + */ + +#include "dir_n_exporter.h" +#include +#include +#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" +#include "../../common/napi/n_func_arg.h" +#include "../class_dirent/dirent_entity.h" +#include "../class_dirent/dirent_n_exporter.h" +#include "../common_func.h" + +namespace OHOS { +namespace DistributedFS { +namespace ModuleFileIO { +using namespace std; + +static DirEntity *GetDirEntity(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 dirEntity = NClass::GetEntityOf(env, funcArg.GetThisVar()); + if (!dirEntity) { + UniError(EIO).ThrowErr(env, "Cannot get entity of Dir"); + return nullptr; + } + return dirEntity; +} + +napi_value DirNExporter::CloseSync(napi_env env, napi_callback_info info) +{ + DirEntity *dirEntity = GetDirEntity(env, info); + if (!dirEntity || !dirEntity->dir_) { + UniError(EBADF).ThrowErr(env, "Dir has been closed yet"); + return nullptr; + } + + dirEntity->dir_.reset(); + return nullptr; +} + +napi_value DirNExporter::Close(napi_env env, napi_callback_info info) +{ + NFuncArg funcArg(env, info); + if (!funcArg.InitArgs(NARG_CNT::ZERO, NARG_CNT::ONE)) { + UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); + return nullptr; + } + + auto dirEntity = NClass::GetEntityOf(env, funcArg.GetThisVar()); + 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; + } + + auto cbExec = [dirEntity](napi_env env) -> UniError { + DIR *dir = dirEntity->dir_.release(); + int ret = closedir(dir); + if (ret == -1) { + return UniError(errno); + } else { + return UniError(ERRNO_NOERR); + } + }; + 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()); + 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_; + } +} + +struct DirReadArgs { + NRef thisptrRef_; + struct dirent dirRes = { + .d_ino = 0, + .d_off = 0, + .d_reclen = 0, + .d_type = 0, + .d_name = { '\0' }, + }; + explicit DirReadArgs(NVal obj) : thisptrRef_(obj) {} +}; + +static NVal DoReadCompile(napi_env env, UniError err, shared_ptr arg) +{ + if (err) { + return { env, err.GetNapiErr(env) }; + } else { + napi_value objDirent = NClass::InstantiateClass(env, DirentNExporter::className_, {}); + if (!objDirent) { + return { env, UniError(EINVAL).GetNapiErr(env) }; + } + auto direntEntity = NClass::GetEntityOf(env, objDirent); + if (!direntEntity) { + return { env, UniError(EINVAL).GetNapiErr(env) }; + } + + if (strlen(arg->dirRes.d_name) == 0) { + return { env, nullptr }; + } else { + direntEntity->dirent_ = arg->dirRes; + return { env, objDirent }; + } + } +} + +napi_value DirNExporter::Read(napi_env env, napi_callback_info info) +{ + NFuncArg funcArg(env, info); + if (!funcArg.InitArgs(NARG_CNT::ZERO, NARG_CNT::ONE)) { + UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); + return nullptr; + } + + auto dirEntity = NClass::GetEntityOf(env, funcArg.GetThisVar()); + 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; + } + + DIR *dir = dirEntity->dir_.get(); + auto arg = make_shared(NVal(env, funcArg.GetThisVar())); + auto cbExec = [arg, dir, dirEntity](napi_env env) -> UniError { + struct dirent tmpDirent; + lock_guard(dirEntity->lock_); + errno = 0; + dirent *res = nullptr; + 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 { + tmpDirent = *res; + break; + } + } while (true); + + arg->dirRes = tmpDirent; + return UniError(ERRNO_NOERR); + }; + auto cbCompl = [arg](napi_env env, UniError err) -> NVal { + return DoReadCompile(env, err, arg); + }; + NVal thisVar(env, funcArg.GetThisVar()); + + if (funcArg.GetArgc() == NARG_CNT::ZERO) { + return NAsyncWorkPromise(env, thisVar).Schedule("fileioDirRead", cbExec, cbCompl).val_; + } else { + NVal cb(env, funcArg[NARG_POS::FIRST]); + return NAsyncWorkCallback(env, thisVar, cb).Schedule("fileioDirRead", cbExec, cbCompl).val_; + } +} + +napi_value DirNExporter::ReadSync(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; + } + + DirEntity *dirEntity = GetDirEntity(env, info); + if (!dirEntity || !dirEntity->dir_) { + UniError(EBADF).ThrowErr(env, "Dir has been closed yet"); + return nullptr; + } + + struct dirent tmpDirent; + { + lock_guard(dirEntity->lock_); + errno = 0; + dirent *res = nullptr; + do { + res = readdir(dirEntity->dir_.get()); + if (res == nullptr && errno) { + UniError(errno).ThrowErr(env); + return nullptr; + } else if (res == nullptr) { + return NVal::CreateUndefined(env).val_; + } else if (string(res->d_name) == "." || string(res->d_name) == "..") { + continue; + } else { + tmpDirent = *res; + break; + } + } while (true); + } + + napi_value objDirent = NClass::InstantiateClass(env, DirentNExporter::className_, {}); + if (!objDirent) { + return nullptr; + } + + auto direntEntity = NClass::GetEntityOf(env, objDirent); + if (!direntEntity) { + return nullptr; + } + direntEntity->dirent_ = tmpDirent; + + return objDirent; +} + +napi_value DirNExporter::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 dirEntity = make_unique(); + if (!NClass::SetEntityFor(env, funcArg.GetThisVar(), move(dirEntity))) { + stringstream ss; + ss << "INNER BUG. Failed to wrap entity for obj dir"; + UniError(EIO).ThrowErr(env, ss.str()); + return nullptr; + } + return funcArg.GetThisVar(); +} + +bool DirNExporter::Export() +{ + vector props = { + NVal::DeclareNapiFunction("readSync", ReadSync), + NVal::DeclareNapiFunction("closeSync", CloseSync), + NVal::DeclareNapiFunction("read", Read), + NVal::DeclareNapiFunction("close", Close), + }; + + string className = GetClassName(); + + bool succ = false; + napi_value classValue = nullptr; + tie(succ, classValue) = NClass::DefineClass(exports_.env_, className, DirNExporter::Constructor, std::move(props)); + if (!succ) { + UniError(EIO).ThrowErr(exports_.env_, "INNER BUG. Failed to define class Dirent"); + return false; + } + + succ = NClass::SaveClass(exports_.env_, className, classValue); + if (!succ) { + UniError(EIO).ThrowErr(exports_.env_, "INNER BUG. Failed to save class Dirent"); + return false; + } + + return exports_.AddProp(className, classValue); +} + +string DirNExporter::GetClassName() +{ + return DirNExporter::className_; +} + +DirNExporter::DirNExporter(napi_env env, napi_value exports) : NExporter(env, exports) {} + +DirNExporter::~DirNExporter() {} +} // namespace ModuleFileIO +} // namespace DistributedFS +} // namespace OHOS \ No newline at end of file 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 new file mode 100644 index 000000000..bd69604b5 --- /dev/null +++ b/interfaces/kits/js/src/mod_fileio/class_dir/dir_n_exporter.h @@ -0,0 +1,45 @@ +/* + * 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. + */ + +#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 + +#include "../../common/napi/n_exporter.h" + +namespace OHOS { +namespace DistributedFS { +namespace ModuleFileIO { +class DirNExporter final : public NExporter { +public: + inline static const std::string className_ = "Dir"; + + bool Export() override; + std::string GetClassName() override; + + static napi_value Constructor(napi_env env, napi_callback_info info); + + 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 Read(napi_env env, napi_callback_info info); + static napi_value Close(napi_env env, napi_callback_info info); + DirNExporter(napi_env env, napi_value exports); + ~DirNExporter() override; +}; +} // namespace ModuleFileIO +} // namespace DistributedFS +} // namespace OHOS +#endif \ No newline at end of file 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 new file mode 100644 index 000000000..d92fa69a2 --- /dev/null +++ b/interfaces/kits/js/src/mod_fileio/class_dirent/dirent_entity.h @@ -0,0 +1,30 @@ +/* + * 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. + */ + +#ifndef INTERFACES_KITS_JS_SRC_MOD_FILEIO_CLASS_DIRENT_DIRENT_ENTITY_H +#define INTERFACES_KITS_JS_SRC_MOD_FILEIO_CLASS_DIRENT_DIRENT_ENTITY_H + +#include + +namespace OHOS { +namespace DistributedFS { +namespace ModuleFileIO { +struct DirentEntity { + struct dirent dirent_; +}; +} // namespace ModuleFileIO +} // namespace DistributedFS +} // namespace OHOS +#endif // INTERFACES_KITS_JS_SRC_MOD_FILEIO_CLASS_DIRENT_DIRENT_ENTITY_H \ No newline at end of file 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 new file mode 100644 index 000000000..2bed85369 --- /dev/null +++ b/interfaces/kits/js/src/mod_fileio/class_dirent/dirent_n_exporter.cpp @@ -0,0 +1,172 @@ +/* + * 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. + */ + +#include "dirent_n_exporter.h" + +#include +#include +#include +#include +#include + +#include "securec.h" + +#include "../../common/log.h" +#include "../../common/napi/n_class.h" +#include "../../common/napi/n_func_arg.h" +#include "../../common/uni_error.h" +#include "../common_func.h" +#include "dirent_entity.h" + +namespace OHOS { +namespace DistributedFS { +namespace ModuleFileIO { +using namespace std; + +static DirentEntity *GetDirentEntity(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 direntEntity = NClass::GetEntityOf(env, funcArg.GetThisVar()); + if (!direntEntity) { + UniError(EIO).ThrowErr(env, "Cannot get entity of Dirent"); + return nullptr; + } + return direntEntity; +} + +static napi_value CheckDirentDType(napi_env env, napi_callback_info info, unsigned char dType) +{ + DirentEntity *direntEntity = GetDirentEntity(env, info); + if (!direntEntity) { + return nullptr; + } + + return NVal::CreateBool(env, direntEntity->dirent_.d_type == dType).val_; +} + +napi_value DirentNExporter::isBlockDevice(napi_env env, napi_callback_info info) +{ + return CheckDirentDType(env, info, DT_BLK); +} + +napi_value DirentNExporter::isCharacterDevice(napi_env env, napi_callback_info info) +{ + return CheckDirentDType(env, info, DT_CHR); +} + +napi_value DirentNExporter::isDirectory(napi_env env, napi_callback_info info) +{ + return CheckDirentDType(env, info, DT_DIR); +} + +napi_value DirentNExporter::isFIFO(napi_env env, napi_callback_info info) +{ + return CheckDirentDType(env, info, DT_FIFO); +} + +napi_value DirentNExporter::isFile(napi_env env, napi_callback_info info) +{ + return CheckDirentDType(env, info, DT_REG); +} + +napi_value DirentNExporter::isSocket(napi_env env, napi_callback_info info) +{ + return CheckDirentDType(env, info, DT_SOCK); +} + +napi_value DirentNExporter::isSymbolicLink(napi_env env, napi_callback_info info) +{ + return CheckDirentDType(env, info, DT_LNK); +} + +napi_value DirentNExporter::GetName(napi_env env, napi_callback_info info) +{ + DirentEntity *direntEntity = GetDirentEntity(env, info); + if (!direntEntity) { + return nullptr; + } + return NVal::CreateUTF8String(env, direntEntity->dirent_.d_name).val_; +} + +napi_value DirentNExporter::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 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()); + return nullptr; + } + return funcArg.GetThisVar(); +} + +bool DirentNExporter::Export() +{ + vector props = { + NVal::DeclareNapiFunction("isBlockDevice", isBlockDevice), + NVal::DeclareNapiFunction("isCharacterDevice", isCharacterDevice), + NVal::DeclareNapiFunction("isDirectory", isDirectory), + NVal::DeclareNapiFunction("isFIFO", isFIFO), + NVal::DeclareNapiFunction("isFile", isFile), + NVal::DeclareNapiFunction("isSocket", isSocket), + NVal::DeclareNapiFunction("isSymbolicLink", isSymbolicLink), + + NVal::DeclareNapiGetter("name", GetName), + }; + + string className = GetClassName(); + + bool succ = false; + napi_value classValue = nullptr; + tie(succ, classValue) = NClass::DefineClass(exports_.env_, + className, + DirentNExporter::Constructor, + std::move(props)); + if (!succ) { + UniError(EIO).ThrowErr(exports_.env_, "INNER BUG. Failed to define class Dirent"); + return false; + } + + succ = NClass::SaveClass(exports_.env_, className, classValue); + if (!succ) { + UniError(EIO).ThrowErr(exports_.env_, "INNER BUG. Failed to save class Dirent"); + return false; + } + + return exports_.AddProp(className, classValue); +} + +string DirentNExporter::GetClassName() +{ + return DirentNExporter::className_; +} + +DirentNExporter::DirentNExporter(napi_env env, napi_value exports) : NExporter(env, exports) {} + +DirentNExporter::~DirentNExporter() {} +} // namespace ModuleFileIO +} // namespace DistributedFS +} // namespace OHOS \ No newline at end of file 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 new file mode 100644 index 000000000..0f60629e0 --- /dev/null +++ b/interfaces/kits/js/src/mod_fileio/class_dirent/dirent_n_exporter.h @@ -0,0 +1,49 @@ +/* + * 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. + */ + +#ifndef INTERFACES_KITS_JS_SRC_MOD_FILEIO_CLASS_DIRENT_DIRENT_N_EXPORTER_H +#define INTERFACES_KITS_JS_SRC_MOD_FILEIO_CLASS_DIRENT_DIRENT_N_EXPORTER_H + +#include "../../common/napi/n_exporter.h" + +namespace OHOS { +namespace DistributedFS { +namespace ModuleFileIO { +class DirentNExporter final : public NExporter { +public: + inline static const std::string className_ = "Dirent"; + + bool Export() override; + std::string GetClassName() override; + + static napi_value Constructor(napi_env env, napi_callback_info cbinfo); + + static napi_value isBlockDevice(napi_env env, napi_callback_info cbinfo); + static napi_value isCharacterDevice(napi_env env, napi_callback_info cbinfo); + static napi_value isDirectory(napi_env env, napi_callback_info cbinfo); + static napi_value isFIFO(napi_env env, napi_callback_info cbinfo); + static napi_value isFile(napi_env env, napi_callback_info cbinfo); + static napi_value isSocket(napi_env env, napi_callback_info cbinfo); + static napi_value isSymbolicLink(napi_env env, napi_callback_info cbinfo); + + static napi_value GetName(napi_env env, napi_callback_info cbinfo); + + DirentNExporter(napi_env env, napi_value exports); + ~DirentNExporter() override; +}; +} // namespace ModuleFileIO +} // namespace DistributedFS +} // namespace OHOS +#endif // INTERFACES_KITS_JS_SRC_MOD_FILEIO_CLASS_DIRENT_DIRENT_N_EXPORTER_H \ 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 new file mode 100644 index 000000000..a82c30f75 --- /dev/null +++ b/interfaces/kits/js/src/mod_fileio/class_stat/stat_entity.h @@ -0,0 +1,30 @@ +/* + * 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. + */ + +#ifndef INTERFACES_KITS_JS_SRC_MOD_FILEIO_CLASS_STAT_STAT_ENTITY_H +#define INTERFACES_KITS_JS_SRC_MOD_FILEIO_CLASS_STAT_STAT_ENTITY_H + +#include + +namespace OHOS { +namespace DistributedFS { +namespace ModuleFileIO { +struct StatEntity { + struct stat stat_; +}; +} // 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_n_exporter.cpp b/interfaces/kits/js/src/mod_fileio/class_stat/stat_n_exporter.cpp new file mode 100644 index 000000000..57c33c6bc --- /dev/null +++ b/interfaces/kits/js/src/mod_fileio/class_stat/stat_n_exporter.cpp @@ -0,0 +1,370 @@ +/* + * 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. + */ + +#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 +#include +#include +#include + +#include "securec.h" + +#include "../../common/log.h" +#include "../../common/napi/n_class.h" +#include "../../common/napi/n_func_arg.h" +#include "../../common/uni_error.h" +#include "stat_entity.h" + +namespace OHOS { +namespace DistributedFS { +namespace ModuleFileIO { +using namespace std; + +static napi_value CheckStatMode(napi_env env, napi_callback_info info, mode_t mode) +{ + NFuncArg funcArg(env, info); + if (!funcArg.InitArgs(NARG_CNT::ZERO)) { + UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); + return nullptr; + } + + auto statEntity = NClass::GetEntityOf(env, funcArg.GetThisVar()); + if (!statEntity) { + return nullptr; + } + + bool check = (statEntity->stat_.st_mode & S_IFMT) == mode; + return NVal::CreateBool(env, check).val_; +} + +napi_value StatNExporter::IsBlockDevice(napi_env env, napi_callback_info info) +{ + return CheckStatMode(env, info, S_IFBLK); +} + +napi_value StatNExporter::IsCharacterDevice(napi_env env, napi_callback_info info) +{ + return CheckStatMode(env, info, S_IFCHR); +} + +napi_value StatNExporter::IsDirectory(napi_env env, napi_callback_info info) +{ + return CheckStatMode(env, info, S_IFDIR); +} + +napi_value StatNExporter::IsFIFO(napi_env env, napi_callback_info info) +{ + return CheckStatMode(env, info, S_IFIFO); +} + +napi_value StatNExporter::IsFile(napi_env env, napi_callback_info info) +{ + return CheckStatMode(env, info, S_IFREG); +} + +napi_value StatNExporter::IsSocket(napi_env env, napi_callback_info info) +{ + return CheckStatMode(env, info, S_IFSOCK); +} + +napi_value StatNExporter::IsSymbolicLink(napi_env env, napi_callback_info info) +{ + return CheckStatMode(env, info, S_IFLNK); +} + +napi_value StatNExporter::GetDev(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 statEntity = NClass::GetEntityOf(env, funcArg.GetThisVar()); + if (!statEntity) { + return nullptr; + } + + return NVal::CreateInt64(env, statEntity->stat_.st_dev).val_; +} + +napi_value StatNExporter::GetIno(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 statEntity = NClass::GetEntityOf(env, funcArg.GetThisVar()); + if (!statEntity) { + return nullptr; + } + + return NVal::CreateInt64(env, statEntity->stat_.st_ino).val_; +} + +napi_value StatNExporter::GetMode(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 statEntity = NClass::GetEntityOf(env, funcArg.GetThisVar()); + if (!statEntity) { + return nullptr; + } + + return NVal::CreateInt64(env, statEntity->stat_.st_mode).val_; +} + +napi_value StatNExporter::GetNlink(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 statEntity = NClass::GetEntityOf(env, funcArg.GetThisVar()); + if (!statEntity) { + return nullptr; + } + + return NVal::CreateInt64(env, statEntity->stat_.st_nlink).val_; +} + +napi_value StatNExporter::GetUid(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 statEntity = NClass::GetEntityOf(env, funcArg.GetThisVar()); + if (!statEntity) { + return nullptr; + } + + return NVal::CreateInt64(env, statEntity->stat_.st_uid).val_; +} + +napi_value StatNExporter::GetGid(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 statEntity = NClass::GetEntityOf(env, funcArg.GetThisVar()); + if (!statEntity) { + return nullptr; + } + + return NVal::CreateInt64(env, statEntity->stat_.st_gid).val_; +} + +napi_value StatNExporter::GetRdev(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 statEntity = NClass::GetEntityOf(env, funcArg.GetThisVar()); + if (!statEntity) { + return nullptr; + } + + return NVal::CreateInt64(env, statEntity->stat_.st_rdev).val_; +} + +napi_value StatNExporter::GetSize(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 statEntity = NClass::GetEntityOf(env, funcArg.GetThisVar()); + if (!statEntity) { + return nullptr; + } + + return NVal::CreateInt64(env, statEntity->stat_.st_size).val_; +} + +napi_value StatNExporter::GetBlksize(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 statEntity = NClass::GetEntityOf(env, funcArg.GetThisVar()); + if (!statEntity) { + return nullptr; + } + + return NVal::CreateInt64(env, statEntity->stat_.st_blksize).val_; +} + +napi_value StatNExporter::GetBlocks(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 statEntity = NClass::GetEntityOf(env, funcArg.GetThisVar()); + if (!statEntity) { + return nullptr; + } + + return NVal::CreateInt64(env, statEntity->stat_.st_blocks).val_; +} + +napi_value StatNExporter::GetAtime(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 statEntity = NClass::GetEntityOf(env, funcArg.GetThisVar()); + if (!statEntity) { + return nullptr; + } + + return NVal::CreateInt64(env, statEntity->stat_.st_atim.tv_sec).val_; +} + +napi_value StatNExporter::GetMtime(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 statEntity = NClass::GetEntityOf(env, funcArg.GetThisVar()); + if (!statEntity) { + return nullptr; + } + + return NVal::CreateInt64(env, statEntity->stat_.st_mtim.tv_sec).val_; +} + +napi_value StatNExporter::GetCtime(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 statEntity = NClass::GetEntityOf(env, funcArg.GetThisVar()); + if (!statEntity) { + return nullptr; + } + + return NVal::CreateInt64(env, statEntity->stat_.st_ctim.tv_sec).val_; +} + +napi_value StatNExporter::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; + } + + 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()); + return nullptr; + } + return funcArg.GetThisVar(); +} + +bool StatNExporter::Export() +{ + vector props = { + NVal::DeclareNapiFunction("isBlockDevice", IsBlockDevice), + NVal::DeclareNapiFunction("isCharacterDevice", IsCharacterDevice), + NVal::DeclareNapiFunction("isDirectory", IsDirectory), + NVal::DeclareNapiFunction("isFIFO", IsFIFO), + NVal::DeclareNapiFunction("isFile", IsFile), + NVal::DeclareNapiFunction("isSocket", IsSocket), + NVal::DeclareNapiFunction("isSymbolicLink", IsSymbolicLink), + + NVal::DeclareNapiGetter("dev", GetDev), + NVal::DeclareNapiGetter("ino", GetIno), + NVal::DeclareNapiGetter("mode", GetMode), + NVal::DeclareNapiGetter("nlink", GetNlink), + NVal::DeclareNapiGetter("uid", GetUid), + NVal::DeclareNapiGetter("gid", GetGid), + NVal::DeclareNapiGetter("rdev", GetRdev), + NVal::DeclareNapiGetter("size", GetSize), + NVal::DeclareNapiGetter("blksize", GetBlksize), + NVal::DeclareNapiGetter("blocks", GetBlocks), + NVal::DeclareNapiGetter("atime", GetAtime), + NVal::DeclareNapiGetter("mtime", GetMtime), + NVal::DeclareNapiGetter("ctime", GetCtime), + }; + + string className = GetClassName(); + bool succ = false; + napi_value classValue = nullptr; + tie(succ, classValue) = NClass::DefineClass(exports_.env_, className, StatNExporter::Constructor, std::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 StatNExporter::GetClassName() +{ + return StatNExporter::className_; +} + +StatNExporter::StatNExporter(napi_env env, napi_value exports) : NExporter(env, exports) {} + +StatNExporter::~StatNExporter() {} +} // namespace ModuleFileIO +} // namespace DistributedFS +} // namespace OHOS \ No newline at end of file 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 new file mode 100644 index 000000000..430485664 --- /dev/null +++ b/interfaces/kits/js/src/mod_fileio/class_stat/stat_n_exporter.h @@ -0,0 +1,61 @@ +/* + * 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. + */ + +#ifndef INTERFACES_KITS_JS_SRC_MOD_FILEIO_CLASS_STAT_N_EXPORTER_H +#define INTERFACES_KITS_JS_SRC_MOD_FILEIO_CLASS_STAT_N_EXPORTER_H + +#include "../../common/napi/n_exporter.h" + +namespace OHOS { +namespace DistributedFS { +namespace ModuleFileIO { +class StatNExporter final : public NExporter { +public: + inline static const std::string className_ = "Stat"; + + bool Export() override; + std::string GetClassName() override; + + static napi_value Constructor(napi_env env, napi_callback_info cbinfo); + + static napi_value IsBlockDevice(napi_env env, napi_callback_info cbinfo); + static napi_value IsCharacterDevice(napi_env env, napi_callback_info cbinfo); + static napi_value IsDirectory(napi_env env, napi_callback_info cbinfo); + static napi_value IsFIFO(napi_env env, napi_callback_info cbinfo); + static napi_value IsFile(napi_env env, napi_callback_info cbinfo); + static napi_value IsSocket(napi_env env, napi_callback_info cbinfo); + static napi_value IsSymbolicLink(napi_env env, napi_callback_info cbinfo); + + static napi_value GetDev(napi_env env, napi_callback_info cbinfo); + static napi_value GetIno(napi_env env, napi_callback_info cbinfo); + static napi_value GetMode(napi_env env, napi_callback_info cbinfo); + static napi_value GetNlink(napi_env env, napi_callback_info cbinfo); + static napi_value GetUid(napi_env env, napi_callback_info cbinfo); + static napi_value GetGid(napi_env env, napi_callback_info cbinfo); + static napi_value GetRdev(napi_env env, napi_callback_info cbinfo); + static napi_value GetSize(napi_env env, napi_callback_info cbinfo); + static napi_value GetBlksize(napi_env env, napi_callback_info cbinfo); + static napi_value GetBlocks(napi_env env, napi_callback_info cbinfo); + static napi_value GetAtime(napi_env env, napi_callback_info cbinfo); + static napi_value GetMtime(napi_env env, napi_callback_info cbinfo); + static napi_value GetCtime(napi_env env, napi_callback_info cbinfo); + + StatNExporter(napi_env env, napi_value exports); + ~StatNExporter() override; +}; +} // namespace ModuleFileIO +} // namespace DistributedFS +} // namespace OHOS +#endif // INTERFACES_KITS_JS_SRC_MOD_FILEIO_CLASS_STAT_N_EXPORTER_H \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fileio/class_stream/flush.cpp b/interfaces/kits/js/src/mod_fileio/class_stream/flush.cpp new file mode 100644 index 000000000..590b47e95 --- /dev/null +++ b/interfaces/kits/js/src/mod_fileio/class_stream/flush.cpp @@ -0,0 +1,101 @@ +/* + * 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. + */ +#include "flush.h" + +#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 "../class_stat/stat_entity.h" +#include "../class_stat/stat_n_exporter.h" + +namespace OHOS { +namespace DistributedFS { +namespace ModuleFileIO { +using namespace std; + +struct StreamEntity { + std::unique_ptr fp = { nullptr, fclose }; +}; + +napi_value Flush::Sync(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 streamEntity = NClass::GetEntityOf(env, funcArg.GetThisVar()); + if (!streamEntity || !streamEntity->fp) { + UniError(EBADF).ThrowErr(env, "Stream may has been closed"); + return nullptr; + } + + int ret = fflush(streamEntity->fp.get()); + if (ret == -1) { + UniError(errno).ThrowErr(env); + return nullptr; + } + return NVal::CreateUndefined(env).val_; +} + +napi_value Flush::Async(napi_env env, napi_callback_info info) +{ + NFuncArg funcArg(env, info); + if (!funcArg.InitArgs(NARG_CNT::ZERO, NARG_CNT::ONE)) { + UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); + return nullptr; + } + + auto streamEntity = NClass::GetEntityOf(env, funcArg.GetThisVar()); + if (!streamEntity || !streamEntity->fp) { + UniError(EBADF).ThrowErr(env, "Stream may has been closed"); + return nullptr; + } + + auto cbExec = [streamEntity](napi_env env) -> UniError { + int ret = fflush(streamEntity->fp.get()); + if (ret == -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()); + string procedureName = "fileIOFlush"; + 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_; + } +} +} // namespace ModuleFileIO +} // namespace DistributedFS +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fileio/class_stream/flush.h b/interfaces/kits/js/src/mod_fileio/class_stream/flush.h new file mode 100644 index 000000000..c616571b3 --- /dev/null +++ b/interfaces/kits/js/src/mod_fileio/class_stream/flush.h @@ -0,0 +1,32 @@ +/* + * 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. + */ + +#ifndef INTERFACES_KITS_JS_SRC_MOD_FILEIO_CLASS_STREAM_FLUSH_H +#define INTERFACES_KITS_JS_SRC_MOD_FILEIO_CLASS_STREAM_FLUSH_H + +#include "../../common/napi/uni_header.h" + +namespace OHOS { +namespace DistributedFS { +namespace ModuleFileIO { +class Flush final { +public: + static napi_value Async(napi_env env, napi_callback_info info); + static napi_value Sync(napi_env env, napi_callback_info info); +}; +} // namespace ModuleFileIO +} // namespace DistributedFS +} // namespace OHOS +#endif \ No newline at end of file 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 new file mode 100644 index 000000000..1c010e015 --- /dev/null +++ b/interfaces/kits/js/src/mod_fileio/class_stream/stream_entity.h @@ -0,0 +1,28 @@ +/* + * 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. + */ + +#ifndef INTERFACES_KITS_JS_SRC_MOD_FILEIO_CLASS_STREAM_STREAM_ENTITY_H +#define INTERFACES_KITS_JS_SRC_MOD_FILEIO_CLASS_STREAM_STREAM_ENTITY_H + +namespace OHOS { +namespace DistributedFS { +namespace ModuleFileIO { +struct StreamEntity { + std::unique_ptr fp = { nullptr, fclose }; +}; +} // namespace ModuleFileIO +} // namespace DistributedFS +} // namespace OHOS +#endif // INTERFACES_KITS_JS_SRC_MOD_FILEIO_CLASS_STREAM_STREAM_ENTITY_H \ No newline at end of file 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 new file mode 100644 index 000000000..947b858d5 --- /dev/null +++ b/interfaces/kits/js/src/mod_fileio/class_stream/stream_n_exporter.cpp @@ -0,0 +1,401 @@ +/* + * 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. + */ + +#include "stream_n_exporter.h" + +#include +#include +#include +#include +#include +#include +#include "flush.h" +#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" +#include "../common_func.h" +#include "stream_entity.h" + +namespace OHOS { +namespace DistributedFS { +namespace ModuleFileIO { +using namespace std; + +napi_value StreamNExporter::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; + } + + /* To get entity */ + bool succ = false; + FILE *filp = nullptr; + auto streamEntity = NClass::GetEntityOf(env, funcArg.GetThisVar()); + if (!streamEntity || !streamEntity->fp) { + UniError(EBADF).ThrowErr(env, "Stream may have been closed"); + return nullptr; + } else { + filp = streamEntity->fp.get(); + } + + 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::FIRST], funcArg[NARG_POS::SECOND]); + if (!succ) { + return nullptr; + } + + if (hasPos && (fseek(filp, pos, SEEK_SET) == -1)) { + UniError(errno).ThrowErr(env); + return nullptr; + } + + size_t actLen = fread(buf, 1, len, filp); + if (actLen != static_cast(len) && ferror(filp)) { + UniError(errno).ThrowErr(env); + } + + return NVal::CreateInt64(env, actLen).val_; +} + +napi_value StreamNExporter::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 streamEntity = NClass::GetEntityOf(env, funcArg.GetThisVar()); + if (!streamEntity || !streamEntity->fp) { + UniError(EINVAL).ThrowErr(env, "Stream may have been closed yet"); + return nullptr; + } + streamEntity->fp.reset(); + return NVal::CreateUndefined(env).val_; +} + +napi_value StreamNExporter::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; + } + + bool succ = false; + FILE *filp = nullptr; + auto streamEntity = NClass::GetEntityOf(env, funcArg.GetThisVar()); + if (!streamEntity || !streamEntity->fp) { + UniError(EBADF).ThrowErr(env, "Stream may has been closed"); + return nullptr; + } else { + filp = streamEntity->fp.get(); + } + + 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::FIRST], funcArg[NARG_POS::SECOND]); + if (!succ) { + return nullptr; + } + if (hasPos && (fseek(filp, position, SEEK_SET) == -1)) { + UniError(errno).ThrowErr(env); + return nullptr; + } + + size_t writeLen = fwrite(buf, 1, len, filp); + if (writeLen != len) { + UniError(errno).ThrowErr(env); + return nullptr; + } + + return NVal::CreateInt64(env, writeLen).val_; +} + +struct AsyncWrtieArg { + NRef refWriteArrayBuf; + unique_ptr guardWriteStr; + size_t actLen { 0 }; + + explicit AsyncWrtieArg(NVal refWriteArrayBuf) : refWriteArrayBuf(refWriteArrayBuf) {} + explicit AsyncWrtieArg(unique_ptr &&guardWriteStr) : guardWriteStr(move(guardWriteStr)) {} + ~AsyncWrtieArg() = default; +}; + +napi_value StreamNExporter::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; + } + + bool succ = false; + FILE *filp = nullptr; + bool hasPosition = false; + size_t position; + auto streamEntity = NClass::GetEntityOf(env, funcArg.GetThisVar()); + if (!streamEntity || !streamEntity->fp) { + UniError(EBADF).ThrowErr(env, "Stream may has been closed"); + return nullptr; + } + filp = streamEntity->fp.get(); + + unique_ptr bufGuard; + void *buf = nullptr; + size_t len; + tie(succ, bufGuard, buf, len, hasPosition, position) = + CommonFunc::GetWriteArg(env, funcArg[NARG_POS::FIRST], funcArg[NARG_POS::SECOND]); + if (!succ) { + return nullptr; + } + + shared_ptr arg; + if (bufGuard) { + arg = make_shared(move(bufGuard)); + } else { + arg = make_shared(NVal(env, funcArg[NARG_POS::FIRST])); + } + + auto cbExec = [arg, buf, len, filp, hasPosition, position](napi_env env) -> UniError { + if (hasPosition && (fseek(filp, position, SEEK_SET) == -1)) { + UniError(errno).ThrowErr(env); + return UniError(errno); + } + arg->actLen = fwrite(buf, 1, len, filp); + if (arg->actLen != static_cast(len) && ferror(filp)) { + return UniError(errno); + } + return UniError(ERRNO_NOERR); + }; + + auto cbCompl = [arg](napi_env env, UniError err) -> NVal { + if (err) { + return { env, err.GetNapiErr(env) }; + } + return { NVal::CreateInt64(env, arg->actLen) }; + }; + + NVal thisVar(env, funcArg.GetThisVar()); + if (funcArg.GetArgc() != NARG_CNT::THREE) { + return NAsyncWorkPromise(env, thisVar).Schedule("FileIOStreamWrite", cbExec, cbCompl).val_; + } else { + NVal cb(env, funcArg[NARG_POS::THIRD]); + return NAsyncWorkCallback(env, thisVar, cb).Schedule("FileIOStreamWrite", cbExec, cbCompl).val_; + } + + return NVal::CreateUndefined(env).val_; +} + +struct AsyncReadArg { + size_t lenRead { 0 }; + NRef refReadBuf; + int offset { 0 }; + + explicit AsyncReadArg(NVal jsReadBuf) : refReadBuf(jsReadBuf) {} + ~AsyncReadArg() = default; +}; + +napi_value StreamNExporter::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; + } + + /* To get entity */ + FILE *filp = nullptr; + auto streamEntity = NClass::GetEntityOf(env, funcArg.GetThisVar()); + if (!streamEntity || !streamEntity->fp) { + UniError(EBADF).ThrowErr(env, "Stream may have been closed"); + return nullptr; + } else { + filp = streamEntity->fp.get(); + } + + bool succ = false; + void *buf = nullptr; + int64_t len; + bool hasPosition = false; + size_t position; + int offset; + tie(succ, buf, len, hasPosition, position, offset) = + CommonFunc::GetReadArg(env, funcArg[NARG_POS::FIRST], funcArg[NARG_POS::SECOND]); + if (!succ) { + UniError(EINVAL).ThrowErr(env, "Failed GetReadArg"); + return nullptr; + } + + auto arg = make_shared(NVal(env, funcArg[NARG_POS::FIRST])); + auto cbExec = [arg, buf, position, filp, len, hasPosition, offset](napi_env env) -> UniError { + if (hasPosition && (fseek(filp, position, SEEK_SET) == -1)) { + UniError(errno).ThrowErr(env); + return UniError(errno); + } + size_t actLen = fread(buf, 1, len, filp); + if (actLen != static_cast(len) && ferror(filp)) { + return UniError(errno); + } else { + arg->lenRead = actLen; + arg->offset = offset; + 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::THREE) { + return NAsyncWorkPromise(env, thisVar).Schedule("FileIOStreamRead", cbExec, cbCompl).val_; + } else { + NVal cb(env, funcArg[NARG_POS::THIRD]); + return NAsyncWorkCallback(env, thisVar, cb).Schedule("FileIOStreamRead", cbExec, cbCompl).val_; + } + + return NVal::CreateUndefined(env).val_; +} + +napi_value StreamNExporter::Close(napi_env env, napi_callback_info info) +{ + NFuncArg funcArg(env, info); + if (!funcArg.InitArgs(NARG_CNT::ZERO, NARG_CNT::ONE)) { + UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); + return nullptr; + } + + auto streamEntity = NClass::GetEntityOf(env, funcArg.GetThisVar()); + if (!streamEntity || !streamEntity->fp) { + UniError(EBADF).ThrowErr(env, "Stream may has been closed"); + return nullptr; + } + + auto cbExec = [streamEntity](napi_env env) -> UniError { + auto filp = streamEntity->fp.release(); + if (!fclose(filp)) { + return UniError(ERRNO_NOERR); + } else { + return UniError(errno); + } + }; + + auto cbCompl = [](napi_env env, UniError err) -> NVal { + if (err) { + return { env, err.GetNapiErr(env) }; + } else { + return NVal::CreateUndefined(env); + } + }; + + string procedureName = "FileIOStreamClose"; + NVal thisVar(env, funcArg.GetThisVar()); + 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_; + } + + return NVal::CreateUndefined(env).val_; +} + +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; + } + + 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()); + return nullptr; + } + return funcArg.GetThisVar(); +} + +bool StreamNExporter::Export() +{ + vector props = { + NVal::DeclareNapiFunction("writeSync", WriteSync), + NVal::DeclareNapiFunction("flush", Flush::Async), + NVal::DeclareNapiFunction("flushSync", Flush::Sync), + NVal::DeclareNapiFunction("readSync", ReadSync), + NVal::DeclareNapiFunction("closeSync", CloseSync), + NVal::DeclareNapiFunction("write", Write), + NVal::DeclareNapiFunction("read", Read), + NVal::DeclareNapiFunction("close", Close), + }; + + string className = GetClassName(); + bool succ = false; + napi_value cls = nullptr; + tie(succ, cls) = NClass::DefineClass(exports_.env_, className, StreamNExporter::Constructor, move(props)); + if (!succ) { + UniError(EIO).ThrowErr(exports_.env_, "INNER BUG. Failed to define class"); + return false; + } + succ = NClass::SaveClass(exports_.env_, className, cls); + if (!succ) { + UniError(EIO).ThrowErr(exports_.env_, "INNER BUG. Failed to save class"); + return false; + } + + return exports_.AddProp(className, cls); +} + +string StreamNExporter::GetClassName() +{ + return StreamNExporter::className_; +} + +StreamNExporter::StreamNExporter(napi_env env, napi_value exports) : NExporter(env, exports) {} + +StreamNExporter::~StreamNExporter() {} +} // namespace ModuleFileIO +} // namespace DistributedFS +} // namespace OHOS \ No newline at end of file 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 new file mode 100644 index 000000000..3cfe4d2d2 --- /dev/null +++ b/interfaces/kits/js/src/mod_fileio/class_stream/stream_n_exporter.h @@ -0,0 +1,48 @@ +/* + * 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. + */ + +#ifndef INTERFACES_KITS_JS_SRC_MOD_FILEIO_CLASS_STREAM_STREAM_N_EXPORTER_H +#define INTERFACES_KITS_JS_SRC_MOD_FILEIO_CLASS_STREAM_STREAM_N_EXPORTER_H + +#include "../../common/napi/n_exporter.h" + +namespace OHOS { +namespace DistributedFS { +namespace ModuleFileIO { +class StreamNExporter final : public NExporter { +public: + inline static const std::string className_ = "Stream"; + + bool Export() override; + std::string GetClassName() override; + + static napi_value Constructor(napi_env env, napi_callback_info cbinfo); + + static napi_value WriteSync(napi_env env, napi_callback_info cbinfo); + static napi_value FlushSync(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 Close(napi_env env, napi_callback_info cbinfo); + + StreamNExporter(napi_env env, napi_value exports); + ~StreamNExporter() override; +}; +} // namespace ModuleFileIO +} // namespace DistributedFS +} // namespace OHOS +#endif \ No newline at end of file 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 new file mode 100644 index 000000000..29a2c204a --- /dev/null +++ b/interfaces/kits/js/src/mod_fileio/class_watcher/watcher_entity.h @@ -0,0 +1,47 @@ +/* + * 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. + */ + +#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 "../../common/napi/uni_header.h" + +namespace OHOS { +namespace DistributedFS { +namespace ModuleFileIO { +class WatcherHandleDeleter { +public: + void operator()(uv_fs_event_t *ptr) + { + uv_fs_event_stop(ptr); + uv_handle_t *handle = reinterpret_cast(ptr); + uv_close(handle, [](uv_handle_t *handle) { delete handle; }); + } +}; + +struct WatcherInforArg { + int events = 0; + napi_env env = nullptr; + napi_ref ref = nullptr; +}; + +struct WatcherEntity { + std::unique_ptr data_; + std::unique_ptr fsEventReq_; +}; +} // namespace ModuleFileIO +} // namespace DistributedFS +} // namespace OHOS +#endif \ No newline at end of file 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 new file mode 100644 index 000000000..588c4f22b --- /dev/null +++ b/interfaces/kits/js/src/mod_fileio/class_watcher/watcher_n_exporter.cpp @@ -0,0 +1,148 @@ +/* + * 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. + */ + +#include "watcher_n_exporter.h" + +#include +#include +#include +#include +#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" +#include "watcher_entity.h" + +namespace OHOS { +namespace DistributedFS { +namespace ModuleFileIO { +using namespace std; + +napi_value WatcherNExporter::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; + } + + unique_ptr watcherEntity = make_unique(); + if (!NClass::SetEntityFor(env, funcArg.GetThisVar(), move(watcherEntity))) { + stringstream ss; + ss << "INNER BUG. Failed to wrap entity for obj stat"; + UniError(EIO).ThrowErr(env, ss.str()); + return nullptr; + } + return funcArg.GetThisVar(); +} + +napi_value WatcherNExporter::StopSync(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 watchEntity = NClass::GetEntityOf(env, funcArg.GetThisVar()); + if (!watchEntity) { + UniError(EINVAL).ThrowErr(env, "get watcherEntity fail"); + return nullptr; + } + + watchEntity->fsEventReq_.reset(); + return NVal::CreateUndefined(env).val_; +} + +napi_value WatcherNExporter::Stop(napi_env env, napi_callback_info info) +{ + NFuncArg funcArg(env, info); + if (!funcArg.InitArgs(NARG_CNT::ZERO, NARG_CNT::ONE)) { + UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); + return nullptr; + } + + auto watchEntity = NClass::GetEntityOf(env, funcArg.GetThisVar()); + if (!watchEntity) { + UniError(EINVAL).ThrowErr(env, "get watcherEntity fail"); + return nullptr; + } + + auto cbExec = [watchEntity](napi_env env) -> UniError { + watchEntity->fsEventReq_.reset(); + return UniError(ERRNO_NOERR); + }; + + auto cbCompl = [](napi_env env, UniError err) -> NVal { + if (err) { + return { env, err.GetNapiErr(env) }; + } + return { NVal::CreateUndefined(env) }; + }; + + string procedureName = "FileIOCreaterWatcher"; + NVal thisVar(env, funcArg.GetThisVar()); + 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_; + } +} + +bool WatcherNExporter::Export() +{ + vector props = { + NVal::DeclareNapiFunction("stop", Stop), + NVal::DeclareNapiFunction("stopSync", StopSync), + }; + + string className = GetClassName(); + bool succ = false; + napi_value classValue = nullptr; + tie(succ, classValue) = NClass::DefineClass(exports_.env_, + className, + WatcherNExporter::Constructor, + std::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 WatcherNExporter::GetClassName() +{ + return WatcherNExporter::className_; +} + +WatcherNExporter::WatcherNExporter(napi_env env, napi_value exports) : NExporter(env, exports) {} + +WatcherNExporter::~WatcherNExporter() {} +} // namespace ModuleFileIO +} // namespace DistributedFS +} // namespace OHOS \ No newline at end of file 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 new file mode 100644 index 000000000..d5492cd18 --- /dev/null +++ b/interfaces/kits/js/src/mod_fileio/class_watcher/watcher_n_exporter.h @@ -0,0 +1,43 @@ +/* + * 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. + */ + +#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 { +namespace DistributedFS { +namespace ModuleFileIO { +class WatcherNExporter final : public NExporter { +public: + inline static const std::string className_ = "Watcher"; + + bool Export() override; + std::string GetClassName() override; + + static napi_value Constructor(napi_env env, napi_callback_info info); + static napi_value Stop(napi_env env, napi_callback_info info); + static napi_value StopSync(napi_env env, napi_callback_info info); + + WatcherNExporter(napi_env env, napi_value exports); + ~WatcherNExporter() override; +}; +} // namespace ModuleFileIO +} // namespace DistributedFS +} // namespace OHOS +#endif \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fileio/common_func.cpp b/interfaces/kits/js/src/mod_fileio/common_func.cpp new file mode 100644 index 000000000..5f834a464 --- /dev/null +++ b/interfaces/kits/js/src/mod_fileio/common_func.cpp @@ -0,0 +1,232 @@ +/* + * 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. + */ + +#include "common_func.h" + +#include +#include +#include +#include +#include + +#include "../common/log.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 GetActualBuf(napi_env env, void *rawBuf, int64_t bufLen, NVal op) +{ + bool succ = false; + void *realBuf = nullptr; + int64_t opOffset = 0; + if (op.HasProp("offset")) { + tie(succ, opOffset) = op.GetProp("offset").ToInt64(); + if (!succ || opOffset < 0) { + UniError(EINVAL).ThrowErr(env, "Invalid option.offset, positive integer is desired"); + return { false, nullptr, opOffset }; + } else if (opOffset > bufLen) { + UniError(EINVAL).ThrowErr(env, "Invalid option.offset, buffer limit exceeded"); + return { false, nullptr, opOffset }; + } else { + realBuf = static_cast(rawBuf) + opOffset; + } + } else { + realBuf = rawBuf; + } + + return { true, realBuf, opOffset }; +} + +static tuple GetActualLen(napi_env env, int64_t bufLen, int64_t bufOff, NVal op) +{ + bool succ = false; + int64_t retLen; + + if (op.HasProp("length")) { + int64_t opLength; + tie(succ, opLength) = op.GetProp("length").ToInt64(); + if (!succ) { + UniError(EINVAL).ThrowErr(env, "Invalid option.length, expect integer"); + return { false, 0 }; + } + if (opLength < 0) { + 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; + } + + return { true, retLen }; +} + +tuple, unique_ptr> CommonFunc::GetCopyPathArg(napi_env env, + napi_value srcPath, + napi_value dstPath) +{ + bool succ = false; + unique_ptr src; + tie(succ, src, ignore) = NVal(env, srcPath).ToUTF8String(); + if (!succ) { + return { false, nullptr, nullptr }; + } + + unique_ptr dest; + tie(succ, dest, ignore) = NVal(env, dstPath).ToUTF8String(); + if (!succ) { + return { false, nullptr, nullptr }; + } + 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; + + NVal txt(env, readBuf); + 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, offset }; + } + + NVal op = NVal(env, option); + 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); + tie(succ, retLen) = GetActualLen(env, bufLen, bufOff, op); + if (!succ) { + return { false, nullptr, 0, posAssigned, position, offset }; + } + + if (op.HasProp("position")) { + tie(succ, position) = op.GetProp("position").ToInt64(); + if (succ && position >= 0) { + posAssigned = true; + } else { + UniError(EINVAL).ThrowErr(env, "option.position shall be positive number"); + return { false, nullptr, 0, posAssigned, position, offset }; + } + } + + return { true, retBuf, retLen, posAssigned, position, offset }; +} + +static tuple, int64_t> DecodeString(napi_env env, NVal jsStr, NVal encoding) +{ + unique_ptr buf; + if (!jsStr.TypeIs(napi_string)) { + return { false, nullptr, 0 }; + } + + bool succ = false; + if (!encoding) { + return jsStr.ToUTF8String(); + } + + unique_ptr encodingBuf; + tie(succ, encodingBuf, ignore) = encoding.ToUTF8String(); + if (!succ) { + return { false, nullptr, 0 }; + } + string encodingStr(encodingBuf.release()); + if (encodingStr == "utf-8") { + return jsStr.ToUTF8String(); + } else if (encodingStr == "utf-16") { + return jsStr.ToUTF16String(); + } else { + return { false, nullptr, 0 }; + } +} + +// 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; + + /* To get write buffer */ + bool succ = false; + void *buf = nullptr; + int64_t bufLen; + NVal op(env, argOption); + NVal jsBuffer(env, argWBuf); + 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, hasPos, retPos }; + } + } else { + buf = bufferGuard.get(); + } + + 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); + 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")) { + 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 }; + } + hasPos = true; + retPos = position; + } else { + retPos = INVALID_POSITION; + } + return { true, move(bufferGuard), retBuf, retLen, hasPos, retPos }; +} +} // namespace ModuleFileIO +} // namespace DistributedFS +} // namespace OHOS diff --git a/interfaces/kits/js/src/mod_fileio/common_func.h b/interfaces/kits/js/src/mod_fileio/common_func.h new file mode 100644 index 000000000..d952ac517 --- /dev/null +++ b/interfaces/kits/js/src/mod_fileio/common_func.h @@ -0,0 +1,40 @@ +/* + * 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. + */ + +#ifndef INTERFACES_KITS_JS_SRC_MOD_FILEIO_COMMON_FUNC_H +#define INTERFACES_KITS_JS_SRC_MOD_FILEIO_COMMON_FUNC_H + +#include "../common/napi/uni_header.h" + +namespace OHOS { +namespace DistributedFS { +namespace ModuleFileIO { +constexpr int64_t INVALID_POSITION = std::numeric_limits::max(); + +struct CommonFunc { + static std::tuple GetReadArg(napi_env env, + 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); + static std::tuple, std::unique_ptr> GetCopyPathArg(napi_env env, + napi_value srcPath, + napi_value dstPath); +}; +} // namespace ModuleFileIO +} // namespace DistributedFS +} // namespace OHOS +#endif \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fileio/module.cpp b/interfaces/kits/js/src/mod_fileio/module.cpp new file mode 100644 index 000000000..51bd91fd0 --- /dev/null +++ b/interfaces/kits/js/src/mod_fileio/module.cpp @@ -0,0 +1,58 @@ +/* + * 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. + */ + +#include +#include + +#include "../common/log.h" +#include "class_constants/constants.h" +#include "class_dir/dir_n_exporter.h" +#include "class_dirent/dirent_n_exporter.h" +#include "class_stat/stat_n_exporter.h" +#include "class_stream/stream_n_exporter.h" +#include "class_watcher/watcher_n_exporter.h" +#include "properties/prop_n_exporter.h" + +using namespace std; + +namespace OHOS { +namespace DistributedFS { +namespace ModuleFileIO { +static napi_value Export(napi_env env, napi_value exports) +{ + std::vector> products; + 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)); + + for (auto &&product : products) { + if (!product->Export()) { + HILOGE("INNER BUG. Failed to export class %{public}s for module fileio", product->GetClassName().c_str()); + return nullptr; + } else { + HILOGE("Class %{public}s for module fileio has been exported", product->GetClassName().c_str()); + } + } + return exports; +} + +NAPI_MODULE(fileio, Export) +} // namespace ModuleFileIO +} // namespace DistributedFS +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fileio/properties/chmod.cpp b/interfaces/kits/js/src/mod_fileio/properties/chmod.cpp new file mode 100644 index 000000000..781dcc547 --- /dev/null +++ b/interfaces/kits/js/src/mod_fileio/properties/chmod.cpp @@ -0,0 +1,112 @@ +/* + * 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. + */ + +#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 { +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; + } + + 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 mode; + tie(succ, mode) = NVal(env, funcArg[NARG_POS::SECOND]).ToInt32(); + if (!succ) { + UniError(EINVAL).ThrowErr(env, "Invalid mode"); + return nullptr; + } + + 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; + } + + 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(); + 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"); + } + + auto cbExec = [path, mode](napi_env env) -> UniError { + if (chmod(path.c_str(), mode) == -1) { + return UniError(errno); + } else { + return UniError(ERRNO_NOERR); + } + }; + auto cbComplete = [](napi_env env, UniError err) -> NVal { + if (err) { + return { env, err.GetNapiErr(env) }; + } + return { NVal::CreateUndefined(env) }; + }; + NVal thisVar(env, funcArg.GetThisVar()); + + 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 +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fileio/properties/chmod.h b/interfaces/kits/js/src/mod_fileio/properties/chmod.h new file mode 100644 index 000000000..825289198 --- /dev/null +++ b/interfaces/kits/js/src/mod_fileio/properties/chmod.h @@ -0,0 +1,32 @@ +/* + * 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. + */ + +#ifndef INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_CHMOD_H +#define INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_CHMOD_H + +#include "../../common/napi/n_val.h" + +namespace OHOS { +namespace DistributedFS { +namespace ModuleFileIO { +class Chmod final { +public: + static napi_value Sync(napi_env env, napi_callback_info info); + static napi_value Async(napi_env env, napi_callback_info info); +}; +} // namespace ModuleFileIO +} // namespace DistributedFS +} // namespace OHOS +#endif \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fileio/properties/chown.cpp b/interfaces/kits/js/src/mod_fileio/properties/chown.cpp new file mode 100644 index 000000000..dfffbb801 --- /dev/null +++ b/interfaces/kits/js/src/mod_fileio/properties/chown.cpp @@ -0,0 +1,126 @@ +/* + * 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. + */ + +#include "chown.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_func_arg.h" +namespace OHOS { +namespace DistributedFS { +namespace ModuleFileIO { +using namespace std; + +static tuple GetChownArg(napi_env env, const NFuncArg &funcArg) +{ + 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 }; + } + + int owner; + tie(succ, owner) = NVal(env, funcArg[NARG_POS::SECOND]).ToInt32(); + if (!succ) { + UniError(EINVAL).ThrowErr(env, "Invalid owner"); + return { false, "", -1, -1 }; + } + + 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; + } + + bool succ = false; + int owner; + int group; + string path; + tie(succ, path, owner, group) = GetChownArg(env, funcArg); + if (!succ) { + return nullptr; + } + + if (chown(path.c_str(), owner, group) == -1) { + UniError(errno).ThrowErr(env); + return nullptr; + } + + return NVal::CreateUndefined(env).val_; +} + +napi_value Chown::Async(napi_env env, napi_callback_info info) +{ + NFuncArg funcArg(env, info); + if (!funcArg.InitArgs(NARG_CNT::THREE, NARG_CNT::FOUR)) { + UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); + return nullptr; + } + + bool succ = false; + int owner; + int group; + string path; + tie(succ, path, owner, group) = GetChownArg(env, funcArg); + if (!succ) { + return nullptr; + } + + auto cbExec = [path, owner, group](napi_env env) -> UniError { + if (chown(path.c_str(), owner, group) == -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) }; + }; + + string procedureName = "FileIOChown"; + NVal thisVar(env, funcArg.GetThisVar()); + if (funcArg.GetArgc() == NARG_CNT::THREE) { + return NAsyncWorkPromise(env, thisVar).Schedule(procedureName, cbExec, cbCompl).val_; + } else { + int cbIdx = NARG_POS::FOURTH; + NVal cb(env, funcArg[cbIdx]); + return NAsyncWorkCallback(env, thisVar, cb).Schedule(procedureName, cbExec, cbCompl).val_; + } +} +} // namespace ModuleFileIO +} // namespace DistributedFS +} // namespace OHOS diff --git a/interfaces/kits/js/src/mod_fileio/properties/chown.h b/interfaces/kits/js/src/mod_fileio/properties/chown.h new file mode 100644 index 000000000..5ac00ec2f --- /dev/null +++ b/interfaces/kits/js/src/mod_fileio/properties/chown.h @@ -0,0 +1,32 @@ +/* + * 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. + */ + +#ifndef INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_CHOWN_H +#define INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_CHOWN_H + +#include "../../common/napi/n_val.h" + +namespace OHOS { +namespace DistributedFS { +namespace ModuleFileIO { +class Chown final { +public: + static napi_value Sync(napi_env env, napi_callback_info info); + static napi_value Async(napi_env env, napi_callback_info info); +}; +} // namespace ModuleFileIO +} // namespace DistributedFS +} // namespace OHOS +#endif \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fileio/properties/close.cpp b/interfaces/kits/js/src/mod_fileio/properties/close.cpp new file mode 100644 index 000000000..32865b6f9 --- /dev/null +++ b/interfaces/kits/js/src/mod_fileio/properties/close.cpp @@ -0,0 +1,96 @@ +/* + * 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. + */ + +#include "close.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_func_arg.h" +namespace OHOS { +namespace DistributedFS { +namespace ModuleFileIO { +using namespace std; + +napi_value Close::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; + } + + 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; + } + + if (close(fd) == -1) { + UniError(errno).ThrowErr(env); + return nullptr; + } + + return NVal::CreateUndefined(env).val_; +} + +napi_value Close::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; + } + 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 cbExec = [fd](napi_env env) -> UniError { + int ret = close(fd); + if (ret == -1) { + return UniError(errno); + } else { + return UniError(ERRNO_NOERR); + } + }; + auto cbComplete = [](napi_env env, UniError err) -> NVal { + if (err) { + return { env, err.GetNapiErr(env) }; + } else { + return NVal::CreateUndefined(env); + } + }; + string procedureName = "FileIOClose"; + size_t argc = funcArg.GetArgc(); + NVal thisVar(env, funcArg.GetThisVar()); + if (argc == NARG_CNT::ONE) { + return NAsyncWorkPromise(env, thisVar).Schedule(procedureName, cbExec, cbComplete).val_; + } else { + NVal cb(env, funcArg[NARG_POS::SECOND]); + return NAsyncWorkCallback(env, thisVar, cb).Schedule(procedureName, cbExec, cbComplete).val_; + } +} +} // namespace ModuleFileIO +} // namespace DistributedFS +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fileio/properties/close.h b/interfaces/kits/js/src/mod_fileio/properties/close.h new file mode 100644 index 000000000..6d6a39646 --- /dev/null +++ b/interfaces/kits/js/src/mod_fileio/properties/close.h @@ -0,0 +1,32 @@ +/* + * 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. + */ + +#ifndef INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_CLOSE_H +#define INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_CLOSE_H + +#include "../../common/napi/n_val.h" + +namespace OHOS { +namespace DistributedFS { +namespace ModuleFileIO { +class Close final { +public: + static napi_value Sync(napi_env env, napi_callback_info info); + static napi_value Async(napi_env env, napi_callback_info info); +}; +} // namespace ModuleFileIO +} // namespace DistributedFS +} // namespace OHOS +#endif \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fileio/properties/copy_file.cpp b/interfaces/kits/js/src/mod_fileio/properties/copy_file.cpp new file mode 100644 index 000000000..6a6dd5aa3 --- /dev/null +++ b/interfaces/kits/js/src/mod_fileio/properties/copy_file.cpp @@ -0,0 +1,203 @@ +/* + * 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. + */ + +#include "copy_file.h" + +#include +#include +#include +#include +#include +#include +#include + +#include "../../common/file_helper/fd_guard.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 { +using namespace std; + +struct FileInfo { + bool isPath = false; + unique_ptr path; + FDGuard fdg; +}; + +static UniError CopyFileCore(FileInfo &srcFile, FileInfo &destFile) +{ + int res = EINVAL; + if (srcFile.isPath) { + 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); + } + + if (destFile.isPath) { + destFile.fdg.SetFD(open(destFile.path.get(), O_WRONLY | O_CREAT, statbf.st_mode), true); + res = errno; + } + if (!destFile.fdg) { + return UniError(res); + } + + int block = 4096; + auto copyBuf = make_unique(block); + do { + ssize_t readSize = read(srcFile.fdg.GetFD(), copyBuf.get(), block); + if (readSize == -1) { + return UniError(errno); + } else if (readSize == 0) { + break; + } + ssize_t writeSize = write(destFile.fdg.GetFD(), copyBuf.get(), readSize); + if (writeSize != readSize) { + return UniError(errno); + } + if (readSize != block) { + break; + } + } while (true); + + return UniError(ERRNO_NOERR); +} + +static tuple ParseJsModeAndProm(napi_env env, const NFuncArg &funcArg) +{ + bool succ = false; + bool promise = false; + bool hasMode = false; + int mode = 0; + if (funcArg.GetArgc() == NARG_CNT::THREE && NVal(env, funcArg[NARG_POS::THIRD]).TypeIs(napi_number)) { + promise = true; + hasMode = true; + } 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}; +} + +static tuple ParseJsOperand(napi_env env, NVal pathOrFdFromJsArg) +{ + auto [isPath, path, ignore] = pathOrFdFromJsArg.ToUTF8String(); + if (isPath) { + return {true, FileInfo{true, move(path), {}}}; + } + + auto [isFd, fd] = pathOrFdFromJsArg.ToInt32(); + if (isFd) { + return {true, FileInfo{false, {}, {fd, false}}}; + } + + return {false, FileInfo{false, {}, {}}}; +}; + +napi_value CopyFile::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 [succSrc, src] = ParseJsOperand(env, {env, funcArg[NARG_POS::FIRST]}); + auto [succDest, dest] = ParseJsOperand(env, {env, funcArg[NARG_POS::SECOND]}); + if (!succSrc || !succDest) { + UniError(EINVAL).ThrowErr(env, "The first/second argument requires filepath/fd"); + return nullptr; + } + + auto [succMode, mode, ignore] = ParseJsModeAndProm(env, funcArg); + if (!succMode) { + UniError(EINVAL).ThrowErr(env, "Invalid mode"); + return nullptr; + } + + auto err = CopyFileCore(src, dest); + if (err) { + err.ThrowErr(env); + return nullptr; + } + + return NVal::CreateUndefined(env).val_; +} + +class Para { +public: + FileInfo src_; + FileInfo dest_; + + Para(FileInfo src, FileInfo dest) : src_(move(src)), dest_(move(dest)) {}; +}; + +napi_value CopyFile::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 [succSrc, src] = ParseJsOperand(env, {env, funcArg[NARG_POS::FIRST]}); + auto [succDest, dest] = ParseJsOperand(env, {env, funcArg[NARG_POS::SECOND]}); + if (!succSrc || !succDest) { + UniError(EINVAL).ThrowErr(env, "The first/second argument requires filepath/fd"); + return nullptr; + } + + auto [succMode, mode, promise] = ParseJsModeAndProm(env, funcArg); + if (!succMode) { + UniError(EINVAL).ThrowErr(env, "Invalid mode"); + return nullptr; + } + + auto cbExec = [para = make_shared(move(src), move(dest))](napi_env env) -> UniError { + return CopyFileCore(para->src_, para->dest_); + }; + + auto cbCompl = [](napi_env env, UniError err) -> NVal { + if (err) { + return {env, err.GetNapiErr(env)}; + } + return {NVal::CreateUndefined(env)}; + }; + + string procedureName = "FileIOCopyFile"; + NVal thisVar(env, funcArg.GetThisVar()); + if (funcArg.GetArgc() == NARG_CNT::TWO || promise) { + return NAsyncWorkPromise(env, thisVar).Schedule(procedureName, cbExec, cbCompl).val_; + } else { + NVal cb(env, funcArg[((funcArg.GetArgc() == NARG_CNT::THREE) ? NARG_POS::THIRD : NARG_POS::FOURTH)]); + return NAsyncWorkCallback(env, thisVar, cb).Schedule(procedureName, cbExec, cbCompl).val_; + } +} +} // namespace ModuleFileIO +} // namespace DistributedFS +} // namespace OHOS diff --git a/interfaces/kits/js/src/mod_fileio/properties/copy_file.h b/interfaces/kits/js/src/mod_fileio/properties/copy_file.h new file mode 100644 index 000000000..bef01ef1e --- /dev/null +++ b/interfaces/kits/js/src/mod_fileio/properties/copy_file.h @@ -0,0 +1,32 @@ +/* + * 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. + */ + +#ifndef INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_COPY_FILE_H +#define INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_COPY_FILE_H + +#include "../../common/napi/n_val.h" + +namespace OHOS { +namespace DistributedFS { +namespace ModuleFileIO { +class CopyFile final { +public: + static napi_value Async(napi_env env, napi_callback_info info); + static napi_value Sync(napi_env env, napi_callback_info info); +}; +} // 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 new file mode 100644 index 000000000..18c037212 --- /dev/null +++ b/interfaces/kits/js/src/mod_fileio/properties/create_stream.cpp @@ -0,0 +1,144 @@ +/* + * 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. + */ +#include "create_stream.h" + +#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 "../class_stream/stream_entity.h" +#include "../class_stream/stream_n_exporter.h" + +namespace OHOS { +namespace DistributedFS { +namespace ModuleFileIO { +using namespace std; + +static NVal InstantiateStream(napi_env env, unique_ptr fp) +{ + napi_value objStream = NClass::InstantiateClass(env, StreamNExporter::className_, {}); + if (!objStream) { + UniError(EIO).ThrowErr(env, "INNER BUG. Cannot instantiate stream"); + return NVal(); + } + + auto streamEntity = NClass::GetEntityOf(env, objStream); + if (!streamEntity) { + UniError(EIO).ThrowErr(env, "Cannot instantiate stream because of void entity"); + return NVal(); + } + + streamEntity->fp.swap(fp); + return { env, objStream }; +} + +static tuple GetCreateStreamArgs(napi_env env, const NFuncArg &funcArg) +{ + 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, "", "" }; + } + + unique_ptr mode; + tie(succ, mode, ignore) = NVal(env, funcArg[NARG_POS::SECOND]).ToUTF8String(); + if (!succ) { + UniError(EINVAL).ThrowErr(env, "Invalid mode"); + return { false, "", "" }; + } + + return { true, path.get(), mode.get() }; +} + +napi_value CreateStream::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; + } + + bool succ = false; + string argPath; + string argMode; + tie(succ, argPath, argMode) = GetCreateStreamArgs(env, funcArg); + if (!succ) { + return nullptr; + } + + unique_ptr fp = { fopen(argPath.c_str(), argMode.c_str()), fclose }; + if (!fp) { + UniError(errno).ThrowErr(env); + return nullptr; + } + return InstantiateStream(env, move(fp)).val_; +} + +struct AsyncCreateStreamArg { + unique_ptr fp = { nullptr, fclose }; +}; + +napi_value CreateStream::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; + } + + bool succ = false; + string argPath; + string argMode; + tie(succ, argPath, argMode) = GetCreateStreamArgs(env, funcArg); + if (!succ) { + return nullptr; + } + + auto arg = make_shared(); + auto cbExec = [arg, argPath = move(argPath), argMode = move(argMode)](napi_env env) -> UniError { + arg->fp = { fopen(argPath.c_str(), argMode.c_str()), fclose }; + if (!arg->fp) { + return UniError(errno); + } else { + return UniError(ERRNO_NOERR); + } + }; + auto cbCompl = [arg](napi_env env, UniError err) -> NVal { + if (err) { + return { env, err.GetNapiErr(env) }; + } + return InstantiateStream(env, move(arg->fp)); + }; + + string procedureName = "FileIOCreateStream"; + NVal thisVar(env, funcArg.GetThisVar()); + if (funcArg.GetArgc() == NARG_CNT::TWO) { + return NAsyncWorkPromise(env, thisVar).Schedule(procedureName, cbExec, cbCompl).val_; + } else { + NVal cb(env, funcArg[NARG_POS::THIRD]); + return NAsyncWorkCallback(env, thisVar, cb).Schedule(procedureName, 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_stream.h b/interfaces/kits/js/src/mod_fileio/properties/create_stream.h new file mode 100644 index 000000000..7c58fa744 --- /dev/null +++ b/interfaces/kits/js/src/mod_fileio/properties/create_stream.h @@ -0,0 +1,32 @@ +/* + * 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. + */ + +#ifndef INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_CREATE_STREAM_H +#define INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_CREATE_STREAM_H + +#include "../../common/napi/uni_header.h" + +namespace OHOS { +namespace DistributedFS { +namespace ModuleFileIO { +class CreateStream final { +public: + static napi_value Async(napi_env env, napi_callback_info info); + static napi_value Sync(napi_env env, napi_callback_info info); +}; +} // namespace ModuleFileIO +} // namespace DistributedFS +} // namespace OHOS +#endif \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fileio/properties/fchmod.cpp b/interfaces/kits/js/src/mod_fileio/properties/fchmod.cpp new file mode 100644 index 000000000..304268d73 --- /dev/null +++ b/interfaces/kits/js/src/mod_fileio/properties/fchmod.cpp @@ -0,0 +1,115 @@ +/* + * 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. + */ + +#include "fchmod.h" +#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; + +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; + } + + 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; + } + + int mode; + tie(succ, mode) = NVal(env, funcArg[NARG_POS::SECOND]).ToInt32(); + if (!succ) { + UniError(EINVAL).ThrowErr(env, "Invalid mode"); + return nullptr; + } + + int ret = fchmod(fd, mode); + if (ret == -1) { + UniError(errno).ThrowErr(env); + return nullptr; + } + + return NVal::CreateUndefined(env).val_; +} + + +napi_value Fchmod::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; + } + + 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; + } + + int mode; + tie(succ, mode) = NVal(env, funcArg[NARG_POS::SECOND]).ToInt32(); + if (!succ) { + UniError(EINVAL).ThrowErr(env, "Invalid owner"); + } + + auto cbExec = [fd, mode](napi_env env) -> UniError { + int ret = fchmod(fd, mode); + if (ret == -1) { + return UniError(errno); + } else { + return UniError(ERRNO_NOERR); + } + }; + + auto cbComplCallback = [](napi_env env, UniError err) -> NVal { + if (err) { + return { env, err.GetNapiErr(env) }; + } + return { NVal::CreateUndefined(env) }; + }; + + string procedureName = "FileIOFchmod"; + NVal thisVar(env, funcArg.GetThisVar()); + if (argc == NARG_CNT::TWO) { + return NAsyncWorkPromise(env, thisVar).Schedule(procedureName, cbExec, cbComplCallback).val_; + } else { + NVal cb(env, funcArg[NARG_POS::THIRD]); + return NAsyncWorkCallback(env, thisVar, cb).Schedule(procedureName, cbExec, cbComplCallback).val_; + } +} +} // namespace ModuleFileIO +} // namespace DistributedFS +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fileio/properties/fchmod.h b/interfaces/kits/js/src/mod_fileio/properties/fchmod.h new file mode 100644 index 000000000..eb7711822 --- /dev/null +++ b/interfaces/kits/js/src/mod_fileio/properties/fchmod.h @@ -0,0 +1,32 @@ +/* + * 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. + */ + +#ifndef INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_FCHMOD_H +#define INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_FCHMOD_H + +#include "../../common/napi/n_val.h" + +namespace OHOS { +namespace DistributedFS { +namespace ModuleFileIO { +class Fchmod final { +public: + static napi_value Sync(napi_env env, napi_callback_info info); + static napi_value Async(napi_env env, napi_callback_info info); +}; +} // namespace ModuleFileIO +} // namespace DistributedFS +} // namespace OHOS +#endif \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fileio/properties/fchown.cpp b/interfaces/kits/js/src/mod_fileio/properties/fchown.cpp new file mode 100644 index 000000000..bbc2c8e7e --- /dev/null +++ b/interfaces/kits/js/src/mod_fileio/properties/fchown.cpp @@ -0,0 +1,123 @@ +/* + * 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. + */ + +#include "fchown.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 { +using namespace std; + +napi_value Fchown::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; + } + + 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; + } + + int owner; + tie(succ, owner) = NVal(env, funcArg[NARG_POS::SECOND]).ToInt32(); + if (!succ) { + UniError(EINVAL).ThrowErr(env, "Invalid owner"); + } + + int group; + tie(succ, group) = NVal(env, funcArg[NARG_POS::THIRD]).ToInt32(); + if (!succ) { + UniError(EINVAL).ThrowErr(env, "Invalid group"); + } + + int ret = fchown(fd, owner, group); + if (ret == -1) { + UniError(errno).ThrowErr(env); + return nullptr; + } + + return NVal::CreateUndefined(env).val_; +} + +napi_value Fchown::Async(napi_env env, napi_callback_info info) +{ + NFuncArg funcArg(env, info); + if (!funcArg.InitArgs(NARG_CNT::THREE, NARG_CNT::FOUR)) { + UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); + return nullptr; + } + + 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; + } + + int owner; + tie(succ, owner) = NVal(env, funcArg[NARG_POS::SECOND]).ToInt32(); + if (!succ) { + UniError(EINVAL).ThrowErr(env, "Invalid owner"); + } + + int group; + tie(succ, group) = NVal(env, funcArg[NARG_POS::THIRD]).ToInt32(); + if (!succ) { + UniError(EINVAL).ThrowErr(env, "Invalid group"); + } + + auto cbExec = [fd, owner, group](napi_env env) -> UniError { + int ret = fchown(fd, owner, group); + if (ret == -1) { + return UniError(errno); + } else { + return UniError(ERRNO_NOERR); + } + }; + + auto cbComplCallback = [](napi_env env, UniError err) -> NVal { + if (err) { + return { env, err.GetNapiErr(env) }; + } + return { NVal::CreateUndefined(env) }; + }; + + string procedureName = "FileIOFchown"; + NVal thisVar(env, funcArg.GetThisVar()); + if (argc == NARG_CNT::THREE) { + return NAsyncWorkPromise(env, thisVar).Schedule(procedureName, cbExec, cbComplCallback).val_; + } else { + NVal cb(env, funcArg[NARG_POS::FOURTH]); + return NAsyncWorkCallback(env, thisVar, cb).Schedule(procedureName, cbExec, cbComplCallback).val_; + } +} +} // namespace ModuleFileIO +} // namespace DistributedFS +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fileio/properties/fchown.h b/interfaces/kits/js/src/mod_fileio/properties/fchown.h new file mode 100644 index 000000000..7439f2e54 --- /dev/null +++ b/interfaces/kits/js/src/mod_fileio/properties/fchown.h @@ -0,0 +1,32 @@ +/* + * 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. + */ + +#ifndef INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_FCHOWN_H +#define INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_FCHOWN_H + +#include "../../common/napi/n_val.h" + +namespace OHOS { +namespace DistributedFS { +namespace ModuleFileIO { +class Fchown final { +public: + static napi_value Sync(napi_env env, napi_callback_info info); + static napi_value Async(napi_env env, napi_callback_info info); +}; +} // namespace ModuleFileIO +} // namespace DistributedFS +} // namespace OHOS +#endif \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fileio/properties/fdatasync.cpp b/interfaces/kits/js/src/mod_fileio/properties/fdatasync.cpp new file mode 100644 index 000000000..95928385a --- /dev/null +++ b/interfaces/kits/js/src/mod_fileio/properties/fdatasync.cpp @@ -0,0 +1,102 @@ +/* + * 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. + */ + +#include "fdatasync.h" +#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; + +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; + } + + 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; + } + + int ret = fdatasync(fd); + if (ret == -1) { + UniError(errno).ThrowErr(env); + return nullptr; + } + + return NVal::CreateUndefined(env).val_; +} + + +napi_value Fdatasync::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; + } + + 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 cbExec = [fd](napi_env env) -> UniError { + int ret = fdatasync(fd); + if (ret == -1) { + return UniError(errno); + } else { + return UniError(ERRNO_NOERR); + } + }; + + auto cbComplCallback = [](napi_env env, UniError err) -> NVal { + if (err) { + return { env, err.GetNapiErr(env) }; + } + return { NVal::CreateUndefined(env) }; + }; + + string procedureName = "FileIOFdatasync"; + NVal thisVar(env, funcArg.GetThisVar()); + if (argc == NARG_CNT::ONE) { + return NAsyncWorkPromise(env, thisVar).Schedule(procedureName, cbExec, cbComplCallback).val_; + } else { + NVal cb(env, funcArg[NARG_POS::SECOND]); + return NAsyncWorkCallback(env, thisVar, cb).Schedule(procedureName, cbExec, cbComplCallback).val_; + } +} +} // namespace ModuleFileIO +} // namespace DistributedFS +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fileio/properties/fdatasync.h b/interfaces/kits/js/src/mod_fileio/properties/fdatasync.h new file mode 100644 index 000000000..f10fcbde3 --- /dev/null +++ b/interfaces/kits/js/src/mod_fileio/properties/fdatasync.h @@ -0,0 +1,32 @@ +/* + * 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. + */ + +#ifndef INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_FDATASYNC_H +#define INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_FDATASYNC_H + +#include "../../common/napi/n_val.h" + +namespace OHOS { +namespace DistributedFS { +namespace ModuleFileIO { +class Fdatasync final { +public: + static napi_value Sync(napi_env env, napi_callback_info info); + static napi_value Async(napi_env env, napi_callback_info info); +}; +} // namespace ModuleFileIO +} // namespace DistributedFS +} // namespace OHOS +#endif \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fileio/properties/fdopen_stream.cpp b/interfaces/kits/js/src/mod_fileio/properties/fdopen_stream.cpp new file mode 100644 index 000000000..2baf39386 --- /dev/null +++ b/interfaces/kits/js/src/mod_fileio/properties/fdopen_stream.cpp @@ -0,0 +1,146 @@ +/* + * 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. + */ + +#include "fdopen_stream.h" +#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 "../class_stream/stream_entity.h" +#include "../class_stream/stream_n_exporter.h" + +namespace OHOS { +namespace DistributedFS { +namespace ModuleFileIO { +using namespace std; + +static NVal InstantiateStream(napi_env env, unique_ptr fp) +{ + napi_value objStream = NClass::InstantiateClass(env, StreamNExporter::className_, {}); + if (!objStream) { + UniError(EIO).ThrowErr(env, "INNER BUG. Cannot instantiate stream"); + return NVal(); + } + + auto streamEntity = NClass::GetEntityOf(env, objStream); + if (!streamEntity) { + UniError(EIO).ThrowErr(env, "Cannot instantiate stream because of void entity"); + return NVal(); + } + + streamEntity->fp.swap(fp); + return { env, objStream }; +} + +static tuple GetFdopenStreamArgs(napi_env env, const NFuncArg &funcArg) +{ + 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, "" }; + } + + 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; + } + + bool succ = false; + int fd; + string mode; + + tie(succ, fd, mode) = GetFdopenStreamArgs(env, funcArg); + if (!succ) { + return nullptr; + } + + unique_ptr fp = { fdopen(fd, mode.c_str()), fclose }; + if (!fp) { + UniError(errno).ThrowErr(env); + return nullptr; + } + + return InstantiateStream(env, move(fp)).val_; +} + +struct AsyncFdopenStreamArg { + unique_ptr fp = { nullptr, fclose }; +}; + +napi_value FdopenStream::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; + } + + bool success = false; + int fd; + string mode; + tie(success, fd, mode) = GetFdopenStreamArgs(env, funcArg); + if (!success) { + return nullptr; + } + + auto arg = make_shared(); + auto cbExec = [arg, fd, mode = move(mode)](napi_env env) -> UniError { + arg->fp = { fdopen(fd, mode.c_str()), fclose }; + if (!arg->fp) { + return UniError(errno); + } else { + return UniError(ERRNO_NOERR); + } + }; + + auto cbCompl = [arg](napi_env env, UniError err) -> NVal { + if (err) { + return { env, err.GetNapiErr(env) }; + } + return InstantiateStream(env, move(arg->fp)); + }; + + string procedureName = "FileIOFdopenStream"; + NVal thisVar(env, funcArg.GetThisVar()); + if (funcArg.GetArgc() == NARG_CNT::TWO) { + return NAsyncWorkPromise(env, thisVar).Schedule(procedureName, cbExec, cbCompl).val_; + } else { + NVal cb(env, funcArg[NARG_POS::THIRD]); + return NAsyncWorkCallback(env, thisVar, cb).Schedule(procedureName, 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/fdopen_stream.h b/interfaces/kits/js/src/mod_fileio/properties/fdopen_stream.h new file mode 100644 index 000000000..195369ece --- /dev/null +++ b/interfaces/kits/js/src/mod_fileio/properties/fdopen_stream.h @@ -0,0 +1,32 @@ +/* + * 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. + */ + +#ifndef INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_FDOPEN_STREAM_H +#define INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_FDOPEN_STREAM_H + +#include "../../common/napi/uni_header.h" + +namespace OHOS { +namespace DistributedFS { +namespace ModuleFileIO { +class FdopenStream final { +public: + static napi_value Async(napi_env env, napi_callback_info info); + static napi_value Sync(napi_env env, napi_callback_info info); +}; +} // namespace ModuleFileIO +} // namespace DistributedFS +} // namespace OHOS +#endif \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fileio/properties/fstat.cpp b/interfaces/kits/js/src/mod_fileio/properties/fstat.cpp new file mode 100644 index 000000000..6479cdf42 --- /dev/null +++ b/interfaces/kits/js/src/mod_fileio/properties/fstat.cpp @@ -0,0 +1,128 @@ +/* + * 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. + */ +#include "fstat.h" + +#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 "../class_stat/stat_entity.h" +#include "../class_stat/stat_n_exporter.h" + +namespace OHOS { +namespace DistributedFS { +namespace ModuleFileIO { +using namespace std; + +napi_value Fstat::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; + } + + 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; + } + + struct stat buf; + if (fstat(fd, &buf) == -1) { + UniError(errno).ThrowErr(env); + return nullptr; + } + + napi_value objStat = NClass::InstantiateClass(env, StatNExporter::className_, {}); + if (!objStat) { + UniError(EINVAL).ThrowErr(env, "Cannot instantiate class"); + return nullptr; + } + + auto statEntity = NClass::GetEntityOf(env, objStat); + if (!statEntity) { + UniError(EINVAL).ThrowErr(env, "Cannot get the entity of objStat"); + return nullptr; + } + statEntity->stat_ = buf; + + return objStat; +} + +struct AsyncStatArg { + struct stat stat_; +}; + +napi_value Fstat::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; + } + + 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 arg = make_shared(); + auto cbExec = [fd, arg](napi_env env) -> UniError { + if (fstat(fd, &arg->stat_)) { + return UniError(errno); + } else { + 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()); + string procedureName = "fileIOFstat"; + 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_; + } +} +} // namespace ModuleFileIO +} // namespace DistributedFS +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fileio/properties/fstat.h b/interfaces/kits/js/src/mod_fileio/properties/fstat.h new file mode 100644 index 000000000..27395df81 --- /dev/null +++ b/interfaces/kits/js/src/mod_fileio/properties/fstat.h @@ -0,0 +1,32 @@ +/* + * 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. + */ + +#ifndef INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_FSTAT_H +#define INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_FSTAT_H + +#include "../../common/napi/uni_header.h" + +namespace OHOS { +namespace DistributedFS { +namespace ModuleFileIO { +class Fstat final { +public: + static napi_value Async(napi_env env, napi_callback_info info); + static napi_value Sync(napi_env env, napi_callback_info info); +}; +} // namespace ModuleFileIO +} // namespace DistributedFS +} // namespace OHOS +#endif \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fileio/properties/fsync.cpp b/interfaces/kits/js/src/mod_fileio/properties/fsync.cpp new file mode 100644 index 000000000..9e4afdc5e --- /dev/null +++ b/interfaces/kits/js/src/mod_fileio/properties/fsync.cpp @@ -0,0 +1,97 @@ +/* + * 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. + */ + +#include "fsync.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_func_arg.h" +namespace OHOS { +namespace DistributedFS { +namespace ModuleFileIO { +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; + } + + 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; + } + + if (fsync(fd) == -1) { + 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; + } + + 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 cbExec = [fd](napi_env env) -> UniError { + if (fsync(fd) == -1) { + return UniError(errno); + } else { + return UniError(ERRNO_NOERR); + } + }; + auto cbComplete = [](napi_env env, UniError err) -> NVal { + if (err) { + return { env, err.GetNapiErr(env) }; + } else { + return NVal::CreateUndefined(env); + } + }; + string procedureName = "FileIOFsync"; + size_t argc = funcArg.GetArgc(); + NVal thisVar(env, funcArg.GetThisVar()); + if (argc == NARG_CNT::ONE) { + return NAsyncWorkPromise(env, thisVar).Schedule(procedureName, cbExec, cbComplete).val_; + } else { + NVal cb(env, funcArg[NARG_POS::SECOND]); + return NAsyncWorkCallback(env, thisVar, cb).Schedule(procedureName, cbExec, cbComplete).val_; + } +} +} // namespace ModuleFileIO +} // namespace DistributedFS +} // namespace OHOS diff --git a/interfaces/kits/js/src/mod_fileio/properties/fsync.h b/interfaces/kits/js/src/mod_fileio/properties/fsync.h new file mode 100644 index 000000000..0e2a54e04 --- /dev/null +++ b/interfaces/kits/js/src/mod_fileio/properties/fsync.h @@ -0,0 +1,32 @@ +/* + * 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. + */ + +#ifndef INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_FSYNC_H +#define INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_FSYNC_H + +#include "../../common/napi/n_val.h" + +namespace OHOS { +namespace DistributedFS { +namespace ModuleFileIO { +class Fsync final { +public: + static napi_value Sync(napi_env env, napi_callback_info info); + static napi_value Async(napi_env env, napi_callback_info info); +}; +} // namespace ModuleFileIO +} // namespace DistributedFS +} // namespace OHOS +#endif \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fileio/properties/ftruncate.cpp b/interfaces/kits/js/src/mod_fileio/properties/ftruncate.cpp new file mode 100644 index 000000000..49e20393e --- /dev/null +++ b/interfaces/kits/js/src/mod_fileio/properties/ftruncate.cpp @@ -0,0 +1,119 @@ +/* + * 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. + */ + +#include "ftruncate.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_func_arg.h" + +namespace OHOS { +namespace DistributedFS { +namespace ModuleFileIO { +using namespace std; + +napi_value Ftruncate::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; + } + + 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 (argc == NARG_CNT::ONE) { + ret = ftruncate(fd, 0); + } else { + int len; + tie(succ, len) = NVal(env, funcArg[NARG_POS::SECOND]).ToInt32(); + if (!succ) { + UniError(EINVAL).ThrowErr(env, "Invalid len"); + return nullptr; + } + ret = ftruncate(fd, len); + } + + if (ret == -1) { + UniError(errno).ThrowErr(env); + return nullptr; + } + + return NVal::CreateUndefined(env).val_; +} +napi_value Ftruncate::Async(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; + } + 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; + } + size_t argc = funcArg.GetArgc(); + if (argc > NARG_CNT::ONE) { + tie(succ, len) = NVal(env, funcArg[NARG_POS::SECOND]).ToInt32(); + if (!succ) { + UniError(EINVAL).ThrowErr(env, "Invalid len"); + return nullptr; + } + } + + auto cbExec = [fd, len](napi_env env) -> UniError { + int ret = ftruncate(fd, len); + if (ret == -1) { + return UniError(errno); + } else { + return UniError(ERRNO_NOERR); + } + }; + auto cbComplete = [](napi_env env, UniError err) -> NVal { + if (err) { + return { env, err.GetNapiErr(env) }; + } else { + return NVal::CreateUndefined(env); + } + }; + 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_; + } else { + NVal cb(env, funcArg[NARG_POS::THIRD]); + return NAsyncWorkCallback(env, thisVar, cb).Schedule(procedureName, cbExec, cbComplete).val_; + } +} +} // namespace ModuleFileIO +} // namespace DistributedFS +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fileio/properties/ftruncate.h b/interfaces/kits/js/src/mod_fileio/properties/ftruncate.h new file mode 100644 index 000000000..f9d076efc --- /dev/null +++ b/interfaces/kits/js/src/mod_fileio/properties/ftruncate.h @@ -0,0 +1,32 @@ +/* + * 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. + */ + +#ifndef INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_FTRUNCATE_H +#define INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_FTRUNCATE_H + +#include "../../common/napi/n_val.h" + +namespace OHOS { +namespace DistributedFS { +namespace ModuleFileIO { +class Ftruncate final { +public: + static napi_value Sync(napi_env env, napi_callback_info info); + static napi_value Async(napi_env env, napi_callback_info info); +}; +} // namespace ModuleFileIO +} // namespace DistributedFS +} // namespace OHOS +#endif \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fileio/properties/hash.cpp b/interfaces/kits/js/src/mod_fileio/properties/hash.cpp new file mode 100644 index 000000000..8497c2694 --- /dev/null +++ b/interfaces/kits/js/src/mod_fileio/properties/hash.cpp @@ -0,0 +1,131 @@ +/* + * 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. + */ + +#include "hash.h" + +#include +#include + +#include "../../common/file_helper/hash_file.h" + +namespace OHOS { +namespace DistributedFS { +namespace ModuleFileIO { +using namespace std; + +enum HASH_ALGORITHM_TYPE { + HASH_ALGORITHM_TYPE_MD5, + HASH_ALGORITHM_TYPE_SHA1, + HASH_ALGORITHM_TYPE_SHA256, + HASH_ALGORITHM_TYPE_UNSUPPORTED, +}; + +static HASH_ALGORITHM_TYPE GetHashAlgorithm(const unique_ptr &alg, const size_t algLen) +{ + if (algLen == ((sizeof("md5") - 1)) && !strncmp(alg.get(), "md5", algLen)) { + return HASH_ALGORITHM_TYPE_MD5; + } else if (algLen == ((sizeof("sha1") - 1)) && !strncmp(alg.get(), "sha1", algLen)) { + return HASH_ALGORITHM_TYPE_SHA1; + } else if (algLen == ((sizeof("sha256") - 1)) && !strncmp(alg.get(), "sha256", algLen)) { + return HASH_ALGORITHM_TYPE_SHA256; + } else { + return HASH_ALGORITHM_TYPE_UNSUPPORTED; + } +} + +static tuple, HASH_ALGORITHM_TYPE, bool> GetHashArgs(napi_env env, const NFuncArg &funcArg) +{ + bool isPromise = false; + 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 }; + } + + 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 }; + } + + HASH_ALGORITHM_TYPE algType = GetHashAlgorithm(alg, algLen); + if (algType == HASH_ALGORITHM_TYPE_UNSUPPORTED) { + UniError(EINVAL).ThrowErr(env, "Invalid algorithm"); + return { false, nullptr, HASH_ALGORITHM_TYPE_UNSUPPORTED, isPromise }; + } + + if (funcArg.GetArgc() == NARG_CNT::THREE && !NVal(env, funcArg[NARG_POS::SECOND]).TypeIs(napi_function)) { + UniError(EINVAL).ThrowErr(env, "Invalid callback"); + return { false, nullptr, HASH_ALGORITHM_TYPE_UNSUPPORTED, isPromise }; + } + + isPromise = funcArg.GetArgc() == NARG_CNT::TWO; + return { true, move(path), algType, isPromise }; +} + +napi_value Hash::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; + } + + 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](napi_env env) -> UniError { + int ret = EIO; + string &res = *arg; + if (algType == HASH_ALGORITHM_TYPE_MD5) { + tie(ret, res) = HashFile::HashWithMD5(fpath); + } else if (algType == HASH_ALGORITHM_TYPE_SHA1) { + tie(ret, res) = HashFile::HashWithSHA1(fpath); + } else if (algType == HASH_ALGORITHM_TYPE_SHA256) { + tie(ret, res) = HashFile::HashWithSHA256(fpath); + } + return UniError(ret); + }; + + auto cbComplete = [arg](napi_env env, UniError err) -> NVal { + if (err) { + return { NVal(env, err.GetNapiErr(env)) }; + } + + return { NVal::CreateUTF8String(env, *arg) }; + }; + string procedureName = "FileIOHash"; + NVal thisVar(env, funcArg.GetThisVar()); + if (isPromise) { + 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_; + } +} +} // namespace ModuleFileIO +} // namespace DistributedFS +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fileio/properties/hash.h b/interfaces/kits/js/src/mod_fileio/properties/hash.h new file mode 100644 index 000000000..8aca34ce1 --- /dev/null +++ b/interfaces/kits/js/src/mod_fileio/properties/hash.h @@ -0,0 +1,34 @@ +/* + * 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. + */ + +#ifndef INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_HASH_H +#define INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_HASH_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_func_arg.h" + +namespace OHOS { +namespace DistributedFS { +namespace ModuleFileIO { +class Hash final { +public: + static napi_value Async(napi_env env, napi_callback_info info); +}; +} // namespace ModuleFileIO +} // namespace DistributedFS +} // namespace OHOS +#endif \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fileio/properties/lchown.cpp b/interfaces/kits/js/src/mod_fileio/properties/lchown.cpp new file mode 100644 index 000000000..61ed53d35 --- /dev/null +++ b/interfaces/kits/js/src/mod_fileio/properties/lchown.cpp @@ -0,0 +1,125 @@ +/* + * 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. + */ + +#include "lchown.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_func_arg.h" +namespace OHOS { +namespace DistributedFS { +namespace ModuleFileIO { +using namespace std; + +static tuple GetLchownArg(napi_env env, const NFuncArg &funcArg) +{ + 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 }; + } + + int owner; + tie(succ, owner) = NVal(env, funcArg[NARG_POS::SECOND]).ToInt32(); + if (!succ) { + UniError(EINVAL).ThrowErr(env, "Invalid owner"); + return { false, "", -1, -1 }; + } + + 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 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; + } + + bool succ = false; + int owner; + int group; + string path; + tie(succ, path, owner, group) = GetLchownArg(env, funcArg); + if (!succ) { + return nullptr; + } + + if (lchown(path.c_str(), owner, group) == -1) { + UniError(errno).ThrowErr(env); + return nullptr; + } + + return NVal::CreateUndefined(env).val_; +} + +napi_value Lchown::Async(napi_env env, napi_callback_info info) +{ + NFuncArg funcArg(env, info); + if (!funcArg.InitArgs(NARG_CNT::THREE, NARG_CNT::FOUR)) { + UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); + return nullptr; + } + + bool succ = false; + int owner; + int group; + string path; + tie(succ, path, owner, group) = GetLchownArg(env, funcArg); + if (!succ) { + return nullptr; + } + + auto cbExec = [path, owner, group](napi_env env) -> UniError { + if (lchown(path.c_str(), owner, group) == -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) }; + }; + + string procedureName = "FileIOLchown"; + NVal thisVar(env, funcArg.GetThisVar()); + if (funcArg.GetArgc() == NARG_CNT::THREE) { + return NAsyncWorkPromise(env, thisVar).Schedule(procedureName, cbExec, cbCompl).val_; + } else { + NVal cb(env, funcArg[NARG_POS::FOURTH]); + return NAsyncWorkCallback(env, thisVar, cb).Schedule(procedureName, cbExec, cbCompl).val_; + } +} +} // namespace ModuleFileIO +} // namespace DistributedFS +} // namespace OHOS diff --git a/interfaces/kits/js/src/mod_fileio/properties/lchown.h b/interfaces/kits/js/src/mod_fileio/properties/lchown.h new file mode 100644 index 000000000..c13ad0967 --- /dev/null +++ b/interfaces/kits/js/src/mod_fileio/properties/lchown.h @@ -0,0 +1,32 @@ +/* + * 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. + */ + +#ifndef INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_LCHOWN_H +#define INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_LCHOWN_H + +#include "../../common/napi/n_val.h" + +namespace OHOS { +namespace DistributedFS { +namespace ModuleFileIO { +class Lchown final { +public: + static napi_value Sync(napi_env env, napi_callback_info info); + static napi_value Async(napi_env env, napi_callback_info info); +}; +} // namespace ModuleFileIO +} // namespace DistributedFS +} // namespace OHOS +#endif \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fileio/properties/link.cpp b/interfaces/kits/js/src/mod_fileio/properties/link.cpp new file mode 100644 index 000000000..8b2cacd8e --- /dev/null +++ b/interfaces/kits/js/src/mod_fileio/properties/link.cpp @@ -0,0 +1,117 @@ +/* + * 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. + */ +#include "link.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 { +using namespace std; + +static tuple GetLinkArg(napi_env env, const NFuncArg &funcArg) +{ + 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, "", "" }; + } + + 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() }; +} + +napi_value Link::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; + } + + 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; + } + + bool succ = false; + string oldPath; + string newPath; + tie(succ, oldPath, newPath) = GetLinkArg(env, funcArg); + if (!succ) { + return nullptr; + } + + auto cbExec = [oldPath = move(oldPath), newPath = move(newPath)](napi_env env) -> UniError { + int ret = link(oldPath.c_str(), newPath.c_str()); + if (ret == -1) { + return UniError(errno); + } else { + return UniError(ERRNO_NOERR); + } + }; + + auto cbComplCallback = [](napi_env env, UniError err) -> NVal { + if (err) { + return { env, err.GetNapiErr(env) }; + } + return { NVal::CreateUndefined(env) }; + }; + + string procedureName = "FileIOLink"; + 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 { + NVal cb(env, funcArg[NARG_POS::THIRD]); + return NAsyncWorkCallback(env, thisVar, cb).Schedule(procedureName, cbExec, cbComplCallback).val_; + } +} +} // namespace ModuleFileIO +} // namespace DistributedFS +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fileio/properties/link.h b/interfaces/kits/js/src/mod_fileio/properties/link.h new file mode 100644 index 000000000..f287a24e7 --- /dev/null +++ b/interfaces/kits/js/src/mod_fileio/properties/link.h @@ -0,0 +1,32 @@ +/* + * 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. + */ + +#ifndef INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_LINK_H +#define INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_LINK_H + +#include "../../common/napi/n_val.h" + +namespace OHOS { +namespace DistributedFS { +namespace ModuleFileIO { +class Link final { +public: + static napi_value Sync(napi_env env, napi_callback_info info); + static napi_value Async(napi_env env, napi_callback_info info); +}; +} // namespace ModuleFileIO +} // namespace DistributedFS +} // namespace OHOS +#endif \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fileio/properties/lseek.cpp b/interfaces/kits/js/src/mod_fileio/properties/lseek.cpp new file mode 100644 index 000000000..6081a68ec --- /dev/null +++ b/interfaces/kits/js/src/mod_fileio/properties/lseek.cpp @@ -0,0 +1,128 @@ +/* + * 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. + */ +#include "lseek.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_func_arg.h" +namespace OHOS { +namespace DistributedFS { +namespace ModuleFileIO { +using namespace std; + +static tuple GetLseekArg(napi_env env, const NFuncArg &funcArg) +{ + 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 }; + } + + 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 }; + } + + 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 { succ, fd, offset, whence }; +} + +napi_value Lseek::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; + } + + bool succ = false; + int fd; + int offset; + int whence; + tie(succ, fd, offset, whence) = GetLseekArg(env, funcArg); + if (!succ) { + return nullptr; + } + + int ret = lseek(fd, offset, whence); + if (ret == -1) { + UniError(errno).ThrowErr(env); + return nullptr; + } + + return NVal::CreateInt64(env, ret).val_; +} + +napi_value Lseek::Async(napi_env env, napi_callback_info info) +{ + NFuncArg funcArg(env, info); + if (!funcArg.InitArgs(NARG_CNT::THREE, NARG_CNT::FOUR)) { + UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); + return nullptr; + } + + 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, offset, whence, arg](napi_env env) -> UniError { + int ret = lseek(fd, offset, whence); + *arg = ret; + if (ret == -1) { + return UniError(errno); + } else { + return UniError(ERRNO_NOERR); + } + }; + + auto cbComplCallback = [arg](napi_env env, UniError err) -> NVal { + if (err) { + return { env, err.GetNapiErr(env) }; + } + return { NVal::CreateInt64(env, *arg) }; + }; + + string procedureName = "FileIOLseek"; + NVal thisVar(env, funcArg.GetThisVar()); + if (argc == NARG_CNT::THREE) { + return NAsyncWorkPromise(env, thisVar).Schedule(procedureName, cbExec, cbComplCallback).val_; + } else { + NVal cb(env, funcArg[NARG_POS::FOURTH]); + return NAsyncWorkCallback(env, thisVar, cb).Schedule(procedureName, cbExec, cbComplCallback).val_; + } +} +} // namespace ModuleFileIO +} // namespace DistributedFS +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fileio/properties/lseek.h b/interfaces/kits/js/src/mod_fileio/properties/lseek.h new file mode 100644 index 000000000..b8ffb861c --- /dev/null +++ b/interfaces/kits/js/src/mod_fileio/properties/lseek.h @@ -0,0 +1,32 @@ +/* + * 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. + */ + +#ifndef INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_LSEEK_H +#define INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_LSEEK_H + +#include "../../common/napi/n_val.h" + +namespace OHOS { +namespace DistributedFS { +namespace ModuleFileIO { +class Lseek final { +public: + static napi_value Sync(napi_env env, napi_callback_info info); + static napi_value Async(napi_env env, napi_callback_info info); +}; +} // namespace ModuleFileIO +} // namespace DistributedFS +} // namespace OHOS +#endif \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fileio/properties/lstat.cpp b/interfaces/kits/js/src/mod_fileio/properties/lstat.cpp new file mode 100644 index 000000000..b74502ad6 --- /dev/null +++ b/interfaces/kits/js/src/mod_fileio/properties/lstat.cpp @@ -0,0 +1,127 @@ +/* + * 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. + */ +#include "lstat.h" + +#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 "../class_stat/stat_entity.h" +#include "../class_stat/stat_n_exporter.h" + +namespace OHOS { +namespace DistributedFS { +namespace ModuleFileIO { +using namespace std; + +napi_value Lstat::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; + } + + 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; + } + + struct stat buf; + int ret = lstat(pathPtr.get(), &buf); + if (ret == -1) { + UniError(errno).ThrowErr(env); + return nullptr; + } + + napi_value objStat = NClass::InstantiateClass(env, StatNExporter::className_, {}); + if (!objStat) { + return nullptr; + } + + auto statEntity = NClass::GetEntityOf(env, objStat); + if (!statEntity) { + return nullptr; + } + + statEntity->stat_ = buf; + return objStat; +} + +struct AsyncStatArg { + struct stat stat_; +}; + +napi_value Lstat::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; + 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(); + + auto arg = make_shared(); + auto cbExec = [arg, path](napi_env env) -> UniError { + if (lstat(path.c_str(), &arg->stat_)) { + return UniError(errno); + } else { + 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()); + string procedureName = "fileIOLstat"; + 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_; + } +} +} // namespace ModuleFileIO +} // namespace DistributedFS +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fileio/properties/lstat.h b/interfaces/kits/js/src/mod_fileio/properties/lstat.h new file mode 100644 index 000000000..6bd24beff --- /dev/null +++ b/interfaces/kits/js/src/mod_fileio/properties/lstat.h @@ -0,0 +1,32 @@ +/* + * 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. + */ + +#ifndef INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_LSTAT_H +#define INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_LSTAT_H + +#include "../../common/napi/uni_header.h" + +namespace OHOS { +namespace DistributedFS { +namespace ModuleFileIO { +class Lstat final { +public: + static napi_value Async(napi_env env, napi_callback_info info); + static napi_value Sync(napi_env env, napi_callback_info info); +}; +} // namespace ModuleFileIO +} // namespace DistributedFS +} // namespace OHOS +#endif \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fileio/properties/mkdtemp.cpp b/interfaces/kits/js/src/mod_fileio/properties/mkdtemp.cpp new file mode 100644 index 000000000..fa914602d --- /dev/null +++ b/interfaces/kits/js/src/mod_fileio/properties/mkdtemp.cpp @@ -0,0 +1,92 @@ +/* + * 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. + */ + +#include "mkdtemp.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 { +using namespace std; +napi_value Mkdtemp::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; + } + + 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(); + if (mkdtemp(const_cast(path.c_str())) == nullptr) { + UniError(errno).ThrowErr(env); + return nullptr; + } + return NVal::CreateUTF8String(env, path).val_; +} + +napi_value Mkdtemp::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; + } + 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(); + auto arg = make_shared(); + auto cbExec = [path, arg](napi_env env) -> UniError { + if (mkdtemp(const_cast(path.c_str())) == nullptr) { + return UniError(errno); + } else { + *arg = path; + return UniError(ERRNO_NOERR); + } + }; + auto cbComplete = [arg](napi_env env, UniError err) -> NVal { + if (err) { + return { env, err.GetNapiErr(env) }; + } else { + return NVal::CreateUTF8String(env, *arg); + } + }; + string procedureName = "FileIOmkdtemp"; + size_t argc = funcArg.GetArgc(); + NVal thisVar(env, funcArg.GetThisVar()); + if (argc == NARG_CNT::ONE) { + return NAsyncWorkPromise(env, thisVar).Schedule(procedureName, cbExec, cbComplete).val_; + } else { + NVal cb(env, funcArg[NARG_POS::SECOND]); + return NAsyncWorkCallback(env, thisVar, cb).Schedule(procedureName, cbExec, cbComplete).val_; + } +} +} // namespace ModuleFileIO +} // namespace DistributedFS +} // namespace OHOS diff --git a/interfaces/kits/js/src/mod_fileio/properties/mkdtemp.h b/interfaces/kits/js/src/mod_fileio/properties/mkdtemp.h new file mode 100644 index 000000000..de9a7aed1 --- /dev/null +++ b/interfaces/kits/js/src/mod_fileio/properties/mkdtemp.h @@ -0,0 +1,32 @@ +/* + * 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. + */ + +#ifndef INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_MKDTEMP_H +#define INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_MKDTEMP_H + +#include "../../common/napi/n_val.h" + +namespace OHOS { +namespace DistributedFS { +namespace ModuleFileIO { +class Mkdtemp final { +public: + static napi_value Sync(napi_env env, napi_callback_info info); + static napi_value Async(napi_env env, napi_callback_info info); +}; +} // namespace ModuleFileIO +} // namespace DistributedFS +} // namespace OHOS +#endif \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fileio/properties/open.cpp b/interfaces/kits/js/src/mod_fileio/properties/open.cpp new file mode 100644 index 000000000..673fa1d91 --- /dev/null +++ b/interfaces/kits/js/src/mod_fileio/properties/open.cpp @@ -0,0 +1,148 @@ +/* + * 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. + */ + +#include "open.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 { +using namespace std; + +napi_value Open::Sync(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; + } + + 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) { + tie(succ, flags) = NVal(env, funcArg[NARG_POS::SECOND]).ToInt32(); + if (!succ) { + UniError(EINVAL).ThrowErr(env, "Invalid flags"); + return nullptr; + } + } + + int fd = -1; + size_t argc = funcArg.GetArgc(); + if (argc != NARG_CNT::THREE) { + size_t flagsFirst { flags }; + if ((flagsFirst & O_CREAT) || (flagsFirst & O_TMPFILE)) { + UniError(EINVAL).ThrowErr(env, "called with O_CREAT/O_TMPFILE but no mode"); + return nullptr; + } + fd = open(path.get(), flags); + } else { + int mode; + tie(succ, mode) = NVal(env, funcArg.GetArg(NARG_POS::THIRD)).ToInt32(); + if (!succ) { + UniError(EINVAL).ThrowErr(env, "Invalid mode"); + return nullptr; + } + fd = open(path.get(), flags, mode); + } + + if (fd == -1) { + UniError(errno).ThrowErr(env); + return nullptr; + } + + return NVal::CreateInt64(env, fd).val_; +} + +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) { + return UniError(errno); + } else { + return UniError(ERRNO_NOERR); + } +} + +napi_value Open::Async(napi_env env, napi_callback_info info) +{ + NFuncArg funcArg(env, info); + if (!funcArg.InitArgs(NARG_CNT::ONE, NARG_CNT::FOUR)) { + UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); + return nullptr; + } + bool succ = false; + size_t argc = funcArg.GetArgc(); + 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 && !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; + } + } + int mode = 0; + if (argc == NARG_CNT::FOUR || + (argc == NARG_CNT::THREE && NVal(env, funcArg[NARG_POS::THIRD]).TypeIs(napi_number))) { + tie(succ, mode) = NVal(env, funcArg[NARG_POS::THIRD]).ToInt32(); + if (!succ) { + UniError(EINVAL).ThrowErr(env, "Invalid mode"); + return nullptr; + } + } + auto arg = make_shared(); + 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) { + return { env, err.GetNapiErr(env) }; + } + return { NVal::CreateInt64(env, *arg) }; + }; + NVal thisVar(env, funcArg.GetThisVar()); + if (argc == NARG_CNT::ONE || (argc == NARG_CNT::TWO && NVal(env, funcArg[NARG_POS::SECOND]).TypeIs(napi_number)) || + (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]); + return NAsyncWorkCallback(env, thisVar, cb).Schedule("FileIOOpen", cbExec, cbComplCallback).val_; + } +} +} // namespace ModuleFileIO +} // namespace DistributedFS +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fileio/properties/open.h b/interfaces/kits/js/src/mod_fileio/properties/open.h new file mode 100644 index 000000000..f6b6d718c --- /dev/null +++ b/interfaces/kits/js/src/mod_fileio/properties/open.h @@ -0,0 +1,32 @@ +/* + * 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. + */ + +#ifndef INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_OPEN_H +#define INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_OPEN_H + +#include "../../common/napi/n_val.h" + +namespace OHOS { +namespace DistributedFS { +namespace ModuleFileIO { +class Open final { +public: + static napi_value Sync(napi_env env, napi_callback_info info); + static napi_value Async(napi_env env, napi_callback_info info); +}; +} // namespace ModuleFileIO +} // namespace DistributedFS +} // namespace OHOS +#endif \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fileio/properties/open_dir.cpp b/interfaces/kits/js/src/mod_fileio/properties/open_dir.cpp new file mode 100644 index 000000000..8dedf7221 --- /dev/null +++ b/interfaces/kits/js/src/mod_fileio/properties/open_dir.cpp @@ -0,0 +1,137 @@ +/* + * 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. + */ + +#include "open_dir.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 "../class_dir/dir_entity.h" +#include "../class_dir/dir_n_exporter.h" + +namespace OHOS { +namespace DistributedFS { +namespace ModuleFileIO { +using namespace std; + +napi_value OpenDir::Sync(napi_env env, napi_callback_info info) +{ + NFuncArg funcArg(env, info); + if (!funcArg.InitArgs(NARG_CNT::ONE)) { + return nullptr; + } + + 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) { + UniError(errno).ThrowErr(env); + return nullptr; + } + + napi_value objDir = NClass::InstantiateClass(env, DirNExporter::className_, {}); + if (!objDir) { + UniError(EINVAL).ThrowErr(env, "Cannot instantiate class DirSync"); + return nullptr; + } + + auto dirEntity = NClass::GetEntityOf(env, objDir); + if (!dirEntity) { + UniError(EINVAL).ThrowErr(env, "Cannot get the entity of objDir"); + return nullptr; + } + dirEntity->dir_.swap(dir); + return objDir; +} + +struct OpenDirArgs { + NRef dirPtr_; + DIR *dir = nullptr; + explicit OpenDirArgs(NVal dirPtr) : dirPtr_(dirPtr) {} + ~OpenDirArgs() = default; +}; + +napi_value OpenDir::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; + 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(); + auto arg = make_shared(NVal(env, funcArg.GetThisVar())); + auto cbExec = [arg, path](napi_env env) -> UniError { + DIR *dir = nullptr; + dir = opendir(path.c_str()); + if (dir == nullptr) { + return UniError(errno); + } + arg->dir = dir; + return UniError(ERRNO_NOERR); + }; + auto cbCompl = [arg](napi_env env, UniError err) -> NVal { + if (err) { + return { env, err.GetNapiErr(env) }; + } + std::unique_ptr> dir = { arg->dir, closedir }; + if (!dir) { + return { env, UniError(errno).GetNapiErr(env) }; + } + + napi_value objDir = NClass::InstantiateClass(env, DirNExporter::className_, {}); + if (!objDir) { + return { env, UniError(EINVAL).GetNapiErr(env) }; + } + + auto dirEntity = NClass::GetEntityOf(env, objDir); + if (!dirEntity) { + return { env, UniError(EINVAL).GetNapiErr(env) }; + } + dirEntity->dir_.swap(dir); + return { env, objDir }; + }; + + NVal thisVar(env, funcArg.GetThisVar()); + if (funcArg.GetArgc() == NARG_CNT::ONE) { + return NAsyncWorkPromise(env, thisVar).Schedule("fileIOOpenDir", cbExec, cbCompl).val_; + } else { + NVal cb(env, funcArg[NARG_POS::SECOND]); + return NAsyncWorkCallback(env, thisVar, cb).Schedule("fileIOOpenDir", 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/open_dir.h b/interfaces/kits/js/src/mod_fileio/properties/open_dir.h new file mode 100644 index 000000000..e2e07d3b0 --- /dev/null +++ b/interfaces/kits/js/src/mod_fileio/properties/open_dir.h @@ -0,0 +1,32 @@ +/* + * 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. + */ + +#ifndef INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_OPEN_DIR_H +#define INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_OPEN_DIR_H + +#include "../../common/napi/uni_header.h" + +namespace OHOS { +namespace DistributedFS { +namespace ModuleFileIO { +class OpenDir final { +public: + static napi_value Async(napi_env env, napi_callback_info info); + static napi_value Sync(napi_env env, napi_callback_info info); +}; +} // namespace ModuleFileIO +} // namespace DistributedFS +} // namespace OHOS +#endif \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fileio/properties/posix_fallocate.cpp b/interfaces/kits/js/src/mod_fileio/properties/posix_fallocate.cpp new file mode 100644 index 000000000..84a86dcc6 --- /dev/null +++ b/interfaces/kits/js/src/mod_fileio/properties/posix_fallocate.cpp @@ -0,0 +1,118 @@ +/* + * 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. + */ +#include "posix_fallocate.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 { +using namespace std; + +static tuple GetPosixFallocateArg(napi_env env, const NFuncArg &funcArg) +{ + 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 }; + } + 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 }; + } + 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 { succ, fd, offset, len }; +} + +napi_value PosixFallocate::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; + } + 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_; +} + +napi_value PosixFallocate::Async(napi_env env, napi_callback_info info) +{ + NFuncArg funcArg(env, info); + if (!funcArg.InitArgs(NARG_CNT::THREE, NARG_CNT::FOUR)) { + UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); + return nullptr; + } + bool succ = false; + int fd; + int offset; + int len; + tie(succ, fd, offset, len) = GetPosixFallocateArg(env, funcArg); + if (!succ) { + return nullptr; + } + 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()); + string procedureName = "fileioPosixFallocate"; + size_t argc = funcArg.GetArgc(); + if (argc == NARG_CNT::THREE) { + return NAsyncWorkPromise(env, thisVar).Schedule(procedureName, cbExec, cbCompl).val_; + } else { + NVal cb(env, funcArg[NARG_POS::FOURTH]); + return NAsyncWorkCallback(env, thisVar, cb).Schedule(procedureName, cbExec, cbCompl).val_; + } + return NVal::CreateUndefined(env).val_; +} +} // namespace ModuleFileIO +} // namespace DistributedFS +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fileio/properties/posix_fallocate.h b/interfaces/kits/js/src/mod_fileio/properties/posix_fallocate.h new file mode 100644 index 000000000..c26c70465 --- /dev/null +++ b/interfaces/kits/js/src/mod_fileio/properties/posix_fallocate.h @@ -0,0 +1,32 @@ +/* + * 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. + */ + +#ifndef INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_POSIX_FALLOCATE_H +#define INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_POSIX_FALLOCATE_H + +#include "../../common/napi/n_val.h" + +namespace OHOS { +namespace DistributedFS { +namespace ModuleFileIO { +class PosixFallocate final { +public: + static napi_value Async(napi_env env, napi_callback_info info); + static napi_value Sync(napi_env env, napi_callback_info info); +}; +} // namespace ModuleFileIO +} // namespace DistributedFS +} // namespace OHOS +#endif \ No newline at end of file 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 new file mode 100644 index 000000000..8e4d0e6fe --- /dev/null +++ b/interfaces/kits/js/src/mod_fileio/properties/prop_n_exporter.cpp @@ -0,0 +1,758 @@ +/* + * 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. + */ + +#include "prop_n_exporter.h" + +#include +#include +#include +#include +#include + +#include "../common_func.h" +#include "chmod.h" +#include "chown.h" +#include "close.h" +#include "copy_file.h" +#include "create_stream.h" +#include "fchmod.h" +#include "fchown.h" +#include "fdatasync.h" +#include "fdopen_stream.h" +#include "fstat.h" +#include "fsync.h" +#include "ftruncate.h" +#include "hash.h" +#include "lchown.h" +#include "link.h" +#include "lseek.h" +#include "lstat.h" +#include "mkdtemp.h" +#include "open.h" +#include "open_dir.h" +#include "posix_fallocate.h" +#include "read_text.h" +#include "rename.h" +#include "rmdir.h" +#include "stat.h" +#include "symlink.h" +#include "truncate.h" +#include "watcher.h" + +namespace OHOS { +namespace DistributedFS { +namespace ModuleFileIO { +using namespace std; + +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; + } + + 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; + } + + size_t argc = funcArg.GetArgc(); + int ret = -1; + if (argc == NARG_CNT::ONE) { + ret = access(path.get(), 0); + } else { + 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; + } + + return NVal::CreateUndefined(env).val_; +} + +static tuple GetAccessArgs(napi_env env, const NFuncArg &funcArg) +{ + 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 }; + } + + size_t argc = funcArg.GetArgc(); + bool promise = true; + bool hasMode = false; + if (argc == NARG_CNT::ONE) { + hasMode = false; + promise = true; + } else if (argc == NARG_CNT::TWO) { + if (NVal(env, funcArg[NARG_POS::SECOND]).TypeIs(napi_function)) { + hasMode = false; + promise = false; + } else { + hasMode = true; + promise = true; + } + } else { + hasMode = true; + promise = false; + } + + int mode = 0; + if (hasMode) { + tie(succ, mode) = NVal(env, funcArg[NARG_POS::SECOND]).ToInt32(); + if (!succ) { + UniError(EINVAL).ThrowErr(env, "Invalid mode"); + return { false, nullptr, 0, false }; + } + } + + return { true, path.get(), mode, promise }; +} + +struct AsyncAccessArg { + unique_ptr fp = nullptr; +}; + +napi_value PropNExporter::Access(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; + } + + 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); + if (ret == -1) { + return UniError(errno); + } else { + return UniError(ERRNO_NOERR); + } + }; + + auto cbComplete = [](napi_env env, UniError err) -> NVal { + if (err) { + return { env, err.GetNapiErr(env) }; + } else { + return NVal::CreateUndefined(env); + } + }; + string procedureName = "FileIOAccess"; + NVal thisVar(env, funcArg.GetThisVar()); + if (promise) { + return NAsyncWorkPromise(env, thisVar).Schedule(procedureName, cbExec, cbComplete).val_; + } else { + 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; + } + + 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(); + + auto cbExec = [path](napi_env env) -> UniError { + if (unlink(path.c_str()) == -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()); + 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_; +} + +napi_value PropNExporter::Mkdir(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; + } + + 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(); + 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) { + tie(succ, mode) = NVal(env, funcArg[NARG_POS::SECOND]).ToInt32(); + if (!succ) { + UniError(EINVAL).ThrowErr(env, "Invalid mode"); + return nullptr; + } + } + auto cbExec = [path, mode](napi_env env) -> UniError { + if (mkdir(path.c_str(), mode) == -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()); + 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 { + int cbIdx = ((argc == NARG_CNT::TWO) ? NARG_POS::SECOND : NARG_POS::THIRD); + 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; + } + + 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 ret = -1; + size_t argc = funcArg.GetArgc(); + if (argc == NARG_CNT::ONE) { + ret = mkdir(path.get(), 0775); + } else { + int mode; + tie(succ, mode) = NVal(env, funcArg[NARG_POS::SECOND]).ToInt32(); + if (!succ) { + UniError(EINVAL).ThrowErr(env, "Invalid mode"); + return nullptr; + } + ret = mkdir(path.get(), mode); + } + + if (ret == -1) { + HILOGE("errno = %{public}d", errno); + UniError(errno).ThrowErr(env); + return nullptr; + } + + return NVal::CreateUndefined(env).val_; +} + +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; + } + + 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; + } + + int mode; + tie(succ, mode) = NVal(env, funcArg[NARG_POS::SECOND]).ToInt32(); + if (!succ) { + UniError(EINVAL).ThrowErr(env, "Invalid mode"); + return nullptr; + } + + int ret = fchmod(fd, mode); + if (ret == -1) { + UniError(errno).ThrowErr(env); + return nullptr; + } + + return NVal::CreateUndefined(env).val_; +} + +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; + } + + 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; + } + + int owner; + tie(succ, owner) = NVal(env, funcArg[NARG_POS::SECOND]).ToInt32(); + if (!succ) { + UniError(EINVAL).ThrowErr(env, "Invalid owner"); + } + + int group; + tie(succ, group) = NVal(env, funcArg[NARG_POS::THIRD]).ToInt32(); + if (!succ) { + UniError(EINVAL).ThrowErr(env, "Invalid group"); + } + + int ret = fchown(fd, owner, group); + if (ret == -1) { + UniError(errno).ThrowErr(env); + return nullptr; + } + + return NVal::CreateUndefined(env).val_; +} + +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; + } + + 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; + } + + 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 (!succ) { + return nullptr; + } + + ssize_t actLen; + if (hasPos) { + actLen = pread(fd, buf, len, pos); + } else { + actLen = read(fd, buf, len); + } + if (actLen == -1) { + UniError(errno).ThrowErr(env); + return nullptr; + } + + 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 PropNExporter::Read(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; + } + + 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; + } + + tie(succ, buf, len, hasPos, pos, offset) = + CommonFunc::GetReadArg(env, funcArg[NARG_POS::SECOND], funcArg[NARG_POS::THIRD]); + if (!succ) { + UniError(EINVAL).ThrowErr(env, "Failed GetReadArg"); + return nullptr; + } + + auto arg = make_shared(NVal(env, funcArg[NARG_POS::SECOND])); + auto cbExec = [arg, buf, len, fd, hasPos, pos, offset](napi_env env) -> UniError { + ssize_t actLen; + if (hasPos) { + actLen = pread(fd, buf, len, pos); + } else { + actLen = read(fd, buf, len); + } + if (actLen == -1) { + return UniError(errno); + } else { + arg->lenRead = actLen; + arg->offset = offset; + 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()); + size_t argc = funcArg.GetArgc(); + bool hasOp = false; + if (argc == NARG_CNT::THREE) { + NVal op = NVal(env, funcArg[NARG_POS::THIRD]); + if (op.HasProp("offset") || op.HasProp("position") || op.HasProp("length")) { + hasOp = true; + } + } + if (argc == NARG_CNT::TWO || (argc == NARG_CNT::THREE && hasOp)) { + return NAsyncWorkPromise(env, thisVar).Schedule("FileIORead", cbExec, cbCompl).val_; + } else { + int cbIdx = ((argc == NARG_CNT::THREE) ? NARG_POS::THIRD : NARG_POS::FOURTH); + 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) +{ + if (position == (size_t)INVALID_POSITION) { + arg->actLen = write(fd, buf, len); + } else { + arg->actLen = pwrite(fd, buf, len, position); + } + + if (arg->actLen == -1) { + return UniError(errno); + } else { + return UniError(ERRNO_NOERR); + } +} + +napi_value PropNExporter::Write(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; + } + + 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; + } + + 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 (!succ) { + UniError(EINVAL).ThrowErr(env, "Failed GetWriteArg"); + return nullptr; + } + + shared_ptr arg; + if (bufGuard) { + arg = make_shared(move(bufGuard)); + } 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); + }; + + 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()); + bool hasOp = false; + size_t argc = funcArg.GetArgc(); + if (argc == NARG_CNT::THREE) { + NVal op = NVal(env, funcArg[NARG_POS::THIRD]); + if (op.HasProp("offset") || op.HasProp("position") || op.HasProp("length") || op.HasProp("encoding")) { + hasOp = true; + } + } + + if (argc == NARG_CNT::TWO || (argc == NARG_CNT::THREE && hasOp)) { + return NAsyncWorkPromise(env, thisVar).Schedule("FileIOWrite", cbExec, cbCompl).val_; + } else { + int cbIdx = ((argc == NARG_CNT::THREE) ? NARG_POS::THIRD : NARG_POS::FOURTH); + 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; + } + + 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; + } + + if (unlink(path.get()) == -1) { + UniError(errno).ThrowErr(env); + return nullptr; + } + + return NVal::CreateUndefined(env).val_; +} + +napi_value PropNExporter::WriteSync(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; + } + + 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; + } + + 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 (!succ) { + return nullptr; + } + + ssize_t writeLen; + if (position == (size_t)INVALID_POSITION) { + writeLen = write(fd, buf, len); + } else { + writeLen = pwrite(fd, buf, len, position); + } + + if (writeLen == -1) { + UniError(errno).ThrowErr(env); + return nullptr; + } + + return NVal::CreateInt64(env, writeLen).val_; +} + +bool PropNExporter::Export() +{ + return exports_.AddProp({ + NVal::DeclareNapiFunction("access", Access), + NVal::DeclareNapiFunction("accessSync", AccessSync), + NVal::DeclareNapiFunction("chmod", Chmod::Async), + NVal::DeclareNapiFunction("chmodSync", Chmod::Sync), + NVal::DeclareNapiFunction("chown", Chown::Async), + NVal::DeclareNapiFunction("chownSync", Chown::Sync), + NVal::DeclareNapiFunction("close", Close::Async), + NVal::DeclareNapiFunction("closeSync", Close::Sync), + NVal::DeclareNapiFunction("copyFile", CopyFile::Async), + NVal::DeclareNapiFunction("copyFileSync", CopyFile::Sync), + NVal::DeclareNapiFunction("createStream", CreateStream::Async), + NVal::DeclareNapiFunction("createStreamSync", CreateStream::Sync), + NVal::DeclareNapiFunction("createWatcher", Watcher::CreateWatcher), + NVal::DeclareNapiFunction("fchmod", Fchmod::Async), + NVal::DeclareNapiFunction("fchmodSync", Fchmod::Sync), + NVal::DeclareNapiFunction("fchown", Fchown::Async), + NVal::DeclareNapiFunction("fchownSync", Fchown::Sync), + NVal::DeclareNapiFunction("fdatasync", Fdatasync::Async), + NVal::DeclareNapiFunction("fdatasyncSync", Fdatasync::Sync), + NVal::DeclareNapiFunction("fdopenStream", FdopenStream::Async), + NVal::DeclareNapiFunction("fdopenStreamSync", FdopenStream::Sync), + NVal::DeclareNapiFunction("fstat", Fstat::Async), + NVal::DeclareNapiFunction("fstatSync", Fstat::Sync), + NVal::DeclareNapiFunction("fsync", Fsync::Async), + NVal::DeclareNapiFunction("fsyncSync", Fsync::Sync), + NVal::DeclareNapiFunction("ftruncate", Ftruncate::Async), + NVal::DeclareNapiFunction("ftruncateSync", Ftruncate::Sync), + NVal::DeclareNapiFunction("hash", Hash::Async), + NVal::DeclareNapiFunction("lchown", Lchown::Async), + NVal::DeclareNapiFunction("lchownSync", Lchown::Sync), + NVal::DeclareNapiFunction("link", Link::Async), + NVal::DeclareNapiFunction("linkSync", Link::Sync), + NVal::DeclareNapiFunction("lseek", Lseek::Async), + NVal::DeclareNapiFunction("lseekSync", Lseek::Sync), + NVal::DeclareNapiFunction("lstat", Lstat::Async), + NVal::DeclareNapiFunction("lstatSync", Lstat::Sync), + NVal::DeclareNapiFunction("mkdir", Mkdir), + NVal::DeclareNapiFunction("mkdirSync", MkdirSync), + NVal::DeclareNapiFunction("mkdtemp", Mkdtemp::Async), + NVal::DeclareNapiFunction("mkdtempSync", Mkdtemp::Sync), + NVal::DeclareNapiFunction("open", Open::Async), + NVal::DeclareNapiFunction("opendir", OpenDir::Async), + NVal::DeclareNapiFunction("opendirSync", OpenDir::Sync), + NVal::DeclareNapiFunction("openSync", Open::Sync), + NVal::DeclareNapiFunction("posixFallocate", PosixFallocate::Async), + NVal::DeclareNapiFunction("posixFallocateSync", PosixFallocate::Sync), + NVal::DeclareNapiFunction("read", Read), + NVal::DeclareNapiFunction("readSync", ReadSync), + NVal::DeclareNapiFunction("readText", ReadText::Async), + 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("stat", Stat::Async), + NVal::DeclareNapiFunction("statSync", Stat::Sync), + NVal::DeclareNapiFunction("symlink", Symlink::Async), + NVal::DeclareNapiFunction("symlinkSync", Symlink::Sync), + NVal::DeclareNapiFunction("truncate", Truncate::Async), + NVal::DeclareNapiFunction("truncateSync", Truncate::Sync), + NVal::DeclareNapiFunction("unlink", Unlink), + NVal::DeclareNapiFunction("unlinkSync", UnlinkSync), + NVal::DeclareNapiFunction("write", Write), + NVal::DeclareNapiFunction("writeSync", WriteSync), + }); +} + +string PropNExporter::GetClassName() +{ + return PropNExporter::className_; +} + +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 new file mode 100644 index 000000000..ad9f99ffe --- /dev/null +++ b/interfaces/kits/js/src/mod_fileio/properties/prop_n_exporter.h @@ -0,0 +1,66 @@ +/* + * 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. + */ + +#ifndef INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_PROP_N_EXPORTER_H +#define INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_PROP_N_EXPORTER_H + +#include "../../common/napi/n_async/n_ref.h" +#include "../../common/napi/n_exporter.h" +#include "../../common/napi/n_val.h" +#include "../../common/uni_error.h" + +namespace OHOS { +namespace DistributedFS { +namespace ModuleFileIO { +struct AsyncIOWrtieArg { + NRef refWriteArrayBuf_; + std::unique_ptr guardWriteStr_; + ssize_t actLen = 0; + + explicit AsyncIOWrtieArg(NVal refWriteArrayBuf) : refWriteArrayBuf_(refWriteArrayBuf) {} + explicit AsyncIOWrtieArg(std::unique_ptr &&guardWriteStr) : guardWriteStr_(move(guardWriteStr)) {} + ~AsyncIOWrtieArg() = default; +}; + +class PropNExporter final : public NExporter { +public: + inline static const std::string className_ = "__properities__"; + + static napi_value AccessSync(napi_env env, napi_callback_info info); + static napi_value FchmodSync(napi_env env, napi_callback_info info); + static napi_value FchownSync(napi_env env, napi_callback_info info); + static napi_value MkdirSync(napi_env env, napi_callback_info info); + static napi_value ReadSync(napi_env env, napi_callback_info info); + static napi_value RenameSync(napi_env env, napi_callback_info info); + static napi_value RmdirSync(napi_env env, napi_callback_info info); + static napi_value UnlinkSync(napi_env env, napi_callback_info info); + static napi_value FsyncSync(napi_env env, napi_callback_info info); + static napi_value WriteSync(napi_env env, napi_callback_info info); + static napi_value Access(napi_env env, napi_callback_info info); + static napi_value Unlink(napi_env env, napi_callback_info info); + static napi_value Mkdir(napi_env env, napi_callback_info info); + static napi_value Read(napi_env env, napi_callback_info info); + static napi_value Write(napi_env env, napi_callback_info info); + static UniError WriteExec(std::shared_ptr arg, void *buf, size_t len, int fd, size_t position); + bool Export() override; + std::string GetClassName() override; + + PropNExporter(napi_env env, napi_value exports); + ~PropNExporter() override; +}; +} // 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 new file mode 100644 index 000000000..6db024c83 --- /dev/null +++ b/interfaces/kits/js/src/mod_fileio/properties/read_text.cpp @@ -0,0 +1,211 @@ +/* + * 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. + */ +#include "read_text.h" + +#include +#include +#include +#include +#include +#include "../../common/file_helper/fd_guard.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" +#include "../common_func.h" + +namespace OHOS { +namespace DistributedFS { +namespace ModuleFileIO { +using namespace std; + +static tuple, bool> GetReadTextArg(napi_env env, napi_value argOption) +{ + NVal op(env, argOption); + ssize_t position = 0; + ssize_t len = 0; + bool succ = false; + bool hasOp = false; + bool hasLen = false; + unique_ptr encoding; + if (op.HasProp("position")) { + tie(succ, position) = op.GetProp("position").ToInt32(); + if (!succ) { + return { false, position, hasLen, len, nullptr, hasOp }; + } + hasOp = true; + } + if (op.HasProp("length")) { + tie(succ, len) = op.GetProp("length").ToInt32(); + if (!succ) { + return { false, position, hasLen, len, nullptr, hasOp }; + } + hasOp = true; + hasLen = true; + } + if (op.HasProp("encoding")) { + 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 }; +} + +napi_value ReadText::Sync(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; + } + 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; + } + 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; + 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); + if (readbuf == nullptr) { + 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_; +} + +UniError ReadText::AsyncExec(const std::string &path, std::shared_ptr arg, ssize_t position, + bool hasLen, ssize_t len) +{ + if (arg == nullptr) { + return UniError(ENOMEM); + } + + FDGuard sfd; + struct stat statbf; + arg->len = len; + sfd.SetFD(open(path.c_str(), O_RDONLY)); + if (sfd.GetFD() == -1) { + return UniError(EINVAL); + } + if (fstat(sfd.GetFD(), &statbf) == -1) { + return UniError(EINVAL); + } + if (position > 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); + } + + return UniError(ERRNO_NOERR); +} + +napi_value ReadText::Async(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; + } + 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; + } + 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, 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) }; + } else { + 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)) { + return NAsyncWorkPromise(env, thisVar).Schedule("FileIOReadText", cbExec, cbComplete).val_; + } else { + int cbIdx = !hasOp ? NARG_POS::SECOND : NARG_POS::THIRD; + NVal cb(env, funcArg[cbIdx]); + return NAsyncWorkCallback(env, thisVar, cb).Schedule("FileIOReadText", cbExec, cbComplete).val_; + } +} +} // namespace ModuleFileIO +} // namespace DistributedFS +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fileio/properties/read_text.h b/interfaces/kits/js/src/mod_fileio/properties/read_text.h new file mode 100644 index 000000000..882143773 --- /dev/null +++ b/interfaces/kits/js/src/mod_fileio/properties/read_text.h @@ -0,0 +1,44 @@ +/* + * 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. + */ + +#ifndef INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_READ_TEXT_H +#define INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_READ_TEXT_H + +#include "../../common/napi/n_async/n_ref.h" +#include "../../common/napi/n_val.h" +#include "../../common/uni_error.h" + +namespace OHOS { +namespace DistributedFS { +namespace ModuleFileIO { +struct AsyncReadTextArg { + NRef _refReadBuf; + std::unique_ptr buf; + ssize_t len = 0; + explicit AsyncReadTextArg(NVal refReadBuf) : _refReadBuf(refReadBuf) {}; + ~AsyncReadTextArg() = default; +}; + +class ReadText final { +public: +static UniError AsyncExec(const std::string &path, std::shared_ptr arg, ssize_t position, + bool hasLen, ssize_t len); + static napi_value Async(napi_env env, napi_callback_info info); + static napi_value Sync(napi_env env, napi_callback_info info); +}; +} // namespace ModuleFileIO +} // namespace DistributedFS +} // namespace OHOS +#endif \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fileio/properties/rename.cpp b/interfaces/kits/js/src/mod_fileio/properties/rename.cpp new file mode 100644 index 000000000..78fb5a2af --- /dev/null +++ b/interfaces/kits/js/src/mod_fileio/properties/rename.cpp @@ -0,0 +1,115 @@ +/* + * 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. + */ + +#include "rename.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_func_arg.h" + +namespace OHOS { +namespace DistributedFS { +namespace ModuleFileIO { +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; + } + + 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; + } + + unique_ptr dest; + tie(succ, dest, ignore) = NVal(env, funcArg[NARG_POS::SECOND]).ToUTF8String(); + if (!succ) { + UniError(EINVAL).ThrowErr(env, "Invalid dest"); + return nullptr; + } + + if (rename(src.get(), dest.get()) == -1) { + UniError(errno).ThrowErr(env); + return nullptr; + } + + return NVal::CreateUndefined(env).val_; +} + +napi_value Rename::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; + } + + 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; + } + + unique_ptr dest; + tie(succ, dest, ignore) = NVal(env, funcArg[NARG_POS::SECOND]).ToUTF8String(); + if (!succ) { + UniError(EINVAL).ThrowErr(env, "Invalid dest"); + return nullptr; + } + + auto cbExec = [opath = string(src.get()), npath = string(dest.get())](napi_env env) -> UniError { + int ret = rename(opath.c_str(), npath.c_str()); + if (ret == -1) { + return UniError(errno); + } else { + return UniError(ERRNO_NOERR); + } + }; + + auto cbComplCallback = [](napi_env env, UniError err) -> NVal { + if (err) { + return { env, err.GetNapiErr(env) }; + } + return { NVal::CreateUndefined(env) }; + }; + + string procedureName = "FileIORename"; + 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 { + NVal cb(env, funcArg[NARG_POS::THIRD]); + return NAsyncWorkCallback(env, thisVar, cb).Schedule(procedureName, cbExec, cbComplCallback).val_; + } +} +} // namespace ModuleFileIO +} // namespace DistributedFS +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fileio/properties/rename.h b/interfaces/kits/js/src/mod_fileio/properties/rename.h new file mode 100644 index 000000000..0333170a6 --- /dev/null +++ b/interfaces/kits/js/src/mod_fileio/properties/rename.h @@ -0,0 +1,31 @@ +/* + * 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. + */ + +#ifndef INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_RENAME_H +#define INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_RENAME_H + +#include "../../common/napi/n_val.h" +namespace OHOS { +namespace DistributedFS { +namespace ModuleFileIO { +class Rename final { +public: + static napi_value Sync(napi_env env, napi_callback_info info); + static napi_value Async(napi_env env, napi_callback_info info); +}; +} // namespace ModuleFileIO +} // namespace DistributedFS +} // namespace OHOS +#endif \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fileio/properties/rmdir.cpp b/interfaces/kits/js/src/mod_fileio/properties/rmdir.cpp new file mode 100644 index 000000000..4a9797c49 --- /dev/null +++ b/interfaces/kits/js/src/mod_fileio/properties/rmdir.cpp @@ -0,0 +1,97 @@ +/* + * 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. + */ + +#include "rmdir.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_func_arg.h" +namespace OHOS { +namespace DistributedFS { +namespace ModuleFileIO { +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; + } + + 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; + } + + if (rmdir(path.get()) == -1) { + UniError(errno).ThrowErr(env); + return nullptr; + } + + return NVal::CreateUndefined(env).val_; +} + +napi_value Rmdir::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; + } + + 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 cbExec = [path = string(path.get())](napi_env env) -> UniError { + int res = rmdir(path.c_str()); + if (res == -1) { + return UniError(errno); + } else { + return UniError(ERRNO_NOERR); + } + }; + auto cbCompl = [](napi_env env, UniError err) -> NVal { + if (err) { + return { env, err.GetNapiErr(env) }; + } else { + return NVal::CreateUndefined(env); + } + }; + string procedureName = "FileIORmdir"; + NVal thisVar(env, funcArg.GetThisVar()); + size_t argc = funcArg.GetArgc(); + if (argc == 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_; + } +} +} // namespace ModuleFileIO +} // namespace DistributedFS +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fileio/properties/rmdir.h b/interfaces/kits/js/src/mod_fileio/properties/rmdir.h new file mode 100644 index 000000000..6e6e7bffe --- /dev/null +++ b/interfaces/kits/js/src/mod_fileio/properties/rmdir.h @@ -0,0 +1,32 @@ +/* + * 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. + */ + +#ifndef INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_RMDIR_H +#define INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_RMDIR_H + +#include "../../common/napi/n_val.h" + +namespace OHOS { +namespace DistributedFS { +namespace ModuleFileIO { +class Rmdir final { +public: + static napi_value Sync(napi_env env, napi_callback_info info); + static napi_value Async(napi_env env, napi_callback_info info); +}; +} // 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 new file mode 100644 index 000000000..029acad9f --- /dev/null +++ b/interfaces/kits/js/src/mod_fileio/properties/stat.cpp @@ -0,0 +1,127 @@ +/* + * 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. + */ +#include "stat.h" + +#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 "../class_stat/stat_entity.h" +#include "../class_stat/stat_n_exporter.h" + +namespace OHOS { +namespace DistributedFS { +namespace ModuleFileIO { +using namespace std; + +napi_value Stat::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; + } + + 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; + } + + struct stat buf; + int ret = stat(pathPtr.get(), &buf); + if (ret == -1) { + UniError(errno).ThrowErr(env); + return nullptr; + } + + napi_value objStat = NClass::InstantiateClass(env, StatNExporter::className_, {}); + if (!objStat) { + return nullptr; + } + + auto statEntity = NClass::GetEntityOf(env, objStat); + if (!statEntity) { + return nullptr; + } + + statEntity->stat_ = buf; + return objStat; +} + +struct AsyncStatArg { + struct stat stat_; +}; + +napi_value Stat::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; + 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(); + + auto arg = make_shared(); + auto cbExec = [arg, path](napi_env env) -> UniError { + if (stat(path.c_str(), &arg->stat_)) { + return UniError(errno); + } else { + 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()); + string procedureName = "fileioStatStat"; + 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_; + } +} +} // namespace ModuleFileIO +} // namespace DistributedFS +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fileio/properties/stat.h b/interfaces/kits/js/src/mod_fileio/properties/stat.h new file mode 100644 index 000000000..8b16373e9 --- /dev/null +++ b/interfaces/kits/js/src/mod_fileio/properties/stat.h @@ -0,0 +1,32 @@ +/* + * 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. + */ + +#ifndef INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_STAT_H +#define INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_STAT_H + +#include "../../common/napi/uni_header.h" + +namespace OHOS { +namespace DistributedFS { +namespace ModuleFileIO { +class Stat final { +public: + static napi_value Async(napi_env env, napi_callback_info info); + static napi_value Sync(napi_env env, napi_callback_info info); +}; +} // namespace ModuleFileIO +} // namespace DistributedFS +} // namespace OHOS +#endif \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fileio/properties/symlink.cpp b/interfaces/kits/js/src/mod_fileio/properties/symlink.cpp new file mode 100644 index 000000000..20180cbdf --- /dev/null +++ b/interfaces/kits/js/src/mod_fileio/properties/symlink.cpp @@ -0,0 +1,116 @@ +/* + * 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. + */ + +#include "symlink.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 { +using namespace std; + +static tuple GetSymlinkArg(napi_env env, const NFuncArg &funcArg) +{ + 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, "", "" }; + } + + 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() }; +} + +napi_value Symlink::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; + } + + bool succ = false; + string oldPath; + string newPath; + tie(succ, oldPath, newPath) = GetSymlinkArg(env, funcArg); + if (!succ) { + return nullptr; + } + + if (symlink(oldPath.c_str(), newPath.c_str()) == -1) { + UniError(errno).ThrowErr(env); + return nullptr; + } + return NVal::CreateUndefined(env).val_; +} + +napi_value Symlink::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; + } + + bool succ = false; + string oldPath; + string newPath; + tie(succ, oldPath, newPath) = GetSymlinkArg(env, funcArg); + if (!succ) { + return nullptr; + } + + auto cbExec = [oldPath = move(oldPath), newPath = move(newPath)](napi_env env) -> UniError { + int ret = symlink(oldPath.c_str(), newPath.c_str()); + if (ret == -1) { + return UniError(errno); + } else { + return UniError(ERRNO_NOERR); + } + }; + + auto cbComplCallback = [](napi_env env, UniError err) -> NVal { + if (err) { + return { env, err.GetNapiErr(env) }; + } + return { NVal::CreateUndefined(env) }; + }; + + string procedureName = "FileIOsymLink"; + 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 { + NVal cb(env, funcArg[NARG_POS::THIRD]); + return NAsyncWorkCallback(env, thisVar, cb).Schedule(procedureName, cbExec, cbComplCallback).val_; + } +} +} // namespace ModuleFileIO +} // namespace DistributedFS +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fileio/properties/symlink.h b/interfaces/kits/js/src/mod_fileio/properties/symlink.h new file mode 100644 index 000000000..b770a27e8 --- /dev/null +++ b/interfaces/kits/js/src/mod_fileio/properties/symlink.h @@ -0,0 +1,32 @@ +/* + * 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. + */ + +#ifndef INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_SYMLINK_H +#define INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_SYMLINK_H + +#include "../../common/napi/n_val.h" + +namespace OHOS { +namespace DistributedFS { +namespace ModuleFileIO { +class Symlink final { +public: + static napi_value Async(napi_env env, napi_callback_info info); + static napi_value Sync(napi_env env, napi_callback_info info); +}; +} // namespace ModuleFileIO +} // namespace DistributedFS +} // namespace OHOS +#endif \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fileio/properties/truncate.cpp b/interfaces/kits/js/src/mod_fileio/properties/truncate.cpp new file mode 100644 index 000000000..f07084b23 --- /dev/null +++ b/interfaces/kits/js/src/mod_fileio/properties/truncate.cpp @@ -0,0 +1,113 @@ +/* + * 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. + */ + +#include "truncate.h" + +#include +#include +#include + +namespace OHOS { +namespace DistributedFS { +namespace ModuleFileIO { +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; + } + + 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 ret = -1; + if (funcArg.GetArgc() == NARG_CNT::ONE) { + ret = truncate(path.get(), 0); + } else { + 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); + } + + if (ret == -1) { + UniError(errno).ThrowErr(env); + return nullptr; + } + return NVal::CreateUndefined(env).val_; +} + +napi_value Truncate::Async(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; + } + 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; + } + size_t argc = funcArg.GetArgc(); + if (argc > NARG_CNT::ONE) { + tie(succ, len) = NVal(env, funcArg[NARG_POS::SECOND]).ToInt32(); + if (!succ) { + UniError(EINVAL).ThrowErr(env, "Invalid len"); + return nullptr; + } + } + auto cbExec = [path = string(path.get()), len](napi_env env) -> UniError { + int ret = truncate(path.c_str(), len); + if (ret == -1) { + return UniError(errno); + } else { + return UniError(ERRNO_NOERR); + } + }; + 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()); + 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 { + NVal cb(env, funcArg[NARG_POS::THIRD]); + return NAsyncWorkCallback(env, thisVar, cb).Schedule(procedureName, 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/truncate.h b/interfaces/kits/js/src/mod_fileio/properties/truncate.h new file mode 100644 index 000000000..b4f32e026 --- /dev/null +++ b/interfaces/kits/js/src/mod_fileio/properties/truncate.h @@ -0,0 +1,35 @@ +/* + * 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. + */ + +#ifndef INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_TRUNCATE_H +#define INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_TRUNCATE_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_func_arg.h" + +namespace OHOS { +namespace DistributedFS { +namespace ModuleFileIO { +class Truncate final { +public: + static napi_value Sync(napi_env env, napi_callback_info info); + static napi_value Async(napi_env env, napi_callback_info info); +}; +} // namespace ModuleFileIO +} // namespace DistributedFS +} // namespace OHOS +#endif \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fileio/properties/watcher.cpp b/interfaces/kits/js/src/mod_fileio/properties/watcher.cpp new file mode 100644 index 000000000..1b3def21c --- /dev/null +++ b/interfaces/kits/js/src/mod_fileio/properties/watcher.cpp @@ -0,0 +1,107 @@ +/* + * 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. + */ + +#include "watcher.h" + +#include +#include +#include +#include + +#include "../../common/napi/n_async/n_ref.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 "../class_watcher/watcher_entity.h" +#include "../class_watcher/watcher_n_exporter.h" +namespace OHOS { +namespace DistributedFS { +namespace ModuleFileIO { +using namespace std; + +void Watcher::RunCommand(uv_fs_event_t *handle, const char *filename, int events, int status) +{ + WatcherInforArg *information = (WatcherInforArg *)handle->data; + uint32_t eventsFirst { events }; + uint32_t eventsSecond { information->events }; + if (eventsFirst & eventsSecond) { + napi_handle_scope scope = nullptr; + napi_open_handle_scope(information->env, &scope); + napi_value callback = nullptr; + napi_get_reference_value(information->env, information->ref, &callback); + vector argv; + argv.push_back(NVal::CreateInt64(information->env, events).val_); + napi_value global = nullptr; + napi_get_global(information->env, &global); + napi_value tmp = nullptr; + napi_call_function(information->env, global, callback, argv.size(), argv.data(), &tmp); + } +} + +napi_value Watcher::CreateWatcher(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; + } + + 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; + } + 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; + } + + unique_ptr data = make_unique(); + data->events = event; + data->env = env; + NVal val = NVal(env, funcArg[NARG_POS::THIRD]); + napi_create_reference(val.env_, val.val_, 1, &(data->ref)); + uv_loop_s *loop = nullptr; + napi_get_uv_event_loop(env, &loop); + unique_ptr fsEventReq(new uv_fs_event_t); + uv_fs_event_init(loop, fsEventReq.get()); + fsEventReq->data = data.get(); + uv_fs_event_start(fsEventReq.get(), RunCommand, filename.get(), UV_FS_EVENT_RECURSIVE); + + napi_value objWatcher = NClass::InstantiateClass(env, WatcherNExporter::className_, {}); + if (!objWatcher) { + 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); + + return objWatcher; +} +} // namespace ModuleFileIO +} // namespace DistributedFS +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fileio/properties/watcher.h b/interfaces/kits/js/src/mod_fileio/properties/watcher.h new file mode 100644 index 000000000..45c100cb2 --- /dev/null +++ b/interfaces/kits/js/src/mod_fileio/properties/watcher.h @@ -0,0 +1,35 @@ +/* + * 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. + */ + +#ifndef INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_WATCHER_H +#define INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_WATCHER_H + +#include +#include "../../common/napi/n_val.h" + +namespace OHOS { +namespace DistributedFS { +namespace ModuleFileIO { +class Watcher final { +public: + static napi_value CreateWatcher(napi_env env, napi_callback_info info); + +private: + static void RunCommand(uv_fs_event_t *handle, const char *filename, int events, int status); +}; +} // namespace ModuleFileIO +} // namespace DistributedFS +} // namespace OHOS +#endif \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_securitylabel/security_label.h b/interfaces/kits/js/src/mod_securitylabel/security_label.h new file mode 100644 index 000000000..6ab5cba60 --- /dev/null +++ b/interfaces/kits/js/src/mod_securitylabel/security_label.h @@ -0,0 +1,75 @@ +/* + * 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. + */ + +#ifndef FOUNDATION_FILEMANAGEMENT_FILEAPI_INTERFACES_INNERKITS_SECURITY_LABEL_H +#define FOUNDATION_FILEMANAGEMENT_FILEAPI_INTERFACES_INNERKITS_SECURITY_LABEL_H + + +#include +#include + +#include +#include +#include + +namespace OHOS { +namespace DistributedFS { +namespace ModuleSecurityLabel { +namespace { + 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 bool SetSecurityLabel(const std::string &path, const std::string &dataLevel) + { + if (DATA_LEVEL.count(dataLevel) != 1) { + return false; + } + if (setxattr(path.c_str(), XATTR_KEY, dataLevel.c_str(), dataLevel.size(), 0) < 0) { + return false; + } + return true; + } + + static std::string GetSecurityLabel(const std::string &path) + { + auto xattrValueSize = getxattr(path.c_str(), XATTR_KEY, NULL, 0); + if (xattrValueSize == -1 || errno == ENOTSUP) { + return ""; + } + if (xattrValueSize <= 0) { + return DEFAULT_DATA_LEVEL; + } + std::unique_ptr xattrValue = std::make_unique((long)xattrValueSize + 1); + if (xattrValue == nullptr) { + return ""; + } + + xattrValueSize = getxattr(path.c_str(), XATTR_KEY, xattrValue.get(), xattrValueSize); + if (xattrValueSize == -1 || errno == ENOTSUP) { + return ""; + } + if (xattrValueSize <= 0) { + return DEFAULT_DATA_LEVEL; + } + return std::string(xattrValue.get()); + } +}; +} // namespace ModuleSecurityLabel +} // namespace FileIO +} // namespace OHOS +#endif diff --git a/interfaces/kits/js/src/mod_securitylabel/securitylabel_n_exporter.cpp b/interfaces/kits/js/src/mod_securitylabel/securitylabel_n_exporter.cpp new file mode 100644 index 000000000..49abd6f50 --- /dev/null +++ b/interfaces/kits/js/src/mod_securitylabel/securitylabel_n_exporter.cpp @@ -0,0 +1,187 @@ +/* + * 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. + */ + +#include "securitylabel_n_exporter.h" + +#include + +#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 "n_async_work_callback.h" +#include "n_async_work_promise.h" +#include "security_label.h" + + +#include + + +namespace OHOS { +namespace DistributedFS { +namespace ModuleSecurityLabel { +using namespace std; + +napi_value SetSecurityLabel(napi_env env, napi_callback_info info) +{ + NFuncArg funcArg(env, info); + if (!funcArg.InitArgs(static_cast(NARG_CNT::TWO), static_cast(NARG_CNT::THREE))) { + UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); + return nullptr; + } + + bool succ = false; + std::unique_ptr path; + std::unique_ptr dataLevel; + tie(succ, path, std::ignore) = NVal(env, funcArg[static_cast(NARG_POS::FIRST)]).ToUTF8String(); + if (!succ) { + 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; + } + std::string pathString(path.get()); + std::string dataLevelString(dataLevel.get()); + if (DATA_LEVEL.find(dataLevelString) == DATA_LEVEL.end()) { + UniError(EINVAL).ThrowErr(env, "Invalid Argument of dataLevelEnum"); + return nullptr; + } + auto cbExec = [pathString, dataLevelString](napi_env env) -> UniError { + bool ret = SecurityLabel::SetSecurityLabel(pathString, dataLevelString); + if (!ret) { + return UniError(-1); + } else { + return UniError(ERRNO_NOERR); + } + }; + auto cbComplete = [](napi_env env, UniError err) -> NVal { + if (err) { + return { env, err.GetNapiErr(env) }; + } else { + return NVal::CreateUndefined(env); + } + }; + 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_; + } else { + NVal cb(env, funcArg[static_cast(NARG_POS::THIRD)]); + if (cb.TypeIs(napi_function)) { + return NAsyncWorkCallback(env, thisVar, cb).Schedule(procedureName, cbExec, cbComplete).val_; + } + } + return NVal::CreateUndefined(env).val_; +} + +napi_value SetSecurityLabelSync(napi_env env, napi_callback_info info) +{ + NFuncArg funcArg(env, info); + if (!funcArg.InitArgs(static_cast(NARG_CNT::TWO), static_cast(NARG_CNT::THREE))) { + UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); + return nullptr; + } + + bool succ = false; + std::unique_ptr path; + std::unique_ptr dataLevel; + tie(succ, path, std::ignore) = NVal(env, funcArg[static_cast(NARG_POS::FIRST)]).ToUTF8String(); + if (!succ) { + 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_; + } +} + +napi_value GetSecurityLabel(napi_env env, napi_callback_info info) +{ + NFuncArg funcArg(env, info); + if (!funcArg.InitArgs(static_cast(NARG_CNT::ONE), static_cast(NARG_CNT::TWO))) { + UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); + return nullptr; + } + + bool succ = false; + std::unique_ptr path; + tie(succ, path, std::ignore) = NVal(env, funcArg[static_cast(NARG_POS::FIRST)]).ToUTF8String(); + if (!succ) { + UniError(EINVAL).ThrowErr(env, "Invalid path"); + return nullptr; + } + auto result = std::make_shared(); + std::string pathString(path.get()); + auto cbExec = [pathString, result](napi_env env) -> UniError { + *result = SecurityLabel::GetSecurityLabel(pathString); + return UniError(ERRNO_NOERR); + }; + auto cbComplete = [result](napi_env env, UniError err) -> NVal { + if (err) { + return { env, err.GetNapiErr(env) }; + } + return { NVal::CreateUTF8String(env, *result) }; + }; + + 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_; + } else { + NVal cb(env, funcArg[static_cast(NARG_POS::SECOND)]); + if (cb.TypeIs(napi_function)) { + return NAsyncWorkCallback(env, thisVar, cb).Schedule(procedureName, cbExec, cbComplete).val_; + } + } + return NVal::CreateUndefined(env).val_; +} + +napi_value GetSecurityLabelSync(napi_env env, napi_callback_info info) +{ + NFuncArg funcArg(env, info); + if (!funcArg.InitArgs(static_cast(NARG_CNT::ONE), static_cast(NARG_CNT::TWO))) { + UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); + return nullptr; + } + + bool succ = false; + std::unique_ptr path; + tie(succ, path, std::ignore) = NVal(env, funcArg[static_cast(NARG_POS::FIRST)]).ToUTF8String(); + if (!succ) { + UniError(EINVAL).ThrowErr(env, "Invalid path"); + return nullptr; + } + auto result = std::make_shared(); + *result = SecurityLabel::GetSecurityLabel(path.get()); + return NVal::CreateUTF8String(env, *result).val_; +} +} // namespace ModuleSecurityLabel +} // namespace DistributedFS +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_securitylabel/securitylabel_n_exporter.h b/interfaces/kits/js/src/mod_securitylabel/securitylabel_n_exporter.h new file mode 100644 index 000000000..0de9959ed --- /dev/null +++ b/interfaces/kits/js/src/mod_securitylabel/securitylabel_n_exporter.h @@ -0,0 +1,32 @@ +/* + * 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. + */ + +#ifndef SECURITYLABEL_N_EXPORTER_H +#define SECURITYLABEL_N_EXPORTER_H + +#include "../common/napi/n_exporter.h" + + +namespace OHOS { +namespace DistributedFS { +namespace ModuleSecurityLabel { +napi_value SetSecurityLabel(napi_env env, napi_callback_info info); +napi_value SetSecurityLabelSync(napi_env env, napi_callback_info info); +napi_value GetSecurityLabel(napi_env env, napi_callback_info info); +napi_value GetSecurityLabelSync(napi_env env, napi_callback_info info); +} // namespace ModuleSecurityLabel +} // namespace DistributedFS +} // namespace OHOS +#endif // SECURITYLABEL_N_EXPORTER_H \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_securitylabel/securitylabel_napi.cpp b/interfaces/kits/js/src/mod_securitylabel/securitylabel_napi.cpp new file mode 100644 index 000000000..dde3f5e5f --- /dev/null +++ b/interfaces/kits/js/src/mod_securitylabel/securitylabel_napi.cpp @@ -0,0 +1,43 @@ +/* + * 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. + */ + +#include "napi/native_api.h" +#include "napi/native_node_api.h" + +#include "securitylabel_n_exporter.h" +#include "securitylabel_napi.h" + +namespace OHOS { +namespace DistributedFS { +namespace ModuleSecurityLabel { +/*********************************************** + * Module export and register + ***********************************************/ +napi_value SecurityLabelExport(napi_env env, napi_value exports) +{ + static napi_property_descriptor desc[] = { + DECLARE_NAPI_FUNCTION("setSecurityLabel", SetSecurityLabel), + DECLARE_NAPI_FUNCTION("setSecurityLabelSync", SetSecurityLabelSync), + DECLARE_NAPI_FUNCTION("getSecurityLabel", GetSecurityLabel), + DECLARE_NAPI_FUNCTION("getSecurityLabelSync", GetSecurityLabelSync), + }; + NAPI_CALL(env, napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc)); + return exports; +} + +NAPI_MODULE(securitylabel, SecurityLabelExport) +} // namespace ModuleSecurityLabel +} // namespace DistributedFS +} // namespace OHOS \ No newline at end of file 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 000000000..66c52dff9 --- /dev/null +++ b/interfaces/kits/js/src/mod_securitylabel/securitylabel_napi.h @@ -0,0 +1,27 @@ +/* + * 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. + */ + +#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 ff857cb08..0acf61a3d 100644 --- a/interfaces/kits/js/src/mod_statfs/statfs_n_exporter.cpp +++ b/interfaces/kits/js/src/mod_statfs/statfs_n_exporter.cpp @@ -18,22 +18,16 @@ #include #include -#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 ModuleStatfs { +using namespace FileManagement::LibN; + napi_value GetFrSizeSync(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"); + NError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); return nullptr; } @@ -41,18 +35,18 @@ napi_value GetFrSizeSync(napi_env env, napi_callback_info info) std::unique_ptr path; tie(succ, path, std::ignore) = NVal(env, funcArg[NARG_POS::FIRST]).ToUTF8String(); if (!succ) { - UniError(EINVAL).ThrowErr(env, "Invalid path"); + NError(EINVAL).ThrowErr(env, "Invalid path"); return nullptr; } struct statvfs diskInfo; int ret = statvfs(path.get(), &diskInfo); if (ret != 0) { - UniError(errno).ThrowErr(env, "Failed get info"); + NError(errno).ThrowErr(env, "Failed get info"); return nullptr; } - unsigned long long freeSize = - static_cast(diskInfo.f_bsize) * static_cast(diskInfo.f_bavail); + unsigned long long freeSize = static_cast(diskInfo.f_bsize) * + static_cast(diskInfo.f_bavail); return NVal::CreateInt64(env, freeSize).val_; } @@ -60,7 +54,7 @@ napi_value GetFrSize(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"); + NError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); return nullptr; } @@ -68,23 +62,23 @@ napi_value GetFrSize(napi_env env, napi_callback_info info) std::unique_ptr path; tie(succ, path, std::ignore) = NVal(env, funcArg[NARG_POS::FIRST]).ToUTF8String(); if (!succ) { - UniError(EINVAL).ThrowErr(env, "Invalid path"); + NError(EINVAL).ThrowErr(env, "Invalid path"); return nullptr; } auto resultSize = std::make_shared(); std::string pathString(path.get()); - auto cbExec = [pathString, resultSize](napi_env env) -> UniError { + auto cbExec = [pathString, resultSize]() -> NError { struct statvfs diskInfo; int ret = statvfs(pathString.c_str(), &diskInfo); if (ret != 0) { - return UniError(errno); + return NError(errno); } - *resultSize = - static_cast(diskInfo.f_bsize) * static_cast(diskInfo.f_bavail); - return UniError(ERRNO_NOERR); + *resultSize = static_cast(diskInfo.f_bsize) * + static_cast(diskInfo.f_bavail); + return NError(ERRNO_NOERR); }; - auto cbComplete = [resultSize](napi_env env, UniError err) -> NVal { + auto cbComplete = [resultSize](napi_env env, NError err) -> NVal { if (err) { return { env, err.GetNapiErr(env) }; } @@ -106,7 +100,7 @@ napi_value GetBSizeSync(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"); + NError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); return nullptr; } @@ -114,14 +108,14 @@ napi_value GetBSizeSync(napi_env env, napi_callback_info info) std::unique_ptr path; tie(succ, path, std::ignore) = NVal(env, funcArg[NARG_POS::FIRST]).ToUTF8String(); if (!succ) { - UniError(EINVAL).ThrowErr(env, "Invalid path"); + NError(EINVAL).ThrowErr(env, "Invalid path"); return nullptr; } struct statvfs diskInfo; int ret = statvfs(path.get(), &diskInfo); if (ret != 0) { - UniError(errno).ThrowErr(env); + NError(errno).ThrowErr(env); return nullptr; } return NVal::CreateInt64(env, diskInfo.f_bsize).val_; @@ -131,7 +125,7 @@ napi_value GetBSize(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"); + NError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); return nullptr; } @@ -139,22 +133,22 @@ napi_value GetBSize(napi_env env, napi_callback_info info) std::unique_ptr path; tie(succ, path, std::ignore) = NVal(env, funcArg[NARG_POS::FIRST]).ToUTF8String(); if (!succ) { - UniError(EINVAL).ThrowErr(env, "Invalid path"); + NError(EINVAL).ThrowErr(env, "Invalid path"); return nullptr; } auto resultSize = std::make_shared(); std::string pathString(path.get()); - auto cbExec = [pathString, resultSize](napi_env env) -> UniError { + auto cbExec = [pathString, resultSize]() -> NError { struct statvfs diskInfo; int ret = statvfs(pathString.c_str(), &diskInfo); if (ret != 0) { - return UniError(errno); + return NError(errno); } *resultSize = diskInfo.f_bsize; - return UniError(ERRNO_NOERR); + return NError(ERRNO_NOERR); }; - auto cbComplete = [resultSize](napi_env env, UniError err) -> NVal { + auto cbComplete = [resultSize](napi_env env, NError err) -> NVal { if (err) { return { env, err.GetNapiErr(env) }; } @@ -176,7 +170,7 @@ napi_value GetBAvailSync(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"); + NError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); return nullptr; } @@ -184,14 +178,14 @@ napi_value GetBAvailSync(napi_env env, napi_callback_info info) std::unique_ptr path; tie(succ, path, std::ignore) = NVal(env, funcArg[NARG_POS::FIRST]).ToUTF8String(); if (!succ) { - UniError(EINVAL).ThrowErr(env, "Invalid path"); + NError(EINVAL).ThrowErr(env, "Invalid path"); return nullptr; } struct statvfs diskInfo; int ret = statvfs(path.get(), &diskInfo); if (ret != 0) { - UniError(errno).ThrowErr(env); + NError(errno).ThrowErr(env); return nullptr; } return NVal::CreateInt64(env, diskInfo.f_bavail).val_; @@ -201,7 +195,7 @@ napi_value GetBAvail(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"); + NError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); return nullptr; } @@ -209,22 +203,22 @@ napi_value GetBAvail(napi_env env, napi_callback_info info) std::unique_ptr path; tie(succ, path, std::ignore) = NVal(env, funcArg[NARG_POS::FIRST]).ToUTF8String(); if (!succ) { - UniError(EINVAL).ThrowErr(env, "Invalid path"); + NError(EINVAL).ThrowErr(env, "Invalid path"); return nullptr; } auto resultSize = std::make_shared(); std::string pathString(path.get()); - auto cbExec = [pathString, resultSize](napi_env env) -> UniError { + auto cbExec = [pathString, resultSize]() -> NError { struct statvfs diskInfo; int ret = statvfs(pathString.c_str(), &diskInfo); if (ret != 0) { - return UniError(errno); + return NError(errno); } *resultSize = diskInfo.f_bavail; - return UniError(ERRNO_NOERR); + return NError(ERRNO_NOERR); }; - auto cbComplete = [resultSize](napi_env env, UniError err) -> NVal { + auto cbComplete = [resultSize](napi_env env, NError err) -> NVal { if (err) { return { env, err.GetNapiErr(env) }; } @@ -246,7 +240,7 @@ napi_value GetBlocksSync(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"); + NError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); return nullptr; } @@ -254,14 +248,14 @@ napi_value GetBlocksSync(napi_env env, napi_callback_info info) std::unique_ptr path; tie(succ, path, std::ignore) = NVal(env, funcArg[NARG_POS::FIRST]).ToUTF8String(); if (!succ) { - UniError(EINVAL).ThrowErr(env, "Invalid path"); + NError(EINVAL).ThrowErr(env, "Invalid path"); return nullptr; } struct statvfs diskInfo; int ret = statvfs(path.get(), &diskInfo); if (ret != 0) { - UniError(errno).ThrowErr(env); + NError(errno).ThrowErr(env); return nullptr; } return NVal::CreateInt64(env, diskInfo.f_blocks).val_; @@ -271,7 +265,7 @@ napi_value GetBlocks(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"); + NError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); return nullptr; } @@ -279,22 +273,22 @@ napi_value GetBlocks(napi_env env, napi_callback_info info) std::unique_ptr path; tie(succ, path, std::ignore) = NVal(env, funcArg[NARG_POS::FIRST]).ToUTF8String(); if (!succ) { - UniError(EINVAL).ThrowErr(env, "Invalid path"); + NError(EINVAL).ThrowErr(env, "Invalid path"); return nullptr; } auto resultSize = std::make_shared(); std::string pathString(path.get()); - auto cbExec = [pathString, resultSize](napi_env env) -> UniError { + auto cbExec = [pathString, resultSize]() -> NError { struct statvfs diskInfo; int ret = statvfs(pathString.c_str(), &diskInfo); if (ret != 0) { - return UniError(errno); + return NError(errno); } *resultSize = diskInfo.f_blocks; - return UniError(ERRNO_NOERR); + return NError(ERRNO_NOERR); }; - auto cbComplete = [resultSize](napi_env env, UniError err) -> NVal { + auto cbComplete = [resultSize](napi_env env, NError err) -> NVal { if (err) { return { env, err.GetNapiErr(env) }; } @@ -316,7 +310,7 @@ napi_value GetBFreeSync(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"); + NError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); return nullptr; } @@ -324,14 +318,14 @@ napi_value GetBFreeSync(napi_env env, napi_callback_info info) std::unique_ptr path; tie(succ, path, std::ignore) = NVal(env, funcArg[NARG_POS::FIRST]).ToUTF8String(); if (!succ) { - UniError(EINVAL).ThrowErr(env, "Invalid path"); + NError(EINVAL).ThrowErr(env, "Invalid path"); return nullptr; } struct statvfs diskInfo; int ret = statvfs(path.get(), &diskInfo); if (ret != 0) { - UniError(errno).ThrowErr(env); + NError(errno).ThrowErr(env); return nullptr; } return NVal::CreateInt64(env, diskInfo.f_bfree).val_; @@ -341,7 +335,7 @@ napi_value GetBFree(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"); + NError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); return nullptr; } @@ -349,22 +343,22 @@ napi_value GetBFree(napi_env env, napi_callback_info info) std::unique_ptr path; tie(succ, path, std::ignore) = NVal(env, funcArg[NARG_POS::FIRST]).ToUTF8String(); if (!succ) { - UniError(EINVAL).ThrowErr(env, "Invalid path"); + NError(EINVAL).ThrowErr(env, "Invalid path"); return nullptr; } auto resultSize = std::make_shared(); std::string pathString(path.get()); - auto cbExec = [pathString, resultSize](napi_env env) -> UniError { + auto cbExec = [pathString, resultSize]() -> NError { struct statvfs diskInfo; int ret = statvfs(pathString.c_str(), &diskInfo); if (ret != 0) { - return UniError(errno); + return NError(errno); } *resultSize = diskInfo.f_bfree; - return UniError(ERRNO_NOERR); + return NError(ERRNO_NOERR); }; - auto cbComplete = [resultSize](napi_env env, UniError err) -> NVal { + auto cbComplete = [resultSize](napi_env env, NError err) -> NVal { if (err) { return { env, err.GetNapiErr(env) }; } @@ -386,7 +380,7 @@ napi_value GetFreeBytesSync(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"); + NError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); return nullptr; } @@ -394,18 +388,18 @@ napi_value GetFreeBytesSync(napi_env env, napi_callback_info info) std::unique_ptr path; tie(succ, path, std::ignore) = NVal(env, funcArg[NARG_POS::FIRST]).ToUTF8String(); if (!succ) { - UniError(EINVAL).ThrowErr(env, "Invalid path"); + NError(EINVAL).ThrowErr(env, "Invalid path"); return nullptr; } struct statvfs diskInfo; int ret = statvfs(path.get(), &diskInfo); if (ret != 0) { - UniError(errno).ThrowErr(env); + NError(errno).ThrowErr(env); return nullptr; } - unsigned long long freeSize = - static_cast(diskInfo.f_bsize) * static_cast(diskInfo.f_bfree); + unsigned long long freeSize = static_cast(diskInfo.f_bsize) * + static_cast(diskInfo.f_bfree); return NVal::CreateInt64(env, freeSize).val_; } @@ -413,7 +407,7 @@ napi_value GetFreeBytes(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"); + NError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); return nullptr; } @@ -421,23 +415,23 @@ napi_value GetFreeBytes(napi_env env, napi_callback_info info) std::unique_ptr path; tie(succ, path, std::ignore) = NVal(env, funcArg[NARG_POS::FIRST]).ToUTF8String(); if (!succ) { - UniError(EINVAL).ThrowErr(env, "Invalid path"); + NError(EINVAL).ThrowErr(env, "Invalid path"); return nullptr; } auto resultSize = std::make_shared(); std::string pathString(path.get()); - auto cbExec = [pathString, resultSize](napi_env env) -> UniError { + auto cbExec = [pathString, resultSize]() -> NError { struct statvfs diskInfo; int ret = statvfs(pathString.c_str(), &diskInfo); if (ret != 0) { - return UniError(errno); + return NError(errno); } - *resultSize = - static_cast(diskInfo.f_bsize) * static_cast(diskInfo.f_bfree); - return UniError(ERRNO_NOERR); + *resultSize = static_cast(diskInfo.f_bsize) * + static_cast(diskInfo.f_bfree); + return NError(ERRNO_NOERR); }; - auto cbComplete = [resultSize](napi_env env, UniError err) -> NVal { + auto cbComplete = [resultSize](napi_env env, NError err) -> NVal { if (err) { return { env, err.GetNapiErr(env) }; } @@ -459,7 +453,7 @@ napi_value GetTotalBytesSync(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"); + NError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); return nullptr; } @@ -467,18 +461,18 @@ napi_value GetTotalBytesSync(napi_env env, napi_callback_info info) std::unique_ptr path; tie(succ, path, std::ignore) = NVal(env, funcArg[NARG_POS::FIRST]).ToUTF8String(); if (!succ) { - UniError(EINVAL).ThrowErr(env, "Invalid path"); + NError(EINVAL).ThrowErr(env, "Invalid path"); return nullptr; } struct statvfs diskInfo; int ret = statvfs(path.get(), &diskInfo); if (ret != 0) { - UniError(errno).ThrowErr(env); + NError(errno).ThrowErr(env); return nullptr; } - unsigned long long totalSize = - static_cast(diskInfo.f_bsize) * static_cast(diskInfo.f_blocks); + unsigned long long totalSize = static_cast(diskInfo.f_bsize) * + static_cast(diskInfo.f_blocks); return NVal::CreateInt64(env, totalSize).val_; } @@ -486,7 +480,7 @@ napi_value GetTotalBytes(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"); + NError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); return nullptr; } @@ -494,23 +488,23 @@ napi_value GetTotalBytes(napi_env env, napi_callback_info info) std::unique_ptr path; tie(succ, path, std::ignore) = NVal(env, funcArg[NARG_POS::FIRST]).ToUTF8String(); if (!succ) { - UniError(EINVAL).ThrowErr(env, "Invalid path"); + NError(EINVAL).ThrowErr(env, "Invalid path"); return nullptr; } auto resultSize = std::make_shared(); std::string pathString(path.get()); - auto cbExec = [pathString, resultSize](napi_env env) -> UniError { + auto cbExec = [pathString, resultSize]() -> NError { struct statvfs diskInfo; int ret = statvfs(pathString.c_str(), &diskInfo); if (ret != 0) { - return UniError(errno); + return NError(errno); } - *resultSize = - static_cast(diskInfo.f_bsize) * static_cast(diskInfo.f_blocks); - return UniError(ERRNO_NOERR); + *resultSize = static_cast(diskInfo.f_bsize) * + static_cast(diskInfo.f_blocks); + return NError(ERRNO_NOERR); }; - auto cbComplete = [resultSize](napi_env env, UniError err) -> NVal { + auto cbComplete = [resultSize](napi_env env, NError err) -> NVal { if (err) { return { env, err.GetNapiErr(env) }; } @@ -529,4 +523,4 @@ napi_value GetTotalBytes(napi_env env, napi_callback_info info) } } // namespace ModuleStatfs } // namespace DistributedFS -} // namespace OHOS \ No newline at end of file +} // namespace OHOS 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 ddee8c664..dd25b1724 100644 --- a/interfaces/kits/js/src/mod_statfs/statfs_n_exporter.h +++ b/interfaces/kits/js/src/mod_statfs/statfs_n_exporter.h @@ -16,7 +16,7 @@ #ifndef STATFS_N_EXPORTER_H #define STATFS_N_EXPORTER_H -#include "../common/napi/n_exporter.h" +#include "filemgmt_libn.h" namespace OHOS { namespace DistributedFS { diff --git a/interfaces/kits/js/src/mod_statfs/statfs_napi.cpp b/interfaces/kits/js/src/mod_statfs/statfs_napi.cpp index e25fddf19..0ec3891e9 100644 --- a/interfaces/kits/js/src/mod_statfs/statfs_napi.cpp +++ b/interfaces/kits/js/src/mod_statfs/statfs_napi.cpp @@ -13,11 +13,8 @@ * limitations under the License. */ -#include "statfs_napi.h" #include "statfs_n_exporter.h" - -#include "napi/native_api.h" -#include "napi/native_node_api.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 index a08b1f281..1af18b97a 100644 --- a/interfaces/kits/js/src/mod_statfs/statfs_napi.h +++ b/interfaces/kits/js/src/mod_statfs/statfs_napi.h @@ -16,7 +16,7 @@ #ifndef STATFS_NAPI_H #define STATFS_NAPI_H -#include "napi/native_api.h" +#include "filemgmt_libn.h" namespace OHOS { namespace DistributedFS { diff --git a/interfaces/kits/napi/BUILD.gn b/interfaces/kits/napi/BUILD.gn new file mode 100644 index 000000000..d34e359a5 --- /dev/null +++ b/interfaces/kits/napi/BUILD.gn @@ -0,0 +1,138 @@ +# 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("//build/ohos.gni") +import( + "//foundation/distributeddatamgr/distributedfile/distributedfile_aafwk.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 = [ + "${aafwk_kits_path}/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 = "distributeddatamgr" + 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 = [ + "${aafwk_kits_path}/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_standard:samgr_proxy", + ] + subsystem_name = "distributeddatamgr" + 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 = [ + "${aafwk_kits_path}/ability/native:abilitykit_native", + "//foundation/arkui/napi:ace_napi", + "//foundation/distributedschedule/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 = "distributeddatamgr" + 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 000000000..c5aae1548 --- /dev/null +++ b/interfaces/kits/napi/common/ability_helper.cpp @@ -0,0 +1,54 @@ +/* + * 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. + */ + +#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 000000000..0b93a005e --- /dev/null +++ b/interfaces/kits/napi/common/ability_helper.h @@ -0,0 +1,29 @@ +/* + * 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. + */ + +#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 000000000..ac022f572 --- /dev/null +++ b/interfaces/kits/napi/common/common_func.cpp @@ -0,0 +1,57 @@ +/* + * 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. + */ + +#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 000000000..2a3553e9f --- /dev/null +++ b/interfaces/kits/napi/common/common_func.h @@ -0,0 +1,34 @@ +/* + * 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. + */ + +#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 000000000..412b5f6cf --- /dev/null +++ b/interfaces/kits/napi/common/log.h @@ -0,0 +1,92 @@ +/* + * 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. + */ + +#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, "distributedfilejs" }; + +#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 000000000..a9cdff36e --- /dev/null +++ b/interfaces/kits/napi/common/napi/n_class.cpp @@ -0,0 +1,100 @@ +/* + * 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. + */ + +#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 000000000..55c97d55d --- /dev/null +++ b/interfaces/kits/napi/common/napi/n_class.h @@ -0,0 +1,81 @@ +/* + * 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. + */ + +#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 000000000..5f1b95163 --- /dev/null +++ b/interfaces/kits/napi/common/napi/n_exporter.h @@ -0,0 +1,40 @@ +/* + * 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. + */ + +#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 000000000..5200ebd60 --- /dev/null +++ b/interfaces/kits/napi/common/napi/n_func_arg.cpp @@ -0,0 +1,107 @@ +/* + * 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. + */ + +#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 000000000..e1fba2118 --- /dev/null +++ b/interfaces/kits/napi/common/napi/n_func_arg.h @@ -0,0 +1,69 @@ +/* + * 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. + */ + +#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 000000000..5c28576b0 --- /dev/null +++ b/interfaces/kits/napi/common/napi/n_val.cpp @@ -0,0 +1,280 @@ +/* + * 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. + */ + +#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 000000000..e23a4c65e --- /dev/null +++ b/interfaces/kits/napi/common/napi/n_val.h @@ -0,0 +1,79 @@ +/* + * 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. + */ + +#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 000000000..b764aae19 --- /dev/null +++ b/interfaces/kits/napi/common/napi/uni_header.h @@ -0,0 +1,25 @@ +/* + * 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. + */ + +#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 000000000..295b28654 --- /dev/null +++ b/interfaces/kits/napi/common/uni_error.cpp @@ -0,0 +1,118 @@ +/* + * 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. + */ + +#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 000000000..2f20d1cb1 --- /dev/null +++ b/interfaces/kits/napi/common/uni_error.h @@ -0,0 +1,60 @@ +/* + * 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. + */ + +#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 000000000..5b38a92c6 --- /dev/null +++ b/interfaces/kits/napi/device_storage_manager/device_sm_exporter.cpp @@ -0,0 +1,1017 @@ +/* + * 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. + */ + +#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 000000000..457931d4f --- /dev/null +++ b/interfaces/kits/napi/device_storage_manager/device_sm_exporter.h @@ -0,0 +1,56 @@ +/* + * 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. + */ +#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 000000000..09c58744f --- /dev/null +++ b/interfaces/kits/napi/device_storage_manager/module.cpp @@ -0,0 +1,47 @@ +/* + * 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. + */ +#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 000000000..20bb9f509 --- /dev/null +++ b/interfaces/kits/napi/device_storage_manager/module.h @@ -0,0 +1,18 @@ +/* + * 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. + */ +#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 000000000..6d5c4947a --- /dev/null +++ b/interfaces/kits/napi/file_picker_service/file_picker_exporter.cpp @@ -0,0 +1,478 @@ +/* + * 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. + */ +#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 000000000..31bd97abc --- /dev/null +++ b/interfaces/kits/napi/file_picker_service/file_picker_exporter.h @@ -0,0 +1,96 @@ +/* + * 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. + */ +#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 000000000..0acd1ca3a --- /dev/null +++ b/interfaces/kits/napi/file_picker_service/module.cpp @@ -0,0 +1,48 @@ +/* + * 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. + */ +#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 000000000..d92e88741 --- /dev/null +++ b/interfaces/kits/napi/file_picker_service/module.h @@ -0,0 +1,18 @@ +/* + * 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. + */ +#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 000000000..50e846daa --- /dev/null +++ b/interfaces/kits/napi/file_share_ability/file_share_exporter.cpp @@ -0,0 +1,278 @@ +/* + * 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. + */ + +#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 000000000..27229812b --- /dev/null +++ b/interfaces/kits/napi/file_share_ability/file_share_exporter.h @@ -0,0 +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. + */ +#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 000000000..25c1336a4 --- /dev/null +++ b/interfaces/kits/napi/file_share_ability/module.cpp @@ -0,0 +1,48 @@ +/* + * 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. + */ +#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 000000000..a287cb5c9 --- /dev/null +++ b/interfaces/kits/napi/file_share_ability/module.h @@ -0,0 +1,18 @@ +/* + * 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. + */ +#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/storage_service/BUILD.gn b/interfaces/kits/native/storage_service/BUILD.gn new file mode 100644 index 000000000..bf6d9bef9 --- /dev/null +++ b/interfaces/kits/native/storage_service/BUILD.gn @@ -0,0 +1,37 @@ +# 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("//build/ohos.gni") + +ohos_shared_library("ss_crypto_api") { + sources = [ "ss_crypto_api.cpp" ] + include_dirs = [ + "include", + "//foundation/distributedschedule/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", + "//utils/native/base/include", + "//third_party/openssl/include", + ] + deps = [ "//utils/native/base:utils" ] + external_deps = [ + "ability_base:want", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + "safwk:system_ability_fwk", + "samgr_standard:samgr_proxy", + ] + subsystem_name = "distributeddatamgr" +} 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 000000000..8cef6e3be --- /dev/null +++ b/interfaces/kits/native/storage_service/ss_crypto_api.cpp @@ -0,0 +1,224 @@ +/* + * 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. + */ +#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 000000000..28008d5fc --- /dev/null +++ b/interfaces/kits/native/storage_service/ss_crypto_api.h @@ -0,0 +1,18 @@ +/* + * 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. + */ +#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_libhilog/BUILD.gn b/utils/filemgmt_libhilog/BUILD.gn new file mode 100644 index 000000000..3e8d9fdff --- /dev/null +++ b/utils/filemgmt_libhilog/BUILD.gn @@ -0,0 +1,29 @@ +# 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("log_public_config") { + visibility = [ ":*" ] + + include_dirs = [ "." ] +} + +ohos_shared_library("filemgmt_libhilog") { + public_configs = [ ":log_public_config" ] + public_deps = + [ "//base/hiviewdfx/hilog/interfaces/native/innerkits:libhilog" ] + + subsystem_name = "filemanagement" + part_name = "file_api" +} diff --git a/utils/filemgmt_libhilog/filemgmt_libhilog.h b/utils/filemgmt_libhilog/filemgmt_libhilog.h new file mode 100644 index 000000000..277a9f859 --- /dev/null +++ b/utils/filemgmt_libhilog/filemgmt_libhilog.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 FILEMGMT_LIBHILOG_H +#define FILEMGMT_LIBHILOG_H + +#include "hilog/log.h" + +#include + +namespace OHOS { +#ifndef LOG_DOMAIN +#define LOG_DOMAIN 0xD001600 +#endif + +#ifndef LOG_TAG +#define LOG_TAG "FileManagement" +#endif + +static constexpr HiviewDFX::HiLogLabel FILEMGMT_LOG_LABEL = {LOG_CORE, LOG_DOMAIN, LOG_TAG}; + +#if defined __FILE_NAME__ +#define FILEMGMT_FILE_NAME __FILE_NAME__ +#else +#include +#define FILEMGMT_FILE_NAME (strrchr(__FILE__, '/') ? strrchr(__FILE__, '/') + 1 : __FILE__) +#endif + +#define FILEMGMT_PRINT_LOG(Level, fmt, ...) \ + HiviewDFX::HiLog::Level(FILEMGMT_LOG_LABEL, "[%{public}s:%{public}d->%{public}s] " fmt, FILEMGMT_FILE_NAME, \ + __LINE__, __FUNCTION__, ##__VA_ARGS__) + +#define HILOGD(fmt, ...) FILEMGMT_PRINT_LOG(Debug, fmt, ##__VA_ARGS__) +#define HILOGI(fmt, ...) FILEMGMT_PRINT_LOG(Info, fmt, ##__VA_ARGS__) +#define HILOGW(fmt, ...) FILEMGMT_PRINT_LOG(Warn, fmt, ##__VA_ARGS__) +#define HILOGE(fmt, ...) FILEMGMT_PRINT_LOG(Error, fmt, ##__VA_ARGS__) +#define HILOGF(fmt, ...) FILEMGMT_PRINT_LOG(Fatal, fmt, ##__VA_ARGS__) +} // namespace OHOS + +#endif // FILEMGMT_LIBHILOG_H \ No newline at end of file diff --git a/utils/filemgmt_libn/BUILD.gn b/utils/filemgmt_libn/BUILD.gn new file mode 100644 index 000000000..d4857b1a7 --- /dev/null +++ b/utils/filemgmt_libn/BUILD.gn @@ -0,0 +1,44 @@ +# 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("libn_public_config") { + visibility = [ ":*" ] + + include_dirs = [ + "include", + "include/n_async", + ] +} + +ohos_shared_library("filemgmt_libn") { + sources = [ + "src/n_async/n_async_work_callback.cpp", + "src/n_async/n_async_work_promise.cpp", + "src/n_async/n_ref.cpp", + "src/n_class.cpp", + "src/n_error.cpp", + "src/n_func_arg.cpp", + "src/n_val.cpp", + ] + + public_configs = [ ":libn_public_config" ] + public_deps = [ + "//foundation/arkui/napi:ace_napi", + "//foundation/filemanagement/file_api/utils/filemgmt_libhilog", + ] + + subsystem_name = "filemanagement" + part_name = "file_api" +} diff --git a/utils/filemgmt_libn/include/filemgmt_libn.h b/utils/filemgmt_libn/include/filemgmt_libn.h new file mode 100644 index 000000000..61e6dd790 --- /dev/null +++ b/utils/filemgmt_libn/include/filemgmt_libn.h @@ -0,0 +1,25 @@ +/* + * 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 FILEMGMT_LIBN_FILEMGMT_LIBN_H +#define FILEMGMT_LIBN_FILEMGMT_LIBN_H + +#include "n_async_work_callback.h" +#include "n_async_work_promise.h" +#include "n_error.h" +#include "n_exporter.h" +#include "n_func_arg.h" + +#endif // FILEMGMT_LIBN_FILEMGMT_LIBN_H \ No newline at end of file diff --git a/utils/filemgmt_libn/include/n_async/n_async_context.h b/utils/filemgmt_libn/include/n_async/n_async_context.h new file mode 100644 index 000000000..4883b6f78 --- /dev/null +++ b/utils/filemgmt_libn/include/n_async/n_async_context.h @@ -0,0 +1,75 @@ +/* + * 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 FILEMGMT_LIBN_N_ASYNC_CONTEXT_H +#define FILEMGMT_LIBN_N_ASYNC_CONTEXT_H + +#include + +#include "n_error.h" +#include "n_ref.h" +#include "n_val.h" + +namespace OHOS { +namespace FileManagement { +namespace LibN { +using NContextCBExec = std::function; +using NContextCBComplete = std::function; + +class NAsyncContext { +public: + NError err_; + NVal res_; + NContextCBExec cbExec_; + NContextCBComplete cbComplete_; + napi_async_work awork_; + NRef thisPtr_; + + NAsyncContext(NVal thisPtr) + : err_(0), res_(NVal()), cbExec_(nullptr), cbComplete_(nullptr), awork_(nullptr), thisPtr_(thisPtr) + { + } + virtual ~NAsyncContext() = default; +}; + +class NAsyncContextPromise : public NAsyncContext { +public: + napi_deferred deferred_ = nullptr; + explicit NAsyncContextPromise(NVal thisPtr) : NAsyncContext(thisPtr) {} + ~NAsyncContextPromise() = default; +}; + +class NAsyncContextCallback : public NAsyncContext { +public: + NRef cb_; + 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 +#endif // FILEMGMT_LIBN_N_ASYNC_CONTEXT_H \ No newline at end of file diff --git a/utils/filemgmt_libn/include/n_async/n_async_work.h b/utils/filemgmt_libn/include/n_async/n_async_work.h new file mode 100644 index 000000000..eb7dad33e --- /dev/null +++ b/utils/filemgmt_libn/include/n_async/n_async_work.h @@ -0,0 +1,36 @@ +/* + * 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 FILEMGMT_LIBN_N_ASYNC_WORK_H +#define FILEMGMT_LIBN_N_ASYNC_WORK_H + +#include "n_async_context.h" + +namespace OHOS { +namespace FileManagement { +namespace LibN { +class NAsyncWork { +public: + NAsyncWork(napi_env env) : env_(env) {} + virtual ~NAsyncWork() = default; + virtual NVal Schedule(std::string procedureName, NContextCBExec cbExec, NContextCBComplete cbComplete) = 0; + + napi_env env_ = nullptr; +}; +} // namespace LibN +} // namespace FileManagement +} // namespace OHOS + +#endif // FILEMGMT_LIBN_N_ASYNC_WORK_H \ No newline at end of file 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 new file mode 100644 index 000000000..afd6cdb29 --- /dev/null +++ b/utils/filemgmt_libn/include/n_async/n_async_work_callback.h @@ -0,0 +1,38 @@ +/* + * 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 FILEMGMT_LIBN_N_ASYNC_WORK_CALLBACK_H +#define FILEMGMT_LIBN_N_ASYNC_WORK_CALLBACK_H + +#include "n_async_work.h" + +namespace OHOS { +namespace FileManagement { +namespace LibN { +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: + NAsyncContextCallback *ctx_ = nullptr; +}; +} // namespace LibN +} // namespace FileManagement +} // namespace OHOS + +#endif // FILEMGMT_LIBN_N_ASYNC_WORK_CALLBACK_H \ No newline at end of file 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 new file mode 100644 index 000000000..ffcc9770e --- /dev/null +++ b/utils/filemgmt_libn/include/n_async/n_async_work_promise.h @@ -0,0 +1,38 @@ +/* + * 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 FILEMGMT_LIBN_N_ASYNC_WORK_PROMISE_H +#define FILEMGMT_LIBN_N_ASYNC_WORK_PROMISE_H + +#include "n_async_work.h" + +namespace OHOS { +namespace FileManagement { +namespace LibN { +class NAsyncWorkPromise : public NAsyncWork { +public: + NAsyncWorkPromise(napi_env env, NVal thisPtr); + ~NAsyncWorkPromise() = default; + + NVal Schedule(std::string procedureName, NContextCBExec cbExec, NContextCBComplete cbComplete) final; + +private: + NAsyncContextPromise *ctx_; +}; +} // namespace LibN +} // namespace FileManagement +} // namespace OHOS + +#endif // FILEMGMT_LIBN_N_ASYNC_WORK_PROMISE_H \ No newline at end of file diff --git a/utils/filemgmt_libn/include/n_async/n_ref.h b/utils/filemgmt_libn/include/n_async/n_ref.h new file mode 100644 index 000000000..e2748077a --- /dev/null +++ b/utils/filemgmt_libn/include/n_async/n_ref.h @@ -0,0 +1,41 @@ +/* + * 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 FILEMGMT_LIBN_N_REF_H +#define FILEMGMT_LIBN_N_REF_H + +#include "n_val.h" + +namespace OHOS { +namespace FileManagement { +namespace LibN { +class NRef { +public: + NRef(); + NRef(NVal val); + ~NRef(); + + explicit operator bool() const; + NVal Deref(napi_env env); + +private: + napi_env env_ = nullptr; + napi_ref ref_ = nullptr; +}; +} // namespace LibN +} // namespace FileManagement +} // namespace OHOS + +#endif // FILEMGMT_LIBN_N_REF_H \ No newline at end of file diff --git a/utils/filemgmt_libn/include/n_class.h b/utils/filemgmt_libn/include/n_class.h new file mode 100644 index 000000000..5fcca8b0b --- /dev/null +++ b/utils/filemgmt_libn/include/n_class.h @@ -0,0 +1,83 @@ +/* + * 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 FILEMGMT_LIBN_N_CLASS_H +#define FILEMGMT_LIBN_N_CLASS_H + +#include +#include +#include +#include +#include +#include + +#include "n_napi.h" +#include "filemgmt_libhilog.h" + +namespace OHOS { +namespace FileManagement { +namespace LibN { +class NClass final { +public: + NClass(const NClass &) = delete; + NClass &operator=(const NClass &) = delete; + + 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; + static NClass &GetInstance(); + std::map exClassMap; + std::mutex exClassMapLock; +}; +} // namespace LibN +} // namespace FileManagement +} // namespace OHOS + +#endif // FILEMGMT_LIBN_N_CLASS_H \ No newline at end of file diff --git a/utils/filemgmt_libn/include/n_error.h b/utils/filemgmt_libn/include/n_error.h new file mode 100644 index 000000000..3c88381fb --- /dev/null +++ b/utils/filemgmt_libn/include/n_error.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 FILEMGMT_LIBN_N_ERROR_H +#define FILEMGMT_LIBN_N_ERROR_H + +#include +#include +#include + +#include "n_napi.h" + +namespace OHOS { +namespace FileManagement { +namespace LibN { +constexpr int ERRNO_NOERR = 0; + +class NError { +public: + NError(); + 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); + +private: + int errno_ = ERRNO_NOERR; + std::string errMsg_; +}; +} // namespace LibN +} // namespace FileManagement +} // namespace OHOS + +#endif // FILEMGMT_LIBN_N_ERROR_H \ No newline at end of file diff --git a/utils/filemgmt_libn/include/n_exporter.h b/utils/filemgmt_libn/include/n_exporter.h new file mode 100644 index 000000000..8a3a32dad --- /dev/null +++ b/utils/filemgmt_libn/include/n_exporter.h @@ -0,0 +1,44 @@ +/* + * 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 FILEMGMT_LIBN_N_EXPORTER_H +#define FILEMGMT_LIBN_N_EXPORTER_H + +#include "n_napi.h" + +#include +#include + +#include "n_val.h" + +namespace OHOS { +namespace FileManagement { +namespace LibN { +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 LibN +} // namespace FileManagement +} // namespace OHOS + +#endif // FILEMGMT_LIBN_N_EXPORTER_H \ No newline at end of file diff --git a/utils/filemgmt_libn/include/n_func_arg.h b/utils/filemgmt_libn/include/n_func_arg.h new file mode 100644 index 000000000..1ccc5d6ff --- /dev/null +++ b/utils/filemgmt_libn/include/n_func_arg.h @@ -0,0 +1,75 @@ +/* + * 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 FILEMGMT_LIBN_N_FUNC_ARG_H +#define FILEMGMT_LIBN_N_FUNC_ARG_H + +#include +#include +#include + +#include "n_napi.h" +#include "n_val.h" + +namespace OHOS { +namespace FileManagement { +namespace LibN { +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 LibN +} // namespace FileManagement +} // namespace OHOS + +#endif // FILEMGMT_LIBN_N_FUNC_ARG_H \ No newline at end of file diff --git a/utils/filemgmt_libn/include/n_napi.h b/utils/filemgmt_libn/include/n_napi.h new file mode 100644 index 000000000..44f963e2e --- /dev/null +++ b/utils/filemgmt_libn/include/n_napi.h @@ -0,0 +1,26 @@ +/* + * 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 FILEMGMT_LIBN_N_NAPI_H +#define FILEMGMT_LIBN_N_NAPI_H + +#ifdef FILE_SUBSYSTEM_DEBUG_LOCAL +#include +#else +#include "napi/native_api.h" +#include "napi/native_node_api.h" +#endif + +#endif // FILEMGMT_LIBN_N_NAPI_H \ No newline at end of file diff --git a/utils/filemgmt_libn/include/n_val.h b/utils/filemgmt_libn/include/n_val.h new file mode 100644 index 000000000..bd770847e --- /dev/null +++ b/utils/filemgmt_libn/include/n_val.h @@ -0,0 +1,85 @@ +/* + * 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 FILEMGMT_LIBN_N_VAL_H +#define FILEMGMT_LIBN_N_VAL_H + +#include +#include +#include +#include + +#include "n_napi.h" + +namespace OHOS { +namespace FileManagement { +namespace LibN { +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; + bool TypeIsError(bool checkErrno = false) 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 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; + 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 LibN +} // namespace FileManagement +} // namespace OHOS + +#endif // FILEMGMT_LIBN_N_VAL_H \ No newline at end of file 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 new file mode 100644 index 000000000..33ec2a5f4 --- /dev/null +++ b/utils/filemgmt_libn/src/n_async/n_async_work_callback.cpp @@ -0,0 +1,100 @@ +/* + * 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 "n_async_work_callback.h" +#include "filemgmt_libhilog.h" + +namespace OHOS { +namespace FileManagement { +namespace LibN { +using namespace std; + +NAsyncWorkCallback::NAsyncWorkCallback(napi_env env, NVal thisPtr, NVal cb) : NAsyncWork(env) +{ + ctx_ = new NAsyncContextCallback(thisPtr, cb); +} + +static void CallbackExecute(napi_env env, void *data) +{ + auto ctx = static_cast(data); + if (ctx != nullptr && ctx->cbExec_ != nullptr) { + ctx->err_ = ctx->cbExec_(); + } +} + +static void CallbackComplete(napi_env env, napi_status status, void *data) +{ + napi_handle_scope scope = nullptr; + napi_open_handle_scope(env, &scope); + auto ctx = static_cast(data); + if (ctx == nullptr) { + return; + } + if (ctx->cbComplete_ != nullptr) { + ctx->res_ = ctx->cbComplete_(env, ctx->err_); + ctx->cbComplete_ = nullptr; + } + + vector argv; + if (!ctx->res_.TypeIsError(true)) { + argv = {NError(ERRNO_NOERR).GetNapiErr(env), ctx->res_.val_}; + } else { + argv = {ctx->res_.val_}; + } + + napi_value global = nullptr; + napi_value callback = ctx->cb_.Deref(env).val_; + napi_value tmp = nullptr; + napi_get_global(env, &global); + napi_status stat = napi_call_function(env, global, callback, argv.size(), argv.data(), &tmp); + 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; +} + +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 shall be a funciton"); + return NVal(); + } + + 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) { + HILOGE("INNER BUG. Failed to create async work for %{public}d", status); + return NVal(); + } + + status = napi_queue_async_work(env_, ctx_->awork_); + if (status != napi_ok) { + HILOGE("INNER BUG. Failed to queue async work for %{public}d", status); + return NVal(); + } + + ctx_ = nullptr; // The ownership of ctx_ has been transferred + return NVal::CreateUndefined(env_); +} +} // namespace LibN +} // namespace FileManagement +} // namespace OHOS 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 new file mode 100644 index 000000000..e8deae7f8 --- /dev/null +++ b/utils/filemgmt_libn/src/n_async/n_async_work_promise.cpp @@ -0,0 +1,93 @@ +/* + * 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 "n_async_work_promise.h" +#include "filemgmt_libhilog.h" + +namespace OHOS { +namespace FileManagement { +namespace LibN { +using namespace std; + +NAsyncWorkPromise::NAsyncWorkPromise(napi_env env, NVal thisPtr) : NAsyncWork(env) +{ + ctx_ = new NAsyncContextPromise(thisPtr); +} + +static void PromiseOnExec(napi_env env, void *data) +{ + auto ctx = static_cast(data); + if (ctx != nullptr && ctx->cbExec_ != nullptr) { + ctx->err_ = ctx->cbExec_(); + } +} + +static void PromiseOnComplete(napi_env env, napi_status status, void *data) +{ + auto ctx = static_cast(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) { + HILOGE("Internal BUG, cannot resolve promise for %{public}d", status); + } + } else { + napi_status status = napi_reject_deferred(env, ctx->deferred_, ctx->res_.val_); + if (status != napi_ok) { + HILOGE("Internal BUG, cannot reject promise for %{public}d", status); + } + } + ctx->deferred_ = nullptr; + napi_delete_async_work(env, ctx->awork_); + delete ctx; +} + +NVal NAsyncWorkPromise::Schedule(string procedureName, NContextCBExec cbExec, NContextCBComplete cbComplete) +{ + ctx_->cbExec_ = move(cbExec); + ctx_->cbComplete_ = move(cbComplete); + + napi_status status; + napi_value result = nullptr; + status = napi_create_promise(env_, &ctx_->deferred_, &result); + if (status != napi_ok) { + HILOGE("INNER BUG. Cannot create promise for %{public}d", status); + return NVal(); + } + + napi_value resource = NVal::CreateUTF8String(env_, procedureName).val_; + status = napi_create_async_work(env_, nullptr, resource, PromiseOnExec, PromiseOnComplete, ctx_, &ctx_->awork_); + if (status != napi_ok) { + HILOGE("INNER BUG. Failed to create async work for %{public}d", status); + return NVal(); + } + + status = napi_queue_async_work(env_, ctx_->awork_); + if (status != napi_ok) { + HILOGE("INNER BUG. Failed to queue async work for %{public}d", status); + return NVal(); + } + + ctx_ = nullptr; // The ownership of ctx_ has been transferred + return {env_, result}; +} +} // namespace LibN +} // namespace FileManagement +} // namespace OHOS diff --git a/utils/filemgmt_libn/src/n_async/n_ref.cpp b/utils/filemgmt_libn/src/n_async/n_ref.cpp new file mode 100644 index 000000000..b0c0ef9d8 --- /dev/null +++ b/utils/filemgmt_libn/src/n_async/n_ref.cpp @@ -0,0 +1,55 @@ +/* + * 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 "n_ref.h" + +namespace OHOS { +namespace FileManagement { +namespace LibN { +NRef::NRef() {} + +NRef::NRef(NVal val) +{ + if (val) { + env_ = val.env_; + napi_create_reference(val.env_, val.val_, 1, &ref_); + } +} + +NRef::~NRef() +{ + if (ref_) { + napi_delete_reference(env_, ref_); + } +} + +NRef::operator bool() const +{ + return ref_ != nullptr; +} + +NVal NRef::Deref(napi_env env) +{ + if (!ref_) { + return NVal(); + } + + napi_value val = nullptr; + napi_get_reference_value(env, ref_, &val); + return {env, val}; +} +} // namespace LibN +} // namespace FileManagement +} // namespace OHOS diff --git a/utils/filemgmt_libn/src/n_class.cpp b/utils/filemgmt_libn/src/n_class.cpp new file mode 100644 index 000000000..15b756875 --- /dev/null +++ b/utils/filemgmt_libn/src/n_class.cpp @@ -0,0 +1,92 @@ +/* + * 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 "n_class.h" + +#include "filemgmt_libhilog.h" + +namespace OHOS { +namespace FileManagement { +namespace LibN { +using namespace std; +NClass &NClass::GetInstance() +{ + static thread_local 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 LibN +} // namespace FileManagement +} // namespace OHOS \ No newline at end of file diff --git a/utils/filemgmt_libn/src/n_error.cpp b/utils/filemgmt_libn/src/n_error.cpp new file mode 100644 index 000000000..66993656d --- /dev/null +++ b/utils/filemgmt_libn/src/n_error.cpp @@ -0,0 +1,72 @@ +/* + * 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 "n_error.h" + +#include + +#include "n_val.h" +#include "filemgmt_libhilog.h" + +namespace OHOS { +namespace FileManagement { +namespace LibN { +using namespace std; + +NError::NError() {} + +NError::NError(int ePosix) : errno_(ePosix), errMsg_(strerror(errno_)) {} + +NError::NError(std::function()> errGen) +{ + tie(errno_, errMsg_) = errGen(); +} + +NError::operator bool() const +{ + return errno_ != ERRNO_NOERR; +} + +napi_value NError::GetNapiErr(napi_env env) +{ + napi_value code = NVal::CreateUTF8String(env, to_string(errno_)).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 NError::ThrowErr(napi_env env, string errMsg) +{ + napi_value tmp = nullptr; + napi_get_and_clear_last_exception(env, &tmp); + // Note that ace engine cannot thow 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()); + } +} + +void NError::ThrowErr(napi_env env) +{ + ThrowErr(env, errMsg_); +} +} // namespace LibN +} // namespace FileManagement +} // namespace OHOS \ No newline at end of file diff --git a/utils/filemgmt_libn/src/n_func_arg.cpp b/utils/filemgmt_libn/src/n_func_arg.cpp new file mode 100644 index 000000000..4d09c3a96 --- /dev/null +++ b/utils/filemgmt_libn/src/n_func_arg.cpp @@ -0,0 +1,110 @@ +/* + * 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 "n_func_arg.h" + +#include "n_error.h" +#include "filemgmt_libhilog.h" + +namespace OHOS { +namespace FileManagement { +namespace LibN { +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 LibN +} // namespace FileManagement +} // namespace OHOS diff --git a/utils/filemgmt_libn/src/n_val.cpp b/utils/filemgmt_libn/src/n_val.cpp new file mode 100644 index 000000000..f8085f637 --- /dev/null +++ b/utils/filemgmt_libn/src/n_val.cpp @@ -0,0 +1,303 @@ +/* + * 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 "n_val.h" + +#include + +#include "n_error.h" +#include "filemgmt_libhilog.h" + +namespace OHOS { +namespace FileManagement { +namespace LibN { +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; +} + +bool NVal::TypeIsError(bool checkErrno) const +{ + if (!*this) { + return false; + } + + bool res = false; + napi_is_error(env_, val_, &res); + + return res; +} + +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 in_array_buffer = nullptr; + size_t byte_offset; + size_t length; + void *data = nullptr; + napi_status status = + napi_get_typedarray_info(env_, val_, &type, &length, (void **)&data, &in_array_buffer, &byte_offset); + 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::CreateUTF8String(napi_env env, const char *str, ssize_t len) +{ + napi_value res = nullptr; + napi_create_string_utf8(env, str, len, &res); + return {env, res}; +} + +NVal NVal::CreateUint8Array(napi_env env, void *buf, size_t bufLen) +{ + napi_value output_buffer = nullptr; + napi_create_external_arraybuffer( + env, buf, bufLen, [](napi_env env, void *finalize_data, void *finalize_hint) { free(finalize_data); }, NULL, + &output_buffer); + napi_value output_array = nullptr; + napi_create_typedarray(env, napi_uint8_array, bufLen, output_buffer, 0, &output_array); + return {env, output_array}; +} + +tuple NVal::CreateArrayBuffer(napi_env env, size_t len) +{ + napi_value val; + void *buf = nullptr; + napi_create_arraybuffer(env, len, &buf, &val); + return {{env, val}, {buf}}; +} + +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 LibN +} // namespace FileManagement +} // namespace OHOS \ No newline at end of file -- Gitee From 7dfbcedbd13aeef2f6397d857bdec264e68c7c8c Mon Sep 17 00:00:00 2001 From: haonan_7 Date: Wed, 6 Jul 2022 17:14:39 +0800 Subject: [PATCH 2/7] fix code check Signed-off-by: haonan_7 --- .../kits/js/src/mod_file/class_file/file_n_exporter.cpp | 4 ++-- .../js/src/mod_fileio/class_stream/stream_n_exporter.cpp | 4 ++-- .../kits/js/src/mod_fileio/properties/copy_file.cpp | 6 +++--- .../kits/js/src/mod_fileio/properties/prop_n_exporter.cpp | 8 ++++---- interfaces/kits/napi/common/napi/n_class.cpp | 2 +- .../napi/device_storage_manager/device_sm_exporter.cpp | 4 ++-- .../kits/napi/file_share_ability/file_share_exporter.cpp | 4 ++-- utils/filemgmt_libn/src/n_class.cpp | 2 +- 8 files changed, 17 insertions(+), 17 deletions(-) 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 842fd80b7..66a86174f 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 @@ -1292,7 +1292,7 @@ napi_value FileNExporter::ReadArrayBuffer(napi_env env, napi_callback_info info) bool FileNExporter::Export() { - return exports_.AddProp({ + return exports_.AddProp( { NVal::DeclareNapiFunction("mkdir", Mkdir), NVal::DeclareNapiFunction("rmdir", Rmdir), NVal::DeclareNapiFunction("get", Get), @@ -1305,7 +1305,7 @@ bool FileNExporter::Export() NVal::DeclareNapiFunction("writeArrayBuffer", WriteArrayBuffer), NVal::DeclareNapiFunction("readText", ReadText), NVal::DeclareNapiFunction("readArrayBuffer", ReadArrayBuffer), - }); + } ); } string FileNExporter::GetClassName() 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 947b858d5..96cd3a389 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 @@ -277,11 +277,11 @@ napi_value StreamNExporter::Read(napi_env env, napi_callback_info info) return { env, err.GetNapiErr(env) }; } NVal obj = NVal::CreateObject(env); - obj.AddProp({ + 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 }; }; 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 6a6dd5aa3..e23bc66b7 100644 --- a/interfaces/kits/js/src/mod_fileio/properties/copy_file.cpp +++ b/interfaces/kits/js/src/mod_fileio/properties/copy_file.cpp @@ -108,15 +108,15 @@ static tuple ParseJsOperand(napi_env env, NVal pathOrFdFromJsArg { auto [isPath, path, ignore] = pathOrFdFromJsArg.ToUTF8String(); if (isPath) { - return {true, FileInfo{true, move(path), {}}}; + return { true, FileInfo { true, move(path), {} } }; } auto [isFd, fd] = pathOrFdFromJsArg.ToInt32(); if (isFd) { - return {true, FileInfo{false, {}, {fd, false}}}; + return { true, FileInfo { false, {} , { fd, false } } }; } - return {false, FileInfo{false, {}, {}}}; + return { false, FileInfo { false, {} , {} } }; }; napi_value CopyFile::Sync(napi_env env, napi_callback_info info) 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 8e4d0e6fe..c0956483d 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 @@ -498,11 +498,11 @@ napi_value PropNExporter::Read(napi_env env, napi_callback_info info) return { env, err.GetNapiErr(env) }; } NVal obj = NVal::CreateObject(env); - obj.AddProp({ + 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 }; }; @@ -677,7 +677,7 @@ napi_value PropNExporter::WriteSync(napi_env env, napi_callback_info info) bool PropNExporter::Export() { - return exports_.AddProp({ + return exports_.AddProp( { NVal::DeclareNapiFunction("access", Access), NVal::DeclareNapiFunction("accessSync", AccessSync), NVal::DeclareNapiFunction("chmod", Chmod::Async), @@ -742,7 +742,7 @@ bool PropNExporter::Export() NVal::DeclareNapiFunction("unlinkSync", UnlinkSync), NVal::DeclareNapiFunction("write", Write), NVal::DeclareNapiFunction("writeSync", WriteSync), - }); + } ); } string PropNExporter::GetClassName() diff --git a/interfaces/kits/napi/common/napi/n_class.cpp b/interfaces/kits/napi/common/napi/n_class.cpp index a9cdff36e..0ed0c865d 100644 --- a/interfaces/kits/napi/common/napi/n_class.cpp +++ b/interfaces/kits/napi/common/napi/n_class.cpp @@ -62,7 +62,7 @@ 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); diff --git a/interfaces/kits/napi/device_storage_manager/device_sm_exporter.cpp b/interfaces/kits/napi/device_storage_manager/device_sm_exporter.cpp index 5b38a92c6..eff576d01 100644 --- a/interfaces/kits/napi/device_storage_manager/device_sm_exporter.cpp +++ b/interfaces/kits/napi/device_storage_manager/device_sm_exporter.cpp @@ -981,7 +981,7 @@ napi_value DeviceSMExporter::GetWritableVolumes(napi_env env, napi_callback_info bool DeviceSMExporter::Export() { - return exports_.AddProp({ + return exports_.AddProp( { NVal::DeclareNapiFunction("mount", Mount), NVal::DeclareNapiFunction("unMount", UnMount), NVal::DeclareNapiFunction("format", Format), @@ -999,7 +999,7 @@ bool DeviceSMExporter::Export() NVal::DeclareNapiFunction("getWritableVolumes", GetWritableVolumes), NVal::DeclareNapiFunction("getBestVolumeDescription", GetBestVolumeDescription), NVal::DeclareNapiFunction("isEncrypted", IsEncrypted), - }); + } ); } string DeviceSMExporter::GetClassName() diff --git a/interfaces/kits/napi/file_share_ability/file_share_exporter.cpp b/interfaces/kits/napi/file_share_ability/file_share_exporter.cpp index 50e846daa..33a291ac2 100644 --- a/interfaces/kits/napi/file_share_ability/file_share_exporter.cpp +++ b/interfaces/kits/napi/file_share_ability/file_share_exporter.cpp @@ -258,9 +258,9 @@ napi_value FileShareExporter::FuzzyFileToUri(napi_env env, napi_callback_info in bool FileShareExporter::Export() { - return exports_.AddProp({ + return exports_.AddProp( { NVal::DeclareNapiFunction("fuzzyFileToUri", FuzzyFileToUri), - }); + } ); } string FileShareExporter::GetClassName() diff --git a/utils/filemgmt_libn/src/n_class.cpp b/utils/filemgmt_libn/src/n_class.cpp index 15b756875..c41f502ac 100644 --- a/utils/filemgmt_libn/src/n_class.cpp +++ b/utils/filemgmt_libn/src/n_class.cpp @@ -53,7 +53,7 @@ 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); -- Gitee From 8d76da87f21853f5461e9e521c575f51e35036fa Mon Sep 17 00:00:00 2001 From: haonan_7 Date: Thu, 7 Jul 2022 10:42:30 +0800 Subject: [PATCH 3/7] fix codecheck Signed-off-by: haonan_7 --- interfaces/kits/js/src/common/ability_helper.h | 6 +++--- interfaces/kits/js/src/common/log.h | 6 +++--- interfaces/kits/js/src/common/napi/n_class.h | 6 +++--- interfaces/kits/js/src/common/napi/n_exporter.h | 6 +++--- interfaces/kits/js/src/common/napi/n_func_arg.h | 6 +++--- interfaces/kits/js/src/common/napi/uni_header.h | 6 +++--- interfaces/kits/js/src/common/uni_error.h | 6 +++--- .../kits/js/src/mod_file/class_file/file_n_exporter.h | 6 +++++- interfaces/kits/js/src/mod_file/common_func.h | 6 +++++- 9 files changed, 31 insertions(+), 23 deletions(-) diff --git a/interfaces/kits/js/src/common/ability_helper.h b/interfaces/kits/js/src/common/ability_helper.h index 36c69cb77..d23285184 100644 --- a/interfaces/kits/js/src/common/ability_helper.h +++ b/interfaces/kits/js/src/common/ability_helper.h @@ -13,8 +13,8 @@ * limitations under the License. */ -#ifndef INTERFACES_KITS_NAPI_COMMON_ABILITY_HELPER_H -#define INTERFACES_KITS_NAPI_COMMON_ABILITY_HELPER_H +#ifndef INTERFACES_KITS_JS_SRC_COMMON_ABILITY_HELPER_H +#define INTERFACES_KITS_JS_SRC_COMMON_ABILITY_HELPER_H #include "ability.h" @@ -25,4 +25,4 @@ struct AbilityHelper { }; } // namespace DistributedFS } // namespace OHOS -#endif \ No newline at end of file +#endif // INTERFACES_KITS_JS_SRC_COMMON_ABILITY_HELPER_H \ No newline at end of file diff --git a/interfaces/kits/js/src/common/log.h b/interfaces/kits/js/src/common/log.h index 412b5f6cf..48eb794a1 100644 --- a/interfaces/kits/js/src/common/log.h +++ b/interfaces/kits/js/src/common/log.h @@ -13,8 +13,8 @@ * limitations under the License. */ -#ifndef INTERFACES_KITS_NAPI_COMMON_LOG_H -#define INTERFACES_KITS_NAPI_COMMON_LOG_H +#ifndef INTERFACES_KITS_JS_SRC_COMMON_LOG_H +#define INTERFACES_KITS_JS_SRC_COMMON_LOG_H #include #include @@ -89,4 +89,4 @@ static constexpr OHOS::HiviewDFX::HiLogLabel FILEIO_LABEL = { LOG_CORE, FILEIO_D #endif } // namespace DistributedFS } // namespace OHOS -#endif \ No newline at end of file +#endif // INTERFACES_KITS_JS_SRC_COMMON_LOG_H \ No newline at end of file diff --git a/interfaces/kits/js/src/common/napi/n_class.h b/interfaces/kits/js/src/common/napi/n_class.h index a6186b638..13a194ade 100644 --- a/interfaces/kits/js/src/common/napi/n_class.h +++ b/interfaces/kits/js/src/common/napi/n_class.h @@ -13,8 +13,8 @@ * limitations under the License. */ -#ifndef INTERFACES_KITS_NAPI_COMMON_NAPI_N_CLASS_H -#define INTERFACES_KITS_NAPI_COMMON_NAPI_N_CLASS_H +#ifndef INTERFACES_KITS_JS_SRC_COMMON_NAPI_N_CLASS_H +#define INTERFACES_KITS_JS_SRC_COMMON_NAPI_N_CLASS_H #include "uni_header.h" @@ -76,4 +76,4 @@ private: }; } // namespace DistributedFS } // namespace OHOS -#endif \ No newline at end of file +#endif // INTERFACES_KITS_JS_SRC_COMMON_NAPI_N_CLASS_H \ 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 db5563f7b..11d2fd7c9 100644 --- a/interfaces/kits/js/src/common/napi/n_exporter.h +++ b/interfaces/kits/js/src/common/napi/n_exporter.h @@ -13,8 +13,8 @@ * limitations under the License. */ -#ifndef INTERFACES_KITS_NAPI_COMMON_NAPI_N_EXPORTER_H -#define INTERFACES_KITS_NAPI_COMMON_NAPI_N_EXPORTER_H +#ifndef INTERFACES_KITS_JS_SRC_COMMON_NAPI_N_EXPORTER_H +#define INTERFACES_KITS_JS_SRC_COMMON_NAPI_N_EXPORTER_H #include "n_val.h" @@ -33,4 +33,4 @@ protected: }; } // namespace DistributedFS } // namespace OHOS -#endif \ No newline at end of file +#endif // INTERFACES_KITS_JS_SRC_COMMON_NAPI_N_EXPORTER_H \ No newline at end of file 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 e0d2a17de..1192094e2 100644 --- a/interfaces/kits/js/src/common/napi/n_func_arg.h +++ b/interfaces/kits/js/src/common/napi/n_func_arg.h @@ -13,8 +13,8 @@ * limitations under the License. */ -#ifndef INTERFACES_KITS_NAPI_COMMON_NAPI_N_FUNC_ARG_H -#define INTERFACES_KITS_NAPI_COMMON_NAPI_N_FUNC_ARG_H +#ifndef INTERFACES_KITS_JS_SRC_COMMON_NAPI_N_FUNC_ARG_H +#define INTERFACES_KITS_JS_SRC_COMMON_NAPI_N_FUNC_ARG_H #include "uni_header.h" @@ -64,4 +64,4 @@ private: }; } // namespace DistributedFS } // namespace OHOS -#endif \ No newline at end of file +#endif // INTERFACES_KITS_JS_SRC_COMMON_NAPI_N_FUNC_ARG_H \ No newline at end of file diff --git a/interfaces/kits/js/src/common/napi/uni_header.h b/interfaces/kits/js/src/common/napi/uni_header.h index 081621198..2b316842c 100644 --- a/interfaces/kits/js/src/common/napi/uni_header.h +++ b/interfaces/kits/js/src/common/napi/uni_header.h @@ -13,8 +13,8 @@ * limitations under the License. */ -#ifndef N_UNI_HEADER_H -#define N_UNI_HEADER_H +#ifndef INTERFACES_KITS_JS_SRC_COMMON_NAPI_UNI_HEADER_H +#define INTERFACES_KITS_JS_SRC_COMMON_NAPI_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 \ No newline at end of file +#endif // INTERFACES_KITS_JS_SRC_COMMON_NAPI_UNI_HEADER_H \ No newline at end of file diff --git a/interfaces/kits/js/src/common/uni_error.h b/interfaces/kits/js/src/common/uni_error.h index e1a2d8663..883756b73 100644 --- a/interfaces/kits/js/src/common/uni_error.h +++ b/interfaces/kits/js/src/common/uni_error.h @@ -13,8 +13,8 @@ * limitations under the License. */ -#ifndef INTERFACES_KITS_NAPI_COMMON_UNI_ERROR_H -#define INTERFACES_KITS_NAPI_COMMON_UNI_ERROR_H +#ifndef INTERFACES_KITS_JS_SRC_COMMON_UNI_ERROR_H +#define INTERFACES_KITS_JS_SRC_COMMON_UNI_ERROR_H #include "napi/uni_header.h" @@ -61,4 +61,4 @@ private: }; } // namespace DistributedFS } // namespace OHOS -#endif \ No newline at end of file +#endif // INTERFACES_KITS_JS_SRC_COMMON_UNI_ERROR_H \ No newline at end of file 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 050f2779b..4f369a249 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,6 +13,9 @@ * 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" @@ -195,4 +198,5 @@ public: }; } // namespace ModuleFile } // namespace DistributedFS -} // namespace OHOS \ No newline at end of file +} // namespace OHOS +#endif // INTERFACES_KITS_JS_SRC_MOD_FILE_CLASS_FILE_FILE_N_EXPORTER_H \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_file/common_func.h b/interfaces/kits/js/src/mod_file/common_func.h index 19924c507..58a0a02e7 100644 --- a/interfaces/kits/js/src/mod_file/common_func.h +++ b/interfaces/kits/js/src/mod_file/common_func.h @@ -13,6 +13,9 @@ * 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" @@ -30,4 +33,5 @@ struct CommonFunc { }; } // namespace ModuleFile } // namespace DistributedFS -} // namespace OHOS \ No newline at end of file +} // namespace OHOS +#endif // INTERFACES_KITS_JS_SRC_MOD_FILE_COMMON_FUNC_H \ No newline at end of file -- Gitee From 4238e02d7dad1d6b99ae97f5057edece99269743 Mon Sep 17 00:00:00 2001 From: haonan_7 Date: Thu, 7 Jul 2022 15:07:17 +0800 Subject: [PATCH 4/7] fix codecheck Signed-off-by: haonan_7 --- .../mod_file/class_file/file_n_exporter.cpp | 8 +++-- .../js/src/mod_fileio/properties/open.cpp | 33 ++++++++++++++++++- .../mod_fileio/properties/prop_n_exporter.cpp | 6 ++-- .../js/src/mod_securitylabel/security_label.h | 9 ++--- 4 files changed, 46 insertions(+), 10 deletions(-) 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 66a86174f..f0d8111e2 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 @@ -138,11 +138,13 @@ bool CheckUri(napi_env env, string &path) int GetRealPath(string &path) { - unique_ptr absPath = make_unique(PATH_MAX + 1); - if (realpath(path.c_str(), absPath.get()) == nullptr) { + char *realPath = realpath(path.c_str(), nullptr); + if (realPath == nullptr) { return errno; } - path = absPath.get(); + + path = realPath; + free(realPath); return 0; } diff --git a/interfaces/kits/js/src/mod_fileio/properties/open.cpp b/interfaces/kits/js/src/mod_fileio/properties/open.cpp index 673fa1d91..f16bd6d90 100644 --- a/interfaces/kits/js/src/mod_fileio/properties/open.cpp +++ b/interfaces/kits/js/src/mod_fileio/properties/open.cpp @@ -27,6 +27,36 @@ namespace DistributedFS { namespace ModuleFileIO { using namespace std; +int AdaptToAbi(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; +} + napi_value Open::Sync(napi_env env, napi_callback_info info) { NFuncArg funcArg(env, info); @@ -52,7 +82,7 @@ napi_value Open::Sync(napi_env env, napi_callback_info info) return nullptr; } } - + (void)AdaptToAbi(flags); int fd = -1; size_t argc = funcArg.GetArgc(); if (argc != NARG_CNT::THREE) { @@ -114,6 +144,7 @@ napi_value Open::Async(napi_env env, napi_callback_info info) return nullptr; } } + (void)AdaptToAbi(flags); int mode = 0; if (argc == NARG_CNT::FOUR || (argc == NARG_CNT::THREE && NVal(env, funcArg[NARG_POS::THIRD]).TypeIs(napi_number))) { 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 c0956483d..140b0bb1f 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 @@ -55,7 +55,9 @@ namespace OHOS { namespace DistributedFS { namespace ModuleFileIO { using namespace std; - +namespace { + static constexpr int MODE_RUO_RWX = 0775; +} napi_value PropNExporter::AccessSync(napi_env env, napi_callback_info info) { NFuncArg funcArg(env, info); @@ -305,7 +307,7 @@ 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(), 0775); + ret = mkdir(path.get(), MODE_RUO_RWX); } else { int mode; tie(succ, mode) = NVal(env, funcArg[NARG_POS::SECOND]).ToInt32(); diff --git a/interfaces/kits/js/src/mod_securitylabel/security_label.h b/interfaces/kits/js/src/mod_securitylabel/security_label.h index 6ab5cba60..6b4aa0845 100644 --- a/interfaces/kits/js/src/mod_securitylabel/security_label.h +++ b/interfaces/kits/js/src/mod_securitylabel/security_label.h @@ -28,12 +28,13 @@ namespace OHOS { namespace DistributedFS { namespace ModuleSecurityLabel { namespace { - const char XATTR_KEY[] = {"user.security"}; - const std::string DEFAULT_DATA_LEVEL = "s3"; - const std::set DATA_LEVEL = {"s0", "s1", "s2", "s3", "s4"}; -} +} // namespace + 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) { -- Gitee From 1662b76bf91f8b1ba40ab5705ac79e7c5784033b Mon Sep 17 00:00:00 2001 From: haonan_7 Date: Thu, 7 Jul 2022 18:23:35 +0800 Subject: [PATCH 5/7] fix problem Signed-off-by: haonan_7 --- interfaces/kits/js/@ohos.document.d.ts | 63 ------ interfaces/kits/js/@ohos.statfs.d.ts | 42 ---- .../mod_file/class_file/file_n_exporter.cpp | 186 ++++++++++++++---- interfaces/kits/js/src/mod_file/common_func.h | 2 - .../src/n_async/n_async_work_callback.cpp | 2 +- 5 files changed, 154 insertions(+), 141 deletions(-) delete mode 100644 interfaces/kits/js/@ohos.document.d.ts delete mode 100644 interfaces/kits/js/@ohos.statfs.d.ts diff --git a/interfaces/kits/js/@ohos.document.d.ts b/interfaces/kits/js/@ohos.document.d.ts deleted file mode 100644 index 1333942fe..000000000 --- a/interfaces/kits/js/@ohos.document.d.ts +++ /dev/null @@ -1,63 +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 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/@ohos.statfs.d.ts b/interfaces/kits/js/@ohos.statfs.d.ts deleted file mode 100644 index 53a32c9ea..000000000 --- a/interfaces/kits/js/@ohos.statfs.d.ts +++ /dev/null @@ -1,42 +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 filesystem statistics APIs - * - * @since 8 - * @sysCap N/A - * @devices phone, tablet - */ -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/src/mod_file/class_file/file_n_exporter.cpp b/interfaces/kits/js/src/mod_file/class_file/file_n_exporter.cpp index f0d8111e2..2458d9191 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 @@ -465,6 +465,60 @@ void ListComp(napi_env env, napi_status status, void *data) delete asyncCallbackInfo; } +int FileCopy(const string& srcPath, const string& dstPath) +{ + bool ret = FILE_IO_ERROR; + string src = srcPath; + string dest = dstPath; + if (GetRealPath(src) == 0) { + if (GetRealPath(dest) == ENOENT) { + FDGuard sfd; + sfd.SetFD(open((char *)src.c_str(), O_RDONLY)); + struct stat attrSrc; + if (stat((char *)src.c_str(), &attrSrc) == FAILED) { + return FILE_IO_ERROR; + } + dest = UriToAbsolute(dest); + FDGuard ofd; + ofd.SetFD(open((char *)dest.c_str(), O_WRONLY | O_CREAT, attrSrc.st_mode)); + if (sfd.GetFD() == FAILED || ofd.GetFD() == FAILED) { + return FILE_IO_ERROR; + } + + if (sendfile(ofd.GetFD(), sfd.GetFD(), nullptr, attrSrc.st_size) != FAILED) { + ret = SUCCESS; + } else { + remove((char *)dest.c_str()); + } + } else if (GetRealPath(dest) == 0) { + return (dest == src) ? SUCCESS : FILE_IO_ERROR; + } + } + return ret; +} + +int DirCopy(const string& srcPath, const string& dstPath) +{ + string src = srcPath; + string dest = dstPath; + if (GetRealPath(src) == ENOENT) { + return FILE_PATH_ERROR; + } + if (GetRealPath(dest) == ENOENT) { + struct stat attrSrc; + if (stat((char *)src.c_str(), &attrSrc) == FAILED || !S_ISDIR(attrSrc.st_mode)) { + return FILE_IO_ERROR; + } + dest = UriToAbsolute(dest); + if (mkdir(dest.c_str(), attrSrc.st_mode) == FAILED) { + return FILE_IO_ERROR; + } + } else { + return (dest == src) ? SUCCESS : FILE_IO_ERROR; + } + return SUCCESS; +} + void CopyExec(napi_env env, void *data) { auto *asyncCallbackInfo = (AsyncCopyCallbackInfo *)data; @@ -472,25 +526,32 @@ void CopyExec(napi_env env, void *data) string pathDst = asyncCallbackInfo->urlDst; asyncCallbackInfo->result = FAILED; asyncCallbackInfo->errorType = FILE_IO_ERROR; - int statPath = GetRealPath(path); - int statDst = GetRealPath(pathDst); - if (statPath == COMMON_NUM::ZERO && statDst == ENOENT) { - pathDst = UriToAbsolute(pathDst); - struct stat statbf; - FDGuard sfd; - FDGuard ofd; - sfd.SetFD(open((char *)path.c_str(), O_RDONLY)); - int res = stat((char *)path.c_str(), &statbf); - ofd.SetFD(open((char *)pathDst.c_str(), O_WRONLY | O_CREAT, statbf.st_mode)); - if (sfd.GetFD() != FAILED && ofd.GetFD() != FAILED && res != FAILED && - sendfile(ofd.GetFD(), sfd.GetFD(), nullptr, statbf.st_size) != FAILED) { + if (GetRealPath(path) == ENOENT) { + asyncCallbackInfo->errorType = FILE_PATH_ERROR; + return; + } + + struct stat statbf; + if (stat((char *)path.c_str(), &statbf) == FAILED) { + asyncCallbackInfo->errorType = FILE_IO_ERROR; + return; + } + + int retval; + if (S_ISREG(statbf.st_mode)) { + retval = FileCopy(path, pathDst); + if (retval == SUCCESS) { asyncCallbackInfo->result = SUCCESS; + } else { + asyncCallbackInfo->errorType = retval; } - if (asyncCallbackInfo->result == FAILED) { - remove((char *)pathDst.c_str()); + } else if (S_ISDIR(statbf.st_mode)) { + retval = DirCopy(path, pathDst); + if (retval == SUCCESS) { + asyncCallbackInfo->result = SUCCESS; + } else { + asyncCallbackInfo->errorType = retval; } - } else if (statPath == ENOENT) { - asyncCallbackInfo->errorType = FILE_PATH_ERROR; } } @@ -513,6 +574,60 @@ void CopyComp(napi_env env, napi_status status, void *data) delete asyncCallbackInfo; } +int DirMove(const string& srcPath, const string& dstPath) +{ + string src = srcPath; + string dest = dstPath; + if (GetRealPath(src) == ENOENT) { + return FILE_PATH_ERROR; + } + + auto res = GetRealPath(dest); + if (res == 0 && dest == src) { + return SUCCESS; + } else if (res != ENOENT) { + return FILE_PATH_ERROR; + } + + struct stat attrSrc; + if (stat((char *)src.c_str(), &attrSrc) == FAILED || !S_ISDIR(attrSrc.st_mode)) { + return FILE_IO_ERROR; + } + dest = UriToAbsolute(dest); + if (FAILED == mkdir(dest.c_str(), attrSrc.st_mode)) { + return FILE_IO_ERROR; + } + DIR *dirp = opendir(src.c_str()); + if (dirp == nullptr) { + return FILE_IO_ERROR; + } + struct dirent *entp; + while ((entp = readdir(dirp)) != nullptr) { + if (string(entp->d_name) == "." || string(entp->d_name) == "..") { + continue; + } + string srcBuf = src + "/" + string(entp->d_name); + string dstBuf = dest + "/" + string(entp->d_name); + if (entp->d_type == DT_DIR && DirMove(srcBuf.c_str(), dstBuf.c_str()) != SUCCESS) { + closedir(dirp); + return FILE_IO_ERROR; + } + + if (entp->d_type == DT_REG) { + if (FileCopy(srcBuf.c_str(), dstBuf.c_str()) != SUCCESS) { + closedir(dirp); + return FILE_IO_ERROR; + } else { + remove(srcBuf.c_str()); + } + } + } + closedir(dirp); + rmdir(src.c_str()); + + return SUCCESS; +} + void MoveExec(napi_env env, void *data) { auto *asyncCallbackInfo = (AsyncMoveCallbackInfo *)data; @@ -520,27 +635,32 @@ void MoveExec(napi_env env, void *data) string pathDst = asyncCallbackInfo->urlDst; asyncCallbackInfo->result = FAILED; asyncCallbackInfo->errorType = FILE_IO_ERROR; - int statPath = GetRealPath(path); - int statDst = GetRealPath(pathDst); - if (statPath == COMMON_NUM::ZERO && statDst == ENOENT) { - pathDst = UriToAbsolute(pathDst); - struct stat statbf; - FDGuard sfd; - FDGuard ofd; - sfd.SetFD(open((char *)path.c_str(), O_RDONLY)); - int res = stat((char *)path.c_str(), &statbf); - ofd.SetFD(open((char *)pathDst.c_str(), O_WRONLY | O_CREAT, statbf.st_mode)); - if (sfd.GetFD() != FAILED && ofd.GetFD() != FAILED && res != FAILED && - sendfile(ofd.GetFD(), sfd.GetFD(), nullptr, statbf.st_size) != FAILED) { + if (GetRealPath(path) == ENOENT) { + asyncCallbackInfo->errorType = FILE_PATH_ERROR; + return; + } + + struct stat statbf; + if (stat((char *)path.c_str(), &statbf) == FAILED) { + asyncCallbackInfo->errorType = FILE_IO_ERROR; + return; + } + + if (S_ISREG(statbf.st_mode)) { + int retval = FileCopy(path, pathDst); + if (retval == SUCCESS) { asyncCallbackInfo->result = SUCCESS; remove((char *)path.c_str()); + } else { + asyncCallbackInfo->errorType = retval; } - if (asyncCallbackInfo->result == FAILED) { - asyncCallbackInfo->errorType = FILE_IO_ERROR; - remove((char *)pathDst.c_str()); + } else if (S_ISDIR(statbf.st_mode)) { + int retval = DirMove(path, pathDst); + if (retval == SUCCESS) { + asyncCallbackInfo->result = SUCCESS; + } else { + asyncCallbackInfo->errorType = retval; } - } else if (statPath == ENOENT) { - asyncCallbackInfo->errorType = FILE_PATH_ERROR; } } diff --git a/interfaces/kits/js/src/mod_file/common_func.h b/interfaces/kits/js/src/mod_file/common_func.h index 58a0a02e7..57e1cd4b2 100644 --- a/interfaces/kits/js/src/mod_file/common_func.h +++ b/interfaces/kits/js/src/mod_file/common_func.h @@ -16,8 +16,6 @@ #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 { 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 33ec2a5f4..f5ad3e5ac 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 @@ -70,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 shall be a funciton"); + NError(EINVAL).ThrowErr(env_, "The callback should be a function"); return NVal(); } -- Gitee From d2bdad9dbc784d1eb48b3cec7e6a95616037d317 Mon Sep 17 00:00:00 2001 From: haonan_7 Date: Fri, 8 Jul 2022 11:03:20 +0800 Subject: [PATCH 6/7] fix problem Signed-off-by: haonan_7 --- interfaces/kits/js/src/mod_securitylabel/security_label.h | 3 --- 1 file changed, 3 deletions(-) diff --git a/interfaces/kits/js/src/mod_securitylabel/security_label.h b/interfaces/kits/js/src/mod_securitylabel/security_label.h index 6b4aa0845..44c20ca1b 100644 --- a/interfaces/kits/js/src/mod_securitylabel/security_label.h +++ b/interfaces/kits/js/src/mod_securitylabel/security_label.h @@ -27,9 +27,6 @@ namespace OHOS { namespace DistributedFS { namespace ModuleSecurityLabel { -namespace { -} // namespace - class SecurityLabel { public: static const char XATTR_KEY[] {"user.security"}; -- Gitee From 19f9aab7e8be79c244761d63b8edd6508ed03410 Mon Sep 17 00:00:00 2001 From: haonan_7 Date: Tue, 12 Jul 2022 11:11:26 +0800 Subject: [PATCH 7/7] fix problem Signed-off-by: haonan_7 --- interfaces/innerkits/include/security_label.h | 37 ------------------- 1 file changed, 37 deletions(-) delete mode 100644 interfaces/innerkits/include/security_label.h diff --git a/interfaces/innerkits/include/security_label.h b/interfaces/innerkits/include/security_label.h deleted file mode 100644 index 07f2c7343..000000000 --- a/interfaces/innerkits/include/security_label.h +++ /dev/null @@ -1,37 +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. - */ - -#ifndef FOUNDATION_FILEMANAGEMENT_FILEAPI_INTERFACES_INNERKITS_SECURITY_LABEL_H -#define FOUNDATION_FILEMANAGEMENT_FILEAPI_INTERFACES_INNERKITS_SECURITY_LABEL_H - -#include - -namespace OHOS { -namespace FileIO { -class SecurityLabel { -public: - static bool SetSecurityLabel(std::string path, std::string dataLevel) - { - return true; - } - static std::string GetSecurityLabel(std::string path) - { - return "data.security.level"; - }; -}; -} // namespace FileIO -} // namespace OHOS - -#endif \ No newline at end of file -- Gitee