pEpForiOS/UI/EmailDisplay/EmailListViewController.swift
author Yves Landert <ylandert@gmail.com>
Tue, 01 Nov 2016 10:53:34 +0100
changeset 935 16f7ad421c63
parent 870 dd67c28b7449
child 941 b53436ddb8c2
permissions -rw-r--r--
added icon for read/unread and mocking for messages
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 */
ylandert@935
    43
        var 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() {
ylandert@935
    99
        super.viewDidLoad()
dirk@356
   100
        UIHelper.variableCellHeightsTableView(self.tableView)
dirk@275
   101
    }
dirk@31
   102
dirk@784
   103
    override func viewWillAppear(_ animated: Bool) {
dirk@854
   104
        updateModel()
ana@207
   105
        super.viewWillAppear(animated)
ana@207
   106
    }
ana@152
   107
dirk@784
   108
    @IBAction func mailSentSegue(_ segue: UIStoryboardSegue) {
dirk@452
   109
    }
dirk@452
   110
dirk@784
   111
    @IBAction func backFromComposeWithoutSavingDraftSegue(_ segue: UIStoryboardSegue) {
dirk@705
   112
    }
dirk@705
   113
dirk@784
   114
    @IBAction func backFromComposeSaveDraftSegue(_ segue: UIStoryboardSegue) {
dirk@867
   115
        guard let message = draftMessageToStore else {
dirk@705
   116
            return
dirk@705
   117
        }
dirk@707
   118
dirk@707
   119
        state.isSynching = true
dirk@707
   120
        updateUI()
dirk@707
   121
dirk@867
   122
        message.imapFlags.draft = true
dirk@867
   123
dirk@854
   124
        // TODO: IOS 222: Save as draft
dirk@867
   125
        if let folder = draftMessageToStore?.parent as? Folder {
dirk@867
   126
            if folder.folderType == .drafts {
dirk@867
   127
                message.save()
dirk@867
   128
                return
dirk@867
   129
            }
dirk@867
   130
        }
dirk@867
   131
dirk@867
   132
        guard let account = config.account else {
dirk@867
   133
            return
dirk@867
   134
        }
xavier@870
   135
        
xavier@870
   136
        if let folder = account.folder(ofType: FolderType.drafts) {
xavier@870
   137
            folder.save(message: message)
xavier@870
   138
            return
xavier@870
   139
        }
dirk@705
   140
    }
dirk@705
   141
dirk@854
   142
    func updateModel() {
ylandert@935
   143
        config.folder = MockData.createFolder(config.account!)
dirk@31
   144
    }
dirk@31
   145
dirk@58
   146
    // MARK: - UI State
dirk@58
   147
dirk@58
   148
    func updateUI() {
dirk@784
   149
        UIApplication.shared.isNetworkActivityIndicatorVisible = state.isSynching
dirk@748
   150
        if !state.isSynching {
dirk@594
   151
            self.refreshControl?.endRefreshing()
dirk@58
   152
        }
dirk@58
   153
    }
dirk@58
   154
dirk@31
   155
    // MARK: - UITableViewDataSource
dirk@31
   156
dirk@784
   157
    override func numberOfSections(in tableView: UITableView) -> Int {
dirk@854
   158
        if let _ = config.folder {
dirk@854
   159
            return 1
dirk@209
   160
        }
dirk@854
   161
        return 0
dirk@31
   162
    }
dirk@31
   163
dirk@784
   164
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
dirk@854
   165
        if let fol = config.folder {
dirk@854
   166
            return fol.messageCount()
dirk@31
   167
        }
dirk@31
   168
        return 0
dirk@31
   169
    }
dirk@31
   170
dirk@784
   171
    override func tableView(_ tableView: UITableView,
dirk@784
   172
                            cellForRowAt indexPath: IndexPath) -> UITableViewCell {
dirk@784
   173
        let cell = tableView.dequeueReusableCell(
dirk@784
   174
            withIdentifier: "EmailListViewCell", for: indexPath) as! EmailListViewCell
dirk@502
   175
        if !determinedCellBackgroundColor {
dirk@502
   176
            defaultCellBackgroundColor = cell.backgroundColor
dirk@502
   177
            determinedCellBackgroundColor = true
dirk@502
   178
        }
dirk@31
   179
        configureCell(cell, indexPath: indexPath)
dirk@31
   180
        return cell
dirk@31
   181
    }
