EditorPersonal.swift 271 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557
  1. //
  2. // EditorPersonal.swift
  3. // Qmera
  4. //
  5. // Created by Akhmad Al Qindi Irsyam on 31/08/21.
  6. //
  7. import UIKit
  8. import AVKit
  9. import AVFoundation
  10. import QuickLook
  11. import ReadabilityKit
  12. import NotificationBannerSwift
  13. import Photos
  14. import nuSDKService
  15. public class EditorPersonal: UIViewController, ImageVideoPickerDelegate {
  16. @IBOutlet var viewButton: UIView!
  17. @IBOutlet var constraintViewTextField: NSLayoutConstraint!
  18. @IBOutlet var buttonVoice: UIButton!
  19. @IBOutlet var buttonSendImage: UIButton!
  20. @IBOutlet var buttonSendPhoto: UIButton!
  21. @IBOutlet var buttonSendSticker: UIButton!
  22. @IBOutlet var buttonSendFile: UIButton!
  23. @IBOutlet var textFieldSend: UITextView!
  24. @IBOutlet var heightTextFieldSend: NSLayoutConstraint!
  25. @IBOutlet var buttonSendChat: UIButton!
  26. @IBOutlet var tableChatView: UITableView!
  27. @IBOutlet var constraintTopTextField: NSLayoutConstraint!
  28. @IBOutlet var constraintBottomAttachment: NSLayoutConstraint!
  29. @IBOutlet var viewTextfield: UIView!
  30. public var dataPerson: [String: String?] = [:]
  31. var dataMessages: [[String: Any?]] = []
  32. var dataDates: [String] = []
  33. var users: [User] = []
  34. public var dataMessageForward: [[String: Any?]]?
  35. var imageVideoPicker: ImageVideoPicker!
  36. var documentPicker: DocumentPicker!
  37. var currentIndexpath: IndexPath?
  38. var previewItem: NSURL?
  39. var reffId: String?
  40. var stickers = [String]()
  41. public var unique_l_pin = ""
  42. public var isContactCenter = false
  43. var isRequestContactCenter = true
  44. public var fromNotification = false
  45. var onGoingCC = false
  46. var fPinContacCenter = ""
  47. var complaintId = ""
  48. var channelContactCenter = ""
  49. var counter = 0
  50. var dateStartCC = ""
  51. var markerCounter: String?
  52. var buttonScrollToBottom = UIButton()
  53. let indicatorCounterBSTB = UIView()
  54. let labelCounter = UILabel()
  55. var copySession = false
  56. var forwardSession = false
  57. var deleteSession = false
  58. let containerMultpileSelectSession = UIView()
  59. let containerAction = UIView()
  60. var removed = false
  61. let viewSticker = UIView()
  62. let containerLink = UIView()
  63. let containerPreviewReply = UIView()
  64. var bottomAnchorPreviewReply = NSLayoutConstraint()
  65. var blocking = ""
  66. var timeoutCC = Timer()
  67. var nowSelectedCategoryCC = ""
  68. var showToastTwiceClick = false
  69. var showToast30s = false
  70. var allowTyping = true
  71. public override func viewDidDisappear(_ animated: Bool) {
  72. if self.isMovingFromParent {
  73. print("MASUK Disappear EDITOR PERSONAL")
  74. self.timeoutCC.invalidate()
  75. UserDefaults.standard.removeObject(forKey: "inEditorPersonal")
  76. NotificationCenter.default.removeObserver(self)
  77. }
  78. }
  79. public override func viewDidAppear(_ animated: Bool) {
  80. navigationController?.navigationBar.isTranslucent = false
  81. navigationController?.navigationBar.barTintColor = UIColor.mainColor
  82. navigationController?.navigationBar.tintColor = .white
  83. if self.navigationController?.isNavigationBarHidden ?? false {
  84. self.navigationController?.setNavigationBarHidden(false, animated: false)
  85. }
  86. }
  87. public override func viewDidLoad() {
  88. super.viewDidLoad()
  89. updateProfile()
  90. // navigationController?.navigationBar.topItem?.title = ""
  91. viewButton.layer.shadowColor = UIColor.gray.cgColor
  92. viewButton.layer.shadowOpacity = 1
  93. viewButton.layer.shadowOffset = .zero
  94. viewButton.layer.shadowRadius = 3
  95. buttonVoice.setImage(resizeImage(image: UIImage(named: "Voice-Record", in: Bundle.resourceBundle(for: Nexilis.self), with: nil)!, targetSize: CGSize(width: 30, height: 30)), for: .normal)
  96. buttonSendImage.setImage(resizeImage(image: UIImage(named: "Send-Image", in: Bundle.resourceBundle(for: Nexilis.self), with: nil)!, targetSize: CGSize(width: 30, height: 30)), for: .normal)
  97. buttonSendPhoto.setImage(resizeImage(image: UIImage(named: "Camera", in: Bundle.resourceBundle(for: Nexilis.self), with: nil)!, targetSize: CGSize(width: 30, height: 30)), for: .normal)
  98. buttonSendSticker.setImage(resizeImage(image: UIImage(named: "Sticker---Emoji", in: Bundle.resourceBundle(for: Nexilis.self), with: nil)!, targetSize: CGSize(width: 30, height: 30)), for: .normal)
  99. buttonSendFile.setImage(resizeImage(image: UIImage(named: "File---Documents", in: Bundle.resourceBundle(for: Nexilis.self), with: nil)!, targetSize: CGSize(width: 30, height: 30)), for: .normal)
  100. buttonSendChat.setImage(resizeImage(image: UIImage(named: "Send-(White)", in: Bundle.resourceBundle(for: Nexilis.self), with: nil)!, targetSize: CGSize(width: 30, height: 30)).withRenderingMode(.alwaysOriginal), for: .normal)
  101. buttonSendChat.circle()
  102. buttonSendChat.addTarget(self, action: #selector(sendTapped), for: .touchUpInside)
  103. textFieldSend.layer.cornerRadius = textFieldSend.maxCornerRadius()
  104. textFieldSend.layer.borderWidth = 1.0
  105. textFieldSend.text = "Send message".localized()
  106. textFieldSend.textColor = UIColor.lightGray
  107. textFieldSend.textContainerInset = UIEdgeInsets(top: 12, left: 20, bottom: 11, right: 40)
  108. textFieldSend.layer.borderColor = UIColor.lightGray.withAlphaComponent(0.5).cgColor
  109. textFieldSend.font = UIFont.systemFont(ofSize: 12)
  110. textFieldSend.delegate = self
  111. textFieldSend.allowsEditingTextAttributes = true
  112. navigationItem.rightBarButtonItem?.tintColor = UIColor.secondaryColor
  113. imageVideoPicker = ImageVideoPicker(presentationController: self, delegate: self)
  114. documentPicker = DocumentPicker(presentationController: self, delegate: self)
  115. let fm = FileManager.default
  116. let path = Bundle.resourceBundle(for: Nexilis.self).resourcePath!
  117. let items = try! fm.contentsOfDirectory(atPath: path)
  118. for item in items {
  119. if item.hasPrefix("sticker") {
  120. stickers.append(item)
  121. }
  122. }
  123. loadData()
  124. setRightButtonItem()
  125. let center: NotificationCenter = NotificationCenter.default
  126. center.addObserver(self, selector: #selector(keyboardWillShow(notification:)), name: UIResponder.keyboardWillShowNotification, object: nil)
  127. center.addObserver(self, selector: #selector(keyboardWillHide(notification:)), name: UIResponder.keyboardWillHideNotification, object: nil)
  128. center.addObserver(self, selector: #selector(onReceiveMessage(notification:)), name: NSNotification.Name(rawValue: "onReceiveChat"), object: nil)
  129. center.addObserver(self, selector: #selector(onStatusChat(notification:)), name: NSNotification.Name(rawValue: "onMessageChat"), object: nil)
  130. center.addObserver(self, selector: #selector(onUploadChat(notification:)), name: NSNotification.Name(rawValue: "onUploadChat"), object: nil)
  131. center.addObserver(self, selector: #selector(onUnfriend(notification:)), name: NSNotification.Name(rawValue: "onUpdatePersonInfo"), object: nil)
  132. center.addObserver(self, selector: #selector(onTyping(notification:)), name: NSNotification.Name(rawValue: "onTypingChat"), object: nil)
  133. if dataMessageForward != nil {
  134. for i in 0..<dataMessageForward!.count {
  135. sendChat(message_scope_id: "3", status: "2", message_text: dataMessageForward![i]["message_text"] as! String, credential: "0", attachment_flag: dataMessageForward![i]["attachment_flag"] as! String, ex_blog_id: "", message_large_text: "", ex_format: "", image_id: dataMessageForward![i]["image_id"] as! String, audio_id: dataMessageForward![i]["audio_id"] as! String, video_id: dataMessageForward![i]["video_id"] as! String, file_id: dataMessageForward![i]["file_id"] as! String, thumb_id: dataMessageForward![i]["thumb_id"] as! String, reff_id: "", read_receipts: "", chat_id: "", is_call_center: "0", call_center_id: "", viewController: self)
  136. }
  137. dataMessageForward = nil
  138. }
  139. if isContactCenter && !isRequestContactCenter && !onGoingCC {
  140. var companyName = ""
  141. Database.shared.database?.inTransaction({ fmdb, rollback in
  142. if let cursor = Database.shared.getRecords(fmdb: fmdb, query: "SELECT first_name, last_name FROM BUDDY where official_account = '1'"), cursor.next() {
  143. companyName = cursor.string(forColumnIndex: 0)! + " " + cursor.string(forColumnIndex: 1)!
  144. companyName = companyName.trimmingCharacters(in: .whitespaces)
  145. cursor.close()
  146. }
  147. })
  148. self.dateStartCC = "\(Date().currentTimeMillis())"
  149. let myName = User.getData(pin: UserDefaults.standard.string(forKey: "me") as String?)
  150. sendChat(message_text: "Hi \(dataPerson["name"]!!), thank you for contacting \(companyName). My name is \(myName!.fullName.trimmingCharacters(in: .whitespaces)), how can I help you?".localized(), ex_format: "1", is_call_center: "1", call_center_id: complaintId, viewController: self, isAutoSendCC: true)
  151. if channelContactCenter == "1" {
  152. if let pin = dataPerson["f_pin"] {
  153. let controller = QmeraAudioViewController()
  154. controller.user = User.getData(pin: pin)
  155. controller.isOutgoing = true
  156. controller.modalPresentationStyle = .overCurrentContext
  157. present(controller, animated: true, completion: nil)
  158. }
  159. } else if channelContactCenter == "2" {
  160. let videoVC = AppStoryBoard.Palio.instance.instantiateViewController(withIdentifier: "videoVCQmera") as! QmeraVideoViewController
  161. videoVC.dataPerson.append(dataPerson)
  162. self.show(videoVC, sender: nil)
  163. }
  164. }
  165. // else if isContactCenter {
  166. // let buttonId = UIButton()
  167. // if channelContactCenter == "0" {
  168. // buttonId.tag = 0
  169. // ccAction(sender: buttonId)
  170. // } else if channelContactCenter == "1" {
  171. // buttonId.tag = 1
  172. // ccAction(sender: buttonId)
  173. // } else if channelContactCenter == "2" {
  174. // buttonId.tag = 2
  175. // ccAction(sender: buttonId)
  176. // }
  177. // }
  178. }
  179. private func setRightButtonItem() {
  180. navigationItem.rightBarButtonItems = nil
  181. var menu = UIMenu(title: "", children: [
  182. UIAction(title: "Delete Conversation".localized(), handler: {(_) in
  183. if !self.isContactCenter {
  184. let alert = UIAlertController(title: "", message: "Are you sure to delete all message in this conversation?".localized(), preferredStyle: .alert)
  185. alert.addAction(UIAlertAction(title: "Cancel".localized(), style: UIAlertAction.Style.default, handler: nil))
  186. alert.addAction(UIAlertAction(title: "Delete".localized(), style: .destructive, handler: {(_) in
  187. DispatchQueue.global().async {
  188. Database.shared.database?.inTransaction({ (fmdb, rollback) in
  189. _ = Database.shared.deleteRecord(fmdb: fmdb, table: "MESSAGE_SUMMARY", _where: "l_pin='\(self.dataPerson["f_pin"]!!)'")
  190. _ = Database.shared.deleteRecord(fmdb: fmdb, table: "MESSAGE", _where: "(f_pin='\(self.dataPerson["f_pin"]!!)' or l_pin='\(self.dataPerson["f_pin"]!!)') and (message_scope_id='3' or message_scope_id='18') and is_call_center = 0")
  191. })
  192. NotificationCenter.default.post(name: NSNotification.Name(rawValue: "reloadTabChats"), object: nil, userInfo: nil)
  193. }
  194. if self.fromNotification {
  195. self.didTapExit()
  196. } else {
  197. self.navigationController?.popViewController(animated: true)
  198. }
  199. // self.dataMessages.removeAll()
  200. // self.dataDates.removeAll()
  201. // self.tableChatView.reloadData()
  202. }))
  203. self.present(alert, animated: true, completion: nil)
  204. }
  205. })
  206. ])
  207. let exblock = User.getData(pin: self.dataPerson["f_pin"]!!)?.ex_block
  208. blocking = exblock == nil ? "0" : exblock!.isEmpty ? "0" : exblock!
  209. if blocking == "1" && self.dataPerson["f_pin"]!! != "-999" {
  210. menu = UIMenu(title: "", children: [
  211. UIAction(title: "Unblock".localized(), handler: {(_) in
  212. if !self.isContactCenter {
  213. DispatchQueue.global().async {
  214. if let response = Nexilis.writeAndWait(message: CoreMessage_TMessageBank.getUnBlock(l_pin: self.dataPerson["f_pin"]!!)) {
  215. if !response.isOk() {
  216. DispatchQueue.main.async {
  217. let imageView = UIImageView(image: UIImage(systemName: "xmark.circle.fill"))
  218. imageView.tintColor = .white
  219. let banner = FloatingNotificationBanner(title: "Unable to complete action".localized(), subtitle: nil, titleFont: UIFont.systemFont(ofSize: 16), titleColor: nil, titleTextAlign: .left, subtitleFont: nil, subtitleColor: nil, subtitleTextAlign: nil, leftView: imageView, rightView: nil, style: .danger, colors: nil, iconPosition: .center)
  220. banner.show()
  221. }
  222. } else {
  223. DispatchQueue.main.async { [self] in
  224. Database.shared.database?.inTransaction({ (fmdb, rollback) in
  225. _ = Database.shared.updateRecord(fmdb: fmdb, table: "BUDDY", cvalues: [
  226. "ex_block" : "0"
  227. ], _where: "f_pin = '\(self.dataPerson["f_pin"]!!)'")
  228. })
  229. containerAction.subviews.forEach({ $0.removeFromSuperview() })
  230. containerAction.removeFromSuperview()
  231. setRightButtonItem()
  232. changeAppBar()
  233. }
  234. }
  235. } else {
  236. DispatchQueue.main.async {
  237. let imageView = UIImageView(image: UIImage(systemName: "xmark.circle.fill"))
  238. imageView.tintColor = .white
  239. let banner = FloatingNotificationBanner(title: "Unable to access servers".localized(), subtitle: nil, titleFont: UIFont.systemFont(ofSize: 16), titleColor: nil, titleTextAlign: .left, subtitleFont: nil, subtitleColor: nil, subtitleTextAlign: nil, leftView: imageView, rightView: nil, style: .danger, colors: nil, iconPosition: .center)
  240. banner.show()
  241. }
  242. }
  243. }
  244. }
  245. }),
  246. UIAction(title: "Delete Conversation".localized(), handler: {(_) in
  247. if !self.isContactCenter {
  248. let alert = UIAlertController(title: "", message: "Are you sure to delete all message in this conversation?".localized(), preferredStyle: .alert)
  249. alert.addAction(UIAlertAction(title: "Cancel".localized(), style: UIAlertAction.Style.default, handler: nil))
  250. alert.addAction(UIAlertAction(title: "Delete".localized(), style: .destructive, handler: {(_) in
  251. DispatchQueue.global().async {
  252. Database.shared.database?.inTransaction({ (fmdb, rollback) in
  253. _ = Database.shared.deleteRecord(fmdb: fmdb, table: "MESSAGE_SUMMARY", _where: "l_pin='\(self.dataPerson["f_pin"]!!)'")
  254. _ = Database.shared.deleteRecord(fmdb: fmdb, table: "MESSAGE", _where: "(f_pin='\(self.dataPerson["f_pin"]!!)' or l_pin='\(self.dataPerson["f_pin"]!!)') and (message_scope_id='3' or message_scope_id='18') and is_call_center = 0")
  255. })
  256. NotificationCenter.default.post(name: NSNotification.Name(rawValue: "reloadTabChats"), object: nil, userInfo: nil)
  257. }
  258. if self.fromNotification {
  259. self.didTapExit()
  260. } else {
  261. self.navigationController?.popViewController(animated: true)
  262. }
  263. // self.dataMessages.removeAll()
  264. // self.dataDates.removeAll()
  265. // self.tableChatView.reloadData()
  266. }))
  267. self.present(alert, animated: true, completion: nil)
  268. }
  269. })
  270. ])
  271. blockedView(blocked: "1")
  272. } else if blocking == "0" {
  273. if self.dataPerson["f_pin"]!! != "-999"{
  274. menu = UIMenu(title: "", children: [
  275. UIAction(title: "Block".localized(), handler: {(_) in
  276. if !self.isContactCenter {
  277. DispatchQueue.global().async {
  278. if let response = Nexilis.writeAndWait(message: CoreMessage_TMessageBank.getBlock(l_pin: self.dataPerson["f_pin"]!!)) {
  279. if !response.isOk() {
  280. DispatchQueue.main.async {
  281. let imageView = UIImageView(image: UIImage(systemName: "xmark.circle.fill"))
  282. imageView.tintColor = .white
  283. let banner = FloatingNotificationBanner(title: "Unable to complete action".localized(), subtitle: nil, titleFont: UIFont.systemFont(ofSize: 16), titleColor: nil, titleTextAlign: .left, subtitleFont: nil, subtitleColor: nil, subtitleTextAlign: nil, leftView: imageView, rightView: nil, style: .danger, colors: nil, iconPosition: .center)
  284. banner.show()
  285. }
  286. } else {
  287. DispatchQueue.main.async { [self] in
  288. Database.shared.database?.inTransaction({ (fmdb, rollback) in
  289. _ = Database.shared.updateRecord(fmdb: fmdb, table: "BUDDY", cvalues: [
  290. "ex_block" : "1"
  291. ], _where: "f_pin = '\(self.dataPerson["f_pin"]!!)'")
  292. })
  293. setRightButtonItem()
  294. changeAppBar()
  295. }
  296. }
  297. } else {
  298. DispatchQueue.main.async {
  299. let imageView = UIImageView(image: UIImage(systemName: "xmark.circle.fill"))
  300. imageView.tintColor = .white
  301. let banner = FloatingNotificationBanner(title: "Unable to access servers".localized(), subtitle: nil, titleFont: UIFont.systemFont(ofSize: 16), titleColor: nil, titleTextAlign: .left, subtitleFont: nil, subtitleColor: nil, subtitleTextAlign: nil, leftView: imageView, rightView: nil, style: .danger, colors: nil, iconPosition: .center)
  302. banner.show()
  303. }
  304. }
  305. }
  306. }
  307. }),
  308. UIAction(title: "Delete Conversation".localized(), handler: {(_) in
  309. if !self.isContactCenter {
  310. let alert = UIAlertController(title: "", message: "Are you sure to delete all message in this conversation?".localized(), preferredStyle: .alert)
  311. alert.addAction(UIAlertAction(title: "Cancel".localized(), style: UIAlertAction.Style.default, handler: nil))
  312. alert.addAction(UIAlertAction(title: "Delete".localized(), style: .destructive, handler: {(_) in
  313. DispatchQueue.global().async {
  314. Database.shared.database?.inTransaction({ (fmdb, rollback) in
  315. _ = Database.shared.deleteRecord(fmdb: fmdb, table: "MESSAGE_SUMMARY", _where: "l_pin='\(self.dataPerson["f_pin"]!!)'")
  316. _ = Database.shared.deleteRecord(fmdb: fmdb, table: "MESSAGE", _where: "(f_pin='\(self.dataPerson["f_pin"]!!)' or l_pin='\(self.dataPerson["f_pin"]!!)') and (message_scope_id='3' or message_scope_id='18') and is_call_center = 0")
  317. })
  318. NotificationCenter.default.post(name: NSNotification.Name(rawValue: "reloadTabChats"), object: nil, userInfo: nil)
  319. }
  320. if self.fromNotification {
  321. self.didTapExit()
  322. } else {
  323. self.navigationController?.popViewController(animated: true)
  324. }
  325. // self.dataMessages.removeAll()
  326. // self.dataDates.removeAll()
  327. // self.tableChatView.reloadData()
  328. }))
  329. self.present(alert, animated: true, completion: nil)
  330. }
  331. })
  332. ])
  333. } else {
  334. menu = UIMenu(title: "", children: [
  335. UIAction(title: "Delete Conversation".localized(), handler: {(_) in
  336. if !self.isContactCenter {
  337. let alert = UIAlertController(title: "", message: "Are you sure to delete all message in this conversation?".localized(), preferredStyle: .alert)
  338. alert.addAction(UIAlertAction(title: "Cancel".localized(), style: UIAlertAction.Style.default, handler: nil))
  339. alert.addAction(UIAlertAction(title: "Delete".localized(), style: .destructive, handler: {(_) in
  340. DispatchQueue.global().async {
  341. Database.shared.database?.inTransaction({ (fmdb, rollback) in
  342. _ = Database.shared.deleteRecord(fmdb: fmdb, table: "MESSAGE_SUMMARY", _where: "l_pin='\(self.dataPerson["f_pin"]!!)'")
  343. _ = Database.shared.deleteRecord(fmdb: fmdb, table: "MESSAGE", _where: "(f_pin='\(self.dataPerson["f_pin"]!!)' or l_pin='\(self.dataPerson["f_pin"]!!)') and (message_scope_id='3' or message_scope_id='18') and is_call_center = 0")
  344. })
  345. NotificationCenter.default.post(name: NSNotification.Name(rawValue: "reloadTabChats"), object: nil, userInfo: nil)
  346. }
  347. if self.fromNotification {
  348. self.didTapExit()
  349. } else {
  350. self.navigationController?.popViewController(animated: true)
  351. }
  352. // self.dataMessages.removeAll()
  353. // self.dataDates.removeAll()
  354. // self.tableChatView.reloadData()
  355. }))
  356. self.present(alert, animated: true, completion: nil)
  357. }
  358. })
  359. ])
  360. }
  361. if containerAction.isDescendant(of: self.view) {
  362. containerAction.subviews.forEach({ $0.removeFromSuperview() })
  363. containerAction.removeFromSuperview()
  364. }
  365. } else {
  366. blockedView(blocked: "-1")
  367. changeAppBar()
  368. }
  369. let moreIcon = UIBarButtonItem(image: UIImage(systemName: "ellipsis", withConfiguration: UIImage.SymbolConfiguration(pointSize: 18, weight: .regular, scale: .default)), menu: menu)
  370. let buttonAudioCall = UIBarButtonItem(image: UIImage(systemName: "phone", withConfiguration: UIImage.SymbolConfiguration(pointSize: 18, weight: .regular, scale: .default)), style: .plain, target: self, action: #selector(audioVideoCall(sender:)))
  371. buttonAudioCall.tag = 0
  372. let buttonVideoCall = UIBarButtonItem(image: UIImage(systemName: "video", withConfiguration: UIImage.SymbolConfiguration(pointSize: 18, weight: .regular, scale: .default)), style: .plain, target: self, action: #selector(audioVideoCall(sender:)))
  373. buttonVideoCall.tag = 1
  374. let buttonAddRoom = UIBarButtonItem(image: UIImage(systemName: "plus.message", withConfiguration: UIImage.SymbolConfiguration(pointSize: 18, weight: .regular, scale: .default)), style: .plain, target: self, action: #selector(addRoom(sender:)))
  375. if dataPerson["f_pin"] != "-999" && !isContactCenter && blocking == "0" {
  376. navigationItem.rightBarButtonItems = [moreIcon,buttonAudioCall,buttonVideoCall]
  377. } else if !isContactCenter {
  378. navigationItem.rightBarButtonItem = moreIcon
  379. } else if !complaintId.isEmpty { //!complaintId.isEmpty
  380. navigationItem.rightBarButtonItem = buttonAddRoom
  381. }
  382. }
  383. func loadData() {
  384. if (unique_l_pin != "" || isContactCenter) {
  385. getDataProfile(fPin: unique_l_pin)
  386. if isContactCenter && !isRequestContactCenter && users.count == 0 {
  387. if !unique_l_pin.isEmpty {
  388. users.append(User.getData(pin: unique_l_pin) ?? User(pin: ""))
  389. }
  390. }
  391. }
  392. if onGoingCC {
  393. UserDefaults.standard.set(self.fPinContacCenter, forKey: "inEditorPersonal")
  394. } else {
  395. UserDefaults.standard.set(dataPerson["f_pin"]!, forKey: "inEditorPersonal")
  396. }
  397. UNUserNotificationCenter.current().removeDeliveredNotifications(withIdentifiers: [dataPerson["f_pin"]!!])
  398. if isContactCenter || fromNotification {
  399. let imageButton = UIImageView(frame: CGRect(x: -16, y: 0, width: 20, height: 44))
  400. imageButton.image = UIImage(systemName: "chevron.backward", withConfiguration: UIImage.SymbolConfiguration(pointSize: 20, weight: .regular, scale: .default))?.withTintColor(.white)
  401. imageButton.contentMode = .left
  402. let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(didTapExit))
  403. imageButton.isUserInteractionEnabled = true
  404. imageButton.addGestureRecognizer(tapGestureRecognizer)
  405. let leftItem = UIBarButtonItem(customView: imageButton)
  406. self.navigationItem.leftBarButtonItem = leftItem
  407. }
  408. if dataPerson["f_pin"] == "-999" {
  409. chatbot()
  410. }
  411. changeAppBar()
  412. getData()
  413. tableChatView.alpha = 0
  414. tableChatView.delegate = self
  415. tableChatView.dataSource = self
  416. tableChatView.keyboardDismissMode = .interactive
  417. let tapGesture = UITapGestureRecognizer(target: self, action: #selector(dismissKeyboard))
  418. tapGesture.cancelsTouchesInView = false
  419. tableChatView.addGestureRecognizer(tapGesture)
  420. if !isContactCenter {
  421. getCounter()
  422. if counter > 0 && dataMessages.count >= counter {
  423. markerCounter = dataMessages[dataMessages.count - counter]["message_id"] as? String
  424. }
  425. tableChatView.alpha = 0
  426. if counter != 0 && dataMessages.count >= counter {
  427. if dataMessages.firstIndex(where: {$0["message_id"] as? String == markerCounter} ) != 0 {
  428. DispatchQueue.main.async {
  429. let data = self.dataMessages.filter({ $0["message_id"] as? String == self.markerCounter })
  430. let section = self.dataDates.firstIndex(of: data[0]["chat_date"] as! String)
  431. let row = self.dataMessages.filter({$0["chat_date"] as! String == data[0]["chat_date"] as! String}).firstIndex(where: { $0["message_id"] as? String == self.markerCounter})
  432. self.tableChatView.scrollToRow(at: IndexPath(row: row!, section: section!), at: .bottom, animated: false)
  433. }
  434. } else {
  435. tableChatView.scrollToTop()
  436. }
  437. DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) { [self] in
  438. if currentIndexpath == nil && counter != 0 {
  439. let idMe = UserDefaults.standard.string(forKey: "me") as String?
  440. if let idx = dataMessages.firstIndex(where: { $0["message_id"] as? String == markerCounter}) {
  441. for i in idx..<dataMessages.count {
  442. if dataMessages[i]["f_pin"] as? String != idMe {
  443. sendReadMessageStatus(chat_id: "", f_pin: dataPerson["f_pin"]!!, message_scope_id: "3", message_id: dataMessages[i]["message_id"] as! String)
  444. }
  445. }
  446. counter = 0
  447. updateCounter(counter: counter)
  448. }
  449. }
  450. }
  451. } else {
  452. tableChatView.scrollToBottom(isAnimated: false)
  453. }
  454. } else if isContactCenter && onGoingCC {
  455. let idMe = UserDefaults.standard.string(forKey: "me") as String?
  456. for i in 0..<dataMessages.count {
  457. if dataMessages[i]["f_pin"] as? String != idMe {
  458. sendReadMessageStatus(chat_id: "", f_pin: dataPerson["f_pin"]!!, message_scope_id: "3", message_id: dataMessages[i]["message_id"] as! String)
  459. }
  460. }
  461. tableChatView.scrollToBottom(isAnimated: false)
  462. } else {
  463. tableChatView.scrollToBottom(isAnimated: false)
  464. }
  465. UIView.animate(withDuration: 0.5, animations: {
  466. self.tableChatView.alpha = 1.0
  467. })
  468. }
  469. private func chatbot() {
  470. let containerChatbot = UIView()
  471. self.view.addSubview(containerChatbot)
  472. containerChatbot.translatesAutoresizingMaskIntoConstraints = false
  473. NSLayoutConstraint.activate([
  474. containerChatbot.leadingAnchor.constraint(equalTo: self.view.leadingAnchor),
  475. containerChatbot.trailingAnchor.constraint(equalTo: self.view.trailingAnchor),
  476. containerChatbot.bottomAnchor.constraint(equalTo: self.view.bottomAnchor),
  477. containerChatbot.heightAnchor.constraint(equalToConstant: 120)
  478. ])
  479. containerChatbot.backgroundColor = .secondaryColor.withAlphaComponent(0.8)
  480. let labelChatbot = UILabel()
  481. containerChatbot.addSubview(labelChatbot)
  482. labelChatbot.translatesAutoresizingMaskIntoConstraints = false
  483. NSLayoutConstraint.activate([
  484. labelChatbot.centerYAnchor.constraint(equalTo: containerChatbot.centerYAnchor),
  485. labelChatbot.centerXAnchor.constraint(equalTo: containerChatbot.centerXAnchor),
  486. ])
  487. labelChatbot.textColor = .black
  488. labelChatbot.font = UIFont.systemFont(ofSize: 12).bold
  489. labelChatbot.text = "Interactive chatbot. Coming soon".localized()
  490. }
  491. private func changeAppBar() {
  492. let viewAppBar = UIView()
  493. viewAppBar.frame.size = CGSize(width: self.view.frame.size.width, height: 44)
  494. let imageProfile = UIImageView(frame: CGRect(x: 0, y: 7, width: 30, height: 30))
  495. imageProfile.circle()
  496. imageProfile.clipsToBounds = true
  497. let pictureImage = dataPerson["picture"]!
  498. var count = 0
  499. if isContactCenter {
  500. if fPinContacCenter.isEmpty && isRequestContactCenter {
  501. getImage(name: dataPerson["picture"]!!, placeholderImage: UIImage(systemName: "person.circle.fill")!) { result, isDownloaded, image in
  502. imageProfile.image = image
  503. }
  504. viewAppBar.addSubview(imageProfile)
  505. } else {
  506. if users.count == 1 {
  507. viewAppBar.addSubview(imageProfile)
  508. getImage(name: users[0].thumb, placeholderImage: UIImage(systemName: "person.circle.fill")!) { result, isDownloaded, image in
  509. imageProfile.image = image
  510. imageProfile.contentMode = .scaleAspectFit
  511. }
  512. } else {
  513. for user in users {
  514. if count == 3 {
  515. count += 1
  516. continue
  517. }
  518. if count == 0 {
  519. let pictures = UIImageView(frame: CGRect(x: 0, y: 7, width: 30, height: 30))
  520. pictures.circle()
  521. pictures.clipsToBounds = true
  522. viewAppBar.addSubview(pictures)
  523. getImage(name: user.thumb, placeholderImage: UIImage(systemName: "person.circle.fill")!) { result, isDownloaded, image in
  524. pictures.image = image
  525. pictures.contentMode = .scaleAspectFit
  526. }
  527. } else {
  528. let pictures = UIImageView(frame: CGRect(x: count * 20 , y: 7, width: 30, height: 30))
  529. pictures.circle()
  530. pictures.clipsToBounds = true
  531. viewAppBar.addSubview(pictures)
  532. getImage(name: user.thumb, placeholderImage: UIImage(systemName: "person.circle.fill")!) { result, isDownloaded, image in
  533. pictures.image = image
  534. pictures.contentMode = .scaleAspectFit
  535. }
  536. }
  537. count += 1
  538. }
  539. }
  540. }
  541. } else if dataPerson["f_pin"]!! == "-999" {
  542. viewAppBar.addSubview(imageProfile)
  543. imageProfile.image = UIImage(named: "pb_button", in: Bundle.resourceBundle(for: Nexilis.self), with: nil)
  544. imageProfile.contentMode = .scaleAspectFit
  545. }
  546. else if (pictureImage != "" && pictureImage != nil) {
  547. viewAppBar.addSubview(imageProfile)
  548. imageProfile.setImage(name: pictureImage!)
  549. imageProfile.contentMode = .scaleAspectFill
  550. } else {
  551. viewAppBar.addSubview(imageProfile)
  552. imageProfile.image = UIImage(systemName: "person")
  553. imageProfile.contentMode = .scaleAspectFit
  554. imageProfile.backgroundColor = .lightGray
  555. }
  556. var titleNavigation = UILabel(frame: CGRect(x: 35, y: 0, width: viewAppBar.frame.size.width - 150, height: 44))
  557. if dataPerson["f_pin"]!! != "-999" && !isContactCenter && (blocking == "-1" || blocking == "1") {
  558. titleNavigation = UILabel(frame: CGRect(x: 35, y: 0, width: viewAppBar.frame.size.width - 250, height: 44))
  559. } else if isContactCenter {
  560. if users.count > 0 {
  561. titleNavigation = UILabel(frame: CGRect(x: 35 * (CGFloat(users.count)) - (CGFloat((users.count - 1) * 15)), y: 0, width: viewAppBar.frame.size.width - 150 - (35 * (CGFloat(users.count - 1)) - (CGFloat((users.count - 1) * 15))), height: 44))
  562. }
  563. }
  564. viewAppBar.addSubview(titleNavigation)
  565. if ((dataPerson["isOfficial"] == "1" && !isContactCenter) || (dataPerson["isOfficial"] == "1" && fPinContacCenter.isEmpty)) {
  566. var name = dataPerson["name"]!!
  567. if (isContactCenter) {
  568. name = name + " " + "Contact Center".localized()
  569. }
  570. titleNavigation.set(image: UIImage(named: "ic_official_flag", in: Bundle.resourceBundle(for: Nexilis.self), with: nil)!.withTintColor(.white), with: " \(name)", size: 15, y: -4)
  571. } else {
  572. if !isContactCenter {
  573. titleNavigation.text = dataPerson["name"] as? String
  574. } else {
  575. if users.count == 1 {
  576. titleNavigation.text = users[0].fullName
  577. } else {
  578. var stringName = ""
  579. for user in users {
  580. if stringName.isEmpty {
  581. stringName = user.fullName
  582. } else {
  583. stringName += ", \(user.fullName)"
  584. }
  585. }
  586. titleNavigation.text = stringName
  587. }
  588. }
  589. }
  590. titleNavigation.textColor = .white
  591. titleNavigation.font = UIFont.systemFont(ofSize: 12).bold
  592. navigationItem.titleView = viewAppBar
  593. if copySession || forwardSession || deleteSession {
  594. navigationItem.hidesBackButton = true
  595. navigationController?.interactivePopGestureRecognizer?.isEnabled = false
  596. } else {
  597. navigationItem.hidesBackButton = false
  598. navigationController?.interactivePopGestureRecognizer?.isEnabled = true
  599. }
  600. viewAppBar.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(seeProfileTapped)))
  601. }
  602. private func getDataProfile(fPin: String) {
  603. var query = "SELECT f_pin, first_name || ' ' || last_name, official_account, image_id, device_id, offline_mode, user_type FROM BUDDY where f_pin = '\(fPin)'"
  604. if (isContactCenter && isRequestContactCenter) {
  605. query = "SELECT group_id, f_name, official, image_id FROM GROUPZ where group_type = 1 AND official = 1"
  606. }
  607. Database.shared.database?.inTransaction({ (fmdb, rollback) in
  608. if let cursorData = Database.shared.getRecords(fmdb: fmdb, query: query) {
  609. if cursorData.next() {
  610. dataPerson["f_pin"] = cursorData.string(forColumnIndex: 0)
  611. dataPerson["name"] = cursorData.string(forColumnIndex: 1)?.trimmingCharacters(in: .whitespaces)
  612. dataPerson["picture"] = cursorData.string(forColumnIndex: 3)
  613. dataPerson["isOfficial"] = cursorData.string(forColumnIndex: 2)
  614. } else {
  615. dataPerson["f_pin"] = "-999"
  616. dataPerson["name"] = "Bot"
  617. dataPerson["picture"] = ""
  618. dataPerson["isOfficial"] = ""
  619. dataPerson["deviceId"] = ""
  620. dataPerson["isOffline"] = "0"
  621. dataPerson["user_type"] = "0"
  622. }
  623. cursorData.close()
  624. }
  625. })
  626. }
  627. private func getData() {
  628. var query = "SELECT message_id, f_pin, l_pin, message_scope_id, server_date, status, message_text, audio_id, video_id, image_id, thumb_id, read_receipts, chat_id, file_id, attachment_flag, reff_id, lock, is_stared, blog_id FROM MESSAGE where (f_pin='\(dataPerson["f_pin"]!!)' or l_pin='\(dataPerson["f_pin"]!!)') AND (message_scope_id = '3' OR message_scope_id = '18') AND is_call_center = 0 order by server_date asc"
  629. if isContactCenter {
  630. if complaintId.isEmpty {
  631. query = "SELECT message_id, f_pin, l_pin, message_scope_id, server_date, status, message_text, audio_id, video_id, image_id, thumb_id, read_receipts, chat_id, file_id, attachment_flag, reff_id, lock, is_stared FROM MESSAGE where (f_pin='\(dataPerson["f_pin"]!!)' or l_pin='\(dataPerson["f_pin"]!!)') AND message_scope_id = '5' AND broadcast_flag = 0 AND is_call_center = 1 order by server_date asc"
  632. } else {
  633. query = "SELECT message_id, f_pin, l_pin, message_scope_id, server_date, status, message_text, audio_id, video_id, image_id, thumb_id, read_receipts, chat_id, file_id, attachment_flag, reff_id, lock, is_stared FROM MESSAGE where message_scope_id = '5' AND broadcast_flag = 0 AND is_call_center = 1 AND call_center_id = '\(complaintId)' order by server_date asc"
  634. }
  635. if isRequestContactCenter {
  636. var row: [String: Any?] = [:]
  637. row["f_pin"] = nil
  638. row["message_id"] = ""
  639. row["chat_date"] = "Today".localized()
  640. let listStringName: [String] = ["Chat with a Representative", "Video Call a Representative", "Call a Representative"]
  641. var data : [CategoryCC] = []
  642. for i in 0..<listStringName.count {
  643. data.append(CategoryCC(id: "level0_\(i)", service_id: "", service_name: listStringName[i], parent: "\(i)", description: "", is_tablet: "0"))
  644. }
  645. row["category_cc"] = data
  646. row["attachment_flag"] = "503"
  647. dataDates.append("Today".localized())
  648. dataMessages.append(row)
  649. }
  650. }
  651. Database.shared.database?.inTransaction({ (fmdb, rollback) in
  652. if let cursorData = Database.shared.getRecords(fmdb: fmdb, query: query) {
  653. while cursorData.next() {
  654. var row: [String: Any?] = [:]
  655. row["message_id"] = cursorData.string(forColumnIndex: 0)
  656. row["f_pin"] = cursorData.string(forColumnIndex: 1)
  657. row["l_pin"] = cursorData.string(forColumnIndex: 2)
  658. row["message_scope_id"] = cursorData.string(forColumnIndex: 3)
  659. row["server_date"] = cursorData.string(forColumnIndex: 4)
  660. row["status"] = cursorData.string(forColumnIndex: 5)
  661. row["message_text"] = cursorData.string(forColumnIndex: 6)
  662. row["audio_id"] = cursorData.string(forColumnIndex: 7)
  663. row["video_id"] = cursorData.string(forColumnIndex: 8)
  664. row["image_id"] = cursorData.string(forColumnIndex: 9)
  665. row["thumb_id"] = cursorData.string(forColumnIndex: 10)
  666. row["read_receipts"] = cursorData.int(forColumnIndex: 11)
  667. row["chat_id"] = cursorData.string(forColumnIndex: 12)
  668. row["file_id"] = cursorData.string(forColumnIndex: 13)
  669. row["attachment_flag"] = cursorData.string(forColumnIndex: 14)
  670. row["reff_id"] = cursorData.string(forColumnIndex: 15)
  671. row["lock"] = cursorData.string(forColumnIndex: 16)
  672. row["is_stared"] = cursorData.string(forColumnIndex: 17)
  673. row["blog_id"] = cursorData.string(forColumnIndex: 18)
  674. if let cursorStatus = Database.shared.getRecords(fmdb: fmdb, query: "SELECT status FROM MESSAGE_STATUS WHERE message_id='\(row["message_id"] as! String)'") {
  675. while cursorStatus.next() {
  676. row["status"] = cursorStatus.string(forColumnIndex: 0)
  677. }
  678. cursorStatus.close()
  679. }
  680. let nsDocumentDirectory = FileManager.SearchPathDirectory.documentDirectory
  681. let nsUserDomainMask = FileManager.SearchPathDomainMask.userDomainMask
  682. let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true)
  683. if let dirPath = paths.first {
  684. let videoURL = URL(fileURLWithPath: dirPath).appendingPathComponent(row["video_id"] as! String)
  685. let fileURL = URL(fileURLWithPath: dirPath).appendingPathComponent(row["file_id"] as! String)
  686. if ((row["video_id"] as! String) != "") {
  687. if FileManager.default.fileExists(atPath: videoURL.path){
  688. row["progress"] = 100.0
  689. } else {
  690. row["progress"] = 0.0
  691. }
  692. } else {
  693. if FileManager.default.fileExists(atPath: fileURL.path){
  694. row["progress"] = 100.0
  695. } else {
  696. row["progress"] = 0.0
  697. }
  698. }
  699. }
  700. row["chat_date"] = chatDate(stringDate: row["server_date"] as! String, messageId: row["message_id"] as! String)
  701. row["isSelected"] = false
  702. dataMessages.append(row)
  703. }
  704. cursorData.close()
  705. }
  706. })
  707. }
  708. func chatDate(stringDate: String, messageId: String) -> String {
  709. let date = Date(milliseconds: Int64(stringDate)!)
  710. let calendar = Calendar.current
  711. if (calendar.isDateInToday(date)) {
  712. if !dataDates.contains("Today".localized()){
  713. dataDates.append("Today".localized())
  714. }
  715. return "Today".localized()
  716. } else {
  717. let startOfNow = calendar.startOfDay(for: Date())
  718. let startOfTimeStamp = calendar.startOfDay(for: date)
  719. let components = calendar.dateComponents([.day], from: startOfNow, to: startOfTimeStamp)
  720. let day = -(components.day!)
  721. if day == 1{
  722. if !dataDates.contains("Yesterday".localized()){
  723. dataDates.append("Yesterday".localized())
  724. }
  725. return "Yesterday".localized()
  726. } else if day < 7 {
  727. if !dataDates.contains("\(day) " + "days".localized() + " " + "ago".localized()){
  728. dataDates.append("\(day) " + "days".localized() + " " + "ago".localized())
  729. }
  730. return "\(day) " + "days".localized() + " " + "ago".localized()
  731. } else {
  732. let formatter = DateFormatter()
  733. formatter.dateFormat = "dd MMMM yyyy"
  734. formatter.locale = NSLocale(localeIdentifier: "id") as Locale?
  735. let stringFormat = formatter.string(from: date as Date)
  736. if !dataDates.contains(stringFormat){
  737. dataDates.append(stringFormat)
  738. }
  739. return stringFormat
  740. }
  741. }
  742. }
  743. @objc func onUploadChat(notification: NSNotification) {
  744. let data:[AnyHashable : Any] = notification.userInfo!
  745. var isImage = false
  746. var idx = dataMessages.lastIndex(where: { $0["video_id"] as? String == data["name"] as? String })
  747. if (idx == nil) {
  748. idx = dataMessages.lastIndex(where: { $0["image_id"] as? String == data["name"] as? String })
  749. isImage = true
  750. }
  751. if (idx != nil) {
  752. let section = dataDates.firstIndex(of: dataMessages[idx!]["chat_date"] as! String)
  753. if section == nil {
  754. return
  755. }
  756. let row = dataMessages.filter({ $0["chat_date"] as! String == dataDates[section!]}).firstIndex(where: { $0["message_id"] as? String == dataMessages[idx!]["message_id"] as? String})
  757. if row == nil {
  758. return
  759. }
  760. DispatchQueue.main.async {
  761. let indexPath = IndexPath(row: row!, section: section!)
  762. if let cell = self.tableChatView.cellForRow(at: indexPath) {
  763. for view in cell.contentView.subviews {
  764. if !(view is UILabel) && !(view is UIImageView) {
  765. for viewInContainer in view.subviews {
  766. if viewInContainer is UIImageView {
  767. if viewInContainer.subviews.count == 0 {
  768. return
  769. }
  770. var containerView = UIView()
  771. if (isImage) {
  772. containerView = viewInContainer.subviews[0]
  773. } else {
  774. containerView = viewInContainer.subviews[1]
  775. }
  776. let loading = containerView.layer.sublayers![1] as! CAShapeLayer
  777. loading.strokeEnd = CGFloat(data["progress"] as! Double / 100)
  778. if (data["progress"] as! Double == 100.0) {
  779. self.dataMessages[idx!]["progress"] = data["progress"]
  780. self.tableChatView.reloadRows(at: [indexPath], with: .none)
  781. }
  782. }
  783. }
  784. }
  785. }
  786. }
  787. }
  788. } else {
  789. idx = dataMessages.lastIndex(where: { $0["file_id"] as? String == data["name"] as? String })
  790. if (idx != nil) {
  791. let section = dataDates.firstIndex(of: dataMessages[idx!]["chat_date"] as! String)
  792. if section == nil {
  793. return
  794. }
  795. let row = dataMessages.filter({ $0["chat_date"] as! String == dataDates[section!]}).firstIndex(where: { $0["message_id"] as? String == dataMessages[idx!]["message_id"] as? String})
  796. if row == nil {
  797. return
  798. }
  799. DispatchQueue.main.async {
  800. let indexPath = IndexPath(row: row!, section: section!)
  801. if let cell = self.tableChatView.cellForRow(at: indexPath) {
  802. for view in cell.contentView.subviews {
  803. if !(view is UILabel) && !(view is UIImageView) {
  804. for viewSubviews in view.subviews {
  805. if !(viewSubviews is UILabel) {
  806. for viewInContainer in viewSubviews.subviews {
  807. if !(viewInContainer is UILabel) && !(viewInContainer is UIImageView) {
  808. if viewInContainer.layer.sublayers!.count < 2 {
  809. return
  810. }
  811. let loading = viewInContainer.layer.sublayers![1] as! CAShapeLayer
  812. loading.strokeEnd = CGFloat(data["progress"] as! Double / 100)
  813. if (data["progress"] as! Double == 100.0) {
  814. self.dataMessages[idx!]["progress"] = data["progress"]
  815. self.tableChatView.reloadRows(at: [indexPath], with: .none)
  816. }
  817. }
  818. }
  819. }
  820. }
  821. }
  822. }
  823. }
  824. }
  825. }
  826. }
  827. }
  828. @objc func onReceiveMessage(notification: NSNotification) {
  829. DispatchQueue.main.async { [self] in
  830. let data:[AnyHashable : Any] = notification.userInfo!
  831. if let dataMessage = data["message"] as? TMessage {
  832. let chatData = dataMessage.mBodies
  833. if (dataMessage.getCode() == CoreMessage_TMessageCode.PUSH_MEMBER_ROOM_CONTACT_CENTER && isContactCenter) {
  834. let data = dataMessage.getBody(key: CoreMessage_TMessageKey.DATA)
  835. if !data.isEmpty {
  836. if let jsonArray = try! JSONSerialization.jsonObject(with: data.data(using: String.Encoding.utf8)!, options: JSONSerialization.ReadingOptions()) as? [AnyObject] {
  837. var members = ""
  838. let idMe = UserDefaults.standard.string(forKey: "me")!
  839. var user : [User] = []
  840. for json in jsonArray {
  841. if "\(json)" != idMe {
  842. if members.isEmpty {
  843. members = "\(json)"
  844. } else {
  845. members += ",\(json)"
  846. }
  847. if let userData = User.getData(pin: "\(json)") {
  848. user.append(userData)
  849. } else {
  850. Nexilis.addFriend (fpin: "\(json)") { result in
  851. DispatchQueue.main.async {
  852. if result {
  853. let userData = User.getData(pin: "\(json)")!
  854. user.append(userData)
  855. } else {
  856. let imageView = UIImageView(image: UIImage(systemName: "xmark.circle.fill"))
  857. imageView.tintColor = .white
  858. let banner = FloatingNotificationBanner(title: "Server busy, please try again later".localized(), subtitle: nil, titleFont: UIFont.systemFont(ofSize: 16), titleColor: nil, titleTextAlign: .left, subtitleFont: nil, subtitleColor: nil, subtitleTextAlign: nil, leftView: imageView, rightView: nil, style: .danger, colors: nil, iconPosition: .center)
  859. banner.show()
  860. }
  861. }
  862. }
  863. }
  864. }
  865. }
  866. self.users = user
  867. self.fPinContacCenter = members
  868. self.changeAppBar()
  869. UserDefaults.standard.set(members, forKey: "inEditorPersonal")
  870. }
  871. }
  872. } else if (dataMessage.getCode() == CoreMessage_TMessageCode.ACCEPT_CALL_CENTER) {
  873. if !self.isRequestContactCenter || !isContactCenter {
  874. return
  875. }
  876. UserDefaults.standard.set(dataMessage.getBody(key: CoreMessage_TMessageKey.F_PIN), forKey: "inEditorPersonal")
  877. let date = Date()
  878. let formatter = DateFormatter()
  879. formatter.dateFormat = "HH:mm"
  880. formatter.locale = NSLocale(localeIdentifier: "id") as Locale?
  881. self.fPinContacCenter = dataMessage.getBody(key: CoreMessage_TMessageKey.F_PIN)
  882. self.complaintId = dataMessage.getBody(key: CoreMessage_TMessageKey.DATA)
  883. self.channelContactCenter = dataMessage.getBody(key: CoreMessage_TMessageKey.CHANNEL)
  884. var row: [String: Any?] = [:]
  885. row["category_cc"] = "You are connecting with ".localized() + dataMessage.getBody(key: CoreMessage_TMessageKey.F_DISPLAY_NAME).trimmingCharacters(in: .whitespaces) + " at ".localized() + formatter.string(from: date as Date) + ".\n" + "In order to improve our service, all conversations will be recorded\naccording to state regulations".localized()
  886. row["message_id"] = ""
  887. row["message_text"] = "You are connecting with ".localized() + dataMessage.getBody(key: CoreMessage_TMessageKey.F_DISPLAY_NAME).trimmingCharacters(in: .whitespaces) + " at ".localized() + formatter.string(from: date as Date) + ".\n" + "In order to improve our service, all conversations will be recorded\naccording to state regulations".localized()
  888. row["chat_date"] = "Today".localized()
  889. self.dataMessages.append(row)
  890. self.users.append(User.getData(pin: dataMessage.getBody(key: CoreMessage_TMessageKey.F_PIN))!)
  891. self.changeAppBar()
  892. self.setRightButtonItem()
  893. self.dateStartCC = "\(Date().currentTimeMillis())"
  894. self.tableChatView.insertRows(at: [IndexPath(row: self.dataMessages.count - 1, section: 0)], with: .none)
  895. self.tableChatView.scrollToBottom()
  896. UserDefaults.standard.removeObject(forKey: "waitingRequestCC")
  897. if dataMessage.getBody(key: CoreMessage_TMessageKey.CHANNEL) != "0" {
  898. UserDefaults.standard.set("\(Date().currentTimeMillis())", forKey: "startTimeCC")
  899. DispatchQueue.main.asyncAfter(deadline: .now() + 1, execute: {
  900. self.dismiss(animated: true, completion: nil)
  901. })
  902. }
  903. } else if (dataMessage.getCode() == CoreMessage_TMessageCode.INVITE_END_CONTACT_CENTER || dataMessage.getCode() == CoreMessage_TMessageCode.END_CALL_CENTER || dataMessage.getCode() == CoreMessage_TMessageCode.INVITE_EXIT_CONTACT_CENTER) {
  904. let onGoingCC = UserDefaults.standard.string(forKey: "onGoingCC") ?? ""
  905. if onGoingCC.isEmpty || !isContactCenter {
  906. return
  907. }
  908. let requester = onGoingCC.components(separatedBy: ",")[0]
  909. let officer = onGoingCC.isEmpty ? "" : onGoingCC.components(separatedBy: ",")[1]
  910. let fPin = dataMessage.getCode() == CoreMessage_TMessageCode.END_CALL_CENTER ? chatData[CoreMessage_TMessageKey.F_PIN] : dataMessage.getPIN()
  911. if fPin == officer || fPin == requester {
  912. DispatchQueue.global().async {
  913. let date = "\(Date().currentTimeMillis())"
  914. Database.shared.database?.inTransaction({ (fmdb, rollback) in
  915. do {
  916. _ = try Database.shared.insertRecord(fmdb: fmdb, table: "CALL_CENTER_HISTORY", cvalues: [
  917. "type" : self.channelContactCenter,
  918. "title" : "Contact Center".localized(),
  919. "time" : self.dateStartCC,
  920. "f_pin" : officer,
  921. "data" : self.complaintId,
  922. "time_end" : date,
  923. "complaint_id" : self.complaintId,
  924. "members" : "",
  925. "requester": requester
  926. ], replace: true)
  927. } catch {
  928. rollback.pointee = true
  929. print(error)
  930. }
  931. })
  932. }
  933. self.dismissKeyboard()
  934. self.disableEditor()
  935. UserDefaults.standard.removeObject(forKey: "onGoingCC")
  936. UserDefaults.standard.removeObject(forKey: "membersCC")
  937. UserDefaults.standard.removeObject(forKey: "waitingRequestCC")
  938. DispatchQueue.main.async {
  939. let imageView = UIImageView(image: UIImage(systemName: "info.circle"))
  940. imageView.tintColor = .white
  941. 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)
  942. banner.show()
  943. }
  944. timeoutCC.invalidate()
  945. DispatchQueue.main.asyncAfter(deadline: .now() + 1.5, execute: {
  946. if !(self.presentedViewController is EditorPersonal) {
  947. self.dismiss(animated: true, completion: nil)
  948. }
  949. DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
  950. self.dismiss(animated: true, completion: nil)
  951. }
  952. })
  953. } else {
  954. var members = ""
  955. self.users.removeAll(where: {$0.pin == fPin})
  956. for user in self.users {
  957. if members.isEmpty {
  958. members = "\(user.pin)"
  959. } else {
  960. members = ",\(user.pin)"
  961. }
  962. }
  963. UserDefaults.standard.set("\(members)", forKey: "membersCC")
  964. self.fPinContacCenter = members
  965. self.changeAppBar()
  966. }
  967. }
  968. else if (chatData[CoreMessage_TMessageKey.F_PIN] == self.dataPerson["f_pin"]!! && !self.isContactCenter && (chatData[CoreMessage_TMessageKey.MESSAGE_SCOPE_ID] == "3")) || (self.isContactCenter && chatData[CoreMessage_TMessageKey.MESSAGE_SCOPE_ID] == "5" && self.complaintId == chatData[CoreMessage_TMessageKey.CALL_CENTER_ID]) {
  969. if chatData[CoreMessage_TMessageKey.F_PIN] == nil {
  970. return
  971. }
  972. print("CHAT DATA \(chatData)")
  973. var row: [String: Any?] = [:]
  974. row["message_id"] = chatData[CoreMessage_TMessageKey.MESSAGE_ID]
  975. row["f_pin"] = chatData[CoreMessage_TMessageKey.F_PIN]
  976. row["l_pin"] = chatData[CoreMessage_TMessageKey.L_PIN]
  977. row["message_scope_id"] = chatData[CoreMessage_TMessageKey.MESSAGE_SCOPE_ID]
  978. row["server_date"] = chatData[CoreMessage_TMessageKey.SERVER_DATE]
  979. row["status"] = chatData[CoreMessage_TMessageKey.STATUS]
  980. row["message_text"] = chatData[CoreMessage_TMessageKey.MESSAGE_TEXT]
  981. if (chatData.keys.contains(CoreMessage_TMessageKey.AUDIO_ID)) {
  982. row["audio_id"] = chatData[CoreMessage_TMessageKey.AUDIO_ID]
  983. } else {
  984. row["audio_id"] = ""
  985. }
  986. if (chatData.keys.contains(CoreMessage_TMessageKey.VIDEO_ID)) {
  987. row["video_id"] = chatData[CoreMessage_TMessageKey.VIDEO_ID]
  988. } else {
  989. row["video_id"] = ""
  990. }
  991. if (chatData.keys.contains(CoreMessage_TMessageKey.IMAGE_ID)) {
  992. row["image_id"] = chatData[CoreMessage_TMessageKey.IMAGE_ID]
  993. } else {
  994. row["image_id"] = ""
  995. }
  996. if (chatData.keys.contains(CoreMessage_TMessageKey.THUMB_ID)) {
  997. row["thumb_id"] = chatData[CoreMessage_TMessageKey.THUMB_ID]
  998. } else {
  999. row["thumb_id"] = ""
  1000. }
  1001. row["read_receipts"] = 0
  1002. row["chat_id"] = ""
  1003. if (chatData.keys.contains(CoreMessage_TMessageKey.FILE_ID)) {
  1004. row["file_id"] = chatData[CoreMessage_TMessageKey.FILE_ID]
  1005. } else {
  1006. row["file_id"] = ""
  1007. }
  1008. row["progress"] = 0.0
  1009. row["attachment_flag"] = chatData[CoreMessage_TMessageKey.ATTACHMENT_FLAG]
  1010. row["reff_id"] = chatData[CoreMessage_TMessageKey.REF_ID] ?? ""
  1011. row["lock"] = ""
  1012. row["is_stared"] = "0"
  1013. row["isSelected"] = false
  1014. if !self.dataDates.contains("Today".localized()) {
  1015. self.dataDates.append("Today".localized())
  1016. self.tableChatView.insertSections(IndexSet(integer: self.dataDates.count - 1), with: .none)
  1017. }
  1018. row["chat_date"] = "Today".localized()
  1019. row["blog_id"] = chatData[CoreMessage_TMessageKey.BLOG_ID]
  1020. self.counter += 1
  1021. self.dataMessages.append(row)
  1022. self.tableChatView.insertRows(at: [IndexPath(row: self.dataMessages.filter({ $0["chat_date"] as! String == self.dataDates[self.dataDates.count - 1]}).count - 1, section: self.dataDates.count - 1)], with: .none)
  1023. if self.isContactCenter {
  1024. let idMe = UserDefaults.standard.string(forKey: "me")!
  1025. let onGoingCC = UserDefaults.standard.string(forKey: "onGoingCC") ?? ""
  1026. let officer = onGoingCC.isEmpty ? "" : onGoingCC.components(separatedBy: ",")[1]
  1027. if officer == idMe {
  1028. self.timeoutCC.invalidate()
  1029. } else {
  1030. if !self.showToast30s {
  1031. self.showToast(message: "Please reply within 30 seconds so the call center session doesn't end.".localized(), font: UIFont.systemFont(ofSize: 12, weight: .medium), controller: self)
  1032. sendTyping(l_pin: fPinContacCenter, isTyping: true)
  1033. self.showToast30s = true
  1034. }
  1035. }
  1036. }
  1037. if chatData[CoreMessage_TMessageKey.FORMAT] == "1" {
  1038. self.sendReadMessageStatus(chat_id: "", f_pin: chatData[CoreMessage_TMessageKey.F_PIN]!, message_scope_id: chatData[CoreMessage_TMessageKey.MESSAGE_SCOPE_ID]!, message_id: chatData[CoreMessage_TMessageKey.MESSAGE_ID]!)
  1039. self.tableChatView.scrollToBottom()
  1040. } else if self.currentIndexpath?.row == (self.dataMessages.count - 2) {
  1041. if (self.viewIfLoaded?.window != nil) {
  1042. self.sendReadMessageStatus(chat_id: "", f_pin: chatData[CoreMessage_TMessageKey.F_PIN]!, message_scope_id: chatData[CoreMessage_TMessageKey.MESSAGE_SCOPE_ID]!, message_id: chatData[CoreMessage_TMessageKey.MESSAGE_ID]!)
  1043. }
  1044. self.tableChatView.scrollToBottom()
  1045. if ( self.currentIndexpath!.section <= self.dataDates.count - 1 && self.currentIndexpath!.row <= self.dataMessages.filter({ $0["chat_date"] as! String == self.dataDates[self.dataDates.count - 1]}).count - 1) {
  1046. self.counter = 0
  1047. self.updateCounter(counter: self.counter)
  1048. }
  1049. if self.markerCounter != nil {
  1050. self.markerCounter = nil
  1051. }
  1052. self.tableChatView.reloadData()
  1053. }
  1054. else if self.currentIndexpath == nil {
  1055. self.counter = 0
  1056. self.updateCounter(counter: self.counter)
  1057. if (self.viewIfLoaded?.window != nil) {
  1058. self.sendReadMessageStatus(chat_id: "", f_pin: chatData[CoreMessage_TMessageKey.F_PIN]!, message_scope_id: chatData[CoreMessage_TMessageKey.MESSAGE_SCOPE_ID]!, message_id: chatData[CoreMessage_TMessageKey.MESSAGE_ID]!)
  1059. }
  1060. }
  1061. else if self.counter != 0 {
  1062. if !self.indicatorCounterBSTB.isDescendant(of: self.view) && self.buttonScrollToBottom.isDescendant(of: self.view) {
  1063. self.markerCounter = row["message_id"] as? String
  1064. self.addCounterAtButttonScrollToBottom()
  1065. self.tableChatView.reloadData()
  1066. } else if self.indicatorCounterBSTB.isDescendant(of: self.view) {
  1067. self.labelCounter.text = "\(self.counter)"
  1068. }
  1069. }
  1070. }
  1071. } else if !self.isContactCenter {
  1072. NotificationCenter.default.post(name: NSNotification.Name(rawValue: "reloadTabChats"), object: nil, userInfo: nil)
  1073. }
  1074. }
  1075. }
  1076. private func disableEditor() {
  1077. view.addSubview(containerAction)
  1078. containerAction.translatesAutoresizingMaskIntoConstraints = false
  1079. NSLayoutConstraint.activate([
  1080. containerAction.leadingAnchor.constraint(equalTo: self.view.leadingAnchor),
  1081. containerAction.trailingAnchor.constraint(equalTo: self.view.trailingAnchor),
  1082. containerAction.bottomAnchor.constraint(equalTo: self.view.bottomAnchor),
  1083. containerAction.heightAnchor.constraint(equalToConstant: 120)
  1084. ])
  1085. containerAction.backgroundColor = .secondaryColor.withAlphaComponent(0.8)
  1086. let labelDisable = UILabel()
  1087. containerAction.addSubview(labelDisable)
  1088. labelDisable.translatesAutoresizingMaskIntoConstraints = false
  1089. NSLayoutConstraint.activate([
  1090. labelDisable.centerYAnchor.constraint(equalTo: containerAction.centerYAnchor),
  1091. labelDisable.centerXAnchor.constraint(equalTo: containerAction.centerXAnchor),
  1092. ])
  1093. labelDisable.textColor = .black
  1094. labelDisable.font = UIFont.systemFont(ofSize: 12).bold
  1095. labelDisable.text = "Call center session is over".localized()
  1096. }
  1097. @objc func onStatusChat(notification: NSNotification) {
  1098. DispatchQueue.main.async {
  1099. let data:[AnyHashable : Any] = notification.userInfo!
  1100. if let dataMessage = data["message"] as? TMessage {
  1101. let chatData = dataMessage.mBodies
  1102. let onGoingCC = UserDefaults.standard.string(forKey: "onGoingCC") ?? ""
  1103. let requester = onGoingCC.components(separatedBy: ",")[0]
  1104. let idMe = UserDefaults.standard.string(forKey: "me")!
  1105. if chatData[CoreMessage_TMessageKey.F_PIN] == self.dataPerson["f_pin"]!! || chatData[CoreMessage_TMessageKey.L_PIN] == self.dataPerson["f_pin"]!! || chatData[CoreMessage_TMessageKey.L_PIN] == self.fPinContacCenter || requester == idMe {
  1106. if (chatData.keys.contains(CoreMessage_TMessageKey.MESSAGE_ID) && !(chatData[CoreMessage_TMessageKey.MESSAGE_ID]!).contains("-2,")) {
  1107. let idx = self.dataMessages.firstIndex(where: { $0["message_id"] as? String == chatData[CoreMessage_TMessageKey.MESSAGE_ID]! })
  1108. if (idx != nil) {
  1109. if (chatData[CoreMessage_TMessageKey.DELETE_MESSAGE_FLAG] == "1") {
  1110. self.dataMessages[idx!]["lock"] = "1"
  1111. self.dataMessages[idx!]["reff_id"] = ""
  1112. let section = self.dataDates.firstIndex(of: self.dataMessages[idx!]["chat_date"] as! String)
  1113. let row = self.dataMessages.filter({ $0["chat_date"] as! String == self.dataMessages[idx!]["chat_date"] as! String}).firstIndex(where: { $0["message_id"] as? String == self.dataMessages[idx!]["message_id"] as? String })
  1114. if row != nil && section != nil {
  1115. self.tableChatView.reloadRows(at: [IndexPath(row: row!, section: section!)], with: .none)
  1116. self.tableChatView.reloadData()
  1117. }
  1118. } else {
  1119. self.dataMessages[idx!]["status"] = chatData[CoreMessage_TMessageKey.STATUS]!
  1120. let section = self.dataDates.firstIndex(of: self.dataMessages[idx!]["chat_date"] as! String)
  1121. let row = self.dataMessages.filter({ $0["chat_date"] as! String == self.dataMessages[idx!]["chat_date"] as! String}).firstIndex(where: { $0["message_id"] as? String == self.dataMessages[idx!]["message_id"] as? String })
  1122. if row != nil && section != nil {
  1123. self.tableChatView.reloadRows(at: [IndexPath(row: row!, section: section!)], with: .none)
  1124. }
  1125. }
  1126. if self.reffId != nil && self.reffId == chatData[CoreMessage_TMessageKey.MESSAGE_ID]! {
  1127. self.deleteReplyView()
  1128. }
  1129. }
  1130. }
  1131. else if (chatData.keys.contains("message_id")) {
  1132. let idx = self.dataMessages.firstIndex(where: { "'\(String(describing: $0["message_id"] as? String))'" == chatData["message_id"]! })
  1133. if (idx != nil) {
  1134. if (chatData[CoreMessage_TMessageKey.DELETE_MESSAGE_FLAG] == "1") {
  1135. self.dataMessages[idx!]["lock"] = "1"
  1136. self.dataMessages[idx!]["reff_id"] = ""
  1137. let section = self.dataDates.firstIndex(of: self.dataMessages[idx!]["chat_date"] as! String)
  1138. let row = self.dataMessages.filter({ $0["chat_date"] as! String == self.dataMessages[idx!]["chat_date"] as! String}).firstIndex(where: { $0["message_id"] as? String == self.dataMessages[idx!]["message_id"] as? String })
  1139. if row != nil && section != nil {
  1140. self.tableChatView.reloadRows(at: [IndexPath(row: row!, section: section!)], with: .none)
  1141. self.tableChatView.reloadData()
  1142. }
  1143. } else {
  1144. self.dataMessages[idx!]["status"] = chatData[CoreMessage_TMessageKey.STATUS]!
  1145. let section = self.dataDates.firstIndex(of: self.dataMessages[idx!]["chat_date"] as! String)
  1146. let row = self.dataMessages.filter({ $0["chat_date"] as! String == self.dataMessages[idx!]["chat_date"] as! String}).firstIndex(where: { $0["message_id"] as? String == self.dataMessages[idx!]["message_id"] as? String })
  1147. if row != nil && section != nil {
  1148. self.tableChatView.reloadRows(at: [IndexPath(row: row!, section: section!)], with: .none)
  1149. }
  1150. }
  1151. if self.reffId != nil && self.reffId == chatData["message_id"]! {
  1152. self.deleteReplyView()
  1153. }
  1154. }
  1155. }
  1156. else {
  1157. let messageId = chatData[CoreMessage_TMessageKey.MESSAGE_ID]!.split(separator: ",")[1]
  1158. let idx = self.dataMessages.firstIndex(where: { $0["message_id"] as? String ?? "" == messageId })
  1159. if (idx != nil) {
  1160. self.dataMessages[idx!]["status"] = chatData[CoreMessage_TMessageKey.STATUS]!
  1161. let section = self.dataDates.firstIndex(of: self.dataMessages[idx!]["chat_date"] as! String)
  1162. let row = self.dataMessages.filter({ $0["chat_date"] as! String == self.dataMessages[idx!]["chat_date"] as! String}).firstIndex(where: { $0["message_id"] as? String == self.dataMessages[idx!]["message_id"] as? String })
  1163. if row != nil && section != nil {
  1164. self.tableChatView.reloadRows(at: [IndexPath(row: row!, section: section!)], with: .none)
  1165. }
  1166. if self.reffId != nil && self.reffId! == messageId {
  1167. self.deleteReplyView()
  1168. }
  1169. }
  1170. }
  1171. }
  1172. }
  1173. }
  1174. }
  1175. @objc func onTyping(notification: NSNotification) {
  1176. DispatchQueue.main.async { [self] in
  1177. let data:[AnyHashable : Any] = notification.userInfo!
  1178. let message: TMessage = data["message"] as! TMessage
  1179. let onGoingCC = UserDefaults.standard.string(forKey: "onGoingCC") ?? ""
  1180. if !onGoingCC.isEmpty {
  1181. let officer = onGoingCC.isEmpty ? "" : onGoingCC.components(separatedBy: ",")[1]
  1182. if message.getBody(key: CoreMessage_TMessageKey.F_PIN) != officer {
  1183. // print("RESET TIMER")
  1184. // timeoutCC.invalidate()
  1185. // timeoutCC = Timer.scheduledTimer(withTimeInterval: 30.0, repeats: false, block: {_ in
  1186. // let imageView = UIImageView(image: UIImage(systemName: "info.circle"))
  1187. // imageView.tintColor = .white
  1188. // let banner = FloatingNotificationBanner(title: "Customer doesn't respond in 30 second, so call center session will be ended automatically.".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)
  1189. // banner.show()
  1190. // self.endCallCenter()
  1191. // })
  1192. }
  1193. } else {
  1194. }
  1195. }
  1196. }
  1197. @objc func onUnfriend(notification: NSNotification) {
  1198. let data:[AnyHashable : Any] = notification.userInfo!
  1199. DispatchQueue.main.async { [self] in
  1200. if data["state"] as! Int == 99 && (data["message"] as! String).components(separatedBy: ",")[0] == "delete_buddy" {
  1201. removed = true
  1202. navigationItem.rightBarButtonItem = nil
  1203. navigationItem.rightBarButtonItems = nil
  1204. changeAppBar()
  1205. view.addSubview(containerAction)
  1206. containerAction.translatesAutoresizingMaskIntoConstraints = false
  1207. NSLayoutConstraint.activate([
  1208. containerAction.leadingAnchor.constraint(equalTo: self.view.leadingAnchor),
  1209. containerAction.trailingAnchor.constraint(equalTo: self.view.trailingAnchor),
  1210. containerAction.bottomAnchor.constraint(equalTo: self.view.bottomAnchor),
  1211. containerAction.heightAnchor.constraint(equalToConstant: 120)
  1212. ])
  1213. containerAction.backgroundColor = .secondaryColor.withAlphaComponent(0.8)
  1214. let labelUnfriend = UILabel()
  1215. containerAction.addSubview(labelUnfriend)
  1216. labelUnfriend.translatesAutoresizingMaskIntoConstraints = false
  1217. NSLayoutConstraint.activate([
  1218. labelUnfriend.centerYAnchor.constraint(equalTo: containerAction.centerYAnchor),
  1219. labelUnfriend.centerXAnchor.constraint(equalTo: containerAction.centerXAnchor),
  1220. ])
  1221. labelUnfriend.textColor = .black
  1222. labelUnfriend.font = UIFont.systemFont(ofSize: 12).bold
  1223. labelUnfriend.text = "You have unfriended this user".localized()
  1224. NotificationCenter.default.post(name: NSNotification.Name(rawValue: "reloadTabChats"), object: nil, userInfo: nil)
  1225. } else if data["state"] as! Int == 01 {
  1226. if let dataMessage = try! JSONSerialization.jsonObject(with: (data["message"] as! String).data(using: .utf8)!, options: []) as? [String: String] {
  1227. if(dataMessage["l_pin"] == dataPerson["f_pin"]!){
  1228. if let block = dataMessage["block"] {
  1229. if(block == "-1"){
  1230. dismissKeyboard()
  1231. }
  1232. blockedView(blocked: block)
  1233. }
  1234. }
  1235. setRightButtonItem()
  1236. }
  1237. }
  1238. }
  1239. }
  1240. func blockedView(blocked: String) {
  1241. dismissKeyboard()
  1242. view.addSubview(containerAction)
  1243. containerAction.translatesAutoresizingMaskIntoConstraints = false
  1244. NSLayoutConstraint.activate([
  1245. containerAction.leadingAnchor.constraint(equalTo: self.view.leadingAnchor),
  1246. containerAction.trailingAnchor.constraint(equalTo: self.view.trailingAnchor),
  1247. containerAction.bottomAnchor.constraint(equalTo: self.view.bottomAnchor),
  1248. containerAction.heightAnchor.constraint(equalToConstant: 120)
  1249. ])
  1250. containerAction.backgroundColor = .secondaryColor.withAlphaComponent(0.8)
  1251. let labelBlocked = UILabel()
  1252. containerAction.addSubview(labelBlocked)
  1253. labelBlocked.translatesAutoresizingMaskIntoConstraints = false
  1254. NSLayoutConstraint.activate([
  1255. labelBlocked.centerYAnchor.constraint(equalTo: containerAction.centerYAnchor),
  1256. labelBlocked.centerXAnchor.constraint(equalTo: containerAction.centerXAnchor),
  1257. ])
  1258. labelBlocked.textColor = .black
  1259. labelBlocked.font = UIFont.systemFont(ofSize: 12).bold
  1260. if blocked == "1" {
  1261. labelBlocked.text = "You blocked this user".localized()
  1262. } else {
  1263. labelBlocked.text = "You have been blocked by this user".localized()
  1264. }
  1265. }
  1266. @objc func seeProfileTapped() {
  1267. if dataPerson["f_pin"] == "-999" || dataPerson["isOfficial"] == "1" || removed || copySession || forwardSession || deleteSession || isContactCenter {
  1268. return
  1269. }
  1270. dismissKeyboard()
  1271. let controller = AppStoryBoard.Palio.instance.instantiateViewController(withIdentifier: "profileView") as! ProfileViewController
  1272. controller.data = dataPerson["f_pin"]!!
  1273. controller.checkReadMessage = {
  1274. if self.currentIndexpath == nil {
  1275. var listData = self.dataMessages
  1276. listData = listData.filter({$0["status"] as! String != "4" && $0["status"] as! String != "8"})
  1277. if listData.count != 0 && !self.isContactCenter {
  1278. let idMe = UserDefaults.standard.string(forKey: "me") as String?
  1279. for i in 0...listData.count - 1 {
  1280. if listData[i]["f_pin"] as? String != idMe {
  1281. self.sendReadMessageStatus(chat_id: "", f_pin: self.dataPerson["f_pin"]!!, message_scope_id: "3", message_id: listData[i]["message_id"] as! String)
  1282. }
  1283. }
  1284. }
  1285. } else {
  1286. let dataMessages = self.dataMessages.filter({ $0["chat_date"] as! String == self.dataDates[self.currentIndexpath!.section] })
  1287. var listData = dataMessages
  1288. listData = listData.filter({$0["status"] as! String != "4" && $0["status"] as! String != "8"})
  1289. if listData.count != 0 && !self.isContactCenter {
  1290. let idMe = UserDefaults.standard.string(forKey: "me") as String?
  1291. for i in 0...listData.count - 1 {
  1292. if listData[i]["f_pin"] as? String != idMe {
  1293. self.sendReadMessageStatus(chat_id: "", f_pin: self.dataPerson["f_pin"]!!, message_scope_id: "3", message_id: listData[i]["message_id"] as! String)
  1294. }
  1295. }
  1296. }
  1297. }
  1298. }
  1299. navigationController?.show(controller, sender: nil)
  1300. }
  1301. @IBAction func voiceTapped(_ sender: UIButton) {
  1302. if (self.constraintBottomAttachment.constant != 0.0) {
  1303. constraintBottomAttachment.constant = 0.0
  1304. self.viewSticker.removeConstraints(self.viewSticker.constraints)
  1305. self.viewSticker.removeFromSuperview()
  1306. }
  1307. }
  1308. @IBAction func imageTapped(_ sender: UIButton) {
  1309. if (self.constraintBottomAttachment.constant != 0.0) {
  1310. constraintBottomAttachment.constant = 0.0
  1311. self.viewSticker.removeConstraints(self.viewSticker.constraints)
  1312. self.viewSticker.removeFromSuperview()
  1313. }
  1314. if isContactCenter && fPinContacCenter.isEmpty && isRequestContactCenter {
  1315. return
  1316. }
  1317. let alertController = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
  1318. if let action = self.actionImageVideo(for: "image", title: "Choose Photo".localized()) {
  1319. alertController.addAction(action)
  1320. }
  1321. if let action = self.actionImageVideo(for: "video", title: "Choose Video".localized()) {
  1322. alertController.addAction(action)
  1323. }
  1324. alertController.addAction(UIAlertAction(title: "Cancel".localized(), style: .cancel, handler: nil))
  1325. self.present(alertController, animated: true)
  1326. }
  1327. private func actionImageVideo(for type: String, title: String) -> UIAlertAction? {
  1328. return UIAlertAction(title: title, style: .default) { [unowned self] _ in
  1329. switch type {
  1330. case "image":
  1331. imageVideoPicker.present(source: .imageAlbum)
  1332. case "video":
  1333. imageVideoPicker.present(source: .videoAlbum)
  1334. case "imageCamera":
  1335. imageVideoPicker.present(source: .imageCamera)
  1336. case "videoCamera":
  1337. imageVideoPicker.present(source: .videoCamera)
  1338. default:
  1339. imageVideoPicker.present(source: .imageAlbum)
  1340. }
  1341. }
  1342. }
  1343. @IBAction func photoTapped(_ sender: UIButton) {
  1344. if (self.constraintBottomAttachment.constant != 0.0) {
  1345. constraintBottomAttachment.constant = 0.0
  1346. self.viewSticker.removeConstraints(self.viewSticker.constraints)
  1347. self.viewSticker.removeFromSuperview()
  1348. }
  1349. if isContactCenter && fPinContacCenter.isEmpty && isRequestContactCenter {
  1350. return
  1351. }
  1352. let alertController = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
  1353. if let action = self.actionImageVideo(for: "imageCamera", title: "Take Photo".localized()) {
  1354. alertController.addAction(action)
  1355. }
  1356. if let action = self.actionImageVideo(for: "videoCamera", title: "Take Video".localized()) {
  1357. alertController.addAction(action)
  1358. }
  1359. alertController.addAction(UIAlertAction(title: "Cancel".localized(), style: .cancel, handler: nil))
  1360. self.present(alertController, animated: true)
  1361. }
  1362. @IBAction func stickerTapped(_ sender: UIButton) {
  1363. if isContactCenter && fPinContacCenter.isEmpty && isRequestContactCenter {
  1364. return
  1365. }
  1366. DispatchQueue.main.async {
  1367. if (self.constraintBottomAttachment.constant == 0.0) {
  1368. self.constraintBottomAttachment.constant = 200.0
  1369. self.view.addSubview(self.viewSticker)
  1370. self.viewSticker.translatesAutoresizingMaskIntoConstraints = false
  1371. NSLayoutConstraint.activate([
  1372. self.viewSticker.bottomAnchor.constraint(equalTo: self.view.bottomAnchor),
  1373. self.viewSticker.leadingAnchor.constraint(equalTo: self.view.leadingAnchor),
  1374. self.viewSticker.trailingAnchor.constraint(equalTo: self.view.trailingAnchor),
  1375. self.viewSticker.heightAnchor.constraint(equalToConstant: 200)
  1376. ])
  1377. let layout = UICollectionViewFlowLayout()
  1378. layout.scrollDirection = .vertical
  1379. let collectionSticker = UICollectionView(frame: .zero, collectionViewLayout: layout)
  1380. collectionSticker.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "cellSticker")
  1381. collectionSticker.delegate = self
  1382. collectionSticker.dataSource = self
  1383. collectionSticker.backgroundColor = .clear
  1384. self.viewSticker.addSubview(collectionSticker)
  1385. collectionSticker.translatesAutoresizingMaskIntoConstraints = false
  1386. NSLayoutConstraint.activate([
  1387. collectionSticker.topAnchor.constraint(equalTo: self.viewSticker.topAnchor, constant: 20),
  1388. collectionSticker.bottomAnchor.constraint(equalTo: self.viewSticker.bottomAnchor, constant: -20),
  1389. collectionSticker.leadingAnchor.constraint(equalTo: self.viewSticker.leadingAnchor, constant: 20),
  1390. collectionSticker.trailingAnchor.constraint(equalTo: self.viewSticker.trailingAnchor, constant: -20)
  1391. ])
  1392. if (self.currentIndexpath != nil) {
  1393. DispatchQueue.main.async {
  1394. self.tableChatView.scrollToRow(at: IndexPath(row: self.currentIndexpath!.row, section: self.currentIndexpath!.section), at: .none, animated: false)
  1395. }
  1396. } else {
  1397. self.tableChatView.scrollToBottom()
  1398. }
  1399. } else {
  1400. self.constraintBottomAttachment.constant = 0.0
  1401. self.viewSticker.removeConstraints(self.viewSticker.constraints)
  1402. self.viewSticker.removeFromSuperview()
  1403. }
  1404. }
  1405. }
  1406. @IBAction func fileTapped(_ sender: UIButton) {
  1407. if isContactCenter && fPinContacCenter.isEmpty && isRequestContactCenter {
  1408. return
  1409. }
  1410. if (self.constraintBottomAttachment.constant != 0.0) {
  1411. constraintBottomAttachment.constant = 0.0
  1412. self.viewSticker.removeConstraints(self.viewSticker.constraints)
  1413. self.viewSticker.removeFromSuperview()
  1414. }
  1415. documentPicker.present()
  1416. }
  1417. @objc func sendTapped() {
  1418. sendChat(message_text: textFieldSend.text!, viewController: self)
  1419. }
  1420. @objc func addRoom(sender: UIBarButtonItem) {
  1421. let controller = QmeraCallContactViewController()
  1422. controller.isDismiss = { user in
  1423. DispatchQueue.global().async {
  1424. _ = Nexilis.write(message: CoreMessage_TMessageBank.getCCRoomInvite(l_pin: user.pin, ticket_id: self.complaintId, channel: self.channelContactCenter))
  1425. }
  1426. }
  1427. controller.selectedUser.append(contentsOf: users)
  1428. controller.isInviteCC = true
  1429. self.navigationController?.show(controller, sender: nil)
  1430. }
  1431. @objc func audioVideoCall(sender: UIBarButtonItem) {
  1432. if sender.tag == 0 {
  1433. if let pin = dataPerson["f_pin"] {
  1434. let controller = QmeraAudioViewController()
  1435. controller.user = User.getData(pin: pin)
  1436. controller.isOutgoing = true
  1437. controller.modalPresentationStyle = .overCurrentContext
  1438. present(controller, animated: true, completion: nil)
  1439. }
  1440. } else {
  1441. let videoVC = AppStoryBoard.Palio.instance.instantiateViewController(withIdentifier: "videoVCQmera") as! QmeraVideoViewController
  1442. videoVC.dataPerson.append(dataPerson)
  1443. self.show(videoVC, sender: nil)
  1444. }
  1445. }
  1446. @objc func dismissKeyboard() {
  1447. textFieldSend.resignFirstResponder() // dismiss keyoard
  1448. if (self.constraintBottomAttachment.constant != 0.0) {
  1449. constraintBottomAttachment.constant = 0.0
  1450. self.viewSticker.removeConstraints(self.viewSticker.constraints)
  1451. self.viewSticker.removeFromSuperview()
  1452. }
  1453. }
  1454. @objc func didTapExit() {
  1455. if complaintId.isEmpty {
  1456. self.timeoutCC.invalidate()
  1457. UserDefaults.standard.removeObject(forKey: "inEditorPersonal")
  1458. NotificationCenter.default.removeObserver(self)
  1459. NotificationCenter.default.post(name: NSNotification.Name(rawValue: "refreshView"), object: nil, userInfo: nil)
  1460. self.dismiss(animated: true, completion: nil)
  1461. } else if !complaintId.isEmpty {
  1462. let alert = UIAlertController(title: "Interaction with Call Center is in progress".localized(), message: "Are you sure you want to end the Call Center?".localized(), preferredStyle: .alert)
  1463. alert.addAction(UIAlertAction(title: "No".localized(), style: UIAlertAction.Style.default, handler: nil))
  1464. alert.addAction(UIAlertAction(title: "Yes".localized(), style: UIAlertAction.Style.default, handler: {(_) in
  1465. self.endCallCenter()
  1466. }))
  1467. self.present(alert, animated: true, completion: nil)
  1468. }
  1469. }
  1470. public func endCallCenter() {
  1471. timeoutCC.invalidate()
  1472. let complaintId = self.complaintId
  1473. let idMe = UserDefaults.standard.string(forKey: "me")!
  1474. let onGoingCC = UserDefaults.standard.string(forKey: "onGoingCC") ?? ""
  1475. let requester = onGoingCC.components(separatedBy: ",")[0]
  1476. let officer = onGoingCC.isEmpty ? "" : onGoingCC.components(separatedBy: ",")[1]
  1477. DispatchQueue.global().async {
  1478. let date = "\(Date().currentTimeMillis())"
  1479. Database.shared.database?.inTransaction({ (fmdb, rollback) in
  1480. do {
  1481. _ = try Database.shared.insertRecord(fmdb: fmdb, table: "CALL_CENTER_HISTORY", cvalues: [
  1482. "type" : self.channelContactCenter,
  1483. "title" : "Contact Center".localized(),
  1484. "time" : self.dateStartCC,
  1485. "f_pin" : officer,
  1486. "data" : self.complaintId,
  1487. "time_end" : date,
  1488. "complaint_id" : self.complaintId,
  1489. "members" : "",
  1490. "requester": requester
  1491. ], replace: true)
  1492. } catch {
  1493. rollback.pointee = true
  1494. print(error)
  1495. }
  1496. })
  1497. if officer == idMe {
  1498. _ = Nexilis.write(message: CoreMessage_TMessageBank.endCallCenter(complaint_id: complaintId, l_pin: requester))
  1499. } else {
  1500. if requester == idMe {
  1501. _ = Nexilis.write(message: CoreMessage_TMessageBank.endCallCenter(complaint_id: complaintId, l_pin: officer))
  1502. } else {
  1503. _ = Nexilis.write(message: CoreMessage_TMessageBank.leaveCCRoomInvite(ticket_id: complaintId))
  1504. }
  1505. }
  1506. UserDefaults.standard.removeObject(forKey: "onGoingCC")
  1507. UserDefaults.standard.removeObject(forKey: "membersCC")
  1508. UserDefaults.standard.removeObject(forKey: "waitingRequestCC")
  1509. }
  1510. self.dismiss(animated: true, completion: nil)
  1511. }
  1512. @objc func keyboardWillHide(notification: NSNotification) {
  1513. if self.viewIfLoaded?.window != nil {
  1514. let info:NSDictionary = notification.userInfo! as NSDictionary
  1515. let duration: CGFloat = info[UIResponder.keyboardAnimationDurationUserInfoKey] as! NSNumber as! CGFloat
  1516. self.constraintViewTextField.constant = 0
  1517. UIView.animate(withDuration: TimeInterval(duration), animations: {
  1518. self.view.layoutIfNeeded()
  1519. })
  1520. }
  1521. }
  1522. @objc func keyboardWillShow(notification: NSNotification) {
  1523. if self.viewIfLoaded?.window != nil {
  1524. if (self.constraintBottomAttachment.constant != 0.0) {
  1525. self.constraintBottomAttachment.constant = 0.0
  1526. self.viewSticker.removeConstraints(self.viewSticker.constraints)
  1527. self.viewSticker.removeFromSuperview()
  1528. }
  1529. let info:NSDictionary = notification.userInfo! as NSDictionary
  1530. let keyboardSize = (info[UIResponder.keyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
  1531. let keyboardHeight: CGFloat = keyboardSize.height
  1532. let duration: CGFloat = info[UIResponder.keyboardAnimationDurationUserInfoKey] as! NSNumber as! CGFloat
  1533. if self.constraintViewTextField.constant != keyboardHeight - 60 {
  1534. self.constraintViewTextField.constant = keyboardHeight - 60
  1535. UIView.animate(withDuration: TimeInterval(duration), animations: {
  1536. self.view.layoutIfNeeded()
  1537. })
  1538. if (self.currentIndexpath != nil) {
  1539. self.tableChatView.scrollToRow(at: IndexPath(row: self.currentIndexpath!.row, section: self.currentIndexpath!.section), at: .none, animated: false)
  1540. } else {
  1541. self.tableChatView.scrollToBottom()
  1542. }
  1543. }
  1544. }
  1545. }
  1546. private func sendChat(message_scope_id:String = "3", status:String = "2", message_text:String = "", credential:String = "0", attachment_flag: String = "0", ex_blog_id: String = "", message_large_text: String = "", ex_format: String = "", image_id: String = "", audio_id: String = "", video_id: String = "", file_id: String = "", thumb_id: String = "", reff_id: String = "", read_receipts: String = "", chat_id: String = "", is_call_center: String = "0", call_center_id: String = "", viewController: UIViewController, isAutoSendCC : Bool = false) {
  1547. if viewController is EditorPersonal && file_id == "" && dataMessageForward == nil && !isAutoSendCC{
  1548. if ((textFieldSend.text!.trimmingCharacters(in: .whitespacesAndNewlines) == "Send message".localized() && textFieldSend.textColor == UIColor.lightGray && attachment_flag != "11") || textFieldSend.text!.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty ) {
  1549. dismissKeyboard()
  1550. viewController.showToast(message: "Type Messages".localized(), font: UIFont.systemFont(ofSize: 12, weight: .medium), controller: self)
  1551. if (textFieldSend.text!.trimmingCharacters(in: .whitespacesAndNewlines) != "Send message".localized()) {
  1552. textFieldSend.text = ""
  1553. }
  1554. if (self.heightTextFieldSend.constant != 40) {
  1555. self.heightTextFieldSend.constant = 40
  1556. }
  1557. return
  1558. }
  1559. }
  1560. var reff_id = reff_id
  1561. if (reffId != nil) {
  1562. reff_id = reffId!
  1563. }
  1564. var is_call_center = is_call_center
  1565. var call_center_id = call_center_id
  1566. var l_pin = dataPerson["f_pin"]!!
  1567. var message_scope_id = message_scope_id
  1568. if (isContactCenter) {
  1569. if fPinContacCenter.isEmpty && isRequestContactCenter {
  1570. if textFieldSend.text!.trimmingCharacters(in: .whitespacesAndNewlines) != "Send message".localized() && textFieldSend.textColor != UIColor.lightGray && constraintViewTextField.constant == 0 {
  1571. textFieldSend.text = "Send message".localized()
  1572. textFieldSend.textColor = UIColor.lightGray
  1573. } else if constraintViewTextField.constant != 0 {
  1574. textFieldSend.text = ""
  1575. }
  1576. dismissKeyboard()
  1577. viewController.showToast(message: "Unable to send message. Waiting for the officer to accept your request".localized(), font: UIFont.systemFont(ofSize: 12, weight: .medium), controller: self)
  1578. return
  1579. }
  1580. is_call_center = "1"
  1581. call_center_id = complaintId
  1582. l_pin = fPinContacCenter
  1583. message_scope_id = "5"
  1584. if isAutoSendCC {
  1585. timeoutCC = Timer.scheduledTimer(withTimeInterval: 30.0, repeats: false, block: {_ in
  1586. let imageView = UIImageView(image: UIImage(systemName: "info.circle"))
  1587. imageView.tintColor = .white
  1588. let banner = FloatingNotificationBanner(title: "Customer doesn't respond in 30 second, so call center session will be ended automatically.".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)
  1589. banner.show()
  1590. self.endCallCenter()
  1591. })
  1592. }
  1593. }
  1594. let message_text = message_text.trimmingCharacters(in: .whitespacesAndNewlines)
  1595. let idMe = UserDefaults.standard.string(forKey: "me") as String?
  1596. var opposite_pin = ""
  1597. if isContactCenter {
  1598. opposite_pin = fPinContacCenter
  1599. }
  1600. sendTyping(l_pin: l_pin, isTyping: true)
  1601. let message = CoreMessage_TMessageBank.sendMessage(l_pin: l_pin, message_scope_id: message_scope_id, status: status, message_text: message_text, credential: credential, attachment_flag: attachment_flag, ex_blog_id: ex_blog_id, message_large_text: message_large_text, ex_format: ex_format, image_id: image_id, audio_id: audio_id, video_id: video_id, file_id: file_id, thumb_id: thumb_id, reff_id: reff_id, read_receipts: read_receipts, chat_id: chat_id, is_call_center: is_call_center, call_center_id: call_center_id, opposite_pin: opposite_pin)
  1602. Nexilis.addQueueMessage(message: message)
  1603. let messageId = String(message.mBodies[CoreMessage_TMessageKey.MESSAGE_ID]!)
  1604. var row: [String: Any?] = [:]
  1605. row["message_id"] = messageId
  1606. row["f_pin"] = idMe
  1607. row["l_pin"] = dataPerson["f_pin"]!!
  1608. row["message_scope_id"] = message_scope_id
  1609. row["server_date"] = "\(Date().millisecondsSince1970)"
  1610. row["status"] = status
  1611. row["message_text"] = message_text
  1612. row["audio_id"] = audio_id
  1613. row["video_id"] = video_id
  1614. row["image_id"] = image_id
  1615. row["thumb_id"] = thumb_id
  1616. row["read_receipts"] = 0
  1617. row["chat_id"] = chat_id
  1618. row["file_id"] = file_id
  1619. row["attachment_flag"] = attachment_flag
  1620. row["reff_id"] = reff_id
  1621. row["progress"] = 0.0
  1622. row["lock"] = "0"
  1623. row["is_stared"] = "0"
  1624. row["isSelected"] = false
  1625. if !dataDates.contains("Today".localized()) {
  1626. dataDates.append("Today".localized())
  1627. tableChatView.insertSections(IndexSet(integer: dataDates.count - 1), with: .none)
  1628. }
  1629. row["chat_date"] = "Today".localized()
  1630. dataMessages.append(row)
  1631. tableChatView.insertRows(at: [IndexPath(row: dataMessages.filter({ $0["chat_date"] as! String == dataDates[dataDates.count - 1]}).count - 1, section: dataDates.count - 1)], with: .none)
  1632. if textFieldSend.text!.trimmingCharacters(in: .whitespacesAndNewlines) != "Send message".localized() && textFieldSend.textColor != UIColor.lightGray && constraintViewTextField.constant == 0 {
  1633. textFieldSend.text = "Send message".localized()
  1634. textFieldSend.textColor = UIColor.lightGray
  1635. } else if constraintViewTextField.constant != 0 {
  1636. textFieldSend.text = ""
  1637. heightTextFieldSend.constant = 40
  1638. }
  1639. deleteReplyView()
  1640. deleteLinkPreview()
  1641. DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) {
  1642. self.tableChatView.scrollToBottom()
  1643. if self.markerCounter != nil {
  1644. self.markerCounter = nil
  1645. self.tableChatView.reloadData()
  1646. }
  1647. }
  1648. }
  1649. @objc func ccAction(sender: UIButton) {
  1650. if self.nowSelectedCategoryCC == "CantReturn" {
  1651. if sender.tag == 503 {
  1652. self.showToast(message: "You can't request Call Center more than one".localized(), font: UIFont.systemFont(ofSize: 12, weight: .medium), controller: self)
  1653. } else if sender.tag == 504 {
  1654. busyCCAction(sender: sender)
  1655. }
  1656. return
  1657. }
  1658. if self.nowSelectedCategoryCC == "endCC" {
  1659. return
  1660. }
  1661. let id = sender.restorationIdentifier?.components(separatedBy: ",")[0]
  1662. let service_id = sender.restorationIdentifier?.components(separatedBy: ",")[1]
  1663. let level = id!.substring(from: 5, to: 5)
  1664. let levelNow = self.nowSelectedCategoryCC.substring(from: 5, to: 5)
  1665. var isRequest = false
  1666. var channel = 0
  1667. var row: [String: Any?] = [:]
  1668. if nowSelectedCategoryCC.isEmpty || level > levelNow {
  1669. row["message_id"] = ""
  1670. row["chat_date"] = "Today".localized()
  1671. let dataChat: [CategoryCC] = CategoryCC.getDatafromParent(parent: service_id!)
  1672. if dataChat.count != 0 {
  1673. var data : [CategoryCC] = []
  1674. for i in 0..<dataChat.count {
  1675. data.append(CategoryCC(id: "level\(Int(level)! + 1)_\(i)", service_id: dataChat[i].service_id, service_name: dataChat[i].service_name, parent: id!, description: dataChat[i].description, is_tablet: dataChat[i].is_tablet))
  1676. }
  1677. row["category_cc"] = data
  1678. } else if dataMessages[Int(level)!]["attachment_flag"] == nil {
  1679. let listStringName: [String] = ["Informasi Umum Produk Call 1500046", "Informasi Spesifik Produk"]
  1680. var data : [CategoryCC] = []
  1681. for i in 0..<listStringName.count {
  1682. data.append(CategoryCC(id: "level\(Int(level)! + 1)_\(i)", service_id: service_id!, service_name: listStringName[i], parent: id!, description: "", is_tablet: "0"))
  1683. }
  1684. row["category_cc"] = data
  1685. row["attachment_flag"] = "502"
  1686. } else if dataMessages[Int(level)!]["attachment_flag"] != nil && dataMessages[Int(level)!]["attachment_flag"] as! String == "502" {
  1687. if id == "level\(Int(level)!)_0" {
  1688. if let url = URL(string: "tel://1500046") {
  1689. UIApplication.shared.open(url)
  1690. }
  1691. return
  1692. } else {
  1693. let listStringName: [String] = ["Chat with a Representative", "Video Call a Representative", "Call a Representative"]
  1694. var data : [CategoryCC] = []
  1695. for i in 0..<listStringName.count {
  1696. data.append(CategoryCC(id: "level\(Int(level)! + 1)_\(i)", service_id: service_id!, service_name: listStringName[i], parent: id!, description: "", is_tablet: "0"))
  1697. }
  1698. row["category_cc"] = data
  1699. row["attachment_flag"] = "503"
  1700. }
  1701. } else {
  1702. if id == "level\(Int(level)!)_1" {
  1703. channel = 2
  1704. } else if id == "level\(Int(level)!)_2" {
  1705. channel = 1
  1706. }
  1707. if channel == 1 || channel == 2 {
  1708. if channel == 2 {
  1709. let goAudioCall = Nexilis.checkMicPermission()
  1710. let goVideoCall = Nexilis.checkCameraPermission()
  1711. if goVideoCall == 0 {
  1712. let alert = UIAlertController(title: "Attention!".localized(), message: !goAudioCall && goVideoCall == 0 && channel == 2 ? "Please allow microphone & camera permission in your settings".localized() : !goAudioCall ? "Please allow microphone permission in your settings".localized() : "Please allow camera permission in your settings", preferredStyle: .alert)
  1713. alert.addAction(UIAlertAction(title: "OK".localized(), style: UIAlertAction.Style.default, handler: {_ in
  1714. if let url = URL(string: UIApplication.openSettingsURLString), UIApplication.shared.canOpenURL(url) {
  1715. UIApplication.shared.open(url, options: [:], completionHandler: nil)
  1716. }
  1717. }))
  1718. self.navigationController?.present(alert, animated: true, completion: nil)
  1719. return
  1720. } else if goVideoCall == -1 {
  1721. return
  1722. }
  1723. } else if channel == 1 {
  1724. let goAudioCall = Nexilis.checkMicPermission()
  1725. if !goAudioCall{
  1726. let alert = UIAlertController(title: "Attention!".localized(), message: "Please allow microphone permission in your settings".localized(), preferredStyle: .alert)
  1727. alert.addAction(UIAlertAction(title: "OK".localized(), style: UIAlertAction.Style.default, handler: {_ in
  1728. if let url = URL(string: UIApplication.openSettingsURLString), UIApplication.shared.canOpenURL(url) {
  1729. UIApplication.shared.open(url, options: [:], completionHandler: nil)
  1730. }
  1731. }))
  1732. self.navigationController?.present(alert, animated: true, completion: nil)
  1733. return
  1734. }
  1735. }
  1736. }
  1737. row["category_cc"] = "Please wait while we connect you\nto one of our service representatives".localized()
  1738. isRequest = true
  1739. }
  1740. if dataMessages[Int(level)!]["attachment_flag"] == nil || dataMessages[Int(level)!]["attachment_flag"] as! String != "503" {
  1741. dataMessages.append(row)
  1742. self.nowSelectedCategoryCC = id!
  1743. tableChatView.insertRows(at: [IndexPath(row: dataMessages.count - 1, section: 0)], with: .none)
  1744. }
  1745. } else {
  1746. if id == self.nowSelectedCategoryCC {
  1747. if level == "0" {
  1748. self.nowSelectedCategoryCC = ""
  1749. } else {
  1750. let categoryCC = dataMessages[dataMessages.count - 2]["category_cc"] as! [CategoryCC]
  1751. self.nowSelectedCategoryCC = categoryCC[0].parent
  1752. }
  1753. tableChatView.beginUpdates()
  1754. tableChatView.deleteRows(at: [IndexPath(row: dataMessages.count - 1, section: 0)], with: .none)
  1755. dataMessages.remove(at: dataMessages.count - 1)
  1756. tableChatView.endUpdates()
  1757. } else {
  1758. return
  1759. }
  1760. }
  1761. // if sender.backgroundColor != .orangeBNI {
  1762. // var button = dataMessages[dataMessages.count - 2]["category_cc"] as! [CategoryCC]
  1763. // if dataMessages[Int(level)!]["attachment_flag"] != nil && dataMessages[Int(level)!]["attachment_flag"] as! String == "503" {
  1764. // button = dataMessages[dataMessages.count - 1]["category_cc"] as! [CategoryCC]
  1765. // }
  1766. // for i in button {
  1767. // if i.id == id! {
  1768. // i.isActive = true
  1769. // break
  1770. // }
  1771. // }
  1772. // sender.backgroundColor = .orangeBNI
  1773. // dataMessages[dataMessages.count - 2]["category_cc"] = button
  1774. // } else {
  1775. // let button = dataMessages[dataMessages.count - 1]["category_cc"] as! [CategoryCC]
  1776. // for i in button {
  1777. // if i.id == id! {
  1778. // i.isActive = false
  1779. // break
  1780. // }
  1781. // }
  1782. // sender.backgroundColor = .clear
  1783. // dataMessages[dataMessages.count - 1]["category_cc"] = button
  1784. // }
  1785. if isRequest {
  1786. requestContactCenter(channel: channel, service_id: service_id!, row: row)
  1787. } else {
  1788. self.tableChatView.scrollToBottom()
  1789. }
  1790. }
  1791. @objc func busyCCAction(sender: UIButton) {
  1792. let id = sender.restorationIdentifier?.components(separatedBy: ",")[0]
  1793. let service_id = sender.restorationIdentifier?.components(separatedBy: ",")[1]
  1794. let level = id!.substring(from: 5, to: 5)
  1795. var row: [String: Any?] = [:]
  1796. if id == "level\(Int(level)!)_0" {
  1797. UserDefaults.standard.set(true, forKey: "waitingRequestCC")
  1798. DispatchQueue.global().async {
  1799. let message = CoreMessage_TMessageBank.getQueuingCallCenter(p_channel: Int(self.channelContactCenter)!)
  1800. message.mBodies[CoreMessage_TMessageKey.CATEGORY_ID] = "\(service_id!)"
  1801. _ = Nexilis.writeSync(message: message, timeout: 30 * 1000)
  1802. }
  1803. row["category_cc"] = "Thank you for contacting us,\none of our officers will contact you soon".localized()
  1804. } else {
  1805. row["category_cc"] = "Thank you for being awesome,\nhave a great day!".localized()
  1806. }
  1807. row["message_id"] = ""
  1808. row["chat_date"] = "Today".localized()
  1809. self.nowSelectedCategoryCC = "endCC"
  1810. dataMessages.append(row)
  1811. tableChatView.insertRows(at: [IndexPath(row: Int(level)!, section: 0)], with: .none)
  1812. self.tableChatView.scrollToBottom()
  1813. // DispatchQueue.main.asyncAfter(deadline: .now() + 2, execute: {
  1814. // self.dismiss(animated: true)
  1815. // })
  1816. }
  1817. func requestContactCenter(channel: Int, service_id: String, row: [String: Any?]) {
  1818. if !CheckConnection.isConnectedToNetwork() || API.nGetCLXConnState() == 0 {
  1819. let imageView = UIImageView(image: UIImage(systemName: "xmark.circle.fill"))
  1820. imageView.tintColor = .white
  1821. let banner = FloatingNotificationBanner(title: "Check your connection".localized(), subtitle: nil, titleFont: UIFont.systemFont(ofSize: 16), titleColor: nil, titleTextAlign: .left, subtitleFont: nil, subtitleColor: nil, subtitleTextAlign: nil, leftView: imageView, rightView: nil, style: .danger, colors: nil, iconPosition: .center)
  1822. banner.show()
  1823. return
  1824. }
  1825. DispatchQueue.global().async {
  1826. let message = CoreMessage_TMessageBank.getRequestCallCenter(p_channel: channel)
  1827. if let response = Nexilis.writeSync(message: message) {
  1828. DispatchQueue.main.async {
  1829. self.dataMessages.append(row)
  1830. self.nowSelectedCategoryCC = "CantReturn"
  1831. self.tableChatView.insertRows(at: [IndexPath(row: self.dataMessages.count - 1, section: 0)], with: .none)
  1832. self.tableChatView.scrollToBottom()
  1833. }
  1834. if (response.getBody(key: CoreMessage_TMessageKey.ERRCOD, default_value: "99") == "00") {
  1835. DispatchQueue.main.async {
  1836. UserDefaults.standard.set(true, forKey: "waitingRequestCC")
  1837. let data = response.getBody(key: CoreMessage_TMessageKey.DATA, default_value: "")
  1838. if data.isEmpty {
  1839. UserDefaults.standard.removeObject(forKey: "waitingRequestCC")
  1840. var row: [String: Any?] = [:]
  1841. row["message_id"] = ""
  1842. row["chat_date"] = "Today".localized()
  1843. row["attachment_flag"] = "504"
  1844. let listStringName: [String] = ["Yes", "No"]
  1845. var data : [CategoryCC] = []
  1846. for i in 0..<listStringName.count {
  1847. data.append(CategoryCC(id: "level\(self.dataMessages.count + 1)_\(i)", service_id: service_id, service_name: listStringName[i], parent: "", description: "", is_tablet: "0"))
  1848. }
  1849. row["category_cc"] = data
  1850. self.dataMessages.append(row)
  1851. self.channelContactCenter = "\(channel)"
  1852. self.tableChatView.insertRows(at: [IndexPath(row: self.dataMessages.count - 1, section: 0)], with: .none)
  1853. self.tableChatView.scrollToBottom()
  1854. } else {
  1855. self.fPinContacCenter = data
  1856. }
  1857. }
  1858. }
  1859. }
  1860. }
  1861. }
  1862. private func sendReadMessageStatus(chat_id: String, f_pin: String, message_scope_id: String, message_id: String) {
  1863. let message = CoreMessage_TMessageBank.getUpdateRead(p_chat_id: chat_id, p_f_pin: f_pin, p_scope_id: message_scope_id, qty: 1)
  1864. let fPin = message.getBody(key: CoreMessage_TMessageKey.F_PIN)
  1865. let scope = message.getBody(key: CoreMessage_TMessageKey.SCOPE_ID)
  1866. message.mBodies[CoreMessage_TMessageKey.SERVER_DATE] = String(Date().currentTimeMillis())
  1867. if (fPin.elementsEqual("-999") || scope.elementsEqual("16") || scope.elementsEqual("15")){
  1868. return
  1869. }
  1870. DispatchQueue.global().async {
  1871. Database.shared.database?.inTransaction({ (fmdb, rollback) in
  1872. _ = Database.shared.updateRecord(fmdb: fmdb, table: "MESSAGE", cvalues: [
  1873. "status" : "4"
  1874. ], _where: "message_id = '\(message_id)'")
  1875. })
  1876. message.mStatus = CoreMessage_TMessageUtil.getTID()
  1877. message.mBodies[CoreMessage_TMessageKey.L_PIN] = f_pin
  1878. message.mBodies[CoreMessage_TMessageKey.MESSAGE_ID] = "-2,\(message_id)"
  1879. _ = Nexilis.write(message: message)
  1880. }
  1881. if let index = dataMessages.firstIndex(where: {$0["message_id"] as? String == message_id}) {
  1882. dataMessages[index]["status"] = "4"
  1883. let auto = UserDefaults.standard.bool(forKey: "autoDownload")
  1884. if auto {
  1885. if dataMessages[index]["image_id"] as? String != nil && !((dataMessages[index]["image_id"] as? String)!.isEmpty) {
  1886. Download().start(forKey:dataMessages[index]["image_id"] as! String) { (name, progress) in
  1887. guard progress == 100 else {
  1888. return
  1889. }
  1890. let nsDocumentDirectory = FileManager.SearchPathDirectory.documentDirectory
  1891. let nsUserDomainMask = FileManager.SearchPathDomainMask.userDomainMask
  1892. let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true)
  1893. if let dirPath = paths.first {
  1894. let imageURL = URL(fileURLWithPath: dirPath).appendingPathComponent(self.dataMessages[index]["image_id"] as! String)
  1895. let image = UIImage(contentsOfFile: imageURL.path)
  1896. let save = UserDefaults.standard.bool(forKey: "saveToGallery")
  1897. if save {
  1898. UIImageWriteToSavedPhotosAlbum(image!, nil, nil, nil)
  1899. }
  1900. }
  1901. DispatchQueue.main.async { [self] in
  1902. let section = dataDates.firstIndex(of: dataMessages[index]["chat_date"] as! String)
  1903. let row = dataMessages.filter({$0["chat_date"] as! String == dataMessages[index]["chat_date"] as! String}).firstIndex(where: { $0["message_id"] as? String == message_id})
  1904. if row != nil && section != nil{
  1905. tableChatView.reloadRows(at: [IndexPath(row: row!, section: section!)], with: .none)
  1906. }
  1907. }
  1908. }
  1909. } else if dataMessages[index]["video_id"] as? String != nil && !((dataMessages[index]["video_id"] as? String)!.isEmpty){
  1910. let section = dataDates.firstIndex(of: dataMessages[index]["chat_date"] as! String)
  1911. let row = dataMessages.filter({$0["chat_date"] as! String == dataMessages[index]["chat_date"] as! String}).firstIndex(where: { $0["message_id"] as? String == message_id})
  1912. if row != nil && section != nil{
  1913. let indexPath = IndexPath(row: row!, section: section!)
  1914. if let cell = tableChatView.cellForRow(at: indexPath) {
  1915. for view in cell.contentView.subviews {
  1916. if view is UIImageView{
  1917. let objectTap = ObjectGesture()
  1918. objectTap.video_id = dataMessages[index]["video_id"] as! String
  1919. objectTap.imageView = view as! UIImageView
  1920. objectTap.indexPath = indexPath
  1921. contentMessageTapped(objectTap)
  1922. break
  1923. }
  1924. }
  1925. }
  1926. }
  1927. }
  1928. }
  1929. }
  1930. }
  1931. private func sendTyping(l_pin: String, isTyping: Bool = false) {
  1932. DispatchQueue.global().async {
  1933. let tmessage = CoreMessage_TMessageBank.getUpdateTypingStatus(p_opposite: l_pin, p_scope: "3", p_status: isTyping ? "3": "4")
  1934. _ = Nexilis.write(message: tmessage)
  1935. }
  1936. }
  1937. private func getCounter() {
  1938. Database().database?.inTransaction({ fmdb, rollback in
  1939. if let c = Database().getRecords(fmdb: fmdb, query: "SELECT counter FROM MESSAGE_SUMMARY where l_pin='\(dataPerson["f_pin"]!!)'"), c.next() {
  1940. counter = Int(c.int(forColumnIndex: 0))
  1941. c.close()
  1942. }
  1943. })
  1944. }
  1945. private func updateCounter(counter: Int) {
  1946. DispatchQueue.global().async {
  1947. Database.shared.database?.inTransaction({ (fmdb, rollback) in
  1948. _ = Database.shared.updateRecord(fmdb: fmdb, table: "MESSAGE_SUMMARY", cvalues: [
  1949. "counter" : "\(counter)"
  1950. ], _where: "l_pin = '\(self.dataPerson["f_pin"]!!)'")
  1951. })
  1952. NotificationCenter.default.post(name: NSNotification.Name(rawValue: "reloadTabChats"), object: nil, userInfo: nil)
  1953. }
  1954. }
  1955. private func addButtonScrollToBottom() {
  1956. self.view.addSubview(buttonScrollToBottom)
  1957. buttonScrollToBottom.translatesAutoresizingMaskIntoConstraints = false
  1958. NSLayoutConstraint.activate([
  1959. buttonScrollToBottom.bottomAnchor.constraint(equalTo: buttonSendChat.topAnchor, constant: -50),
  1960. buttonScrollToBottom.trailingAnchor.constraint(equalTo: self.view.trailingAnchor),
  1961. buttonScrollToBottom.widthAnchor.constraint(equalToConstant: 60),
  1962. buttonScrollToBottom.heightAnchor.constraint(equalToConstant: 30.0)
  1963. ])
  1964. buttonScrollToBottom.backgroundColor = .greenColor
  1965. buttonScrollToBottom.setImage(UIImage(systemName: "chevron.down.circle"), for: .normal)
  1966. buttonScrollToBottom.imageView?.contentMode = .scaleAspectFit
  1967. buttonScrollToBottom.imageView?.tintColor = .white
  1968. buttonScrollToBottom.contentVerticalAlignment = .fill
  1969. buttonScrollToBottom.contentHorizontalAlignment = .fill
  1970. buttonScrollToBottom.imageEdgeInsets.top = 2.0
  1971. buttonScrollToBottom.imageEdgeInsets.bottom = 2.0
  1972. buttonScrollToBottom.layer.cornerRadius = 10.0
  1973. buttonScrollToBottom.layer.maskedCorners = [.layerMinXMinYCorner, .layerMinXMaxYCorner]
  1974. buttonScrollToBottom.clipsToBounds = true
  1975. buttonScrollToBottom.addTarget(self, action: #selector(scrollTobottomAction), for: .touchUpInside)
  1976. }
  1977. private func addCounterAtButttonScrollToBottom() {
  1978. self.view.addSubview(indicatorCounterBSTB)
  1979. indicatorCounterBSTB.translatesAutoresizingMaskIntoConstraints = false
  1980. indicatorCounterBSTB.backgroundColor = .systemRed
  1981. indicatorCounterBSTB.layer.cornerRadius = 7.5
  1982. indicatorCounterBSTB.clipsToBounds = true
  1983. indicatorCounterBSTB.layer.borderWidth = 0.5
  1984. indicatorCounterBSTB.layer.borderColor = UIColor.secondaryColor.cgColor
  1985. NSLayoutConstraint.activate([
  1986. indicatorCounterBSTB.bottomAnchor.constraint(equalTo: buttonScrollToBottom.topAnchor, constant: 5),
  1987. indicatorCounterBSTB.trailingAnchor.constraint(equalTo: self.view.trailingAnchor, constant: -50),
  1988. indicatorCounterBSTB.widthAnchor.constraint(greaterThanOrEqualToConstant: 15),
  1989. indicatorCounterBSTB.heightAnchor.constraint(equalToConstant: 15)
  1990. ])
  1991. indicatorCounterBSTB.addSubview(labelCounter)
  1992. labelCounter.translatesAutoresizingMaskIntoConstraints = false
  1993. NSLayoutConstraint.activate([
  1994. labelCounter.leadingAnchor.constraint(equalTo: indicatorCounterBSTB.leadingAnchor, constant: 2),
  1995. labelCounter.trailingAnchor.constraint(equalTo: indicatorCounterBSTB.trailingAnchor, constant: -2),
  1996. labelCounter.centerXAnchor.constraint(equalTo: indicatorCounterBSTB.centerXAnchor),
  1997. ])
  1998. labelCounter.font = UIFont.systemFont(ofSize: 11)
  1999. labelCounter.text = "\(counter)"
  2000. labelCounter.textColor = .secondaryColor
  2001. labelCounter.textAlignment = .center
  2002. }
  2003. @objc func scrollTobottomAction() {
  2004. tableChatView.scrollToBottom()
  2005. DispatchQueue.main.asyncAfter(deadline: .now() + 0.35) { [self] in
  2006. if buttonScrollToBottom.isDescendant(of: self.view) {
  2007. buttonScrollToBottom.removeConstraints(buttonScrollToBottom.constraints)
  2008. buttonScrollToBottom.removeFromSuperview()
  2009. if indicatorCounterBSTB.isDescendant(of: self.view) {
  2010. indicatorCounterBSTB.removeConstraints(indicatorCounterBSTB.constraints)
  2011. indicatorCounterBSTB.removeFromSuperview()
  2012. }
  2013. }
  2014. }
  2015. }
  2016. private func checkNewMessage(tableView: UITableView) {
  2017. currentIndexpath = tableView.indexPathsForVisibleRows?.last
  2018. if currentIndexpath != nil {
  2019. let dataMessages = dataMessages.filter({ $0["chat_date"] as! String == dataDates[currentIndexpath!.section] })
  2020. if dataMessages.count == 0 || dataMessages.count - 1 < currentIndexpath!.row {
  2021. return
  2022. }
  2023. if currentIndexpath!.section == dataDates.count - 1 && currentIndexpath!.row != dataMessages.count - 1 && currentIndexpath!.row != dataMessages.count - 2 && !buttonScrollToBottom.isDescendant(of: self.view) {
  2024. addButtonScrollToBottom()
  2025. addCounterAtButttonScrollToBottom()
  2026. } else if currentIndexpath!.section == dataDates.count - 1 && currentIndexpath!.row == dataMessages.count - 1 {
  2027. if buttonScrollToBottom.isDescendant(of: self.view) {
  2028. buttonScrollToBottom.removeConstraints(buttonScrollToBottom.constraints)
  2029. buttonScrollToBottom.removeFromSuperview()
  2030. if indicatorCounterBSTB.isDescendant(of: self.view) {
  2031. indicatorCounterBSTB.removeConstraints(indicatorCounterBSTB.constraints)
  2032. indicatorCounterBSTB.removeFromSuperview()
  2033. }
  2034. }
  2035. }
  2036. var listData = dataMessages[0...currentIndexpath!.row]
  2037. listData = listData.filter({$0["status"] as? String != "4" && $0["status"] as? String != "8"})
  2038. if listData.count != 0 && !isContactCenter {
  2039. let idMe = UserDefaults.standard.string(forKey: "me") as String?
  2040. for i in 0...listData.count - 1 {
  2041. if listData[i]["f_pin"] as? String != idMe {
  2042. sendReadMessageStatus(chat_id: "", f_pin: dataPerson["f_pin"]!!, message_scope_id: "3", message_id: listData[i]["message_id"] as! String)
  2043. }
  2044. }
  2045. }
  2046. }
  2047. if counter == 0 && indicatorCounterBSTB.isDescendant(of: self.view) {
  2048. indicatorCounterBSTB.removeConstraints(indicatorCounterBSTB.constraints)
  2049. indicatorCounterBSTB.removeFromSuperview()
  2050. } else if counter != 0 && currentIndexpath != nil {
  2051. let dataFilter = dataMessages.filter({ $0["chat_date"] as! String == dataDates[currentIndexpath!.section] })
  2052. if dataFilter.count == 0 {
  2053. return
  2054. }
  2055. let idx = dataMessages.firstIndex(where: { $0["message_id"] as? String == dataFilter[currentIndexpath!.row]["message_id"] as? String})
  2056. if idx == nil {
  2057. return
  2058. }
  2059. if (dataMessages.count - counter) <= idx! {
  2060. let countUpdate = idx! - (dataMessages.count - counter)
  2061. counter = counter - (countUpdate + 1)
  2062. if indicatorCounterBSTB.isDescendant(of: self.view) {
  2063. labelCounter.text = "\(counter)"
  2064. }
  2065. updateCounter(counter: counter)
  2066. }
  2067. }
  2068. }
  2069. }
  2070. //EPV
  2071. extension EditorPersonal: PreviewAttachmentImageVideoDelegate {
  2072. public func didSelect(imagevideo: Any?) {
  2073. if (imagevideo != nil) {
  2074. let imageVideoData = imagevideo as! [UIImagePickerController.InfoKey: Any]
  2075. let previewImageVC = PreviewAttachmentImageVideo(nibName: "PreviewAttachmentImageVideo", bundle: Bundle.resourceBundle(for: Nexilis.self))
  2076. previewImageVC.imageVideoData = imageVideoData
  2077. if (textFieldSend.textColor != .lightGray) {
  2078. previewImageVC.currentTextTextField = textFieldSend.text
  2079. }
  2080. previewImageVC.modalPresentationStyle = .custom
  2081. previewImageVC.delegate = self
  2082. self.present(previewImageVC, animated: true, completion: nil)
  2083. }
  2084. }
  2085. func sendChatFromPreviewImage(message_text: String, attachment_flag: String, image_id: String, video_id: String, thumb_id: String, viewController: UIViewController) {
  2086. sendChat(message_text: message_text, attachment_flag: attachment_flag, image_id: image_id, video_id: video_id, thumb_id: thumb_id, viewController: viewController)
  2087. }
  2088. }
  2089. //EQL
  2090. extension EditorPersonal: UIDocumentPickerDelegate, DocumentPickerDelegate, QLPreviewControllerDataSource {
  2091. public func didSelectDocument(document: Any?) {
  2092. if (document != nil) {
  2093. self.previewItem = (document as! [URL])[0] as NSURL
  2094. let previewController = QLPreviewController()
  2095. let navController = UINavigationController(rootViewController: previewController)
  2096. let leftBarButton = navigationQLPreviewDocument(title: "Cancel".localized(), style: .plain, target: self, action: #selector(cancelDocumentPreview))
  2097. let rightBarButton = navigationQLPreviewDocument(title: "Send".localized(), style: .done, target: self, action: #selector(sendDocument))
  2098. // leftBarButton.tintColor = .white
  2099. // rightBarButton.tintColor = .white
  2100. leftBarButton.navigation = navController
  2101. rightBarButton.navigation = navController
  2102. // navController.navigationBar.barTintColor = .mainColor
  2103. navController.navigationBar.isTranslucent = false
  2104. previewController.navigationItem.leftBarButtonItem = leftBarButton
  2105. previewController.navigationItem.rightBarButtonItem = rightBarButton
  2106. previewController.dataSource = self
  2107. previewController.modalPresentationStyle = .pageSheet
  2108. self.present(navController, animated: true, completion: nil)
  2109. }
  2110. }
  2111. @objc private func cancelDocumentPreview(sender: navigationQLPreviewDocument) {
  2112. sender.navigation.dismiss(animated: true, completion: nil)
  2113. }
  2114. @objc private func sendDocument(sender: navigationQLPreviewDocument) {
  2115. sender.navigation.dismiss(animated: true, completion: nil)
  2116. do {
  2117. let dataFile = try Data(contentsOf: self.previewItem! as URL)
  2118. let urlFile = self.previewItem?.absoluteString
  2119. var originaFileName = (urlFile! as NSString).lastPathComponent
  2120. originaFileName = NSString(string: originaFileName).removingPercentEncoding!
  2121. let renamedNameFile = "Qmera_doc_" + "\(Date().millisecondsSince1970)_" + originaFileName
  2122. let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
  2123. let fileURL = documentsDirectory.appendingPathComponent(renamedNameFile)
  2124. if !FileManager.default.fileExists(atPath: fileURL.path) {
  2125. do {
  2126. try dataFile.write(to: fileURL)
  2127. print("file saved")
  2128. } catch {
  2129. print("error saving file:", error)
  2130. }
  2131. }
  2132. sendChat(message_text: "\(originaFileName)|", attachment_flag: "6", file_id: renamedNameFile, viewController: self)
  2133. } catch {
  2134. }
  2135. }
  2136. public func numberOfPreviewItems(in controller: QLPreviewController) -> Int {
  2137. 1
  2138. }
  2139. public func previewController(_ controller: QLPreviewController, previewItemAt index: Int) -> QLPreviewItem {
  2140. return self.previewItem!
  2141. }
  2142. }
  2143. //ETV
  2144. extension EditorPersonal: UITextViewDelegate {
  2145. public func textViewDidChange(_ textView: UITextView) {
  2146. if allowTyping {
  2147. allowTyping = false
  2148. if isContactCenter && !fPinContacCenter.isEmpty {
  2149. sendTyping(l_pin: fPinContacCenter, isTyping: true)
  2150. } else {
  2151. sendTyping(l_pin: dataPerson["f_pin"]!!, isTyping: true)
  2152. }
  2153. DispatchQueue.main.asyncAfter(deadline: .now() + 4, execute: {
  2154. self.allowTyping = true
  2155. })
  2156. }
  2157. if let selectedRange = textView.selectedTextRange {
  2158. let cursorPosition = textView.offset(from: textView.beginningOfDocument, to: selectedRange.start)
  2159. let beforeCursor = textView.text.substring(from: cursorPosition - cursorPosition, to: cursorPosition - 1).split(separator: " ").last
  2160. let afterCursor = textView.text.substring(from: cursorPosition, to: textView.text.count - 1).split(separator: " ").first
  2161. var firstCount = 0
  2162. var lastCount = textView.text.count
  2163. if beforeCursor != nil {
  2164. firstCount = cursorPosition - beforeCursor!.count - 1
  2165. if firstCount == -1 {
  2166. firstCount = 0
  2167. }
  2168. if beforeCursor!.lowercased().checkStartWithLink() {
  2169. if textView.text.split(separator: " ").count > 1 && self.containerLink.isDescendant(of: self.viewTextfield) {
  2170. } else {
  2171. if ((beforeCursor!.lowercased().starts(with: "www.") && beforeCursor!.lowercased().split(separator: ".").count >= 3) || (!beforeCursor!.lowercased().starts(with: "www.") && beforeCursor!.lowercased().split(separator: ".").count >= 2)) && beforeCursor!.lowercased().split(separator: ".").last!.count >= 2 {
  2172. checkLink(text: beforeCursor!.lowercased())
  2173. } else {
  2174. deleteLinkPreview()
  2175. }
  2176. }
  2177. }
  2178. }
  2179. if afterCursor != nil {
  2180. if beforeCursor == nil {
  2181. lastCount = afterCursor!.count + 2
  2182. } else {
  2183. lastCount = beforeCursor!.count + afterCursor!.count + 2
  2184. }
  2185. if afterCursor!.lowercased().checkStartWithLink() {
  2186. if textView.text.split(separator: " ").count > 1 && self.containerLink.isDescendant(of: self.viewTextfield) {
  2187. } else {
  2188. if ((afterCursor!.lowercased().starts(with: "www.") && afterCursor!.lowercased().split(separator: ".").count >= 3) || afterCursor!.lowercased().split(separator: ".").count >= 2) && afterCursor!.lowercased().split(separator: ".").last!.count >= 2 {
  2189. checkLink(text: afterCursor!.lowercased())
  2190. } else {
  2191. deleteLinkPreview()
  2192. }
  2193. }
  2194. }
  2195. }
  2196. if textView.text.contains("*") || textView.text.contains("_") || textView.text.contains("^") || textView.text.contains("~") {
  2197. textView.preserveCursorPosition(withChanges: { _ in
  2198. textView.attributedText = textView.text.richText(isEditing: true, first: firstCount, last: lastCount)
  2199. return .preserveCursor
  2200. })
  2201. }
  2202. }
  2203. }
  2204. private func checkLink(text: String) {
  2205. var stringURl = text
  2206. if stringURl.starts(with: "www.") {
  2207. stringURl = "https://" + stringURl.replacingOccurrences(of: "www.", with: "")
  2208. }
  2209. var dataURL = ""
  2210. Database.shared.database?.inTransaction({ (fmdb, rollback) in
  2211. if let cursor = Database.shared.getRecords(fmdb: fmdb, query: "select data_link from LINK_PREVIEW where link='\(stringURl)'") {
  2212. while cursor.next() {
  2213. if let data = cursor.string(forColumnIndex: 0) {
  2214. dataURL = data
  2215. }
  2216. }
  2217. cursor.close()
  2218. }
  2219. })
  2220. if !dataURL.isEmpty {
  2221. if let data = try! JSONSerialization.jsonObject(with: dataURL.data(using: String.Encoding.utf8)!, options: []) as? [String: Any] {
  2222. let title = data["title"] as! String
  2223. let description = data["description"] as! String
  2224. let imageUrl = data["imageUrl"] as? String
  2225. self.buildPreviewLink(imageUrl: imageUrl, title: title, description: description, stringURl: text)
  2226. }
  2227. } else {
  2228. if let urlData = URL(string: stringURl) {
  2229. Readability.parse(url: urlData, completion: { data in
  2230. self.deleteLinkPreview()
  2231. if data != nil {
  2232. let title = data!.title
  2233. let description = data!.description
  2234. let imageUrl = data!.topImage
  2235. Database.shared.database?.inTransaction({ (fmdb, rollback) in
  2236. do {
  2237. var dataJson: [String: Any] = [:]
  2238. dataJson["title"] = title
  2239. dataJson["description"] = description
  2240. dataJson["imageUrl"] = imageUrl
  2241. guard let json = String(data: try! JSONSerialization.data(withJSONObject: dataJson, options: []), encoding: String.Encoding.utf8) else {
  2242. return
  2243. }
  2244. _ = try Database.shared.insertRecord(fmdb: fmdb, table: "LINK_PREVIEW", cvalues: [
  2245. "id" : "\(Date().currentTimeMillis().toHex())",
  2246. "link" : stringURl,
  2247. "data_link" : json,
  2248. "retry": 0
  2249. ], replace: true)
  2250. } catch {
  2251. rollback.pointee = true
  2252. print(error)
  2253. }
  2254. })
  2255. self.buildPreviewLink(imageUrl: imageUrl, title: title, description: description, stringURl: text)
  2256. }
  2257. })
  2258. }
  2259. }
  2260. }
  2261. private func buildPreviewLink(imageUrl: String?, title: String, description: String?, stringURl: String) {
  2262. UIView.animate(withDuration: 0.25, delay: 0.0, options: .curveEaseInOut, animations: {
  2263. self.constraintTopTextField.constant = self.constraintTopTextField.constant + 80
  2264. }, completion: nil)
  2265. self.viewTextfield.addSubview(self.containerLink)
  2266. self.containerLink.translatesAutoresizingMaskIntoConstraints = false
  2267. self.containerLink.leadingAnchor.constraint(equalTo: self.viewTextfield.leadingAnchor).isActive = true
  2268. self.containerLink.bottomAnchor.constraint(equalTo: self.textFieldSend.topAnchor).isActive = true
  2269. self.containerLink.trailingAnchor.constraint(equalTo: self.viewTextfield.trailingAnchor).isActive = true
  2270. self.containerLink.heightAnchor.constraint(equalToConstant: 80.0).isActive = true
  2271. self.containerLink.backgroundColor = .secondaryColor
  2272. if self.reffId != nil {
  2273. self.bottomAnchorPreviewReply.isActive = false
  2274. self.bottomAnchorPreviewReply = self.containerPreviewReply.bottomAnchor.constraint(equalTo: self.containerLink.topAnchor)
  2275. self.bottomAnchorPreviewReply.isActive = true
  2276. }
  2277. let imagePreview = UIImageView()
  2278. if imageUrl != nil {
  2279. self.containerLink.addSubview(imagePreview)
  2280. imagePreview.translatesAutoresizingMaskIntoConstraints = false
  2281. imagePreview.leadingAnchor.constraint(equalTo: self.containerLink.leadingAnchor).isActive = true
  2282. imagePreview.bottomAnchor.constraint(equalTo: self.containerLink.bottomAnchor).isActive = true
  2283. imagePreview.topAnchor.constraint(equalTo: self.containerLink.topAnchor).isActive = true
  2284. imagePreview.widthAnchor.constraint(equalToConstant: 80.0).isActive = true
  2285. if !imageUrl!.starts(with: "https://") {
  2286. imagePreview.loadImageAsync(with: "https://www.google.be" + imageUrl!)
  2287. } else {
  2288. imagePreview.loadImageAsync(with: imageUrl)
  2289. }
  2290. imagePreview.contentMode = .scaleAspectFit
  2291. }
  2292. let titlePreview = UILabel()
  2293. self.containerLink.addSubview(titlePreview)
  2294. titlePreview.translatesAutoresizingMaskIntoConstraints = false
  2295. if imageUrl != nil {
  2296. titlePreview.leadingAnchor.constraint(equalTo: imagePreview.trailingAnchor, constant: 5.0).isActive = true
  2297. } else {
  2298. titlePreview.leadingAnchor.constraint(equalTo: self.containerLink.leadingAnchor, constant: 5.0).isActive = true
  2299. }
  2300. titlePreview.topAnchor.constraint(equalTo: self.containerLink.topAnchor, constant: 25.0).isActive = true
  2301. titlePreview.trailingAnchor.constraint(equalTo: self.containerLink.trailingAnchor, constant: -80.0).isActive = true
  2302. titlePreview.text = title
  2303. titlePreview.font = UIFont.systemFont(ofSize: 14.0, weight: .bold)
  2304. titlePreview.textColor = .black
  2305. let descPreview = UILabel()
  2306. self.containerLink.addSubview(descPreview)
  2307. descPreview.translatesAutoresizingMaskIntoConstraints = false
  2308. if imageUrl != nil {
  2309. descPreview.leadingAnchor.constraint(equalTo: imagePreview.trailingAnchor, constant: 5.0).isActive = true
  2310. } else {
  2311. descPreview.leadingAnchor.constraint(equalTo: self.containerLink.leadingAnchor, constant: 5.0).isActive = true
  2312. }
  2313. descPreview.topAnchor.constraint(equalTo: titlePreview.bottomAnchor).isActive = true
  2314. descPreview.trailingAnchor.constraint(equalTo: self.containerLink.trailingAnchor, constant: -80.0).isActive = true
  2315. descPreview.text = description
  2316. descPreview.font = UIFont.systemFont(ofSize: 12.0)
  2317. descPreview.textColor = .gray
  2318. descPreview.numberOfLines = 1
  2319. let linkPreview = UILabel()
  2320. self.containerLink.addSubview(linkPreview)
  2321. linkPreview.translatesAutoresizingMaskIntoConstraints = false
  2322. if imageUrl != nil {
  2323. linkPreview.leadingAnchor.constraint(equalTo: imagePreview.trailingAnchor, constant: 5.0).isActive = true
  2324. } else {
  2325. linkPreview.leadingAnchor.constraint(equalTo: self.containerLink.leadingAnchor, constant: 5.0).isActive = true
  2326. }
  2327. linkPreview.topAnchor.constraint(equalTo: descPreview.bottomAnchor, constant: 8.0).isActive = true
  2328. linkPreview.trailingAnchor.constraint(equalTo: self.containerLink.trailingAnchor, constant: -80.0).isActive = true
  2329. linkPreview.text = stringURl
  2330. linkPreview.font = UIFont.systemFont(ofSize: 10.0)
  2331. linkPreview.textColor = .gray
  2332. linkPreview.numberOfLines = 1
  2333. let cancelPreview = UIButton(type: .custom)
  2334. self.containerLink.addSubview(cancelPreview)
  2335. cancelPreview.translatesAutoresizingMaskIntoConstraints = false
  2336. cancelPreview.trailingAnchor.constraint(equalTo: self.containerLink.trailingAnchor, constant: -10).isActive = true
  2337. cancelPreview.centerYAnchor.constraint(equalTo: self.containerLink.centerYAnchor).isActive = true
  2338. cancelPreview.setImage(UIImage(systemName: "xmark.circle" , withConfiguration: UIImage.SymbolConfiguration(pointSize: 20, weight: .regular, scale: .default)), for: .normal)
  2339. cancelPreview.addTarget(nil, action: #selector(self.deleteLinkPreview), for: .touchUpInside)
  2340. cancelPreview.backgroundColor = .clear
  2341. cancelPreview.tintColor = .mainColor
  2342. }
  2343. public func textViewDidBeginEditing(_ textView: UITextView) {
  2344. if textView.textColor == UIColor.lightGray {
  2345. textView.text = nil
  2346. textView.textColor = UIColor.black
  2347. }
  2348. }
  2349. public func textViewDidEndEditing(_ textView: UITextView) {
  2350. if textView.text.isEmpty {
  2351. textView.text = "Send message".localized()
  2352. textView.textColor = UIColor.lightGray
  2353. }
  2354. }
  2355. public override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
  2356. if action == #selector(UIResponderStandardEditActions.paste(_:)) && (UIPasteboard.general.image != nil) {
  2357. return true
  2358. }
  2359. return super.canPerformAction(action, withSender: sender)
  2360. }
  2361. public override func paste(_ sender: Any?) {
  2362. if UIPasteboard.general.image != nil {
  2363. let previewImageVC = PreviewAttachmentImageVideo(nibName: "PreviewAttachmentImageVideo", bundle: Bundle.resourceBundle(for: Nexilis.self))
  2364. previewImageVC.image = UIPasteboard.general.image
  2365. previewImageVC.fromCopy = true
  2366. previewImageVC.currentTextTextField = textFieldSend.text
  2367. previewImageVC.modalPresentationStyle = .custom
  2368. previewImageVC.delegate = self
  2369. self.present(previewImageVC, animated: true, completion: nil)
  2370. }
  2371. }
  2372. public func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
  2373. let cursorPosition = textView.caretRect(for: self.textFieldSend.selectedTextRange!.start).origin
  2374. let currentLine = Int(cursorPosition.y / self.textFieldSend.font!.lineHeight)
  2375. UIView.animate(withDuration: 0.3) {
  2376. if currentLine == 0 && text != "\n" {
  2377. self.heightTextFieldSend.constant = 40
  2378. } else if currentLine < 4 {
  2379. // DispatchQueue.main.async {
  2380. // if (self.currentIndexpath != nil) {
  2381. // self.tableChatView.scrollToRow(at: IndexPath(row: self.currentIndexpath!.row, section: self.currentIndexpath!.section), at: .none, animated: false)
  2382. // }
  2383. // }
  2384. if (text == "\n" && self.textFieldSend.text.count > 0) {
  2385. self.heightTextFieldSend.constant = self.textFieldSend.contentSize.height + 18
  2386. }
  2387. else if (self.textFieldSend.text.count > 0) {
  2388. self.heightTextFieldSend.constant = self.textFieldSend.contentSize.height
  2389. }
  2390. let txt = textView.text
  2391. let txtRange = Range(range, in: txt!)
  2392. let subString: Substring = txt![txtRange!]
  2393. if subString == "\n" {
  2394. self.heightTextFieldSend.constant = self.textFieldSend.contentSize.height - 18
  2395. if (self.heightTextFieldSend.constant <= 50 && self.heightTextFieldSend.constant >= 40) {
  2396. self.heightTextFieldSend.constant = 40
  2397. }
  2398. }
  2399. }
  2400. let countBreakLine = text.split(separator: "\n").count
  2401. if countBreakLine > 1 && self.heightTextFieldSend.constant != CGFloat(40 + (countBreakLine * 18)) {
  2402. self.heightTextFieldSend.constant = CGFloat(40 + (countBreakLine * 18))
  2403. }
  2404. }
  2405. if (self.textFieldSend.text.count == 0) {
  2406. return text != "\n"
  2407. }
  2408. return true
  2409. }
  2410. }
  2411. //EUC
  2412. extension EditorPersonal: UIContextMenuInteractionDelegate {
  2413. public func contextMenuInteraction(_ interaction: UIContextMenuInteraction, configurationForMenuAtLocation location: CGPoint) -> UIContextMenuConfiguration? {
  2414. if textFieldSend.isFirstResponder {
  2415. textFieldSend.resignFirstResponder()
  2416. }
  2417. let indexPath = self.tableChatView.indexPathForRow(at: interaction.view!.convert(location, to: self.tableChatView))
  2418. let dataMessages = self.dataMessages.filter({ $0["chat_date"] as! String == dataDates[indexPath!.section]})
  2419. var star: UIAction
  2420. if (dataMessages[indexPath!.row]["is_stared"] as! String == "0") {
  2421. star = UIAction(title: "Star".localized(), image: UIImage(systemName: "star.fill"), handler: {(_) in
  2422. DispatchQueue.global().async {
  2423. Database.shared.database?.inTransaction({ (fmdb, rollback) in
  2424. _ = Database.shared.updateRecord(fmdb: fmdb, table: "MESSAGE", cvalues: [
  2425. "is_stared" : 1
  2426. ], _where: "message_id = '\(dataMessages[indexPath!.row]["message_id"] as! String)'")
  2427. })
  2428. }
  2429. let idx = self.dataMessages.firstIndex(where: { $0["message_id"] as? String == dataMessages[indexPath!.row]["message_id"] as? String})
  2430. if idx != nil{
  2431. self.dataMessages[idx!]["is_stared"] = "1"
  2432. }
  2433. self.tableChatView.reloadRows(at: [indexPath!], with: .none)
  2434. })
  2435. } else {
  2436. star = UIAction(title: "Unstar".localized(), image: UIImage(systemName: "star.fill"), handler: {(_) in
  2437. DispatchQueue.global().async {
  2438. Database.shared.database?.inTransaction({ (fmdb, rollback) in
  2439. _ = Database.shared.updateRecord(fmdb: fmdb, table: "MESSAGE", cvalues: [
  2440. "is_stared" : 0
  2441. ], _where: "message_id = '\(dataMessages[indexPath!.row]["message_id"] as! String)'")
  2442. })
  2443. }
  2444. let idx = self.dataMessages.firstIndex(where: { $0["message_id"] as? String == dataMessages[indexPath!.row]["message_id"] as? String})
  2445. if idx != nil{
  2446. self.dataMessages[idx!]["is_stared"] = "0"
  2447. }
  2448. self.tableChatView.reloadRows(at: [indexPath!], with: .none)
  2449. })
  2450. }
  2451. let reply = UIAction(title: "Reply".localized(), image: UIImage(systemName: "arrowshape.turn.up.left.fill"), handler: {(_) in
  2452. self.deleteReplyView()
  2453. self.textFieldSend.becomeFirstResponder()
  2454. self.reffId = dataMessages[indexPath!.row]["message_id"] as? String
  2455. UIView.animate(withDuration: 0.25, delay: 0.0, options: .curveEaseInOut, animations: {
  2456. self.constraintTopTextField.constant = self.constraintTopTextField.constant + 50
  2457. }, completion: nil)
  2458. if (self.currentIndexpath != nil) {
  2459. DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) {
  2460. self.tableChatView.scrollToRow(at: IndexPath(row: self.currentIndexpath!.row, section: self.currentIndexpath!.section), at: .none, animated: false)
  2461. }
  2462. } else {
  2463. self.tableChatView.scrollToBottom()
  2464. }
  2465. self.viewTextfield.addSubview(self.containerPreviewReply)
  2466. self.containerPreviewReply.translatesAutoresizingMaskIntoConstraints = false
  2467. self.containerPreviewReply.leadingAnchor.constraint(equalTo: self.viewTextfield.leadingAnchor).isActive = true
  2468. self.containerPreviewReply.topAnchor.constraint(equalTo: self.viewTextfield.topAnchor).isActive = true
  2469. if !self.containerLink.isDescendant(of: self.viewTextfield) {
  2470. self.bottomAnchorPreviewReply = self.containerPreviewReply.bottomAnchor.constraint(equalTo: self.textFieldSend.topAnchor)
  2471. } else {
  2472. self.bottomAnchorPreviewReply = self.containerPreviewReply.bottomAnchor.constraint(equalTo: self.containerLink.topAnchor)
  2473. }
  2474. self.bottomAnchorPreviewReply.isActive = true
  2475. self.containerPreviewReply.trailingAnchor.constraint(equalTo: self.viewTextfield.trailingAnchor).isActive = true
  2476. self.containerPreviewReply.backgroundColor = .secondaryColor
  2477. let leftReply = UIView()
  2478. self.containerPreviewReply.addSubview(leftReply)
  2479. leftReply.translatesAutoresizingMaskIntoConstraints = false
  2480. leftReply.leadingAnchor.constraint(equalTo: self.viewTextfield.leadingAnchor).isActive = true
  2481. leftReply.topAnchor.constraint(equalTo: self.containerPreviewReply.topAnchor).isActive = true
  2482. leftReply.bottomAnchor.constraint(equalTo: self.containerPreviewReply.bottomAnchor).isActive = true
  2483. leftReply.widthAnchor.constraint(equalToConstant: 3).isActive = true
  2484. leftReply.backgroundColor = .orangeColor
  2485. let titleReply = UILabel()
  2486. self.containerPreviewReply.addSubview(titleReply)
  2487. titleReply.translatesAutoresizingMaskIntoConstraints = false
  2488. titleReply.leadingAnchor.constraint(equalTo: leftReply.leadingAnchor, constant: 10).isActive = true
  2489. titleReply.topAnchor.constraint(equalTo: self.containerPreviewReply.topAnchor, constant: 10).isActive = true
  2490. titleReply.font = UIFont.systemFont(ofSize: 12).bold
  2491. let idMe = UserDefaults.standard.string(forKey: "me") as String?
  2492. if (dataMessages[indexPath!.row]["f_pin"] as? String == idMe) {
  2493. titleReply.text = "You".localized()
  2494. } else {
  2495. if self.isContactCenter {
  2496. let user: [User] = self.users.filter({$0.pin == dataMessages[indexPath!.row]["f_pin"] as? String})
  2497. titleReply.text = user.first!.fullName
  2498. } else {
  2499. titleReply.text = self.dataPerson["name"]!!
  2500. }
  2501. }
  2502. titleReply.textColor = .orangeColor
  2503. let contentReply = UILabel()
  2504. self.containerPreviewReply.addSubview(contentReply)
  2505. contentReply.translatesAutoresizingMaskIntoConstraints = false
  2506. contentReply.leadingAnchor.constraint(equalTo: leftReply.leadingAnchor, constant: 10).isActive = true
  2507. contentReply.topAnchor.constraint(equalTo: titleReply.bottomAnchor).isActive = true
  2508. contentReply.font = UIFont.systemFont(ofSize: 10)
  2509. let message_text = dataMessages[indexPath!.row]["message_text"] as! String
  2510. let attachment_flag = dataMessages[indexPath!.row]["attachment_flag"] as! String
  2511. let thumb_chat = dataMessages[indexPath!.row]["thumb_id"] as! String
  2512. let image_chat = dataMessages[indexPath!.row]["image_id"] as! String
  2513. let video_chat = dataMessages[indexPath!.row]["video_id"] as! String
  2514. let file_chat = dataMessages[indexPath!.row]["file_id"] as! String
  2515. if (attachment_flag == "0" && thumb_chat == "") {
  2516. contentReply.attributedText = message_text.richText()
  2517. } else if (attachment_flag == "1" || image_chat != "") {
  2518. if (message_text == "") {
  2519. contentReply.text = "📷 Photo".localized()
  2520. } else {
  2521. contentReply.attributedText = message_text.richText()
  2522. }
  2523. } else if (attachment_flag == "2" || video_chat != "") {
  2524. if (message_text == "") {
  2525. contentReply.text = "📹 Video".localized()
  2526. } else {
  2527. contentReply.attributedText = message_text.richText()
  2528. }
  2529. } else if (attachment_flag == "6" || file_chat != ""){
  2530. contentReply.text = "📄 \(message_text.components(separatedBy: "|")[0])"
  2531. } else if (attachment_flag == "11") {
  2532. contentReply.text = "❤️ Sticker"
  2533. }
  2534. contentReply.textColor = .gray
  2535. let buttonCancelReply = UIButton(type: .custom)
  2536. self.containerPreviewReply.addSubview(buttonCancelReply)
  2537. buttonCancelReply.translatesAutoresizingMaskIntoConstraints = false
  2538. buttonCancelReply.trailingAnchor.constraint(equalTo: self.containerPreviewReply.trailingAnchor, constant: -10).isActive = true
  2539. buttonCancelReply.centerYAnchor.constraint(equalTo: self.containerPreviewReply.centerYAnchor).isActive = true
  2540. buttonCancelReply.setImage(UIImage(systemName: "xmark.circle" , withConfiguration: UIImage.SymbolConfiguration(pointSize: 20, weight: .regular, scale: .default)), for: .normal)
  2541. buttonCancelReply.addTarget(nil, action: #selector(self.deleteReplyView), for: .touchUpInside)
  2542. buttonCancelReply.backgroundColor = .clear
  2543. buttonCancelReply.tintColor = .mainColor
  2544. if (attachment_flag == "1" || attachment_flag == "2" || image_chat != "" || video_chat != "") {
  2545. let nsDocumentDirectory = FileManager.SearchPathDirectory.documentDirectory
  2546. let nsUserDomainMask = FileManager.SearchPathDomainMask.userDomainMask
  2547. let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true)
  2548. if let dirPath = paths.first {
  2549. let thumbURL = URL(fileURLWithPath: dirPath).appendingPathComponent(thumb_chat)
  2550. let image = UIImage(contentsOfFile: thumbURL.path)
  2551. let imageThumb = UIImageView(image: image)
  2552. self.containerPreviewReply.addSubview(imageThumb)
  2553. imageThumb.layer.cornerRadius = 2.0
  2554. imageThumb.clipsToBounds = true
  2555. imageThumb.translatesAutoresizingMaskIntoConstraints = false
  2556. imageThumb.trailingAnchor.constraint(equalTo: buttonCancelReply.leadingAnchor, constant: -10).isActive = true
  2557. imageThumb.centerYAnchor.constraint(equalTo: self.containerPreviewReply.centerYAnchor).isActive = true
  2558. imageThumb.widthAnchor.constraint(equalToConstant: 30).isActive = true
  2559. imageThumb.heightAnchor.constraint(equalToConstant: 30).isActive = true
  2560. if (attachment_flag == "2") {
  2561. let imagePlay = UIImageView(image: UIImage(systemName: "play.circle.fill"))
  2562. imageThumb.addSubview(imagePlay)
  2563. imagePlay.clipsToBounds = true
  2564. imagePlay.translatesAutoresizingMaskIntoConstraints = false
  2565. imagePlay.centerYAnchor.constraint(equalTo: imageThumb.centerYAnchor).isActive = true
  2566. imagePlay.centerXAnchor.constraint(equalTo: imageThumb.centerXAnchor).isActive = true
  2567. imagePlay.widthAnchor.constraint(equalToConstant: 10).isActive = true
  2568. imagePlay.heightAnchor.constraint(equalToConstant: 10).isActive = true
  2569. imagePlay.tintColor = .white
  2570. }
  2571. }
  2572. }
  2573. if (attachment_flag == "11") {
  2574. let imageSticker = UIImageView(image: UIImage(named: (message_text.components(separatedBy: "/")[1]), in: Bundle.resourceBundle(for: Nexilis.self), with: nil))
  2575. self.containerPreviewReply.addSubview(imageSticker)
  2576. imageSticker.layer.cornerRadius = 2.0
  2577. imageSticker.clipsToBounds = true
  2578. imageSticker.translatesAutoresizingMaskIntoConstraints = false
  2579. imageSticker.trailingAnchor.constraint(equalTo: buttonCancelReply.leadingAnchor, constant: -10).isActive = true
  2580. imageSticker.centerYAnchor.constraint(equalTo: self.containerPreviewReply.centerYAnchor).isActive = true
  2581. imageSticker.widthAnchor.constraint(equalToConstant: 30).isActive = true
  2582. imageSticker.heightAnchor.constraint(equalToConstant: 30).isActive = true
  2583. }
  2584. })
  2585. let forward = UIAction(title: "Forward".localized(), image: UIImage(systemName: "arrowshape.turn.up.right.fill"), handler: {(_) in
  2586. self.forwardSession = true
  2587. if self.reffId != nil {
  2588. self.deleteReplyView()
  2589. }
  2590. DispatchQueue.main.asyncAfter(deadline: .now() + 0.35) {
  2591. let cancelButton = UIBarButtonItem(title: "Cancel".localized(), style: .plain, target: self, action: #selector(self.cancelAction))
  2592. if self.dataPerson["f_pin"] != "-999" && !self.isContactCenter {
  2593. self.navigationItem.rightBarButtonItems = nil
  2594. }
  2595. self.navigationItem.rightBarButtonItem = cancelButton
  2596. if self.isContactCenter || self.fromNotification {
  2597. self.navigationItem.leftBarButtonItem = nil
  2598. }
  2599. self.changeAppBar()
  2600. let idx = self.dataMessages.firstIndex(where: { $0["message_id"] as? String == dataMessages[indexPath!.row]["message_id"] as? String})
  2601. if idx != nil{
  2602. self.dataMessages[idx!]["isSelected"] = true
  2603. }
  2604. self.addMultipleSelectSession()
  2605. self.tableChatView.reloadData()
  2606. }
  2607. })
  2608. let copy = UIAction(title: "Copy".localized(), image: UIImage(systemName: "doc.on.doc.fill"), handler: {(_) in
  2609. self.copySession = true
  2610. if self.reffId != nil {
  2611. self.deleteReplyView()
  2612. }
  2613. DispatchQueue.main.asyncAfter(deadline: .now() + 0.35) {
  2614. let cancelButton = UIBarButtonItem(title: "Cancel".localized(), style: .plain, target: self, action: #selector(self.cancelAction))
  2615. if self.dataPerson["f_pin"] != "-999" && !self.isContactCenter {
  2616. self.navigationItem.rightBarButtonItems = nil
  2617. }
  2618. self.navigationItem.rightBarButtonItem = cancelButton
  2619. if self.isContactCenter || self.fromNotification {
  2620. self.navigationItem.leftBarButtonItem = nil
  2621. }
  2622. self.changeAppBar()
  2623. let idx = self.dataMessages.firstIndex(where: { $0["message_id"] as? String == dataMessages[indexPath!.row]["message_id"] as? String})
  2624. if idx != nil{
  2625. self.dataMessages[idx!]["isSelected"] = true
  2626. }
  2627. self.addMultipleSelectSession()
  2628. self.tableChatView.reloadData()
  2629. }
  2630. })
  2631. let delete = UIAction(title: "Delete".localized(), image: UIImage(systemName: "trash.fill"), attributes: .destructive, handler: {(_) in
  2632. self.deleteSession = true
  2633. if self.reffId != nil {
  2634. self.deleteReplyView()
  2635. }
  2636. DispatchQueue.main.asyncAfter(deadline: .now() + 0.35) {
  2637. let cancelButton = UIBarButtonItem(title: "Cancel".localized(), style: .plain, target: self, action: #selector(self.cancelAction))
  2638. if self.dataPerson["f_pin"] != "-999" && !self.isContactCenter {
  2639. self.navigationItem.rightBarButtonItems = nil
  2640. }
  2641. self.navigationItem.rightBarButtonItem = cancelButton
  2642. if self.isContactCenter || self.fromNotification {
  2643. self.navigationItem.leftBarButtonItem = nil
  2644. }
  2645. self.changeAppBar()
  2646. let idx = self.dataMessages.firstIndex(where: { $0["message_id"] as? String == dataMessages[indexPath!.row]["message_id"] as? String})
  2647. if idx != nil{
  2648. self.dataMessages[idx!]["isSelected"] = true
  2649. }
  2650. self.addMultipleSelectSession()
  2651. self.tableChatView.reloadData()
  2652. }
  2653. })
  2654. var children: [UIMenuElement] = [star, reply, forward, copy, delete]
  2655. // let copyOption = self.copyOption(indexPath: indexPath!)
  2656. if isContactCenter {
  2657. children = [reply, copy]
  2658. } else if (dataMessages[indexPath!.row]["lock"] != nil && dataMessages[indexPath!.row]["lock"] as! String == "1") || dataMessages[indexPath!.row]["message_scope_id"] as! String == "18" || dataPerson["f_pin"] == "-999" {
  2659. children = [delete]
  2660. } else if self.removed || blocking == "1" || blocking == "-1" {
  2661. children = [copy]
  2662. if !(dataMessages[indexPath!.row]["image_id"] as! String).isEmpty || !(dataMessages[indexPath!.row]["video_id"] as! String).isEmpty {
  2663. children = []
  2664. }
  2665. }
  2666. else if !(dataMessages[indexPath!.row]["image_id"] as! String).isEmpty || !(dataMessages[indexPath!.row]["video_id"] as! String).isEmpty || !(dataMessages[indexPath!.row]["file_id"] as! String).isEmpty || dataMessages[indexPath!.row]["attachment_flag"] as! String == "11" {
  2667. children = [star, reply, forward ,delete]
  2668. }
  2669. return UIContextMenuConfiguration(identifier: nil,
  2670. previewProvider: nil) { _ in
  2671. UIMenu(title: "", children: children)
  2672. }
  2673. }
  2674. @objc func cancelAction() {
  2675. DispatchQueue.main.async {
  2676. if self.copySession {
  2677. self.copySession = false
  2678. } else if self.forwardSession {
  2679. self.forwardSession = false
  2680. } else if self.deleteSession {
  2681. self.deleteSession = false
  2682. }
  2683. let data = self.dataMessages.filter({ $0["isSelected"] as! Bool == true })
  2684. for i in 0..<data.count {
  2685. let idx = self.dataMessages.firstIndex(where: { $0["message_id"] as? String == data[i]["message_id"] as? String})
  2686. if idx != nil{
  2687. self.dataMessages[idx!]["isSelected"] = false
  2688. }
  2689. }
  2690. self.tableChatView.reloadData()
  2691. self.setRightButtonItem()
  2692. self.changeAppBar()
  2693. if self.isContactCenter || self.fromNotification {
  2694. let backButton = UIBarButtonItem(image: UIImage(systemName: "chevron.backward"), style: .plain, target: self, action: #selector(self.didTapExit))
  2695. self.navigationItem.leftBarButtonItem = backButton
  2696. }
  2697. self.containerMultpileSelectSession.removeFromSuperview()
  2698. self.checkNewMessage(tableView: self.tableChatView)
  2699. }
  2700. }
  2701. private func addMultipleSelectSession() {
  2702. view.addSubview(containerMultpileSelectSession)
  2703. containerMultpileSelectSession.translatesAutoresizingMaskIntoConstraints = false
  2704. NSLayoutConstraint.activate([
  2705. containerMultpileSelectSession.leadingAnchor.constraint(equalTo: self.view.leadingAnchor),
  2706. containerMultpileSelectSession.trailingAnchor.constraint(equalTo: self.view.trailingAnchor),
  2707. containerMultpileSelectSession.bottomAnchor.constraint(equalTo: self.view.bottomAnchor),
  2708. containerMultpileSelectSession.heightAnchor.constraint(equalToConstant: 120)
  2709. ])
  2710. containerMultpileSelectSession.backgroundColor = .white
  2711. addSubviewMultipleSession()
  2712. }
  2713. private func addSubviewMultipleSession() {
  2714. let container = UIView()
  2715. containerMultpileSelectSession.addSubview(container)
  2716. container.translatesAutoresizingMaskIntoConstraints = false
  2717. NSLayoutConstraint.activate([
  2718. container.leadingAnchor.constraint(equalTo: containerMultpileSelectSession.leadingAnchor),
  2719. container.trailingAnchor.constraint(equalTo:containerMultpileSelectSession.trailingAnchor),
  2720. container.bottomAnchor.constraint(equalTo: containerMultpileSelectSession.bottomAnchor),
  2721. container.heightAnchor.constraint(equalToConstant: 50)
  2722. ])
  2723. container.layer.shadowOpacity = 0.7
  2724. container.layer.shadowOffset = CGSize(width: 3, height: 3)
  2725. container.layer.shadowRadius = 3.0
  2726. container.layer.shadowColor = UIColor.black.cgColor
  2727. container.backgroundColor = .secondaryColor
  2728. let title = UILabel()
  2729. container.addSubview(title)
  2730. title.translatesAutoresizingMaskIntoConstraints = false
  2731. NSLayoutConstraint.activate([
  2732. title.centerXAnchor.constraint(equalTo: container.centerXAnchor),
  2733. title.centerYAnchor.constraint(equalTo:container.centerYAnchor),
  2734. ])
  2735. let countSelected = dataMessages.filter({ $0["isSelected"] as! Bool == true }).count
  2736. title.text = "\(countSelected) " + "Selected".localized()
  2737. title.textColor = .mainColor
  2738. title.font = UIFont.systemFont(ofSize: 15.0).bold
  2739. let button = UIImageView()
  2740. container.addSubview(button)
  2741. button.translatesAutoresizingMaskIntoConstraints = false
  2742. NSLayoutConstraint.activate([
  2743. button.leadingAnchor.constraint(equalTo: container.leadingAnchor, constant: 15),
  2744. button.centerYAnchor.constraint(equalTo:container.centerYAnchor),
  2745. button.widthAnchor.constraint(equalToConstant: 30),
  2746. button.heightAnchor.constraint(equalToConstant: 30),
  2747. ])
  2748. if copySession {
  2749. button.image = UIImage(systemName: "doc.on.doc")
  2750. if countSelected == 0 {
  2751. button.tintColor = .gray
  2752. } else {
  2753. button.tintColor = .mainColor
  2754. }
  2755. } else if forwardSession {
  2756. button.image = UIImage(systemName: "arrowshape.turn.up.right")
  2757. if countSelected == 0 {
  2758. button.tintColor = .gray
  2759. } else {
  2760. button.tintColor = .mainColor
  2761. }
  2762. } else if deleteSession {
  2763. button.image = UIImage(systemName: "trash")
  2764. if countSelected == 0 {
  2765. button.tintColor = .gray
  2766. } else {
  2767. button.tintColor = .red
  2768. }
  2769. }
  2770. let buttonGesture = UITapGestureRecognizer(target: self, action: #selector(sessionAction))
  2771. button.isUserInteractionEnabled = true
  2772. button.addGestureRecognizer(buttonGesture)
  2773. }
  2774. @objc func sessionAction() {
  2775. if copySession {
  2776. let dataMessages = self.dataMessages.filter({ $0["isSelected"] as! Bool == true })
  2777. let countSelected = dataMessages.count
  2778. if countSelected == 0 {
  2779. return
  2780. }
  2781. var text = ""
  2782. for i in 0..<countSelected {
  2783. let stringDate = (dataMessages[i]["server_date"] as! String)
  2784. let date = Date(milliseconds: Int64(stringDate)!)
  2785. let formatterDate = DateFormatter()
  2786. let formatterTime = DateFormatter()
  2787. formatterDate.dateFormat = "dd/MM/yy"
  2788. formatterDate.locale = NSLocale(localeIdentifier: "id") as Locale?
  2789. formatterTime.dateFormat = "HH:mm"
  2790. formatterTime.locale = NSLocale(localeIdentifier: "id") as Locale?
  2791. let dataProfile = getDataProfile(message_id: dataMessages[i]["message_id"] as! String)
  2792. if text.isEmpty {
  2793. text = "*[\(formatterDate.string(from: date as Date)) \(formatterTime.string(from: date as Date))] \(dataProfile["name"]!):*\n\(dataMessages[i]["message_text"] as! String)"
  2794. } else {
  2795. text = text + "\n\n*[\(formatterDate.string(from: date as Date)) \(formatterTime.string(from: date as Date))] \(dataProfile["name"]!):*\n\(dataMessages[i]["message_text"] as! String)"
  2796. }
  2797. }
  2798. text = text + "\n\n\nchat powered by Nexilis"
  2799. DispatchQueue.main.async {
  2800. UIPasteboard.general.string = text
  2801. self.showToast(message: "Text coppied to clipboard".localized(), font: UIFont.systemFont(ofSize: 12, weight: .medium), controller: self)
  2802. }
  2803. cancelAction()
  2804. } else if forwardSession {
  2805. let dataMessages = self.dataMessages.filter({ $0["isSelected"] as! Bool == true })
  2806. let countSelected = dataMessages.count
  2807. if countSelected == 0 {
  2808. return
  2809. }
  2810. let navigationController = AppStoryBoard.Palio.instance.instantiateViewController(withIdentifier: "contactChatNav") as! UINavigationController
  2811. navigationController.modalPresentationStyle = .custom
  2812. if let controller = navigationController.viewControllers.first as? ContactChatViewController {
  2813. controller.isChooser = { [weak self] scope, pin in
  2814. if scope == "3" {
  2815. let editorPersonalVC = AppStoryBoard.Palio.instance.instantiateViewController(identifier: "editorPersonalVC") as! EditorPersonal
  2816. editorPersonalVC.unique_l_pin = pin
  2817. editorPersonalVC.dataMessageForward = dataMessages
  2818. self?.navigationController?.replaceAllViewController(with: editorPersonalVC, animated: true)
  2819. } else {
  2820. let editorGroupVC = AppStoryBoard.Palio.instance.instantiateViewController(identifier: "editorGroupVC") as! EditorGroup
  2821. editorGroupVC.unique_l_pin = pin
  2822. editorGroupVC.dataMessageForward = dataMessages
  2823. self?.navigationController?.replaceAllViewController(with: editorGroupVC, animated: true)
  2824. }
  2825. }
  2826. }
  2827. self.present(navigationController, animated: true, completion: nil)
  2828. } else if deleteSession {
  2829. let dataMessages = self.dataMessages.filter({ $0["isSelected"] as! Bool == true })
  2830. let countSelected = dataMessages.count
  2831. if countSelected == 0 {
  2832. return
  2833. }
  2834. let alertController = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
  2835. if let action = self.actionDelete(for: "me", title: "Delete".localized() + " \(countSelected) " + "For Me".localized(), dataMessages: dataMessages) {
  2836. alertController.addAction(action)
  2837. }
  2838. let idMe = UserDefaults.standard.string(forKey: "me") as String?
  2839. let dataFilterFpin = dataMessages.filter({ $0["l_pin"] as? String == idMe})
  2840. let dataFilterLock = dataMessages.filter({ $0["lock"] as? String == "1"})
  2841. if dataFilterFpin.count == 0 && dataFilterLock.count == 0 {
  2842. if let action = self.actionDelete(for: "everyone", title: "Delete".localized() + " \(countSelected) " + "For Everyone".localized(), dataMessages: dataMessages) {
  2843. alertController.addAction(action)
  2844. }
  2845. }
  2846. alertController.addAction(UIAlertAction(title: "Cancel".localized(), style: .cancel, handler: nil))
  2847. self.present(alertController, animated: true)
  2848. }
  2849. }
  2850. private func getDataProfile(message_id: String) -> [String: String]{
  2851. var data: [String: String] = [:]
  2852. Database().database?.inTransaction({ fmdb, rollback in
  2853. if let c = Database().getRecords(fmdb: fmdb, query: "select f_display_name from MESSAGE where message_id = '\(message_id)'"), c.next() {
  2854. data["name"] = c.string(forColumnIndex: 0)!
  2855. c.close()
  2856. } else {
  2857. data["name"] = "Unknown".localized()
  2858. data["image_id"] = ""
  2859. }
  2860. })
  2861. return data
  2862. }
  2863. private func deleteMessage(l_pin: String, message_id: String, scope: String, type: String, chat: String) {
  2864. let tmessage = CoreMessage_TMessageBank.deleteMessage(l_pin: l_pin, messageId: message_id, scope: scope, type: type, chat: chat)
  2865. Nexilis.addQueueMessage(message: tmessage)
  2866. }
  2867. private func queryMessageReply(message_id: String) -> [String: Any?] {
  2868. var dataQuery: [String: Any] = [:]
  2869. Database().database?.inTransaction({ fmdb, rollback in
  2870. if let c = Database().getRecords(fmdb: fmdb, query: "SELECT message_id, f_pin, message_text, attachment_flag, thumb_id, image_id, video_id, file_id FROM MESSAGE where message_id='\(message_id)'"), c.next() {
  2871. dataQuery["message_id"] = c.string(forColumnIndex: 0)
  2872. dataQuery["f_pin"] = c.string(forColumnIndex: 1)
  2873. dataQuery["message_text"] = c.string(forColumnIndex: 2)
  2874. dataQuery["attachment_flag"] = c.string(forColumnIndex: 3)
  2875. dataQuery["thumb_id"] = c.string(forColumnIndex: 4)
  2876. dataQuery["image_id"] = c.string(forColumnIndex: 5)
  2877. dataQuery["video_id"] = c.string(forColumnIndex: 6)
  2878. dataQuery["file_id"] = c.string(forColumnIndex: 7)
  2879. c.close()
  2880. }
  2881. })
  2882. return dataQuery
  2883. }
  2884. @objc func segmentedControlValueChanged(_ sender: segmentedControllerObject) {
  2885. switch sender.selectedSegmentIndex {
  2886. case 0:
  2887. sender.navigation.viewControllers[0].children[1].view.isHidden = true
  2888. break;
  2889. case 1:
  2890. sender.navigation.viewControllers[0].children[1].view.isHidden = false
  2891. break;
  2892. default:
  2893. break;
  2894. }
  2895. }
  2896. private func copyOption(indexPath: IndexPath) -> UIMenu {
  2897. var ratingButtonTitles = ["Text".localized(), "Image".localized()]
  2898. if (dataMessages[indexPath.row]["message_text"] as! String).isEmpty {
  2899. ratingButtonTitles = ["Image".localized()]
  2900. }
  2901. let dataMessages = self.dataMessages.filter({ $0["chat_date"] as! String == dataDates[indexPath.section]})
  2902. let copyActions = ratingButtonTitles
  2903. .enumerated()
  2904. .map { index, title in
  2905. return UIAction(
  2906. title: title,
  2907. identifier: nil,
  2908. handler: {(_) in
  2909. if (dataMessages[indexPath.row]["message_text"] as! String).isEmpty {
  2910. DispatchQueue.main.async {
  2911. let nsDocumentDirectory = FileManager.SearchPathDirectory.documentDirectory
  2912. let nsUserDomainMask = FileManager.SearchPathDomainMask.userDomainMask
  2913. let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true)
  2914. if let dirPath = paths.first {
  2915. let imageURL = URL(fileURLWithPath: dirPath).appendingPathComponent(dataMessages[indexPath.row]["image_id"] as! String)
  2916. if FileManager.default.fileExists(atPath: imageURL.path) {
  2917. let image = UIImage(contentsOfFile: imageURL.path)
  2918. UIPasteboard.general.image = image
  2919. self.showToast(message: "Image coppied to clipboard".localized(), font: UIFont.systemFont(ofSize: 12, weight: .medium), controller: self)
  2920. }
  2921. }
  2922. }
  2923. return
  2924. }
  2925. if (index == 0) {
  2926. DispatchQueue.main.async {
  2927. UIPasteboard.general.string = dataMessages[indexPath.row]["message_text"] as? String
  2928. self.showToast(message: "Text coppied to clipboard".localized(), font: UIFont.systemFont(ofSize: 12, weight: .medium), controller: self)
  2929. }
  2930. } else {
  2931. DispatchQueue.main.async {
  2932. let nsDocumentDirectory = FileManager.SearchPathDirectory.documentDirectory
  2933. let nsUserDomainMask = FileManager.SearchPathDomainMask.userDomainMask
  2934. let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true)
  2935. if let dirPath = paths.first {
  2936. let imageURL = URL(fileURLWithPath: dirPath).appendingPathComponent(dataMessages[indexPath.row]["image_id"] as! String)
  2937. if FileManager.default.fileExists(atPath: imageURL.path) {
  2938. let image = UIImage(contentsOfFile: imageURL.path)
  2939. UIPasteboard.general.image = image
  2940. self.showToast(message: "Image coppied to clipboard".localized(), font: UIFont.systemFont(ofSize: 12, weight: .medium), controller: self)
  2941. }
  2942. }
  2943. }
  2944. }
  2945. self.dismissKeyboard()
  2946. })
  2947. }
  2948. return UIMenu(
  2949. title: "Copy".localized(),
  2950. image: UIImage(systemName: "doc.on.doc.fill"),
  2951. children: copyActions)
  2952. }
  2953. private func actionDelete(for type: String, title: String, dataMessages: [[String: Any?]]) -> UIAlertAction? {
  2954. return UIAlertAction(title: title, style: .destructive) { [unowned self] _ in
  2955. for i in 0..<dataMessages.count {
  2956. if (type == "me") {
  2957. self.deleteMessage(l_pin: dataMessages[i]["l_pin"] as! String, message_id: dataMessages[i]["message_id"] as! String, scope: "3", type: "1", chat: "")
  2958. let idx = self.dataMessages.firstIndex(where: { $0["message_id"] as? String == dataMessages[i]["message_id"] as? String})
  2959. if idx != nil {
  2960. self.dataMessages.remove(at: idx!)
  2961. if (idx == self.dataMessages.count - 1) {
  2962. NotificationCenter.default.post(name: NSNotification.Name(rawValue: "reloadTabChats"), object: nil, userInfo: nil)
  2963. }
  2964. for i in 0..<dataDates.count {
  2965. if self.dataMessages.filter({ $0["chat_date"] as! String == dataDates[i] }).count == 0 {
  2966. dataDates.remove(at: i)
  2967. }
  2968. }
  2969. }
  2970. } else {
  2971. self.deleteMessage(l_pin: dataMessages[i]["l_pin"] as! String, message_id: dataMessages[i]["message_id"] as! String, scope: "3", type: "2", chat: "")
  2972. let idx = self.dataMessages.firstIndex(where: { $0["message_id"] as? String == dataMessages[i]["message_id"] as? String})
  2973. if idx != nil {
  2974. self.dataMessages[idx!]["lock"] = "1"
  2975. self.dataMessages[idx!]["attachment_flag"] = "0"
  2976. self.dataMessages[idx!]["reff_id"] = ""
  2977. }
  2978. }
  2979. cancelAction()
  2980. }
  2981. }
  2982. }
  2983. private func updateProfile() {
  2984. let idMe = UserDefaults.standard.string(forKey: "me") as String?
  2985. DispatchQueue.global().async {
  2986. let message = CoreMessage_TMessageBank.getBatchBuddiesInfos(p_f_pin: idMe!, last_update: 0)
  2987. let _ = Nexilis.write(message: message)
  2988. }
  2989. }
  2990. private func generateQRCode(from string: String) -> UIImage? {
  2991. let data = string.data(using: String.Encoding.ascii)
  2992. if let filter = CIFilter(name: "CIQRCodeGenerator") {
  2993. filter.setValue(data, forKey: "inputMessage")
  2994. let transform = CGAffineTransform(scaleX: 3, y: 3)
  2995. if let output = filter.outputImage?.transformed(by: transform) {
  2996. return UIImage(ciImage: output)
  2997. }
  2998. }
  2999. return nil
  3000. }
  3001. @objc func deleteReplyView() {
  3002. if self.containerPreviewReply.isDescendant(of: self.viewTextfield) {
  3003. self.containerPreviewReply.subviews.forEach { $0.removeFromSuperview() }
  3004. self.containerPreviewReply.removeConstraints(self.containerPreviewReply.constraints)
  3005. self.containerPreviewReply.removeFromSuperview()
  3006. self.reffId = nil
  3007. UIView.animate(withDuration: 0.25, delay: 0.0, options: .curveEaseInOut, animations: {
  3008. self.constraintTopTextField.constant = self.constraintTopTextField.constant - 50
  3009. }, completion: nil)
  3010. }
  3011. }
  3012. @objc func deleteLinkPreview() {
  3013. if self.containerLink.isDescendant(of: self.viewTextfield) {
  3014. self.containerLink.subviews.forEach { $0.removeFromSuperview() }
  3015. self.containerLink.removeConstraints(self.containerLink.constraints)
  3016. self.containerLink.removeFromSuperview()
  3017. UIView.animate(withDuration: 0.25, delay: 0.0, options: .curveEaseInOut, animations: {
  3018. self.constraintTopTextField.constant = self.constraintTopTextField.constant - 80
  3019. }, completion: nil)
  3020. }
  3021. if self.reffId != nil {
  3022. self.bottomAnchorPreviewReply.isActive = false
  3023. self.bottomAnchorPreviewReply = self.containerPreviewReply.bottomAnchor.constraint(equalTo: self.textFieldSend.topAnchor)
  3024. self.bottomAnchorPreviewReply.isActive = true
  3025. }
  3026. }
  3027. }
  3028. //ECL
  3029. extension EditorPersonal: UICollectionViewDelegate, UICollectionViewDataSource {
  3030. public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
  3031. return 76
  3032. }
  3033. public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
  3034. let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cellSticker", for: indexPath)
  3035. if (cell.contentView.subviews.count > 0) {
  3036. cell.contentView.subviews.forEach({ $0.removeFromSuperview() })
  3037. }
  3038. let imageSticker = UIImageView()
  3039. cell.contentView.addSubview(imageSticker)
  3040. imageSticker.translatesAutoresizingMaskIntoConstraints = false
  3041. NSLayoutConstraint.activate([
  3042. imageSticker.topAnchor.constraint(equalTo: cell.contentView.topAnchor),
  3043. imageSticker.bottomAnchor.constraint(equalTo: cell.contentView.bottomAnchor),
  3044. imageSticker.leadingAnchor.constraint(equalTo: cell.contentView.leadingAnchor),
  3045. imageSticker.trailingAnchor.constraint(equalTo: cell.contentView.trailingAnchor)
  3046. ])
  3047. imageSticker.image = UIImage(named: stickers[indexPath.row], in: Bundle.resourceBundle(for: Nexilis.self), with: nil)
  3048. return cell
  3049. }
  3050. public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
  3051. sendChat(message_text: "sticker/\(stickers[indexPath.row])", attachment_flag: "11", viewController: self)
  3052. constraintBottomAttachment.constant = 0.0
  3053. self.viewSticker.removeConstraints(self.viewSticker.constraints)
  3054. self.viewSticker.removeFromSuperview()
  3055. }
  3056. }
  3057. //ETB
  3058. extension EditorPersonal: UITableViewDelegate, UITableViewDataSource {
  3059. // public func tableView(_ tableView: UITableView, didEndDisplaying cell: UITableViewCell, forRowAt indexPath: IndexPath) {
  3060. // checkNewMessage(tableView: tableView)
  3061. // }
  3062. public func scrollViewDidScroll(_ scrollView: UIScrollView) {
  3063. checkNewMessage(tableView: self.tableChatView)
  3064. }
  3065. public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
  3066. if isContactCenter && indexPath.row == 0 && isRequestContactCenter {
  3067. return
  3068. }
  3069. let dataMessages = self.dataMessages.filter({ $0["chat_date"] as! String == dataDates[indexPath.section] })
  3070. if copySession || forwardSession || deleteSession {
  3071. if (dataMessages[indexPath.row]["attachment_flag"] as! String != "0" || dataMessages[indexPath.row]["lock"] as? String == "1") && !forwardSession && !deleteSession {
  3072. return
  3073. }
  3074. if !(dataMessages[indexPath.row]["image_id"] as! String).isEmpty || !(dataMessages[indexPath.row]["video_id"] as! String).isEmpty || !(dataMessages[indexPath.row]["file_id"] as! String).isEmpty {
  3075. var file = dataMessages[indexPath.row]["image_id"] as! String
  3076. if file.isEmpty {
  3077. file = dataMessages[indexPath.row]["video_id"] as! String
  3078. if file.isEmpty {
  3079. file = dataMessages[indexPath.row]["file_id"] as! String
  3080. }
  3081. }
  3082. let nsDocumentDirectory = FileManager.SearchPathDirectory.documentDirectory
  3083. let nsUserDomainMask = FileManager.SearchPathDomainMask.userDomainMask
  3084. let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true)
  3085. if let dirPath = paths.first {
  3086. let fileURL = URL(fileURLWithPath: dirPath).appendingPathComponent(file)
  3087. if !FileManager.default.fileExists(atPath: fileURL.path) {
  3088. return
  3089. }
  3090. }
  3091. }
  3092. let idx = self.dataMessages.firstIndex(where: { $0["message_id"] as? String == dataMessages[indexPath.row]["message_id"] as? String})
  3093. if idx != nil {
  3094. self.dataMessages[idx!]["isSelected"] = !(self.dataMessages[idx!]["isSelected"] as! Bool)
  3095. self.tableChatView.reloadRows(at: [indexPath], with: .none)
  3096. }
  3097. containerMultpileSelectSession.subviews.forEach({ $0.removeFromSuperview() })
  3098. addSubviewMultipleSession()
  3099. return
  3100. }
  3101. let message = dataMessages[indexPath.row]
  3102. if let attachmentFlag = message["attachment_flag"], let attachmentFlag = attachmentFlag as? String {
  3103. if attachmentFlag == "27" {
  3104. let streamingController = QmeraCreateStreamingViewController()
  3105. if let messageText = message["message_text"],
  3106. let messageText = messageText as? String,
  3107. var json = try! JSONSerialization.jsonObject(with: messageText.data(using: String.Encoding.utf8)!, options: []) as? [String: Any] {
  3108. if json["blog"] == nil {
  3109. json["blog"] = message["blog_id"] ?? nil
  3110. }
  3111. streamingController.data = json
  3112. if json["by"] as? String != UserDefaults.standard.string(forKey: "me") as String? {
  3113. streamingController.isJoin = true
  3114. }
  3115. }
  3116. let streamingNav = UINavigationController(rootViewController: streamingController)
  3117. streamingNav.modalPresentationStyle = .custom
  3118. streamingNav.navigationBar.barTintColor = .mainColor
  3119. streamingNav.navigationBar.tintColor = .white
  3120. let textAttributes = [NSAttributedString.Key.foregroundColor:UIColor.white]
  3121. streamingNav.navigationBar.titleTextAttributes = textAttributes
  3122. streamingNav.view.backgroundColor = .mainColor
  3123. streamingNav.navigationBar.isTranslucent = false
  3124. navigationController?.present(streamingNav, animated: true, completion: nil)
  3125. } else if message["message_scope_id"] as? String == "18" {
  3126. let formView = FormEditor()
  3127. let messageText = message["message_text"] as! String
  3128. formView.jsonData = messageText
  3129. formView.dataMessage = message
  3130. formView.dataPerson = self.dataPerson
  3131. formView.modalPresentationStyle = .custom
  3132. formView.modalTransitionStyle = .crossDissolve
  3133. formView.view.backgroundColor = .black.withAlphaComponent(0.2)
  3134. self.present(formView, animated: true, completion: nil)
  3135. }
  3136. }
  3137. }
  3138. public func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
  3139. let containerView = UIView()
  3140. containerView.backgroundColor = .clear
  3141. let dateView = UIView()
  3142. containerView.addSubview(dateView)
  3143. dateView.translatesAutoresizingMaskIntoConstraints = false
  3144. var topAnchor = dateView.topAnchor.constraint(equalTo: containerView.topAnchor)
  3145. if section == 0 {
  3146. topAnchor = dateView.topAnchor.constraint(equalTo: containerView.topAnchor, constant: 10.0)
  3147. }
  3148. NSLayoutConstraint.activate([
  3149. topAnchor,
  3150. dateView.bottomAnchor.constraint(equalTo: containerView.bottomAnchor),
  3151. dateView.centerXAnchor.constraint(equalTo: containerView.centerXAnchor),
  3152. dateView.heightAnchor.constraint(equalToConstant: 30),
  3153. dateView.widthAnchor.constraint(greaterThanOrEqualToConstant: 60)
  3154. ])
  3155. dateView.backgroundColor = .orangeColor
  3156. dateView.layer.cornerRadius = 15.0
  3157. dateView.clipsToBounds = true
  3158. let labelDate = UILabel()
  3159. dateView.addSubview(labelDate)
  3160. labelDate.translatesAutoresizingMaskIntoConstraints = false
  3161. NSLayoutConstraint.activate([
  3162. labelDate.centerYAnchor.constraint(equalTo: dateView.centerYAnchor),
  3163. labelDate.centerXAnchor.constraint(equalTo: dateView.centerXAnchor),
  3164. labelDate.leadingAnchor.constraint(equalTo: dateView.leadingAnchor, constant: 10),
  3165. labelDate.trailingAnchor.constraint(equalTo: dateView.trailingAnchor, constant: -10),
  3166. ])
  3167. labelDate.textAlignment = .center
  3168. labelDate.textColor = .secondaryColor
  3169. labelDate.font = UIFont.systemFont(ofSize: 12, weight: .medium)
  3170. labelDate.text = dataDates[section]
  3171. return containerView
  3172. }
  3173. public func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
  3174. if section == 0 {
  3175. return 40
  3176. }
  3177. return 30
  3178. }
  3179. public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
  3180. let idMe = UserDefaults.standard.string(forKey: "me") as String?
  3181. let dataMessages = dataMessages.filter({$0["chat_date"] as! String == dataDates[indexPath.section]})
  3182. let profileMessage = UIImageView()
  3183. if isContactCenter && isRequestContactCenter && dataMessages[indexPath.row]["category_cc"] != nil {
  3184. let cell = UITableViewCell()
  3185. cell.backgroundColor = .clear
  3186. cell.selectionStyle = .none
  3187. if dataMessages[indexPath.row]["category_cc"] is [CategoryCC] {
  3188. let category_cc = dataMessages[indexPath.row]["category_cc"] as! [CategoryCC]
  3189. profileMessage.frame.size = CGSize(width: 35, height: 35)
  3190. cell.contentView.addSubview(profileMessage)
  3191. profileMessage.translatesAutoresizingMaskIntoConstraints = false
  3192. profileMessage.topAnchor.constraint(equalTo: cell.contentView.topAnchor, constant: 5).isActive = true
  3193. profileMessage.leadingAnchor.constraint(equalTo: cell.contentView.leadingAnchor, constant: 15).isActive = true
  3194. profileMessage.heightAnchor.constraint(equalToConstant: 37).isActive = true
  3195. profileMessage.widthAnchor.constraint(equalToConstant: 35).isActive = true
  3196. profileMessage.circle()
  3197. profileMessage.clipsToBounds = true
  3198. profileMessage.backgroundColor = .lightGray
  3199. profileMessage.image = UIImage(systemName: "person")
  3200. profileMessage.tintColor = .white
  3201. profileMessage.contentMode = .scaleAspectFit
  3202. getImage(name: dataPerson["picture"]!!, placeholderImage: UIImage(systemName: "person.circle.fill")!) { result, isDownloaded, image in
  3203. profileMessage.image = image
  3204. }
  3205. profileMessage.contentMode = .scaleAspectFill
  3206. let containerMessage = UIView()
  3207. cell.contentView.addSubview(containerMessage)
  3208. containerMessage.translatesAutoresizingMaskIntoConstraints = false
  3209. containerMessage.topAnchor.constraint(equalTo: cell.contentView.topAnchor, constant: 5).isActive = true
  3210. containerMessage.leadingAnchor.constraint(equalTo: profileMessage.trailingAnchor, constant: 5).isActive = true
  3211. containerMessage.trailingAnchor.constraint(lessThanOrEqualTo: cell.contentView.trailingAnchor, constant: -60).isActive = true
  3212. containerMessage.widthAnchor.constraint(greaterThanOrEqualToConstant: 46).isActive = true
  3213. containerMessage.backgroundColor = .grayColor
  3214. containerMessage.layer.cornerRadius = 10.0
  3215. containerMessage.layer.maskedCorners = [.layerMinXMaxYCorner, .layerMaxXMinYCorner, .layerMaxXMaxYCorner]
  3216. containerMessage.clipsToBounds = true
  3217. let timeMessage = UILabel()
  3218. cell.contentView.addSubview(timeMessage)
  3219. timeMessage.translatesAutoresizingMaskIntoConstraints = false
  3220. timeMessage.leadingAnchor.constraint(equalTo: containerMessage.trailingAnchor, constant: 8).isActive = true
  3221. let messageText = UILabel()
  3222. containerMessage.addSubview(messageText)
  3223. messageText.translatesAutoresizingMaskIntoConstraints = false
  3224. messageText.numberOfLines = 0
  3225. messageText.lineBreakMode = .byWordWrapping
  3226. containerMessage.addSubview(messageText)
  3227. messageText.topAnchor.constraint(equalTo: containerMessage.topAnchor, constant: 15).isActive = true
  3228. messageText.leadingAnchor.constraint(equalTo: containerMessage.leadingAnchor, constant: 15).isActive = true
  3229. messageText.bottomAnchor.constraint(equalTo: containerMessage.bottomAnchor, constant: -15).isActive = true
  3230. messageText.trailingAnchor.constraint(equalTo: containerMessage.trailingAnchor, constant: -15).isActive = true
  3231. if category_cc[0].id.contains("level0_") || dataMessages[indexPath.row]["attachment_flag"] != nil && dataMessages[indexPath.row]["attachment_flag"] as! String == "503" {
  3232. messageText.text = "Welcome to".localized() + " " + dataPerson["name"]!! + " " + "Contact Center".localized() + "\n" + "\n" + "Please select the communication media do you want".localized()
  3233. } else if category_cc[0].id.contains("level1_") {
  3234. messageText.text = "Please select your Consultation Topic:".localized()
  3235. } else if !category_cc[0].id.contains("level1_") && dataMessages[indexPath.row]["attachment_flag"] == nil {
  3236. messageText.text = "Please select the type of topic that you chosen".localized()
  3237. } else if dataMessages[indexPath.row]["attachment_flag"] != nil && dataMessages[indexPath.row]["attachment_flag"] as! String == "502" {
  3238. messageText.text = "Please select the information option:".localized()
  3239. } else {
  3240. messageText.text = "Sorry, currently all our representatives are busy helping other customers. Do you want us to get back to you as soon as one of them is available?".localized()
  3241. }
  3242. messageText.font = UIFont.italicSystemFont(ofSize: 12)
  3243. messageText.textColor = .black
  3244. let date = Date()
  3245. let formatter = DateFormatter()
  3246. formatter.dateFormat = "HH:mm"
  3247. formatter.locale = NSLocale(localeIdentifier: "id") as Locale?
  3248. timeMessage.text = formatter.string(from: date as Date)
  3249. timeMessage.font = UIFont.systemFont(ofSize: 10, weight: .medium)
  3250. timeMessage.textColor = .lightGray
  3251. let containerButton = UIView()
  3252. cell.contentView.addSubview(containerButton)
  3253. containerButton.translatesAutoresizingMaskIntoConstraints = false
  3254. containerButton.topAnchor.constraint(equalTo: containerMessage.bottomAnchor, constant: 5).isActive = true
  3255. containerButton.bottomAnchor.constraint(equalTo: cell.contentView.bottomAnchor, constant: -5).isActive = true
  3256. containerButton.leadingAnchor.constraint(equalTo: cell.contentView.leadingAnchor, constant: 55).isActive = true
  3257. containerButton.widthAnchor.constraint(equalToConstant: self.view!.frame.size.width * 0.65).isActive = true
  3258. containerButton.heightAnchor.constraint(greaterThanOrEqualToConstant: 45).isActive = true
  3259. containerButton.backgroundColor = .clear
  3260. timeMessage.bottomAnchor.constraint(equalTo:containerButton.topAnchor, constant: -5).isActive = true
  3261. for i in 0..<category_cc.count {
  3262. let buttonChat = UIButton()
  3263. containerButton.addSubview(buttonChat)
  3264. buttonChat.translatesAutoresizingMaskIntoConstraints = false
  3265. buttonChat.widthAnchor.constraint(equalToConstant: self.view!.frame.size.width * 0.65 / 2 - 10).isActive = true
  3266. buttonChat.heightAnchor.constraint(equalToConstant: 45).isActive = true
  3267. if i % 2 == 0 {
  3268. if i / 2 + 1 == 1 {
  3269. buttonChat.topAnchor.constraint(equalTo: containerButton.topAnchor, constant: 5).isActive = true
  3270. } else {
  3271. var constantTop = (i / 2 - 1) * 50
  3272. if constantTop == 0 {
  3273. constantTop = 55
  3274. } else {
  3275. constantTop = constantTop + 55
  3276. }
  3277. buttonChat.topAnchor.constraint(equalTo: containerButton.topAnchor, constant: CGFloat(constantTop)).isActive = true
  3278. }
  3279. if i == category_cc.count - 1 {
  3280. buttonChat.bottomAnchor.constraint(equalTo: containerButton.bottomAnchor, constant: -5).isActive = true
  3281. }
  3282. buttonChat.leadingAnchor.constraint(equalTo: containerButton.leadingAnchor, constant: 5).isActive = true
  3283. } else {
  3284. let newi = i - 1
  3285. if newi / 2 + 1 == 1 {
  3286. buttonChat.topAnchor.constraint(equalTo: containerButton.topAnchor, constant: 5).isActive = true
  3287. } else {
  3288. var constantTop = (newi / 2 - 1) * 50
  3289. if constantTop == 0 {
  3290. constantTop = 55
  3291. } else {
  3292. constantTop = constantTop + 55
  3293. }
  3294. buttonChat.topAnchor.constraint(equalTo: containerButton.topAnchor, constant: CGFloat(constantTop)).isActive = true
  3295. }
  3296. if i == category_cc.count - 1 {
  3297. buttonChat.bottomAnchor.constraint(equalTo: containerButton.bottomAnchor, constant: -5).isActive = true
  3298. }
  3299. buttonChat.trailingAnchor.constraint(equalTo: containerButton.trailingAnchor, constant: -5).isActive = true
  3300. }
  3301. if category_cc[i].isActive {
  3302. buttonChat.backgroundColor = .orangeBNI
  3303. }
  3304. buttonChat.setTitle(category_cc[i].service_name.localized(), for: .normal)
  3305. buttonChat.setTitleColor(.black, for: .normal)
  3306. buttonChat.titleLabel?.font = UIFont.systemFont(ofSize: 12)
  3307. buttonChat.titleLabel?.numberOfLines = 0
  3308. buttonChat.titleLabel?.textAlignment = .center
  3309. buttonChat.layer.borderWidth = 1
  3310. buttonChat.layer.borderColor = UIColor.lightGray.withAlphaComponent(0.3).cgColor
  3311. buttonChat.restorationIdentifier = "\(category_cc[i].id),\(category_cc[i].service_id)"
  3312. if dataMessages[indexPath.row]["attachment_flag"] != nil {
  3313. buttonChat.tag = Int(dataMessages[indexPath.row]["attachment_flag"] as! String)!
  3314. }
  3315. buttonChat.addTarget(self, action: #selector(ccAction(sender:)), for: .touchUpInside)
  3316. }
  3317. } else {
  3318. let messageWait = UILabel()
  3319. cell.contentView.addSubview(messageWait)
  3320. messageWait.translatesAutoresizingMaskIntoConstraints = false
  3321. messageWait.topAnchor.constraint(equalTo: cell.contentView.topAnchor).isActive = true
  3322. messageWait.bottomAnchor.constraint(equalTo: cell.contentView.bottomAnchor).isActive = true
  3323. messageWait.leftAnchor.constraint(equalTo: cell.contentView.leftAnchor, constant: 10).isActive = true
  3324. messageWait.rightAnchor.constraint(equalTo: cell.contentView.rightAnchor, constant: -10).isActive = true
  3325. messageWait.text = dataMessages[indexPath.row]["category_cc"] as? String ?? dataMessages[indexPath.row]["message_text"] as? String ?? ""
  3326. messageWait.numberOfLines = 0
  3327. messageWait.font = UIFont.systemFont(ofSize: 12)
  3328. messageWait.textColor = .gray
  3329. messageWait.textAlignment = .center
  3330. }
  3331. return cell
  3332. }
  3333. let thumbChat = (dataMessages[indexPath.row]["thumb_id"] as? String) ?? ""
  3334. let imageChat = (dataMessages[indexPath.row]["image_id"] as? String) ?? ""
  3335. let videoChat = (dataMessages[indexPath.row]["video_id"] as? String) ?? ""
  3336. let fileChat = (dataMessages[indexPath.row]["file_id"] as? String) ?? ""
  3337. let reffChat = (dataMessages[indexPath.row]["reff_id"] as? String) ?? ""
  3338. let cellMessage = UITableViewCell()
  3339. cellMessage.backgroundColor = .clear
  3340. cellMessage.selectionStyle = .none
  3341. let nameSender = UILabel()
  3342. if isContactCenter {
  3343. profileMessage.frame.size = CGSize(width: 35, height: 35)
  3344. cellMessage.contentView.addSubview(profileMessage)
  3345. profileMessage.translatesAutoresizingMaskIntoConstraints = false
  3346. profileMessage.topAnchor.constraint(equalTo: cellMessage.contentView.topAnchor, constant: 5).isActive = true
  3347. if (dataMessages[indexPath.row]["f_pin"] as? String == idMe) {
  3348. profileMessage.trailingAnchor.constraint(equalTo: cellMessage.contentView.trailingAnchor, constant: -15).isActive = true
  3349. } else {
  3350. if copySession || forwardSession || deleteSession {
  3351. profileMessage.leadingAnchor.constraint(equalTo: cellMessage.contentView.leadingAnchor, constant: 50).isActive = true
  3352. } else {
  3353. profileMessage.leadingAnchor.constraint(equalTo: cellMessage.contentView.leadingAnchor, constant: 15).isActive = true
  3354. }
  3355. }
  3356. profileMessage.heightAnchor.constraint(equalToConstant: 37).isActive = true
  3357. profileMessage.widthAnchor.constraint(equalToConstant: 35).isActive = true
  3358. profileMessage.circle()
  3359. profileMessage.clipsToBounds = true
  3360. profileMessage.backgroundColor = .lightGray
  3361. profileMessage.image = UIImage(systemName: "person")
  3362. profileMessage.tintColor = .white
  3363. profileMessage.contentMode = .scaleAspectFit
  3364. let user = User.getData(pin: dataMessages[indexPath.row]["f_pin"] as? String)
  3365. getImage(name: user?.thumb ?? "", placeholderImage: UIImage(systemName: "person.circle.fill")!, tableView: tableView, indexPath: indexPath) { result, isDownloaded, image in
  3366. profileMessage.image = image
  3367. }
  3368. profileMessage.contentMode = .scaleAspectFill
  3369. cellMessage.contentView.addSubview(nameSender)
  3370. nameSender.translatesAutoresizingMaskIntoConstraints = false
  3371. if markerCounter != nil && dataMessages[indexPath.row]["message_id"] as? String == markerCounter {
  3372. nameSender.topAnchor.constraint(equalTo: cellMessage.contentView.topAnchor, constant: 35).isActive = true
  3373. } else {
  3374. nameSender.topAnchor.constraint(equalTo: cellMessage.contentView.topAnchor, constant: 5).isActive = true
  3375. }
  3376. nameSender.font = UIFont.systemFont(ofSize: 12, weight: UIFont.Weight(800))
  3377. nameSender.text = user?.fullName ?? ""
  3378. nameSender.textAlignment = .right
  3379. if (dataMessages[indexPath.row]["f_pin"] as? String == idMe) {
  3380. nameSender.trailingAnchor.constraint(equalTo:profileMessage.leadingAnchor, constant: -5).isActive = true
  3381. nameSender.textColor = .systemBlue
  3382. } else {
  3383. nameSender.leadingAnchor.constraint(equalTo:profileMessage.trailingAnchor, constant: 5).isActive = true
  3384. nameSender.textColor = .orangeColor
  3385. }
  3386. }
  3387. let containerMessage = UIView()
  3388. if !copySession && !forwardSession && !deleteSession {
  3389. let interaction = UIContextMenuInteraction(delegate: self)
  3390. containerMessage.addInteraction(interaction)
  3391. containerMessage.isUserInteractionEnabled = true
  3392. }
  3393. cellMessage.contentView.addSubview(containerMessage)
  3394. containerMessage.translatesAutoresizingMaskIntoConstraints = false
  3395. let timeMessage = UILabel()
  3396. cellMessage.contentView.addSubview(timeMessage)
  3397. timeMessage.translatesAutoresizingMaskIntoConstraints = false
  3398. timeMessage.bottomAnchor.constraint(equalTo: cellMessage.contentView.bottomAnchor, constant: -5).isActive = true
  3399. let statusMessage = UIImageView()
  3400. if (dataMessages[indexPath.row]["attachment_flag"] as? String == "0" && dataMessages[indexPath.row]["lock"] as? String != "1") || forwardSession || deleteSession {
  3401. var showSelectedImage = true
  3402. if (!imageChat.isEmpty || !videoChat.isEmpty || !fileChat.isEmpty) && forwardSession {
  3403. var file = dataMessages[indexPath.row]["image_id"] as! String
  3404. if file.isEmpty {
  3405. file = dataMessages[indexPath.row]["video_id"] as! String
  3406. if file.isEmpty {
  3407. file = dataMessages[indexPath.row]["file_id"] as! String
  3408. }
  3409. }
  3410. let nsDocumentDirectory = FileManager.SearchPathDirectory.documentDirectory
  3411. let nsUserDomainMask = FileManager.SearchPathDomainMask.userDomainMask
  3412. let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true)
  3413. if let dirPath = paths.first {
  3414. let fileURL = URL(fileURLWithPath: dirPath).appendingPathComponent(file)
  3415. if !FileManager.default.fileExists(atPath: fileURL.path) {
  3416. showSelectedImage = false
  3417. }
  3418. }
  3419. }
  3420. if showSelectedImage {
  3421. let selectedImage = UIImageView()
  3422. cellMessage.contentView.addSubview(selectedImage)
  3423. selectedImage.translatesAutoresizingMaskIntoConstraints = false
  3424. selectedImage.frame.size = CGSize(width: 20, height: 20)
  3425. var leading = selectedImage.leadingAnchor.constraint(equalTo: cellMessage.contentView.leadingAnchor, constant: -20)
  3426. if copySession || forwardSession || deleteSession {
  3427. leading = selectedImage.leadingAnchor.constraint(equalTo: cellMessage.contentView.leadingAnchor, constant: 15)
  3428. }
  3429. NSLayoutConstraint.activate([
  3430. leading,
  3431. selectedImage.centerYAnchor.constraint(equalTo: cellMessage.contentView.centerYAnchor),
  3432. selectedImage.widthAnchor.constraint(equalToConstant: 20),
  3433. selectedImage.heightAnchor.constraint(equalToConstant: 20)
  3434. ])
  3435. selectedImage.circle()
  3436. selectedImage.layer.borderWidth = 2
  3437. selectedImage.layer.borderColor = UIColor.mainColor.cgColor
  3438. if dataMessages[indexPath.row]["isSelected"] as! Bool {
  3439. selectedImage.image = UIImage(systemName: "checkmark.circle.fill")
  3440. }
  3441. selectedImage.tintColor = .mainColor
  3442. }
  3443. }
  3444. if (dataMessages[indexPath.row]["f_pin"] as? String == idMe) {
  3445. containerMessage.leadingAnchor.constraint(greaterThanOrEqualTo: cellMessage.contentView.leadingAnchor, constant: 60).isActive = true
  3446. containerMessage.bottomAnchor.constraint(equalTo: cellMessage.contentView.bottomAnchor, constant: -5).isActive = true
  3447. if isContactCenter {
  3448. containerMessage.topAnchor.constraint(equalTo: nameSender.bottomAnchor).isActive = true
  3449. containerMessage.trailingAnchor.constraint(equalTo: profileMessage.leadingAnchor, constant: -5).isActive = true
  3450. } else {
  3451. containerMessage.topAnchor.constraint(equalTo: cellMessage.contentView.topAnchor, constant: 5).isActive = true
  3452. containerMessage.trailingAnchor.constraint(equalTo: cellMessage.contentView.trailingAnchor, constant: -15).isActive = true
  3453. }
  3454. containerMessage.widthAnchor.constraint(greaterThanOrEqualToConstant: 46).isActive = true
  3455. if (dataMessages[indexPath.row]["attachment_flag"] as? String == "11" && dataMessages[indexPath.row]["reff_id"]as? String == "") {
  3456. containerMessage.backgroundColor = .clear
  3457. } else {
  3458. containerMessage.backgroundColor = .blueBubbleColor
  3459. }
  3460. containerMessage.layer.cornerRadius = 10.0
  3461. containerMessage.layer.maskedCorners = [.layerMinXMaxYCorner, .layerMaxXMaxYCorner, .layerMinXMinYCorner]
  3462. containerMessage.clipsToBounds = true
  3463. timeMessage.trailingAnchor.constraint(equalTo: containerMessage.leadingAnchor, constant: -8).isActive = true
  3464. if dataMessages[indexPath.row]["lock"] == nil || dataMessages[indexPath.row]["lock"] as! String == "0" {
  3465. cellMessage.contentView.addSubview(statusMessage)
  3466. statusMessage.translatesAutoresizingMaskIntoConstraints = false
  3467. statusMessage.bottomAnchor.constraint(equalTo: timeMessage.topAnchor).isActive = true
  3468. statusMessage.trailingAnchor.constraint(equalTo: containerMessage.leadingAnchor, constant: -8).isActive = true
  3469. statusMessage.widthAnchor.constraint(equalToConstant: 15).isActive = true
  3470. statusMessage.heightAnchor.constraint(equalToConstant: 15).isActive = true
  3471. if (dataMessages[indexPath.row]["status"]! as! String == "1" || dataMessages[indexPath.row]["status"]! as! String == "2" ) {
  3472. statusMessage.image = UIImage(named: "checklist", in: Bundle.resourceBundle(for: Nexilis.self), with: nil)!.withTintColor(UIColor.lightGray)
  3473. } else if (dataMessages[indexPath.row]["status"]! as! String == "3") {
  3474. statusMessage.image = UIImage(named: "double-checklist", in: Bundle.resourceBundle(for: Nexilis.self), with: nil)!.withTintColor(UIColor.lightGray)
  3475. } else {
  3476. statusMessage.image = UIImage(named: "double-checklist", in: Bundle.resourceBundle(for: Nexilis.self), with: nil)!.withTintColor(UIColor.systemBlue)
  3477. }
  3478. }
  3479. } else {
  3480. if markerCounter != nil && dataMessages[indexPath.row]["message_id"] as? String == markerCounter {
  3481. if isContactCenter {
  3482. containerMessage.topAnchor.constraint(equalTo: nameSender.bottomAnchor).isActive = true
  3483. } else {
  3484. containerMessage.topAnchor.constraint(equalTo: cellMessage.contentView.topAnchor, constant: 35).isActive = true
  3485. }
  3486. let newMessagesView = UIView()
  3487. cellMessage.contentView.addSubview(newMessagesView)
  3488. newMessagesView.translatesAutoresizingMaskIntoConstraints = false
  3489. NSLayoutConstraint.activate([
  3490. newMessagesView.topAnchor.constraint(equalTo: newMessagesView.topAnchor),
  3491. newMessagesView.bottomAnchor.constraint(equalTo: containerMessage.topAnchor),
  3492. newMessagesView.centerXAnchor.constraint(equalTo: cellMessage.contentView.centerXAnchor),
  3493. newMessagesView.heightAnchor.constraint(equalToConstant: 30),
  3494. newMessagesView.widthAnchor.constraint(greaterThanOrEqualToConstant: 60)
  3495. ])
  3496. newMessagesView.backgroundColor = .greenColor
  3497. newMessagesView.layer.cornerRadius = 15.0
  3498. newMessagesView.clipsToBounds = true
  3499. let labelNewMessages = UILabel()
  3500. newMessagesView.addSubview(labelNewMessages)
  3501. labelNewMessages.translatesAutoresizingMaskIntoConstraints = false
  3502. NSLayoutConstraint.activate([
  3503. labelNewMessages.centerYAnchor.constraint(equalTo: newMessagesView.centerYAnchor),
  3504. labelNewMessages.centerXAnchor.constraint(equalTo: newMessagesView.centerXAnchor),
  3505. labelNewMessages.leadingAnchor.constraint(equalTo: newMessagesView.leadingAnchor, constant: 10),
  3506. labelNewMessages.trailingAnchor.constraint(equalTo: newMessagesView.trailingAnchor, constant: -10),
  3507. ])
  3508. labelNewMessages.textAlignment = .center
  3509. labelNewMessages.textColor = .secondaryColor
  3510. labelNewMessages.font = UIFont.systemFont(ofSize: 12, weight: .medium)
  3511. labelNewMessages.text = "Unread Messages".localized()
  3512. } else {
  3513. if isContactCenter {
  3514. containerMessage.topAnchor.constraint(equalTo: nameSender.bottomAnchor).isActive = true
  3515. } else {
  3516. containerMessage.topAnchor.constraint(equalTo: cellMessage.contentView.topAnchor, constant: 5).isActive = true
  3517. }
  3518. }
  3519. if isContactCenter {
  3520. containerMessage.leadingAnchor.constraint(equalTo: profileMessage.trailingAnchor, constant: 5).isActive = true
  3521. } else {
  3522. if copySession || forwardSession || deleteSession {
  3523. containerMessage.leadingAnchor.constraint(equalTo: cellMessage.contentView.leadingAnchor, constant: 50).isActive = true
  3524. } else {
  3525. containerMessage.leadingAnchor.constraint(equalTo: cellMessage.contentView.leadingAnchor, constant: 15).isActive = true
  3526. }
  3527. }
  3528. containerMessage.bottomAnchor.constraint(equalTo: cellMessage.contentView.bottomAnchor, constant: -5).isActive = true
  3529. containerMessage.trailingAnchor.constraint(lessThanOrEqualTo: cellMessage.contentView.trailingAnchor, constant: -60).isActive = true
  3530. containerMessage.widthAnchor.constraint(greaterThanOrEqualToConstant: 46).isActive = true
  3531. if dataMessages[indexPath.row]["attachment_flag"] as? String == "11" && dataMessages[indexPath.row]["reff_id"]as? String == "" && (dataMessages[indexPath.row]["lock"] == nil || dataMessages[indexPath.row]["lock"] as! String != "1") {
  3532. containerMessage.backgroundColor = .clear
  3533. } else {
  3534. containerMessage.backgroundColor = .grayColor
  3535. }
  3536. containerMessage.layer.cornerRadius = 10.0
  3537. containerMessage.layer.maskedCorners = [.layerMinXMaxYCorner, .layerMaxXMinYCorner, .layerMaxXMaxYCorner]
  3538. containerMessage.clipsToBounds = true
  3539. timeMessage.leadingAnchor.constraint(equalTo: containerMessage.trailingAnchor, constant: 8).isActive = true
  3540. }
  3541. if dataMessages[indexPath.row]["is_stared"] as? String == "1" && (dataMessages[indexPath.row]["lock"] == nil || dataMessages[indexPath.row]["lock"] as! String == "0") {
  3542. let imageStared = UIImageView()
  3543. cellMessage.contentView.addSubview(imageStared)
  3544. imageStared.translatesAutoresizingMaskIntoConstraints = false
  3545. if (dataMessages[indexPath.row]["f_pin"] as? String == idMe) {
  3546. imageStared.bottomAnchor.constraint(equalTo: statusMessage.topAnchor).isActive = true
  3547. imageStared.trailingAnchor.constraint(equalTo: containerMessage.leadingAnchor, constant: -8).isActive = true
  3548. } else {
  3549. imageStared.bottomAnchor.constraint(equalTo: timeMessage.topAnchor).isActive = true
  3550. imageStared.leadingAnchor.constraint(equalTo: containerMessage.trailingAnchor, constant: 8).isActive = true
  3551. }
  3552. imageStared.widthAnchor.constraint(equalToConstant: 15).isActive = true
  3553. imageStared.heightAnchor.constraint(equalToConstant: 15).isActive = true
  3554. imageStared.image = UIImage(systemName: "star.fill")
  3555. imageStared.backgroundColor = .clear
  3556. imageStared.tintColor = .systemYellow
  3557. }
  3558. let messageText = UILabel()
  3559. messageText.numberOfLines = 0
  3560. messageText.lineBreakMode = .byWordWrapping
  3561. containerMessage.addSubview(messageText)
  3562. messageText.translatesAutoresizingMaskIntoConstraints = false
  3563. let topMarginText = messageText.topAnchor.constraint(equalTo: containerMessage.topAnchor, constant: 15)
  3564. topMarginText.isActive = true
  3565. messageText.textColor = .black
  3566. if dataMessages[indexPath.row]["attachment_flag"] as? String == "27" || dataMessages[indexPath.row]["attachment_flag"] as? String == "26" || dataMessages[indexPath.row]["message_scope_id"] as? String == "18" {
  3567. messageText.leadingAnchor.constraint(equalTo: containerMessage.leadingAnchor, constant: 85).isActive = true
  3568. let imageLS = UIImageView()
  3569. containerMessage.addSubview(imageLS)
  3570. imageLS.translatesAutoresizingMaskIntoConstraints = false
  3571. NSLayoutConstraint.activate([
  3572. imageLS.leadingAnchor.constraint(equalTo: containerMessage.leadingAnchor, constant: 15.0),
  3573. imageLS.trailingAnchor.constraint(equalTo: messageText.leadingAnchor, constant: -10.0),
  3574. imageLS.centerYAnchor.constraint(equalTo: containerMessage.centerYAnchor),
  3575. imageLS.heightAnchor.constraint(equalToConstant: 60.0)
  3576. ])
  3577. if dataMessages[indexPath.row]["attachment_flag"] as! String == "26" {
  3578. imageLS.image = UIImage(named: "pb_seminar_wpr", in: Bundle.resourceBundle(for: Nexilis.self), with: nil)
  3579. } else if dataMessages[indexPath.row]["attachment_flag"] as! String == "27" {
  3580. imageLS.image = UIImage(named: "pb_live_tv", in: Bundle.resourceBundle(for: Nexilis.self), with: nil)
  3581. } else if dataMessages[indexPath.row]["message_scope_id"] as? String == "18" {
  3582. imageLS.image = UIImage(systemName: "doc.richtext.fill")
  3583. imageLS.tintColor = .mainColor
  3584. }
  3585. } else {
  3586. messageText.leadingAnchor.constraint(equalTo: containerMessage.leadingAnchor, constant: 15).isActive = true
  3587. }
  3588. if dataMessages[indexPath.row]["f_pin"] as? String == "-999" && (dataMessages[indexPath.row]["blog_id"] as? String) != nil && !(dataMessages[indexPath.row]["blog_id"] as! String).isEmpty && (dataMessages[indexPath.row]["message_text"] as! String).contains("Berikut QR Code dan detil booking Anda") {
  3589. messageText.bottomAnchor.constraint(equalTo: containerMessage.bottomAnchor, constant: -115).isActive = true
  3590. let imageQR = UIImageView()
  3591. containerMessage.addSubview(imageQR)
  3592. imageQR.translatesAutoresizingMaskIntoConstraints = false
  3593. NSLayoutConstraint.activate([
  3594. imageQR.centerXAnchor.constraint(equalTo: containerMessage.centerXAnchor),
  3595. imageQR.topAnchor.constraint(equalTo: messageText.bottomAnchor),
  3596. imageQR.widthAnchor.constraint(equalToConstant: 100.0),
  3597. imageQR.heightAnchor.constraint(equalToConstant: 100.0)
  3598. ])
  3599. imageQR.image = generateQRCode(from: dataMessages[indexPath.row]["blog_id"] as! String)
  3600. } else {
  3601. messageText.bottomAnchor.constraint(equalTo: containerMessage.bottomAnchor, constant: -15).isActive = true
  3602. }
  3603. messageText.trailingAnchor.constraint(equalTo: containerMessage.trailingAnchor, constant: -15).isActive = true
  3604. var textChat = (dataMessages[indexPath.row]["message_text"] as? String) ?? ""
  3605. if (dataMessages[indexPath.row]["lock"] != nil && (dataMessages[indexPath.row]["lock"])! as? String == "1") {
  3606. if (dataMessages[indexPath.row]["f_pin"] as? String == idMe) {
  3607. textChat = "🚫 _"+"You were deleted this message".localized()+"_"
  3608. } else {
  3609. textChat = "🚫 _"+"This message was deleted".localized()+"_"
  3610. }
  3611. }
  3612. let imageSticker = UIImageView()
  3613. if let attachmentFlag = dataMessages[indexPath.row]["attachment_flag"], let attachmentFlag = attachmentFlag as? String {
  3614. if attachmentFlag == "27" || attachmentFlag == "26" { // live streaming
  3615. let data = textChat
  3616. if let json = try! JSONSerialization.jsonObject(with: data.data(using: String.Encoding.utf8)!, options: []) as? [String: Any] {
  3617. Database().database?.inTransaction({ fmdb, rollback in
  3618. let title = json["title"] as? String ?? ""
  3619. let description = json["description"] as? String ?? ""
  3620. let start = json["time"] as? Int64 ?? 0
  3621. let by = json["by"] as? String ?? ""
  3622. var type = "*Live Streaming*"
  3623. if attachmentFlag == "26" {
  3624. type = "*Seminar*"
  3625. }
  3626. if let c = Database().getRecords(fmdb: fmdb, query: "select first_name || ' ' || last_name from BUDDY where f_pin = '\(by)'"), c.next() {
  3627. let name = c.string(forColumnIndex: 0)!
  3628. messageText.attributedText = "\(type) \nTitle: \(title) \nDescription: \(description) \nStart: \(Date(milliseconds: start).format(dateFormat: "dd/MM/yyyy HH:mm")) \nBroadcaster: \(name)".richText()
  3629. c.close()
  3630. } else {
  3631. messageText.attributedText = ("\(type) \nTitle: \(title) \nDescription: \(description) \nStart: \(Date(milliseconds: start).format(dateFormat: "dd/MM/yyyy HH:mm"))").richText()
  3632. }
  3633. })
  3634. }
  3635. }
  3636. else if attachmentFlag == "11" && (dataMessages[indexPath.row]["lock"] == nil || dataMessages[indexPath.row]["lock"] as! String != "1") {
  3637. messageText.text = ""
  3638. topMarginText.constant = topMarginText.constant + 100
  3639. containerMessage.addSubview(imageSticker)
  3640. imageSticker.translatesAutoresizingMaskIntoConstraints = false
  3641. if (reffChat == "") {
  3642. imageSticker.topAnchor.constraint(equalTo: containerMessage.topAnchor, constant: 15).isActive = true
  3643. imageSticker.widthAnchor.constraint(equalToConstant: 80).isActive = true
  3644. } else {
  3645. imageSticker.widthAnchor.constraint(greaterThanOrEqualToConstant: 80).isActive = true
  3646. }
  3647. imageSticker.leadingAnchor.constraint(equalTo: containerMessage.leadingAnchor, constant: 15).isActive = true
  3648. imageSticker.bottomAnchor.constraint(equalTo: messageText.topAnchor, constant: -5).isActive = true
  3649. imageSticker.trailingAnchor.constraint(equalTo: containerMessage.trailingAnchor, constant: -15).isActive = true
  3650. imageSticker.image = UIImage(named: (textChat.components(separatedBy: "/")[1]), in: Bundle.resourceBundle(for: Nexilis.self), with: nil)
  3651. imageSticker.contentMode = .scaleAspectFit
  3652. } else if dataMessages[indexPath.row]["message_scope_id"] as! String == "18" {
  3653. let data = textChat
  3654. if let jsonForm = try! JSONSerialization.jsonObject(with: data.data(using: String.Encoding.utf8)!, options: []) as? [String: Any] {
  3655. let form_title = jsonForm["form_title"] as! String
  3656. let club_type = jsonForm["club_type"] as! String
  3657. let province = jsonForm["province"] as! String
  3658. let club = jsonForm["club"] as! String
  3659. messageText.attributedText = "*\(form_title.replacingOccurrences(of: "+", with: " "))* \nClub Type: \(club_type) \nProvince: \(province) \nClub Name: \(club) ".richText()
  3660. }
  3661. }
  3662. else {
  3663. messageText.attributedText = textChat.richText()
  3664. }
  3665. } else {
  3666. messageText.attributedText = textChat.richText()
  3667. }
  3668. messageText.isUserInteractionEnabled = true
  3669. if !textChat.isEmpty {
  3670. let listText = textChat.split(separator: " ")
  3671. for i in 0...listText.count - 1 {
  3672. if listText[i].lowercased().checkStartWithLink() {
  3673. if ((listText[i].lowercased().starts(with: "www.") && listText[i].lowercased().split(separator: ".").count >= 3) || (!listText[i].lowercased().starts(with: "www.") && listText[i].lowercased().split(separator: ".").count >= 2)) && listText[i].lowercased().split(separator: ".").last!.count >= 2 {
  3674. let objectGesture = ObjectGesture(target: self, action: #selector(tapMessageText(_:)))
  3675. objectGesture.message_id = "\(listText[i])"
  3676. messageText.addGestureRecognizer(objectGesture)
  3677. }
  3678. }
  3679. }
  3680. }
  3681. let stringDate = (dataMessages[indexPath.row]["server_date"] as? String) ?? ""
  3682. if !stringDate.isEmpty {
  3683. let date = Date(milliseconds: Int64(stringDate) ?? 100)
  3684. let formatter = DateFormatter()
  3685. formatter.dateFormat = "HH:mm"
  3686. formatter.locale = NSLocale(localeIdentifier: "id") as Locale?
  3687. timeMessage.text = formatter.string(from: date as Date)
  3688. timeMessage.font = UIFont.systemFont(ofSize: 10, weight: .medium)
  3689. timeMessage.textColor = .lightGray
  3690. }
  3691. let imageThumb = UIImageView()
  3692. let containerViewFile = UIView()
  3693. if (!thumbChat.isEmpty && (dataMessages[indexPath.row]["lock"] == nil || dataMessages[indexPath.row]["lock"] as! String != "1")) {
  3694. topMarginText.constant = topMarginText.constant + 205
  3695. containerMessage.addSubview(imageThumb)
  3696. imageThumb.translatesAutoresizingMaskIntoConstraints = false
  3697. let data = queryMessageReply(message_id: reffChat)
  3698. if (data.count == 0) {
  3699. imageThumb.topAnchor.constraint(equalTo: containerMessage.topAnchor, constant: 15).isActive = true
  3700. }
  3701. imageThumb.leadingAnchor.constraint(equalTo: containerMessage.leadingAnchor, constant: 15).isActive = true
  3702. imageThumb.bottomAnchor.constraint(equalTo: messageText.topAnchor, constant: -5).isActive = true
  3703. imageThumb.trailingAnchor.constraint(equalTo: containerMessage.trailingAnchor, constant: -15).isActive = true
  3704. imageThumb.widthAnchor.constraint(equalToConstant: self.view.frame.size.width * 0.6).isActive = true
  3705. imageThumb.layer.cornerRadius = 5.0
  3706. imageThumb.clipsToBounds = true
  3707. imageThumb.contentMode = .scaleAspectFill
  3708. let nsDocumentDirectory = FileManager.SearchPathDirectory.documentDirectory
  3709. let nsUserDomainMask = FileManager.SearchPathDomainMask.userDomainMask
  3710. let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true)
  3711. if let dirPath = paths.first {
  3712. let thumbURL = URL(fileURLWithPath: dirPath).appendingPathComponent(thumbChat)
  3713. let image = UIImage(contentsOfFile: thumbURL.path)
  3714. imageThumb.image = image
  3715. let videoURL = URL(fileURLWithPath: dirPath).appendingPathComponent(videoChat)
  3716. let imageURL = URL(fileURLWithPath: dirPath).appendingPathComponent(imageChat)
  3717. if !FileManager.default.fileExists(atPath: imageURL.path) || !FileManager.default.fileExists(atPath: videoURL.path) {
  3718. let blurEffect = UIBlurEffect(style: UIBlurEffect.Style.light)
  3719. let blurEffectView = UIVisualEffectView(effect: blurEffect)
  3720. blurEffectView.frame = CGRect(x: 0, y: 0, width: imageThumb.frame.size.width, height: imageThumb.frame.size.height)
  3721. blurEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
  3722. imageThumb.addSubview(blurEffectView)
  3723. if !imageChat.isEmpty {
  3724. let imageDownload = UIImageView(image: UIImage(systemName: "arrow.down.circle.fill", withConfiguration: UIImage.SymbolConfiguration(pointSize: 50, weight: .bold, scale: .default)))
  3725. imageThumb.addSubview(imageDownload)
  3726. imageDownload.tintColor = .black.withAlphaComponent(0.3)
  3727. imageDownload.translatesAutoresizingMaskIntoConstraints = false
  3728. imageDownload.centerXAnchor.constraint(equalTo: imageThumb.centerXAnchor).isActive = true
  3729. imageDownload.centerYAnchor.constraint(equalTo: imageThumb.centerYAnchor).isActive = true
  3730. }
  3731. }
  3732. }
  3733. if (videoChat != "") {
  3734. let imagePlay = UIImageView(image: UIImage(systemName: "play.fill", withConfiguration: UIImage.SymbolConfiguration(pointSize: 20, weight: .bold, scale: .default))?.imageWithInsets(insets: UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10))?.withTintColor(.white))
  3735. imagePlay.circle()
  3736. imageThumb.addSubview(imagePlay)
  3737. imagePlay.backgroundColor = .black.withAlphaComponent(0.3)
  3738. imagePlay.translatesAutoresizingMaskIntoConstraints = false
  3739. imagePlay.centerXAnchor.constraint(equalTo: imageThumb.centerXAnchor).isActive = true
  3740. imagePlay.centerYAnchor.constraint(equalTo: imageThumb.centerYAnchor).isActive = true
  3741. }
  3742. if (dataMessages[indexPath.row]["progress"] as! Double != 100.0 && dataMessages[indexPath.row]["f_pin"] as? String == idMe) {
  3743. let container = UIView()
  3744. imageThumb.addSubview(container)
  3745. container.translatesAutoresizingMaskIntoConstraints = false
  3746. container.bottomAnchor.constraint(equalTo: imageThumb.bottomAnchor, constant: -10).isActive = true
  3747. container.leadingAnchor.constraint(equalTo: imageThumb.leadingAnchor, constant: 10).isActive = true
  3748. container.widthAnchor.constraint(equalToConstant: 30).isActive = true
  3749. container.heightAnchor.constraint(equalToConstant: 30).isActive = true
  3750. container.backgroundColor = .white.withAlphaComponent(0.1)
  3751. let circlePath = UIBezierPath(arcCenter: CGPoint(x: 10, y: 20), radius: 15, startAngle: -(.pi / 2), endAngle: .pi * 2, clockwise: true)
  3752. let trackShape = CAShapeLayer()
  3753. trackShape.path = circlePath.cgPath
  3754. trackShape.fillColor = UIColor.black.withAlphaComponent(0.3).cgColor
  3755. trackShape.lineWidth = 3
  3756. trackShape.strokeColor = UIColor.blueBubbleColor.withAlphaComponent(0.3).cgColor
  3757. container.backgroundColor = .clear
  3758. container.layer.addSublayer(trackShape)
  3759. let shapeLoading = CAShapeLayer()
  3760. shapeLoading.path = circlePath.cgPath
  3761. shapeLoading.fillColor = UIColor.clear.cgColor
  3762. shapeLoading.lineWidth = 3
  3763. shapeLoading.strokeEnd = 0
  3764. shapeLoading.strokeColor = UIColor.blueBubbleColor.cgColor
  3765. container.layer.addSublayer(shapeLoading)
  3766. let imageupload = UIImageView(image: UIImage(systemName: "arrow.up", withConfiguration: UIImage.SymbolConfiguration(pointSize: 10, weight: .bold, scale: .default)))
  3767. imageupload.tintColor = .white
  3768. container.addSubview(imageupload)
  3769. imageupload.translatesAutoresizingMaskIntoConstraints = false
  3770. imageupload.bottomAnchor.constraint(equalTo: imageThumb.bottomAnchor, constant: -10).isActive = true
  3771. imageupload.leadingAnchor.constraint(equalTo: imageThumb.leadingAnchor, constant: 10).isActive = true
  3772. imageupload.widthAnchor.constraint(equalToConstant: 20).isActive = true
  3773. imageupload.heightAnchor.constraint(equalToConstant: 20).isActive = true
  3774. }
  3775. if !copySession && !forwardSession && !deleteSession {
  3776. let objectTap = ObjectGesture(target: self, action: #selector(contentMessageTapped(_:)))
  3777. imageThumb.isUserInteractionEnabled = true
  3778. imageThumb.addGestureRecognizer(objectTap)
  3779. objectTap.image_id = imageChat
  3780. objectTap.video_id = videoChat
  3781. objectTap.imageView = imageThumb
  3782. objectTap.indexPath = indexPath
  3783. }
  3784. }
  3785. if (fileChat != "" && (dataMessages[indexPath.row]["lock"] == nil || dataMessages[indexPath.row]["lock"] as! String != "1") && dataMessages[indexPath.row]["message_scope_id"] as! String != "18") {
  3786. topMarginText.constant = topMarginText.constant + 55
  3787. let nsDocumentDirectory = FileManager.SearchPathDirectory.documentDirectory
  3788. let nsUserDomainMask = FileManager.SearchPathDomainMask.userDomainMask
  3789. let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true)
  3790. let arrExtFile = (textChat.components(separatedBy: "|")[0]).split(separator: ".")
  3791. let finalExtFile = arrExtFile[arrExtFile.count - 1]
  3792. if let dirPath = paths.first {
  3793. let fileURL = URL(fileURLWithPath: dirPath).appendingPathComponent(fileChat)
  3794. if let dataFile = try? Data(contentsOf: fileURL) {
  3795. var sizeOfFile = Int(dataFile.count / 1000000)
  3796. if (sizeOfFile < 1) {
  3797. sizeOfFile = Int(dataFile.count / 1000)
  3798. if (finalExtFile.count > 4) {
  3799. messageText.text = "\(sizeOfFile) kB \u{2022} TXT"
  3800. }else {
  3801. messageText.text = "\(sizeOfFile) kB \u{2022} \(finalExtFile.uppercased())"
  3802. }
  3803. } else {
  3804. if (finalExtFile.count > 4) {
  3805. messageText.text = "\(sizeOfFile) MB \u{2022} TXT"
  3806. }else {
  3807. messageText.text = "\(sizeOfFile) MB \u{2022} \(finalExtFile.uppercased())"
  3808. }
  3809. }
  3810. } else {
  3811. messageText.text = ""
  3812. }
  3813. }
  3814. containerMessage.addSubview(containerViewFile)
  3815. containerViewFile.translatesAutoresizingMaskIntoConstraints = false
  3816. let data = queryMessageReply(message_id: reffChat)
  3817. if (data.count == 0) {
  3818. containerViewFile.topAnchor.constraint(equalTo: containerMessage.topAnchor, constant: 15).isActive = true
  3819. }
  3820. containerViewFile.leadingAnchor.constraint(equalTo: containerMessage.leadingAnchor, constant: 15).isActive = true
  3821. containerViewFile.bottomAnchor.constraint(equalTo:messageText.topAnchor, constant: -5).isActive = true
  3822. containerViewFile.trailingAnchor.constraint(equalTo: containerMessage.trailingAnchor, constant: -15).isActive = true
  3823. containerViewFile.heightAnchor.constraint(equalToConstant: 50).isActive = true
  3824. containerViewFile.backgroundColor = .black.withAlphaComponent(0.2)
  3825. containerViewFile.layer.cornerRadius = 5.0
  3826. containerViewFile.clipsToBounds = true
  3827. let imageFile = UIImageView(image: UIImage(systemName: "doc.fill", withConfiguration: UIImage.SymbolConfiguration(pointSize: 30, weight: .bold, scale: .default)))
  3828. containerViewFile.addSubview(imageFile)
  3829. let nameFile = UILabel()
  3830. containerViewFile.addSubview(nameFile)
  3831. imageFile.translatesAutoresizingMaskIntoConstraints = false
  3832. imageFile.leadingAnchor.constraint(equalTo: containerViewFile.leadingAnchor, constant: 5).isActive = true
  3833. imageFile.trailingAnchor.constraint(equalTo: nameFile.leadingAnchor, constant: -5).isActive = true
  3834. imageFile.centerYAnchor.constraint(equalTo: containerViewFile.centerYAnchor).isActive = true
  3835. imageFile.widthAnchor.constraint(equalToConstant: 30).isActive = true
  3836. imageFile.heightAnchor.constraint(equalToConstant: 30).isActive = true
  3837. imageFile.tintColor = .docColor
  3838. nameFile.translatesAutoresizingMaskIntoConstraints = false
  3839. nameFile.centerYAnchor.constraint(equalTo: containerViewFile.centerYAnchor).isActive = true
  3840. nameFile.widthAnchor.constraint(lessThanOrEqualToConstant: 200).isActive = true
  3841. nameFile.font = UIFont.systemFont(ofSize: 12, weight: .medium)
  3842. nameFile.textColor = .white
  3843. nameFile.text = textChat.components(separatedBy: "|")[0]
  3844. if (dataMessages[indexPath.row]["progress"] as! Double != 100.0) {
  3845. let containerLoading = UIView()
  3846. containerViewFile.addSubview(containerLoading)
  3847. containerLoading.translatesAutoresizingMaskIntoConstraints = false
  3848. containerLoading.centerYAnchor.constraint(equalTo: containerViewFile.centerYAnchor).isActive = true
  3849. containerLoading.leadingAnchor.constraint(equalTo: nameFile.trailingAnchor, constant: 5).isActive = true
  3850. containerLoading.trailingAnchor.constraint(equalTo: containerViewFile.trailingAnchor, constant: -5).isActive = true
  3851. containerLoading.widthAnchor.constraint(equalToConstant: 30).isActive = true
  3852. containerLoading.heightAnchor.constraint(equalToConstant: 30).isActive = true
  3853. let circlePath = UIBezierPath(arcCenter: CGPoint(x: 15, y: 15), radius: 10, startAngle: -(.pi / 2), endAngle: .pi * 2, clockwise: true)
  3854. let trackShape = CAShapeLayer()
  3855. trackShape.path = circlePath.cgPath
  3856. trackShape.fillColor = UIColor.clear.cgColor
  3857. trackShape.lineWidth = 5
  3858. trackShape.strokeColor = UIColor.blueBubbleColor.withAlphaComponent(0.3).cgColor
  3859. containerLoading.layer.addSublayer(trackShape)
  3860. let shapeLoading = CAShapeLayer()
  3861. shapeLoading.path = circlePath.cgPath
  3862. shapeLoading.fillColor = UIColor.clear.cgColor
  3863. shapeLoading.lineWidth = 3
  3864. shapeLoading.strokeEnd = 0
  3865. shapeLoading.strokeColor = UIColor.secondaryColor.cgColor
  3866. containerLoading.layer.addSublayer(shapeLoading)
  3867. var imageupload = UIImageView(image: UIImage(systemName: "arrow.up", withConfiguration: UIImage.SymbolConfiguration(pointSize: 10, weight: .bold, scale: .default)))
  3868. if dataMessages[indexPath.row]["f_pin"] as? String != idMe {
  3869. imageupload = UIImageView(image: UIImage(systemName: "arrow.down", withConfiguration: UIImage.SymbolConfiguration(pointSize: 10, weight: .bold, scale: .default)))
  3870. shapeLoading.strokeColor = UIColor.blueBubbleColor.cgColor
  3871. }
  3872. imageupload.tintColor = .white
  3873. containerLoading.addSubview(imageupload)
  3874. imageupload.translatesAutoresizingMaskIntoConstraints = false
  3875. imageupload.centerYAnchor.constraint(equalTo: containerLoading.centerYAnchor).isActive = true
  3876. imageupload.centerXAnchor.constraint(equalTo: containerLoading.centerXAnchor).isActive = true
  3877. } else {
  3878. nameFile.trailingAnchor.constraint(equalTo: containerViewFile.trailingAnchor, constant: -5).isActive = true
  3879. }
  3880. if !copySession && !forwardSession && !deleteSession {
  3881. let objectTap = ObjectGesture(target: self, action: #selector(contentMessageTapped(_:)))
  3882. containerViewFile.addGestureRecognizer(objectTap)
  3883. objectTap.containerFile = containerViewFile
  3884. objectTap.labelFile = nameFile
  3885. objectTap.file_id = fileChat
  3886. objectTap.indexPath = indexPath
  3887. }
  3888. }
  3889. if (reffChat != "" && dataMessages[indexPath.row]["message_scope_id"] as! String != "18") {
  3890. let data = queryMessageReply(message_id: reffChat)
  3891. if data.count != 0 {
  3892. topMarginText.constant = topMarginText.constant + 55
  3893. let containerReply = UIView()
  3894. containerMessage.addSubview(containerReply)
  3895. containerReply.translatesAutoresizingMaskIntoConstraints = false
  3896. containerReply.leadingAnchor.constraint(equalTo: containerMessage.leadingAnchor, constant: 15).isActive = true
  3897. containerReply.topAnchor.constraint(equalTo: containerMessage.topAnchor, constant: 15).isActive = true
  3898. if thumbChat != "" && (dataMessages[indexPath.row]["lock"] == nil || dataMessages[indexPath.row]["lock"] as! String != "1") {
  3899. containerReply.bottomAnchor.constraint(equalTo: imageThumb.topAnchor, constant: -5).isActive = true
  3900. } else if fileChat != "" && (dataMessages[indexPath.row]["lock"] == nil || dataMessages[indexPath.row]["lock"] as! String != "1") {
  3901. containerReply.bottomAnchor.constraint(equalTo: containerViewFile.topAnchor, constant: -5).isActive = true
  3902. } else if dataMessages[indexPath.row]["attachment_flag"] as? String == "11" && (dataMessages[indexPath.row]["lock"] == nil || dataMessages[indexPath.row]["lock"] as! String != "1") {
  3903. containerReply.bottomAnchor.constraint(equalTo: imageSticker.topAnchor, constant: -5).isActive = true
  3904. } else {
  3905. containerReply.bottomAnchor.constraint(equalTo: messageText.topAnchor, constant: -5).isActive = true
  3906. }
  3907. containerReply.trailingAnchor.constraint(equalTo: containerMessage.trailingAnchor, constant: -15).isActive = true
  3908. containerReply.heightAnchor.constraint(equalToConstant: 50).isActive = true
  3909. containerReply.backgroundColor = .black.withAlphaComponent(0.2)
  3910. containerReply.layer.cornerRadius = 5
  3911. containerReply.clipsToBounds = true
  3912. let leftReply = UIView()
  3913. containerReply.addSubview(leftReply)
  3914. leftReply.translatesAutoresizingMaskIntoConstraints = false
  3915. leftReply.leadingAnchor.constraint(equalTo: containerReply.leadingAnchor).isActive = true
  3916. leftReply.topAnchor.constraint(equalTo: containerReply.topAnchor).isActive = true
  3917. leftReply.bottomAnchor.constraint(equalTo: containerReply.bottomAnchor).isActive = true
  3918. leftReply.widthAnchor.constraint(equalToConstant: 3).isActive = true
  3919. leftReply.layer.cornerRadius = 5
  3920. leftReply.clipsToBounds = true
  3921. leftReply.layer.maskedCorners = [.layerMinXMaxYCorner, .layerMinXMinYCorner]
  3922. let titleReply = UILabel()
  3923. containerReply.addSubview(titleReply)
  3924. titleReply.translatesAutoresizingMaskIntoConstraints = false
  3925. titleReply.leadingAnchor.constraint(equalTo: leftReply.leadingAnchor, constant: 10).isActive = true
  3926. titleReply.topAnchor.constraint(equalTo: containerReply.topAnchor, constant: 10).isActive = true
  3927. titleReply.trailingAnchor.constraint(lessThanOrEqualTo: containerReply.trailingAnchor, constant: -20).isActive = true
  3928. titleReply.font = UIFont.systemFont(ofSize: 12).bold
  3929. if (data["f_pin"] as? String == idMe) {
  3930. titleReply.text = "You".localized()
  3931. if dataMessages[indexPath.row]["f_pin"] as? String == idMe {
  3932. titleReply.textColor = .white
  3933. leftReply.backgroundColor = .white
  3934. } else {
  3935. titleReply.textColor = .mainColor
  3936. leftReply.backgroundColor = .mainColor
  3937. }
  3938. } else {
  3939. if isContactCenter {
  3940. let user: [User] = users.filter({$0.pin == data["f_pin"] as? String})
  3941. titleReply.text = user.first!.fullName
  3942. } else {
  3943. titleReply.text = self.dataPerson["name"]!!
  3944. }
  3945. if dataMessages[indexPath.row]["f_pin"] as? String == idMe {
  3946. titleReply.textColor = .white
  3947. leftReply.backgroundColor = .white
  3948. } else {
  3949. titleReply.textColor = .mainColor
  3950. leftReply.backgroundColor = .mainColor
  3951. }
  3952. }
  3953. let contentReply = UILabel()
  3954. containerReply.addSubview(contentReply)
  3955. contentReply.translatesAutoresizingMaskIntoConstraints = false
  3956. contentReply.leadingAnchor.constraint(equalTo: leftReply.leadingAnchor, constant: 10).isActive = true
  3957. contentReply.bottomAnchor.constraint(equalTo: containerReply.bottomAnchor, constant: -10).isActive = true
  3958. contentReply.font = UIFont.systemFont(ofSize: 10)
  3959. let message_text = data["message_text"] as! String
  3960. let attachment_flag = data["attachment_flag"] as! String
  3961. let thumb_chat = data["thumb_id"] as! String
  3962. let image_chat = data["image_id"] as! String
  3963. let video_chat = data["video_id"] as! String
  3964. let file_chat = data["file_id"] as! String
  3965. if (attachment_flag == "0" && thumb_chat == "") {
  3966. contentReply.trailingAnchor.constraint(equalTo: containerReply.trailingAnchor, constant: -20).isActive = true
  3967. contentReply.attributedText = message_text.richText()
  3968. } else if (attachment_flag == "1" || image_chat != "") {
  3969. if (message_text == "") {
  3970. contentReply.text = "📷 Photo".localized()
  3971. } else {
  3972. contentReply.attributedText = message_text.richText()
  3973. }
  3974. } else if (attachment_flag == "2" || video_chat != "") {
  3975. if (message_text == "") {
  3976. contentReply.text = "📹 Video".localized()
  3977. } else {
  3978. contentReply.attributedText = message_text.richText()
  3979. }
  3980. } else if (attachment_flag == "6" || file_chat != ""){
  3981. contentReply.trailingAnchor.constraint(equalTo: containerReply.trailingAnchor, constant: -20).isActive = true
  3982. contentReply.text = "📄 \(message_text.components(separatedBy: "|")[0])"
  3983. } else if (attachment_flag == "11") {
  3984. contentReply.text = "❤️ Sticker"
  3985. }
  3986. contentReply.textColor = .white.withAlphaComponent(0.8)
  3987. if (attachment_flag == "1" || attachment_flag == "2" || image_chat != "" || video_chat != "") {
  3988. let nsDocumentDirectory = FileManager.SearchPathDirectory.documentDirectory
  3989. let nsUserDomainMask = FileManager.SearchPathDomainMask.userDomainMask
  3990. let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true)
  3991. if let dirPath = paths.first {
  3992. let thumbURL = URL(fileURLWithPath: dirPath).appendingPathComponent(thumb_chat)
  3993. let image = UIImage(contentsOfFile: thumbURL.path)
  3994. let imageThumb = UIImageView(image: image)
  3995. containerReply.addSubview(imageThumb)
  3996. imageThumb.layer.cornerRadius = 2.0
  3997. imageThumb.clipsToBounds = true
  3998. imageThumb.contentMode = .scaleAspectFill
  3999. imageThumb.translatesAutoresizingMaskIntoConstraints = false
  4000. imageThumb.trailingAnchor.constraint(equalTo: containerReply.trailingAnchor, constant: -10).isActive = true
  4001. imageThumb.centerYAnchor.constraint(equalTo: containerReply.centerYAnchor).isActive = true
  4002. imageThumb.widthAnchor.constraint(equalToConstant: 30).isActive = true
  4003. imageThumb.heightAnchor.constraint(equalToConstant: 30).isActive = true
  4004. if (attachment_flag == "2") {
  4005. let imagePlay = UIImageView(image: UIImage(systemName: "play.circle.fill"))
  4006. imageThumb.addSubview(imagePlay)
  4007. imagePlay.clipsToBounds = true
  4008. imagePlay.translatesAutoresizingMaskIntoConstraints = false
  4009. imagePlay.centerYAnchor.constraint(equalTo: imageThumb.centerYAnchor).isActive = true
  4010. imagePlay.centerXAnchor.constraint(equalTo: imageThumb.centerXAnchor).isActive = true
  4011. imagePlay.widthAnchor.constraint(equalToConstant: 10).isActive = true
  4012. imagePlay.heightAnchor.constraint(equalToConstant: 10).isActive = true
  4013. imagePlay.tintColor = .white
  4014. }
  4015. titleReply.trailingAnchor.constraint(equalTo: imageThumb.leadingAnchor, constant: -20).isActive = true
  4016. contentReply.trailingAnchor.constraint(equalTo: imageThumb.leadingAnchor, constant: -20).isActive = true
  4017. }
  4018. }
  4019. if (attachment_flag == "11" && message_text.components(separatedBy: "/").count > 1) {
  4020. let imageSticker = UIImageView(image: UIImage(named: (message_text.components(separatedBy: "/")[1]), in: Bundle.resourceBundle(for: Nexilis.self), with: nil))
  4021. containerReply.addSubview(imageSticker)
  4022. imageSticker.layer.cornerRadius = 2.0
  4023. imageSticker.clipsToBounds = true
  4024. imageSticker.translatesAutoresizingMaskIntoConstraints = false
  4025. imageSticker.trailingAnchor.constraint(equalTo: containerReply.trailingAnchor, constant: -10).isActive = true
  4026. imageSticker.centerYAnchor.constraint(equalTo: containerReply.centerYAnchor).isActive = true
  4027. imageSticker.widthAnchor.constraint(equalToConstant: 30).isActive = true
  4028. imageSticker.heightAnchor.constraint(equalToConstant: 30).isActive = true
  4029. titleReply.trailingAnchor.constraint(equalTo: imageSticker.leadingAnchor, constant: -20).isActive = true
  4030. contentReply.trailingAnchor.constraint(equalTo: imageSticker.leadingAnchor, constant: -20).isActive = true
  4031. }
  4032. if !copySession && !forwardSession && !deleteSession {
  4033. let objectTap = ObjectGesture(target: self, action: #selector(contentMessageTapped(_:)))
  4034. containerReply.addGestureRecognizer(objectTap)
  4035. objectTap.indexPath = indexPath
  4036. objectTap.message_id = data["message_id"] as! String
  4037. }
  4038. }
  4039. }
  4040. return cellMessage
  4041. }
  4042. public func numberOfSections(in tableView: UITableView) -> Int {
  4043. dataDates.count
  4044. }
  4045. public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
  4046. let count = dataMessages.filter({ $0["chat_date"] as! String == dataDates[section] }).count
  4047. return count
  4048. }
  4049. @objc func contentMessageTapped(_ sender: ObjectGesture) {
  4050. let nsDocumentDirectory = FileManager.SearchPathDirectory.documentDirectory
  4051. let nsUserDomainMask = FileManager.SearchPathDomainMask.userDomainMask
  4052. let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true)
  4053. if (sender.image_id != "") {
  4054. if let dirPath = paths.first {
  4055. let imageURL = URL(fileURLWithPath: dirPath).appendingPathComponent(sender.image_id)
  4056. if FileManager.default.fileExists(atPath: imageURL.path) {
  4057. let image = UIImage(contentsOfFile: imageURL.path)
  4058. let previewImageVC = PreviewAttachmentImageVideo(nibName: "PreviewAttachmentImageVideo", bundle: Bundle.resourceBundle(for: Nexilis.self))
  4059. previewImageVC.image = image
  4060. previewImageVC.isHiddenTextField = true
  4061. previewImageVC.modalPresentationStyle = .custom
  4062. previewImageVC.modalTransitionStyle = .crossDissolve
  4063. self.present(previewImageVC, animated: true, completion: nil)
  4064. } else {
  4065. for view in sender.imageView.subviews {
  4066. if view is UIImageView {
  4067. view.removeFromSuperview()
  4068. }
  4069. }
  4070. let activityIndicator = UIActivityIndicatorView(style: .large)
  4071. activityIndicator.color = .mainColor
  4072. activityIndicator.hidesWhenStopped = true
  4073. activityIndicator.center = CGPoint(x:sender.imageView.frame.width/2,
  4074. y: sender.imageView.frame.height/2)
  4075. activityIndicator.startAnimating()
  4076. sender.imageView.addSubview(activityIndicator)
  4077. Download().start(forKey: sender.image_id) { (name, progress) in
  4078. guard progress == 100 else {
  4079. return
  4080. }
  4081. let imageURL = URL(fileURLWithPath: dirPath).appendingPathComponent(sender.image_id)
  4082. let image = UIImage(contentsOfFile: imageURL.path)
  4083. let save = UserDefaults.standard.bool(forKey: "saveToGallery")
  4084. if save {
  4085. UIImageWriteToSavedPhotosAlbum(image!, nil, nil, nil)
  4086. }
  4087. DispatchQueue.main.async {
  4088. activityIndicator.stopAnimating()
  4089. self.tableChatView.reloadRows(at: [sender.indexPath], with: .none)
  4090. }
  4091. }
  4092. }
  4093. }
  4094. } else if (sender.video_id != "") {
  4095. if let dirPath = paths.first {
  4096. let videoURL = URL(fileURLWithPath: dirPath).appendingPathComponent(sender.video_id)
  4097. if FileManager.default.fileExists(atPath: videoURL.path) {
  4098. let player = AVPlayer(url: videoURL as URL)
  4099. let playerVC = AVPlayerViewController()
  4100. playerVC.modalPresentationStyle = .custom
  4101. playerVC.player = player
  4102. self.present(playerVC, animated: true, completion: nil)
  4103. } else {
  4104. for view in sender.imageView.subviews {
  4105. if view is UIImageView {
  4106. view.removeFromSuperview()
  4107. }
  4108. }
  4109. let container = UIView()
  4110. sender.imageView.addSubview(container)
  4111. container.translatesAutoresizingMaskIntoConstraints = false
  4112. container.centerXAnchor.constraint(equalTo: sender.imageView.centerXAnchor).isActive = true
  4113. container.centerYAnchor.constraint(equalTo: sender.imageView.centerYAnchor).isActive = true
  4114. container.widthAnchor.constraint(equalToConstant: 50).isActive = true
  4115. container.heightAnchor.constraint(equalToConstant: 50).isActive = true
  4116. let circlePath = UIBezierPath(arcCenter: CGPoint(x: 25, y: 25), radius: 20, startAngle: -(.pi / 2), endAngle: .pi * 2, clockwise: true)
  4117. let trackShape = CAShapeLayer()
  4118. trackShape.path = circlePath.cgPath
  4119. trackShape.fillColor = UIColor.clear.cgColor
  4120. trackShape.lineWidth = 10
  4121. trackShape.strokeColor = UIColor.blueBubbleColor.withAlphaComponent(0.3).cgColor
  4122. container.backgroundColor = .clear
  4123. container.layer.addSublayer(trackShape)
  4124. let shapeLoading = CAShapeLayer()
  4125. shapeLoading.path = circlePath.cgPath
  4126. shapeLoading.fillColor = UIColor.clear.cgColor
  4127. shapeLoading.lineWidth = 10
  4128. shapeLoading.strokeEnd = 0
  4129. shapeLoading.strokeColor = UIColor.blueBubbleColor.cgColor
  4130. container.layer.addSublayer(shapeLoading)
  4131. let imageDownload = UIImageView(image: UIImage(systemName: "arrow.down", withConfiguration: UIImage.SymbolConfiguration(pointSize: 10, weight: .bold, scale: .default)))
  4132. imageDownload.tintColor = .white
  4133. container.addSubview(imageDownload)
  4134. imageDownload.translatesAutoresizingMaskIntoConstraints = false
  4135. imageDownload.centerXAnchor.constraint(equalTo: sender.imageView.centerXAnchor).isActive = true
  4136. imageDownload.centerYAnchor.constraint(equalTo: sender.imageView.centerYAnchor).isActive = true
  4137. imageDownload.widthAnchor.constraint(equalToConstant: 30).isActive = true
  4138. imageDownload.heightAnchor.constraint(equalToConstant: 30).isActive = true
  4139. Download().start(forKey: sender.video_id) { (name, progress) in
  4140. DispatchQueue.main.async {
  4141. guard progress == 100 else {
  4142. shapeLoading.strokeEnd = CGFloat(progress / 100)
  4143. return
  4144. }
  4145. let save = UserDefaults.standard.bool(forKey: "saveToGallery")
  4146. if save {
  4147. let videoURL = URL(fileURLWithPath: dirPath).appendingPathComponent(sender.video_id)
  4148. PHPhotoLibrary.shared().performChanges({
  4149. PHAssetChangeRequest.creationRequestForAssetFromVideo(atFileURL: videoURL)
  4150. }) { saved, error in
  4151. }
  4152. }
  4153. let idx = self.dataMessages.firstIndex(where: { $0["video_id"] as! String == sender.video_id})
  4154. if idx != nil {
  4155. self.dataMessages[idx!]["progress"] = progress
  4156. self.tableChatView.reloadRows(at: [sender.indexPath], with: .none)
  4157. }
  4158. }
  4159. }
  4160. }
  4161. }
  4162. } else if (sender.file_id != "") {
  4163. if let dirPath = paths.first {
  4164. let fileURL = URL(fileURLWithPath: dirPath).appendingPathComponent(sender.file_id)
  4165. if FileManager.default.fileExists(atPath: fileURL.path) {
  4166. self.previewItem = fileURL as NSURL
  4167. let previewController = QLPreviewController()
  4168. let rightBarButton = UIBarButtonItem()
  4169. previewController.navigationItem.rightBarButtonItem = rightBarButton
  4170. previewController.dataSource = self
  4171. previewController.modalPresentationStyle = .custom
  4172. self.show(previewController, sender: nil)
  4173. } else {
  4174. for view in sender.containerFile.subviews {
  4175. if !(view is UIImageView) && !(view is UILabel) {
  4176. view.removeFromSuperview()
  4177. }
  4178. }
  4179. let containerLoading = UIView()
  4180. sender.containerFile.addSubview(containerLoading)
  4181. containerLoading.translatesAutoresizingMaskIntoConstraints = false
  4182. containerLoading.centerYAnchor.constraint(equalTo: sender.containerFile.centerYAnchor).isActive = true
  4183. containerLoading.leadingAnchor.constraint(equalTo: sender.labelFile.trailingAnchor, constant: 5).isActive = true
  4184. containerLoading.trailingAnchor.constraint(equalTo: sender.containerFile.trailingAnchor, constant: -5).isActive = true
  4185. containerLoading.widthAnchor.constraint(equalToConstant: 30).isActive = true
  4186. containerLoading.heightAnchor.constraint(equalToConstant: 30).isActive = true
  4187. let circlePath = UIBezierPath(arcCenter: CGPoint(x: 15, y: 15), radius: 10, startAngle: -(.pi / 2), endAngle: .pi * 2, clockwise: true)
  4188. let trackShape = CAShapeLayer()
  4189. trackShape.path = circlePath.cgPath
  4190. trackShape.fillColor = UIColor.clear.cgColor
  4191. trackShape.lineWidth = 5
  4192. trackShape.strokeColor = UIColor.blueBubbleColor.withAlphaComponent(0.3).cgColor
  4193. containerLoading.layer.addSublayer(trackShape)
  4194. let shapeLoading = CAShapeLayer()
  4195. shapeLoading.path = circlePath.cgPath
  4196. shapeLoading.fillColor = UIColor.clear.cgColor
  4197. shapeLoading.lineWidth = 3
  4198. shapeLoading.strokeEnd = 0
  4199. shapeLoading.strokeColor = UIColor.blueBubbleColor.cgColor
  4200. containerLoading.layer.addSublayer(shapeLoading)
  4201. let imageupload = UIImageView(image: UIImage(systemName: "arrow.down", withConfiguration: UIImage.SymbolConfiguration(pointSize: 10, weight: .bold, scale: .default)))
  4202. imageupload.tintColor = .white
  4203. containerLoading.addSubview(imageupload)
  4204. imageupload.translatesAutoresizingMaskIntoConstraints = false
  4205. imageupload.centerYAnchor.constraint(equalTo: containerLoading.centerYAnchor).isActive = true
  4206. imageupload.centerXAnchor.constraint(equalTo: containerLoading.centerXAnchor).isActive = true
  4207. Download().start(forKey: sender.file_id) { (name, progress) in
  4208. DispatchQueue.main.async {
  4209. guard progress == 100 else {
  4210. shapeLoading.strokeEnd = CGFloat(progress / 100)
  4211. return
  4212. }
  4213. let idx = self.dataMessages.firstIndex(where: { $0["file_id"] as! String == sender.file_id})
  4214. if idx != nil {
  4215. self.dataMessages[idx!]["progress"] = progress
  4216. self.tableChatView.reloadRows(at: [sender.indexPath], with: .none)
  4217. }
  4218. }
  4219. }
  4220. }
  4221. }
  4222. } else {
  4223. DispatchQueue.main.async {
  4224. let idx = self.dataMessages.firstIndex(where: { $0["message_id"] as? String == sender.message_id})
  4225. if idx == nil {
  4226. return
  4227. }
  4228. let section = self.dataDates.firstIndex(of: self.dataMessages[idx!]["chat_date"] as! String)
  4229. if section == nil {
  4230. return
  4231. }
  4232. let row = self.dataMessages.filter({ $0["chat_date"] as! String == self.dataDates[section!]}).firstIndex(where: { $0["message_id"] as? String == self.dataMessages[idx!]["message_id"] as? String})
  4233. if row == nil {
  4234. return
  4235. }
  4236. let indexPath = IndexPath(row: row!, section: section!)
  4237. self.tableChatView.scrollToRow(at: indexPath, at: .middle, animated: true)
  4238. DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
  4239. if let cell = self.tableChatView.cellForRow(at: indexPath) {
  4240. let containerMessage = cell.contentView.subviews[0]
  4241. let idMe = UserDefaults.standard.string(forKey: "me") as String?
  4242. if (self.dataMessages[idx!]["f_pin"] as? String == idMe) {
  4243. containerMessage.backgroundColor = .blueBubbleColor.withAlphaComponent(0.3)
  4244. DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
  4245. if (self.dataMessages[idx!]["attachment_flag"] as? String == "11") {
  4246. containerMessage.backgroundColor = .clear
  4247. } else {
  4248. containerMessage.backgroundColor = .blueBubbleColor
  4249. }
  4250. }
  4251. } else {
  4252. containerMessage.backgroundColor = .grayColor.withAlphaComponent(0.3)
  4253. DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
  4254. if (self.dataMessages[idx!]["attachment_flag"] as? String == "11") {
  4255. containerMessage.backgroundColor = .clear
  4256. } else {
  4257. containerMessage.backgroundColor = .grayColor
  4258. }
  4259. }
  4260. }
  4261. }
  4262. }
  4263. }
  4264. }
  4265. }
  4266. @objc func tapMessageText(_ sender: ObjectGesture) {
  4267. var stringURl = sender.message_id.lowercased()
  4268. if stringURl.starts(with: "www.") {
  4269. stringURl = "https://" + stringURl.replacingOccurrences(of: "www.", with: "")
  4270. }
  4271. guard let url = URL(string: stringURl) else { return }
  4272. UIApplication.shared.open(url)
  4273. }
  4274. }
  4275. extension UITableView {
  4276. func scrollToBottom(isAnimated:Bool = true){
  4277. DispatchQueue.main.async {
  4278. if self.numberOfSections == 0 {
  4279. return
  4280. }
  4281. let indexPath = IndexPath(
  4282. row: self.numberOfRows(inSection: self.numberOfSections-1) - 1,
  4283. section: self.numberOfSections - 1)
  4284. if indexPath.row != -1 {
  4285. self.scrollToRow(at: indexPath, at: .bottom, animated: isAnimated)
  4286. }
  4287. }
  4288. }
  4289. func scrollToTop(isAnimated:Bool = true) {
  4290. DispatchQueue.main.async {
  4291. let indexPath = IndexPath(row: 0, section: 0)
  4292. if indexPath.row != -1 {
  4293. self.scrollToRow(at: indexPath, at: .top, animated: isAnimated)
  4294. }
  4295. }
  4296. }
  4297. }
  4298. extension UIImage {
  4299. func imageWithInsets(insets: UIEdgeInsets) -> UIImage? {
  4300. UIGraphicsBeginImageContextWithOptions(
  4301. CGSize(width: self.size.width + insets.left + insets.right,
  4302. height: self.size.height + insets.top + insets.bottom), false, self.scale)
  4303. let _ = UIGraphicsGetCurrentContext()
  4304. let origin = CGPoint(x: insets.left, y: insets.top)
  4305. self.draw(at: origin)
  4306. let imageWithInsets = UIGraphicsGetImageFromCurrentImageContext()
  4307. UIGraphicsEndImageContext()
  4308. return imageWithInsets
  4309. }
  4310. }
  4311. public class ObjectGesture: UITapGestureRecognizer {
  4312. public var message_id = ""
  4313. public var image_id = ""
  4314. public var video_id = ""
  4315. public var file_id = ""
  4316. public var imageView = UIImageView()
  4317. public var containerFile = UIView()
  4318. public var labelFile = UILabel()
  4319. public var videoURL: NSURL?
  4320. public var indexPath = IndexPath()
  4321. }
  4322. class navigationQLPreviewDocument: UIBarButtonItem {
  4323. var navigation = UINavigationController()
  4324. }
  4325. class segmentedControllerObject: UISegmentedControl {
  4326. var navigation = UINavigationController()
  4327. }