EditorGroup.swift 298 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012
  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: DigiX.self), with: nil)!, targetSize: CGSize(width: 30, height: 30)), for: .normal)
  139. buttonSendImage.setImage(resizeImage(image: UIImage(named: "Send-Image", in: Bundle.resourceBundle(for: DigiX.self), with: nil)!, targetSize: CGSize(width: 30, height: 30)).withTintColor(.mainColor), for: .normal)
  140. buttonSendPhoto.setImage(resizeImage(image: UIImage(named: "Camera", in: Bundle.resourceBundle(for: DigiX.self), with: nil)!, targetSize: CGSize(width: 30, height: 30)).withTintColor(.mainColor), for: .normal)
  141. buttonSendSticker.setImage(resizeImage(image: UIImage(named: "Sticker---Emoji", in: Bundle.resourceBundle(for: DigiX.self), with: nil)!, targetSize: CGSize(width: 30, height: 30)).withTintColor(.mainColor), for: .normal)
  142. buttonSendFile.setImage(resizeImage(image: UIImage(named: "File---Documents", in: Bundle.resourceBundle(for: DigiX.self), with: nil)!, targetSize: CGSize(width: 30, height: 30)).withTintColor(.mainColor), for: .normal)
  143. buttonSendChat.setImage(resizeImage(image: UIImage(named: "Send-(White)", in: Bundle.resourceBundle(for: DigiX.self), with: nil)!, targetSize: CGSize(width: 30, height: 30)).withRenderingMode(.alwaysOriginal), for: .normal)
  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: DigiX.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: DigiX.listenerReceiveChat), object: nil)
  176. center.addObserver(self, selector: #selector(onStatusChat(notification:)), name: NSNotification.Name(rawValue: DigiX.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 _ = DigiX.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: DigiX.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: DigiX.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: DigiX.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. DigiX.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. _ = DigiX.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. _ = DigiX.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: DigiX.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: DigiX.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 Telkomsel".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. DigiX.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: DigiX.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: DigiX.self), with: nil)!.withTintColor(UIColor.lightGray)
  3059. } else if (status == "3") {
  3060. statusMessage.image = UIImage(named: "double-checklist", in: Bundle.resourceBundle(for: DigiX.self), with: nil)!.withTintColor(UIColor.lightGray)
  3061. } else if (status == "8") {
  3062. statusMessage.image = UIImage(named: "message_status_ack", in: Bundle.resourceBundle(for: DigiX.self), with: nil)!.withRenderingMode(.alwaysOriginal)
  3063. } else {
  3064. statusMessage.image = UIImage(named: "double-checklist", in: Bundle.resourceBundle(for: DigiX.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: DigiX.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: DigiX.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: DigiX.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: DigiX.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: DigiX.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: DigiX.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: DigiX.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. if textChat!.contains("■"){
  3309. textChat = textChat?.components(separatedBy: "■")[0]
  3310. textChat = textChat?.trimmingCharacters(in: .whitespacesAndNewlines)
  3311. }
  3312. let listTextEnter = textChat!.split(separator: "\n")
  3313. for j in 0...listTextEnter.count - 1 {
  3314. let listText = listTextEnter[j].split(separator: " ")
  3315. for i in 0...listText.count - 1 {
  3316. if listText[i].lowercased().checkStartWithLink() {
  3317. let rangeTapLink = (textChat! as NSString).range(of: String(listText[i]))
  3318. // Add tap gesture recognizer to the range of text
  3319. let attributedString = textChat!.richText(group_id: self.dataGroup["group_id"] as! String)
  3320. attributedString.addAttributes([.foregroundColor: UIColor.blue, .underlineStyle: NSUnderlineStyle.single.rawValue], range: rangeTapLink)
  3321. messageText.attributedText = attributedString
  3322. if messageText.isUserInteractionEnabled == false && !copySession && !forwardSession && !deleteSession && !isHistoryCC && !removed {
  3323. messageText.isUserInteractionEnabled = true
  3324. let longPress = UILongPressGestureRecognizer(target: self, action: #selector(handleLongPressLink(_:)))
  3325. longPress.minimumPressDuration = 0.1
  3326. containerMessage.addGestureRecognizer(longPress)
  3327. }
  3328. }
  3329. }
  3330. }
  3331. }
  3332. if !copySession && !forwardSession && !deleteSession && !isHistoryCC && !removed && messageText.isUserInteractionEnabled == false {
  3333. let interaction = UIContextMenuInteraction(delegate: self)
  3334. containerMessage.addInteraction(interaction)
  3335. containerMessage.isUserInteractionEnabled = true
  3336. }
  3337. if isSearching && textSearch.count > 1 {
  3338. messageText.attributedText = textChat!.richText(isSearching: true, textSearch: textSearch, group_id: self.dataGroup["group_id"] as! String)
  3339. if textChat!.lowercased().contains(textSearch) {
  3340. countMatchesSearch += 1
  3341. }
  3342. }
  3343. let stringDate = (dataMessages[indexPath.row]["server_date"] as! String)
  3344. let date = Date(milliseconds: Int64(stringDate)!)
  3345. let formatter = DateFormatter()
  3346. formatter.dateFormat = "HH:mm"
  3347. formatter.locale = NSLocale(localeIdentifier: "id") as Locale?
  3348. timeMessage.text = formatter.string(from: date as Date)
  3349. timeMessage.font = UIFont.systemFont(ofSize: 10, weight: .medium)
  3350. timeMessage.textColor = .lightGray
  3351. let imageThumb = UIImageView()
  3352. let containerViewFile = UIView()
  3353. if (thumbChat != "" && (dataMessages[indexPath.row]["lock"] == nil || dataMessages[indexPath.row]["lock"] as! String != "1")) {
  3354. if let listImages = groupImages[messageIdChat] {
  3355. timeMessage.isHidden = true
  3356. statusMessage.isHidden = true
  3357. imageStared.isHidden = true
  3358. topMarginText.constant = topMarginText.constant + 205
  3359. let listImageThumb: [UIImageView] = [UIImageView(), UIImageView(), UIImageView(), UIImageView()]
  3360. for i in 0..<4 {
  3361. containerMessage.addSubview(listImageThumb[i])
  3362. listImageThumb[i].layer.cornerRadius = 5.0
  3363. listImageThumb[i].clipsToBounds = true
  3364. listImageThumb[i].contentMode = .scaleAspectFill
  3365. let widthHeightImage: CGFloat = 120
  3366. switch i {
  3367. case 0:
  3368. listImageThumb[i].anchor(top: containerMessage.topAnchor, left: containerMessage.leftAnchor, paddingTop: 5, paddingLeft: 5, width: widthHeightImage, height: widthHeightImage)
  3369. case 1:
  3370. listImageThumb[i].anchor(top: containerMessage.topAnchor, left: listImageThumb[0].rightAnchor, right: containerMessage.rightAnchor, paddingTop: 5, paddingLeft: 5, paddingRight: 5, width: widthHeightImage, height: widthHeightImage)
  3371. case 2:
  3372. listImageThumb[i].anchor(left: containerMessage.leftAnchor, bottom: containerMessage.bottomAnchor, paddingLeft: 5, paddingBottom: 5, width: widthHeightImage, height: widthHeightImage)
  3373. default:
  3374. listImageThumb[i].anchor(left: listImageThumb[2].rightAnchor, bottom: containerMessage.bottomAnchor, right: containerMessage.rightAnchor, paddingLeft: 5, paddingBottom: 5, paddingRight: 5, width: widthHeightImage, height: widthHeightImage)
  3375. }
  3376. let nsDocumentDirectory = FileManager.SearchPathDirectory.documentDirectory
  3377. let nsUserDomainMask = FileManager.SearchPathDomainMask.userDomainMask
  3378. let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true)
  3379. if let dirPath = paths.first {
  3380. let thumbURL = URL(fileURLWithPath: dirPath).appendingPathComponent(listImages[i].thumbId)
  3381. let image : UIImage? = {
  3382. if let img = DigiX.imageCache.object(forKey: listImages[i].thumbId as NSString) {
  3383. return img
  3384. }
  3385. else if let img = UIImage(contentsOfFile: thumbURL.path)?.resize(target: CGSize(width: 500, height: 500)) {
  3386. DigiX.imageCache.setObject(img, forKey: listImages[i].thumbId as NSString)
  3387. return img
  3388. }
  3389. return nil
  3390. }()
  3391. // let image = UIGraphicsRenderer.renderImageAt(url: thumbURL as NSURL, size: CGSize(width: 250, height: 250))
  3392. listImageThumb[i].image = image
  3393. let imageURL = URL(fileURLWithPath: dirPath).appendingPathComponent(listImages[i].imageId)
  3394. if !FileManager.default.fileExists(atPath: imageURL.path) {
  3395. let blurEffect = UIBlurEffect(style: UIBlurEffect.Style.light)
  3396. let blurEffectView = UIVisualEffectView(effect: blurEffect)
  3397. blurEffectView.frame = CGRect(x: 0, y: 0, width: listImageThumb[i].frame.size.width, height: listImageThumb[i].frame.size.height)
  3398. blurEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
  3399. listImageThumb[i].addSubview(blurEffectView)
  3400. }
  3401. }
  3402. let containerTimeStatus = UIView()
  3403. listImageThumb[i].addSubview(containerTimeStatus)
  3404. containerTimeStatus.anchor(bottom: listImageThumb[i].bottomAnchor, right: listImageThumb[i].rightAnchor, height: 15)
  3405. let widthcontainerTimeStatus = containerTimeStatus.widthAnchor.constraint(equalToConstant: 50)
  3406. widthcontainerTimeStatus.isActive = true
  3407. containerTimeStatus.layer.cornerRadius = 5.0
  3408. containerTimeStatus.layer.masksToBounds = true
  3409. containerTimeStatus.backgroundColor = .black.withAlphaComponent(0.15)
  3410. let timeInImage = UILabel()
  3411. containerTimeStatus.addSubview(timeInImage)
  3412. let date = Date(milliseconds: Int64(listImages[i].time) ?? 100)
  3413. let formatter = DateFormatter()
  3414. formatter.dateFormat = "HH:mm"
  3415. formatter.locale = NSLocale(localeIdentifier: "id") as Locale?
  3416. timeInImage.text = formatter.string(from: date as Date)
  3417. timeInImage.textColor = .white
  3418. timeInImage.font = UIFont.systemFont(ofSize: 10, weight: .medium)
  3419. if (dataMessages[indexPath.row]["f_pin"] as? String == idMe) {
  3420. let statusInImage = UIImageView()
  3421. containerTimeStatus.addSubview(statusInImage)
  3422. statusInImage.anchor(right: containerTimeStatus.rightAnchor, centerY: containerTimeStatus.centerYAnchor, width: 15, height: 15)
  3423. if listImages[i].status == "1" || listImages[i].status == "2" {
  3424. statusInImage.image = UIImage(named: "checklist", in: Bundle.resourceBundle(for: DigiX.self), with: nil)!.withTintColor(UIColor.white)
  3425. } else if listImages[i].status == "3" {
  3426. statusInImage.image = UIImage(named: "double-checklist", in: Bundle.resourceBundle(for: DigiX.self), with: nil)!.withTintColor(UIColor.white)
  3427. } else {
  3428. statusInImage.image = UIImage(named: "double-checklist", in: Bundle.resourceBundle(for: DigiX.self), with: nil)!.withTintColor(UIColor.systemBlue)
  3429. }
  3430. timeInImage.anchor(right: statusInImage.leftAnchor, centerY: containerTimeStatus.centerYAnchor, height: 15)
  3431. } else {
  3432. timeInImage.anchor(right: containerTimeStatus.rightAnchor, paddingRight: 5, centerY: containerTimeStatus.centerYAnchor, height: 15)
  3433. widthcontainerTimeStatus.constant = widthcontainerTimeStatus.constant - 10
  3434. }
  3435. if listImages[i].dataMessage["is_stared"] as? String == "1" {
  3436. let iconStar = UIImageView()
  3437. containerTimeStatus.addSubview(iconStar)
  3438. iconStar.anchor(right: timeInImage.leftAnchor, paddingRight: 2, centerY: containerTimeStatus.centerYAnchor, width: 15, height: 15)
  3439. widthcontainerTimeStatus.constant = widthcontainerTimeStatus.constant + 15
  3440. iconStar.image = UIImage(systemName: "star.fill")
  3441. iconStar.tintColor = .white
  3442. }
  3443. if !copySession && !forwardSession && !deleteSession {
  3444. let objectTap = ObjectGesture(target: self, action: #selector(imageGroupingTapped(_:)))
  3445. listImageThumb[i].isUserInteractionEnabled = true
  3446. listImageThumb[i].addGestureRecognizer(objectTap)
  3447. objectTap.indexImageTapped = i
  3448. objectTap.listImageFromGrouping = listImages
  3449. objectTap.isInitiator = dataMessages[indexPath.row]["f_pin"] as? String == idMe
  3450. }
  3451. }
  3452. if listImages.count > 4 {
  3453. let blurEffect = UIBlurEffect(style: UIBlurEffect.Style.dark)
  3454. let blurEffectView = UIVisualEffectView(effect: blurEffect)
  3455. blurEffectView.frame = CGRect(x: 0, y: 0, width: listImageThumb[3].frame.size.width, height: listImageThumb[3].frame.size.height)
  3456. blurEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
  3457. listImageThumb[3].addSubview(blurEffectView)
  3458. let countRestImages = UILabel()
  3459. listImageThumb[3].addSubview(countRestImages)
  3460. countRestImages.anchor(centerX: listImageThumb[3].centerXAnchor, centerY: listImageThumb[3].centerYAnchor)
  3461. countRestImages.font = UIFont.systemFont(ofSize: 30, weight: .medium)
  3462. countRestImages.text = "+\(listImages.count - 3)"
  3463. countRestImages.textColor = .white
  3464. }
  3465. } else {
  3466. topMarginText.constant = topMarginText.constant + ListGroupImages.getImageSize(image: thumbChat, screenWidth: self.view.frame.size.width * 0.6, screenHeight: 305)!.height
  3467. containerMessage.addSubview(imageThumb)
  3468. imageThumb.translatesAutoresizingMaskIntoConstraints = false
  3469. let data = queryMessageReply(message_id: reffChat)
  3470. if (data.count == 0) {
  3471. imageThumb.topAnchor.constraint(equalTo: containerMessage.topAnchor, constant: 32).isActive = true
  3472. }
  3473. imageThumb.leadingAnchor.constraint(equalTo: containerMessage.leadingAnchor, constant: 15).isActive = true
  3474. imageThumb.bottomAnchor.constraint(equalTo: messageText.topAnchor, constant: -5).isActive = true
  3475. imageThumb.trailingAnchor.constraint(equalTo: containerMessage.trailingAnchor, constant: -15).isActive = true
  3476. imageThumb.widthAnchor.constraint(equalToConstant: ListGroupImages.getImageSize(image: thumbChat, screenWidth: self.view.frame.size.width * 0.6, screenHeight: 305)!.width).isActive = true
  3477. imageThumb.layer.cornerRadius = 5.0
  3478. imageThumb.clipsToBounds = true
  3479. imageThumb.contentMode = .scaleAspectFill
  3480. let nsDocumentDirectory = FileManager.SearchPathDirectory.documentDirectory
  3481. let nsUserDomainMask = FileManager.SearchPathDomainMask.userDomainMask
  3482. let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true)
  3483. if let dirPath = paths.first {
  3484. let thumbURL = URL(fileURLWithPath: dirPath).appendingPathComponent(thumbChat)
  3485. let image : UIImage? = {
  3486. if let img = DigiX.imageCache.object(forKey: thumbChat as NSString) {
  3487. return img
  3488. }
  3489. else if let img = UIImage(contentsOfFile: thumbURL.path)?.resize(target: CGSize(width: 500, height: 500)) {
  3490. DigiX.imageCache.setObject(img, forKey: thumbChat as NSString)
  3491. return img
  3492. }
  3493. return nil
  3494. }()
  3495. // let image = UIGraphicsRenderer.renderImageAt(url: thumbURL as NSURL, size: CGSize(width: 250, height: 250))
  3496. imageThumb.image = image
  3497. let videoURL = URL(fileURLWithPath: dirPath).appendingPathComponent(videoChat)
  3498. let imageURL = URL(fileURLWithPath: dirPath).appendingPathComponent(imageChat)
  3499. if !FileManager.default.fileExists(atPath: imageURL.path) || !FileManager.default.fileExists(atPath: videoURL.path){
  3500. let blurEffect = UIBlurEffect(style: UIBlurEffect.Style.light)
  3501. let blurEffectView = UIVisualEffectView(effect: blurEffect)
  3502. blurEffectView.frame = CGRect(x: 0, y: 0, width: imageThumb.frame.size.width, height: imageThumb.frame.size.height)
  3503. blurEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
  3504. imageThumb.addSubview(blurEffectView)
  3505. if !imageChat.isEmpty {
  3506. let imageDownload = UIImageView(image: UIImage(systemName: "arrow.down.circle.fill", withConfiguration: UIImage.SymbolConfiguration(pointSize: 50, weight: .bold, scale: .default)))
  3507. imageThumb.addSubview(blurEffectView)
  3508. imageThumb.addSubview(imageDownload)
  3509. imageDownload.tintColor = .black.withAlphaComponent(0.3)
  3510. imageDownload.translatesAutoresizingMaskIntoConstraints = false
  3511. imageDownload.centerXAnchor.constraint(equalTo: imageThumb.centerXAnchor).isActive = true
  3512. imageDownload.centerYAnchor.constraint(equalTo: imageThumb.centerYAnchor).isActive = true
  3513. }
  3514. }
  3515. }
  3516. if (videoChat != "") {
  3517. 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))
  3518. imagePlay.circle()
  3519. imageThumb.addSubview(imagePlay)
  3520. imagePlay.backgroundColor = .black.withAlphaComponent(0.3)
  3521. imagePlay.translatesAutoresizingMaskIntoConstraints = false
  3522. imagePlay.centerXAnchor.constraint(equalTo: imageThumb.centerXAnchor).isActive = true
  3523. imagePlay.centerYAnchor.constraint(equalTo: imageThumb.centerYAnchor).isActive = true
  3524. }
  3525. if (dataMessages[indexPath.row]["progress"] as! Double != 100.0 && dataMessages[indexPath.row]["f_pin"] as? String == idMe) {
  3526. let container = UIView()
  3527. imageThumb.addSubview(container)
  3528. container.translatesAutoresizingMaskIntoConstraints = false
  3529. container.bottomAnchor.constraint(equalTo: imageThumb.bottomAnchor, constant: -10).isActive = true
  3530. container.leadingAnchor.constraint(equalTo: imageThumb.leadingAnchor, constant: 10).isActive = true
  3531. container.widthAnchor.constraint(equalToConstant: 30).isActive = true
  3532. container.heightAnchor.constraint(equalToConstant: 30).isActive = true
  3533. container.backgroundColor = .white.withAlphaComponent(0.1)
  3534. let circlePath = UIBezierPath(arcCenter: CGPoint(x: 10, y: 20), radius: 15, startAngle: -(.pi / 2), endAngle: .pi * 2, clockwise: true)
  3535. let trackShape = CAShapeLayer()
  3536. trackShape.path = circlePath.cgPath
  3537. trackShape.fillColor = UIColor.black.withAlphaComponent(0.3).cgColor
  3538. trackShape.lineWidth = 3
  3539. trackShape.strokeColor = UIColor.blueBubbleColor.withAlphaComponent(0.3).cgColor
  3540. container.backgroundColor = .clear
  3541. container.layer.addSublayer(trackShape)
  3542. let shapeLoading = CAShapeLayer()
  3543. shapeLoading.path = circlePath.cgPath
  3544. shapeLoading.fillColor = UIColor.clear.cgColor
  3545. shapeLoading.lineWidth = 3
  3546. shapeLoading.strokeEnd = 0
  3547. shapeLoading.strokeColor = UIColor.blueBubbleColor.cgColor
  3548. container.layer.addSublayer(shapeLoading)
  3549. let imageupload = UIImageView(image: UIImage(systemName: "arrow.up", withConfiguration: UIImage.SymbolConfiguration(pointSize: 10, weight: .bold, scale: .default)))
  3550. imageupload.tintColor = .white
  3551. container.addSubview(imageupload)
  3552. imageupload.translatesAutoresizingMaskIntoConstraints = false
  3553. imageupload.bottomAnchor.constraint(equalTo: imageThumb.bottomAnchor, constant: -10).isActive = true
  3554. imageupload.leadingAnchor.constraint(equalTo: imageThumb.leadingAnchor, constant: 10).isActive = true
  3555. imageupload.widthAnchor.constraint(equalToConstant: 20).isActive = true
  3556. imageupload.heightAnchor.constraint(equalToConstant: 20).isActive = true
  3557. }
  3558. if !copySession && !forwardSession && !deleteSession {
  3559. let objectTap = ObjectGesture(target: self, action: #selector(contentMessageTapped(_:)))
  3560. imageThumb.isUserInteractionEnabled = true
  3561. imageThumb.addGestureRecognizer(objectTap)
  3562. objectTap.image_id = imageChat
  3563. objectTap.video_id = videoChat
  3564. objectTap.imageView = imageThumb
  3565. objectTap.indexPath = indexPath
  3566. }
  3567. }
  3568. }
  3569. if (fileChat != "" && (dataMessages[indexPath.row]["lock"] == nil || dataMessages[indexPath.row]["lock"] as! String != "1")) {
  3570. topMarginText.constant = topMarginText.constant + 55
  3571. let nsDocumentDirectory = FileManager.SearchPathDirectory.documentDirectory
  3572. let nsUserDomainMask = FileManager.SearchPathDomainMask.userDomainMask
  3573. let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true)
  3574. let arrExtFile = (textChat?.components(separatedBy: "|")[0])?.split(separator: ".")
  3575. let finalExtFile = arrExtFile![arrExtFile!.count - 1]
  3576. if let dirPath = paths.first {
  3577. let fileURL = URL(fileURLWithPath: dirPath).appendingPathComponent(fileChat)
  3578. if let dataFile = try? Data(contentsOf: fileURL) {
  3579. var sizeOfFile = Int(dataFile.count / 1000000)
  3580. if (sizeOfFile < 1) {
  3581. sizeOfFile = Int(dataFile.count / 1000)
  3582. if (finalExtFile.count > 4) {
  3583. messageText.text = "\(sizeOfFile) kB \u{2022} TXT"
  3584. }else {
  3585. messageText.text = "\(sizeOfFile) kB \u{2022} \(finalExtFile.uppercased())"
  3586. }
  3587. } else {
  3588. if (finalExtFile.count > 4) {
  3589. messageText.text = "\(sizeOfFile) MB \u{2022} TXT"
  3590. }else {
  3591. messageText.text = "\(sizeOfFile) MB \u{2022} \(finalExtFile.uppercased())"
  3592. }
  3593. }
  3594. } else {
  3595. messageText.text = ""
  3596. }
  3597. }
  3598. containerMessage.addSubview(containerViewFile)
  3599. containerViewFile.translatesAutoresizingMaskIntoConstraints = false
  3600. let data = queryMessageReply(message_id: reffChat)
  3601. if (data.count == 0) {
  3602. containerViewFile.topAnchor.constraint(equalTo: containerMessage.topAnchor, constant: 32).isActive = true
  3603. }
  3604. containerViewFile.leadingAnchor.constraint(equalTo: containerMessage.leadingAnchor, constant: 15).isActive = true
  3605. containerViewFile.bottomAnchor.constraint(equalTo:messageText.topAnchor, constant: -5).isActive = true
  3606. containerViewFile.trailingAnchor.constraint(equalTo: containerMessage.trailingAnchor, constant: -15).isActive = true
  3607. containerViewFile.heightAnchor.constraint(equalToConstant: 50).isActive = true
  3608. containerViewFile.backgroundColor = .black.withAlphaComponent(0.2)
  3609. containerViewFile.layer.cornerRadius = 5.0
  3610. containerViewFile.clipsToBounds = true
  3611. let imageFile = UIImageView(image: UIImage(systemName: "doc.fill", withConfiguration: UIImage.SymbolConfiguration(pointSize: 30, weight: .bold, scale: .default)))
  3612. containerViewFile.addSubview(imageFile)
  3613. let nameFile = UILabel()
  3614. containerViewFile.addSubview(nameFile)
  3615. imageFile.translatesAutoresizingMaskIntoConstraints = false
  3616. imageFile.leadingAnchor.constraint(equalTo: containerViewFile.leadingAnchor, constant: 5).isActive = true
  3617. imageFile.trailingAnchor.constraint(equalTo: nameFile.leadingAnchor, constant: -5).isActive = true
  3618. imageFile.centerYAnchor.constraint(equalTo: containerViewFile.centerYAnchor).isActive = true
  3619. imageFile.widthAnchor.constraint(equalToConstant: 30).isActive = true
  3620. imageFile.heightAnchor.constraint(equalToConstant: 30).isActive = true
  3621. imageFile.tintColor = .docColor
  3622. nameFile.translatesAutoresizingMaskIntoConstraints = false
  3623. nameFile.centerYAnchor.constraint(equalTo: containerViewFile.centerYAnchor).isActive = true
  3624. nameFile.widthAnchor.constraint(lessThanOrEqualToConstant: 200).isActive = true
  3625. nameFile.font = UIFont.systemFont(ofSize: 12, weight: .medium)
  3626. nameFile.textColor = .white
  3627. nameFile.text = textChat?.components(separatedBy: "|")[0]
  3628. if (dataMessages[indexPath.row]["progress"] as! Double != 100.0) {
  3629. let containerLoading = UIView()
  3630. containerViewFile.addSubview(containerLoading)
  3631. containerLoading.translatesAutoresizingMaskIntoConstraints = false
  3632. containerLoading.centerYAnchor.constraint(equalTo: containerViewFile.centerYAnchor).isActive = true
  3633. containerLoading.leadingAnchor.constraint(equalTo: nameFile.trailingAnchor, constant: 5).isActive = true
  3634. containerLoading.trailingAnchor.constraint(equalTo: containerViewFile.trailingAnchor, constant: -5).isActive = true
  3635. containerLoading.widthAnchor.constraint(equalToConstant: 30).isActive = true
  3636. containerLoading.heightAnchor.constraint(equalToConstant: 30).isActive = true
  3637. let circlePath = UIBezierPath(arcCenter: CGPoint(x: 15, y: 15), radius: 10, startAngle: -(.pi / 2), endAngle: .pi * 2, clockwise: true)
  3638. let trackShape = CAShapeLayer()
  3639. trackShape.path = circlePath.cgPath
  3640. trackShape.fillColor = UIColor.clear.cgColor
  3641. trackShape.lineWidth = 5
  3642. trackShape.strokeColor = UIColor.blueBubbleColor.withAlphaComponent(0.3).cgColor
  3643. containerLoading.layer.addSublayer(trackShape)
  3644. let shapeLoading = CAShapeLayer()
  3645. shapeLoading.path = circlePath.cgPath
  3646. shapeLoading.fillColor = UIColor.clear.cgColor
  3647. shapeLoading.lineWidth = 3
  3648. shapeLoading.strokeEnd = 0
  3649. shapeLoading.strokeColor = UIColor.secondaryColor.cgColor
  3650. containerLoading.layer.addSublayer(shapeLoading)
  3651. var imageupload = UIImageView(image: UIImage(systemName: "arrow.up", withConfiguration: UIImage.SymbolConfiguration(pointSize: 10, weight: .bold, scale: .default)))
  3652. if dataMessages[indexPath.row]["f_pin"] as? String != idMe {
  3653. imageupload = UIImageView(image: UIImage(systemName: "arrow.down", withConfiguration: UIImage.SymbolConfiguration(pointSize: 10, weight: .bold, scale: .default)))
  3654. shapeLoading.strokeColor = UIColor.blueBubbleColor.cgColor
  3655. }
  3656. imageupload.tintColor = .white
  3657. containerLoading.addSubview(imageupload)
  3658. imageupload.translatesAutoresizingMaskIntoConstraints = false
  3659. imageupload.centerYAnchor.constraint(equalTo: containerLoading.centerYAnchor).isActive = true
  3660. imageupload.centerXAnchor.constraint(equalTo: containerLoading.centerXAnchor).isActive = true
  3661. } else {
  3662. nameFile.trailingAnchor.constraint(equalTo: containerViewFile.trailingAnchor, constant: -5).isActive = true
  3663. }
  3664. if !copySession && !forwardSession && !deleteSession {
  3665. let objectTap = ObjectGesture(target: self, action: #selector(contentMessageTapped(_:)))
  3666. containerViewFile.addGestureRecognizer(objectTap)
  3667. objectTap.containerFile = containerViewFile
  3668. objectTap.labelFile = nameFile
  3669. objectTap.file_id = fileChat
  3670. objectTap.indexPath = indexPath
  3671. }
  3672. }
  3673. let containerLinkMessage = UIView()
  3674. if thumbChat.isEmpty && fileChat.isEmpty && !textChat!.isEmpty {
  3675. var text = ""
  3676. let listTextSplitBreak = textChat!.components(separatedBy: "\n")
  3677. let indexFirstLinkSplitBreak = listTextSplitBreak.firstIndex(where: { $0.contains("www.") || $0.contains("http://") || $0.contains("https://") })
  3678. if indexFirstLinkSplitBreak != nil {
  3679. let listTextSplitSpace = listTextSplitBreak[indexFirstLinkSplitBreak!].components(separatedBy: " ")
  3680. 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) })
  3681. if indexFirstLinkSplitSpace != nil {
  3682. text = listTextSplitSpace[indexFirstLinkSplitSpace!]
  3683. }
  3684. }
  3685. if !text.isEmpty {
  3686. func showLink() {
  3687. if let data = try! JSONSerialization.jsonObject(with: dataURL.data(using: String.Encoding.utf8)!, options: []) as? [String: Any] {
  3688. let title = data["title"] as! String
  3689. let description = data["description"] as! String
  3690. let imageUrl = data["imageUrl"] as? String
  3691. let link = data["link"] as! String
  3692. topMarginText.constant = topMarginText.constant + 80
  3693. containerMessage.addSubview(containerLinkMessage)
  3694. containerLinkMessage.translatesAutoresizingMaskIntoConstraints = false
  3695. containerLinkMessage.leadingAnchor.constraint(equalTo:containerMessage.leadingAnchor, constant: 15).isActive = true
  3696. if dataMessages[indexPath.row]["attachment_flag"] as? String == "11" {
  3697. containerLinkMessage.bottomAnchor.constraint(equalTo: imageSticker.topAnchor, constant: -5).isActive = true
  3698. } else {
  3699. containerLinkMessage.bottomAnchor.constraint(equalTo: messageText.topAnchor, constant: -5).isActive = true
  3700. }
  3701. containerLinkMessage.trailingAnchor.constraint(equalTo: containerMessage.trailingAnchor, constant: -15).isActive = true
  3702. containerLinkMessage.heightAnchor.constraint(equalToConstant: 80.0).isActive = true
  3703. containerLinkMessage.backgroundColor = .gray.withAlphaComponent(0.2)
  3704. let imagePreview = UIImageView()
  3705. if imageUrl != nil {
  3706. containerLinkMessage.addSubview(imagePreview)
  3707. imagePreview.translatesAutoresizingMaskIntoConstraints = false
  3708. imagePreview.leadingAnchor.constraint(equalTo: containerLinkMessage.leadingAnchor).isActive = true
  3709. imagePreview.bottomAnchor.constraint(equalTo: containerLinkMessage.bottomAnchor).isActive = true
  3710. imagePreview.topAnchor.constraint(equalTo: containerLinkMessage.topAnchor).isActive = true
  3711. imagePreview.widthAnchor.constraint(equalToConstant: 80.0).isActive = true
  3712. if !imageUrl!.starts(with: "https://") {
  3713. imagePreview.loadImageAsync(with: "https://www.google.be" + imageUrl!)
  3714. } else {
  3715. imagePreview.loadImageAsync(with: imageUrl)
  3716. }
  3717. imagePreview.contentMode = .scaleAspectFit
  3718. }
  3719. let titlePreview = UILabel()
  3720. containerLinkMessage.addSubview(titlePreview)
  3721. titlePreview.translatesAutoresizingMaskIntoConstraints = false
  3722. if imageUrl != nil {
  3723. titlePreview.leadingAnchor.constraint(equalTo: imagePreview.trailingAnchor, constant: 5.0).isActive = true
  3724. } else {
  3725. titlePreview.leadingAnchor.constraint(equalTo: containerLinkMessage.leadingAnchor, constant: 5.0).isActive = true
  3726. }
  3727. titlePreview.topAnchor.constraint(equalTo: containerLinkMessage.topAnchor, constant: 25.0).isActive = true
  3728. titlePreview.trailingAnchor.constraint(equalTo: containerLinkMessage.trailingAnchor, constant: -80.0).isActive = true
  3729. titlePreview.text = title
  3730. titlePreview.font = UIFont.systemFont(ofSize: 14.0, weight: .bold)
  3731. titlePreview.textColor = .black
  3732. let descPreview = UILabel()
  3733. containerLinkMessage.addSubview(descPreview)
  3734. descPreview.translatesAutoresizingMaskIntoConstraints = false
  3735. if imageUrl != nil {
  3736. descPreview.leadingAnchor.constraint(equalTo: imagePreview.trailingAnchor, constant: 5.0).isActive = true
  3737. } else {
  3738. descPreview.leadingAnchor.constraint(equalTo: containerLinkMessage.leadingAnchor, constant: 5.0).isActive = true
  3739. }
  3740. descPreview.topAnchor.constraint(equalTo: titlePreview.bottomAnchor).isActive = true
  3741. descPreview.trailingAnchor.constraint(equalTo: containerLinkMessage.trailingAnchor, constant: -80.0).isActive = true
  3742. descPreview.text = description
  3743. descPreview.font = UIFont.systemFont(ofSize: 12.0)
  3744. descPreview.textColor = .gray
  3745. descPreview.numberOfLines = 1
  3746. let linkPreview = UILabel()
  3747. containerLinkMessage.addSubview(linkPreview)
  3748. linkPreview.translatesAutoresizingMaskIntoConstraints = false
  3749. if imageUrl != nil {
  3750. linkPreview.leadingAnchor.constraint(equalTo: imagePreview.trailingAnchor, constant: 5.0).isActive = true
  3751. } else {
  3752. linkPreview.leadingAnchor.constraint(equalTo: containerLinkMessage.leadingAnchor, constant: 5.0).isActive = true
  3753. }
  3754. linkPreview.topAnchor.constraint(equalTo: descPreview.bottomAnchor, constant: 8.0).isActive = true
  3755. linkPreview.trailingAnchor.constraint(equalTo: containerLinkMessage.trailingAnchor, constant: -80.0).isActive = true
  3756. linkPreview.text = link
  3757. linkPreview.font = UIFont.systemFont(ofSize: 10.0)
  3758. linkPreview.textColor = .gray
  3759. linkPreview.numberOfLines = 1
  3760. if !copySession && !forwardSession && !deleteSession {
  3761. let objectTap = ObjectGesture(target: self, action: #selector(tapMessageText(_:)))
  3762. objectTap.message_id = text
  3763. containerLinkMessage.addGestureRecognizer(objectTap)
  3764. }
  3765. }
  3766. }
  3767. var dataURL = ""
  3768. Database.shared.database?.inTransaction({ (fmdb, rollback) in
  3769. if let cursor = Database.shared.getRecords(fmdb: fmdb, query: "select data_link from LINK_PREVIEW where link='\(text)'"), cursor.next() {
  3770. if let data = cursor.string(forColumnIndex: 0) {
  3771. dataURL = data
  3772. }
  3773. cursor.close()
  3774. }
  3775. })
  3776. if dataURL.isEmpty {
  3777. let slp = SwiftLinkPreview(session: URLSession.shared,
  3778. workQueue: SwiftLinkPreview.defaultWorkQueue,
  3779. responseQueue: DispatchQueue.main,
  3780. cache: DisabledCache.instance)
  3781. let preview = slp.preview(text,
  3782. onSuccess: { result in
  3783. let title = result.title ?? "No Title"
  3784. let description = text.contains("google.com") ? "" : result.description
  3785. let imageUrl = result.image
  3786. Database.shared.database?.inTransaction({ (fmdb, rollback) in
  3787. do {
  3788. var dataJson: [String: Any] = [:]
  3789. dataJson["title"] = title
  3790. dataJson["description"] = description
  3791. dataJson["imageUrl"] = imageUrl
  3792. dataJson["link"] = text
  3793. guard let json = String(data: try! JSONSerialization.data(withJSONObject: dataJson, options: []), encoding: String.Encoding.utf8) else {
  3794. return
  3795. }
  3796. _ = try Database.shared.insertRecord(fmdb: fmdb, table: "LINK_PREVIEW", cvalues: [
  3797. "id" : "\(Date().currentTimeMillis().toHex())",
  3798. "link" : text,
  3799. "data_link" : json,
  3800. "retry": 0
  3801. ], replace: true)
  3802. dataURL = json
  3803. showLink()
  3804. } catch {
  3805. rollback.pointee = true
  3806. //print(error)
  3807. }
  3808. })
  3809. }, onError: { error in
  3810. })
  3811. } else {
  3812. showLink()
  3813. }
  3814. }
  3815. }
  3816. if (reffChat != "") {
  3817. let data = queryMessageReply(message_id: reffChat)
  3818. if data.count != 0 {
  3819. topMarginText.constant = topMarginText.constant + 55
  3820. let containerReply = UIView()
  3821. containerMessage.addSubview(containerReply)
  3822. containerReply.translatesAutoresizingMaskIntoConstraints = false
  3823. containerReply.leadingAnchor.constraint(equalTo: containerMessage.leadingAnchor, constant: 15).isActive = true
  3824. containerReply.topAnchor.constraint(equalTo: containerMessage.topAnchor, constant: 32).isActive = true
  3825. if thumbChat != "" && (dataMessages[indexPath.row]["lock"] == nil || dataMessages[indexPath.row]["lock"] as! String != "1") {
  3826. containerReply.bottomAnchor.constraint(equalTo: imageThumb.topAnchor, constant: -5).isActive = true
  3827. } else if fileChat != "" && (dataMessages[indexPath.row]["lock"] == nil || dataMessages[indexPath.row]["lock"] as! String != "1") {
  3828. containerReply.bottomAnchor.constraint(equalTo: containerViewFile.topAnchor, constant: -5).isActive = true
  3829. } else if containerMessage.subviews.contains(containerLinkMessage) {
  3830. containerReply.bottomAnchor.constraint(equalTo: containerLinkMessage.topAnchor, constant: -5).isActive = true
  3831. } else if dataMessages[indexPath.row]["attachment_flag"] as? String == "11" && (dataMessages[indexPath.row]["lock"] == nil || dataMessages[indexPath.row]["lock"] as! String != "1") {
  3832. containerReply.bottomAnchor.constraint(equalTo: imageSticker.topAnchor, constant: -5).isActive = true
  3833. } else {
  3834. containerReply.bottomAnchor.constraint(equalTo: messageText.topAnchor, constant: -5).isActive = true
  3835. }
  3836. containerReply.trailingAnchor.constraint(equalTo: containerMessage.trailingAnchor, constant: -15).isActive = true
  3837. containerReply.heightAnchor.constraint(equalToConstant: 50).isActive = true
  3838. containerReply.backgroundColor = .black.withAlphaComponent(0.2)
  3839. containerReply.layer.cornerRadius = 5
  3840. containerReply.clipsToBounds = true
  3841. let leftReply = UIView()
  3842. containerReply.addSubview(leftReply)
  3843. leftReply.translatesAutoresizingMaskIntoConstraints = false
  3844. leftReply.leadingAnchor.constraint(equalTo: containerReply.leadingAnchor).isActive = true
  3845. leftReply.topAnchor.constraint(equalTo: containerReply.topAnchor).isActive = true
  3846. leftReply.bottomAnchor.constraint(equalTo: containerReply.bottomAnchor).isActive = true
  3847. leftReply.widthAnchor.constraint(equalToConstant: 3).isActive = true
  3848. leftReply.layer.cornerRadius = 5
  3849. leftReply.clipsToBounds = true
  3850. leftReply.layer.maskedCorners = [.layerMinXMaxYCorner, .layerMinXMinYCorner]
  3851. let titleReply = UILabel()
  3852. containerReply.addSubview(titleReply)
  3853. titleReply.translatesAutoresizingMaskIntoConstraints = false
  3854. titleReply.leadingAnchor.constraint(equalTo: leftReply.leadingAnchor, constant: 10).isActive = true
  3855. titleReply.topAnchor.constraint(equalTo: containerReply.topAnchor, constant: 10).isActive = true
  3856. titleReply.trailingAnchor.constraint(lessThanOrEqualTo: containerReply.trailingAnchor, constant: -20).isActive = true
  3857. titleReply.font = UIFont.systemFont(ofSize: 12).bold
  3858. if (data["f_pin"] as? String == idMe) {
  3859. titleReply.text = "You".localized()
  3860. if dataMessages[indexPath.row]["f_pin"] as? String == idMe {
  3861. titleReply.textColor = .white
  3862. leftReply.backgroundColor = .white
  3863. } else {
  3864. titleReply.textColor = .mainColor
  3865. leftReply.backgroundColor = .mainColor
  3866. }
  3867. } else {
  3868. if data["f_pin"] as? String != "-999" {
  3869. let dataProfile = getDataProfile(f_pin: data["f_pin"] as! String, message_id: data["message_id"] as! String)
  3870. titleReply.text = dataProfile["name"]
  3871. } else {
  3872. titleReply.text = "Bot"
  3873. }
  3874. if dataMessages[indexPath.row]["f_pin"] as? String == idMe {
  3875. titleReply.textColor = .white
  3876. leftReply.backgroundColor = .white
  3877. } else {
  3878. titleReply.textColor = .mainColor
  3879. leftReply.backgroundColor = .mainColor
  3880. }
  3881. }
  3882. let contentReply = UILabel()
  3883. containerReply.addSubview(contentReply)
  3884. contentReply.translatesAutoresizingMaskIntoConstraints = false
  3885. contentReply.leadingAnchor.constraint(equalTo: leftReply.leadingAnchor, constant: 10).isActive = true
  3886. contentReply.bottomAnchor.constraint(equalTo: containerReply.bottomAnchor, constant: -10).isActive = true
  3887. contentReply.font = UIFont.systemFont(ofSize: 10)
  3888. let message_text = data["message_text"] as? String ?? ""
  3889. let attachment_flag = data["attachment_flag"] as? String ?? ""
  3890. let thumb_chat = data["thumb_id"] as? String ?? ""
  3891. let image_chat = data["image_id"] as? String ?? ""
  3892. let video_chat = data["video_id"] as? String ?? ""
  3893. let file_chat = data["file_id"] as? String ?? ""
  3894. if (attachment_flag == "0" && thumb_chat == "") {
  3895. contentReply.trailingAnchor.constraint(equalTo: containerReply.trailingAnchor, constant: -20).isActive = true
  3896. contentReply.attributedText = message_text.richText(group_id: self.dataGroup["group_id"] as! String)
  3897. } else if (attachment_flag == "1" || image_chat != "") {
  3898. if (message_text == "") {
  3899. contentReply.text = "📷 Photo".localized()
  3900. } else {
  3901. contentReply.attributedText = message_text.richText(group_id: self.dataGroup["group_id"] as! String)
  3902. }
  3903. } else if (attachment_flag == "2" || video_chat != "") {
  3904. if (message_text == "") {
  3905. contentReply.text = "📹 Video".localized()
  3906. } else {
  3907. contentReply.attributedText = message_text.richText(group_id: self.dataGroup["group_id"] as! String)
  3908. }
  3909. } else if (attachment_flag == "6" || file_chat != ""){
  3910. contentReply.trailingAnchor.constraint(equalTo: containerReply.trailingAnchor, constant: -20).isActive = true
  3911. contentReply.text = "📄 \(message_text.components(separatedBy: "|")[0])"
  3912. } else if (attachment_flag == "11") {
  3913. contentReply.text = "❤️ Sticker"
  3914. } else if attachment_flag == "27" {
  3915. contentReply.trailingAnchor.constraint(equalTo: containerReply.trailingAnchor, constant: -20).isActive = true
  3916. contentReply.text = "📄 " + "Live Streaming".localized()
  3917. } else if attachment_flag == "26" {
  3918. contentReply.trailingAnchor.constraint(equalTo: containerReply.trailingAnchor, constant: -20).isActive = true
  3919. contentReply.text = "📄 " + "Seminar".localized()
  3920. }
  3921. contentReply.textColor = .white.withAlphaComponent(0.8)
  3922. if (attachment_flag == "1" || attachment_flag == "2" || image_chat != "" || video_chat != "") {
  3923. let nsDocumentDirectory = FileManager.SearchPathDirectory.documentDirectory
  3924. let nsUserDomainMask = FileManager.SearchPathDomainMask.userDomainMask
  3925. let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true)
  3926. if let dirPath = paths.first {
  3927. let thumbURL = URL(fileURLWithPath: dirPath).appendingPathComponent(thumb_chat)
  3928. let image : UIImage? = {
  3929. if let img = DigiX.imageCache.object(forKey: thumb_chat as NSString) {
  3930. return img
  3931. }
  3932. else if let img = UIImage(contentsOfFile: thumbURL.path)?.resize(target: CGSize(width: 500, height: 500)) {
  3933. DigiX.imageCache.setObject(img, forKey: thumb_chat as NSString)
  3934. return img
  3935. }
  3936. return nil
  3937. }()
  3938. // let image = UIGraphicsRenderer.renderImageAt(url: thumbURL as NSURL, size: CGSize(width: 250, height: 250))
  3939. let imageThumb = UIImageView(image: image)
  3940. containerReply.addSubview(imageThumb)
  3941. imageThumb.layer.cornerRadius = 2.0
  3942. imageThumb.clipsToBounds = true
  3943. imageThumb.contentMode = .scaleAspectFill
  3944. imageThumb.translatesAutoresizingMaskIntoConstraints = false
  3945. imageThumb.trailingAnchor.constraint(equalTo: containerReply.trailingAnchor, constant: -10).isActive = true
  3946. imageThumb.centerYAnchor.constraint(equalTo: containerReply.centerYAnchor).isActive = true
  3947. imageThumb.widthAnchor.constraint(equalToConstant: 30).isActive = true
  3948. imageThumb.heightAnchor.constraint(equalToConstant: 30).isActive = true
  3949. if (attachment_flag == "2") {
  3950. let imagePlay = UIImageView(image: UIImage(systemName: "play.circle.fill"))
  3951. imageThumb.addSubview(imagePlay)
  3952. imagePlay.clipsToBounds = true
  3953. imagePlay.translatesAutoresizingMaskIntoConstraints = false
  3954. imagePlay.centerYAnchor.constraint(equalTo: imageThumb.centerYAnchor).isActive = true
  3955. imagePlay.centerXAnchor.constraint(equalTo: imageThumb.centerXAnchor).isActive = true
  3956. imagePlay.widthAnchor.constraint(equalToConstant: 10).isActive = true
  3957. imagePlay.heightAnchor.constraint(equalToConstant: 10).isActive = true
  3958. imagePlay.tintColor = .white
  3959. }
  3960. titleReply.trailingAnchor.constraint(equalTo: imageThumb.leadingAnchor, constant: -20).isActive = true
  3961. contentReply.trailingAnchor.constraint(equalTo: imageThumb.leadingAnchor, constant: -20).isActive = true
  3962. }
  3963. }
  3964. if (attachment_flag == "11") {
  3965. let imageSticker = UIImageView(image: UIImage(named: (message_text.components(separatedBy: "/")[1]), in: Bundle.resourceBundle(for: DigiX.self), with: nil))
  3966. containerReply.addSubview(imageSticker)
  3967. imageSticker.layer.cornerRadius = 2.0
  3968. imageSticker.clipsToBounds = true
  3969. imageSticker.translatesAutoresizingMaskIntoConstraints = false
  3970. imageSticker.trailingAnchor.constraint(equalTo: containerReply.trailingAnchor, constant: -10).isActive = true
  3971. imageSticker.centerYAnchor.constraint(equalTo: containerReply.centerYAnchor).isActive = true
  3972. imageSticker.widthAnchor.constraint(equalToConstant: 30).isActive = true
  3973. imageSticker.heightAnchor.constraint(equalToConstant: 30).isActive = true
  3974. titleReply.trailingAnchor.constraint(equalTo: imageSticker.leadingAnchor, constant: -20).isActive = true
  3975. contentReply.trailingAnchor.constraint(equalTo: imageSticker.leadingAnchor, constant: -20).isActive = true
  3976. }
  3977. if !copySession && !forwardSession && !deleteSession {
  3978. let objectTap = ObjectGesture(target: self, action: #selector(contentMessageTapped(_:)))
  3979. containerReply.addGestureRecognizer(objectTap)
  3980. objectTap.indexPath = indexPath
  3981. objectTap.message_id = data["message_id"] as! String
  3982. }
  3983. }
  3984. }
  3985. return cellMessage
  3986. }
  3987. @objc func imageGroupingTapped(_ sender: ObjectGesture) {
  3988. let listGroupingImages = ListGroupImages()
  3989. listGroupingImages.imageTapped = sender.indexImageTapped
  3990. listGroupingImages.listGroupingImages = sender.listImageFromGrouping
  3991. listGroupingImages.titleName = titleText
  3992. listGroupingImages.isInitiator = sender.isInitiator
  3993. listGroupingImages.isPersonal = false
  3994. listGroupingImages.updateEditor = { [self] updatedData, replyData, isUpdateDelete in
  3995. if replyData.count == 0 {
  3996. if updatedData.count != 0 && !isUpdateDelete {
  3997. groupImages[sender.listImageFromGrouping[0].messageId] = updatedData
  3998. } else if updatedData.count > 0 {
  3999. let deletedForEveryoneData = updatedData.filter({ $0.dataMessage["lock"] as? String == "1" })
  4000. if deletedForEveryoneData.count != 0 {
  4001. if groupImages[sender.listImageFromGrouping[0].messageId] != nil {
  4002. var dataWillEmpty = updatedData
  4003. while dataWillEmpty.count > 0 {
  4004. if let lastIdx = dataWillEmpty.lastIndex(where: { $0.dataMessage["lock"] as? String == "1" }) {
  4005. if let idx = self.dataMessages.firstIndex(where: { $0["message_id"] as! String == sender.listImageFromGrouping[0].messageId }) {
  4006. if dataWillEmpty[lastIdx].messageId == sender.listImageFromGrouping[0].messageId {
  4007. self.dataMessages.remove(at: idx)
  4008. self.dataMessages.insert(dataWillEmpty[lastIdx].dataMessage, at: idx)
  4009. } else {
  4010. self.dataMessages.insert(dataWillEmpty[lastIdx].dataMessage, at: idx + 1)
  4011. }
  4012. let subData = Array(updatedData[lastIdx+1..<dataWillEmpty.count])
  4013. if subData.count >= 4 {
  4014. groupImages[subData[0].messageId] = subData
  4015. self.dataMessages.insert(subData[0].dataMessage, at: lastIdx + 1)
  4016. } else {
  4017. if subData.count > 0 {
  4018. self.dataMessages.insert(contentsOf: subData.map({ $0.dataMessage }), at: idx + (dataWillEmpty[lastIdx].messageId == sender.listImageFromGrouping[0].messageId ? 1 : 2))
  4019. }
  4020. }
  4021. }
  4022. dataWillEmpty.removeSubrange(lastIdx..<dataWillEmpty.count)
  4023. } else if dataWillEmpty.count >= 4 {
  4024. groupImages[dataWillEmpty[0].messageId] = dataWillEmpty
  4025. dataWillEmpty.removeAll()
  4026. } else {
  4027. if let idx = self.dataMessages.firstIndex(where: { $0["message_id"] as! String == sender.listImageFromGrouping[0].messageId }) {
  4028. self.dataMessages.remove(at: idx)
  4029. self.dataMessages.insert(contentsOf: dataWillEmpty.map({ $0.dataMessage }), at: idx)
  4030. groupImages.removeValue(forKey: sender.listImageFromGrouping[0].messageId)
  4031. }
  4032. dataWillEmpty.removeAll()
  4033. }
  4034. }
  4035. } else {
  4036. }
  4037. } else {
  4038. if updatedData.count >= 4 {
  4039. if updatedData[0].messageId == sender.listImageFromGrouping[0].messageId {
  4040. groupImages[sender.listImageFromGrouping[0].messageId] = updatedData
  4041. } else {
  4042. if let idx = self.dataMessages.firstIndex(where: { $0["message_id"] as! String == sender.listImageFromGrouping[0].messageId }) {
  4043. self.dataMessages.remove(at: idx)
  4044. self.dataMessages.insert(updatedData[0].dataMessage, at: idx)
  4045. groupImages.removeValue(forKey: sender.listImageFromGrouping[0].messageId)
  4046. groupImages[updatedData[0].messageId] = updatedData
  4047. }
  4048. }
  4049. } else {
  4050. if let idx = self.dataMessages.firstIndex(where: { $0["message_id"] as! String == sender.listImageFromGrouping[0].messageId }) {
  4051. groupImages.removeValue(forKey: sender.listImageFromGrouping[0].messageId)
  4052. self.dataMessages.remove(at: idx)
  4053. let dataMessageInGrouping = updatedData.map({ $0.dataMessage })
  4054. self.dataMessages.insert(contentsOf: dataMessageInGrouping, at: idx)
  4055. }
  4056. }
  4057. }
  4058. } else {
  4059. groupImages.removeValue(forKey: sender.listImageFromGrouping[0].messageId)
  4060. if let idx = self.dataMessages.firstIndex(where: { $0["message_id"] as! String == sender.listImageFromGrouping[0].messageId }) {
  4061. self.dataMessages.remove(at: idx)
  4062. }
  4063. }
  4064. DispatchQueue.main.async { [self] in
  4065. tableChatView.reloadData()
  4066. }
  4067. } else if replyData.count != 0 {
  4068. handleReply(indexPath: IndexPath(row: 0, section: 0), dataMessagesImage: replyData)
  4069. }
  4070. }
  4071. self.navigationController?.pushViewController(listGroupingImages, animated: true)
  4072. }
  4073. @objc func tapAck(_ sender: ObjectGesture) {
  4074. let indexPath = sender.indexPath
  4075. let dataMessages = self.dataMessages.filter({ $0["chat_date"] as! String == dataDates[indexPath.section]})
  4076. if dataMessages[indexPath.row]["status"] as! String == "8" {
  4077. return
  4078. }
  4079. if !CheckConnection.isConnectedToNetwork() || API.nGetCLXConnState() == 0 {
  4080. let imageView = UIImageView(image: UIImage(systemName: "xmark.circle.fill"))
  4081. imageView.tintColor = .white
  4082. 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)
  4083. banner.show()
  4084. return
  4085. }
  4086. DispatchQueue.global().async {
  4087. var opposite_pin = self.dataGroup["group_id"] as! String
  4088. if (self.dataTopic["chat_id"] as! String != "") {
  4089. opposite_pin = self.dataTopic["chat_id"] as! String
  4090. }
  4091. let result = DigiX.write(message: CoreMessage_TMessageBank.getAckLocationMessage(f_pin: dataMessages[indexPath.row]["f_pin"] as! String, message_id: dataMessages[indexPath.row]["message_id"] as! String, l_pin: opposite_pin, server_date: "\(Date().currentTimeMillis())", message_scope_id: dataMessages[indexPath.row]["message_scope_id"] as! String, longitude: "", latitude: "", description: ""))
  4092. if result != nil {
  4093. Database.shared.database?.inTransaction({ (fmdb, rollback) in
  4094. _ = Database.shared.updateRecord(fmdb: fmdb, table: "MESSAGE", cvalues: [
  4095. "status" : "8"
  4096. ], _where: "message_id = '\(dataMessages[indexPath.row]["message_id"] as! String)'")
  4097. })
  4098. DispatchQueue.main.async {
  4099. if let index = self.dataMessages.firstIndex(where: {$0["message_id"] as? String == dataMessages[indexPath.row]["message_id"] as? String}) {
  4100. self.dataMessages[index]["status"] = "8"
  4101. let section = self.dataDates.firstIndex(of: self.dataMessages[index]["chat_date"] as! String)
  4102. 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})
  4103. if row != nil && section != nil {
  4104. self.tableChatView.reloadRows(at: [IndexPath(row: row!, section: section!)], with: .none)
  4105. }
  4106. self.showToast(message: "Confirmation Success.".localized(), font: UIFont.systemFont(ofSize: 12, weight: .medium), controller: self)
  4107. }
  4108. }
  4109. }
  4110. }
  4111. }
  4112. @objc func contentMessageTapped(_ sender: ObjectGesture) {
  4113. let nsDocumentDirectory = FileManager.SearchPathDirectory.documentDirectory
  4114. let nsUserDomainMask = FileManager.SearchPathDomainMask.userDomainMask
  4115. let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true)
  4116. if (sender.image_id != "") {
  4117. if let dirPath = paths.first {
  4118. let imageURL = URL(fileURLWithPath: dirPath).appendingPathComponent(sender.image_id)
  4119. if FileManager.default.fileExists(atPath: imageURL.path) {
  4120. let image = UIImage(contentsOfFile: imageURL.path)
  4121. let previewImageVC = PreviewAttachmentImageVideo(nibName: "PreviewAttachmentImageVideo", bundle: Bundle.resourceBundle(for: DigiX.self))
  4122. previewImageVC.image = image
  4123. previewImageVC.isHiddenTextField = true
  4124. previewImageVC.modalPresentationStyle = .custom
  4125. previewImageVC.modalTransitionStyle = .crossDissolve
  4126. self.present(previewImageVC, animated: true, completion: nil)
  4127. } else {
  4128. for view in sender.imageView.subviews {
  4129. if view is UIImageView {
  4130. view.removeFromSuperview()
  4131. }
  4132. }
  4133. let activityIndicator = UIActivityIndicatorView(style: .large)
  4134. activityIndicator.color = .mainColor
  4135. activityIndicator.hidesWhenStopped = true
  4136. activityIndicator.center = CGPoint(x:sender.imageView.frame.width/2,
  4137. y: sender.imageView.frame.height/2)
  4138. activityIndicator.startAnimating()
  4139. sender.imageView.addSubview(activityIndicator)
  4140. Download().startHTTP(forKey: sender.image_id) { (name, progress) in
  4141. guard progress == 100 else {
  4142. return
  4143. }
  4144. let imageURL = URL(fileURLWithPath: dirPath).appendingPathComponent(sender.image_id)
  4145. let image = UIImage(contentsOfFile: imageURL.path)
  4146. let save = UserDefaults.standard.bool(forKey: "saveToGallery")
  4147. if save {
  4148. UIImageWriteToSavedPhotosAlbum(image!, nil, nil, nil)
  4149. }
  4150. DispatchQueue.main.async {
  4151. activityIndicator.stopAnimating()
  4152. self.tableChatView.reloadRows(at: [sender.indexPath], with: .none)
  4153. }
  4154. }
  4155. }
  4156. }
  4157. } else if (sender.video_id != "") {
  4158. if let dirPath = paths.first {
  4159. let videoURL = URL(fileURLWithPath: dirPath).appendingPathComponent(sender.video_id)
  4160. if FileManager.default.fileExists(atPath: videoURL.path) {
  4161. let player = AVPlayer(url: videoURL as URL)
  4162. let playerVC = AVPlayerViewController()
  4163. playerVC.modalPresentationStyle = .custom
  4164. playerVC.player = player
  4165. self.present(playerVC, animated: true, completion: nil)
  4166. } else {
  4167. for view in sender.imageView.subviews {
  4168. if view is UIImageView {
  4169. view.removeFromSuperview()
  4170. }
  4171. }
  4172. let container = UIView()
  4173. sender.imageView.addSubview(container)
  4174. container.translatesAutoresizingMaskIntoConstraints = false
  4175. container.centerXAnchor.constraint(equalTo: sender.imageView.centerXAnchor).isActive = true
  4176. container.centerYAnchor.constraint(equalTo: sender.imageView.centerYAnchor).isActive = true
  4177. container.widthAnchor.constraint(equalToConstant: 50).isActive = true
  4178. container.heightAnchor.constraint(equalToConstant: 50).isActive = true
  4179. let circlePath = UIBezierPath(arcCenter: CGPoint(x: 25, y: 25), radius: 20, startAngle: -(.pi / 2), endAngle: .pi * 2, clockwise: true)
  4180. let trackShape = CAShapeLayer()
  4181. trackShape.path = circlePath.cgPath
  4182. trackShape.fillColor = UIColor.clear.cgColor
  4183. trackShape.lineWidth = 10
  4184. trackShape.strokeColor = UIColor.blueBubbleColor.withAlphaComponent(0.3).cgColor
  4185. container.backgroundColor = .clear
  4186. container.layer.addSublayer(trackShape)
  4187. let shapeLoading = CAShapeLayer()
  4188. shapeLoading.path = circlePath.cgPath
  4189. shapeLoading.fillColor = UIColor.clear.cgColor
  4190. shapeLoading.lineWidth = 10
  4191. shapeLoading.strokeEnd = 0
  4192. shapeLoading.strokeColor = UIColor.blueBubbleColor.cgColor
  4193. container.layer.addSublayer(shapeLoading)
  4194. let imageDownload = UIImageView(image: UIImage(systemName: "arrow.down", withConfiguration: UIImage.SymbolConfiguration(pointSize: 10, weight: .bold, scale: .default)))
  4195. imageDownload.tintColor = .white
  4196. container.addSubview(imageDownload)
  4197. imageDownload.translatesAutoresizingMaskIntoConstraints = false
  4198. imageDownload.centerXAnchor.constraint(equalTo: sender.imageView.centerXAnchor).isActive = true
  4199. imageDownload.centerYAnchor.constraint(equalTo: sender.imageView.centerYAnchor).isActive = true
  4200. imageDownload.widthAnchor.constraint(equalToConstant: 30).isActive = true
  4201. imageDownload.heightAnchor.constraint(equalToConstant: 30).isActive = true
  4202. Download().startHTTP(forKey: sender.video_id) { (name, progress) in
  4203. DispatchQueue.main.async {
  4204. guard progress == 100 else {
  4205. shapeLoading.strokeEnd = CGFloat(progress / 100)
  4206. return
  4207. }
  4208. let save = UserDefaults.standard.bool(forKey: "saveToGallery")
  4209. if save {
  4210. let videoURL = URL(fileURLWithPath: dirPath).appendingPathComponent(sender.video_id)
  4211. PHPhotoLibrary.shared().performChanges({
  4212. PHAssetChangeRequest.creationRequestForAssetFromVideo(atFileURL: videoURL)
  4213. }) { saved, error in
  4214. }
  4215. }
  4216. let idx = self.dataMessages.firstIndex(where: { $0["video_id"] as! String == sender.video_id})
  4217. if idx != nil {
  4218. self.dataMessages[idx!]["progress"] = progress
  4219. self.tableChatView.reloadRows(at: [sender.indexPath], with: .none)
  4220. }
  4221. }
  4222. }
  4223. }
  4224. }
  4225. } else if (sender.file_id != "") {
  4226. if let dirPath = paths.first {
  4227. let fileURL = URL(fileURLWithPath: dirPath).appendingPathComponent(sender.file_id)
  4228. if FileManager.default.fileExists(atPath: fileURL.path) {
  4229. self.previewItem = fileURL as NSURL
  4230. let previewController = QLPreviewController()
  4231. let rightBarButton = UIBarButtonItem()
  4232. previewController.navigationItem.rightBarButtonItem = rightBarButton
  4233. previewController.dataSource = self
  4234. previewController.modalPresentationStyle = .custom
  4235. self.show(previewController, sender: nil)
  4236. } else {
  4237. for view in sender.containerFile.subviews {
  4238. if !(view is UIImageView) && !(view is UILabel) {
  4239. view.removeFromSuperview()
  4240. }
  4241. }
  4242. let containerLoading = UIView()
  4243. sender.containerFile.addSubview(containerLoading)
  4244. containerLoading.translatesAutoresizingMaskIntoConstraints = false
  4245. containerLoading.centerYAnchor.constraint(equalTo: sender.containerFile.centerYAnchor).isActive = true
  4246. containerLoading.leadingAnchor.constraint(equalTo: sender.labelFile.trailingAnchor, constant: 5).isActive = true
  4247. containerLoading.trailingAnchor.constraint(equalTo: sender.containerFile.trailingAnchor, constant: -5).isActive = true
  4248. containerLoading.widthAnchor.constraint(equalToConstant: 30).isActive = true
  4249. containerLoading.heightAnchor.constraint(equalToConstant: 30).isActive = true
  4250. let circlePath = UIBezierPath(arcCenter: CGPoint(x: 15, y: 15), radius: 10, startAngle: -(.pi / 2), endAngle: .pi * 2, clockwise: true)
  4251. let trackShape = CAShapeLayer()
  4252. trackShape.path = circlePath.cgPath
  4253. trackShape.fillColor = UIColor.clear.cgColor
  4254. trackShape.lineWidth = 5
  4255. trackShape.strokeColor = UIColor.blueBubbleColor.withAlphaComponent(0.3).cgColor
  4256. containerLoading.layer.addSublayer(trackShape)
  4257. let shapeLoading = CAShapeLayer()
  4258. shapeLoading.path = circlePath.cgPath
  4259. shapeLoading.fillColor = UIColor.clear.cgColor
  4260. shapeLoading.lineWidth = 3
  4261. shapeLoading.strokeEnd = 0
  4262. shapeLoading.strokeColor = UIColor.blueBubbleColor.cgColor
  4263. containerLoading.layer.addSublayer(shapeLoading)
  4264. let imageupload = UIImageView(image: UIImage(systemName: "arrow.down", withConfiguration: UIImage.SymbolConfiguration(pointSize: 10, weight: .bold, scale: .default)))
  4265. imageupload.tintColor = .white
  4266. containerLoading.addSubview(imageupload)
  4267. imageupload.translatesAutoresizingMaskIntoConstraints = false
  4268. imageupload.centerYAnchor.constraint(equalTo: containerLoading.centerYAnchor).isActive = true
  4269. imageupload.centerXAnchor.constraint(equalTo: containerLoading.centerXAnchor).isActive = true
  4270. Download().startHTTP(forKey: sender.file_id) { (name, progress) in
  4271. DispatchQueue.main.async {
  4272. guard progress == 100 else {
  4273. shapeLoading.strokeEnd = CGFloat(progress / 100)
  4274. return
  4275. }
  4276. let idx = self.dataMessages.firstIndex(where: { $0["file_id"] as! String == sender.file_id})
  4277. if idx != nil {
  4278. self.dataMessages[idx!]["progress"] = progress
  4279. self.tableChatView.reloadRows(at: [sender.indexPath], with: .none)
  4280. }
  4281. }
  4282. }
  4283. }
  4284. }
  4285. } else {
  4286. DispatchQueue.main.async {
  4287. let idx = self.dataMessages.firstIndex(where: { $0["message_id"] as! String == sender.message_id})
  4288. if idx == nil {
  4289. return
  4290. }
  4291. let section = self.dataDates.firstIndex(of: self.dataMessages[idx!]["chat_date"] as! String)
  4292. if section == nil {
  4293. return
  4294. }
  4295. 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})
  4296. if row == nil {
  4297. return
  4298. }
  4299. let indexPath = IndexPath(row: row!, section: section!)
  4300. self.tableChatView.scrollToRow(at: indexPath, at: .middle, animated: true)
  4301. DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
  4302. if let cell = self.tableChatView.cellForRow(at: indexPath) {
  4303. let containerMessage = cell.contentView.subviews[1]
  4304. let idMe = UserDefaults.standard.string(forKey: "me") as String?
  4305. if (self.dataMessages[idx!]["f_pin"] as? String == idMe) {
  4306. containerMessage.backgroundColor = .blueBubbleColor.withAlphaComponent(0.3)
  4307. DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
  4308. if (self.dataMessages[idx!]["attachment_flag"] as? String == "11") {
  4309. containerMessage.backgroundColor = .clear
  4310. } else {
  4311. containerMessage.backgroundColor = .blueBubbleColor
  4312. }
  4313. }
  4314. } else {
  4315. containerMessage.backgroundColor = .grayColor.withAlphaComponent(0.3)
  4316. DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
  4317. if (self.dataMessages[idx!]["attachment_flag"] as? String == "11") {
  4318. containerMessage.backgroundColor = .clear
  4319. } else {
  4320. containerMessage.backgroundColor = .grayColor
  4321. }
  4322. }
  4323. }
  4324. }
  4325. }
  4326. }
  4327. }
  4328. }
  4329. @objc func handleLongPressLink(_ gestureRecognizer: UILongPressGestureRecognizer) {
  4330. func showMenuContext() {
  4331. if gestureRecognizer.state == .cancelled || gestureRecognizer.state == .ended{
  4332. timerCheckLink?.invalidate()
  4333. } else if gestureRecognizer.state == .began {
  4334. timerCheckLink = Timer.scheduledTimer(withTimeInterval: 0.2, repeats: false, block: {_ in
  4335. let interaction = UIContextMenuInteraction(delegate: self)
  4336. gestureRecognizer.view!.addInteraction(interaction)
  4337. guard let interaction = gestureRecognizer.view!.interactions.first,
  4338. let data = Data(base64Encoded: "X3ByZXNlbnRNZW51QXRMb2NhdGlvbjo="),
  4339. let str = String(data: data, encoding: .utf8)
  4340. else {
  4341. return
  4342. }
  4343. let selector = NSSelectorFromString(str)
  4344. guard interaction.responds(to: selector) else {
  4345. return
  4346. }
  4347. let impactHeavy = UIImpactFeedbackGenerator(style: .heavy)
  4348. impactHeavy.impactOccurred()
  4349. interaction.perform(selector, with: self.view)
  4350. self.isLinkCopied = true
  4351. })
  4352. }
  4353. }
  4354. if gestureRecognizer.state == .began {
  4355. let touchPoint = gestureRecognizer.location(in: self.view)
  4356. touchedSubview = self.view.hitTest(touchPoint, with: nil) ?? UIView()
  4357. if !(touchedSubview is UILabel) {
  4358. showMenuContext()
  4359. }
  4360. }
  4361. guard let label = touchedSubview as? UILabel else { return }
  4362. let touchPointLabel = gestureRecognizer.location(in: label)
  4363. if let text = label.text, let range = getWordRange(at: touchPointLabel, in: label) {
  4364. let word = String(text[range])
  4365. if word.starts(with: "www.") || word.starts(with: "https://") || word.starts(with: "http://") {
  4366. if gestureRecognizer.state == .cancelled || gestureRecognizer.state == .ended{
  4367. timerCheckLink?.invalidate()
  4368. if !isLinkCopied {
  4369. var stringURl = word
  4370. if stringURl.starts(with: "www.") {
  4371. stringURl = "https://" + stringURl.replacingOccurrences(of: "www.", with: "")
  4372. }
  4373. guard let url = URL(string: stringURl) else { return }
  4374. UIApplication.shared.open(url)
  4375. label.attributedText = removeHighlightedText(for: text, in: range, label: label)
  4376. }
  4377. isLinkCopied = false
  4378. } else if gestureRecognizer.state == .began {
  4379. label.attributedText = highlightedText(for: text, in: range, label: label)
  4380. timerCheckLink = Timer.scheduledTimer(withTimeInterval: 0.5, repeats: false, block: {_ in
  4381. self.isLinkCopied = true
  4382. UIPasteboard.general.string = word
  4383. self.showToast(message: "Link Copied".localized(), font: UIFont.systemFont(ofSize: 12, weight: .medium), controller: self)
  4384. label.attributedText = self.removeHighlightedText(for: text, in: range, label: label)
  4385. self.timerCheckLink?.invalidate()
  4386. })
  4387. }
  4388. } else {
  4389. showMenuContext()
  4390. }
  4391. } else {
  4392. showMenuContext()
  4393. }
  4394. }
  4395. func getWordRange(at point: CGPoint, in label: UILabel) -> Range<String.Index>? {
  4396. guard let text = label.text else { return nil }
  4397. let layoutManager = NSLayoutManager()
  4398. let textContainer = NSTextContainer(size: label.frame.size)
  4399. let textStorage = NSTextStorage(attributedString: NSAttributedString(string: text))
  4400. layoutManager.addTextContainer(textContainer)
  4401. textStorage.addLayoutManager(layoutManager)
  4402. textContainer.lineFragmentPadding = 0
  4403. textContainer.maximumNumberOfLines = label.numberOfLines
  4404. lastTouchPoint = point
  4405. let characterIndex = layoutManager.characterIndex(for: point, in: textContainer, fractionOfDistanceBetweenInsertionPoints: nil)
  4406. if characterIndex == text.count - 1 {
  4407. return nil
  4408. }
  4409. var wordStartIndex = characterIndex
  4410. while wordStartIndex > 0 && text[text.index(text.startIndex, offsetBy: wordStartIndex - 1)] != " " && text[text.index(text.startIndex, offsetBy: wordStartIndex - 1)] != "\n" {
  4411. wordStartIndex -= 1
  4412. }
  4413. var wordEndIndex = characterIndex
  4414. while wordEndIndex < text.count && text[text.index(text.startIndex, offsetBy: wordEndIndex)] != " " && text[text.index(text.startIndex, offsetBy: wordEndIndex)] != "\n" {
  4415. wordEndIndex += 1
  4416. }
  4417. return text.index(text.startIndex, offsetBy: wordStartIndex)..<text.index(text.startIndex, offsetBy: wordEndIndex)
  4418. }
  4419. func highlightedText(for text: String, in range: Range<String.Index>, label: UILabel) -> NSAttributedString {
  4420. let mutableAttributedString = label.attributedText!.mutableCopy() as! NSMutableAttributedString
  4421. mutableAttributedString.addAttribute(.backgroundColor, value: UIColor.lightGray.withAlphaComponent(0.5), range: NSRange(range, in: text))
  4422. return mutableAttributedString
  4423. }
  4424. func removeHighlightedText(for text: String, in range: Range<String.Index>, label: UILabel) -> NSAttributedString {
  4425. let mutableAttributedString = label.attributedText!.mutableCopy() as! NSMutableAttributedString
  4426. mutableAttributedString.removeAttribute(.backgroundColor, range: NSRange(range, in: text))
  4427. return mutableAttributedString
  4428. }
  4429. @objc func tapMessageText(_ sender: ObjectGesture) {
  4430. var stringURl = sender.message_id.lowercased()
  4431. if stringURl.starts(with: "www.") {
  4432. stringURl = "https://" + stringURl.replacingOccurrences(of: "www.", with: "")
  4433. }
  4434. guard let url = URL(string: stringURl) else { return }
  4435. UIApplication.shared.open(url)
  4436. }
  4437. // public func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
  4438. // if copySession || forwardSession || deleteSession {
  4439. // return nil
  4440. // }
  4441. // let idMe = UserDefaults.standard.string(forKey: "me") as String?
  4442. // if (dataMessages[indexPath.row]["f_pin"] as? String != idMe) {
  4443. // return nil
  4444. // }
  4445. // let messageInfoVC = MessageInfo()
  4446. // self.navigationController?.show(messageInfoVC, sender: nil)
  4447. // return UISwipeActionsConfiguration()
  4448. // }
  4449. //
  4450. // public func tableView(_ tableView: UITableView, leadingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
  4451. // if copySession || forwardSession || deleteSession {
  4452. // return nil
  4453. // }
  4454. // let action = UIContextualAction(style: .normal,
  4455. // title: "") { [weak self] (action, view, completionHandler) in
  4456. // self?.handleReply(indexPath: indexPath)
  4457. // completionHandler(true)
  4458. // }
  4459. // action.backgroundColor = .white
  4460. // action.image = UIImage(systemName: "arrowshape.turn.up.left.fill")?.withTintColor(.black, renderingMode: .alwaysOriginal)
  4461. // return UISwipeActionsConfiguration(actions: [action])
  4462. // }
  4463. private func handleReply(indexPath: IndexPath, dataMessagesImage: [String: Any?] = [:]) {
  4464. self.deleteReplyView()
  4465. var dataMessages = self.dataMessages.filter({ $0["chat_date"] as! String == dataDates[indexPath.section]})
  4466. if dataMessages.count != 0 {
  4467. dataMessages = [dataMessagesImage]
  4468. } else {
  4469. self.textFieldSend.becomeFirstResponder()
  4470. }
  4471. self.reffId = dataMessages[indexPath.row]["message_id"] as? String
  4472. UIView.animate(withDuration: 0.25, delay: 0.0, options: .curveEaseInOut, animations: {
  4473. self.constraintTopTextField.constant = self.constraintTopTextField.constant + 50
  4474. if self.contraintBottomMention.constant > 0 {
  4475. self.contraintBottomMention.constant = self.contraintBottomMention.constant + 50
  4476. }
  4477. }, completion: nil)
  4478. if (self.currentIndexpath != nil) {
  4479. DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) {
  4480. self.tableChatView.scrollToRow(at: IndexPath(row: self.currentIndexpath!.row, section: self.currentIndexpath!.section), at: .none, animated: false)
  4481. }
  4482. } else {
  4483. self.tableChatView.scrollToBottom()
  4484. }
  4485. self.viewTextfield.addSubview(self.containerPreviewReply)
  4486. self.containerPreviewReply.translatesAutoresizingMaskIntoConstraints = false
  4487. self.containerPreviewReply.leadingAnchor.constraint(equalTo: self.viewTextfield.leadingAnchor).isActive = true
  4488. self.containerPreviewReply.topAnchor.constraint(equalTo: self.viewTextfield.topAnchor).isActive = true
  4489. if !self.containerLink.isDescendant(of: self.viewTextfield) {
  4490. self.bottomAnchorPreviewReply = self.containerPreviewReply.bottomAnchor.constraint(equalTo: self.textFieldSend.topAnchor)
  4491. } else {
  4492. self.bottomAnchorPreviewReply = self.containerPreviewReply.bottomAnchor.constraint(equalTo: self.containerLink.topAnchor)
  4493. }
  4494. self.bottomAnchorPreviewReply.isActive = true
  4495. self.containerPreviewReply.trailingAnchor.constraint(equalTo: self.viewTextfield.trailingAnchor).isActive = true
  4496. self.containerPreviewReply.backgroundColor = .secondaryColor
  4497. let leftReply = UIView()
  4498. self.containerPreviewReply.addSubview(leftReply)
  4499. leftReply.translatesAutoresizingMaskIntoConstraints = false
  4500. leftReply.leadingAnchor.constraint(equalTo: self.viewTextfield.leadingAnchor).isActive = true
  4501. leftReply.topAnchor.constraint(equalTo: self.containerPreviewReply.topAnchor).isActive = true
  4502. leftReply.bottomAnchor.constraint(equalTo: self.containerPreviewReply.bottomAnchor).isActive = true
  4503. leftReply.widthAnchor.constraint(equalToConstant: 3).isActive = true
  4504. leftReply.backgroundColor = .orangeColor
  4505. let titleReply = UILabel()
  4506. self.containerPreviewReply.addSubview(titleReply)
  4507. titleReply.translatesAutoresizingMaskIntoConstraints = false
  4508. titleReply.leadingAnchor.constraint(equalTo: leftReply.leadingAnchor, constant: 10).isActive = true
  4509. titleReply.topAnchor.constraint(equalTo: self.containerPreviewReply.topAnchor, constant: 10).isActive = true
  4510. titleReply.font = UIFont.systemFont(ofSize: 12).bold
  4511. let idMe = UserDefaults.standard.string(forKey: "me") as String?
  4512. if (dataMessages[indexPath.row]["f_pin"] as? String == idMe) {
  4513. titleReply.text = "You".localized()
  4514. } else {
  4515. if dataMessages[indexPath.row]["f_pin"] as? String != "-999" {
  4516. let dataPerson = self.getDataProfile(f_pin: dataMessages[indexPath.row]["f_pin"] as! String, message_id: dataMessages[indexPath.row]["message_id"] as! String)
  4517. titleReply.text = dataPerson["name"]
  4518. } else {
  4519. titleReply.text = "Bot"
  4520. }
  4521. }
  4522. titleReply.textColor = .orangeColor
  4523. let contentReply = UILabel()
  4524. self.containerPreviewReply.addSubview(contentReply)
  4525. contentReply.translatesAutoresizingMaskIntoConstraints = false
  4526. contentReply.leadingAnchor.constraint(equalTo: leftReply.leadingAnchor, constant: 10).isActive = true
  4527. contentReply.topAnchor.constraint(equalTo: titleReply.bottomAnchor).isActive = true
  4528. contentReply.font = UIFont.systemFont(ofSize: 10)
  4529. let message_text = dataMessages[indexPath.row]["message_text"] as! String
  4530. let attachment_flag = dataMessages[indexPath.row]["attachment_flag"] as! String
  4531. let thumb_chat = dataMessages[indexPath.row]["thumb_id"] as! String
  4532. let image_chat = dataMessages[indexPath.row]["image_id"] as! String
  4533. let video_chat = dataMessages[indexPath.row]["video_id"] as! String
  4534. let file_chat = dataMessages[indexPath.row]["file_id"] as! String
  4535. if (attachment_flag == "0" && thumb_chat == "") {
  4536. contentReply.attributedText = message_text.richText(group_id: self.dataGroup["group_id"] as! String)
  4537. } else if (attachment_flag == "1" || image_chat != "") {
  4538. if (message_text == "") {
  4539. contentReply.text = "📷 Photo".localized()
  4540. } else {
  4541. contentReply.attributedText = message_text.richText(group_id: self.dataGroup["group_id"] as! String)
  4542. }
  4543. } else if (attachment_flag == "2" || video_chat != "") {
  4544. if (message_text == "") {
  4545. contentReply.text = "📹 Video".localized()
  4546. } else {
  4547. contentReply.attributedText = message_text.richText(group_id: self.dataGroup["group_id"] as! String)
  4548. }
  4549. } else if (attachment_flag == "6" || file_chat != ""){
  4550. contentReply.text = "📄 \(message_text.components(separatedBy: "|")[0])"
  4551. } else if (attachment_flag == "11") {
  4552. contentReply.text = "❤️ Sticker"
  4553. } else if attachment_flag == "27" {
  4554. contentReply.text = "📄 " + "Live Streaming".localized()
  4555. } else if attachment_flag == "26" {
  4556. contentReply.text = "📄 " + "Seminar".localized()
  4557. }
  4558. contentReply.textColor = .gray
  4559. let buttonCancelReply = UIButton(type: .custom)
  4560. self.containerPreviewReply.addSubview(buttonCancelReply)
  4561. buttonCancelReply.translatesAutoresizingMaskIntoConstraints = false
  4562. buttonCancelReply.trailingAnchor.constraint(equalTo: self.containerPreviewReply.trailingAnchor, constant: -10).isActive = true
  4563. buttonCancelReply.centerYAnchor.constraint(equalTo: self.containerPreviewReply.centerYAnchor).isActive = true
  4564. buttonCancelReply.setImage(UIImage(systemName: "xmark.circle" , withConfiguration: UIImage.SymbolConfiguration(pointSize: 20, weight: .regular, scale: .default)), for: .normal)
  4565. buttonCancelReply.addTarget(nil, action: #selector(self.deleteReplyView), for: .touchUpInside)
  4566. buttonCancelReply.backgroundColor = .clear
  4567. buttonCancelReply.tintColor = .mainColor
  4568. if (attachment_flag == "1" || attachment_flag == "2" || image_chat != "" || video_chat != "") {
  4569. let nsDocumentDirectory = FileManager.SearchPathDirectory.documentDirectory
  4570. let nsUserDomainMask = FileManager.SearchPathDomainMask.userDomainMask
  4571. let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true)
  4572. if let dirPath = paths.first {
  4573. let thumbURL = URL(fileURLWithPath: dirPath).appendingPathComponent(thumb_chat)
  4574. let image : UIImage? = {
  4575. if let img = DigiX.imageCache.object(forKey: thumb_chat as NSString) {
  4576. return img
  4577. }
  4578. else if let img = UIImage(contentsOfFile: thumbURL.path)?.resize(target: CGSize(width: 500, height: 500)) {
  4579. DigiX.imageCache.setObject(img, forKey: thumb_chat as NSString)
  4580. return img
  4581. }
  4582. return nil
  4583. }()
  4584. // let image = UIGraphicsRenderer.renderImageAt(url: thumbURL as NSURL, size: CGSize(width: 250, height: 250))
  4585. let imageThumb = UIImageView(image: image)
  4586. self.containerPreviewReply.addSubview(imageThumb)
  4587. imageThumb.layer.cornerRadius = 2.0
  4588. imageThumb.clipsToBounds = true
  4589. imageThumb.translatesAutoresizingMaskIntoConstraints = false
  4590. imageThumb.trailingAnchor.constraint(equalTo: buttonCancelReply.leadingAnchor, constant: -10).isActive = true
  4591. imageThumb.centerYAnchor.constraint(equalTo: self.containerPreviewReply.centerYAnchor).isActive = true
  4592. imageThumb.widthAnchor.constraint(equalToConstant: 30).isActive = true
  4593. imageThumb.heightAnchor.constraint(equalToConstant: 30).isActive = true
  4594. if (attachment_flag == "2") {
  4595. let imagePlay = UIImageView(image: UIImage(systemName: "play.circle.fill"))
  4596. imageThumb.addSubview(imagePlay)
  4597. imagePlay.clipsToBounds = true
  4598. imagePlay.translatesAutoresizingMaskIntoConstraints = false
  4599. imagePlay.centerYAnchor.constraint(equalTo: imageThumb.centerYAnchor).isActive = true
  4600. imagePlay.centerXAnchor.constraint(equalTo: imageThumb.centerXAnchor).isActive = true
  4601. imagePlay.widthAnchor.constraint(equalToConstant: 10).isActive = true
  4602. imagePlay.heightAnchor.constraint(equalToConstant: 10).isActive = true
  4603. imagePlay.tintColor = .white
  4604. }
  4605. }
  4606. }
  4607. if (attachment_flag == "11") {
  4608. let imageSticker = UIImageView(image: UIImage(named: (message_text.components(separatedBy: "/")[1]), in: Bundle.resourceBundle(for: DigiX.self), with: nil))
  4609. self.containerPreviewReply.addSubview(imageSticker)
  4610. imageSticker.layer.cornerRadius = 2.0
  4611. imageSticker.clipsToBounds = true
  4612. imageSticker.translatesAutoresizingMaskIntoConstraints = false
  4613. imageSticker.trailingAnchor.constraint(equalTo: buttonCancelReply.leadingAnchor, constant: -10).isActive = true
  4614. imageSticker.centerYAnchor.constraint(equalTo: self.containerPreviewReply.centerYAnchor).isActive = true
  4615. imageSticker.widthAnchor.constraint(equalToConstant: 30).isActive = true
  4616. imageSticker.heightAnchor.constraint(equalToConstant: 30).isActive = true
  4617. }
  4618. }
  4619. func scrollToFirstSearchMessage(indexScroll: Int = 1) {
  4620. if textSearch.count < 2 {
  4621. return
  4622. }
  4623. var lastIndex = 0
  4624. let messageTextForSearch: [[String: Any?]] = self.dataMessages.reversed()
  4625. for idx in 0..<messageTextForSearch.count {
  4626. if (messageTextForSearch[idx]["message_text"] as! String).lowercased().contains(textSearch) {
  4627. lastIndex += 1
  4628. if lastIndex < indexScroll {
  4629. continue
  4630. }
  4631. lastScrollIdxSearch = lastIndex
  4632. let section = self.dataDates.firstIndex(of: messageTextForSearch[idx]["chat_date"] as! String)
  4633. if section == nil {
  4634. return
  4635. }
  4636. 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})
  4637. if row == nil {
  4638. return
  4639. }
  4640. let indexPath = IndexPath(row: row!, section: section!)
  4641. self.tableChatView.scrollToRow(at: indexPath, at: .middle, animated: true)
  4642. DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
  4643. if let cell = self.tableChatView.cellForRow(at: indexPath) {
  4644. let containerMessage = cell.contentView.subviews[1]
  4645. let idMe = UserDefaults.standard.string(forKey: "me") as String?
  4646. if (messageTextForSearch[idx]["f_pin"] as? String == idMe) {
  4647. containerMessage.backgroundColor = .blueBubbleColor.withAlphaComponent(0.3)
  4648. DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
  4649. if (messageTextForSearch[idx]["attachment_flag"] as? String == "11") {
  4650. containerMessage.backgroundColor = .clear
  4651. } else {
  4652. containerMessage.backgroundColor = .blueBubbleColor
  4653. }
  4654. }
  4655. } else {
  4656. containerMessage.backgroundColor = .grayColor.withAlphaComponent(0.3)
  4657. DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
  4658. if (messageTextForSearch[idx]["attachment_flag"] as? String == "11") {
  4659. containerMessage.backgroundColor = .clear
  4660. } else {
  4661. containerMessage.backgroundColor = .grayColor
  4662. }
  4663. }
  4664. }
  4665. }
  4666. }
  4667. titleSearchMatches.isHidden = false
  4668. if countMatchesSearch != 0 {
  4669. if countMatchesSearch > 1 {
  4670. titleSearchMatches.text = "\(lastScrollIdxSearch) " + "of".localized() + " \(countMatchesSearch) " + "matches".localized()
  4671. } else {
  4672. titleSearchMatches.text = "\(countMatchesSearch) " + "matches".localized()
  4673. }
  4674. } else {
  4675. titleSearchMatches.text = "Not found".localized()
  4676. }
  4677. if lastScrollIdxSearch == countMatchesSearch || countMatchesSearch == 0 {
  4678. buttonUp.isEnabled = false
  4679. buttonUp.tintColor = .gray
  4680. } else {
  4681. buttonUp.isEnabled = true
  4682. buttonUp.tintColor = .mainColor
  4683. }
  4684. if countMatchesSearch == 0 || lastScrollIdxSearch == 1 || countMatchesSearch == 1 {
  4685. buttonDown.isEnabled = false
  4686. buttonDown.tintColor = .gray
  4687. } else {
  4688. buttonDown.isEnabled = true
  4689. buttonDown.tintColor = .mainColor
  4690. }
  4691. break
  4692. }
  4693. }
  4694. }
  4695. public func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
  4696. let indexPath = tableChatView.indexPathsForVisibleRows?.first
  4697. if indexPath != nil {
  4698. let headerRect = tableChatView.rectForHeader(inSection: indexPath!.section)
  4699. let isPinned = headerRect.origin.y <= scrollView.contentOffset.y
  4700. if listViewOnSection.count != 0 && listViewOnSection.count - 1 == indexPath!.section && indexPath!.row > 0 {
  4701. let sect = listViewOnSection.count - 1 < currentIndexpath!.section ? listViewOnSection.count - 1 : currentIndexpath!.section
  4702. let headerView = listViewOnSection[sect]
  4703. headerView.isHidden = true
  4704. }
  4705. }
  4706. }
  4707. public func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
  4708. if !decelerate {
  4709. let indexPath = tableChatView.indexPathsForVisibleRows?.first
  4710. if indexPath != nil {
  4711. let headerRect = tableChatView.rectForHeader(inSection: indexPath!.section)
  4712. let isPinned = headerRect.origin.y <= scrollView.contentOffset.y
  4713. if listViewOnSection.count != 0 && listViewOnSection.count - 1 == indexPath!.section && isPinned {
  4714. let sect = listViewOnSection.count - 1 < currentIndexpath!.section ? listViewOnSection.count - 1 : currentIndexpath!.section
  4715. let headerView = listViewOnSection[sect]
  4716. headerView.isHidden = true
  4717. }
  4718. }
  4719. }
  4720. }
  4721. }
  4722. extension EditorGroup: UISearchBarDelegate {
  4723. public func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
  4724. textSearch = searchText.trimmingCharacters(in: .whitespacesAndNewlines)
  4725. countMatchesSearch = 0
  4726. titleSearchMatches.isHidden = true
  4727. tableChatView.reloadData()
  4728. scrollToFirstSearchMessage()
  4729. }
  4730. }