mirror of
https://bitbucket.org/vendoo/vendoo_v1.0.git
synced 2025-12-25 19:57:41 +00:00
369 lines
15 KiB
Swift
369 lines
15 KiB
Swift
//
|
|
// EtsyRESTConnectionManager.swift
|
|
// Vendoo
|
|
//
|
|
// Created by Okechi Onyeje on 5/25/16.
|
|
// Copyright © 2016 Okechi Onyeje. All rights reserved.
|
|
//
|
|
|
|
//NOT ABLE TO CAPTURE NEEDED DATA FROM RESPONSE IN OAUTH PROCESS FOR ETSY
|
|
|
|
import Foundation
|
|
import SwiftyJSON
|
|
import OAuthSwift
|
|
import Locksmith
|
|
import AFNetworking
|
|
|
|
|
|
typealias ServiceResponse = (JSON, NSError?) -> Void
|
|
|
|
|
|
class EtsyRESTAPIManager: NSObject {
|
|
|
|
//API Manager class variables
|
|
//----------------------------------------------//
|
|
static let sharedInstance = EtsyRESTAPIManager()
|
|
|
|
|
|
|
|
let baseURL = "https://openapi.etsy.com/v2/private"
|
|
|
|
private var apiKey: String!
|
|
private var apiSecret: String!
|
|
private var userEmail:String = (NSUserDefaults.standardUserDefaults().objectForKey("email") as? String)!
|
|
var isAuthorized: Bool = NSUserDefaults.standardUserDefaults().boolForKey("etsyAuthorized")
|
|
//---------------------------------------------//
|
|
|
|
//User specific class variables
|
|
private var etsyUser: String!
|
|
private var oauthswift: OAuth1Swift!
|
|
//private let oauthswift = OAuth1Swift(parameters: ["consumerKey":"snbs78qkfy3yqq6yhe6yv49b","consumerSecret":"4sbva4oqb6", "requestTokenUrl": "https://openapi.etsy.com/v2/oauth/request_token?scope=listings_w%20listings_r%20listings_d%20transactions_r%20transactions_w%20"])
|
|
|
|
override init(){
|
|
if let path = NSBundle.mainBundle().pathForResource("Services", ofType: "plist"), dict = NSDictionary(contentsOfFile: path) as? [String: AnyObject] {
|
|
// use swift dictionary as normal
|
|
|
|
self.apiKey = ((dict["Etsy"] as! Dictionary<String, AnyObject>)["consumerKey"] as! String)
|
|
self.apiSecret = ((dict["Etsy"] as! Dictionary<String, AnyObject>)["consumerSecret"] as! String)
|
|
|
|
|
|
oauthswift = OAuth1Swift(parameters: ["consumerKey":self.apiKey,"consumerSecret":self.apiSecret, "requestTokenUrl" : "https://openapi.etsy.com/v2/oauth/request_token?scope=listings_w%20listings_r%20listings_d%20transactions_r%20transactions_w",
|
|
"authorizeUrl": "https://www.etsy.com/oauth/signin?",
|
|
"accessTokenUrl": "https://openapi.etsy.com/v2/oauth/access_token?",
|
|
"responseType": "token"])
|
|
|
|
|
|
//something is wrong when here when logging back in with a diff user
|
|
if(self.isAuthorized){
|
|
let dictionary = Locksmith.loadDataForUserAccount(self.userEmail, inService: "vendoo_oauth_etsy")
|
|
let oauthDictionary = dictionary?["etsy_oauth"] as? Dictionary<String, AnyObject!>
|
|
print((oauthDictionary?["token"] as? String!)!)
|
|
self.oauthswift.client.credential.oauth_token = (oauthDictionary?["token"] as? String!)!
|
|
self.oauthswift.client.credential.oauth_token_secret = (oauthDictionary?["secret"] as? String!)!
|
|
}
|
|
|
|
/*scope=listings_w%20listings_r%20listings_d%20transactions_r%20transactions_w"*/
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
//Mark: - OAuth Methods
|
|
extension EtsyRESTAPIManager {
|
|
|
|
//makes application ready for use with users etsy account
|
|
func authorizeApp(viewcontroller: UIViewController){
|
|
var boolResult: Bool!
|
|
|
|
|
|
|
|
if(!isAuthorized){
|
|
|
|
|
|
oauthswift!.authorize_url_handler = SafariURLHandler(viewController: viewcontroller)
|
|
|
|
/*
|
|
let authRequest = self.oauthswift.client.makeRequest("https://openapi.etsy.com/v2/oauth/request_token?", method: OAuthSwiftHTTPRequest.Method.GET, parameters: ["scope":"listings_w%20listings_r%20listings_d%20transactions_r%20transactions_w"] , headers: nil)
|
|
|
|
do{
|
|
|
|
try authRequest?.makeRequest()
|
|
|
|
|
|
}catch{
|
|
(error)
|
|
}
|
|
*/
|
|
|
|
/*["scope":"listings_w%20listings_r%20listings_d%20transactions_r%20transactions_w"]*/
|
|
self.oauthswift!.client.get("https://openapi.etsy.com/v2/oauth/request_token?scope=listings_w%20listings_r%20listings_d%20transactions_r%20transactions_w",
|
|
success: {
|
|
data, response in
|
|
|
|
let dataString = NSString(data: data, encoding: NSUTF8StringEncoding)
|
|
|
|
|
|
|
|
//print(response.allHeaderFields)
|
|
//print(dataSting)
|
|
let json = JSON(data)
|
|
print(json)
|
|
print(dataString)
|
|
|
|
|
|
|
|
self.oauthswift!.authorizeWithCallbackURL( NSURL(string: "vendoo://oauth-callback/etsy")!, success: {
|
|
credential, response, parameters in
|
|
print(credential.oauth_token)
|
|
print(credential.oauth_token_secret)
|
|
|
|
print(response)
|
|
boolResult = false
|
|
|
|
|
|
}, failure: { error in
|
|
//print(error)
|
|
|
|
dispatch_async(dispatch_get_main_queue(), {() -> Void in
|
|
print(self.oauthswift!.client.credential.oauth_token)
|
|
print(self.oauthswift!.client.credential.oauth_token_secret)
|
|
print(self.oauthswift.allowMissingOauthVerifier = true)
|
|
//save data to keychain
|
|
let creds = self.oauthswift?.client.credential
|
|
let oauth: Dictionary<String, AnyObject!>? = [ "token" : creds!.oauth_token, "secret" : creds!.oauth_token_secret ]
|
|
do{
|
|
try Locksmith.saveData(["etsy_oauth" : oauth!], forUserAccount: self.userEmail, inService: "vendoo_oauth_etsy")
|
|
print("account credentials saved")
|
|
NSUserDefaults.standardUserDefaults().setBool(true, forKey: "etsyAuthorized")
|
|
self.isAuthorized = true
|
|
boolResult = true
|
|
|
|
self.oauthswift!.client.get("https://openapi.etsy.com/v2/oauth/scopes",
|
|
success: {
|
|
data, response in
|
|
let dataString = NSString(data: data, encoding: NSUTF8StringEncoding)
|
|
print(dataString)
|
|
boolResult = true
|
|
}
|
|
, failure: { error in
|
|
print(error)
|
|
boolResult = true
|
|
}
|
|
)
|
|
}
|
|
catch{
|
|
(error)
|
|
print(error)
|
|
//could not save data to keychain
|
|
print("account credentials could not be saved")
|
|
boolResult = false
|
|
|
|
}
|
|
|
|
//return boolResult
|
|
|
|
})
|
|
})
|
|
|
|
//getting error here when trying to retrieve the login url from the response
|
|
//var dataDictionary = self.convertStringToDictionary(dataString! as String)
|
|
//print(dataDictionary!["login_url"])
|
|
}
|
|
, failure: { error in
|
|
print(error)
|
|
}
|
|
)
|
|
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
//once everything is authorized save true value to the authorization boolean
|
|
/*
|
|
NSUserDefaults.standardUserDefaults().setBool(true, forKey: "etsyAuthorized")
|
|
self.isAuthorized = NSUserDefaults.standardUserDefaults().boolForKey("etsyAuthorized")
|
|
*/
|
|
}
|
|
|
|
|
|
func deAuthorizeApp(viewcontroller: UIViewController){
|
|
|
|
|
|
|
|
|
|
|
|
oauthswift!.authorize_url_handler = SafariURLHandler(viewController: viewcontroller)
|
|
oauthswift!.client.get("https://openapi.etsy.com/v2/oauth/request_token?scope=listings_w%20listings_r%20listings_d%20transactions_r%20transactions_w",
|
|
success: {
|
|
data, response in
|
|
let dataString = NSString(data: data, encoding: NSUTF8StringEncoding)
|
|
print(dataString!)
|
|
print(response)
|
|
|
|
|
|
|
|
|
|
//getting error here when trying to retrieve the login url from the response
|
|
//var dataDictionary = self.convertStringToDictionary(dataString! as String)
|
|
//print(dataDictionary!["login_url"])
|
|
}
|
|
, failure: { error in
|
|
print(error)
|
|
}
|
|
)
|
|
|
|
dispatch_async(dispatch_get_main_queue(), {() -> Void in
|
|
|
|
|
|
self.oauthswift!.authorizeWithCallbackURL( NSURL(string: "vendoo://oauth-callback/etsy")!, success: {
|
|
credential, response, parameters in
|
|
print(credential.oauth_token)
|
|
print(credential.oauth_token_secret)
|
|
print(response)
|
|
|
|
//erase all authorization variables
|
|
do {
|
|
try Locksmith.deleteDataForUserAccount(self.userEmail, inService: "vendoo_oauth_etsy")
|
|
self.oauthswift.client.credential.oauth_token = ""
|
|
self.oauthswift.client.credential.oauth_token_secret = ""
|
|
NSUserDefaults.standardUserDefaults().setBool(false, forKey: "etsyAuthorized")
|
|
self.isAuthorized = false
|
|
|
|
print("oauth credentials deleted and app deauthorized from etsy")
|
|
}catch{
|
|
(error)
|
|
print(error)
|
|
("failed to delete credentails and deauthorize app")
|
|
}
|
|
|
|
|
|
}, failure: { error in
|
|
print(error)
|
|
|
|
dispatch_async(dispatch_get_main_queue(), {() -> Void in
|
|
|
|
//erase all authorization variables
|
|
do {
|
|
try Locksmith.deleteDataForUserAccount(self.userEmail, inService: "vendoo_oauth_etsy")
|
|
self.oauthswift.client.credential.oauth_token = ""
|
|
self.oauthswift.client.credential.oauth_token_secret = ""
|
|
NSUserDefaults.standardUserDefaults().setBool(false, forKey: "etsyAuthorized")
|
|
self.isAuthorized = false
|
|
|
|
print("oauth credentials deleted and app deauthorized from etsy")
|
|
}catch{
|
|
(error)
|
|
print(error)
|
|
("failed to delete credentails and deauthorize app")
|
|
}
|
|
|
|
})
|
|
|
|
})
|
|
})
|
|
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
//MARK: - Request Methods
|
|
extension EtsyRESTAPIManager {
|
|
func generateUserRequest(etsyName: String!, etsyOptions: [String]!) -> String {
|
|
|
|
//starting url for user request to api
|
|
var userRequest: String!
|
|
|
|
if(etsyName == nil || etsyName == ""){
|
|
userRequest = (baseURL + "/users/etsystore?")
|
|
}
|
|
else{
|
|
userRequest = (baseURL + "/users/" + etsyName + "?")
|
|
}
|
|
|
|
//final api request
|
|
return userRequest + "api_key=" + self.apiKey
|
|
}
|
|
|
|
func generateListingRequest(etsyListing: String!){
|
|
|
|
//starting url for listing request
|
|
}
|
|
|
|
//sends the pregenerated url as a request to api service
|
|
func sendGETRequest(request: String, onCompletion: ServiceResponse) {
|
|
let request = NSMutableURLRequest(URL: NSURL(string: request)!)
|
|
|
|
let session = NSURLSession.sharedSession()
|
|
|
|
let task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
|
|
if let jsonData = data {
|
|
let json:JSON = JSON(data: jsonData)
|
|
onCompletion(json, error)
|
|
} else {
|
|
onCompletion(nil, error)
|
|
}
|
|
})
|
|
task.resume()
|
|
}
|
|
|
|
//sends the pregenerated url as a request to api service
|
|
func sendPOSTRequest(request: String, body: [String: AnyObject], onCompletion: ServiceResponse) {
|
|
let request = NSMutableURLRequest(URL: NSURL(string: request)!)
|
|
|
|
// Set the method to POST
|
|
request.HTTPMethod = "POST"
|
|
|
|
do {
|
|
// Set the POST body for the request
|
|
let jsonBody = try NSJSONSerialization.dataWithJSONObject(body, options: .PrettyPrinted)
|
|
request.HTTPBody = jsonBody
|
|
let session = NSURLSession.sharedSession()
|
|
|
|
let task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
|
|
if let jsonData = data {
|
|
let json:JSON = JSON(data: jsonData)
|
|
onCompletion(json, nil)
|
|
} else {
|
|
onCompletion(nil, error)
|
|
}
|
|
})
|
|
task.resume()
|
|
} catch {
|
|
// Create your personal error
|
|
onCompletion(nil, nil)
|
|
}
|
|
}
|
|
|
|
}
|
|
|
|
//MARK: - JSON Methods
|
|
extension EtsyRESTAPIManager {
|
|
|
|
func convertStringToDictionary(text: String) -> [String:AnyObject]? {
|
|
if let data = text.dataUsingEncoding(NSUTF8StringEncoding) {
|
|
do {
|
|
return try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments) as? [String:AnyObject]
|
|
} catch let error as NSError {
|
|
print(error)
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
}
|