pEpForiOS/UI/EmailDisplay/EmailListViewController.swift
author Xavier Algarra <xavier@pep-project.org>
Wed, 02 Aug 2017 14:18:48 +0200
changeset 2585 6e67065e5b3c
parent 2458 1ea96e50273e
child 2639 d4f638d00237
permissions -rw-r--r--
IOS-613 folder button hiden when showing a folder
     1 //
     2 //  EmailListViewController.swift
     3 //  pEpForiOS
     4 //
     5 //  Created by Dirk Zimmermann on 16/04/16.
     6 //  Copyright © 2016 p≡p Security S.A. All rights reserved.
     7 //
     8 
     9 import Foundation
    10 import UIKit
    11 import CoreData
    12 import MessageModel
    13 
    14 struct EmailListConfig {
    15     var appConfig: AppConfig?
    16 
    17     /** The folder to display, if it exists */
    18     var folder: Folder?
    19 
    20     let imageProvider = IdentityImageProvider()
    21 }
    22 
    23 class EmailListViewController: UITableViewController {
    24     struct UIState {
    25         var isSynching: Bool = false
    26     }
    27 
    28     var config: EmailListConfig?
    29     var viewModel: EmailListViewModel?
    30     var state = UIState()
    31     let searchController = UISearchController(searchResultsController: nil)
    32     //let cellsInUse = NSCache<NSString, EmailListViewCell>()
    33 
    34     /**
    35      After trustwords have been invoked, this will be the partner identity that
    36      was either confirmed or mistrusted.
    37      */
    38     var partnerIdentity: Identity?
    39 
    40     @IBOutlet weak var enableFilterButton: UIBarButtonItem!
    41     @IBOutlet weak var textFilterButton: UIBarButtonItem!
    42 
    43     @IBOutlet var showFoldersButton: UIBarButtonItem!
    44     //private var filterEnabled = false
    45 
    46     override func viewDidLoad() {
    47         super.viewDidLoad()
    48 
    49         title = NSLocalizedString("Inbox", comment: "General name for (unified) inbox")
    50         UIHelper.emailListTableHeight(self.tableView)
    51         addSearchBar()
    52     }
    53 
    54     override func viewWillAppear(_ animated: Bool) {
    55         super.viewWillAppear(animated)
    56         self.navigationController?.setToolbarHidden(false, animated: true)
    57         if MiscUtil.isUnitTest() {
    58             return
    59         }
    60 
    61         if let vm = viewModel {
    62             self.textFilterButton.isEnabled = vm.filterEnabled
    63         } else {
    64             self.textFilterButton.isEnabled = false
    65         }
    66 
    67         setDefaultColors()
    68         initialConfig()
    69         updateModel()
    70 
    71         // Mark this folder as having been looked at by the user
    72         if let fol = config?.folder {
    73             fol.updateLastLookAt()
    74         }
    75         if viewModel == nil {
    76             viewModel = EmailListViewModel(config: config, delegate: self)
    77         }
    78         MessageModelConfig.messageFolderDelegate = self
    79 
    80         if let size = navigationController?.viewControllers.count, size > 1 {
    81             self.showFoldersButton.isEnabled = false
    82         } else {
    83             self.showFoldersButton.isEnabled = true
    84         }
    85         
    86     }
    87 
    88 
    89     override func viewWillDisappear(_ animated: Bool) {
    90         super.viewWillDisappear(animated)
    91         MessageModelConfig.messageFolderDelegate = nil
    92     }
    93 
    94     func initialConfig() {
    95         guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else {
    96             return
    97         }
    98         if config == nil {
    99             config = EmailListConfig(appConfig: appDelegate.appConfig,
   100                                      folder: Folder.unifiedInbox())
   101         }
   102 
   103         if Account.all().isEmpty {
   104             performSegue(withIdentifier:.segueAddNewAccount, sender: self)
   105         }
   106         self.title = config?.folder?.realName
   107     }
   108 
   109     func addSearchBar() {
   110         searchController.searchResultsUpdater = self
   111         searchController.dimsBackgroundDuringPresentation = false
   112         searchController.delegate = self
   113         definesPresentationContext = true
   114         tableView.tableHeaderView = searchController.searchBar
   115         tableView.setContentOffset(CGPoint(x: 0.0, y: 40.0), animated: false)
   116     }
   117 
   118     func updateModel() {
   119         tableView.reloadData()
   120     }
   121 
   122 
   123     @IBAction func showUnreadButtonTapped(_ sender: UIBarButtonItem) {
   124         if let vm = viewModel {
   125             if vm.filterEnabled {
   126                 vm.filterEnabled = false
   127                 textFilterButton.title = ""
   128                 enableFilterButton.image = UIImage(named: "unread-icon")
   129                 if config != nil {
   130                     vm.resetFilters()
   131                 }
   132             } else {
   133                 vm.filterEnabled = true
   134                 textFilterButton.title = "Filter by: unread"
   135                 enableFilterButton.image = UIImage(named: "unread-icon-active")
   136                 if config != nil {
   137                     vm.updateFilter(filter: Filter.unread())
   138                 }
   139             }
   140             self.textFilterButton.isEnabled = vm.filterEnabled
   141         }
   142 
   143 
   144     }
   145 
   146     // MARK: - UI State
   147 
   148     func updateUI() {
   149         UIApplication.shared.isNetworkActivityIndicatorVisible = state.isSynching
   150         if !state.isSynching {
   151             refreshControl?.endRefreshing()
   152         }
   153     }
   154 
   155     // MARK: - UITableViewDataSource
   156 
   157     override func numberOfSections(in tableView: UITableView) -> Int {
   158         if let _ = viewModel?.folderToShow {
   159             return 1
   160         }
   161         return 0
   162     }
   163 
   164     override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
   165         if let vm = viewModel {
   166             return vm.count
   167         }
   168         return 0
   169     }
   170 
   171     override func tableView(_ tableView: UITableView,
   172                             cellForRowAt indexPath: IndexPath) -> UITableViewCell {
   173         let cell = tableView.dequeueReusableCell(
   174             withIdentifier: "EmailListViewCell", for: indexPath) as! EmailListViewCell
   175         //mantener el configure cell para tal de no generar un vm para celdas
   176         let _ = cell.configureCell(config: config, indexPath: indexPath)
   177         viewModel?.associate(cell: cell, position: indexPath.row)
   178         return cell
   179     }
   180 
   181     // MARK: - UITableViewDelegate
   182 
   183     override func tableView(_ tableView: UITableView, editActionsForRowAt
   184         indexPath: IndexPath)-> [UITableViewRowAction]? {
   185 
   186         let cell = tableView.cellForRow(at: indexPath) as! EmailListViewCell
   187         if let email = cell.messageAt(indexPath: indexPath, config: config) {
   188             let flagAction = createFlagAction(message: email, cell: cell)
   189             let deleteAction = createDeleteAction(message: email, cell: cell)
   190             let moreAction = createMoreAction(message: email, cell: cell)
   191             return [deleteAction, flagAction, moreAction]
   192         }
   193         return nil
   194     }
   195 
   196     // MARK: - Misc
   197 
   198     func createRowAction(cell: EmailListViewCell,
   199                          image: UIImage?, action: @escaping (UITableViewRowAction, IndexPath) -> Void,
   200                          title: String) -> UITableViewRowAction {
   201         let rowAction = UITableViewRowAction(
   202             style: .normal, title: title, handler: action)
   203 
   204         if let theImage = image {
   205             let iconColor = UIColor(patternImage: theImage)
   206             rowAction.backgroundColor = iconColor
   207         }
   208 
   209         return rowAction
   210     }
   211 
   212     func createFlagAction(message: Message, cell: EmailListViewCell) -> UITableViewRowAction {
   213         func action(action: UITableViewRowAction, indexPath: IndexPath) -> Void {
   214             if message.imapFlags == nil {
   215                 Log.warn(component: #function, content: "message.imapFlags == nil")
   216             }
   217             if cell.isFlagged(message: message) {
   218                 message.imapFlags?.flagged = false
   219             } else {
   220                 message.imapFlags?.flagged = true
   221             }
   222             message.save()
   223             self.tableView.reloadRows(at: [indexPath], with: .none)
   224         }
   225 
   226         var title = "\n\n\(NSLocalizedString("Flag", comment: "Message action (on swipe)"))"
   227         if message.imapFlags?.flagged ?? true {
   228             title = "\n\n\(NSLocalizedString("Unflag", comment: "Message action (on swipe)"))"
   229         }
   230 
   231         return createRowAction(
   232             cell: cell, image: UIImage(named: "swipe-flag"), action: action, title: title)
   233     }
   234 
   235     func createDeleteAction(message: Message, cell: EmailListViewCell) -> UITableViewRowAction {
   236         func action(action: UITableViewRowAction, indexPath: IndexPath) -> Void {
   237             guard let message = cell.messageAt(indexPath: indexPath, config: self.config) else {
   238                 return
   239             }
   240 
   241             message.delete() // mark for deletion/trash
   242             message.save()
   243             self.tableView.reloadData()
   244         }
   245 
   246         return createRowAction(
   247             cell: cell, image: UIImage(named: "swipe-trash"), action: action,
   248             title: "\n\n\(NSLocalizedString("Delete", comment: "Message action (on swipe)"))")
   249     }
   250 
   251     func createMarkAsReadAction(message: Message, cell: EmailListViewCell) -> UITableViewRowAction {
   252         func action(action: UITableViewRowAction, indexPath: IndexPath) -> Void {
   253             if cell.haveSeen(message: message) {
   254                 message.imapFlags?.seen = false
   255             } else {
   256                 message.imapFlags?.seen = true
   257             }
   258             self.tableView.reloadRows(at: [indexPath], with: .none)
   259         }
   260 
   261         var title = NSLocalizedString(
   262             "Unread", comment: "Message action (on swipe)")
   263         if !cell.haveSeen(message: message) {
   264             title = NSLocalizedString(
   265                 "Read", comment: "Message action (on swipe)")
   266         }
   267 
   268         let isReadAction = createRowAction(cell: cell, image: nil, action: action,
   269                                            title: title)
   270         isReadAction.backgroundColor = UIColor.blue
   271 
   272         return isReadAction
   273     }
   274 
   275     func createMoreAction(message: Message, cell: EmailListViewCell) -> UITableViewRowAction {
   276         func action(action: UITableViewRowAction, indexPath: IndexPath) -> Void {
   277             self.showMoreActionSheet(cell: cell)
   278         }
   279 
   280         return createRowAction(
   281             cell: cell, image: UIImage(named: "swipe-more"), action: action,
   282             title: "\n\n\(NSLocalizedString("More", comment: "Message action (on swipe)"))")
   283     }
   284 
   285     // MARK: - Action Sheet
   286 
   287     func showMoreActionSheet(cell: EmailListViewCell) {
   288         let alertControler = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
   289         alertControler.view.tintColor = .pEpGreen
   290         let cancelAction = createCancelAction()
   291         let replyAction = createReplyAction(cell: cell)
   292         let replyAllAction = createReplyAllAction(cell: cell)
   293         let forwardAction = createForwardAction(cell: cell)
   294         let markAction = createMarkAction()
   295         alertControler.addAction(cancelAction)
   296         alertControler.addAction(replyAction)
   297         alertControler.addAction(replyAllAction)
   298         alertControler.addAction(forwardAction)
   299         alertControler.addAction(markAction)
   300         if let popoverPresentationController = alertControler.popoverPresentationController {
   301             popoverPresentationController.sourceView = cell
   302         }
   303         present(alertControler, animated: true, completion: nil)
   304     }
   305 
   306     // MARK: - Action Sheet Actions
   307 
   308     func createCancelAction() -> UIAlertAction {
   309         return  UIAlertAction(title: "Cancel", style: .cancel) { (action) in}
   310     }
   311 
   312     func createReplyAction(cell: EmailListViewCell) ->  UIAlertAction {
   313         return UIAlertAction(title: "Reply", style: .default) { (action) in
   314             // self.performSegue(withIdentifier: self.segueCompose, sender: cell)
   315             self.performSegue(withIdentifier: .segueCompose, sender: cell)
   316         }
   317     }
   318 
   319     func createReplyAllAction(cell: EmailListViewCell) ->  UIAlertAction {
   320         return UIAlertAction(title: "Reply All", style: .default) { (action) in
   321             self.performSegue(withIdentifier: .segueReplyAll, sender: cell)
   322         }
   323     }
   324 
   325     func createForwardAction(cell: EmailListViewCell) -> UIAlertAction {
   326         return UIAlertAction(title: "Forward", style: .default) { (action) in
   327             self.performSegue(withIdentifier: .segueForward, sender: cell)
   328         }
   329     }
   330 
   331     func createMarkAction() -> UIAlertAction {
   332         return UIAlertAction(title: "Mark", style: .default) { (action) in
   333         }
   334     }
   335 
   336 }
   337 
   338 extension EmailListViewController: UISearchResultsUpdating, UISearchControllerDelegate {
   339     public func updateSearchResults(for searchController: UISearchController) {
   340         if let vm = viewModel {
   341             vm.filterContentForSearchText(searchText: searchController.searchBar.text!, clear: false)
   342         }
   343     }
   344 
   345     func didDismissSearchController(_ searchController: UISearchController) {
   346         if let vm = viewModel {
   347             vm.filterContentForSearchText(clear: true)
   348         }
   349     }
   350 }
   351 
   352 // MARK: - Navigation
   353 
   354 extension EmailListViewController: SegueHandlerType {
   355 
   356     // MARK: - SegueHandlerType
   357 
   358     enum SegueIdentifier: String {
   359         case segueAddNewAccount
   360         case segueEditAccounts
   361         case segueShowEmail
   362         case segueCompose
   363         case segueReplyAll
   364         case segueForward
   365         case segueFilter
   366         case segueFolderViews
   367         case noSegue
   368     }
   369 
   370     override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
   371         switch segueIdentifier(for: segue) {
   372         case .segueReplyAll:
   373             if let nav = segue.destination as? UINavigationController,
   374                 let destination = nav.topViewController as? ComposeTableViewController,
   375                 let cell = sender as? EmailListViewCell,
   376                 let indexPath = self.tableView.indexPath(for: cell),
   377                 let email = cell.messageAt(indexPath: indexPath, config: config) {
   378                 destination.composeMode = .replyAll
   379                 destination.appConfig = config?.appConfig
   380                 destination.originalMessage = email
   381             }
   382             break
   383         case .segueShowEmail:
   384             if let vc = segue.destination as? EmailViewController,
   385                 let cell = sender as? EmailListViewCell,
   386                 let indexPath = self.tableView.indexPath(for: cell),
   387                 let email = cell.messageAt(indexPath: indexPath, config: config) {
   388                 vc.appConfig = config?.appConfig
   389                 vc.message = email
   390                 vc.folderShow = viewModel?.folderToShow
   391                 vc.messageId = indexPath.row
   392             }
   393             break
   394         case .segueForward:
   395             if let nav = segue.destination as? UINavigationController,
   396                 let destination = nav.topViewController as? ComposeTableViewController,
   397                 let cell = sender as? EmailListViewCell,
   398                 let indexPath = self.tableView.indexPath(for: cell),
   399                 let email = cell.messageAt(indexPath: indexPath, config: config) {
   400                 destination.composeMode = .forward
   401                 destination.appConfig = config?.appConfig
   402                 destination.originalMessage = email
   403             }
   404             break
   405         case .segueFilter:
   406             if let destiny = segue.destination as? FilterTableViewController {
   407                 destiny.filterDelegate = self.viewModel
   408                 destiny.inFolder = false
   409                 destiny.filterEnabled = self.viewModel?.folderToShow?.filter
   410                 destiny.hidesBottomBarWhenPushed = true
   411             }
   412             break
   413         case .segueAddNewAccount:
   414             if let vc = segue.destination as? LoginTableViewController {
   415                 vc.appConfig = config?.appConfig
   416                 vc.hidesBottomBarWhenPushed = true
   417             }
   418         case .segueFolderViews:
   419             if let vC = segue.destination as? FolderTableViewController {
   420                 vC.appConfig = config?.appConfig
   421                 vC.hidesBottomBarWhenPushed = true
   422             }
   423         case .segueEditAccounts, .segueCompose, .noSegue:
   424             break
   425         }
   426 
   427     }
   428     
   429     @IBAction func segueUnwindAccountAdded(segue: UIStoryboardSegue) {
   430     }
   431 
   432     func didChangeInternal(messageFolder: MessageFolder) {
   433         if let folder = config?.folder,
   434             let message = messageFolder as? Message,
   435             folder.contains(message: message, deletedMessagesAreContained: true) {
   436             if message.isOriginal {
   437                 // new message has arrived
   438                 if let index = folder.indexOf(message: message) {
   439                     let ip = IndexPath(row: index, section: 0)
   440                     Log.info(
   441                         component: #function,
   442                         content: "insert message at \(index), \(folder.messageCount()) messages")
   443                     tableView.insertRows(at: [ip], with: .automatic)
   444                 } else {
   445                     tableView.reloadData()
   446                 }
   447             } else if message.isGhost {
   448                 if let vm = viewModel, let cell = vm.cellFor(message: message), let ip = tableView.indexPath(for: cell) {
   449                     Log.info(
   450                         component: #function,
   451                         content: "delete message at \(index), \(folder.messageCount()) messages")
   452                     tableView.deleteRows(at: [ip], with: .automatic)
   453                 } else {
   454                     tableView.reloadData()
   455                 }
   456             } else {
   457                 // other flags than delete must have been changed
   458                 if let vm = viewModel, let cell = vm.cellFor(message: message) {
   459                     cell.updateFlags(message: message)
   460                 } else {
   461                     tableView.reloadData()
   462                 }
   463             }
   464         }
   465     }
   466 
   467 }
   468 
   469 // MARK: - MessageFolderDelegate
   470 
   471 extension EmailListViewController: MessageFolderDelegate {
   472     func didChange(messageFolder: MessageFolder) {
   473         GCD.onMainWait {
   474             self.didChangeInternal(messageFolder: messageFolder)
   475         }
   476     }
   477 }
   478 
   479 extension EmailListViewController: tableViewUpdate {
   480     func updateView() {
   481         self.tableView.reloadData()
   482     }
   483 }