ChatGPTBotView.swift 134 KB

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