pEpForiOS/UI/EmailDisplay/EmailListViewController.swift
author Dirk Zimmermann <dirk@pep-project.org>
Wed, 21 Sep 2016 07:56:15 +0200
changeset 748 98b0bcd48ea8
parent 746 99a786a69567
child 784 03ecceb48c71
permissions -rw-r--r--
IOS-198 better delete folder
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@745
    13
class EmailListViewController: FetchTableViewController {
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 segueShowEmail = "segueShowEmail"
dirk@397
    38
    let segueCompose = "segueCompose"
dirk@397
    39
    let segueUserSettings = "segueUserSettings"
dirk@30
    40
dirk@583
    41
    var config: EmailListConfig!
dirk@583
    42
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@594
    57
    var refreshController: UIRefreshControl!
dirk@594
    58
dirk@705
    59
    /**
dirk@705
    60
     The message that should be saved as a draft when compose gets aborted.
dirk@705
    61
     */
dirk@705
    62
    var draftMessageToStore: IMessage?
dirk@705
    63
dirk@719
    64
    /**
dirk@719
    65
     When the user taps on a draft email, this is the message that was selected
dirk@719
    66
     and should be given to the compose view.
dirk@719
    67
     */
dirk@719
    68
    var draftMessageToCompose: IMessage?
dirk@719
    69
dirk@745
    70
    required init?(coder aDecoder: NSCoder) {
dirk@745
    71
        super.init(coder: aDecoder)
dirk@745
    72
        self.comp = "EmailListViewController"
dirk@745
    73
    }
dirk@745
    74
ana@620
    75
    func isReadedMessage(message: IMessage)-> Bool {
dirk@637
    76
        return message.flagSeen.boolValue
ana@614
    77
    }
ana@614
    78
ana@620
    79
    func isImportantMessage(message: IMessage)-> Bool {
ana@621
    80
        return message.flagFlagged.boolValue
ana@614
    81
    }
ana@614
    82
dirk@275
    83
    override func viewDidLoad() {
dirk@594
    84
        refreshController = UIRefreshControl.init()
dirk@593
    85
        refreshController.addTarget(self, action: #selector(self.fetchMailsRefreshControl(_:)),
dirk@275
    86
                                    forControlEvents: UIControlEvents.ValueChanged)
dirk@356
    87
        UIHelper.variableCellHeightsTableView(self.tableView)
dirk@275
    88
    }
dirk@31
    89
dirk@31
    90
    override func viewWillAppear(animated: Bool) {
dirk@594
    91
        // Disable fetching if there is no account
dirk@594
    92
        if config.account != nil {
dirk@594
    93
            self.refreshControl = refreshController
dirk@594
    94
        } else {
dirk@594
    95
            self.refreshControl = nil
dirk@594
    96
        }
dirk@594
    97
dirk@209
    98
        prepareFetchRequest()
dirk@593
    99
        if config.syncOnAppear {
dirk@593
   100
            fetchMailsRefreshControl()
dirk@593
   101
        }
ana@207
   102
        super.viewWillAppear(animated)
ana@207
   103
    }
ana@152
   104
dirk@275
   105
    func fetchMailsRefreshControl(refreshControl: UIRefreshControl? = nil) {
dirk@583
   106
        if let account = config.account {
dirk@55
   107
            let connectInfo = account.connectInfo
dirk@55
   108
dirk@275
   109
            state.isSynching = true
dirk@588
   110
            updateUI()
dirk@368
   111
dirk@588
   112
            config.appConfig.grandOperator.fetchEmailsAndDecryptConnectInfos(
dirk@590
   113
                [connectInfo], folderName: config.folderName,
dirk@466
   114
                completionBlock: { error in
dirk@466
   115
                    Log.infoComponent(self.comp, "Sync completed, error: \(error)")
dirk@707
   116
                    UIHelper.displayError(error, controller: self)
dirk@583
   117
                    self.config.appConfig.model.save()
dirk@466
   118
                    self.state.isSynching = false
dirk@466
   119
                    refreshControl?.endRefreshing()
dirk@466
   120
                    self.updateUI()
dirk@466
   121
            })
dirk@594
   122
        } else {
dirk@594
   123
            state.isSynching = false
dirk@594
   124
            updateUI()
dirk@55
   125
        }
dirk@31
   126
    }
dirk@31
   127
dirk@452
   128
    @IBAction func mailSentSegue(segue: UIStoryboardSegue) {
dirk@452
   129
    }
dirk@452
   130
dirk@705
   131
    @IBAction func backFromComposeWithoutSavingDraftSegue(segue: UIStoryboardSegue) {
dirk@705
   132
    }
dirk@705
   133
dirk@705
   134
    @IBAction func backFromComposeSaveDraftSegue(segue: UIStoryboardSegue) {
dirk@705
   135
        guard let msg = draftMessageToStore else {
dirk@705
   136
            return
dirk@705
   137
        }
dirk@707
   138
dirk@707
   139
        state.isSynching = true
dirk@707
   140
        updateUI()
dirk@707
   141
dirk@706
   142
        config.appConfig.grandOperator.saveDraftMail(
dirk@706
   143
            msg, account: msg.folder.account, completionBlock: { error in
dirk@707
   144
                GCD.onMain() {
dirk@709
   145
                    UIHelper.displayError(error, controller: self)
dirk@707
   146
                    self.state.isSynching = false
dirk@707
   147
                    self.updateUI()
dirk@707
   148
                }
dirk@706
   149
        })
dirk@705
   150
    }
dirk@705
   151
ana@143
   152
    func prepareFetchRequest() {
dirk@31
   153
        let fetchRequest = NSFetchRequest.init(entityName: Message.entityName())
dirk@583
   154
        fetchRequest.predicate = config.predicate
dirk@583
   155
        fetchRequest.sortDescriptors = config.sortDescriptors
dirk@31
   156
        fetchController = NSFetchedResultsController.init(
dirk@31
   157
            fetchRequest: fetchRequest,
dirk@583
   158
            managedObjectContext: config.appConfig.coreDataUtil.managedObjectContext,
dirk@31
   159
            sectionNameKeyPath: nil, cacheName: nil)
dirk@31
   160
        fetchController?.delegate = self
dirk@31
   161
        do {
dirk@31
   162
            try fetchController?.performFetch()
dirk@31
   163
        } catch let err as NSError {
dirk@414
   164
            Log.errorComponent(comp, error: err)
dirk@31
   165
        }
dirk@31
   166
    }
dirk@31
   167
dirk@58
   168
    // MARK: - UI State
dirk@58
   169
dirk@58
   170
    func updateUI() {
dirk@748
   171
        UIApplication.sharedApplication().networkActivityIndicatorVisible = state.isSynching
dirk@748
   172
        if !state.isSynching {
dirk@594
   173
            self.refreshControl?.endRefreshing()
dirk@58
   174
        }
dirk@58
   175
    }
dirk@58
   176
dirk@31
   177
    // MARK: - UITableViewDataSource
dirk@31
   178
dirk@31
   179
    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
dirk@209
   180
        if let count = fetchController?.sections?.count {
dirk@209
   181
            return count
dirk@209
   182
        } else {
dirk@209
   183
            return 0
dirk@209
   184
        }
dirk@31
   185
    }
