views.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646
  1. import datetime
  2. import pytz
  3. from django.db.models import Q
  4. from django.http import HttpResponse
  5. from django.shortcuts import render, redirect
  6. from apps.main.models import Playlist
  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 Context, loader
  12. # Create your views here.
  13. @login_required
  14. def home(request):
  15. user_profile = request.user.profile
  16. user_playlists = user_profile.playlists.filter(is_in_db=True).order_by("-num_of_accesses")
  17. watching = user_profile.playlists.filter(Q(marked_as="watching") & Q(is_in_db=True)).order_by("-num_of_accesses")
  18. recently_accessed_playlists = user_profile.playlists.filter(is_in_db=True).order_by("-updated_at")[:6]
  19. recently_added_playlists = user_profile.playlists.filter(is_in_db=True).order_by("-created_at")[:6]
  20. #### FOR NEWLY JOINED USERS ######
  21. channel_found = True
  22. if user_profile.just_joined:
  23. if user_profile.import_in_progress:
  24. return render(request, "import_in_progress.html")
  25. else:
  26. if user_profile.access_token.strip() == "" or user_profile.refresh_token.strip() == "":
  27. user_social_token = SocialToken.objects.get(account__user=request.user)
  28. user_profile.access_token = user_social_token.token
  29. user_profile.refresh_token = user_social_token.token_secret
  30. user_profile.expires_at = user_social_token.expires_at
  31. request.user.save()
  32. user_profile.just_joined = False
  33. user_profile.save()
  34. return render(request, "home.html", {"import_successful": True})
  35. # if Playlist.objects.getUserYTChannelID(request.user) == -1: # user channel not found
  36. # channel_found = False
  37. # else:
  38. # Playlist.objects.initPlaylist(request.user, None) # get all playlists from user's YT channel
  39. # return render(request, "home.html", {"import_successful": True})
  40. ##################################
  41. if request.method == "POST":
  42. print(request.POST)
  43. if Playlist.objects.initPlaylist(request.user, request.POST['playlist-id'].strip()) == -1:
  44. print("No such playlist found.")
  45. playlist = []
  46. videos = []
  47. else:
  48. playlist = user_profile.playlists.get(playlist_id__exact=request.POST['playlist-id'].strip())
  49. videos = playlist.videos.all()
  50. else: # GET request
  51. videos = []
  52. playlist = []
  53. print("TESTING")
  54. return render(request, 'home.html', {"channel_found": channel_found,
  55. "playlist": playlist,
  56. "videos": videos,
  57. "user_playlists": user_playlists,
  58. "watching": watching,
  59. "recently_accessed_playlists": recently_accessed_playlists,
  60. "recently_added_playlists": recently_added_playlists})
  61. @login_required
  62. def view_video(request, playlist_id, video_id):
  63. video = request.user.profile.playlists.get(playlist_id=playlist_id).videos.get(video_id=video_id)
  64. print(video.name)
  65. return HttpResponse(loader.get_template("intercooler/video_details.html").render({"video": video}))
  66. @login_required
  67. def video_notes(request, playlist_id, video_id):
  68. video = request.user.profile.playlists.get(playlist_id=playlist_id).videos.get(video_id=video_id)
  69. if request.method == "POST":
  70. if 'video-notes-text-area' in request.POST:
  71. video.user_notes = request.POST['video-notes-text-area']
  72. video.save()
  73. return HttpResponse(loader.get_template("intercooler/messages.html").render(
  74. {"message_type": "success", "message_content": "Saved!"}))
  75. else:
  76. print("GET VIDEO NOTES")
  77. return HttpResponse(loader.get_template("intercooler/video_notes.html").render({"video": video,
  78. "playlist_id": playlist_id}))
  79. @login_required
  80. def view_playlist(request, playlist_id):
  81. user_profile = request.user.profile
  82. # specific playlist requested
  83. if user_profile.playlists.filter(Q(playlist_id=playlist_id) & Q(is_in_db=True)).count() != 0:
  84. playlist = user_profile.playlists.get(playlist_id__exact=playlist_id)
  85. playlist.num_of_accesses += 1
  86. playlist.save()
  87. else:
  88. messages.error(request, "No such playlist found!")
  89. return redirect('home')
  90. if playlist.has_new_updates:
  91. recently_updated_videos = playlist.videos.filter(video_details_modified=True)
  92. for video in recently_updated_videos:
  93. if video.video_details_modified_at + datetime.timedelta(hours=12) < datetime.datetime.now(
  94. pytz.utc): # expired
  95. video.video_details_modified = False
  96. video.save()
  97. if recently_updated_videos.count() == 0:
  98. playlist.has_new_updates = False
  99. playlist.save()
  100. videos = playlist.videos.order_by("video_position")
  101. return render(request, 'view_playlist.html', {"playlist": playlist,
  102. "videos": videos})
  103. @login_required
  104. def all_playlists(request, playlist_type):
  105. """
  106. Possible playlist types for marked_as attribute: (saved in database like this)
  107. "none", "watching", "plan-to-watch"
  108. """
  109. playlist_type = playlist_type.lower()
  110. if playlist_type == "" or playlist_type == "all":
  111. playlists = request.user.profile.playlists.all().filter(is_in_db=True)
  112. playlist_type_display = "All Playlists"
  113. elif playlist_type == "user-owned": # YT playlists owned by user
  114. playlists = request.user.profile.playlists.all().filter(Q(is_user_owned=True) & Q(is_in_db=True))
  115. playlist_type_display = "Your YouTube Playlists"
  116. elif playlist_type == "imported": # YT playlists (public) owned by others
  117. playlists = request.user.profile.playlists.all().filter(Q(is_user_owned=False) & Q(is_in_db=True))
  118. playlist_type_display = "Imported playlists"
  119. elif playlist_type == "favorites": # YT playlists (public) owned by others
  120. playlists = request.user.profile.playlists.all().filter(Q(is_favorite=True) & Q(is_in_db=True))
  121. playlist_type_display = "Favorites"
  122. elif playlist_type.lower() in ["watching", "plan-to-watch"]:
  123. playlists = request.user.profile.playlists.filter(Q(marked_as=playlist_type.lower()) & Q(is_in_db=True))
  124. playlist_type_display = playlist_type.lower().replace("-", " ")
  125. elif playlist_type.lower() == "home": # displays cards of all playlist types
  126. return render(request, 'playlists_home.html')
  127. else:
  128. return redirect('home')
  129. return render(request, 'all_playlists.html', {"playlists": playlists,
  130. "playlist_type": playlist_type,
  131. "playlist_type_display": playlist_type_display})
  132. @login_required
  133. def order_playlist_by(request, playlist_id, order_by):
  134. playlist = request.user.profile.playlists.get(Q(playlist_id=playlist_id) & Q(is_in_db=True))
  135. display_text = "Nothing in this playlist! Add something!" # what to display when requested order/filter has no videws
  136. videos_details = ""
  137. if order_by == "all":
  138. videos = playlist.videos.order_by("video_position")
  139. elif order_by == "favorites":
  140. videos = playlist.videos.filter(is_favorite=True).order_by("video_position")
  141. videos_details = "Sorted by Favorites"
  142. display_text = "No favorites yet!"
  143. elif order_by == "popularity":
  144. videos_details = "Sorted by Popularity"
  145. videos = playlist.videos.order_by("-like_count")
  146. elif order_by == "date-published":
  147. videos_details = "Sorted by Date Published"
  148. videos = playlist.videos.order_by("-published_at")
  149. elif order_by == "views":
  150. videos_details = "Sorted by View Count"
  151. videos = playlist.videos.order_by("-view_count")
  152. elif order_by == "has-cc":
  153. videos_details = "Filtered by Has CC"
  154. videos = playlist.videos.filter(has_cc=True).order_by("video_position")
  155. display_text = "No videos in this playlist have CC :("
  156. elif order_by == "duration":
  157. videos_details = "Sorted by Video Duration"
  158. videos = playlist.videos.order_by("-duration_in_seconds")
  159. elif order_by == 'new-updates':
  160. videos = []
  161. videos_details = "Sorted by New Updates"
  162. display_text = "No new updates! Note that deleted videos will not show up here."
  163. if playlist.has_new_updates:
  164. recently_updated_videos = playlist.videos.filter(video_details_modified=True)
  165. for video in recently_updated_videos:
  166. if video.video_details_modified_at + datetime.timedelta(hours=12) < datetime.datetime.now(
  167. pytz.utc): # expired
  168. video.video_details_modified = False
  169. video.save()
  170. if recently_updated_videos.count() == 0:
  171. playlist.has_new_updates = False
  172. playlist.save()
  173. else:
  174. videos = recently_updated_videos.order_by("video_position")
  175. elif order_by == 'unavailable-videos':
  176. videos = playlist.videos.filter(Q(is_unavailable_on_yt=True) & Q(was_deleted_on_yt=True))
  177. videos_details = "Sorted by Unavailable Videos"
  178. display_text = "None of the videos in this playlist have gone unavailable... yet."
  179. else:
  180. return redirect('home')
  181. return HttpResponse(loader.get_template("intercooler/videos.html").render({"playlist": playlist,
  182. "videos": videos,
  183. "videos_details": videos_details,
  184. "display_text": display_text}))
  185. @login_required
  186. def order_playlists_by(request, playlist_type, order_by):
  187. if playlist_type == "" or playlist_type.lower() == "all":
  188. playlists = request.user.profile.playlists.all()
  189. playlist_type_display = "All Playlists"
  190. elif playlist_type.lower() == "favorites":
  191. playlists = request.user.profile.playlists.filter(Q(is_favorite=True) & Q(is_in_db=True))
  192. playlist_type_display = "Favorites"
  193. elif playlist_type.lower() in ["watching", "plan-to-watch"]:
  194. playlists = request.user.profile.playlists.filter(Q(marked_as=playlist_type.lower()) & Q(is_in_db=True))
  195. playlist_type_display = "Watching"
  196. else:
  197. return redirect('home')
  198. if order_by == 'recently-accessed':
  199. playlists = playlists.order_by("-updated_at")
  200. elif order_by == 'playlist-duration-in-seconds':
  201. playlists = playlists.order_by("-playlist_duration_in_seconds")
  202. elif order_by == 'video-count':
  203. playlists = playlists.order_by("-video_count")
  204. return HttpResponse(loader.get_template("intercooler/playlists.html")
  205. .render({"playlists": playlists,
  206. "playlist_type_display": playlist_type_display,
  207. "playlist_type": playlist_type}))
  208. @login_required
  209. def mark_playlist_as(request, playlist_id, mark_as):
  210. playlist = request.user.profile.playlists.get(playlist_id=playlist_id)
  211. marked_as_response = ""
  212. if mark_as in ["watching", "on-hold", "plan-to-watch"]:
  213. playlist.marked_as = mark_as
  214. playlist.save()
  215. marked_as_response = f'<span class="badge bg-success text-white" >{mark_as.replace("-", " ")}</span>'
  216. elif mark_as == "none":
  217. playlist.marked_as = mark_as
  218. playlist.save()
  219. elif mark_as == "favorite":
  220. if playlist.is_favorite:
  221. playlist.is_favorite = False
  222. playlist.save()
  223. return HttpResponse('<i class="far fa-star"></i>')
  224. else:
  225. playlist.is_favorite = True
  226. playlist.save()
  227. return HttpResponse('<i class="fas fa-star"></i>')
  228. else:
  229. return render('home')
  230. return HttpResponse(marked_as_response)
  231. @login_required
  232. def playlists_home(request):
  233. return render(request, 'playlists_home.html')
  234. @login_required
  235. @require_POST
  236. def delete_videos(request, playlist_id, command):
  237. video_ids = request.POST.getlist("video-id", default=[])
  238. print(request.META, request.META["HTTP_HOST"])
  239. if command == "confirm":
  240. print(video_ids)
  241. num_vids = len(video_ids)
  242. extra_text = " "
  243. if num_vids == 0:
  244. return HttpResponse("<h5>Select some videos first!</h5>")
  245. elif num_vids == request.user.profile.playlists.get(playlist_id=playlist_id).videos.all().count():
  246. delete_text = "ALL VIDEOS"
  247. extra_text = " This will not delete the playlist itself, will only make the playlist empty. "
  248. else:
  249. delete_text = f"{num_vids} videos"
  250. return HttpResponse(
  251. f"<h5>Are you sure you want to delete {delete_text} from your YouTube playlist?{extra_text}This cannot be undone.</h5>")
  252. elif command == "confirmed":
  253. print(video_ids)
  254. return HttpResponse(
  255. f'<div class="spinner-border text-light" role="status" hx-post="/from/{playlist_id}/delete-videos/start" hx-trigger="load" hx-swap="outerHTML"></div>')
  256. elif command == "start":
  257. Playlist.objects.deletePlaylistItems(request.user, playlist_id, video_ids)
  258. return HttpResponse(f'<div hx-get="http://{request.META["HTTP_HOST"]}/update_playlist/{playlist_id}/manual" hx-target="#view_playlist" hx-trigger="load">Done!</div>')
  259. @login_required
  260. @require_POST
  261. def search_playlists(request, playlist_type):
  262. print(request.POST) # prints <QueryDict: {'search': ['aa']}>
  263. search_query = request.POST["search"]
  264. if playlist_type == "all":
  265. try:
  266. playlists = request.user.profile.playlists.all().filter(Q(name__startswith=search_query) & Q(is_in_db=True))
  267. except:
  268. playlists = request.user.profile.playlists.all()
  269. playlist_type_display = "All Playlists"
  270. elif playlist_type == "user-owned": # YT playlists owned by user
  271. try:
  272. playlists = request.user.profile.playlists.filter(Q(name__startswith=search_query) & Q(is_user_owned=True) & Q(is_in_db=True))
  273. except:
  274. playlists = request.user.profile.playlists.filter(Q(is_user_owned=True) & Q(is_in_db=True))
  275. playlist_type_display = "Your YouTube Playlists"
  276. elif playlist_type == "imported": # YT playlists (public) owned by others
  277. try:
  278. playlists = request.user.profile.playlists.filter(Q(name__startswith=search_query) & Q(is_user_owned=False) & Q(is_in_db=True))
  279. except:
  280. playlists = request.user.profile.playlists.filter(Q(is_user_owned=True) & Q(is_in_db=True))
  281. playlist_type_display = "Imported Playlists"
  282. elif playlist_type == "favorites": # YT playlists (public) owned by others
  283. try:
  284. playlists = request.user.profile.playlists.filter(Q(name__startswith=search_query) & Q(is_favorite=True) & Q(is_in_db=True))
  285. except:
  286. playlists = request.user.profile.playlists.filter(Q(is_favorite=True) & Q(is_in_db=True))
  287. playlist_type_display = "Your Favorites"
  288. elif playlist_type in ["watching", "plan-to-watch"]:
  289. try:
  290. playlists = request.user.profile.playlists.filter(
  291. Q(name__startswith=search_query) & Q(marked_as=playlist_type) & Q(is_in_db=True))
  292. except:
  293. playlists = request.user.profile.playlists.all().filter(Q(marked_as=playlist_type) & Q(is_in_db=True))
  294. playlist_type_display = playlist_type.replace("-", " ")
  295. return HttpResponse(loader.get_template("intercooler/playlists.html")
  296. .render({"playlists": playlists,
  297. "playlist_type_display": playlist_type_display,
  298. "playlist_type": playlist_type,
  299. "search_query": search_query}))
  300. #### MANAGE VIDEOS #####
  301. def mark_video_favortie(request, playlist_id, video_id):
  302. video = request.user.profile.playlists.get(playlist_id=playlist_id).videos.get(video_id=video_id)
  303. if video.is_favorite:
  304. video.is_favorite = False
  305. video.save()
  306. return HttpResponse('<i class="far fa-heart"></i>')
  307. else:
  308. video.is_favorite = True
  309. video.save()
  310. return HttpResponse('<i class="fas fa-heart"></i>')
  311. ###########
  312. @login_required
  313. def search(request):
  314. if request.method == "GET":
  315. return render(request, 'search_untube_page.html')
  316. else:
  317. return render('home')
  318. @login_required
  319. @require_POST
  320. def search_UnTube(request):
  321. print(request.POST)
  322. search_query = request.POST["search"]
  323. all_playlists = request.user.profile.playlists.filter(is_in_db=True)
  324. videos = []
  325. starts_with = False
  326. contains = False
  327. if request.POST['search-settings'] == 'starts-with':
  328. playlists = request.user.profile.playlists.filter(Q(name__startswith=search_query) & Q(is_in_db=True)) if search_query != "" else []
  329. if search_query != "":
  330. for playlist in all_playlists:
  331. pl_videos = playlist.videos.filter(name__startswith=search_query)
  332. if pl_videos.count() != 0:
  333. for v in pl_videos.all():
  334. videos.append(v)
  335. starts_with = True
  336. else:
  337. playlists = request.user.profile.playlists.filter(Q(name__contains=search_query) & Q(is_in_db=True)) if search_query != "" else []
  338. if search_query != "":
  339. for playlist in all_playlists:
  340. pl_videos = playlist.videos.filter(name__contains=search_query)
  341. if pl_videos.count() != 0:
  342. for v in pl_videos.all():
  343. videos.append(v)
  344. contains = True
  345. return HttpResponse(loader.get_template("intercooler/search_untube.html")
  346. .render({"playlists": playlists,
  347. "videos": videos,
  348. "videos_count": len(videos),
  349. "search_query": search_query,
  350. "starts_with": starts_with,
  351. "contains": contains}))
  352. @login_required
  353. def manage_playlists(request):
  354. return render(request, "manage_playlists.html")
  355. @login_required
  356. def manage_view_page(request, page):
  357. if page == "import":
  358. return HttpResponse(loader.get_template("intercooler/manage_playlists_import.html")
  359. .render(
  360. {"manage_playlists_import_textarea": request.user.profile.manage_playlists_import_textarea}))
  361. elif page == "create":
  362. return HttpResponse(loader.get_template("intercooler/manage_playlists_create.html")
  363. .render(
  364. {}))
  365. else:
  366. return redirect('home')
  367. @login_required
  368. @require_POST
  369. def manage_save(request, what):
  370. if what == "manage_playlists_import_textarea":
  371. request.user.profile.manage_playlists_import_textarea = request.POST["import-playlist-textarea"]
  372. request.user.save()
  373. return HttpResponse("")
  374. @login_required
  375. @require_POST
  376. def manage_import_playlists(request):
  377. playlist_links = request.POST["import-playlist-textarea"].replace(",", "").split("\n")
  378. num_playlists_already_in_db = 0
  379. num_playlists_initialized_in_db = 0
  380. num_playlists_not_found = 0
  381. new_playlists = []
  382. old_playlists = []
  383. not_found_playlists = []
  384. done = []
  385. for playlist_link in playlist_links:
  386. if playlist_link.strip() != "" and playlist_link.strip() not in done:
  387. pl_id = Playlist.objects.getPlaylistId(playlist_link.strip())
  388. if pl_id is None:
  389. num_playlists_not_found += 1
  390. continue
  391. status = Playlist.objects.initPlaylist(request.user, pl_id)
  392. if status == -1 or status == -2:
  393. print("\nNo such playlist found:", pl_id)
  394. num_playlists_not_found += 1
  395. not_found_playlists.append(playlist_link)
  396. elif status == -3:
  397. num_playlists_already_in_db += 1
  398. playlist = request.user.profile.playlists.get(playlist_id__exact=pl_id)
  399. old_playlists.append(playlist)
  400. else:
  401. print(status)
  402. playlist = request.user.profile.playlists.get(playlist_id__exact=pl_id)
  403. new_playlists.append(playlist)
  404. num_playlists_initialized_in_db += 1
  405. done.append(playlist_link.strip())
  406. request.user.profile.manage_playlists_import_textarea = ""
  407. request.user.save()
  408. return HttpResponse(loader.get_template("intercooler/manage_playlists_import_results.html")
  409. .render(
  410. {"new_playlists": new_playlists,
  411. "old_playlists": old_playlists,
  412. "not_found_playlists": not_found_playlists,
  413. "num_playlists_already_in_db": num_playlists_already_in_db,
  414. "num_playlists_initialized_in_db": num_playlists_initialized_in_db,
  415. "num_playlists_not_found": num_playlists_not_found
  416. }))
  417. @login_required
  418. @require_POST
  419. def manage_create_playlist(request):
  420. print(request.POST)
  421. return HttpResponse("")
  422. @login_required
  423. def update_playlist(request, playlist_id, type):
  424. playlist = request.user.profile.playlists.get(playlist_id=playlist_id)
  425. if type == "checkforupdates":
  426. print("Checking if playlist changed...")
  427. result = Playlist.objects.checkIfPlaylistChangedOnYT(request.user, playlist_id)
  428. if result[0] == 1: # full scan was done (full scan is done for a playlist if a week has passed)
  429. deleted_videos, unavailable_videos, added_videos = result[1:]
  430. print("CHANGES", deleted_videos, unavailable_videos, added_videos)
  431. playlist_changed_text = ["The following modifications happened to this playlist on YouTube:"]
  432. if deleted_videos != 0 or unavailable_videos != 0 or added_videos != 0:
  433. if added_videos > 0:
  434. playlist_changed_text.append(f"{added_videos} new video(s) were added")
  435. if deleted_videos > 0:
  436. playlist_changed_text.append(f"{deleted_videos} video(s) were deleted")
  437. if unavailable_videos > 0:
  438. playlist_changed_text.append(f"{unavailable_videos} video(s) went private/unavailable")
  439. playlist.playlist_changed_text = "\n".join(playlist_changed_text)
  440. playlist.has_playlist_changed = True
  441. playlist.save()
  442. else: # no updates found
  443. return HttpResponse("""
  444. <div class="alert alert-success alert-dismissible fade show visually-hidden" role="alert">
  445. No new updates!
  446. </div>
  447. """)
  448. elif result[0] == -1: # playlist changed
  449. print("!!!Playlist changed")
  450. current_playlist_vid_count = playlist.video_count
  451. new_playlist_vid_count = result[1]
  452. print(current_playlist_vid_count)
  453. print(new_playlist_vid_count)
  454. if current_playlist_vid_count > new_playlist_vid_count:
  455. playlist.playlist_changed_text = f"Looks like {current_playlist_vid_count - new_playlist_vid_count} video(s) were deleted from this playlist on YouTube!"
  456. else:
  457. playlist.playlist_changed_text = f"Looks like {new_playlist_vid_count - current_playlist_vid_count} video(s) were added to this playlist on YouTube!"
  458. playlist.has_playlist_changed = True
  459. playlist.save()
  460. print(playlist.playlist_changed_text)
  461. else: # no updates found
  462. return HttpResponse("""
  463. <div class="alert alert-success alert-dismissible fade show visually-hidden" role="alert">
  464. No new updates!
  465. </div>
  466. """)
  467. return HttpResponse(f"""
  468. <div hx-get="/playlist/{playlist_id}/update/auto" hx-trigger="load" hx-target="#view_playlist">
  469. <div class="alert alert-success alert-dismissible fade show" role="alert">
  470. {playlist.playlist_changed_text}
  471. <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
  472. </div>
  473. <div class="d-flex justify-content-center mt-4 mb-3" id="loading-sign">
  474. <img src="/static/svg-loaders/circles.svg" width="40" height="40">
  475. <h5 class="mt-2 ms-2">Updating playlist '{playlist.name}', please wait!</h5>
  476. </div>
  477. </div>
  478. """)
  479. if type == "manual":
  480. print("MANUAL")
  481. return HttpResponse(
  482. f"""<div hx-get="/playlist/{playlist_id}/update/auto" hx-trigger="load" hx-swap="outerHTML">
  483. <div class="d-flex justify-content-center mt-4 mb-3" id="loading-sign">
  484. <img src="/static/svg-loaders/circles.svg" width="40" height="40">
  485. <h5 class="mt-2 ms-2">Refreshing playlist '{playlist.name}', please wait!</h5>
  486. </div>
  487. </div>""")
  488. print("Attempting to update playlist")
  489. status, deleted_video_ids, unavailable_videos, added_videos = Playlist.objects.updatePlaylist(request.user, playlist_id)
  490. playlist = request.user.profile.playlists.get(playlist_id=playlist_id)
  491. if status == -1:
  492. playlist_name = playlist.name
  493. playlist.delete()
  494. return HttpResponse(
  495. f"""
  496. <div class="d-flex justify-content-center mt-4 mb-3" id="loading-sign">
  497. <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>
  498. </div>
  499. """)
  500. print("Updated playlist")
  501. playlist_changed_text = []
  502. if len(added_videos) != 0:
  503. playlist_changed_text.append(f"{len(added_videos)} added")
  504. for video in added_videos:
  505. playlist_changed_text.append(f"--> {video.name}")
  506. #if len(added_videos) > 3:
  507. # playlist_changed_text.append(f"+ {len(added_videos) - 3} more")
  508. if len(unavailable_videos) != 0:
  509. if len(playlist_changed_text) == 0:
  510. playlist_changed_text.append(f"{len(unavailable_videos)} went unavailable")
  511. else:
  512. playlist_changed_text.append(f"\n{len(unavailable_videos)} went unavailable")
  513. for video in unavailable_videos:
  514. playlist_changed_text.append(f"--> {video.name}")
  515. if len(deleted_video_ids) != 0:
  516. if len(playlist_changed_text) == 0:
  517. playlist_changed_text.append(f"{len(deleted_video_ids)} deleted")
  518. else:
  519. playlist_changed_text.append(f"\n{len(deleted_video_ids)} deleted")
  520. for video_id in deleted_video_ids:
  521. video = playlist.videos.get(video_id=video_id)
  522. playlist_changed_text.append(f"--> {video.name}")
  523. video.delete()
  524. if len(playlist_changed_text) == 0:
  525. playlist_changed_text = ["Successfully refreshed playlist! No new changes found!"]
  526. # return HttpResponse
  527. return HttpResponse(loader.get_template("intercooler/playlist_updates.html")
  528. .render(
  529. {"playlist_changed_text": "\n".join(playlist_changed_text),
  530. "playlist_id": playlist_id}))
  531. def view_playlist_settings(request, playlist_id):
  532. playlist = request.user.profile.playlists.get(playlist_id=playlist_id)
  533. return render(request, 'view_playlist_settings.html', {"playlist": playlist})