A WIP iOS app for Mastodon and Pleroma.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

StatusTableViewCell.swift 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381
  1. //
  2. // StatusTableViewCell.swift
  3. // Tusker
  4. //
  5. // Created by Shadowfacts on 8/16/18.
  6. // Copyright © 2018 Shadowfacts. All rights reserved.
  7. //
  8. import UIKit
  9. import Pachyderm
  10. protocol StatusTableViewCellDelegate: TuskerNavigationDelegate {
  11. }
  12. class StatusTableViewCell: UITableViewCell, PreferencesAdaptive {
  13. var delegate: StatusTableViewCellDelegate? {
  14. didSet {
  15. contentLabel.navigationDelegate = delegate
  16. }
  17. }
  18. @IBOutlet weak var displayNameLabel: UILabel!
  19. @IBOutlet weak var usernameLabel: UILabel!
  20. @IBOutlet weak var contentLabel: StatusContentLabel!
  21. @IBOutlet weak var avatarImageView: UIImageView!
  22. @IBOutlet weak var reblogLabel: UILabel!
  23. @IBOutlet weak var timestampLabel: UILabel!
  24. @IBOutlet weak var attachmentsView: UIView!
  25. @IBOutlet weak var favoriteButton: UIButton!
  26. @IBOutlet weak var reblogButton: UIButton!
  27. var statusID: String!
  28. var accountID: String!
  29. var reblogStatusID: String?
  30. var rebloggerID: String?
  31. var favorited: Bool = false {
  32. didSet {
  33. favoriteButton.tintColor = favorited ? UIColor(displayP3Red: 1, green: 0.8, blue: 0, alpha: 1) : tintColor
  34. }
  35. }
  36. var reblogged: Bool = false {
  37. didSet {
  38. reblogButton.tintColor = reblogged ? UIColor(displayP3Red: 1, green: 0.8, blue: 0, alpha: 1) : tintColor
  39. }
  40. }
  41. var avatarURL: URL?
  42. var updateTimestampWorkItem: DispatchWorkItem?
  43. var attachmentDataTasks: [URLSessionDataTask] = []
  44. override func awakeFromNib() {
  45. displayNameLabel.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(accountPressed)))
  46. displayNameLabel.isUserInteractionEnabled = true
  47. usernameLabel.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(accountPressed)))
  48. usernameLabel.isUserInteractionEnabled = true
  49. reblogLabel.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(reblogLabelPressed)))
  50. reblogLabel.isUserInteractionEnabled = true
  51. avatarImageView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(accountPressed)))
  52. avatarImageView.isUserInteractionEnabled = true
  53. avatarImageView.layer.masksToBounds = true
  54. attachmentsView.layer.cornerRadius = 5
  55. attachmentsView.layer.masksToBounds = true
  56. }
  57. func updateUIForPreferences() {
  58. guard let account = MastodonCache.account(for: accountID) else { fatalError("") }
  59. avatarImageView.layer.cornerRadius = Preferences.shared.avatarStyle.cornerRadius(for: avatarImageView)
  60. if let rebloggerID = rebloggerID,
  61. let reblogger = MastodonCache.account(for: rebloggerID) {
  62. reblogLabel.text = "Reblogged by \(reblogger.realDisplayName)"
  63. }
  64. displayNameLabel.text = account.realDisplayName
  65. }
  66. func updateUI(for statusID: String) {
  67. guard var status = MastodonCache.status(for: statusID) else { fatalError("Missing cached status \(statusID)") }
  68. if let reblogID = status.reblog?.id,
  69. let reblog = MastodonCache.status(for: reblogID) {
  70. reblogStatusID = statusID
  71. rebloggerID = status.account.id
  72. status = reblog
  73. reblogLabel.isHidden = false
  74. } else {
  75. reblogStatusID = nil
  76. rebloggerID = nil
  77. reblogLabel.isHidden = true
  78. }
  79. let account = status.account
  80. self.accountID = account.id
  81. self.statusID = status.id
  82. updateUIForPreferences()
  83. usernameLabel.text = "@\(account.acct)"
  84. avatarImageView.image = nil
  85. avatarURL = account.avatar
  86. ImageCache.avatars.get(account.avatar) { (data) in
  87. guard let data = data else { return }
  88. DispatchQueue.main.async {
  89. self.avatarImageView.image = UIImage(data: data)
  90. self.avatarURL = nil
  91. }
  92. }
  93. updateTimestamp()
  94. let attachments = status.attachments.filter({ $0.kind == .image })
  95. if attachments.count > 0 {
  96. attachmentsView.isHidden = false
  97. let width = attachmentsView.bounds.width
  98. let height: CGFloat = 200
  99. switch attachments.count {
  100. case 1:
  101. addAttachmentView(frame: CGRect(x: 0, y: 0, width: width, height: height), attachment: attachments[0])
  102. case 2:
  103. addAttachmentView(frame: CGRect(x: 0, y: 0, width: width / 2 - 4, height: height), attachment: attachments[0])
  104. addAttachmentView(frame: CGRect(x: width / 2 + 4, y: 0, width: width / 2 - 4, height: height), attachment: attachments[1])
  105. case 3:
  106. addAttachmentView(frame: CGRect(x: 0, y: 0, width: width / 2 - 4, height: height), attachment: attachments[0])
  107. addAttachmentView(frame: CGRect(x: width / 2 + 4, y: 0, width: width / 2 - 4, height: height / 2 - 4), attachment: attachments[1])
  108. addAttachmentView(frame: CGRect(x: width / 2 + 4, y: height / 2 + 4, width: width / 2 - 4, height: height / 2 - 4), attachment: attachments[2])
  109. case 4:
  110. addAttachmentView(frame: CGRect(x: 0, y: 0, width: width / 2 - 4, height: height / 2 - 4), attachment: attachments[0])
  111. addAttachmentView(frame: CGRect(x: 0, y: height / 2 + 4, width: width / 2 - 4, height: height / 2 - 4), attachment: attachments[1])
  112. addAttachmentView(frame: CGRect(x: width / 2 + 4, y: 0, width: width / 2 - 4, height: height / 2 - 4), attachment: attachments[2])
  113. addAttachmentView(frame: CGRect(x: width / 2 + 4, y: height / 2 + 4, width: width / 2 - 4, height: height / 2 - 4), attachment: attachments[3])
  114. default:
  115. fatalError("Too many attachments")
  116. }
  117. } else {
  118. attachmentsView.isHidden = true
  119. }
  120. let realStatus = status.reblog ?? status
  121. favorited = realStatus.favourited ?? false
  122. reblogged = realStatus.reblogged ?? false
  123. contentLabel.statusID = statusID
  124. }
  125. func updateTimestamp() {
  126. guard let status = MastodonCache.status(for: statusID) else { fatalError("Missing cached status \(statusID!)") }
  127. timestampLabel.text = status.createdAt.timeAgoString()
  128. let delay: DispatchTimeInterval?
  129. switch status.createdAt.timeAgo().1 {
  130. case .second:
  131. delay = .seconds(10)
  132. case .minute:
  133. delay = .seconds(60)
  134. default:
  135. delay = nil
  136. }
  137. if let delay = delay {
  138. updateTimestampWorkItem = DispatchWorkItem {
  139. self.updateTimestamp()
  140. }
  141. DispatchQueue.main.asyncAfter(deadline: .now() + delay, execute: updateTimestampWorkItem!)
  142. } else {
  143. updateTimestampWorkItem = nil
  144. }
  145. }
  146. func addAttachmentView(frame: CGRect, attachment: Attachment) {
  147. let attachmentView = AttachmentView(frame: frame, attachment: attachment)
  148. attachmentView.delegate = self
  149. attachmentsView.addSubview(attachmentView)
  150. }
  151. override func prepareForReuse() {
  152. if let url = avatarURL {
  153. ImageCache.avatars.cancel(url)
  154. }
  155. updateTimestampWorkItem?.cancel()
  156. updateTimestampWorkItem = nil
  157. attachmentsView.subviews.forEach { $0.removeFromSuperview() }
  158. }
  159. override func setSelected(_ selected: Bool, animated: Bool) {
  160. super.setSelected(selected, animated: animated)
  161. if selected {
  162. delegate?.selected(status: statusID)
  163. }
  164. }
  165. @IBAction func replyPressed(_ sender: Any) {
  166. delegate?.reply(to: statusID)
  167. }
  168. @objc func accountPressed() {
  169. delegate?.selected(account: accountID)
  170. }
  171. @objc func reblogLabelPressed() {
  172. guard let rebloggerID = rebloggerID else { return }
  173. delegate?.selected(account: rebloggerID)
  174. }
  175. @IBAction func favoritePressed(_ sender: Any) {
  176. guard let status = MastodonCache.status(for: statusID) else { fatalError("Missing cached status \(statusID!)") }
  177. let oldValue = favorited
  178. favorited = !favorited
  179. let realStatus: Status = status.reblog ?? status
  180. let request = (favorited ? Status.favourite : Status.unfavourite)(realStatus)
  181. MastodonController.client.run(request) { response in
  182. DispatchQueue.main.async {
  183. self.favorited = realStatus.favourited ?? false
  184. if case .success = response {
  185. self.favorited = realStatus.favourited ?? false
  186. UIImpactFeedbackGenerator(style: .light).impactOccurred()
  187. } else {
  188. self.favorited = oldValue
  189. print("Couldn't favorite status \(realStatus.id)")
  190. // todo: display error message
  191. UINotificationFeedbackGenerator().notificationOccurred(.error)
  192. return
  193. }
  194. }
  195. }
  196. }
  197. @IBAction func reblogPressed(_ sender: Any) {
  198. guard let status = MastodonCache.status(for: statusID) else { fatalError("Missing cached status \(statusID!)") }
  199. let oldValue = reblogged
  200. reblogged = !reblogged
  201. let realStatus: Status = status.reblog ?? status
  202. let request = (reblogged ? Status.reblog : Status.unreblog)(realStatus)
  203. MastodonController.client.run(request) { response in
  204. self.reblogged = realStatus.reblogged ?? false
  205. DispatchQueue.main.async {
  206. if case .success = response {
  207. self.reblogged = realStatus.reblogged ?? false
  208. UIImpactFeedbackGenerator(style: .light).impactOccurred()
  209. } else {
  210. self.reblogged = oldValue
  211. print("Couldn't reblog status \(realStatus.id)")
  212. // todo: display error message
  213. UINotificationFeedbackGenerator().notificationOccurred(.error)
  214. }
  215. }
  216. }
  217. }
  218. @IBAction func morePressed(_ sender: Any) {
  219. delegate?.showMoreOptions(forStatus: statusID)
  220. }
  221. }
  222. extension StatusTableViewCell: TableViewSwipeActionProvider {
  223. static var favoriteActionImage: UIImage = UIGraphicsImageRenderer(size: CGSize(width: 30 * 137/131, height: 30)).image { _ in
  224. UIImage(named: "Favorite")!.draw(in: CGRect(x: 0, y: 0, width: 30 * 137/131, height: 30))
  225. }
  226. static var reblogActionImage: UIImage = UIGraphicsImageRenderer(size: CGSize(width: 30 * 927/558, height: 30)).image { _ in
  227. UIImage(named: "Reblog")!.draw(in: CGRect(x: 0, y: 0, width: 30 * 927/558, height: 30))
  228. }
  229. static var replyActionImage: UIImage = UIGraphicsImageRenderer(size: CGSize(width: 30 * 205/151, height: 30)).image { _ in
  230. UIImage(named: "Reply")!.draw(in: CGRect(x: 0, y: 0, width: 30 * 205/151, height: 30))
  231. }
  232. static var moreActionImage: UIImage = UIGraphicsImageRenderer(size: CGSize(width: 30 * 2/1, height: 30)).image { _ in
  233. UIImage(named: "More")!.draw(in: CGRect(x: 0, y: 0, width: 30 * 2/1, height: 30))
  234. }
  235. func leadingSwipeActionsConfiguration() -> UISwipeActionsConfiguration? {
  236. guard let status = MastodonCache.status(for: statusID) else { fatalError("Missing cached status \(statusID!)") }
  237. let favoriteTitle: String
  238. let favoriteRequest: Request<Status>
  239. let favoriteColor: UIColor
  240. if status.favourited ?? false {
  241. favoriteTitle = "Unfavorite"
  242. favoriteRequest = Status.unfavourite(status)
  243. favoriteColor = UIColor(displayP3Red: 235/255, green: 77/255, blue: 62/255, alpha: 1)
  244. } else {
  245. favoriteTitle = "Favorite"
  246. favoriteRequest = Status.favourite(status)
  247. favoriteColor = UIColor(displayP3Red: 1, green: 204/255, blue: 0, alpha: 1)
  248. }
  249. let favorite = UIContextualAction(style: .normal, title: favoriteTitle) { (action, view, completion) in
  250. MastodonController.client.run(favoriteRequest, completion: { response in
  251. DispatchQueue.main.async {
  252. guard case let .success(status, _) = response else {
  253. completion(false)
  254. return
  255. }
  256. completion(true)
  257. MastodonCache.add(status: status)
  258. self.updateUI(for: self.reblogStatusID ?? self.statusID)
  259. }
  260. })
  261. }
  262. favorite.image = StatusTableViewCell.favoriteActionImage
  263. favorite.backgroundColor = favoriteColor
  264. let reblogTitle: String
  265. let reblogRequest: Request<Status>
  266. let reblogColor: UIColor
  267. if status.reblogged ?? false {
  268. reblogTitle = "Unreblog"
  269. reblogRequest = Status.unreblog(status)
  270. reblogColor = UIColor(displayP3Red: 235/255, green: 77/255, blue: 62/255, alpha: 1)
  271. } else {
  272. reblogTitle = "Reblog"
  273. reblogRequest = Status.reblog(status)
  274. reblogColor = tintColor
  275. }
  276. let reblog = UIContextualAction(style: .normal, title: reblogTitle) { (action, view, completion) in
  277. MastodonController.client.run(reblogRequest, completion: { response in
  278. DispatchQueue.main.async {
  279. guard case let .success(status, _) = response else {
  280. completion(false)
  281. return
  282. }
  283. completion(true)
  284. MastodonCache.add(status: status)
  285. self.updateUI(for: self.reblogStatusID ?? self.statusID)
  286. }
  287. })
  288. }
  289. reblog.image = StatusTableViewCell.reblogActionImage
  290. reblog.backgroundColor = reblogColor
  291. return UISwipeActionsConfiguration(actions: [favorite, reblog])
  292. }
  293. func trailingSwipeActionsConfiguration() -> UISwipeActionsConfiguration? {
  294. let reply = UIContextualAction(style: .normal, title: "Reply") { (action, view, completion) in
  295. completion(true)
  296. self.delegate?.reply(to: self.statusID)
  297. }
  298. reply.image = StatusTableViewCell.replyActionImage
  299. reply.backgroundColor = tintColor
  300. let more = UIContextualAction(style: .normal, title: "More") { (action, view, completion) in
  301. completion(true)
  302. self.delegate?.showMoreOptions(forStatus: self.statusID)
  303. }
  304. more.image = StatusTableViewCell.moreActionImage
  305. more.backgroundColor = .gray
  306. return UISwipeActionsConfiguration(actions: [reply, more])
  307. }
  308. }
  309. extension StatusTableViewCell: AttachmentViewDelegate {
  310. func showLargeAttachment(for attachmentView: AttachmentView) {
  311. if let gifData = attachmentView.gifData {
  312. delegate?.showLargeImage(gifData: gifData, description: attachmentView.attachment.description, animatingFrom: attachmentView)
  313. } else {
  314. delegate?.showLargeImage(attachmentView.image!, description: attachmentView.attachment.description, animatingFrom: attachmentView)
  315. }
  316. }
  317. }
  318. extension StatusTableViewCell: PreviewViewControllerProvider {
  319. func getPreviewViewController(forLocation location: CGPoint, sourceViewController: UIViewController) -> UIViewController? {
  320. if avatarImageView.frame.contains(location) {
  321. return delegate?.router.profile(for: accountID)
  322. } else if attachmentsView.frame.contains(location) {
  323. let attachmentsViewLocation = attachmentsView.convert(location, from: self)
  324. if let attachmentView = attachmentsView.subviews.first(where: { $0.frame.contains(attachmentsViewLocation) }) as? AttachmentView {
  325. let image = attachmentView.image!
  326. let description = attachmentView.attachment.description
  327. return delegate?.largeImage(image, description: description, sourceView: attachmentView)
  328. }
  329. } else if contentLabel.frame.contains(location),
  330. let vc = contentLabel.getViewController(forLinkAt: contentLabel.convert(location, from: self)) {
  331. return vc
  332. }
  333. return delegate?.router.conversation(for: statusID)
  334. }
  335. }