EditorGroup.swift 271 KB

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