2
0

views.py 50 KB

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