views.py 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226
  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 django.template import loader
  12. # Create your views here.
  13. def index(request):
  14. if request.user.is_anonymous:
  15. return render(request, 'index.html')
  16. else:
  17. return redirect('home')
  18. @login_required
  19. def profile(request):
  20. return render(request, 'profile.html')
  21. @require_POST
  22. def update_settings(request):
  23. print(request.POST)
  24. user = request.user
  25. username_input = request.POST['username'].strip()
  26. message_content = "Saved!"
  27. message_type = "success"
  28. if username_input != user.username:
  29. if User.objects.filter(username__exact=username_input).count() != 0:
  30. message_type = "danger"
  31. message_content = f"Username {request.POST['username'].strip()} already taken"
  32. else:
  33. user.username = request.POST['username'].strip()
  34. # user.save()
  35. message_content = f"Username updated to {username_input}!"
  36. if 'open search in new tab' in request.POST:
  37. user.profile.open_search_new_tab = True
  38. else:
  39. user.profile.open_search_new_tab = False
  40. user.save()
  41. return HttpResponse(loader.get_template("intercooler/messages.html").render(
  42. {"message_type": message_type, "message_content": message_content, "refresh_page": True}))
  43. @login_required
  44. def delete_account(request):
  45. request.user.profile.delete()
  46. request.user.delete()
  47. request.session.flush()
  48. messages.success(request, "Account data deleted successfully.")
  49. return redirect('index')
  50. @login_required
  51. def log_out(request):
  52. request.session.flush() # delete all stored session keys
  53. logout(request) # log out authenticated user
  54. return redirect('/')
  55. @login_required
  56. def start_import(request):
  57. '''
  58. Initializes only the user's playlist data in the database. Returns the progress bar, which will
  59. keep calling continue_import
  60. :param request:
  61. :return:
  62. '''
  63. user_profile = request.user.profile
  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. result = Playlist.objects.getAllPlaylistsFromYT(request.user)
  71. channel_found = True
  72. if result["status"] == -1:
  73. print("User has no YT channel")
  74. channel_found = False
  75. return HttpResponse(loader.get_template('intercooler/progress_bar.html').render(
  76. {"channel_found": channel_found}
  77. ))
  78. elif result["status"] == -2:
  79. request.user.profile.import_in_progress = False
  80. request.user.save()
  81. print("User has no playlists on YT")
  82. if request.user.profile.yt_channel_id == "":
  83. Playlist.objects.getUserYTChannelID(request.user)
  84. return HttpResponse(loader.get_template('intercooler/progress_bar.html').render(
  85. {"total_playlists": 0,
  86. "playlists_imported": 0,
  87. "done": True,
  88. "progress": 100,
  89. "channel_found": channel_found}))
  90. else:
  91. if request.user.profile.yt_channel_id == "":
  92. Playlist.objects.getUserYTChannelID(request.user)
  93. return HttpResponse(loader.get_template('intercooler/progress_bar.html').render(
  94. {"total_playlists": result["num_of_playlists"],
  95. "playlist_name": result["first_playlist_name"],
  96. "playlists_imported": 0,
  97. "progress": 0,
  98. "channel_found": channel_found}
  99. ))
  100. @login_required
  101. def settings(request):
  102. return render(request, 'settings.html')
  103. @login_required
  104. def continue_import(request):
  105. if request.user.profile.import_in_progress is False:
  106. return redirect('home')
  107. num_of_playlists = request.user.profile.playlists.all().count()
  108. try:
  109. remaining_playlists = request.user.profile.playlists.filter(is_in_db=False)
  110. playlists_imported = num_of_playlists - remaining_playlists.count() + 1
  111. playlist = remaining_playlists.order_by("created_at")[0]
  112. playlist_name = playlist.name
  113. playlist_id = playlist.playlist_id
  114. Playlist.objects.getAllVideosForPlaylist(request.user, playlist.playlist_id)
  115. except:
  116. playlist_id = -1
  117. if playlist_id != -1:
  118. return HttpResponse(loader.get_template('intercooler/progress_bar.html').render(
  119. {"total_playlists": num_of_playlists,
  120. "playlists_imported": playlists_imported,
  121. "playlist_name": playlist_name,
  122. "progress": round((playlists_imported / num_of_playlists) * 100, 1),
  123. "channel_found": True}))
  124. else:
  125. # request.user.profile.just_joined = False
  126. request.user.profile.import_in_progress = False
  127. request.user.save()
  128. return HttpResponse(loader.get_template('intercooler/progress_bar.html').render(
  129. {"total_playlists": num_of_playlists,
  130. "playlists_imported": num_of_playlists,
  131. "done": True,
  132. "progress": 100,
  133. "channel_found": True}))
  134. @login_required
  135. def user_playlists_updates(request, action):
  136. if action == 'check-for-updates':
  137. user_playlists_on_UnTube = request.user.profile.playlists.filter(Q(is_user_owned=True) & Q(is_in_db=True))
  138. result = Playlist.objects.getAllPlaylistsFromYT(request.user)
  139. youtube_playlist_ids = result["playlist_ids"]
  140. untube_playlist_ids = []
  141. for playlist in user_playlists_on_UnTube:
  142. untube_playlist_ids.append(playlist.playlist_id)
  143. deleted_playlist_ids = []
  144. deleted_playlist_names = []
  145. for pl_id in untube_playlist_ids:
  146. if pl_id not in youtube_playlist_ids: # ie this playlist was deleted on youtube
  147. deleted_playlist_ids.append(pl_id)
  148. pl = request.user.profile.playlists.get(playlist_id__exact=pl_id)
  149. deleted_playlist_names.append(f"{pl.name} (had {pl.video_count} videos)")
  150. pl.delete()
  151. if result["num_of_playlists"] == user_playlists_on_UnTube.count() and len(deleted_playlist_ids) == 0:
  152. print("No new updates")
  153. playlists = []
  154. else:
  155. playlists = request.user.profile.playlists.filter(Q(is_user_owned=True) & Q(is_in_db=False))
  156. print(
  157. f"New updates found! {playlists.count()} newly added and {len(deleted_playlist_ids)} playlists deleted!")
  158. print(deleted_playlist_names)
  159. return HttpResponse(loader.get_template('intercooler/user_playlist_updates.html').render(
  160. {"playlists": playlists,
  161. "deleted_playlist_names": deleted_playlist_names}))
  162. elif action == 'init-update':
  163. unimported_playlists = request.user.profile.playlists.filter(Q(is_user_owned=True) & Q(is_in_db=False)).count()
  164. return HttpResponse(f"""
  165. <div hx-get="/updates/user-playlists/start-update" hx-trigger="load" hx-target="#user-pl-updates">
  166. <div class="alert alert-dismissible fade show" role="alert" style="background-color: cadetblue">
  167. <div class="d-flex justify-content-center mt-4 mb-3 ms-2" id="loading-sign" >
  168. <img src="/static/svg-loaders/spinning-circles.svg" width="40" height="40">
  169. <h5 class="mt-2 ms-2 text-black">Importing {unimported_playlists} new playlists into UnTube, please wait!</h5>
  170. </div>
  171. </div>
  172. </div>
  173. """)
  174. elif action == 'start-update':
  175. unimported_playlists = request.user.profile.playlists.filter(Q(is_user_owned=True) & Q(is_in_db=False))
  176. for playlist in unimported_playlists:
  177. Playlist.objects.getAllVideosForPlaylist(request.user, playlist.playlist_id)
  178. return HttpResponse("""
  179. <div class="alert alert-success alert-dismissible fade show d-flex justify-content-center" role="alert">
  180. <h4 class="">Successfully imported new playlists into UnTube! Refresh :)</h4>
  181. <button type="button" class="btn-close" data-bs-dismiss="alert" aria-la bel="Close"></button>
  182. </div>
  183. """)