pEpForiOS/UI/EmailDisplay/EmailListViewController.swift
author Dirk Zimmermann <dirk@pep-project.org>
Wed, 24 Aug 2016 12:10:18 +0200
changeset 591 06e031dc9477
parent 590 ec3de67ef11a
child 593 ec1c8c29731c
permissions -rw-r--r--
IOS-108 Display arbitrary folders
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@591
    23
        /** If applicable, the accounts 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@591
    28
    }
dirk@58
    29
dirk@583
    30
    struct UIState {
dirk@583
    31
        var isSynching: Bool = false
dirk@583
    32
    }
dirk@583
    33
    
dirk@273
    34
    let comp = "EmailListViewController"
dirk@361
    35
dirk@273
    36
    let segueShowEmail = "segueShowEmail"
dirk@397
    37
    let segueCompose = "segueCompose"
dirk@397
    38
    let segueUserSettings = "segueUserSettings"
dirk@30
    39
dirk@583
    40
    var config: EmailListConfig!
dirk@583
    41
dirk@212
    42
    var fetchController: NSFetchedResultsController?
dirk@275
    43
    var state = UIState()
dirk@342
    44
    let dateFormatter = UIHelper.dateFormatterEmailList()
dirk@275
    45
dirk@502
    46
    /**
dirk@502
    47
     The default background color for an email cell, as determined the first time a cell is
dirk@502
    48
     created.
dirk@502
    49
     */
dirk@502
    50
    var defaultCellBackgroundColor: UIColor?
dirk@502
    51
dirk@502
    52
    /**
dirk@502
    53
     Indicates whether `defaultCellBackgroundColor` has been determined or not.
dirk@502
    54
     */
dirk@502
    55
    var determinedCellBackgroundColor: Bool = false
dirk@502
    56
dirk@275
    57
    override func viewDidLoad() {
dirk@275
    58
        let refreshController = UIRefreshControl.init()
dirk@275
    59
        refreshController.addTarget(self, action: #selector(self.refresh(_:)),
dirk@275
    60
                                    forControlEvents: UIControlEvents.ValueChanged)
dirk@275
    61
        self.refreshControl = refreshController
dirk@356
    62
        UIHelper.variableCellHeightsTableView(self.tableView)
dirk@275
    63
    }
dirk@31
    64
dirk@31
    65
    override func viewWillAppear(animated: Bool) {
dirk@209
    66
        prepareFetchRequest()
ana@207
    67
        super.viewWillAppear(animated)
ana@207
    68
    }
ana@152
    69
dirk@275
    70
    func refresh(refreshControl: UIRefreshControl) {
dirk@275
    71
        fetchMailsRefreshControl(refreshControl)
dirk@275
    72
    }
dirk@275
    73
dirk@275
    74
    func fetchMailsRefreshControl(refreshControl: UIRefreshControl? = nil) {
dirk@583
    75
        if let account = config.account {
dirk@55
    76
            let connectInfo = account.connectInfo
dirk@55
    77
dirk@275
    78
            state.isSynching = true
dirk@588
    79
            updateUI()
dirk@368
    80
dirk@588
    81
            config.appConfig.grandOperator.fetchEmailsAndDecryptConnectInfos(
dirk@590
    82
                [connectInfo], folderName: config.folderName,
dirk@466
    83
                completionBlock: { error in
dirk@466
    84
                    Log.infoComponent(self.comp, "Sync completed, error: \(error)")
dirk@585
    85
                    if let err = error {
dirk@585
    86
                        UIHelper.displayError(err, controller: self)
dirk@585
    87
                    }
dirk@583
    88
                    self.config.appConfig.model.save()
dirk@466
    89
                    self.state.isSynching = false
dirk@466
    90
                    refreshControl?.endRefreshing()
dirk@466
    91
                    self.updateUI()
dirk@466
    92
            })
dirk@55
    93
        }
dirk@31
    94
    }
dirk@31
    95
dirk@452
    96
    @IBAction func mailSentSegue(segue: UIStoryboardSegue) {
dirk@452
    97
    }
dirk@452
    98
ana@143
    99
    func prepareFetchRequest() {
dirk@31
   100
        let fetchRequest = NSFetchRequest.init(entityName: Message.entityName())
dirk@583
   101
        fetchRequest.predicate = config.predicate
dirk@583
   102
        fetchRequest.sortDescriptors = config.sortDescriptors
dirk@31
   103
        fetchController = NSFetchedResultsController.init(
dirk@31
   104
            fetchRequest: fetchRequest,
dirk@583
   105
            managedObjectContext: config.appConfig.coreDataUtil.managedObjectContext,
dirk@31
   106
            sectionNameKeyPath: nil, cacheName: nil)
dirk@31
   107
        fetchController?.delegate = self
dirk@31
   108
        do {
dirk@31
   109
            try fetchController?.performFetch()
dirk@31
   110
        } catch let err as NSError {
dirk@414
   111
            Log.errorComponent(comp, error: err)
dirk@31
   112
        }
dirk@31
   113
    }
dirk@31
   114
dirk@58
   115
    // MARK: - UI State
dirk@58
   116
dirk@58
   117
    func updateUI() {
dirk@275
   118
        if state.isSynching {
dirk@58
   119
            UIApplication.sharedApplication().networkActivityIndicatorVisible = true
dirk@58
   120
        } else {
dirk@58
   121
            UIApplication.sharedApplication().networkActivityIndicatorVisible = false
dirk@58
   122
        }
dirk@58
   123
    }
dirk@58
   124
dirk@31
   125
    // MARK: - UITableViewDataSource
dirk@31
   126
dirk@31
   127
    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
dirk@209
   128
        if let count = fetchController?.sections?.count {
dirk@209
   129
            return count
dirk@209
   130
        } else {
dirk@209
   131
            return 0
dirk@209
   132
        }
dirk@31
   133
    }
dirk@31
   134
dirk@31
   135
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
dirk@31
   136
        if fetchController?.sections?.count > 0 {
dirk@31
   137
            if let sections = fetchController?.sections {
dirk@31
   138
                let sectionInfo = sections[section]
dirk@31
   139
                return sectionInfo.numberOfObjects
dirk@31
   140
            }
dirk@31
   141
        }
dirk@31
   142
        return 0
dirk@31
   143
    }
dirk@31
   144
dirk@31
   145
    override func tableView(tableView: UITableView,
dirk@31
   146
                            cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
dirk@209
   147
        let cell = tableView.dequeueReusableCellWithIdentifier(
dirk@209
   148
            "EmailListViewCell", forIndexPath: indexPath) as! EmailListViewCell
dirk@502
   149
        if !determinedCellBackgroundColor {
dirk@502
   150
            defaultCellBackgroundColor = cell.backgroundColor
dirk@502
   151
            determinedCellBackgroundColor = true
dirk@502
   152
        }
dirk@31
   153
        configureCell(cell, indexPath: indexPath)
dirk@31
   154
        return cell
dirk@31
   155
    }
dirk@31
   156
dirk@31
   157
    func configureCell(cell: EmailListViewCell, indexPath: NSIndexPath) {
dirk@31
   158
        if let email = fetchController?.objectAtIndexPath(indexPath) as? Message {
dirk@502
   159
            if let colorRating = PEPUtil.colorRatingFromInt(email.pepColorRating?.integerValue) {
dirk@574
   160
                let privacyColor = PEPUtil.colorFromPepRating(colorRating)
dirk@502
   161
                if let uiColor = UIHelper.textBackgroundUIColorFromPrivacyColor(privacyColor) {
dirk@502
   162
                    cell.backgroundColor = uiColor
dirk@502
   163
                } else {
dirk@502
   164
                    if determinedCellBackgroundColor {
dirk@502
   165
                        cell.backgroundColor = defaultCellBackgroundColor
dirk@502
   166
                    }
dirk@502
   167
                }
dirk@502
   168
            }
dirk@342
   169
            UIHelper.putString(email.from?.displayString(), toLabel: cell.senderLabel)
dirk@342
   170
            UIHelper.putString(email.subject, toLabel: cell.subjectLabel)
dirk@572
   171
dirk@572
   172
            // Snippet
dirk@565
   173
            if let text = email.longMessage {
dirk@572
   174
                let theText = text.replaceNewLinesWith(" ").trimmedWhiteSpace()
dirk@565
   175
                UIHelper.putString(theText, toLabel: cell.summaryLabel)
dirk@572
   176
            } else if let html = email.longMessageFormatted {
dirk@568
   177
                var text = html.extractTextFromHTML()
dirk@572
   178
                text = text.replaceNewLinesWith(" ").trimmedWhiteSpace()
dirk@568
   179
                UIHelper.putString(text, toLabel: cell.summaryLabel)
dirk@568
   180
            } else {
dirk@568
   181
                UIHelper.putString(nil, toLabel: cell.summaryLabel)
dirk@565
   182
            }
dirk@32
   183
dirk@480
   184
            if let receivedDate = email.receivedDate {
dirk@480
   185
                UIHelper.putString(dateFormatter.stringFromDate(receivedDate),
dirk@342
   186
                                   toLabel: cell.dateLabel)
dirk@32
   187
            } else {
dirk@342
   188
                UIHelper.putString(nil, toLabel: cell.dateLabel)
dirk@32
   189
            }
dirk@31
   190
        }
dirk@30
   191
    }
dirk@30
   192
