feat:the last commit

Signed-off-by: caochuan <caochuan@huawei.com>
This commit is contained in:
caochuan 2023-06-07 08:47:41 +08:00
parent d2ce217240
commit 4a3e67227e
43 changed files with 897 additions and 266 deletions

View File

@ -26,6 +26,7 @@
"ability_runtime",
"ipc",
"samgr",
"safwk",
"napi",
"file_api",
"bundle_framework",
@ -34,7 +35,8 @@
"access_token",
"c_utils",
"image_framework",
"common_event_service"
"common_event_service",
"ability_tools"
]
},
"build": {

View File

@ -204,5 +204,21 @@ void InitCopyResult(napi_env env, napi_value exports)
sizeof(desc) / sizeof(*desc), desc, &obj);
napi_set_named_property(env, exports, className, obj);
}
void InitNotifyType(napi_env env, napi_value exports)
{
char className[] = "NotifyType";
napi_property_descriptor desc[] = {
DECLARE_NAPI_STATIC_PROPERTY("NOTIFY_ADD", NVal::CreateInt32(env, ADD_EVENT).val_),
DECLARE_NAPI_STATIC_PROPERTY("NOTIFY_DELETE", NVal::CreateInt32(env, DELETE_EVENT).val_),
DECLARE_NAPI_STATIC_PROPERTY("NOTIFY_MOVED_TO", NVal::CreateInt32(env, MOVED_TO).val_),
DECLARE_NAPI_STATIC_PROPERTY("NOTIFY_MOVED_FROM", NVal::CreateInt32(env, MOVED_FROM).val_),
DECLARE_NAPI_STATIC_PROPERTY("NOTIFY_MOVE_SELF", NVal::CreateInt32(env, MOVED_SELF).val_),
};
napi_value obj = nullptr;
napi_define_class(env, className, NAPI_AUTO_LENGTH, RootInfoConstructor, nullptr,
sizeof(desc) / sizeof(*desc), desc, &obj);
napi_set_named_property(env, exports, className, obj);
}
} // namespace FileAccessFwk
} // namespace OHOS

View File

@ -28,6 +28,7 @@ void InitRootInfo(napi_env env, napi_value exports);
void InitOpenFlags(napi_env env, napi_value exports);
void InitQueryFlags(napi_env env, napi_value exports);
void InitCopyResult(napi_env env, napi_value exports);
void InitNotifyType(napi_env env, napi_value exports);
} // namespace FileAccessFwk
} // namespace OHOS
#endif // FILE_EXTENSION_INFO_NAPI_H

View File

@ -35,13 +35,17 @@ ohos_shared_library("fileaccess") {
"file_info/napi_file_info_exporter.cpp",
"file_info/napi_file_iterator_exporter.cpp",
"napi_fileaccess_helper.cpp",
"napi_observer_callback.cpp",
"napi_utils.cpp",
"native_fileaccess_module.cpp",
"root_info/napi_root_info_exporter.cpp",
"root_info/napi_root_iterator_exporter.cpp",
]
deps = [ "${user_file_service_path}/interfaces/inner_api/file_access:file_access_extension_ability_kit" ]
deps = [
"${user_file_service_path}/interfaces/inner_api/file_access:file_access_extension_ability_kit",
"${user_file_service_path}/services:file_access_service",
]
external_deps = [
"ability_base:want",
@ -55,6 +59,7 @@ ohos_shared_library("fileaccess") {
"file_api:filemgmt_libn",
"hilog:libhilog",
"image_framework:image",
"ipc:ipc_core",
"napi:ace_napi",
]
}

View File

