pEpForiOS/UI/EmailDisplay/EmailListViewController.swift
author Dirk Zimmermann <dirk@pep-project.org>
Fri, 26 Aug 2016 10:02:23 +0200
changeset 615 5bd251bd89f7
parent 614 5a739a7466a0
child 620 1b83e1fcee8f
permissions -rw-r--r--
IOS-108 Fix refresh email list
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
ana@614
    62
    func dummyIsReadedMessage (indexPath: NSIndexPath)-> Bool{
ana@614
    63
ana@614
    64
        if (indexPath.row < 2) {
ana@614
    65
            return true
ana@614
    66
        } else if (indexPath.row > 2 || indexPath.row < 4) {
ana@614
    67
            return false;
ana@614
    68
        }
ana@614
    69
        else {
ana@614
    70
            return true
ana@614
    71
        }
ana@614
    72
    }
ana@614
    73
ana@614
    74
    func dummyIsImportantMessage(indexPath: NSIndexPath)-> Bool {
ana@614
    75
        if (indexPath.row < 2) {
ana@614
    76
            return false
ana@614
    77
        } else if (indexPath.row > 2 || indexPath.row < 4) {
ana@614
    78
            return true;
ana@614
    79
        }
ana@614
    80
        else {
ana@614
    81
            return true
ana@614
    82
        }
ana@614
    83
    }
ana@614
    84
dirk@275
    85
    override func viewDidLoad() {
dirk@594
    86
        refreshController = UIRefreshControl.init()
dirk@593
    87
        refreshController.addTarget(self, action: #selector(self.fetchMailsRefreshControl(_:)),
dirk@275
    88
                                    forControlEvents: UIControlEvents.ValueChanged)
dirk@356
    89
        UIHelper.variableCellHeightsTableView(self.tableView)
dirk@275
    90
    }
dirk@31
    91
dirk@31
    92
    override func viewWillAppear(animated: Bool) {
dirk@594
    93
        // Disable fetching if there is no account
dirk@594
    94
        if config.account != nil {
dirk@594
    95
            self.refreshControl = refreshController
dirk@594
    96
        } else {
dirk@594
    97
            self.refreshControl = nil
dirk@594
    98
        }
dirk@594
    99
dirk@209
   100
        prepareFetchRequest()
dirk@593
   101
        if config.syncOnAppear {
dirk@593
   102
            fetchMailsRefreshControl()
dirk@593
   103
        }
ana@207
   104
        super.viewWillAppear(animated)
ana@207
   105
    }
ana@152
   106
dirk@275
   107
    func fetchMailsRefreshControl(refreshControl: UIRefreshControl? = nil) {
dirk@583
   108
        if let account = config.account {
dirk@55
   109
            let connectInfo = account.connectInfo
dirk@55
   110
dirk@275
   111
            state.isSynching = true
dirk@588
   112
            updateUI()
dirk@368
   113
dirk@588
   114
            config.appConfig.grandOperator.fetchEmailsAndDecryptConnectInfos(
dirk@590
   115
                [connectInfo], folderName: config.folderName,
dirk@466
   116
                completionBlock: { error in
dirk@466
   117
                    Log.infoComponent(self.comp, "Sync completed, error: \(error)")
dirk@585
   118
                    if let err = error {
dirk@585
   119
                        UIHelper.displayError(err, controller: self)
dirk@585
   120
                    }
dirk@583
   121
                    self.config.appConfig.model.save()
dirk@466
   122
                    self.state.isSynching = false
dirk@466
   123
                    refreshControl?.endRefreshing()
dirk@466
   124
                    self.updateUI()
dirk@466
   125
            })
dirk@594
   126
        } else {
dirk@594
   127
            state.isSynching = false
dirk@594
   128
            updateUI()
dirk@55
   129
        }
dirk@31
   130
    }
dirk@31
   131
dirk@452
   132
    @IBAction func mailSentSegue(segue: UIStoryboardSegue) {
dirk@452
   133
    }
dirk@452
   134
