Nexilis.swift 192 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337
  1. //
  2. // Qmera.swift
  3. // Runner
  4. //
  5. // Created by Yayan Dwi on 15/04/20.
  6. // Copyright © 2020 The Chromium Authors. All rights reserved.
  7. //
  8. import Foundation
  9. import nuSDKService
  10. import AVFoundation
  11. import AVKit
  12. import UIKit
  13. import FMDB
  14. import QuickLook
  15. import NotificationBannerSwift
  16. public class Nexilis: NSObject {
  17. public static var sAPIKey = ""
  18. public static var ADDRESS = ADDRESS_RELEASE
  19. static let ADDRESS_33 = "192.168.0.33"
  20. // static let ADDRESS_RELEASE = "202.158.33.26" //CBN
  21. static let ADDRESS_RELEASE = "108.137.84.148" //AWS
  22. // static let PORT = 45328
  23. // static let PORT = 65328 // 33
  24. static var PORT = PORT_RELEASE
  25. static let PORT_33 = 62328
  26. static let PORT_RELEASE = 42328
  27. static var nSessionMode: Int! = 1
  28. static var dispatch: DispatchGroup?
  29. let callManager = CallManager()
  30. var providerDelegate: CallProviderDelegate?
  31. public static let shared = Nexilis()
  32. public static var broadcastTimer = Timer()
  33. public static var broadcastList = [[String: String]]()
  34. public static var onGoingPushCC: [String: String] = [:]
  35. public static var openBroadcast = false
  36. public static var loadingAlert = UIAlertController()
  37. private func createDelegate() {
  38. print("createDelegate...")
  39. callDelegate = self
  40. messageDelegate = self
  41. groupDelegate = self
  42. personInfoDelegate = self
  43. providerDelegate = CallProviderDelegate(callManager: callManager)
  44. }
  45. public static func connect(apiKey: String, delegate: ConnectDelegate, showButton: Bool = true, fromMAB: Bool = false) {
  46. do {
  47. Nexilis.shared.createDelegate()
  48. Nexilis.sAPIKey = apiKey
  49. Database.shared.openDatabase()
  50. IncomingThread.default.run()
  51. let address = Nexilis.getAddress(apiKey:apiKey)
  52. if address.count == 0 {
  53. return
  54. }
  55. UserDefaults.standard.set(address, forKey: "address")
  56. UserDefaults.standard.set(address[0], forKey: "server")
  57. Nexilis.dispatch = DispatchGroup()
  58. Nexilis.dispatch?.enter()
  59. var server = UserDefaults.standard.string(forKey: "server")
  60. if let s = server, let a = UserDefaults.standard.stringArray(forKey: "address"), s != a[0] {
  61. server = a[0]
  62. UserDefaults.standard.set(server, forKey: "server")
  63. }
  64. var ip = ""
  65. var port = 0
  66. if let s = server {
  67. let data = s.split(separator: ":")
  68. ip = String(data[0])
  69. if let p = Int(data[1]) {
  70. port = p
  71. }
  72. }
  73. Nexilis.ADDRESS = ip
  74. Nexilis.PORT = port
  75. print(API.sGetVersion())
  76. var id = ""
  77. if let device_id = UserDefaults.standard.string(forKey: "device_id") {
  78. try API.initConnection(bSwitchIP: false, sAPIK: apiKey, aAppMain: nil, cbiI: Callback(), sTCPAddr: Nexilis.ADDRESS, nTCPPort: Nexilis.PORT, sUserID: device_id, sStartWH: "09:00")
  79. } else if let me = UserDefaults.standard.string(forKey: "me") {
  80. try API.initConnection(bSwitchIP: false, sAPIK: apiKey, aAppMain: nil, cbiI: Callback(), sTCPAddr: Nexilis.ADDRESS, nTCPPort: Nexilis.PORT, sUserID: me, sStartWH: "09:00")
  81. } else {
  82. let uuid = UIDevice.current.identifierForVendor?.uuidString ?? "UNK-DEVICE"
  83. try API.initConnection(bSwitchIP: false, sAPIK: apiKey, aAppMain: nil, cbiI: Callback(), sTCPAddr: Nexilis.ADDRESS, nTCPPort: Nexilis.PORT, sUserID: uuid, sStartWH: "09:00")
  84. id = uuid
  85. }
  86. // wait until connection true
  87. Nexilis.dispatch?.wait()
  88. Nexilis.dispatch = nil
  89. // Nexilis.initiateAudio()
  90. if(!id.isEmpty && (UserDefaults.standard.string(forKey: "me") == nil)){
  91. if let response = Nexilis.writeSync(message: CoreMessage_TMessageBank.getSignUpApi(api: apiKey, p_pin: id), timeout: 30 * 1000){
  92. id = response.getBody(key: CoreMessage_TMessageKey.F_PIN, default_value: "")
  93. let enable_signup = (response.getBody(key: CoreMessage_TMessageKey.IS_ENABLED_ANONYMOUS, default_value: "0")) == "1"
  94. Utils.setForceAnonymous(value: enable_signup)
  95. if(!id.isEmpty) {
  96. Nexilis.changeUser(f_pin: id)
  97. UserDefaults.standard.setValue(id, forKey: "me")
  98. }
  99. }
  100. }
  101. if UserDefaults.standard.string(forKey: "apiKey") == nil {
  102. UserDefaults.standard.setValue(apiKey, forKey: "apiKey")
  103. }
  104. if let me = UserDefaults.standard.string(forKey: "me") {
  105. if Utils.getForceAnonymous() || (!Utils.getForceAnonymous() && Utils.getSetProfile()) {
  106. Database.shared.database?.inTransaction({ (fmdb, rollback) in
  107. if let cursorData = Database.shared.getRecords(fmdb: fmdb, query: "SELECT * FROM BUDDY where f_pin = '\(me)' ") {
  108. if !cursorData.next() {
  109. _ = Nexilis.write(message: CoreMessage_TMessageBank.getPostRegistration(p_pin: me))
  110. }
  111. cursorData.close()
  112. }
  113. })
  114. DispatchQueue.global().asyncAfter(deadline: .now() + 1.5, execute: {
  115. Database.shared.database?.inTransaction({ (fmdb, rollback) in
  116. if let cursorData = Database.shared.getRecords(fmdb: fmdb, query: "SELECT image_id FROM GROUPZ where group_type = 1 AND official = 1"), cursorData.next() {
  117. do {
  118. let documentDir = try FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
  119. let file = documentDir.appendingPathComponent(cursorData.string(forColumnIndex: 0)!)
  120. if !FileManager().fileExists(atPath: file.path) {
  121. Download().start(forKey: cursorData.string(forColumnIndex: 0)!) { (name, progress) in}
  122. }
  123. } catch {}
  124. cursorData.close()
  125. }
  126. })
  127. })
  128. }
  129. delegate.onSuccess(userId: me)
  130. if showButton {
  131. DispatchQueue.main.async {
  132. var viewController = UIApplication.shared.windows.first?.rootViewController
  133. var notNull = false
  134. while !notNull {
  135. viewController = UIApplication.shared.windows.first?.rootViewController
  136. if viewController != nil {
  137. notNull = true
  138. }
  139. }
  140. let fb = FloatingButton()
  141. if fromMAB {
  142. var vc = viewController
  143. if viewController is UINavigationController {
  144. vc = (viewController as! UINavigationController).rootViewController
  145. }
  146. vc?.view.addSubview(fb)
  147. fb.mySettingDelegate = vc as? any SettingMABDelegate
  148. } else {
  149. viewController?.view.addSubview(fb)
  150. }
  151. }
  152. }
  153. }
  154. Nexilis.destroyAll()
  155. OutgoingThread.default.run()
  156. InquiryThread.default.run()
  157. }
  158. catch {
  159. print(error)
  160. delegate.onFailed(error: "99:Something went wrong")
  161. }
  162. }
  163. public static func destroyAll() {
  164. let onGoingCC = UserDefaults.standard.string(forKey: "onGoingCC") ?? ""
  165. if !onGoingCC.isEmpty {
  166. let requester = onGoingCC.components(separatedBy: ",")[0]
  167. let officer = onGoingCC.isEmpty ? "" : onGoingCC.components(separatedBy: ",")[1]
  168. let complaintId = onGoingCC.isEmpty ? "" : onGoingCC.components(separatedBy: ",")[2]
  169. let idMe = UserDefaults.standard.string(forKey: "me")!
  170. let startTimeCC = UserDefaults.standard.string(forKey: "startTimeCC") ?? ""
  171. let date = "\(Date().currentTimeMillis())"
  172. Database.shared.database?.inTransaction({ (fmdb, rollback) in
  173. do {
  174. _ = try Database.shared.insertRecord(fmdb: fmdb, table: "CALL_CENTER_HISTORY", cvalues: [
  175. "type" : "0",
  176. "title" : "Contact Center".localized(),
  177. "time" : startTimeCC,
  178. "f_pin" : officer,
  179. "data" : complaintId,
  180. "time_end" : date,
  181. "complaint_id" : complaintId,
  182. "members" : "",
  183. "requester": requester
  184. ], replace: true)
  185. } catch {
  186. rollback.pointee = true
  187. print(error)
  188. }
  189. })
  190. if officer == idMe {
  191. _ = Nexilis.write(message: CoreMessage_TMessageBank.endCallCenter(complaint_id: complaintId, l_pin: requester))
  192. } else {
  193. if requester == idMe {
  194. _ = Nexilis.write(message: CoreMessage_TMessageBank.endCallCenter(complaint_id: complaintId, l_pin: officer))
  195. } else {
  196. _ = Nexilis.write(message: CoreMessage_TMessageBank.leaveCCRoomInvite(ticket_id: complaintId))
  197. }
  198. }
  199. UserDefaults.standard.removeObject(forKey: "onGoingCC")
  200. UserDefaults.standard.removeObject(forKey: "membersCC")
  201. UserDefaults.standard.removeObject(forKey: "startTimeCC")
  202. if UIApplication.shared.applicationState == .active {
  203. DispatchQueue.main.async {
  204. let imageView = UIImageView(image: UIImage(systemName: "info.circle"))
  205. imageView.tintColor = .white
  206. let banner = FloatingNotificationBanner(title: "Call Center Session has ended".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)
  207. banner.show()
  208. }
  209. }
  210. }
  211. if !Nexilis.onGoingPushCC.isEmpty {
  212. DispatchQueue.global().async {
  213. _ = Nexilis.write(message: CoreMessage_TMessageBank.timeOutRequestCallCenter(channel: Nexilis.onGoingPushCC["channel"]!, l_pin: Nexilis.onGoingPushCC["l_pin"]!))
  214. }
  215. }
  216. UserDefaults.standard.removeObject(forKey: "inEditorPersonal")
  217. UserDefaults.standard.removeObject(forKey: "inEditorGroup")
  218. UserDefaults.standard.removeObject(forKey: "waitingRequestCC")
  219. }
  220. public static func changeUser(f_pin: String){
  221. do {
  222. print("change user to fpin")
  223. Nexilis.dispatch = DispatchGroup()
  224. Nexilis.dispatch?.enter()
  225. try API.switchUser(cbiI: Callback(), sUserID: f_pin)
  226. // wait until connection true
  227. Nexilis.dispatch?.wait()
  228. Nexilis.dispatch = nil
  229. print("success change user to fpin")
  230. _ = Nexilis.write(message: CoreMessage_TMessageBank.getChangeConnectionID(p_pin: f_pin))
  231. } catch{
  232. print(error)
  233. }
  234. }
  235. public static func addQueueMessage(message: TMessage) {
  236. // OutgoingThread.default.addQueue(message: message)
  237. InquiryThread.default.addQueue(message: message)
  238. }
  239. public static func deleteQueueMessage(message: TMessage) {
  240. OutgoingThread.default.addQueue(message: message)
  241. }
  242. private static var wbDelegate: WhiteboardDelegate?
  243. private static var wbReceiver: WhiteboardReceiver?
  244. public static func setWhiteboardDelegate(delegate: WhiteboardDelegate?){
  245. Nexilis.wbDelegate = delegate
  246. }
  247. public static func getWhiteboardDelegate() -> WhiteboardDelegate? {
  248. return Nexilis.wbDelegate
  249. }
  250. public static func setWhiteboardReceiver(receiver: WhiteboardReceiver?){
  251. Nexilis.wbReceiver = receiver
  252. }
  253. public static func getWhiteboardReceiver() -> WhiteboardReceiver? {
  254. return Nexilis.wbReceiver
  255. }
  256. public static func getEditorPersonal() -> EditorPersonal {
  257. return AppStoryBoard.Palio.instance.instantiateViewController(identifier: "editorPersonalVC") as! EditorPersonal
  258. }
  259. public static func getEditorGroup() -> EditorGroup {
  260. return AppStoryBoard.Palio.instance.instantiateViewController(identifier: "editorGroupVC") as! EditorGroup
  261. }
  262. public static func getEditorStarMessage() -> EditorStarMessages {
  263. return AppStoryBoard.Palio.instance.instantiateViewController(identifier: "staredVC") as! EditorStarMessages
  264. }
  265. static func getAddress(apiKey: String) -> [String] {
  266. var result = [String]()
  267. let url = URL(string: "https://newuniverse.io/dipp/NuN1v3rs3/Qm3r4i0/get_ip?account=\(apiKey)")!
  268. let urlConfig = URLSessionConfiguration.default
  269. urlConfig.requestCachePolicy = .returnCacheDataElseLoad
  270. urlConfig.timeoutIntervalForRequest = 10.0
  271. urlConfig.timeoutIntervalForResource = 10.0
  272. let semaphore = DispatchSemaphore(value: 0)
  273. let task = URLSession(configuration: urlConfig).dataTask(with: url) {(data, response, error) in
  274. guard let data = data else {
  275. semaphore.signal()
  276. return
  277. }
  278. let html = String(data: data, encoding: .utf8)!
  279. let base64Address = html.components(separatedBy: "<body>")[1].components(separatedBy: "</body>")[0].trimmingCharacters(in: .whitespacesAndNewlines)
  280. if let addressData = Data(base64Encoded: base64Address), let decodeAddress = String(data: addressData, encoding: .utf8) {
  281. let rows = decodeAddress.trimmingCharacters(in: CharacterSet.newlines).split(separator: ",")
  282. for r in rows {
  283. let _address = r.split(separator: ":")
  284. var ip:String = ""
  285. let _data = _address[0].split(separator: ".", maxSplits: 4, omittingEmptySubsequences: false)
  286. ip.append(String(_data[3]))
  287. ip.append(".")
  288. ip.append(String(_data[1]))
  289. ip.append(".")
  290. ip.append(String(_data[0]))
  291. ip.append(".")
  292. ip.append(String(_data[2]))
  293. result.append(ip + ":" + _address[2])
  294. }
  295. }
  296. semaphore.signal()
  297. }
  298. task.resume()
  299. _ = semaphore.wait(timeout: .distantFuture)
  300. debugPrint("[App] getAddress:", result)
  301. return result
  302. }
  303. static func getCLMUserId() -> String {
  304. guard let me = UserDefaults.standard.string(forKey: "me") else {
  305. return ""
  306. }
  307. return me
  308. }
  309. public static func writeSync(message: TMessage, timeout: Int = 15 * 1000) -> TMessage? {
  310. do {
  311. print(">> SENDING MESSAGE >> ", message.toLogString())
  312. if let data = try API.sGetResponse(sRequest: message.pack(), lTimeout: timeout, bKeepTOResp: true) {
  313. let response = TMessage(data: data)
  314. print("<< RESPONSE MESSAGE << ", response.toLogString())
  315. return response
  316. }
  317. } catch {
  318. print(error)
  319. }
  320. return nil
  321. }
  322. public static func write(message: TMessage, timeout: Int = 15 * 1000) -> String? {
  323. do {
  324. if API.nGetCLXConnState() == 0 {
  325. return nil
  326. }
  327. print(">> SENDING MESSAGE >> ", message.toLogString())
  328. if message.getMedia().count == 0 {
  329. if let data = try API.sSend(sData: message.pack(), nPriority: 1, lTimeout: timeout) {
  330. print("<< RESPONSE MESSAGE << ", data)
  331. return data
  332. }
  333. }
  334. // media
  335. if let data = try API.sSend(abData: message.toBytes(), nPriority: 2, lTimeout: timeout) {
  336. print("<< RESPONSE MESSAGE << ", data)
  337. return data
  338. }
  339. } catch {
  340. print(error)
  341. }
  342. return nil
  343. }
  344. public static func writeDraw(data: String, timeout: Int = 15 * 1000) -> String? {
  345. do {
  346. if !API.bInetConnAvailable() {
  347. return nil
  348. }
  349. print(">> SENDING MESSAGE >> ", data)
  350. if let data = try API.sSend(sData: data, nPriority: 1, lTimeout: timeout) {
  351. print("<< RESPONSE MESSAGE << ", data)
  352. return data
  353. }
  354. } catch {
  355. print(error)
  356. }
  357. return nil
  358. }
  359. public static func response(packetId: String, message: TMessage, timeout: Int = 15 * 1000) -> String? {
  360. var result: String? = nil
  361. do {
  362. if !API.bInetConnAvailable() {
  363. return nil
  364. }
  365. print(">> RESPONSE >> " + packetId + " " + message.toLogString());
  366. result = try API.sSendResponse(sRequestID: packetId, sResponse: message.pack(), lTimeout: timeout)
  367. } catch {
  368. print(error)
  369. }
  370. return result
  371. }
  372. public static func setSpeaker(_ isEnabled: Bool) {
  373. do {
  374. API.adjustVolume(fValue: isEnabled ? 10.0: 3.0)
  375. } catch {
  376. }
  377. }
  378. // public static func initiateAudio() {
  379. // do {
  380. // try AVAudioSession.sharedInstance().setPreferredSampleRate(AVAudioSession.sharedInstance().sampleRate)
  381. // } catch {
  382. // }
  383. // }
  384. // public static func startAudio(isVideo: Bool = true) {
  385. // do {
  386. // try AVAudioSession.sharedInstance().setCategory(.playAndRecord, options: .defaultToSpeaker)
  387. // try AVAudioSession.sharedInstance().setMode(.voiceChat)
  388. // try AVAudioSession.sharedInstance().overrideOutputAudioPort(isVideo ? .speaker : .none)
  389. // try AVAudioSession.sharedInstance().setActive(true)
  390. // } catch {
  391. // }
  392. // }
  393. //
  394. // public static func stopAudio() {
  395. // do {
  396. // try AVAudioSession.sharedInstance().setCategory(.soloAmbient)
  397. // try AVAudioSession.sharedInstance().setMode(.default)
  398. // try AVAudioSession.sharedInstance().overrideOutputAudioPort(.none)
  399. // try AVAudioSession.sharedInstance().setActive(true)
  400. // } catch {
  401. // }
  402. // }
  403. public static func muteMicrophone(isMute: Bool!){
  404. do {
  405. if(isMute){
  406. try AVAudioSession.sharedInstance().setCategory(.playback)
  407. }
  408. else{
  409. try AVAudioSession.sharedInstance().setCategory(.playAndRecord)
  410. }
  411. }catch{
  412. print(error)
  413. }
  414. }
  415. public static func buttonClicked(index: Int, id: String = "") {
  416. print("BTNCLICK \(index) \(id)")
  417. if index == 2 {
  418. Nexilis.openUrl(url: id)
  419. } else if index == 3 {
  420. Nexilis.openNotificationCenter()
  421. } else if index == 6 {
  422. Nexilis.openChat()
  423. } else if index == 7 {
  424. Nexilis.openCall()
  425. } else if index == 8 {
  426. Nexilis.openStreaming()
  427. } else if index == 9 {
  428. Nexilis.openContactCenter()
  429. } else {
  430. Nexilis.openApp(id: id)
  431. }
  432. }
  433. public static func openContactCenter() {
  434. let isChangeProfile = Utils.getSetProfile()
  435. if !isChangeProfile {
  436. let alert = UIAlertController(title: "Change Profile".localized(), message: "You must change your name to use this feature".localized(), preferredStyle: .alert)
  437. alert.addAction(UIAlertAction(title: "OK".localized(), style: UIAlertAction.Style.default, handler: {(_) in
  438. let controller = AppStoryBoard.Palio.instance.instantiateViewController(withIdentifier: "signupsignin") as! SignUpSignIn
  439. controller.forceLogin = true
  440. let navigationController = UINavigationController(rootViewController: controller)
  441. navigationController.modalPresentationStyle = .fullScreen
  442. navigationController.navigationBar.tintColor = .white
  443. navigationController.navigationBar.barTintColor = .mainColor
  444. navigationController.navigationBar.isTranslucent = false
  445. let cancelButtonAttributes: [NSAttributedString.Key: Any] = [NSAttributedString.Key.foregroundColor: UIColor.white]
  446. UIBarButtonItem.appearance().setTitleTextAttributes(cancelButtonAttributes, for: .normal)
  447. let textAttributes = [NSAttributedString.Key.foregroundColor:UIColor.white]
  448. navigationController.navigationBar.titleTextAttributes = textAttributes
  449. navigationController.view.backgroundColor = .mainColor
  450. navigationController.navigationBar.overrideUserInterfaceStyle = .dark
  451. navigationController.navigationBar.barStyle = .black
  452. if UIApplication.shared.visibleViewController?.navigationController != nil {
  453. UIApplication.shared.visibleViewController?.navigationController?.present(navigationController, animated: true, completion: nil)
  454. } else {
  455. UIApplication.shared.visibleViewController?.present(navigationController, animated: true, completion: nil)
  456. }
  457. }))
  458. if UIApplication.shared.visibleViewController?.navigationController != nil {
  459. UIApplication.shared.visibleViewController?.navigationController?.present(alert, animated: true, completion: nil)
  460. } else {
  461. UIApplication.shared.visibleViewController?.present(alert, animated: true, completion: nil)
  462. }
  463. return
  464. }
  465. let isWaitingRequestCC = UserDefaults.standard.bool(forKey: "waitingRequestCC")
  466. if isWaitingRequestCC {
  467. let imageView = UIImageView(image: UIImage(systemName: "info.circle"))
  468. imageView.tintColor = .white
  469. 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)
  470. banner.show()
  471. return
  472. }
  473. let controller = AppStoryBoard.Palio.instance.instantiateViewController(identifier: "editorPersonalVC") as! EditorPersonal
  474. controller.isContactCenter = true
  475. let navigationController = UINavigationController(rootViewController: controller)
  476. navigationController.modalPresentationStyle = .fullScreen
  477. navigationController.navigationBar.tintColor = .white
  478. navigationController.navigationBar.barTintColor = .mainColor
  479. navigationController.navigationBar.isTranslucent = false
  480. navigationController.navigationBar.overrideUserInterfaceStyle = .dark
  481. navigationController.navigationBar.barStyle = .black
  482. let cancelButtonAttributes: [NSAttributedString.Key: Any] = [NSAttributedString.Key.foregroundColor: UIColor.white]
  483. UIBarButtonItem.appearance().setTitleTextAttributes(cancelButtonAttributes, for: .normal)
  484. let textAttributes = [NSAttributedString.Key.foregroundColor:UIColor.white]
  485. navigationController.navigationBar.titleTextAttributes = textAttributes
  486. navigationController.view.backgroundColor = .mainColor
  487. if UIApplication.shared.visibleViewController?.navigationController != nil {
  488. UIApplication.shared.visibleViewController?.navigationController?.present(navigationController, animated: true, completion: nil)
  489. } else {
  490. UIApplication.shared.visibleViewController?.present(navigationController, animated: true, completion: nil)
  491. }
  492. }
  493. public static func openChat() {
  494. let isChangeProfile = Utils.getSetProfile()
  495. if !isChangeProfile {
  496. let alert = UIAlertController(title: "Change Profile".localized(), message: "You must change your name to use this feature".localized(), preferredStyle: .alert)
  497. alert.addAction(UIAlertAction(title: "OK".localized(), style: UIAlertAction.Style.default, handler: {(_) in
  498. let controller = AppStoryBoard.Palio.instance.instantiateViewController(withIdentifier: "signupsignin") as! SignUpSignIn
  499. controller.forceLogin = true
  500. let navigationController = UINavigationController(rootViewController: controller)
  501. navigationController.modalPresentationStyle = .fullScreen
  502. navigationController.navigationBar.tintColor = .white
  503. navigationController.navigationBar.barTintColor = .mainColor
  504. navigationController.navigationBar.isTranslucent = false
  505. navigationController.navigationBar.overrideUserInterfaceStyle = .dark
  506. navigationController.navigationBar.barStyle = .black
  507. let cancelButtonAttributes: [NSAttributedString.Key: Any] = [NSAttributedString.Key.foregroundColor: UIColor.white]
  508. UIBarButtonItem.appearance().setTitleTextAttributes(cancelButtonAttributes, for: .normal)
  509. let textAttributes = [NSAttributedString.Key.foregroundColor:UIColor.white]
  510. navigationController.navigationBar.titleTextAttributes = textAttributes
  511. navigationController.view.backgroundColor = .mainColor
  512. if UIApplication.shared.visibleViewController?.navigationController != nil {
  513. UIApplication.shared.visibleViewController?.navigationController?.present(navigationController, animated: true, completion: nil)
  514. } else {
  515. UIApplication.shared.visibleViewController?.present(navigationController, animated: true, completion: nil)
  516. }
  517. }))
  518. if UIApplication.shared.visibleViewController?.navigationController != nil {
  519. UIApplication.shared.visibleViewController?.navigationController?.present(alert, animated: true, completion: nil)
  520. } else {
  521. UIApplication.shared.visibleViewController?.present(alert, animated: true, completion: nil)
  522. }
  523. return
  524. }
  525. let navigationController = AppStoryBoard.Palio.instance.instantiateViewController(withIdentifier: "contactChatNav") as! UINavigationController
  526. navigationController.modalPresentationStyle = .fullScreen
  527. navigationController.navigationBar.tintColor = .white
  528. navigationController.navigationBar.barTintColor = .mainColor
  529. navigationController.navigationBar.isTranslucent = false
  530. navigationController.navigationBar.overrideUserInterfaceStyle = .dark
  531. navigationController.navigationBar.barStyle = .black
  532. let cancelButtonAttributes: [NSAttributedString.Key: Any] = [NSAttributedString.Key.foregroundColor: UIColor.white]
  533. UIBarButtonItem.appearance().setTitleTextAttributes(cancelButtonAttributes, for: .normal)
  534. let textAttributes = [NSAttributedString.Key.foregroundColor:UIColor.white]
  535. navigationController.navigationBar.titleTextAttributes = textAttributes
  536. navigationController.view.backgroundColor = .mainColor
  537. if UIApplication.shared.visibleViewController?.navigationController != nil {
  538. UIApplication.shared.visibleViewController?.navigationController?.present(navigationController, animated: true, completion: nil)
  539. } else {
  540. UIApplication.shared.visibleViewController?.present(navigationController, animated: true, completion: nil)
  541. }
  542. }
  543. public static func openCall() {
  544. let isChangeProfile = Utils.getSetProfile()
  545. if !isChangeProfile {
  546. let alert = UIAlertController(title: "Change Profile".localized(), message: "You must change your name to use this feature".localized(), preferredStyle: .alert)
  547. alert.addAction(UIAlertAction(title: "OK".localized(), style: UIAlertAction.Style.default, handler: {(_) in
  548. let controller = AppStoryBoard.Palio.instance.instantiateViewController(withIdentifier: "signupsignin") as! SignUpSignIn
  549. controller.forceLogin = true
  550. let navigationController = UINavigationController(rootViewController: controller)
  551. navigationController.modalPresentationStyle = .fullScreen
  552. navigationController.navigationBar.tintColor = .white
  553. navigationController.navigationBar.barTintColor = .mainColor
  554. navigationController.navigationBar.isTranslucent = false
  555. navigationController.navigationBar.overrideUserInterfaceStyle = .dark
  556. navigationController.navigationBar.barStyle = .black
  557. let cancelButtonAttributes: [NSAttributedString.Key: Any] = [NSAttributedString.Key.foregroundColor: UIColor.white]
  558. UIBarButtonItem.appearance().setTitleTextAttributes(cancelButtonAttributes, for: .normal)
  559. let textAttributes = [NSAttributedString.Key.foregroundColor:UIColor.white]
  560. navigationController.navigationBar.titleTextAttributes = textAttributes
  561. navigationController.view.backgroundColor = .mainColor
  562. if UIApplication.shared.visibleViewController?.navigationController != nil {
  563. UIApplication.shared.visibleViewController?.navigationController?.present(navigationController, animated: true, completion: nil)
  564. } else {
  565. UIApplication.shared.visibleViewController?.present(navigationController, animated: true, completion: nil)
  566. }
  567. }))
  568. if UIApplication.shared.visibleViewController?.navigationController != nil {
  569. UIApplication.shared.visibleViewController?.navigationController?.present(alert, animated: true, completion: nil)
  570. } else {
  571. UIApplication.shared.visibleViewController?.present(alert, animated: true, completion: nil)
  572. }
  573. return
  574. }
  575. let callContact = AppStoryBoard.Palio.instance.instantiateViewController(withIdentifier: "contactSID")
  576. let navigationController = UINavigationController(rootViewController: callContact)
  577. navigationController.modalPresentationStyle = .fullScreen
  578. navigationController.navigationBar.tintColor = .white
  579. navigationController.navigationBar.barTintColor = .mainColor
  580. navigationController.navigationBar.isTranslucent = false
  581. navigationController.navigationBar.overrideUserInterfaceStyle = .dark
  582. navigationController.navigationBar.barStyle = .black
  583. let cancelButtonAttributes: [NSAttributedString.Key: Any] = [NSAttributedString.Key.foregroundColor: UIColor.white]
  584. UIBarButtonItem.appearance().setTitleTextAttributes(cancelButtonAttributes, for: .normal)
  585. let textAttributes = [NSAttributedString.Key.foregroundColor:UIColor.white]
  586. navigationController.navigationBar.titleTextAttributes = textAttributes
  587. navigationController.view.backgroundColor = .mainColor
  588. if UIApplication.shared.visibleViewController?.navigationController != nil {
  589. UIApplication.shared.visibleViewController?.navigationController?.present(navigationController, animated: true, completion: nil)
  590. } else {
  591. UIApplication.shared.visibleViewController?.present(navigationController, animated: true, completion: nil)
  592. }
  593. }
  594. public static func openStreaming() {
  595. let isChangeProfile = Utils.getSetProfile()
  596. if !isChangeProfile {
  597. let alert = UIAlertController(title: "Change Profile".localized(), message: "You must change your name to use this feature".localized(), preferredStyle: .alert)
  598. alert.addAction(UIAlertAction(title: "OK".localized(), style: UIAlertAction.Style.default, handler: {(_) in
  599. let controller = AppStoryBoard.Palio.instance.instantiateViewController(withIdentifier: "signupsignin") as! SignUpSignIn
  600. controller.forceLogin = true
  601. let navigationController = UINavigationController(rootViewController: controller)
  602. navigationController.modalPresentationStyle = .fullScreen
  603. navigationController.navigationBar.tintColor = .white
  604. navigationController.navigationBar.barTintColor = .mainColor
  605. navigationController.navigationBar.isTranslucent = false
  606. navigationController.navigationBar.overrideUserInterfaceStyle = .dark
  607. navigationController.navigationBar.barStyle = .black
  608. let cancelButtonAttributes: [NSAttributedString.Key: Any] = [NSAttributedString.Key.foregroundColor: UIColor.white]
  609. UIBarButtonItem.appearance().setTitleTextAttributes(cancelButtonAttributes, for: .normal)
  610. let textAttributes = [NSAttributedString.Key.foregroundColor:UIColor.white]
  611. navigationController.navigationBar.titleTextAttributes = textAttributes
  612. navigationController.view.backgroundColor = .mainColor
  613. if UIApplication.shared.visibleViewController?.navigationController != nil {
  614. UIApplication.shared.visibleViewController?.navigationController?.present(navigationController, animated: true, completion: nil)
  615. } else {
  616. UIApplication.shared.visibleViewController?.present(navigationController, animated: true, completion: nil)
  617. }
  618. }))
  619. if UIApplication.shared.visibleViewController?.navigationController != nil {
  620. UIApplication.shared.visibleViewController?.navigationController?.present(alert, animated: true, completion: nil)
  621. } else {
  622. UIApplication.shared.visibleViewController?.present(alert, animated: true, completion: nil)
  623. }
  624. return
  625. }
  626. let navigationController = UINavigationController(rootViewController: QmeraCreateStreamingViewController())
  627. navigationController.modalPresentationStyle = .fullScreen
  628. navigationController.navigationBar.tintColor = .white
  629. navigationController.navigationBar.barTintColor = .mainColor
  630. navigationController.navigationBar.isTranslucent = false
  631. navigationController.navigationBar.overrideUserInterfaceStyle = .dark
  632. navigationController.navigationBar.barStyle = .black
  633. let cancelButtonAttributes: [NSAttributedString.Key: Any] = [NSAttributedString.Key.foregroundColor: UIColor.white]
  634. UIBarButtonItem.appearance().setTitleTextAttributes(cancelButtonAttributes, for: .normal)
  635. let textAttributes = [NSAttributedString.Key.foregroundColor:UIColor.white]
  636. navigationController.navigationBar.titleTextAttributes = textAttributes
  637. navigationController.view.backgroundColor = .mainColor
  638. if UIApplication.shared.visibleViewController?.navigationController != nil {
  639. UIApplication.shared.visibleViewController?.navigationController?.present(navigationController, animated: true, completion: nil)
  640. } else {
  641. UIApplication.shared.visibleViewController?.present(navigationController, animated: true, completion: nil)
  642. }
  643. }
  644. public static func openUrl(isBNI: Bool = false, url: String = "") {
  645. let isChangeProfile = Utils.getSetProfile()
  646. if !isChangeProfile {
  647. let alert = UIAlertController(title: "Change Profile".localized(), message: "You must change your name to use this feature".localized(), preferredStyle: .alert)
  648. alert.addAction(UIAlertAction(title: "OK".localized(), style: UIAlertAction.Style.default, handler: {(_) in
  649. let controller = AppStoryBoard.Palio.instance.instantiateViewController(withIdentifier: "signupsignin") as! SignUpSignIn
  650. controller.forceLogin = true
  651. let navigationController = UINavigationController(rootViewController: controller)
  652. navigationController.modalPresentationStyle = .fullScreen
  653. navigationController.navigationBar.tintColor = .white
  654. navigationController.navigationBar.barTintColor = .mainColor
  655. navigationController.navigationBar.isTranslucent = false
  656. navigationController.navigationBar.overrideUserInterfaceStyle = .dark
  657. navigationController.navigationBar.barStyle = .black
  658. let cancelButtonAttributes: [NSAttributedString.Key: Any] = [NSAttributedString.Key.foregroundColor: UIColor.white]
  659. UIBarButtonItem.appearance().setTitleTextAttributes(cancelButtonAttributes, for: .normal)
  660. let textAttributes = [NSAttributedString.Key.foregroundColor:UIColor.white]
  661. navigationController.navigationBar.titleTextAttributes = textAttributes
  662. navigationController.view.backgroundColor = .mainColor
  663. if UIApplication.shared.visibleViewController?.navigationController != nil {
  664. UIApplication.shared.visibleViewController?.navigationController?.present(navigationController, animated: true, completion: nil)
  665. } else {
  666. UIApplication.shared.visibleViewController?.present(navigationController, animated: true, completion: nil)
  667. }
  668. }))
  669. if UIApplication.shared.visibleViewController?.navigationController != nil {
  670. UIApplication.shared.visibleViewController?.navigationController?.present(alert, animated: true, completion: nil)
  671. } else {
  672. UIApplication.shared.visibleViewController?.present(alert, animated: true, completion: nil)
  673. }
  674. return
  675. }
  676. let controller = BNIBookingWebView()
  677. if !isBNI {
  678. controller.customUrl = url
  679. }
  680. if UIApplication.shared.visibleViewController?.navigationController != nil {
  681. UIApplication.shared.visibleViewController?.navigationController?.present(controller, animated: true, completion: nil)
  682. } else {
  683. UIApplication.shared.visibleViewController?.present(controller, animated: true, completion: nil)
  684. }
  685. }
  686. public static func openNotificationCenter() {
  687. let isChangeProfile = Utils.getSetProfile()
  688. if !isChangeProfile {
  689. let alert = UIAlertController(title: "Change Profile".localized(), message: "You must change your name to use this feature".localized(), preferredStyle: .alert)
  690. alert.addAction(UIAlertAction(title: "OK".localized(), style: UIAlertAction.Style.default, handler: {(_) in
  691. let controller = AppStoryBoard.Palio.instance.instantiateViewController(withIdentifier: "signupsignin") as! SignUpSignIn
  692. controller.forceLogin = true
  693. let navigationController = UINavigationController(rootViewController: controller)
  694. navigationController.modalPresentationStyle = .fullScreen
  695. navigationController.navigationBar.tintColor = .white
  696. navigationController.navigationBar.barTintColor = .mainColor
  697. navigationController.navigationBar.isTranslucent = false
  698. navigationController.navigationBar.overrideUserInterfaceStyle = .dark
  699. navigationController.navigationBar.barStyle = .black
  700. let cancelButtonAttributes: [NSAttributedString.Key: Any] = [NSAttributedString.Key.foregroundColor: UIColor.white]
  701. UIBarButtonItem.appearance().setTitleTextAttributes(cancelButtonAttributes, for: .normal)
  702. let textAttributes = [NSAttributedString.Key.foregroundColor:UIColor.white]
  703. navigationController.navigationBar.titleTextAttributes = textAttributes
  704. navigationController.view.backgroundColor = .mainColor
  705. if UIApplication.shared.visibleViewController?.navigationController != nil {
  706. UIApplication.shared.visibleViewController?.navigationController?.present(navigationController, animated: true, completion: nil)
  707. } else {
  708. UIApplication.shared.visibleViewController?.present(navigationController, animated: true, completion: nil)
  709. }
  710. }))
  711. if UIApplication.shared.visibleViewController?.navigationController != nil {
  712. UIApplication.shared.visibleViewController?.navigationController?.present(alert, animated: true, completion: nil)
  713. } else {
  714. UIApplication.shared.visibleViewController?.present(alert, animated: true, completion: nil)
  715. }
  716. return
  717. }
  718. let controller = HistoryBroadcastViewController()
  719. let navigationController = UINavigationController(rootViewController: controller)
  720. navigationController.modalPresentationStyle = .fullScreen
  721. navigationController.navigationBar.tintColor = .white
  722. navigationController.navigationBar.barTintColor = .mainColor
  723. navigationController.navigationBar.isTranslucent = false
  724. navigationController.navigationBar.overrideUserInterfaceStyle = .dark
  725. navigationController.navigationBar.barStyle = .black
  726. let cancelButtonAttributes: [NSAttributedString.Key: Any] = [NSAttributedString.Key.foregroundColor: UIColor.white]
  727. UIBarButtonItem.appearance().setTitleTextAttributes(cancelButtonAttributes, for: .normal)
  728. let textAttributes = [NSAttributedString.Key.foregroundColor:UIColor.white]
  729. navigationController.navigationBar.titleTextAttributes = textAttributes
  730. navigationController.view.backgroundColor = .mainColor
  731. if UIApplication.shared.visibleViewController?.navigationController != nil {
  732. UIApplication.shared.visibleViewController?.navigationController?.present(navigationController, animated: true, completion: nil)
  733. } else {
  734. UIApplication.shared.visibleViewController?.present(navigationController, animated: true, completion: nil)
  735. }
  736. }
  737. public static func openApp(id: String) {
  738. print("openApp itms-apps://apple.com/app/\(id)")
  739. let isChangeProfile = Utils.getSetProfile()
  740. if !isChangeProfile {
  741. let alert = UIAlertController(title: "Change Profile".localized(), message: "You must change your name to use this feature".localized(), preferredStyle: .alert)
  742. alert.addAction(UIAlertAction(title: "OK".localized(), style: UIAlertAction.Style.default, handler: {(_) in
  743. let controller = AppStoryBoard.Palio.instance.instantiateViewController(withIdentifier: "signupsignin") as! SignUpSignIn
  744. controller.forceLogin = true
  745. let navigationController = UINavigationController(rootViewController: controller)
  746. navigationController.modalPresentationStyle = .fullScreen
  747. navigationController.navigationBar.tintColor = .white
  748. navigationController.navigationBar.barTintColor = .mainColor
  749. navigationController.navigationBar.isTranslucent = false
  750. navigationController.navigationBar.overrideUserInterfaceStyle = .dark
  751. navigationController.navigationBar.barStyle = .black
  752. let cancelButtonAttributes: [NSAttributedString.Key: Any] = [NSAttributedString.Key.foregroundColor: UIColor.white]
  753. UIBarButtonItem.appearance().setTitleTextAttributes(cancelButtonAttributes, for: .normal)
  754. let textAttributes = [NSAttributedString.Key.foregroundColor:UIColor.white]
  755. navigationController.navigationBar.titleTextAttributes = textAttributes
  756. navigationController.view.backgroundColor = .mainColor
  757. if UIApplication.shared.visibleViewController?.navigationController != nil {
  758. UIApplication.shared.visibleViewController?.navigationController?.present(navigationController, animated: true, completion: nil)
  759. } else {
  760. UIApplication.shared.visibleViewController?.present(navigationController, animated: true, completion: nil)
  761. }
  762. }))
  763. if UIApplication.shared.visibleViewController?.navigationController != nil {
  764. UIApplication.shared.visibleViewController?.navigationController?.present(alert, animated: true, completion: nil)
  765. } else {
  766. UIApplication.shared.visibleViewController?.present(alert, animated: true, completion: nil)
  767. }
  768. return
  769. }
  770. if id == nil {
  771. return
  772. }
  773. if let url = URL(string: "itms-apps://apple.com/app/\(id)") {
  774. UIApplication.shared.open(url)
  775. }
  776. }
  777. static var alertChangeProfile = UIAlertController()
  778. public static func checkIsChangePerson() -> Bool {
  779. let isChangeProfile = Utils.getSetProfile()
  780. if !isChangeProfile {
  781. alertChangeProfile.dismiss(animated: false)
  782. alertChangeProfile = UIAlertController(title: "Change Profile".localized(), message: "You must change your name to use this feature".localized().localized(), preferredStyle: .alert)
  783. alertChangeProfile.addAction(UIAlertAction(title: "Cancel".localized(), style: .destructive, handler: nil))
  784. alertChangeProfile.addAction(UIAlertAction(title: "OK".localized(), style: UIAlertAction.Style.default, handler: {(_) in
  785. let controller = AppStoryBoard.Palio.instance.instantiateViewController(withIdentifier: "signupsignin") as! SignUpSignIn
  786. controller.forceLogin = true
  787. let navigationController = UINavigationController(rootViewController: controller)
  788. navigationController.modalPresentationStyle = .fullScreen
  789. navigationController.navigationBar.tintColor = .white
  790. navigationController.navigationBar.barTintColor = .mainColor
  791. navigationController.navigationBar.isTranslucent = false
  792. navigationController.navigationBar.overrideUserInterfaceStyle = .dark
  793. navigationController.navigationBar.barStyle = .black
  794. let cancelButtonAttributes: [NSAttributedString.Key: Any] = [NSAttributedString.Key.foregroundColor: UIColor.white]
  795. UIBarButtonItem.appearance().setTitleTextAttributes(cancelButtonAttributes, for: .normal)
  796. let textAttributes = [NSAttributedString.Key.foregroundColor:UIColor.white]
  797. navigationController.navigationBar.titleTextAttributes = textAttributes
  798. navigationController.view.backgroundColor = .mainColor
  799. let rootVC = UIApplication.shared.windows.filter {$0.isKeyWindow}.first?.rootViewController
  800. if rootVC?.presentedViewController == nil {
  801. rootVC?.present(navigationController, animated: true, completion: nil)
  802. } else {
  803. rootVC?.presentedViewController?.present(navigationController, animated: true, completion: nil)
  804. }
  805. }))
  806. let rootVC = UIApplication.shared.windows.filter {$0.isKeyWindow}.first?.rootViewController
  807. if rootVC?.presentedViewController == nil {
  808. rootVC?.present(alertChangeProfile, animated: true, completion: nil)
  809. } else {
  810. rootVC?.presentedViewController?.present(alertChangeProfile, animated: true, completion: nil)
  811. }
  812. return false
  813. }
  814. return true
  815. }
  816. public static func showLoader() {
  817. loadingAlert = UIAlertController(title: nil, message: "Please wait...".localized(), preferredStyle: .alert)
  818. let loadingIndicator = UIActivityIndicatorView(frame: CGRect(x: 10, y: 5, width: 50, height: 50))
  819. loadingIndicator.hidesWhenStopped = true
  820. loadingIndicator.style = .medium
  821. loadingIndicator.startAnimating()
  822. loadingAlert.view.addSubview(loadingIndicator)
  823. UIApplication.shared.visibleViewController?.present(loadingAlert, animated: true, completion: nil)
  824. }
  825. public static func hideLoader(completion: @escaping () -> ()) {
  826. loadingAlert.dismiss(animated: true, completion: completion)
  827. }
  828. private static var groupWait = DispatchGroup()
  829. private static var waitQueue = [String: TMessage]()
  830. private static var onDispatchGroupLeave = ""
  831. public static func writeAndWait(message: TMessage, timeout: Int = 15 * 1000) -> TMessage? {
  832. groupWait.enter()
  833. _ = write(message: message, timeout: timeout)
  834. waitQueue[message.getStatus()] = message
  835. if groupWait.wait(timeout: .now() + 15) == .timedOut {
  836. waitQueue.removeValue(forKey: message.getStatus())
  837. groupWait.leave()
  838. return nil
  839. }
  840. return waitQueue.removeValue(forKey: message.getStatus())
  841. }
  842. static func incomingData(packetId: String, data: AnyObject) {
  843. let message = TMessage()
  844. if data is String {
  845. let d = data as! String
  846. guard message.unpack(data: d) else {
  847. print("UNKNOWN DATA STRING...", data)
  848. if(data.hasPrefix("WB")){
  849. let dataWB = data.components(separatedBy: "/")
  850. if(dataWB[1] == "1"){
  851. let x = dataWB[2]
  852. let y = dataWB[3]
  853. let w = dataWB[4]
  854. let h = dataWB[5]
  855. let fc = dataWB[6]
  856. let sw = dataWB[7]
  857. let xo = dataWB[8]
  858. let yo = dataWB[9]
  859. if(Nexilis.getWhiteboardDelegate() != nil){
  860. Nexilis.getWhiteboardDelegate()!.draw(x: x, y: y, w: w, h: h, fc: fc, sw: sw, xo: xo, yo: yo, data: "")
  861. }
  862. } else if(dataWB[1] == "3") {
  863. if(Nexilis.getWhiteboardDelegate() != nil){
  864. Nexilis.getWhiteboardDelegate()!.clear()
  865. }
  866. } else if(dataWB[1] == "2"){
  867. if(Nexilis.getWhiteboardReceiver() != nil){
  868. Nexilis.getWhiteboardReceiver()!.incomingWB(roomId: dataWB[2])
  869. }
  870. } else if(dataWB[1] == "22"){
  871. } else if(dataWB[1] == "88"){
  872. if(Nexilis.getWhiteboardReceiver() != nil){
  873. Nexilis.getWhiteboardReceiver()!.cancel(roomId: dataWB[2])
  874. }
  875. }
  876. }
  877. return
  878. }
  879. } else if data is [UInt8] {
  880. let d = data as! [UInt8]
  881. guard message.unpack(bytes_data: d) else {
  882. print("UNKNOWN DATA BYTES...", data)
  883. return
  884. }
  885. }
  886. message.mBodies[CoreMessage_TMessageKey.PACKET_ID] = packetId
  887. if let _ = waitQueue[message.getStatus()] {
  888. print("MESSAGE INCOMING DATA \(message.toLogString())")
  889. if message.mBodies.keys.contains(CoreMessage_TMessageKey.ERRCOD) {
  890. if onDispatchGroupLeave != message.getStatus() {
  891. onDispatchGroupLeave = message.getStatus()
  892. print("LEAVE GROUP INCOMING DATA")
  893. waitQueue[message.getStatus()] = message
  894. groupWait.leave()
  895. return
  896. }
  897. }
  898. }
  899. IncomingThread.default.addQueue(message: message)
  900. }
  901. static func saveMessage(message: TMessage, withStatus: Bool = true) {
  902. guard let me = UserDefaults.standard.string(forKey: "me") else {
  903. return
  904. }
  905. let message_id = message.getBody(key : CoreMessage_TMessageKey.MESSAGE_ID, default_value : "")
  906. guard !message_id.isEmpty else {
  907. return
  908. }
  909. let f_pin = message.getBody(key : CoreMessage_TMessageKey.F_PIN, default_value : "")
  910. guard !f_pin.isEmpty else {
  911. return
  912. }
  913. Database.shared.database?.inTransaction({ (fmdb, rollback) in
  914. if let cursor = Database.shared.getRecords(fmdb: fmdb, query: "select message_id from MESSAGE where message_id = '\(message_id)'") {
  915. if cursor.next() {
  916. print("message exist")
  917. return
  918. }
  919. cursor.close()
  920. }
  921. let l_pin = message.getBody(key : CoreMessage_TMessageKey.L_PIN, default_value : "")
  922. let scope = message.getBody(key : CoreMessage_TMessageKey.MESSAGE_SCOPE_ID, default_value : "3")
  923. let status = message.getBody(key : CoreMessage_TMessageKey.STATUS, default_value : "")
  924. let chat_id = message.getBody(key : CoreMessage_TMessageKey.CHAT_ID, default_value : "")
  925. let broadcast_flag = message.getBody(key: CoreMessage_TMessageKey.BROADCAST_FLAG, default_value: "0")
  926. let is_call_center = message.getBody(key: CoreMessage_TMessageKey.IS_CALL_CENTER, default_value: "0")
  927. let call_center_id = message.getBody(key: CoreMessage_TMessageKey.CALL_CENTER_ID, default_value: "")
  928. let opposite_pin = message.getBody(key: CoreMessage_TMessageKey.OPPOSITE_PIN, default_value: "")
  929. print("prepare save db")
  930. do {
  931. _ = try Database.shared.insertRecord(fmdb: fmdb, table: "MESSAGE", cvalues: [
  932. "message_id" : message_id,
  933. "f_pin" : f_pin,
  934. "f_display_name" : message.getBody(key : CoreMessage_TMessageKey.F_DISPLAY_NAME, default_value : ""),
  935. "l_pin" : l_pin,
  936. "l_user_id" : message.getBody(key : CoreMessage_TMessageKey.L_USER_ID, default_value : ""),
  937. "message_scope_id" : scope,
  938. "server_date" : message.getBody(key: CoreMessage_TMessageKey.SERVER_DATE, default_value : String(Date().currentTimeMillis())),
  939. "status" : status,
  940. "message_text" : message.getBody(key : CoreMessage_TMessageKey.MESSAGE_TEXT, default_value : "").toNormalString(),
  941. "audio_id" : message.getBody(key : CoreMessage_TMessageKey.AUDIO_ID, default_value : ""),
  942. "video_id" : message.getBody(key : CoreMessage_TMessageKey.VIDEO_ID, default_value : ""),
  943. "image_id" : message.getBody(key : CoreMessage_TMessageKey.IMAGE_ID, default_value : ""),
  944. "file_id" : message.getBody(key : CoreMessage_TMessageKey.FILE_ID, default_value : ""),
  945. "thumb_id" : message.getBody(key : CoreMessage_TMessageKey.THUMB_ID, default_value : ""),
  946. "opposite_pin" : message.getBody(key : CoreMessage_TMessageKey.OPPOSITE_PIN, default_value : ""),
  947. "format" : message.getBody(key : CoreMessage_TMessageKey.FORMAT, default_value : ""),
  948. "blog_id" : message.getBody(key : CoreMessage_TMessageKey.BLOG_ID, default_value : ""),
  949. "read_receipts" : message.getBody(key: CoreMessage_TMessageKey.READ_RECEIPTS, default_value: "0"),
  950. "chat_id" : chat_id,
  951. "account_type" : message.getBody(key : CoreMessage_TMessageKey.BUSINESS_CATEGORY, default_value : "1"),
  952. "credential" : message.getBody(key : CoreMessage_TMessageKey.CREDENTIAL, default_value : ""),
  953. "reff_id" : message.getBody(key : CoreMessage_TMessageKey.REF_ID, default_value : ""),
  954. "message_large_text" : message.getBody(key : CoreMessage_TMessageKey.BODY, default_value : "").toNormalString(),
  955. "attachment_flag" : message.getBody(key: CoreMessage_TMessageKey.ATTACHMENT_FLAG, default_value: "0"),
  956. "local_timestamp" : message.getBody(key: CoreMessage_TMessageKey.LOCAL_TIMESTAMP, default_value : String(Date().currentTimeMillis())),
  957. "broadcast_flag" : broadcast_flag,
  958. "is_call_center" : is_call_center,
  959. "call_center_id" : call_center_id
  960. ], replace: true)
  961. } catch {
  962. rollback.pointee = true
  963. print(error)
  964. }
  965. if withStatus {
  966. do {
  967. if scope == "4" {
  968. for pin in getGroupMembers(fmdb: fmdb, l_pin: l_pin) {
  969. if f_pin == pin { continue }
  970. _ = try Database.shared.insertRecord(fmdb: fmdb, table: "MESSAGE_STATUS", cvalues: [
  971. "message_id" : message_id,
  972. "status" : status,
  973. "f_pin" : pin,
  974. "last_update" : Date().currentTimeMillis()
  975. ], replace: true)
  976. }
  977. } else {
  978. _ = try Database.shared.insertRecord(fmdb: fmdb, table: "MESSAGE_STATUS", cvalues: [
  979. "message_id" : message_id,
  980. "status" : status,
  981. "f_pin" : l_pin,
  982. "last_update" : Date().currentTimeMillis()
  983. ], replace: true)
  984. }
  985. } catch {
  986. rollback.pointee = true
  987. print(error)
  988. }
  989. } else {
  990. DispatchQueue.main.async {
  991. if let delegate = Nexilis.shared.messageDelegate, Utils.getSetProfile() {
  992. message.mBodies[CoreMessage_TMessageKey.MESSAGE_TEXT] = message.getBody(key : CoreMessage_TMessageKey.MESSAGE_TEXT, default_value : "").toNormalString()
  993. delegate.onReceive(message: message)
  994. }
  995. }
  996. }
  997. var pin = l_pin
  998. if l_pin == me {
  999. pin = f_pin
  1000. }
  1001. if !chat_id.isEmpty {
  1002. pin = chat_id
  1003. }
  1004. var counter : Int? = nil
  1005. if !withStatus {
  1006. if let cursor = Database.shared.getRecords(fmdb: fmdb, query: "select counter from MESSAGE_SUMMARY where l_pin = '\(pin)'"), cursor.next() {
  1007. counter = Int(cursor.int(forColumnIndex: 0))
  1008. counter! += 1
  1009. cursor.close()
  1010. print("select db message summary")
  1011. }
  1012. if counter == nil {
  1013. counter = 1
  1014. print("set counter message summary")
  1015. }
  1016. }
  1017. if counter == nil {
  1018. counter = 0
  1019. }
  1020. if is_call_center == "0" {
  1021. do {
  1022. let queryGetLastMessageId = "SELECT message_id FROM MESSAGE where opposite_pin = '\(opposite_pin)' OR l_pin = '\(pin)' order by server_date desc LIMIT 1"
  1023. var messageId = ""
  1024. if let cursorData = Database.shared.getRecords(fmdb: fmdb, query: queryGetLastMessageId), cursorData.next() {
  1025. messageId = cursorData.string(forColumnIndex: 0) ?? ""
  1026. cursorData.close()
  1027. }
  1028. if !messageId.isEmpty {
  1029. _ = try Database.shared.insertRecord(fmdb: fmdb, table: "MESSAGE_SUMMARY", cvalues: [
  1030. "l_pin" : pin,
  1031. "message_id" : messageId,
  1032. "counter" : counter!
  1033. ], replace: true)
  1034. }
  1035. } catch {
  1036. rollback.pointee = true
  1037. print(error)
  1038. }
  1039. }
  1040. print("insert db message summary \(message_id)")
  1041. })
  1042. }
  1043. public static func saveMessageBot(textMessage: String, blog_id: String, attachment_type:String)->Void{
  1044. guard let me = UserDefaults.standard.string(forKey: "me") else {
  1045. return
  1046. }
  1047. var user_id:String? = ""
  1048. let message_id = me + CoreMessage_TMessageUtil.getTID()
  1049. Database.shared.database?.inTransaction({ (fmdb, rollback) in
  1050. if let cursor = Database.shared.getRecords(fmdb: fmdb, query: "select user_id from BUDDY where f_pin = '\(me)'"), cursor.next() {
  1051. user_id = cursor.string(forColumnIndex: 0)
  1052. cursor.close()
  1053. }
  1054. })
  1055. Database.shared.database?.inTransaction({ (fmdb, rollback) in
  1056. do {
  1057. _ = try Database.shared.insertRecord(fmdb: fmdb, table: "MESSAGE", cvalues: [
  1058. "message_id" : message_id ,
  1059. "f_pin" : "-999",
  1060. "f_display_name" : "Bot",
  1061. "l_pin" : me,
  1062. "l_user_id" : String(user_id!),
  1063. "message_scope_id" : "3",
  1064. "server_date" : String(Date().currentTimeMillis()),
  1065. "status" : "3",
  1066. "message_text" : textMessage,
  1067. "audio_id" : "",
  1068. "video_id" : "",
  1069. "image_id" : "",
  1070. "file_id" : "",
  1071. "thumb_id" : "",
  1072. "opposite_pin" : "",
  1073. "format" : "",
  1074. "blog_id" : blog_id,
  1075. "read_receipts" : "0",
  1076. "chat_id" : "",
  1077. "account_type" : "1",
  1078. "credential" :"",
  1079. "reff_id" : "",
  1080. "message_large_text" : "",
  1081. "attachment_flag" : attachment_type,
  1082. "local_timestamp" : String(Date().currentTimeMillis())
  1083. ], replace: true)
  1084. } catch {
  1085. rollback.pointee = true
  1086. print(error)
  1087. }
  1088. })
  1089. let pin = "-999"
  1090. var counter : Int? = nil
  1091. Database.shared.database?.inTransaction({ (fmdb, rollback) in
  1092. if let cursor = Database.shared.getRecords(fmdb: fmdb, query: "select counter from MESSAGE_SUMMARY where l_pin = '\(pin)'"), cursor.next() {
  1093. counter = Int(cursor.int(forColumnIndex: 0))
  1094. counter! += 1
  1095. cursor.close()
  1096. print("select db message summary")
  1097. }
  1098. })
  1099. if counter == nil {
  1100. counter = 1
  1101. print("set counter message summary")
  1102. }
  1103. Database.shared.database?.inTransaction({ (fmdb, rollback) in
  1104. do {
  1105. _ = try Database.shared.insertRecord(fmdb: fmdb, table: "MESSAGE_SUMMARY", cvalues: [
  1106. "l_pin" : pin,
  1107. "message_id" : message_id,
  1108. "counter" : counter!
  1109. ], replace: true)
  1110. } catch {
  1111. rollback.pointee = true
  1112. print(error)
  1113. }
  1114. })
  1115. print("insert db message summary \(message_id)")
  1116. }
  1117. static func updateMessageStatus(message: TMessage) -> Void {
  1118. let message_id = message.getBody(key : CoreMessage_TMessageKey.MESSAGE_ID, default_value : "")
  1119. guard !message_id.isEmpty else {
  1120. return
  1121. }
  1122. let status = message.getBody(key : CoreMessage_TMessageKey.STATUS, default_value : "")
  1123. guard !status.isEmpty else {
  1124. return
  1125. }
  1126. let l_pin = message.getBody(key : CoreMessage_TMessageKey.L_PIN, default_value : "")
  1127. guard !l_pin.isEmpty else {
  1128. return
  1129. }
  1130. Database.shared.database?.inTransaction({ (fmdb, rollbac) in
  1131. if message_id.starts(with: "-1") || message_id.starts(with: "-2") {
  1132. for s in message_id.split(separator: ",") {
  1133. let t = s.trimmingCharacters(in: .whitespaces)
  1134. if t == "-1" || t == "-2" {
  1135. continue
  1136. }
  1137. if status == "3" {
  1138. _ = Database.shared.updateRecord(fmdb: fmdb, table: "MESSAGE_STATUS", cvalues: [
  1139. "status" : status,
  1140. "time_delivered" : String(Date().currentTimeMillis()),
  1141. "last_update" : String(Date().currentTimeMillis())], _where: "message_id = '\(t)' and f_pin = '\(l_pin)'")
  1142. } else if status == "4" {
  1143. _ = Database.shared.updateRecord(fmdb: fmdb, table: "MESSAGE_STATUS", cvalues: [
  1144. "status" : status,
  1145. "time_read" : String(Date().currentTimeMillis()),
  1146. "last_update" : String(Date().currentTimeMillis())], _where: "message_id = '\(t)' and f_pin = '\(l_pin)'")
  1147. } else if status == "8" {
  1148. _ = Database.shared.updateRecord(fmdb: fmdb, table: "MESSAGE_STATUS", cvalues: [
  1149. "status" : status,
  1150. "time_ack" : String(Date().currentTimeMillis()),
  1151. "last_update" : String(Date().currentTimeMillis())], _where: "message_id = '\(t)' and f_pin = '\(l_pin)'")
  1152. } else {
  1153. _ = Database.shared.updateRecord(fmdb: fmdb, table: "MESSAGE_STATUS", cvalues: [
  1154. "status" : status,
  1155. "last_update" : String(Date().currentTimeMillis())], _where: "message_id = '\(t)' and f_pin = '\(l_pin)'")
  1156. }
  1157. }
  1158. } else {
  1159. if status == "3" {
  1160. _ = Database.shared.updateRecord(fmdb: fmdb, table: "MESSAGE_STATUS", cvalues: [
  1161. "status" : status,
  1162. "time_delivered" : String(Date().currentTimeMillis()),
  1163. "last_update" : String(Date().currentTimeMillis())], _where: "message_id = '\(message_id)' and f_pin = '\(l_pin)'")
  1164. } else if status == "4" {
  1165. _ = Database.shared.updateRecord(fmdb: fmdb, table: "MESSAGE_STATUS", cvalues: [
  1166. "status" : status,
  1167. "time_read" : String(Date().currentTimeMillis()),
  1168. "last_update" : String(Date().currentTimeMillis())], _where: "message_id = '\(message_id)' and f_pin = '\(l_pin)'")
  1169. } else if status == "8" {
  1170. _ = Database.shared.updateRecord(fmdb: fmdb, table: "MESSAGE_STATUS", cvalues: [
  1171. "status" : status,
  1172. "time_ack" : String(Date().currentTimeMillis()),
  1173. "last_update" : String(Date().currentTimeMillis())], _where: "message_id = '\(message_id)' and f_pin = '\(l_pin)'")
  1174. } else {
  1175. _ = Database.shared.updateRecord(fmdb: fmdb, table: "MESSAGE_STATUS", cvalues: [
  1176. "status" : status,
  1177. "last_update" : String(Date().currentTimeMillis())], _where: "message_id = '\(message_id)' and f_pin = '\(l_pin)'")
  1178. }
  1179. }
  1180. })
  1181. }
  1182. static func getGroupMembers(fmdb: FMDatabase, l_pin: String) -> [String] {
  1183. var result = [String]()
  1184. if let cursor = Database.shared.getRecords(fmdb: fmdb, query: "select f_pin from GROUPZ_MEMBER where group_id = '\(l_pin)'") {
  1185. while cursor.next() {
  1186. if let value = cursor.string(forColumnIndex: 0) {
  1187. result.append(value)
  1188. }
  1189. }
  1190. cursor.close()
  1191. }
  1192. return result
  1193. }
  1194. static func getVideoThumbnail(name: String, completion: @escaping (Bool)->()) {
  1195. DispatchQueue.global().async {
  1196. do {
  1197. let fileManager = FileManager.default
  1198. let documentDir = try fileManager.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
  1199. let fileDir = documentDir.appendingPathComponent(name)
  1200. let path = fileDir.path
  1201. if FileManager.default.fileExists(atPath: path) {
  1202. let asset = AVAsset(url: URL(fileURLWithPath: path))
  1203. let avAssetImageGenerator = AVAssetImageGenerator(asset: asset)
  1204. avAssetImageGenerator.appliesPreferredTrackTransform = true
  1205. let thumnailTime = CMTimeMake(value: 2, timescale: 1)
  1206. let thumbImage = UIImage(cgImage: try avAssetImageGenerator.copyCGImage(at: thumnailTime, actualTime: nil))
  1207. guard let data = thumbImage.jpegData(compressionQuality: 1.0) else {
  1208. completion(false)
  1209. return
  1210. }
  1211. let thumbFileDir = documentDir.appendingPathComponent("THUMB_" + name)
  1212. try data.write(to: thumbFileDir)
  1213. completion(true)
  1214. } else {
  1215. completion(false)
  1216. }
  1217. } catch {
  1218. print(error)
  1219. }
  1220. }
  1221. }
  1222. static func resizedImage(at url: URL, for size: CGSize) -> UIImage? {
  1223. guard let image = UIImage(contentsOfFile: url.path) else {
  1224. return nil
  1225. }
  1226. let renderer = UIGraphicsImageRenderer(size: size)
  1227. return renderer.image { (context) in
  1228. image.draw(in: CGRect(origin: .zero, size: size))
  1229. }
  1230. }
  1231. static func initFollowing() -> Void {
  1232. if let me = UserDefaults.standard.string(forKey: "me") {
  1233. if let response = Nexilis.writeSync(message: CoreMessage_TMessageBank.getListFollowing(l_pin: me)) {
  1234. let data = response.getBody(key: CoreMessage_TMessageKey.DATA)
  1235. if !data.isEmpty {
  1236. if let jsonArray = try! JSONSerialization.jsonObject(with: data.data(using: String.Encoding.utf8)!, options: JSONSerialization.ReadingOptions()) as? [AnyObject] {
  1237. Database.shared.database?.inTransaction({ (fmdb, rollback) in
  1238. do {
  1239. for json in jsonArray {
  1240. _ = try Database.shared.insertRecord(fmdb: fmdb, table: "FOLLOW", cvalues: [
  1241. "f_pin" : CoreMessage_TMessageUtil.getString(json: json, key: "pin")
  1242. ], replace: true)
  1243. }
  1244. } catch {
  1245. rollback.pointee = true
  1246. print(error)
  1247. }
  1248. })
  1249. }
  1250. }
  1251. }
  1252. }
  1253. }
  1254. // do {
  1255. // _ = try Database.shared.insertRecord(fmdb: fmdb, table: "CALL_CENTER_HISTORY", cvalues: [
  1256. // "type" : "1",
  1257. // "title" : displayName,
  1258. // "time" : timeStart,
  1259. // "f_pin" : f_pin,
  1260. // "data" : dataCC,
  1261. // "time_end" : date,
  1262. // "complaint_id" : complaint_id.isEmpty ? "C\(date)" : complaint_id,
  1263. // "members" : "",
  1264. // "requester": ""
  1265. // ], replace: true)
  1266. // _ = try Database.shared.insertRecord(fmdb: fmdb, table: "PREFS", cvalues: [
  1267. // "key" : "CC:\(f_pin)",
  1268. // "value" : status,
  1269. // ], replace: true)
  1270. // ret = true
  1271. // } catch {
  1272. // rollback.pointee = true
  1273. // print(error)
  1274. // }
  1275. private static var uploadQueue = DispatchQueue(label: "UPLOAD_DICT", attributes: .concurrent)
  1276. private static var UPLOAD_DICT = [String: Network]()
  1277. static func removeUploadFile(forKey: String) -> Network? {
  1278. var _result: Network? = nil
  1279. uploadQueue.sync {
  1280. _result = self.UPLOAD_DICT.removeValue(forKey: forKey)
  1281. }
  1282. return _result
  1283. }
  1284. static func putUploadFile(forKey: String, uploader: Network) {
  1285. uploadQueue.async (flags: .barrier) {
  1286. self.UPLOAD_DICT[forKey] = uploader
  1287. }
  1288. }
  1289. static func getUploadFile(forKey: String) -> Network? {
  1290. var _result: Network? = nil
  1291. uploadQueue.sync {
  1292. _result = self.UPLOAD_DICT[forKey]
  1293. }
  1294. return _result
  1295. }
  1296. private static var downloadQueue = DispatchQueue(label: "DOWNLOAD_DICT", attributes: .concurrent)
  1297. private static var DOWNLOAD_DICT = [String:Download]()
  1298. static func addDownload(forKey : String, download: Download){
  1299. downloadQueue.async (flags: .barrier) {
  1300. self.DOWNLOAD_DICT[forKey] = download
  1301. }
  1302. }
  1303. static func getDownload(forKey: String) -> Download? {
  1304. var _result: Download? = nil
  1305. downloadQueue.sync {
  1306. _result = self.DOWNLOAD_DICT[forKey]
  1307. }
  1308. return _result
  1309. }
  1310. static func writeImageToFile(data: Data, fileName: String){
  1311. guard let directory = FileManager.default.urls(for: .picturesDirectory, in: .userDomainMask).last else {
  1312. return
  1313. }
  1314. let fileURL = directory.appendingPathComponent("\(fileName)")
  1315. if FileManager.default.fileExists(atPath: fileURL.path) {
  1316. if let fileHandle = FileHandle(forWritingAtPath: fileURL.path) {
  1317. fileHandle.seekToEndOfFile()
  1318. fileHandle.write(data)
  1319. fileHandle.closeFile()
  1320. } else {
  1321. print("Can't open file to write")
  1322. }
  1323. } else {
  1324. do {
  1325. try data.write(to: fileURL, options: .atomic)
  1326. } catch {
  1327. print("Unable to write in new file")
  1328. }
  1329. }
  1330. }
  1331. static func writeVideoToFile(data: Data, fileName: String){
  1332. guard let directory = FileManager.default.urls(for: .moviesDirectory, in: .userDomainMask).last else {
  1333. return
  1334. }
  1335. let fileURL = directory.appendingPathComponent("\(fileName)")
  1336. if FileManager.default.fileExists(atPath: fileURL.path) {
  1337. if let fileHandle = FileHandle(forWritingAtPath: fileURL.path) {
  1338. fileHandle.seekToEndOfFile()
  1339. fileHandle.write(data)
  1340. fileHandle.closeFile()
  1341. } else {
  1342. print("Can't open file to write")
  1343. }
  1344. } else {
  1345. do {
  1346. try data.write(to: fileURL, options: .atomic)
  1347. } catch {
  1348. print("Unable to write in new file")
  1349. }
  1350. }
  1351. }
  1352. static func writeDocumentsToFile(data: Data, fileName: String){
  1353. guard let directory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).last else {
  1354. return
  1355. }
  1356. let fileURL = directory.appendingPathComponent("\(fileName)")
  1357. if FileManager.default.fileExists(atPath: fileURL.path) {
  1358. if let fileHandle = FileHandle(forWritingAtPath: fileURL.path) {
  1359. fileHandle.seekToEndOfFile()
  1360. fileHandle.write(data)
  1361. fileHandle.closeFile()
  1362. } else {
  1363. print("Can't open file to write")
  1364. }
  1365. } else {
  1366. do {
  1367. try data.write(to: fileURL, options: .atomic)
  1368. } catch {
  1369. print("Unable to write in new file")
  1370. }
  1371. }
  1372. }
  1373. public static func checkMicPermission() -> Bool {
  1374. var permissionCheck: Bool = false
  1375. switch AVAudioSession.sharedInstance().recordPermission {
  1376. case .granted:
  1377. permissionCheck = true
  1378. case .denied:
  1379. permissionCheck = false
  1380. case .undetermined:
  1381. AVAudioSession.sharedInstance().requestRecordPermission({ (granted) in
  1382. if granted {
  1383. permissionCheck = true
  1384. } else {
  1385. permissionCheck = false
  1386. }
  1387. })
  1388. default:
  1389. break
  1390. }
  1391. return permissionCheck
  1392. }
  1393. public static func checkCameraPermission() -> Int {
  1394. var permissionCheck: Int = -1
  1395. if AVCaptureDevice.authorizationStatus(for: .video) == .authorized {
  1396. permissionCheck = 1
  1397. } else if AVCaptureDevice.authorizationStatus(for: .video) == .denied {
  1398. permissionCheck = 0
  1399. } else {
  1400. AVCaptureDevice.requestAccess(for: .video, completionHandler: { (granted: Bool) -> Void in
  1401. })
  1402. }
  1403. return permissionCheck
  1404. }
  1405. public static func startTimer(){
  1406. broadcastTimer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true, block: {_ in
  1407. if(!openBroadcast && !broadcastList.isEmpty){
  1408. openBroadcast = true
  1409. let m = broadcastList.removeFirst()
  1410. print("broadcast show: \(m)")
  1411. DispatchQueue.main.async {
  1412. Nexilis.shared.showBroadcastMessage(m: m)
  1413. }
  1414. }
  1415. })
  1416. }
  1417. /*
  1418. * Delegate
  1419. */
  1420. weak open var loginDelegate: LoginDelegate?
  1421. weak open var messageDelegate: MessageDelegate?
  1422. weak open var groupDelegate: GroupDelegate?
  1423. weak open var callDelegate: CallDelegate?
  1424. weak open var streamingDelagate: LiveStreamingDelegate?
  1425. weak open var personInfoDelegate: PersonInfoDelegate?
  1426. weak open var screenSharingDelegate: ScreenSharingDelegate?
  1427. weak open var commentDelegate: CommentDelegate?
  1428. weak open var uploadDelegate: UploadDelegate?
  1429. weak open var timelineDelegate: TimelineDelegate?
  1430. weak open var connectionDelegate: ConnectionDelegate?
  1431. var floating: FloatingNotificationBanner!
  1432. var stateUnfriend = ""
  1433. }
  1434. public protocol LoginDelegate: NSObjectProtocol {
  1435. func onProgress(code: String, progress: Int)
  1436. func onProcess(message: String, status: String)
  1437. }
  1438. public protocol MessageDelegate: NSObjectProtocol {
  1439. func onReceive(message: TMessage)
  1440. func onReceiveComment(message: TMessage)
  1441. func onReceive(message: [AnyHashable: Any?])
  1442. func onMessage(message: TMessage)
  1443. func onUpload(name: String, progress: Double)
  1444. func onTyping(message: TMessage)
  1445. }
  1446. public protocol GroupDelegate: NSObjectProtocol {
  1447. func onGroup(code: String, f_pin: String, groupId: String)
  1448. func onTopic(code: String, f_pin: String, topicId: String)
  1449. func onMember(code: String, f_pin: String, groupId: String, member: String)
  1450. }
  1451. public protocol DownloadDelegate: NSObjectProtocol {
  1452. func onDownloadProgress(fileName: String, progress: Double)
  1453. }
  1454. public protocol CallDelegate: NSObjectProtocol {
  1455. func onIncomingCall(state: Int, message: String)
  1456. func onStatusCall(state: Int, message: String)
  1457. }
  1458. public protocol LiveStreamingDelegate: NSObjectProtocol {
  1459. func onStartLS(state: Int, message: String)
  1460. func onJoinLS(state: Int, message: String)
  1461. }
  1462. public protocol VideoCallDelegate: NSObjectProtocol {
  1463. func onInitiateVideoCall(destination:String,state: Int, message: String)
  1464. func onAcceptVideoCall(originator:String,state: Int, message: String)
  1465. func onVideoCallReceiverTerminate(originator:String,state: Int, message: String)
  1466. }
  1467. public protocol PersonInfoDelegate: NSObjectProtocol {
  1468. func onUpdatePersonInfo(state: Int, message: String)
  1469. }
  1470. public protocol ScreenSharingDelegate: NSObjectProtocol {
  1471. func onStartScreenSharing(state:Int,message:String)
  1472. func onJoinScreenSharing(state:Int,message:String)
  1473. }
  1474. public protocol CommentDelegate: NSObjectProtocol {
  1475. func onReceiveComment(message: TMessage)
  1476. func onDeleteComment(message: TMessage)
  1477. }
  1478. public protocol UploadDelegate: NSObjectProtocol {
  1479. func onUploadProgress(fileName: String, progress: Double)
  1480. }
  1481. public protocol TimelineDelegate: NSObjectProtocol {
  1482. func onPostUpdate(status: String, message: String)
  1483. }
  1484. public protocol ConnectionDelegate: NSObjectProtocol {
  1485. func connectionStateChanged(userId: String!, deviceId: String, state: Bool)
  1486. }
  1487. public protocol ConnectDelegate: NSObjectProtocol {
  1488. func onSuccess(userId: String)
  1489. func onFailed(error: String)
  1490. }
  1491. public enum AppStoryBoard: String {
  1492. case Palio = "Palio"
  1493. public var instance: UIStoryboard {
  1494. return UIStoryboard(name: self.rawValue, bundle: Bundle.resourceBundle(for: Nexilis.self))
  1495. }
  1496. }
  1497. public var uuidOngoing = UUID()
  1498. extension Nexilis: CallDelegate {
  1499. func displayIncomingCall(uuid: UUID, handle: String, hasVideo: Bool = false, completion: ((Error?) -> Void)? = nil) {
  1500. providerDelegate?.reportIncomingCall(uuid: uuid, handle: handle, hasVideo: hasVideo, completion: completion)
  1501. }
  1502. public func onIncomingCall(state: Int, message: String) {
  1503. DispatchQueue.main.async {
  1504. let idMe = UserDefaults.standard.string(forKey: "me")!
  1505. let myData = User.getData(pin: idMe)
  1506. let onGoingCC = UserDefaults.standard.string(forKey: "onGoingCC") ?? ""
  1507. let deviceId = message.split(separator: ",")[0]
  1508. if myData?.offline_mode == "1" || self.stateUnfriend == deviceId {
  1509. DispatchQueue.main.asyncAfter(deadline: .now() + 0.5, execute: {
  1510. API.terminateCall(sParty: nil)
  1511. })
  1512. return
  1513. }
  1514. var isShowAlert: Double?
  1515. let canShow = UIApplication.shared.visibleViewController
  1516. if canShow != nil && !(canShow is UINavigationController) {
  1517. if !(canShow is EditorPersonal) {
  1518. isShowAlert = 0
  1519. } else {
  1520. isShowAlert = 1.5
  1521. }
  1522. } else if canShow != nil {
  1523. if canShow is UINavigationController {
  1524. let canShowNC = canShow as! UINavigationController
  1525. if !(canShowNC.visibleViewController is EditorPersonal) {
  1526. isShowAlert = 0
  1527. } else {
  1528. isShowAlert = 1.5
  1529. }
  1530. } else {
  1531. isShowAlert = 0
  1532. }
  1533. }
  1534. if (state == 21 && message.split(separator: ",")[1] != "joining Ac.room on channel 0") {
  1535. if onGoingCC.isEmpty {
  1536. let data = User.getDataCanNil(pin: String(deviceId))
  1537. if data == nil {
  1538. DispatchQueue.main.asyncAfter(deadline: .now() + 0.5, execute: {
  1539. API.terminateCall(sParty: nil)
  1540. })
  1541. return
  1542. }
  1543. // let backgroundTaskIdentifier = UIApplication.shared.beginBackgroundTask(expirationHandler: nil)
  1544. // uuidOngoing = UUID()
  1545. // self.displayIncomingCall(uuid: uuidOngoing, handle: String(deviceId), hasVideo: false) { error in
  1546. // UIApplication.shared.endBackgroundTask(backgroundTaskIdentifier)
  1547. // }
  1548. let controller = QmeraAudioViewController()
  1549. controller.user = User.getData(pin: String(deviceId))
  1550. controller.isOutgoing = false
  1551. controller.modalPresentationStyle = .overCurrentContext
  1552. if UIApplication.shared.visibleViewController is UIAlertController {
  1553. let vc = UIApplication.shared.visibleViewController as! UIAlertController
  1554. vc.dismiss(animated: true, completion: {
  1555. if UIApplication.shared.visibleViewController?.navigationController != nil {
  1556. UIApplication.shared.visibleViewController?.navigationController?.present(controller, animated: true, completion: nil)
  1557. } else {
  1558. UIApplication.shared.visibleViewController?.present(controller, animated: true, completion: nil)
  1559. }
  1560. })
  1561. return
  1562. }
  1563. if UIApplication.shared.visibleViewController?.navigationController != nil {
  1564. UIApplication.shared.visibleViewController?.navigationController?.present(controller, animated: true, completion: nil)
  1565. } else {
  1566. UIApplication.shared.visibleViewController?.present(controller, animated: true, completion: nil)
  1567. }
  1568. // API.receiveCCall(sParty: String(deviceId))
  1569. } else {
  1570. DispatchQueue.main.asyncAfter(deadline: .now() + isShowAlert!, execute: {
  1571. let controller = QmeraAudioViewController()
  1572. controller.user = User.getData(pin: String(deviceId))
  1573. controller.isOnGoing = true
  1574. controller.isOutgoing = false
  1575. controller.modalPresentationStyle = .overCurrentContext
  1576. if UIApplication.shared.visibleViewController?.navigationController != nil {
  1577. UIApplication.shared.visibleViewController?.navigationController?.present(controller, animated: true, completion: nil)
  1578. } else {
  1579. UIApplication.shared.visibleViewController?.present(controller, animated: true, completion: nil)
  1580. }
  1581. API.receiveCCall(sParty: String(deviceId))
  1582. })
  1583. }
  1584. } else if state == 31 {
  1585. let dataUser = User.getDataCanNil(pin: String(deviceId))
  1586. if dataUser == nil {
  1587. DispatchQueue.main.asyncAfter(deadline: .now() + 0.5, execute: {
  1588. API.terminateCall(sParty: nil)
  1589. })
  1590. return
  1591. }
  1592. let fpin = deviceId
  1593. var data: [String: String?] = [:]
  1594. Database.shared.database?.inTransaction({ (fmdb, rollback) in
  1595. if let cursorData = Database.shared.getRecords(fmdb: fmdb, query: "SELECT f_pin, first_name, last_name, official_account, image_id, device_id, offline_mode, user_type FROM BUDDY where f_pin = '\(fpin)'"), cursorData.next() {
  1596. data["f_pin"] = cursorData.string(forColumnIndex: 0)
  1597. var name = ""
  1598. if let firstname = cursorData.string(forColumnIndex: 1) {
  1599. name = firstname
  1600. }
  1601. if let lastname = cursorData.string(forColumnIndex: 2) {
  1602. name = name + " " + lastname
  1603. }
  1604. data["name"] = name
  1605. data["picture"] = cursorData.string(forColumnIndex: 4)
  1606. data["isOfficial"] = cursorData.string(forColumnIndex: 3)
  1607. data["deviceId"] = cursorData.string(forColumnIndex: 5)
  1608. data["isOffline"] = cursorData.string(forColumnIndex: 6)
  1609. data["user_type"] = cursorData.string(forColumnIndex: 7)
  1610. cursorData.close()
  1611. let videoController = AppStoryBoard.Palio.instance.instantiateViewController(withIdentifier: "videoVCQmera") as! QmeraVideoViewController
  1612. videoController.dataPerson.append(data)
  1613. videoController.isInisiator = false
  1614. if !onGoingCC.isEmpty {
  1615. videoController.users.append(User.getData(pin: data["f_pin"]!!, fmdb: fmdb)!)
  1616. }
  1617. let navigationController = UINavigationController(rootViewController: videoController)
  1618. navigationController.modalPresentationStyle = .fullScreen
  1619. if !onGoingCC.isEmpty {
  1620. videoController.isAutoAccept = true
  1621. DispatchQueue.main.asyncAfter(deadline: .now() + isShowAlert!, execute: {
  1622. if UIApplication.shared.visibleViewController is UIAlertController {
  1623. let vc = UIApplication.shared.visibleViewController as! UIAlertController
  1624. vc.dismiss(animated: true, completion: {
  1625. if UIApplication.shared.visibleViewController?.navigationController != nil {
  1626. UIApplication.shared.visibleViewController?.navigationController?.present(navigationController, animated: true, completion: nil)
  1627. } else {
  1628. UIApplication.shared.visibleViewController?.present(navigationController, animated: true, completion: nil)
  1629. }
  1630. })
  1631. return
  1632. }
  1633. if UIApplication.shared.visibleViewController?.navigationController != nil {
  1634. UIApplication.shared.visibleViewController?.navigationController?.present(navigationController, animated: true, completion: nil)
  1635. } else {
  1636. UIApplication.shared.visibleViewController?.present(navigationController, animated: true, completion: nil)
  1637. }
  1638. })
  1639. } else {
  1640. if UIApplication.shared.visibleViewController is UIAlertController {
  1641. let vc = UIApplication.shared.visibleViewController as! UIAlertController
  1642. vc.dismiss(animated: true, completion: {
  1643. if UIApplication.shared.visibleViewController?.navigationController != nil {
  1644. UIApplication.shared.visibleViewController?.navigationController?.present(navigationController, animated: true, completion: nil)
  1645. } else {
  1646. UIApplication.shared.visibleViewController?.present(navigationController, animated: true, completion: nil)
  1647. }
  1648. })
  1649. return
  1650. }
  1651. if UIApplication.shared.visibleViewController?.navigationController != nil {
  1652. UIApplication.shared.visibleViewController?.navigationController?.present(navigationController, animated: true, completion: nil)
  1653. } else {
  1654. UIApplication.shared.visibleViewController?.present(navigationController, animated: true, completion: nil)
  1655. }
  1656. }
  1657. }
  1658. })
  1659. }
  1660. }
  1661. }
  1662. public func onStatusCall(state: Int, message: String) {
  1663. let r = message.split(separator: ",")
  1664. if state == 23 {
  1665. if let call = callManager.call(with: String(r[0])) {
  1666. print("onStatusCall:connectingCall")
  1667. DispatchQueue.main.async {
  1668. call.connectingCall()
  1669. }
  1670. }
  1671. } else if state == 22 {
  1672. // if let call = callManager.call(with: String(r[1])) {
  1673. // print("onStatusCall:answerCall")
  1674. // DispatchQueue.main.async {
  1675. // call.answerCall()
  1676. // }
  1677. // }
  1678. } else if state == 28 {
  1679. DispatchQueue.main.async {
  1680. if QmeraAudioViewController().viewIfLoaded?.window == nil {
  1681. Nexilis.shared.callManager.end(call: Call(uuid: uuidOngoing))
  1682. }
  1683. }
  1684. }
  1685. var dataCall: [AnyHashable : Any] = [:]
  1686. dataCall["state"] = state
  1687. dataCall["message"] = message
  1688. NotificationCenter.default.post(name: NSNotification.Name(rawValue: "onStatusCall"), object: nil, userInfo: dataCall)
  1689. }
  1690. }
  1691. var previewItem : NSURL?
  1692. extension Nexilis: MessageDelegate {
  1693. public func onReceiveComment(message: TMessage) {
  1694. var dataMessage: [AnyHashable : Any] = [:]
  1695. dataMessage["message"] = message
  1696. NotificationCenter.default.post(name: NSNotification.Name(rawValue: "onReceiveComment"), object: nil, userInfo: dataMessage)
  1697. }
  1698. @objc func tapLinkBroadcast(_ sender: ObjectGesture) {
  1699. var stringURl = sender.message_id.lowercased()
  1700. if stringURl.starts(with: "www.") {
  1701. stringURl = "https://" + stringURl.replacingOccurrences(of: "www.", with: "")
  1702. }
  1703. guard let url = URL(string: stringURl) else { return }
  1704. UIApplication.shared.open(url)
  1705. }
  1706. func showBroadcastMessage(m: [String: String]) {
  1707. let fileType = m[CoreMessage_TMessageKey.CATEGORY_FLAG]!
  1708. let broadcastVC = UIViewController()
  1709. if let viewBroadcast = broadcastVC.view {
  1710. broadcastVC.modalPresentationStyle = .custom
  1711. viewBroadcast.backgroundColor = .black.withAlphaComponent(0.3)
  1712. let stringLink = m[CoreMessage_TMessageKey.LINK] ?? ""
  1713. let containerView = UIView()
  1714. viewBroadcast.addSubview(containerView)
  1715. if stringLink.isEmpty {
  1716. containerView.anchor(centerX: viewBroadcast.centerXAnchor, centerY: viewBroadcast.centerYAnchor, width: viewBroadcast.bounds.width - 40, minHeight: 100, maxHeight: viewBroadcast.bounds.height - 100)
  1717. } else {
  1718. containerView.anchor(centerX: viewBroadcast.centerXAnchor, centerY: viewBroadcast.centerYAnchor, width: viewBroadcast.bounds.width - 40, minHeight: 200, maxHeight: viewBroadcast.bounds.height - 100)
  1719. }
  1720. containerView.backgroundColor = .white.withAlphaComponent(0.9)
  1721. containerView.layer.cornerRadius = 15.0
  1722. containerView.clipsToBounds = true
  1723. let subContainerView = UIView()
  1724. subContainerView.backgroundColor = .clear
  1725. containerView.addSubview(subContainerView)
  1726. subContainerView.anchor(top: containerView.topAnchor, left: containerView.leftAnchor, bottom: containerView.bottomAnchor, right: containerView.rightAnchor, paddingTop: 20.0, paddingLeft: 10.0, paddingBottom: 20.0, paddingRight: 10.0)
  1727. let buttonClose = UIButton(type: .close)
  1728. buttonClose.frame.size = CGSize(width: 30, height: 30)
  1729. buttonClose.layer.cornerRadius = 15.0
  1730. buttonClose.clipsToBounds = true
  1731. buttonClose.backgroundColor = .secondaryColor.withAlphaComponent(0.5)
  1732. buttonClose.actionHandle(controlEvents: .touchUpInside,
  1733. ForAction:{() -> Void in
  1734. broadcastVC.dismiss(animated: true, completion: {
  1735. Nexilis.broadcastList.remove(at: 0)
  1736. if Nexilis.broadcastList.count > 0 {
  1737. Nexilis.shared.showBroadcastMessage(m: Nexilis.broadcastList[0])
  1738. }
  1739. })
  1740. })
  1741. containerView.addSubview(buttonClose)
  1742. buttonClose.anchor(top: containerView.topAnchor, right: containerView.rightAnchor, width: 30, height: 30)
  1743. let title = UILabel()
  1744. title.font = .systemFont(ofSize: 18, weight: .bold)
  1745. title.text = m["MERNAM"]
  1746. title.textAlignment = .center
  1747. subContainerView.addSubview(title)
  1748. title.anchor(top: subContainerView.topAnchor, left: subContainerView.leftAnchor, right: subContainerView.rightAnchor)
  1749. let titleBroadcast = UILabel()
  1750. subContainerView.addSubview(titleBroadcast)
  1751. titleBroadcast.translatesAutoresizingMaskIntoConstraints = false
  1752. NSLayoutConstraint.activate([
  1753. titleBroadcast.topAnchor.constraint(equalTo: title.bottomAnchor, constant: 20.0),
  1754. titleBroadcast.leadingAnchor.constraint(equalTo: subContainerView.leadingAnchor),
  1755. titleBroadcast.trailingAnchor.constraint(equalTo: subContainerView.trailingAnchor),
  1756. ])
  1757. titleBroadcast.font = UIFont.systemFont(ofSize: 14, weight: .semibold)
  1758. titleBroadcast.numberOfLines = 0
  1759. titleBroadcast.attributedText = m[CoreMessage_TMessageKey.TITLE]!.richText()
  1760. titleBroadcast.textColor = .black
  1761. let descBroadcast = UILabel()
  1762. subContainerView.addSubview(descBroadcast)
  1763. descBroadcast.translatesAutoresizingMaskIntoConstraints = false
  1764. let constraintDesc = descBroadcast.bottomAnchor.constraint(equalTo: subContainerView.bottomAnchor)
  1765. if !stringLink.isEmpty{
  1766. constraintDesc.constant = constraintDesc.constant - 30
  1767. }
  1768. if fileType != BroadcastViewController.FILE_TYPE_CHAT {
  1769. constraintDesc.constant = constraintDesc.constant - 260
  1770. }
  1771. NSLayoutConstraint.activate([
  1772. descBroadcast.topAnchor.constraint(equalTo: titleBroadcast.bottomAnchor, constant: 10),
  1773. descBroadcast.leadingAnchor.constraint(equalTo: subContainerView.leadingAnchor),
  1774. descBroadcast.trailingAnchor.constraint(equalTo: subContainerView.trailingAnchor),
  1775. constraintDesc,
  1776. ])
  1777. descBroadcast.font = UIFont.systemFont(ofSize: 12)
  1778. descBroadcast.numberOfLines = 0
  1779. descBroadcast.attributedText = m[CoreMessage_TMessageKey.MESSAGE_TEXT_ENG]!.richText()
  1780. descBroadcast.textColor = .black
  1781. let linkBroadcast = UILabel()
  1782. if !stringLink.isEmpty {
  1783. subContainerView.addSubview(linkBroadcast)
  1784. linkBroadcast.translatesAutoresizingMaskIntoConstraints = false
  1785. NSLayoutConstraint.activate([
  1786. linkBroadcast.topAnchor.constraint(equalTo: descBroadcast.bottomAnchor, constant: 10),
  1787. linkBroadcast.leadingAnchor.constraint(equalTo: subContainerView.leadingAnchor),
  1788. linkBroadcast.trailingAnchor.constraint(equalTo: subContainerView.trailingAnchor),
  1789. ])
  1790. linkBroadcast.font = UIFont.systemFont(ofSize: 12)
  1791. linkBroadcast.isUserInteractionEnabled = true
  1792. linkBroadcast.numberOfLines = 2
  1793. let attributedString = NSMutableAttributedString(string: stringLink, attributes:[NSAttributedString.Key.link: URL(string: stringLink)!])
  1794. linkBroadcast.attributedText = attributedString
  1795. let tap = ObjectGesture(target: self, action: #selector(tapLinkBroadcast))
  1796. tap.message_id = stringLink
  1797. linkBroadcast.addGestureRecognizer(tap)
  1798. }
  1799. let thumb = m[CoreMessage_TMessageKey.THUMB_ID] ?? ""
  1800. let image = m[CoreMessage_TMessageKey.IMAGE_ID] ?? ""
  1801. let video = m[CoreMessage_TMessageKey.VIDEO_ID] ?? ""
  1802. let file = m[CoreMessage_TMessageKey.FILE_ID] ?? ""
  1803. if fileType != BroadcastViewController.FILE_TYPE_CHAT {
  1804. let imageBroadcast = UIImageView()
  1805. subContainerView.addSubview(imageBroadcast)
  1806. imageBroadcast.translatesAutoresizingMaskIntoConstraints = false
  1807. var constImage = imageBroadcast.topAnchor.constraint(equalTo: descBroadcast.bottomAnchor, constant: 10)
  1808. if !stringLink.isEmpty {
  1809. constImage = imageBroadcast.topAnchor.constraint(equalTo: linkBroadcast.bottomAnchor, constant: 10)
  1810. }
  1811. NSLayoutConstraint.activate([
  1812. constImage,
  1813. imageBroadcast.leadingAnchor.constraint(equalTo: subContainerView.leadingAnchor),
  1814. imageBroadcast.trailingAnchor.constraint(equalTo: subContainerView.trailingAnchor),
  1815. imageBroadcast.heightAnchor.constraint(equalToConstant: 250)
  1816. ])
  1817. imageBroadcast.layer.cornerRadius = 10.0
  1818. imageBroadcast.clipsToBounds = true
  1819. if fileType != BroadcastViewController.FILE_TYPE_DOCUMENT {
  1820. imageBroadcast.contentMode = .scaleAspectFill
  1821. imageBroadcast.setImage(name: thumb)
  1822. if fileType == BroadcastViewController.FILE_TYPE_VIDEO {
  1823. let imagePlay = UIImageView(image: UIImage(systemName: "play.circle.fill"))
  1824. imageBroadcast.addSubview(imagePlay)
  1825. imagePlay.clipsToBounds = true
  1826. imagePlay.translatesAutoresizingMaskIntoConstraints = false
  1827. imagePlay.centerYAnchor.constraint(equalTo: imageBroadcast.centerYAnchor).isActive = true
  1828. imagePlay.centerXAnchor.constraint(equalTo: imageBroadcast.centerXAnchor).isActive = true
  1829. imagePlay.widthAnchor.constraint(equalToConstant: 60).isActive = true
  1830. imagePlay.heightAnchor.constraint(equalToConstant: 60).isActive = true
  1831. imagePlay.tintColor = .gray.withAlphaComponent(0.5)
  1832. }
  1833. } else {
  1834. imageBroadcast.image = UIImage(systemName: "doc.fill")
  1835. imageBroadcast.tintColor = .mainColor
  1836. imageBroadcast.contentMode = .scaleAspectFit
  1837. }
  1838. imageBroadcast.actionHandle(controlEvents: .touchUpInside,
  1839. ForAction:{() -> Void in
  1840. let nsDocumentDirectory = FileManager.SearchPathDirectory.documentDirectory
  1841. let nsUserDomainMask = FileManager.SearchPathDomainMask.userDomainMask
  1842. let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true)
  1843. if fileType == BroadcastViewController.FILE_TYPE_IMAGE {
  1844. if let dirPath = paths.first {
  1845. let imageURL = URL(fileURLWithPath: dirPath).appendingPathComponent(image)
  1846. if FileManager.default.fileExists(atPath: imageURL.path) {
  1847. let image = UIImage(contentsOfFile: imageURL.path)
  1848. let previewImageVC = PreviewAttachmentImageVideo(nibName: "PreviewAttachmentImageVideo", bundle: Bundle.resourceBundle(for: Nexilis.self))
  1849. previewImageVC.image = image
  1850. previewImageVC.isHiddenTextField = true
  1851. previewImageVC.modalPresentationStyle = .overFullScreen
  1852. previewImageVC.modalTransitionStyle = .crossDissolve
  1853. if UIApplication.shared.visibleViewController?.navigationController != nil {
  1854. UIApplication.shared.visibleViewController?.navigationController?.present(previewImageVC, animated: true, completion: nil)
  1855. } else {
  1856. UIApplication.shared.visibleViewController?.present(previewImageVC, animated: true, completion: nil)
  1857. }
  1858. } else {
  1859. Download().start(forKey: image) { (name, progress) in
  1860. guard progress == 100 else {
  1861. return
  1862. }
  1863. DispatchQueue.main.async {
  1864. let image = UIImage(contentsOfFile: imageURL.path)
  1865. let previewImageVC = PreviewAttachmentImageVideo(nibName: "PreviewAttachmentImageVideo", bundle: Bundle.resourceBundle(for: Nexilis.self))
  1866. previewImageVC.image = image
  1867. previewImageVC.isHiddenTextField = true
  1868. previewImageVC.modalPresentationStyle = .overFullScreen
  1869. previewImageVC.modalTransitionStyle = .crossDissolve
  1870. if UIApplication.shared.visibleViewController?.navigationController != nil {
  1871. UIApplication.shared.visibleViewController?.navigationController?.present(previewImageVC, animated: true, completion: nil)
  1872. } else {
  1873. UIApplication.shared.visibleViewController?.present(previewImageVC, animated: true, completion: nil)
  1874. }
  1875. }
  1876. }
  1877. }
  1878. }
  1879. } else if fileType == BroadcastViewController.FILE_TYPE_VIDEO {
  1880. //https://qmera.io/filepalio/image/
  1881. let player = AVPlayer(url: URL(string: "https://newuniverse.io/get_file?account=\(Nexilis.sAPIKey)&image=\(video)")!)
  1882. let playerVC = AVPlayerViewController()
  1883. playerVC.player = player
  1884. playerVC.modalPresentationStyle = .custom
  1885. if UIApplication.shared.visibleViewController?.navigationController != nil {
  1886. UIApplication.shared.visibleViewController?.navigationController?.present(playerVC, animated: true, completion: nil)
  1887. } else {
  1888. UIApplication.shared.visibleViewController?.present(playerVC, animated: true, completion: nil)
  1889. }
  1890. } else if fileType == BroadcastViewController.FILE_TYPE_DOCUMENT {
  1891. if let dirPath = paths.first {
  1892. let fileURL = URL(fileURLWithPath: dirPath).appendingPathComponent(file)
  1893. if FileManager.default.fileExists(atPath: fileURL.path) {
  1894. previewItem = fileURL as NSURL
  1895. let previewController = QLPreviewController()
  1896. let rightBarButton = UIBarButtonItem()
  1897. previewController.navigationItem.rightBarButtonItem = rightBarButton
  1898. previewController.dataSource = self
  1899. previewController.modalPresentationStyle = .overFullScreen
  1900. if UIApplication.shared.visibleViewController?.navigationController != nil {
  1901. UIApplication.shared.visibleViewController?.navigationController?.present(previewController, animated: true, completion: nil)
  1902. } else {
  1903. UIApplication.shared.visibleViewController?.present(previewController, animated: true, completion: nil)
  1904. }
  1905. } else {
  1906. Download().start(forKey: file) { (name, progress) in
  1907. DispatchQueue.main.async {
  1908. guard progress == 100 else {
  1909. return
  1910. }
  1911. previewItem = fileURL as NSURL
  1912. let previewController = QLPreviewController()
  1913. let rightBarButton = UIBarButtonItem()
  1914. previewController.navigationItem.rightBarButtonItem = rightBarButton
  1915. previewController.dataSource = self
  1916. previewController.modalPresentationStyle = .overFullScreen
  1917. if UIApplication.shared.visibleViewController?.navigationController != nil {
  1918. UIApplication.shared.visibleViewController?.navigationController?.present(previewController, animated: true, completion: nil)
  1919. } else {
  1920. UIApplication.shared.visibleViewController?.present(previewController, animated: true, completion: nil)
  1921. }
  1922. }
  1923. }
  1924. }
  1925. }
  1926. }
  1927. })
  1928. }
  1929. broadcastVC.modalTransitionStyle = .crossDissolve
  1930. if UIApplication.shared.visibleViewController?.navigationController != nil {
  1931. UIApplication.shared.visibleViewController?.navigationController?.present(broadcastVC, animated: true, completion: nil)
  1932. } else {
  1933. UIApplication.shared.visibleViewController?.present(broadcastVC, animated: true, completion: nil)
  1934. }
  1935. }
  1936. }
  1937. public func onReceive(message: TMessage) {
  1938. var dataMessage: [AnyHashable : Any] = [:]
  1939. dataMessage["message"] = message
  1940. NotificationCenter.default.post(name: NSNotification.Name(rawValue: "onReceiveChat"), object: nil, userInfo: dataMessage)
  1941. if message.getCode() == CoreMessage_TMessageCode.PUSH_CALL_CENTER {
  1942. DispatchQueue.main.async {
  1943. if Nexilis.onGoingPushCC.isEmpty {
  1944. var data: [String: String] = [:]
  1945. data["channel"] = message.getBody(key: CoreMessage_TMessageKey.CHANNEL)
  1946. data["l_pin"] = message.getBody(key: CoreMessage_TMessageKey.L_PIN)
  1947. data["f_display_name"] = message.getBody(key: CoreMessage_TMessageKey.F_DISPLAY_NAME)
  1948. Nexilis.onGoingPushCC = data
  1949. } else if Nexilis.onGoingPushCC["f_display_name"] == message.getBody(key: CoreMessage_TMessageKey.F_DISPLAY_NAME) {
  1950. return
  1951. }
  1952. let alert = UIAlertController(title: "", message: "\n\n\n\n\n\n\n\n\n\n".localized(), preferredStyle: .alert)
  1953. let newWidth = UIScreen.main.bounds.width * 0.90 - 270
  1954. // update width constraint value for main view
  1955. if let viewWidthConstraint = alert.view.constraints.filter({ return $0.firstAttribute == .width }).first{
  1956. viewWidthConstraint.constant = newWidth
  1957. }
  1958. // update width constraint value for container view
  1959. if let containerViewWidthConstraint = alert.view.subviews.first?.constraints.filter({ return $0.firstAttribute == .width }).first {
  1960. containerViewWidthConstraint.constant = newWidth
  1961. }
  1962. let titleFont = [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 18), NSAttributedString.Key.foregroundColor: UIColor.black]
  1963. let titleAttrString = NSMutableAttributedString(string: "Call Center".localized(), attributes: titleFont)
  1964. alert.setValue(titleAttrString, forKey: "attributedTitle")
  1965. alert.view.subviews.first?.subviews.first?.subviews.first?.backgroundColor = .lightGray
  1966. alert.view.tintColor = .black
  1967. let rejectAction = UIAlertAction(title: "Pass to other representative".localized(), style: .destructive, handler: {(_) in
  1968. DispatchQueue.global().async {
  1969. _ = Nexilis.write(message: CoreMessage_TMessageBank.timeOutRequestCallCenter(channel: message.getBody(key: CoreMessage_TMessageKey.CHANNEL), l_pin: message.getBody(key: CoreMessage_TMessageKey.L_PIN)))
  1970. }
  1971. Nexilis.onGoingPushCC.removeAll()
  1972. alert.dismiss(animated: true, completion: nil)
  1973. })
  1974. let acceptAction = UIAlertAction(title: "I'll handle the customer".localized(), style: .default, handler: {(_) in
  1975. let goAudioCall = Nexilis.checkMicPermission()
  1976. if !goAudioCall && message.getBody(key: CoreMessage_TMessageKey.CHANNEL) == "1" {
  1977. let alert = UIAlertController(title: "Attention!".localized(), message: "Please allow microphone permission in your settings".localized(), preferredStyle: .alert)
  1978. alert.addAction(UIAlertAction(title: "OK".localized(), style: UIAlertAction.Style.default, handler: { _ in
  1979. if let url = URL(string: UIApplication.openSettingsURLString), UIApplication.shared.canOpenURL(url) {
  1980. UIApplication.shared.open(url, options: [:], completionHandler: nil)
  1981. }
  1982. }))
  1983. if UIApplication.shared.visibleViewController?.navigationController != nil {
  1984. UIApplication.shared.visibleViewController?.navigationController?.present(alert, animated: true, completion: nil)
  1985. } else {
  1986. UIApplication.shared.visibleViewController?.present(alert, animated: true, completion: nil)
  1987. }
  1988. DispatchQueue.global().async {
  1989. DispatchQueue.global().async {
  1990. _ = Nexilis.write(message: CoreMessage_TMessageBank.timeOutRequestCallCenter(channel: message.getBody(key: CoreMessage_TMessageKey.CHANNEL), l_pin: message.getBody(key: CoreMessage_TMessageKey.L_PIN)))
  1991. }
  1992. }
  1993. Nexilis.onGoingPushCC.removeAll()
  1994. return
  1995. }
  1996. if message.getBody(key: CoreMessage_TMessageKey.CHANNEL) == "2" {
  1997. var permissionCheck = -1
  1998. if AVCaptureDevice.authorizationStatus(for: .video) == .authorized {
  1999. permissionCheck = 1
  2000. } else if AVCaptureDevice.authorizationStatus(for: .video) == .denied {
  2001. permissionCheck = 0
  2002. } else {
  2003. AVCaptureDevice.requestAccess(for: .video, completionHandler: { (granted: Bool) -> Void in
  2004. if granted == true {
  2005. permissionCheck = 1
  2006. } else {
  2007. permissionCheck = 0
  2008. }
  2009. })
  2010. }
  2011. while permissionCheck == -1 {
  2012. sleep(1)
  2013. }
  2014. if permissionCheck == 0 {
  2015. let alert = UIAlertController(title: "Attention!".localized(), message: "Please allow camera permission in your settings".localized(), preferredStyle: .alert)
  2016. alert.addAction(UIAlertAction(title: "OK".localized(), style: UIAlertAction.Style.default, handler: { _ in
  2017. if let url = URL(string: UIApplication.openSettingsURLString), UIApplication.shared.canOpenURL(url) {
  2018. UIApplication.shared.open(url, options: [:], completionHandler: nil)
  2019. }
  2020. }))
  2021. if UIApplication.shared.visibleViewController?.navigationController != nil {
  2022. UIApplication.shared.visibleViewController?.navigationController?.present(alert, animated: true, completion: nil)
  2023. } else {
  2024. UIApplication.shared.visibleViewController?.present(alert, animated: true, completion: nil)
  2025. }
  2026. DispatchQueue.global().async {
  2027. DispatchQueue.global().async {
  2028. _ = Nexilis.write(message: CoreMessage_TMessageBank.timeOutRequestCallCenter(channel: message.getBody(key: CoreMessage_TMessageKey.CHANNEL), l_pin: message.getBody(key: CoreMessage_TMessageKey.L_PIN)))
  2029. }
  2030. }
  2031. Nexilis.onGoingPushCC.removeAll()
  2032. return
  2033. }
  2034. }
  2035. if UIApplication.shared.visibleViewController is UINavigationController {
  2036. let nc = UIApplication.shared.visibleViewController as! UINavigationController
  2037. if nc.visibleViewController is QmeraStreamingViewController {
  2038. let vc = nc.visibleViewController as! QmeraStreamingViewController
  2039. var alert = UIAlertController(title: "", message: "Are you sure you want to end Live Streaming, and open notification?".localized(), preferredStyle: .alert)
  2040. if !vc.isLive {
  2041. alert = UIAlertController(title: "", message: "Are you sure you want to leave Live Streaming, and open notification?".localized(), preferredStyle: .alert)
  2042. }
  2043. alert.addAction(UIAlertAction(title: "No".localized(), style: UIAlertAction.Style.default, handler: { _ in
  2044. DispatchQueue.global().async {
  2045. _ = Nexilis.write(message: CoreMessage_TMessageBank.timeOutRequestCallCenter(channel: message.getBody(key: CoreMessage_TMessageKey.CHANNEL), l_pin: message.getBody(key: CoreMessage_TMessageKey.L_PIN)))
  2046. }
  2047. Nexilis.onGoingPushCC.removeAll()
  2048. alert.dismiss(animated: true, completion: nil)
  2049. }))
  2050. alert.addAction(UIAlertAction(title: "Yes".localized(), style: UIAlertAction.Style.default, handler: { _ in
  2051. DispatchQueue.global().async {
  2052. API.terminateBC(sBroadcasterID: vc.isLive ? nil : vc.data)
  2053. vc.sendLeft()
  2054. }
  2055. vc.dismiss(animated: true, completion: {
  2056. acceptCC()
  2057. })
  2058. }))
  2059. nc.present(alert, animated: true, completion: nil)
  2060. // NotificationCenter.default.post(name: NSNotification.Name(rawValue: "isRunningStreaming"), object: nil, userInfo: dataMessage)
  2061. } else {
  2062. acceptCC()
  2063. }
  2064. } else {
  2065. acceptCC()
  2066. }
  2067. func acceptCC() {
  2068. if let response = Nexilis.writeSync(message: CoreMessage_TMessageBank.acceptRequestCallCenter(channel: message.getBody(key: CoreMessage_TMessageKey.CHANNEL), l_pin: message.getBody(key: CoreMessage_TMessageKey.L_PIN), complaint_id: message.getBody(key: CoreMessage_TMessageKey.DATA))) {
  2069. if (response.getBody(key: CoreMessage_TMessageKey.ERRCOD, default_value: "99") == "00") {
  2070. Nexilis.onGoingPushCC.removeAll()
  2071. let complaintId = response.getBody(key: CoreMessage_TMessageKey.DATA, default_value: "")
  2072. if !complaintId.isEmpty {
  2073. alert.dismiss(animated: true, completion: nil)
  2074. let idMe = UserDefaults.standard.string(forKey: "me")!
  2075. UserDefaults.standard.set("\(message.getBody(key: CoreMessage_TMessageKey.L_PIN)),\(idMe),\(complaintId)", forKey: "onGoingCC")
  2076. UserDefaults.standard.set("\(message.getBody(key: CoreMessage_TMessageKey.L_PIN))", forKey: "membersCC")
  2077. if message.getBody(key: CoreMessage_TMessageKey.CHANNEL) == "0" {
  2078. let editorPersonalVC = AppStoryBoard.Palio.instance.instantiateViewController(identifier: "editorPersonalVC") as! EditorPersonal
  2079. editorPersonalVC.isContactCenter = true
  2080. editorPersonalVC.isRequestContactCenter = false
  2081. editorPersonalVC.unique_l_pin = message.getBody(key: CoreMessage_TMessageKey.L_PIN)
  2082. editorPersonalVC.complaintId = complaintId
  2083. editorPersonalVC.channelContactCenter = message.getBody(key: CoreMessage_TMessageKey.CHANNEL)
  2084. editorPersonalVC.fPinContacCenter = message.getBody(key: CoreMessage_TMessageKey.L_PIN)
  2085. let navigationController = UINavigationController(rootViewController: editorPersonalVC)
  2086. navigationController.modalPresentationStyle = .fullScreen
  2087. navigationController.navigationBar.tintColor = .white
  2088. navigationController.navigationBar.barTintColor = .mainColor
  2089. navigationController.navigationBar.isTranslucent = false
  2090. navigationController.navigationBar.overrideUserInterfaceStyle = .dark
  2091. navigationController.navigationBar.barStyle = .black
  2092. let cancelButtonAttributes: [NSAttributedString.Key: Any] = [NSAttributedString.Key.foregroundColor: UIColor.white]
  2093. UIBarButtonItem.appearance().setTitleTextAttributes(cancelButtonAttributes, for: .normal)
  2094. let textAttributes = [NSAttributedString.Key.foregroundColor:UIColor.white]
  2095. navigationController.navigationBar.titleTextAttributes = textAttributes
  2096. navigationController.view.backgroundColor = .mainColor
  2097. if UIApplication.shared.visibleViewController?.navigationController != nil {
  2098. UIApplication.shared.visibleViewController?.navigationController?.present(navigationController, animated: true, completion: nil)
  2099. } else {
  2100. UIApplication.shared.visibleViewController?.present(navigationController, animated: true, completion: nil)
  2101. }
  2102. } else {
  2103. UserDefaults.standard.set("\(Date().currentTimeMillis())", forKey: "startTimeCC")
  2104. DispatchQueue.main.asyncAfter(deadline: .now() + 1, execute: {
  2105. if message.getBody(key: CoreMessage_TMessageKey.CHANNEL) == "1" {
  2106. let pin = message.getBody(key: CoreMessage_TMessageKey.L_PIN)
  2107. let controller = QmeraAudioViewController()
  2108. controller.user = User.getData(pin: pin)
  2109. controller.isOutgoing = true
  2110. controller.modalPresentationStyle = .overCurrentContext
  2111. let navigationController = UINavigationController(rootViewController: controller)
  2112. navigationController.modalPresentationStyle = .fullScreen
  2113. if UIApplication.shared.visibleViewController?.navigationController != nil {
  2114. UIApplication.shared.visibleViewController?.navigationController?.present(navigationController, animated: true, completion: nil)
  2115. } else {
  2116. UIApplication.shared.visibleViewController?.present(navigationController, animated: true, completion: nil)
  2117. }
  2118. } else if message.getBody(key: CoreMessage_TMessageKey.CHANNEL) == "2" {
  2119. let videoVC = AppStoryBoard.Palio.instance.instantiateViewController(withIdentifier: "videoVCQmera") as! QmeraVideoViewController
  2120. videoVC.fPin = message.getBody(key: CoreMessage_TMessageKey.L_PIN)
  2121. videoVC.users.append(User.getData(pin: message.getBody(key: CoreMessage_TMessageKey.L_PIN))!)
  2122. let navigationController = UINavigationController(rootViewController: videoVC)
  2123. navigationController.modalPresentationStyle = .fullScreen
  2124. if UIApplication.shared.visibleViewController?.navigationController != nil {
  2125. UIApplication.shared.visibleViewController?.navigationController?.present(navigationController, animated: true, completion: nil)
  2126. } else {
  2127. UIApplication.shared.visibleViewController?.present(navigationController, animated: true, completion: nil)
  2128. }
  2129. }
  2130. })
  2131. }
  2132. }
  2133. }
  2134. }
  2135. }
  2136. })
  2137. alert.addAction(acceptAction)
  2138. alert.addAction(rejectAction)
  2139. let containerView = UIView(frame: CGRect(x: 20, y: 60, width: alert.view.bounds.size.width * 0.9 - 40, height: 150))
  2140. alert.view.addSubview(containerView)
  2141. containerView.layer.cornerRadius = 10.0
  2142. containerView.clipsToBounds = true
  2143. containerView.backgroundColor = .secondaryColor.withAlphaComponent(0.5)
  2144. let imageProfile = UIImageView()
  2145. containerView.addSubview(imageProfile)
  2146. imageProfile.translatesAutoresizingMaskIntoConstraints = false
  2147. NSLayoutConstraint.activate([
  2148. imageProfile.topAnchor.constraint(equalTo: containerView.topAnchor, constant: 10),
  2149. imageProfile.bottomAnchor.constraint(equalTo: containerView.bottomAnchor, constant: -10),
  2150. imageProfile.leadingAnchor.constraint(equalTo: containerView.leadingAnchor, constant: 10),
  2151. imageProfile.widthAnchor.constraint(equalToConstant: 100)
  2152. ])
  2153. imageProfile.layer.cornerRadius = 10.0
  2154. imageProfile.clipsToBounds = true
  2155. imageProfile.backgroundColor = .lightGray.withAlphaComponent(0.3)
  2156. imageProfile.tintColor = .secondaryColor
  2157. imageProfile.image = UIImage(systemName: "person")
  2158. if message.getBody(key: CoreMessage_TMessageKey.THUMB_ID) != "" {
  2159. imageProfile.setImage(name: message.getBody(key: CoreMessage_TMessageKey.THUMB_ID))
  2160. imageProfile.contentMode = .scaleAspectFill
  2161. }
  2162. let labelName = UILabel()
  2163. containerView.addSubview(labelName)
  2164. labelName.translatesAutoresizingMaskIntoConstraints = false
  2165. NSLayoutConstraint.activate([
  2166. labelName.topAnchor.constraint(equalTo: containerView.topAnchor, constant: 15),
  2167. labelName.leadingAnchor.constraint(equalTo: imageProfile.trailingAnchor, constant: 5)
  2168. ])
  2169. labelName.font = UIFont.systemFont(ofSize: 12)
  2170. labelName.text = "Name".localized()
  2171. labelName.textColor = .mainColor
  2172. let valueName = UILabel()
  2173. containerView.addSubview(valueName)
  2174. valueName.translatesAutoresizingMaskIntoConstraints = false
  2175. NSLayoutConstraint.activate([
  2176. valueName.topAnchor.constraint(equalTo: labelName.bottomAnchor),
  2177. valueName.leadingAnchor.constraint(equalTo: imageProfile.trailingAnchor, constant: 5)
  2178. ])
  2179. valueName.font = UIFont.systemFont(ofSize: 12)
  2180. valueName.text = message.getBody(key: CoreMessage_TMessageKey.F_DISPLAY_NAME)
  2181. valueName.textColor = .mainColor
  2182. let labelType = UILabel()
  2183. containerView.addSubview(labelType)
  2184. labelType.translatesAutoresizingMaskIntoConstraints = false
  2185. NSLayoutConstraint.activate([
  2186. labelType.topAnchor.constraint(equalTo: valueName.bottomAnchor, constant: 5),
  2187. labelType.leadingAnchor.constraint(equalTo: imageProfile.trailingAnchor, constant: 5)
  2188. ])
  2189. labelType.font = UIFont.systemFont(ofSize: 12)
  2190. labelType.text = "Request Type".localized()
  2191. labelType.textColor = .mainColor
  2192. let valueType = UILabel()
  2193. containerView.addSubview(valueType)
  2194. valueType.translatesAutoresizingMaskIntoConstraints = false
  2195. NSLayoutConstraint.activate([
  2196. valueType.topAnchor.constraint(equalTo: labelType.bottomAnchor),
  2197. valueType.leadingAnchor.constraint(equalTo: imageProfile.trailingAnchor, constant: 5)
  2198. ])
  2199. valueType.font = UIFont.systemFont(ofSize: 12)
  2200. if message.getBody(key: CoreMessage_TMessageKey.CHANNEL) == "0" {
  2201. valueType.text = "Chat".localized()
  2202. } else if message.getBody(key: CoreMessage_TMessageKey.CHANNEL) == "1" {
  2203. valueType.text = "Audio Call".localized()
  2204. } else if message.getBody(key: CoreMessage_TMessageKey.CHANNEL) == "2" {
  2205. valueType.text = "Video Call".localized()
  2206. } else {
  2207. valueType.text = "Email".localized()
  2208. }
  2209. valueType.textColor = .mainColor
  2210. let labelIdentity = UILabel()
  2211. containerView.addSubview(labelIdentity)
  2212. labelIdentity.translatesAutoresizingMaskIntoConstraints = false
  2213. NSLayoutConstraint.activate([
  2214. labelIdentity.topAnchor.constraint(equalTo: valueType.bottomAnchor, constant: 5),
  2215. labelIdentity.leadingAnchor.constraint(equalTo: imageProfile.trailingAnchor, constant: 5)
  2216. ])
  2217. labelIdentity.font = UIFont.systemFont(ofSize: 12)
  2218. labelIdentity.text = "Complaint ID".localized()
  2219. labelIdentity.textColor = .mainColor
  2220. let valueIdentity = UILabel()
  2221. containerView.addSubview(valueIdentity)
  2222. valueIdentity.translatesAutoresizingMaskIntoConstraints = false
  2223. NSLayoutConstraint.activate([
  2224. valueIdentity.topAnchor.constraint(equalTo: labelIdentity.bottomAnchor),
  2225. valueIdentity.leadingAnchor.constraint(equalTo: imageProfile.trailingAnchor, constant: 5),
  2226. valueIdentity.trailingAnchor.constraint(equalTo: containerView.trailingAnchor)
  2227. ])
  2228. valueIdentity.font = UIFont.systemFont(ofSize: 12)
  2229. valueIdentity.text = message.getBody(key: CoreMessage_TMessageKey.DATA)
  2230. valueIdentity.numberOfLines = 0
  2231. valueIdentity.textColor = .mainColor
  2232. var isShowAlert: Int?
  2233. let canShow = UIApplication.shared.visibleViewController
  2234. if canShow != nil && !(canShow is UINavigationController) {
  2235. if !(canShow is EditorPersonal) && !(canShow is QmeraAudioViewController) && !(canShow is QmeraVideoViewController) {
  2236. isShowAlert = 0
  2237. } else {
  2238. isShowAlert = 3
  2239. }
  2240. } else if canShow != nil {
  2241. if canShow is UINavigationController {
  2242. let canShowNC = canShow as! UINavigationController
  2243. if !(canShowNC.visibleViewController is EditorPersonal) && !(canShowNC.visibleViewController is QmeraAudioViewController) && !(canShowNC.visibleViewController is QmeraVideoViewController) {
  2244. isShowAlert = 0
  2245. } else {
  2246. isShowAlert = 3
  2247. }
  2248. } else {
  2249. isShowAlert = 0
  2250. }
  2251. }
  2252. DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(isShowAlert!), execute: {
  2253. if UIApplication.shared.visibleViewController?.navigationController != nil {
  2254. UIApplication.shared.visibleViewController?.navigationController?.present(alert, animated: true, completion: nil)
  2255. } else {
  2256. UIApplication.shared.visibleViewController?.present(alert, animated: true, completion: nil)
  2257. }
  2258. })
  2259. }
  2260. } else if message.getCode() == CoreMessage_TMessageCode.ACCEPT_CALL_CENTER {
  2261. let fPinContacCenter = message.getBody(key: CoreMessage_TMessageKey.F_PIN)
  2262. let requester = message.getBody(key: CoreMessage_TMessageKey.UPLINE_PIN)
  2263. let complaintId = message.getBody(key: CoreMessage_TMessageKey.DATA)
  2264. if !requester.isEmpty {
  2265. UserDefaults.standard.set("\(requester),\(fPinContacCenter),\(complaintId)", forKey: "onGoingCC")
  2266. UserDefaults.standard.set("\(fPinContacCenter)", forKey: "membersCC")
  2267. }
  2268. } else if message.getCode() == CoreMessage_TMessageCode.INVITE_TO_ROOM_CONTACT_CENTER {
  2269. DispatchQueue.main.async {
  2270. let alert = UIAlertController(title: "", message: "\n\n\n\n\n\n\n\n\n\n".localized(), preferredStyle: .alert)
  2271. let newWidth = UIScreen.main.bounds.width * 0.90 - 270
  2272. // update width constraint value for main view
  2273. if let viewWidthConstraint = alert.view.constraints.filter({ return $0.firstAttribute == .width }).first{
  2274. viewWidthConstraint.constant = newWidth
  2275. }
  2276. // update width constraint value for container view
  2277. if let containerViewWidthConstraint = alert.view.subviews.first?.constraints.filter({ return $0.firstAttribute == .width }).first {
  2278. containerViewWidthConstraint.constant = newWidth
  2279. }
  2280. let titleFont = [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 18), NSAttributedString.Key.foregroundColor: UIColor.black]
  2281. let titleAttrString = NSMutableAttributedString(string: "You're invited to\nCall Center".localized(), attributes: titleFont)
  2282. alert.setValue(titleAttrString, forKey: "attributedTitle")
  2283. alert.view.subviews.first?.subviews.first?.subviews.first?.backgroundColor = .lightGray
  2284. alert.view.tintColor = .black
  2285. let rejectAction = UIAlertAction(title: "Reject".localized(), style: .destructive, handler: {(_) in
  2286. DispatchQueue.global().async {
  2287. if let result = Nexilis.writeSync(message: CoreMessage_TMessageBank.acceptCCRoomInvite(l_pin: message.getPIN(), type: 0, ticket_id: message.getBody(key: CoreMessage_TMessageKey.CALL_CENTER_ID))) {
  2288. if result.isOk() {
  2289. return
  2290. }
  2291. }
  2292. }
  2293. alert.dismiss(animated: true, completion: nil)
  2294. })
  2295. let acceptAction = UIAlertAction(title: "Accept".localized(), style: .default, handler: {(_) in
  2296. let goAudioCall = Nexilis.checkMicPermission()
  2297. if !goAudioCall && message.getBody(key: CoreMessage_TMessageKey.CHANNEL) == "1" {
  2298. let alert = UIAlertController(title: "Attention!".localized(), message: "Please allow microphone permission in your settings".localized(), preferredStyle: .alert)
  2299. alert.addAction(UIAlertAction(title: "OK".localized(), style: UIAlertAction.Style.default, handler: { _ in
  2300. if let url = URL(string: UIApplication.openSettingsURLString), UIApplication.shared.canOpenURL(url) {
  2301. UIApplication.shared.open(url, options: [:], completionHandler: nil)
  2302. }
  2303. }))
  2304. if UIApplication.shared.visibleViewController?.navigationController != nil {
  2305. UIApplication.shared.visibleViewController?.navigationController?.present(alert, animated: true, completion: nil)
  2306. } else {
  2307. UIApplication.shared.visibleViewController?.present(alert, animated: true, completion: nil)
  2308. }
  2309. DispatchQueue.global().async {
  2310. if let result = Nexilis.writeSync(message: CoreMessage_TMessageBank.acceptCCRoomInvite(l_pin: message.getPIN(), type: 0, ticket_id: message.getBody(key: CoreMessage_TMessageKey.CALL_CENTER_ID))) {
  2311. if result.isOk() {
  2312. return
  2313. }
  2314. }
  2315. }
  2316. return
  2317. }
  2318. if message.getBody(key: CoreMessage_TMessageKey.CHANNEL) == "2" {
  2319. var permissionCheck = -1
  2320. if AVCaptureDevice.authorizationStatus(for: .video) == .authorized {
  2321. permissionCheck = 1
  2322. } else if AVCaptureDevice.authorizationStatus(for: .video) == .denied {
  2323. permissionCheck = 0
  2324. } else {
  2325. AVCaptureDevice.requestAccess(for: .video, completionHandler: { (granted: Bool) -> Void in
  2326. if granted == true {
  2327. permissionCheck = 1
  2328. } else {
  2329. permissionCheck = 0
  2330. }
  2331. })
  2332. }
  2333. while permissionCheck == -1 {
  2334. sleep(1)
  2335. }
  2336. if permissionCheck == 0 {
  2337. let alert = UIAlertController(title: "Attention!".localized(), message: "Please allow camera permission in your settings".localized(), preferredStyle: .alert)
  2338. alert.addAction(UIAlertAction(title: "OK".localized(), style: UIAlertAction.Style.default, handler: { _ in
  2339. if let url = URL(string: UIApplication.openSettingsURLString), UIApplication.shared.canOpenURL(url) {
  2340. UIApplication.shared.open(url, options: [:], completionHandler: nil)
  2341. }
  2342. }))
  2343. if UIApplication.shared.visibleViewController?.navigationController != nil {
  2344. UIApplication.shared.visibleViewController?.navigationController?.present(alert, animated: true, completion: nil)
  2345. } else {
  2346. UIApplication.shared.visibleViewController?.present(alert, animated: true, completion: nil)
  2347. }
  2348. DispatchQueue.global().async {
  2349. if let result = Nexilis.writeSync(message: CoreMessage_TMessageBank.acceptCCRoomInvite(l_pin: message.getPIN(), type: 0, ticket_id: message.getBody(key: CoreMessage_TMessageKey.CALL_CENTER_ID))) {
  2350. if result.isOk() {
  2351. return
  2352. }
  2353. }
  2354. }
  2355. return
  2356. }
  2357. }
  2358. if UIApplication.shared.visibleViewController is UINavigationController {
  2359. let nc = UIApplication.shared.visibleViewController as! UINavigationController
  2360. if nc.visibleViewController is QmeraStreamingViewController {
  2361. let vc = nc.visibleViewController as! QmeraStreamingViewController
  2362. var alert = UIAlertController(title: "", message: "Are you sure you want to end Live Streaming, and open notification?".localized(), preferredStyle: .alert)
  2363. if !vc.isLive {
  2364. alert = UIAlertController(title: "", message: "Are you sure you want to leave Live Streaming, and open notification?".localized(), preferredStyle: .alert)
  2365. }
  2366. alert.addAction(UIAlertAction(title: "No".localized(), style: UIAlertAction.Style.default, handler: { _ in
  2367. DispatchQueue.global().async {
  2368. if let result = Nexilis.writeSync(message: CoreMessage_TMessageBank.acceptCCRoomInvite(l_pin: message.getPIN(), type: 0, ticket_id: message.getBody(key: CoreMessage_TMessageKey.CALL_CENTER_ID))) {
  2369. if result.isOk() {
  2370. return
  2371. }
  2372. }
  2373. }
  2374. alert.dismiss(animated: true, completion: nil)
  2375. }))
  2376. alert.addAction(UIAlertAction(title: "Yes".localized(), style: UIAlertAction.Style.default, handler: { _ in
  2377. DispatchQueue.global().async {
  2378. API.terminateBC(sBroadcasterID: vc.isLive ? nil : vc.data)
  2379. vc.sendLeft()
  2380. }
  2381. vc.dismiss(animated: true, completion: {
  2382. acceptCC()
  2383. })
  2384. }))
  2385. nc.present(alert, animated: true, completion: nil)
  2386. } else {
  2387. acceptCC()
  2388. }
  2389. } else {
  2390. acceptCC()
  2391. }
  2392. func acceptCC() {
  2393. if let result = Nexilis.writeSync(message: CoreMessage_TMessageBank.acceptCCRoomInvite(l_pin: message.getPIN(), type: 1, ticket_id: message.getBody(key: CoreMessage_TMessageKey.CALL_CENTER_ID))) {
  2394. if result.isOk() {
  2395. let requester = result.getBody(key: CoreMessage_TMessageKey.UPLINE_PIN)
  2396. let officer = result.getBody(key: CoreMessage_TMessageKey.FRIEND_FPIN)
  2397. let data = result.getBody(key: CoreMessage_TMessageKey.DATA)
  2398. let complaintId = message.getBody(key: CoreMessage_TMessageKey.CALL_CENTER_ID)
  2399. UserDefaults.standard.set("\(requester),\(officer),\(complaintId)", forKey: "onGoingCC")
  2400. UserDefaults.standard.set("\(Date().currentTimeMillis())", forKey: "startTimeCC")
  2401. if !data.isEmpty {
  2402. if let jsonArray = try! JSONSerialization.jsonObject(with: data.data(using: String.Encoding.utf8)!, options: JSONSerialization.ReadingOptions()) as? [AnyObject] {
  2403. var members = ""
  2404. var user : [User] = []
  2405. let idMe = UserDefaults.standard.string(forKey: "me")!
  2406. for json in jsonArray {
  2407. if "\(json)" != idMe {
  2408. if members.isEmpty {
  2409. members = "\(json)"
  2410. } else {
  2411. members += ",\(json)"
  2412. }
  2413. if let userData = User.getData(pin: "\(json)") {
  2414. user.append(userData)
  2415. } else {
  2416. Nexilis.addFriend (fpin: "\(json)") { result in
  2417. DispatchQueue.main.async {
  2418. if result {
  2419. let userData = User.getData(pin: "\(json)")!
  2420. user.append(userData)
  2421. } else {
  2422. let imageView = UIImageView(image: UIImage(systemName: "xmark.circle.fill"))
  2423. imageView.tintColor = .white
  2424. let banner = FloatingNotificationBanner(title: "Server busy, please try again later".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)
  2425. banner.show()
  2426. }
  2427. }
  2428. }
  2429. }
  2430. }
  2431. }
  2432. UserDefaults.standard.set("\(members)", forKey: "membersCC")
  2433. if message.getBody(key: CoreMessage_TMessageKey.CHANNEL) == "0" {
  2434. let editorPersonalVC = AppStoryBoard.Palio.instance.instantiateViewController(identifier: "editorPersonalVC") as! EditorPersonal
  2435. editorPersonalVC.hidesBottomBarWhenPushed = true
  2436. editorPersonalVC.unique_l_pin = officer
  2437. editorPersonalVC.fromNotification = true
  2438. editorPersonalVC.isContactCenter = true
  2439. editorPersonalVC.fPinContacCenter = members
  2440. editorPersonalVC.complaintId = complaintId
  2441. editorPersonalVC.onGoingCC = true
  2442. editorPersonalVC.isRequestContactCenter = false
  2443. editorPersonalVC.users = user
  2444. let navigationController = UINavigationController(rootViewController: editorPersonalVC)
  2445. navigationController.modalPresentationStyle = .fullScreen
  2446. navigationController.navigationBar.tintColor = .white
  2447. navigationController.navigationBar.barTintColor = .mainColor
  2448. navigationController.navigationBar.isTranslucent = false
  2449. navigationController.navigationBar.overrideUserInterfaceStyle = .dark
  2450. navigationController.navigationBar.barStyle = .black
  2451. let cancelButtonAttributes: [NSAttributedString.Key: Any] = [NSAttributedString.Key.foregroundColor: UIColor.white]
  2452. UIBarButtonItem.appearance().setTitleTextAttributes(cancelButtonAttributes, for: .normal)
  2453. let textAttributes = [NSAttributedString.Key.foregroundColor:UIColor.white]
  2454. navigationController.navigationBar.titleTextAttributes = textAttributes
  2455. navigationController.view.backgroundColor = .mainColor
  2456. if UIApplication.shared.visibleViewController?.navigationController != nil {
  2457. UIApplication.shared.visibleViewController?.navigationController?.present(navigationController, animated: true, completion: nil)
  2458. } else {
  2459. UIApplication.shared.visibleViewController?.present(navigationController, animated: true, completion: nil)
  2460. }
  2461. }
  2462. }
  2463. }
  2464. } else {
  2465. let imageView = UIImageView(image: UIImage(systemName: "info.circle"))
  2466. imageView.tintColor = .white
  2467. let banner = FloatingNotificationBanner(title: "Call Center Session has ended".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)
  2468. banner.show()
  2469. }
  2470. }
  2471. }
  2472. })
  2473. alert.addAction(rejectAction)
  2474. alert.addAction(acceptAction)
  2475. let containerView = UIView(frame: CGRect(x: 50, y: 80, width: alert.view.bounds.size.width * 0.9 - 100, height: 150))
  2476. alert.view.addSubview(containerView)
  2477. containerView.layer.cornerRadius = 10.0
  2478. containerView.clipsToBounds = true
  2479. containerView.backgroundColor = .secondaryColor.withAlphaComponent(0.5)
  2480. let userData = User.getData(pin: message.getPIN())
  2481. let imageProfile = UIImageView()
  2482. containerView.addSubview(imageProfile)
  2483. imageProfile.translatesAutoresizingMaskIntoConstraints = false
  2484. NSLayoutConstraint.activate([
  2485. imageProfile.topAnchor.constraint(equalTo: containerView.topAnchor, constant: 10),
  2486. imageProfile.bottomAnchor.constraint(equalTo: containerView.bottomAnchor, constant: -10),
  2487. imageProfile.leadingAnchor.constraint(equalTo: containerView.leadingAnchor, constant: 10),
  2488. imageProfile.widthAnchor.constraint(equalToConstant: 100)
  2489. ])
  2490. imageProfile.layer.cornerRadius = 10.0
  2491. imageProfile.clipsToBounds = true
  2492. imageProfile.backgroundColor = .lightGray.withAlphaComponent(0.3)
  2493. imageProfile.tintColor = .secondaryColor
  2494. imageProfile.image = UIImage(systemName: "person")
  2495. if userData!.thumb != "" {
  2496. imageProfile.setImage(name: userData!.thumb)
  2497. imageProfile.contentMode = .scaleAspectFill
  2498. }
  2499. let labelName = UILabel()
  2500. containerView.addSubview(labelName)
  2501. labelName.translatesAutoresizingMaskIntoConstraints = false
  2502. NSLayoutConstraint.activate([
  2503. labelName.topAnchor.constraint(equalTo: containerView.topAnchor, constant: 15),
  2504. labelName.leadingAnchor.constraint(equalTo: imageProfile.trailingAnchor, constant: 5)
  2505. ])
  2506. labelName.font = UIFont.systemFont(ofSize: 12)
  2507. labelName.text = "Name".localized()
  2508. labelName.textColor = .mainColor
  2509. let valueName = UILabel()
  2510. containerView.addSubview(valueName)
  2511. valueName.translatesAutoresizingMaskIntoConstraints = false
  2512. NSLayoutConstraint.activate([
  2513. valueName.topAnchor.constraint(equalTo: labelName.bottomAnchor),
  2514. valueName.leadingAnchor.constraint(equalTo: imageProfile.trailingAnchor, constant: 5)
  2515. ])
  2516. valueName.font = UIFont.systemFont(ofSize: 12)
  2517. valueName.text = userData!.fullName
  2518. valueName.textColor = .mainColor
  2519. let labelType = UILabel()
  2520. containerView.addSubview(labelType)
  2521. labelType.translatesAutoresizingMaskIntoConstraints = false
  2522. NSLayoutConstraint.activate([
  2523. labelType.topAnchor.constraint(equalTo: valueName.bottomAnchor, constant: 5),
  2524. labelType.leadingAnchor.constraint(equalTo: imageProfile.trailingAnchor, constant: 5)
  2525. ])
  2526. labelType.font = UIFont.systemFont(ofSize: 12)
  2527. labelType.text = "Request Type".localized()
  2528. labelType.textColor = .mainColor
  2529. let valueType = UILabel()
  2530. containerView.addSubview(valueType)
  2531. valueType.translatesAutoresizingMaskIntoConstraints = false
  2532. NSLayoutConstraint.activate([
  2533. valueType.topAnchor.constraint(equalTo: labelType.bottomAnchor),
  2534. valueType.leadingAnchor.constraint(equalTo: imageProfile.trailingAnchor, constant: 5)
  2535. ])
  2536. valueType.font = UIFont.systemFont(ofSize: 12)
  2537. if message.getBody(key: CoreMessage_TMessageKey.CHANNEL) == "0" {
  2538. valueType.text = "Chat".localized()
  2539. } else if message.getBody(key: CoreMessage_TMessageKey.CHANNEL) == "1" {
  2540. valueType.text = "Audio Call".localized()
  2541. } else if message.getBody(key: CoreMessage_TMessageKey.CHANNEL) == "2" {
  2542. valueType.text = "Video Call".localized()
  2543. } else {
  2544. valueType.text = "Email".localized()
  2545. }
  2546. valueType.textColor = .mainColor
  2547. let labelIdentity = UILabel()
  2548. containerView.addSubview(labelIdentity)
  2549. labelIdentity.translatesAutoresizingMaskIntoConstraints = false
  2550. NSLayoutConstraint.activate([
  2551. labelIdentity.topAnchor.constraint(equalTo: valueType.bottomAnchor, constant: 5),
  2552. labelIdentity.leadingAnchor.constraint(equalTo: imageProfile.trailingAnchor, constant: 5)
  2553. ])
  2554. labelIdentity.font = UIFont.systemFont(ofSize: 12)
  2555. labelIdentity.text = "Complaint ID".localized()
  2556. labelIdentity.textColor = .mainColor
  2557. let valueIdentity = UILabel()
  2558. containerView.addSubview(valueIdentity)
  2559. valueIdentity.translatesAutoresizingMaskIntoConstraints = false
  2560. NSLayoutConstraint.activate([
  2561. valueIdentity.topAnchor.constraint(equalTo: labelIdentity.bottomAnchor),
  2562. valueIdentity.leadingAnchor.constraint(equalTo: imageProfile.trailingAnchor, constant: 5),
  2563. valueIdentity.trailingAnchor.constraint(equalTo: containerView.trailingAnchor)
  2564. ])
  2565. valueIdentity.font = UIFont.systemFont(ofSize: 12)
  2566. valueIdentity.text = message.getBody(key: CoreMessage_TMessageKey.CALL_CENTER_ID)
  2567. valueIdentity.numberOfLines = 0
  2568. valueIdentity.textColor = .mainColor
  2569. if UIApplication.shared.visibleViewController?.navigationController != nil {
  2570. UIApplication.shared.visibleViewController?.navigationController?.present(alert, animated: true, completion: nil)
  2571. } else {
  2572. UIApplication.shared.visibleViewController?.present(alert, animated: true, completion: nil)
  2573. }
  2574. }
  2575. } else if message.getCode() != CoreMessage_TMessageCode.PUSH_CALL_CENTER && message.getCode() != CoreMessage_TMessageCode.ACCEPT_CALL_CENTER && message.getCode() != CoreMessage_TMessageCode.END_CALL_CENTER && message.getCode() != CoreMessage_TMessageCode.TIMEOUT_CONTACT_CENTER && message.getCode() != CoreMessage_TMessageCode.ACCEPT_CONTACT_CENTER && message.getCode() != CoreMessage_TMessageCode.PUSH_MEMBER_ROOM_CONTACT_CENTER && message.getCode() != CoreMessage_TMessageCode.INVITE_END_CONTACT_CENTER && message.getCode() != CoreMessage_TMessageCode.INVITE_EXIT_CONTACT_CENTER || message.mBodies["MERNAM"] != nil {
  2576. let m = message.mBodies
  2577. // if m[CoreMessage_TMessageKey.IS_CALL_CENTER] == "1" {
  2578. // return
  2579. // }
  2580. if message.mBodies["MERNAM"] != nil {
  2581. DispatchQueue.main.async {
  2582. if !Nexilis.broadcastList.isEmpty {
  2583. Nexilis.broadcastList.append(m)
  2584. } else {
  2585. Nexilis.broadcastList.append(m)
  2586. Nexilis.shared.showBroadcastMessage(m: m)
  2587. }
  2588. }
  2589. return
  2590. }
  2591. let sender = m[CoreMessage_TMessageKey.F_PIN]!
  2592. let me = UserDefaults.standard.string(forKey: "me")!
  2593. if(sender != me) {
  2594. let inEditorPersonal = UserDefaults.standard.string(forKey: "inEditorPersonal")
  2595. let inEditorGroup = UserDefaults.standard.stringArray(forKey: "inEditorGroup")
  2596. var text = m["A07"]!
  2597. if (m.keys.contains("A57") && !((m["A57"]!).isEmpty)) {
  2598. text = "Sent Image 📷"
  2599. } else if (m.keys.contains("A149")) && (m["A149"]!) == "11" {
  2600. text = "Sent Sticker ❤️"
  2601. } else if (m.keys.contains("A47") && !((m["A47"]!).isEmpty)) {
  2602. text = "Sent Video 📹"
  2603. } else if (m.keys.contains("BN") && !((m["BN"]!).isEmpty)) {
  2604. if m["A06"]! == "18" {
  2605. text = "Sent Form 📄"
  2606. } else {
  2607. text = "Sent File 📄"
  2608. }
  2609. } else if (m.keys.contains("A63") && !((m["A63"]!).isEmpty)) {
  2610. text = "Sent Audio 🎵"
  2611. } else if ((m["A07"]!).contains("Share%20location%20")) {
  2612. text = "Sent Location 📌"
  2613. } else if (m.keys.contains("A149")) && (m["A149"]!) == "27" {
  2614. text = "Sent link Live Streaming"
  2615. } else if (m.keys.contains("A149")) && (m["A149"]!) == "25" {
  2616. text = "Sent link Video Conference Room"
  2617. } else if (m.keys.contains("A149")) && (m["A149"]!) == "24" {
  2618. text = "Sent link Quiz"
  2619. } else if (m.keys.contains("A118")) && (m["A118"]!) == "1" {
  2620. text = "Sent Confidential Message"
  2621. }
  2622. var nameUser: String?
  2623. var profile = ""
  2624. var threadIdentifier = sender
  2625. let onGoingCC = UserDefaults.standard.string(forKey: "onGoingCC") ?? ""
  2626. if !onGoingCC.isEmpty {
  2627. return
  2628. }
  2629. if Utils.inTabChats{
  2630. return
  2631. }
  2632. if(m["A06"]! == "3" || m["A06"]! == "18" || m["A06"]! == "5") {
  2633. if inEditorPersonal == sender || (inEditorPersonal != nil && inEditorPersonal!.contains(",")) {
  2634. return
  2635. }
  2636. if(nameUser == nil) {
  2637. Database.shared.database?.inTransaction({ (fmdb, rollback) in
  2638. if let cursor = Database.shared.getRecords(fmdb: fmdb, query: "SELECT first_name, last_name, image_id FROM BUDDY WHERE f_pin='\(String(describing: sender))'") {
  2639. while cursor.next() {
  2640. let first_name = cursor.string(forColumnIndex: 0)!
  2641. let last_name = cursor.string(forColumnIndex: 1)!
  2642. nameUser = "\(first_name) \(last_name)".trimmingCharacters(in: .whitespaces)
  2643. profile = cursor.string(forColumnIndex: 2)!
  2644. }
  2645. cursor.close()
  2646. }
  2647. })
  2648. }
  2649. } else {
  2650. let idGroup = m["A01"]!
  2651. var topicGroup: String?
  2652. var idTopic: String?
  2653. if (m.keys.contains("BA")) {
  2654. idTopic = m["BA"]
  2655. }
  2656. if (idTopic == nil) {
  2657. idTopic = "Lounge"
  2658. topicGroup = "Lounge"
  2659. } else {
  2660. Database.shared.database?.inTransaction({ (fmdb, rollback) in
  2661. if let cursor = Database.shared.getRecords(fmdb: fmdb, query: "SELECT title FROM DISCUSSION_FORUM WHERE chat_id='\(idTopic!)'") {
  2662. while cursor.next() {
  2663. let title = cursor.string(forColumnIndex: 0)
  2664. topicGroup = title
  2665. }
  2666. cursor.close()
  2667. }
  2668. })
  2669. }
  2670. if (inEditorGroup != nil) {
  2671. let editorIdGroup = inEditorGroup![0]
  2672. let editorIdTopic = inEditorGroup![1]
  2673. var idTempTopic = idTopic
  2674. if (idTempTopic == "Lounge") {
  2675. idTempTopic = ""
  2676. }
  2677. if (editorIdGroup == idGroup && editorIdTopic == idTempTopic) {
  2678. return
  2679. }
  2680. }
  2681. Database.shared.database?.inTransaction({ (fmdb, rollback) in
  2682. if let cursor = Database.shared.getRecords(fmdb: fmdb, query: "SELECT f_name, image_id FROM GROUPZ WHERE group_id='\(idGroup)'") {
  2683. while cursor.next() {
  2684. let f_name = cursor.string(forColumnIndex: 0)
  2685. var senderName = m["BR"]
  2686. if senderName == nil {
  2687. senderName = "Bot"
  2688. }
  2689. nameUser =
  2690. "\(senderName!) \u{2022} \(f_name!)(\(topicGroup!))"
  2691. profile = cursor.string(forColumnIndex: 1)!
  2692. }
  2693. cursor.close()
  2694. }
  2695. })
  2696. if idTopic == "Lounge" {
  2697. threadIdentifier = idGroup
  2698. } else {
  2699. threadIdentifier = idTopic!
  2700. }
  2701. }
  2702. if nameUser == nil && threadIdentifier == "-999" {
  2703. nameUser = "Bot"
  2704. }
  2705. DispatchQueue.main.async { [self] in
  2706. let container = UIView()
  2707. container.backgroundColor = .gray
  2708. let profileImage = UIImageView()
  2709. profileImage.frame.size = CGSize(width: 60, height: 60)
  2710. container.addSubview(profileImage)
  2711. profileImage.translatesAutoresizingMaskIntoConstraints = false
  2712. NSLayoutConstraint.activate([
  2713. profileImage.leadingAnchor.constraint(equalTo: container.leadingAnchor, constant: 8.0),
  2714. profileImage.centerYAnchor.constraint(equalTo: container.centerYAnchor),
  2715. profileImage.widthAnchor.constraint(equalToConstant: 60),
  2716. profileImage.heightAnchor.constraint(equalToConstant: 60),
  2717. ])
  2718. let title = UILabel()
  2719. container.addSubview(title)
  2720. title.translatesAutoresizingMaskIntoConstraints = false
  2721. NSLayoutConstraint.activate([
  2722. title.leadingAnchor.constraint(equalTo: profileImage.trailingAnchor, constant: 8.0),
  2723. title.topAnchor.constraint(equalTo: container.topAnchor, constant: 20.0),
  2724. ])
  2725. title.font = UIFont.systemFont(ofSize: 14)
  2726. title.text = nameUser ?? "Unknown"
  2727. title.textColor = .white
  2728. let subtitle = UILabel()
  2729. container.addSubview(subtitle)
  2730. subtitle.translatesAutoresizingMaskIntoConstraints = false
  2731. NSLayoutConstraint.activate([
  2732. subtitle.leadingAnchor.constraint(equalTo: profileImage.trailingAnchor, constant: 8.0),
  2733. subtitle.trailingAnchor.constraint(equalTo: container.trailingAnchor, constant: -15.0),
  2734. subtitle.topAnchor.constraint(equalTo: title.bottomAnchor),
  2735. ])
  2736. subtitle.font = UIFont.systemFont(ofSize: 12)
  2737. subtitle.attributedText = text.richText()
  2738. subtitle.textColor = .white
  2739. if floating != nil {
  2740. floating.dismiss()
  2741. }
  2742. floating = FloatingNotificationBanner(customView: container)
  2743. floating.bannerHeight = 100.0
  2744. floating.transparency = 0.9
  2745. if threadIdentifier == "-999" {
  2746. if Utils.getIconDock() != nil {
  2747. let dataImage = try? Data(contentsOf: URL(string: Utils.getUrlDock()!)!) //make sure your image in this url does exist, otherwise unwrap in a if let check / try-catch
  2748. if dataImage != nil {
  2749. profileImage.image = UIImage(data: dataImage!)
  2750. }
  2751. } else {
  2752. profileImage.image = UIImage(named: "pb_button", in: Bundle.resourceBundle(for: Nexilis.self), with: nil)
  2753. }
  2754. } else if profile != "" {
  2755. profileImage.circle()
  2756. do {
  2757. let documentDir = try FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
  2758. let file = documentDir.appendingPathComponent(profile)
  2759. if FileManager().fileExists(atPath: file.path) {
  2760. profileImage.image = UIImage(contentsOfFile: file.path)
  2761. profileImage.backgroundColor = .clear
  2762. } else {
  2763. Download().start(forKey: profile) { (name, progress) in
  2764. guard progress == 100 else {
  2765. return
  2766. }
  2767. DispatchQueue.main.async { [self] in
  2768. profileImage.image = UIImage(contentsOfFile: file.path)
  2769. profileImage.backgroundColor = .clear
  2770. if !onGoingCC.isEmpty {
  2771. floating.autoDismiss = false
  2772. }
  2773. floating.show(queuePosition: .front, bannerPosition: .top, queue: NotificationBannerQueue(maxBannersOnScreenSimultaneously: 1), on: nil, edgeInsets: UIEdgeInsets(top: 8.0, left: 8.0, bottom: 0, right: 8.0), cornerRadius: 8.0, shadowColor: .clear, shadowOpacity: .zero, shadowBlurRadius: .zero, shadowCornerRadius: .zero, shadowOffset: .zero, shadowEdgeInsets: nil)
  2774. floating.onTap = {
  2775. showNotif()
  2776. }
  2777. }
  2778. }
  2779. return
  2780. }
  2781. } catch {}
  2782. profileImage.contentMode = .scaleAspectFill
  2783. } else {
  2784. profileImage.circle()
  2785. if m["A06"]! == "3" {
  2786. profileImage.image = UIImage(systemName: "person")
  2787. } else {
  2788. profileImage.image = UIImage(systemName: "person.3")
  2789. }
  2790. profileImage.contentMode = .scaleAspectFit
  2791. profileImage.backgroundColor = .lightGray
  2792. profileImage.tintColor = .white
  2793. }
  2794. floating.show(queuePosition: .front, bannerPosition: .top, queue: NotificationBannerQueue(maxBannersOnScreenSimultaneously: 1), on: nil, edgeInsets: UIEdgeInsets(top: 8.0, left: 8.0, bottom: 0, right: 8.0), cornerRadius: 8.0, shadowColor: .clear, shadowOpacity: .zero, shadowBlurRadius: .zero, shadowCornerRadius: .zero, shadowOffset: .zero, shadowEdgeInsets: nil)
  2795. let vibrateMode = UserDefaults.standard.bool(forKey: "vibrateMode")
  2796. var soundId = UserDefaults.standard.string(forKey: "notifSoundPersonal") ?? ""
  2797. if message.getBody(key: CoreMessage_TMessageKey.MESSAGE_SCOPE_ID) == "4" {
  2798. soundId = UserDefaults.standard.string(forKey: "notifSoundGroup") ?? ""
  2799. }
  2800. var systemSoundID: SystemSoundID!
  2801. if soundId.isEmpty {
  2802. systemSoundID = 1007
  2803. } else {
  2804. systemSoundID = SystemSoundID(Int(soundId.components(separatedBy: ":")[0])!)
  2805. }
  2806. if vibrateMode {
  2807. AudioServicesPlaySystemSound(systemSoundID)
  2808. } else {
  2809. var nameSound = "sms-received1"
  2810. if systemSoundID != 1007 {
  2811. nameSound = soundId.components(separatedBy: ":")[1]
  2812. }
  2813. let url = URL(fileURLWithPath: "/System/Library/Audio/UISounds/\(nameSound).caf")
  2814. AudioServicesCreateSystemSoundID(url as CFURL, &systemSoundID)
  2815. AudioServicesPlaySystemSound(systemSoundID)
  2816. }
  2817. if !onGoingCC.isEmpty {
  2818. floating.autoDismiss = false
  2819. }
  2820. floating.onTap = {
  2821. showNotif()
  2822. }
  2823. func showNotif() {
  2824. if !onGoingCC.isEmpty {
  2825. floating.dismiss()
  2826. }
  2827. Database.shared.database?.inTransaction({ (fmdb, rollback) in
  2828. if let cursorData = Database.shared.getRecords(fmdb: fmdb, query: "SELECT first_name, last_name FROM BUDDY where f_pin = '\(UserDefaults.standard.string(forKey: "me")!)'"), cursorData.next() {
  2829. if (cursorData.string(forColumnIndex: 0)! + " " + cursorData.string(forColumnIndex: 1)!).trimmingCharacters(in: .whitespaces) == "USR\(UserDefaults.standard.string(forKey: "me")!)" {
  2830. let alert = UIAlertController(title: "Change Profile".localized(), message: "You must change your name to use this feature".localized(), preferredStyle: .alert)
  2831. alert.addAction(UIAlertAction(title: "OK".localized(), style: UIAlertAction.Style.default, handler: {(_) in
  2832. let controller = AppStoryBoard.Palio.instance.instantiateViewController(withIdentifier: "signupsignin") as! SignUpSignIn
  2833. controller.forceLogin = true
  2834. let navigationController = UINavigationController(rootViewController: controller)
  2835. navigationController.modalPresentationStyle = .fullScreen
  2836. navigationController.navigationBar.tintColor = .white
  2837. navigationController.navigationBar.barTintColor = .mainColor
  2838. navigationController.navigationBar.isTranslucent = false
  2839. navigationController.navigationBar.overrideUserInterfaceStyle = .dark
  2840. navigationController.navigationBar.barStyle = .black
  2841. let cancelButtonAttributes: [NSAttributedString.Key: Any] = [NSAttributedString.Key.foregroundColor: UIColor.white]
  2842. UIBarButtonItem.appearance().setTitleTextAttributes(cancelButtonAttributes, for: .normal)
  2843. let textAttributes = [NSAttributedString.Key.foregroundColor:UIColor.white]
  2844. navigationController.navigationBar.titleTextAttributes = textAttributes
  2845. navigationController.view.backgroundColor = .mainColor
  2846. if UIApplication.shared.visibleViewController?.navigationController != nil {
  2847. UIApplication.shared.visibleViewController?.navigationController?.present(navigationController, animated: true, completion: nil)
  2848. } else {
  2849. UIApplication.shared.visibleViewController?.present(navigationController, animated: true, completion: nil)
  2850. }
  2851. }))
  2852. if UIApplication.shared.visibleViewController?.navigationController != nil {
  2853. UIApplication.shared.visibleViewController?.navigationController?.present(alert, animated: true, completion: nil)
  2854. } else {
  2855. UIApplication.shared.visibleViewController?.present(alert, animated: true, completion: nil)
  2856. }
  2857. }
  2858. cursorData.close()
  2859. return
  2860. }
  2861. })
  2862. if(m["A06"]! == "3" || m["A06"]! == "5" || m["A06"]! == "18") {
  2863. func openEditor() {
  2864. let editorPersonalVC = AppStoryBoard.Palio.instance.instantiateViewController(identifier: "editorPersonalVC") as! EditorPersonal
  2865. editorPersonalVC.hidesBottomBarWhenPushed = true
  2866. editorPersonalVC.unique_l_pin = threadIdentifier
  2867. editorPersonalVC.fromNotification = true
  2868. if !onGoingCC.isEmpty {
  2869. let compalintId = onGoingCC.components(separatedBy: ",")[2]
  2870. let fPinCC = onGoingCC.isEmpty ? "" : onGoingCC.components(separatedBy: ",")[1]
  2871. editorPersonalVC.isContactCenter = true
  2872. editorPersonalVC.fPinContacCenter = fPinCC
  2873. editorPersonalVC.complaintId = compalintId
  2874. editorPersonalVC.onGoingCC = true
  2875. editorPersonalVC.isRequestContactCenter = false
  2876. }
  2877. let navigationController = UINavigationController(rootViewController: editorPersonalVC)
  2878. navigationController.modalPresentationStyle = .fullScreen
  2879. navigationController.navigationBar.tintColor = .white
  2880. navigationController.navigationBar.barTintColor = .mainColor
  2881. navigationController.navigationBar.isTranslucent = false
  2882. navigationController.navigationBar.overrideUserInterfaceStyle = .dark
  2883. navigationController.navigationBar.barStyle = .black
  2884. let cancelButtonAttributes: [NSAttributedString.Key: Any] = [NSAttributedString.Key.foregroundColor: UIColor.white]
  2885. UIBarButtonItem.appearance().setTitleTextAttributes(cancelButtonAttributes, for: .normal)
  2886. let textAttributes = [NSAttributedString.Key.foregroundColor:UIColor.white]
  2887. navigationController.navigationBar.titleTextAttributes = textAttributes
  2888. navigationController.view.backgroundColor = .mainColor
  2889. if UIApplication.shared.visibleViewController?.navigationController != nil {
  2890. UIApplication.shared.visibleViewController?.navigationController?.present(navigationController, animated: true, completion: nil)
  2891. } else {
  2892. UIApplication.shared.visibleViewController?.present(navigationController, animated: true, completion: nil)
  2893. }
  2894. }
  2895. if UIApplication.shared.visibleViewController is UINavigationController {
  2896. let nc = UIApplication.shared.visibleViewController as! UINavigationController
  2897. if nc.visibleViewController is QmeraStreamingViewController {
  2898. let vc = nc.visibleViewController as! QmeraStreamingViewController
  2899. var alert = UIAlertController(title: "", message: "Are you sure you want to end Live Streaming, and open notification?".localized(), preferredStyle: .alert)
  2900. if !vc.isLive {
  2901. alert = UIAlertController(title: "", message: "Are you sure you want to leave Live Streaming, and open notification?".localized(), preferredStyle: .alert)
  2902. }
  2903. alert.addAction(UIAlertAction(title: "No".localized(), style: UIAlertAction.Style.default, handler: nil))
  2904. alert.addAction(UIAlertAction(title: "Yes".localized(), style: UIAlertAction.Style.default, handler: { _ in
  2905. DispatchQueue.global().async {
  2906. API.terminateBC(sBroadcasterID: vc.isLive ? nil : vc.data)
  2907. vc.sendLeft()
  2908. }
  2909. vc.dismiss(animated: true, completion: {
  2910. openEditor()
  2911. })
  2912. }))
  2913. nc.present(alert, animated: true, completion: nil)
  2914. // NotificationCenter.default.post(name: NSNotification.Name(rawValue: "isRunningStreaming"), object: nil, userInfo: dataMessage)
  2915. } else if nc.visibleViewController is EditorPersonal {
  2916. let vc = nc.visibleViewController as! EditorPersonal
  2917. if vc.fromNotification {
  2918. vc.dismiss(animated: true, completion: {
  2919. openEditor()
  2920. })
  2921. } else {
  2922. vc.navigationController?.popViewController(animated: true)
  2923. openEditor()
  2924. }
  2925. } else {
  2926. openEditor()
  2927. }
  2928. } else if UIApplication.shared.visibleViewController is EditorPersonal {
  2929. let vc = UIApplication.shared.visibleViewController as! EditorPersonal
  2930. if vc.fromNotification{
  2931. vc.dismiss(animated: true, completion: {
  2932. openEditor()
  2933. })
  2934. } else {
  2935. vc.navigationController?.popViewController(animated: true)
  2936. openEditor()
  2937. }
  2938. } else if UIApplication.shared.visibleViewController is UIAlertController {
  2939. let vc = UIApplication.shared.visibleViewController as! UIAlertController
  2940. vc.dismiss(animated: true, completion: {
  2941. openEditor()
  2942. })
  2943. } else {
  2944. openEditor()
  2945. }
  2946. } else {
  2947. func openEditor() {
  2948. let editorGroupVC = AppStoryBoard.Palio.instance.instantiateViewController(withIdentifier: "editorGroupVC") as! EditorGroup
  2949. editorGroupVC.hidesBottomBarWhenPushed = true
  2950. editorGroupVC.unique_l_pin = threadIdentifier
  2951. editorGroupVC.fromNotification = true
  2952. let navigationController = UINavigationController(rootViewController: editorGroupVC)
  2953. navigationController.modalPresentationStyle = .fullScreen
  2954. navigationController.navigationBar.tintColor = .white
  2955. navigationController.navigationBar.barTintColor = .mainColor
  2956. navigationController.navigationBar.isTranslucent = false
  2957. navigationController.navigationBar.overrideUserInterfaceStyle = .dark
  2958. navigationController.navigationBar.barStyle = .black
  2959. let cancelButtonAttributes: [NSAttributedString.Key: Any] = [NSAttributedString.Key.foregroundColor: UIColor.white]
  2960. UIBarButtonItem.appearance().setTitleTextAttributes(cancelButtonAttributes, for: .normal)
  2961. let textAttributes = [NSAttributedString.Key.foregroundColor:UIColor.white]
  2962. navigationController.navigationBar.titleTextAttributes = textAttributes
  2963. navigationController.view.backgroundColor = .mainColor
  2964. if UIApplication.shared.visibleViewController?.navigationController != nil {
  2965. UIApplication.shared.visibleViewController?.navigationController?.present(navigationController, animated: true, completion: nil)
  2966. } else {
  2967. UIApplication.shared.visibleViewController?.present(navigationController, animated: true, completion: nil)
  2968. }
  2969. }
  2970. if UIApplication.shared.visibleViewController is UINavigationController {
  2971. let nc = UIApplication.shared.visibleViewController as! UINavigationController
  2972. if nc.visibleViewController is QmeraStreamingViewController {
  2973. let vc = nc.visibleViewController as! QmeraStreamingViewController
  2974. var alert = UIAlertController(title: "", message: "Are you sure you want to end Live Streaming, and open notification?".localized(), preferredStyle: .alert)
  2975. if !vc.isLive {
  2976. alert = UIAlertController(title: "", message: "Are you sure you want to leave Live Streaming, and open notification?".localized(), preferredStyle: .alert)
  2977. }
  2978. alert.addAction(UIAlertAction(title: "No".localized(), style: UIAlertAction.Style.default, handler: nil))
  2979. alert.addAction(UIAlertAction(title: "Yes".localized(), style: UIAlertAction.Style.default, handler: { _ in
  2980. DispatchQueue.global().async {
  2981. API.terminateBC(sBroadcasterID: vc.isLive ? nil : vc.data)
  2982. vc.sendLeft()
  2983. }
  2984. vc.dismiss(animated: true, completion: {
  2985. openEditor()
  2986. })
  2987. }))
  2988. nc.present(alert, animated: true, completion: nil)
  2989. // NotificationCenter.default.post(name: NSNotification.Name(rawValue: "isRunningStreaming"), object: nil, userInfo: dataMessage)
  2990. } else if nc.visibleViewController is EditorGroup {
  2991. let vc = nc.visibleViewController as! EditorGroup
  2992. if vc.fromNotification {
  2993. vc.dismiss(animated: true, completion: {
  2994. openEditor()
  2995. })
  2996. } else {
  2997. vc.navigationController?.popViewController(animated: true)
  2998. openEditor()
  2999. }
  3000. } else {
  3001. openEditor()
  3002. }
  3003. } else if UIApplication.shared.visibleViewController is EditorGroup {
  3004. let vc = UIApplication.shared.visibleViewController as! EditorGroup
  3005. if vc.fromNotification {
  3006. vc.dismiss(animated: true, completion: {
  3007. openEditor()
  3008. })
  3009. } else {
  3010. vc.navigationController?.popViewController(animated: true)
  3011. openEditor()
  3012. }
  3013. } else if UIApplication.shared.visibleViewController is UIAlertController {
  3014. let vc = UIApplication.shared.visibleViewController as! UIAlertController
  3015. vc.dismiss(animated: true, completion: {
  3016. openEditor()
  3017. })
  3018. } else {
  3019. openEditor()
  3020. }
  3021. }
  3022. }
  3023. }
  3024. }
  3025. }
  3026. }
  3027. public static func addFriend(fpin: String, completion: @escaping (Bool) -> ()) {
  3028. DispatchQueue.global().async {
  3029. if let response = Nexilis.writeAndWait(message: CoreMessage_TMessageBank.getAddFriendQRCode(fpin: fpin)), response.isOk() {
  3030. completion(true)
  3031. } else {
  3032. completion(false)
  3033. }
  3034. }
  3035. }
  3036. public func onReceive(message: [AnyHashable : Any?]) {
  3037. var dataMessage: [AnyHashable : Any] = [:]
  3038. dataMessage["message"] = message
  3039. NotificationCenter.default.post(name: NSNotification.Name(rawValue: "onReceiveChat"), object: nil, userInfo: dataMessage)
  3040. }
  3041. public func onMessage(message: TMessage) {
  3042. var dataMessage: [AnyHashable : Any] = [:]
  3043. dataMessage["message"] = message
  3044. NotificationCenter.default.post(name: NSNotification.Name(rawValue: "onMessageChat"), object: nil, userInfo: dataMessage)
  3045. }
  3046. public func onUpload(name: String, progress: Double) {
  3047. var dataMessage: [AnyHashable : Any] = [:]
  3048. dataMessage["name"] = name
  3049. dataMessage["progress"] = progress
  3050. NotificationCenter.default.post(name: NSNotification.Name(rawValue: "onUploadChat"), object: nil, userInfo: dataMessage)
  3051. }
  3052. public func onTyping(message: TMessage) {
  3053. var dataMessage: [AnyHashable : Any] = [:]
  3054. dataMessage["message"] = message
  3055. NotificationCenter.default.post(name: NSNotification.Name(rawValue: "onTypingChat"), object: nil, userInfo: dataMessage)
  3056. }
  3057. // public static func faceDetect(fd: FaceDetector?,image: UIImage, completion: ((Bool) -> ())?){
  3058. // print("enter vision")
  3059. // let visionImage = VisionImage(image: image)
  3060. // print("exit vision")
  3061. // var retval = false
  3062. // visionImage.orientation = image.imageOrientation
  3063. // var fd1 : FaceDetector?
  3064. // if(fd == nil){
  3065. // fd1 = FaceDetector.faceDetector()
  3066. // }
  3067. // else {
  3068. // fd1 = fd
  3069. // }
  3070. //
  3071. // // [START detect_faces]
  3072. // fd1?.process(visionImage) {faces, error in
  3073. // guard error == nil, let faces = faces, !faces.isEmpty else {
  3074. // print("faces empty")
  3075. // completion?(false)
  3076. // return
  3077. // }
  3078. // if(faces.count > 0){
  3079. // print("face count: \(faces.count)")
  3080. // retval = true
  3081. // }
  3082. // completion?(retval)
  3083. // }
  3084. //
  3085. // }
  3086. }
  3087. extension Nexilis: GroupDelegate {
  3088. public func onGroup(code: String, f_pin: String, groupId: String) {
  3089. var data: [AnyHashable : Any] = [:]
  3090. data["code"] = code
  3091. data["f_pin"] = f_pin
  3092. data["groupId"] = groupId
  3093. NotificationCenter.default.post(name: NSNotification.Name(rawValue: "onGroup"), object: nil, userInfo: data)
  3094. }
  3095. public func onTopic(code: String, f_pin: String, topicId: String) {
  3096. var data: [AnyHashable : Any] = [:]
  3097. data["code"] = code
  3098. data["f_pin"] = f_pin
  3099. data["topicId"] = topicId
  3100. NotificationCenter.default.post(name: NSNotification.Name(rawValue: "onTopic"), object: nil, userInfo: data)
  3101. }
  3102. public func onMember(code: String, f_pin: String, groupId: String, member: String) {
  3103. var data: [AnyHashable : Any] = [:]
  3104. data["code"] = code
  3105. data["f_pin"] = f_pin
  3106. data["groupId"] = groupId
  3107. data["member"] = member
  3108. NotificationCenter.default.post(name: NSNotification.Name(rawValue: "onMember"), object: nil, userInfo: data)
  3109. }
  3110. }
  3111. extension Nexilis: PersonInfoDelegate {
  3112. public func onUpdatePersonInfo(state: Int, message: String) {
  3113. var data: [AnyHashable : Any] = [:]
  3114. data["state"] = state
  3115. data["message"] = message
  3116. NotificationCenter.default.post(name: NSNotification.Name(rawValue: "onUpdatePersonInfo"), object: nil, userInfo: data)
  3117. }
  3118. }
  3119. extension Nexilis: QLPreviewControllerDataSource {
  3120. public func numberOfPreviewItems(in controller: QLPreviewController) -> Int {
  3121. return 1
  3122. }
  3123. public func previewController(_ controller: QLPreviewController, previewItemAt index: Int) -> QLPreviewItem {
  3124. return previewItem!
  3125. }
  3126. }