Browse Source

use custom print function

Mohammed Khan 1 year ago
parent
commit
e12dcc996c
5 changed files with 60 additions and 50 deletions
  1. 6 0
      backend/general/utils/misc.py
  2. 32 31
      backend/main/models.py
  3. 11 10
      backend/main/views.py
  4. 3 2
      backend/search/views.py
  5. 8 7
      backend/users/views.py

+ 6 - 0
backend/general/utils/misc.py

@@ -1,4 +1,5 @@
 import yaml
+from django.conf import settings
 
 
 def yaml_coerce(value):
@@ -12,3 +13,8 @@ def yaml_coerce(value):
         return yaml.load(f'dummy: {value}', Loader=yaml.SafeLoader)['dummy']
 
     return value
+
+
+def print_(*args, **kwargs):
+    if settings.ENABLE_PRINT_STATEMENTS:
+        print(*args, **kwargs)

+ 32 - 31
backend/main/models.py

@@ -5,6 +5,7 @@ from django.db import models
 from googleapiclient.discovery import build
 import googleapiclient.errors
 from django.db.models import Q, Sum
+from ..general.utils.misc import print_
 
 
 def get_message_from_httperror(e):
@@ -58,10 +59,10 @@ class PlaylistManager(models.Manager):
 
             pl_response = pl_request.execute()
 
-            print(pl_response)
+            print_(pl_response)
 
             if pl_response['pageInfo']['totalResults'] == 0:
-                print("Looks like do not have a channel on youtube. Create one to import all of your playlists. Retry?")
+                print_("Looks like do not have a channel on youtube. Create one to import all of your playlists. Retry?")
                 return -1
             else:
                 user_profile.yt_channel_id = pl_response['items'][0]['id']
@@ -97,7 +98,7 @@ class PlaylistManager(models.Manager):
                     maxResults=50
                 )
             else:
