diff --git a/bundle.json b/bundle.json index d81e5f73a9067cf8bbc51de3e9539ff9991670e6..4e053079943df38a3960c495baebc94cefbd9d9a 100644 --- a/bundle.json +++ b/bundle.json @@ -37,6 +37,7 @@ "ipc", "init", "napi", + "runtime_core", "safwk", "samgr", "storage_service", @@ -67,6 +68,8 @@ "//foundation/filemanagement/app_file_service/interfaces/kits/js:fileshare", "//foundation/filemanagement/app_file_service/interfaces/kits/js:fileuri", "//foundation/filemanagement/app_file_service/interfaces/kits/js:backup", + "//foundation/filemanagement/app_file_service/interfaces/kits/ani/file_share:fileshare_ani_package", + "//foundation/filemanagement/app_file_service/interfaces/kits/ani/file_uri:fileuri_ani_package", "//foundation/filemanagement/app_file_service/interfaces/kits/ndk/fileuri/src:ohfileuri", "//foundation/filemanagement/app_file_service/interfaces/kits/ndk/fileshare/src:ohfileshare" ], diff --git a/interfaces/kits/ani/file_share/BUILD.gn b/interfaces/kits/ani/file_share/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..772e9e2591adec8eb005bfdaf1e5bf43b24fa735 --- /dev/null +++ b/interfaces/kits/ani/file_share/BUILD.gn @@ -0,0 +1,88 @@ +# Copyright (c) 2025 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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/config/components/ets_frontend/ets2abc_config.gni") +import("//build/ohos.gni") +import("//foundation/filemanagement/app_file_service/app_file_service.gni") + +ohos_shared_library("fileshare_ani") { + branch_protector_ret = "pac_ret" + sanitize = { + boundary_sanitize = true + ubsan = true + cfi = true + cfi_cross_dso = true + debug = false + } + + cflags_cc = [ "-Wno-unused-function" ] + sources = [ "src/ani_file_share.cpp" ] + + include_dirs = [ + "include", + "../../../common/include", + "${app_file_service_path}/interfaces/innerkits/native/file_share/include", + ] + + deps = + [ "${app_file_service_path}/interfaces/innerkits/native:fileuri_native" ] + + external_deps = [ + "ability_base:want", + "ability_base:zuri", + "ability_runtime:abilitykit_native", + "ability_runtime:extensionkit_native", + "ability_runtime:uri_permission_mgr", + "access_token:libaccesstoken_sdk", + "access_token:libtokenid_sdk", + "bundle_framework:appexecfwk_base", + "c_utils:utils", + "common_event_service:cesfwk_innerkits", + "data_share:datashare_common", + "data_share:datashare_consumer", + "file_api:filemgmt_libhilog", + "file_api:filemgmt_libn", + "file_api:remote_uri_native", + "hilog:libhilog", + "init:libbegetutil", + "ipc:ipc_core", + "runtime_core:ani", + ] + part_name = "app_file_service" + subsystem_name = "filemanagement" + output_extension = "so" +} + +generate_static_abc("fileshare_abc") { + base_url = "./ets" + files = [ "./ets/@ohos.fileshare.ets" ] + dst_file = "$target_out_dir/fileshare.abc" + out_puts = [ "$target_out_dir/fileshare.abc" ] + is_boot_abc = "True" + device_dst_file = "/system/framework/fileshare.abc" +} + +ohos_prebuilt_etc("fileshare_abc_etc") { + source = "$target_out_dir/fileshare.abc" + module_install_dir = "framework" + subsystem_name = "filemanagement" + part_name = "app_file_service" + deps = [ ":fileshare_abc" ] +} + +group("fileshare_ani_package") { + deps = [ + ":fileshare_abc_etc", + ":fileshare_ani", + ] +} diff --git a/interfaces/kits/ani/file_share/ets/@ohos.fileshare.ets b/interfaces/kits/ani/file_share/ets/@ohos.fileshare.ets new file mode 100644 index 0000000000000000000000000000000000000000..caa55189da14107d7eaf4002374d6a8c09c2d072 --- /dev/null +++ b/interfaces/kits/ani/file_share/ets/@ohos.fileshare.ets @@ -0,0 +1,59 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 type { AsyncCallback } from '@ohos.base'; +import { BusinessError } from '@ohos.base'; +import type wantConstant from '@ohos.app.ability.wantConstant'; + +export namespace fileShare { + loadLibrary("fileshare_ani") + + export function grantUriPermission(uri: string, bundleName: string, flag: wantConstant.Flags, + callback: AsyncCallback): void { + console.log("Start grantUriPermission in callback main thread."); + let p1 = taskpool.execute(grantUriPermissionSync, uri, bundleName, flag); + p1.then((err: NullishType) => { + let error: BusinessError; + callback(error, undefined); + }); + p1.catch((err: NullishType) => { + console.log("grantUriPermission catch in callback thread."); + let error: BusinessError; + callback(error, undefined); + }); + } + + export function grantUriPermission(uri: string, bundleName: string, flag: wantConstant.Flags): Promise { + console.log("Start grantUriPermission in promise main thread"); + let p = new Promise((resolve: (value: undefined) => void, reject: (error: Object) => void): void => { + let p1 = taskpool.execute(grantUriPermissionSync, uri, bundleName, flag); + p1.then((e: NullishType): void => { + resolve(undefined); + }); + p1.catch((e: Error): void => { + console.log("grantUriPermission catch in promise thread."); + reject(e); + }); + }); + return p; + } + + export function grantUriPermissionSync(uri: string, bundleName: string, flag: wantConstant.Flags):int { + console.log("Start grantUriPermissionSync in thread."); + grantUriPermissionInner(uri, bundleName, flag); + return 0; + } + native function grantUriPermissionInner(uri: string, bundleName: string, flag: wantConstant.Flags):void; +} diff --git a/interfaces/kits/ani/file_share/include/ani_file_share.h b/interfaces/kits/ani/file_share/include/ani_file_share.h new file mode 100644 index 0000000000000000000000000000000000000000..86e1ac8f1588a60a46d7b177452cf099436f7bf6 --- /dev/null +++ b/interfaces/kits/ani/file_share/include/ani_file_share.h @@ -0,0 +1,69 @@ + /* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 ANI_FILE_SHARE_H +#define ANI_FILE_SHARE_H + +#include +#include "iremote_broker.h" + +namespace OHOS { +namespace AppFileService { +namespace ModuleFileShare { + +const std::string MEDIA_GRANT_URI_PERMISSION = + "datashare:///media/bundle_permission_insert_operation/bundle_permission_insert_operation"; +const std::string MEDIALIBRARY_DATA_URI = "datashare:///media"; +const std::string MEDIA_FILEMODE_READONLY = "r"; +const std::string GRANT_URI_NAME = "file_share_grant_uri_permission"; +const std::string MEDIA_API_VERSION_10 = "?api_version=10"; +const std::string PERMISSION_BUNDLE_NAME = "bundle_name"; +const std::string PERMISSION_FILE_ID = "file_id"; +const std::string PERMISSION_MODE = "mode"; +const std::string MEDIA_AUTHORITY = "media"; +const std::string FILE_SCHEME = "file"; +const std::string PERMISSION_TABLE_TYPE = "table_type"; +const std::string FILE_MANAGER_AUTHORITY = "docs"; +const std::string MEDIA_FILE_URI_PHOTO_PREFEX = "file://media/Photo/"; +const std::string MEDIA_FILE_URI_AUDIO_PREFEX = "file://media/Audio/"; +const std::string MEDIA_FILE_URI_VIDEO_PREFEX = "file://media/video/"; +const std::string MEDIA_FILE_URI_IMAGE_PREFEX = "file://media/image/"; +const std::string MEDIA_FILE_URI_FILE_PREFEX = "file://media/file/"; +const std::string MEDIA_FILE_URI_Audio_PREFEX = "file://media/audio/"; + +class FileShareGrantToken : public IRemoteBroker { +public: + DECLARE_INTERFACE_DESCRIPTOR(u"ohos.fileshare.grantUriPermission"); + + FileShareGrantToken() = default; + virtual ~FileShareGrantToken() noexcept = default; +}; + +enum MediaFileTable { + FILE_TABLE = 0, + PHOTO_TABLE = 1, + AUDIO_TABLE = 2, +}; + +struct UriPermissionInfo { + unsigned int flag; + std::string mode; + std::string bundleName; + std::string uri; +}; + +} // namespace ModuleFileShare +} // namespace AppFileService +} // namespace OHOS +#endif // ANI_FILE_SHARE_H diff --git a/interfaces/kits/ani/file_share/src/ani_file_share.cpp b/interfaces/kits/ani/file_share/src/ani_file_share.cpp new file mode 100644 index 0000000000000000000000000000000000000000..800b8e50f7b3da4449617ee6a0488f351c87f41f --- /dev/null +++ b/interfaces/kits/ani/file_share/src/ani_file_share.cpp @@ -0,0 +1,299 @@ + /* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "ani_file_share.h" + +#include +#include +#include +#include "ability.h" +#include "datashare_helper.h" +#include "datashare_values_bucket.h" +#include "ipc_skeleton.h" +#include "log.h" +#include "remote_uri.h" +#include "tokenid_kit.h" +#include "uri.h" +#include "uri_permission_manager_client.h" +#include "want.h" + +using namespace OHOS::DataShare; +using namespace OHOS::DistributedFS::ModuleRemoteUri; + +namespace OHOS { +namespace AppFileService { +namespace ModuleFileShare { + +static std::string ParseObjToStr(ani_env *env, ani_string stringObj) +{ + ani_size strSize; + env->String_GetUTF8Size(stringObj, &strSize); + std::vector buffer(strSize + 1); + char* utf8Buffer = buffer.data(); + + ani_size byteswritten = 0; + env->String_GetUTF8(stringObj, utf8Buffer, strSize + 1, &byteswritten); + + utf8Buffer[byteswritten] = '\0'; + std::string path = std::string(utf8Buffer); + return path; +} + +static ani_int ParseEnumToInt(ani_env *env, ani_enum_item enumItem) +{ + ani_int intValue = -1; + if (ANI_OK != env->EnumItem_GetValue_Int(enumItem, &intValue)) { + LOGE("%{public}s: EnumItem_GetValue_Int FAILD.", __func__); + return -1; + } + LOGD("%{public}s: Enum Value: %{public}d.", __func__, intValue); + return intValue; +} + +static ani_error CreateAniError(ani_env *env, std::string&& errMsg) +{ + static const char *errorClsName = "Lescompat/Error;"; + ani_class cls {}; + if (ANI_OK != env->FindClass(errorClsName, &cls)) { + LOGE("%{public}s: Not found namespace %{public}s.", __func__, errorClsName); + return nullptr; + } + ani_method ctor; + if (ANI_OK != env->Class_FindMethod(cls, "", "Lstd/core/String;:V", &ctor)) { + LOGE("%{public}s: Not found in %{public}s.", __func__, errorClsName); + return nullptr; + } + ani_string error_msg; + env->String_NewUTF8(errMsg.c_str(), 17U, &error_msg); + ani_object errorObject; + env->Object_New(cls, ctor, &errorObject, error_msg); + return static_cast(errorObject); +} + +static bool IsSystemApp() +{ + uint64_t fullTokenId = OHOS::IPCSkeleton::GetCallingFullTokenID(); + return OHOS::Security::AccessToken::TokenIdKit::IsSystemAppByFullTokenID(fullTokenId); +} + +static int32_t GetIdFromUri(string uri) +{ + std::replace(uri.begin(), uri.end(), '/', ' '); + std::stringstream ss(uri); + std::string tmp; + int fileId = -1; + ss >> tmp >> tmp >> tmp >> fileId; + return fileId; +} + +static bool CheckValidPublicUri(const std::string &inputUri) +{ + Uri uri(inputUri); + std::string scheme = uri.GetScheme(); + if (scheme != FILE_SCHEME) { + return false; + } + + std::string authority = uri.GetAuthority(); + if (authority != MEDIA_AUTHORITY && authority != FILE_MANAGER_AUTHORITY) { + return false; + } + + return true; +} + +static std::string GetModeFromFlag(unsigned int flag) +{ + std::string mode = ""; + if (flag & OHOS::AAFwk::Want::FLAG_AUTH_READ_URI_PERMISSION) { + mode += "r"; + } + if (flag & OHOS::AAFwk::Want::FLAG_AUTH_WRITE_URI_PERMISSION) { + mode += "w"; + } + return mode; +} + +static int32_t GetMediaTypeAndApiFromUri(const std::string &uri, bool &isApi10) +{ + if (uri.find(MEDIA_FILE_URI_PHOTO_PREFEX) == 0) { + isApi10 = true; + return MediaFileTable::PHOTO_TABLE; + } else if (uri.find(MEDIA_FILE_URI_VIDEO_PREFEX) == 0 || + uri.find(MEDIA_FILE_URI_IMAGE_PREFEX) == 0) { + return MediaFileTable::PHOTO_TABLE; + } else if (uri.find(MEDIA_FILE_URI_AUDIO_PREFEX) == 0) { + isApi10 = true; + return MediaFileTable::AUDIO_TABLE; + } else if (uri.find(MEDIA_FILE_URI_Audio_PREFEX) == 0) { + return MediaFileTable::AUDIO_TABLE; + } else if (uri.find(MEDIA_FILE_URI_FILE_PREFEX) == 0) { + return MediaFileTable::FILE_TABLE; + } + + return MediaFileTable::FILE_TABLE; +} + +static int InitValuesBucket(const UriPermissionInfo &uriPermInfo, Uri &uri, bool &isApi10, + DataShareValuesBucket &valuesBucket) +{ + int32_t fileId = GetIdFromUri(uriPermInfo.uri); + if (fileId == -1) { + LOGE("%{public}s: get fileId parameter failed!", __func__); + return -EINVAL; + } + + int32_t filesType = GetMediaTypeAndApiFromUri(uri.ToString(), isApi10); + valuesBucket.Put(PERMISSION_FILE_ID, fileId); + valuesBucket.Put(PERMISSION_BUNDLE_NAME, uriPermInfo.bundleName); + valuesBucket.Put(PERMISSION_MODE, uriPermInfo.mode); + valuesBucket.Put(PERMISSION_TABLE_TYPE, filesType); + return 0; +} + +static int InsertByDatashare(const DataShareValuesBucket &valuesBucket, bool isApi10) +{ + int ret = -1; + std::shared_ptr dataShareHelper = nullptr; + sptr remote = new IRemoteStub(); + if (remote == nullptr) { + LOGE("%{public}s: get remoteObject failed!", __func__); + return -ret; + } + + dataShareHelper = DataShare::DataShareHelper::Creator(remote->AsObject(), MEDIALIBRARY_DATA_URI); + if (!dataShareHelper) { + LOGE("%{public}s: connect to datashare failed!", __func__); + return ret; + } + string uriStr = MEDIA_GRANT_URI_PERMISSION; + if (isApi10) { + uriStr += MEDIA_API_VERSION_10; + } + + Uri uri(uriStr); + ret = dataShareHelper->Insert(uri, valuesBucket); + if (ret < 0) { + LOGE("%{public}s: insert failed with error code %{public}d!", __func__, ret); + return ret; + } + return ret; +} + +static int GrantInMediaLibrary(const UriPermissionInfo &uriPermInfo, Uri &uri) +{ + bool isApi10 = false; + DataShareValuesBucket valuesBucket; + int ret = InitValuesBucket(uriPermInfo, uri, isApi10, valuesBucket); + if (ret < 0) { + LOGE("%{public}s: InitValuesBucket failed!", __func__); + return ret; + } + + ret = InsertByDatashare(valuesBucket, isApi10); + if (ret < 0) { + LOGE("%{public}s: InsertByDatashare failed!", __func__); + return ret; + } + return 0; +} + +static int DoGrantUriPermission(const UriPermissionInfo &uriPermInfo) +{ + Uri uri(uriPermInfo.uri); + std::string authority = uri.GetAuthority(); + std::string path = uri.GetPath(); + if (authority == MEDIA_AUTHORITY && path.find(".") == string::npos) { + return GrantInMediaLibrary(uriPermInfo, uri); + } else { + auto& uriPermissionClient = OHOS::AAFwk::UriPermissionManagerClient::GetInstance(); + int ret = uriPermissionClient.GrantUriPermission(uri, uriPermInfo.flag, uriPermInfo.bundleName); + if (ret != 0) { + LOGD("%{public}s: uriPermissionClient.GrantUriPermission by uri permission client failed!", __func__); + return GrantInMediaLibrary(uriPermInfo, uri); + } + } + + return 0; +} + +static void GrantUriPermission(ani_env *env, ani_string uri, ani_string bundleName, ani_object enumIndex) +{ + LOGD("Enter GrantUriPermission."); + if (!IsSystemApp()) { + LOGE("%{public}s: GrantUriPermission is not System App!", __func__); + ani_error error = CreateAniError(env, "GrantUriPermission is not System App!"); + env->ThrowError(error); + return; + } + + UriPermissionInfo uriPermInfo; + std::string uriStr = ParseObjToStr(env, uri); + if (!CheckValidPublicUri(uriStr)) { + LOGE("%{public}s: GrantUriPermission uri is not valid!", __func__); + ani_error error = CreateAniError(env, "GrantUriPermission uri is not valid!"); + env->ThrowError(error); + return; + } + uriPermInfo.uri = uriStr; + std::string bundleNameStr = ParseObjToStr(env, bundleName); + uriPermInfo.bundleName = bundleNameStr; + + ani_int wantConstantFlag = ParseEnumToInt(env, static_cast(enumIndex)); + if (wantConstantFlag < 0) { + LOGE("%{public}s: GrantUriPermission ParseEnumToInt Faild!", __func__); + ani_error error = CreateAniError(env, "GrantUriPermission ParseEnumToInt Faild!"); + env->ThrowError(error); + return; + } + uriPermInfo.flag = wantConstantFlag; + uriPermInfo.mode = GetModeFromFlag(wantConstantFlag); + LOGD("GrantUriPermission uri: %{public}s, bundleName: %{public}s, flag: %{public}d, mode: %{public}s", + uriStr.c_str(), bundleNameStr.c_str(), wantConstantFlag, uriPermInfo.mode.c_str()); + + int ret = DoGrantUriPermission(uriPermInfo); + LOGD("DoGrantUriPermission ret: %{public}d.", ret); +} +} // namespace ModuleFileShare +} // namespace AppFileService +} // namespace OHOS + +ANI_EXPORT ani_status ANI_Constructor(ani_vm *vm, uint32_t *result) +{ + LOGD("Enter ANI_Constructor."); + ani_env *env; + if (ANI_OK != vm->GetEnv(ANI_VERSION_1, &env)) { + LOGE("Unsupported ANI_VERSION_1"); + return ANI_ERROR; + } + + static const char *nsName = "L@ohos/fileshare/fileShare;"; + ani_namespace ns; + if (ANI_OK != env->FindNamespace(nsName, &ns)) { + LOGE("Not found namespace %{public}s.", nsName); + return ANI_NOT_FOUND; + } + std::array nsMethods = { + ani_native_function {"grantUriPermissionInner", nullptr, + reinterpret_cast(OHOS::AppFileService::ModuleFileShare::GrantUriPermission)}, + }; + if (ANI_OK != env->Namespace_BindNativeFunctions(ns, nsMethods.data(), nsMethods.size())) { + LOGE("Cannot bind native methods to namespace %{public}s.", nsName); + return ANI_ERROR; + }; + + *result = ANI_VERSION_1; + return ANI_OK; +} diff --git a/interfaces/kits/ani/file_uri/BUILD.gn b/interfaces/kits/ani/file_uri/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..c3545159d00f886955e9eb735f777a1e5335bde7 --- /dev/null +++ b/interfaces/kits/ani/file_uri/BUILD.gn @@ -0,0 +1,82 @@ +# Copyright (c) 2025 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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/config/components/ets_frontend/ets2abc_config.gni") +import("//build/ohos.gni") +import("//foundation/filemanagement/app_file_service/app_file_service.gni") + +ohos_shared_library("fileuri_ani") { + branch_protector_ret = "pac_ret" + sanitize = { + boundary_sanitize = true + ubsan = true + cfi = true + cfi_cross_dso = true + debug = false + } + + cflags_cc = [ "-Wno-unused-function" ] + sources = [ + "../../../common/src/common_func.cpp", + "src/ani_file_uri.cpp", + ] + + include_dirs = [ + "../../../common/include", + "../../js/file_uri", + "${app_file_service_path}/interfaces/innerkits/native/file_uri/include", + ] + + deps = + [ "${app_file_service_path}/interfaces/innerkits/native:fileuri_native" ] + + external_deps = [ + "ability_base:zuri", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", + "c_utils:utils", + "file_api:filemgmt_libhilog", + "file_api:filemgmt_libn", + "hilog:libhilog", + "ipc:ipc_core", + "runtime_core:ani", + "samgr:samgr_proxy", + ] + part_name = "app_file_service" + subsystem_name = "filemanagement" + output_extension = "so" +} + +generate_static_abc("fileuri_abc") { + base_url = "./ets" + files = [ "./ets/@ohos.file.fileuri.ets" ] + dst_file = "$target_out_dir/fileuri.abc" + out_puts = [ "$target_out_dir/fileuri.abc" ] + is_boot_abc = "True" + device_dst_file = "/system/framework/fileuri.abc" +} + +ohos_prebuilt_etc("fileuri_abc_etc") { + source = "$target_out_dir/fileuri.abc" + module_install_dir = "framework" + subsystem_name = "filemanagement" + part_name = "app_file_service" + deps = [ ":fileuri_abc" ] +} + +group("fileuri_ani_package") { + deps = [ + ":fileuri_abc_etc", + ":fileuri_ani", + ] +} diff --git a/interfaces/kits/ani/file_uri/ets/@ohos.file.fileuri.ets b/interfaces/kits/ani/file_uri/ets/@ohos.file.fileuri.ets new file mode 100644 index 0000000000000000000000000000000000000000..0e2afd40d0c038872e9f471288604940881990e9 --- /dev/null +++ b/interfaces/kits/ani/file_uri/ets/@ohos.file.fileuri.ets @@ -0,0 +1,33 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 uri from '@ohos.uri'; + +export default namespace fileUri { + loadLibrary("fileuri_ani") + + export class FileUri { + native constructor(uriOrPath: string); + getFileUriEntity():long { + return this.fileUriEntity_; + } + + private fileUriEntity_: long = 0; + private acquireFileUriEntity(fileUriEntity: long) { + this.fileUriEntity_ = fileUriEntity; + } + }; + export native function getUriFromPath(path: string): string; +} diff --git a/interfaces/kits/ani/file_uri/src/ani_file_uri.cpp b/interfaces/kits/ani/file_uri/src/ani_file_uri.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ee5c314bdde9041ae7aa3dd306441c026585f728 --- /dev/null +++ b/interfaces/kits/ani/file_uri/src/ani_file_uri.cpp @@ -0,0 +1,187 @@ + /* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 +#include "common_func.h" +#include "file_uri_entity.h" +#include "file_utils.h" +#include "log.h" + +using namespace OHOS::AppFileService; + +static std::string ParseObjToStr(ani_env *env, ani_string stringObj) +{ + ani_size strSize; + env->String_GetUTF8Size(stringObj, &strSize); + std::vector buffer(strSize + 1); + char* utf8Buffer = buffer.data(); + + ani_size byteswritten = 0; + env->String_GetUTF8(stringObj, utf8Buffer, strSize + 1, &byteswritten); + + utf8Buffer[byteswritten] = '\0'; + std::string path = std::string(utf8Buffer); + return path; +} + +static ModuleFileUri::FileUriEntity *unwrapp(ani_env *env, ani_object object) +{ + ani_long fileuriEntity_; + if (ANI_OK != env->Object_GetFieldByName_Long(object, "fileUriEntity_", &fileuriEntity_)) { + return nullptr; + } + return reinterpret_cast(fileuriEntity_); +} + +static ani_error CreateAniError(ani_env *env, std::string&& errMsg) +{ + static const char *errorClsName = "Lescompat/Error;"; + ani_class cls {}; + if (ANI_OK != env->FindClass(errorClsName, &cls)) { + LOGE("Not found %{public}s.", errorClsName); + return nullptr; + } + ani_method ctor; + if (ANI_OK != env->Class_FindMethod(cls, "", "Lstd/core/String;:V", &ctor)) { + LOGE("Not found method in %{public}s.", errorClsName); + return nullptr; + } + ani_string error_msg; + env->String_NewUTF8(errMsg.c_str(), 17U, &error_msg); + ani_object errorObject; + env->Object_New(cls, ctor, &errorObject, error_msg); + return static_cast(errorObject); +} + +static ani_string GetUriFromPath(ani_env *env, ani_string stringObj) +{ + LOGD("Enter GetUriFromPath"); + ani_string uriObj = nullptr; + std::string path = ParseObjToStr(env, stringObj); + if (path == "") { + LOGE("GetUriFromPath get path parameter failed!"); + ani_error err = CreateAniError(env, "GetUriFromPath get path parameter failed!"); + env->ThrowError(err); + return uriObj; + } + + std::string uri = CommonFunc::GetUriFromPath(path); + if (uri == "") { + LOGE("CommonFunc::GetUriFromPath failed!"); + ani_error err = CreateAniError(env, "GetUriFromPath failed!"); + env->ThrowError(err); + return uriObj; + } + LOGD("GetUriFromPath uri: %{public}s", uri.c_str()); + + env->String_NewUTF8(uri.c_str(), uri.size(), &uriObj); + + return uriObj; +} + +void FileUriConstructor(ani_env *env, ani_object obj, ani_string stringObj) +{ + LOGD("Enter FileUriConstructor"); + std::string path = ParseObjToStr(env, stringObj); + if (path == "") { + LOGE("FileUriConstructor get path parameter failed!"); + ani_error err = CreateAniError(env, "GetUriFromPath get path parameter failed!"); + env->ThrowError(err); + return; + } + auto fileuriEntity = OHOS::FileManagement::CreateUniquePtr(path); + if (fileuriEntity == nullptr) { + LOGE("Failed to request heap memory."); + ani_error err = CreateAniError(env, "Failed to request heap memory."); + env->ThrowError(err); + return; + } + LOGD("FileUriConstructor fileuriEntity: %{public}p.", fileuriEntity.get()); + + ani_namespace ns; + if (env->FindNamespace("L@ohos/file/fileuri/fileUri;", &ns) != ANI_OK) { + LOGE("Namespace L@ohos/file/fileuri/fileUri not found."); + ani_error err = CreateAniError(env, "Namespace L@ohos/file/fileuri/fileUri not found."); + env->ThrowError(err); + return; + }; + + ani_class cls; + static const char *className = "LFileUri;"; + if (env->Namespace_FindClass(ns, className, &cls) != ANI_OK) { + LOGE("Not found class LFileUri in Namespace L@ohos/file/fileuri/fileUri."); + ani_error err = CreateAniError(env, "Class LFileUri not found."); + env->ThrowError(err); + return; + } + + ani_method acquireObj; + if (ANI_OK != env->Class_FindMethod(cls, "acquireFileUriEntity", "J:V", &acquireObj)) { + LOGE("Not found method acquireFileUriEntity in class LFileUri."); + ani_error err = CreateAniError(env, "Method acquireFileUriEntity not found."); + env->ThrowError(err); + return; + } + + if (ANI_OK != env->Object_CallMethod_Void(obj, acquireObj, reinterpret_cast(fileuriEntity.get()))) { + LOGE("Call method acquireFileUriEntity failed."); + ani_error err = CreateAniError(env, "Call method acquireFileUriEntity failed."); + env->ThrowError(err); + return; + } +} + +ANI_EXPORT ani_status ANI_Constructor(ani_vm *vm, uint32_t *result) +{ + LOGD("Enter ANI_Constructor."); + ani_env *env; + if (ANI_OK != vm->GetEnv(ANI_VERSION_1, &env)) { + LOGE("Unsupported ANI_VERSION_1"); + return ANI_ERROR; + } + + static const char *nsName = "L@ohos/file/fileuri/fileUri;"; + ani_namespace ns; + if (ANI_OK != env->FindNamespace(nsName, &ns)) { + LOGE("Not found namespace %{public}s.", nsName); + return ANI_NOT_FOUND; + } + std::array nsMethods = { + ani_native_function {"getUriFromPath", nullptr, reinterpret_cast(GetUriFromPath)}, + }; + if (ANI_OK != env->Namespace_BindNativeFunctions(ns, nsMethods.data(), nsMethods.size())) { + LOGE("Cannot bind native methods to namespace %{public}s.", nsName); + return ANI_ERROR; + }; + + static const char *className = "LFileUri;"; + ani_class fileUriClass; + if (ANI_OK != env->Namespace_FindClass(ns, className, &fileUriClass)) { + LOGE("Not found class %{public}s in %{public}s.", nsName, nsName); + return ANI_NOT_FOUND; + } + std::array classMethods = { + ani_native_function {"", "Lstd/core/String;:V", reinterpret_cast(FileUriConstructor)}, + }; + if (ANI_OK != env->Class_BindNativeMethods(fileUriClass, classMethods.data(), classMethods.size())) { + LOGE("Cannot bind native methods to class %{public}s.", className); + return ANI_ERROR; + }; + + *result = ANI_VERSION_1; + return ANI_OK; +}