BNIBookingWebView.swift 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926
  1. //
  2. // BNIBookingWebView.swift
  3. // FMDB
  4. //
  5. // Created by Qindi on 01/04/22.
  6. //
  7. import Foundation
  8. import UIKit
  9. import WebKit
  10. import Speech
  11. import CommonCrypto
  12. public class BNIBookingWebView: UIViewController, WKNavigationDelegate, UIScrollViewDelegate, UIGestureRecognizerDelegate, WKScriptMessageHandler, SFSpeechRecognizerDelegate, ImageVideoPickerDelegate {
  13. var webView: WKWebView!
  14. let closeButton = UIButton()
  15. public var customUrl = ""
  16. public var isSecureBrowser = false
  17. let textField = UITextField()
  18. var isAllowSpeech = false
  19. let speechRecognizer = SFSpeechRecognizer(locale: Locale(identifier: "id"))
  20. var recognitionRequest : SFSpeechAudioBufferRecognitionRequest?
  21. var recognitionTask : SFSpeechRecognitionTask?
  22. let audioEngine = AVAudioEngine()
  23. var alertController = LibAlertController()
  24. var indexImageVideoWv = 0
  25. var imageVideoPicker: ImageVideoPicker!
  26. var blockedCertificate = ""
  27. var allowedURLs = Set<String>()
  28. var loadingURL = false
  29. public override var preferredStatusBarStyle: UIStatusBarStyle {
  30. return .default
  31. }
  32. public override func viewDidLoad() {
  33. super.viewDidLoad()
  34. let configuration = WKWebViewConfiguration()
  35. configuration.allowsInlineMediaPlayback = true
  36. loadContentBlocker(into: configuration) { [self] in
  37. DispatchQueue.main.async {
  38. self.initializeWebView(with: configuration)
  39. }
  40. }
  41. }
  42. func initializeWebView(with configuration: WKWebViewConfiguration) {
  43. let customUserAgent = "Mozilla/5.0 (iPhone; CPU iPhone OS 16_6 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.5 Mobile/15E148 Safari/604.1 \(Utils.getUserAgent())"
  44. let finalUserAgent = "\(customUserAgent)"
  45. configuration.applicationNameForUserAgent = finalUserAgent
  46. webView = WKWebView(frame: .zero, configuration: configuration)
  47. let containerView = UIView()
  48. containerView.backgroundColor = .white
  49. if isSecureBrowser {
  50. view.addSubview(containerView)
  51. containerView.translatesAutoresizingMaskIntoConstraints = false
  52. containerView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
  53. containerView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
  54. containerView.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
  55. containerView.heightAnchor.constraint(equalToConstant: 44).isActive = true
  56. containerView.addSubview(textField)
  57. textField.translatesAutoresizingMaskIntoConstraints = false
  58. textField.leftAnchor.constraint(equalTo: containerView.leftAnchor, constant: 10.0).isActive = true
  59. textField.centerYAnchor.constraint(equalTo: containerView.centerYAnchor).isActive = true
  60. textField.heightAnchor.constraint(equalToConstant: 40).isActive = true
  61. textField.widthAnchor.constraint(equalToConstant: view.bounds.size.width - 80).isActive = true
  62. textField.layer.borderColor = UIColor.lightGray.cgColor
  63. textField.layer.borderWidth = 1.0
  64. textField.layer.cornerRadius = 5.0
  65. textField.clipsToBounds = true
  66. let buttonGo = UIButton(type: .custom)
  67. buttonGo.setTitle("Go".localized(), for: .normal)
  68. buttonGo.setTitleColor(.black, for: .normal)
  69. buttonGo.addTarget(self, action: #selector(goAction), for: .touchUpInside)
  70. containerView.addSubview(buttonGo)
  71. buttonGo.translatesAutoresizingMaskIntoConstraints = false
  72. buttonGo.leftAnchor.constraint(equalTo: textField.rightAnchor, constant: 10.0).isActive = true
  73. buttonGo.rightAnchor.constraint(equalTo: containerView.rightAnchor, constant: -10.0).isActive = true
  74. buttonGo.centerYAnchor.constraint(equalTo: containerView.centerYAnchor).isActive = true
  75. buttonGo.heightAnchor.constraint(equalToConstant: 40).isActive = true
  76. }
  77. view.addSubview(webView)
  78. webView.translatesAutoresizingMaskIntoConstraints = false
  79. if isSecureBrowser {
  80. webView.topAnchor.constraint(equalTo: containerView.bottomAnchor).isActive = true
  81. } else {
  82. webView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
  83. }
  84. webView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
  85. webView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
  86. webView.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
  87. webView.navigationDelegate = self
  88. webView.allowsBackForwardNavigationGestures = true
  89. webView.scrollView.delegate = self
  90. let contentController = webView.configuration.userContentController
  91. contentController.add(self, name: "sendQueueBNI")
  92. contentController.add(self, name: "checkProfile")
  93. contentController.add(self, name: "setIsProductModalOpen")
  94. contentController.add(self, name: "toggleVoiceSearch")
  95. contentController.add(self, name: "blockUser")
  96. contentController.add(self, name: "showAlert")
  97. contentController.add(self, name: "closeProfile")
  98. contentController.add(self, name: "successChangeTheme")
  99. contentController.add(self, name: "finishForm")
  100. contentController.add(self, name: "shareText")
  101. contentController.add(self, name: "openGalleryiOS")
  102. let source: String = "var meta = document.createElement('meta');" +
  103. "meta.name = 'viewport';" +
  104. "meta.content = 'width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no';" +
  105. "var head = document.getElementsByTagName('head')[0];" +
  106. "head.appendChild(meta);" +
  107. "$('#header-layout').find('.col-8').removeClass('col-8').addClass('col');" +
  108. "$('#header-layout').find('.col-4').removeClass('col-4').addClass('col');"
  109. let script: WKUserScript = WKUserScript(source: source, injectionTime: .atDocumentEnd, forMainFrameOnly: false)
  110. contentController.addUserScript(script)
  111. let cookieScript1 = "document.cookie = '\(Utils.getCookiesMobile().components(separatedBy: ";")[0])';"
  112. let cookieScriptInjection1 = WKUserScript(source: cookieScript1, injectionTime: .atDocumentStart, forMainFrameOnly: false)
  113. configuration.userContentController.addUserScript(cookieScriptInjection1)
  114. let cookieScript2 = "document.cookie = '\(Utils.getCookiesMobile().components(separatedBy: ";")[1])';"
  115. let cookieScriptInjection2 = WKUserScript(source: cookieScript2, injectionTime: .atDocumentStart, forMainFrameOnly: false)
  116. configuration.userContentController.addUserScript(cookieScriptInjection2)
  117. let refreshControl = UIRefreshControl()
  118. refreshControl.addTarget(self, action: #selector(reloadWebView(_:)), for: .valueChanged)
  119. webView.scrollView.addSubview(refreshControl)
  120. webView.isOpaque = false
  121. webView.backgroundColor = .white
  122. webView.scrollView.backgroundColor = .white
  123. var stringQMS = "https://sqbni.murni.id:4200/bnibookingonline/#/?userid="
  124. if !customUrl.isEmpty {
  125. stringQMS = customUrl
  126. }
  127. if stringQMS.lowercased().contains("?userid=") {
  128. let name = User.getData(pin: User.getMyPin())!.fullName
  129. stringQMS += name
  130. } else if stringQMS.lowercased().contains("?f_pin=") {
  131. stringQMS += User.getMyPin()!
  132. }
  133. if stringQMS.contains("<<f_pin>>") {
  134. stringQMS = stringQMS.replacingOccurrences(of: "<<f_pin>>", with: User.getMyPin()!)
  135. }
  136. let lang: String = SecureUserDefaults.shared.value(forKey: "i18n_language") ?? "en"
  137. var intLang = 0
  138. if lang == "id" {
  139. intLang = 1
  140. }
  141. if stringQMS.starts(with: Utils.getURLBase()) {
  142. stringQMS = stringQMS + "&lang=\(intLang)&theme=\(self.traitCollection.userInterfaceStyle == .dark ? "0" : "1")"
  143. }
  144. if let url = URL(string: "\(stringQMS)") {
  145. if !isSecureBrowser {
  146. loadURLWithCookie(url: url)
  147. }
  148. }
  149. }
  150. func loadContentBlocker(into config: WKWebViewConfiguration, completion: @escaping () -> Void) {
  151. // Define ad-blocking rules directly in Swift as a string
  152. let contentRules = """
  153. [
  154. {
  155. "trigger": {
  156. "url-filter": ".*(ads|adserver|advert|doubleclick|popads|popcash|onclickads|adfly|shorte).*",
  157. "resource-type": ["script", "image", "stylesheet", "document", "subdocument", "media"]
  158. },
  159. "action": { "type": "block" }
  160. },
  161. {
  162. "trigger": {
  163. "url-filter": ".*(taboola|outbrain|scorecardresearch|googlesyndication|tracking|track|pixel).*",
  164. "resource-type": ["script", "iframe", "xmlhttprequest"]
  165. },
  166. "action": { "type": "block" }
  167. },
  168. {
  169. "trigger": {
  170. "url-filter": ".*(google-analytics|facebook.com/tr|analytics|gtag|data-collect|collect).*",
  171. "resource-type": ["script", "xmlhttprequest"]
  172. },
  173. "action": { "type": "block" }
  174. },
  175. {
  176. "trigger": {
  177. "url-filter": ".*(banner|sponsored|clicktrack|beacon|stats|metrics).*",
  178. "resource-type": ["script", "image", "iframe"]
  179. },
  180. "action": { "type": "block" }
  181. }
  182. ]
  183. """
  184. WKContentRuleListStore.default().compileContentRuleList(forIdentifier: "AdBlocker", encodedContentRuleList: contentRules) { ruleList, error in
  185. if let ruleList = ruleList {
  186. config.userContentController.add(ruleList)
  187. } else {
  188. print("Failed to compile content rule list: \(error?.localizedDescription ?? "Unknown error")")
  189. }
  190. completion()
  191. }
  192. }
  193. @objc func goAction() {
  194. if let text = textField.text, !text.isEmpty {
  195. var urlString = text
  196. if !text.starts(with: "www.") && !text.starts(with: "https://") {
  197. urlString = "https://www.google.com/search?q=\(text)"
  198. }
  199. if let url = URL(string: urlString.trimmingCharacters(in: .whitespacesAndNewlines)) {
  200. loadURLWithCookie(url: url)
  201. }
  202. }
  203. }
  204. func loadURLWithCookie(url: URL) {
  205. print("KACAU \(url)")
  206. var urlRequest = URLRequest(url: url)
  207. let customUserAgent = "Mozilla/5.0 (iPhone; CPU iPhone OS 16_6 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.5 Mobile/15E148 Safari/604.1 \(Utils.getUserAgent())"
  208. urlRequest.setValue(customUserAgent, forHTTPHeaderField: "User-Agent")
  209. if let cookies = HTTPCookieStorage.shared.cookies(for: url) {
  210. for cookie in cookies {
  211. webView.configuration.websiteDataStore.httpCookieStore.setCookie(cookie)
  212. }
  213. webView.load(urlRequest)
  214. }
  215. }
  216. public func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
  217. return true
  218. }
  219. public func scrollViewDidScroll(_ scrollView: UIScrollView) {
  220. }
  221. public func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
  222. if message.name == "sendQueueBNI" {
  223. guard let dict = message.body as? [String: AnyObject],
  224. let param1 = dict["param1"] as? String else {
  225. return
  226. }
  227. DispatchQueue.global().async {
  228. let _ = Nexilis.writeSync(message: CoreMessage_TMessageBank.queueBNI(service_id: param1), timeout: 30 * 1000)
  229. }
  230. }
  231. if message.name == "checkProfile" {
  232. guard let dict = message.body as? [String: AnyObject],
  233. let param1 = dict["param1"] as? String,
  234. let param2 = dict["param2"] as? String else {
  235. return
  236. }
  237. if Nexilis.checkIsChangePerson() {
  238. if param2 == "like" {
  239. self.webView.evaluateJavaScript("likeProduct('\(param1)',1,true);")
  240. } else if param2 == "comment" {
  241. self.webView.evaluateJavaScript("openComment('\(param1.split(separator: "|")[0])',\(param1.split(separator: "|")[1]),true);")
  242. } else if param2 == "report_user" {
  243. self.webView.evaluateJavaScript("reportUser('\(param1)',true);")
  244. } else if param2 == "report_content" {
  245. self.webView.evaluateJavaScript("reportContent('\(param1.split(separator: "|")[0])','\(param1.split(separator: "|")[1])',true);")
  246. } else if param2 == "block_user" {
  247. self.webView.evaluateJavaScript("blockUser('\(param1)',true);")
  248. } else if param2 == "follow_user" {
  249. self.webView.evaluateJavaScript("followUser('\(param1.split(separator: "|")[0])',\(param1.split(separator: "|")[1]),true);")
  250. } else if param2 == "homepage" || param2 == "gif" {
  251. self.webView.evaluateJavaScript("window.location.href = '\(param1)';")
  252. } else if param2 == "block_content" {
  253. self.webView.evaluateJavaScript("blockContent('\(param1)',true);")
  254. } else {
  255. self.webView.evaluateJavaScript("openNewPost(true);")
  256. }
  257. } else {
  258. self.webView.evaluateJavaScript("{if(pauseAll){pauseAll();}}")
  259. }
  260. } else if message.name == "setIsProductModalOpen" {
  261. guard let dict = message.body as? [String: AnyObject],
  262. let param1 = dict["param1"] as? Bool else {
  263. return
  264. }
  265. if param1 {
  266. if self.webView.scrollView.contentOffset.y < 0 { // Move tableView to top
  267. self.webView.scrollView.setContentOffset(CGPoint.zero, animated: true)
  268. }
  269. }
  270. } else if message.name == "toggleVoiceSearch" {
  271. if !isAllowSpeech {
  272. setupSpeech()
  273. } else {
  274. runVoice()
  275. }
  276. } else if message.name == "blockUser" {
  277. guard let dict = message.body as? [String: AnyObject],
  278. let param1 = dict["param1"] as? String,
  279. let param2 = dict["param2"] as? Bool else {
  280. return
  281. }
  282. if param2 {
  283. DispatchQueue.global().async {
  284. if let response = Nexilis.writeAndWait(message: CoreMessage_TMessageBank.getBlock(l_pin: param1)) {
  285. if response.isOk() {
  286. DispatchQueue.main.async {
  287. Database.shared.database?.inTransaction({ (fmdb, rollback) in
  288. do {
  289. _ = Database.shared.updateRecord(fmdb: fmdb, table: "BUDDY", cvalues: [
  290. "ex_block" : "1"
  291. ], _where: "f_pin = '\(param1)'")
  292. } catch {
  293. rollback.pointee = true
  294. print("Access database error: \(error.localizedDescription)")
  295. }
  296. })
  297. }
  298. }
  299. }
  300. }
  301. } else {
  302. DispatchQueue.global().async {
  303. if let response = Nexilis.writeAndWait(message: CoreMessage_TMessageBank.getUnBlock(l_pin: param1)) {
  304. if response.isOk() {
  305. DispatchQueue.main.async {
  306. Database.shared.database?.inTransaction({ (fmdb, rollback) in
  307. do {
  308. _ = Database.shared.updateRecord(fmdb: fmdb, table: "BUDDY", cvalues: [
  309. "ex_block" : "0"
  310. ], _where: "f_pin = '\(param1)'")
  311. } catch {
  312. rollback.pointee = true
  313. print("Access database error: \(error.localizedDescription)")
  314. }
  315. })
  316. }
  317. }
  318. }
  319. }
  320. }
  321. } else if message.name == "showAlert" {
  322. guard let dict = message.body as? [String: AnyObject],
  323. let param1 = dict["param1"] as? String else {
  324. return
  325. }
  326. self.view.makeToast(param1, duration: 3)
  327. } else if message.name == "blockUser" {
  328. guard let dict = message.body as? [String: AnyObject],
  329. let param1 = dict["param1"] as? String,
  330. let param2 = dict["param2"] as? Bool else {
  331. return
  332. }
  333. if param2 {
  334. DispatchQueue.global().async {
  335. if let response = Nexilis.writeAndWait(message: CoreMessage_TMessageBank.getBlock(l_pin: param1)) {
  336. if response.isOk() {
  337. DispatchQueue.main.async {
  338. Database.shared.database?.inTransaction({ (fmdb, rollback) in
  339. do {
  340. _ = Database.shared.updateRecord(fmdb: fmdb, table: "BUDDY", cvalues: [
  341. "ex_block" : "1"
  342. ], _where: "f_pin = '\(param1)'")
  343. } catch {
  344. rollback.pointee = true
  345. print("Access database error: \(error.localizedDescription)")
  346. }
  347. })
  348. }
  349. }
  350. }
  351. }
  352. } else {
  353. DispatchQueue.global().async {
  354. if let response = Nexilis.writeAndWait(message: CoreMessage_TMessageBank.getUnBlock(l_pin: param1)) {
  355. if response.isOk() {
  356. DispatchQueue.main.async {
  357. Database.shared.database?.inTransaction({ (fmdb, rollback) in
  358. do {
  359. _ = Database.shared.updateRecord(fmdb: fmdb, table: "BUDDY", cvalues: [
  360. "ex_block" : "0"
  361. ], _where: "f_pin = '\(param1)'")
  362. } catch {
  363. rollback.pointee = true
  364. print("Access database error: \(error.localizedDescription)")
  365. }
  366. })
  367. }
  368. }
  369. }
  370. }
  371. }
  372. } else if message.name == "successChangeTheme" {
  373. guard let dict = message.body as? [String: AnyObject],
  374. let param1 = dict["param1"] as? String,
  375. let param2 = dict["param2"] as? Bool else {
  376. return
  377. }
  378. Utils.setMyTheme(value: param1)
  379. Utils.setIsLoadThemeFromOther(value: true)
  380. Utils.resetValueSuperApp()
  381. if let jsonArray = try! JSONSerialization.jsonObject(with: param1.data(using: String.Encoding.utf8)!, options: JSONSerialization.ReadingOptions()) as? [AnyObject] {
  382. do {
  383. for json in jsonArray {
  384. if json["KEY"] as! String == "app_builder_url_webview_1" {
  385. Utils.setURLFirstTab(value: json["VALUE"] as! String)
  386. }
  387. if json["KEY"] as! String == "app_builder_url_webview_2" {
  388. Utils.setURLThirdTab(value: json["VALUE"] as! String)
  389. }
  390. if json["KEY"] as! String == "app_builder_url_webview_3" {
  391. Utils.setURLWv3(value: json["VALUE"] as! String)
  392. }
  393. if json["KEY"] as! String == "app_builder_url_webview_4" {
  394. Utils.setURLWv4(value: json["VALUE"] as! String)
  395. }
  396. if json["KEY"] as! String == "app_builder_url_webview_5" {
  397. Utils.setURLWv5(value: json["VALUE"] as! String)
  398. }
  399. if json["KEY"] as! String == "app_builder_url_webview_6" {
  400. Utils.setURLWv6(value: json["VALUE"] as! String)
  401. }
  402. if json["KEY"] as! String == "app_builder_custom_tab" {
  403. Utils.setCustomTab(cust: json["VALUE"] as! String)
  404. }
  405. if json["KEY"] as! String == "app_builder_icon_dock" {
  406. Utils.setIconDock(value: json["VALUE"] as! String)
  407. }
  408. if json["KEY"] as! String == "app_builder_background" {
  409. Utils.setBackground(value: json["VALUE"] as! String)
  410. }
  411. if json["KEY"] as! String == "app_builder_background_light" {
  412. Utils.setBackgroundLight(value: json["VALUE"] as! String)
  413. }
  414. if json["KEY"] as! String == "app_builder_background_dark" {
  415. Utils.setBackgroundDark(value: json["VALUE"] as! String)
  416. }
  417. if json["KEY"] as! String == "app_builder_background_1" {
  418. Utils.setBackgroundTab1(value: json["VALUE"] as! String)
  419. }
  420. if json["KEY"] as! String == "app_builder_background_2" {
  421. Utils.setBackgroundTab2(value: json["VALUE"] as! String)
  422. }
  423. if json["KEY"] as! String == "app_builder_background_3" {
  424. Utils.setBackgroundTab3(value: json["VALUE"] as! String)
  425. }
  426. if json["KEY"] as! String == "app_builder_background_4" {
  427. Utils.setBackgroundTab4(value: json["VALUE"] as! String)
  428. }
  429. if json["KEY"] as! String == "app_builder_background_5" {
  430. Utils.setBackgroundTab5(value: json["VALUE"] as! String)
  431. }
  432. if json["KEY"] as! String == "app_builder_background_6" {
  433. Utils.setBackgroundTab6(value: json["VALUE"] as! String)
  434. }
  435. if json["KEY"] as! String == "access_model" {
  436. Utils.setCpaasMode(mode: Int(json["VALUE"] as! String) ?? 0)
  437. }
  438. if json["KEY"] as! String == "app_builder_custom_buttons" {
  439. Utils.setCustomButtons(value: json["VALUE"] as! String)
  440. }
  441. if json["KEY"] as! String == "cpaas_icon" {
  442. Utils.setIconDock(value: json["VALUE"] as! String)
  443. }
  444. if json["KEY"] as! String == "tab1_icon" {
  445. Utils.setTab1Icon(value: json["VALUE"] as! String)
  446. }
  447. if json["KEY"] as! String == "tab2_icon" {
  448. Utils.setTab2Icon(value: json["VALUE"] as! String)
  449. }
  450. if json["KEY"] as! String == "tab3_icon" {
  451. Utils.setTab3Icon(value: json["VALUE"] as! String)
  452. }
  453. if json["KEY"] as! String == "tab4_icon" {
  454. Utils.setTab4Icon(value: json["VALUE"] as! String)
  455. }
  456. if json["KEY"] as! String == "tab5_icon" {
  457. Utils.setTab5Icon(value: json["VALUE"] as! String)
  458. }
  459. if json["KEY"] as! String == "tab6_icon" {
  460. Utils.setTab6Icon(value: json["VALUE"] as! String)
  461. }
  462. if json["KEY"] as! String == "app_builder_button_icon" {
  463. Utils.setButtonIcon(value: json["VALUE"] as! String)
  464. }
  465. if json["KEY"] as! String == "reverse_tab_color" {
  466. Utils.setReverseTab(value: json["VALUE"] as! String)
  467. }
  468. if json["KEY"] as! String == "icon_size" {
  469. Utils.setIconDockSize(value: json["VALUE"] as! String)
  470. }
  471. if json["KEY"] as! String == "app_id" {
  472. changeIconApp(appId: json["VALUE"] as! String)
  473. }
  474. }
  475. } catch {
  476. }
  477. }
  478. Database.shared.database?.inTransaction({ fmdb, rollback in
  479. do {
  480. _ = Database.shared.deleteRecord(fmdb: fmdb, table: "GROUPZ", _where: "")
  481. _ = Database.shared.deleteRecord(fmdb: fmdb, table: "GROUPZ_MEMBER", _where: "")
  482. _ = Database.shared.deleteRecord(fmdb: fmdb, table: "DISCUSSION_FORUM", _where: "")
  483. _ = Nexilis.write(message: CoreMessage_TMessageBank.getPostRegistration(p_pin: User.getMyPin() ?? ""))
  484. } catch {
  485. rollback.pointee = true
  486. print("Access database error: \(error.localizedDescription)")
  487. }
  488. })
  489. let alert = LibAlertController(title: "Successfully changed".localized(), message: "Please open the app again to see the changes".localized(), preferredStyle: .alert)
  490. alert.addAction(UIAlertAction(title: "OK".localized(), style: .default, handler: {(_) in
  491. exit(0)
  492. }))
  493. self.present(alert, animated: true, completion: nil)
  494. } else if message.name == "finishForm" {
  495. if self.webView.canGoBack {
  496. self.webView.goBack()
  497. } else {
  498. self.dismiss(animated: true)
  499. }
  500. } else if message.name == "shareText" {
  501. guard let dict = message.body as? [String: AnyObject],
  502. let param1 = dict["param1"] as? String else {
  503. return
  504. }
  505. if loadingURL {
  506. return
  507. }
  508. let activityViewController = UIActivityViewController(activityItems: [param1], applicationActivities: nil)
  509. self.present(activityViewController, animated: true, completion: nil)
  510. } else if message.name == "openGalleryiOS" {
  511. guard let dict = message.body as? [String: AnyObject],
  512. let param1 = dict["param1"] as? Int else {
  513. return
  514. }
  515. indexImageVideoWv = param1
  516. let alertController = LibAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
  517. if let action = self.actionImageVideo(for: "image", title: "Choose Photo".localized()) {
  518. alertController.addAction(action)
  519. }
  520. if let action = self.actionImageVideo(for: "video", title: "Choose Video".localized()) {
  521. alertController.addAction(action)
  522. }
  523. alertController.addAction(UIAlertAction(title: "Cancel".localized(), style: .cancel, handler: nil))
  524. self.present(alertController, animated: true)
  525. }
  526. }
  527. private func actionImageVideo(for type: String, title: String) -> UIAlertAction? {
  528. return UIAlertAction(title: title, style: .default) { [unowned self] _ in
  529. switch type {
  530. case "image":
  531. imageVideoPicker.present(source: .imageAlbum)
  532. case "video":
  533. imageVideoPicker.present(source: .videoAlbum)
  534. default:
  535. imageVideoPicker.present(source: .imageAlbum)
  536. }
  537. }
  538. }
  539. public func didSelect(imagevideo: Any?) {
  540. if imagevideo != nil {
  541. let imageData = imagevideo! as! [UIImagePickerController.InfoKey : Any]
  542. if (imageData[.mediaType] as! String == "public.image") {
  543. let compressedImage = (imageData[.originalImage] as! UIImage).pngData()!
  544. let base64String = compressedImage.base64EncodedString()
  545. let base64ToWeb = "data:image/jpeg;base64,\(base64String)"
  546. webView.evaluateJavaScript("loadFromMobile('\(base64ToWeb)',\(indexImageVideoWv))") { (result, error) in
  547. if let error = error {
  548. print("Error executing JavaScript: \(error)")
  549. }
  550. }
  551. } else {
  552. guard var dataVideo = try? Data(contentsOf: imageData[.mediaURL] as! URL) else {
  553. return
  554. }
  555. let sizeOfVideo = Double(dataVideo.count / 1048576)
  556. if (sizeOfVideo > 10.0) {
  557. let compressedURL = NSURL.fileURL(withPath: NSTemporaryDirectory() + UUID().uuidString + ".mp4")
  558. compressVideo(inputURL: imageData[.mediaURL] as! URL,
  559. outputURL: compressedURL) { exportSession in
  560. guard let session = exportSession else {
  561. return
  562. }
  563. switch session.status {
  564. case .unknown:
  565. break
  566. case .waiting:
  567. break
  568. case .exporting:
  569. break
  570. case .completed:
  571. guard let compressedData = try? Data(contentsOf: compressedURL) else {
  572. return
  573. }
  574. dataVideo = compressedData
  575. case .failed:
  576. break
  577. case .cancelled:
  578. break
  579. @unknown default:
  580. break
  581. }
  582. }
  583. }
  584. let base64String = dataVideo.base64EncodedString()
  585. let base64ToWeb = "data:video/mp4;base64,\(base64String)"
  586. webView.evaluateJavaScript("loadFromMobile('\(base64ToWeb)',\(indexImageVideoWv))") { (result, error) in
  587. if let error = error {
  588. print("Error executing JavaScript: \(error)")
  589. }
  590. }
  591. }
  592. }
  593. }
  594. func compressVideo(inputURL: URL,
  595. outputURL: URL,
  596. handler:@escaping (_ exportSession: AVAssetExportSession?) -> Void) {
  597. let urlAsset = AVURLAsset(url: inputURL, options: nil)
  598. guard let exportSession = AVAssetExportSession(asset: urlAsset,
  599. presetName: AVAssetExportPresetMediumQuality) else {
  600. handler(nil)
  601. return
  602. }
  603. exportSession.outputURL = outputURL
  604. exportSession.outputFileType = .mp4
  605. exportSession.exportAsynchronously {
  606. handler(exportSession)
  607. }
  608. }
  609. func changeIconApp(appId: String) {
  610. let digisalesKey = "1694457466830"
  611. let nuKey = "1693550500075"
  612. let iknKey = "1693542580518"
  613. let diginetsKey = "1693456149709"
  614. let biKey = "1692873053159"
  615. let nxcookKey = "1692863737543"
  616. let nxsportKey = "1692863037019"
  617. let bpkhKey = "1711023277251"
  618. let disiniKey = "1711024221024"
  619. let gudegKey = "1712052403416"
  620. let kmiKey = "1713407687550"
  621. switch appId {
  622. case digisalesKey:
  623. UIApplication.shared.setAlternateIconName("digisales_icon")
  624. case nuKey:
  625. UIApplication.shared.setAlternateIconName("nu_icon")
  626. case iknKey:
  627. UIApplication.shared.setAlternateIconName("ikn_icon")
  628. case diginetsKey:
  629. UIApplication.shared.setAlternateIconName("diginets_icon")
  630. case biKey:
  631. UIApplication.shared.setAlternateIconName("bi_icon")
  632. case nxcookKey:
  633. UIApplication.shared.setAlternateIconName("nxcook_icon")
  634. case nxsportKey:
  635. UIApplication.shared.setAlternateIconName("nxsport_icon")
  636. case bpkhKey:
  637. UIApplication.shared.setAlternateIconName("bpkh_icon")
  638. case disiniKey:
  639. UIApplication.shared.setAlternateIconName("disini_icon")
  640. case gudegKey:
  641. UIApplication.shared.setAlternateIconName("gudeg_icon")
  642. case kmiKey:
  643. UIApplication.shared.setAlternateIconName("kmi_icon")
  644. default:
  645. UIApplication.shared.setAlternateIconName(nil)
  646. }
  647. }
  648. func setupSpeech() {
  649. self.speechRecognizer?.delegate = self
  650. SFSpeechRecognizer.requestAuthorization { (authStatus) in
  651. var isButtonEnabled = false
  652. switch authStatus {
  653. case .authorized:
  654. isButtonEnabled = true
  655. case .denied:
  656. isButtonEnabled = false
  657. //print("User denied access to speech recognition")
  658. case .restricted:
  659. isButtonEnabled = false
  660. //print("Speech recognition restricted on this device")
  661. case .notDetermined:
  662. isButtonEnabled = false
  663. //print("Speech recognition not yet authorized")
  664. @unknown default:
  665. isButtonEnabled = false
  666. }
  667. OperationQueue.main.addOperation() {
  668. self.isAllowSpeech = isButtonEnabled
  669. if isButtonEnabled {
  670. SecureUserDefaults.shared.set(isButtonEnabled, forKey: "allowSpeech")
  671. self.runVoice()
  672. }
  673. }
  674. }
  675. }
  676. func runVoice() {
  677. if !audioEngine.isRunning {
  678. alertController = LibAlertController(title: "Start Recording".localized(), message: "Say something, I'm listening!".localized(), preferredStyle: .alert)
  679. self.present(alertController, animated: true)
  680. self.webView.evaluateJavaScript("toggleVoiceButton(true)")
  681. self.startRecording()
  682. }
  683. }
  684. func startRecording() {
  685. // Clear all previous session data and cancel task
  686. if recognitionTask != nil {
  687. recognitionTask?.cancel()
  688. recognitionTask = nil
  689. }
  690. // Create instance of audio session to record voice
  691. let audioSession = AVAudioSession.sharedInstance()
  692. do {
  693. try audioSession.setCategory(AVAudioSession.Category.record, mode: .default, options: [])
  694. try audioSession.setMode(AVAudioSession.Mode.measurement)
  695. try audioSession.setActive(true, options: .notifyOthersOnDeactivation)
  696. } catch {
  697. //print("audioSession properties weren't set because of an error.")
  698. }
  699. self.recognitionRequest = SFSpeechAudioBufferRecognitionRequest()
  700. let inputNode = audioEngine.inputNode
  701. guard let recognitionRequest = recognitionRequest else {
  702. fatalError("Unable to create an SFSpeechAudioBufferRecognitionRequest object")
  703. }
  704. recognitionRequest.shouldReportPartialResults = true
  705. self.recognitionTask = speechRecognizer?.recognitionTask(with: recognitionRequest, resultHandler: { (result, error) in
  706. var isFinal = false
  707. var text = ""
  708. if result != nil {
  709. text = result?.bestTranscription.formattedString ?? ""
  710. isFinal = (result?.isFinal)!
  711. self.alertController.dismiss(animated: true)
  712. self.audioEngine.stop()
  713. self.recognitionRequest?.endAudio()
  714. } else {
  715. self.alertController.dismiss(animated: true)
  716. }
  717. if error != nil || isFinal {
  718. if error == nil {
  719. self.webView.evaluateJavaScript("toggleVoiceButton(false)")
  720. self.webView.evaluateJavaScript("submitVoiceSearch('\(text)')")
  721. } else {
  722. self.audioEngine.stop()
  723. self.recognitionRequest?.endAudio()
  724. }
  725. inputNode.removeTap(onBus: 0)
  726. self.recognitionRequest = nil
  727. self.recognitionTask = nil
  728. self.isAllowSpeech = true
  729. }
  730. })
  731. let recordingFormat = inputNode.outputFormat(forBus: 0)
  732. inputNode.installTap(onBus: 0, bufferSize: 1024, format: recordingFormat) { (buffer, when) in
  733. self.recognitionRequest?.append(buffer)
  734. }
  735. self.audioEngine.prepare()
  736. do {
  737. try self.audioEngine.start()
  738. } catch {
  739. //print("audioEngine couldn't start because of an error.")
  740. }
  741. }
  742. @objc func reloadWebView(_ sender: UIRefreshControl) {
  743. webView.reload()
  744. sender.endRefreshing()
  745. }
  746. public func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping @MainActor (WKNavigationActionPolicy) -> Void) {
  747. guard let url = navigationAction.request.url else {
  748. decisionHandler(.cancel)
  749. return
  750. }
  751. if loadingURL {
  752. decisionHandler(.cancel)
  753. return
  754. }
  755. loadingURL = true
  756. if allowedURLs.contains(url.absoluteString) {
  757. loadingURL = false
  758. decisionHandler(.allow)
  759. return
  760. }
  761. validateSSLCertificate(url: url) { isValid in
  762. if isValid {
  763. self.allowedURLs.insert(url.absoluteString)
  764. self.loadingURL = false
  765. decisionHandler(.allow)
  766. } else {
  767. let host = url.host ?? ""
  768. DispatchQueue.main.async {
  769. var messageText = "You're about to access a website that is not currently trusted by your Nexilis Browser. This website's security certificate is not recognized.\n\nDo you wish to proceed to <<domain>> and trust the website's security certificate?\n\nNote: Adding a website to the trusted list may increase your risk of security vulnerability".localized()
  770. messageText = messageText.replacingOccurrences(of: "<<domain>>", with: host)
  771. let alert = UIAlertController(title: "Warning Unknown Url!".localized(),
  772. message: messageText,
  773. preferredStyle: .alert)
  774. let yesAction = UIAlertAction(title: "Yes", style: .default) { _ in
  775. let storedCertificate = Utils.getCertificatePinningWebview()
  776. if let jsonData = storedCertificate.data(using: .utf8),
  777. let certJson = try? JSONSerialization.jsonObject(with: jsonData, options: []) as? [String: String] {
  778. var certJson = certJson
  779. certJson[host] = self.blockedCertificate
  780. if let jsonData = try? JSONSerialization.data(withJSONObject: certJson, options: []),
  781. let jsonString = String(data: jsonData, encoding: .utf8) {
  782. Utils.setCertificatePinningWebview(value: jsonString)
  783. }
  784. }
  785. self.allowedURLs.insert(url.absoluteString)
  786. self.loadingURL = false
  787. decisionHandler(.allow)
  788. }
  789. let noAction = UIAlertAction(title: "No", style: .cancel) { _ in
  790. self.loadingURL = false
  791. decisionHandler(.cancel)
  792. }
  793. alert.addAction(yesAction)
  794. alert.addAction(noAction)
  795. self.present(alert, animated: true, completion: nil)
  796. }
  797. }
  798. }
  799. }
  800. private func validateSSLCertificate(url: URL, completion: @escaping (Bool) -> Void) {
  801. let session = URLSession(configuration: .ephemeral, delegate: self, delegateQueue: nil)
  802. let request = URLRequest(url: url)
  803. let task = session.dataTask(with: request) { _, response, error in
  804. if let error = error {
  805. completion(false)
  806. return
  807. }
  808. completion(true)
  809. }
  810. task.resume()
  811. }
  812. }
  813. extension BNIBookingWebView: URLSessionDelegate {
  814. public func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
  815. guard let serverTrust = challenge.protectionSpace.serverTrust else {
  816. completionHandler(.cancelAuthenticationChallenge, nil)
  817. return
  818. }
  819. if let publicKeyHash = extractPublicKeyHash(from: serverTrust) {
  820. let domain = challenge.protectionSpace.host
  821. let storedCertificate = Utils.getCertificatePinningWebview()
  822. if let jsonData = storedCertificate.data(using: .utf8),
  823. let certJson = try? JSONSerialization.jsonObject(with: jsonData, options: []) as? [String: String] {
  824. if publicKeyHash == certJson[domain] {
  825. completionHandler(.useCredential, URLCredential(trust: serverTrust))
  826. } else {
  827. blockedCertificate = publicKeyHash
  828. completionHandler(.cancelAuthenticationChallenge, nil)
  829. }
  830. }
  831. } else {
  832. completionHandler(.cancelAuthenticationChallenge, nil)
  833. }
  834. }
  835. func extractPublicKeyHash(from serverTrust: SecTrust) -> String? {
  836. guard let certificate = SecTrustGetCertificateAtIndex(serverTrust, 0) else { return nil }
  837. guard let publicKey = SecCertificateCopyKey(certificate) else { return nil }
  838. var error: Unmanaged<CFError>?
  839. guard let publicKeyData = SecKeyCopyExternalRepresentation(publicKey, &error) as Data? else {
  840. return nil
  841. }
  842. // Compute SHA-256 hash
  843. var hash = [UInt8](repeating: 0, count: Int(CC_SHA256_DIGEST_LENGTH))
  844. publicKeyData.withUnsafeBytes {
  845. _ = CC_SHA256($0.baseAddress, CC_LONG(publicKeyData.count), &hash)
  846. }
  847. let hashData = Data(hash)
  848. let base64Hash = hashData.base64EncodedString()
  849. return base64Hash
  850. }
  851. }