diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000000000000000000000000000000000000..51c63e295e0232f7095a8ee8e03713837e37f419 --- /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 4947287f7b5ccb5d1e8b7b2d3aa5d89f322c160d..2bb9ad240fa04c8cf706a4901c4807878e90c2dc 100644 --- a/LICENSE +++ b/LICENSE @@ -1,4 +1,3 @@ - Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ diff --git a/README.md b/README.md index 76562969b350c0a8a0d32232860b134f43e815c8..55e6ee10c334df771a9acec62c42f9e386b3b3db 100644 --- a/README.md +++ b/README.md @@ -1,36 +1,280 @@ -# storage_app_file_manager +# Distributed File -#### 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**} +- [Introduction](#section104mcpsimp) + - [Architecture](#section110mcpsimp) -#### Software Architecture -Software architecture description +- [Directory Structure](#section113mcpsimp) +- [Constraints](#section117mcpsimp) +- [Usage](#section125mcpsimp) + - [Available APIs](#section127mcpsimp) + - [Usage Guidelines](#section149mcpsimp) -#### Installation +- [Repositories Involved](#section178mcpsimp) -1. xxxx -2. xxxx -3. xxxx +## Introduction -#### Instructions +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. -1. xxxx -2. xxxx -3. xxxx +### Architecture -#### Contribution +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. -1. Fork the repository -2. Create Feat_xxx branch -3. Commit your code -4. Create Pull Request +**Figure 1** Distributed File subsystem architecture +![](figures/distributed-file-subsystem-architecture.png "distributed-file-subsystem-architecture") +## Directory Structure -#### Gitee Feature +``` +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 -1. You can use Readme\_XXX.md to support different languages, such as Readme\_en.md, Readme\_zh.md -2. Gitee blog [blog.gitee.com](https://blog.gitee.com) -3. Explore open source project [https://gitee.com/explore](https://gitee.com/explore) -4. The most valuable open source project [GVP](https://gitee.com/gvp) -5. The manual of Gitee [https://gitee.com/help](https://gitee.com/help) -6. The most popular members [https://gitee.com/gitee-stars/](https://gitee.com/gitee-stars/) diff --git a/README_zh.md b/README_zh.md index 25fb3eb92931621d20f68452b45c55351b43c2ac..362301a666a4ca36cd4bd481264a598996157ca5 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 0000000000000000000000000000000000000000..65ff5c02e3e49bdf036b8f8428828463fab09633 --- /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 Binary files /dev/null and b/figures/distributed-file-subsystem-architecture.png differ diff --git "a/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" "b/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" new file mode 100644 index 0000000000000000000000000000000000000000..e3763b766aff5cf1c80c31a0ea17c527a9f70a8f Binary files /dev/null and "b/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" differ diff --git a/file_api_aafwk.gni b/file_api_aafwk.gni new file mode 100644 index 0000000000000000000000000000000000000000..36d78c22cc8c87aef866c493fdb69951b4045cc5 --- /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/kits/js/BUILD.gn b/interfaces/kits/js/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..9b02240db3474290ed455ddc4c24785165826bc6 --- /dev/null +++ b/interfaces/kits/js/BUILD.gn @@ -0,0 +1,247 @@ +# 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/src/common/ability_helper.cpp b/interfaces/kits/js/src/common/ability_helper.cpp index c5aae1548bf0240a16147f25ad208ca7700a55fa..595bee685037846a54b02689bddf6258866b4675 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 e998027c021b5d2d21cdbab1558a4718d100b888..36c69cb77ea8bd958c2c46b5f32a4894e853f43e 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 0000000000000000000000000000000000000000..6959b45a52f534f468561ff090199b2e3c5f8735 --- /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 0000000000000000000000000000000000000000..07c27b19d46a21d9e11eb999877be70306671699 --- /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 0000000000000000000000000000000000000000..2bd54cc657cafbf6dbb1c3bb026eee2b118a118a --- /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 0000000000000000000000000000000000000000..81d68a2e4c3e1a3028c7569785706f97c9db02dc --- /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 32a09a751f6885a9ddca0cddfe3b31df3dc0ee21..412b5f6cf15ac22e2b441e570ef4495cf65388f9 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 7c45ce20a60e0377caef091ef15b9794b6b0ff7c..87339bbdddfdc837b658e60e7026f2bc10e6bdc7 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 6b6d0b70a6fd54e7c9193d4867600aae41e70759..8c3af6149c68a3270987cb6e9c7c15710bcc1d2a 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 7b7f190c8f45636fdded6b81871ce5487bd30535..9bc6d5f3d7b7125e50fda9baedb4d70f2b397003 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 3809c1a4b0255236ceb8dadfb3d05c77b67366d9..f0ef6df4985a4e6b7b6618d3c917179c66625f7d 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 f2406913f1262b79307cf12091f494c2375e104e..8a049de65e913edaeb99a297acefacf6a1a6d4a0 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 0e9028b02e2bca7e956fe993da40425a34bbac84..dbda702d0e8dd2849d9ea5515138cd78b95e3faf 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 2ade0c076d11ed9f64b8d578f9a11d34241210a8..db5563f7be0153dfe4a00442736cac102a81b21c 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 123ef8d0ab67ee1bcbe2e3149f2eab6935c9d45e..1a3d6d8dd0058ac6f9590d40a638f823002aa14d 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 7ff5b29425721764591f7d706909fed35e117963..e0d2a17dec0240a3e79f7cb6d41b74f018fce470 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 6a234449d5ea46a53e384d8bd005848721e7aa73..4333208406865c075ae3a02f47e08fcd457c6a6f 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 c772b9c5e9bdabb44c048bbe6a52f9c90eaddf75..9d46fca4a1b95ed769f01984c15f232ae8f0de24 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 a79d4e1ed89dbfd9de5d04b7c51316d28eb29a1e..0816211981a6875e9842b4f14bb45523e8d67ad2 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 010aa3dad835557c4d19f4631e9a9ba0d5f7e28c..295b2865459191b92afda6ce447bba5da2837c44 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 a4183986d255ca8dd8a1ade45bc6fed666760020..e1a2d86635a735ad5bd599c27166cc9452000dc6 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 eacc54f8d40133cc7537f4c9486ef762bc984ed7..d2257d5a90b00b9724a894f3538cbdd6944a695e 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 0000000000000000000000000000000000000000..a702f8b49cbecb891ceaa7c866b0ec747152976f --- /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 0000000000000000000000000000000000000000..1b46a7b96924b89f17d889df4f1436be00dd2a53 --- /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 0000000000000000000000000000000000000000..67c338badbb9f8e66226b73cd411f5291e9170cb --- /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 0000000000000000000000000000000000000000..dd259e0aaaa4755b4b6d0fc8ec4f4f7780e393e5 --- /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 0000000000000000000000000000000000000000..32337cc3be7a15eea64ac6d12d5ce82ec5cf968f --- /dev/null +++ b/interfaces/kits/js/src/mod_file/class_file/file_n_exporter.cpp @@ -0,0 +1,1325 @@ +/* + * 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) +{ + char *realPath = realpath(path.c_str(), nullptr); + if (realPath == nullptr) { + return errno; + } + + path = realPath; + free(realPath); + 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 0000000000000000000000000000000000000000..4159ec48649d7519155f2bf8b618a7508a4377e1 --- /dev/null +++ b/interfaces/kits/js/src/mod_file/class_file/file_n_exporter.h @@ -0,0 +1,200 @@ +/* + * 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_FILE_CLASS_FILE_FILE_N_EXPORTER_H +#define INTERFACES_KITS_JS_SRC_MOD_FILE_CLASS_FILE_FILE_N_EXPORTER_H + +#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 +#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.cpp b/interfaces/kits/js/src/mod_file/common_func.cpp new file mode 100644 index 0000000000000000000000000000000000000000..71b76d325bbc81323f9bab5380316ec5f8d82843 --- /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 0000000000000000000000000000000000000000..57e1cd4b210db28a569f7cbe16610466b7c1aca7 --- /dev/null +++ b/interfaces/kits/js/src/mod_file/common_func.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_FILE_COMMON_FUNC_H +#define INTERFACES_KITS_JS_SRC_MOD_FILE_COMMON_FUNC_H + +#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 +#endif // INTERFACES_KITS_JS_SRC_MOD_FILE_COMMON_FUNC_H \ 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 0000000000000000000000000000000000000000..6defa937f97fcb345b47afdeddd7957dbbadf02c --- /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 0000000000000000000000000000000000000000..0cde079cfe8cf992b3278c4b6fababb0ca0f1f94 --- /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 0000000000000000000000000000000000000000..63033a7cee6b2012c656b7817241b90ff065f690 --- /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 0000000000000000000000000000000000000000..b6b2eb78ad1f72b7f13fa1063d6335f42c004e78 --- /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 0000000000000000000000000000000000000000..03b048083910c7de09e661c9c8ce0170be13f64c --- /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 0000000000000000000000000000000000000000..bd69604b502a2244a9e8e628323746a92aa5e9bb --- /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 0000000000000000000000000000000000000000..d92fa69a2276f6d05a5c258300c07edb9c6a390e --- /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 0000000000000000000000000000000000000000..2bed8536955351153cb7b845bd09b4189147ccc1 --- /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 0000000000000000000000000000000000000000..0f60629e09429656f044da1090fa5974c116b994 --- /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 0000000000000000000000000000000000000000..a82c30f75045c77dbeb05fbf65bc501e6d3a7c31 --- /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 0000000000000000000000000000000000000000..57c33c6bc64a980443b460535de7f82ea0500e3e --- /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 0000000000000000000000000000000000000000..4304856649cc81f9e6b455207e98a3f1dc6b208b --- /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 0000000000000000000000000000000000000000..590b47e95eea7e25a8e5c85fa91c23764ca2300c --- /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 0000000000000000000000000000000000000000..c616571b3f8c3435cbb0ea2bd336661f18bff024 --- /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 0000000000000000000000000000000000000000..1c010e0152f224dbfd129bf1f3351f0f79cdb081 --- /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 0000000000000000000000000000000000000000..947b858d5e380c3efd42f0d6a8e6bc49b26398e2 --- /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 0000000000000000000000000000000000000000..3cfe4d2d204f21f3481e4518094bae338f7bede8 --- /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 0000000000000000000000000000000000000000..29a2c204a639353eb95b645c1b0d4e43ae619c0d --- /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 0000000000000000000000000000000000000000..588c4f22b8bf6a87e681a10a56ce3763f8442687 --- /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 0000000000000000000000000000000000000000..d5492cd1843c440540eecf9005a1211c1fb69bfc --- /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 0000000000000000000000000000000000000000..5f834a46460ea6e7193c37af7e07145dc24ace3e --- /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 0000000000000000000000000000000000000000..d952ac5174de01d78bf15c98ec66eab1cc3cb026 --- /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 0000000000000000000000000000000000000000..51bd91fd03f73edb66e6f11f8baf9335e6633b5f --- /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 0000000000000000000000000000000000000000..781dcc5473936f6596b8ae01ac42cd6032115015 --- /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 0000000000000000000000000000000000000000..825289198b788ae310362e2850ff1e508e4dfe4f --- /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 0000000000000000000000000000000000000000..dfffbb80123fb04992b04feaead9203a86bacedc --- /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 0000000000000000000000000000000000000000..5ac00ec2fa502fa6f1bb70227a6e28c8f12dcf0b --- /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 0000000000000000000000000000000000000000..32865b6f97190beac184a3a179b9b195c081f99d --- /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 0000000000000000000000000000000000000000..6d6a3964682a2e10c6f29306fea72a396b9544a0 --- /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 0000000000000000000000000000000000000000..6a6dd5aa3dfc013331c7c3d07cd3fdfd81050f01 --- /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 0000000000000000000000000000000000000000..bef01ef1e7a6d0ee54ad37903525210be32e9d98 --- /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 0000000000000000000000000000000000000000..18c03721257830ecd113a3e0e53f0f7fbdade41a --- /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 0000000000000000000000000000000000000000..7c58fa744a9dbb7a0e85d3c7e7258b4695c8c13c --- /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 0000000000000000000000000000000000000000..304268d7317312bbf93488d6bfcc2950b2ad6084 --- /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 0000000000000000000000000000000000000000..eb7711822870984742d1190bedfb61200768b2d6 --- /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 0000000000000000000000000000000000000000..bbc2c8e7e9b9699f66f90b1547947f79f6e98040 --- /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 0000000000000000000000000000000000000000..7439f2e542f346eeb6f8c9affaca8f3a8705e752 --- /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 0000000000000000000000000000000000000000..95928385ae8b285ca2231324a5ea9733e2b8e60e --- /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 0000000000000000000000000000000000000000..f10fcbde3a1faa694680ef8ce97aaba17824e65f --- /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 0000000000000000000000000000000000000000..2baf3938682eeda101f6a917f43f1ff384a5b165 --- /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 0000000000000000000000000000000000000000..195369eceec8a73a7278380675ae64be6a358626 --- /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 0000000000000000000000000000000000000000..6479cdf42d2747602aacdfa0a1b2e65e41f58357 --- /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 0000000000000000000000000000000000000000..27395df81e9d5802c873d5c7be42b066fc254640 --- /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 0000000000000000000000000000000000000000..9e4afdc5e4d29c3f5a9f43dc2a8da458f76235f2 --- /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 0000000000000000000000000000000000000000..0e2a54e040fd05388608de6d0bc3a38ad264c868 --- /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 0000000000000000000000000000000000000000..49e20393eecebb543e67bf924e972ddae5dd5453 --- /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 0000000000000000000000000000000000000000..f9d076efc337ce69f6ea7d804d07a580964b1c91 --- /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 0000000000000000000000000000000000000000..8497c26949ae5f4522b67c3bdd0af030cb4cd187 --- /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 0000000000000000000000000000000000000000..8aca34ce1315691044ee8e86d9605a104a8c07d1 --- /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 0000000000000000000000000000000000000000..61ed53d35e3a51cca654474dd4daa2edb40347f0 --- /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 0000000000000000000000000000000000000000..c13ad09673d250a4185c7b6ca36cbb0fef0896be --- /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 0000000000000000000000000000000000000000..8b2cacd8e50001b3a07ecbe847c53c131cc9ce27 --- /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 0000000000000000000000000000000000000000..f287a24e75023561a4227eab08be337b337ded7e --- /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 0000000000000000000000000000000000000000..6081a68ec2be3f9723e613a6b486f2fa6ebe88e2 --- /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 0000000000000000000000000000000000000000..b8ffb861cb7b6daa8193e42dd1fee4d659c1d018 --- /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 0000000000000000000000000000000000000000..b74502ad62205337500412c9131cd0f79eeddfbc --- /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 0000000000000000000000000000000000000000..6bd24beff996b5bfc26c1caec660f5c57cd8e242 --- /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 0000000000000000000000000000000000000000..fa914602d0ea82430eba72447a4e2e25a7c8d187 --- /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 0000000000000000000000000000000000000000..de9a7aed1df9d29d2737ea623ce7059ce388a93d --- /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 0000000000000000000000000000000000000000..f16bd6d905c8a587da586d00f47d65c8cc96e5a0 --- /dev/null +++ b/interfaces/kits/js/src/mod_fileio/properties/open.cpp @@ -0,0 +1,179 @@ +/* + * 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; + +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); + + 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; + } + } + (void)AdaptToAbi(flags); + 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; + } + } + (void)AdaptToAbi(flags); + 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 0000000000000000000000000000000000000000..f6b6d718cb0f58c91b30071ac11a87459fc8f765 --- /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 0000000000000000000000000000000000000000..8dedf72214e9c5cc8dda3df8525bc48cd600d18e --- /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 0000000000000000000000000000000000000000..e2e07d3b068ca8b5f40d7c98b0eef91a0abcf57d --- /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 0000000000000000000000000000000000000000..84a86dcc620112b575eed0f1c11e914458c7778a --- /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 0000000000000000000000000000000000000000..c26c70465bb28497c41c39f884f78d85f40f4bcf --- /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 0000000000000000000000000000000000000000..36b4c92efd9867050c2e39600ec968457259244b --- /dev/null +++ b/interfaces/kits/js/src/mod_fileio/properties/prop_n_exporter.cpp @@ -0,0 +1,760 @@ +/* + * 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; +namespace { + static constexpr int MODE_RUO_RWX = 0775; +} +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(), MODE_RUO_RWX); + } 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 0000000000000000000000000000000000000000..ad9f99ffe68703bd896766498d8a201006f0a62b --- /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 0000000000000000000000000000000000000000..6db024c83463bd3403efc002f2861b1cfe1743a9 --- /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 0000000000000000000000000000000000000000..8821437732bc7ef7235a5785b4e5bce5346f5aec --- /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 0000000000000000000000000000000000000000..78fb5a2af3f873ecf90b3ec98ade32040083c04e --- /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 0000000000000000000000000000000000000000..0333170a66be1f5666ae5f17de6856d0bbf4e81c --- /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 0000000000000000000000000000000000000000..4a9797c4938a8ccb0b5c85e77f09309721d62145 --- /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 0000000000000000000000000000000000000000..6e6e7bffeeda510f10ff9a79a5d08a8d7b830c4c --- /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 0000000000000000000000000000000000000000..029acad9ffb5b208adaa8d435c8e7685c7345d73 --- /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 0000000000000000000000000000000000000000..8b16373e9b313c97cbfb9c3c21c06cf521edb82f --- /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 0000000000000000000000000000000000000000..20180cbdfd98156a9021fef840c346e23c4c59d0 --- /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 0000000000000000000000000000000000000000..b770a27e874c3392e3ae46e112a6342140ed06f7 --- /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 0000000000000000000000000000000000000000..f07084b23432005a30dd16ea51d55746ef0fdf65 --- /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 0000000000000000000000000000000000000000..b4f32e0264947345ea5803bec3148181aabf347f --- /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 0000000000000000000000000000000000000000..1b3def21cdf0af2964339298b8bc08108223868d --- /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 0000000000000000000000000000000000000000..45c100cb21057e0a0711212df5ec9846985aebaf --- /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 0000000000000000000000000000000000000000..743babf0f9973b9fff3f25aa6f12fa231e033200 --- /dev/null +++ b/interfaces/kits/js/src/mod_securitylabel/security_label.h @@ -0,0 +1,76 @@ +/* + * 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 { +} // 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) { + 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 \ No newline at end of file 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 0000000000000000000000000000000000000000..49abd6f5092c3260631a620208b0a803f461d6ef --- /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 0000000000000000000000000000000000000000..0de9959ed8be231f723918bc41069b303b16d2af --- /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 0000000000000000000000000000000000000000..dde3f5e5f6802c4661c48ee2c602a0e663f62da6 --- /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 0000000000000000000000000000000000000000..66c52dff93941252042c59007c177ceca076099c --- /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 ff857cb08a246a976458742cddd2a4e9cf968744..0acf61a3d71a885f3a3ec8dbca5810f52281d7d7 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 ddee8c66441c6fd5f127aecc766efb072246f7d3..dd25b1724926781155cab9fd431acff1d11309bf 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 e25fddf191f05009858636c1a4a9a6b336367a8a..0ec3891e96fe0de8c1fd6d7e84992a79e4230e41 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 a08b1f28111acd81ffff5b015b06fbee906ecb82..1af18b97adff1266ee79dbd8754a26a5d5e06e84 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/utils/filemgmt_libhilog/BUILD.gn b/utils/filemgmt_libhilog/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..48d6be334cf7f4e47a20996d4c4c68d688263a8e --- /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 0000000000000000000000000000000000000000..0cdf4267e4d82450aa3773bfdd8c8ea8dbd39eb0 --- /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 0000000000000000000000000000000000000000..ffb8aafc0d804376588bdfe1d7ccbe9faa8b1214 --- /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 0000000000000000000000000000000000000000..28b1a8e856ef381ba9c5f58df8a34f824e584cac --- /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 0000000000000000000000000000000000000000..fb092495548b8f05b35087afe38a25c19c35bdb0 --- /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 0000000000000000000000000000000000000000..d3bf6f7a97a419f96dbf463022e8091292004d0e --- /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 0000000000000000000000000000000000000000..938a2d7099bd06ebdcb4450a0f274fba92967a2e --- /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 0000000000000000000000000000000000000000..2703a846151c26ccea97a79b581d6e02b02bfbd3 --- /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 0000000000000000000000000000000000000000..2526d009957bcbb0e1950bc8dc73d89fe74fc1dd --- /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 0000000000000000000000000000000000000000..c4d8cae191c7193d7ca45b05a1017610036d89d3 --- /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 0000000000000000000000000000000000000000..0241fcc60df47dd545e9a647d423b9fbe1bc1b49 --- /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 0000000000000000000000000000000000000000..ec64e7aa219a1fd9aa42d182beea794567dccc70 --- /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 0000000000000000000000000000000000000000..271ad7a956c7b6907a661dde555c344307c8b8d7 --- /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 0000000000000000000000000000000000000000..61704ef6db0fe0f8e564f036ab662ee1dba7e1a8 --- /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 0000000000000000000000000000000000000000..aa480d5abe27059cf1714ba9dbc839409e3c39f8 --- /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 0000000000000000000000000000000000000000..d7a67934b680f80a6c302a73bfdfacbb5259eb98 --- /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 0000000000000000000000000000000000000000..443c450efd521541549d5cfe136235f714c94765 --- /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 0000000000000000000000000000000000000000..bd5ebc900d645131e24dd36c71b14bf87a0bcadc --- /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 0000000000000000000000000000000000000000..45a6f56ed85928552f95e739e2fdcdb6b7e7fd05 --- /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 0000000000000000000000000000000000000000..88fff79c06db7d291464396d61cbb1a55167c408 --- /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 0000000000000000000000000000000000000000..0e4fdfc47739ac5e52c13f66c873c20b215e08ea --- /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 0000000000000000000000000000000000000000..7ecb4e15d3e25d383037bb3dcab9fb42fc2359ce --- /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