views.py 51 KB

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