import { readFile , writeFile } from 'fs' ; import { join } from 'path' ; import { BrowserWindow , app } from 'electron' ; import log from './log' ; import { OAuth } from 'oauth' ; const config_path = join ( app . getPath ( 'userData' ) , 'tokens.json' ) ; function authenticate_with_request_tokens ( oauth , request_token , request_token_secret ) { return new Promise ( ( resolve , reject ) => { let login_window = new BrowserWindow ( { width : 800 , height : 600 , webPreferences : { webSecurity : true , nodeIntegration : false , } , } ) as ( Electron . BrowserWindow | null ) ; login_window ! . webContents . on ( 'will-navigate' , ( event , url ) => { event . preventDefault ( ) ; log . debug ( 'Login window: will-navigate: ' , url ) ; const match = url . match ( /\?oauth_token=([^&]*)&oauth_verifier=([^&]*)/ ) ; if ( ! match ) { return ; } oauth . getOAuthAccessToken ( request_token , request_token_secret , match [ 2 ] , ( err , token , token_secret ) => { log . debug ( 'access token:' , token ) ; if ( err ) { setTimeout ( ( ) => login_window ! . close ( ) , 0 ) ; reject ( err ) ; return ; } const access = { token , token_secret , } ; resolve ( access ) ; writeFile ( config_path , JSON . stringify ( access ) , e => { if ( e ) { log . warn ( 'Failed to store tokens to a token.json' , e ) ; } login_window ! . close ( ) ; } ) ; } ) ; } ) ; login_window ! . on ( 'closed' , ( ) => { login_window = null ; } ) ; const login_url = `https://twitter.com/oauth/authenticate?oauth_token=${ request_token }` ; log . debug ( 'Start authentication:' , login_url ) ; login_window ! . loadURL ( login_url ) ; } ) ; } export function authenticate ( consumer_key , consumer_secret ) { return new Promise ( ( resolve , reject ) => { const oauth = new OAuth ( 'https://twitter.com/oauth/request_token' , 'https://twitter.com/oauth/access_token' , consumer_key , consumer_secret , '1.0A' , 'https://example.com' , 'HMAC-SHA1' ) ; oauth . getOAuthRequestToken ( ( err , token , token_secret ) => { log . debug ( 'Request token:' , token ) ; if ( err ) { reject ( err ) ; return ; } resolve ( authenticate_with_request_tokens ( oauth , token , token_secret ) ) ; } ) ; } ) ; } export function load_cached_tokens ( ) { if ( process . env . YOURFUKUROU_ACCESS_TOKEN && process . env . YOURFUKUROU_ACCESS_TOKEN_SECRET ) { log . debug ( 'Access tokens from environment variables:' , process . env . YOURFUKUROU_ACCESS_TOKEN ) ; return Promise . resolve ( { token : process . env . YOURFUKUROU_ACCESS_TOKEN , token_secret : process . env . YOURFUKUROU_ACCESS_TOKEN_SECRET , } ) ; } return new Promise ( ( resolve , reject ) => { readFile ( config_path , 'utf8' , ( err , str ) => { if ( err ) { log . debug ( 'Failed to load access token cache:' , config_path ) ; reject ( err ) ; return ; } log . debug ( 'Loaded access token cache' ) ; resolve ( JSON . parse ( str ) as AccessToken ) ; } ) ; } ) ; }