views.py 50 KB

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