2
0

views.py 51 KB

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