Set audio language.
[audio.git] / src / apiclient / models.py
1 import json
2 from django.db import models
3 from django.contrib.auth.models import User
4 from requests_oauthlib import OAuth2Session
5 from .settings import YOUTUBE_CLIENT_ID, YOUTUBE_CLIENT_SECRET, YOUTUBE_TOKEN_URL
6
7
8 class OAuthConnection(models.Model):
9     user = models.ForeignKey(User, models.CASCADE)
10     access = models.BooleanField(default=False)
11     token = models.CharField(max_length=64, null=True, blank=True)
12     token_secret = models.CharField(max_length=64, null=True, blank=True)
13
14     @classmethod
15     def get(cls, user):
16         try:
17             return cls.objects.get(user=user)
18         except cls.DoesNotExist:
19             o = cls(user=user)
20             o.save()
21             return o
22
23
24 class YouTubeToken(models.Model):
25     token = models.TextField()
26
27     def token_updater(self, token):
28         self.token = json.dumps(token)
29         self.save()
30
31     def get_session(self):
32         return OAuth2Session(
33             client_id=YOUTUBE_CLIENT_ID,
34             auto_refresh_url=YOUTUBE_TOKEN_URL,
35             token=json.loads(self.token),
36             auto_refresh_kwargs={'client_id':YOUTUBE_CLIENT_ID,'client_secret':YOUTUBE_CLIENT_SECRET},
37             token_updater=self.token_updater
38         )
39
40     def call(self, method, url, params=None, json=None, data=None, resumable_data=None):
41         params = params or {}
42         if resumable_data:
43             params['uploadType'] = 'resumable'
44
45         session = self.get_session()
46         response = session.request(
47             method=method,
48             url=url,
49             json=json,
50             data=data,
51             params=params,
52             headers={
53                 'X-Upload-Content-Length': str(len(resumable_data)),
54                 'x-upload-content-type': 'application/octet-stream',
55             } if resumable_data else {}
56         )
57         if resumable_data:
58             location = response.headers['Location']
59             return session.put(
60                 url=location,
61                 data=resumable_data,
62                 headers={"Content-Type": "application/octet-stream"},
63             )