pEpForiOS/UI/EmailDisplay/EmailListViewController.swift
author Dirk Zimmermann <dirk@pep-project.org>
Thu, 15 Sep 2016 11:30:55 +0200
changeset 707 82ce882f3a11
parent 706 6572d60e11f4
child 709 9fcba4722858
permissions -rw-r--r--
IOS-104 Showing errors and logging them now supports optionals
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@606
    23
        /** If applicable, the account 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@594
    60
    var refreshController: UIRefreshControl!
dirk@594
    61
dirk@705
    62
    /**
dirk@705
    63
     The message that should be saved as a draft when compose gets aborted.
dirk@705
    64
     */
dirk@705
    65
    var draftMessageToStore: IMessage?
dirk@705
    66
ana@620
    67
    func isReadedMessage(message: IMessage)-> Bool {
dirk@637
    68
        return message.flagSeen.boolValue
ana@614
    69
    }
ana@614
    70
ana@620
    71
    func isImportantMessage(message: IMessage)-> Bool {
ana@621
    72
        return message.flagFlagged.boolValue
ana@614
    73
    }
ana@614
    74
dirk@275
    75
    override func viewDidLoad() {
dirk@594
    76
        refreshController = UIRefreshControl.init()
dirk@593
    77
        refreshController.addTarget(self, action: #selector(self.fetchMailsRefreshControl(_:)),
dirk@275
    78
                                    forControlEvents: UIControlEvents.ValueChanged)
dirk@356
    79
        UIHelper.variableCellHeightsTableView(self.tableView)
dirk@275
    80
    }
dirk@31
    81
dirk@31
    82
    override func viewWillAppear(animated: Bool) {
dirk@594
    83
        // Disable fetching if there is no account
dirk@594
    84
        if config.account != nil {
dirk@594
    85
            self.refreshControl = refreshController
dirk@594
    86
        } else {
dirk@594
    87
            self.refreshControl = nil
dirk@594
    88
        }
dirk@594
    89
dirk@209
    90
        prepareFetchRequest()
dirk@593
    91
        if config.syncOnAppear {
dirk@593
    92
            fetchMailsRefreshControl()
dirk@593
    93
        }
ana@207
    94
        super.viewWillAppear(animated)
ana@207
    95
    }
ana@152
    96
dirk@275
    97
    func fetchMailsRefreshControl(refreshControl: UIRefreshControl? = nil) {
dirk@583
    98
        if let account = config.account {
dirk@55
    99
            let connectInfo = account.connectInfo
dirk@55
   100
dirk@275
   101
            state.isSynching = true
dirk@588
   102
            updateUI()
dirk@368
   103
dirk@588
   104
            config.appConfig.grandOperator.fetchEmailsAndDecryptConnectInfos(
dirk@590
   105
                [connectInfo], folderName: config.folderName,
dirk@466
   106
                completionBlock: { error in
dirk@466
   107
                    Log.infoComponent(self.comp, "Sync completed, error: \(error)")
dirk@707
   108
                    UIHelper.displayError(error, controller: self)
dirk@583
   109
                    self.config.appConfig.model.save()
dirk@466
   110
                    self.state.isSynching = false
dirk@466
   111
                    refreshControl?.endRefreshing()
dirk@466
   112
                    self.updateUI()
dirk@466
   113
            })
dirk@594
   114
        } else {
dirk@594
   115
            state.isSynching = false
dirk@594
   116
            updateUI()
dirk@55
   117
        }
dirk@31
   118
    }
dirk@31
   119
dirk@452
   120
    @IBAction func mailSentSegue(segue: UIStoryboardSegue) {
dirk@452
   121
    }
dirk@452
   122
dirk@705
   123
    @IBAction func backFromComposeWithoutSavingDraftSegue(segue: UIStoryboardSegue) {
dirk@705
   124
    }
dirk@705
   125
dirk@705
   126
    @IBAction func backFromComposeSaveDraftSegue(segue: UIStoryboardSegue) {
dirk@705
   127
        // TODO: Save draft
dirk@705
   128
        guard let msg = draftMessageToStore else {
dirk@705
   129
            return
dirk@705
   130
        }
dirk@705
   131
        print("compose aborted, saving draft")
dirk@707
   132
dirk@707
   133
        state.isSynching = true
dirk@707
   134
        updateUI()
dirk@707
   135
dirk@706
   136
        config.appConfig.grandOperator.saveDraftMail(
dirk@706
   137
            msg, account: msg.folder.account, completionBlock: { error in
dirk@707
   138
                UIHelper.displayError(error, controller: self)
dirk@707
   139
                GCD.onMain() {
dirk@707
   140
                    self.state.isSynching = false
dirk@707
   141
                    self.updateUI()
dirk@707
   142
                }
dirk@706
   143
        })
dirk@705
   144
    }
