pEpForiOS/UI/EmailDisplay/EmailListViewController.swift
author Dirk Zimmermann <dirk@pep-project.org>
Tue, 25 Oct 2016 09:47:36 +0200
branchIOS-230
changeset 867 89ccccb16970
parent 861 53c7f9ec0dec
child 870 dd67c28b7449
permissions -rw-r--r--
IOS-234 Skeleton for saving drafts (to be fleshed out)
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@854
    36
class EmailListViewController: UITableViewController {
dirk@591
    37
    struct EmailListConfig {
dirk@591
    38
        let appConfig: AppConfig
dirk@583
    39
dirk@855
    40
        let account: Account?
dirk@855
    41
dirk@854
    42
        /** The folder to display, if it exists */
dirk@854
    43
        let folder: Folder?
dirk@854
    44
    }
dirk@583
    45
dirk@854
    46
    var comp = "EmailListViewController"
dirk@58
    47
dirk@583
    48
    struct UIState {
dirk@583
    49
        var isSynching: Bool = false
dirk@583
    50
    }
dirk@583
    51
    
dirk@273
    52
    let segueShowEmail = "segueShowEmail"
dirk@397
    53
    let segueCompose = "segueCompose"
dirk@397
    54
    let segueUserSettings = "segueUserSettings"
dirk@30
    55
dirk@583
    56
    var config: EmailListConfig!
dirk@583
    57
dirk@275
    58
    var state = UIState()
dirk@342
    59
    let dateFormatter = UIHelper.dateFormatterEmailList()
dirk@275
    60
dirk@502
    61
    /**
dirk@502
    62
     The default background color for an email cell, as determined the first time a cell is
dirk@502
    63
     created.
dirk@502
    64
     */
dirk@502
    65
    var defaultCellBackgroundColor: UIColor?
dirk@502
    66
dirk@502
    67
    /**
dirk@502
    68
     Indicates whether `defaultCellBackgroundColor` has been determined or not.
dirk@502
    69
     */
dirk@502
    70
    var determinedCellBackgroundColor: Bool = false
dirk@502
    71
dirk@594
    72
    var refreshController: UIRefreshControl!
dirk@594
    73
dirk@705
    74
    /**
dirk@705
    75
     The message that should be saved as a draft when compose gets aborted.
dirk@705
    76
     */
dirk@841
    77
    var draftMessageToStore: Message?
dirk@705
    78
dirk@719
    79
    /**
dirk@719
    80
     When the user taps on a draft email, this is the message that was selected
dirk@719
    81
     and should be given to the compose view.
dirk@719
    82
     */
dirk@841
    83
    var draftMessageToCompose: Message?
dirk@719
    84
dirk@745
    85
    required init?(coder aDecoder: NSCoder) {
dirk@745
    86
        super.init(coder: aDecoder)
dirk@745
    87
        self.comp = "EmailListViewController"
dirk@745
    88
    }
dirk@745
    89
dirk@855
    90
    func isRead(message: Message)-> Bool {
dirk@855
    91
        return message.imapFlags.seen
ana@614
    92
    }
ana@614
    93
dirk@855
    94
    func isImportant(message: Message)-> Bool {
dirk@855
    95
        return message.imapFlags.flagged
ana@614
    96
    }
ana@614
    97
dirk@275
    98
    override func viewDidLoad() {
dirk@356
    99
        UIHelper.variableCellHeightsTableView(self.tableView)
dirk@275
   100
    }
dirk@31
   101
dirk@784
   102
    override func viewWillAppear(_ animated: Bool) {
dirk@854
   103
        updateModel()
ana@207
   104
        super.viewWillAppear(animated)
ana@207
   105
    }
ana@152
   106
dirk@784
   107
    @IBAction func mailSentSegue(_ segue: UIStoryboardSegue) {
dirk@452
   108
    }
dirk@452
   109
dirk@784
   110
    @IBAction func backFromComposeWithoutSavingDraftSegue(_ segue: UIStoryboardSegue) {
dirk@705
   111
    }
dirk@705
   112
dirk@784
   113
    @IBAction func backFromComposeSaveDraftSegue(_ segue: UIStoryboardSegue) {
dirk@867
   114
        guard let message = draftMessageToStore else {
dirk@705
   115
            return
dirk@705
   116
        }
dirk@707
   117
dirk@707
   118
        state.isSynching = true
dirk@707
   119
        updateUI()
dirk@707
   120
dirk@867
   121
        message.imapFlags.draft = true
dirk@867
   122
dirk@854
   123
        // TODO: IOS 222: Save as draft
dirk@867
   124
        if let folder = draftMessageToStore?.parent as? Folder {
dirk@867
   125
            if folder.folderType == .drafts {
dirk@867
   126
                message.save()
dirk@867
   127
                return
dirk@867
   128
            }
dirk@867
   129
        }
dirk@867
   130
dirk@867
   131
        guard let account = config.account else {
dirk@867
   132
            return
dirk@867
   133
        }
dirk@705
   134
    }
dirk@705
   135
dirk@854
   136
    func updateModel() {
dirk@31
   137
    }
dirk@31
   138
dirk@58
   139
    // MARK: - UI State
dirk@58
   140
dirk@58
   141
    func updateUI() {
dirk@784
   142
        UIApplication.shared.isNetworkActivityIndicatorVisible = state.isSynching
dirk@748
   143
        if !state.isSynching {
dirk@594
   144
            self.refreshControl?.endRefreshing()
dirk@58
   145
        }
dirk@58
   146
    }
dirk@58
   147
dirk@31
   148
    // MARK: - UITableViewDataSource
dirk@31
   149
dirk@784
   150
    override func numberOfSections(in tableView: UITableView) -> Int {
dirk@854
   151
        if let _ = config.folder {
dirk@854
   152
            return 1
dirk@209
   153
        }
dirk@854
   154
        return 0
dirk@31
   155
    }
dirk@31
   156
dirk@784
   157
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
dirk@854
   158
        if let fol = config.folder {
dirk@854
   159
            return fol.messageCount()
dirk@31
   160
        }
dirk@31
   161
        return 0
dirk@31
   162
    }
