inoreader2readwise/app/main.py

216 lines
6.8 KiB
Python
Raw Normal View History

2024-01-24 11:29:35 +00:00
import os
2024-01-30 06:02:03 +00:00
from flask import Flask, render_template, request, redirect, abort, url_for, session
2024-01-24 11:29:35 +00:00
import requests
2024-01-24 13:55:17 +00:00
from datetime import datetime
2024-01-24 11:29:35 +00:00
def get_env_variable(var_name):
value = os.environ.get(var_name)
if not value:
raise ValueError(f"Missing required environment variable: {var_name}")
return value
app = Flask(__name__)
# Read environment variables outside the route function
client_id = get_env_variable('CLIENT_ID')
2024-01-31 06:31:28 +00:00
client_secret = get_env_variable('CLIENT_SECRET')
2024-01-24 11:29:35 +00:00
redirect_uri = get_env_variable('REDIRECT_URI')
optional_scopes = get_env_variable('OPTIONAL_SCOPES')
database_url = get_env_variable('DATABASE_URL')
2024-01-30 06:08:58 +00:00
secret_key = get_env_variable('APP_SECRET_KEY')
# Set secret key to enable sessions
app.secret_key = secret_key
2024-01-24 11:29:35 +00:00
csrf_protection_string = None
@app.route('/')
def home():
if is_logged_in():
token_id = session.get('token_id')
resp = requests.get(f'{database_url}/token/{token_id}')
raise_for_status(resp)
resp_json = resp.json()
token = resp_json['token']
2024-01-30 06:02:03 +00:00
2024-01-30 05:25:52 +00:00
user_info = requests.get('https://api.github.com/user', headers={
'Authorization': f'Bearer {token.get("access_token")}'
2024-01-30 05:25:52 +00:00
}).json()
2024-01-30 16:47:08 +00:00
last_synced = datetime.fromtimestamp(token.get('updated_at')).strftime('%Y-%m-%d %H:%M:%S')
next_sync = datetime.fromtimestamp(token.get('updated_at') + token.get('expiration_seconds')).strftime('%Y-%m-%d %H:%M:%S')
2024-02-01 10:55:04 +00:00
return render_template('home.html', user_login=user_info.login, user_email=user_info.email, # for inoreader it's userName
2024-01-30 17:36:16 +00:00
readwise_api_key=token.get('readwise_api_key') or '',
last_synced=last_synced, next_sync=next_sync)
2024-01-24 11:29:35 +00:00
# Generate a CSRF protection string
global csrf_protection_string
csrf_protection_string = os.urandom(16).hex()
# Pass dynamic variables to the template
return render_template('login.html', client_id=client_id, redirect_uri=redirect_uri,
2024-01-24 11:29:35 +00:00
optional_scopes=optional_scopes, csrf_protection_string=csrf_protection_string)
@app.route('/oauth-redirect')
def oauth_redirect():
auth_code = request.args.get('code')
csrf_token = request.args.get('state')
# Verify the CSRF protection string
if csrf_token != csrf_protection_string:
abort(400, 'Invalid CSRF token. Please try again.')
# Exchange authorization code for access and refresh tokens
2024-01-30 05:25:52 +00:00
# response = requests.post(
# 'https://www.inoreader.com/oauth2/token',
# headers={
# 'Content-Type': 'application/x-www-form-urlencoded',
# },
# data={
# 'code': auth_code,
2024-01-31 06:31:28 +00:00
# 'redirect_uri': redirect_uri,
# 'client_id': client_id,
# 'client_secret': client_secret,
2024-01-30 05:25:52 +00:00
# 'scope': '',
# 'grant_type': 'authorization_code'
# }
# )
# TEST: Github OAuth - REMOVE
2024-01-24 11:29:35 +00:00
response = requests.post(
2024-01-30 05:25:52 +00:00
'https://github.com/login/oauth/access_token',
2024-01-24 11:29:35 +00:00
headers={
2024-01-30 05:25:52 +00:00
'Accept': 'application/json'
2024-01-24 11:29:35 +00:00
},
data={
'code': auth_code,
2024-01-31 06:31:28 +00:00
'redirect_uri': redirect_uri,
'client_id': client_id,
'client_secret': client_secret,
2024-01-24 11:29:35 +00:00
}
)
raise_for_status(response)
2024-01-24 11:29:35 +00:00
token = response.json()
2024-01-24 11:29:35 +00:00
2024-01-30 05:25:52 +00:00
# TEST: Github OAuth - REMOVE
token['refresh_token'] = 'N/A'
token['expires_in'] = 3600
2024-01-30 05:25:52 +00:00
2024-01-31 06:16:41 +00:00
# REPLACE user API call with inoreader API call
# https://www.inoreader.com/reader/api/0/user-info
user_info = requests.get('https://api.github.com/user', headers={
'Authorization': f'Bearer {token.get("access_token")}'
}).json()
2024-01-24 11:29:35 +00:00
# Save tokens for later use
token_id = save_token(
user_info.get('email'), # for inoreader it's userEmail
token.get('access_token'),
token.get('refresh_token'),
token.get('expires_in')
)
2024-01-24 11:29:35 +00:00
set_session_token_id(token_id)
2024-01-30 06:02:03 +00:00
return redirect(url_for('home'))
# logout
2024-01-30 06:11:58 +00:00
@app.route('/logout', methods=['POST'])
2024-01-30 06:02:03 +00:00
def logout():
token_id = session.get('token_id')
if not token_id:
return redirect(url_for('home'))
# remove token_id from session
session.pop('token_id', None)
# response = requests.put(f'{database_url}/token/{token_id}', headers={
# 'Content-Type': 'application/json'
# }, json={
# 'is_logged_in': False
# })
# response.raise_for_status()
return redirect(url_for('home'))
@app.route('/readwise', methods=['POST'])
def submit_readwise_api():
token_id = session.get('token_id')
if not token_id:
return redirect(url_for('home'))
2024-01-30 06:02:03 +00:00
response = requests.put(f'{database_url}/token/{token_id}', headers={
'Content-Type': 'application/json'
}, json={
'readwise_api_key': request.form.get('readwise_api_key')
2024-01-30 06:02:03 +00:00
})
raise_for_status(response)
2024-01-30 06:02:03 +00:00
return redirect(url_for('home'))
2024-01-24 11:29:35 +00:00
def is_logged_in():
token_id = session.get('token_id')
if not token_id:
2024-01-24 11:29:35 +00:00
return False
response = requests.get(f'{database_url}/token/{token_id}')
raise_for_status(response)
resp_json = response.json()
token = resp_json['token']
return token.get('active', False)
def save_token(email, access_token, refresh_token, expiration_seconds):
2024-01-30 16:47:08 +00:00
# check if an active token with this email already exists
token_by_email_resp = requests.get(f'{database_url}/token?email={email}')
raise_for_status(token_by_email_resp)
if token_by_email_resp.status_code != 200:
response = requests.post(
f'{database_url}/token',
headers={
'Content-Type': 'application/json'
},
json={
'email': email,
'access_token': access_token,
'refresh_token': refresh_token,
'expiration_seconds': expiration_seconds
}
)
raise_for_status(response)
return response.json().get('id')
else:
token_by_email_resp_json = token_by_email_resp.json()
token = token_by_email_resp_json['token']
response = requests.put(
f'{database_url}/token/{token["id"]}',
headers={
'Content-Type': 'application/json'
},
json={
'access_token': access_token,
'refresh_token': refresh_token,
'expiration_seconds': expiration_seconds,
}
)
raise_for_status(response)
return token['id']
def set_session_token_id(token_id):
session['token_id'] = token_id
def raise_for_status(response):
if response.status_code not in range(200, 300):
2024-01-30 16:15:08 +00:00
msg = None
try:
msg = response.json().get('error', '')
except:
2024-01-30 16:16:20 +00:00
msg = response.text
2024-01-30 16:15:08 +00:00
raise Exception(f'HTTPError: {response.status_code} \n Message: {msg}')
2024-01-24 11:29:35 +00:00
if __name__ == '__main__':
2024-01-24 13:41:56 +00:00
app.run(host='0.0.0.0', debug=True, port=5000)