2
0

views.py 44 KB

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