pEpForiOS/UI/EmailDisplay/EmailListViewController.swift
author Dirk Zimmermann <dirk@pep-project.org>
Wed, 24 Aug 2016 12:46:11 +0200
changeset 593 ec1c8c29731c
parent 591 06e031dc9477
child 594 04edcc364282
permissions -rw-r--r--
IOS-108: Sync on appear settable by previous view
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@591
    13
class EmailListViewController: UITableViewController {
dirk@591
    14
    struct EmailListConfig {
dirk@591
    15
        let appConfig: AppConfig
dirk@583
    16
dirk@591
    17
        /** Set to whatever criteria you want to have mails displayed */
dirk@591
    18
        let predicate: NSPredicate?
dirk@583
    19
dirk@591
    20
        /** The sort descriptors to be used for displaying emails */
dirk@591
    21
        let sortDescriptors: [NSSortDescriptor]?
dirk@583
    22
dirk@591
    23
        /** If applicable, the accounts to refresh from */
dirk@591
    24
        let account: IAccount?
dirk@585
    25
dirk@591
    26
        /** If applicable, the folder name to sync */
dirk@591
    27
        let folderName: String?
dirk@593
    28
dirk@593
    29
        /** Should there be a sync directly when the view appears? */
dirk@593
    30
        let syncOnAppear: Bool
dirk@591
    31
    }
dirk@58
    32
dirk@583
    33
    struct UIState {
dirk@583
    34
        var isSynching: Bool = false
dirk@583
    35
    }
dirk@583
    36
    
dirk@273
    37
    let comp = "EmailListViewController"
dirk@361
    38
dirk@273
    39
    let segueShowEmail = "segueShowEmail"
dirk@397
    40
    let segueCompose = "segueCompose"
dirk@397
    41
    let segueUserSettings = "segueUserSettings"
dirk@30
    42
dirk@583
    43
    var config: EmailListConfig!
dirk@583
    44
dirk@212
    45
    var fetchController: NSFetchedResultsController?
dirk@275
    46
    var state = UIState()
dirk@342
    47
    let dateFormatter = UIHelper.dateFormatterEmailList()
dirk@275
    48
dirk@502
    49
    /**
dirk@502
    50
     The default background color for an email cell, as determined the first time a cell is
dirk@502
    51
     created.
dirk@502
    52
     */
dirk@502
    53
    var defaultCellBackgroundColor: UIColor?
dirk@502
    54
dirk@502
    55
    /**
dirk@502
    56
     Indicates whether `defaultCellBackgroundColor` has been determined or not.
dirk@502
    57
     */
dirk@502
    58
    var determinedCellBackgroundColor: Bool = false
dirk@502
    59
dirk@275
    60
    override func viewDidLoad() {
dirk@275
    61
        let refreshController = UIRefreshControl.init()
dirk@593
    62
        refreshController.addTarget(self, action: #selector(self.fetchMailsRefreshControl(_:)),
dirk@275
    63
                                    forControlEvents: UIControlEvents.ValueChanged)
dirk@275
    64
        self.refreshControl = refreshController
dirk@356
    65
        UIHelper.variableCellHeightsTableView(self.tableView)
dirk@275
    66
    }
dirk@31
    67
dirk@31
    68
    override func viewWillAppear(animated: Bool) {
dirk@209
    69
        prepareFetchRequest()
dirk@593
    70
        if config.syncOnAppear {
dirk@593
    71
            fetchMailsRefreshControl()
dirk@593
    72
        }
ana@207
    73
        super.viewWillAppear(animated)
ana@207
    74
    }
ana@152
    75
dirk@275
    76
    func fetchMailsRefreshControl(refreshControl: UIRefreshControl? = nil) {
dirk@583
    77
        if let account = config.account {
dirk@55
    78
            let connectInfo = account.connectInfo
dirk@55
    79
dirk@275
    80
            state.isSynching = true
dirk@588
    81
            updateUI()
dirk@368
    82
dirk@588
    83
            config.appConfig.grandOperator.fetchEmailsAndDecryptConnectInfos(
dirk@590
    84
                [connectInfo], folderName: config.folderName,
dirk@466
    85
                completionBlock: { error in
dirk@466
    86
                    Log.infoComponent(self.comp, "Sync completed, error: \(error)")
dirk@585
    87
                    if let err = error {
dirk@585
    88
                        UIHelper.displayError(err, controller: self)
dirk@585
    89
                    }
dirk@583
    90
                    self.config.appConfig.model.save()
dirk@466
    91
                    self.state.isSynching = false
dirk@466
    92
                    refreshControl?.endRefreshing()
dirk@466
    93
                    self.updateUI()
dirk@466
    94
            })
dirk@55
    95
        }
dirk@31
    96
    }
dirk@31
    97
dirk@452
    98
    @IBAction func mailSentSegue(segue: UIStoryboardSegue) {
dirk@452
    99
    }
dirk@452
   100
ana@143
   101
    func prepareFetchRequest() {
dirk@31
   102
        let fetchRequest = NSFetchRequest.init(entityName: Message.entityName())
dirk@583
   103
        fetchRequest.predicate = config.predicate
dirk@583
   104
        fetchRequest.sortDescriptors = config.sortDescriptors
dirk@31
   105
        fetchController = NSFetchedResultsController.init(
dirk@31
   106
            fetchRequest: fetchRequest,
dirk@583
   107
            managedObjectContext: config.appConfig.coreDataUtil.managedObjectContext,
dirk@31
   108
            sectionNameKeyPath: nil, cacheName: nil)
dirk@31
   109
        fetchController?.delegate = self
dirk@31
   110
        do {
dirk@31
   111
            try fetchController?.performFetch()
dirk@31
   112
        } catch let err as NSError {
dirk@414
   113
            Log.errorComponent(comp, error: err)
dirk@31
   114
        }
dirk@31
   115
    }
dirk@31
   116
dirk@58
   117
    // MARK: - UI State
dirk@58
   118
dirk@58
   119
    func updateUI() {
dirk@275
   120
        if state.isSynching {
dirk@58
   121
            UIApplication.sharedApplication().networkActivityIndicatorVisible = true
dirk@58
   122
        } else {
dirk@58
   123
            UIApplication.sharedApplication().networkActivityIndicatorVisible = false
dirk@58
   124
        }
dirk@58
   125
    }
dirk@58
   126
dirk@31
   127
    // MARK: - UITableViewDataSource
dirk@31
   128
dirk@31
   129
    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
dirk@209
   130
        if let count = fetchController?.sections?.count {
dirk@209
   131
            return count
dirk@209
   132
        } else {
dirk@209
   133
            return 0
dirk@209
   134
        }
dirk@31
   135
    }
