EditorPersonal.swift 412 KB

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