dirk@705
   145
ana@143
   146
    func prepareFetchRequest() {
dirk@31
   147
        let fetchRequest = NSFetchRequest.init(entityName: Message.entityName())
dirk@583
   148
        fetchRequest.predicate = config.predicate
dirk@583
   149
        fetchRequest.sortDescriptors = config.sortDescriptors
dirk@31
   150
        fetchController = NSFetchedResultsController.init(
dirk@31
   151
            fetchRequest: fetchRequest,
dirk@583
   152
            managedObjectContext: config.appConfig.coreDataUtil.managedObjectContext,
dirk@31
   153
            sectionNameKeyPath: nil, cacheName: nil)
dirk@31
   154
        fetchController?.delegate = self
dirk@31
   155
        do {
dirk@31
   156
            try fetchController?.performFetch()
dirk@31
   157
        } catch let err as NSError {
dirk@414
   158
            Log.errorComponent(comp, error: err)
dirk@31
   159
        }
dirk@31
   160
    }
dirk@31
   161
dirk@58
   162
    // MARK: - UI State
dirk@58
   163
dirk@58
   164
    func updateUI() {
dirk@275
   165
        if state.isSynching {
dirk@58
   166
            UIApplication.sharedApplication().networkActivityIndicatorVisible = true
dirk@58
   167
        } else {
dirk@58
   168
            UIApplication.sharedApplication().networkActivityIndicatorVisible = false
dirk@594
   169
            self.refreshControl?.endRefreshing()
dirk@58
   170
        }
dirk@58
   171
    }
dirk@58
   172
dirk@31
   173
    // MARK: - UITableViewDataSource
dirk@31
   174
dirk@31
   175
    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
dirk@209
   176
        if let count = fetchController?.sections?.count {
dirk@209
   177
            return count
dirk@209
   178
        } else {
dirk@209
   179
            return 0
dirk@209
   180
        }
dirk@31
   181
    }
dirk@31
   182
dirk@31
   183
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
dirk@31
   184
        if fetchController?.sections?.count > 0 {
dirk@31
   185
            if let sections = fetchController?.sections {
dirk@31
   186
                let sectionInfo = sections[section]
dirk@31
   187
                return sectionInfo.numberOfObjects
dirk@31
   188
            }
dirk@31
   189
        }
dirk@31
   190
        return 0
dirk@31
   191
    }
dirk@31
   192
dirk@31
   193
    override func tableView(tableView: UITableView,
dirk@31
   194
                            cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
dirk@209
   195
        let cell = tableView.dequeueReusableCellWithIdentifier(
dirk@209
   196
            "EmailListViewCell", forIndexPath: indexPath) as! EmailListViewCell
dirk@502
   197
        if !determinedCellBackgroundColor {
dirk@502
   198
            defaultCellBackgroundColor = cell.backgroundColor
dirk@502
   199
            determinedCellBackgroundColor = true
dirk@502
   200
        }
dirk@31
   201
        configureCell(cell, indexPath: indexPath)
dirk@31
   202
        return cell
dirk@31
   203
    }
dirk@31
   204
