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