Advertisement
Guest User

Untitled

a guest
Apr 28th, 2017
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Swift 20.17 KB | None | 0 0
  1. import UIKit
  2. import Firebase
  3. import FirebaseStorage
  4. import FirebaseDatabase
  5.  
  6. class NetworkDataManager {
  7.    
  8.     // MARK: - Singleton
  9.     static let instance = NetworkDataManager()
  10.     private init() {}
  11.    
  12.     // MARK: - Private properties
  13.     fileprivate let referance = FIRDatabase.database().reference(fromURL: "https://socialapp-9d146.firebaseio.com/")
  14. }
  15.  
  16. extension NetworkDataManager {
  17.     // MARK: - Fetching data from Firebase
  18.     func fetchUsers(_ completion: @escaping (([User]) -> Void)) {
  19.         referance.child("users").observeSingleEvent(of: .value, with: { snapshot in
  20.             var users = [User]()
  21.             if let data = snapshot.value as? [String: AnyObject] {
  22.                
  23.                 let sessionUserEmail = SessionDataManager.instance.sessionUser?.email
  24.                 let sessionUserKey = Utils.convertToKey(string: sessionUserEmail!)
  25.                
  26.                 for index in 0..<data.count {
  27.                     let currentKey = data.keys.sorted()[index]
  28.                     if currentKey == sessionUserKey { continue }
  29.                    
  30.                     let currentUser = data[currentKey]
  31.                    
  32.                     let id = currentUser?["id"] as! String
  33.                     let imageUrl = URL(string: currentUser?["imageUrl"] as! String)!
  34.                     let firstName = currentUser?["firstName"] as! String
  35.                     let lastName = currentUser?["lastName"] as! String
  36.                     let email = currentUser?["email"] as! String
  37.                     let password = currentUser?["password"] as! String
  38.                    
  39.                     let user = User(id: id, imageUrl: imageUrl, firstName: firstName, lastName: lastName, email: email, password: password, signedOnList: nil, postsID: nil, likedNews: nil)
  40.                    
  41.                     users.append(user)
  42.                 }
  43.             }
  44.             completion(users)
  45.         })
  46.     }
  47.    
  48.     func getUrl(fromImage image: UIImage, withEmail email: String, _ completion: @escaping ((URL?) -> Void)) {
  49.         let key = Utils.convertToKey(string: email)
  50.         var imageUrl: URL?
  51.        
  52.         let storageRef = FIRStorage.storage().reference(forURL: "gs://socialapp-9d146.appspot.com").child("\(key).png")
  53.        
  54.         let group = DispatchGroup()
  55.         group.enter()
  56.         if let uploadData = UIImagePNGRepresentation(image) {
  57.             storageRef.put(uploadData, metadata: nil) { (metadata, error) in
  58.                 if error != nil {
  59.                     print(error as Any)
  60.                     return
  61.                 }
  62.                 imageUrl = metadata?.downloadURL()
  63.                 group.leave()
  64.             }
  65.         }
  66.         group.notify(queue: DispatchQueue.main) {
  67.             completion(imageUrl)
  68.         }
  69.     }
  70. }
  71.  
  72. // MARK: - Session Methods
  73. extension NetworkDataManager {
  74.     func getUserData(withEmail email: String, password: String, _ completion: @escaping ((User?) -> Void)) {
  75.         let key = Utils.convertToKey(string: email)
  76.        
  77.         referance.child("users").observeSingleEvent(of: .value, with: { snapshot in
  78.             var user: User?
  79.             if snapshot.hasChild(key) {
  80.                 if let currentUser = snapshot.childSnapshot(forPath: key).value as? [String: AnyObject] {
  81.                     let userPassword = currentUser["password"] as? String
  82.                    
  83.                     if password != userPassword {
  84.                         completion(nil)
  85.                         return
  86.                     }
  87.                    
  88.                     guard let id = currentUser["id"] as? String,
  89.                         let imageUrlText = currentUser["imageUrl"] as? String,
  90.                         let imageUrl = URL(string: imageUrlText),
  91.                        
  92.                         let firstName = currentUser["firstName"] as? String,
  93.                         let lastName = currentUser["lastName"] as? String,
  94.                         let email = currentUser["email"] as? String else {
  95.                             print("Invalid user data")
  96.                             return
  97.                     }
  98.                    
  99.                     user = User(id: id, imageUrl: imageUrl, firstName: firstName, lastName: lastName, email: email, password: password, signedOnList: nil, postsID: nil, likedNews: nil)
  100.                 }
  101.             }
  102.             completion(user)
  103.         })
  104.     }
  105.    
  106.     func signUp(user: User, _ completion: @escaping ((User?) -> Void)) {
  107.         let key = Utils.convertToKey(string: user.email!)
  108.         referance.child("users").observeSingleEvent(of: .value, with: { [weak self] snapshot in
  109.             if snapshot.hasChild(key) {
  110.                 completion(nil)
  111.                 return
  112.             }
  113.            
  114.             self?.referance.child("users/\(key)").setValue(["id": user.id!,
  115.                                                             "imageUrl": "\(user.imageUrl!)",
  116.                 "firstName": user.firstName!,
  117.                 "lastName": user.lastName!,
  118.                 "email": user.email!,
  119.                 "password": user.password!])
  120.             completion(user)
  121.         })
  122.        
  123.        
  124.     }
  125.    
  126.     func getSignedOnList(forUser user: User, _ completion: @escaping (([User]?) -> Void)) {
  127.         guard let email = user.email else { return }
  128.         let key = Utils.convertToKey(string: email)
  129.         let signedOnUsersIdReferance = referance.child("users/\(key)/signedOnList")
  130.        
  131.         signedOnUsersIdReferance.observeSingleEvent(of: .value, with: { [weak self] snapshot in
  132.             var userList = [User]()
  133.            
  134.             if let dictionary = snapshot.value as? [String: AnyObject] {
  135.                 for index in dictionary.keys.sorted() {
  136.                     if let currentUserKey = dictionary[index] as? String {
  137.                         let currentUserRef = self?.referance.child("users/\(currentUserKey)")
  138.                        
  139.                         let group = DispatchGroup()
  140.                         group.enter()
  141.                        
  142.                         currentUserRef?.observeSingleEvent(of: .value, with: { userSnapshot in
  143.                            
  144.                             if let currentUserDictionary = userSnapshot.value as? [String: AnyObject] {
  145.                                 let id = currentUserDictionary["id"] as? String
  146.                                 let email = currentUserDictionary["email"] as? String
  147.                                 let imageUrlStrign = currentUserDictionary["imageUrl"] as! String
  148.                                 let imageUrl = URL(string: imageUrlStrign)
  149.                                
  150.                                 let firstName = currentUserDictionary["firstName"] as? String
  151.                                 let lastName = currentUserDictionary["lastName"] as? String
  152.                                 let password = currentUserDictionary["password"] as? String
  153.                                
  154.                                 let user = User(id: id, imageUrl: imageUrl, firstName: firstName, lastName: lastName, email: email, password: password, signedOnList: nil, postsID: nil, likedNews: nil)
  155.                                 userList.append(user)
  156.                                
  157.                                 group.leave()
  158.                             }
  159.                         })
  160.                         group.notify(queue: DispatchQueue.main, execute: {
  161.                             completion(userList)
  162.                         })
  163.                     }
  164.                 }
  165.             }
  166.         })
  167.     }
  168.    
  169.     func getPostList(forUser user: User, _ completion: @escaping ((_ userNews: [Post]?,_ followedUsersNews: [Post]?) -> Void)) {
  170.         guard let sessionUserEmail = user.email else { return }
  171.         let sessionUserKey = Utils.convertToKey(string: sessionUserEmail)
  172.        
  173.         var userPostsList = [Post]()
  174.         let sessionUserPostsRef = referance.child("posts/\(sessionUserKey)")
  175.         sessionUserPostsRef.observeSingleEvent(of: .value, with: { snapshot in
  176.             if let dictionary = snapshot.value as? [String: AnyObject] {
  177.                 for index in 0..<dictionary.count {
  178.                     let currentPostIndex = dictionary.keys.sorted()[index]
  179.                     let currentPost = dictionary[currentPostIndex]
  180.                    
  181.                     guard let id =  currentPost?["id"] as? String,
  182.                         let text = currentPost?["text"] as? String else {
  183.                             print("Invalid post data")
  184.                             return
  185.                     }
  186.                    
  187.                     let post = Post(id: id, text: text)
  188.                    
  189.                     userPostsList.append(post)
  190.                 }
  191.             }
  192.         })
  193.        
  194.         let signedOnUsersIdsRef = referance.child("users/\(sessionUserKey)/signedOnList")
  195.         var followedPostsList = [Post]()
  196.         signedOnUsersIdsRef.observeSingleEvent(of: .value, with: { snapshot in
  197.            
  198.             if let dictionary = snapshot.value as? [String: AnyObject] {
  199.                 for index in 0..<dictionary.count {
  200.                     let currentUserIndex = dictionary.keys.sorted()[index]
  201.                     if let currentUserKey = dictionary[currentUserIndex] {
  202.                         let postsReferance = FIRDatabase.database().reference().child("posts/\(currentUserKey)")
  203.                        
  204.                         let group = DispatchGroup()
  205.                         group.enter()
  206.                        
  207.                         postsReferance.observeSingleEvent(of: .value, with: { postSnapshot in
  208.                             if let postDictionary = postSnapshot.value as? [String: AnyObject] {
  209.                                 for postIndex in postDictionary.keys.sorted() {
  210.                                     let currentPost = postDictionary[postIndex]
  211.                                     guard let id = currentPost?["id"] as? String,
  212.                                         let text = currentPost?["text"] as? String else {
  213.                                             print("Invalid post data")
  214.                                             return
  215.                                     }
  216.                                     let post = Post(id: id, text: text)
  217.                                     followedPostsList.append(post)
  218.                                 }
  219.                                 group.leave()
  220.                             }
  221.                         })
  222.                         group.notify(queue: DispatchQueue.main, execute: {
  223.                             completion(userPostsList, followedPostsList)
  224.                         })
  225.                     }
  226.                 }
  227.             }
  228.         })
  229.     }
  230.    
  231.     func getLikedPostList(forUser user: User, _ completion: @escaping (([Post]?) -> Void)) {
  232.         guard let email = user.email else { return }
  233.         let key = Utils.convertToKey(string: email)
  234.         let likedPostsRef = referance.child("users/\(key)/likedPosts")
  235.        
  236.         likedPostsRef.observeSingleEvent(of: .value, with: { [weak self] likedPostsSnapshot in
  237.             var likedPosts = [Post]()
  238.            
  239.             if let likedPostsDictionary = likedPostsSnapshot.value as? [String: AnyObject] {
  240.                 let likedPostsKeys = likedPostsDictionary.keys.sorted()
  241.                 for currentPostKey in likedPostsKeys {
  242.                     let currentPostId = likedPostsDictionary[currentPostKey] as? String
  243.                    
  244.                     let postsRef = self?.referance.child("posts")
  245.                    
  246.                     let group = DispatchGroup()
  247.                     group.enter()
  248.                    
  249.                     postsRef?.observeSingleEvent(of: .value, with: { postSnapshot in
  250.                         if let postDictionary = postSnapshot.value as? [String: AnyObject] {
  251.                             let postsKeys = postDictionary.keys.sorted()
  252.                             for currentPostKey in postsKeys {
  253.                                 let currentPostList = postDictionary[currentPostKey] as? [String: AnyObject]
  254.                                 if (currentPostList?.keys.contains(currentPostId!))! {
  255.                                     let currentPost = currentPostList?[currentPostId!] as? [String: AnyObject]
  256.                                    
  257.                                     guard let id = currentPost?["id"] as? String,
  258.                                         let text = currentPost?["text"] as? String else { return }
  259.                                     let post = Post(id: id, text: text)
  260.                                    
  261.                                     likedPosts.append(post)
  262.                                     group.leave()
  263.                                 }
  264.                             }
  265.                         }
  266.                         group.notify(queue: .main, execute: {
  267.                             completion(likedPosts)
  268.                         })
  269.                     })
  270.                 }
  271.             }
  272.         })
  273.     }
  274.    
  275.     // MARK: - Follow methods
  276.     func follow(user: User) {
  277.         guard let sessionUser = SessionDataManager.instance.sessionUser,
  278.             let sessionUserEmail = sessionUser.email,
  279.             let followedUserEmail = user.email else { return }
  280.        
  281.         let currentUserkey = Utils.convertToKey(string: sessionUserEmail)
  282.         let followedUserKey = Utils.convertToKey(string: followedUserEmail)
  283.        
  284.         let signedOnListRef = FIRDatabase.database().reference().child("users/\(currentUserkey)/signedOnList")
  285.        
  286.         signedOnListRef.observeSingleEvent(of: .value, with: { snapshot in
  287.             if let dictionary = snapshot.value as? [String: AnyObject] {
  288.                 let lastUserId = dictionary.keys.sorted()[dictionary.count - 1]
  289.                
  290.                 let substringStartIndex = lastUserId.index(lastUserId.startIndex, offsetBy: +2)
  291.                 guard let lastUserNumber = Int(lastUserId.substring(from: substringStartIndex)) else { return }
  292.                
  293.                 let userIndex = lastUserNumber + 1
  294.                 signedOnListRef.child("id\(userIndex)").setValue(followedUserKey)
  295.             } else {
  296.                 signedOnListRef.child("id0").setValue(followedUserKey)
  297.             }
  298.            
  299.         })
  300.        
  301.     }
  302.    
  303.     func unFollow(user: User) {
  304.         guard let sessionUser = SessionDataManager.instance.sessionUser,
  305.             let sessionUserEmail = sessionUser.email,
  306.             let followedUserEmail = user.email else { return }
  307.        
  308.         let key = Utils.convertToKey(string: sessionUserEmail)
  309.         let followedUserKey = Utils.convertToKey(string: followedUserEmail)
  310.        
  311.         let signedOnIdList = FIRDatabase.database().reference().child("users/\(key)/signedOnList")
  312.        
  313.         signedOnIdList.observeSingleEvent(of: .value, with: { snapshot in
  314.             if let dictionary = snapshot.value as? [String: AnyObject] {
  315.                 for index in 0..<dictionary.count {
  316.                     let currentKey = dictionary.keys.sorted()[index]
  317.                     let currentUserKey = dictionary[currentKey] as? String
  318.                    
  319.                     if currentUserKey == followedUserKey {
  320.                         signedOnIdList.child(currentKey).removeValue()
  321.                     }
  322.                 }
  323.             }
  324.         })
  325.     }
  326. }
  327.  
  328. // MARK: - UserInteraction Methods
  329. extension NetworkDataManager: UserInteraction {
  330.     func edit(user: User) {
  331.        
  332.         let key = Utils.convertToKey(string: user.email!)
  333.         let currentUserRef = referance.child("users/\(key)")
  334.        
  335.         currentUserRef.child("imageUrl").setValue("\(user.imageUrl!)")
  336.         currentUserRef.child("firstName").setValue(user.firstName!)
  337.         currentUserRef.child("lastName").setValue(user.lastName!)
  338.     }
  339.    
  340.     func delete(user: User) {
  341.        
  342.     }
  343. }
  344.  
  345. // MARK: - PostInteraction Methods
  346. extension NetworkDataManager: PostInteraction {
  347.     func add(post: Post) {
  348.         guard let user = SessionDataManager.instance.sessionUser, let email = user.email else { return }
  349.         let key = Utils.convertToKey(string: email)
  350.        
  351.         let postsRef = FIRDatabase.database().reference().child("posts/\(key)/\(post.id)")
  352.         postsRef.setValue(["id": post.id,
  353.                            "text": post.text])
  354.        
  355.         let idPostsRef = FIRDatabase.database().reference().child("users/\(key)/postsID")
  356.         idPostsRef.observeSingleEvent(of: .value, with: { snapshot in
  357.             if let dictionary = snapshot.value as? [String: AnyObject] {
  358.                 let lastPostId = dictionary.keys.sorted()[dictionary.count - 1]
  359.                
  360.                 let substringStartIndex = lastPostId.index(lastPostId.startIndex, offsetBy: +2)
  361.                 guard let lastPostNumber = Int(lastPostId.substring(from: substringStartIndex)) else { return }
  362.                
  363.                 let index = lastPostNumber + 1
  364.                 idPostsRef.child("id\(index)").setValue(post.id)
  365.             } else {
  366.                 idPostsRef.child("id0").setValue(post.id)
  367.             }
  368.            
  369.         })
  370.     }
  371.    
  372.     func edit(post: Post) {
  373.         guard let user = SessionDataManager.instance.sessionUser, let email = user.email else { return }
  374.         let key = Utils.convertToKey(string: email)
  375.        
  376.         let currentPostRef = referance.child("posts/\(key)/\(post.id)")
  377.         currentPostRef.child("text").setValue(post.text)
  378.     }
  379.    
  380.     func delete(post: Post) {
  381.         guard let user = SessionDataManager.instance.sessionUser, let email = user.email else { return }
  382.         let key = Utils.convertToKey(string: email)
  383.        
  384.         referance.child("posts/\(key)/\(post.id)").removeValue()
  385.        
  386.         let idPostsRef = referance.child("users/\(key)/postsID")
  387.         idPostsRef.observeSingleEvent(of: .value, with: { snapshot in
  388.             if let dictionary = snapshot.value as? [String: AnyObject] {
  389.                 for index in 0..<dictionary.count {
  390.                     let currentKey = dictionary.keys.sorted()[index]
  391.                     let currentPostId = dictionary[currentKey] as? String
  392.                    
  393.                     if currentPostId == post.id {
  394.                         idPostsRef.child(currentKey).removeValue()
  395.                     }
  396.                 }
  397.             }
  398.         })
  399.     }
  400.    
  401.     func like(post: Post) {
  402.         guard let sessionUser = SessionDataManager.instance.sessionUser, let email = sessionUser.email else { return }
  403.         let key = Utils.convertToKey(string: email)
  404.        
  405.         let likedPostsRef = referance.child("users/\(key)/likedPosts")
  406.        
  407.         likedPostsRef.observeSingleEvent(of: .value, with: { snapshot in
  408.             if let dictionary = snapshot.value as? [String: AnyObject] {
  409.                 let lastPostId = dictionary.keys.sorted()[dictionary.count - 1]
  410.                
  411.                 let substringStartIndex = lastPostId.index(lastPostId.startIndex, offsetBy: +2)
  412.                 guard let lastPostNumber = Int(lastPostId.substring(from: substringStartIndex)) else { return }
  413.                
  414.                 let index = lastPostNumber + 1
  415.                 likedPostsRef.child("id\(index)").setValue(post.id)
  416.             } else {
  417.                 likedPostsRef.child("id0").setValue(post.id)
  418.             }
  419.            
  420.         })
  421.     }
  422.    
  423.     func dislike(post: Post) {
  424.         guard let sessionUser = SessionDataManager.instance.sessionUser, let email = sessionUser.email else { return }
  425.         let key = Utils.convertToKey(string: email)
  426.        
  427.         let likedPostsRef = referance.child("users/\(key)/likedPosts")
  428.         likedPostsRef.observeSingleEvent(of: .value, with: { snapshot in
  429.             if let dictionary = snapshot.value as? [String: AnyObject] {
  430.                 for index in 0..<dictionary.count {
  431.                     let currentKey = dictionary.keys.sorted()[index]
  432.                     let currentPostId = dictionary[currentKey] as? String
  433.                    
  434.                     if currentPostId == post.id {
  435.                         likedPostsRef.child(currentKey).removeValue()
  436.                     }
  437.                 }
  438.             }
  439.         })
  440.     }
  441. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement