Merge pull request #106 from dylanpdx/main

2023-07-01 Update
This commit is contained in:
Dylan 2023-07-01 19:08:28 +01:00 committed by GitHub
commit 2401265ed3
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 28 additions and 18 deletions

View File

@ -30,10 +30,9 @@ def scaleImageIterable(args):
targetWidth = args[1]
targetHeight = args[2]
pad=args[3]
image = image.convert('RGBA')
image = ImageOps.expand(image,20)
if pad:
newImg = ImageOps.contain(image, (targetWidth, targetHeight))
image = image.convert('RGBA')
newImg = ImageOps.pad(image, (targetWidth, targetHeight),color=(0, 0, 0, 0))
else:
newImg = ImageOps.fit(image, (targetWidth, targetHeight)) # scale + crop
return newImg
@ -69,8 +68,7 @@ def combineImages(imageArray, totalWidth, totalHeight,pad=True):
x += image.size[0]
y += imageArray[0].size[1]
x = 0
# paste the final image so that it's centered
newImage.paste(imageArray[2], (int((totalWidth - imageArray[2].size[0]) / 2), y))
newImage.paste(imageArray[2], (x, y))
elif (len(imageArray) == 4): # if there are four images, combine the first two horizontally, then combine the last two vertically
for image in imageArray[0:2]:
newImage.paste(image, (x, y))
@ -93,16 +91,20 @@ def saveImage(image, name):
def genImage(imageArray):
totalSize=getTotalImgSize(imageArray)
combined = combineImages(imageArray, *totalSize)
finalImg = combined.convert('RGB')
bbox = finalImg.getbbox()
finalImg = finalImg.crop(bbox)
combinedBG = combineImages(imageArray, *totalSize,False)
combinedBG = blurImage(combinedBG,50)
finalImg = Image.alpha_composite(combinedBG,combined)
#finalImg = ImageOps.pad(finalImg, findImageWithMostPixels(imageArray).size,color=(0, 0, 0, 0))
finalImg = finalImg.convert('RGB')
return finalImg
def downloadImage(url):
return Image.open(BytesIO(get(url).content))
for i in range(3):
try:
return Image.open(BytesIO(get(url).content))
except:
pass
return None
def genImageFromURL(urlArray):
# this method avoids storing the images in disk, instead they're stored in memory
@ -113,6 +115,8 @@ def genImageFromURL(urlArray):
imageArray = [executor.submit(downloadImage, url) for url in urlArray]
imageArray = [future.result() for future in imageArray]
print(f"Images downloaded in: {timer() - start}s")
if (None in imageArray): # return none if any of the images failed to download
return None
start = timer()
finalImg = genImage(imageArray)
print(f"Image generated in: {timer() - start}s")
@ -129,6 +133,8 @@ def lambda_handler(event, context):
if not img.startswith("https://pbs.twimg.com"):
return {'statusCode':400,'body':'Invalid image URL'}
combined = genImageFromURL(images)
if (combined == None):
return {'statusCode':500,'body':'Failed to download image(s)'}
buffered = BytesIO()
combined.save(buffered,format="JPEG",quality=60)
combined_str=base64.b64encode(buffered.getvalue()).decode('ascii')
@ -136,7 +142,8 @@ def lambda_handler(event, context):
'statusCode': 200,
"headers":
{
"Content-Type": "image/jpeg"
"Content-Type": "image/jpeg",
"Cache-Control": "public, max-age=86400"
},
'body': combined_str,
'isBase64Encoded': True

View File

@ -1,4 +1,4 @@
failedToScan="Failed to scan your link! This may be due to an incorrect link, private/suspended account, deleted tweet, or Twitter itself might be having issues (Check here: https://api.twitterstat.us/)"
failedToScan="Failed to scan your link! This may be due to an incorrect link, private/suspended account, deleted tweet, or recent changes to Twitter's API (Thanks, Elon!)."
failedToScanExtra = "\n\nTwitter gave me this error: "
tweetNotFound="Tweet not found."
tweetSuspended="This Tweet is from a suspended account."

View File

@ -36,10 +36,13 @@ generate_embed_user_agents = [
"Synapse (bot; +https://github.com/matrix-org/synapse)",
"test"]
def isValidUserAgent(user_agent):
return user_agent in generate_embed_user_agents
@app.route('/') # If the useragent is discord, return the embed, if not, redirect to configured repo directly
def default():
user_agent = request.headers.get('user-agent')
if user_agent in generate_embed_user_agents:
if isValidUserAgent(user_agent):
return message("TwitFix is an attempt to fix twitter video embeds in discord! created by Robin Universe :)\n\n💖\n\nClick me to be redirected to the repo!")
else:
return redirect(config['config']['repo'], 301)
@ -72,7 +75,7 @@ def twitfix(sub_path):
return message(msgs.failedToScan)
return make_cached_vnf_response(vnf,getTemplate("rawvideo.html",vnf,"","",clean,"","","",""))
elif request.url.startswith("https://d.vx"): # Matches d.fx? Try to give the user a direct link
if user_agent in generate_embed_user_agents:
if isValidUserAgent(user_agent):
twitter_url = config['config']['url'] + "/"+sub_path
log.debug( "d.vx link shown to discord user-agent!")
if request.url.endswith(".mp4") and "?" not in request.url:
@ -103,7 +106,7 @@ def twitfix(sub_path):
if match.start() == 0:
twitter_url = "https://twitter.com/" + sub_path
if user_agent in generate_embed_user_agents:
if isValidUserAgent(user_agent):
res = embedCombined(twitter_url)
return res
@ -125,7 +128,7 @@ def dir(sub_path):
if match.start() == 0:
twitter_url = "https://twitter.com/" + url
if user_agent in generate_embed_user_agents:
if isValidUserAgent(user_agent):
res = embed_video(twitter_url)
return res