Nexilis.swift 219 KB

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