pEpForiOS/UI/EmailDisplay/EmailListViewController.swift
author Dirk Zimmermann <dirk@pep-project.org>
Wed, 22 Jun 2016 12:17:34 +0200
changeset 371 bbd508223c51
parent 368 f45028b1ac03
child 376 a414e8f07b57
permissions -rw-r--r--
Fetching folders on first sync, not caching connections
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@361
    21
    let segueCompose = "composeSegue"
dirk@361
    22
    let segueUserSettings = "userSettings"
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
ana@152
    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@365
    50
            PEPUtil.myselfFromAccount(
dirk@365
    51
                account as! Account, block: { identity in
dirk@365
    52
                    Log.info(self.comp,
dirk@365
    53
                        "myself: \(identity[kPepAddress]) -> \(identity[kPepFingerprint])")
dirk@365
    54
            })
dirk@275
    55
            fetchMailsRefreshControl()
dirk@365
    56
ana@152
    57
        }
ana@207
    58
        super.viewWillAppear(animated)
ana@207
    59
    }
ana@152
    60
dirk@275
    61
    func refresh(refreshControl: UIRefreshControl) {
dirk@275
    62
        fetchMailsRefreshControl(refreshControl)
dirk@275
    63
    }
dirk@275
    64
dirk@275
    65
    func fetchMailsRefreshControl(refreshControl: UIRefreshControl? = nil) {
dirk@115
    66
        if let account = appConfig?.model.fetchLastAccount() {
dirk@55
    67
            let connectInfo = account.connectInfo
dirk@55
    68
dirk@275
    69
            state.isSynching = true
dirk@368
    70
dirk@371
    71
            var operations: [BaseOperation] = []
dirk@371
    72
            if shouldFetchFolders {
dirk@371
    73
                shouldFetchFolders = false
dirk@371
    74
                operations.append(CreateLocalSpecialFoldersOperation.init(
dirk@371
    75
                    grandOperator: appConfig.grandOperator, accountEmail: account.email))
dirk@371
    76
                operations.append(FetchFoldersOperation.init(
dirk@371
    77
                    grandOperator: appConfig.grandOperator, connectInfo: connectInfo))
dirk@371
    78
            }
dirk@371
    79
            operations.append(PrefetchEmailsOperation.init(
dirk@371
    80
                grandOperator: appConfig.grandOperator, connectInfo: connectInfo,
dirk@371
    81
                folder: ImapSync.defaultImapInboxName))
dirk@371
    82
dirk@371
    83
            appConfig.grandOperator.chainOperations(
dirk@371
    84
                operations, completionBlock: { [unowned self] error in
dirk@58
    85
                    GCD.onMain({
dirk@67
    86
                        Log.info(self.comp, "Sync completed, error: \(error)")
dirk@325
    87
                        self.appConfig?.model.save()
dirk@275
    88
                        self.state.isSynching = false
dirk@275
    89
                        refreshControl?.endRefreshing()
dirk@149
    90
                        self.updateUI()
dirk@58
    91
                    })
dirk@371
    92
            })
dirk@149
    93
            updateUI()
dirk@55
    94
        }
dirk@31
    95
    }
dirk@31
    96
dirk@196
    97
    @IBAction func newAccountCreatedSegue(segue: UIStoryboardSegue) {
dirk@275
    98
        fetchMailsRefreshControl()
dirk@196
    99
    }
dirk@196
   100
ana@143
   101
    func prepareFetchRequest() {
dirk@324
   102
        let predicates: [NSPredicate] = [NSPredicate.init(format: "bodyFetched = true")]
dirk@31
   103
        let fetchRequest = NSFetchRequest.init(entityName: Message.entityName())
dirk@31
   104
        fetchRequest.predicate = NSCompoundPredicate.init(
dirk@31
   105
            andPredicateWithSubpredicates: predicates)
dirk@324
   106
        fetchRequest.sortDescriptors = [NSSortDescriptor.init(key: "originationDate",
dirk@324
   107
            ascending: false)]
dirk@31
   108
        fetchController = NSFetchedResultsController.init(
dirk@31
   109
            fetchRequest: fetchRequest,
dirk@31
   110
            managedObjectContext: appConfig!.coreDataUtil.managedObjectContext,
dirk@31
   111
            sectionNameKeyPath: nil, cacheName: nil)
dirk@31
   112
        fetchController?.delegate = self
dirk@31
   113
        do {
dirk@31
   114
            try fetchController?.performFetch()
dirk@31
   115
        } catch let err as NSError {
dirk@31
   116
            Log.error(comp, error: err)
dirk@31
   117
        }
dirk@31
   118
    }
dirk@31
   119
dirk@58
   120
    // MARK: - UI State
dirk@58
   121
dirk@58
   122
    func updateUI() {
dirk@275
   123
        if state.isSynching {
dirk@58
   124
            UIApplication.sharedApplication().networkActivityIndicatorVisible = true
dirk@58
   125
        } else {
dirk@58
   126
            UIApplication.sharedApplication().networkActivityIndicatorVisible = false
dirk@58
   127
        }
dirk@58
   128
    }
dirk@58
   129
dirk@31
   130
    // MARK: - UITableViewDataSource
dirk@31
   131
dirk@31
   132
    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
dirk@209
   133
        if let count = fetchController?.sections?.count {
dirk@209
   134
            return count
dirk@209
   135
        } else {
dirk@209
   136
            return 0
dirk@209
   137
        }
dirk@31
   138
    }
dirk@31
   139
dirk@31
   140
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
dirk@31
   141
        if fetchController?.sections?.count > 0 {
dirk@31
   142
            if let sections = fetchController?.sections {
dirk@31
   143
                let sectionInfo = sections[section]
dirk@31
   144
                return sectionInfo.numberOfObjects
dirk@31
   145
            }
dirk@31
   146
        }
