views.py 34 KB

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