summaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
Diffstat (limited to 'src')
-rw-r--r--src/twitcr.cr2
-rw-r--r--src/twitcr/client.cr7
-rw-r--r--src/twitcr/mappings/token.cr7
-rw-r--r--src/twitcr/rest.cr22
4 files changed, 33 insertions, 5 deletions
diff --git a/src/twitcr.cr b/src/twitcr.cr
index 0d63180..9bb13cf 100644
--- a/src/twitcr.cr
+++ b/src/twitcr.cr
@@ -1,5 +1,5 @@
require "./twitcr/**"
module Twitcr
- VERSION = "0.2.0"
+ VERSION = "0.3.0"
end
diff --git a/src/twitcr/client.cr b/src/twitcr/client.cr
index 74b2a80..51dedad 100644
--- a/src/twitcr/client.cr
+++ b/src/twitcr/client.cr
@@ -4,11 +4,12 @@ require "./mappings/*"
class Twitcr::Client
include REST
- getter token : String
+ getter token : String?
getter client_id : String
+ getter client_secret : String
- def initialize(@token, @client_id)
- @token = "Bearer" + @token
+ def initialize(@client_secret, @client_id)
+ @token = nil
end
def user?(name : String)
diff --git a/src/twitcr/mappings/token.cr b/src/twitcr/mappings/token.cr
new file mode 100644
index 0000000..a141a68
--- /dev/null
+++ b/src/twitcr/mappings/token.cr
@@ -0,0 +1,7 @@
+struct Twitcr::Token
+ JSON.mapping({
+ access_token: String,
+ expires_in: Int64,
+ token_type: String
+ })
+end
diff --git a/src/twitcr/rest.cr b/src/twitcr/rest.cr
index 1de8d6f..cb2c1a0 100644
--- a/src/twitcr/rest.cr
+++ b/src/twitcr/rest.cr
@@ -11,7 +11,9 @@ module Twitcr::REST
# Executes an HTTP request against the API_BASE url
def request(method : String, route : String, version = "5", headers = HTTP::Headers.new, body : String? = nil)
- headers["Authorization"] = @token
+ get_token unless @token
+
+ headers["Authorization"] = @token || "test"
headers["Client-ID"] = @client_id
response = HTTP::Client.exec(
@@ -21,6 +23,12 @@ module Twitcr::REST
tls: SSL_CONTEXT
)
+ if response.status_code == 401
+ get_token
+ puts "Had to get new token"
+ return request(method, route, version, headers, body)
+ end
+
response.body
end
@@ -47,4 +55,16 @@ module Twitcr::REST
list.data.first
end
+
+ def get_token
+ response = HTTP::Client.exec(
+ "POST",
+ "https://id.twitch.tv/oauth2/token?client_id=#{@client_id}&client_secret=#{@client_secret}&grant_type=client_credentials",
+ tls: SSL_CONTEXT
+ )
+
+ access_token = Token.from_json(response.body).access_token
+
+ @token = "Bearer #{access_token}"
+ end
end