Prechádzať zdrojové kódy

add email checking regex / simplify credentials screen

Jonas Reinsch 7 rokov pred
rodič
commit
734c6c0ec7

+ 19 - 11
deltachat-ios/AppCoordinator.swift

@@ -13,16 +13,30 @@ protocol Coordinator {
 }
 
 class AppCoordinator: Coordinator {
+    let tabBarController = UITabBarController()
+
     func setupViewControllers(window: UIWindow) {
-        let credentialsController = CredentialsController()
-        let credentialsNav = UINavigationController(rootViewController: credentialsController)
-        
-        window.rootViewController = credentialsNav
+        window.rootViewController = tabBarController
         window.makeKeyAndVisible()
         window.backgroundColor = UIColor.white
+        
+        let ud = UserDefaults.standard
+        if ud.bool(forKey: Constants.Keys.deltachatUserProvidedCredentialsKey) {
+            initCore(withCredentials: false)
+            setupInnerViewControllers()
+        } else {
+//            let email = "alice@librechat.net"
+//            let password = "foobar"
+//            initCore(email: email, password: password)
+            
+            let credentialsController = CredentialsController()
+            let credentialsNav = UINavigationController(rootViewController: credentialsController)
+
+            tabBarController.present(credentialsNav, animated: false, completion: nil)
+        }
     }
     
-    func setupViewControllersReal(window: UIWindow) {
+    func setupInnerViewControllers() {
 
         let contactViewController = ContactViewController(coordinator: self)
         let contactNavigationController = UINavigationController(rootViewController: contactViewController)
@@ -47,16 +61,10 @@ class AppCoordinator: Coordinator {
         chatNavigationController.tabBarItem = chatTabbarItem
         settingsNavigationController.tabBarItem = settingsTabbarItem
         
-        let tabBarController = UITabBarController()
-        
         tabBarController.viewControllers = [
 //            contactNavigationController,
             chatNavigationController,
             settingsNavigationController,
         ]
-        
-        window.rootViewController = tabBarController
-        window.makeKeyAndVisible()
-        window.backgroundColor = UIColor.white
     }
 }

+ 47 - 34
deltachat-ios/AppDelegate.swift

@@ -15,7 +15,7 @@ var mailboxPointer:UnsafeMutablePointer<mrmailbox_t>!
 func sendTestMessage(name n: String, email: String, text: String) {
     let contactId = mrmailbox_create_contact(mailboxPointer, n, email)
     let chatId = mrmailbox_create_chat_by_contact_id(mailboxPointer, contactId)
-    mrmailbox_send_text_msg(mailboxPointer, chatId, text)
+//    mrmailbox_send_text_msg(mailboxPointer, chatId, text)
 }
 
 @_silgen_name("callbackSwift")
@@ -80,6 +80,7 @@ public func callbackSwift(event: CInt, data1: CUnsignedLong, data2: CUnsignedLon
 
 @UIApplicationMain
 class AppDelegate: UIResponder, UIApplicationDelegate {
+    static let appCoordinator = AppCoordinator()
     var window: UIWindow?
 
     func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
@@ -89,41 +90,53 @@ class AppDelegate: UIResponder, UIApplicationDelegate {
         guard let window = window else {
             fatalError("window was nil in app delegate")
         }
-        let appCoordinator = AppCoordinator()
-        appCoordinator.setupViewControllers(window: window)
-        
-        //       - second param remains nil (user data for more than one mailbox)
-        mailboxPointer = mrmailbox_new(callback_ios, nil, "iOS")
-        guard mailboxPointer != nil else {
-            fatalError("Error: mrmailbox_new returned nil")
-        }
-        
-        let paths = NSSearchPathForDirectoriesInDomains(.libraryDirectory, .userDomainMask, true)
-        let documentsPath = paths[0]
-        let dbfile = documentsPath + "/messenger.db"
-        print(dbfile)
-        
-        let r = mrmailbox_open(mailboxPointer, dbfile, nil)
-        
-        mrmailbox_set_config(mailboxPointer, "addr", "alice@librechat.net")
-        mrmailbox_set_config(mailboxPointer, "mail_pw", "foobar")
-        
-        mrmailbox_configure_and_connect(mailboxPointer)
-        
-        let nc = NotificationCenter.default
-        nc.addObserver(forName:Notification.Name(rawValue:"MrEventMsgsChanged"),
-                       object:nil, queue:nil) {
-                        notification in
-                        print("----------- MrEventMsgsChanged notification received --------")
+        AppDelegate.appCoordinator.setupViewControllers(window: window)
+
+        return true
+    }
+}
+
+
+func initCore(withCredentials: Bool, email: String = "", password: String = "") {
+    let paths = NSSearchPathForDirectoriesInDomains(.libraryDirectory, .userDomainMask, true)
+    let documentsPath = paths[0]
+    let dbfile = documentsPath + "/messenger.db"
+    print(dbfile)
+    
+    //       - second param remains nil (user data for more than one mailbox)
+    mailboxPointer = mrmailbox_new(callback_ios, nil, "iOS")
+    guard mailboxPointer != nil else {
+        fatalError("Error: mrmailbox_new returned nil")
+    }
+    
+    let _ = mrmailbox_open(mailboxPointer, dbfile, nil)
+    
+    if withCredentials {
+        if !(email.contains("@") && (email.count >= 3)) {
+            fatalError("initCore called with withCredentials flag set to true, but email not valid")
         }
-        
-        nc.addObserver(forName:Notification.Name(rawValue:"MrEventIncomingMsg"),
-                       object:nil, queue:nil) {
-                        notification in
-                        print("----------- MrEventIncomingMsg received --------")
-                        AudioServicesPlaySystemSound(UInt32(kSystemSoundID_Vibrate))
+        if password.isEmpty {
+            fatalError("initCore called with withCredentials flag set to true, password is empty")
         }
+        mrmailbox_set_config(mailboxPointer, "addr", email)
+        mrmailbox_set_config(mailboxPointer, "mail_pw", password)
+//            -        mrmailbox_set_config(mailboxPointer, "addr", "alice@librechat.net")
+//            -        mrmailbox_set_config(mailboxPointer, "mail_pw", "foobar")
+        UserDefaults.standard.set(true, forKey: Constants.Keys.deltachatUserProvidedCredentialsKey)
+        UserDefaults.standard.synchronize()
+    }
+    
+    mrmailbox_configure_and_connect(mailboxPointer)
+    
+    addVibrationOnIncomingMessage()
+}
 
-        return true
+func addVibrationOnIncomingMessage() {
+    let nc = NotificationCenter.default
+    nc.addObserver(forName:Notification.Name(rawValue:"MrEventIncomingMsg"),
+                   object:nil, queue:nil) {
+                    notification in
+                    print("----------- MrEventIncomingMsg received --------")
+                    AudioServicesPlaySystemSound(UInt32(kSystemSoundID_Vibrate))
     }
 }

+ 6 - 0
deltachat-ios/Constants.swift

@@ -12,4 +12,10 @@ struct Constants {
      struct Color {
         static let bubble = UIColor(netHex: 0xefffde)
     }
+    
+    struct Keys {
+        static let deltachatUserProvidedCredentialsKey = "__DELTACHAT_USER_PROVIDED_CREDENTIALS_KEY__"
+        static let deltachatImapEmailKey = "__DELTACHAT_IMAP_EMAIL_KEY__"
+        static let deltachatImapPasswordKey = "__DELTACHAT_IMAP_PASSWORD_KEY__"
+    }
 }

+ 37 - 91
deltachat-ios/CredentialsController.swift

@@ -8,47 +8,33 @@
 
 import UIKit
 
-class TextFieldCell:UITableViewCell {
-    let height: CGFloat = 80
-    let margin: CGFloat = 15
+class TextFieldCell2:UITableViewCell {
     let textField = UITextField()
-    let label = UILabel()
     
-    init(placeholder: String) {
-        super.init(style: .default, reuseIdentifier: nil)
-
-        layout()
-        
-        label.text = "\(placeholder):"
-        textField.placeholder = placeholder
-    }
-    
-    func layout() {
-        label.translatesAutoresizingMaskIntoConstraints = false
-        contentView.addSubview(label)
+    init(description: String, placeholder: String) {
+        super.init(style: .value1, reuseIdentifier: nil)
         
-        textField.translatesAutoresizingMaskIntoConstraints = false
+        textLabel?.text = "\(description):"
         contentView.addSubview(textField)
         
-        contentView.heightAnchor.constraint(equalToConstant: height).isActive = true
-        
-        label.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: margin).isActive = true
-        label.widthAnchor.constraint(equalTo: contentView.widthAnchor, multiplier: 0.3).isActive = true
-        label.topAnchor.constraint(equalTo: contentView.topAnchor, constant: margin).isActive = true
-        label.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -margin).isActive = true
+        textField.translatesAutoresizingMaskIntoConstraints = false
+        textField.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -15).isActive = true
+        textField.centerYAnchor.constraint(equalTo: contentView.centerYAnchor).isActive = true
+        textField.textAlignment = .right
+
+        textField.placeholder = placeholder
         
-        textField.widthAnchor.constraint(equalTo: contentView.widthAnchor, multiplier: 0.6).isActive = true
-        textField.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -margin).isActive = true
-        textField.topAnchor.constraint(equalTo: contentView.topAnchor, constant: margin).isActive = true
-        textField.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -margin).isActive = true
+        selectionStyle = .none
     }
-
+    
+    
+    
     required init?(coder aDecoder: NSCoder) {
         fatalError("init(coder:) has not been implemented")
     }
     
-    static func makeEmailCell() -> TextFieldCell {
-        let emailCell = TextFieldCell(placeholder: "Email")
+    static func makeEmailCell() -> TextFieldCell2 {
+        let emailCell = TextFieldCell2(description: "Email", placeholder: "you@example.com")
         
         emailCell.textField.textContentType = UITextContentType.emailAddress
         emailCell.textField.keyboardType = .emailAddress
@@ -59,8 +45,8 @@ class TextFieldCell:UITableViewCell {
         return emailCell
     }
     
-    static func makePasswordCell() -> TextFieldCell {
-        let passwordCell = TextFieldCell(placeholder: "Password")
+    static func makePasswordCell() -> TextFieldCell2 {
+        let passwordCell = TextFieldCell2(description: "Password", placeholder: "your IMAP password")
         
         passwordCell.textField.textContentType = UITextContentType.password
         passwordCell.textField.isSecureTextEntry = true
@@ -69,56 +55,17 @@ class TextFieldCell:UITableViewCell {
     }
 }
 
-
-class ButtonCell:UITableViewCell {
-    let height: CGFloat = 80
-    let margin: CGFloat = 15
-    let button = UIButton(type: UIButtonType.system)
-    
-    func enable() {
-        button.isEnabled = true
-    }
-    
-    func disable() {
-        button.isEnabled = false
-    }
-    
-    init() {
-        super.init(style: .default, reuseIdentifier: nil)
-
-        button.setTitle("Save Account", for: .normal)
-        
-        layout()
-    }
-    
-    required init?(coder aDecoder: NSCoder) {
-        fatalError("init(coder:) has not been implemented")
-    }
-
-    func layout() {
-        contentView.heightAnchor.constraint(equalToConstant: height).isActive = true
-        
-        button.translatesAutoresizingMaskIntoConstraints = false
-        contentView.addSubview(button)
-        
-        button.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: margin).isActive = true
-        button.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -margin).isActive = true
-        button.topAnchor.constraint(equalTo: contentView.topAnchor, constant: margin).isActive = true
-        button.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -margin).isActive = true
-    }
-}
-
 class CredentialsController: UITableViewController {
-    let emailCell = TextFieldCell.makeEmailCell()
-    let passwordCell = TextFieldCell.makePasswordCell()
-    let buttonCell = ButtonCell()
+    let emailCell = TextFieldCell2.makeEmailCell()
+    let passwordCell = TextFieldCell2.makePasswordCell()
+    var doneButton:UIBarButtonItem?
     
     var model:(email:String, password:String) = ("", "") {
         didSet {
-            if (model.email.contains("@") && model.email.count >= 3 && !model.password.isEmpty) {
-                buttonCell.enable()
+            if (Utils.isValid(model.email) && !model.password.isEmpty) {
+                doneButton?.isEnabled = true
             } else {
-                buttonCell.disable()
+                doneButton?.isEnabled = false
             }
         }
     }
@@ -126,15 +73,18 @@ class CredentialsController: UITableViewController {
     let cells:[UITableViewCell]
     
     init() {
-        cells = [emailCell, passwordCell, buttonCell]
 
-        super.init(style: .plain)
+
+        
+        cells = [emailCell, passwordCell]
+
+        super.init(style: .grouped)
+        doneButton = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(CredentialsController.saveAccountButtonPressed))
+        doneButton?.isEnabled = false
+        navigationItem.rightBarButtonItem = doneButton
         
         emailCell.textField.addTarget(self, action: #selector(CredentialsController.emailTextChanged), for: UIControlEvents.editingChanged)
         passwordCell.textField.addTarget(self, action: #selector(CredentialsController.passwordTextChanged), for: UIControlEvents.editingChanged)
-        buttonCell.button.addTarget(self, action: #selector(CredentialsController.saveAccountButtonPressed), for: .touchUpInside)
-        
-        buttonCell.disable()
     }
     
     @objc func emailTextChanged() {
@@ -150,7 +100,10 @@ class CredentialsController: UITableViewController {
     }
     
     @objc func saveAccountButtonPressed() {
-        print("model: \(model)")
+        dismiss(animated: true) {
+            initCore(withCredentials: true, email: self.model.email, password: self.model.password)
+            AppDelegate.appCoordinator.setupInnerViewControllers()
+        }
     }
     
     required init?(coder aDecoder: NSCoder) {
@@ -160,13 +113,7 @@ class CredentialsController: UITableViewController {
     override func viewDidLoad() {
         super.viewDidLoad()
         
-        title = "Email Account"
-        
-        // auto-size table view cells
-        tableView.rowHeight = UITableViewAutomaticDimension
-        tableView.estimatedRowHeight = 80
-        
-        tableView.separatorStyle = .none
+        title = "Account"
     }
     
     override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
@@ -178,7 +125,6 @@ class CredentialsController: UITableViewController {
         
         return cells[row]
     }
-    
 
     override func didReceiveMemoryWarning() {
         super.didReceiveMemoryWarning()

+ 7 - 0
deltachat-ios/Utils.swift

@@ -19,6 +19,13 @@ struct Utils {
         carray_free(inputArray)
         return acc
     }
+    
+    static func isValid(_ email: String) -> Bool {
+        let emailRegEx = "(?:[a-z0-9!#$%\\&'*+/=?\\^_`{|}~-]+(?:\\.[a-z0-9!#$%\\&'*+/=?\\^_`{|}"+"~-]+)*|\"(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21\\x23-\\x5b\\x5d-\\"+"x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])*\")@(?:(?:[a-z0-9](?:[a-"+"z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\\[(?:(?:25[0-5"+"]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-"+"9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21"+"-\\x5a\\x53-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])+)\\])"
+        
+        let emailTest = NSPredicate(format:"SELF MATCHES[c] %@", emailRegEx)
+        return emailTest.evaluate(with: email)
+    }
 }