dirk@31
   163
dirk@784
   164
    override func tableView(_ tableView: UITableView,
dirk@784
   165
                            cellForRowAt indexPath: IndexPath) -> UITableViewCell {
dirk@784
   166
        let cell = tableView.dequeueReusableCell(
dirk@784
   167
            withIdentifier: "EmailListViewCell", for: indexPath) as! EmailListViewCell
dirk@502
   168
        if !determinedCellBackgroundColor {
dirk@502
   169
            defaultCellBackgroundColor = cell.backgroundColor
dirk@502
   170
            determinedCellBackgroundColor = true
dirk@502
   171
        }
dirk@31
   172
        configureCell(cell, indexPath: indexPath)
dirk@31
   173
        return cell
dirk@31
   174
    }
dirk@31
   175
dirk@861
   176
    /**
dirk@861
   177
     The message at the given position.
dirk@861
   178
     */
dirk@861
   179
    func messageAt(indexPath: IndexPath) -> Message? {
dirk@861
   180
        if let fol = config.folder {
dirk@861
   181
            return fol.messageByIndex(indexPath.row)
dirk@861
   182
        }
dirk@861
   183
        return nil
dirk@861
   184
    }
dirk@861
   185
dirk@719
   186
    // MARK: - UITableViewDelegate
dirk@719
   187
