Nexilis.swift 149 KB

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