EditorPersonal.swift 397 KB

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