Nexilis.swift 240 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204
  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. import SDWebImage
  17. public class Nexilis: NSObject {
  18. public static var sAPIKey = ""
  19. public static var ADDRESS = ""
  20. // static let ADDRESS_33 = "192.168.0.33"
  21. // static let ADDRESS_RELEASE = "202.158.33.26" //CBN
  22. // static let ADDRESS_RELEASE = "108.137.84.148" //AWS
  23. // static let PORT = 45328
  24. // static let PORT = 65328 // 33
  25. static var PORT = PORT_RELEASE
  26. static let PORT_33 = 62328
  27. static let PORT_RELEASE = 42328
  28. static var nSessionMode: Int! = 1
  29. static var dispatch: DispatchGroup?
  30. public static var showFB = false
  31. public static var fromMAB = false
  32. let callManager = CallManager()
  33. var providerDelegate: CallProviderDelegate?
  34. public static let shared = Nexilis()
  35. // public static var broadcastTimer = Timer()
  36. public static var broadcastList = [[String: String]]()
  37. public static var onGoingPushCC: [String: String] = [:]
  38. public static var openBroadcast = false
  39. public static var loadingAlert = LibAlertController()
  40. public static var floatingButton = FloatingButton()
  41. public static var defaultFloatingButton: [Int] = []
  42. public static var showButtonFB = false
  43. public static var isShowForceSignIn = true
  44. public static var imageCache = NSCache<NSString, UIImage>()
  45. public static let listenerReceiveChat = "onReceiveChatLibLite"
  46. public static let listenerStatusChat = "onMessageChatLibLite"
  47. public static let listenerTypingChat = "onTypingChatLibLite"
  48. public static let listenerStatusCall = "onStatusCallLibLite"
  49. public static let callFCM = "onCallFCM"
  50. public static let failedSendMessage = "onFailedSendMessage"
  51. public static var showLibraryNotification = true
  52. public static let STREAMING_SEMINAR_ENDED = 88
  53. public static let VIDEO_CALL_END = 38
  54. public static let VIDEO_CALL_MUTE_UNMUTE = 36
  55. public static let VIDEO_CALL_ZOOM = 35
  56. public static let VIDEO_CAMERA_PARAMS_CHANED = 34
  57. public static let VIDEO_CALL_RINGING = 33
  58. public static let VIDEO_CALL_OFFHOOK = 32
  59. public static let VIDEO_CALL_INCOMING = 31
  60. public static let AUDIO_CALL_END = 28
  61. public static let AUDIO_CALL_RINGING = 23
  62. public static let AUDIO_CALL_OFFHOOK = 22
  63. public static let AUDIO_CALL_INCOMING = 21
  64. public static let AUDIO_VIDEO_CALL_MUTED = 26
  65. public static let VIDEO_RINGING = 11
  66. public static let ENDED = 8
  67. public static let INITIATING = 4
  68. public static let AUDIO_RINGING = 1
  69. public static let OUTGOING_CALL = 0
  70. public static let OFFLINE = -3
  71. public static let BUSY = -4
  72. public static let IDX_QUEUE_SYSTEM = 2
  73. public static let IDX_NOTIF_CENTER = 3
  74. public static let IDX_CC_STREAM = 4
  75. public static let IDX_CHAT = 6
  76. public static let IDX_CALL = 7
  77. public static let IDX_STREAM = 8
  78. public static let IDX_CC = 9
  79. public static let IDX_CALL_AUDIO = 11
  80. public static let IDX_CALL_VIDEO = 12
  81. public static let IDX_WHITEBOARD = 13
  82. public static let IDX_SCREENSHARING = 14
  83. public static let IDX_WB_SS = 15
  84. public static let IDX_BROADCAST_FORM = 16
  85. public static let IDX_CONVERSATION = 17
  86. public static let IDX_FAVORITEMESSAGE = 18
  87. public static let IDX_CONFERENCE_ROOM_FORM = 19
  88. public static let IDX_EMAIL_CONFIGURATION = 20
  89. public static let IDX_CREATE_GROUP = 21
  90. public static let IDX_ADDFRIEND = 22
  91. public static let IDX_SIGNUP_OR_IN_PAGE = 23
  92. public static let IDX_POST = 99
  93. public static let IDX_SELF_ACT = 100
  94. public static let IDX_SOCIAL_COMMERCE = 101
  95. public static let IDX_NEWS = 102
  96. static var ringtonePlayer: AVAudioPlayer?
  97. static var ringbacktonePlayer: AVAudioPlayer?
  98. private func createDelegate() {
  99. //print("createDelegate...")
  100. callDelegate = self
  101. messageDelegate = self
  102. groupDelegate = self
  103. personInfoDelegate = self
  104. providerDelegate = CallProviderDelegate(callManager: callManager)
  105. }
  106. public static func connect(apiKey: String, delegate: ConnectDelegate, showButton: Bool = true, fromMAB: Bool = false) {
  107. showFB = showButton
  108. Nexilis.fromMAB = fromMAB
  109. Nexilis.shared.createDelegate()
  110. Nexilis.sAPIKey = apiKey
  111. Nexilis.showButtonFB = showButton
  112. do {
  113. try MasterKeyUtil.shared.generateAndStoreMasterKey()
  114. try MasterKeyUtil.shared.generateAndStorePrefsKey()
  115. Utils.setCertificatePinningWebview(value: Utils.decrypt(str: "6]qaAhNXHAxGKAOsFZmoIRUIn2Hp3rdfGAOFEfcnY4SIZ"))
  116. } catch {
  117. }
  118. IncomingThread.default.run()
  119. imageCache.countLimit = 100
  120. imageCache.totalCostLimit = 1024 * 1024 * 200
  121. DispatchQueue.global().async {
  122. do {
  123. let address = Nexilis.getAddressNew(apiKey:apiKey)
  124. if address.isEmpty {
  125. return
  126. }
  127. Nexilis.dispatch = DispatchGroup()
  128. Nexilis.dispatch?.enter()
  129. Nexilis.ADDRESS = address.components(separatedBy: ":")[0]
  130. Nexilis.PORT = Int(address.components(separatedBy: ":")[1]) ?? 0
  131. var id = Utils.getConnectionID()
  132. if id.isEmpty {
  133. let sDID = UIDevice.current.identifierForVendor?.uuidString ?? "UNK-DEVICE"
  134. id = String(sDID[sDID.index(sDID.endIndex, offsetBy: -5)...])
  135. Utils.setConnectionID(value: id)
  136. }
  137. try API.initConnection(bSwitchIP: false, sAPIK: apiKey, aAppMain: nil, cbiI: Callback(), sTCPAddr: Nexilis.ADDRESS, nTCPPort: Nexilis.PORT, sUserID: id, sStartWH: "09:00")
  138. // wait until connection true
  139. Nexilis.dispatch?.wait()
  140. Nexilis.dispatch = nil
  141. if(User.getMyPin() == nil){
  142. if let response = Nexilis.writeSync(message: CoreMessage_TMessageBank.getSignUpApi(api: apiKey, p_pin: id), timeout: 30 * 1000){
  143. id = response.getBody(key: CoreMessage_TMessageKey.F_PIN, default_value: "")
  144. let enable_signup = (response.getBody(key: CoreMessage_TMessageKey.IS_ENABLED_ANONYMOUS, default_value: "0")) == "1"
  145. Utils.setForceAnonymous(value: enable_signup)
  146. if(!id.isEmpty) {
  147. SecureUserDefaults.shared.set(id, forKey: "me")
  148. }
  149. }
  150. }
  151. let api: String? = SecureUserDefaults.shared.value(forKey: "apiKey") ?? nil
  152. if api == nil {
  153. SecureUserDefaults.shared.set(apiKey, forKey: "apiKey")
  154. }
  155. getPullPrefs()
  156. getFeatureAccess()
  157. if let me = User.getMyPin() {
  158. if Utils.getSetProfile() {
  159. _ = Database.shared.openDatabase()
  160. Database.shared.database?.inTransaction({ (fmdb, rollback) in
  161. do {
  162. if let cursorData = Database.shared.getRecords(fmdb: fmdb, query: "SELECT * FROM BUDDY where f_pin = '\(me)' ") {
  163. if !cursorData.next() {
  164. _ = Nexilis.write(message: CoreMessage_TMessageBank.getPostRegistration(p_pin: me))
  165. }
  166. cursorData.close()
  167. }
  168. } catch {
  169. rollback.pointee = true
  170. print("Access database error: \(error.localizedDescription)")
  171. }
  172. })
  173. Database.shared.database?.inTransaction({ (fmdb, rollback) in
  174. do {
  175. if let cursorData = Database.shared.getRecords(fmdb: fmdb, query: "SELECT image_id FROM GROUPZ where group_type = 1 AND official = 1"), cursorData.next() {
  176. do {
  177. let documentDir = try FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
  178. let file = documentDir.appendingPathComponent(cursorData.string(forColumnIndex: 0)!)
  179. if !FileManager().fileExists(atPath: file.path) {
  180. Download().startHTTP(forKey: cursorData.string(forColumnIndex: 0)!) { (name, progress) in}
  181. }
  182. } catch {}
  183. cursorData.close()
  184. }
  185. } catch {
  186. rollback.pointee = true
  187. print("Access database error: \(error.localizedDescription)")
  188. }
  189. })
  190. } else if isShowForceSignIn && !Utils.getForceAnonymous() && !Utils.getSetProfile() {
  191. DispatchQueue.main.async {
  192. showForceSignIn()
  193. }
  194. }
  195. getServiceBank()
  196. getPullWorkingArea()
  197. getPullGroupNoMember()
  198. delegate.onSuccess(userId: me)
  199. DispatchQueue.main.async {
  200. var viewController = UIApplication.shared.windows.first?.rootViewController
  201. var notNull = false
  202. while !notNull {
  203. viewController = UIApplication.shared.windows.first?.rootViewController
  204. if viewController != nil && Utils.getFinishInitPrefsr() {
  205. notNull = true
  206. }
  207. }
  208. if showButton {
  209. addFB(viewController: viewController!, fromMAB: fromMAB)
  210. }
  211. if let rootViewController = viewController {
  212. let isDarkMode = rootViewController.traitCollection.userInterfaceStyle == .dark
  213. if isDarkMode {
  214. UITextField.appearance(whenContainedInInstancesOf: [UISearchBar.self]).defaultTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.white]
  215. let cancelButtonAttributes = [NSAttributedString.Key.foregroundColor: UIColor.white, NSAttributedString.Key.font : UIFont.systemFont(ofSize: 16)]
  216. UIBarButtonItem.appearance().setTitleTextAttributes(cancelButtonAttributes , for: .normal)
  217. } else {
  218. UITextField.appearance(whenContainedInInstancesOf: [UISearchBar.self]).defaultTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.black]
  219. let cancelButtonAttributes = [NSAttributedString.Key.foregroundColor: UIColor.black, NSAttributedString.Key.font : UIFont.systemFont(ofSize: 16)]
  220. UIBarButtonItem.appearance().setTitleTextAttributes(cancelButtonAttributes , for: .normal)
  221. }
  222. }
  223. }
  224. Nexilis.destroyAll()
  225. if (Utils.getSetProfile() && !Utils.getFinishInitPrefsr()) || (!Utils.getForceAnonymous() && !Utils.getFinishInitPrefsr()) {
  226. Utils.setFinishInitPrefs(value: true)
  227. }
  228. if !Utils.getLoginMultipleFPin().isEmpty {
  229. let dialog = DialogUnableAccess()
  230. dialog.modalTransitionStyle = .crossDissolve
  231. dialog.modalPresentationStyle = .overCurrentContext
  232. UIApplication.shared.visibleViewController?.present(dialog, animated: true)
  233. }
  234. }
  235. } catch {
  236. delegate.onFailed(error: "99:Something went wrong")
  237. }
  238. }
  239. NetworkMonitor.shared.startMonitoring()
  240. OutgoingThread.default.run()
  241. InquiryThread.default.run()
  242. if UIFont.systemFont(ofSize: 12).familyName == ".AppleSystemUIFont" {
  243. UIFont.libOverrideInitialize()
  244. }
  245. _ = LocationManager()
  246. initiateSoundCall()
  247. //print("MANIA \(UIFont.systemFont(ofSize: 12)) <> \(UIFont.italicSystemFont(ofSize: 12)) <> \(UIFont.boldSystemFont(ofSize: 12))")
  248. }
  249. private static func initiateSoundCall() {
  250. do {
  251. guard let ringtonePath = Bundle.resourceBundle(for: Nexilis.self).url(forResource: "pb_call_in", withExtension: "mp3") else {
  252. return
  253. }
  254. // print("ringtone ada")
  255. ringtonePlayer = try AVAudioPlayer(contentsOf:ringtonePath)
  256. ringtonePlayer?.numberOfLoops = -1
  257. ringtonePlayer?.prepareToPlay()
  258. // print("END INITIATE ringtone")
  259. guard let ringbacktonePath = Bundle.resourceBundle(for: Nexilis.self).url(forResource: "pb_call_out", withExtension: "mp3") else {
  260. return
  261. }
  262. // print("ringbacktone ada")
  263. ringbacktonePlayer = try AVAudioPlayer(contentsOf:ringbacktonePath)
  264. ringbacktonePlayer?.numberOfLoops = -1
  265. ringbacktonePlayer?.prepareToPlay()
  266. // print("END INITIATE ringbacktone")
  267. } catch {
  268. }
  269. }
  270. public static func addFB(viewController: UIViewController, fromMAB: Bool) {
  271. if let keyWindow = UIApplication.shared.windows.first(where: { $0.isKeyWindow }) {
  272. keyWindow.addSubview(floatingButton)
  273. }
  274. if fromMAB {
  275. var vc = viewController
  276. if viewController is UINavigationController {
  277. vc = (viewController as! UINavigationController).rootViewController!
  278. }
  279. floatingButton.mySettingDelegate = vc as? any SettingMABDelegate
  280. }
  281. }
  282. private static func getPullPrefs() {
  283. DispatchQueue.global().async {
  284. let urlString = Utils.getBEId().isEmpty ? Utils.getDomainOpr() + "nexilis/logics/get_baseurl_new?key=\(Nexilis.sAPIKey)" : Utils.getDomainOpr() + "nexilis/logics/get_prefs?be=\(Utils.getBEId())&appId=\(APIS.getAppNm())"
  285. Utils.fetchDataWithCookiesAndUserAgent(from: URL(string: urlString)!) { data, response, error in
  286. if let data = data, let responseString = String(data: data, encoding: .utf8) {
  287. if let json = try? JSONSerialization.jsonObject(with: responseString.data(using: String.Encoding.utf8)!, options: JSONSerialization.ReadingOptions()) as? [String: Any?] {
  288. do {
  289. if Utils.getBEId().isEmpty {
  290. Utils.setBEId(value: "\(json["be_id"]!!)")
  291. getPullPrefs()
  292. } else {
  293. let dataArray: [[String: Any?]] = [json]
  294. if !dataArray.isEmpty && !Utils.getIsLoadThemeFromOther() {
  295. if let jsonData = try? JSONSerialization.data(withJSONObject: dataArray, options: .prettyPrinted) {
  296. // Convert to JSON String
  297. let jsonString = String(data: jsonData, encoding: .utf8)
  298. Utils.setPrefTheme(value: jsonString ?? "")
  299. Utils.setValueInitialApp(data: jsonString ?? "")
  300. }
  301. }
  302. }
  303. } catch {
  304. }
  305. }
  306. }
  307. }
  308. }
  309. }
  310. private static func getPullGroupNoMember() {
  311. if let response = Nexilis.writeSync(message: CoreMessage_TMessageBank.pullGroupNoMember(), timeout: 30 * 1000), response.isOk() {
  312. let data = response.getBody(key: CoreMessage_TMessageKey.DATA)
  313. //print("KUACAU \(data)")
  314. if !data.isEmpty {
  315. if let jsonArray = try! JSONSerialization.jsonObject(with: data.data(using: String.Encoding.utf8)!, options: JSONSerialization.ReadingOptions()) as? [AnyObject] {
  316. Database.shared.database?.inTransaction({ (fmdb, rollback) in
  317. do {
  318. for json in jsonArray {
  319. let group_id = CoreMessage_TMessageUtil.getString(json: json, key: CoreMessage_TMessageKey.GROUP_ID)
  320. _ = try Database.shared.insertRecord(fmdb: fmdb, table: "GROUP_NM", cvalues: [
  321. "group_id" : group_id,
  322. "f_name" : CoreMessage_TMessageUtil.getString(json: json, key: CoreMessage_TMessageKey.GROUP_NAME),
  323. "scope_id" : CoreMessage_TMessageUtil.getString(json: json, key: CoreMessage_TMessageKey.MESSAGE_SCOPE_ID),
  324. "image_id": CoreMessage_TMessageUtil.getString(json: json, key: CoreMessage_TMessageKey.THUMB_ID),
  325. "quote": CoreMessage_TMessageUtil.getString(json: json, key: CoreMessage_TMessageKey.QUOTE),
  326. "last_update" : CoreMessage_TMessageUtil.getString(json: json, key: CoreMessage_TMessageKey.LAST_UPDATE),
  327. "created_by" : CoreMessage_TMessageUtil.getString(json: json, key: CoreMessage_TMessageKey.CREATED_BY),
  328. "created_date" : CoreMessage_TMessageUtil.getString(json: json, key: CoreMessage_TMessageKey.CREATED_DATE),
  329. "ex_block" : CoreMessage_TMessageUtil.getString(json: json, key: CoreMessage_TMessageKey.BLOCK),
  330. "folder_id" : "",
  331. "chat_modifier" : CoreMessage_TMessageUtil.getString(json: json, key: CoreMessage_TMessageKey.CHAT_MODIFIER),
  332. "group_type" : CoreMessage_TMessageUtil.getString(json: json, key: CoreMessage_TMessageKey.IS_ORGANIZATION),
  333. "parent" : CoreMessage_TMessageUtil.getString(json: json, key: CoreMessage_TMessageKey.PARENT_ID),
  334. "level" : CoreMessage_TMessageUtil.getString(json: json, key: CoreMessage_TMessageKey.LEVEL),
  335. "is_open" : CoreMessage_TMessageUtil.getString(json: json, key: CoreMessage_TMessageKey.IS_OPEN),
  336. "official" : CoreMessage_TMessageUtil.getString(json: json, key: CoreMessage_TMessageKey.OFFICIAL_ACCOUNT),
  337. "level_edu" : CoreMessage_TMessageUtil.getString(json: json, key: CoreMessage_TMessageKey.LEVEL_EDU),
  338. "materi_edu" : CoreMessage_TMessageUtil.getString(json: json, key: CoreMessage_TMessageKey.MATERI_EDU),
  339. "is_education" : CoreMessage_TMessageUtil.getString(json: json, key: CoreMessage_TMessageKey.IS_EDUCATION)
  340. ], replace: true)
  341. }
  342. } catch {
  343. rollback.pointee = true
  344. print("Access database error: \(error.localizedDescription)")
  345. }
  346. })
  347. }
  348. }
  349. }
  350. }
  351. private static func getServiceBank() {
  352. DispatchQueue.global().async {
  353. _ = Nexilis.write(message: CoreMessage_TMessageBank.getServiceBank())
  354. }
  355. }
  356. private static func getFeatureAccess() {
  357. DispatchQueue.global().async {
  358. Utils.postDataWithCookiesAndUserAgent(from: URL(string: Utils.getDomainOpr() + "get_feature_access_new")!) { data, response, error in
  359. let response = response as? HTTPURLResponse
  360. if response?.statusCode != 200 || error != nil {
  361. return
  362. }
  363. if let data = data, let responseString = String(data: data, encoding: .utf8) {
  364. if let jsonArray = try? JSONSerialization.jsonObject(with: responseString.data(using: String.Encoding.utf8)!, options: JSONSerialization.ReadingOptions()) as? [AnyObject] {
  365. do {
  366. var jsonFA: [String: Any] = [:]
  367. for jsonData in jsonArray {
  368. var tmp = jsonData as! [String: Any]
  369. tmp.removeValue(forKey: "action")
  370. tmp.removeValue(forKey: "alert_title")
  371. tmp.removeValue(forKey: "alert_message")
  372. jsonFA[Array(tmp.keys)[0]] = Array(tmp.values)[0]
  373. if jsonData["upload_max_retry"]! != nil {
  374. let umr = jsonData["upload_max_retry"] as! String
  375. Utils.setMaxRetryUpload(value: umr)
  376. jsonFA[Array(tmp.keys)[0]] = Array(tmp.values)[0]
  377. }
  378. if jsonData["upload_max_time"]! != nil {
  379. let umt = jsonData["upload_max_time"] as! String
  380. Utils.setMaxRetryTimeUpload(value: umt)
  381. jsonFA[Array(tmp.keys)[0]] = Array(tmp.values)[0]
  382. }
  383. if jsonData["default_fb"]! != nil {
  384. if !Utils.getAfterConfigFB() {
  385. Utils.setConfigModeFB(value: jsonData["default_fb"] as! String)
  386. }
  387. jsonFA[Array(tmp.keys)[0]] = Array(tmp.values)[0]
  388. }
  389. if jsonData["authentication_duration"]! != nil {
  390. let ad = jsonData["authentication_duration"] as! String
  391. Utils.setAuthenticationDuration(value: ad)
  392. }
  393. if jsonData["secure_folder_encrypt_key"]! != nil {
  394. do {
  395. if let documentsDirectoryURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first {
  396. let secureURL = documentsDirectoryURL.appendingPathComponent("secure")
  397. if !FileManager.default.fileExists(atPath: secureURL.path){
  398. try FileManager.default.createDirectory(at: secureURL, withIntermediateDirectories: true, attributes: nil)
  399. }
  400. }
  401. try MasterKeyUtil.shared.generateAndStoreServerKey(jsonData["secure_folder_encrypt_key"] as! String)
  402. }
  403. catch {
  404. }
  405. }
  406. if jsonData["secure_folder_encrypt_key_iv"]! != nil {
  407. Utils.setSecureFolderEncryptIv(value: jsonData["secure_folder_encrypt_key_iv"] as! String)
  408. }
  409. if jsonData["chatbot_greetings"]! != nil {
  410. if let greeting = jsonData["chatbot_greetings"] as? String {
  411. print("Chatbot greeting: \(greeting)")
  412. Utils.setChatbotGreetings(value: greeting)
  413. }
  414. }
  415. }
  416. if let convertJsonFA = try? JSONSerialization.data(withJSONObject: jsonFA, options: .prettyPrinted) {
  417. if let jsonFAString = String(data: convertJsonFA, encoding: .utf8) {
  418. Utils.setFeatureAccess(value: jsonFAString)
  419. }
  420. }
  421. } catch {
  422. }
  423. }
  424. }
  425. }
  426. }
  427. }
  428. public static func checkingAccess(key: String) -> Bool {
  429. let dataAccess = Utils.getFeatureAccess()
  430. if dataAccess.isEmpty {
  431. if key == "battery_optimization_force" || key == "backup_restore" || key == "check_sim_swap" || key == "admin_features" {
  432. return false
  433. } else {
  434. return true
  435. }
  436. } else if let jsonArray = try? JSONSerialization.jsonObject(with: dataAccess.data(using: String.Encoding.utf8)!, options: []) as? [String: Any] {
  437. if jsonArray[key] != nil {
  438. return jsonArray[key] as! String == "1"
  439. } else {
  440. if key == "sms" || key == "email" || key == "whatsapp" || key == "battery_optimization_force" || key == "backup_restore" || key == "check_sim_swap" || key == "admin_features" {
  441. return false
  442. } else {
  443. return true
  444. }
  445. }
  446. }
  447. return false
  448. }
  449. private static func getPullWorkingArea() {
  450. if let response = Nexilis.writeSync(message: CoreMessage_TMessageBank.getWorkingAreaContactCenter(), timeout: 30 * 1000), response.isOk() {
  451. let data = response.getBody(key: CoreMessage_TMessageKey.DATA)
  452. if !data.isEmpty {
  453. if let jsonArray = try! JSONSerialization.jsonObject(with: data.data(using: String.Encoding.utf8)!, options: JSONSerialization.ReadingOptions()) as? [AnyObject] {
  454. Database.shared.database?.inTransaction({ (fmdb, rollback) in
  455. do {
  456. for json in jsonArray {
  457. var parent = CoreMessage_TMessageUtil.getString(json: json, key: CoreMessage_TMessageKey.PARENT_ID)
  458. if parent.isEmpty {
  459. parent = "-99"
  460. }
  461. _ = try Database.shared.insertRecord(fmdb: fmdb, table: "WORKING_AREA", cvalues: [
  462. "area_id" : CoreMessage_TMessageUtil.getString(json: json, key: CoreMessage_TMessageKey.WORKING_AREA),
  463. "name" : CoreMessage_TMessageUtil.getString(json: json, key: CoreMessage_TMessageKey.NAME),
  464. "parent" : CoreMessage_TMessageUtil.getString(json: json, key: CoreMessage_TMessageKey.PARENT_ID),
  465. "level" : CoreMessage_TMessageUtil.getString(json: json, key: CoreMessage_TMessageKey.LEVEL)
  466. ], replace: true)
  467. }
  468. } catch {
  469. rollback.pointee = true
  470. print("Access database error: \(error.localizedDescription)")
  471. }
  472. })
  473. }
  474. }
  475. }
  476. }
  477. public static func showForceSignIn() {
  478. let controller = AppStoryBoard.Palio.instance.instantiateViewController(withIdentifier: "changeDevice") as! ChangeDeviceViewController
  479. controller.forceLogin = true
  480. let navigationController = CustomNavigationController(rootViewController: controller)
  481. navigationController.modalPresentationStyle = .fullScreen
  482. navigationController.navigationBar.tintColor = .white
  483. navigationController.navigationBar.barTintColor = UIApplication.shared.visibleViewController?.traitCollection.userInterfaceStyle == .dark ? .blackDarkMode : .mainColor
  484. navigationController.navigationBar.isTranslucent = false
  485. navigationController.navigationBar.overrideUserInterfaceStyle = .dark
  486. navigationController.navigationBar.barStyle = .black
  487. let cancelButtonAttributes: [NSAttributedString.Key: Any] = [NSAttributedString.Key.foregroundColor: UIColor.white, NSAttributedString.Key.font : UIFont.systemFont(ofSize: 16)]
  488. UIBarButtonItem.appearance().setTitleTextAttributes(cancelButtonAttributes, for: .normal)
  489. let textAttributes = [NSAttributedString.Key.foregroundColor:UIColor.white]
  490. navigationController.navigationBar.titleTextAttributes = textAttributes
  491. navigationController.modalPresentationStyle = .fullScreen
  492. navigationController.modalTransitionStyle = .crossDissolve
  493. UIApplication.shared.visibleViewController?.present(navigationController, animated: true)
  494. }
  495. public static func destroyAll() {
  496. let onGoingCC: String = SecureUserDefaults.shared.value(forKey: "onGoingCC") ?? ""
  497. if !onGoingCC.isEmpty {
  498. let requester = onGoingCC.components(separatedBy: ",")[0]
  499. let officer = onGoingCC.isEmpty ? "" : onGoingCC.components(separatedBy: ",")[1]
  500. let complaintId = onGoingCC.isEmpty ? "" : onGoingCC.components(separatedBy: ",")[2]
  501. let idMe = User.getMyPin()!
  502. let startTimeCC: String = SecureUserDefaults.shared.value(forKey: "startTimeCC") ?? ""
  503. let date = "\(Date().currentTimeMillis())"
  504. Database.shared.database?.inTransaction({ (fmdb, rollback) in
  505. do {
  506. _ = try Database.shared.insertRecord(fmdb: fmdb, table: "CALL_CENTER_HISTORY", cvalues: [
  507. "type" : "0",
  508. "title" : "Contact Center".localized(),
  509. "time" : startTimeCC,
  510. "f_pin" : officer,
  511. "data" : complaintId,
  512. "time_end" : date,
  513. "complaint_id" : complaintId,
  514. "members" : "",
  515. "requester": requester
  516. ], replace: true)
  517. } catch {
  518. rollback.pointee = true
  519. print("Access database error: \(error.localizedDescription)")
  520. }
  521. })
  522. if officer == idMe {
  523. _ = Nexilis.write(message: CoreMessage_TMessageBank.endCallCenter(complaint_id: complaintId, l_pin: requester))
  524. } else {
  525. if requester == idMe {
  526. _ = Nexilis.write(message: CoreMessage_TMessageBank.endCallCenter(complaint_id: complaintId, l_pin: officer))
  527. } else {
  528. _ = Nexilis.write(message: CoreMessage_TMessageBank.leaveCCRoomInvite(ticket_id: complaintId))
  529. }
  530. }
  531. SecureUserDefaults.shared.removeValue(forKey: "onGoingCC")
  532. SecureUserDefaults.shared.removeValue(forKey: "membersCC")
  533. SecureUserDefaults.shared.removeValue(forKey: "startTimeCC")
  534. DispatchQueue.main.async {
  535. if UIApplication.shared.applicationState == .active {
  536. let imageView = UIImageView(image: UIImage(systemName: "info.circle"))
  537. imageView.tintColor = .white
  538. 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)
  539. banner.show()
  540. }
  541. }
  542. }
  543. if !Nexilis.onGoingPushCC.isEmpty {
  544. DispatchQueue.global().async {
  545. _ = Nexilis.write(message: CoreMessage_TMessageBank.timeOutRequestCallCenter(channel: Nexilis.onGoingPushCC["channel"]!, l_pin: Nexilis.onGoingPushCC["l_pin"]!))
  546. }
  547. }
  548. SecureUserDefaults.shared.removeValue(forKey: "inEditorPersonal")
  549. SecureUserDefaults.shared.removeValue(forKey: "inEditorGroup")
  550. SecureUserDefaults.shared.removeValue(forKey: "waitingRequestCC")
  551. }
  552. public static func changeUser(f_pin: String){
  553. do {
  554. //print("change user to fpin")
  555. Nexilis.dispatch = DispatchGroup()
  556. Nexilis.dispatch?.enter()
  557. try API.switchUser(cbiI: Callback(), sUserID: f_pin)
  558. // wait until connection true
  559. Nexilis.dispatch?.wait()
  560. Nexilis.dispatch = nil
  561. //print("success change user to fpin")
  562. // _ = Nexilis.write(message: CoreMessage_TMessageBank.getChangeConnectionID(p_pin: f_pin))
  563. } catch{
  564. //print(error)
  565. }
  566. }
  567. public static func apiSendChat(destination: String, message: String, isGroup: Bool, thumbnailName: String = "", imageName: String = "", videoName: String = "", fileName: String = "", audioName: String = "", replyMessageId : String = "") -> String {
  568. let message = CoreMessage_TMessageBank.sendMessage(l_pin: destination, message_scope_id: isGroup ? "4" : "3", status: "3", message_text: message, credential: "", attachment_flag: !imageName.isEmpty ? "1" : !videoName.isEmpty ? "2" : !audioName.isEmpty ? "5" : !fileName.isEmpty ? "6" : "0", ex_blog_id: "", message_large_text: "", ex_format: "", image_id: imageName, audio_id: audioName, video_id: videoName, file_id: fileName, thumb_id: thumbnailName, reff_id: replyMessageId, read_receipts: "4", chat_id: "", is_call_center: "0", call_center_id: "", opposite_pin: User.getMyPin() ?? "")
  569. addQueueMessage(message: message)
  570. return message.getBody(key: CoreMessage_TMessageKey.MESSAGE_ID)
  571. }
  572. public static func apiInitiateAudioCall(destination: String) {
  573. API.initiateCCall(sParty: destination)
  574. }
  575. public static func apiReceiveAudioCall(destination: String) {
  576. API.receiveCCall(sParty: destination)
  577. }
  578. public static func apiInitiateVideoCall(destination: String, backCamera: Bool = false, listRemoteViews: [UIImageView], localView: UIImageView, remoteViewSpeaker: UIImageView) {
  579. API.initiateCCall(sParty: destination, nCamIdx: backCamera ? 0 : 1, nResIdx: 2, nVQuality: 4, ivRemoteView: listRemoteViews, ivLocalView: localView, ivRemoteZ: remoteViewSpeaker)
  580. }
  581. public static func apiReceiveVideoCall(destination: String, backCamera: Bool = false, listRemoteViews: [UIImageView], localView: UIImageView, remoteViewSpeaker: UIImageView) {
  582. API.receiveCCall(sParty: destination, nCamIdx: backCamera ? 0 : 1, nResIdx: 2, nVQuality: 4, ivRemoteView: listRemoteViews, ivLocalView: localView, ivRemoteZ: remoteViewSpeaker)
  583. }
  584. public static func apiInitiateStreaming(localView: UIImageView, titleStream: String = "", backCamera: Bool = false) {
  585. API.initiateBC(sTitle: titleStream, nCamIdx: backCamera ? 0 : 1, nResIdx: 2, nVQuality: 4, ivLocalView: localView)
  586. }
  587. public static func apiJoinStreaming(streamerId: String, remoteView: UIImageView) {
  588. API.joinBC(sBroadcasterID: streamerId, ivRemoteView: remoteView)
  589. }
  590. public static func apiTerminateStreaming(streamerId: String?) {
  591. API.terminateBC(sBroadcasterID: streamerId)
  592. }
  593. public static func apiEndAllCall() {
  594. API.terminateCall(sParty: nil)
  595. }
  596. public static func addQueueMessage(message: TMessage, isEditMessage: Bool = false) {
  597. // OutgoingThread.default.addQueue(message: message)
  598. if isEditMessage {
  599. OutgoingThread.default.addQueue(message: message)
  600. } else {
  601. InquiryThread.default.addQueue(message: message)
  602. }
  603. }
  604. public static func deleteQueueMessage(message: TMessage) {
  605. OutgoingThread.default.addQueue(message: message)
  606. }
  607. private static var wbDelegate: WhiteboardDelegate?
  608. private static var wbReceiver: WhiteboardReceiver?
  609. public static func setWhiteboardDelegate(delegate: WhiteboardDelegate?){
  610. Nexilis.wbDelegate = delegate
  611. }
  612. public static func getWhiteboardDelegate() -> WhiteboardDelegate? {
  613. return Nexilis.wbDelegate
  614. }
  615. public static func setWhiteboardReceiver(receiver: WhiteboardReceiver?){
  616. Nexilis.wbReceiver = receiver
  617. }
  618. public static func getWhiteboardReceiver() -> WhiteboardReceiver? {
  619. return Nexilis.wbReceiver
  620. }
  621. public static func getEditorPersonal() -> EditorPersonal {
  622. return AppStoryBoard.Palio.instance.instantiateViewController(identifier: "editorPersonalVC") as! EditorPersonal
  623. }
  624. public static func getEditorGroup() -> EditorGroup {
  625. return AppStoryBoard.Palio.instance.instantiateViewController(identifier: "editorGroupVC") as! EditorGroup
  626. }
  627. public static func getEditorStarMessage() -> EditorStarMessages {
  628. return AppStoryBoard.Palio.instance.instantiateViewController(identifier: "staredVC") as! EditorStarMessages
  629. }
  630. static func getAddress(apiKey: String) -> [String] {
  631. var result = [String]()
  632. let url = URL(string: "https://nexilis.io/dipp/NuN1v3rs3/Qm3r4i0/get_ip?account=\(apiKey)")!
  633. let urlConfig = URLSessionConfiguration.default
  634. let sessionDelegate = SelfSignedURLSessionDelegate()
  635. urlConfig.requestCachePolicy = .returnCacheDataElseLoad
  636. urlConfig.timeoutIntervalForRequest = 10.0
  637. urlConfig.timeoutIntervalForResource = 10.0
  638. let semaphore = DispatchSemaphore(value: 0)
  639. let task = URLSession(configuration: urlConfig, delegate: sessionDelegate, delegateQueue: nil).dataTask(with: url) {(data, response, error) in
  640. guard let data = data else {
  641. semaphore.signal()
  642. return
  643. }
  644. let html = String(data: data, encoding: .utf8)!
  645. let base64Address = html.components(separatedBy: "<body>")[1].components(separatedBy: "</body>")[0].trimmingCharacters(in: .whitespacesAndNewlines)
  646. if let addressData = Data(base64Encoded: base64Address), let decodeAddress = String(data: addressData, encoding: .utf8) {
  647. let rows = decodeAddress.trimmingCharacters(in: CharacterSet.newlines).split(separator: ",")
  648. for r in rows {
  649. let _address = r.split(separator: ":")
  650. var ip:String = ""
  651. let _data = _address[0].split(separator: ".", maxSplits: 4, omittingEmptySubsequences: false)
  652. ip.append(String(_data[3]))
  653. ip.append(".")
  654. ip.append(String(_data[1]))
  655. ip.append(".")
  656. ip.append(String(_data[0]))
  657. ip.append(".")
  658. ip.append(String(_data[2]))
  659. result.append(ip + ":" + _address[2])
  660. }
  661. }
  662. semaphore.signal()
  663. }
  664. task.resume()
  665. _ = semaphore.wait(timeout: .distantFuture)
  666. //print("[App] getAddress:", result)
  667. return result
  668. }
  669. static func getAddressNew(apiKey: String) -> String {
  670. var result = ""
  671. if !Utils.getHarcodedIp().isEmpty {
  672. result = Utils.getHarcodedIp()
  673. return result
  674. }
  675. let url = URL(string: "\(Utils.getDomainOpr())dipp/NuN1v3rs3/Qm3r4i0/get_ip_domain?account=\(apiKey)")!
  676. let urlConfig = URLSessionConfiguration.default
  677. let sessionDelegate = SelfSignedURLSessionDelegate()
  678. urlConfig.requestCachePolicy = .returnCacheDataElseLoad
  679. urlConfig.timeoutIntervalForRequest = 10.0
  680. urlConfig.timeoutIntervalForResource = 10.0
  681. let semaphore = DispatchSemaphore(value: 0)
  682. let task = URLSession(configuration: urlConfig, delegate: sessionDelegate, delegateQueue: nil).dataTask(with: url) {(data, response, error) in
  683. guard let data = data,
  684. let url = response?.url,
  685. let httpResponse = response as? HTTPURLResponse,
  686. let fields = httpResponse.allHeaderFields as? [String: String] else {
  687. print("MASUK SINI0 \(url)")
  688. semaphore.signal()
  689. return
  690. }
  691. let cookies = HTTPCookie.cookies(withResponseHeaderFields: fields, for: url)
  692. //print("MASUK SINI1 \(cookies)")
  693. HTTPCookieStorage.shared.setCookies(cookies, for: url, mainDocumentURL: nil)
  694. if let cookieHeader = HTTPCookie.requestHeaderFields(with: cookies)["Cookie"] {
  695. Utils.setCookiesMobile(value: cookieHeader.replacingOccurrences(of: "; ", with: ";"))
  696. }
  697. let dataEncode = String(data: data, encoding: .utf8)!
  698. // print("dataEncode \(dataEncode.trimmingCharacters(in: .whitespacesAndNewlines))")
  699. // //print("decrypt \(Utils.decrypt(str: "4=sm<wmpm1ir==>wtxxl"))")
  700. if !dataEncode.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
  701. let dataDecodeBase64 = String(data: Data(base64Encoded: dataEncode)!, encoding: .utf8)!
  702. let dataRealDecode = Utils.decrypt(str: dataDecodeBase64)
  703. // print("dataRealDecode \(dataRealDecode)")
  704. do {
  705. if let jsonData = dataRealDecode.data(using: .utf8), let jsonObject = try JSONSerialization.jsonObject(with: jsonData, options: []) as? [String: Any] {
  706. var newDomain = jsonObject["domain"] as! String
  707. let jsonAddress = jsonObject["address"] as! [[String: Any]]
  708. let newIp = jsonAddress[0]["ip"] as! String
  709. let newPort = jsonAddress[0]["portI"] as! String
  710. if newDomain.substring(from: newDomain.count-1, to: nil) != "/" {
  711. newDomain += "/"
  712. }
  713. if (newIp+":"+newPort) != Utils.getIpOpr() || newDomain != Utils.getDomainOpr() {
  714. //check new domain
  715. if checkNewDomain(newDomain) {
  716. Utils.setDomainOpr(value: newDomain)
  717. Utils.setIpPortOpr(value: (newIp+":"+newPort))
  718. }
  719. }
  720. }
  721. } catch {
  722. }
  723. }
  724. semaphore.signal()
  725. }
  726. task.resume()
  727. _ = semaphore.wait(timeout: .distantFuture)
  728. result = Utils.getIpOpr()
  729. //print("[App] getAddress:", result)
  730. return result
  731. }
  732. private static func checkNewDomain(_ newDomain: String) -> Bool {
  733. var result = false
  734. let url = URL(string: "\(newDomain)dipp/NuN1v3rs3/Qm3r4i0/get_ip_domain?account=\(Nexilis.sAPIKey)")!
  735. let urlConfig = URLSessionConfiguration.default
  736. let sessionDelegate = SelfSignedURLSessionDelegate()
  737. urlConfig.requestCachePolicy = .returnCacheDataElseLoad
  738. urlConfig.timeoutIntervalForRequest = 10.0
  739. urlConfig.timeoutIntervalForResource = 10.0
  740. let semaphore = DispatchSemaphore(value: 0)
  741. let task = URLSession(configuration: urlConfig, delegate: sessionDelegate, delegateQueue: nil).dataTask(with: url) {(data, response, error) in
  742. if let httpResponse = response as? HTTPURLResponse {
  743. if httpResponse.statusCode == 200 {
  744. guard let url = response?.url,
  745. let fields = httpResponse.allHeaderFields as? [String: String] else {
  746. semaphore.signal()
  747. return
  748. }
  749. let cookies = HTTPCookie.cookies(withResponseHeaderFields: fields, for: url)
  750. HTTPCookieStorage.shared.setCookies(cookies, for: url, mainDocumentURL: nil)
  751. if let cookieHeader = HTTPCookie.requestHeaderFields(with: cookies)["Cookie"] {
  752. Utils.setCookiesMobile(value: cookieHeader.replacingOccurrences(of: "; ", with: ";"))
  753. }
  754. result = true
  755. }
  756. }
  757. semaphore.signal()
  758. }
  759. task.resume()
  760. _ = semaphore.wait(timeout: .distantFuture)
  761. return result
  762. }
  763. static func getCLMUserId() -> String {
  764. guard let me = User.getMyPin() else {
  765. return ""
  766. }
  767. return me
  768. }
  769. public static func writeSync(message: TMessage, timeout: Int = 15 * 1000) -> TMessage? {
  770. do {
  771. //print(">> SENDING MESSAGE >> ", message.toLogString())
  772. if let data = try API.sGetResponse(sRequest: message.pack(), lTimeout: timeout, bKeepTOResp: true) {
  773. let response = TMessage(data: data)
  774. //print("<< RESPONSE MESSAGE << ", response.toLogString())
  775. return response
  776. }
  777. } catch {
  778. //print(error)
  779. }
  780. return nil
  781. }
  782. public static func write(message: TMessage, timeout: Int = 15 * 1000) -> String? {
  783. do {
  784. if API.nGetCLXConnState() == 0 {
  785. return nil
  786. }
  787. //print(">> SENDING MESSAGE >> ", message.toLogString())
  788. if message.getMedia().count == 0 {
  789. if let data = try API.sSend(sData: message.pack(), nPriority: 1, lTimeout: timeout) {
  790. //print("<< RESPONSE MESSAGE << ", data)
  791. return data
  792. }
  793. }
  794. // media
  795. if let data = try API.sSend(abData: message.toBytes(), nPriority: 2, lTimeout: timeout) {
  796. //print("<< RESPONSE MESSAGE << ", data)
  797. return data
  798. }
  799. } catch {
  800. //print(error)
  801. }
  802. return nil
  803. }
  804. public static func writeDraw(data: String, timeout: Int = 15 * 1000) -> String? {
  805. do {
  806. if !API.bInetConnAvailable() {
  807. return nil
  808. }
  809. //print(">> SENDING MESSAGE >> ", data)
  810. if let data = try API.sSend(sData: data, nPriority: 1, lTimeout: timeout) {
  811. //print("<< RESPONSE MESSAGE << ", data)
  812. return data
  813. }
  814. } catch {
  815. //print(error)
  816. }
  817. return nil
  818. }
  819. public static func response(packetId: String, message: TMessage, timeout: Int = 15 * 1000) -> String? {
  820. var result: String? = nil
  821. do {
  822. if !API.bInetConnAvailable() {
  823. return nil
  824. }
  825. //print(">> RESPONSE >> " + packetId + " " + message.toLogString());
  826. result = try API.sSendResponse(sRequestID: packetId, sResponse: message.pack(), lTimeout: timeout)
  827. } catch {
  828. //print(error)
  829. }
  830. return result
  831. }
  832. public static func responseString(packetId: String, message: String, timeout: Int = 15 * 1000) -> String? {
  833. var result: String? = nil
  834. do {
  835. if !API.bInetConnAvailable() {
  836. return nil
  837. }
  838. //print(">> RESPONSE >> " + packetId + " " + message);
  839. result = try API.sSendResponse(sRequestID: packetId, sResponse: message, lTimeout: timeout)
  840. } catch {
  841. //print(error)
  842. }
  843. return result
  844. }
  845. public static func setSpeaker(_ isEnabled: Bool, isVideo: Bool = false) {
  846. do {
  847. API.adjustVolume(fValue: isEnabled ? 10.0: isVideo ? 0.0 : 3.0)
  848. } catch {
  849. }
  850. }
  851. // public static func initiateAudio() {
  852. // do {
  853. // try AVAudioSession.sharedInstance().setPreferredSampleRate(AVAudioSession.sharedInstance().sampleRate)
  854. // } catch {
  855. // }
  856. // }
  857. // public static func startAudio(isVideo: Bool = true) {
  858. // do {
  859. // try AVAudioSession.sharedInstance().setCategory(.playAndRecord, options: .defaultToSpeaker)
  860. // try AVAudioSession.sharedInstance().setMode(.voiceChat)
  861. // try AVAudioSession.sharedInstance().overrideOutputAudioPort(isVideo ? .speaker : .none)
  862. // try AVAudioSession.sharedInstance().setActive(true)
  863. // } catch {
  864. // }
  865. // }
  866. //
  867. // public static func stopAudio() {
  868. // do {
  869. // try AVAudioSession.sharedInstance().setCategory(.soloAmbient)
  870. // try AVAudioSession.sharedInstance().setMode(.default)
  871. // try AVAudioSession.sharedInstance().overrideOutputAudioPort(.none)
  872. // try AVAudioSession.sharedInstance().setActive(true)
  873. // } catch {
  874. // }
  875. // }
  876. public static func muteMicrophone(isMute: Bool!){
  877. do {
  878. if(isMute){
  879. try AVAudioSession.sharedInstance().setCategory(.playback)
  880. }
  881. else{
  882. try AVAudioSession.sharedInstance().setCategory(.playAndRecord)
  883. }
  884. }catch{
  885. //print(error)
  886. }
  887. }
  888. public static func buttonClicked(index: Int, id: String = "") {
  889. //print("BTNCLICK \(index) \(id)")
  890. if index == IDX_QUEUE_SYSTEM || index == IDX_NEWS || index == IDX_SOCIAL_COMMERCE {
  891. openUrl(url: id)
  892. } else if index == IDX_NOTIF_CENTER {
  893. APIS.openNotificationCenter()
  894. } else if index == IDX_CHAT {
  895. APIS.openChat()
  896. } else if index == IDX_CALL {
  897. APIS.openCall()
  898. } else if index == IDX_STREAM {
  899. APIS.openStreaming()
  900. } else if index == IDX_CC {
  901. APIS.openContactCenter()
  902. } else if index == IDX_ADDFRIEND {
  903. APIS.openAddFriend()
  904. } else if index == IDX_WB_SS {
  905. APIS.openWhiteboardAndScreenSharing()
  906. } else if index == IDX_WHITEBOARD {
  907. APIS.openWhiteboard()
  908. } else if index == IDX_SCREENSHARING {
  909. APIS.openWhiteboardAndScreenSharing()
  910. } else if index == IDX_POST {
  911. } else if index == IDX_CONVERSATION {
  912. APIS.openConversation()
  913. } else if index == IDX_FAVORITEMESSAGE {
  914. APIS.openFavoriteMessage()
  915. } else {
  916. openApp(id: id)
  917. }
  918. }
  919. public static func openUrl(isBNI: Bool = false, url: String = "") {
  920. let isChangeProfile = Utils.getSetProfile()
  921. if !isChangeProfile {
  922. let alert = LibAlertController(title: "Change Profile".localized(), message: "You must change your name to use this feature".localized(), preferredStyle: .alert)
  923. alert.addAction(UIAlertAction(title: "OK".localized(), style: UIAlertAction.Style.default, handler: {(_) in
  924. let controller = AppStoryBoard.Palio.instance.instantiateViewController(withIdentifier: "signupsignin") as! SignUpSignIn
  925. controller.forceLogin = true
  926. let navigationController = CustomNavigationController(rootViewController: controller)
  927. navigationController.modalPresentationStyle = .fullScreen
  928. navigationController.navigationBar.tintColor = .white
  929. navigationController.navigationBar.barTintColor = UIApplication.shared.visibleViewController?.traitCollection.userInterfaceStyle == .dark ? .blackDarkMode : .mainColor
  930. navigationController.navigationBar.isTranslucent = false
  931. navigationController.navigationBar.overrideUserInterfaceStyle = .dark
  932. navigationController.navigationBar.barStyle = .black
  933. let cancelButtonAttributes: [NSAttributedString.Key: Any] = [NSAttributedString.Key.foregroundColor: UIColor.white, NSAttributedString.Key.font : UIFont.systemFont(ofSize: 16)]
  934. UIBarButtonItem.appearance().setTitleTextAttributes(cancelButtonAttributes, for: .normal)
  935. let textAttributes = [NSAttributedString.Key.foregroundColor:UIColor.white]
  936. navigationController.navigationBar.titleTextAttributes = textAttributes
  937. if UIApplication.shared.visibleViewController?.navigationController != nil {
  938. UIApplication.shared.visibleViewController?.navigationController?.present(navigationController, animated: true, completion: nil)
  939. } else {
  940. UIApplication.shared.visibleViewController?.present(navigationController, animated: true, completion: nil)
  941. }
  942. }))
  943. if UIApplication.shared.visibleViewController?.navigationController != nil {
  944. UIApplication.shared.visibleViewController?.navigationController?.present(alert, animated: true, completion: nil)
  945. } else {
  946. UIApplication.shared.visibleViewController?.present(alert, animated: true, completion: nil)
  947. }
  948. return
  949. }
  950. let controller = BNIBookingWebView()
  951. if !isBNI {
  952. controller.customUrl = url
  953. }
  954. if UIApplication.shared.visibleViewController?.navigationController != nil {
  955. UIApplication.shared.visibleViewController?.navigationController?.present(controller, animated: true, completion: nil)
  956. } else {
  957. UIApplication.shared.visibleViewController?.present(controller, animated: true, completion: nil)
  958. }
  959. }
  960. public static func openApp(id: String) {
  961. //print("openApp itms-apps://apple.com/app/\(id)")
  962. let isChangeProfile = Utils.getSetProfile()
  963. if !isChangeProfile {
  964. let alert = LibAlertController(title: "Change Profile".localized(), message: "You must change your name to use this feature".localized(), preferredStyle: .alert)
  965. alert.addAction(UIAlertAction(title: "OK".localized(), style: UIAlertAction.Style.default, handler: {(_) in
  966. let controller = AppStoryBoard.Palio.instance.instantiateViewController(withIdentifier: "signupsignin") as! SignUpSignIn
  967. controller.forceLogin = true
  968. let navigationController = CustomNavigationController(rootViewController: controller)
  969. navigationController.modalPresentationStyle = .fullScreen
  970. navigationController.navigationBar.tintColor = .white
  971. navigationController.navigationBar.barTintColor = UIApplication.shared.visibleViewController?.traitCollection.userInterfaceStyle == .dark ? .blackDarkMode : .mainColor
  972. navigationController.navigationBar.isTranslucent = false
  973. navigationController.navigationBar.overrideUserInterfaceStyle = .dark
  974. navigationController.navigationBar.barStyle = .black
  975. let cancelButtonAttributes: [NSAttributedString.Key: Any] = [NSAttributedString.Key.foregroundColor: UIColor.white, NSAttributedString.Key.font : UIFont.systemFont(ofSize: 16)]
  976. UIBarButtonItem.appearance().setTitleTextAttributes(cancelButtonAttributes, for: .normal)
  977. let textAttributes = [NSAttributedString.Key.foregroundColor:UIColor.white]
  978. navigationController.navigationBar.titleTextAttributes = textAttributes
  979. if UIApplication.shared.visibleViewController?.navigationController != nil {
  980. UIApplication.shared.visibleViewController?.navigationController?.present(navigationController, animated: true, completion: nil)
  981. } else {
  982. UIApplication.shared.visibleViewController?.present(navigationController, animated: true, completion: nil)
  983. }
  984. }))
  985. if UIApplication.shared.visibleViewController?.navigationController != nil {
  986. UIApplication.shared.visibleViewController?.navigationController?.present(alert, animated: true, completion: nil)
  987. } else {
  988. UIApplication.shared.visibleViewController?.present(alert, animated: true, completion: nil)
  989. }
  990. return
  991. }
  992. if id == nil {
  993. return
  994. }
  995. if let url = URL(string: "itms-apps://apple.com/app/\(id)") {
  996. UIApplication.shared.open(url)
  997. }
  998. }
  999. static func openmailAction(subject: String = "", body: String = "", to: String = "") {
  1000. let subjectEncoded = subject.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!
  1001. let bodyEncoded = body.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!
  1002. let toEmail = to
  1003. let gmailUrl = URL(string: "googlegmail://co?to=\(toEmail)&subject=\(subjectEncoded)&body=\(bodyEncoded)")!
  1004. let outlookUrl = URL(string: "ms-outlook://compose?to=\(toEmail)&subject=\(subjectEncoded)&body=\(bodyEncoded)")!
  1005. let yahooMail = URL(string: "ymail://mail/compose?to=\(toEmail)&subject=\(subjectEncoded)&body=\(bodyEncoded)")!
  1006. let sparkUrl = URL(string: "readdle-spark://compose?recipient=\(toEmail)&subject=\(subjectEncoded)&body=\(bodyEncoded)")!
  1007. let defaultUrl = URL(string: "mailto:\(toEmail)?subject=\(subjectEncoded)&body=\(bodyEncoded)")!
  1008. if UIApplication.shared.canOpenURL(gmailUrl as URL) {
  1009. openMail(gmailUrl)
  1010. } else if UIApplication.shared.canOpenURL(outlookUrl as URL) {
  1011. openMail(outlookUrl)
  1012. } else if UIApplication.shared.canOpenURL(yahooMail as URL) {
  1013. openMail(yahooMail)
  1014. } else if UIApplication.shared.canOpenURL(sparkUrl as URL) {
  1015. openMail(sparkUrl)
  1016. } else if UIApplication.shared.canOpenURL(defaultUrl as URL) {
  1017. openMail(defaultUrl)
  1018. }
  1019. }
  1020. private static func openMail(_ url: URL) {
  1021. UIApplication.shared.open(url as URL, options: [:], completionHandler: nil)
  1022. }
  1023. static var alertChangeProfile = LibAlertController()
  1024. public static func checkIsChangePerson() -> Bool {
  1025. let isChangeProfile = Utils.getSetProfile()
  1026. if !isChangeProfile {
  1027. alertChangeProfile.dismiss(animated: false)
  1028. alertChangeProfile = LibAlertController(title: "Change Profile".localized(), message: "You must change your name to use this feature".localized().localized(), preferredStyle: .alert)
  1029. alertChangeProfile.addAction(UIAlertAction(title: "Cancel".localized(), style: .destructive, handler: nil))
  1030. alertChangeProfile.addAction(UIAlertAction(title: "OK".localized(), style: UIAlertAction.Style.default, handler: {(_) in
  1031. let controller = AppStoryBoard.Palio.instance.instantiateViewController(withIdentifier: "signupsignin") as! SignUpSignIn
  1032. controller.forceLogin = true
  1033. let navigationController = CustomNavigationController(rootViewController: controller)
  1034. navigationController.modalPresentationStyle = .fullScreen
  1035. navigationController.navigationBar.tintColor = .white
  1036. navigationController.navigationBar.barTintColor = UIApplication.shared.visibleViewController?.traitCollection.userInterfaceStyle == .dark ? .blackDarkMode : .mainColor
  1037. navigationController.navigationBar.isTranslucent = false
  1038. navigationController.navigationBar.overrideUserInterfaceStyle = .dark
  1039. navigationController.navigationBar.barStyle = .black
  1040. let cancelButtonAttributes: [NSAttributedString.Key: Any] = [NSAttributedString.Key.foregroundColor: UIColor.white, NSAttributedString.Key.font : UIFont.systemFont(ofSize: 16)]
  1041. UIBarButtonItem.appearance().setTitleTextAttributes(cancelButtonAttributes, for: .normal)
  1042. let textAttributes = [NSAttributedString.Key.foregroundColor:UIColor.white]
  1043. navigationController.navigationBar.titleTextAttributes = textAttributes
  1044. let rootVC = UIApplication.shared.windows.filter {$0.isKeyWindow}.first?.rootViewController
  1045. if rootVC?.presentedViewController == nil {
  1046. rootVC?.present(navigationController, animated: true, completion: nil)
  1047. } else {
  1048. rootVC?.presentedViewController?.present(navigationController, animated: true, completion: nil)
  1049. }
  1050. }))
  1051. let rootVC = UIApplication.shared.windows.filter {$0.isKeyWindow}.first?.rootViewController
  1052. if rootVC?.presentedViewController == nil {
  1053. rootVC?.present(alertChangeProfile, animated: true, completion: nil)
  1054. } else {
  1055. rootVC?.presentedViewController?.present(alertChangeProfile, animated: true, completion: nil)
  1056. }
  1057. return false
  1058. }
  1059. return true
  1060. }
  1061. public static func showLoader() {
  1062. loadingAlert = LibAlertController(title: nil, message: "Please wait...".localized(), preferredStyle: .alert)
  1063. let loadingIndicator = UIActivityIndicatorView(frame: CGRect(x: 10, y: 5, width: 50, height: 50))
  1064. loadingIndicator.hidesWhenStopped = true
  1065. loadingIndicator.style = .medium
  1066. loadingIndicator.startAnimating()
  1067. loadingAlert.view.addSubview(loadingIndicator)
  1068. UIApplication.shared.visibleViewController?.present(loadingAlert, animated: true, completion: nil)
  1069. }
  1070. public static func hideLoader(completion: @escaping () -> ()) {
  1071. loadingAlert.dismiss(animated: true, completion: completion)
  1072. }
  1073. private static var groupWait = DispatchGroup()
  1074. private static var waitQueue = [String: TMessage]()
  1075. private static var onDispatchGroupLeave = ""
  1076. public static func writeAndWait(message: TMessage, timeout: Int = 15 * 1000) -> TMessage? {
  1077. groupWait.enter()
  1078. _ = write(message: message, timeout: timeout)
  1079. waitQueue[message.getStatus()] = message
  1080. if groupWait.wait(timeout: .now() + 15) == .timedOut {
  1081. waitQueue.removeValue(forKey: message.getStatus())
  1082. groupWait.leave()
  1083. return nil
  1084. }
  1085. return waitQueue.removeValue(forKey: message.getStatus())
  1086. }
  1087. static func incomingData(packetId: String, data: AnyObject) {
  1088. let message = TMessage()
  1089. if data is String {
  1090. let d = data as! String
  1091. guard message.unpack(data: d) else {
  1092. //print("UNKNOWN DATA STRING...", data)
  1093. if(data.hasPrefix("WB")){
  1094. let dataWB = data.components(separatedBy: "/")
  1095. if(dataWB[1] == "1"){
  1096. let x = dataWB[2]
  1097. let y = dataWB[3]
  1098. let w = dataWB[4]
  1099. let h = dataWB[5]
  1100. let fc = dataWB[6]
  1101. let sw = dataWB[7]
  1102. let xo = dataWB[8]
  1103. let yo = dataWB[9]
  1104. if(Nexilis.getWhiteboardDelegate() != nil){
  1105. Nexilis.getWhiteboardDelegate()!.draw(x: x, y: y, w: w, h: h, fc: fc, sw: sw, xo: xo, yo: yo, data: "")
  1106. }
  1107. } else if(dataWB[1] == "3") {
  1108. if(Nexilis.getWhiteboardDelegate() != nil){
  1109. Nexilis.getWhiteboardDelegate()!.clear()
  1110. }
  1111. } else if(dataWB[1] == "2"){
  1112. if(Nexilis.getWhiteboardReceiver() != nil){
  1113. Nexilis.getWhiteboardReceiver()!.incomingWB(roomId: dataWB[2])
  1114. }
  1115. } else if(dataWB[1] == "22"){
  1116. } else if(dataWB[1] == "88"){
  1117. if(Nexilis.getWhiteboardReceiver() != nil){
  1118. Nexilis.getWhiteboardReceiver()!.cancel(roomId: dataWB[2])
  1119. }
  1120. }
  1121. }
  1122. return
  1123. }
  1124. } else if data is [UInt8] {
  1125. let d = data as! [UInt8]
  1126. guard message.unpack(bytes_data: d) else {
  1127. //print("UNKNOWN DATA BYTES...", data)
  1128. return
  1129. }
  1130. }
  1131. message.mBodies[CoreMessage_TMessageKey.PACKET_ID] = packetId
  1132. if let _ = waitQueue[message.getStatus()] {
  1133. //print("MESSAGE INCOMING DATA \(message.toLogString())")
  1134. if message.mBodies.keys.contains(CoreMessage_TMessageKey.ERRCOD) {
  1135. if onDispatchGroupLeave != message.getStatus() {
  1136. onDispatchGroupLeave = message.getStatus()
  1137. //print("LEAVE GROUP INCOMING DATA")
  1138. waitQueue[message.getStatus()] = message
  1139. groupWait.leave()
  1140. return
  1141. }
  1142. }
  1143. }
  1144. IncomingThread.default.addQueue(message: message)
  1145. }
  1146. static func saveMessage(message: TMessage, withStatus: Bool = true) {
  1147. // print("save message \(message.toLogString())")
  1148. guard let me = User.getMyPin() else {
  1149. return
  1150. }
  1151. let message_id = message.getBody(key : CoreMessage_TMessageKey.MESSAGE_ID, default_value : "")
  1152. guard !message_id.isEmpty else {
  1153. return
  1154. }
  1155. let f_pin = message.getBody(key : CoreMessage_TMessageKey.F_PIN, default_value : "")
  1156. guard !f_pin.isEmpty else {
  1157. return
  1158. }
  1159. Database.shared.database?.inTransaction({ (fmdb, rollback) in
  1160. do {
  1161. // if let cursor = Database.shared.getRecords(fmdb: fmdb, query: "select message_id from MESSAGE where message_id = '\(message_id)'") {
  1162. // if cursor.next() {
  1163. // //print("message exist")
  1164. // return
  1165. // }
  1166. // cursor.close()
  1167. // }
  1168. let l_pin = message.getBody(key : CoreMessage_TMessageKey.L_PIN, default_value : "")
  1169. let scope = message.getBody(key : CoreMessage_TMessageKey.MESSAGE_SCOPE_ID, default_value : "3")
  1170. let status = message.getBody(key : CoreMessage_TMessageKey.STATUS, default_value : "")
  1171. let chat_id = message.getBody(key : CoreMessage_TMessageKey.CHAT_ID, default_value : "")
  1172. let broadcast_flag = message.getBody(key: CoreMessage_TMessageKey.BROADCAST_FLAG, default_value: "0")
  1173. let is_call_center = message.getBody(key: CoreMessage_TMessageKey.IS_CALL_CENTER, default_value: "0")
  1174. let call_center_id = message.getBody(key: CoreMessage_TMessageKey.CALL_CENTER_ID, default_value: "")
  1175. let last_edited = message.getBodyAsLong(key: CoreMessage_TMessageKey.LAST_EDIT, default_value: 0)
  1176. //print("prepare save db")
  1177. do {
  1178. _ = try Database.shared.insertRecord(fmdb: fmdb, table: "MESSAGE", cvalues: [
  1179. "message_id" : message_id,
  1180. "f_pin" : f_pin,
  1181. "f_display_name" : message.getBody(key : CoreMessage_TMessageKey.F_DISPLAY_NAME, default_value : ""),
  1182. "l_pin" : l_pin,
  1183. "l_user_id" : message.getBody(key : CoreMessage_TMessageKey.L_USER_ID, default_value : ""),
  1184. "message_scope_id" : scope,
  1185. "server_date" : message.getBody(key: CoreMessage_TMessageKey.SERVER_DATE, default_value : String(Date().currentTimeMillis())),
  1186. "status" : status,
  1187. "message_text" : message.getBody(key : CoreMessage_TMessageKey.MESSAGE_TEXT, default_value : "").toNormalString(),
  1188. "audio_id" : message.getBody(key : CoreMessage_TMessageKey.AUDIO_ID, default_value : ""),
  1189. "video_id" : message.getBody(key : CoreMessage_TMessageKey.VIDEO_ID, default_value : ""),
  1190. "image_id" : message.getBody(key : CoreMessage_TMessageKey.IMAGE_ID, default_value : ""),
  1191. "file_id" : message.getBody(key : CoreMessage_TMessageKey.FILE_ID, default_value : ""),
  1192. "gif_id" : message.getBody(key : CoreMessage_TMessageKey.GIF_ID, default_value : ""),
  1193. "thumb_id" : message.getBody(key : CoreMessage_TMessageKey.THUMB_ID, default_value : ""),
  1194. "opposite_pin" : message.getBody(key : CoreMessage_TMessageKey.OPPOSITE_PIN, default_value : ""),
  1195. "format" : message.getBody(key : CoreMessage_TMessageKey.FORMAT, default_value : ""),
  1196. "blog_id" : message.getBody(key : CoreMessage_TMessageKey.BLOG_ID, default_value : ""),
  1197. "read_receipts" : message.getBody(key: CoreMessage_TMessageKey.READ_RECEIPTS, default_value: "0"),
  1198. "chat_id" : chat_id,
  1199. "account_type" : message.getBody(key : CoreMessage_TMessageKey.BUSINESS_CATEGORY, default_value : "1"),
  1200. "credential" : message.getBody(key : CoreMessage_TMessageKey.CREDENTIAL, default_value : ""),
  1201. "reff_id" : message.getBody(key : CoreMessage_TMessageKey.REF_ID, default_value : ""),
  1202. "message_large_text" : message.getBody(key : CoreMessage_TMessageKey.BODY, default_value : "").toNormalString(),
  1203. "attachment_flag" : message.getBody(key: CoreMessage_TMessageKey.ATTACHMENT_FLAG, default_value: "0"),
  1204. "local_timestamp" : message.getBody(key: CoreMessage_TMessageKey.LOCAL_TIMESTAMP, default_value : String(Date().currentTimeMillis())),
  1205. "broadcast_flag" : broadcast_flag,
  1206. "is_call_center" : is_call_center,
  1207. "call_center_id" : call_center_id,
  1208. "last_edited" : last_edited
  1209. ], replace: true)
  1210. } catch {
  1211. rollback.pointee = true
  1212. //print(error)
  1213. }
  1214. if withStatus {
  1215. do {
  1216. if scope == "4" {
  1217. for pin in getGroupMembers(fmdb: fmdb, l_pin: l_pin) {
  1218. if f_pin == pin { continue }
  1219. _ = try Database.shared.insertRecord(fmdb: fmdb, table: "MESSAGE_STATUS", cvalues: [
  1220. "message_id" : message_id,
  1221. "status" : status,
  1222. "f_pin" : pin,
  1223. "last_update" : Date().currentTimeMillis()
  1224. ], replace: true)
  1225. }
  1226. } else {
  1227. _ = try Database.shared.insertRecord(fmdb: fmdb, table: "MESSAGE_STATUS", cvalues: [
  1228. "message_id" : message_id,
  1229. "status" : status,
  1230. "f_pin" : l_pin,
  1231. "last_update" : Date().currentTimeMillis()
  1232. ], replace: true)
  1233. }
  1234. } catch {
  1235. rollback.pointee = true
  1236. //print(error)
  1237. }
  1238. }
  1239. var pin = l_pin
  1240. if l_pin == me {
  1241. pin = f_pin
  1242. }
  1243. if !chat_id.isEmpty {
  1244. pin = chat_id
  1245. }
  1246. var counter : Int? = nil
  1247. if !withStatus {
  1248. if let cursor = Database.shared.getRecords(fmdb: fmdb, query: "select counter from MESSAGE_SUMMARY where l_pin = '\(pin)'"), cursor.next() {
  1249. counter = Int(cursor.int(forColumnIndex: 0))
  1250. if last_edited == 0 {
  1251. counter! += 1
  1252. }
  1253. cursor.close()
  1254. //print("select db message summary")
  1255. }
  1256. if counter == nil {
  1257. counter = 1
  1258. //print("set counter message summary")
  1259. }
  1260. }
  1261. if counter == nil {
  1262. counter = 0
  1263. }
  1264. if is_call_center == "0" {
  1265. do {
  1266. var queryGetLastMessageId = "SELECT message_id FROM MESSAGE where f_pin = '\(pin)' OR l_pin = '\(pin)' order by server_date desc LIMIT 1"
  1267. if scope == "4" {
  1268. queryGetLastMessageId = "SELECT message_id FROM MESSAGE where l_pin = '\(pin)' AND chat_id = '' order by server_date desc LIMIT 1"
  1269. if !chat_id.isEmpty {
  1270. queryGetLastMessageId = "SELECT message_id FROM MESSAGE where chat_id = '\(pin)' order by server_date desc LIMIT 1"
  1271. }
  1272. }
  1273. var messageId = ""
  1274. if let cursorData = Database.shared.getRecords(fmdb: fmdb, query: queryGetLastMessageId), cursorData.next() {
  1275. messageId = cursorData.string(forColumnIndex: 0) ?? ""
  1276. cursorData.close()
  1277. }
  1278. if !messageId.isEmpty {
  1279. _ = try Database.shared.insertRecord(fmdb: fmdb, table: "MESSAGE_SUMMARY", cvalues: [
  1280. "l_pin" : pin,
  1281. "message_id" : messageId,
  1282. "counter" : counter!
  1283. ], replace: true)
  1284. }
  1285. } catch {
  1286. rollback.pointee = true
  1287. //print(error)
  1288. }
  1289. }
  1290. if !withStatus {
  1291. DispatchQueue.main.async {
  1292. if let delegate = Nexilis.shared.messageDelegate, Utils.getSetProfile() {
  1293. message.mBodies[CoreMessage_TMessageKey.MESSAGE_TEXT] = message.getBody(key : CoreMessage_TMessageKey.MESSAGE_TEXT, default_value : "").toNormalString()
  1294. delegate.onReceive(message: message)
  1295. }
  1296. }
  1297. }
  1298. //print("insert db message summary \(message_id)")
  1299. } catch {
  1300. rollback.pointee = true
  1301. print("Access database error: \(error.localizedDescription)")
  1302. }
  1303. })
  1304. }
  1305. public static func saveMessageBot(textMessage: String, blog_id: String, attachment_type:String)->Void{
  1306. guard let me = User.getMyPin() else {
  1307. return
  1308. }
  1309. var user_id:String? = ""
  1310. let message_id = me + CoreMessage_TMessageUtil.getTID()
  1311. Database.shared.database?.inTransaction({ (fmdb, rollback) in
  1312. do {
  1313. if let cursor = Database.shared.getRecords(fmdb: fmdb, query: "select user_id from BUDDY where f_pin = '\(me)'"), cursor.next() {
  1314. user_id = cursor.string(forColumnIndex: 0)
  1315. cursor.close()
  1316. }
  1317. } catch {
  1318. rollback.pointee = true
  1319. print("Access database error: \(error.localizedDescription)")
  1320. }
  1321. })
  1322. Database.shared.database?.inTransaction({ (fmdb, rollback) in
  1323. do {
  1324. _ = try Database.shared.insertRecord(fmdb: fmdb, table: "MESSAGE", cvalues: [
  1325. "message_id" : message_id ,
  1326. "f_pin" : "-999",
  1327. "f_display_name" : "Bot",
  1328. "l_pin" : me,
  1329. "l_user_id" : String(user_id!),
  1330. "message_scope_id" : "3",
  1331. "server_date" : String(Date().currentTimeMillis()),
  1332. "status" : "3",
  1333. "message_text" : textMessage,
  1334. "audio_id" : "",
  1335. "video_id" : "",
  1336. "image_id" : "",
  1337. "file_id" : "",
  1338. "thumb_id" : "",
  1339. "opposite_pin" : "",
  1340. "format" : "",
  1341. "blog_id" : blog_id,
  1342. "read_receipts" : "0",
  1343. "chat_id" : "",
  1344. "account_type" : "1",
  1345. "credential" :"",
  1346. "reff_id" : "",
  1347. "message_large_text" : "",
  1348. "attachment_flag" : attachment_type,
  1349. "local_timestamp" : String(Date().currentTimeMillis())
  1350. ], replace: true)
  1351. } catch {
  1352. rollback.pointee = true
  1353. print("Access database error: \(error.localizedDescription)")
  1354. }
  1355. })
  1356. let pin = "-999"
  1357. var counter : Int? = nil
  1358. Database.shared.database?.inTransaction({ (fmdb, rollback) in
  1359. do {
  1360. if let cursor = Database.shared.getRecords(fmdb: fmdb, query: "select counter from MESSAGE_SUMMARY where l_pin = '\(pin)'"), cursor.next() {
  1361. counter = Int(cursor.int(forColumnIndex: 0))
  1362. counter! += 1
  1363. cursor.close()
  1364. //print("select db message summary")
  1365. }
  1366. } catch {
  1367. rollback.pointee = true
  1368. print("Access database error: \(error.localizedDescription)")
  1369. }
  1370. })
  1371. if counter == nil {
  1372. counter = 1
  1373. //print("set counter message summary")
  1374. }
  1375. Database.shared.database?.inTransaction({ (fmdb, rollback) in
  1376. do {
  1377. _ = try Database.shared.insertRecord(fmdb: fmdb, table: "MESSAGE_SUMMARY", cvalues: [
  1378. "l_pin" : pin,
  1379. "message_id" : message_id,
  1380. "counter" : counter!
  1381. ], replace: true)
  1382. } catch {
  1383. rollback.pointee = true
  1384. print("Access database error: \(error.localizedDescription)")
  1385. }
  1386. })
  1387. //print("insert db message summary \(message_id)")
  1388. }
  1389. static func updateMessageStatus(message: TMessage) -> Void {
  1390. let message_id = message.getBody(key : CoreMessage_TMessageKey.MESSAGE_ID, default_value : "")
  1391. guard !message_id.isEmpty else {
  1392. return
  1393. }
  1394. let status = message.getBody(key : CoreMessage_TMessageKey.STATUS, default_value : "")
  1395. let latitude = message.getBody(key : CoreMessage_TMessageKey.LATITUDE, default_value : "")
  1396. let longitude = message.getBody(key : CoreMessage_TMessageKey.LONGITUDE, default_value : "")
  1397. let desc = message.getBody(key : CoreMessage_TMessageKey.DESCRIPTION, default_value : "")
  1398. guard !status.isEmpty else {
  1399. return
  1400. }
  1401. let l_pin = message.getBody(key : CoreMessage_TMessageKey.L_PIN, default_value : "")
  1402. guard !l_pin.isEmpty else {
  1403. return
  1404. }
  1405. Database.shared.database?.inTransaction({ (fmdb, rollback) in
  1406. do {
  1407. if message_id.starts(with: "-1") || message_id.starts(with: "-2") {
  1408. for s in message_id.split(separator: ",") {
  1409. let t = s.trimmingCharacters(in: .whitespaces)
  1410. if t == "-1" || t == "-2" {
  1411. continue
  1412. }
  1413. if let cursorStatus = Database.shared.getRecords(fmdb: fmdb, query: "SELECT status FROM MESSAGE_STATUS where message_id = '\(t)'"), cursorStatus.next() {
  1414. let lastStatus = cursorStatus.int(forColumnIndex: 0)
  1415. if lastStatus < Int(status)! {
  1416. if status == "3" {
  1417. _ = Database.shared.updateRecord(fmdb: fmdb, table: "MESSAGE_STATUS", cvalues: [
  1418. "status" : status,
  1419. "longitude" : longitude,
  1420. "latitude" : latitude,
  1421. "location" : desc,
  1422. "time_delivered" : String(Date().currentTimeMillis()),
  1423. "last_update" : String(Date().currentTimeMillis())], _where: "message_id = '\(t)' and f_pin = '\(l_pin)'")
  1424. } else if status == "4" {
  1425. _ = Database.shared.updateRecord(fmdb: fmdb, table: "MESSAGE_STATUS", cvalues: [
  1426. "status" : status,
  1427. "time_read" : String(Date().currentTimeMillis()),
  1428. "longitude" : longitude,
  1429. "latitude" : latitude,
  1430. "location" : desc,
  1431. "last_update" : String(Date().currentTimeMillis())], _where: "message_id = '\(t)' and f_pin = '\(l_pin)'")
  1432. } else if status == "8" {
  1433. _ = Database.shared.updateRecord(fmdb: fmdb, table: "MESSAGE_STATUS", cvalues: [
  1434. "status" : status,
  1435. "time_ack" : String(Date().currentTimeMillis()),
  1436. "longitude" : longitude,
  1437. "latitude" : latitude,
  1438. "location" : desc,
  1439. "last_update" : String(Date().currentTimeMillis())], _where: "message_id = '\(t)' and f_pin = '\(l_pin)'")
  1440. } else {
  1441. _ = Database.shared.updateRecord(fmdb: fmdb, table: "MESSAGE_STATUS", cvalues: [
  1442. "status" : status,
  1443. "last_update" : String(Date().currentTimeMillis())], _where: "message_id = '\(t)' and f_pin = '\(l_pin)'")
  1444. }
  1445. }
  1446. cursorStatus.close()
  1447. }
  1448. }
  1449. } else {
  1450. if let cursorStatus = Database.shared.getRecords(fmdb: fmdb, query: "SELECT status FROM MESSAGE_STATUS where message_id = '\(message_id)'"), cursorStatus.next() {
  1451. let lastStatus = cursorStatus.int(forColumnIndex: 0)
  1452. if lastStatus < Int(status)! {
  1453. if status == "3" {
  1454. _ = Database.shared.updateRecord(fmdb: fmdb, table: "MESSAGE_STATUS", cvalues: [
  1455. "status" : status,
  1456. "time_delivered" : String(Date().currentTimeMillis()),
  1457. "longitude" : longitude,
  1458. "latitude" : latitude,
  1459. "location" : desc,
  1460. "last_update" : String(Date().currentTimeMillis())], _where: "message_id = '\(message_id)' and f_pin = '\(l_pin)'")
  1461. } else if status == "4" {
  1462. _ = Database.shared.updateRecord(fmdb: fmdb, table: "MESSAGE_STATUS", cvalues: [
  1463. "status" : status,
  1464. "time_read" : String(Date().currentTimeMillis()),
  1465. "longitude" : longitude,
  1466. "latitude" : latitude,
  1467. "location" : desc,
  1468. "last_update" : String(Date().currentTimeMillis())], _where: "message_id = '\(message_id)' and f_pin = '\(l_pin)'")
  1469. } else if status == "8" {
  1470. _ = Database.shared.updateRecord(fmdb: fmdb, table: "MESSAGE_STATUS", cvalues: [
  1471. "status" : status,
  1472. "time_ack" : String(Date().currentTimeMillis()),
  1473. "longitude" : longitude,
  1474. "latitude" : latitude,
  1475. "location" : desc,
  1476. "last_update" : String(Date().currentTimeMillis())], _where: "message_id = '\(message_id)' and f_pin = '\(l_pin)'")
  1477. } else {
  1478. _ = Database.shared.updateRecord(fmdb: fmdb, table: "MESSAGE_STATUS", cvalues: [
  1479. "status" : status,
  1480. "longitude" : longitude,
  1481. "latitude" : latitude,
  1482. "location" : desc,
  1483. "last_update" : String(Date().currentTimeMillis())], _where: "message_id = '\(message_id)' and f_pin = '\(l_pin)'")
  1484. }
  1485. }
  1486. cursorStatus.close()
  1487. }
  1488. }
  1489. } catch {
  1490. rollback.pointee = true
  1491. print("Access database error: \(error.localizedDescription)")
  1492. }
  1493. })
  1494. }
  1495. static func getGroupMembers(fmdb: FMDatabase, l_pin: String) -> [String] {
  1496. var result = [String]()
  1497. if let cursor = Database.shared.getRecords(fmdb: fmdb, query: "select f_pin from GROUPZ_MEMBER where group_id = '\(l_pin)'") {
  1498. while cursor.next() {
  1499. if let value = cursor.string(forColumnIndex: 0) {
  1500. result.append(value)
  1501. }
  1502. }
  1503. cursor.close()
  1504. }
  1505. return result
  1506. }
  1507. static func getVideoThumbnail(name: String, completion: @escaping (Bool)->()) {
  1508. DispatchQueue.global().async {
  1509. do {
  1510. let fileManager = FileManager.default
  1511. let documentDir = try fileManager.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
  1512. let fileDir = documentDir.appendingPathComponent(name)
  1513. let path = fileDir.path
  1514. if FileManager.default.fileExists(atPath: path) {
  1515. let asset = AVAsset(url: URL(fileURLWithPath: path))
  1516. let avAssetImageGenerator = AVAssetImageGenerator(asset: asset)
  1517. avAssetImageGenerator.appliesPreferredTrackTransform = true
  1518. let thumnailTime = CMTimeMake(value: 2, timescale: 1)
  1519. let thumbImage = UIImage(cgImage: try avAssetImageGenerator.copyCGImage(at: thumnailTime, actualTime: nil))
  1520. guard let data = thumbImage.jpegData(compressionQuality: 1.0) else {
  1521. completion(false)
  1522. return
  1523. }
  1524. let thumbFileDir = documentDir.appendingPathComponent("THUMB_" + name)
  1525. try data.write(to: thumbFileDir)
  1526. completion(true)
  1527. } else {
  1528. completion(false)
  1529. }
  1530. } catch {
  1531. //print(error)
  1532. }
  1533. }
  1534. }
  1535. static func resizedImage(at url: URL, for size: CGSize) -> UIImage? {
  1536. var image : UIImage?
  1537. if FileManager.default.fileExists(atPath: url.path){
  1538. image = UIImage(contentsOfFile: url.path)
  1539. }
  1540. else if FileEncryption.shared.isSecureExists(filename: url.lastPathComponent) {
  1541. do {
  1542. if let imageData = try FileEncryption.shared.readSecure(filename: url.lastPathComponent) {
  1543. image = UIImage(data: imageData)
  1544. }
  1545. }
  1546. catch {
  1547. }
  1548. }
  1549. if image == nil {
  1550. return nil
  1551. }
  1552. let renderer = UIGraphicsImageRenderer(size: size)
  1553. return renderer.image { (context) in
  1554. image!.draw(in: CGRect(origin: .zero, size: size))
  1555. }
  1556. }
  1557. static func initFollowing() -> Void {
  1558. if let me = User.getMyPin() {
  1559. if let response = Nexilis.writeSync(message: CoreMessage_TMessageBank.getListFollowing(l_pin: me)) {
  1560. let data = response.getBody(key: CoreMessage_TMessageKey.DATA)
  1561. if !data.isEmpty {
  1562. if let jsonArray = try! JSONSerialization.jsonObject(with: data.data(using: String.Encoding.utf8)!, options: JSONSerialization.ReadingOptions()) as? [AnyObject] {
  1563. Database.shared.database?.inTransaction({ (fmdb, rollback) in
  1564. do {
  1565. for json in jsonArray {
  1566. _ = try Database.shared.insertRecord(fmdb: fmdb, table: "FOLLOW", cvalues: [
  1567. "f_pin" : CoreMessage_TMessageUtil.getString(json: json, key: "pin")
  1568. ], replace: true)
  1569. }
  1570. } catch {
  1571. rollback.pointee = true
  1572. print("Access database error: \(error.localizedDescription)")
  1573. }
  1574. })
  1575. }
  1576. }
  1577. }
  1578. }
  1579. }
  1580. // do {
  1581. // _ = try Database.shared.insertRecord(fmdb: fmdb, table: "CALL_CENTER_HISTORY", cvalues: [
  1582. // "type" : "1",
  1583. // "title" : displayName,
  1584. // "time" : timeStart,
  1585. // "f_pin" : f_pin,
  1586. // "data" : dataCC,
  1587. // "time_end" : date,
  1588. // "complaint_id" : complaint_id.isEmpty ? "C\(date)" : complaint_id,
  1589. // "members" : "",
  1590. // "requester": ""
  1591. // ], replace: true)
  1592. // _ = try Database.shared.insertRecord(fmdb: fmdb, table: "PREFS", cvalues: [
  1593. // "key" : "CC:\(f_pin)",
  1594. // "value" : status,
  1595. // ], replace: true)
  1596. // ret = true
  1597. // } catch {
  1598. // rollback.pointee = true
  1599. // //print(error)
  1600. // }
  1601. private static var uploadQueue = DispatchQueue(label: "UPLOAD_DICT", attributes: .concurrent)
  1602. private static var UPLOAD_DICT = [String: Network]()
  1603. static func removeUploadFile(forKey: String) -> Network? {
  1604. var _result: Network? = nil
  1605. uploadQueue.sync {
  1606. _result = self.UPLOAD_DICT.removeValue(forKey: forKey)
  1607. }
  1608. return _result
  1609. }
  1610. static func putUploadFile(forKey: String, uploader: Network) {
  1611. uploadQueue.async (flags: .barrier) {
  1612. self.UPLOAD_DICT[forKey] = uploader
  1613. }
  1614. }
  1615. static func getUploadFile(forKey: String) -> Network? {
  1616. var _result: Network? = nil
  1617. uploadQueue.sync {
  1618. _result = self.UPLOAD_DICT[forKey]
  1619. }
  1620. return _result
  1621. }
  1622. private static var downloadQueue = DispatchQueue(label: "DOWNLOAD_DICT", attributes: .concurrent)
  1623. private static var DOWNLOAD_DICT = [String:Download]()
  1624. static func addDownload(forKey : String, download: Download){
  1625. downloadQueue.async (flags: .barrier) {
  1626. self.DOWNLOAD_DICT[forKey] = download
  1627. }
  1628. }
  1629. static func getDownload(forKey: String) -> Download? {
  1630. var _result: Download? = nil
  1631. downloadQueue.sync {
  1632. _result = self.DOWNLOAD_DICT[forKey]
  1633. }
  1634. return _result
  1635. }
  1636. static func removeDownload(forKey: String) -> Download? {
  1637. var _result: Download? = nil
  1638. downloadQueue.sync {
  1639. _result = self.DOWNLOAD_DICT.removeValue(forKey: forKey)
  1640. }
  1641. return _result
  1642. }
  1643. static func writeImageToFile(data: Data, fileName: String){
  1644. guard let directory = FileManager.default.urls(for: .picturesDirectory, in: .userDomainMask).last else {
  1645. return
  1646. }
  1647. let fileURL = directory.appendingPathComponent("\(fileName)")
  1648. if FileManager.default.fileExists(atPath: fileURL.path) {
  1649. if let fileHandle = FileHandle(forWritingAtPath: fileURL.path) {
  1650. fileHandle.seekToEndOfFile()
  1651. fileHandle.write(data)
  1652. fileHandle.closeFile()
  1653. } else {
  1654. //print("Can't open file to write")
  1655. }
  1656. } else {
  1657. do {
  1658. try data.write(to: fileURL, options: .atomic)
  1659. } catch {
  1660. //print("Unable to write in new file")
  1661. }
  1662. }
  1663. }
  1664. static func writeVideoToFile(data: Data, fileName: String){
  1665. guard let directory = FileManager.default.urls(for: .moviesDirectory, in: .userDomainMask).last else {
  1666. return
  1667. }
  1668. let fileURL = directory.appendingPathComponent("\(fileName)")
  1669. if FileManager.default.fileExists(atPath: fileURL.path) {
  1670. if let fileHandle = FileHandle(forWritingAtPath: fileURL.path) {
  1671. fileHandle.seekToEndOfFile()
  1672. fileHandle.write(data)
  1673. fileHandle.closeFile()
  1674. } else {
  1675. //print("Can't open file to write")
  1676. }
  1677. } else {
  1678. do {
  1679. try data.write(to: fileURL, options: .atomic)
  1680. } catch {
  1681. //print("Unable to write in new file")
  1682. }
  1683. }
  1684. }
  1685. static func writeDocumentsToFile(data: Data, fileName: String){
  1686. guard let directory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).last else {
  1687. return
  1688. }
  1689. let fileURL = directory.appendingPathComponent("\(fileName)")
  1690. if FileManager.default.fileExists(atPath: fileURL.path) {
  1691. if let fileHandle = FileHandle(forWritingAtPath: fileURL.path) {
  1692. fileHandle.seekToEndOfFile()
  1693. fileHandle.write(data)
  1694. fileHandle.closeFile()
  1695. } else {
  1696. //print("Can't open file to write")
  1697. }
  1698. } else {
  1699. do {
  1700. try data.write(to: fileURL, options: .atomic)
  1701. } catch {
  1702. //print("Unable to write in new file")
  1703. }
  1704. }
  1705. }
  1706. public static func checkMicPermission() -> Bool {
  1707. var permissionCheck: Bool = false
  1708. switch AVAudioSession.sharedInstance().recordPermission {
  1709. case .granted:
  1710. permissionCheck = true
  1711. case .denied:
  1712. permissionCheck = false
  1713. case .undetermined:
  1714. Nexilis.dispatch = DispatchGroup()
  1715. Nexilis.dispatch?.enter()
  1716. AVAudioSession.sharedInstance().requestRecordPermission({ (granted) in
  1717. if granted {
  1718. permissionCheck = true
  1719. } else {
  1720. permissionCheck = false
  1721. }
  1722. if let dispatch = Nexilis.dispatch {
  1723. dispatch.leave()
  1724. }
  1725. })
  1726. Nexilis.dispatch?.wait()
  1727. Nexilis.dispatch = nil
  1728. default:
  1729. break
  1730. }
  1731. return permissionCheck
  1732. }
  1733. public static func checkCameraPermission() -> Int {
  1734. var permissionCheck: Int = -1
  1735. if AVCaptureDevice.authorizationStatus(for: .video) == .authorized {
  1736. permissionCheck = 1
  1737. } else if AVCaptureDevice.authorizationStatus(for: .video) == .denied {
  1738. permissionCheck = 0
  1739. } else {
  1740. AVCaptureDevice.requestAccess(for: .video, completionHandler: { (granted: Bool) -> Void in
  1741. })
  1742. }
  1743. return permissionCheck
  1744. }
  1745. // public static func startTimer(){
  1746. // broadcastTimer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true, block: {_ in
  1747. // if(!openBroadcast && !broadcastList.isEmpty){
  1748. // openBroadcast = true
  1749. // let m = broadcastList.removeFirst()
  1750. // //print("broadcast show: \(m)")
  1751. // DispatchQueue.main.async {
  1752. // Nexilis.shared.showBroadcastMessage(m: m)
  1753. // }
  1754. // }
  1755. // })
  1756. // }
  1757. public static func debugBroadcast(){
  1758. if(Utils.getDebugBC() != nil) {
  1759. let m = Utils.getDebugBC()
  1760. Nexilis.shared.showBroadcastMessage(m: m!)
  1761. }
  1762. }
  1763. /*
  1764. * Delegate
  1765. */
  1766. weak open var loginDelegate: LoginDelegate?
  1767. weak open var messageDelegate: MessageDelegate?
  1768. weak open var groupDelegate: GroupDelegate?
  1769. weak open var callDelegate: CallDelegate?
  1770. weak open var streamingDelagate: LiveStreamingDelegate?
  1771. weak open var seminarDelegate: SeminarDelegate?
  1772. weak open var personInfoDelegate: PersonInfoDelegate?
  1773. weak open var screenSharingDelegate: ScreenSharingDelegate?
  1774. weak open var commentDelegate: CommentDelegate?
  1775. weak open var uploadDelegate: UploadDelegate?
  1776. weak open var timelineDelegate: TimelineDelegate?
  1777. weak open var connectionDelegate: ConnectionDelegate?
  1778. var floating: FloatingNotificationBanner!
  1779. var stateUnfriend = ""
  1780. }
  1781. struct LibFontName {
  1782. static let regular = "Poppins-Regular"
  1783. static let bold = "Poppins-SemiBold"
  1784. static let italic = "Poppins-Italic"
  1785. static let medium = "Poppins-Medium"
  1786. static let boldItalic = "Poppins-SemiBoldItalic"
  1787. }
  1788. extension UIFontDescriptor.AttributeName {
  1789. static let nsctFontUIUsage = UIFontDescriptor.AttributeName(rawValue: "NSCTFontUIUsageAttribute")
  1790. }
  1791. extension UIFont {
  1792. static var isOverrided: Bool = false
  1793. static let FONT_SELECT = 0
  1794. @objc class func libSystemFont(ofSize size: CGFloat) -> UIFont? {
  1795. if UIFont(name: LibFontName.regular, size: size) == nil {
  1796. jbs_registerFont(withFilenameString: LibFontName.regular)
  1797. }
  1798. return UIFont(name: LibFontName.regular, size: size)
  1799. }
  1800. @objc class func libSystemFontWeight(ofSize size: CGFloat, weight: UIFont.Weight) -> UIFont? {
  1801. if weight == .medium {
  1802. if UIFont(name: LibFontName.medium, size: size) == nil {
  1803. jbs_registerFont(withFilenameString: LibFontName.medium)
  1804. }
  1805. return UIFont(name: LibFontName.medium, size: size)
  1806. } else if weight == .semibold {
  1807. if UIFont(name: LibFontName.boldItalic, size: size) == nil {
  1808. jbs_registerFont(withFilenameString: LibFontName.boldItalic)
  1809. }
  1810. return UIFont(name: LibFontName.boldItalic, size: size)
  1811. }
  1812. return UIFont(name: LibFontName.regular, size: size)
  1813. }
  1814. @objc class func libBoldSystemFont(ofSize size: CGFloat) -> UIFont? {
  1815. if UIFont(name: LibFontName.bold, size: size) == nil {
  1816. jbs_registerFont(withFilenameString: LibFontName.bold)
  1817. }
  1818. return UIFont(name: LibFontName.bold, size: size)
  1819. }
  1820. @objc class func libItalicSystemFont(ofSize size: CGFloat) -> UIFont? {
  1821. if UIFont(name: LibFontName.italic, size: size) == nil {
  1822. jbs_registerFont(withFilenameString: LibFontName.italic)
  1823. }
  1824. return UIFont(name: LibFontName.italic, size: size)
  1825. }
  1826. @objc convenience init(myCoder aDecoder: NSCoder) {
  1827. guard
  1828. let fontDescriptor = aDecoder.decodeObject(forKey: "UIFontDescriptor") as? UIFontDescriptor,
  1829. let fontAttribute = fontDescriptor.fontAttributes[.nsctFontUIUsage] as? String else {
  1830. self.init(myCoder: aDecoder)
  1831. return
  1832. }
  1833. var fontName = ""
  1834. switch fontAttribute {
  1835. case "CTFontRegularUsage":
  1836. fontName = LibFontName.regular
  1837. case "CTFontEmphasizedUsage", "CTFontBoldUsage":
  1838. fontName = LibFontName.bold
  1839. case "CTFontObliqueUsage":
  1840. fontName = LibFontName.italic
  1841. default:
  1842. fontName = LibFontName.regular
  1843. }
  1844. self.init(name: fontName, size: fontDescriptor.pointSize)!
  1845. }
  1846. class func libOverrideInitialize() {
  1847. guard self == UIFont.self, !isOverrided, FONT_SELECT == 0 else { return }
  1848. // Avoid method swizzling run twice and revert to original initialize function
  1849. isOverrided = true
  1850. if let systemFontMethod = class_getClassMethod(self, #selector(systemFont(ofSize:))),
  1851. let mySystemFontMethod = class_getClassMethod(self, #selector(libSystemFont(ofSize:))) {
  1852. method_exchangeImplementations(systemFontMethod, mySystemFontMethod)
  1853. }
  1854. if let systemFontWeightMethod = class_getClassMethod(self, #selector(systemFont(ofSize:weight:))),
  1855. let mySystemFontWeightMethod = class_getClassMethod(self, #selector(libSystemFontWeight(ofSize:weight:))) {
  1856. method_exchangeImplementations(systemFontWeightMethod, mySystemFontWeightMethod)
  1857. }
  1858. if let boldSystemFontMethod = class_getClassMethod(self, #selector(boldSystemFont(ofSize:))),
  1859. let myBoldSystemFontMethod = class_getClassMethod(self, #selector(libBoldSystemFont(ofSize:))) {
  1860. method_exchangeImplementations(boldSystemFontMethod, myBoldSystemFontMethod)
  1861. }
  1862. if let italicSystemFontMethod = class_getClassMethod(self, #selector(italicSystemFont(ofSize:))),
  1863. let myItalicSystemFontMethod = class_getClassMethod(self, #selector(libItalicSystemFont(ofSize:))) {
  1864. method_exchangeImplementations(italicSystemFontMethod, myItalicSystemFontMethod)
  1865. }
  1866. if let initCoderMethod = class_getInstanceMethod(self, #selector(UIFontDescriptor.init(coder:))), // Trick to get over the lack of UIFont.init(coder:))
  1867. let myInitCoderMethod = class_getInstanceMethod(self, #selector(UIFont.init(myCoder:))) {
  1868. method_exchangeImplementations(initCoderMethod, myInitCoderMethod)
  1869. }
  1870. }
  1871. class func jbs_registerFont(withFilenameString filenameString: String) {
  1872. // guard let pathForResourceString = Bundle.resourceBundle(for: Nexilis.self).path(forResource: filenameString, ofType: "otf") else { //resourcesMediaBundle
  1873. // //print("UIFont+: Failed to register font - path for resource not found.")
  1874. // return
  1875. // }
  1876. guard let pathForResourceURL = Bundle.resourceBundle(for: Nexilis.self).url(forResource: filenameString, withExtension: "otf") else { //resourcesMediaBundle
  1877. //print("UIFont+: Failed to register font - path for resource not found.")
  1878. return
  1879. }
  1880. var errorRef: Unmanaged<CFError>? = nil
  1881. CTFontManagerRegisterFontsForURL(pathForResourceURL as CFURL, .process, &errorRef)
  1882. // guard let fontData = NSData(contentsOfFile: pathForResourceString) else {
  1883. // //print("UIFont+: Failed to register font - font data could not be loaded.")
  1884. // return
  1885. // }
  1886. //
  1887. // guard let dataProvider = CGDataProvider(data: fontData) else {
  1888. // //print("UIFont+: Failed to register font - data provider could not be loaded.")
  1889. // return
  1890. // }
  1891. //
  1892. // guard let font = CGFont(dataProvider) else {
  1893. // //print("UIFont+: Failed to register font - font could not be loaded.")
  1894. // return
  1895. // }
  1896. //
  1897. // var errorRef: Unmanaged<CFError>? = nil
  1898. // if (CTFontManagerRegisterGraphicsFont(font, &errorRef) == false) {
  1899. // }
  1900. }
  1901. }
  1902. public protocol LoginDelegate: NSObjectProtocol {
  1903. func onProgress(code: String, progress: Int)
  1904. func onProcess(message: String, status: String)
  1905. }
  1906. public protocol MessageDelegate: NSObjectProtocol {
  1907. func onReceive(message: TMessage)
  1908. func onReceiveComment(message: TMessage)
  1909. func onReceive(message: [AnyHashable: Any?])
  1910. func onMessage(message: TMessage)
  1911. func onUpload(name: String, progress: Double)
  1912. func onTyping(message: TMessage)
  1913. }
  1914. public protocol GroupDelegate: NSObjectProtocol {
  1915. func onGroup(code: String, f_pin: String, groupId: String)
  1916. func onTopic(code: String, f_pin: String, topicId: String)
  1917. func onMember(code: String, f_pin: String, groupId: String, member: String)
  1918. }
  1919. public protocol DownloadDelegate: NSObjectProtocol {
  1920. func onDownloadProgress(fileName: String, progress: Double)
  1921. }
  1922. public protocol CallDelegate: NSObjectProtocol {
  1923. func onIncomingCall(state: Int, message: String)
  1924. func onStatusCall(state: Int, message: String)
  1925. }
  1926. public protocol LiveStreamingDelegate: NSObjectProtocol {
  1927. func onStartLS(state: Int, message: String)
  1928. func onJoinLS(state: Int, message: String)
  1929. }
  1930. public protocol SeminarDelegate: NSObjectProtocol {
  1931. func onStartSeminar(state: Int, message: String)
  1932. func onJoinSeminar(state: Int, message: String)
  1933. }
  1934. public protocol VideoCallDelegate: NSObjectProtocol {
  1935. func onInitiateVideoCall(destination:String,state: Int, message: String)
  1936. func onAcceptVideoCall(originator:String,state: Int, message: String)
  1937. func onVideoCallReceiverTerminate(originator:String,state: Int, message: String)
  1938. }
  1939. public protocol PersonInfoDelegate: NSObjectProtocol {
  1940. func onUpdatePersonInfo(state: Int, message: String)
  1941. }
  1942. public protocol ScreenSharingDelegate: NSObjectProtocol {
  1943. func onStartScreenSharing(state:Int,message:String)
  1944. func onJoinScreenSharing(state:Int,message:String)
  1945. }
  1946. public protocol CommentDelegate: NSObjectProtocol {
  1947. func onReceiveComment(message: TMessage)
  1948. func onDeleteComment(message: TMessage)
  1949. }
  1950. public protocol UploadDelegate: NSObjectProtocol {
  1951. func onUploadProgress(fileName: String, progress: Double)
  1952. }
  1953. public protocol TimelineDelegate: NSObjectProtocol {
  1954. func onPostUpdate(status: String, message: String)
  1955. }
  1956. public protocol ConnectionDelegate: NSObjectProtocol {
  1957. func connectionStateChanged(userId: String!, deviceId: String, state: Bool)
  1958. }
  1959. public protocol ConnectDelegate: NSObjectProtocol {
  1960. func onSuccess(userId: String)
  1961. func onFailed(error: String)
  1962. }
  1963. public enum AppStoryBoard: String {
  1964. case Palio = "Palio"
  1965. public var instance: UIStoryboard {
  1966. return UIStoryboard(name: self.rawValue, bundle: Bundle.resourceBundle(for: Nexilis.self))
  1967. }
  1968. }
  1969. public var uuidOngoing = UUID()
  1970. extension Nexilis: CallDelegate {
  1971. func displayIncomingCall(uuid: UUID, handle: String, hasVideo: Bool = false, completion: ((Error?) -> Void)? = nil) {
  1972. providerDelegate?.reportIncomingCall(uuid: uuid, handle: handle, hasVideo: hasVideo, completion: completion)
  1973. }
  1974. public func onIncomingCall(state: Int, message: String) {
  1975. DispatchQueue.main.async {
  1976. let idMe = User.getMyPin()!
  1977. let myData = User.getData(pin: idMe)
  1978. let onGoingCC: String = SecureUserDefaults.shared.value(forKey: "onGoingCC") ?? ""
  1979. if !onGoingCC.isEmpty {
  1980. return
  1981. }
  1982. let deviceId = message.split(separator: ",")[0]
  1983. if myData?.offline_mode == "1" || self.stateUnfriend == deviceId {
  1984. DispatchQueue.main.asyncAfter(deadline: .now() + 0.5, execute: {
  1985. API.terminateCall(sParty: nil)
  1986. })
  1987. return
  1988. }
  1989. var isShowAlert: Double?
  1990. let canShow = UIApplication.shared.visibleViewController
  1991. if canShow != nil && !(canShow is UINavigationController) {
  1992. if !(canShow is EditorPersonal) {
  1993. isShowAlert = 0
  1994. } else {
  1995. isShowAlert = 1.5
  1996. }
  1997. } else if canShow != nil {
  1998. if canShow is UINavigationController {
  1999. let canShowNC = canShow as! UINavigationController
  2000. if !(canShowNC.visibleViewController is EditorPersonal) {
  2001. isShowAlert = 0
  2002. } else {
  2003. isShowAlert = 1.5
  2004. }
  2005. } else {
  2006. isShowAlert = 0
  2007. }
  2008. }
  2009. if (state == Nexilis.AUDIO_CALL_INCOMING && message.split(separator: ",")[1] != "joining Ac.room on channel 0") {
  2010. let data = User.getDataCanNil(pin: String(deviceId))
  2011. if data == nil {
  2012. DispatchQueue.main.asyncAfter(deadline: .now() + 0.5, execute: {
  2013. API.terminateCall(sParty: nil)
  2014. })
  2015. return
  2016. }
  2017. // let backgroundTaskIdentifier = UIApplication.shared.beginBackgroundTask(expirationHandler: nil)
  2018. // uuidOngoing = UUID()
  2019. // self.displayIncomingCall(uuid: uuidOngoing, handle: String(deviceId), hasVideo: false) { error in
  2020. // UIApplication.shared.endBackgroundTask(backgroundTaskIdentifier)
  2021. // }
  2022. Nexilis.ringtonePlayer?.play()
  2023. let controller = QmeraAudioViewController()
  2024. controller.user = User.getData(pin: String(deviceId))
  2025. controller.isOutgoing = false
  2026. controller.modalPresentationStyle = .overCurrentContext
  2027. if UIApplication.shared.visibleViewController is UIAlertController {
  2028. let vc = UIApplication.shared.visibleViewController as! UIAlertController
  2029. vc.dismiss(animated: true, completion: {
  2030. if UIApplication.shared.visibleViewController?.navigationController != nil {
  2031. UIApplication.shared.visibleViewController?.navigationController?.present(controller, animated: true, completion: nil)
  2032. } else {
  2033. UIApplication.shared.visibleViewController?.present(controller, animated: true, completion: nil)
  2034. }
  2035. })
  2036. return
  2037. }
  2038. if UIApplication.shared.visibleViewController?.navigationController != nil {
  2039. UIApplication.shared.visibleViewController?.navigationController?.present(controller, animated: true, completion: nil)
  2040. } else {
  2041. UIApplication.shared.visibleViewController?.present(controller, animated: true, completion: nil)
  2042. }
  2043. // API.receiveCCall(sParty: String(deviceId))
  2044. } else if state == Nexilis.VIDEO_CALL_INCOMING {
  2045. let dataUser = User.getDataCanNil(pin: String(deviceId))
  2046. if dataUser == nil {
  2047. DispatchQueue.main.asyncAfter(deadline: .now() + 0.5, execute: {
  2048. API.terminateCall(sParty: nil)
  2049. })
  2050. return
  2051. }
  2052. Nexilis.ringtonePlayer?.play()
  2053. let videoController = AppStoryBoard.Palio.instance.instantiateViewController(withIdentifier: "videoVCQmera") as! QmeraVideoViewController
  2054. videoController.fPin = String(deviceId)
  2055. videoController.isInisiator = false
  2056. let navigationController = CustomNavigationController(rootViewController: videoController)
  2057. navigationController.modalPresentationStyle = .fullScreen
  2058. if UIApplication.shared.visibleViewController is UIAlertController {
  2059. let vc = UIApplication.shared.visibleViewController as! UIAlertController
  2060. vc.dismiss(animated: true, completion: {
  2061. if UIApplication.shared.visibleViewController?.navigationController != nil {
  2062. UIApplication.shared.visibleViewController?.navigationController?.present(navigationController, animated: true, completion: nil)
  2063. } else {
  2064. UIApplication.shared.visibleViewController?.present(navigationController, animated: true, completion: nil)
  2065. }
  2066. })
  2067. return
  2068. }
  2069. if UIApplication.shared.visibleViewController?.navigationController != nil {
  2070. UIApplication.shared.visibleViewController?.navigationController?.present(navigationController, animated: true, completion: nil)
  2071. } else {
  2072. UIApplication.shared.visibleViewController?.present(navigationController, animated: true, completion: nil)
  2073. }
  2074. }
  2075. }
  2076. }
  2077. public func onStatusCall(state: Int, message: String) {
  2078. // let r = message.split(separator: ",")
  2079. // if state == Nexilis.AUDIO_CALL_RINGING {
  2080. // if let call = callManager.call(with: String(r[0])) {
  2081. // //print("onStatusCall:connectingCall")
  2082. // DispatchQueue.main.async {
  2083. // call.connectingCall()
  2084. // }
  2085. // }
  2086. // } else if state == Nexilis.AUDIO_CALL_OFFHOOK {
  2087. //// if let call = callManager.call(with: String(r[1])) {
  2088. // //print("onStatusCall:answerCall")
  2089. //// DispatchQueue.main.async {
  2090. //// call.answerCall()
  2091. //// }
  2092. //// }
  2093. // } else if state == Nexilis.AUDIO_CALL_END {
  2094. // DispatchQueue.main.async {
  2095. // if QmeraAudioViewController().viewIfLoaded?.window == nil {
  2096. // Nexilis.shared.callManager.end(call: Call(uuid: uuidOngoing))
  2097. // }
  2098. // }
  2099. // }
  2100. var dataCall: [AnyHashable : Any] = [:]
  2101. dataCall["state"] = state
  2102. dataCall["message"] = message
  2103. NotificationCenter.default.post(name: NSNotification.Name(rawValue: Nexilis.listenerStatusCall), object: nil, userInfo: dataCall)
  2104. }
  2105. }
  2106. var previewItem : NSURL?
  2107. var listCCIdInv: [String] = []
  2108. var imageGif: UIImageView!
  2109. var posGif = "0"
  2110. var loopGif = "0"
  2111. var timerAnimationGif = Timer()
  2112. extension Nexilis: MessageDelegate {
  2113. public func onReceiveComment(message: TMessage) {
  2114. var dataMessage: [AnyHashable : Any] = [:]
  2115. dataMessage["message"] = message
  2116. NotificationCenter.default.post(name: NSNotification.Name(rawValue: "onReceiveComment"), object: nil, userInfo: dataMessage)
  2117. }
  2118. @objc func tapLinkBroadcast(_ sender: ObjectGesture) {
  2119. var stringURl = sender.message_id.lowercased()
  2120. if stringURl.starts(with: "www.") {
  2121. stringURl = "https://" + stringURl.replacingOccurrences(of: "www.", with: "")
  2122. }
  2123. guard let url = URL(string: stringURl) else { return }
  2124. UIApplication.shared.open(url)
  2125. }
  2126. private func runAnimationGif() {
  2127. DispatchQueue.main.asyncAfter(deadline: .now() + 3, execute: { [self] in
  2128. if imageGif != nil {
  2129. timerAnimationGif.invalidate()
  2130. timerAnimationGif = Timer.scheduledTimer(timeInterval: 0.001, target: self, selector: #selector(animateGif), userInfo: nil, repeats: true)
  2131. }
  2132. })
  2133. }
  2134. @objc func animateGif() {
  2135. DispatchQueue.main.async {
  2136. if posGif == "0" { //left
  2137. if imageGif.frame.origin.x < (UIScreen.main.bounds.width - imageGif.frame.width) {
  2138. imageGif.frame.origin.x+=0.1
  2139. } else {
  2140. timerAnimationGif.invalidate()
  2141. }
  2142. } else if posGif == "1" { //right
  2143. if imageGif.frame.origin.x > 0 {
  2144. imageGif.frame.origin.x-=0.1
  2145. } else {
  2146. timerAnimationGif.invalidate()
  2147. }
  2148. } else if posGif == "2" { //top
  2149. if imageGif.frame.origin.y < (UIScreen.main.bounds.height - imageGif.frame.height) {
  2150. imageGif.frame.origin.y+=0.1
  2151. } else {
  2152. timerAnimationGif.invalidate()
  2153. }
  2154. } else { //bottom
  2155. if imageGif.frame.origin.y > 20 {
  2156. imageGif.frame.origin.y-=0.1
  2157. } else {
  2158. timerAnimationGif.invalidate()
  2159. }
  2160. }
  2161. }
  2162. }
  2163. func showBroadcastMessage(m: [String: String]) {
  2164. let fileType = m[CoreMessage_TMessageKey.CATEGORY_FLAG]!
  2165. let gifId = m[CoreMessage_TMessageKey.GIF_ID] ?? ""
  2166. let broadcastVC = UIViewController()
  2167. if let viewBroadcast = broadcastVC.view {
  2168. broadcastVC.modalPresentationStyle = .custom
  2169. viewBroadcast.backgroundColor = .black.withAlphaComponent(0.3)
  2170. if !gifId.isEmpty {
  2171. let urlGif = "\(Utils.getURLBase())filepalio/image/\(gifId)"
  2172. let scale = m[CoreMessage_TMessageKey.SCALE] ?? "0"
  2173. let link = m[CoreMessage_TMessageKey.LINK] ?? ""
  2174. posGif = m[CoreMessage_TMessageKey.START_ANIMATION] ?? "0"
  2175. loopGif = m[CoreMessage_TMessageKey.LOOP_ANIMATION] ?? "0"
  2176. imageGif = UIImageView()
  2177. viewBroadcast.addSubview(imageGif)
  2178. imageGif.isUserInteractionEnabled = true
  2179. imageGif.contentMode = .scaleAspectFit
  2180. let buttonClose = UIButton(type: .close)
  2181. buttonClose.frame.size = CGSize(width: 30, height: 30)
  2182. buttonClose.layer.cornerRadius = 15.0
  2183. buttonClose.clipsToBounds = true
  2184. buttonClose.backgroundColor = .black.withAlphaComponent(0.5)
  2185. buttonClose.actionHandle(controlEvents: .touchUpInside,
  2186. ForAction:{() -> Void in
  2187. broadcastVC.dismiss(animated: true, completion: {
  2188. imageGif = nil
  2189. Nexilis.broadcastList.remove(at: 0)
  2190. if Nexilis.broadcastList.count > 0 {
  2191. Nexilis.shared.showBroadcastMessage(m: Nexilis.broadcastList[0])
  2192. }
  2193. })
  2194. })
  2195. imageGif.addSubview(buttonClose)
  2196. buttonClose.anchor(top: imageGif.topAnchor, right: imageGif.rightAnchor, width: 30, height: 30)
  2197. var xpos: CGFloat = 0
  2198. var ypos: CGFloat = 0
  2199. var widthImage: CGFloat = 300
  2200. var heightImage: CGFloat = 300
  2201. if scale == "2" { //50%
  2202. widthImage = 150
  2203. heightImage = 150
  2204. } else if scale == "1" { //75%
  2205. widthImage = 225
  2206. heightImage = 225
  2207. }
  2208. if posGif == "0" { //left
  2209. xpos = 0
  2210. ypos = (viewBroadcast.frame.size.height / 2) - (heightImage / 2)
  2211. } else if posGif == "1" { //right
  2212. xpos = viewBroadcast.frame.size.width - widthImage
  2213. ypos = (viewBroadcast.frame.size.height / 2) - (heightImage / 2)
  2214. } else if posGif == "2" { //top
  2215. xpos = (viewBroadcast.frame.size.width / 2) - (widthImage / 2)
  2216. ypos = 20
  2217. } else { //bottom
  2218. xpos = (viewBroadcast.frame.size.width / 2) - (widthImage / 2)
  2219. ypos = viewBroadcast.frame.size.height - heightImage
  2220. }
  2221. imageGif.frame = CGRect(x: xpos, y: ypos, width: widthImage, height: heightImage)
  2222. imageGif.loadImageAsync(with: urlGif, isGif: true)
  2223. runAnimationGif()
  2224. imageGif.actionHandle(controlEvents: .touchUpInside, ForAction: {
  2225. broadcastVC.dismiss(animated: true, completion: {
  2226. imageGif = nil
  2227. Nexilis.broadcastList.remove(at: 0)
  2228. if Nexilis.broadcastList.count > 0 {
  2229. Nexilis.shared.showBroadcastMessage(m: Nexilis.broadcastList[0])
  2230. }
  2231. if !link.isEmpty {
  2232. APIS.openUrl(url: link)
  2233. }
  2234. })
  2235. })
  2236. } else {
  2237. let stringLink = m[CoreMessage_TMessageKey.LINK] ?? ""
  2238. let containerView = UIView()
  2239. viewBroadcast.addSubview(containerView)
  2240. if stringLink.isEmpty {
  2241. containerView.anchor(centerX: viewBroadcast.centerXAnchor, centerY: viewBroadcast.centerYAnchor, width: viewBroadcast.bounds.width - 40, minHeight: 100, maxHeight: viewBroadcast.bounds.height - 100)
  2242. } else {
  2243. containerView.anchor(centerX: viewBroadcast.centerXAnchor, centerY: viewBroadcast.centerYAnchor, width: viewBroadcast.bounds.width - 40, minHeight: 200, maxHeight: viewBroadcast.bounds.height - 100)
  2244. }
  2245. containerView.backgroundColor = .white.withAlphaComponent(0.9)
  2246. containerView.layer.cornerRadius = 15.0
  2247. containerView.clipsToBounds = true
  2248. let subContainerView = UIView()
  2249. subContainerView.backgroundColor = .clear
  2250. containerView.addSubview(subContainerView)
  2251. 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)
  2252. let buttonClose = UIButton(type: .close)
  2253. buttonClose.frame.size = CGSize(width: 30, height: 30)
  2254. buttonClose.layer.cornerRadius = 15.0
  2255. buttonClose.clipsToBounds = true
  2256. buttonClose.backgroundColor = .secondaryColor.withAlphaComponent(0.5)
  2257. buttonClose.actionHandle(controlEvents: .touchUpInside,
  2258. ForAction:{() -> Void in
  2259. broadcastVC.dismiss(animated: true, completion: {
  2260. Nexilis.broadcastList.remove(at: 0)
  2261. if Nexilis.broadcastList.count > 0 {
  2262. Nexilis.shared.showBroadcastMessage(m: Nexilis.broadcastList[0])
  2263. }
  2264. })
  2265. })
  2266. containerView.addSubview(buttonClose)
  2267. buttonClose.anchor(top: containerView.topAnchor, right: containerView.rightAnchor, width: 30, height: 30)
  2268. let title = UILabel()
  2269. title.font = .systemFont(ofSize: 18, weight: .bold)
  2270. title.text = m["MERNAM"]
  2271. title.textAlignment = .center
  2272. subContainerView.addSubview(title)
  2273. title.anchor(top: subContainerView.topAnchor, left: subContainerView.leftAnchor, right: subContainerView.rightAnchor)
  2274. let titleBroadcast = UILabel()
  2275. subContainerView.addSubview(titleBroadcast)
  2276. titleBroadcast.translatesAutoresizingMaskIntoConstraints = false
  2277. NSLayoutConstraint.activate([
  2278. titleBroadcast.topAnchor.constraint(equalTo: title.bottomAnchor, constant: 20.0),
  2279. titleBroadcast.leadingAnchor.constraint(equalTo: subContainerView.leadingAnchor),
  2280. titleBroadcast.trailingAnchor.constraint(equalTo: subContainerView.trailingAnchor),
  2281. ])
  2282. titleBroadcast.font = UIFont.systemFont(ofSize: 14, weight: .semibold)
  2283. titleBroadcast.numberOfLines = 0
  2284. titleBroadcast.attributedText = m[CoreMessage_TMessageKey.TITLE]!.richText()
  2285. titleBroadcast.textColor = .black
  2286. let descBroadcast = UILabel()
  2287. subContainerView.addSubview(descBroadcast)
  2288. descBroadcast.translatesAutoresizingMaskIntoConstraints = false
  2289. let constraintDesc = descBroadcast.bottomAnchor.constraint(equalTo: subContainerView.bottomAnchor)
  2290. if !stringLink.isEmpty{
  2291. constraintDesc.constant = constraintDesc.constant - 30
  2292. }
  2293. if fileType != BroadcastViewController.FILE_TYPE_CHAT {
  2294. constraintDesc.constant = constraintDesc.constant - 260
  2295. }
  2296. NSLayoutConstraint.activate([
  2297. descBroadcast.topAnchor.constraint(equalTo: titleBroadcast.bottomAnchor, constant: 10),
  2298. descBroadcast.leadingAnchor.constraint(equalTo: subContainerView.leadingAnchor),
  2299. descBroadcast.trailingAnchor.constraint(equalTo: subContainerView.trailingAnchor),
  2300. constraintDesc,
  2301. ])
  2302. descBroadcast.font = UIFont.systemFont(ofSize: 12)
  2303. descBroadcast.numberOfLines = 0
  2304. descBroadcast.attributedText = m[CoreMessage_TMessageKey.MESSAGE_TEXT_ENG]!.richText()
  2305. descBroadcast.textColor = .black
  2306. let linkBroadcast = UILabel()
  2307. if !stringLink.isEmpty {
  2308. subContainerView.addSubview(linkBroadcast)
  2309. linkBroadcast.translatesAutoresizingMaskIntoConstraints = false
  2310. NSLayoutConstraint.activate([
  2311. linkBroadcast.topAnchor.constraint(equalTo: descBroadcast.bottomAnchor, constant: 10),
  2312. linkBroadcast.leadingAnchor.constraint(equalTo: subContainerView.leadingAnchor),
  2313. linkBroadcast.trailingAnchor.constraint(equalTo: subContainerView.trailingAnchor),
  2314. ])
  2315. linkBroadcast.font = UIFont.systemFont(ofSize: 12)
  2316. linkBroadcast.isUserInteractionEnabled = true
  2317. linkBroadcast.numberOfLines = 2
  2318. let attributedString = NSMutableAttributedString(string: stringLink, attributes:[NSAttributedString.Key.link: URL(string: stringLink)!])
  2319. linkBroadcast.attributedText = attributedString
  2320. let tap = ObjectGesture(target: self, action: #selector(tapLinkBroadcast))
  2321. tap.message_id = stringLink
  2322. linkBroadcast.addGestureRecognizer(tap)
  2323. }
  2324. let thumb = m[CoreMessage_TMessageKey.THUMB_ID] ?? ""
  2325. let image = m[CoreMessage_TMessageKey.IMAGE_ID] ?? ""
  2326. let video = m[CoreMessage_TMessageKey.VIDEO_ID] ?? ""
  2327. let file = m[CoreMessage_TMessageKey.FILE_ID] ?? ""
  2328. if fileType != BroadcastViewController.FILE_TYPE_CHAT {
  2329. let imageBroadcast = UIImageView()
  2330. subContainerView.addSubview(imageBroadcast)
  2331. imageBroadcast.translatesAutoresizingMaskIntoConstraints = false
  2332. var constImage = imageBroadcast.topAnchor.constraint(equalTo: descBroadcast.bottomAnchor, constant: 10)
  2333. if !stringLink.isEmpty {
  2334. constImage = imageBroadcast.topAnchor.constraint(equalTo: linkBroadcast.bottomAnchor, constant: 10)
  2335. }
  2336. NSLayoutConstraint.activate([
  2337. constImage,
  2338. imageBroadcast.leadingAnchor.constraint(equalTo: subContainerView.leadingAnchor),
  2339. imageBroadcast.trailingAnchor.constraint(equalTo: subContainerView.trailingAnchor),
  2340. imageBroadcast.heightAnchor.constraint(equalToConstant: 250)
  2341. ])
  2342. imageBroadcast.layer.cornerRadius = 10.0
  2343. imageBroadcast.clipsToBounds = true
  2344. if fileType != BroadcastViewController.FILE_TYPE_DOCUMENT {
  2345. imageBroadcast.contentMode = .scaleAspectFill
  2346. imageBroadcast.setImage(name: thumb)
  2347. if fileType == BroadcastViewController.FILE_TYPE_VIDEO {
  2348. let imagePlay = UIImageView(image: UIImage(systemName: "play.circle.fill"))
  2349. imageBroadcast.addSubview(imagePlay)
  2350. imagePlay.clipsToBounds = true
  2351. imagePlay.translatesAutoresizingMaskIntoConstraints = false
  2352. imagePlay.centerYAnchor.constraint(equalTo: imageBroadcast.centerYAnchor).isActive = true
  2353. imagePlay.centerXAnchor.constraint(equalTo: imageBroadcast.centerXAnchor).isActive = true
  2354. imagePlay.widthAnchor.constraint(equalToConstant: 60).isActive = true
  2355. imagePlay.heightAnchor.constraint(equalToConstant: 60).isActive = true
  2356. imagePlay.tintColor = .gray.withAlphaComponent(0.5)
  2357. }
  2358. } else {
  2359. imageBroadcast.image = UIImage(systemName: "doc.fill")
  2360. imageBroadcast.tintColor = .mainColor
  2361. imageBroadcast.contentMode = .scaleAspectFit
  2362. }
  2363. imageBroadcast.actionHandle(controlEvents: .touchUpInside,
  2364. ForAction:{() -> Void in
  2365. let nsDocumentDirectory = FileManager.SearchPathDirectory.documentDirectory
  2366. let nsUserDomainMask = FileManager.SearchPathDomainMask.userDomainMask
  2367. let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true)
  2368. if fileType == BroadcastViewController.FILE_TYPE_IMAGE {
  2369. if let dirPath = paths.first {
  2370. let imageURL = URL(fileURLWithPath: dirPath).appendingPathComponent(image)
  2371. if FileManager.default.fileExists(atPath: imageURL.path) {
  2372. let image = UIImage(contentsOfFile: imageURL.path)
  2373. let previewImageVC = PreviewAttachmentImageVideo(nibName: "PreviewAttachmentImageVideo", bundle: Bundle.resourceBundle(for: Nexilis.self))
  2374. previewImageVC.image = image
  2375. previewImageVC.isHiddenTextField = true
  2376. previewImageVC.modalPresentationStyle = .overFullScreen
  2377. previewImageVC.modalTransitionStyle = .crossDissolve
  2378. if UIApplication.shared.visibleViewController?.navigationController != nil {
  2379. UIApplication.shared.visibleViewController?.navigationController?.present(previewImageVC, animated: true, completion: nil)
  2380. } else {
  2381. UIApplication.shared.visibleViewController?.present(previewImageVC, animated: true, completion: nil)
  2382. }
  2383. } else if FileEncryption.shared.isSecureExists(filename: image) {
  2384. do {
  2385. let data = try FileEncryption.shared.readSecure(filename: image)
  2386. let image = UIImage(data: data!)
  2387. let previewImageVC = PreviewAttachmentImageVideo(nibName: "PreviewAttachmentImageVideo", bundle: Bundle.resourceBundle(for: Nexilis.self))
  2388. previewImageVC.image = image
  2389. previewImageVC.isHiddenTextField = true
  2390. previewImageVC.modalPresentationStyle = .overFullScreen
  2391. previewImageVC.modalTransitionStyle = .crossDissolve
  2392. if UIApplication.shared.visibleViewController?.navigationController != nil {
  2393. UIApplication.shared.visibleViewController?.navigationController?.present(previewImageVC, animated: true, completion: nil)
  2394. } else {
  2395. UIApplication.shared.visibleViewController?.present(previewImageVC, animated: true, completion: nil)
  2396. }
  2397. } catch {
  2398. }
  2399. } else {
  2400. Download().startHTTP(forKey: image) { (name, progress) in
  2401. guard progress == 100 else {
  2402. return
  2403. }
  2404. do {
  2405. try FileEncryption.shared.writeSecure(filename: image)
  2406. } catch {
  2407. }
  2408. DispatchQueue.main.async {
  2409. var image : UIImage?
  2410. if FileManager.default.fileExists(atPath: imageURL.path) {
  2411. image = UIImage(contentsOfFile: imageURL.path)
  2412. }
  2413. else if FileEncryption.shared.isSecureExists(filename: imageURL.lastPathComponent) {
  2414. do {
  2415. if let imageData = try FileEncryption.shared.readSecure(filename: imageURL.lastPathComponent) {
  2416. image = UIImage(data: imageData)
  2417. }
  2418. } catch {
  2419. }
  2420. }
  2421. let previewImageVC = PreviewAttachmentImageVideo(nibName: "PreviewAttachmentImageVideo", bundle: Bundle.resourceBundle(for: Nexilis.self))
  2422. previewImageVC.image = image
  2423. previewImageVC.isHiddenTextField = true
  2424. previewImageVC.modalPresentationStyle = .overFullScreen
  2425. previewImageVC.modalTransitionStyle = .crossDissolve
  2426. if UIApplication.shared.visibleViewController?.navigationController != nil {
  2427. UIApplication.shared.visibleViewController?.navigationController?.present(previewImageVC, animated: true, completion: nil)
  2428. } else {
  2429. UIApplication.shared.visibleViewController?.present(previewImageVC, animated: true, completion: nil)
  2430. }
  2431. }
  2432. }
  2433. }
  2434. }
  2435. } else if fileType == BroadcastViewController.FILE_TYPE_VIDEO {
  2436. //https://qmera.io/filepalio/image/
  2437. let player = AVPlayer(url: URL(string: "https://nexilis.io/get_file?account=\(Nexilis.sAPIKey)&image=\(video)")!)
  2438. let playerVC = AVPlayerViewController()
  2439. playerVC.player = player
  2440. playerVC.modalPresentationStyle = .custom
  2441. if UIApplication.shared.visibleViewController?.navigationController != nil {
  2442. UIApplication.shared.visibleViewController?.navigationController?.present(playerVC, animated: true, completion: nil)
  2443. } else {
  2444. UIApplication.shared.visibleViewController?.present(playerVC, animated: true, completion: nil)
  2445. }
  2446. } else if fileType == BroadcastViewController.FILE_TYPE_DOCUMENT {
  2447. if let dirPath = paths.first {
  2448. let fileURL = URL(fileURLWithPath: dirPath).appendingPathComponent(file)
  2449. if FileManager.default.fileExists(atPath: fileURL.path) {
  2450. previewItem = fileURL as NSURL
  2451. let previewController = QLPreviewController()
  2452. let rightBarButton = UIBarButtonItem()
  2453. previewController.navigationItem.rightBarButtonItem = rightBarButton
  2454. previewController.dataSource = self
  2455. previewController.modalPresentationStyle = .overFullScreen
  2456. if UIApplication.shared.visibleViewController?.navigationController != nil {
  2457. UIApplication.shared.visibleViewController?.navigationController?.present(previewController, animated: true, completion: nil)
  2458. } else {
  2459. UIApplication.shared.visibleViewController?.present(previewController, animated: true, completion: nil)
  2460. }
  2461. } else if FileEncryption.shared.isSecureExists(filename: file) {
  2462. do {
  2463. if let docData = try FileEncryption.shared.readSecure(filename: file) {
  2464. let cachesDirectory = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first!
  2465. let tempPath = cachesDirectory.appendingPathComponent(file)
  2466. try docData.write(to: tempPath)
  2467. previewItem = tempPath as NSURL
  2468. let previewController = QLPreviewController()
  2469. let rightBarButton = UIBarButtonItem()
  2470. previewController.navigationItem.rightBarButtonItem = rightBarButton
  2471. previewController.dataSource = self
  2472. previewController.modalPresentationStyle = .overFullScreen
  2473. if UIApplication.shared.visibleViewController?.navigationController != nil {
  2474. UIApplication.shared.visibleViewController?.navigationController?.present(previewController, animated: true, completion: nil)
  2475. } else {
  2476. UIApplication.shared.visibleViewController?.present(previewController, animated: true, completion: nil)
  2477. }
  2478. }
  2479. } catch {
  2480. }
  2481. } else {
  2482. Download().startHTTP(forKey: file, isImage: false) { (name, progress) in
  2483. DispatchQueue.main.async {
  2484. guard progress == 100 else {
  2485. return
  2486. }
  2487. do {
  2488. let secureFilename = try FileEncryption.shared.writeSecure(filename: name)
  2489. if let docData = try FileEncryption.shared.readSecure(filename: secureFilename?[0] as! String) {
  2490. let cachesDirectory = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first!
  2491. let tempPath = cachesDirectory.appendingPathComponent(file)
  2492. try docData.write(to: tempPath)
  2493. previewItem = tempPath as NSURL
  2494. let previewController = QLPreviewController()
  2495. let rightBarButton = UIBarButtonItem()
  2496. previewController.navigationItem.rightBarButtonItem = rightBarButton
  2497. previewController.dataSource = self
  2498. previewController.modalPresentationStyle = .overFullScreen
  2499. if UIApplication.shared.visibleViewController?.navigationController != nil {
  2500. UIApplication.shared.visibleViewController?.navigationController?.present(previewController, animated: true, completion: nil)
  2501. } else {
  2502. UIApplication.shared.visibleViewController?.present(previewController, animated: true, completion: nil)
  2503. }
  2504. }
  2505. }
  2506. catch {
  2507. }
  2508. }
  2509. }
  2510. }
  2511. }
  2512. }
  2513. })
  2514. }
  2515. }
  2516. broadcastVC.modalTransitionStyle = .crossDissolve
  2517. if UIApplication.shared.visibleViewController?.navigationController != nil {
  2518. UIApplication.shared.visibleViewController?.navigationController?.present(broadcastVC, animated: true, completion: nil)
  2519. } else {
  2520. UIApplication.shared.visibleViewController?.present(broadcastVC, animated: true, completion: nil)
  2521. }
  2522. }
  2523. }
  2524. public func onReceive(message: TMessage) {
  2525. var dataMessage: [AnyHashable : Any] = [:]
  2526. dataMessage["message"] = message
  2527. NotificationCenter.default.post(name: NSNotification.Name(rawValue: Nexilis.listenerReceiveChat), object: nil, userInfo: dataMessage)
  2528. if message.getCode() == CoreMessage_TMessageCode.PUSH_CALL_CENTER {
  2529. if User.getDataCanNil(pin: message.getBody(key: CoreMessage_TMessageKey.L_PIN)) == nil {
  2530. Nexilis.addFriendSilent(fpin: message.getBody(key: CoreMessage_TMessageKey.L_PIN))
  2531. sleep(1)
  2532. }
  2533. DispatchQueue.main.async {
  2534. if Nexilis.onGoingPushCC.isEmpty {
  2535. var data: [String: String] = [:]
  2536. data["channel"] = message.getBody(key: CoreMessage_TMessageKey.CHANNEL)
  2537. data["l_pin"] = message.getBody(key: CoreMessage_TMessageKey.L_PIN)
  2538. data["f_display_name"] = message.getBody(key: CoreMessage_TMessageKey.F_DISPLAY_NAME)
  2539. Nexilis.onGoingPushCC = data
  2540. } else if Nexilis.onGoingPushCC["f_display_name"] == message.getBody(key: CoreMessage_TMessageKey.F_DISPLAY_NAME) {
  2541. return
  2542. }
  2543. let alert = LibAlertController(title: "", message: "\n\n\n\n\n\n\n\n\n\n".localized(), preferredStyle: .alert)
  2544. let newWidth = UIScreen.main.bounds.width * 0.90 - 270
  2545. // update width constraint value for main view
  2546. if let viewWidthConstraint = alert.view.constraints.filter({ return $0.firstAttribute == .width }).first{
  2547. viewWidthConstraint.constant = newWidth
  2548. }
  2549. // update width constraint value for container view
  2550. if let containerViewWidthConstraint = alert.view.subviews.first?.constraints.filter({ return $0.firstAttribute == .width }).first {
  2551. containerViewWidthConstraint.constant = newWidth
  2552. }
  2553. let titleFont = [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 18), NSAttributedString.Key.foregroundColor: UIColor.black]
  2554. let titleAttrString = NSMutableAttributedString(string: "Call Center".localized(), attributes: titleFont)
  2555. alert.setValue(titleAttrString, forKey: "attributedTitle")
  2556. alert.view.subviews.first?.subviews.first?.subviews.first?.backgroundColor = .lightGray
  2557. alert.view.tintColor = .black
  2558. let rejectAction = UIAlertAction(title: "Pass to other representative".localized(), style: .destructive, handler: {(_) in
  2559. DispatchQueue.global().async {
  2560. _ = Nexilis.write(message: CoreMessage_TMessageBank.timeOutRequestCallCenter(channel: message.getBody(key: CoreMessage_TMessageKey.CHANNEL), l_pin: message.getBody(key: CoreMessage_TMessageKey.L_PIN)))
  2561. }
  2562. Nexilis.onGoingPushCC.removeAll()
  2563. alert.dismiss(animated: true, completion: nil)
  2564. })
  2565. let acceptAction = UIAlertAction(title: "I'll handle the customer".localized(), style: .default, handler: {(_) in
  2566. let goAudioCall = Nexilis.checkMicPermission()
  2567. if !goAudioCall && message.getBody(key: CoreMessage_TMessageKey.CHANNEL) == "1" {
  2568. let alert = LibAlertController(title: "Attention!".localized(), message: "Please allow microphone permission in your settings".localized(), preferredStyle: .alert)
  2569. alert.addAction(UIAlertAction(title: "OK".localized(), style: UIAlertAction.Style.default, handler: { _ in
  2570. if let url = URL(string: UIApplication.openSettingsURLString), UIApplication.shared.canOpenURL(url) {
  2571. UIApplication.shared.open(url, options: [:], completionHandler: nil)
  2572. }
  2573. }))
  2574. if UIApplication.shared.visibleViewController?.navigationController != nil {
  2575. UIApplication.shared.visibleViewController?.navigationController?.present(alert, animated: true, completion: nil)
  2576. } else {
  2577. UIApplication.shared.visibleViewController?.present(alert, animated: true, completion: nil)
  2578. }
  2579. DispatchQueue.global().async {
  2580. DispatchQueue.global().async {
  2581. _ = Nexilis.write(message: CoreMessage_TMessageBank.timeOutRequestCallCenter(channel: message.getBody(key: CoreMessage_TMessageKey.CHANNEL), l_pin: message.getBody(key: CoreMessage_TMessageKey.L_PIN)))
  2582. }
  2583. }
  2584. Nexilis.onGoingPushCC.removeAll()
  2585. return
  2586. }
  2587. if message.getBody(key: CoreMessage_TMessageKey.CHANNEL) == "2" {
  2588. var permissionCheck = -1
  2589. if AVCaptureDevice.authorizationStatus(for: .video) == .authorized {
  2590. permissionCheck = 1
  2591. } else if AVCaptureDevice.authorizationStatus(for: .video) == .denied {
  2592. permissionCheck = 0
  2593. } else {
  2594. Nexilis.dispatch = DispatchGroup()
  2595. Nexilis.dispatch?.enter()
  2596. AVCaptureDevice.requestAccess(for: .video, completionHandler: { (granted: Bool) -> Void in
  2597. if granted == true {
  2598. permissionCheck = 1
  2599. } else {
  2600. permissionCheck = 0
  2601. }
  2602. if let dispatch = Nexilis.dispatch {
  2603. dispatch.leave()
  2604. }
  2605. })
  2606. Nexilis.dispatch?.wait()
  2607. Nexilis.dispatch = nil
  2608. }
  2609. if permissionCheck == 0 {
  2610. let alert = LibAlertController(title: "Attention!".localized(), message: "Please allow camera permission in your settings".localized(), preferredStyle: .alert)
  2611. alert.addAction(UIAlertAction(title: "OK".localized(), style: UIAlertAction.Style.default, handler: { _ in
  2612. if let url = URL(string: UIApplication.openSettingsURLString), UIApplication.shared.canOpenURL(url) {
  2613. UIApplication.shared.open(url, options: [:], completionHandler: nil)
  2614. }
  2615. }))
  2616. if UIApplication.shared.visibleViewController?.navigationController != nil {
  2617. UIApplication.shared.visibleViewController?.navigationController?.present(alert, animated: true, completion: nil)
  2618. } else {
  2619. UIApplication.shared.visibleViewController?.present(alert, animated: true, completion: nil)
  2620. }
  2621. DispatchQueue.global().async {
  2622. DispatchQueue.global().async {
  2623. _ = Nexilis.write(message: CoreMessage_TMessageBank.timeOutRequestCallCenter(channel: message.getBody(key: CoreMessage_TMessageKey.CHANNEL), l_pin: message.getBody(key: CoreMessage_TMessageKey.L_PIN)))
  2624. }
  2625. }
  2626. Nexilis.onGoingPushCC.removeAll()
  2627. return
  2628. }
  2629. }
  2630. if UIApplication.shared.visibleViewController is UINavigationController {
  2631. let nc = UIApplication.shared.visibleViewController as! UINavigationController
  2632. if nc.visibleViewController is QmeraStreamingViewController {
  2633. let vc = nc.visibleViewController as! QmeraStreamingViewController
  2634. var alert = LibAlertController(title: "", message: "Are you sure you want to end Live Streaming, and open notification?".localized(), preferredStyle: .alert)
  2635. if !vc.isLive {
  2636. alert = LibAlertController(title: "", message: "Are you sure you want to leave Live Streaming, and open notification?".localized(), preferredStyle: .alert)
  2637. }
  2638. alert.addAction(UIAlertAction(title: "No".localized(), style: UIAlertAction.Style.default, handler: { _ in
  2639. DispatchQueue.global().async {
  2640. _ = Nexilis.write(message: CoreMessage_TMessageBank.timeOutRequestCallCenter(channel: message.getBody(key: CoreMessage_TMessageKey.CHANNEL), l_pin: message.getBody(key: CoreMessage_TMessageKey.L_PIN)))
  2641. }
  2642. Nexilis.onGoingPushCC.removeAll()
  2643. alert.dismiss(animated: true, completion: nil)
  2644. }))
  2645. alert.addAction(UIAlertAction(title: "Yes".localized(), style: UIAlertAction.Style.default, handler: { _ in
  2646. DispatchQueue.global().async {
  2647. API.terminateBC(sBroadcasterID: vc.isLive ? nil : vc.data)
  2648. vc.sendLeft()
  2649. }
  2650. vc.dismiss(animated: true, completion: {
  2651. acceptCC()
  2652. })
  2653. }))
  2654. nc.present(alert, animated: true, completion: nil)
  2655. // NotificationCenter.default.post(name: NSNotification.Name(rawValue: "isRunningStreaming"), object: nil, userInfo: dataMessage)
  2656. } else if nc.visibleViewController is SeminarViewController {
  2657. let vc = nc.visibleViewController as! SeminarViewController
  2658. var alert = LibAlertController(title: "", message: "Are you sure you want to end Seminar, and open notification?".localized(), preferredStyle: .alert)
  2659. if !vc.isLive {
  2660. alert = LibAlertController(title: "", message: "Are you sure you want to leave Seminar, and open notification?".localized(), preferredStyle: .alert)
  2661. }
  2662. alert.addAction(UIAlertAction(title: "No".localized(), style: UIAlertAction.Style.default, handler: { _ in
  2663. DispatchQueue.global().async {
  2664. _ = Nexilis.write(message: CoreMessage_TMessageBank.timeOutRequestCallCenter(channel: message.getBody(key: CoreMessage_TMessageKey.CHANNEL), l_pin: message.getBody(key: CoreMessage_TMessageKey.L_PIN)))
  2665. }
  2666. Nexilis.onGoingPushCC.removeAll()
  2667. alert.dismiss(animated: true, completion: nil)
  2668. }))
  2669. alert.addAction(UIAlertAction(title: "Yes".localized(), style: UIAlertAction.Style.default, handler: { _ in
  2670. DispatchQueue.global().async {
  2671. API.terminateBC(sBroadcasterID: vc.isLive ? nil : vc.data)
  2672. vc.sendLeft()
  2673. }
  2674. vc.dismiss(animated: true, completion: {
  2675. acceptCC()
  2676. })
  2677. }))
  2678. nc.present(alert, animated: true, completion: nil)
  2679. // NotificationCenter.default.post(name: NSNotification.Name(rawValue: "isRunningStreaming"), object: nil, userInfo: dataMessage)
  2680. } else {
  2681. acceptCC()
  2682. }
  2683. } else {
  2684. acceptCC()
  2685. }
  2686. func acceptCC() {
  2687. 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))) {
  2688. if (response.getBody(key: CoreMessage_TMessageKey.ERRCOD, default_value: "99") == "00") {
  2689. Nexilis.onGoingPushCC.removeAll()
  2690. let complaintId = response.getBody(key: CoreMessage_TMessageKey.DATA, default_value: "")
  2691. if !complaintId.isEmpty {
  2692. alert.dismiss(animated: true, completion: nil)
  2693. let idMe = User.getMyPin()!
  2694. SecureUserDefaults.shared.set("\(message.getBody(key: CoreMessage_TMessageKey.L_PIN)),\(idMe),\(complaintId)", forKey: "onGoingCC")
  2695. SecureUserDefaults.shared.set("\(message.getBody(key: CoreMessage_TMessageKey.L_PIN))", forKey: "membersCC")
  2696. if message.getBody(key: CoreMessage_TMessageKey.CHANNEL) == "0" {
  2697. let editorPersonalVC = AppStoryBoard.Palio.instance.instantiateViewController(identifier: "editorPersonalVC") as! EditorPersonal
  2698. editorPersonalVC.isContactCenter = true
  2699. editorPersonalVC.isRequestContactCenter = false
  2700. editorPersonalVC.unique_l_pin = message.getBody(key: CoreMessage_TMessageKey.L_PIN)
  2701. editorPersonalVC.complaintId = complaintId
  2702. editorPersonalVC.channelContactCenter = message.getBody(key: CoreMessage_TMessageKey.CHANNEL)
  2703. editorPersonalVC.fPinContacCenter = message.getBody(key: CoreMessage_TMessageKey.L_PIN)
  2704. let navigationController = CustomNavigationController(rootViewController: editorPersonalVC)
  2705. navigationController.modalPresentationStyle = .fullScreen
  2706. navigationController.navigationBar.tintColor = .white
  2707. navigationController.navigationBar.barTintColor = UIApplication.shared.visibleViewController?.traitCollection.userInterfaceStyle == .dark ? .blackDarkMode : .mainColor
  2708. navigationController.navigationBar.isTranslucent = false
  2709. navigationController.navigationBar.overrideUserInterfaceStyle = .dark
  2710. navigationController.navigationBar.barStyle = .black
  2711. let cancelButtonAttributes: [NSAttributedString.Key: Any] = [NSAttributedString.Key.foregroundColor: UIColor.white, NSAttributedString.Key.font : UIFont.systemFont(ofSize: 16)]
  2712. UIBarButtonItem.appearance().setTitleTextAttributes(cancelButtonAttributes, for: .normal)
  2713. let textAttributes = [NSAttributedString.Key.foregroundColor:UIColor.white]
  2714. navigationController.navigationBar.titleTextAttributes = textAttributes
  2715. if UIApplication.shared.visibleViewController?.navigationController != nil {
  2716. UIApplication.shared.visibleViewController?.navigationController?.present(navigationController, animated: true, completion: nil)
  2717. } else {
  2718. UIApplication.shared.visibleViewController?.present(navigationController, animated: true, completion: nil)
  2719. }
  2720. } else {
  2721. SecureUserDefaults.shared.set("\(Date().currentTimeMillis())", forKey: "startTimeCC")
  2722. DispatchQueue.main.asyncAfter(deadline: .now() + 1, execute: {
  2723. if message.getBody(key: CoreMessage_TMessageKey.CHANNEL) == "1" {
  2724. let pin = message.getBody(key: CoreMessage_TMessageKey.L_PIN)
  2725. let controller = QmeraAudioViewController()
  2726. controller.user = User.getData(pin: pin)
  2727. controller.isOutgoing = true
  2728. controller.ticketId = complaintId
  2729. controller.modalPresentationStyle = .overCurrentContext
  2730. let navigationController = CustomNavigationController(rootViewController: controller)
  2731. navigationController.modalPresentationStyle = .fullScreen
  2732. if UIApplication.shared.visibleViewController?.navigationController != nil {
  2733. UIApplication.shared.visibleViewController?.navigationController?.present(navigationController, animated: true, completion: nil)
  2734. } else {
  2735. UIApplication.shared.visibleViewController?.present(navigationController, animated: true, completion: nil)
  2736. }
  2737. } else if message.getBody(key: CoreMessage_TMessageKey.CHANNEL) == "2" {
  2738. let videoVC = AppStoryBoard.Palio.instance.instantiateViewController(withIdentifier: "videoVCQmera") as! QmeraVideoViewController
  2739. videoVC.fPin = message.getBody(key: CoreMessage_TMessageKey.L_PIN)
  2740. videoVC.users.append(User.getData(pin: message.getBody(key: CoreMessage_TMessageKey.L_PIN))!)
  2741. videoVC.ticketId = complaintId
  2742. let navigationController = CustomNavigationController(rootViewController: videoVC)
  2743. navigationController.modalPresentationStyle = .fullScreen
  2744. if UIApplication.shared.visibleViewController?.navigationController != nil {
  2745. UIApplication.shared.visibleViewController?.navigationController?.present(navigationController, animated: true, completion: nil)
  2746. } else {
  2747. UIApplication.shared.visibleViewController?.present(navigationController, animated: true, completion: nil)
  2748. }
  2749. }
  2750. })
  2751. }
  2752. }
  2753. }
  2754. }
  2755. }
  2756. })
  2757. alert.addAction(acceptAction)
  2758. alert.addAction(rejectAction)
  2759. let containerView = UIView(frame: CGRect(x: 20, y: 60, width: alert.view.bounds.size.width * 0.9 - 40, height: 150))
  2760. alert.view.addSubview(containerView)
  2761. containerView.layer.cornerRadius = 10.0
  2762. containerView.clipsToBounds = true
  2763. containerView.backgroundColor = .secondaryColor.withAlphaComponent(0.5)
  2764. let imageProfile = UIImageView()
  2765. containerView.addSubview(imageProfile)
  2766. imageProfile.translatesAutoresizingMaskIntoConstraints = false
  2767. NSLayoutConstraint.activate([
  2768. imageProfile.topAnchor.constraint(equalTo: containerView.topAnchor, constant: 10),
  2769. imageProfile.bottomAnchor.constraint(equalTo: containerView.bottomAnchor, constant: -10),
  2770. imageProfile.leadingAnchor.constraint(equalTo: containerView.leadingAnchor, constant: 10),
  2771. imageProfile.widthAnchor.constraint(equalToConstant: 100)
  2772. ])
  2773. imageProfile.layer.cornerRadius = 10.0
  2774. imageProfile.clipsToBounds = true
  2775. imageProfile.backgroundColor = .lightGray.withAlphaComponent(0.3)
  2776. imageProfile.tintColor = .secondaryColor
  2777. imageProfile.image = UIImage(systemName: "person")
  2778. if message.getBody(key: CoreMessage_TMessageKey.THUMB_ID) != "" {
  2779. imageProfile.setImage(name: message.getBody(key: CoreMessage_TMessageKey.THUMB_ID))
  2780. imageProfile.contentMode = .scaleAspectFill
  2781. }
  2782. let labelName = UILabel()
  2783. containerView.addSubview(labelName)
  2784. labelName.translatesAutoresizingMaskIntoConstraints = false
  2785. NSLayoutConstraint.activate([
  2786. labelName.topAnchor.constraint(equalTo: containerView.topAnchor, constant: 15),
  2787. labelName.leadingAnchor.constraint(equalTo: imageProfile.trailingAnchor, constant: 5)
  2788. ])
  2789. labelName.font = UIFont.systemFont(ofSize: 12)
  2790. labelName.text = "Name".localized()
  2791. labelName.textColor = .mainColor
  2792. let valueName = UILabel()
  2793. containerView.addSubview(valueName)
  2794. valueName.translatesAutoresizingMaskIntoConstraints = false
  2795. NSLayoutConstraint.activate([
  2796. valueName.topAnchor.constraint(equalTo: labelName.bottomAnchor),
  2797. valueName.leadingAnchor.constraint(equalTo: imageProfile.trailingAnchor, constant: 5)
  2798. ])
  2799. valueName.font = UIFont.systemFont(ofSize: 12)
  2800. valueName.text = message.getBody(key: CoreMessage_TMessageKey.F_DISPLAY_NAME)
  2801. valueName.textColor = .mainColor
  2802. let labelType = UILabel()
  2803. containerView.addSubview(labelType)
  2804. labelType.translatesAutoresizingMaskIntoConstraints = false
  2805. NSLayoutConstraint.activate([
  2806. labelType.topAnchor.constraint(equalTo: valueName.bottomAnchor, constant: 5),
  2807. labelType.leadingAnchor.constraint(equalTo: imageProfile.trailingAnchor, constant: 5)
  2808. ])
  2809. labelType.font = UIFont.systemFont(ofSize: 12)
  2810. labelType.text = "Request Type".localized()
  2811. labelType.textColor = .mainColor
  2812. let valueType = UILabel()
  2813. containerView.addSubview(valueType)
  2814. valueType.translatesAutoresizingMaskIntoConstraints = false
  2815. NSLayoutConstraint.activate([
  2816. valueType.topAnchor.constraint(equalTo: labelType.bottomAnchor),
  2817. valueType.leadingAnchor.constraint(equalTo: imageProfile.trailingAnchor, constant: 5)
  2818. ])
  2819. valueType.font = UIFont.systemFont(ofSize: 12)
  2820. if message.getBody(key: CoreMessage_TMessageKey.CHANNEL) == "0" {
  2821. valueType.text = "Chat".localized()
  2822. } else if message.getBody(key: CoreMessage_TMessageKey.CHANNEL) == "1" {
  2823. valueType.text = "Audio Call".localized()
  2824. } else if message.getBody(key: CoreMessage_TMessageKey.CHANNEL) == "2" {
  2825. valueType.text = "Video Call".localized()
  2826. } else {
  2827. valueType.text = "Email".localized()
  2828. }
  2829. valueType.textColor = .mainColor
  2830. let labelIdentity = UILabel()
  2831. containerView.addSubview(labelIdentity)
  2832. labelIdentity.translatesAutoresizingMaskIntoConstraints = false
  2833. NSLayoutConstraint.activate([
  2834. labelIdentity.topAnchor.constraint(equalTo: valueType.bottomAnchor, constant: 5),
  2835. labelIdentity.leadingAnchor.constraint(equalTo: imageProfile.trailingAnchor, constant: 5)
  2836. ])
  2837. labelIdentity.font = UIFont.systemFont(ofSize: 12)
  2838. labelIdentity.text = "Complaint ID".localized()
  2839. labelIdentity.textColor = .mainColor
  2840. let valueIdentity = UILabel()
  2841. containerView.addSubview(valueIdentity)
  2842. valueIdentity.translatesAutoresizingMaskIntoConstraints = false
  2843. NSLayoutConstraint.activate([
  2844. valueIdentity.topAnchor.constraint(equalTo: labelIdentity.bottomAnchor),
  2845. valueIdentity.leadingAnchor.constraint(equalTo: imageProfile.trailingAnchor, constant: 5),
  2846. valueIdentity.trailingAnchor.constraint(equalTo: containerView.trailingAnchor)
  2847. ])
  2848. valueIdentity.font = UIFont.systemFont(ofSize: 12)
  2849. valueIdentity.text = message.getBody(key: CoreMessage_TMessageKey.DATA)
  2850. valueIdentity.numberOfLines = 0
  2851. valueIdentity.textColor = .mainColor
  2852. var isShowAlert: Int?
  2853. let canShow = UIApplication.shared.visibleViewController
  2854. if canShow != nil && !(canShow is UINavigationController) {
  2855. if !(canShow is EditorPersonal) && !(canShow is QmeraAudioViewController) && !(canShow is QmeraVideoViewController) {
  2856. isShowAlert = 0
  2857. } else {
  2858. isShowAlert = 3
  2859. }
  2860. } else if canShow != nil {
  2861. if canShow is UINavigationController {
  2862. let canShowNC = canShow as! UINavigationController
  2863. if !(canShowNC.visibleViewController is EditorPersonal) && !(canShowNC.visibleViewController is QmeraAudioViewController) && !(canShowNC.visibleViewController is QmeraVideoViewController) {
  2864. isShowAlert = 0
  2865. } else {
  2866. isShowAlert = 3
  2867. }
  2868. } else {
  2869. isShowAlert = 0
  2870. }
  2871. }
  2872. DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(isShowAlert!), execute: {
  2873. if UIApplication.shared.visibleViewController?.navigationController != nil {
  2874. UIApplication.shared.visibleViewController?.navigationController?.present(alert, animated: true, completion: nil)
  2875. } else {
  2876. UIApplication.shared.visibleViewController?.present(alert, animated: true, completion: nil)
  2877. }
  2878. })
  2879. }
  2880. } else if message.getCode() == CoreMessage_TMessageCode.ACCEPT_CALL_CENTER {
  2881. let fPinContacCenter = message.getBody(key: CoreMessage_TMessageKey.F_PIN)
  2882. let requester = message.getBody(key: CoreMessage_TMessageKey.UPLINE_PIN)
  2883. let complaintId = message.getBody(key: CoreMessage_TMessageKey.DATA)
  2884. if !requester.isEmpty {
  2885. SecureUserDefaults.shared.set("\(requester),\(fPinContacCenter),\(complaintId)", forKey: "onGoingCC")
  2886. SecureUserDefaults.shared.set("\(fPinContacCenter)", forKey: "membersCC")
  2887. }
  2888. } else if message.getCode() == CoreMessage_TMessageCode.INVITE_TO_ROOM_CONTACT_CENTER {
  2889. if listCCIdInv.contains(message.getBody(key: CoreMessage_TMessageKey.CALL_CENTER_ID)) {
  2890. return
  2891. }
  2892. listCCIdInv.append(message.getBody(key: CoreMessage_TMessageKey.CALL_CENTER_ID))
  2893. DispatchQueue.main.async {
  2894. let alert = LibAlertController(title: "", message: "\n\n\n\n\n\n\n\n\n\n".localized(), preferredStyle: .alert)
  2895. let newWidth = UIScreen.main.bounds.width * 0.90 - 270
  2896. // update width constraint value for main view
  2897. if let viewWidthConstraint = alert.view.constraints.filter({ return $0.firstAttribute == .width }).first{
  2898. viewWidthConstraint.constant = newWidth
  2899. }
  2900. // update width constraint value for container view
  2901. if let containerViewWidthConstraint = alert.view.subviews.first?.constraints.filter({ return $0.firstAttribute == .width }).first {
  2902. containerViewWidthConstraint.constant = newWidth
  2903. }
  2904. let titleFont = [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 18), NSAttributedString.Key.foregroundColor: UIColor.black]
  2905. let titleAttrString = NSMutableAttributedString(string: "You're invited to\nCall Center".localized(), attributes: titleFont)
  2906. alert.setValue(titleAttrString, forKey: "attributedTitle")
  2907. alert.view.subviews.first?.subviews.first?.subviews.first?.backgroundColor = .lightGray
  2908. alert.view.tintColor = .black
  2909. let rejectAction = UIAlertAction(title: "Reject".localized(), style: .destructive, handler: {(_) in
  2910. listCCIdInv.removeAll(where: {$0 == message.getBody(key: CoreMessage_TMessageKey.CALL_CENTER_ID)})
  2911. DispatchQueue.global().async {
  2912. 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))) {
  2913. if result.isOk() {
  2914. return
  2915. }
  2916. }
  2917. }
  2918. alert.dismiss(animated: true, completion: nil)
  2919. })
  2920. let acceptAction = UIAlertAction(title: "Accept".localized(), style: .default, handler: {(_) in
  2921. listCCIdInv.removeAll(where: {$0 == message.getBody(key: CoreMessage_TMessageKey.CALL_CENTER_ID)})
  2922. let goAudioCall = Nexilis.checkMicPermission()
  2923. if !goAudioCall && message.getBody(key: CoreMessage_TMessageKey.CHANNEL) == "1" {
  2924. let alert = LibAlertController(title: "Attention!".localized(), message: "Please allow microphone permission in your settings".localized(), preferredStyle: .alert)
  2925. alert.addAction(UIAlertAction(title: "OK".localized(), style: UIAlertAction.Style.default, handler: { _ in
  2926. if let url = URL(string: UIApplication.openSettingsURLString), UIApplication.shared.canOpenURL(url) {
  2927. UIApplication.shared.open(url, options: [:], completionHandler: nil)
  2928. }
  2929. }))
  2930. if UIApplication.shared.visibleViewController?.navigationController != nil {
  2931. UIApplication.shared.visibleViewController?.navigationController?.present(alert, animated: true, completion: nil)
  2932. } else {
  2933. UIApplication.shared.visibleViewController?.present(alert, animated: true, completion: nil)
  2934. }
  2935. DispatchQueue.global().async {
  2936. 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))) {
  2937. if result.isOk() {
  2938. return
  2939. }
  2940. }
  2941. }
  2942. return
  2943. }
  2944. if message.getBody(key: CoreMessage_TMessageKey.CHANNEL) == "2" {
  2945. var permissionCheck = -1
  2946. if AVCaptureDevice.authorizationStatus(for: .video) == .authorized {
  2947. permissionCheck = 1
  2948. } else if AVCaptureDevice.authorizationStatus(for: .video) == .denied {
  2949. permissionCheck = 0
  2950. } else {
  2951. Nexilis.dispatch = DispatchGroup()
  2952. Nexilis.dispatch?.enter()
  2953. AVCaptureDevice.requestAccess(for: .video, completionHandler: { (granted: Bool) -> Void in
  2954. if granted == true {
  2955. permissionCheck = 1
  2956. } else {
  2957. permissionCheck = 0
  2958. }
  2959. if let dispatch = Nexilis.dispatch {
  2960. dispatch.leave()
  2961. }
  2962. })
  2963. Nexilis.dispatch?.wait()
  2964. Nexilis.dispatch = nil
  2965. }
  2966. if permissionCheck == 0 {
  2967. let alert = LibAlertController(title: "Attention!".localized(), message: "Please allow camera permission in your settings".localized(), preferredStyle: .alert)
  2968. alert.addAction(UIAlertAction(title: "OK".localized(), style: UIAlertAction.Style.default, handler: { _ in
  2969. if let url = URL(string: UIApplication.openSettingsURLString), UIApplication.shared.canOpenURL(url) {
  2970. UIApplication.shared.open(url, options: [:], completionHandler: nil)
  2971. }
  2972. }))
  2973. if UIApplication.shared.visibleViewController?.navigationController != nil {
  2974. UIApplication.shared.visibleViewController?.navigationController?.present(alert, animated: true, completion: nil)
  2975. } else {
  2976. UIApplication.shared.visibleViewController?.present(alert, animated: true, completion: nil)
  2977. }
  2978. DispatchQueue.global().async {
  2979. 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))) {
  2980. if result.isOk() {
  2981. return
  2982. }
  2983. }
  2984. }
  2985. return
  2986. }
  2987. }
  2988. if UIApplication.shared.visibleViewController is UINavigationController {
  2989. let nc = UIApplication.shared.visibleViewController as! UINavigationController
  2990. if nc.visibleViewController is QmeraStreamingViewController {
  2991. let vc = nc.visibleViewController as! QmeraStreamingViewController
  2992. var alert = LibAlertController(title: "", message: "Are you sure you want to end Live Streaming, and open notification?".localized(), preferredStyle: .alert)
  2993. if !vc.isLive {
  2994. alert = LibAlertController(title: "", message: "Are you sure you want to leave Live Streaming, and open notification?".localized(), preferredStyle: .alert)
  2995. }
  2996. alert.addAction(UIAlertAction(title: "No".localized(), style: UIAlertAction.Style.default, handler: { _ in
  2997. DispatchQueue.global().async {
  2998. 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))) {
  2999. if result.isOk() {
  3000. return
  3001. }
  3002. }
  3003. }
  3004. alert.dismiss(animated: true, completion: nil)
  3005. }))
  3006. alert.addAction(UIAlertAction(title: "Yes".localized(), style: UIAlertAction.Style.default, handler: { _ in
  3007. DispatchQueue.global().async {
  3008. API.terminateBC(sBroadcasterID: vc.isLive ? nil : vc.data)
  3009. vc.sendLeft()
  3010. }
  3011. vc.dismiss(animated: true, completion: {
  3012. acceptCC()
  3013. })
  3014. }))
  3015. nc.present(alert, animated: true, completion: nil)
  3016. } else if nc.visibleViewController is SeminarViewController {
  3017. let vc = nc.visibleViewController as! SeminarViewController
  3018. var alert = LibAlertController(title: "", message: "Are you sure you want to end Seminar, and open notification?".localized(), preferredStyle: .alert)
  3019. if !vc.isLive {
  3020. alert = LibAlertController(title: "", message: "Are you sure you want to leave Seminar, and open notification?".localized(), preferredStyle: .alert)
  3021. }
  3022. alert.addAction(UIAlertAction(title: "No".localized(), style: UIAlertAction.Style.default, handler: { _ in
  3023. DispatchQueue.global().async {
  3024. 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))) {
  3025. if result.isOk() {
  3026. return
  3027. }
  3028. }
  3029. }
  3030. alert.dismiss(animated: true, completion: nil)
  3031. }))
  3032. alert.addAction(UIAlertAction(title: "Yes".localized(), style: UIAlertAction.Style.default, handler: { _ in
  3033. DispatchQueue.global().async {
  3034. API.terminateBC(sBroadcasterID: vc.isLive ? nil : vc.data)
  3035. vc.sendLeft()
  3036. }
  3037. vc.dismiss(animated: true, completion: {
  3038. acceptCC()
  3039. })
  3040. }))
  3041. nc.present(alert, animated: true, completion: nil)
  3042. } else {
  3043. acceptCC()
  3044. }
  3045. } else {
  3046. acceptCC()
  3047. }
  3048. func acceptCC() {
  3049. 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))) {
  3050. if result.isOk() {
  3051. let requester = result.getBody(key: CoreMessage_TMessageKey.UPLINE_PIN)
  3052. let officer = result.getBody(key: CoreMessage_TMessageKey.FRIEND_FPIN)
  3053. let data = result.getBody(key: CoreMessage_TMessageKey.DATA)
  3054. let complaintId = message.getBody(key: CoreMessage_TMessageKey.CALL_CENTER_ID)
  3055. SecureUserDefaults.shared.set("\(requester),\(officer),\(complaintId)", forKey: "onGoingCC")
  3056. SecureUserDefaults.shared.set("\(Date().currentTimeMillis())", forKey: "startTimeCC")
  3057. if !data.isEmpty {
  3058. if let jsonArray = try! JSONSerialization.jsonObject(with: data.data(using: String.Encoding.utf8)!, options: JSONSerialization.ReadingOptions()) as? [AnyObject] {
  3059. var members = ""
  3060. var user : [User] = []
  3061. let idMe = User.getMyPin()!
  3062. for json in jsonArray {
  3063. if "\(json)" != idMe {
  3064. if members.isEmpty {
  3065. members = "\(json)"
  3066. } else {
  3067. members += ",\(json)"
  3068. }
  3069. if let userData = User.getData(pin: "\(json)") {
  3070. user.append(userData)
  3071. } else {
  3072. Nexilis.addFriendSilent(fpin: "\(json)")
  3073. DispatchQueue.main.asyncAfter(deadline: .now() + 1, execute: {
  3074. if let userData = User.getData(pin: "\(json)") {
  3075. user.append(userData)
  3076. }
  3077. })
  3078. }
  3079. }
  3080. }
  3081. SecureUserDefaults.shared.set("\(members)", forKey: "membersCC")
  3082. if message.getBody(key: CoreMessage_TMessageKey.CHANNEL) == "0" {
  3083. let editorPersonalVC = AppStoryBoard.Palio.instance.instantiateViewController(identifier: "editorPersonalVC") as! EditorPersonal
  3084. editorPersonalVC.hidesBottomBarWhenPushed = true
  3085. editorPersonalVC.unique_l_pin = officer
  3086. editorPersonalVC.fromNotification = true
  3087. editorPersonalVC.isContactCenter = true
  3088. editorPersonalVC.fPinContacCenter = members
  3089. editorPersonalVC.complaintId = complaintId
  3090. editorPersonalVC.onGoingCC = true
  3091. editorPersonalVC.isRequestContactCenter = false
  3092. editorPersonalVC.users = user
  3093. let navigationController = CustomNavigationController(rootViewController: editorPersonalVC)
  3094. navigationController.modalPresentationStyle = .fullScreen
  3095. navigationController.navigationBar.tintColor = .white
  3096. navigationController.navigationBar.barTintColor = UIApplication.shared.visibleViewController?.traitCollection.userInterfaceStyle == .dark ? .blackDarkMode : .mainColor
  3097. navigationController.navigationBar.isTranslucent = false
  3098. navigationController.navigationBar.overrideUserInterfaceStyle = .dark
  3099. navigationController.navigationBar.barStyle = .black
  3100. let cancelButtonAttributes: [NSAttributedString.Key: Any] = [NSAttributedString.Key.foregroundColor: UIColor.white, NSAttributedString.Key.font : UIFont.systemFont(ofSize: 16)]
  3101. UIBarButtonItem.appearance().setTitleTextAttributes(cancelButtonAttributes, for: .normal)
  3102. let textAttributes = [NSAttributedString.Key.foregroundColor:UIColor.white]
  3103. navigationController.navigationBar.titleTextAttributes = textAttributes
  3104. if UIApplication.shared.visibleViewController?.navigationController != nil {
  3105. UIApplication.shared.visibleViewController?.navigationController?.present(navigationController, animated: true, completion: nil)
  3106. } else {
  3107. UIApplication.shared.visibleViewController?.present(navigationController, animated: true, completion: nil)
  3108. }
  3109. } else {
  3110. SecureUserDefaults.shared.set("\(Date().currentTimeMillis())", forKey: "startTimeCC")
  3111. DispatchQueue.main.asyncAfter(deadline: .now() + 1, execute: {
  3112. if message.getBody(key: CoreMessage_TMessageKey.CHANNEL) == "1" {
  3113. let pin = officer
  3114. let controller = QmeraAudioViewController()
  3115. controller.user = User.getData(pin: pin)
  3116. controller.isOutgoing = false
  3117. controller.ticketId = complaintId
  3118. controller.modalPresentationStyle = .overCurrentContext
  3119. let navigationController = CustomNavigationController(rootViewController: controller)
  3120. navigationController.modalPresentationStyle = .fullScreen
  3121. if UIApplication.shared.visibleViewController?.navigationController != nil {
  3122. UIApplication.shared.visibleViewController?.navigationController?.present(navigationController, animated: true, completion: nil)
  3123. } else {
  3124. UIApplication.shared.visibleViewController?.present(navigationController, animated: true, completion: nil)
  3125. }
  3126. } else if message.getBody(key: CoreMessage_TMessageKey.CHANNEL) == "2" {
  3127. let videoVC = AppStoryBoard.Palio.instance.instantiateViewController(withIdentifier: "videoVCQmera") as! QmeraVideoViewController
  3128. videoVC.fPin = officer
  3129. videoVC.users.append(User.getData(pin: officer)!)
  3130. videoVC.ticketId = complaintId
  3131. videoVC.isInisiator = false
  3132. videoVC.isAutoAccept = true
  3133. let navigationController = CustomNavigationController(rootViewController: videoVC)
  3134. navigationController.modalPresentationStyle = .fullScreen
  3135. if UIApplication.shared.visibleViewController?.navigationController != nil {
  3136. UIApplication.shared.visibleViewController?.navigationController?.present(navigationController, animated: true, completion: nil)
  3137. } else {
  3138. UIApplication.shared.visibleViewController?.present(navigationController, animated: true, completion: nil)
  3139. }
  3140. }
  3141. })
  3142. }
  3143. }
  3144. }
  3145. } else {
  3146. let imageView = UIImageView(image: UIImage(systemName: "info.circle"))
  3147. imageView.tintColor = .white
  3148. 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)
  3149. banner.show()
  3150. }
  3151. }
  3152. }
  3153. })
  3154. alert.addAction(rejectAction)
  3155. alert.addAction(acceptAction)
  3156. let containerView = UIView(frame: CGRect(x: 50, y: 80, width: alert.view.bounds.size.width * 0.9 - 100, height: 150))
  3157. alert.view.addSubview(containerView)
  3158. containerView.layer.cornerRadius = 10.0
  3159. containerView.clipsToBounds = true
  3160. containerView.backgroundColor = .secondaryColor.withAlphaComponent(0.5)
  3161. let userData = User.getData(pin: message.getPIN())
  3162. let imageProfile = UIImageView()
  3163. containerView.addSubview(imageProfile)
  3164. imageProfile.translatesAutoresizingMaskIntoConstraints = false
  3165. NSLayoutConstraint.activate([
  3166. imageProfile.topAnchor.constraint(equalTo: containerView.topAnchor, constant: 10),
  3167. imageProfile.bottomAnchor.constraint(equalTo: containerView.bottomAnchor, constant: -10),
  3168. imageProfile.leadingAnchor.constraint(equalTo: containerView.leadingAnchor, constant: 10),
  3169. imageProfile.widthAnchor.constraint(equalToConstant: 100)
  3170. ])
  3171. imageProfile.layer.cornerRadius = 10.0
  3172. imageProfile.clipsToBounds = true
  3173. imageProfile.backgroundColor = .lightGray.withAlphaComponent(0.3)
  3174. imageProfile.tintColor = .secondaryColor
  3175. imageProfile.image = UIImage(systemName: "person")
  3176. if userData!.thumb != "" {
  3177. imageProfile.setImage(name: userData!.thumb)
  3178. imageProfile.contentMode = .scaleAspectFill
  3179. }
  3180. let labelName = UILabel()
  3181. containerView.addSubview(labelName)
  3182. labelName.translatesAutoresizingMaskIntoConstraints = false
  3183. NSLayoutConstraint.activate([
  3184. labelName.topAnchor.constraint(equalTo: containerView.topAnchor, constant: 15),
  3185. labelName.leadingAnchor.constraint(equalTo: imageProfile.trailingAnchor, constant: 5)
  3186. ])
  3187. labelName.font = UIFont.systemFont(ofSize: 12)
  3188. labelName.text = "Name".localized()
  3189. labelName.textColor = .mainColor
  3190. let valueName = UILabel()
  3191. containerView.addSubview(valueName)
  3192. valueName.translatesAutoresizingMaskIntoConstraints = false
  3193. NSLayoutConstraint.activate([
  3194. valueName.topAnchor.constraint(equalTo: labelName.bottomAnchor),
  3195. valueName.leadingAnchor.constraint(equalTo: imageProfile.trailingAnchor, constant: 5)
  3196. ])
  3197. valueName.font = UIFont.systemFont(ofSize: 12)
  3198. valueName.text = userData!.fullName
  3199. valueName.textColor = .mainColor
  3200. let labelType = UILabel()
  3201. containerView.addSubview(labelType)
  3202. labelType.translatesAutoresizingMaskIntoConstraints = false
  3203. NSLayoutConstraint.activate([
  3204. labelType.topAnchor.constraint(equalTo: valueName.bottomAnchor, constant: 5),
  3205. labelType.leadingAnchor.constraint(equalTo: imageProfile.trailingAnchor, constant: 5)
  3206. ])
  3207. labelType.font = UIFont.systemFont(ofSize: 12)
  3208. labelType.text = "Request Type".localized()
  3209. labelType.textColor = .mainColor
  3210. let valueType = UILabel()
  3211. containerView.addSubview(valueType)
  3212. valueType.translatesAutoresizingMaskIntoConstraints = false
  3213. NSLayoutConstraint.activate([
  3214. valueType.topAnchor.constraint(equalTo: labelType.bottomAnchor),
  3215. valueType.leadingAnchor.constraint(equalTo: imageProfile.trailingAnchor, constant: 5)
  3216. ])
  3217. valueType.font = UIFont.systemFont(ofSize: 12)
  3218. if message.getBody(key: CoreMessage_TMessageKey.CHANNEL) == "0" {
  3219. valueType.text = "Chat".localized()
  3220. } else if message.getBody(key: CoreMessage_TMessageKey.CHANNEL) == "1" {
  3221. valueType.text = "Audio Call".localized()
  3222. } else if message.getBody(key: CoreMessage_TMessageKey.CHANNEL) == "2" {
  3223. valueType.text = "Video Call".localized()
  3224. } else {
  3225. valueType.text = "Email".localized()
  3226. }
  3227. valueType.textColor = .mainColor
  3228. let labelIdentity = UILabel()
  3229. containerView.addSubview(labelIdentity)
  3230. labelIdentity.translatesAutoresizingMaskIntoConstraints = false
  3231. NSLayoutConstraint.activate([
  3232. labelIdentity.topAnchor.constraint(equalTo: valueType.bottomAnchor, constant: 5),
  3233. labelIdentity.leadingAnchor.constraint(equalTo: imageProfile.trailingAnchor, constant: 5)
  3234. ])
  3235. labelIdentity.font = UIFont.systemFont(ofSize: 12)
  3236. labelIdentity.text = "Complaint ID".localized()
  3237. labelIdentity.textColor = .mainColor
  3238. let valueIdentity = UILabel()
  3239. containerView.addSubview(valueIdentity)
  3240. valueIdentity.translatesAutoresizingMaskIntoConstraints = false
  3241. NSLayoutConstraint.activate([
  3242. valueIdentity.topAnchor.constraint(equalTo: labelIdentity.bottomAnchor),
  3243. valueIdentity.leadingAnchor.constraint(equalTo: imageProfile.trailingAnchor, constant: 5),
  3244. valueIdentity.trailingAnchor.constraint(equalTo: containerView.trailingAnchor)
  3245. ])
  3246. valueIdentity.font = UIFont.systemFont(ofSize: 12)
  3247. valueIdentity.text = message.getBody(key: CoreMessage_TMessageKey.CALL_CENTER_ID)
  3248. valueIdentity.numberOfLines = 0
  3249. valueIdentity.textColor = .mainColor
  3250. if UIApplication.shared.visibleViewController?.navigationController != nil {
  3251. UIApplication.shared.visibleViewController?.navigationController?.present(alert, animated: true, completion: nil)
  3252. } else {
  3253. UIApplication.shared.visibleViewController?.present(alert, animated: true, completion: nil)
  3254. }
  3255. }
  3256. } 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.getBody(key: CoreMessage_TMessageKey.MERCHANT_NAME).isEmpty {
  3257. let m = message.mBodies
  3258. if !message.getBody(key: CoreMessage_TMessageKey.MERCHANT_NAME).isEmpty {
  3259. // Utils.setDebugBC(value: m)
  3260. DispatchQueue.main.async {
  3261. if !Nexilis.broadcastList.isEmpty {
  3262. Nexilis.broadcastList.append(m)
  3263. } else {
  3264. Nexilis.broadcastList.append(m)
  3265. Nexilis.shared.showBroadcastMessage(m: m)
  3266. }
  3267. }
  3268. return
  3269. }
  3270. if !Nexilis.showLibraryNotification {
  3271. return
  3272. }
  3273. let sender = message.getBody(key: CoreMessage_TMessageKey.F_PIN)
  3274. let me = User.getMyPin()!
  3275. if(sender != me) {
  3276. let inEditorPersonal: String? = SecureUserDefaults.shared.value(forKey: "inEditorPersonal") ?? nil
  3277. let inEditorGroup: [String]? = SecureUserDefaults.shared.value(forKey: "inEditorGroup") ?? nil
  3278. var text = message.getBody(key: CoreMessage_TMessageKey.MESSAGE_TEXT)
  3279. let imageId = CoreMessage_TMessageKey.IMAGE_ID
  3280. let videoId = CoreMessage_TMessageKey.VIDEO_ID
  3281. let fileId = CoreMessage_TMessageKey.FILE_ID
  3282. let audioId = CoreMessage_TMessageKey.AUDIO_ID
  3283. let attachmentFlag = CoreMessage_TMessageKey.ATTACHMENT_FLAG
  3284. let messageScopeId = CoreMessage_TMessageKey.MESSAGE_SCOPE_ID
  3285. let messageText = CoreMessage_TMessageKey.MESSAGE_TEXT
  3286. let credential = CoreMessage_TMessageKey.CREDENTIAL
  3287. if !message.getBody(key: imageId).isEmpty {
  3288. text = "Sent Image 📷"
  3289. } else if message.getBody(key: attachmentFlag) == "11" {
  3290. text = "Sent Sticker ❤️"
  3291. } else if !message.getBody(key: videoId).isEmpty {
  3292. text = "Sent Video 📹"
  3293. } else if !message.getBody(key: fileId).isEmpty {
  3294. if message.getBody(key: messageScopeId) == "18" {
  3295. text = "Sent Form 📄"
  3296. } else {
  3297. text = "Sent File 📄"
  3298. }
  3299. } else if !message.getBody(key: audioId).isEmpty {
  3300. text = "Sent Audio ♫"
  3301. } else if message.getBody(key: messageText).contains("Share%20location%20") {
  3302. text = "Sent Location 📌"
  3303. } else if message.getBody(key: attachmentFlag) == "27" {
  3304. text = "Sent Live Streaming"
  3305. } else if message.getBody(key: attachmentFlag) == "26" {
  3306. text = "Sent Seminar"
  3307. } else if message.getBody(key: attachmentFlag) == "25" {
  3308. text = "Sent Video Conference Room"
  3309. } else if message.getBody(key: attachmentFlag) == "24" {
  3310. text = "Sent Quiz"
  3311. } else if message.getBody(key: credential) == "1" {
  3312. text = "Sent Confidential Message"
  3313. }
  3314. var nameUser: String?
  3315. var profile = ""
  3316. var threadIdentifier = sender
  3317. let onGoingCC: String = SecureUserDefaults.shared.value(forKey: "onGoingCC") ?? ""
  3318. if !onGoingCC.isEmpty {
  3319. return
  3320. }
  3321. if Utils.inTabChats{
  3322. return
  3323. }
  3324. if message.getBody(key: messageScopeId) == "3" || message.getBody(key: messageScopeId) == "18" || message.getBody(key: messageScopeId) == "5" {
  3325. if inEditorPersonal == sender || (inEditorPersonal != nil && inEditorPersonal!.contains(",")) {
  3326. return
  3327. }
  3328. if(nameUser == nil) {
  3329. Database.shared.database?.inTransaction({ (fmdb, rollback) in
  3330. do {
  3331. if let cursor = Database.shared.getRecords(fmdb: fmdb, query: "SELECT first_name, last_name, image_id FROM BUDDY WHERE f_pin='\(String(describing: sender))'") {
  3332. while cursor.next() {
  3333. let first_name = cursor.string(forColumnIndex: 0)!
  3334. let last_name = cursor.string(forColumnIndex: 1)!
  3335. nameUser = "\(first_name) \(last_name)".trimmingCharacters(in: .whitespaces)
  3336. profile = cursor.string(forColumnIndex: 2)!
  3337. }
  3338. cursor.close()
  3339. }
  3340. } catch {
  3341. rollback.pointee = true
  3342. print("Access database error: \(error.localizedDescription)")
  3343. }
  3344. })
  3345. }
  3346. } else {
  3347. let idGroup = message.getBody(key: CoreMessage_TMessageKey.L_PIN)
  3348. var topicGroup: String?
  3349. var idTopic: String?
  3350. if !message.getBody(key: CoreMessage_TMessageKey.CHAT_ID).isEmpty {
  3351. idTopic = message.getBody(key: CoreMessage_TMessageKey.CHAT_ID)
  3352. }
  3353. if (idTopic == nil) {
  3354. idTopic = "Lounge"
  3355. topicGroup = "Lounge"
  3356. } else {
  3357. Database.shared.database?.inTransaction({ (fmdb, rollback) in
  3358. do {
  3359. if let cursor = Database.shared.getRecords(fmdb: fmdb, query: "SELECT title FROM DISCUSSION_FORUM WHERE chat_id='\(idTopic!)'") {
  3360. while cursor.next() {
  3361. let title = cursor.string(forColumnIndex: 0)
  3362. topicGroup = title
  3363. }
  3364. cursor.close()
  3365. }
  3366. } catch {
  3367. rollback.pointee = true
  3368. print("Access database error: \(error.localizedDescription)")
  3369. }
  3370. })
  3371. }
  3372. if (inEditorGroup != nil) {
  3373. let editorIdGroup = inEditorGroup![0]
  3374. let editorIdTopic = inEditorGroup![1]
  3375. var idTempTopic = idTopic
  3376. if (idTempTopic == "Lounge") {
  3377. idTempTopic = ""
  3378. }
  3379. if (editorIdGroup == idGroup && editorIdTopic == idTempTopic) {
  3380. return
  3381. }
  3382. }
  3383. Database.shared.database?.inTransaction({ (fmdb, rollback) in
  3384. do {
  3385. if let cursor = Database.shared.getRecords(fmdb: fmdb, query: "SELECT f_name, image_id FROM GROUPZ WHERE group_id='\(idGroup)'") {
  3386. while cursor.next() {
  3387. let f_name = cursor.string(forColumnIndex: 0)
  3388. var senderName = message.getBody(key: CoreMessage_TMessageKey.F_DISPLAY_NAME)
  3389. if senderName.isEmpty {
  3390. senderName = "Bot"
  3391. }
  3392. nameUser =
  3393. "\(senderName) \u{2022} \(f_name!)(\(topicGroup!))"
  3394. profile = cursor.string(forColumnIndex: 1)!
  3395. }
  3396. cursor.close()
  3397. }
  3398. } catch {
  3399. rollback.pointee = true
  3400. print("Access database error: \(error.localizedDescription)")
  3401. }
  3402. })
  3403. if idTopic == "Lounge" {
  3404. threadIdentifier = idGroup
  3405. } else {
  3406. threadIdentifier = idTopic!
  3407. }
  3408. }
  3409. if nameUser == nil && threadIdentifier == "-999" {
  3410. nameUser = "Bot"
  3411. }
  3412. DispatchQueue.main.async { [self] in
  3413. let container = UIView()
  3414. container.backgroundColor = .gray
  3415. let profileImage = UIImageView()
  3416. profileImage.frame.size = CGSize(width: 60, height: 60)
  3417. container.addSubview(profileImage)
  3418. profileImage.translatesAutoresizingMaskIntoConstraints = false
  3419. NSLayoutConstraint.activate([
  3420. profileImage.leadingAnchor.constraint(equalTo: container.leadingAnchor, constant: 8.0),
  3421. profileImage.centerYAnchor.constraint(equalTo: container.centerYAnchor),
  3422. profileImage.widthAnchor.constraint(equalToConstant: 60),
  3423. profileImage.heightAnchor.constraint(equalToConstant: 60),
  3424. ])
  3425. let title = UILabel()
  3426. container.addSubview(title)
  3427. title.translatesAutoresizingMaskIntoConstraints = false
  3428. NSLayoutConstraint.activate([
  3429. title.leadingAnchor.constraint(equalTo: profileImage.trailingAnchor, constant: 8.0),
  3430. title.topAnchor.constraint(equalTo: container.topAnchor, constant: 20.0),
  3431. ])
  3432. title.font = UIFont.systemFont(ofSize: 14)
  3433. title.text = nameUser ?? "Unknown"
  3434. title.textColor = .white
  3435. let subtitle = UILabel()
  3436. container.addSubview(subtitle)
  3437. subtitle.translatesAutoresizingMaskIntoConstraints = false
  3438. NSLayoutConstraint.activate([
  3439. subtitle.leadingAnchor.constraint(equalTo: profileImage.trailingAnchor, constant: 8.0),
  3440. subtitle.trailingAnchor.constraint(equalTo: container.trailingAnchor, constant: -15.0),
  3441. subtitle.topAnchor.constraint(equalTo: title.bottomAnchor),
  3442. ])
  3443. subtitle.font = UIFont.systemFont(ofSize: 12)
  3444. subtitle.attributedText = text.richText()
  3445. subtitle.textColor = .white
  3446. if floating != nil {
  3447. floating.dismiss()
  3448. }
  3449. floating = FloatingNotificationBanner(customView: container)
  3450. floating.bannerHeight = 100.0
  3451. floating.transparency = 0.9
  3452. if threadIdentifier == "-999" {
  3453. if !Utils.getIconDock().isEmpty {
  3454. 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
  3455. if dataImage != nil {
  3456. profileImage.image = UIImage(data: dataImage!)
  3457. }
  3458. } else {
  3459. profileImage.image = UIImage(named: "pb_button", in: Bundle.resourceBundle(for: Nexilis.self), with: nil)
  3460. }
  3461. } else if profile != "" {
  3462. profileImage.circle()
  3463. do {
  3464. let documentDir = try FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
  3465. let file = documentDir.appendingPathComponent(profile)
  3466. if FileManager().fileExists(atPath: file.path) {
  3467. profileImage.image = UIImage(contentsOfFile: file.path)
  3468. profileImage.backgroundColor = .clear
  3469. } else {
  3470. Download().startHTTP(forKey: profile) { (name, progress) in
  3471. guard progress == 100 else {
  3472. return
  3473. }
  3474. DispatchQueue.main.async { [self] in
  3475. profileImage.image = UIImage(contentsOfFile: file.path)
  3476. profileImage.backgroundColor = .clear
  3477. if !onGoingCC.isEmpty {
  3478. floating.autoDismiss = false
  3479. }
  3480. 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)
  3481. floating.onTap = {
  3482. showNotif()
  3483. }
  3484. }
  3485. }
  3486. return
  3487. }
  3488. } catch {}
  3489. profileImage.contentMode = .scaleAspectFill
  3490. } else {
  3491. profileImage.circle()
  3492. if message.getBody(key: messageScopeId) == "3" {
  3493. profileImage.image = UIImage(systemName: "person")
  3494. } else {
  3495. profileImage.image = UIImage(systemName: "person.3")
  3496. }
  3497. profileImage.contentMode = .scaleAspectFit
  3498. profileImage.backgroundColor = .lightGray
  3499. profileImage.tintColor = .white
  3500. }
  3501. 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)
  3502. let vibrateMode: Bool = SecureUserDefaults.shared.value(forKey: "vibrateMode") ?? false
  3503. var soundId: String = SecureUserDefaults.shared.value(forKey: "notifSoundPersonal") ?? ""
  3504. if message.getBody(key: CoreMessage_TMessageKey.MESSAGE_SCOPE_ID) == "4" {
  3505. soundId = SecureUserDefaults.shared.value(forKey: "notifSoundGroup") ?? ""
  3506. }
  3507. var systemSoundID: SystemSoundID!
  3508. if soundId.isEmpty {
  3509. systemSoundID = 1007
  3510. } else {
  3511. systemSoundID = SystemSoundID(Int(soundId.components(separatedBy: ":")[0])!)
  3512. }
  3513. if vibrateMode {
  3514. AudioServicesPlaySystemSound(systemSoundID)
  3515. } else {
  3516. var nameSound = "sms-received1"
  3517. if systemSoundID != 1007 {
  3518. nameSound = soundId.components(separatedBy: ":")[1]
  3519. }
  3520. let url = URL(fileURLWithPath: "/System/Library/Audio/UISounds/\(nameSound).caf")
  3521. AudioServicesCreateSystemSoundID(url as CFURL, &systemSoundID)
  3522. AudioServicesPlaySystemSound(systemSoundID)
  3523. }
  3524. if !onGoingCC.isEmpty {
  3525. floating.autoDismiss = false
  3526. }
  3527. floating.onTap = {
  3528. showNotif()
  3529. }
  3530. func showNotif() {
  3531. if message.getBody(key: attachmentFlag) == "59" {
  3532. let date = Date(milliseconds: Int64(message.getBody(key: CoreMessage_TMessageKey.LOCAL_TIMESTAMP))!)
  3533. let formatter = DateFormatter()
  3534. formatter.dateFormat = "HH:mm"
  3535. formatter.locale = NSLocale(localeIdentifier: "id") as Locale?
  3536. var timeSignIn = formatter.string(from: date as Date)
  3537. let dialog = DialogSignIn()
  3538. dialog.valueDevice = message.getBody(key: CoreMessage_TMessageKey.DEVICE_BRAND)
  3539. dialog.valueTime = timeSignIn
  3540. dialog.valueLocation = message.getBody(key: CoreMessage_TMessageKey.PLACE_NAME)
  3541. dialog.valueToken = message.getBody(key: CoreMessage_TMessageKey.TOKEN)
  3542. dialog.valueUser = message.getBody(key: CoreMessage_TMessageKey.USER_ID)
  3543. dialog.modalTransitionStyle = .crossDissolve
  3544. dialog.modalPresentationStyle = .overCurrentContext
  3545. UIApplication.shared.visibleViewController?.present(dialog, animated: true)
  3546. return
  3547. }
  3548. if !onGoingCC.isEmpty {
  3549. floating.dismiss()
  3550. }
  3551. Database.shared.database?.inTransaction({ (fmdb, rollback) in
  3552. do {
  3553. if let cursorData = Database.shared.getRecords(fmdb: fmdb, query: "SELECT first_name, last_name FROM BUDDY where f_pin = '\(User.getMyPin()!)'"), cursorData.next() {
  3554. if (cursorData.string(forColumnIndex: 0)! + " " + cursorData.string(forColumnIndex: 1)!).trimmingCharacters(in: .whitespaces) == "USR\(User.getMyPin()!)" {
  3555. let alert = LibAlertController(title: "Change Profile".localized(), message: "You must change your name to use this feature".localized(), preferredStyle: .alert)
  3556. alert.addAction(UIAlertAction(title: "OK".localized(), style: UIAlertAction.Style.default, handler: {(_) in
  3557. let controller = AppStoryBoard.Palio.instance.instantiateViewController(withIdentifier: "signupsignin") as! SignUpSignIn
  3558. controller.forceLogin = true
  3559. let navigationController = CustomNavigationController(rootViewController: controller)
  3560. navigationController.modalPresentationStyle = .fullScreen
  3561. navigationController.navigationBar.tintColor = .white
  3562. navigationController.navigationBar.barTintColor = UIApplication.shared.visibleViewController?.traitCollection.userInterfaceStyle == .dark ? .blackDarkMode : .mainColor
  3563. navigationController.navigationBar.isTranslucent = false
  3564. navigationController.navigationBar.overrideUserInterfaceStyle = .dark
  3565. navigationController.navigationBar.barStyle = .black
  3566. let cancelButtonAttributes: [NSAttributedString.Key: Any] = [NSAttributedString.Key.foregroundColor: UIColor.white, NSAttributedString.Key.font : UIFont.systemFont(ofSize: 16)]
  3567. UIBarButtonItem.appearance().setTitleTextAttributes(cancelButtonAttributes, for: .normal)
  3568. let textAttributes = [NSAttributedString.Key.foregroundColor:UIColor.white]
  3569. navigationController.navigationBar.titleTextAttributes = textAttributes
  3570. if UIApplication.shared.visibleViewController?.navigationController != nil {
  3571. UIApplication.shared.visibleViewController?.navigationController?.present(navigationController, animated: true, completion: nil)
  3572. } else {
  3573. UIApplication.shared.visibleViewController?.present(navigationController, animated: true, completion: nil)
  3574. }
  3575. }))
  3576. if UIApplication.shared.visibleViewController?.navigationController != nil {
  3577. UIApplication.shared.visibleViewController?.navigationController?.present(alert, animated: true, completion: nil)
  3578. } else {
  3579. UIApplication.shared.visibleViewController?.present(alert, animated: true, completion: nil)
  3580. }
  3581. }
  3582. cursorData.close()
  3583. return
  3584. }
  3585. } catch {
  3586. rollback.pointee = true
  3587. print("Access database error: \(error.localizedDescription)")
  3588. }
  3589. })
  3590. if message.getBody(key: messageScopeId) == "3" || message.getBody(key: messageScopeId) == "18" || message.getBody(key: messageScopeId) == "5" {
  3591. func openEditor() {
  3592. let editorPersonalVC = AppStoryBoard.Palio.instance.instantiateViewController(identifier: "editorPersonalVC") as! EditorPersonal
  3593. editorPersonalVC.hidesBottomBarWhenPushed = true
  3594. editorPersonalVC.unique_l_pin = threadIdentifier
  3595. editorPersonalVC.fromNotification = true
  3596. if !onGoingCC.isEmpty {
  3597. let compalintId = onGoingCC.components(separatedBy: ",")[2]
  3598. let fPinCC = onGoingCC.isEmpty ? "" : onGoingCC.components(separatedBy: ",")[1]
  3599. editorPersonalVC.isContactCenter = true
  3600. editorPersonalVC.fPinContacCenter = fPinCC
  3601. editorPersonalVC.complaintId = compalintId
  3602. editorPersonalVC.onGoingCC = true
  3603. editorPersonalVC.isRequestContactCenter = false
  3604. }
  3605. let navigationController = CustomNavigationController(rootViewController: editorPersonalVC)
  3606. navigationController.modalPresentationStyle = .fullScreen
  3607. navigationController.navigationBar.tintColor = .white
  3608. navigationController.navigationBar.barTintColor = UIApplication.shared.visibleViewController?.traitCollection.userInterfaceStyle == .dark ? .blackDarkMode : .mainColor
  3609. navigationController.navigationBar.isTranslucent = false
  3610. navigationController.navigationBar.overrideUserInterfaceStyle = .dark
  3611. navigationController.navigationBar.barStyle = .black
  3612. let cancelButtonAttributes: [NSAttributedString.Key: Any] = [NSAttributedString.Key.foregroundColor: UIColor.white, NSAttributedString.Key.font : UIFont.systemFont(ofSize: 16)]
  3613. UIBarButtonItem.appearance().setTitleTextAttributes(cancelButtonAttributes, for: .normal)
  3614. let textAttributes = [NSAttributedString.Key.foregroundColor:UIColor.white]
  3615. navigationController.navigationBar.titleTextAttributes = textAttributes
  3616. if UIApplication.shared.visibleViewController?.navigationController != nil {
  3617. UIApplication.shared.visibleViewController?.navigationController?.present(navigationController, animated: true, completion: nil)
  3618. } else {
  3619. UIApplication.shared.visibleViewController?.present(navigationController, animated: true, completion: nil)
  3620. }
  3621. }
  3622. if UIApplication.shared.visibleViewController is UINavigationController {
  3623. let nc = UIApplication.shared.visibleViewController as! UINavigationController
  3624. if nc.visibleViewController is QmeraStreamingViewController {
  3625. let vc = nc.visibleViewController as! QmeraStreamingViewController
  3626. var alert = LibAlertController(title: "", message: "Are you sure you want to end Live Streaming, and open notification?".localized(), preferredStyle: .alert)
  3627. if !vc.isLive {
  3628. alert = LibAlertController(title: "", message: "Are you sure you want to leave Live Streaming, and open notification?".localized(), preferredStyle: .alert)
  3629. }
  3630. alert.addAction(UIAlertAction(title: "No".localized(), style: UIAlertAction.Style.default, handler: nil))
  3631. alert.addAction(UIAlertAction(title: "Yes".localized(), style: UIAlertAction.Style.default, handler: { _ in
  3632. DispatchQueue.global().async {
  3633. API.terminateBC(sBroadcasterID: vc.isLive ? nil : vc.data)
  3634. vc.sendLeft()
  3635. }
  3636. vc.dismiss(animated: true, completion: {
  3637. openEditor()
  3638. })
  3639. }))
  3640. nc.present(alert, animated: true, completion: nil)
  3641. // NotificationCenter.default.post(name: NSNotification.Name(rawValue: "isRunningStreaming"), object: nil, userInfo: dataMessage)
  3642. } else if nc.visibleViewController is SeminarViewController {
  3643. let vc = nc.visibleViewController as! SeminarViewController
  3644. var alert = LibAlertController(title: "", message: "Are you sure you want to end Seminar, and open notification?".localized(), preferredStyle: .alert)
  3645. if !vc.isLive {
  3646. alert = LibAlertController(title: "", message: "Are you sure you want to leave Seminar, and open notification?".localized(), preferredStyle: .alert)
  3647. }
  3648. alert.addAction(UIAlertAction(title: "No".localized(), style: UIAlertAction.Style.default, handler: nil))
  3649. alert.addAction(UIAlertAction(title: "Yes".localized(), style: UIAlertAction.Style.default, handler: { _ in
  3650. DispatchQueue.global().async {
  3651. API.terminateBC(sBroadcasterID: vc.isLive ? nil : vc.data)
  3652. vc.sendLeft()
  3653. }
  3654. vc.dismiss(animated: true, completion: {
  3655. openEditor()
  3656. })
  3657. }))
  3658. nc.present(alert, animated: true, completion: nil)
  3659. // NotificationCenter.default.post(name: NSNotification.Name(rawValue: "isRunningStreaming"), object: nil, userInfo: dataMessage)
  3660. } else if nc.visibleViewController is EditorPersonal {
  3661. let vc = nc.visibleViewController as! EditorPersonal
  3662. if vc.fromNotification {
  3663. vc.dismiss(animated: true, completion: {
  3664. openEditor()
  3665. })
  3666. } else {
  3667. vc.navigationController?.popViewController(animated: true)
  3668. openEditor()
  3669. }
  3670. } else {
  3671. openEditor()
  3672. }
  3673. } else if UIApplication.shared.visibleViewController is EditorPersonal {
  3674. let vc = UIApplication.shared.visibleViewController as! EditorPersonal
  3675. if vc.fromNotification{
  3676. vc.dismiss(animated: true, completion: {
  3677. openEditor()
  3678. })
  3679. } else {
  3680. vc.navigationController?.popViewController(animated: true)
  3681. openEditor()
  3682. }
  3683. } else if UIApplication.shared.visibleViewController is UIAlertController {
  3684. let vc = UIApplication.shared.visibleViewController as! UIAlertController
  3685. vc.dismiss(animated: true, completion: {
  3686. openEditor()
  3687. })
  3688. } else {
  3689. openEditor()
  3690. }
  3691. } else {
  3692. func openEditor() {
  3693. let editorGroupVC = AppStoryBoard.Palio.instance.instantiateViewController(withIdentifier: "editorGroupVC") as! EditorGroup
  3694. editorGroupVC.hidesBottomBarWhenPushed = true
  3695. editorGroupVC.unique_l_pin = threadIdentifier
  3696. editorGroupVC.fromNotification = true
  3697. let navigationController = CustomNavigationController(rootViewController: editorGroupVC)
  3698. navigationController.modalPresentationStyle = .fullScreen
  3699. navigationController.navigationBar.tintColor = .white
  3700. navigationController.navigationBar.barTintColor = UIApplication.shared.visibleViewController?.traitCollection.userInterfaceStyle == .dark ? .blackDarkMode : .mainColor
  3701. navigationController.navigationBar.isTranslucent = false
  3702. navigationController.navigationBar.overrideUserInterfaceStyle = .dark
  3703. navigationController.navigationBar.barStyle = .black
  3704. let cancelButtonAttributes: [NSAttributedString.Key: Any] = [NSAttributedString.Key.foregroundColor: UIColor.white, NSAttributedString.Key.font : UIFont.systemFont(ofSize: 16)]
  3705. UIBarButtonItem.appearance().setTitleTextAttributes(cancelButtonAttributes, for: .normal)
  3706. let textAttributes = [NSAttributedString.Key.foregroundColor:UIColor.white]
  3707. navigationController.navigationBar.titleTextAttributes = textAttributes
  3708. if UIApplication.shared.visibleViewController?.navigationController != nil {
  3709. UIApplication.shared.visibleViewController?.navigationController?.present(navigationController, animated: true, completion: nil)
  3710. } else {
  3711. UIApplication.shared.visibleViewController?.present(navigationController, animated: true, completion: nil)
  3712. }
  3713. }
  3714. if UIApplication.shared.visibleViewController is UINavigationController {
  3715. let nc = UIApplication.shared.visibleViewController as! UINavigationController
  3716. if nc.visibleViewController is QmeraStreamingViewController {
  3717. let vc = nc.visibleViewController as! QmeraStreamingViewController
  3718. var alert = LibAlertController(title: "", message: "Are you sure you want to end Live Streaming, and open notification?".localized(), preferredStyle: .alert)
  3719. if !vc.isLive {
  3720. alert = LibAlertController(title: "", message: "Are you sure you want to leave Live Streaming, and open notification?".localized(), preferredStyle: .alert)
  3721. }
  3722. alert.addAction(UIAlertAction(title: "No".localized(), style: UIAlertAction.Style.default, handler: nil))
  3723. alert.addAction(UIAlertAction(title: "Yes".localized(), style: UIAlertAction.Style.default, handler: { _ in
  3724. DispatchQueue.global().async {
  3725. API.terminateBC(sBroadcasterID: vc.isLive ? nil : vc.data)
  3726. vc.sendLeft()
  3727. }
  3728. vc.dismiss(animated: true, completion: {
  3729. openEditor()
  3730. })
  3731. }))
  3732. nc.present(alert, animated: true, completion: nil)
  3733. // NotificationCenter.default.post(name: NSNotification.Name(rawValue: "isRunningStreaming"), object: nil, userInfo: dataMessage)
  3734. } else if nc.visibleViewController is SeminarViewController {
  3735. let vc = nc.visibleViewController as! SeminarViewController
  3736. var alert = LibAlertController(title: "", message: "Are you sure you want to end Seminar, and open notification?".localized(), preferredStyle: .alert)
  3737. if !vc.isLive {
  3738. alert = LibAlertController(title: "", message: "Are you sure you want to leave Seminar, and open notification?".localized(), preferredStyle: .alert)
  3739. }
  3740. alert.addAction(UIAlertAction(title: "No".localized(), style: UIAlertAction.Style.default, handler: nil))
  3741. alert.addAction(UIAlertAction(title: "Yes".localized(), style: UIAlertAction.Style.default, handler: { _ in
  3742. DispatchQueue.global().async {
  3743. API.terminateBC(sBroadcasterID: vc.isLive ? nil : vc.data)
  3744. vc.sendLeft()
  3745. }
  3746. vc.dismiss(animated: true, completion: {
  3747. openEditor()
  3748. })
  3749. }))
  3750. nc.present(alert, animated: true, completion: nil)
  3751. // NotificationCenter.default.post(name: NSNotification.Name(rawValue: "isRunningStreaming"), object: nil, userInfo: dataMessage)
  3752. } else if nc.visibleViewController is EditorGroup {
  3753. let vc = nc.visibleViewController as! EditorGroup
  3754. if vc.fromNotification {
  3755. vc.dismiss(animated: true, completion: {
  3756. openEditor()
  3757. })
  3758. } else {
  3759. vc.navigationController?.popViewController(animated: true)
  3760. openEditor()
  3761. }
  3762. } else {
  3763. openEditor()
  3764. }
  3765. } else if UIApplication.shared.visibleViewController is EditorGroup {
  3766. let vc = UIApplication.shared.visibleViewController as! EditorGroup
  3767. if vc.fromNotification {
  3768. vc.dismiss(animated: true, completion: {
  3769. openEditor()
  3770. })
  3771. } else {
  3772. vc.navigationController?.popViewController(animated: true)
  3773. openEditor()
  3774. }
  3775. } else if UIApplication.shared.visibleViewController is UIAlertController {
  3776. let vc = UIApplication.shared.visibleViewController as! UIAlertController
  3777. vc.dismiss(animated: true, completion: {
  3778. openEditor()
  3779. })
  3780. } else {
  3781. openEditor()
  3782. }
  3783. }
  3784. }
  3785. }
  3786. }
  3787. }
  3788. }
  3789. public static func addFriend(fpin: String, completion: @escaping (Bool) -> ()) {
  3790. DispatchQueue.global().async {
  3791. if let response = Nexilis.writeAndWait(message: CoreMessage_TMessageBank.getAddFriendQRCode(fpin: fpin)), response.isOk() {
  3792. completion(true)
  3793. } else {
  3794. completion(false)
  3795. }
  3796. }
  3797. }
  3798. public static func addFriendSilent(fpin: String) {
  3799. DispatchQueue.global().async {
  3800. _ = Nexilis.write(message: CoreMessage_TMessageBank.getAddFriendQRCodeSilent(fpin: fpin))
  3801. }
  3802. }
  3803. public func onReceive(message: [AnyHashable : Any?]) {
  3804. var dataMessage: [AnyHashable : Any] = [:]
  3805. dataMessage["message"] = message
  3806. NotificationCenter.default.post(name: NSNotification.Name(rawValue: Nexilis.listenerReceiveChat), object: nil, userInfo: dataMessage)
  3807. }
  3808. public func onMessage(message: TMessage) {
  3809. var dataMessage: [AnyHashable : Any] = [:]
  3810. dataMessage["message"] = message
  3811. NotificationCenter.default.post(name: NSNotification.Name(rawValue: Nexilis.listenerStatusChat), object: nil, userInfo: dataMessage)
  3812. }
  3813. public func onUpload(name: String, progress: Double) {
  3814. var dataMessage: [AnyHashable : Any] = [:]
  3815. dataMessage["name"] = name
  3816. dataMessage["progress"] = progress
  3817. NotificationCenter.default.post(name: NSNotification.Name(rawValue: "onUploadChat"), object: nil, userInfo: dataMessage)
  3818. }
  3819. public func onTyping(message: TMessage) {
  3820. var dataMessage: [AnyHashable : Any] = [:]
  3821. dataMessage["message"] = message
  3822. NotificationCenter.default.post(name: NSNotification.Name(rawValue: Nexilis.listenerTypingChat), object: nil, userInfo: dataMessage)
  3823. }
  3824. // public static func faceDetect(fd: FaceDetector?,image: UIImage, completion: ((Bool) -> ())?){
  3825. // //print("enter vision")
  3826. // let visionImage = VisionImage(image: image)
  3827. // //print("exit vision")
  3828. // var retval = false
  3829. // visionImage.orientation = image.imageOrientation
  3830. // var fd1 : FaceDetector?
  3831. // if(fd == nil){
  3832. // fd1 = FaceDetector.faceDetector()
  3833. // }
  3834. // else {
  3835. // fd1 = fd
  3836. // }
  3837. //
  3838. // // [START detect_faces]
  3839. // fd1?.process(visionImage) {faces, error in
  3840. // guard error == nil, let faces = faces, !faces.isEmpty else {
  3841. // //print("faces empty")
  3842. // completion?(false)
  3843. // return
  3844. // }
  3845. // if(faces.count > 0){
  3846. // //print("face count: \(faces.count)")
  3847. // retval = true
  3848. // }
  3849. // completion?(retval)
  3850. // }
  3851. //
  3852. // }
  3853. }
  3854. extension Nexilis: GroupDelegate {
  3855. public func onGroup(code: String, f_pin: String, groupId: String) {
  3856. var data: [AnyHashable : Any] = [:]
  3857. data["code"] = code
  3858. data["f_pin"] = f_pin
  3859. data["groupId"] = groupId
  3860. NotificationCenter.default.post(name: NSNotification.Name(rawValue: "onGroup"), object: nil, userInfo: data)
  3861. }
  3862. public func onTopic(code: String, f_pin: String, topicId: String) {
  3863. var data: [AnyHashable : Any] = [:]
  3864. data["code"] = code
  3865. data["f_pin"] = f_pin
  3866. data["topicId"] = topicId
  3867. NotificationCenter.default.post(name: NSNotification.Name(rawValue: "onTopic"), object: nil, userInfo: data)
  3868. }
  3869. public func onMember(code: String, f_pin: String, groupId: String, member: String) {
  3870. var data: [AnyHashable : Any] = [:]
  3871. data["code"] = code
  3872. data["f_pin"] = f_pin
  3873. data["groupId"] = groupId
  3874. data["member"] = member
  3875. NotificationCenter.default.post(name: NSNotification.Name(rawValue: "onMember"), object: nil, userInfo: data)
  3876. }
  3877. }
  3878. extension Nexilis: PersonInfoDelegate {
  3879. public func onUpdatePersonInfo(state: Int, message: String) {
  3880. var data: [AnyHashable : Any] = [:]
  3881. data["state"] = state
  3882. data["message"] = message
  3883. NotificationCenter.default.post(name: NSNotification.Name(rawValue: "onUpdatePersonInfo"), object: nil, userInfo: data)
  3884. }
  3885. }
  3886. extension Nexilis: QLPreviewControllerDataSource {
  3887. public func numberOfPreviewItems(in controller: QLPreviewController) -> Int {
  3888. return 1
  3889. }
  3890. public func previewController(_ controller: QLPreviewController, previewItemAt index: Int) -> QLPreviewItem {
  3891. return previewItem!
  3892. }
  3893. }
  3894. public class SelfSignedURLSessionDelegate: NSObject, URLSessionTaskDelegate, URLSessionDataDelegate {
  3895. public func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
  3896. if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust {
  3897. if let serverTrust = challenge.protectionSpace.serverTrust {
  3898. let credential = URLCredential(trust: serverTrust)
  3899. completionHandler(.useCredential, credential)
  3900. }
  3901. }
  3902. }
  3903. }