Nexilis.swift 246 KB

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