EditorPersonal.swift 396 KB

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