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