models.py 69 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318
  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. is_duplicate = True
  221. else:
  222. playlist.videos.add(video)
  223. playlist_item = PlaylistItem(
  224. playlist_item_id=playlist_item_id,
  225. published_at=item['snippet']['publishedAt'] if 'publishedAt' in
  226. item[
  227. 'snippet'] else None,
  228. channel_id=item['snippet']['channelId'] if 'channelId' in
  229. item[
  230. 'snippet'] else None,
  231. channel_name=item['snippet']['channelTitle'] if 'channelTitle' in
  232. item[
  233. 'snippet'] else None,
  234. video_position=item['snippet']['position'],
  235. playlist=playlist,
  236. video=video,
  237. is_duplicate=is_duplicate
  238. )
  239. playlist_item.save()
  240. # check if the video became unavailable on youtube
  241. if not video.is_unavailable_on_yt and not video.was_deleted_on_yt and (
  242. 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. is_duplicate = True
  308. else:
  309. playlist.videos.add(video)
  310. playlist_item = PlaylistItem(
  311. playlist_item_id=playlist_item_id,
  312. published_at=item['snippet']['publishedAt'] if 'publishedAt' in
  313. item[
  314. 'snippet'] else None,
  315. channel_id=item['snippet']['channelId'] if 'channelId' in
  316. item[
  317. 'snippet'] else None,
  318. channel_name=item['snippet']['channelTitle'] if 'channelTitle' in
  319. item[
  320. 'snippet'] else None,
  321. video_position=item['snippet']['position'],
  322. playlist=playlist,
  323. video=video,
  324. is_duplicate=is_duplicate
  325. )
  326. playlist_item.save()
  327. # check if the video became unavailable on youtube
  328. if not video.is_unavailable_on_yt and not video.was_deleted_on_yt and (
  329. 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(seconds=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. current_video_ids = [playlist_item.video.video_id for playlist_item in playlist.playlist_items.all()]
  501. current_playlist_item_ids = [playlist_item.playlist_item_id for playlist_item in playlist.playlist_items.all()]
  502. updated_playlist_video_count = 0
  503. deleted_playlist_item_ids, unavailable_videos, added_videos = [], [], []
  504. ### GET ALL VIDEO IDS FROM THE PLAYLIST
  505. video_ids = [] # stores list of all video ids for a given playlist
  506. with build('youtube', 'v3', credentials=credentials) as youtube:
  507. pl_request = youtube.playlistItems().list(
  508. part='contentDetails, snippet, status',
  509. playlistId=playlist_id, # get all playlist videos details for this playlist id
  510. maxResults=50
  511. )
  512. # execute the above request, and store the response
  513. try:
  514. pl_response = pl_request.execute()
  515. except googleapiclient.errors.HttpError:
  516. print("Playist was deleted on YouTube")
  517. return [-1, [], [], []]
  518. print("ESTIMATED VIDEO IDS FROM RESPONSE", len(pl_response["items"]))
  519. updated_playlist_video_count += len(pl_response["items"])
  520. for item in pl_response['items']:
  521. playlist_item_id = item["id"]
  522. video_id = item['contentDetails']['videoId']
  523. video_ids.append(video_id)
  524. # check if new playlist item added
  525. if not playlist.playlist_items.filter(playlist_item_id=playlist_item_id).exists():
  526. # if video dne in user's db at all, create and save it
  527. if not user.videos.filter(video_id=video_id).exists():
  528. if (item['snippet']['title'] == "Deleted video" and item['snippet'][
  529. 'description'] == "This video is unavailable.") or (item['snippet'][
  530. 'title'] == "Private video" and
  531. item['snippet'][
  532. '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 (
  558. item['snippet']['title'] == "Deleted video" and
  559. item['snippet'][
  560. 'description'] == "This video is unavailable.") or (
  561. item['snippet']['title'] == "Private video" and item['snippet'][
  562. 'description'] == "This video is private."):
  563. video.was_deleted_on_yt = True
  564. playlist.has_unavailable_videos = True
  565. is_duplicate = False
  566. if not playlist.videos.filter(video_id=video_id).exists():
  567. playlist.videos.add(video)
  568. else:
  569. is_duplicate = 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(
  590. update_fields=['video_details_modified', 'video_details_modified_at', 'was_deleted_on_yt'])
  591. added_videos.append(video)
  592. else: # if playlist item already in playlist
  593. current_playlist_item_ids.remove(playlist_item_id)
  594. playlist_item = playlist.playlist_items.get(playlist_item_id=playlist_item_id)
  595. playlist_item.video_position = item['snippet']['position']
  596. playlist_item.save(update_fields=['video_position'])
  597. # check if the video became unavailable on youtube
  598. if not playlist_item.video.is_unavailable_on_yt and not playlist_item.video.was_deleted_on_yt:
  599. if (item['snippet']['title'] == "Deleted video" and
  600. item['snippet']['description'] == "This video is unavailable.") or (
  601. item['snippet']['title'] == "Private video" and item['snippet'][
  602. 'description'] == "This video is private."):
  603. playlist_item.video.was_deleted_on_yt = True # video went private on YouTube
  604. playlist_item.video.video_details_modified = True
  605. playlist_item.video.video_details_modified_at = datetime.datetime.now(tz=pytz.utc)
  606. playlist_item.video.save(update_fields=['was_deleted_on_yt', 'video_details_modified',
  607. 'video_details_modified_at'])
  608. unavailable_videos.append(playlist_item.video)
  609. while True:
  610. try:
  611. pl_request = youtube.playlistItems().list_next(pl_request, pl_response)
  612. pl_response = pl_request.execute()
  613. updated_playlist_video_count += len(pl_response["items"])
  614. for item in pl_response['items']:
  615. playlist_item_id = item["id"]
  616. video_id = item['contentDetails']['videoId']
  617. video_ids.append(video_id)
  618. # check if new playlist item added
  619. if not playlist.playlist_items.filter(playlist_item_id=playlist_item_id).exists():
  620. # if video dne in user's db at all, create and save it
  621. if not user.videos.filter(video_id=video_id).exists():
  622. if (item['snippet']['title'] == "Deleted video" and item['snippet'][
  623. 'description'] == "This video is unavailable.") or (item['snippet'][
  624. 'title'] == "Private video" and
  625. item['snippet'][
  626. 'description'] == "This video is private."):
  627. video = Video(
  628. video_id=video_id,
  629. name=item['snippet']['title'],
  630. description=item['snippet']['description'],
  631. is_unavailable_on_yt=True,
  632. untube_user=user
  633. )
  634. video.save()
  635. else:
  636. video = Video(
  637. video_id=video_id,
  638. published_at=item['contentDetails']['videoPublishedAt'] if 'videoPublishedAt' in
  639. item[
  640. 'contentDetails'] else None,
  641. name=item['snippet']['title'],
  642. description=item['snippet']['description'],
  643. thumbnail_url=getThumbnailURL(item['snippet']['thumbnails']),
  644. channel_id=item['snippet']['videoOwnerChannelId'],
  645. channel_name=item['snippet']['videoOwnerChannelTitle'],
  646. untube_user=user
  647. )
  648. video.save()
  649. video = user.videos.get(video_id=video_id)
  650. # check if the video became unavailable on youtube
  651. if not video.is_unavailable_on_yt and not video.was_deleted_on_yt and (
  652. item['snippet']['title'] == "Deleted video" and
  653. item['snippet'][
  654. 'description'] == "This video is unavailable.") or (
  655. item['snippet']['title'] == "Private video" and item['snippet'][
  656. 'description'] == "This video is private."):
  657. video.was_deleted_on_yt = True
  658. playlist.has_unavailable_videos = True
  659. is_duplicate = False
  660. if not playlist.videos.filter(video_id=video_id).exists():
  661. playlist.videos.add(video)
  662. else:
  663. is_duplicate = True
  664. playlist_item = PlaylistItem(
  665. playlist_item_id=playlist_item_id,
  666. published_at=item['snippet']['publishedAt'] if 'publishedAt' in
  667. item[
  668. 'snippet'] else None,
  669. channel_id=item['snippet']['channelId'] if 'channelId' in
  670. item[
  671. 'snippet'] else None,
  672. channel_name=item['snippet']['channelTitle'] if 'channelTitle' in
  673. item[
  674. 'snippet'] else None,
  675. video_position=item['snippet']['position'],
  676. playlist=playlist,
  677. video=video,
  678. is_duplicate=is_duplicate
  679. )
  680. playlist_item.save()
  681. video.video_details_modified = True
  682. video.video_details_modified_at = datetime.datetime.now(tz=pytz.utc)
  683. video.save(update_fields=['video_details_modified', 'video_details_modified_at',
  684. 'was_deleted_on_yt'])
  685. added_videos.append(video)
  686. else: # if playlist item already in playlist
  687. current_playlist_item_ids.remove(playlist_item_id)
  688. playlist_item = playlist.playlist_items.get(playlist_item_id=playlist_item_id)
  689. playlist_item.video_position = item['snippet']['position']
  690. playlist_item.save(update_fields=['video_position'])
  691. # check if the video became unavailable on youtube
  692. if not playlist_item.video.is_unavailable_on_yt and not playlist_item.video.was_deleted_on_yt:
  693. if (item['snippet']['title'] == "Deleted video" and
  694. item['snippet']['description'] == "This video is unavailable.") or (
  695. item['snippet']['title'] == "Private video" and item['snippet'][
  696. 'description'] == "This video is private."):
  697. playlist_item.video.was_deleted_on_yt = True # video went private on YouTube
  698. playlist_item.video.video_details_modified = True
  699. playlist_item.video.video_details_modified_at = datetime.datetime.now(tz=pytz.utc)
  700. playlist_item.video.save(
  701. update_fields=['was_deleted_on_yt', 'video_details_modified',
  702. 'video_details_modified_at'])
  703. unavailable_videos.append(playlist_item.video)
  704. except AttributeError:
  705. break
  706. # API expects the video ids to be a string of comma seperated values, not a python list
  707. video_ids_strings = getVideoIdsStrings(video_ids)
  708. # store duration of all the videos in the playlist
  709. vid_durations = []
  710. for video_ids_string in video_ids_strings:
  711. # query the videos resource using API with the string above
  712. vid_request = youtube.videos().list(
  713. part="contentDetails,player,snippet,statistics", # get details of eac video
  714. id=video_ids_string,
  715. maxResults=50
  716. )
  717. vid_response = vid_request.execute()
  718. for item in vid_response['items']:
  719. duration = item['contentDetails']['duration']
  720. vid = playlist.videos.get(video_id=item['id'])
  721. if (item['snippet']['title'] == "Deleted video" or
  722. item['snippet'][
  723. 'description'] == "This video is unavailable.") or (
  724. item['snippet']['title'] == "Private video" or item['snippet'][
  725. 'description'] == "This video is private."):
  726. playlist.has_unavailable_videos = True
  727. vid_durations.append(duration)
  728. vid.video_details_modified = True
  729. vid.video_details_modified_at = datetime.datetime.now(tz=pytz.utc)
  730. vid.save(
  731. update_fields=['video_details_modified', 'video_details_modified_at', 'was_deleted_on_yt',
  732. 'is_unavailable_on_yt'])
  733. continue
  734. vid.name = item['snippet']['title']
  735. vid.description = item['snippet']['description']
  736. vid.thumbnail_url = getThumbnailURL(item['snippet']['thumbnails'])
  737. vid.duration = duration.replace("PT", "")
  738. vid.duration_in_seconds = calculateDuration([duration])
  739. vid.has_cc = True if item['contentDetails']['caption'].lower() == 'true' else False
  740. vid.view_count = item['statistics']['viewCount'] if 'viewCount' in item[
  741. 'statistics'] else -1
  742. vid.like_count = item['statistics']['likeCount'] if 'likeCount' in item[
  743. 'statistics'] else -1
  744. vid.dislike_count = item['statistics']['dislikeCount'] if 'dislikeCount' in item[
  745. 'statistics'] else -1
  746. vid.comment_count = item['statistics']['commentCount'] if 'commentCount' in item[
  747. 'statistics'] else -1
  748. vid.yt_player_HTML = item['player']['embedHtml'] if 'embedHtml' in item['player'] else ''
  749. vid.save()
  750. vid_durations.append(duration)
  751. playlist_duration_in_seconds = calculateDuration(vid_durations)
  752. playlist.playlist_duration_in_seconds = playlist_duration_in_seconds
  753. playlist.playlist_duration = getHumanizedTimeString(playlist_duration_in_seconds)
  754. if len(video_ids) != len(vid_durations) or len(
  755. unavailable_videos) != 0: # that means some videos in the playlist became private/deleted
  756. playlist.has_unavailable_videos = True
  757. playlist.has_playlist_changed = False
  758. playlist.video_count = updated_playlist_video_count
  759. playlist.has_new_updates = True
  760. playlist.save()
  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 deletePlaylistFromYouTube(self, user, playlist_id):
  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. pl_request = youtube.playlists().delete(
  773. id=playlist_id
  774. )
  775. try:
  776. pl_response = pl_request.execute()
  777. print(pl_response)
  778. except googleapiclient.errors.HttpError as e: # failed to delete playlist
  779. # possible causes:
  780. # playlistForbidden (403)
  781. # playlistNotFound (404)
  782. # playlistOperationUnsupported (400)
  783. print(e.error_details, e.status_code)
  784. return -1
  785. # playlistItem was successfully deleted if no HttpError, so delete it from db
  786. playlist.delete()
  787. return 0
  788. def deletePlaylistItems(self, user, playlist_id, playlist_item_ids):
  789. """
  790. Takes in playlist itemids for the videos in a particular playlist
  791. """
  792. credentials = self.getCredentials(user)
  793. playlist = user.playlists.get(playlist_id=playlist_id)
  794. playlist_items = user.playlists.get(playlist_id=playlist_id).playlist_items.select_related('video').filter(
  795. playlist_item_id__in=playlist_item_ids)
  796. # new_playlist_duration_in_seconds = playlist.playlist_duration_in_seconds
  797. # new_playlist_video_count = playlist.video_count
  798. with build('youtube', 'v3', credentials=credentials) as youtube:
  799. for playlist_item in playlist_items:
  800. pl_request = youtube.playlistItems().delete(
  801. id=playlist_item.playlist_item_id
  802. )
  803. print(pl_request)
  804. try:
  805. pl_response = pl_request.execute()
  806. print(pl_response)
  807. except googleapiclient.errors.HttpError as e: # failed to delete playlist item
  808. # possible causes:
  809. # playlistItemsNotAccessible (403)
  810. # playlistItemNotFound (404)
  811. # playlistOperationUnsupported (400)
  812. print(e, e.error_details, e.status_code)
  813. continue
  814. # playlistItem was successfully deleted if no HttpError, so delete it from db
  815. video = playlist_item.video
  816. playlist_item.delete()
  817. if not playlist.playlist_items.filter(video__video_id=video.video_id).exists():
  818. playlist.videos.remove(video)
  819. # video = playlist.videos.get(playlist_item_id=playlist_item_id)
  820. # new_playlist_video_count -= 1
  821. # new_playlist_duration_in_seconds -= video.duration_in_seconds
  822. # video.delete()
  823. # playlist.video_count = new_playlist_video_count
  824. # playlist.playlist_duration_in_seconds = new_playlist_duration_in_seconds
  825. # playlist.playlist_duration = getHumanizedTimeString(new_playlist_duration_in_seconds)
  826. # playlist.save(update_fields=['video_count', 'playlist_duration', 'playlist_duration_in_seconds'])
  827. # time.sleep(2)
  828. def updatePlaylistDetails(self, user, playlist_id, details):
  829. """
  830. Takes in playlist itemids for the videos in a particular playlist
  831. """
  832. credentials = self.getCredentials(user)
  833. playlist = user.playlists.get(playlist_id=playlist_id)
  834. with build('youtube', 'v3', credentials=credentials) as youtube:
  835. pl_request = youtube.playlists().update(
  836. part="id,snippet,status",
  837. body={
  838. "id": playlist_id,
  839. "snippet": {
  840. "title": details["title"],
  841. "description": details["description"],
  842. },
  843. "status": {
  844. "privacyStatus": "private" if details["privacyStatus"] else "public"
  845. }
  846. },
  847. )
  848. print(details["description"])
  849. try:
  850. pl_response = pl_request.execute()
  851. except googleapiclient.errors.HttpError as e: # failed to update playlist details
  852. # possible causes:
  853. # playlistItemsNotAccessible (403)
  854. # playlistItemNotFound (404)
  855. # playlistOperationUnsupported (400)
  856. # errors i ran into:
  857. # runs into HttpError 400 "Invalid playlist snippet." when the description contains <, >
  858. print("ERROR UPDATING PLAYLIST DETAILS", e, e.status_code, e.error_details)
  859. return -1
  860. print(pl_response)
  861. playlist.name = pl_response['snippet']['title']
  862. playlist.description = pl_response['snippet']['description']
  863. playlist.is_private_on_yt = True if pl_response['status']['privacyStatus'] == "private" else False
  864. playlist.save(update_fields=['name', 'description', 'is_private_on_yt'])
  865. return 0
  866. def moveCopyVideosFromPlaylist(self, user, from_playlist_id, to_playlist_ids, playlist_item_ids, action="copy"):
  867. """
  868. Takes in playlist itemids for the videos in a particular playlist
  869. """
  870. credentials = self.getCredentials(user)
  871. playlist_items = user.playlists.get(playlist_id=from_playlist_id).playlist_items.select_related('video').filter(
  872. playlist_item_id__in=playlist_item_ids)
  873. with build('youtube', 'v3', credentials=credentials) as youtube:
  874. for playlist_id in to_playlist_ids:
  875. for playlist_item in playlist_items:
  876. pl_request = youtube.playlistItems().insert(
  877. part="snippet",
  878. body={
  879. "snippet": {
  880. "playlistId": playlist_id,
  881. "position": 0,
  882. "resourceId": {
  883. "kind": "youtube#video",
  884. "videoId": playlist_item.video.video_id,
  885. }
  886. },
  887. }
  888. )
  889. try:
  890. pl_response = pl_request.execute()
  891. except googleapiclient.errors.HttpError as e: # failed to update playlist details
  892. # possible causes:
  893. # playlistItemsNotAccessible (403)
  894. # playlistItemNotFound (404)
  895. # playlistOperationUnsupported (400)
  896. # errors i ran into:
  897. # runs into HttpError 400 "Invalid playlist snippet." when the description contains <, >
  898. print("ERROR UPDATING PLAYLIST DETAILS", e, e.status_code, e.error_details)
  899. return -1
  900. print(pl_response)
  901. if action == "move": # delete from the current playlist
  902. self.deletePlaylistItems(user, from_playlist_id, playlist_item_ids)
  903. return 0
  904. class Tag(models.Model):
  905. name = models.CharField(max_length=69)
  906. created_by = models.ForeignKey(User, related_name="playlist_tags", on_delete=models.CASCADE, null=True)
  907. times_viewed = models.IntegerField(default=0)
  908. # type = models.CharField(max_length=10) # either 'playlist' or 'video'
  909. created_at = models.DateTimeField(auto_now_add=True)
  910. updated_at = models.DateTimeField(auto_now=True)
  911. class Channel(models.Model):
  912. channel_id = models.CharField(max_length=420, default="")
  913. name = models.CharField(max_length=420, default="")
  914. description = models.CharField(max_length=420, default="No description")
  915. thumbnail_url = models.CharField(max_length=420, blank=True)
  916. published_at = models.DateTimeField(blank=True)
  917. # statistics
  918. view_count = models.IntegerField(default=0)
  919. subscriberCount = models.IntegerField(default=0)
  920. hidden_subscriber_count = models.BooleanField(null=True)
  921. video_ount = models.IntegerField(default=0)
  922. is_private = models.BooleanField(null=True)
  923. created_at = models.DateTimeField(auto_now_add=True)
  924. updated_at = models.DateTimeField(auto_now=True)
  925. class Video(models.Model):
  926. untube_user = models.ForeignKey(User, related_name="videos", on_delete=models.CASCADE, null=True)
  927. # video details
  928. video_id = models.CharField(max_length=100)
  929. name = models.CharField(max_length=100, blank=True)
  930. duration = models.CharField(max_length=100, blank=True)
  931. duration_in_seconds = models.IntegerField(default=0)
  932. thumbnail_url = models.CharField(max_length=420, blank=True)
  933. published_at = models.DateTimeField(blank=True, null=True)
  934. description = models.CharField(max_length=420, default="")
  935. has_cc = models.BooleanField(default=False, blank=True, null=True)
  936. # video stats
  937. public_stats_viewable = models.BooleanField(default=True)
  938. view_count = models.IntegerField(default=0)
  939. like_count = models.IntegerField(default=0)
  940. dislike_count = models.IntegerField(default=0)
  941. comment_count = models.IntegerField(default=0)
  942. yt_player_HTML = models.CharField(max_length=420, blank=True)
  943. # video is made by this channel
  944. # channel = models.ForeignKey(Channel, related_name="videos", on_delete=models.CASCADE)
  945. channel_id = models.CharField(max_length=420, blank=True)
  946. channel_name = models.CharField(max_length=420, blank=True)
  947. # which playlist this video belongs to, and position of that video in the playlist (i.e ALL videos belong to some pl)
  948. # playlist = models.ForeignKey(Playlist, related_name="videos", on_delete=models.CASCADE)
  949. # (moved to playlistItem)
  950. # is_duplicate = models.BooleanField(default=False) # True if the same video exists more than once in the playlist
  951. # video_position = models.IntegerField(blank=True)
  952. # NOTE: For a video in db:
  953. # 1.) if both is_unavailable_on_yt and was_deleted_on_yt are true,
  954. # that means the video was originally fine, but then went unavailable when updatePlaylist happened
  955. # 2.) if only is_unavailable_on_yt is true and was_deleted_on_yt is false,
  956. # then that means the video was an unavaiable video when initPlaylist was happening
  957. # 3.) if both is_unavailable_on_yt and was_deleted_on_yt are false, the video is fine, ie up on Youtube
  958. is_unavailable_on_yt = models.BooleanField(
  959. default=False) # True if the video was unavailable (private/deleted) when the API call was first made
  960. was_deleted_on_yt = models.BooleanField(default=False) # True if video became unavailable on a subsequent API call
  961. is_pinned = models.BooleanField(default=False)
  962. is_marked_as_watched = models.BooleanField(default=False) # mark video as watched
  963. is_favorite = models.BooleanField(default=False, blank=True) # mark video as favorite
  964. num_of_accesses = models.IntegerField(default=0) # tracks num of times this video was clicked on by user
  965. user_label = models.CharField(max_length=100, default="") # custom user given name for this video
  966. user_notes = models.CharField(max_length=420, default="") # user can take notes on the video and save them
  967. created_at = models.DateTimeField(auto_now_add=True)
  968. updated_at = models.DateTimeField(auto_now=True)
  969. # for new videos added/modified/deleted in the playlist
  970. video_details_modified = models.BooleanField(
  971. default=False) # is true for videos whose details changed after playlist update
  972. video_details_modified_at = models.DateTimeField(auto_now_add=True) # to set the above false after a day
  973. class Playlist(models.Model):
  974. tags = models.ManyToManyField(Tag, related_name="playlists")
  975. untube_user = models.ForeignKey(User, related_name="playlists", on_delete=models.CASCADE, null=True)
  976. # playlist is made by this channel
  977. channel_id = models.CharField(max_length=420, blank=True)
  978. channel_name = models.CharField(max_length=420, blank=True)
  979. # playlist details
  980. is_yt_mix = models.BooleanField(default=False)
  981. playlist_id = models.CharField(max_length=150)
  982. name = models.CharField(max_length=150, blank=True) # YT PLAYLIST NAMES CAN ONLY HAVE MAX OF 150 CHARS
  983. thumbnail_url = models.CharField(max_length=420, blank=True)
  984. description = models.CharField(max_length=420, default="No description")
  985. video_count = models.IntegerField(default=0)
  986. published_at = models.DateTimeField(blank=True)
  987. is_private_on_yt = models.BooleanField(default=False)
  988. videos = models.ManyToManyField(Video, related_name="playlists")
  989. # 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>"
  990. playlist_yt_player_HTML = models.CharField(max_length=420, blank=True)
  991. playlist_duration = models.CharField(max_length=69, blank=True) # string version of playlist dureation
  992. playlist_duration_in_seconds = models.IntegerField(default=0)
  993. has_unavailable_videos = models.BooleanField(default=False) # if videos in playlist are private/deleted
  994. # watch playlist details
  995. # watch_time_left = models.CharField(max_length=150, default="")
  996. started_on = models.DateTimeField(auto_now_add=True, null=True)
  997. last_watched = models.DateTimeField(auto_now_add=True, null=True)
  998. # manage playlist
  999. is_pinned = models.BooleanField(default=False)
  1000. user_notes = models.CharField(max_length=420, default="") # user can take notes on the playlist and save them
  1001. user_label = models.CharField(max_length=100, default="") # custom user given name for this playlist
  1002. marked_as = models.CharField(default="none",
  1003. max_length=100) # can be set to "none", "watching", "on-hold", "plan-to-watch"
  1004. is_favorite = models.BooleanField(default=False, blank=True) # to mark playlist as fav
  1005. num_of_accesses = models.IntegerField(default="0") # tracks num of times this playlist was opened by user
  1006. last_accessed_on = models.DateTimeField(default=datetime.datetime.now)
  1007. is_user_owned = models.BooleanField(default=True) # represents YouTube playlist owned by user
  1008. # set playlist manager
  1009. objects = PlaylistManager()
  1010. # playlist settings
  1011. hide_unavailable_videos = models.BooleanField(default=False)
  1012. confirm_before_deleting = models.BooleanField(default=True)
  1013. # for import
  1014. is_in_db = models.BooleanField(default=False) # is true when all the videos of a playlist have been imported
  1015. created_at = models.DateTimeField(auto_now_add=True)
  1016. updated_at = models.DateTimeField(auto_now=True)
  1017. # for updates
  1018. last_full_scan_at = models.DateTimeField(auto_now_add=True)
  1019. has_playlist_changed = models.BooleanField(default=False) # determines whether playlist was modified online or not
  1020. has_new_updates = models.BooleanField(default=False) # meant to keep track of newly added/unavailable videos
  1021. def __str__(self):
  1022. return str(self.playlist_id)
  1023. def has_duplicate_videos(self):
  1024. if self.playlist_items.filter(is_duplicate=True).exists():
  1025. return True
  1026. return False
  1027. def get_channels_list(self):
  1028. channels_list = []
  1029. num_channels = 0
  1030. for video in self.videos.all():
  1031. channel = video.channel_name
  1032. if channel not in channels_list:
  1033. channels_list.append(channel)
  1034. num_channels += 1
  1035. return [num_channels, channels_list]
  1036. def generate_playlist_thumbnail_url(self):
  1037. pl_name = self.name
  1038. response = requests.get(
  1039. f'https://api.unsplash.com/search/photos/?client_id={SECRETS["UNSPLASH_API_ACCESS_KEY"]}&page=1&query={pl_name}')
  1040. image = response.json()["results"][0]["urls"]["small"]
  1041. print(image)
  1042. return image
  1043. def get_unavailable_videos_count(self):
  1044. return self.video_count - self.get_watchable_videos_count()
  1045. # return count of watchable videos, i.e # videos that are not private or deleted in the playlist
  1046. def get_watchable_videos_count(self):
  1047. return self.playlist_items.filter(
  1048. Q(is_duplicate=False) & Q(video__is_unavailable_on_yt=False) & Q(video__was_deleted_on_yt=False)).count()
  1049. def get_watched_videos_count(self):
  1050. return self.playlist_items.filter(Q(is_duplicate=False) &
  1051. Q(video__is_marked_as_watched=True) & Q(
  1052. video__is_unavailable_on_yt=False) & Q(video__was_deleted_on_yt=False)).count()
  1053. # diff of time from when playlist was first marked as watched and playlist reached 100% completion
  1054. def get_finish_time(self):
  1055. return self.last_watched - self.started_on
  1056. def get_watch_time_left(self):
  1057. unwatched_playlist_items_secs = self.playlist_items.filter(Q(is_duplicate=False) &
  1058. Q(video__is_marked_as_watched=False) &
  1059. Q(video__is_unavailable_on_yt=False) &
  1060. Q(video__was_deleted_on_yt=False)).aggregate(
  1061. Sum('video__duration_in_seconds'))['video__duration_in_seconds__sum']
  1062. watch_time_left = getHumanizedTimeString(
  1063. unwatched_playlist_items_secs) if unwatched_playlist_items_secs is not None else getHumanizedTimeString(0)
  1064. return watch_time_left
  1065. # return 0 if playlist empty or all videos in playlist are unavailable
  1066. def get_percent_complete(self):
  1067. total_playlist_video_count = self.get_watchable_videos_count()
  1068. watched_videos = self.playlist_items.filter(Q(is_duplicate=False) &
  1069. Q(video__is_marked_as_watched=True) & Q(
  1070. video__is_unavailable_on_yt=False) & Q(video__was_deleted_on_yt=False))
  1071. num_videos_watched = watched_videos.count()
  1072. percent_complete = round((num_videos_watched / total_playlist_video_count) * 100,
  1073. 1) if total_playlist_video_count != 0 else 0
  1074. return percent_complete
  1075. def all_videos_unavailable(self):
  1076. all_vids_unavailable = False
  1077. if self.videos.filter(
  1078. Q(is_unavailable_on_yt=True) | Q(was_deleted_on_yt=True)).count() == self.video_count:
  1079. all_vids_unavailable = True
  1080. return all_vids_unavailable
  1081. class PlaylistItem(models.Model):
  1082. playlist = models.ForeignKey(Playlist, related_name="playlist_items",
  1083. on_delete=models.CASCADE, null=True) # playlist this pl item belongs to
  1084. video = models.ForeignKey(Video, on_delete=models.CASCADE, null=True)
  1085. # details
  1086. playlist_item_id = models.CharField(max_length=100) # the item id of the playlist this video beo
  1087. video_position = models.IntegerField(blank=True) # video position in the playlist
  1088. published_at = models.DateTimeField(
  1089. default=datetime.datetime.now) # snippet.publishedAt - The date and time that the item was added to the playlist
  1090. channel_id = models.CharField(null=True,
  1091. max_length=250) # snippet.channelId - The ID that YouTube uses to uniquely identify the user that added the item to the playlist.
  1092. channel_name = models.CharField(null=True,
  1093. max_length=250) # snippet.channelTitle - The channel title of the channel that the playlist item belongs to.
  1094. # video_owner_channel_id = models.CharField(max_length=100)
  1095. # video_owner_channel_title = models.CharField(max_length=100)
  1096. is_duplicate = models.BooleanField(default=False) # True if the same video exists more than once in the playlist
  1097. is_marked_as_watched = models.BooleanField(default=False, blank=True) # mark video as watched
  1098. num_of_accesses = models.IntegerField(default=0) # tracks num of times this video was clicked on by user
  1099. # for new videos added/modified/deleted in the playlist
  1100. # video_details_modified = models.BooleanField(
  1101. # default=False) # is true for videos whose details changed after playlist update
  1102. # video_details_modified_at = models.DateTimeField(auto_now_add=True) # to set the above false after a day
  1103. created_at = models.DateTimeField(auto_now_add=True)
  1104. updated_at = models.DateTimeField(auto_now=True)
  1105. class Pin(models.Model):
  1106. untube_user = models.ForeignKey(User, related_name="pins",
  1107. on_delete=models.CASCADE, null=True) # untube user this pin is linked to
  1108. type = models.CharField(max_length=100) # "playlist", "video"
  1109. playlist = models.ForeignKey(Playlist, on_delete=models.CASCADE, null=True)
  1110. video = models.ForeignKey(Video, on_delete=models.CASCADE, null=True)