Nexilis.swift 100 KB

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