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.
367 lines
13 KiB
367 lines
13 KiB
//
|
|
// TimelineTableViewController.swift
|
|
// elpha-ios
|
|
//
|
|
// Created by Dwayne Harris on 10/1/18.
|
|
// Copyright © 2018 Elpha. All rights reserved.
|
|
//
|
|
|
|
import AlamofireImage
|
|
import CoreData
|
|
import UIKit
|
|
|
|
class TimelineTableViewController: UITableViewController, TimelinesTableViewControllerDelegate {
|
|
var fetchedResultsController: NSFetchedResultsController<StatusMO>? = nil
|
|
let fetchLimit = 20
|
|
|
|
var loading: Bool = false {
|
|
didSet {
|
|
DispatchQueue.main.async {
|
|
if self.loading {
|
|
self.refreshControl?.beginRefreshing()
|
|
} else {
|
|
self.refreshControl?.endRefreshing()
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
var currentPaginationContext: String {
|
|
guard let timeline = AuthenticationManager.session?.timeline, let categoryString = timeline.category else {
|
|
return ""
|
|
}
|
|
|
|
switch TimelineCategory(rawValue: categoryString)! {
|
|
case .home:
|
|
return "timeline:home"
|
|
case .local:
|
|
return "timeline:local"
|
|
case .federated:
|
|
return "timeline:federated"
|
|
case .tag:
|
|
return "timeline:tag:\(timeline.subcategory!)"
|
|
case .favorites:
|
|
return "timeline:favorites"
|
|
}
|
|
}
|
|
|
|
override func viewDidLoad() {
|
|
super.viewDidLoad()
|
|
initializeFetchedResultsController()
|
|
|
|
let moreButtonItem = UIBarButtonItem(image: UIImage(named: "More"), style: .plain, target: self, action: #selector(more))
|
|
let composeButtonItem = UIBarButtonItem(image: UIImage(named: "Compose"), style: .plain, target: self, action: #selector(compose))
|
|
|
|
navigationItem.leftBarButtonItems = [moreButtonItem]
|
|
navigationItem.rightBarButtonItems = [composeButtonItem]
|
|
|
|
if let timeline = AuthenticationManager.session?.timeline {
|
|
navigationItem.title = timeline.name
|
|
} else {
|
|
navigationItem.title = "Home"
|
|
}
|
|
|
|
refreshControl?.addTarget(self, action: #selector(self.fetch), for: .valueChanged)
|
|
}
|
|
|
|
override func viewDidAppear(_ animated: Bool) {
|
|
super.viewDidAppear(animated)
|
|
// fetchTimeline()
|
|
}
|
|
|
|
@objc func more() {
|
|
performSegue(withIdentifier: "TimelinesSegue", sender: self)
|
|
}
|
|
|
|
@objc func compose() {
|
|
let alertController = UIAlertController(title: "Compose", message: "Toot", preferredStyle: .alert)
|
|
alertController.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
|
|
present(alertController, animated: true)
|
|
}
|
|
|
|
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
|
|
if segue.identifier == "TimelinesSegue" {
|
|
if let destination = segue.destination as? TimelinesTableViewController {
|
|
destination.delegate = self
|
|
}
|
|
}
|
|
}
|
|
|
|
func didSelect(timeline: TimelineMO) {
|
|
navigationItem.title = timeline.name
|
|
AuthenticationManager.session?.timeline = timeline
|
|
CoreDataManager.shared.saveContext()
|
|
|
|
initializeFetchedResultsController()
|
|
tableView.reloadData()
|
|
}
|
|
|
|
func createDefaultTimelines(account: AccountMO) {
|
|
let homeTimeline = TimelineMO(context: CoreDataManager.shared.context)
|
|
homeTimeline.name = "Home"
|
|
homeTimeline.category = TimelineCategory.home.rawValue
|
|
homeTimeline.account = account
|
|
homeTimeline.order = 1
|
|
|
|
let localTimeline = TimelineMO(context: CoreDataManager.shared.context)
|
|
localTimeline.name = "Local"
|
|
localTimeline.category = TimelineCategory.local.rawValue
|
|
localTimeline.account = account
|
|
localTimeline.order = 2
|
|
|
|
let federatedTimeline = TimelineMO(context: CoreDataManager.shared.context)
|
|
federatedTimeline.name = "Home"
|
|
federatedTimeline.category = TimelineCategory.federated.rawValue
|
|
federatedTimeline.account = account
|
|
federatedTimeline.order = 3
|
|
|
|
let favoritesTimeline = TimelineMO(context: CoreDataManager.shared.context)
|
|
favoritesTimeline.name = "Home"
|
|
favoritesTimeline.category = TimelineCategory.favorites.rawValue
|
|
favoritesTimeline.account = account
|
|
favoritesTimeline.order = 4
|
|
|
|
CoreDataManager.shared.saveContext()
|
|
}
|
|
|
|
@objc func fetch() {
|
|
fetchTimeline { error in
|
|
if error != nil {
|
|
print("\(String(describing: error))")
|
|
}
|
|
}
|
|
}
|
|
|
|
func fetchTimeline(withPagination pagination: PaginationItem? = nil, completion: @escaping (Error?) -> Void) {
|
|
guard let session = AuthenticationManager.session, let account = session.account else {
|
|
completion(nil)
|
|
return
|
|
}
|
|
|
|
if session.timeline == nil {
|
|
if let timelines = account.timelines, timelines.count == 0 {
|
|
createDefaultTimelines(account: account)
|
|
}
|
|
|
|
let request = NSFetchRequest<TimelineMO>(entityName: "Timeline")
|
|
request.predicate = NSPredicate(format: "category == %@", TimelineCategory.home.rawValue)
|
|
|
|
do {
|
|
let results = try CoreDataManager.shared.context.fetch(request)
|
|
session.timeline = results.first
|
|
CoreDataManager.shared.saveContext()
|
|
} catch {
|
|
print("\(error)")
|
|
}
|
|
}
|
|
|
|
guard let timeline = session.timeline else {
|
|
completion(nil)
|
|
return
|
|
}
|
|
|
|
func requestCompletion(data: [JSONObject]?, pagination: [PaginationItem]?, error: Error?) {
|
|
guard let data = data, error == nil else {
|
|
completion(error)
|
|
return
|
|
}
|
|
|
|
DispatchQueue.main.async {
|
|
for (index, status) in data.enumerated() {
|
|
if let upsertResult = MastodonDataManager.upsertStatus(status) {
|
|
let status = upsertResult.object
|
|
|
|
if let pagination = pagination {
|
|
var markers: [PaginationMarker] = status.markers ?? []
|
|
|
|
if index == 0 {
|
|
pagination.forEach { item in
|
|
if item.direction == .prev {
|
|
markers.append(PaginationMarker(context: self.currentPaginationContext, item: item))
|
|
}
|
|
}
|
|
}
|
|
|
|
if index == data.count - 1 {
|
|
pagination.forEach { item in
|
|
if item.direction == .next {
|
|
markers.append(PaginationMarker(context: self.currentPaginationContext, item: item))
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
timeline.addToStatuses(status)
|
|
}
|
|
}
|
|
|
|
CoreDataManager.shared.saveContext()
|
|
|
|
self.loading = false
|
|
completion(nil)
|
|
}
|
|
}
|
|
|
|
loading = true
|
|
|
|
switch TimelineCategory(rawValue: timeline.category!)! {
|
|
case .home:
|
|
MastodonAPI.homeTimeline(
|
|
limit: fetchLimit,
|
|
pagination: pagination,
|
|
completion: requestCompletion
|
|
)
|
|
case .local:
|
|
MastodonAPI.publicTimeline(
|
|
local: true,
|
|
limit: fetchLimit,
|
|
pagination: pagination,
|
|
completion: requestCompletion
|
|
)
|
|
case .federated:
|
|
MastodonAPI.publicTimeline(
|
|
local: false,
|
|
limit: fetchLimit,
|
|
pagination: pagination,
|
|
completion: requestCompletion
|
|
)
|
|
case .tag:
|
|
MastodonAPI.tagTimeline(
|
|
local: false,
|
|
limit: fetchLimit,
|
|
pagination: pagination,
|
|
completion: requestCompletion
|
|
)
|
|
case .favorites:
|
|
MastodonAPI.favorites(
|
|
limit: fetchLimit,
|
|
pagination: pagination,
|
|
completion: requestCompletion
|
|
)
|
|
}
|
|
}
|
|
}
|
|
|
|
extension TimelineTableViewController: NSFetchedResultsControllerDelegate {
|
|
func initializeFetchedResultsController() {
|
|
guard let timeline = AuthenticationManager.session?.timeline else {
|
|
return
|
|
}
|
|
|
|
let request = NSFetchRequest<StatusMO>(entityName: "Status")
|
|
request.predicate = NSPredicate(format: "ANY timelines = %@", timeline)
|
|
request.sortDescriptors = [
|
|
NSSortDescriptor(key: "createdAt", ascending: false),
|
|
]
|
|
|
|
fetchedResultsController = NSFetchedResultsController(
|
|
fetchRequest: request,
|
|
managedObjectContext: CoreDataManager.shared.context,
|
|
sectionNameKeyPath: nil,
|
|
cacheName: nil
|
|
)
|
|
|
|
fetchedResultsController!.delegate = self
|
|
|
|
do {
|
|
try fetchedResultsController!.performFetch()
|
|
} catch {
|
|
print("\(error)")
|
|
}
|
|
}
|
|
|
|
func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
|
|
self.tableView.reloadData()
|
|
}
|
|
}
|
|
|
|
extension TimelineTableViewController {
|
|
override func numberOfSections(in tableView: UITableView) -> Int {
|
|
return 1
|
|
}
|
|
|
|
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
|
|
guard let count = fetchedResultsController?.fetchedObjects?.count else {
|
|
return 0
|
|
}
|
|
|
|
return count
|
|
}
|
|
|
|
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
|
|
guard let cell = tableView.dequeueReusableCell(withIdentifier: "TimelineTableViewCell", for: indexPath) as? TimelineTableViewCell else {
|
|
fatalError("Unable to find reusable cell")
|
|
}
|
|
|
|
guard let status = fetchedResultsController?.object(at: indexPath) else {
|
|
fatalError("CoreData error")
|
|
}
|
|
|
|
cell.statusView.delegate = self
|
|
cell.statusView.update(withStatus: status)
|
|
cell.statusView.topDividerView.isHidden = indexPath.row == 0
|
|
|
|
if let markers = status.markers {
|
|
markers.forEach { marker in
|
|
if marker.context == self.currentPaginationContext {
|
|
print("Found marker: \(marker)")
|
|
}
|
|
}
|
|
}
|
|
|
|
return cell
|
|
}
|
|
}
|
|
|
|
extension TimelineTableViewController: StatusViewDelegate {
|
|
func accountTapped(account: AccountMO) {
|
|
let storyboard = UIStoryboard(name: "Main", bundle: nil)
|
|
|
|
if let controller = storyboard.instantiateViewController(withIdentifier: "AccountTableViewController") as? AccountTableViewController {
|
|
controller.account = account
|
|
self.navigationController?.pushViewController(controller, animated: true)
|
|
}
|
|
}
|
|
|
|
func statusTapped(status: StatusMO) {
|
|
let storyboard = UIStoryboard(name: "Main", bundle: nil)
|
|
|
|
if let controller = storyboard.instantiateViewController(withIdentifier: "StatusTableViewController") as? StatusTableViewController {
|
|
controller.status = status
|
|
self.navigationController?.pushViewController(controller, animated: true)
|
|
}
|
|
}
|
|
}
|
|
|
|
extension TimelineTableViewController {
|
|
func newStatusView() -> NewStatusesView {
|
|
let newStatusesView = NewStatusesView()
|
|
newStatusesView.translatesAutoresizingMaskIntoConstraints = false
|
|
|
|
let blurEffectView = UIVisualEffectView(effect: UIBlurEffect(style: UIBlurEffect.Style.prominent))
|
|
blurEffectView.translatesAutoresizingMaskIntoConstraints = false
|
|
blurEffectView.contentView.addSubview(newStatusesView)
|
|
blurEffectView.layer.cornerRadius = 10
|
|
blurEffectView.layer.masksToBounds = true
|
|
|
|
NSLayoutConstraint.activate([
|
|
newStatusesView.leadingAnchor.constraint(equalTo: blurEffectView.leadingAnchor),
|
|
newStatusesView.trailingAnchor.constraint(equalTo: blurEffectView.trailingAnchor),
|
|
newStatusesView.topAnchor.constraint(equalTo: blurEffectView.topAnchor),
|
|
newStatusesView.bottomAnchor.constraint(equalTo: blurEffectView.bottomAnchor),
|
|
])
|
|
|
|
view.addSubview(blurEffectView)
|
|
|
|
let bottomLayoutConstraint = blurEffectView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor, constant: 100)
|
|
|
|
NSLayoutConstraint.activate([
|
|
blurEffectView.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -20),
|
|
blurEffectView.widthAnchor.constraint(equalToConstant: 200),
|
|
blurEffectView.heightAnchor.constraint(equalToConstant: 50),
|
|
bottomLayoutConstraint,
|
|
])
|
|
|
|
return newStatusesView
|
|
}
|
|
}
|