http://git-wip-us.apache.org/repos/asf/usergrid/blob/7442c881/sdks/swift/Samples/Push/Pods/UsergridSDK/sdks/swift/Source/UsergridAsset.swift ---------------------------------------------------------------------- diff --git a/sdks/swift/Samples/Push/Pods/UsergridSDK/sdks/swift/Source/UsergridAsset.swift b/sdks/swift/Samples/Push/Pods/UsergridSDK/sdks/swift/Source/UsergridAsset.swift new file mode 100644 index 0000000..3f74796 --- /dev/null +++ b/sdks/swift/Samples/Push/Pods/UsergridSDK/sdks/swift/Source/UsergridAsset.swift @@ -0,0 +1,198 @@ +// +// UsergridAsset.swift +// UsergridSDK +// +// Created by Robert Walsh on 9/21/15. +// +/* + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. The ASF licenses this file to You + * under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. For additional information regarding + * copyright in this work, please see the NOTICE file in the top level + * directory of this distribution. + * + */ + +import Foundation + +#if os(iOS) || os(watchOS) || os(tvOS) +import UIKit +import MobileCoreServices +#endif + +/// The progress block used in `UsergridAsset` are being uploaded or downloaded. +public typealias UsergridAssetRequestProgress = (bytesFinished:Int64, bytesExpected: Int64) -> Void + +/// The completion block used in `UsergridAsset` are finished uploading. +public typealias UsergridAssetUploadCompletion = (response:UsergridResponse,asset:UsergridAsset?, error: String?) -> Void + +/// The completion block used in `UsergridAsset` are finished downloading. +public typealias UsergridAssetDownloadCompletion = (asset:UsergridAsset?, error: String?) -> Void + +/** +As Usergrid supports storing binary assets, the SDKs are designed to make uploading assets easier and more robust. Attaching, uploading, and downloading assets is handled by the `UsergridEntity` class. + +Unless defined, whenever possible, the content-type will be inferred from the data provided, and the attached file (if not already a byte-array representation) will be binary-encoded. +*/ +public class UsergridAsset: NSObject, NSCoding { + + private static let DEFAULT_FILE_NAME = "file" + + // MARK: - Instance Properties - + + /// The filename to be used in the multipart/form-data request. + public let filename: String + + /// Binary representation of the asset's data. + public let data: NSData + + /// A representation of the folder location the asset was loaded from, if it was provided in the initialization. + public let originalLocation: String? + + /// The Content-type of the asset to be used when defining content-type inside the multipart/form-data request. + public var contentType: String + + /// The content length of the assets data. + public var contentLength: Int { return self.data.length } + + // MARK: - Initialization - + + /** + Designated initializer for `UsergridAsset` objects. + + - parameter fileName: The file name associated with the file data. + - parameter data: The data of the file. + - parameter originalLocation: An optional original location of the file. + - parameter contentType: The content type of the file. + + - returns: A new instance of `UsergridAsset`. + */ + public init(filename:String? = UsergridAsset.DEFAULT_FILE_NAME, data:NSData, originalLocation:String? = nil, contentType:String) { + self.filename = filename ?? UsergridAsset.DEFAULT_FILE_NAME + self.data = data + self.originalLocation = originalLocation + self.contentType = contentType + } + + #if os(iOS) || os(watchOS) || os(tvOS) + /** + Convenience initializer for `UsergridAsset` objects dealing with image data. + + - parameter fileName: The file name associated with the file data. + - parameter image: The `UIImage` object to upload. + - parameter imageContentType: The content type of the `UIImage` + + - returns: A new instance of `UsergridAsset` if the data can be gathered from the passed in `UIImage`, otherwise nil. + */ + public convenience init?(fileName:String? = UsergridAsset.DEFAULT_FILE_NAME, image:UIImage, imageContentType:UsergridImageContentType = .Png) { + var imageData: NSData? + switch(imageContentType) { + case .Png : + imageData = UIImagePNGRepresentation(image) + case .Jpeg : + imageData = UIImageJPEGRepresentation(image, 1.0) + } + if let assetData = imageData { + self.init(filename:fileName,data:assetData,contentType:imageContentType.stringValue) + } else { + self.init(filename:"",data:NSData(),contentType:"") + return nil + } + } + #endif + + /** + Convenience initializer for `UsergridAsset` objects dealing directly with files on disk. + + - parameter fileName: The file name associated with the file data. + - parameter fileURL: The `NSURL` object associated with the file. + - parameter contentType: The content type of the `UIImage`. If not specified it will try to figure out the type and if it can't initialization will fail. + + - returns: A new instance of `UsergridAsset` if the data can be gathered from the passed in `NSURL`, otherwise nil. + */ + public convenience init?(fileName:String? = UsergridAsset.DEFAULT_FILE_NAME, fileURL:NSURL, contentType:String? = nil) { + if fileURL.isFileReferenceURL(), let assetData = NSData(contentsOfURL: fileURL) { + var fileNameToUse = fileName + if fileNameToUse != UsergridAsset.DEFAULT_FILE_NAME, let inferredFileName = fileURL.lastPathComponent { + fileNameToUse = inferredFileName + } + if let fileContentType = contentType ?? UsergridAsset.MIMEType(fileURL) { + self.init(filename:fileNameToUse,data:assetData,originalLocation:fileURL.absoluteString,contentType:fileContentType) + } else { + print("Usergrid Error: Failed to imply content type of the asset.") + self.init(filename:"",data:NSData(),contentType:"") + return nil + } + } else { + print("Usergrid Error: fileURL parameter must be a file reference URL.") + self.init(filename:"",data:NSData(),contentType:"") + return nil + } + } + + // MARK: - NSCoding - + + /** + NSCoding protocol initializer. + + - parameter aDecoder: The decoder. + + - returns: A decoded `UsergridUser` object. + */ + required public init?(coder aDecoder: NSCoder) { + guard let filename = aDecoder.decodeObjectForKey("filename") as? String, + let assetData = aDecoder.decodeObjectForKey("data") as? NSData, + let contentType = aDecoder.decodeObjectForKey("contentType") as? String + else { + self.filename = "" + self.contentType = "" + self.originalLocation = nil + self.data = NSData() + super.init() + return nil + } + self.filename = filename + self.data = assetData + self.contentType = contentType + self.originalLocation = aDecoder.decodeObjectForKey("originalLocation") as? String + super.init() + } + + /** + NSCoding protocol encoder. + + - parameter aCoder: The encoder. + */ + public func encodeWithCoder(aCoder: NSCoder) { + aCoder.encodeObject(self.filename, forKey: "filename") + aCoder.encodeObject(self.data, forKey: "data") + aCoder.encodeObject(self.contentType, forKey: "contentType") + aCoder.encodeObject(self.originalLocation, forKey: "originalLocation") + } + + private static func MIMEType(fileURL: NSURL) -> String? { + if let pathExtension = fileURL.pathExtension { + if let UTIRef = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, pathExtension, nil) { + let UTI = UTIRef.takeUnretainedValue() + UTIRef.release() + if let MIMETypeRef = UTTypeCopyPreferredTagWithClass(UTI, kUTTagClassMIMEType) { + let MIMEType = MIMETypeRef.takeUnretainedValue() + MIMETypeRef.release() + return MIMEType as String + } + } + } + return nil + } +} \ No newline at end of file
http://git-wip-us.apache.org/repos/asf/usergrid/blob/7442c881/sdks/swift/Samples/Push/Pods/UsergridSDK/sdks/swift/Source/UsergridAssetRequestWrapper.swift ---------------------------------------------------------------------- diff --git a/sdks/swift/Samples/Push/Pods/UsergridSDK/sdks/swift/Source/UsergridAssetRequestWrapper.swift b/sdks/swift/Samples/Push/Pods/UsergridSDK/sdks/swift/Source/UsergridAssetRequestWrapper.swift new file mode 100644 index 0000000..d715652 --- /dev/null +++ b/sdks/swift/Samples/Push/Pods/UsergridSDK/sdks/swift/Source/UsergridAssetRequestWrapper.swift @@ -0,0 +1,48 @@ +// +// UsergridAssetRequestWrapper.swift +// UsergridSDK +// +// Created by Robert Walsh on 10/1/15. +// +/* + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. The ASF licenses this file to You + * under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. For additional information regarding + * copyright in this work, please see the NOTICE file in the top level + * directory of this distribution. + * + */ + +import Foundation + +typealias UsergridAssetRequestWrapperCompletionBlock = (requestWrapper:UsergridAssetRequestWrapper) -> Void + +final class UsergridAssetRequestWrapper { + weak var session: NSURLSession? + let sessionTask: NSURLSessionTask + + var response: NSURLResponse? + var responseData: NSData? + var error: NSError? + + var progress: UsergridAssetRequestProgress? + let completion: UsergridAssetRequestWrapperCompletionBlock + + init(session:NSURLSession?, sessionTask:NSURLSessionTask, progress:UsergridAssetRequestProgress?, completion:UsergridAssetRequestWrapperCompletionBlock) { + self.session = session + self.sessionTask = sessionTask + self.progress = progress + self.completion = completion + } +} \ No newline at end of file http://git-wip-us.apache.org/repos/asf/usergrid/blob/7442c881/sdks/swift/Samples/Push/Pods/UsergridSDK/sdks/swift/Source/UsergridAuth.swift ---------------------------------------------------------------------- diff --git a/sdks/swift/Samples/Push/Pods/UsergridSDK/sdks/swift/Source/UsergridAuth.swift b/sdks/swift/Samples/Push/Pods/UsergridSDK/sdks/swift/Source/UsergridAuth.swift new file mode 100644 index 0000000..a8879b2 --- /dev/null +++ b/sdks/swift/Samples/Push/Pods/UsergridSDK/sdks/swift/Source/UsergridAuth.swift @@ -0,0 +1,276 @@ +// +// UsergridAuth.swift +// UsergridSDK +// +// Created by Robert Walsh on 9/11/15. +// +/* + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. The ASF licenses this file to You + * under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. For additional information regarding + * copyright in this work, please see the NOTICE file in the top level + * directory of this distribution. + * + */ + +import Foundation + +/// The completion block used in `UsergridAppAuth` authentication methods. +public typealias UsergridAppAuthCompletionBlock = (auth:UsergridAppAuth?, error: UsergridResponseError?) -> Void + +/// The completion block used in `UsergridUserAuth` authentication methods. +public typealias UsergridUserAuthCompletionBlock = (auth:UsergridUserAuth?, user:UsergridUser?, error: UsergridResponseError?) -> Void + +/** + The `UsergridAuth` class functions to create and store authentication information used by Usergrid. + + The `UsergridAuth` sub classes, `UsergridAppAuth` and `UsergridUserAuth`, provide different ways for authentication to be used in creating requests for access tokens through the SDK. +*/ +public class UsergridAuth : NSObject, NSCoding { + + // MARK: - Instance Properties - + + /// The access token, if this `UsergridAuth` was authorized successfully. + public var accessToken : String? + + /// The expires at date, if this `UsergridAuth` was authorized successfully and their was a expires in time stamp within the token response. + public var expiry : NSDate? + + /// Determines if an access token exists. + public var hasToken: Bool { return self.accessToken != nil } + + /// Determines if the token was set explicitly within the init method or not. + private var usingToken: Bool = false + + /// Determines if an access token exists and if the token is not expired. + public var isValid : Bool { return self.hasToken && !self.isExpired } + + /// Determines if the access token, if one exists, is expired. + public var isExpired: Bool { + var isExpired = false + if let expires = self.expiry { + isExpired = expires.timeIntervalSinceNow < 0.0 + } else { + isExpired = !self.usingToken + } + return isExpired + } + + /// The credentials dictionary. Subclasses must override this method and provide an actual dictionary containing the credentials to send with requests. + var credentialsJSONDict: [String:AnyObject] { + return [:] + } + + // MARK: - Initialization - + + /** + Internal initialization method. Note this should never be used outside of internal methods. + + - returns: A new instance of `UsergridAuth`. + */ + override private init() { + super.init() + } + + /** + Initializer for a base `UsergridAuth` object that just contains an `accessToken` and an optional `expiry` date. + + - parameter accessToken: The access token. + - parameter expiry: The optional expiry date. + + - returns: A new instance of `UsergridAuth` + */ + public init(accessToken:String, expiry:NSDate? = nil) { + self.usingToken = true + self.accessToken = accessToken + self.expiry = expiry + } + + // MARK: - NSCoding - + + /** + NSCoding protocol initializer. + + - parameter aDecoder: The decoder. + + - returns: A decoded `UsergridUser` object. + */ + required public init?(coder aDecoder: NSCoder) { + self.accessToken = aDecoder.decodeObjectForKey("accessToken") as? String + self.expiry = aDecoder.decodeObjectForKey("expiry") as? NSDate + } + + /** + NSCoding protocol encoder. + + - parameter aCoder: The encoder. + */ + public func encodeWithCoder(aCoder: NSCoder) { + if let accessToken = self.accessToken { + aCoder.encodeObject(accessToken, forKey: "accessToken") + } + if let expiresAt = self.expiry { + aCoder.encodeObject(expiresAt, forKey: "expiry") + } + } + + // MARK: - Instance Methods - + + /** + Destroys/removes the access token and expiry. + */ + public func destroy() { + self.accessToken = nil + self.expiry = nil + } +} + +/// The `UsergridAuth` subclass used for user level authorization. +public class UsergridUserAuth : UsergridAuth { + + // MARK: - Instance Properties - + + /// The username associated with the User. + public let username: String + + /// The password associated with the User. + private let password: String + + /// The credentials dictionary constructed with the `UsergridUserAuth`'s `username` and `password`. + override var credentialsJSONDict: [String:AnyObject] { + return ["grant_type":"password", + "username":self.username, + "password":self.password] + } + + // MARK: - Initialization - + + /** + Designated initializer for `UsergridUserAuth` objects. + + - parameter username: The username associated with the User. + - parameter password: The password associated with the User. + + - returns: A new instance of `UsergridUserAuth`. + */ + public init(username:String, password: String){ + self.username = username + self.password = password + super.init() + } + + // MARK: - NSCoding - + + /** + NSCoding protocol initializer. + + - parameter aDecoder: The decoder. + + - returns: A decoded `UsergridUser` object. + */ + required public init?(coder aDecoder: NSCoder) { + guard let username = aDecoder.decodeObjectForKey("username") as? String, + password = aDecoder.decodeObjectForKey("password") as? String + else { + self.username = "" + self.password = "" + super.init(coder: aDecoder) + return nil + } + + self.username = username + self.password = password + super.init(coder: aDecoder) + } + + /** + NSCoding protocol encoder. + + - parameter aCoder: The encoder. + */ + override public func encodeWithCoder(aCoder: NSCoder) { + aCoder.encodeObject(self.username, forKey: "username") + aCoder.encodeObject(self.password, forKey: "password") + super.encodeWithCoder(aCoder) + } +} + +/// The `UsergridAuth` subclass used for application level authorization. +public class UsergridAppAuth : UsergridAuth { + + // MARK: - Instance Properties - + + /// The client identifier associated with the application. + public let clientId: String + + /// The client secret associated with the application. + private let clientSecret: String + + /// The credentials dictionary constructed with the `UsergridAppAuth`'s `clientId` and `clientSecret`. + override var credentialsJSONDict: [String:AnyObject] { + return ["grant_type":"client_credentials", + "client_id":self.clientId, + "client_secret":self.clientSecret] + } + + // MARK: - Initialization - + + /** + Designated initializer for `UsergridAppAuth` objects. + + - parameter clientId: The client identifier associated with the application. + - parameter clientSecret: The client secret associated with the application. + + - returns: A new instance of `UsergridAppAuth`. + */ + public init(clientId:String,clientSecret:String){ + self.clientId = clientId + self.clientSecret = clientSecret + super.init() + } + + // MARK: - NSCoding - + + /** + NSCoding protocol initializer. + + - parameter aDecoder: The decoder. + + - returns: A decoded `UsergridUser` object. + */ + required public init?(coder aDecoder: NSCoder) { + guard let clientId = aDecoder.decodeObjectForKey("clientId") as? String, + let clientSecret = aDecoder.decodeObjectForKey("clientSecret") as? String + else { + self.clientId = "" + self.clientSecret = "" + super.init(coder: aDecoder) + return nil + } + self.clientId = clientId + self.clientSecret = clientSecret + super.init(coder: aDecoder) + } + + /** + NSCoding protocol encoder. + + - parameter aCoder: The encoder. + */ + override public func encodeWithCoder(aCoder: NSCoder) { + aCoder.encodeObject(self.clientId, forKey: "clientId") + aCoder.encodeObject(self.clientSecret, forKey: "clientSecret") + super.encodeWithCoder(aCoder) + } +} \ No newline at end of file http://git-wip-us.apache.org/repos/asf/usergrid/blob/7442c881/sdks/swift/Samples/Push/Pods/UsergridSDK/sdks/swift/Source/UsergridClient.swift ---------------------------------------------------------------------- diff --git a/sdks/swift/Samples/Push/Pods/UsergridSDK/sdks/swift/Source/UsergridClient.swift b/sdks/swift/Samples/Push/Pods/UsergridSDK/sdks/swift/Source/UsergridClient.swift new file mode 100644 index 0000000..cbb416f --- /dev/null +++ b/sdks/swift/Samples/Push/Pods/UsergridSDK/sdks/swift/Source/UsergridClient.swift @@ -0,0 +1,875 @@ +// +// UsergridClient.swift +// UsergridSDK +// +// Created by Robert Walsh on 9/3/15. +// +/* + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. The ASF licenses this file to You + * under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. For additional information regarding + * copyright in this work, please see the NOTICE file in the top level + * directory of this distribution. + * + */ + + +import Foundation + +/** +The `UsergridClient` class is the base handler for making client connections to and managing relationships with Usergrid's API. +*/ +public class UsergridClient: NSObject, NSCoding { + + static let DEFAULT_BASE_URL = "https://api.usergrid.com" + + // MARK: - Instance Properties - + + lazy private var _requestManager: UsergridRequestManager = UsergridRequestManager(client: self) + + /// The configuration object used by the client. + public let config: UsergridClientConfig + + /// The application identifier. + public var appId : String { return config.appId } + + /// The organization identifier. + public var orgId : String { return config.orgId } + + /// The base URL that all calls will be made with. + public var baseUrl : String { return config.baseUrl } + + /// The constructed URL string based on the `UsergridClient`'s `baseUrl`, `orgId`, and `appId`. + internal var clientAppURL : String { return "\(baseUrl)/\(orgId)/\(appId)" } + + /// The currently logged in `UsergridUser`. + internal(set) public var currentUser: UsergridUser? = nil { + didSet { + if let newUser = self.currentUser { + UsergridUser.saveCurrentUserKeychainItem(self,currentUser:newUser) + } else if oldValue != nil { + UsergridUser.deleteCurrentUserKeychainItem(self) + } + } + } + + /// The `UsergridUserAuth` which consists of the token information from the `currentUser` property. + public var userAuth: UsergridUserAuth? { return currentUser?.auth } + + /// The temporary `UsergridAuth` object that is set when calling the `UsergridClient.usingAuth()` method. + private var tempAuth: UsergridAuth? = nil + + /// The application level `UsergridAppAuth` object. Can be set manually but must call `authenticateApp` to retrive token. + public var appAuth: UsergridAppAuth? { + set { config.appAuth = newValue } + get { return config.appAuth } + } + + /// The `UsergridAuthFallback` value used to determine what type of token will be sent, if any. + public var authFallback: UsergridAuthFallback { + set { config.authFallback = newValue } + get { return config.authFallback } + } + + // MARK: - Initialization - + + /** + Initializes instances of `UsergridClient`. + + - parameter orgId: The organization identifier. + - parameter appId: The application identifier. + + - returns: The new instance of `UsergridClient`. + */ + public convenience init(orgId: String, appId:String) { + self.init(configuration:UsergridClientConfig(orgId: orgId, appId: appId)) + } + + /** + Initializes instances of `UsergridClient`. + + - parameter orgId: The organization identifier. + - parameter appId: The application identifier. + - parameter baseUrl: The base URL that all calls will be made with. + + - returns: The new instance of `UsergridClient`. + */ + public convenience init(orgId: String, appId:String, baseUrl:String) { + self.init(configuration:UsergridClientConfig(orgId: orgId, appId: appId, baseUrl:baseUrl)) + } + + /** + Initializes instances of `UsergridClient`. + + - parameter configuration: The configuration for the client to be set up with. + + - returns: The new instance of `UsergridClient`. + */ + public init(configuration:UsergridClientConfig) { + self.config = configuration + super.init() + self.currentUser = UsergridUser.getCurrentUserFromKeychain(self) // Attempt to get the current user from the saved keychain data. + } + + // MARK: - NSCoding - + + /** + NSCoding protocol initializer. + + - parameter aDecoder: The decoder. + + - returns: A decoded `UsergridClient` object. + */ + public required init?(coder aDecoder: NSCoder) { + guard let config = aDecoder.decodeObjectForKey("config") as? UsergridClientConfig + else { + self.config = UsergridClientConfig(orgId: "", appId: "") + super.init() + return nil + } + + self.config = config + super.init() + + if let currentUser = aDecoder.decodeObjectForKey("currentUser") as? UsergridUser { + self.currentUser = currentUser + } else { + // If we didn't decode a current user, attempt to get the current user from the saved keychain data. + self.currentUser = UsergridUser.getCurrentUserFromKeychain(self) + } + } + + /** + NSCoding protocol encoder. + + - parameter aCoder: The encoder. + */ + public func encodeWithCoder(aCoder: NSCoder) { + aCoder.encodeObject(self.config, forKey: "config") + aCoder.encodeObject(self.currentUser, forKey: "currentUser") + } + + // MARK: - Device Registration/Push Notifications - + + /** + Sets the push token for the given notifier ID and performs a PUT request to update the shared `UsergridDevice` instance. + + - parameter pushToken: The push token from Apple. + - parameter notifierID: The Usergrid notifier ID. + - parameter completion: The completion block. + */ + public func applyPushToken(pushToken: NSData, notifierID: String, completion: UsergridResponseCompletion? = nil) { + self.applyPushToken(UsergridDevice.sharedDevice, pushToken: pushToken, notifierID: notifierID, completion: completion) + } + + /** + Sets the push token for the given notifier ID and performs a PUT request to update the given `UsergridDevice` instance. + + - parameter device: The `UsergridDevice` object. + - parameter pushToken: The push token from Apple. + - parameter notifierID: The Usergrid notifier ID. + - parameter completion: The completion block. + */ + public func applyPushToken(device: UsergridDevice, pushToken: NSData, notifierID: String, completion: UsergridResponseCompletion? = nil) { + device.applyPushToken(pushToken, notifierID: notifierID) + PUT(UsergridDevice.DEVICE_ENTITY_TYPE, jsonBody: device.jsonObjectValue, completion: completion) + } + + // MARK: - Authorization and User Management - + + /** + Determines the `UsergridAuth` object that will be used for all outgoing requests made. + + If there is a valid temporary `UsergridAuth` set by the functions `usingAuth` or `usingToken` it will return that. + + If there is a `UsergridUser` logged in and the token of that user is valid then it will return that. + + Otherwise, if the `authFallback` is `.App`, and the `UsergridAppAuth` of the client is set and the token is valid it will return that. + + - returns: The `UsergridAuth` if one is found or nil if not. + */ + internal func authForRequests() -> UsergridAuth? { + var usergridAuth: UsergridAuth? + if let tempAuth = self.tempAuth where tempAuth.isValid { + usergridAuth = tempAuth + self.tempAuth = nil + } else if let userAuth = self.userAuth where userAuth.isValid { + usergridAuth = userAuth + } else if self.authFallback == .App, let appAuth = self.appAuth where appAuth.isValid { + usergridAuth = appAuth + } + return usergridAuth + } + + /** + Sets the client's `tempAuth` property using the passed in `UsergridAuth`. + + This will cause the next CRUD method performed by the client to use the `tempAuth` property once and will then reset. + + - parameter auth: The `UsergridAuth` object to temporarily use for authentication. + + - returns: `Self` + */ + public func usingAuth(auth:UsergridAuth) -> Self { + self.tempAuth = auth + return self + } + + /** + Sets the client's `tempAuth` property using the passed in token. + + This will cause the next CRUD method performed by the client to use the `tempAuth` property once and will then reset. + + - parameter auth: The access token to temporarily use for authentication. + + - returns: `Self` + */ + public func usingToken(token:String) -> Self { + self.tempAuth = UsergridAuth(accessToken: token) + return self + } + + /** + Authenticates with the `UsergridAppAuth` that is contained this instance of `UsergridCient`. + + - parameter completion: The completion block that will be called after authentication has completed. + */ + public func authenticateApp(completion: UsergridAppAuthCompletionBlock? = nil) { + guard let appAuth = self.appAuth + else { + let error = UsergridResponseError(errorName: "Invalid UsergridAppAuth.", errorDescription: "UsergridClient's appAuth is nil.") + completion?(auth: nil, error: error) + return + } + self.authenticateApp(appAuth, completion: completion) + } + + /** + Authenticates with the `UsergridAppAuth` that is passed in. + + - parameter auth: The `UsergridAppAuth` that will be authenticated. + - parameter completion: The completion block that will be called after authentication has completed. + */ + public func authenticateApp(appAuth: UsergridAppAuth, completion: UsergridAppAuthCompletionBlock? = nil) { + let request = UsergridRequest(method: .Post, + baseUrl: self.clientAppURL, + paths: ["token"], + auth: self.authForRequests(), + jsonBody: appAuth.credentialsJSONDict) + + _requestManager.performAppAuthRequest(appAuth, request: request) { [weak self] (auth,error) in + self?.appAuth = auth + completion?(auth: auth, error: error) + } + } + + /** + Authenticates with the `UsergridUserAuth` that is passed in. + + - parameter auth: The `UsergridUserAuth` that will be authenticated. + - parameter completion: The completion block that will be called after authentication has completed. + */ + public func authenticateUser(userAuth: UsergridUserAuth, completion: UsergridUserAuthCompletionBlock? = nil) { + self.authenticateUser(userAuth, setAsCurrentUser:true, completion:completion) + } + + /** + Authenticates with the `UsergridUserAuth` that is passed in. + + - parameter auth: The `UsergridUserAuth` that will be authenticated. + - parameter setAsCurrentUser: If the authenticated user should be set as the `UsergridClient.currentUser`. + - parameter completion: The completion block that will be called after authentication has completed. + */ + public func authenticateUser(userAuth: UsergridUserAuth, setAsCurrentUser: Bool, completion: UsergridUserAuthCompletionBlock? = nil) { + let request = UsergridRequest(method: .Post, + baseUrl: self.clientAppURL, + paths: ["token"], + auth: self.authForRequests(), + jsonBody: userAuth.credentialsJSONDict) + _requestManager.performUserAuthRequest(userAuth, request: request) { [weak self] (auth,user,error) in + if setAsCurrentUser { + self?.currentUser = user + } + completion?(auth: auth, user: user, error: error) + } + } + + /** + Changes the give `UsergridUser`'s current password with the shared instance of `UsergridClient`. + + - parameter user: The user. + - parameter old: The old password. + - parameter new: The new password. + - parameter completion: The optional completion block. + */ + public func resetPassword(user: UsergridUser, old:String, new:String, completion:UsergridUserResetPasswordCompletion? = nil) { + guard let usernameOrEmail = user.usernameOrEmail + else { + completion?(error: UsergridResponseError(errorName: "Error resetting password.", errorDescription: "The UsergridUser object must contain a valid username or email to reset the password."), didSucceed: false) + return + } + + let request = UsergridRequest(method: .Put, + baseUrl: self.clientAppURL, + paths: ["users",usernameOrEmail,"password"], + auth: self.authForRequests(), + jsonBody:["oldpassword":old,"newpassword":new]) + + _requestManager.performRequest(request, completion: { (response) -> Void in + completion?(error: response.error, didSucceed: response.statusCode == 200) + }) + } + + /** + Logs out the current user locally and remotely. + + - parameter completion: The completion block that will be called after logout has completed. + */ + public func logoutCurrentUser(completion:UsergridResponseCompletion? = nil) { + guard let uuidOrUsername = self.currentUser?.uuidOrUsername, + let token = self.currentUser?.auth?.accessToken + else { + completion?(response:UsergridResponse(client: self, errorName: "Logout Failed.", errorDescription: "UsergridClient's currentUser is not valid.")) + return + } + + self.logoutUser(uuidOrUsername, token: token) { (response) -> Void in + if response.ok || response.error?.errorName == "auth_bad_access_token" { + self.currentUser?.auth = nil + self.currentUser = nil + } + completion?(response: response) + } + } + + /** + Logs out the user remotely with the given tokens. + + - parameter completion: The completion block that will be called after logout has completed. + */ + public func logoutUserAllTokens(uuidOrUsername:String, completion:UsergridResponseCompletion? = nil) { + self.logoutUser(uuidOrUsername, token: nil, completion: completion) + } + + /** + Logs out a user with the give UUID or username using the shared instance of `UsergridCient`. + + Passing in a token will log out the user for just that token. Passing in nil for the token will logout the user for all tokens. + + - parameter completion: The completion block that will be called after logout has completed. + */ + public func logoutUser(uuidOrUsername:String, token:String?, completion:UsergridResponseCompletion? = nil) { + var paths = ["users",uuidOrUsername] + var queryParams: [String: String]? + if let accessToken = token { + paths.append("revoketoken") + queryParams = ["token": accessToken] + } else { + paths.append("revoketokens") + } + let request = UsergridRequest(method: .Put, + baseUrl: self.clientAppURL, + paths: paths, + auth: self.authForRequests(), + queryParams: queryParams) + self.sendRequest(request, completion: completion) + } + + // MARK: - Generic Request Methods - + + /** + Starts the `UsergridRequest` sending process. + + - Note: This method should only be used when you construct your own `UsergridRequest` objects. + + - parameter request: The `UsergridRequest` object to send. + - parameter completion: The optional completion block that will be called once the request has completed. + */ + public func sendRequest(request:UsergridRequest, completion:UsergridResponseCompletion? = nil) { + _requestManager.performRequest(request, completion: completion) + } + + // MARK: - GET - + + /** + Gets a single `UsergridEntity` of a given type with a specific UUID/name. + + - parameter type: The `UsergridEntity` type. + - parameter uuidOrName: The UUID or name of the `UsergridEntity`. + - parameter completion: The optional completion block that will be called once the request has completed. + */ + public func GET(type: String, uuidOrName: String, completion: UsergridResponseCompletion? = nil) { + let request = UsergridRequest(method: .Get, baseUrl: self.clientAppURL, paths: [type,uuidOrName], auth:self.authForRequests()) + self.sendRequest(request, completion: completion) + } + + /** + Gets a group of `UsergridEntity` objects of a given type with an optional query. + + - parameter type: The `UsergridEntity` type. + - parameter query: The optional query to use when gathering `UsergridEntity` objects. + - parameter completion: The optional completion block that will be called once the request has completed. + */ + public func GET(type: String, query: UsergridQuery? = nil, completion: UsergridResponseCompletion? = nil) { + let request = UsergridRequest(method: .Get, baseUrl: self.clientAppURL, paths: [type], query: query, auth: self.authForRequests()) + self.sendRequest(request, completion: completion) + } + + // MARK: - PUT - + + /** + Updates an `UsergridEntity` with the given type and UUID/name specified using the passed in jsonBody. + + - parameter type: The `UsergridEntity` type. + - parameter uuidOrName: The UUID or name of the `UsergridEntity`. + - parameter jsonBody: The valid JSON body dictionary to update the `UsergridEntity` with. + - parameter completion: The optional completion block that will be called once the request has completed. + */ + public func PUT(type: String, uuidOrName: String, jsonBody:[String:AnyObject], completion: UsergridResponseCompletion? = nil) { + let request = UsergridRequest(method: .Put, + baseUrl: self.clientAppURL, + paths: [type,uuidOrName], + auth: self.authForRequests(), + headers: UsergridRequest.JSON_CONTENT_TYPE_HEADER, + jsonBody: jsonBody) + self.sendRequest(request, completion: completion) + } + + /** + Updates the passed in `UsergridEntity`. + + - parameter entity: The `UsergridEntity` to update. + - parameter completion: The optional completion block that will be called once the request has completed. + */ + public func PUT(entity: UsergridEntity, completion: UsergridResponseCompletion? = nil) { + PUT(entity.type, jsonBody: entity.jsonObjectValue, completion: completion) + } + + /** + Updates an `UsergridEntity` with the given type using the jsonBody where the UUID/name is specified inside of the jsonBody. + + - Note: The `jsonBody` must contain a valid value for either `uuid` or `name` keys. + + - parameter type: The `UsergridEntity` type. + - parameter jsonBody: The valid JSON body dictionary to update the `UsergridEntity` with. + - parameter completion: The optional completion block that will be called once the request has completed. + */ + public func PUT(type: String, jsonBody:[String:AnyObject], completion: UsergridResponseCompletion? = nil) { + guard let uuidOrName = (jsonBody[UsergridEntityProperties.UUID.stringValue] ?? jsonBody[UsergridEntityProperties.Name.stringValue]) as? String + else { + completion?(response: UsergridResponse(client:self, errorName: "jsonBody not valid.", errorDescription: "The `jsonBody` must contain a valid value for either `uuid` or `name`.")) + return + } + let request = UsergridRequest(method: .Put, + baseUrl: self.clientAppURL, + paths: [type,uuidOrName], + auth: self.authForRequests(), + headers: UsergridRequest.JSON_CONTENT_TYPE_HEADER, + jsonBody: jsonBody) + self.sendRequest(request, completion: completion) + } + + /** + Updates the entities that fit the given query using the passed in jsonBody. + + - Note: The query parameter must have a valid `collectionName` before calling this method. + + - parameter query: The query to use when filtering what entities to update. + - parameter jsonBody: The valid JSON body dictionary to update with. + - parameter queryCompletion: The optional completion block that will be called once the request has completed. + */ + public func PUT(query: UsergridQuery, jsonBody:[String:AnyObject], queryCompletion: UsergridResponseCompletion? = nil) { + guard let type = query.collectionName + else { + queryCompletion?(response: UsergridResponse(client:self, errorName: "Query collection name invalid.", errorDescription: "Query is missing a collection name.")) + return + } + let request = UsergridRequest(method: .Put, + baseUrl: self.clientAppURL, + paths: [type], + query: query, + auth: self.authForRequests(), + headers: UsergridRequest.JSON_CONTENT_TYPE_HEADER, + jsonBody: jsonBody) + self.sendRequest(request, completion: queryCompletion) + } + + // MARK: - POST - + + /** + Creates and posts creates an `UsergridEntity`. + - parameter entity: The `UsergridEntity` to create. + - parameter completion: The optional completion block that will be called once the request has completed. + */ + public func POST(entity:UsergridEntity, completion: UsergridResponseCompletion? = nil) { + let request = UsergridRequest(method: .Post, + baseUrl: self.clientAppURL, + paths: [entity.type], + auth: self.authForRequests(), + headers: UsergridRequest.JSON_CONTENT_TYPE_HEADER, + jsonBody: entity.jsonObjectValue) + self.sendRequest(request, completion: completion) + } + + /** + Creates and posts an array of `UsergridEntity` objects. + + - Note: Each `UsergridEntity` in the array much already have a type assigned and must be the same. + + - parameter entities: The `UsergridEntity` objects to create. + - parameter entitiesCompletion: The optional completion block that will be called once the request has completed. + */ + public func POST(entities:[UsergridEntity], entitiesCompletion: UsergridResponseCompletion? = nil) { + guard let type = entities.first?.type + else { + entitiesCompletion?(response: UsergridResponse(client:self, errorName: "No type found.", errorDescription: "The first entity in the array had no type found.")) + return + } + POST(type, jsonBodies: entities.map { return ($0).jsonObjectValue }, completion: entitiesCompletion) + } + + /** + Creates and posts an `UsergridEntity` of the given type with the given jsonBody. + + - parameter type: The `UsergridEntity` type. + - parameter jsonBody: The valid JSON body dictionary to use when creating the `UsergridEntity`. + - parameter completion: The optional completion block that will be called once the request has completed. + */ + public func POST(type: String, jsonBody:[String:AnyObject], completion: UsergridResponseCompletion? = nil) { + let request = UsergridRequest(method: .Post, + baseUrl: self.clientAppURL, + paths: [type], + auth: self.authForRequests(), + headers: UsergridRequest.JSON_CONTENT_TYPE_HEADER, + jsonBody: jsonBody) + self.sendRequest(request, completion: completion) + } + + /** + Creates and posts an array of `Entity` objects while assigning the given type to them. + + - parameter type: The `UsergridEntity` type. + - parameter jsonBody: The valid JSON body dictionaries to use when creating the `UsergridEntity` objects. + - parameter completion: The optional completion block that will be called once the request has completed. + */ + public func POST(type: String, jsonBodies:[[String:AnyObject]], completion: UsergridResponseCompletion? = nil) { + let request = UsergridRequest(method: .Post, + baseUrl: self.clientAppURL, + paths: [type], + auth: self.authForRequests(), + headers: UsergridRequest.JSON_CONTENT_TYPE_HEADER, + jsonBody: jsonBodies) + self.sendRequest(request, completion: completion) + } + + /** + Creates and posts an `UsergridEntity` of the given type with a given name and the given jsonBody. + + - parameter type: The `UsergridEntity` type. + - parameter name: The name of the `UsergridEntity`. + - parameter jsonBody: The valid JSON body dictionary to use when creating the `UsergridEntity`. + - parameter completion: The optional completion block that will be called once the request has completed. + */ + public func POST(type: String, name: String, jsonBody:[String:AnyObject], completion: UsergridResponseCompletion? = nil) { + var jsonBodyWithName = jsonBody + jsonBodyWithName[UsergridEntityProperties.Name.stringValue] = name + let request = UsergridRequest(method: .Post, + baseUrl: self.clientAppURL, + paths: [type], + auth: self.authForRequests(), + headers: UsergridRequest.JSON_CONTENT_TYPE_HEADER, + jsonBody: jsonBodyWithName) + self.sendRequest(request, completion: completion) + + } + + // MARK: - DELETE - + + /** + Destroys the passed `UsergridEntity`. + + - Note: The entity object must have a `uuid` or `name` assigned. + + - parameter entity: The `UsergridEntity` to delete. + - parameter completion: The optional completion block that will be called once the request has completed. + */ + public func DELETE(entity:UsergridEntity, completion: UsergridResponseCompletion? = nil) { + guard let uuidOrName = entity.uuidOrName + else { + completion?(response: UsergridResponse(client:self, errorName: "No UUID or name found.", errorDescription: "The entity object must have a `uuid` or `name` assigned.")) + return + } + + DELETE(entity.type, uuidOrName: uuidOrName, completion: completion) + } + + /** + Destroys the `UsergridEntity` objects that fit the given `UsergridQuery`. + + - Note: The query parameter must have a valid `collectionName` before calling this method. + + - parameter query: The query to use when filtering what entities to delete. + - parameter queryCompletion: The optional completion block that will be called once the request has completed. + */ + public func DELETE(query:UsergridQuery, queryCompletion: UsergridResponseCompletion? = nil) { + guard let type = query.collectionName + else { + queryCompletion?(response: UsergridResponse(client:self, errorName: "Query collection name invalid.", errorDescription: "Query is missing a collection name.")) + return + } + + let request = UsergridRequest(method: .Delete, + baseUrl: self.clientAppURL, + paths: [type], + query: query, + auth: self.authForRequests(), + headers: UsergridRequest.JSON_CONTENT_TYPE_HEADER) + self.sendRequest(request, completion: queryCompletion) + } + + /** + Destroys the `UsergridEntity` of a given type with a specific UUID/name. + + - parameter type: The `UsergridEntity` type. + - parameter uuidOrName: The UUID or name of the `UsergridEntity`. + - parameter completion: The optional completion block that will be called once the request has completed. + */ + public func DELETE(type:String, uuidOrName: String, completion: UsergridResponseCompletion? = nil) { + let request = UsergridRequest(method: .Delete, + baseUrl: self.clientAppURL, + paths: [type,uuidOrName], + auth: self.authForRequests(), + headers: UsergridRequest.JSON_CONTENT_TYPE_HEADER) + self.sendRequest(request, completion: completion) + } + + // MARK: - Connection Management - + + /** + Connects the `UsergridEntity` objects via the relationship. + + - parameter entity: The `UsergridEntity` that will contain the connection. + - parameter relationship: The relationship of the connection. + - parameter to: The `UsergridEntity` which is connected. + - parameter completion: The optional completion block that will be called once the request has completed. + */ + public func connect(entity:UsergridEntity, relationship:String, to:UsergridEntity, completion: UsergridResponseCompletion? = nil) { + guard let entityID = entity.uuidOrName, + let toID = to.uuidOrName + else { + completion?(response: UsergridResponse(client: self, errorName: "Invalid Entity Connection Attempt.", errorDescription: "One or both entities that are attempting to be connected do not contain a valid UUID or Name property.")) + return + } + self.connect(entity.type, entityID: entityID, relationship: relationship, toType: to.type, toID: toID, completion: completion) + } + + /** + Connects the entity objects via the relationship. + + - parameter entityType: The entity type. + - parameter entityID: The entity UUID or name. + - parameter relationship: The relationship of the connection. + - parameter toType: The type of the entity you are connecting to. + - parameter toName: The name of the entity you are connecting to. + - parameter completion: The optional completion block that will be called once the request has completed. + */ + public func connect(entityType:String, entityID:String, relationship:String, toType:String, toName: String, completion: UsergridResponseCompletion? = nil) { + self.connect(entityType, entityID: entityID, relationship: relationship, toType: toType, toID: toName, completion: completion) + } + + /** + Connects the entity objects via the relationship. + + - parameter entityType: The entity type. + - parameter entityID: The entity UUID or name. + - parameter relationship: The relationship of the connection. + - parameter toType: The optional type of the entity you are connecting to. + - parameter toID: The UUID of the entity you are connecting to. + - parameter completion: The optional completion block that will be called once the request has completed. + */ + public func connect(entityType:String, entityID:String, relationship:String, toType:String?, toID: String, completion: UsergridResponseCompletion? = nil) { + var paths = [entityType,entityID,relationship] + if let toType = toType { + paths.append(toType) + } + paths.append(toID) + + let request = UsergridRequest(method: .Post, + baseUrl: self.clientAppURL, + paths: paths, + auth: self.authForRequests()) + self.sendRequest(request, completion: completion) + } + + /** + Disconnects the `UsergridEntity` objects via the relationship. + + - parameter entity: The `UsergridEntity` that contains the connection. + - parameter relationship: The relationship of the connection. + - parameter from: The `UsergridEntity` which is connected. + - parameter completion: The optional completion block that will be called once the request has completed. + */ + public func disconnect(entity:UsergridEntity, relationship:String, from:UsergridEntity, completion: UsergridResponseCompletion? = nil) { + guard let entityID = entity.uuidOrName, + let fromID = from.uuidOrName + else { + completion?(response: UsergridResponse(client: self, errorName: "Invalid Entity Disconnect Attempt.", errorDescription: "The connecting and connected entities must have a `uuid` or `name` assigned.")) + return + } + + self.disconnect(entity.type, entityID: entityID, relationship: relationship, fromType: from.type, fromID: fromID, completion: completion) + } + + /** + Disconnects the entity objects via the relationship. + + - parameter entityType: The entity type. + - parameter entityID: The entity UUID or name. + - parameter relationship: The relationship of the connection. + - parameter fromType: The type of the entity you are disconnecting from. + - parameter fromName: The name of the entity you are disconnecting from. + - parameter completion: The optional completion block that will be called once the request has completed. + */ + public func disconnect(entityType:String, entityID:String, relationship:String, fromType:String, fromName: String, completion: UsergridResponseCompletion? = nil) { + self.disconnect(entityType, entityID: entityID, relationship: relationship, fromType: fromType, fromID: fromName, completion: completion) + } + + /** + Disconnects the entity objects via the relationship. + + - parameter entityType: The entity type. + - parameter entityID: The entity UUID or name. + - parameter relationship: The relationship of the connection. + - parameter fromType: The optional type of the entity you are disconnecting from. + - parameter toID: The UUID of the entity you are disconnecting from. + - parameter completion: The optional completion block that will be called once the request has completed. + */ + public func disconnect(entityType:String, entityID:String, relationship:String, fromType:String?, fromID: String, completion: UsergridResponseCompletion? = nil) { + + var paths = [entityType,entityID,relationship] + if let fromType = fromType { + paths.append(fromType) + } + paths.append(fromID) + + let request = UsergridRequest(method: .Delete, + baseUrl: self.clientAppURL, + paths: paths, + auth: self.authForRequests()) + self.sendRequest(request, completion: completion) + } + + /** + Gets the connected entities for the given relationship. + + - parameter entity: The entity that contains the connection. + - parameter relationship: The relationship of the connection. + - parameter query: The optional query. + - parameter completion: The optional completion block that will be called once the request has completed. + */ + public func getConnections(direction:UsergridDirection, entity:UsergridEntity, relationship:String, query:UsergridQuery?, completion:UsergridResponseCompletion? = nil) { + guard let uuidOrName = entity.uuidOrName + else { + completion?(response: UsergridResponse(client: self, errorName: "Invalid Entity Get Connections Attempt.", errorDescription: "The entity must have a `uuid` or `name` assigned.")) + return + } + self.getConnections(direction, type: entity.type, uuidOrName: uuidOrName, relationship: relationship, query:query, completion: completion) + } + + /** + Gets the connected entities for the given relationship. + + - parameter direction: The direction of the connection. + - parameter type: The entity type. + - parameter uuidOrName: The entity UUID or name. + - parameter relationship: The relationship of the connection. + - parameter query: The optional query. + - parameter completion: The optional completion block that will be called once the request has completed. + */ + public func getConnections(direction:UsergridDirection, type:String, uuidOrName:String, relationship:String, query:UsergridQuery?, completion:UsergridResponseCompletion? = nil) { + let request = UsergridRequest(method: .Get, + baseUrl: self.clientAppURL, + paths: [type, uuidOrName, direction.connectionValue, relationship], + query: query, + auth: self.authForRequests()) + self.sendRequest(request, completion: completion) + } + + /** + Gets the connected entities for the given relationship. + + - parameter direction: The direction of the connection. + - parameter uuid: The entity UUID. + - parameter relationship: The relationship of the connection. + - parameter query: The optional query. + - parameter completion: The optional completion block that will be called once the request has completed. + */ + public func getConnections(direction:UsergridDirection, uuid:String, relationship:String, query:UsergridQuery?, completion:UsergridResponseCompletion? = nil) { + let request = UsergridRequest(method: .Get, + baseUrl: self.clientAppURL, + paths: [uuid, direction.connectionValue, relationship], + query: query, + auth: self.authForRequests()) + self.sendRequest(request, completion: completion) + } + + // MARK: - Asset Management - + + /** + Uploads the asset and connects the data to the given `UsergridEntity`. + + - parameter entity: The `UsergridEntity` to connect the asset to. + - parameter asset: The `UsergridAsset` to upload. + - parameter progress: The optional progress block that will be called to update the progress of the upload. + - parameter completion: The optional completion block that will be called once the request has completed. + */ + public func uploadAsset(entity:UsergridEntity, asset:UsergridAsset, progress:UsergridAssetRequestProgress? = nil, completion:UsergridAssetUploadCompletion? = nil) { + let assetRequest = UsergridAssetUploadRequest(baseUrl: self.clientAppURL, + paths: [entity.type,entity.uuidOrName!], + auth: self.authForRequests(), + asset: asset) + + _requestManager.performAssetUpload(assetRequest, progress: progress) { [weak entity] (response, asset, error) -> Void in + entity?.asset = asset + completion?(response: response, asset: asset, error: error) + } + } + + /** + Downloads the asset from the given `UsergridEntity`. + + - parameter entity: The `UsergridEntity` to which the asset to. + - parameter contentType: The content type of the asset's data. + - parameter progress: The optional progress block that will be called to update the progress of the download. + - parameter completion: The optional completion block that will be called once the request has completed. + */ + public func downloadAsset(entity:UsergridEntity, contentType:String, progress:UsergridAssetRequestProgress? = nil, completion:UsergridAssetDownloadCompletion? = nil) { + guard entity.hasAsset + else { + completion?(asset: nil, error: "Entity does not have an asset attached.") + return + } + + let downloadAssetRequest = UsergridRequest(method: .Get, + baseUrl: self.clientAppURL, + paths: [entity.type,entity.uuidOrName!], + auth: self.authForRequests(), + headers: ["Accept":contentType]) + + _requestManager.performAssetDownload(contentType, usergridRequest: downloadAssetRequest, progress: progress, completion: { (asset, error) -> Void in + entity.asset = asset + completion?(asset: asset, error: error) + }) + } +} http://git-wip-us.apache.org/repos/asf/usergrid/blob/7442c881/sdks/swift/Samples/Push/Pods/UsergridSDK/sdks/swift/Source/UsergridClientConfig.swift ---------------------------------------------------------------------- diff --git a/sdks/swift/Samples/Push/Pods/UsergridSDK/sdks/swift/Source/UsergridClientConfig.swift b/sdks/swift/Samples/Push/Pods/UsergridSDK/sdks/swift/Source/UsergridClientConfig.swift new file mode 100644 index 0000000..c79b6b2 --- /dev/null +++ b/sdks/swift/Samples/Push/Pods/UsergridSDK/sdks/swift/Source/UsergridClientConfig.swift @@ -0,0 +1,142 @@ +// +// UsergridClientConfig.swift +// UsergridSDK +// +// Created by Robert Walsh on 10/5/15. +// +/* + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. The ASF licenses this file to You + * under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. For additional information regarding + * copyright in this work, please see the NOTICE file in the top level + * directory of this distribution. + * + */ + +import Foundation + +/** +`UsergridClientConfig` is used when initializing `UsergridClient` objects. + +The `UsergridClientConfig` is meant for further customization of `UsergridClient` objects when needed. +*/ +public class UsergridClientConfig : NSObject, NSCoding { + + // MARK: - Instance Properties - + + /// The organization identifier. + public var orgId : String + + /// The application identifier. + public var appId : String + + /// The base URL that all calls will be made with. + public var baseUrl: String = UsergridClient.DEFAULT_BASE_URL + + /// The `UsergridAuthFallback` value used to determine what type of token will be sent, if any. + public var authFallback: UsergridAuthFallback = .App + + /** + The application level `UsergridAppAuth` object. + + Note that you still need to call the authentication methods within `UsergridClient` once it has been initialized. + */ + public var appAuth: UsergridAppAuth? + + // MARK: - Initialization - + + /** + Designated initializer for `UsergridClientConfig` objects. + + - parameter orgId: The organization identifier. + - parameter appId: The application identifier. + + - returns: A new instance of `UsergridClientConfig`. + */ + public init(orgId: String, appId: String) { + self.orgId = orgId + self.appId = appId + } + + /** + Convenience initializer for `UsergridClientConfig`. + + - parameter orgId: The organization identifier. + - parameter appId: The application identifier. + - parameter baseUrl: The base URL that all calls will be made with. + + - returns: A new instance of `UsergridClientConfig`. + */ + public convenience init(orgId: String, appId: String, baseUrl:String) { + self.init(orgId:orgId,appId:appId) + self.baseUrl = baseUrl + } + + /** + Convenience initializer for `UsergridClientConfig`. + + - parameter orgId: The organization identifier. + - parameter appId: The application identifier. + - parameter baseUrl: The base URL that all calls will be made with. + - parameter authFallback: The `UsergridAuthFallback` value used to determine what type of token will be sent, if any. + - parameter appAuth: The application level `UsergridAppAuth` object. + + - returns: A new instance of `UsergridClientConfig`. + */ + public convenience init(orgId: String, appId: String, baseUrl:String, authFallback:UsergridAuthFallback, appAuth:UsergridAppAuth? = nil) { + self.init(orgId:orgId,appId:appId,baseUrl:baseUrl) + self.authFallback = authFallback + self.appAuth = appAuth + } + + // MARK: - NSCoding - + + /** + NSCoding protocol initializer. + + - parameter aDecoder: The decoder. + + - returns: A decoded `UsergridUser` object. + */ + public required init?(coder aDecoder: NSCoder) { + guard let appId = aDecoder.decodeObjectForKey("appId") as? String, + let orgId = aDecoder.decodeObjectForKey("orgId") as? String, + let baseUrl = aDecoder.decodeObjectForKey("baseUrl") as? String + else { + self.appId = "" + self.orgId = "" + super.init() + return nil + } + self.appId = appId + self.orgId = orgId + self.baseUrl = baseUrl + self.appAuth = aDecoder.decodeObjectForKey("appAuth") as? UsergridAppAuth + self.authFallback = UsergridAuthFallback(rawValue:aDecoder.decodeIntegerForKey("authFallback")) ?? .App + super.init() + } + + /** + NSCoding protocol encoder. + + - parameter aCoder: The encoder. + */ + public func encodeWithCoder(aCoder: NSCoder) { + aCoder.encodeObject(self.appId, forKey: "appId") + aCoder.encodeObject(self.orgId, forKey: "orgId") + aCoder.encodeObject(self.baseUrl, forKey: "baseUrl") + aCoder.encodeObject(self.appAuth, forKey: "appAuth") + aCoder.encodeInteger(self.authFallback.rawValue, forKey: "authFallback") + } +} http://git-wip-us.apache.org/repos/asf/usergrid/blob/7442c881/sdks/swift/Samples/Push/Pods/UsergridSDK/sdks/swift/Source/UsergridDevice.swift ---------------------------------------------------------------------- diff --git a/sdks/swift/Samples/Push/Pods/UsergridSDK/sdks/swift/Source/UsergridDevice.swift b/sdks/swift/Samples/Push/Pods/UsergridSDK/sdks/swift/Source/UsergridDevice.swift new file mode 100644 index 0000000..c08fcf6 --- /dev/null +++ b/sdks/swift/Samples/Push/Pods/UsergridSDK/sdks/swift/Source/UsergridDevice.swift @@ -0,0 +1,168 @@ +// +// UsergridDevice.swift +// UsergridSDK +// +// Created by Robert Walsh on 10/23/15. +// +/* + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. The ASF licenses this file to You + * under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. For additional information regarding + * copyright in this work, please see the NOTICE file in the top level + * directory of this distribution. + * + */ + +import Foundation + +#if !os(OSX) +import UIKit +#endif + +#if os(watchOS) +import WatchKit +#endif + +/** +`UsergridDevice` is an `UsergridEntity` subclass that encapsulates information about the current device as well as stores information about push tokens and Usergrid notifiers. + +To apply push tokens for Usergrid notifiers use the `UsergridClient.applyPushToken` method. +*/ +public class UsergridDevice : UsergridEntity { + + /// The `UsergridDevice` type. + static let DEVICE_ENTITY_TYPE = "device" + + // MARK: - Instance Properties - + + /// Property helper method for the `UsergridDevice` objects `uuid`. + override public var uuid: String! { return super[UsergridEntityProperties.UUID.stringValue] as! String } + + /// Property helper method for the `UsergridDevice` objects device model. + public var model: String { return super[UsergridDeviceProperties.Model.stringValue] as! String } + + /// Property helper method for the `UsergridDevice` objects device platform. + public var platform: String { return super[UsergridDeviceProperties.Platform.stringValue] as! String } + + /// Property helper method for the `UsergridDevice` objects device operating system version. + public var osVersion: String { return super[UsergridDeviceProperties.OSVersion.stringValue] as! String } + + // MARK: - Initialization - + + /// The shared instance of `UsergridDevice`. + public static var sharedDevice: UsergridDevice = UsergridDevice() + + /** + Designated Initializer for `UsergridDevice` objects + + Most likely you will never need to create seperate instances of `UsergridDevice`. Use of `UsergridDevice.sharedInstance` is recommended. + + - returns: A new instance of `UsergridDevice`. + */ + public init() { + var deviceEntityDict: [String:AnyObject] = [:] + deviceEntityDict[UsergridEntityProperties.EntityType.stringValue] = UsergridDevice.DEVICE_ENTITY_TYPE + deviceEntityDict[UsergridEntityProperties.UUID.stringValue] = UsergridDevice.usergridDeviceUUID() + + #if os(watchOS) + deviceEntityDict[UsergridDeviceProperties.Model.stringValue] = WKInterfaceDevice.currentDevice().model + deviceEntityDict[UsergridDeviceProperties.Platform.stringValue] = WKInterfaceDevice.currentDevice().systemName + deviceEntityDict[UsergridDeviceProperties.OSVersion.stringValue] = WKInterfaceDevice.currentDevice().systemVersion + #elseif os(iOS) || os(tvOS) + deviceEntityDict[UsergridDeviceProperties.Model.stringValue] = UIDevice.currentDevice().model + deviceEntityDict[UsergridDeviceProperties.Platform.stringValue] = UIDevice.currentDevice().systemName + deviceEntityDict[UsergridDeviceProperties.OSVersion.stringValue] = UIDevice.currentDevice().systemVersion + #elseif os(OSX) + deviceEntityDict[UsergridDeviceProperties.Model.stringValue] = "Mac" + deviceEntityDict[UsergridDeviceProperties.Platform.stringValue] = "OSX" + deviceEntityDict[UsergridDeviceProperties.OSVersion.stringValue] = NSProcessInfo.processInfo().operatingSystemVersionString + #endif + + super.init(type: UsergridDevice.DEVICE_ENTITY_TYPE, propertyDict: deviceEntityDict) + } + + /** + The required public initializer for `UsergridEntity` subclasses. + + - parameter type: The type associated with the `UsergridEntity` object. + - parameter name: The optional name associated with the `UsergridEntity` object. + - parameter propertyDict: The optional property dictionary that the `UsergridEntity` object will start out with. + + - returns: A new `UsergridDevice` object. + */ + required public init(type: String, name: String?, propertyDict: [String : AnyObject]?) { + super.init(type: type, name: name, propertyDict: propertyDict) + } + + // MARK: - NSCoding - + + /** + NSCoding protocol initializer. + + - parameter aDecoder: The decoder. + + - returns: A decoded `UsergridUser` object. + */ + required public init?(coder aDecoder: NSCoder) { + super.init(coder: aDecoder) + } + + /** + NSCoding protocol encoder. + + - parameter aCoder: The encoder. + */ + public override func encodeWithCoder(aCoder: NSCoder) { + super.encodeWithCoder(aCoder) + } + + /** + Subscript for the `UsergridDevice` class. Note that all of the `UsergridDeviceProperties` are immutable. + + - Warning: When setting a properties value must be a valid JSON object. + + - Example usage: + ``` + let uuid = usergridDevice["uuid"] + ``` + */ + override public subscript(propertyName: String) -> AnyObject? { + get { + return super[propertyName] + } + set(propertyValue) { + if UsergridDeviceProperties.fromString(propertyName) == nil { + super[propertyName] = propertyValue + } + } + } + + // MARK: - Push Token Handling - + + /** + Sets the push token for the given notifier ID. + + This does not perform any API requests to update on Usergrid, rather it will just set the information in the `UsergridDevice` instance. + + In order to set the push token and perform an API request, use `UsergridClient.applyPushToken`. + + - parameter pushToken: The push token from Apple. + - parameter notifierID: The notifier ID. + */ + internal func applyPushToken(pushToken: NSData, notifierID: String) { + self[notifierID + USERGRID_NOTIFIER_ID_SUFFIX] = pushToken.description.stringByTrimmingCharactersInSet(NSCharacterSet(charactersInString: "<>")).stringByReplacingOccurrencesOfString(" ", withString: "") + } +} + +private let USERGRID_NOTIFIER_ID_SUFFIX = ".notifier.id"