ana@246
   193
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
dirk@361
   194
        if segue.identifier == segueCompose {
dirk@397
   195
            let destination = segue.destinationViewController
dirk@434
   196
                as! ComposeViewController
dirk@583
   197
            destination.appConfig = config.appConfig
dirk@273
   198
        } else if segue.identifier == segueShowEmail {
dirk@273
   199
            guard
dirk@273
   200
                let vc = segue.destinationViewController as? EmailViewController,
dirk@273
   201
                let cell = sender as? UITableViewCell,
dirk@273
   202
                let indexPath = self.tableView.indexPathForCell(cell),
dirk@273
   203
                let email = fetchController?.objectAtIndexPath(indexPath) as? Message else {
dirk@273
   204
                    return
dirk@273
   205
            }
dirk@583
   206
            vc.appConfig = config.appConfig
dirk@273
   207
            vc.message = email
ana@246
   208
        }
ana@246
   209
    }
dirk@30
   210
}
dirk@30
   211
dirk@31
   212
extension EmailListViewController: NSFetchedResultsControllerDelegate {
dirk@31
   213
    func controllerWillChangeContent(controller: NSFetchedResultsController) {
dirk@31
   214
        tableView.beginUpdates()
dirk@30
   215
    }
dirk@30
   216
dirk@31
   217
    func controller(controller: NSFetchedResultsController,
dirk@31
   218
                    didChangeSection sectionInfo: NSFetchedResultsSectionInfo,
dirk@31
   219
                                     atIndex sectionIndex: Int,
dirk@31
   220
                                             forChangeType type: NSFetchedResultsChangeType) {
dirk@31
   221
        switch (type) {
dirk@31
   222
        case .Insert:
dirk@31
   223
            tableView.insertSections(NSIndexSet.init(index: sectionIndex),
dirk@31
   224
                                     withRowAnimation: .Fade)
dirk@31
   225
        case .Delete:
dirk@31
   226
            tableView.deleteSections(NSIndexSet.init(index: sectionIndex),
dirk@31
   227
                                     withRowAnimation: .Fade)
dirk@31
   228
        default:
dirk@414
   229
            Log.infoComponent(comp, "unhandled changeSectionType: \(type)")
dirk@31
   230
        }
dirk@30
   231
    }
dirk@30
   232
dirk@31
   233
    func controller(controller: NSFetchedResultsController, didChangeObject anObject: AnyObject,
dirk@31
   234
                    atIndexPath indexPath: NSIndexPath?,
dirk@31
   235
                                forChangeType type: NSFetchedResultsChangeType,
dirk@31
   236
                                              newIndexPath: NSIndexPath?) {
dirk@40
   237
        switch type {
dirk@40
   238
        case .Insert:
dirk@40
   239
            tableView.insertRowsAtIndexPaths([newIndexPath!], withRowAnimation: .Fade)
dirk@40
   240
        case .Delete:
dirk@40
   241
            tableView.deleteRowsAtIndexPaths([indexPath!], withRowAnimation: .Fade)
dirk@40
   242
        case .Update:
dirk@40
   243
            if let cell = tableView.cellForRowAtIndexPath(indexPath!) {
dirk@40
   244
                self.configureCell(cell as! EmailListViewCell, indexPath: indexPath!)
dirk@40
   245
            } else {
dirk@414
   246
                Log.warnComponent(comp, "Could not find cell for changed indexPath: \(indexPath!)")
dirk@31
   247
            }
dirk@40
   248
        case .Move:
dirk@40
   249
            if newIndexPath != indexPath {
dirk@40
   250
                tableView.deleteRowsAtIndexPaths([indexPath!], withRowAnimation: .Fade)
dirk@40
   251
                tableView.insertRowsAtIndexPaths([newIndexPath!], withRowAnimation: .Fade)
dirk@40
   252
            }
dirk@31
   253
        }
dirk@31
   254
    }
dirk@31
   255
dirk@31
   256
    func controllerDidChangeContent(controller: NSFetchedResultsController) {
dirk@31
   257
        tableView.endUpdates()
dirk@31
   258
    }
ana@562
   259
ana@562
   260
    override func tableView(tableView: UITableView,
ana@562
   261
                            commitEditingStyle editingStyle: UITableViewCellEditingStyle,
ana@562
   262
                                               forRowAtIndexPath indexPath: NSIndexPath) {
ana@562
   263
        // TODO: Delete from the server and managed errors
ana@562
   264
        if editingStyle == .Delete {
ana@562
   265
            let managedObject = fetchController?.objectAtIndexPath(indexPath) as? Message
ana@562
   266
            fetchController?.managedObjectContext.deleteObject(managedObject!)
ana@562
   267
        }
ana@562
   268
    }
dirk@30
   269
}