views.py 50 KB

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