EditorGroup.swift 296 KB

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