EditorPersonal.swift 399 KB

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