ChatGPTBotView.swift 145 KB

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