dirk@31
   186
dirk@31
   187
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
dirk@31
   188
        if fetchController?.sections?.count > 0 {
dirk@31
   189
            if let sections = fetchController?.sections {
dirk@31
   190
                let sectionInfo = sections[section]
dirk@31
   191
                return sectionInfo.numberOfObjects
dirk@31
   192
            }
dirk@31
   193
        }
dirk@31
   194
        return 0
dirk@31
   195
    }
dirk@31
   196
dirk@31
   197
    override func tableView(tableView: UITableView,
dirk@31
   198
                            cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
dirk@209
   199
        let cell = tableView.dequeueReusableCellWithIdentifier(
dirk@209
   200
            "EmailListViewCell", forIndexPath: indexPath) as! EmailListViewCell
dirk@502
   201
        if !determinedCellBackgroundColor {
dirk@502
   202
            defaultCellBackgroundColor = cell.backgroundColor
dirk@502
   203
            determinedCellBackgroundColor = true
dirk@502
   204
        }
dirk@31
   205
        configureCell(cell, indexPath: indexPath)
dirk@31
   206
        return cell
dirk@31
   207
    }
dirk@31
   208
dirk@719
   209
    // MARK: - UITableViewDelegate
dirk@719
   210
dirk@719
   211
    override func tableView(tableView: UITableView,
dirk@719
   212
                            didSelectRowAtIndexPath indexPath: NSIndexPath) {
dirk@719
   213
        draftMessageToCompose = nil
dirk@719
   214
dirk@719
   215
        let cell = tableView.cellForRowAtIndexPath(indexPath)
dirk@719
   216
dirk@719
   217
        if let fn = config.folderName, let ac = config.account,
dirk@719
   218
            let folder = config.appConfig.model.folderByName(fn, email: ac.email) {
dirk@719
   219
            if folder.folderType.integerValue == FolderType.Drafts.rawValue {
dirk@719
   220
                draftMessageToCompose = fetchController?.objectAtIndexPath(indexPath)
dirk@719
   221
                    as? IMessage
dirk@719
   222
                performSegueWithIdentifier(segueCompose, sender: cell)
dirk@719
   223
                return
dirk@719
   224
            }
dirk@719
   225
        }
dirk@719
   226
dirk@719
   227
        performSegueWithIdentifier(segueShowEmail, sender: cell)
dirk@719
   228
    }