-                print("GETTING ALL USER AUTH PLAYLISTS")
+                print_("GETTING ALL USER AUTH PLAYLISTS")
                 pl_request = youtube.playlists().list(
                     part='contentDetails, snippet, id, player, status',
                     mine=True,  # get playlist details for this playlist id
@@ -108,15 +109,15 @@ class PlaylistManager(models.Manager):
             try:
                 pl_response = pl_request.execute()
             except googleapiclient.errors.HttpError as e:
-                print("YouTube channel not found if mine=True")
-                print("YouTube playlist not found if id=playlist_id")
+                print_("YouTube channel not found if mine=True")
+                print_("YouTube playlist not found if id=playlist_id")
                 result["status"] = -1
                 result["error_message"] = get_message_from_httperror(e)
                 return result
 
-            print(pl_response)
+            print_(pl_response)
             if pl_response["pageInfo"]["totalResults"] == 0:
-                print("No playlists created yet on youtube.")
+                print_("No playlists created yet on youtube.")
                 result["status"] = -2
                 return result
 
@@ -145,7 +146,7 @@ class PlaylistManager(models.Manager):
             # check if this playlist already exists in user's untube collection
             if user.playlists.filter(Q(playlist_id=playlist_id) & Q(is_in_db=True)).exists():
                 playlist = user.playlists.get(playlist_id=playlist_id)
-                print(f"PLAYLIST {playlist.name} ({playlist_id}) ALREADY EXISTS IN DB")
+                print_(f"PLAYLIST {playlist.name} ({playlist_id}) ALREADY EXISTS IN DB")
 
                 # POSSIBLE CASES:
                 # 1. PLAYLIST HAS DUPLICATE VIDEOS, DELETED VIDS, UNAVAILABLE VIDS
@@ -159,7 +160,7 @@ class PlaylistManager(models.Manager):
                     result["status"] = -3
                     return result
             else:  # no such playlist in database
-                print(f"CREATING {item['snippet']['title']} ({playlist_id})")
+                print_(f"CREATING {item['snippet']['title']} ({playlist_id})")
                 if user.playlists.filter(Q(playlist_id=playlist_id) & Q(is_in_db=False)).exists():
                     unimported_playlist = user.playlists.filter(Q(playlist_id=playlist_id) & Q(is_in_db=False)).first()
                     unimported_playlist.delete()
@@ -260,7 +261,7 @@ class PlaylistManager(models.Manager):
 
                 else:  # video found in user's db
                     if playlist.playlist_items.filter(playlist_item_id=playlist_item_id).exists():
-                        print("PLAYLIST ITEM ALREADY EXISTS")
+                        print_("PLAYLIST ITEM ALREADY EXISTS")
                         continue
 
                     video = user.videos.get(video_id=video_id)
@@ -465,7 +466,7 @@ class PlaylistManager(models.Manager):
         # if its been a week since the last full scan, do a full playlist scan
         # basically checks all the playlist video for any updates
         if playlist.last_full_scan_at + datetime.timedelta(minutes=1) < datetime.datetime.now(pytz.utc):
-            print("DOING A FULL SCAN")
+            print_("DOING A FULL SCAN")
             current_playlist_item_ids = [playlist_item.playlist_item_id for playlist_item in
                                          playlist.playlist_items.all()]
 
@@ -546,10 +547,10 @@ class PlaylistManager(models.Manager):
 
             return [1, deleted_videos, unavailable_videos, added_videos]
         else:
-            print("YOU CAN DO A FULL SCAN AGAIN IN",
+            print_("YOU CAN DO A FULL SCAN AGAIN IN",
                   str(datetime.datetime.now(pytz.utc) - (playlist.last_full_scan_at + datetime.timedelta(minutes=1))))
         """
-        print("DOING A SMOL SCAN")
+        print_("DOING A SMOL SCAN")
 
         with build('youtube', 'v3', credentials=credentials) as youtube:
             pl_request = youtube.playlists().list(
@@ -562,11 +563,11 @@ class PlaylistManager(models.Manager):
             try:
                 pl_response = pl_request.execute()
             except googleapiclient.errors.HttpError:
-                print("YouTube channel not found if mine=True")
-                print("YouTube playlist not found if id=playlist_id")
+                print_("YouTube channel not found if mine=True")
+                print_("YouTube playlist not found if id=playlist_id")
                 return -1
 
-            print("PLAYLIST", pl_response)
+            print_("PLAYLIST", pl_response)
 
             playlist_items = []
 
@@ -588,7 +589,7 @@ class PlaylistManager(models.Manager):
             # check if this playlist already exists in database
             if user.playlists.filter(playlist_id=playlist_id).exists():
                 playlist = user.playlists.get(playlist_id__exact=playlist_id)
-                print(f"PLAYLIST {playlist.name} ALREADY EXISTS IN DB")
+                print_(f"PLAYLIST {playlist.name} ALREADY EXISTS IN DB")
 
                 # POSSIBLE CASES:
                 # 1. PLAYLIST HAS DUPLICATE VIDEOS, DELETED VIDS, UNAVAILABLE VIDS
@@ -627,10 +628,10 @@ class PlaylistManager(models.Manager):
             try:
                 pl_response = pl_request.execute()
             except googleapiclient.errors.HttpError:
-                print("Playist was deleted on YouTube")
+                print_("Playist was deleted on YouTube")
                 return [-1, [], [], []]
 
-            print("ESTIMATED VIDEO IDS FROM RESPONSE", len(pl_response["items"]))
+            print_("ESTIMATED VIDEO IDS FROM RESPONSE", len(pl_response["items"]))
             updated_playlist_video_count += len(pl_response["items"])
             for item in pl_response['items']:
                 playlist_item_id = item["id"]
@@ -920,13 +921,13 @@ class PlaylistManager(models.Manager):
             )
             try:
                 pl_response = pl_request.execute()
-                print(pl_response)
+                print_(pl_response)
             except googleapiclient.errors.HttpError as e:  # failed to delete playlist
                 # possible causes:
                 # playlistForbidden (403)
                 # playlistNotFound  (404)
                 # playlistOperationUnsupported (400)
-                print(e.error_details, e.status_code)
+                print_(e.error_details, e.status_code)
                 return [-1, get_message_from_httperror(e), e.status_code]
 
             # playlistItem was successfully deleted if no HttpError, so delete it from db
@@ -955,16 +956,16 @@ class PlaylistManager(models.Manager):
                 pl_request = youtube.playlistItems().delete(
                     id=playlist_item.playlist_item_id
                 )
-                print(pl_request)
+                print_(pl_request)
                 try:
                     pl_response = pl_request.execute()
-                    print(pl_response)
+                    print_(pl_response)
                 except googleapiclient.errors.HttpError as e:  # failed to delete playlist item
                     # possible causes:
                     # playlistItemsNotAccessible (403)
                     # playlistItemNotFound (404)
                     # playlistOperationUnsupported (400)
-                    print(e, e.error_details, e.status_code)
+                    print_(e, e.error_details, e.status_code)
                     continue
 
                 # playlistItem was successfully deleted if no HttpError, so delete it from db
@@ -1049,7 +1050,7 @@ class PlaylistManager(models.Manager):
             try:
                 pl_response = pl_request.execute()
             except googleapiclient.errors.HttpError as e:  # failed to create playlist
-                print(e.status_code, e.error_details)
+                print_(e.status_code, e.error_details)
                 if e.status_code == 400:  # maxPlaylistExceeded
                     result["status"] = 400
                 result["status"] = -1
@@ -1079,7 +1080,7 @@ class PlaylistManager(models.Manager):
                 },
             )
 
-            print(details["description"])
+            print_(details["description"])
             try:
                 pl_response = pl_request.execute()
             except googleapiclient.errors.HttpError as e:  # failed to update playlist details
@@ -1089,10 +1090,10 @@ class PlaylistManager(models.Manager):
                 # playlistOperationUnsupported (400)
                 # errors i ran into:
                 # runs into HttpError 400 "Invalid playlist snippet." when the description contains <, >
-                print("ERROR UPDATING PLAYLIST DETAILS", e, e.status_code, e.error_details)
+                print_("ERROR UPDATING PLAYLIST DETAILS", e, e.status_code, e.error_details)
                 return -1
 
-            print(pl_response)
+            print_(pl_response)
             playlist.name = pl_response['snippet']['title']
             playlist.description = pl_response['snippet']['description']
             playlist.is_private_on_yt = True if pl_response['status']['privacyStatus'] == "private" else False
@@ -1140,7 +1141,7 @@ class PlaylistManager(models.Manager):
                         # playlistOperationUnsupported (400)
                         # errors i ran into:
                         # runs into HttpError 400 "Invalid playlist snippet." when the description contains <, >
-                        print("ERROR UPDATING PLAYLIST DETAILS", e.status_code, e.error_details)
+                        print_("ERROR UPDATING PLAYLIST DETAILS", e.status_code, e.error_details)
                         if e.status_code == 400:
                             pl_request = youtube.playlistItems().insert(
                                 part="snippet",
@@ -1202,7 +1203,7 @@ class PlaylistManager(models.Manager):
                 try:
                     pl_response = pl_request.execute()
                 except googleapiclient.errors.HttpError as e:  # failed to update add video to playlis
-                    print("ERROR ADDDING VIDEOS TO PLAYLIST", e.status_code, e.error_details)
+                    print_("ERROR ADDDING VIDEOS TO PLAYLIST", e.status_code, e.error_details)
                     if e.status_code == 400:  # manualSortRequired - see errors https://developers.google.com/youtube/v3/docs/playlistItems/insert
                         pl_request = youtube.playlistItems().insert(
                             part="snippet",
@@ -1402,7 +1403,7 @@ class Playlist(models.Model):
     #         f'https://api.unsplash.com/search/photos/?client_id={SECRETS["UNSPLASH_API_ACCESS_KEY"]}&page=1&query={pl_name}')
     #     image = response.json()["results"][0]["urls"]["small"]
     #
-    #     print(image)
+    #     print_(image)
     #
     #     return image
 

+ 11 - 10
backend/main/views.py

@@ -11,6 +11,7 @@ from django.views.decorators.http import require_POST
 from django.contrib import messages
 from django.template import loader
 from .util import *
+from ..general.utils.misc import print_
 
 
 # Create your views here.
@@ -130,7 +131,7 @@ def view_playlist(request, playlist_id):
         # if its been 1 days since the last full scan, force refresh the playlist
         if playlist.last_full_scan_at + datetime.timedelta(days=2) < datetime.datetime.now(pytz.utc):
             playlist.has_playlist_changed = True
-            print("ITS BEEN 15 DAYS, FORCE REFRESHING PLAYLIST")
+            print_("ITS BEEN 15 DAYS, FORCE REFRESHING PLAYLIST")
 
         # only note down that the playlist as been viewed when 30s has passed since the last access
         if playlist.last_accessed_on + datetime.timedelta(seconds=30) < datetime.datetime.now(pytz.utc):
@@ -448,7 +449,7 @@ def playlist_delete_videos(request, playlist_id, command):
             <div class="spinner-border text-light" role="status" hx-post="{url}" {hx_vals} hx-trigger="load" hx-include="[id='video-checkboxes']" hx-target="#delete-videos-confirm-box"></div><hr>
             """)
     elif command == "start":
-        print("Deleting", len(playlist_item_ids), "videos")
+        print_("Deleting", len(playlist_item_ids), "videos")
         Playlist.objects.deletePlaylistItems(request.user, playlist_id, playlist_item_ids)
         if all:
             help_text = "Finished emptying this playlist."
@@ -551,7 +552,7 @@ def load_more_videos(request, playlist_id, order_by, page):
     playlist_items = None
     if order_by == "all":
         playlist_items = playlist.playlist_items.select_related('video').order_by("video_position")
-        print(f"loading page 1: {playlist_items.count()} videos")
+        print_(f"loading page 1: {playlist_items.count()} videos")
     elif order_by == "favorites":
         playlist_items = playlist.playlist_items.select_related('video').filter(video__is_favorite=True).order_by(
             "video_position")
@@ -648,13 +649,13 @@ def update_playlist(request, playlist_id, command):
     playlist = request.user.playlists.get(playlist_id=playlist_id)
 
     if command == "checkforupdates":
-        print("Checking if playlist changed...")
+        print_("Checking if playlist changed...")
         result = Playlist.objects.checkIfPlaylistChangedOnYT(request.user, playlist_id)
 
         if result[0] == 1:  # full scan was done (full scan is done for a playlist if a week has passed)
             deleted_videos, unavailable_videos, added_videos = result[1:]
 
-            print("CHANGES", deleted_videos, unavailable_videos, added_videos)
+            print_("CHANGES", deleted_videos, unavailable_videos, added_videos)
 
             # playlist_changed_text = ["The following modifications happened to this playlist on YouTube:"]
             if deleted_videos != 0 or unavailable_videos != 0 or added_videos != 0:
@@ -682,7 +683,7 @@ def update_playlist(request, playlist_id, command):
                 </div>
                 """)
         elif result[0] == -1:  # playlist changed
-            print("Playlist was deleted from YouTube")
+            print_("Playlist was deleted from YouTube")
             playlist.videos.all().delete()
             playlist.delete()
             return HttpResponse("""
@@ -717,7 +718,7 @@ def update_playlist(request, playlist_id, command):
         """)
 
     if command == "manual":
-        print("MANUAL")
+        print_("MANUAL")
         return HttpResponse(
             f"""<div hx-get="/playlist/{playlist_id}/update/auto" hx-trigger="load" hx-swap="outerHTML">
                     <div class="d-flex justify-content-center mt-4 mb-3" id="loading-sign">
@@ -726,7 +727,7 @@ def update_playlist(request, playlist_id, command):
                     </div>
                 </div>""")
 
-    print("Attempting to update playlist")
+    print_("Attempting to update playlist")
     status, deleted_playlist_item_ids, unavailable_videos, added_videos = Playlist.objects.updatePlaylist(request.user,
                                                                                                           playlist_id)
 
@@ -742,7 +743,7 @@ def update_playlist(request, playlist_id, command):
                 </div>
             """)
 
