pEpForiOS/UI/EmailDisplay/EmailListViewController.swift
author Dirk Zimmermann <dirk@pep-project.org>
Mon, 18 Jul 2016 15:50:37 +0200
changeset 437 4c7e1b466422
parent 434 62a11e58b6ae
child 452 5efee166262b
permissions -rw-r--r--
Showing outgoing message color
dirk@30
     1
//
dirk@30
     2
//  EmailListViewController.swift
dirk@30
     3
//  pEpForiOS
dirk@30
     4
//
dirk@30
     5
//  Created by Dirk Zimmermann on 16/04/16.
dirk@30
     6
//  Copyright © 2016 p≡p Security S.A. All rights reserved.
dirk@30
     7
//
dirk@30
     8
dirk@30
     9
import Foundation
dirk@30
    10
import UIKit
dirk@31
    11
import CoreData
dirk@30
    12
dirk@58
    13
struct UIState {
dirk@275
    14
    var isSynching: Bool = false
dirk@58
    15
}
dirk@58
    16
dirk@31
    17
class EmailListViewController: UITableViewController {
dirk@273
    18
    let comp = "EmailListViewController"
dirk@361
    19
dirk@273
    20
    let segueShowEmail = "segueShowEmail"
dirk@397
    21
    let segueCompose = "segueCompose"
dirk@397
    22
    let segueUserSettings = "segueUserSettings"
dirk@30
    23
dirk@368
    24
    var appConfig: AppConfig!
dirk@212
    25
    var fetchController: NSFetchedResultsController?
dirk@275
    26
    var state = UIState()
dirk@342
    27
    let dateFormatter = UIHelper.dateFormatterEmailList()
dirk@371
    28
    var shouldFetchFolders = true
dirk@275
    29
dirk@275
    30
    override func viewDidLoad() {
dirk@275
    31
        let refreshController = UIRefreshControl.init()
dirk@275
    32
        refreshController.addTarget(self, action: #selector(self.refresh(_:)),
dirk@275
    33
                                    forControlEvents: UIControlEvents.ValueChanged)
dirk@275
    34
        self.refreshControl = refreshController
dirk@356
    35
        UIHelper.variableCellHeightsTableView(self.tableView)
dirk@275
    36
    }
dirk@31
    37
dirk@31
    38
    override func viewWillAppear(animated: Bool) {
dirk@31
    39
        if appConfig == nil {
dirk@31
    40
            if let appDelegate = UIApplication.sharedApplication().delegate as? AppDelegate {
dirk@31
    41
                appConfig = appDelegate.appConfig
dirk@31
    42
            }
dirk@273
    43
        }
dirk@209
    44
        prepareFetchRequest()
dirk@209
    45
dirk@437
    46
        let account:IAccount? = appConfig.model.fetchLastAccount()
ana@152
    47
        if (account == nil)  {
dirk@361
    48
            self.performSegueWithIdentifier(segueUserSettings, sender: self)
ana@207
    49
        } else {
dirk@437
    50
            appConfig.currentAccount = account
dirk@365
    51
            PEPUtil.myselfFromAccount(
dirk@365
    52
                account as! Account, block: { identity in
dirk@414
    53
                    Log.infoComponent(self.comp,
dirk@365
    54
                        "myself: \(identity[kPepAddress]) -> \(identity[kPepFingerprint])")
dirk@365
    55
            })
dirk@275
    56
            fetchMailsRefreshControl()
dirk@365
    57
ana@152
    58
        }
ana@207
    59
        super.viewWillAppear(animated)
ana@207
    60
    }
ana@152
    61
dirk@275
    62
    func refresh(refreshControl: UIRefreshControl) {
dirk@275
    63
        fetchMailsRefreshControl(refreshControl)
dirk@275
    64
    }
dirk@275
    65
dirk@275
    66
    func fetchMailsRefreshControl(refreshControl: UIRefreshControl? = nil) {
dirk@115
    67
        if let account = appConfig?.model.fetchLastAccount() {
dirk@55
    68
            let connectInfo = account.connectInfo
dirk@55
    69
dirk@275
    70
            state.isSynching = true
dirk@368
    71
dirk@371
    72
            var operations: [BaseOperation] = []
dirk@371
    73
            if shouldFetchFolders {
dirk@371
    74
                shouldFetchFolders = false
dirk@371
    75
                operations.append(CreateLocalSpecialFoldersOperation.init(
dirk@376
    76
                    coreDataUtil: appConfig.grandOperator.coreDataUtil,
dirk@376
    77
                    accountEmail: account.email))
dirk@371
    78
                operations.append(FetchFoldersOperation.init(
dirk@371
    79
                    grandOperator: appConfig.grandOperator, connectInfo: connectInfo))
dirk@371
    80
            }
dirk@371
    81
            operations.append(PrefetchEmailsOperation.init(
dirk@371
    82
                grandOperator: appConfig.grandOperator, connectInfo: connectInfo,
dirk@371
    83
                folder: ImapSync.defaultImapInboxName))
dirk@371
    84
dirk@371
    85
            appConfig.grandOperator.chainOperations(
dirk@371
    86
                operations, completionBlock: { [unowned self] error in
dirk@58
    87
                    GCD.onMain({
dirk@414
    88
                        Log.infoComponent(self.comp, "Sync completed, error: \(error)")
dirk@325
    89
                        self.appConfig?.model.save()
dirk@275
    90
                        self.state.isSynching = false
dirk@275
    91
                        refreshControl?.endRefreshing()
dirk@149
    92
                        self.updateUI()
dirk@58
    93
                    })
dirk@371
    94
            })
dirk@149
    95
            updateUI()
dirk@55
    96
        }
dirk@31
    97
    }
dirk@31
    98
dirk@196
    99
    @IBAction func newAccountCreatedSegue(segue: UIStoryboardSegue) {
dirk@275
   100
        fetchMailsRefreshControl()
dirk@196
   101
    }
dirk@196
   102
ana@143
   103
    func prepareFetchRequest() {
dirk@324
   104
        let predicates: [NSPredicate] = [NSPredicate.init(format: "bodyFetched = true")]
dirk@31
   105
        let fetchRequest = NSFetchRequest.init(entityName: Message.entityName())
dirk@31
   106
        fetchRequest.predicate = NSCompoundPredicate.init(
dirk@31
   107
            andPredicateWithSubpredicates: predicates)
dirk@324
   108
        fetchRequest.sortDescriptors = [NSSortDescriptor.init(key: "originationDate",
dirk@324
   109
            ascending: false)]
dirk@31
   110
        fetchController = NSFetchedResultsController.init(
dirk@31
   111
            fetchRequest: fetchRequest,
dirk@437
   112
            managedObjectContext: appConfig.coreDataUtil.managedObjectContext,
dirk@31
   113
            sectionNameKeyPath: nil, cacheName: nil)
dirk@31
   114
        fetchController?.delegate = self
dirk@31
   115
        do {
dirk@31
   116
            try fetchController?.performFetch()
dirk@31
   117
        } catch let err as NSError {
dirk@414
   118
            Log.errorComponent(comp, error: err)
dirk@31
   119
        }
dirk@31
   120
    }
dirk@31
   121
dirk@58
   122
    // MARK: - UI State
dirk@58
   123
dirk@58
   124
    func updateUI() {
dirk@275
   125
        if state.isSynching {
dirk@58
   126
            UIApplication.sharedApplication().networkActivityIndicatorVisible = true
dirk@58
   127
        } else {
dirk@58
   128
            UIApplication.sharedApplication().networkActivityIndicatorVisible = false
dirk@58
   129
        }
dirk@58
   130
    }
dirk@58
   131
dirk@31
   132
    // MARK: - UITableViewDataSource
dirk@31
   133
dirk@31
   134
    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
dirk@209
   135
        if let count = fetchController?.sections?.count {
dirk@209
   136
            return count
dirk@209
   137
        } else {
dirk@209
   138
            return 0
dirk@209
   139
        }
dirk@31
   140
    }