dirk@719
   229
dirk@744
   230
    override func tableView(tableView: UITableView, editActionsForRowAtIndexPath
dirk@744
   231
        indexPath: NSIndexPath)-> [UITableViewRowAction]? {
dirk@744
   232
dirk@744
   233
        let cell = tableView.cellForRowAtIndexPath(indexPath) as! EmailListViewCell
dirk@744
   234
        let email = fetchController?.objectAtIndexPath(indexPath) as! Message
dirk@744
   235
dirk@744
   236
        let isFlagAction = createIsFlagAction(email, cell: cell)
dirk@744
   237
        let deleteAction = createDeleteAction(cell)
dirk@744
   238
        let isReadAction = createIsReadAction(email, cell: cell)
dirk@744
   239
        return [deleteAction,isFlagAction,isReadAction]
dirk@744
   240
    }
dirk@744
   241
dirk@719
   242
    // MARK: - Misc
dirk@719
   243
dirk@745
   244
    override func configureCell(theCell: UITableViewCell, indexPath: NSIndexPath) {
dirk@745
   245
        guard let cell = theCell as? EmailListViewCell else {
dirk@745
   246
            return
dirk@745
   247
        }
dirk@31
   248
        if let email = fetchController?.objectAtIndexPath(indexPath) as? Message {
dirk@502
   249
            if let colorRating = PEPUtil.colorRatingFromInt(email.pepColorRating?.integerValue) {
dirk@574
   250
                let privacyColor = PEPUtil.colorFromPepRating(colorRating)
dirk@502
   251
                if let uiColor = UIHelper.textBackgroundUIColorFromPrivacyColor(privacyColor) {
dirk@502
   252
                    cell.backgroundColor = uiColor
dirk@502
   253
                } else {
dirk@502
   254
                    if determinedCellBackgroundColor {
dirk@502
   255
                        cell.backgroundColor = defaultCellBackgroundColor
dirk@502
   256
                    }
dirk@502
   257
                }
dirk@502
   258
            }
dirk@342
   259
            UIHelper.putString(email.from?.displayString(), toLabel: cell.senderLabel)
dirk@342
   260
            UIHelper.putString(email.subject, toLabel: cell.subjectLabel)
dirk@572
   261
dirk@572
   262
            // Snippet
dirk@565
   263
            if let text = email.longMessage {
dirk@572
   264
                let theText = text.replaceNewLinesWith(" ").trimmedWhiteSpace()
dirk@565
   265
                UIHelper.putString(theText, toLabel: cell.summaryLabel)
dirk@572
   266
            } else if let html = email.longMessageFormatted {
dirk@568
   267
                var text = html.extractTextFromHTML()
dirk@572
   268
                text = text.replaceNewLinesWith(" ").trimmedWhiteSpace()
dirk@568
   269
                UIHelper.putString(text, toLabel: cell.summaryLabel)
dirk@568
   270
            } else {
dirk@568
   271
                UIHelper.putString(nil, toLabel: cell.summaryLabel)
dirk@565
   272
            }
dirk@32
   273
dirk@480
   274
            if let receivedDate = email.receivedDate {
dirk@480
   275
                UIHelper.putString(dateFormatter.stringFromDate(receivedDate),
dirk@342
   276
                                   toLabel: cell.dateLabel)
dirk@32
   277
            } else {
dirk@342
   278
                UIHelper.putString(nil, toLabel: cell.dateLabel)
dirk@32
   279
            }
ana@620
   280
ana@656
   281
            if (isImportantMessage(email) && isReadedMessage(email)) {
ana@666
   282
                cell.isImportantImage.hidden = false
ana@666
   283
                cell.isImportantImage.backgroundColor = UIColor.orangeColor()
ana@666
   284
            }
ana@666
   285
            else if (isImportantMessage(email) && !isReadedMessage(email)) {
ana@666
   286
                cell.isImportantImage.hidden = false
ana@656
   287
                cell.isImportantImage.backgroundColor = UIColor.blueColor()
ana@656
   288
                cell.isImportantImage.layer.borderWidth = 2
ana@656
   289
                cell.isImportantImage.layer.borderColor = UIColor.orangeColor().CGColor
ana@666
   290
            } else if (!isImportantMessage(email) && isReadedMessage(email)) {
ana@666
   291
                    cell.isImportantImage.hidden = true
ana@666
   292
            } else if (!isImportantMessage(email) && !isReadedMessage(email)) {
ana@620
   293
                cell.isImportantImage.hidden = false
ana@666
   294
                cell.isImportantImage.backgroundColor = UIColor.blueColor()
ana@620
   295
            }
dirk@31
   296
        }
dirk@30
   297
    }