dirk@784
   188
    override func tableView(_ tableView: UITableView,
dirk@784
   189
                            didSelectRowAt indexPath: IndexPath) {
dirk@719
   190
        draftMessageToCompose = nil
dirk@719
   191
dirk@784
   192
        let cell = tableView.cellForRow(at: indexPath)
dirk@719
   193
dirk@855
   194
        if let fol = config.folder {
dirk@855
   195
            if fol.folderType == .drafts {
dirk@855
   196
                draftMessageToCompose = messageAt(indexPath: indexPath)
dirk@784
   197
                performSegue(withIdentifier: segueCompose, sender: cell)
dirk@719
   198
                return
dirk@719
   199
            }
dirk@719
   200
        }
dirk@719
   201
dirk@784
   202
        performSegue(withIdentifier: segueShowEmail, sender: cell)
dirk@719
   203
    }
dirk@719
   204
dirk@784
   205
    override func tableView(_ tableView: UITableView, editActionsForRowAt
dirk@784
   206
        indexPath: IndexPath)-> [UITableViewRowAction]? {
dirk@784
   207
        let cell = tableView.cellForRow(at: indexPath) as! EmailListViewCell
dirk@855
   208
        if let email = messageAt(indexPath: indexPath) {
dirk@855
   209
            let isFlagAction = createIsFlagAction(message: email, cell: cell)
dirk@855
   210
            let deleteAction = createDeleteAction(cell)
dirk@855
   211
            let isReadAction = createIsReadAction(message: email, cell: cell)
dirk@855
   212
            return [deleteAction,isFlagAction,isReadAction]
dirk@855
   213
        }
dirk@855
   214
        return nil
dirk@744
   215
    }
dirk@744
   216
dirk@719
   217
    // MARK: - Misc
dirk@719
   218
dirk@855
   219
    func configureCell(_ theCell: UITableViewCell, indexPath: IndexPath) {
dirk@745
   220
        guard let cell = theCell as? EmailListViewCell else {
dirk@745
   221
            return
dirk@745
   222
        }
dirk@855
   223
        if let email = messageAt(indexPath: indexPath) {
dirk@855
   224
            if let pEpRating = email.pEpRating {
dirk@855
   225
                let privacyColor = PEPUtil.pEpColorFromRating(pEpRating)
dirk@502
   226
                if let uiColor = UIHelper.textBackgroundUIColorFromPrivacyColor(privacyColor) {
dirk@502
   227
                    cell.backgroundColor = uiColor
dirk@502
   228
                } else {
dirk@502
   229
                    if determinedCellBackgroundColor {
dirk@502
   230
                        cell.backgroundColor = defaultCellBackgroundColor
dirk@502
   231
                    }
dirk@502
   232
                }
dirk@502
   233
            }
dirk@855
   234
            UIHelper.putString(email.from?.displayString, toLabel: cell.senderLabel)
dirk@855
   235
            UIHelper.putString(email.shortMessage, toLabel: cell.subjectLabel)
dirk@572
   236
dirk@572
   237
            // Snippet
dirk@565
   238
            if let text = email.longMessage {
dirk@572
   239
                let theText = text.replaceNewLinesWith(" ").trimmedWhiteSpace()
dirk@565
   240
                UIHelper.putString(theText, toLabel: cell.summaryLabel)
dirk@572
   241
            } else if let html = email.longMessageFormatted {
dirk@568
   242
                var text = html.extractTextFromHTML()
dirk@572
   243
                text = text.replaceNewLinesWith(" ").trimmedWhiteSpace()
dirk@568
   244
                UIHelper.putString(text, toLabel: cell.summaryLabel)
dirk@568
   245
            } else {
dirk@568
   246
                UIHelper.putString(nil, toLabel: cell.summaryLabel)
dirk@565
   247
            }
dirk@32
   248
dirk@855
   249
            if let receivedDate = email.received {
dirk@788
   250
                UIHelper.putString(dateFormatter.string(from: receivedDate as Date),
dirk@342
   251
                                   toLabel: cell.dateLabel)
dirk@32
   252
            } else {
dirk@342
   253
                UIHelper.putString(nil, toLabel: cell.dateLabel)
dirk@32
   254
            }
ana@620
   255
dirk@855
   256
            if (isImportant(message: email) && isRead(message: email)) {
dirk@784
   257
                cell.isImportantImage.isHidden = false
dirk@784
   258
                cell.isImportantImage.backgroundColor = UIColor.orange
ana@666
   259
            }
dirk@855
   260
            else if (isImportant(message: email) && !isRead(message: email)) {
dirk@784
   261
                cell.isImportantImage.isHidden = false
dirk@784
   262
                cell.isImportantImage.backgroundColor = UIColor.blue
ana@656
   263
                cell.isImportantImage.layer.borderWidth = 2
dirk@784
   264
                cell.isImportantImage.layer.borderColor = UIColor.orange.cgColor
dirk@855
   265
            } else if (!isImportant(message: email) && isRead(message: email)) {
dirk@784
   266
                    cell.isImportantImage.isHidden = true
dirk@855
   267
            } else if (!isImportant(message: email) && !isRead(message: email)) {
dirk@784
   268
                cell.isImportantImage.isHidden = false
dirk@784
   269
                cell.isImportantImage.backgroundColor = UIColor.blue
ana@620
   270
            }
dirk@31
   271
        }
dirk@30
   272
    }
