Nexilis.swift 248 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340
  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 {
  998. openApp(id: id)
  999. }
  1000. }
  1001. public static func openUrl(isBNI: Bool = false, url: String = "") {
  1002. let isChangeProfile = Utils.getSetProfile()
  1003. if !isChangeProfile {
  1004. let alert = LibAlertController(title: "Change Profile".localized(), message: "You must change your name to use this feature".localized(), preferredStyle: .alert)
  1005. alert.addAction(UIAlertAction(title: "OK".localized(), style: UIAlertAction.Style.default, handler: {(_) in
  1006. let controller = AppStoryBoard.Palio.instance.instantiateViewController(withIdentifier: "signupsignin") as! SignUpSignIn
  1007. controller.forceLogin = true
  1008. let navigationController = CustomNavigationController(rootViewController: controller)
  1009. navigationController.modalPresentationStyle = .fullScreen
  1010. navigationController.navigationBar.tintColor = .white
  1011. navigationController.navigationBar.barTintColor = UIApplication.shared.visibleViewController?.traitCollection.userInterfaceStyle == .dark ? .blackDarkMode : .mainColor
  1012. navigationController.navigationBar.isTranslucent = false
  1013. navigationController.navigationBar.overrideUserInterfaceStyle = .dark
  1014. navigationController.navigationBar.barStyle = .black
  1015. let cancelButtonAttributes: [NSAttributedString.Key: Any] = [NSAttributedString.Key.foregroundColor: UIColor.white, NSAttributedString.Key.font : UIFont.systemFont(ofSize: 16)]
  1016. UIBarButtonItem.appearance().setTitleTextAttributes(cancelButtonAttributes, for: .normal)
  1017. let textAttributes = [NSAttributedString.Key.foregroundColor:UIColor.white]
  1018. navigationController.navigationBar.titleTextAttributes = textAttributes
  1019. if UIApplication.shared.visibleViewController?.navigationController != nil {
  1020. UIApplication.shared.visibleViewController?.navigationController?.present(navigationController, animated: true, completion: nil)
  1021. } else {
  1022. UIApplication.shared.visibleViewController?.present(navigationController, animated: true, completion: nil)
  1023. }
  1024. }))
  1025. if UIApplication.shared.visibleViewController?.navigationController != nil {
  1026. UIApplication.shared.visibleViewController?.navigationController?.present(alert, animated: true, completion: nil)
  1027. } else {
  1028. UIApplication.shared.visibleViewController?.present(alert, animated: true, completion: nil)
  1029. }
  1030. return
  1031. }
  1032. let controller = BNIBookingWebView()
  1033. if !isBNI {
  1034. controller.customUrl = url
  1035. }
  1036. if UIApplication.shared.visibleViewController?.navigationController != nil {
  1037. UIApplication.shared.visibleViewController?.navigationController?.present(controller, animated: true, completion: nil)
  1038. } else {
  1039. UIApplication.shared.visibleViewController?.present(controller, animated: true, completion: nil)
  1040. }
  1041. }
  1042. public static func openApp(id: String) {
  1043. //print("openApp itms-apps://apple.com/app/\(id)")
  1044. let isChangeProfile = Utils.getSetProfile()
  1045. if !isChangeProfile {
  1046. let alert = LibAlertController(title: "Change Profile".localized(), message: "You must change your name to use this feature".localized(), preferredStyle: .alert)
  1047. alert.addAction(UIAlertAction(title: "OK".localized(), style: UIAlertAction.Style.default, handler: {(_) in
  1048. let controller = AppStoryBoard.Palio.instance.instantiateViewController(withIdentifier: "signupsignin") as! SignUpSignIn
  1049. controller.forceLogin = true
  1050. let navigationController = CustomNavigationController(rootViewController: controller)
  1051. navigationController.modalPresentationStyle = .fullScreen
  1052. navigationController.navigationBar.tintColor = .white
  1053. navigationController.navigationBar.barTintColor = UIApplication.shared.visibleViewController?.traitCollection.userInterfaceStyle == .dark ? .blackDarkMode : .mainColor
  1054. navigationController.navigationBar.isTranslucent = false
  1055. navigationController.navigationBar.overrideUserInterfaceStyle = .dark
  1056. navigationController.navigationBar.barStyle = .black
  1057. let cancelButtonAttributes: [NSAttributedString.Key: Any] = [NSAttributedString.Key.foregroundColor: UIColor.white, NSAttributedString.Key.font : UIFont.systemFont(ofSize: 16)]
  1058. UIBarButtonItem.appearance().setTitleTextAttributes(cancelButtonAttributes, for: .normal)
  1059. let textAttributes = [NSAttributedString.Key.foregroundColor:UIColor.white]
  1060. navigationController.navigationBar.titleTextAttributes = textAttributes
  1061. if UIApplication.shared.visibleViewController?.navigationController != nil {
  1062. UIApplication.shared.visibleViewController?.navigationController?.present(navigationController, animated: true, completion: nil)
  1063. } else {
  1064. UIApplication.shared.visibleViewController?.present(navigationController, animated: true, completion: nil)
  1065. }
  1066. }))
  1067. if UIApplication.shared.visibleViewController?.navigationController != nil {
  1068. UIApplication.shared.visibleViewController?.navigationController?.present(alert, animated: true, completion: nil)
  1069. } else {
  1070. UIApplication.shared.visibleViewController?.present(alert, animated: true, completion: nil)
  1071. }
  1072. return
  1073. }
  1074. if id == nil {
  1075. return
  1076. }
  1077. if let url = URL(string: "itms-apps://apple.com/app/\(id)") {
  1078. UIApplication.shared.open(url)
  1079. }
  1080. }
  1081. static func openmailAction(subject: String = "", body: String = "", to: String = "") {
  1082. let subjectEncoded = subject.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!
  1083. let bodyEncoded = body.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!
  1084. let toEmail = to
  1085. let gmailUrl = URL(string: "googlegmail://co?to=\(toEmail)&subject=\(subjectEncoded)&body=\(bodyEncoded)")!
  1086. let outlookUrl = URL(string: "ms-outlook://compose?to=\(toEmail)&subject=\(subjectEncoded)&body=\(bodyEncoded)")!
  1087. let yahooMail = URL(string: "ymail://mail/compose?to=\(toEmail)&subject=\(subjectEncoded)&body=\(bodyEncoded)")!
  1088. let sparkUrl = URL(string: "readdle-spark://compose?recipient=\(toEmail)&subject=\(subjectEncoded)&body=\(bodyEncoded)")!
  1089. let defaultUrl = URL(string: "mailto:\(toEmail)?subject=\(subjectEncoded)&body=\(bodyEncoded)")!
  1090. if UIApplication.shared.canOpenURL(gmailUrl as URL) {
  1091. openMail(gmailUrl)
  1092. } else if UIApplication.shared.canOpenURL(outlookUrl as URL) {
  1093. openMail(outlookUrl)
  1094. } else if UIApplication.shared.canOpenURL(yahooMail as URL) {
  1095. openMail(yahooMail)
  1096. } else if UIApplication.shared.canOpenURL(sparkUrl as URL) {
  1097. openMail(sparkUrl)
  1098. } else if UIApplication.shared.canOpenURL(defaultUrl as URL) {
  1099. openMail(defaultUrl)
  1100. }
  1101. }
  1102. private static func openMail(_ url: URL) {
  1103. UIApplication.shared.open(url as URL, options: [:], completionHandler: nil)
  1104. }
  1105. static var alertChangeProfile = LibAlertController()
  1106. public static func checkIsChangePerson() -> Bool {
  1107. let isChangeProfile = Utils.getSetProfile()
  1108. if !isChangeProfile {
  1109. alertChangeProfile.dismiss(animated: false)
  1110. alertChangeProfile = LibAlertController(title: "Change Profile".localized(), message: "You must change your name to use this feature".localized().localized(), preferredStyle: .alert)
  1111. alertChangeProfile.addAction(UIAlertAction(title: "Cancel".localized(), style: .destructive, handler: nil))
  1112. alertChangeProfile.addAction(UIAlertAction(title: "OK".localized(), style: UIAlertAction.Style.default, handler: {(_) in
  1113. let controller = AppStoryBoard.Palio.instance.instantiateViewController(withIdentifier: "signupsignin") as! SignUpSignIn
  1114. controller.forceLogin = true
  1115. let navigationController = CustomNavigationController(rootViewController: controller)
  1116. navigationController.modalPresentationStyle = .fullScreen
  1117. navigationController.navigationBar.tintColor = .white
  1118. navigationController.navigationBar.barTintColor = UIApplication.shared.visibleViewController?.traitCollection.userInterfaceStyle == .dark ? .blackDarkMode : .mainColor
  1119. navigationController.navigationBar.isTranslucent = false
  1120. navigationController.navigationBar.overrideUserInterfaceStyle = .dark
  1121. navigationController.navigationBar.barStyle = .black
  1122. let cancelButtonAttributes: [NSAttributedString.Key: Any] = [NSAttributedString.Key.foregroundColor: UIColor.white, NSAttributedString.Key.font : UIFont.systemFont(ofSize: 16)]
  1123. UIBarButtonItem.appearance().setTitleTextAttributes(cancelButtonAttributes, for: .normal)
  1124. let textAttributes = [NSAttributedString.Key.foregroundColor:UIColor.white]
  1125. navigationController.navigationBar.titleTextAttributes = textAttributes
  1126. let rootVC = UIApplication.shared.windows.filter {$0.isKeyWindow}.first?.rootViewController
  1127. if rootVC?.presentedViewController == nil {
  1128. rootVC?.present(navigationController, animated: true, completion: nil)
  1129. } else {
  1130. rootVC?.presentedViewController?.present(navigationController, animated: true, completion: nil)
  1131. }
  1132. }))
  1133. let rootVC = UIApplication.shared.windows.filter {$0.isKeyWindow}.first?.rootViewController
  1134. if rootVC?.presentedViewController == nil {
  1135. rootVC?.present(alertChangeProfile, animated: true, completion: nil)
  1136. } else {
  1137. rootVC?.presentedViewController?.present(alertChangeProfile, animated: true, completion: nil)
  1138. }
  1139. return false
  1140. }
  1141. return true
  1142. }
  1143. public static func showLoader() {
  1144. loadingAlert = LibAlertController(title: nil, message: "Please wait...".localized(), preferredStyle: .alert)
  1145. let loadingIndicator = UIActivityIndicatorView(frame: CGRect(x: 10, y: 5, width: 50, height: 50))
  1146. loadingIndicator.hidesWhenStopped = true
  1147. loadingIndicator.style = .medium
  1148. loadingIndicator.startAnimating()
  1149. loadingAlert.view.addSubview(loadingIndicator)
  1150. UIApplication.shared.visibleViewController?.present(loadingAlert, animated: true, completion: nil)
  1151. }
  1152. public static func hideLoader(completion: @escaping () -> ()) {
  1153. loadingAlert.dismiss(animated: true, completion: completion)
  1154. }
  1155. private static var groupWait = DispatchGroup()
  1156. private static var waitQueue = [String: TMessage]()
  1157. private static var onDispatchGroupLeave = ""
  1158. public static func writeAndWait(message: TMessage, timeout: Int = 15 * 1000) -> TMessage? {
  1159. groupWait.enter()
  1160. _ = write(message: message, timeout: timeout)
  1161. waitQueue[message.getStatus()] = message
  1162. if groupWait.wait(timeout: .now() + 15) == .timedOut {
  1163. waitQueue.removeValue(forKey: message.getStatus())
  1164. groupWait.leave()
  1165. return nil
  1166. }
  1167. return waitQueue.removeValue(forKey: message.getStatus())
  1168. }
  1169. static func incomingData(packetId: String, data: AnyObject) {
  1170. let message = TMessage()
  1171. if data is String {
  1172. let d = data as! String
  1173. guard message.unpack(data: d) else {
  1174. //print("UNKNOWN DATA STRING...", data)
  1175. if(data.hasPrefix("WB")){
  1176. let dataWB = data.components(separatedBy: "/")
  1177. if(dataWB[1] == "1"){
  1178. let x = dataWB[2]
  1179. let y = dataWB[3]
  1180. let w = dataWB[4]
  1181. let h = dataWB[5]
  1182. let fc = dataWB[6]
  1183. let sw = dataWB[7]
  1184. let xo = dataWB[8]
  1185. let yo = dataWB[9]
  1186. if(Nexilis.getWhiteboardDelegate() != nil){
  1187. Nexilis.getWhiteboardDelegate()!.draw(x: x, y: y, w: w, h: h, fc: fc, sw: sw, xo: xo, yo: yo, data: "")
  1188. }
  1189. } else if(dataWB[1] == "3") {
  1190. if(Nexilis.getWhiteboardDelegate() != nil){
  1191. Nexilis.getWhiteboardDelegate()!.clear()
  1192. }
  1193. } else if(dataWB[1] == "2"){
  1194. if(Nexilis.getWhiteboardReceiver() != nil){
  1195. Nexilis.getWhiteboardReceiver()!.incomingWB(roomId: dataWB[2])
  1196. }
  1197. } else if(dataWB[1] == "22"){
  1198. } else if(dataWB[1] == "88"){
  1199. if(Nexilis.getWhiteboardReceiver() != nil){
  1200. Nexilis.getWhiteboardReceiver()!.cancel(roomId: dataWB[2])
  1201. }
  1202. }
  1203. }
  1204. return
  1205. }
  1206. } else if data is [UInt8] {
  1207. let d = data as! [UInt8]
  1208. guard message.unpack(bytes_data: d) else {
  1209. //print("UNKNOWN DATA BYTES...", data)
  1210. return
  1211. }
  1212. }
  1213. message.mBodies[CoreMessage_TMessageKey.PACKET_ID] = packetId
  1214. if let _ = waitQueue[message.getStatus()] {
  1215. //print("MESSAGE INCOMING DATA \(message.toLogString())")
  1216. if message.mBodies.keys.contains(CoreMessage_TMessageKey.ERRCOD) {
  1217. if onDispatchGroupLeave != message.getStatus() {
  1218. onDispatchGroupLeave = message.getStatus()
  1219. //print("LEAVE GROUP INCOMING DATA")
  1220. waitQueue[message.getStatus()] = message
  1221. groupWait.leave()
  1222. return
  1223. }
  1224. }
  1225. }
  1226. IncomingThread.default.addQueue(message: message)
  1227. }
  1228. static func saveMessage(message: TMessage, withStatus: Bool = true, fromAPNS: Bool = false) {
  1229. // print("save message \(message.toLogString())")
  1230. guard let me = User.getMyPin() else {
  1231. return
  1232. }
  1233. let message_id = message.getBody(key : CoreMessage_TMessageKey.MESSAGE_ID, default_value : "")
  1234. guard !message_id.isEmpty else {
  1235. return
  1236. }
  1237. let f_pin = message.getBody(key : CoreMessage_TMessageKey.F_PIN, default_value : "")
  1238. guard !f_pin.isEmpty else {
  1239. return
  1240. }
  1241. Database.shared.database?.inTransaction({ (fmdb, rollback) in
  1242. do {
  1243. var messageExist = false
  1244. if let cursor = Database.shared.getRecords(fmdb: fmdb, query: "select message_id from MESSAGE where message_id = '\(message_id)'"), cursor.next() {
  1245. messageExist = true
  1246. cursor.close()
  1247. }
  1248. let l_pin = message.getBody(key : CoreMessage_TMessageKey.L_PIN, default_value : "")
  1249. let scope = message.getBody(key : CoreMessage_TMessageKey.MESSAGE_SCOPE_ID, default_value : "3")
  1250. let status = message.getBody(key : CoreMessage_TMessageKey.STATUS, default_value : "")
  1251. let chat_id = message.getBody(key : CoreMessage_TMessageKey.CHAT_ID, default_value : "")
  1252. let broadcast_flag = message.getBody(key: CoreMessage_TMessageKey.BROADCAST_FLAG, default_value: "0")
  1253. let is_call_center = message.getBody(key: CoreMessage_TMessageKey.IS_CALL_CENTER, default_value: "0")
  1254. let call_center_id = message.getBody(key: CoreMessage_TMessageKey.CALL_CENTER_ID, default_value: "")
  1255. let last_edited = message.getBodyAsLong(key: CoreMessage_TMessageKey.LAST_EDIT, default_value: 0)
  1256. let is_secret = message.getBodyAsLong(key: CoreMessage_TMessageKey.IS_SECRET, default_value: 0)
  1257. let is_delete_retention = message.getBodyAsLong(key: CoreMessage_TMessageKey.IS_DELETED_RETENTION, default_value: 0)
  1258. let is_forwarded_message = message.getBodyAsLong(key: CoreMessage_TMessageKey.IS_FORWARDED_MESSAGE, default_value: 0)
  1259. let opposite_pin = message.getBody(key: CoreMessage_TMessageKey.OPPOSITE_PIN, default_value: "")
  1260. //print("prepare save db")
  1261. do {
  1262. _ = try Database.shared.insertRecord(fmdb: fmdb, table: "MESSAGE", cvalues: [
  1263. "message_id" : message_id,
  1264. "f_pin" : f_pin,
  1265. "f_display_name" : message.getBody(key : CoreMessage_TMessageKey.F_DISPLAY_NAME, default_value : ""),
  1266. "l_pin" : l_pin,
  1267. "l_user_id" : message.getBody(key : CoreMessage_TMessageKey.L_USER_ID, default_value : ""),
  1268. "message_scope_id" : scope,
  1269. "server_date" : message.getBody(key: CoreMessage_TMessageKey.SERVER_DATE, default_value : String(Date().currentTimeMillis())),
  1270. "status" : status,
  1271. "message_text" : message.getBody(key : CoreMessage_TMessageKey.MESSAGE_TEXT, default_value : "").toNormalString(),
  1272. "audio_id" : message.getBody(key : CoreMessage_TMessageKey.AUDIO_ID, default_value : ""),
  1273. "video_id" : message.getBody(key : CoreMessage_TMessageKey.VIDEO_ID, default_value : ""),
  1274. "image_id" : message.getBody(key : CoreMessage_TMessageKey.IMAGE_ID, default_value : ""),
  1275. "file_id" : message.getBody(key : CoreMessage_TMessageKey.FILE_ID, default_value : ""),
  1276. "gif_id" : message.getBody(key : CoreMessage_TMessageKey.GIF_ID, default_value : ""),
  1277. "thumb_id" : message.getBody(key : CoreMessage_TMessageKey.THUMB_ID, default_value : ""),
  1278. "opposite_pin" : message.getBody(key : CoreMessage_TMessageKey.OPPOSITE_PIN, default_value : ""),
  1279. "format" : message.getBody(key : CoreMessage_TMessageKey.FORMAT, default_value : ""),
  1280. "blog_id" : message.getBody(key : CoreMessage_TMessageKey.BLOG_ID, default_value : ""),
  1281. "read_receipts" : message.getBody(key: CoreMessage_TMessageKey.READ_RECEIPTS, default_value: "0"),
  1282. "chat_id" : chat_id,
  1283. "account_type" : message.getBody(key : CoreMessage_TMessageKey.BUSINESS_CATEGORY, default_value : "1"),
  1284. "credential" : message.getBody(key : CoreMessage_TMessageKey.CREDENTIAL, default_value : ""),
  1285. "reff_id" : message.getBody(key : CoreMessage_TMessageKey.REF_ID, default_value : ""),
  1286. "message_large_text" : message.getBody(key : CoreMessage_TMessageKey.BODY, default_value : "").toNormalString(),
  1287. "attachment_flag" : message.getBody(key: CoreMessage_TMessageKey.ATTACHMENT_FLAG, default_value: "0"),
  1288. "local_timestamp" : message.getBody(key: CoreMessage_TMessageKey.LOCAL_TIMESTAMP, default_value : String(Date().currentTimeMillis())),
  1289. "broadcast_flag" : broadcast_flag,
  1290. "is_call_center" : is_call_center,
  1291. "call_center_id" : call_center_id,
  1292. "last_edited" : last_edited,
  1293. "is_secret" : is_secret,
  1294. "is_deleted_retention" : is_delete_retention,
  1295. "is_forwarded_message" : is_forwarded_message
  1296. ], replace: true)
  1297. } catch {
  1298. rollback.pointee = true
  1299. //print(error)
  1300. }
  1301. if withStatus {
  1302. do {
  1303. if scope == "4" {
  1304. for pin in getGroupMembers(fmdb: fmdb, l_pin: l_pin) {
  1305. if f_pin == pin { continue }
  1306. _ = try Database.shared.insertRecord(fmdb: fmdb, table: "MESSAGE_STATUS", cvalues: [
  1307. "message_id" : message_id,
  1308. "status" : status,
  1309. "f_pin" : pin,
  1310. "last_update" : Date().currentTimeMillis()
  1311. ], replace: true)
  1312. }
  1313. } else {
  1314. _ = try Database.shared.insertRecord(fmdb: fmdb, table: "MESSAGE_STATUS", cvalues: [
  1315. "message_id" : message_id,
  1316. "status" : status,
  1317. "f_pin" : l_pin,
  1318. "last_update" : Date().currentTimeMillis()
  1319. ], replace: true)
  1320. }
  1321. } catch {
  1322. rollback.pointee = true
  1323. //print(error)
  1324. }
  1325. }
  1326. var pin = opposite_pin
  1327. if pin.isEmpty {
  1328. if scope == "4" {
  1329. pin = chat_id.isEmpty ? l_pin : chat_id
  1330. } else {
  1331. pin = f_pin
  1332. }
  1333. }
  1334. if pin == me {
  1335. pin = l_pin
  1336. }
  1337. var counter : Int? = nil
  1338. if !withStatus {
  1339. if let cursor = Database.shared.getRecords(fmdb: fmdb, query: "select counter from MESSAGE_SUMMARY where l_pin = '\(pin)'"), cursor.next() {
  1340. counter = Int(cursor.int(forColumnIndex: 0))
  1341. if last_edited == 0 && !messageExist {
  1342. counter! += 1
  1343. }
  1344. cursor.close()
  1345. //print("select db message summary")
  1346. }
  1347. if counter == nil {
  1348. counter = 1
  1349. //print("set counter message summary")
  1350. }
  1351. }
  1352. if is_call_center == "0" {
  1353. do {
  1354. 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"
  1355. if scope == "4" {
  1356. 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"
  1357. }
  1358. var messageId = ""
  1359. if let cursorData = Database.shared.getRecords(fmdb: fmdb, query: queryGetLastMessageId), cursorData.next() {
  1360. messageId = cursorData.string(forColumnIndex: 0) ?? ""
  1361. cursorData.close()
  1362. }
  1363. if !messageId.isEmpty {
  1364. _ = try Database.shared.insertRecord(fmdb: fmdb, table: "MESSAGE_SUMMARY", cvalues: [
  1365. "l_pin" : pin,
  1366. "message_id" : messageId,
  1367. "counter" : counter ?? 0
  1368. ], replace: true)
  1369. }
  1370. } catch {
  1371. rollback.pointee = true
  1372. //print(error)
  1373. }
  1374. }
  1375. if !withStatus && !fromAPNS && (!messageExist || last_edited != 0) {
  1376. DispatchQueue.main.async {
  1377. if let delegate = Nexilis.shared.messageDelegate, Utils.getSetProfile() {
  1378. message.mBodies[CoreMessage_TMessageKey.MESSAGE_TEXT] = message.getBody(key : CoreMessage_TMessageKey.MESSAGE_TEXT, default_value : "").toNormalString()
  1379. delegate.onReceive(message: message)
  1380. }
  1381. }
  1382. }
  1383. //print("insert db message summary \(message_id)")
  1384. } catch {
  1385. rollback.pointee = true
  1386. print("Access database error: \(error.localizedDescription)")
  1387. }
  1388. })
  1389. }
  1390. public static func saveMessageBot(textMessage: String, blog_id: String, attachment_type:String)->Void{
  1391. guard let me = User.getMyPin() else {
  1392. return
  1393. }
  1394. var user_id:String? = ""
  1395. let message_id = me + CoreMessage_TMessageUtil.getTID()
  1396. Database.shared.database?.inTransaction({ (fmdb, rollback) in
  1397. do {
  1398. if let cursor = Database.shared.getRecords(fmdb: fmdb, query: "select user_id from BUDDY where f_pin = '\(me)'"), cursor.next() {
  1399. user_id = cursor.string(forColumnIndex: 0)
  1400. cursor.close()
  1401. }
  1402. } catch {
  1403. rollback.pointee = true
  1404. print("Access database error: \(error.localizedDescription)")
  1405. }
  1406. })
  1407. Database.shared.database?.inTransaction({ (fmdb, rollback) in
  1408. do {
  1409. _ = try Database.shared.insertRecord(fmdb: fmdb, table: "MESSAGE", cvalues: [
  1410. "message_id" : message_id ,
  1411. "f_pin" : "-999",
  1412. "f_display_name" : "Bot",
  1413. "l_pin" : me,
  1414. "l_user_id" : String(user_id!),
  1415. "message_scope_id" : "3",
  1416. "server_date" : String(Date().currentTimeMillis()),
  1417. "status" : "3",
  1418. "message_text" : textMessage,
  1419. "audio_id" : "",
  1420. "video_id" : "",
  1421. "image_id" : "",
  1422. "file_id" : "",
  1423. "thumb_id" : "",
  1424. "opposite_pin" : "",
  1425. "format" : "",
  1426. "blog_id" : blog_id,
  1427. "read_receipts" : "0",
  1428. "chat_id" : "",
  1429. "account_type" : "1",
  1430. "credential" :"",
  1431. "reff_id" : "",
  1432. "message_large_text" : "",
  1433. "attachment_flag" : attachment_type,
  1434. "local_timestamp" : String(Date().currentTimeMillis())
  1435. ], replace: true)
  1436. } catch {
  1437. rollback.pointee = true
  1438. print("Access database error: \(error.localizedDescription)")
  1439. }
  1440. })
  1441. let pin = "-999"
  1442. var counter : Int? = nil
  1443. Database.shared.database?.inTransaction({ (fmdb, rollback) in
  1444. do {
  1445. if let cursor = Database.shared.getRecords(fmdb: fmdb, query: "select counter from MESSAGE_SUMMARY where l_pin = '\(pin)'"), cursor.next() {
  1446. counter = Int(cursor.int(forColumnIndex: 0))
  1447. counter! += 1
  1448. cursor.close()
  1449. //print("select db message summary")
  1450. }
  1451. } catch {
  1452. rollback.pointee = true
  1453. print("Access database error: \(error.localizedDescription)")
  1454. }
  1455. })
  1456. if counter == nil {
  1457. counter = 1
  1458. //print("set counter message summary")
  1459. }
  1460. Database.shared.database?.inTransaction({ (fmdb, rollback) in
  1461. do {
  1462. _ = try Database.shared.insertRecord(fmdb: fmdb, table: "MESSAGE_SUMMARY", cvalues: [
  1463. "l_pin" : pin,
  1464. "message_id" : message_id,
  1465. "counter" : counter!
  1466. ], replace: true)
  1467. } catch {
  1468. rollback.pointee = true
  1469. print("Access database error: \(error.localizedDescription)")
  1470. }
  1471. })
  1472. //print("insert db message summary \(message_id)")
  1473. }
  1474. static func updateMessageStatus(message: TMessage) -> Void {
  1475. let message_id = message.getBody(key : CoreMessage_TMessageKey.MESSAGE_ID, default_value : "")
  1476. guard !message_id.isEmpty else {
  1477. return
  1478. }
  1479. let status = message.getBody(key : CoreMessage_TMessageKey.STATUS, default_value : "")
  1480. let latitude = message.getBody(key : CoreMessage_TMessageKey.LATITUDE, default_value : "")
  1481. let longitude = message.getBody(key : CoreMessage_TMessageKey.LONGITUDE, default_value : "")
  1482. let desc = message.getBody(key : CoreMessage_TMessageKey.DESCRIPTION, default_value : "")
  1483. guard !status.isEmpty else {
  1484. return
  1485. }
  1486. let l_pin = message.getBody(key : CoreMessage_TMessageKey.L_PIN, default_value : "")
  1487. guard !l_pin.isEmpty else {
  1488. return
  1489. }
  1490. Database.shared.database?.inTransaction({ (fmdb, rollback) in
  1491. do {
  1492. if message_id.starts(with: "-1") || message_id.starts(with: "-2") {
  1493. for s in message_id.split(separator: ",") {
  1494. let t = s.trimmingCharacters(in: .whitespaces)
  1495. if t == "-1" || t == "-2" {
  1496. continue
  1497. }
  1498. if let cursorStatus = Database.shared.getRecords(fmdb: fmdb, query: "SELECT status FROM MESSAGE_STATUS where message_id = '\(t)'"), cursorStatus.next() {
  1499. let lastStatus = cursorStatus.int(forColumnIndex: 0)
  1500. if lastStatus < Int(status)! {
  1501. if status == "3" {
  1502. _ = Database.shared.updateRecord(fmdb: fmdb, table: "MESSAGE_STATUS", cvalues: [
  1503. "status" : status,
  1504. "longitude" : longitude,
  1505. "latitude" : latitude,
  1506. "location" : desc,
  1507. "time_delivered" : String(Date().currentTimeMillis()),
  1508. "last_update" : String(Date().currentTimeMillis())], _where: "message_id = '\(t)' and f_pin = '\(l_pin)'")
  1509. } else if status == "4" {
  1510. _ = Database.shared.updateRecord(fmdb: fmdb, table: "MESSAGE_STATUS", cvalues: [
  1511. "status" : status,
  1512. "time_read" : String(Date().currentTimeMillis()),
  1513. "longitude" : longitude,
  1514. "latitude" : latitude,
  1515. "location" : desc,
  1516. "last_update" : String(Date().currentTimeMillis())], _where: "message_id = '\(t)' and f_pin = '\(l_pin)'")
  1517. } else if status == "8" {
  1518. _ = Database.shared.updateRecord(fmdb: fmdb, table: "MESSAGE_STATUS", cvalues: [
  1519. "status" : status,
  1520. "time_ack" : String(Date().currentTimeMillis()),
  1521. "longitude" : longitude,
  1522. "latitude" : latitude,
  1523. "location" : desc,
  1524. "last_update" : String(Date().currentTimeMillis())], _where: "message_id = '\(t)' and f_pin = '\(l_pin)'")
  1525. } else {
  1526. _ = Database.shared.updateRecord(fmdb: fmdb, table: "MESSAGE_STATUS", cvalues: [
  1527. "status" : status,
  1528. "last_update" : String(Date().currentTimeMillis())], _where: "message_id = '\(t)' and f_pin = '\(l_pin)'")
  1529. }
  1530. }
  1531. cursorStatus.close()
  1532. }
  1533. }
  1534. } else {
  1535. if let cursorStatus = Database.shared.getRecords(fmdb: fmdb, query: "SELECT status FROM MESSAGE_STATUS where message_id = '\(message_id)'"), cursorStatus.next() {
  1536. let lastStatus = cursorStatus.int(forColumnIndex: 0)
  1537. if lastStatus < Int(status)! {
  1538. if status == "3" {
  1539. _ = Database.shared.updateRecord(fmdb: fmdb, table: "MESSAGE_STATUS", cvalues: [
  1540. "status" : status,
  1541. "time_delivered" : String(Date().currentTimeMillis()),
  1542. "longitude" : longitude,
  1543. "latitude" : latitude,
  1544. "location" : desc,
  1545. "last_update" : String(Date().currentTimeMillis())], _where: "message_id = '\(message_id)' and f_pin = '\(l_pin)'")
  1546. } else if status == "4" {
  1547. _ = Database.shared.updateRecord(fmdb: fmdb, table: "MESSAGE_STATUS", cvalues: [
  1548. "status" : status,
  1549. "time_read" : String(Date().currentTimeMillis()),
  1550. "longitude" : longitude,
  1551. "latitude" : latitude,
  1552. "location" : desc,
  1553. "last_update" : String(Date().currentTimeMillis())], _where: "message_id = '\(message_id)' and f_pin = '\(l_pin)'")
  1554. } else if status == "8" {
  1555. _ = Database.shared.updateRecord(fmdb: fmdb, table: "MESSAGE_STATUS", cvalues: [
  1556. "status" : status,
  1557. "time_ack" : String(Date().currentTimeMillis()),
  1558. "longitude" : longitude,
  1559. "latitude" : latitude,
  1560. "location" : desc,
  1561. "last_update" : String(Date().currentTimeMillis())], _where: "message_id = '\(message_id)' and f_pin = '\(l_pin)'")
  1562. } else {
  1563. _ = Database.shared.updateRecord(fmdb: fmdb, table: "MESSAGE_STATUS", cvalues: [
  1564. "status" : status,
  1565. "longitude" : longitude,
  1566. "latitude" : latitude,
  1567. "location" : desc,
  1568. "last_update" : String(Date().currentTimeMillis())], _where: "message_id = '\(message_id)' and f_pin = '\(l_pin)'")
  1569. }
  1570. }
  1571. cursorStatus.close()
  1572. }
  1573. }
  1574. } catch {
  1575. rollback.pointee = true
  1576. print("Access database error: \(error.localizedDescription)")
  1577. }
  1578. })
  1579. }
  1580. static func getGroupMembers(fmdb: FMDatabase, l_pin: String) -> [String] {
  1581. var result = [String]()
  1582. if let cursor = Database.shared.getRecords(fmdb: fmdb, query: "select f_pin from GROUPZ_MEMBER where group_id = '\(l_pin)'") {
  1583. while cursor.next() {
  1584. if let value = cursor.string(forColumnIndex: 0) {
  1585. result.append(value)
  1586. }
  1587. }
  1588. cursor.close()
  1589. }
  1590. return result
  1591. }
  1592. static func getVideoThumbnail(name: String, completion: @escaping (Bool)->()) {
  1593. DispatchQueue.global().async {
  1594. do {
  1595. let fileManager = FileManager.default
  1596. let documentDir = try fileManager.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
  1597. let fileDir = documentDir.appendingPathComponent(name)
  1598. let path = fileDir.path
  1599. if FileManager.default.fileExists(atPath: path) {
  1600. let asset = AVAsset(url: URL(fileURLWithPath: path))
  1601. let avAssetImageGenerator = AVAssetImageGenerator(asset: asset)
  1602. avAssetImageGenerator.appliesPreferredTrackTransform = true
  1603. let thumnailTime = CMTimeMake(value: 2, timescale: 1)
  1604. let thumbImage = UIImage(cgImage: try avAssetImageGenerator.copyCGImage(at: thumnailTime, actualTime: nil))
  1605. guard let data = thumbImage.jpegData(compressionQuality: 1.0) else {
  1606. completion(false)
  1607. return
  1608. }
  1609. let thumbFileDir = documentDir.appendingPathComponent("THUMB_" + name)
  1610. try data.write(to: thumbFileDir)
  1611. completion(true)
  1612. } else {
  1613. completion(false)
  1614. }
  1615. } catch {
  1616. //print(error)
  1617. }
  1618. }
  1619. }
  1620. static func resizedImage(at url: URL, for size: CGSize) -> UIImage? {
  1621. var image : UIImage?
  1622. if FileManager.default.fileExists(atPath: url.path){
  1623. image = UIImage(contentsOfFile: url.path)
  1624. }
  1625. else if FileEncryption.shared.isSecureExists(filename: url.lastPathComponent) {
  1626. do {
  1627. if let imageData = try FileEncryption.shared.readSecure(filename: url.lastPathComponent) {
  1628. image = UIImage(data: imageData)
  1629. }
  1630. }
  1631. catch {
  1632. }
  1633. }
  1634. if image == nil {
  1635. return nil
  1636. }
  1637. let renderer = UIGraphicsImageRenderer(size: size)
  1638. return renderer.image { (context) in
  1639. image!.draw(in: CGRect(origin: .zero, size: size))
  1640. }
  1641. }
  1642. static func initFollowing() -> Void {
  1643. if let me = User.getMyPin() {
  1644. if let response = Nexilis.writeSync(message: CoreMessage_TMessageBank.getListFollowing(l_pin: me)) {
  1645. let data = response.getBody(key: CoreMessage_TMessageKey.DATA)
  1646. if !data.isEmpty {
  1647. if let jsonArray = try! JSONSerialization.jsonObject(with: data.data(using: String.Encoding.utf8)!, options: JSONSerialization.ReadingOptions()) as? [AnyObject] {
  1648. Database.shared.database?.inTransaction({ (fmdb, rollback) in
  1649. do {
  1650. for json in jsonArray {
  1651. _ = try Database.shared.insertRecord(fmdb: fmdb, table: "FOLLOW", cvalues: [
  1652. "f_pin" : CoreMessage_TMessageUtil.getString(json: json, key: "pin")
  1653. ], replace: true)
  1654. }
  1655. } catch {
  1656. rollback.pointee = true
  1657. print("Access database error: \(error.localizedDescription)")
  1658. }
  1659. })
  1660. }
  1661. }
  1662. }
  1663. }
  1664. }
  1665. // do {
  1666. // _ = try Database.shared.insertRecord(fmdb: fmdb, table: "CALL_CENTER_HISTORY", cvalues: [
  1667. // "type" : "1",
  1668. // "title" : displayName,
  1669. // "time" : timeStart,
  1670. // "f_pin" : f_pin,
  1671. // "data" : dataCC,
  1672. // "time_end" : date,
  1673. // "complaint_id" : complaint_id.isEmpty ? "C\(date)" : complaint_id,
  1674. // "members" : "",
  1675. // "requester": ""
  1676. // ], replace: true)
  1677. // _ = try Database.shared.insertRecord(fmdb: fmdb, table: "PREFS", cvalues: [
  1678. // "key" : "CC:\(f_pin)",
  1679. // "value" : status,
  1680. // ], replace: true)
  1681. // ret = true
  1682. // } catch {
  1683. // rollback.pointee = true
  1684. // //print(error)
  1685. // }
  1686. private static var uploadQueue = DispatchQueue(label: "UPLOAD_DICT", attributes: .concurrent)
  1687. private static var UPLOAD_DICT = [String: Network]()
  1688. static func removeUploadFile(forKey: String) -> Network? {
  1689. var _result: Network? = nil
  1690. uploadQueue.sync {
  1691. _result = self.UPLOAD_DICT.removeValue(forKey: forKey)
  1692. }
  1693. return _result
  1694. }
  1695. static func putUploadFile(forKey: String, uploader: Network) {
  1696. uploadQueue.async (flags: .barrier) {
  1697. self.UPLOAD_DICT[forKey] = uploader
  1698. }
  1699. }
  1700. static func getUploadFile(forKey: String) -> Network? {
  1701. var _result: Network? = nil
  1702. uploadQueue.sync {
  1703. _result = self.UPLOAD_DICT[forKey]
  1704. }
  1705. return _result
  1706. }
  1707. private static var downloadQueue = DispatchQueue(label: "DOWNLOAD_DICT", attributes: .concurrent)
  1708. private static var DOWNLOAD_DICT = [String:Download]()
  1709. static func addDownload(forKey : String, download: Download){
  1710. downloadQueue.async (flags: .barrier) {
  1711. self.DOWNLOAD_DICT[forKey] = download
  1712. }
  1713. }
  1714. static func getDownload(forKey: String) -> Download? {
  1715. var _result: Download? = nil
  1716. downloadQueue.sync {
  1717. _result = self.DOWNLOAD_DICT[forKey]
  1718. }
  1719. return _result
  1720. }
  1721. static func removeDownload(forKey: String) -> Download? {
  1722. var _result: Download? = nil
  1723. downloadQueue.sync {
  1724. _result = self.DOWNLOAD_DICT.removeValue(forKey: forKey)
  1725. }
  1726. return _result
  1727. }
  1728. static func writeImageToFile(data: Data, fileName: String){
  1729. guard let directory = FileManager.default.urls(for: .picturesDirectory, in: .userDomainMask).last else {
  1730. return
  1731. }
  1732. let fileURL = directory.appendingPathComponent("\(fileName)")
  1733. if FileManager.default.fileExists(atPath: fileURL.path) {
  1734. if let fileHandle = FileHandle(forWritingAtPath: fileURL.path) {
  1735. fileHandle.seekToEndOfFile()
  1736. fileHandle.write(data)
  1737. fileHandle.closeFile()
  1738. } else {
  1739. //print("Can't open file to write")
  1740. }
  1741. } else {
  1742. do {
  1743. try data.write(to: fileURL, options: .atomic)
  1744. } catch {
  1745. //print("Unable to write in new file")
  1746. }
  1747. }
  1748. }
  1749. static func writeVideoToFile(data: Data, fileName: String){
  1750. guard let directory = FileManager.default.urls(for: .moviesDirectory, in: .userDomainMask).last else {
  1751. return
  1752. }
  1753. let fileURL = directory.appendingPathComponent("\(fileName)")
  1754. if FileManager.default.fileExists(atPath: fileURL.path) {
  1755. if let fileHandle = FileHandle(forWritingAtPath: fileURL.path) {
  1756. fileHandle.seekToEndOfFile()
  1757. fileHandle.write(data)
  1758. fileHandle.closeFile()
  1759. } else {
  1760. //print("Can't open file to write")
  1761. }
  1762. } else {
  1763. do {
  1764. try data.write(to: fileURL, options: .atomic)
  1765. } catch {
  1766. //print("Unable to write in new file")
  1767. }
  1768. }
  1769. }
  1770. static func writeDocumentsToFile(data: Data, fileName: String){
  1771. guard let directory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).last else {
  1772. return
  1773. }
  1774. let fileURL = directory.appendingPathComponent("\(fileName)")
  1775. if FileManager.default.fileExists(atPath: fileURL.path) {
  1776. if let fileHandle = FileHandle(forWritingAtPath: fileURL.path) {
  1777. fileHandle.seekToEndOfFile()
  1778. fileHandle.write(data)
  1779. fileHandle.closeFile()
  1780. } else {
  1781. //print("Can't open file to write")
  1782. }
  1783. } else {
  1784. do {
  1785. try data.write(to: fileURL, options: .atomic)
  1786. } catch {
  1787. //print("Unable to write in new file")
  1788. }
  1789. }
  1790. }
  1791. public static func checkMicPermission() -> Bool {
  1792. var permissionCheck: Bool = false
  1793. switch AVAudioSession.sharedInstance().recordPermission {
  1794. case .granted:
  1795. permissionCheck = true
  1796. case .denied:
  1797. permissionCheck = false
  1798. case .undetermined:
  1799. Nexilis.dispatch = DispatchGroup()
  1800. Nexilis.dispatch?.enter()
  1801. AVAudioSession.sharedInstance().requestRecordPermission({ (granted) in
  1802. if granted {
  1803. permissionCheck = true
  1804. } else {
  1805. permissionCheck = false
  1806. }
  1807. if let dispatch = Nexilis.dispatch {
  1808. dispatch.leave()
  1809. }
  1810. })
  1811. Nexilis.dispatch?.wait()
  1812. Nexilis.dispatch = nil
  1813. default:
  1814. break
  1815. }
  1816. return permissionCheck
  1817. }
  1818. public static func checkCameraPermission() -> Int {
  1819. var permissionCheck: Int = -1
  1820. if AVCaptureDevice.authorizationStatus(for: .video) == .authorized {
  1821. permissionCheck = 1
  1822. } else if AVCaptureDevice.authorizationStatus(for: .video) == .denied {
  1823. permissionCheck = 0
  1824. } else {
  1825. AVCaptureDevice.requestAccess(for: .video, completionHandler: { (granted: Bool) -> Void in
  1826. })
  1827. }
  1828. return permissionCheck
  1829. }
  1830. // public static func startTimer(){
  1831. // broadcastTimer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true, block: {_ in
  1832. // if(!openBroadcast && !broadcastList.isEmpty){
  1833. // openBroadcast = true
  1834. // let m = broadcastList.removeFirst()
  1835. // //print("broadcast show: \(m)")
  1836. // DispatchQueue.main.async {
  1837. // Nexilis.shared.showBroadcastMessage(m: m)
  1838. // }
  1839. // }
  1840. // })
  1841. // }
  1842. public static func debugBroadcast(){
  1843. if(Utils.getDebugBC() != nil) {
  1844. let m = Utils.getDebugBC()
  1845. Nexilis.shared.showBroadcastMessage(m: m!)
  1846. }
  1847. }
  1848. /*
  1849. * Delegate
  1850. */
  1851. weak open var loginDelegate: LoginDelegate?
  1852. weak open var messageDelegate: MessageDelegate?
  1853. weak open var groupDelegate: GroupDelegate?
  1854. weak open var callDelegate: CallDelegate?
  1855. weak open var streamingDelagate: LiveStreamingDelegate?
  1856. weak open var seminarDelegate: SeminarDelegate?
  1857. weak open var personInfoDelegate: PersonInfoDelegate?
  1858. weak open var screenSharingDelegate: ScreenSharingDelegate?
  1859. weak open var commentDelegate: CommentDelegate?
  1860. weak open var uploadDelegate: UploadDelegate?
  1861. weak open var timelineDelegate: TimelineDelegate?
  1862. weak open var connectionDelegate: ConnectionDelegate?
  1863. var floating: FloatingNotificationBanner!
  1864. var stateUnfriend = ""
  1865. }
  1866. struct LibFontName {
  1867. static let regular = "Poppins-Regular"
  1868. static let bold = "Poppins-SemiBold"
  1869. static let italic = "Poppins-Italic"
  1870. static let medium = "Poppins-Medium"
  1871. static let boldItalic = "Poppins-SemiBoldItalic"
  1872. }
  1873. extension UIFontDescriptor.AttributeName {
  1874. static let nsctFontUIUsage = UIFontDescriptor.AttributeName(rawValue: "NSCTFontUIUsageAttribute")
  1875. }
  1876. extension UIFont {
  1877. static var isOverrided: Bool = false
  1878. static let FONT_SELECT = 0
  1879. @objc class func libSystemFont(ofSize size: CGFloat) -> UIFont? {
  1880. if UIFont(name: LibFontName.regular, size: size) == nil {
  1881. jbs_registerFont(withFilenameString: LibFontName.regular)
  1882. }
  1883. return UIFont(name: LibFontName.regular, size: size)
  1884. }
  1885. @objc class func libSystemFontWeight(ofSize size: CGFloat, weight: UIFont.Weight) -> UIFont? {
  1886. if weight == .medium {
  1887. if UIFont(name: LibFontName.medium, size: size) == nil {
  1888. jbs_registerFont(withFilenameString: LibFontName.medium)
  1889. }
  1890. return UIFont(name: LibFontName.medium, size: size)
  1891. } else if weight == .semibold {
  1892. if UIFont(name: LibFontName.boldItalic, size: size) == nil {
  1893. jbs_registerFont(withFilenameString: LibFontName.boldItalic)
  1894. }
  1895. return UIFont(name: LibFontName.boldItalic, size: size)
  1896. }
  1897. return UIFont(name: LibFontName.regular, size: size)
  1898. }
  1899. @objc class func libBoldSystemFont(ofSize size: CGFloat) -> UIFont? {
  1900. if UIFont(name: LibFontName.bold, size: size) == nil {
  1901. jbs_registerFont(withFilenameString: LibFontName.bold)
  1902. }
  1903. return UIFont(name: LibFontName.bold, size: size)
  1904. }
  1905. @objc class func libItalicSystemFont(ofSize size: CGFloat) -> UIFont? {
  1906. if UIFont(name: LibFontName.italic, size: size) == nil {
  1907. jbs_registerFont(withFilenameString: LibFontName.italic)
  1908. }
  1909. return UIFont(name: LibFontName.italic, size: size)
  1910. }
  1911. @objc convenience init(myCoder aDecoder: NSCoder) {
  1912. guard
  1913. let fontDescriptor = aDecoder.decodeObject(forKey: "UIFontDescriptor") as? UIFontDescriptor,
  1914. let fontAttribute = fontDescriptor.fontAttributes[.nsctFontUIUsage] as? String else {
  1915. self.init(myCoder: aDecoder)
  1916. return
  1917. }
  1918. var fontName = ""
  1919. switch fontAttribute {
  1920. case "CTFontRegularUsage":
  1921. fontName = LibFontName.regular
  1922. case "CTFontEmphasizedUsage", "CTFontBoldUsage":
  1923. fontName = LibFontName.bold
  1924. case "CTFontObliqueUsage":
  1925. fontName = LibFontName.italic
  1926. default:
  1927. fontName = LibFontName.regular
  1928. }
  1929. self.init(name: fontName, size: fontDescriptor.pointSize)!
  1930. }
  1931. class func libOverrideInitialize() {
  1932. guard self == UIFont.self, !isOverrided, FONT_SELECT == 0 else { return }
  1933. // Avoid method swizzling run twice and revert to original initialize function
  1934. isOverrided = true
  1935. if let systemFontMethod = class_getClassMethod(self, #selector(systemFont(ofSize:))),
  1936. let mySystemFontMethod = class_getClassMethod(self, #selector(libSystemFont(ofSize:))) {
  1937. method_exchangeImplementations(systemFontMethod, mySystemFontMethod)
  1938. }
  1939. if let systemFontWeightMethod = class_getClassMethod(self, #selector(systemFont(ofSize:weight:))),
  1940. let mySystemFontWeightMethod = class_getClassMethod(self, #selector(libSystemFontWeight(ofSize:weight:))) {
  1941. method_exchangeImplementations(systemFontWeightMethod, mySystemFontWeightMethod)
  1942. }
  1943. if let boldSystemFontMethod = class_getClassMethod(self, #selector(boldSystemFont(ofSize:))),
  1944. let myBoldSystemFontMethod = class_getClassMethod(self, #selector(libBoldSystemFont(ofSize:))) {
  1945. method_exchangeImplementations(boldSystemFontMethod, myBoldSystemFontMethod)
  1946. }
  1947. if let italicSystemFontMethod = class_getClassMethod(self, #selector(italicSystemFont(ofSize:))),
  1948. let myItalicSystemFontMethod = class_getClassMethod(self, #selector(libItalicSystemFont(ofSize:))) {
  1949. method_exchangeImplementations(italicSystemFontMethod, myItalicSystemFontMethod)
  1950. }
  1951. if let initCoderMethod = class_getInstanceMethod(self, #selector(UIFontDescriptor.init(coder:))), // Trick to get over the lack of UIFont.init(coder:))
  1952. let myInitCoderMethod = class_getInstanceMethod(self, #selector(UIFont.init(myCoder:))) {
  1953. method_exchangeImplementations(initCoderMethod, myInitCoderMethod)
  1954. }
  1955. }
  1956. class func jbs_registerFont(withFilenameString filenameString: String) {
  1957. // guard let pathForResourceString = Bundle.resourceBundle(for: Nexilis.self).path(forResource: filenameString, ofType: "otf") else { //resourcesMediaBundle
  1958. // //print("UIFont+: Failed to register font - path for resource not found.")
  1959. // return
  1960. // }
  1961. var pathForResourceURL = Bundle.resourceBundle(for: Nexilis.self).url(forResource: filenameString, withExtension: "otf")
  1962. if pathForResourceURL == nil {
  1963. pathForResourceURL = Bundle.resourcesMediaBundle(for: Nexilis.self).url(forResource: filenameString, withExtension: "otf")
  1964. }
  1965. // guard let pathForResourceURL = Bundle.resourceBundle(for: Nexilis.self).url(forResource: filenameString, withExtension: "otf") else { //resourcesMediaBundle
  1966. // //print("UIFont+: Failed to register font - path for resource not found.")
  1967. // return
  1968. // }
  1969. var errorRef: Unmanaged<CFError>? = nil
  1970. CTFontManagerRegisterFontsForURL(pathForResourceURL! as CFURL, .process, &errorRef)
  1971. // guard let fontData = NSData(contentsOfFile: pathForResourceString) else {
  1972. // //print("UIFont+: Failed to register font - font data could not be loaded.")
  1973. // return
  1974. // }
  1975. //
  1976. // guard let dataProvider = CGDataProvider(data: fontData) else {
  1977. // //print("UIFont+: Failed to register font - data provider could not be loaded.")
  1978. // return
  1979. // }
  1980. //
  1981. // guard let font = CGFont(dataProvider) else {
  1982. // //print("UIFont+: Failed to register font - font could not be loaded.")
  1983. // return
  1984. // }
  1985. //
  1986. // var errorRef: Unmanaged<CFError>? = nil
  1987. // if (CTFontManagerRegisterGraphicsFont(font, &errorRef) == false) {
  1988. // }
  1989. }
  1990. }
  1991. public protocol LoginDelegate: NSObjectProtocol {
  1992. func onProgress(code: String, progress: Int)
  1993. func onProcess(message: String, status: String)
  1994. }
  1995. public protocol MessageDelegate: NSObjectProtocol {
  1996. func onReceive(message: TMessage)
  1997. func onReceiveComment(message: TMessage)
  1998. func onReceive(message: [AnyHashable: Any?])
  1999. func onMessage(message: TMessage)
  2000. func onUpload(name: String, progress: Double)
  2001. func onTyping(message: TMessage)
  2002. }
  2003. public protocol GroupDelegate: NSObjectProtocol {
  2004. func onGroup(code: String, f_pin: String, groupId: String)
  2005. func onTopic(code: String, f_pin: String, topicId: String)
  2006. func onMember(code: String, f_pin: String, groupId: String, member: String)
  2007. }
  2008. public protocol DownloadDelegate: NSObjectProtocol {
  2009. func onDownloadProgress(fileName: String, progress: Double)
  2010. }
  2011. public protocol CallDelegate: NSObjectProtocol {
  2012. func onIncomingCall(state: Int, message: String)
  2013. func onStatusCall(state: Int, message: String)
  2014. }
  2015. public protocol LiveStreamingDelegate: NSObjectProtocol {
  2016. func onStartLS(state: Int, message: String)
  2017. func onJoinLS(state: Int, message: String)
  2018. }
  2019. public protocol SeminarDelegate: NSObjectProtocol {
  2020. func onStartSeminar(state: Int, message: String)
  2021. func onJoinSeminar(state: Int, message: String)
  2022. }
  2023. public protocol VideoCallDelegate: NSObjectProtocol {
  2024. func onInitiateVideoCall(destination:String,state: Int, message: String)
  2025. func onAcceptVideoCall(originator:String,state: Int, message: String)
  2026. func onVideoCallReceiverTerminate(originator:String,state: Int, message: String)
  2027. }
  2028. public protocol PersonInfoDelegate: NSObjectProtocol {
  2029. func onUpdatePersonInfo(state: Int, message: String)
  2030. }
  2031. public protocol ScreenSharingDelegate: NSObjectProtocol {
  2032. func onStartScreenSharing(state:Int,message:String)
  2033. func onJoinScreenSharing(state:Int,message:String)
  2034. }
  2035. public protocol CommentDelegate: NSObjectProtocol {
  2036. func onReceiveComment(message: TMessage)
  2037. func onDeleteComment(message: TMessage)
  2038. }
  2039. public protocol UploadDelegate: NSObjectProtocol {
  2040. func onUploadProgress(fileName: String, progress: Double)
  2041. }
  2042. public protocol TimelineDelegate: NSObjectProtocol {
  2043. func onPostUpdate(status: String, message: String)
  2044. }
  2045. public protocol ConnectionDelegate: NSObjectProtocol {
  2046. func connectionStateChanged(userId: String!, deviceId: String, state: Bool)
  2047. }
  2048. public protocol ConnectDelegate: NSObjectProtocol {
  2049. func onSuccess(userId: String)
  2050. func onFailed(error: String)
  2051. }
  2052. public enum AppStoryBoard: String {
  2053. case Palio = "Palio"
  2054. public var instance: UIStoryboard {
  2055. return UIStoryboard(name: self.rawValue, bundle: Bundle.resourceBundle(for: Nexilis.self))
  2056. }
  2057. }
  2058. public var uuidOngoing = UUID()
  2059. extension Nexilis: CallDelegate {
  2060. func displayIncomingCall(uuid: UUID, handle: String, hasVideo: Bool = false, completion: ((Error?) -> Void)? = nil) {
  2061. providerDelegate?.reportIncomingCall(uuid: uuid, handle: handle, hasVideo: hasVideo, completion: completion)
  2062. }
  2063. public func onIncomingCall(state: Int, message: String) {
  2064. DispatchQueue.main.async {
  2065. let idMe = User.getMyPin()!
  2066. let myData = User.getData(pin: idMe)
  2067. let onGoingCC: String = SecureUserDefaults.shared.value(forKey: "onGoingCC") ?? ""
  2068. if !onGoingCC.isEmpty {
  2069. return
  2070. }
  2071. let deviceId = message.split(separator: ",")[0]
  2072. if myData?.offline_mode == "1" || self.stateUnfriend == deviceId {
  2073. DispatchQueue.main.asyncAfter(deadline: .now() + 0.5, execute: {
  2074. API.terminateCall(sParty: nil)
  2075. })
  2076. return
  2077. }
  2078. var isShowAlert: Double?
  2079. let canShow = UIApplication.shared.visibleViewController
  2080. if canShow != nil && !(canShow is UINavigationController) {
  2081. if !(canShow is EditorPersonal) {
  2082. isShowAlert = 0
  2083. } else {
  2084. isShowAlert = 1.5
  2085. }
  2086. } else if canShow != nil {
  2087. if canShow is UINavigationController {
  2088. let canShowNC = canShow as! UINavigationController
  2089. if !(canShowNC.visibleViewController is EditorPersonal) {
  2090. isShowAlert = 0
  2091. } else {
  2092. isShowAlert = 1.5
  2093. }
  2094. } else {
  2095. isShowAlert = 0
  2096. }
  2097. }
  2098. if (state == Nexilis.AUDIO_CALL_INCOMING && message.split(separator: ",")[1] != "joining Ac.room on channel 0") {
  2099. if Nexilis.callAPNActivated || APIS.checkAppStateisBackground() {
  2100. return
  2101. }
  2102. let data = User.getDataCanNil(pin: String(deviceId))
  2103. if data == nil {
  2104. DispatchQueue.main.asyncAfter(deadline: .now() + 0.5, execute: {
  2105. API.terminateCall(sParty: nil)
  2106. })
  2107. return
  2108. }
  2109. // let backgroundTaskIdentifier = UIApplication.shared.beginBackgroundTask(expirationHandler: nil)
  2110. // uuidOngoing = UUID()
  2111. // self.displayIncomingCall(uuid: uuidOngoing, handle: String(deviceId), hasVideo: false) { error in
  2112. // UIApplication.shared.endBackgroundTask(backgroundTaskIdentifier)
  2113. // }
  2114. let controller = QmeraAudioViewController()
  2115. controller.user = User.getData(pin: String(deviceId))
  2116. controller.isOutgoing = false
  2117. controller.modalPresentationStyle = .overCurrentContext
  2118. if UIApplication.shared.visibleViewController is UIAlertController {
  2119. let vc = UIApplication.shared.visibleViewController as! UIAlertController
  2120. vc.dismiss(animated: true, completion: {
  2121. if UIApplication.shared.visibleViewController?.navigationController != nil {
  2122. UIApplication.shared.visibleViewController?.navigationController?.present(controller, animated: true, completion: nil)
  2123. } else {
  2124. UIApplication.shared.visibleViewController?.present(controller, animated: true, completion: nil)
  2125. }
  2126. })
  2127. return
  2128. }
  2129. if UIApplication.shared.visibleViewController?.navigationController != nil {
  2130. UIApplication.shared.visibleViewController?.navigationController?.present(controller, animated: true, completion: nil)
  2131. } else {
  2132. UIApplication.shared.visibleViewController?.present(controller, animated: true, completion: nil)
  2133. }
  2134. // API.receiveCCall(sParty: String(deviceId))
  2135. } else if state == Nexilis.VIDEO_CALL_INCOMING {
  2136. if Nexilis.callAPNActivated || APIS.checkAppStateisBackground() {
  2137. return
  2138. }
  2139. let dataUser = User.getDataCanNil(pin: String(deviceId))
  2140. if dataUser == nil {
  2141. DispatchQueue.main.asyncAfter(deadline: .now() + 0.5, execute: {
  2142. API.terminateCall(sParty: nil)
  2143. })
  2144. return
  2145. }
  2146. let videoController = AppStoryBoard.Palio.instance.instantiateViewController(withIdentifier: "videoVCQmera") as! QmeraVideoViewController
  2147. videoController.fPin = String(deviceId)
  2148. videoController.isInisiator = false
  2149. let navigationController = CustomNavigationController(rootViewController: videoController)
  2150. navigationController.modalPresentationStyle = .fullScreen
  2151. if UIApplication.shared.visibleViewController is UIAlertController {
  2152. let vc = UIApplication.shared.visibleViewController as! UIAlertController
  2153. vc.dismiss(animated: true, completion: {
  2154. if UIApplication.shared.visibleViewController?.navigationController != nil {
  2155. UIApplication.shared.visibleViewController?.navigationController?.present(navigationController, animated: true, completion: nil)
  2156. } else {
  2157. UIApplication.shared.visibleViewController?.present(navigationController, animated: true, completion: nil)
  2158. }
  2159. })
  2160. return
  2161. }
  2162. if UIApplication.shared.visibleViewController?.navigationController != nil {
  2163. UIApplication.shared.visibleViewController?.navigationController?.present(navigationController, animated: true, completion: nil)
  2164. } else {
  2165. UIApplication.shared.visibleViewController?.present(navigationController, animated: true, completion: nil)
  2166. }
  2167. }
  2168. }
  2169. }
  2170. public func onStatusCall(state: Int, message: String) {
  2171. // let r = message.split(separator: ",")
  2172. // if state == Nexilis.AUDIO_CALL_RINGING {
  2173. // if let call = callManager.call(with: String(r[0])) {
  2174. // //print("onStatusCall:connectingCall")
  2175. // DispatchQueue.main.async {
  2176. // call.connectingCall()
  2177. // }
  2178. // }
  2179. // } else if state == Nexilis.AUDIO_CALL_OFFHOOK {
  2180. //// if let call = callManager.call(with: String(r[1])) {
  2181. // //print("onStatusCall:answerCall")
  2182. //// DispatchQueue.main.async {
  2183. //// call.answerCall()
  2184. //// }
  2185. //// }
  2186. // } else if state == Nexilis.AUDIO_CALL_END {
  2187. // DispatchQueue.main.async {
  2188. // if QmeraAudioViewController().viewIfLoaded?.window == nil {
  2189. // Nexilis.shared.callManager.end(call: Call(uuid: uuidOngoing))
  2190. // }
  2191. // }
  2192. // }
  2193. var dataCall: [AnyHashable : Any] = [:]
  2194. dataCall["state"] = state
  2195. dataCall["message"] = message
  2196. NotificationCenter.default.post(name: NSNotification.Name(rawValue: Nexilis.listenerStatusCall), object: nil, userInfo: dataCall)
  2197. }
  2198. }
  2199. var previewItem : NSURL?
  2200. var listCCIdInv: [String] = []
  2201. var imageGif: UIImageView!
  2202. var posGif = "0"
  2203. var loopGif = "0"
  2204. var timerAnimationGif = Timer()
  2205. extension Nexilis: MessageDelegate {
  2206. public func onReceiveComment(message: TMessage) {
  2207. var dataMessage: [AnyHashable : Any] = [:]
  2208. dataMessage["message"] = message
  2209. NotificationCenter.default.post(name: NSNotification.Name(rawValue: "onReceiveComment"), object: nil, userInfo: dataMessage)
  2210. }
  2211. @objc func tapLinkBroadcast(_ sender: ObjectGesture) {
  2212. var stringURl = sender.message_id.lowercased()
  2213. if stringURl.starts(with: "www.") {
  2214. stringURl = "https://" + stringURl.replacingOccurrences(of: "www.", with: "")
  2215. }
  2216. guard let url = URL(string: stringURl) else { return }
  2217. UIApplication.shared.open(url)
  2218. }
  2219. private func runAnimationGif() {
  2220. DispatchQueue.main.asyncAfter(deadline: .now() + 3, execute: { [self] in
  2221. if imageGif != nil {
  2222. timerAnimationGif.invalidate()
  2223. timerAnimationGif = Timer.scheduledTimer(timeInterval: 0.001, target: self, selector: #selector(animateGif), userInfo: nil, repeats: true)
  2224. }
  2225. })
  2226. }
  2227. @objc func animateGif() {
  2228. DispatchQueue.main.async {
  2229. if posGif == "0" { //left
  2230. if imageGif.frame.origin.x < (UIScreen.main.bounds.width - imageGif.frame.width) {
  2231. imageGif.frame.origin.x+=0.1
  2232. } else {
  2233. timerAnimationGif.invalidate()
  2234. }
  2235. } else if posGif == "1" { //right
  2236. if imageGif.frame.origin.x > 0 {
  2237. imageGif.frame.origin.x-=0.1
  2238. } else {
  2239. timerAnimationGif.invalidate()
  2240. }
  2241. } else if posGif == "2" { //top
  2242. if imageGif.frame.origin.y < (UIScreen.main.bounds.height - imageGif.frame.height) {
  2243. imageGif.frame.origin.y+=0.1
  2244. } else {
  2245. timerAnimationGif.invalidate()
  2246. }
  2247. } else { //bottom
  2248. if imageGif.frame.origin.y > 20 {
  2249. imageGif.frame.origin.y-=0.1
  2250. } else {
  2251. timerAnimationGif.invalidate()
  2252. }
  2253. }
  2254. }
  2255. }
  2256. func showBroadcastMessage(m: [String: String]) {
  2257. let fileType = m[CoreMessage_TMessageKey.CATEGORY_FLAG]!
  2258. let gifId = m[CoreMessage_TMessageKey.GIF_ID] ?? ""
  2259. let broadcastVC = UIViewController()
  2260. if let viewBroadcast = broadcastVC.view {
  2261. broadcastVC.modalPresentationStyle = .custom
  2262. viewBroadcast.backgroundColor = .black.withAlphaComponent(0.3)
  2263. if !gifId.isEmpty {
  2264. let urlGif = "\(Utils.getURLBase())filepalio/image/\(gifId)"
  2265. let scale = m[CoreMessage_TMessageKey.SCALE] ?? "0"
  2266. let link = m[CoreMessage_TMessageKey.LINK] ?? ""
  2267. posGif = m[CoreMessage_TMessageKey.START_ANIMATION] ?? "0"
  2268. loopGif = m[CoreMessage_TMessageKey.LOOP_ANIMATION] ?? "0"
  2269. imageGif = UIImageView()
  2270. viewBroadcast.addSubview(imageGif)
  2271. imageGif.isUserInteractionEnabled = true
  2272. imageGif.contentMode = .scaleAspectFit
  2273. let buttonClose = UIButton(type: .close)
  2274. buttonClose.frame.size = CGSize(width: 30, height: 30)
  2275. buttonClose.layer.cornerRadius = 15.0
  2276. buttonClose.clipsToBounds = true
  2277. buttonClose.backgroundColor = .black.withAlphaComponent(0.5)
  2278. buttonClose.actionHandle(controlEvents: .touchUpInside,
  2279. ForAction:{() -> Void in
  2280. broadcastVC.dismiss(animated: true, completion: {
  2281. imageGif = nil
  2282. Nexilis.broadcastList.remove(at: 0)
  2283. if Nexilis.broadcastList.count > 0 {
  2284. Nexilis.shared.showBroadcastMessage(m: Nexilis.broadcastList[0])
  2285. }
  2286. })
  2287. })
  2288. imageGif.addSubview(buttonClose)
  2289. buttonClose.anchor(top: imageGif.topAnchor, right: imageGif.rightAnchor, width: 30, height: 30)
  2290. var xpos: CGFloat = 0
  2291. var ypos: CGFloat = 0
  2292. var widthImage: CGFloat = 300
  2293. var heightImage: CGFloat = 300
  2294. if scale == "2" { //50%
  2295. widthImage = 150
  2296. heightImage = 150
  2297. } else if scale == "1" { //75%
  2298. widthImage = 225
  2299. heightImage = 225
  2300. }
  2301. if posGif == "0" { //left
  2302. xpos = 0
  2303. ypos = (viewBroadcast.frame.size.height / 2) - (heightImage / 2)
  2304. } else if posGif == "1" { //right
  2305. xpos = viewBroadcast.frame.size.width - widthImage
  2306. ypos = (viewBroadcast.frame.size.height / 2) - (heightImage / 2)
  2307. } else if posGif == "2" { //top
  2308. xpos = (viewBroadcast.frame.size.width / 2) - (widthImage / 2)
  2309. ypos = 20
  2310. } else { //bottom
  2311. xpos = (viewBroadcast.frame.size.width / 2) - (widthImage / 2)
  2312. ypos = viewBroadcast.frame.size.height - heightImage
  2313. }
  2314. imageGif.frame = CGRect(x: xpos, y: ypos, width: widthImage, height: heightImage)
  2315. imageGif.loadImageAsync(with: urlGif, isGif: true)
  2316. runAnimationGif()
  2317. imageGif.actionHandle(controlEvents: .touchUpInside, ForAction: {
  2318. broadcastVC.dismiss(animated: true, completion: {
  2319. imageGif = nil
  2320. Nexilis.broadcastList.remove(at: 0)
  2321. if Nexilis.broadcastList.count > 0 {
  2322. Nexilis.shared.showBroadcastMessage(m: Nexilis.broadcastList[0])
  2323. }
  2324. if !link.isEmpty {
  2325. APIS.openUrl(url: link)
  2326. }
  2327. })
  2328. })
  2329. } else {
  2330. let stringLink = m[CoreMessage_TMessageKey.LINK] ?? ""
  2331. let containerView = UIView()
  2332. viewBroadcast.addSubview(containerView)
  2333. if stringLink.isEmpty {
  2334. containerView.anchor(centerX: viewBroadcast.centerXAnchor, centerY: viewBroadcast.centerYAnchor, width: viewBroadcast.bounds.width - 40, minHeight: 100, maxHeight: viewBroadcast.bounds.height - 100)
  2335. } else {
  2336. containerView.anchor(centerX: viewBroadcast.centerXAnchor, centerY: viewBroadcast.centerYAnchor, width: viewBroadcast.bounds.width - 40, minHeight: 200, maxHeight: viewBroadcast.bounds.height - 100)
  2337. }
  2338. containerView.backgroundColor = .white.withAlphaComponent(0.9)
  2339. containerView.layer.cornerRadius = 15.0
  2340. containerView.clipsToBounds = true
  2341. let subContainerView = UIView()
  2342. subContainerView.backgroundColor = .clear
  2343. containerView.addSubview(subContainerView)
  2344. 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)
  2345. let buttonClose = UIButton(type: .close)
  2346. buttonClose.frame.size = CGSize(width: 30, height: 30)
  2347. buttonClose.layer.cornerRadius = 15.0
  2348. buttonClose.clipsToBounds = true
  2349. buttonClose.backgroundColor = .secondaryColor.withAlphaComponent(0.5)
  2350. buttonClose.actionHandle(controlEvents: .touchUpInside,
  2351. ForAction:{() -> Void in
  2352. broadcastVC.dismiss(animated: true, completion: {
  2353. Nexilis.broadcastList.remove(at: 0)
  2354. if Nexilis.broadcastList.count > 0 {
  2355. Nexilis.shared.showBroadcastMessage(m: Nexilis.broadcastList[0])
  2356. }
  2357. })
  2358. })
  2359. containerView.addSubview(buttonClose)
  2360. buttonClose.anchor(top: containerView.topAnchor, right: containerView.rightAnchor, width: 30, height: 30)
  2361. let title = UILabel()
  2362. title.font = .systemFont(ofSize: 18, weight: .bold)
  2363. title.text = m["MERNAM"]
  2364. title.textAlignment = .center
  2365. subContainerView.addSubview(title)
  2366. title.anchor(top: subContainerView.topAnchor, left: subContainerView.leftAnchor, right: subContainerView.rightAnchor)
  2367. let titleBroadcast = UILabel()
  2368. subContainerView.addSubview(titleBroadcast)
  2369. titleBroadcast.translatesAutoresizingMaskIntoConstraints = false
  2370. NSLayoutConstraint.activate([
  2371. titleBroadcast.topAnchor.constraint(equalTo: title.bottomAnchor, constant: 20.0),
  2372. titleBroadcast.leadingAnchor.constraint(equalTo: subContainerView.leadingAnchor),
  2373. titleBroadcast.trailingAnchor.constraint(equalTo: subContainerView.trailingAnchor),
  2374. ])
  2375. titleBroadcast.font = UIFont.systemFont(ofSize: 14, weight: .semibold)
  2376. titleBroadcast.numberOfLines = 0
  2377. titleBroadcast.attributedText = m[CoreMessage_TMessageKey.TITLE]!.richText()
  2378. titleBroadcast.textColor = .black
  2379. let descBroadcast = UILabel()
  2380. subContainerView.addSubview(descBroadcast)
  2381. descBroadcast.translatesAutoresizingMaskIntoConstraints = false
  2382. let constraintDesc = descBroadcast.bottomAnchor.constraint(equalTo: subContainerView.bottomAnchor)
  2383. if !stringLink.isEmpty{
  2384. constraintDesc.constant = constraintDesc.constant - 30
  2385. }
  2386. if fileType != BroadcastViewController.FILE_TYPE_CHAT {
  2387. constraintDesc.constant = constraintDesc.constant - 260
  2388. }
  2389. NSLayoutConstraint.activate([
  2390. descBroadcast.topAnchor.constraint(equalTo: titleBroadcast.bottomAnchor, constant: 10),
  2391. descBroadcast.leadingAnchor.constraint(equalTo: subContainerView.leadingAnchor),
  2392. descBroadcast.trailingAnchor.constraint(equalTo: subContainerView.trailingAnchor),
  2393. constraintDesc,
  2394. ])
  2395. descBroadcast.font = UIFont.systemFont(ofSize: 12)
  2396. descBroadcast.numberOfLines = 0
  2397. descBroadcast.attributedText = m[CoreMessage_TMessageKey.MESSAGE_TEXT_ENG]!.richText()
  2398. descBroadcast.textColor = .black
  2399. let linkBroadcast = UILabel()
  2400. if !stringLink.isEmpty {
  2401. subContainerView.addSubview(linkBroadcast)
  2402. linkBroadcast.translatesAutoresizingMaskIntoConstraints = false
  2403. NSLayoutConstraint.activate([
  2404. linkBroadcast.topAnchor.constraint(equalTo: descBroadcast.bottomAnchor, constant: 10),
  2405. linkBroadcast.leadingAnchor.constraint(equalTo: subContainerView.leadingAnchor),
  2406. linkBroadcast.trailingAnchor.constraint(equalTo: subContainerView.trailingAnchor),
  2407. ])
  2408. linkBroadcast.font = UIFont.systemFont(ofSize: 12)
  2409. linkBroadcast.isUserInteractionEnabled = true
  2410. linkBroadcast.numberOfLines = 2
  2411. let attributedString = NSMutableAttributedString(string: stringLink, attributes:[NSAttributedString.Key.link: URL(string: stringLink)!])
  2412. linkBroadcast.attributedText = attributedString
  2413. let tap = ObjectGesture(target: self, action: #selector(tapLinkBroadcast))
  2414. tap.message_id = stringLink
  2415. linkBroadcast.addGestureRecognizer(tap)
  2416. }
  2417. let thumb = m[CoreMessage_TMessageKey.THUMB_ID] ?? ""
  2418. let image = m[CoreMessage_TMessageKey.IMAGE_ID] ?? ""
  2419. let video = m[CoreMessage_TMessageKey.VIDEO_ID] ?? ""
  2420. let file = m[CoreMessage_TMessageKey.FILE_ID] ?? ""
  2421. if fileType != BroadcastViewController.FILE_TYPE_CHAT {
  2422. let imageBroadcast = UIImageView()
  2423. subContainerView.addSubview(imageBroadcast)
  2424. imageBroadcast.translatesAutoresizingMaskIntoConstraints = false
  2425. var constImage = imageBroadcast.topAnchor.constraint(equalTo: descBroadcast.bottomAnchor, constant: 10)
  2426. if !stringLink.isEmpty {
  2427. constImage = imageBroadcast.topAnchor.constraint(equalTo: linkBroadcast.bottomAnchor, constant: 10)
  2428. }
  2429. NSLayoutConstraint.activate([
  2430. constImage,
  2431. imageBroadcast.leadingAnchor.constraint(equalTo: subContainerView.leadingAnchor),
  2432. imageBroadcast.trailingAnchor.constraint(equalTo: subContainerView.trailingAnchor),
  2433. imageBroadcast.heightAnchor.constraint(equalToConstant: 250)
  2434. ])
  2435. imageBroadcast.layer.cornerRadius = 10.0
  2436. imageBroadcast.clipsToBounds = true
  2437. if fileType != BroadcastViewController.FILE_TYPE_DOCUMENT {
  2438. imageBroadcast.contentMode = .scaleAspectFill
  2439. imageBroadcast.setImage(name: thumb)
  2440. if fileType == BroadcastViewController.FILE_TYPE_VIDEO {
  2441. let imagePlay = UIImageView(image: UIImage(systemName: "play.circle.fill"))
  2442. imageBroadcast.addSubview(imagePlay)
  2443. imagePlay.clipsToBounds = true
  2444. imagePlay.translatesAutoresizingMaskIntoConstraints = false
  2445. imagePlay.centerYAnchor.constraint(equalTo: imageBroadcast.centerYAnchor).isActive = true
  2446. imagePlay.centerXAnchor.constraint(equalTo: imageBroadcast.centerXAnchor).isActive = true
  2447. imagePlay.widthAnchor.constraint(equalToConstant: 60).isActive = true
  2448. imagePlay.heightAnchor.constraint(equalToConstant: 60).isActive = true
  2449. imagePlay.tintColor = .gray.withAlphaComponent(0.5)
  2450. }
  2451. } else {
  2452. imageBroadcast.image = UIImage(systemName: "doc.fill")
  2453. imageBroadcast.tintColor = .mainColor
  2454. imageBroadcast.contentMode = .scaleAspectFit
  2455. }
  2456. imageBroadcast.actionHandle(controlEvents: .touchUpInside,
  2457. ForAction:{() -> Void in
  2458. let nsDocumentDirectory = FileManager.SearchPathDirectory.documentDirectory
  2459. let nsUserDomainMask = FileManager.SearchPathDomainMask.userDomainMask
  2460. let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true)
  2461. if fileType == BroadcastViewController.FILE_TYPE_IMAGE {
  2462. if let dirPath = paths.first {
  2463. let imageURL = URL(fileURLWithPath: dirPath).appendingPathComponent(image)
  2464. if FileManager.default.fileExists(atPath: imageURL.path) {
  2465. let image = UIImage(contentsOfFile: imageURL.path)
  2466. let previewImageVC = PreviewAttachmentImageVideo(nibName: "PreviewAttachmentImageVideo", bundle: Bundle.resourceBundle(for: Nexilis.self))
  2467. previewImageVC.image = image
  2468. previewImageVC.isHiddenTextField = true
  2469. previewImageVC.modalPresentationStyle = .overFullScreen
  2470. previewImageVC.modalTransitionStyle = .crossDissolve
  2471. if UIApplication.shared.visibleViewController?.navigationController != nil {
  2472. UIApplication.shared.visibleViewController?.navigationController?.present(previewImageVC, animated: true, completion: nil)
  2473. } else {
  2474. UIApplication.shared.visibleViewController?.present(previewImageVC, animated: true, completion: nil)
  2475. }
  2476. } else if FileEncryption.shared.isSecureExists(filename: image) {
  2477. do {
  2478. let data = try FileEncryption.shared.readSecure(filename: image)
  2479. let image = UIImage(data: data!)
  2480. let previewImageVC = PreviewAttachmentImageVideo(nibName: "PreviewAttachmentImageVideo", bundle: Bundle.resourceBundle(for: Nexilis.self))
  2481. previewImageVC.image = image
  2482. previewImageVC.isHiddenTextField = true
  2483. previewImageVC.modalPresentationStyle = .overFullScreen
  2484. previewImageVC.modalTransitionStyle = .crossDissolve
  2485. if UIApplication.shared.visibleViewController?.navigationController != nil {
  2486. UIApplication.shared.visibleViewController?.navigationController?.present(previewImageVC, animated: true, completion: nil)
  2487. } else {
  2488. UIApplication.shared.visibleViewController?.present(previewImageVC, animated: true, completion: nil)
  2489. }
  2490. } catch {
  2491. }
  2492. } else {
  2493. Download().startHTTP(forKey: image) { (name, progress) in
  2494. guard progress == 100 else {
  2495. return
  2496. }
  2497. do {
  2498. try FileEncryption.shared.writeSecure(filename: image)
  2499. } catch {
  2500. }
  2501. DispatchQueue.main.async {
  2502. var image : UIImage?
  2503. if FileManager.default.fileExists(atPath: imageURL.path) {
  2504. image = UIImage(contentsOfFile: imageURL.path)
  2505. }
  2506. else if FileEncryption.shared.isSecureExists(filename: imageURL.lastPathComponent) {
  2507. do {
  2508. if let imageData = try FileEncryption.shared.readSecure(filename: imageURL.lastPathComponent) {
  2509. image = UIImage(data: imageData)
  2510. }
  2511. } catch {
  2512. }
  2513. }
  2514. let previewImageVC = PreviewAttachmentImageVideo(nibName: "PreviewAttachmentImageVideo", bundle: Bundle.resourceBundle(for: Nexilis.self))
  2515. previewImageVC.image = image
  2516. previewImageVC.isHiddenTextField = true
  2517. previewImageVC.modalPresentationStyle = .overFullScreen
  2518. previewImageVC.modalTransitionStyle = .crossDissolve
  2519. if UIApplication.shared.visibleViewController?.navigationController != nil {
  2520. UIApplication.shared.visibleViewController?.navigationController?.present(previewImageVC, animated: true, completion: nil)
  2521. } else {
  2522. UIApplication.shared.visibleViewController?.present(previewImageVC, animated: true, completion: nil)
  2523. }
  2524. }
  2525. }
  2526. }
  2527. }
  2528. } else if fileType == BroadcastViewController.FILE_TYPE_VIDEO {
  2529. //https://qmera.io/filepalio/image/
  2530. let player = AVPlayer(url: URL(string: "https://nexilis.io/get_file?account=\(Nexilis.sAPIKey)&image=\(video)")!)
  2531. let playerVC = AVPlayerViewController()
  2532. playerVC.player = player
  2533. playerVC.modalPresentationStyle = .custom
  2534. if UIApplication.shared.visibleViewController?.navigationController != nil {
  2535. UIApplication.shared.visibleViewController?.navigationController?.present(playerVC, animated: true, completion: nil)
  2536. } else {
  2537. UIApplication.shared.visibleViewController?.present(playerVC, animated: true, completion: nil)
  2538. }
  2539. } else if fileType == BroadcastViewController.FILE_TYPE_DOCUMENT {
  2540. if let dirPath = paths.first {
  2541. let fileURL = URL(fileURLWithPath: dirPath).appendingPathComponent(file)
  2542. if FileManager.default.fileExists(atPath: fileURL.path) {
  2543. previewItem = fileURL as NSURL
  2544. let previewController = QLPreviewController()
  2545. let rightBarButton = UIBarButtonItem()
  2546. previewController.navigationItem.rightBarButtonItem = rightBarButton
  2547. previewController.dataSource = self
  2548. previewController.modalPresentationStyle = .overFullScreen
  2549. if UIApplication.shared.visibleViewController?.navigationController != nil {
  2550. UIApplication.shared.visibleViewController?.navigationController?.present(previewController, animated: true, completion: nil)
  2551. } else {
  2552. UIApplication.shared.visibleViewController?.present(previewController, animated: true, completion: nil)
  2553. }
  2554. } else if FileEncryption.shared.isSecureExists(filename: file) {
  2555. do {
  2556. if let docData = try FileEncryption.shared.readSecure(filename: file) {
  2557. let cachesDirectory = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first!
  2558. let tempPath = cachesDirectory.appendingPathComponent(file)
  2559. try docData.write(to: tempPath)
  2560. previewItem = tempPath as NSURL
  2561. let previewController = QLPreviewController()
  2562. let rightBarButton = UIBarButtonItem()
  2563. previewController.navigationItem.rightBarButtonItem = rightBarButton
  2564. previewController.dataSource = self
  2565. previewController.modalPresentationStyle = .overFullScreen
  2566. if UIApplication.shared.visibleViewController?.navigationController != nil {
  2567. UIApplication.shared.visibleViewController?.navigationController?.present(previewController, animated: true, completion: nil)
  2568. } else {
  2569. UIApplication.shared.visibleViewController?.present(previewController, animated: true, completion: nil)
  2570. }
  2571. }
  2572. } catch {
  2573. }
  2574. } else {
  2575. Download().startHTTP(forKey: file, isImage: false) { (name, progress) in
  2576. DispatchQueue.main.async {
  2577. guard progress == 100 else {
  2578. return
  2579. }
  2580. do {
  2581. let secureFilename = try FileEncryption.shared.writeSecure(filename: name)
  2582. if let docData = try FileEncryption.shared.readSecure(filename: secureFilename?[0] as! String) {
  2583. let cachesDirectory = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first!
  2584. let tempPath = cachesDirectory.appendingPathComponent(file)
  2585. try docData.write(to: tempPath)
  2586. previewItem = tempPath as NSURL
  2587. let previewController = QLPreviewController()
  2588. let rightBarButton = UIBarButtonItem()
  2589. previewController.navigationItem.rightBarButtonItem = rightBarButton
  2590. previewController.dataSource = self
  2591. previewController.modalPresentationStyle = .overFullScreen
  2592. if UIApplication.shared.visibleViewController?.navigationController != nil {
  2593. UIApplication.shared.visibleViewController?.navigationController?.present(previewController, animated: true, completion: nil)
  2594. } else {
  2595. UIApplication.shared.visibleViewController?.present(previewController, animated: true, completion: nil)
  2596. }
  2597. }
  2598. }
  2599. catch {
  2600. }
  2601. }
  2602. }
  2603. }
  2604. }
  2605. }
  2606. })
  2607. }
  2608. }
  2609. broadcastVC.modalTransitionStyle = .crossDissolve
  2610. if UIApplication.shared.visibleViewController?.navigationController != nil {
  2611. UIApplication.shared.visibleViewController?.navigationController?.present(broadcastVC, animated: true, completion: nil)
  2612. } else {
  2613. UIApplication.shared.visibleViewController?.present(broadcastVC, animated: true, completion: nil)
  2614. }
  2615. }
  2616. }
  2617. public func onReceive(message: TMessage) {
  2618. var dataMessage: [AnyHashable : Any] = [:]
  2619. dataMessage["message"] = message
  2620. NotificationCenter.default.post(name: NSNotification.Name(rawValue: Nexilis.listenerReceiveChat), object: nil, userInfo: dataMessage)
  2621. if message.getCode() == CoreMessage_TMessageCode.PUSH_CALL_CENTER {
  2622. if User.getDataCanNil(pin: message.getBody(key: CoreMessage_TMessageKey.L_PIN)) == nil {
  2623. Nexilis.addFriendSilent(fpin: message.getBody(key: CoreMessage_TMessageKey.L_PIN))
  2624. sleep(1)
  2625. }
  2626. DispatchQueue.main.async {
  2627. if Nexilis.onGoingPushCC.isEmpty {
  2628. var data: [String: String] = [:]
  2629. data["channel"] = message.getBody(key: CoreMessage_TMessageKey.CHANNEL)
  2630. data["l_pin"] = message.getBody(key: CoreMessage_TMessageKey.L_PIN)
  2631. data["f_display_name"] = message.getBody(key: CoreMessage_TMessageKey.F_DISPLAY_NAME)
  2632. Nexilis.onGoingPushCC = data
  2633. } else if Nexilis.onGoingPushCC["f_display_name"] == message.getBody(key: CoreMessage_TMessageKey.F_DISPLAY_NAME) {
  2634. return
  2635. }
  2636. let alert = LibAlertController(title: "", message: "\n\n\n\n\n\n\n\n\n\n".localized(), preferredStyle: .alert)
  2637. let newWidth = UIScreen.main.bounds.width * 0.90 - 270
  2638. // update width constraint value for main view
  2639. if let viewWidthConstraint = alert.view.constraints.filter({ return $0.firstAttribute == .width }).first{
  2640. viewWidthConstraint.constant = newWidth
  2641. }
  2642. // update width constraint value for container view
  2643. if let containerViewWidthConstraint = alert.view.subviews.first?.constraints.filter({ return $0.firstAttribute == .width }).first {
  2644. containerViewWidthConstraint.constant = newWidth
  2645. }
  2646. let titleFont = [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 18), NSAttributedString.Key.foregroundColor: UIColor.black]
  2647. let titleAttrString = NSMutableAttributedString(string: "Call Center".localized(), attributes: titleFont)
  2648. alert.setValue(titleAttrString, forKey: "attributedTitle")
  2649. alert.view.subviews.first?.subviews.first?.subviews.first?.backgroundColor = .lightGray
  2650. alert.view.tintColor = .black
  2651. let rejectAction = UIAlertAction(title: "Pass to other representative".localized(), style: .destructive, handler: {(_) in
  2652. DispatchQueue.global().async {
  2653. _ = Nexilis.write(message: CoreMessage_TMessageBank.timeOutRequestCallCenter(channel: message.getBody(key: CoreMessage_TMessageKey.CHANNEL), l_pin: message.getBody(key: CoreMessage_TMessageKey.L_PIN)))
  2654. }
  2655. Nexilis.onGoingPushCC.removeAll()
  2656. alert.dismiss(animated: true, completion: nil)
  2657. })
  2658. let acceptAction = UIAlertAction(title: "I'll handle the customer".localized(), style: .default, handler: {(_) in
  2659. let goAudioCall = Nexilis.checkMicPermission()
  2660. if !goAudioCall && message.getBody(key: CoreMessage_TMessageKey.CHANNEL) == "1" {
  2661. let alert = LibAlertController(title: "Attention!".localized(), message: "Please allow microphone permission in your settings".localized(), preferredStyle: .alert)
  2662. alert.addAction(UIAlertAction(title: "OK".localized(), style: UIAlertAction.Style.default, handler: { _ in
  2663. if let url = URL(string: UIApplication.openSettingsURLString), UIApplication.shared.canOpenURL(url) {
  2664. UIApplication.shared.open(url, options: [:], completionHandler: nil)
  2665. }
  2666. }))
  2667. if UIApplication.shared.visibleViewController?.navigationController != nil {
  2668. UIApplication.shared.visibleViewController?.navigationController?.present(alert, animated: true, completion: nil)
  2669. } else {
  2670. UIApplication.shared.visibleViewController?.present(alert, animated: true, completion: nil)
  2671. }
  2672. DispatchQueue.global().async {
  2673. DispatchQueue.global().async {
  2674. _ = Nexilis.write(message: CoreMessage_TMessageBank.timeOutRequestCallCenter(channel: message.getBody(key: CoreMessage_TMessageKey.CHANNEL), l_pin: message.getBody(key: CoreMessage_TMessageKey.L_PIN)))
  2675. }
  2676. }
  2677. Nexilis.onGoingPushCC.removeAll()
  2678. return
  2679. }
  2680. if message.getBody(key: CoreMessage_TMessageKey.CHANNEL) == "2" {
  2681. var permissionCheck = -1
  2682. if AVCaptureDevice.authorizationStatus(for: .video) == .authorized {
  2683. permissionCheck = 1
  2684. } else if AVCaptureDevice.authorizationStatus(for: .video) == .denied {
  2685. permissionCheck = 0
  2686. } else {
  2687. Nexilis.dispatch = DispatchGroup()
  2688. Nexilis.dispatch?.enter()
  2689. AVCaptureDevice.requestAccess(for: .video, completionHandler: { (granted: Bool) -> Void in
  2690. if granted == true {
  2691. permissionCheck = 1
  2692. } else {
  2693. permissionCheck = 0
  2694. }
  2695. if let dispatch = Nexilis.dispatch {
  2696. dispatch.leave()
  2697. }
  2698. })
  2699. Nexilis.dispatch?.wait()
  2700. Nexilis.dispatch = nil
  2701. }
  2702. if permissionCheck == 0 {
  2703. let alert = LibAlertController(title: "Attention!".localized(), message: "Please allow camera permission in your settings".localized(), preferredStyle: .alert)
  2704. alert.addAction(UIAlertAction(title: "OK".localized(), style: UIAlertAction.Style.default, handler: { _ in
  2705. if let url = URL(string: UIApplication.openSettingsURLString), UIApplication.shared.canOpenURL(url) {
  2706. UIApplication.shared.open(url, options: [:], completionHandler: nil)
  2707. }
  2708. }))
  2709. if UIApplication.shared.visibleViewController?.navigationController != nil {
  2710. UIApplication.shared.visibleViewController?.navigationController?.present(alert, animated: true, completion: nil)
  2711. } else {
  2712. UIApplication.shared.visibleViewController?.present(alert, animated: true, completion: nil)
  2713. }
  2714. DispatchQueue.global().async {
  2715. DispatchQueue.global().async {
  2716. _ = Nexilis.write(message: CoreMessage_TMessageBank.timeOutRequestCallCenter(channel: message.getBody(key: CoreMessage_TMessageKey.CHANNEL), l_pin: message.getBody(key: CoreMessage_TMessageKey.L_PIN)))
  2717. }
  2718. }
  2719. Nexilis.onGoingPushCC.removeAll()
  2720. return
  2721. }
  2722. }
  2723. if UIApplication.shared.visibleViewController is UINavigationController {
  2724. let nc = UIApplication.shared.visibleViewController as! UINavigationController
  2725. if nc.visibleViewController is QmeraStreamingViewController {
  2726. let vc = nc.visibleViewController as! QmeraStreamingViewController
  2727. var alert = LibAlertController(title: "", message: "Are you sure you want to end Live Streaming, and open notification?".localized(), preferredStyle: .alert)
  2728. if !vc.isLive {
  2729. alert = LibAlertController(title: "", message: "Are you sure you want to leave Live Streaming, and open notification?".localized(), preferredStyle: .alert)
  2730. }
  2731. alert.addAction(UIAlertAction(title: "No".localized(), style: UIAlertAction.Style.default, handler: { _ in
  2732. DispatchQueue.global().async {
  2733. _ = Nexilis.write(message: CoreMessage_TMessageBank.timeOutRequestCallCenter(channel: message.getBody(key: CoreMessage_TMessageKey.CHANNEL), l_pin: message.getBody(key: CoreMessage_TMessageKey.L_PIN)))
  2734. }
  2735. Nexilis.onGoingPushCC.removeAll()
  2736. alert.dismiss(animated: true, completion: nil)
  2737. }))
  2738. alert.addAction(UIAlertAction(title: "Yes".localized(), style: UIAlertAction.Style.default, handler: { _ in
  2739. DispatchQueue.global().async {
  2740. API.terminateBC(sBroadcasterID: vc.isLive ? nil : vc.data)
  2741. vc.sendLeft()
  2742. }
  2743. vc.dismiss(animated: true, completion: {
  2744. acceptCC()
  2745. })
  2746. }))
  2747. nc.present(alert, animated: true, completion: nil)
  2748. // NotificationCenter.default.post(name: NSNotification.Name(rawValue: "isRunningStreaming"), object: nil, userInfo: dataMessage)
  2749. } else if nc.visibleViewController is SeminarViewController {
  2750. let vc = nc.visibleViewController as! SeminarViewController
  2751. var alert = LibAlertController(title: "", message: "Are you sure you want to end Seminar, and open notification?".localized(), preferredStyle: .alert)
  2752. if !vc.isLive {
  2753. alert = LibAlertController(title: "", message: "Are you sure you want to leave Seminar, and open notification?".localized(), preferredStyle: .alert)
  2754. }
  2755. alert.addAction(UIAlertAction(title: "No".localized(), style: UIAlertAction.Style.default, handler: { _ in
  2756. DispatchQueue.global().async {
  2757. _ = Nexilis.write(message: CoreMessage_TMessageBank.timeOutRequestCallCenter(channel: message.getBody(key: CoreMessage_TMessageKey.CHANNEL), l_pin: message.getBody(key: CoreMessage_TMessageKey.L_PIN)))
  2758. }
  2759. Nexilis.onGoingPushCC.removeAll()
  2760. alert.dismiss(animated: true, completion: nil)
  2761. }))
  2762. alert.addAction(UIAlertAction(title: "Yes".localized(), style: UIAlertAction.Style.default, handler: { _ in
  2763. DispatchQueue.global().async {
  2764. API.terminateBC(sBroadcasterID: vc.isLive ? nil : vc.data)
  2765. vc.sendLeft()
  2766. }
  2767. vc.dismiss(animated: true, completion: {
  2768. acceptCC()
  2769. })
  2770. }))
  2771. nc.present(alert, animated: true, completion: nil)
  2772. // NotificationCenter.default.post(name: NSNotification.Name(rawValue: "isRunningStreaming"), object: nil, userInfo: dataMessage)
  2773. } else {
  2774. acceptCC()
  2775. }
  2776. } else {
  2777. acceptCC()
  2778. }
  2779. func acceptCC() {
  2780. 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))) {
  2781. if (response.getBody(key: CoreMessage_TMessageKey.ERRCOD, default_value: "99") == "00") {
  2782. Nexilis.onGoingPushCC.removeAll()
  2783. let complaintId = response.getBody(key: CoreMessage_TMessageKey.DATA, default_value: "")
  2784. if !complaintId.isEmpty {
  2785. alert.dismiss(animated: true, completion: nil)
  2786. let idMe = User.getMyPin()!
  2787. SecureUserDefaults.shared.set("\(message.getBody(key: CoreMessage_TMessageKey.L_PIN)),\(idMe),\(complaintId)", forKey: "onGoingCC")
  2788. SecureUserDefaults.shared.set("\(message.getBody(key: CoreMessage_TMessageKey.L_PIN))", forKey: "membersCC")
  2789. if message.getBody(key: CoreMessage_TMessageKey.CHANNEL) == "0" {
  2790. let editorPersonalVC = AppStoryBoard.Palio.instance.instantiateViewController(identifier: "editorPersonalVC") as! EditorPersonal
  2791. editorPersonalVC.isContactCenter = true
  2792. editorPersonalVC.isRequestContactCenter = false
  2793. editorPersonalVC.unique_l_pin = message.getBody(key: CoreMessage_TMessageKey.L_PIN)
  2794. editorPersonalVC.complaintId = complaintId
  2795. editorPersonalVC.channelContactCenter = message.getBody(key: CoreMessage_TMessageKey.CHANNEL)
  2796. editorPersonalVC.fPinContacCenter = message.getBody(key: CoreMessage_TMessageKey.L_PIN)
  2797. let navigationController = CustomNavigationController(rootViewController: editorPersonalVC)
  2798. navigationController.modalPresentationStyle = .fullScreen
  2799. navigationController.navigationBar.tintColor = .white
  2800. navigationController.navigationBar.barTintColor = UIApplication.shared.visibleViewController?.traitCollection.userInterfaceStyle == .dark ? .blackDarkMode : .mainColor
  2801. navigationController.navigationBar.isTranslucent = false
  2802. navigationController.navigationBar.overrideUserInterfaceStyle = .dark
  2803. navigationController.navigationBar.barStyle = .black
  2804. let cancelButtonAttributes: [NSAttributedString.Key: Any] = [NSAttributedString.Key.foregroundColor: UIColor.white, NSAttributedString.Key.font : UIFont.systemFont(ofSize: 16)]
  2805. UIBarButtonItem.appearance().setTitleTextAttributes(cancelButtonAttributes, for: .normal)
  2806. let textAttributes = [NSAttributedString.Key.foregroundColor:UIColor.white]
  2807. navigationController.navigationBar.titleTextAttributes = textAttributes
  2808. if UIApplication.shared.visibleViewController?.navigationController != nil {
  2809. UIApplication.shared.visibleViewController?.navigationController?.present(navigationController, animated: true, completion: nil)
  2810. } else {
  2811. UIApplication.shared.visibleViewController?.present(navigationController, animated: true, completion: nil)
  2812. }
  2813. } else {
  2814. SecureUserDefaults.shared.set("\(Date().currentTimeMillis())", forKey: "startTimeCC")
  2815. DispatchQueue.main.asyncAfter(deadline: .now() + 1, execute: {
  2816. if message.getBody(key: CoreMessage_TMessageKey.CHANNEL) == "1" {
  2817. let pin = message.getBody(key: CoreMessage_TMessageKey.L_PIN)
  2818. let controller = QmeraAudioViewController()
  2819. controller.user = User.getData(pin: pin)
  2820. controller.isOutgoing = true
  2821. controller.ticketId = complaintId
  2822. controller.modalPresentationStyle = .overCurrentContext
  2823. let navigationController = CustomNavigationController(rootViewController: controller)
  2824. navigationController.modalPresentationStyle = .fullScreen
  2825. if UIApplication.shared.visibleViewController?.navigationController != nil {
  2826. UIApplication.shared.visibleViewController?.navigationController?.present(navigationController, animated: true, completion: nil)
  2827. } else {
  2828. UIApplication.shared.visibleViewController?.present(navigationController, animated: true, completion: nil)
  2829. }
  2830. } else if message.getBody(key: CoreMessage_TMessageKey.CHANNEL) == "2" {
  2831. let videoVC = AppStoryBoard.Palio.instance.instantiateViewController(withIdentifier: "videoVCQmera") as! QmeraVideoViewController
  2832. videoVC.fPin = message.getBody(key: CoreMessage_TMessageKey.L_PIN)
  2833. videoVC.users.append(User.getData(pin: message.getBody(key: CoreMessage_TMessageKey.L_PIN))!)
  2834. videoVC.ticketId = complaintId
  2835. let navigationController = CustomNavigationController(rootViewController: videoVC)
  2836. navigationController.modalPresentationStyle = .fullScreen
  2837. if UIApplication.shared.visibleViewController?.navigationController != nil {
  2838. UIApplication.shared.visibleViewController?.navigationController?.present(navigationController, animated: true, completion: nil)
  2839. } else {
  2840. UIApplication.shared.visibleViewController?.present(navigationController, animated: true, completion: nil)
  2841. }
  2842. }
  2843. })
  2844. }
  2845. }
  2846. }
  2847. }
  2848. }
  2849. })
  2850. alert.addAction(acceptAction)
  2851. alert.addAction(rejectAction)
  2852. let containerView = UIView(frame: CGRect(x: 20, y: 60, width: alert.view.bounds.size.width * 0.9 - 40, height: 150))
  2853. alert.view.addSubview(containerView)
  2854. containerView.layer.cornerRadius = 10.0
  2855. containerView.clipsToBounds = true
  2856. containerView.backgroundColor = .secondaryColor.withAlphaComponent(0.5)
  2857. let imageProfile = UIImageView()
  2858. containerView.addSubview(imageProfile)
  2859. imageProfile.translatesAutoresizingMaskIntoConstraints = false
  2860. NSLayoutConstraint.activate([
  2861. imageProfile.topAnchor.constraint(equalTo: containerView.topAnchor, constant: 10),
  2862. imageProfile.bottomAnchor.constraint(equalTo: containerView.bottomAnchor, constant: -10),
  2863. imageProfile.leadingAnchor.constraint(equalTo: containerView.leadingAnchor, constant: 10),
  2864. imageProfile.widthAnchor.constraint(equalToConstant: 100)
  2865. ])
  2866. imageProfile.layer.cornerRadius = 10.0
  2867. imageProfile.clipsToBounds = true
  2868. imageProfile.backgroundColor = .lightGray.withAlphaComponent(0.3)
  2869. imageProfile.tintColor = .secondaryColor
  2870. imageProfile.image = UIImage(systemName: "person")
  2871. if message.getBody(key: CoreMessage_TMessageKey.THUMB_ID) != "" {
  2872. imageProfile.setImage(name: message.getBody(key: CoreMessage_TMessageKey.THUMB_ID))
  2873. imageProfile.contentMode = .scaleAspectFill
  2874. }
  2875. let labelName = UILabel()
  2876. containerView.addSubview(labelName)
  2877. labelName.translatesAutoresizingMaskIntoConstraints = false
  2878. NSLayoutConstraint.activate([
  2879. labelName.topAnchor.constraint(equalTo: containerView.topAnchor, constant: 15),
  2880. labelName.leadingAnchor.constraint(equalTo: imageProfile.trailingAnchor, constant: 5)
  2881. ])
  2882. labelName.font = UIFont.systemFont(ofSize: 12)
  2883. labelName.text = "Name".localized()
  2884. labelName.textColor = .mainColor
  2885. let valueName = UILabel()
  2886. containerView.addSubview(valueName)
  2887. valueName.translatesAutoresizingMaskIntoConstraints = false
  2888. NSLayoutConstraint.activate([
  2889. valueName.topAnchor.constraint(equalTo: labelName.bottomAnchor),
  2890. valueName.leadingAnchor.constraint(equalTo: imageProfile.trailingAnchor, constant: 5)
  2891. ])
  2892. valueName.font = UIFont.systemFont(ofSize: 12)
  2893. valueName.text = message.getBody(key: CoreMessage_TMessageKey.F_DISPLAY_NAME)
  2894. valueName.textColor = .mainColor
  2895. let labelType = UILabel()
  2896. containerView.addSubview(labelType)
  2897. labelType.translatesAutoresizingMaskIntoConstraints = false
  2898. NSLayoutConstraint.activate([
  2899. labelType.topAnchor.constraint(equalTo: valueName.bottomAnchor, constant: 5),
  2900. labelType.leadingAnchor.constraint(equalTo: imageProfile.trailingAnchor, constant: 5)
  2901. ])
  2902. labelType.font = UIFont.systemFont(ofSize: 12)
  2903. labelType.text = "Request Type".localized()
  2904. labelType.textColor = .mainColor
  2905. let valueType = UILabel()
  2906. containerView.addSubview(valueType)
  2907. valueType.translatesAutoresizingMaskIntoConstraints = false
  2908. NSLayoutConstraint.activate([
  2909. valueType.topAnchor.constraint(equalTo: labelType.bottomAnchor),
  2910. valueType.leadingAnchor.constraint(equalTo: imageProfile.trailingAnchor, constant: 5)
  2911. ])
  2912. valueType.font = UIFont.systemFont(ofSize: 12)
  2913. if message.getBody(key: CoreMessage_TMessageKey.CHANNEL) == "0" {
  2914. valueType.text = "Chat".localized()
  2915. } else if message.getBody(key: CoreMessage_TMessageKey.CHANNEL) == "1" {
  2916. valueType.text = "Audio Call".localized()
  2917. } else if message.getBody(key: CoreMessage_TMessageKey.CHANNEL) == "2" {
  2918. valueType.text = "Video Call".localized()
  2919. } else {
  2920. valueType.text = "Email".localized()
  2921. }
  2922. valueType.textColor = .mainColor
  2923. let labelIdentity = UILabel()
  2924. containerView.addSubview(labelIdentity)
  2925. labelIdentity.translatesAutoresizingMaskIntoConstraints = false
  2926. NSLayoutConstraint.activate([
  2927. labelIdentity.topAnchor.constraint(equalTo: valueType.bottomAnchor, constant: 5),
  2928. labelIdentity.leadingAnchor.constraint(equalTo: imageProfile.trailingAnchor, constant: 5)
  2929. ])
  2930. labelIdentity.font = UIFont.systemFont(ofSize: 12)
  2931. labelIdentity.text = "Complaint ID".localized()
  2932. labelIdentity.textColor = .mainColor
  2933. let valueIdentity = UILabel()
  2934. containerView.addSubview(valueIdentity)
  2935. valueIdentity.translatesAutoresizingMaskIntoConstraints = false
  2936. NSLayoutConstraint.activate([
  2937. valueIdentity.topAnchor.constraint(equalTo: labelIdentity.bottomAnchor),
  2938. valueIdentity.leadingAnchor.constraint(equalTo: imageProfile.trailingAnchor, constant: 5),
  2939. valueIdentity.trailingAnchor.constraint(equalTo: containerView.trailingAnchor)
  2940. ])
  2941. valueIdentity.font = UIFont.systemFont(ofSize: 12)
  2942. valueIdentity.text = message.getBody(key: CoreMessage_TMessageKey.DATA)
  2943. valueIdentity.numberOfLines = 0
  2944. valueIdentity.textColor = .mainColor
  2945. var isShowAlert: Int?
  2946. let canShow = UIApplication.shared.visibleViewController
  2947. if canShow != nil && !(canShow is UINavigationController) {
  2948. if !(canShow is EditorPersonal) && !(canShow is QmeraAudioViewController) && !(canShow is QmeraVideoViewController) {
  2949. isShowAlert = 0
  2950. } else {
  2951. isShowAlert = 3
  2952. }
  2953. } else if canShow != nil {
  2954. if canShow is UINavigationController {
  2955. let canShowNC = canShow as! UINavigationController
  2956. if !(canShowNC.visibleViewController is EditorPersonal) && !(canShowNC.visibleViewController is QmeraAudioViewController) && !(canShowNC.visibleViewController is QmeraVideoViewController) {
  2957. isShowAlert = 0
  2958. } else {
  2959. isShowAlert = 3
  2960. }
  2961. } else {
  2962. isShowAlert = 0
  2963. }
  2964. }
  2965. DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(isShowAlert!), execute: {
  2966. if UIApplication.shared.visibleViewController?.navigationController != nil {
  2967. UIApplication.shared.visibleViewController?.navigationController?.present(alert, animated: true, completion: nil)
  2968. } else {
  2969. UIApplication.shared.visibleViewController?.present(alert, animated: true, completion: nil)
  2970. }
  2971. })
  2972. }
  2973. } else if message.getCode() == CoreMessage_TMessageCode.ACCEPT_CALL_CENTER {
  2974. let fPinContacCenter = message.getBody(key: CoreMessage_TMessageKey.F_PIN)
  2975. let requester = message.getBody(key: CoreMessage_TMessageKey.UPLINE_PIN)
  2976. let complaintId = message.getBody(key: CoreMessage_TMessageKey.DATA)
  2977. let onGoingCC: String = SecureUserDefaults.shared.value(forKey: "onGoingCC") ?? ""
  2978. if !requester.isEmpty && onGoingCC.isEmpty {
  2979. SecureUserDefaults.shared.set("\(requester),\(fPinContacCenter),\(complaintId)", forKey: "onGoingCC")
  2980. SecureUserDefaults.shared.set("\(fPinContacCenter)", forKey: "membersCC")
  2981. }
  2982. } else if message.getCode() == CoreMessage_TMessageCode.INVITE_TO_ROOM_CONTACT_CENTER {
  2983. if listCCIdInv.contains(message.getBody(key: CoreMessage_TMessageKey.CALL_CENTER_ID)) {
  2984. return
  2985. }
  2986. listCCIdInv.append(message.getBody(key: CoreMessage_TMessageKey.CALL_CENTER_ID))
  2987. DispatchQueue.main.async {
  2988. let alert = LibAlertController(title: "", message: "\n\n\n\n\n\n\n\n\n\n".localized(), preferredStyle: .alert)
  2989. let newWidth = UIScreen.main.bounds.width * 0.90 - 270
  2990. // update width constraint value for main view
  2991. if let viewWidthConstraint = alert.view.constraints.filter({ return $0.firstAttribute == .width }).first{
  2992. viewWidthConstraint.constant = newWidth
  2993. }
  2994. // update width constraint value for container view
  2995. if let containerViewWidthConstraint = alert.view.subviews.first?.constraints.filter({ return $0.firstAttribute == .width }).first {
  2996. containerViewWidthConstraint.constant = newWidth
  2997. }
  2998. let titleFont = [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 18), NSAttributedString.Key.foregroundColor: UIColor.black]
  2999. let titleAttrString = NSMutableAttributedString(string: "You're invited to\nCall Center".localized(), attributes: titleFont)
  3000. alert.setValue(titleAttrString, forKey: "attributedTitle")
  3001. alert.view.subviews.first?.subviews.first?.subviews.first?.backgroundColor = .lightGray
  3002. alert.view.tintColor = .black
  3003. let rejectAction = UIAlertAction(title: "Reject".localized(), style: .destructive, handler: {(_) in
  3004. listCCIdInv.removeAll(where: {$0 == message.getBody(key: CoreMessage_TMessageKey.CALL_CENTER_ID)})
  3005. DispatchQueue.global().async {
  3006. 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))) {
  3007. if result.isOk() {
  3008. return
  3009. }
  3010. }
  3011. }
  3012. alert.dismiss(animated: true, completion: nil)
  3013. })
  3014. let acceptAction = UIAlertAction(title: "Accept".localized(), style: .default, handler: {(_) in
  3015. listCCIdInv.removeAll(where: {$0 == message.getBody(key: CoreMessage_TMessageKey.CALL_CENTER_ID)})
  3016. let goAudioCall = Nexilis.checkMicPermission()
  3017. if !goAudioCall && message.getBody(key: CoreMessage_TMessageKey.CHANNEL) == "1" {
  3018. let alert = LibAlertController(title: "Attention!".localized(), message: "Please allow microphone permission in your settings".localized(), preferredStyle: .alert)
  3019. alert.addAction(UIAlertAction(title: "OK".localized(), style: UIAlertAction.Style.default, handler: { _ in
  3020. if let url = URL(string: UIApplication.openSettingsURLString), UIApplication.shared.canOpenURL(url) {
  3021. UIApplication.shared.open(url, options: [:], completionHandler: nil)
  3022. }
  3023. }))
  3024. if UIApplication.shared.visibleViewController?.navigationController != nil {
  3025. UIApplication.shared.visibleViewController?.navigationController?.present(alert, animated: true, completion: nil)
  3026. } else {
  3027. UIApplication.shared.visibleViewController?.present(alert, animated: true, completion: nil)
  3028. }
  3029. DispatchQueue.global().async {
  3030. 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))) {
  3031. if result.isOk() {
  3032. return
  3033. }
  3034. }
  3035. }
  3036. return
  3037. }
  3038. if message.getBody(key: CoreMessage_TMessageKey.CHANNEL) == "2" {
  3039. var permissionCheck = -1
  3040. if AVCaptureDevice.authorizationStatus(for: .video) == .authorized {
  3041. permissionCheck = 1
  3042. } else if AVCaptureDevice.authorizationStatus(for: .video) == .denied {
  3043. permissionCheck = 0
  3044. } else {
  3045. Nexilis.dispatch = DispatchGroup()
  3046. Nexilis.dispatch?.enter()
  3047. AVCaptureDevice.requestAccess(for: .video, completionHandler: { (granted: Bool) -> Void in
  3048. if granted == true {
  3049. permissionCheck = 1
  3050. } else {
  3051. permissionCheck = 0
  3052. }
  3053. if let dispatch = Nexilis.dispatch {
  3054. dispatch.leave()
  3055. }
  3056. })
  3057. Nexilis.dispatch?.wait()
  3058. Nexilis.dispatch = nil
  3059. }
  3060. if permissionCheck == 0 {
  3061. let alert = LibAlertController(title: "Attention!".localized(), message: "Please allow camera permission in your settings".localized(), preferredStyle: .alert)
  3062. alert.addAction(UIAlertAction(title: "OK".localized(), style: UIAlertAction.Style.default, handler: { _ in
  3063. if let url = URL(string: UIApplication.openSettingsURLString), UIApplication.shared.canOpenURL(url) {
  3064. UIApplication.shared.open(url, options: [:], completionHandler: nil)
  3065. }
  3066. }))
  3067. if UIApplication.shared.visibleViewController?.navigationController != nil {
  3068. UIApplication.shared.visibleViewController?.navigationController?.present(alert, animated: true, completion: nil)
  3069. } else {
  3070. UIApplication.shared.visibleViewController?.present(alert, animated: true, completion: nil)
  3071. }
  3072. DispatchQueue.global().async {
  3073. 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))) {
  3074. if result.isOk() {
  3075. return
  3076. }
  3077. }
  3078. }
  3079. return
  3080. }
  3081. }
  3082. if UIApplication.shared.visibleViewController is UINavigationController {
  3083. let nc = UIApplication.shared.visibleViewController as! UINavigationController
  3084. if nc.visibleViewController is QmeraStreamingViewController {
  3085. let vc = nc.visibleViewController as! QmeraStreamingViewController
  3086. var alert = LibAlertController(title: "", message: "Are you sure you want to end Live Streaming, and open notification?".localized(), preferredStyle: .alert)
  3087. if !vc.isLive {
  3088. alert = LibAlertController(title: "", message: "Are you sure you want to leave Live Streaming, and open notification?".localized(), preferredStyle: .alert)
  3089. }
  3090. alert.addAction(UIAlertAction(title: "No".localized(), style: UIAlertAction.Style.default, handler: { _ in
  3091. DispatchQueue.global().async {
  3092. 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))) {
  3093. if result.isOk() {
  3094. return
  3095. }
  3096. }
  3097. }
  3098. alert.dismiss(animated: true, completion: nil)
  3099. }))
  3100. alert.addAction(UIAlertAction(title: "Yes".localized(), style: UIAlertAction.Style.default, handler: { _ in
  3101. DispatchQueue.global().async {
  3102. API.terminateBC(sBroadcasterID: vc.isLive ? nil : vc.data)
  3103. vc.sendLeft()
  3104. }
  3105. vc.dismiss(animated: true, completion: {
  3106. acceptCC()
  3107. })
  3108. }))
  3109. nc.present(alert, animated: true, completion: nil)
  3110. } else if nc.visibleViewController is SeminarViewController {
  3111. let vc = nc.visibleViewController as! SeminarViewController
  3112. var alert = LibAlertController(title: "", message: "Are you sure you want to end Seminar, and open notification?".localized(), preferredStyle: .alert)
  3113. if !vc.isLive {
  3114. alert = LibAlertController(title: "", message: "Are you sure you want to leave Seminar, and open notification?".localized(), preferredStyle: .alert)
  3115. }
  3116. alert.addAction(UIAlertAction(title: "No".localized(), style: UIAlertAction.Style.default, handler: { _ in
  3117. DispatchQueue.global().async {
  3118. 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))) {
  3119. if result.isOk() {
  3120. return
  3121. }
  3122. }
  3123. }
  3124. alert.dismiss(animated: true, completion: nil)
  3125. }))
  3126. alert.addAction(UIAlertAction(title: "Yes".localized(), style: UIAlertAction.Style.default, handler: { _ in
  3127. DispatchQueue.global().async {
  3128. API.terminateBC(sBroadcasterID: vc.isLive ? nil : vc.data)
  3129. vc.sendLeft()
  3130. }
  3131. vc.dismiss(animated: true, completion: {
  3132. acceptCC()
  3133. })
  3134. }))
  3135. nc.present(alert, animated: true, completion: nil)
  3136. } else {
  3137. acceptCC()
  3138. }
  3139. } else {
  3140. acceptCC()
  3141. }
  3142. func acceptCC() {
  3143. 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))) {
  3144. if result.isOk() {
  3145. let requester = result.getBody(key: CoreMessage_TMessageKey.UPLINE_PIN)
  3146. let officer = result.getBody(key: CoreMessage_TMessageKey.FRIEND_FPIN)
  3147. let data = result.getBody(key: CoreMessage_TMessageKey.DATA)
  3148. let complaintId = message.getBody(key: CoreMessage_TMessageKey.CALL_CENTER_ID)
  3149. SecureUserDefaults.shared.set("\(requester),\(officer),\(complaintId)", forKey: "onGoingCC")
  3150. SecureUserDefaults.shared.set("\(Date().currentTimeMillis())", forKey: "startTimeCC")
  3151. if !data.isEmpty {
  3152. if let jsonArray = try! JSONSerialization.jsonObject(with: data.data(using: String.Encoding.utf8)!, options: JSONSerialization.ReadingOptions()) as? [AnyObject] {
  3153. var members = ""
  3154. var user : [User] = []
  3155. let idMe = User.getMyPin()!
  3156. for json in jsonArray {
  3157. if "\(json)" != idMe {
  3158. if let userData = User.getData(pin: "\(json)") {
  3159. user.append(userData)
  3160. } else {
  3161. Nexilis.addFriendSilent(fpin: "\(json)")
  3162. DispatchQueue.main.asyncAfter(deadline: .now() + 1, execute: {
  3163. if let userData = User.getData(pin: "\(json)") {
  3164. user.append(userData)
  3165. }
  3166. })
  3167. }
  3168. if members.isEmpty {
  3169. members = "\(json)"
  3170. } else {
  3171. members += ",\(json)"
  3172. }
  3173. }
  3174. }
  3175. SecureUserDefaults.shared.set("\(members)", forKey: "membersCC")
  3176. if message.getBody(key: CoreMessage_TMessageKey.CHANNEL) == "0" {
  3177. let editorPersonalVC = AppStoryBoard.Palio.instance.instantiateViewController(identifier: "editorPersonalVC") as! EditorPersonal
  3178. editorPersonalVC.hidesBottomBarWhenPushed = true
  3179. editorPersonalVC.unique_l_pin = officer
  3180. editorPersonalVC.fromNotification = true
  3181. editorPersonalVC.isContactCenter = true
  3182. editorPersonalVC.fPinContacCenter = members
  3183. editorPersonalVC.complaintId = complaintId
  3184. editorPersonalVC.onGoingCC = true
  3185. editorPersonalVC.isRequestContactCenter = false
  3186. editorPersonalVC.users = user
  3187. let navigationController = CustomNavigationController(rootViewController: editorPersonalVC)
  3188. navigationController.modalPresentationStyle = .fullScreen
  3189. navigationController.navigationBar.tintColor = .white
  3190. navigationController.navigationBar.barTintColor = UIApplication.shared.visibleViewController?.traitCollection.userInterfaceStyle == .dark ? .blackDarkMode : .mainColor
  3191. navigationController.navigationBar.isTranslucent = false
  3192. navigationController.navigationBar.overrideUserInterfaceStyle = .dark
  3193. navigationController.navigationBar.barStyle = .black
  3194. let cancelButtonAttributes: [NSAttributedString.Key: Any] = [NSAttributedString.Key.foregroundColor: UIColor.white, NSAttributedString.Key.font : UIFont.systemFont(ofSize: 16)]
  3195. UIBarButtonItem.appearance().setTitleTextAttributes(cancelButtonAttributes, for: .normal)
  3196. let textAttributes = [NSAttributedString.Key.foregroundColor:UIColor.white]
  3197. navigationController.navigationBar.titleTextAttributes = textAttributes
  3198. if UIApplication.shared.visibleViewController?.navigationController != nil {
  3199. UIApplication.shared.visibleViewController?.navigationController?.present(navigationController, animated: true, completion: nil)
  3200. } else {
  3201. UIApplication.shared.visibleViewController?.present(navigationController, animated: true, completion: nil)
  3202. }
  3203. } else {
  3204. SecureUserDefaults.shared.set("\(Date().currentTimeMillis())", forKey: "startTimeCC")
  3205. DispatchQueue.main.asyncAfter(deadline: .now() + 1, execute: {
  3206. if message.getBody(key: CoreMessage_TMessageKey.CHANNEL) == "1" {
  3207. let pin = officer
  3208. let controller = QmeraAudioViewController()
  3209. controller.user = User.getData(pin: pin)
  3210. controller.isOutgoing = false
  3211. controller.ticketId = complaintId
  3212. controller.modalPresentationStyle = .overCurrentContext
  3213. let navigationController = CustomNavigationController(rootViewController: controller)
  3214. navigationController.modalPresentationStyle = .fullScreen
  3215. if UIApplication.shared.visibleViewController?.navigationController != nil {
  3216. UIApplication.shared.visibleViewController?.navigationController?.present(navigationController, animated: true, completion: nil)
  3217. } else {
  3218. UIApplication.shared.visibleViewController?.present(navigationController, animated: true, completion: nil)
  3219. }
  3220. } else if message.getBody(key: CoreMessage_TMessageKey.CHANNEL) == "2" {
  3221. let videoVC = AppStoryBoard.Palio.instance.instantiateViewController(withIdentifier: "videoVCQmera") as! QmeraVideoViewController
  3222. videoVC.fPin = officer
  3223. videoVC.users.append(User.getData(pin: officer)!)
  3224. videoVC.ticketId = complaintId
  3225. videoVC.isInisiator = false
  3226. videoVC.isAutoAccept = true
  3227. let navigationController = CustomNavigationController(rootViewController: videoVC)
  3228. navigationController.modalPresentationStyle = .fullScreen
  3229. if UIApplication.shared.visibleViewController?.navigationController != nil {
  3230. UIApplication.shared.visibleViewController?.navigationController?.present(navigationController, animated: true, completion: nil)
  3231. } else {
  3232. UIApplication.shared.visibleViewController?.present(navigationController, animated: true, completion: nil)
  3233. }
  3234. }
  3235. })
  3236. }
  3237. }
  3238. }
  3239. } else {
  3240. let imageView = UIImageView(image: UIImage(systemName: "info.circle"))
  3241. imageView.tintColor = .white
  3242. 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)
  3243. banner.show()
  3244. }
  3245. }
  3246. }
  3247. })
  3248. alert.addAction(rejectAction)
  3249. alert.addAction(acceptAction)
  3250. let containerView = UIView(frame: CGRect(x: 50, y: 80, width: alert.view.bounds.size.width * 0.9 - 100, height: 150))
  3251. alert.view.addSubview(containerView)
  3252. containerView.layer.cornerRadius = 10.0
  3253. containerView.clipsToBounds = true
  3254. containerView.backgroundColor = .secondaryColor.withAlphaComponent(0.5)
  3255. let userData = User.getData(pin: message.getPIN())
  3256. let imageProfile = UIImageView()
  3257. containerView.addSubview(imageProfile)
  3258. imageProfile.translatesAutoresizingMaskIntoConstraints = false
  3259. NSLayoutConstraint.activate([
  3260. imageProfile.topAnchor.constraint(equalTo: containerView.topAnchor, constant: 10),
  3261. imageProfile.bottomAnchor.constraint(equalTo: containerView.bottomAnchor, constant: -10),
  3262. imageProfile.leadingAnchor.constraint(equalTo: containerView.leadingAnchor, constant: 10),
  3263. imageProfile.widthAnchor.constraint(equalToConstant: 100)
  3264. ])
  3265. imageProfile.layer.cornerRadius = 10.0
  3266. imageProfile.clipsToBounds = true
  3267. imageProfile.backgroundColor = .lightGray.withAlphaComponent(0.3)
  3268. imageProfile.tintColor = .secondaryColor
  3269. imageProfile.image = UIImage(systemName: "person")
  3270. if userData!.thumb != "" {
  3271. imageProfile.setImage(name: userData!.thumb)
  3272. imageProfile.contentMode = .scaleAspectFill
  3273. }
  3274. let labelName = UILabel()
  3275. containerView.addSubview(labelName)
  3276. labelName.translatesAutoresizingMaskIntoConstraints = false
  3277. NSLayoutConstraint.activate([
  3278. labelName.topAnchor.constraint(equalTo: containerView.topAnchor, constant: 15),
  3279. labelName.leadingAnchor.constraint(equalTo: imageProfile.trailingAnchor, constant: 5)
  3280. ])
  3281. labelName.font = UIFont.systemFont(ofSize: 12)
  3282. labelName.text = "Name".localized()
  3283. labelName.textColor = .mainColor
  3284. let valueName = UILabel()
  3285. containerView.addSubview(valueName)
  3286. valueName.translatesAutoresizingMaskIntoConstraints = false
  3287. NSLayoutConstraint.activate([
  3288. valueName.topAnchor.constraint(equalTo: labelName.bottomAnchor),
  3289. valueName.leadingAnchor.constraint(equalTo: imageProfile.trailingAnchor, constant: 5)
  3290. ])
  3291. valueName.font = UIFont.systemFont(ofSize: 12)
  3292. valueName.text = userData!.fullName
  3293. valueName.textColor = .mainColor
  3294. let labelType = UILabel()
  3295. containerView.addSubview(labelType)
  3296. labelType.translatesAutoresizingMaskIntoConstraints = false
  3297. NSLayoutConstraint.activate([
  3298. labelType.topAnchor.constraint(equalTo: valueName.bottomAnchor, constant: 5),
  3299. labelType.leadingAnchor.constraint(equalTo: imageProfile.trailingAnchor, constant: 5)
  3300. ])
  3301. labelType.font = UIFont.systemFont(ofSize: 12)
  3302. labelType.text = "Request Type".localized()
  3303. labelType.textColor = .mainColor
  3304. let valueType = UILabel()
  3305. containerView.addSubview(valueType)
  3306. valueType.translatesAutoresizingMaskIntoConstraints = false
  3307. NSLayoutConstraint.activate([
  3308. valueType.topAnchor.constraint(equalTo: labelType.bottomAnchor),
  3309. valueType.leadingAnchor.constraint(equalTo: imageProfile.trailingAnchor, constant: 5)
  3310. ])
  3311. valueType.font = UIFont.systemFont(ofSize: 12)
  3312. if message.getBody(key: CoreMessage_TMessageKey.CHANNEL) == "0" {
  3313. valueType.text = "Chat".localized()
  3314. } else if message.getBody(key: CoreMessage_TMessageKey.CHANNEL) == "1" {
  3315. valueType.text = "Audio Call".localized()
  3316. } else if message.getBody(key: CoreMessage_TMessageKey.CHANNEL) == "2" {
  3317. valueType.text = "Video Call".localized()
  3318. } else {
  3319. valueType.text = "Email".localized()
  3320. }
  3321. valueType.textColor = .mainColor
  3322. let labelIdentity = UILabel()
  3323. containerView.addSubview(labelIdentity)
  3324. labelIdentity.translatesAutoresizingMaskIntoConstraints = false
  3325. NSLayoutConstraint.activate([
  3326. labelIdentity.topAnchor.constraint(equalTo: valueType.bottomAnchor, constant: 5),
  3327. labelIdentity.leadingAnchor.constraint(equalTo: imageProfile.trailingAnchor, constant: 5)
  3328. ])
  3329. labelIdentity.font = UIFont.systemFont(ofSize: 12)
  3330. labelIdentity.text = "Complaint ID".localized()
  3331. labelIdentity.textColor = .mainColor
  3332. let valueIdentity = UILabel()
  3333. containerView.addSubview(valueIdentity)
  3334. valueIdentity.translatesAutoresizingMaskIntoConstraints = false
  3335. NSLayoutConstraint.activate([
  3336. valueIdentity.topAnchor.constraint(equalTo: labelIdentity.bottomAnchor),
  3337. valueIdentity.leadingAnchor.constraint(equalTo: imageProfile.trailingAnchor, constant: 5),
  3338. valueIdentity.trailingAnchor.constraint(equalTo: containerView.trailingAnchor)
  3339. ])
  3340. valueIdentity.font = UIFont.systemFont(ofSize: 12)
  3341. valueIdentity.text = message.getBody(key: CoreMessage_TMessageKey.CALL_CENTER_ID)
  3342. valueIdentity.numberOfLines = 0
  3343. valueIdentity.textColor = .mainColor
  3344. if UIApplication.shared.visibleViewController?.navigationController != nil {
  3345. UIApplication.shared.visibleViewController?.navigationController?.present(alert, animated: true, completion: nil)
  3346. } else {
  3347. UIApplication.shared.visibleViewController?.present(alert, animated: true, completion: nil)
  3348. }
  3349. }
  3350. } 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 {
  3351. let m = message.mBodies
  3352. if !message.getBody(key: CoreMessage_TMessageKey.MERCHANT_NAME).isEmpty {
  3353. // Utils.setDebugBC(value: m)
  3354. DispatchQueue.main.async {
  3355. if !Nexilis.broadcastList.isEmpty {
  3356. Nexilis.broadcastList.append(m)
  3357. } else {
  3358. Nexilis.broadcastList.append(m)
  3359. Nexilis.shared.showBroadcastMessage(m: m)
  3360. }
  3361. }
  3362. return
  3363. }
  3364. if !Nexilis.showLibraryNotification || APIS.checkAppStateisBackground() {
  3365. return
  3366. }
  3367. let sender = message.getBody(key: CoreMessage_TMessageKey.F_PIN)
  3368. let me = User.getMyPin()!
  3369. if(sender != me) {
  3370. let inEditorPersonal: String? = SecureUserDefaults.shared.value(forKey: "inEditorPersonal") ?? nil
  3371. let inEditorGroup: [String]? = SecureUserDefaults.shared.value(forKey: "inEditorGroup") ?? nil
  3372. var text = message.getBody(key: CoreMessage_TMessageKey.MESSAGE_TEXT)
  3373. let imageId = CoreMessage_TMessageKey.IMAGE_ID
  3374. let videoId = CoreMessage_TMessageKey.VIDEO_ID
  3375. let fileId = CoreMessage_TMessageKey.FILE_ID
  3376. let audioId = CoreMessage_TMessageKey.AUDIO_ID
  3377. let attachmentFlag = CoreMessage_TMessageKey.ATTACHMENT_FLAG
  3378. let messageScopeId = CoreMessage_TMessageKey.MESSAGE_SCOPE_ID
  3379. let messageText = CoreMessage_TMessageKey.MESSAGE_TEXT
  3380. let credential = CoreMessage_TMessageKey.CREDENTIAL
  3381. let gif_id = CoreMessage_TMessageKey.GIF_ID
  3382. let is_secret = CoreMessage_TMessageKey.IS_SECRET
  3383. if message.getBody(key: is_secret) == "1" {
  3384. text = "You got messages..."
  3385. } else if message.getBody(key: gif_id) != "" {
  3386. text = "Sent GIF 🎬"
  3387. } else if !message.getBody(key: imageId).isEmpty {
  3388. text = "Sent Image 📷"
  3389. } else if message.getBody(key: attachmentFlag) == "11" {
  3390. text = "Sent Sticker ❤️"
  3391. } else if !message.getBody(key: videoId).isEmpty {
  3392. text = "Sent Video 📹"
  3393. } else if !message.getBody(key: fileId).isEmpty {
  3394. if message.getBody(key: messageScopeId) == "18" {
  3395. text = "Sent Form 📄"
  3396. } else {
  3397. text = "Sent File 📄"
  3398. }
  3399. } else if !message.getBody(key: audioId).isEmpty {
  3400. text = "Sent Audio ♫"
  3401. } else if message.getBody(key: messageText).contains("Share%20location%20") {
  3402. text = "Sent Location 📌"
  3403. } else if message.getBody(key: attachmentFlag) == "27" {
  3404. text = "Sent Live Streaming"
  3405. } else if message.getBody(key: attachmentFlag) == "26" {
  3406. text = "Sent Seminar"
  3407. } else if message.getBody(key: attachmentFlag) == "25" {
  3408. text = "Sent Video Conference Room"
  3409. } else if message.getBody(key: attachmentFlag) == "24" {
  3410. text = "Sent Quiz"
  3411. } else if message.getBody(key: credential) == "1" {
  3412. text = "Sent Confidential Message"
  3413. }
  3414. var nameUser: String?
  3415. var profile = ""
  3416. var threadIdentifier = sender
  3417. let onGoingCC: String = SecureUserDefaults.shared.value(forKey: "onGoingCC") ?? ""
  3418. if !onGoingCC.isEmpty {
  3419. return
  3420. }
  3421. if Utils.inTabChats{
  3422. return
  3423. }
  3424. if message.getBody(key: messageScopeId) == "3" || message.getBody(key: messageScopeId) == "18" || message.getBody(key: messageScopeId) == "5" {
  3425. if inEditorPersonal == sender || (inEditorPersonal != nil && inEditorPersonal!.contains(",")) {
  3426. return
  3427. }
  3428. if(nameUser == nil) {
  3429. Database.shared.database?.inTransaction({ (fmdb, rollback) in
  3430. do {
  3431. if let cursor = Database.shared.getRecords(fmdb: fmdb, query: "SELECT first_name, last_name, image_id FROM BUDDY WHERE f_pin='\(String(describing: sender))'") {
  3432. while cursor.next() {
  3433. let first_name = cursor.string(forColumnIndex: 0)!
  3434. let last_name = cursor.string(forColumnIndex: 1)!
  3435. nameUser = "\(first_name) \(last_name)".trimmingCharacters(in: .whitespaces)
  3436. profile = cursor.string(forColumnIndex: 2)!
  3437. }
  3438. cursor.close()
  3439. }
  3440. } catch {
  3441. rollback.pointee = true
  3442. print("Access database error: \(error.localizedDescription)")
  3443. }
  3444. })
  3445. }
  3446. } else {
  3447. let idGroup = message.getBody(key: CoreMessage_TMessageKey.L_PIN)
  3448. var topicGroup: String?
  3449. var idTopic: String?
  3450. if !message.getBody(key: CoreMessage_TMessageKey.CHAT_ID).isEmpty {
  3451. idTopic = message.getBody(key: CoreMessage_TMessageKey.CHAT_ID)
  3452. }
  3453. if (idTopic == nil) {
  3454. idTopic = "Lounge"
  3455. topicGroup = "Lounge"
  3456. } else {
  3457. Database.shared.database?.inTransaction({ (fmdb, rollback) in
  3458. do {
  3459. if let cursor = Database.shared.getRecords(fmdb: fmdb, query: "SELECT title FROM DISCUSSION_FORUM WHERE chat_id='\(idTopic!)'") {
  3460. while cursor.next() {
  3461. let title = cursor.string(forColumnIndex: 0)
  3462. topicGroup = title
  3463. }
  3464. cursor.close()
  3465. }
  3466. } catch {
  3467. rollback.pointee = true
  3468. print("Access database error: \(error.localizedDescription)")
  3469. }
  3470. })
  3471. }
  3472. if (inEditorGroup != nil) {
  3473. let editorIdGroup = inEditorGroup![0]
  3474. let editorIdTopic = inEditorGroup![1]
  3475. var idTempTopic = idTopic
  3476. if (idTempTopic == "Lounge") {
  3477. idTempTopic = ""
  3478. }
  3479. if (editorIdGroup == idGroup && editorIdTopic == idTempTopic) {
  3480. return
  3481. }
  3482. }
  3483. Database.shared.database?.inTransaction({ (fmdb, rollback) in
  3484. do {
  3485. if let cursor = Database.shared.getRecords(fmdb: fmdb, query: "SELECT f_name, image_id FROM GROUPZ WHERE group_id='\(idGroup)'") {
  3486. while cursor.next() {
  3487. let f_name = cursor.string(forColumnIndex: 0)
  3488. var senderName = message.getBody(key: CoreMessage_TMessageKey.F_DISPLAY_NAME)
  3489. if senderName.isEmpty {
  3490. senderName = "Bot"
  3491. }
  3492. nameUser =
  3493. "\(senderName) \u{2022} \(f_name!)(\(topicGroup!))"
  3494. profile = cursor.string(forColumnIndex: 1)!
  3495. }
  3496. cursor.close()
  3497. }
  3498. } catch {
  3499. rollback.pointee = true
  3500. print("Access database error: \(error.localizedDescription)")
  3501. }
  3502. })
  3503. if idTopic == "Lounge" {
  3504. threadIdentifier = idGroup
  3505. } else {
  3506. threadIdentifier = idTopic!
  3507. }
  3508. }
  3509. if nameUser == nil && threadIdentifier == "-999" {
  3510. nameUser = "Bot"
  3511. }
  3512. DispatchQueue.main.async { [self] in
  3513. let container = UIView()
  3514. container.backgroundColor = .gray
  3515. let profileImage = UIImageView()
  3516. profileImage.frame.size = CGSize(width: 60, height: 60)
  3517. container.addSubview(profileImage)
  3518. profileImage.translatesAutoresizingMaskIntoConstraints = false
  3519. NSLayoutConstraint.activate([
  3520. profileImage.leadingAnchor.constraint(equalTo: container.leadingAnchor, constant: 8.0),
  3521. profileImage.centerYAnchor.constraint(equalTo: container.centerYAnchor),
  3522. profileImage.widthAnchor.constraint(equalToConstant: 60),
  3523. profileImage.heightAnchor.constraint(equalToConstant: 60),
  3524. ])
  3525. let title = UILabel()
  3526. container.addSubview(title)
  3527. title.translatesAutoresizingMaskIntoConstraints = false
  3528. NSLayoutConstraint.activate([
  3529. title.leadingAnchor.constraint(equalTo: profileImage.trailingAnchor, constant: 8.0),
  3530. title.topAnchor.constraint(equalTo: container.topAnchor, constant: 20.0),
  3531. ])
  3532. title.font = UIFont.systemFont(ofSize: 14)
  3533. title.text = nameUser ?? "Unknown"
  3534. title.textColor = .white
  3535. let subtitle = UILabel()
  3536. container.addSubview(subtitle)
  3537. subtitle.translatesAutoresizingMaskIntoConstraints = false
  3538. NSLayoutConstraint.activate([
  3539. subtitle.leadingAnchor.constraint(equalTo: profileImage.trailingAnchor, constant: 8.0),
  3540. subtitle.trailingAnchor.constraint(equalTo: container.trailingAnchor, constant: -15.0),
  3541. subtitle.topAnchor.constraint(equalTo: title.bottomAnchor),
  3542. ])
  3543. subtitle.font = UIFont.systemFont(ofSize: 12)
  3544. subtitle.attributedText = text.richText()
  3545. subtitle.textColor = .white
  3546. if floating != nil {
  3547. return
  3548. }
  3549. displayNotif()
  3550. func displayNotif() {
  3551. floating = FloatingNotificationBanner(customView: container)
  3552. floating.bannerHeight = 100.0
  3553. floating.transparency = 0.9
  3554. if threadIdentifier == "-999" {
  3555. if !Utils.getIconDock().isEmpty {
  3556. 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
  3557. if dataImage != nil {
  3558. profileImage.image = UIImage(data: dataImage!)
  3559. }
  3560. } else {
  3561. profileImage.image = UIImage(named: "pb_button", in: Bundle.resourceBundle(for: Nexilis.self), with: nil)
  3562. }
  3563. } else if profile != "" {
  3564. profileImage.circle()
  3565. do {
  3566. let documentDir = try FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
  3567. let file = documentDir.appendingPathComponent(profile)
  3568. if FileManager().fileExists(atPath: file.path) {
  3569. profileImage.image = UIImage(contentsOfFile: file.path)
  3570. profileImage.backgroundColor = .clear
  3571. } else {
  3572. Download().startHTTP(forKey: profile) { (name, progress) in
  3573. guard progress == 100 else {
  3574. return
  3575. }
  3576. DispatchQueue.main.async { [self] in
  3577. profileImage.image = UIImage(contentsOfFile: file.path)
  3578. profileImage.backgroundColor = .clear
  3579. if !onGoingCC.isEmpty {
  3580. floating.autoDismiss = false
  3581. }
  3582. 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)
  3583. floating.onTap = {
  3584. self.floating = nil
  3585. showNotif()
  3586. }
  3587. var soundId: String = SecureUserDefaults.shared.value(forKey: "newNotifSoundPersonal") ?? "001:Nexilis Message (Default)"
  3588. if message.getBody(key: CoreMessage_TMessageKey.MESSAGE_SCOPE_ID) == "4" {
  3589. soundId = SecureUserDefaults.shared.value(forKey: "newNotifSoundGroup") ?? "001:Nexilis Message (Default)"
  3590. }
  3591. do {
  3592. var nameSound = soundId.components(separatedBy: ":")[1].replacingOccurrences(of: " ", with: "_")
  3593. if nameSound.contains("_(Default)") {
  3594. nameSound = nameSound.replacingOccurrences(of: "_(Default)", with: "")
  3595. }
  3596. var soundURL = Bundle.resourceBundle(for: Nexilis.self).url(forResource: nameSound, withExtension: "mp3")
  3597. if soundURL == nil {
  3598. soundURL = Bundle.resourcesMediaBundle(for: Nexilis.self).url(forResource: nameSound, withExtension: "mp3")
  3599. }
  3600. Nexilis.sharedAudioPlayer = try AVAudioPlayer(contentsOf: soundURL!)
  3601. Nexilis.sharedAudioPlayer?.prepareToPlay()
  3602. Nexilis.sharedAudioPlayer?.play()
  3603. DispatchQueue.main.asyncAfter(deadline: .now() + 3, execute: {
  3604. self.floating = nil
  3605. })
  3606. } catch {
  3607. }
  3608. }
  3609. }
  3610. return
  3611. }
  3612. } catch {}
  3613. profileImage.contentMode = .scaleAspectFill
  3614. } else {
  3615. profileImage.circle()
  3616. if message.getBody(key: messageScopeId) == "3" {
  3617. profileImage.image = UIImage(systemName: "person")
  3618. } else {
  3619. profileImage.image = UIImage(systemName: "person.3")
  3620. }
  3621. profileImage.contentMode = .scaleAspectFit
  3622. profileImage.backgroundColor = .lightGray
  3623. profileImage.tintColor = .white
  3624. }
  3625. print("SHOW KAH?0")
  3626. 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)
  3627. // let vibrateMode: Bool = SecureUserDefaults.shared.value(forKey: "vibrateMode") ?? false
  3628. var soundId: String = SecureUserDefaults.shared.value(forKey: "newNotifSoundPersonal") ?? "001:Nexilis Message (Default)"
  3629. if message.getBody(key: CoreMessage_TMessageKey.MESSAGE_SCOPE_ID) == "4" {
  3630. soundId = SecureUserDefaults.shared.value(forKey: "newNotifSoundGroup") ?? "001:Nexilis Message (Default)"
  3631. }
  3632. do {
  3633. var nameSound = soundId.components(separatedBy: ":")[1].replacingOccurrences(of: " ", with: "_")
  3634. if nameSound.contains("_(Default)") {
  3635. nameSound = nameSound.replacingOccurrences(of: "_(Default)", with: "")
  3636. }
  3637. var soundURL = Bundle.resourceBundle(for: Nexilis.self).url(forResource: nameSound, withExtension: "mp3")
  3638. if soundURL == nil {
  3639. soundURL = Bundle.resourcesMediaBundle(for: Nexilis.self).url(forResource: nameSound, withExtension: "mp3")
  3640. }
  3641. Nexilis.sharedAudioPlayer = try AVAudioPlayer(contentsOf: soundURL!)
  3642. Nexilis.sharedAudioPlayer?.prepareToPlay()
  3643. Nexilis.sharedAudioPlayer?.play()
  3644. } catch {
  3645. }
  3646. DispatchQueue.main.asyncAfter(deadline: .now() + 3, execute: {
  3647. self.floating = nil
  3648. })
  3649. // if !onGoingCC.isEmpty {
  3650. // floating.autoDismiss = false
  3651. // }
  3652. floating.onTap = {
  3653. self.floating = nil
  3654. showNotif()
  3655. }
  3656. }
  3657. func showNotif() {
  3658. if message.getBody(key: attachmentFlag) == "59" {
  3659. let date = Date(milliseconds: Int64(message.getBody(key: CoreMessage_TMessageKey.LOCAL_TIMESTAMP))!)
  3660. let formatter = DateFormatter()
  3661. formatter.dateFormat = "HH:mm"
  3662. formatter.locale = NSLocale(localeIdentifier: "id") as Locale?
  3663. var timeSignIn = formatter.string(from: date as Date)
  3664. let dialog = DialogSignIn()
  3665. dialog.valueDevice = message.getBody(key: CoreMessage_TMessageKey.DEVICE_BRAND)
  3666. dialog.valueTime = timeSignIn
  3667. dialog.valueLocation = message.getBody(key: CoreMessage_TMessageKey.PLACE_NAME)
  3668. dialog.valueToken = message.getBody(key: CoreMessage_TMessageKey.TOKEN)
  3669. dialog.valueUser = message.getBody(key: CoreMessage_TMessageKey.USER_ID)
  3670. dialog.modalTransitionStyle = .crossDissolve
  3671. dialog.modalPresentationStyle = .overCurrentContext
  3672. UIApplication.shared.visibleViewController?.present(dialog, animated: true)
  3673. return
  3674. }
  3675. if !onGoingCC.isEmpty {
  3676. floating.dismiss()
  3677. }
  3678. Database.shared.database?.inTransaction({ (fmdb, rollback) in
  3679. do {
  3680. if let cursorData = Database.shared.getRecords(fmdb: fmdb, query: "SELECT first_name, last_name FROM BUDDY where f_pin = '\(User.getMyPin()!)'"), cursorData.next() {
  3681. if (cursorData.string(forColumnIndex: 0)! + " " + cursorData.string(forColumnIndex: 1)!).trimmingCharacters(in: .whitespaces) == "USR\(User.getMyPin()!)" {
  3682. let alert = LibAlertController(title: "Change Profile".localized(), message: "You must change your name to use this feature".localized(), preferredStyle: .alert)
  3683. alert.addAction(UIAlertAction(title: "OK".localized(), style: UIAlertAction.Style.default, handler: {(_) in
  3684. let controller = AppStoryBoard.Palio.instance.instantiateViewController(withIdentifier: "signupsignin") as! SignUpSignIn
  3685. controller.forceLogin = true
  3686. let navigationController = CustomNavigationController(rootViewController: controller)
  3687. navigationController.modalPresentationStyle = .fullScreen
  3688. navigationController.navigationBar.tintColor = .white
  3689. navigationController.navigationBar.barTintColor = UIApplication.shared.visibleViewController?.traitCollection.userInterfaceStyle == .dark ? .blackDarkMode : .mainColor
  3690. navigationController.navigationBar.isTranslucent = false
  3691. navigationController.navigationBar.overrideUserInterfaceStyle = .dark
  3692. navigationController.navigationBar.barStyle = .black
  3693. let cancelButtonAttributes: [NSAttributedString.Key: Any] = [NSAttributedString.Key.foregroundColor: UIColor.white, NSAttributedString.Key.font : UIFont.systemFont(ofSize: 16)]
  3694. UIBarButtonItem.appearance().setTitleTextAttributes(cancelButtonAttributes, for: .normal)
  3695. let textAttributes = [NSAttributedString.Key.foregroundColor:UIColor.white]
  3696. navigationController.navigationBar.titleTextAttributes = textAttributes
  3697. if UIApplication.shared.visibleViewController?.navigationController != nil {
  3698. UIApplication.shared.visibleViewController?.navigationController?.present(navigationController, animated: true, completion: nil)
  3699. } else {
  3700. UIApplication.shared.visibleViewController?.present(navigationController, animated: true, completion: nil)
  3701. }
  3702. }))
  3703. if UIApplication.shared.visibleViewController?.navigationController != nil {
  3704. UIApplication.shared.visibleViewController?.navigationController?.present(alert, animated: true, completion: nil)
  3705. } else {
  3706. UIApplication.shared.visibleViewController?.present(alert, animated: true, completion: nil)
  3707. }
  3708. }
  3709. cursorData.close()
  3710. return
  3711. }
  3712. } catch {
  3713. rollback.pointee = true
  3714. print("Access database error: \(error.localizedDescription)")
  3715. }
  3716. })
  3717. if message.getBody(key: messageScopeId) == "3" || message.getBody(key: messageScopeId) == "18" || message.getBody(key: messageScopeId) == "5" {
  3718. func openEditor() {
  3719. let editorPersonalVC = AppStoryBoard.Palio.instance.instantiateViewController(identifier: "editorPersonalVC") as! EditorPersonal
  3720. editorPersonalVC.hidesBottomBarWhenPushed = true
  3721. editorPersonalVC.unique_l_pin = threadIdentifier
  3722. editorPersonalVC.fromNotification = true
  3723. if !onGoingCC.isEmpty {
  3724. let compalintId = onGoingCC.components(separatedBy: ",")[2]
  3725. let fPinCC = onGoingCC.isEmpty ? "" : onGoingCC.components(separatedBy: ",")[1]
  3726. editorPersonalVC.isContactCenter = true
  3727. editorPersonalVC.fPinContacCenter = fPinCC
  3728. editorPersonalVC.complaintId = compalintId
  3729. editorPersonalVC.onGoingCC = true
  3730. editorPersonalVC.isRequestContactCenter = false
  3731. }
  3732. let navigationController = CustomNavigationController(rootViewController: editorPersonalVC)
  3733. navigationController.modalPresentationStyle = .fullScreen
  3734. navigationController.navigationBar.tintColor = .white
  3735. navigationController.navigationBar.barTintColor = UIApplication.shared.visibleViewController?.traitCollection.userInterfaceStyle == .dark ? .blackDarkMode : .mainColor
  3736. navigationController.navigationBar.isTranslucent = false
  3737. navigationController.navigationBar.overrideUserInterfaceStyle = .dark
  3738. navigationController.navigationBar.barStyle = .black
  3739. let cancelButtonAttributes: [NSAttributedString.Key: Any] = [NSAttributedString.Key.foregroundColor: UIColor.white, NSAttributedString.Key.font : UIFont.systemFont(ofSize: 16)]
  3740. UIBarButtonItem.appearance().setTitleTextAttributes(cancelButtonAttributes, for: .normal)
  3741. let textAttributes = [NSAttributedString.Key.foregroundColor:UIColor.white]
  3742. navigationController.navigationBar.titleTextAttributes = textAttributes
  3743. if UIApplication.shared.visibleViewController?.navigationController != nil {
  3744. UIApplication.shared.visibleViewController?.navigationController?.present(navigationController, animated: true, completion: nil)
  3745. } else {
  3746. UIApplication.shared.visibleViewController?.present(navigationController, animated: true, completion: nil)
  3747. }
  3748. }
  3749. if UIApplication.shared.visibleViewController is UINavigationController {
  3750. let nc = UIApplication.shared.visibleViewController as! UINavigationController
  3751. if nc.visibleViewController is QmeraStreamingViewController {
  3752. let vc = nc.visibleViewController as! QmeraStreamingViewController
  3753. var alert = LibAlertController(title: "", message: "Are you sure you want to end Live Streaming, and open notification?".localized(), preferredStyle: .alert)
  3754. if !vc.isLive {
  3755. alert = LibAlertController(title: "", message: "Are you sure you want to leave Live Streaming, and open notification?".localized(), preferredStyle: .alert)
  3756. }
  3757. alert.addAction(UIAlertAction(title: "No".localized(), style: UIAlertAction.Style.default, handler: nil))
  3758. alert.addAction(UIAlertAction(title: "Yes".localized(), style: UIAlertAction.Style.default, handler: { _ in
  3759. DispatchQueue.global().async {
  3760. API.terminateBC(sBroadcasterID: vc.isLive ? nil : vc.data)
  3761. vc.sendLeft()
  3762. }
  3763. vc.dismiss(animated: true, completion: {
  3764. openEditor()
  3765. })
  3766. }))
  3767. nc.present(alert, animated: true, completion: nil)
  3768. // NotificationCenter.default.post(name: NSNotification.Name(rawValue: "isRunningStreaming"), object: nil, userInfo: dataMessage)
  3769. } else if nc.visibleViewController is SeminarViewController {
  3770. let vc = nc.visibleViewController as! SeminarViewController
  3771. var alert = LibAlertController(title: "", message: "Are you sure you want to end Seminar, and open notification?".localized(), preferredStyle: .alert)
  3772. if !vc.isLive {
  3773. alert = LibAlertController(title: "", message: "Are you sure you want to leave Seminar, and open notification?".localized(), preferredStyle: .alert)
  3774. }
  3775. alert.addAction(UIAlertAction(title: "No".localized(), style: UIAlertAction.Style.default, handler: nil))
  3776. alert.addAction(UIAlertAction(title: "Yes".localized(), style: UIAlertAction.Style.default, handler: { _ in
  3777. DispatchQueue.global().async {
  3778. API.terminateBC(sBroadcasterID: vc.isLive ? nil : vc.data)
  3779. vc.sendLeft()
  3780. }
  3781. vc.dismiss(animated: true, completion: {
  3782. openEditor()
  3783. })
  3784. }))
  3785. nc.present(alert, animated: true, completion: nil)
  3786. // NotificationCenter.default.post(name: NSNotification.Name(rawValue: "isRunningStreaming"), object: nil, userInfo: dataMessage)
  3787. } else if nc.visibleViewController is EditorPersonal {
  3788. let vc = nc.visibleViewController as! EditorPersonal
  3789. if vc.fromNotification {
  3790. vc.dismiss(animated: true, completion: {
  3791. openEditor()
  3792. })
  3793. } else {
  3794. vc.navigationController?.popViewController(animated: true)
  3795. openEditor()
  3796. }
  3797. } else {
  3798. openEditor()
  3799. }
  3800. } else if UIApplication.shared.visibleViewController is EditorPersonal {
  3801. let vc = UIApplication.shared.visibleViewController as! EditorPersonal
  3802. if vc.fromNotification{
  3803. vc.dismiss(animated: true, completion: {
  3804. openEditor()
  3805. })
  3806. } else {
  3807. vc.navigationController?.popViewController(animated: true)
  3808. openEditor()
  3809. }
  3810. } else if UIApplication.shared.visibleViewController is UIAlertController {
  3811. let vc = UIApplication.shared.visibleViewController as! UIAlertController
  3812. vc.dismiss(animated: true, completion: {
  3813. openEditor()
  3814. })
  3815. } else {
  3816. openEditor()
  3817. }
  3818. } else {
  3819. func openEditor() {
  3820. let editorGroupVC = AppStoryBoard.Palio.instance.instantiateViewController(withIdentifier: "editorGroupVC") as! EditorGroup
  3821. editorGroupVC.hidesBottomBarWhenPushed = true
  3822. editorGroupVC.unique_l_pin = threadIdentifier
  3823. editorGroupVC.fromNotification = true
  3824. let navigationController = CustomNavigationController(rootViewController: editorGroupVC)
  3825. navigationController.modalPresentationStyle = .fullScreen
  3826. navigationController.navigationBar.tintColor = .white
  3827. navigationController.navigationBar.barTintColor = UIApplication.shared.visibleViewController?.traitCollection.userInterfaceStyle == .dark ? .blackDarkMode : .mainColor
  3828. navigationController.navigationBar.isTranslucent = false
  3829. navigationController.navigationBar.overrideUserInterfaceStyle = .dark
  3830. navigationController.navigationBar.barStyle = .black
  3831. let cancelButtonAttributes: [NSAttributedString.Key: Any] = [NSAttributedString.Key.foregroundColor: UIColor.white, NSAttributedString.Key.font : UIFont.systemFont(ofSize: 16)]
  3832. UIBarButtonItem.appearance().setTitleTextAttributes(cancelButtonAttributes, for: .normal)
  3833. let textAttributes = [NSAttributedString.Key.foregroundColor:UIColor.white]
  3834. navigationController.navigationBar.titleTextAttributes = textAttributes
  3835. if UIApplication.shared.visibleViewController?.navigationController != nil {
  3836. UIApplication.shared.visibleViewController?.navigationController?.present(navigationController, animated: true, completion: nil)
  3837. } else {
  3838. UIApplication.shared.visibleViewController?.present(navigationController, animated: true, completion: nil)
  3839. }
  3840. }
  3841. if UIApplication.shared.visibleViewController is UINavigationController {
  3842. let nc = UIApplication.shared.visibleViewController as! UINavigationController
  3843. if nc.visibleViewController is QmeraStreamingViewController {
  3844. let vc = nc.visibleViewController as! QmeraStreamingViewController
  3845. var alert = LibAlertController(title: "", message: "Are you sure you want to end Live Streaming, and open notification?".localized(), preferredStyle: .alert)
  3846. if !vc.isLive {
  3847. alert = LibAlertController(title: "", message: "Are you sure you want to leave Live Streaming, and open notification?".localized(), preferredStyle: .alert)
  3848. }
  3849. alert.addAction(UIAlertAction(title: "No".localized(), style: UIAlertAction.Style.default, handler: nil))
  3850. alert.addAction(UIAlertAction(title: "Yes".localized(), style: UIAlertAction.Style.default, handler: { _ in
  3851. DispatchQueue.global().async {
  3852. API.terminateBC(sBroadcasterID: vc.isLive ? nil : vc.data)
  3853. vc.sendLeft()
  3854. }
  3855. vc.dismiss(animated: true, completion: {
  3856. openEditor()
  3857. })
  3858. }))
  3859. nc.present(alert, animated: true, completion: nil)
  3860. // NotificationCenter.default.post(name: NSNotification.Name(rawValue: "isRunningStreaming"), object: nil, userInfo: dataMessage)
  3861. } else if nc.visibleViewController is SeminarViewController {
  3862. let vc = nc.visibleViewController as! SeminarViewController
  3863. var alert = LibAlertController(title: "", message: "Are you sure you want to end Seminar, and open notification?".localized(), preferredStyle: .alert)
  3864. if !vc.isLive {
  3865. alert = LibAlertController(title: "", message: "Are you sure you want to leave Seminar, and open notification?".localized(), preferredStyle: .alert)
  3866. }
  3867. alert.addAction(UIAlertAction(title: "No".localized(), style: UIAlertAction.Style.default, handler: nil))
  3868. alert.addAction(UIAlertAction(title: "Yes".localized(), style: UIAlertAction.Style.default, handler: { _ in
  3869. DispatchQueue.global().async {
  3870. API.terminateBC(sBroadcasterID: vc.isLive ? nil : vc.data)
  3871. vc.sendLeft()
  3872. }
  3873. vc.dismiss(animated: true, completion: {
  3874. openEditor()
  3875. })
  3876. }))
  3877. nc.present(alert, animated: true, completion: nil)
  3878. // NotificationCenter.default.post(name: NSNotification.Name(rawValue: "isRunningStreaming"), object: nil, userInfo: dataMessage)
  3879. } else if nc.visibleViewController is EditorGroup {
  3880. let vc = nc.visibleViewController as! EditorGroup
  3881. if vc.fromNotification {
  3882. vc.dismiss(animated: true, completion: {
  3883. openEditor()
  3884. })
  3885. } else {
  3886. vc.navigationController?.popViewController(animated: true)
  3887. openEditor()
  3888. }
  3889. } else {
  3890. openEditor()
  3891. }
  3892. } else if UIApplication.shared.visibleViewController is EditorGroup {
  3893. let vc = UIApplication.shared.visibleViewController as! EditorGroup
  3894. if vc.fromNotification {
  3895. vc.dismiss(animated: true, completion: {
  3896. openEditor()
  3897. })
  3898. } else {
  3899. vc.navigationController?.popViewController(animated: true)
  3900. openEditor()
  3901. }
  3902. } else if UIApplication.shared.visibleViewController is UIAlertController {
  3903. let vc = UIApplication.shared.visibleViewController as! UIAlertController
  3904. vc.dismiss(animated: true, completion: {
  3905. openEditor()
  3906. })
  3907. } else {
  3908. openEditor()
  3909. }
  3910. }
  3911. }
  3912. }
  3913. }
  3914. }
  3915. }
  3916. public static func addFriend(fpin: String, completion: @escaping (Bool) -> ()) {
  3917. DispatchQueue.global().async {
  3918. if let response = Nexilis.writeAndWait(message: CoreMessage_TMessageBank.getAddFriendQRCode(fpin: fpin)), response.isOk() {
  3919. completion(true)
  3920. } else {
  3921. completion(false)
  3922. }
  3923. }
  3924. }
  3925. public static func addFriendSilent(fpin: String) {
  3926. DispatchQueue.global().async {
  3927. _ = Nexilis.write(message: CoreMessage_TMessageBank.getAddFriendQRCodeSilent(fpin: fpin))
  3928. }
  3929. }
  3930. public func onReceive(message: [AnyHashable : Any?]) {
  3931. var dataMessage: [AnyHashable : Any] = [:]
  3932. dataMessage["message"] = message
  3933. NotificationCenter.default.post(name: NSNotification.Name(rawValue: Nexilis.listenerReceiveChat), object: nil, userInfo: dataMessage)
  3934. }
  3935. public func onMessage(message: TMessage) {
  3936. var dataMessage: [AnyHashable : Any] = [:]
  3937. dataMessage["message"] = message
  3938. NotificationCenter.default.post(name: NSNotification.Name(rawValue: Nexilis.listenerStatusChat), object: nil, userInfo: dataMessage)
  3939. }
  3940. public func onUpload(name: String, progress: Double) {
  3941. var dataMessage: [AnyHashable : Any] = [:]
  3942. dataMessage["name"] = name
  3943. dataMessage["progress"] = progress
  3944. NotificationCenter.default.post(name: NSNotification.Name(rawValue: "onUploadChat"), object: nil, userInfo: dataMessage)
  3945. }
  3946. public func onTyping(message: TMessage) {
  3947. var dataMessage: [AnyHashable : Any] = [:]
  3948. dataMessage["message"] = message
  3949. NotificationCenter.default.post(name: NSNotification.Name(rawValue: Nexilis.listenerTypingChat), object: nil, userInfo: dataMessage)
  3950. }
  3951. // public static func faceDetect(fd: FaceDetector?,image: UIImage, completion: ((Bool) -> ())?){
  3952. // //print("enter vision")
  3953. // let visionImage = VisionImage(image: image)
  3954. // //print("exit vision")
  3955. // var retval = false
  3956. // visionImage.orientation = image.imageOrientation
  3957. // var fd1 : FaceDetector?
  3958. // if(fd == nil){
  3959. // fd1 = FaceDetector.faceDetector()
  3960. // }
  3961. // else {
  3962. // fd1 = fd
  3963. // }
  3964. //
  3965. // // [START detect_faces]
  3966. // fd1?.process(visionImage) {faces, error in
  3967. // guard error == nil, let faces = faces, !faces.isEmpty else {
  3968. // //print("faces empty")
  3969. // completion?(false)
  3970. // return
  3971. // }
  3972. // if(faces.count > 0){
  3973. // //print("face count: \(faces.count)")
  3974. // retval = true
  3975. // }
  3976. // completion?(retval)
  3977. // }
  3978. //
  3979. // }
  3980. }
  3981. extension Nexilis: GroupDelegate {
  3982. public func onGroup(code: String, f_pin: String, groupId: String) {
  3983. var data: [AnyHashable : Any] = [:]
  3984. data["code"] = code
  3985. data["f_pin"] = f_pin
  3986. data["groupId"] = groupId
  3987. NotificationCenter.default.post(name: NSNotification.Name(rawValue: "onGroup"), object: nil, userInfo: data)
  3988. }
  3989. public func onTopic(code: String, f_pin: String, topicId: String) {
  3990. var data: [AnyHashable : Any] = [:]
  3991. data["code"] = code
  3992. data["f_pin"] = f_pin
  3993. data["topicId"] = topicId
  3994. NotificationCenter.default.post(name: NSNotification.Name(rawValue: "onTopic"), object: nil, userInfo: data)
  3995. }
  3996. public func onMember(code: String, f_pin: String, groupId: String, member: String) {
  3997. var data: [AnyHashable : Any] = [:]
  3998. data["code"] = code
  3999. data["f_pin"] = f_pin
  4000. data["groupId"] = groupId
  4001. data["member"] = member
  4002. NotificationCenter.default.post(name: NSNotification.Name(rawValue: "onMember"), object: nil, userInfo: data)
  4003. }
  4004. }
  4005. extension Nexilis: PersonInfoDelegate {
  4006. public func onUpdatePersonInfo(state: Int, message: String) {
  4007. var data: [AnyHashable : Any] = [:]
  4008. data["state"] = state
  4009. data["message"] = message
  4010. NotificationCenter.default.post(name: NSNotification.Name(rawValue: "onUpdatePersonInfo"), object: nil, userInfo: data)
  4011. }
  4012. }
  4013. extension Nexilis: QLPreviewControllerDataSource {
  4014. public func numberOfPreviewItems(in controller: QLPreviewController) -> Int {
  4015. return 1
  4016. }
  4017. public func previewController(_ controller: QLPreviewController, previewItemAt index: Int) -> QLPreviewItem {
  4018. return previewItem!
  4019. }
  4020. }
  4021. public class SelfSignedURLSessionDelegate: NSObject, URLSessionTaskDelegate, URLSessionDataDelegate {
  4022. public func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
  4023. if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust {
  4024. if let serverTrust = challenge.protectionSpace.serverTrust {
  4025. let credential = URLCredential(trust: serverTrust)
  4026. completionHandler(.useCredential, credential)
  4027. }
  4028. }
  4029. }
  4030. }