views.py 33 KB

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