ChatGPTBotView.swift 137 KB

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