pEpForiOS/UI/EmailDisplay/EmailListViewController.swift
author Xavier Algarra <xavier@pep-project.org>
Mon, 13 Mar 2017 16:10:34 +0100
changeset 1832 8f9685564441
parent 1826 f8fe61819ba6
child 1865 fdd32d28247a
permissions -rw-r--r--
IOS-170 FilterView with diferents options
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@810
    12
import MessageModel
dirk@810
    13
igor@1260
    14
struct EmailListConfig {
igor@1338
    15
    var appConfig: AppConfig?
dirk@1333
    16
igor@1260
    17
    /** The folder to display, if it exists */
igor@1260
    18
    var folder: Folder?
igor@1260
    19
}
dirk@30
    20
dirk@854
    21
class EmailListViewController: UITableViewController {
dirk@583
    22
    struct UIState {
dirk@583
    23
        var isSynching: Bool = false
dirk@583
    24
    }
dirk@30
    25
dirk@1344
    26
    var config: EmailListConfig?
dirk@275
    27
    var state = UIState()
igor@1301
    28
    let searchController = UISearchController(searchResultsController: nil)
dirk@1737
    29
    let cellsInUse = NSCache<NSString, EmailListViewCell>()
dirk@719
    30
dirk@1724
    31
    /**
dirk@1724
    32
     After trustwords have been invoked, this will be the partner identity that
dirk@1724
    33
     was either confirmed or mistrusted.
dirk@1724
    34
     */
dirk@1724
    35
    var partnerIdentity: Identity?
dirk@1724
    36
dirk@275
    37
    override func viewDidLoad() {
ylandert@935
    38
        super.viewDidLoad()
xavier@1623
    39
igor@1408
    40
        title = "EmailList.title".localized
igor@1284
    41
        UIHelper.emailListTableHeight(self.tableView)
igor@1301
    42
        addSearchBar()
dirk@275
    43
    }
dirk@31
    44
dirk@784
    45
    override func viewWillAppear(_ animated: Bool) {
igor@1301
    46
        super.viewWillAppear(animated)
xavier@1623
    47
dirk@1344
    48
        if MiscUtil.isUnitTest() {
dirk@1344
    49
            return
dirk@1344
    50
        }
dirk@1344
    51
xavier@1832
    52
        self.textFilterButton.isEnabled = filterEnabled
xavier@1832
    53
dirk@1826
    54
        setDefaultColors()
dirk@1344
    55
        initialConfig()
dirk@854
    56
        updateModel()
dirk@1348
    57
dirk@1348
    58
        MessageModelConfig.messageFolderDelegate = self
dirk@1348
    59
    }
dirk@1348
    60
dirk@1348
    61
    override func viewWillDisappear(_ animated: Bool) {
dirk@1348
    62
        super.viewWillDisappear(animated)
dirk@1348
    63
        MessageModelConfig.messageFolderDelegate = nil
igor@1301
    64
    }
xavier@1623
    65
igor@1338
    66
    func initialConfig() {
dirk@1344
    67
        guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else {
igor@1338
    68
            return
igor@1338
    69
        }
dirk@1344
    70
dirk@1344
    71
        if config == nil {
igor@1395
    72
            config = EmailListConfig(appConfig: appDelegate.appConfig, folder: Folder.unifiedInbox())
dirk@1344
    73
        }
dirk@1348
    74
        if Account.all().isEmpty {
igor@1338
    75
            performSegue(withIdentifier:.segueAddNewAccount, sender: self)
igor@1338
    76
        }
igor@1338
    77
    }
xavier@1623
    78
igor@1301
    79
    func addSearchBar() {
igor@1301
    80
        searchController.searchResultsUpdater = self
igor@1301
    81
        searchController.dimsBackgroundDuringPresentation = false
igor@1301
    82
        searchController.delegate = self
igor@1301
    83
        definesPresentationContext = true
igor@1301
    84
        tableView.tableHeaderView = searchController.searchBar
igor@1301
    85
        tableView.setContentOffset(CGPoint(x: 0.0, y: 40.0), animated: false)
igor@1301
    86
    }
dirk@705
    87
dirk@854
    88
    func updateModel() {
igor@1318
    89
        tableView.reloadData()
dirk@31
    90
    }
dirk@31
    91
xavier@1832
    92
xavier@1832
    93
    private var filterEnabled = false
xavier@1832
    94
    @IBOutlet weak var enableFilterButton: UIBarButtonItem!
xavier@1832
    95
    @IBOutlet weak var textFilterButton: UIBarButtonItem!
xavier@1832
    96
    @IBAction func showUnreadButtonTapped(_ sender: UIBarButtonItem) {
xavier@1832
    97
        if filterEnabled {
xavier@1832
    98
            filterEnabled = false
xavier@1832
    99
            textFilterButton.title = ""
xavier@1832
   100
            enableFilterButton.image = UIImage(named: "unread-icon")
xavier@1832
   101
            config?.folder?.updateFilter(filter: Filter.unified())
xavier@1832
   102
            self.tableView.reloadData()
xavier@1832
   103
        } else {
xavier@1832
   104
            filterEnabled = true
xavier@1832
   105
            textFilterButton.title = "Filter by: unread"
xavier@1832
   106
            enableFilterButton.image = UIImage(named: "unread-icon-active")
xavier@1832
   107
            if config != nil {
xavier@1832
   108
                config?.folder?.updateFilter(filter: Filter.unread())
xavier@1832
   109
                self.tableView.reloadData()
xavier@1832
   110
            }
xavier@1832
   111
        }
xavier@1832
   112
        self.textFilterButton.isEnabled = filterEnabled
xavier@1832
   113
xavier@1832
   114
    }
xavier@1832
   115
dirk@58
   116
    // MARK: - UI State
dirk@58
   117
dirk@58
   118
    func updateUI() {
dirk@784
   119
        UIApplication.shared.isNetworkActivityIndicatorVisible = state.isSynching
dirk@748
   120
        if !state.isSynching {
igor@1260
   121
            refreshControl?.endRefreshing()
dirk@58
   122
        }
dirk@58
   123
    }
dirk@58
   124
dirk@31
   125
    // MARK: - UITableViewDataSource
dirk@31
   126
dirk@784
   127
    override func numberOfSections(in tableView: UITableView) -> Int {
dirk@1344
   128
        if let _ = config?.folder {
dirk@854
   129
            return 1
dirk@209
   130
        }
dirk@854
   131
        return 0
dirk@31
   132
    }
dirk@31
   133
dirk@784
   134
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
dirk@1344
   135
        if let fol = config?.folder  {
dirk@854
   136
            return fol.messageCount()
dirk@31
   137
        }
dirk@31
   138
        return 0
dirk@31
   139
    }