-    print("Updated playlist")
+    print_("Updated playlist")
     playlist_changed_text = []
 
     if len(added_videos) != 0:
@@ -903,7 +904,7 @@ def remove_playlist_tag(request, playlist_id, tag_name):
     if playlist_tags.filter(name__iexact=tag_name).exists():  # tag on this playlist, remove it it
         tag = Tag.objects.filter(Q(created_by=request.user) & Q(name__iexact=tag_name)).first()
 
-        print("Removed tag", tag_name)
+        print_("Removed tag", tag_name)
         # remove it from the playlist
         playlist.tags.remove(tag)
     else:

+ 3 - 2
backend/search/views.py

@@ -5,12 +5,13 @@ from django.http import HttpResponse
 from django.shortcuts import render, redirect
 from django.template import loader
 from django.views.decorators.http import require_POST
+from backend.general.utils.misc import print_
 
 
 @login_required
 def search(request):
     if request.method == "GET":
-        print(request.GET)
+        print_(request.GET)
         if 'mode' in request.GET:
             mode = bleach.clean(request.GET['mode'])
         else:
@@ -155,7 +156,7 @@ def search_UnTube(request):
 @login_required
 @require_POST
 def search_library(request, library_type):
-    # print(request.POST)  # prints <QueryDict: {'search': ['aa']}>
+    # print_(request.POST)  # prints <QueryDict: {'search': ['aa']}>
 
     search_query = bleach.clean(request.POST["search"])
     watching = False

