views.py 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826
  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. @login_required
  382. def manage_playlists(request):
  383. return render(request, "manage_playlists.html")
  384. @login_required
  385. def manage_view_page(request, page):
  386. if page == "import":
  387. return render(request, "manage_playlists_import.html",
  388. {"manage_playlists_import_textarea": request.user.profile.manage_playlists_import_textarea})
  389. elif page == "create":
  390. return render(request, "manage_playlists_create.html")
  391. else:
  392. return HttpResponse('Working on this!')
  393. @login_required
  394. @require_POST
  395. def manage_save(request, what):
  396. if what == "manage_playlists_import_textarea":
  397. request.user.profile.manage_playlists_import_textarea = request.POST["import-playlist-textarea"]
  398. request.user.save()
  399. return HttpResponse("")
  400. @login_required
  401. @require_POST
  402. def manage_import_playlists(request):
  403. playlist_links = request.POST["import-playlist-textarea"].replace(",", "").split("\n")
  404. num_playlists_already_in_db = 0
  405. num_playlists_initialized_in_db = 0
  406. num_playlists_not_found = 0
  407. new_playlists = []
  408. old_playlists = []
  409. not_found_playlists = []
  410. done = []
  411. for playlist_link in playlist_links:
  412. if playlist_link.strip() != "" and playlist_link.strip() not in done:
  413. pl_id = Playlist.objects.getPlaylistId(playlist_link.strip())
  414. if pl_id is None:
  415. num_playlists_not_found += 1
  416. continue
  417. status = Playlist.objects.initPlaylist(request.user, pl_id)
  418. if status == -1 or status == -2:
  419. print("\nNo such playlist found:", pl_id)
  420. num_playlists_not_found += 1
  421. not_found_playlists.append(playlist_link)
  422. elif status == -3:
  423. num_playlists_already_in_db += 1
  424. playlist = request.user.profile.playlists.get(playlist_id__exact=pl_id)
  425. old_playlists.append(playlist)
  426. else:
  427. print(status)
  428. playlist = request.user.profile.playlists.get(playlist_id__exact=pl_id)
  429. new_playlists.append(playlist)
  430. num_playlists_initialized_in_db += 1
  431. done.append(playlist_link.strip())
  432. request.user.profile.manage_playlists_import_textarea = ""
  433. request.user.save()
  434. return HttpResponse(loader.get_template("intercooler/manage_playlists_import_results.html")
  435. .render(
  436. {"new_playlists": new_playlists,
  437. "old_playlists": old_playlists,
  438. "not_found_playlists": not_found_playlists,
  439. "num_playlists_already_in_db": num_playlists_already_in_db,
  440. "num_playlists_initialized_in_db": num_playlists_initialized_in_db,
  441. "num_playlists_not_found": num_playlists_not_found
  442. }))
  443. @login_required
  444. @require_POST
  445. def manage_create_playlist(request):
  446. print(request.POST)
  447. return HttpResponse("")
  448. @login_required
  449. def load_more_videos(request, playlist_id, page):
  450. playlist = request.user.profile.playlists.get(playlist_id=playlist_id)
  451. videos = playlist.videos.order_by("video_position")[50 * page:]
  452. return HttpResponse(loader.get_template("intercooler/videos.html")
  453. .render(
  454. {
  455. "playlist": playlist,
  456. "videos": videos,
  457. "page": page + 1}))
  458. @login_required
  459. @require_POST
  460. def update_playlist_settings(request, playlist_id):
  461. message_type = "success"
  462. message_content = "Saved!"
  463. if "user_label" in request.POST:
  464. playlist = request.user.profile.playlists.get(playlist_id=playlist_id)
  465. playlist.user_label = request.POST["user_label"]
  466. playlist.save(update_fields=['user_label'])
  467. return HttpResponse(loader.get_template("intercooler/messages.html")
  468. .render(
  469. {"message_type": message_type,
  470. "message_content": message_content}))
  471. details = {
  472. "title": request.POST['playlistTitle'],
  473. "description": request.POST['playlistDesc'],
  474. "privacyStatus": True if request.POST['playlistPrivacy'] == "Private" else False
  475. }
  476. status = Playlist.objects.updatePlaylistDetails(request.user, playlist_id, details)
  477. if status == -1:
  478. message_type = "error"
  479. message_content = "Could not save :("
  480. return HttpResponse(loader.get_template("intercooler/messages.html")
  481. .render(
  482. {"message_type": message_type,
  483. "message_content": message_content}))
  484. @login_required
  485. def update_playlist(request, playlist_id, type):
  486. playlist = request.user.profile.playlists.get(playlist_id=playlist_id)
  487. if type == "checkforupdates":
  488. print("Checking if playlist changed...")
  489. result = Playlist.objects.checkIfPlaylistChangedOnYT(request.user, playlist_id)
  490. if result[0] == 1: # full scan was done (full scan is done for a playlist if a week has passed)
  491. deleted_videos, unavailable_videos, added_videos = result[1:]
  492. print("CHANGES", deleted_videos, unavailable_videos, added_videos)
  493. # playlist_changed_text = ["The following modifications happened to this playlist on YouTube:"]
  494. if deleted_videos != 0 or unavailable_videos != 0 or added_videos != 0:
  495. pass
  496. # if added_videos > 0:
  497. # playlist_changed_text.append(f"{added_videos} new video(s) were added")
  498. # if deleted_videos > 0:
  499. # playlist_changed_text.append(f"{deleted_videos} video(s) were deleted")
  500. # if unavailable_videos > 0:
  501. # playlist_changed_text.append(f"{unavailable_videos} video(s) went private/unavailable")
  502. # playlist.playlist_changed_text = "\n".join(playlist_changed_text)
  503. # playlist.has_playlist_changed = True
  504. # playlist.save()
  505. else: # no updates found
  506. return HttpResponse("""
  507. <div id="checkforupdates" class="sticky-top" style="top: 0.5em;">
  508. <div class="alert alert-success alert-dismissible fade show visually-hidden" role="alert">
  509. No new updates!
  510. </div>
  511. <br>
  512. </div>
  513. """)
  514. elif result[0] == -1: # playlist changed
  515. print("!!!Playlist changed")
  516. # current_playlist_vid_count = playlist.video_count
  517. # new_playlist_vid_count = result[1]
  518. # print(current_playlist_vid_count)
  519. # print(new_playlist_vid_count)
  520. # playlist.has_playlist_changed = True
  521. # playlist.save()
  522. # print(playlist.playlist_changed_text)
  523. else: # no updates found
  524. return HttpResponse("""
  525. <div id="checkforupdates" class="sticky-top" style="top: 0.5em;">
  526. <div class="alert alert-success alert-dismissible fade show visually-hidden sticky-top" role="alert" style="top: 0.5em;">
  527. No new updates!
  528. </div>
  529. <br>
  530. </div>
  531. """)
  532. return HttpResponse(f"""
  533. <div hx-get="/playlist/{playlist_id}/update/auto" hx-trigger="load" hx-target="this" class="sticky-top" style="top: 0.5em;">
  534. <div class="alert alert-success alert-dismissible fade show" role="alert">
  535. <div class="d-flex justify-content-center" id="loading-sign">
  536. <img src="/static/svg-loaders/circles.svg" width="40" height="40">
  537. <h5 class="mt-2 ms-2">Changes detected on YouTube, updating playlist '{playlist.name}'...</h5>
  538. </div>
  539. </div>
  540. </div>
  541. """)
  542. if type == "manual":
  543. print("MANUAL")
  544. return HttpResponse(
  545. f"""<div hx-get="/playlist/{playlist_id}/update/auto" hx-trigger="load" hx-swap="outerHTML">
  546. <div class="d-flex justify-content-center mt-4 mb-3" id="loading-sign">
  547. <img src="/static/svg-loaders/circles.svg" width="40" height="40">
  548. <h5 class="mt-2 ms-2">Refreshing playlist '{playlist.name}', please wait!</h5>
  549. </div>
  550. </div>""")
  551. print("Attempting to update playlist")
  552. status, deleted_video_ids, unavailable_videos, added_videos = Playlist.objects.updatePlaylist(request.user,
  553. playlist_id)
  554. playlist = request.user.profile.playlists.get(playlist_id=playlist_id)
  555. if status == -1:
  556. playlist_name = playlist.name
  557. playlist.delete()
  558. return HttpResponse(
  559. f"""
  560. <div class="d-flex justify-content-center mt-4 mb-3" id="loading-sign">
  561. <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>
  562. </div>
  563. """)
  564. print("Updated playlist")
  565. playlist_changed_text = []
  566. if len(added_videos) != 0:
  567. playlist_changed_text.append(f"{len(added_videos)} added")
  568. for video in added_videos:
  569. playlist_changed_text.append(f"--> {video.name}")
  570. # if len(added_videos) > 3:
  571. # playlist_changed_text.append(f"+ {len(added_videos) - 3} more")
  572. if len(unavailable_videos) != 0:
  573. if len(playlist_changed_text) == 0:
  574. playlist_changed_text.append(f"{len(unavailable_videos)} went unavailable")
  575. else:
  576. playlist_changed_text.append(f"\n{len(unavailable_videos)} went unavailable")
  577. for video in unavailable_videos:
  578. playlist_changed_text.append(f"--> {video.name}")
  579. if len(deleted_video_ids) != 0:
  580. if len(playlist_changed_text) == 0:
  581. playlist_changed_text.append(f"{len(deleted_video_ids)} deleted")
  582. else:
  583. playlist_changed_text.append(f"\n{len(deleted_video_ids)} deleted")
  584. for video_id in deleted_video_ids:
  585. video = playlist.videos.get(video_id=video_id)
  586. playlist_changed_text.append(f"--> {video.name}")
  587. video.delete()
  588. if len(playlist_changed_text) == 0:
  589. playlist_changed_text = ["Successfully refreshed playlist! No new changes found!"]
  590. # return HttpResponse
  591. return HttpResponse(loader.get_template("intercooler/playlist_updates.html")
  592. .render(
  593. {"playlist_changed_text": "\n".join(playlist_changed_text),
  594. "playlist_id": playlist_id}))
  595. @login_required
  596. def view_playlist_settings(request, playlist_id):
  597. playlist = request.user.profile.playlists.get(playlist_id=playlist_id)
  598. return render(request, 'view_playlist_settings.html', {"playlist": playlist})
  599. def get_playlist_tags(request, playlist_id):
  600. playlist = request.user.profile.playlists.get(playlist_id=playlist_id)
  601. playlist_tags = playlist.tags.all()
  602. return HttpResponse(loader.get_template("intercooler/playlist_tags.html")
  603. .render(
  604. {"playlist_id": playlist_id,
  605. "playlist_tags": playlist_tags}))
  606. def get_unused_playlist_tags(request, playlist_id):
  607. playlist = request.user.profile.playlists.get(playlist_id=playlist_id)
  608. user_created_tags = Tag.objects.filter(created_by=request.user)
  609. playlist_tags = playlist.tags.all()
  610. unused_tags = user_created_tags.difference(playlist_tags)
  611. return HttpResponse(loader.get_template("intercooler/playlist_tags_unused.html")
  612. .render(
  613. {"unused_tags": unused_tags}))
  614. @login_required
  615. @require_POST
  616. def create_playlist_tag(request, playlist_id):
  617. tag_name = request.POST["createTagField"]
  618. if tag_name.lower() == 'Pick from existing unused tags'.lower():
  619. return HttpResponse("Can't use that! Try again >_<")
  620. playlist = request.user.profile.playlists.get(playlist_id=playlist_id)
  621. user_created_tags = Tag.objects.filter(created_by=request.user)
  622. if user_created_tags.filter(name__iexact=tag_name).count() == 0: # no tag found, so create it
  623. tag = Tag(name=tag_name, created_by=request.user)
  624. tag.save()
  625. # add it to playlist
  626. playlist.tags.add(tag)
  627. else:
  628. return HttpResponse("""
  629. Already created. Try Again >w<
  630. """)
  631. #playlist_tags = playlist.tags.all()
  632. #unused_tags = user_created_tags.difference(playlist_tags)
  633. return HttpResponse(f"""
  634. Created and Added!
  635. <span class="visually-hidden" hx-get="/playlist/{playlist_id}/get-tags" hx-trigger="load" hx-target="#playlist-tags"></span>
  636. """)
  637. @login_required
  638. @require_POST
  639. def add_playlist_tag(request, playlist_id):
  640. tag_name = request.POST["playlistTag"]
  641. if tag_name == 'Pick from existing unused tags':
  642. return HttpResponse("Pick something! >w<")
  643. playlist = request.user.profile.playlists.get(playlist_id=playlist_id)
  644. playlist_tags = playlist.tags.all()
  645. if playlist_tags.filter(name__iexact=tag_name).count() == 0: # tag not on this playlist, so add it
  646. tag = Tag.objects.filter(Q(created_by=request.user) & Q(name__iexact=tag_name)).first()
  647. # add it to playlist
  648. playlist.tags.add(tag)
  649. else:
  650. return HttpResponse("Already Added >w<")
  651. return HttpResponse(f"""
  652. Added!
  653. <span class="visually-hidden" hx-get="/playlist/{playlist_id}/get-tags" hx-trigger="load" hx-target="#playlist-tags"></span>
  654. """)
  655. @login_required
  656. @require_POST
  657. def remove_playlist_tag(request, playlist_id, tag_name):
  658. playlist = request.user.profile.playlists.get(playlist_id=playlist_id)
  659. playlist_tags = playlist.tags.all()
  660. if playlist_tags.filter(name__iexact=tag_name).count() != 0: # tag on this playlist, remove it it
  661. tag = Tag.objects.filter(Q(created_by=request.user) & Q(name__iexact=tag_name)).first()
  662. print("Removed tag", tag_name)
  663. # remove it from the playlist
  664. playlist.tags.remove(tag)
  665. else:
  666. return HttpResponse("Whoops >w<")
  667. return HttpResponse("")