Nexilis.swift 179 KB

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