EditorPersonal.swift 284 KB

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