Nexilis.swift 178 KB

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