views.py 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018
  1. import datetime
  2. import random
  3. import humanize
  4. import pytz
  5. from django.db.models import Q
  6. from django.http import HttpResponse, HttpResponseRedirect
  7. from django.shortcuts import render, redirect, get_object_or_404
  8. import apps
  9. from apps.main.models import Playlist, Tag
  10. from django.contrib.auth.decorators import login_required # redirects user to settings.LOGIN_URL
  11. from allauth.socialaccount.models import SocialToken
  12. from django.views.decorators.http import require_POST
  13. from django.contrib import messages
  14. from django.template import loader
  15. from .util import *
  16. # Create your views here.
  17. @login_required
  18. def home(request):
  19. user_profile = request.user.profile
  20. user_playlists = user_profile.playlists.filter(Q(is_in_db=True) & Q(num_of_accesses__gt=0)).order_by(
  21. "-num_of_accesses")
  22. watching = user_profile.playlists.filter(Q(marked_as="watching") & Q(is_in_db=True)).order_by("-num_of_accesses")
  23. recently_accessed_playlists = user_profile.playlists.filter(is_in_db=True).filter(
  24. updated_at__gt=user_profile.updated_at).order_by("-updated_at")[:6]
  25. recently_added_playlists = user_profile.playlists.filter(is_in_db=True).order_by("-created_at")[:6]
  26. #### FOR NEWLY JOINED USERS ######
  27. channel_found = True
  28. if user_profile.show_import_page:
  29. """
  30. Logic:
  31. show_import_page is True by default. When a user logs in for the first time (infact anytime), google
  32. redirects them to 'home' url. Since, show_import_page is True by default, the user is then redirected
  33. from 'home' to 'import_in_progress' url
  34. show_import_page is only set false in the import_in_progress.html page, i.e when user cancels YT import
  35. """
  36. # user_profile.show_import_page = False
  37. if user_profile.access_token.strip() == "" or user_profile.refresh_token.strip() == "":
  38. user_social_token = SocialToken.objects.get(account__user=request.user)
  39. user_profile.access_token = user_social_token.token
  40. user_profile.refresh_token = user_social_token.token_secret
  41. user_profile.expires_at = user_social_token.expires_at
  42. request.user.save()
  43. if user_profile.imported_yt_playlists:
  44. user_profile.show_import_page = False # after user imports all their YT playlists no need to show_import_page again
  45. user_profile.save(update_fields=['show_import_page'])
  46. return render(request, "home.html", {"import_successful": True})
  47. return render(request, "import_in_progress.html")
  48. # if Playlist.objects.getUserYTChannelID(request.user) == -1: # user channel not found
  49. # channel_found = False
  50. # else:
  51. # Playlist.objects.initPlaylist(request.user, None) # get all playlists from user's YT channel
  52. # return render(request, "home.html", {"import_successful": True})
  53. ##################################
  54. if request.method == "POST":
  55. print(request.POST)
  56. if Playlist.objects.initPlaylist(request.user, request.POST['playlist-id'].strip()) == -1:
  57. print("No such playlist found.")
  58. playlist = []
  59. videos = []
  60. else:
  61. playlist = user_profile.playlists.get(playlist_id__exact=request.POST['playlist-id'].strip())
  62. videos = playlist.videos.all()
  63. else: # GET request
  64. videos = []
  65. playlist = []
  66. print("TESTING")
  67. return render(request, 'home.html', {"channel_found": channel_found,
  68. "playlist": playlist,
  69. "videos": videos,
  70. "user_playlists": user_playlists,
  71. "watching": watching,
  72. "recently_accessed_playlists": recently_accessed_playlists,
  73. "recently_added_playlists": recently_added_playlists})
  74. @login_required
  75. def view_video(request, playlist_id, video_id):
  76. video = request.user.profile.playlists.get(playlist_id=playlist_id).videos.get(video_id=video_id)
  77. print(video.name)
  78. return HttpResponse(loader.get_template("intercooler/video_details.html").render({"video": video}))
  79. @login_required
  80. def video_notes(request, playlist_id, video_id):
  81. video = request.user.profile.playlists.get(playlist_id=playlist_id).videos.get(video_id=video_id)
  82. if request.method == "POST":
  83. if 'video-notes-text-area' in request.POST:
  84. video.user_notes = request.POST['video-notes-text-area']
  85. video.save()
  86. return HttpResponse(loader.get_template("intercooler/messages.html").render(
  87. {"message_type": "success", "message_content": "Saved!"}))
  88. else:
  89. print("GET VIDEO NOTES")
  90. return HttpResponse(loader.get_template("intercooler/video_notes.html").render({"video": video,
  91. "playlist_id": playlist_id}))
  92. @login_required
  93. def view_playlist(request, playlist_id):
  94. user_profile = request.user.profile
  95. user_owned_playlists = user_profile.playlists.filter(Q(is_user_owned=True) & Q(is_in_db=True))
  96. # specific playlist requested
  97. if user_profile.playlists.filter(Q(playlist_id=playlist_id) & Q(is_in_db=True)).count() != 0:
  98. playlist = user_profile.playlists.get(playlist_id__exact=playlist_id)
  99. playlist.num_of_accesses += 1
  100. playlist.save()
  101. else:
  102. messages.error(request, "No such playlist found!")
  103. return redirect('home')
  104. if playlist.has_new_updates:
  105. recently_updated_videos = playlist.videos.filter(video_details_modified=True)
  106. for video in recently_updated_videos:
  107. if video.video_details_modified_at + datetime.timedelta(hours=12) < datetime.datetime.now(
  108. pytz.utc): # expired
  109. video.video_details_modified = False
  110. video.save()
  111. if recently_updated_videos.count() == 0:
  112. playlist.has_new_updates = False
  113. playlist.save()
  114. videos = playlist.videos.order_by("video_position")
  115. user_created_tags = Tag.objects.filter(created_by=request.user)
  116. playlist_tags = playlist.tags.all()
  117. for tag in playlist_tags:
  118. tag.times_viewed += 1
  119. tag.save(update_fields=['times_viewed'])
  120. unused_tags = user_created_tags.difference(playlist_tags)
  121. all_videos_unavailable = False
  122. if playlist.videos.filter(Q(is_unavailable_on_yt=True) | Q(was_deleted_on_yt=True)).count() == playlist.videos.all().count():
  123. all_videos_unavailable = True
  124. return render(request, 'view_playlist.html', {"playlist": playlist,
  125. "playlist_tags": playlist_tags,
  126. "unused_tags": unused_tags,
  127. "videos": videos,
  128. "user_owned_playlists": user_owned_playlists,
  129. "watching_message": generateWatchingMessage(playlist),
  130. })
  131. @login_required
  132. def tagged_playlists(request, tag):
  133. tag = get_object_or_404(Tag, created_by=request.user, name=tag)
  134. playlists = tag.playlists.all()
  135. return render(request, 'all_playlists_with_tag.html', {"playlists": playlists, "tag": tag})
  136. @login_required
  137. def all_playlists(request, playlist_type):
  138. """
  139. Possible playlist types for marked_as attribute: (saved in database like this)
  140. "none", "watching", "plan-to-watch"
  141. """
  142. playlist_type = playlist_type.lower()
  143. if playlist_type == "" or playlist_type == "all":
  144. playlists = request.user.profile.playlists.all().filter(is_in_db=True)
  145. playlist_type_display = "All Playlists"
  146. elif playlist_type == "user-owned": # YT playlists owned by user
  147. playlists = request.user.profile.playlists.all().filter(Q(is_user_owned=True) & Q(is_in_db=True))
  148. playlist_type_display = "Your YouTube Playlists"
  149. elif playlist_type == "imported": # YT playlists (public) owned by others
  150. playlists = request.user.profile.playlists.all().filter(Q(is_user_owned=False) & Q(is_in_db=True))
  151. playlist_type_display = "Imported playlists"
  152. elif playlist_type == "favorites": # YT playlists (public) owned by others
  153. playlists = request.user.profile.playlists.all().filter(Q(is_favorite=True) & Q(is_in_db=True))
  154. playlist_type_display = "Favorites"
  155. elif playlist_type.lower() in ["watching", "plan-to-watch"]:
  156. playlists = request.user.profile.playlists.filter(Q(marked_as=playlist_type.lower()) & Q(is_in_db=True))
  157. playlist_type_display = playlist_type.lower().replace("-", " ")
  158. elif playlist_type.lower() == "home": # displays cards of all playlist types
  159. return render(request, 'playlists_home.html')
  160. elif playlist_type.lower() == "random": # randomize playlist
  161. if request.method == "POST":
  162. playlists_type = request.POST["playlistsType"]
  163. if playlists_type == "All":
  164. playlists = request.user.profile.playlists.all().filter(is_in_db=True)
  165. elif playlists_type == "Favorites":
  166. playlists = request.user.profile.playlists.all().filter(Q(is_favorite=True) & Q(is_in_db=True))
  167. elif playlists_type == "Watching":
  168. playlists = request.user.profile.playlists.filter(Q(marked_as="watching") & Q(is_in_db=True))
  169. elif playlists_type == "Plan to Watch":
  170. playlists = request.user.profile.playlists.filter(Q(marked_as="plan-to-watch") & Q(is_in_db=True))
  171. else:
  172. return redirect('/playlists/home')
  173. if playlists.count() == 0:
  174. messages.warning(request, f"No playlists in {playlists_type}")
  175. return redirect('/playlists/home')
  176. random_playlist = random.choice(playlists)
  177. return redirect(f'/playlist/{random_playlist.playlist_id}')
  178. return render(request, 'playlists_home.html')
  179. else:
  180. return redirect('home')
  181. return render(request, 'all_playlists.html', {"playlists": playlists,
  182. "playlist_type": playlist_type,
  183. "playlist_type_display": playlist_type_display})
  184. @login_required
  185. def all_videos(request, videos_type):
  186. """
  187. To implement this need to redesign the database
  188. Currently videos -> playlist -> user.profile
  189. Need to do
  190. user.profile <- videos <- playlistItem -> playlist
  191. many ways actually
  192. """
  193. videos_type = videos_type.lower()
  194. if videos_type == "" or videos_type == "all":
  195. playlists = request.user.profile.playlists.all().filter(is_in_db=True)
  196. videos_type_display = "All Videos"
  197. elif videos_type == "user-owned": # YT playlists owned by user
  198. playlists = request.user.profile.playlists.all().filter(Q(is_user_owned=True) & Q(is_in_db=True))
  199. videos_type_display = "All Videos in your YouTube Playlists"
  200. elif videos_type == "imported": # YT playlists (public) owned by others
  201. playlists = request.user.profile.playlists.all().filter(Q(is_user_owned=False) & Q(is_in_db=True))
  202. videos_type_display = "Imported YouTube Playlists Videos"
  203. elif videos_type == "favorites": # YT playlists (public) owned by others
  204. playlists = request.user.profile.playlists.all().filter(Q(is_favorite=True) & Q(is_in_db=True))
  205. videos_type_display = "Favorite Videos"
  206. elif videos_type == "watched": # YT playlists (public) owned by others
  207. playlists = request.user.profile.playlists.all().filter(Q(is_favorite=True) & Q(is_in_db=True))
  208. videos_type_display = "Watched Videos"
  209. elif videos_type == 'hidden-videos': # YT playlists (public) owned by others
  210. playlists = request.user.profile.playlists.all().filter(Q(is_favorite=True) & Q(is_in_db=True))
  211. videos_type_display = "Hidden Videos"
  212. elif videos_type.lower() == "home": # displays cards of all playlist types
  213. return render(request, 'videos_home.html')
  214. else:
  215. return redirect('home')
  216. return render(request, 'all_playlists.html', {"playlists": playlists,
  217. "videos_type": videos_type,
  218. "videos_type_display": videos_type_display})
  219. @login_required
  220. def order_playlist_by(request, playlist_id, order_by):
  221. playlist = request.user.profile.playlists.get(Q(playlist_id=playlist_id) & Q(is_in_db=True))
  222. display_text = "Nothing in this playlist! Add something!" # what to display when requested order/filter has no videws
  223. videos_details = ""
  224. if order_by == "all":
  225. videos = playlist.videos.order_by("video_position")
  226. elif order_by == "favorites":
  227. videos = playlist.videos.filter(is_favorite=True).order_by("video_position")
  228. videos_details = "Sorted by Favorites"
  229. display_text = "No favorites yet!"
  230. elif order_by == "popularity":
  231. videos_details = "Sorted by Popularity"
  232. videos = playlist.videos.order_by("-like_count")
  233. elif order_by == "date-published":
  234. videos_details = "Sorted by Date Published"
  235. videos = playlist.videos.order_by("-published_at")
  236. elif order_by == "views":
  237. videos_details = "Sorted by View Count"
  238. videos = playlist.videos.order_by("-view_count")
  239. elif order_by == "has-cc":
  240. videos_details = "Filtered by Has CC"
  241. videos = playlist.videos.filter(has_cc=True).order_by("video_position")
  242. display_text = "No videos in this playlist have CC :("
  243. elif order_by == "duration":
  244. videos_details = "Sorted by Video Duration"
  245. videos = playlist.videos.order_by("-duration_in_seconds")
  246. elif order_by == 'new-updates':
  247. videos = []
  248. videos_details = "Sorted by New Updates"
  249. display_text = "No new updates! Note that deleted videos will not show up here."
  250. if playlist.has_new_updates:
  251. recently_updated_videos = playlist.videos.filter(video_details_modified=True)
  252. for video in recently_updated_videos:
  253. if video.video_details_modified_at + datetime.timedelta(hours=12) < datetime.datetime.now(
  254. pytz.utc): # expired
  255. video.video_details_modified = False
  256. video.save()
  257. if recently_updated_videos.count() == 0:
  258. playlist.has_new_updates = False
  259. playlist.save()
  260. else:
  261. videos = recently_updated_videos.order_by("video_position")
  262. elif order_by == 'unavailable-videos':
  263. videos = playlist.videos.filter(Q(is_unavailable_on_yt=True) & Q(was_deleted_on_yt=True))
  264. videos_details = "Sorted by Unavailable Videos"
  265. display_text = "None of the videos in this playlist have gone unavailable... yet."
  266. else:
  267. return redirect('home')
  268. return HttpResponse(loader.get_template("intercooler/videos.html").render({"playlist": playlist,
  269. "videos": videos,
  270. "videos_details": videos_details,
  271. "display_text": display_text,
  272. "order_by": order_by}))
  273. @login_required
  274. def order_playlists_by(request, playlist_type, order_by):
  275. if playlist_type == "" or playlist_type.lower() == "all":
  276. playlists = request.user.profile.playlists.all()
  277. playlist_type_display = "All Playlists"
  278. elif playlist_type.lower() == "favorites":
  279. playlists = request.user.profile.playlists.filter(Q(is_favorite=True) & Q(is_in_db=True))
  280. playlist_type_display = "Favorites"
  281. elif playlist_type.lower() in ["watching", "plan-to-watch"]:
  282. playlists = request.user.profile.playlists.filter(Q(marked_as=playlist_type.lower()) & Q(is_in_db=True))
  283. playlist_type_display = "Watching"
  284. else:
  285. return redirect('home')
  286. if order_by == 'recently-accessed':
  287. playlists = playlists.order_by("-updated_at")
  288. elif order_by == 'playlist-duration-in-seconds':
  289. playlists = playlists.order_by("-playlist_duration_in_seconds")
  290. elif order_by == 'video-count':
  291. playlists = playlists.order_by("-video_count")
  292. return HttpResponse(loader.get_template("intercooler/playlists.html")
  293. .render({"playlists": playlists,
  294. "playlist_type_display": playlist_type_display,
  295. "playlist_type": playlist_type}))
  296. @login_required
  297. def mark_playlist_as(request, playlist_id, mark_as):
  298. playlist = request.user.profile.playlists.get(playlist_id=playlist_id)
  299. marked_as_response = '<span></span><meta http-equiv="refresh" content="0" />'
  300. if mark_as in ["watching", "on-hold", "plan-to-watch"]:
  301. playlist.marked_as = mark_as
  302. playlist.save()
  303. icon = ""
  304. if mark_as == "watching":
  305. icon = '<i class="fas fa-fire-alt me-2"></i>'
  306. elif mark_as == "plan-to-watch":
  307. icon = '<i class="fas fa-flag me-2"></i>'
  308. marked_as_response = f'<span class="badge bg-success text-white" >{icon}{mark_as}</span> <meta http-equiv="refresh" content="0" />'
  309. elif mark_as == "none":
  310. playlist.marked_as = mark_as
  311. playlist.save()
  312. elif mark_as == "favorite":
  313. if playlist.is_favorite:
  314. playlist.is_favorite = False
  315. playlist.save()
  316. return HttpResponse('<i class="far fa-star"></i>')
  317. else:
  318. playlist.is_favorite = True
  319. playlist.save()
  320. return HttpResponse('<i class="fas fa-star"></i>')
  321. else:
  322. return render('home')
  323. return HttpResponse(marked_as_response)
  324. @login_required
  325. def playlists_home(request):
  326. return render(request, 'playlists_home.html')
  327. @login_required
  328. @require_POST
  329. def delete_videos(request, playlist_id, command):
  330. video_ids = request.POST.getlist("video-id", default=[])
  331. if command == "confirm":
  332. print(video_ids)
  333. num_vids = len(video_ids)
  334. extra_text = " "
  335. if num_vids == 0:
  336. return HttpResponse("<h5>Select some videos first!</h5><hr>")
  337. elif num_vids == request.user.profile.playlists.get(playlist_id=playlist_id).videos.all().count():
  338. delete_text = "ALL VIDEOS"
  339. extra_text = " This will not delete the playlist itself, will only make the playlist empty. "
  340. else:
  341. delete_text = f"{num_vids} videos"
  342. return HttpResponse(
  343. f"""<h5>
  344. Are you sure you want to delete {delete_text} from your YouTube playlist?{extra_text}This cannot be undone.</h5>
  345. <button hx-post="/from/{playlist_id}/delete-videos/confirmed" hx-include="[id='video-checkboxes']" hx-target="#delete-videos-confirm-box" type="button" class="btn btn-outline-danger btn-sm" id="select-all-btn">Confirm</button>
  346. <hr>
  347. """)
  348. elif command == "confirmed":
  349. print(video_ids)
  350. return HttpResponse(
  351. f'<div class="spinner-border text-light" role="status" hx-post="/from/{playlist_id}/delete-videos/start" hx-trigger="load" hx-swap="outerHTML"></div>')
  352. elif command == "start":
  353. Playlist.objects.deletePlaylistItems(request.user, playlist_id, video_ids)
  354. # playlist = request.user.profile.playlists.get(playlist_id=playlist_id)
  355. # playlist.has_playlist_changed = True
  356. # playlist.save(update_fields=['has_playlist_changed'])
  357. return HttpResponse(f"""
  358. <h5 hx-get="/playlist/{playlist_id}/update/checkforupdates" hx-trigger="load delay:3s" hx-target="#checkforupdates">
  359. Done deleting videos from your playlist on YouTube. Playlist on UnTube will update soon.
  360. </h5>
  361. <hr>
  362. """)
  363. @login_required
  364. @require_POST
  365. def search_tagged_playlists(request, tag):
  366. tag = get_object_or_404(Tag, created_by=request.user, name=tag)
  367. playlists = tag.playlists.all()
  368. return HttpResponse("yay")
  369. @login_required
  370. @require_POST
  371. def search_playlists(request, playlist_type):
  372. # print(request.POST) # prints <QueryDict: {'search': ['aa']}>
  373. search_query = request.POST["search"]
  374. if playlist_type == "all":
  375. try:
  376. playlists = request.user.profile.playlists.all().filter(Q(name__startswith=search_query) & Q(is_in_db=True))
  377. except:
  378. playlists = request.user.profile.playlists.all()
  379. playlist_type_display = "All Playlists"
  380. elif playlist_type == "user-owned": # YT playlists owned by user
  381. try:
  382. playlists = request.user.profile.playlists.filter(
  383. Q(name__startswith=search_query) & Q(is_user_owned=True) & Q(is_in_db=True))
  384. except:
  385. playlists = request.user.profile.playlists.filter(Q(is_user_owned=True) & Q(is_in_db=True))
  386. playlist_type_display = "Your YouTube Playlists"
  387. elif playlist_type == "imported": # YT playlists (public) owned by others
  388. try:
  389. playlists = request.user.profile.playlists.filter(
  390. Q(name__startswith=search_query) & Q(is_user_owned=False) & Q(is_in_db=True))
  391. except:
  392. playlists = request.user.profile.playlists.filter(Q(is_user_owned=True) & Q(is_in_db=True))
  393. playlist_type_display = "Imported Playlists"
  394. elif playlist_type == "favorites": # YT playlists (public) owned by others
  395. try:
  396. playlists = request.user.profile.playlists.filter(
  397. Q(name__startswith=search_query) & Q(is_favorite=True) & Q(is_in_db=True))
  398. except:
  399. playlists = request.user.profile.playlists.filter(Q(is_favorite=True) & Q(is_in_db=True))
  400. playlist_type_display = "Your Favorites"
  401. elif playlist_type in ["watching", "plan-to-watch"]:
  402. try:
  403. playlists = request.user.profile.playlists.filter(
  404. Q(name__startswith=search_query) & Q(marked_as=playlist_type) & Q(is_in_db=True))
  405. except:
  406. playlists = request.user.profile.playlists.all().filter(Q(marked_as=playlist_type) & Q(is_in_db=True))
  407. playlist_type_display = playlist_type.replace("-", " ")
  408. return HttpResponse(loader.get_template("intercooler/playlists.html")
  409. .render({"playlists": playlists,
  410. "playlist_type_display": playlist_type_display,
  411. "playlist_type": playlist_type,
  412. "search_query": search_query}))
  413. #### MANAGE VIDEOS #####
  414. @login_required
  415. def mark_video_favortie(request, playlist_id, video_id):
  416. video = request.user.profile.playlists.get(playlist_id=playlist_id).videos.get(video_id=video_id)
  417. if video.is_favorite:
  418. video.is_favorite = False
  419. video.save(update_fields=['is_favorite'])
  420. return HttpResponse('<i class="far fa-heart"></i>')
  421. else:
  422. video.is_favorite = True
  423. video.save(update_fields=['is_favorite'])
  424. return HttpResponse('<i class="fas fa-heart" style="color: #fafa06"></i>')
  425. @login_required
  426. def mark_video_watched(request, playlist_id, video_id):
  427. playlist = request.user.profile.playlists.get(playlist_id=playlist_id)
  428. video = playlist.videos.get(video_id=video_id)
  429. if video.is_marked_as_watched:
  430. video.is_marked_as_watched = False
  431. video.save(update_fields=['is_marked_as_watched'])
  432. return HttpResponse(
  433. f'<i class="far fa-check-circle" hx-get="/playlist/{playlist_id}/get-watch-message" hx-trigger="load" hx-target="#playlist-watch-message"></i>')
  434. else:
  435. video.is_marked_as_watched = True
  436. video.save(update_fields=['is_marked_as_watched'])
  437. return HttpResponse(
  438. f'<i class="fas fa-check-circle" hx-get="/playlist/{playlist_id}/get-watch-message" hx-trigger="load" hx-target="#playlist-watch-message"></i>')
  439. generateWatchingMessage(playlist)
  440. ###########
  441. @login_required
  442. def search(request):
  443. if request.method == "GET":
  444. return render(request, 'search_untube_page.html')
  445. else:
  446. return render('home')
  447. @login_required
  448. @require_POST
  449. def search_UnTube(request):
  450. print(request.POST)
  451. search_query = request.POST["search"]
  452. all_playlists = request.user.profile.playlists.filter(is_in_db=True)
  453. if 'playlist-tags' in request.POST:
  454. tags = request.POST.getlist('playlist-tags')
  455. for tag in tags:
  456. all_playlists = all_playlists.filter(tags__name=tag)
  457. #all_playlists = all_playlists.filter(tags__name__in=tags)
  458. videos = []
  459. if request.POST['search-settings'] == 'starts-with':
  460. playlists = all_playlists.filter(name__istartswith=search_query) if search_query != "" else all_playlists.none()
  461. if search_query != "":
  462. for playlist in all_playlists:
  463. pl_videos = playlist.videos.filter(name__istartswith=search_query)
  464. if pl_videos.count() != 0:
  465. for v in pl_videos.all():
  466. videos.append(v)
  467. else:
  468. playlists = all_playlists.filter(name__icontains=search_query) if search_query != "" else all_playlists.none()
  469. if search_query != "":
  470. for playlist in all_playlists:
  471. pl_videos = playlist.videos.filter(name__icontains=search_query)
  472. if pl_videos.count() != 0:
  473. for v in pl_videos.all():
  474. videos.append(v)
  475. return HttpResponse(loader.get_template("intercooler/search_untube_results.html")
  476. .render({"playlists": playlists,
  477. "videos": videos,
  478. "videos_count": len(videos),
  479. "search_query": True if search_query != "" else False,
  480. "all_playlists": all_playlists}))
  481. @login_required
  482. def manage_playlists(request):
  483. return render(request, "manage_playlists.html")
  484. @login_required
  485. def manage_view_page(request, page):
  486. if page == "import":
  487. return render(request, "manage_playlists_import.html",
  488. {"manage_playlists_import_textarea": request.user.profile.manage_playlists_import_textarea})
  489. elif page == "create":
  490. return render(request, "manage_playlists_create.html")
  491. else:
  492. return HttpResponse('Working on this!')
  493. @login_required
  494. @require_POST
  495. def manage_save(request, what):
  496. if what == "manage_playlists_import_textarea":
  497. request.user.profile.manage_playlists_import_textarea = request.POST["import-playlist-textarea"]
  498. request.user.save()
  499. return HttpResponse("")
  500. @login_required
  501. @require_POST
  502. def manage_import_playlists(request):
  503. playlist_links = request.POST["import-playlist-textarea"].replace(",", "").split("\n")
  504. num_playlists_already_in_db = 0
  505. num_playlists_initialized_in_db = 0
  506. num_playlists_not_found = 0
  507. new_playlists = []
  508. old_playlists = []
  509. not_found_playlists = []
  510. done = []
  511. for playlist_link in playlist_links:
  512. if playlist_link.strip() != "" and playlist_link.strip() not in done:
  513. pl_id = Playlist.objects.getPlaylistId(playlist_link.strip())
  514. if pl_id is None:
  515. num_playlists_not_found += 1
  516. continue
  517. status = Playlist.objects.initPlaylist(request.user, pl_id)
  518. if status == -1 or status == -2:
  519. print("\nNo such playlist found:", pl_id)
  520. num_playlists_not_found += 1
  521. not_found_playlists.append(playlist_link)
  522. elif status == -3:
  523. num_playlists_already_in_db += 1
  524. playlist = request.user.profile.playlists.get(playlist_id__exact=pl_id)
  525. old_playlists.append(playlist)
  526. else:
  527. print(status)
  528. playlist = request.user.profile.playlists.get(playlist_id__exact=pl_id)
  529. new_playlists.append(playlist)
  530. num_playlists_initialized_in_db += 1
  531. done.append(playlist_link.strip())
  532. request.user.profile.manage_playlists_import_textarea = ""
  533. request.user.save()
  534. return HttpResponse(loader.get_template("intercooler/manage_playlists_import_results.html")
  535. .render(
  536. {"new_playlists": new_playlists,
  537. "old_playlists": old_playlists,
  538. "not_found_playlists": not_found_playlists,
  539. "num_playlists_already_in_db": num_playlists_already_in_db,
  540. "num_playlists_initialized_in_db": num_playlists_initialized_in_db,
  541. "num_playlists_not_found": num_playlists_not_found
  542. }))
  543. @login_required
  544. @require_POST
  545. def manage_create_playlist(request):
  546. print(request.POST)
  547. return HttpResponse("")
  548. @login_required
  549. def load_more_videos(request, playlist_id, order_by, page):
  550. playlist = request.user.profile.playlists.get(playlist_id=playlist_id)
  551. if order_by == "all":
  552. videos = playlist.videos.order_by("video_position")
  553. elif order_by == "favorites":
  554. videos = playlist.videos.filter(is_favorite=True).order_by("video_position")
  555. elif order_by == "popularity":
  556. videos = playlist.videos.order_by("-like_count")
  557. elif order_by == "date-published":
  558. videos = playlist.videos.order_by("-published_at")
  559. elif order_by == "views":
  560. videos = playlist.videos.order_by("-view_count")
  561. elif order_by == "has-cc":
  562. videos = playlist.videos.filter(has_cc=True).order_by("video_position")
  563. elif order_by == "duration":
  564. videos = playlist.videos.order_by("-duration_in_seconds")
  565. elif order_by == 'new-updates':
  566. videos = []
  567. if playlist.has_new_updates:
  568. recently_updated_videos = playlist.videos.filter(video_details_modified=True)
  569. for video in recently_updated_videos:
  570. if video.video_details_modified_at + datetime.timedelta(hours=12) < datetime.datetime.now(
  571. pytz.utc): # expired
  572. video.video_details_modified = False
  573. video.save()
  574. if recently_updated_videos.count() == 0:
  575. playlist.has_new_updates = False
  576. playlist.save()
  577. else:
  578. videos = recently_updated_videos.order_by("video_position")
  579. elif order_by == 'unavailable-videos':
  580. videos = playlist.videos.filter(Q(is_unavailable_on_yt=True) & Q(was_deleted_on_yt=True))
  581. return HttpResponse(loader.get_template("intercooler/videos.html")
  582. .render(
  583. {
  584. "playlist": playlist,
  585. "videos": videos[50 * page:], # only send 50 results per page
  586. "page": page + 1,
  587. "order_by": order_by}))
  588. @login_required
  589. @require_POST
  590. def update_playlist_settings(request, playlist_id):
  591. message_type = "success"
  592. message_content = "Saved!"
  593. if "user_label" in request.POST:
  594. playlist = request.user.profile.playlists.get(playlist_id=playlist_id)
  595. playlist.user_label = request.POST["user_label"]
  596. playlist.save(update_fields=['user_label'])
  597. return HttpResponse(loader.get_template("intercooler/messages.html")
  598. .render(
  599. {"message_type": message_type,
  600. "message_content": message_content}))
  601. valid_title = request.POST['playlistTitle'].replace(">", "greater than").replace("<", "less than")
  602. valid_description = request.POST['playlistDesc'].replace(">", "greater than").replace("<", "less than")
  603. details = {
  604. "title": valid_title,
  605. "description": valid_description,
  606. "privacyStatus": True if request.POST['playlistPrivacy'] == "Private" else False
  607. }
  608. status = Playlist.objects.updatePlaylistDetails(request.user, playlist_id, details)
  609. if status == -1:
  610. message_type = "danger"
  611. message_content = "Could not save :("
  612. return HttpResponse(loader.get_template("intercooler/messages.html")
  613. .render(
  614. {"message_type": message_type,
  615. "message_content": message_content}))
  616. @login_required
  617. def update_playlist(request, playlist_id, type):
  618. playlist = request.user.profile.playlists.get(playlist_id=playlist_id)
  619. if type == "checkforupdates":
  620. print("Checking if playlist changed...")
  621. result = Playlist.objects.checkIfPlaylistChangedOnYT(request.user, playlist_id)
  622. if result[0] == 1: # full scan was done (full scan is done for a playlist if a week has passed)
  623. deleted_videos, unavailable_videos, added_videos = result[1:]
  624. print("CHANGES", deleted_videos, unavailable_videos, added_videos)
  625. # playlist_changed_text = ["The following modifications happened to this playlist on YouTube:"]
  626. if deleted_videos != 0 or unavailable_videos != 0 or added_videos != 0:
  627. pass
  628. # if added_videos > 0:
  629. # playlist_changed_text.append(f"{added_videos} new video(s) were added")
  630. # if deleted_videos > 0:
  631. # playlist_changed_text.append(f"{deleted_videos} video(s) were deleted")
  632. # if unavailable_videos > 0:
  633. # playlist_changed_text.append(f"{unavailable_videos} video(s) went private/unavailable")
  634. # playlist.playlist_changed_text = "\n".join(playlist_changed_text)
  635. # playlist.has_playlist_changed = True
  636. # playlist.save()
  637. else: # no updates found
  638. return HttpResponse("""
  639. <div id="checkforupdates" class="sticky-top" style="top: 0.5em;">
  640. <div class="alert alert-success alert-dismissible fade show visually-hidden" role="alert">
  641. No new updates!
  642. </div>
  643. </div>
  644. """)
  645. elif result[0] == -1: # playlist changed
  646. print("!!!Playlist changed")
  647. # current_playlist_vid_count = playlist.video_count
  648. # new_playlist_vid_count = result[1]
  649. # print(current_playlist_vid_count)
  650. # print(new_playlist_vid_count)
  651. # playlist.has_playlist_changed = True
  652. # playlist.save()
  653. # print(playlist.playlist_changed_text)
  654. else: # no updates found
  655. return HttpResponse("""
  656. <div id="checkforupdates" class="sticky-top" style="top: 0.5em;">
  657. <div class="alert alert-success alert-dismissible fade show visually-hidden sticky-top" role="alert" style="top: 0.5em;">
  658. No new updates!
  659. </div>
  660. </div>
  661. """)
  662. return HttpResponse(f"""
  663. <div hx-get="/playlist/{playlist_id}/update/auto" hx-trigger="load" hx-target="this" class="sticky-top" style="top: 0.5em;">
  664. <div class="alert alert-success alert-dismissible fade show" role="alert">
  665. <div class="d-flex justify-content-center" id="loading-sign">
  666. <img src="/static/svg-loaders/circles.svg" width="40" height="40">
  667. <h5 class="mt-2 ms-2">Changes detected on YouTube, updating playlist '{playlist.name}'...</h5>
  668. </div>
  669. </div>
  670. </div>
  671. """)
  672. if type == "manual":
  673. print("MANUAL")
  674. return HttpResponse(
  675. f"""<div hx-get="/playlist/{playlist_id}/update/auto" hx-trigger="load" hx-swap="outerHTML">
  676. <div class="d-flex justify-content-center mt-4 mb-3" id="loading-sign">
  677. <img src="/static/svg-loaders/circles.svg" width="40" height="40">
  678. <h5 class="mt-2 ms-2">Refreshing playlist '{playlist.name}', please wait!</h5>
  679. </div>
  680. </div>""")
  681. print("Attempting to update playlist")
  682. status, deleted_video_ids, unavailable_videos, added_videos = Playlist.objects.updatePlaylist(request.user,
  683. playlist_id)
  684. playlist = request.user.profile.playlists.get(playlist_id=playlist_id)
  685. if status == -1:
  686. playlist_name = playlist.name
  687. playlist.delete()
  688. return HttpResponse(
  689. f"""
  690. <div class="d-flex justify-content-center mt-4 mb-3" id="loading-sign">
  691. <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>
  692. </div>
  693. """)
  694. print("Updated playlist")
  695. playlist_changed_text = []
  696. if len(added_videos) != 0:
  697. playlist_changed_text.append(f"{len(added_videos)} added")
  698. for video in added_videos:
  699. playlist_changed_text.append(f"--> {video.name}")
  700. # if len(added_videos) > 3:
  701. # playlist_changed_text.append(f"+ {len(added_videos) - 3} more")
  702. if len(unavailable_videos) != 0:
  703. if len(playlist_changed_text) == 0:
  704. playlist_changed_text.append(f"{len(unavailable_videos)} went unavailable")
  705. else:
  706. playlist_changed_text.append(f"\n{len(unavailable_videos)} went unavailable")
  707. for video in unavailable_videos:
  708. playlist_changed_text.append(f"--> {video.name}")
  709. if len(deleted_video_ids) != 0:
  710. if len(playlist_changed_text) == 0:
  711. playlist_changed_text.append(f"{len(deleted_video_ids)} deleted")
  712. else:
  713. playlist_changed_text.append(f"\n{len(deleted_video_ids)} deleted")
  714. for video_id in deleted_video_ids:
  715. video = playlist.videos.get(video_id=video_id)
  716. playlist_changed_text.append(f"--> {video.name}")
  717. video.delete()
  718. if len(playlist_changed_text) == 0:
  719. playlist_changed_text = ["Successfully refreshed playlist! No new changes found!"]
  720. # return HttpResponse
  721. return HttpResponse(loader.get_template("intercooler/playlist_updates.html")
  722. .render(
  723. {"playlist_changed_text": "\n".join(playlist_changed_text),
  724. "playlist_id": playlist_id}))
  725. @login_required
  726. def view_playlist_settings(request, playlist_id):
  727. try:
  728. playlist = request.user.profile.playlists.get(playlist_id=playlist_id)
  729. except apps.main.models.Playlist.DoesNotExist:
  730. messages.error(request, "No such playlist found!")
  731. return redirect('home')
  732. return render(request, 'view_playlist_settings.html', {"playlist": playlist})
  733. @login_required
  734. def get_playlist_tags(request, playlist_id):
  735. playlist = request.user.profile.playlists.get(playlist_id=playlist_id)
  736. playlist_tags = playlist.tags.all()
  737. return HttpResponse(loader.get_template("intercooler/playlist_tags.html")
  738. .render(
  739. {"playlist_id": playlist_id,
  740. "playlist_tags": playlist_tags}))
  741. @login_required
  742. def get_unused_playlist_tags(request, playlist_id):
  743. playlist = request.user.profile.playlists.get(playlist_id=playlist_id)
  744. user_created_tags = Tag.objects.filter(created_by=request.user)
  745. playlist_tags = playlist.tags.all()
  746. unused_tags = user_created_tags.difference(playlist_tags)
  747. return HttpResponse(loader.get_template("intercooler/playlist_tags_unused.html")
  748. .render(
  749. {"unused_tags": unused_tags}))
  750. @login_required
  751. def get_watch_message(request, playlist_id):
  752. playlist = request.user.profile.playlists.get(playlist_id=playlist_id)
  753. return HttpResponse(loader.get_template("intercooler/playlist_watch_message.html")
  754. .render(
  755. {"playlist": playlist}))
  756. @login_required
  757. @require_POST
  758. def create_playlist_tag(request, playlist_id):
  759. tag_name = request.POST["createTagField"]
  760. if tag_name.lower() == 'Pick from existing unused tags'.lower():
  761. return HttpResponse("Can't use that! Try again >_<")
  762. playlist = request.user.profile.playlists.get(playlist_id=playlist_id)
  763. user_created_tags = Tag.objects.filter(created_by=request.user)
  764. if user_created_tags.filter(name__iexact=tag_name).count() == 0: # no tag found, so create it
  765. tag = Tag(name=tag_name, created_by=request.user)
  766. tag.save()
  767. # add it to playlist
  768. playlist.tags.add(tag)
  769. else:
  770. return HttpResponse("""
  771. Already created. Try Again >w<
  772. """)
  773. # playlist_tags = playlist.tags.all()
  774. # unused_tags = user_created_tags.difference(playlist_tags)
  775. return HttpResponse(f"""
  776. Created and Added!
  777. <span class="visually-hidden" hx-get="/playlist/{playlist_id}/get-tags" hx-trigger="load" hx-target="#playlist-tags"></span>
  778. """)
  779. @login_required
  780. @require_POST
  781. def add_playlist_tag(request, playlist_id):
  782. tag_name = request.POST["playlistTag"]
  783. if tag_name == 'Pick from existing unused tags':
  784. return HttpResponse("Pick something! >w<")
  785. playlist = request.user.profile.playlists.get(playlist_id=playlist_id)
  786. playlist_tags = playlist.tags.all()
  787. if playlist_tags.filter(name__iexact=tag_name).count() == 0: # tag not on this playlist, so add it
  788. tag = Tag.objects.filter(Q(created_by=request.user) & Q(name__iexact=tag_name)).first()
  789. # add it to playlist
  790. playlist.tags.add(tag)
  791. else:
  792. return HttpResponse("Already Added >w<")
  793. return HttpResponse(f"""
  794. Added!
  795. <span class="visually-hidden" hx-get="/playlist/{playlist_id}/get-tags" hx-trigger="load" hx-target="#playlist-tags"></span>
  796. """)
  797. @login_required
  798. @require_POST
  799. def remove_playlist_tag(request, playlist_id, tag_name):
  800. playlist = request.user.profile.playlists.get(playlist_id=playlist_id)
  801. playlist_tags = playlist.tags.all()
  802. if playlist_tags.filter(name__iexact=tag_name).count() != 0: # tag on this playlist, remove it it
  803. tag = Tag.objects.filter(Q(created_by=request.user) & Q(name__iexact=tag_name)).first()
  804. print("Removed tag", tag_name)
  805. # remove it from the playlist
  806. playlist.tags.remove(tag)
  807. else:
  808. return HttpResponse("Whoops >w<")
  809. return HttpResponse("")
  810. @login_required
  811. def delete_playlist(request, playlist_id):
  812. playlist = request.user.profile.playlists.get(playlist_id=playlist_id)
  813. if not playlist.is_user_owned: # if playlist trying to delete isn't user owned
  814. playlist.delete() # just delete it from untrue
  815. else:
  816. # delete it from YouTube first then from UnTube
  817. pass
  818. messages.success(request, "Successfully deleted playlist from UnTube.")
  819. return redirect('home')
  820. @login_required
  821. def reset_watched(request, playlist_id):
  822. playlist = request.user.profile.playlists.get(playlist_id=playlist_id)
  823. for video in playlist.videos.filter(Q(is_unavailable_on_yt=False) & Q(was_deleted_on_yt=False)):
  824. video.is_marked_as_watched = False
  825. video.save(update_fields=['is_marked_as_watched'])
  826. # messages.success(request, "Successfully marked all videos unwatched.")
  827. return redirect(f'/playlist/{playlist.playlist_id}')