EditorGroup.swift 301 KB

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