dirk@31
   140
dirk@784
   141
    override func tableView(_ tableView: UITableView,
dirk@784
   142
                            cellForRowAt indexPath: IndexPath) -> UITableViewCell {
dirk@784
   143
        let cell = tableView.dequeueReusableCell(
dirk@784
   144
            withIdentifier: "EmailListViewCell", for: indexPath) as! EmailListViewCell
dirk@1737
   145
        if let message = cell.configureCell(config: config, indexPath: indexPath) {
dirk@1737
   146
            associate(message: message, toCell: cell)
dirk@1542
   147
        }
dirk@31
   148
        return cell
dirk@31
   149
    }
dirk@31
   150
dirk@719
   151
    // MARK: - UITableViewDelegate
dirk@719
   152
dirk@784
   153
    override func tableView(_ tableView: UITableView, editActionsForRowAt
dirk@784
   154
        indexPath: IndexPath)-> [UITableViewRowAction]? {
xavier@1623
   155
dirk@784
   156
        let cell = tableView.cellForRow(at: indexPath) as! EmailListViewCell
igor@1260
   157
        if let email = cell.messageAt(indexPath: indexPath, config: config) {
igor@1576
   158
            let flagAction = createFlagAction(message: email, cell: cell)
dirk@1507
   159
            let deleteAction = createDeleteAction(message: email, cell: cell)
igor@1242
   160
            let moreAction = createMoreAction(message: email, cell: cell)
igor@1576
   161
            return [deleteAction, flagAction, moreAction]
dirk@855
   162
        }
dirk@855
   163
        return nil
dirk@744
   164
    }
