EditorPersonal.swift 384 KB

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