models.py 76 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507
  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. app = SocialApp.objects.get(provider='google')
  21. credentials = Credentials(
  22. token=user.profile.access_token,
  23. refresh_token=user.profile.refresh_token,
  24. token_uri="https://oauth2.googleapis.com/token",
  25. client_id=app.client_id,
  26. client_secret=app.secret,
  27. scopes=['https://www.googleapis.com/auth/youtube']
  28. )
  29. if not credentials.valid:
  30. credentials.refresh(Request())
  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, playlist_link):
  36. if "?" not in playlist_link:
  37. return playlist_link
  38. temp = playlist_link.split("?")[-1].split("&")
  39. for el in temp:
  40. if "list=" in el:
  41. return el.split("list=")[-1]
  42. # Used to check if the user has a vaild YouTube channel
  43. # Will return -1 if user does not have a YouTube channel
  44. def getUserYTChannelID(self, user):
  45. credentials = self.getCredentials(user)
  46. with build('youtube', 'v3', credentials=credentials) as youtube:
  47. pl_request = youtube.channels().list(
  48. part='id,topicDetails,status,statistics,snippet,localizations,contentOwnerDetails,contentDetails,brandingSettings',
  49. mine=True # get playlist details for this user's playlists
  50. )
  51. pl_response = pl_request.execute()
  52. print(pl_response)
  53. if pl_response['pageInfo']['totalResults'] == 0:
  54. print("Looks like do not have a channel on youtube. Create one to import all of your playlists. Retry?")
  55. return -1
  56. else:
  57. user.profile.yt_channel_id = pl_response['items'][0]['id']
  58. user.save()
  59. return 0
  60. # Set pl_id as None to retrive all the playlists from authenticated user. Playlists already imported will be skipped by default.
  61. # Set pl_id = <valid playlist id>, to import that specific playlist into the user's account
  62. def initializePlaylist(self, user, pl_id=None):
  63. '''
  64. Retrieves all of user's playlists from YT and stores them in the Playlist model. Note: only stores
  65. the few of the columns of each playlist in every row, and has is_in_db column as false as no videos will be
  66. saved yet.
  67. :param user: django User object
  68. :param pl_id:
  69. :return:
  70. '''
  71. result = {"status": 0,
  72. "num_of_playlists": 0,
  73. "first_playlist_name": "N/A",
  74. "error_message": "",
  75. "playlist_ids": []}
  76. credentials = self.getCredentials(user)
  77. playlist_ids = []
  78. with build('youtube', 'v3', credentials=credentials) as youtube:
  79. if pl_id is not None:
  80. pl_request = youtube.playlists().list(
  81. part='contentDetails, snippet, id, player, status',
  82. id=pl_id, # get playlist details for this playlist id
  83. maxResults=50
  84. )
  85. else:
  86. print("GETTING ALL USER AUTH PLAYLISTS")
  87. pl_request = youtube.playlists().list(
  88. part='contentDetails, snippet, id, player, status',
  89. mine=True, # get playlist details for this playlist id
  90. maxResults=50
  91. )
  92. # execute the above request, and store the response
  93. try:
  94. pl_response = pl_request.execute()
  95. except googleapiclient.errors.HttpError as e:
  96. print("YouTube channel not found if mine=True")
  97. print("YouTube playlist not found if id=playlist_id")
  98. result["status"] = -1
  99. result["error_message"] = get_message_from_httperror(e)
  100. return result
  101. print(pl_response)
  102. if pl_response["pageInfo"]["totalResults"] == 0:
  103. print("No playlists created yet on youtube.")
  104. result["status"] = -2
  105. return result
  106. playlist_items = []
  107. for item in pl_response["items"]:
  108. playlist_items.append(item)
  109. if pl_id is None:
  110. while True:
  111. try:
  112. pl_request = youtube.playlists().list_next(pl_request, pl_response)
  113. pl_response = pl_request.execute()
  114. for item in pl_response["items"]:
  115. playlist_items.append(item)
  116. except AttributeError:
  117. break
  118. result["num_of_playlists"] = len(playlist_items)
  119. result["first_playlist_name"] = playlist_items[0]["snippet"]["title"]
  120. for item in playlist_items:
  121. playlist_id = item["id"]
  122. playlist_ids.append(playlist_id)
  123. # check if this playlist already exists in user's untube collection
  124. if user.playlists.filter(Q(playlist_id=playlist_id) & Q(is_in_db=True)).exists():
  125. playlist = user.playlists.get(playlist_id=playlist_id)
  126. print(f"PLAYLIST {playlist.name} ({playlist_id}) ALREADY EXISTS IN DB")
  127. # POSSIBLE CASES:
  128. # 1. PLAYLIST HAS DUPLICATE VIDEOS, DELETED VIDS, UNAVAILABLE VIDS
  129. # check if playlist count changed on youtube
  130. if playlist.video_count != item['contentDetails']['itemCount']:
  131. playlist.has_playlist_changed = True
  132. playlist.save(update_fields=['has_playlist_changed'])
  133. if pl_id is not None:
  134. result["status"] = -3
  135. return result
  136. else: # no such playlist in database
  137. print(f"CREATING {item['snippet']['title']} ({playlist_id})")
  138. if user.playlists.filter(Q(playlist_id=playlist_id) & Q(is_in_db=False)).exists():
  139. unimported_playlist = user.playlists.filter(Q(playlist_id=playlist_id) & Q(is_in_db=False)).first()
  140. unimported_playlist.delete()
  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",
  471. str(datetime.datetime.now(pytz.utc) - (playlist.last_full_scan_at + datetime.timedelta(minutes=1))))
  472. """
  473. print("DOING A SMOL SCAN")
  474. with build('youtube', 'v3', credentials=credentials) as youtube:
  475. pl_request = youtube.playlists().list(
  476. part='contentDetails, snippet, id, status',
  477. id=pl_id, # get playlist details for this playlist id
  478. maxResults=50
  479. )
  480. # execute the above request, and store the response
  481. try:
  482. pl_response = pl_request.execute()
  483. except googleapiclient.errors.HttpError:
  484. print("YouTube channel not found if mine=True")
  485. print("YouTube playlist not found if id=playlist_id")
  486. return -1
  487. print("PLAYLIST", pl_response)
  488. playlist_items = []
  489. for item in pl_response["items"]:
  490. playlist_items.append(item)
  491. while True:
  492. try:
  493. pl_request = youtube.playlists().list_next(pl_request, pl_response)
  494. pl_response = pl_request.execute()
  495. for item in pl_response["items"]:
  496. playlist_items.append(item)
  497. except AttributeError:
  498. break
  499. for item in playlist_items:
  500. playlist_id = item["id"]
  501. # check if this playlist already exists in database
  502. if user.playlists.filter(playlist_id=playlist_id).exists():
  503. playlist = user.playlists.get(playlist_id__exact=playlist_id)
  504. print(f"PLAYLIST {playlist.name} ALREADY EXISTS IN DB")
  505. # POSSIBLE CASES:
  506. # 1. PLAYLIST HAS DUPLICATE VIDEOS, DELETED VIDS, UNAVAILABLE VIDS
  507. # check if playlist changed on youtube
  508. if playlist.video_count != item['contentDetails']['itemCount']:
  509. playlist.has_playlist_changed = True
  510. playlist.save()
  511. return [-1, item['contentDetails']['itemCount']]
  512. """
  513. return [0, "no change"]
  514. def updatePlaylist(self, user, playlist_id):
  515. credentials = self.getCredentials(user)
  516. playlist = user.playlists.get(playlist_id__exact=playlist_id)
  517. current_video_ids = [playlist_item.video.video_id for playlist_item in playlist.playlist_items.all()]
  518. current_playlist_item_ids = [playlist_item.playlist_item_id for playlist_item in playlist.playlist_items.all()]
  519. updated_playlist_video_count = 0
  520. deleted_playlist_item_ids, unavailable_videos, added_videos = [], [], []
  521. ### GET ALL VIDEO IDS FROM THE PLAYLIST
  522. video_ids = [] # stores list of all video ids for a given playlist
  523. with build('youtube', 'v3', credentials=credentials) as youtube:
  524. pl_request = youtube.playlistItems().list(
  525. part='contentDetails, snippet, status',
  526. playlistId=playlist_id, # get all playlist videos details for this playlist id
  527. maxResults=50
  528. )
  529. # execute the above request, and store the response
  530. try:
  531. pl_response = pl_request.execute()
  532. except googleapiclient.errors.HttpError:
  533. print("Playist was deleted on YouTube")
  534. return [-1, [], [], []]
  535. print("ESTIMATED VIDEO IDS FROM RESPONSE", len(pl_response["items"]))
  536. updated_playlist_video_count += len(pl_response["items"])
  537. for item in pl_response['items']:
  538. playlist_item_id = item["id"]
  539. video_id = item['contentDetails']['videoId']
  540. video_ids.append(video_id)
  541. # check if new playlist item added
  542. if not playlist.playlist_items.filter(playlist_item_id=playlist_item_id).exists():
  543. # if video dne in user's db at all, create and save it
  544. if not user.videos.filter(video_id=video_id).exists():
  545. if (item['snippet']['title'] == "Deleted video" and item['snippet'][
  546. 'description'] == "This video is unavailable.") or (item['snippet'][
  547. 'title'] == "Private video" and
  548. item['snippet'][
  549. 'description'] == "This video is private."):
  550. video = Video(
  551. video_id=video_id,
  552. name=item['snippet']['title'],
  553. description=item['snippet']['description'],
  554. is_unavailable_on_yt=True,
  555. untube_user=user
  556. )
  557. video.save()
  558. else:
  559. video = Video(
  560. video_id=video_id,
  561. published_at=item['contentDetails']['videoPublishedAt'] if 'videoPublishedAt' in
  562. item[
  563. 'contentDetails'] else None,
  564. name=item['snippet']['title'],
  565. description=item['snippet']['description'],
  566. thumbnail_url=getThumbnailURL(item['snippet']['thumbnails']),
  567. channel_id=item['snippet']['videoOwnerChannelId'],
  568. channel_name=item['snippet']['videoOwnerChannelTitle'],
  569. untube_user=user
  570. )
  571. video.save()
  572. video = user.videos.get(video_id=video_id)
  573. # check if the video became unavailable on youtube
  574. if not video.is_unavailable_on_yt and not video.was_deleted_on_yt and (
  575. item['snippet']['title'] == "Deleted video" and
  576. item['snippet'][
  577. 'description'] == "This video is unavailable.") or (
  578. item['snippet']['title'] == "Private video" and item['snippet'][
  579. 'description'] == "This video is private."):
  580. video.was_deleted_on_yt = True
  581. is_duplicate = False
  582. if not playlist.videos.filter(video_id=video_id).exists():
  583. playlist.videos.add(video)
  584. else:
  585. is_duplicate = True
  586. playlist_item = PlaylistItem(
  587. playlist_item_id=playlist_item_id,
  588. published_at=item['snippet']['publishedAt'] if 'publishedAt' in
  589. item[
  590. 'snippet'] else None,
  591. channel_id=item['snippet']['channelId'] if 'channelId' in
  592. item[
  593. 'snippet'] else None,
  594. channel_name=item['snippet']['channelTitle'] if 'channelTitle' in
  595. item[
  596. 'snippet'] else None,
  597. video_position=item['snippet']['position'],
  598. playlist=playlist,
  599. video=video,
  600. is_duplicate=is_duplicate
  601. )
  602. playlist_item.save()
  603. video.video_details_modified = True
  604. video.video_details_modified_at = datetime.datetime.now(tz=pytz.utc)
  605. video.save(
  606. update_fields=['video_details_modified', 'video_details_modified_at', 'was_deleted_on_yt'])
  607. added_videos.append(video)
  608. else: # if playlist item already in playlist
  609. current_playlist_item_ids.remove(playlist_item_id)
  610. playlist_item = playlist.playlist_items.get(playlist_item_id=playlist_item_id)
  611. playlist_item.video_position = item['snippet']['position']
  612. playlist_item.save(update_fields=['video_position'])
  613. # check if the video became unavailable on youtube
  614. if not playlist_item.video.is_unavailable_on_yt and not playlist_item.video.was_deleted_on_yt:
  615. if (item['snippet']['title'] == "Deleted video" and
  616. item['snippet']['description'] == "This video is unavailable.") or (
  617. item['snippet']['title'] == "Private video" and item['snippet'][
  618. 'description'] == "This video is private."):
  619. playlist_item.video.was_deleted_on_yt = True # video went private on YouTube
  620. playlist_item.video.video_details_modified = True
  621. playlist_item.video.video_details_modified_at = datetime.datetime.now(tz=pytz.utc)
  622. playlist_item.video.save(update_fields=['was_deleted_on_yt', 'video_details_modified',
  623. 'video_details_modified_at'])
  624. unavailable_videos.append(playlist_item.video)
  625. while True:
  626. try:
  627. pl_request = youtube.playlistItems().list_next(pl_request, pl_response)
  628. pl_response = pl_request.execute()
  629. updated_playlist_video_count += len(pl_response["items"])
  630. for item in pl_response['items']:
  631. playlist_item_id = item["id"]
  632. video_id = item['contentDetails']['videoId']
  633. video_ids.append(video_id)
  634. # check if new playlist item added
  635. if not playlist.playlist_items.filter(playlist_item_id=playlist_item_id).exists():
  636. # if video dne in user's db at all, create and save it
  637. if not user.videos.filter(video_id=video_id).exists():
  638. if (item['snippet']['title'] == "Deleted video" and item['snippet'][
  639. 'description'] == "This video is unavailable.") or (item['snippet'][
  640. 'title'] == "Private video" and
  641. item['snippet'][
  642. 'description'] == "This video is private."):
  643. video = Video(
  644. video_id=video_id,
  645. name=item['snippet']['title'],
  646. description=item['snippet']['description'],
  647. is_unavailable_on_yt=True,
  648. untube_user=user
  649. )
  650. video.save()
  651. else:
  652. video = Video(
  653. video_id=video_id,
  654. published_at=item['contentDetails']['videoPublishedAt'] if 'videoPublishedAt' in
  655. item[
  656. 'contentDetails'] else None,
  657. name=item['snippet']['title'],
  658. description=item['snippet']['description'],
  659. thumbnail_url=getThumbnailURL(item['snippet']['thumbnails']),
  660. channel_id=item['snippet']['videoOwnerChannelId'],
  661. channel_name=item['snippet']['videoOwnerChannelTitle'],
  662. untube_user=user
  663. )
  664. video.save()
  665. video = user.videos.get(video_id=video_id)
  666. # check if the video became unavailable on youtube
  667. if not video.is_unavailable_on_yt and not video.was_deleted_on_yt and (
  668. item['snippet']['title'] == "Deleted video" and
  669. item['snippet'][
  670. 'description'] == "This video is unavailable.") or (
  671. item['snippet']['title'] == "Private video" and item['snippet'][
  672. 'description'] == "This video is private."):
  673. video.was_deleted_on_yt = True
  674. is_duplicate = False
  675. if not playlist.videos.filter(video_id=video_id).exists():
  676. playlist.videos.add(video)
  677. else:
  678. is_duplicate = True
  679. playlist_item = PlaylistItem(
  680. playlist_item_id=playlist_item_id,
  681. published_at=item['snippet']['publishedAt'] if 'publishedAt' in
  682. item[
  683. 'snippet'] else None,
  684. channel_id=item['snippet']['channelId'] if 'channelId' in
  685. item[
  686. 'snippet'] else None,
  687. channel_name=item['snippet']['channelTitle'] if 'channelTitle' in
  688. item[
  689. 'snippet'] else None,
  690. video_position=item['snippet']['position'],
  691. playlist=playlist,
  692. video=video,
  693. is_duplicate=is_duplicate
  694. )
  695. playlist_item.save()
  696. video.video_details_modified = True
  697. video.video_details_modified_at = datetime.datetime.now(tz=pytz.utc)
  698. video.save(update_fields=['video_details_modified', 'video_details_modified_at',
  699. 'was_deleted_on_yt'])
  700. added_videos.append(video)
  701. else: # if playlist item already in playlist
  702. current_playlist_item_ids.remove(playlist_item_id)
  703. playlist_item = playlist.playlist_items.get(playlist_item_id=playlist_item_id)
  704. playlist_item.video_position = item['snippet']['position']
  705. playlist_item.save(update_fields=['video_position'])
  706. # check if the video became unavailable on youtube
  707. if not playlist_item.video.is_unavailable_on_yt and not playlist_item.video.was_deleted_on_yt:
  708. if (item['snippet']['title'] == "Deleted video" and
  709. item['snippet']['description'] == "This video is unavailable.") or (
  710. item['snippet']['title'] == "Private video" and item['snippet'][
  711. 'description'] == "This video is private."):
  712. playlist_item.video.was_deleted_on_yt = True # video went private on YouTube
  713. playlist_item.video.video_details_modified = True
  714. playlist_item.video.video_details_modified_at = datetime.datetime.now(tz=pytz.utc)
  715. playlist_item.video.save(
  716. update_fields=['was_deleted_on_yt', 'video_details_modified',
  717. 'video_details_modified_at'])
  718. unavailable_videos.append(playlist_item.video)
  719. except AttributeError:
  720. break
  721. # API expects the video ids to be a string of comma seperated values, not a python list
  722. video_ids_strings = getVideoIdsStrings(video_ids)
  723. # store duration of all the videos in the playlist
  724. vid_durations = []
  725. for video_ids_string in video_ids_strings:
  726. # query the videos resource using API with the string above
  727. vid_request = youtube.videos().list(
  728. part="contentDetails,player,snippet,statistics", # get details of eac video
  729. id=video_ids_string,
  730. maxResults=50
  731. )
  732. vid_response = vid_request.execute()
  733. for item in vid_response['items']:
  734. duration = item['contentDetails']['duration']
  735. vid = playlist.videos.get(video_id=item['id'])
  736. if (item['snippet']['title'] == "Deleted video" or
  737. item['snippet'][
  738. 'description'] == "This video is unavailable.") or (
  739. item['snippet']['title'] == "Private video" or item['snippet'][
  740. 'description'] == "This video is private."):
  741. vid_durations.append(duration)
  742. vid.video_details_modified = True
  743. vid.video_details_modified_at = datetime.datetime.now(tz=pytz.utc)
  744. vid.save(
  745. update_fields=['video_details_modified', 'video_details_modified_at', 'was_deleted_on_yt',
  746. 'is_unavailable_on_yt'])
  747. continue
  748. vid.name = item['snippet']['title']
  749. vid.description = item['snippet']['description']
  750. vid.thumbnail_url = getThumbnailURL(item['snippet']['thumbnails'])
  751. vid.duration = duration.replace("PT", "")
  752. vid.duration_in_seconds = calculateDuration([duration])
  753. vid.has_cc = True if item['contentDetails']['caption'].lower() == 'true' else False
  754. vid.view_count = item['statistics']['viewCount'] if 'viewCount' in item[
  755. 'statistics'] else -1
  756. vid.like_count = item['statistics']['likeCount'] if 'likeCount' in item[
  757. 'statistics'] else -1
  758. vid.dislike_count = item['statistics']['dislikeCount'] if 'dislikeCount' in item[
  759. 'statistics'] else -1
  760. vid.comment_count = item['statistics']['commentCount'] if 'commentCount' in item[
  761. 'statistics'] else -1
  762. vid.yt_player_HTML = item['player']['embedHtml'] if 'embedHtml' in item['player'] else ''
  763. vid.save()
  764. vid_durations.append(duration)
  765. playlist_duration_in_seconds = calculateDuration(vid_durations)
  766. playlist.playlist_duration_in_seconds = playlist_duration_in_seconds
  767. playlist.playlist_duration = getHumanizedTimeString(playlist_duration_in_seconds)
  768. playlist.has_playlist_changed = False
  769. playlist.video_count = updated_playlist_video_count
  770. playlist.has_new_updates = True
  771. playlist.last_full_scan_at = datetime.datetime.now(pytz.utc)
  772. playlist.save()
  773. deleted_playlist_item_ids = current_playlist_item_ids # left out playlist_item_ids
  774. return [0, deleted_playlist_item_ids, unavailable_videos, added_videos]
  775. def deletePlaylistFromYouTube(self, user, playlist_id):
  776. """
  777. Takes in playlist itemids for the videos in a particular playlist
  778. """
  779. credentials = self.getCredentials(user)
  780. playlist = user.playlists.get(playlist_id=playlist_id)
  781. # new_playlist_duration_in_seconds = playlist.playlist_duration_in_seconds
  782. # new_playlist_video_count = playlist.video_count
  783. with build('youtube', 'v3', credentials=credentials) as youtube:
  784. pl_request = youtube.playlists().delete(
  785. id=playlist_id
  786. )
  787. try:
  788. pl_response = pl_request.execute()
  789. print(pl_response)
  790. except googleapiclient.errors.HttpError as e: # failed to delete playlist
  791. # possible causes:
  792. # playlistForbidden (403)
  793. # playlistNotFound (404)
  794. # playlistOperationUnsupported (400)
  795. print(e.error_details, e.status_code)
  796. return [-1, get_message_from_httperror(e), e.status_code]
  797. # playlistItem was successfully deleted if no HttpError, so delete it from db
  798. video_ids = [video.video_id for video in playlist.videos.all()]
  799. playlist.delete()
  800. for video_id in video_ids:
  801. video = user.videos.get(video_id=video_id)
  802. if video.playlists.all().count() == 0:
  803. video.delete()
  804. return [0]
  805. def deletePlaylistItems(self, user, playlist_id, playlist_item_ids):
  806. """
  807. Takes in playlist itemids for the videos in a particular playlist
  808. """
  809. credentials = self.getCredentials(user)
  810. playlist = user.playlists.get(playlist_id=playlist_id)
  811. playlist_items = user.playlists.get(playlist_id=playlist_id).playlist_items.select_related('video').filter(
  812. playlist_item_id__in=playlist_item_ids)
  813. new_playlist_duration_in_seconds = playlist.playlist_duration_in_seconds
  814. new_playlist_video_count = playlist.video_count
  815. with build('youtube', 'v3', credentials=credentials) as youtube:
  816. for playlist_item in playlist_items:
  817. pl_request = youtube.playlistItems().delete(
  818. id=playlist_item.playlist_item_id
  819. )
  820. print(pl_request)
  821. try:
  822. pl_response = pl_request.execute()
  823. print(pl_response)
  824. except googleapiclient.errors.HttpError as e: # failed to delete playlist item
  825. # possible causes:
  826. # playlistItemsNotAccessible (403)
  827. # playlistItemNotFound (404)
  828. # playlistOperationUnsupported (400)
  829. print(e, e.error_details, e.status_code)
  830. continue
  831. # playlistItem was successfully deleted if no HttpError, so delete it from db
  832. video = playlist_item.video
  833. playlist_item.delete()
  834. if not playlist.playlist_items.filter(video__video_id=video.video_id).exists():
  835. playlist.videos.remove(video)
  836. # if video.playlists.all().count() == 0: # also delete the video if it is not found in other playlists
  837. # video.delete()
  838. if playlist_id == "LL":
  839. video.liked = False
  840. video.save(update_fields=['liked'])
  841. new_playlist_video_count -= 1
  842. new_playlist_duration_in_seconds -= video.duration_in_seconds
  843. playlist.video_count = new_playlist_video_count
  844. if new_playlist_video_count == 0:
  845. playlist.thumbnail_url = ""
  846. playlist.playlist_duration_in_seconds = new_playlist_duration_in_seconds
  847. playlist.playlist_duration = getHumanizedTimeString(new_playlist_duration_in_seconds)
  848. playlist.save(
  849. update_fields=['video_count', 'playlist_duration', 'playlist_duration_in_seconds', 'thumbnail_url'])
  850. # time.sleep(2)
  851. playlist_items = playlist.playlist_items.select_related('video').order_by("video_position")
  852. counter = 0
  853. videos = []
  854. for playlist_item in playlist_items:
  855. playlist_item.video_position = counter
  856. is_duplicate = False
  857. if playlist_item.video_id in videos:
  858. is_duplicate = True
  859. else:
  860. videos.append(playlist_item.video_id)
  861. playlist_item.is_duplicate = is_duplicate
  862. playlist_item.save(update_fields=['video_position', 'is_duplicate'])
  863. counter += 1
  864. def deleteSpecificPlaylistItems(self, user, playlist_id, command):
  865. playlist = user.playlists.get(playlist_id=playlist_id)
  866. playlist_items = []
  867. if command == "duplicate":
  868. playlist_items = playlist.playlist_items.filter(is_duplicate=True)
  869. elif command == "unavailable":
  870. playlist_items = playlist.playlist_items.filter(
  871. Q(video__is_unavailable_on_yt=True) & Q(video__was_deleted_on_yt=False))
  872. playlist_item_ids = []
  873. for playlist_item in playlist_items:
  874. playlist_item_ids.append(playlist_item.playlist_item_id)
  875. self.deletePlaylistItems(user, playlist_id, playlist_item_ids)
  876. def createNewPlaylist(self, user, playlist_name, playlist_description):
  877. """
  878. Takes in playlist details and creates a new private playlist in the user's account
  879. """
  880. credentials = self.getCredentials(user)
  881. result = {
  882. "status": 0,
  883. "playlist_id": None
  884. }
  885. with build('youtube', 'v3', credentials=credentials) as youtube:
  886. pl_request = youtube.playlists().insert(
  887. part='snippet,status',
  888. body={
  889. "snippet": {
  890. "title": playlist_name,
  891. "description": playlist_description,
  892. "defaultLanguage": "en"
  893. },
  894. "status": {
  895. "privacyStatus": "private"
  896. }
  897. }
  898. )
  899. try:
  900. pl_response = pl_request.execute()
  901. except googleapiclient.errors.HttpError as e: # failed to create playlist
  902. print(e.status_code, e.error_details)
  903. if e.status_code == 400: # maxPlaylistExceeded
  904. result["status"] = 400
  905. result["status"] = -1
  906. result["playlist_id"] = pl_response["id"]
  907. return result
  908. def updatePlaylistDetails(self, user, playlist_id, details):
  909. """
  910. Takes in playlist itemids for the videos in a particular playlist
  911. """
  912. credentials = self.getCredentials(user)
  913. playlist = user.playlists.get(playlist_id=playlist_id)
  914. with build('youtube', 'v3', credentials=credentials) as youtube:
  915. pl_request = youtube.playlists().update(
  916. part="id,snippet,status",
  917. body={
  918. "id": playlist_id,
  919. "snippet": {
  920. "title": details["title"],
  921. "description": details["description"],
  922. },
  923. "status": {
  924. "privacyStatus": "private" if details["privacyStatus"] else "public"
  925. }
  926. },
  927. )
  928. print(details["description"])
  929. try:
  930. pl_response = pl_request.execute()
  931. except googleapiclient.errors.HttpError as e: # failed to update playlist details
  932. # possible causes:
  933. # playlistItemsNotAccessible (403)
  934. # playlistItemNotFound (404)
  935. # playlistOperationUnsupported (400)
  936. # errors i ran into:
  937. # runs into HttpError 400 "Invalid playlist snippet." when the description contains <, >
  938. print("ERROR UPDATING PLAYLIST DETAILS", e, e.status_code, e.error_details)
  939. return -1
  940. print(pl_response)
  941. playlist.name = pl_response['snippet']['title']
  942. playlist.description = pl_response['snippet']['description']
  943. playlist.is_private_on_yt = True if pl_response['status']['privacyStatus'] == "private" else False
  944. playlist.save(update_fields=['name', 'description', 'is_private_on_yt'])
  945. return 0
  946. def moveCopyVideosFromPlaylist(self, user, from_playlist_id, to_playlist_ids, playlist_item_ids, action="copy"):
  947. """
  948. Takes in playlist itemids for the videos in a particular playlist
  949. """
  950. credentials = self.getCredentials(user)
  951. playlist_items = user.playlists.get(playlist_id=from_playlist_id).playlist_items.select_related('video').filter(
  952. playlist_item_id__in=playlist_item_ids)
  953. result = {
  954. "status": 0,
  955. "num_moved_copied": 0,
  956. "playlistContainsMaximumNumberOfVideos": False,
  957. }
  958. with build('youtube', 'v3', credentials=credentials) as youtube:
  959. for playlist_id in to_playlist_ids:
  960. for playlist_item in playlist_items:
  961. pl_request = youtube.playlistItems().insert(
  962. part="snippet",
  963. body={
  964. "snippet": {
  965. "playlistId": playlist_id,
  966. "position": 0,
  967. "resourceId": {
  968. "kind": "youtube#video",
  969. "videoId": playlist_item.video.video_id,
  970. }
  971. },
  972. }
  973. )
  974. try:
  975. pl_response = pl_request.execute()
  976. except googleapiclient.errors.HttpError as e: # failed to update playlist details
  977. # possible causes:
  978. # playlistItemsNotAccessible (403)
  979. # playlistItemNotFound (404) - I ran into 404 while trying to copy an unavailable video into another playlist
  980. # playlistOperationUnsupported (400)
  981. # errors i ran into:
  982. # runs into HttpError 400 "Invalid playlist snippet." when the description contains <, >
  983. print("ERROR UPDATING PLAYLIST DETAILS", e.status_code, e.error_details)
  984. if e.status_code == 400:
  985. pl_request = youtube.playlistItems().insert(
  986. part="snippet",
  987. body={
  988. "snippet": {
  989. "playlistId": playlist_id,
  990. "resourceId": {
  991. "kind": "youtube#video",
  992. "videoId": playlist_item.video.video_id,
  993. }
  994. },
  995. }
  996. )
  997. try:
  998. pl_response = pl_request.execute()
  999. except googleapiclient.errors.HttpError as e:
  1000. result['status'] = -1
  1001. elif e.status_code == 403:
  1002. result["playlistContainsMaximumNumberOfVideos"] = True
  1003. else:
  1004. result['status'] = -1
  1005. result["num_moved_copied"] += 1
  1006. if action == "move": # delete from the current playlist
  1007. self.deletePlaylistItems(user, from_playlist_id, playlist_item_ids)
  1008. return result
  1009. def addVideosToPlaylist(self, user, playlist_id, video_ids):
  1010. """
  1011. Takes in playlist itemids for the videos in a particular playlist
  1012. """
  1013. credentials = self.getCredentials(user)
  1014. result = {
  1015. "num_added": 0,
  1016. "playlistContainsMaximumNumberOfVideos": False,
  1017. }
  1018. added = 0
  1019. with build('youtube', 'v3', credentials=credentials) as youtube:
  1020. for video_id in video_ids:
  1021. pl_request = youtube.playlistItems().insert(
  1022. part="snippet",
  1023. body={
  1024. "snippet": {
  1025. "playlistId": playlist_id,
  1026. "position": 0,
  1027. "resourceId": {
  1028. "kind": "youtube#video",
  1029. "videoId": video_id,
  1030. }
  1031. },
  1032. }
  1033. )
  1034. try:
  1035. pl_response = pl_request.execute()
  1036. except googleapiclient.errors.HttpError as e: # failed to update add video to playlis
  1037. print("ERROR ADDDING VIDEOS TO PLAYLIST", e.status_code, e.error_details)
  1038. if e.status_code == 400: # manualSortRequired - see errors https://developers.google.com/youtube/v3/docs/playlistItems/insert
  1039. pl_request = youtube.playlistItems().insert(
  1040. part="snippet",
  1041. body={
  1042. "snippet": {
  1043. "playlistId": playlist_id,
  1044. "resourceId": {
  1045. "kind": "youtube#video",
  1046. "videoId": video_id,
  1047. }
  1048. },
  1049. }
  1050. )
  1051. try:
  1052. pl_response = pl_request.execute()
  1053. except googleapiclient.errors.HttpError as e: # failed to update playlist details
  1054. pass
  1055. elif e.status_code == 403:
  1056. result["playlistContainsMaximumNumberOfVideos"] = True
  1057. continue
  1058. added += 1
  1059. result["num_added"] = added
  1060. try:
  1061. playlist = user.playlists.get(playlist_id=playlist_id)
  1062. if added > 0:
  1063. playlist.has_playlist_changed = True
  1064. playlist.save(update_fields=['has_playlist_changed'])
  1065. except:
  1066. pass
  1067. return result
  1068. class Tag(models.Model):
  1069. name = models.CharField(max_length=69)
  1070. created_by = models.ForeignKey(User, related_name="playlist_tags", on_delete=models.CASCADE, null=True)
  1071. times_viewed = models.IntegerField(default=0)
  1072. times_viewed_per_week = models.IntegerField(default=0)
  1073. # type = models.CharField(max_length=10) # either 'playlist' or 'video'
  1074. last_views_reset = models.DateTimeField(default=datetime.datetime.now)
  1075. created_at = models.DateTimeField(auto_now_add=True)
  1076. updated_at = models.DateTimeField(auto_now=True)
  1077. class Video(models.Model):
  1078. untube_user = models.ForeignKey(User, related_name="videos", on_delete=models.CASCADE, null=True)
  1079. # video details
  1080. video_id = models.CharField(max_length=100)
  1081. name = models.CharField(max_length=100, blank=True)
  1082. duration = models.CharField(max_length=100, blank=True)
  1083. duration_in_seconds = models.BigIntegerField(default=0)
  1084. thumbnail_url = models.TextField(blank=True)
  1085. published_at = models.DateTimeField(blank=True, null=True)
  1086. description = models.TextField(default="")
  1087. has_cc = models.BooleanField(default=False, blank=True, null=True)
  1088. liked = models.BooleanField(default=False) # whether this video liked on YouTube by user or not
  1089. # video stats
  1090. public_stats_viewable = models.BooleanField(default=True)
  1091. view_count = models.BigIntegerField(default=0)
  1092. like_count = models.BigIntegerField(default=0)
  1093. dislike_count = models.BigIntegerField(default=0)
  1094. comment_count = models.BigIntegerField(default=0)
  1095. yt_player_HTML = models.TextField(blank=True)
  1096. # video is made by this channel
  1097. # channel = models.ForeignKey(Channel, related_name="videos", on_delete=models.CASCADE)
  1098. channel_id = models.TextField(blank=True)
  1099. channel_name = models.TextField(blank=True)
  1100. # which playlist this video belongs to, and position of that video in the playlist (i.e ALL videos belong to some pl)
  1101. # playlist = models.ForeignKey(Playlist, related_name="videos", on_delete=models.CASCADE)
  1102. # (moved to playlistItem)
  1103. # is_duplicate = models.BooleanField(default=False) # True if the same video exists more than once in the playlist
  1104. # video_position = models.IntegerField(blank=True)
  1105. # NOTE: For a video in db:
  1106. # 1.) if both is_unavailable_on_yt and was_deleted_on_yt are true,
  1107. # that means the video was originally fine, but then went unavailable when updatePlaylist happened
  1108. # 2.) if only is_unavailable_on_yt is true and was_deleted_on_yt is false,
  1109. # then that means the video was an unavaiable video when initPlaylist was happening
  1110. # 3.) if both is_unavailable_on_yt and was_deleted_on_yt are false, the video is fine, ie up on Youtube
  1111. is_unavailable_on_yt = models.BooleanField(
  1112. default=False) # True if the video was unavailable (private/deleted) when the API call was first made
  1113. was_deleted_on_yt = models.BooleanField(default=False) # True if video became unavailable on a subsequent API call
  1114. is_planned_to_watch = models.BooleanField(default=False) # mark video as plan to watch later
  1115. is_marked_as_watched = models.BooleanField(default=False) # mark video as watched
  1116. is_favorite = models.BooleanField(default=False, blank=True) # mark video as favorite
  1117. num_of_accesses = models.IntegerField(default=0) # tracks num of times this video was clicked on by user
  1118. user_label = models.CharField(max_length=100, blank=True) # custom user given name for this video
  1119. user_notes = models.TextField(blank=True) # user can take notes on the video and save them
  1120. created_at = models.DateTimeField(auto_now_add=True)
  1121. updated_at = models.DateTimeField(auto_now=True)
  1122. # for new videos added/modified/deleted in the playlist
  1123. video_details_modified = models.BooleanField(
  1124. default=False) # is true for videos whose details changed after playlist update
  1125. video_details_modified_at = models.DateTimeField(auto_now_add=True) # to set the above false after a day
  1126. class Playlist(models.Model):
  1127. tags = models.ManyToManyField(Tag, related_name="playlists")
  1128. untube_user = models.ForeignKey(User, related_name="playlists", on_delete=models.CASCADE, null=True)
  1129. # playlist is made by this channel
  1130. channel_id = models.TextField(blank=True)
  1131. channel_name = models.TextField(blank=True)
  1132. # playlist details
  1133. is_yt_mix = models.BooleanField(default=False)
  1134. playlist_id = models.CharField(max_length=150)
  1135. name = models.CharField(max_length=150, blank=True) # YT PLAYLIST NAMES CAN ONLY HAVE MAX OF 150 CHARS
  1136. thumbnail_url = models.TextField(blank=True)
  1137. description = models.TextField(default="No description")
  1138. video_count = models.IntegerField(default=0)
  1139. published_at = models.DateTimeField(blank=True)
  1140. is_private_on_yt = models.BooleanField(default=False)
  1141. videos = models.ManyToManyField(Video, related_name="playlists")
  1142. # 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>"
  1143. playlist_yt_player_HTML = models.TextField(blank=True)
  1144. playlist_duration = models.CharField(max_length=69, blank=True) # string version of playlist dureation
  1145. playlist_duration_in_seconds = models.BigIntegerField(default=0)
  1146. # watch playlist details
  1147. # watch_time_left = models.CharField(max_length=150, default="")
  1148. started_on = models.DateTimeField(auto_now_add=True, null=True)
  1149. last_watched = models.DateTimeField(auto_now_add=True, null=True)
  1150. # manage playlist
  1151. user_notes = models.TextField(default="") # user can take notes on the playlist and save them
  1152. user_label = models.CharField(max_length=100, default="") # custom user given name for this playlist
  1153. marked_as = models.CharField(default="none",
  1154. max_length=100) # can be set to "none", "watching", "on-hold", "plan-to-watch"
  1155. is_favorite = models.BooleanField(default=False, blank=True) # to mark playlist as fav
  1156. num_of_accesses = models.IntegerField(default="0") # tracks num of times this playlist was opened by user
  1157. last_accessed_on = models.DateTimeField(default=datetime.datetime.now)
  1158. is_user_owned = models.BooleanField(default=True) # represents YouTube playlist owned by user
  1159. # set playlist manager
  1160. objects = PlaylistManager()
  1161. # playlist settings (moved to global preferences)
  1162. # hide_unavailable_videos = models.BooleanField(default=False)
  1163. # confirm_before_deleting = models.BooleanField(default=True)
  1164. auto_check_for_updates = models.BooleanField(default=False)
  1165. # for import
  1166. is_in_db = models.BooleanField(default=False) # is true when all the videos of a playlist have been imported
  1167. created_at = models.DateTimeField(auto_now_add=True)
  1168. updated_at = models.DateTimeField(auto_now=True)
  1169. # for updates
  1170. last_full_scan_at = models.DateTimeField(auto_now_add=True)
  1171. has_playlist_changed = models.BooleanField(default=False) # determines whether playlist was modified online or not
  1172. has_new_updates = models.BooleanField(default=False) # meant to keep track of newly added/unavailable videos
  1173. def __str__(self):
  1174. return str(self.playlist_id)
  1175. def has_unavailable_videos(self):
  1176. if self.playlist_items.filter(Q(video__is_unavailable_on_yt=True) & Q(video__was_deleted_on_yt=False)).exists():
  1177. return True
  1178. return False
  1179. def has_duplicate_videos(self):
  1180. if self.playlist_items.filter(is_duplicate=True).exists():
  1181. return True
  1182. return False
  1183. def get_channels_list(self):
  1184. channels_list = []
  1185. num_channels = 0
  1186. for video in self.videos.all():
  1187. channel = video.channel_name
  1188. if channel not in channels_list:
  1189. channels_list.append(channel)
  1190. num_channels += 1
  1191. return [num_channels, channels_list]
  1192. def generate_playlist_thumbnail_url(self):
  1193. """
  1194. Generates a playlist thumnail url based on the playlist name
  1195. """
  1196. pl_name = self.name
  1197. response = requests.get(
  1198. f'https://api.unsplash.com/search/photos/?client_id={SECRETS["UNSPLASH_API_ACCESS_KEY"]}&page=1&query={pl_name}')
  1199. image = response.json()["results"][0]["urls"]["small"]
  1200. print(image)
  1201. return image
  1202. def get_playlist_thumbnail_url(self):
  1203. playlist_items = self.playlist_items.filter(
  1204. Q(video__was_deleted_on_yt=False) & Q(video__is_unavailable_on_yt=False))
  1205. if playlist_items.exists():
  1206. return playlist_items.first().video.thumbnail_url
  1207. else:
  1208. return "https://i.ytimg.com/vi/9219YrnwDXE/maxresdefault.jpg"
  1209. def get_unavailable_videos_count(self):
  1210. return self.video_count - self.get_watchable_videos_count()
  1211. def get_duplicate_videos_count(self):
  1212. return self.playlist_items.filter(is_duplicate=True).count()
  1213. # return count of watchable videos, i.e # videos that are not private or deleted in the playlist
  1214. def get_watchable_videos_count(self):
  1215. return self.playlist_items.filter(
  1216. Q(is_duplicate=False) & Q(video__is_unavailable_on_yt=False) & Q(video__was_deleted_on_yt=False)).count()
  1217. def get_watched_videos_count(self):
  1218. return self.playlist_items.filter(Q(is_duplicate=False) &
  1219. Q(video__is_marked_as_watched=True) & Q(
  1220. video__is_unavailable_on_yt=False) & Q(video__was_deleted_on_yt=False)).count()
  1221. # diff of time from when playlist was first marked as watched and playlist reached 100% completion
  1222. def get_finish_time(self):
  1223. return self.last_watched - self.started_on
  1224. def get_watch_time_left(self):
  1225. unwatched_playlist_items_secs = self.playlist_items.filter(Q(is_duplicate=False) &
  1226. Q(video__is_marked_as_watched=False) &
  1227. Q(video__is_unavailable_on_yt=False) &
  1228. Q(video__was_deleted_on_yt=False)).aggregate(
  1229. Sum('video__duration_in_seconds'))['video__duration_in_seconds__sum']
  1230. watch_time_left = getHumanizedTimeString(
  1231. unwatched_playlist_items_secs) if unwatched_playlist_items_secs is not None else getHumanizedTimeString(0)
  1232. return watch_time_left
  1233. # return 0 if playlist empty or all videos in playlist are unavailable
  1234. def get_percent_complete(self):
  1235. total_playlist_video_count = self.get_watchable_videos_count()
  1236. watched_videos = self.playlist_items.filter(Q(is_duplicate=False) &
  1237. Q(video__is_marked_as_watched=True) & Q(
  1238. video__is_unavailable_on_yt=False) & Q(video__was_deleted_on_yt=False))
  1239. num_videos_watched = watched_videos.count()
  1240. percent_complete = round((num_videos_watched / total_playlist_video_count) * 100,
  1241. 1) if total_playlist_video_count != 0 else 0
  1242. return percent_complete
  1243. def all_videos_unavailable(self):
  1244. all_vids_unavailable = False
  1245. if self.videos.filter(
  1246. Q(is_unavailable_on_yt=True) | Q(was_deleted_on_yt=True)).count() == self.video_count:
  1247. all_vids_unavailable = True
  1248. return all_vids_unavailable
  1249. class PlaylistItem(models.Model):
  1250. playlist = models.ForeignKey(Playlist, related_name="playlist_items",
  1251. on_delete=models.CASCADE, null=True) # playlist this pl item belongs to
  1252. video = models.ForeignKey(Video, on_delete=models.CASCADE, null=True)
  1253. # details
  1254. playlist_item_id = models.CharField(max_length=100) # the item id of the playlist this video beo
  1255. video_position = models.IntegerField(blank=True) # video position in the playlist
  1256. published_at = models.DateTimeField(
  1257. default=datetime.datetime.now) # snippet.publishedAt - The date and time that the item was added to the playlist
  1258. channel_id = models.CharField(null=True,
  1259. max_length=250) # snippet.channelId - The ID that YouTube uses to uniquely identify the user that added the item to the playlist.
  1260. channel_name = models.CharField(null=True,
  1261. max_length=250) # snippet.channelTitle - The channel title of the channel that the playlist item belongs to.
  1262. # video_owner_channel_id = models.CharField(max_length=100)
  1263. # video_owner_channel_title = models.CharField(max_length=100)
  1264. is_duplicate = models.BooleanField(default=False) # True if the same video exists more than once in the playlist
  1265. is_marked_as_watched = models.BooleanField(default=False, blank=True) # mark video as watched
  1266. num_of_accesses = models.IntegerField(default=0) # tracks num of times this video was clicked on by user
  1267. # for new videos added/modified/deleted in the playlist
  1268. # video_details_modified = models.BooleanField(
  1269. # default=False) # is true for videos whose details changed after playlist update
  1270. # video_details_modified_at = models.DateTimeField(auto_now_add=True) # to set the above false after a day
  1271. created_at = models.DateTimeField(auto_now_add=True)
  1272. updated_at = models.DateTimeField(auto_now=True)
  1273. class Pin(models.Model):
  1274. untube_user = models.ForeignKey(User, related_name="pins",
  1275. on_delete=models.CASCADE, null=True) # untube user this pin is linked to
  1276. kind = models.CharField(max_length=100) # "playlist", "video"
  1277. playlist = models.ForeignKey(Playlist, on_delete=models.CASCADE, null=True)
  1278. video = models.ForeignKey(Video, on_delete=models.CASCADE, null=True)