Nexilis.swift 148 KB

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