dirk@31
   141
dirk@31
   142
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
dirk@31
   143
        if fetchController?.sections?.count > 0 {
dirk@31
   144
            if let sections = fetchController?.sections {
dirk@31
   145
                let sectionInfo = sections[section]
dirk@31
   146
                return sectionInfo.numberOfObjects
dirk@31
   147
            }
dirk@31
   148
        }
dirk@31
   149
        return 0
dirk@31
   150
    }
dirk@31
   151
dirk@31
   152
    override func tableView(tableView: UITableView,
dirk@31
   153
                            cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
dirk@209
   154
        let cell = tableView.dequeueReusableCellWithIdentifier(
dirk@209
   155
            "EmailListViewCell", forIndexPath: indexPath) as! EmailListViewCell
dirk@31
   156
        configureCell(cell, indexPath: indexPath)
dirk@31
   157
        return cell
dirk@31
   158
    }
dirk@31
   159
dirk@31
   160
    func configureCell(cell: EmailListViewCell, indexPath: NSIndexPath) {
dirk@31
   161
        if let email = fetchController?.objectAtIndexPath(indexPath) as? Message {
dirk@342
   162
            UIHelper.putString(email.from?.displayString(), toLabel: cell.senderLabel)
dirk@342
   163
            UIHelper.putString(email.subject, toLabel: cell.subjectLabel)
dirk@342
   164
            UIHelper.putString(nil, toLabel: cell.summaryLabel)
dirk@32
   165
dirk@119
   166
            if let originationDate = email.originationDate {
dirk@342
   167
                UIHelper.putString(dateFormatter.stringFromDate(originationDate),
dirk@342
   168
                                   toLabel: cell.dateLabel)
dirk@32
   169
            } else {
dirk@342
   170
                UIHelper.putString(nil, toLabel: cell.dateLabel)
dirk@32
   171
            }
dirk@31
   172
        }
dirk@30
   173
    }
