views.py 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836
  1. import datetime
  2. import pytz
  3. from django.db.models import Q
  4. from django.http import HttpResponse, HttpResponseRedirect
  5. from django.shortcuts import render, redirect, get_object_or_404
  6. from apps.main.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 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. user_owned_playlists = user_profile.playlists.filter(Q(is_user_owned=True) & Q(is_in_db=True))
  91. # specific playlist requested
  92. if user_profile.playlists.filter(Q(playlist_id=playlist_id) & Q(is_in_db=True)).count() != 0:
  93. playlist = user_profile.playlists.get(playlist_id__exact=playlist_id)
  94. playlist.num_of_accesses += 1
  95. playlist.save()
  96. else:
  97. messages.error(request, "No such playlist found!")
  98. return redirect('home')
  99. if playlist.has_new_updates:
  100. recently_updated_videos = playlist.videos.filter(video_details_modified=True)
  101. for video in recently_updated_videos:
  102. if video.video_details_modified_at + datetime.timedelta(hours=12) < datetime.datetime.now(
  103. pytz.utc): # expired
  104. video.video_details_modified = False
  105. video.save()
  106. if recently_updated_videos.count() == 0:
  107. playlist.has_new_updates = False
  108. playlist.save()
  109. videos = playlist.videos.order_by("video_position")
  110. user_created_tags = Tag.objects.filter(created_by=request.user)
  111. playlist_tags = playlist.tags.all()
  112. unused_tags = user_created_tags.difference(playlist_tags)
  113. return render(request, 'view_playlist.html', {"playlist": playlist,
  114. "playlist_tags": playlist_tags,
  115. "unused_tags": unused_tags,
  116. "videos": videos,
  117. "user_owned_playlists": user_owned_playlists})
  118. @login_required
  119. def tagged_playlists(request, tag):
  120. tag = get_object_or_404(Tag, created_by=request.user, name=tag)
  121. playlists = tag.playlists.all()
  122. return render(request, 'all_playlists_with_tag.html', {"playlists": playlists, "tag": tag})
  123. @login_required
  124. def all_playlists(request, playlist_type):
  125. """
  126. Possible playlist types for marked_as attribute: (saved in database like this)
  127. "none", "watching", "plan-to-watch"
  128. """
  129. playlist_type = playlist_type.lower()
  130. if playlist_type == "" or playlist_type == "all":
  131. playlists = request.user.profile.playlists.all().filter(is_in_db=True)
  132. playlist_type_display = "All Playlists"
  133. elif playlist_type == "user-owned": # YT playlists owned by user
  134. playlists = request.user.profile.playlists.all().filter(Q(is_user_owned=True) & Q(is_in_db=True))
  135. playlist_type_display = "Your YouTube Playlists"
  136. elif playlist_type == "imported": # YT playlists (public) owned by others
  137. playlists = request.user.profile.playlists.all().filter(Q(is_user_owned=False) & Q(is_in_db=True))
  138. playlist_type_display = "Imported playlists"
  139. elif playlist_type == "favorites": # YT playlists (public) owned by others
  140. playlists = request.user.profile.playlists.all().filter(Q(is_favorite=True) & Q(is_in_db=True))
  141. playlist_type_display = "Favorites"
  142. elif playlist_type.lower() in ["watching", "plan-to-watch"]:
  143. playlists = request.user.profile.playlists.filter(Q(marked_as=playlist_type.lower()) & Q(is_in_db=True))
  144. playlist_type_display = playlist_type.lower().replace("-", " ")
  145. elif playlist_type.lower() == "home": # displays cards of all playlist types
  146. return render(request, 'playlists_home.html')
  147. else:
  148. return redirect('home')
  149. return render(request, 'all_playlists.html', {"playlists": playlists,
  150. "playlist_type": playlist_type,
  151. "playlist_type_display": playlist_type_display})
  152. @login_required
  153. def order_playlist_by(request, playlist_id, order_by):
  154. playlist = request.user.profile.playlists.get(Q(playlist_id=playlist_id) & Q(is_in_db=True))
  155. display_text = "Nothing in this playlist! Add something!" # what to display when requested order/filter has no videws
  156. videos_details = ""
  157. if order_by == "all":
  158. videos = playlist.videos.order_by("video_position")
  159. elif order_by == "favorites":
  160. videos = playlist.videos.filter(is_favorite=True).order_by("video_position")
  161. videos_details = "Sorted by Favorites"
  162. display_text = "No favorites yet!"
  163. elif order_by == "popularity":
  164. videos_details = "Sorted by Popularity"
  165. videos = playlist.videos.order_by("-like_count")
  166. elif order_by == "date-published":
  167. videos_details = "Sorted by Date Published"
  168. videos = playlist.videos.order_by("-published_at")
  169. elif order_by == "views":
  170. videos_details = "Sorted by View Count"
  171. videos = playlist.videos.order_by("-view_count")
  172. elif order_by == "has-cc":
  173. videos_details = "Filtered by Has CC"
  174. videos = playlist.videos.filter(has_cc=True).order_by("video_position")
  175. display_text = "No videos in this playlist have CC :("
  176. elif order_by == "duration":
  177. videos_details = "Sorted by Video Duration"
  178. videos = playlist.videos.order_by("-duration_in_seconds")
  179. elif order_by == 'new-updates':
  180. videos = []
  181. videos_details = "Sorted by New Updates"
  182. display_text = "No new updates! Note that deleted videos will not show up here."
  183. if playlist.has_new_updates:
  184. recently_updated_videos = playlist.videos.filter(video_details_modified=True)
  185. for video in recently_updated_videos:
  186. if video.video_details_modified_at + datetime.timedelta(hours=12) < datetime.datetime.now(
  187. pytz.utc): # expired
  188. video.video_details_modified = False
  189. video.save()
  190. if recently_updated_videos.count() == 0:
  191. playlist.has_new_updates = False
  192. playlist.save()
  193. else:
  194. videos = recently_updated_videos.order_by("video_position")
  195. elif order_by == 'unavailable-videos':
  196. videos = playlist.videos.filter(Q(is_unavailable_on_yt=True) & Q(was_deleted_on_yt=True))
  197. videos_details = "Sorted by Unavailable Videos"
  198. display_text = "None of the videos in this playlist have gone unavailable... yet."
  199. else:
  200. return redirect('home')
  201. return HttpResponse(loader.get_template("intercooler/videos.html").render({"playlist": playlist,
  202. "videos": videos,
  203. "videos_details": videos_details,
  204. "display_text": display_text}))
  205. @login_required
  206. def order_playlists_by(request, playlist_type, order_by):
  207. if playlist_type == "" or playlist_type.lower() == "all":
  208. playlists = request.user.profile.playlists.all()
  209. playlist_type_display = "All Playlists"
  210. elif playlist_type.lower() == "favorites":
  211. playlists = request.user.profile.playlists.filter(Q(is_favorite=True) & Q(is_in_db=True))
  212. playlist_type_display = "Favorites"
  213. elif playlist_type.lower() in ["watching", "plan-to-watch"]:
  214. playlists = request.user.profile.playlists.filter(Q(marked_as=playlist_type.lower()) & Q(is_in_db=True))
  215. playlist_type_display = "Watching"
  216. else:
  217. return redirect('home')
  218. if order_by == 'recently-accessed':
  219. playlists = playlists.order_by("-updated_at")
  220. elif order_by == 'playlist-duration-in-seconds':
  221. playlists = playlists.order_by("-playlist_duration_in_seconds")
  222. elif order_by == 'video-count':
  223. playlists = playlists.order_by("-video_count")
  224. return HttpResponse(loader.get_template("intercooler/playlists.html")
  225. .render({"playlists": playlists,
  226. "playlist_type_display": playlist_type_display,
  227. "playlist_type": playlist_type}))
  228. @login_required
  229. def mark_playlist_as(request, playlist_id, mark_as):
  230. playlist = request.user.profile.playlists.get(playlist_id=playlist_id)
  231. marked_as_response = ""
  232. if mark_as in ["watching", "on-hold", "plan-to-watch"]:
  233. playlist.marked_as = mark_as
  234. playlist.save()
  235. icon = ""
  236. if mark_as == "watching":
  237. icon = '<i class="fas fa-fire-alt me-2"></i>'
  238. elif mark_as == "plan-to-watch":
  239. icon = '<i class="fas fa-flag me-2"></i>'
  240. marked_as_response = f'<span class="badge bg-success text-white" >{icon}{mark_as}</span> <meta http-equiv="refresh" content="0" />'
  241. elif mark_as == "none":
  242. playlist.marked_as = mark_as
  243. playlist.save()
  244. elif mark_as == "favorite":
  245. if playlist.is_favorite:
  246. playlist.is_favorite = False
  247. playlist.save()
  248. return HttpResponse('<i class="far fa-star"></i>')
  249. else:
  250. playlist.is_favorite = True
  251. playlist.save()
  252. return HttpResponse('<i class="fas fa-star"></i>')
  253. else:
  254. return render('home')
  255. return HttpResponse(marked_as_response)
  256. @login_required
  257. def playlists_home(request):
  258. return render(request, 'playlists_home.html')
  259. @login_required
  260. @require_POST
  261. def delete_videos(request, playlist_id, command):
  262. video_ids = request.POST.getlist("video-id", default=[])
  263. if command == "confirm":
  264. print(video_ids)
  265. num_vids = len(video_ids)
  266. extra_text = " "
  267. if num_vids == 0:
  268. return HttpResponse("<h5>Select some videos first!</h5>")
  269. elif num_vids == request.user.profile.playlists.get(playlist_id=playlist_id).videos.all().count():
  270. delete_text = "ALL VIDEOS"
  271. extra_text = " This will not delete the playlist itself, will only make the playlist empty. "
  272. else:
  273. delete_text = f"{num_vids} videos"
  274. return HttpResponse(
  275. f"<h5>Are you sure you want to delete {delete_text} from your YouTube playlist?{extra_text}This cannot be undone.</h5>")
  276. elif command == "confirmed":
  277. print(video_ids)
  278. return HttpResponse(
  279. f'<div class="spinner-border text-light" role="status" hx-post="/from/{playlist_id}/delete-videos/start" hx-trigger="load" hx-swap="outerHTML"></div>')
  280. elif command == "start":
  281. Playlist.objects.deletePlaylistItems(request.user, playlist_id, video_ids)
  282. # playlist = request.user.profile.playlists.get(playlist_id=playlist_id)
  283. # playlist.has_playlist_changed = True
  284. # playlist.save(update_fields=['has_playlist_changed'])
  285. return HttpResponse(f"""
  286. <div hx-get="/playlist/{playlist_id}/update/checkforupdates" hx-trigger="load delay:1s" hx-target="#checkforupdates" class="sticky-top" style="top: 0.5rem;">
  287. Done! Playlist on UnTube will update in soon...
  288. </div>
  289. """)
  290. @login_required
  291. @require_POST
  292. def search_tagged_playlists(request, tag):
  293. tag = get_object_or_404(Tag, created_by=request.user, name=tag)
  294. playlists = tag.playlists.all()
  295. return HttpResponse("yay")
  296. @login_required
  297. @require_POST
  298. def search_playlists(request, playlist_type):
  299. # print(request.POST) # prints <QueryDict: {'search': ['aa']}>
  300. search_query = request.POST["search"]
  301. if playlist_type == "all":
  302. try:
  303. playlists = request.user.profile.playlists.all().filter(Q(name__startswith=search_query) & Q(is_in_db=True))
  304. except:
  305. playlists = request.user.profile.playlists.all()
  306. playlist_type_display = "All Playlists"
  307. elif playlist_type == "user-owned": # YT playlists owned by user
  308. try:
  309. playlists = request.user.profile.playlists.filter(
  310. Q(name__startswith=search_query) & Q(is_user_owned=True) & Q(is_in_db=True))
  311. except:
  312. playlists = request.user.profile.playlists.filter(Q(is_user_owned=True) & Q(is_in_db=True))
  313. playlist_type_display = "Your YouTube Playlists"
  314. elif playlist_type == "imported": # YT playlists (public) owned by others
  315. try:
  316. playlists = request.user.profile.playlists.filter(
  317. Q(name__startswith=search_query) & Q(is_user_owned=False) & Q(is_in_db=True))
  318. except:
  319. playlists = request.user.profile.playlists.filter(Q(is_user_owned=True) & Q(is_in_db=True))
  320. playlist_type_display = "Imported Playlists"
  321. elif playlist_type == "favorites": # YT playlists (public) owned by others
  322. try:
  323. playlists = request.user.profile.playlists.filter(
  324. Q(name__startswith=search_query) & Q(is_favorite=True) & Q(is_in_db=True))
  325. except:
  326. playlists = request.user.profile.playlists.filter(Q(is_favorite=True) & Q(is_in_db=True))
  327. playlist_type_display = "Your Favorites"
  328. elif playlist_type in ["watching", "plan-to-watch"]:
  329. try:
  330. playlists = request.user.profile.playlists.filter(
  331. Q(name__startswith=search_query) & Q(marked_as=playlist_type) & Q(is_in_db=True))
  332. except:
  333. playlists = request.user.profile.playlists.all().filter(Q(marked_as=playlist_type) & Q(is_in_db=True))
  334. playlist_type_display = playlist_type.replace("-", " ")
  335. return HttpResponse(loader.get_template("intercooler/playlists.html")
  336. .render({"playlists": playlists,
  337. "playlist_type_display": playlist_type_display,
  338. "playlist_type": playlist_type,
  339. "search_query": search_query}))
  340. #### MANAGE VIDEOS #####
  341. def mark_video_favortie(request, playlist_id, video_id):
  342. video = request.user.profile.playlists.get(playlist_id=playlist_id).videos.get(video_id=video_id)
  343. if video.is_favorite:
  344. video.is_favorite = False
  345. video.save()
  346. return HttpResponse('<i class="far fa-heart"></i>')
  347. else:
  348. video.is_favorite = True
  349. video.save()
  350. return HttpResponse('<i class="fas fa-heart"></i>')
  351. ###########
  352. @login_required
  353. def search(request):
  354. if request.method == "GET":
  355. return render(request, 'search_untube_page.html')
  356. else:
  357. return render('home')
  358. @login_required
  359. @require_POST
  360. def search_UnTube(request):
  361. print(request.POST)
  362. search_query = request.POST["search"]
  363. all_playlists = request.user.profile.playlists.filter(is_in_db=True)
  364. if 'playlist-tags' in request.POST:
  365. tags = request.POST.getlist('playlist-tags')
  366. all_playlists = all_playlists.filter(tags__name__in=tags)
  367. videos = []
  368. if request.POST['search-settings'] == 'starts-with':
  369. playlists = all_playlists.filter(name__istartswith=search_query) if search_query != "" else all_playlists.none()
  370. if search_query != "":
  371. for playlist in all_playlists:
  372. pl_videos = playlist.videos.filter(name__istartswith=search_query)
  373. if pl_videos.count() != 0:
  374. for v in pl_videos.all():
  375. videos.append(v)
  376. else:
  377. playlists = all_playlists.filter(name__icontains=search_query) if search_query != "" else all_playlists.none()
  378. if search_query != "":
  379. for playlist in all_playlists:
  380. pl_videos = playlist.videos.filter(name__icontains=search_query)
  381. if pl_videos.count() != 0:
  382. for v in pl_videos.all():
  383. videos.append(v)
  384. return HttpResponse(loader.get_template("intercooler/search_untube_results.html")
  385. .render({"playlists": playlists,
  386. "videos": videos,
  387. "videos_count": len(videos),
  388. "search_query": True if search_query != "" else False,
  389. "all_playlists": all_playlists}))
  390. @login_required
  391. def manage_playlists(request):
  392. return render(request, "manage_playlists.html")
  393. @login_required
  394. def manage_view_page(request, page):
  395. if page == "import":
  396. return render(request, "manage_playlists_import.html",
  397. {"manage_playlists_import_textarea": request.user.profile.manage_playlists_import_textarea})
  398. elif page == "create":
  399. return render(request, "manage_playlists_create.html")
  400. else:
  401. return HttpResponse('Working on this!')
  402. @login_required
  403. @require_POST
  404. def manage_save(request, what):
  405. if what == "manage_playlists_import_textarea":
  406. request.user.profile.manage_playlists_import_textarea = request.POST["import-playlist-textarea"]
  407. request.user.save()
  408. return HttpResponse("")
  409. @login_required
  410. @require_POST
  411. def manage_import_playlists(request):
  412. playlist_links = request.POST["import-playlist-textarea"].replace(",", "").split("\n")
  413. num_playlists_already_in_db = 0
  414. num_playlists_initialized_in_db = 0
  415. num_playlists_not_found = 0
  416. new_playlists = []
  417. old_playlists = []
  418. not_found_playlists = []
  419. done = []
  420. for playlist_link in playlist_links:
  421. if playlist_link.strip() != "" and playlist_link.strip() not in done:
  422. pl_id = Playlist.objects.getPlaylistId(playlist_link.strip())
  423. if pl_id is None:
  424. num_playlists_not_found += 1
  425. continue
  426. status = Playlist.objects.initPlaylist(request.user, pl_id)
  427. if status == -1 or status == -2:
  428. print("\nNo such playlist found:", pl_id)
  429. num_playlists_not_found += 1
  430. not_found_playlists.append(playlist_link)
  431. elif status == -3:
  432. num_playlists_already_in_db += 1
  433. playlist = request.user.profile.playlists.get(playlist_id__exact=pl_id)
  434. old_playlists.append(playlist)
  435. else:
  436. print(status)
  437. playlist = request.user.profile.playlists.get(playlist_id__exact=pl_id)
  438. new_playlists.append(playlist)
  439. num_playlists_initialized_in_db += 1
  440. done.append(playlist_link.strip())
  441. request.user.profile.manage_playlists_import_textarea = ""
  442. request.user.save()
  443. return HttpResponse(loader.get_template("intercooler/manage_playlists_import_results.html")
  444. .render(
  445. {"new_playlists": new_playlists,
  446. "old_playlists": old_playlists,
  447. "not_found_playlists": not_found_playlists,
  448. "num_playlists_already_in_db": num_playlists_already_in_db,
  449. "num_playlists_initialized_in_db": num_playlists_initialized_in_db,
  450. "num_playlists_not_found": num_playlists_not_found
  451. }))
  452. @login_required
  453. @require_POST
  454. def manage_create_playlist(request):
  455. print(request.POST)
  456. return HttpResponse("")
  457. @login_required
  458. def load_more_videos(request, playlist_id, page):
  459. playlist = request.user.profile.playlists.get(playlist_id=playlist_id)
  460. videos = playlist.videos.order_by("video_position")[50 * page:]
  461. return HttpResponse(loader.get_template("intercooler/videos.html")
  462. .render(
  463. {
  464. "playlist": playlist,
  465. "videos": videos,
  466. "page": page + 1}))
  467. @login_required
  468. @require_POST
  469. def update_playlist_settings(request, playlist_id):
  470. message_type = "success"
  471. message_content = "Saved!"
  472. if "user_label" in request.POST:
  473. playlist = request.user.profile.playlists.get(playlist_id=playlist_id)
  474. playlist.user_label = request.POST["user_label"]
  475. playlist.save(update_fields=['user_label'])
  476. return HttpResponse(loader.get_template("intercooler/messages.html")
  477. .render(
  478. {"message_type": message_type,
  479. "message_content": message_content}))
  480. details = {
  481. "title": request.POST['playlistTitle'],
  482. "description": request.POST['playlistDesc'],
  483. "privacyStatus": True if request.POST['playlistPrivacy'] == "Private" else False
  484. }
  485. status = Playlist.objects.updatePlaylistDetails(request.user, playlist_id, details)
  486. if status == -1:
  487. message_type = "error"
  488. message_content = "Could not save :("
  489. return HttpResponse(loader.get_template("intercooler/messages.html")
  490. .render(
  491. {"message_type": message_type,
  492. "message_content": message_content}))
  493. @login_required
  494. def update_playlist(request, playlist_id, type):
  495. playlist = request.user.profile.playlists.get(playlist_id=playlist_id)
  496. if type == "checkforupdates":
  497. print("Checking if playlist changed...")
  498. result = Playlist.objects.checkIfPlaylistChangedOnYT(request.user, playlist_id)
  499. if result[0] == 1: # full scan was done (full scan is done for a playlist if a week has passed)
  500. deleted_videos, unavailable_videos, added_videos = result[1:]
  501. print("CHANGES", deleted_videos, unavailable_videos, added_videos)
  502. # playlist_changed_text = ["The following modifications happened to this playlist on YouTube:"]
  503. if deleted_videos != 0 or unavailable_videos != 0 or added_videos != 0:
  504. pass
  505. # if added_videos > 0:
  506. # playlist_changed_text.append(f"{added_videos} new video(s) were added")
  507. # if deleted_videos > 0:
  508. # playlist_changed_text.append(f"{deleted_videos} video(s) were deleted")
  509. # if unavailable_videos > 0:
  510. # playlist_changed_text.append(f"{unavailable_videos} video(s) went private/unavailable")
  511. # playlist.playlist_changed_text = "\n".join(playlist_changed_text)
  512. # playlist.has_playlist_changed = True
  513. # playlist.save()
  514. else: # no updates found
  515. return HttpResponse("""
  516. <div id="checkforupdates" class="sticky-top" style="top: 0.5em;">
  517. <div class="alert alert-success alert-dismissible fade show visually-hidden" role="alert">
  518. No new updates!
  519. </div>
  520. </div>
  521. """)
  522. elif result[0] == -1: # playlist changed
  523. print("!!!Playlist changed")
  524. # current_playlist_vid_count = playlist.video_count
  525. # new_playlist_vid_count = result[1]
  526. # print(current_playlist_vid_count)
  527. # print(new_playlist_vid_count)
  528. # playlist.has_playlist_changed = True
  529. # playlist.save()
  530. # print(playlist.playlist_changed_text)
  531. else: # no updates found
  532. return HttpResponse("""
  533. <div id="checkforupdates" class="sticky-top" style="top: 0.5em;">
  534. <div class="alert alert-success alert-dismissible fade show visually-hidden sticky-top" role="alert" style="top: 0.5em;">
  535. No new updates!
  536. </div>
  537. </div>
  538. """)
  539. return HttpResponse(f"""
  540. <div hx-get="/playlist/{playlist_id}/update/auto" hx-trigger="load" hx-target="this" class="sticky-top" style="top: 0.5em;">
  541. <div class="alert alert-success alert-dismissible fade show" role="alert">
  542. <div class="d-flex justify-content-center" id="loading-sign">
  543. <img src="/static/svg-loaders/circles.svg" width="40" height="40">
  544. <h5 class="mt-2 ms-2">Changes detected on YouTube, updating playlist '{playlist.name}'...</h5>
  545. </div>
  546. </div>
  547. </div>
  548. """)
  549. if type == "manual":
  550. print("MANUAL")
  551. return HttpResponse(
  552. f"""<div hx-get="/playlist/{playlist_id}/update/auto" hx-trigger="load" hx-swap="outerHTML">
  553. <div class="d-flex justify-content-center mt-4 mb-3" id="loading-sign">
  554. <img src="/static/svg-loaders/circles.svg" width="40" height="40">
  555. <h5 class="mt-2 ms-2">Refreshing playlist '{playlist.name}', please wait!</h5>
  556. </div>
  557. </div>""")
  558. print("Attempting to update playlist")
  559. status, deleted_video_ids, unavailable_videos, added_videos = Playlist.objects.updatePlaylist(request.user,
  560. playlist_id)
  561. playlist = request.user.profile.playlists.get(playlist_id=playlist_id)
  562. if status == -1:
  563. playlist_name = playlist.name
  564. playlist.delete()
  565. return HttpResponse(
  566. f"""
  567. <div class="d-flex justify-content-center mt-4 mb-3" id="loading-sign">
  568. <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>
  569. </div>
  570. """)
  571. print("Updated playlist")
  572. playlist_changed_text = []
  573. if len(added_videos) != 0:
  574. playlist_changed_text.append(f"{len(added_videos)} added")
  575. for video in added_videos:
  576. playlist_changed_text.append(f"--> {video.name}")
  577. # if len(added_videos) > 3:
  578. # playlist_changed_text.append(f"+ {len(added_videos) - 3} more")
  579. if len(unavailable_videos) != 0:
  580. if len(playlist_changed_text) == 0:
  581. playlist_changed_text.append(f"{len(unavailable_videos)} went unavailable")
  582. else:
  583. playlist_changed_text.append(f"\n{len(unavailable_videos)} went unavailable")
  584. for video in unavailable_videos:
  585. playlist_changed_text.append(f"--> {video.name}")
  586. if len(deleted_video_ids) != 0:
  587. if len(playlist_changed_text) == 0:
  588. playlist_changed_text.append(f"{len(deleted_video_ids)} deleted")
  589. else:
  590. playlist_changed_text.append(f"\n{len(deleted_video_ids)} deleted")
  591. for video_id in deleted_video_ids:
  592. video = playlist.videos.get(video_id=video_id)
  593. playlist_changed_text.append(f"--> {video.name}")
  594. video.delete()
  595. if len(playlist_changed_text) == 0:
  596. playlist_changed_text = ["Successfully refreshed playlist! No new changes found!"]
  597. # return HttpResponse
  598. return HttpResponse(loader.get_template("intercooler/playlist_updates.html")
  599. .render(
  600. {"playlist_changed_text": "\n".join(playlist_changed_text),
  601. "playlist_id": playlist_id}))
  602. @login_required
  603. def view_playlist_settings(request, playlist_id):
  604. playlist = request.user.profile.playlists.get(playlist_id=playlist_id)
  605. return render(request, 'view_playlist_settings.html', {"playlist": playlist})
  606. def get_playlist_tags(request, playlist_id):
  607. playlist = request.user.profile.playlists.get(playlist_id=playlist_id)
  608. playlist_tags = playlist.tags.all()
  609. return HttpResponse(loader.get_template("intercooler/playlist_tags.html")
  610. .render(
  611. {"playlist_id": playlist_id,
  612. "playlist_tags": playlist_tags}))
  613. def get_unused_playlist_tags(request, playlist_id):
  614. playlist = request.user.profile.playlists.get(playlist_id=playlist_id)
  615. user_created_tags = Tag.objects.filter(created_by=request.user)
  616. playlist_tags = playlist.tags.all()
  617. unused_tags = user_created_tags.difference(playlist_tags)
  618. return HttpResponse(loader.get_template("intercooler/playlist_tags_unused.html")
  619. .render(
  620. {"unused_tags": unused_tags}))
  621. @login_required
  622. @require_POST
  623. def create_playlist_tag(request, playlist_id):
  624. tag_name = request.POST["createTagField"]
  625. if tag_name.lower() == 'Pick from existing unused tags'.lower():
  626. return HttpResponse("Can't use that! Try again >_<")
  627. playlist = request.user.profile.playlists.get(playlist_id=playlist_id)
  628. user_created_tags = Tag.objects.filter(created_by=request.user)
  629. if user_created_tags.filter(name__iexact=tag_name).count() == 0: # no tag found, so create it
  630. tag = Tag(name=tag_name, created_by=request.user)
  631. tag.save()
  632. # add it to playlist
  633. playlist.tags.add(tag)
  634. else:
  635. return HttpResponse("""
  636. Already created. Try Again >w<
  637. """)
  638. # playlist_tags = playlist.tags.all()
  639. # unused_tags = user_created_tags.difference(playlist_tags)
  640. return HttpResponse(f"""
  641. Created and Added!
  642. <span class="visually-hidden" hx-get="/playlist/{playlist_id}/get-tags" hx-trigger="load" hx-target="#playlist-tags"></span>
  643. """)
  644. @login_required
  645. @require_POST
  646. def add_playlist_tag(request, playlist_id):
  647. tag_name = request.POST["playlistTag"]
  648. if tag_name == 'Pick from existing unused tags':
  649. return HttpResponse("Pick something! >w<")
  650. playlist = request.user.profile.playlists.get(playlist_id=playlist_id)
  651. playlist_tags = playlist.tags.all()
  652. if playlist_tags.filter(name__iexact=tag_name).count() == 0: # tag not on this playlist, so add it
  653. tag = Tag.objects.filter(Q(created_by=request.user) & Q(name__iexact=tag_name)).first()
  654. # add it to playlist
  655. playlist.tags.add(tag)
  656. else:
  657. return HttpResponse("Already Added >w<")
  658. return HttpResponse(f"""
  659. Added!
  660. <span class="visually-hidden" hx-get="/playlist/{playlist_id}/get-tags" hx-trigger="load" hx-target="#playlist-tags"></span>
  661. """)
  662. @login_required
  663. @require_POST
  664. def remove_playlist_tag(request, playlist_id, tag_name):
  665. playlist = request.user.profile.playlists.get(playlist_id=playlist_id)
  666. playlist_tags = playlist.tags.all()
  667. if playlist_tags.filter(name__iexact=tag_name).count() != 0: # tag on this playlist, remove it it
  668. tag = Tag.objects.filter(Q(created_by=request.user) & Q(name__iexact=tag_name)).first()
  669. print("Removed tag", tag_name)
  670. # remove it from the playlist
  671. playlist.tags.remove(tag)
  672. else:
  673. return HttpResponse("Whoops >w<")
  674. return HttpResponse("")