dirk@744
   165
dirk@719
   166
    // MARK: - Misc
dirk@719
   167
dirk@1507
   168
    func createRowAction(cell: EmailListViewCell,
xavier@1623
   169
                         image: UIImage?, action: @escaping (UITableViewRowAction, IndexPath) -> Void,
xavier@1623
   170
                         title: String) -> UITableViewRowAction {
dirk@1510
   171
        let rowAction = UITableViewRowAction(
dirk@1510
   172
            style: .normal, title: title, handler: action)
dirk@1507
   173
dirk@1507
   174
        if let theImage = image {
dirk@1507
   175
            let iconColor = UIColor(patternImage: theImage)
dirk@1507
   176
            rowAction.backgroundColor = iconColor
dirk@744
   177
        }
dirk@744
   178
dirk@1507
   179
        return rowAction
dirk@744
   180
    }
dirk@744
   181
dirk@1507
   182
    func createFlagAction(message: Message, cell: EmailListViewCell) -> UITableViewRowAction {
dirk@1507
   183
        func action(action: UITableViewRowAction, indexPath: IndexPath) -> Void {
dirk@1522
   184
            if message.imapFlags == nil {
dirk@1522
   185
                Log.warn(component: #function, content: "message.imapFlags == nil")
dirk@1522
   186
            }
dirk@1605
   187
            if cell.isFlagged(message: message) {
dirk@1507
   188
                message.imapFlags?.flagged = false
dirk@1507
   189
            } else {
dirk@1507
   190
                message.imapFlags?.flagged = true
dirk@1507
   191
            }
dirk@1507
   192
            message.save()
dirk@1507
   193
            self.tableView.reloadRows(at: [indexPath], with: .none)
dirk@1507
   194
        }
dirk@1510
   195
igor@1523
   196
        var title = "\n\nFlag".localized
dirk@1605
   197
        if message.imapFlags?.flagged ?? true {
igor@1530
   198
            title = "\n\nUnFlag".localized
dirk@744
   199
        }
dirk@744
   200
dirk@1510
   201
        return createRowAction(
dirk@1510
   202
            cell: cell, image: UIImage(named: "swipe-flag"), action: action, title: title)
dirk@744
   203
    }
dirk@744
   204
dirk@1507
   205
    func createDeleteAction(message: Message, cell: EmailListViewCell) -> UITableViewRowAction {
dirk@1507
   206
        func action(action: UITableViewRowAction, indexPath: IndexPath) -> Void {
dirk@1507
   207
            guard let message = cell.messageAt(indexPath: indexPath, config: self.config) else {
dirk@1507
   208
                return
dirk@1507
   209
            }
xavier@1623
   210
dirk@1650
   211
            message.delete() // mark for deletion/trash
dirk@1507
   212
            message.save()
igor@1576
   213
            self.tableView.reloadData()
dirk@1507
   214
        }
dirk@744
   215
dirk@1510
   216
        return createRowAction(
dirk@1510
   217
            cell: cell, image: UIImage(named: "swipe-trash"), action: action,
igor@1523
   218
            title: "\n\nDelete".localized)
dirk@1507
   219
    }
dirk@1507
   220
dirk@1507
   221
    func createMarkAsReadAction(message: Message, cell: EmailListViewCell) -> UITableViewRowAction {
dirk@1507
   222
        func action(action: UITableViewRowAction, indexPath: IndexPath) -> Void {
dirk@1605
   223
            if cell.haveSeen(message: message) {
dirk@1507
   224
                message.imapFlags?.seen = false
dirk@1507
   225
            } else {
dirk@1507
   226
                message.imapFlags?.seen = true
dirk@1507
   227
            }
dirk@1507
   228
            self.tableView.reloadRows(at: [indexPath], with: .none)
dirk@744
   229
        }
dirk@1510
   230
dirk@1510
   231
        var title = NSLocalizedString(
dirk@1510
   232
            "Unread", comment: "Unread button title in swipe action on EmailListViewController")
dirk@1605
   233
        if !cell.haveSeen(message: message) {
dirk@1510
   234
            title = NSLocalizedString(
dirk@1510
   235
                "Read", comment: "Read button title in swipe action on EmailListViewController")
dirk@1507
   236
        }
dirk@1507
   237
dirk@1507
   238
        let isReadAction = createRowAction(cell: cell, image: nil, action: action,
dirk@1510
   239
                                           title: title)
dirk@784
   240
        isReadAction.backgroundColor = UIColor.blue
dirk@744
   241
dirk@744
   242
        return isReadAction
dirk@744
   243
    }
xavier@1623
   244
igor@1242
   245
    func createMoreAction(message: Message, cell: EmailListViewCell) -> UITableViewRowAction {
dirk@1510
   246
        func action(action: UITableViewRowAction, indexPath: IndexPath) -> Void {
igor@1242
   247
            self.showMoreActionSheet(cell: cell)
igor@1242
   248
        }
dirk@1510
   249
dirk@1510
   250
        return createRowAction(
dirk@1510
   251
            cell: cell, image: UIImage(named: "swipe-more"), action: action,
igor@1523
   252
            title: "\n\nMore".localized)
igor@1242
   253
    }
xavier@1623
   254
igor@1242
   255
    // MARK: - Action Sheet
xavier@1623
   256
igor@1242
   257
    func showMoreActionSheet(cell: EmailListViewCell) {
igor@1242
   258
        let alertControler = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
igor@1438
   259
        alertControler.view.tintColor = .pEpGreen
igor@1242
   260
        let cancelAction = createCancelAction()
igor@1242
   261
        let replyAction = createReplyAction(cell: cell)
xavier@1623
   262
        let replyAllAction = createReplyAllAction(cell: cell)
igor@1242
   263
        let forwardAction = createForwardAction(cell: cell)
igor@1242
   264
        let markAction = createMarkAction()
igor@1242
   265
        alertControler.addAction(cancelAction)
igor@1242
   266
        alertControler.addAction(replyAction)
xavier@1620
   267
        alertControler.addAction(replyAllAction)
igor@1242
   268
        alertControler.addAction(forwardAction)
igor@1242
   269
        alertControler.addAction(markAction)
igor@1414
   270
        if let popoverPresentationController = alertControler.popoverPresentationController {
igor@1414
   271
            popoverPresentationController.sourceView = cell
igor@1414
   272
        }
igor@1242
   273
        present(alertControler, animated: true, completion: nil)
igor@1242
   274
    }
xavier@1623
   275
igor@1242
   276
    // MARK: - Action Sheet Actions
igor@1242
   277
igor@1242
   278
    func createCancelAction() -> UIAlertAction {
xavier@1623
   279
        return  UIAlertAction(title: "Cancel", style: .cancel) { (action) in}
igor@1242
   280
    }
xavier@1623
   281
igor@1242
   282
    func createReplyAction(cell: EmailListViewCell) ->  UIAlertAction {
igor@1242
   283
        return UIAlertAction(title: "Reply", style: .default) { (action) in
xavier@1623
   284
            // self.performSegue(withIdentifier: self.segueCompose, sender: cell)
igor@1338
   285
            self.performSegue(withIdentifier: .segueCompose, sender: cell)
igor@1242
   286
        }
igor@1242
   287
    }
xavier@1620
   288
xavier@1620
   289
    func createReplyAllAction(cell: EmailListViewCell) ->  UIAlertAction {
xavier@1623
   290
        return UIAlertAction(title: "Reply All", style: .default) { (action) in
xavier@1623
   291
            self.performSegue(withIdentifier: .segueReplyAll, sender: cell)
xavier@1620
   292
        }
xavier@1620
   293
    }
xavier@1620
   294
igor@1242
   295
    func createForwardAction(cell: EmailListViewCell) -> UIAlertAction {
igor@1242
   296
        return UIAlertAction(title: "Forward", style: .default) { (action) in
igor@1338
   297
            //self.performSegue(withIdentifier: self.segueCompose, sender: cell)
xavier@1664
   298
            self.performSegue(withIdentifier: .segueForward, sender: cell)
igor@1242
   299
        }
igor@1242
   300
    }
xavier@1623
   301
igor@1242
   302
    func createMarkAction() -> UIAlertAction {
igor@1242
   303
        return UIAlertAction(title: "Mark", style: .default) { (action) in
igor@1242
   304
        }
igor@1242
   305
    }
xavier@1623
   306
igor@1301
   307
    // MARK: - Content Search
xavier@1623
   308
igor@1301
   309
    func filterContentForSearchText(searchText: String) {
xavier@1623
   310
igor@1301
   311
    }
xavier@1623
   312
dirk@784
   313
}
igor@1301
   314
