Publish volumes of audiobooks on YT.
[audio.git] / src / apiclient / views.py
1 import json
2 from django.contrib.auth.decorators import login_required
3 from django.urls import reverse
4 from django.http import HttpResponseRedirect, HttpResponse
5 import requests
6 from requests_oauthlib import OAuth1Session, OAuth2Session
7
8 from apiclient.models import OAuthConnection, YouTubeToken
9 from apiclient.settings import WL_CONSUMER_KEY, WL_CONSUMER_SECRET
10 from apiclient.settings import WL_REQUEST_TOKEN_URL, WL_ACCESS_TOKEN_URL, WL_AUTHORIZE_URL, YOUTUBE_AUTH_URL, YOUTUBE_TOKEN_URL, YOUTUBE_CLIENT_ID, YOUTUBE_CLIENT_SECRET, YOUTUBE_SCOPE
11
12
13 @login_required
14 def oauth(request):
15     oauth = OAuth1Session(WL_CONSUMER_KEY, WL_CONSUMER_SECRET)
16     request_token = oauth.fetch_request_token(WL_REQUEST_TOKEN_URL)
17
18     conn = OAuthConnection.get(request.user)
19     conn.access = False
20     conn.token = request_token['oauth_token']
21     conn.token_secret = request_token['oauth_token_secret']
22     conn.save()
23
24     url = oauth.authorization_url(WL_AUTHORIZE_URL)
25     url += '&oauth_callback=' + request.build_absolute_uri(reverse("apiclient_oauth_callback"))
26     return HttpResponseRedirect(url)
27
28
29 @login_required
30 def oauth_callback(request):
31     conn = OAuthConnection.get(request.user)
32     oauth_verifier = request.GET.get('oauth_verifier', 'verifier')
33
34     oauth = OAuth1Session(
35         WL_CONSUMER_KEY, WL_CONSUMER_SECRET,
36                           conn.token, conn.token_secret,
37                           verifier=oauth_verifier)
38     access_token = oauth.fetch_access_token(WL_ACCESS_TOKEN_URL)
39
40     conn.access = True
41     conn.token = access_token['oauth_token']
42     conn.token_secret = access_token['oauth_token_secret']
43     conn.save()
44
45     return HttpResponseRedirect('/')
46
47
48 @login_required
49 def oauth2(request):
50     redirect_uri = request.build_absolute_uri(reverse("apiclient_oauth2_redirect"))
51     oauth = OAuth2Session(YOUTUBE_CLIENT_ID, redirect_uri=redirect_uri, scope=YOUTUBE_SCOPE)
52     authorization_url, state = oauth.authorization_url(YOUTUBE_AUTH_URL)
53     return HttpResponseRedirect(authorization_url)
54
55
56 @login_required
57 def oauth2_redirect(request):
58     redirect_uri = request.build_absolute_uri(reverse("apiclient_oauth2_redirect"))
59     oauth = OAuth2Session(YOUTUBE_CLIENT_ID, redirect_uri=redirect_uri, scope=YOUTUBE_SCOPE)
60     token = oauth.fetch_token(
61             YOUTUBE_TOKEN_URL,
62             authorization_response=request.get_full_path(),
63             client_secret=YOUTUBE_CLIENT_SECRET,
64         )
65     YouTubeToken.objects.all().delete()
66     YouTubeToken.objects.create(token=json.dumps(token))
67     return HttpResponseRedirect('/')