ChatGPTBotView.swift 138 KB

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