EditorGroup.swift 301 KB

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