EditorGroup.swift 332 KB

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