dirk@31
   136
dirk@31
   137
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
dirk@31
   138
        if fetchController?.sections?.count > 0 {
dirk@31
   139
            if let sections = fetchController?.sections {
dirk@31
   140
                let sectionInfo = sections[section]
dirk@31
   141
                return sectionInfo.numberOfObjects
dirk@31
   142
            }
dirk@31
   143
        }
dirk@31
   144
        return 0
dirk@31
   145
    }
dirk@31
   146
dirk@31
   147
    override func tableView(tableView: UITableView,
dirk@31
   148
                            cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
dirk@209
   149
        let cell = tableView.dequeueReusableCellWithIdentifier(
dirk@209
   150
            "EmailListViewCell", forIndexPath: indexPath) as! EmailListViewCell
dirk@502
   151
        if !determinedCellBackgroundColor {
dirk@502
   152
            defaultCellBackgroundColor = cell.backgroundColor
dirk@502
   153
            determinedCellBackgroundColor = true
dirk@502
   154
        }
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@502
   161
            if let colorRating = PEPUtil.colorRatingFromInt(email.pepColorRating?.integerValue) {
dirk@574
   162
                let privacyColor = PEPUtil.colorFromPepRating(colorRating)
dirk@502
   163
                if let uiColor = UIHelper.textBackgroundUIColorFromPrivacyColor(privacyColor) {
dirk@502
   164
                    cell.backgroundColor = uiColor
dirk@502
   165
                } else {
dirk@502
   166
                    if determinedCellBackgroundColor {
dirk@502
   167
                        cell.backgroundColor = defaultCellBackgroundColor
dirk@502
   168
                    }
dirk@502
   169
                }
dirk@502
   170
            }
dirk@342
   171
            UIHelper.putString(email.from?.displayString(), toLabel: cell.senderLabel)
dirk@342
   172
            UIHelper.putString(email.subject, toLabel: cell.subjectLabel)
dirk@572
   173
dirk@572
   174
            // Snippet
dirk@565
   175
            if let text = email.longMessage {
dirk@572
   176
                let theText = text.replaceNewLinesWith(" ").trimmedWhiteSpace()
dirk@565
   177
                UIHelper.putString(theText, toLabel: cell.summaryLabel)
dirk@572
   178
            } else if let html = email.longMessageFormatted {
dirk@568
   179
                var text = html.extractTextFromHTML()
dirk@572
   180
                text = text.replaceNewLinesWith(" ").trimmedWhiteSpace()
dirk@568
   181
                UIHelper.putString(text, toLabel: cell.summaryLabel)
dirk@568
   182
            } else {
dirk@568
   183
                UIHelper.putString(nil, toLabel: cell.summaryLabel)
dirk@565
   184
            }
dirk@32
   185
dirk@480
   186
            if let receivedDate = email.receivedDate {
dirk@480
   187
                UIHelper.putString(dateFormatter.stringFromDate(receivedDate),
dirk@342
   188
                                   toLabel: cell.dateLabel)
dirk@32
   189
            } else {
dirk@342
   190
                UIHelper.putString(nil, toLabel: cell.dateLabel)
dirk@32
   191
            }
dirk@31
   192
        }
