From bd5e56278fdb4b61797bf41265d250a7540692bd Mon Sep 17 00:00:00 2001 From: Moon Date: Thu, 12 Jun 2025 12:43:42 +0900 Subject: [PATCH] works now but may need to revert file upload change --- bot/config.py | 3 ++ bot/pleroma_service.py | 66 ++++++++++++++++++++++++++++++++++++++++-- example_config.ini | 5 +++- web/app.py | 10 +++++-- 4 files changed, 79 insertions(+), 5 deletions(-) diff --git a/bot/config.py b/bot/config.py index e47e2f7..9c2c1c4 100644 --- a/bot/config.py +++ b/bot/config.py @@ -24,6 +24,9 @@ if instance_type not in ('misskey', 'pleroma'): INSTANCE_TYPE = instance_type +# Web server port +WEB_PORT = config['application'].getint('WebPort', 5000) + # Extra stuff for control of the bot # TODO: move this to db diff --git a/bot/pleroma_service.py b/bot/pleroma_service.py index 753b1dc..4ec3496 100644 --- a/bot/pleroma_service.py +++ b/bot/pleroma_service.py @@ -1,5 +1,7 @@ from mastodon import Mastodon from typing import List, Optional, Dict, Any, Union, BinaryIO +import mimetypes +import io from fediverse_service import FediverseService from fediverse_types import ( FediverseNotification, FediversePost, FediverseUser, FediverseFile, @@ -157,7 +159,67 @@ class PleromaService(FediverseService): def upload_file(self, file_data: Union[BinaryIO, bytes], filename: Optional[str] = None) -> FediverseFile: """Upload a file to Pleroma instance""" try: - media = self.client.media_post(file_data, mime_type=None, description=filename) - return self._convert_mastodon_file(media) + import requests + + # Convert file_data to bytes if it's a stream + if hasattr(file_data, 'read'): + file_bytes = file_data.read() + else: + file_bytes = file_data + + # Determine mime type from file header + mime_type = 'image/jpeg' # default + if file_bytes.startswith(b'\xff\xd8\xff'): + mime_type = 'image/jpeg' + ext = '.jpg' + elif file_bytes.startswith(b'\x89PNG\r\n\x1a\n'): + mime_type = 'image/png' + ext = '.png' + elif file_bytes.startswith(b'GIF8'): + mime_type = 'image/gif' + ext = '.gif' + elif file_bytes.startswith(b'RIFF') and b'WEBP' in file_bytes[:12]: + mime_type = 'image/webp' + ext = '.webp' + else: + ext = '.jpg' + + # Create a filename if none provided + if not filename: + filename = f"upload{ext}" + + # Direct HTTP POST to /api/v1/media with headers matching browser behavior + headers = { + 'Authorization': f'Bearer {self.client.access_token}', + 'Accept': '*/*', + 'Cache-Control': 'no-cache', + 'Pragma': 'no-cache', + 'User-Agent': 'Kemoverse-Bot/1.0' + } + + # Use files parameter to let requests handle multipart/form-data and content-type + files = { + 'file': (filename, file_bytes, mime_type) + } + + url = f"{self.client.api_base_url}/api/v1/media" + + # Debug logging + print(f"DEBUG: Making POST request to: {url}") + print(f"DEBUG: Headers: {headers}") + print(f"DEBUG: Files keys: {list(files.keys())}") + + response = requests.post(url, headers=headers, files=files) + + print(f"DEBUG: Response status: {response.status_code}") + print(f"DEBUG: Response headers: {dict(response.headers)}") + print(f"DEBUG: Request method was: {response.request.method}") + + if response.status_code in (200, 201): + media = response.json() + return self._convert_mastodon_file(media) + else: + raise Exception(f"Upload failed with {response.status_code}: {response.text}") + except Exception as e: raise RuntimeError(f"Failed to upload file to Pleroma: {e}") from e \ No newline at end of file diff --git a/example_config.ini b/example_config.ini index aa93e07..19ed86f 100644 --- a/example_config.ini +++ b/example_config.ini @@ -17,4 +17,7 @@ InstanceType = misskey DefaultAdmins = ['admin@example.tld'] ; SQLite Database location -DatabaseLocation = ./gacha_game.db \ No newline at end of file +DatabaseLocation = ./gacha_game.db + +; Web server port (default: 5000) +WebPort = 5000 \ No newline at end of file diff --git a/web/app.py b/web/app.py index f68084c..ac7e306 100644 --- a/web/app.py +++ b/web/app.py @@ -1,8 +1,14 @@ from flask import Flask, render_template import sqlite3 +import sys +import os + +# Add bot directory to path to import config +sys.path.append(os.path.join(os.path.dirname(__file__), '..', 'bot')) +import config app = Flask(__name__) -DB_PATH = "./gacha_game.db" # Adjust path if needed +DB_PATH = config.DB_PATH def get_db_connection(): conn = sqlite3.connect(DB_PATH) @@ -56,4 +62,4 @@ def submit_character(): if __name__ == '__main__': - app.run(host='0.0.0.0', port=5000, debug=True) + app.run(host='0.0.0.0', port=config.WEB_PORT, debug=True)