views.py 45 KB

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