works now but may need to revert file upload change

This commit is contained in:
Moon 2025-06-12 12:43:42 +09:00
parent f101119b47
commit bd5e56278f
4 changed files with 79 additions and 5 deletions

View file

@ -24,6 +24,9 @@ if instance_type not in ('misskey', 'pleroma'):
INSTANCE_TYPE = instance_type INSTANCE_TYPE = instance_type
# Web server port
WEB_PORT = config['application'].getint('WebPort', 5000)
# Extra stuff for control of the bot # Extra stuff for control of the bot
# TODO: move this to db # TODO: move this to db

View file

@ -1,5 +1,7 @@
from mastodon import Mastodon from mastodon import Mastodon
from typing import List, Optional, Dict, Any, Union, BinaryIO from typing import List, Optional, Dict, Any, Union, BinaryIO
import mimetypes
import io
from fediverse_service import FediverseService from fediverse_service import FediverseService
from fediverse_types import ( from fediverse_types import (
FediverseNotification, FediversePost, FediverseUser, FediverseFile, 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: def upload_file(self, file_data: Union[BinaryIO, bytes], filename: Optional[str] = None) -> FediverseFile:
"""Upload a file to Pleroma instance""" """Upload a file to Pleroma instance"""
try: try:
media = self.client.media_post(file_data, mime_type=None, description=filename) import requests
return self._convert_mastodon_file(media)
# 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: except Exception as e:
raise RuntimeError(f"Failed to upload file to Pleroma: {e}") from e raise RuntimeError(f"Failed to upload file to Pleroma: {e}") from e

View file

@ -17,4 +17,7 @@ InstanceType = misskey
DefaultAdmins = ['admin@example.tld'] DefaultAdmins = ['admin@example.tld']
; SQLite Database location ; SQLite Database location
DatabaseLocation = ./gacha_game.db DatabaseLocation = ./gacha_game.db
; Web server port (default: 5000)
WebPort = 5000

View file

@ -1,8 +1,14 @@
from flask import Flask, render_template from flask import Flask, render_template
import sqlite3 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__) app = Flask(__name__)
DB_PATH = "./gacha_game.db" # Adjust path if needed DB_PATH = config.DB_PATH
def get_db_connection(): def get_db_connection():
conn = sqlite3.connect(DB_PATH) conn = sqlite3.connect(DB_PATH)
@ -56,4 +62,4 @@ def submit_character():
if __name__ == '__main__': 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)