2
0

models.py 75 KB

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