2
0

views.py 34 KB

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