dirk@31
   147
        return 0
dirk@31
   148
    }
dirk@31
   149
dirk@31
   150
    override func tableView(tableView: UITableView,
dirk@31
   151
                            cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
dirk@209
   152
        let cell = tableView.dequeueReusableCellWithIdentifier(
dirk@209
   153
            "EmailListViewCell", forIndexPath: indexPath) as! EmailListViewCell
dirk@31
   154
        configureCell(cell, indexPath: indexPath)
dirk@31
   155
        return cell
dirk@31
   156
    }
dirk@31
   157
dirk@31
   158
    func configureCell(cell: EmailListViewCell, indexPath: NSIndexPath) {
dirk@31
   159
        if let email = fetchController?.objectAtIndexPath(indexPath) as? Message {
dirk@342
   160
            UIHelper.putString(email.from?.displayString(), toLabel: cell.senderLabel)
dirk@342
   161
            UIHelper.putString(email.subject, toLabel: cell.subjectLabel)
dirk@342
   162
            UIHelper.putString(nil, toLabel: cell.summaryLabel)
dirk@32
   163
dirk@119
   164
            if let originationDate = email.originationDate {
dirk@342
   165
                UIHelper.putString(dateFormatter.stringFromDate(originationDate),
dirk@342
   166
                                   toLabel: cell.dateLabel)
dirk@32
   167
            } else {
dirk@342
   168
                UIHelper.putString(nil, toLabel: cell.dateLabel)
dirk@32
   169
            }
dirk@31
   170
        }
dirk@30
   171
    }
dirk@30
   172
ana@246
   173
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
dirk@361
   174
        if segue.identifier == segueCompose {
ana@334
   175
            let destination = segue.destinationViewController as! ComposeWithAutocompleteViewController
ana@246
   176
            destination.appConfig = appConfig
dirk@273
   177
        } else if segue.identifier == segueShowEmail {
dirk@273
   178
            guard
dirk@273
   179
                let vc = segue.destinationViewController as? EmailViewController,
dirk@273
   180
                let cell = sender as? UITableViewCell,
dirk@273
   181
                let indexPath = self.tableView.indexPathForCell(cell),
dirk@273
   182
                let email = fetchController?.objectAtIndexPath(indexPath) as? Message else {
dirk@273
   183
                    return
dirk@273
   184
            }
dirk@273
   185
            vc.appConfig = appConfig
dirk@273
   186
            vc.message = email
ana@246
   187
        }
ana@246
   188
    }
ana@246
   189
dirk@30
   190
}
dirk@30
   191
dirk@31
   192
extension EmailListViewController: NSFetchedResultsControllerDelegate {
dirk@31
   193
    func controllerWillChangeContent(controller: NSFetchedResultsController) {
dirk@31
   194
        tableView.beginUpdates()
dirk@30
   195
    }
dirk@30
   196
dirk@31
   197
    func controller(controller: NSFetchedResultsController,
dirk@31
   198
                    didChangeSection sectionInfo: NSFetchedResultsSectionInfo,
dirk@31
   199
                                     atIndex sectionIndex: Int,
dirk@31
   200
                                             forChangeType type: NSFetchedResultsChangeType) {
dirk@31
   201
        switch (type) {
dirk@31
   202
        case .Insert:
dirk@31
   203
            tableView.insertSections(NSIndexSet.init(index: sectionIndex),
dirk@31
   204
                                     withRowAnimation: .Fade)
dirk@31
   205
        case .Delete:
dirk@31
   206
            tableView.deleteSections(NSIndexSet.init(index: sectionIndex),
dirk@31
   207
                                     withRowAnimation: .Fade)
dirk@31
   208
        default:
dirk@31
   209
            Log.info(comp, "unhandled changeSectionType: \(type)")
dirk@31
   210
        }
dirk@30
   211
    }
dirk@30
   212
dirk@31
   213
    func controller(controller: NSFetchedResultsController, didChangeObject anObject: AnyObject,
dirk@31
   214
                    atIndexPath indexPath: NSIndexPath?,
dirk@31
   215
                                forChangeType type: NSFetchedResultsChangeType,
dirk@31
   216
                                              newIndexPath: NSIndexPath?) {
dirk@40
   217
        switch type {
dirk@40
   218
        case .Insert:
dirk@40
   219
            tableView.insertRowsAtIndexPaths([newIndexPath!], withRowAnimation: .Fade)
dirk@40
   220
        case .Delete:
dirk@40
   221
            tableView.deleteRowsAtIndexPaths([indexPath!], withRowAnimation: .Fade)
dirk@40
   222
        case .Update:
dirk@40
   223
            if let cell = tableView.cellForRowAtIndexPath(indexPath!) {
dirk@40
   224
                self.configureCell(cell as! EmailListViewCell, indexPath: indexPath!)
dirk@40
   225
            } else {
dirk@40
   226
                Log.warn(comp, "Could not find cell for changed indexPath: \(indexPath!)")
dirk@31
   227
            }
dirk@40
   228
        case .Move:
dirk@40
   229
            if newIndexPath != indexPath {
dirk@40
   230
                tableView.deleteRowsAtIndexPaths([indexPath!], withRowAnimation: .Fade)
dirk@40
   231
                tableView.insertRowsAtIndexPaths([newIndexPath!], withRowAnimation: .Fade)
dirk@40
   232
            }
dirk@31
   233
        }
dirk@31
   234
    }
dirk@31
   235
dirk@31
   236
    func controllerDidChangeContent(controller: NSFetchedResultsController) {
dirk@31
   237
        tableView.endUpdates()
dirk@31
   238
    }
dirk@30
   239
}