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