dirk@30
   273
dirk@784
   274
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
dirk@606
   275
        // Make sure the current account is set, if defined
dirk@606
   276
        config.appConfig.currentAccount = config.account
dirk@606
   277
dirk@361
   278
        if segue.identifier == segueCompose {
dirk@784
   279
            let destination = segue.destination
dirk@434
   280
                as! ComposeViewController
dirk@583
   281
            destination.appConfig = config.appConfig
dirk@719
   282
            if let draft = draftMessageToCompose {
dirk@855
   283
                draft.imapFlags.seen = true
dirk@723
   284
                config.appConfig.model.save()
dirk@723
   285
dirk@719
   286
                destination.originalMessage = draft
dirk@784
   287
                destination.composeMode = .composeDraft
dirk@719
   288
            }
dirk@273
   289
        } else if segue.identifier == segueShowEmail {
dirk@273
   290
            guard
dirk@784
   291
                let vc = segue.destination as? EmailViewController,
dirk@273
   292
                let cell = sender as? UITableViewCell,
dirk@784
   293
                let indexPath = self.tableView.indexPath(for: cell),
dirk@855
   294
                let email = messageAt(indexPath: indexPath) else {
dirk@273
   295
                    return
dirk@273
   296
            }
dirk@583
   297
            vc.appConfig = config.appConfig
dirk@273
   298
            vc.message = email
ana@246
   299
        }
ana@246
   300
    }
dirk@744
   301
dirk@855
   302
    func syncFlagsToServer(message: Message) {
dirk@855
   303
        // TODO: IOS 222: Sync flags back to server
dirk@744
   304
    }
dirk@744
   305
dirk@855
   306
    func createIsFlagAction(message: Message, cell: EmailListViewCell) -> UITableViewRowAction {
dirk@744
   307
        // preparing the title action to show when user swipe
dirk@744
   308
        var localizedIsFlagTitle = " "
dirk@855
   309
        if (isImportant(message: message)) {
dirk@855
   310
            localizedIsFlagTitle = NSLocalizedString(
dirk@855
   311
                "Unflag",
dirk@855
   312
                comment: "Unflag button title in swipe action on EmailListViewController")
dirk@744
   313
        } else {
dirk@855
   314
            localizedIsFlagTitle = NSLocalizedString(
dirk@855
   315
                "Flag",
dirk@855
   316
                comment: "Flag button title in swipe action on EmailListViewController")
dirk@744
   317
        }
dirk@744
   318
dirk@744
   319
        // preparing action to trigger when user swipe
dirk@784
   320
        let isFlagCompletionHandler: (UITableViewRowAction, IndexPath) -> Void =
dirk@744
   321
            { (action, indexPath) in
dirk@855
   322
                if (self.isImportant(message: message)) {
dirk@855
   323
                    message.imapFlags.flagged = false
dirk@744
   324
dirk@744
   325
                } else {
dirk@855
   326
                    message.imapFlags.flagged = true
dirk@744
   327
                }
dirk@855
   328
                self.syncFlagsToServer(message: message)
dirk@784
   329
                self.tableView.reloadRows(at: [indexPath], with: .none)
dirk@744
   330
        }
dirk@744
   331
        // creating the action
dirk@784
   332
        let isFlagAction = UITableViewRowAction(style: .default, title: localizedIsFlagTitle,
dirk@744
   333
                                                handler: isFlagCompletionHandler)
dirk@744
   334
        // changing default action color
dirk@784
   335
        isFlagAction.backgroundColor = UIColor.orange
dirk@744
   336
dirk@744
   337
        return isFlagAction
dirk@744
   338
    }
