EditorGroup.swift 267 KB

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