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