igor@1301
   315
extension EmailListViewController: UISearchResultsUpdating, UISearchControllerDelegate {
igor@1301
   316
    public func updateSearchResults(for searchController: UISearchController) {
igor@1301
   317
        filterContentForSearchText(searchText: searchController.searchBar.text!)
igor@1301
   318
    }
xavier@1623
   319
igor@1301
   320
    func didDismissSearchController(_ searchController: UISearchController) {
igor@1301
   321
    }
igor@1301
   322
}
igor@1338
   323
igor@1338
   324
// MARK: - Navigation
igor@1338
   325
igor@1338
   326
extension EmailListViewController: SegueHandlerType {
xavier@1623
   327
igor@1338
   328
    // MARK: - SegueHandlerType
xavier@1623
   329
igor@1338
   330
    enum SegueIdentifier: String {
igor@1338
   331
        case segueAddNewAccount
igor@1338
   332
        case segueEditAccounts
igor@1338
   333
        case segueShowEmail
igor@1338
   334
        case segueCompose
xavier@1623
   335
        case segueReplyAll
xavier@1664
   336
        case segueForward
igor@1338
   337
        case noSegue
igor@1338
   338
    }
xavier@1623
   339
igor@1338
   340
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
igor@1338
   341
        switch segueIdentifier(for: segue) {
xavier@1623
   342
        case .segueReplyAll:
xavier@1623
   343
            if let nav = segue.destination as? UINavigationController,
xavier@1623
   344
                let destination = nav.topViewController as? ComposeTableViewController,
xavier@1623
   345
                let cell = sender as? EmailListViewCell,
xavier@1623
   346
                let indexPath = self.tableView.indexPath(for: cell),
xavier@1623
   347
                let email = cell.messageAt(indexPath: indexPath, config: config) {
xavier@1623
   348
                destination.composeMode = .replyAll
xavier@1623
   349
                destination.appConfig = config?.appConfig
xavier@1623
   350
                destination.originalMessage = email
xavier@1623
   351
            }
igor@1338
   352
            break
igor@1338
   353
        case .segueShowEmail:
dirk@1594
   354
            if let vc = segue.destination as? EmailViewController,
igor@1338
   355
                let cell = sender as? EmailListViewCell,
igor@1338
   356
                let indexPath = self.tableView.indexPath(for: cell),
dirk@1594
   357
                let email = cell.messageAt(indexPath: indexPath, config: config) {
xavier@1623
   358
                vc.appConfig = config?.appConfig
xavier@1623
   359
                vc.message = email
igor@1338
   360
            }
igor@1338
   361
            break
xavier@1664
   362
        case .segueForward:
xavier@1664
   363
            if let nav = segue.destination as? UINavigationController,
xavier@1664
   364
                let destination = nav.topViewController as? ComposeTableViewController,
xavier@1664
   365
                let cell = sender as? EmailListViewCell,
xavier@1664
   366
                let indexPath = self.tableView.indexPath(for: cell),
xavier@1664
   367
                let email = cell.messageAt(indexPath: indexPath, config: config) {
xavier@1664
   368
                destination.composeMode = .forward
xavier@1664
   369
                destination.appConfig = config?.appConfig
xavier@1664
   370
                destination.originalMessage = email
xavier@1664
   371
            }
xavier@1664
   372
            break
dirk@1694
   373
        case .segueAddNewAccount, .segueEditAccounts, .segueCompose, .noSegue:
dirk@1694
   374
            break
igor@1338
   375
        }
igor@1338
   376
    }
