views.py 38 KB

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