EditorGroup.swift 303 KB

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