EditorPersonal.swift 362 KB

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