ChatListViewModel.swift 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373
  1. import UIKit
  2. import DcCore
  3. import Intents
  4. // MARK: - ChatListViewModel
  5. class ChatListViewModel: NSObject {
  6. var onChatListUpdate: VoidFunction?
  7. private var inBgSearch = false
  8. private var needsAnotherBgSearch = false
  9. enum ChatListSectionType {
  10. case chats
  11. case contacts
  12. case messages
  13. }
  14. private(set) public var isArchive: Bool
  15. private let dcContext: DcContext
  16. private(set) public var searchActive: Bool = false
  17. // if searchfield is empty we show default chat list
  18. private var showSearchResults: Bool {
  19. return searchActive && searchText.containsCharacters()
  20. }
  21. private var chatList: DcChatlist!
  22. // for search filtering
  23. private var searchText: String = ""
  24. private var searchResultChatList: DcChatlist?
  25. private var searchResultContactIds: [Int] = []
  26. private var searchResultMessageIds: [Int] = []
  27. // to manage sections dynamically
  28. private var searchResultsChatsSection: ChatListSectionType = .chats
  29. private var searchResultsContactsSection: ChatListSectionType = .contacts
  30. private var searchResultsMessagesSection: ChatListSectionType = .messages
  31. private var searchResultSections: [ChatListSectionType] = []
  32. init(dcContext: DcContext, isArchive: Bool) {
  33. self.isArchive = isArchive
  34. self.dcContext = dcContext
  35. super.init()
  36. updateChatList(notifyListener: true)
  37. }
  38. private func updateChatList(notifyListener: Bool) {
  39. var gclFlags: Int32 = 0
  40. if isArchive {
  41. gclFlags |= DC_GCL_ARCHIVED_ONLY
  42. } else if RelayHelper.sharedInstance.isForwarding() {
  43. gclFlags |= DC_GCL_FOR_FORWARDING
  44. }
  45. self.chatList = dcContext.getChatlist(flags: gclFlags, queryString: nil, queryId: 0)
  46. if notifyListener, let onChatListUpdate = onChatListUpdate {
  47. if Thread.isMainThread {
  48. onChatListUpdate()
  49. } else {
  50. DispatchQueue.main.async {
  51. onChatListUpdate()
  52. }
  53. }
  54. }
  55. }
  56. var numberOfSections: Int {
  57. if showSearchResults {
  58. return searchResultSections.count
  59. }
  60. return 1
  61. }
  62. func numberOfRowsIn(section: Int) -> Int {
  63. if showSearchResults {
  64. switch searchResultSections[section] {
  65. case .chats:
  66. return searchResultChatList?.length ?? 0
  67. case .contacts:
  68. return searchResultContactIds.count
  69. case .messages:
  70. return searchResultMessageIds.count
  71. }
  72. }
  73. return chatList.length
  74. }
  75. func cellDataFor(section: Int, row: Int) -> AvatarCellViewModel {
  76. if showSearchResults {
  77. switch searchResultSections[section] {
  78. case .chats:
  79. return makeChatCellViewModel(index: row, searchText: searchText)
  80. case .contacts:
  81. if row >= 0 && row < searchResultContactIds.count {
  82. return ContactCellViewModel.make(contactId: searchResultContactIds[row], searchText: searchText, dcContext: dcContext)
  83. } else {
  84. logger.warning("search: requested contact index \(row) not in range 0..\(searchResultContactIds.count)")
  85. }
  86. case .messages:
  87. if row >= 0 && row < searchResultMessageIds.count {
  88. return makeMessageCellViewModel(msgId: searchResultMessageIds[row])
  89. } else {
  90. logger.warning("search: requested message index \(row) not in range 0..\(searchResultMessageIds.count)")
  91. }
  92. }
  93. }
  94. return makeChatCellViewModel(index: row, searchText: "")
  95. }
  96. // only visible on search results
  97. func titleForHeaderIn(section: Int) -> String? {
  98. if showSearchResults {
  99. switch searchResultSections[section] {
  100. case .chats:
  101. return String.localized(stringID: "n_chats", count: numberOfRowsIn(section: section))
  102. case .contacts:
  103. return String.localized(stringID: "n_contacts", count: numberOfRowsIn(section: section))
  104. case .messages:
  105. let count = numberOfRowsIn(section: section)
  106. var ret = String.localized(stringID: "n_messages", count: count)
  107. if count==1000 {
  108. // a count of 1000 results may be limited, see documentation of dc_search_msgs()
  109. // (formatting may be "1.000" or "1,000", so just skip the first digit)
  110. ret = ret.replacingOccurrences(of: "000", with: "000+")
  111. }
  112. return ret
  113. }
  114. }
  115. return nil
  116. }
  117. func chatIdFor(section: Int, row: Int) -> Int? {
  118. let cellData = cellDataFor(section: section, row: row)
  119. switch cellData.type {
  120. case .chat(let data):
  121. return data.chatId
  122. case .contact:
  123. return nil
  124. case .profile:
  125. return nil
  126. }
  127. }
  128. func msgIdFor(row: Int) -> Int? {
  129. if showSearchResults {
  130. return nil
  131. }
  132. return chatList.getMsgId(index: row)
  133. }
  134. func refreshData() {
  135. updateChatList(notifyListener: true)
  136. }
  137. func beginSearch() {
  138. searchActive = true
  139. }
  140. func endSearch() {
  141. searchActive = false
  142. searchText = ""
  143. resetSearch()
  144. }
  145. var emptySearchText: String? {
  146. if searchActive && numberOfSections == 0 {
  147. return searchText
  148. }
  149. return nil
  150. }
  151. func deleteChat(chatId: Int) {
  152. dcContext.deleteChat(chatId: chatId)
  153. NotificationManager.removeNotificationsForChat(dcContext: dcContext, chatId: chatId)
  154. INInteraction.delete(with: ["\(dcContext.id).\(chatId)"])
  155. }
  156. func archiveChatToggle(chatId: Int) {
  157. let chat = dcContext.getChat(chatId: chatId)
  158. let isArchivedBefore = chat.isArchived
  159. dcContext.archiveChat(chatId: chatId, archive: !isArchivedBefore)
  160. if !isArchivedBefore {
  161. NotificationManager.removeNotificationsForChat(dcContext: dcContext, chatId: chatId)
  162. }
  163. updateChatList(notifyListener: false)
  164. }
  165. func pinChatToggle(chatId: Int) {
  166. let chat: DcChat = dcContext.getChat(chatId: chatId)
  167. let pinned = chat.visibility==DC_CHAT_VISIBILITY_PINNED
  168. self.dcContext.setChatVisibility(chatId: chatId, visibility: pinned ? DC_CHAT_VISIBILITY_NORMAL : DC_CHAT_VISIBILITY_PINNED)
  169. updateChatList(notifyListener: false)
  170. }
  171. }
  172. private extension ChatListViewModel {
  173. // MARK: - avatarCellViewModel factory
  174. func makeChatCellViewModel(index: Int, searchText: String) -> AvatarCellViewModel {
  175. let list: DcChatlist = searchResultChatList ?? chatList
  176. let chatId = list.getChatId(index: index)
  177. let summary = list.getSummary(index: index)
  178. let chat = dcContext.getChat(chatId: chatId)
  179. let unreadMessages = dcContext.getUnreadMessages(chatId: chatId)
  180. var chatTitleIndexes: [Int] = []
  181. if searchText.containsCharacters() {
  182. let chatName = chat.name
  183. chatTitleIndexes = chatName.containsExact(subSequence: searchText)
  184. }
  185. let viewModel = ChatCellViewModel(
  186. dcContext: dcContext,
  187. chatData: ChatCellData(
  188. chatId: chatId,
  189. highlightMsgId: nil,
  190. summary: summary,
  191. unreadMessages: unreadMessages
  192. ),
  193. titleHighlightIndexes: chatTitleIndexes
  194. )
  195. return viewModel
  196. }
  197. func makeMessageCellViewModel(msgId: Int) -> AvatarCellViewModel {
  198. let msg: DcMsg = dcContext.getMessage(id: msgId)
  199. let chatId: Int = msg.chatId
  200. let chat: DcChat = dcContext.getChat(chatId: chatId)
  201. if !chat.isValid {
  202. // chat might be deleted and searchResultMessageIds deprecated, so return a dummy view model
  203. // cleanup of the searchResultMessageIds will be done in message change event handling
  204. return ChatCellViewModel(
  205. dcContext: dcContext,
  206. chatData: ChatCellData(
  207. chatId: 0,
  208. highlightMsgId: 0,
  209. summary: DcLot(nil),
  210. unreadMessages: 0
  211. )
  212. )
  213. }
  214. let summary: DcLot = msg.summary(chat: chat)
  215. let unreadMessages = dcContext.getUnreadMessages(chatId: chatId)
  216. let viewModel = ChatCellViewModel(
  217. dcContext: dcContext,
  218. chatData: ChatCellData(
  219. chatId: chatId,
  220. highlightMsgId: msgId,
  221. summary: summary,
  222. unreadMessages: unreadMessages
  223. )
  224. )
  225. let subtitle = viewModel.subtitle
  226. viewModel.subtitleHighlightIndexes = subtitle.containsExact(subSequence: searchText)
  227. return viewModel
  228. }
  229. // MARK: - search
  230. private func updateSearchResultSections() {
  231. var sections: [ChatListSectionType] = []
  232. if let chatList = searchResultChatList, chatList.length > 0 {
  233. sections.append(searchResultsChatsSection)
  234. }
  235. if !searchResultContactIds.isEmpty {
  236. sections.append(searchResultsContactsSection)
  237. }
  238. if !searchResultMessageIds.isEmpty {
  239. sections.append(searchResultsMessagesSection)
  240. }
  241. searchResultSections = sections
  242. }
  243. private func resetSearch() {
  244. searchResultChatList = nil
  245. searchResultContactIds = []
  246. searchResultMessageIds = []
  247. updateSearchResultSections()
  248. }
  249. private func filterContentForSearchText(_ searchText: String) {
  250. if !searchText.isEmpty {
  251. filterAndUpdateList(searchText: searchText)
  252. } else {
  253. // when search input field empty we show default chatList
  254. resetSearch()
  255. }
  256. if let onChatListUpdate = onChatListUpdate {
  257. if Thread.isMainThread {
  258. onChatListUpdate()
  259. } else {
  260. DispatchQueue.main.async {
  261. onChatListUpdate()
  262. }
  263. }
  264. }
  265. }
  266. func filterAndUpdateList(searchText: String) {
  267. var overallCnt = 0
  268. // #1 chats with searchPattern in title bar
  269. searchResultChatList = dcContext.getChatlist(flags: DC_GCL_NO_SPECIALS, queryString: searchText, queryId: 0)
  270. if let chatlist = searchResultChatList {
  271. overallCnt += chatlist.length
  272. }
  273. // #2 contacts with searchPattern in name or in email
  274. if searchText != self.searchText && overallCnt > 0 {
  275. logger.info("... skipping getContacts and searchMessages, more recent search pending")
  276. searchResultContactIds = []
  277. searchResultMessageIds = []
  278. updateSearchResultSections()
  279. return
  280. }
  281. searchResultContactIds = dcContext.getContacts(flags: DC_GCL_ADD_SELF, queryString: searchText)
  282. overallCnt += searchResultContactIds.count
  283. // #3 messages with searchPattern (filtered by dc_core)
  284. if searchText != self.searchText && overallCnt > 0 {
  285. logger.info("... skipping searchMessages, more recent search pending")
  286. searchResultMessageIds = []
  287. updateSearchResultSections()
  288. return
  289. }
  290. if searchText.count <= 1 {
  291. logger.info("... skipping searchMessages, string too short")
  292. searchResultMessageIds = []
  293. updateSearchResultSections()
  294. return
  295. }
  296. searchResultMessageIds = dcContext.searchMessages(searchText: searchText)
  297. updateSearchResultSections()
  298. }
  299. }
  300. // MARK: UISearchResultUpdating
  301. extension ChatListViewModel: UISearchResultsUpdating {
  302. func updateSearchResults(for searchController: UISearchController) {
  303. self.searchText = searchController.searchBar.text ?? ""
  304. if inBgSearch {
  305. needsAnotherBgSearch = true
  306. logger.info("... search call debounced")
  307. } else {
  308. inBgSearch = true
  309. DispatchQueue.global(qos: .userInteractive).async { [weak self] in
  310. usleep(100000)
  311. self?.needsAnotherBgSearch = false
  312. self?.filterContentForSearchText(self?.searchText ?? "")
  313. while self?.needsAnotherBgSearch != false {
  314. usleep(100000)
  315. self?.needsAnotherBgSearch = false
  316. logger.info("... executing debounced search call")
  317. self?.filterContentForSearchText(self?.searchText ?? "")
  318. }
  319. self?.inBgSearch = false
  320. }
  321. }
  322. }
  323. }