2
0

views.py 43 KB

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