dirk@1350
   377
dirk@1350
   378
    func didChangeInternal(messageFolder: MessageFolder) {
dirk@1350
   379
        if let folder = config?.folder,
dirk@1350
   380
            let message = messageFolder as? Message,
dirk@1558
   381
            folder.contains(message: message, deletedMessagesAreContained: true) {
dirk@1350
   382
            if let msg = messageFolder as? Message {
dirk@1350
   383
                if msg.isOriginal {
dirk@1535
   384
                    // new message has arrived
dirk@1675
   385
                    if let index = folder.indexOf(message: msg) {
dirk@1675
   386
                        let ip = IndexPath(row: index, section: 0)
dirk@1737
   387
                        Log.info(
dirk@1737
   388
                            component: #function,
dirk@1737
   389
                            content: "insert message at \(index), \(folder.messageCount()) messages")
dirk@1675
   390
                        tableView.insertRows(at: [ip], with: .automatic)
dirk@1675
   391
                    } else {
dirk@1675
   392
                        tableView.reloadData()
dirk@1675
   393
                    }
dirk@1558
   394
                } else if msg.isGhost {
dirk@1737
   395
                    if let cell = cellFor(message: msg), let ip = tableView.indexPath(for: cell) {
dirk@1737
   396
                        Log.info(
dirk@1737
   397
                            component: #function,
dirk@1737
   398
                            content: "delete message at \(index), \(folder.messageCount()) messages")
dirk@1737
   399
                        tableView.deleteRows(at: [ip], with: .automatic)
dirk@1737
   400
                    } else {
dirk@1737
   401
                        tableView.reloadData()
dirk@1558
   402
                    }
dirk@1535
   403
                } else {
dirk@1558
   404
                    // other flags than delete must have been changed
dirk@1737
   405
                    if let cell = cellFor(message: msg) {
dirk@1542
   406
                        cell.updateFlags(message: message)
dirk@1737
   407
                    } else {
dirk@1737
   408
                        tableView.reloadData()
dirk@1542
   409
                    }
dirk@1350
   410
                }
dirk@1350
   411
            }
dirk@1350
   412
        }
dirk@1350
   413
    }