dirk@31
   205
    func configureCell(cell: EmailListViewCell, indexPath: NSIndexPath) {
dirk@31
   206
        if let email = fetchController?.objectAtIndexPath(indexPath) as? Message {
dirk@502
   207
            if let colorRating = PEPUtil.colorRatingFromInt(email.pepColorRating?.integerValue) {
dirk@574
   208
                let privacyColor = PEPUtil.colorFromPepRating(colorRating)
dirk@502
   209
                if let uiColor = UIHelper.textBackgroundUIColorFromPrivacyColor(privacyColor) {
dirk@502
   210
                    cell.backgroundColor = uiColor
dirk@502
   211
                } else {
dirk@502
   212
                    if determinedCellBackgroundColor {
dirk@502
   213
                        cell.backgroundColor = defaultCellBackgroundColor
dirk@502
   214
                    }
dirk@502
   215
                }
dirk@502
   216
            }
dirk@342
   217
            UIHelper.putString(email.from?.displayString(), toLabel: cell.senderLabel)
dirk@342
   218
            UIHelper.putString(email.subject, toLabel: cell.subjectLabel)
dirk@572
   219
dirk@572
   220
            // Snippet
dirk@565
   221
            if let text = email.longMessage {
dirk@572
   222
                let theText = text.replaceNewLinesWith(" ").trimmedWhiteSpace()
dirk@565
   223
                UIHelper.putString(theText, toLabel: cell.summaryLabel)
dirk@572
   224
            } else if let html = email.longMessageFormatted {
dirk@568
   225
                var text = html.extractTextFromHTML()
dirk@572
   226
                text = text.replaceNewLinesWith(" ").trimmedWhiteSpace()
dirk@568
   227
                UIHelper.putString(text, toLabel: cell.summaryLabel)
dirk@568
   228
            } else {
dirk@568
   229
                UIHelper.putString(nil, toLabel: cell.summaryLabel)
dirk@565
   230
            }
dirk@32
   231
dirk@480
   232
            if let receivedDate = email.receivedDate {
dirk@480
   233
                UIHelper.putString(dateFormatter.stringFromDate(receivedDate),
dirk@342
   234
                                   toLabel: cell.dateLabel)
dirk@32
   235
            } else {
dirk@342
   236
                UIHelper.putString(nil, toLabel: cell.dateLabel)
dirk@32
   237
            }
ana@620
   238
ana@656
   239
            if (isImportantMessage(email) && isReadedMessage(email)) {
ana@666
   240
                cell.isImportantImage.hidden = false
ana@666
   241
                cell.isImportantImage.backgroundColor = UIColor.orangeColor()
ana@666
   242
            }
ana@666
   243
            else if (isImportantMessage(email) && !isReadedMessage(email)) {
ana@666
   244
                cell.isImportantImage.hidden = false
ana@656
   245
                cell.isImportantImage.backgroundColor = UIColor.blueColor()
ana@656
   246
                cell.isImportantImage.layer.borderWidth = 2
ana@656
   247
                cell.isImportantImage.layer.borderColor = UIColor.orangeColor().CGColor
ana@666
   248
            } else if (!isImportantMessage(email) && isReadedMessage(email)) {
ana@666
   249
                    cell.isImportantImage.hidden = true
ana@666
   250
            } else if (!isImportantMessage(email) && !isReadedMessage(email)) {
ana@620
   251
                cell.isImportantImage.hidden = false
ana@666
   252
                cell.isImportantImage.backgroundColor = UIColor.blueColor()
ana@620
   253
            }
dirk@31
   254
        }
dirk@30
   255
    }
dirk@30
   256
ana@246
   257
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
dirk@606
   258
        // Make sure the current account is set, if defined
dirk@606
   259
        config.appConfig.currentAccount = config.account
dirk@606
   260
dirk@361
   261
        if segue.identifier == segueCompose {
dirk@397
   262
            let destination = segue.destinationViewController
dirk@434
   263
                as! ComposeViewController
dirk@583
   264
            destination.appConfig = config.appConfig
dirk@273
   265
        } else if segue.identifier == segueShowEmail {
dirk@273
   266
            guard
dirk@273
   267
                let vc = segue.destinationViewController as? EmailViewController,
dirk@273
   268
                let cell = sender as? UITableViewCell,
dirk@273
   269
                let indexPath = self.tableView.indexPathForCell(cell),
dirk@273
   270
                let email = fetchController?.objectAtIndexPath(indexPath) as? Message else {
dirk@273
   271
                    return
dirk@273
   272
            }
dirk@583
   273
            vc.appConfig = config.appConfig
dirk@273
   274
            vc.message = email
ana@246
   275
        }
ana@246
   276
    }
dirk@30
   277
}
dirk@30
   278
dirk@31
   279