dirk@744
   339
dirk@784
   340
    func createDeleteAction (_ cell: EmailListViewCell) -> UITableViewRowAction {
dirk@744
   341
dirk@744
   342
        // preparing the title action to show when user swipe
dirk@855
   343
        let localizedDeleteTitle = NSLocalizedString(
dirk@855
   344
            "Erase",
dirk@855
   345
            comment: "Erase button title in swipe action on EmailListViewController")
dirk@744
   346
dirk@784
   347
        let deleteCompletionHandler: (UITableViewRowAction, IndexPath) -> Void =
dirk@744
   348
            { (action, indexPath) in
dirk@855
   349
                let message = self.messageAt(indexPath: indexPath)
dirk@855
   350
                message?.imapFlags.deleted = true
dirk@855
   351
                self.syncFlagsToServer(message: message!)
dirk@744
   352
        }
dirk@744
   353
dirk@744
   354
        // creating the action
dirk@784
   355
        let deleteAction = UITableViewRowAction(style: .default, title: localizedDeleteTitle,
dirk@744
   356
                                                handler: deleteCompletionHandler)
dirk@744
   357
        return deleteAction
dirk@744
   358
    }
dirk@744
   359
dirk@855
   360
    func createIsReadAction(message: Message, cell: EmailListViewCell) -> UITableViewRowAction {
dirk@744
   361
        // preparing the title action to show when user swipe
dirk@744
   362
        var localizedisReadTitle = " "
dirk@855
   363
        if (isRead(message: message)) {
dirk@855
   364
            localizedisReadTitle = NSLocalizedString(
dirk@855
   365
                "Unread",
dirk@855
   366
                comment: "Unread button title in swipe action on EmailListViewController")
dirk@744
   367
        } else {
dirk@855
   368
            localizedisReadTitle = NSLocalizedString(
dirk@855
   369
                "Read",
dirk@855
   370
                comment: "Read button title in swipe action on EmailListViewController")
dirk@744
   371
        }
dirk@744
   372
dirk@744
   373
        // creating the action
dirk@784
   374
        let isReadCompletionHandler: (UITableViewRowAction, IndexPath) -> Void =
dirk@744
   375
            { (action, indexPath) in
dirk@855
   376
                if (self.isRead(message: message)) {
dirk@855
   377
                    message.imapFlags.seen = false
dirk@744
   378
                } else {
dirk@855
   379
                    message.imapFlags.seen = true
dirk@744
   380
                }
dirk@855
   381
                self.syncFlagsToServer(message: message)
dirk@784
   382
                self.tableView.reloadRows(at: [indexPath], with: .none)
dirk@744
   383
        }
dirk@784
   384
        let isReadAction = UITableViewRowAction(style: .default, title: localizedisReadTitle,
dirk@744
   385
                                                handler: isReadCompletionHandler)
dirk@784
   386
        isReadAction.backgroundColor = UIColor.blue
dirk@744
   387
dirk@744
   388
        return isReadAction
dirk@744
   389
    }
dirk@784
   390
}