diff --git a/gelbooru_poster.py b/gelbooru_poster.py index cfb785b..d86a2b2 100644 --- a/gelbooru_poster.py +++ b/gelbooru_poster.py @@ -90,10 +90,13 @@ class BotInstance: if image_request.status_code != 200: print("Error: " + image_request.json()["error"]["message"], file=log_file) return False + #Save image_request.content, based on image_url extension + with open("image_original" + os.path.splitext(image_url)[-1], "wb") as image_file: + image_file.write(image_request.content) + # Optimise the image by reducing it to max width of 2048px image = Image.open(BytesIO(image_request.content)) - #Save a copy of the original image - image.save("image_original.jpg") + if image.width > 2048: image = image.resize((2048, int(image.height * (2048 / image.width))), Image.Resampling.LANCZOS) # Apply JPEG compression @@ -101,17 +104,22 @@ class BotInstance: image.save("image.jpg", optimize=True, quality=90) # If the image is larger than the original, use the original - if os.path.getsize("image.jpg") > os.path.getsize("image_original.jpg"): - os.remove("image.jpg") - os.rename("image_original.jpg", "image.jpg") + if os.path.getsize("image.jpg") > os.path.getsize("image_original" + os.path.splitext(image_url)[-1]): + upload_from_url_request = requests.post(self.misskey_url + "drive/files/upload-from-url", json = {"url": image_url, "isSensitive": image_rating != 'general', "i": self.misskey_token}) + # If error, print error and exit + if upload_from_url_request.status_code != 204 and upload_from_url_request.status_code != 200: + print("Error: " + upload_from_url_request.json()["error"]["message"], file=log_file) + return False + else: + # Submit a /drive/files/create request to Misskey + create_file_request = requests.post(self.misskey_url + "drive/files/create", data = {"name": os.path.split(image_url)[-1], "i": self.misskey_token, "isSensitive": str(image_rating != 'general').lower()}, files = {"file": open("image.jpg", "rb")}) + # If error, print error and exit + if create_file_request.status_code != 200: + print("Error: " + create_file_request.json()["error"]["message"], file=log_file) + return False - # Submit a /drive/files/create request to Misskey - create_file_request = requests.post(self.misskey_url + "drive/files/create", data = {"name": os.path.split(image_url)[-1], "i": self.misskey_token, "isSensitive": str(image_rating != 'general').lower()}, files = {"file": open("image.jpg", "rb")}) - - # If error, print error and exit - if create_file_request.status_code != 200: - print("Error: " + create_file_request.json()["error"]["message"], file=log_file) - return False + os.remove("image.jpg") + os.remove("image_original" + os.path.splitext(image_url)[-1]) else: upload_from_url_request = requests.post(self.misskey_url + "drive/files/upload-from-url", json = {"url": image_url, "isSensitive": image_rating != 'general', "i": self.misskey_token}) # If error, print error and exit