models.py 77 KB

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