-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAsahi.swift
566 lines (487 loc) · 21.9 KB
/
Asahi.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
//
// Asahi.swift (AKA Bellini)
// Absinthe-iOS
//
// Created by Noah on 7/19/16.
// Edits by Mitch Sept 2016
// Completely re-written for Swift 3/PromiseKit in Jan 2017
// Copyright © 2016 Ourglass TV. All rights reserved.
//
import Foundation
import Alamofire
import PromiseKit
import SwiftyJSON
/// Error class used with Asahi
///
/// - authFailure: the user is not authorized to perform the action
/// - tokenInvalid: the current token is invalid
/// - malformedJson: the response JSON was not as expected
enum AsahiError: Error {
case authFailure
case tokenInvalid
case malformedJson
}
/// The interface to the Ourglass Cloud Server aka Asahi aka Applejack
open class Asahi: NSObject {
static let sharedInstance = Asahi()
/// time to wait on the initial dispatch group to complete
let INIT_WAIT_TIME = 2.0
var _postNotification = false
let initGroup = DispatchGroup()
override init() {
super.init()
// throwaway call to set the Sails cookie
// put in DispatchGroup so we don't make any other calls until this completes
self.initGroup.enter()
self.checkJWT().always {
self.initGroup.leave()
}
}
/// Creates an API endpoint with the default base URL and default
/// port stored in Settings.
///
/// - Parameter endpoint: the endpoint to append to the base
/// - Returns: the complete API endpoint
// MAK: These don't work well with DNA named endpoints in front of NGINX
// func createApiEndpoint(_ endpoint: String) -> String {
// //return Settings.sharedInstance.ourglassCloudBaseUrl + ":" + Settings.sharedInstance.ourglassBasePort + endpoint
// return Settings.sharedInstance.ourglassCloudBaseUrl + ":" + Settings.sharedInstance.ourglassBasePort + endpoint
// }
/// Creates an API endpoing with the default base URL stored in
/// Settings and the provided port.
///
/// - Parameters:
/// - endpoint: endpoint to append to the base
/// - port: port
/// - Returns: the complete API endpoint
// func createApiEndpoint(_ endpoint: String, withPort port: String) -> String {
// return Settings.sharedInstance.ourglassCloudBaseUrl + ":" + port + endpoint
// }
/// Makes an HTTP request with Alamofire to get the JSON contents
/// of the response.
///
/// - Parameters:
/// - endpoint: the URL
/// - data: parameters to send
/// - method: the HTTP method
/// - encoding: the parameter encoding
/// - Returns: a promise resolving in the JSON contents of the response
func doJsonTransaction( _ endpoint: String,
data: Dictionary<String, Any>,
method: HTTPMethod,
encoding: ParameterEncoding) -> Promise<JSON> {
// wait for initial DispatchGroup to complete
_ = initGroup.wait(timeout: DispatchTime.now() + INIT_WAIT_TIME)
return Promise { fulfill, reject in
Alamofire.request(endpoint,
method: method,
parameters: data,
encoding: encoding,
headers: [ "Authorization" : "Bearer \(Settings.sharedInstance.userBelliniJWT ?? "")" ])
.validate()
.responseJSON() { response in
switch response.result {
case .success(let dict):
fulfill(JSON(dict))
case .failure(let error):
if let statusCode = response.response?.statusCode {
if statusCode == 403 {
Asahi.sharedInstance.checkJWT()
.then { response -> Void in
log.debug("\(statusCode): resource not allowed for this user")
reject(AsahiError.authFailure)
}
.catch { error -> Void in
log.debug("\(statusCode): token invalid")
reject(AsahiError.tokenInvalid)
}
} else {
reject(error)
}
} else {
reject(error)
}
}
}
}
}
/// Makes an HTTP request with Alamofire.
///
/// - Parameters:
/// - endpoint: the URL
/// - data: parameters to send
/// - method: the HTTP method
/// - encoding: the parameter encoding
/// - Returns: a promise resolving in `true` on success
func doTransaction( _ endpoint: String,
data: Dictionary<String, Any>,
method: HTTPMethod,
encoding: ParameterEncoding) -> Promise<Bool> {
// wait for initial DispatchGroup to complete
_ = initGroup.wait(timeout: DispatchTime.now() + INIT_WAIT_TIME)
return Promise { fulfill, reject in
Alamofire.request(endpoint,
method: method,
parameters: data,
encoding: encoding,
headers: [ "Authorization" : "Bearer \(Settings.sharedInstance.userBelliniJWT ?? "")" ])
.validate()
.responseData() { response in
switch response.result {
case .success( _):
fulfill(true)
case .failure(let error):
if let statusCode = response.response?.statusCode {
if statusCode == 403 {
Asahi.sharedInstance.checkJWT()
.then { response -> Void in
log.debug("\(statusCode): resource not allowed for this user")
reject(AsahiError.authFailure)
}
.catch { error -> Void in
log.debug("\(statusCode): token invalid")
reject(AsahiError.tokenInvalid)
}
} else {
reject(error)
}
} else {
reject(error)
}
}
}
}
}
/// Promisified JSON Poster.
func postJson( _ endpoint: String, data: Dictionary<String, Any> ) -> Promise<JSON> {
return doJsonTransaction(endpoint, data: data, method: .post,
encoding: JSONEncoding.default)
}
/// Promisified JSON Putter.
func putJson( _ endpoint: String, data: Dictionary<String, Any> ) -> Promise<JSON> {
return doJsonTransaction(endpoint, data: data, method: .put,
encoding: JSONEncoding.default)
}
/// Promisified JSON Getter.
func getJson(_ endpoint: String, parameters: [String: Any] = [:]) -> Promise<JSON> {
return doJsonTransaction(endpoint, data: parameters, method: .get,
encoding: URLEncoding.default)
}
/// Registers a new user, gets a token, and sets `Settings` user variables.
///
/// - Parameters:
/// - email: user's email
/// - password: user's password
/// - user: user's first and last name
/// - Returns: a promise resolving in the new user's JWT
func register(_ email: String, password: String, user: Dictionary<String, Any>)
-> Promise<String> {
let params: Dictionary<String, Any> = [
"email":email,
"password":password,
"user": user,
"type":"local"]
return postJson(Settings.sharedInstance.belliniCoreBaseUrl + "/auth/addUser",
data: params as Dictionary<String, AnyObject>)
.then{ _ -> Promise<String> in
Settings.sharedInstance.userEmail = email
return self.getToken()
}.then { token -> Promise<String> in
return self.checkSession().then {_ -> Promise<String> in
return token
}
}
}
/// Logs in to OurGlass, gets a token, and sets `Settings` user variables.
///
/// - Parameters:
/// - email: user email
/// - password: user password
/// - Returns: a promise resolving in the user's JWT
func login(_ email: String, password: String) -> Promise<String> {
return loginOnly(email, password: password).then { _ -> Promise<String> in
return self.getToken()
}.then { token -> Promise<String> in
return self.checkSession().then {_ -> Promise<String> in
return token
}
}
}
// TODO: sign in with Facebook (use "type": "facebook" on login and register)
/// Logs in to Ourglass without getting a JWT.
///
/// - Parameters:
/// - email: user email
/// - password: user password
/// - Returns: a promise resolving in `true` on success
func loginOnly(_ email: String, password: String) -> Promise<Bool> {
// TODO: MAK This should be replaced with a proper JSON login endpoint (see above)
let params: Dictionary<String, Any> = [
"email":email,
"password":password,
"type":"local"]
return postJson( Settings.sharedInstance.belliniCoreBaseUrl + "/auth/login", data: params)
.then{ response -> Bool in
Settings.sharedInstance.userEmail = email
ASNotification.asahiLoggedIn.issue()
return true
}
}
/// Gets a JWT.
///
/// - Returns: a promise resolving in the JWT
func getToken() -> Promise<String> {
return getJson( Settings.sharedInstance.belliniCoreBaseUrl + "/user/jwt")
.then{ response -> String in
guard let token = response["token"].string,
let expires = response["expires"].double else {
throw AsahiError.malformedJson
}
Settings.sharedInstance.userBelliniJWT = token
Settings.sharedInstance.userBelliniJWTExpiry = expires / 1000.0
return token
}
}
/// Checks the user's current JWT to see if it is still valid.
///
/// - Returns: a promise resolving in the response JSON
func checkJWT() -> Promise<JSON> {
// wait for initial DispatchGroup to complete
_ = initGroup.wait(timeout: DispatchTime.now() + INIT_WAIT_TIME)
// cannot use same getJson() as everyone else or we might end up in a loop on 403 error handling
return Promise { fulfill, reject in
Alamofire.request( Settings.sharedInstance.belliniCoreBaseUrl + "/user/checkjwt",
method: .get,
headers: ["Authorization" : "Bearer \(Settings.sharedInstance.userBelliniJWT ?? "")" ])
.validate()
.responseJSON() { response in
switch response.result {
case .success(let dict):
let response = JSON(dict)
guard let id = response["id"].string,
let first = response["firstName"].string,
let last = response["lastName"].string,
let email = response["email"].string else {
log.error("unable to get user info from /user/checkjwt")
fulfill(response)
return
}
Settings.sharedInstance.userId = id
Settings.sharedInstance.userFirstName = first
Settings.sharedInstance.userLastName = last
Settings.sharedInstance.userEmail = email
fulfill(response)
case .failure(let error):
reject(error)
}
}
}
}
/// Checks the current user's session and stores user info if it finds it.
///
/// - Returns: a promise resolving in the response JSON
func checkSession() -> Promise<JSON> {
return getJson( Settings.sharedInstance.belliniCoreBaseUrl + "/user/checksession")
.then { response -> JSON in
guard let id = response["id"].string,
let first = response["firstName"].string,
let last = response["lastName"].string,
let email = response["email"].string else {
log.error("unable to get user info from /user/checksession")
return response
}
Settings.sharedInstance.userId = id
Settings.sharedInstance.userFirstName = first
Settings.sharedInstance.userLastName = last
Settings.sharedInstance.userEmail = email
return response
}
}
/// Gets all venues.
///
/// - Returns: a promise resolving in the response JSON which contains the venues
func getVenues() -> Promise<JSON> {
return getJson( Settings.sharedInstance.belliniCoreBaseUrl + "/venue/all" )
}
/// Gets the venues associated with the current user.
///
/// - Returns: a promise resolving in the venues JSON
func getUserVenues() -> Promise<JSON> {
return getJson( Settings.sharedInstance.belliniCoreBaseUrl + "/venue/myvenues" )
}
/// Gets the devices associated with a venue.
///
/// - Parameter venueUUID: venue's UUID
/// - Returns: a promise resolving in the response JSON
func getDevices(_ venueUUID: String) -> Promise<JSON> {
return getJson( Settings.sharedInstance.belliniDMBaseUrl + "/venue/devices?atVenueUUID=" + venueUUID )
}
/// Changes account information of a user.
///
/// - Parameters:
/// - firstName: new first name
/// - lastName: new last name
/// - email: new email
/// - userId: the user's ID
/// - Returns: a promise resolving in the response JSON
func changeAccountInfo(_ firstName: String, lastName: String, email: String, userId: String) -> Promise<JSON> {
let params: Dictionary<String, Any> = ["email": email, "firstName": firstName, "lastName": lastName]
return putJson( Settings.sharedInstance.belliniCoreBaseUrl + "/user/\(userId)", data: params)
}
/// Changes the password of the user.
///
/// - Parameters:
/// - email: user's email
/// - newPassword: new password
/// - Returns: a promise resolving in `true` on success
func changePassword(_ email: String, newPassword: String) -> Promise<Bool> {
let params = ["email": email, "newpass": newPassword]
return postJson( Settings.sharedInstance.belliniCoreBaseUrl + "/auth/changePwd", data: params)
.then{ json -> Bool in
return true
}
}
/// Logs out of OurGlass by removing stored information.
func logout() { // TODO: is there more we need to do here?
Settings.sharedInstance.userBelliniJWT = nil
Settings.sharedInstance.userBelliniJWTExpiry = nil
Settings.sharedInstance.userId = nil
}
/// Invites someone to OurGlass via email.
///
/// - Parameter email: invitee's email
/// - Returns: a promise resolving in the response JSON
func inviteNewUser(_ email: String) -> Promise<Bool> {
let params = ["email": email]
//return postJson(createApiEndpoint("/user/inviteNewUser"), data: params)
return doTransaction( Settings.sharedInstance.belliniCoreBaseUrl + "/user/inviteNewUser",
data: params, method: .post, encoding: JSONEncoding.default)
}
/// Finds a device by its registration code.
///
/// - Parameter regCode: registration code
/// - Returns: a promise resolving in the device JSON
func findByRegCode(_ regCode: String) -> Promise<JSON> {
let params = ["regcode": regCode]
return getJson( Settings.sharedInstance.belliniDMBaseUrl + "/ogdevice/findByRegCode",
parameters: params)
}
/// Changes the name of the device associated with `udid`.
///
/// - Parameters:
/// - udid: device UDID
/// - name: name to give the device
/// - Returns: a promise resolving in the device's `udid`
func changeDeviceName(_ udid: String, name: String) -> Promise<String> {
let params = ["deviceUDID": udid, "name": name]
return postJson( Settings.sharedInstance.belliniDMBaseUrl + "/ogdevice/changeName",
data: params)
.then { _ -> String in
ASNotification.asahiUpdatedDevice.issue()
return udid
}
}
/// Associates a device with a venue.
///
/// - Parameters:
/// - deviceUdid: device UDID
/// - withVenueUuid: venue UUID
/// - Returns: a promise resolving in the JSON response from the call
func associate(deviceUdid: String, withVenueUuid: String) -> Promise<JSON> {
let params = ["deviceUDID": deviceUdid, "venueUUID": withVenueUuid]
return postJson( Settings.sharedInstance.belliniDMBaseUrl + "/ogdevice/associateWithVenue",
data: params)
.then { response -> JSON in
ASNotification.asahiUpdatedDevice.issue()
return response
}
}
/// Performs a Yelp search.
///
/// - Parameters:
/// - location: location of the search
/// - term: search term
/// - Returns: a promise resolving in a JSON array of the results
func yelpSearch(location: String, term: String) -> Promise<JSON> {
let params = ["location": location, "term": term]
return getJson( Settings.sharedInstance.belliniCoreBaseUrl + "/venue/yelpSearch", parameters: params)
}
/// Performs a Yelp search.
///
/// - Parameters:
/// - latitude: latitude of search location
/// - longitude: longitude of search location
/// - term: search term
/// - Returns: a promise resolving in a JSON array of the results
func yelpSearch(latitude: Double, longitude: Double, term: String) -> Promise<JSON> {
let params = ["latitude": latitude, "longitude": longitude, "term": term] as [String : Any]
return getJson( Settings.sharedInstance.belliniCoreBaseUrl + "/venue/yelpSearch", parameters: params)
}
/// Creates a new venue.
///
/// - Parameter venue: the venue to create
/// - Returns: a promise resolving in the new venue's uuid
func addVenue(venue: OGVenue) -> Promise<String> {
let params: [String: Any] = [
"name": venue.name,
"address": [
"street": venue.street,
"street2": venue.street2,
"city": venue.city,
"state": venue.state,
"zip": venue.zip
],
"geolocation": [
"latitude": venue.latitude,
"longitude": venue.longitude
],
"yelpId": venue.yelpId
]
return postJson( Settings.sharedInstance.belliniCoreBaseUrl + "/venue", data: params)
.then { response -> String in
guard let uuid = response["uuid"].string else {
throw AsahiError.malformedJson
}
ASNotification.asahiAddedVenue.issue()
return uuid
}
}
// MARK Test Methods
//TODO these are probably shite with all the casts to NSError no longer needed
func testRegistration(){
// Create unique email
let email = "absinthe-\(Date().timeIntervalSince1970)@test.com"
register(email, password: "yah00die", user: [ "firstName":"Dick", "lastName":"Yahoodie"])
.then { response -> Void in
log.debug("Well, I got a response regging: \(response)")
}
.catch { ( err: Error ) -> Void in
log.debug("hmm, that sucks")
let nse = err as NSError
log.error("\(nse.localizedDescription)")
}
}
// MARK Assumes "[email protected]/ab5inth3" exists in the system
func testLogin(){
login("[email protected]", password: "ab5inth3")
.then { response -> Void in
log.debug("Well, I got a response logging in: \(response)")
}
.catch { ( err: Error ) -> Void in
log.debug("hmm, that sucks")
let nse = err as NSError
log.error("\(nse.localizedDescription)")
}
}
func testGetVenues(){
getVenues()
.then { response -> Void in
log.debug("Well, I got a response logging in: \(response)")
}
.catch { ( err: Error ) -> Void in
log.debug("hmm, that sucks")
let nse = err as NSError
log.error("\(nse.localizedDescription)")
}
}
}