views.py 51 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248
  1. import random
  2. import bleach
  3. from django.contrib import messages
  4. from django.contrib.auth.decorators import login_required # redirects user to settings.LOGIN_URL
  5. from django.db.models import Count, Q
  6. from django.http import HttpResponse
  7. from django.shortcuts import get_object_or_404, redirect, render
  8. from django.template import loader
  9. from django.views.decorators.http import require_POST
  10. from ..general.utils.misc import print_
  11. from .models import Playlist, Tag
  12. from .util import *
  13. # Create your views here.
  14. @login_required
  15. def home(request):
  16. user_profile = request.user
  17. # FOR NEWLY JOINED USERS
  18. # channel_found = True
  19. if user_profile.profile.show_import_page:
  20. """
  21. Logic:
  22. show_import_page is True by default. When a user logs in for the first time (infact anytime), google
  23. redirects them to 'home' url. Since, show_import_page is True by default, the user is then redirected
  24. from 'home' to 'import_in_progress' url show_import_page is only set false in the import_in_progress.html
  25. page, i.e when user cancels YT import
  26. """
  27. Playlist.objects.getUserYTChannelID(request.user)
  28. # after user imports all their YT playlists no need to show_import_page again
  29. if user_profile.profile.imported_yt_playlists:
  30. user_profile.profile.show_import_page = False
  31. user_profile.profile.save(update_fields=['show_import_page'])
  32. imported_playlists_count = request.user.playlists.filter(Q(is_user_owned=True) &
  33. Q(is_in_db=True)).exclude(playlist_id='LL'
  34. ).count()
  35. return render(
  36. request, 'home.html', {
  37. 'import_successful': True,
  38. 'imported_playlists_count': imported_playlists_count
  39. }
  40. )
  41. return render(request, 'import_in_progress.html')
  42. ##################################
  43. watching = user_profile.playlists.filter(Q(marked_as='watching') & Q(is_in_db=True)).order_by('-num_of_accesses')
  44. recently_accessed_playlists = user_profile.playlists.filter(is_in_db=True).order_by('-updated_at')[:6]
  45. recently_added_playlists = user_profile.playlists.filter(is_in_db=True).order_by('-created_at')[:6]
  46. playlist_tags = request.user.playlist_tags.filter(times_viewed_per_week__gte=1).order_by('-times_viewed_per_week')
  47. videos = request.user.videos.filter(Q(is_unavailable_on_yt=False) & Q(was_deleted_on_yt=False))
  48. channels = videos.values('channel_name').annotate(channel_videos_count=Count('video_id'))
  49. return render(
  50. request, 'home.html', {
  51. 'playlist_tags': playlist_tags,
  52. 'watching': watching,
  53. 'recently_accessed_playlists': recently_accessed_playlists,
  54. 'recently_added_playlists': recently_added_playlists,
  55. 'videos': videos,
  56. 'channels': channels
  57. }
  58. )
  59. @login_required
  60. def favorites(request):
  61. favorite_playlists = request.user.playlists.filter(Q(is_favorite=True) &
  62. Q(is_in_db=True)).order_by('-last_accessed_on')
  63. favorite_videos = request.user.videos.filter(is_favorite=True).order_by('-num_of_accesses')
  64. return render(request, 'favorites.html', {'playlists': favorite_playlists, 'videos': favorite_videos})
  65. @login_required
  66. def planned_to_watch(request):
  67. planned_to_watch_playlists = request.user.playlists.filter(Q(marked_as='plan-to-watch') &
  68. Q(is_in_db=True)).order_by('-last_accessed_on')
  69. planned_to_watch_videos = request.user.videos.filter(is_planned_to_watch=True).order_by('-num_of_accesses')
  70. return render(
  71. request, 'planned_to_watch.html', {
  72. 'playlists': planned_to_watch_playlists,
  73. 'videos': planned_to_watch_videos
  74. }
  75. )
  76. @login_required
  77. def view_video(request, video_id):
  78. if request.user.videos.filter(video_id=video_id).exists():
  79. video = request.user.videos.get(video_id=video_id)
  80. if video.is_unavailable_on_yt:
  81. messages.error(request, 'Video went private/deleted on YouTube!')
  82. return redirect('home')
  83. video.num_of_accesses += 1
  84. video.save(update_fields=['num_of_accesses'])
  85. return render(request, 'view_video.html', {'video': video})
  86. else:
  87. messages.error(request, 'No such video in your UnTube collection!')
  88. return redirect('home')
  89. @login_required
  90. @require_POST
  91. def video_notes(request, video_id):
  92. if request.user.videos.filter(video_id=video_id).exists():
  93. video = request.user.videos.get(video_id=video_id)
  94. if 'video-notes-text-area' in request.POST:
  95. video.user_notes = bleach.clean(request.POST['video-notes-text-area'], tags=['br'])
  96. video.save(update_fields=['user_notes', 'user_label'])
  97. # messages.success(request, 'Saved!')
  98. return HttpResponse(
  99. """
  100. <div hx-ext='class-tools'>
  101. <div classes='add visually-hidden:2s'>Saved!</div>
  102. </div>
  103. """
  104. )
  105. else:
  106. return HttpResponse('No such video in your UnTube collection!')
  107. @login_required
  108. def view_playlist(request, playlist_id):
  109. user_profile = request.user
  110. user_owned_playlists = user_profile.playlists.filter(Q(is_user_owned=True) & Q(is_in_db=True))
  111. # specific playlist requested
  112. if user_profile.playlists.filter(Q(playlist_id=playlist_id) & Q(is_in_db=True)).exists():
  113. playlist = user_profile.playlists.get(playlist_id__exact=playlist_id)
  114. playlist_tags = playlist.tags.all()
  115. # if its been 1 days since the last full scan, force refresh the playlist
  116. if playlist.last_full_scan_at + datetime.timedelta(days=2) < datetime.datetime.now(pytz.utc):
  117. playlist.has_playlist_changed = True
  118. print_('ITS BEEN 15 DAYS, FORCE REFRESHING PLAYLIST')
  119. # only note down that the playlist as been viewed when 30s has passed since the last access
  120. if playlist.last_accessed_on + datetime.timedelta(seconds=30) < datetime.datetime.now(pytz.utc):
  121. playlist.last_accessed_on = datetime.datetime.now(pytz.utc)
  122. playlist.num_of_accesses += 1
  123. increment_tag_views(playlist_tags)
  124. playlist.save(update_fields=['num_of_accesses', 'last_accessed_on', 'has_playlist_changed'])
  125. else:
  126. if playlist_id == 'LL': # liked videos playlist hasnt been imported yet
  127. return render(request, 'view_playlist.html', {'not_imported_LL': True})
  128. messages.error(request, 'No such playlist found!')
  129. return redirect('home')
  130. if playlist.has_new_updates:
  131. recently_updated_videos = playlist.videos.filter(video_details_modified=True)
  132. for video in recently_updated_videos:
  133. if video.video_details_modified_at + datetime.timedelta(hours=12) < datetime.datetime.now(
  134. pytz.utc
  135. ): # expired
  136. video.video_details_modified = False
  137. video.save()
  138. if not recently_updated_videos.exists():
  139. playlist.has_new_updates = False
  140. playlist.save()
  141. playlist_items = playlist.playlist_items.select_related('video').order_by('video_position')
  142. user_created_tags = Tag.objects.filter(created_by=request.user)
  143. # unused_tags = user_created_tags.difference(playlist_tags)
  144. if request.user.profile.hide_unavailable_videos:
  145. playlist_items.exclude(Q(video__is_unavailable_on_yt=True) & Q(video__was_deleted_on_yt=False))
  146. return render(
  147. request, 'view_playlist.html', {
  148. 'playlist': playlist,
  149. 'playlist_tags': playlist_tags,
  150. 'unused_tags': user_created_tags,
  151. 'playlist_items': playlist_items,
  152. 'user_owned_playlists': user_owned_playlists,
  153. 'watching_message': generateWatchingMessage(playlist),
  154. }
  155. )
  156. @login_required
  157. def tagged_playlists(request, tag):
  158. tag = get_object_or_404(Tag, created_by=request.user, name=tag)
  159. playlists = request.user.playlists.all().filter(Q(is_in_db=True) & Q(tags__name=tag.name)).order_by('-updated_at')
  160. return render(request, 'all_playlists_with_tag.html', {'playlists': playlists, 'tag': tag})
  161. @login_required
  162. def library(request, library_type):
  163. """
  164. Possible playlist types for marked_as attribute: (saved in database like this)
  165. 'none', 'watching', 'plan-to-watch'
  166. """
  167. library_type = library_type.lower()
  168. watching = False
  169. if library_type.lower() == 'home': # displays cards of all playlist types
  170. return render(request, 'library.html')
  171. elif library_type == 'all':
  172. playlists = request.user.playlists.all().filter(is_in_db=True)
  173. library_type_display = 'All Playlists'
  174. elif library_type == 'user-owned': # YT playlists owned by user
  175. playlists = request.user.playlists.all().filter(Q(is_user_owned=True) & Q(is_in_db=True))
  176. library_type_display = 'Your YouTube Playlists'
  177. elif library_type == 'imported': # YT playlists (public) owned by others
  178. playlists = request.user.playlists.all().filter(Q(is_user_owned=False) & Q(is_in_db=True))
  179. library_type_display = 'Imported playlists'
  180. elif library_type == 'favorites': # YT playlists (public) owned by others
  181. playlists = request.user.playlists.all().filter(Q(is_favorite=True) & Q(is_in_db=True))
  182. library_type_display = 'Favorites'
  183. elif library_type.lower() in ['watching', 'plan-to-watch']:
  184. playlists = request.user.playlists.filter(Q(marked_as=library_type.lower()) & Q(is_in_db=True))
  185. library_type_display = library_type.lower().replace('-', ' ')
  186. if library_type.lower() == 'watching':
  187. watching = True
  188. elif library_type.lower() == 'yt-mix':
  189. playlists = request.user.playlists.all().filter(Q(is_yt_mix=True) & Q(is_in_db=True))
  190. library_type_display = 'Your YouTube Mixes'
  191. elif library_type.lower() == 'unavailable-videos':
  192. videos = request.user.videos.all().filter(Q(is_unavailable_on_yt=False) & Q(was_deleted_on_yt=True))
  193. return render(request, 'unavailable_videos.html', {'videos': videos})
  194. elif library_type.lower() == 'random': # randomize playlist
  195. if request.method == 'POST':
  196. playlists_type = bleach.clean(request.POST['playlistsType'])
  197. if playlists_type == 'All':
  198. playlists = request.user.playlists.all().filter(is_in_db=True)
  199. elif playlists_type == 'Favorites':
  200. playlists = request.user.playlists.all().filter(Q(is_favorite=True) & Q(is_in_db=True))
  201. elif playlists_type == 'Watching':
  202. playlists = request.user.playlists.filter(Q(marked_as='watching') & Q(is_in_db=True))
  203. elif playlists_type == 'Plan to Watch':
  204. playlists = request.user.playlists.filter(Q(marked_as='plan-to-watch') & Q(is_in_db=True))
  205. else:
  206. return redirect('/library/home')
  207. if not playlists.exists():
  208. messages.info(request, f'No playlists in {playlists_type}')
  209. return redirect('/library/home')
  210. random_playlist = random.choice(playlists)
  211. return redirect(f'/playlist/{random_playlist.playlist_id}')
  212. return render(request, 'library.html')
  213. else:
  214. return redirect('home')
  215. return render(
  216. request, 'all_playlists.html', {
  217. 'playlists': playlists.order_by('-updated_at'),
  218. 'library_type': library_type,
  219. 'library_type_display': library_type_display,
  220. 'watching': watching
  221. }
  222. )
  223. @login_required
  224. def order_playlist_by(request, playlist_id, order_by):
  225. playlist = request.user.playlists.get(Q(playlist_id=playlist_id) & Q(is_in_db=True))
  226. display_text = 'Nothing in this playlist! Add something!' # what to display when requested order/filter has no videws
  227. videos_details = ''
  228. if order_by == 'all':
  229. playlist_items = playlist.playlist_items.select_related('video').order_by('video_position')
  230. elif order_by == 'favorites':
  231. playlist_items = playlist.playlist_items.select_related('video').filter(video__is_favorite=True
  232. ).order_by('video_position')
  233. videos_details = 'Sorted by Favorites'
  234. display_text = 'No favorites yet!'
  235. elif order_by == 'popularity':
  236. videos_details = 'Sorted by Popularity'
  237. playlist_items = playlist.playlist_items.select_related('video').order_by('-video__like_count')
  238. elif order_by == 'date-published':
  239. videos_details = 'Sorted by Date Published'
  240. playlist_items = playlist.playlist_items.select_related('video').order_by('published_at')
  241. elif order_by == 'views':
  242. videos_details = 'Sorted by View Count'
  243. playlist_items = playlist.playlist_items.select_related('video').order_by('-video__view_count')
  244. elif order_by == 'has-cc':
  245. videos_details = 'Filtered by Has CC'
  246. playlist_items = playlist.playlist_items.select_related('video').filter(video__has_cc=True
  247. ).order_by('video_position')
  248. display_text = 'No videos in this playlist have CC :('
  249. elif order_by == 'duration':
  250. videos_details = 'Sorted by Video Duration'
  251. playlist_items = playlist.playlist_items.select_related('video').order_by('-video__duration_in_seconds')
  252. elif order_by == 'new-updates':
  253. playlist_items = []
  254. videos_details = 'Sorted by New Updates'
  255. display_text = 'No new updates! Note that deleted videos will not show up here.'
  256. if playlist.has_new_updates:
  257. recently_updated_videos = playlist.playlist_items.select_related('video').filter(
  258. video__video_details_modified=True
  259. )
  260. for playlist_item in recently_updated_videos:
  261. if playlist_item.video.video_details_modified_at + datetime.timedelta(hours=12
  262. ) < datetime.datetime.now(
  263. pytz.utc
  264. ): # expired
  265. playlist_item.video.video_details_modified = False
  266. playlist_item.video.save(update_fields=['video_details_modified'])
  267. if not recently_updated_videos.exists():
  268. playlist.has_new_updates = False
  269. playlist.save(update_fields=['has_new_updates'])
  270. else:
  271. playlist_items = recently_updated_videos.order_by('video_position')
  272. elif order_by == 'unavailable-videos':
  273. playlist_items = playlist.playlist_items.select_related('video').filter(
  274. Q(video__is_unavailable_on_yt=False) & Q(video__was_deleted_on_yt=True)
  275. )
  276. videos_details = 'Sorted by Unavailable Videos'
  277. display_text = 'None of the videos in this playlist have gone unavailable... yet.'
  278. elif order_by == 'channel':
  279. channel_name = bleach.clean(request.GET['channel-name'])
  280. playlist_items = playlist.playlist_items.select_related('video').filter(video__channel_name=channel_name
  281. ).order_by('video_position')
  282. videos_details = f'Sorted by Channel "{channel_name}"'
  283. else:
  284. return HttpResponse('Something went wrong :(')
  285. return HttpResponse(
  286. loader.get_template('intercooler/playlist_items.html').render({
  287. 'playlist': playlist,
  288. 'playlist_items': playlist_items,
  289. 'videos_details': videos_details,
  290. 'display_text': display_text,
  291. 'order_by': order_by
  292. })
  293. )
  294. @login_required
  295. def order_playlists_by(request, library_type, order_by):
  296. watching = False
  297. if library_type == '' or library_type.lower() == 'all':
  298. playlists = request.user.playlists.all()
  299. elif library_type.lower() == 'favorites':
  300. playlists = request.user.playlists.filter(Q(is_favorite=True) & Q(is_in_db=True))
  301. elif library_type.lower() in ['watching', 'plan-to-watch']:
  302. playlists = request.user.playlists.filter(Q(marked_as=library_type.lower()) & Q(is_in_db=True))
  303. if library_type.lower() == 'watching':
  304. watching = True
  305. elif library_type.lower() == 'imported':
  306. playlists = request.user.playlists.filter(Q(is_user_owned=False) & Q(is_in_db=True))
  307. elif library_type.lower() == 'user-owned':
  308. playlists = request.user.playlists.filter(Q(is_user_owned=True) & Q(is_in_db=True))
  309. else:
  310. return HttpResponse('Not found.')
  311. if order_by == 'recently-accessed':
  312. playlists = playlists.order_by('-updated_at')
  313. elif order_by == 'playlist-duration-in-seconds':
  314. playlists = playlists.order_by('-playlist_duration_in_seconds')
  315. elif order_by == 'video-count':
  316. playlists = playlists.order_by('-video_count')
  317. return HttpResponse(
  318. loader.get_template('intercooler/playlists.html').render({
  319. 'playlists': playlists,
  320. 'watching': watching
  321. })
  322. )
  323. @login_required
  324. def mark_playlist_as(request, playlist_id, mark_as):
  325. playlist = request.user.playlists.get(playlist_id=playlist_id)
  326. marked_as_response = '<span></span><meta http-equiv="refresh" content="0" />'
  327. if mark_as in ['watching', 'on-hold', 'plan-to-watch']:
  328. playlist.marked_as = mark_as
  329. playlist.save()
  330. icon = ''
  331. if mark_as == 'watching':
  332. playlist.last_watched = datetime.datetime.now(pytz.utc)
  333. playlist.save(update_fields=['last_watched'])
  334. icon = '<i class="fas fa-fire-alt me-2"></i>'
  335. elif mark_as == 'plan-to-watch':
  336. icon = '<i class="fas fa-flag me-2"></i>'
  337. marked_as_response = f'<span class="badge bg-success text-white" >{icon}{mark_as}</span> <meta http-equiv="refresh" content="0" />'
  338. elif mark_as == 'none':
  339. playlist.marked_as = mark_as
  340. playlist.save()
  341. elif mark_as == 'favorite':
  342. if playlist.is_favorite:
  343. playlist.is_favorite = False
  344. playlist.save()
  345. return HttpResponse('<i class="far fa-star"></i>')
  346. else:
  347. playlist.is_favorite = True
  348. playlist.save()
  349. return HttpResponse('<i class="fas fa-star" style="color: #fafa06"></i>')
  350. else:
  351. return redirect('home')
  352. return HttpResponse(marked_as_response)
  353. @login_required
  354. def playlists_home(request):
  355. return render(request, 'library.html')
  356. @login_required
  357. @require_POST
  358. def playlist_delete_videos(request, playlist_id, command):
  359. all_ = False
  360. num_vids = 0
  361. playlist_item_ids = []
  362. if 'all' in request.POST:
  363. if request.POST['all'] == 'yes':
  364. all_ = True
  365. num_vids = request.user.playlists.get(playlist_id=playlist_id).playlist_items.all().count()
  366. if command == 'start':
  367. playlist_item_ids = [
  368. playlist_item.playlist_item_id
  369. for playlist_item in request.user.playlists.get(playlist_id=playlist_id).playlist_items.all()
  370. ]
  371. else:
  372. playlist_item_ids = [bleach.clean(item_id) for item_id in request.POST.getlist('video-id', default=[])]
  373. num_vids = len(playlist_item_ids)
  374. extra_text = ' '
  375. if num_vids == 0:
  376. return HttpResponse("""
  377. <h5>Select some videos first!</h5><hr>
  378. """)
  379. if 'confirm before deleting' in request.POST:
  380. if request.POST['confirm before deleting'] == 'False':
  381. command = 'confirmed'
  382. if command == 'confirm':
  383. if all_ or num_vids == request.user.playlists.get(playlist_id=playlist_id).playlist_items.all().count():
  384. hx_vals = """hx-vals='{"all": "yes"}'"""
  385. delete_text = 'ALL VIDEOS'
  386. extra_text = ' This will not delete the playlist itself, will only make the playlist empty. '
  387. else:
  388. hx_vals = ''
  389. delete_text = f'{num_vids} videos'
  390. if playlist_id == 'LL':
  391. extra_text += "Since you're deleting from your Liked Videos playlist, the selected videos will also be unliked from YouTube. "
  392. url = f'/playlist/{playlist_id}/delete-videos/confirmed'
  393. return HttpResponse(
  394. f"""
  395. <div hx-ext='class-tools'>
  396. <div classes='add visually-hidden:30s'>
  397. <h5>
  398. Are you sure you want to delete {delete_text} from your YouTube playlist?{extra_text}This cannot be undone.</h5>
  399. <button hx-post='{url}' hx-include='[id='video-checkboxes']' {hx_vals} hx-target='#delete-videos-confirm-box' type='button'
  400. class='btn btn-outline-danger btn-sm'>Confirm</button>
  401. <hr>
  402. </div>
  403. </div>
  404. """
  405. )
  406. elif command == 'confirmed':
  407. if all_:
  408. hx_vals = """hx-vals='{"all": "yes"}'"""
  409. else:
  410. hx_vals = ''
  411. url = f'/playlist/{playlist_id}/delete-videos/start'
  412. return HttpResponse(
  413. f"""
  414. <div class='spinner-border text-light' role='status'
  415. hx-post='{url}' {hx_vals} hx-trigger='load' hx-include='[id='video-checkboxes']'
  416. hx-target='#delete-videos-confirm-box'></div><hr>
  417. """
  418. )
  419. elif command == 'start':
  420. print_('Deleting', len(playlist_item_ids), 'videos')
  421. Playlist.objects.deletePlaylistItems(request.user, playlist_id, playlist_item_ids)
  422. if all_:
  423. help_text = 'Finished emptying this playlist.'
  424. else:
  425. help_text = 'Done deleting selected videos from your playlist on YouTube.'
  426. messages.success(request, help_text)
  427. return HttpResponse(
  428. """
  429. <h5>
  430. Done! Refreshing...
  431. <script>
  432. window.location.reload();
  433. </script>
  434. </h5>
  435. <hr>
  436. """
  437. )
  438. @login_required
  439. @require_POST
  440. def delete_specific_videos(request, playlist_id, command):
  441. Playlist.objects.deleteSpecificPlaylistItems(request.user, playlist_id, command)
  442. help_text = 'Error.'
  443. if command == 'unavailable':
  444. help_text = 'Deleted all unavailable videos.'
  445. elif command == 'duplicate':
  446. help_text = 'Deleted all duplicate videos.'
  447. messages.success(request, help_text)
  448. return HttpResponse(
  449. """
  450. <h5>
  451. Done. Refreshing...
  452. <script>
  453. window.location.reload();
  454. </script>
  455. </h5>
  456. <hr>
  457. """
  458. )
  459. # MANAGE VIDEOS
  460. @login_required
  461. def mark_video_favortie(request, video_id):
  462. video = request.user.videos.get(video_id=video_id)
  463. if video.is_favorite:
  464. video.is_favorite = False
  465. video.save(update_fields=['is_favorite'])
  466. return HttpResponse('<i class="far fa-heart"></i>')
  467. else:
  468. video.is_favorite = True
  469. video.save(update_fields=['is_favorite'])
  470. return HttpResponse('<i class="fas fa-heart" style="color: #fafa06"></i>')
  471. @login_required
  472. def mark_video_planned_to_watch(request, video_id):
  473. video = request.user.videos.get(video_id=video_id)
  474. if video.is_planned_to_watch:
  475. video.is_planned_to_watch = False
  476. video.save(update_fields=['is_planned_to_watch'])
  477. return HttpResponse('<i class="far fa-clock"></i>')
  478. else:
  479. video.is_planned_to_watch = True
  480. video.save(update_fields=['is_planned_to_watch'])
  481. return HttpResponse('<i class="fas fa-clock" style="color: #000000"></i>')
  482. @login_required
  483. def mark_video_watched(request, playlist_id, video_id):
  484. playlist = request.user.playlists.get(playlist_id=playlist_id)
  485. video = playlist.videos.get(video_id=video_id)
  486. if video.is_marked_as_watched:
  487. video.is_marked_as_watched = False
  488. video.save(update_fields=['is_marked_as_watched'])
  489. return HttpResponse(
  490. f'<i class="far fa-check-circle" hx-get="/playlist/{playlist_id}/get-watch-message" '
  491. f'hx-trigger="load" hx-target="#playlist-watch-message"></i>'
  492. )
  493. else:
  494. video.is_marked_as_watched = True
  495. video.save(update_fields=['is_marked_as_watched'])
  496. playlist.last_watched = datetime.datetime.now(pytz.utc)
  497. playlist.save(update_fields=['last_watched'])
  498. return HttpResponse(
  499. f'<i class="fas fa-check-circle" hx-get="/playlist/{playlist_id}/get-watch-message" '
  500. f'hx-trigger="load" hx-target="#playlist-watch-message"></i>'
  501. )
  502. ###########
  503. @login_required
  504. def load_more_videos(request, playlist_id, order_by, page):
  505. playlist = request.user.playlists.get(playlist_id=playlist_id)
  506. playlist_items = None
  507. if order_by == 'all':
  508. playlist_items = playlist.playlist_items.select_related('video').order_by('video_position')
  509. print_(f'loading page 1: {playlist_items.count()} videos')
  510. elif order_by == 'favorites':
  511. playlist_items = playlist.playlist_items.select_related('video').filter(video__is_favorite=True
  512. ).order_by('video_position')
  513. elif order_by == 'popularity':
  514. playlist_items = playlist.playlist_items.select_related('video').order_by('-video__like_count')
  515. elif order_by == 'date-published':
  516. playlist_items = playlist.playlist_items.select_related('video').order_by('published_at')
  517. elif order_by == 'views':
  518. playlist_items = playlist.playlist_items.select_related('video').order_by('-video__view_count')
  519. elif order_by == 'has-cc':
  520. playlist_items = playlist.playlist_items.select_related('video').filter(video__has_cc=True
  521. ).order_by('video_position')
  522. elif order_by == 'duration':
  523. playlist_items = playlist.playlist_items.select_related('video').order_by('-video__duration_in_seconds')
  524. elif order_by == 'new-updates':
  525. playlist_items = []
  526. if playlist.has_new_updates:
  527. recently_updated_videos = playlist.playlist_items.select_related('video').filter(
  528. video__video_details_modified=True
  529. )
  530. for playlist_item in recently_updated_videos:
  531. if playlist_item.video.video_details_modified_at + datetime.timedelta(hours=12
  532. ) < datetime.datetime.now(
  533. pytz.utc
  534. ): # expired
  535. playlist_item.video.video_details_modified = False
  536. playlist_item.video.save()
  537. if not recently_updated_videos.exists():
  538. playlist.has_new_updates = False
  539. playlist.save()
  540. else:
  541. playlist_items = recently_updated_videos.order_by('video_position')
  542. elif order_by == 'unavailable-videos':
  543. playlist_items = playlist.playlist_items.select_related('video').filter(
  544. Q(video__is_unavailable_on_yt=True) & Q(video__was_deleted_on_yt=True)
  545. )
  546. elif order_by == 'channel':
  547. channel_name = bleach.clean(request.GET['channel-name'])
  548. playlist_items = playlist.playlist_items.select_related('video').filter(video__channel_name=channel_name
  549. ).order_by('video_position')
  550. if request.user.profile.hide_unavailable_videos:
  551. playlist_items.exclude(Q(video__is_unavailable_on_yt=True) & Q(video__was_deleted_on_yt=False))
  552. return HttpResponse(
  553. loader.get_template('intercooler/playlist_items.html').render({
  554. 'playlist': playlist,
  555. 'playlist_items': playlist_items[50 * page:], # only send 50 results per page
  556. 'page': page + 1,
  557. 'order_by': order_by
  558. })
  559. )
  560. @login_required
  561. @require_POST
  562. def update_playlist_settings(request, playlist_id):
  563. message_type = 'success'
  564. message_content = 'Saved!'
  565. playlist = request.user.playlists.get(playlist_id=playlist_id)
  566. if 'user_label' in request.POST:
  567. playlist.user_label = bleach.clean(request.POST['user_label'])
  568. if 'pl-auto-update' in request.POST:
  569. playlist.auto_check_for_updates = True
  570. else:
  571. playlist.auto_check_for_updates = False
  572. playlist.save(update_fields=['auto_check_for_updates', 'user_label'])
  573. try:
  574. valid_title = bleach.clean(request.POST['playlistTitle'])
  575. valid_description = bleach.clean(request.POST['playlistDesc'])
  576. details = {
  577. 'title': valid_title,
  578. 'description': valid_description,
  579. 'privacyStatus': True if request.POST['playlistPrivacy'] == 'Private' else False
  580. }
  581. status = Playlist.objects.updatePlaylistDetails(request.user, playlist_id, details)
  582. if status == -1:
  583. message_type = 'danger'
  584. message_content = 'Could not save :('
  585. except Exception:
  586. pass
  587. return HttpResponse(
  588. loader.get_template('intercooler/messages.html').render({
  589. 'message_type': message_type,
  590. 'message_content': message_content
  591. })
  592. )
  593. @login_required
  594. def update_playlist(request, playlist_id, command):
  595. playlist = request.user.playlists.get(playlist_id=playlist_id)
  596. if command == 'checkforupdates':
  597. print_('Checking if playlist changed...')
  598. result = Playlist.objects.checkIfPlaylistChangedOnYT(request.user, playlist_id)
  599. if result[0] == 1: # full scan was done (full scan is done for a playlist if a week has passed)
  600. deleted_videos, unavailable_videos, added_videos = result[1:]
  601. print_('CHANGES', deleted_videos, unavailable_videos, added_videos)
  602. # playlist_changed_text = ['The following modifications happened to this playlist on YouTube:']
  603. if deleted_videos != 0 or unavailable_videos != 0 or added_videos != 0:
  604. pass
  605. # if added_videos > 0:
  606. # playlist_changed_text.append(f'{added_videos} new video(s) were added')
  607. # if deleted_videos > 0:
  608. # playlist_changed_text.append(f'{deleted_videos} video(s) were deleted')
  609. # if unavailable_videos > 0:
  610. # playlist_changed_text.append(f'{unavailable_videos} video(s) went private/unavailable')
  611. # playlist.playlist_changed_text = '\n'.join(playlist_changed_text)
  612. # playlist.has_playlist_changed = True
  613. # playlist.save()
  614. else: # no updates found
  615. return HttpResponse(
  616. """
  617. <div hx-ext='class-tools'>
  618. <div id='checkforupdates' class='sticky-top' style='top: 0.5em;'>
  619. <div class='alert alert-success alert-dismissible fade show' classes='add visually-hidden:1s' role='alert'>
  620. Playlist upto date!
  621. </div>
  622. </div>
  623. </div>
  624. """
  625. )
  626. elif result[0] == -1: # playlist changed
  627. print_('Playlist was deleted from YouTube')
  628. playlist.videos.all().delete()
  629. playlist.delete()
  630. return HttpResponse(
  631. """
  632. <div id='checkforupdates' class='sticky-top' style='top: 0.5em;'>
  633. <div class='alert alert-danger alert-dismissible fade show sticky-top visually-hidden' role='alert' style='top: 0.5em;'>
  634. The playlist owner deleted this playlist on YouTube. It will be deleted for you as well :(
  635. <meta http-equiv='refresh' content='1' />
  636. </div>
  637. </div>
  638. """
  639. )
  640. else: # no updates found
  641. return HttpResponse(
  642. """
  643. <div id='checkforupdates' class='sticky-top' style='top: 0.5em;'>
  644. <div hx-ext='class-tools'>
  645. <div classes='add visually-hidden:2s' class='alert alert-success alert-dismissible fade show sticky-top visually-hidden'
  646. role='alert' style='top: 0.5em;'>
  647. No new updates!
  648. </div>
  649. </div>
  650. </div>
  651. """
  652. )
  653. return HttpResponse(
  654. f"""
  655. <div hx-get='/playlist/{playlist_id}/update/auto' hx-trigger='load' hx-target='this' class='sticky-top' style='top: 0.5em;'>
  656. <div class='alert alert-success alert-dismissible fade show' role='alert'>
  657. <div class='d-flex justify-content-center' id='loading-sign'>
  658. <img src='/static/svg-loaders/circles.svg' width='40' height='40'>
  659. <h5 class='mt-2 ms-2'>Changes detected on YouTube, updating playlist '{playlist.name}'...</h5>
  660. </div>
  661. </div>
  662. </div>
  663. """
  664. )
  665. if command == 'manual':
  666. print_('MANUAL')
  667. return HttpResponse(
  668. f"""<div hx-get='/playlist/{playlist_id}/update/auto' hx-trigger='load' hx-swap='outerHTML'>
  669. <div class='d-flex justify-content-center mt-4 mb-3' id='loading-sign'>
  670. <img src='/static/svg-loaders/circles.svg' width='40' height='40'
  671. style='filter: invert(0%) sepia(18%) saturate(7468%) hue-rotate(241deg) brightness(84%) contrast(101%);'>
  672. <h5 class='mt-2 ms-2'>Refreshing playlist '{playlist.name}', please wait!</h5>
  673. </div>
  674. </div>"""
  675. )
  676. print_('Attempting to update playlist')
  677. status, deleted_playlist_item_ids, unavailable_videos, added_videos = Playlist.objects.updatePlaylist(
  678. request.user, playlist_id
  679. )
  680. playlist = request.user.playlists.get(playlist_id=playlist_id)
  681. if status == -1:
  682. playlist_name = playlist.name
  683. playlist.delete()
  684. return HttpResponse(
  685. f"""
  686. <div class='d-flex justify-content-center mt-4 mb-3' id='loading-sign'>
  687. <h5 class='mt-2 ms-2'>Looks like the playlist '{playlist_name}' was deleted on YouTube.
  688. It has been removed from UnTube as well.</h5>
  689. </div>
  690. """
  691. )
  692. print_('Updated playlist')
  693. playlist_changed_text = []
  694. if len(added_videos) != 0:
  695. playlist_changed_text.append(f'{len(added_videos)} added')
  696. for video in added_videos:
  697. playlist_changed_text.append(f'--> {video.name}')
  698. # if len(added_videos) > 3:
  699. # playlist_changed_text.append(f'+ {len(added_videos) - 3} more')
  700. if len(unavailable_videos) != 0:
  701. if len(playlist_changed_text) == 0:
  702. playlist_changed_text.append(f'{len(unavailable_videos)} went unavailable')
  703. else:
  704. playlist_changed_text.append(f'\n{len(unavailable_videos)} went unavailable')
  705. for video in unavailable_videos:
  706. playlist_changed_text.append(f'--> {video.name}')
  707. if len(deleted_playlist_item_ids) != 0:
  708. if len(playlist_changed_text) == 0:
  709. playlist_changed_text.append(f'{len(deleted_playlist_item_ids)} deleted')
  710. else:
  711. playlist_changed_text.append(f'\n{len(deleted_playlist_item_ids)} deleted')
  712. for playlist_item_id in deleted_playlist_item_ids:
  713. playlist_item = playlist.playlist_items.select_related('video').get(playlist_item_id=playlist_item_id)
  714. video = playlist_item.video
  715. playlist_changed_text.append(f'--> {playlist_item.video.name}')
  716. playlist_item.delete()
  717. if playlist_id == 'LL':
  718. video.liked = False
  719. video.save(update_fields=['liked'])
  720. if not playlist.playlist_items.filter(video__video_id=video.video_id).exists():
  721. playlist.videos.remove(video)
  722. if len(playlist_changed_text) == 0:
  723. playlist_changed_text = [
  724. 'Updated playlist and video details to their latest. No new changes found in terms of modifications made to this playlist!'
  725. ]
  726. # return HttpResponse
  727. return HttpResponse(
  728. loader.get_template('intercooler/playlist_updates.html').render({
  729. 'playlist_changed_text': '\n'.join(playlist_changed_text),
  730. 'playlist_id': playlist_id
  731. })
  732. )
  733. @login_required
  734. def view_playlist_settings(request, playlist_id):
  735. try:
  736. playlist = request.user.playlists.get(playlist_id=playlist_id)
  737. except Playlist.DoesNotExist:
  738. messages.error(request, 'No such playlist found!')
  739. return redirect('home')
  740. return render(request, 'view_playlist_settings.html', {'playlist': playlist})
  741. @login_required
  742. def get_playlist_tags(request, playlist_id):
  743. playlist = request.user.playlists.get(playlist_id=playlist_id)
  744. playlist_tags = playlist.tags.all()
  745. return HttpResponse(
  746. loader.get_template('intercooler/playlist_tags.html').render({
  747. 'playlist_id': playlist_id,
  748. 'playlist_tags': playlist_tags
  749. })
  750. )
  751. @login_required
  752. def get_unused_playlist_tags(request, playlist_id):
  753. # playlist = request.user.playlists.get(playlist_id=playlist_id)
  754. user_created_tags = Tag.objects.filter(created_by=request.user)
  755. # playlist_tags = playlist.tags.all()
  756. # unused_tags = user_created_tags.difference(playlist_tags)
  757. return HttpResponse(
  758. loader.get_template('intercooler/playlist_tags_unused.html').render({'unused_tags': user_created_tags})
  759. )
  760. @login_required
  761. def get_watch_message(request, playlist_id):
  762. playlist = request.user.playlists.get(playlist_id=playlist_id)
  763. return HttpResponse(loader.get_template('intercooler/playlist_watch_message.html').render({'playlist': playlist}))
  764. @login_required
  765. @require_POST
  766. def create_playlist_tag(request, playlist_id):
  767. tag_name = bleach.clean(request.POST['createTagField'])
  768. if tag_name.lower() == 'Pick from existing unused tags'.lower():
  769. return HttpResponse("Can't use that! Try again >_<")
  770. playlist = request.user.playlists.get(playlist_id=playlist_id)
  771. user_created_tags = Tag.objects.filter(created_by=request.user)
  772. if not user_created_tags.filter(name__iexact=tag_name).exists(): # no tag found, so create it
  773. tag = Tag(name=tag_name, created_by=request.user)
  774. tag.save()
  775. # add it to playlist
  776. playlist.tags.add(tag)
  777. else:
  778. return HttpResponse("""
  779. Already created. Try Again >w<
  780. """)
  781. # playlist_tags = playlist.tags.all()
  782. # unused_tags = user_created_tags.difference(playlist_tags)
  783. return HttpResponse(
  784. f"""
  785. Created and Added!
  786. <span class='visually-hidden' hx-get='/playlist/{playlist_id}/get-tags' hx-trigger='load' hx-target='#playlist-tags'></span>
  787. """
  788. )
  789. @login_required
  790. @require_POST
  791. def add_playlist_tag(request, playlist_id):
  792. tag_name = bleach.clean(request.POST['playlistTag'])
  793. if tag_name == 'Pick from existing unused tags':
  794. return HttpResponse('Pick something! >w<')
  795. try:
  796. tag = request.user.playlist_tags.get(name__iexact=tag_name)
  797. except Exception:
  798. return HttpResponse('Uh-oh, looks like this tag was deleted :(')
  799. playlist = request.user.playlists.get(playlist_id=playlist_id)
  800. playlist_tags = playlist.tags.all()
  801. if not playlist_tags.filter(name__iexact=tag_name).exists(): # tag not on this playlist, so add it
  802. # add it to playlist
  803. playlist.tags.add(tag)
  804. else:
  805. return HttpResponse('Already Added >w<')
  806. return HttpResponse(
  807. f"""
  808. Added!
  809. <span class='visually-hidden' hx-get='/playlist/{playlist_id}/get-tags' hx-trigger='load' hx-target='#playlist-tags'></span>
  810. """
  811. )
  812. @login_required
  813. @require_POST
  814. def remove_playlist_tag(request, playlist_id, tag_name):
  815. playlist = request.user.playlists.get(playlist_id=playlist_id)
  816. playlist_tags = playlist.tags.all()
  817. if playlist_tags.filter(name__iexact=tag_name).exists(): # tag on this playlist, remove it it
  818. tag = Tag.objects.filter(Q(created_by=request.user) & Q(name__iexact=tag_name)).first()
  819. print_('Removed tag', tag_name)
  820. # remove it from the playlist
  821. playlist.tags.remove(tag)
  822. else:
  823. return HttpResponse('Whoops >w<')
  824. return HttpResponse('')
  825. @login_required
  826. def delete_playlist(request, playlist_id):
  827. playlist = request.user.playlists.get(playlist_id=playlist_id)
  828. if request.GET['confirmed'] == 'no':
  829. return HttpResponse(
  830. f"""
  831. <a href='/playlist/{playlist_id}/delete-playlist?confirmed=yes' hx-indicator='#delete-pl-loader' class='btn btn-danger'>Confirm Delete</a>
  832. <a href='/playlist/{playlist_id}' class='btn btn-secondary ms-1'>Cancel</a>
  833. """
  834. )
  835. if not playlist.is_user_owned: # if playlist trying to delete isn't user owned
  836. video_ids = [video.video_id for video in playlist.videos.all()]
  837. playlist.delete()
  838. for video_id in video_ids:
  839. video = request.user.videos.get(video_id=video_id)
  840. if video.playlists.all().count() == 0:
  841. video.delete()
  842. messages.success(request, 'Successfully deleted playlist from UnTube.')
  843. else:
  844. # deletes it from YouTube first then from UnTube
  845. status = Playlist.objects.deletePlaylistFromYouTube(request.user, playlist_id)
  846. if status[0] == -1: # failed to delete playlist from youtube
  847. # if status[2] == 404:
  848. # playlist.delete()
  849. # messages.success(request, 'Looks like the playlist was already deleted on YouTube. Removed it from UnTube as well.')
  850. # return redirect('home')
  851. messages.error(request, f'[{status[1]}] Failed to delete playlist from YouTube :(')
  852. return redirect('view_playlist_settings', playlist_id=playlist_id)
  853. messages.success(request, 'Successfully deleted playlist from YouTube and removed it from UnTube as well.')
  854. return redirect('home')
  855. @login_required
  856. def reset_watched(request, playlist_id):
  857. playlist = request.user.playlists.get(playlist_id=playlist_id)
  858. for video in playlist.videos.filter(Q(is_unavailable_on_yt=False) & Q(was_deleted_on_yt=False)):
  859. video.is_marked_as_watched = False
  860. video.save(update_fields=['is_marked_as_watched'])
  861. # messages.success(request, 'Successfully marked all videos unwatched.')
  862. return redirect(f'/playlist/{playlist.playlist_id}')
  863. @login_required
  864. @require_POST
  865. def playlist_move_copy_videos(request, playlist_id, action):
  866. playlist_ids = [bleach.clean(pl_id) for pl_id in request.POST.getlist('playlist-ids', default=[])]
  867. playlist_item_ids = [bleach.clean(item_id) for item_id in request.POST.getlist('video-id', default=[])]
  868. # basic processing
  869. if not playlist_ids and not playlist_item_ids:
  870. return HttpResponse("""<span class='text-warning'>Mistakes happen. Try again >w<</span>""")
  871. elif not playlist_ids:
  872. return HttpResponse("""<span class='text-danger'>First select some playlists to {action} to!</span>""")
  873. elif not playlist_item_ids:
  874. return HttpResponse(f"""<span class='text-danger'>First select some videos to {action}!</span>""")
  875. success_message = f"""
  876. <div hx-ext='class-tools'>
  877. <span classes='add visually-hidden:5s' class='text-success'>Successfully {'moved' if action == 'move' else 'copied'}
  878. {len(playlist_item_ids)} video(s) to {len(playlist_ids)} other playlist(s)!
  879. Go visit those playlist(s)!</span>
  880. </div>
  881. """
  882. if action == 'move':
  883. result = Playlist.objects.moveCopyVideosFromPlaylist(
  884. request.user,
  885. from_playlist_id=playlist_id,
  886. to_playlist_ids=playlist_ids,
  887. playlist_item_ids=playlist_item_ids,
  888. action='move'
  889. )
  890. if result['status'] == -1:
  891. if result['status'] == 404:
  892. return HttpResponse(
  893. '<span class="text-danger">You cannot copy/move unavailable videos! De-select them and try again.</span>'
  894. )
  895. return HttpResponse('Error moving!')
  896. else: # copy
  897. status = Playlist.objects.moveCopyVideosFromPlaylist(
  898. request.user,
  899. from_playlist_id=playlist_id,
  900. to_playlist_ids=playlist_ids,
  901. playlist_item_ids=playlist_item_ids
  902. )
  903. if status[0] == -1:
  904. if status[1] == 404:
  905. return HttpResponse(
  906. '<span class="text-danger">You cannot copy/move unavailable videos! De-select them and try again.</span>'
  907. )
  908. return HttpResponse('Error copying!')
  909. return HttpResponse(success_message)
  910. @login_required
  911. def playlist_open_random_video(request, playlist_id):
  912. playlist = request.user.playlists.get(playlist_id=playlist_id)
  913. videos = playlist.videos.all()
  914. random_video = random.choice(videos)
  915. return redirect(f'/video/{random_video.video_id}')
  916. @login_required
  917. def playlist_completion_times(request, playlist_id):
  918. playlist_duration = request.user.playlists.get(playlist_id=playlist_id).playlist_duration_in_seconds
  919. return HttpResponse(
  920. f"""
  921. <h5 class='text-warning'>Playlist completion times:</h5>
  922. <h6>At 1.25x speed: {getHumanizedTimeString(playlist_duration / 1.25)}</h6>
  923. <h6>At 1.5x speed: {getHumanizedTimeString(playlist_duration / 1.5)}</h6>
  924. <h6>At 1.75x speed: {getHumanizedTimeString(playlist_duration / 1.75)}</h6>
  925. <h6>At 2x speed: {getHumanizedTimeString(playlist_duration / 2)}</h6>
  926. """
  927. )
  928. @login_required
  929. def video_completion_times(request, video_id):
  930. video_duration = request.user.videos.get(video_id=video_id).duration_in_seconds
  931. return HttpResponse(
  932. f"""
  933. <h5 class='text-warning'>Video completion times:</h5>
  934. <h6>At 1.25x speed: {getHumanizedTimeString(video_duration / 1.25)}</h6>
  935. <h6>At 1.5x speed: {getHumanizedTimeString(video_duration / 1.5)}</h6>
  936. <h6>At 1.75x speed: {getHumanizedTimeString(video_duration / 1.75)}</h6>
  937. <h6>At 2x speed: {getHumanizedTimeString(video_duration / 2)}</h6>
  938. """
  939. )
  940. @login_required
  941. @require_POST
  942. def add_video_user_label(request, video_id):
  943. video = request.user.videos.get(video_id=video_id)
  944. if 'user_label' in request.POST:
  945. video.user_label = bleach.clean(request.POST['user_label'])
  946. video.save(update_fields=['user_label'])
  947. return redirect('video', video_id=video_id)
  948. @login_required
  949. @require_POST
  950. def edit_tag(request, tag):
  951. tag = request.user.playlist_tags.get(name=tag)
  952. if 'tag_name' in request.POST:
  953. tag.name = bleach.clean(request.POST['tag_name'])
  954. tag.save(update_fields=['name'])
  955. messages.success(request, "Successfully updated the tag's name!")
  956. return redirect('tagged_playlists', tag=tag.name)
  957. @login_required
  958. @require_POST
  959. def delete_tag(request, tag):
  960. tag = request.user.playlist_tags.get(name__iexact=tag)
  961. tag.delete()
  962. messages.success(request, f'Successfully deleted the tag "{tag.name}"')
  963. return redirect('/library/home')
  964. @login_required
  965. @require_POST
  966. def add_playlist_user_label(request, playlist_id):
  967. playlist = request.user.playlists.get(playlist_id=playlist_id)
  968. if 'user_label' in request.POST:
  969. playlist.user_label = bleach.clean(request.POST['user_label'].strip())
  970. playlist.save(update_fields=['user_label'])
  971. return redirect('playlist', playlist_id=playlist_id)
  972. @login_required
  973. @require_POST
  974. def playlist_add_new_videos(request, playlist_id):
  975. textarea_input = bleach.clean(request.POST['add-videos-textarea'])
  976. video_links = textarea_input.strip().split('\n')[:25]
  977. video_ids = []
  978. for video_link in video_links:
  979. if video_link.strip() == '':
  980. continue
  981. video_id = getVideoId(video_link)
  982. if video_id is None or video_id in video_ids:
  983. continue
  984. video_ids.append(video_id)
  985. result = Playlist.objects.addVideosToPlaylist(request.user, playlist_id, video_ids)
  986. added = result['num_added']
  987. max_limit_reached = result['playlistContainsMaximumNumberOfVideos']
  988. if max_limit_reached and added == 0:
  989. message = 'Could not add any new videos to this playlist as the max limit has been reached :('
  990. messages.error(request, message)
  991. elif max_limit_reached and added != 0:
  992. message = f'Only added the first {added} video link(s) to this playlist as the max playlist limit has been reached :('
  993. messages.warning(request, message)
  994. # else:
  995. # message = f'Successfully added {added} videos to this playlist.'
  996. # messages.success(request, message)
  997. return HttpResponse(
  998. """
  999. Done! Refreshing...
  1000. <script>
  1001. window.location.reload();
  1002. </script>
  1003. """
  1004. )
  1005. @login_required
  1006. @require_POST
  1007. def playlist_create_new_playlist(request, playlist_id):
  1008. playlist_name = bleach.clean(request.POST['playlist-name'].strip())
  1009. playlist_description = bleach.clean(request.POST['playlist-description'])
  1010. if playlist_name == '':
  1011. return HttpResponse('Enter a playlist name first!')
  1012. unclean_playlist_item_ids = request.POST.getlist('video-id', default=[])
  1013. clean_playlist_item_ids = [bleach.clean(playlist_item_id) for playlist_item_id in unclean_playlist_item_ids]
  1014. playlist_items = request.user.playlists.get(playlist_id=playlist_id
  1015. ).playlist_items.filter(playlist_item_id__in=clean_playlist_item_ids)
  1016. if not playlist_items.exists():
  1017. return HttpResponse('Select some videos first!')
  1018. else:
  1019. result = Playlist.objects.createNewPlaylist(request.user, playlist_name, playlist_description)
  1020. if result['status'] == 0: # playlist created on youtube
  1021. new_playlist_id = result['playlist_id']
  1022. elif result['status'] == -1:
  1023. return HttpResponse('Error creating playlist!')
  1024. elif result['status'] == 400:
  1025. return HttpResponse('Max playlists limit reached!')
  1026. video_ids = []
  1027. for playlist_item in playlist_items:
  1028. video_ids.append(playlist_item.video.video_id)
  1029. result = Playlist.objects.addVideosToPlaylist(request.user, new_playlist_id, video_ids)
  1030. added = result['num_added']
  1031. max_limit_reached = result['playlistContainsMaximumNumberOfVideos']
  1032. if max_limit_reached:
  1033. message = f'Only added the first {added} video link(s) to the new playlist as the max playlist limit has been reached :('
  1034. else:
  1035. message = f"""Successfully created '{playlist_name}' and added {added} videos to it. Visit the
  1036. <a href='/home/' target='_blank' style='text-decoration: none; color: white' class='ms-1 me-1'>dashboard</a> to import it into UnTube."""
  1037. return HttpResponse(message)