• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 Deletes one or more data records from the database.
143      *
144      * @param uri Indicates the path of the data to operate.
145      * @param predicates Indicates filter criteria. You should define the processing logic when this parameter is null.
146      *
147      * @return Returns the number of data records deleted.
148      */
149     int Delete(const Uri &uri, const DataSharePredicates &predicates) override;
150 
151     /**
152      * @brief Deletes one or more data records from the database.
153      *
154      * @param uri Indicates the path of data to query.
155      * @param predicates Indicates filter criteria. You should define the processing logic when this parameter is null.
156      * @param columns Indicates the columns to query. If this parameter is null, all columns are queried.
157      *
158      * @return Returns the query result.
159      */
160     std::shared_ptr<DataShareResultSet> Query(const Uri &uri, const DataSharePredicates &predicates,
161         std::vector<std::string> &columns, DatashareBusinessError &businessError) override;
162 
163     /**
164      * @brief Obtains the MIME type matching the data specified by the URI of the Data ability. This method should be
165      * implemented by a Data ability. Data abilities supports general data types, including text, HTML, and JPEG.
166      *
167      * @param uri Indicates the URI of the data.
168      *
169      * @return Returns the MIME type that matches the data specified by uri.
170      */
171     std::string GetType(const Uri &uri) override;
172 
173     /**
174      * @brief Inserts multiple data records into the database.
175      *
176      * @param uri Indicates the path of the data to operate.
177      * @param values Indicates the data records to insert.
178      *
179      * @return Returns the number of data records inserted.
180      */
181     int BatchInsert(const Uri &uri, const std::vector<DataShareValuesBucket> &values) override;
182 
183     /**
184      * @brief Registers an observer to DataObsMgr specified by the given Uri.
185      *
186      * @param uri, Indicates the path of the data to operate.
187      * @param dataObserver, Indicates the IDataAbilityObserver object.
188      */
189     bool RegisterObserver(const Uri &uri, const sptr<AAFwk::IDataAbilityObserver> &dataObserver) override;
190 
191     /**
192      * @brief Deregisters an observer used for DataObsMgr specified by the given Uri.
193      *
194      * @param uri, Indicates the path of the data to operate.
195      * @param dataObserver, Indicates the IDataAbilityObserver object.
196      */
197     bool UnregisterObserver(const Uri &uri, const sptr<AAFwk::IDataAbilityObserver> &dataObserver) override;
198 
199     /**
200      * @brief Notifies the registered observers of a change to the data resource specified by Uri.
201      *
202      * @param uri, Indicates the path of the data to operate.
203      *
204      * @return Return true if success. otherwise return false.
205      */
206     bool NotifyChange(const Uri &uri) override;
207 
208     /**
209      * @brief Converts the given uri that refer to the Data ability into a normalized URI. A normalized URI can be used
210      * across devices, persisted, backed up, and restored. It can refer to the same item in the Data ability even if
211      * the context has changed. If you implement URI normalization for a Data ability, you must also implement
212      * denormalizeUri(ohos.utils.net.Uri) to enable URI denormalization. After this feature is enabled, URIs passed to
213      * any method that is called on the Data ability must require normalization verification and denormalization. The
214      * default implementation of this method returns null, indicating that this Data ability does not support URI
215      * normalization.
216      *
217      * @param uri Indicates the Uri object to normalize.
218      *
219      * @return Returns the normalized Uri object if the Data ability supports URI normalization; returns null otherwise.
220      */
221     Uri NormalizeUri(const Uri &uri) override;
222 
223     /**
224      * @brief Converts the given normalized uri generated by normalizeUri(ohos.utils.net.Uri) into a denormalized one.
225      * The default implementation of this method returns the original URI passed to it.
226      *
227      * @param uri uri Indicates the Uri object to denormalize.
228      *
229      * @return Returns the denormalized Uri object if the denormalization is successful; returns the original Uri
230      * passed to this method if there is nothing to do; returns null if the data identified by the original Uri cannot
231      * be found in the current environment.
232      */
233     Uri DenormalizeUri(const Uri &uri) override;
234 
GetBlockWaiting()235     bool GetBlockWaiting() const
236     {
237         return isBlockWaiting_;
238     }
SetBlockWaiting(bool blockWaiting)239     void SetBlockWaiting(bool blockWaiting)
240     {
241         isBlockWaiting_ = blockWaiting;
242     }
243 
GetAsyncResult()244     NativeValue* GetAsyncResult() const
245     {
246         return callbackData_;
247     }
248 
SetAsyncResult(NativeValue * asyncResult)249     void SetAsyncResult(NativeValue* asyncResult)
250     {
251         callbackData_ = asyncResult;
252     }
253 
GetResult(int & value)254     void GetResult(int &value)
255     {
256         value = callbackResultNumber_;
257     }
258 
SetResult(const int value)259     void SetResult(const int value)
260     {
261         callbackResultNumber_ = value;
262     }
263 
GetResult(std::string & value)264     void GetResult(std::string &value)
265     {
266         value = callbackResultString_;
267     }
268 
SetResult(const std::string value)269     void SetResult(const std::string value)
270     {
271         callbackResultString_ = value;
272     }
273 
GetResult(std::vector<std::string> & value)274     void GetResult(std::vector<std::string> &value)
275     {
276         value = callbackResultStringArr_;
277     }
278 
SetResult(const std::vector<std::string> value)279     void SetResult(const std::vector<std::string> value)
280     {
281         callbackResultStringArr_ = value;
282     }
283 
GetResult(std::shared_ptr<DataShareResultSet> & value)284     void GetResult(std::shared_ptr<DataShareResultSet> &value)
285     {
286         value = callbackResultObject_;
287     }
288 
SetResult(const std::shared_ptr<DataShareResultSet> value)289     void SetResult(const std::shared_ptr<DataShareResultSet> value)
290     {
291         callbackResultObject_ = value;
292     }
293 
GetBusinessError(DatashareBusinessError & businessError)294     void GetBusinessError(DatashareBusinessError &businessError)
295     {
296         businessError = businessError_;
297     }
298 
SetBusinessError(DatashareBusinessError & businessError)299     void SetBusinessError(DatashareBusinessError &businessError)
300     {
301         businessError_ = businessError;
302     }
303     struct AsyncContext {
304         bool isNeedNotify_ = false;
305     };
306 private:
307     struct AsyncPoint {
308         std::shared_ptr<AsyncContext> context;
309     };
310     NativeValue* CallObjectMethod(const char *name, NativeValue * const *argv = nullptr, size_t argc = 0,
311         bool isAsync = true);
312     NativeValue *CallObjectMethod(
313         const char *name, NativeValue **argv, size_t argc, std::shared_ptr<AsyncContext> asyncContext);
314     void GetSrcPath(std::string &srcPath);
315     napi_value MakePredicates(napi_env env, const DataSharePredicates &predicates);
316     static NativeValue* AsyncCallback(NativeEngine* engine, NativeCallbackInfo* info);
317     static NativeValue* AsyncCallbackWithContext(NativeEngine* engine, NativeCallbackInfo* info);
318     void CheckAndSetAsyncResult(NativeEngine* engine);
319     static void NotifyToDataShareService();
320     static void UnWrapBusinessError(napi_env env, napi_value info, DatashareBusinessError &businessError);
321     static napi_valuetype UnWrapPropertyType(napi_env env, napi_value info,
322         const std::string &key);
323     static std::string UnWrapProperty(napi_env env, napi_value info, const std::string &key);
324 
325     JsRuntime& jsRuntime_;
326     std::unique_ptr<NativeReference> jsObj_;
327     bool isBlockWaiting_ = false;
328     NativeValue* callbackData_ = nullptr;
329     int callbackResultNumber_ = -1;
330     std::string callbackResultString_ = "";
331     std::vector<std::string> callbackResultStringArr_ = {};
332     std::shared_ptr<DataShareResultSet> callbackResultObject_ = nullptr;
333     DatashareBusinessError businessError_;
334 };
335 } // namespace DataShare
336 } // namespace OHOS
337 #endif // JS_DATASHARE_EXT_ABILITY_H