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