1+ import { client } from './twitch'
2+
3+ import * as OAuth2 from '../../modules/twitch/oauth2'
4+
5+ function alternativeFlow ( element ) {
6+ const tokenDialog = element . querySelector ( 'dialog.token' )
7+ element . querySelector ( 'a.twitch' ) . addEventListener ( 'click' , event => {
8+ tokenDialog . showModal ( )
9+ window . invokeNative ( 'openUrl' ,
10+ OAuth2 . authorize (
11+ `${ location . origin } ${ location . pathname } ` , /** @todo external website */
12+ client . client_id ,
13+ client . scopes
14+ )
15+ )
16+ } )
17+ const errorElement = tokenDialog . querySelector ( 'form div.error' )
18+ tokenDialog . querySelector ( 'form' ) . addEventListener ( 'submit' , event => {
19+ event . preventDefault ( )
20+ const { target : [ input , submit ] } = event
21+ const { value : token } = input
22+ if (
23+ ! token
24+ || token === 'Bearer '
25+ || ! token . startsWith ( 'Bearer ' )
26+ ) return errorElement . innerText = 'Invalid authorization token'
27+ submit . disabled = true
28+ submit . value = 'Validating...'
29+ OAuth2 . validate ( token ) . then ( response => {
30+ submit . value = 'Connect'
31+ input . addEventListener ( 'input' , ( ) => submit . disabled = false , { once : true } )
32+ if ( response . status )
33+ return errorElement . innerText = `${ response . status } - ${ response . message } `
34+ localStorage . setItem ( 'tts_twitch_token' , token )
35+ location . reload ( )
36+ } )
37+ } )
38+ }
39+
40+ function authorizationFlow ( error ) {
41+ const element = document . importNode (
42+ document . head . querySelector ( 'template#authorize' ) . content ,
43+ true
44+ )
45+
46+ if ( error )
47+ element . querySelector ( 'div.error' ) . innerText = error
48+
49+ if ( window . invokeNative )
50+ alternativeFlow ( client , element )
51+ else
52+ element . querySelector ( 'a.twitch' ) . href =
53+ OAuth2 . authorize (
54+ `${ location . origin } ${ location . pathname } ` ,
55+ client . client_id ,
56+ client . scopes
57+ )
58+
59+ document . body . replaceChildren ( element )
60+ }
61+
62+ export default function ( ) {
63+ const response = OAuth2 . response ( )
64+
65+ if ( response && ! client . token )
66+ localStorage . setItem ( 'tts_twitch_token' , client . token = response . token )
67+
68+ if ( client . token )
69+ OAuth2 . validate ( client . token ) . then ( response => {
70+ const error = response . status
71+ ? `${ response . status } - ${ response . message } `
72+ : ! OAuth2 . compareScopes ( client . scopes , response . scopes )
73+ ? 'Scopes changed, please reauthorize.'
74+ : client . connect ( client . user_id = response . user_id )
75+ if ( ! error ) return
76+ localStorage . removeItem ( 'tts_twitch_token' )
77+ authorizationFlow ( error )
78+ } )
79+ else
80+ authorizationFlow ( OAuth2 . error ( ) )
81+ }
0 commit comments