2 from django.conf import settings
3 from django.db import models
4 from requests_oauthlib import OAuth2Session
8 'https://www.googleapis.com/auth/youtube',
10 YOUTUBE_AUTH_URL = 'https://accounts.google.com/o/oauth2/auth'
11 YOUTUBE_TOKEN_URL = 'https://oauth2.googleapis.com/token'
14 class Course(models.Model):
15 slug = models.SlugField()
16 title = models.CharField(max_length=255)
22 class Track(models.Model):
23 course = models.ForeignKey(Course, models.CASCADE)
26 class Tag(models.Model):
27 name = models.CharField(max_length=255)
30 class Item(models.Model):
31 course = models.ForeignKey(Course, models.CASCADE)
32 title = models.CharField(max_length=255, blank=True)
33 tags = models.ManyToManyField(Tag, blank=True)
34 youtube_id = models.CharField(max_length=255, blank=True)
35 order = models.IntegerField(default=0, blank=True)
44 class YPlaylist(models.Model):
45 course = models.ForeignKey(Course, models.CASCADE)
46 youtube_id = models.CharField(max_length=255, blank=True)
53 response = YouTubeToken.objects.first().call(
55 "https://www.googleapis.com/youtube/v3/playlistItems",
58 'playlistId': self.youtube_id,
62 data = response.json()
63 for item in data['items']:
64 self.course.item_set.update_or_create(
65 youtube_id=item['snippet']['resourceId']['videoId'],
67 'title': item['snippet']['title'],
68 'order': item['snippet']['position'],
74 class YouTubeToken(models.Model):
75 token = models.TextField()
77 def token_updater(self, token):
78 self.token = json.dumps(token)
81 def get_session(self):
83 client_id=settings.YOUTUBE_CLIENT_ID,
84 auto_refresh_url=YOUTUBE_TOKEN_URL,
85 token=json.loads(self.token),
86 auto_refresh_kwargs={'client_id':settings.YOUTUBE_CLIENT_ID,'client_secret':settings.YOUTUBE_CLIENT_SECRET},
87 token_updater=self.token_updater
90 def call(self, method, url, params=None, json=None, data=None, resumable_file_path=None):
92 if resumable_file_path:
93 params['uploadType'] = 'resumable'
94 file_size = os.stat(resumable_file_path).st_size
96 session = self.get_session()
97 response = session.request(
104 'X-Upload-Content-Length': str(file_size),
105 'x-upload-content-type': 'application/octet-stream',
106 } if resumable_file_path else {}
108 response.raise_for_status()