feat: replace format with fstrings

This commit is contained in:
Markos Gogoulos
2025-07-07 11:26:08 +03:00
committed by GitHub
parent d54732040a
commit 79f2e2bb11
8 changed files with 65 additions and 79 deletions

View File

@ -83,7 +83,7 @@ class IndexRSSFeed(Feed):
return item.edit_date
def item_link(self, item):
return reverse("get_media") + "?m={0}".format(item.friendly_token)
return f"{reverse('get_media')}?m={item.friendly_token}"
def item_extra_kwargs(self, item):
item = {
@ -151,7 +151,7 @@ class SearchRSSFeed(Feed):
return item.edit_date
def item_link(self, item):
return reverse("get_media") + "?m={0}".format(item.friendly_token)
return f"{reverse('get_media')}?m={item.friendly_token}"
def item_extra_kwargs(self, item):
item = {

View File

@ -173,7 +173,7 @@ def rm_dir(directory):
def url_from_path(filename):
# TODO: find a way to preserver http - https ...
return "{0}{1}".format(settings.MEDIA_URL, filename.replace(settings.MEDIA_ROOT, ""))
return f"{settings.MEDIA_URL}{filename.replace(settings.MEDIA_ROOT, '')}"
def create_temp_file(suffix=None, dir=settings.TEMP_DIRECTORY):
@ -488,7 +488,7 @@ def show_file_size(size):
if size:
size = size / 1000000
size = round(size, 1)
size = "{0}MB".format(str(size))
size = f"{str(size)}MB"
return size

View File

@ -166,14 +166,14 @@ Media becomes private if it gets reported %s times\n
)
if settings.ADMINS_NOTIFICATIONS.get("MEDIA_REPORTED", False):
title = "[{}] - Media was reported".format(settings.PORTAL_NAME)
title = f"[{settings.PORTAL_NAME}] - Media was reported"
d = {}
d["title"] = title
d["msg"] = msg
d["to"] = settings.ADMIN_EMAIL_LIST
notify_items.append(d)
if settings.USERS_NOTIFICATIONS.get("MEDIA_REPORTED", False):
title = "[{}] - Media was reported".format(settings.PORTAL_NAME)
title = f"[{settings.PORTAL_NAME}] - Media was reported"
d = {}
d["title"] = title
d["msg"] = msg
@ -182,7 +182,7 @@ Media becomes private if it gets reported %s times\n
if action == "media_added" and media:
if settings.ADMINS_NOTIFICATIONS.get("MEDIA_ADDED", False):
title = "[{}] - Media was added".format(settings.PORTAL_NAME)
title = f"[{settings.PORTAL_NAME}] - Media was added"
msg = """
Media %s was added by user %s.
""" % (
@ -195,7 +195,7 @@ Media %s was added by user %s.
d["to"] = settings.ADMIN_EMAIL_LIST
notify_items.append(d)
if settings.USERS_NOTIFICATIONS.get("MEDIA_ADDED", False):
title = "[{}] - Your media was added".format(settings.PORTAL_NAME)
title = f"[{settings.PORTAL_NAME}] - Your media was added"
msg = """
Your media has been added! It will be encoded and will be available soon.
URL: %s
@ -339,7 +339,7 @@ def notify_user_on_comment(friendly_token):
media_url = settings.SSL_FRONTEND_HOST + media.get_absolute_url()
if user.notification_on_comments:
title = "[{}] - A comment was added".format(settings.PORTAL_NAME)
title = f"[{settings.PORTAL_NAME}] - A comment was added"
msg = """
A comment has been added to your media %s .
View it on %s
@ -363,7 +363,7 @@ def notify_user_on_mention(friendly_token, user_mentioned, cleaned_comment):
media_url = settings.SSL_FRONTEND_HOST + media.get_absolute_url()
if user.notification_on_comments:
title = "[{}] - You were mentioned in a comment".format(settings.PORTAL_NAME)
title = f"[{settings.PORTAL_NAME}] - You were mentioned in a comment"
msg = """
You were mentioned in a comment on %s .
View it on %s

View File

@ -13,7 +13,8 @@ from django.contrib.postgres.indexes import GinIndex
from django.contrib.postgres.search import SearchVectorField
from django.core.exceptions import ValidationError
from django.core.files import File
from django.db import connection, models
from django.db import models
from django.db.models import Func, Value
from django.db.models.signals import m2m_changed, post_delete, post_save, pre_delete
from django.dispatch import receiver
from django.urls import reverse
@ -90,34 +91,34 @@ def generate_uid():
def original_media_file_path(instance, filename):
"""Helper function to place original media file"""
file_name = "{0}.{1}".format(instance.uid.hex, helpers.get_file_name(filename))
return settings.MEDIA_UPLOAD_DIR + "user/{0}/{1}".format(instance.user.username, file_name)
file_name = f"{instance.uid.hex}.{helpers.get_file_name(filename)}"
return settings.MEDIA_UPLOAD_DIR + f"user/{instance.user.username}/{file_name}"
def encoding_media_file_path(instance, filename):
"""Helper function to place encoded media file"""
file_name = "{0}.{1}".format(instance.media.uid.hex, helpers.get_file_name(filename))
return settings.MEDIA_ENCODING_DIR + "{0}/{1}/{2}".format(instance.profile.id, instance.media.user.username, file_name)
file_name = f"{instance.media.uid.hex}.{helpers.get_file_name(filename)}"
return settings.MEDIA_ENCODING_DIR + f"{instance.profile.id}/{instance.media.user.username}/{file_name}"
def original_thumbnail_file_path(instance, filename):
"""Helper function to place original media thumbnail file"""
return settings.THUMBNAIL_UPLOAD_DIR + "user/{0}/{1}".format(instance.user.username, filename)
return settings.THUMBNAIL_UPLOAD_DIR + f"user/{instance.user.username}/{filename}"
def subtitles_file_path(instance, filename):
"""Helper function to place subtitle file"""
return settings.SUBTITLES_UPLOAD_DIR + "user/{0}/{1}".format(instance.media.user.username, filename)
return settings.SUBTITLES_UPLOAD_DIR + f"user/{instance.media.user.username}/{filename}"
def category_thumb_path(instance, filename):
"""Helper function to place category thumbnail file"""
file_name = "{0}.{1}".format(instance.uid.hex, helpers.get_file_name(filename))
return settings.MEDIA_UPLOAD_DIR + "categories/{0}".format(file_name)
file_name = f"{instance.uid}.{helpers.get_file_name(filename)}"
return settings.MEDIA_UPLOAD_DIR + f"categories/{file_name}"
class Media(models.Model):
@ -388,8 +389,6 @@ class Media(models.Model):
search field is used to store SearchVector
"""
db_table = self._meta.db_table
# first get anything interesting out of the media
# that needs to be search able
@ -413,19 +412,8 @@ class Media(models.Model):
text = helpers.clean_query(text)
sql_code = """
UPDATE {db_table} SET search = to_tsvector(
'{config}', '{text}'
) WHERE {db_table}.id = {id}
""".format(
db_table=db_table, config="simple", text=text, id=self.id
)
Media.objects.filter(id=self.id).update(search=Func(Value('simple'), Value(text), function='to_tsvector'))
try:
with connection.cursor() as cursor:
cursor.execute(sql_code)
except BaseException:
pass # TODO:add log
return True
def media_init(self):
@ -925,7 +913,7 @@ class Media(models.Model):
if resolution not in valid_resolutions:
resolution = iframe_playlist.iframe_stream_info.resolution[0]
res["{}_iframe".format(resolution)] = helpers.url_from_path(uri)
res[f"{resolution}_iframe"] = helpers.url_from_path(uri)
for playlist in m3u8_obj.playlists:
uri = os.path.join(p, playlist.uri)
if os.path.exists(uri):
@ -934,7 +922,8 @@ class Media(models.Model):
if resolution not in valid_resolutions:
resolution = playlist.stream_info.resolution[0]
res["{}_playlist".format(resolution)] = helpers.url_from_path(uri)
res[f"{resolution}_playlist"] = helpers.url_from_path(uri)
return res
@property
@ -953,11 +942,11 @@ class Media(models.Model):
def get_absolute_url(self, api=False, edit=False):
if edit:
return reverse("edit_media") + "?m={0}".format(self.friendly_token)
return f"{reverse('edit_media')}?m={self.friendly_token}"
if api:
return reverse("api_get_media", kwargs={"friendly_token": self.friendly_token})
else:
return reverse("get_media") + "?m={0}".format(self.friendly_token)
return f"{reverse('get_media')}?m={self.friendly_token}"
@property
def edit_url(self):
@ -965,7 +954,7 @@ class Media(models.Model):
@property
def add_subtitle_url(self):
return "/add_subtitle?m=%s" % self.friendly_token
return f"/add_subtitle?m={self.friendly_token}"
@property
def ratings_info(self):
@ -1060,7 +1049,7 @@ class Category(models.Model):
verbose_name_plural = "Categories"
def get_absolute_url(self):
return reverse("search") + "?c={0}".format(self.title)
return f"{reverse('search')}?c={self.title}"
def update_category_media(self):
"""Set media_count"""
@ -1122,7 +1111,7 @@ class Tag(models.Model):
ordering = ["title"]
def get_absolute_url(self):
return reverse("search") + "?t={0}".format(self.title)
return f"{reverse('search')}?t={self.title}"
def update_tag_media(self):
self.media_count = Media.objects.filter(state="public", is_reviewed=True, tags=self).count()
@ -1261,7 +1250,7 @@ class Encoding(models.Model):
return False
def __str__(self):
return "{0}-{1}".format(self.profile.name, self.media.title)
return f"{self.profile.name}-{self.media.title}"
def get_absolute_url(self):
return reverse("api_get_encoding", kwargs={"encoding_id": self.id})
@ -1280,7 +1269,7 @@ class Language(models.Model):
ordering = ["id"]
def __str__(self):
return "{0}-{1}".format(self.code, self.title)
return f"{self.code}-{self.title}"
class Subtitle(models.Model):
@ -1303,7 +1292,7 @@ class Subtitle(models.Model):
ordering = ["language__title"]
def __str__(self):
return "{0}-{1}".format(self.media.title, self.language.title)
return f"{self.media.title}-{self.language.title}"
def get_absolute_url(self):
return f"{reverse('edit_subtitle')}?id={self.id}"
@ -1347,7 +1336,7 @@ class RatingCategory(models.Model):
verbose_name_plural = "Rating Categories"
def __str__(self):
return "{0}".format(self.title)
return f"{self.title}"
def validate_rating(value):
@ -1376,7 +1365,7 @@ class Rating(models.Model):
unique_together = ("user", "media", "rating_category")
def __str__(self):
return "{0}, rate for {1} for category {2}".format(self.user.username, self.media.title, self.rating_category.title)
return f"{self.user.username}, rate for {self.media.title} for category {self.rating_category.title}"
class Playlist(models.Model):
@ -1488,7 +1477,7 @@ class Comment(MPTTModel):
order_insertion_by = ["add_date"]
def __str__(self):
return "On {0} by {1}".format(self.media.title, self.user.username)
return f"On {self.media.title} by {self.user.username}"
def save(self, *args, **kwargs):
strip_text_items = ["text"]
@ -1501,7 +1490,7 @@ class Comment(MPTTModel):
super(Comment, self).save(*args, **kwargs)
def get_absolute_url(self):
return reverse("get_media") + "?m={0}".format(self.media.friendly_token)
return f"{reverse('get_media')}?m={self.media.friendly_token}"
@property
def media_url(self):
@ -1720,10 +1709,10 @@ def encoding_file_save(sender, instance, created, **kwargs):
with tempfile.TemporaryDirectory(dir=settings.TEMP_DIRECTORY) as temp_dir:
seg_file = helpers.create_temp_file(suffix=".txt", dir=temp_dir)
tf = helpers.create_temp_file(suffix=".{0}".format(instance.profile.extension), dir=temp_dir)
tf = helpers.create_temp_file(suffix=f".{instance.profile.extension}", dir=temp_dir)
with open(seg_file, "w") as ff:
for f in chunks_paths:
ff.write("file {}\n".format(f))
ff.write(f"file {f}\n")
cmd = [
settings.FFMPEG_COMMAND,
"-y",
@ -1750,7 +1739,7 @@ def encoding_file_save(sender, instance, created, **kwargs):
progress=100,
)
all_logs = "\n".join([st.logs for st in chunks])
encoding.logs = "{0}\n{1}\n{2}".format(chunks_paths, stdout, all_logs)
encoding.logs = f"{chunks_paths}\n{stdout}\n{all_logs}"
workers = list(set([st.worker for st in chunks]))
encoding.worker = json.dumps({"workers": workers})
@ -1761,10 +1750,7 @@ def encoding_file_save(sender, instance, created, **kwargs):
with open(tf, "rb") as f:
myfile = File(f)
output_name = "{0}.{1}".format(
helpers.get_file_name(instance.media.media_file.path),
instance.profile.extension,
)
output_name = f"{helpers.get_file_name(instance.media.media_file.path)}.{instance.profile.extension}"
encoding.media_file.save(content=myfile, name=output_name)
# encoding is saved, deleting chunks
@ -1803,7 +1789,7 @@ def encoding_file_save(sender, instance, created, **kwargs):
chunks_paths = [f.media_file.path for f in chunks]
all_logs = "\n".join([st.logs for st in chunks])
encoding.logs = "{0}\n{1}".format(chunks_paths, all_logs)
encoding.logs = f"{chunks_paths}\n{all_logs}"
workers = list(set([st.worker for st in chunks]))
encoding.worker = json.dumps({"workers": workers})
start_date = min([st.add_date for st in chunks])

View File

@ -136,8 +136,8 @@ def chunkize_media(self, friendly_token, profiles, force=True):
cwd = os.path.dirname(os.path.realpath(media.media_file.path))
file_name = media.media_file.path.split("/")[-1]
random_prefix = produce_friendly_token()
file_format = "{0}_{1}".format(random_prefix, file_name)
chunks_file_name = "%02d_{0}".format(file_format)
file_format = f"{random_prefix}_{file_name}"
chunks_file_name = f"%02d_{file_format}"
chunks_file_name += ".mkv"
cmd = [
settings.FFMPEG_COMMAND,
@ -162,7 +162,7 @@ def chunkize_media(self, friendly_token, profiles, force=True):
chunks.append(ch[0])
if not chunks:
# command completely failed to segment file.putting to normal encode
logger.info("Failed to break file {0} in chunks." " Putting to normal encode queue".format(friendly_token))
logger.info(f"Failed to break file {friendly_token} in chunks. Putting to normal encode queue")
for profile in profiles:
if media.video_height and media.video_height < profile.resolution:
if profile.resolution not in settings.MINIMUM_RESOLUTIONS_TO_ENCODE:
@ -211,7 +211,7 @@ def chunkize_media(self, friendly_token, profiles, force=True):
priority=priority,
)
logger.info("got {0} chunks and will encode to {1} profiles".format(len(chunks), to_profiles))
logger.info(f"got {len(chunks)} chunks and will encode to {to_profiles} profiles")
return True
@ -355,8 +355,8 @@ def encode_media(
# return False
with tempfile.TemporaryDirectory(dir=settings.TEMP_DIRECTORY) as temp_dir:
tf = create_temp_file(suffix=".{0}".format(profile.extension), dir=temp_dir)
tfpass = create_temp_file(suffix=".{0}".format(profile.extension), dir=temp_dir)
tf = create_temp_file(suffix=f".{profile.extension}", dir=temp_dir)
tfpass = create_temp_file(suffix=f".{profile.extension}", dir=temp_dir)
ffmpeg_commands = produce_ffmpeg_commands(
original_media_path,
media.media_info,
@ -398,7 +398,7 @@ def encode_media(
if n_times % 60 == 0:
encoding.progress = percent
encoding.save(update_fields=["progress", "update_date"])
logger.info("Saved {0}".format(round(percent, 2)))
logger.info(f"Saved {round(percent, 2)}")
n_times += 1
except DatabaseError:
# primary reason for this is that the encoding has been deleted, because
@ -451,7 +451,7 @@ def encode_media(
with open(tf, "rb") as f:
myfile = File(f)
output_name = "{0}.{1}".format(get_file_name(original_media_path), profile.extension)
output_name = f"{get_file_name(original_media_path)}.{profile.extension}"
encoding.media_file.save(content=myfile, name=output_name)
encoding.total_run_time = (encoding.update_date - encoding.add_date).seconds
@ -472,7 +472,7 @@ def produce_sprite_from_video(friendly_token):
try:
media = Media.objects.get(friendly_token=friendly_token)
except BaseException:
logger.info("failed to get media with friendly_token %s" % friendly_token)
logger.info(f"failed to get media with friendly_token {friendly_token}")
return False
with tempfile.TemporaryDirectory(dir=settings.TEMP_DIRECTORY) as tmpdirname:
@ -516,7 +516,7 @@ def create_hls(friendly_token):
try:
media = Media.objects.get(friendly_token=friendly_token)
except BaseException:
logger.info("failed to get media with friendly_token %s" % friendly_token)
logger.info(f"failed to get media with friendly_token {friendly_token}")
return False
p = media.uid.hex
@ -558,7 +558,7 @@ def check_running_states():
encodings = Encoding.objects.filter(status="running")
logger.info("got {0} encodings that are in state running".format(encodings.count()))
logger.info(f"got {encodings.count()} encodings that are in state running")
changed = 0
for encoding in encodings:
now = datetime.now(encoding.update_date.tzinfo)
@ -575,7 +575,7 @@ def check_running_states():
# TODO: allign with new code + chunksize...
changed += 1
if changed:
logger.info("changed from running to pending on {0} items".format(changed))
logger.info(f"changed from running to pending on {changed} items")
return True
@ -585,7 +585,7 @@ def check_media_states():
# check encoding status of not success media
media = Media.objects.filter(Q(encoding_status="running") | Q(encoding_status="fail") | Q(encoding_status="pending"))
logger.info("got {0} media that are not in state success".format(media.count()))
logger.info(f"got {media.count()} media that are not in state success")
changed = 0
for m in media:
@ -593,7 +593,7 @@ def check_media_states():
m.save(update_fields=["encoding_status"])
changed += 1
if changed:
logger.info("changed encoding status to {0} media items".format(changed))
logger.info(f"changed encoding status to {changed} media items")
return True
@ -628,7 +628,7 @@ def check_pending_states():
media.encode(profiles=[profile], force=False)
changed += 1
if changed:
logger.info("set to the encode queue {0} encodings that were on pending state".format(changed))
logger.info(f"set to the encode queue {changed} encodings that were on pending state")
return True
@ -652,7 +652,7 @@ def check_missing_profiles():
# if they appear on the meanwhile (eg on a big queue)
changed += 1
if changed:
logger.info("set to the encode queue {0} profiles".format(changed))
logger.info(f"set to the encode queue {changed} profiles")
return True
@ -828,7 +828,7 @@ def update_listings_thumbnails():
object.save(update_fields=["listings_thumbnail"])
used_media.append(media.friendly_token)
saved += 1
logger.info("updated {} categories".format(saved))
logger.info(f"updated {saved} categories")
# Tags
used_media = []
@ -841,7 +841,7 @@ def update_listings_thumbnails():
object.save(update_fields=["listings_thumbnail"])
used_media.append(media.friendly_token)
saved += 1
logger.info("updated {} tags".format(saved))
logger.info(f"updated {saved} tags")
return True

View File

@ -211,7 +211,7 @@ def contact(request):
name = request.POST.get("name")
message = request.POST.get("message")
title = "[{}] - Contact form message received".format(settings.PORTAL_NAME)
title = f"[{settings.PORTAL_NAME}] - Contact form message received"
msg = """
You have received a message through the contact form\n

View File

@ -7,7 +7,7 @@ def import_class(path):
path_bits = path.split(".")
if len(path_bits) < 2:
message = "'{0}' is not a complete Python path.".format(path)
message = f"'{path}' is not a complete Python path."
raise ImproperlyConfigured(message)
class_name = path_bits.pop()
@ -15,7 +15,7 @@ def import_class(path):
module_itself = import_module(module_path)
if not hasattr(module_itself, class_name):
message = "The Python module '{}' has no '{}' class.".format(module_path, class_name)
message = f"The Python module '{module_path}' has no '{class_name}' class."
raise ImportError(message)
return getattr(module_itself, class_name)

View File

@ -105,7 +105,7 @@ class User(AbstractUser):
ret = {}
results = []
ret["results"] = results
ret["user_media"] = "/api/v1/media?author={0}".format(self.username)
ret["user_media"] = f"/api/v1/media?author={self.username}"
return ret
def save(self, *args, **kwargs):
@ -210,7 +210,7 @@ class Channel(models.Model):
super(Channel, self).save(*args, **kwargs)
def __str__(self):
return "{0} -{1}".format(self.user.username, self.title)
return f"{self.user.username} -{self.title}"
def get_absolute_url(self, edit=False):
if edit:
@ -230,7 +230,7 @@ def post_user_create(sender, instance, created, **kwargs):
new = Channel.objects.create(title="default", user=instance)
new.save()
if settings.ADMINS_NOTIFICATIONS.get("NEW_USER", False):
title = "[{}] - New user just registered".format(settings.PORTAL_NAME)
title = f"[{settings.PORTAL_NAME}] - New user just registered"
msg = """
User has just registered with email %s\n
Visit user profile page at %s