1 /*
2  * Copyright (c) 2022 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 #ifndef JS_DATASHARE_EXT_ABILITY_H
17 #define JS_DATASHARE_EXT_ABILITY_H
18 
19 #include <memory>
20 #include "datashare_result_set.h"
21 #include "datashare_predicates.h"
22 #include "datashare_ext_ability.h"
23 #include "js_runtime.h"
24 #include "napi/native_api.h"
25 #include "napi/native_common.h"
26 #include "napi/native_node_api.h"
27 #include "datashare_business_error.h"
28 
29 namespace OHOS {
30 namespace DataShare {
31 using namespace AbilityRuntime;
32 
33 /**
34  * @brief Basic datashare extension ability components.
35  */
36 class JsDataShareExtAbility : public DataShareExtAbility {
37 public:
38     explicit JsDataShareExtAbility(JsRuntime& jsRuntime);
39     virtual ~JsDataShareExtAbility() override;
40 
41     /**
42      * @brief Create JsDataShareExtAbility.
43      *
44      * @param runtime The runtime.
45      * @return The JsDataShareExtAbility instance.
46      */
47     static JsDataShareExtAbility* Create(const std::unique_ptr<Runtime>& runtime);
48 
49     /**
50      * @brief Init the extension.
51      *
52      * @param record the extension record.
53      * @param application the application info.
54      * @param handler the extension handler.
55      * @param token the remote token.
56      */
57     void Init(const std::shared_ptr<AppExecFwk::AbilityLocalRecord> &record,
58         const std::shared_ptr<AppExecFwk::OHOSApplication> &application,
59         std::shared_ptr<AppExecFwk::AbilityHandler> &handler,
60         const sptr<IRemoteObject> &token) override;
61 
62     /**
63      * @brief Called when this datashare extension ability is started. You must override this function if you want to
64      *        perform some initialization operations during extension startup.
65      *
66      * This function can be called only once in the entire lifecycle of an extension.
67      * @param Want Indicates the {@link Want} structure containing startup information about the extension.
68      */
69     void OnStart(const AAFwk::Want &want) override;
70 
71     /**
72      * @brief Called when this datashare extension ability is connected for the first time.
73      *
74      * You can override this function to implement your own processing logic.
75      *
76      * @param want Indicates the {@link Want} structure containing connection information about the datashare
77      * extension.
78      * @return Returns a pointer to the <b>sid</b> of the connected datashare extension ability.
79      */
80     sptr<IRemoteObject> OnConnect(const AAFwk::Want &want) override;
81 
82     /**
83      * @brief Obtains the MIME types of files supported.
84      *
85      * @param uri Indicates the path of the files to obtain.
86      * @param mimeTypeFilter Indicates the MIME types of the files to obtain. This parameter cannot be null.
87      *
88      * @return Returns the matched MIME types. If there is no match, null is returned.
89      */
90     std::vector<std::string> GetFileTypes(const Uri &uri, const std::string &mimeTypeFilter) override;
91 
92     /**
93      * @brief Opens a file in a specified remote path.
94      *
95      * @param uri Indicates the path of the file to open.
96      * @param mode Indicates the file open mode, which can be "r" for read-only access, "w" for write-only access
97      * (erasing whatever data is currently in the file), "wt" for write access that truncates any existing file,
98      * "wa" for write-only access to append to any existing data, "rw" for read and write access on any existing data,
99      *  or "rwt" for read and write access that truncates any existing file.
100      *
101      * @return Returns the file descriptor.
102      */
103     int OpenFile(const Uri &uri, const std::string &mode) override;
104 
105     /**
106      * @brief This is like openFile, open a file that need to be able to return sub-sections of files,often assets
107      * inside of their .hap.
108      *
109      * @param uri Indicates the path of the file to open.
110      * @param mode Indicates the file open mode, which can be "r" for read-only access, "w" for write-only access
111      * (erasing whatever data is currently in the file), "wt" for write access that truncates any existing file,
112      * "wa" for write-only access to append to any existing data, "rw" for read and write access on any existing
113      * data, or "rwt" for read and write access that truncates any existing file.
114      *
115      * @return Returns the RawFileDescriptor object containing file descriptor.
116      */
117     int OpenRawFile(const Uri &uri, const std::string &mode) override;
118 
119     /**
120      * @brief Inserts a single data record into the database.
121      *
122      * @param uri Indicates the path of the data to operate.
123      * @param value  Indicates the data record to insert. If this parameter is null, a blank row will be inserted.
124      *
125      * @return Returns the index of the inserted data record.
126      */
127     int Insert(const Uri &uri, const DataShareValuesBucket &value) override;
128 
129     /**
130      * @brief Updates data records in the database.
131      *
132      * @param uri Indicates the path of data to update.
133      * @param predicates Indicates filter criteria. You should define the processing logic when this parameter is null.
134      * @param value Indicates the data to update. This parameter can be null.
135      *
136      * @return Returns the number of data records updated.
137      */
138     int Update(const Uri &uri, const DataSharePredicates &predicates,
139         const DataShareValuesBucket &value) override;
140 
141     /**
142      * @brief Batch updates data records in the database.
143      *
144      * @param updateOperations Indicates the param of data to update.
145      * @param results Indicates the number of data records updated.
146      *
147      * @return Return the execution results of batch updates.
148      */
149     virtual int BatchUpdate(const UpdateOperations &operations, std::vector<BatchUpdateResult> &results) override;
150 
151     /**
152      * @brief Deletes one or more data records from the database.
153      *
154      * @param uri Indicates the path of the data to operate.
155      * @param predicates Indicates filter criteria. You should define the processing logic when this parameter is null.
156      *
157      * @return Returns the number of data records deleted.
158      */
159     int Delete(const Uri &uri, const DataSharePredicates &predicates) override;
160 
161     /**
162      * @brief Deletes one or more data records from the database.
163      *
164      * @param uri Indicates the path of data to query.
165      * @param predicates Indicates filter criteria. You should define the processing logic when this parameter is null.
166      * @param columns Indicates the columns to query. If this parameter is null, all columns are queried.
167      *
168      * @return Returns the query result.
169      */
170     std::shared_ptr<DataShareResultSet> Query(const Uri &uri, const DataSharePredicates &predicates,
171         std::vector<std::string> &columns, DatashareBusinessError &businessError) override;
172 
173     /**
174      * @brief Obtains the MIME type matching the data specified by the URI of the Data ability. This method should be
175      * implemented by a Data ability. Data abilities supports general data types, including text, HTML, and JPEG.
176      *
177      * @param uri Indicates the URI of the data.
178      *
179      * @return Returns the MIME type that matches the data specified by uri.
180      */
181     std::string GetType(const Uri &uri) override;
182 
183     /**
184      * @brief Inserts multiple data records into the database.
185      *
186      * @param uri Indicates the path of the data to operate.
187      * @param values Indicates the data records to insert.
188      *
189      * @return Returns the number of data records inserted.
190      */
191     int BatchInsert(const Uri &uri, const std::vector<DataShareValuesBucket> &values) override;
192 
193     /**
194      * @brief Registers an observer to DataObsMgr specified by the given Uri.
195      *
196      * @param uri, Indicates the path of the data to operate.
197      * @param dataObserver, Indicates the IDataAbilityObserver object.
198      */
199     bool RegisterObserver(const Uri &uri, const sptr<AAFwk::IDataAbilityObserver> &dataObserver) override;
200 
201     /**
202      * @brief Deregisters an observer used for DataObsMgr specified by the given Uri.
203      *
204      * @param uri, Indicates the path of the data to operate.
205      * @param dataObserver, Indicates the IDataAbilityObserver object.
206      */
207     bool UnregisterObserver(const Uri &uri, const sptr<AAFwk::IDataAbilityObserver> &dataObserver) override;
208 
209     /**
210      * @brief Notifies the registered observers of a change to the data resource specified by Uri.
211      *
212      * @param uri, Indicates the path of the data to operate.
213      *
214      * @return Return true if success. otherwise return false.
215      */
216     bool NotifyChange(const Uri &uri) override;
217 
218     /**
219      * @brief Converts the given uri that refer to the Data ability into a normalized URI. A normalized URI can be used
220      * across devices, persisted, backed up, and restored. It can refer to the same item in the Data ability even if
221      * the context has changed. If you implement URI normalization for a Data ability, you must also implement
222      * denormalizeUri(ohos.utils.net.Uri) to enable URI denormalization. After this feature is enabled, URIs passed to
223      * any method that is called on the Data ability must require normalization verification and denormalization. The
224      * default implementation of this method returns null, indicating that this Data ability does not support URI
225      * normalization.
226      *
227      * @param uri Indicates the Uri object to normalize.
228      *
229      * @return Returns the normalized Uri object if the Data ability supports URI normalization; returns null otherwise.
230      */
231     Uri NormalizeUri(const Uri &uri) override;
232 
233     /**
234      * @brief Converts the given normalized uri generated by normalizeUri(ohos.utils.net.Uri) into a denormalized one.
235      * The default implementation of this method returns the original URI passed to it.
236      *
237      * @param uri uri Indicates the Uri object to denormalize.
238      *
239      * @return Returns the denormalized Uri object if the denormalization is successful; returns the original Uri
240      * passed to this method if there is nothing to do; returns null if the data identified by the original Uri cannot
241      * be found in the current environment.
242      */
243     Uri DenormalizeUri(const Uri &uri) override;
244 
GetRecvReply()245     bool GetRecvReply() const
246     {
247         return isRecvReply_;
248     }
SetRecvReply(bool recvReply)249     void SetRecvReply(bool recvReply)
250     {
251         isRecvReply_ = recvReply;
252     }
253 
GetAsyncResult()254     napi_value GetAsyncResult() const
255     {
256         return callbackData_;
257     }
258 
SetAsyncResult(napi_value asyncResult)259     void SetAsyncResult(napi_value asyncResult)
260     {
261         callbackData_ = asyncResult;
262     }
263 
GetResult(int & value)264     void GetResult(int &value)
265     {
266         value = callbackResultNumber_;
267     }
268 
SetResult(const int value)269     void SetResult(const int value)
270     {
271         callbackResultNumber_ = value;
272     }
273 
GetResult(std::string & value)274     void GetResult(std::string &value)
275     {
276         value = callbackResultString_;
277     }
278 
SetResult(const std::string value)279     void SetResult(const std::string value)
280     {
281         callbackResultString_ = value;
282     }
283 
GetResult(std::vector<std::string> & value)284     void GetResult(std::vector<std::string> &value)
285     {
286         value = callbackResultStringArr_;
287     }
288 
SetResult(const std::vector<BatchUpdateResult> & results)289     void SetResult(const std::vector<BatchUpdateResult> &results)
290     {
291         updateResults_ = results;
292     }
293 
GetResult(std::vector<BatchUpdateResult> & results)294     void GetResult(std::vector<BatchUpdateResult> &results)
295     {
296         results = updateResults_;
297     }
298 
SetResult(const std::vector<std::string> value)299     void SetResult(const std::vector<std::string> value)
300     {
301         callbackResultStringArr_ = value;
302     }
303 
GetResultSet(std::shared_ptr<DataShareResultSet> & value)304     void GetResultSet(std::shared_ptr<DataShareResultSet> &value)
305     {
306         std::lock_guard<std::mutex> lock(resultSetLock_);
307         value = callbackResultObject_;
308     }
309 
SetResultSet(const std::shared_ptr<DataShareResultSet> value)310     void SetResultSet(const std::shared_ptr<DataShareResultSet> value)
311     {
312         std::lock_guard<std::mutex> lock(resultSetLock_);
313         callbackResultObject_ = value;
314     }
315 
GetBusinessError(DatashareBusinessError & businessError)316     void GetBusinessError(DatashareBusinessError &businessError)
317     {
318         businessError = businessError_;
319     }
320 
SetBusinessError(DatashareBusinessError & businessError)321     void SetBusinessError(DatashareBusinessError &businessError)
322     {
323         businessError_ = businessError;
324     }
325     struct AsyncContext {
326         bool isNeedNotify_ = false;
327     };
328 private:
329     struct AsyncPoint {
330         std::shared_ptr<AsyncContext> context;
331     };
332     struct AsyncCallBackPoint {
333         std::weak_ptr<JsDataShareExtAbility> extAbility;
334     };
335     napi_value CallObjectMethod(const char *name, napi_value const *argv = nullptr, size_t argc = 0,
336         bool isAsync = true);
337     napi_value CallObjectMethod(
338         const char *name, napi_value const *argv, size_t argc, std::shared_ptr<AsyncContext> asyncContext);
339     void SaveNewCallingInfo(napi_env &env);
340     void GetSrcPath(std::string &srcPath);
341     napi_value MakePredicates(napi_env env, const DataSharePredicates &predicates);
342     napi_value MakeUpdateOperation(napi_env env, const UpdateOperation &updateOperation);
343     static napi_value AsyncCallback(napi_env env, napi_callback_info info);
344     static napi_value AsyncCallbackWithContext(napi_env env, napi_callback_info info);
345     void CheckAndSetAsyncResult(napi_env env);
346     static void NotifyToDataShareService();
347     static void UnWrapBusinessError(napi_env env, napi_value info, DatashareBusinessError &businessError);
348     static napi_valuetype UnWrapPropertyType(napi_env env, napi_value info,
349         const std::string &key);
350     static bool UnwrapBatchUpdateResult(napi_env env, napi_value &info, std::vector<BatchUpdateResult> &results);
351     static std::string UnWrapProperty(napi_env env, napi_value info, const std::string &key);
352     int32_t InitAsyncCallParams(size_t argc, napi_env &env, napi_value *args);
353 
354     static constexpr int ACTIVE_INVOKER = 1;
355     JsRuntime& jsRuntime_;
356     std::unique_ptr<NativeReference> jsObj_;
357     bool isRecvReply_ = false;
358     napi_value callbackData_ = nullptr;
359     int callbackResultNumber_ = -1;
360     std::string callbackResultString_ = "";
361     std::vector<std::string> callbackResultStringArr_ = {};
362     std::mutex resultSetLock_;
363     std::shared_ptr<DataShareResultSet> callbackResultObject_ = nullptr;
364     DatashareBusinessError businessError_;
365     std::vector<BatchUpdateResult> updateResults_ = {};
366 };
367 } // namespace DataShare
368 } // namespace OHOS
369 #endif // JS_DATASHARE_EXT_ABILITY_H