mirror of
https://github.com/tappollo/OSCKit.git
synced 2026-03-29 01:28:05 +08:00
68 lines
1.8 KiB
Swift
68 lines
1.8 KiB
Swift
//
|
|
// Session.swift
|
|
// ThreeSixtyCamera
|
|
//
|
|
// Created by Zhigang Fang on 4/18/17.
|
|
// Copyright © 2017 Tappollo Inc. All rights reserved.
|
|
//
|
|
|
|
import Foundation
|
|
import SwiftyyJSON
|
|
import PromiseKit
|
|
import AwaitKit
|
|
|
|
public struct Session {
|
|
let id: String
|
|
let expires: Date
|
|
|
|
fileprivate static var currentSession: Session?
|
|
|
|
init (json: JSON) throws {
|
|
self.id = try json["results"]["sessionId"].string !! OSCKit.SDKError.unableToParse(json)
|
|
let expire = try json["results"]["timeout"].int !! OSCKit.SDKError.unableToParse(json)
|
|
self.expires = Date().addingTimeInterval(TimeInterval(expire))
|
|
}
|
|
|
|
var isExpired: Bool {
|
|
return self.expires < Date()
|
|
}
|
|
|
|
var wasJustedIssued: Bool {
|
|
return self.expires.addingTimeInterval(10) > Date()
|
|
}
|
|
}
|
|
|
|
extension OSCKit {
|
|
public var session: Promise<Session> {
|
|
if let currentSession = Session.currentSession {
|
|
if currentSession.wasJustedIssued {
|
|
return Promise(value: currentSession)
|
|
}
|
|
if currentSession.isExpired {
|
|
return startSession
|
|
}
|
|
return update(session: currentSession)
|
|
}
|
|
return startSession
|
|
}
|
|
|
|
var startSession: Promise<Session> {
|
|
return async {
|
|
let response = try await(self.execute(command: .startSession))
|
|
return try Session(json: response)
|
|
}
|
|
}
|
|
|
|
func update(session: Session) -> Promise<Session> {
|
|
return async {
|
|
do {
|
|
let response = try await(self.execute(command: .updateSession(sessionId: session.id)))
|
|
return try Session(json: response)
|
|
} catch {
|
|
return try await(self.startSession)
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|