Skip to content

Commit

Permalink
fix: Upload media in target format directly and use original file on …
Browse files Browse the repository at this point in the history
…error
  • Loading branch information
MinmoTech committed Nov 23, 2023
1 parent 5e3475d commit b3f5758
Showing 1 changed file with 35 additions and 25 deletions.
60 changes: 35 additions & 25 deletions src/migaku_connection/srs_util.py
Original file line number Diff line number Diff line change
Expand Up @@ -219,34 +219,44 @@ def _upload_media_single_attempt(fname, user_token, is_audio=False):
with open(in_path, "wb") as file:
file.write(data)

if is_audio:
fname = os.path.splitext(fname)[0] + ".m4a"
out_path = tmp_path(fname)
# The arguments to ffmpeg are the same as in MM
r = aqt.mw.migaku_connection.ffmpeg.call(
"-y", "-i", in_path, "-vn", "-b:a", "128k", out_path,
)
if r != 0:
# ignore failed conversions, most likely bad audio
return None
try:
if fname.endswith(".webp") or fname.endswith(".m4a"):
# if file is already in target format, use it directly
with open(in_path, "rb") as file:
data = file.read()
elif is_audio:
fname = os.path.splitext(fname)[0] + ".m4a"
out_path = tmp_path(fname)
# The arguments to ffmpeg are the same as in MM
r = aqt.mw.migaku_connection.ffmpeg.call(
"-y", "-i", in_path, "-vn", "-b:a", "128k", out_path,
)
if r != 0:
# ignore failed conversions, most likely bad audio
return None

with open(out_path, "rb") as file:
data = file.read()
with open(out_path, "rb") as file:
data = file.read()

else:
# We assume that if something is not audio, it is a picture
fname = os.path.splitext(fname)[0] + ".webp"
out_path = tmp_path(fname)

# The arguments to ffmpeg are the same as in MM
r = aqt.mw.migaku_connection.ffmpeg.call(
"-y", "-i", in_path, "-vf", "scale='min(800,iw)':-1", out_path,
)
if r != 0:
# ignore failed conversions, most likely bad audio
return None
else:
# We assume that if something is not audio, it is a picture
fname = os.path.splitext(fname)[0] + ".webp"
out_path = tmp_path(fname)

with open(out_path, "rb") as file:
# The arguments to ffmpeg are the same as in MM
r = aqt.mw.migaku_connection.ffmpeg.call(
"-y", "-i", in_path, "-vf", "scale='min(800,iw)':-1", out_path,
)
if r != 0:
# ignore failed conversions, most likely bad audio
return None

with open(out_path, "rb") as file:
data = file.read()
except Exception as e:
print(f"File conversion failed: {e}")
# use original file in case of error
with open(in_path, "rb") as file:
data = file.read()

quoted = urllib.parse.quote(fname)
Expand Down

0 comments on commit b3f5758

Please sign in to comment.