models.py 76 KB

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