dirk@31
   182
dirk@861
   183
    /**
dirk@861
   184
     The message at the given position.
dirk@861
   185
     */
dirk@861
   186
    func messageAt(indexPath: IndexPath) -> Message? {
dirk@861
   187
        if let fol = config.folder {
dirk@861
   188
            return fol.messageByIndex(indexPath.row)
dirk@861
   189
        }
dirk@861
   190
        return nil
dirk@861
   191
    }
dirk@861
   192
dirk@719
   193
    // MARK: - UITableViewDelegate
dirk@719
   194
dirk@784
   195
    override func tableView(_ tableView: UITableView,
dirk@784
   196
                            didSelectRowAt indexPath: IndexPath) {
dirk@719
   197
        draftMessageToCompose = nil
dirk@719
   198
dirk@784
   199
        let cell = tableView.cellForRow(at: indexPath)
dirk@719
   200
dirk@855
   201
        if let fol = config.folder {
dirk@855
   202
            if fol.folderType == .drafts {
dirk@855
   203
                draftMessageToCompose = messageAt(indexPath: indexPath)
dirk@784
   204
                performSegue(withIdentifier: segueCompose, sender: cell)
dirk@719
   205
                return
dirk@719
   206
            }
dirk@719
   207
        }
dirk@719
   208
dirk@784
   209
        performSegue(withIdentifier: segueShowEmail, sender: cell)
dirk@719
   210
    }
dirk@719
   211
dirk@784
   212
    override func tableView(_ tableView: UITableView, editActionsForRowAt
dirk@784
   213
        indexPath: IndexPath)-> [UITableViewRowAction]? {
dirk@784
   214
        let cell = tableView.cellForRow(at: indexPath) as! EmailListViewCell
dirk@855
   215
        if let email = messageAt(indexPath: indexPath) {
dirk@855
   216
            let isFlagAction = createIsFlagAction(message: email, cell: cell)
dirk@855
   217
            let deleteAction = createDeleteAction(cell)
dirk@855
   218
            let isReadAction = createIsReadAction(message: email, cell: cell)
dirk@855
   219
            return [deleteAction,isFlagAction,isReadAction]
dirk@855
   220
        }
dirk@855
   221
        return nil
dirk@744
   222
    }
dirk@744
   223
dirk@719
   224
    // MARK: - Misc
dirk@719
   225