@ -240,8 +240,8 @@ napi_value FileAccessHelperInit(napi_env env, napi_value exports)
DECLARE_NAPI_FUNCTION("getFileInfoFromUri", NAPI_GetFileInfoFromUri),
DECLARE_NAPI_FUNCTION("getFileInfoFromRelativePath", NAPI_GetFileInfoFromRelativePath),
DECLARE_NAPI_FUNCTION("getThumbnail", NAPI_GetThumbnail),
DECLARE_NAPI_FUNCTION("on", NAPI_RegisterObserver),
DECLARE_NAPI_FUNCTION("off", NAPI_UnregisterObserver)
DECLARE_NAPI_FUNCTION("registerObserver", NAPI_RegisterObserver),
DECLARE_NAPI_FUNCTION("unregisterObserver", NAPI_UnregisterObserver)
};
napi_value cons = nullptr;
NAPI_CALL(env,
@ -1217,6 +1217,8 @@ static bool parseRegisterObserverArgs(napi_env env, NFuncArg &funcArg, std::stri
NError(EINVAL).ThrowErr(env);
return false;
}
uri = uriPtr.get();
std::tie(succ, notifyForDescendants) = NVal(env, funcArg[NARG_POS::SECOND]).ToBool();
if (!succ) {
NError(EINVAL).ThrowErr(env);
@ -1231,6 +1233,30 @@ static bool parseRegisterObserverArgs(napi_env env, NFuncArg &funcArg, std::stri
return succ;
}
static bool RegisterObserver(napi_env env, NFuncArg &funcArg, sptr<IFileAccessObserver> &observer)
{
std::string uriString;
bool notifyForDescendants = false;
if (!parseRegisterObserverArgs(env, funcArg, uriString, notifyForDescendants)) {
NError(EINVAL).ThrowErr(env);
HILOG_ERROR("parse Args error");
return false;
}
OHOS::Uri uri(uriString);
FileAccessHelper *fileAccessHelper = GetFileAccessHelper(env, funcArg.GetThisVar());
if (fileAccessHelper == nullptr) {
return false;
}
auto retCode = fileAccessHelper->RegisterNotify(uri, notifyForDescendants, observer);
if (retCode != ERR_OK) {
NError(retCode).ThrowErr(env);
return false;
}
return true;
}
napi_value NAPI_RegisterObserver(napi_env env, napi_callback_info info)
{
NFuncArg funcArg(env, info);
@ -1239,44 +1265,37 @@ napi_value NAPI_RegisterObserver(napi_env env, napi_callback_info info)
return nullptr;
}
std::string uriString;
bool notifyForDescendants = false;
if (!parseRegisterObserverArgs(env, funcArg, uriString, notifyForDescendants)) {
NError(EINVAL).ThrowErr(env);
HILOG_ERROR("parse Args error");
return nullptr;
}
sptr<IFileAccessObserver> callback;
if (callback == nullptr) {
NError(EINVAL).ThrowErr(env);
return nullptr;
}
auto finalize = [](napi_env env, void *data, void *hint) {
FileObserverCallbackWrapper *observerWrapper = static_cast<FileObserverCallbackWrapper *>(data);
if (observerWrapper != nullptr) {
delete observerWrapper;
}
};
std::unique_ptr<FileObserverCallbackWrapper> observerWrapper = std::make_unique<FileObserverCallbackWrapper>();
observerWrapper->callback = callback;
napi_value napiCallback = funcArg[NARG_POS::THIRD];
if (napi_wrap(env, napiCallback, observerWrapper.get(), finalize, nullptr, nullptr) != napi_ok) {
NError(EINVAL).ThrowErr(env);
return nullptr;
}
observerWrapper.release();
FileObserverCallbackWrapper* wrapper = nullptr;
if (napi_unwrap(env, napiCallback, (void **)&wrapper) != napi_ok || wrapper == nullptr) {
std::shared_ptr<NapiObserver> observer = std::make_shared<NapiObserver>(env, napiCallback);
sptr<IFileAccessObserver> callback(new (std::nothrow) NapiObserverCallback(observer));
if (callback == nullptr) {
NError(EINVAL).ThrowErr(env);
return nullptr;
}
if (!RegisterObserver(env, funcArg, callback)) {
return nullptr;
}
FileAccessHelper *fileAccessHelper = GetFileAccessHelper(env, funcArg.GetThisVar());
if (fileAccessHelper == nullptr) {
return nullptr;
}
OHOS::Uri uri(uriString);
auto retCode = fileAccessHelper->RegisterNotify(uri, callback, notifyForDescendants);
if (retCode != ERR_OK) {
NError(retCode).ThrowErr(env);
return nullptr;
auto finalize = [](napi_env env, void *data, void *hint) {
FileObserverCallbackWrapper *observerWrapper = static_cast<FileObserverCallbackWrapper *>(data);
if (observerWrapper != nullptr) {
delete observerWrapper;
}
};
std::unique_ptr<FileObserverCallbackWrapper> observerWrapper = std::make_unique<FileObserverCallbackWrapper>();
observerWrapper->callback = callback;
if (napi_wrap(env, napiCallback, observerWrapper.get(), finalize, nullptr, nullptr) != napi_ok) {
NError(EINVAL).ThrowErr(env);
HILOG_ERROR("napi_wrap error");
return nullptr;
}
observerWrapper.release();
} else {
if (!RegisterObserver(env, funcArg, wrapper->callback)) {
return nullptr;
}
}
return NVal::CreateUndefined(env).val_;
}
@ -1284,7 +1303,7 @@ napi_value NAPI_RegisterObserver(napi_env env, napi_callback_info info)
napi_value NAPI_UnregisterObserver(napi_env env, napi_callback_info info)
{
NFuncArg funcArg(env, info);
if (!funcArg.InitArgs(NARG_CNT::TWO)) {
if (!funcArg.InitArgs(NARG_CNT::ONE, NARG_CNT::TWO)) {
NError(EINVAL).ThrowErr(env);
return nullptr;
}
@ -1298,23 +1317,6 @@ napi_value NAPI_UnregisterObserver(napi_env env, napi_callback_info info)
return nullptr;
}
napi_value napiCallback = funcArg[NARG_POS::SECOND];
if (!NVal(env, napiCallback).TypeIs(napi_function)) {
NError(EINVAL).ThrowErr(env);
return nullptr;
}
std::unique_ptr<FileObserverCallbackWrapper> observerWrapper;
if (napi_unwrap(env, napiCallback, (void **)&(observerWrapper)) != napi_ok) {
NError(EINVAL).ThrowErr(env);
return nullptr;
}
if (observerWrapper == nullptr) {
NError(EINVAL).ThrowErr(env);
return nullptr;
}
auto wrapper = observerWrapper.release();
FileAccessHelper *fileAccessHelper = GetFileAccessHelper(env, funcArg.GetThisVar());
if (fileAccessHelper == nullptr) {
return nullptr;
@ -1322,7 +1324,26 @@ napi_value NAPI_UnregisterObserver(napi_env env, napi_callback_info info)
std::string uriString(uriPtr.get());
OHOS::Uri uri(uriString);
auto retCode = fileAccessHelper->UnregisterNotify(uri, wrapper->callback);
int retCode = EINVAL;
if (funcArg.GetArgc() == NARG_CNT::ONE) {
retCode = fileAccessHelper->UnregisterNotify(uri);
} else {
napi_value napiCallback = funcArg[NARG_POS::SECOND];
if (!NVal(env, napiCallback).TypeIs(napi_function)) {
NError(EINVAL).ThrowErr(env);
return nullptr;
}
std::unique_ptr<FileObserverCallbackWrapper> observerWrapper;
if (napi_unwrap(env, napiCallback, (void **)&(observerWrapper)) != napi_ok || observerWrapper == nullptr) {
NError(EINVAL).ThrowErr(env);
return nullptr;
}
auto wrapper = observerWrapper.release();
retCode = fileAccessHelper->UnregisterNotify(uri, wrapper->callback);
}
if (retCode != ERR_OK) {
NError(retCode).ThrowErr(env);
return nullptr;

View File

@ -83,11 +83,11 @@ void NapiObserver::OnChange(NotifyMessage &notifyMessage)
work_ = std::make_unique<uv_work_t>();
}
std::unique_ptr<CallbackParam> callbackParam = std::make_unique<CallbackParam>(this, notifyMessage);
if (work_ == nullptr) {
HILOG_ERROR("napi_get_work failed");
return;
}
std::unique_ptr<CallbackParam> callbackParam = std::make_unique<CallbackParam>(this, notifyMessage);
work_->data = callbackParam.get();
int ret = uv_queue_work(loop, work_.get(),
[](uv_work_t *work) {},
@ -107,9 +107,9 @@ void NapiObserver::OnChange(NotifyMessage &notifyMessage)
napi_value callback = nullptr;
napi_value args[ARGS_ONE] = {napiNotifyMessage.val_};
napi_status status = napi_get_reference_value(param->napiObserver->env_, param->napiObserver->cbOnRef_,
napi_status ret = napi_get_reference_value(param->napiObserver->env_, param->napiObserver->cbOnRef_,
&callback);
if (status != napi_ok) {
if (ret != napi_ok) {
HILOG_ERROR("Notify get reference failed, status:%{public}d.", status);
napi_close_handle_scope(param->napiObserver->env_, scope);
return;
@ -117,7 +117,7 @@ void NapiObserver::OnChange(NotifyMessage &notifyMessage)
napi_value global = nullptr;
napi_get_global(param->napiObserver->env_, &global);
napi_value result = nullptr;
napi_status ret = napi_call_function(param->napiObserver->env_, global, callback, ARGS_ONE, args, &result);
ret = napi_call_function(param->napiObserver->env_, global, callback, ARGS_ONE, args, &result);
if (ret != napi_ok) {
HILOG_ERROR("Notify failed, status:%{public}d.", ret);
napi_close_handle_scope(param->napiObserver->env_, scope);
@ -127,6 +127,7 @@ void NapiObserver::OnChange(NotifyMessage &notifyMessage)
});
if (ret == 0) {
callbackParam.release();
work_.release();
}
}
} // namespace FileAccessFwk

View File

@ -18,10 +18,12 @@
#include "file_access_framework_errno.h"
#include "hilog_wrapper.h"
#include "observer_callback_stub.h"
#include "napi/native_common.h"
#include "napi/native_node_api.h"
#include "napi/native_api.h"
#include "uri.h"
#include "uv.h"
namespace OHOS {
namespace FileAccessFwk {
@ -42,11 +44,12 @@ private:
std::unique_ptr<uv_work_t> work_ = nullptr;
};
class NapiObserverCallback {
class NapiObserverCallback : public ObserverCallbackStub {
public:
explicit NapiObserverCallback(std::shared_ptr<NapiObserver> observer): observer_(observer) {}
virtual ~NapiObserverCallback() {}
void OnChange(NotifyMessage &notifyMessage)
explicit NapiObserverCallback(std::shared_ptr<NapiObserver> observer): ObserverCallbackStub(),
observer_(observer) {}
virtual ~NapiObserverCallback() = default;
void OnChange(NotifyMessage &notifyMessage) override
{
observer_->OnChange(notifyMessage);
}

View File

@ -44,6 +44,7 @@ static napi_value Init(napi_env env, napi_value exports)
InitOpenFlags(env, exports);
InitQueryFlags(env, exports);
InitCopyResult(env, exports);
InitNotifyType(env, exports);
std::vector<std::unique_ptr<NExporter>> products;
products.emplace_back(std::make_unique<NapiRootIteratorExporter>(env, exports));

View File

@ -51,9 +51,11 @@ ohos_shared_library("file_access_extension_ability_kit") {
include_dirs = [
"${ability_runtime_path}/interfaces/kits/native/appkit/ability_runtime/context",
"${file_api_path}/utils/filemgmt_libn/include",
"${user_file_service_path}/services/native/file_access_service/include",
]
sources = [
"${user_file_service_path}/services/native/file_access_service/src/file_access_service_proxy.cpp",
"src/file_access_ext_ability.cpp",
"src/file_access_ext_connection.cpp",
"src/file_access_ext_proxy.cpp",

View File

@ -62,8 +62,7 @@ public:
virtual int Access(const Uri &uri, bool &isExist);
static void SetCreator(const CreatorFunc& creator);
virtual int StartWatcher(const Uri &uri);
virtual int StopWatcher(const Uri &uri);
virtual int Notify(Uri &uri, NotifyType notifyType);
virtual int StopWatcher(const Uri &uri, bool isUnregisterAll);
private:
static CreatorFunc creator_;
};

View File

@ -58,7 +58,7 @@ public:
virtual int GetRoots(std::vector<RootInfo> &rootInfoVec) override;
virtual int Access(const Uri &uri, bool &isExist) override;
virtual int StartWatcher(const Uri &uri) override;
virtual int StopWatcher(const Uri &uri) override;
virtual int StopWatcher(const Uri &uri, bool isUnregisterAll) override;
private:
static inline BrokerDelegator<FileAccessExtProxy> delegator_;
};

View File

@ -55,7 +55,7 @@ public:
int GetRoots(std::vector<RootInfo> &rootInfoVec) override;
int Access(const Uri &uri, bool &isExist) override;
int StartWatcher(const Uri &uri) override;
int StopWatcher(const Uri &uri) override;
int StopWatcher(const Uri &uri, bool isUnregisterAll) override;
private:
std::shared_ptr<FileAccessExtAbility> GetOwner();

View File

@ -71,6 +71,15 @@ constexpr int32_t READ = 0;
constexpr int32_t WRITE = 1;
constexpr int32_t WRITE_READ = 2;
/**
* Indicates the supported Event change type.
*/
constexpr int32_t ADD_EVENT = 0;
constexpr int32_t DELETE_EVENT = 1;
constexpr int32_t MOVED_TO = 2;
constexpr int32_t MOVED_FROM = 3;
constexpr int32_t MOVED_SELF = 4;
struct FileInfo : public virtual OHOS::Parcelable {
public:
std::string uri { "" };

View File

@ -86,11 +86,12 @@ public:
int GetFileInfoFromUri(Uri &selectFile, FileInfo &fileInfo);
int GetFileInfoFromRelativePath(std::string &selectFile, FileInfo &fileInfo);
int GetRoots(std::vector<RootInfo> &rootInfoVec);
int RegisterNotify(Uri uri, sptr<IFileAccessObserver> &observer, bool notifyForDescendants);
int RegisterNotify(Uri uri, bool notifyForDescendants, sptr<IFileAccessObserver> &observer);
int UnregisterNotify(Uri uri, sptr<IFileAccessObserver> &observer);
int UnregisterNotify(Uri uri);
private:
int StartWatcher(Uri &uri);
int StopWatcher(Uri &uri);
int StopWatcher(Uri &uri, bool isUnregisterAll);
sptr<IFileAccessExtBase> GetProxyByUri(Uri &uri);
sptr<IFileAccessExtBase> GetProxyByBundleName(const std::string &bundleName);
bool GetProxy();

View File

@ -29,7 +29,9 @@ namespace FileAccessFwk {
enum NotifyType {
NOTIFY_ADD = 0,
NOTIFY_DELETE,
NOTIFY_UPDATE
NOTIFY_MOVE_TO,
NOTIFY_MOVE_FROM,
NOTIFY_MOVE_SELE
};
struct NotifyMessage : public OHOS::Parcelable {

View File

@ -75,7 +75,7 @@ public:
virtual int GetRoots(std::vector<RootInfo> &rootInfoVec) = 0;
virtual int Access(const Uri &uri, bool &isExist) = 0;
virtual int StartWatcher(const Uri &uri) = 0;
virtual int StopWatcher(const Uri &uri) = 0;
virtual int StopWatcher(const Uri &uri, bool isUnregisterAll) = 0;
};
} // namespace FileAccessFwk
} // namespace OHOS

View File

@ -76,13 +76,14 @@ public:
int Access(const Uri &uri, bool &isExist) override;
int Query(const Uri &uri, std::vector<std::string> &columns, std::vector<std::string> &results) override;
int StartWatcher(const Uri &uri) override;
int StopWatcher(const Uri &uri) override;
int StopWatcher(const Uri &uri, bool isUnregisterAll) override;
private:
NativeValue* CallObjectMethod(const char *name, NativeValue * const *argv = nullptr, size_t argc = 0);
int CallJsMethod(const std::string &funcName, JsRuntime &jsRuntime, NativeReference *jsObj,
InputArgsParser argParser, ResultValueParser retParser);
void GetSrcPath(std::string &srcPath);
static int Notify(Uri &uri, NotifyType notifyType);
static NativeValue* FuncCallback(NativeEngine *engine, NativeCallbackInfo *info);
JsRuntime &jsRuntime_;
std::shared_ptr<NativeReference> jsObj_;

View File

@ -20,6 +20,7 @@
#include "file_access_framework_errno.h"
#include "hilog_wrapper.h"
#include "hitrace_meter.h"
#include "if_system_ability_manager.h"
#include "js_file_access_ext_ability.h"
#include "runtime.h"
@ -159,16 +160,10 @@ int FileAccessExtAbility::StartWatcher(const Uri &uri)
return EPERM;
}
int FileAccessExtAbility::StopWatcher(const Uri &uri)
int FileAccessExtAbility::StopWatcher(const Uri &uri, bool isUnregisterAll)
{
HILOG_ERROR("FileAccessExtAbility::StopWatcher Undefined operation");
return EPERM;
}
int FileAccessExtAbility::Notify(Uri &uri, NotifyType notifyType)
{
HILOG_ERROR("FileAccessExtAbility::Notify Undefined operation");
return EPERM;
}
} // namespace FileAccessFwk
} // namespace OHOS

View File

@ -989,7 +989,7 @@ int FileAccessExtProxy::StartWatcher(const Uri &uri)
return ERR_OK;
}
int FileAccessExtProxy::StopWatcher(const Uri &uri)
int FileAccessExtProxy::StopWatcher(const Uri &uri, bool isUnregisterAll)
{
StartTrace(HITRACE_TAG_FILEMANAGEMENT, "StopWatcher");
MessageParcel data;
@ -1006,6 +1006,12 @@ int FileAccessExtProxy::StopWatcher(const Uri &uri)
return E_IPCS;
}
if (!data.WriteBool(isUnregisterAll)) {
HILOG_ERROR("fail to WriteBool isUnregisterAll");
FinishTrace(HITRACE_TAG_FILEMANAGEMENT);
return E_IPCS;
}
MessageParcel reply;
MessageOption option;
int err = Remote()->SendRequest(CMD_STOP_WATCHER, data, reply, option);

View File

@ -71,12 +71,6 @@ int FileAccessExtStub::OnRemoteRequest(uint32_t code, MessageParcel& data, Messa
MessageOption& option)
{
StartTrace(HITRACE_TAG_FILEMANAGEMENT, "OnRemoteRequest");
if (!CheckCallingPermission(FILE_ACCESS_PERMISSION)) {
HILOG_ERROR("permission error");
FinishTrace(HITRACE_TAG_FILEMANAGEMENT);
return E_PERMISSION;
}
std::u16string descriptor = FileAccessExtStub::GetDescriptor();
std::u16string remoteDescriptor = data.ReadInterfaceToken();
if (descriptor != remoteDescriptor) {
@ -90,6 +84,11 @@ int FileAccessExtStub::OnRemoteRequest(uint32_t code, MessageParcel& data, Messa
return (this->*(itFunc->second))(data, reply);
}
if (!CheckCallingPermission(FILE_ACCESS_PERMISSION)) {
HILOG_ERROR("permission error");
FinishTrace(HITRACE_TAG_FILEMANAGEMENT);
return E_PERMISSION;
}
FinishTrace(HITRACE_TAG_FILEMANAGEMENT);
return IPCObjectStub::OnRemoteRequest(code, data, reply, option);
}
@ -767,8 +766,15 @@ ErrCode FileAccessExtStub::CmdStopWatcher(MessageParcel &data, MessageParcel &re
return EINVAL;
}
bool isUnregisterAll = false;
if (!data.ReadBool(isUnregisterAll)) {
HILOG_ERROR("Parameter Copy fail to ReadBool isUnregisterAll");
FinishTrace(HITRACE_TAG_FILEMANAGEMENT);
return E_IPCS;
}
Uri uri(uriString);
int ret = StopWatcher(uri);
int ret = StopWatcher(uri, isUnregisterAll);
if (!reply.WriteInt32(ret)) {
HILOG_ERROR("Parameter StopWatcher fail to WriteInt32 ret");
FinishTrace(HITRACE_TAG_FILEMANAGEMENT);

View File

@ -262,7 +262,7 @@ int FileAccessExtStubImpl::StartWatcher(const Uri &uri)
return ret;
}
int FileAccessExtStubImpl::StopWatcher(const Uri &uri)
int FileAccessExtStubImpl::StopWatcher(const Uri &uri, bool isUnregisterAll)
{
StartTrace(HITRACE_TAG_FILEMANAGEMENT, "StopWatcher");
if (extension_ == nullptr) {
@ -271,7 +271,7 @@ int FileAccessExtStubImpl::StopWatcher(const Uri &uri)
return E_IPCS;
}
int ret = extension_->StopWatcher(uri);
int ret = extension_->StopWatcher(uri, isUnregisterAll);
FinishTrace(HITRACE_TAG_FILEMANAGEMENT);
return ret;
}

View File

@ -20,6 +20,7 @@
#include "bundle_mgr_proxy.h"
#include "file_access_framework_errno.h"
#include "file_access_extension_info.h"
#include "file_access_service_proxy.h"
#include "hilog_wrapper.h"
#include "hitrace_meter.h"
#include "if_system_ability_manager.h"
@ -1190,7 +1191,7 @@ int FileAccessHelper::StartWatcher(Uri &uri)
return ERR_OK;
}
int FileAccessHelper::StopWatcher(Uri &uri)
int FileAccessHelper::StopWatcher(Uri &uri, bool isUnregisterAll)
{
StartTrace(HITRACE_TAG_FILEMANAGEMENT, "StopWatcher");
sptr<IFileAccessExtBase> fileExtProxy = GetProxyByUri(uri);
@ -1200,9 +1201,9 @@ int FileAccessHelper::StopWatcher(Uri &uri)
return E_IPCS;
}
int ret = fileExtProxy->StopWatcher(uri);
int ret = fileExtProxy->StopWatcher(uri, isUnregisterAll);
if (ret != ERR_OK) {
HILOG_ERROR("Delete get result error, code:%{public}d", ret);
HILOG_ERROR("StopWatcher get result error, code:%{public}d", ret);
FinishTrace(HITRACE_TAG_FILEMANAGEMENT);
return ret;
}
@ -1211,16 +1212,117 @@ int FileAccessHelper::StopWatcher(Uri &uri)
return ERR_OK;
}
int FileAccessHelper::RegisterNotify(Uri uri, sptr<IFileAccessObserver> &observer, bool notifyForDescendants)
int FileAccessHelper::RegisterNotify(Uri uri, bool notifyForDescendants, sptr<IFileAccessObserver> &observer)
{
StartTrace(HITRACE_TAG_FILEMANAGEMENT, "RegisterNotify");
return ERR_OK;
if (!IsSystemApp()) {
HILOG_ERROR("FileAccessHelper::RegisterNotify check IsSystemAppByFullTokenID failed");
FinishTrace(HITRACE_TAG_FILEMANAGEMENT);
return E_PERMISSION_SYS;
}
if (!CheckUri(uri) || observer == nullptr) {
HILOG_ERROR("parameter check error.");
FinishTrace(HITRACE_TAG_FILEMANAGEMENT);
return EINVAL;
}
auto proxy = FileAccessServiceProxy::GetInstance();
if (proxy == nullptr) {
HILOG_ERROR("RegisterNotify get SA failed");
FinishTrace(HITRACE_TAG_FILEMANAGEMENT);
return E_LOAD_SA;
}
int ret = proxy->RegisterNotify(uri, notifyForDescendants, observer);
if (ret != ERR_OK) {
HILOG_ERROR("RegisterNotify error ret = %{public}d", ret);
FinishTrace(HITRACE_TAG_FILEMANAGEMENT);
return ret;
}
ret = StartWatcher(uri);
if (ret != ERR_OK) {
HILOG_ERROR("StartWatcher error ret = %{public}d", ret);
}
FinishTrace(HITRACE_TAG_FILEMANAGEMENT);
return ret;
}
int FileAccessHelper::UnregisterNotify(Uri uri, sptr<IFileAccessObserver> &observer)
{
StartTrace(HITRACE_TAG_FILEMANAGEMENT, "UnregisterNotify");
return ERR_OK;
if (!IsSystemApp()) {
HILOG_ERROR("FileAccessHelper::UnregisterNotify check IsSystemAppByFullTokenID failed");
FinishTrace(HITRACE_TAG_FILEMANAGEMENT);
return E_PERMISSION_SYS;
}
if (!CheckUri(uri) || observer == nullptr) {
HILOG_ERROR("parameter check error.");
FinishTrace(HITRACE_TAG_FILEMANAGEMENT);
return EINVAL;
}
auto proxy = FileAccessServiceProxy::GetInstance();
if (proxy == nullptr) {
HILOG_ERROR("UnregisterNotify get SA failed");
FinishTrace(HITRACE_TAG_FILEMANAGEMENT);
return E_LOAD_SA;
}
int ret = proxy->UnregisterNotify(uri, observer);
if (ret != ERR_OK) {
HILOG_ERROR("UnregisterNotify error ret = %{public}d", ret);
FinishTrace(HITRACE_TAG_FILEMANAGEMENT);
return ret;
}
bool isUnregisterAll = false;
ret = StopWatcher(uri, isUnregisterAll);
if (ret != ERR_OK) {
HILOG_ERROR("StopWatcher error ret = %{public}d", ret);
}
FinishTrace(HITRACE_TAG_FILEMANAGEMENT);
return ret;
}
int FileAccessHelper::UnregisterNotify(Uri uri)
{
StartTrace(HITRACE_TAG_FILEMANAGEMENT, "UnregisterNotify");
if (!IsSystemApp()) {
HILOG_ERROR("FileAccessHelper::UnregisterNotify check IsSystemAppByFullTokenID failed");
FinishTrace(HITRACE_TAG_FILEMANAGEMENT);
return E_PERMISSION_SYS;
}
if (!CheckUri(uri)) {
HILOG_ERROR("parameter check error.");
FinishTrace(HITRACE_TAG_FILEMANAGEMENT);
return EINVAL;
}
auto proxy = FileAccessServiceProxy::GetInstance();
if (proxy == nullptr) {
HILOG_ERROR("UnregisterNotify get SA failed");
FinishTrace(HITRACE_TAG_FILEMANAGEMENT);
return E_LOAD_SA;
}
sptr<IFileAccessObserver> observer = nullptr;
int ret = proxy->UnregisterNotify(uri, observer);
if (ret != ERR_OK) {
HILOG_ERROR("UnregisterNotify error ret = %{public}d", ret);
FinishTrace(HITRACE_TAG_FILEMANAGEMENT);
return ret;
}
bool isUnregisterAll = true;
ret = StopWatcher(uri, isUnregisterAll);
if (ret != ERR_OK) {
HILOG_ERROR("StopWatcher error ret = %{public}d", ret);
}
FinishTrace(HITRACE_TAG_FILEMANAGEMENT);
return ret;
}
void FileAccessDeathRecipient::OnRemoteDied(const wptr<IRemoteObject> &remote)

View File

@ -18,13 +18,16 @@
#include "ability_info.h"
#include "accesstoken_kit.h"
#include "extension_context.h"
#include "file_access_service_proxy.h"
#include "file_access_ext_stub_impl.h"
#include "file_access_observer_common.h"
#include "file_access_extension_info.h"
#include "file_access_framework_errno.h"
#include "hilog_wrapper.h"
#include "hitrace_meter.h"
#include "if_system_ability_manager.h"
#include "ipc_skeleton.h"
#include "iservice_registry.h"
#include "js_runtime.h"
#include "js_runtime_utils.h"
#include "napi/native_api.h"
@ -32,6 +35,7 @@
#include "napi_common_util.h"
#include "napi_common_want.h"
#include "napi_remote_object.h"
#include "system_ability_definition.h"
namespace OHOS {
namespace FileAccessFwk {
@ -1378,16 +1382,9 @@ NativeValue* JsFileAccessExtAbility::FuncCallback(NativeEngine* engine, NativeCa
int32_t event = UnwrapInt32FromJS(reinterpret_cast<napi_env>(engine),
reinterpret_cast<napi_value>(info->argv[ARGC_ONE]));
JsFileAccessExtAbility* jsExtension = static_cast<JsFileAccessExtAbility*>(info->functionInfo->data);
if (jsExtension == nullptr) {
HILOG_ERROR("invalid JsFileAccessExtAbility.");
FinishTrace(HITRACE_TAG_FILEMANAGEMENT);
return engine->CreateUndefined();
}
Uri uri(uriString);
NotifyType notifyType = static_cast<NotifyType>(event);
auto ret = jsExtension->Notify(uri, notifyType);
auto ret = Notify(uri, notifyType);
if (ret != ERR_OK) {
HILOG_ERROR("JsFileAccessExtAbility notify error, ret:%{public}d", ret);
}
@ -1445,7 +1442,7 @@ int JsFileAccessExtAbility::StartWatcher(const Uri &uri)
return ERR_OK;
}
int JsFileAccessExtAbility::StopWatcher(const Uri &uri)
int JsFileAccessExtAbility::StopWatcher(const Uri &uri, bool isUnregisterAll)
{
StartTrace(HITRACE_TAG_FILEMANAGEMENT, "StopWatcher");
auto ret = std::make_shared<int>();
@ -1455,14 +1452,16 @@ int JsFileAccessExtAbility::StopWatcher(const Uri &uri)
return E_GETRESULT;
}
auto argParser = [uri](NativeEngine &engine, NativeValue *argv[], size_t &argc) -> bool {
auto argParser = [uri, isUnregisterAll](NativeEngine &engine, NativeValue *argv[], size_t &argc) -> bool {
NativeValue *nativeUri = engine.CreateString(uri.ToString().c_str(), uri.ToString().length());
if (nativeUri == nullptr) {
HILOG_ERROR("create uri native js value fail.");
return false;
}
NativeValue *isCleanAll = engine.CreateBoolean(isUnregisterAll);
argv[ARGC_ZERO] = nativeUri;
argc = ARGC_ONE;
argv[ARGC_ONE] = isCleanAll;
argc = ARGC_TWO;
return true;
};
@ -1490,5 +1489,24 @@ int JsFileAccessExtAbility::StopWatcher(const Uri &uri)
FinishTrace(HITRACE_TAG_FILEMANAGEMENT);
return ERR_OK;
}
int JsFileAccessExtAbility::Notify(Uri &uri, NotifyType notifyType)
{
StartTrace(HITRACE_TAG_FILEMANAGEMENT, "Notify");
auto proxy = FileAccessServiceProxy::GetInstance();
if (proxy == nullptr) {
HILOG_ERROR("Notify get SA failed");
FinishTrace(HITRACE_TAG_FILEMANAGEMENT);
return E_LOAD_SA;
}
auto ret = proxy->OnChange(uri, notifyType);
if (ret != ERR_OK) {
HILOG_ERROR("notify error, ret:%{public}d", ret);
FinishTrace(HITRACE_TAG_FILEMANAGEMENT);
return ret;
}
FinishTrace(HITRACE_TAG_FILEMANAGEMENT);
return ERR_OK;
}
} // namespace FileAccessFwk
} // namespace OHOS

12
services/5010.json Executable file
View File

@ -0,0 +1,12 @@
{
"process": "file_access_service",
"systemability": [
{
"name": 5010,
"libpath": "libfile_access_service.z.so",
"run-on-create": false,
"distributed": false,
"dump_level": 1
}
]
}

View File

@ -1,24 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright (C) 2023 Huawei Device Co., Ltd.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<info>
<process>file_access_service</process>
<systemability>
<name>5010</name>
<libpath>libfile_access_service.z.so</libpath>
<run-on-create>false</run-on-create>
<distributed>false</distributed>
<dump-level>1</dump-level>
</systemability>
</info>

View File

@ -15,7 +15,12 @@ import("//build/ohos.gni")
import("//foundation/filemanagement/user_file_service/filemanagement_aafwk.gni")
group("user_file_managers") {
deps = [ ":external_file_manager_hap" ]
deps = [
":external_file_manager_hap",
":file_access_service",
":file_access_service.cfg",
":file_access_service_profile",
]
}
ohos_hap("external_file_manager_hap") {
@ -42,8 +47,82 @@ ohos_app_scope("external_file_manager_app_profile") {
sources = [ "file_extension_hap/AppScope/resources" ]
}
ohos_sa_profile("file_access_service_profile") {
sources = [ "5010.json" ]
part_name = "user_file_service"
}
ohos_prebuilt_etc("file_access_service.cfg") {
source = "file_access_service.cfg"
relative_install_dir = "init"
subsystem_name = "filemanagement"
part_name = "user_file_service"
}
config("ability_config") {
visibility = [ ":*" ]
include_dirs = [
"native/file_access_service/include",
"${user_file_service_path}/utils",
"${user_file_service_path}/interfaces/inner_api/file_access/include",
"${user_file_service_path}/frameworks/js/napi/file_access_module",
"${ability_runtime_services_path}/common/include",
"${ability_runtime_kits_path}/ability/native/include/continuation/distributed",
"${ability_runtime_kits_path}/ability/native/include/continuation/kits",
"${ability_runtime_kits_path}/appkit/native/app/include",
"${ability_runtime_napi_path}/inner/napi_common",
"${access_token_path}/interfaces/innerkits/accesstoken/include",
]
}
config("ability_public_config") {
visibility = [ ":*" ]
include_dirs = [
"native/file_access_service/include",
"${user_file_service_path}/utils",
"${ability_runtime_kits_path}/appkit/native/ability_runtime/app",
"${ability_runtime_kits_path}/appkit/native/app/include",
"${ability_runtime_kits_path}/appkit/native/ability_runtime/context",
"${user_file_service_path}/interfaces/kits/js/src/common",
]
}
ohos_resources("external_file_manager_resources") {
sources = [ "file_extension_hap/entry/src/main/resources" ]
deps = [ ":external_file_manager_app_profile" ]
hap_profile = "file_extension_hap/entry/src/main/module.json"
}
ohos_shared_library("file_access_service") {
include_dirs = [
"${user_file_service_path}/services/native/file_access_service/include",
"${ability_runtime_path}/interfaces/kits/native/appkit/ability_runtime/context",
]
shlib_type = "sa"
sources = [
"native/file_access_service/src/file_access_service.cpp",
"native/file_access_service/src/file_access_service_proxy.cpp",
"native/file_access_service/src/file_access_service_stub.cpp",
"native/file_access_service/src/observer_callback_proxy.cpp",
"native/file_access_service/src/observer_callback_stub.cpp",
]
configs = [ ":ability_config" ]
version_script = "libfile_access_service.map"
public_configs = [ ":ability_public_config" ]
external_deps = [
"ability_base:want",
"ability_base:zuri",
"access_token:libaccesstoken_sdk",
"access_token:libtokenid_sdk",
"c_utils:utils",
"hilog:libhilog",
"hitrace:hitrace_meter",
"ipc:ipc_core",
"safwk:system_ability_fwk",
"samgr:samgr_proxy",
]
subsystem_name = "filemanagement"
part_name = "user_file_service"
}

View File

@ -1,8 +1,9 @@
{
"services" : [{
"name" : "file_access_service",
"path" : ["/system/bin/sa_main", "/system/profile/file_access_service.xml"],
"path" : ["/system/bin/sa_main", "/system/profile/file_access_service.json"],
"uid" : "file_manager",
"ondemand" : true,
"secon" : "u:r:file_access_service:s0"
}
]

View File

@ -34,13 +34,27 @@ const E_INVAL = 13900020;
const E_URIS = 14300002;
const E_GETRESULT = 14300004;
const CREATE_EVENT_CODE = 0x00000100;
const DELETE_EVENT_CODE = 0x00000200 | 0x00000400;
const UPDATE_EVENT_CODE = 0x00000040 | 0x00000080 | 0x00000800;
const IN_DELETE_EVENT_CODE = 0x00000200;
const DELETE_SELF_EVENT_CODE = 0x00000400;
const MOVE_TO_CODE = 0x00000080;
const MOVED_FROM_CODE = 0x00000040;
const MOVE_SELF_CODE = 0x00000800;
const MOVE_MODLE_CODE = 3;
const CREATE_EVENT = 0;
const DELETE_EVENT = 1;
const UPDATE_EVENT = 2;
const CONVERT_TO_HEX = 16;
const MOVE_MODLE_CODE = 3;
const MOVED_TO = 2;
const MOVED_FROM = 3;
const MOVED_SELF = 4;
let observerMap = new Map();
let watcherCountMap = new Map();
let eventMap = new Map([
[CREATE_EVENT_CODE, CREATE_EVENT],
[IN_DELETE_EVENT_CODE, DELETE_EVENT],
[DELETE_SELF_EVENT_CODE, DELETE_EVENT],
[MOVE_TO_CODE, MOVED_TO],
[MOVED_FROM_CODE, MOVED_FROM],
[MOVE_SELF_CODE, MOVED_SELF]
]);
// ['IN_ACCESS', 0x00000001],
// ['IN_MODIFY', 0x00000002],
@ -55,21 +69,6 @@ const MOVE_MODLE_CODE = 3;
// ['IN_DELETE_SELF', 0x00000400],
// ['IN_MOVE_SELF', 0x00000800]
enum createEvent {
create = 100
}
enum deleteEvent {
delete = 200,
deleteSelf = 400
}
enum updataEvent {
moveSelf = 800,
moveFrom = 40,
moveTo = 80
}
export default class FileExtAbility extends Extension {
onCreate(want): void {
hilog.info(DOMAIN_CODE, TAG, 'Extension init process');
@ -378,8 +377,8 @@ export default class FileExtAbility extends Extension {
fs.moveFileSync(oldPath, newPath, 0);
return {
uri: newFileUri,
code: ERR_OK,
uri: newFileUri,
code: ERR_OK,
};
} catch (e) {
hilog.error(DOMAIN_CODE, TAG, 'move error ' + e.message);
@ -760,29 +759,34 @@ export default class FileExtAbility extends Extension {
}
let watchPath = getPath(uri);
try {
let watcher = fs.createWatcher(watchPath, CREATE_EVENT_CODE | DELETE_EVENT_CODE | UPDATE_EVENT_CODE, (data) => {
try {
let notifyEvent = (data.event).toString(CONVERT_TO_HEX);
if (notifyEvent in createEvent) {
notifyEvent = CREATE_EVENT;
if (!observerMap.has(uri)) {
let watcher = fs.createWatcher(watchPath, CREATE_EVENT_CODE | IN_DELETE_EVENT_CODE | DELETE_SELF_EVENT_CODE |
MOVE_TO_CODE | MOVED_FROM_CODE | MOVE_SELF_CODE, (data) => {
try {
let eventCode = -1;
eventMap.forEach((value, key) => {
if (data.event & key) {
eventCode = value;
}
});
let targetUri = FILE_PREFIX_NAME + BUNDLE_NAME + data.fileName;
targetUri = this.encode(targetUri);
if (eventCode >= 0) {
callback(targetUri, eventCode);
} else {
hilog.info(DOMAIN_CODE, TAG, 'eventCode =' + data.event);
}
} catch (error) {
hilog.error(DOMAIN_CODE, TAG, 'onchange error ' + error.message);
}
if (notifyEvent in deleteEvent) {
notifyEvent = DELETE_EVENT;
}
if (notifyEvent in updataEvent) {
notifyEvent = UPDATE_EVENT;
}
let watchUri = FILE_PREFIX_NAME + BUNDLE_NAME + watchPath;
watchUri = this.encode(watchUri);
callback(watchUri, notifyEvent);
} catch (error) {
hilog.error(DOMAIN_CODE, TAG, 'onchange error ' + error.message);
}
});
observerMap.set(uri, watcher);
watcher.start();
});
watcher.start();
observerMap.set(uri, watcher);
watcherCountMap.set(uri, 1);
} else {
let temp = watcherCountMap.get(uri) + 1;
watcherCountMap.set(uri, temp);
}
} catch (e) {
hilog.error(DOMAIN_CODE, TAG, 'startWatcher error ' + e.message);
return E_GETRESULT;
@ -790,7 +794,7 @@ export default class FileExtAbility extends Extension {
return ERR_OK;
}
stopWatcher(uri): number {
stopWatcher(uri, isUnregisterAll): number {
uri = this.decode(uri);
if (uri === '') {
return {
@ -802,9 +806,23 @@ export default class FileExtAbility extends Extension {
return E_URIS;
}
try {
let watcher = observerMap.get(uri);
watcher.stop();
observerMap.delete(uri);
if (!watcherCountMap.has(uri)) {
return E_GETRESULT;
}
if (isUnregisterAll) {
watcherCountMap.set(uri, 0);
} else {
let temp = watcherCountMap.get(uri) - 1;
watcherCountMap.set(uri, temp);
}
if (watcherCountMap.get(uri) === 0) {
watcherCountMap.delete(uri);
let watcher = observerMap.get(uri);
if (typeof watcher !== undefined) {
watcher.stop();
observerMap.delete(uri);
}
}
} catch (e) {
hilog.error(DOMAIN_CODE, TAG, 'stopWatcher error ' + e.message);
return E_GETRESULT;

View File

@ -0,0 +1,26 @@
# Copyright (c) 2023 Huawei Device Co., Ltd.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
1.0 {
global:
extern "C++" {
*FileAccessServiceProxy*;
*FileAccessService*;
*FileAccessServiceStub*;
*ObserverCallbackStub*;
*ObserverCallbackProxy*;
**;
};
local:
*;
};

View File

@ -90,8 +90,9 @@ public:
int32_t Dump(int32_t fd, const std::vector<std::u16string> &args) override;
public:
int32_t RegisterNotify(Uri uri, const sptr<IFileAccessObserver> &observer, bool notifyForDescendants) override;
int32_t RegisterNotify(Uri uri, bool notifyForDescendants, const sptr<IFileAccessObserver> &observer) override;
int32_t UnregisterNotify(Uri uri, const sptr<IFileAccessObserver> &observer) override;
int32_t CleanAllNotify(Uri uri) override;
int32_t OnChange(Uri uri, NotifyType notifyType) override;
private:

View File

@ -0,0 +1,24 @@
/*
* Copyright (c) 2023 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace OHOS {
namespace FileAccessFwk {
enum class FileAccessServiceInterfaceCode {
CMD_REGISTER_NOTIFY = 0,
CMD_UNREGISTER_NOTIFY,
CMD_ONCHANGE
};
} // namespace FileAccessFwk
} // namespace OHOS

View File

@ -18,6 +18,7 @@
#include "ifile_access_service_base.h"
#include "iremote_proxy.h"
#include "system_ability_load_callback_stub.h"
namespace OHOS {
namespace FileAccessFwk {
@ -25,11 +26,23 @@ class FileAccessServiceProxy : public IRemoteProxy<IFileAccessServiceBase> {
public:
explicit FileAccessServiceProxy(const sptr<IRemoteObject> &impl) : IRemoteProxy<IFileAccessServiceBase>(impl) {}
~FileAccessServiceProxy() = default;
static sptr<IFileAccessServiceBase> GetInstance();
int32_t OnChange(Uri uri, NotifyType notifyType) override;
int32_t RegisterNotify(Uri uri, const sptr<IFileAccessObserver> &observer, bool notifyForDescendants) override;
int32_t RegisterNotify(Uri uri, bool notifyForDescendants, const sptr<IFileAccessObserver> &observer) override;
int32_t UnregisterNotify(Uri uri, const sptr<IFileAccessObserver> &observer) override;
class ServiceProxyLoadCallback : public SystemAbilityLoadCallbackStub {
public:
void OnLoadSystemAbilitySuccess(int32_t systemAbilityId, const sptr<IRemoteObject> &remoteObject) override;
void OnLoadSystemAbilityFail(int32_t systemAbilityId) override;
std::condition_variable proxyConVar_;
std::atomic<bool> isLoadSuccess_{false};
};
private:
int32_t UnregisterNotifyInternal(MessageParcel &data);
static inline std::mutex proxyMutex_;
static inline sptr<IFileAccessServiceBase> serviceProxy_;
static inline BrokerDelegator<FileAccessServiceProxy> delegator_;
};
} // namespace FileAccessFwk

View File

@ -28,6 +28,7 @@ class FileAccessServiceStub : public IRemoteStub<IFileAccessServiceBase> {
public:
FileAccessServiceStub();
virtual ~FileAccessServiceStub();
virtual int32_t CleanAllNotify (Uri uri) = 0;
int32_t OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) override;
private:

View File

@ -110,4 +110,4 @@ private:
};
} // namespace FileAccessFwk
} // namespace OHOS
#endif // FRAMEWORKS_INNERKITSIMPL_UTILS_INCLUDE_IMAGE_HOLDER_MANAGER_H_
#endif // FRAMEWORKS_INNERKITSIMPL_UTILS_INCLUDE_IMAGE_HOLDER_MANAGER_H_

View File

@ -29,14 +29,8 @@ public:
DECLARE_INTERFACE_DESCRIPTOR(u"OHOS.FileAccessFwk.IFileAccessServiceBase");
public:
enum {
CMD_REGISTER_NOTIFY = 0,
CMD_UNREGISTER_NOTIFY,
CMD_ONCHANGE
};
virtual int32_t OnChange(Uri uri, NotifyType notifyType) = 0;
virtual int32_t RegisterNotify(Uri uri, const sptr<IFileAccessObserver> &observer, bool notifyForDescendants) = 0;
virtual int32_t RegisterNotify(Uri uri, bool notifyForDescendants, const sptr<IFileAccessObserver> &observer) = 0;
virtual int32_t UnregisterNotify(Uri uri, const sptr<IFileAccessObserver> &observer) = 0;
};
} // namespace FileAccessFwk

View File

@ -27,7 +27,7 @@ class ObserverCallbackProxy : public IRemoteProxy<IFileAccessObserver> {
public:
explicit ObserverCallbackProxy(const sptr<IRemoteObject>& remote) : IRemoteProxy<IFileAccessObserver>(remote) {}
~ObserverCallbackProxy() = default;
void OnChange(NotifyMessage &notifyMessage) {} override;
void OnChange(NotifyMessage &notifyMessage) override;
private:
static inline BrokerDelegator<ObserverCallbackProxy> delegator_;

View File

@ -18,6 +18,7 @@
#include <errors.h>
#include <cstdint>
#include <map>
#include "iobserver_callback.h"
#include "iremote_stub.h"
@ -30,13 +31,14 @@ namespace FileAccessFwk {
class ObserverCallbackStub : public IRemoteStub<IFileAccessObserver> {
public:
ObserverCallbackStub() = default;
virtual ~ObserverCallbackStub() = default;
int OnRemoteRequest(uint32_t code, MessageParcel& data, MessageParcel& reply, MessageOption& option) override;
void OnChange(NotifyMessage &notifyMessage) override {}
virtual ~ObserverCallbackStub();
int32_t OnRemoteRequest(uint32_t code, MessageParcel& data, MessageParcel& reply, MessageOption& option) override;
private:
int32_t OnChangeStub(MessageParcel &data, MessageParcel &reply);
int32_t ChooseCodeStub(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option);
void InitStubFuncMap();
using RequestFuncType = int (ObserverCallbackStub::*)(MessageParcel &data, MessageParcel &reply);
std::map<uint32_t, RequestFuncType> stubFuncMap_ = {};
};
} // namespace FileAccessFwk
} // namespace OHOS

View File

@ -22,17 +22,22 @@
#include "hitrace_meter.h"
#include "system_ability_definition.h"
using namespace std;
namespace OHOS {
namespace FileAccessFwk {
namespace {
auto pms = FileAccessService::GetInstance();
const bool G_REGISTER_RESULT = SystemAbility::MakeAndRegisterAbility(pms.GetRefPtr());
}
sptr<FileAccessService> FileAccessService::instance_;
std::mutex FileAccessService::mutex_;
mutex FileAccessService::mutex_;
sptr<FileAccessService> FileAccessService::GetInstance()
{
if (instance_ != nullptr) {
return instance_;
}
std::lock_guard<std::mutex> lock(mutex_);
lock_guard<mutex> lock(mutex_);
if (instance_ == nullptr) {
instance_ = new FileAccessService();
if (instance_ == nullptr) {
@ -70,7 +75,7 @@ void FileAccessService::OnStop()
ready_ = false;
}
int32_t FileAccessService::Dump(int32_t fd, const std::vector<std::u16string> &args)
int32_t FileAccessService::Dump(int32_t fd, const vector<u16string> &args)
{
return ERR_OK;
}
@ -110,8 +115,7 @@ static bool IsChildUri(const string &comparedUriStr, string &srcUriStr)
return false;
}
int32_t FileAccessService::RegisterNotify(Uri uri, const sptr<IFileAccessObserver> &observer,
bool notifyForDescendants)
int32_t FileAccessService::RegisterNotify(Uri uri, bool notifyForDescendants, const sptr<IFileAccessObserver> &observer)
{
StartTrace(HITRACE_TAG_FILEMANAGEMENT, "RegisterNotify");
shared_ptr<ObserverContext> obsContext = make_shared<ObserverContext>(observer);
@ -119,7 +123,7 @@ int32_t FileAccessService::RegisterNotify(Uri uri, const sptr<IFileAccessObserve
uint32_t code = obsManager_.getId([obsContext](const shared_ptr<ObserverContext> &afterContext) {
return obsContext->EqualTo(afterContext);
});
if (code == HolderManager<std::shared_ptr<ObserverContext>>::CODE_CAN_NOT_FIND) {
if (code == HolderManager<shared_ptr<ObserverContext>>::CODE_CAN_NOT_FIND) {
// this is new callback, save this context
obsContext->Ref();
code = obsManager_.save(obsContext);
@ -128,7 +132,7 @@ int32_t FileAccessService::RegisterNotify(Uri uri, const sptr<IFileAccessObserve
obsManager_.get(code)->Ref();
}
string uriStr = uri.ToString();
std::lock_guard<std::mutex> lock(nodeMutex_);
lock_guard<mutex> lock(nodeMutex_);
auto iter = relationshipMap_.find(uriStr);
shared_ptr<ObserverNode> obsNode;
if (iter != relationshipMap_.end()) {
@ -174,10 +178,10 @@ int32_t FileAccessService::RegisterNotify(Uri uri, const sptr<IFileAccessObserve
void FileAccessService::RemoveRelations(string &uriStr, shared_ptr<ObserverNode> obsNode)
{
std::lock_guard<std::mutex> lock(nodeMutex_);
lock_guard<mutex> lock(nodeMutex_);
for (auto &[comUri, node] : relationshipMap_) {
auto childrenIter = find_if(node->children_.begin(), node->children_.end(),
[obsNode](const std::shared_ptr<ObserverNode> &obsListNode) { return obsNode == obsListNode; });
[obsNode](const shared_ptr<ObserverNode> &obsListNode) { return obsNode == obsListNode; });
if (childrenIter != node->children_.end()) {
node->children_.erase(childrenIter);
}
@ -190,7 +194,7 @@ void FileAccessService::RemoveRelations(string &uriStr, shared_ptr<ObserverNode>
int FileAccessService::FindUri(const string &uriStr, shared_ptr<ObserverNode> &outObsNode)
{
std::lock_guard<std::mutex> lock(nodeMutex_);
lock_guard<mutex> lock(nodeMutex_);
auto iter = relationshipMap_.find(uriStr);
if (iter == relationshipMap_.end()) {
HILOG_ERROR("Can not find uri");
@ -200,6 +204,28 @@ int FileAccessService::FindUri(const string &uriStr, shared_ptr<ObserverNode> &o
return ERR_OK;
}
int32_t FileAccessService::CleanAllNotify(Uri uri)
{
StartTrace(HITRACE_TAG_FILEMANAGEMENT, "CleanAllNotify");
string uriStr = uri.ToString();
shared_ptr<ObserverNode> obsNode;
if (FindUri(uriStr, obsNode) != ERR_OK) {
HILOG_ERROR("Can not find unregisterNotify uri");
FinishTrace(HITRACE_TAG_FILEMANAGEMENT);
return E_CAN_NOT_FIND_URI;
}
for (auto code : obsNode->obsCodeList_) {
auto context = obsManager_.get(code);
context->UnRef();
if (!context->IsValid()) {
obsManager_.release(code);
}
}
RemoveRelations(uriStr, obsNode);
FinishTrace(HITRACE_TAG_FILEMANAGEMENT);
return ERR_OK;
}
int32_t FileAccessService::UnregisterNotify(Uri uri, const sptr<IFileAccessObserver> &observer)
{
StartTrace(HITRACE_TAG_FILEMANAGEMENT, "UnregisterNotify");
@ -220,7 +246,7 @@ int32_t FileAccessService::UnregisterNotify(Uri uri, const sptr<IFileAccessObser
uint32_t code = obsManager_.getId([obsContext](const shared_ptr<ObserverContext> &afterContext) {
return obsContext->EqualTo(afterContext);
});
if (code == HolderManager<std::shared_ptr<ObserverContext>>::CODE_CAN_NOT_FIND) {
if (code == HolderManager<shared_ptr<ObserverContext>>::CODE_CAN_NOT_FIND) {
HILOG_ERROR("Can not find observer");
FinishTrace(HITRACE_TAG_FILEMANAGEMENT);
return E_CALLBACK_IS_NOT_REGISTER;
@ -266,15 +292,33 @@ int32_t FileAccessService::OnChange(Uri uri, NotifyType notifyType)
StartTrace(HITRACE_TAG_FILEMANAGEMENT, "OnChange");
string uriStr = uri.ToString();
shared_ptr<ObserverNode> node;
if (FindUri(uriStr, node) != ERR_OK) {
FinishTrace(HITRACE_TAG_FILEMANAGEMENT);
HILOG_ERROR("Can not find onChange uri");
return E_CAN_NOT_FIND_URI;
}
NotifyMessage notifyMessage;
notifyMessage.notifyType_ = notifyType;
std::vector<std::string> uris {uriStr};
vector<string> uris {uriStr};
notifyMessage.uris_ = uris;
//When the path is not found, search for its parent path
if (FindUri(uriStr, node) != ERR_OK) {
size_t slashIndex = uriStr.rfind("/");
if (slashIndex == string::npos) {
HILOG_ERROR("Do not have parent");
FinishTrace(HITRACE_TAG_FILEMANAGEMENT);
return E_DO_NOT_HAVE_PARENT;
}
string parentUri = uriStr.substr(0, slashIndex);
if (FindUri(parentUri, node) != ERR_OK) {
HILOG_DEBUG("Can not find onChange parent uri");
FinishTrace(HITRACE_TAG_FILEMANAGEMENT);
return ERR_OK;
}
if (!node->needChildNote_) {
HILOG_DEBUG("Do not need send onChange message");
FinishTrace(HITRACE_TAG_FILEMANAGEMENT);
return ERR_OK;
}
SendListNotify(node->obsCodeList_, notifyMessage);
FinishTrace(HITRACE_TAG_FILEMANAGEMENT);
return ERR_OK;
}
SendListNotify(node->obsCodeList_, notifyMessage);
if ((node->parent_ == nullptr) || (!node->parent_->needChildNote_)) {
HILOG_DEBUG("Do not need notify parent");

View File

@ -16,16 +16,76 @@
#include "file_access_service_proxy.h"
#include "file_access_framework_errno.h"
#include "file_access_service_ipc_interface_code.h"
#include "hilog_wrapper.h"
#include "hitrace_meter.h"
#include "iservice_registry.h"
#include "system_ability_definition.h"
namespace OHOS {
namespace FileAccessFwk {
constexpr int LOAD_SA_TIMEOUT_MS = 5000;
sptr<IFileAccessServiceBase> FileAccessServiceProxy::GetInstance()
{
HILOG_INFO("Getinstance");
std::unique_lock<std::mutex> lock(proxyMutex_);
if (serviceProxy_ != nullptr) {
return serviceProxy_;
}
auto samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
if (samgr == nullptr) {
HILOG_ERROR("Samgr is nullptr");
return nullptr;
}
sptr<ServiceProxyLoadCallback> loadCallback(new ServiceProxyLoadCallback());
if (loadCallback == nullptr) {
HILOG_ERROR("loadCallback is nullptr");
return nullptr;
}
int32_t ret = samgr->LoadSystemAbility(FILE_ACCESS_SERVICE_ID, loadCallback);
if (ret != ERR_OK) {
HILOG_ERROR("Failed to Load systemAbility, systemAbilityId:%{pulbic}d, ret code:%{pulbic}d",
FILE_ACCESS_SERVICE_ID, ret);
return nullptr;
}
auto waitStatus = loadCallback->proxyConVar_.wait_for(
lock, std::chrono::milliseconds(LOAD_SA_TIMEOUT_MS),
[loadCallback]() { return loadCallback->isLoadSuccess_.load(); });
if (!waitStatus) {
HILOG_ERROR("Load FileAccessService SA timeout");
return nullptr;
}
return serviceProxy_;
}
void FileAccessServiceProxy::ServiceProxyLoadCallback::OnLoadSystemAbilitySuccess(
int32_t systemAbilityId,
const sptr<IRemoteObject> &remoteObject)
{
HILOG_INFO("Load FileAccessService SA success,systemAbilityId:%{public}d, remoteObj result:%{private}s",
systemAbilityId, (remoteObject == nullptr ? "false" : "true"));
std::unique_lock<std::mutex> lock(proxyMutex_);
serviceProxy_ = iface_cast<IFileAccessServiceBase>(remoteObject);
isLoadSuccess_.store(true);
proxyConVar_.notify_one();
}
void FileAccessServiceProxy::ServiceProxyLoadCallback::OnLoadSystemAbilityFail(int32_t systemAbilityId)
{
HILOG_INFO("Load FileAccessService SA failed,systemAbilityId:%{public}d", systemAbilityId);
std::unique_lock<std::mutex> lock(proxyMutex_);
serviceProxy_ = nullptr;
isLoadSuccess_.store(false);
proxyConVar_.notify_one();
}
int32_t FileAccessServiceProxy::OnChange(Uri uri, NotifyType notifyType)
{
StartTrace(HITRACE_TAG_FILEMANAGEMENT, "OnChange");
MessageParcel data;
if (!data.WriteInterfaceToken(FileAccessObserverProxy::GetDescriptor())) {
if (!data.WriteInterfaceToken(FileAccessServiceProxy::GetDescriptor())) {
HILOG_ERROR("WriteInterfaceToken failed");
FinishTrace(HITRACE_TAG_FILEMANAGEMENT);
return E_IPCS;
@ -45,7 +105,8 @@ int32_t FileAccessServiceProxy::OnChange(Uri uri, NotifyType notifyType)
MessageParcel reply;
MessageOption option;
int err = Remote()->SendRequest(CMD_ONCHANGE, data, reply, option);
int err = Remote()->SendRequest(static_cast<uint32_t>(FileAccessServiceInterfaceCode::CMD_ONCHANGE), data, reply,
option);
if (err != ERR_OK) {
HILOG_ERROR("fail to SendRequest. err: %{public}d", err);
FinishTrace(HITRACE_TAG_FILEMANAGEMENT);
@ -63,8 +124,8 @@ int32_t FileAccessServiceProxy::OnChange(Uri uri, NotifyType notifyType)
return ERR_OK;
}
int32_t FileAccessServiceProxy::RegisterNotify(Uri uri, const sptr<IFileAccessObserver> &observer,
bool notifyForDescendants)
int32_t FileAccessServiceProxy::RegisterNotify(Uri uri, bool notifyForDescendants,
const sptr<IFileAccessObserver> &observer)
{
StartTrace(HITRACE_TAG_FILEMANAGEMENT, "RegisterNotify");
MessageParcel data;
@ -94,7 +155,8 @@ int32_t FileAccessServiceProxy::RegisterNotify(Uri uri, const sptr<IFileAccessOb
MessageParcel reply;
MessageOption option;
int err = Remote()->SendRequest(CMD_REGISTER_NOTIFY, data, reply, option);
int err = Remote()->SendRequest(static_cast<uint32_t>(FileAccessServiceInterfaceCode::CMD_REGISTER_NOTIFY), data,
reply, option);
if (err != ERR_OK) {
HILOG_ERROR("fail to SendRequest. err: %{public}d", err);
FinishTrace(HITRACE_TAG_FILEMANAGEMENT);
@ -112,6 +174,26 @@ int32_t FileAccessServiceProxy::RegisterNotify(Uri uri, const sptr<IFileAccessOb
return ERR_OK;
}
int32_t FileAccessServiceProxy::UnregisterNotifyInternal(MessageParcel &data)
{
MessageParcel reply;
MessageOption option;
int err = Remote()->SendRequest(static_cast<uint32_t>(FileAccessServiceInterfaceCode::CMD_UNREGISTER_NOTIFY), data,
reply, option);
if (err != ERR_OK) {
HILOG_ERROR("fail to SendRequest. err: %{public}d", err);
return err;
}
int ret = E_IPCS;
if (!reply.ReadInt32(ret) || ret != ERR_OK) {
HILOG_ERROR("UnregisterNotify operation failed ret : %{public}d", ret);
return ret;
}
return ERR_OK;
}
int32_t FileAccessServiceProxy::UnregisterNotify(Uri uri, const sptr<IFileAccessObserver> &observer)
{
StartTrace(HITRACE_TAG_FILEMANAGEMENT, "UnregisterNotify");
@ -127,31 +209,32 @@ int32_t FileAccessServiceProxy::UnregisterNotify(Uri uri, const sptr<IFileAccess
FinishTrace(HITRACE_TAG_FILEMANAGEMENT);
return E_IPCS;
}
if (!data.WriteRemoteObject(observer->AsObject())) {
HILOG_ERROR("fail to WriteRemoteObject observer");
FinishTrace(HITRACE_TAG_FILEMANAGEMENT);
return E_IPCS;
bool observerNotNull = true;
if (observer != nullptr) {
if (!data.WriteBool(observerNotNull)) {
HILOG_ERROR("fail to WriteBool observerNotNull");
FinishTrace(HITRACE_TAG_FILEMANAGEMENT);
return E_IPCS;
}
if (!data.WriteRemoteObject(observer->AsObject())) {
HILOG_ERROR("fail to WriteRemoteObject observer");
FinishTrace(HITRACE_TAG_FILEMANAGEMENT);
return E_IPCS;
}
} else {
observerNotNull = false;
if (!data.WriteBool(observerNotNull)) {
HILOG_ERROR("fail to WriteBool observerNotNull");
FinishTrace(HITRACE_TAG_FILEMANAGEMENT);
return E_IPCS;
}
}
MessageParcel reply;
MessageOption option;
int err = Remote()->SendRequest(CMD_UNREGISTER_NOTIFY, data, reply, option);
if (err != ERR_OK) {
HILOG_ERROR("fail to SendRequest. err: %{public}d", err);
FinishTrace(HITRACE_TAG_FILEMANAGEMENT);
return err;
}
int ret = E_IPCS;
if (!reply.ReadInt32(ret) || ret != ERR_OK) {
HILOG_ERROR("UnregisterNotify operation failed ret : %{public}d", ret);
FinishTrace(HITRACE_TAG_FILEMANAGEMENT);
return ret;
}
// Split the code into two functions for better readability
int32_t result = UnregisterNotifyInternal(data);
FinishTrace(HITRACE_TAG_FILEMANAGEMENT);
return ERR_OK;
return result;
}
} // namespace FileAccessFwk
} // namespace OHOS

View File

@ -21,6 +21,7 @@
#include "access_token.h"
#include "accesstoken_kit.h"
#include "file_access_framework_errno.h"
#include "file_access_service_ipc_interface_code.h"
#include "hilog_wrapper.h"
#include "hitrace_meter.h"
#include "ipc_object_stub.h"
@ -36,9 +37,12 @@ namespace {
}
FileAccessServiceStub::FileAccessServiceStub()
{
stubFuncMap_[CMD_REGISTER_NOTIFY] = &FileAccessServiceStub::CmdRegisterNotify;
stubFuncMap_[CMD_UNREGISTER_NOTIFY] = &FileAccessServiceStub::CmdUnregisterNotify;
stubFuncMap_[CMD_ONCHANGE] = &FileAccessServiceStub::CmdOnChange;
stubFuncMap_[static_cast<uint32_t>(FileAccessServiceInterfaceCode::CMD_REGISTER_NOTIFY)] =
&FileAccessServiceStub::CmdRegisterNotify;
stubFuncMap_[static_cast<uint32_t>(FileAccessServiceInterfaceCode::CMD_UNREGISTER_NOTIFY)] =
&FileAccessServiceStub::CmdUnregisterNotify;
stubFuncMap_[static_cast<uint32_t>(FileAccessServiceInterfaceCode::CMD_ONCHANGE)] =
&FileAccessServiceStub::CmdOnChange;
}
FileAccessServiceStub::~FileAccessServiceStub()
@ -50,12 +54,6 @@ int32_t FileAccessServiceStub::OnRemoteRequest(uint32_t code, MessageParcel &dat
MessageOption &option)
{
StartTrace(HITRACE_TAG_FILEMANAGEMENT, "OnRemoteRequest");
if (!CheckCallingPermission(FILE_ACCESS_PERMISSION)) {
HILOG_ERROR("permission error");
FinishTrace(HITRACE_TAG_FILEMANAGEMENT);
return E_PERMISSION;
}
std::u16string descriptor = FileAccessServiceStub::GetDescriptor();
std::u16string remoteDescriptor = data.ReadInterfaceToken();
if (descriptor != remoteDescriptor) {
@ -69,6 +67,11 @@ int32_t FileAccessServiceStub::OnRemoteRequest(uint32_t code, MessageParcel &dat
return (this->*(itFunc->second))(data, reply);
}
if (!CheckCallingPermission(FILE_ACCESS_PERMISSION)) {
HILOG_ERROR("permission error");
FinishTrace(HITRACE_TAG_FILEMANAGEMENT);
return E_PERMISSION;
}
FinishTrace(HITRACE_TAG_FILEMANAGEMENT);
return IPCObjectStub::OnRemoteRequest(code, data, reply, option);
}
@ -120,7 +123,7 @@ ErrCode FileAccessServiceStub::CmdRegisterNotify(MessageParcel &data, MessagePar
}
bool notifyForDescendants = data.ReadBool();
int ret = RegisterNotify(*uri, observer, notifyForDescendants);
int ret = RegisterNotify(*uri, notifyForDescendants, observer);
if (!reply.WriteInt32(ret)) {
HILOG_ERROR("Parameter RegisterNotify fail to WriteInt32 ret");
FinishTrace(HITRACE_TAG_FILEMANAGEMENT);
@ -140,21 +143,27 @@ ErrCode FileAccessServiceStub::CmdUnregisterNotify(MessageParcel &data, MessageP
return E_IPCS;
}
sptr<IRemoteObject> obj = data.ReadRemoteObject();
if (obj == nullptr) {
HILOG_INFO("get remote obj fail.");
FinishTrace(HITRACE_TAG_FILEMANAGEMENT);
return E_IPCS;
bool observerNotNull = data.ReadBool();
int ret = E_IPCS;
if (observerNotNull) {
sptr<IRemoteObject> obj = data.ReadRemoteObject();
if (obj == nullptr) {
HILOG_INFO("get remote obj fail.");
FinishTrace(HITRACE_TAG_FILEMANAGEMENT);
return E_IPCS;
}
sptr<IFileAccessObserver> observer = iface_cast<IFileAccessObserver>(obj);
if (observer == nullptr) {
HILOG_INFO("get observer fail");
FinishTrace(HITRACE_TAG_FILEMANAGEMENT);
return E_IPCS;
}
ret = UnregisterNotify(*uri, observer);
} else {
ret = CleanAllNotify(*uri);
}
sptr<IFileAccessObserver> observer = iface_cast<IFileAccessObserver>(obj);
if (observer == nullptr) {
HILOG_INFO("get observer fail");
FinishTrace(HITRACE_TAG_FILEMANAGEMENT);
return E_IPCS;
}
int ret = UnregisterNotify(*uri, observer);
if (!reply.WriteInt32(ret)) {
HILOG_ERROR("Parameter UnregisterNotify fail to WriteInt32 ret");
FinishTrace(HITRACE_TAG_FILEMANAGEMENT);

View File

@ -0,0 +1,68 @@
/*
* Copyright (c) 2023 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT 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 "observer_callback_proxy.h"
#include "file_access_framework_errno.h"
#include "hilog_wrapper.h"
#include "hitrace_meter.h"
#include "ipc_types.h"
#include "message_option.h"
#include "message_parcel.h"
namespace OHOS {
namespace FileAccessFwk {
void ObserverCallbackProxy::OnChange(NotifyMessage &notifyMessage)
{
StartTrace(HITRACE_TAG_FILEMANAGEMENT, "OnChange");
MessageParcel data;
if (!data.WriteInterfaceToken(ObserverCallbackProxy::GetDescriptor())) {
HILOG_ERROR("WriteInterfaceToken failed");
FinishTrace(HITRACE_TAG_FILEMANAGEMENT);
return;
}
if (!data.WriteParcelable(&notifyMessage)) {
HILOG_ERROR("fail to WriteParcelable notifyMessage");
FinishTrace(HITRACE_TAG_FILEMANAGEMENT);
return;
}
MessageParcel reply;
MessageOption option;
int err = Remote()->SendRequest(CMD_ONCHANGE, data, reply, option);
if (err != ERR_OK) {
HILOG_ERROR("fail to SendRequest. err: %{public}d", err);
FinishTrace(HITRACE_TAG_FILEMANAGEMENT);
return;
}
int ret = E_IPCS;
if (!reply.ReadInt32(ret)) {
HILOG_ERROR("fail to ReadInt32 ret");
FinishTrace(HITRACE_TAG_FILEMANAGEMENT);
return;
}
if (ret != ERR_OK) {
HILOG_ERROR("OnChange operation failed ret : %{public}d", ret);
FinishTrace(HITRACE_TAG_FILEMANAGEMENT);
return;
}
FinishTrace(HITRACE_TAG_FILEMANAGEMENT);
return;
}
} // namespace FileAccessFwk
} // namespace OHOS

View File

@ -0,0 +1,87 @@
/*
* Copyright (c) 2023 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT 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 "observer_callback_stub.h"
#include <string>
#include <memory>
#include "accesstoken_kit.h"
#include "file_access_framework_errno.h"
#include "hilog_wrapper.h"
#include "hitrace_meter.h"
#include "ipc_object_stub.h"
#include "ipc_skeleton.h"
#include "ipc_types.h"
#include "message_parcel.h"
namespace OHOS {
namespace FileAccessFwk {
ObserverCallbackStub::~ObserverCallbackStub()
{
stubFuncMap_.clear();
}
void ObserverCallbackStub::InitStubFuncMap()
{
if (stubFuncMap_.size() == 0) {
stubFuncMap_[CMD_ONCHANGE] = &ObserverCallbackStub::OnChangeStub;
}
}
int32_t ObserverCallbackStub::OnRemoteRequest(uint32_t code, MessageParcel& data, MessageParcel& reply,
MessageOption& option)
{
StartTrace(HITRACE_TAG_FILEMANAGEMENT, "OnRemoteRequest");
InitStubFuncMap();
std::u16string descriptor = ObserverCallbackStub::GetDescriptor();
std::u16string remoteDescriptor = data.ReadInterfaceToken();
if (descriptor != remoteDescriptor) {
FinishTrace(HITRACE_TAG_FILEMANAGEMENT);
return ERR_INVALID_STATE;
}
const auto &itFunc = stubFuncMap_.find(code);
if (itFunc != stubFuncMap_.end()) {
FinishTrace(HITRACE_TAG_FILEMANAGEMENT);
return (this->*(itFunc->second))(data, reply);
}
FinishTrace(HITRACE_TAG_FILEMANAGEMENT);
return IPCObjectStub::OnRemoteRequest(code, data, reply, option);
}
int32_t ObserverCallbackStub::OnChangeStub(MessageParcel &data, MessageParcel &reply)
{
StartTrace(HITRACE_TAG_FILEMANAGEMENT, "OnChangeStub");
std::shared_ptr<NotifyMessage> notifyMessage(data.ReadParcelable<NotifyMessage>());
if (notifyMessage == nullptr) {
HILOG_ERROR("OnChange uri is nullptr");
FinishTrace(HITRACE_TAG_FILEMANAGEMENT);
return E_URIS;
}
OnChange(*notifyMessage);
int ret = ERR_OK;
if (!reply.WriteInt32(ret)) {
HILOG_ERROR("Parameter OnChangeStub fail to WriteInt32 ret");
FinishTrace(HITRACE_TAG_FILEMANAGEMENT);
return E_IPCS;
}
FinishTrace(HITRACE_TAG_FILEMANAGEMENT);
return ERR_OK;
}
}
}

View File

@ -39,10 +39,12 @@ enum {
E_CALLBACK_AND_URI_HAS_NOT_RELATIONS, // Uri and callback do not has relations, can not unregister
E_CALLBACK_IS_NOT_REGISTER, // CallBack is not registered, can not unregister
E_CAN_NOT_FIND_URI, // Can not find registered uri
E_DO_NOT_HAVE_PARENT, // Do not have parent uri in observerNode
E_LOAD_SA, // load SA failed
E_PERMISSION = 201, // Permission verification failed
E_PERMISSION_SYS, // is not system app
E_COUNT
};
} // namespace FileAccessFwk
} // namespace OHOS
#endif // FILE_ACCESS_FRAMEWORK_ERRNO_H
#endif // FILE_ACCESS_FRAMEWORK_ERRNO_H