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