Nexilis.swift 155 KB

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