EditorPersonal.swift 384 KB

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