EditorGroup.swift 270 KB

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