dirk@1737
   414
dirk@1737
   415
    // MARK: - Message -> Cell association
dirk@1737
   416
dirk@1737
   417
    func keyFor(message: Message) -> NSString {
dirk@1737
   418
        let parentName = message.parent?.name ?? "unknown"
dirk@1737
   419
        return "\(message.uuid) \(parentName) \(message.uuid)" as NSString
dirk@1737
   420
    }
dirk@1737
   421
dirk@1737
   422
    func associate(message: Message, toCell: EmailListViewCell) {
dirk@1737
   423
        cellsInUse.setObject(toCell, forKey: keyFor(message: message))
dirk@1737
   424
    }
dirk@1737
   425
dirk@1737
   426
    func cellFor(message: Message) -> EmailListViewCell? {
dirk@1737
   427
        return cellsInUse.object(forKey: keyFor(message: message))
dirk@1737
   428
    }
igor@1338
   429
}
dirk@1348
   430
dirk@1348
   431
// MARK: - MessageFolderDelegate
dirk@1348
   432
dirk@1348
   433
extension EmailListViewController: MessageFolderDelegate {
dirk@1348
   434
    func didChange(messageFolder: MessageFolder) {
dirk@1675
   435
        GCD.onMainWait {
dirk@1350
   436
            self.didChangeInternal(messageFolder: messageFolder)
dirk@1348
   437
        }
dirk@1348
   438
    }
dirk@1348
   439
}