2
0

views.py 42 KB

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