views.py 42 KB

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