• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2022-2024 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 "nweb_helper.h"
17 
18 #include <cstdint>
19 #include <dirent.h>
20 #include <dlfcn.h>
21 #include <fcntl.h>
22 #include <memory>
23 #include <refbase.h>
24 #include <surface.h>
25 #include <sys/stat.h>
26 #include <thread>
27 #include <unistd.h>
28 
29 #include "app_mgr_client.h"
30 #include "application_context.h"
31 #include "ark_web_nweb_bridge_helper.h"
32 #include "config_policy_utils.h"
33 #include "locale_config.h"
34 #include "nweb_adapter_helper.h"
35 #include "nweb_c_api.h"
36 #include "nweb_enhance_surface_adapter.h"
37 #include "nweb_hisysevent.h"
38 #include "nweb_log.h"
39 #include "nweb_surface_adapter.h"
40 #include "parameter.h"
41 #include "parameters.h"
42 
43 namespace {
44 const int32_t NS_TO_S = 1000000000;
45 const uint32_t NWEB_SURFACE_MAX_WIDTH = 7680;
46 const uint32_t NWEB_SURFACE_MAX_HEIGHT = 7680;
47 #if defined(webview_arm64)
48 const std::string RELATIVE_PATH_FOR_MOCK = "libs/arm64";
49 const std::string RELATIVE_PATH_FOR_BUNDLE = "nweb/libs/arm64";
50 #elif defined(webview_x86_64)
51 const std::string RELATIVE_PATH_FOR_MOCK = "libs/x86_64";
52 const std::string RELATIVE_PATH_FOR_BUNDLE = "nweb/libs/x86_64";
53 #else
54 const std::string RELATIVE_PATH_FOR_MOCK = "libs/arm";
55 const std::string RELATIVE_PATH_FOR_BUNDLE = "nweb/libs/arm";
56 #endif
57 const std::string LIB_NAME_WEB_ENGINE = "libweb_engine.so";
58 static bool g_isFirstTimeStartUp = false;
59 
60 // Run DO macro for every function defined in the API.
61 #define FOR_EACH_API_FN(DO)                          \
62     DO(WebDownloadManager_PutDownloadCallback)       \
63     DO(WebDownloader_ResumeDownloadStatic)           \
64     DO(WebDownloader_StartDownload)                  \
65     DO(WebDownloader_CreateDownloadDelegateCallback) \
66     DO(WebDownloader_SetDownloadBeforeStart)         \
67     DO(WebDownloader_SetDownloadDidUpdate)           \
68     DO(WebDownload_Continue)                         \
69     DO(WebDownload_CancelBeforeDownload)             \
70     DO(WebDownload_PauseBeforeDownload)              \
71     DO(WebDownload_ResumeBeforeDownload)             \
72     DO(WebDownload_Cancel)                           \
73     DO(WebDownload_Pause)                            \
74     DO(WebDownload_Resume)                           \
75     DO(WebDownload_GetItemState)                     \
76     DO(WebDownload_GetItemStateByGuid)               \
77     DO(WebDownloadItem_Guid)                         \
78     DO(WebDownloadItem_GetDownloadItemId)            \
79     DO(WebDownloadItem_GetState)                     \
80     DO(WebDownloadItem_CurrentSpeed)                 \
81     DO(WebDownloadItem_PercentComplete)              \
82     DO(WebDownloadItem_TotalBytes)                   \
83     DO(WebDownloadItem_ReceivedBytes)                \
84     DO(WebDownloadItem_FullPath)                     \
85     DO(WebDownloadItem_Url)                          \
86     DO(WebDownloadItem_OriginalUrl)                  \
87     DO(WebDownloadItem_SuggestedFileName)            \
88     DO(WebDownloadItem_ContentDisposition)           \
89     DO(WebDownloadItem_ETag)                         \
90     DO(WebDownloadItem_MimeType)                     \
91     DO(WebDownloadItem_NWebId)                       \
92     DO(WebDownloadItem_IsPaused)                     \
93     DO(WebDownloadItem_Method)                       \
94     DO(WebDownloadItem_LastErrorCode)                \
95     DO(WebDownloadItem_ReceivedSlices)               \
96     DO(WebDownloadItem_LastModified)                 \
97     DO(WebDownloadItem_CreateWebDownloadItem)        \
98     DO(WebDownloadItem_Destroy)                      \
99     DO(WebDownloadItem_SetUrl)                       \
100     DO(WebDownloadItem_SetFullPath)                  \
101     DO(WebDownloadItem_SetETag)                      \
102     DO(WebDownloadItem_SetLastModified)              \
103     DO(WebDownloadItem_SetMimeType)                  \
104     DO(WebDownloadItem_SetReceivedBytes)             \
105     DO(WebDownloadItem_SetTotalBytes)                \
106     DO(WebDownloadItem_SetReceivedSlices)            \
107     DO(WebDownloadItem_SetGuid)                      \
108     DO(DestroyBeforeDownloadCallbackWrapper)         \
109     DO(DestroyDownloadItemCallbackWrapper)           \
110 
111 
112 struct NWebCApi {
113     // Generate a function pointer field for every NWeb C API function.
114 #define GEN_FN_PTR(fn) decltype(&fn) impl_##fn = nullptr;
115     FOR_EACH_API_FN(GEN_FN_PTR)
116 #undef GEN_FN_PTR
117 };
118 
LoadFunction(void * handle,const char * functionName,Fn * fnOut)119 template <typename Fn> void LoadFunction(void *handle, const char *functionName, Fn *fnOut)
120 {
121     void *fn = dlsym(handle, functionName);
122     if (!fn) {
123         WVLOG_E("%{public}s not found.", functionName);
124         return;
125     }
126     *fnOut = reinterpret_cast<Fn>(fn);
127 }
128 
129 NWebCApi *g_nwebCApi = nullptr;
130 
LoadNWebCApi(void * handle,NWebCApi * api)131 void LoadNWebCApi(void *handle, NWebCApi *api)
132 {
133     // Initialize each NWebExApi function pointer field from the DLL
134 #define LOAD_FN_PTR(fn) LoadFunction(handle, #fn, &api->impl_##fn);
135     FOR_EACH_API_FN(LOAD_FN_PTR)
136 #undef LOAD_FN_PTR
137 }
138 
LoadNWebSDK(void * handle)139 bool LoadNWebSDK(void *handle)
140 {
141     if (g_nwebCApi) {
142         WVLOG_I("LoadNWebSDK had loaded.");
143         return true;
144     }
145 
146     if (handle == nullptr) {
147         WVLOG_E("LoadNWebSDK handle is nullptr.");
148         return false;
149     }
150 
151     auto *nwebCApi = new NWebCApi();
152     if (nwebCApi == nullptr) {
153         WVLOG_E("nwebCApi is nullptr.");
154         return false;
155     }
156     LoadNWebCApi(handle, nwebCApi);
157     g_nwebCApi = nwebCApi;
158     return true;
159 }
160 #undef FOR_EACH_API_FN
161 }
162 
WebDownloadManager_PutDownloadCallback(WebDownloadDelegateCallback * callback)163 extern "C" void WebDownloadManager_PutDownloadCallback(WebDownloadDelegateCallback *callback)
164 {
165     if (!g_nwebCApi->impl_WebDownloadManager_PutDownloadCallback) {
166         WVLOG_E("WebDownloadManager_PutDownloadCallback not found.");
167         return;
168     }
169     g_nwebCApi->impl_WebDownloadManager_PutDownloadCallback(callback);
170 }
171 
WebDownloader_SetDownloadBeforeStart(WebDownloadDelegateCallback * callback,OnDownloadBeforeStart fun)172 extern "C" void WebDownloader_SetDownloadBeforeStart(WebDownloadDelegateCallback *callback, OnDownloadBeforeStart fun)
173 {
174     if (!g_nwebCApi->impl_WebDownloader_SetDownloadBeforeStart) {
175         WVLOG_E("WebDownloader_SetDownloadBeforeStart not found.");
176         return;
177     }
178     g_nwebCApi->impl_WebDownloader_SetDownloadBeforeStart(callback, fun);
179 }
180 
WebDownloader_SetDownloadDidUpdate(WebDownloadDelegateCallback * callback,OnDownloadDidUpdate fun)181 extern "C" void WebDownloader_SetDownloadDidUpdate(WebDownloadDelegateCallback *callback, OnDownloadDidUpdate fun)
182 {
183     if (!g_nwebCApi->impl_WebDownloader_SetDownloadDidUpdate) {
184         WVLOG_E("WebDownloader_SetDownloadDidUpdate not found");
185         return;
186     }
187     g_nwebCApi->impl_WebDownloader_SetDownloadDidUpdate(callback, fun);
188 }
189 
WebDownloader_ResumeDownloadStatic(const NWebDownloadItem * downloadItem)190 extern "C" void WebDownloader_ResumeDownloadStatic(const NWebDownloadItem *downloadItem)
191 {
192     if (!g_nwebCApi->impl_WebDownloader_ResumeDownloadStatic) {
193         WVLOG_E("WebDownloader_ResumeDownloadStatic not found.");
194         return;
195     }
196     g_nwebCApi->impl_WebDownloader_ResumeDownloadStatic(downloadItem);
197 }
198 
WebDownloader_StartDownload(int32_t nwebId,const char * url)199 extern "C" void WebDownloader_StartDownload(int32_t nwebId, const char* url)
200 {
201     if (!g_nwebCApi->impl_WebDownloader_StartDownload) {
202         WVLOG_E("WebDownloader_StartDownload not found.");
203         return;
204     }
205     g_nwebCApi->impl_WebDownloader_StartDownload(nwebId, url);
206 }
207 
WebDownloader_CreateDownloadDelegateCallback(WebDownloadDelegateCallback ** callback)208 extern "C" void WebDownloader_CreateDownloadDelegateCallback(WebDownloadDelegateCallback **callback)
209 {
210     if (!g_nwebCApi || !g_nwebCApi->impl_WebDownloader_CreateDownloadDelegateCallback) {
211         WVLOG_E("WebDownloader_CreateDownloadDelegateCallback not found.");
212         return;
213     }
214 
215     return g_nwebCApi->impl_WebDownloader_CreateDownloadDelegateCallback(callback);
216 }
217 
WebDownload_Continue(const WebBeforeDownloadCallbackWrapper * wrapper,const char * downloadPath)218 extern "C" void WebDownload_Continue(const WebBeforeDownloadCallbackWrapper *wrapper, const char *downloadPath)
219 {
220     if (!g_nwebCApi->impl_WebDownload_Continue) {
221         WVLOG_E("WebDownload_Continue not found.");
222         return;
223     }
224     g_nwebCApi->impl_WebDownload_Continue(wrapper, downloadPath);
225 }
226 
WebDownload_CancelBeforeDownload(const WebBeforeDownloadCallbackWrapper * wrapper)227 extern "C" void WebDownload_CancelBeforeDownload(const WebBeforeDownloadCallbackWrapper *wrapper)
228 {
229     if (!g_nwebCApi->impl_WebDownload_CancelBeforeDownload) {
230         WVLOG_E("WebDownload_CancelBeforeDownload not found.");
231         return;
232     }
233     g_nwebCApi->impl_WebDownload_CancelBeforeDownload(wrapper);
234 }
235 
WebDownload_PauseBeforeDownload(const WebBeforeDownloadCallbackWrapper * wrapper)236 extern "C" void WebDownload_PauseBeforeDownload(const WebBeforeDownloadCallbackWrapper *wrapper)
237 {
238     if (!g_nwebCApi->impl_WebDownload_PauseBeforeDownload) {
239         WVLOG_E("WebDownload_PauseBeforeDownload not found.");
240         return;
241     }
242     g_nwebCApi->impl_WebDownload_PauseBeforeDownload(wrapper);
243 }
244 
WebDownload_ResumeBeforeDownload(const WebBeforeDownloadCallbackWrapper * wrapper)245 extern "C" void WebDownload_ResumeBeforeDownload(const WebBeforeDownloadCallbackWrapper *wrapper)
246 {
247     if (!g_nwebCApi->impl_WebDownload_ResumeBeforeDownload) {
248         WVLOG_E("WebDownload_ResumeBeforeDownload not found.");
249         return;
250     }
251     g_nwebCApi->impl_WebDownload_ResumeBeforeDownload(wrapper);
252 }
253 
WebDownload_Cancel(const WebDownloadItemCallbackWrapper * wrapper)254 extern "C" void WebDownload_Cancel(const WebDownloadItemCallbackWrapper *wrapper)
255 {
256     if (!g_nwebCApi->impl_WebDownload_Cancel) {
257         WVLOG_E("WebDownload_Cancel not found.");
258         return;
259     }
260     g_nwebCApi->impl_WebDownload_Cancel(wrapper);
261 }
262 
WebDownload_Pause(const WebDownloadItemCallbackWrapper * wrapper)263 extern "C" void WebDownload_Pause(const WebDownloadItemCallbackWrapper *wrapper)
264 {
265     if (!g_nwebCApi->impl_WebDownload_Pause) {
266         WVLOG_E("WebDownload_Pause not found");
267         return;
268     }
269     g_nwebCApi->impl_WebDownload_Pause(wrapper);
270 }
271 
WebDownload_Resume(const WebDownloadItemCallbackWrapper * wrapper)272 extern "C" void WebDownload_Resume(const WebDownloadItemCallbackWrapper *wrapper)
273 {
274     if (!g_nwebCApi->impl_WebDownload_Resume) {
275         WVLOG_E("WebDownload_Resume not found.");
276         return;
277     }
278     g_nwebCApi->impl_WebDownload_Resume(wrapper);
279 }
280 
WebDownload_GetItemState(int32_t nwebId,long downloadItemId)281 extern "C" NWebDownloadItemState WebDownload_GetItemState(int32_t nwebId, long downloadItemId)
282 {
283     if (!g_nwebCApi || !g_nwebCApi->impl_WebDownload_GetItemState) {
284         return NWebDownloadItemState::MAX_DOWNLOAD_STATE;
285     }
286     return g_nwebCApi->impl_WebDownload_GetItemState(nwebId, downloadItemId);
287 }
288 
WebDownload_GetItemStateByGuid(const std::string & guid)289 extern "C" NWebDownloadItemState WebDownload_GetItemStateByGuid(const std::string& guid)
290 {
291     if (!g_nwebCApi || !g_nwebCApi->impl_WebDownload_GetItemStateByGuid) {
292         return NWebDownloadItemState::MAX_DOWNLOAD_STATE;
293     }
294     return g_nwebCApi->impl_WebDownload_GetItemStateByGuid(guid);
295 }
296 
WebDownloadItem_Guid(const NWebDownloadItem * downloadItem)297 extern "C" char *WebDownloadItem_Guid(const NWebDownloadItem *downloadItem)
298 {
299     if (!g_nwebCApi->impl_WebDownloadItem_Guid) {
300         WVLOG_E("WebDownloadItem_Guid not found.");
301         return nullptr;
302     }
303     return g_nwebCApi->impl_WebDownloadItem_Guid(downloadItem);
304 }
305 
WebDownloadItem_GetDownloadItemId(const NWebDownloadItem * downloadItem)306 extern "C" long WebDownloadItem_GetDownloadItemId(const NWebDownloadItem *downloadItem)
307 {
308     if (!g_nwebCApi->impl_WebDownloadItem_GetDownloadItemId) {
309         return false;
310     }
311     return g_nwebCApi->impl_WebDownloadItem_GetDownloadItemId(downloadItem);
312 }
313 
WebDownloadItem_GetState(const NWebDownloadItem * downloadItem)314 extern "C" NWebDownloadItemState WebDownloadItem_GetState(const NWebDownloadItem *downloadItem)
315 {
316     if (!g_nwebCApi->impl_WebDownloadItem_GetState) {
317         return NWebDownloadItemState::MAX_DOWNLOAD_STATE;
318     }
319     return g_nwebCApi->impl_WebDownloadItem_GetState(downloadItem);
320 }
321 
WebDownloadItem_CurrentSpeed(const NWebDownloadItem * downloadItem)322 extern "C" int WebDownloadItem_CurrentSpeed(const NWebDownloadItem *downloadItem)
323 {
324     if (!g_nwebCApi->impl_WebDownloadItem_CurrentSpeed) {
325         WVLOG_E("WebDownloadItem_CurrentSpeed not found.");
326         return 0;
327     }
328     return g_nwebCApi->impl_WebDownloadItem_CurrentSpeed(downloadItem);
329 }
330 
WebDownloadItem_PercentComplete(const NWebDownloadItem * downloadItem)331 extern "C" int WebDownloadItem_PercentComplete(const NWebDownloadItem *downloadItem)
332 {
333     if (!g_nwebCApi->impl_WebDownloadItem_PercentComplete) {
334         WVLOG_E("WebDownloadItem_TotalBytes not found.");
335         return 0;
336     }
337     return g_nwebCApi->impl_WebDownloadItem_PercentComplete(downloadItem);
338 }
339 
WebDownloadItem_TotalBytes(const NWebDownloadItem * downloadItem)340 extern "C" int64_t WebDownloadItem_TotalBytes(const NWebDownloadItem *downloadItem)
341 {
342     if (!g_nwebCApi->impl_WebDownloadItem_TotalBytes) {
343         WVLOG_E("WebDownloadItem_TotalBytes not found.");
344         return 0;
345     }
346     return g_nwebCApi->impl_WebDownloadItem_TotalBytes(downloadItem);
347 }
348 
WebDownloadItem_ReceivedBytes(const NWebDownloadItem * downloadItem)349 extern "C" int64_t WebDownloadItem_ReceivedBytes(const NWebDownloadItem *downloadItem)
350 {
351     if (!g_nwebCApi->impl_WebDownloadItem_ReceivedBytes) {
352         WVLOG_E("WebDownloadItem_ReceivedBytes not found.");
353         return 0;
354     }
355     return g_nwebCApi->impl_WebDownloadItem_ReceivedBytes(downloadItem);
356 }
357 
WebDownloadItem_FullPath(const NWebDownloadItem * downloadItem)358 extern "C" char *WebDownloadItem_FullPath(const NWebDownloadItem *downloadItem)
359 {
360     if (!g_nwebCApi->impl_WebDownloadItem_FullPath) {
361         WVLOG_E("WebDownloadItem_FullPath not found");
362         return nullptr;
363     }
364     return g_nwebCApi->impl_WebDownloadItem_FullPath(downloadItem);
365 }
366 
WebDownloadItem_Url(const NWebDownloadItem * downloadItem)367 extern "C" char *WebDownloadItem_Url(const NWebDownloadItem *downloadItem)
368 {
369     if (!g_nwebCApi->impl_WebDownloadItem_Url) {
370         WVLOG_E("WebDownloadItem_Url not found.");
371         return nullptr;
372     }
373     return g_nwebCApi->impl_WebDownloadItem_Url(downloadItem);
374 }
375 
WebDownloadItem_OriginalUrl(const NWebDownloadItem * downloadItem)376 extern "C" char *WebDownloadItem_OriginalUrl(const NWebDownloadItem *downloadItem)
377 {
378     if (!g_nwebCApi->impl_WebDownloadItem_OriginalUrl) {
379         WVLOG_E("WebDownloadItem_OriginalUrl not found.");
380         return nullptr;
381     }
382     return g_nwebCApi->impl_WebDownloadItem_OriginalUrl(downloadItem);
383 }
384 
WebDownloadItem_SuggestedFileName(const NWebDownloadItem * downloadItem)385 extern "C" char *WebDownloadItem_SuggestedFileName(const NWebDownloadItem *downloadItem)
386 {
387     if (!g_nwebCApi->impl_WebDownloadItem_SuggestedFileName) {
388         WVLOG_E("WebDownloadItem_SuggestedFileName not found.");
389         return nullptr;
390     }
391     return g_nwebCApi->impl_WebDownloadItem_SuggestedFileName(downloadItem);
392 }
393 
WebDownloadItem_ContentDisposition(const NWebDownloadItem * downloadItem)394 extern "C" char *WebDownloadItem_ContentDisposition(const NWebDownloadItem *downloadItem)
395 {
396     if (!g_nwebCApi->impl_WebDownloadItem_ContentDisposition) {
397         WVLOG_E("WebDownloadItem_ContentDisposition not found.");
398         return nullptr;
399     }
400     return g_nwebCApi->impl_WebDownloadItem_ContentDisposition(downloadItem);
401 }
402 
WebDownloadItem_ETag(const NWebDownloadItem * downloadItem)403 extern "C" char *WebDownloadItem_ETag(const NWebDownloadItem *downloadItem)
404 {
405     if (!g_nwebCApi->impl_WebDownloadItem_ETag) {
406         WVLOG_E("WebDownloadItem_ETag not found.");
407         return nullptr;
408     }
409     return g_nwebCApi->impl_WebDownloadItem_ETag(downloadItem);
410 }
411 
WebDownloadItem_MimeType(const NWebDownloadItem * downloadItem)412 extern "C" char *WebDownloadItem_MimeType(const NWebDownloadItem *downloadItem)
413 {
414     if (!g_nwebCApi->impl_WebDownloadItem_MimeType) {
415         WVLOG_E("WebDownloadItem_MimeType not found.");
416         return nullptr;
417     }
418     return g_nwebCApi->impl_WebDownloadItem_MimeType(downloadItem);
419 }
420 
WebDownloadItem_IsPaused(const NWebDownloadItem * downloadItem)421 extern "C" bool WebDownloadItem_IsPaused(const NWebDownloadItem *downloadItem)
422 {
423     if (!g_nwebCApi->impl_WebDownloadItem_IsPaused) {
424         WVLOG_E("WebDownloadItem_IsPaused not found.");
425         return false;
426     }
427     return g_nwebCApi->impl_WebDownloadItem_IsPaused(downloadItem);
428 }
429 
WebDownloadItem_Method(const NWebDownloadItem * downloadItem)430 extern "C" char *WebDownloadItem_Method(const NWebDownloadItem *downloadItem)
431 {
432     if (!g_nwebCApi->impl_WebDownloadItem_Method) {
433         WVLOG_E("WebDownloadItem_Method not found.");
434         return nullptr;
435     }
436     return g_nwebCApi->impl_WebDownloadItem_Method(downloadItem);
437 }
438 
WebDownloadItem_LastErrorCode(const NWebDownloadItem * downloadItem)439 extern "C" int WebDownloadItem_LastErrorCode(const NWebDownloadItem *downloadItem)
440 {
441     if (!g_nwebCApi->impl_WebDownloadItem_LastErrorCode) {
442         WVLOG_E("WebDownloadItem_LastErrorCode not found.");
443         return 0;
444     }
445     return g_nwebCApi->impl_WebDownloadItem_LastErrorCode(downloadItem);
446 }
447 
WebDownloadItem_ReceivedSlices(const NWebDownloadItem * downloadItem)448 extern "C" char *WebDownloadItem_ReceivedSlices(const NWebDownloadItem *downloadItem)
449 {
450     if (!g_nwebCApi->impl_WebDownloadItem_ReceivedSlices) {
451         WVLOG_E("WebDownloadItem_ReceivedSlices not found.");
452         return nullptr;
453     }
454     return g_nwebCApi->impl_WebDownloadItem_ReceivedSlices(downloadItem);
455 }
456 
WebDownloadItem_LastModified(const NWebDownloadItem * downloadItem)457 extern "C" char *WebDownloadItem_LastModified(const NWebDownloadItem *downloadItem)
458 {
459     if (!g_nwebCApi->impl_WebDownloadItem_LastModified) {
460         WVLOG_E("WebDownloadItem_LastModified not found.");
461         return nullptr;
462     }
463     return g_nwebCApi->impl_WebDownloadItem_LastModified(downloadItem);
464 }
465 
WebDownloadItem_NWebId(const NWebDownloadItem * downloadItem)466 extern "C" int WebDownloadItem_NWebId(const NWebDownloadItem *downloadItem)
467 {
468     if (!g_nwebCApi->impl_WebDownloadItem_NWebId) {
469         WVLOG_E("WebDownloadItem_NWebId not found.");
470         return -1;
471     }
472     return g_nwebCApi->impl_WebDownloadItem_NWebId(downloadItem);
473 }
474 
WebDownloadItem_CreateWebDownloadItem(NWebDownloadItem ** downloadItem)475 extern "C" void WebDownloadItem_CreateWebDownloadItem(NWebDownloadItem **downloadItem)
476 {
477     if (!g_nwebCApi->impl_WebDownloadItem_CreateWebDownloadItem) {
478         WVLOG_E("WebDownloadItem_CreateWebDownloadItem not found.");
479         return;
480     }
481     g_nwebCApi->impl_WebDownloadItem_CreateWebDownloadItem(downloadItem);
482 }
483 
WebDownloadItem_Destroy(NWebDownloadItem * downloadItem)484 extern "C" void WebDownloadItem_Destroy(NWebDownloadItem *downloadItem)
485 {
486     if (!g_nwebCApi->impl_WebDownloadItem_Destroy) {
487         WVLOG_E("WebDownloadItem_Destroy not found.");
488         return;
489     }
490     g_nwebCApi->impl_WebDownloadItem_Destroy(downloadItem);
491 }
492 
DestroyBeforeDownloadCallbackWrapper(WebBeforeDownloadCallbackWrapper * wrapper)493 extern "C" void DestroyBeforeDownloadCallbackWrapper(WebBeforeDownloadCallbackWrapper *wrapper)
494 {
495     if (!g_nwebCApi->impl_DestroyBeforeDownloadCallbackWrapper) {
496         WVLOG_E("DestroyBeforeDownloadCallbackWrapper not found.");
497         return;
498     }
499     g_nwebCApi->impl_DestroyBeforeDownloadCallbackWrapper(wrapper);
500 }
501 
DestroyDownloadItemCallbackWrapper(WebDownloadItemCallbackWrapper * wrapper)502 extern "C" void DestroyDownloadItemCallbackWrapper(WebDownloadItemCallbackWrapper *wrapper)
503 {
504     if (!g_nwebCApi->impl_DestroyDownloadItemCallbackWrapper) {
505         WVLOG_E("DestroyDownloadItemCallbackWrapper not found.");
506         return;
507     }
508     g_nwebCApi->impl_DestroyDownloadItemCallbackWrapper(wrapper);
509 }
510 
WebDownloadItem_SetGuid(NWebDownloadItem * downloadItem,const char * guid)511 extern "C" void WebDownloadItem_SetGuid(NWebDownloadItem *downloadItem, const char *guid)
512 {
513     if (!g_nwebCApi->impl_WebDownloadItem_SetGuid) {
514         WVLOG_E("WebDownloadItem_SetGuid not found.");
515         return;
516     }
517     g_nwebCApi->impl_WebDownloadItem_SetGuid(downloadItem, guid);
518 }
519 
WebDownloadItem_SetUrl(NWebDownloadItem * downloadItem,const char * url)520 extern "C" void WebDownloadItem_SetUrl(NWebDownloadItem *downloadItem, const char *url)
521 {
522     if (!g_nwebCApi->impl_WebDownloadItem_SetUrl) {
523         WVLOG_E("WebDownloadItem_SetUrl not found.");
524         return;
525     }
526     g_nwebCApi->impl_WebDownloadItem_SetUrl(downloadItem, url);
527 }
528 
WebDownloadItem_SetFullPath(NWebDownloadItem * downloadItem,const char * fullPath)529 extern "C" void WebDownloadItem_SetFullPath(NWebDownloadItem *downloadItem, const char *fullPath)
530 {
531     if (!g_nwebCApi->impl_WebDownloadItem_SetFullPath) {
532         WVLOG_E("WebDownloadItem_SetFullPath not found.");
533         return;
534     }
535     g_nwebCApi->impl_WebDownloadItem_SetFullPath(downloadItem, fullPath);
536 }
537 
WebDownloadItem_SetETag(NWebDownloadItem * downloadItem,const char * etag)538 extern "C" void WebDownloadItem_SetETag(NWebDownloadItem *downloadItem, const char *etag)
539 {
540     if (!g_nwebCApi->impl_WebDownloadItem_SetETag) {
541         WVLOG_E("WebDownloadItem_SetETag not found.");
542         return;
543     }
544     g_nwebCApi->impl_WebDownloadItem_SetETag(downloadItem, etag);
545 }
546 
WebDownloadItem_SetLastModified(NWebDownloadItem * downloadItem,const char * lastModified)547 extern "C" void WebDownloadItem_SetLastModified(NWebDownloadItem *downloadItem, const char *lastModified)
548 {
549     if (!g_nwebCApi->impl_WebDownloadItem_SetLastModified) {
550         WVLOG_E("WebDownloadItem_SetLastModified not found.");
551         return;
552     }
553     g_nwebCApi->impl_WebDownloadItem_SetLastModified(downloadItem, lastModified);
554 }
555 
WebDownloadItem_SetMimeType(NWebDownloadItem * downloadItem,const char * mimeType)556 extern "C" void WebDownloadItem_SetMimeType(NWebDownloadItem *downloadItem, const char *mimeType)
557 {
558     if (!g_nwebCApi->impl_WebDownloadItem_SetMimeType) {
559         WVLOG_E("WebDownloadItem_SetMimeType not found.");
560         return;
561     }
562     g_nwebCApi->impl_WebDownloadItem_SetMimeType(downloadItem, mimeType);
563 }
564 
WebDownloadItem_SetReceivedBytes(NWebDownloadItem * downloadItem,int64_t receivedBytes)565 extern "C" void WebDownloadItem_SetReceivedBytes(NWebDownloadItem *downloadItem, int64_t receivedBytes)
566 {
567     if (!g_nwebCApi->impl_WebDownloadItem_SetReceivedBytes) {
568         WVLOG_E("WebDownloadItem_SetReceivedBytes not found.");
569         return;
570     }
571     g_nwebCApi->impl_WebDownloadItem_SetReceivedBytes(downloadItem, receivedBytes);
572 }
573 
WebDownloadItem_SetTotalBytes(NWebDownloadItem * downloadItem,int64_t totalBytes)574 extern "C" void WebDownloadItem_SetTotalBytes(NWebDownloadItem *downloadItem, int64_t totalBytes)
575 {
576     if (!g_nwebCApi->impl_WebDownloadItem_SetTotalBytes) {
577         WVLOG_E("WebDownloadItem_SetTotalBytes not found.");
578         return;
579     }
580     g_nwebCApi->impl_WebDownloadItem_SetTotalBytes(downloadItem, totalBytes);
581 }
582 
WebDownloadItem_SetReceivedSlices(NWebDownloadItem * downloadItem,const char * receivedSlices)583 extern "C" void WebDownloadItem_SetReceivedSlices(NWebDownloadItem *downloadItem, const char *receivedSlices)
584 {
585     if (!g_nwebCApi->impl_WebDownloadItem_SetReceivedSlices) {
586         WVLOG_E("WebDownloadItem_SetReceivedSlices not found.");
587         return;
588     }
589     g_nwebCApi->impl_WebDownloadItem_SetReceivedSlices(downloadItem, receivedSlices);
590 }
591 
592 namespace OHOS::NWeb {
LoadNWebSDK()593 bool NWebHelper::LoadNWebSDK()
594 {
595     return ::LoadNWebSDK(libHandleWebEngine_);
596 }
597 
Instance()598 NWebHelper &NWebHelper::Instance()
599 {
600     static NWebHelper helper;
601     return helper;
602 }
603 
604 #ifdef __MUSL__
LoadLib(bool from_ark)605 bool NWebHelper::LoadLib(bool from_ark)
606 {
607     if (libHandleWebEngine_ != nullptr) {
608         return true;
609     }
610     if (bundlePath_.empty()) {
611         WVLOG_E("load lib failed, because bundle path is empty");
612         return false;
613     }
614     std::string loadLibPath;
615     if (from_ark) {
616         loadLibPath = bundlePath_ + "/" + WEBVIEW_SANDBOX_RELATIVE_LIB_PATH;
617     } else {
618         loadLibPath = bundlePath_ + "/" + RELATIVE_PATH_FOR_MOCK;
619     }
620     Dl_namespace dlns;
621     dlns_init(&dlns, "nweb_ns");
622     dlns_create(&dlns, loadLibPath.c_str());
623     void *libHandleWebEngine = dlopen_ns(&dlns, WEBVIEW_ENGINE_SO, RTLD_NOW | RTLD_GLOBAL);
624     if (libHandleWebEngine == nullptr) {
625         if (from_ark) {
626             loadLibPath = bundlePath_ + "/" + RELATIVE_PATH_FOR_BUNDLE;
627         }
628         dlns_create(&dlns, loadLibPath.c_str());
629         libHandleWebEngine = dlopen_ns(&dlns, LIB_NAME_WEB_ENGINE.c_str(), RTLD_NOW | RTLD_GLOBAL);
630         if (libHandleWebEngine == nullptr) {
631             WVLOG_E("fail to dlopen %{public}s, errmsg=%{public}s", LIB_NAME_WEB_ENGINE.c_str(), dlerror());
632             return false;
633         }
634     }
635     libHandleWebEngine_ = libHandleWebEngine;
636     auto appMgrClient = std::make_unique<OHOS::AppExecFwk::AppMgrClient>();
637     auto result = appMgrClient->ConnectAppMgrService();
638     if (result == OHOS::AppExecFwk::AppMgrResultCode::RESULT_OK) {
639         auto ret = appMgrClient->NotifyProcessDependedOnWeb();
640         WVLOG_I("NotifyProcessDependedOnWeb. %{public}d", ret);
641     }
642     return true;
643 }
644 #else
LoadLib(bool from_ark)645 bool NWebHelper::LoadLib(bool from_ark)
646 {
647     if (libHandleWebEngine_ != nullptr) {
648         return true;
649     }
650     if (bundlePath_.empty()) {
651         WVLOG_E("fail to load lib bundle path is empty");
652         return false;
653     }
654     std::string loadLibPath;
655     if (from_ark) {
656         loadLibPath = bundlePath_ + "/" + WEBVIEW_SANDBOX_RELATIVE_LIB_PATH;
657     } else {
658         loadLibPath = bundlePath_ + "/" + RELATIVE_PATH_FOR_MOCK;
659     }
660     const std::string libPathWebEngine = loadLibPath + "/" + WEBVIEW_ENGINE_SO;
661     void *libHandleWebEngine = ::dlopen(libPathWebEngine.c_str(), RTLD_NOW);
662     if (libHandleWebEngine == nullptr) {
663         if (from_ark) {
664             loadLibPath = bundlePath_ + "/" + RELATIVE_PATH_FOR_BUNDLE;
665         }
666         const std::string libPathWebEngine2 = loadLibPath + "/" + LIB_NAME_WEB_ENGINE;
667         libHandleWebEngine = ::dlopen(libPathWebEngine2.c_str(), RTLD_NOW);
668         if (libHandleWebEngine == nullptr) {
669             WVLOG_E("fail to dlopen %{public}s, errmsg=%{public}s", libPathWebEngine2.c_str(), dlerror());
670             return false;
671         }
672     }
673     libHandleWebEngine_ = libHandleWebEngine;
674     return true;
675 }
676 #endif
677 
GetWebEngineHandler(bool shouldRun)678 void* NWebHelper::GetWebEngineHandler(bool shouldRun)
679 {
680     WVLOG_I("NWebHelper GetWebEngineHandler");
681     if (libHandleWebEngine_) {
682         return libHandleWebEngine_;
683     }
684 
685     std::shared_ptr<AbilityRuntime::ApplicationContext> ctx =
686         AbilityRuntime::ApplicationContext::GetApplicationContext();
687     if (!ctx) {
688         WVLOG_E("Failed to init web engine due to nil application context.");
689         return nullptr;
690     }
691 
692     // load so
693     const std::string& bundle_path = ctx->GetBundleCodeDir();
694     SetBundlePath(bundle_path);
695     if (shouldRun) {
696         if (!InitAndRun(true)) {
697             WVLOG_I("NWebHelper Init failed");
698             return nullptr;
699         }
700     } else {
701         if (!Init(true)) {
702             WVLOG_I("NWebHelper Init failed.");
703             return nullptr;
704         }
705     }
706 
707     return libHandleWebEngine_;
708 }
709 
UnloadLib()710 void NWebHelper::UnloadLib()
711 {
712     if (libHandleWebEngine_ != nullptr) {
713         ::dlclose(libHandleWebEngine_);
714         libHandleWebEngine_ = nullptr;
715     }
716 }
717 
LoadEngine()718 bool NWebHelper::LoadEngine()
719 {
720     if (nwebEngine_) {
721         return true;
722     }
723 
724     nwebEngine_ = NWebEngine::GetInstance();
725     if (nwebEngine_) {
726         return true;
727     }
728 
729     return false;
730 }
731 
DoPreReadLib(const std::string & bundlePath)732 static void DoPreReadLib(const std::string &bundlePath)
733 {
734     WVLOG_I("NWebHelper PreReadLib");
735     std::string libPathWebEngine = bundlePath + "/" + WEBVIEW_SANDBOX_RELATIVE_LIB_PATH + "/" + WEBVIEW_ENGINE_SO;
736 
737     char tempPath[PATH_MAX] = {0};
738     if (realpath(libPathWebEngine.c_str(), tempPath) == nullptr) {
739         libPathWebEngine = bundlePath + "/" + RELATIVE_PATH_FOR_BUNDLE + "/" + LIB_NAME_WEB_ENGINE;
740         if (realpath(libPathWebEngine.c_str(), tempPath) == nullptr) {
741             WVLOG_E("path to realpath error");
742             return;
743         }
744     }
745 
746     struct stat stats;
747     int ret = stat(tempPath, &stats);
748     if (ret < 0) {
749         WVLOG_E("stat web engine library failed, errno(%{public}d):%{public}s", errno, strerror(errno));
750         return;
751     }
752 
753     static const int SINGLE_READ_SIZE = 5 * 1024 * 1024;
754     char *buf = new (std::nothrow) char[SINGLE_READ_SIZE];
755     if (buf == nullptr) {
756         WVLOG_E("malloc buf failed");
757         return;
758     }
759 
760     int fd = open(tempPath, O_RDONLY);
761     if (fd <= 0) {
762         WVLOG_E("open web engine library failed, errno(%{public}d):%{public}s", errno, strerror(errno));
763         delete[] buf;
764         return;
765     }
766 
767     int readCnt = stats.st_size / SINGLE_READ_SIZE;
768     if (readCnt * SINGLE_READ_SIZE < stats.st_size) {
769         readCnt += 1;
770     }
771 
772     for (int i = 0; i < readCnt; i++) {
773         (void)read(fd, buf, SINGLE_READ_SIZE);
774     }
775 
776     (void)close(fd);
777     delete[] buf;
778     WVLOG_I("NWebHelper PreReadLib Finish");
779 }
780 
TryPreReadLib(bool isFirstTimeStartUpWeb,const std::string & bundlePath)781 void NWebHelper::TryPreReadLib(bool isFirstTimeStartUpWeb, const std::string &bundlePath)
782 {
783     g_isFirstTimeStartUp = isFirstTimeStartUpWeb;
784     if (isFirstTimeStartUpWeb) {
785         WVLOG_D("first time startup, need to wait until the nweb init stage");
786         return;
787     }
788 
789     DoPreReadLib(bundlePath);
790 }
791 
TryPreReadLibForFirstlyAppStartUp(const std::string & bundlePath)792 static void TryPreReadLibForFirstlyAppStartUp(const std::string &bundlePath)
793 {
794     if (g_isFirstTimeStartUp) {
795         std::thread preReadThread([bundlePath]() { DoPreReadLib(bundlePath); });
796 
797         preReadThread.detach();
798     }
799 }
800 
Init(bool from_ark)801 bool NWebHelper::Init(bool from_ark)
802 {
803     TryPreReadLibForFirstlyAppStartUp(bundlePath_);
804     if (!LoadLib(from_ark)) {
805         return false;
806     }
807 
808     std::string relativeLibPath = WEBVIEW_SANDBOX_RELATIVE_LIB_PATH;
809     std::string arkWebEngineSo = WEBVIEW_ENGINE_SO;
810     if (!OHOS::ArkWeb::ArkWebNWebBridgeHelper::GetInstance().InitArkWeb(
811         from_ark, bundlePath_, relativeLibPath, arkWebEngineSo)) {
812         if (!OHOS::ArkWeb::ArkWebNWebBridgeHelper::GetInstance().Init(from_ark, bundlePath_)) {
813             return false;
814         }
815     }
816 
817     return LoadEngine();
818 }
819 
InitAndRun(bool from_ark)820 bool NWebHelper::InitAndRun(bool from_ark)
821 {
822     if (!Init(from_ark)) {
823         return false;
824     }
825 
826     WVLOG_I("InitializeWebEngine: load libs and initiallize cef.");
827     if (nwebEngine_ == nullptr) {
828         WVLOG_E("nweb engine is nullptr");
829         return false;
830     }
831 
832     std::shared_ptr<NWebEngineInitArgsImpl> initArgs = std::make_shared<NWebEngineInitArgsImpl>();
833     NWebAdapterHelper::Instance().ParseConfig(initArgs);
834     // obtain bundle path
835     std::shared_ptr<AbilityRuntime::ApplicationContext> ctx =
836         AbilityRuntime::ApplicationContext::GetApplicationContext();
837     if (!ctx) {
838         WVLOG_E("Failed to init cef due to nil application context.");
839         return false;
840     }
841 
842     if (ctx->GetBaseDir().empty()) {
843         WVLOG_E("Failed to init cef due to base dir is empty.");
844         return false;
845     }
846 
847     initArgs->AddArg(std::string("--user-data-dir=").append(ctx->GetBaseDir()));
848     initArgs->AddArg(std::string("--bundle-installation-dir=").append(bundlePath_));
849     if (!customSchemeCmdLine_.empty()) {
850         initArgs->AddArg(std::string("--ohos-custom-scheme=").append(customSchemeCmdLine_));
851     }
852 
853     std::string systemLanguage = OHOS::Global::I18n::LocaleConfig::GetSystemLanguage();
854     std::string systemRegion = OHOS::Global::I18n::LocaleConfig::GetSystemRegion();
855     size_t dashPos = systemLanguage.find('-');
856     std::string baseLanguage = (dashPos == std::string::npos) ? systemLanguage : systemLanguage.substr(0, dashPos);
857     std::string simplifiedLocale = baseLanguage + "-" + systemRegion;
858     initArgs->AddArg(std::string("--lang=").append(simplifiedLocale));
859 
860     for (auto backForwardCacheCmdLine : backForwardCacheCmdLine_) {
861         initArgs->AddArg(backForwardCacheCmdLine);
862         WVLOG_I("Add command line when init web engine: %{public}s", backForwardCacheCmdLine.c_str());
863     }
864 
865     nwebEngine_->InitializeWebEngine(initArgs);
866     return true;
867 }
868 
ReadConfigIfNeeded()869 void NWebAdapterHelper::ReadConfigIfNeeded()
870 {
871     NWebConfigHelper::Instance().ReadConfigIfNeeded();
872 }
873 
SetBundlePath(const std::string & path)874 void NWebHelper::SetBundlePath(const std::string &path)
875 {
876     bundlePath_ = path;
877 }
878 
~NWebHelper()879 NWebHelper::~NWebHelper()
880 {
881     UnloadLib();
882 }
883 
CreateNWeb(std::shared_ptr<NWebCreateInfo> create_info)884 std::shared_ptr<NWeb> NWebHelper::CreateNWeb(std::shared_ptr<NWebCreateInfo> create_info)
885 {
886     if (nwebEngine_ == nullptr) {
887         WVLOG_E("nweb engine is nullptr");
888         return nullptr;
889     }
890 
891     return nwebEngine_->CreateNWeb(create_info);
892 }
893 
GetCookieManager()894 std::shared_ptr<NWebCookieManager> NWebHelper::GetCookieManager()
895 {
896     if (libHandleWebEngine_ == nullptr) {
897         WVLOG_I("GetCookieManager: init web engine start.");
898         // obtain bundle path
899         std::shared_ptr<AbilityRuntime::ApplicationContext> ctx =
900             AbilityRuntime::ApplicationContext::GetApplicationContext();
901         if (!ctx) {
902             WVLOG_E("GetCookieManager: Failed to init web engine due to nil application context.");
903             return nullptr;
904         }
905         // load so
906         const std::string& bundle_path = ctx->GetBundleCodeDir();
907         SetBundlePath(bundle_path);
908         if (!InitAndRun(true)) {
909             WVLOG_E("GetCookieManager: Failed to init web engine due to NWebHelper failure.");
910             return nullptr;
911         }
912         WVLOG_I("GetCookieManager: init web engine success.");
913     }
914 
915     if (nwebEngine_ == nullptr) {
916         WVLOG_E("nweb engine is nullptr");
917         return nullptr;
918     }
919 
920     return nwebEngine_->GetCookieManager();
921 }
922 
GetNWeb(int32_t nweb_id)923 std::shared_ptr<NWeb> NWebHelper::GetNWeb(int32_t nweb_id)
924 {
925     if (nwebEngine_ == nullptr) {
926         WVLOG_E("nweb engine is nullptr");
927         return nullptr;
928     }
929 
930     return nwebEngine_->GetNWeb(nweb_id);
931 }
932 
SetWebTag(int32_t nweb_id,const char * webTag)933 void NWebHelper::SetWebTag(int32_t nweb_id, const char* webTag)
934 {
935     if (nwebEngine_ == nullptr) {
936         WVLOG_I("SetWebTag try to init web engine handler");
937         if (GetWebEngineHandler() == nullptr) {
938             WVLOG_E("nwebEngine_ is nullptr");
939             return;
940         }
941     }
942 
943     nwebEngine_->SetWebTag(nweb_id, webTag);
944 }
945 
SetHttpDns(std::shared_ptr<NWebDOHConfig> config)946 void NWebHelper::SetHttpDns(std::shared_ptr<NWebDOHConfig> config)
947 {
948     if (nwebEngine_ == nullptr) {
949         WVLOG_E("nweb engine is nullptr");
950         return;
951     }
952 
953     std::shared_ptr<NWebDownloadManager> downloadManagr = nwebEngine_->GetDownloadManager();
954     if (!downloadManagr) {
955         WVLOG_E("download manager is nullptr");
956         return;
957     }
958 
959     downloadManagr->SetHttpDns(config);
960 }
961 
PrepareForPageLoad(std::string url,bool preconnectable,int32_t numSockets)962 void NWebHelper::PrepareForPageLoad(std::string url, bool preconnectable, int32_t numSockets)
963 {
964     if (nwebEngine_ == nullptr) {
965         WVLOG_E("nweb engine is nullptr");
966         return;
967     }
968 
969     nwebEngine_->PrepareForPageLoad(url, preconnectable, numSockets);
970 }
971 
GetDataBase()972 std::shared_ptr<NWebDataBase> NWebHelper::GetDataBase()
973 {
974     if (nwebEngine_ == nullptr) {
975         WVLOG_E("nweb engine is nullptr");
976         return nullptr;
977     }
978 
979     return nwebEngine_->GetDataBase();
980 }
981 
GetWebStorage()982 std::shared_ptr<NWebWebStorage> NWebHelper::GetWebStorage()
983 {
984     if (nwebEngine_ == nullptr) {
985         WVLOG_E("nweb engine is nullptr");
986         return nullptr;
987     }
988 
989     return nwebEngine_->GetWebStorage();
990 }
991 
SetConnectionTimeout(const int32_t & timeout)992 void NWebHelper::SetConnectionTimeout(const int32_t& timeout)
993 {
994     if (nwebEngine_ == nullptr) {
995         WVLOG_E("nweb engine is nullptr");
996         return;
997     }
998 
999     std::shared_ptr<NWebDownloadManager> downloadManagr = nwebEngine_->GetDownloadManager();
1000     if (!downloadManagr) {
1001         WVLOG_E("download manager is nullptr");
1002         return;
1003     }
1004 
1005     downloadManagr->SetConnectionTimeout(timeout);
1006     WVLOG_I("timeout value in NWebHelper: %{public}d", timeout);
1007 }
1008 
AddIntelligentTrackingPreventionBypassingList(const std::vector<std::string> & hosts)1009 void NWebHelper::AddIntelligentTrackingPreventionBypassingList(
1010     const std::vector<std::string>& hosts)
1011 {
1012     if (nwebEngine_ == nullptr) {
1013         WVLOG_E("nweb engine is nullptr");
1014         return;
1015     }
1016 
1017     nwebEngine_->AddIntelligentTrackingPreventionBypassingList(hosts);
1018 }
1019 
RemoveIntelligentTrackingPreventionBypassingList(const std::vector<std::string> & hosts)1020 void NWebHelper::RemoveIntelligentTrackingPreventionBypassingList(const std::vector<std::string>& hosts)
1021 {
1022     if (nwebEngine_ == nullptr) {
1023         WVLOG_E("nweb engine is nullptr");
1024         return;
1025     }
1026 
1027     nwebEngine_->RemoveIntelligentTrackingPreventionBypassingList(hosts);
1028 }
1029 
ClearIntelligentTrackingPreventionBypassingList()1030 void NWebHelper::ClearIntelligentTrackingPreventionBypassingList()
1031 {
1032     if (nwebEngine_ == nullptr) {
1033         WVLOG_E("nweb engine is nullptr");
1034         return;
1035     }
1036 
1037     nwebEngine_->ClearIntelligentTrackingPreventionBypassingList();
1038 }
1039 
PauseAllTimers()1040 void NWebHelper::PauseAllTimers()
1041 {
1042     if (nwebEngine_ == nullptr) {
1043         WVLOG_E("nweb engine is nullptr");
1044         return;
1045     }
1046 
1047     nwebEngine_->PauseAllTimers();
1048 }
1049 
ResumeAllTimers()1050 void NWebHelper::ResumeAllTimers()
1051 {
1052     if (nwebEngine_ == nullptr) {
1053         WVLOG_E("nweb engine is nullptr");
1054         return;
1055     }
1056 
1057     nwebEngine_->ResumeAllTimers();
1058 }
1059 
PrefetchResource(const std::shared_ptr<NWebEnginePrefetchArgs> & pre_args,const std::map<std::string,std::string> & additional_http_headers,const std::string & cache_key,const uint32_t & cache_valid_time)1060 void NWebHelper::PrefetchResource(const std::shared_ptr<NWebEnginePrefetchArgs> &pre_args,
1061                                   const std::map<std::string, std::string> &additional_http_headers,
1062                                   const std::string &cache_key,
1063                                   const uint32_t &cache_valid_time)
1064 {
1065     if (nwebEngine_ == nullptr) {
1066         WVLOG_E("nweb engine is nullptr");
1067         return;
1068     }
1069 
1070     nwebEngine_->PrefetchResource(pre_args, additional_http_headers, cache_key, cache_valid_time);
1071 }
1072 
ClearPrefetchedResource(const std::vector<std::string> & cache_key_list)1073 void NWebHelper::ClearPrefetchedResource(const std::vector<std::string>& cache_key_list)
1074 {
1075     if (nwebEngine_ == nullptr) {
1076         WVLOG_E("nweb engine is nullptr");
1077         return;
1078     }
1079 
1080     nwebEngine_->ClearPrefetchedResource(cache_key_list);
1081 }
1082 
SetRenderProcessMode(RenderProcessMode mode)1083 void NWebHelper::SetRenderProcessMode(RenderProcessMode mode)
1084 {
1085     if (nwebEngine_ == nullptr) {
1086         WVLOG_E("nweb engine is nullptr");
1087         return;
1088     }
1089 
1090     nwebEngine_->SetRenderProcessMode(mode);
1091 }
1092 
GetRenderProcessMode()1093 RenderProcessMode NWebHelper::GetRenderProcessMode()
1094 {
1095     if (nwebEngine_ == nullptr) {
1096         WVLOG_E("nweb engine is nullptr");
1097         return RenderProcessMode::SINGLE_MODE;
1098     }
1099 
1100     return nwebEngine_->GetRenderProcessMode();
1101 }
1102 
SetHostIP(const std::string & hostName,const std::string & address,int32_t aliveTime)1103 void NWebHelper::SetHostIP(const std::string& hostName, const std::string& address, int32_t aliveTime)
1104 {
1105     if (nwebEngine_ == nullptr) {
1106         WVLOG_E("nweb engine is nullptr");
1107         return;
1108     }
1109 
1110     nwebEngine_->SetHostIP(hostName, address, aliveTime);
1111 }
1112 
EnableBackForwardCache(bool enableNativeEmbed,bool enableMediaTakeOver)1113 void NWebHelper::EnableBackForwardCache(bool enableNativeEmbed, bool enableMediaTakeOver)
1114 {
1115     this->backForwardCacheCmdLine_.emplace_back("--enable-bfcache");
1116     if (enableNativeEmbed) {
1117         this->backForwardCacheCmdLine_.emplace_back("--enable-cache-native-embed");
1118     }
1119 
1120     if (enableMediaTakeOver) {
1121         this->backForwardCacheCmdLine_.emplace_back("--enable-cache-media-take-over");
1122     }
1123 }
1124 
ClearHostIP(const std::string & hostName)1125 void NWebHelper::ClearHostIP(const std::string& hostName)
1126 {
1127     if (nwebEngine_ == nullptr) {
1128         WVLOG_E("nweb engine is nullptr");
1129         return;
1130     }
1131 
1132     nwebEngine_->ClearHostIP(hostName);
1133 }
1134 
WarmupServiceWorker(const std::string & url)1135 void NWebHelper::WarmupServiceWorker(const std::string &url)
1136 {
1137     if (nwebEngine_ == nullptr) {
1138         WVLOG_E("nweb engine is nullptr");
1139         return;
1140     }
1141 
1142     nwebEngine_->WarmupServiceWorker(url);
1143 }
1144 
SetWholeWebDrawing()1145 void NWebHelper::SetWholeWebDrawing()
1146 {
1147     WVLOG_I("===== Engine set whole =====");
1148     if (nwebEngine_ == nullptr) {
1149         WVLOG_E("nweb engine is nullptr");
1150         return;
1151     }
1152     WVLOG_I("===== go webview engine =====");
1153     nwebEngine_->SetWholeWebDrawing();
1154 }
1155 
GetAdsBlockManager()1156 std::shared_ptr<NWebAdsBlockManager> NWebHelper::GetAdsBlockManager()
1157 {
1158     if (libHandleWebEngine_ == nullptr) {
1159         WVLOG_I("GetAdsBlockManager: init web engine start.");
1160         // obtain bundle path
1161         std::shared_ptr<AbilityRuntime::ApplicationContext> ctx =
1162             AbilityRuntime::ApplicationContext::GetApplicationContext();
1163         if (!ctx) {
1164             WVLOG_E("GetAdsBlockManager: Failed to init web engine due to nil application context.");
1165             return nullptr;
1166         }
1167         // load so
1168         const std::string& bundle_path = ctx->GetBundleCodeDir();
1169         SetBundlePath(bundle_path);
1170         if (!Init(true)) {
1171             WVLOG_E("GetAdsBlockManager: Failed to init web engine due to NWebHelper failure.");
1172             return nullptr;
1173         }
1174         WVLOG_I("GetAdsBlockManager: init web engine success.");
1175     }
1176 
1177     if (nwebEngine_ == nullptr) {
1178         WVLOG_E("nweb engine is nullptr");
1179         return nullptr;
1180     }
1181 
1182     return nwebEngine_->GetAdsBlockManager();
1183 }
1184 
Instance()1185 NWebAdapterHelper &NWebAdapterHelper::Instance()
1186 {
1187     static NWebAdapterHelper helper;
1188     return helper;
1189 }
1190 
Init(bool from_ark)1191 bool NWebAdapterHelper::Init(bool from_ark)
1192 {
1193     return NWebHelper::Instance().Init(from_ark);
1194 }
1195 
GetCurrentRealTimeNs()1196 static int64_t GetCurrentRealTimeNs()
1197 {
1198     struct timespec ts = { 0, 0 };
1199     if (clock_gettime(CLOCK_MONOTONIC, &ts) != 0) {
1200         return 0;
1201     }
1202     return (ts.tv_sec * NS_TO_S + ts.tv_nsec);
1203 }
1204 
CreateNWeb(sptr<Surface> surface,std::shared_ptr<NWebEngineInitArgsImpl> initArgs,uint32_t width,uint32_t height,bool incognitoMode)1205 std::shared_ptr<NWeb> NWebAdapterHelper::CreateNWeb(sptr<Surface> surface,
1206     std::shared_ptr<NWebEngineInitArgsImpl> initArgs,
1207     uint32_t width, uint32_t height, bool incognitoMode)
1208 {
1209     int64_t startTime = GetCurrentRealTimeNs();
1210     if (surface == nullptr) {
1211         WVLOG_E("fail to create nweb, input surface is nullptr");
1212         return nullptr;
1213     }
1214     if (width > NWEB_SURFACE_MAX_WIDTH || height > NWEB_SURFACE_MAX_HEIGHT) {
1215         WVLOG_E("input size %{public}u*%{public}u is invalid.", width, height);
1216         return nullptr;
1217     }
1218     auto createInfo = NWebSurfaceAdapter::Instance().GetCreateInfo(
1219         surface, initArgs, width, height, incognitoMode);
1220     NWebConfigHelper::Instance().ParseConfig(initArgs);
1221 
1222     // obtain bundle path
1223     std::shared_ptr<AbilityRuntime::ApplicationContext> ctx =
1224         AbilityRuntime::ApplicationContext::GetApplicationContext();
1225     if (ctx) {
1226         std::string bundleName = ctx->GetBundleName();
1227         initArgs->AddArg(std::string("--bundle-name=").append(bundleName));
1228     }
1229 
1230     auto nweb = NWebHelper::Instance().CreateNWeb(createInfo);
1231     if (nweb == nullptr) {
1232         WVLOG_E("fail to create nweb instance");
1233         return nullptr;
1234     }
1235     int64_t endTime = GetCurrentRealTimeNs();
1236     EventReport::ReportCreateWebInstanceTime(nweb->GetWebId(), endTime - startTime);
1237     return nweb;
1238 }
1239 
CreateNWeb(void * enhanceSurfaceInfo,std::shared_ptr<NWebEngineInitArgsImpl> initArgs,uint32_t width,uint32_t height,bool incognitoMode)1240 std::shared_ptr<NWeb> NWebAdapterHelper::CreateNWeb(void *enhanceSurfaceInfo,
1241     std::shared_ptr<NWebEngineInitArgsImpl> initArgs, uint32_t width, uint32_t height, bool incognitoMode)
1242 {
1243     int64_t startTime = GetCurrentRealTimeNs();
1244     if (enhanceSurfaceInfo == nullptr) {
1245         WVLOG_E("fail to create nweb, input surface is nullptr");
1246         return nullptr;
1247     }
1248     if (width > NWEB_SURFACE_MAX_WIDTH || height > NWEB_SURFACE_MAX_HEIGHT) {
1249         WVLOG_E("input size %{public}u*%{public}u is invalid.", width, height);
1250         return nullptr;
1251     }
1252     auto createInfo = NWebEnhanceSurfaceAdapter::Instance().GetCreateInfo(
1253         enhanceSurfaceInfo, initArgs, width, height, incognitoMode);
1254     auto nweb = NWebHelper::Instance().CreateNWeb(createInfo);
1255     if (nweb == nullptr) {
1256         WVLOG_E("fail to create nweb instance");
1257         return nullptr;
1258     }
1259     int64_t endTime = GetCurrentRealTimeNs();
1260     EventReport::ReportCreateWebInstanceTime(nweb->GetWebId(), endTime - startTime);
1261     return nweb;
1262 }
1263 
ParseConfig(std::shared_ptr<NWebEngineInitArgsImpl> initArgs)1264 void NWebAdapterHelper::ParseConfig(std::shared_ptr<NWebEngineInitArgsImpl> initArgs)
1265 {
1266     NWebConfigHelper::Instance().ParseConfig(initArgs);
1267 }
1268 
GetPerfConfig(const std::string & settingName)1269 std::vector<FrameRateSetting> NWebAdapterHelper::GetPerfConfig(const std::string& settingName)
1270 {
1271     auto perfConfig = NWebConfigHelper::Instance().GetPerfConfig(settingName);
1272     return perfConfig;
1273 }
1274 
ParsePerfConfig(const std::string & configNodeName,const std::string & argsNodeName)1275 std::string NWebAdapterHelper::ParsePerfConfig(const std::string &configNodeName, const std::string &argsNodeName)
1276 {
1277     std::string config = NWebConfigHelper::Instance().ParsePerfConfig(configNodeName, argsNodeName);
1278     return config;
1279 }
1280 } // namespace OHOS::NWeb
1281