ana@143
   135
    func prepareFetchRequest() {
dirk@31
   136
        let fetchRequest = NSFetchRequest.init(entityName: Message.entityName())
dirk@583
   137
        fetchRequest.predicate = config.predicate
dirk@583
   138
        fetchRequest.sortDescriptors = config.sortDescriptors
dirk@31
   139
        fetchController = NSFetchedResultsController.init(
dirk@31
   140
            fetchRequest: fetchRequest,
dirk@583
   141
            managedObjectContext: config.appConfig.coreDataUtil.managedObjectContext,
dirk@31
   142
            sectionNameKeyPath: nil, cacheName: nil)
dirk@31
   143
        fetchController?.delegate = self
dirk@31
   144
        do {
dirk@31
   145
            try fetchController?.performFetch()
dirk@31
   146
        } catch let err as NSError {
dirk@414
   147
            Log.errorComponent(comp, error: err)
dirk@31
   148
        }
dirk@31
   149
    }
dirk@31
   150
dirk@58
   151
    // MARK: - UI State
dirk@58
   152
dirk@58
   153
    func updateUI() {
dirk@275
   154
        if state.isSynching {
dirk@58
   155
            UIApplication.sharedApplication().networkActivityIndicatorVisible = true
dirk@58
   156
        } else {
dirk@58
   157
            UIApplication.sharedApplication().networkActivityIndicatorVisible = false
dirk@594
   158
            self.refreshControl?.endRefreshing()
dirk@58
   159
        }
dirk@58
   160
    }
dirk@58
   161
dirk@31
   162
    // MARK: - UITableViewDataSource
dirk@31
   163
dirk@31
   164
    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
dirk@209
   165
        if let count = fetchController?.sections?.count {
dirk@209
   166
            return count
dirk@209
   167
        } else {
dirk@209
   168
            return 0
dirk@209
   169
        }
dirk@31
   170
    }
dirk@31
   171
dirk@31
   172
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
dirk@31
   173
        if fetchController?.sections?.count > 0 {
dirk@31
   174
            if let sections = fetchController?.sections {
dirk@31
   175
                let sectionInfo = sections[section]
dirk@31
   176
                return sectionInfo.numberOfObjects
dirk@31
   177
            }
dirk@31
   178
        }
dirk@31
   179
        return 0
dirk@31
   180
    }
dirk@31
   181
dirk@31
   182
    override func tableView(tableView: UITableView,
dirk@31
   183
                            cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
dirk@209
   184
        let cell = tableView.dequeueReusableCellWithIdentifier(
dirk@209
   185
            "EmailListViewCell", forIndexPath: indexPath) as! EmailListViewCell
dirk@502
   186
        if !determinedCellBackgroundColor {
dirk@502
   187
            defaultCellBackgroundColor = cell.backgroundColor
dirk@502
   188
            determinedCellBackgroundColor = true
dirk@502
   189
        }
dirk@31
   190
        configureCell(cell, indexPath: indexPath)
dirk@31
   191
        return cell
dirk@31
   192
    }
dirk@31
   193
dirk@31
   194
    func configureCell(cell: EmailListViewCell, indexPath: NSIndexPath) {
dirk@31
   195
        if let email = fetchController?.objectAtIndexPath(indexPath) as? Message {
dirk@502
   196
            if let colorRating = PEPUtil.colorRatingFromInt(email.pepColorRating?.integerValue) {
dirk@574
   197
                let privacyColor = PEPUtil.colorFromPepRating(colorRating)
dirk@502
   198
                if let uiColor = UIHelper.textBackgroundUIColorFromPrivacyColor(privacyColor) {
dirk@502
   199
                    cell.backgroundColor = uiColor
dirk@502
   200
                } else {
dirk@502
   201
                    if determinedCellBackgroundColor {
dirk@502
   202
                        cell.backgroundColor = defaultCellBackgroundColor
dirk@502
   203
                    }
dirk@502
   204
                }
dirk@502
   205
            }
dirk@342
   206
            UIHelper.putString(email.from?.displayString(), toLabel: cell.senderLabel)
dirk@342
   207
            UIHelper.putString(email.subject, toLabel: cell.subjectLabel)
dirk@572
   208
dirk@572
   209
            // Snippet
dirk@565
   210
            if let text = email.longMessage {
dirk@572
   211
                let theText = text.replaceNewLinesWith(" ").trimmedWhiteSpace()
dirk@565
   212
                UIHelper.putString(theText, toLabel: cell.summaryLabel)
dirk@572
   213
            } else if let html = email.longMessageFormatted {
dirk@568
   214
                var text = html.extractTextFromHTML()
dirk@572
   215
                text = text.replaceNewLinesWith(" ").trimmedWhiteSpace()
dirk@568
   216
                UIHelper.putString(text, toLabel: cell.summaryLabel)
dirk@568
   217
            } else {
dirk@568
   218
                UIHelper.putString(nil, toLabel: cell.summaryLabel)
dirk@565
   219
            }
dirk@32
   220
dirk@480
   221
            if let receivedDate = email.receivedDate {
dirk@480
   222
                UIHelper.putString(dateFormatter.stringFromDate(receivedDate),
dirk@342
   223
                                   toLabel: cell.dateLabel)
dirk@32
   224
            } else {
dirk@342
   225
                UIHelper.putString(nil, toLabel: cell.dateLabel)
dirk@32
   226
            }
dirk@31
   227
        }
dirk@30
   228
    }