extension EmailListViewController: NSFetchedResultsControllerDelegate {
dirk@31
   280
    func controllerWillChangeContent(controller: NSFetchedResultsController) {
dirk@31
   281
        tableView.beginUpdates()
dirk@30
   282
    }
dirk@30
   283
dirk@31
   284
    func controller(controller: NSFetchedResultsController,
dirk@31
   285
                    didChangeSection sectionInfo: NSFetchedResultsSectionInfo,
dirk@31
   286
                                     atIndex sectionIndex: Int,
dirk@31
   287
                                             forChangeType type: NSFetchedResultsChangeType) {
dirk@31
   288
        switch (type) {
dirk@31
   289
        case .Insert:
dirk@31
   290
            tableView.insertSections(NSIndexSet.init(index: sectionIndex),
dirk@31
   291
                                     withRowAnimation: .Fade)
dirk@31
   292
        case .Delete:
dirk@31
   293
            tableView.deleteSections(NSIndexSet.init(index: sectionIndex),
dirk@31
   294
                                     withRowAnimation: .Fade)
dirk@31
   295
        default:
dirk@414
   296
            Log.infoComponent(comp, "unhandled changeSectionType: \(type)")
dirk@31
   297
        }
dirk@30
   298
    }
dirk@30
   299
dirk@31
   300
    func controller(controller: NSFetchedResultsController, didChangeObject anObject: AnyObject,
dirk@31
   301
                    atIndexPath indexPath: NSIndexPath?,
dirk@31
   302
                                forChangeType type: NSFetchedResultsChangeType,
dirk@31
   303
                                              newIndexPath: NSIndexPath?) {
dirk@40
   304
        switch type {
dirk@40
   305
        case .Insert:
dirk@40
   306
            tableView.insertRowsAtIndexPaths([newIndexPath!], withRowAnimation: .Fade)
dirk@40
   307
        case .Delete:
dirk@40
   308
            tableView.deleteRowsAtIndexPaths([indexPath!], withRowAnimation: .Fade)
dirk@40
   309
        case .Update:
dirk@40
   310
            if let cell = tableView.cellForRowAtIndexPath(indexPath!) {
dirk@40
   311
                self.configureCell(cell as! EmailListViewCell, indexPath: indexPath!)
dirk@40
   312
            } else {
dirk@414
   313
                Log.warnComponent(comp, "Could not find cell for changed indexPath: \(indexPath!)")
dirk@31
   314
            }
dirk@40
   315
        case .Move:
dirk@40
   316
            if newIndexPath != indexPath {
dirk@40
   317
                tableView.deleteRowsAtIndexPaths([indexPath!], withRowAnimation: .Fade)
dirk@40
   318
                tableView.insertRowsAtIndexPaths([newIndexPath!], withRowAnimation: .Fade)
dirk@40
   319
            }
dirk@31
   320
        }
dirk@31
   321
    }
dirk@31
   322
dirk@31
   323
    func controllerDidChangeContent(controller: NSFetchedResultsController) {
dirk@31
   324
        tableView.endUpdates()
dirk@31
   325
    }
ana@562
   326
ana@653
   327
    func syncFlagsToServer(message: IMessage) {
dirk@678
   328
        self.config.appConfig.grandOperator.syncFlagsToServerForFolder(
dirk@678
   329
            message.folder,
dirk@678
   330
            completionBlock: { error in
dirk@707
   331
                UIHelper.displayError(error, controller: self)
dirk@678
   332
        })
ana@653
   333
    }
ana@653
   334
ana@621
   335
    func createIsFlagAction(message: Message, cell: EmailListViewCell) -> UITableViewRowAction {
ana@599
   336
ana@620
   337
        // preparing the title action to show when user swipe
ana@620
   338
        var localizedIsFlagTitle = " "
ana@621
   339
        if (isImportantMessage(message)) {
ana@651
   340
            localizedIsFlagTitle = NSLocalizedString("Unflag",
ana@651
   341
            comment: "Unflag button title in swipe action on EmailListViewController")
ana@651
   342
        } else {
ana@620
   343
            localizedIsFlagTitle = NSLocalizedString("Flag",
ana@620
   344
            comment: "Flag button title in swipe action on EmailListViewController")
ana@620
   345
        }
ana@620
   346
ana@620
   347
        // preparing action to trigger when user swipe
ana@614
   348
        let isFlagCompletionHandler: (UITableViewRowAction, NSIndexPath) -> Void =
ana@601
   349
            { (action, indexPath) in
ana@651
   350
                if (self.isImportantMessage(message)) {
ana@651
   351
                    message.flagFlagged = false
ana@666
   352
ana@651
   353
                } else {
ana@651
   354
                    message.flagFlagged = true
ana@651
   355
                }
ana@666
   356
                message.updateFlags()
ana@653
   357
                self.syncFlagsToServer(message)
ana@614
   358
                self.tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: .None)
ana@601
   359
            }
ana@620
   360
        // creating the action
ana@620
   361
        let isFlagAction = UITableViewRowAction(style: .Default, title: localizedIsFlagTitle,
ana@620
   362
                                                handler: isFlagCompletionHandler)
ana@620
   363
        // changing default action color
ana@620
   364
        isFlagAction.backgroundColor = UIColor.orangeColor()
ana@602
   365
ana@620
   366
        return isFlagAction
ana@620
   367
    }
