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