dirk@30
   229
ana@246
   230
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
dirk@606
   231
        // Make sure the current account is set, if defined
dirk@606
   232
        config.appConfig.currentAccount = config.account
dirk@606
   233
dirk@361
   234
        if segue.identifier == segueCompose {
dirk@397
   235
            let destination = segue.destinationViewController
dirk@434
   236
                as! ComposeViewController
dirk@583
   237
            destination.appConfig = config.appConfig
dirk@273
   238
        } else if segue.identifier == segueShowEmail {
dirk@273
   239
            guard
dirk@273
   240
                let vc = segue.destinationViewController as? EmailViewController,
dirk@273
   241
                let cell = sender as? UITableViewCell,
dirk@273
   242
                let indexPath = self.tableView.indexPathForCell(cell),
dirk@273
   243
                let email = fetchController?.objectAtIndexPath(indexPath) as? Message else {
dirk@273
   244
                    return
dirk@273
   245
            }
dirk@583
   246
            vc.appConfig = config.appConfig
dirk@273
   247
            vc.message = email
ana@246
   248
        }
ana@246
   249
    }
dirk@30
   250
}
dirk@30
   251
dirk@31
   252
extension EmailListViewController: NSFetchedResultsControllerDelegate {
dirk@31
   253
    func controllerWillChangeContent(controller: NSFetchedResultsController) {
dirk@31
   254
        tableView.beginUpdates()
dirk@30
   255
    }
dirk@30
   256
dirk@31
   257
    func controller(controller: NSFetchedResultsController,
dirk@31
   258
                    didChangeSection sectionInfo: NSFetchedResultsSectionInfo,
dirk@31
   259
                                     atIndex sectionIndex: Int,
dirk@31
   260
                                             forChangeType type: NSFetchedResultsChangeType) {
dirk@31
   261
        switch (type) {
dirk@31
   262
        case .Insert:
dirk@31
   263
            tableView.insertSections(NSIndexSet.init(index: sectionIndex),
dirk@31
   264
                                     withRowAnimation: .Fade)
dirk@31
   265
        case .Delete:
dirk@31
   266
            tableView.deleteSections(NSIndexSet.init(index: sectionIndex),
dirk@31
   267
                                     withRowAnimation: .Fade)
dirk@31
   268
        default:
dirk@414
   269
            Log.infoComponent(comp, "unhandled changeSectionType: \(type)")
dirk@31
   270
        }
dirk@30
   271
    }
dirk@30
   272
dirk@31
   273
    func controller(controller: NSFetchedResultsController, didChangeObject anObject: AnyObject,
dirk@31
   274
                    atIndexPath indexPath: NSIndexPath?,
dirk@31
   275
                                forChangeType type: NSFetchedResultsChangeType,
dirk@31
   276
                                              newIndexPath: NSIndexPath?) {
dirk@40
   277
        switch type {
dirk@40
   278
        case .Insert:
dirk@40
   279
            tableView.insertRowsAtIndexPaths([newIndexPath!], withRowAnimation: .Fade)
dirk@40
   280
        case .Delete:
dirk@40
   281
            tableView.deleteRowsAtIndexPaths([indexPath!], withRowAnimation: .Fade)
dirk@40
   282
        case .Update:
dirk@40
   283
            if let cell = tableView.cellForRowAtIndexPath(indexPath!) {
dirk@40
   284
                self.configureCell(cell as! EmailListViewCell, indexPath: indexPath!)
dirk@40
   285
            } else {
dirk@414
   286
                Log.warnComponent(comp, "Could not find cell for changed indexPath: \(indexPath!)")
dirk@31
   287
            }
dirk@40
   288
        case .Move:
dirk@40
   289
            if newIndexPath != indexPath {
dirk@40
   290
                tableView.deleteRowsAtIndexPaths([indexPath!], withRowAnimation: .Fade)
dirk@40
   291
                tableView.insertRowsAtIndexPaths([newIndexPath!], withRowAnimation: .Fade)
dirk@40
   292
            }
dirk@31
   293
        }
dirk@31
   294
    }
dirk@31
   295
dirk@31
   296
    func controllerDidChangeContent(controller: NSFetchedResultsController) {
dirk@31
   297
        tableView.endUpdates()
dirk@31
   298
    }
ana@562
   299
ana@599
   300
    override func tableView(tableView: UITableView, editActionsForRowAtIndexPath
ana@599
   301
                  indexPath: NSIndexPath)-> [UITableViewRowAction]? {
ana@614
   302
        let cell = tableView.cellForRowAtIndexPath(indexPath) as! EmailListViewCell
ana@599
   303
ana@614
   304
        let isFlagCompletionHandler: (UITableViewRowAction, NSIndexPath) -> Void =
ana@601
   305
            { (action, indexPath) in
ana@614
   306
                cell.isImportantImage.hidden = false
ana@614
   307
                cell.isImportantImage.backgroundColor = UIColor.orangeColor()
ana@614
   308
                self.tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: .None)
ana@601
   309
            }
ana@614
   310
        let localizedIsFlagTitle = NSLocalizedString(
ana@614
   311
            "Flag",
ana@614
   312
            comment: "Flag button title in swipe action on EmailListViewController")
ana@602
   313
ana@614
   314
        let isFlagAction = UITableViewRowAction(style: .Default, title: localizedIsFlagTitle,
ana@614
   315
         handler: isFlagCompletionHandler)
ana@614
   316
        isFlagAction.backgroundColor = UIColor.orangeColor()
ana@599
   317
ana@601
   318
        let deleteCompletionHandler: (UITableViewRowAction, NSIndexPath) -> Void =
ana@601
   319
            { (action, indexPath) in
ana@601
   320
                let managedObject = self.fetchController?.objectAtIndexPath(indexPath) as? Message
ana@601
   321
                self.fetchController?.managedObjectContext.deleteObject(managedObject!)
ana@601
   322
            }
ana@602
   323
        let localizedDeleteTitle = NSLocalizedString(
ana@602
   324
            "Erase",
ana@602
   325
            comment: "Erase button title in swipe action on EmailListViewController")
ana@601
   326
        let deleteAction = UITableViewRowAction(style: .Default, title: localizedDeleteTitle,
ana@601
   327
                                                handler: deleteCompletionHandler)
ana@614
   328
ana@614
   329
        let isReadCompletionHandler: (UITableViewRowAction, NSIndexPath) -> Void =
ana@614
   330
            { (action, indexPath) in
ana@614
   331
                cell.isImportantImage.hidden = false
ana@614
   332
                cell.isImportantImage.backgroundColor = UIColor.blueColor()
ana@614
   333
                self.tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: .None)
ana@614
   334
            }
ana@614
   335
        let localizedisReadTitle = NSLocalizedString(
ana@614
   336
            "Read",
ana@614
   337
            comment: "Read button title in swipe action on EmailListViewController")
ana@614
   338
        let isReadAction = UITableViewRowAction(style: .Default, title: localizedisReadTitle,
ana@614
   339
                                                handler: isReadCompletionHandler)
ana@614
   340
        isReadAction.backgroundColor = UIColor.blueColor()
ana@614
   341
        return [deleteAction,isFlagAction,isReadAction]
ana@599
   342
    }
dirk@30
   343
}