Nexilis.swift 238 KB

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