dirk@30
   298
ana@246
   299
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
dirk@606
   300
        // Make sure the current account is set, if defined
dirk@606
   301
        config.appConfig.currentAccount = config.account
dirk@606
   302
dirk@361
   303
        if segue.identifier == segueCompose {
dirk@397
   304
            let destination = segue.destinationViewController
dirk@434
   305
                as! ComposeViewController
dirk@583
   306
            destination.appConfig = config.appConfig
dirk@719
   307
            if let draft = draftMessageToCompose {
dirk@723
   308
                draft.flagSeen = true
dirk@723
   309
                draft.updateFlags()
dirk@723
   310
                config.appConfig.model.save()
dirk@723
   311
dirk@719
   312
                destination.originalMessage = draft
dirk@719
   313
                destination.composeMode = .ComposeDraft
dirk@719
   314
            }
dirk@273
   315
        } else if segue.identifier == segueShowEmail {
dirk@273
   316
            guard
dirk@273
   317
                let vc = segue.destinationViewController as? EmailViewController,
dirk@273
   318
                let cell = sender as? UITableViewCell,
dirk@273
   319
                let indexPath = self.tableView.indexPathForCell(cell),
dirk@273
   320
                let email = fetchController?.objectAtIndexPath(indexPath) as? Message else {
dirk@273
   321
                    return
dirk@273
   322
            }
dirk@583
   323
            vc.appConfig = config.appConfig
dirk@273
   324
            vc.message = email
ana@246
   325
        }
ana@246
   326
    }
dirk@744
   327
dirk@744
   328
    func syncFlagsToServer(message: IMessage) {
dirk@744
   329
        self.config.appConfig.grandOperator.syncFlagsToServerForFolder(
dirk@744
   330
            message.folder,
dirk@744
   331
            completionBlock: { error in
dirk@744
   332
                UIHelper.displayError(error, controller: self)
dirk@744
   333
        })
dirk@744
   334
    }
dirk@744
   335
dirk@744
   336
    func createIsFlagAction(message: Message, cell: EmailListViewCell) -> UITableViewRowAction {
dirk@744
   337
dirk@744
   338
        // preparing the title action to show when user swipe
dirk@744
   339
        var localizedIsFlagTitle = " "
dirk@744
   340
        if (isImportantMessage(message)) {
dirk@744
   341
            localizedIsFlagTitle = NSLocalizedString("Unflag",
dirk@744
   342
                                                     comment: "Unflag button title in swipe action on EmailListViewController")
dirk@744
   343
        } else {
dirk@744
   344
            localizedIsFlagTitle = NSLocalizedString("Flag",
dirk@744
   345
                                                     comment: "Flag button title in swipe action on EmailListViewController")
dirk@744
   346
        }
dirk@744
   347
dirk@744
   348
        // preparing action to trigger when user swipe
dirk@744
   349
        let isFlagCompletionHandler: (UITableViewRowAction, NSIndexPath) -> Void =
dirk@744
   350
            { (action, indexPath) in
dirk@744
   351
                if (self.isImportantMessage(message)) {
dirk@744
   352
                    message.flagFlagged = false
dirk@744
   353
dirk@744
   354
                } else {
dirk@744
   355
                    message.flagFlagged = true
dirk@744
   356
                }
dirk@744
   357
                message.updateFlags()
dirk@744
   358
                self.syncFlagsToServer(message)
dirk@744
   359
                self.tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: .None)
dirk@744
   360
        }
