EditorPersonal.swift 319 KB

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