+ 8 - 7
backend/users/views.py

@@ -13,6 +13,7 @@ from .models import Untube
 from django.template import loader
 from django.conf import settings
 from django.contrib.sites.models import Site
+from ..general.utils.misc import print_
 
 
 # Create your views here.
@@ -247,18 +248,18 @@ def continue_import(request):
         return redirect('home')
 
     num_of_playlists = request.user.playlists.filter(Q(is_user_owned=True)).exclude(playlist_id="LL").count()
-    print("NUM OF PLAYLISTS", num_of_playlists)
+    print_("NUM OF PLAYLISTS", num_of_playlists)
     try:
         remaining_playlists = request.user.playlists.filter(Q(is_user_owned=True) & Q(is_in_db=False)).exclude(
             playlist_id="LL")
-        print(remaining_playlists.count(), "REMAINING PLAYLISTS")
+        print_(remaining_playlists.count(), "REMAINING PLAYLISTS")
         playlists_imported = num_of_playlists - remaining_playlists.count() + 1
         playlist = remaining_playlists.order_by("created_at")[0]
         playlist_name = playlist.name
         playlist_id = playlist.playlist_id
         Playlist.objects.getAllVideosForPlaylist(request.user, playlist_id)
     except:
-        print("NO REMAINING PLAYLISTS")
+        print_("NO REMAINING PLAYLISTS")
         playlist_id = -1
 
     if playlist_id != -1:
@@ -299,7 +300,7 @@ def user_playlists_updates(request, action):
 
         result = Playlist.objects.initializePlaylist(request.user)
 
-        print(result)
+        print_(result)
         youtube_playlist_ids = result["playlist_ids"]
         untube_playlist_ids = []
         for playlist in user_playlists_on_UnTube:
@@ -315,14 +316,14 @@ def user_playlists_updates(request, action):
                 pl.delete()
 
         if result["num_of_playlists"] == user_playlists_on_UnTube.count() and len(deleted_playlist_ids) == 0:
-            print("No new updates")
+            print_("No new updates")
             playlists = []
         else:
             playlists = request.user.playlists.filter(Q(is_user_owned=True) & Q(is_in_db=False)).exclude(
                 playlist_id="LL")
-            print(
+            print_(
                 f"New updates found! {playlists.count()} newly added and {len(deleted_playlist_ids)} playlists deleted!")
-            print(deleted_playlist_names)
+            print_(deleted_playlist_names)
 
         return HttpResponse(loader.get_template('intercooler/user_playlist_updates.html').render(
             {"playlists": playlists,