Nexilis.swift 100 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915
  1. //
  2. // Qmera.swift
  3. // Runner
  4. //
  5. // Created by Yayan Dwi on 15/04/20.
  6. // Copyright © 2020 The Chromium Authors. All rights reserved.
  7. //
  8. import Foundation
  9. import nuSDKService
  10. import AVFoundation
  11. import AVKit
  12. import UIKit
  13. import FMDB
  14. import QuickLook
  15. import NotificationBannerSwift
  16. public class Nexilis: NSObject {
  17. public static var sAPIKey = ""
  18. static let ADDRESS = ADDRESS_RELEASE
  19. static let ADDRESS_33 = "192.168.0.33"
  20. static let ADDRESS_RELEASE = "202.158.33.26"
  21. // static let PORT = 45328
  22. // static let PORT = 65328 // 33
  23. static let PORT = PORT_RELEASE
  24. static let PORT_33 = 62328
  25. static let PORT_RELEASE = 42328
  26. static var nSessionMode: Int! = 1
  27. static var dispatch: DispatchGroup?
  28. let callManager = CallManager()
  29. var providerDelegate: CallProviderDelegate?
  30. public static let shared = Nexilis()
  31. private func createDelegate() {
  32. print("createDelegate...")
  33. callDelegate = self
  34. messageDelegate = self
  35. groupDelegate = self
  36. personInfoDelegate = self
  37. providerDelegate = CallProviderDelegate(callManager: callManager)
  38. }
  39. public static func connect(apiKey: String, delegate: ConnectDelegate) {
  40. do {
  41. Nexilis.shared.createDelegate()
  42. Nexilis.sAPIKey = apiKey
  43. Database.shared.openDatabase()
  44. IncomingThread.default.run()
  45. OutgoingThread.default.run()
  46. if let _ = UserDefaults.standard.stringArray(forKey: "address") {
  47. }
  48. else {
  49. // let address = App.getAddress()
  50. // if !address.isEmpty {
  51. // print(address)
  52. // print(address[0])
  53. // UserDefaults.standard.set(address, forKey: "address")
  54. // UserDefaults.standard.set(address[0], forKey: "server")
  55. // }
  56. }
  57. Nexilis.dispatch = DispatchGroup()
  58. Nexilis.dispatch?.enter()
  59. // var server = UserDefaults.standard.string(forKey: "server")
  60. // if let s = server, let a = UserDefaults.standard.stringArray(forKey: "address"), s != a[0] {
  61. // server = a[0]
  62. // UserDefaults.standard.set(server, forKey: "server")
  63. // }
  64. // var ip = ""
  65. // var port = 0
  66. // if let s = server {
  67. // let data = s.split(separator: ":")
  68. // ip = String(data[0])
  69. // if let p = Int(data[1]) {
  70. // port = p
  71. // }
  72. // }
  73. // print(API.sGetVersion())
  74. var id = ""
  75. if let me = UserDefaults.standard.string(forKey: "me") {
  76. try API.initConnection(bSwitchIP: false, sAPIK: apiKey, aAppMain: nil, cbiI: Callback(), sTCPAddr: Nexilis.ADDRESS, nTCPPort: Nexilis.PORT, sUserID: me, sStartWH: "09:01")
  77. } else {
  78. let uuid = UIDevice.current.identifierForVendor?.uuidString ?? "UNK-DEVICE"
  79. try API.initConnection(bSwitchIP: false, sAPIK: apiKey, aAppMain: nil, cbiI: Callback(), sTCPAddr: Nexilis.ADDRESS, nTCPPort: Nexilis.PORT, sUserID: uuid, sStartWH: "09:01")
  80. id = uuid
  81. }
  82. // wait until connection true
  83. Nexilis.dispatch?.wait()
  84. Nexilis.dispatch = nil
  85. if(!id.isEmpty && (UserDefaults.standard.string(forKey: "me") == nil)){
  86. if let response = Nexilis.writeSync(message: CoreMessage_TMessageBank.getSignUpApi(api: apiKey, p_pin: id), timeout: 30 * 1000){
  87. id = response.getBody(key: CoreMessage_TMessageKey.F_PIN, default_value: "")
  88. if(!id.isEmpty){
  89. Nexilis.changeUser(f_pin: id)
  90. UserDefaults.standard.setValue(id, forKey: "me")
  91. // pos registration
  92. _ = Nexilis.write(message: CoreMessage_TMessageBank.getPostRegistration(p_pin: id))
  93. }
  94. }
  95. }
  96. if UserDefaults.standard.string(forKey: "apiKey") == nil {
  97. UserDefaults.standard.setValue(apiKey, forKey: "apiKey")
  98. }
  99. if let me = UserDefaults.standard.string(forKey: "me") {
  100. delegate.onSuccess(userId: me)
  101. }
  102. }
  103. catch {
  104. print(error)
  105. delegate.onFailed(error: "99:Something went wrong")
  106. }
  107. }
  108. public static func changeUser(f_pin: String){
  109. do {
  110. print("change user to fpin")
  111. Nexilis.dispatch = DispatchGroup()
  112. Nexilis.dispatch?.enter()
  113. try API.initConnection(bSwitchIP: true, sAPIK: Nexilis.sAPIKey, aAppMain: nil, cbiI: Callback(), sTCPAddr: Nexilis.ADDRESS, nTCPPort: Nexilis.PORT, sUserID: f_pin, sStartWH: "09:01")
  114. // wait until connection true
  115. Nexilis.dispatch?.wait()
  116. Nexilis.dispatch = nil
  117. print("success change user to fpin")
  118. _ = Nexilis.writeSync(message: CoreMessage_TMessageBank.getChangeConnectionID(p_pin: f_pin))
  119. } catch{
  120. print(error)
  121. }
  122. }
  123. public static func addQueueMessage(message: TMessage) {
  124. OutgoingThread.default.addQueue(message: message)
  125. }
  126. private static var wbDelegate: WhiteboardDelegate?
  127. private static var wbReceiver: WhiteboardReceiver?
  128. public static func setWhiteboardDelegate(delegate: WhiteboardDelegate?){
  129. Nexilis.wbDelegate = delegate
  130. }
  131. public static func getWhiteboardDelegate() -> WhiteboardDelegate? {
  132. return Nexilis.wbDelegate
  133. }
  134. public static func setWhiteboardReceiver(receiver: WhiteboardReceiver?){
  135. Nexilis.wbReceiver = receiver
  136. }
  137. public static func getWhiteboardReceiver() -> WhiteboardReceiver? {
  138. return Nexilis.wbReceiver
  139. }
  140. public static func getEditorPersonal() -> EditorPersonal {
  141. return AppStoryBoard.Palio.instance.instantiateViewController(identifier: "editorPersonalVC") as! EditorPersonal
  142. }
  143. public static func getEditorGroup() -> EditorGroup {
  144. return AppStoryBoard.Palio.instance.instantiateViewController(identifier: "editorGroupVC") as! EditorGroup
  145. }
  146. public static func getEditorStarMessage() -> EditorStarMessages {
  147. return AppStoryBoard.Palio.instance.instantiateViewController(identifier: "staredVC") as! EditorStarMessages
  148. }
  149. static func getAddress() -> [String] {
  150. var result = [String]()
  151. let url = URL(string: "https://newuniverse.io/dipp/NuN1v3rs3/5ch0oL18")!
  152. let urlConfig = URLSessionConfiguration.default
  153. urlConfig.requestCachePolicy = .returnCacheDataElseLoad
  154. urlConfig.timeoutIntervalForRequest = 10.0
  155. urlConfig.timeoutIntervalForResource = 10.0
  156. let semaphore = DispatchSemaphore(value: 0)
  157. let task = URLSession(configuration: urlConfig).dataTask(with: url) {(data, response, error) in
  158. debugPrint("getAddress: ", data, "response", response, "error", error)
  159. guard let data = data else {
  160. semaphore.signal()
  161. return
  162. }
  163. let html = String(data: data, encoding: .utf8)!
  164. let base64Address = html.components(separatedBy: "<body>")[1].components(separatedBy: "</body>")[0].trimmingCharacters(in: .whitespacesAndNewlines)
  165. if let addressData = Data(base64Encoded: base64Address), let decodeAddress = String(data: addressData, encoding: .utf8) {
  166. let rows = decodeAddress.trimmingCharacters(in: CharacterSet.newlines).split(separator: ",")
  167. for r in rows {
  168. let _address = r.split(separator: ":")
  169. var ip:String = ""
  170. let _data = _address[0].split(separator: ".", maxSplits: 4, omittingEmptySubsequences: false)
  171. ip.append(String(_data[3]))
  172. ip.append(".")
  173. ip.append(String(_data[1]))
  174. ip.append(".")
  175. ip.append(String(_data[0]))
  176. ip.append(".")
  177. ip.append(String(_data[2]))
  178. result.append(ip + ":" + _address[2])
  179. }
  180. }
  181. semaphore.signal()
  182. }
  183. task.resume()
  184. _ = semaphore.wait(timeout: .distantFuture)
  185. debugPrint("[App] getAddress:", result)
  186. return result
  187. }
  188. static func getCLMUserId() -> String {
  189. return String(API.sGetCurentUserID().split(separator: "(")[0])
  190. }
  191. public static func writeSync(message: TMessage, timeout: Int = 15 * 1000) -> TMessage? {
  192. do {
  193. print(">> SENDING MESSAGE >> ", message.toLogString())
  194. if let data = try API.sGetResponse(sRequest: message.pack(), lTimeout: timeout, bKeepTOResp: true) {
  195. let response = TMessage(data: data)
  196. print("<< RESPONSE MESSAGE << ", response.toLogString())
  197. return response
  198. }
  199. } catch {
  200. print(error)
  201. }
  202. return nil
  203. }
  204. public static func write(message: TMessage, timeout: Int = 15 * 1000) -> String? {
  205. do {
  206. if !API.bInetConnAvailable() {
  207. return nil
  208. }
  209. print(">> SENDING MESSAGE >> ", message.toLogString())
  210. if message.getMedia().count == 0 {
  211. if let data = try API.sSend(sData: message.pack(), nPriority: 1, lTimeout: timeout) {
  212. print("<< RESPONSE MESSAGE << ", data)
  213. return data
  214. }
  215. }
  216. // media
  217. if let data = try API.sSend(abData: message.toBytes(), nPriority: 2, lTimeout: timeout) {
  218. print("<< RESPONSE MESSAGE << ", data)
  219. return data
  220. }
  221. } catch {
  222. print(error)
  223. }
  224. return nil
  225. }
  226. public static func writeDraw(data: String, timeout: Int = 15 * 1000) -> String? {
  227. do {
  228. if !API.bInetConnAvailable() {
  229. return nil
  230. }
  231. print(">> SENDING MESSAGE >> ", data)
  232. if let data = try API.sSend(sData: data, nPriority: 1, lTimeout: timeout) {
  233. print("<< RESPONSE MESSAGE << ", data)
  234. return data
  235. }
  236. } catch {
  237. print(error)
  238. }
  239. return nil
  240. }
  241. public static func response(packetId: String, message: TMessage, timeout: Int = 15 * 1000) -> String? {
  242. var result: String? = nil
  243. do {
  244. if !API.bInetConnAvailable() {
  245. return nil
  246. }
  247. print(">> RESPONSE >> " + packetId + " " + message.toLogString());
  248. result = try API.sSendResponse(sRequestID: packetId, sResponse: message.pack(), lTimeout: timeout)
  249. } catch {
  250. print(error)
  251. }
  252. return result
  253. }
  254. public static func startAudio(nMode: Int!, bSpeakerOn: Bool!) {
  255. let xSessionMode = nMode == 0 ? nSessionMode : nMode
  256. do {
  257. if ("iPhone 6" == UIDevice.current.modelName) {
  258. try AVAudioSession.sharedInstance().setCategory(.playAndRecord, options: .duckOthers)
  259. if (xSessionMode == 1) {
  260. try AVAudioSession.sharedInstance().setMode(.voiceChat)
  261. } else if (xSessionMode == 2) {
  262. try AVAudioSession.sharedInstance().setMode(.voiceChat)
  263. // try avAudioSession.setMode(AVAudioSessionModeVideoChat)
  264. }
  265. if (bSpeakerOn) {
  266. try AVAudioSession.sharedInstance().overrideOutputAudioPort(.speaker)
  267. } else {
  268. try AVAudioSession.sharedInstance().overrideOutputAudioPort(.none)
  269. }
  270. } else {
  271. if (bSpeakerOn) {
  272. try AVAudioSession.sharedInstance().setCategory(.playAndRecord, options: .defaultToSpeaker)
  273. } else {
  274. try AVAudioSession.sharedInstance().setCategory(.playAndRecord, options: .duckOthers)
  275. }
  276. if (xSessionMode == 1) {
  277. try AVAudioSession.sharedInstance().setMode(.voiceChat)
  278. } else if (xSessionMode == 2) {
  279. try AVAudioSession.sharedInstance().setMode(.voiceChat)
  280. }
  281. }
  282. try AVAudioSession.sharedInstance().setActive(true)
  283. } catch {}
  284. nSessionMode = xSessionMode
  285. }
  286. public static func turnSpeakerOn(bSpeakerOn: Bool!) {
  287. do{
  288. if ("iPhone 6" == UIDevice.current.modelName) {
  289. if (bSpeakerOn) {
  290. try AVAudioSession.sharedInstance().overrideOutputAudioPort(.speaker)
  291. } else {
  292. try AVAudioSession.sharedInstance().overrideOutputAudioPort(.none)
  293. }
  294. return
  295. }
  296. }catch{
  297. print(error)
  298. }
  299. API.pauseAudio()
  300. stopAudio()
  301. startAudio(nMode: 0, bSpeakerOn: bSpeakerOn)
  302. API.resumeAudio(bSpeakerOn: bSpeakerOn)
  303. }
  304. public static func stopAudio() {
  305. do {
  306. try AVAudioSession.sharedInstance().setCategory(.ambient)
  307. try AVAudioSession.sharedInstance().setMode(.default)
  308. try AVAudioSession.sharedInstance().overrideOutputAudioPort(.none)
  309. }catch{
  310. print(error)
  311. }
  312. }
  313. public static func muteMicrophone(isMute: Bool!){
  314. do {
  315. if(isMute){
  316. try AVAudioSession.sharedInstance().setCategory(.playback)
  317. }
  318. else{
  319. try AVAudioSession.sharedInstance().setCategory(.playAndRecord)
  320. }
  321. }catch{
  322. print(error)
  323. }
  324. }
  325. private static var groupWait = DispatchGroup()
  326. private static var waitQueue = [String: TMessage]()
  327. public static func writeAndWait(message: TMessage, timeout: Int = 15 * 1000) -> TMessage? {
  328. groupWait.enter()
  329. _ = write(message: message, timeout: timeout)
  330. waitQueue[message.getStatus()] = message
  331. if groupWait.wait(timeout: .now() + 15) == .timedOut {
  332. waitQueue.removeValue(forKey: message.getStatus())
  333. groupWait.leave()
  334. return nil
  335. }
  336. return waitQueue.removeValue(forKey: message.getStatus())
  337. }
  338. static func incomingData(packetId: String, data: AnyObject) {
  339. let message = TMessage()
  340. if data is String {
  341. let d = data as! String
  342. guard message.unpack(data: d) else {
  343. print("UNKNOWN DATA STRING...", data)
  344. if(data.hasPrefix("WB")){
  345. let dataWB = data.components(separatedBy: "/")
  346. if(dataWB[1] == "1"){
  347. let x = dataWB[2]
  348. let y = dataWB[3]
  349. let w = dataWB[4]
  350. let h = dataWB[5]
  351. let fc = dataWB[6]
  352. let sw = dataWB[7]
  353. let xo = dataWB[8]
  354. let yo = dataWB[9]
  355. if(Nexilis.getWhiteboardDelegate() != nil){
  356. Nexilis.getWhiteboardDelegate()!.draw(x: x, y: y, w: w, h: h, fc: fc, sw: sw, xo: xo, yo: yo, data: "")
  357. }
  358. } else if(dataWB[1] == "3") {
  359. if(Nexilis.getWhiteboardDelegate() != nil){
  360. Nexilis.getWhiteboardDelegate()!.clear()
  361. }
  362. } else if(dataWB[1] == "2"){
  363. if(Nexilis.getWhiteboardReceiver() != nil){
  364. Nexilis.getWhiteboardReceiver()!.incomingWB(roomId: dataWB[2])
  365. }
  366. } else if(dataWB[1] == "22"){
  367. } else if(dataWB[1] == "88"){
  368. if(Nexilis.getWhiteboardReceiver() != nil){
  369. Nexilis.getWhiteboardReceiver()!.cancel(roomId: dataWB[2])
  370. }
  371. }
  372. }
  373. return
  374. }
  375. } else if data is [UInt8] {
  376. let d = data as! [UInt8]
  377. guard message.unpack(bytes_data: d) else {
  378. print("UNKNOWN DATA BYTES...", data)
  379. return
  380. }
  381. }
  382. message.mBodies[CoreMessage_TMessageKey.PACKET_ID] = packetId
  383. if let _ = waitQueue[message.getStatus()] {
  384. waitQueue[message.getStatus()] = message
  385. groupWait.leave()
  386. return
  387. }
  388. IncomingThread.default.addQueue(message: message)
  389. }
  390. static func saveMessage(message: TMessage, withStatus: Bool = true) {
  391. guard let me = UserDefaults.standard.string(forKey: "me") else {
  392. return
  393. }
  394. let message_id = message.getBody(key : CoreMessage_TMessageKey.MESSAGE_ID, default_value : "")
  395. guard !message_id.isEmpty else {
  396. return
  397. }
  398. let f_pin = message.getBody(key : CoreMessage_TMessageKey.F_PIN, default_value : "")
  399. guard !f_pin.isEmpty else {
  400. return
  401. }
  402. let l_pin = message.getBody(key : CoreMessage_TMessageKey.L_PIN, default_value : "")
  403. let scope = message.getBody(key : CoreMessage_TMessageKey.MESSAGE_SCOPE_ID, default_value : "3")
  404. let status = message.getBody(key : CoreMessage_TMessageKey.STATUS, default_value : "")
  405. let chat_id = message.getBody(key : CoreMessage_TMessageKey.CHAT_ID, default_value : "")
  406. let broadcast_flag = message.getBody(key: CoreMessage_TMessageKey.BROADCAST_FLAG, default_value: "0")
  407. let is_call_center = message.getBody(key: CoreMessage_TMessageKey.IS_CALL_CENTER, default_value: "0")
  408. let call_center_id = message.getBody(key: CoreMessage_TMessageKey.CALL_CENTER_ID, default_value: "")
  409. print("prepare save db")
  410. Database.shared.database?.inTransaction({ (fmdb, rollback) in
  411. do {
  412. _ = try Database.shared.insertRecord(fmdb: fmdb, table: "MESSAGE", cvalues: [
  413. "message_id" : message_id,
  414. "f_pin" : f_pin,
  415. "f_display_name" : message.getBody(key : CoreMessage_TMessageKey.F_DISPLAY_NAME, default_value : ""),
  416. "l_pin" : l_pin,
  417. "l_user_id" : message.getBody(key : CoreMessage_TMessageKey.L_USER_ID, default_value : ""),
  418. "message_scope_id" : scope,
  419. "server_date" : message.getBody(key: CoreMessage_TMessageKey.SERVER_DATE, default_value : String(Date().currentTimeMillis())),
  420. "status" : status,
  421. "message_text" : message.getBody(key : CoreMessage_TMessageKey.MESSAGE_TEXT, default_value : "").toNormalString(),
  422. "audio_id" : message.getBody(key : CoreMessage_TMessageKey.AUDIO_ID, default_value : ""),
  423. "video_id" : message.getBody(key : CoreMessage_TMessageKey.VIDEO_ID, default_value : ""),
  424. "image_id" : message.getBody(key : CoreMessage_TMessageKey.IMAGE_ID, default_value : ""),
  425. "file_id" : message.getBody(key : CoreMessage_TMessageKey.FILE_ID, default_value : ""),
  426. "thumb_id" : message.getBody(key : CoreMessage_TMessageKey.THUMB_ID, default_value : ""),
  427. "opposite_pin" : message.getBody(key : CoreMessage_TMessageKey.L_PIN, default_value : ""),
  428. "format" : message.getBody(key : CoreMessage_TMessageKey.FORMAT, default_value : ""),
  429. "blog_id" : message.getBody(key : CoreMessage_TMessageKey.BLOG_ID, default_value : ""),
  430. "read_receipts" : message.getBody(key: CoreMessage_TMessageKey.READ_RECEIPTS, default_value: "0"),
  431. "chat_id" : chat_id,
  432. "account_type" : message.getBody(key : CoreMessage_TMessageKey.ACCOUNT_TYPE, default_value : "1"),
  433. "credential" : message.getBody(key : CoreMessage_TMessageKey.CREDENTIAL, default_value : ""),
  434. "reff_id" : message.getBody(key : CoreMessage_TMessageKey.REF_ID, default_value : ""),
  435. "message_large_text" : message.getBody(key : CoreMessage_TMessageKey.BODY, default_value : "").toNormalString(),
  436. "attachment_flag" : message.getBody(key: CoreMessage_TMessageKey.ATTACHMENT_FLAG, default_value: "0"),
  437. "local_timestamp" : message.getBody(key: CoreMessage_TMessageKey.LOCAL_TIMESTAMP, default_value : String(Date().currentTimeMillis())),
  438. "broadcast_flag" : broadcast_flag,
  439. "is_call_center" : is_call_center,
  440. "call_center_id" : call_center_id
  441. ], replace: true)
  442. } catch {
  443. rollback.pointee = true
  444. print(error)
  445. }
  446. })
  447. if withStatus {
  448. Database.shared.database?.inTransaction({ (fmdb, rollback) in
  449. do {
  450. if scope == "4" {
  451. for pin in getGroupMembers(fmdb: fmdb, l_pin: l_pin) {
  452. if f_pin == pin { continue }
  453. _ = try Database.shared.insertRecord(fmdb: fmdb, table: "MESSAGE_STATUS", cvalues: [
  454. "message_id" : message_id,
  455. "status" : status,
  456. "f_pin" : pin,
  457. "last_update" : Date().currentTimeMillis()
  458. ], replace: true)
  459. }
  460. } else {
  461. _ = try Database.shared.insertRecord(fmdb: fmdb, table: "MESSAGE_STATUS", cvalues: [
  462. "message_id" : message_id,
  463. "status" : status,
  464. "f_pin" : l_pin,
  465. "last_update" : Date().currentTimeMillis()
  466. ], replace: true)
  467. }
  468. } catch {
  469. rollback.pointee = true
  470. print(error)
  471. }
  472. })
  473. }
  474. var pin = l_pin
  475. if l_pin == me {
  476. pin = f_pin
  477. }
  478. if !chat_id.isEmpty {
  479. pin = chat_id
  480. }
  481. var counter : Int? = nil
  482. if l_pin == me || (scope == "4" && f_pin != me) {
  483. Database.shared.database?.inTransaction({ (fmdb, rollback) in
  484. if let cursor = Database.shared.getRecords(fmdb: fmdb, query: "select counter from MESSAGE_SUMMARY where l_pin = '\(pin)'"), cursor.next() {
  485. counter = Int(cursor.int(forColumnIndex: 0))
  486. counter! += 1
  487. cursor.close()
  488. print("select db message summary")
  489. }
  490. })
  491. if counter == nil {
  492. counter = 1
  493. print("set counter message summary")
  494. }
  495. }
  496. if counter == nil {
  497. counter = 0
  498. }
  499. if is_call_center == "0" {
  500. Database.shared.database?.inTransaction({ (fmdb, rollback) in
  501. do {
  502. _ = try Database.shared.insertRecord(fmdb: fmdb, table: "MESSAGE_SUMMARY", cvalues: [
  503. "l_pin" : pin,
  504. "message_id" : message_id,
  505. "counter" : counter!
  506. ], replace: true)
  507. } catch {
  508. rollback.pointee = true
  509. print(error)
  510. }
  511. })
  512. }
  513. print("insert db message summary \(message_id)")
  514. }
  515. public static func saveMessageBot(textMessage: String, blog_id: String, attachment_type:String)->Void{
  516. guard let me = UserDefaults.standard.string(forKey: "me") else {
  517. return
  518. }
  519. var user_id:String? = ""
  520. let message_id = me + CoreMessage_TMessageUtil.getTID()
  521. Database.shared.database?.inTransaction({ (fmdb, rollback) in
  522. if let cursor = Database.shared.getRecords(fmdb: fmdb, query: "select user_id from BUDDY where f_pin = '\(me)'"), cursor.next() {
  523. user_id = cursor.string(forColumnIndex: 0)
  524. cursor.close()
  525. }
  526. })
  527. Database.shared.database?.inTransaction({ (fmdb, rollback) in
  528. do {
  529. _ = try Database.shared.insertRecord(fmdb: fmdb, table: "MESSAGE", cvalues: [
  530. "message_id" : message_id ,
  531. "f_pin" : "-999",
  532. "f_display_name" : "Bot",
  533. "l_pin" : me,
  534. "l_user_id" : String(user_id!),
  535. "message_scope_id" : "3",
  536. "server_date" : String(Date().currentTimeMillis()),
  537. "status" : "3",
  538. "message_text" : textMessage,
  539. "audio_id" : "",
  540. "video_id" : "",
  541. "image_id" : "",
  542. "file_id" : "",
  543. "thumb_id" : "",
  544. "opposite_pin" : "",
  545. "format" : "",
  546. "blog_id" : blog_id,
  547. "read_receipts" : "0",
  548. "chat_id" : "",
  549. "account_type" : "1",
  550. "credential" :"",
  551. "reff_id" : "",
  552. "message_large_text" : "",
  553. "attachment_flag" : attachment_type,
  554. "local_timestamp" : String(Date().currentTimeMillis())
  555. ], replace: true)
  556. } catch {
  557. rollback.pointee = true
  558. print(error)
  559. }
  560. })
  561. let pin = "-999"
  562. var counter : Int? = nil
  563. Database.shared.database?.inTransaction({ (fmdb, rollback) in
  564. if let cursor = Database.shared.getRecords(fmdb: fmdb, query: "select counter from MESSAGE_SUMMARY where l_pin = '\(pin)'"), cursor.next() {
  565. counter = Int(cursor.int(forColumnIndex: 0))
  566. counter! += 1
  567. cursor.close()
  568. print("select db message summary")
  569. }
  570. })
  571. if counter == nil {
  572. counter = 1
  573. print("set counter message summary")
  574. }
  575. Database.shared.database?.inTransaction({ (fmdb, rollback) in
  576. do {
  577. _ = try Database.shared.insertRecord(fmdb: fmdb, table: "MESSAGE_SUMMARY", cvalues: [
  578. "l_pin" : pin,
  579. "message_id" : message_id,
  580. "counter" : counter!
  581. ], replace: true)
  582. } catch {
  583. rollback.pointee = true
  584. print(error)
  585. }
  586. })
  587. print("insert db message summary \(message_id)")
  588. }
  589. static func updateMessageStatus(message: TMessage) -> Void {
  590. let message_id = message.getBody(key : CoreMessage_TMessageKey.MESSAGE_ID, default_value : "")
  591. guard !message_id.isEmpty else {
  592. return
  593. }
  594. let status = message.getBody(key : CoreMessage_TMessageKey.STATUS, default_value : "")
  595. guard !status.isEmpty else {
  596. return
  597. }
  598. let l_pin = message.getBody(key : CoreMessage_TMessageKey.L_PIN, default_value : "")
  599. guard !l_pin.isEmpty else {
  600. return
  601. }
  602. Database.shared.database?.inTransaction({ (fmdb, rollbac) in
  603. if message_id.starts(with: "-1") || message_id.starts(with: "-2") {
  604. for s in message_id.split(separator: ",") {
  605. let t = s.trimmingCharacters(in: .whitespaces)
  606. if t == "-1" || t == "-2" {
  607. continue
  608. }
  609. _ = Database.shared.updateRecord(fmdb: fmdb, table: "MESSAGE_STATUS", cvalues: [
  610. "status" : status,
  611. "last_update" : String(Date().currentTimeMillis())], _where: "message_id = '\(t)' and f_pin = '\(l_pin)'")
  612. }
  613. } else {
  614. _ = Database.shared.updateRecord(fmdb: fmdb, table: "MESSAGE_STATUS", cvalues: [
  615. "status" : status,
  616. "last_update" : String(Date().currentTimeMillis())], _where: "message_id = '\(message_id)' and f_pin = '\(l_pin)'")
  617. }
  618. })
  619. }
  620. static func getGroupMembers(fmdb: FMDatabase, l_pin: String) -> [String] {
  621. var result = [String]()
  622. if let cursor = Database.shared.getRecords(fmdb: fmdb, query: "select f_pin from GROUPZ_MEMBER where group_id = '\(l_pin)'") {
  623. while cursor.next() {
  624. if let value = cursor.string(forColumnIndex: 0) {
  625. result.append(value)
  626. }
  627. }
  628. cursor.close()
  629. }
  630. return result
  631. }
  632. static func getVideoThumbnail(name: String, completion: @escaping (Bool)->()) {
  633. DispatchQueue.global().async {
  634. do {
  635. let fileManager = FileManager.default
  636. let documentDir = try fileManager.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
  637. let fileDir = documentDir.appendingPathComponent(name)
  638. let path = fileDir.path
  639. if FileManager.default.fileExists(atPath: path) {
  640. let asset = AVAsset(url: URL(fileURLWithPath: path))
  641. let avAssetImageGenerator = AVAssetImageGenerator(asset: asset)
  642. avAssetImageGenerator.appliesPreferredTrackTransform = true
  643. let thumnailTime = CMTimeMake(value: 2, timescale: 1)
  644. let thumbImage = UIImage(cgImage: try avAssetImageGenerator.copyCGImage(at: thumnailTime, actualTime: nil))
  645. guard let data = thumbImage.jpegData(compressionQuality: 1.0) else {
  646. completion(false)
  647. return
  648. }
  649. let thumbFileDir = documentDir.appendingPathComponent("THUMB_" + name)
  650. try data.write(to: thumbFileDir)
  651. completion(true)
  652. } else {
  653. completion(false)
  654. }
  655. } catch {
  656. print(error)
  657. }
  658. }
  659. }
  660. static func resizedImage(at url: URL, for size: CGSize) -> UIImage? {
  661. guard let image = UIImage(contentsOfFile: url.path) else {
  662. return nil
  663. }
  664. let renderer = UIGraphicsImageRenderer(size: size)
  665. return renderer.image { (context) in
  666. image.draw(in: CGRect(origin: .zero, size: size))
  667. }
  668. }
  669. static func initFollowing() -> Void {
  670. if let me = UserDefaults.standard.string(forKey: "me") {
  671. if let response = Nexilis.writeSync(message: CoreMessage_TMessageBank.getListFollowing(l_pin: me)) {
  672. let data = response.getBody(key: CoreMessage_TMessageKey.DATA)
  673. if !data.isEmpty {
  674. if let jsonArray = try! JSONSerialization.jsonObject(with: data.data(using: String.Encoding.utf8)!, options: JSONSerialization.ReadingOptions()) as? [AnyObject] {
  675. Database.shared.database?.inTransaction({ (fmdb, rollback) in
  676. do {
  677. for json in jsonArray {
  678. _ = try Database.shared.insertRecord(fmdb: fmdb, table: "FOLLOW", cvalues: [
  679. "f_pin" : CoreMessage_TMessageUtil.getString(json: json, key: "pin")
  680. ], replace: true)
  681. }
  682. } catch {
  683. rollback.pointee = true
  684. print(error)
  685. }
  686. })
  687. }
  688. }
  689. }
  690. }
  691. }
  692. // do {
  693. // _ = try Database.shared.insertRecord(fmdb: fmdb, table: "CALL_CENTER_HISTORY", cvalues: [
  694. // "type" : "1",
  695. // "title" : displayName,
  696. // "time" : timeStart,
  697. // "f_pin" : f_pin,
  698. // "data" : dataCC,
  699. // "time_end" : date,
  700. // "complaint_id" : complaint_id.isEmpty ? "C\(date)" : complaint_id,
  701. // "members" : "",
  702. // "requester": ""
  703. // ], replace: true)
  704. // _ = try Database.shared.insertRecord(fmdb: fmdb, table: "PREFS", cvalues: [
  705. // "key" : "CC:\(f_pin)",
  706. // "value" : status,
  707. // ], replace: true)
  708. // ret = true
  709. // } catch {
  710. // rollback.pointee = true
  711. // print(error)
  712. // }
  713. private static var uploadQueue = DispatchQueue(label: "UPLOAD_DICT", attributes: .concurrent)
  714. private static var UPLOAD_DICT = [String: Network]()
  715. static func removeUploadFile(forKey: String) -> Network? {
  716. var _result: Network? = nil
  717. uploadQueue.sync {
  718. _result = self.UPLOAD_DICT.removeValue(forKey: forKey)
  719. }
  720. return _result
  721. }
  722. static func putUploadFile(forKey: String, uploader: Network) {
  723. uploadQueue.async (flags: .barrier) {
  724. self.UPLOAD_DICT[forKey] = uploader
  725. }
  726. }
  727. static func getUploadFile(forKey: String) -> Network? {
  728. var _result: Network? = nil
  729. uploadQueue.sync {
  730. _result = self.UPLOAD_DICT[forKey]
  731. }
  732. return _result
  733. }
  734. private static var downloadQueue = DispatchQueue(label: "DOWNLOAD_DICT", attributes: .concurrent)
  735. private static var DOWNLOAD_DICT = [String:Download]()
  736. static func addDownload(forKey : String, download: Download){
  737. downloadQueue.async (flags: .barrier) {
  738. self.DOWNLOAD_DICT[forKey] = download
  739. }
  740. }
  741. static func getDownload(forKey: String) -> Download? {
  742. var _result: Download? = nil
  743. downloadQueue.sync {
  744. _result = self.DOWNLOAD_DICT[forKey]
  745. }
  746. return _result
  747. }
  748. static func writeImageToFile(data: Data, fileName: String){
  749. guard let directory = FileManager.default.urls(for: .picturesDirectory, in: .userDomainMask).last else {
  750. return
  751. }
  752. let fileURL = directory.appendingPathComponent("\(fileName)")
  753. if FileManager.default.fileExists(atPath: fileURL.path) {
  754. if let fileHandle = FileHandle(forWritingAtPath: fileURL.path) {
  755. fileHandle.seekToEndOfFile()
  756. fileHandle.write(data)
  757. fileHandle.closeFile()
  758. } else {
  759. print("Can't open file to write")
  760. }
  761. } else {
  762. do {
  763. try data.write(to: fileURL, options: .atomic)
  764. } catch {
  765. print("Unable to write in new file")
  766. }
  767. }
  768. }
  769. static func writeVideoToFile(data: Data, fileName: String){
  770. guard let directory = FileManager.default.urls(for: .moviesDirectory, in: .userDomainMask).last else {
  771. return
  772. }
  773. let fileURL = directory.appendingPathComponent("\(fileName)")
  774. if FileManager.default.fileExists(atPath: fileURL.path) {
  775. if let fileHandle = FileHandle(forWritingAtPath: fileURL.path) {
  776. fileHandle.seekToEndOfFile()
  777. fileHandle.write(data)
  778. fileHandle.closeFile()
  779. } else {
  780. print("Can't open file to write")
  781. }
  782. } else {
  783. do {
  784. try data.write(to: fileURL, options: .atomic)
  785. } catch {
  786. print("Unable to write in new file")
  787. }
  788. }
  789. }
  790. static func writeDocumentsToFile(data: Data, fileName: String){
  791. guard let directory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).last else {
  792. return
  793. }
  794. let fileURL = directory.appendingPathComponent("\(fileName)")
  795. if FileManager.default.fileExists(atPath: fileURL.path) {
  796. if let fileHandle = FileHandle(forWritingAtPath: fileURL.path) {
  797. fileHandle.seekToEndOfFile()
  798. fileHandle.write(data)
  799. fileHandle.closeFile()
  800. } else {
  801. print("Can't open file to write")
  802. }
  803. } else {
  804. do {
  805. try data.write(to: fileURL, options: .atomic)
  806. } catch {
  807. print("Unable to write in new file")
  808. }
  809. }
  810. }
  811. /*
  812. * Delegate
  813. */
  814. weak open var loginDelegate: LoginDelegate?
  815. weak open var messageDelegate: MessageDelegate?
  816. weak open var groupDelegate: GroupDelegate?
  817. weak open var callDelegate: CallDelegate?
  818. weak open var streamingDelagate: LiveStreamingDelegate?
  819. weak open var personInfoDelegate: PersonInfoDelegate?
  820. weak open var screenSharingDelegate: ScreenSharingDelegate?
  821. weak open var commentDelegate: CommentDelegate?
  822. weak open var uploadDelegate: UploadDelegate?
  823. weak open var timelineDelegate: TimelineDelegate?
  824. weak open var connectionDelegate: ConnectionDelegate?
  825. }
  826. public protocol LoginDelegate: NSObjectProtocol {
  827. func onProgress(code: String, progress: Int)
  828. func onProcess(message: String, status: String)
  829. }
  830. public protocol MessageDelegate: NSObjectProtocol {
  831. func onReceive(message: TMessage)
  832. func onReceiveComment(message: TMessage)
  833. func onReceive(message: [AnyHashable: Any?])
  834. func onMessage(message: TMessage)
  835. func onUpload(name: String, progress: Double)
  836. func onTyping(message: TMessage)
  837. }
  838. public protocol GroupDelegate: NSObjectProtocol {
  839. func onGroup(code: String, f_pin: String, groupId: String)
  840. func onTopic(code: String, f_pin: String, topicId: String)
  841. func onMember(code: String, f_pin: String, groupId: String, member: String)
  842. }
  843. public protocol DownloadDelegate: NSObjectProtocol {
  844. func onDownloadProgress(fileName: String, progress: Double)
  845. }
  846. public protocol CallDelegate: NSObjectProtocol {
  847. func onIncomingCall(state: Int, message: String)
  848. func onStatusCall(state: Int, message: String)
  849. }
  850. public protocol LiveStreamingDelegate: NSObjectProtocol {
  851. func onStartLS(state: Int, message: String)
  852. func onJoinLS(state: Int, message: String)
  853. }
  854. public protocol VideoCallDelegate: NSObjectProtocol {
  855. func onInitiateVideoCall(destination:String,state: Int, message: String)
  856. func onAcceptVideoCall(originator:String,state: Int, message: String)
  857. func onVideoCallReceiverTerminate(originator:String,state: Int, message: String)
  858. }
  859. public protocol PersonInfoDelegate: NSObjectProtocol {
  860. func onUpdatePersonInfo(state: Int, message: String)
  861. }
  862. public protocol ScreenSharingDelegate: NSObjectProtocol {
  863. func onStartScreenSharing(state:Int,message:String)
  864. func onJoinScreenSharing(state:Int,message:String)
  865. }
  866. public protocol CommentDelegate: NSObjectProtocol {
  867. func onReceiveComment(message: TMessage)
  868. func onDeleteComment(message: TMessage)
  869. }
  870. public protocol UploadDelegate: NSObjectProtocol {
  871. func onUploadProgress(fileName: String, progress: Double)
  872. }
  873. public protocol TimelineDelegate: NSObjectProtocol {
  874. func onPostUpdate(status: String, message: String)
  875. }
  876. public protocol ConnectionDelegate: NSObjectProtocol {
  877. func connectionStateChanged(userId: String!, deviceId: String, state: Bool)
  878. }
  879. public protocol ConnectDelegate: NSObjectProtocol {
  880. func onSuccess(userId: String)
  881. func onFailed(error: String)
  882. }
  883. public enum AppStoryBoard: String {
  884. case Palio = "Palio"
  885. public var instance: UIStoryboard {
  886. return UIStoryboard(name: self.rawValue, bundle: Bundle.resourceBundle(for: Nexilis.self))
  887. }
  888. }
  889. extension Nexilis: CallDelegate {
  890. func displayIncomingCall(uuid: UUID, handle: String, hasVideo: Bool = false, completion: ((Error?) -> Void)? = nil) {
  891. providerDelegate?.reportIncomingCall(uuid: uuid, handle: handle, hasVideo: hasVideo, completion: completion)
  892. }
  893. public func onIncomingCall(state: Int, message: String) {
  894. let deviceId = message.split(separator: ",")[0]
  895. if (state == 21) {
  896. let backgroundTaskIdentifier = UIApplication.shared.beginBackgroundTask(expirationHandler: nil)
  897. DispatchQueue.main.async {
  898. self.displayIncomingCall(uuid: UUID(), handle: String(deviceId), hasVideo: false) { error in
  899. UIApplication.shared.endBackgroundTask(backgroundTaskIdentifier)
  900. }
  901. }
  902. } else {
  903. let fpin = deviceId
  904. var data: [String: String?] = [:]
  905. Database.shared.database?.inTransaction({ (fmdb, rollback) in
  906. 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)'") {
  907. while cursorData.next() {
  908. data["f_pin"] = cursorData.string(forColumnIndex: 0)
  909. var name = ""
  910. if let firstname = cursorData.string(forColumnIndex: 1) {
  911. name = firstname
  912. }
  913. if let lastname = cursorData.string(forColumnIndex: 2) {
  914. name = name + " " + lastname
  915. }
  916. data["name"] = name
  917. data["picture"] = cursorData.string(forColumnIndex: 4)
  918. data["isOfficial"] = cursorData.string(forColumnIndex: 3)
  919. data["deviceId"] = cursorData.string(forColumnIndex: 5)
  920. data["isOffline"] = cursorData.string(forColumnIndex: 6)
  921. data["user_type"] = cursorData.string(forColumnIndex: 7)
  922. }
  923. cursorData.close()
  924. }
  925. })
  926. DispatchQueue.main.async {
  927. let videoController = AppStoryBoard.Palio.instance.instantiateViewController(withIdentifier: "videoVCQmera") as! QmeraVideoViewController
  928. videoController.dataPerson.append(data)
  929. videoController.isInisiator = false
  930. let navigationController = UINavigationController(rootViewController: videoController)
  931. navigationController.modalPresentationStyle = .fullScreen
  932. let checkViewController = UIApplication.shared.windows.filter {$0.isKeyWindow}.first?.rootViewController?.presentedViewController
  933. if checkViewController == nil {
  934. UIApplication.shared.windows.filter {$0.isKeyWindow}.last?.rootViewController?.present(navigationController, animated: true, completion: nil)
  935. } else {
  936. UIApplication.shared.windows.filter {$0.isKeyWindow}.last?.rootViewController?.presentedViewController?.present(navigationController, animated: true, completion: nil)
  937. }
  938. }
  939. }
  940. }
  941. public func onStatusCall(state: Int, message: String) {
  942. let r = message.split(separator: ",")
  943. if state == 23 {
  944. if let call = callManager.call(with: String(r[0])) {
  945. print("onStatusCall:connectingCall")
  946. DispatchQueue.main.async {
  947. call.connectingCall()
  948. }
  949. }
  950. } else if state == 22 {
  951. if let call = callManager.call(with: String(r[1])) {
  952. print("onStatusCall:answerCall")
  953. DispatchQueue.main.async {
  954. call.answerCall()
  955. }
  956. }
  957. }
  958. var dataCall: [AnyHashable : Any] = [:]
  959. dataCall["state"] = state
  960. dataCall["message"] = message
  961. NotificationCenter.default.post(name: NSNotification.Name(rawValue: "onStatusCall"), object: nil, userInfo: dataCall)
  962. }
  963. }
  964. var previewItem : NSURL?
  965. extension Nexilis: MessageDelegate {
  966. public func onReceiveComment(message: TMessage) {
  967. var dataMessage: [AnyHashable : Any] = [:]
  968. dataMessage["message"] = message
  969. NotificationCenter.default.post(name: NSNotification.Name(rawValue: "onReceiveComment"), object: nil, userInfo: dataMessage)
  970. }
  971. @objc func tapLinkBroadcast(_ sender: ObjectGesture) {
  972. var stringURl = sender.message_id.lowercased()
  973. if stringURl.starts(with: "www.") {
  974. stringURl = "https://" + stringURl.replacingOccurrences(of: "www.", with: "")
  975. }
  976. guard let url = URL(string: stringURl) else { return }
  977. UIApplication.shared.open(url)
  978. }
  979. func showBroadcastMessage(m: [String: String]) {
  980. let fileType = m[CoreMessage_TMessageKey.CATEGORY_FLAG]!
  981. let alert = UIAlertController(title: "", message: "\n\n\n\n\n\n\n\n\n\n".localized(), preferredStyle: .alert)
  982. let newWidth = UIScreen.main.bounds.width * 0.90 - 270
  983. // update width constraint value for main view
  984. if let viewWidthConstraint = alert.view.constraints.filter({ return $0.firstAttribute == .width }).first{
  985. viewWidthConstraint.constant = newWidth
  986. }
  987. // update width constraint value for container view
  988. if let containerViewWidthConstraint = alert.view.subviews.first?.constraints.filter({ return $0.firstAttribute == .width }).first {
  989. containerViewWidthConstraint.constant = newWidth
  990. }
  991. let titleFont = [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 18), NSAttributedString.Key.foregroundColor: UIColor.black]
  992. let titleAttrString = NSMutableAttributedString(string: m["MERNAM"]!.localized(), attributes: titleFont)
  993. alert.setValue(titleAttrString, forKey: "attributedTitle")
  994. alert.view.subviews.first?.subviews.first?.subviews.first?.backgroundColor = .lightGray
  995. alert.view.tintColor = .black
  996. if fileType != BroadcastViewController.FILE_TYPE_CHAT{
  997. let height:NSLayoutConstraint = NSLayoutConstraint(item: alert.view!, attribute: NSLayoutConstraint.Attribute.height, relatedBy: NSLayoutConstraint.Relation.equal, toItem: nil, attribute: NSLayoutConstraint.Attribute.notAnAttribute, multiplier: 1, constant: UIScreen.main.bounds.height * 0.6)
  998. alert.view.addConstraint(height)
  999. }
  1000. var containerView = UIView(frame: CGRect(x: 20, y: 60, width: alert.view.bounds.size.width * 0.9 - 40, height: 350))
  1001. if fileType == BroadcastViewController.FILE_TYPE_CHAT {
  1002. containerView = UIView(frame: CGRect(x: 20, y: 60, width: alert.view.bounds.size.width * 0.9 - 40, height: 100))
  1003. }
  1004. alert.view.addSubview(containerView)
  1005. containerView.layer.cornerRadius = 10.0
  1006. containerView.clipsToBounds = true
  1007. let buttonClose = UIButton(type: .close)
  1008. buttonClose.frame = CGRect(x: alert.view.bounds.size.width * 0.9 - 50, y: 15, width: 30, height: 30)
  1009. buttonClose.layer.cornerRadius = 15.0
  1010. buttonClose.clipsToBounds = true
  1011. buttonClose.backgroundColor = .secondaryColor.withAlphaComponent(0.5)
  1012. buttonClose.actionHandle(controlEvents: .touchUpInside,
  1013. ForAction:{() -> Void in
  1014. alert.dismiss(animated: true, completion: nil)
  1015. })
  1016. alert.view.addSubview(buttonClose)
  1017. let titleBroadcast = UILabel()
  1018. containerView.addSubview(titleBroadcast)
  1019. titleBroadcast.translatesAutoresizingMaskIntoConstraints = false
  1020. NSLayoutConstraint.activate([
  1021. titleBroadcast.topAnchor.constraint(equalTo: containerView.topAnchor),
  1022. titleBroadcast.leadingAnchor.constraint(equalTo: containerView.leadingAnchor),
  1023. ])
  1024. titleBroadcast.font = UIFont.systemFont(ofSize: 18)
  1025. titleBroadcast.text = m[CoreMessage_TMessageKey.TITLE]
  1026. titleBroadcast.textColor = .black
  1027. let descBroadcast = UILabel()
  1028. containerView.addSubview(descBroadcast)
  1029. descBroadcast.translatesAutoresizingMaskIntoConstraints = false
  1030. NSLayoutConstraint.activate([
  1031. descBroadcast.topAnchor.constraint(equalTo: titleBroadcast.bottomAnchor, constant: 10),
  1032. descBroadcast.leadingAnchor.constraint(equalTo: containerView.leadingAnchor),
  1033. ])
  1034. descBroadcast.font = UIFont.systemFont(ofSize: 15)
  1035. descBroadcast.text = m["A07_eng"]
  1036. descBroadcast.textColor = .black
  1037. let stringLink = m[CoreMessage_TMessageKey.LINK] ?? ""
  1038. let linkBroadcast = UILabel()
  1039. if !stringLink.isEmpty {
  1040. containerView.addSubview(linkBroadcast)
  1041. linkBroadcast.translatesAutoresizingMaskIntoConstraints = false
  1042. NSLayoutConstraint.activate([
  1043. linkBroadcast.topAnchor.constraint(equalTo: descBroadcast.bottomAnchor, constant: 10),
  1044. linkBroadcast.leadingAnchor.constraint(equalTo: containerView.leadingAnchor),
  1045. ])
  1046. linkBroadcast.font = UIFont.systemFont(ofSize: 15)
  1047. linkBroadcast.isUserInteractionEnabled = true
  1048. let attributedString = NSMutableAttributedString(string: stringLink, attributes:[NSAttributedString.Key.link: URL(string: stringLink)!])
  1049. linkBroadcast.attributedText = attributedString
  1050. let tap = ObjectGesture(target: self, action: #selector(tapLinkBroadcast))
  1051. tap.message_id = stringLink
  1052. linkBroadcast.addGestureRecognizer(tap)
  1053. }
  1054. let dottedLine = UIView()
  1055. containerView.addSubview(dottedLine)
  1056. dottedLine.translatesAutoresizingMaskIntoConstraints = false
  1057. var constraintDottedLine = dottedLine.topAnchor.constraint(equalTo: descBroadcast.bottomAnchor, constant: 20)
  1058. if !stringLink.isEmpty{
  1059. constraintDottedLine = dottedLine.topAnchor.constraint(equalTo: linkBroadcast.bottomAnchor, constant: 20)
  1060. }
  1061. NSLayoutConstraint.activate([
  1062. constraintDottedLine,
  1063. dottedLine.leadingAnchor.constraint(equalTo: containerView.leadingAnchor),
  1064. dottedLine.widthAnchor.constraint(equalToConstant: alert.view.bounds.size.width * 0.9 - 40),
  1065. dottedLine.heightAnchor.constraint(equalToConstant: 2)
  1066. ])
  1067. dottedLine.backgroundColor = .black.withAlphaComponent(0.1)
  1068. let shapeLayer = CAShapeLayer()
  1069. shapeLayer.strokeColor = UIColor.black.withAlphaComponent(0.2).cgColor
  1070. shapeLayer.lineWidth = 2
  1071. // passing an array with the values [2,3] sets a dash pattern that alternates between a 2-user-space-unit-long painted segment and a 3-user-space-unit-long unpainted segment
  1072. shapeLayer.lineDashPattern = [2,3]
  1073. let path = CGMutablePath()
  1074. path.addLines(between: [CGPoint(x: 0, y: 0),
  1075. CGPoint(x: alert.view.bounds.size.width * 0.9 - 20, y: 0)])
  1076. shapeLayer.path = path
  1077. dottedLine.layer.addSublayer(shapeLayer)
  1078. let thumb = m[CoreMessage_TMessageKey.THUMB_ID] ?? ""
  1079. let image = m[CoreMessage_TMessageKey.IMAGE_ID] ?? ""
  1080. let video = m[CoreMessage_TMessageKey.VIDEO_ID] ?? ""
  1081. let file = m[CoreMessage_TMessageKey.FILE_ID] ?? ""
  1082. if fileType != BroadcastViewController.FILE_TYPE_CHAT {
  1083. let imageBroadcast = UIImageView()
  1084. containerView.addSubview(imageBroadcast)
  1085. imageBroadcast.translatesAutoresizingMaskIntoConstraints = false
  1086. NSLayoutConstraint.activate([
  1087. imageBroadcast.topAnchor.constraint(equalTo: dottedLine.bottomAnchor, constant: 20),
  1088. imageBroadcast.widthAnchor.constraint(equalToConstant: alert.view.bounds.size.width * 0.9 - 40),
  1089. imageBroadcast.heightAnchor.constraint(equalToConstant: 250)
  1090. ])
  1091. imageBroadcast.layer.cornerRadius = 10.0
  1092. imageBroadcast.clipsToBounds = true
  1093. if fileType != BroadcastViewController.FILE_TYPE_DOCUMENT {
  1094. imageBroadcast.contentMode = .scaleAspectFill
  1095. imageBroadcast.setImage(name: thumb)
  1096. if fileType == BroadcastViewController.FILE_TYPE_VIDEO {
  1097. let imagePlay = UIImageView(image: UIImage(systemName: "play.circle.fill"))
  1098. imageBroadcast.addSubview(imagePlay)
  1099. imagePlay.clipsToBounds = true
  1100. imagePlay.translatesAutoresizingMaskIntoConstraints = false
  1101. imagePlay.centerYAnchor.constraint(equalTo: imageBroadcast.centerYAnchor).isActive = true
  1102. imagePlay.centerXAnchor.constraint(equalTo: imageBroadcast.centerXAnchor).isActive = true
  1103. imagePlay.widthAnchor.constraint(equalToConstant: 60).isActive = true
  1104. imagePlay.heightAnchor.constraint(equalToConstant: 60).isActive = true
  1105. imagePlay.tintColor = .gray.withAlphaComponent(0.5)
  1106. }
  1107. } else {
  1108. imageBroadcast.image = UIImage(systemName: "doc.fill")
  1109. imageBroadcast.tintColor = .mainColor
  1110. imageBroadcast.contentMode = .scaleAspectFit
  1111. }
  1112. imageBroadcast.actionHandle(controlEvents: .touchUpInside,
  1113. ForAction:{() -> Void in
  1114. let nsDocumentDirectory = FileManager.SearchPathDirectory.documentDirectory
  1115. let nsUserDomainMask = FileManager.SearchPathDomainMask.userDomainMask
  1116. let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true)
  1117. if fileType == BroadcastViewController.FILE_TYPE_IMAGE {
  1118. if let dirPath = paths.first {
  1119. let imageURL = URL(fileURLWithPath: dirPath).appendingPathComponent(image)
  1120. if FileManager.default.fileExists(atPath: imageURL.path) {
  1121. let image = UIImage(contentsOfFile: imageURL.path)
  1122. let previewImageVC = PreviewAttachmentImageVideo(nibName: "PreviewAttachmentImageVideo", bundle: Bundle.resourceBundle(for: Nexilis.self))
  1123. previewImageVC.image = image
  1124. previewImageVC.isHiddenTextField = true
  1125. previewImageVC.modalPresentationStyle = .overFullScreen
  1126. previewImageVC.modalTransitionStyle = .crossDissolve
  1127. let checkViewController = UIApplication.shared.windows.filter {$0.isKeyWindow}.first?.rootViewController?.presentedViewController
  1128. if checkViewController != nil {
  1129. UIApplication.shared.windows.filter {$0.isKeyWindow}.first?.rootViewController?.presentedViewController?.present(previewImageVC, animated: true, completion: nil)
  1130. } else {
  1131. UIApplication.shared.windows.filter {$0.isKeyWindow}.first?.rootViewController?.present(previewImageVC, animated: true, completion: nil)
  1132. }
  1133. } else {
  1134. Download().start(forKey: image) { (name, progress) in
  1135. guard progress == 100 else {
  1136. return
  1137. }
  1138. DispatchQueue.main.async {
  1139. let image = UIImage(contentsOfFile: imageURL.path)
  1140. let previewImageVC = PreviewAttachmentImageVideo(nibName: "PreviewAttachmentImageVideo", bundle: Bundle.resourceBundle(for: Nexilis.self))
  1141. previewImageVC.image = image
  1142. previewImageVC.isHiddenTextField = true
  1143. previewImageVC.modalPresentationStyle = .overFullScreen
  1144. previewImageVC.modalTransitionStyle = .crossDissolve
  1145. let checkViewController = UIApplication.shared.windows.filter {$0.isKeyWindow}.first?.rootViewController?.presentedViewController
  1146. if checkViewController != nil {
  1147. UIApplication.shared.windows.filter {$0.isKeyWindow}.first?.rootViewController?.presentedViewController?.present(previewImageVC, animated: true, completion: nil)
  1148. } else {
  1149. UIApplication.shared.windows.filter {$0.isKeyWindow}.first?.rootViewController?.present(previewImageVC, animated: true, completion: nil)
  1150. }
  1151. }
  1152. }
  1153. }
  1154. }
  1155. } else if fileType == BroadcastViewController.FILE_TYPE_VIDEO {
  1156. if let dirPath = paths.first {
  1157. let videoURL = URL(fileURLWithPath: dirPath).appendingPathComponent(video)
  1158. if FileManager.default.fileExists(atPath: videoURL.path) {
  1159. let player = AVPlayer(url: videoURL as URL)
  1160. let playerVC = AVPlayerViewController()
  1161. playerVC.player = player
  1162. playerVC.modalPresentationStyle = .overFullScreen
  1163. let checkViewController = UIApplication.shared.windows.filter {$0.isKeyWindow}.first?.rootViewController?.presentedViewController
  1164. if checkViewController != nil {
  1165. UIApplication.shared.windows.filter {$0.isKeyWindow}.first?.rootViewController?.presentedViewController?.present(playerVC, animated: true, completion: nil)
  1166. } else {
  1167. UIApplication.shared.windows.filter {$0.isKeyWindow}.first?.rootViewController?.present(playerVC, animated: true, completion: nil)
  1168. }
  1169. } else {
  1170. Download().start(forKey: video) { (name, progress) in
  1171. DispatchQueue.main.async {
  1172. guard progress == 100 else {
  1173. return
  1174. }
  1175. let player = AVPlayer(url: videoURL as URL)
  1176. let playerVC = AVPlayerViewController()
  1177. playerVC.player = player
  1178. playerVC.modalPresentationStyle = .overFullScreen
  1179. let checkViewController = UIApplication.shared.windows.filter {$0.isKeyWindow}.first?.rootViewController?.presentedViewController
  1180. if checkViewController != nil {
  1181. UIApplication.shared.windows.filter {$0.isKeyWindow}.first?.rootViewController?.presentedViewController?.present(playerVC, animated: true, completion: nil)
  1182. } else {
  1183. UIApplication.shared.windows.filter {$0.isKeyWindow}.first?.rootViewController?.present(playerVC, animated: true, completion: nil)
  1184. }
  1185. }
  1186. }
  1187. }
  1188. }
  1189. } else if fileType == BroadcastViewController.FILE_TYPE_DOCUMENT {
  1190. if let dirPath = paths.first {
  1191. let fileURL = URL(fileURLWithPath: dirPath).appendingPathComponent(file)
  1192. if FileManager.default.fileExists(atPath: fileURL.path) {
  1193. previewItem = fileURL as NSURL
  1194. let previewController = QLPreviewController()
  1195. let rightBarButton = UIBarButtonItem()
  1196. previewController.navigationItem.rightBarButtonItem = rightBarButton
  1197. previewController.dataSource = self
  1198. previewController.modalPresentationStyle = .overFullScreen
  1199. let checkViewController = UIApplication.shared.windows.filter {$0.isKeyWindow}.first?.rootViewController?.presentedViewController
  1200. if checkViewController != nil {
  1201. UIApplication.shared.windows.filter {$0.isKeyWindow}.first?.rootViewController?.presentedViewController?.show(previewController, sender: nil)
  1202. } else {
  1203. UIApplication.shared.windows.filter {$0.isKeyWindow}.first?.rootViewController?.show(previewController, sender: nil)
  1204. }
  1205. } else {
  1206. Download().start(forKey: file) { (name, progress) in
  1207. DispatchQueue.main.async {
  1208. guard progress == 100 else {
  1209. return
  1210. }
  1211. previewItem = fileURL as NSURL
  1212. let previewController = QLPreviewController()
  1213. let rightBarButton = UIBarButtonItem()
  1214. previewController.navigationItem.rightBarButtonItem = rightBarButton
  1215. previewController.dataSource = self
  1216. previewController.modalPresentationStyle = .overFullScreen
  1217. let checkViewController = UIApplication.shared.windows.filter {$0.isKeyWindow}.first?.rootViewController?.presentedViewController
  1218. if checkViewController != nil {
  1219. UIApplication.shared.windows.filter {$0.isKeyWindow}.first?.rootViewController?.presentedViewController?.show(previewController, sender: nil)
  1220. } else {
  1221. UIApplication.shared.windows.filter {$0.isKeyWindow}.first?.rootViewController?.show(previewController, sender: nil)
  1222. }
  1223. }
  1224. }
  1225. }
  1226. }
  1227. }
  1228. })
  1229. }
  1230. let checkViewController = UIApplication.shared.windows.filter {$0.isKeyWindow}.first?.rootViewController?.presentedViewController
  1231. if checkViewController != nil {
  1232. UIApplication.shared.windows.filter {$0.isKeyWindow}.first?.rootViewController?.presentedViewController?.present(alert, animated: true, completion: nil)
  1233. } else {
  1234. UIApplication.shared.windows.filter {$0.isKeyWindow}.first?.rootViewController?.present(alert, animated: true, completion: nil)
  1235. }
  1236. }
  1237. public func onReceive(message: TMessage) {
  1238. var dataMessage: [AnyHashable : Any] = [:]
  1239. dataMessage["message"] = message
  1240. NotificationCenter.default.post(name: NSNotification.Name(rawValue: "onReceiveChat"), object: nil, userInfo: dataMessage)
  1241. if message.getCode() == CoreMessage_TMessageCode.PUSH_CALL_CENTER {
  1242. DispatchQueue.main.async {
  1243. let alert = UIAlertController(title: "", message: "\n\n\n\n\n\n\n\n\n\n".localized(), preferredStyle: .alert)
  1244. let newWidth = UIScreen.main.bounds.width * 0.90 - 270
  1245. // update width constraint value for main view
  1246. if let viewWidthConstraint = alert.view.constraints.filter({ return $0.firstAttribute == .width }).first{
  1247. viewWidthConstraint.constant = newWidth
  1248. }
  1249. // update width constraint value for container view
  1250. if let containerViewWidthConstraint = alert.view.subviews.first?.constraints.filter({ return $0.firstAttribute == .width }).first {
  1251. containerViewWidthConstraint.constant = newWidth
  1252. }
  1253. let titleFont = [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 18), NSAttributedString.Key.foregroundColor: UIColor.black]
  1254. let titleAttrString = NSMutableAttributedString(string: "Call Center".localized(), attributes: titleFont)
  1255. alert.setValue(titleAttrString, forKey: "attributedTitle")
  1256. alert.view.subviews.first?.subviews.first?.subviews.first?.backgroundColor = .lightGray
  1257. alert.view.tintColor = .black
  1258. let rejectAction = UIAlertAction(title: "Pass to other representative".localized(), style: .destructive, handler: {(_) in
  1259. DispatchQueue.global().async {
  1260. _ = Nexilis.write(message: CoreMessage_TMessageBank.timeOutRequestCallCenter(channel: message.getBody(key: CoreMessage_TMessageKey.CHANNEL), l_pin: message.getBody(key: CoreMessage_TMessageKey.L_PIN)))
  1261. }
  1262. alert.dismiss(animated: true, completion: nil)
  1263. })
  1264. let acceptAction = UIAlertAction(title: "I'll handle the customer".localized(), style: .default, handler: {(_) in
  1265. 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))) {
  1266. if (response.getBody(key: CoreMessage_TMessageKey.ERRCOD, default_value: "99") == "00") {
  1267. let complaintId = response.getBody(key: CoreMessage_TMessageKey.DATA, default_value: "")
  1268. if !complaintId.isEmpty {
  1269. alert.dismiss(animated: true, completion: nil)
  1270. let editorPersonalVC = AppStoryBoard.Palio.instance.instantiateViewController(identifier: "editorPersonalVC") as! EditorPersonal
  1271. editorPersonalVC.isContactCenter = true
  1272. editorPersonalVC.isRequestContactCenter = false
  1273. editorPersonalVC.unique_l_pin = message.getBody(key: CoreMessage_TMessageKey.L_PIN)
  1274. editorPersonalVC.complaintId = complaintId
  1275. editorPersonalVC.channelContactCenter = message.getBody(key: CoreMessage_TMessageKey.CHANNEL)
  1276. editorPersonalVC.fPinContacCenter = message.getBody(key: CoreMessage_TMessageKey.L_PIN)
  1277. let navigationController = UINavigationController(rootViewController: editorPersonalVC)
  1278. navigationController.modalPresentationStyle = .fullScreen
  1279. UIApplication.shared.windows.filter {$0.isKeyWindow}.first?.rootViewController?.present(navigationController, animated: true, completion: nil)
  1280. }
  1281. }
  1282. }
  1283. })
  1284. alert.addAction(acceptAction)
  1285. alert.addAction(rejectAction)
  1286. let containerView = UIView(frame: CGRect(x: 20, y: 60, width: alert.view.bounds.size.width * 0.9 - 40, height: 150))
  1287. alert.view.addSubview(containerView)
  1288. containerView.layer.cornerRadius = 10.0
  1289. containerView.clipsToBounds = true
  1290. containerView.backgroundColor = .secondaryColor
  1291. let imageProfile = UIImageView()
  1292. containerView.addSubview(imageProfile)
  1293. imageProfile.translatesAutoresizingMaskIntoConstraints = false
  1294. NSLayoutConstraint.activate([
  1295. imageProfile.topAnchor.constraint(equalTo: containerView.topAnchor, constant: 10),
  1296. imageProfile.bottomAnchor.constraint(equalTo: containerView.bottomAnchor, constant: -10),
  1297. imageProfile.leadingAnchor.constraint(equalTo: containerView.leadingAnchor, constant: 10),
  1298. imageProfile.widthAnchor.constraint(equalToConstant: 100)
  1299. ])
  1300. imageProfile.layer.cornerRadius = 10.0
  1301. imageProfile.clipsToBounds = true
  1302. imageProfile.backgroundColor = .lightGray.withAlphaComponent(0.3)
  1303. imageProfile.tintColor = .secondaryColor
  1304. imageProfile.image = UIImage(systemName: "person")
  1305. if message.getBody(key: CoreMessage_TMessageKey.THUMB_ID) != "" {
  1306. imageProfile.setImage(name: message.getBody(key: CoreMessage_TMessageKey.THUMB_ID))
  1307. imageProfile.contentMode = .scaleAspectFill
  1308. }
  1309. let labelName = UILabel()
  1310. containerView.addSubview(labelName)
  1311. labelName.translatesAutoresizingMaskIntoConstraints = false
  1312. NSLayoutConstraint.activate([
  1313. labelName.topAnchor.constraint(equalTo: containerView.topAnchor, constant: 15),
  1314. labelName.leadingAnchor.constraint(equalTo: imageProfile.trailingAnchor, constant: 5)
  1315. ])
  1316. labelName.font = UIFont.systemFont(ofSize: 12)
  1317. labelName.text = "Name".localized()
  1318. labelName.textColor = .mainColor
  1319. let valueName = UILabel()
  1320. containerView.addSubview(valueName)
  1321. valueName.translatesAutoresizingMaskIntoConstraints = false
  1322. NSLayoutConstraint.activate([
  1323. valueName.topAnchor.constraint(equalTo: labelName.bottomAnchor),
  1324. valueName.leadingAnchor.constraint(equalTo: imageProfile.trailingAnchor, constant: 5)
  1325. ])
  1326. valueName.font = UIFont.systemFont(ofSize: 12)
  1327. valueName.text = message.getBody(key: CoreMessage_TMessageKey.F_DISPLAY_NAME)
  1328. valueName.textColor = .mainColor
  1329. let labelType = UILabel()
  1330. containerView.addSubview(labelType)
  1331. labelType.translatesAutoresizingMaskIntoConstraints = false
  1332. NSLayoutConstraint.activate([
  1333. labelType.topAnchor.constraint(equalTo: valueName.bottomAnchor, constant: 5),
  1334. labelType.leadingAnchor.constraint(equalTo: imageProfile.trailingAnchor, constant: 5)
  1335. ])
  1336. labelType.font = UIFont.systemFont(ofSize: 12)
  1337. labelType.text = "Request Type".localized()
  1338. labelType.textColor = .mainColor
  1339. let valueType = UILabel()
  1340. containerView.addSubview(valueType)
  1341. valueType.translatesAutoresizingMaskIntoConstraints = false
  1342. NSLayoutConstraint.activate([
  1343. valueType.topAnchor.constraint(equalTo: labelType.bottomAnchor),
  1344. valueType.leadingAnchor.constraint(equalTo: imageProfile.trailingAnchor, constant: 5)
  1345. ])
  1346. valueType.font = UIFont.systemFont(ofSize: 12)
  1347. if message.getBody(key: CoreMessage_TMessageKey.CHANNEL) == "0" {
  1348. valueType.text = "Chat".localized()
  1349. } else if message.getBody(key: CoreMessage_TMessageKey.CHANNEL) == "1" {
  1350. valueType.text = "Audio Call".localized()
  1351. } else if message.getBody(key: CoreMessage_TMessageKey.CHANNEL) == "2" {
  1352. valueType.text = "Video Call".localized()
  1353. } else {
  1354. valueType.text = "Email".localized()
  1355. }
  1356. valueType.textColor = .mainColor
  1357. let labelIdentity = UILabel()
  1358. containerView.addSubview(labelIdentity)
  1359. labelIdentity.translatesAutoresizingMaskIntoConstraints = false
  1360. NSLayoutConstraint.activate([
  1361. labelIdentity.topAnchor.constraint(equalTo: valueType.bottomAnchor, constant: 5),
  1362. labelIdentity.leadingAnchor.constraint(equalTo: imageProfile.trailingAnchor, constant: 5)
  1363. ])
  1364. labelIdentity.font = UIFont.systemFont(ofSize: 12)
  1365. labelIdentity.text = "Identity Number".localized()
  1366. labelIdentity.textColor = .mainColor
  1367. let valueIdentity = UILabel()
  1368. containerView.addSubview(valueIdentity)
  1369. valueIdentity.translatesAutoresizingMaskIntoConstraints = false
  1370. NSLayoutConstraint.activate([
  1371. valueIdentity.topAnchor.constraint(equalTo: labelIdentity.bottomAnchor),
  1372. valueIdentity.leadingAnchor.constraint(equalTo: imageProfile.trailingAnchor, constant: 5)
  1373. ])
  1374. valueIdentity.font = UIFont.systemFont(ofSize: 12)
  1375. valueIdentity.text = "-"
  1376. valueIdentity.textColor = .mainColor
  1377. let checkViewController = UIApplication.shared.windows.filter {$0.isKeyWindow}.first?.rootViewController?.presentedViewController
  1378. if checkViewController != nil {
  1379. UIApplication.shared.windows.filter {$0.isKeyWindow}.first?.rootViewController?.presentedViewController?.present(alert, animated: true, completion: nil)
  1380. } else {
  1381. UIApplication.shared.windows.filter {$0.isKeyWindow}.first?.rootViewController?.present(alert, animated: true, completion: nil)
  1382. }
  1383. }
  1384. } 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.mBodies["MERNAM"] != nil {
  1385. let m = message.mBodies
  1386. if m[CoreMessage_TMessageKey.IS_CALL_CENTER] == "1" {
  1387. return
  1388. }
  1389. if message.mBodies["MERNAM"] != nil {
  1390. DispatchQueue.main.async {
  1391. self.showBroadcastMessage(m: m)
  1392. }
  1393. return
  1394. }
  1395. let sender = m[CoreMessage_TMessageKey.F_PIN]!
  1396. let me = UserDefaults.standard.string(forKey: "me")!
  1397. if(sender != me) {
  1398. let inEditorPersonal = UserDefaults.standard.string(forKey: "inEditorPersonal")
  1399. let inEditorGroup = UserDefaults.standard.stringArray(forKey: "inEditorGroup")
  1400. var text = m["A07"]!
  1401. if (m.keys.contains("A57") && !((m["A57"]!).isEmpty)) {
  1402. text = "Sent Image 📷"
  1403. } else if (m.keys.contains("A149")) && (m["A149"]!) == "11" {
  1404. text = "Sent Sticker ❤️"
  1405. } else if (m.keys.contains("A47") && !((m["A47"]!).isEmpty)) {
  1406. text = "Sent Video 📹"
  1407. } else if (m.keys.contains("BN") && !((m["BN"]!).isEmpty)) {
  1408. text = "Sent File 📄"
  1409. } else if (m.keys.contains("A63") && !((m["A63"]!).isEmpty)) {
  1410. text = "Sent Audio 🎵"
  1411. } else if ((m["A07"]!).contains("Share%20location%20")) {
  1412. text = "Sent Location 📌"
  1413. } else if (m.keys.contains("A149")) && (m["A149"]!) == "27" {
  1414. text = "Sent link Live Video Promotion"
  1415. } else if (m.keys.contains("A149")) && (m["A149"]!) == "25" {
  1416. text = "Sent link Video Conference Room"
  1417. } else if (m.keys.contains("A149")) && (m["A149"]!) == "24" {
  1418. text = "Sent link Quiz"
  1419. }
  1420. var nameUser: String?
  1421. var profile = ""
  1422. var threadIdentifier = sender
  1423. if(m["A06"]! == "3" || m["A06"]! == "18") {
  1424. if (inEditorPersonal != nil && inEditorPersonal == sender) {
  1425. return
  1426. }
  1427. if(nameUser == nil) {
  1428. Database.shared.database?.inTransaction({ (fmdb, rollback) in
  1429. if let cursor = Database.shared.getRecords(fmdb: fmdb, query: "SELECT first_name, last_name, image_id FROM BUDDY WHERE f_pin='\(String(describing: sender))'") {
  1430. while cursor.next() {
  1431. let first_name = cursor.string(forColumnIndex: 0)!
  1432. let last_name = cursor.string(forColumnIndex: 1)!
  1433. nameUser = "\(first_name) \(last_name)".trimmingCharacters(in: .whitespaces)
  1434. profile = cursor.string(forColumnIndex: 2)!
  1435. }
  1436. cursor.close()
  1437. }
  1438. })
  1439. }
  1440. } else {
  1441. let idGroup = m["A01"]!
  1442. var topicGroup: String?
  1443. var idTopic: String?
  1444. if (m.keys.contains("BA")) {
  1445. idTopic = m["BA"]
  1446. }
  1447. if (idTopic == nil) {
  1448. idTopic = "Lounge"
  1449. topicGroup = "Lounge"
  1450. } else {
  1451. Database.shared.database?.inTransaction({ (fmdb, rollback) in
  1452. if let cursor = Database.shared.getRecords(fmdb: fmdb, query: "SELECT title FROM DISCUSSION_FORUM WHERE chat_id='\(idTopic!)'") {
  1453. while cursor.next() {
  1454. let title = cursor.string(forColumnIndex: 0)
  1455. topicGroup = title
  1456. }
  1457. cursor.close()
  1458. }
  1459. })
  1460. }
  1461. if (inEditorGroup != nil) {
  1462. let editorIdGroup = inEditorGroup![0]
  1463. let editorIdTopic = inEditorGroup![1]
  1464. var idTempTopic = idTopic
  1465. if (idTempTopic == "Lounge") {
  1466. idTempTopic = ""
  1467. }
  1468. if (editorIdGroup == idGroup && editorIdTopic == idTempTopic) {
  1469. return
  1470. }
  1471. }
  1472. Database.shared.database?.inTransaction({ (fmdb, rollback) in
  1473. if let cursor = Database.shared.getRecords(fmdb: fmdb, query: "SELECT f_name, image_id FROM GROUPZ WHERE group_id='\(idGroup)'") {
  1474. while cursor.next() {
  1475. let f_name = cursor.string(forColumnIndex: 0)
  1476. var senderName = m["BR"]
  1477. if senderName == nil {
  1478. senderName = "Bot"
  1479. }
  1480. nameUser =
  1481. "\(senderName!) \u{2022} \(f_name!)(\(topicGroup!))"
  1482. profile = cursor.string(forColumnIndex: 1)!
  1483. }
  1484. cursor.close()
  1485. }
  1486. })
  1487. if idTopic == "Lounge" {
  1488. threadIdentifier = idGroup
  1489. } else {
  1490. threadIdentifier = idTopic!
  1491. }
  1492. }
  1493. if nameUser == nil && threadIdentifier == "-999" {
  1494. nameUser = "Bot"
  1495. }
  1496. DispatchQueue.main.async {
  1497. let container = UIView()
  1498. container.backgroundColor = .gray
  1499. let profileImage = UIImageView()
  1500. profileImage.frame.size = CGSize(width: 60, height: 60)
  1501. container.addSubview(profileImage)
  1502. profileImage.translatesAutoresizingMaskIntoConstraints = false
  1503. NSLayoutConstraint.activate([
  1504. profileImage.leadingAnchor.constraint(equalTo: container.leadingAnchor, constant: 8.0),
  1505. profileImage.centerYAnchor.constraint(equalTo: container.centerYAnchor),
  1506. profileImage.widthAnchor.constraint(equalToConstant: 60),
  1507. profileImage.heightAnchor.constraint(equalToConstant: 60),
  1508. ])
  1509. let title = UILabel()
  1510. container.addSubview(title)
  1511. title.translatesAutoresizingMaskIntoConstraints = false
  1512. NSLayoutConstraint.activate([
  1513. title.leadingAnchor.constraint(equalTo: profileImage.trailingAnchor, constant: 8.0),
  1514. title.topAnchor.constraint(equalTo: container.topAnchor, constant: 20.0),
  1515. ])
  1516. title.font = UIFont.systemFont(ofSize: 14)
  1517. title.text = nameUser ?? "Unknown"
  1518. title.textColor = .white
  1519. let subtitle = UILabel()
  1520. container.addSubview(subtitle)
  1521. subtitle.translatesAutoresizingMaskIntoConstraints = false
  1522. NSLayoutConstraint.activate([
  1523. subtitle.leadingAnchor.constraint(equalTo: profileImage.trailingAnchor, constant: 8.0),
  1524. subtitle.topAnchor.constraint(equalTo: title.bottomAnchor),
  1525. ])
  1526. subtitle.font = UIFont.systemFont(ofSize: 12)
  1527. subtitle.attributedText = text.richText()
  1528. subtitle.textColor = .white
  1529. let floating = FloatingNotificationBanner(customView: container)
  1530. floating.bannerHeight = 100.0
  1531. floating.transparency = 0.9
  1532. if threadIdentifier == "-999" {
  1533. profileImage.image = UIImage(named: "Q-Button-PNG", in: Bundle.resourceBundle(for: Nexilis.self), with: nil)
  1534. } else if profile != "" {
  1535. profileImage.circle()
  1536. do {
  1537. let documentDir = try FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
  1538. let file = documentDir.appendingPathComponent(profile)
  1539. if FileManager().fileExists(atPath: file.path) {
  1540. profileImage.image = UIImage(contentsOfFile: file.path)
  1541. profileImage.backgroundColor = .clear
  1542. } else {
  1543. Download().start(forKey: profile) { (name, progress) in
  1544. guard progress == 100 else {
  1545. return
  1546. }
  1547. DispatchQueue.main.async {
  1548. profileImage.image = UIImage(contentsOfFile: file.path)
  1549. profileImage.backgroundColor = .clear
  1550. 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)
  1551. floating.onTap = {
  1552. Database.shared.database?.inTransaction({ (fmdb, rollback) in
  1553. 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() {
  1554. if (cursorData.string(forColumnIndex: 0)! + " " + cursorData.string(forColumnIndex: 1)!).trimmingCharacters(in: .whitespaces) == "USR\(UserDefaults.standard.string(forKey: "me")!)" {
  1555. let alert = UIAlertController(title: "Change Profile".localized(), message: "You must change your name to use this feature".localized(), preferredStyle: .alert)
  1556. alert.addAction(UIAlertAction(title: "Ok".localized(), style: UIAlertAction.Style.default, handler: {(_) in
  1557. let controller = AppStoryBoard.Palio.instance.instantiateViewController(withIdentifier: "changeNS") as! ChangeNamePassswordViewController
  1558. let navigationController = UINavigationController(rootViewController: controller)
  1559. navigationController.modalPresentationStyle = .fullScreen
  1560. navigationController.navigationBar.tintColor = .white
  1561. navigationController.navigationBar.barTintColor = .mainColor
  1562. navigationController.navigationBar.isTranslucent = false
  1563. let textAttributes = [NSAttributedString.Key.foregroundColor:UIColor.white]
  1564. navigationController.navigationBar.titleTextAttributes = textAttributes
  1565. navigationController.view.backgroundColor = .mainColor
  1566. let checkViewController = UIApplication.shared.windows.filter {$0.isKeyWindow}.first?.rootViewController?.presentedViewController
  1567. if checkViewController != nil {
  1568. UIApplication.shared.windows.filter {$0.isKeyWindow}.first?.rootViewController?.dismiss(animated: true, completion: nil)
  1569. UIApplication.shared.windows.filter {$0.isKeyWindow}.first?.rootViewController?.presentedViewController?.show(navigationController, sender: nil)
  1570. } else {
  1571. UIApplication.shared.windows.filter {$0.isKeyWindow}.first?.rootViewController?.dismiss(animated: true, completion: nil)
  1572. UIApplication.shared.windows.filter {$0.isKeyWindow}.first?.rootViewController?.present(navigationController, animated: true, completion: nil)
  1573. }
  1574. }))
  1575. UIApplication.shared.windows.filter {$0.isKeyWindow}.first?.rootViewController?.present(alert, animated: true, completion: nil)
  1576. }
  1577. cursorData.close()
  1578. return
  1579. }
  1580. })
  1581. if(m["A06"]! == "3") {
  1582. let editorPersonalVC = AppStoryBoard.Palio.instance.instantiateViewController(identifier: "editorPersonalVC") as! EditorPersonal
  1583. editorPersonalVC.hidesBottomBarWhenPushed = true
  1584. editorPersonalVC.unique_l_pin = threadIdentifier
  1585. editorPersonalVC.fromNotification = true
  1586. let navigationController = UINavigationController(rootViewController: editorPersonalVC)
  1587. navigationController.modalPresentationStyle = .fullScreen
  1588. let checkViewController = UIApplication.shared.windows.filter {$0.isKeyWindow}.first?.rootViewController?.presentedViewController
  1589. if checkViewController == nil {
  1590. UIApplication.shared.windows.filter {$0.isKeyWindow}.last?.rootViewController?.present(navigationController, animated: true, completion: nil)
  1591. } else {
  1592. UIApplication.shared.windows.filter {$0.isKeyWindow}.last?.rootViewController?.presentedViewController?.show(navigationController, sender: nil)
  1593. }
  1594. } else {
  1595. let editorGroupVC = AppStoryBoard.Palio.instance.instantiateViewController(withIdentifier: "editorGroupVC") as! EditorGroup
  1596. editorGroupVC.hidesBottomBarWhenPushed = true
  1597. editorGroupVC.unique_l_pin = threadIdentifier
  1598. editorGroupVC.fromNotification = true
  1599. let navigationController = UINavigationController(rootViewController: editorGroupVC)
  1600. navigationController.modalPresentationStyle = .fullScreen
  1601. let checkViewController = UIApplication.shared.windows.filter {$0.isKeyWindow}.first?.rootViewController?.presentedViewController
  1602. if checkViewController == nil {
  1603. UIApplication.shared.windows.filter {$0.isKeyWindow}.last?.rootViewController?.present(navigationController, animated: true, completion: nil)
  1604. } else {
  1605. UIApplication.shared.windows.filter {$0.isKeyWindow}.last?.rootViewController?.presentedViewController?.show(navigationController, sender: nil)
  1606. }
  1607. }
  1608. }
  1609. }
  1610. }
  1611. return
  1612. }
  1613. } catch {}
  1614. profileImage.contentMode = .scaleAspectFill
  1615. } else {
  1616. profileImage.circle()
  1617. if m["A06"]! == "3" {
  1618. profileImage.image = UIImage(systemName: "person")
  1619. } else {
  1620. profileImage.image = UIImage(systemName: "person.3")
  1621. }
  1622. profileImage.contentMode = .scaleAspectFit
  1623. profileImage.backgroundColor = .lightGray
  1624. profileImage.tintColor = .white
  1625. }
  1626. 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)
  1627. floating.onTap = {
  1628. Database.shared.database?.inTransaction({ (fmdb, rollback) in
  1629. 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() {
  1630. if (cursorData.string(forColumnIndex: 0)! + " " + cursorData.string(forColumnIndex: 1)!).trimmingCharacters(in: .whitespaces) == "USR\(UserDefaults.standard.string(forKey: "me")!)" {
  1631. let alert = UIAlertController(title: "Change Profile".localized(), message: "You must change your name to use this feature".localized(), preferredStyle: .alert)
  1632. alert.addAction(UIAlertAction(title: "Ok".localized(), style: UIAlertAction.Style.default, handler: {(_) in
  1633. let controller = AppStoryBoard.Palio.instance.instantiateViewController(withIdentifier: "changeNS") as! ChangeNamePassswordViewController
  1634. let navigationController = UINavigationController(rootViewController: controller)
  1635. navigationController.modalPresentationStyle = .fullScreen
  1636. navigationController.navigationBar.tintColor = .white
  1637. navigationController.navigationBar.barTintColor = .mainColor
  1638. navigationController.navigationBar.isTranslucent = false
  1639. let textAttributes = [NSAttributedString.Key.foregroundColor:UIColor.white]
  1640. navigationController.navigationBar.titleTextAttributes = textAttributes
  1641. navigationController.view.backgroundColor = .mainColor
  1642. let checkViewController = UIApplication.shared.windows.filter {$0.isKeyWindow}.first?.rootViewController?.presentedViewController
  1643. if checkViewController != nil {
  1644. UIApplication.shared.windows.filter {$0.isKeyWindow}.first?.rootViewController?.dismiss(animated: true, completion: nil)
  1645. UIApplication.shared.windows.filter {$0.isKeyWindow}.first?.rootViewController?.presentedViewController?.show(navigationController, sender: nil)
  1646. } else {
  1647. UIApplication.shared.windows.filter {$0.isKeyWindow}.first?.rootViewController?.dismiss(animated: true, completion: nil)
  1648. UIApplication.shared.windows.filter {$0.isKeyWindow}.first?.rootViewController?.present(navigationController, animated: true, completion: nil)
  1649. }
  1650. }))
  1651. UIApplication.shared.windows.filter {$0.isKeyWindow}.first?.rootViewController?.present(alert, animated: true, completion: nil)
  1652. }
  1653. cursorData.close()
  1654. return
  1655. }
  1656. })
  1657. if(m["A06"]! == "3") {
  1658. let editorPersonalVC = AppStoryBoard.Palio.instance.instantiateViewController(identifier: "editorPersonalVC") as! EditorPersonal
  1659. editorPersonalVC.hidesBottomBarWhenPushed = true
  1660. editorPersonalVC.unique_l_pin = threadIdentifier
  1661. editorPersonalVC.fromNotification = true
  1662. let navigationController = UINavigationController(rootViewController: editorPersonalVC)
  1663. navigationController.modalPresentationStyle = .fullScreen
  1664. let checkViewController = UIApplication.shared.windows.filter {$0.isKeyWindow}.first?.rootViewController?.presentedViewController
  1665. if checkViewController == nil {
  1666. UIApplication.shared.windows.filter {$0.isKeyWindow}.last?.rootViewController?.present(navigationController, animated: true, completion: nil)
  1667. } else {
  1668. UIApplication.shared.windows.filter {$0.isKeyWindow}.last?.rootViewController?.presentedViewController?.show(navigationController, sender: nil)
  1669. }
  1670. } else {
  1671. let editorGroupVC = AppStoryBoard.Palio.instance.instantiateViewController(withIdentifier: "editorGroupVC") as! EditorGroup
  1672. editorGroupVC.hidesBottomBarWhenPushed = true
  1673. editorGroupVC.unique_l_pin = threadIdentifier
  1674. editorGroupVC.fromNotification = true
  1675. let navigationController = UINavigationController(rootViewController: editorGroupVC)
  1676. navigationController.modalPresentationStyle = .fullScreen
  1677. let checkViewController = UIApplication.shared.windows.filter {$0.isKeyWindow}.first?.rootViewController?.presentedViewController
  1678. if checkViewController == nil {
  1679. UIApplication.shared.windows.filter {$0.isKeyWindow}.last?.rootViewController?.present(navigationController, animated: true, completion: nil)
  1680. } else {
  1681. UIApplication.shared.windows.filter {$0.isKeyWindow}.last?.rootViewController?.presentedViewController?.show(navigationController, sender: nil)
  1682. }
  1683. }
  1684. }
  1685. }
  1686. }
  1687. }
  1688. }
  1689. public func onReceive(message: [AnyHashable : Any?]) {
  1690. var dataMessage: [AnyHashable : Any] = [:]
  1691. dataMessage["message"] = message
  1692. NotificationCenter.default.post(name: NSNotification.Name(rawValue: "onReceiveChat"), object: nil, userInfo: dataMessage)
  1693. }
  1694. public func onMessage(message: TMessage) {
  1695. var dataMessage: [AnyHashable : Any] = [:]
  1696. dataMessage["message"] = message
  1697. NotificationCenter.default.post(name: NSNotification.Name(rawValue: "onMessageChat"), object: nil, userInfo: dataMessage)
  1698. }
  1699. public func onUpload(name: String, progress: Double) {
  1700. var dataMessage: [AnyHashable : Any] = [:]
  1701. dataMessage["name"] = name
  1702. dataMessage["progress"] = progress
  1703. NotificationCenter.default.post(name: NSNotification.Name(rawValue: "onUploadChat"), object: nil, userInfo: dataMessage)
  1704. }
  1705. public func onTyping(message: TMessage) {
  1706. var dataMessage: [AnyHashable : Any] = [:]
  1707. dataMessage["message"] = message
  1708. NotificationCenter.default.post(name: NSNotification.Name(rawValue: "onTypingChat"), object: nil, userInfo: dataMessage)
  1709. }
  1710. }
  1711. extension Nexilis: GroupDelegate {
  1712. public func onGroup(code: String, f_pin: String, groupId: String) {
  1713. var data: [AnyHashable : Any] = [:]
  1714. data["code"] = code
  1715. data["f_pin"] = f_pin
  1716. data["groupId"] = groupId
  1717. NotificationCenter.default.post(name: NSNotification.Name(rawValue: "onGroup"), object: nil, userInfo: data)
  1718. }
  1719. public func onTopic(code: String, f_pin: String, topicId: String) {
  1720. var data: [AnyHashable : Any] = [:]
  1721. data["code"] = code
  1722. data["f_pin"] = f_pin
  1723. data["topicId"] = topicId
  1724. NotificationCenter.default.post(name: NSNotification.Name(rawValue: "onTopic"), object: nil, userInfo: data)
  1725. }
  1726. public func onMember(code: String, f_pin: String, groupId: String, member: String) {
  1727. var data: [AnyHashable : Any] = [:]
  1728. data["code"] = code
  1729. data["f_pin"] = f_pin
  1730. data["groupId"] = groupId
  1731. data["member"] = member
  1732. NotificationCenter.default.post(name: NSNotification.Name(rawValue: "onMember"), object: nil, userInfo: data)
  1733. }
  1734. }
  1735. extension Nexilis: PersonInfoDelegate {
  1736. public func onUpdatePersonInfo(state: Int, message: String) {
  1737. var data: [AnyHashable : Any] = [:]
  1738. data["state"] = state
  1739. data["message"] = message
  1740. NotificationCenter.default.post(name: NSNotification.Name(rawValue: "onUpdatePersonInfo"), object: nil, userInfo: data)
  1741. }
  1742. }
  1743. extension Nexilis: QLPreviewControllerDataSource {
  1744. public func numberOfPreviewItems(in controller: QLPreviewController) -> Int {
  1745. return 1
  1746. }
  1747. public func previewController(_ controller: QLPreviewController, previewItemAt index: Int) -> QLPreviewItem {
  1748. return previewItem!
  1749. }
  1750. }