EditorPersonal.swift 392 KB

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