EditorGroup.swift 205 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493
  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 ReadabilityKit
  12. import Photos
  13. public class EditorGroup: UIViewController {
  14. @IBOutlet var viewButton: UIView!
  15. @IBOutlet var constraintViewTextField: NSLayoutConstraint!
  16. @IBOutlet var buttonVoice: UIButton!
  17. @IBOutlet var buttonSendImage: UIButton!
  18. @IBOutlet var buttonSendPhoto: UIButton!
  19. @IBOutlet var buttonSendSticker: UIButton!
  20. @IBOutlet var buttonSendFile: UIButton!
  21. @IBOutlet var textFieldSend: UITextView!
  22. @IBOutlet var heightTextFieldSend: NSLayoutConstraint!
  23. @IBOutlet var buttonSendChat: UIButton!
  24. @IBOutlet var tableChatView: UITableView!
  25. @IBOutlet var constraintTopTextField: NSLayoutConstraint!
  26. @IBOutlet var constraintBottomAttachment: NSLayoutConstraint!
  27. @IBOutlet var viewTextfield: UIView!
  28. public var dataGroup: [String: Any?] = [:]
  29. public var dataTopic: [String: Any?] = [:]
  30. var dataMessages: [[String: Any?]] = []
  31. var dataDates: [String] = []
  32. public var dataMessageForward: [[String: Any?]]?
  33. var imageVideoPicker: ImageVideoPicker!
  34. var documentPicker: DocumentPicker!
  35. var currentIndexpath: IndexPath?
  36. var previewItem: NSURL?
  37. var reffId: String?
  38. var stickers = [String]()
  39. public var unique_l_pin = ""
  40. public var fromNotification = false
  41. var isHistoryCC = false
  42. var complaintId = ""
  43. var counter = 0
  44. var markerCounter: String?
  45. var buttonScrollToBottom = UIButton()
  46. let indicatorCounterBSTB = UIView()
  47. let labelCounter = UILabel()
  48. let containerActionGroup = UIView()
  49. var removed = false
  50. var copySession = false
  51. var forwardSession = false
  52. var deleteSession = false
  53. let containerMultpileSelectSession = UIView()
  54. let viewSticker = UIView()
  55. let containerLink = UIView()
  56. let containerPreviewReply = UIView()
  57. var bottomAnchorPreviewReply = NSLayoutConstraint()
  58. let containerAction = UIView()
  59. var allowTyping = true
  60. public override func viewDidDisappear(_ animated: Bool) {
  61. if self.isMovingFromParent {
  62. UserDefaults.standard.removeObject(forKey: "inEditorGroup")
  63. NotificationCenter.default.removeObserver(self)
  64. }
  65. }
  66. deinit {
  67. UserDefaults.standard.removeObject(forKey: "inEditorGroup")
  68. NotificationCenter.default.removeObserver(self)
  69. NotificationCenter.default.post(name: NSNotification.Name(rawValue: "refreshView"), object: nil, userInfo: nil)
  70. }
  71. public override func viewDidAppear(_ animated: Bool) {
  72. if self.navigationController?.isNavigationBarHidden ?? false {
  73. self.navigationController?.setNavigationBarHidden(false, animated: false)
  74. }
  75. }
  76. public override func viewDidLoad() {
  77. super.viewDidLoad()
  78. updateProfile()
  79. navigationController?.navigationBar.isTranslucent = false
  80. navigationController?.navigationBar.barTintColor = UIColor.mainColor
  81. navigationController?.navigationBar.tintColor = .white
  82. // navigationController?.navigationBar.topItem?.title = ""
  83. viewButton.layer.shadowColor = UIColor.gray.cgColor
  84. viewButton.layer.shadowOpacity = 1
  85. viewButton.layer.shadowOffset = .zero
  86. viewButton.layer.shadowRadius = 3
  87. buttonVoice.setImage(resizeImage(image: UIImage(named: "Voice-Record", in: Bundle.resourceBundle(for: Nexilis.self), with: nil)!, targetSize: CGSize(width: 30, height: 30)), for: .normal)
  88. buttonSendImage.setImage(resizeImage(image: UIImage(named: "Send-Image", in: Bundle.resourceBundle(for: Nexilis.self), with: nil)!, targetSize: CGSize(width: 30, height: 30)), for: .normal)
  89. buttonSendPhoto.setImage(resizeImage(image: UIImage(named: "Camera", in: Bundle.resourceBundle(for: Nexilis.self), with: nil)!, targetSize: CGSize(width: 30, height: 30)), for: .normal)
  90. buttonSendSticker.setImage(resizeImage(image: UIImage(named: "Sticker---Emoji", in: Bundle.resourceBundle(for: Nexilis.self), with: nil)!, targetSize: CGSize(width: 30, height: 30)), for: .normal)
  91. buttonSendFile.setImage(resizeImage(image: UIImage(named: "File---Documents", in: Bundle.resourceBundle(for: Nexilis.self), with: nil)!, targetSize: CGSize(width: 30, height: 30)), for: .normal)
  92. 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)
  93. buttonSendChat.circle()
  94. buttonSendChat.addTarget(self, action: #selector(sendTapped), for: .touchUpInside)
  95. textFieldSend.layer.cornerRadius = textFieldSend.maxCornerRadius()
  96. textFieldSend.layer.borderWidth = 1.0
  97. textFieldSend.text = "Send message".localized()
  98. textFieldSend.textColor = UIColor.lightGray
  99. textFieldSend.textContainerInset = UIEdgeInsets(top: 12, left: 20, bottom: 11, right: 40)
  100. textFieldSend.layer.borderColor = UIColor.lightGray.withAlphaComponent(0.5).cgColor
  101. textFieldSend.font = UIFont.systemFont(ofSize: 12)
  102. textFieldSend.delegate = self
  103. navigationItem.rightBarButtonItem?.tintColor = UIColor.secondaryColor
  104. imageVideoPicker = ImageVideoPicker(presentationController: self, delegate: self)
  105. documentPicker = DocumentPicker(presentationController: self, delegate: self)
  106. let fm = FileManager.default
  107. let path = Bundle.resourceBundle(for: Nexilis.self).resourcePath!
  108. let items = try! fm.contentsOfDirectory(atPath: path)
  109. for item in items {
  110. if item.hasPrefix("sticker") {
  111. stickers.append(item)
  112. }
  113. }
  114. loadData()
  115. setRightButtonItem()
  116. let center: NotificationCenter = NotificationCenter.default
  117. center.addObserver(self, selector: #selector(keyboardWillShow(notification:)), name: UIResponder.keyboardWillShowNotification, object: nil)
  118. center.addObserver(self, selector: #selector(keyboardWillHide(notification:)), name: UIResponder.keyboardWillHideNotification, object: nil)
  119. center.addObserver(self, selector: #selector(onReceiveMessage(notification:)), name: NSNotification.Name(rawValue: "onReceiveChat"), object: nil)
  120. center.addObserver(self, selector: #selector(onStatusChat(notification:)), name: NSNotification.Name(rawValue: "onMessageChat"), object: nil)
  121. center.addObserver(self, selector: #selector(onUploadChat(notification:)), name: NSNotification.Name(rawValue: "onUploadChat"), object: nil)
  122. center.addObserver(self, selector: #selector(onMemberTopic(notification:)), name: NSNotification.Name(rawValue: "onMember"), object: nil)
  123. center.addObserver(self, selector: #selector(onGroup(notification:)), name: NSNotification.Name(rawValue: "onGroup"), object: nil)
  124. center.addObserver(self, selector: #selector(onMemberTopic(notification:)), name: NSNotification.Name(rawValue: "onTopic"), object: nil)
  125. if dataMessageForward != nil {
  126. for i in 0..<dataMessageForward!.count {
  127. 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)
  128. }
  129. dataMessageForward = nil
  130. }
  131. }
  132. private func updateProfile() {
  133. let idMe = UserDefaults.standard.string(forKey: "me") as String?
  134. DispatchQueue.global().async {
  135. let message = CoreMessage_TMessageBank.getBatchBuddiesInfos(p_f_pin: idMe!, last_update: 0)
  136. let _ = Nexilis.write(message: message)
  137. }
  138. }
  139. private func setRightButtonItem() {
  140. let menu = UIMenu(title: "", children: [
  141. UIAction(title: "Delete Conversation".localized(), handler: {(_) in
  142. let alert = UIAlertController(title: "", message: "Are you sure to delete all message in this conversation?".localized(), preferredStyle: .alert)
  143. alert.addAction(UIAlertAction(title: "Cancel".localized(), style: UIAlertAction.Style.default, handler: nil))
  144. alert.addAction(UIAlertAction(title: "Delete".localized(), style: .destructive, handler: {(_) in
  145. var l_pin = self.dataGroup["group_id"] as! String
  146. DispatchQueue.global().async {
  147. Database.shared.database?.inTransaction({ (fmdb, rollback) in
  148. if (self.dataTopic["chat_id"] as! String != "") {
  149. l_pin = self.dataTopic["chat_id"] as! String
  150. }
  151. _ = Database.shared.deleteRecord(fmdb: fmdb, table: "MESSAGE_SUMMARY", _where: "l_pin='\(l_pin)'")
  152. _ = 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'")
  153. })
  154. NotificationCenter.default.post(name: NSNotification.Name(rawValue: "reloadTabChats"), object: nil, userInfo: nil)
  155. }
  156. if self.fromNotification {
  157. self.didTapExit()
  158. } else {
  159. self.navigationController?.popViewController(animated: true)
  160. }
  161. // self.dataMessages.removeAll()
  162. // self.dataDates.removeAll()
  163. // self.tableChatView.reloadData()
  164. }))
  165. self.present(alert, animated: true, completion: nil)
  166. }),
  167. ])
  168. if !isHistoryCC {
  169. let moreIcon = UIBarButtonItem(image: UIImage(systemName: "ellipsis"), menu: menu)
  170. navigationItem.rightBarButtonItem = moreIcon
  171. }
  172. }
  173. private func getOfficialGroup() {
  174. let query = "SELECT group_id, f_name, official, image_id FROM GROUPZ where group_type = 1 AND official = 1"
  175. Database.shared.database?.inTransaction({ (fmdb, rollback) in
  176. if let cursorData = Database.shared.getRecords(fmdb: fmdb, query: query) {
  177. if cursorData.next() {
  178. dataGroup["group_id"] = cursorData.string(forColumnIndex: 0)
  179. dataTopic["chat_id"] = ""
  180. dataGroup["f_name"] = cursorData.string(forColumnIndex: 1)
  181. dataGroup["image_id"] = cursorData.string(forColumnIndex: 3)
  182. dataGroup["official"] = cursorData.string(forColumnIndex: 2)
  183. }
  184. cursorData.close()
  185. }
  186. })
  187. }
  188. func loadData() {
  189. if (unique_l_pin != "") {
  190. dataDates.removeAll()
  191. dataGroup.removeAll()
  192. dataTopic.removeAll()
  193. dataMessages.removeAll()
  194. tableChatView.reloadData()
  195. currentIndexpath = nil
  196. reffId = nil
  197. getDataGroup(unique_l_pin: unique_l_pin)
  198. }
  199. if removed {
  200. removed = false
  201. containerActionGroup.removeConstraints(containerActionGroup.constraints)
  202. containerActionGroup.removeFromSuperview()
  203. setRightButtonItem()
  204. }
  205. if !isHistoryCC {
  206. UserDefaults.standard.set([dataGroup["group_id"], dataTopic["chat_id"]], forKey: "inEditorGroup")
  207. if dataTopic["chat_id"] as! String == "" {
  208. UNUserNotificationCenter.current().removeDeliveredNotifications(withIdentifiers: [dataGroup["group_id"] as! String])
  209. sendTyping(l_pin: dataGroup["group_id"] as! String)
  210. } else {
  211. UNUserNotificationCenter.current().removeDeliveredNotifications(withIdentifiers: [dataTopic["chat_id"] as! String])
  212. sendTyping(l_pin: dataTopic["chat_id"] as! String)
  213. }
  214. } else {
  215. getOfficialGroup()
  216. disableEditor()
  217. }
  218. if fromNotification {
  219. let imageButton = UIImageView(frame: CGRect(x: 0, y: 0, width: 20, height: 44))
  220. imageButton.image = UIImage(systemName: "chevron.backward")?.withTintColor(.white)
  221. imageButton.contentMode = .right
  222. let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(didTapExit))
  223. imageButton.isUserInteractionEnabled = true
  224. imageButton.addGestureRecognizer(tapGestureRecognizer)
  225. let leftItem = UIBarButtonItem(customView: imageButton)
  226. self.navigationItem.leftBarButtonItem = leftItem
  227. }
  228. changeAppBar()
  229. getData()
  230. getCounter()
  231. if counter > 0 {
  232. markerCounter = dataMessages[dataMessages.count - counter]["message_id"] as? String
  233. }
  234. tableChatView.alpha = 0
  235. tableChatView.delegate = self
  236. tableChatView.dataSource = self
  237. tableChatView.reloadData()
  238. if counter != 0 {
  239. if dataMessages.firstIndex(where: {$0["message_id"] as? String == markerCounter} ) != 0 {
  240. DispatchQueue.main.async {
  241. let data = self.dataMessages.filter({ $0["message_id"] as? String == self.markerCounter })
  242. let section = self.dataDates.firstIndex(of: data[0]["chat_date"] as! String)
  243. 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})
  244. self.tableChatView.scrollToRow(at: IndexPath(row: row!, section: section!), at: .bottom, animated: false)
  245. }
  246. } else {
  247. tableChatView.scrollToTop()
  248. }
  249. DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) { [self] in
  250. if currentIndexpath == nil && counter != 0 {
  251. let idMe = UserDefaults.standard.string(forKey: "me") as String?
  252. if let idx = dataMessages.firstIndex(where: { $0["message_id"] as? String == markerCounter}) {
  253. for i in idx..<dataMessages.count {
  254. if dataMessages[i]["f_pin"] as? String != idMe {
  255. 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)
  256. }
  257. }
  258. counter = 0
  259. updateCounter(counter: counter)
  260. }
  261. }
  262. }
  263. } else {
  264. tableChatView.scrollToBottom(isAnimated: false)
  265. }
  266. tableChatView.keyboardDismissMode = .interactive
  267. let tapGesture = UITapGestureRecognizer(target: self, action: #selector(dismissKeyboard))
  268. tapGesture.cancelsTouchesInView = false
  269. tableChatView.addGestureRecognizer(tapGesture)
  270. UIView.animate(withDuration: 0.5, animations: {
  271. self.tableChatView.alpha = 1.0
  272. })
  273. }
  274. func getDataProfile(f_pin: String, message_id: String) -> [String: String]{
  275. var data: [String: String] = [:]
  276. Database().database?.inTransaction({ fmdb, rollback in
  277. if let c = Database().getRecords(fmdb: fmdb, query: "select first_name || ' ' || last_name, image_id from BUDDY where f_pin = '\(f_pin)'"), c.next() {
  278. data["name"] = c.string(forColumnIndex: 0)!.trimmingCharacters(in: .whitespacesAndNewlines)
  279. data["image_id"] = c.string(forColumnIndex: 1)!
  280. c.close()
  281. }
  282. 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() {
  283. data["name"] = c.string(forColumnIndex: 0)!.trimmingCharacters(in: .whitespacesAndNewlines)
  284. data["image_id"] = c.string(forColumnIndex: 1)!
  285. c.close()
  286. } else if let c = Database().getRecords(fmdb: fmdb, query: "select f_display_name from MESSAGE where message_id = '\(message_id)'"), c.next() {
  287. data["name"] = c.string(forColumnIndex: 0)!
  288. data["image_id"] = ""
  289. c.close()
  290. } else {
  291. data["name"] = "Unknown".localized()
  292. }
  293. })
  294. return data
  295. }
  296. private func getDataGroup(unique_l_pin: String) {
  297. Database.shared.database?.inTransaction({ (fmdb, rollback) in
  298. 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() {
  299. dataGroup["group_id"] = cursorGroup.string(forColumnIndex: 0)
  300. dataGroup["f_name"] = cursorGroup.string(forColumnIndex: 1)
  301. dataGroup["image_id"] = cursorGroup.string(forColumnIndex: 2)
  302. dataGroup["official"] = cursorGroup.string(forColumnIndex: 3)
  303. dataGroup["parent"] = cursorGroup.string(forColumnIndex: 4)
  304. dataTopic["title"] = "Lounge".localized()
  305. dataTopic["chat_id"] = ""
  306. cursorGroup.close()
  307. } 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() {
  308. dataGroup["group_id"] = cursorTopic.string(forColumnIndex: 0)
  309. dataTopic["title"] = cursorTopic.string(forColumnIndex: 1)
  310. dataTopic["chat_id"] = unique_l_pin
  311. cursorTopic.close()
  312. 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() {
  313. dataGroup["f_name"] = cursorGroup.string(forColumnIndex: 0)
  314. dataGroup["image_id"] = cursorGroup.string(forColumnIndex: 1)
  315. dataGroup["official"] = cursorGroup.string(forColumnIndex: 2)
  316. dataGroup["parent"] = cursorGroup.string(forColumnIndex: 3)
  317. cursorGroup.close()
  318. }
  319. }
  320. })
  321. }
  322. private func getData() {
  323. Database.shared.database?.inTransaction({ (fmdb, rollback) in
  324. 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"
  325. if isHistoryCC {
  326. 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"
  327. } else if (dataTopic["chat_id"] as! String != "") {
  328. 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"
  329. }
  330. if let cursorData = Database.shared.getRecords(fmdb: fmdb, query: query) {
  331. while cursorData.next() {
  332. var row: [String: Any?] = [:]
  333. row["message_id"] = cursorData.string(forColumnIndex: 0)
  334. row["f_pin"] = cursorData.string(forColumnIndex: 1)
  335. row["l_pin"] = cursorData.string(forColumnIndex: 2)
  336. row["message_scope_id"] = cursorData.string(forColumnIndex: 3)
  337. row["server_date"] = cursorData.string(forColumnIndex: 4)
  338. row["status"] = cursorData.string(forColumnIndex: 5)
  339. row["message_text"] = cursorData.string(forColumnIndex: 6)
  340. row["audio_id"] = cursorData.string(forColumnIndex: 7)
  341. row["video_id"] = cursorData.string(forColumnIndex: 8)
  342. row["image_id"] = cursorData.string(forColumnIndex: 9)
  343. row["thumb_id"] = cursorData.string(forColumnIndex: 10)
  344. row["read_receipts"] = cursorData.int(forColumnIndex: 11)
  345. row["chat_id"] = cursorData.string(forColumnIndex: 12)
  346. row["file_id"] = cursorData.string(forColumnIndex: 13)
  347. row["attachment_flag"] = cursorData.string(forColumnIndex: 14)
  348. row["reff_id"] = cursorData.string(forColumnIndex: 15)
  349. row["lock"] = cursorData.string(forColumnIndex: 16)
  350. row["is_stared"] = cursorData.string(forColumnIndex: 17)
  351. row["blog_id"] = cursorData.string(forColumnIndex: 18)
  352. row["isSelected"] = false
  353. if let cursorStatus = Database.shared.getRecords(fmdb: fmdb, query: "SELECT status FROM MESSAGE_STATUS WHERE message_id='\(row["message_id"] as! String)'") {
  354. while cursorStatus.next() {
  355. row["status"] = cursorStatus.string(forColumnIndex: 0)
  356. }
  357. cursorStatus.close()
  358. }
  359. let nsDocumentDirectory = FileManager.SearchPathDirectory.documentDirectory
  360. let nsUserDomainMask = FileManager.SearchPathDomainMask.userDomainMask
  361. let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true)
  362. if let dirPath = paths.first {
  363. let videoURL = URL(fileURLWithPath: dirPath).appendingPathComponent(row["video_id"] as! String)
  364. let fileURL = URL(fileURLWithPath: dirPath).appendingPathComponent(row["file_id"] as! String)
  365. if ((row["video_id"] as! String) != "") {
  366. if FileManager.default.fileExists(atPath: videoURL.path){
  367. row["progress"] = 100.0
  368. } else {
  369. row["progress"] = 0.0
  370. }
  371. } else {
  372. if FileManager.default.fileExists(atPath: fileURL.path){
  373. row["progress"] = 100.0
  374. } else {
  375. row["progress"] = 0.0
  376. }
  377. }
  378. }
  379. row["chat_date"] = chatDate(stringDate: row["server_date"] as! String, messageId: row["message_id"] as! String)
  380. dataMessages.append(row)
  381. }
  382. // if isHistoryCC {
  383. // dataMessages.remove(at: 0)
  384. // }
  385. cursorData.close()
  386. }
  387. })
  388. }
  389. private func chatDate(stringDate: String, messageId: String) -> String {
  390. let date = Date(milliseconds: Int64(stringDate)!)
  391. let calendar = Calendar.current
  392. if (calendar.isDateInToday(date)) {
  393. if !dataDates.contains("Today".localized()){
  394. dataDates.append("Today".localized())
  395. }
  396. return "Today".localized()
  397. } else {
  398. let startOfNow = calendar.startOfDay(for: Date())
  399. let startOfTimeStamp = calendar.startOfDay(for: date)
  400. let components = calendar.dateComponents([.day], from: startOfNow, to: startOfTimeStamp)
  401. let day = -(components.day!)
  402. if day == 1{
  403. if !dataDates.contains("Yesterday".localized()){
  404. dataDates.append("Yesterday".localized())
  405. }
  406. return "Yesterday".localized()
  407. } else if day < 7 {
  408. if !dataDates.contains("\(day) " + "days".localized() + " " + "ago".localized()){
  409. dataDates.append("\(day) " + "days".localized() + " " + "ago".localized())
  410. }
  411. return "\(day) " + "days".localized() + " " + "ago".localized()
  412. } else {
  413. let formatter = DateFormatter()
  414. formatter.dateFormat = "dd MMMM yyyy"
  415. formatter.locale = NSLocale(localeIdentifier: "id") as Locale?
  416. let stringFormat = formatter.string(from: date as Date)
  417. if !dataDates.contains(stringFormat){
  418. dataDates.append(stringFormat)
  419. }
  420. return stringFormat
  421. }
  422. }
  423. }
  424. private func changeAppBar() {
  425. let viewAppBar = UIView()
  426. viewAppBar.frame.size = CGSize(width: self.view.frame.size.width, height: 44)
  427. let imageProfile = UIImageView(frame: CGRect(x: 0, y: 7, width: 30, height: 30))
  428. imageProfile.circle()
  429. imageProfile.clipsToBounds = true
  430. viewAppBar.addSubview(imageProfile)
  431. let pictureImage = dataGroup["image_id"]!
  432. if (pictureImage as! String != "" && pictureImage != nil) {
  433. imageProfile.setImage(name: pictureImage! as! String)
  434. imageProfile.contentMode = .scaleAspectFill
  435. } else {
  436. imageProfile.image = UIImage(systemName: "person.3")
  437. imageProfile.contentMode = .scaleAspectFit
  438. imageProfile.backgroundColor = .lightGray
  439. }
  440. let titleNavigation = UILabel(frame: CGRect(x: 35, y: 0, width: viewAppBar.frame.size.width - 150, height: 44))
  441. viewAppBar.addSubview(titleNavigation)
  442. if (dataGroup["official"] as! String == "1") {
  443. if !isHistoryCC {
  444. titleNavigation.set(image: UIImage(named: "ic_official_flag", in: Bundle.resourceBundle(for: Nexilis.self), with: nil)!.withTintColor(.white), with: " \(dataGroup["f_name"]!!) (\(dataTopic["title"]!!))", size: 15, y: -4)
  445. } else {
  446. titleNavigation.text = (dataGroup["f_name"] as? String)! + " " + "Contact Center".localized()
  447. }
  448. } else {
  449. titleNavigation.text = (dataGroup["f_name"] as? String)! + " (\(dataTopic["title"]!!))"
  450. }
  451. titleNavigation.textColor = .white
  452. titleNavigation.font = UIFont.systemFont(ofSize: 12).bold
  453. navigationItem.titleView = viewAppBar
  454. if copySession || forwardSession || deleteSession {
  455. navigationItem.hidesBackButton = true
  456. navigationController?.interactivePopGestureRecognizer?.isEnabled = false
  457. } else {
  458. navigationItem.hidesBackButton = false
  459. navigationController?.interactivePopGestureRecognizer?.isEnabled = true
  460. }
  461. viewAppBar.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(seeProfileTapped)))
  462. }
  463. @objc func onUploadChat(notification: NSNotification) {
  464. let data:[AnyHashable : Any] = notification.userInfo!
  465. var isImage = false
  466. var idx = dataMessages.lastIndex(where: { $0["video_id"] as! String == data["name"] as! String })
  467. if (idx == nil) {
  468. idx = dataMessages.lastIndex(where: { $0["image_id"] as! String == data["name"] as! String })
  469. isImage = true
  470. }
  471. if (idx != nil) {
  472. let section = dataDates.firstIndex(of: dataMessages[idx!]["chat_date"] as! String)
  473. if section == nil {
  474. return
  475. }
  476. let row = dataMessages.filter({ $0["chat_date"] as! String == dataDates[section!]}).firstIndex(where: { $0["message_id"] as! String == dataMessages[idx!]["message_id"] as! String})
  477. if row == nil {
  478. return
  479. }
  480. DispatchQueue.main.async {
  481. let indexPath = IndexPath(row: row!, section: section!)
  482. if let cell = self.tableChatView.cellForRow(at: indexPath) {
  483. for view in cell.contentView.subviews {
  484. if !(view is UILabel) && !(view is UIImageView) {
  485. for viewInContainer in view.subviews {
  486. if viewInContainer is UIImageView {
  487. if viewInContainer.subviews.count == 0 {
  488. return
  489. }
  490. var containerView = UIView()
  491. if (isImage) {
  492. containerView = viewInContainer.subviews[0]
  493. } else {
  494. containerView = viewInContainer.subviews[1]
  495. }
  496. let loading = containerView.layer.sublayers![1] as! CAShapeLayer
  497. loading.strokeEnd = CGFloat(data["progress"] as! Double / 100)
  498. if (data["progress"] as! Double == 100.0) {
  499. self.dataMessages[idx!]["progress"] = data["progress"]
  500. self.tableChatView.reloadRows(at: [indexPath], with: .none)
  501. }
  502. }
  503. }
  504. }
  505. }
  506. }
  507. }
  508. } else {
  509. idx = dataMessages.lastIndex(where: { $0["file_id"] as! String == data["name"] as! String })
  510. if (idx != nil) {
  511. DispatchQueue.main.async {
  512. let section = 0
  513. let indexPath = IndexPath(row: idx!, section: section)
  514. if let cell = self.tableChatView.cellForRow(at: indexPath) {
  515. for view in cell.contentView.subviews {
  516. if !(view is UILabel) && !(view is UIImageView) {
  517. for viewSubviews in view.subviews {
  518. if !(viewSubviews is UILabel) {
  519. for viewInContainer in viewSubviews.subviews {
  520. if !(viewInContainer is UILabel) && !(viewInContainer is UIImageView) {
  521. if viewInContainer.layer.sublayers!.count < 2 {
  522. return
  523. }
  524. let loading = viewInContainer.layer.sublayers![1] as! CAShapeLayer
  525. loading.strokeEnd = CGFloat(data["progress"] as! Double / 100)
  526. if (data["progress"] as! Double == 100.0) {
  527. self.dataMessages[idx!]["progress"] = data["progress"]
  528. self.tableChatView.reloadRows(at: [indexPath], with: .none)
  529. }
  530. }
  531. }
  532. }
  533. }
  534. }
  535. }
  536. }
  537. }
  538. }
  539. }
  540. }
  541. @objc func onReceiveMessage(notification: NSNotification) {
  542. DispatchQueue.main.async {
  543. let data:[AnyHashable : Any] = notification.userInfo!
  544. if let dataMessage = data["message"] as? TMessage {
  545. let chatData = dataMessage.mBodies
  546. let group_id = self.dataGroup["group_id"] as! String
  547. let chat_id = self.dataTopic["chat_id"] as! String
  548. if chatData[CoreMessage_TMessageKey.L_PIN] == group_id && (chatData[CoreMessage_TMessageKey.CHAT_ID] ?? "") == chat_id {
  549. var row: [String: Any?] = [:]
  550. row["message_id"] = chatData[CoreMessage_TMessageKey.MESSAGE_ID]
  551. row["f_pin"] = chatData[CoreMessage_TMessageKey.F_PIN]
  552. row["l_pin"] = chatData[CoreMessage_TMessageKey.L_PIN]
  553. row["message_scope_id"] = chatData[CoreMessage_TMessageKey.MESSAGE_SCOPE_ID]
  554. row["server_date"] = chatData[CoreMessage_TMessageKey.SERVER_DATE]
  555. row["status"] = chatData[CoreMessage_TMessageKey.STATUS]
  556. row["message_text"] = chatData[CoreMessage_TMessageKey.MESSAGE_TEXT]
  557. if (chatData.keys.contains(CoreMessage_TMessageKey.AUDIO_ID)) {
  558. row["audio_id"] = chatData[CoreMessage_TMessageKey.AUDIO_ID]
  559. } else {
  560. row["audio_id"] = ""
  561. }
  562. if (chatData.keys.contains(CoreMessage_TMessageKey.VIDEO_ID)) {
  563. row["video_id"] = chatData[CoreMessage_TMessageKey.VIDEO_ID]
  564. } else {
  565. row["video_id"] = ""
  566. }
  567. if (chatData.keys.contains(CoreMessage_TMessageKey.IMAGE_ID)) {
  568. row["image_id"] = chatData[CoreMessage_TMessageKey.IMAGE_ID]
  569. } else {
  570. row["image_id"] = ""
  571. }
  572. if (chatData.keys.contains(CoreMessage_TMessageKey.THUMB_ID)) {
  573. row["thumb_id"] = chatData[CoreMessage_TMessageKey.THUMB_ID]
  574. } else {
  575. row["thumb_id"] = ""
  576. }
  577. row["read_receipts"] = 0
  578. row["chat_id"] = ""
  579. if (chatData.keys.contains(CoreMessage_TMessageKey.FILE_ID)) {
  580. row["file_id"] = chatData[CoreMessage_TMessageKey.FILE_ID]
  581. } else {
  582. row["file_id"] = ""
  583. }
  584. row["progress"] = 0.0
  585. row["attachment_flag"] = chatData[CoreMessage_TMessageKey.ATTACHMENT_FLAG]
  586. row["reff_id"] = chatData[CoreMessage_TMessageKey.REF_ID] ?? ""
  587. row["lock"] = ""
  588. row["is_stared"] = "0"
  589. row["isSelected"] = false
  590. if !self.dataDates.contains("Today".localized()){
  591. self.dataDates.append("Today".localized())
  592. self.tableChatView.insertSections(IndexSet(integer: self.dataDates.count - 1), with: .fade)
  593. }
  594. row["chat_date"] = "Today".localized()
  595. row["blog_id"] = chatData[CoreMessage_TMessageKey.BLOG_ID]
  596. self.counter += 1
  597. self.dataMessages.append(row)
  598. 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)
  599. if self.currentIndexpath?.row == (self.dataMessages.count - 2) {
  600. if (self.viewIfLoaded?.window != nil) {
  601. 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]!)
  602. }
  603. self.tableChatView.scrollToBottom()
  604. 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) {
  605. self.counter = 0
  606. self.updateCounter(counter: self.counter)
  607. }
  608. if self.markerCounter != nil {
  609. self.markerCounter = nil
  610. }
  611. self.tableChatView.reloadData()
  612. }
  613. else if self.currentIndexpath == nil {
  614. self.counter = 0
  615. self.updateCounter(counter: self.counter)
  616. if (self.viewIfLoaded?.window != nil) {
  617. 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]!)
  618. }
  619. }
  620. else if self.counter != 0 {
  621. if !self.indicatorCounterBSTB.isDescendant(of: self.view) && self.buttonScrollToBottom.isDescendant(of: self.view) {
  622. self.markerCounter = row["message_id"] as? String
  623. self.addCounterAtButttonScrollToBottom()
  624. self.tableChatView.reloadData()
  625. } else if self.indicatorCounterBSTB.isDescendant(of: self.view) {
  626. self.labelCounter.text = "\(self.counter)"
  627. }
  628. }
  629. }
  630. } else {
  631. NotificationCenter.default.post(name: NSNotification.Name(rawValue: "reloadTabChats"), object: nil, userInfo: nil)
  632. }
  633. }
  634. }
  635. @objc func onStatusChat(notification: NSNotification) {
  636. DispatchQueue.main.async {
  637. if (self.viewIfLoaded?.window != nil) {
  638. let data:[AnyHashable : Any] = notification.userInfo!
  639. if let dataMessage = data["message"] as? TMessage {
  640. let idMe = UserDefaults.standard.string(forKey: "me") as String?
  641. let chatData = dataMessage.mBodies
  642. 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" {
  643. if (chatData.keys.contains(CoreMessage_TMessageKey.MESSAGE_ID) && !(chatData[CoreMessage_TMessageKey.MESSAGE_ID]!).contains("-2,")) {
  644. let idx = self.dataMessages.firstIndex(where: { $0["message_id"] as! String == chatData[CoreMessage_TMessageKey.MESSAGE_ID]! })
  645. if (idx != nil) {
  646. if (chatData[CoreMessage_TMessageKey.DELETE_MESSAGE_FLAG] == "1") {
  647. self.dataMessages[idx!]["lock"] = "1"
  648. self.dataMessages[idx!]["reff_id"] = ""
  649. let section = self.dataDates.firstIndex(of: self.dataMessages[idx!]["chat_date"] as! String)
  650. 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 })
  651. if row != nil && section != nil {
  652. self.tableChatView.reloadRows(at: [IndexPath(row: row!, section: section!)], with: .none)
  653. }
  654. } else {
  655. self.dataMessages[idx!]["status"] = chatData[CoreMessage_TMessageKey.STATUS]!
  656. let section = self.dataDates.firstIndex(of: self.dataMessages[idx!]["chat_date"] as! String)
  657. 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 })
  658. if row != nil && section != nil {
  659. self.tableChatView.reloadRows(at: [IndexPath(row: row!, section: section!)], with: .none)
  660. }
  661. }
  662. if self.reffId != nil && self.reffId == chatData[CoreMessage_TMessageKey.MESSAGE_ID]! {
  663. self.deleteReplyView()
  664. }
  665. }
  666. }
  667. else if (chatData.keys.contains("message_id")) {
  668. let idx = self.dataMessages.firstIndex(where: { "'\($0["message_id"] as! String)'" == chatData["message_id"]! })
  669. if (idx != nil) {
  670. if (chatData[CoreMessage_TMessageKey.DELETE_MESSAGE_FLAG] == "1") {
  671. self.dataMessages[idx!]["lock"] = "1"
  672. self.dataMessages[idx!]["reff_id"] = ""
  673. let section = self.dataDates.firstIndex(of: self.dataMessages[idx!]["chat_date"] as! String)
  674. 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 })
  675. if row != nil && section != nil {
  676. self.tableChatView.reloadRows(at: [IndexPath(row: row!, section: section!)], with: .none)
  677. }
  678. } else {
  679. self.dataMessages[idx!]["status"] = chatData[CoreMessage_TMessageKey.STATUS]!
  680. let section = self.dataDates.firstIndex(of: self.dataMessages[idx!]["chat_date"] as! String)
  681. 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 })
  682. if row != nil && section != nil {
  683. self.tableChatView.reloadRows(at: [IndexPath(row: row!, section: section!)], with: .none)
  684. }
  685. }
  686. if self.reffId != nil && self.reffId == chatData["message_id"]! {
  687. self.deleteReplyView()
  688. }
  689. }
  690. }
  691. else {
  692. let messageId = chatData[CoreMessage_TMessageKey.MESSAGE_ID]!.split(separator: ",")[1]
  693. let idx = self.dataMessages.firstIndex(where: { $0["message_id"] as! String == messageId })
  694. if (idx != nil) {
  695. self.dataMessages[idx!]["status"] = chatData[CoreMessage_TMessageKey.STATUS]!
  696. let section = self.dataDates.firstIndex(of: self.dataMessages[idx!]["chat_date"] as! String)
  697. 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 })
  698. if row != nil && section != nil {
  699. self.tableChatView.reloadRows(at: [IndexPath(row: row!, section: section!)], with: .none)
  700. }
  701. if self.reffId != nil && self.reffId! == messageId {
  702. self.deleteReplyView()
  703. }
  704. }
  705. }
  706. }
  707. }
  708. }
  709. }
  710. }
  711. @objc func onMemberTopic(notification: NSNotification) {
  712. let data:[AnyHashable : Any] = notification.userInfo!
  713. DispatchQueue.main.async { [self] in
  714. 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) {
  715. dismissKeyboard()
  716. let labelKicked = UILabel()
  717. if data["member"] == nil && data["code"] as! String == CoreMessage_TMessageCode.DELETE_CHAT && data["topicId"] as! String == dataTopic["chat_id"] as! String {
  718. labelKicked.text = "This topic has been deleted".localized()
  719. } else if data["member"] != nil && data["member"] as! String == data["f_pin"] as! String {
  720. labelKicked.text = "You have left this group".localized()
  721. } else if data["member"] != nil {
  722. labelKicked.text = "You have been removed from this group".localized()
  723. } else if data["code"] as! String == CoreMessage_TMessageCode.UPDATE_CHAT {
  724. dataGroup.removeAll()
  725. dataTopic.removeAll()
  726. getDataGroup(unique_l_pin: unique_l_pin)
  727. changeAppBar()
  728. return
  729. } else {
  730. return
  731. }
  732. removed = true
  733. navigationItem.rightBarButtonItem = nil
  734. view.addSubview(containerActionGroup)
  735. containerActionGroup.translatesAutoresizingMaskIntoConstraints = false
  736. NSLayoutConstraint.activate([
  737. containerActionGroup.leadingAnchor.constraint(equalTo: self.view.leadingAnchor),
  738. containerActionGroup.trailingAnchor.constraint(equalTo: self.view.trailingAnchor),
  739. containerActionGroup.bottomAnchor.constraint(equalTo: self.view.bottomAnchor),
  740. containerActionGroup.heightAnchor.constraint(equalToConstant: 120)
  741. ])
  742. containerActionGroup.backgroundColor = .secondaryColor.withAlphaComponent(0.8)
  743. containerActionGroup.addSubview(labelKicked)
  744. labelKicked.translatesAutoresizingMaskIntoConstraints = false
  745. NSLayoutConstraint.activate([
  746. labelKicked.centerYAnchor.constraint(equalTo: containerActionGroup.centerYAnchor),
  747. labelKicked.centerXAnchor.constraint(equalTo: containerActionGroup.centerXAnchor),
  748. ])
  749. labelKicked.textColor = .black
  750. labelKicked.font = UIFont.systemFont(ofSize: 12).bold
  751. }
  752. }
  753. }
  754. @objc func onGroup(notification: NSNotification) {
  755. let data:[AnyHashable : Any] = notification.userInfo!
  756. if data["code"] as! String == "A010" && data["groupId"] as! String == self.dataGroup["group_id"] as! String {
  757. DispatchQueue.main.async {
  758. Database().database?.inTransaction({ fmdb, rollback in
  759. if let c = Database().getRecords(fmdb: fmdb, query: "select f_name, image_id from GROUPZ where group_id = '\(self.dataGroup["group_id"]!!)'"), c.next() {
  760. self.dataGroup["f_name"] = c.string(forColumnIndex: 0)!.trimmingCharacters(in: .whitespacesAndNewlines)
  761. self.dataGroup["image_id"] = c.string(forColumnIndex: 1)!
  762. c.close()
  763. }
  764. })
  765. self.changeAppBar()
  766. }
  767. }
  768. }
  769. @IBAction func voiceTapped(_ sender: UIButton) {
  770. if (self.constraintBottomAttachment.constant != 0.0) {
  771. constraintBottomAttachment.constant = 0.0
  772. self.viewSticker.removeConstraints(self.viewSticker.constraints)
  773. self.viewSticker.removeFromSuperview()
  774. }
  775. }
  776. @IBAction func imageTapped(_ sender: UIButton) {
  777. if (self.constraintBottomAttachment.constant != 0.0) {
  778. constraintBottomAttachment.constant = 0.0
  779. self.viewSticker.removeConstraints(self.viewSticker.constraints)
  780. self.viewSticker.removeFromSuperview()
  781. }
  782. let alertController = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
  783. if let action = self.actionImageVideo(for: "image", title: "Choose Photo".localized()) {
  784. alertController.addAction(action)
  785. }
  786. if let action = self.actionImageVideo(for: "video", title: "Choose Video".localized()) {
  787. alertController.addAction(action)
  788. }
  789. alertController.addAction(UIAlertAction(title: "Cancel".localized(), style: .cancel, handler: nil))
  790. self.present(alertController, animated: true)
  791. }
  792. private func actionImageVideo(for type: String, title: String) -> UIAlertAction? {
  793. return UIAlertAction(title: title, style: .default) { [unowned self] _ in
  794. switch type {
  795. case "image":
  796. imageVideoPicker.present(source: .imageAlbum)
  797. case "video":
  798. imageVideoPicker.present(source: .videoAlbum)
  799. case "imageCamera":
  800. imageVideoPicker.present(source: .imageCamera)
  801. case "videoCamera":
  802. imageVideoPicker.present(source: .videoCamera)
  803. default:
  804. imageVideoPicker.present(source: .imageAlbum)
  805. }
  806. }
  807. }
  808. @IBAction func photoTapped(_ sender: UIButton) {
  809. if (self.constraintBottomAttachment.constant != 0.0) {
  810. constraintBottomAttachment.constant = 0.0
  811. self.viewSticker.removeConstraints(self.viewSticker.constraints)
  812. self.viewSticker.removeFromSuperview()
  813. }
  814. let alertController = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
  815. if let action = self.actionImageVideo(for: "imageCamera", title: "Take Photo".localized()) {
  816. alertController.addAction(action)
  817. }
  818. if let action = self.actionImageVideo(for: "videoCamera", title: "Take Video".localized()) {
  819. alertController.addAction(action)
  820. }
  821. alertController.addAction(UIAlertAction(title: "Cancel".localized(), style: .cancel, handler: nil))
  822. self.present(alertController, animated: true)
  823. }
  824. @IBAction func stickerTapped(_ sender: UIButton) {
  825. DispatchQueue.main.async {
  826. if (self.constraintBottomAttachment.constant == 0.0) {
  827. self.constraintBottomAttachment.constant = 200.0
  828. self.view.addSubview(self.viewSticker)
  829. self.viewSticker.translatesAutoresizingMaskIntoConstraints = false
  830. NSLayoutConstraint.activate([
  831. self.viewSticker.bottomAnchor.constraint(equalTo: self.view.bottomAnchor),
  832. self.viewSticker.leadingAnchor.constraint(equalTo: self.view.leadingAnchor),
  833. self.viewSticker.trailingAnchor.constraint(equalTo: self.view.trailingAnchor),
  834. self.viewSticker.heightAnchor.constraint(equalToConstant: 200)
  835. ])
  836. let layout = UICollectionViewFlowLayout()
  837. layout.scrollDirection = .vertical
  838. let collectionSticker = UICollectionView(frame: .zero, collectionViewLayout: layout)
  839. collectionSticker.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "cellSticker")
  840. collectionSticker.delegate = self
  841. collectionSticker.dataSource = self
  842. collectionSticker.backgroundColor = .clear
  843. self.viewSticker.addSubview(collectionSticker)
  844. collectionSticker.translatesAutoresizingMaskIntoConstraints = false
  845. NSLayoutConstraint.activate([
  846. collectionSticker.topAnchor.constraint(equalTo: self.viewSticker.topAnchor, constant: 20),
  847. collectionSticker.bottomAnchor.constraint(equalTo: self.viewSticker.bottomAnchor, constant: -20),
  848. collectionSticker.leadingAnchor.constraint(equalTo: self.viewSticker.leadingAnchor, constant: 20),
  849. collectionSticker.trailingAnchor.constraint(equalTo: self.viewSticker.trailingAnchor, constant: -20)
  850. ])
  851. if (self.currentIndexpath != nil) {
  852. DispatchQueue.main.async {
  853. self.tableChatView.scrollToRow(at: IndexPath(row: self.currentIndexpath!.row, section: self.currentIndexpath!.section), at: .none, animated: false)
  854. }
  855. } else {
  856. self.tableChatView.scrollToBottom()
  857. }
  858. } else {
  859. self.constraintBottomAttachment.constant = 0.0
  860. self.viewSticker.removeConstraints(self.viewSticker.constraints)
  861. self.viewSticker.removeFromSuperview()
  862. }
  863. }
  864. }
  865. @IBAction func fileTapped(_ sender: UIButton) {
  866. if (self.constraintBottomAttachment.constant != 0.0) {
  867. constraintBottomAttachment.constant = 0.0
  868. self.viewSticker.removeConstraints(self.viewSticker.constraints)
  869. self.viewSticker.removeFromSuperview()
  870. }
  871. documentPicker.present()
  872. }
  873. @objc func didTapExit() {
  874. UserDefaults.standard.removeObject(forKey: "inEditorGroup")
  875. NotificationCenter.default.removeObserver(self)
  876. self.dismiss(animated: true, completion: nil)
  877. }
  878. @objc func profilePersonTapped(_ sender: ObjectGesture) {
  879. if isHistoryCC {
  880. return
  881. }
  882. let idMe = UserDefaults.standard.string(forKey: "me") as String?
  883. if sender.message_id == idMe {
  884. let controller = AppStoryBoard.Palio.instance.instantiateViewController(withIdentifier: "profileView") as! ProfileViewController
  885. controller.data = sender.message_id
  886. controller.flag = .me
  887. navigationController?.show(controller, sender: nil)
  888. } else {
  889. let data = User.getData(pin: sender.message_id)
  890. if data != nil {
  891. let controller = AppStoryBoard.Palio.instance.instantiateViewController(withIdentifier: "profileView") as! ProfileViewController
  892. controller.flag = .friend
  893. controller.user = data
  894. controller.name = data!.fullName
  895. controller.data = sender.message_id
  896. controller.picture = data!.thumb
  897. self.navigationController?.show(controller, sender: nil)
  898. } else {
  899. let dataUser = getDataProfile(f_pin: sender.message_id, message_id: "")
  900. let controller = AppStoryBoard.Palio.instance.instantiateViewController(withIdentifier: "profileView") as! ProfileViewController
  901. controller.flag = .invite
  902. controller.user = nil
  903. controller.name = dataUser["name"]!
  904. controller.data = sender.message_id
  905. controller.picture = dataUser["image_id"]!
  906. self.navigationController?.show(controller, sender: nil)
  907. }
  908. }
  909. }
  910. @objc func seeProfileTapped() {
  911. if isHistoryCC || removed || copySession || forwardSession || deleteSession || (dataGroup["official"] as? String == "1" && (dataGroup["parent"] as? String)!.isEmpty) {
  912. return
  913. }
  914. dismissKeyboard()
  915. let controller = AppStoryBoard.Palio.instance.instantiateViewController(withIdentifier: "groupDetailView") as! GroupDetailViewController
  916. controller.data = dataGroup["group_id"] as! String
  917. controller.checkReadMessage = {
  918. if self.currentIndexpath == nil {
  919. var listData = self.dataMessages
  920. listData = listData.filter({$0["status"] as! String != "4" && $0["status"] as! String != "8"})
  921. if listData.count != 0 {
  922. let idMe = UserDefaults.standard.string(forKey: "me") as String?
  923. for i in 0...listData.count - 1 {
  924. if listData[i]["f_pin"] as? String != idMe {
  925. 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)
  926. }
  927. }
  928. }
  929. } else {
  930. let dataMessages = self.dataMessages.filter({ $0["chat_date"] as! String == self.dataDates[self.currentIndexpath!.section] })
  931. var listData = dataMessages
  932. listData = listData.filter({$0["status"] as! String != "4" && $0["status"] as! String != "8"})
  933. if listData.count != 0 {
  934. let idMe = UserDefaults.standard.string(forKey: "me") as String?
  935. for i in 0...listData.count - 1 {
  936. if listData[i]["f_pin"] as? String != idMe {
  937. 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)
  938. }
  939. }
  940. }
  941. }
  942. }
  943. navigationController?.show(controller, sender: nil)
  944. }
  945. @objc func dismissKeyboard() {
  946. textFieldSend.resignFirstResponder() // dismiss keyoard
  947. if (self.constraintBottomAttachment.constant != 0.0) {
  948. constraintBottomAttachment.constant = 0.0
  949. self.viewSticker.removeConstraints(self.viewSticker.constraints)
  950. self.viewSticker.removeFromSuperview()
  951. }
  952. }
  953. @objc func keyboardWillShow(notification: NSNotification) {
  954. if self.viewIfLoaded?.window != nil {
  955. if (self.constraintBottomAttachment.constant != 0.0) {
  956. self.constraintBottomAttachment.constant = 0.0
  957. self.viewSticker.removeConstraints(self.viewSticker.constraints)
  958. self.viewSticker.removeFromSuperview()
  959. }
  960. let info:NSDictionary = notification.userInfo! as NSDictionary
  961. let keyboardSize = (info[UIResponder.keyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
  962. let keyboardHeight: CGFloat = keyboardSize.height
  963. let duration: CGFloat = info[UIResponder.keyboardAnimationDurationUserInfoKey] as! NSNumber as! CGFloat
  964. if self.constraintViewTextField.constant != keyboardHeight - 60 {
  965. self.constraintViewTextField.constant = keyboardHeight - 60
  966. UIView.animate(withDuration: TimeInterval(duration), animations: {
  967. self.view.layoutIfNeeded()
  968. })
  969. if (self.currentIndexpath != nil) {
  970. self.tableChatView.scrollToRow(at: IndexPath(row: self.currentIndexpath!.row, section: self.currentIndexpath!.section), at: .none, animated: false)
  971. } else {
  972. self.tableChatView.scrollToBottom()
  973. }
  974. }
  975. }
  976. }
  977. @objc func keyboardWillHide(notification: NSNotification) {
  978. if self.viewIfLoaded?.window != nil {
  979. let info:NSDictionary = notification.userInfo! as NSDictionary
  980. let duration: CGFloat = info[UIResponder.keyboardAnimationDurationUserInfoKey] as! NSNumber as! CGFloat
  981. self.constraintViewTextField.constant = 0
  982. UIView.animate(withDuration: TimeInterval(duration), animations: {
  983. self.view.layoutIfNeeded()
  984. })
  985. }
  986. }
  987. @objc func sendTapped() {
  988. sendChat(message_text: textFieldSend.text!, viewController: self)
  989. }
  990. 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) {
  991. if viewController is EditorGroup && file_id == "" && dataMessageForward == nil {
  992. if ((textFieldSend.text!.trimmingCharacters(in: .whitespacesAndNewlines) == "Send message".localized() && textFieldSend.textColor == UIColor.lightGray && attachment_flag != "11") || textFieldSend.text!.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty ) {
  993. dismissKeyboard()
  994. viewController.showToast(message: "Type Messages".localized(), font: UIFont.systemFont(ofSize: 12, weight: .medium), controller: self)
  995. if (textFieldSend.text!.trimmingCharacters(in: .whitespacesAndNewlines) != "Send message".localized()) {
  996. textFieldSend.text = ""
  997. }
  998. if (self.heightTextFieldSend.constant != 40) {
  999. self.heightTextFieldSend.constant = 40
  1000. }
  1001. return
  1002. }
  1003. }
  1004. var reff_id = reff_id
  1005. if (reffId != nil) {
  1006. reff_id = reffId!
  1007. }
  1008. let message_text = message_text.trimmingCharacters(in: .whitespacesAndNewlines)
  1009. let idMe = UserDefaults.standard.string(forKey: "me") as String?
  1010. 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: "")
  1011. Nexilis.addQueueMessage(message: message)
  1012. let messageId = String(message.mBodies[CoreMessage_TMessageKey.MESSAGE_ID]!)
  1013. var row: [String: Any?] = [:]
  1014. row["message_id"] = messageId
  1015. row["f_pin"] = idMe
  1016. row["l_pin"] = dataGroup["group_id"]!!
  1017. row["message_scope_id"] = message_scope_id
  1018. row["server_date"] = "\(Date().millisecondsSince1970)"
  1019. row["status"] = status
  1020. row["message_text"] = message_text
  1021. row["audio_id"] = audio_id
  1022. row["video_id"] = video_id
  1023. row["image_id"] = image_id
  1024. row["thumb_id"] = thumb_id
  1025. row["read_receipts"] = 0
  1026. row["chat_id"] = dataTopic["chat_id"]!!
  1027. row["file_id"] = file_id
  1028. row["attachment_flag"] = attachment_flag
  1029. row["reff_id"] = reff_id
  1030. row["progress"] = 0.0
  1031. row["lock"] = "0"
  1032. row["is_stared"] = "0"
  1033. row["isSelected"] = false
  1034. if !dataDates.contains("Today".localized()){
  1035. dataDates.append("Today".localized())
  1036. tableChatView.insertSections(IndexSet(integer: dataDates.count - 1), with: .fade)
  1037. }
  1038. row["chat_date"] = "Today".localized()
  1039. dataMessages.append(row)
  1040. tableChatView.insertRows(at: [IndexPath(row: dataMessages.filter({ $0["chat_date"] as! String == dataDates[dataDates.count - 1]}).count - 1, section: dataDates.count - 1)], with: .fade)
  1041. if textFieldSend.text!.trimmingCharacters(in: .whitespacesAndNewlines) != "Send message".localized() && textFieldSend.textColor != UIColor.lightGray && constraintViewTextField.constant == 0 {
  1042. textFieldSend.text = "Send message".localized()
  1043. textFieldSend.textColor = UIColor.lightGray
  1044. } else if constraintViewTextField.constant != 0 {
  1045. textFieldSend.text = ""
  1046. heightTextFieldSend.constant = 40
  1047. }
  1048. deleteReplyView()
  1049. deleteLinkPreview()
  1050. DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) {
  1051. self.tableChatView.scrollToBottom()
  1052. if self.markerCounter != nil {
  1053. self.markerCounter = nil
  1054. self.tableChatView.reloadData()
  1055. }
  1056. }
  1057. }
  1058. private func getCounter() {
  1059. Database().database?.inTransaction({ fmdb, rollback in
  1060. var l_pin = self.dataGroup["group_id"]!!
  1061. if (self.dataTopic["chat_id"] as! String != "") {
  1062. l_pin = self.dataTopic["chat_id"] as! String
  1063. }
  1064. if let c = Database().getRecords(fmdb: fmdb, query: "SELECT counter FROM MESSAGE_SUMMARY where l_pin='\(l_pin)'"), c.next() {
  1065. counter = Int(c.int(forColumnIndex: 0))
  1066. c.close()
  1067. }
  1068. })
  1069. }
  1070. private func updateCounter(counter: Int) {
  1071. DispatchQueue.global().async {
  1072. Database.shared.database?.inTransaction({ (fmdb, rollback) in
  1073. var l_pin = self.dataGroup["group_id"]!!
  1074. if (self.dataTopic["chat_id"] as! String != "") {
  1075. l_pin = self.dataTopic["chat_id"] as! String
  1076. }
  1077. _ = Database.shared.updateRecord(fmdb: fmdb, table: "MESSAGE_SUMMARY", cvalues: [
  1078. "counter" : "\(counter)"
  1079. ], _where: "l_pin = '\(l_pin)'")
  1080. })
  1081. NotificationCenter.default.post(name: NSNotification.Name(rawValue: "reloadTabChats"), object: nil, userInfo: nil)
  1082. }
  1083. }
  1084. private func disableEditor() {
  1085. view.addSubview(containerAction)
  1086. containerAction.translatesAutoresizingMaskIntoConstraints = false
  1087. NSLayoutConstraint.activate([
  1088. containerAction.leadingAnchor.constraint(equalTo: self.view.leadingAnchor),
  1089. containerAction.trailingAnchor.constraint(equalTo: self.view.trailingAnchor),
  1090. containerAction.bottomAnchor.constraint(equalTo: self.view.bottomAnchor),
  1091. containerAction.heightAnchor.constraint(equalToConstant: 120)
  1092. ])
  1093. containerAction.backgroundColor = .secondaryColor.withAlphaComponent(0.8)
  1094. let labelDisable = UILabel()
  1095. containerAction.addSubview(labelDisable)
  1096. labelDisable.translatesAutoresizingMaskIntoConstraints = false
  1097. NSLayoutConstraint.activate([
  1098. labelDisable.centerYAnchor.constraint(equalTo: containerAction.centerYAnchor),
  1099. labelDisable.centerXAnchor.constraint(equalTo: containerAction.centerXAnchor),
  1100. ])
  1101. labelDisable.textColor = .black
  1102. labelDisable.font = UIFont.systemFont(ofSize: 12).bold
  1103. labelDisable.text = "Call Center Session has ended".localized()
  1104. }
  1105. private func addButtonScrollToBottom() {
  1106. self.view.addSubview(buttonScrollToBottom)
  1107. buttonScrollToBottom.translatesAutoresizingMaskIntoConstraints = false
  1108. NSLayoutConstraint.activate([
  1109. buttonScrollToBottom.bottomAnchor.constraint(equalTo: buttonSendChat.topAnchor, constant: -50),
  1110. buttonScrollToBottom.trailingAnchor.constraint(equalTo: self.view.trailingAnchor),
  1111. buttonScrollToBottom.widthAnchor.constraint(equalToConstant: 60),
  1112. buttonScrollToBottom.heightAnchor.constraint(equalToConstant: 30.0)
  1113. ])
  1114. buttonScrollToBottom.backgroundColor = .greenColor
  1115. buttonScrollToBottom.setImage(UIImage(systemName: "chevron.down.circle"), for: .normal)
  1116. buttonScrollToBottom.imageView?.contentMode = .scaleAspectFit
  1117. buttonScrollToBottom.imageView?.tintColor = .white
  1118. buttonScrollToBottom.contentVerticalAlignment = .fill
  1119. buttonScrollToBottom.contentHorizontalAlignment = .fill
  1120. buttonScrollToBottom.imageEdgeInsets.top = 2.0
  1121. buttonScrollToBottom.imageEdgeInsets.bottom = 2.0
  1122. buttonScrollToBottom.layer.cornerRadius = 10.0
  1123. buttonScrollToBottom.layer.maskedCorners = [.layerMinXMinYCorner, .layerMinXMaxYCorner]
  1124. buttonScrollToBottom.clipsToBounds = true
  1125. buttonScrollToBottom.addTarget(self, action: #selector(scrollTobottomAction), for: .touchUpInside)
  1126. }
  1127. private func addCounterAtButttonScrollToBottom() {
  1128. self.view.addSubview(indicatorCounterBSTB)
  1129. indicatorCounterBSTB.translatesAutoresizingMaskIntoConstraints = false
  1130. indicatorCounterBSTB.backgroundColor = .systemRed
  1131. indicatorCounterBSTB.layer.cornerRadius = 7.5
  1132. indicatorCounterBSTB.clipsToBounds = true
  1133. indicatorCounterBSTB.layer.borderWidth = 0.5
  1134. indicatorCounterBSTB.layer.borderColor = UIColor.secondaryColor.cgColor
  1135. NSLayoutConstraint.activate([
  1136. indicatorCounterBSTB.bottomAnchor.constraint(equalTo: buttonScrollToBottom.topAnchor, constant: 5),
  1137. indicatorCounterBSTB.trailingAnchor.constraint(equalTo: self.view.trailingAnchor, constant: -50),
  1138. indicatorCounterBSTB.widthAnchor.constraint(greaterThanOrEqualToConstant: 15),
  1139. indicatorCounterBSTB.heightAnchor.constraint(equalToConstant: 15)
  1140. ])
  1141. indicatorCounterBSTB.addSubview(labelCounter)
  1142. labelCounter.translatesAutoresizingMaskIntoConstraints = false
  1143. NSLayoutConstraint.activate([
  1144. labelCounter.leadingAnchor.constraint(equalTo: indicatorCounterBSTB.leadingAnchor, constant: 2),
  1145. labelCounter.trailingAnchor.constraint(equalTo: indicatorCounterBSTB.trailingAnchor, constant: -2),
  1146. labelCounter.centerXAnchor.constraint(equalTo: indicatorCounterBSTB.centerXAnchor),
  1147. ])
  1148. labelCounter.font = UIFont.systemFont(ofSize: 11)
  1149. labelCounter.text = "\(counter)"
  1150. labelCounter.textColor = .secondaryColor
  1151. labelCounter.textAlignment = .center
  1152. }
  1153. @objc func scrollTobottomAction() {
  1154. tableChatView.scrollToBottom()
  1155. DispatchQueue.main.asyncAfter(deadline: .now() + 0.35) { [self] in
  1156. if buttonScrollToBottom.isDescendant(of: self.view) {
  1157. buttonScrollToBottom.removeConstraints(buttonScrollToBottom.constraints)
  1158. buttonScrollToBottom.removeFromSuperview()
  1159. if indicatorCounterBSTB.isDescendant(of: self.view) {
  1160. indicatorCounterBSTB.removeConstraints(indicatorCounterBSTB.constraints)
  1161. indicatorCounterBSTB.removeFromSuperview()
  1162. }
  1163. }
  1164. }
  1165. }
  1166. private func sendReadMessageStatus(chat_id: String, f_pin: String, message_scope_id: String, message_id: String) {
  1167. let message = CoreMessage_TMessageBank.getUpdateRead(p_chat_id: chat_id, p_f_pin: f_pin, p_scope_id: message_scope_id, qty: 1)
  1168. let fPin = message.getBody(key: CoreMessage_TMessageKey.F_PIN)
  1169. let scope = message.getBody(key: CoreMessage_TMessageKey.SCOPE_ID)
  1170. message.mBodies[CoreMessage_TMessageKey.SERVER_DATE] = String(Date().currentTimeMillis())
  1171. if (fPin.elementsEqual("-999") || scope.elementsEqual("16") || scope.elementsEqual("15")){
  1172. return
  1173. }
  1174. DispatchQueue.global().async {
  1175. Database.shared.database?.inTransaction({ (fmdb, rollback) in
  1176. _ = Database.shared.updateRecord(fmdb: fmdb, table: "MESSAGE", cvalues: [
  1177. "status" : "4"
  1178. ], _where: "message_id = '\(message_id)'")
  1179. })
  1180. message.mStatus = CoreMessage_TMessageUtil.getTID()
  1181. message.mBodies[CoreMessage_TMessageKey.L_PIN] = f_pin
  1182. message.mBodies[CoreMessage_TMessageKey.MESSAGE_ID] = "-2,\(message_id)"
  1183. _ = Nexilis.write(message: message)
  1184. }
  1185. if let index = dataMessages.firstIndex(where: {$0["message_id"] as? String == message_id}) {
  1186. dataMessages[index]["status"] = "4"
  1187. let auto = UserDefaults.standard.bool(forKey: "autoDownload")
  1188. if auto {
  1189. if dataMessages[index]["image_id"] as? String != nil && !((dataMessages[index]["image_id"] as? String)!.isEmpty) {
  1190. Download().start(forKey:dataMessages[index]["image_id"] as! String) { (name, progress) in
  1191. guard progress == 100 else {
  1192. return
  1193. }
  1194. let nsDocumentDirectory = FileManager.SearchPathDirectory.documentDirectory
  1195. let nsUserDomainMask = FileManager.SearchPathDomainMask.userDomainMask
  1196. let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true)
  1197. if let dirPath = paths.first {
  1198. let imageURL = URL(fileURLWithPath: dirPath).appendingPathComponent(self.dataMessages[index]["image_id"] as! String)
  1199. let image = UIImage(contentsOfFile: imageURL.path)
  1200. let save = UserDefaults.standard.bool(forKey: "saveToGallery")
  1201. if save {
  1202. UIImageWriteToSavedPhotosAlbum(image!, nil, nil, nil)
  1203. }
  1204. }
  1205. DispatchQueue.main.async { [self] in
  1206. let section = self.dataDates.firstIndex(of: dataMessages[index]["chat_date"] as! String)
  1207. let row = self.dataMessages.filter({$0["chat_date"] as! String == dataMessages[index]["chat_date"] as! String}).firstIndex(where: { $0["message_id"] as? String == message_id})
  1208. if row != nil && section != nil{
  1209. tableChatView.reloadRows(at: [IndexPath(row: row!, section: section!)], with: .automatic)
  1210. }
  1211. }
  1212. }
  1213. } else if dataMessages[index]["video_id"] as? String != nil && !((dataMessages[index]["video_id"] as? String)!.isEmpty){
  1214. let section = dataDates.firstIndex(of: dataMessages[index]["chat_date"] as! String)
  1215. let row = dataMessages.filter({$0["chat_date"] as! String == dataMessages[index]["chat_date"] as! String}).firstIndex(where: { $0["message_id"] as? String == message_id})
  1216. if row != nil && section != nil{
  1217. let indexPath = IndexPath(row: row!, section: section!)
  1218. if let cell = tableChatView.cellForRow(at: indexPath) {
  1219. for view in cell.contentView.subviews {
  1220. if view is UIImageView {
  1221. let objectTap = ObjectGesture()
  1222. objectTap.video_id = dataMessages[index]["video_id"] as! String
  1223. objectTap.imageView = view as! UIImageView
  1224. objectTap.indexPath = indexPath
  1225. contentMessageTapped(objectTap)
  1226. break
  1227. }
  1228. }
  1229. }
  1230. }
  1231. }
  1232. }
  1233. }
  1234. }
  1235. private func sendTyping(l_pin: String, isTyping: Bool = false) {
  1236. DispatchQueue.global().async {
  1237. let tmessage = CoreMessage_TMessageBank.getUpdateTypingStatus(p_opposite: l_pin, p_scope: "4", p_status: isTyping ? "3": "4")
  1238. _ = Nexilis.write(message: tmessage)
  1239. }
  1240. }
  1241. private func checkNewMessage(tableView: UITableView) {
  1242. currentIndexpath = tableView.indexPathsForVisibleRows?.last
  1243. if currentIndexpath != nil {
  1244. let dataMessages = dataMessages.filter({ $0["chat_date"] as! String == dataDates[currentIndexpath!.section] })
  1245. if dataMessages.count == 0 {
  1246. return
  1247. }
  1248. if currentIndexpath!.section == dataDates.count - 1 && currentIndexpath!.row != dataMessages.count - 1 && currentIndexpath!.row != dataMessages.count - 2 && !buttonScrollToBottom.isDescendant(of: self.view) {
  1249. addButtonScrollToBottom()
  1250. addCounterAtButttonScrollToBottom()
  1251. } else if currentIndexpath!.section == dataDates.count - 1 && currentIndexpath!.row == dataMessages.count - 1 {
  1252. if buttonScrollToBottom.isDescendant(of: self.view) {
  1253. buttonScrollToBottom.removeConstraints(buttonScrollToBottom.constraints)
  1254. buttonScrollToBottom.removeFromSuperview()
  1255. if indicatorCounterBSTB.isDescendant(of: self.view) {
  1256. indicatorCounterBSTB.removeConstraints(indicatorCounterBSTB.constraints)
  1257. indicatorCounterBSTB.removeFromSuperview()
  1258. }
  1259. }
  1260. }
  1261. if dataMessages.count - 1 < currentIndexpath!.row {
  1262. return
  1263. }
  1264. var listData = dataMessages[0...currentIndexpath!.row]
  1265. listData = listData.filter({$0["status"] as! String != "4" && $0["status"] as! String != "8"})
  1266. if listData.count != 0 {
  1267. let idMe = UserDefaults.standard.string(forKey: "me") as String?
  1268. for i in 0...listData.count - 1 {
  1269. if listData[i]["f_pin"] as? String != idMe {
  1270. 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)
  1271. }
  1272. }
  1273. }
  1274. }
  1275. if counter == 0 && indicatorCounterBSTB.isDescendant(of: self.view) {
  1276. indicatorCounterBSTB.removeConstraints(indicatorCounterBSTB.constraints)
  1277. indicatorCounterBSTB.removeFromSuperview()
  1278. } else if counter != 0 && currentIndexpath != nil {
  1279. let dataFilter = dataMessages.filter({ $0["chat_date"] as! String == dataDates[currentIndexpath!.section] })
  1280. if dataFilter.count == 0 {
  1281. return
  1282. }
  1283. let idx = dataMessages.firstIndex(where: { $0["message_id"] as! String == dataFilter[currentIndexpath!.row]["message_id"] as! String})
  1284. if idx == nil {
  1285. return
  1286. }
  1287. if (dataMessages.count - counter) <= idx! {
  1288. let countUpdate = idx! - (dataMessages.count - counter)
  1289. counter = counter - (countUpdate + 1)
  1290. if indicatorCounterBSTB.isDescendant(of: self.view) {
  1291. labelCounter.text = "\(counter)"
  1292. }
  1293. updateCounter(counter: counter)
  1294. }
  1295. }
  1296. }
  1297. }
  1298. extension EditorGroup: ImageVideoPickerDelegate, PreviewAttachmentImageVideoDelegate {
  1299. public func didSelect(imagevideo: Any?) {
  1300. if (imagevideo != nil) {
  1301. let imageVideoData = imagevideo as! [UIImagePickerController.InfoKey: Any]
  1302. let previewImageVC = PreviewAttachmentImageVideo(nibName: "PreviewAttachmentImageVideo", bundle: Bundle.resourceBundle(for: Nexilis.self))
  1303. previewImageVC.imageVideoData = imageVideoData
  1304. if (textFieldSend.textColor != .lightGray) {
  1305. previewImageVC.currentTextTextField = textFieldSend.text
  1306. }
  1307. previewImageVC.modalPresentationStyle = .custom
  1308. previewImageVC.delegate = self
  1309. self.present(previewImageVC, animated: true, completion: nil)
  1310. }
  1311. }
  1312. func sendChatFromPreviewImage(message_text: String, attachment_flag: String, image_id: String, video_id: String, thumb_id: String, viewController: UIViewController) {
  1313. sendChat(message_text: message_text, attachment_flag: attachment_flag, image_id: image_id, video_id: video_id, thumb_id: thumb_id, viewController: viewController)
  1314. }
  1315. }
  1316. extension EditorGroup: UIDocumentPickerDelegate, DocumentPickerDelegate, QLPreviewControllerDataSource {
  1317. public func didSelectDocument(document: Any?) {
  1318. if (document != nil) {
  1319. self.previewItem = (document as! [URL])[0] as NSURL
  1320. let previewController = QLPreviewController()
  1321. let navController = UINavigationController(rootViewController: previewController)
  1322. let leftBarButton = navigationQLPreviewDocument(title: "Cancel".localized(), style: .plain, target: self, action: #selector(cancelDocumentPreview))
  1323. let rightBarButton = navigationQLPreviewDocument(title: "Send".localized(), style: .done, target: self, action: #selector(sendDocument))
  1324. // leftBarButton.tintColor = .white
  1325. // rightBarButton.tintColor = .white
  1326. leftBarButton.navigation = navController
  1327. rightBarButton.navigation = navController
  1328. // navController.navigationBar.barTintColor = .mainColor
  1329. navController.navigationBar.isTranslucent = false
  1330. previewController.navigationItem.leftBarButtonItem = leftBarButton
  1331. previewController.navigationItem.rightBarButtonItem = rightBarButton
  1332. previewController.dataSource = self
  1333. previewController.modalPresentationStyle = .pageSheet
  1334. self.present(navController, animated: true, completion: nil)
  1335. }
  1336. }
  1337. @objc private func cancelDocumentPreview(sender: navigationQLPreviewDocument) {
  1338. sender.navigation.dismiss(animated: true, completion: nil)
  1339. }
  1340. @objc private func sendDocument(sender: navigationQLPreviewDocument) {
  1341. sender.navigation.dismiss(animated: true, completion: nil)
  1342. do {
  1343. let dataFile = try Data(contentsOf: self.previewItem! as URL)
  1344. let urlFile = self.previewItem?.absoluteString
  1345. var originaFileName = (urlFile! as NSString).lastPathComponent
  1346. originaFileName = NSString(string: originaFileName).removingPercentEncoding!
  1347. let renamedNameFile = "Qmera_doc_" + "\(Date().millisecondsSince1970)_" + originaFileName
  1348. let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
  1349. let fileURL = documentsDirectory.appendingPathComponent(renamedNameFile)
  1350. if !FileManager.default.fileExists(atPath: fileURL.path) {
  1351. do {
  1352. try dataFile.write(to: fileURL)
  1353. print("file saved")
  1354. } catch {
  1355. print("error saving file:", error)
  1356. }
  1357. }
  1358. sendChat(message_text: "\(originaFileName)|", attachment_flag: "6", file_id: renamedNameFile, viewController: self)
  1359. } catch {
  1360. }
  1361. }
  1362. }
  1363. extension EditorGroup: UITextViewDelegate {
  1364. public func textViewDidChange(_ textView: UITextView) {
  1365. if allowTyping {
  1366. allowTyping = false
  1367. if dataTopic["chat_id"] as! String == "" {
  1368. UNUserNotificationCenter.current().removeDeliveredNotifications(withIdentifiers: [dataGroup["group_id"] as! String])
  1369. sendTyping(l_pin: dataGroup["group_id"] as! String)
  1370. } else {
  1371. UNUserNotificationCenter.current().removeDeliveredNotifications(withIdentifiers: [dataTopic["chat_id"] as! String])
  1372. sendTyping(l_pin: dataTopic["chat_id"] as! String)
  1373. }
  1374. DispatchQueue.main.asyncAfter(deadline: .now() + 4, execute: {
  1375. self.allowTyping = true
  1376. })
  1377. }
  1378. if let selectedRange = textView.selectedTextRange {
  1379. let cursorPosition = textView.offset(from: textView.beginningOfDocument, to: selectedRange.start)
  1380. let beforeCursor = textView.text.substring(from: cursorPosition - cursorPosition, to: cursorPosition - 1).split(separator: " ").last
  1381. let afterCursor = textView.text.substring(from: cursorPosition, to: textView.text.count - 1).split(separator: " ").first
  1382. var firstCount = 0
  1383. var lastCount = textView.text.count
  1384. if beforeCursor != nil {
  1385. firstCount = cursorPosition - beforeCursor!.count - 1
  1386. if firstCount == -1 {
  1387. firstCount = 0
  1388. }
  1389. if beforeCursor!.lowercased().checkStartWithLink() {
  1390. if textView.text.split(separator: " ").count > 1 && self.containerLink.isDescendant(of: self.viewTextfield) {
  1391. } else {
  1392. if ((beforeCursor!.lowercased().starts(with: "www.") && beforeCursor!.lowercased().split(separator: ".").count >= 3) || (!beforeCursor!.lowercased().starts(with: "www.") && beforeCursor!.lowercased().split(separator: ".").count >= 2)) && beforeCursor!.lowercased().split(separator: ".").last!.count >= 2 {
  1393. checkLink(text: beforeCursor!.lowercased())
  1394. } else {
  1395. deleteLinkPreview()
  1396. }
  1397. }
  1398. }
  1399. }
  1400. if afterCursor != nil {
  1401. if beforeCursor == nil {
  1402. lastCount = afterCursor!.count + 2
  1403. } else {
  1404. lastCount = beforeCursor!.count + afterCursor!.count + 2
  1405. }
  1406. if afterCursor!.lowercased().checkStartWithLink() {
  1407. if textView.text.split(separator: " ").count > 1 && self.containerLink.isDescendant(of: self.viewTextfield) {
  1408. } else {
  1409. if ((afterCursor!.lowercased().starts(with: "www.") && afterCursor!.lowercased().split(separator: ".").count >= 3) || afterCursor!.lowercased().split(separator: ".").count >= 2) && afterCursor!.lowercased().split(separator: ".").last!.count >= 2 {
  1410. checkLink(text: afterCursor!.lowercased())
  1411. } else {
  1412. deleteLinkPreview()
  1413. }
  1414. }
  1415. }
  1416. }
  1417. if textView.text.contains("*") || textView.text.contains("_") || textView.text.contains("^") || textView.text.contains("~") {
  1418. textView.preserveCursorPosition(withChanges: { _ in
  1419. textView.attributedText = textView.text.richText(isEditing: true, first: firstCount, last: lastCount)
  1420. return .preserveCursor
  1421. })
  1422. }
  1423. }
  1424. }
  1425. private func checkLink(text: String) {
  1426. var stringURl = text
  1427. if stringURl.starts(with: "www.") {
  1428. stringURl = "https://" + stringURl.replacingOccurrences(of: "www.", with: "")
  1429. }
  1430. var dataURL = ""
  1431. Database.shared.database?.inTransaction({ (fmdb, rollback) in
  1432. if let cursor = Database.shared.getRecords(fmdb: fmdb, query: "select data_link from LINK_PREVIEW where link='\(stringURl)'") {
  1433. while cursor.next() {
  1434. if let data = cursor.string(forColumnIndex: 0) {
  1435. dataURL = data
  1436. }
  1437. }
  1438. cursor.close()
  1439. }
  1440. })
  1441. if !dataURL.isEmpty {
  1442. if let data = try! JSONSerialization.jsonObject(with: dataURL.data(using: String.Encoding.utf8)!, options: []) as? [String: Any] {
  1443. let title = data["title"] as! String
  1444. let description = data["description"] as! String
  1445. let imageUrl = data["imageUrl"] as? String
  1446. self.buildPreviewLink(imageUrl: imageUrl, title: title, description: description, stringURl: text)
  1447. }
  1448. } else {
  1449. let urlData = URL(string: stringURl)!
  1450. Readability.parse(url: urlData, completion: { data in
  1451. self.deleteLinkPreview()
  1452. if data != nil {
  1453. let title = data!.title
  1454. let description = data!.description
  1455. let imageUrl = data!.topImage
  1456. Database.shared.database?.inTransaction({ (fmdb, rollback) in
  1457. do {
  1458. var dataJson: [String: Any] = [:]
  1459. dataJson["title"] = title
  1460. dataJson["description"] = description
  1461. dataJson["imageUrl"] = imageUrl
  1462. guard let json = String(data: try! JSONSerialization.data(withJSONObject: dataJson, options: []), encoding: String.Encoding.utf8) else {
  1463. return
  1464. }
  1465. _ = try Database.shared.insertRecord(fmdb: fmdb, table: "LINK_PREVIEW", cvalues: [
  1466. "id" : "\(Date().currentTimeMillis().toHex())",
  1467. "link" : stringURl,
  1468. "data_link" : json,
  1469. "retry": 0
  1470. ], replace: true)
  1471. } catch {
  1472. rollback.pointee = true
  1473. print(error)
  1474. }
  1475. })
  1476. self.buildPreviewLink(imageUrl: imageUrl, title: title, description: description, stringURl: text)
  1477. }
  1478. })
  1479. }
  1480. }
  1481. private func buildPreviewLink(imageUrl: String?, title: String, description: String?, stringURl: String) {
  1482. UIView.animate(withDuration: 0.25, delay: 0.0, options: .curveEaseInOut, animations: {
  1483. self.constraintTopTextField.constant = self.constraintTopTextField.constant + 80
  1484. }, completion: nil)
  1485. self.viewTextfield.addSubview(self.containerLink)
  1486. self.containerLink.translatesAutoresizingMaskIntoConstraints = false
  1487. self.containerLink.leadingAnchor.constraint(equalTo: self.viewTextfield.leadingAnchor).isActive = true
  1488. self.containerLink.bottomAnchor.constraint(equalTo: self.textFieldSend.topAnchor).isActive = true
  1489. self.containerLink.trailingAnchor.constraint(equalTo: self.viewTextfield.trailingAnchor).isActive = true
  1490. self.containerLink.heightAnchor.constraint(equalToConstant: 80.0).isActive = true
  1491. self.containerLink.backgroundColor = .secondaryColor
  1492. if self.reffId != nil {
  1493. self.bottomAnchorPreviewReply.isActive = false
  1494. self.bottomAnchorPreviewReply = self.containerPreviewReply.bottomAnchor.constraint(equalTo: self.containerLink.topAnchor)
  1495. self.bottomAnchorPreviewReply.isActive = true
  1496. }
  1497. let imagePreview = UIImageView()
  1498. if imageUrl != nil {
  1499. self.containerLink.addSubview(imagePreview)
  1500. imagePreview.translatesAutoresizingMaskIntoConstraints = false
  1501. imagePreview.leadingAnchor.constraint(equalTo: self.containerLink.leadingAnchor).isActive = true
  1502. imagePreview.bottomAnchor.constraint(equalTo: self.containerLink.bottomAnchor).isActive = true
  1503. imagePreview.topAnchor.constraint(equalTo: self.containerLink.topAnchor).isActive = true
  1504. imagePreview.widthAnchor.constraint(equalToConstant: 80.0).isActive = true
  1505. if !imageUrl!.starts(with: "https://") {
  1506. imagePreview.loadImageAsync(with: "https://www.google.be" + imageUrl!)
  1507. } else {
  1508. imagePreview.loadImageAsync(with: imageUrl)
  1509. }
  1510. imagePreview.contentMode = .scaleAspectFit
  1511. }
  1512. let titlePreview = UILabel()
  1513. self.containerLink.addSubview(titlePreview)
  1514. titlePreview.translatesAutoresizingMaskIntoConstraints = false
  1515. if imageUrl != nil {
  1516. titlePreview.leadingAnchor.constraint(equalTo: imagePreview.trailingAnchor, constant: 5.0).isActive = true
  1517. } else {
  1518. titlePreview.leadingAnchor.constraint(equalTo: self.containerLink.leadingAnchor, constant: 5.0).isActive = true
  1519. }
  1520. titlePreview.topAnchor.constraint(equalTo: self.containerLink.topAnchor, constant: 25.0).isActive = true
  1521. titlePreview.trailingAnchor.constraint(equalTo: self.containerLink.trailingAnchor, constant: -80.0).isActive = true
  1522. titlePreview.text = title
  1523. titlePreview.font = UIFont.systemFont(ofSize: 14.0, weight: .bold)
  1524. titlePreview.textColor = .black
  1525. let descPreview = UILabel()
  1526. self.containerLink.addSubview(descPreview)
  1527. descPreview.translatesAutoresizingMaskIntoConstraints = false
  1528. if imageUrl != nil {
  1529. descPreview.leadingAnchor.constraint(equalTo: imagePreview.trailingAnchor, constant: 5.0).isActive = true
  1530. } else {
  1531. descPreview.leadingAnchor.constraint(equalTo: self.containerLink.leadingAnchor, constant: 5.0).isActive = true
  1532. }
  1533. descPreview.topAnchor.constraint(equalTo: titlePreview.bottomAnchor).isActive = true
  1534. descPreview.trailingAnchor.constraint(equalTo: self.containerLink.trailingAnchor, constant: -80.0).isActive = true
  1535. descPreview.text = description
  1536. descPreview.font = UIFont.systemFont(ofSize: 12.0)
  1537. descPreview.textColor = .gray
  1538. descPreview.numberOfLines = 1
  1539. let linkPreview = UILabel()
  1540. self.containerLink.addSubview(linkPreview)
  1541. linkPreview.translatesAutoresizingMaskIntoConstraints = false
  1542. if imageUrl != nil {
  1543. linkPreview.leadingAnchor.constraint(equalTo: imagePreview.trailingAnchor, constant: 5.0).isActive = true
  1544. } else {
  1545. linkPreview.leadingAnchor.constraint(equalTo: self.containerLink.leadingAnchor, constant: 5.0).isActive = true
  1546. }
  1547. linkPreview.topAnchor.constraint(equalTo: descPreview.bottomAnchor, constant: 8.0).isActive = true
  1548. linkPreview.trailingAnchor.constraint(equalTo: self.containerLink.trailingAnchor, constant: -80.0).isActive = true
  1549. linkPreview.text = stringURl
  1550. linkPreview.font = UIFont.systemFont(ofSize: 10.0)
  1551. linkPreview.textColor = .gray
  1552. linkPreview.numberOfLines = 1
  1553. let cancelPreview = UIButton(type: .custom)
  1554. self.containerLink.addSubview(cancelPreview)
  1555. cancelPreview.translatesAutoresizingMaskIntoConstraints = false
  1556. cancelPreview.trailingAnchor.constraint(equalTo: self.containerLink.trailingAnchor, constant: -10).isActive = true
  1557. cancelPreview.centerYAnchor.constraint(equalTo: self.containerLink.centerYAnchor).isActive = true
  1558. cancelPreview.setImage(UIImage(systemName: "xmark.circle" , withConfiguration: UIImage.SymbolConfiguration(pointSize: 20, weight: .regular, scale: .default)), for: .normal)
  1559. cancelPreview.addTarget(nil, action: #selector(self.deleteLinkPreview), for: .touchUpInside)
  1560. cancelPreview.backgroundColor = .clear
  1561. cancelPreview.tintColor = .mainColor
  1562. }
  1563. public func textViewDidBeginEditing(_ textView: UITextView) {
  1564. if textView.textColor == UIColor.lightGray {
  1565. textView.text = nil
  1566. textView.textColor = UIColor.black
  1567. }
  1568. }
  1569. public func textViewDidEndEditing(_ textView: UITextView) {
  1570. if textView.text.isEmpty {
  1571. textView.text = "Send message".localized()
  1572. textView.textColor = UIColor.lightGray
  1573. }
  1574. }
  1575. public override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
  1576. if action == #selector(UIResponderStandardEditActions.paste(_:)) && (UIPasteboard.general.image != nil) {
  1577. return true
  1578. }
  1579. return super.canPerformAction(action, withSender: sender)
  1580. }
  1581. public override func paste(_ sender: Any?) {
  1582. if UIPasteboard.general.image != nil {
  1583. let previewImageVC = PreviewAttachmentImageVideo(nibName: "PreviewAttachmentImageVideo", bundle: Bundle.resourceBundle(for: Nexilis.self))
  1584. previewImageVC.image = UIPasteboard.general.image
  1585. previewImageVC.fromCopy = true
  1586. previewImageVC.currentTextTextField = textFieldSend.text
  1587. previewImageVC.modalPresentationStyle = .custom
  1588. previewImageVC.delegate = self
  1589. self.present(previewImageVC, animated: true, completion: nil)
  1590. }
  1591. }
  1592. public func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
  1593. let cursorPosition = textView.caretRect(for: self.textFieldSend.selectedTextRange!.start).origin
  1594. let currentLine = Int(cursorPosition.y / self.textFieldSend.font!.lineHeight)
  1595. UIView.animate(withDuration: 0.3) {
  1596. if currentLine == 0 && text != "\n"{
  1597. self.heightTextFieldSend.constant = 40
  1598. } else if currentLine < 4 {
  1599. DispatchQueue.main.async {
  1600. if (self.currentIndexpath != nil) {
  1601. self.tableChatView.scrollToRow(at: IndexPath(row: self.currentIndexpath!.row, section: self.currentIndexpath!.section), at: .none, animated: false)
  1602. }
  1603. }
  1604. if (text == "\n" && self.textFieldSend.text.count > 0) {
  1605. self.heightTextFieldSend.constant = self.textFieldSend.contentSize.height + 18
  1606. }
  1607. else if (self.textFieldSend.text.count > 0) {
  1608. self.heightTextFieldSend.constant = self.textFieldSend.contentSize.height
  1609. }
  1610. let txt = textView.text
  1611. let txtRange = Range(range, in: txt!)
  1612. let subString: Substring = txt![txtRange!]
  1613. if subString == "\n" {
  1614. self.heightTextFieldSend.constant = self.textFieldSend.contentSize.height - 18
  1615. if (self.heightTextFieldSend.constant <= 50 && self.heightTextFieldSend.constant >= 40) {
  1616. self.heightTextFieldSend.constant = 40
  1617. }
  1618. }
  1619. }
  1620. let countBreakLine = text.split(separator: "\n").count
  1621. if countBreakLine > 1 && self.heightTextFieldSend.constant != CGFloat(40 + (countBreakLine * 18)) {
  1622. self.heightTextFieldSend.constant = CGFloat(40 + (countBreakLine * 18))
  1623. }
  1624. }
  1625. if (self.textFieldSend.text.count == 0) {
  1626. return text != "\n"
  1627. }
  1628. return true
  1629. }
  1630. }
  1631. extension EditorGroup: UIContextMenuInteractionDelegate {
  1632. public func contextMenuInteraction(_ interaction: UIContextMenuInteraction, configurationForMenuAtLocation location: CGPoint) -> UIContextMenuConfiguration? {
  1633. if textFieldSend.isFirstResponder {
  1634. textFieldSend.resignFirstResponder()
  1635. }
  1636. let indexPath = self.tableChatView.indexPathForRow(at: interaction.view!.convert(location, to: self.tableChatView))
  1637. let dataMessages = self.dataMessages.filter({ $0["chat_date"] as! String == dataDates[indexPath!.section]})
  1638. var star: UIAction
  1639. if (dataMessages[indexPath!.row]["is_stared"] as! String == "0") {
  1640. star = UIAction(title: "Star".localized(), image: UIImage(systemName: "star.fill"), handler: {(_) in
  1641. DispatchQueue.global().async {
  1642. Database.shared.database?.inTransaction({ (fmdb, rollback) in
  1643. _ = Database.shared.updateRecord(fmdb: fmdb, table: "MESSAGE", cvalues: [
  1644. "is_stared" : 1
  1645. ], _where: "message_id = '\(dataMessages[indexPath!.row]["message_id"] as! String)'")
  1646. })
  1647. }
  1648. let idx = self.dataMessages.firstIndex(where: { $0["message_id"] as! String == dataMessages[indexPath!.row]["message_id"] as! String})
  1649. if idx != nil{
  1650. self.dataMessages[idx!]["is_stared"] = "1"
  1651. }
  1652. self.tableChatView.reloadRows(at: [indexPath!], with: .none)
  1653. })
  1654. } else {
  1655. star = UIAction(title: "Unstar".localized(), image: UIImage(systemName: "star.fill"), handler: {(_) in
  1656. DispatchQueue.global().async {
  1657. Database.shared.database?.inTransaction({ (fmdb, rollback) in
  1658. _ = Database.shared.updateRecord(fmdb: fmdb, table: "MESSAGE", cvalues: [
  1659. "is_stared" : 0
  1660. ], _where: "message_id = '\(dataMessages[indexPath!.row]["message_id"] as! String)'")
  1661. })
  1662. }
  1663. let idx = self.dataMessages.firstIndex(where: { $0["message_id"] as! String == dataMessages[indexPath!.row]["message_id"] as! String})
  1664. if idx != nil{
  1665. self.dataMessages[idx!]["is_stared"] = "0"
  1666. }
  1667. self.tableChatView.reloadRows(at: [indexPath!], with: .none)
  1668. })
  1669. }
  1670. let reply = UIAction(title: "Reply".localized(), image: UIImage(systemName: "arrowshape.turn.up.left.fill"), handler: {(_) in
  1671. self.deleteReplyView()
  1672. self.textFieldSend.becomeFirstResponder()
  1673. self.reffId = dataMessages[indexPath!.row]["message_id"] as? String
  1674. UIView.animate(withDuration: 0.25, delay: 0.0, options: .curveEaseInOut, animations: {
  1675. self.constraintTopTextField.constant = self.constraintTopTextField.constant + 50
  1676. }, completion: nil)
  1677. if (self.currentIndexpath != nil) {
  1678. DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) {
  1679. self.tableChatView.scrollToRow(at: IndexPath(row: self.currentIndexpath!.row, section: self.currentIndexpath!.section), at: .none, animated: false)
  1680. }
  1681. } else {
  1682. self.tableChatView.scrollToBottom()
  1683. }
  1684. self.viewTextfield.addSubview(self.containerPreviewReply)
  1685. self.containerPreviewReply.translatesAutoresizingMaskIntoConstraints = false
  1686. self.containerPreviewReply.leadingAnchor.constraint(equalTo: self.viewTextfield.leadingAnchor).isActive = true
  1687. self.containerPreviewReply.topAnchor.constraint(equalTo: self.viewTextfield.topAnchor).isActive = true
  1688. if !self.containerLink.isDescendant(of: self.viewTextfield) {
  1689. self.bottomAnchorPreviewReply = self.containerPreviewReply.bottomAnchor.constraint(equalTo: self.textFieldSend.topAnchor)
  1690. } else {
  1691. self.bottomAnchorPreviewReply = self.containerPreviewReply.bottomAnchor.constraint(equalTo: self.containerLink.topAnchor)
  1692. }
  1693. self.bottomAnchorPreviewReply.isActive = true
  1694. self.containerPreviewReply.trailingAnchor.constraint(equalTo: self.viewTextfield.trailingAnchor).isActive = true
  1695. self.containerPreviewReply.backgroundColor = .secondaryColor
  1696. let leftReply = UIView()
  1697. self.containerPreviewReply.addSubview(leftReply)
  1698. leftReply.translatesAutoresizingMaskIntoConstraints = false
  1699. leftReply.leadingAnchor.constraint(equalTo: self.viewTextfield.leadingAnchor).isActive = true
  1700. leftReply.topAnchor.constraint(equalTo: self.containerPreviewReply.topAnchor).isActive = true
  1701. leftReply.bottomAnchor.constraint(equalTo: self.containerPreviewReply.bottomAnchor).isActive = true
  1702. leftReply.widthAnchor.constraint(equalToConstant: 3).isActive = true
  1703. leftReply.backgroundColor = .orangeColor
  1704. let titleReply = UILabel()
  1705. self.containerPreviewReply.addSubview(titleReply)
  1706. titleReply.translatesAutoresizingMaskIntoConstraints = false
  1707. titleReply.leadingAnchor.constraint(equalTo: leftReply.leadingAnchor, constant: 10).isActive = true
  1708. titleReply.topAnchor.constraint(equalTo: self.containerPreviewReply.topAnchor, constant: 10).isActive = true
  1709. titleReply.font = UIFont.systemFont(ofSize: 12).bold
  1710. let idMe = UserDefaults.standard.string(forKey: "me") as String?
  1711. if (dataMessages[indexPath!.row]["f_pin"] as? String == idMe) {
  1712. titleReply.text = "You".localized()
  1713. } else {
  1714. if dataMessages[indexPath!.row]["f_pin"] as? String != "-999" {
  1715. let dataPerson = self.getDataProfile(f_pin: dataMessages[indexPath!.row]["f_pin"] as! String, message_id: dataMessages[indexPath!.row]["message_id"] as! String)
  1716. titleReply.text = dataPerson["name"]
  1717. } else {
  1718. titleReply.text = "Bot"
  1719. }
  1720. }
  1721. titleReply.textColor = .orangeColor
  1722. let contentReply = UILabel()
  1723. self.containerPreviewReply.addSubview(contentReply)
  1724. contentReply.translatesAutoresizingMaskIntoConstraints = false
  1725. contentReply.leadingAnchor.constraint(equalTo: leftReply.leadingAnchor, constant: 10).isActive = true
  1726. contentReply.topAnchor.constraint(equalTo: titleReply.bottomAnchor).isActive = true
  1727. contentReply.font = UIFont.systemFont(ofSize: 10)
  1728. let message_text = dataMessages[indexPath!.row]["message_text"] as! String
  1729. let attachment_flag = dataMessages[indexPath!.row]["attachment_flag"] as! String
  1730. let thumb_chat = dataMessages[indexPath!.row]["thumb_id"] as! String
  1731. let image_chat = dataMessages[indexPath!.row]["image_id"] as! String
  1732. let video_chat = dataMessages[indexPath!.row]["video_id"] as! String
  1733. let file_chat = dataMessages[indexPath!.row]["file_id"] as! String
  1734. if (attachment_flag == "0" && thumb_chat == "") {
  1735. contentReply.attributedText = message_text.richText()
  1736. } else if (attachment_flag == "1" || image_chat != "") {
  1737. if (message_text == "") {
  1738. contentReply.text = "📷 Photo".localized()
  1739. } else {
  1740. contentReply.attributedText = message_text.richText()
  1741. }
  1742. } else if (attachment_flag == "2" || video_chat != "") {
  1743. if (message_text == "") {
  1744. contentReply.text = "📹 Video".localized()
  1745. } else {
  1746. contentReply.attributedText = message_text.richText()
  1747. }
  1748. } else if (attachment_flag == "6" || file_chat != ""){
  1749. contentReply.text = "📄 \(message_text.components(separatedBy: "|")[0])"
  1750. } else if (attachment_flag == "11") {
  1751. contentReply.text = "❤️ Sticker"
  1752. } else if attachment_flag == "27" {
  1753. contentReply.text = "📄 " + "Live Streaming".localized()
  1754. } else if attachment_flag == "26" {
  1755. contentReply.text = "📄 " + "Seminar".localized()
  1756. }
  1757. contentReply.textColor = .gray
  1758. let buttonCancelReply = UIButton(type: .custom)
  1759. self.containerPreviewReply.addSubview(buttonCancelReply)
  1760. buttonCancelReply.translatesAutoresizingMaskIntoConstraints = false
  1761. buttonCancelReply.trailingAnchor.constraint(equalTo: self.containerPreviewReply.trailingAnchor, constant: -10).isActive = true
  1762. buttonCancelReply.centerYAnchor.constraint(equalTo: self.containerPreviewReply.centerYAnchor).isActive = true
  1763. buttonCancelReply.setImage(UIImage(systemName: "xmark.circle" , withConfiguration: UIImage.SymbolConfiguration(pointSize: 20, weight: .regular, scale: .default)), for: .normal)
  1764. buttonCancelReply.addTarget(nil, action: #selector(self.deleteReplyView), for: .touchUpInside)
  1765. buttonCancelReply.backgroundColor = .clear
  1766. buttonCancelReply.tintColor = .mainColor
  1767. if (attachment_flag == "1" || attachment_flag == "2" || image_chat != "" || video_chat != "") {
  1768. let nsDocumentDirectory = FileManager.SearchPathDirectory.documentDirectory
  1769. let nsUserDomainMask = FileManager.SearchPathDomainMask.userDomainMask
  1770. let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true)
  1771. if let dirPath = paths.first {
  1772. let thumbURL = URL(fileURLWithPath: dirPath).appendingPathComponent(thumb_chat)
  1773. let image = UIImage(contentsOfFile: thumbURL.path)
  1774. let imageThumb = UIImageView(image: image)
  1775. self.containerPreviewReply.addSubview(imageThumb)
  1776. imageThumb.layer.cornerRadius = 2.0
  1777. imageThumb.clipsToBounds = true
  1778. imageThumb.translatesAutoresizingMaskIntoConstraints = false
  1779. imageThumb.trailingAnchor.constraint(equalTo: buttonCancelReply.leadingAnchor, constant: -10).isActive = true
  1780. imageThumb.centerYAnchor.constraint(equalTo: self.containerPreviewReply.centerYAnchor).isActive = true
  1781. imageThumb.widthAnchor.constraint(equalToConstant: 30).isActive = true
  1782. imageThumb.heightAnchor.constraint(equalToConstant: 30).isActive = true
  1783. if (attachment_flag == "2") {
  1784. let imagePlay = UIImageView(image: UIImage(systemName: "play.circle.fill"))
  1785. imageThumb.addSubview(imagePlay)
  1786. imagePlay.clipsToBounds = true
  1787. imagePlay.translatesAutoresizingMaskIntoConstraints = false
  1788. imagePlay.centerYAnchor.constraint(equalTo: imageThumb.centerYAnchor).isActive = true
  1789. imagePlay.centerXAnchor.constraint(equalTo: imageThumb.centerXAnchor).isActive = true
  1790. imagePlay.widthAnchor.constraint(equalToConstant: 10).isActive = true
  1791. imagePlay.heightAnchor.constraint(equalToConstant: 10).isActive = true
  1792. imagePlay.tintColor = .white
  1793. }
  1794. }
  1795. }
  1796. if (attachment_flag == "11") {
  1797. let imageSticker = UIImageView(image: UIImage(named: (message_text.components(separatedBy: "/")[1]), in: Bundle.resourceBundle(for: Nexilis.self), with: nil))
  1798. self.containerPreviewReply.addSubview(imageSticker)
  1799. imageSticker.layer.cornerRadius = 2.0
  1800. imageSticker.clipsToBounds = true
  1801. imageSticker.translatesAutoresizingMaskIntoConstraints = false
  1802. imageSticker.trailingAnchor.constraint(equalTo: buttonCancelReply.leadingAnchor, constant: -10).isActive = true
  1803. imageSticker.centerYAnchor.constraint(equalTo: self.containerPreviewReply.centerYAnchor).isActive = true
  1804. imageSticker.widthAnchor.constraint(equalToConstant: 30).isActive = true
  1805. imageSticker.heightAnchor.constraint(equalToConstant: 30).isActive = true
  1806. }
  1807. })
  1808. let forward = UIAction(title: "Forward".localized(), image: UIImage(systemName: "arrowshape.turn.up.right.fill"), handler: {(_) in
  1809. self.forwardSession = true
  1810. if self.reffId != nil {
  1811. self.deleteReplyView()
  1812. }
  1813. DispatchQueue.main.asyncAfter(deadline: .now() + 0.35) {
  1814. let cancelButton = UIBarButtonItem(title: "Cancel".localized(), style: .plain, target: self, action: #selector(self.cancelAction))
  1815. self.navigationItem.rightBarButtonItem = cancelButton
  1816. self.changeAppBar()
  1817. let idx = self.dataMessages.firstIndex(where: { $0["message_id"] as! String == dataMessages[indexPath!.row]["message_id"] as! String})
  1818. if idx != nil{
  1819. self.dataMessages[idx!]["isSelected"] = true
  1820. }
  1821. self.addMultipleSelectSession()
  1822. self.tableChatView.reloadData()
  1823. }
  1824. })
  1825. let copy = UIAction(title: "Copy".localized(), image: UIImage(systemName: "doc.on.doc.fill"), handler: {(_) in
  1826. self.copySession = true
  1827. if self.reffId != nil {
  1828. self.deleteReplyView()
  1829. }
  1830. DispatchQueue.main.asyncAfter(deadline: .now() + 0.35) {
  1831. let cancelButton = UIBarButtonItem(title: "Cancel".localized(), style: .plain, target: self, action: #selector(self.cancelAction))
  1832. self.navigationItem.rightBarButtonItem = cancelButton
  1833. self.changeAppBar()
  1834. let idx = self.dataMessages.firstIndex(where: { $0["message_id"] as! String == dataMessages[indexPath!.row]["message_id"] as! String})
  1835. if idx != nil{
  1836. self.dataMessages[idx!]["isSelected"] = true
  1837. }
  1838. self.addMultipleSelectSession()
  1839. self.tableChatView.reloadData()
  1840. }
  1841. })
  1842. let delete = UIAction(title: "Delete".localized(), image: UIImage(systemName: "trash.fill"), attributes: .destructive, handler: {(_) in
  1843. self.deleteSession = true
  1844. if self.reffId != nil {
  1845. self.deleteReplyView()
  1846. }
  1847. DispatchQueue.main.asyncAfter(deadline: .now() + 0.35) {
  1848. let cancelButton = UIBarButtonItem(title: "Cancel".localized(), style: .plain, target: self, action: #selector(self.cancelAction))
  1849. self.navigationItem.rightBarButtonItem = cancelButton
  1850. self.changeAppBar()
  1851. let idx = self.dataMessages.firstIndex(where: { $0["message_id"] as! String == dataMessages[indexPath!.row]["message_id"] as! String})
  1852. if idx != nil{
  1853. self.dataMessages[idx!]["isSelected"] = true
  1854. }
  1855. self.addMultipleSelectSession()
  1856. self.tableChatView.reloadData()
  1857. }
  1858. })
  1859. var children: [UIMenuElement] = [star, reply, forward, copy, delete]
  1860. // let copyOption = self.copyOption(indexPath: indexPath!)
  1861. if (dataMessages[indexPath!.row]["lock"] != nil && dataMessages[indexPath!.row]["lock"] as! String == "1") {
  1862. children = [delete]
  1863. }
  1864. else if dataMessages[indexPath!.row]["f_pin"] as! String == "-999" {
  1865. children = [star, reply ,delete]
  1866. }
  1867. else if self.removed {
  1868. children = [star, forward, copy ,delete]
  1869. if !(dataMessages[indexPath!.row]["image_id"] as! String).isEmpty || !(dataMessages[indexPath!.row]["video_id"] as! String).isEmpty {
  1870. children = [star, forward ,delete]
  1871. }
  1872. }
  1873. 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" {
  1874. children = [star, reply, forward ,delete]
  1875. }
  1876. return UIContextMenuConfiguration(identifier: nil,
  1877. previewProvider: nil) { _ in
  1878. UIMenu(title: "", children: children)
  1879. }
  1880. }
  1881. @objc func cancelAction() {
  1882. DispatchQueue.main.async {
  1883. if self.copySession {
  1884. self.copySession = false
  1885. } else if self.forwardSession {
  1886. self.forwardSession = false
  1887. } else if self.deleteSession {
  1888. self.deleteSession = false
  1889. }
  1890. let data = self.dataMessages.filter({ $0["isSelected"] as! Bool == true })
  1891. for i in 0..<data.count {
  1892. let idx = self.dataMessages.firstIndex(where: { $0["message_id"] as! String == data[i]["message_id"] as! String})
  1893. if idx != nil{
  1894. self.dataMessages[idx!]["isSelected"] = false
  1895. }
  1896. }
  1897. self.tableChatView.reloadData()
  1898. self.setRightButtonItem()
  1899. self.changeAppBar()
  1900. self.containerMultpileSelectSession.removeFromSuperview()
  1901. self.checkNewMessage(tableView: self.tableChatView)
  1902. }
  1903. }
  1904. private func addMultipleSelectSession() {
  1905. view.addSubview(containerMultpileSelectSession)
  1906. containerMultpileSelectSession.translatesAutoresizingMaskIntoConstraints = false
  1907. NSLayoutConstraint.activate([
  1908. containerMultpileSelectSession.leadingAnchor.constraint(equalTo: self.view.leadingAnchor),
  1909. containerMultpileSelectSession.trailingAnchor.constraint(equalTo: self.view.trailingAnchor),
  1910. containerMultpileSelectSession.bottomAnchor.constraint(equalTo: self.view.bottomAnchor),
  1911. containerMultpileSelectSession.heightAnchor.constraint(equalToConstant: 120)
  1912. ])
  1913. containerMultpileSelectSession.backgroundColor = .white
  1914. addSubviewMultipleSession()
  1915. }
  1916. private func addSubviewMultipleSession() {
  1917. let container = UIView()
  1918. containerMultpileSelectSession.addSubview(container)
  1919. container.translatesAutoresizingMaskIntoConstraints = false
  1920. NSLayoutConstraint.activate([
  1921. container.leadingAnchor.constraint(equalTo: containerMultpileSelectSession.leadingAnchor),
  1922. container.trailingAnchor.constraint(equalTo:containerMultpileSelectSession.trailingAnchor),
  1923. container.bottomAnchor.constraint(equalTo: containerMultpileSelectSession.bottomAnchor),
  1924. container.heightAnchor.constraint(equalToConstant: 50)
  1925. ])
  1926. container.layer.shadowOpacity = 0.7
  1927. container.layer.shadowOffset = CGSize(width: 3, height: 3)
  1928. container.layer.shadowRadius = 3.0
  1929. container.layer.shadowColor = UIColor.black.cgColor
  1930. container.backgroundColor = .secondaryColor
  1931. let title = UILabel()
  1932. container.addSubview(title)
  1933. title.translatesAutoresizingMaskIntoConstraints = false
  1934. NSLayoutConstraint.activate([
  1935. title.centerXAnchor.constraint(equalTo: container.centerXAnchor),
  1936. title.centerYAnchor.constraint(equalTo:container.centerYAnchor),
  1937. ])
  1938. let countSelected = dataMessages.filter({ $0["isSelected"] as! Bool == true }).count
  1939. title.text = "\(countSelected) " + "Selected".localized()
  1940. title.textColor = .mainColor
  1941. title.font = UIFont.systemFont(ofSize: 15).bold
  1942. let button = UIImageView()
  1943. container.addSubview(button)
  1944. button.translatesAutoresizingMaskIntoConstraints = false
  1945. NSLayoutConstraint.activate([
  1946. button.leadingAnchor.constraint(equalTo: container.leadingAnchor, constant: 15),
  1947. button.centerYAnchor.constraint(equalTo:container.centerYAnchor),
  1948. button.widthAnchor.constraint(equalToConstant: 30),
  1949. button.heightAnchor.constraint(equalToConstant: 30),
  1950. ])
  1951. if copySession {
  1952. button.image = UIImage(systemName: "doc.on.doc")
  1953. if countSelected == 0{
  1954. button.tintColor = .gray
  1955. } else {
  1956. button.tintColor = .mainColor
  1957. }
  1958. } else if forwardSession {
  1959. button.image = UIImage(systemName: "arrowshape.turn.up.right")
  1960. if countSelected == 0{
  1961. button.tintColor = .gray
  1962. } else {
  1963. button.tintColor = .mainColor
  1964. }
  1965. } else if deleteSession {
  1966. button.image = UIImage(systemName: "trash")
  1967. if countSelected == 0{
  1968. button.tintColor = .gray
  1969. } else {
  1970. button.tintColor = .red
  1971. }
  1972. }
  1973. let buttonGesture = UITapGestureRecognizer(target: self, action: #selector(sessionAction))
  1974. button.isUserInteractionEnabled = true
  1975. button.addGestureRecognizer(buttonGesture)
  1976. }
  1977. @objc func sessionAction() {
  1978. if copySession {
  1979. let dataMessages = self.dataMessages.filter({ $0["isSelected"] as! Bool == true })
  1980. let countSelected = dataMessages.count
  1981. if countSelected == 0 {
  1982. return
  1983. }
  1984. var nameTopic = "Lounge".localized()
  1985. if !dataTopic.isEmpty {
  1986. nameTopic = dataTopic["title"] as! String
  1987. }
  1988. var text = "*^\(dataGroup["f_name"]!!) (\(nameTopic))^*"
  1989. for i in 0..<countSelected {
  1990. let stringDate = (dataMessages[i]["server_date"] as! String)
  1991. let date = Date(milliseconds: Int64(stringDate)!)
  1992. let formatterDate = DateFormatter()
  1993. let formatterTime = DateFormatter()
  1994. formatterDate.dateFormat = "dd/MM/yy"
  1995. formatterDate.locale = NSLocale(localeIdentifier: "id") as Locale?
  1996. formatterTime.dateFormat = "HH:mm"
  1997. formatterTime.locale = NSLocale(localeIdentifier: "id") as Locale?
  1998. let dataProfile = getDataProfile(f_pin: dataMessages[i]["f_pin"] as! String, message_id: dataMessages[i]["message_id"] as! String)
  1999. 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)"
  2000. }
  2001. text = text + "\n\n\nchat powered by Nexilis"
  2002. DispatchQueue.main.async {
  2003. UIPasteboard.general.string = text
  2004. self.showToast(message: "Text coppied to clipboard".localized(), font: UIFont.systemFont(ofSize: 12, weight: .medium), controller: self)
  2005. }
  2006. cancelAction()
  2007. } else if forwardSession {
  2008. let dataMessages = self.dataMessages.filter({ $0["isSelected"] as! Bool == true })
  2009. let countSelected = dataMessages.count
  2010. if countSelected == 0 {
  2011. return
  2012. }
  2013. let navigationController = AppStoryBoard.Palio.instance.instantiateViewController(withIdentifier: "contactChatNav") as! UINavigationController
  2014. navigationController.modalPresentationStyle = .custom
  2015. if let controller = navigationController.viewControllers.first as? ContactChatViewController {
  2016. controller.isChooser = { [weak self] scope, pin in
  2017. if scope == "3" {
  2018. let editorPersonalVC = AppStoryBoard.Palio.instance.instantiateViewController(identifier: "editorPersonalVC") as! EditorPersonal
  2019. editorPersonalVC.unique_l_pin = pin
  2020. editorPersonalVC.dataMessageForward = dataMessages
  2021. self?.navigationController?.replaceAllViewController(with: editorPersonalVC, animated: true)
  2022. } else {
  2023. let editorGroupVC = AppStoryBoard.Palio.instance.instantiateViewController(identifier: "editorGroupVC") as! EditorGroup
  2024. editorGroupVC.unique_l_pin = pin
  2025. editorGroupVC.dataMessageForward = dataMessages
  2026. self?.navigationController?.replaceAllViewController(with: editorGroupVC, animated: true)
  2027. }
  2028. }
  2029. }
  2030. self.present(navigationController, animated: true, completion: nil)
  2031. } else if deleteSession {
  2032. let dataMessages = self.dataMessages.filter({ $0["isSelected"] as! Bool == true })
  2033. let countSelected = dataMessages.count
  2034. if countSelected == 0 {
  2035. return
  2036. }
  2037. let alertController = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
  2038. if let action = self.actionDelete(for: "me", title: "Delete".localized() + " \(countSelected) " + "For Me".localized(), dataMessages: dataMessages) {
  2039. alertController.addAction(action)
  2040. }
  2041. let idMe = UserDefaults.standard.string(forKey: "me") as String?
  2042. let dataFilterFpin = dataMessages.filter({ $0["f_pin"] as? String != idMe})
  2043. let dataFilterLock = dataMessages.filter({ $0["lock"] as? String == "1"})
  2044. if dataFilterFpin.count == 0 && dataFilterLock.count == 0 {
  2045. if let action = self.actionDelete(for: "everyone", title: "Delete".localized() + " \(countSelected) " + "For Everyone".localized(), dataMessages: dataMessages) {
  2046. alertController.addAction(action)
  2047. }
  2048. }
  2049. alertController.addAction(UIAlertAction(title: "Cancel".localized(), style: .cancel, handler: nil))
  2050. self.present(alertController, animated: true)
  2051. }
  2052. }
  2053. private func deleteMessage(l_pin: String, message_id: String, scope: String, type: String, chat: String) {
  2054. let tmessage = CoreMessage_TMessageBank.deleteMessage(l_pin: l_pin, messageId: message_id, scope: scope, type: type, chat: chat)
  2055. Nexilis.addQueueMessage(message: tmessage)
  2056. }
  2057. private func queryMessageReply(message_id: String) -> [String: Any?] {
  2058. var dataQuery: [String: Any] = [:]
  2059. Database().database?.inTransaction({ fmdb, rollback in
  2060. 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() {
  2061. dataQuery["message_id"] = c.string(forColumnIndex: 0)
  2062. dataQuery["f_pin"] = c.string(forColumnIndex: 1)
  2063. dataQuery["message_text"] = c.string(forColumnIndex: 2)
  2064. dataQuery["attachment_flag"] = c.string(forColumnIndex: 3)
  2065. dataQuery["thumb_id"] = c.string(forColumnIndex: 4)
  2066. dataQuery["image_id"] = c.string(forColumnIndex: 5)
  2067. dataQuery["video_id"] = c.string(forColumnIndex: 6)
  2068. dataQuery["file_id"] = c.string(forColumnIndex: 7)
  2069. c.close()
  2070. }
  2071. })
  2072. return dataQuery
  2073. }
  2074. @objc func segmentedControlValueChanged(_ sender: segmentedControllerObject) {
  2075. switch sender.selectedSegmentIndex {
  2076. case 0:
  2077. sender.navigation.viewControllers[0].children[1].view.isHidden = true
  2078. break;
  2079. case 1:
  2080. sender.navigation.viewControllers[0].children[1].view.isHidden = false
  2081. break;
  2082. default:
  2083. break;
  2084. }
  2085. }
  2086. private func copyOption(indexPath: IndexPath) -> UIMenu {
  2087. var ratingButtonTitles = ["Text".localized(), "Image".localized()]
  2088. if (dataMessages[indexPath.row]["message_text"] as! String).isEmpty {
  2089. ratingButtonTitles = ["Image".localized()]
  2090. }
  2091. let dataMessages = self.dataMessages.filter({ $0["chat_date"] as! String == dataDates[indexPath.section]})
  2092. let copyActions = ratingButtonTitles
  2093. .enumerated()
  2094. .map { index, title in
  2095. return UIAction(
  2096. title: title,
  2097. identifier: nil,
  2098. handler: {(_) in
  2099. if (dataMessages[indexPath.row]["message_text"] as! String).isEmpty {
  2100. DispatchQueue.main.async {
  2101. let nsDocumentDirectory = FileManager.SearchPathDirectory.documentDirectory
  2102. let nsUserDomainMask = FileManager.SearchPathDomainMask.userDomainMask
  2103. let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true)
  2104. if let dirPath = paths.first {
  2105. let imageURL = URL(fileURLWithPath: dirPath).appendingPathComponent(dataMessages[indexPath.row]["image_id"] as! String)
  2106. if FileManager.default.fileExists(atPath: imageURL.path) {
  2107. let image = UIImage(contentsOfFile: imageURL.path)
  2108. UIPasteboard.general.image = image
  2109. self.showToast(message: "Image coppied to clipboard".localized(), font: UIFont.systemFont(ofSize: 12, weight: .medium), controller: self)
  2110. }
  2111. }
  2112. }
  2113. return
  2114. }
  2115. if (index == 0) {
  2116. DispatchQueue.main.async {
  2117. UIPasteboard.general.string = dataMessages[indexPath.row]["message_text"] as? String
  2118. self.showToast(message: "Text coppied to clipboard".localized(), font: UIFont.systemFont(ofSize: 12, weight: .medium), controller: self)
  2119. }
  2120. } else {
  2121. DispatchQueue.main.async {
  2122. let nsDocumentDirectory = FileManager.SearchPathDirectory.documentDirectory
  2123. let nsUserDomainMask = FileManager.SearchPathDomainMask.userDomainMask
  2124. let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true)
  2125. if let dirPath = paths.first {
  2126. let imageURL = URL(fileURLWithPath: dirPath).appendingPathComponent(dataMessages[indexPath.row]["image_id"] as! String)
  2127. if FileManager.default.fileExists(atPath: imageURL.path) {
  2128. let image = UIImage(contentsOfFile: imageURL.path)
  2129. UIPasteboard.general.image = image
  2130. self.showToast(message: "Image coppied to clipboard".localized(), font: UIFont.systemFont(ofSize: 12, weight: .medium), controller: self)
  2131. }
  2132. }
  2133. }
  2134. }
  2135. self.dismissKeyboard()
  2136. })
  2137. }
  2138. return UIMenu(
  2139. title: "Copy".localized(),
  2140. image: UIImage(systemName: "doc.on.doc.fill"),
  2141. children: copyActions)
  2142. }
  2143. private func actionDelete(for type: String, title: String, dataMessages: [[String: Any?]]) -> UIAlertAction? {
  2144. return UIAlertAction(title: title, style: .destructive) { [unowned self] _ in
  2145. for i in 0..<dataMessages.count {
  2146. if (type == "me") {
  2147. 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)
  2148. let idx = self.dataMessages.firstIndex(where: { $0["message_id"] as? String == dataMessages[i]["message_id"] as? String})
  2149. if idx != nil {
  2150. self.dataMessages.remove(at: idx!)
  2151. if (idx == self.dataMessages.count - 1) {
  2152. NotificationCenter.default.post(name: NSNotification.Name(rawValue: "reloadTabChats"), object: nil, userInfo: nil)
  2153. }
  2154. for i in 0..<dataDates.count {
  2155. if self.dataMessages.filter({ $0["chat_date"] as! String == dataDates[i] }).count == 0 {
  2156. dataDates.remove(at: i)
  2157. }
  2158. }
  2159. }
  2160. } else {
  2161. 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)
  2162. let idx = self.dataMessages.firstIndex(where: { $0["message_id"] as! String == dataMessages[i]["message_id"] as! String})
  2163. if idx != nil {
  2164. self.dataMessages[idx!]["lock"] = "1"
  2165. self.dataMessages[idx!]["attachment_flag"] = "0"
  2166. self.dataMessages[idx!]["reff_id"] = ""
  2167. }
  2168. }
  2169. cancelAction()
  2170. }
  2171. }
  2172. }
  2173. @objc func deleteReplyView() {
  2174. if self.containerPreviewReply.isDescendant(of: self.viewTextfield) {
  2175. self.containerPreviewReply.subviews.forEach { $0.removeFromSuperview() }
  2176. self.containerPreviewReply.removeConstraints(self.containerPreviewReply.constraints)
  2177. self.containerPreviewReply.removeFromSuperview()
  2178. self.reffId = nil
  2179. UIView.animate(withDuration: 0.25, delay: 0.0, options: .curveEaseInOut, animations: {
  2180. self.constraintTopTextField.constant = self.constraintTopTextField.constant - 50
  2181. }, completion: nil)
  2182. }
  2183. }
  2184. @objc func deleteLinkPreview() {
  2185. if self.containerLink.isDescendant(of: self.viewTextfield) {
  2186. self.containerLink.subviews.forEach { $0.removeFromSuperview() }
  2187. self.containerLink.removeConstraints(self.containerLink.constraints)
  2188. self.containerLink.removeFromSuperview()
  2189. UIView.animate(withDuration: 0.25, delay: 0.0, options: .curveEaseInOut, animations: {
  2190. self.constraintTopTextField.constant = self.constraintTopTextField.constant - 80
  2191. }, completion: nil)
  2192. }
  2193. if self.reffId != nil {
  2194. self.bottomAnchorPreviewReply.isActive = false
  2195. self.bottomAnchorPreviewReply = self.containerPreviewReply.bottomAnchor.constraint(equalTo: self.textFieldSend.topAnchor)
  2196. self.bottomAnchorPreviewReply.isActive = true
  2197. }
  2198. }
  2199. }
  2200. extension EditorGroup: UICollectionViewDelegate, UICollectionViewDataSource {
  2201. public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
  2202. return 76
  2203. }
  2204. public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
  2205. let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cellSticker", for: indexPath)
  2206. if (cell.contentView.subviews.count > 0) {
  2207. cell.contentView.subviews[0].removeFromSuperview()
  2208. }
  2209. let imageSticker = UIImageView()
  2210. cell.contentView.addSubview(imageSticker)
  2211. imageSticker.translatesAutoresizingMaskIntoConstraints = false
  2212. NSLayoutConstraint.activate([
  2213. imageSticker.topAnchor.constraint(equalTo: cell.contentView.topAnchor),
  2214. imageSticker.bottomAnchor.constraint(equalTo: cell.contentView.bottomAnchor),
  2215. imageSticker.leadingAnchor.constraint(equalTo: cell.contentView.leadingAnchor),
  2216. imageSticker.trailingAnchor.constraint(equalTo: cell.contentView.trailingAnchor)
  2217. ])
  2218. imageSticker.image = UIImage(named: stickers[indexPath.row], in: Bundle.resourceBundle(for: Nexilis.self), with: nil)
  2219. return cell
  2220. }
  2221. public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
  2222. sendChat(message_text: "sticker/\(stickers[indexPath.row])", attachment_flag: "11", viewController: self)
  2223. constraintBottomAttachment.constant = 0.0
  2224. self.viewSticker.removeConstraints(self.viewSticker.constraints)
  2225. self.viewSticker.removeFromSuperview()
  2226. }
  2227. public func numberOfPreviewItems(in controller: QLPreviewController) -> Int {
  2228. 1
  2229. }
  2230. public func previewController(_ controller: QLPreviewController, previewItemAt index: Int) -> QLPreviewItem {
  2231. return self.previewItem!
  2232. }
  2233. }
  2234. extension EditorGroup: UITableViewDelegate, UITableViewDataSource {
  2235. // public func tableView(_ tableView: UITableView, didEndDisplaying cell: UITableViewCell, forRowAt indexPath: IndexPath) {
  2236. // checkNewMessage(tableView: tableView)
  2237. // }
  2238. public func scrollViewDidScroll(_ scrollView: UIScrollView) {
  2239. checkNewMessage(tableView: self.tableChatView)
  2240. }
  2241. public func numberOfSections(in tableView: UITableView) -> Int {
  2242. dataDates.count
  2243. }
  2244. public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
  2245. let count = dataMessages.filter({ $0["chat_date"] as! String == dataDates[section] }).count
  2246. return count
  2247. }
  2248. public func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
  2249. let containerView = UIView()
  2250. containerView.backgroundColor = .clear
  2251. let dateView = UIView()
  2252. containerView.addSubview(dateView)
  2253. dateView.translatesAutoresizingMaskIntoConstraints = false
  2254. var topAnchor = dateView.topAnchor.constraint(equalTo: containerView.topAnchor)
  2255. if section == 0 {
  2256. topAnchor = dateView.topAnchor.constraint(equalTo: containerView.topAnchor, constant: 10.0)
  2257. }
  2258. NSLayoutConstraint.activate([
  2259. topAnchor,
  2260. dateView.bottomAnchor.constraint(equalTo: containerView.bottomAnchor),
  2261. dateView.centerXAnchor.constraint(equalTo: containerView.centerXAnchor),
  2262. dateView.heightAnchor.constraint(equalToConstant: 30),
  2263. dateView.widthAnchor.constraint(greaterThanOrEqualToConstant: 60)
  2264. ])
  2265. dateView.backgroundColor = .orangeColor
  2266. dateView.layer.cornerRadius = 15.0
  2267. dateView.clipsToBounds = true
  2268. let labelDate = UILabel()
  2269. dateView.addSubview(labelDate)
  2270. labelDate.translatesAutoresizingMaskIntoConstraints = false
  2271. NSLayoutConstraint.activate([
  2272. labelDate.centerYAnchor.constraint(equalTo: dateView.centerYAnchor),
  2273. labelDate.centerXAnchor.constraint(equalTo: dateView.centerXAnchor),
  2274. labelDate.leadingAnchor.constraint(equalTo: dateView.leadingAnchor, constant: 10),
  2275. labelDate.trailingAnchor.constraint(equalTo: dateView.trailingAnchor, constant: -10),
  2276. ])
  2277. labelDate.textAlignment = .center
  2278. labelDate.textColor = .secondaryColor
  2279. labelDate.font = UIFont.systemFont(ofSize: 12, weight: .medium)
  2280. labelDate.text = dataDates[section]
  2281. return containerView
  2282. }
  2283. public func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
  2284. if section == 0 {
  2285. return 40
  2286. }
  2287. return 30
  2288. }
  2289. public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
  2290. let dataMessages = self.dataMessages.filter({ $0["chat_date"] as! String == dataDates[indexPath.section] })
  2291. if copySession || forwardSession || deleteSession {
  2292. if copySession && dataMessages[indexPath.row]["f_pin"] as! String != "-999" {
  2293. return
  2294. }
  2295. if (dataMessages[indexPath.row]["attachment_flag"] as! String != "0" || dataMessages[indexPath.row]["lock"] as? String == "1") && !forwardSession && !deleteSession {
  2296. return
  2297. }
  2298. let idx = self.dataMessages.firstIndex(where: { $0["message_id"] as! String == dataMessages[indexPath.row]["message_id"] as! String})
  2299. if idx != nil {
  2300. self.dataMessages[idx!]["isSelected"] = !(self.dataMessages[idx!]["isSelected"] as! Bool)
  2301. self.tableChatView.reloadRows(at: [indexPath], with: .none)
  2302. }
  2303. containerMultpileSelectSession.subviews.forEach({ $0.removeFromSuperview() })
  2304. addSubviewMultipleSession()
  2305. return
  2306. }
  2307. 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 {
  2308. var file = dataMessages[indexPath.row]["image_id"] as! String
  2309. if file.isEmpty {
  2310. file = dataMessages[indexPath.row]["video_id"] as! String
  2311. if file.isEmpty {
  2312. file = dataMessages[indexPath.row]["file_id"] as! String
  2313. }
  2314. }
  2315. let nsDocumentDirectory = FileManager.SearchPathDirectory.documentDirectory
  2316. let nsUserDomainMask = FileManager.SearchPathDomainMask.userDomainMask
  2317. let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true)
  2318. if let dirPath = paths.first {
  2319. let fileURL = URL(fileURLWithPath: dirPath).appendingPathComponent(file)
  2320. if !FileManager.default.fileExists(atPath: fileURL.path) {
  2321. return
  2322. }
  2323. }
  2324. }
  2325. let message = dataMessages[indexPath.row]
  2326. if let attachmentFlag = message["attachment_flag"], let attachmentFlag = attachmentFlag as? String {
  2327. if attachmentFlag == "27" {
  2328. let streamingController = QmeraCreateStreamingViewController()
  2329. streamingController.isJoin = true
  2330. if let messageText = message["message_text"],
  2331. let messageText = messageText as? String,
  2332. var json = try! JSONSerialization.jsonObject(with: messageText.data(using: String.Encoding.utf8)!, options: []) as? [String: Any] {
  2333. if json["blog"] == nil {
  2334. json["blog"] = message["blog_id"] ?? nil
  2335. }
  2336. streamingController.data = json
  2337. }
  2338. let streamingNav = UINavigationController(rootViewController: streamingController)
  2339. streamingNav.modalPresentationStyle = .custom
  2340. streamingNav.navigationBar.barTintColor = .mainColor
  2341. streamingNav.navigationBar.tintColor = .white
  2342. let textAttributes = [NSAttributedString.Key.foregroundColor:UIColor.white]
  2343. streamingNav.navigationBar.titleTextAttributes = textAttributes
  2344. streamingNav.navigationBar.isTranslucent = false
  2345. navigationController?.present(streamingNav, animated: true, completion: nil)
  2346. }
  2347. }
  2348. }
  2349. public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
  2350. let idMe = UserDefaults.standard.string(forKey: "me") as String?
  2351. let dataMessages = dataMessages.filter({$0["chat_date"] as! String == dataDates[indexPath.section]})
  2352. let cellMessage = UITableViewCell()
  2353. cellMessage.backgroundColor = .clear
  2354. cellMessage.selectionStyle = .none
  2355. let profileMessage = UIImageView()
  2356. profileMessage.frame.size = CGSize(width: 35, height: 35)
  2357. cellMessage.contentView.addSubview(profileMessage)
  2358. profileMessage.translatesAutoresizingMaskIntoConstraints = false
  2359. let tapGestureRecognizer = ObjectGesture(target: self, action: #selector(profilePersonTapped(_:)))
  2360. tapGestureRecognizer.message_id = dataMessages[indexPath.row]["f_pin"] as! String
  2361. profileMessage.isUserInteractionEnabled = true
  2362. profileMessage.addGestureRecognizer(tapGestureRecognizer)
  2363. let containerMessage = UIView()
  2364. if !copySession && !forwardSession && !deleteSession && !isHistoryCC {
  2365. let interaction = UIContextMenuInteraction(delegate: self)
  2366. containerMessage.addInteraction(interaction)
  2367. containerMessage.isUserInteractionEnabled = true
  2368. }
  2369. let thumbChat = dataMessages[indexPath.row]["thumb_id"] as! String
  2370. let imageChat = dataMessages[indexPath.row]["image_id"] as! String
  2371. let videoChat = dataMessages[indexPath.row]["video_id"] as! String
  2372. let fileChat = dataMessages[indexPath.row]["file_id"] as! String
  2373. let reffChat = dataMessages[indexPath.row]["reff_id"] as! String
  2374. cellMessage.contentView.addSubview(containerMessage)
  2375. containerMessage.translatesAutoresizingMaskIntoConstraints = false
  2376. let timeMessage = UILabel()
  2377. cellMessage.contentView.addSubview(timeMessage)
  2378. timeMessage.translatesAutoresizingMaskIntoConstraints = false
  2379. timeMessage.bottomAnchor.constraint(equalTo: cellMessage.contentView.bottomAnchor, constant: -5).isActive = true
  2380. let messageText = UILabel()
  2381. containerMessage.addSubview(messageText)
  2382. messageText.translatesAutoresizingMaskIntoConstraints = false
  2383. let topMarginText = messageText.topAnchor.constraint(equalTo: containerMessage.topAnchor, constant: 32)
  2384. let dataProfile = getDataProfile(f_pin: dataMessages[indexPath.row]["f_pin"] as! String, message_id: dataMessages[indexPath.row]["message_id"] as! String)
  2385. let statusMessage = UIImageView()
  2386. if (dataMessages[indexPath.row]["attachment_flag"] as? String == "0" && dataMessages[indexPath.row]["lock"] as? String != "1") || forwardSession || deleteSession {
  2387. var showSelectedImage = true
  2388. if (!imageChat.isEmpty || !videoChat.isEmpty || !fileChat.isEmpty) && forwardSession {
  2389. var file = dataMessages[indexPath.row]["image_id"] as! String
  2390. if file.isEmpty {
  2391. file = dataMessages[indexPath.row]["video_id"] as! String
  2392. if file.isEmpty {
  2393. file = dataMessages[indexPath.row]["file_id"] as! String
  2394. }
  2395. }
  2396. let nsDocumentDirectory = FileManager.SearchPathDirectory.documentDirectory
  2397. let nsUserDomainMask = FileManager.SearchPathDomainMask.userDomainMask
  2398. let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true)
  2399. if let dirPath = paths.first {
  2400. let fileURL = URL(fileURLWithPath: dirPath).appendingPathComponent(file)
  2401. if !FileManager.default.fileExists(atPath: fileURL.path) {
  2402. showSelectedImage = false
  2403. }
  2404. }
  2405. }
  2406. if dataMessages[indexPath.row]["f_pin"] as! String == "-999" && !deleteSession {
  2407. showSelectedImage = false
  2408. }
  2409. if showSelectedImage {
  2410. let selectedImage = UIImageView()
  2411. cellMessage.contentView.addSubview(selectedImage)
  2412. selectedImage.translatesAutoresizingMaskIntoConstraints = false
  2413. selectedImage.frame.size = CGSize(width: 20, height: 20)
  2414. var leading = selectedImage.leadingAnchor.constraint(equalTo: cellMessage.contentView.leadingAnchor, constant: -20)
  2415. if copySession || forwardSession || deleteSession {
  2416. leading = selectedImage.leadingAnchor.constraint(equalTo: cellMessage.contentView.leadingAnchor, constant: 15)
  2417. }
  2418. NSLayoutConstraint.activate([
  2419. leading,
  2420. selectedImage.centerYAnchor.constraint(equalTo: cellMessage.contentView.centerYAnchor),
  2421. selectedImage.widthAnchor.constraint(equalToConstant: 20),
  2422. selectedImage.heightAnchor.constraint(equalToConstant: 20)
  2423. ])
  2424. selectedImage.circle()
  2425. selectedImage.layer.borderWidth = 2
  2426. selectedImage.layer.borderColor = UIColor.mainColor.cgColor
  2427. if dataMessages[indexPath.row]["isSelected"] as! Bool {
  2428. selectedImage.image = UIImage(systemName: "checkmark.circle.fill")
  2429. }
  2430. selectedImage.tintColor = .mainColor
  2431. }
  2432. }
  2433. if (dataMessages[indexPath.row]["f_pin"] as? String == idMe) {
  2434. profileMessage.topAnchor.constraint(equalTo: cellMessage.contentView.topAnchor, constant: 5).isActive = true
  2435. profileMessage.trailingAnchor.constraint(equalTo: cellMessage.contentView.trailingAnchor, constant: -15).isActive = true
  2436. profileMessage.heightAnchor.constraint(equalToConstant: 37).isActive = true
  2437. profileMessage.widthAnchor.constraint(equalToConstant: 35).isActive = true
  2438. profileMessage.circle()
  2439. profileMessage.clipsToBounds = true
  2440. profileMessage.backgroundColor = .lightGray
  2441. profileMessage.image = UIImage(systemName: "person")
  2442. profileMessage.tintColor = .white
  2443. profileMessage.contentMode = .scaleAspectFit
  2444. let pictureImage = dataProfile["image_id"]
  2445. if (pictureImage != "" && pictureImage != nil) {
  2446. profileMessage.setImage(name: pictureImage!)
  2447. profileMessage.contentMode = .scaleAspectFill
  2448. }
  2449. containerMessage.topAnchor.constraint(equalTo: cellMessage.contentView.topAnchor, constant: 5).isActive = true
  2450. containerMessage.leadingAnchor.constraint(greaterThanOrEqualTo: cellMessage.contentView.leadingAnchor, constant: 60).isActive = true
  2451. containerMessage.bottomAnchor.constraint(equalTo: cellMessage.contentView.bottomAnchor, constant: -5).isActive = true
  2452. containerMessage.trailingAnchor.constraint(equalTo: profileMessage.leadingAnchor, constant: -5).isActive = true
  2453. containerMessage.widthAnchor.constraint(greaterThanOrEqualToConstant: 46).isActive = true
  2454. containerMessage.layer.cornerRadius = 10.0
  2455. containerMessage.layer.maskedCorners = [.layerMinXMaxYCorner, .layerMaxXMaxYCorner, .layerMinXMinYCorner]
  2456. containerMessage.clipsToBounds = true
  2457. timeMessage.trailingAnchor.constraint(equalTo: containerMessage.leadingAnchor, constant: -8).isActive = true
  2458. if dataMessages[indexPath.row]["lock"] == nil || dataMessages[indexPath.row]["lock"] as! String == "0" {
  2459. cellMessage.contentView.addSubview(statusMessage)
  2460. statusMessage.translatesAutoresizingMaskIntoConstraints = false
  2461. statusMessage.bottomAnchor.constraint(equalTo: timeMessage.topAnchor).isActive = true
  2462. statusMessage.trailingAnchor.constraint(equalTo: containerMessage.leadingAnchor, constant: -8).isActive = true
  2463. statusMessage.widthAnchor.constraint(equalToConstant: 15).isActive = true
  2464. statusMessage.heightAnchor.constraint(equalToConstant: 15).isActive = true
  2465. if (dataMessages[indexPath.row]["status"]! as! String == "1" || dataMessages[indexPath.row]["status"]! as! String == "2" ) {
  2466. statusMessage.image = UIImage(named: "checklist", in: Bundle.resourceBundle(for: Nexilis.self), with: nil)!.withTintColor(UIColor.lightGray)
  2467. } else if (dataMessages[indexPath.row]["status"]! as! String == "3") {
  2468. statusMessage.image = UIImage(named: "double-checklist", in: Bundle.resourceBundle(for: Nexilis.self), with: nil)!.withTintColor(UIColor.lightGray)
  2469. } else {
  2470. statusMessage.image = UIImage(named: "double-checklist", in: Bundle.resourceBundle(for: Nexilis.self), with: nil)!.withTintColor(UIColor.systemBlue)
  2471. }
  2472. }
  2473. let nameSender = UILabel()
  2474. containerMessage.addSubview(nameSender)
  2475. nameSender.translatesAutoresizingMaskIntoConstraints = false
  2476. nameSender.topAnchor.constraint(equalTo: containerMessage.topAnchor, constant: 15).isActive = true
  2477. nameSender.leadingAnchor.constraint(equalTo: containerMessage.leadingAnchor, constant: 15).isActive = true
  2478. nameSender.trailingAnchor.constraint(equalTo: containerMessage.trailingAnchor, constant: -15).isActive = true
  2479. nameSender.font = UIFont.systemFont(ofSize: 12).bold
  2480. nameSender.text = dataProfile["name"]
  2481. nameSender.textAlignment = .right
  2482. if (dataMessages[indexPath.row]["attachment_flag"] as? String == "11" && dataMessages[indexPath.row]["reff_id"]as? String == "") {
  2483. containerMessage.backgroundColor = .clear
  2484. nameSender.textColor = .mainColor
  2485. } else {
  2486. containerMessage.backgroundColor = .blueBubbleColor
  2487. nameSender.textColor = .mainColor
  2488. }
  2489. } else {
  2490. if copySession || forwardSession || deleteSession {
  2491. profileMessage.leadingAnchor.constraint(equalTo: cellMessage.contentView.leadingAnchor, constant: 50).isActive = true
  2492. } else {
  2493. profileMessage.leadingAnchor.constraint(equalTo: cellMessage.contentView.leadingAnchor, constant: 15).isActive = true
  2494. }
  2495. profileMessage.heightAnchor.constraint(equalToConstant: 37).isActive = true
  2496. profileMessage.widthAnchor.constraint(equalToConstant: 35).isActive = true
  2497. profileMessage.circle()
  2498. profileMessage.clipsToBounds = true
  2499. profileMessage.backgroundColor = .lightGray
  2500. profileMessage.image = UIImage(systemName: "person")
  2501. profileMessage.tintColor = .white
  2502. profileMessage.contentMode = .scaleAspectFit
  2503. let pictureImage = dataProfile["image_id"]
  2504. if dataMessages[indexPath.row]["f_pin"] as? String == "-999" {
  2505. profileMessage.image = UIImage(named: "pb_ball", in: Bundle.resourceBundle(for: Nexilis.self), with: nil)
  2506. profileMessage.contentMode = .scaleAspectFill
  2507. }
  2508. else if (pictureImage != "" && pictureImage != nil) {
  2509. profileMessage.setImage(name: pictureImage!)
  2510. profileMessage.contentMode = .scaleAspectFill
  2511. }
  2512. if markerCounter != nil && dataMessages[indexPath.row]["message_id"] as? String == markerCounter {
  2513. profileMessage.topAnchor.constraint(equalTo: cellMessage.contentView.topAnchor, constant: 35).isActive = true
  2514. containerMessage.topAnchor.constraint(equalTo: cellMessage.contentView.topAnchor, constant: 35).isActive = true
  2515. let newMessagesView = UIView()
  2516. cellMessage.contentView.addSubview(newMessagesView)
  2517. newMessagesView.translatesAutoresizingMaskIntoConstraints = false
  2518. NSLayoutConstraint.activate([
  2519. newMessagesView.topAnchor.constraint(equalTo: newMessagesView.topAnchor),
  2520. newMessagesView.bottomAnchor.constraint(equalTo: containerMessage.topAnchor),
  2521. newMessagesView.centerXAnchor.constraint(equalTo: cellMessage.contentView.centerXAnchor),
  2522. newMessagesView.heightAnchor.constraint(equalToConstant: 30),
  2523. newMessagesView.widthAnchor.constraint(greaterThanOrEqualToConstant: 60)
  2524. ])
  2525. newMessagesView.backgroundColor = .greenColor
  2526. newMessagesView.layer.cornerRadius = 15.0
  2527. newMessagesView.clipsToBounds = true
  2528. let labelNewMessages = UILabel()
  2529. newMessagesView.addSubview(labelNewMessages)
  2530. labelNewMessages.translatesAutoresizingMaskIntoConstraints = false
  2531. NSLayoutConstraint.activate([
  2532. labelNewMessages.centerYAnchor.constraint(equalTo: newMessagesView.centerYAnchor),
  2533. labelNewMessages.centerXAnchor.constraint(equalTo: newMessagesView.centerXAnchor),
  2534. labelNewMessages.leadingAnchor.constraint(equalTo: newMessagesView.leadingAnchor, constant: 10),
  2535. labelNewMessages.trailingAnchor.constraint(equalTo: newMessagesView.trailingAnchor, constant: -10),
  2536. ])
  2537. labelNewMessages.textAlignment = .center
  2538. labelNewMessages.textColor = .secondaryColor
  2539. labelNewMessages.font = UIFont.systemFont(ofSize: 12, weight: .medium)
  2540. labelNewMessages.text = "Unread Messages".localized()
  2541. } else {
  2542. profileMessage.topAnchor.constraint(equalTo: cellMessage.contentView.topAnchor, constant: 5).isActive = true
  2543. containerMessage.topAnchor.constraint(equalTo: cellMessage.contentView.topAnchor, constant: 5).isActive = true
  2544. }
  2545. containerMessage.leadingAnchor.constraint(equalTo: profileMessage.trailingAnchor, constant: 5).isActive = true
  2546. containerMessage.bottomAnchor.constraint(equalTo: cellMessage.contentView.bottomAnchor, constant: -5).isActive = true
  2547. containerMessage.trailingAnchor.constraint(lessThanOrEqualTo: cellMessage.contentView.trailingAnchor, constant: -60).isActive = true
  2548. containerMessage.widthAnchor.constraint(greaterThanOrEqualToConstant: 46).isActive = true
  2549. 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") {
  2550. containerMessage.backgroundColor = .clear
  2551. } else {
  2552. containerMessage.backgroundColor = .grayColor
  2553. }
  2554. containerMessage.layer.cornerRadius = 10.0
  2555. containerMessage.layer.maskedCorners = [.layerMinXMaxYCorner, .layerMaxXMinYCorner, .layerMaxXMaxYCorner]
  2556. containerMessage.clipsToBounds = true
  2557. timeMessage.leadingAnchor.constraint(equalTo: containerMessage.trailingAnchor, constant: 8).isActive = true
  2558. let nameSender = UILabel()
  2559. containerMessage.addSubview(nameSender)
  2560. nameSender.translatesAutoresizingMaskIntoConstraints = false
  2561. nameSender.topAnchor.constraint(equalTo: containerMessage.topAnchor, constant: 15).isActive = true
  2562. nameSender.leadingAnchor.constraint(equalTo: containerMessage.leadingAnchor, constant: 15).isActive = true
  2563. nameSender.trailingAnchor.constraint(equalTo: containerMessage.trailingAnchor, constant: -15).isActive = true
  2564. nameSender.font = UIFont.systemFont(ofSize: 12).bold
  2565. if dataMessages[indexPath.row]["f_pin"] as? String == "-999" {
  2566. nameSender.text = "Bot"
  2567. }
  2568. else {
  2569. nameSender.text = dataProfile["name"]
  2570. }
  2571. nameSender.textAlignment = .left
  2572. nameSender.textColor = .mainColor
  2573. }
  2574. if dataMessages[indexPath.row]["is_stared"] as? String == "1" && (dataMessages[indexPath.row]["lock"] == nil || dataMessages[indexPath.row]["lock"] as! String == "0") {
  2575. let imageStared = UIImageView()
  2576. cellMessage.contentView.addSubview(imageStared)
  2577. imageStared.translatesAutoresizingMaskIntoConstraints = false
  2578. if (dataMessages[indexPath.row]["f_pin"] as? String == idMe) {
  2579. imageStared.bottomAnchor.constraint(equalTo: statusMessage.topAnchor).isActive = true
  2580. imageStared.trailingAnchor.constraint(equalTo: containerMessage.leadingAnchor, constant: -8).isActive = true
  2581. } else {
  2582. imageStared.bottomAnchor.constraint(equalTo: timeMessage.topAnchor).isActive = true
  2583. imageStared.leadingAnchor.constraint(equalTo: containerMessage.trailingAnchor, constant: 8).isActive = true
  2584. }
  2585. imageStared.widthAnchor.constraint(equalToConstant: 15).isActive = true
  2586. imageStared.heightAnchor.constraint(equalToConstant: 15).isActive = true
  2587. imageStared.image = UIImage(systemName: "star.fill")
  2588. imageStared.backgroundColor = .clear
  2589. imageStared.tintColor = .systemYellow
  2590. }
  2591. messageText.numberOfLines = 0
  2592. messageText.lineBreakMode = .byWordWrapping
  2593. containerMessage.addSubview(messageText)
  2594. topMarginText.isActive = true
  2595. if dataMessages[indexPath.row]["attachment_flag"] as! String == "27" || dataMessages[indexPath.row]["attachment_flag"] as! String == "26" {
  2596. messageText.leadingAnchor.constraint(equalTo: containerMessage.leadingAnchor, constant: 85).isActive = true
  2597. let imageLS = UIImageView()
  2598. containerMessage.addSubview(imageLS)
  2599. imageLS.translatesAutoresizingMaskIntoConstraints = false
  2600. NSLayoutConstraint.activate([
  2601. imageLS.leadingAnchor.constraint(equalTo: containerMessage.leadingAnchor, constant: 15.0),
  2602. imageLS.trailingAnchor.constraint(equalTo: messageText.leadingAnchor, constant: -10.0),
  2603. imageLS.centerYAnchor.constraint(equalTo: containerMessage.centerYAnchor),
  2604. imageLS.heightAnchor.constraint(equalToConstant: 60.0)
  2605. ])
  2606. if dataMessages[indexPath.row]["attachment_flag"] as! String == "26" {
  2607. imageLS.image = UIImage(named: "pb_seminar_wpr", in: Bundle.resourceBundle(for: Nexilis.self), with: nil)
  2608. } else if dataMessages[indexPath.row]["attachment_flag"] as! String == "27" {
  2609. imageLS.image = UIImage(named: "pb_live_tv", in: Bundle.resourceBundle(for: Nexilis.self), with: nil)
  2610. }
  2611. } else {
  2612. messageText.leadingAnchor.constraint(equalTo: containerMessage.leadingAnchor, constant: 15).isActive = true
  2613. }
  2614. messageText.bottomAnchor.constraint(equalTo: containerMessage.bottomAnchor, constant: -15).isActive = true
  2615. messageText.trailingAnchor.constraint(equalTo: containerMessage.trailingAnchor, constant: -15).isActive = true
  2616. if (dataMessages[indexPath.row]["f_pin"] as? String == idMe) {
  2617. messageText.textColor = .black
  2618. } else {
  2619. messageText.textColor = .black
  2620. }
  2621. var textChat = (dataMessages[indexPath.row]["message_text"])! as? String
  2622. if (dataMessages[indexPath.row]["lock"] != nil && (dataMessages[indexPath.row]["lock"])! as? String == "1") {
  2623. if (dataMessages[indexPath.row]["f_pin"] as? String == idMe) {
  2624. textChat = "🚫 _You were deleted this message_"
  2625. } else {
  2626. textChat = "🚫 _This message was deleted_"
  2627. }
  2628. }
  2629. let imageSticker = UIImageView()
  2630. if let attachmentFlag = dataMessages[indexPath.row]["attachment_flag"], let attachmentFlag = attachmentFlag as? String {
  2631. if attachmentFlag == "27" || attachmentFlag == "26", let data = textChat { // live streaming
  2632. if let json = try! JSONSerialization.jsonObject(with: data.data(using: String.Encoding.utf8)!, options: []) as? [String: Any] {
  2633. Database().database?.inTransaction({ fmdb, rollback in
  2634. let title = json["title"] as! String
  2635. let description = json["description"] as! String
  2636. let start = json["time"] as! Int64
  2637. let by = json["by"] as! String
  2638. var type = "*Live Streaming*"
  2639. if attachmentFlag == "26" {
  2640. type = "*Seminar*"
  2641. }
  2642. if let c = Database().getRecords(fmdb: fmdb, query: "select first_name || ' ' || last_name from BUDDY where f_pin = '\(by)'"), c.next() {
  2643. let name = c.string(forColumnIndex: 0)!
  2644. messageText.attributedText = "\(type) \nTitle: \(title) \nDescription: \(description) \nStart: \(Date(milliseconds: start).format(dateFormat: "dd/MM/yyyy HH:mm")) \nBroadcaster: \(name)".richText()
  2645. c.close()
  2646. } else {
  2647. messageText.attributedText = ("\(type) \nTitle: \(title) \nDescription: \(description) \nStart: \(Date(milliseconds: start).format(dateFormat: "dd/MM/yyyy HH:mm")) \nBroadcaster: " + "Unknown".localized()).richText()
  2648. }
  2649. })
  2650. }
  2651. }
  2652. else if attachmentFlag == "11" && (dataMessages[indexPath.row]["lock"] == nil || dataMessages[indexPath.row]["lock"] as! String != "1") {
  2653. messageText.text = ""
  2654. topMarginText.constant = topMarginText.constant + 100
  2655. containerMessage.addSubview(imageSticker)
  2656. imageSticker.translatesAutoresizingMaskIntoConstraints = false
  2657. if (reffChat == "") {
  2658. imageSticker.topAnchor.constraint(equalTo: containerMessage.topAnchor, constant: 32).isActive = true
  2659. imageSticker.widthAnchor.constraint(equalToConstant: 80).isActive = true
  2660. } else {
  2661. imageSticker.widthAnchor.constraint(greaterThanOrEqualToConstant: 80).isActive = true
  2662. }
  2663. imageSticker.leadingAnchor.constraint(equalTo: containerMessage.leadingAnchor, constant: 15).isActive = true
  2664. imageSticker.bottomAnchor.constraint(equalTo: messageText.topAnchor, constant: -5).isActive = true
  2665. imageSticker.trailingAnchor.constraint(equalTo: containerMessage.trailingAnchor, constant: -15).isActive = true
  2666. imageSticker.image = UIImage(named: (textChat?.components(separatedBy: "/")[1])!, in: Bundle.resourceBundle(for: Nexilis.self), with: nil)
  2667. imageSticker.contentMode = .scaleAspectFit
  2668. }
  2669. else {
  2670. messageText.attributedText = textChat!.richText()
  2671. }
  2672. } else {
  2673. messageText.attributedText = textChat!.richText()
  2674. }
  2675. messageText.isUserInteractionEnabled = true
  2676. if !textChat!.isEmpty {
  2677. let listText = textChat!.split(separator: " ")
  2678. for i in 0...listText.count - 1 {
  2679. if listText[i].lowercased().checkStartWithLink() {
  2680. if ((listText[i].lowercased().starts(with: "www.") && listText[i].lowercased().split(separator: ".").count >= 3) || (!listText[i].lowercased().starts(with: "www.") && listText[i].lowercased().split(separator: ".").count >= 2)) && listText[i].lowercased().split(separator: ".").last!.count >= 2 {
  2681. let objectGesture = ObjectGesture(target: self, action: #selector(tapMessageText(_:)))
  2682. objectGesture.message_id = "\(listText[i])"
  2683. messageText.addGestureRecognizer(objectGesture)
  2684. }
  2685. }
  2686. }
  2687. }
  2688. let stringDate = (dataMessages[indexPath.row]["server_date"] as! String)
  2689. let date = Date(milliseconds: Int64(stringDate)!)
  2690. let formatter = DateFormatter()
  2691. formatter.dateFormat = "HH:mm"
  2692. formatter.locale = NSLocale(localeIdentifier: "id") as Locale?
  2693. timeMessage.text = formatter.string(from: date as Date)
  2694. timeMessage.font = UIFont.systemFont(ofSize: 10, weight: .medium)
  2695. timeMessage.textColor = .lightGray
  2696. let imageThumb = UIImageView()
  2697. let containerViewFile = UIView()
  2698. if (thumbChat != "" && (dataMessages[indexPath.row]["lock"] == nil || dataMessages[indexPath.row]["lock"] as! String != "1")) {
  2699. topMarginText.constant = topMarginText.constant + 205
  2700. containerMessage.addSubview(imageThumb)
  2701. imageThumb.translatesAutoresizingMaskIntoConstraints = false
  2702. let data = queryMessageReply(message_id: reffChat)
  2703. if (data.count == 0) {
  2704. imageThumb.topAnchor.constraint(equalTo: containerMessage.topAnchor, constant: 32).isActive = true
  2705. }
  2706. imageThumb.leadingAnchor.constraint(equalTo: containerMessage.leadingAnchor, constant: 15).isActive = true
  2707. imageThumb.bottomAnchor.constraint(equalTo: messageText.topAnchor, constant: -5).isActive = true
  2708. imageThumb.trailingAnchor.constraint(equalTo: containerMessage.trailingAnchor, constant: -15).isActive = true
  2709. imageThumb.widthAnchor.constraint(equalToConstant: self.view.frame.size.width * 0.6).isActive = true
  2710. imageThumb.layer.cornerRadius = 5.0
  2711. imageThumb.clipsToBounds = true
  2712. imageThumb.contentMode = .scaleAspectFill
  2713. let nsDocumentDirectory = FileManager.SearchPathDirectory.documentDirectory
  2714. let nsUserDomainMask = FileManager.SearchPathDomainMask.userDomainMask
  2715. let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true)
  2716. if let dirPath = paths.first {
  2717. let thumbURL = URL(fileURLWithPath: dirPath).appendingPathComponent(thumbChat)
  2718. let image = UIImage(contentsOfFile: thumbURL.path)
  2719. imageThumb.image = image
  2720. let videoURL = URL(fileURLWithPath: dirPath).appendingPathComponent(videoChat)
  2721. let imageURL = URL(fileURLWithPath: dirPath).appendingPathComponent(imageChat)
  2722. if !FileManager.default.fileExists(atPath: imageURL.path) || !FileManager.default.fileExists(atPath: videoURL.path){
  2723. let blurEffect = UIBlurEffect(style: UIBlurEffect.Style.light)
  2724. let blurEffectView = UIVisualEffectView(effect: blurEffect)
  2725. blurEffectView.frame = CGRect(x: 0, y: 0, width: imageThumb.frame.size.width, height: imageThumb.frame.size.height)
  2726. blurEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
  2727. imageThumb.addSubview(blurEffectView)
  2728. if !imageChat.isEmpty {
  2729. let imageDownload = UIImageView(image: UIImage(systemName: "arrow.down.circle.fill", withConfiguration: UIImage.SymbolConfiguration(pointSize: 50, weight: .bold, scale: .default)))
  2730. imageThumb.addSubview(blurEffectView)
  2731. imageThumb.addSubview(imageDownload)
  2732. imageDownload.tintColor = .black.withAlphaComponent(0.3)
  2733. imageDownload.translatesAutoresizingMaskIntoConstraints = false
  2734. imageDownload.centerXAnchor.constraint(equalTo: imageThumb.centerXAnchor).isActive = true
  2735. imageDownload.centerYAnchor.constraint(equalTo: imageThumb.centerYAnchor).isActive = true
  2736. }
  2737. }
  2738. }
  2739. if (videoChat != "") {
  2740. 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))
  2741. imagePlay.circle()
  2742. imageThumb.addSubview(imagePlay)
  2743. imagePlay.backgroundColor = .black.withAlphaComponent(0.3)
  2744. imagePlay.translatesAutoresizingMaskIntoConstraints = false
  2745. imagePlay.centerXAnchor.constraint(equalTo: imageThumb.centerXAnchor).isActive = true
  2746. imagePlay.centerYAnchor.constraint(equalTo: imageThumb.centerYAnchor).isActive = true
  2747. }
  2748. if (dataMessages[indexPath.row]["progress"] as! Double != 100.0 && dataMessages[indexPath.row]["f_pin"] as? String == idMe) {
  2749. let container = UIView()
  2750. imageThumb.addSubview(container)
  2751. container.translatesAutoresizingMaskIntoConstraints = false
  2752. container.bottomAnchor.constraint(equalTo: imageThumb.bottomAnchor, constant: -10).isActive = true
  2753. container.leadingAnchor.constraint(equalTo: imageThumb.leadingAnchor, constant: 10).isActive = true
  2754. container.widthAnchor.constraint(equalToConstant: 30).isActive = true
  2755. container.heightAnchor.constraint(equalToConstant: 30).isActive = true
  2756. container.backgroundColor = .white.withAlphaComponent(0.1)
  2757. let circlePath = UIBezierPath(arcCenter: CGPoint(x: 10, y: 20), radius: 15, startAngle: -(.pi / 2), endAngle: .pi * 2, clockwise: true)
  2758. let trackShape = CAShapeLayer()
  2759. trackShape.path = circlePath.cgPath
  2760. trackShape.fillColor = UIColor.black.withAlphaComponent(0.3).cgColor
  2761. trackShape.lineWidth = 3
  2762. trackShape.strokeColor = UIColor.blueBubbleColor.withAlphaComponent(0.3).cgColor
  2763. container.backgroundColor = .clear
  2764. container.layer.addSublayer(trackShape)
  2765. let shapeLoading = CAShapeLayer()
  2766. shapeLoading.path = circlePath.cgPath
  2767. shapeLoading.fillColor = UIColor.clear.cgColor
  2768. shapeLoading.lineWidth = 3
  2769. shapeLoading.strokeEnd = 0
  2770. shapeLoading.strokeColor = UIColor.blueBubbleColor.cgColor
  2771. container.layer.addSublayer(shapeLoading)
  2772. let imageupload = UIImageView(image: UIImage(systemName: "arrow.up", withConfiguration: UIImage.SymbolConfiguration(pointSize: 10, weight: .bold, scale: .default)))
  2773. imageupload.tintColor = .white
  2774. container.addSubview(imageupload)
  2775. imageupload.translatesAutoresizingMaskIntoConstraints = false
  2776. imageupload.bottomAnchor.constraint(equalTo: imageThumb.bottomAnchor, constant: -10).isActive = true
  2777. imageupload.leadingAnchor.constraint(equalTo: imageThumb.leadingAnchor, constant: 10).isActive = true
  2778. imageupload.widthAnchor.constraint(equalToConstant: 20).isActive = true
  2779. imageupload.heightAnchor.constraint(equalToConstant: 20).isActive = true
  2780. }
  2781. if !copySession && !forwardSession && !deleteSession {
  2782. let objectTap = ObjectGesture(target: self, action: #selector(contentMessageTapped(_:)))
  2783. imageThumb.isUserInteractionEnabled = true
  2784. imageThumb.addGestureRecognizer(objectTap)
  2785. objectTap.image_id = imageChat
  2786. objectTap.video_id = videoChat
  2787. objectTap.imageView = imageThumb
  2788. objectTap.indexPath = indexPath
  2789. }
  2790. }
  2791. if (fileChat != "" && (dataMessages[indexPath.row]["lock"] == nil || dataMessages[indexPath.row]["lock"] as! String != "1")) {
  2792. topMarginText.constant = topMarginText.constant + 55
  2793. let nsDocumentDirectory = FileManager.SearchPathDirectory.documentDirectory
  2794. let nsUserDomainMask = FileManager.SearchPathDomainMask.userDomainMask
  2795. let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true)
  2796. let arrExtFile = (textChat?.components(separatedBy: "|")[0])?.split(separator: ".")
  2797. let finalExtFile = arrExtFile![arrExtFile!.count - 1]
  2798. if let dirPath = paths.first {
  2799. let fileURL = URL(fileURLWithPath: dirPath).appendingPathComponent(fileChat)
  2800. if let dataFile = try? Data(contentsOf: fileURL) {
  2801. var sizeOfFile = Int(dataFile.count / 1000000)
  2802. if (sizeOfFile < 1) {
  2803. sizeOfFile = Int(dataFile.count / 1000)
  2804. if (finalExtFile.count > 4) {
  2805. messageText.text = "\(sizeOfFile) kB \u{2022} TXT"
  2806. }else {
  2807. messageText.text = "\(sizeOfFile) kB \u{2022} \(finalExtFile.uppercased())"
  2808. }
  2809. } else {
  2810. if (finalExtFile.count > 4) {
  2811. messageText.text = "\(sizeOfFile) MB \u{2022} TXT"
  2812. }else {
  2813. messageText.text = "\(sizeOfFile) MB \u{2022} \(finalExtFile.uppercased())"
  2814. }
  2815. }
  2816. } else {
  2817. messageText.text = ""
  2818. }
  2819. }
  2820. containerMessage.addSubview(containerViewFile)
  2821. containerViewFile.translatesAutoresizingMaskIntoConstraints = false
  2822. let data = queryMessageReply(message_id: reffChat)
  2823. if (data.count == 0) {
  2824. containerViewFile.topAnchor.constraint(equalTo: containerMessage.topAnchor, constant: 32).isActive = true
  2825. }
  2826. containerViewFile.leadingAnchor.constraint(equalTo: containerMessage.leadingAnchor, constant: 15).isActive = true
  2827. containerViewFile.bottomAnchor.constraint(equalTo:messageText.topAnchor, constant: -5).isActive = true
  2828. containerViewFile.trailingAnchor.constraint(equalTo: containerMessage.trailingAnchor, constant: -15).isActive = true
  2829. containerViewFile.heightAnchor.constraint(equalToConstant: 50).isActive = true
  2830. containerViewFile.backgroundColor = .black.withAlphaComponent(0.2)
  2831. containerViewFile.layer.cornerRadius = 5.0
  2832. containerViewFile.clipsToBounds = true
  2833. let imageFile = UIImageView(image: UIImage(systemName: "doc.fill", withConfiguration: UIImage.SymbolConfiguration(pointSize: 30, weight: .bold, scale: .default)))
  2834. containerViewFile.addSubview(imageFile)
  2835. let nameFile = UILabel()
  2836. containerViewFile.addSubview(nameFile)
  2837. imageFile.translatesAutoresizingMaskIntoConstraints = false
  2838. imageFile.leadingAnchor.constraint(equalTo: containerViewFile.leadingAnchor, constant: 5).isActive = true
  2839. imageFile.trailingAnchor.constraint(equalTo: nameFile.leadingAnchor, constant: -5).isActive = true
  2840. imageFile.centerYAnchor.constraint(equalTo: containerViewFile.centerYAnchor).isActive = true
  2841. imageFile.widthAnchor.constraint(equalToConstant: 30).isActive = true
  2842. imageFile.heightAnchor.constraint(equalToConstant: 30).isActive = true
  2843. imageFile.tintColor = .docColor
  2844. nameFile.translatesAutoresizingMaskIntoConstraints = false
  2845. nameFile.centerYAnchor.constraint(equalTo: containerViewFile.centerYAnchor).isActive = true
  2846. nameFile.widthAnchor.constraint(lessThanOrEqualToConstant: 200).isActive = true
  2847. nameFile.font = UIFont.systemFont(ofSize: 12, weight: .medium)
  2848. nameFile.textColor = .white
  2849. nameFile.text = textChat?.components(separatedBy: "|")[0]
  2850. if (dataMessages[indexPath.row]["progress"] as! Double != 100.0) {
  2851. let containerLoading = UIView()
  2852. containerViewFile.addSubview(containerLoading)
  2853. containerLoading.translatesAutoresizingMaskIntoConstraints = false
  2854. containerLoading.centerYAnchor.constraint(equalTo: containerViewFile.centerYAnchor).isActive = true
  2855. containerLoading.leadingAnchor.constraint(equalTo: nameFile.trailingAnchor, constant: 5).isActive = true
  2856. containerLoading.trailingAnchor.constraint(equalTo: containerViewFile.trailingAnchor, constant: -5).isActive = true
  2857. containerLoading.widthAnchor.constraint(equalToConstant: 30).isActive = true
  2858. containerLoading.heightAnchor.constraint(equalToConstant: 30).isActive = true
  2859. let circlePath = UIBezierPath(arcCenter: CGPoint(x: 15, y: 15), radius: 10, startAngle: -(.pi / 2), endAngle: .pi * 2, clockwise: true)
  2860. let trackShape = CAShapeLayer()
  2861. trackShape.path = circlePath.cgPath
  2862. trackShape.fillColor = UIColor.clear.cgColor
  2863. trackShape.lineWidth = 5
  2864. trackShape.strokeColor = UIColor.blueBubbleColor.withAlphaComponent(0.3).cgColor
  2865. containerLoading.layer.addSublayer(trackShape)
  2866. let shapeLoading = CAShapeLayer()
  2867. shapeLoading.path = circlePath.cgPath
  2868. shapeLoading.fillColor = UIColor.clear.cgColor
  2869. shapeLoading.lineWidth = 3
  2870. shapeLoading.strokeEnd = 0
  2871. shapeLoading.strokeColor = UIColor.secondaryColor.cgColor
  2872. containerLoading.layer.addSublayer(shapeLoading)
  2873. var imageupload = UIImageView(image: UIImage(systemName: "arrow.up", withConfiguration: UIImage.SymbolConfiguration(pointSize: 10, weight: .bold, scale: .default)))
  2874. if dataMessages[indexPath.row]["f_pin"] as? String != idMe {
  2875. imageupload = UIImageView(image: UIImage(systemName: "arrow.down", withConfiguration: UIImage.SymbolConfiguration(pointSize: 10, weight: .bold, scale: .default)))
  2876. shapeLoading.strokeColor = UIColor.blueBubbleColor.cgColor
  2877. }
  2878. imageupload.tintColor = .white
  2879. containerLoading.addSubview(imageupload)
  2880. imageupload.translatesAutoresizingMaskIntoConstraints = false
  2881. imageupload.centerYAnchor.constraint(equalTo: containerLoading.centerYAnchor).isActive = true
  2882. imageupload.centerXAnchor.constraint(equalTo: containerLoading.centerXAnchor).isActive = true
  2883. } else {
  2884. nameFile.trailingAnchor.constraint(equalTo: containerViewFile.trailingAnchor, constant: -5).isActive = true
  2885. }
  2886. if !copySession && !forwardSession && !deleteSession {
  2887. let objectTap = ObjectGesture(target: self, action: #selector(contentMessageTapped(_:)))
  2888. containerViewFile.addGestureRecognizer(objectTap)
  2889. objectTap.containerFile = containerViewFile
  2890. objectTap.labelFile = nameFile
  2891. objectTap.file_id = fileChat
  2892. objectTap.indexPath = indexPath
  2893. }
  2894. }
  2895. if (reffChat != "") {
  2896. let data = queryMessageReply(message_id: reffChat)
  2897. if data.count != 0 {
  2898. topMarginText.constant = topMarginText.constant + 55
  2899. let containerReply = UIView()
  2900. containerMessage.addSubview(containerReply)
  2901. containerReply.translatesAutoresizingMaskIntoConstraints = false
  2902. containerReply.leadingAnchor.constraint(equalTo: containerMessage.leadingAnchor, constant: 15).isActive = true
  2903. containerReply.topAnchor.constraint(equalTo: containerMessage.topAnchor, constant: 32).isActive = true
  2904. if thumbChat != "" && (dataMessages[indexPath.row]["lock"] == nil || dataMessages[indexPath.row]["lock"] as! String != "1") {
  2905. containerReply.bottomAnchor.constraint(equalTo: imageThumb.topAnchor, constant: -5).isActive = true
  2906. } else if fileChat != "" && (dataMessages[indexPath.row]["lock"] == nil || dataMessages[indexPath.row]["lock"] as! String != "1") {
  2907. containerReply.bottomAnchor.constraint(equalTo: containerViewFile.topAnchor, constant: -5).isActive = true
  2908. } else if dataMessages[indexPath.row]["attachment_flag"] as? String == "11" && (dataMessages[indexPath.row]["lock"] == nil || dataMessages[indexPath.row]["lock"] as! String != "1") {
  2909. containerReply.bottomAnchor.constraint(equalTo: imageSticker.topAnchor, constant: -5).isActive = true
  2910. } else {
  2911. containerReply.bottomAnchor.constraint(equalTo: messageText.topAnchor, constant: -5).isActive = true
  2912. }
  2913. containerReply.trailingAnchor.constraint(equalTo: containerMessage.trailingAnchor, constant: -15).isActive = true
  2914. containerReply.heightAnchor.constraint(equalToConstant: 50).isActive = true
  2915. containerReply.backgroundColor = .black.withAlphaComponent(0.2)
  2916. containerReply.layer.cornerRadius = 5
  2917. containerReply.clipsToBounds = true
  2918. let leftReply = UIView()
  2919. containerReply.addSubview(leftReply)
  2920. leftReply.translatesAutoresizingMaskIntoConstraints = false
  2921. leftReply.leadingAnchor.constraint(equalTo: containerReply.leadingAnchor).isActive = true
  2922. leftReply.topAnchor.constraint(equalTo: containerReply.topAnchor).isActive = true
  2923. leftReply.bottomAnchor.constraint(equalTo: containerReply.bottomAnchor).isActive = true
  2924. leftReply.widthAnchor.constraint(equalToConstant: 3).isActive = true
  2925. leftReply.layer.cornerRadius = 5
  2926. leftReply.clipsToBounds = true
  2927. leftReply.layer.maskedCorners = [.layerMinXMaxYCorner, .layerMinXMinYCorner]
  2928. let titleReply = UILabel()
  2929. containerReply.addSubview(titleReply)
  2930. titleReply.translatesAutoresizingMaskIntoConstraints = false
  2931. titleReply.leadingAnchor.constraint(equalTo: leftReply.leadingAnchor, constant: 10).isActive = true
  2932. titleReply.topAnchor.constraint(equalTo: containerReply.topAnchor, constant: 10).isActive = true
  2933. titleReply.trailingAnchor.constraint(lessThanOrEqualTo: containerReply.trailingAnchor, constant: -20).isActive = true
  2934. titleReply.font = UIFont.systemFont(ofSize: 12).bold
  2935. if (data["f_pin"] as? String == idMe) {
  2936. titleReply.text = "You".localized()
  2937. if dataMessages[indexPath.row]["f_pin"] as? String == idMe {
  2938. titleReply.textColor = .white
  2939. leftReply.backgroundColor = .white
  2940. } else {
  2941. titleReply.textColor = .mainColor
  2942. leftReply.backgroundColor = .mainColor
  2943. }
  2944. } else {
  2945. if data["f_pin"] as? String != "-999" {
  2946. let dataProfile = getDataProfile(f_pin: data["f_pin"] as! String, message_id: data["message_id"] as! String)
  2947. titleReply.text = dataProfile["name"]
  2948. } else {
  2949. titleReply.text = "Bot"
  2950. }
  2951. if dataMessages[indexPath.row]["f_pin"] as? String == idMe {
  2952. titleReply.textColor = .white
  2953. leftReply.backgroundColor = .white
  2954. } else {
  2955. titleReply.textColor = .mainColor
  2956. leftReply.backgroundColor = .mainColor
  2957. }
  2958. }
  2959. let contentReply = UILabel()
  2960. containerReply.addSubview(contentReply)
  2961. contentReply.translatesAutoresizingMaskIntoConstraints = false
  2962. contentReply.leadingAnchor.constraint(equalTo: leftReply.leadingAnchor, constant: 10).isActive = true
  2963. contentReply.bottomAnchor.constraint(equalTo: containerReply.bottomAnchor, constant: -10).isActive = true
  2964. contentReply.font = UIFont.systemFont(ofSize: 10)
  2965. let message_text = data["message_text"] as! String
  2966. let attachment_flag = data["attachment_flag"] as! String
  2967. let thumb_chat = data["thumb_id"] as! String
  2968. let image_chat = data["image_id"] as! String
  2969. let video_chat = data["video_id"] as! String
  2970. let file_chat = data["file_id"] as! String
  2971. if (attachment_flag == "0" && thumb_chat == "") {
  2972. contentReply.trailingAnchor.constraint(equalTo: containerReply.trailingAnchor, constant: -20).isActive = true
  2973. contentReply.attributedText = message_text.richText()
  2974. } else if (attachment_flag == "1" || image_chat != "") {
  2975. if (message_text == "") {
  2976. contentReply.text = "📷 Photo".localized()
  2977. } else {
  2978. contentReply.attributedText = message_text.richText()
  2979. }
  2980. } else if (attachment_flag == "2" || video_chat != "") {
  2981. if (message_text == "") {
  2982. contentReply.text = "📹 Video".localized()
  2983. } else {
  2984. contentReply.attributedText = message_text.richText()
  2985. }
  2986. } else if (attachment_flag == "6" || file_chat != ""){
  2987. contentReply.trailingAnchor.constraint(equalTo: containerReply.trailingAnchor, constant: -20).isActive = true
  2988. contentReply.text = "📄 \(message_text.components(separatedBy: "|")[0])"
  2989. } else if (attachment_flag == "11") {
  2990. contentReply.text = "❤️ Sticker"
  2991. } else if attachment_flag == "27" {
  2992. contentReply.trailingAnchor.constraint(equalTo: containerReply.trailingAnchor, constant: -20).isActive = true
  2993. contentReply.text = "📄 " + "Live Streaming".localized()
  2994. } else if attachment_flag == "26" {
  2995. contentReply.trailingAnchor.constraint(equalTo: containerReply.trailingAnchor, constant: -20).isActive = true
  2996. contentReply.text = "📄 " + "Seminar".localized()
  2997. }
  2998. contentReply.textColor = .white.withAlphaComponent(0.8)
  2999. if (attachment_flag == "1" || attachment_flag == "2" || image_chat != "" || video_chat != "") {
  3000. let nsDocumentDirectory = FileManager.SearchPathDirectory.documentDirectory
  3001. let nsUserDomainMask = FileManager.SearchPathDomainMask.userDomainMask
  3002. let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true)
  3003. if let dirPath = paths.first {
  3004. let thumbURL = URL(fileURLWithPath: dirPath).appendingPathComponent(thumb_chat)
  3005. let image = UIImage(contentsOfFile: thumbURL.path)
  3006. let imageThumb = UIImageView(image: image)
  3007. containerReply.addSubview(imageThumb)
  3008. imageThumb.layer.cornerRadius = 2.0
  3009. imageThumb.clipsToBounds = true
  3010. imageThumb.contentMode = .scaleAspectFill
  3011. imageThumb.translatesAutoresizingMaskIntoConstraints = false
  3012. imageThumb.trailingAnchor.constraint(equalTo: containerReply.trailingAnchor, constant: -10).isActive = true
  3013. imageThumb.centerYAnchor.constraint(equalTo: containerReply.centerYAnchor).isActive = true
  3014. imageThumb.widthAnchor.constraint(equalToConstant: 30).isActive = true
  3015. imageThumb.heightAnchor.constraint(equalToConstant: 30).isActive = true
  3016. if (attachment_flag == "2") {
  3017. let imagePlay = UIImageView(image: UIImage(systemName: "play.circle.fill"))
  3018. imageThumb.addSubview(imagePlay)
  3019. imagePlay.clipsToBounds = true
  3020. imagePlay.translatesAutoresizingMaskIntoConstraints = false
  3021. imagePlay.centerYAnchor.constraint(equalTo: imageThumb.centerYAnchor).isActive = true
  3022. imagePlay.centerXAnchor.constraint(equalTo: imageThumb.centerXAnchor).isActive = true
  3023. imagePlay.widthAnchor.constraint(equalToConstant: 10).isActive = true
  3024. imagePlay.heightAnchor.constraint(equalToConstant: 10).isActive = true
  3025. imagePlay.tintColor = .white
  3026. }
  3027. titleReply.trailingAnchor.constraint(equalTo: imageThumb.leadingAnchor, constant: -20).isActive = true
  3028. contentReply.trailingAnchor.constraint(equalTo: imageThumb.leadingAnchor, constant: -20).isActive = true
  3029. }
  3030. }
  3031. if (attachment_flag == "11") {
  3032. let imageSticker = UIImageView(image: UIImage(named: (message_text.components(separatedBy: "/")[1]), in: Bundle.resourceBundle(for: Nexilis.self), with: nil))
  3033. containerReply.addSubview(imageSticker)
  3034. imageSticker.layer.cornerRadius = 2.0
  3035. imageSticker.clipsToBounds = true
  3036. imageSticker.translatesAutoresizingMaskIntoConstraints = false
  3037. imageSticker.trailingAnchor.constraint(equalTo: containerReply.trailingAnchor, constant: -10).isActive = true
  3038. imageSticker.centerYAnchor.constraint(equalTo: containerReply.centerYAnchor).isActive = true
  3039. imageSticker.widthAnchor.constraint(equalToConstant: 30).isActive = true
  3040. imageSticker.heightAnchor.constraint(equalToConstant: 30).isActive = true
  3041. titleReply.trailingAnchor.constraint(equalTo: imageSticker.leadingAnchor, constant: -20).isActive = true
  3042. contentReply.trailingAnchor.constraint(equalTo: imageSticker.leadingAnchor, constant: -20).isActive = true
  3043. }
  3044. if !copySession && !forwardSession && !deleteSession {
  3045. let objectTap = ObjectGesture(target: self, action: #selector(contentMessageTapped(_:)))
  3046. containerReply.addGestureRecognizer(objectTap)
  3047. objectTap.indexPath = indexPath
  3048. objectTap.message_id = data["message_id"] as! String
  3049. }
  3050. }
  3051. }
  3052. return cellMessage
  3053. }
  3054. @objc func contentMessageTapped(_ sender: ObjectGesture) {
  3055. let nsDocumentDirectory = FileManager.SearchPathDirectory.documentDirectory
  3056. let nsUserDomainMask = FileManager.SearchPathDomainMask.userDomainMask
  3057. let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true)
  3058. if (sender.image_id != "") {
  3059. if let dirPath = paths.first {
  3060. let imageURL = URL(fileURLWithPath: dirPath).appendingPathComponent(sender.image_id)
  3061. if FileManager.default.fileExists(atPath: imageURL.path) {
  3062. let image = UIImage(contentsOfFile: imageURL.path)
  3063. let previewImageVC = PreviewAttachmentImageVideo(nibName: "PreviewAttachmentImageVideo", bundle: Bundle.resourceBundle(for: Nexilis.self))
  3064. previewImageVC.image = image
  3065. previewImageVC.isHiddenTextField = true
  3066. previewImageVC.modalPresentationStyle = .custom
  3067. previewImageVC.modalTransitionStyle = .crossDissolve
  3068. self.present(previewImageVC, animated: true, completion: nil)
  3069. } else {
  3070. for view in sender.imageView.subviews {
  3071. if view is UIImageView {
  3072. view.removeFromSuperview()
  3073. }
  3074. }
  3075. let activityIndicator = UIActivityIndicatorView(style: .large)
  3076. activityIndicator.color = .mainColor
  3077. activityIndicator.hidesWhenStopped = true
  3078. activityIndicator.center = CGPoint(x:sender.imageView.frame.width/2,
  3079. y: sender.imageView.frame.height/2)
  3080. activityIndicator.startAnimating()
  3081. sender.imageView.addSubview(activityIndicator)
  3082. Download().start(forKey: sender.image_id) { (name, progress) in
  3083. guard progress == 100 else {
  3084. return
  3085. }
  3086. let imageURL = URL(fileURLWithPath: dirPath).appendingPathComponent(sender.image_id)
  3087. let image = UIImage(contentsOfFile: imageURL.path)
  3088. let save = UserDefaults.standard.bool(forKey: "saveToGallery")
  3089. if save {
  3090. UIImageWriteToSavedPhotosAlbum(image!, nil, nil, nil)
  3091. }
  3092. DispatchQueue.main.async {
  3093. activityIndicator.stopAnimating()
  3094. self.tableChatView.reloadRows(at: [sender.indexPath], with: .none)
  3095. }
  3096. }
  3097. }
  3098. }
  3099. } else if (sender.video_id != "") {
  3100. if let dirPath = paths.first {
  3101. let videoURL = URL(fileURLWithPath: dirPath).appendingPathComponent(sender.video_id)
  3102. if FileManager.default.fileExists(atPath: videoURL.path) {
  3103. let player = AVPlayer(url: videoURL as URL)
  3104. let playerVC = AVPlayerViewController()
  3105. playerVC.modalPresentationStyle = .custom
  3106. playerVC.player = player
  3107. self.present(playerVC, animated: true, completion: nil)
  3108. } else {
  3109. for view in sender.imageView.subviews {
  3110. if view is UIImageView {
  3111. view.removeFromSuperview()
  3112. }
  3113. }
  3114. let container = UIView()
  3115. sender.imageView.addSubview(container)
  3116. container.translatesAutoresizingMaskIntoConstraints = false
  3117. container.centerXAnchor.constraint(equalTo: sender.imageView.centerXAnchor).isActive = true
  3118. container.centerYAnchor.constraint(equalTo: sender.imageView.centerYAnchor).isActive = true
  3119. container.widthAnchor.constraint(equalToConstant: 50).isActive = true
  3120. container.heightAnchor.constraint(equalToConstant: 50).isActive = true
  3121. let circlePath = UIBezierPath(arcCenter: CGPoint(x: 25, y: 25), radius: 20, startAngle: -(.pi / 2), endAngle: .pi * 2, clockwise: true)
  3122. let trackShape = CAShapeLayer()
  3123. trackShape.path = circlePath.cgPath
  3124. trackShape.fillColor = UIColor.clear.cgColor
  3125. trackShape.lineWidth = 10
  3126. trackShape.strokeColor = UIColor.blueBubbleColor.withAlphaComponent(0.3).cgColor
  3127. container.backgroundColor = .clear
  3128. container.layer.addSublayer(trackShape)
  3129. let shapeLoading = CAShapeLayer()
  3130. shapeLoading.path = circlePath.cgPath
  3131. shapeLoading.fillColor = UIColor.clear.cgColor
  3132. shapeLoading.lineWidth = 10
  3133. shapeLoading.strokeEnd = 0
  3134. shapeLoading.strokeColor = UIColor.blueBubbleColor.cgColor
  3135. container.layer.addSublayer(shapeLoading)
  3136. let imageDownload = UIImageView(image: UIImage(systemName: "arrow.down", withConfiguration: UIImage.SymbolConfiguration(pointSize: 10, weight: .bold, scale: .default)))
  3137. imageDownload.tintColor = .white
  3138. container.addSubview(imageDownload)
  3139. imageDownload.translatesAutoresizingMaskIntoConstraints = false
  3140. imageDownload.centerXAnchor.constraint(equalTo: sender.imageView.centerXAnchor).isActive = true
  3141. imageDownload.centerYAnchor.constraint(equalTo: sender.imageView.centerYAnchor).isActive = true
  3142. imageDownload.widthAnchor.constraint(equalToConstant: 30).isActive = true
  3143. imageDownload.heightAnchor.constraint(equalToConstant: 30).isActive = true
  3144. Download().start(forKey: sender.video_id) { (name, progress) in
  3145. DispatchQueue.main.async {
  3146. guard progress == 100 else {
  3147. shapeLoading.strokeEnd = CGFloat(progress / 100)
  3148. return
  3149. }
  3150. let save = UserDefaults.standard.bool(forKey: "saveToGallery")
  3151. if save {
  3152. let videoURL = URL(fileURLWithPath: dirPath).appendingPathComponent(sender.video_id)
  3153. PHPhotoLibrary.shared().performChanges({
  3154. PHAssetChangeRequest.creationRequestForAssetFromVideo(atFileURL: videoURL)
  3155. }) { saved, error in
  3156. }
  3157. }
  3158. let idx = self.dataMessages.firstIndex(where: { $0["video_id"] as! String == sender.video_id})
  3159. if idx != nil {
  3160. self.dataMessages[idx!]["progress"] = progress
  3161. self.tableChatView.reloadRows(at: [sender.indexPath], with: .none)
  3162. }
  3163. }
  3164. }
  3165. }
  3166. }
  3167. } else if (sender.file_id != "") {
  3168. if let dirPath = paths.first {
  3169. let fileURL = URL(fileURLWithPath: dirPath).appendingPathComponent(sender.file_id)
  3170. if FileManager.default.fileExists(atPath: fileURL.path) {
  3171. self.previewItem = fileURL as NSURL
  3172. let previewController = QLPreviewController()
  3173. let rightBarButton = UIBarButtonItem()
  3174. previewController.navigationItem.rightBarButtonItem = rightBarButton
  3175. previewController.dataSource = self
  3176. previewController.modalPresentationStyle = .custom
  3177. self.show(previewController, sender: nil)
  3178. } else {
  3179. for view in sender.containerFile.subviews {
  3180. if !(view is UIImageView) && !(view is UILabel) {
  3181. view.removeFromSuperview()
  3182. }
  3183. }
  3184. let containerLoading = UIView()
  3185. sender.containerFile.addSubview(containerLoading)
  3186. containerLoading.translatesAutoresizingMaskIntoConstraints = false
  3187. containerLoading.centerYAnchor.constraint(equalTo: sender.containerFile.centerYAnchor).isActive = true
  3188. containerLoading.leadingAnchor.constraint(equalTo: sender.labelFile.trailingAnchor, constant: 5).isActive = true
  3189. containerLoading.trailingAnchor.constraint(equalTo: sender.containerFile.trailingAnchor, constant: -5).isActive = true
  3190. containerLoading.widthAnchor.constraint(equalToConstant: 30).isActive = true
  3191. containerLoading.heightAnchor.constraint(equalToConstant: 30).isActive = true
  3192. let circlePath = UIBezierPath(arcCenter: CGPoint(x: 15, y: 15), radius: 10, startAngle: -(.pi / 2), endAngle: .pi * 2, clockwise: true)
  3193. let trackShape = CAShapeLayer()
  3194. trackShape.path = circlePath.cgPath
  3195. trackShape.fillColor = UIColor.clear.cgColor
  3196. trackShape.lineWidth = 5
  3197. trackShape.strokeColor = UIColor.blueBubbleColor.withAlphaComponent(0.3).cgColor
  3198. containerLoading.layer.addSublayer(trackShape)
  3199. let shapeLoading = CAShapeLayer()
  3200. shapeLoading.path = circlePath.cgPath
  3201. shapeLoading.fillColor = UIColor.clear.cgColor
  3202. shapeLoading.lineWidth = 3
  3203. shapeLoading.strokeEnd = 0
  3204. shapeLoading.strokeColor = UIColor.blueBubbleColor.cgColor
  3205. containerLoading.layer.addSublayer(shapeLoading)
  3206. let imageupload = UIImageView(image: UIImage(systemName: "arrow.down", withConfiguration: UIImage.SymbolConfiguration(pointSize: 10, weight: .bold, scale: .default)))
  3207. imageupload.tintColor = .white
  3208. containerLoading.addSubview(imageupload)
  3209. imageupload.translatesAutoresizingMaskIntoConstraints = false
  3210. imageupload.centerYAnchor.constraint(equalTo: containerLoading.centerYAnchor).isActive = true
  3211. imageupload.centerXAnchor.constraint(equalTo: containerLoading.centerXAnchor).isActive = true
  3212. Download().start(forKey: sender.file_id) { (name, progress) in
  3213. DispatchQueue.main.async {
  3214. guard progress == 100 else {
  3215. shapeLoading.strokeEnd = CGFloat(progress / 100)
  3216. return
  3217. }
  3218. let idx = self.dataMessages.firstIndex(where: { $0["file_id"] as! String == sender.file_id})
  3219. if idx != nil {
  3220. self.dataMessages[idx!]["progress"] = progress
  3221. self.tableChatView.reloadRows(at: [sender.indexPath], with: .none)
  3222. }
  3223. }
  3224. }
  3225. }
  3226. }
  3227. } else {
  3228. DispatchQueue.main.async {
  3229. let idx = self.dataMessages.firstIndex(where: { $0["message_id"] as! String == sender.message_id})
  3230. if idx == nil {
  3231. return
  3232. }
  3233. let section = self.dataDates.firstIndex(of: self.dataMessages[idx!]["chat_date"] as! String)
  3234. if section == nil {
  3235. return
  3236. }
  3237. 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})
  3238. if row == nil {
  3239. return
  3240. }
  3241. let indexPath = IndexPath(row: row!, section: section!)
  3242. self.tableChatView.scrollToRow(at: indexPath, at: .middle, animated: true)
  3243. DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
  3244. if let cell = self.tableChatView.cellForRow(at: indexPath) {
  3245. let containerMessage = cell.contentView.subviews[1]
  3246. let idMe = UserDefaults.standard.string(forKey: "me") as String?
  3247. if (self.dataMessages[idx!]["f_pin"] as? String == idMe) {
  3248. containerMessage.backgroundColor = .blueBubbleColor.withAlphaComponent(0.3)
  3249. DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
  3250. if (self.dataMessages[idx!]["attachment_flag"] as? String == "11") {
  3251. containerMessage.backgroundColor = .clear
  3252. } else {
  3253. containerMessage.backgroundColor = .blueBubbleColor
  3254. }
  3255. }
  3256. } else {
  3257. containerMessage.backgroundColor = .grayColor.withAlphaComponent(0.3)
  3258. DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
  3259. if (self.dataMessages[idx!]["attachment_flag"] as? String == "11") {
  3260. containerMessage.backgroundColor = .clear
  3261. } else {
  3262. containerMessage.backgroundColor = .grayColor
  3263. }
  3264. }
  3265. }
  3266. }
  3267. }
  3268. }
  3269. }
  3270. }
  3271. @objc func tapMessageText(_ sender: ObjectGesture) {
  3272. var stringURl = sender.message_id.lowercased()
  3273. if stringURl.starts(with: "www.") {
  3274. stringURl = "https://" + stringURl.replacingOccurrences(of: "www.", with: "")
  3275. }
  3276. guard let url = URL(string: stringURl) else { return }
  3277. UIApplication.shared.open(url)
  3278. }
  3279. }