• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2022-2023 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #include "data_ability_helper_impl.h"
17 
18 #include "ability_manager_client.h"
19 #include "ability_scheduler_interface.h"
20 #include "ability_thread.h"
21 #include "abs_shared_result_set.h"
22 #include "hitrace_meter.h"
23 #include "data_ability_observer_interface.h"
24 #include "data_ability_operation.h"
25 #include "data_ability_predicates.h"
26 #include "data_ability_result.h"
27 #include "hilog_wrapper.h"
28 #include "values_bucket.h"
29 
30 namespace OHOS {
31 namespace AppExecFwk {
32 std::string SchemeOhos = "dataability";
33 using IAbilityScheduler = OHOS::AAFwk::IAbilityScheduler;
34 using AbilityManagerClient = OHOS::AAFwk::AbilityManagerClient;
DataAbilityHelperImpl(const std::shared_ptr<Context> & context,const std::shared_ptr<Uri> & uri,const sptr<IAbilityScheduler> & dataAbilityProxy,bool tryBind)35 DataAbilityHelperImpl::DataAbilityHelperImpl(const std::shared_ptr<Context> &context, const std::shared_ptr<Uri> &uri,
36     const sptr<IAbilityScheduler> &dataAbilityProxy, bool tryBind)
37 {
38     token_ = context->GetToken();
39     context_ = std::weak_ptr<Context>(context);
40     uri_ = uri;
41     tryBind_ = tryBind;
42     dataAbilityProxy_ = dataAbilityProxy;
43 }
44 
DataAbilityHelperImpl(const std::shared_ptr<OHOS::AbilityRuntime::Context> & context,const std::shared_ptr<Uri> & uri,const sptr<IAbilityScheduler> & dataAbilityProxy,bool tryBind)45 DataAbilityHelperImpl::DataAbilityHelperImpl(const std::shared_ptr<OHOS::AbilityRuntime::Context> &context,
46     const std::shared_ptr<Uri> &uri, const sptr<IAbilityScheduler> &dataAbilityProxy, bool tryBind)
47 {
48     token_ = context->GetToken();
49     uri_ = uri;
50     tryBind_ = tryBind;
51     dataAbilityProxy_ = dataAbilityProxy;
52 }
53 
DataAbilityHelperImpl(const std::shared_ptr<Context> & context)54 DataAbilityHelperImpl::DataAbilityHelperImpl(const std::shared_ptr<Context> &context)
55 {
56     token_ = context->GetToken();
57     context_ = std::weak_ptr<Context>(context);
58 }
59 
DataAbilityHelperImpl(const sptr<IRemoteObject> & token,const std::shared_ptr<Uri> & uri,const sptr<AAFwk::IAbilityScheduler> & dataAbilityProxy)60 DataAbilityHelperImpl::DataAbilityHelperImpl(const sptr<IRemoteObject> &token, const std::shared_ptr<Uri> &uri,
61     const sptr<AAFwk::IAbilityScheduler> &dataAbilityProxy)
62 {
63     token_ = token;
64     uri_ = uri;
65     tryBind_ = false;
66     dataAbilityProxy_ = dataAbilityProxy;
67     isSystemCaller_ = true;
68 }
69 
DataAbilityHelperImpl(const sptr<IRemoteObject> & token)70 DataAbilityHelperImpl::DataAbilityHelperImpl(const sptr<IRemoteObject> &token)
71 {
72     token_ = token;
73     isSystemCaller_ = true;
74 }
75 
AddDataAbilityDeathRecipient(const sptr<IRemoteObject> & token)76 void DataAbilityHelperImpl::AddDataAbilityDeathRecipient(const sptr<IRemoteObject> &token)
77 {
78     if (token != nullptr && callerDeathRecipient_ != nullptr) {
79         HILOG_INFO("Remove death recipient.");
80         token->RemoveDeathRecipient(callerDeathRecipient_);
81     }
82     if (callerDeathRecipient_ == nullptr) {
83         std::weak_ptr<DataAbilityHelperImpl> thisWeakPtr(shared_from_this());
84         callerDeathRecipient_ =
85             new DataAbilityDeathRecipient([thisWeakPtr](const wptr<IRemoteObject> &remote) {
86                 auto DataAbilityHelperImpl = thisWeakPtr.lock();
87                 if (DataAbilityHelperImpl) {
88                     DataAbilityHelperImpl->OnSchedulerDied(remote);
89                 }
90             });
91     }
92     HILOG_INFO("Add death recipient.");
93     if (token == nullptr || !token->AddDeathRecipient(callerDeathRecipient_)) {
94         HILOG_ERROR("AddDeathRecipient failed.");
95     }
96 }
97 
OnSchedulerDied(const wptr<IRemoteObject> & remote)98 void DataAbilityHelperImpl::OnSchedulerDied(const wptr<IRemoteObject> &remote)
99 {
100     HILOG_INFO("On scheduler died.");
101     std::lock_guard<std::mutex> guard(lock_);
102     auto object = remote.promote();
103     object = nullptr;
104     dataAbilityProxy_ = nullptr;
105     uri_ = nullptr;
106 }
107 
108 /**
109  * @brief Creates a DataAbilityHelperImpl instance without specifying the Uri based on the given Context.
110  *
111  * @param context Indicates the Context object on OHOS.
112  *
113  * @return Returns the created DataAbilityHelperImpl instance where Uri is not specified.
114  */
Creator(const std::shared_ptr<Context> & context)115 std::shared_ptr<DataAbilityHelperImpl> DataAbilityHelperImpl::Creator(const std::shared_ptr<Context> &context)
116 {
117     if (context == nullptr) {
118         HILOG_ERROR("Input param invalid, context is nullptr.");
119         return nullptr;
120     }
121 
122     auto ptrDataAbilityHelperImpl = new (std::nothrow) DataAbilityHelperImpl(context);
123     if (ptrDataAbilityHelperImpl == nullptr) {
124         HILOG_ERROR("New DataAbilityHelperImpl failed.");
125         return nullptr;
126     }
127 
128     return std::shared_ptr<DataAbilityHelperImpl>(ptrDataAbilityHelperImpl);
129 }
130 
131 /**
132  * @brief You can use this method to specify the Uri of the data to operate and set the binding relationship
133  * between the ability using the Data template (Data ability for short) and the associated client process in
134  * a DataAbilityHelperImpl instance.
135  *
136  * @param context Indicates the Context object on OHOS.
137  * @param uri Indicates the database table or disk file to operate.
138  * @param tryBind Specifies whether the exit of the corresponding Data ability process causes the exit of the
139  * client process.
140  *
141  * @return Returns the created DataAbilityHelperImpl instance.
142  */
Creator(const std::shared_ptr<Context> & context,const std::shared_ptr<Uri> & uri,const bool tryBind)143 std::shared_ptr<DataAbilityHelperImpl> DataAbilityHelperImpl::Creator(
144     const std::shared_ptr<Context> &context, const std::shared_ptr<Uri> &uri, const bool tryBind)
145 {
146     if (context == nullptr) {
147         HILOG_ERROR("Input param invalid, context is null.");
148         return nullptr;
149     }
150 
151     if (!CheckUri(uri)) {
152         HILOG_ERROR("uri is invalid");
153         return nullptr;
154     }
155 
156     sptr<IAbilityScheduler> dataAbilityProxy =
157         AbilityManagerClient::GetInstance()->AcquireDataAbility(*uri.get(), tryBind, context->GetToken());
158     if (dataAbilityProxy == nullptr) {
159         HILOG_ERROR("Acquire data ability error.");
160         return nullptr;
161     }
162 
163     auto ptrDataAbilityHelperImpl = new (std::nothrow) DataAbilityHelperImpl(context, uri, dataAbilityProxy, tryBind);
164     if (ptrDataAbilityHelperImpl == nullptr) {
165         HILOG_ERROR("New DataAbilityHelperImpl error.");
166         return nullptr;
167     }
168 
169     return std::shared_ptr<DataAbilityHelperImpl>(ptrDataAbilityHelperImpl);
170 }
171 
172 /**
173  * @brief You can use this method to specify the Uri of the data to operate and set the binding relationship
174  * between the ability using the Data template (Data ability for short) and the associated client process in
175  * a DataAbilityHelperImpl instance.
176  *
177  * @param context Indicates the Context object on OHOS.
178  * @param uri Indicates the database table or disk file to operate.
179  * @param tryBind Specifies whether the exit of the corresponding Data ability process causes the exit of the
180  * client process.
181  *
182  * @return Returns the created DataAbilityHelperImpl instance.
183  */
Creator(const std::shared_ptr<OHOS::AbilityRuntime::Context> & context,const std::shared_ptr<Uri> & uri,const bool tryBind)184 std::shared_ptr<DataAbilityHelperImpl> DataAbilityHelperImpl::Creator(
185     const std::shared_ptr<OHOS::AbilityRuntime::Context> &context, const std::shared_ptr<Uri> &uri, const bool tryBind)
186 {
187     if (context == nullptr) {
188         HILOG_ERROR("Input param invalid, context is nullptr.");
189         return nullptr;
190     }
191 
192     if (!CheckUri(uri)) {
193         HILOG_ERROR("uri is invalid.");
194         return nullptr;
195     }
196 
197     sptr<IAbilityScheduler> dataAbilityProxy =
198         AbilityManagerClient::GetInstance()->AcquireDataAbility(*uri.get(), tryBind, context->GetToken());
199     if (dataAbilityProxy == nullptr) {
200         HILOG_ERROR("Acquire data ability failed.");
201         return nullptr;
202     }
203 
204     auto ptrDataAbilityHelperImpl = new (std::nothrow) DataAbilityHelperImpl(context, uri, dataAbilityProxy, tryBind);
205     if (ptrDataAbilityHelperImpl == nullptr) {
206         HILOG_ERROR("New DataAbilityHelperImpl failed.");
207         return nullptr;
208     }
209 
210     return std::shared_ptr<DataAbilityHelperImpl>(ptrDataAbilityHelperImpl);
211 }
212 
213 /**
214  * @brief Creates a DataAbilityHelperImpl instance without specifying the Uri based.
215  *
216  * @param token Indicates the System token.
217  *
218  * @return Returns the created DataAbilityHelperImpl instance where Uri is not specified.
219  */
Creator(const sptr<IRemoteObject> & token)220 std::shared_ptr<DataAbilityHelperImpl> DataAbilityHelperImpl::Creator(const sptr<IRemoteObject> &token)
221 {
222     if (token == nullptr) {
223         HILOG_ERROR("Input param invalid, token is nullptr.");
224         return nullptr;
225     }
226 
227     auto ptrDataAbilityHelperImpl = new (std::nothrow) DataAbilityHelperImpl(token);
228     if (ptrDataAbilityHelperImpl == nullptr) {
229         HILOG_ERROR("New DataAbilityHelperImpl failed.");
230         return nullptr;
231     }
232 
233     return std::shared_ptr<DataAbilityHelperImpl>(ptrDataAbilityHelperImpl);
234 }
235 
236 /**
237  * @brief You can use this method to specify the Uri of the data to operate and set the binding relationship
238  * between the ability using the Data template (Data ability for short) and the associated client process in
239  * a DataAbilityHelperImpl instance.
240  *
241  * @param token Indicates the System token.
242  * @param uri Indicates the database table or disk file to operate.
243  *
244  * @return Returns the created DataAbilityHelperImpl instance.
245  */
Creator(const sptr<IRemoteObject> & token,const std::shared_ptr<Uri> & uri)246 std::shared_ptr<DataAbilityHelperImpl> DataAbilityHelperImpl::Creator(
247     const sptr<IRemoteObject> &token, const std::shared_ptr<Uri> &uri)
248 {
249     if (token == nullptr) {
250         HILOG_ERROR("Input param invalid, token is nullptr.");
251         return nullptr;
252     }
253 
254     if (!CheckUri(uri)) {
255         HILOG_ERROR("uri is invalid.");
256         return nullptr;
257     }
258 
259     sptr<IAbilityScheduler> dataAbilityProxy =
260         AbilityManagerClient::GetInstance()->AcquireDataAbility(*uri.get(), false, token);
261     if (dataAbilityProxy == nullptr) {
262         HILOG_ERROR("Acquire data ability failed.");
263         return nullptr;
264     }
265 
266     auto ptrDataAbilityHelperImpl = new (std::nothrow) DataAbilityHelperImpl(token, uri, dataAbilityProxy);
267     if (ptrDataAbilityHelperImpl == nullptr) {
268         HILOG_ERROR("New DataAbilityHelperImpl failed.");
269         return nullptr;
270     }
271 
272     return std::shared_ptr<DataAbilityHelperImpl>(ptrDataAbilityHelperImpl);
273 }
274 
275 /**
276  * @brief Releases the client resource of the Data ability.
277  * You should call this method to releases client resource after the data operations are complete.
278  *
279  * @return Returns true if the resource is successfully released; returns false otherwise.
280  */
Release()281 bool DataAbilityHelperImpl::Release()
282 {
283     if (uri_ == nullptr) {
284         HILOG_ERROR("Release failed, uri_ is nullptr.");
285         return false;
286     }
287 
288     int err = AbilityManagerClient::GetInstance()->ReleaseDataAbility(dataAbilityProxy_, token_);
289     if (err != ERR_OK) {
290         HILOG_ERROR("Release data ability failed, err = %{public}d.", err);
291         return false;
292     }
293 
294     return true;
295 }
296 
297 /**
298  * @brief Obtains the MIME types of files supported.
299  *
300  * @param uri Indicates the path of the files to obtain.
301  * @param mimeTypeFilter Indicates the MIME types of the files to obtain. This parameter cannot be null.
302  *
303  * @return Returns the matched MIME types. If there is no match, null is returned.
304  */
GetFileTypes(Uri & uri,const std::string & mimeTypeFilter)305 std::vector<std::string> DataAbilityHelperImpl::GetFileTypes(Uri &uri, const std::string &mimeTypeFilter)
306 {
307     std::vector<std::string> matchedMIMEs;
308     sptr<AAFwk::IAbilityScheduler> dataAbilityProxy = GetDataAbilityProxy(uri);
309     if (dataAbilityProxy == nullptr) {
310         HILOG_ERROR("Get data ability proxy failed.");
311         return matchedMIMEs;
312     }
313 
314     matchedMIMEs = dataAbilityProxy->GetFileTypes(uri, mimeTypeFilter);
315 
316     ReleaseDataAbility(dataAbilityProxy);
317     HILOG_INFO("Return matchedMIMEs size: %{public}zu.", matchedMIMEs.size());
318     return matchedMIMEs;
319 }
320 
321 /**
322  * @brief Opens a file in a specified remote path.
323  *
324  * @param uri Indicates the path of the file to open.
325  * @param mode Indicates the file open mode, which can be "r" for read-only access, "w" for write-only access
326  * (erasing whatever data is currently in the file), "wt" for write access that truncates any existing file,
327  * "wa" for write-only access to append to any existing data, "rw" for read and write access on any existing data,
328  *  or "rwt" for read and write access that truncates any existing file.
329  *
330  * @return Returns the file descriptor.
331  */
OpenFile(Uri & uri,const std::string & mode)332 int DataAbilityHelperImpl::OpenFile(Uri &uri, const std::string &mode)
333 {
334     int fd = -1;
335     sptr<AAFwk::IAbilityScheduler> dataAbilityProxy = GetDataAbilityProxy(uri);
336     if (dataAbilityProxy == nullptr) {
337         HILOG_ERROR("Get data ability proxy failed.");
338         return fd;
339     }
340 
341     fd = dataAbilityProxy->OpenFile(uri, mode);
342 
343     ReleaseDataAbility(dataAbilityProxy);
344     HILOG_INFO("Return fd: %{public}d.", fd);
345     return fd;
346 }
347 
348 /**
349  * @brief This is like openFile, open a file that need to be able to return sub-sections of files,often assets
350  * inside of their .hap.
351  *
352  * @param uri Indicates the path of the file to open.
353  * @param mode Indicates the file open mode, which can be "r" for read-only access, "w" for write-only access
354  * (erasing whatever data is currently in the file), "wt" for write access that truncates any existing file,
355  * "wa" for write-only access to append to any existing data, "rw" for read and write access on any existing
356  * data, or "rwt" for read and write access that truncates any existing file.
357  *
358  * @return Returns the RawFileDescriptor object containing file descriptor.
359  */
OpenRawFile(Uri & uri,const std::string & mode)360 int DataAbilityHelperImpl::OpenRawFile(Uri &uri, const std::string &mode)
361 {
362     int fd = -1;
363     sptr<AAFwk::IAbilityScheduler> dataAbilityProxy = GetDataAbilityProxy(uri);
364     if (dataAbilityProxy == nullptr) {
365         HILOG_ERROR("Get data ability proxy failed.");
366         return fd;
367     }
368 
369     fd = dataAbilityProxy->OpenRawFile(uri, mode);
370 
371     ReleaseDataAbility(dataAbilityProxy);
372     HILOG_INFO("Return fd: %{public}d.", fd);
373     return fd;
374 }
375 
376 /**
377  * @brief Inserts a single data record into the database.
378  *
379  * @param uri Indicates the path of the data to operate.
380  * @param value Indicates the data record to insert. If this parameter is null, a blank row will be inserted.
381  *
382  * @return Returns the index of the inserted data record.
383  */
Insert(Uri & uri,const NativeRdb::ValuesBucket & value)384 int DataAbilityHelperImpl::Insert(Uri &uri, const NativeRdb::ValuesBucket &value)
385 {
386     int index = -1;
387     sptr<AAFwk::IAbilityScheduler> dataAbilityProxy = GetDataAbilityProxy(uri);
388     if (dataAbilityProxy == nullptr) {
389         HILOG_ERROR("Get data ability proxy failed.");
390         return index;
391     }
392 
393     index = dataAbilityProxy->Insert(uri, value);
394 
395     ReleaseDataAbility(dataAbilityProxy);
396     HILOG_INFO("Return index: %{public}d.", index);
397     return index;
398 }
399 
Call(const Uri & uri,const std::string & method,const std::string & arg,const AppExecFwk::PacMap & pacMap)400 std::shared_ptr<AppExecFwk::PacMap> DataAbilityHelperImpl::Call(
401     const Uri &uri, const std::string &method, const std::string &arg, const AppExecFwk::PacMap &pacMap)
402 {
403     std::shared_ptr<AppExecFwk::PacMap> result = nullptr;
404     sptr<AAFwk::IAbilityScheduler> dataAbilityProxy = GetDataAbilityProxy(uri);
405     if (dataAbilityProxy == nullptr) {
406         HILOG_ERROR("Get data ability proxy failed.");
407         return result;
408     }
409 
410     result = dataAbilityProxy->Call(uri, method, arg, pacMap);
411 
412     ReleaseDataAbility(dataAbilityProxy);
413     HILOG_INFO("Return result is or not nullptr: %{public}d.", result == nullptr);
414     return result;
415 }
416 
417 /**
418  * @brief Updates data records in the database.
419  *
420  * @param uri Indicates the path of data to update.
421  * @param value Indicates the data to update. This parameter can be null.
422  * @param predicates Indicates filter criteria. You should define the processing logic when this parameter is null.
423  *
424  * @return Returns the number of data records updated.
425  */
Update(Uri & uri,const NativeRdb::ValuesBucket & value,const NativeRdb::DataAbilityPredicates & predicates)426 int DataAbilityHelperImpl::Update(
427     Uri &uri, const NativeRdb::ValuesBucket &value, const NativeRdb::DataAbilityPredicates &predicates)
428 {
429     int index = -1;
430     sptr<AAFwk::IAbilityScheduler> dataAbilityProxy = GetDataAbilityProxy(uri);
431     if (dataAbilityProxy == nullptr) {
432         HILOG_ERROR("Get data ability proxy failed.");
433         return index;
434     }
435 
436     index = dataAbilityProxy->Update(uri, value, predicates);
437 
438     ReleaseDataAbility(dataAbilityProxy);
439     HILOG_INFO("Return index: %{public}d.", index);
440     return index;
441 }
442 
443 /**
444  * @brief Deletes one or more data records from the database.
445  *
446  * @param uri Indicates the path of the data to operate.
447  * @param predicates Indicates filter criteria. You should define the processing logic when this parameter is null.
448  *
449  * @return Returns the number of data records deleted.
450  */
Delete(Uri & uri,const NativeRdb::DataAbilityPredicates & predicates)451 int DataAbilityHelperImpl::Delete(Uri &uri, const NativeRdb::DataAbilityPredicates &predicates)
452 {
453     int index = -1;
454     sptr<AAFwk::IAbilityScheduler> dataAbilityProxy = GetDataAbilityProxy(uri);
455     if (dataAbilityProxy == nullptr) {
456         HILOG_ERROR("Get data ability proxy failed.");
457         return index;
458     }
459 
460     index = dataAbilityProxy->Delete(uri, predicates);
461 
462     ReleaseDataAbility(dataAbilityProxy);
463     HILOG_INFO("Return index: %{public}d.", index);
464     return index;
465 }
466 
467 /**
468  * @brief Deletes one or more data records from the database.
469  *
470  * @param uri Indicates the path of data to query.
471  * @param columns Indicates the columns to query. If this parameter is null, all columns are queried.
472  * @param predicates Indicates filter criteria. You should define the processing logic when this parameter is null.
473  *
474  * @return Returns the query result.
475  */
Query(Uri & uri,std::vector<std::string> & columns,const NativeRdb::DataAbilityPredicates & predicates)476 std::shared_ptr<NativeRdb::AbsSharedResultSet> DataAbilityHelperImpl::Query(
477     Uri &uri, std::vector<std::string> &columns, const NativeRdb::DataAbilityPredicates &predicates)
478 {
479     std::shared_ptr<NativeRdb::AbsSharedResultSet> resultset = nullptr;
480     sptr<AAFwk::IAbilityScheduler> dataAbilityProxy = GetDataAbilityProxy(uri);
481     if (dataAbilityProxy == nullptr) {
482         HILOG_ERROR("Get data ability proxy failed.");
483         return resultset;
484     }
485 
486     resultset = dataAbilityProxy->Query(uri, columns, predicates);
487 
488     ReleaseDataAbility(dataAbilityProxy);
489     HILOG_DEBUG("Return resultset is or not nullptr: %{public}d.", resultset == nullptr);
490     return resultset;
491 }
492 
493 /**
494  * @brief Obtains the MIME type matching the data specified by the URI of the Data ability. This method should be
495  * implemented by a Data ability. Data abilities supports general data types, including text, HTML, and JPEG.
496  *
497  * @param uri Indicates the URI of the data.
498  *
499  * @return Returns the MIME type that matches the data specified by uri.
500  */
GetType(Uri & uri)501 std::string DataAbilityHelperImpl::GetType(Uri &uri)
502 {
503     std::string type;
504     sptr<AAFwk::IAbilityScheduler> dataAbilityProxy = GetDataAbilityProxy(uri);
505     if (dataAbilityProxy == nullptr) {
506         HILOG_ERROR("Get data ability proxy failed.");
507         return type;
508     }
509 
510     type = dataAbilityProxy->GetType(uri);
511 
512     ReleaseDataAbility(dataAbilityProxy);
513     HILOG_INFO("Return type: %{public}s.", type.c_str());
514     return type;
515 }
516 
517 /**
518  * @brief Reloads data in the database.
519  *
520  * @param uri Indicates the position where the data is to reload. This parameter is mandatory.
521  * @param extras Indicates the PacMap object containing the additional parameters to be passed in this call. This
522  * parameter can be null. If a custom Sequenceable object is put in the PacMap object and will be transferred across
523  * processes, you must call BasePacMap.setClassLoader(ClassLoader) to set a class loader for the custom object.
524  *
525  * @return Returns true if the data is successfully reloaded; returns false otherwise.
526  */
Reload(Uri & uri,const PacMap & extras)527 bool DataAbilityHelperImpl::Reload(Uri &uri, const PacMap &extras)
528 {
529     bool ret = false;
530     sptr<AAFwk::IAbilityScheduler> dataAbilityProxy = GetDataAbilityProxy(uri);
531     if (dataAbilityProxy == nullptr) {
532         HILOG_ERROR("Get data ability proxy failed.");
533         return ret;
534     }
535 
536     ret = dataAbilityProxy->Reload(uri, extras);
537 
538     ReleaseDataAbility(dataAbilityProxy);
539     HILOG_INFO("Return ret: %{public}d.", ret);
540     return ret;
541 }
542 
543 /**
544  * @brief Inserts multiple data records into the database.
545  *
546  * @param uri Indicates the path of the data to operate.
547  * @param values Indicates the data records to insert.
548  *
549  * @return Returns the number of data records inserted.
550  */
BatchInsert(Uri & uri,const std::vector<NativeRdb::ValuesBucket> & values)551 int DataAbilityHelperImpl::BatchInsert(Uri &uri, const std::vector<NativeRdb::ValuesBucket> &values)
552 {
553     int ret = -1;
554     sptr<AAFwk::IAbilityScheduler> dataAbilityProxy = GetDataAbilityProxy(uri);
555     if (dataAbilityProxy == nullptr) {
556         HILOG_ERROR("Get data ability proxy failed.");
557         return ret;
558     }
559 
560     ret = dataAbilityProxy->BatchInsert(uri, values);
561 
562     ReleaseDataAbility(dataAbilityProxy);
563     HILOG_INFO("Return ret: %{public}d.", ret);
564     return ret;
565 }
566 
CheckUriParam(const Uri & uri)567 bool DataAbilityHelperImpl::CheckUriParam(const Uri &uri)
568 {
569     Uri checkUri(uri.ToString());
570     if (!CheckOhosUri(checkUri)) {
571         HILOG_ERROR("Check ohos uri failed, uri: %{public}s.", uri.ToString().c_str());
572         return false;
573     }
574 
575     // do not directly use uri_ here, otherwise, it will probably crash.
576     std::vector<std::string> segments;
577     {
578         std::lock_guard<std::mutex> guard(lock_);
579         if (!uri_) {
580             HILOG_INFO("uri_ is nullptr, no need check.");
581             return true;
582         }
583         Uri checkUri(uri_->ToString());
584         if (!CheckOhosUri(checkUri)) {
585             HILOG_ERROR("Check ohos uri failed, uri_: %{public}s.", uri_->ToString().c_str());
586             return false;
587         }
588 
589         uri_->GetPathSegments(segments);
590     }
591 
592     std::vector<std::string> checkSegments;
593     checkUri.GetPathSegments(checkSegments);
594     if (checkSegments.empty() || segments.empty() || checkSegments[0] != segments[0]) {
595         HILOG_ERROR("The dataability in uri doesn't equal the one in uri_.");
596         return false;
597     }
598 
599     return true;
600 }
601 
CheckOhosUri(const Uri & checkUri)602 bool DataAbilityHelperImpl::CheckOhosUri(const Uri &checkUri)
603 {
604     Uri uri(checkUri);
605     if (uri.GetScheme() != SchemeOhos) {
606         HILOG_ERROR("Input uri is not a dataability one, uri: %{public}s.", uri.ToString().c_str());
607         return false;
608     }
609 
610     std::vector<std::string> segments;
611     uri.GetPathSegments(segments);
612     if (segments.empty()) {
613         HILOG_ERROR("There is no segments in the uri, uri: %{public}s.", uri.ToString().c_str());
614         return false;
615     }
616 
617     if (uri.GetPath() == "") {
618         HILOG_ERROR("The path in the uri is empty, uri: %{public}s.", uri.ToString().c_str());
619         return false;
620     }
621 
622     return true;
623 }
624 
625 /**
626  * @brief Registers an observer to DataObsMgr specified by the given Uri.
627  *
628  * @param uri, Indicates the path of the data to operate.
629  * @param dataObserver, Indicates the IDataAbilityObserver object.
630  */
RegisterObserver(const Uri & uri,const sptr<AAFwk::IDataAbilityObserver> & dataObserver)631 void DataAbilityHelperImpl::RegisterObserver(const Uri &uri, const sptr<AAFwk::IDataAbilityObserver> &dataObserver)
632 {
633     if (!CheckUriAndDataObserver(uri, dataObserver)) {
634         HILOG_ERROR("RegisterObserver param is invalid.");
635         return;
636     }
637 
638     Uri tmpUri(uri.ToString());
639 
640     std::lock_guard<std::mutex> lock_l(oplock_);
641     sptr<AAFwk::IAbilityScheduler> dataAbilityProxy = nullptr;
642     if (uri_ == nullptr) {
643         auto dataability = registerMap_.find(dataObserver);
644         if (dataability == registerMap_.end()) {
645             dataAbilityProxy = AbilityManagerClient::GetInstance()->AcquireDataAbility(uri, tryBind_, token_);
646             registerMap_.emplace(dataObserver, dataAbilityProxy);
647             uriMap_.emplace(dataObserver, tmpUri.GetPath());
648         } else {
649             auto path = uriMap_.find(dataObserver);
650             if (path == uriMap_.end()) {
651                 return;
652             }
653             if (path->second != tmpUri.GetPath()) {
654                 HILOG_ERROR("Input uri's path is not equal the one the observer used.");
655                 return;
656             }
657             dataAbilityProxy = dataability->second;
658         }
659     } else {
660         dataAbilityProxy = dataAbilityProxy_;
661     }
662 
663     if (dataAbilityProxy == nullptr) {
664         HILOG_ERROR("dataAbilityProxy is nullptr.");
665         registerMap_.erase(dataObserver);
666         uriMap_.erase(dataObserver);
667         return;
668     }
669     dataAbilityProxy->ScheduleRegisterObserver(uri, dataObserver);
670 }
671 
672 /**
673  * @brief Deregisters an observer used for DataObsMgr specified by the given Uri.
674  *
675  * @param uri, Indicates the path of the data to operate.
676  * @param dataObserver, Indicates the IDataAbilityObserver object.
677  */
UnregisterObserver(const Uri & uri,const sptr<AAFwk::IDataAbilityObserver> & dataObserver)678 void DataAbilityHelperImpl::UnregisterObserver(const Uri &uri, const sptr<AAFwk::IDataAbilityObserver> &dataObserver)
679 {
680     if (!CheckUriAndDataObserver(uri, dataObserver)) {
681         HILOG_ERROR("UnregisterObserver param is invalid.");
682         return;
683     }
684 
685     Uri tmpUri(uri.ToString());
686     std::lock_guard<std::mutex> lock_l(oplock_);
687     sptr<AAFwk::IAbilityScheduler> dataAbilityProxy = nullptr;
688     if (uri_ == nullptr) {
689         auto dataability = registerMap_.find(dataObserver);
690         if (dataability == registerMap_.end()) {
691             return;
692         }
693         auto path = uriMap_.find(dataObserver);
694         if (path == uriMap_.end()) {
695             return;
696         }
697         if (path->second != tmpUri.GetPath()) {
698             HILOG_ERROR("Input uri's path is not equal the one the observer used.");
699             return;
700         }
701         dataAbilityProxy = dataability->second;
702     } else {
703         dataAbilityProxy = dataAbilityProxy_;
704     }
705 
706     if (dataAbilityProxy == nullptr) {
707         HILOG_ERROR("dataAbilityProxy is nullptr.");
708         return;
709     }
710 
711     dataAbilityProxy->ScheduleUnregisterObserver(uri, dataObserver);
712     ReleaseDataAbility(dataAbilityProxy_);
713     if (uri_ == nullptr) {
714         dataAbilityProxy_ = nullptr;
715     }
716     registerMap_.erase(dataObserver);
717     uriMap_.erase(dataObserver);
718 }
719 
720 /**
721  * @brief Notifies the registered observers of a change to the data resource specified by Uri.
722  *
723  * @param uri, Indicates the path of the data to operate.
724  */
NotifyChange(const Uri & uri)725 void DataAbilityHelperImpl::NotifyChange(const Uri &uri)
726 {
727     sptr<AAFwk::IAbilityScheduler> dataAbilityProxy = GetDataAbilityProxy(uri);
728     if (dataAbilityProxy == nullptr) {
729         HILOG_ERROR("Get data ability proxy failed.");
730         return;
731     }
732 
733     dataAbilityProxy->ScheduleNotifyChange(uri);
734     ReleaseDataAbility(dataAbilityProxy);
735 }
736 
737 /**
738  * @brief Converts the given uri that refer to the Data ability into a normalized URI. A normalized URI can be used
739  * across devices, persisted, backed up, and restored. It can refer to the same item in the Data ability even if the
740  * context has changed. If you implement URI normalization for a Data ability, you must also implement
741  * denormalizeUri(ohos.utils.net.Uri) to enable URI denormalization. After this feature is enabled, URIs passed to any
742  * method that is called on the Data ability must require normalization verification and denormalization. The default
743  * implementation of this method returns null, indicating that this Data ability does not support URI normalization.
744  *
745  * @param uri Indicates the Uri object to normalize.
746  *
747  * @return Returns the normalized Uri object if the Data ability supports URI normalization; returns null otherwise.
748  */
NormalizeUri(Uri & uri)749 Uri DataAbilityHelperImpl::NormalizeUri(Uri &uri)
750 {
751     Uri urivalue("");
752     sptr<AAFwk::IAbilityScheduler> dataAbilityProxy = GetDataAbilityProxy(uri);
753     if (dataAbilityProxy == nullptr) {
754         HILOG_ERROR("Get data ability proxy failed.");
755         return urivalue;
756     }
757 
758     urivalue = dataAbilityProxy->NormalizeUri(uri);
759 
760     ReleaseDataAbility(dataAbilityProxy);
761     HILOG_INFO("Return uri: %{public}s.", urivalue.ToString().c_str());
762     return urivalue;
763 }
764 
765 /**
766  * @brief Converts the given normalized uri generated by normalizeUri(ohos.utils.net.Uri) into a denormalized one.
767  * The default implementation of this method returns the original URI passed to it.
768  *
769  * @param uri uri Indicates the Uri object to denormalize.
770  *
771  * @return Returns the denormalized Uri object if the denormalization is successful; returns the original Uri passed to
772  * this method if there is nothing to do; returns null if the data identified by the original Uri cannot be found in the
773  * current environment.
774  */
DenormalizeUri(Uri & uri)775 Uri DataAbilityHelperImpl::DenormalizeUri(Uri &uri)
776 {
777     Uri urivalue("");
778     sptr<AAFwk::IAbilityScheduler> dataAbilityProxy = GetDataAbilityProxy(uri);
779     if (dataAbilityProxy == nullptr) {
780         HILOG_ERROR("Get data ability proxy failed.");
781         return urivalue;
782     }
783 
784     urivalue = dataAbilityProxy->DenormalizeUri(uri);
785 
786     ReleaseDataAbility(dataAbilityProxy);
787     HILOG_INFO("Return uri: %{public}s.", urivalue.ToString().c_str());
788     return urivalue;
789 }
790 
ExecuteBatch(const Uri & uri,const std::vector<std::shared_ptr<DataAbilityOperation>> & operations)791 std::vector<std::shared_ptr<DataAbilityResult>> DataAbilityHelperImpl::ExecuteBatch(
792     const Uri &uri, const std::vector<std::shared_ptr<DataAbilityOperation>> &operations)
793 {
794     std::vector<std::shared_ptr<DataAbilityResult>> results;
795     sptr<AAFwk::IAbilityScheduler> dataAbilityProxy = GetDataAbilityProxy(uri, false);
796     if (dataAbilityProxy == nullptr) {
797         HILOG_ERROR("Get data ability proxy failed.");
798         return results;
799     }
800 
801     results = dataAbilityProxy->ExecuteBatch(operations);
802 
803     ReleaseDataAbility(dataAbilityProxy);
804     HILOG_INFO("Return results size: %{public}zu.", results.size());
805     return results;
806 }
807 
GetDataAbilityProxy(const Uri & uri,bool addDeathRecipient)808 sptr<AAFwk::IAbilityScheduler> DataAbilityHelperImpl::GetDataAbilityProxy(const Uri &uri, bool addDeathRecipient)
809 {
810     if (!CheckUriParam(uri)) {
811         HILOG_ERROR("Check uri param failed.");
812         return nullptr;
813     }
814     // if uri_ is nullptr, it indicates the operation(such as insert, delete and so on) is temporary,
815     // so, we need acquire the dataability before the operation.
816     sptr<AAFwk::IAbilityScheduler> dataAbilityProxy = dataAbilityProxy_;
817     if (uri_ == nullptr) {
818         HILOG_INFO("The uri_ is nullptr, need acquire data ability.");
819         dataAbilityProxy = AbilityManagerClient::GetInstance()->AcquireDataAbility(uri, tryBind_, token_);
820         if (dataAbilityProxy == nullptr) {
821             HILOG_ERROR("Acquire data ability failed.");
822             return nullptr;
823         }
824         if (addDeathRecipient && isSystemCaller_) {
825             AddDataAbilityDeathRecipient(dataAbilityProxy->AsObject());
826         }
827     }
828     return dataAbilityProxy;
829 }
830 
ReleaseDataAbility(sptr<AAFwk::IAbilityScheduler> dataAbilityProxy)831 void DataAbilityHelperImpl::ReleaseDataAbility(sptr<AAFwk::IAbilityScheduler> dataAbilityProxy)
832 {
833     // if uri_ is nullptr, it indicates the operation(such as insert, delete and so on) is temporary,
834     // so, we need release the dataability after the operation.
835     HILOG_INFO("ReleaseDataAbility start.");
836     if (!uri_ && dataAbilityProxy && token_) {
837         int ret = AbilityManagerClient::GetInstance()->ReleaseDataAbility(dataAbilityProxy, token_);
838         HILOG_INFO("Release data ability, ret: %{public}d.", ret);
839     }
840     HILOG_INFO("ReleaseDataAbility end.");
841 }
842 
CheckUri(const std::shared_ptr<Uri> & uri)843 bool DataAbilityHelperImpl::CheckUri(const std::shared_ptr<Uri> &uri)
844 {
845     if (uri == nullptr) {
846         HILOG_ERROR("Input param invalid, uri is nullptr.");
847         return false;
848     }
849 
850     if (uri->GetScheme() != SchemeOhos) {
851         HILOG_ERROR("Input param invalid, the uri is not dataability, Scheme: %{private}s.", uri->GetScheme().c_str());
852         return false;
853     }
854 
855     return true;
856 }
857 
CheckUriAndDataObserver(const Uri & uri,const sptr<AAFwk::IDataAbilityObserver> & dataObserver)858 bool DataAbilityHelperImpl::CheckUriAndDataObserver(const Uri &uri,
859     const sptr<AAFwk::IDataAbilityObserver> &dataObserver)
860 {
861     if (!CheckUriParam(uri)) {
862         HILOG_ERROR("Check uri param failed.");
863         return false;
864     }
865 
866     if (dataObserver == nullptr) {
867         HILOG_ERROR("Input param invalid, dataObserver is nullptr.");
868         return false;
869     }
870 
871     return true;
872 }
873 
OnRemoteDied(const wptr<IRemoteObject> & remote)874 void DataAbilityDeathRecipient::OnRemoteDied(const wptr<IRemoteObject> &remote)
875 {
876     HILOG_INFO("recv DataAbilityDeathRecipient death notice.");
877     if (handler_) {
878         handler_(remote);
879     }
880     HILOG_INFO("OnRemoteDied end.");
881 }
882 
DataAbilityDeathRecipient(RemoteDiedHandler handler)883 DataAbilityDeathRecipient::DataAbilityDeathRecipient(RemoteDiedHandler handler) : handler_(handler)
884 {}
885 
~DataAbilityDeathRecipient()886 DataAbilityDeathRecipient::~DataAbilityDeathRecipient()
887 {}
888 }  // namespace AppExecFwk
889 }  // namespace OHOS
890 
891