dirk@30
   174
ana@246
   175
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
dirk@361
   176
        if segue.identifier == segueCompose {
dirk@397
   177
            let destination = segue.destinationViewController
dirk@434
   178
                as! ComposeViewController
ana@246
   179
            destination.appConfig = appConfig
dirk@273
   180
        } else if segue.identifier == segueShowEmail {
dirk@273
   181
            guard
dirk@273
   182
                let vc = segue.destinationViewController as? EmailViewController,
dirk@273
   183
                let cell = sender as? UITableViewCell,
dirk@273
   184
                let indexPath = self.tableView.indexPathForCell(cell),
dirk@273
   185
                let email = fetchController?.objectAtIndexPath(indexPath) as? Message else {
dirk@273
   186
                    return
dirk@273
   187
            }
dirk@273
   188
            vc.appConfig = appConfig
dirk@273
   189
            vc.message = email
ana@246
   190
        }
ana@246
   191
    }
dirk@30
   192
}
dirk@30
   193
dirk@31
   194
extension EmailListViewController: NSFetchedResultsControllerDelegate {
dirk@31
   195
    func controllerWillChangeContent(controller: NSFetchedResultsController) {
dirk@31
   196
        tableView.beginUpdates()
dirk@30
   197
    }
dirk@30
   198
dirk@31
   199
    func controller(controller: NSFetchedResultsController,
dirk@31
   200
                    didChangeSection sectionInfo: NSFetchedResultsSectionInfo,
dirk@31
   201
                                     atIndex sectionIndex: Int,
dirk@31
   202
                                             forChangeType type: NSFetchedResultsChangeType) {
dirk@31
   203
        switch (type) {
dirk@31
   204
        case .Insert:
dirk@31
   205
            tableView.insertSections(NSIndexSet.init(index: sectionIndex),
dirk@31
   206
                                     withRowAnimation: .Fade)
dirk@31
   207
        case .Delete:
dirk@31
   208
            tableView.deleteSections(NSIndexSet.init(index: sectionIndex),
dirk@31
   209
                                     withRowAnimation: .Fade)
dirk@31
   210
        default:
dirk@414
   211
            Log.infoComponent(comp, "unhandled changeSectionType: \(type)")
dirk@31
   212
        }
dirk@30
   213
    }
dirk@30
   214
dirk@31
   215
    func controller(controller: NSFetchedResultsController, didChangeObject anObject: AnyObject,
dirk@31
   216
                    atIndexPath indexPath: NSIndexPath?,
dirk@31
   217
                                forChangeType type: NSFetchedResultsChangeType,
dirk@31
   218
                                              newIndexPath: NSIndexPath?) {
dirk@40
   219
        switch type {
dirk@40
   220
        case .Insert:
dirk@40
   221
            tableView.insertRowsAtIndexPaths([newIndexPath!], withRowAnimation: .Fade)
dirk@40
   222
        case .Delete:
dirk@40
   223
            tableView.deleteRowsAtIndexPaths([indexPath!], withRowAnimation: .Fade)
dirk@40
   224
        case .Update:
dirk@40
   225
            if let cell = tableView.cellForRowAtIndexPath(indexPath!) {
dirk@40
   226
                self.configureCell(cell as! EmailListViewCell, indexPath: indexPath!)
dirk@40
   227
            } else {
dirk@414
   228
                Log.warnComponent(comp, "Could not find cell for changed indexPath: \(indexPath!)")
dirk@31
   229
            }
dirk@40
   230
        case .Move:
dirk@40
   231
            if newIndexPath != indexPath {
dirk@40
   232
                tableView.deleteRowsAtIndexPaths([indexPath!], withRowAnimation: .Fade)
dirk@40
   233
                tableView.insertRowsAtIndexPaths([newIndexPath!], withRowAnimation: .Fade)
dirk@40
   234
            }
dirk@31
   235
        }
dirk@31
   236
    }
dirk@31
   237
dirk@31
   238
    func controllerDidChangeContent(controller: NSFetchedResultsController) {
dirk@31
   239
        tableView.endUpdates()
dirk@31
   240
    }
dirk@30
   241
}