models.py 65 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228
  1. import requests
  2. from django.contrib.auth.models import User
  3. from allauth.socialaccount.models import SocialAccount, SocialApp, SocialToken
  4. from apps.users.models import Profile
  5. from .util import *
  6. import pytz
  7. from UnTube.secrets import SECRETS
  8. from django.db import models
  9. from google.oauth2.credentials import Credentials
  10. from google.auth.transport.requests import Request
  11. from datetime import timedelta
  12. from googleapiclient.discovery import build
  13. import googleapiclient.errors
  14. from django.db.models import Q, Sum
  15. class PlaylistManager(models.Manager):
  16. def getCredentials(self, user):
  17. credentials = Credentials(
  18. user.profile.access_token,
  19. refresh_token=user.profile.refresh_token,
  20. # id_token=session.token.get("id_token"),
  21. token_uri="https://oauth2.googleapis.com/token",
  22. client_id=SECRETS["GOOGLE_OAUTH_CLIENT_ID"],
  23. client_secret=SECRETS["GOOGLE_OAUTH_CLIENT_SECRET"],
  24. scopes=SECRETS["GOOGLE_OAUTH_SCOPES"]
  25. )
  26. credentials.expiry = user.profile.expires_at.replace(tzinfo=None)
  27. if not credentials.valid:
  28. # if credentials and credentials.expired and credentials.refresh_token:
  29. credentials.refresh(Request())
  30. user.profile.expires_at = credentials.expiry
  31. user.profile.access_token = credentials.token
  32. user.profile.refresh_token = credentials.refresh_token
  33. user.save()
  34. return credentials
  35. def getPlaylistId(self, video_link):
  36. temp = video_link.split("?")[-1].split("&")
  37. for el in temp:
  38. if "list=" in el:
  39. return el.split("list=")[-1]
  40. # Used to check if the user has a vaild YouTube channel
  41. # Will return -1 if user does not have a YouTube channel
  42. def getUserYTChannelID(self, user):
  43. credentials = self.getCredentials(user)
  44. with build('youtube', 'v3', credentials=credentials) as youtube:
  45. pl_request = youtube.channels().list(
  46. part='id,topicDetails,status,statistics,snippet,localizations,contentOwnerDetails,contentDetails,brandingSettings',
  47. mine=True # get playlist details for this user's playlists
  48. )
  49. pl_response = pl_request.execute()
  50. print(pl_response)
  51. if pl_response['pageInfo']['totalResults'] == 0:
  52. print("Looks like do not have a channel on youtube. Create one to import all of your playlists. Retry?")
  53. return -1
  54. else:
  55. user.profile.yt_channel_id = pl_response['items'][0]['id']
  56. user.save()
  57. return 0
  58. # Set pl_id as None to retrive all the playlists from authenticated user. Playlists already imported will be skipped by default.
  59. # Set pl_id = <valid playlist id>, to import that specific playlist into the user's account
  60. def initializePlaylist(self, user, pl_id=None):
  61. '''
  62. Retrieves all of user's playlists from YT and stores them in the Playlist model. Note: only stores
  63. the few of the columns of each playlist in every row, and has is_in_db column as false as no videos will be
  64. saved yet.
  65. :param user: django User object
  66. :param pl_id:
  67. :return:
  68. '''
  69. result = {"status": 0,
  70. "num_of_playlists": 0,
  71. "first_playlist_name": "N/A",
  72. "playlist_ids": []}
  73. credentials = self.getCredentials(user)
  74. playlist_ids = []
  75. with build('youtube', 'v3', credentials=credentials) as youtube:
  76. if pl_id is not None:
  77. pl_request = youtube.playlists().list(
  78. part='contentDetails, snippet, id, player, status',
  79. id=pl_id, # get playlist details for this playlist id
  80. maxResults=50
  81. )
  82. else:
  83. print("GETTING ALL USER AUTH PLAYLISTS")
  84. pl_request = youtube.playlists().list(
  85. part='contentDetails, snippet, id, player, status',
  86. mine=True, # get playlist details for this playlist id
  87. maxResults=50
  88. )
  89. # execute the above request, and store the response
  90. try:
  91. pl_response = pl_request.execute()
  92. except googleapiclient.errors.HttpError:
  93. print("YouTube channel not found if mine=True")
  94. print("YouTube playlist not found if id=playlist_id")
  95. result["status"] = -1
  96. return result
  97. if pl_response["pageInfo"]["totalResults"] == 0:
  98. print("No playlists created yet on youtube.")
  99. result["status"] = -2
  100. return result
  101. playlist_items = []
  102. for item in pl_response["items"]:
  103. playlist_items.append(item)
  104. if pl_id is None:
  105. while True:
  106. try:
  107. pl_request = youtube.playlists().list_next(pl_request, pl_response)
  108. pl_response = pl_request.execute()
  109. for item in pl_response["items"]:
  110. playlist_items.append(item)
  111. except AttributeError:
  112. break
  113. result["num_of_playlists"] = len(playlist_items)
  114. result["first_playlist_name"] = playlist_items[0]["snippet"]["title"]
  115. for item in playlist_items:
  116. playlist_id = item["id"]
  117. playlist_ids.append(playlist_id)
  118. # check if this playlist already exists in user's untube collection
  119. if user.playlists.filter(playlist_id=playlist_id).exists():
  120. playlist = user.playlists.get(playlist_id=playlist_id)
  121. print(f"PLAYLIST {playlist.name} ALREADY EXISTS IN DB")
  122. # POSSIBLE CASES:
  123. # 1. PLAYLIST HAS DUPLICATE VIDEOS, DELETED VIDS, UNAVAILABLE VIDS
  124. # check if playlist count changed on youtube
  125. if playlist.video_count != item['contentDetails']['itemCount']:
  126. playlist.has_playlist_changed = True
  127. playlist.save(update_fields=['has_playlist_changed'])
  128. if pl_id is not None:
  129. result["status"] = -3
  130. return result
  131. else: # no such playlist in database
  132. ### MAKE THE PLAYLIST AND LINK IT TO CURRENT_USER
  133. playlist = Playlist( # create the playlist and link it to current user
  134. playlist_id=playlist_id,
  135. name=item['snippet']['title'],
  136. description=item['snippet']['description'],
  137. published_at=item['snippet']['publishedAt'],
  138. thumbnail_url=getThumbnailURL(item['snippet']['thumbnails']),
  139. channel_id=item['snippet']['channelId'] if 'channelId' in
  140. item['snippet'] else '',
  141. channel_name=item['snippet']['channelTitle'] if 'channelTitle' in
  142. item[
  143. 'snippet'] else '',
  144. video_count=item['contentDetails']['itemCount'],
  145. is_private_on_yt=True if item['status']['privacyStatus'] == 'private' else False,
  146. playlist_yt_player_HTML=item['player']['embedHtml'],
  147. untube_user=user,
  148. is_user_owned=True if item['snippet']['channelId'] == user.profile.yt_channel_id else False,
  149. is_yt_mix=True if ("My Mix" in item['snippet']['title'] or "Mix -" in item['snippet']['title']) and
  150. item['snippet']['channelId'] == "UCBR8-60-B28hp2BmDPdntcQ" else False
  151. )
  152. playlist.save()
  153. result["playlist_ids"] = playlist_ids
  154. return result
  155. def getAllVideosForPlaylist(self, user, playlist_id):
  156. credentials = self.getCredentials(user)
  157. playlist = user.playlists.get(playlist_id=playlist_id)
  158. ### GET ALL VIDEO IDS FROM THE PLAYLIST
  159. video_ids = [] # stores list of all video ids for a given playlist
  160. with build('youtube', 'v3', credentials=credentials) as youtube:
  161. pl_request = youtube.playlistItems().list(
  162. part='contentDetails, snippet, status',
  163. playlistId=playlist_id, # get all playlist videos details for this playlist id
  164. maxResults=50
  165. )
  166. # execute the above request, and store the response
  167. pl_response = pl_request.execute()
  168. for item in pl_response['items']:
  169. playlist_item_id = item["id"]
  170. video_id = item['contentDetails']['videoId']
  171. video_ids.append(video_id)
  172. # video DNE in user's untube:
  173. # 1. create and save the video in user's untube
  174. # 2. add it to playlist
  175. # 3. make a playlist item which is linked to the video
  176. if not user.videos.filter(video_id=video_id).exists():
  177. if item['snippet']['title'] == "Deleted video" or item['snippet'][
  178. 'description'] == "This video is unavailable." or item['snippet']['title'] == "Private video" or \
  179. item['snippet']['description'] == "This video is private.":
  180. video = Video(
  181. video_id=video_id,
  182. name=item['snippet']['title'],
  183. description=item['snippet']['description'],
  184. is_unavailable_on_yt=True,
  185. untube_user=user
  186. )
  187. video.save()
  188. else:
  189. video = Video(
  190. video_id=video_id,
  191. published_at=item['contentDetails']['videoPublishedAt'] if 'videoPublishedAt' in
  192. item[
  193. 'contentDetails'] else None,
  194. name=item['snippet']['title'],
  195. description=item['snippet']['description'],
  196. thumbnail_url=getThumbnailURL(item['snippet']['thumbnails']),
  197. channel_id=item['snippet']['videoOwnerChannelId'],
  198. channel_name=item['snippet']['videoOwnerChannelTitle'],
  199. untube_user=user
  200. )
  201. video.save()
  202. playlist.videos.add(video)
  203. playlist_item = PlaylistItem(
  204. playlist_item_id=playlist_item_id,
  205. published_at=item['snippet']['publishedAt'] if 'publishedAt' in
  206. item[
  207. 'snippet'] else None,
  208. channel_id=item['snippet']['channelId'],
  209. channel_name=item['snippet']['channelTitle'],
  210. video_position=item['snippet']['position'],
  211. playlist=playlist,
  212. video=video
  213. )
  214. playlist_item.save()
  215. else: # video found in user's db
  216. video = user.videos.get(video_id=video_id)
  217. # if video already in playlist.videos
  218. is_duplicate = False
  219. if playlist.videos.filter(video_id=video_id).exists():
  220. playlist.has_duplicate_videos = True
  221. is_duplicate = True
  222. else:
  223. playlist.videos.add(video)
  224. playlist_item = PlaylistItem(
  225. playlist_item_id=playlist_item_id,
  226. published_at=item['snippet']['publishedAt'] if 'publishedAt' in
  227. item[
  228. 'snippet'] else None,
  229. channel_id=item['snippet']['channelId'] if 'channelId' in
  230. item[
  231. 'snippet'] else None,
  232. channel_name=item['snippet']['channelTitle'] if 'channelTitle' in
  233. item[
  234. 'snippet'] else None,
  235. video_position=item['snippet']['position'],
  236. playlist=playlist,
  237. video=video,
  238. is_duplicate=is_duplicate
  239. )
  240. playlist_item.save()
  241. # check if the video became unavailable on youtube
  242. if not video.is_unavailable_on_yt and not video.was_deleted_on_yt and (item['snippet']['title'] == "Deleted video" or
  243. item['snippet'][
  244. 'description'] == "This video is unavailable.") or (
  245. item['snippet']['title'] == "Private video" or item['snippet'][
  246. 'description'] == "This video is private."):
  247. video.was_deleted_on_yt = True
  248. playlist.has_unavailable_videos = True
  249. video.save(update_fields=['was_deleted_on_yt'])
  250. while True:
  251. try:
  252. pl_request = youtube.playlistItems().list_next(pl_request, pl_response)
  253. pl_response = pl_request.execute()
  254. for item in pl_response['items']:
  255. playlist_item_id = item["id"]
  256. video_id = item['contentDetails']['videoId']
  257. video_ids.append(video_id)
  258. # video DNE in user's untube:
  259. # 1. create and save the video in user's untube
  260. # 2. add it to playlist
  261. # 3. make a playlist item which is linked to the video
  262. if not user.videos.filter(video_id=video_id).exists():
  263. if item['snippet']['title'] == "Deleted video" or item['snippet'][
  264. 'description'] == "This video is unavailable." or item['snippet'][
  265. 'title'] == "Private video" or \
  266. item['snippet']['description'] == "This video is private.":
  267. video = Video(
  268. video_id=video_id,
  269. name=item['snippet']['title'],
  270. description=item['snippet']['description'],
  271. is_unavailable_on_yt=True,
  272. untube_user=user
  273. )
  274. video.save()
  275. else:
  276. video = Video(
  277. video_id=video_id,
  278. published_at=item['contentDetails']['videoPublishedAt'] if 'videoPublishedAt' in
  279. item[
  280. 'contentDetails'] else None,
  281. name=item['snippet']['title'],
  282. description=item['snippet']['description'],
  283. thumbnail_url=getThumbnailURL(item['snippet']['thumbnails']),
  284. channel_id=item['snippet']['videoOwnerChannelId'],
  285. channel_name=item['snippet']['videoOwnerChannelTitle'],
  286. untube_user=user
  287. )
  288. video.save()
  289. playlist.videos.add(video)
  290. playlist_item = PlaylistItem(
  291. playlist_item_id=playlist_item_id,
  292. published_at=item['snippet']['publishedAt'] if 'publishedAt' in
  293. item[
  294. 'snippet'] else None,
  295. channel_id=item['snippet']['channelId'],
  296. channel_name=item['snippet']['channelTitle'],
  297. video_position=item['snippet']['position'],
  298. playlist=playlist,
  299. video=video
  300. )
  301. playlist_item.save()
  302. else: # video found in user's db
  303. video = user.videos.get(video_id=video_id)
  304. # if video already in playlist.videos
  305. is_duplicate = False
  306. if playlist.videos.filter(video_id=video_id).exists():
  307. playlist.has_duplicate_videos = True
  308. is_duplicate = True
  309. else:
  310. playlist.videos.add(video)
  311. playlist_item = PlaylistItem(
  312. playlist_item_id=playlist_item_id,
  313. published_at=item['snippet']['publishedAt'] if 'publishedAt' in
  314. item[
  315. 'snippet'] else None,
  316. channel_id=item['snippet']['channelId'] if 'channelId' in
  317. item[
  318. 'snippet'] else None,
  319. channel_name=item['snippet']['channelTitle'] if 'channelTitle' in
  320. item[
  321. 'snippet'] else None,
  322. video_position=item['snippet']['position'],
  323. playlist=playlist,
  324. video=video,
  325. is_duplicate=is_duplicate
  326. )
  327. playlist_item.save()
  328. # check if the video became unavailable on youtube
  329. if not video.is_unavailable_on_yt and not video.was_deleted_on_yt and (item['snippet']['title'] == "Deleted video" or
  330. item['snippet'][
  331. 'description'] == "This video is unavailable.") or (
  332. item['snippet']['title'] == "Private video" or item['snippet'][
  333. 'description'] == "This video is private."):
  334. video.was_deleted_on_yt = True
  335. playlist.has_unavailable_videos = True
  336. video.save(update_fields=['was_deleted_on_yt'])
  337. except AttributeError:
  338. break
  339. # API expects the video ids to be a string of comma seperated values, not a python list
  340. video_ids_strings = getVideoIdsStrings(video_ids)
  341. # store duration of all the videos in the playlist
  342. vid_durations = []
  343. for video_ids_string in video_ids_strings:
  344. # query the videos resource using API with the string above
  345. vid_request = youtube.videos().list(
  346. part="contentDetails,player,snippet,statistics", # get details of eac video
  347. id=video_ids_string,
  348. maxResults=50
  349. )
  350. vid_response = vid_request.execute()
  351. for item in vid_response['items']:
  352. duration = item['contentDetails']['duration']
  353. vid = playlist.videos.get(video_id=item['id'])
  354. vid.name = item['snippet']['title']
  355. vid.description = item['snippet']['description']
  356. vid.thumbnail_url = getThumbnailURL(item['snippet']['thumbnails'])
  357. vid.duration = duration.replace("PT", "")
  358. vid.duration_in_seconds = calculateDuration([duration])
  359. vid.has_cc = True if item['contentDetails']['caption'].lower() == 'true' else False
  360. vid.view_count = item['statistics']['viewCount'] if 'viewCount' in item[
  361. 'statistics'] else -1
  362. vid.like_count = item['statistics']['likeCount'] if 'likeCount' in item[
  363. 'statistics'] else -1
  364. vid.dislike_count = item['statistics']['dislikeCount'] if 'dislikeCount' in item[
  365. 'statistics'] else -1
  366. vid.comment_count = item['statistics']['commentCount'] if 'commentCount' in item[
  367. 'statistics'] else -1
  368. vid.yt_player_HTML = item['player']['embedHtml'] if 'embedHtml' in item['player'] else ''
  369. vid.save()
  370. vid_durations.append(duration)
  371. playlist_duration_in_seconds = calculateDuration(vid_durations)
  372. playlist.playlist_duration_in_seconds = playlist_duration_in_seconds
  373. playlist.playlist_duration = getHumanizedTimeString(playlist_duration_in_seconds)
  374. if len(video_ids) != len(vid_durations): # that means some videos in the playlist are deleted
  375. playlist.has_unavailable_videos = True
  376. playlist.is_in_db = True
  377. playlist.save()
  378. # Returns True if the video count for a playlist on UnTube and video count on same playlist on YouTube is different
  379. def checkIfPlaylistChangedOnYT(self, user, pl_id):
  380. """
  381. If full_scan is true, the whole playlist (i.e each and every video from the PL on YT and PL on UT, is scanned and compared)
  382. is scanned to see if there are any missing/deleted/newly added videos. This will be only be done
  383. weekly by looking at the playlist.last_full_scan_at
  384. If full_scan is False, only the playlist count difference on YT and UT is checked on every visit
  385. to the playlist page. This is done everytime.
  386. """
  387. credentials = self.getCredentials(user)
  388. playlist = user.playlists.get(playlist_id=pl_id)
  389. # if its been a week since the last full scan, do a full playlist scan
  390. # basically checks all the playlist video for any updates
  391. if playlist.last_full_scan_at + datetime.timedelta(minutes=2) < datetime.datetime.now(pytz.utc):
  392. print("DOING A FULL SCAN")
  393. current_video_ids = [playlist_item.video_id for playlist_item in playlist.playlist_items.all()]
  394. current_playlist_item_ids = [playlist_item.playlist_item_id for playlist_item in
  395. playlist.playlist_items.all()]
  396. deleted_videos, unavailable_videos, added_videos = 0, 0, 0
  397. ### GET ALL VIDEO IDS FROM THE PLAYLIST
  398. video_ids = [] # stores list of all video ids for a given playlist
  399. with build('youtube', 'v3', credentials=credentials) as youtube:
  400. pl_request = youtube.playlistItems().list(
  401. part='contentDetails, snippet, status',
  402. playlistId=pl_id, # get all playlist videos details for this playlist id
  403. maxResults=50
  404. )
  405. # execute the above request, and store the response
  406. pl_response = pl_request.execute()
  407. for item in pl_response['items']:
  408. playlist_item_id = item['id']
  409. video_id = item['contentDetails']['videoId']
  410. if not playlist.playlist_items.filter(
  411. playlist_item_id=playlist_item_id).exists(): # if playlist item DNE in playlist, a new vid added to playlist
  412. added_videos += 1
  413. video_ids.append(video_id)
  414. else: # playlist_item found in playlist
  415. if playlist_item_id in current_playlist_item_ids:
  416. video_ids.append(video_id)
  417. current_playlist_item_ids.remove(playlist_item_id)
  418. video = playlist.videos.get(video_id=video_id)
  419. # check if the video became unavailable on youtube
  420. if not video.is_unavailable_on_yt and not video.was_deleted_on_yt:
  421. if (item['snippet']['title'] == "Deleted video" or
  422. item['snippet']['description'] == "This video is unavailable." or
  423. item['snippet']['title'] == "Private video" or item['snippet'][
  424. 'description'] == "This video is private."):
  425. unavailable_videos += 1
  426. while True:
  427. try:
  428. pl_request = youtube.playlistItems().list_next(pl_request, pl_response)
  429. pl_response = pl_request.execute()
  430. for item in pl_response['items']:
  431. playlist_item_id = item['id']
  432. video_id = item['contentDetails']['videoId']
  433. if not playlist.playlist_items.filter(
  434. playlist_item_id=playlist_item_id).exists(): # if playlist item DNE in playlist, a new vid added to playlist
  435. added_videos += 1
  436. video_ids.append(video_id)
  437. else: # playlist_item found in playlist
  438. if playlist_item_id in current_playlist_item_ids:
  439. video_ids.append(video_id)
  440. current_playlist_item_ids.remove(playlist_item_id)
  441. video = playlist.videos.get(video_id=video_id)
  442. # check if the video became unavailable on youtube
  443. if not video.is_unavailable_on_yt and not video.was_deleted_on_yt:
  444. if (item['snippet']['title'] == "Deleted video" or
  445. item['snippet']['description'] == "This video is unavailable." or
  446. item['snippet']['title'] == "Private video" or item['snippet'][
  447. 'description'] == "This video is private."):
  448. unavailable_videos += 1
  449. except AttributeError:
  450. break
  451. playlist.last_full_scan_at = datetime.datetime.now(pytz.utc)
  452. playlist.save()
  453. deleted_videos = len(current_playlist_item_ids) # left out video ids
  454. return [1, deleted_videos, unavailable_videos, added_videos]
  455. """
  456. print("DOING A SMOL SCAN")
  457. with build('youtube', 'v3', credentials=credentials) as youtube:
  458. pl_request = youtube.playlists().list(
  459. part='contentDetails, snippet, id, status',
  460. id=pl_id, # get playlist details for this playlist id
  461. maxResults=50
  462. )
  463. # execute the above request, and store the response
  464. try:
  465. pl_response = pl_request.execute()
  466. except googleapiclient.errors.HttpError:
  467. print("YouTube channel not found if mine=True")
  468. print("YouTube playlist not found if id=playlist_id")
  469. return -1
  470. print("PLAYLIST", pl_response)
  471. playlist_items = []
  472. for item in pl_response["items"]:
  473. playlist_items.append(item)
  474. while True:
  475. try:
  476. pl_request = youtube.playlists().list_next(pl_request, pl_response)
  477. pl_response = pl_request.execute()
  478. for item in pl_response["items"]:
  479. playlist_items.append(item)
  480. except AttributeError:
  481. break
  482. for item in playlist_items:
  483. playlist_id = item["id"]
  484. # check if this playlist already exists in database
  485. if user.playlists.filter(playlist_id=playlist_id).exists():
  486. playlist = user.playlists.get(playlist_id__exact=playlist_id)
  487. print(f"PLAYLIST {playlist.name} ALREADY EXISTS IN DB")
  488. # POSSIBLE CASES:
  489. # 1. PLAYLIST HAS DUPLICATE VIDEOS, DELETED VIDS, UNAVAILABLE VIDS
  490. # check if playlist changed on youtube
  491. if playlist.video_count != item['contentDetails']['itemCount']:
  492. playlist.has_playlist_changed = True
  493. playlist.save()
  494. return [-1, item['contentDetails']['itemCount']]
  495. """
  496. return [0, "no change"]
  497. def updatePlaylist(self, user, playlist_id):
  498. credentials = self.getCredentials(user)
  499. playlist = user.playlists.get(playlist_id__exact=playlist_id)
  500. playlist.has_duplicate_videos = False # reset this to false for now
  501. has_duplicate_videos = False
  502. current_video_ids = [playlist_item.video.video_id for playlist_item in playlist.playlist_items.all()]
  503. current_playlist_item_ids = [playlist_item.playlist_item_id for playlist_item in playlist.playlist_items.all()]
  504. updated_playlist_video_count = 0
  505. deleted_playlist_item_ids, unavailable_videos, added_videos = [], [], []
  506. ### GET ALL VIDEO IDS FROM THE PLAYLIST
  507. video_ids = [] # stores list of all video ids for a given playlist
  508. with build('youtube', 'v3', credentials=credentials) as youtube:
  509. pl_request = youtube.playlistItems().list(
  510. part='contentDetails, snippet, status',
  511. playlistId=playlist_id, # get all playlist videos details for this playlist id
  512. maxResults=50
  513. )
  514. # execute the above request, and store the response
  515. try:
  516. pl_response = pl_request.execute()
  517. except googleapiclient.errors.HttpError:
  518. print("Playist was deleted on YouTube")
  519. return [-1, [], [], []]
  520. print("ESTIMATED VIDEO IDS FROM RESPONSE", len(pl_response["items"]))
  521. updated_playlist_video_count += len(pl_response["items"])
  522. for item in pl_response['items']:
  523. playlist_item_id = item["id"]
  524. video_id = item['contentDetails']['videoId']
  525. video_ids.append(video_id)
  526. # check if new playlist item added
  527. if not playlist.playlist_items.filter(playlist_item_id=playlist_item_id).exists():
  528. # if video dne in user's db at all, create and save it
  529. if not user.videos.filter(video_id=video_id).exists():
  530. if (item['snippet']['title'] == "Deleted video" and item['snippet'][
  531. 'description'] == "This video is unavailable.") or (item['snippet'][
  532. 'title'] == "Private video" and item['snippet']['description'] == "This video is private."):
  533. video = Video(
  534. video_id=video_id,
  535. name=item['snippet']['title'],
  536. description=item['snippet']['description'],
  537. is_unavailable_on_yt=True,
  538. untube_user=user
  539. )
  540. video.save()
  541. else:
  542. video = Video(
  543. video_id=video_id,
  544. published_at=item['contentDetails']['videoPublishedAt'] if 'videoPublishedAt' in
  545. item[
  546. 'contentDetails'] else None,
  547. name=item['snippet']['title'],
  548. description=item['snippet']['description'],
  549. thumbnail_url=getThumbnailURL(item['snippet']['thumbnails']),
  550. channel_id=item['snippet']['videoOwnerChannelId'],
  551. channel_name=item['snippet']['videoOwnerChannelTitle'],
  552. untube_user=user
  553. )
  554. video.save()
  555. video = user.videos.get(video_id=video_id)
  556. # check if the video became unavailable on youtube
  557. if not video.is_unavailable_on_yt and not video.was_deleted_on_yt and (item['snippet']['title'] == "Deleted video" and
  558. item['snippet'][
  559. 'description'] == "This video is unavailable.") or (
  560. item['snippet']['title'] == "Private video" and item['snippet'][
  561. 'description'] == "This video is private."):
  562. video.was_deleted_on_yt = True
  563. playlist.has_unavailable_videos = True
  564. is_duplicate = False
  565. if not playlist.videos.filter(video_id=video_id).exists():
  566. playlist.videos.add(video)
  567. else:
  568. is_duplicate = True
  569. has_duplicate_videos = True
  570. playlist_item = PlaylistItem(
  571. playlist_item_id=playlist_item_id,
  572. published_at=item['snippet']['publishedAt'] if 'publishedAt' in
  573. item[
  574. 'snippet'] else None,
  575. channel_id=item['snippet']['channelId'] if 'channelId' in
  576. item[
  577. 'snippet'] else None,
  578. channel_name=item['snippet']['channelTitle'] if 'channelTitle' in
  579. item[
  580. 'snippet'] else None,
  581. video_position=item['snippet']['position'],
  582. playlist=playlist,
  583. video=video,
  584. is_duplicate=is_duplicate
  585. )
  586. playlist_item.save()
  587. video.video_details_modified = True
  588. video.video_details_modified_at = datetime.datetime.now(tz=pytz.utc)
  589. video.save(update_fields=['video_details_modified', 'video_details_modified_at', 'was_deleted_on_yt'])
  590. added_videos.append(video)
  591. else: # if playlist item already in playlist
  592. current_playlist_item_ids.remove(playlist_item_id)
  593. playlist_item = playlist.playlist_items.get(playlist_item_id=playlist_item_id)
  594. playlist_item.video_position = item['snippet']['position']
  595. playlist_item.save(update_fields=['video_position'])
  596. # check if the video became unavailable on youtube
  597. if not playlist_item.video.is_unavailable_on_yt and not playlist_item.video.was_deleted_on_yt:
  598. if (item['snippet']['title'] == "Deleted video" and
  599. item['snippet']['description'] == "This video is unavailable.") or (
  600. item['snippet']['title'] == "Private video" and item['snippet'][
  601. 'description'] == "This video is private."):
  602. playlist_item.video.was_deleted_on_yt = True # video went private on YouTube
  603. playlist_item.video.video_details_modified = True
  604. playlist_item.video.video_details_modified_at = datetime.datetime.now(tz=pytz.utc)
  605. playlist_item.video.save(update_fields=['was_deleted_on_yt', 'video_details_modified',
  606. 'video_details_modified_at'])
  607. unavailable_videos.append(playlist_item.video)
  608. while True:
  609. try:
  610. pl_request = youtube.playlistItems().list_next(pl_request, pl_response)
  611. pl_response = pl_request.execute()
  612. updated_playlist_video_count += len(pl_response["items"])
  613. for item in pl_response['items']:
  614. playlist_item_id = item["id"]
  615. video_id = item['contentDetails']['videoId']
  616. video_ids.append(video_id)
  617. # check if new playlist item added
  618. if not playlist.playlist_items.filter(playlist_item_id=playlist_item_id).exists():
  619. # if video dne in user's db at all, create and save it
  620. if not user.videos.filter(video_id=video_id).exists():
  621. if (item['snippet']['title'] == "Deleted video" and item['snippet'][
  622. 'description'] == "This video is unavailable.") or (item['snippet'][
  623. 'title'] == "Private video" and
  624. item['snippet'][
  625. 'description'] == "This video is private."):
  626. video = Video(
  627. video_id=video_id,
  628. name=item['snippet']['title'],
  629. description=item['snippet']['description'],
  630. is_unavailable_on_yt=True,
  631. untube_user=user
  632. )
  633. video.save()
  634. else:
  635. video = Video(
  636. video_id=video_id,
  637. published_at=item['contentDetails']['videoPublishedAt'] if 'videoPublishedAt' in
  638. item[
  639. 'contentDetails'] else None,
  640. name=item['snippet']['title'],
  641. description=item['snippet']['description'],
  642. thumbnail_url=getThumbnailURL(item['snippet']['thumbnails']),
  643. channel_id=item['snippet']['videoOwnerChannelId'],
  644. channel_name=item['snippet']['videoOwnerChannelTitle'],
  645. untube_user=user
  646. )
  647. video.save()
  648. video = user.videos.get(video_id=video_id)
  649. # check if the video became unavailable on youtube
  650. if not video.is_unavailable_on_yt and not video.was_deleted_on_yt and (item['snippet']['title'] == "Deleted video" and
  651. item['snippet'][
  652. 'description'] == "This video is unavailable.") or (
  653. item['snippet']['title'] == "Private video" and item['snippet'][
  654. 'description'] == "This video is private."):
  655. video.was_deleted_on_yt = True
  656. playlist.has_unavailable_videos = True
  657. is_duplicate = False
  658. if not playlist.videos.filter(video_id=video_id).exists():
  659. playlist.videos.add(video)
  660. else:
  661. is_duplicate = True
  662. has_duplicate_videos = True
  663. playlist_item = PlaylistItem(
  664. playlist_item_id=playlist_item_id,
  665. published_at=item['snippet']['publishedAt'] if 'publishedAt' in
  666. item[
  667. 'snippet'] else None,
  668. channel_id=item['snippet']['channelId'] if 'channelId' in
  669. item[
  670. 'snippet'] else None,
  671. channel_name=item['snippet']['channelTitle'] if 'channelTitle' in
  672. item[
  673. 'snippet'] else None,
  674. video_position=item['snippet']['position'],
  675. playlist=playlist,
  676. video=video,
  677. is_duplicate=is_duplicate
  678. )
  679. playlist_item.save()
  680. video.video_details_modified = True
  681. video.video_details_modified_at = datetime.datetime.now(tz=pytz.utc)
  682. video.save(update_fields=['video_details_modified', 'video_details_modified_at',
  683. 'was_deleted_on_yt'])
  684. added_videos.append(video)
  685. else: # if playlist item already in playlist
  686. current_playlist_item_ids.remove(playlist_item_id)
  687. playlist_item = playlist.playlist_items.get(playlist_item_id=playlist_item_id)
  688. playlist_item.video_position = item['snippet']['position']
  689. playlist_item.save(update_fields=['video_position'])
  690. # check if the video became unavailable on youtube
  691. if not playlist_item.video.is_unavailable_on_yt and not playlist_item.video.was_deleted_on_yt:
  692. if (item['snippet']['title'] == "Deleted video" and
  693. item['snippet']['description'] == "This video is unavailable.") or (
  694. item['snippet']['title'] == "Private video" and item['snippet'][
  695. 'description'] == "This video is private."):
  696. playlist_item.video.was_deleted_on_yt = True # video went private on YouTube
  697. playlist_item.video.video_details_modified = True
  698. playlist_item.video.video_details_modified_at = datetime.datetime.now(tz=pytz.utc)
  699. playlist_item.video.save(
  700. update_fields=['was_deleted_on_yt', 'video_details_modified',
  701. 'video_details_modified_at'])
  702. unavailable_videos.append(playlist_item.video)
  703. except AttributeError:
  704. break
  705. # API expects the video ids to be a string of comma seperated values, not a python list
  706. video_ids_strings = getVideoIdsStrings(video_ids)
  707. # store duration of all the videos in the playlist
  708. vid_durations = []
  709. for video_ids_string in video_ids_strings:
  710. # query the videos resource using API with the string above
  711. vid_request = youtube.videos().list(
  712. part="contentDetails,player,snippet,statistics", # get details of eac video
  713. id=video_ids_string,
  714. maxResults=50
  715. )
  716. vid_response = vid_request.execute()
  717. for item in vid_response['items']:
  718. duration = item['contentDetails']['duration']
  719. vid = playlist.videos.get(video_id=item['id'])
  720. if (item['snippet']['title'] == "Deleted video" or
  721. item['snippet'][
  722. 'description'] == "This video is unavailable.") or (
  723. item['snippet']['title'] == "Private video" or item['snippet'][
  724. 'description'] == "This video is private."):
  725. playlist.has_unavailable_videos = True
  726. vid_durations.append(duration)
  727. vid.video_details_modified = True
  728. vid.video_details_modified_at = datetime.datetime.now(tz=pytz.utc)
  729. vid.save(
  730. update_fields=['video_details_modified', 'video_details_modified_at', 'was_deleted_on_yt',
  731. 'is_unavailable_on_yt'])
  732. continue
  733. vid.name = item['snippet']['title']
  734. vid.description = item['snippet']['description']
  735. vid.thumbnail_url = getThumbnailURL(item['snippet']['thumbnails'])
  736. vid.duration = duration.replace("PT", "")
  737. vid.duration_in_seconds = calculateDuration([duration])
  738. vid.has_cc = True if item['contentDetails']['caption'].lower() == 'true' else False
  739. vid.view_count = item['statistics']['viewCount'] if 'viewCount' in item[
  740. 'statistics'] else -1
  741. vid.like_count = item['statistics']['likeCount'] if 'likeCount' in item[
  742. 'statistics'] else -1
  743. vid.dislike_count = item['statistics']['dislikeCount'] if 'dislikeCount' in item[
  744. 'statistics'] else -1
  745. vid.comment_count = item['statistics']['commentCount'] if 'commentCount' in item[
  746. 'statistics'] else -1
  747. vid.yt_player_HTML = item['player']['embedHtml'] if 'embedHtml' in item['player'] else ''
  748. vid.save()
  749. vid_durations.append(duration)
  750. playlist_duration_in_seconds = calculateDuration(vid_durations)
  751. playlist.playlist_duration_in_seconds = playlist_duration_in_seconds
  752. playlist.playlist_duration = getHumanizedTimeString(playlist_duration_in_seconds)
  753. if len(video_ids) != len(vid_durations) or len(
  754. unavailable_videos) != 0: # that means some videos in the playlist became private/deleted
  755. playlist.has_unavailable_videos = True
  756. playlist.has_playlist_changed = False
  757. playlist.video_count = updated_playlist_video_count
  758. playlist.has_new_updates = True
  759. playlist.save()
  760. playlist.has_duplicate_videos = has_duplicate_videos
  761. deleted_playlist_item_ids = current_playlist_item_ids # left out playlist_item_ids
  762. return [0, deleted_playlist_item_ids, unavailable_videos, added_videos]
  763. def deletePlaylistItems(self, user, playlist_id, playlist_item_ids):
  764. """
  765. Takes in playlist itemids for the videos in a particular playlist
  766. """
  767. credentials = self.getCredentials(user)
  768. playlist = user.playlists.get(playlist_id=playlist_id)
  769. # new_playlist_duration_in_seconds = playlist.playlist_duration_in_seconds
  770. # new_playlist_video_count = playlist.video_count
  771. with build('youtube', 'v3', credentials=credentials) as youtube:
  772. for playlist_item_id in playlist_item_ids:
  773. pl_request = youtube.playlistItems().delete(
  774. id=playlist_item_id
  775. )
  776. print(pl_request)
  777. try:
  778. pl_response = pl_request.execute()
  779. print(pl_response)
  780. except googleapiclient.errors.HttpError as e: # failed to delete playlist item
  781. # possible causes:
  782. # playlistItemsNotAccessible (403)
  783. # playlistItemNotFound (404)
  784. # playlistOperationUnsupported (400)
  785. print(e, e.error_details, e.status_code)
  786. continue
  787. # playlistItem was successfully deleted if no HttpError, so delete it from db
  788. # video = playlist.videos.get(playlist_item_id=playlist_item_id)
  789. # new_playlist_video_count -= 1
  790. # new_playlist_duration_in_seconds -= video.duration_in_seconds
  791. # video.delete()
  792. # playlist.video_count = new_playlist_video_count
  793. # playlist.playlist_duration_in_seconds = new_playlist_duration_in_seconds
  794. # playlist.playlist_duration = getHumanizedTimeString(new_playlist_duration_in_seconds)
  795. # playlist.save(update_fields=['video_count', 'playlist_duration', 'playlist_duration_in_seconds'])
  796. # time.sleep(2)
  797. def updatePlaylistDetails(self, user, playlist_id, details):
  798. """
  799. Takes in playlist itemids for the videos in a particular playlist
  800. """
  801. credentials = self.getCredentials(user)
  802. playlist = user.playlists.get(playlist_id=playlist_id)
  803. with build('youtube', 'v3', credentials=credentials) as youtube:
  804. pl_request = youtube.playlists().update(
  805. part="id,snippet,status",
  806. body={
  807. "id": playlist_id,
  808. "snippet": {
  809. "title": details["title"],
  810. "description": details["description"],
  811. },
  812. "status": {
  813. "privacyStatus": "private" if details["privacyStatus"] else "public"
  814. }
  815. },
  816. )
  817. print(details["description"])
  818. try:
  819. pl_response = pl_request.execute()
  820. except googleapiclient.errors.HttpError as e: # failed to update playlist details
  821. # possible causes:
  822. # playlistItemsNotAccessible (403)
  823. # playlistItemNotFound (404)
  824. # playlistOperationUnsupported (400)
  825. # errors i ran into:
  826. # runs into HttpError 400 "Invalid playlist snippet." when the description contains <, >
  827. print("ERROR UPDATING PLAYLIST DETAILS", e, e.status_code, e.error_details)
  828. return -1
  829. print(pl_response)
  830. playlist.name = pl_response['snippet']['title']
  831. playlist.description = pl_response['snippet']['description']
  832. playlist.is_private_on_yt = True if pl_response['status']['privacyStatus'] == "private" else False
  833. playlist.save(update_fields=['name', 'description', 'is_private_on_yt'])
  834. return 0
  835. class Tag(models.Model):
  836. name = models.CharField(max_length=69)
  837. created_by = models.ForeignKey(User, related_name="playlist_tags", on_delete=models.CASCADE)
  838. times_viewed = models.IntegerField(default=0)
  839. # type = models.CharField(max_length=10) # either 'playlist' or 'video'
  840. created_at = models.DateTimeField(auto_now_add=True)
  841. updated_at = models.DateTimeField(auto_now=True)
  842. class Channel(models.Model):
  843. channel_id = models.CharField(max_length=420, default="")
  844. name = models.CharField(max_length=420, default="")
  845. description = models.CharField(max_length=420, default="No description")
  846. thumbnail_url = models.CharField(max_length=420, blank=True)
  847. published_at = models.DateTimeField(blank=True)
  848. # statistics
  849. view_count = models.IntegerField(default=0)
  850. subscriberCount = models.IntegerField(default=0)
  851. hidden_subscriber_count = models.BooleanField(null=True)
  852. video_ount = models.IntegerField(default=0)
  853. is_private = models.BooleanField(null=True)
  854. created_at = models.DateTimeField(auto_now_add=True)
  855. updated_at = models.DateTimeField(auto_now=True)
  856. class Video(models.Model):
  857. untube_user = models.ForeignKey(User, related_name="videos", on_delete=models.CASCADE, null=True)
  858. # video details
  859. video_id = models.CharField(max_length=100)
  860. name = models.CharField(max_length=100, blank=True)
  861. duration = models.CharField(max_length=100, blank=True)
  862. duration_in_seconds = models.IntegerField(default=0)
  863. thumbnail_url = models.CharField(max_length=420, blank=True)
  864. published_at = models.DateTimeField(blank=True, null=True)
  865. description = models.CharField(max_length=420, default="")
  866. has_cc = models.BooleanField(default=False, blank=True, null=True)
  867. # video stats
  868. public_stats_viewable = models.BooleanField(default=True)
  869. view_count = models.IntegerField(default=0)
  870. like_count = models.IntegerField(default=0)
  871. dislike_count = models.IntegerField(default=0)
  872. comment_count = models.IntegerField(default=0)
  873. yt_player_HTML = models.CharField(max_length=420, blank=True)
  874. # video is made by this channel
  875. # channel = models.ForeignKey(Channel, related_name="videos", on_delete=models.CASCADE)
  876. channel_id = models.CharField(max_length=420, blank=True)
  877. channel_name = models.CharField(max_length=420, blank=True)
  878. # which playlist this video belongs to, and position of that video in the playlist (i.e ALL videos belong to some pl)
  879. # playlist = models.ForeignKey(Playlist, related_name="videos", on_delete=models.CASCADE)
  880. # (moved to playlistItem)
  881. # is_duplicate = models.BooleanField(default=False) # True if the same video exists more than once in the playlist
  882. # video_position = models.IntegerField(blank=True)
  883. # NOTE: For a video in db:
  884. # 1.) if both is_unavailable_on_yt and was_deleted_on_yt are true,
  885. # that means the video was originally fine, but then went unavailable when updatePlaylist happened
  886. # 2.) if only is_unavailable_on_yt is true and was_deleted_on_yt is false,
  887. # then that means the video was an unavaiable video when initPlaylist was happening
  888. # 3.) if both is_unavailable_on_yt and was_deleted_on_yt are false, the video is fine, ie up on Youtube
  889. is_unavailable_on_yt = models.BooleanField(
  890. default=False) # True if the video was unavailable (private/deleted) when the API call was first made
  891. was_deleted_on_yt = models.BooleanField(default=False) # True if video became unavailable on a subsequent API call
  892. is_pinned = models.BooleanField(default=False)
  893. is_marked_as_watched = models.BooleanField(default=False) # mark video as watched
  894. is_favorite = models.BooleanField(default=False, blank=True) # mark video as favorite
  895. num_of_accesses = models.IntegerField(default=0) # tracks num of times this video was clicked on by user
  896. user_label = models.CharField(max_length=100, default="") # custom user given name for this video
  897. user_notes = models.CharField(max_length=420, default="") # user can take notes on the video and save them
  898. created_at = models.DateTimeField(auto_now_add=True)
  899. updated_at = models.DateTimeField(auto_now=True)
  900. # for new videos added/modified/deleted in the playlist
  901. video_details_modified = models.BooleanField(
  902. default=False) # is true for videos whose details changed after playlist update
  903. video_details_modified_at = models.DateTimeField(auto_now_add=True) # to set the above false after a day
  904. class Playlist(models.Model):
  905. tags = models.ManyToManyField(Tag, related_name="playlists")
  906. untube_user = models.ForeignKey(User, related_name="playlists", on_delete=models.CASCADE, null=True)
  907. # playlist is made by this channel
  908. channel_id = models.CharField(max_length=420, blank=True)
  909. channel_name = models.CharField(max_length=420, blank=True)
  910. # playlist details
  911. is_yt_mix = models.BooleanField(default=False)
  912. playlist_id = models.CharField(max_length=150)
  913. name = models.CharField(max_length=150, blank=True) # YT PLAYLIST NAMES CAN ONLY HAVE MAX OF 150 CHARS
  914. thumbnail_url = models.CharField(max_length=420, blank=True)
  915. description = models.CharField(max_length=420, default="No description")
  916. video_count = models.IntegerField(default=0)
  917. published_at = models.DateTimeField(blank=True)
  918. is_private_on_yt = models.BooleanField(default=False)
  919. videos = models.ManyToManyField(Video, related_name="playlists")
  920. # eg. "<iframe width=\"640\" height=\"360\" src=\"http://www.youtube.com/embed/videoseries?list=PLFuZstFnF1jFwMDffUhV81h0xeff0TXzm\" frameborder=\"0\" allow=\"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture\" allowfullscreen></iframe>"
  921. playlist_yt_player_HTML = models.CharField(max_length=420, blank=True)
  922. playlist_duration = models.CharField(max_length=69, blank=True) # string version of playlist dureation
  923. playlist_duration_in_seconds = models.IntegerField(default=0)
  924. has_unavailable_videos = models.BooleanField(default=False) # if videos in playlist are private/deleted
  925. has_duplicate_videos = models.BooleanField(default=False) # duplicate videos will not be shown on site
  926. # watch playlist details
  927. # watch_time_left = models.CharField(max_length=150, default="")
  928. started_on = models.DateTimeField(auto_now_add=True, null=True)
  929. last_watched = models.DateTimeField(auto_now_add=True, null=True)
  930. # manage playlist
  931. is_pinned = models.BooleanField(default=False)
  932. user_notes = models.CharField(max_length=420, default="") # user can take notes on the playlist and save them
  933. user_label = models.CharField(max_length=100, default="") # custom user given name for this playlist
  934. marked_as = models.CharField(default="none",
  935. max_length=100) # can be set to "none", "watching", "on-hold", "plan-to-watch"
  936. is_favorite = models.BooleanField(default=False, blank=True) # to mark playlist as fav
  937. num_of_accesses = models.IntegerField(default="0") # tracks num of times this playlist was opened by user
  938. last_accessed_on = models.DateTimeField(default=datetime.datetime.now)
  939. is_user_owned = models.BooleanField(default=True) # represents YouTube playlist owned by user
  940. # set playlist manager
  941. objects = PlaylistManager()
  942. # playlist settings
  943. hide_unavailable_videos = models.BooleanField(default=False)
  944. confirm_before_deleting = models.BooleanField(default=True)
  945. # for import
  946. is_in_db = models.BooleanField(default=False) # is true when all the videos of a playlist have been imported
  947. created_at = models.DateTimeField(auto_now_add=True)
  948. updated_at = models.DateTimeField(auto_now=True)
  949. # for updates
  950. last_full_scan_at = models.DateTimeField(auto_now_add=True)
  951. has_playlist_changed = models.BooleanField(default=False) # determines whether playlist was modified online or not
  952. has_new_updates = models.BooleanField(default=False) # meant to keep track of newly added/unavailable videos
  953. def __str__(self):
  954. return str(self.playlist_id)
  955. def get_channels_list(self):
  956. channels_list = []
  957. num_channels = 0
  958. for video in self.videos.all():
  959. channel = video.channel_name
  960. if channel not in channels_list:
  961. channels_list.append(channel)
  962. num_channels += 1
  963. return [num_channels, channels_list]
  964. def generate_playlist_thumbnail_url(self):
  965. pl_name = self.name
  966. response = requests.get(
  967. f'https://api.unsplash.com/search/photos/?client_id={SECRETS["UNSPLASH_API_ACCESS_KEY"]}&page=1&query={pl_name}')
  968. image = response.json()["results"][0]["urls"]["small"]
  969. print(image)
  970. return image
  971. def get_unavailable_videos_count(self):
  972. return self.video_count - self.get_watchable_videos_count()
  973. # return count of watchable videos, i.e # videos that are not private or deleted in the playlist
  974. def get_watchable_videos_count(self):
  975. return self.playlist_items.filter(Q(is_duplicate=False) & Q(video__is_unavailable_on_yt=False) & Q(video__was_deleted_on_yt=False)).count()
  976. def get_watched_videos_count(self):
  977. return self.playlist_items.filter(Q(is_duplicate=False) &
  978. Q(video__is_marked_as_watched=True) & Q(video__is_unavailable_on_yt=False) & Q(video__was_deleted_on_yt=False)).count()
  979. # diff of time from when playlist was first marked as watched and playlist reached 100% completion
  980. def get_finish_time(self):
  981. return self.last_watched - self.started_on
  982. def get_watch_time_left(self):
  983. unwatched_playlist_items_secs = self.playlist_items.filter(Q(is_duplicate=False) &
  984. Q(video__is_marked_as_watched=False) &
  985. Q(video__is_unavailable_on_yt=False) &
  986. Q(video__was_deleted_on_yt=False)).aggregate(Sum('video__duration_in_seconds'))['video__duration_in_seconds__sum']
  987. watch_time_left = getHumanizedTimeString(unwatched_playlist_items_secs) if unwatched_playlist_items_secs is not None else getHumanizedTimeString(0)
  988. return watch_time_left
  989. # return 0 if playlist empty or all videos in playlist are unavailable
  990. def get_percent_complete(self):
  991. total_playlist_video_count = self.get_watchable_videos_count()
  992. watched_videos = self.playlist_items.filter(Q(is_duplicate=False) &
  993. Q(video__is_marked_as_watched=True) & Q(video__is_unavailable_on_yt=False) & Q(video__was_deleted_on_yt=False))
  994. num_videos_watched = watched_videos.count()
  995. percent_complete = round((num_videos_watched / total_playlist_video_count) * 100,
  996. 1) if total_playlist_video_count != 0 else 0
  997. return percent_complete
  998. def all_videos_unavailable(self):
  999. all_vids_unavailable = False
  1000. if self.videos.filter(
  1001. Q(is_unavailable_on_yt=True) | Q(was_deleted_on_yt=True)).count() == self.video_count:
  1002. all_vids_unavailable = True
  1003. return all_vids_unavailable
  1004. class PlaylistItem(models.Model):
  1005. playlist = models.ForeignKey(Playlist, related_name="playlist_items",
  1006. on_delete=models.CASCADE) # playlist this pl item belongs to
  1007. video = models.ForeignKey(Video, on_delete=models.CASCADE)
  1008. # details
  1009. playlist_item_id = models.CharField(max_length=100) # the item id of the playlist this video beo
  1010. video_position = models.IntegerField(blank=True) # video position in the playlist
  1011. published_at = models.DateTimeField(
  1012. default=datetime.datetime.now) # snippet.publishedAt - The date and time that the item was added to the playlist
  1013. channel_id = models.CharField(null=True,
  1014. max_length=250) # snippet.channelId - The ID that YouTube uses to uniquely identify the user that added the item to the playlist.
  1015. channel_name = models.CharField(null=True,
  1016. max_length=250) # snippet.channelTitle - The channel title of the channel that the playlist item belongs to.
  1017. # video_owner_channel_id = models.CharField(max_length=100)
  1018. # video_owner_channel_title = models.CharField(max_length=100)
  1019. is_duplicate = models.BooleanField(default=False) # True if the same video exists more than once in the playlist
  1020. is_marked_as_watched = models.BooleanField(default=False, blank=True) # mark video as watched
  1021. num_of_accesses = models.IntegerField(default=0) # tracks num of times this video was clicked on by user
  1022. # for new videos added/modified/deleted in the playlist
  1023. # video_details_modified = models.BooleanField(
  1024. # default=False) # is true for videos whose details changed after playlist update
  1025. # video_details_modified_at = models.DateTimeField(auto_now_add=True) # to set the above false after a day
  1026. created_at = models.DateTimeField(auto_now_add=True)
  1027. updated_at = models.DateTimeField(auto_now=True)
  1028. class Pin(models.Model):
  1029. type = models.CharField(max_length=100) # "playlist", "video"
  1030. playlist = models.ForeignKey(Playlist, on_delete=models.CASCADE)
  1031. video = models.ForeignKey(Video, on_delete=models.CASCADE)