Bastian van de Wetering 6 жил өмнө
parent
commit
bec32b97e9

+ 48 - 50
deltachat-ios/AccountSetupController.swift

@@ -35,11 +35,11 @@ class AccountSetupController: UITableViewController {
     return cell
   }()
 
-	private lazy var restoreCell: ActionCell = {
-		let cell = ActionCell(title: "Restore from backup")
-		cell.accessibilityIdentifier = "restoreCell"
-		return cell
-	}()
+  private lazy var restoreCell: ActionCell = {
+    let cell = ActionCell(title: "Restore from backup")
+    cell.accessibilityIdentifier = "restoreCell"
+    return cell
+  }()
 
   lazy var imapServerCell: TextFieldCell = {
     let cell = TextFieldCell(description: "IMAP Server", placeholder: MRConfig.mailServer ?? MRConfig.configuredMailServer, delegate: self)
@@ -112,7 +112,7 @@ class AccountSetupController: UITableViewController {
   let loginButton: UIBarButtonItem = UIBarButtonItem(title: "Login", style: .done, target: self, action: #selector(loginButtonPressed))
 
   private lazy var basicSectionCells: [UITableViewCell] = [emailCell, passwordCell]
-	private lazy var restoreCells: [UITableViewCell] = [restoreCell]
+  private lazy var restoreCells: [UITableViewCell] = [restoreCell]
   private lazy var advancedSectionCells: [UITableViewCell] = [
     imapServerCell,
     imapUserCell,
@@ -146,7 +146,7 @@ class AccountSetupController: UITableViewController {
     super.viewDidAppear(animated)
     addProgressHudEventListener()
     // loginButton.isEnabled = false
-	}
+  }
 
   override func viewDidDisappear(_: Bool) {
     let nc = NotificationCenter.default
@@ -171,9 +171,9 @@ class AccountSetupController: UITableViewController {
   override func tableView(_: UITableView, numberOfRowsInSection section: Int) -> Int {
     // #warning Incomplete implementation, return the number of rows
     if section == 0 {
-			return basicSectionCells.count
-		} else if section == 1 {
-			return restoreCells.count
+      return basicSectionCells.count
+    } else if section == 1 {
+      return restoreCells.count
     } else {
       return advancedSectionShowing ? advancedSectionCells.count : 0
     }
@@ -207,12 +207,11 @@ class AccountSetupController: UITableViewController {
   override func tableView(_: UITableView, titleForFooterInSection section: Int) -> String? {
     if section == 0 {
       return "There are no Delta Chat servers, your data stays on your device!"
-    } else if section == 2{
+    } else if section == 2 {
       return "For known email providers additional settings are setup automatically. Sometimes IMAP needs to be enabled in the web frontend. Consult your email provider or friends for help"
-		} else {
-			return nil
-		}
-
+    } else {
+      return nil
+    }
   }
 
   override func tableView(_: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
@@ -222,8 +221,8 @@ class AccountSetupController: UITableViewController {
     if section == 0 {
       // basicSection
       return basicSectionCells[row]
-		} else if section == 1 {
-			return restoreCells[row]
+    } else if section == 1 {
+      return restoreCells[row]
     } else {
       // advancedSection
       return advancedSectionCells[row]
@@ -231,9 +230,8 @@ class AccountSetupController: UITableViewController {
   }
 
   override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
-
-		guard let tappedCell = tableView.cellForRow(at: indexPath) else { return }
-		// handle tap on password -> show oAuthDialogue
+    guard let tappedCell = tableView.cellForRow(at: indexPath) else { return }
+    // handle tap on password -> show oAuthDialogue
     if let textFieldCell = tappedCell as? TextFieldCell {
       if textFieldCell.accessibilityIdentifier == "passwordCell" {
         if let emailAdress = textFieldCell.getText() {
@@ -242,9 +240,9 @@ class AccountSetupController: UITableViewController {
       }
     }
 
-		if tappedCell.accessibilityIdentifier == "restoreCell" {
-				self.restoreBackup()
-		}
+    if tappedCell.accessibilityIdentifier == "restoreCell" {
+      restoreBackup()
+    }
   }
 
   private func toggleAdvancedSection(button: UILabel) {
@@ -417,34 +415,34 @@ class AccountSetupController: UITableViewController {
     }
   }
 
-	private func restoreBackup() {
-		logger.info("restoring backup")
-		if MRConfig.configured {
-			return
-		}
-		let documents = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
-		if !documents.isEmpty {
-			logger.info("looking for backup in: \(documents[0])")
+  private func restoreBackup() {
+    logger.info("restoring backup")
+    if MRConfig.configured {
+      return
+    }
+    let documents = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
+    if !documents.isEmpty {
+      logger.info("looking for backup in: \(documents[0])")
 
-			if let file = dc_imex_has_backup(mailboxPointer, documents[0]) {
-				logger.info("restoring backup: \(String(cString: file))")
+      if let file = dc_imex_has_backup(mailboxPointer, documents[0]) {
+        logger.info("restoring backup: \(String(cString: file))")
 
-				hudHandler.showBackupHud("Restoring Backup")
-				dc_imex(mailboxPointer, DC_IMEX_IMPORT_BACKUP, file, nil)
+        hudHandler.showBackupHud("Restoring Backup")
+        dc_imex(mailboxPointer, DC_IMEX_IMPORT_BACKUP, file, nil)
 
-				return
-			}
+        return
+      }
 
-			let alert = UIAlertController(title: "Can not restore", message: "No Backup found", preferredStyle: .alert)
-			alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: { _ in
+      let alert = UIAlertController(title: "Can not restore", message: "No Backup found", preferredStyle: .alert)
+      alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: { _ in
 
-			}))
-			present(alert, animated: true, completion: nil)
-			return
-		}
+      }))
+      present(alert, animated: true, completion: nil)
+      return
+    }
 
-		logger.error("no documents directory found")
-	}
+    logger.error("no documents directory found")
+  }
 
   private func handleLoginSuccess() {
     // used when login hud successfully went trough
@@ -460,7 +458,7 @@ extension AccountSetupController: UITextFieldDelegate {
       // special case: email field should check for potential oAuth
 
       // this will activate passwordTextField if oAuth-Dialogue was canceled
-      self.passwordCell.textField.becomeFirstResponder()
+      passwordCell.textField.becomeFirstResponder()
     }) {
       // all the action is defined in if condition
     } else {
@@ -579,10 +577,10 @@ class AdvancedSectionHeader: UIView {
 
  // TODO: to add Eye-icon -> uncomment -> add to inputField.rightView
  /*
-  lazy var makeVisibleIcon: UIImageView = {
-  let view = UIImageView(image: )
-  return view
-  }()
+   lazy var makeVisibleIcon: UIImageView = {
+   let view = UIImageView(image: )
+   return view
+   }()
   */
  init() {
  super.init(style: .default, reuseIdentifier: nil)

+ 44 - 47
deltachat-ios/ActionCell.swift

@@ -8,54 +8,51 @@
 
 import UIKit
 
-
 // a cell with a centered label in system blue
 
 class ActionCell: UITableViewCell {
-
-	var actionTitle: String? {
-		didSet {
-			actionLabel.text = actionTitle
-		}
-	}
-
-	private lazy var actionLabel:UILabel = {
-		let label = UILabel()
-		label.text = actionTitle
-		label.textColor = UIColor.systemBlue
-		return label
-	}()
-
-	// use this constructor if cell won't be reused
-	init(title: String) {
-		actionTitle = title
-		super.init(style: .default, reuseIdentifier: nil)
-		setupSubviews()
-	}
-
-	override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
-		super.init(style: style, reuseIdentifier: reuseIdentifier)
-		setupSubviews()
-	}
-
-	required init?(coder aDecoder: NSCoder) {
-		fatalError("init(coder:) has not been implemented")
-	}
-
-	override func awakeFromNib() {
-			super.awakeFromNib()
-			// Initialization code
-	}
-
-	override func setSelected(_ selected: Bool, animated: Bool) {
-			// no selection style ...
-	}
-
-	private func setupSubviews() {
-		contentView.addSubview(actionLabel)
-		actionLabel.translatesAutoresizingMaskIntoConstraints = false
-		actionLabel.centerXAnchor.constraint(equalTo: contentView.centerXAnchor, constant: 0).isActive = true
-		actionLabel.centerYAnchor.constraint(equalTo: contentView.centerYAnchor, constant: 0).isActive = true
-	}
-
+  var actionTitle: String? {
+    didSet {
+      actionLabel.text = actionTitle
+    }
+  }
+
+  private lazy var actionLabel: UILabel = {
+    let label = UILabel()
+    label.text = actionTitle
+    label.textColor = UIColor.systemBlue
+    return label
+  }()
+
+  // use this constructor if cell won't be reused
+  init(title: String) {
+    actionTitle = title
+    super.init(style: .default, reuseIdentifier: nil)
+    setupSubviews()
+  }
+
+  override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
+    super.init(style: style, reuseIdentifier: reuseIdentifier)
+    setupSubviews()
+  }
+
+  required init?(coder _: NSCoder) {
+    fatalError("init(coder:) has not been implemented")
+  }
+
+  override func awakeFromNib() {
+    super.awakeFromNib()
+    // Initialization code
+  }
+
+  override func setSelected(_: Bool, animated _: Bool) {
+    // no selection style ...
+  }
+
+  private func setupSubviews() {
+    contentView.addSubview(actionLabel)
+    actionLabel.translatesAutoresizingMaskIntoConstraints = false
+    actionLabel.centerXAnchor.constraint(equalTo: contentView.centerXAnchor, constant: 0).isActive = true
+    actionLabel.centerYAnchor.constraint(equalTo: contentView.centerYAnchor, constant: 0).isActive = true
+  }
 }

+ 3 - 3
deltachat-ios/Colors.swift

@@ -9,7 +9,7 @@
 import UIKit
 
 extension UIColor {
-	static var systemBlue: UIColor {
-		return UIButton(type: .system).tintColor
-	}
+  static var systemBlue: UIColor {
+    return UIButton(type: .system).tintColor
+  }
 }

+ 61 - 78
deltachat-ios/DeviceContactsHandler.swift

@@ -9,89 +9,72 @@
 import Contacts
 import UIKit
 
-// MARK - ContactModel
-
-struct DeviceContact {
-	let displayName: String
-	let emailAddresses: [String]
-}
-
 class DeviceContactsHandler {
+  private let store = CNContactStore()
 
-	private let store = CNContactStore()
-
-
-	private func makeContactString(contacts: [CNContact]) -> String {
-		var contactString:String = ""
-		for contact in contacts {
-			let displayName: String = "\(contact.givenName) \(contact.familyName)"
-			// cnContact can have multiple email addresses -> create contact for each email address
-			for emailAddress in contact.emailAddresses {
-				contactString += "\(displayName)\n\(emailAddress.value)\n"
-			}
-		}
-		return contactString
-	}
-
-	private func getContacts() -> String {
-			let storedContacts = self.fetchContactsWithEmailFromDevice()
-			return makeContactString(contacts: storedContacts)
-	}
-
-
-	private func fetchContactsWithEmailFromDevice() -> [CNContact] {
-		var fetchedContacts: [CNContact] = []
+  private func makeContactString(contacts: [CNContact]) -> String {
+    var contactString: String = ""
+    for contact in contacts {
+      let displayName: String = "\(contact.givenName) \(contact.familyName)"
+      // cnContact can have multiple email addresses -> create contact for each email address
+      for emailAddress in contact.emailAddresses {
+        contactString += "\(displayName)\n\(emailAddress.value)\n"
+      }
+    }
+    return contactString
+  }
 
-		// takes id from userDefaults (system settings)
-		let defaultContainerId = store.defaultContainerIdentifier()
-		let predicates = CNContact.predicateForContactsInContainer(withIdentifier: defaultContainerId)
-		let keys = [CNContactFamilyNameKey, CNContactGivenNameKey, CNContactEmailAddressesKey]
-		let request = CNContactFetchRequest(keysToFetch: keys as [CNKeyDescriptor])
-		request.mutableObjects = true
-		request.unifyResults = true
-		request.sortOrder = .userDefault
-		request.predicate = predicates
+  private func addContactsToCore() {
+    let storedContacts = fetchContactsWithEmailFromDevice()
+    let contactString = makeContactString(contacts: storedContacts)
+    dc_add_address_book(mailboxPointer, contactString)
+  }
 
-		do {
-			try store.enumerateContacts(with: request) {(contact, error) in
-				if !contact.emailAddresses.isEmpty {
-					fetchedContacts.append(contact)
-				}
-			}
-		} catch let error {
-			print(error)
-		}
-		return fetchedContacts
-	}
+  private func fetchContactsWithEmailFromDevice() -> [CNContact] {
+    var fetchedContacts: [CNContact] = []
 
-	private func makeContact(from contact: CNContact) -> DeviceContact {
-		let rawDisplayName: String = "\(contact.givenName) \(contact.familyName)"
-		let displayName = rawDisplayName.trimmingCharacters(in: .whitespacesAndNewlines)
-		let emailAdresses = contact.emailAddresses.map({String($0.value)})
-		return DeviceContact(displayName: displayName, emailAddresses: emailAdresses)
-	}
+    // takes id from userDefaults (system settings)
+    let defaultContainerId = store.defaultContainerIdentifier()
+    let predicates = CNContact.predicateForContactsInContainer(withIdentifier: defaultContainerId)
+    let keys = [CNContactFamilyNameKey, CNContactGivenNameKey, CNContactEmailAddressesKey]
+    let request = CNContactFetchRequest(keysToFetch: keys as [CNKeyDescriptor])
+    request.mutableObjects = true
+    request.unifyResults = true
+    request.sortOrder = .userDefault
+    request.predicate = predicates
 
-	func importDeviceContacts(delegate: DeviceContactsDelegate) {
-		switch CNContactStore.authorizationStatus(for: .contacts) {
-		case .authorized:
-			let contactString = getContacts()
-			delegate.setContacts(contactString: contactString)
-		case .denied:
-			delegate.accessDenied()
-		case .restricted, .notDetermined:
-			store.requestAccess(for: .contacts) {[unowned self] granted, error in
-				if granted {
-					DispatchQueue.main.async {
-						let contactString = self.getContacts()
-						delegate.setContacts(contactString: contactString)
-					}
-				} else {
-					DispatchQueue.main.async {
-						delegate.accessDenied()
-					}
-				}
-			}
-		}
-	}
+    do {
+      try store.enumerateContacts(with: request) { contact, _ in
+        if !contact.emailAddresses.isEmpty {
+          fetchedContacts.append(contact)
+        }
+      }
+    } catch {
+      print(error)
+    }
+    return fetchedContacts
+  }
 
+  public func importDeviceContacts(delegate: DeviceContactsDelegate?) {
+    switch CNContactStore.authorizationStatus(for: .contacts) {
+    case .authorized:
+      addContactsToCore()
+      delegate?.accessGranted()
+    case .denied:
+      delegate?.accessDenied()
+    case .restricted, .notDetermined:
+      store.requestAccess(for: .contacts) { [unowned self] granted, _ in
+        if granted {
+          DispatchQueue.main.async {
+            self.addContactsToCore()
+            delegate?.accessGranted()
+          }
+        } else {
+          DispatchQueue.main.async {
+            delegate?.accessDenied()
+          }
+        }
+      }
+    }
+  }
 }

+ 0 - 2
deltachat-ios/Extensions/Extensions.swift

@@ -14,8 +14,6 @@ extension String {
   }
 }
 
-
-
 extension URL {
   public var queryParameters: [String: String]? {
     guard

+ 36 - 46
deltachat-ios/NewChatViewController.swift

@@ -7,8 +7,8 @@
 //
 
 import ALCameraViewController
-import UIKit
 import Contacts
+import UIKit
 
 protocol ChatDisplayer: class {
   func displayNewChat(contactId: Int)
@@ -22,13 +22,20 @@ class NewChatViewController: UITableViewController {
   var syncObserver: Any?
   var hud: ProgressHud?
 
-	let deviceContactHandler = DeviceContactsHandler()
-	var deviceContactAccessGranted: Bool = false {
-		didSet {
-			tableView.reloadData()
-		}
-	}
+  let deviceContactHandler = DeviceContactsHandler()
+  var deviceContactAccessGranted: Bool = false {
+    didSet {
+      tableView.reloadData()
+    }
+  }
+
+  init() {
+    super.init(style: .grouped)
+  }
 
+  required init?(coder _: NSCoder) {
+    fatalError("init(coder:) has not been implemented")
+  }
 
   override func viewDidLoad() {
     super.viewDidLoad()
@@ -39,13 +46,12 @@ class NewChatViewController: UITableViewController {
     let cancelButton = UIBarButtonItem(barButtonSystemItem: .cancel, target: self, action: #selector(NewChatViewController.cancelButtonPressed))
     navigationItem.rightBarButtonItem = cancelButton
 
-		deviceContactHandler.importDeviceContacts(delegate: self)
+    deviceContactHandler.importDeviceContacts(delegate: self)
   }
 
   override func viewDidAppear(_ animated: Bool) {
     super.viewDidAppear(animated)
 
-
     contactIds = Utils.getContactIds()
     tableView.reloadData()
 
@@ -235,44 +241,28 @@ extension NewChatViewController: QrCodeReaderDelegate {
 }
 
 extension NewChatViewController: DeviceContactsDelegate {
-	func setContacts(contactString: String) {
-		let number = dc_add_address_book(mailboxPointer, contactString)
-		self.deviceContactAccessGranted = true
-		print(number)
-	}
-
-
-	func accessDenied() {
-		self.deviceContactAccessGranted = false
-	}
-
-	func requestAccess() {
-		// ignore for now
-	}
-
-
-
-	private func showSettingsAlert(_ completionHandler: @escaping (_ accessGranted: Bool) -> Void) {
-		let alert = UIAlertController(title: nil, message: "This app requires access to Contacts to proceed. Would you like to open settings and grant permission to contacts?", preferredStyle: .alert)
-		alert.addAction(UIAlertAction(title: "Open Settings", style: .default) { action in
-			completionHandler(false)
-			UIApplication.shared.open(URL(string: UIApplication.openSettingsURLString)!)
-		})
-		alert.addAction(UIAlertAction(title: "Cancel", style: .cancel) { action in
-			completionHandler(false)
-		})
-		present(alert, animated: true)
-	}
+  func accessGranted() {
+    deviceContactAccessGranted = false
+  }
+
+  func accessDenied() {
+    deviceContactAccessGranted = false
+  }
+
+  private func showSettingsAlert(_ completionHandler: @escaping (_ accessGranted: Bool) -> Void) {
+    let alert = UIAlertController(title: nil, message: "This app requires access to Contacts to proceed. Would you like to open settings and grant permission to contacts?", preferredStyle: .alert)
+    alert.addAction(UIAlertAction(title: "Open Settings", style: .default) { _ in
+      completionHandler(false)
+      UIApplication.shared.open(URL(string: UIApplication.openSettingsURLString)!)
+    })
+    alert.addAction(UIAlertAction(title: "Cancel", style: .cancel) { _ in
+      completionHandler(false)
+    })
+    present(alert, animated: true)
+  }
 }
 
 protocol DeviceContactsDelegate {
-	func setContacts(contactString: String)
-	func accessDenied()
-	func requestAccess()
+  func accessGranted()
+  func accessDenied()
 }
-
-/*
-To Chat
-
-
-*/

+ 9 - 13
deltachat-ios/TopViews/ChatListController.swift

@@ -22,8 +22,6 @@ class ChatListController: UIViewController {
 
   var newButton: UIBarButtonItem!
 
-
-
   override func viewWillAppear(_ animated: Bool) {
     super.viewWillAppear(animated)
 
@@ -109,16 +107,16 @@ class ChatListController: UIViewController {
     present(nav, animated: true, completion: nil)
   }
 
-	func getChatList() {
-		guard let chatlistPointer = dc_get_chatlist(mailboxPointer, DC_GCL_NO_SPECIALS, nil, 0) else {
-			fatalError("chatlistPointer was nil")
-		}
-		// ownership of chatlistPointer transferred here to ChatList object
-		chatList = MRChatList(chatListPointer: chatlistPointer)
+  func getChatList() {
+    guard let chatlistPointer = dc_get_chatlist(mailboxPointer, DC_GCL_NO_SPECIALS, nil, 0) else {
+      fatalError("chatlistPointer was nil")
+    }
+    // ownership of chatlistPointer transferred here to ChatList object
+    chatList = MRChatList(chatListPointer: chatlistPointer)
 
-		chatTableDataSource.chatList = chatList
-		chatTable.reloadData()
-	}
+    chatTableDataSource.chatList = chatList
+    chatTable.reloadData()
+  }
 }
 
 extension ChatListController: ChatPresenter {
@@ -197,8 +195,6 @@ class ChatTableDataSource: NSObject, UITableViewDataSource {
     cell.emailLabel.text = result
     return cell
   }
-
-
 }
 
 protocol ChatPresenter: class {

+ 3 - 4
deltachat-ios/TopViews/SettingsController.swift

@@ -234,7 +234,6 @@ internal final class SettingsViewController: QuickTableViewController {
     }
   }
 
-
   private func configure(_: Row) {
     hudHandler.showBackupHud("Configuring account")
     dc_configure(mailboxPointer)
@@ -274,8 +273,8 @@ internal final class SettingsViewController: QuickTableViewController {
   }
 
   private func presentAccountSetup(_: Row) {
-		if let nav = self.navigationController {
-			nav.pushViewController(AccountSetupController(), animated: true)
-		}	
+    if let nav = self.navigationController {
+      nav.pushViewController(AccountSetupController(), animated: true)
+    }
   }
 }