views.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402
  1. from django.db.models import Q
  2. from django.shortcuts import render, redirect
  3. from django.contrib.auth import logout
  4. from django.views.decorators.http import require_POST
  5. from django.contrib.auth.decorators import login_required
  6. from allauth.socialaccount.models import SocialToken
  7. from django.http import HttpResponse
  8. from django.contrib.auth.models import User
  9. from django.contrib import messages
  10. from apps.main.models import Playlist
  11. from .models import Untube
  12. from django.template import loader
  13. # Create your views here.
  14. def index(request):
  15. if Untube.objects.all().count() == 0:
  16. untube = Untube.objects.create()
  17. untube.save()
  18. if not request.session.exists(request.session.session_key):
  19. request.session.create()
  20. request.session['liked_untube'] = False
  21. if request.user.is_anonymous:
  22. return render(request, 'index.html', {"likes": Untube.objects.all().first().page_likes,
  23. "users_joined": User.objects.all().count()})
  24. else:
  25. return redirect('home')
  26. @login_required
  27. def profile(request):
  28. user_playlists = request.user.playlists.all()
  29. watching = user_playlists.filter(marked_as="watching")
  30. total_num_playlists = user_playlists.count()
  31. statistics = {
  32. "public_x": 0,
  33. "private_x": 0,
  34. "favorites_x": 0,
  35. "watching_x": 0,
  36. "imported_x": 0
  37. }
  38. if total_num_playlists != 0:
  39. # x means percentage
  40. statistics["public_x"] = round(user_playlists.filter(is_private_on_yt=False).count() / total_num_playlists,
  41. 1) * 100
  42. statistics["private_x"] = round(user_playlists.filter(is_private_on_yt=True).count() / total_num_playlists,
  43. 1) * 100
  44. statistics["favorites_x"] = round(user_playlists.filter(is_favorite=True).count() / total_num_playlists,
  45. 1) * 100
  46. statistics["watching_x"] = round(user_playlists.filter(marked_as="watching").count() / total_num_playlists,
  47. 1) * 100
  48. statistics["imported_x"] = round(user_playlists.filter(is_user_owned=False).count() / total_num_playlists,
  49. 1) * 100
  50. return render(request, 'profile.html', {
  51. "total_num_playlists": total_num_playlists,
  52. "statistics": statistics,
  53. "watching": watching})
  54. @login_required
  55. def settings(request):
  56. return render(request, 'settings.html')
  57. @require_POST
  58. def update_settings(request):
  59. print(request.POST)
  60. user = request.user
  61. username_input = request.POST['username'].strip()
  62. message_content = "Saved!"
  63. #message_type = "success"
  64. if username_input != user.username:
  65. if User.objects.filter(username__exact=username_input).count() != 0:
  66. #message_type = "danger"
  67. message_content = f"Username {request.POST['username'].strip()} already taken"
  68. messages.error(request, message_content)
  69. else:
  70. user.username = request.POST['username'].strip()
  71. # user.save()
  72. message_content = f"Username updated to {username_input}!"
  73. messages.success(request, message_content)
  74. if 'open search in new tab' in request.POST and user.profile.open_search_new_tab is False:
  75. user.profile.open_search_new_tab = True
  76. elif 'open search in new tab' not in request.POST and user.profile.open_search_new_tab is True:
  77. user.profile.open_search_new_tab = False
  78. if 'enable gradient bg' in request.POST and user.profile.enable_gradient_bg is False:
  79. user.profile.enable_gradient_bg = True
  80. elif 'enable gradient bg' not in request.POST and user.profile.enable_gradient_bg is True:
  81. user.profile.enable_gradient_bg = False
  82. if 'auto refresh playlists' in request.POST and user.profile.auto_check_for_updates is False:
  83. user.profile.auto_check_for_updates = True
  84. for playlist in user.playlists.all():
  85. playlist.auto_check_for_updates = True
  86. playlist.save(update_fields=['auto_check_for_updates'])
  87. elif 'auto refresh playlists' not in request.POST and user.profile.auto_check_for_updates is True:
  88. user.profile.auto_check_for_updates = False
  89. for playlist in user.playlists.all():
  90. playlist.auto_check_for_updates = False
  91. playlist.save(update_fields=['auto_check_for_updates'])
  92. if 'confirm before deleting' in request.POST and user.profile.confirm_before_deleting is False:
  93. user.profile.confirm_before_deleting = True
  94. elif 'confirm before deleting' not in request.POST and user.profile.confirm_before_deleting is True:
  95. user.profile.confirm_before_deleting = False
  96. if 'hide videos' in request.POST and user.profile.hide_unavailable_videos is False:
  97. user.profile.hide_unavailable_videos = True
  98. elif 'hide videos' not in request.POST and user.profile.hide_unavailable_videos is True:
  99. user.profile.hide_unavailable_videos = False
  100. user.save()
  101. if message_content == "Saved!":
  102. messages.success(request, message_content)
  103. return redirect('settings')
  104. @login_required
  105. def delete_account(request):
  106. request.user.playlists.all().delete()
  107. request.user.videos.all().delete()
  108. request.user.playlist_tags.all().delete()
  109. request.user.profile.delete()
  110. request.user.delete()
  111. request.session.flush()
  112. messages.success(request, "Account data deleted successfully.")
  113. return redirect('index')
  114. @login_required
  115. def log_out(request):
  116. request.session.flush() # delete all stored session keys
  117. logout(request) # log out authenticated user
  118. if "troll" in request.GET:
  119. print("TROLLED")
  120. messages.success(request, "Hee Hee")
  121. else:
  122. messages.success(request, "Successfully logged out. Hope to see you back again!")
  123. return redirect('/')
  124. def cancel_import(request):
  125. user_profile = request.user.profile
  126. if user_profile.access_token.strip() == "" or user_profile.refresh_token.strip() == "":
  127. user_social_token = SocialToken.objects.get(account__user=request.user)
  128. user_profile.access_token = user_social_token.token
  129. user_profile.refresh_token = user_social_token.token_secret
  130. user_profile.expires_at = user_social_token.expires_at
  131. # request.user.save()
  132. user_profile.imported_yt_playlists = False
  133. user_profile.show_import_page = False
  134. user_profile.save()
  135. return redirect('home')
  136. def import_user_yt_playlists(request):
  137. request.user.profile.show_import_page = True
  138. request.user.profile.save(update_fields=['show_import_page'])
  139. return render(request, 'import_in_progress.html')
  140. @login_required
  141. def start_import(request):
  142. """
  143. Initializes only the user's playlist data in the database. Returns the progress bar, which will
  144. keep calling continue_import
  145. :param request:
  146. :return:
  147. """
  148. user_profile = request.user.profile
  149. if user_profile.access_token.strip() == "" or user_profile.refresh_token.strip() == "":
  150. user_social_token = SocialToken.objects.get(account__user=request.user)
  151. user_profile.access_token = user_social_token.token
  152. user_profile.refresh_token = user_social_token.token_secret
  153. user_profile.expires_at = user_social_token.expires_at
  154. request.user.save()
  155. result = Playlist.objects.initializePlaylist(request.user)
  156. if result["status"] == -1:
  157. print("User has no YT channel")
  158. return HttpResponse(loader.get_template('intercooler/progress_bar.html').render(
  159. {
  160. "channel_found": False,
  161. "error_message": result["error_message"]
  162. }
  163. ))
  164. elif result["status"] == -2:
  165. user_profile.import_in_progress = False
  166. user_profile.imported_yt_playlists = True
  167. user_profile.show_import_page = True
  168. user_profile.save()
  169. print("User has no playlists on YT")
  170. if request.user.profile.yt_channel_id == "":
  171. Playlist.objects.getUserYTChannelID(request.user)
  172. Playlist.objects.initializePlaylist(request.user, "LL")
  173. return HttpResponse(loader.get_template('intercooler/progress_bar.html').render(
  174. {"total_playlists": 0,
  175. "playlists_imported": 0,
  176. "done": True,
  177. "progress": 100,
  178. "channel_found": True}))
  179. else:
  180. if request.user.profile.yt_channel_id == "":
  181. Playlist.objects.getUserYTChannelID(request.user)
  182. Playlist.objects.initializePlaylist(request.user, "LL")
  183. user_profile.import_in_progress = True
  184. user_profile.save()
  185. return HttpResponse(loader.get_template('intercooler/progress_bar.html').render(
  186. {"total_playlists": result["num_of_playlists"],
  187. "playlist_name": result["first_playlist_name"],
  188. "playlists_imported": 0,
  189. "progress": 0,
  190. "channel_found": True}
  191. ))
  192. @login_required
  193. def continue_import(request):
  194. if request.user.profile.import_in_progress is False:
  195. return redirect('home')
  196. num_of_playlists = request.user.playlists.filter(Q(is_user_owned=True)).exclude(playlist_id="LL").count()
  197. print("NUM OF PLAYLISTS", num_of_playlists)
  198. try:
  199. remaining_playlists = request.user.playlists.filter(Q(is_user_owned=True) & Q(is_in_db=False)).exclude(
  200. playlist_id="LL")
  201. print(remaining_playlists.count(), "REMAINING PLAYLISTS")
  202. playlists_imported = num_of_playlists - remaining_playlists.count() + 1
  203. playlist = remaining_playlists.order_by("created_at")[0]
  204. playlist_name = playlist.name
  205. playlist_id = playlist.playlist_id
  206. Playlist.objects.getAllVideosForPlaylist(request.user, playlist_id)
  207. except:
  208. print("NO REMAINING PLAYLISTS")
  209. playlist_id = -1
  210. if playlist_id != -1:
  211. return HttpResponse(loader.get_template('intercooler/progress_bar.html').render(
  212. {"total_playlists": num_of_playlists,
  213. "playlists_imported": playlists_imported,
  214. "playlist_name": playlist_name,
  215. "progress": round((playlists_imported / num_of_playlists) * 100, 1),
  216. "channel_found": True}))
  217. else:
  218. # request.user.profile.just_joined = False
  219. request.user.profile.import_in_progress = False
  220. request.user.profile.imported_yt_playlists = True
  221. request.user.profile.show_import_page = True # set back to true again so as to show users the welcome screen on 'home'
  222. request.user.save()
  223. user_pl_count = request.user.playlists.filter(Q(is_user_owned=True) & Q(is_in_db=True)).exclude(
  224. playlist_id="LL").count()
  225. return HttpResponse(loader.get_template('intercooler/progress_bar.html').render(
  226. {"total_playlists": user_pl_count,
  227. "playlists_imported": user_pl_count,
  228. "done": True,
  229. "progress": 100,
  230. "channel_found": True}))
  231. @login_required
  232. def user_playlists_updates(request, action):
  233. """
  234. Gets all user created playlist's ids from YouTube and checks them with the user playlists imported on UnTube.
  235. If any playlist id is on UnTube but not on YouTube, deletes the playlist from YouTube.
  236. If any new playlist id, imports it to UnTube
  237. """
  238. if action == 'check-for-updates':
  239. user_playlists_on_UnTube = request.user.playlists.filter(Q(is_user_owned=True) & Q(is_in_db=True)).exclude(
  240. playlist_id="LL")
  241. result = Playlist.objects.initializePlaylist(request.user)
  242. print(result)
  243. youtube_playlist_ids = result["playlist_ids"]
  244. untube_playlist_ids = []
  245. for playlist in user_playlists_on_UnTube:
  246. untube_playlist_ids.append(playlist.playlist_id)
  247. deleted_playlist_ids = []
  248. deleted_playlist_names = []
  249. for pl_id in untube_playlist_ids:
  250. if pl_id not in youtube_playlist_ids: # ie this playlist was deleted on youtube
  251. deleted_playlist_ids.append(pl_id)
  252. pl = request.user.playlists.get(playlist_id__exact=pl_id)
  253. deleted_playlist_names.append(f"{pl.name} (had {pl.video_count} videos)")
  254. pl.delete()
  255. if result["num_of_playlists"] == user_playlists_on_UnTube.count() and len(deleted_playlist_ids) == 0:
  256. print("No new updates")
  257. playlists = []
  258. else:
  259. playlists = request.user.playlists.filter(Q(is_user_owned=True) & Q(is_in_db=False)).exclude(playlist_id="LL")
  260. print(
  261. f"New updates found! {playlists.count()} newly added and {len(deleted_playlist_ids)} playlists deleted!")
  262. print(deleted_playlist_names)
  263. return HttpResponse(loader.get_template('intercooler/user_playlist_updates.html').render(
  264. {"playlists": playlists,
  265. "deleted_playlist_names": deleted_playlist_names}))
  266. elif action == 'init-update':
  267. unimported_playlists = request.user.playlists.filter(Q(is_user_owned=True) & Q(is_in_db=False)).exclude(playlist_id="LL").count()
  268. return HttpResponse(f"""
  269. <div hx-get="/updates/user-playlists/start-update" hx-trigger="load" hx-target="#user-pl-updates">
  270. <div class="alert alert-dismissible fade show" role="alert" style="background-color: cadetblue">
  271. <div class="d-flex justify-content-center mt-4 mb-3 ms-2" id="loading-sign" >
  272. <img src="/static/svg-loaders/spinning-circles.svg" width="40" height="40">
  273. <h5 class="mt-2 ms-2 text-black">Importing {unimported_playlists} new playlists into UnTube, please wait!</h5>
  274. </div>
  275. </div>
  276. </div>
  277. """)
  278. elif action == 'start-update':
  279. unimported_playlists = request.user.playlists.filter(Q(is_user_owned=True) & Q(is_in_db=False)).exclude(playlist_id="LL")
  280. for playlist in unimported_playlists:
  281. Playlist.objects.getAllVideosForPlaylist(request.user, playlist.playlist_id)
  282. return HttpResponse("""
  283. <div class="alert alert-success alert-dismissible fade show d-flex justify-content-center" role="alert">
  284. <h4 class="">Successfully imported new playlists into UnTube! Refresh :)</h4>
  285. <button type="button" class="btn-close" data-bs-dismiss="alert" aria-la bel="Close"></button>
  286. </div>
  287. """)
  288. @login_required
  289. def get_user_liked_videos_playlist(request):
  290. if not request.user.playlists.filter(Q(playlist_id="LL") & Q(is_in_db=True)).exists():
  291. Playlist.objects.initializePlaylist(request.user, "LL")
  292. Playlist.objects.getAllVideosForPlaylist(request.user, "LL")
  293. messages.success(request, "Successfully imported your Liked Videos playlist!")
  294. return HttpResponse("""
  295. <script>
  296. window.location.reload();
  297. </script>
  298. """)
  299. ### FOR INDEX.HTML
  300. @require_POST
  301. def like_untube(request):
  302. untube = Untube.objects.all().first()
  303. untube.page_likes += 1
  304. untube.save()
  305. request.session['liked_untube'] = True
  306. request.session.save()
  307. return HttpResponse(f"""
  308. <a hx-post="/unlike-untube/" hx-swap="outerHTML" style="text-decoration: none; color: black">
  309. <i class="fas fa-heart" style="color: #d02e2e"></i> {untube.page_likes} likes (p.s glad you liked it!)
  310. </a>
  311. """)
  312. @require_POST
  313. def unlike_untube(request):
  314. untube = Untube.objects.all().first()
  315. untube.page_likes -= 1
  316. untube.save()
  317. request.session['liked_untube'] = False
  318. request.session.save()
  319. return HttpResponse(f"""
  320. <a hx-post="/like-untube/" hx-swap="outerHTML" style="text-decoration: none; color: black">
  321. <i class="fas fa-heart"></i> {untube.page_likes} likes (p.s :/)
  322. </a>
  323. """)