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