views.py 29 KB

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