dirk@30
   193
    }
dirk@30
   194
ana@246
   195
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
dirk@361
   196
        if segue.identifier == segueCompose {
dirk@397
   197
            let destination = segue.destinationViewController
dirk@434
   198
                as! ComposeViewController
dirk@583
   199
            destination.appConfig = config.appConfig
dirk@273
   200
        } else if segue.identifier == segueShowEmail {
dirk@273
   201
            guard
dirk@273
   202
                let vc = segue.destinationViewController as? EmailViewController,
dirk@273
   203
                let cell = sender as? UITableViewCell,
dirk@273
   204
                let indexPath = self.tableView.indexPathForCell(cell),
dirk@273
   205
                let email = fetchController?.objectAtIndexPath(indexPath) as? Message else {
dirk@273
   206
                    return
dirk@273
   207
            }
dirk@583
   208
            vc.appConfig = config.appConfig
dirk@273
   209
            vc.message = email
ana@246
   210
        }
ana@246
   211
    }
dirk@30
   212
}
dirk@30
   213
dirk@31
   214
extension EmailListViewController: NSFetchedResultsControllerDelegate {
dirk@31
   215
    func controllerWillChangeContent(controller: NSFetchedResultsController) {
dirk@31
   216
        tableView.beginUpdates()
dirk@30
   217
    }
dirk@30
   218
dirk@31
   219
    func controller(controller: NSFetchedResultsController,
dirk@31
   220
                    didChangeSection sectionInfo: NSFetchedResultsSectionInfo,
dirk@31
   221
                                     atIndex sectionIndex: Int,
dirk@31
   222
                                             forChangeType type: NSFetchedResultsChangeType) {
dirk@31
   223
        switch (type) {
dirk@31
   224
        case .Insert:
dirk@31
   225
            tableView.insertSections(NSIndexSet.init(index: sectionIndex),
dirk@31
   226
                                     withRowAnimation: .Fade)
dirk@31
   227
        case .Delete:
dirk@31
   228
            tableView.deleteSections(NSIndexSet.init(index: sectionIndex),
dirk@31
   229
                                     withRowAnimation: .Fade)
dirk@31
   230
        default:
dirk@414
   231
            Log.infoComponent(comp, "unhandled changeSectionType: \(type)")
dirk@31
   232
        }
dirk@30
   233
    }
dirk@30
   234
dirk@31
   235
    func controller(controller: NSFetchedResultsController, didChangeObject anObject: AnyObject,
dirk@31
   236
                    atIndexPath indexPath: NSIndexPath?,
dirk@31
   237
                                forChangeType type: NSFetchedResultsChangeType,
dirk@31
   238
                                              newIndexPath: NSIndexPath?) {
dirk@40
   239
        switch type {
dirk@40
   240
        case .Insert:
dirk@40
   241
            tableView.insertRowsAtIndexPaths([newIndexPath!], withRowAnimation: .Fade)
dirk@40
   242
        case .Delete:
dirk@40
   243
            tableView.deleteRowsAtIndexPaths([indexPath!], withRowAnimation: .Fade)
dirk@40
   244
        case .Update:
dirk@40
   245
            if let cell = tableView.cellForRowAtIndexPath(indexPath!) {
dirk@40
   246
                self.configureCell(cell as! EmailListViewCell, indexPath: indexPath!)
dirk@40
   247
            } else {
dirk@414
   248
                Log.warnComponent(comp, "Could not find cell for changed indexPath: \(indexPath!)")
dirk@31
   249
            }
dirk@40
   250
        case .Move:
dirk@40
   251
            if newIndexPath != indexPath {
dirk@40
   252
                tableView.deleteRowsAtIndexPaths([indexPath!], withRowAnimation: .Fade)
dirk@40
   253
                tableView.insertRowsAtIndexPaths([newIndexPath!], withRowAnimation: .Fade)
dirk@40
   254
            }
dirk@31
   255
        }
dirk@31
   256
    }
dirk@31
   257
dirk@31
   258
    func controllerDidChangeContent(controller: NSFetchedResultsController) {
dirk@31
   259
        tableView.endUpdates()
dirk@31
   260
    }
ana@562
   261
ana@562
   262
    override func tableView(tableView: UITableView,
ana@562
   263
                            commitEditingStyle editingStyle: UITableViewCellEditingStyle,
ana@562
   264
                                               forRowAtIndexPath indexPath: NSIndexPath) {
ana@562
   265
        // TODO: Delete from the server and managed errors
ana@562
   266
        if editingStyle == .Delete {
ana@562
   267
            let managedObject = fetchController?.objectAtIndexPath(indexPath) as? Message
ana@562
   268
            fetchController?.managedObjectContext.deleteObject(managedObject!)
ana@562
   269
        }
ana@562
   270
    }
dirk@30
   271
}