Skip to content

Commit

Permalink
Made OAuth2 AppFlow run local server and open in browser when using GUI.
Browse files Browse the repository at this point in the history
This should entirely rid us of needing access to a console \o/

Also made application a bit more robust when tackling OAuth failures, be
it aborted auth or missing files.
  • Loading branch information
BluABK committed Mar 13, 2019
1 parent 5ab714f commit c6428ce
Show file tree
Hide file tree
Showing 7 changed files with 45 additions and 3 deletions.
5 changes: 5 additions & 0 deletions CHANGELOG
Original file line number Diff line number Diff line change
@@ -1,4 +1,9 @@
Current

v0.5.1
- Made OAuth2 AppFlow run local server and open in browser when using GUI. This should entirely rid us of needing access
to a console \o/
- Made application a bit more robust when tackling OAuth failures, be it aborted auth or missing files.
- Moved API Key/OAuth file exists logic to MainWindow and made it a pop-up. In the case of a missing key or client
secret file, the user will from now on be prompted from GUI about whether they want to load their own or use the
public set (NB: prone to exceeded quota).
Expand Down
2 changes: 1 addition & 1 deletion VERSION
Original file line number Diff line number Diff line change
@@ -1 +1 @@
0.5.0
0.5.1
5 changes: 4 additions & 1 deletion config.ini.sample
Original file line number Diff line number Diff line change
Expand Up @@ -132,4 +132,7 @@ Image =
[Logging]
use_socket_log = False
log_level = 1
logging_port = 19996
logging_port = 19996

[Authentication]
oauth2_local_server_port = 10600
19 changes: 18 additions & 1 deletion sane_yt_subfeed/authentication.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,11 @@
import os
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
from oauthlib.oauth2 import MissingCodeError

from sane_yt_subfeed.config_handler import read_config
from sane_yt_subfeed.log_handler import create_logger
from sane_yt_subfeed.settings import mutable_settings

# FIXME: module level logger not suggested: https://fangpenlin.com/posts/2012/08/26/good-logging-practice-in-python/
logger = create_logger(__name__)
Expand Down Expand Up @@ -50,7 +53,21 @@ def youtube_auth_oauth():
"""
logger.info("OAuth: Authorising API...")
flow = InstalledAppFlow.from_client_secrets_file(CLIENT_SECRET_FILE, SCOPES)
credentials = flow.run_console()
if mutable_settings.using_gui:
try:
credentials = flow.run_local_server(host='localhost',
port=read_config('Authentication', 'oauth2_local_server_port',
literal_eval=True),
authorization_prompt_message='Please visit this URL: {url}',
success_message='The auth flow is complete; you may close this window.',
open_browser=True)
except MissingCodeError as exc_mce:
logger.exception("A MissingCodeError Exception occurred during OAuth2",
exc_info=exc_mce)
return None

else:
credentials = flow.run_console()
logger.info("OAuth: Instantiated flow (console)")
# Note: If you try to send in requestBuilder here it will fail, but OAuth isn't threaded so it should be fine...
return build(API_SERVICE_NAME, API_VERSION, credentials=credentials)
Expand Down
3 changes: 3 additions & 0 deletions sane_yt_subfeed/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
from timeit import default_timer
from tqdm import tqdm

from sane_yt_subfeed.settings import mutable_settings
from sane_yt_subfeed.controller.controller import Controller
from sane_yt_subfeed.database.models import Test
from sane_yt_subfeed.database.orm import db_session
Expand All @@ -28,6 +29,8 @@

def run_with_gui():
logger.info('Running with GUI')
# Used by backend to determine whether or not application is using GUI
mutable_settings.using_gui = True
controller = Controller()
controller.run()

Expand Down
8 changes: 8 additions & 0 deletions sane_yt_subfeed/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,11 @@
YOUTUBE_URL_PART_VIDEO = "watch?v="
YOUTUBE_URL_PART_PLIST = "playlist?list ="
YOUTUBE_URL_VIDEO = YOUTUBE_URL_BASE + YOUTUBE_URL_PART_VIDEO


class MutableSettings:
def __init__(self):
self.using_gui = False


mutable_settings = MutableSettings()
6 changes: 6 additions & 0 deletions sane_yt_subfeed/youtube/youtube_requests.py
Original file line number Diff line number Diff line change
Expand Up @@ -290,6 +290,9 @@ def get_remote_subscriptions(youtube_oauth):
:param youtube_oauth:
:return: [subs]
"""
if youtube_oauth is None:
logger.critical("YouTube API OAuth object was NoneType, aborting!")
return None
subscription_list_request = youtube_oauth.subscriptions().list(part='snippet', mine=True,
maxResults=50)
subs = []
Expand Down Expand Up @@ -349,6 +352,9 @@ def get_remote_subscriptions_cached_oauth():
except FileNotFoundError:
logger.warning("Loading of cached OAuth: File not found. Requesting new OAuth from user.")
youtube_oauth = youtube_auth_oauth()
if youtube_oauth is None:
logger.critical("Failed to authenticate YouTube API OAuth2!")
return None
save_youtube_resource_oauth(youtube_oauth)
temp_subscriptions = get_remote_subscriptions(youtube_oauth)
return temp_subscriptions
Expand Down

0 comments on commit c6428ce

Please sign in to comment.