dirk@855
   226
    func configureCell(_ theCell: UITableViewCell, indexPath: IndexPath) {
dirk@745
   227
        guard let cell = theCell as? EmailListViewCell else {
dirk@745
   228
            return
dirk@745
   229
        }
dirk@855
   230
        if let email = messageAt(indexPath: indexPath) {
dirk@855
   231
            if let pEpRating = email.pEpRating {
dirk@855
   232
                let privacyColor = PEPUtil.pEpColorFromRating(pEpRating)
dirk@502
   233
                if let uiColor = UIHelper.textBackgroundUIColorFromPrivacyColor(privacyColor) {
dirk@502
   234
                    cell.backgroundColor = uiColor
dirk@502
   235
                } else {
dirk@502
   236
                    if determinedCellBackgroundColor {
dirk@502
   237
                        cell.backgroundColor = defaultCellBackgroundColor
dirk@502
   238
                    }
dirk@502
   239
                }
dirk@502
   240
            }
dirk@855
   241
            UIHelper.putString(email.from?.displayString, toLabel: cell.senderLabel)
dirk@855
   242
            UIHelper.putString(email.shortMessage, toLabel: cell.subjectLabel)
dirk@572
   243
dirk@572
   244
            // Snippet
dirk@565
   245
            if let text = email.longMessage {
dirk@572
   246
                let theText = text.replaceNewLinesWith(" ").trimmedWhiteSpace()
ylandert@935
   247
                UIHelper.putString(UIHelper.cleanHtml(theText), toLabel: cell.summaryLabel)
dirk@572
   248
            } else if let html = email.longMessageFormatted {
dirk@568
   249
                var text = html.extractTextFromHTML()
dirk@572
   250
                text = text.replaceNewLinesWith(" ").trimmedWhiteSpace()
dirk@568
   251
                UIHelper.putString(text, toLabel: cell.summaryLabel)
dirk@568
   252
            } else {
dirk@568
   253
                UIHelper.putString(nil, toLabel: cell.summaryLabel)
dirk@565
   254
            }
dirk@32
   255
dirk@855
   256
            if let receivedDate = email.received {
dirk@788
   257
                UIHelper.putString(dateFormatter.string(from: receivedDate as Date),
dirk@342
   258
                                   toLabel: cell.dateLabel)
dirk@32
   259
            } else {
dirk@342
   260
                UIHelper.putString(nil, toLabel: cell.dateLabel)
dirk@32
   261
            }
ana@620
   262
dirk@855
   263
            if (isImportant(message: email) && isRead(message: email)) {
dirk@784
   264
                cell.isImportantImage.isHidden = false
dirk@784
   265
                cell.isImportantImage.backgroundColor = UIColor.orange
ana@666
   266
            }
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@656
   270
                cell.isImportantImage.layer.borderWidth = 2
dirk@784
   271
                cell.isImportantImage.layer.borderColor = UIColor.orange.cgColor
dirk@855
   272
            } else if (!isImportant(message: email) && isRead(message: email)) {
dirk@784
   273
                    cell.isImportantImage.isHidden = true
dirk@855
   274
            } else if (!isImportant(message: email) && !isRead(message: email)) {
dirk@784
   275
                cell.isImportantImage.isHidden = false
dirk@784
   276
                cell.isImportantImage.backgroundColor = UIColor.blue
ana@620
   277
            }
dirk@31
   278
        }
dirk@30
   279
    }
dirk@30
   280
dirk@784
   281
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
dirk@606
   282
        // Make sure the current account is set, if defined
dirk@606
   283
        config.appConfig.currentAccount = config.account
dirk@606
   284
dirk@361
   285
        if segue.identifier == segueCompose {
dirk@784
   286
            let destination = segue.destination
dirk@434
   287
                as! ComposeViewController
dirk@583
   288
            destination.appConfig = config.appConfig
dirk@719
   289
            if let draft = draftMessageToCompose {
dirk@855
   290
                draft.imapFlags.seen = true
dirk@723
   291
                config.appConfig.model.save()
dirk@723
   292
dirk@719
   293
                destination.originalMessage = draft
dirk@784
   294
                destination.composeMode = .composeDraft
dirk@719
   295
            }
dirk@273
   296
        } else if segue.identifier == segueShowEmail {
dirk@273
   297
            guard
dirk@784
   298
                let vc = segue.destination as? EmailViewController,
dirk@273
   299
                let cell = sender as? UITableViewCell,
dirk@784
   300
                let indexPath = self.tableView.indexPath(for: cell),
dirk@855
   301
                let email = messageAt(indexPath: indexPath) else {
dirk@273
   302
                    return
dirk@273
   303
            }
dirk@583
   304
            vc.appConfig = config.appConfig
dirk@273
   305
            vc.message = email
ana@246
   306
        }
ana@246
   307
    }
dirk@744
   308
dirk@855
   309
    func syncFlagsToServer(message: Message) {
dirk@855
   310
        // TODO: IOS 222: Sync flags back to server
dirk@744
   311
    }
dirk@744
   312
