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