pleroma-support #56

Closed
waifu wants to merge 13 commits from pleroma-support into dev
4 changed files with 78 additions and 4 deletions
Showing only changes of commit 91376c0eba - Show all commits

View file

@ -51,6 +51,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

View file

@ -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

View file

@ -35,3 +35,6 @@ Token = abcdefghijklmnopqrstuvwxyz012345
; Instance type - either "misskey" or "pleroma"
InstanceType = misskey
; Web server port (default: 5000)
WebPort = 5000

View file

@ -1,10 +1,16 @@
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
from flask import Flask, render_template, abort
from werkzeug.exceptions import HTTPException
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)
@ -68,4 +74,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)