Nexilis.swift 229 KB

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