forked from shadowfacts/Tusker
370 lines
16 KiB
Swift
370 lines
16 KiB
Swift
//
|
|
// NotificationsTableViewController.swift
|
|
// Tusker
|
|
//
|
|
// Created by Shadowfacts on 9/2/18.
|
|
// Copyright © 2018 Shadowfacts. All rights reserved.
|
|
//
|
|
|
|
import UIKit
|
|
import Pachyderm
|
|
import Sentry
|
|
|
|
class NotificationsTableViewController: DiffableTimelineLikeTableViewController<NotificationsTableViewController.Section, NotificationsTableViewController.Item> {
|
|
|
|
private let statusCell = "statusCell"
|
|
private let actionGroupCell = "actionGroupCell"
|
|
private let followGroupCell = "followGroupCell"
|
|
private let followRequestCell = "followRequestCell"
|
|
private let pollCell = "pollCell"
|
|
private let updatedCell = "updatedCell"
|
|
private let unknownCell = "unknownCell"
|
|
|
|
weak var mastodonController: MastodonController!
|
|
|
|
private let allowedTypes: [Pachyderm.Notification.Kind]
|
|
private let groupTypes = [Pachyderm.Notification.Kind.favourite, .reblog, .follow]
|
|
|
|
private var newer: RequestRange?
|
|
private var older: RequestRange?
|
|
|
|
init(allowedTypes: [Pachyderm.Notification.Kind], mastodonController: MastodonController) {
|
|
self.allowedTypes = allowedTypes
|
|
self.mastodonController = mastodonController
|
|
|
|
super.init()
|
|
|
|
dragEnabled = true
|
|
}
|
|
|
|
required init?(coder: NSCoder) {
|
|
fatalError("init(coder:) has not been implemented")
|
|
}
|
|
|
|
override class func refreshCommandTitle() -> String {
|
|
return NSLocalizedString("Refresh Notifications", comment: "refresh notifications command discoverability title")
|
|
}
|
|
|
|
override func viewDidLoad() {
|
|
super.viewDidLoad()
|
|
|
|
tableView.register(UINib(nibName: "TimelineStatusTableViewCell", bundle: .main), forCellReuseIdentifier: statusCell)
|
|
tableView.register(UINib(nibName: "ActionNotificationGroupTableViewCell", bundle: .main), forCellReuseIdentifier: actionGroupCell)
|
|
tableView.register(UINib(nibName: "FollowNotificationGroupTableViewCell", bundle: .main), forCellReuseIdentifier: followGroupCell)
|
|
tableView.register(UINib(nibName: "FollowRequestNotificationTableViewCell", bundle: .main), forCellReuseIdentifier: followRequestCell)
|
|
tableView.register(UINib(nibName: "PollFinishedTableViewCell", bundle: .main), forCellReuseIdentifier: pollCell)
|
|
tableView.register(UINib(nibName: "StatusUpdatedNotificationTableViewCell", bundle: .main), forCellReuseIdentifier: updatedCell)
|
|
tableView.register(UINib(nibName: "BasicTableViewCell", bundle: .main), forCellReuseIdentifier: unknownCell)
|
|
|
|
tableView.cellLayoutMarginsFollowReadableWidth = UIDevice.current.userInterfaceIdiom == .pad || UIDevice.current.userInterfaceIdiom == .mac
|
|
tableView.allowsFocus = true
|
|
|
|
NotificationCenter.default.addObserver(self, selector: #selector(handleStatusDeleted), name: .statusDeleted, object: nil)
|
|
}
|
|
|
|
@objc private func handleStatusDeleted(_ notification: Foundation.Notification) {
|
|
guard let userInfo = notification.userInfo,
|
|
let accountID = mastodonController.accountInfo?.id,
|
|
userInfo["accountID"] as? String == accountID,
|
|
let statusIDs = userInfo["statusIDs"] as? [String] else {
|
|
return
|
|
}
|
|
var snapshot = self.dataSource.snapshot()
|
|
// this is not efficient, since the number of notifications is almost certainly greater than the number of deleted statuses
|
|
// but we can't just check if the status is in the data source, since we don't have the corresponding notification/group
|
|
let toDelete = snapshot.itemIdentifiers
|
|
.filter { item in
|
|
guard case .notificationGroup(let group) = item else {
|
|
return false
|
|
}
|
|
return group.kind == .mention && statusIDs.contains(group.notifications.first!.status!.id)
|
|
}
|
|
if !toDelete.isEmpty {
|
|
snapshot.deleteItems(toDelete)
|
|
self.dataSource.apply(snapshot, animatingDifferences: true)
|
|
}
|
|
}
|
|
|
|
private func request(range: RequestRange) -> Request<[Pachyderm.Notification]> {
|
|
if mastodonController.instanceFeatures.notificationsAllowedTypes {
|
|
return Client.getNotifications(allowedTypes: allowedTypes, range: range)
|
|
} else {
|
|
var types = Set(Notification.Kind.allCases)
|
|
allowedTypes.forEach { types.remove($0) }
|
|
return Client.getNotifications(excludedTypes: Array(types), range: range)
|
|
}
|
|
}
|
|
|
|
// MARK: - DiffableTimelineLikeTableViewController
|
|
|
|
override func cellProvider(_ tableView: UITableView, _ indexPath: IndexPath, _ item: Item) -> UITableViewCell? {
|
|
if case .loadingIndicator = item {
|
|
return self.loadingIndicatorCell(indexPath: indexPath)
|
|
}
|
|
let group = item.group!
|
|
|
|
switch group.kind {
|
|
case .mention:
|
|
guard let notification = group.notifications.first,
|
|
let cell = tableView.dequeueReusableCell(withIdentifier: statusCell, for: indexPath) as? TimelineStatusTableViewCell else {
|
|
fatalError()
|
|
}
|
|
cell.delegate = self
|
|
guard let status = notification.status else {
|
|
let crumb = Breadcrumb(level: .fatal, category: "notifications")
|
|
crumb.data = [
|
|
"id": notification.id,
|
|
"type": notification.kind.rawValue,
|
|
"created_at": notification.createdAt.formatted(.iso8601),
|
|
"account": notification.account.id,
|
|
]
|
|
SentrySDK.addBreadcrumb(crumb: crumb)
|
|
fatalError("missing status for mention notification")
|
|
}
|
|
cell.updateUI(statusID: status.id, state: group.statusState!)
|
|
return cell
|
|
|
|
case .favourite, .reblog:
|
|
guard let cell = tableView.dequeueReusableCell(withIdentifier: actionGroupCell, for: indexPath) as? ActionNotificationGroupTableViewCell else { fatalError() }
|
|
cell.delegate = self
|
|
cell.updateUI(group: group)
|
|
return cell
|
|
|
|
case .follow:
|
|
guard let cell = tableView.dequeueReusableCell(withIdentifier: followGroupCell, for: indexPath) as? FollowNotificationGroupTableViewCell else { fatalError() }
|
|
cell.delegate = self
|
|
cell.updateUI(group: group)
|
|
return cell
|
|
|
|
case .followRequest:
|
|
guard let notification = group.notifications.first,
|
|
let cell = tableView.dequeueReusableCell(withIdentifier: followRequestCell, for: indexPath) as? FollowRequestNotificationTableViewCell else { fatalError() }
|
|
cell.delegate = self
|
|
cell.updateUI(notification: notification)
|
|
return cell
|
|
|
|
case .poll:
|
|
guard let notification = group.notifications.first,
|
|
let cell = tableView.dequeueReusableCell(withIdentifier: pollCell, for: indexPath) as? PollFinishedTableViewCell else { fatalError() }
|
|
cell.delegate = self
|
|
cell.updateUI(notification: notification)
|
|
return cell
|
|
|
|
case .update:
|
|
guard let notification = group.notifications.first,
|
|
let cell = tableView.dequeueReusableCell(withIdentifier: updatedCell, for: indexPath) as? StatusUpdatedNotificationTableViewCell else { fatalError() }
|
|
cell.delegate = self
|
|
cell.updateUI(notification: notification)
|
|
return cell
|
|
|
|
case .unknown:
|
|
let cell = tableView.dequeueReusableCell(withIdentifier: unknownCell, for: indexPath)
|
|
cell.textLabel!.text = NSLocalizedString("Unknown Notification", comment: "unknown notification fallback cell text")
|
|
return cell
|
|
}
|
|
}
|
|
|
|
private func validateNotifications(_ notifications: [Pachyderm.Notification]) {
|
|
for notif in notifications where notif.status == nil && (notif.kind == .mention || notif.kind == .reblog || notif.kind == .favourite) {
|
|
let crumb = Breadcrumb(level: .fatal, category: "notifications")
|
|
crumb.data = [
|
|
"id": notif.id,
|
|
"type": notif.kind.rawValue,
|
|
"created_at": notif.createdAt.formatted(.iso8601),
|
|
"account": notif.account.id,
|
|
]
|
|
SentrySDK.addBreadcrumb(crumb: crumb)
|
|
}
|
|
}
|
|
|
|
override func loadInitialItems(completion: @escaping (LoadResult) -> Void) {
|
|
mastodonController.run(request(range: .default)) { (response) in
|
|
switch response {
|
|
case let .failure(error):
|
|
completion(.failure(.client(error)))
|
|
|
|
case let .success(notifications, _):
|
|
self.validateNotifications(notifications)
|
|
let groups = NotificationGroup.createGroups(notifications: notifications, only: self.groupTypes)
|
|
|
|
if !notifications.isEmpty {
|
|
self.newer = .after(id: notifications.first!.id, count: nil)
|
|
self.older = .before(id: notifications.last!.id, count: nil)
|
|
}
|
|
|
|
self.mastodonController.persistentContainer.addAll(notifications: notifications) {
|
|
var snapshot = Snapshot()
|
|
snapshot.appendSections([.notifications])
|
|
snapshot.appendItems(groups.map { .notificationGroup($0) }, toSection: .notifications)
|
|
completion(.success(snapshot))
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
override func loadOlderItems(currentSnapshot: @escaping () -> Snapshot, completion: @escaping (LoadResult) -> Void) {
|
|
guard let older = older else {
|
|
completion(.failure(.noOlder))
|
|
return
|
|
}
|
|
|
|
mastodonController.run(request(range: older)) { (response) in
|
|
switch response {
|
|
case let .failure(error):
|
|
completion(.failure(.client(error)))
|
|
|
|
case let .success(newNotifications, _):
|
|
self.validateNotifications(newNotifications)
|
|
if !newNotifications.isEmpty {
|
|
self.older = .before(id: newNotifications.last!.id, count: nil)
|
|
}
|
|
|
|
let olderGroups = NotificationGroup.createGroups(notifications: newNotifications, only: self.groupTypes)
|
|
|
|
self.mastodonController.persistentContainer.addAll(notifications: newNotifications) {
|
|
let existingGroups = currentSnapshot().itemIdentifiers.compactMap(\.group)
|
|
let merged = NotificationGroup.mergeGroups(first: existingGroups, second: olderGroups, only: self.groupTypes)
|
|
var snapshot = NSDiffableDataSourceSnapshot<Section, Item>()
|
|
snapshot.appendSections([.notifications])
|
|
snapshot.appendItems(merged.map { .notificationGroup($0) }, toSection: .notifications)
|
|
completion(.success(snapshot))
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
override func loadNewerItems(currentSnapshot: @escaping () -> Snapshot, completion: @escaping (LoadResult) -> Void) {
|
|
guard let newer = newer else {
|
|
completion(.failure(.noNewer))
|
|
return
|
|
}
|
|
|
|
mastodonController.run(request(range: newer)) { (response) in
|
|
switch response {
|
|
case let .failure(error):
|
|
completion(.failure(.client(error)))
|
|
|
|
case let .success(newNotifications, _):
|
|
self.validateNotifications(newNotifications)
|
|
guard !newNotifications.isEmpty else {
|
|
completion(.failure(.allCaughtUp))
|
|
return
|
|
}
|
|
|
|
self.newer = .after(id: newNotifications.first!.id, count: nil)
|
|
|
|
let newerGroups = NotificationGroup.createGroups(notifications: newNotifications, only: self.groupTypes)
|
|
|
|
self.mastodonController.persistentContainer.addAll(notifications: newNotifications) {
|
|
let existingGroups = currentSnapshot().itemIdentifiers.compactMap(\.group)
|
|
let merged = NotificationGroup.mergeGroups(first: newerGroups, second: existingGroups, only: self.groupTypes)
|
|
var snapshot = NSDiffableDataSourceSnapshot<Section, Item>()
|
|
snapshot.appendSections([.notifications])
|
|
snapshot.appendItems(merged.map { .notificationGroup($0) }, toSection: .notifications)
|
|
completion(.success(snapshot))
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
private func dismissNotificationsInGroup(at indexPath: IndexPath, completion: (() -> Void)? = nil) {
|
|
guard let item = dataSource.itemIdentifier(for: indexPath),
|
|
let notifications = item.group?.notifications else {
|
|
return
|
|
}
|
|
let group = DispatchGroup()
|
|
notifications
|
|
.map { Pachyderm.Notification.dismiss(id: $0.id) }
|
|
.forEach { (request) in
|
|
group.enter()
|
|
mastodonController.run(request) { (_) in
|
|
group.leave()
|
|
}
|
|
}
|
|
group.notify(queue: .main) {
|
|
var snapshot = self.dataSource.snapshot()
|
|
snapshot.deleteItems([item])
|
|
self.dataSource.apply(snapshot, completion: completion)
|
|
}
|
|
}
|
|
|
|
// MARK: - UITableViewDelegate
|
|
|
|
override func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
|
|
let dismissAction = UIContextualAction(style: .destructive, title: NSLocalizedString("Dismiss", comment: "dismiss notification swipe action title")) { (action, view, completion) in
|
|
self.dismissNotificationsInGroup(at: indexPath) {
|
|
completion(true)
|
|
}
|
|
}
|
|
dismissAction.image = UIImage(systemName: "clear.fill")
|
|
|
|
let cellConfiguration = (tableView.cellForRow(at: indexPath) as? TableViewSwipeActionProvider)?.trailingSwipeActionsConfiguration()
|
|
|
|
let config: UISwipeActionsConfiguration
|
|
if let cellConfiguration = cellConfiguration {
|
|
config = UISwipeActionsConfiguration(actions: cellConfiguration.actions + [dismissAction])
|
|
config.performsFirstActionWithFullSwipe = cellConfiguration.performsFirstActionWithFullSwipe
|
|
} else {
|
|
config = UISwipeActionsConfiguration(actions: [dismissAction])
|
|
config.performsFirstActionWithFullSwipe = false
|
|
}
|
|
return config
|
|
}
|
|
|
|
override func getSuggestedContextMenuActions(tableView: UITableView, indexPath: IndexPath, point: CGPoint) -> [UIAction] {
|
|
return [
|
|
UIAction(title: "Dismiss Notification", image: UIImage(systemName: "clear.fill"), identifier: .init("dismissnotification"), handler: { (_) in
|
|
self.dismissNotificationsInGroup(at: indexPath)
|
|
})
|
|
]
|
|
}
|
|
}
|
|
|
|
extension NotificationsTableViewController {
|
|
enum Section: DiffableTimelineLikeSection {
|
|
case loadingIndicator
|
|
case notifications
|
|
}
|
|
enum Item: DiffableTimelineLikeItem {
|
|
case loadingIndicator
|
|
case notificationGroup(NotificationGroup)
|
|
|
|
var group: NotificationGroup? {
|
|
switch self {
|
|
case .loadingIndicator:
|
|
return nil
|
|
case .notificationGroup(let group):
|
|
return group
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
extension NotificationsTableViewController: TuskerNavigationDelegate {
|
|
var apiController: MastodonController! { mastodonController }
|
|
}
|
|
|
|
extension NotificationsTableViewController: MenuActionProvider {
|
|
}
|
|
|
|
extension NotificationsTableViewController: StatusTableViewCellDelegate {
|
|
func statusCellCollapsedStateChanged(_ cell: BaseStatusTableViewCell) {
|
|
if #available(iOS 16.0, *) {
|
|
} else {
|
|
cellHeightChanged()
|
|
}
|
|
}
|
|
}
|
|
|
|
extension NotificationsTableViewController: UITableViewDataSourcePrefetching {
|
|
func tableView(_ tableView: UITableView, prefetchRowsAt indexPaths: [IndexPath]) {
|
|
for indexPath in indexPaths {
|
|
guard let group = dataSource.itemIdentifier(for: indexPath)?.group else { continue }
|
|
for notification in group.notifications {
|
|
guard let avatar = notification.account.avatar else { continue }
|
|
ImageCache.avatars.fetchIfNotCached(avatar)
|
|
}
|
|
}
|
|
}
|
|
}
|