1 /*
2  * Copyright (c) 2022 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  * http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #ifndef NWEB_WEBVIEW_CONTROLLER_H
17 #define NWEB_WEBVIEW_CONTROLLER_H
18 
19 #include <filesystem>
20 #include <memory>
21 #include <string>
22 #include <unordered_map>
23 
24 #include "napi/native_api.h"
25 #include "napi/native_common.h"
26 #include "napi/native_node_api.h"
27 #include "nweb.h"
28 #include "nweb_helper.h"
29 #include "nweb_web_message.h"
30 #include "web_errors.h"
31 #include "webview_javascript_result_callback.h"
32 #include "print_manager_adapter.h"
33 
34 #include "web_scheme_handler_request.h"
35 
36 namespace OHOS {
37 namespace NWeb {
38 enum class WebHitTestType : int {
39     EDIT = 0,
40     EMAIL,
41     HTTP,
42     HTTP_IMG,
43     IMG,
44     MAP,
45     PHONE,
46     UNKNOWN
47 };
48 
49 enum class SecureDnsModeType : int {
50     OFF = 0,
51     AUTO,
52     SECURE_ONLY
53 };
54 
55 enum class ResourceType : uint32_t {
56     COLOR = 10001,
57     FLOAT,
58     STRING,
59     PLURAL,
60     BOOLEAN,
61     INTARRAY,
62     INTEGER,
63     PATTERN,
64     STRARRAY,
65     MEDIA = 20000,
66     RAWFILE = 30000
67 };
68 
69 enum class WebMessageType : int {
70     NOTSUPPORT = 0,
71     STRING,
72     NUMBER,
73     BOOLEAN,
74     ARRAYBUFFER,
75     ARRAY,
76     ERROR
77 };
78 
79 enum class MediaPlaybackState : int {
80     NONE = 0,
81     PLAYING,
82     PAUSED,
83     STOP
84 };
85 
86 enum class SecurityLevel : int {
87     NONE = 0,
88     SECURE,
89     WARNING,
90     DANGEROUS
91 };
92 
93 enum class CoreSecurityLevel : int {
94     NONE = 0,
95     SECURE = 3,
96     DANGEROUS = 5,
97     WARNING = 6
98 };
99 
100 enum class OfflineResourceType : int {
101     IMAGE = 0,
102     CSS,
103     CLASSIC_JS,
104     MODULE_JS
105 };
106 
107 enum class ParseURLResult : int {
108     OK = 0,
109     FAILED,
110     INVALID_URL
111 };
112 
113 enum class UrlListSetResult : int {
114     INIT_ERROR = -2,
115     PARAM_ERROR = -1,
116     SET_OK = 0,
117 };
118 
119 enum class PressureLevel : int {
120     MEMORY_PRESSURE_LEVEL_MODERATE = 1,
121     MEMORY_PRESSURE_LEVEL_CRITICAL = 2,
122 };
123 
124 enum class ScrollType : int {
125     EVENT = 0,
126 };
127 
128 class WebPrintDocument;
129 class WebviewController {
130 public:
131     explicit WebviewController() = default;
132     explicit WebviewController(int32_t nwebId);
133     explicit WebviewController(const std::string& webTag);
134     ~WebviewController();
135 
136     bool IsInit() const;
137 
138     void SetWebId(int32_t nwebId);
139 
140     WebviewController* FromID(int32_t nwebId);
141 
142     bool AccessForward() const;
143 
144     bool AccessBackward() const;
145 
146     bool AccessStep(int32_t step) const;
147 
148     void ClearHistory();
149 
150     void Forward();
151 
152     void Backward();
153 
154     void OnActive();
155 
156     void OnInactive();
157 
158     void Refresh();
159 
160     ErrCode ZoomIn();
161 
162     ErrCode ZoomOut();
163 
164     int32_t GetWebId() const;
165 
166     std::string GetUserAgent();
167 
168     std::string GetCustomUserAgent() const;
169 
170     ErrCode SetCustomUserAgent(const std::string& userAgent);
171 
172     std::string GetTitle();
173 
174     int32_t GetPageHeight();
175 
176     ErrCode BackOrForward(int32_t step);
177 
178     void StoreWebArchiveCallback(const std::string &baseName, bool autoName, napi_env env, napi_ref jsCallback);
179 
180     void StoreWebArchivePromise(const std::string &baseName, bool autoName, napi_env env, napi_deferred deferred);
181 
182     std::vector<std::string> CreateWebMessagePorts();
183 
184     ErrCode PostWebMessage(std::string& message, std::vector<std::string>& ports, std::string& targetUrl);
185 
186     std::shared_ptr<HitTestResult> GetHitTestValue();
187 
188     void RequestFocus();
189 
190     bool ParseUrl(napi_env env, napi_value urlObj, std::string& result) const;
191 
192     ErrCode LoadUrl(std::string url);
193 
194     ErrCode LoadUrl(std::string url, std::map<std::string, std::string> httpHeaders);
195 
196     ErrCode LoadData(std::string data, std::string mimeType, std::string encoding,
197         std::string baseUrl, std::string historyUrl);
198 
199     int GetHitTest();
200 
201     void ClearMatches();
202 
203     void SearchNext(bool forward);
204 
205     void SearchAllAsync(const std::string& searchString);
206 
207     void ClearSslCache();
208 
209     void ClearClientAuthenticationCache();
210 
211     void Stop();
212 
213     ErrCode Zoom(float factor);
214 
215     void InnerCompleteWindowNew(int32_t parentNwebId);
216 
217     void SetNWebJavaScriptResultCallBack();
218 
219     void RegisterJavaScriptProxy(RegisterJavaScriptProxyParam& param);
220 
221     ErrCode DeleteJavaScriptRegister(const std::string& objName,
222         const std::vector<std::string>& methodList);
223 
224     void RunJavaScriptCallback(const std::string &script, napi_env env, napi_ref jsCallback, bool extention);
225 
226     void RunJavaScriptPromise(const std::string &script, napi_env env, napi_deferred deferred, bool extention);
227 
228     void RunJavaScriptCallbackExt(
229         const int fd, const size_t scriptLength, napi_env env, napi_ref jsCallback, bool extention);
230 
231     void RunJavaScriptPromiseExt(
232         const int fd, const size_t scriptLength, napi_env env, napi_deferred deferred, bool extention);
233 
234     std::string GetUrl();
235 
236     std::string GetOriginalUrl();
237 
238     bool TerminateRenderProcess() const;
239 
240     void PutNetworkAvailable(bool available);
241 
242     bool HasImage(std::shared_ptr<NWebBoolValueCallback> callback);
243 
244     ErrCode HasImagesCallback(napi_env env, napi_ref jsCallback);
245 
246     ErrCode HasImagesPromise(napi_env env, napi_deferred deferred);
247 
248     void RemoveCache(bool includeDiskFiles);
249 
250     std::shared_ptr<NWebHistoryList> GetHistoryList();
251 
252     bool GetFavicon(
253         const void **data, size_t &width, size_t &height, ImageColorType &colorType, ImageAlphaType &alphaType) const;
254 
255     std::vector<uint8_t> SerializeWebState();
256 
257     bool RestoreWebState(const std::vector<uint8_t> &state) const;
258 
259     void ScrollPageDown(bool bottom);
260 
261     void ScrollPageUp(bool top);
262 
263     void ScrollTo(float x, float y);
264 
265     void ScrollBy(float deltaX, float deltaY);
266 
267     void SlideScroll(float vx, float vy);
268 
269     void SetScrollable(bool enable);
270 
271     void SetScrollable(bool enable, int32_t scrollType);
272 
273     bool GetScrollable() const;
274 
275     void InnerSetHapPath(const std::string &hapPath);
276 
277     bool GetCertChainDerData(std::vector<std::string> &certChainDerData) const;
278 
279     ErrCode SetAudioMuted(bool muted);
280 
281     ErrCode PrefetchPage(std::string& url, std::map<std::string, std::string> additionalHttpHeaders);
282 
283     void* CreateWebPrintDocumentAdapter(const std::string &jobName);
284 
285     ErrCode PostUrl(std::string& url, std::vector<char>& postData);
286 
287     int GetSecurityLevel();
288 
289     void EnableSafeBrowsing(bool enable);
290 
291     bool IsSafeBrowsingEnabled() const;
292 
293     bool IsIncognitoMode() const;
294 
295     void SetPrintBackground(bool enable);
296 
297     bool GetPrintBackground() const;
298 
299     std::string GetLastJavascriptProxyCallingFrameUrl();
300 
301     static std::string GenerateWebTag();
302 
303     bool SetWebSchemeHandler(const char* scheme, WebSchemeHandler* handler) const;
304 
305     int32_t ClearWebSchemeHandler();
306 
307     static bool SetWebServiveWorkerSchemeHandler(
308         const char* scheme, WebSchemeHandler* handler);
309 
310     static int32_t ClearWebServiceWorkerSchemeHandler();
311 
312     void CloseAllMediaPresentations();
313 
314     void StopAllMedia();
315 
316     void ResumeAllMedia();
317 
318     void PauseAllMedia();
319 
320     int GetMediaPlaybackState();
321 
322     void EnableIntelligentTrackingPrevention(bool enable);
323 
324     bool IsIntelligentTrackingPreventionEnabled() const;
325 
326     ErrCode StartCamera();
327 
328     ErrCode StopCamera();
329 
330     ErrCode CloseCamera();
331 
332     void OnCreateNativeMediaPlayer(napi_env env, napi_ref callback);
333 
334     bool ParseScriptContent(napi_env env, napi_value value, std::string &script);
335 
336     std::shared_ptr<CacheOptions> ParseCacheOptions(napi_env env, napi_value value);
337 
338     void PrecompileJavaScriptPromise(napi_env env,
339                                      napi_deferred deferred,
340                                      const std::string &url, const std::string &script,
341                                      std::shared_ptr<CacheOptions> cacheOptions);
342 
343     bool ParseResponseHeaders(napi_env env,
344                               napi_value value,
345                               std::map<std::string, std::string> &responseHeaders) const;
346 
347     ParseURLResult ParseURLList(napi_env env, napi_value value, std::vector<std::string>& urlList);
348 
349     bool CheckURL(std::string& url) const;
350 
351     std::vector<uint8_t> ParseUint8Array(napi_env env, napi_value value);
352 
353     void InjectOfflineResource(const std::vector<std::string>& urlList,
354                                const std::vector<uint8_t>& resource,
355                                const std::map<std::string, std::string>& response_headers,
356                                const uint32_t type);
357 
358     ErrCode SetUrlTrustList(const std::string& urlTrustList, std::string& detailErrMsg);
359 
360     void EnableAdsBlock(bool enable);
361 
362     bool IsAdsBlockEnabled() const;
363 
364     bool IsAdsBlockEnabledForCurPage() const;
365 
366     std::string GetSurfaceId();
367 
368     void UpdateInstanceId(int32_t newId);
369 
370     bool ParseJsLengthToInt(napi_env env,
371                             napi_value jsLength,
372                             PixelUnit& type,
373                             int32_t& result) const;
374 
375     ErrCode WebPageSnapshot(const char* id,
376                             PixelUnit type,
377                             int32_t width,
378                             int32_t height,
379                             const WebSnapshotCallback callback);
380 
381     void SetPathAllowingUniversalAccess(const std::vector<std::string>& pathList,
382                                         std::string& errorPath);
383 
384     void ScrollToWithAnime(float x, float y, int32_t duration) ;
385 
386     void ScrollByWithAnime(float deltaX, float deltaY, int32_t duration) ;
387 
388     void SetBackForwardCacheOptions(int32_t size, int32_t timeToLive);
389 
390     void GetScrollOffset(float* offset_x, float* offset_y);
391 
392     void CreatePDFCallbackExt(
393         napi_env env, std::shared_ptr<NWebPDFConfigArgs> pdfConfig, napi_ref pdfCallback);
394 
395     void CreatePDFPromiseExt(
396         napi_env env, std::shared_ptr<NWebPDFConfigArgs> pdfConfig, napi_deferred deferred);
397 
398     bool ScrollByWithResult(float deltaX, float deltaY) const;
399 private:
400     int ConverToWebHitTestType(int hitType);
401 
402     bool GetRawFileUrl(const std::string &fileName,
403         const std::string& bundleName, const std::string& moduleName, std::string &result) const;
404 
405     bool ParseRawFileUrl(napi_env env, napi_value urlObj, std::string& result) const;
406 
407     bool GetResourceUrl(napi_env env, napi_value urlObj, std::string& result) const;
408 
409     bool ParseJsLengthResourceToInt(napi_env env,
410                                     napi_value jsLength,
411                                     PixelUnit& type,
412                                     int32_t& result) const;
413     bool GetHapModuleInfo();
414 
415 public:
416     static std::string customeSchemeCmdLine_;
417     static bool existNweb_;
418     static bool webDebuggingAccess_;
419     static std::set<std::string> webTagSet_;
420     static int32_t webTagStrId_;
421 
422 private:
423     std::mutex webMtx_;
424     int32_t nwebId_ = -1;
425     std::shared_ptr<WebviewJavaScriptResultCallBack> javaScriptResultCb_ = nullptr;
426     std::string hapPath_ = "";
427     std::string webTag_ = "";
428     std::vector<std::string> moduleName_;
429 };
430 
431 class WebMessagePort {
432 public:
433     WebMessagePort(int32_t nwebId, std::string& port, bool isExtentionType);
434 
435     ~WebMessagePort() = default;
436 
437     ErrCode ClosePort();
438 
439     ErrCode PostPortMessage(std::shared_ptr<NWebMessage> data);
440 
441     ErrCode SetPortMessageCallback(std::shared_ptr<NWebMessageValueCallback> callback);
442 
443     std::string GetPortHandle() const;
444 
IsExtentionType()445     bool IsExtentionType()
446     {
447         return isExtentionType_;
448     }
449 
450 private:
451     int32_t nwebId_ = -1;
452     std::string portHandle_;
453     bool isExtentionType_;
454 };
455 
456 class WebMessageExt {
457 public:
WebMessageExt(std::shared_ptr<NWebMessage> data)458     explicit WebMessageExt(std::shared_ptr<NWebMessage> data) : data_(data) {};
459     ~WebMessageExt() = default;
460 
461     void SetType(int type);
462 
463     int ConvertNwebType2JsType(NWebValue::Type type);
464 
GetType()465     int GetType()
466     {
467         if (data_) {
468             return ConvertNwebType2JsType(data_->GetType());
469         }
470         return static_cast<int>(WebMessageType::NOTSUPPORT);
471     }
472 
SetString(std::string value)473     void SetString(std::string value)
474     {
475         if (data_) {
476             data_->SetType(NWebValue::Type::STRING);
477             data_->SetString(value);
478         }
479     }
480 
SetNumber(double value)481     void SetNumber(double value)
482     {
483         if (data_) {
484             data_->SetType(NWebValue::Type::DOUBLE);
485             data_->SetDouble(value);
486         }
487     }
488 
SetBoolean(bool value)489     void SetBoolean(bool value)
490     {
491         if (data_) {
492             data_->SetType(NWebValue::Type::BOOLEAN);
493             data_->SetBoolean(value);
494         }
495     }
496 
SetArrayBuffer(std::vector<uint8_t>& value)497     void SetArrayBuffer(std::vector<uint8_t>& value)
498     {
499         if (data_) {
500             data_->SetType(NWebValue::Type::BINARY);
501             data_->SetBinary(value);
502         }
503     }
504 
SetStringArray(std::vector<std::string> value)505     void SetStringArray(std::vector<std::string> value)
506     {
507         if (data_) {
508             data_->SetType(NWebValue::Type::STRINGARRAY);
509             data_->SetStringArray(value);
510         }
511     }
512 
SetDoubleArray(std::vector<double> value)513     void SetDoubleArray(std::vector<double> value)
514     {
515         if (data_) {
516             data_->SetType(NWebValue::Type::DOUBLEARRAY);
517             data_->SetDoubleArray(value);
518         }
519     }
520 
SetInt64Array(std::vector<int64_t> value)521     void SetInt64Array(std::vector<int64_t> value)
522     {
523         if (data_) {
524             data_->SetType(NWebValue::Type::INT64ARRAY);
525             data_->SetInt64Array(value);
526         }
527     }
528 
SetBooleanArray(std::vector<bool> value)529     void SetBooleanArray(std::vector<bool> value)
530     {
531         if (data_) {
532             data_->SetType(NWebValue::Type::BOOLEANARRAY);
533             data_->SetBooleanArray(value);
534         }
535     }
536 
SetError(std::string name, std::string message)537     void SetError(std::string name, std::string message)
538     {
539         if (data_) {
540             data_->SetType(NWebValue::Type::ERROR);
541             data_->SetErrName(name);
542             data_->SetErrMsg(message);
543         }
544     }
545 
GetData() const546     std::shared_ptr<NWebMessage> GetData() const
547     {
548         return data_;
549     }
550 
551 private:
552     int type_ = 0;
553     std::shared_ptr<NWebMessage> data_;
554 };
555 
556 class WebHistoryList {
557 public:
WebHistoryList(std::shared_ptr<NWebHistoryList> sptrHistoryList)558     explicit WebHistoryList(std::shared_ptr<NWebHistoryList> sptrHistoryList) : sptrHistoryList_(sptrHistoryList) {};
559     ~WebHistoryList() = default;
560 
561     int32_t GetCurrentIndex();
562 
563     std::shared_ptr<NWebHistoryItem> GetItem(int32_t index);
564 
565     int32_t GetListSize();
566 
567 private:
568     OHOS::NWeb::NWeb* nweb_ = nullptr;
569     std::shared_ptr<NWebHistoryList> sptrHistoryList_ = nullptr;
570 };
571 
572 class WebPrintDocument {
573 public:
WebPrintDocument(void* webPrintdoc)574     explicit WebPrintDocument(void* webPrintdoc) : printDocAdapter_((PrintDocumentAdapterAdapter*)webPrintdoc) {};
575     ~WebPrintDocument() = default;
576     void OnStartLayoutWrite(const std::string& jobId, const PrintAttributesAdapter& oldAttrs,
577         const PrintAttributesAdapter& newAttrs, uint32_t fd,
578         std::function<void(std::string, uint32_t)> writeResultCallback);
579 
580     void OnJobStateChanged(const std::string& jobId, uint32_t state);
581 
582 private:
583     std::unique_ptr<PrintDocumentAdapterAdapter> printDocAdapter_ = nullptr;
584 };
585 
586 class WebPrintWriteResultCallbackAdapter : public PrintWriteResultCallbackAdapter {
587 public:
WebPrintWriteResultCallbackAdapter(std::function<void(std::string, uint32_t)>& cb)588     explicit WebPrintWriteResultCallbackAdapter(std::function<void(std::string, uint32_t)>& cb) : cb_(cb) {};
589 
590     void WriteResultCallback(std::string jobId, uint32_t code) override;
591 
592 private:
593     std::function<void(std::string, uint32_t)> cb_;
594 };
595 } // namespace NWeb
596 } // namespace OHOS
597 
598 #endif // NWEB_WEBVIEW_CONTROLLER_H
599