Nexilis.swift 153 KB

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