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