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