ana@620
   368
ana@620
   369
    func createDeleteAction (cell: EmailListViewCell) -> UITableViewRowAction {
ana@620
   370
ana@620
   371
        // preparing the title action to show when user swipe
ana@620
   372
        let localizedDeleteTitle = NSLocalizedString("Erase",
ana@620
   373
        comment: "Erase button title in swipe action on EmailListViewController")
ana@599
   374
ana@601
   375
        let deleteCompletionHandler: (UITableViewRowAction, NSIndexPath) -> Void =
ana@601
   376
            { (action, indexPath) in
ana@650
   377
                let managedObject = self.fetchController?.objectAtIndexPath(indexPath) as? IMessage
ana@650
   378
                managedObject?.flagDeleted = true
ana@651
   379
                managedObject?.updateFlags()
ana@653
   380
                self.syncFlagsToServer(managedObject!)
ana@601
   381
            }
ana@620
   382
ana@620
   383
        // creating the action
ana@601
   384
        let deleteAction = UITableViewRowAction(style: .Default, title: localizedDeleteTitle,
ana@601
   385
                                                handler: deleteCompletionHandler)
ana@620
   386
        return deleteAction
ana@620
   387
    }
ana@620
   388
ana@621
   389
    func createIsReadAction (message: Message, cell: EmailListViewCell) -> UITableViewRowAction {
ana@620
   390
ana@620
   391
        // preparing the title action to show when user swipe
ana@620
   392
        var localizedisReadTitle = " "
ana@621
   393
        if (isReadedMessage(message)) {
ana@651
   394
            localizedisReadTitle = NSLocalizedString("Unread",
ana@651
   395
            comment: "Unread button title in swipe action on EmailListViewController")
ana@651
   396
        } else {
ana@620
   397
            localizedisReadTitle = NSLocalizedString("Read",
ana@620
   398
            comment: "Read button title in swipe action on EmailListViewController")
ana@620
   399
        }
ana@620
   400
ana@620
   401
        // creating the action
ana@614
   402
        let isReadCompletionHandler: (UITableViewRowAction, NSIndexPath) -> Void =
ana@614
   403
            { (action, indexPath) in
ana@651
   404
                if (self.isReadedMessage(message)) {
ana@651
   405
                    message.flagSeen = false
ana@651
   406
                    message.updateFlags()
ana@651
   407
                } else {
ana@651
   408
                    message.flagSeen = true
ana@651
   409
                    message.updateFlags()
ana@651
   410
                }
ana@653
   411
                self.syncFlagsToServer(message)
ana@614
   412
                self.tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: .None)
ana@614
   413
            }
ana@614
   414
        let isReadAction = UITableViewRowAction(style: .Default, title: localizedisReadTitle,
ana@614
   415
                                                handler: isReadCompletionHandler)
ana@614
   416
        isReadAction.backgroundColor = UIColor.blueColor()
ana@620
   417
ana@620
   418
        return isReadAction
ana@620
   419
    }
ana@620
   420
ana@620
   421
    override func tableView(tableView: UITableView, editActionsForRowAtIndexPath
ana@620
   422
                  indexPath: NSIndexPath)-> [UITableViewRowAction]? {
ana@620
   423
ana@620
   424
        let cell = tableView.cellForRowAtIndexPath(indexPath) as! EmailListViewCell
ana@620
   425
        let email = fetchController?.objectAtIndexPath(indexPath) as! Message
ana@621
   426
ana@621
   427
        let isFlagAction = createIsFlagAction(email, cell: cell)
ana@620
   428
        let deleteAction = createDeleteAction(cell)
ana@621
   429
        let isReadAction = createIsReadAction(email, cell: cell)
ana@614
   430
        return [deleteAction,isFlagAction,isReadAction]
ana@599
   431
    }
dirk@30
   432
}