APIS.swift 91 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561
  1. //
  2. // APIS.swift
  3. // NexilisLite
  4. //
  5. // Created by Akhmad Al Qindi Irsyam on 05/05/23.
  6. //
  7. import Foundation
  8. import UIKit
  9. import FMDB
  10. import NotificationBannerSwift
  11. import Toast_Swift
  12. import nuSDKService
  13. import AVFoundation
  14. import AVKit
  15. import Intents
  16. public class APIS: NSObject {
  17. public static func connect(appName: String, apiKey: String, delegate: ConnectDelegate, showButton: Bool = true, fromMAB: Bool = false) {
  18. APIS.appNm = appName.trimmingCharacters(in: .whitespacesAndNewlines)
  19. Nexilis.connect(apiKey: apiKey, delegate: delegate, showButton: showButton, fromMAB: fromMAB)
  20. }
  21. public static func getTotalCounter() -> Int32 {
  22. var counter: Int32?
  23. Database.shared.database?.inTransaction({ (fmdb, rollback) in
  24. do {
  25. if let cursor = Database.shared.getRecords(fmdb: fmdb, query: "SELECT SUM(counter) FROM MESSAGE_SUMMARY"), cursor.next() {
  26. counter = cursor.int(forColumnIndex: 0)
  27. cursor.close()
  28. }
  29. } catch {
  30. rollback.pointee = true
  31. print("Access database error: \(error.localizedDescription)")
  32. }
  33. })
  34. return counter ?? 0
  35. }
  36. private static func showChangeProfile() {
  37. let alert = LibAlertController(title: "Change Profile".localized(), message: "You must change your name to use this feature".localized(), preferredStyle: .alert)
  38. alert.addAction(UIAlertAction(title: "OK".localized(), style: UIAlertAction.Style.default, handler: {(_) in
  39. let controller = AppStoryBoard.Palio.instance.instantiateViewController(withIdentifier: "signupsignin") as! SignUpSignIn
  40. controller.forceLogin = true
  41. let navigationController = CustomNavigationController(rootViewController: controller)
  42. navigationController.defaultStyle()
  43. if UIApplication.shared.visibleViewController?.navigationController != nil {
  44. UIApplication.shared.visibleViewController?.navigationController?.present(navigationController, animated: true, completion: nil)
  45. } else {
  46. UIApplication.shared.visibleViewController?.present(navigationController, animated: true, completion: nil)
  47. }
  48. }))
  49. if UIApplication.shared.visibleViewController?.navigationController != nil {
  50. UIApplication.shared.visibleViewController?.navigationController?.present(alert, animated: true, completion: nil)
  51. } else {
  52. UIApplication.shared.visibleViewController?.present(alert, animated: true, completion: nil)
  53. }
  54. }
  55. public static func openContactCenter(media: Int? = nil, category: Int? = nil) {
  56. let isChangeProfile = Utils.getSetProfile()
  57. if !isChangeProfile {
  58. APIS.showChangeProfile()
  59. return
  60. }
  61. if User.isCallCenter(userType: (User.getData(pin: User.getMyPin())?.userType)!) {
  62. let controller = AppStoryBoard.Palio.instance.instantiateViewController(withIdentifier: "myHistoryCC") as! HistoryCCViewController
  63. controller.isOfficer = true
  64. controller.fromAPI = true
  65. let navigationController = CustomNavigationController(rootViewController: controller)
  66. navigationController.setNavigationBarHidden(false, animated: false)
  67. navigationController.navigationBar.isTranslucent = false
  68. navigationController.defaultStyle()
  69. if UIApplication.shared.visibleViewController?.navigationController != nil {
  70. UIApplication.shared.visibleViewController?.navigationController?.present(navigationController, animated: true, completion: nil)
  71. } else {
  72. UIApplication.shared.visibleViewController?.present(navigationController, animated: true, completion: nil)
  73. }
  74. } else {
  75. if media != nil || (media == nil && category != nil) {
  76. if media == nil || media! < 0 || media! > 2 {
  77. UIApplication.shared.visibleViewController?.view.makeToast("108:Invalid Contact Center media parameter (0:Chat, 1:Audio Call, 2:Video Call)".localized(), duration: 3)
  78. return
  79. }
  80. }
  81. if category != nil {
  82. if category != 0 {
  83. let service = CategoryCC.getDataFromServiceId(service_id: "\(category!)")
  84. if service == nil {
  85. UIApplication.shared.visibleViewController?.view.makeToast("109:Invalid Contact Center category parameter".localized(), duration: 3)
  86. return
  87. }
  88. let serviceChilds = CategoryCC.getDatafromParent(parent: service!.service_id)
  89. if serviceChilds.count > 0 {
  90. UIApplication.shared.visibleViewController?.view.makeToast("109:Invalid Contact Center category parameter".localized(), duration: 3)
  91. return
  92. }
  93. }
  94. }
  95. let isWaitingRequestCC: Bool = SecureUserDefaults.shared.value(forKey: "waitingRequestCC") ?? false
  96. if isWaitingRequestCC {
  97. let imageView = UIImageView(image: UIImage(systemName: "info.circle"))
  98. imageView.tintColor = .white
  99. let banner = FloatingNotificationBanner(title: "You have requested Call Center, please wait for response.".localized(), subtitle: nil, titleFont: UIFont.systemFont(ofSize: 16), titleColor: nil, titleTextAlign: .left, subtitleFont: nil, subtitleColor: nil, subtitleTextAlign: nil, leftView: imageView, rightView: nil, style: .info, colors: nil, iconPosition: .center)
  100. banner.show()
  101. return
  102. }
  103. let controller = AppStoryBoard.Palio.instance.instantiateViewController(identifier: "editorPersonalVC") as! EditorPersonal
  104. controller.isContactCenter = true
  105. if media != nil {
  106. controller.isDirectCC = true
  107. controller.channelContactCenter = "\(media!)"
  108. controller.serviceIdCC = category == nil ? "" : "\(category!)"
  109. }
  110. let navigationController = CustomNavigationController(rootViewController: controller)
  111. navigationController.defaultStyle()
  112. if UIApplication.shared.visibleViewController?.navigationController != nil {
  113. UIApplication.shared.visibleViewController?.navigationController?.present(navigationController, animated: true, completion: nil)
  114. } else {
  115. UIApplication.shared.visibleViewController?.present(navigationController, animated: true, completion: nil)
  116. }
  117. }
  118. }
  119. public static func openUrl(url: String) {
  120. let isChangeProfile = Utils.getSetProfile()
  121. if !isChangeProfile {
  122. APIS.showChangeProfile()
  123. return
  124. }
  125. let controller = BNIBookingWebView()
  126. controller.customUrl = url
  127. if UIApplication.shared.visibleViewController?.navigationController != nil {
  128. UIApplication.shared.visibleViewController?.navigationController?.present(controller, animated: true, completion: nil)
  129. } else {
  130. UIApplication.shared.visibleViewController?.present(controller, animated: true, completion: nil)
  131. }
  132. }
  133. public static func openNotificationCenter() {
  134. let isChangeProfile = Utils.getSetProfile()
  135. if !isChangeProfile {
  136. APIS.showChangeProfile()
  137. return
  138. }
  139. let controller = HistoryBroadcastViewController()
  140. let navigationController = CustomNavigationController(rootViewController: controller)
  141. navigationController.defaultStyle()
  142. if UIApplication.shared.visibleViewController?.navigationController != nil {
  143. UIApplication.shared.visibleViewController?.navigationController?.present(navigationController, animated: true, completion: nil)
  144. } else {
  145. UIApplication.shared.visibleViewController?.present(navigationController, animated: true, completion: nil)
  146. }
  147. }
  148. public static func openChat() {
  149. let isChangeProfile = Utils.getSetProfile()
  150. if !isChangeProfile {
  151. APIS.showChangeProfile()
  152. return
  153. }
  154. let navigationController = AppStoryBoard.Palio.instance.instantiateViewController(withIdentifier: "contactChatNav") as! UINavigationController
  155. Utils.addBackground(view: navigationController.view)
  156. let vc = navigationController.topViewController as! ContactChatViewController
  157. vc.noUCList = true
  158. navigationController.defaultStyle()
  159. if UIApplication.shared.visibleViewController?.navigationController != nil {
  160. UIApplication.shared.visibleViewController?.navigationController?.present(navigationController, animated: true, completion: nil)
  161. } else {
  162. UIApplication.shared.visibleViewController?.present(navigationController, animated: true, completion: nil)
  163. }
  164. }
  165. public static func openSmartChatbot() {
  166. let isChangeProfile = Utils.getSetProfile()
  167. if !isChangeProfile {
  168. APIS.showChangeProfile()
  169. return
  170. }
  171. let smartChatVC = AppStoryBoard.Palio.instance.instantiateViewController(identifier: "chatGptVC") as! ChatGPTBotView
  172. smartChatVC.hidesBottomBarWhenPushed = true
  173. let navigationController = CustomNavigationController(rootViewController: smartChatVC)
  174. navigationController.defaultStyle()
  175. if UIApplication.shared.visibleViewController?.navigationController != nil {
  176. UIApplication.shared.visibleViewController?.navigationController?.present(navigationController, animated: true, completion: nil)
  177. } else {
  178. UIApplication.shared.visibleViewController?.present(navigationController, animated: true, completion: nil)
  179. }
  180. }
  181. public static func startChat(name: String) {
  182. if name.isEmpty {
  183. UIApplication.shared.visibleViewController?.view.makeToast("92:Username is empty".localized(), duration: 2)
  184. return
  185. }
  186. let user = User.getDataFromNameCanNil(name: name)
  187. if user == nil {
  188. UIApplication.shared.visibleViewController?.view.makeToast("91:Invalid name or you must add Username to your contact first".localized(), duration: 3)
  189. return
  190. }
  191. let editorPersonalVC = AppStoryBoard.Palio.instance.instantiateViewController(identifier: "editorPersonalVC") as! EditorPersonal
  192. editorPersonalVC.hidesBottomBarWhenPushed = true
  193. editorPersonalVC.unique_l_pin = user!.pin
  194. editorPersonalVC.fromNotification = true
  195. let navigationController = CustomNavigationController(rootViewController: editorPersonalVC)
  196. navigationController.modalPresentationStyle = .fullScreen
  197. navigationController.navigationBar.tintColor = .white
  198. navigationController.navigationBar.barTintColor = UIApplication.shared.visibleViewController?.traitCollection.userInterfaceStyle == .dark ? .blackDarkMode : .mainColor
  199. navigationController.navigationBar.isTranslucent = false
  200. navigationController.navigationBar.overrideUserInterfaceStyle = .dark
  201. navigationController.navigationBar.barStyle = .black
  202. let cancelButtonAttributes: [NSAttributedString.Key: Any] = [NSAttributedString.Key.foregroundColor: UIColor.white, NSAttributedString.Key.font : UIFont.systemFont(ofSize: 16)]
  203. UIBarButtonItem.appearance().setTitleTextAttributes(cancelButtonAttributes, for: .normal)
  204. let textAttributes = [NSAttributedString.Key.foregroundColor:UIColor.white]
  205. navigationController.navigationBar.titleTextAttributes = textAttributes
  206. if UIApplication.shared.visibleViewController?.navigationController != nil {
  207. UIApplication.shared.visibleViewController?.navigationController?.present(navigationController, animated: true, completion: nil)
  208. } else {
  209. UIApplication.shared.visibleViewController?.present(navigationController, animated: true, completion: nil)
  210. }
  211. }
  212. public static func openCall() {
  213. let isChangeProfile = Utils.getSetProfile()
  214. if !isChangeProfile {
  215. APIS.showChangeProfile()
  216. return
  217. }
  218. let callContact = AppStoryBoard.Palio.instance.instantiateViewController(withIdentifier: "contactSID")
  219. let navigationController = CustomNavigationController(rootViewController: callContact)
  220. navigationController.defaultStyle()
  221. if UIApplication.shared.visibleViewController?.navigationController != nil {
  222. UIApplication.shared.visibleViewController?.navigationController?.present(navigationController, animated: true, completion: nil)
  223. } else {
  224. UIApplication.shared.visibleViewController?.present(navigationController, animated: true, completion: nil)
  225. }
  226. }
  227. public static func openStreaming() {
  228. let isChangeProfile = Utils.getSetProfile()
  229. if !isChangeProfile {
  230. APIS.showChangeProfile()
  231. return
  232. }
  233. let navigationController = CustomNavigationController(rootViewController: QmeraCreateStreamingViewController())
  234. navigationController.defaultStyle()
  235. if UIApplication.shared.visibleViewController?.navigationController != nil {
  236. UIApplication.shared.visibleViewController?.navigationController?.present(navigationController, animated: true, completion: nil)
  237. } else {
  238. UIApplication.shared.visibleViewController?.present(navigationController, animated: true, completion: nil)
  239. }
  240. }
  241. public static func openConference() {
  242. let isChangeProfile = Utils.getSetProfile()
  243. if !isChangeProfile {
  244. APIS.showChangeProfile()
  245. return
  246. }
  247. let navigationController = CustomNavigationController(rootViewController: CreateSeminarViewController())
  248. navigationController.defaultStyle()
  249. if UIApplication.shared.visibleViewController?.navigationController != nil {
  250. UIApplication.shared.visibleViewController?.navigationController?.present(navigationController, animated: true, completion: nil)
  251. } else {
  252. UIApplication.shared.visibleViewController?.present(navigationController, animated: true, completion: nil)
  253. }
  254. }
  255. public static func openAudioCall() {
  256. let isChangeProfile = Utils.getSetProfile()
  257. if !isChangeProfile {
  258. APIS.showChangeProfile()
  259. return
  260. }
  261. let callContact = AppStoryBoard.Palio.instance.instantiateViewController(withIdentifier: "contactSID") as! ContactCallViewController
  262. callContact.onlyAudioOrVideo = 1
  263. let navigationController = CustomNavigationController(rootViewController: callContact)
  264. navigationController.defaultStyle()
  265. if UIApplication.shared.visibleViewController?.navigationController != nil {
  266. UIApplication.shared.visibleViewController?.navigationController?.present(navigationController, animated: true, completion: nil)
  267. } else {
  268. UIApplication.shared.visibleViewController?.present(navigationController, animated: true, completion: nil)
  269. }
  270. }
  271. public static func startAudioCall(name: String) {
  272. if name.isEmpty {
  273. UIApplication.shared.visibleViewController?.view.makeToast("92:Username is empty".localized(), duration: 3)
  274. return
  275. }
  276. let user = User.getDataFromNameCanNil(name: name)
  277. if user == nil {
  278. UIApplication.shared.visibleViewController?.view.makeToast("91:Invalid name or you must add Username to your contact first".localized(), duration: 3)
  279. return
  280. }
  281. if !CheckConnection.isConnectedToNetwork() {
  282. let imageView = UIImageView(image: UIImage(systemName: "xmark.circle.fill"))
  283. imageView.tintColor = .white
  284. let banner = FloatingNotificationBanner(title: "Check your connection".localized(), subtitle: nil, titleFont: UIFont.systemFont(ofSize: 16), titleColor: nil, titleTextAlign: .left, subtitleFont: nil, subtitleColor: nil, subtitleTextAlign: nil, leftView: imageView, rightView: nil, style: .danger, colors: nil, iconPosition: .center)
  285. banner.show()
  286. return
  287. }
  288. let controller = QmeraAudioViewController()
  289. controller.user = user
  290. controller.isOutgoing = true
  291. controller.modalPresentationStyle = .overFullScreen
  292. if UIApplication.shared.visibleViewController?.navigationController != nil {
  293. UIApplication.shared.visibleViewController?.navigationController?.present(controller, animated: true, completion: nil)
  294. } else {
  295. UIApplication.shared.visibleViewController?.present(controller, animated: true, completion: nil)
  296. }
  297. }
  298. public static func openVideoCall() {
  299. let isChangeProfile = Utils.getSetProfile()
  300. if !isChangeProfile {
  301. APIS.showChangeProfile()
  302. return
  303. }
  304. let callContact = AppStoryBoard.Palio.instance.instantiateViewController(withIdentifier: "contactSID") as! ContactCallViewController
  305. callContact.onlyAudioOrVideo = 2
  306. let navigationController = CustomNavigationController(rootViewController: callContact)
  307. navigationController.defaultStyle()
  308. if UIApplication.shared.visibleViewController?.navigationController != nil {
  309. UIApplication.shared.visibleViewController?.navigationController?.present(navigationController, animated: true, completion: nil)
  310. } else {
  311. UIApplication.shared.visibleViewController?.present(navigationController, animated: true, completion: nil)
  312. }
  313. }
  314. public static func startVideoCall(name: String) {
  315. if name.isEmpty {
  316. UIApplication.shared.visibleViewController?.view.makeToast("92:Username is empty".localized(), duration: 3)
  317. return
  318. }
  319. let user = User.getDataFromNameCanNil(name: name)
  320. if user == nil {
  321. UIApplication.shared.visibleViewController?.view.makeToast("91:Invalid name or you must add Username to your contact first".localized(), duration: 3)
  322. return
  323. }
  324. if !CheckConnection.isConnectedToNetwork() {
  325. let imageView = UIImageView(image: UIImage(systemName: "xmark.circle.fill"))
  326. imageView.tintColor = .white
  327. let banner = FloatingNotificationBanner(title: "Check your connection".localized(), subtitle: nil, titleFont: UIFont.systemFont(ofSize: 16), titleColor: nil, titleTextAlign: .left, subtitleFont: nil, subtitleColor: nil, subtitleTextAlign: nil, leftView: imageView, rightView: nil, style: .danger, colors: nil, iconPosition: .center)
  328. banner.show()
  329. return
  330. }
  331. let videoVC = AppStoryBoard.Palio.instance.instantiateViewController(withIdentifier: "videoVCQmera") as! QmeraVideoViewController
  332. var data: [String: String?] = [:]
  333. data["f_pin"] = user!.pin
  334. data["name"] = user!.fullName
  335. data["picture"] = user!.thumb
  336. data["isOfficial"] = user!.official
  337. data["deviceId"] = user!.device_id
  338. data["isOffline"] = user!.offline_mode
  339. data["user_type"] = user!.userType
  340. videoVC.dataPerson.append(data)
  341. videoVC.isPresent = true
  342. videoVC.modalPresentationStyle = .overFullScreen
  343. if UIApplication.shared.visibleViewController?.navigationController != nil {
  344. UIApplication.shared.visibleViewController?.navigationController?.present(videoVC, animated: true, completion: nil)
  345. } else {
  346. UIApplication.shared.visibleViewController?.present(videoVC, animated: true, completion: nil)
  347. }
  348. }
  349. public static func openBroadcastForm() {
  350. let isChangeProfile = Utils.getSetProfile()
  351. if !isChangeProfile {
  352. APIS.showChangeProfile()
  353. return
  354. }
  355. let controller = AppStoryBoard.Palio.instance.instantiateViewController(identifier: "broadcastNav")
  356. if UIApplication.shared.visibleViewController?.navigationController != nil {
  357. UIApplication.shared.visibleViewController?.navigationController?.present(controller, animated: true, completion: nil)
  358. } else {
  359. UIApplication.shared.visibleViewController?.present(controller, animated: true, completion: nil)
  360. }
  361. }
  362. public static func openConversation() {
  363. let isChangeProfile = Utils.getSetProfile()
  364. if !isChangeProfile {
  365. APIS.showChangeProfile()
  366. return
  367. }
  368. let navigationController = AppStoryBoard.Palio.instance.instantiateViewController(withIdentifier: "contactChatNav") as! UINavigationController
  369. Utils.addBackground(view: navigationController.view)
  370. navigationController.defaultStyle()
  371. if UIApplication.shared.visibleViewController?.navigationController != nil {
  372. UIApplication.shared.visibleViewController?.navigationController?.present(navigationController, animated: true, completion: nil)
  373. } else {
  374. UIApplication.shared.visibleViewController?.present(navigationController, animated: true, completion: nil)
  375. }
  376. }
  377. public static func openFavoriteMessage() {
  378. let isChangeProfile = Utils.getSetProfile()
  379. if !isChangeProfile {
  380. APIS.showChangeProfile()
  381. return
  382. }
  383. let editorStaredVC = AppStoryBoard.Palio.instance.instantiateViewController(withIdentifier: "staredVC") as! EditorStarMessages
  384. editorStaredVC.fromNotification = true
  385. let navigationController = CustomNavigationController(rootViewController: editorStaredVC)
  386. navigationController.defaultStyle()
  387. if UIApplication.shared.visibleViewController?.navigationController != nil {
  388. UIApplication.shared.visibleViewController?.navigationController?.present(navigationController, animated: true, completion: nil)
  389. } else {
  390. UIApplication.shared.visibleViewController?.present(navigationController, animated: true, completion: nil)
  391. }
  392. }
  393. public static func openSecureFolder() {
  394. let isChangeProfile = Utils.getSetProfile()
  395. if !isChangeProfile {
  396. APIS.showChangeProfile()
  397. return
  398. }
  399. let controller = AppStoryBoard.Palio.instance.instantiateViewController(withIdentifier: "secureFolderView") as! SecureFolderViewController
  400. let navigationController = CustomNavigationController(rootViewController: controller)
  401. navigationController.defaultStyle()
  402. if UIApplication.shared.visibleViewController?.navigationController != nil {
  403. UIApplication.shared.visibleViewController?.navigationController?.present(navigationController, animated: true, completion: nil)
  404. } else {
  405. UIApplication.shared.visibleViewController?.present(navigationController, animated: true, completion: nil)
  406. }
  407. }
  408. public static func openSecureBrowser() {
  409. let isChangeProfile = Utils.getSetProfile()
  410. if !isChangeProfile {
  411. APIS.showChangeProfile()
  412. return
  413. }
  414. let controller = BNIBookingWebView()
  415. controller.isSecureBrowser = true
  416. if UIApplication.shared.visibleViewController?.navigationController != nil {
  417. UIApplication.shared.visibleViewController?.navigationController?.present(controller, animated: true, completion: nil)
  418. } else {
  419. UIApplication.shared.visibleViewController?.present(controller, animated: true, completion: nil)
  420. }
  421. }
  422. public static func openCreateGroup() {
  423. let isChangeProfile = Utils.getSetProfile()
  424. if !isChangeProfile {
  425. APIS.showChangeProfile()
  426. return
  427. }
  428. let controller = AppStoryBoard.Palio.instance.instantiateViewController(identifier: "createGroupNav") as! UINavigationController
  429. Utils.addBackground(view: controller.view)
  430. let vc = controller.topViewController as! GroupCreateViewController
  431. vc.isDismiss = { id in
  432. let controller = AppStoryBoard.Palio.instance.instantiateViewController(withIdentifier: "groupDetailView") as! GroupDetailViewController
  433. controller.data = id
  434. controller.fromNotification = true
  435. let navigationController = CustomNavigationController(rootViewController: controller)
  436. navigationController.defaultStyle()
  437. DispatchQueue.main.asyncAfter(deadline: .now() + 1, execute: {
  438. if UIApplication.shared.visibleViewController?.navigationController != nil {
  439. UIApplication.shared.visibleViewController?.navigationController?.present(navigationController, animated: true, completion: nil)
  440. } else {
  441. UIApplication.shared.visibleViewController?.present(navigationController, animated: true, completion: nil)
  442. }
  443. })
  444. }
  445. controller.defaultStyle()
  446. if UIApplication.shared.visibleViewController?.navigationController != nil {
  447. UIApplication.shared.visibleViewController?.navigationController?.present(controller, animated: true, completion: nil)
  448. } else {
  449. UIApplication.shared.visibleViewController?.present(controller, animated: true, completion: nil)
  450. }
  451. }
  452. public static func openAddFriend() {
  453. let isChangeProfile = Utils.getSetProfile()
  454. if !isChangeProfile {
  455. APIS.showChangeProfile()
  456. return
  457. }
  458. let controller = AppStoryBoard.Palio.instance.instantiateViewController(identifier: "addFriendNav") as! UINavigationController
  459. Utils.addBackground(view: controller.view)
  460. controller.defaultStyle()
  461. if UIApplication.shared.visibleViewController?.navigationController != nil {
  462. UIApplication.shared.visibleViewController?.navigationController?.present(controller, animated: true, completion: nil)
  463. } else {
  464. UIApplication.shared.visibleViewController?.present(controller, animated: true, completion: nil)
  465. }
  466. }
  467. public static func openSignUpOrSignIn() {
  468. let isChangeProfile = Utils.getSetProfile()
  469. if !isChangeProfile {
  470. APIS.showChangeProfile()
  471. return
  472. }
  473. let controller = AppStoryBoard.Palio.instance.instantiateViewController(withIdentifier: "signupsignin") as! SignUpSignIn
  474. controller.forceLogin = true
  475. let navigationController = CustomNavigationController(rootViewController: controller)
  476. navigationController.defaultStyle()
  477. if UIApplication.shared.visibleViewController?.navigationController != nil {
  478. UIApplication.shared.visibleViewController?.navigationController?.present(navigationController, animated: true, completion: nil)
  479. } else {
  480. UIApplication.shared.visibleViewController?.present(navigationController, animated: true, completion: nil)
  481. }
  482. }
  483. public static func openSetting() {
  484. let navigationController = AppStoryBoard.Palio.instance.instantiateViewController(withIdentifier: "settingNav") as! UINavigationController
  485. let vc = navigationController.rootViewController as! SettingTableViewController
  486. vc.fromAPI = true
  487. Utils.addBackground(view: navigationController.view)
  488. navigationController.defaultStyle()
  489. if UIApplication.shared.visibleViewController is UINavigationController && (UIApplication.shared.visibleViewController as! UINavigationController).rootViewController is SettingTableViewController {
  490. return
  491. }
  492. if UIApplication.shared.visibleViewController?.navigationController != nil {
  493. UIApplication.shared.visibleViewController?.navigationController?.present(navigationController, animated: true, completion: nil)
  494. } else {
  495. UIApplication.shared.visibleViewController?.present(navigationController, animated: true, completion: nil)
  496. }
  497. }
  498. public static func openProfile() {
  499. let isChangeProfile = Utils.getSetProfile()
  500. if !isChangeProfile {
  501. APIS.showChangeProfile()
  502. return
  503. }
  504. let controller = AppStoryBoard.Palio.instance.instantiateViewController(withIdentifier: "profileView") as! ProfileViewController
  505. controller.data = User.getMyPin()!
  506. controller.flag = .me
  507. controller.fromAPI = true
  508. controller.dismissImage = { image, imageName in
  509. var dataImage: [AnyHashable : Any] = [:]
  510. dataImage["name"] = imageName
  511. NotificationCenter.default.post(name: NSNotification.Name(rawValue: "imageFBUpdate"), object: nil, userInfo: dataImage)
  512. }
  513. let navigationController = CustomNavigationController(rootViewController: controller)
  514. navigationController.defaultStyle()
  515. if UIApplication.shared.visibleViewController?.navigationController != nil {
  516. UIApplication.shared.visibleViewController?.navigationController?.present(navigationController, animated: true, completion: nil)
  517. } else {
  518. UIApplication.shared.visibleViewController?.present(navigationController, animated: true, completion: nil)
  519. }
  520. }
  521. public static func openWhiteboard() {
  522. let isChangeProfile = Utils.getSetProfile()
  523. if !isChangeProfile {
  524. APIS.showChangeProfile()
  525. return
  526. }
  527. let callContact = AppStoryBoard.Palio.instance.instantiateViewController(withIdentifier: "contactSID") as! ContactCallViewController
  528. callContact.startWhiteBoard = true
  529. let navigationController = CustomNavigationController(rootViewController: callContact)
  530. navigationController.defaultStyle()
  531. if UIApplication.shared.visibleViewController?.navigationController != nil {
  532. UIApplication.shared.visibleViewController?.navigationController?.present(navigationController, animated: true, completion: nil)
  533. } else {
  534. UIApplication.shared.visibleViewController?.present(navigationController, animated: true, completion: nil)
  535. }
  536. }
  537. public static func startWhiteboard(name: String) {
  538. if name.isEmpty {
  539. UIApplication.shared.visibleViewController?.view.makeToast("92:Username is empty".localized(), duration: 3)
  540. return
  541. }
  542. let user = User.getDataFromNameCanNil(name: name)
  543. if user == nil {
  544. UIApplication.shared.visibleViewController?.view.makeToast("91:Invalid name or you must add Username to your contact first".localized(), duration: 3)
  545. return
  546. }
  547. if !CheckConnection.isConnectedToNetwork() {
  548. let imageView = UIImageView(image: UIImage(systemName: "xmark.circle.fill"))
  549. imageView.tintColor = .white
  550. let banner = FloatingNotificationBanner(title: "Check your connection".localized(), subtitle: nil, titleFont: UIFont.systemFont(ofSize: 16), titleColor: nil, titleTextAlign: .left, subtitleFont: nil, subtitleColor: nil, subtitleTextAlign: nil, leftView: imageView, rightView: nil, style: .danger, colors: nil, iconPosition: .center)
  551. banner.show()
  552. return
  553. }
  554. let controller = AppStoryBoard.Palio.instance.instantiateViewController(identifier: "wbVC") as! WhiteboardViewController
  555. controller.modalPresentationStyle = .overFullScreen
  556. controller.fromContact = 0
  557. controller.user = user
  558. if UIApplication.shared.visibleViewController?.navigationController != nil {
  559. UIApplication.shared.visibleViewController?.navigationController?.present(controller, animated: true, completion: nil)
  560. } else {
  561. UIApplication.shared.visibleViewController?.present(controller, animated: true, completion: nil)
  562. }
  563. }
  564. // public static func openScreenSharing() {
  565. // let isChangeProfile = Utils.getSetProfile()
  566. // if !isChangeProfile {
  567. // APIS.showChangeProfile()
  568. // return
  569. // }
  570. // let callContact = AppStoryBoard.Palio.instance.instantiateViewController(withIdentifier: "contactSID") as! ContactCallViewController
  571. // callContact.startSS = true
  572. // let navigationController = CustomNavigationController(rootViewController: callContact)
  573. // navigationController.defaultStyle()
  574. // if UIApplication.shared.visibleViewController?.navigationController != nil {
  575. // UIApplication.shared.visibleViewController?.navigationController?.present(navigationController, animated: true, completion: nil)
  576. // } else {
  577. // UIApplication.shared.visibleViewController?.present(navigationController, animated: true, completion: nil)
  578. // }
  579. // }
  580. public static func startScreenSharing(name: String) {
  581. if name.isEmpty {
  582. UIApplication.shared.visibleViewController?.view.makeToast("92:Username is empty".localized(), duration: 3)
  583. return
  584. }
  585. let user = User.getDataFromNameCanNil(name: name)
  586. if user == nil {
  587. UIApplication.shared.visibleViewController?.view.makeToast("91:Invalid name or you must add Username to your contact first".localized(), duration: 3)
  588. return
  589. }
  590. if !CheckConnection.isConnectedToNetwork() {
  591. let imageView = UIImageView(image: UIImage(systemName: "xmark.circle.fill"))
  592. imageView.tintColor = .white
  593. let banner = FloatingNotificationBanner(title: "Check your connection".localized(), subtitle: nil, titleFont: UIFont.systemFont(ofSize: 16), titleColor: nil, titleTextAlign: .left, subtitleFont: nil, subtitleColor: nil, subtitleTextAlign: nil, leftView: imageView, rightView: nil, style: .danger, colors: nil, iconPosition: .center)
  594. banner.show()
  595. return
  596. }
  597. let controller = ScreenSharingViewController()
  598. controller.modalPresentationStyle = .overFullScreen
  599. controller.fromContact = 0
  600. controller.user = user
  601. if UIApplication.shared.visibleViewController?.navigationController != nil {
  602. UIApplication.shared.visibleViewController?.navigationController?.present(controller, animated: true, completion: nil)
  603. } else {
  604. UIApplication.shared.visibleViewController?.present(controller, animated: true, completion: nil)
  605. }
  606. }
  607. public static func openWhiteboardAndScreenSharing() {
  608. let isChangeProfile = Utils.getSetProfile()
  609. if !isChangeProfile {
  610. APIS.showChangeProfile()
  611. return
  612. }
  613. let callContact = AppStoryBoard.Palio.instance.instantiateViewController(withIdentifier: "contactSID") as! ContactCallViewController
  614. callContact.startSS = true
  615. callContact.startWhiteBoard = true
  616. let navigationController = CustomNavigationController(rootViewController: callContact)
  617. navigationController.defaultStyle()
  618. if UIApplication.shared.visibleViewController?.navigationController != nil {
  619. UIApplication.shared.visibleViewController?.navigationController?.present(navigationController, animated: true, completion: nil)
  620. } else {
  621. UIApplication.shared.visibleViewController?.present(navigationController, animated: true, completion: nil)
  622. }
  623. }
  624. public static func signInAdmin(password: String) {
  625. if password.isEmpty {
  626. UIApplication.shared.visibleViewController?.view.makeToast("113:Password is empty".localized(), duration: 3)
  627. return
  628. }
  629. let isChangeProfile = Utils.getSetProfile()
  630. if !isChangeProfile {
  631. APIS.showChangeProfile()
  632. return
  633. }
  634. let isAdmin = User.isAdmin()
  635. if isAdmin {
  636. UIApplication.shared.visibleViewController?.view.makeToast("112:You already login or registered as Admin".localized(), duration: 3)
  637. return
  638. }
  639. if !CheckConnection.isConnectedToNetwork() || API.nGetCLXConnState() == 0 {
  640. let imageView = UIImageView(image: UIImage(systemName: "xmark.circle.fill"))
  641. imageView.tintColor = .white
  642. let banner = FloatingNotificationBanner(title: "Check your connection".localized(), subtitle: nil, titleFont: UIFont.systemFont(ofSize: 16), titleColor: nil, titleTextAlign: .left, subtitleFont: nil, subtitleColor: nil, subtitleTextAlign: nil, leftView: imageView, rightView: nil, style: .danger, colors: nil, iconPosition: .center)
  643. banner.show()
  644. return
  645. }
  646. Nexilis.showLoader()
  647. self.signInAdmin(password: password, completion: { result in
  648. if result {
  649. DispatchQueue.main.async {
  650. Nexilis.hideLoader {
  651. let imageView = UIImageView(image: UIImage(systemName: "checkmark.circle.fill"))
  652. imageView.tintColor = .white
  653. let banner = FloatingNotificationBanner(title: "Successfully Sign-In Admin".localized(), subtitle: nil, titleFont: UIFont.systemFont(ofSize: 16), titleColor: nil, titleTextAlign: .left, subtitleFont: nil, subtitleColor: nil, subtitleTextAlign: nil, leftView: imageView, rightView: nil, style: .success, colors: nil, iconPosition: .center)
  654. banner.show()
  655. }
  656. }
  657. } else {
  658. DispatchQueue.main.async {
  659. Nexilis.hideLoader {}
  660. }
  661. }
  662. })
  663. }
  664. private static func signInAdmin(password: String, completion: @escaping (Bool) -> ()) {
  665. DispatchQueue.global().async {
  666. let idMe = User.getMyPin() as String?
  667. let p_password = password
  668. let md5Hex = p_password
  669. var result: Bool = false
  670. if let response = Nexilis.writeSync(message: CoreMessage_TMessageBank.getSignInApiAdmin(p_name: idMe!, p_password: md5Hex)) {
  671. if response.isOk() {
  672. result = true
  673. }
  674. DispatchQueue.main.async {
  675. if response.getBody(key: CoreMessage_TMessageKey.ERRCOD, default_value: "99") == "11" {
  676. let imageView = UIImageView(image: UIImage(systemName: "xmark.circle.fill"))
  677. imageView.tintColor = .white
  678. let banner = FloatingNotificationBanner(title: "Username or password does not match".localized(), subtitle: nil, titleFont: UIFont.systemFont(ofSize: 16), titleColor: nil, titleTextAlign: .left, subtitleFont: nil, subtitleColor: nil, subtitleTextAlign: nil, leftView: imageView, rightView: nil, style: .danger, colors: nil, iconPosition: .top)
  679. banner.show()
  680. } else if response.getBody(key: CoreMessage_TMessageKey.ERRCOD, default_value: "99") == "20" {
  681. let imageView = UIImageView(image: UIImage(systemName: "xmark.circle.fill"))
  682. imageView.tintColor = .white
  683. let banner = FloatingNotificationBanner(title: "Invalid password".localized(), subtitle: nil, titleFont: UIFont.systemFont(ofSize: 16), titleColor: nil, titleTextAlign: .left, subtitleFont: nil, subtitleColor: nil, subtitleTextAlign: nil, leftView: imageView, rightView: nil, style: .danger, colors: nil, iconPosition: .top)
  684. banner.show()
  685. }
  686. }
  687. } else {
  688. DispatchQueue.main.async {
  689. let imageView = UIImageView(image: UIImage(systemName: "xmark.circle.fill"))
  690. imageView.tintColor = .white
  691. let banner = FloatingNotificationBanner(title: "Unable to access servers".localized(), subtitle: nil, titleFont: UIFont.systemFont(ofSize: 16), titleColor: nil, titleTextAlign: .left, subtitleFont: nil, subtitleColor: nil, subtitleTextAlign: nil, leftView: imageView, rightView: nil, style: .danger, colors: nil, iconPosition: .top)
  692. banner.show()
  693. }
  694. }
  695. completion(result)
  696. }
  697. }
  698. public static func openSetAsOfficerForm() {
  699. let isChangeProfile = Utils.getSetProfile()
  700. if !isChangeProfile {
  701. APIS.showChangeProfile()
  702. return
  703. }
  704. let isAdmin = User.isAdmin()
  705. if !isAdmin {
  706. UIApplication.shared.visibleViewController?.view.makeToast("111:You must Sign In as Admin to use this feature".localized(), duration: 3)
  707. return
  708. }
  709. let controller = SetInternalCSAccount()
  710. controller.isSetCS = true
  711. controller.fromNotification = true
  712. let navigationController = CustomNavigationController(rootViewController: controller)
  713. navigationController.defaultStyle()
  714. if UIApplication.shared.visibleViewController?.navigationController != nil {
  715. UIApplication.shared.visibleViewController?.navigationController?.present(navigationController, animated: true, completion: nil)
  716. } else {
  717. UIApplication.shared.visibleViewController?.present(navigationController, animated: true, completion: nil)
  718. }
  719. }
  720. public static func sendSMS(phoneNumber: String, message: String = ""){
  721. let formattedNumber = phoneNumber.replacingOccurrences(of: "-", with: "")
  722. let urlStringEncoded = message.addingPercentEncoding(withAllowedCharacters: NSCharacterSet.urlQueryAllowed)
  723. let paramMessage = message.isEmpty ? "" : "&body=\(urlStringEncoded!)"
  724. let url = URL(string: "sms:\(formattedNumber)\(paramMessage)")
  725. if UIApplication.shared.canOpenURL(url!) {
  726. UIApplication.shared.open(url!)
  727. }
  728. }
  729. public static func sendWhatsapp(phoneNumber: String, message: String = "") {
  730. let formattedNumber = phoneNumber.replacingOccurrences(of: "+", with: "").replacingOccurrences(of: "-", with: "")
  731. let urlStringEncoded = message.addingPercentEncoding(withAllowedCharacters: NSCharacterSet.urlQueryAllowed)
  732. let paramMessage = message.isEmpty ? "" : "?text=\(urlStringEncoded!)"
  733. let url = URL(string: "https://wa.me/\(formattedNumber)\(paramMessage)")
  734. if UIApplication.shared.canOpenURL(url!) {
  735. UIApplication.shared.open(url!, options: [:]) { (success) in
  736. // if success {
  737. // //print("WhatsApp accessed successfully")
  738. // } else {
  739. // //print("Error accessing WhatsApp")
  740. // }
  741. }
  742. }
  743. }
  744. public static func changeUsername(uname: String) {
  745. let isChangeProfile = Utils.getSetProfile()
  746. if !isChangeProfile {
  747. APIS.showChangeProfile()
  748. return
  749. }
  750. let finalUname = uname.replacingOccurrences(of: "[\\n\\r\\t~%()\"]", with: "", options: .regularExpression)
  751. if finalUname == User.getData(pin: User.getMyPin())?.fullName {
  752. UIApplication.shared.visibleViewController?.view.makeToast("102:Duplicate username".localized(), duration: 3)
  753. return
  754. }
  755. if finalUname.count == 0 {
  756. UIApplication.shared.visibleViewController?.view.makeToast("103:Username is empty".localized(), duration: 3)
  757. return
  758. }
  759. if finalUname.count < 3 {
  760. UIApplication.shared.visibleViewController?.view.makeToast("104:Username length is too short".localized(), duration: 3)
  761. return
  762. }
  763. let a = finalUname.split(separator: " ", maxSplits: 1)
  764. let first = String(a[0])
  765. let last = a.count == 2 ? String(a[1]) : ""
  766. DispatchQueue.global().async {
  767. if let resp = Nexilis.writeAndWait(message: CoreMessage_TMessageBank.getChangePersonInfoName(firstname: first, lastname: last)) {
  768. if resp.isOk() {
  769. Database.shared.database?.inTransaction({ fmdb, rollback in
  770. do {
  771. _ = Database.shared.updateRecord(fmdb: fmdb, table: "BUDDY", cvalues: ["first_name": first , "last_name": last], _where: "f_pin = '\(User.getMyPin())'")
  772. } catch {
  773. rollback.pointee = true
  774. print("Access database error: \(error.localizedDescription)")
  775. }
  776. })
  777. NotificationCenter.default.post(name: NSNotification.Name(rawValue: "updateFifthTab"), object: nil, userInfo: nil)
  778. DispatchQueue.main.async {
  779. Nexilis.hideLoader {
  780. let imageView = UIImageView(image: UIImage(systemName: "checkmark.circle.fill"))
  781. imageView.tintColor = .white
  782. let banner = FloatingNotificationBanner(title: "Successfully changed name".localized(), subtitle: nil, titleFont: UIFont.systemFont(ofSize: 16), titleColor: nil, titleTextAlign: .left, subtitleFont: nil, subtitleColor: nil, subtitleTextAlign: nil, leftView: imageView, rightView: nil, style: .success, colors: nil, iconPosition: .center)
  783. banner.show()
  784. }
  785. }
  786. } else if resp.getBody(key: CoreMessage_TMessageKey.ERRCOD, default_value: "99") == "1a" {
  787. DispatchQueue.main.async {
  788. let imageView = UIImageView(image: UIImage(systemName: "xmark.circle.fill"))
  789. imageView.tintColor = .white
  790. let banner = FloatingNotificationBanner(title: "Username has been registered, please use another name".localized(), subtitle: nil, titleFont: UIFont.systemFont(ofSize: 16), titleColor: nil, titleTextAlign: .left, subtitleFont: nil, subtitleColor: nil, subtitleTextAlign: nil, leftView: imageView, rightView: nil, style: .danger, colors: nil, iconPosition: .center)
  791. banner.show()
  792. }
  793. }
  794. }
  795. }
  796. }
  797. public static func openMail() {
  798. Nexilis.openmailAction()
  799. }
  800. public static func sendPushToken(_ token: String, isResend: Bool = false) {
  801. DispatchQueue.global().async{
  802. var isResend = isResend
  803. if Utils.getTokenAPN().isEmpty || token != Utils.getTokenAPN() || isResend {
  804. Utils.setTokenAPN(value: token)
  805. isResend = true
  806. }
  807. if isResend {
  808. _ = Nexilis.write(message: CoreMessage_TMessageBank.getToken(token: token))
  809. }
  810. }
  811. }
  812. public static var uuidCall: UUID?
  813. public static var fpinCall: String?
  814. public static func showNotificationNexilis(_ userInfo: [AnyHashable : Any]) {
  815. // let center = UNUserNotificationCenter.current()
  816. // let content = UNMutableNotificationContent()
  817. // content.title = "showNotificationNexilis"
  818. // content.body = ""
  819. // content.sound = .default
  820. // content.userInfo = userInfo
  821. // let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 1, repeats: false)
  822. // let request = UNNotificationRequest(identifier: "HJK", content: content, trigger: trigger)
  823. // center.add(request) { error in
  824. // if let error = error {
  825. // print("Error scheduling notification: \(error.localizedDescription)")
  826. // }
  827. // }
  828. if checkAppStateisBackground() {
  829. DispatchQueue.main.async {
  830. if let payload = userInfo["payload"] as? [String: Any] {
  831. if let messagePayload = payload["message"] as? [String: Any] {
  832. if let data = messagePayload["data"] as? [String: Any] {
  833. let code = data["nx_code"] as? String ?? ""
  834. while (!API.bnuSDKServiceReady() || API.nGetCLXConnState() == 0) {
  835. }
  836. if code == "CL01" {
  837. if let message = data["bodies"] as? [String: String] {
  838. let messageToSave = TMessage()
  839. messageToSave.mBodies = message
  840. do {
  841. var messageExist = false
  842. Database.shared.database?.inTransaction({ (fmdb, rollback) in
  843. if let cursor = Database.shared.getRecords(fmdb: fmdb, query: "select message_id from MESSAGE where message_id = '\(message[CoreMessage_TMessageKey.MESSAGE_ID] ?? "")'"), cursor.next() {
  844. messageExist = true
  845. cursor.close()
  846. }
  847. })
  848. if messageExist {
  849. return
  850. }
  851. Nexilis.saveMessage(message: messageToSave, withStatus: false, fromAPNS: true)
  852. DispatchQueue.global().async {
  853. _ = Nexilis.write(message: CoreMessage_TMessageBank.getAckMessage(messageId: message[CoreMessage_TMessageKey.MESSAGE_ID] ?? ""))
  854. }
  855. } catch {
  856. print("error saving message: \(error)")
  857. }
  858. APIS.addNotificationNexilis(messageToSave)
  859. }
  860. } else if code == "CL03" {
  861. let callFromName = data["call-from-name"] as? String ?? ""
  862. let callFrom = data["call-from"] as? String ?? ""
  863. let callType = data["call-type"] as? String ?? ""
  864. // uuidCall = UUID()
  865. fpinCall = callFrom
  866. Nexilis.callAPNActivated = true
  867. // CallManager.shared.reportIncomingCall(uuid: uuidCall!, callerName: callFromName, callerId: callFrom, isVideo: callType != "1") { error in
  868. // if let error = error {
  869. // print("Error reporting incoming call: \(error.localizedDescription)")
  870. // } else {
  871. // print("Incoming call reported successfully")
  872. // }
  873. // }
  874. copySoundToLocalPath("pb_call_in")
  875. let center = UNUserNotificationCenter.current()
  876. let content = UNMutableNotificationContent()
  877. content.title = callFromName
  878. if callType == "1" {
  879. content.body = "Incoming Audio Call".localized()
  880. } else {
  881. content.body = "Incoming Video Call".localized()
  882. }
  883. content.userInfo = ["id" : callFrom, "type" : code, "callType": callType]
  884. content.sound = UNNotificationSound(named: UNNotificationSoundName("pb_call_in.mp3"))
  885. let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 1, repeats: false)
  886. let request = UNNotificationRequest(identifier: callFrom, content: content, trigger: trigger)
  887. center.add(request) { error in
  888. if let error = error {
  889. print("Error scheduling notification: \(error.localizedDescription)")
  890. }
  891. }
  892. } else if code == "CL02" {
  893. let callFrom = data["call-from"] as? String ?? ""
  894. // if let uuidCall = uuidCall {
  895. Nexilis.callAPNActivated = false
  896. let center = UNUserNotificationCenter.current()
  897. center.removeDeliveredNotifications(withIdentifiers: [callFrom])
  898. // CallManager.shared.endCall(with: uuidCall)
  899. // }
  900. }
  901. }
  902. }
  903. }
  904. }
  905. }
  906. }
  907. public static func addNotificationNexilis(_ message: TMessage) {
  908. var text = message.getBody(key: CoreMessage_TMessageKey.MESSAGE_TEXT)
  909. text = text.toNormalString()
  910. let nameUser = message.getBody(key: CoreMessage_TMessageKey.F_DISPLAY_NAME)
  911. var threadIdentifier = message.getBody(key: CoreMessage_TMessageKey.OPPOSITE_PIN)
  912. let scope = message.getBody(key: CoreMessage_TMessageKey.MESSAGE_SCOPE_ID)
  913. if threadIdentifier.isEmpty {
  914. if scope == "4" {
  915. threadIdentifier = message.getBody(key: CoreMessage_TMessageKey.CHAT_ID).isEmpty ? message.getBody(key: CoreMessage_TMessageKey.L_PIN) : message.getBody(key: CoreMessage_TMessageKey.CHAT_ID)
  916. } else {
  917. threadIdentifier = message.getBody(key: CoreMessage_TMessageKey.F_PIN)
  918. }
  919. }
  920. let messageId = message.getBody(key: CoreMessage_TMessageKey.MESSAGE_ID)
  921. var nameSubtitle = ""
  922. let imageId = CoreMessage_TMessageKey.IMAGE_ID
  923. let videoId = CoreMessage_TMessageKey.VIDEO_ID
  924. let fileId = CoreMessage_TMessageKey.FILE_ID
  925. let audioId = CoreMessage_TMessageKey.AUDIO_ID
  926. let attachmentFlag = CoreMessage_TMessageKey.ATTACHMENT_FLAG
  927. let messageScopeId = CoreMessage_TMessageKey.MESSAGE_SCOPE_ID
  928. let credential = CoreMessage_TMessageKey.CREDENTIAL
  929. let gif_id = CoreMessage_TMessageKey.GIF_ID
  930. let is_secret = CoreMessage_TMessageKey.IS_SECRET
  931. if message.getBody(key: is_secret) == "1" {
  932. text = "You got messages..."
  933. } else if message.getBody(key: gif_id) != "" {
  934. text = "Sent GIF 🎬"
  935. } else if !message.getBody(key: imageId).isEmpty {
  936. text = "Sent Image 📷"
  937. } else if message.getBody(key: attachmentFlag) == "11" {
  938. text = "Sent Sticker ❤️"
  939. } else if !message.getBody(key: videoId).isEmpty {
  940. text = "Sent Video 📹"
  941. } else if !message.getBody(key: fileId).isEmpty {
  942. if message.getBody(key: messageScopeId) == "18" {
  943. text = "Sent Form 📄"
  944. } else {
  945. text = "Sent File 📄"
  946. }
  947. } else if !message.getBody(key: audioId).isEmpty {
  948. text = "Sent Audio ♫"
  949. } else if text.contains("Share%20location%20") {
  950. text = "Sent Location 📌"
  951. } else if message.getBody(key: attachmentFlag) == "27" {
  952. text = "Sent Live Streaming"
  953. } else if message.getBody(key: attachmentFlag) == "26" {
  954. text = "Sent Seminar"
  955. } else if message.getBody(key: attachmentFlag) == "25" {
  956. text = "Sent Video Conference Room"
  957. } else if message.getBody(key: attachmentFlag) == "24" {
  958. text = "Sent Quiz"
  959. } else if message.getBody(key: credential) == "1" {
  960. text = "Sent Confidential Message"
  961. }
  962. var type = "1"
  963. var nameTopic = "Lounge".localized()
  964. var idGroup = ""
  965. if scope == "3" || scope == "18" || scope == "5"{
  966. type = "0"
  967. }
  968. var soundId: String = SecureUserDefaults.shared.value(forKey: "newNotifSoundPersonal") ?? "001:Nexilis Message (Default)"
  969. if type == "1" {
  970. Database.shared.database?.inTransaction({ (fmdb, rollback) in
  971. do {
  972. if let cursor = Database.shared.getRecords(fmdb: fmdb, query: "SELECT title, group_id FROM DISCUSSION_FORUM WHERE chat_id='\(threadIdentifier)'"), cursor.next() {
  973. nameTopic = cursor.string(forColumnIndex: 0) ?? ""
  974. idGroup = cursor.string(forColumnIndex: 1) ?? ""
  975. cursor.close()
  976. }
  977. if idGroup.isEmpty {
  978. idGroup = threadIdentifier
  979. }
  980. if let cursorGroup = Database.shared.getRecords(fmdb: fmdb, query: "SELECT f_name, image_id FROM GROUPZ WHERE group_id='\(idGroup)'"), cursorGroup.next() {
  981. let nameGroup = cursorGroup.string(forColumnIndex: 0) ?? ""
  982. nameSubtitle = "\(nameGroup) (\(nameTopic))"
  983. cursorGroup.close()
  984. }
  985. } catch {
  986. rollback.pointee = true
  987. print("Access database error: \(error.localizedDescription)")
  988. }
  989. })
  990. soundId = SecureUserDefaults.shared.value(forKey: "newNotifSoundGroup") ?? "001:Nexilis Message (Default)"
  991. if idGroup.isEmpty {
  992. return
  993. }
  994. }
  995. var nameSound = soundId.components(separatedBy: ":")[1].replacingOccurrences(of: " ", with: "_")
  996. if nameSound.contains("_(Default)") {
  997. nameSound = nameSound.replacingOccurrences(of: "_(Default)", with: "")
  998. }
  999. copySoundToLocalPath(nameSound)
  1000. let center = UNUserNotificationCenter.current()
  1001. let content = UNMutableNotificationContent()
  1002. content.title = nameUser
  1003. if type == "1" {
  1004. content.body = text.richText(group_id: idGroup).string
  1005. content.subtitle = nameSubtitle
  1006. } else {
  1007. content.body = text.richText().string
  1008. }
  1009. content.userInfo = ["id" : threadIdentifier, "type" : type]
  1010. content.sound = UNNotificationSound(named: UNNotificationSoundName("\(nameSound).mp3"))
  1011. let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 1, repeats: false)
  1012. let request = UNNotificationRequest(identifier: messageId, content: content, trigger: trigger)
  1013. center.add(request) { error in
  1014. if let error = error {
  1015. print("Error scheduling notification: \(error.localizedDescription)")
  1016. }
  1017. }
  1018. DispatchQueue.main.async {
  1019. UIApplication.shared.applicationIconBadgeNumber = Int(APIS.getTotalCounter())
  1020. }
  1021. }
  1022. private static func copySoundToLocalPath(_ nameSound: String) {
  1023. var sourceURL = Bundle.resourceBundle(for: Nexilis.self).url(forResource: nameSound, withExtension: "mp3")
  1024. if sourceURL == nil {
  1025. sourceURL = Bundle.resourcesMediaBundle(for: Nexilis.self).url(forResource: nameSound, withExtension: "mp3")
  1026. }
  1027. let fileManager = FileManager.default
  1028. let soundDirectory = FileManager.default.urls(for: .libraryDirectory, in: .userDomainMask).first!.appendingPathComponent("Sounds", isDirectory: true)
  1029. if !fileManager.fileExists(atPath: soundDirectory.path) {
  1030. do {
  1031. try fileManager.createDirectory(at: soundDirectory, withIntermediateDirectories: true, attributes: nil)
  1032. } catch {
  1033. print("Error creating Sounds directory: \(error)")
  1034. return
  1035. }
  1036. }
  1037. let destinationURL = soundDirectory.appendingPathComponent("\(nameSound).mp3")
  1038. if !fileManager.fileExists(atPath: destinationURL.path) {
  1039. do {
  1040. try fileManager.copyItem(at: sourceURL!, to: destinationURL)
  1041. } catch {
  1042. }
  1043. }
  1044. }
  1045. public static func openNotificationNexilis(_ response: UNNotificationResponse) {
  1046. DispatchQueue.main.async{
  1047. if let userInfo = response.notification.request.content.userInfo as? [String: String] {
  1048. let id = userInfo["id"] ?? ""
  1049. let type = userInfo["type"] ?? ""
  1050. if let navigationC = UIApplication.shared.visibleViewController as? UINavigationController {
  1051. if navigationC.viewControllers[navigationC.viewControllers.count - 1] is EditorPersonal || navigationC.viewControllers[navigationC.viewControllers.count - 1] is EditorGroup {
  1052. navigationC.popViewController(animated: true)
  1053. }
  1054. }
  1055. if type == "0" {
  1056. if User.getDataCanNil(pin: id) == nil {
  1057. return
  1058. }
  1059. let editorPersonalVC = AppStoryBoard.Palio.instance.instantiateViewController(identifier: "editorPersonalVC") as! EditorPersonal
  1060. editorPersonalVC.hidesBottomBarWhenPushed = true
  1061. editorPersonalVC.unique_l_pin = id
  1062. editorPersonalVC.fromNotification = true
  1063. let navigationController = CustomNavigationController(rootViewController: editorPersonalVC)
  1064. navigationController.modalPresentationStyle = .fullScreen
  1065. navigationController.navigationBar.tintColor = .white
  1066. navigationController.navigationBar.barTintColor = UIApplication.shared.visibleViewController?.traitCollection.userInterfaceStyle == .dark ? .blackDarkMode : .mainColor
  1067. navigationController.navigationBar.isTranslucent = false
  1068. navigationController.navigationBar.overrideUserInterfaceStyle = .dark
  1069. navigationController.navigationBar.barStyle = .black
  1070. let cancelButtonAttributes: [NSAttributedString.Key: Any] = [NSAttributedString.Key.foregroundColor: UIColor.white, NSAttributedString.Key.font : UIFont.systemFont(ofSize: 16)]
  1071. UIBarButtonItem.appearance().setTitleTextAttributes(cancelButtonAttributes, for: .normal)
  1072. let textAttributes = [NSAttributedString.Key.foregroundColor:UIColor.white]
  1073. navigationController.navigationBar.titleTextAttributes = textAttributes
  1074. if UIApplication.shared.visibleViewController?.navigationController != nil {
  1075. UIApplication.shared.visibleViewController?.navigationController?.present(navigationController, animated: true, completion: nil)
  1076. } else {
  1077. UIApplication.shared.visibleViewController?.present(navigationController, animated: true, completion: nil)
  1078. }
  1079. } else if type == "1" {
  1080. var groupExist = false
  1081. Database.shared.database?.inTransaction({ (fmdb, rollback) in
  1082. var idGroup = ""
  1083. if let cursor = Database.shared.getRecords(fmdb: fmdb, query: "SELECT title, group_id FROM DISCUSSION_FORUM WHERE chat_id='\(id)'"), cursor.next() {
  1084. groupExist = true
  1085. cursor.close()
  1086. } else {
  1087. if idGroup.isEmpty {
  1088. idGroup = id
  1089. }
  1090. if let cursorGroup = Database.shared.getRecords(fmdb: fmdb, query: "SELECT f_name, image_id FROM GROUPZ WHERE group_id='\(idGroup)'"), cursorGroup.next() {
  1091. groupExist = true
  1092. cursorGroup.close()
  1093. }
  1094. }
  1095. })
  1096. if !groupExist {
  1097. return
  1098. }
  1099. let editorGroupVC = AppStoryBoard.Palio.instance.instantiateViewController(withIdentifier: "editorGroupVC") as! EditorGroup
  1100. editorGroupVC.hidesBottomBarWhenPushed = true
  1101. editorGroupVC.unique_l_pin = id
  1102. editorGroupVC.fromNotification = true
  1103. let navigationController = CustomNavigationController(rootViewController: editorGroupVC)
  1104. navigationController.modalPresentationStyle = .fullScreen
  1105. navigationController.navigationBar.tintColor = .white
  1106. navigationController.navigationBar.barTintColor = UIApplication.shared.visibleViewController?.traitCollection.userInterfaceStyle == .dark ? .blackDarkMode : .mainColor
  1107. navigationController.navigationBar.isTranslucent = false
  1108. navigationController.navigationBar.overrideUserInterfaceStyle = .dark
  1109. navigationController.navigationBar.barStyle = .black
  1110. let cancelButtonAttributes: [NSAttributedString.Key: Any] = [NSAttributedString.Key.foregroundColor: UIColor.white, NSAttributedString.Key.font : UIFont.systemFont(ofSize: 16)]
  1111. UIBarButtonItem.appearance().setTitleTextAttributes(cancelButtonAttributes, for: .normal)
  1112. let textAttributes = [NSAttributedString.Key.foregroundColor:UIColor.white]
  1113. navigationController.navigationBar.titleTextAttributes = textAttributes
  1114. if UIApplication.shared.visibleViewController?.navigationController != nil {
  1115. UIApplication.shared.visibleViewController?.navigationController?.present(navigationController, animated: true, completion: nil)
  1116. } else {
  1117. UIApplication.shared.visibleViewController?.present(navigationController, animated: true, completion: nil)
  1118. }
  1119. } else if type == "CL03" {
  1120. let callType = userInfo["callType"] ?? ""
  1121. if callType == "1" {
  1122. if let user = User.getData(pin: id), user.firstName == "User".localized() {
  1123. return
  1124. }
  1125. let controller = QmeraAudioViewController()
  1126. controller.isOutgoing = false
  1127. controller.user = User.getData(pin: id)
  1128. controller.autoAcceptAPN = true
  1129. controller.modalPresentationStyle = .overCurrentContext
  1130. if UIApplication.shared.visibleViewController is UIAlertController {
  1131. let vc = UIApplication.shared.visibleViewController as! UIAlertController
  1132. vc.dismiss(animated: true, completion: {
  1133. if UIApplication.shared.visibleViewController?.navigationController != nil {
  1134. UIApplication.shared.visibleViewController?.navigationController?.present(controller, animated: true, completion: nil)
  1135. } else {
  1136. UIApplication.shared.visibleViewController?.present(controller, animated: true, completion: nil)
  1137. }
  1138. })
  1139. return
  1140. }
  1141. if UIApplication.shared.visibleViewController?.navigationController != nil {
  1142. UIApplication.shared.visibleViewController?.navigationController?.present(controller, animated: true, completion: nil)
  1143. } else {
  1144. UIApplication.shared.visibleViewController?.present(controller, animated: true, completion: nil)
  1145. }
  1146. } else {
  1147. if let user = User.getData(pin: id), user.firstName == "User".localized() {
  1148. return
  1149. }
  1150. let videoController = AppStoryBoard.Palio.instance.instantiateViewController(withIdentifier: "videoVCQmera") as! QmeraVideoViewController
  1151. videoController.fPin = id
  1152. videoController.isInisiator = false
  1153. videoController.autoAcceptAPN = true
  1154. let navigationController = CustomNavigationController(rootViewController: videoController)
  1155. navigationController.modalPresentationStyle = .fullScreen
  1156. if UIApplication.shared.visibleViewController is UIAlertController {
  1157. let vc = UIApplication.shared.visibleViewController as! UIAlertController
  1158. vc.dismiss(animated: true, completion: {
  1159. if UIApplication.shared.visibleViewController?.navigationController != nil {
  1160. UIApplication.shared.visibleViewController?.navigationController?.present(navigationController, animated: true, completion: nil)
  1161. } else {
  1162. UIApplication.shared.visibleViewController?.present(navigationController, animated: true, completion: nil)
  1163. }
  1164. })
  1165. return
  1166. }
  1167. if UIApplication.shared.visibleViewController?.navigationController != nil {
  1168. UIApplication.shared.visibleViewController?.navigationController?.present(navigationController, animated: true, completion: nil)
  1169. } else {
  1170. UIApplication.shared.visibleViewController?.present(navigationController, animated: true, completion: nil)
  1171. }
  1172. }
  1173. }
  1174. }
  1175. }
  1176. // UNUserNotificationCenter.current().removeAllDeliveredNotifications()
  1177. }
  1178. public static func checkAppStateisBackground() -> Bool {
  1179. let state = UIApplication.shared.applicationState
  1180. switch state {
  1181. case .active:
  1182. return false
  1183. case .inactive:
  1184. return false
  1185. case .background:
  1186. return true
  1187. @unknown default:
  1188. return false
  1189. }
  1190. }
  1191. public static func enterBackground() {
  1192. UIApplication.shared.setMinimumBackgroundFetchInterval(UIApplication.backgroundFetchIntervalMinimum)
  1193. }
  1194. public static func enterForeground() {
  1195. DispatchQueue.global().async {
  1196. do {
  1197. if !Nexilis.afterConnect {
  1198. var id = Utils.getConnectionID()
  1199. try API.initConnection(sAPIK: Nexilis.sAPIKey, cbiI: Callback(), sTCPAddr: Nexilis.ADDRESS, nTCPPort: Nexilis.PORT, sUserID: id, sStartWH: "09:00")
  1200. }
  1201. // listIdentifierNotif.removeAll()
  1202. Nexilis.afterConnect = false
  1203. } catch {
  1204. }
  1205. }
  1206. checkDataForShareExtension()
  1207. UIApplication.shared.applicationIconBadgeNumber = 0
  1208. UNUserNotificationCenter.current().removeAllDeliveredNotifications()
  1209. }
  1210. public static func willTerminate() {
  1211. Nexilis.destroyAll()
  1212. }
  1213. public static func checkDataForShareExtension() {
  1214. DispatchQueue.global().async {
  1215. if let userDefaults = UserDefaults(suiteName: "group.nexilis.share") {
  1216. if let value = userDefaults.string(forKey: "sharedItem") {
  1217. if !value.isEmpty {
  1218. if let jsonData = value.data(using: .utf8) {
  1219. do {
  1220. if let json = try JSONSerialization.jsonObject(with: jsonData, options: []) as? [String: Any] {
  1221. let typeImage = 2
  1222. let typeVideo = 3
  1223. let typeFile = 4
  1224. let typeContact = json["typeContact"] as? String ?? "0"
  1225. var data = json["data"] as? String ?? ""
  1226. let idContact = json["idContact"] as? String ?? ""
  1227. let typeShare = json["typeShare"] as? Int ?? 1
  1228. var message = TMessage()
  1229. var groupId = ""
  1230. var chatId = ""
  1231. let scopeId = typeContact == "1" ? "4" : "3"
  1232. let thumb = json["thumb"] as? String ?? ""
  1233. let imageId = json["image"] as? String ?? ""
  1234. let videoId = json["video"] as? String ?? ""
  1235. let fileId = json["file"] as? String ?? ""
  1236. var renamedFileId = ""
  1237. var attachmentFlag = ""
  1238. if scopeId == "4" {
  1239. Database.shared.database?.inTransaction({ (fmdb, rollback) in
  1240. if let cursor = Database.shared.getRecords(fmdb: fmdb, query: "SELECT group_id id FROM DISCUSSION_FORUM WHERE chat_id = '\(idContact)'"), cursor.next() {
  1241. groupId = cursor.string(forColumnIndex: 0) ?? ""
  1242. chatId = idContact
  1243. cursor.close()
  1244. } else {
  1245. groupId = idContact
  1246. }
  1247. })
  1248. }
  1249. if typeShare == typeImage {
  1250. if let appGroupURL = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.nexilis.share") {
  1251. let sharedImageURL = appGroupURL.appendingPathComponent(imageId)
  1252. let sharedThumbURL = appGroupURL.appendingPathComponent(thumb)
  1253. let documentDir = try FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
  1254. if FileManager.default.fileExists(atPath: sharedImageURL.path) {
  1255. let file = documentDir.appendingPathComponent(imageId)
  1256. if !FileManager().fileExists(atPath: file.path) {
  1257. try? FileManager.default.copyItem(at: sharedImageURL, to: file)
  1258. }
  1259. }
  1260. if FileManager.default.fileExists(atPath: sharedThumbURL.path) {
  1261. let file = documentDir.appendingPathComponent(thumb)
  1262. if !FileManager().fileExists(atPath: file.path) {
  1263. try? FileManager.default.copyItem(at: sharedThumbURL, to: file)
  1264. }
  1265. }
  1266. }
  1267. attachmentFlag = "1"
  1268. } else if typeShare == typeVideo {
  1269. if let appGroupURL = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.nexilis.share") {
  1270. let sharedVideoURL = appGroupURL.appendingPathComponent(videoId)
  1271. let sharedThumbURL = appGroupURL.appendingPathComponent(thumb)
  1272. let documentDir = try FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
  1273. if FileManager.default.fileExists(atPath: sharedVideoURL.path) {
  1274. let file = documentDir.appendingPathComponent(videoId)
  1275. if !FileManager().fileExists(atPath: file.path) {
  1276. try? FileManager.default.copyItem(at: sharedVideoURL, to: file)
  1277. }
  1278. }
  1279. if FileManager.default.fileExists(atPath: sharedThumbURL.path) {
  1280. let file = documentDir.appendingPathComponent(thumb)
  1281. if !FileManager().fileExists(atPath: file.path) {
  1282. try? FileManager.default.copyItem(at: sharedThumbURL, to: file)
  1283. }
  1284. }
  1285. }
  1286. attachmentFlag = "2"
  1287. } else if typeShare == typeFile {
  1288. if let appGroupURL = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.nexilis.share") {
  1289. renamedFileId = "Nexilis_\(Date().currentTimeMillis())_" + fileId
  1290. let sharedFileURL = appGroupURL.appendingPathComponent(fileId)
  1291. let documentDir = try FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
  1292. if FileManager.default.fileExists(atPath: sharedFileURL.path) {
  1293. let file = documentDir.appendingPathComponent(renamedFileId)
  1294. if !FileManager().fileExists(atPath: file.path) {
  1295. try? FileManager.default.copyItem(at: sharedFileURL, to: file)
  1296. }
  1297. }
  1298. data = "\(fileId)|\(data)"
  1299. }
  1300. attachmentFlag = "6"
  1301. }
  1302. message = CoreMessage_TMessageBank.sendMessage(l_pin: groupId.isEmpty ? idContact : groupId, message_scope_id: scopeId, status: scopeId == "3" ? "1" : "2", message_text: data, credential: "0", attachment_flag: attachmentFlag, ex_blog_id: "", message_large_text: "", ex_format: "", image_id: imageId, audio_id: "", video_id: videoId, file_id: renamedFileId, thumb_id: thumb, reff_id: "", read_receipts: "4", chat_id: chatId, is_call_center: "0", call_center_id: "", opposite_pin: scopeId == "3" ? (User.getMyPin() ?? "") : idContact, gif_id: "", isForwarded: "0", isSecret: "0")
  1303. Nexilis.addQueueMessage(message: message)
  1304. userDefaults.set("", forKey: "sharedItem")
  1305. userDefaults.synchronize()
  1306. }
  1307. } catch {
  1308. print("Error parsing JSON: \(error)")
  1309. }
  1310. }
  1311. }
  1312. }
  1313. }
  1314. DispatchQueue.global().asyncAfter(deadline: .now() + 0.5, execute: {
  1315. NotificationCenter.default.post(name: NSNotification.Name(rawValue: "reloadTabChats"), object: nil, userInfo: nil)
  1316. })
  1317. }
  1318. }
  1319. public static func setDataForShareExtension() {
  1320. DispatchQueue.global().async {
  1321. if let userDefaults = UserDefaults(suiteName: "group.nexilis.share") {
  1322. Database.shared.database?.inTransaction({ (fmdb, rollback) in
  1323. var dataShared: [[String: Any]] = []
  1324. if let cursor = Database.shared.getRecords(fmdb: fmdb, query: "SELECT f_pin id, image_id image, first_name || ' ' || ifnull(last_name, '') name FROM BUDDY WHERE f_pin != '\(User.getMyPin() ?? "")' AND f_pin != '-997' AND official_account != '1'") {
  1325. while cursor.next() {
  1326. var dataTemp: [String: Any] = [:]
  1327. for columnIndex in 0..<cursor.columnCount {
  1328. if let columnName = cursor.columnName(for: columnIndex) {
  1329. if let value = cursor.object(forColumn: columnName) {
  1330. if columnName == "image" {
  1331. dataTemp[columnName] = value
  1332. if let imageString = dataTemp[columnName] as? String, !imageString.isEmpty {
  1333. do {
  1334. let documentDir = try FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
  1335. let file = documentDir.appendingPathComponent(imageString)
  1336. if FileManager().fileExists(atPath: file.path) {
  1337. if let appGroupURL = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.nexilis.share") {
  1338. let sharedFileURL = appGroupURL.appendingPathComponent(imageString)
  1339. if !FileManager.default.fileExists(atPath: sharedFileURL.path) {
  1340. try? FileManager.default.copyItem(at: file, to: sharedFileURL)
  1341. }
  1342. }
  1343. }
  1344. } catch {
  1345. }
  1346. }
  1347. } else {
  1348. dataTemp[columnName] = value
  1349. }
  1350. dataTemp["type"] = 0
  1351. }
  1352. }
  1353. }
  1354. dataShared.append(dataTemp)
  1355. }
  1356. cursor.close()
  1357. }
  1358. if let cursor = Database.shared.getRecords(fmdb: fmdb, query: "SELECT group_id id, image_id image, f_name name FROM GROUPZ WHERE official != 1") {
  1359. while cursor.next() {
  1360. var dataTemp: [String: Any] = [:]
  1361. for columnIndex in 0..<cursor.columnCount {
  1362. if let columnName = cursor.columnName(for: columnIndex) {
  1363. if let value = cursor.object(forColumn: columnName) {
  1364. if columnName == "name" {
  1365. dataTemp[columnName] = "\(value) (Lounge)"
  1366. } else if columnName == "image" {
  1367. dataTemp[columnName] = value
  1368. if let imageString = dataTemp[columnName] as? String, !imageString.isEmpty {
  1369. do {
  1370. let documentDir = try FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
  1371. let file = documentDir.appendingPathComponent(imageString)
  1372. if FileManager().fileExists(atPath: file.path) {
  1373. if let appGroupURL = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.nexilis.share") {
  1374. let sharedFileURL = appGroupURL.appendingPathComponent(imageString)
  1375. if !FileManager.default.fileExists(atPath: sharedFileURL.path) {
  1376. try? FileManager.default.copyItem(at: file, to: sharedFileURL)
  1377. }
  1378. }
  1379. }
  1380. } catch {
  1381. }
  1382. }
  1383. } else {
  1384. dataTemp[columnName] = value
  1385. }
  1386. dataTemp["type"] = 1
  1387. }
  1388. }
  1389. }
  1390. dataShared.append(dataTemp)
  1391. let group_id = cursor.string(forColumnIndex: 0) ?? ""
  1392. let image_group = cursor.string(forColumnIndex: 1) ?? ""
  1393. let name_group = cursor.string(forColumnIndex: 2) ?? ""
  1394. if let cursorTopic = Database.shared.getRecords(fmdb: fmdb, query: "SELECT chat_id id, thumb image, title name FROM DISCUSSION_FORUM WHERE group_id = '\(group_id)'") {
  1395. while cursorTopic.next() {
  1396. var dataTempTopic: [String: Any] = [:]
  1397. for columnIndex in 0..<cursorTopic.columnCount {
  1398. if let columnName = cursorTopic.columnName(for: columnIndex) {
  1399. if let value = cursorTopic.object(forColumn: columnName) {
  1400. if columnName == "name" {
  1401. dataTempTopic[columnName] = "\(name_group) (\(value))"
  1402. } else if columnName == "image" {
  1403. dataTempTopic[columnName] = "\(value)".isEmpty ? image_group : "\(value)"
  1404. if let imageString = dataTempTopic[columnName] as? String, !imageString.isEmpty {
  1405. do {
  1406. let documentDir = try FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
  1407. let file = documentDir.appendingPathComponent(imageString)
  1408. if FileManager().fileExists(atPath: file.path) {
  1409. if let appGroupURL = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.nexilis.share") {
  1410. let sharedFileURL = appGroupURL.appendingPathComponent(imageString)
  1411. if !FileManager.default.fileExists(atPath: sharedFileURL.path) {
  1412. try? FileManager.default.copyItem(at: file, to: sharedFileURL)
  1413. }
  1414. }
  1415. }
  1416. } catch {
  1417. }
  1418. }
  1419. } else {
  1420. dataTempTopic[columnName] = value
  1421. }
  1422. dataTempTopic["type"] = 1
  1423. }
  1424. }
  1425. }
  1426. dataShared.append(dataTempTopic)
  1427. }
  1428. cursorTopic.close()
  1429. }
  1430. }
  1431. cursor.close()
  1432. }
  1433. do {
  1434. let jsonData = try JSONSerialization.data(withJSONObject: dataShared, options: .prettyPrinted)
  1435. if let jsonString = String(data: jsonData, encoding: .utf8) {
  1436. userDefaults.set(jsonString, forKey: "shareContacts")
  1437. userDefaults.synchronize()
  1438. }
  1439. } catch {
  1440. print("Error converting to JSON: \(error)")
  1441. }
  1442. })
  1443. }
  1444. }
  1445. }
  1446. public static func setCheckEmulator(isActive: Bool) {
  1447. // Utils.bCheckEmulator = isActive
  1448. }
  1449. public static func setCheckRootedDevice(isActive: Bool) {
  1450. // Utils.bCheckRooted = isActive
  1451. }
  1452. public static func setPreventScreenCapture(isActive: Bool) {
  1453. // Utils.bPreventScreenCapture = isActive
  1454. }
  1455. public static func openImageNexilis(image: UIImage, data: Data? = nil, isGIF: Bool = false) {
  1456. let previewImageVC = PreviewAttachmentImageVideo(nibName: "PreviewAttachmentImageVideo", bundle: Bundle.resourceBundle(for: Nexilis.self))
  1457. previewImageVC.image = image
  1458. previewImageVC.isHiddenTextField = true
  1459. previewImageVC.isGIF = isGIF
  1460. previewImageVC.dataGIF = data
  1461. previewImageVC.modalPresentationStyle = .custom
  1462. previewImageVC.modalTransitionStyle = .crossDissolve
  1463. if UIApplication.shared.visibleViewController?.navigationController != nil {
  1464. UIApplication.shared.visibleViewController?.navigationController?.present(previewImageVC, animated: true, completion: nil)
  1465. } else {
  1466. UIApplication.shared.visibleViewController?.present(previewImageVC, animated: true, completion: nil)
  1467. }
  1468. }
  1469. public static func openVideoNexilis(videoURL: URL) {
  1470. let player = AVPlayer(url: videoURL)
  1471. let playerVC = AVPlayerViewController()
  1472. playerVC.modalPresentationStyle = .custom
  1473. playerVC.player = player
  1474. if UIApplication.shared.visibleViewController?.navigationController != nil {
  1475. UIApplication.shared.visibleViewController?.navigationController?.present(playerVC, animated: true, completion: nil)
  1476. } else {
  1477. UIApplication.shared.visibleViewController?.present(playerVC, animated: true, completion: nil)
  1478. }
  1479. }
  1480. private static var appNm = "";
  1481. public static func getAppNm() -> String {
  1482. return appNm
  1483. }
  1484. }
  1485. extension UINavigationController {
  1486. func defaultStyle() {
  1487. self.view.backgroundColor = self.traitCollection.userInterfaceStyle == .dark ? .black : .white
  1488. self.modalPresentationStyle = .fullScreen
  1489. self.navigationBar.tintColor = .white
  1490. self.navigationBar.barTintColor = self.traitCollection.userInterfaceStyle == .dark ? .blackDarkMode : .mainColor
  1491. self.navigationBar.isTranslucent = false
  1492. self.navigationBar.overrideUserInterfaceStyle = .dark
  1493. self.navigationBar.barStyle = .black
  1494. let cancelButtonAttributes: [NSAttributedString.Key: Any] = [NSAttributedString.Key.foregroundColor: UIColor.white, NSAttributedString.Key.font : UIFont.systemFont(ofSize: 16)]
  1495. UIBarButtonItem.appearance().setTitleTextAttributes(cancelButtonAttributes, for: .normal)
  1496. let textAttributes = [NSAttributedString.Key.foregroundColor:UIColor.white]
  1497. self.navigationBar.titleTextAttributes = textAttributes
  1498. }
  1499. }