Nexilis.swift 187 KB

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