ChatGPTBotView.swift 147 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566
  1. //
  2. // ChatGPTBotView.swift
  3. // NexilisLite
  4. //
  5. // Created by Maronakins on 21/09/23.
  6. //
  7. import UIKit
  8. import Alamofire
  9. import NotificationBannerSwift
  10. import nuSDKService
  11. class ChatGPTBotView: UIViewController, UIGestureRecognizerDelegate {
  12. public var dataPerson : [String: String?] = [
  13. "f_pin" : "-997",
  14. "firstName" : "GPT SmartBot",
  15. "picture" : ""
  16. ]
  17. var dataMessages: [[String: Any?]] = []
  18. var dataDates: [String] = []
  19. var chatGPTMessages: [[String: String]] = []
  20. @IBOutlet var tableChatView: UITableView!
  21. @IBOutlet var viewTextField: UIView!
  22. @IBOutlet var buttonSendChat: UIButton!
  23. @IBOutlet var textFieldSend: CustomTextView!
  24. @IBOutlet var heightTextFieldSend: NSLayoutConstraint!
  25. @IBOutlet var constraintBottomTableViewWithTextfield: NSLayoutConstraint!
  26. @IBOutlet var constraintTopTextField: NSLayoutConstraint!
  27. @IBOutlet var constraintViewTextField: NSLayoutConstraint!
  28. var gettingDataMessage = true
  29. var listViewOnSection: [UIView] = []
  30. var currentIndexpath: IndexPath?
  31. public var unique_l_pin = ""
  32. var counter = 0
  33. var markerCounter: String?
  34. var buttonScrollToBottom = UIButton()
  35. let indicatorCounterBSTB = UIView()
  36. let labelCounter = UILabel()
  37. var titleText: String!
  38. var isSearching = false
  39. var searchBar: UISearchBar!
  40. let containerMultpileSelectSession = UIView()
  41. var constraintBottomContainerMultpileSelectSession = NSLayoutConstraint()
  42. var copySession = false
  43. var deleteSession = false
  44. var showMenuContext = false
  45. var touchedSubview = UIView()
  46. var titleSearchMatches: UILabel!
  47. var textSearch = ""
  48. var countMatchesSearch = 0
  49. var lastScrollIdxSearch = 0
  50. var buttonUp: UIButton!
  51. var buttonDown: UIButton!
  52. public var fromNotification = true
  53. var lastY: CGFloat = 0
  54. var allowTyping = true
  55. struct Payload: Encodable {
  56. let use_video : String
  57. let payload : [[String: String]]
  58. }
  59. public override func viewDidDisappear(_ animated: Bool) {
  60. if self.isMovingFromParent {
  61. SecureUserDefaults.shared.removeValue(forKey: "inEditorPersonal")
  62. NotificationCenter.default.removeObserver(self)
  63. super.viewDidDisappear(true)
  64. self.removeFromParent()
  65. self.dismiss(animated: true, completion: nil)
  66. }
  67. }
  68. public override func viewDidAppear(_ animated: Bool) {
  69. let navBarAppearance = UINavigationBarAppearance()
  70. navBarAppearance.configureWithOpaqueBackground()
  71. navBarAppearance.backgroundColor = self.traitCollection.userInterfaceStyle == .dark ? .blackDarkMode : .mainColor
  72. navigationController?.navigationBar.standardAppearance = navBarAppearance
  73. navigationController?.navigationBar.scrollEdgeAppearance = navBarAppearance
  74. navigationController?.navigationBar.isTranslucent = false
  75. navigationController?.navigationBar.backgroundColor = self.traitCollection.userInterfaceStyle == .dark ? .blackDarkMode : .mainColor
  76. navigationController?.navigationBar.tintColor = .white
  77. navigationController?.navigationBar.overrideUserInterfaceStyle = .dark
  78. navigationController?.navigationBar.barStyle = .black
  79. if self.navigationController?.isNavigationBarHidden ?? false {
  80. self.navigationController?.setNavigationBarHidden(false, animated: false)
  81. }
  82. gettingDataMessage = false
  83. let indexPath = tableChatView.indexPathsForVisibleRows?.first
  84. if indexPath != nil {
  85. let headerRect = tableChatView.rectForHeader(inSection: indexPath!.section)
  86. let isPinned = headerRect.origin.y <= tableChatView.contentOffset.y
  87. if listViewOnSection.count != 0 && listViewOnSection.count - 1 == indexPath!.section && isPinned {
  88. let sect = listViewOnSection.count - 1 < currentIndexpath!.section ? listViewOnSection.count - 1 : currentIndexpath!.section
  89. let headerView = listViewOnSection[sect]
  90. headerView.isHidden = true
  91. }
  92. }
  93. }
  94. public override func viewDidLoad() {
  95. super.viewDidLoad()
  96. navigationController?.navigationBar.topItem?.title = "GPT SmartBot"
  97. buttonSendChat.setImage(resizeImage(image: self.traitCollection.userInterfaceStyle == .dark ? UIImage(named: "Send-(White)", in: Bundle.resourceBundle(for: Nexilis.self), with: nil)!.withTintColor(.blackDarkMode) : UIImage(named: "Send-(White)", in: Bundle.resourceBundle(for: Nexilis.self), with: nil)!, targetSize: CGSize(width: 30, height: 30)).withRenderingMode(.alwaysOriginal), for: .normal)
  98. buttonSendChat.circle()
  99. buttonSendChat.addTarget(self, action: #selector(sendTapped), for: .touchUpInside)
  100. buttonSendChat.backgroundColor = self.traitCollection.userInterfaceStyle == .dark ? .white : .mainColor
  101. textFieldSend.layer.cornerRadius = textFieldSend.maxCornerRadius()
  102. textFieldSend.layer.borderWidth = 1.0
  103. textFieldSend.text = "Send message".localized()
  104. textFieldSend.textColor = UIColor.lightGray
  105. textFieldSend.tintColor = self.traitCollection.userInterfaceStyle == .dark ? .white : .black
  106. textFieldSend.textContainerInset = UIEdgeInsets(top: 12, left: 20, bottom: 11, right: 40)
  107. textFieldSend.layer.borderColor = UIColor.lightGray.withAlphaComponent(0.5).cgColor
  108. textFieldSend.font = UIFont.systemFont(ofSize: 12)
  109. textFieldSend.delegate = self
  110. textFieldSend.allowsEditingTextAttributes = true
  111. navigationItem.rightBarButtonItem?.tintColor = UIColor.secondaryColor
  112. tableChatView.register(UITableViewCell.self, forCellReuseIdentifier: "cellEditorPersonal")
  113. loadData()
  114. setRightButtonItem()
  115. addGreeting()
  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: Nexilis.listenerReceiveChat), object: nil)
  120. center.addObserver(self, selector: #selector(onStatusChat(notification:)), name: NSNotification.Name(rawValue: Nexilis.listenerStatusChat), object: nil)
  121. center.addObserver(self, selector: #selector(onTyping(notification:)), name: NSNotification.Name(rawValue: Nexilis.listenerTypingChat), object: nil)
  122. }
  123. private func addGreeting() {
  124. guard let me = User.getMyPin() else {
  125. return
  126. }
  127. var user_id:String? = ""
  128. let message_id = me + CoreMessage_TMessageUtil.getTID()
  129. let server_date = String(Date().currentTimeMillis())
  130. var gptRow : [String: String] = [:]
  131. gptRow["role"] = "assistant"
  132. gptRow["content"] = Utils.getChatbotGreetings()
  133. chatGPTMessages.append(gptRow)
  134. Database.shared.database?.inTransaction({ (fmdb, rollback) in
  135. do {
  136. if let cursor = Database.shared.getRecords(fmdb: fmdb, query: "select user_id from BUDDY where f_pin = '\(me)'"), cursor.next() {
  137. user_id = cursor.string(forColumnIndex: 0)
  138. cursor.close()
  139. }
  140. } catch {
  141. rollback.pointee = true
  142. print("Access database error: \(error.localizedDescription)")
  143. }
  144. })
  145. Database.shared.database?.inTransaction({ (fmdb, rollback) in
  146. do {
  147. _ = try Database.shared.insertRecord(fmdb: fmdb, table: "MESSAGE", cvalues: [
  148. "message_id" : message_id ,
  149. "f_pin" : "-997",
  150. "f_display_name" : "GPT SmartBot",
  151. "l_pin" : me,
  152. "l_user_id" : String(user_id!),
  153. "message_scope_id" : "31",
  154. "server_date" : server_date,
  155. "status" : "3",
  156. "message_text" : gptRow["content"],
  157. "audio_id" : "",
  158. "video_id" : "",
  159. "image_id" : "",
  160. "file_id" : "",
  161. "thumb_id" : "",
  162. "opposite_pin" : "",
  163. "format" : "",
  164. "blog_id" : "",
  165. "read_receipts" : "0",
  166. "chat_id" : "",
  167. "account_type" : "1",
  168. "credential" :"",
  169. "reff_id" : "",
  170. "message_large_text" : "",
  171. "attachment_flag" : "0",
  172. "local_timestamp" : String(Date().currentTimeMillis())
  173. ], replace: true)
  174. } catch {
  175. rollback.pointee = true
  176. print("Access database error: \(error.localizedDescription)")
  177. }
  178. })
  179. let pin = "-997"
  180. var counter : Int? = nil
  181. Database.shared.database?.inTransaction({ (fmdb, rollback) in
  182. do {
  183. if let cursor = Database.shared.getRecords(fmdb: fmdb, query: "select counter from MESSAGE_SUMMARY where l_pin = '\(pin)'"), cursor.next() {
  184. counter = Int(cursor.int(forColumnIndex: 0))
  185. counter! += 0
  186. cursor.close()
  187. //print("select db message summary")
  188. }
  189. } catch {
  190. rollback.pointee = true
  191. print("Access database error: \(error.localizedDescription)")
  192. }
  193. })
  194. if counter == nil {
  195. counter = 0
  196. //print("set counter message summary")
  197. }
  198. Database.shared.database?.inTransaction({ (fmdb, rollback) in
  199. do {
  200. _ = try Database.shared.insertRecord(fmdb: fmdb, table: "MESSAGE_SUMMARY", cvalues: [
  201. "l_pin" : pin,
  202. "message_id" : message_id,
  203. "counter" : counter!
  204. ], replace: true)
  205. } catch {
  206. rollback.pointee = true
  207. print("Access database error: \(error.localizedDescription)")
  208. }
  209. })
  210. var row: [String: Any?] = [:]
  211. row["message_id"] = message_id
  212. row["f_pin"] = "-997"
  213. row["l_pin"] = me
  214. row["message_scope_id"] = "31"
  215. row["server_date"] = server_date
  216. row["status"] = "3"
  217. row["message_text"] = gptRow["content"]
  218. row["audio_id"] = ""
  219. row["video_id"] = ""
  220. row["image_id"] = ""
  221. row["thumb_id"] = ""
  222. row["read_receipts"] = "0"
  223. row["credential"] = ""
  224. row["file_id"] = ""
  225. row["reff_id"] = ""
  226. row["progress"] = 100.0
  227. row["attachment_flag"] = "0"
  228. row["lock"] = ""
  229. row["is_stared"] = "0"
  230. row["isSelected"] = false
  231. if !self.dataDates.contains("Today".localized()) {
  232. self.dataDates.append("Today".localized())
  233. self.tableChatView.insertSections(IndexSet(integer: self.dataDates.count - 1), with: .none)
  234. }
  235. row["chat_date"] = "Today".localized()
  236. row["blog_id"] = "0"
  237. self.dataMessages.append(row)
  238. self.tableChatView.insertRows(at: [IndexPath(row: self.dataMessages.filter({ $0["chat_date"] as! String == self.dataDates[self.dataDates.count - 1]}).count - 1, section: self.dataDates.count - 1)], with: .none)
  239. self.tableChatView.scrollToBottom()
  240. }
  241. @objc func sendTapped() {
  242. sendChat(message_text: textFieldSend.text!, viewController: self)
  243. }
  244. @objc func didTapExit() {
  245. self.dismiss(animated: true)
  246. // if complaintId.isEmpty || fromVCAC {
  247. // for timer in self.timerCredential.values {
  248. // timer.invalidate()
  249. // }
  250. // self.timeoutCC.invalidate()
  251. // NotificationCenter.default.removeObserver(self)
  252. // NotificationCenter.default.post(name: NSNotification.Name(rawValue: "refreshView"), object: nil, userInfo: nil)
  253. // self.dismiss(animated: true, completion: nil)
  254. // } else if !complaintId.isEmpty {
  255. // let alert = LibAlertController(title: "Interaction with Call Center is in progress".localized(), message: "Are you sure you want to end the Call Center?".localized(), preferredStyle: .alert)
  256. // alert.addAction(UIAlertAction(title: "No".localized(), style: UIAlertAction.Style.default, handler: nil))
  257. // alert.addAction(UIAlertAction(title: "Yes".localized(), style: UIAlertAction.Style.default, handler: {(_) in
  258. // self.endCallCenter()
  259. // }))
  260. // self.present(alert, animated: true, completion: nil)
  261. // }
  262. }
  263. private func sendChat(message_scope_id:String = "31", status:String = "4", 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 = "4", chat_id: String = "", is_call_center: String = "0", call_center_id: String = "", viewController: UIViewController) {
  264. if viewController is ChatGPTBotView {
  265. if ((textFieldSend.text!.trimmingCharacters(in: .whitespacesAndNewlines) == "Send message".localized() && textFieldSend.textColor == UIColor.lightGray && attachment_flag != "11") || textFieldSend.text!.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty ) {
  266. dismissKeyboard()
  267. viewController.showToast(message: "Write Messages".localized(), font: UIFont.systemFont(ofSize: 12, weight: .medium), controller: self)
  268. if (textFieldSend.text!.trimmingCharacters(in: .whitespacesAndNewlines) != "Send message".localized()) {
  269. textFieldSend.text = ""
  270. }
  271. if (self.heightTextFieldSend.constant != 40) {
  272. self.heightTextFieldSend.constant = 40
  273. }
  274. return
  275. }
  276. }
  277. var l_pin = dataPerson["f_pin"]!!
  278. var message_scope_id = message_scope_id
  279. var chat_id = chat_id
  280. let message_text = message_text.trimmingCharacters(in: .whitespacesAndNewlines)
  281. let idMe = User.getMyPin() as String?
  282. var opposite_pin = idMe ?? ""
  283. sendTyping(l_pin: l_pin, isTyping: true)
  284. let message = CoreMessage_TMessageBank.sendMessage(l_pin: l_pin, message_scope_id: message_scope_id, status: status, message_text: message_text, credential: credential, attachment_flag: attachment_flag, ex_blog_id: ex_blog_id, message_large_text: message_large_text, ex_format: ex_format, image_id: image_id, audio_id: audio_id, video_id: video_id, file_id: file_id, thumb_id: thumb_id, reff_id: reff_id, read_receipts: read_receipts, chat_id: chat_id, is_call_center: is_call_center, call_center_id: call_center_id, opposite_pin: opposite_pin)
  285. Nexilis.saveMessage(message: message)
  286. let messageId = String(message.mBodies[CoreMessage_TMessageKey.MESSAGE_ID]!)
  287. var row: [String: Any?] = [:]
  288. row["message_id"] = messageId
  289. row["f_pin"] = idMe
  290. row["l_pin"] = dataPerson["f_pin"]!!
  291. row["message_scope_id"] = message_scope_id
  292. row["server_date"] = "\(Date().currentTimeMillis())"
  293. row["status"] = status
  294. row["message_text"] = message_text
  295. row["audio_id"] = audio_id
  296. row["video_id"] = video_id
  297. row["image_id"] = image_id
  298. row["thumb_id"] = thumb_id
  299. row["read_receipts"] = read_receipts
  300. row["credential"] = credential
  301. row["chat_id"] = chat_id
  302. row["file_id"] = file_id
  303. row["attachment_flag"] = attachment_flag
  304. row["reff_id"] = reff_id
  305. row["progress"] = 0.0
  306. row["lock"] = "0"
  307. row["is_stared"] = "0"
  308. row["isSelected"] = false
  309. if !dataDates.contains("Today".localized()) {
  310. dataDates.append("Today".localized())
  311. tableChatView.insertSections(IndexSet(integer: dataDates.count - 1), with: .none)
  312. }
  313. row["chat_date"] = "Today".localized()
  314. dataMessages.append(row)
  315. var gptRow : [String: String] = [:]
  316. gptRow["role"] = row["f_pin"] as! String == "-997" ? "assistant" : "user"
  317. gptRow["content"] = row["message_text"] as? String
  318. chatGPTMessages.append(gptRow)
  319. request(mesage: row["message_text"] as! String)
  320. tableChatView.insertRows(at: [IndexPath(row: dataMessages.filter({ $0["chat_date"] as! String == dataDates[dataDates.count - 1]}).count - 1, section: dataDates.count - 1)], with: .none)
  321. if textFieldSend.text!.trimmingCharacters(in: .whitespacesAndNewlines) != "Send message".localized() && textFieldSend.textColor != UIColor.lightGray && constraintViewTextField.constant == 0 {
  322. textFieldSend.text = "Send message".localized()
  323. textFieldSend.textColor = UIColor.lightGray
  324. } else if constraintViewTextField.constant != 0 {
  325. textFieldSend.text = ""
  326. heightTextFieldSend.constant = 40
  327. }
  328. NotificationCenter.default.post(name: NSNotification.Name(rawValue: "reloadTabChats"), object: nil, userInfo: nil)
  329. DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) {
  330. self.tableChatView.scrollToBottom()
  331. if self.markerCounter != nil {
  332. let lastMarkerCounter = self.markerCounter
  333. self.markerCounter = nil
  334. self.tableChatView.beginUpdates()
  335. let indexMessage = self.dataMessages.firstIndex(where: { $0["message_id"] as? String == lastMarkerCounter })
  336. if indexMessage != nil {
  337. let section = self.dataDates.firstIndex(of: self.dataMessages[indexMessage!]["chat_date"] as! String)
  338. let row = self.dataMessages.filter({ $0["chat_date"] as! String == self.dataMessages[indexMessage!]["chat_date"] as! String}).firstIndex(where: { $0["message_id"] as? String == self.dataMessages[indexMessage!]["message_id"] as? String })
  339. if row != nil && section != nil {
  340. self.tableChatView.reloadRows(at: [IndexPath(row: row!, section: section!)], with: .none)
  341. }
  342. }
  343. self.tableChatView.endUpdates()
  344. }
  345. }
  346. // DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
  347. // self.timerFakeProgress = Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { _ in
  348. // self.updateProgress(row as [AnyHashable : Any])
  349. // if self.fakeProgMultip == self.maxFakeProgMultip {
  350. // self.timerFakeProgress?.invalidate()
  351. // self.fakeProgMultip = 0
  352. // }
  353. // }
  354. // }
  355. }
  356. private func request(mesage: String) {
  357. DispatchQueue.global().async {
  358. do {
  359. if let response = Nexilis.writeSync(message: CoreMessage_TMessageBank.requestGPTBot(message: mesage)) {
  360. if response.isOk() {
  361. let data = response.getBody(key: CoreMessage_TMessageKey.DATA)
  362. if let json = try! JSONSerialization.jsonObject(with: data.data(using: String.Encoding.utf8)!, options: []) as? [String: Any?] {
  363. print("HMM \(json)")
  364. DispatchQueue.main.async {
  365. var gptRow : [String: String] = [:]
  366. gptRow["role"] = json["role"] as? String
  367. gptRow["content"] = json["content"] as? String
  368. self.chatGPTMessages.append(gptRow)
  369. guard let me = User.getMyPin() else {
  370. return
  371. }
  372. var user_id:String? = ""
  373. let message_id = me + CoreMessage_TMessageUtil.getTID()
  374. let server_date = String(Date().currentTimeMillis())
  375. Database.shared.database?.inTransaction({ (fmdb, rollback) in
  376. do {
  377. if let cursor = Database.shared.getRecords(fmdb: fmdb, query: "select user_id from BUDDY where f_pin = '\(me)'"), cursor.next() {
  378. user_id = cursor.string(forColumnIndex: 0)
  379. cursor.close()
  380. }
  381. } catch {
  382. rollback.pointee = true
  383. print("Access database error: \(error.localizedDescription)")
  384. }
  385. })
  386. Database.shared.database?.inTransaction({ (fmdb, rollback) in
  387. do {
  388. _ = try Database.shared.insertRecord(fmdb: fmdb, table: "MESSAGE", cvalues: [
  389. "message_id" : message_id ,
  390. "f_pin" : "-997",
  391. "f_display_name" : "GPT SmartBot",
  392. "l_pin" : me,
  393. "l_user_id" : String(user_id!),
  394. "message_scope_id" : "31",
  395. "server_date" : server_date,
  396. "status" : "3",
  397. "message_text" : gptRow["content"],
  398. "audio_id" : "",
  399. "video_id" : "",
  400. "image_id" : "",
  401. "file_id" : "",
  402. "thumb_id" : "",
  403. "opposite_pin" : "",
  404. "format" : "",
  405. "blog_id" : "",
  406. "read_receipts" : "0",
  407. "chat_id" : "",
  408. "account_type" : "1",
  409. "credential" :"",
  410. "reff_id" : "",
  411. "message_large_text" : "",
  412. "attachment_flag" : "0",
  413. "local_timestamp" : String(Date().currentTimeMillis())
  414. ], replace: true)
  415. } catch {
  416. rollback.pointee = true
  417. print("Access database error: \(error.localizedDescription)")
  418. }
  419. })
  420. let pin = "-997"
  421. var counter : Int? = nil
  422. Database.shared.database?.inTransaction({ (fmdb, rollback) in
  423. do {
  424. if let cursor = Database.shared.getRecords(fmdb: fmdb, query: "select counter from MESSAGE_SUMMARY where l_pin = '\(pin)'"), cursor.next() {
  425. counter = Int(cursor.int(forColumnIndex: 0))
  426. counter! += 1
  427. cursor.close()
  428. //print("select db message summary")
  429. }
  430. } catch {
  431. rollback.pointee = true
  432. print("Access database error: \(error.localizedDescription)")
  433. }
  434. })
  435. if counter == nil {
  436. counter = 1
  437. //print("set counter message summary")
  438. }
  439. Database.shared.database?.inTransaction({ (fmdb, rollback) in
  440. do {
  441. _ = try Database.shared.insertRecord(fmdb: fmdb, table: "MESSAGE_SUMMARY", cvalues: [
  442. "l_pin" : pin,
  443. "message_id" : message_id,
  444. "counter" : counter!
  445. ], replace: true)
  446. } catch {
  447. rollback.pointee = true
  448. print("Access database error: \(error.localizedDescription)")
  449. }
  450. })
  451. //print("insert db message summary \(message_id)")
  452. var row: [String: Any?] = [:]
  453. row["message_id"] = message_id
  454. row["f_pin"] = "-997"
  455. row["l_pin"] = me
  456. row["message_scope_id"] = "31"
  457. row["server_date"] = server_date
  458. row["status"] = "3"
  459. row["message_text"] = gptRow["content"]
  460. row["audio_id"] = ""
  461. row["video_id"] = ""
  462. row["image_id"] = ""
  463. row["thumb_id"] = ""
  464. row["read_receipts"] = "0"
  465. row["credential"] = ""
  466. row["file_id"] = ""
  467. row["reff_id"] = ""
  468. row["progress"] = 100.0
  469. row["attachment_flag"] = "0"
  470. row["lock"] = ""
  471. row["is_stared"] = "0"
  472. row["isSelected"] = false
  473. if !self.dataDates.contains("Today".localized()) {
  474. self.dataDates.append("Today".localized())
  475. self.tableChatView.insertSections(IndexSet(integer: self.dataDates.count - 1), with: .none)
  476. }
  477. row["chat_date"] = "Today".localized()
  478. row["blog_id"] = "0"
  479. self.counter += 1
  480. self.dataMessages.append(row)
  481. self.tableChatView.insertRows(at: [IndexPath(row: self.dataMessages.filter({ $0["chat_date"] as! String == self.dataDates[self.dataDates.count - 1]}).count - 1, section: self.dataDates.count - 1)], with: .none)
  482. if self.currentIndexpath?.row == (self.dataMessages.count - 2) {
  483. if (self.viewIfLoaded?.window != nil) {
  484. self.sendReadMessageStatus(chat_id: "", f_pin: row["f_pin"] as! String, message_scope_id: row["message_scope_id"] as! String, message_id: message_id)
  485. }
  486. self.tableChatView.scrollToBottom()
  487. 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) {
  488. self.counter = 0
  489. self.updateCounter(counter: self.counter)
  490. }
  491. let lastMarkerCounter = self.markerCounter
  492. if self.markerCounter != nil {
  493. self.markerCounter = nil
  494. }
  495. self.tableChatView.beginUpdates()
  496. let indexMessage = self.dataMessages.firstIndex(where: { $0["message_id"] as? String == lastMarkerCounter })
  497. if indexMessage != nil {
  498. let section = self.dataDates.firstIndex(of: self.dataMessages[indexMessage!]["chat_date"] as! String)
  499. let row = self.dataMessages.filter({ $0["chat_date"] as! String == self.dataMessages[indexMessage!]["chat_date"] as! String}).firstIndex(where: { $0["message_id"] as? String == self.dataMessages[indexMessage!]["message_id"] as? String })
  500. if row != nil && section != nil {
  501. self.tableChatView.reloadRows(at: [IndexPath(row: row!, section: section!)], with: .none)
  502. }
  503. }
  504. self.tableChatView.endUpdates()
  505. }
  506. else if self.currentIndexpath == nil {
  507. self.counter = 0
  508. self.updateCounter(counter: self.counter)
  509. if (self.viewIfLoaded?.window != nil) {
  510. self.sendReadMessageStatus(chat_id: "", f_pin: row["f_pin"] as! String, message_scope_id: row["message_scope_id"] as! String, message_id: message_id)
  511. }
  512. }
  513. else if self.counter != 0 {
  514. if !self.indicatorCounterBSTB.isDescendant(of: self.view) && self.buttonScrollToBottom.isDescendant(of: self.view) {
  515. self.markerCounter = row["message_id"] as? String
  516. self.addCounterAtButttonScrollToBottom()
  517. self.tableChatView.beginUpdates()
  518. let indexMessage = self.dataMessages.firstIndex(where: { $0["message_id"] as? String == self.markerCounter })
  519. if indexMessage != nil {
  520. let section = self.dataDates.firstIndex(of: self.dataMessages[indexMessage!]["chat_date"] as! String)
  521. let row = self.dataMessages.filter({ $0["chat_date"] as! String == self.dataMessages[indexMessage!]["chat_date"] as! String}).firstIndex(where: { $0["message_id"] as? String == self.dataMessages[indexMessage!]["message_id"] as? String })
  522. if row != nil && section != nil {
  523. self.tableChatView.reloadRows(at: [IndexPath(row: row!, section: section!)], with: .none)
  524. }
  525. }
  526. self.tableChatView.endUpdates()
  527. } else if self.indicatorCounterBSTB.isDescendant(of: self.view) {
  528. self.labelCounter.text = "\(self.counter)"
  529. }
  530. }
  531. }
  532. }
  533. }
  534. }
  535. } catch {
  536. print("Error encoding data: \(error.localizedDescription)")
  537. }
  538. }
  539. }
  540. func loadData(){
  541. SecureUserDefaults.shared.set(dataPerson["f_pin"]!, forKey: "inEditorPersonal")
  542. UNUserNotificationCenter.current().removeDeliveredNotifications(withIdentifiers: [dataPerson["f_pin"]!!])
  543. if self.fromNotification {
  544. let imageButton = UIImageView(frame: CGRect(x: -16, y: 0, width: 20, height: 44))
  545. imageButton.image = UIImage(systemName: "chevron.backward", withConfiguration: UIImage.SymbolConfiguration(pointSize: 20, weight: .regular, scale: .default))?.withTintColor(.white)
  546. imageButton.contentMode = .left
  547. let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(didTapExit))
  548. imageButton.isUserInteractionEnabled = true
  549. imageButton.addGestureRecognizer(tapGestureRecognizer)
  550. let leftItem = UIBarButtonItem(customView: imageButton)
  551. self.navigationItem.leftBarButtonItem = leftItem
  552. }
  553. changeAppBar()
  554. getData()
  555. tableChatView.alpha = 0
  556. tableChatView.delegate = self
  557. tableChatView.dataSource = self
  558. tableChatView.keyboardDismissMode = .interactive
  559. let tapGesture = UITapGestureRecognizer(target: self, action: #selector(dismissKeyboard))
  560. tapGesture.cancelsTouchesInView = false
  561. tableChatView.addGestureRecognizer(tapGesture)
  562. let idMe = User.getMyPin() as String?
  563. for i in 0..<dataMessages.count {
  564. if dataMessages[i]["f_pin"] as? String != idMe {
  565. sendReadMessageStatus(chat_id: "", f_pin: dataPerson["f_pin"]!!, message_scope_id: "3", message_id: dataMessages[i]["message_id"] as! String)
  566. }
  567. }
  568. tableChatView.scrollToBottom(isAnimated: false)
  569. DispatchQueue.main.asyncAfter(deadline: .now() + 0.5, execute: {
  570. if self.tableChatView.alpha != 1.0 {
  571. UIView.animate(withDuration: 0.5, animations: {
  572. self.tableChatView.alpha = 1.0
  573. })
  574. }
  575. })
  576. }
  577. private func changeAppBar() {
  578. let viewAppBar = UIView()
  579. viewAppBar.frame.size = CGSize(width: self.view.frame.size.width, height: 44)
  580. if !isSearching {
  581. let imageProfile = UIImageView(frame: CGRect(x: 0, y: 7, width: 30, height: 30))
  582. imageProfile.circle()
  583. imageProfile.clipsToBounds = true
  584. var count = 0
  585. viewAppBar.addSubview(imageProfile)
  586. imageProfile.image = UIImage(named: "pb_gpt_bot", in: Bundle.resourceBundle(for: Nexilis.self), with: nil)
  587. imageProfile.contentMode = .scaleAspectFit
  588. let titleNavigation = UILabel(frame: CGRect(x: 35, y: 0, width: viewAppBar.frame.size.width - 250, height: 44))
  589. viewAppBar.addSubview(titleNavigation)
  590. titleNavigation.set(image: UIImage(named: "ic_official_flag", in: Bundle.resourceBundle(for: Nexilis.self), with: nil)!, with: " GPT SmartBot", size: 15, y: -4)
  591. titleNavigation.textColor = .white
  592. titleNavigation.font = UIFont.systemFont(ofSize: 12).bold
  593. navigationItem.titleView = viewAppBar
  594. titleText = titleNavigation.text
  595. } else {
  596. searchBar = UISearchBar()
  597. searchBar.autocapitalizationType = .none
  598. searchBar.delegate = self
  599. searchBar.searchTextField.tintColor = .mainColor
  600. searchBar.searchTextField.textColor = .mainColor
  601. // searchBar.updateHeight(height: 36, radius: 18)
  602. searchBar.showsCancelButton = false
  603. // searchBar.setMagnifyingGlassColorTo(color: .white)
  604. searchBar.setImage(UIImage(), for: .search, state: .normal)
  605. searchBar.setPositionAdjustment(UIOffset(horizontal: 10, vertical: 0), for: .search)
  606. searchBar.setCustomBackgroundImage(image: UIImage(named: self.traitCollection.userInterfaceStyle == .dark ? "nx_search_bar_dark" : "nx_search_bar", in: Bundle.resourceBundle(for: Nexilis.self), with: nil)!)
  607. navigationItem.titleView = searchBar
  608. self.definesPresentationContext = true
  609. }
  610. if copySession || deleteSession || isSearching {
  611. navigationItem.hidesBackButton = true
  612. navigationController?.interactivePopGestureRecognizer?.isEnabled = false
  613. } else {
  614. navigationItem.hidesBackButton = false
  615. navigationController?.interactivePopGestureRecognizer?.isEnabled = true
  616. }
  617. }
  618. private func getData() {
  619. 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, credential FROM MESSAGE where (f_pin='\(dataPerson["f_pin"]!!)' or l_pin='\(dataPerson["f_pin"]!!)') AND message_scope_id = '31' order by server_date asc"
  620. Database.shared.database?.inTransaction({ (fmdb, rollback) in
  621. do {
  622. if let cursorData = Database.shared.getRecords(fmdb: fmdb, query: query) {
  623. while cursorData.next() {
  624. var row: [String: Any?] = [:]
  625. row["message_id"] = cursorData.string(forColumnIndex: 0)
  626. row["f_pin"] = cursorData.string(forColumnIndex: 1)
  627. row["l_pin"] = cursorData.string(forColumnIndex: 2)
  628. row["message_scope_id"] = cursorData.string(forColumnIndex: 3)
  629. row["server_date"] = cursorData.string(forColumnIndex: 4)
  630. row["status"] = cursorData.string(forColumnIndex: 5)
  631. row["message_text"] = cursorData.string(forColumnIndex: 6)
  632. row["audio_id"] = cursorData.string(forColumnIndex: 7)
  633. row["video_id"] = cursorData.string(forColumnIndex: 8)
  634. row["image_id"] = cursorData.string(forColumnIndex: 9)
  635. row["thumb_id"] = cursorData.string(forColumnIndex: 10)
  636. row["read_receipts"] = cursorData.string(forColumnIndex: 11)
  637. row["chat_id"] = cursorData.string(forColumnIndex: 12)
  638. row["file_id"] = cursorData.string(forColumnIndex: 13)
  639. row["attachment_flag"] = cursorData.string(forColumnIndex: 14)
  640. row["reff_id"] = cursorData.string(forColumnIndex: 15)
  641. row["lock"] = cursorData.string(forColumnIndex: 16)
  642. row["is_stared"] = cursorData.string(forColumnIndex: 17)
  643. row["blog_id"] = cursorData.string(forColumnIndex: 18)
  644. row["credential"] = cursorData.string(forColumnIndex: 19)
  645. if let cursorStatus = Database.shared.getRecords(fmdb: fmdb, query: "SELECT status FROM MESSAGE_STATUS WHERE message_id='\(row["message_id"] as! String)'") {
  646. while cursorStatus.next() {
  647. row["status"] = cursorStatus.string(forColumnIndex: 0)
  648. }
  649. cursorStatus.close()
  650. }
  651. let nsDocumentDirectory = FileManager.SearchPathDirectory.documentDirectory
  652. let nsUserDomainMask = FileManager.SearchPathDomainMask.userDomainMask
  653. let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true)
  654. if let dirPath = paths.first {
  655. let videoURL = URL(fileURLWithPath: dirPath).appendingPathComponent(row["video_id"] as! String)
  656. let fileURL = URL(fileURLWithPath: dirPath).appendingPathComponent(row["file_id"] as! String)
  657. do {
  658. if ((row["video_id"] as! String) != "") {
  659. if FileManager.default.fileExists(atPath: videoURL.path) || FileEncryption.shared.isSecureExists(filename: row["video_id"] as! String){
  660. row["progress"] = 100.0
  661. } else {
  662. row["progress"] = 0.0
  663. }
  664. } else {
  665. if FileManager.default.fileExists(atPath: fileURL.path) || FileEncryption.shared.isSecureExists(filename: row["file_id"] as! String){
  666. row["progress"] = 100.0
  667. } else {
  668. row["progress"] = 0.0
  669. }
  670. }
  671. }
  672. }
  673. row["chat_date"] = chatDate(stringDate: row["server_date"] as! String)
  674. row["isSelected"] = false
  675. dataMessages.append(row)
  676. var gptRow : [String: String] = [:]
  677. gptRow["role"] = row["f_pin"] as! String == "-997" ? "assistant" : "user"
  678. gptRow["content"] = row["message_text"] as! String
  679. chatGPTMessages.append(gptRow)
  680. }
  681. cursorData.close()
  682. }
  683. } catch {
  684. rollback.pointee = true
  685. print("Access database error: \(error.localizedDescription)")
  686. }
  687. })
  688. }
  689. private func setRightButtonItem() {
  690. navigationItem.rightBarButtonItems = nil
  691. let actionDelete = UIAction(title: "Delete Conversation".localized(), handler: {(_) in
  692. let alert = LibAlertController(title: "", message: "Are you sure to delete all message in this conversation?".localized(), preferredStyle: .alert)
  693. alert.addAction(UIAlertAction(title: "Cancel".localized(), style: UIAlertAction.Style.default, handler: nil))
  694. alert.addAction(UIAlertAction(title: "Delete".localized(), style: .destructive, handler: {(_) in
  695. Database.shared.database?.inTransaction({ (fmdb, rollback) in
  696. do {
  697. _ = Database.shared.deleteRecord(fmdb: fmdb, table: "MESSAGE", _where: "f_pin='\(self.dataPerson["f_pin"]!!)' or l_pin='\(self.dataPerson["f_pin"]!!)'")
  698. _ = Database.shared.deleteRecord(fmdb: fmdb, table: "MESSAGE_SUMMARY", _where: "l_pin='\(self.dataPerson["f_pin"]!!)'")
  699. let l_pin = self.dataPerson["f_pin"]!!
  700. SecureUserDefaults.shared.removeValue(forKey: "saved_\(l_pin)")
  701. NotificationCenter.default.post(name: NSNotification.Name(rawValue: "reloadTabChats"), object: nil, userInfo: nil)
  702. self.navigationController?.popViewController(animated: true)
  703. } catch {
  704. rollback.pointee = true
  705. print("Access database error: \(error.localizedDescription)")
  706. }
  707. })
  708. }))
  709. self.present(alert, animated: true, completion: nil)
  710. })
  711. let actionSearch = UIAction(title: "Search".localized(), handler: {(_) in
  712. self.isSearching = true
  713. DispatchQueue.main.asyncAfter(deadline: .now() + 0.35) {
  714. let cancelButton = UIBarButtonItem(title: "Cancel".localized(), style: .plain, target: self, action: #selector(self.cancelAction))
  715. cancelButton.setTitleTextAttributes([NSAttributedString.Key.foregroundColor: UIColor.white, NSAttributedString.Key.font: UIFont.systemFont(ofSize: 16)], for: .normal)
  716. if self.dataPerson["f_pin"] != "-999" {
  717. self.navigationItem.rightBarButtonItems = nil
  718. // TODO: sus
  719. }
  720. self.navigationItem.rightBarButtonItem = cancelButton
  721. self.changeAppBar()
  722. self.addMultipleSelectSession()
  723. }
  724. })
  725. var menu = UIMenu(title: "", children: [
  726. actionSearch,
  727. actionDelete
  728. ])
  729. let moreIcon = UIBarButtonItem(image: UIImage(systemName: "ellipsis", withConfiguration: UIImage.SymbolConfiguration(pointSize: 18, weight: .regular, scale: .default)), menu: menu)
  730. navigationItem.rightBarButtonItem = moreIcon
  731. }
  732. @objc func dismissKeyboard() {
  733. if isSearching {
  734. searchBar.resignFirstResponder()
  735. } else {
  736. textFieldSend.resignFirstResponder() // dismiss keyoard
  737. }
  738. }
  739. @objc func keyboardWillHide(notification: NSNotification) {
  740. if self.viewIfLoaded?.window != nil {
  741. let info:NSDictionary = notification.userInfo! as NSDictionary
  742. let duration: CGFloat = info[UIResponder.keyboardAnimationDurationUserInfoKey] as! NSNumber as! CGFloat
  743. self.constraintViewTextField.constant = 0
  744. self.constraintBottomContainerMultpileSelectSession.constant = 0
  745. UIView.animate(withDuration: TimeInterval(duration), animations: {
  746. self.view.layoutIfNeeded()
  747. })
  748. }
  749. }
  750. @objc func keyboardWillShow(notification: NSNotification) {
  751. if self.viewIfLoaded?.window != nil {
  752. let info:NSDictionary = notification.userInfo! as NSDictionary
  753. let keyboardSize = (info[UIResponder.keyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
  754. let keyboardHeight: CGFloat = keyboardSize.height
  755. let duration: CGFloat = info[UIResponder.keyboardAnimationDurationUserInfoKey] as! NSNumber as! CGFloat
  756. if self.constraintViewTextField.constant != -keyboardHeight {
  757. self.constraintViewTextField.constant = -keyboardHeight
  758. if isSearching {
  759. self.constraintViewTextField.constant = self.constraintViewTextField.constant - 60
  760. self.constraintBottomContainerMultpileSelectSession.constant = -keyboardHeight
  761. }
  762. UIView.animate(withDuration: TimeInterval(duration), animations: {
  763. self.view.layoutIfNeeded()
  764. })
  765. if isSearching {
  766. self.tableChatView.scrollToBottom()
  767. } else {
  768. if (self.currentIndexpath != nil) {
  769. self.tableChatView.scrollToRow(at: IndexPath(row: self.currentIndexpath!.row, section: self.currentIndexpath!.section), at: .none, animated: false)
  770. } else {
  771. self.tableChatView.scrollToBottom()
  772. }
  773. }
  774. }
  775. }
  776. }
  777. @objc func onReceiveMessage(notification: NSNotification) {
  778. DispatchQueue.main.async { [self] in
  779. let data:[AnyHashable : Any] = notification.userInfo!
  780. if let dataMessage = data["message"] as? TMessage {
  781. let chatData = dataMessage.mBodies
  782. if (chatData[CoreMessage_TMessageKey.F_PIN] == self.dataPerson["f_pin"]!! && (chatData[CoreMessage_TMessageKey.MESSAGE_SCOPE_ID] == "3")) {
  783. if chatData[CoreMessage_TMessageKey.F_PIN] == nil {
  784. return
  785. }
  786. var row: [String: Any?] = [:]
  787. row["message_id"] = chatData[CoreMessage_TMessageKey.MESSAGE_ID]
  788. row["f_pin"] = chatData[CoreMessage_TMessageKey.F_PIN]
  789. row["l_pin"] = chatData[CoreMessage_TMessageKey.L_PIN]
  790. row["message_scope_id"] = chatData[CoreMessage_TMessageKey.MESSAGE_SCOPE_ID]
  791. row["server_date"] = chatData[CoreMessage_TMessageKey.SERVER_DATE]
  792. row["status"] = chatData[CoreMessage_TMessageKey.STATUS]
  793. row["message_text"] = chatData[CoreMessage_TMessageKey.MESSAGE_TEXT]
  794. if (chatData.keys.contains(CoreMessage_TMessageKey.AUDIO_ID)) {
  795. row["audio_id"] = chatData[CoreMessage_TMessageKey.AUDIO_ID]
  796. } else {
  797. row["audio_id"] = ""
  798. }
  799. if (chatData.keys.contains(CoreMessage_TMessageKey.VIDEO_ID)) {
  800. row["video_id"] = chatData[CoreMessage_TMessageKey.VIDEO_ID]
  801. } else {
  802. row["video_id"] = ""
  803. }
  804. if (chatData.keys.contains(CoreMessage_TMessageKey.IMAGE_ID)) {
  805. row["image_id"] = chatData[CoreMessage_TMessageKey.IMAGE_ID]
  806. } else {
  807. row["image_id"] = ""
  808. }
  809. if (chatData.keys.contains(CoreMessage_TMessageKey.THUMB_ID)) {
  810. row["thumb_id"] = chatData[CoreMessage_TMessageKey.THUMB_ID]
  811. } else {
  812. row["thumb_id"] = ""
  813. }
  814. if (chatData.keys.contains(CoreMessage_TMessageKey.READ_RECEIPTS)) {
  815. row["read_receipts"] = chatData[CoreMessage_TMessageKey.READ_RECEIPTS]
  816. } else {
  817. row["read_receipts"] = ""
  818. }
  819. if (chatData.keys.contains(CoreMessage_TMessageKey.CREDENTIAL)) {
  820. row["credential"] = chatData[CoreMessage_TMessageKey.CREDENTIAL]
  821. } else {
  822. row["credential"] = ""
  823. }
  824. row["chat_id"] = ""
  825. if (chatData.keys.contains(CoreMessage_TMessageKey.FILE_ID)) {
  826. row["file_id"] = chatData[CoreMessage_TMessageKey.FILE_ID]
  827. } else {
  828. row["file_id"] = ""
  829. }
  830. row["progress"] = 0.0
  831. row["attachment_flag"] = chatData[CoreMessage_TMessageKey.ATTACHMENT_FLAG]
  832. row["reff_id"] = chatData[CoreMessage_TMessageKey.REF_ID] ?? ""
  833. row["lock"] = ""
  834. row["is_stared"] = "0"
  835. row["isSelected"] = false
  836. if !self.dataDates.contains("Today".localized()) {
  837. self.dataDates.append("Today".localized())
  838. self.tableChatView.insertSections(IndexSet(integer: self.dataDates.count - 1), with: .none)
  839. }
  840. row["chat_date"] = "Today".localized()
  841. row["blog_id"] = chatData[CoreMessage_TMessageKey.BLOG_ID]
  842. self.counter += 1
  843. self.dataMessages.append(row)
  844. self.tableChatView.insertRows(at: [IndexPath(row: self.dataMessages.filter({ $0["chat_date"] as! String == self.dataDates[self.dataDates.count - 1]}).count - 1, section: self.dataDates.count - 1)], with: .none)
  845. if chatData[CoreMessage_TMessageKey.FORMAT] == "1" {
  846. self.sendReadMessageStatus(chat_id: "", f_pin: chatData[CoreMessage_TMessageKey.F_PIN]!, message_scope_id: chatData[CoreMessage_TMessageKey.MESSAGE_SCOPE_ID]!, message_id: chatData[CoreMessage_TMessageKey.MESSAGE_ID]!)
  847. self.tableChatView.scrollToBottom()
  848. } else if self.currentIndexpath?.row == (self.dataMessages.count - 2) {
  849. if (self.viewIfLoaded?.window != nil) {
  850. self.sendReadMessageStatus(chat_id: "", f_pin: chatData[CoreMessage_TMessageKey.F_PIN]!, message_scope_id: chatData[CoreMessage_TMessageKey.MESSAGE_SCOPE_ID]!, message_id: chatData[CoreMessage_TMessageKey.MESSAGE_ID]!)
  851. }
  852. self.tableChatView.scrollToBottom()
  853. 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) {
  854. self.counter = 0
  855. self.updateCounter(counter: self.counter)
  856. }
  857. let lastMarkerCounter = markerCounter
  858. if self.markerCounter != nil {
  859. self.markerCounter = nil
  860. }
  861. self.tableChatView.beginUpdates()
  862. let indexMessage = self.dataMessages.firstIndex(where: { $0["message_id"] as? String == lastMarkerCounter })
  863. if indexMessage != nil {
  864. let section = self.dataDates.firstIndex(of: self.dataMessages[indexMessage!]["chat_date"] as! String)
  865. let row = self.dataMessages.filter({ $0["chat_date"] as! String == self.dataMessages[indexMessage!]["chat_date"] as! String}).firstIndex(where: { $0["message_id"] as? String == self.dataMessages[indexMessage!]["message_id"] as? String })
  866. if row != nil && section != nil {
  867. self.tableChatView.reloadRows(at: [IndexPath(row: row!, section: section!)], with: .none)
  868. }
  869. }
  870. self.tableChatView.endUpdates()
  871. }
  872. else if self.currentIndexpath == nil {
  873. self.counter = 0
  874. self.updateCounter(counter: self.counter)
  875. if (self.viewIfLoaded?.window != nil) {
  876. self.sendReadMessageStatus(chat_id: "", f_pin: chatData[CoreMessage_TMessageKey.F_PIN]!, message_scope_id: chatData[CoreMessage_TMessageKey.MESSAGE_SCOPE_ID]!, message_id: chatData[CoreMessage_TMessageKey.MESSAGE_ID]!)
  877. }
  878. }
  879. else if self.counter != 0 {
  880. if !self.indicatorCounterBSTB.isDescendant(of: self.view) && self.buttonScrollToBottom.isDescendant(of: self.view) {
  881. self.markerCounter = row["message_id"] as? String
  882. self.addCounterAtButttonScrollToBottom()
  883. self.tableChatView.beginUpdates()
  884. let indexMessage = self.dataMessages.firstIndex(where: { $0["message_id"] as? String == self.markerCounter })
  885. if indexMessage != nil {
  886. let section = self.dataDates.firstIndex(of: self.dataMessages[indexMessage!]["chat_date"] as! String)
  887. let row = self.dataMessages.filter({ $0["chat_date"] as! String == self.dataMessages[indexMessage!]["chat_date"] as! String}).firstIndex(where: { $0["message_id"] as? String == self.dataMessages[indexMessage!]["message_id"] as? String })
  888. if row != nil && section != nil {
  889. self.tableChatView.reloadRows(at: [IndexPath(row: row!, section: section!)], with: .none)
  890. }
  891. }
  892. self.tableChatView.endUpdates()
  893. } else if self.indicatorCounterBSTB.isDescendant(of: self.view) {
  894. self.labelCounter.text = "\(self.counter)"
  895. }
  896. }
  897. }
  898. }
  899. }
  900. }
  901. @objc func onStatusChat(notification: NSNotification) {
  902. DispatchQueue.main.async {
  903. let data:[AnyHashable : Any] = notification.userInfo!
  904. if let dataMessage = data["message"] as? TMessage {
  905. let chatData = dataMessage.mBodies
  906. let onGoingCC: String = SecureUserDefaults.shared.value(forKey: "onGoingCC") ?? ""
  907. let requester = onGoingCC.components(separatedBy: ",")[0]
  908. let idMe = User.getMyPin()!
  909. if chatData[CoreMessage_TMessageKey.F_PIN] == self.dataPerson["f_pin"]!! || chatData[CoreMessage_TMessageKey.L_PIN] == self.dataPerson["f_pin"]!! || requester == idMe {
  910. if (chatData.keys.contains(CoreMessage_TMessageKey.MESSAGE_ID) && !(chatData[CoreMessage_TMessageKey.MESSAGE_ID]!).contains("-2,")) {
  911. var idx = self.dataMessages.firstIndex(where: { $0["message_id"] as? String == chatData[CoreMessage_TMessageKey.MESSAGE_ID]! })
  912. if (idx != nil) {
  913. if (chatData[CoreMessage_TMessageKey.DELETE_MESSAGE_FLAG] == "1") {
  914. self.dataMessages[idx!]["lock"] = "1"
  915. self.dataMessages[idx!]["reff_id"] = ""
  916. let section = self.dataDates.firstIndex(of: self.dataMessages[idx!]["chat_date"] as! String)
  917. 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 })
  918. if row != nil && section != nil {
  919. self.tableChatView.reloadRows(at: [IndexPath(row: row!, section: section!)], with: .none)
  920. }
  921. } else {
  922. self.dataMessages[idx!]["status"] = chatData[CoreMessage_TMessageKey.STATUS]!
  923. let section = self.dataDates.firstIndex(of: self.dataMessages[idx!]["chat_date"] as! String)
  924. 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 })
  925. if row != nil && section != nil {
  926. self.tableChatView.reloadRows(at: [IndexPath(row: row!, section: section!)], with: .none)
  927. }
  928. }
  929. }
  930. }
  931. else if (chatData.keys.contains("message_id")) {
  932. var idx = self.dataMessages.firstIndex(where: { "'\(String(describing: $0["message_id"] as? String))'" == chatData["message_id"]! })
  933. if (idx != nil) {
  934. if (chatData[CoreMessage_TMessageKey.DELETE_MESSAGE_FLAG] == "1") {
  935. self.dataMessages[idx!]["lock"] = "1"
  936. self.dataMessages[idx!]["reff_id"] = ""
  937. let section = self.dataDates.firstIndex(of: self.dataMessages[idx!]["chat_date"] as! String)
  938. 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 })
  939. if row != nil && section != nil {
  940. self.tableChatView.reloadRows(at: [IndexPath(row: row!, section: section!)], with: .none)
  941. }
  942. } else {
  943. self.dataMessages[idx!]["status"] = chatData[CoreMessage_TMessageKey.STATUS]!
  944. let section = self.dataDates.firstIndex(of: self.dataMessages[idx!]["chat_date"] as! String)
  945. 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 })
  946. if row != nil && section != nil {
  947. self.tableChatView.reloadRows(at: [IndexPath(row: row!, section: section!)], with: .none)
  948. }
  949. }
  950. }
  951. }
  952. else {
  953. let messageId = chatData[CoreMessage_TMessageKey.MESSAGE_ID]!.split(separator: ",")[1]
  954. var idx = self.dataMessages.firstIndex(where: { $0["message_id"] as? String ?? "" == messageId })
  955. if (idx != nil) {
  956. self.dataMessages[idx!]["status"] = chatData[CoreMessage_TMessageKey.STATUS]!
  957. let section = self.dataDates.firstIndex(of: self.dataMessages[idx!]["chat_date"] as! String)
  958. 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 })
  959. if row != nil && section != nil {
  960. self.tableChatView.reloadRows(at: [IndexPath(row: row!, section: section!)], with: .none)
  961. }
  962. }
  963. }
  964. }
  965. }
  966. }
  967. }
  968. @objc func onTyping(notification: NSNotification) {
  969. DispatchQueue.main.async { [self] in
  970. let data:[AnyHashable : Any] = notification.userInfo!
  971. let message: TMessage = data["message"] as! TMessage
  972. let onGoingCC: String = SecureUserDefaults.shared.value(forKey: "onGoingCC") ?? ""
  973. if !onGoingCC.isEmpty {
  974. let officer = onGoingCC.isEmpty ? "" : onGoingCC.components(separatedBy: ",")[1]
  975. if message.getBody(key: CoreMessage_TMessageKey.F_PIN) != officer {
  976. //print("RESET TIMER")
  977. // timeoutCC.invalidate()
  978. // timeoutCC = Timer.scheduledTimer(withTimeInterval: 30.0, repeats: false, block: {_ in
  979. // let imageView = UIImageView(image: UIImage(systemName: "info.circle"))
  980. // imageView.tintColor = .white
  981. // let banner = FloatingNotificationBanner(title: "Customer doesn't respond in 30 second, so call center session will be ended automatically.".localized(), subtitle: nil, titleFont: UIFont.systemFont(ofSize: 16), titleColor: nil, titleTextAlign: .left, subtitleFont: nil, subtitleColor: nil, subtitleTextAlign: nil, leftView: imageView, rightView: nil, style: .info, colors: nil, iconPosition: .center)
  982. // banner.show()
  983. // self.endCallCenter()
  984. // })
  985. }
  986. } else {
  987. }
  988. }
  989. }
  990. private func sendReadMessageStatus(chat_id: String, f_pin: String, message_scope_id: String, message_id: String) {
  991. let message = CoreMessage_TMessageBank.getUpdateRead(p_chat_id: chat_id, p_f_pin: f_pin, p_scope_id: message_scope_id, qty: 1)
  992. let fPin = message.getBody(key: CoreMessage_TMessageKey.F_PIN)
  993. let scope = message.getBody(key: CoreMessage_TMessageKey.SCOPE_ID)
  994. message.mBodies[CoreMessage_TMessageKey.SERVER_DATE] = String(Date().currentTimeMillis())
  995. if (fPin.elementsEqual("-999") || scope.elementsEqual("16") || scope.elementsEqual("15")){
  996. return
  997. }
  998. DispatchQueue.global().async {
  999. Database.shared.database?.inTransaction({ (fmdb, rollback) in
  1000. do {
  1001. _ = Database.shared.updateRecord(fmdb: fmdb, table: "MESSAGE", cvalues: [
  1002. "status" : "4"
  1003. ], _where: "message_id = '\(message_id)'")
  1004. } catch {
  1005. rollback.pointee = true
  1006. print("Access database error: \(error.localizedDescription)")
  1007. }
  1008. })
  1009. message.mStatus = CoreMessage_TMessageUtil.getTID()
  1010. message.mBodies[CoreMessage_TMessageKey.L_PIN] = f_pin
  1011. message.mBodies[CoreMessage_TMessageKey.MESSAGE_ID] = "-2,\(message_id)"
  1012. _ = Nexilis.write(message: message)
  1013. }
  1014. if let index = dataMessages.firstIndex(where: {$0["message_id"] as? String == message_id}) {
  1015. dataMessages[index]["status"] = "4"
  1016. }
  1017. }
  1018. func chatDate(stringDate: String) -> String {
  1019. let date = Date(milliseconds: Int64(stringDate)!)
  1020. let calendar = Calendar.current
  1021. if (calendar.isDateInToday(date)) {
  1022. if !dataDates.contains("Today".localized()){
  1023. dataDates.append("Today".localized())
  1024. }
  1025. return "Today".localized()
  1026. } else {
  1027. let startOfNow = calendar.startOfDay(for: Date())
  1028. let startOfTimeStamp = calendar.startOfDay(for: date)
  1029. let components = calendar.dateComponents([.day], from: startOfNow, to: startOfTimeStamp)
  1030. let day = -(components.day!)
  1031. if day == 1{
  1032. if !dataDates.contains("Yesterday".localized()){
  1033. dataDates.append("Yesterday".localized())
  1034. }
  1035. return "Yesterday".localized()
  1036. } else if day < 7 {
  1037. let formatter = DateFormatter()
  1038. formatter.dateFormat = "EEEE"
  1039. let lang: String = SecureUserDefaults.shared.value(forKey: "i18n_language") ?? "en"
  1040. if lang == "id" {
  1041. formatter.locale = NSLocale(localeIdentifier: "id") as Locale?
  1042. }
  1043. if !dataDates.contains(formatter.string(from: date)){
  1044. dataDates.append(formatter.string(from: date))
  1045. }
  1046. return formatter.string(from: date)
  1047. } else {
  1048. let formatter = DateFormatter()
  1049. formatter.dateFormat = "EE, dd MMM"
  1050. let lang: String = SecureUserDefaults.shared.value(forKey: "i18n_language") ?? "en"
  1051. if lang == "id" {
  1052. formatter.locale = NSLocale(localeIdentifier: "id") as Locale?
  1053. }
  1054. let stringFormat = formatter.string(from: date as Date)
  1055. if !dataDates.contains(stringFormat){
  1056. dataDates.append(stringFormat)
  1057. }
  1058. return stringFormat
  1059. }
  1060. }
  1061. }
  1062. private func updateCounter(counter: Int) {
  1063. DispatchQueue.global().async {
  1064. Database.shared.database?.inTransaction({ (fmdb, rollback) in
  1065. do {
  1066. _ = Database.shared.updateRecord(fmdb: fmdb, table: "MESSAGE_SUMMARY", cvalues: [
  1067. "counter" : "\(counter)"
  1068. ], _where: "l_pin = '\(self.dataPerson["f_pin"]!!)'")
  1069. } catch {
  1070. rollback.pointee = true
  1071. print("Access database error: \(error.localizedDescription)")
  1072. }
  1073. })
  1074. NotificationCenter.default.post(name: NSNotification.Name(rawValue: "reloadTabChats"), object: nil, userInfo: nil)
  1075. }
  1076. }
  1077. private func addButtonScrollToBottom() {
  1078. self.view.addSubview(buttonScrollToBottom)
  1079. buttonScrollToBottom.translatesAutoresizingMaskIntoConstraints = false
  1080. NSLayoutConstraint.activate([
  1081. buttonScrollToBottom.bottomAnchor.constraint(equalTo: buttonSendChat.topAnchor, constant: -50),
  1082. buttonScrollToBottom.trailingAnchor.constraint(equalTo: self.view.trailingAnchor),
  1083. buttonScrollToBottom.widthAnchor.constraint(equalToConstant: 60),
  1084. buttonScrollToBottom.heightAnchor.constraint(equalToConstant: 30.0)
  1085. ])
  1086. buttonScrollToBottom.backgroundColor = .greenColor
  1087. buttonScrollToBottom.setImage(UIImage(systemName: "chevron.down.circle"), for: .normal)
  1088. buttonScrollToBottom.imageView?.contentMode = .scaleAspectFit
  1089. buttonScrollToBottom.imageView?.tintColor = .white
  1090. buttonScrollToBottom.contentVerticalAlignment = .fill
  1091. buttonScrollToBottom.contentHorizontalAlignment = .fill
  1092. buttonScrollToBottom.imageEdgeInsets.top = 2.0
  1093. buttonScrollToBottom.imageEdgeInsets.bottom = 2.0
  1094. buttonScrollToBottom.layer.cornerRadius = 10.0
  1095. buttonScrollToBottom.layer.maskedCorners = [.layerMinXMinYCorner, .layerMinXMaxYCorner]
  1096. buttonScrollToBottom.clipsToBounds = true
  1097. buttonScrollToBottom.addTarget(self, action: #selector(scrollTobottomAction), for: .touchUpInside)
  1098. }
  1099. private func addCounterAtButttonScrollToBottom() {
  1100. self.view.addSubview(indicatorCounterBSTB)
  1101. indicatorCounterBSTB.translatesAutoresizingMaskIntoConstraints = false
  1102. indicatorCounterBSTB.backgroundColor = .systemRed
  1103. indicatorCounterBSTB.layer.cornerRadius = 7.5
  1104. indicatorCounterBSTB.clipsToBounds = true
  1105. indicatorCounterBSTB.layer.borderWidth = 0.5
  1106. indicatorCounterBSTB.layer.borderColor = UIColor.secondaryColor.cgColor
  1107. NSLayoutConstraint.activate([
  1108. indicatorCounterBSTB.bottomAnchor.constraint(equalTo: buttonScrollToBottom.topAnchor, constant: 5),
  1109. indicatorCounterBSTB.trailingAnchor.constraint(equalTo: self.view.trailingAnchor, constant: -50),
  1110. indicatorCounterBSTB.widthAnchor.constraint(greaterThanOrEqualToConstant: 15),
  1111. indicatorCounterBSTB.heightAnchor.constraint(equalToConstant: 15)
  1112. ])
  1113. indicatorCounterBSTB.addSubview(labelCounter)
  1114. labelCounter.translatesAutoresizingMaskIntoConstraints = false
  1115. NSLayoutConstraint.activate([
  1116. labelCounter.leadingAnchor.constraint(equalTo: indicatorCounterBSTB.leadingAnchor, constant: 2),
  1117. labelCounter.trailingAnchor.constraint(equalTo: indicatorCounterBSTB.trailingAnchor, constant: -2),
  1118. labelCounter.centerXAnchor.constraint(equalTo: indicatorCounterBSTB.centerXAnchor),
  1119. ])
  1120. labelCounter.font = UIFont.systemFont(ofSize: 11)
  1121. labelCounter.text = "\(counter)"
  1122. labelCounter.textColor = .secondaryColor
  1123. labelCounter.textAlignment = .center
  1124. }
  1125. @objc func scrollTobottomAction() {
  1126. tableChatView.scrollToBottom()
  1127. DispatchQueue.main.asyncAfter(deadline: .now() + 0.35) { [self] in
  1128. if buttonScrollToBottom.isDescendant(of: self.view) {
  1129. buttonScrollToBottom.removeConstraints(buttonScrollToBottom.constraints)
  1130. buttonScrollToBottom.removeFromSuperview()
  1131. if indicatorCounterBSTB.isDescendant(of: self.view) {
  1132. indicatorCounterBSTB.removeConstraints(indicatorCounterBSTB.constraints)
  1133. indicatorCounterBSTB.removeFromSuperview()
  1134. }
  1135. }
  1136. }
  1137. }
  1138. private func checkNewMessage(tableView: UITableView) {
  1139. // let indexPathFirst = tableView.indexPathsForVisibleRows?.first
  1140. // if indexPathFirst != nil {
  1141. // let dataMessages = self.dataMessages.filter({ $0["chat_date"] as! String == dataDates[indexPathFirst!.section] })
  1142. // if self.dataMessages.firstIndex(where: { $0["message_id"] as? String == dataMessages[indexPathFirst!.row]["message_id"] as? String }) == 0 && !gettingDataMessage {
  1143. // gettingDataMessage = true
  1144. // addDataMessage()
  1145. // }
  1146. // }
  1147. currentIndexpath = tableView.indexPathsForVisibleRows?.last
  1148. if currentIndexpath != nil {
  1149. let dataMessages = dataMessages.filter({ $0["chat_date"] as! String == dataDates[currentIndexpath!.section] })
  1150. if dataMessages.count == 0 || dataMessages.count - 1 < currentIndexpath!.row {
  1151. return
  1152. }
  1153. if currentIndexpath!.section == dataDates.count - 1 && currentIndexpath!.row != dataMessages.count - 1 && currentIndexpath!.row != dataMessages.count - 2 && !buttonScrollToBottom.isDescendant(of: self.view) {
  1154. addButtonScrollToBottom()
  1155. addCounterAtButttonScrollToBottom()
  1156. } else if currentIndexpath!.section == dataDates.count - 1 && currentIndexpath!.row == dataMessages.count - 1 {
  1157. if buttonScrollToBottom.isDescendant(of: self.view) {
  1158. buttonScrollToBottom.removeConstraints(buttonScrollToBottom.constraints)
  1159. buttonScrollToBottom.removeFromSuperview()
  1160. if indicatorCounterBSTB.isDescendant(of: self.view) {
  1161. indicatorCounterBSTB.removeConstraints(indicatorCounterBSTB.constraints)
  1162. indicatorCounterBSTB.removeFromSuperview()
  1163. }
  1164. }
  1165. }
  1166. let indexPathFirst = tableChatView.indexPathsForVisibleRows?.first
  1167. if indexPathFirst != nil && listViewOnSection.count != 0 && listViewOnSection.count - 1 >= indexPathFirst!.section {
  1168. let headerView = listViewOnSection[indexPathFirst!.section]
  1169. if headerView.isHidden {
  1170. headerView.isHidden = false
  1171. }
  1172. }
  1173. var listData = dataMessages[0...currentIndexpath!.row]
  1174. listData = listData.filter({$0["status"] as? String != "4" && $0["status"] as? String != "8"})
  1175. if listData.count != 0 {
  1176. let idMe = User.getMyPin() as String?
  1177. for i in 0...listData.count - 1 {
  1178. if listData[i]["f_pin"] as? String != idMe {
  1179. sendReadMessageStatus(chat_id: "", f_pin: dataPerson["f_pin"]!!, message_scope_id: "31", message_id: listData[i]["message_id"] as! String)
  1180. }
  1181. }
  1182. }
  1183. }
  1184. if counter == 0 && indicatorCounterBSTB.isDescendant(of: self.view) {
  1185. indicatorCounterBSTB.removeConstraints(indicatorCounterBSTB.constraints)
  1186. indicatorCounterBSTB.removeFromSuperview()
  1187. } else if counter != 0 && currentIndexpath != nil {
  1188. let dataFilter = dataMessages.filter({ $0["chat_date"] as! String == dataDates[currentIndexpath!.section] })
  1189. if dataFilter.count == 0 {
  1190. return
  1191. }
  1192. let idx = dataMessages.firstIndex(where: { $0["message_id"] as? String == dataFilter[currentIndexpath!.row]["message_id"] as? String})
  1193. if idx == nil {
  1194. return
  1195. }
  1196. if (dataMessages.count - counter) <= idx! {
  1197. let countUpdate = idx! - (dataMessages.count - counter)
  1198. counter = counter - (countUpdate + 1)
  1199. if indicatorCounterBSTB.isDescendant(of: self.view) {
  1200. labelCounter.text = "\(counter)"
  1201. }
  1202. updateCounter(counter: counter)
  1203. }
  1204. }
  1205. }
  1206. private func sendTyping(l_pin: String, isTyping: Bool = false) {
  1207. DispatchQueue.global().async {
  1208. let tmessage = CoreMessage_TMessageBank.getUpdateTypingStatus(p_opposite: l_pin, p_scope: "3", p_status: isTyping ? "3": "4")
  1209. _ = Nexilis.write(message: tmessage)
  1210. }
  1211. }
  1212. }
  1213. extension ChatGPTBotView: UIContextMenuInteractionDelegate {
  1214. public func contextMenuInteraction(_ interaction: UIContextMenuInteraction, willEndFor configuration: UIContextMenuConfiguration, animator: UIContextMenuInteractionAnimating?) {
  1215. if showMenuContext {
  1216. showMenuContext = false
  1217. interaction.view!.removeInteraction(interaction)
  1218. }
  1219. }
  1220. public func contextMenuInteraction(_ interaction: UIContextMenuInteraction, configurationForMenuAtLocation location: CGPoint) -> UIContextMenuConfiguration? {
  1221. if textFieldSend.isFirstResponder {
  1222. textFieldSend.resignFirstResponder()
  1223. }
  1224. let indexPath = self.tableChatView.indexPathForRow(at: interaction.view!.convert(location, to: self.tableChatView))
  1225. let dataMessages = self.dataMessages.filter({ $0["chat_date"] as! String == dataDates[indexPath!.section]})
  1226. let copy = UIAction(title: "Copy".localized(), image: UIImage(systemName: "doc.on.doc.fill"), handler: {(_) in
  1227. if self.isSearching {
  1228. self.cancelAction()
  1229. }
  1230. DispatchQueue.main.asyncAfter(deadline: .now() + 0.35) {
  1231. self.copySession = true
  1232. let cancelButton = UIBarButtonItem(title: "Cancel".localized(), style: .plain, target: self, action: #selector(self.cancelAction))
  1233. cancelButton.setTitleTextAttributes([NSAttributedString.Key.foregroundColor: UIColor.white, NSAttributedString.Key.font: UIFont.systemFont(ofSize: 16)], for: .normal)
  1234. if self.dataPerson["f_pin"] != "-999" {
  1235. self.navigationItem.rightBarButtonItems = nil
  1236. }
  1237. self.navigationItem.rightBarButtonItem = cancelButton
  1238. self.changeAppBar()
  1239. let idx = self.dataMessages.firstIndex(where: { $0["message_id"] as? String == dataMessages[indexPath!.row]["message_id"] as? String})
  1240. if idx != nil{
  1241. self.dataMessages[idx!]["isSelected"] = true
  1242. }
  1243. self.addMultipleSelectSession()
  1244. self.tableChatView.reloadData()
  1245. }
  1246. })
  1247. let info = UIAction(title: "Info".localized(), image: UIImage(systemName: "info.circle.fill"), handler: {(_) in
  1248. let messageInfoVC = MessageInfo()
  1249. messageInfoVC.data = dataMessages[indexPath!.row]
  1250. messageInfoVC.dataPerson = self.dataPerson
  1251. self.navigationController?.pushViewController(messageInfoVC, animated: true)
  1252. })
  1253. let delete = UIAction(title: "Delete".localized(), image: UIImage(systemName: "trash.fill"), attributes: .destructive, handler: {(_) in
  1254. if self.isSearching {
  1255. self.cancelAction()
  1256. }
  1257. DispatchQueue.main.asyncAfter(deadline: .now() + 0.35) {
  1258. self.deleteSession = true
  1259. let cancelButton = UIBarButtonItem(title: "Cancel".localized(), style: .plain, target: self, action: #selector(self.cancelAction))
  1260. cancelButton.setTitleTextAttributes([NSAttributedString.Key.foregroundColor: UIColor.white, NSAttributedString.Key.font: UIFont.systemFont(ofSize: 16)], for: .normal)
  1261. if self.dataPerson["f_pin"] != "-999" {
  1262. self.navigationItem.rightBarButtonItems = nil
  1263. }
  1264. self.navigationItem.rightBarButtonItem = cancelButton
  1265. self.changeAppBar()
  1266. let idx = self.dataMessages.firstIndex(where: { $0["message_id"] as? String == dataMessages[indexPath!.row]["message_id"] as? String})
  1267. if idx != nil{
  1268. self.dataMessages[idx!]["isSelected"] = true
  1269. }
  1270. self.addMultipleSelectSession()
  1271. self.tableChatView.reloadData()
  1272. }
  1273. })
  1274. var children: [UIMenuElement] = [copy, delete]
  1275. // let copyOption = self.copyOption(indexPath: indexPath!)
  1276. let idMe = User.getMyPin() as String?
  1277. // if (dataMessages[indexPath!.row]["lock"] != nil && dataMessages[indexPath!.row]["lock"] as! String == "1") || dataMessages[indexPath!.row]["message_scope_id"] as! String == "18" || dataPerson["f_pin"] == "-999" || dataMessages[indexPath!.row]["credential"] as! String == "1" {
  1278. // children = [delete]
  1279. // } else {
  1280. // if (dataMessages[indexPath!.row]["f_pin"] as! String) == idMe {
  1281. // children.insert(info, at: children.count - 1)
  1282. // }
  1283. // }
  1284. return UIContextMenuConfiguration(identifier: nil,
  1285. previewProvider: nil) { _ in
  1286. UIMenu(title: "", children: children)
  1287. }
  1288. }
  1289. @objc func cancelAction() {
  1290. DispatchQueue.main.async {
  1291. if self.copySession {
  1292. self.copySession = false
  1293. } else if self.deleteSession {
  1294. self.deleteSession = false
  1295. } else if self.isSearching {
  1296. self.countMatchesSearch = 0
  1297. self.isSearching = false
  1298. }
  1299. if self.viewTextField.isHidden {
  1300. self.viewTextField.isHidden = false
  1301. }
  1302. if self.constraintBottomTableViewWithTextfield.constant == -60.0 {
  1303. self.constraintBottomTableViewWithTextfield.constant = self.constraintBottomTableViewWithTextfield.constant + 70
  1304. DispatchQueue.main.asyncAfter(deadline: .now() + 0.3, execute: {
  1305. if (self.currentIndexpath != nil) {
  1306. self.tableChatView.scrollToRow(at: IndexPath(row: self.currentIndexpath!.row, section: self.currentIndexpath!.section), at: .none, animated: true)
  1307. } else {
  1308. self.tableChatView.scrollToBottom()
  1309. }
  1310. })
  1311. }
  1312. let data = self.dataMessages.filter({ $0["isSelected"] as! Bool == true })
  1313. for i in 0..<data.count {
  1314. let idx = self.dataMessages.firstIndex(where: { $0["message_id"] as? String == data[i]["message_id"] as? String})
  1315. if idx != nil{
  1316. self.dataMessages[idx!]["isSelected"] = false
  1317. }
  1318. }
  1319. self.tableChatView.reloadData()
  1320. self.setRightButtonItem()
  1321. self.changeAppBar()
  1322. if self.fromNotification {
  1323. let backButton = UIBarButtonItem(image: UIImage(systemName: "chevron.backward"), style: .plain, target: self, action: #selector(self.didTapExit))
  1324. self.navigationItem.leftBarButtonItem = backButton
  1325. }
  1326. self.containerMultpileSelectSession.removeFromSuperview()
  1327. self.checkNewMessage(tableView: self.tableChatView)
  1328. }
  1329. }
  1330. private func addMultipleSelectSession() {
  1331. viewTextField.isHidden = true
  1332. constraintBottomTableViewWithTextfield.constant = constraintBottomTableViewWithTextfield.constant - 70
  1333. view.addSubview(containerMultpileSelectSession)
  1334. containerMultpileSelectSession.translatesAutoresizingMaskIntoConstraints = false
  1335. constraintBottomContainerMultpileSelectSession = containerMultpileSelectSession.bottomAnchor.constraint(equalTo: self.view.bottomAnchor, constant: 0)
  1336. NSLayoutConstraint.activate([
  1337. containerMultpileSelectSession.leadingAnchor.constraint(equalTo: self.view.leadingAnchor),
  1338. containerMultpileSelectSession.trailingAnchor.constraint(equalTo: self.view.trailingAnchor),
  1339. constraintBottomContainerMultpileSelectSession,
  1340. containerMultpileSelectSession.heightAnchor.constraint(equalToConstant: 50)
  1341. ])
  1342. containerMultpileSelectSession.backgroundColor = .white
  1343. addSubviewMultipleSession()
  1344. }
  1345. private func addSubviewMultipleSession() {
  1346. let container = UIView()
  1347. containerMultpileSelectSession.addSubview(container)
  1348. container.translatesAutoresizingMaskIntoConstraints = false
  1349. NSLayoutConstraint.activate([
  1350. container.leadingAnchor.constraint(equalTo: containerMultpileSelectSession.leadingAnchor),
  1351. container.trailingAnchor.constraint(equalTo:containerMultpileSelectSession.trailingAnchor),
  1352. container.bottomAnchor.constraint(equalTo: containerMultpileSelectSession.bottomAnchor),
  1353. container.heightAnchor.constraint(equalToConstant: 50)
  1354. ])
  1355. container.layer.shadowOpacity = 0.7
  1356. container.layer.shadowOffset = CGSize(width: 3, height: 3)
  1357. container.layer.shadowRadius = 3.0
  1358. container.layer.shadowColor = UIColor.black.cgColor
  1359. container.backgroundColor = .secondaryColor
  1360. if !isSearching {
  1361. let title = UILabel()
  1362. container.addSubview(title)
  1363. title.translatesAutoresizingMaskIntoConstraints = false
  1364. NSLayoutConstraint.activate([
  1365. title.centerXAnchor.constraint(equalTo: container.centerXAnchor),
  1366. title.centerYAnchor.constraint(equalTo:container.centerYAnchor),
  1367. ])
  1368. let countSelected = dataMessages.filter({ $0["isSelected"] as! Bool == true }).count
  1369. title.text = "\(countSelected) " + "Selected".localized()
  1370. title.textColor = .mainColor
  1371. title.font = UIFont.systemFont(ofSize: 15.0).bold
  1372. let button = UIImageView()
  1373. container.addSubview(button)
  1374. button.translatesAutoresizingMaskIntoConstraints = false
  1375. NSLayoutConstraint.activate([
  1376. button.leadingAnchor.constraint(equalTo: container.leadingAnchor, constant: 15),
  1377. button.centerYAnchor.constraint(equalTo:container.centerYAnchor),
  1378. button.widthAnchor.constraint(equalToConstant: 30),
  1379. button.heightAnchor.constraint(equalToConstant: 30),
  1380. ])
  1381. if copySession {
  1382. button.image = UIImage(systemName: "doc.on.doc")
  1383. if countSelected == 0 {
  1384. button.tintColor = .gray
  1385. } else {
  1386. button.tintColor = .mainColor
  1387. }
  1388. } else if deleteSession {
  1389. button.image = UIImage(systemName: "trash")
  1390. if countSelected == 0 {
  1391. button.tintColor = .gray
  1392. } else {
  1393. button.tintColor = .red
  1394. }
  1395. }
  1396. let buttonGesture = UITapGestureRecognizer(target: self, action: #selector(sessionAction))
  1397. button.isUserInteractionEnabled = true
  1398. button.addGestureRecognizer(buttonGesture)
  1399. } else {
  1400. buttonUp = UIButton()
  1401. container.addSubview(buttonUp)
  1402. buttonUp.translatesAutoresizingMaskIntoConstraints = false
  1403. NSLayoutConstraint.activate([
  1404. buttonUp.leadingAnchor.constraint(equalTo: container.leadingAnchor, constant: 10),
  1405. buttonUp.centerYAnchor.constraint(equalTo:container.centerYAnchor),
  1406. buttonUp.widthAnchor.constraint(equalToConstant: 30),
  1407. buttonUp.heightAnchor.constraint(equalToConstant: 30),
  1408. ])
  1409. buttonUp.addTarget(self, action: #selector(upSearchText), for: .touchUpInside)
  1410. buttonDown = UIButton()
  1411. container.addSubview(buttonDown)
  1412. buttonDown.translatesAutoresizingMaskIntoConstraints = false
  1413. NSLayoutConstraint.activate([
  1414. buttonDown.leadingAnchor.constraint(equalTo: buttonUp.trailingAnchor, constant: 15),
  1415. buttonDown.centerYAnchor.constraint(equalTo:container.centerYAnchor),
  1416. buttonDown.widthAnchor.constraint(equalToConstant: 30),
  1417. buttonDown.heightAnchor.constraint(equalToConstant: 30),
  1418. ])
  1419. buttonDown.addTarget(self, action: #selector(downSearchText), for: .touchUpInside)
  1420. buttonUp.setImage(UIImage(systemName: "chevron.up"), for: .normal)
  1421. buttonUp.tintColor = .gray
  1422. buttonDown.setImage(UIImage(systemName: "chevron.down"), for: .normal)
  1423. buttonDown.tintColor = .gray
  1424. titleSearchMatches = UILabel()
  1425. container.addSubview(titleSearchMatches)
  1426. titleSearchMatches.translatesAutoresizingMaskIntoConstraints = false
  1427. NSLayoutConstraint.activate([
  1428. titleSearchMatches.centerXAnchor.constraint(equalTo: container.centerXAnchor),
  1429. titleSearchMatches.centerYAnchor.constraint(equalTo:container.centerYAnchor),
  1430. ])
  1431. titleSearchMatches.textColor = .mainColor
  1432. titleSearchMatches.font = UIFont.systemFont(ofSize: 15.0).bold
  1433. titleSearchMatches.isHidden = true
  1434. DispatchQueue.main.asyncAfter(deadline: .now() + 0.3, execute: {
  1435. self.searchBar.becomeFirstResponder()
  1436. })
  1437. }
  1438. }
  1439. @objc func upSearchText() {
  1440. scrollToFirstSearchMessage(indexScroll: lastScrollIdxSearch + 1)
  1441. }
  1442. @objc func downSearchText() {
  1443. scrollToFirstSearchMessage(indexScroll: lastScrollIdxSearch - 1)
  1444. }
  1445. @objc func sessionAction() {
  1446. if copySession {
  1447. let dataMessages = self.dataMessages.filter({ $0["isSelected"] as! Bool == true })
  1448. let countSelected = dataMessages.count
  1449. if countSelected == 0 {
  1450. return
  1451. }
  1452. var text = ""
  1453. for i in 0..<countSelected {
  1454. let stringDate = (dataMessages[i]["server_date"] as! String)
  1455. let date = Date(milliseconds: Int64(stringDate)!)
  1456. let formatterDate = DateFormatter()
  1457. let formatterTime = DateFormatter()
  1458. formatterDate.dateFormat = "dd/MM/yy"
  1459. formatterDate.locale = NSLocale(localeIdentifier: "id") as Locale?
  1460. formatterTime.dateFormat = "HH:mm"
  1461. formatterTime.locale = NSLocale(localeIdentifier: "id") as Locale?
  1462. let dataProfile = getDataProfile(message_id: dataMessages[i]["message_id"] as! String)
  1463. if text.isEmpty {
  1464. text = "*[\(formatterDate.string(from: date as Date)) \(formatterTime.string(from: date as Date))] \(dataProfile["name"]!):*\n\(dataMessages[i]["message_text"] as! String)"
  1465. } else {
  1466. 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)"
  1467. }
  1468. }
  1469. text = text + "\n\n\nchat " + "Powered by Nexilis".localized()
  1470. DispatchQueue.main.async {
  1471. UIPasteboard.general.string = text
  1472. self.showToast(message: "Text coppied to clipboard".localized(), font: UIFont.systemFont(ofSize: 12, weight: .medium), controller: self)
  1473. }
  1474. cancelAction()
  1475. } else if deleteSession {
  1476. let dataMessages = self.dataMessages.filter({ $0["isSelected"] as! Bool == true })
  1477. var countSelected = dataMessages.count
  1478. if countSelected == 0 {
  1479. return
  1480. }
  1481. let alertController = LibAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
  1482. if let action = self.actionDelete(for: "me", title: "Delete".localized() + " \(countSelected) " + "For Me".localized(), dataMessages: dataMessages) {
  1483. alertController.addAction(action)
  1484. }
  1485. let idMe = User.getMyPin() as String?
  1486. let dataFilterFpin = dataMessages.filter({ $0["l_pin"] as? String == idMe})
  1487. let dataFilterLock = dataMessages.filter({ $0["lock"] as? String == "1" || $0["lock"] as? String == "2" })
  1488. let statusDataRead = dataMessages.filter({ Int($0["status"] as! String)! >= 4})
  1489. if dataFilterFpin.count == 0 && dataFilterLock.count == 0 && statusDataRead.count == 0 {
  1490. if let action = self.actionDelete(for: "everyone", title: "Delete".localized() + " \(countSelected) " + "For Everyone".localized(), dataMessages: dataMessages) {
  1491. alertController.addAction(action)
  1492. }
  1493. }
  1494. alertController.addAction(UIAlertAction(title: "Cancel".localized(), style: .cancel, handler: nil))
  1495. self.present(alertController, animated: true)
  1496. }
  1497. }
  1498. private func getDataProfile(message_id: String) -> [String: String]{
  1499. var data: [String: String] = [:]
  1500. Database().database?.inTransaction({ fmdb, rollback in
  1501. if let c = Database().getRecords(fmdb: fmdb, query: "select f_display_name from MESSAGE where message_id = '\(message_id)'"), c.next() {
  1502. data["name"] = c.string(forColumnIndex: 0)!
  1503. c.close()
  1504. } else {
  1505. data["name"] = "Unknown".localized()
  1506. data["image_id"] = ""
  1507. }
  1508. })
  1509. return data
  1510. }
  1511. private func deleteMessage(l_pin: String, message_id: String, scope: String, type: String, chat: String) {
  1512. let tmessage = CoreMessage_TMessageBank.deleteMessage(l_pin: l_pin, messageId: message_id, scope: scope, type: type, chat: chat)
  1513. Nexilis.deleteQueueMessage(message: tmessage)
  1514. }
  1515. @objc func segmentedControlValueChanged(_ sender: segmentedControllerObject) {
  1516. switch sender.selectedSegmentIndex {
  1517. case 0:
  1518. sender.navigation.viewControllers[0].children[1].view.isHidden = true
  1519. break;
  1520. case 1:
  1521. sender.navigation.viewControllers[0].children[1].view.isHidden = false
  1522. break;
  1523. default:
  1524. break;
  1525. }
  1526. }
  1527. private func copyOption(indexPath: IndexPath) -> UIMenu {
  1528. var ratingButtonTitles = ["Text".localized(), "Image".localized()]
  1529. if (dataMessages[indexPath.row]["message_text"] as! String).isEmpty {
  1530. ratingButtonTitles = ["Image".localized()]
  1531. }
  1532. let dataMessages = self.dataMessages.filter({ $0["chat_date"] as! String == dataDates[indexPath.section]})
  1533. let copyActions = ratingButtonTitles
  1534. .enumerated()
  1535. .map { index, title in
  1536. return UIAction(
  1537. title: title,
  1538. identifier: nil,
  1539. handler: {(_) in
  1540. if (dataMessages[indexPath.row]["message_text"] as! String).isEmpty {
  1541. DispatchQueue.main.async {
  1542. let nsDocumentDirectory = FileManager.SearchPathDirectory.documentDirectory
  1543. let nsUserDomainMask = FileManager.SearchPathDomainMask.userDomainMask
  1544. let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true)
  1545. if let dirPath = paths.first {
  1546. let imageURL = URL(fileURLWithPath: dirPath).appendingPathComponent(dataMessages[indexPath.row]["image_id"] as! String)
  1547. if FileManager.default.fileExists(atPath: imageURL.path) || FileEncryption.shared.isSecureExists(filename: imageURL.lastPathComponent) {
  1548. if FileManager.default.fileExists(atPath: imageURL.path) {
  1549. let image = UIImage(contentsOfFile: imageURL.path)
  1550. UIPasteboard.general.image = image
  1551. self.showToast(message: "Image coppied to clipboard".localized(), font: UIFont.systemFont(ofSize: 12, weight: .medium), controller: self)
  1552. }
  1553. else if FileEncryption.shared.isSecureExists(filename: imageURL.lastPathComponent) {
  1554. do {
  1555. if let imageData = try FileEncryption.shared.readSecure(filename: imageURL.lastPathComponent) {
  1556. let image = UIImage(data: imageData)
  1557. UIPasteboard.general.image = image
  1558. self.showToast(message: "Image coppied to clipboard".localized(), font: UIFont.systemFont(ofSize: 12, weight: .medium), controller: self)
  1559. }
  1560. } catch {
  1561. }
  1562. }
  1563. }
  1564. }
  1565. }
  1566. return
  1567. }
  1568. if (index == 0) {
  1569. DispatchQueue.main.async {
  1570. UIPasteboard.general.string = dataMessages[indexPath.row]["message_text"] as? String
  1571. self.showToast(message: "Text coppied to clipboard".localized(), font: UIFont.systemFont(ofSize: 12, weight: .medium), controller: self)
  1572. }
  1573. } else {
  1574. DispatchQueue.main.async {
  1575. let nsDocumentDirectory = FileManager.SearchPathDirectory.documentDirectory
  1576. let nsUserDomainMask = FileManager.SearchPathDomainMask.userDomainMask
  1577. let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true)
  1578. if let dirPath = paths.first {
  1579. let imageURL = URL(fileURLWithPath: dirPath).appendingPathComponent(dataMessages[indexPath.row]["image_id"] as! String)
  1580. if FileManager.default.fileExists(atPath: imageURL.path) || FileEncryption.shared.isSecureExists(filename: imageURL.lastPathComponent ) {
  1581. if FileManager.default.fileExists(atPath: imageURL.path) {
  1582. let image = UIImage(contentsOfFile: imageURL.path)
  1583. UIPasteboard.general.image = image
  1584. self.showToast(message: "Image coppied to clipboard".localized(), font: UIFont.systemFont(ofSize: 12, weight: .medium), controller: self)
  1585. }
  1586. else if FileEncryption.shared.isSecureExists(filename: imageURL.lastPathComponent) {
  1587. do {
  1588. if let imageData = try FileEncryption.shared.readSecure(filename: imageURL.lastPathComponent) {
  1589. let image = UIImage(data: imageData)
  1590. UIPasteboard.general.image = image
  1591. self.showToast(message: "Image coppied to clipboard".localized(), font: UIFont.systemFont(ofSize: 12, weight: .medium), controller: self)
  1592. }
  1593. } catch {
  1594. }
  1595. }
  1596. }
  1597. }
  1598. }
  1599. }
  1600. self.dismissKeyboard()
  1601. })
  1602. }
  1603. return UIMenu(
  1604. title: "Copy".localized(),
  1605. image: UIImage(systemName: "doc.on.doc.fill"),
  1606. children: copyActions)
  1607. }
  1608. private func actionDelete(for type: String, title: String, dataMessages: [[String: Any?]]) -> UIAlertAction? {
  1609. return UIAlertAction(title: title, style: .destructive) { [unowned self] _ in
  1610. for i in 0..<dataMessages.count {
  1611. if (type == "me") {
  1612. self.deleteMessage(l_pin: dataMessages[i]["l_pin"] as! String, message_id: dataMessages[i]["message_id"] as! String, scope: "3", type: "1", chat: "")
  1613. let idx = self.dataMessages.firstIndex(where: { $0["message_id"] as? String == dataMessages[i]["message_id"] as? String})
  1614. if idx != nil {
  1615. self.dataMessages.remove(at: idx!)
  1616. if (idx == self.dataMessages.count - 1) {
  1617. NotificationCenter.default.post(name: NSNotification.Name(rawValue: "reloadTabChats"), object: nil, userInfo: nil)
  1618. }
  1619. for i in 0..<dataDates.count {
  1620. if self.dataMessages.filter({ $0["chat_date"] as! String == dataDates[i] }).count == 0 {
  1621. dataDates.remove(at: i)
  1622. }
  1623. }
  1624. }
  1625. } else {
  1626. self.deleteMessage(l_pin: dataMessages[i]["l_pin"] as! String, message_id: dataMessages[i]["message_id"] as! String, scope: "3", type: "2", chat: "")
  1627. let idx = self.dataMessages.firstIndex(where: { $0["message_id"] as? String == dataMessages[i]["message_id"] as? String})
  1628. if idx != nil {
  1629. self.dataMessages[idx!]["lock"] = "1"
  1630. self.dataMessages[idx!]["attachment_flag"] = "0"
  1631. self.dataMessages[idx!]["reff_id"] = ""
  1632. }
  1633. }
  1634. }
  1635. cancelAction()
  1636. }
  1637. }
  1638. private func updateProfile() {
  1639. let idMe = User.getMyPin() as String?
  1640. DispatchQueue.global().async {
  1641. let message = CoreMessage_TMessageBank.getBatchBuddiesInfos(p_f_pin: idMe!, last_update: 0)
  1642. let _ = Nexilis.write(message: message)
  1643. }
  1644. }
  1645. private func generateQRCode(from string: String) -> UIImage? {
  1646. let data = string.data(using: String.Encoding.ascii)
  1647. if let filter = CIFilter(name: "CIQRCodeGenerator") {
  1648. filter.setValue(data, forKey: "inputMessage")
  1649. let transform = CGAffineTransform(scaleX: 3, y: 3)
  1650. if let output = filter.outputImage?.transformed(by: transform) {
  1651. return UIImage(ciImage: output)
  1652. }
  1653. }
  1654. return nil
  1655. }
  1656. }
  1657. extension ChatGPTBotView: UITableViewDelegate, UITableViewDataSource {
  1658. // public func tableView(_ tableView: UITableView, didEndDisplaying cell: UITableViewCell, forRowAt indexPath: IndexPath) {
  1659. // checkNewMessage(tableView: tableView)
  1660. // }
  1661. public func tableView(_ tableView: UITableView, didEndDisplaying cell: UITableViewCell, forRowAt indexPath: IndexPath) {
  1662. if self.tableChatView.alpha != 1.0 {
  1663. UIView.animate(withDuration: 0.5, animations: {
  1664. self.tableChatView.alpha = 1.0
  1665. })
  1666. }
  1667. }
  1668. public func scrollViewDidScroll(_ scrollView: UIScrollView) {
  1669. lastY = scrollView.contentOffset.y
  1670. DispatchQueue.main.async { [self] in
  1671. checkNewMessage(tableView: self.tableChatView)
  1672. }
  1673. }
  1674. public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
  1675. let dataMessages = self.dataMessages.filter({ $0["chat_date"] as! String == dataDates[indexPath.section] })
  1676. if copySession || deleteSession {
  1677. if (dataMessages[indexPath.row]["attachment_flag"] as! String != "0" || dataMessages[indexPath.row]["lock"] as? String == "1") && !deleteSession {
  1678. return
  1679. }
  1680. let idx = self.dataMessages.firstIndex(where: { $0["message_id"] as? String == dataMessages[indexPath.row]["message_id"] as? String})
  1681. if idx != nil {
  1682. self.dataMessages[idx!]["isSelected"] = !(self.dataMessages[idx!]["isSelected"] as! Bool)
  1683. self.tableChatView.reloadRows(at: [indexPath], with: .none)
  1684. }
  1685. containerMultpileSelectSession.subviews.forEach({ $0.removeFromSuperview() })
  1686. addSubviewMultipleSession()
  1687. return
  1688. }
  1689. let message = dataMessages[indexPath.row]
  1690. }
  1691. public func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
  1692. let containerView = UIView()
  1693. containerView.backgroundColor = .clear
  1694. let dateView = UIView()
  1695. containerView.addSubview(dateView)
  1696. dateView.translatesAutoresizingMaskIntoConstraints = false
  1697. var topAnchor = dateView.topAnchor.constraint(equalTo: containerView.topAnchor)
  1698. topAnchor = dateView.topAnchor.constraint(equalTo: containerView.topAnchor, constant: 10.0)
  1699. NSLayoutConstraint.activate([
  1700. topAnchor,
  1701. dateView.bottomAnchor.constraint(equalTo: containerView.bottomAnchor),
  1702. dateView.centerXAnchor.constraint(equalTo: containerView.centerXAnchor),
  1703. dateView.heightAnchor.constraint(equalToConstant: 30),
  1704. dateView.widthAnchor.constraint(greaterThanOrEqualToConstant: 60)
  1705. ])
  1706. dateView.backgroundColor = .orangeColor
  1707. dateView.layer.cornerRadius = 15.0
  1708. dateView.clipsToBounds = true
  1709. let labelDate = UILabel()
  1710. dateView.addSubview(labelDate)
  1711. labelDate.translatesAutoresizingMaskIntoConstraints = false
  1712. NSLayoutConstraint.activate([
  1713. labelDate.centerYAnchor.constraint(equalTo: dateView.centerYAnchor),
  1714. labelDate.centerXAnchor.constraint(equalTo: dateView.centerXAnchor),
  1715. labelDate.leadingAnchor.constraint(equalTo: dateView.leadingAnchor, constant: 10),
  1716. labelDate.trailingAnchor.constraint(equalTo: dateView.trailingAnchor, constant: -10),
  1717. ])
  1718. labelDate.textAlignment = .center
  1719. labelDate.textColor = .secondaryColor
  1720. labelDate.font = UIFont.systemFont(ofSize: 12, weight: .medium)
  1721. labelDate.text = dataDates[section]
  1722. if listViewOnSection.count == 0 || listViewOnSection.count - 1 < section {
  1723. listViewOnSection.append(containerView)
  1724. } else {
  1725. listViewOnSection.remove(at: section)
  1726. listViewOnSection.insert(containerView, at: section)
  1727. }
  1728. return containerView
  1729. }
  1730. public func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
  1731. return 40
  1732. }
  1733. public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
  1734. let idMe = User.getMyPin() as String?
  1735. let dataMessages = dataMessages.filter({$0["chat_date"] as! String == dataDates[indexPath.section]})
  1736. let profileMessage = UIImageView()
  1737. let cell = tableView.dequeueReusableCell(withIdentifier: "cellEditorPersonal", for: indexPath as IndexPath)
  1738. cell.contentView.subviews.forEach({ $0.removeFromSuperview() })
  1739. let messageIdChat = (dataMessages[indexPath.row]["message_id"] as? String) ?? ""
  1740. cell.backgroundColor = .clear
  1741. cell.selectionStyle = .none
  1742. let nameSender = UILabel()
  1743. let containerMessage = UIView()
  1744. cell.contentView.addSubview(containerMessage)
  1745. containerMessage.translatesAutoresizingMaskIntoConstraints = false
  1746. let timeMessage = UILabel()
  1747. cell.contentView.addSubview(timeMessage)
  1748. timeMessage.translatesAutoresizingMaskIntoConstraints = false
  1749. if (dataMessages[indexPath.row]["read_receipts"] as? String) == "8" || ((dataMessages[indexPath.row]["credential"] as? String) == "1" && dataMessages[indexPath.row]["lock"] as? String != "2") {
  1750. timeMessage.bottomAnchor.constraint(equalTo: cell.contentView.bottomAnchor, constant: -40).isActive = true
  1751. } else {
  1752. timeMessage.bottomAnchor.constraint(equalTo: cell.contentView.bottomAnchor, constant: -5).isActive = true
  1753. }
  1754. let statusMessage = UIImageView()
  1755. if (dataMessages[indexPath.row]["f_pin"] as? String == idMe) {
  1756. containerMessage.leadingAnchor.constraint(greaterThanOrEqualTo: cell.contentView.leadingAnchor, constant: 60).isActive = true
  1757. if (dataMessages[indexPath.row]["read_receipts"] as? String) == "8" || ((dataMessages[indexPath.row]["credential"] as? String) == "1" && dataMessages[indexPath.row]["lock"] as? String != "2") {
  1758. containerMessage.bottomAnchor.constraint(equalTo: cell.contentView.bottomAnchor, constant: -40).isActive = true
  1759. } else {
  1760. containerMessage.bottomAnchor.constraint(equalTo: cell.contentView.bottomAnchor, constant: -5).isActive = true
  1761. }
  1762. containerMessage.topAnchor.constraint(equalTo: cell.contentView.topAnchor, constant: 5).isActive = true
  1763. containerMessage.trailingAnchor.constraint(equalTo: cell.contentView.trailingAnchor, constant: -15).isActive = true
  1764. containerMessage.widthAnchor.constraint(greaterThanOrEqualToConstant: 46).isActive = true
  1765. if (dataMessages[indexPath.row]["attachment_flag"] as? String == "11" && dataMessages[indexPath.row]["reff_id"]as? String == "") {
  1766. containerMessage.backgroundColor = .clear
  1767. } else {
  1768. containerMessage.backgroundColor = .blueBubbleColor
  1769. }
  1770. containerMessage.layer.cornerRadius = 10.0
  1771. containerMessage.layer.maskedCorners = [.layerMinXMaxYCorner, .layerMaxXMaxYCorner, .layerMinXMinYCorner]
  1772. containerMessage.clipsToBounds = true
  1773. timeMessage.trailingAnchor.constraint(equalTo: containerMessage.leadingAnchor, constant: -8).isActive = true
  1774. if (dataMessages[indexPath.row]["lock"] == nil || dataMessages[indexPath.row]["lock"] as! String == "0") && (dataMessages[indexPath.row]["lock"] as? String != "2") {
  1775. cell.contentView.addSubview(statusMessage)
  1776. statusMessage.translatesAutoresizingMaskIntoConstraints = false
  1777. statusMessage.bottomAnchor.constraint(equalTo: timeMessage.topAnchor).isActive = true
  1778. statusMessage.trailingAnchor.constraint(equalTo: containerMessage.leadingAnchor, constant: -8).isActive = true
  1779. statusMessage.widthAnchor.constraint(equalToConstant: 15).isActive = true
  1780. statusMessage.heightAnchor.constraint(equalToConstant: 15).isActive = true
  1781. if (dataMessages[indexPath.row]["status"]! as! String == "1" || dataMessages[indexPath.row]["status"]! as! String == "2" ) {
  1782. statusMessage.image = UIImage(named: "checklist", in: Bundle.resourceBundle(for: Nexilis.self), with: nil)!.withTintColor(UIColor.lightGray)
  1783. } else if (dataMessages[indexPath.row]["status"]! as! String == "3") {
  1784. statusMessage.image = UIImage(named: "double-checklist", in: Bundle.resourceBundle(for: Nexilis.self), with: nil)!.withTintColor(UIColor.lightGray)
  1785. } else if (dataMessages[indexPath.row]["status"]! as! String == "8") {
  1786. statusMessage.image = UIImage(named: "message_status_ack", in: Bundle.resourceBundle(for: Nexilis.self), with: nil)!.withRenderingMode(.alwaysOriginal)
  1787. } else {
  1788. statusMessage.image = UIImage(named: "double-checklist", in: Bundle.resourceBundle(for: Nexilis.self), with: nil)!.withTintColor(UIColor.systemBlue)
  1789. }
  1790. }
  1791. } else {
  1792. if markerCounter != nil && dataMessages[indexPath.row]["message_id"] as? String == markerCounter {
  1793. containerMessage.topAnchor.constraint(equalTo: cell.contentView.topAnchor, constant: 35).isActive = true
  1794. let newMessagesView = UIView()
  1795. cell.contentView.addSubview(newMessagesView)
  1796. newMessagesView.translatesAutoresizingMaskIntoConstraints = false
  1797. NSLayoutConstraint.activate([
  1798. newMessagesView.topAnchor.constraint(equalTo: newMessagesView.topAnchor),
  1799. newMessagesView.bottomAnchor.constraint(equalTo: containerMessage.topAnchor),
  1800. newMessagesView.centerXAnchor.constraint(equalTo: cell.contentView.centerXAnchor),
  1801. newMessagesView.heightAnchor.constraint(equalToConstant: 30),
  1802. newMessagesView.widthAnchor.constraint(greaterThanOrEqualToConstant: 60)
  1803. ])
  1804. newMessagesView.backgroundColor = .greenColor
  1805. newMessagesView.layer.cornerRadius = 15.0
  1806. newMessagesView.clipsToBounds = true
  1807. let labelNewMessages = UILabel()
  1808. newMessagesView.addSubview(labelNewMessages)
  1809. labelNewMessages.translatesAutoresizingMaskIntoConstraints = false
  1810. NSLayoutConstraint.activate([
  1811. labelNewMessages.centerYAnchor.constraint(equalTo: newMessagesView.centerYAnchor),
  1812. labelNewMessages.centerXAnchor.constraint(equalTo: newMessagesView.centerXAnchor),
  1813. labelNewMessages.leadingAnchor.constraint(equalTo: newMessagesView.leadingAnchor, constant: 10),
  1814. labelNewMessages.trailingAnchor.constraint(equalTo: newMessagesView.trailingAnchor, constant: -10),
  1815. ])
  1816. labelNewMessages.textAlignment = .center
  1817. labelNewMessages.textColor = .secondaryColor
  1818. labelNewMessages.font = UIFont.systemFont(ofSize: 12, weight: .medium)
  1819. labelNewMessages.text = "Unread Messages".localized()
  1820. } else {
  1821. containerMessage.topAnchor.constraint(equalTo: cell.contentView.topAnchor, constant: 5).isActive = true
  1822. }
  1823. if copySession || deleteSession {
  1824. containerMessage.leadingAnchor.constraint(equalTo: cell.contentView.leadingAnchor, constant: 50).isActive = true
  1825. } else {
  1826. containerMessage.leadingAnchor.constraint(equalTo: cell.contentView.leadingAnchor, constant: 15).isActive = true
  1827. }
  1828. if (dataMessages[indexPath.row]["read_receipts"] as? String) == "8" || ((dataMessages[indexPath.row]["credential"] as? String) == "1" && dataMessages[indexPath.row]["lock"] as? String != "2") {
  1829. containerMessage.bottomAnchor.constraint(equalTo: cell.contentView.bottomAnchor, constant: -40).isActive = true
  1830. } else {
  1831. containerMessage.bottomAnchor.constraint(equalTo: cell.contentView.bottomAnchor, constant: -5).isActive = true
  1832. }
  1833. containerMessage.trailingAnchor.constraint(lessThanOrEqualTo: cell.contentView.trailingAnchor, constant: -60).isActive = true
  1834. containerMessage.widthAnchor.constraint(greaterThanOrEqualToConstant: 46).isActive = true
  1835. 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") {
  1836. containerMessage.backgroundColor = .clear
  1837. } else {
  1838. containerMessage.backgroundColor = .whiteBubbleColor
  1839. }
  1840. containerMessage.layer.cornerRadius = 10.0
  1841. containerMessage.layer.maskedCorners = [.layerMinXMaxYCorner, .layerMaxXMinYCorner, .layerMaxXMaxYCorner]
  1842. containerMessage.clipsToBounds = true
  1843. timeMessage.leadingAnchor.constraint(equalTo: containerMessage.trailingAnchor, constant: 8).isActive = true
  1844. }
  1845. let imageStared = UIImageView()
  1846. if dataMessages[indexPath.row]["is_stared"] as? String == "1" && (dataMessages[indexPath.row]["lock"] == nil || dataMessages[indexPath.row]["lock"] as! String == "0") {
  1847. cell.contentView.addSubview(imageStared)
  1848. imageStared.translatesAutoresizingMaskIntoConstraints = false
  1849. if (dataMessages[indexPath.row]["f_pin"] as? String == idMe) {
  1850. imageStared.bottomAnchor.constraint(equalTo: statusMessage.topAnchor).isActive = true
  1851. imageStared.trailingAnchor.constraint(equalTo: containerMessage.leadingAnchor, constant: -8).isActive = true
  1852. } else {
  1853. imageStared.bottomAnchor.constraint(equalTo: timeMessage.topAnchor).isActive = true
  1854. imageStared.leadingAnchor.constraint(equalTo: containerMessage.trailingAnchor, constant: 8).isActive = true
  1855. }
  1856. imageStared.widthAnchor.constraint(equalToConstant: 15).isActive = true
  1857. imageStared.heightAnchor.constraint(equalToConstant: 15).isActive = true
  1858. imageStared.image = UIImage(systemName: "star.fill")
  1859. imageStared.backgroundColor = .clear
  1860. imageStared.tintColor = .systemYellow
  1861. }
  1862. if dataMessages[indexPath.row]["read_receipts"] as? String == "8" {
  1863. let imageAckView = UIImageView()
  1864. var imageAck = UIImage(named: "ack_icon_gray", in: Bundle.resourceBundle(for: Nexilis.self), with: nil)!.withRenderingMode(.alwaysOriginal)
  1865. if dataMessages[indexPath.row]["status"] as? String == "8" {
  1866. imageAck = UIImage(named: "ack_icon", in: Bundle.resourceBundle(for: Nexilis.self), with: nil)!.withRenderingMode(.alwaysOriginal)
  1867. }
  1868. imageAckView.image = imageAck
  1869. cell.contentView.addSubview(imageAckView)
  1870. imageAckView.translatesAutoresizingMaskIntoConstraints = false
  1871. imageAckView.widthAnchor.constraint(equalToConstant: 30).isActive = true
  1872. imageAckView.heightAnchor.constraint(equalToConstant: 30).isActive = true
  1873. if (dataMessages[indexPath.row]["f_pin"] as? String == idMe) {
  1874. imageAckView.topAnchor.constraint(equalTo: containerMessage.bottomAnchor, constant: 5).isActive = true
  1875. imageAckView.trailingAnchor.constraint(equalTo: containerMessage.leadingAnchor, constant: 30).isActive = true
  1876. } else {
  1877. imageAckView.topAnchor.constraint(equalTo: containerMessage.bottomAnchor, constant: 5).isActive = true
  1878. imageAckView.leadingAnchor.constraint(equalTo: containerMessage.trailingAnchor, constant: -30).isActive = true
  1879. let tap = ObjectGesture(target: self, action: #selector(tapAck(_:)))
  1880. tap.indexPath = indexPath
  1881. imageAckView.addGestureRecognizer(tap)
  1882. imageAckView.isUserInteractionEnabled = true
  1883. }
  1884. }
  1885. if (dataMessages[indexPath.row]["credential"] as? String) == "1" && (dataMessages[indexPath.row]["lock"] as? String) != "2" {
  1886. let imageCredentialView = UIImageView()
  1887. let imageCredential = UIImage(named: "confidential_icon", in: Bundle.resourceBundle(for: Nexilis.self), with: nil)!.withRenderingMode(.alwaysOriginal)
  1888. imageCredentialView.image = imageCredential
  1889. cell.contentView.addSubview(imageCredentialView)
  1890. imageCredentialView.translatesAutoresizingMaskIntoConstraints = false
  1891. imageCredentialView.widthAnchor.constraint(equalToConstant: 30).isActive = true
  1892. imageCredentialView.heightAnchor.constraint(equalToConstant: 30).isActive = true
  1893. if (dataMessages[indexPath.row]["f_pin"] as? String == idMe) {
  1894. imageCredentialView.topAnchor.constraint(equalTo: containerMessage.bottomAnchor, constant: 5).isActive = true
  1895. imageCredentialView.trailingAnchor.constraint(equalTo: containerMessage.leadingAnchor, constant: 30).isActive = true
  1896. } else {
  1897. imageCredentialView.topAnchor.constraint(equalTo: containerMessage.bottomAnchor, constant: 5).isActive = true
  1898. imageCredentialView.leadingAnchor.constraint(equalTo: containerMessage.trailingAnchor, constant: -30).isActive = true
  1899. }
  1900. }
  1901. let messageText = UILabel()
  1902. messageText.numberOfLines = 0
  1903. messageText.lineBreakMode = .byWordWrapping
  1904. containerMessage.addSubview(messageText)
  1905. messageText.translatesAutoresizingMaskIntoConstraints = false
  1906. let topMarginText = messageText.topAnchor.constraint(equalTo: containerMessage.topAnchor, constant: 15)
  1907. topMarginText.isActive = true
  1908. messageText.textColor = self.traitCollection.userInterfaceStyle == .dark ? .white : .black
  1909. messageText.font = .systemFont(ofSize: 12)
  1910. messageText.leadingAnchor.constraint(equalTo: containerMessage.leadingAnchor, constant: 15).isActive = true
  1911. if dataMessages[indexPath.row]["f_pin"] as? String == "-999" && (dataMessages[indexPath.row]["blog_id"] as? String) != nil && !(dataMessages[indexPath.row]["blog_id"] as! String).isEmpty && (dataMessages[indexPath.row]["message_text"] as! String).contains("Berikut QR Code dan detil booking Anda") {
  1912. messageText.bottomAnchor.constraint(equalTo: containerMessage.bottomAnchor, constant: -115).isActive = true
  1913. let imageQR = UIImageView()
  1914. containerMessage.addSubview(imageQR)
  1915. imageQR.translatesAutoresizingMaskIntoConstraints = false
  1916. NSLayoutConstraint.activate([
  1917. imageQR.centerXAnchor.constraint(equalTo: containerMessage.centerXAnchor),
  1918. imageQR.topAnchor.constraint(equalTo: messageText.bottomAnchor),
  1919. imageQR.widthAnchor.constraint(equalToConstant: 100.0),
  1920. imageQR.heightAnchor.constraint(equalToConstant: 100.0)
  1921. ])
  1922. imageQR.image = generateQRCode(from: dataMessages[indexPath.row]["blog_id"] as! String)
  1923. } else {
  1924. messageText.bottomAnchor.constraint(equalTo: containerMessage.bottomAnchor, constant: -15).isActive = true
  1925. }
  1926. messageText.trailingAnchor.constraint(equalTo: containerMessage.trailingAnchor, constant: -15).isActive = true
  1927. var textChat = (dataMessages[indexPath.row]["message_text"] as? String) ?? ""
  1928. if (dataMessages[indexPath.row]["lock"] != nil && (dataMessages[indexPath.row]["lock"])! as? String == "1") {
  1929. if (dataMessages[indexPath.row]["f_pin"] as? String == idMe) {
  1930. textChat = "🚫 _"+"You were deleted this message".localized()+"_"
  1931. } else {
  1932. textChat = "🚫 _"+"This message was deleted".localized()+"_"
  1933. }
  1934. }
  1935. if dataMessages[indexPath.row]["lock"] as? String == "2" {
  1936. textChat = "🚫 _"+"Message has expired".localized()+"_"
  1937. }
  1938. let imageSticker = UIImageView()
  1939. if let attachmentFlag = dataMessages[indexPath.row]["attachment_flag"], let attachmentFlag = attachmentFlag as? String {
  1940. if attachmentFlag == "27" || attachmentFlag == "26" { // live streaming
  1941. let data = textChat
  1942. if let json = try! JSONSerialization.jsonObject(with: data.data(using: String.Encoding.utf8)!, options: []) as? [String: Any] {
  1943. Database().database?.inTransaction({ fmdb, rollback in
  1944. let title = json["title"] as? String ?? ""
  1945. let description = json["description"] as? String ?? ""
  1946. let start = json["time"] as? Int64 ?? 0
  1947. let by = json["by"] as? String ?? ""
  1948. let textLS = "Live Streaming".localized()
  1949. var type = "*\(textLS)*"
  1950. if attachmentFlag == "26" {
  1951. let textSeminar = "Seminar".localized()
  1952. type = "*\(textSeminar)*"
  1953. }
  1954. if let c = Database().getRecords(fmdb: fmdb, query: "select first_name || ' ' || last_name from BUDDY where f_pin = '\(by)'"), c.next() {
  1955. let name = c.string(forColumnIndex: 0)!
  1956. messageText.attributedText = "\(type) \nTitle: \(title) \nDescription: \(description) \nStart: \(Date(milliseconds: start).format(dateFormat: "dd/MM/yyyy HH:mm")) \nBroadcaster: \(name)".richText()
  1957. c.close()
  1958. } else {
  1959. messageText.attributedText = ("\(type) \nTitle: \(title) \nDescription: \(description) \nStart: \(Date(milliseconds: start).format(dateFormat: "dd/MM/yyyy HH:mm"))").richText()
  1960. }
  1961. })
  1962. }
  1963. }
  1964. else if attachmentFlag == "11" && (dataMessages[indexPath.row]["lock"] == nil || dataMessages[indexPath.row]["lock"] as! String != "1") && (dataMessages[indexPath.row]["lock"] as? String != "2") {
  1965. messageText.text = ""
  1966. topMarginText.constant = topMarginText.constant + 100
  1967. containerMessage.addSubview(imageSticker)
  1968. imageSticker.translatesAutoresizingMaskIntoConstraints = false
  1969. imageSticker.topAnchor.constraint(equalTo: containerMessage.topAnchor, constant: 15).isActive = true
  1970. imageSticker.widthAnchor.constraint(equalToConstant: 80).isActive = true
  1971. imageSticker.leadingAnchor.constraint(equalTo: containerMessage.leadingAnchor, constant: 15).isActive = true
  1972. imageSticker.bottomAnchor.constraint(equalTo: messageText.topAnchor, constant: -5).isActive = true
  1973. imageSticker.trailingAnchor.constraint(equalTo: containerMessage.trailingAnchor, constant: -15).isActive = true
  1974. imageSticker.image = UIImage(named: (textChat.components(separatedBy: "/")[1]), in: Bundle.resourceBundle(for: Nexilis.self), with: nil) //resourcesMediaBundle
  1975. imageSticker.contentMode = .scaleAspectFit
  1976. }
  1977. else {
  1978. messageText.attributedText = textChat.richText()
  1979. }
  1980. } else {
  1981. messageText.attributedText = textChat.richText()
  1982. }
  1983. messageText.isUserInteractionEnabled = false
  1984. if !textChat.isEmpty {
  1985. if textChat.contains("■"){
  1986. textChat = textChat.components(separatedBy: "■")[0]
  1987. textChat = textChat.trimmingCharacters(in: .whitespacesAndNewlines)
  1988. }
  1989. let listTextEnter = textChat.split(separator: "\n")
  1990. let finalAtribute = textChat.richText()
  1991. }
  1992. if !copySession && !deleteSession && messageText.isUserInteractionEnabled == false {
  1993. let interaction = UIContextMenuInteraction(delegate: self)
  1994. containerMessage.addInteraction(interaction)
  1995. containerMessage.isUserInteractionEnabled = true
  1996. }
  1997. if isSearching && textSearch.count > 1 {
  1998. messageText.attributedText = textChat.richText(isSearching: true, textSearch: textSearch)
  1999. if textChat.lowercased().contains(textSearch) {
  2000. countMatchesSearch += 1
  2001. }
  2002. }
  2003. let stringDate = (dataMessages[indexPath.row]["server_date"] as? String) ?? ""
  2004. if !stringDate.isEmpty {
  2005. let date = Date(milliseconds: Int64(stringDate) ?? 100)
  2006. let formatter = DateFormatter()
  2007. formatter.dateFormat = "HH:mm"
  2008. formatter.locale = NSLocale(localeIdentifier: "id") as Locale?
  2009. timeMessage.text = formatter.string(from: date as Date)
  2010. timeMessage.textColor = .lightGray
  2011. timeMessage.font = UIFont.systemFont(ofSize: 10, weight: .medium)
  2012. }
  2013. // let panGestureRecognizer = UIPanGestureRecognizer(target: self, action: #selector(panGestureCellAction))
  2014. // panGestureRecognizer.delegate = self
  2015. // cellMessage.addGestureRecognizer(panGestureRecognizer)
  2016. return cell
  2017. }
  2018. @objc func tapAck(_ sender: ObjectGesture) {
  2019. let indexPath = sender.indexPath
  2020. let dataMessages = self.dataMessages.filter({ $0["chat_date"] as! String == dataDates[indexPath.section]})
  2021. if dataMessages[indexPath.row]["status"] as! String == "8" {
  2022. return
  2023. }
  2024. if !CheckConnection.isConnectedToNetwork() || API.nGetCLXConnState() == 0 {
  2025. let imageView = UIImageView(image: UIImage(systemName: "xmark.circle.fill"))
  2026. imageView.tintColor = .white
  2027. let banner = FloatingNotificationBanner(title: "Check your connection".localized(), subtitle: nil, titleFont: UIFont.systemFont(ofSize: 16), titleColor: nil, titleTextAlign: .left, subtitleFont: nil, subtitleColor: nil, subtitleTextAlign: nil, leftView: imageView, rightView: nil, style: .danger, colors: nil, iconPosition: .center)
  2028. banner.show()
  2029. return
  2030. }
  2031. DispatchQueue.global().async {
  2032. let result = Nexilis.write(message: CoreMessage_TMessageBank.getAckLocationMessage(f_pin: dataMessages[indexPath.row]["f_pin"] as! String, message_id: dataMessages[indexPath.row]["message_id"] as! String, l_pin: dataMessages[indexPath.row]["l_pin"] as! String, server_date: "\(Date().currentTimeMillis())", message_scope_id: dataMessages[indexPath.row]["message_scope_id"] as! String, longitude: "", latitude: "", description: ""))
  2033. if result != nil {
  2034. Database.shared.database?.inTransaction({ (fmdb, rollback) in
  2035. do {
  2036. _ = Database.shared.updateRecord(fmdb: fmdb, table: "MESSAGE", cvalues: [
  2037. "status" : "8"
  2038. ], _where: "message_id = '\(dataMessages[indexPath.row]["message_id"] as! String)'")
  2039. } catch {
  2040. rollback.pointee = true
  2041. print("Access database error: \(error.localizedDescription)")
  2042. }
  2043. })
  2044. DispatchQueue.main.async {
  2045. if let index = self.dataMessages.firstIndex(where: {$0["message_id"] as? String == dataMessages[indexPath.row]["message_id"] as? String}) {
  2046. self.dataMessages[index]["status"] = "8"
  2047. let section = self.dataDates.firstIndex(of: self.dataMessages[index]["chat_date"] as! String)
  2048. let row = self.dataMessages.filter({ $0["chat_date"] as! String == self.dataDates[section!]}).firstIndex(where: { $0["message_id"] as! String == self.dataMessages[index]["message_id"] as! String})
  2049. if row != nil && section != nil {
  2050. self.tableChatView.reloadRows(at: [IndexPath(row: row!, section: section!)], with: .none)
  2051. }
  2052. self.showToast(message: "Confirmation Success.".localized(), font: UIFont.systemFont(ofSize: 12, weight: .medium), controller: self)
  2053. }
  2054. }
  2055. }
  2056. }
  2057. }
  2058. // public func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
  2059. // let velocity : CGPoint = gestureRecognizer.location(in: tableChatView)
  2060. // if velocity.x < 0 {
  2061. // return false
  2062. // }
  2063. // return abs(Float(velocity.x)) > abs(Float(velocity.y))
  2064. // }
  2065. //
  2066. // @objc func panGestureCellAction(recognizer: UIPanGestureRecognizer) {
  2067. // let translation = recognizer.translation(in: tableChatView)
  2068. // let x = recognizer.view?.frame.origin.x ?? 0
  2069. // if x >= -(recognizer.view?.frame.size.width ?? 0) * 0.05 {
  2070. // recognizer.view?.center = CGPoint(
  2071. // x: (recognizer.view?.center.x ?? 0) + translation.x,
  2072. // y: (recognizer.view?.center.y ?? 0))
  2073. // recognizer.setTranslation(CGPoint(x: 0, y: 0), in: view)
  2074. // if (recognizer.view?.frame.origin.x ?? 0) > UIScreen.main.bounds.size.width * 0.9 {
  2075. // UIView.animate(withDuration: 0.25, delay: 0, options: .curveEaseOut, animations: {
  2076. // recognizer.view?.frame = CGRect(x: 0, y: recognizer.view?.frame.origin.y ?? 0, width: recognizer.view?.frame.size.width ?? 0, height: recognizer.view?.frame.size.height ?? 0)
  2077. // })
  2078. // }
  2079. // }
  2080. // if x <= -(recognizer.view?.frame.size.width ?? 0) * 0.05 {
  2081. // let idMe = User.getMyPin() as String?
  2082. // let indexPath = self.tableChatView.indexPath(for: recognizer.view! as! UITableViewCell)
  2083. // let dataMessages = self.dataMessages.filter({ $0["chat_date"] as! String == dataDates[indexPath!.section]})
  2084. // if (dataMessages[indexPath!.row]["f_pin"] as? String == idMe) {
  2085. // let messageInfoVC = MessageInfo()
  2086. // messageInfoVC.data = dataMessages[indexPath!.row]
  2087. // self.navigationController?.pushViewController(messageInfoVC, animated: true)
  2088. // return
  2089. // }
  2090. // }
  2091. // if x >= ((recognizer.view?.frame.size.width ?? 0) * 0.2) {
  2092. // if !hapticSwipeLeft {
  2093. // UINotificationFeedbackGenerator().notificationOccurred(.success)
  2094. // }
  2095. // hapticSwipeLeft = true
  2096. // } else if x < ((recognizer.view?.frame.size.width ?? 0) * 0.2) {
  2097. // hapticSwipeLeft = false
  2098. // }
  2099. // if recognizer.state == .ended {
  2100. // UIView.animate(withDuration: 0.25, delay: 0, options: .curveEaseOut) {
  2101. // recognizer.view?.frame = CGRect(x: 0, y: recognizer.view?.frame.origin.y ?? 0, width: recognizer.view?.frame.size.width ?? 0, height: recognizer.view?.frame.size.height ?? 0)
  2102. // } completion: { (finished) in
  2103. // if x > ((recognizer.view?.frame.size.width ?? 0) * 0.2) {
  2104. // self.hapticSwipeLeft = false
  2105. //
  2106. // }
  2107. // }
  2108. // }
  2109. // }
  2110. public func numberOfSections(in tableView: UITableView) -> Int {
  2111. dataDates.count
  2112. }
  2113. public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
  2114. let count = dataMessages.filter({ $0["chat_date"] as! String == dataDates[section] }).count
  2115. return count
  2116. }
  2117. @objc func contentMessageTapped(_ sender: ObjectGesture) {
  2118. let nsDocumentDirectory = FileManager.SearchPathDirectory.documentDirectory
  2119. let nsUserDomainMask = FileManager.SearchPathDomainMask.userDomainMask
  2120. let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true)
  2121. DispatchQueue.main.async {
  2122. let idx = self.dataMessages.firstIndex(where: { $0["message_id"] as? String == sender.message_id})
  2123. if idx == nil {
  2124. return
  2125. }
  2126. let section = self.dataDates.firstIndex(of: self.dataMessages[idx!]["chat_date"] as! String)
  2127. if section == nil {
  2128. return
  2129. }
  2130. 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})
  2131. if row == nil {
  2132. return
  2133. }
  2134. let indexPath = IndexPath(row: row!, section: section!)
  2135. self.tableChatView.scrollToRow(at: indexPath, at: .middle, animated: true)
  2136. DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
  2137. if let cell = self.tableChatView.cellForRow(at: indexPath) {
  2138. let containerMessage = cell.contentView.subviews[0]
  2139. let idMe = User.getMyPin() as String?
  2140. if (self.dataMessages[idx!]["f_pin"] as? String == idMe) {
  2141. containerMessage.backgroundColor = .blueBubbleColor.withAlphaComponent(0.3)
  2142. DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
  2143. if (self.dataMessages[idx!]["attachment_flag"] as? String == "11") {
  2144. containerMessage.backgroundColor = .clear
  2145. } else {
  2146. containerMessage.backgroundColor = .blueBubbleColor
  2147. }
  2148. }
  2149. } else {
  2150. containerMessage.backgroundColor = .whiteBubbleColor.withAlphaComponent(0.3)
  2151. DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
  2152. if (self.dataMessages[idx!]["attachment_flag"] as? String == "11") {
  2153. containerMessage.backgroundColor = .clear
  2154. } else {
  2155. containerMessage.backgroundColor = .whiteBubbleColor
  2156. }
  2157. }
  2158. }
  2159. }
  2160. }
  2161. }
  2162. }
  2163. func getWordRange(at point: CGPoint, in label: UILabel) -> Range<String.Index>? {
  2164. guard let text = label.text else { return nil }
  2165. let layoutManager = NSLayoutManager()
  2166. let textContainer = NSTextContainer(size: .zero)
  2167. let textStorage = NSTextStorage(attributedString: label.attributedText ?? NSAttributedString())
  2168. layoutManager.addTextContainer(textContainer)
  2169. textStorage.addLayoutManager(layoutManager)
  2170. textContainer.lineFragmentPadding = 0.0
  2171. textContainer.lineBreakMode = label.lineBreakMode
  2172. textContainer.maximumNumberOfLines = label.numberOfLines
  2173. textContainer.size = label.bounds.size
  2174. let characterIndex = layoutManager.characterIndex(for: point, in: textContainer, fractionOfDistanceBetweenInsertionPoints: nil)
  2175. if characterIndex == text.count - 1 {
  2176. return nil
  2177. }
  2178. var wordStartIndex = characterIndex
  2179. while wordStartIndex > 0 && text[text.index(text.startIndex, offsetBy: wordStartIndex - 1)] != " " && text[text.index(text.startIndex, offsetBy: wordStartIndex - 1)] != "\n" {
  2180. wordStartIndex -= 1
  2181. }
  2182. var wordEndIndex = characterIndex
  2183. while wordEndIndex < text.count && text[text.index(text.startIndex, offsetBy: wordEndIndex)] != " " && text[text.index(text.startIndex, offsetBy: wordEndIndex)] != "\n" {
  2184. wordEndIndex += 1
  2185. }
  2186. return text.index(text.startIndex, offsetBy: wordStartIndex)..<text.index(text.startIndex, offsetBy: wordEndIndex)
  2187. }
  2188. func highlightedText(for text: String, in range: Range<String.Index>, label: UILabel) -> NSAttributedString {
  2189. let mutableAttributedString = label.attributedText!.mutableCopy() as! NSMutableAttributedString
  2190. mutableAttributedString.addAttribute(.backgroundColor, value: UIColor.lightGray.withAlphaComponent(0.5), range: NSRange(range, in: text))
  2191. label.isHighlighted = true
  2192. return mutableAttributedString
  2193. }
  2194. func removeHighlightedText(for text: String, in range: Range<String.Index>, label: UILabel) -> NSAttributedString {
  2195. let mutableAttributedString = label.attributedText!.mutableCopy() as! NSMutableAttributedString
  2196. mutableAttributedString.removeAttribute(.backgroundColor, range: NSRange(range, in: text))
  2197. label.isHighlighted = false
  2198. return mutableAttributedString
  2199. }
  2200. @objc func tapMessageText(_ sender: ObjectGesture) {
  2201. var stringURl = sender.message_id
  2202. if stringURl.lowercased().starts(with: "www.") {
  2203. stringURl = "https://" + stringURl.replacingOccurrences(of: "www.", with: "")
  2204. }
  2205. guard let url = URL(string: stringURl) else { return }
  2206. UIApplication.shared.open(url)
  2207. }
  2208. // public func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
  2209. // if copySession || forwardSession || deleteSession {
  2210. // return nil
  2211. // }
  2212. // let idMe = User.getMyPin() as String?
  2213. // if (dataMessages[indexPath.row]["f_pin"] as? String != idMe) {
  2214. // return nil
  2215. // }
  2216. // let messageInfoVC = MessageInfo()
  2217. // messageInfoVC.data = dataMessages[indexPath.row]
  2218. // self.navigationController?.show(messageInfoVC, sender: nil)
  2219. // return UISwipeActionsConfiguration()
  2220. // }
  2221. //
  2222. // public func tableView(_ tableView: UITableView, leadingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
  2223. // if copySession || forwardSession || deleteSession {
  2224. // return nil
  2225. // }
  2226. // let action = UIContextualAction(style: .normal,
  2227. // title: "") { [weak self] (action, view, completionHandler) in
  2228. // self?.handleReply(indexPath: indexPath)
  2229. // completionHandler(true)
  2230. // }
  2231. // action.backgroundColor = .white
  2232. // action.image = UIImage(systemName: "arrowshape.turn.up.left.fill")?.withTintColor(.black, renderingMode: .alwaysOriginal)
  2233. // return UISwipeActionsConfiguration(actions: [action])
  2234. // }
  2235. func scrollToFirstSearchMessage(indexScroll: Int = 1) {
  2236. if textSearch.count < 2 {
  2237. return
  2238. }
  2239. var lastIndex = 0
  2240. let messageTextForSearch: [[String: Any?]] = self.dataMessages.reversed()
  2241. for idx in 0..<messageTextForSearch.count {
  2242. if (messageTextForSearch[idx]["message_text"] as! String).lowercased().contains(textSearch) {
  2243. lastIndex += 1
  2244. if lastIndex < indexScroll {
  2245. continue
  2246. }
  2247. lastScrollIdxSearch = lastIndex
  2248. let section = self.dataDates.firstIndex(of: messageTextForSearch[idx]["chat_date"] as! String)
  2249. if section == nil {
  2250. return
  2251. }
  2252. let row = self.dataMessages.filter({ $0["chat_date"] as! String == self.dataDates[section!]}).firstIndex(where: { $0["message_id"] as? String == messageTextForSearch[idx]["message_id"] as? String})
  2253. if row == nil {
  2254. return
  2255. }
  2256. let indexPath = IndexPath(row: row!, section: section!)
  2257. self.tableChatView.scrollToRow(at: indexPath, at: .middle, animated: true)
  2258. DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
  2259. if let cell = self.tableChatView.cellForRow(at: indexPath) {
  2260. let containerMessage = cell.contentView.subviews[0]
  2261. let idMe = User.getMyPin() as String?
  2262. if (messageTextForSearch[idx]["f_pin"] as? String == idMe) {
  2263. containerMessage.backgroundColor = .blueBubbleColor.withAlphaComponent(0.3)
  2264. DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
  2265. if (messageTextForSearch[idx]["attachment_flag"] as? String == "11") {
  2266. containerMessage.backgroundColor = .clear
  2267. } else {
  2268. containerMessage.backgroundColor = .blueBubbleColor
  2269. }
  2270. }
  2271. } else {
  2272. containerMessage.backgroundColor = .whiteBubbleColor.withAlphaComponent(0.3)
  2273. DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
  2274. if (messageTextForSearch[idx]["attachment_flag"] as? String == "11") {
  2275. containerMessage.backgroundColor = .clear
  2276. } else {
  2277. containerMessage.backgroundColor = .whiteBubbleColor
  2278. }
  2279. }
  2280. }
  2281. }
  2282. }
  2283. titleSearchMatches.isHidden = false
  2284. if countMatchesSearch != 0 {
  2285. if countMatchesSearch > 1 {
  2286. titleSearchMatches.text = "\(lastScrollIdxSearch) " + "of".localized() + " \(countMatchesSearch) " + "matches".localized()
  2287. } else {
  2288. titleSearchMatches.text = "\(countMatchesSearch) " + "matches".localized()
  2289. }
  2290. } else {
  2291. titleSearchMatches.text = "Not found".localized()
  2292. }
  2293. if lastScrollIdxSearch == countMatchesSearch || countMatchesSearch == 0 {
  2294. buttonUp.isEnabled = false
  2295. buttonUp.tintColor = .gray
  2296. } else {
  2297. buttonUp.isEnabled = true
  2298. buttonUp.tintColor = .mainColor
  2299. }
  2300. if countMatchesSearch == 0 || lastScrollIdxSearch == 1 || countMatchesSearch == 1 {
  2301. buttonDown.isEnabled = false
  2302. buttonDown.tintColor = .gray
  2303. } else {
  2304. buttonDown.isEnabled = true
  2305. buttonDown.tintColor = .mainColor
  2306. }
  2307. break
  2308. }
  2309. }
  2310. }
  2311. public func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
  2312. let indexPath = tableChatView.indexPathsForVisibleRows?.first
  2313. if indexPath != nil {
  2314. let headerRect = tableChatView.rectForHeader(inSection: indexPath!.section)
  2315. let isPinned = headerRect.origin.y <= scrollView.contentOffset.y
  2316. if listViewOnSection.count != 0 && listViewOnSection.count - 1 == indexPath!.section && indexPath!.row > 0 {
  2317. let sect = listViewOnSection.count - 1 < currentIndexpath!.section ? listViewOnSection.count - 1 : currentIndexpath!.section
  2318. let headerView = listViewOnSection[sect]
  2319. headerView.isHidden = true
  2320. }
  2321. }
  2322. }
  2323. public func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
  2324. if !decelerate {
  2325. let indexPath = tableChatView.indexPathsForVisibleRows?.first
  2326. if indexPath != nil {
  2327. let headerRect = tableChatView.rectForHeader(inSection: indexPath!.section)
  2328. let isPinned = headerRect.origin.y <= scrollView.contentOffset.y
  2329. if listViewOnSection.count != 0 && listViewOnSection.count - 1 == indexPath!.section && isPinned {
  2330. let sect = listViewOnSection.count - 1 < currentIndexpath!.section ? listViewOnSection.count - 1 : currentIndexpath!.section
  2331. let headerView = listViewOnSection[sect]
  2332. headerView.isHidden = true
  2333. }
  2334. }
  2335. }
  2336. }
  2337. }
  2338. extension ChatGPTBotView: UITextViewDelegate {
  2339. public func textViewDidChangeSelection(_ textView: UITextView) {
  2340. let cursorPosition = textView.caretRect(for: self.textFieldSend.selectedTextRange!.start).origin
  2341. let currentLine = Int(cursorPosition.y / self.textFieldSend.font!.lineHeight)
  2342. UIView.animate(withDuration: 0.3) {
  2343. let numberOfLines = textView.textContainer.lineBreakMode == .byWordWrapping ? Int(textView.contentSize.height / textView.font!.lineHeight) - 1 : 1
  2344. if currentLine == 0 && numberOfLines == 1 {
  2345. self.heightTextFieldSend.constant = 40
  2346. } else if self.heightTextFieldSend.constant < 95.0 && currentLine >= 4 {
  2347. self.heightTextFieldSend.constant = 95.0
  2348. } else if currentLine < 4 && numberOfLines < 5 {
  2349. if (self.textFieldSend.text.count > 0 && self.heightTextFieldSend.constant != self.textFieldSend.contentSize.height) {
  2350. self.heightTextFieldSend.constant = self.textFieldSend.contentSize.height
  2351. }
  2352. }
  2353. }
  2354. }
  2355. public func textViewDidChange(_ textView: UITextView) {
  2356. if allowTyping {
  2357. allowTyping = false
  2358. sendTyping(l_pin: dataPerson["f_pin"]!!, isTyping: true)
  2359. DispatchQueue.main.asyncAfter(deadline: .now() + 4, execute: {
  2360. self.allowTyping = true
  2361. })
  2362. }
  2363. if textView.text.contains("*") || textView.text.contains("_") || textView.text.contains("^") || textView.text.contains("~") {
  2364. textView.preserveCursorPosition(withChanges: { _ in
  2365. textView.attributedText = textView.text.richText(isEditing: true)
  2366. return .preserveCursor
  2367. })
  2368. }
  2369. }
  2370. public func textViewDidBeginEditing(_ textView: UITextView) {
  2371. if textView.textColor == UIColor.lightGray {
  2372. textView.text = nil
  2373. textView.textColor = self.traitCollection.userInterfaceStyle == .dark ? .white : UIColor.black
  2374. }
  2375. }
  2376. public func textViewDidEndEditing(_ textView: UITextView) {
  2377. if textView.text.isEmpty {
  2378. textView.text = "Send message".localized()
  2379. textView.textColor = UIColor.lightGray
  2380. }
  2381. }
  2382. public override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
  2383. if action == #selector(UIResponderStandardEditActions.paste(_:)) && (UIPasteboard.general.image != nil) {
  2384. return true
  2385. }
  2386. return super.canPerformAction(action, withSender: sender)
  2387. }
  2388. public override func paste(_ sender: Any?) {
  2389. }
  2390. public func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
  2391. if (self.textFieldSend.text.count == 0) {
  2392. return text != "\n"
  2393. }
  2394. return true
  2395. }
  2396. }
  2397. extension ChatGPTBotView: UISearchBarDelegate {
  2398. public func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
  2399. textSearch = searchText.trimmingCharacters(in: .whitespacesAndNewlines)
  2400. countMatchesSearch = 0
  2401. titleSearchMatches.isHidden = true
  2402. tableChatView.reloadData()
  2403. scrollToFirstSearchMessage()
  2404. }
  2405. }