2
0

views.py 13 KB

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