models.py 71 KB

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