views.py 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833
  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. marked_as_response = f'<span class="badge bg-success text-white" >{mark_as.replace("-", " ")}</span>'
  236. elif mark_as == "none":
  237. playlist.marked_as = mark_as
  238. playlist.save()
  239. elif mark_as == "favorite":
  240. if playlist.is_favorite:
  241. playlist.is_favorite = False
  242. playlist.save()
  243. return HttpResponse('<i class="far fa-star"></i>')
  244. else:
  245. playlist.is_favorite = True
  246. playlist.save()
  247. return HttpResponse('<i class="fas fa-star"></i>')
  248. else:
  249. return render('home')
  250. return HttpResponse(marked_as_response)
  251. @login_required
  252. def playlists_home(request):
  253. return render(request, 'playlists_home.html')
  254. @login_required
  255. @require_POST
  256. def delete_videos(request, playlist_id, command):
  257. video_ids = request.POST.getlist("video-id", default=[])
  258. if command == "confirm":
  259. print(video_ids)
  260. num_vids = len(video_ids)
  261. extra_text = " "
  262. if num_vids == 0:
  263. return HttpResponse("<h5>Select some videos first!</h5>")
  264. elif num_vids == request.user.profile.playlists.get(playlist_id=playlist_id).videos.all().count():
  265. delete_text = "ALL VIDEOS"
  266. extra_text = " This will not delete the playlist itself, will only make the playlist empty. "
  267. else:
  268. delete_text = f"{num_vids} videos"
  269. return HttpResponse(
  270. f"<h5>Are you sure you want to delete {delete_text} from your YouTube playlist?{extra_text}This cannot be undone.</h5>")
  271. elif command == "confirmed":
  272. print(video_ids)
  273. return HttpResponse(
  274. f'<div class="spinner-border text-light" role="status" hx-post="/from/{playlist_id}/delete-videos/start" hx-trigger="load" hx-swap="outerHTML"></div>')
  275. elif command == "start":
  276. Playlist.objects.deletePlaylistItems(request.user, playlist_id, video_ids)
  277. # playlist = request.user.profile.playlists.get(playlist_id=playlist_id)
  278. # playlist.has_playlist_changed = True
  279. # playlist.save(update_fields=['has_playlist_changed'])
  280. return HttpResponse(f"""
  281. <div hx-get="/playlist/{playlist_id}/update/checkforupdates" hx-trigger="load delay:4s" hx-target="#checkforupdates" class="sticky-top" style="top: 0.5rem;">
  282. Done! Playlist on UnTube will update in 3s...
  283. </div>
  284. """)
  285. @login_required
  286. @require_POST
  287. def search_tagged_playlists(request, tag):
  288. tag = get_object_or_404(Tag, created_by=request.user, name=tag)
  289. playlists = tag.playlists.all()
  290. return HttpResponse("yay")
  291. @login_required
  292. @require_POST
  293. def search_playlists(request, playlist_type):
  294. # print(request.POST) # prints <QueryDict: {'search': ['aa']}>
  295. search_query = request.POST["search"]
  296. if playlist_type == "all":
  297. try:
  298. playlists = request.user.profile.playlists.all().filter(Q(name__startswith=search_query) & Q(is_in_db=True))
  299. except:
  300. playlists = request.user.profile.playlists.all()
  301. playlist_type_display = "All Playlists"
  302. elif playlist_type == "user-owned": # YT playlists owned by user
  303. try:
  304. playlists = request.user.profile.playlists.filter(
  305. Q(name__startswith=search_query) & Q(is_user_owned=True) & Q(is_in_db=True))
  306. except:
  307. playlists = request.user.profile.playlists.filter(Q(is_user_owned=True) & Q(is_in_db=True))
  308. playlist_type_display = "Your YouTube Playlists"
  309. elif playlist_type == "imported": # YT playlists (public) owned by others
  310. try:
  311. playlists = request.user.profile.playlists.filter(
  312. Q(name__startswith=search_query) & Q(is_user_owned=False) & Q(is_in_db=True))
  313. except:
  314. playlists = request.user.profile.playlists.filter(Q(is_user_owned=True) & Q(is_in_db=True))
  315. playlist_type_display = "Imported Playlists"
  316. elif playlist_type == "favorites": # YT playlists (public) owned by others
  317. try:
  318. playlists = request.user.profile.playlists.filter(
  319. Q(name__startswith=search_query) & Q(is_favorite=True) & Q(is_in_db=True))
  320. except:
  321. playlists = request.user.profile.playlists.filter(Q(is_favorite=True) & Q(is_in_db=True))
  322. playlist_type_display = "Your Favorites"
  323. elif playlist_type in ["watching", "plan-to-watch"]:
  324. try:
  325. playlists = request.user.profile.playlists.filter(
  326. Q(name__startswith=search_query) & Q(marked_as=playlist_type) & Q(is_in_db=True))
  327. except:
  328. playlists = request.user.profile.playlists.all().filter(Q(marked_as=playlist_type) & Q(is_in_db=True))
  329. playlist_type_display = playlist_type.replace("-", " ")
  330. return HttpResponse(loader.get_template("intercooler/playlists.html")
  331. .render({"playlists": playlists,
  332. "playlist_type_display": playlist_type_display,
  333. "playlist_type": playlist_type,
  334. "search_query": search_query}))
  335. #### MANAGE VIDEOS #####
  336. def mark_video_favortie(request, playlist_id, video_id):
  337. video = request.user.profile.playlists.get(playlist_id=playlist_id).videos.get(video_id=video_id)
  338. if video.is_favorite:
  339. video.is_favorite = False
  340. video.save()
  341. return HttpResponse('<i class="far fa-heart"></i>')
  342. else:
  343. video.is_favorite = True
  344. video.save()
  345. return HttpResponse('<i class="fas fa-heart"></i>')
  346. ###########
  347. @login_required
  348. def search(request):
  349. if request.method == "GET":
  350. return render(request, 'search_untube_page.html')
  351. else:
  352. return render('home')
  353. @login_required
  354. @require_POST
  355. def search_UnTube(request):
  356. print(request.POST)
  357. search_query = request.POST["search"]
  358. all_playlists = request.user.profile.playlists.filter(is_in_db=True)
  359. if 'playlist-tags' in request.POST:
  360. tags = request.POST.getlist('playlist-tags')
  361. all_playlists = all_playlists.filter(tags__name__in=tags)
  362. videos = []
  363. if request.POST['search-settings'] == 'starts-with':
  364. playlists = all_playlists.filter(name__istartswith=search_query) if search_query != "" else all_playlists.none()
  365. if search_query != "":
  366. for playlist in all_playlists:
  367. pl_videos = playlist.videos.filter(name__istartswith=search_query)
  368. if pl_videos.count() != 0:
  369. for v in pl_videos.all():
  370. videos.append(v)
  371. else:
  372. playlists = all_playlists.filter(name__icontains=search_query) if search_query != "" else all_playlists.none()
  373. if search_query != "":
  374. for playlist in all_playlists:
  375. pl_videos = playlist.videos.filter(name__icontains=search_query)
  376. if pl_videos.count() != 0:
  377. for v in pl_videos.all():
  378. videos.append(v)
  379. return HttpResponse(loader.get_template("intercooler/search_untube_results.html")
  380. .render({"playlists": playlists,
  381. "videos": videos,
  382. "videos_count": len(videos),
  383. "search_query": True if search_query != "" else False,
  384. "all_playlists": all_playlists}))
  385. @login_required
  386. def manage_playlists(request):
  387. return render(request, "manage_playlists.html")
  388. @login_required
  389. def manage_view_page(request, page):
  390. if page == "import":
  391. return render(request, "manage_playlists_import.html",
  392. {"manage_playlists_import_textarea": request.user.profile.manage_playlists_import_textarea})
  393. elif page == "create":
  394. return render(request, "manage_playlists_create.html")
  395. else:
  396. return HttpResponse('Working on this!')
  397. @login_required
  398. @require_POST
  399. def manage_save(request, what):
  400. if what == "manage_playlists_import_textarea":
  401. request.user.profile.manage_playlists_import_textarea = request.POST["import-playlist-textarea"]
  402. request.user.save()
  403. return HttpResponse("")
  404. @login_required
  405. @require_POST
  406. def manage_import_playlists(request):
  407. playlist_links = request.POST["import-playlist-textarea"].replace(",", "").split("\n")
  408. num_playlists_already_in_db = 0
  409. num_playlists_initialized_in_db = 0
  410. num_playlists_not_found = 0
  411. new_playlists = []
  412. old_playlists = []
  413. not_found_playlists = []
  414. done = []
  415. for playlist_link in playlist_links:
  416. if playlist_link.strip() != "" and playlist_link.strip() not in done:
  417. pl_id = Playlist.objects.getPlaylistId(playlist_link.strip())
  418. if pl_id is None:
  419. num_playlists_not_found += 1
  420. continue
  421. status = Playlist.objects.initPlaylist(request.user, pl_id)
  422. if status == -1 or status == -2:
  423. print("\nNo such playlist found:", pl_id)
  424. num_playlists_not_found += 1
  425. not_found_playlists.append(playlist_link)
  426. elif status == -3:
  427. num_playlists_already_in_db += 1
  428. playlist = request.user.profile.playlists.get(playlist_id__exact=pl_id)
  429. old_playlists.append(playlist)
  430. else:
  431. print(status)
  432. playlist = request.user.profile.playlists.get(playlist_id__exact=pl_id)
  433. new_playlists.append(playlist)
  434. num_playlists_initialized_in_db += 1
  435. done.append(playlist_link.strip())
  436. request.user.profile.manage_playlists_import_textarea = ""
  437. request.user.save()
  438. return HttpResponse(loader.get_template("intercooler/manage_playlists_import_results.html")
  439. .render(
  440. {"new_playlists": new_playlists,
  441. "old_playlists": old_playlists,
  442. "not_found_playlists": not_found_playlists,
  443. "num_playlists_already_in_db": num_playlists_already_in_db,
  444. "num_playlists_initialized_in_db": num_playlists_initialized_in_db,
  445. "num_playlists_not_found": num_playlists_not_found
  446. }))
  447. @login_required
  448. @require_POST
  449. def manage_create_playlist(request):
  450. print(request.POST)
  451. return HttpResponse("")
  452. @login_required
  453. def load_more_videos(request, playlist_id, page):
  454. playlist = request.user.profile.playlists.get(playlist_id=playlist_id)
  455. videos = playlist.videos.order_by("video_position")[50 * page:]
  456. return HttpResponse(loader.get_template("intercooler/videos.html")
  457. .render(
  458. {
  459. "playlist": playlist,
  460. "videos": videos,
  461. "page": page + 1}))
  462. @login_required
  463. @require_POST
  464. def update_playlist_settings(request, playlist_id):
  465. message_type = "success"
  466. message_content = "Saved!"
  467. if "user_label" in request.POST:
  468. playlist = request.user.profile.playlists.get(playlist_id=playlist_id)
  469. playlist.user_label = request.POST["user_label"]
  470. playlist.save(update_fields=['user_label'])
  471. return HttpResponse(loader.get_template("intercooler/messages.html")
  472. .render(
  473. {"message_type": message_type,
  474. "message_content": message_content}))
  475. details = {
  476. "title": request.POST['playlistTitle'],
  477. "description": request.POST['playlistDesc'],
  478. "privacyStatus": True if request.POST['playlistPrivacy'] == "Private" else False
  479. }
  480. status = Playlist.objects.updatePlaylistDetails(request.user, playlist_id, details)
  481. if status == -1:
  482. message_type = "error"
  483. message_content = "Could not save :("
  484. return HttpResponse(loader.get_template("intercooler/messages.html")
  485. .render(
  486. {"message_type": message_type,
  487. "message_content": message_content}))
  488. @login_required
  489. def update_playlist(request, playlist_id, type):
  490. playlist = request.user.profile.playlists.get(playlist_id=playlist_id)
  491. if type == "checkforupdates":
  492. print("Checking if playlist changed...")
  493. result = Playlist.objects.checkIfPlaylistChangedOnYT(request.user, playlist_id)
  494. if result[0] == 1: # full scan was done (full scan is done for a playlist if a week has passed)
  495. deleted_videos, unavailable_videos, added_videos = result[1:]
  496. print("CHANGES", deleted_videos, unavailable_videos, added_videos)
  497. # playlist_changed_text = ["The following modifications happened to this playlist on YouTube:"]
  498. if deleted_videos != 0 or unavailable_videos != 0 or added_videos != 0:
  499. pass
  500. # if added_videos > 0:
  501. # playlist_changed_text.append(f"{added_videos} new video(s) were added")
  502. # if deleted_videos > 0:
  503. # playlist_changed_text.append(f"{deleted_videos} video(s) were deleted")
  504. # if unavailable_videos > 0:
  505. # playlist_changed_text.append(f"{unavailable_videos} video(s) went private/unavailable")
  506. # playlist.playlist_changed_text = "\n".join(playlist_changed_text)
  507. # playlist.has_playlist_changed = True
  508. # playlist.save()
  509. else: # no updates found
  510. return HttpResponse("""
  511. <div id="checkforupdates" class="sticky-top" style="top: 0.5em;">
  512. <div class="alert alert-success alert-dismissible fade show visually-hidden" role="alert">
  513. No new updates!
  514. </div>
  515. <br>
  516. </div>
  517. """)
  518. elif result[0] == -1: # playlist changed
  519. print("!!!Playlist changed")
  520. # current_playlist_vid_count = playlist.video_count
  521. # new_playlist_vid_count = result[1]
  522. # print(current_playlist_vid_count)
  523. # print(new_playlist_vid_count)
  524. # playlist.has_playlist_changed = True
  525. # playlist.save()
  526. # print(playlist.playlist_changed_text)
  527. else: # no updates found
  528. return HttpResponse("""
  529. <div id="checkforupdates" class="sticky-top" style="top: 0.5em;">
  530. <div class="alert alert-success alert-dismissible fade show visually-hidden sticky-top" role="alert" style="top: 0.5em;">
  531. No new updates!
  532. </div>
  533. <br>
  534. </div>
  535. """)
  536. return HttpResponse(f"""
  537. <div hx-get="/playlist/{playlist_id}/update/auto" hx-trigger="load" hx-target="this" class="sticky-top" style="top: 0.5em;">
  538. <div class="alert alert-success alert-dismissible fade show" role="alert">
  539. <div class="d-flex justify-content-center" id="loading-sign">
  540. <img src="/static/svg-loaders/circles.svg" width="40" height="40">
  541. <h5 class="mt-2 ms-2">Changes detected on YouTube, updating playlist '{playlist.name}'...</h5>
  542. </div>
  543. </div>
  544. </div>
  545. """)
  546. if type == "manual":
  547. print("MANUAL")
  548. return HttpResponse(
  549. f"""<div hx-get="/playlist/{playlist_id}/update/auto" hx-trigger="load" hx-swap="outerHTML">
  550. <div class="d-flex justify-content-center mt-4 mb-3" id="loading-sign">
  551. <img src="/static/svg-loaders/circles.svg" width="40" height="40">
  552. <h5 class="mt-2 ms-2">Refreshing playlist '{playlist.name}', please wait!</h5>
  553. </div>
  554. </div>""")
  555. print("Attempting to update playlist")
  556. status, deleted_video_ids, unavailable_videos, added_videos = Playlist.objects.updatePlaylist(request.user,
  557. playlist_id)
  558. playlist = request.user.profile.playlists.get(playlist_id=playlist_id)
  559. if status == -1:
  560. playlist_name = playlist.name
  561. playlist.delete()
  562. return HttpResponse(
  563. f"""
  564. <div class="d-flex justify-content-center mt-4 mb-3" id="loading-sign">
  565. <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>
  566. </div>
  567. """)
  568. print("Updated playlist")
  569. playlist_changed_text = []
  570. if len(added_videos) != 0:
  571. playlist_changed_text.append(f"{len(added_videos)} added")
  572. for video in added_videos:
  573. playlist_changed_text.append(f"--> {video.name}")
  574. # if len(added_videos) > 3:
  575. # playlist_changed_text.append(f"+ {len(added_videos) - 3} more")
  576. if len(unavailable_videos) != 0:
  577. if len(playlist_changed_text) == 0:
  578. playlist_changed_text.append(f"{len(unavailable_videos)} went unavailable")
  579. else:
  580. playlist_changed_text.append(f"\n{len(unavailable_videos)} went unavailable")
  581. for video in unavailable_videos:
  582. playlist_changed_text.append(f"--> {video.name}")
  583. if len(deleted_video_ids) != 0:
  584. if len(playlist_changed_text) == 0:
  585. playlist_changed_text.append(f"{len(deleted_video_ids)} deleted")
  586. else:
  587. playlist_changed_text.append(f"\n{len(deleted_video_ids)} deleted")
  588. for video_id in deleted_video_ids:
  589. video = playlist.videos.get(video_id=video_id)
  590. playlist_changed_text.append(f"--> {video.name}")
  591. video.delete()
  592. if len(playlist_changed_text) == 0:
  593. playlist_changed_text = ["Successfully refreshed playlist! No new changes found!"]
  594. # return HttpResponse
  595. return HttpResponse(loader.get_template("intercooler/playlist_updates.html")
  596. .render(
  597. {"playlist_changed_text": "\n".join(playlist_changed_text),
  598. "playlist_id": playlist_id}))
  599. @login_required
  600. def view_playlist_settings(request, playlist_id):
  601. playlist = request.user.profile.playlists.get(playlist_id=playlist_id)
  602. return render(request, 'view_playlist_settings.html', {"playlist": playlist})
  603. def get_playlist_tags(request, playlist_id):
  604. playlist = request.user.profile.playlists.get(playlist_id=playlist_id)
  605. playlist_tags = playlist.tags.all()
  606. return HttpResponse(loader.get_template("intercooler/playlist_tags.html")
  607. .render(
  608. {"playlist_id": playlist_id,
  609. "playlist_tags": playlist_tags}))
  610. def get_unused_playlist_tags(request, playlist_id):
  611. playlist = request.user.profile.playlists.get(playlist_id=playlist_id)
  612. user_created_tags = Tag.objects.filter(created_by=request.user)
  613. playlist_tags = playlist.tags.all()
  614. unused_tags = user_created_tags.difference(playlist_tags)
  615. return HttpResponse(loader.get_template("intercooler/playlist_tags_unused.html")
  616. .render(
  617. {"unused_tags": unused_tags}))
  618. @login_required
  619. @require_POST
  620. def create_playlist_tag(request, playlist_id):
  621. tag_name = request.POST["createTagField"]
  622. if tag_name.lower() == 'Pick from existing unused tags'.lower():
  623. return HttpResponse("Can't use that! Try again >_<")
  624. playlist = request.user.profile.playlists.get(playlist_id=playlist_id)
  625. user_created_tags = Tag.objects.filter(created_by=request.user)
  626. if user_created_tags.filter(name__iexact=tag_name).count() == 0: # no tag found, so create it
  627. tag = Tag(name=tag_name, created_by=request.user)
  628. tag.save()
  629. # add it to playlist
  630. playlist.tags.add(tag)
  631. else:
  632. return HttpResponse("""
  633. Already created. Try Again >w<
  634. """)
  635. # playlist_tags = playlist.tags.all()
  636. # unused_tags = user_created_tags.difference(playlist_tags)
  637. return HttpResponse(f"""
  638. Created and Added!
  639. <span class="visually-hidden" hx-get="/playlist/{playlist_id}/get-tags" hx-trigger="load" hx-target="#playlist-tags"></span>
  640. """)
  641. @login_required
  642. @require_POST
  643. def add_playlist_tag(request, playlist_id):
  644. tag_name = request.POST["playlistTag"]
  645. if tag_name == 'Pick from existing unused tags':
  646. return HttpResponse("Pick something! >w<")
  647. playlist = request.user.profile.playlists.get(playlist_id=playlist_id)
  648. playlist_tags = playlist.tags.all()
  649. if playlist_tags.filter(name__iexact=tag_name).count() == 0: # tag not on this playlist, so add it
  650. tag = Tag.objects.filter(Q(created_by=request.user) & Q(name__iexact=tag_name)).first()
  651. # add it to playlist
  652. playlist.tags.add(tag)
  653. else:
  654. return HttpResponse("Already Added >w<")
  655. return HttpResponse(f"""
  656. Added!
  657. <span class="visually-hidden" hx-get="/playlist/{playlist_id}/get-tags" hx-trigger="load" hx-target="#playlist-tags"></span>
  658. """)
  659. @login_required
  660. @require_POST
  661. def remove_playlist_tag(request, playlist_id, tag_name):
  662. playlist = request.user.profile.playlists.get(playlist_id=playlist_id)
  663. playlist_tags = playlist.tags.all()
  664. if playlist_tags.filter(name__iexact=tag_name).count() != 0: # tag on this playlist, remove it it
  665. tag = Tag.objects.filter(Q(created_by=request.user) & Q(name__iexact=tag_name)).first()
  666. print("Removed tag", tag_name)
  667. # remove it from the playlist
  668. playlist.tags.remove(tag)
  669. else:
  670. return HttpResponse("Whoops >w<")
  671. return HttpResponse("")