EditorPersonal.swift 397 KB

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