Nexilis.swift 192 KB

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