dirk@855
   313
    func createIsFlagAction(message: Message, cell: EmailListViewCell) -> UITableViewRowAction {
dirk@744
   314
        // preparing the title action to show when user swipe
dirk@744
   315
        var localizedIsFlagTitle = " "
dirk@855
   316
        if (isImportant(message: message)) {
dirk@855
   317
            localizedIsFlagTitle = NSLocalizedString(
dirk@855
   318
                "Unflag",
dirk@855
   319
                comment: "Unflag button title in swipe action on EmailListViewController")
dirk@744
   320
        } else {
dirk@855
   321
            localizedIsFlagTitle = NSLocalizedString(
dirk@855
   322
                "Flag",
dirk@855
   323
                comment: "Flag button title in swipe action on EmailListViewController")
dirk@744
   324
        }
dirk@744
   325
dirk@744
   326
        // preparing action to trigger when user swipe
dirk@784
   327
        let isFlagCompletionHandler: (UITableViewRowAction, IndexPath) -> Void =
dirk@744
   328
            { (action, indexPath) in
dirk@855
   329
                if (self.isImportant(message: message)) {
dirk@855
   330
                    message.imapFlags.flagged = false
dirk@744
   331
dirk@744
   332
                } else {
dirk@855
   333
                    message.imapFlags.flagged = true
dirk@744
   334
                }
dirk@855
   335
                self.syncFlagsToServer(message: message)
dirk@784
   336
                self.tableView.reloadRows(at: [indexPath], with: .none)
dirk@744
   337
        }
dirk@744
   338
        // creating the action
dirk@784
   339
        let isFlagAction = UITableViewRowAction(style: .default, title: localizedIsFlagTitle,
dirk@744
   340
                                                handler: isFlagCompletionHandler)
dirk@744
   341
        // changing default action color
dirk@784
   342
        isFlagAction.backgroundColor = UIColor.orange
dirk@744
   343
dirk@744
   344
        return isFlagAction
dirk@744
   345
    }
dirk@744
   346
dirk@784
   347
    func createDeleteAction (_ cell: EmailListViewCell) -> UITableViewRowAction {
dirk@744
   348
dirk@744
   349
        // preparing the title action to show when user swipe
dirk@855
   350
        let localizedDeleteTitle = NSLocalizedString(
dirk@855
   351
            "Erase",
dirk@855
   352
            comment: "Erase button title in swipe action on EmailListViewController")
dirk@744
   353
dirk@784
   354
        let deleteCompletionHandler: (UITableViewRowAction, IndexPath) -> Void =
dirk@744
   355
            { (action, indexPath) in
dirk@855
   356
                let message = self.messageAt(indexPath: indexPath)
dirk@855
   357
                message?.imapFlags.deleted = true
dirk@855
   358
                self.syncFlagsToServer(message: message!)
dirk@744
   359
        }
dirk@744
   360
dirk@744
   361
        // creating the action
dirk@784
   362
        let deleteAction = UITableViewRowAction(style: .default, title: localizedDeleteTitle,
dirk@744
   363
                                                handler: deleteCompletionHandler)
dirk@744
   364
        return deleteAction
dirk@744
   365
    }
dirk@744
   366
dirk@855
   367
    func createIsReadAction(message: Message, cell: EmailListViewCell) -> UITableViewRowAction {
dirk@744
   368
        // preparing the title action to show when user swipe
dirk@744
   369
        var localizedisReadTitle = " "
dirk@855
   370
        if (isRead(message: message)) {
dirk@855
   371
            localizedisReadTitle = NSLocalizedString(
dirk@855
   372
                "Unread",
dirk@855
   373
                comment: "Unread button title in swipe action on EmailListViewController")
dirk@744
   374
        } else {
dirk@855
   375
            localizedisReadTitle = NSLocalizedString(
dirk@855
   376
                "Read",
dirk@855
   377
                comment: "Read button title in swipe action on EmailListViewController")
dirk@744
   378
        }
dirk@744
   379
dirk@744
   380
        // creating the action
dirk@784
   381
        let isReadCompletionHandler: (UITableViewRowAction, IndexPath) -> Void =
dirk@744
   382
            { (action, indexPath) in
dirk@855
   383
                if (self.isRead(message: message)) {
dirk@855
   384
                    message.imapFlags.seen = false
dirk@744
   385
                } else {
dirk@855
   386
                    message.imapFlags.seen = true
dirk@744
   387
                }
dirk@855
   388
                self.syncFlagsToServer(message: message)
dirk@784
   389
                self.tableView.reloadRows(at: [indexPath], with: .none)
dirk@744
   390
        }
dirk@784
   391
        let isReadAction = UITableViewRowAction(style: .default, title: localizedisReadTitle,
dirk@744
   392
                                                handler: isReadCompletionHandler)
dirk@784
   393
        isReadAction.backgroundColor = UIColor.blue
dirk@744
   394
dirk@744
   395
        return isReadAction
dirk@744
   396
    }
dirk@784
   397
}