dirk@744
   361
        // creating the action
dirk@744
   362
        let isFlagAction = UITableViewRowAction(style: .Default, title: localizedIsFlagTitle,
dirk@744
   363
                                                handler: isFlagCompletionHandler)
dirk@744
   364
        // changing default action color
dirk@744
   365
        isFlagAction.backgroundColor = UIColor.orangeColor()
dirk@744
   366
dirk@744
   367
        return isFlagAction
dirk@744
   368
    }
dirk@744
   369
dirk@744
   370
    func createDeleteAction (cell: EmailListViewCell) -> UITableViewRowAction {
dirk@744
   371
dirk@744
   372
        // preparing the title action to show when user swipe
dirk@744
   373
        let localizedDeleteTitle = NSLocalizedString("Erase",
dirk@744
   374
                                                     comment: "Erase button title in swipe action on EmailListViewController")
dirk@744
   375
dirk@744
   376
        let deleteCompletionHandler: (UITableViewRowAction, NSIndexPath) -> Void =
dirk@744
   377
            { (action, indexPath) in
dirk@744
   378
                let managedObject = self.fetchController?.objectAtIndexPath(indexPath) as? IMessage
dirk@744
   379
                managedObject?.flagDeleted = true
dirk@744
   380
                managedObject?.updateFlags()
dirk@744
   381
                self.syncFlagsToServer(managedObject!)
dirk@744
   382
        }
dirk@744
   383
dirk@744
   384
        // creating the action
dirk@744
   385
        let deleteAction = UITableViewRowAction(style: .Default, title: localizedDeleteTitle,
dirk@744
   386
                                                handler: deleteCompletionHandler)
dirk@744
   387
        return deleteAction
dirk@744
   388
    }
dirk@744
   389
dirk@744
   390
    func createIsReadAction (message: Message, cell: EmailListViewCell) -> UITableViewRowAction {
dirk@744
   391
dirk@744
   392
        // preparing the title action to show when user swipe
dirk@744
   393
        var localizedisReadTitle = " "
dirk@744
   394
        if (isReadedMessage(message)) {
dirk@744
   395
            localizedisReadTitle = NSLocalizedString("Unread",
dirk@744
   396
                                                     comment: "Unread button title in swipe action on EmailListViewController")
dirk@744
   397
        } else {
dirk@744
   398
            localizedisReadTitle = NSLocalizedString("Read",
dirk@744
   399
                                                     comment: "Read button title in swipe action on EmailListViewController")
dirk@744
   400
        }
dirk@744
   401
dirk@744
   402
        // creating the action
dirk@744
   403
        let isReadCompletionHandler: (UITableViewRowAction, NSIndexPath) -> Void =
dirk@744
   404
            { (action, indexPath) in
dirk@744
   405
                if (self.isReadedMessage(message)) {
dirk@744
   406
                    message.flagSeen = false
dirk@744
   407
                    message.updateFlags()
dirk@744
   408
                } else {
dirk@744
   409
                    message.flagSeen = true
dirk@744
   410
                    message.updateFlags()
dirk@744
   411
                }
dirk@744
   412
                self.syncFlagsToServer(message)
dirk@744
   413
                self.tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: .None)
dirk@744
   414
        }
dirk@744
   415
        let isReadAction = UITableViewRowAction(style: .Default, title: localizedisReadTitle,
dirk@744
   416
                                                handler: isReadCompletionHandler)
dirk@744
   417
        isReadAction.backgroundColor = UIColor.blueColor()
dirk@744
   418
dirk@744
   419
        return isReadAction
dirk@744
   420
    }
dirk@30
   421
}