Nexilis.swift 187 KB

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