EditorGroup.swift 266 KB

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