Nexilis.swift 247 KB

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