aboutsummaryrefslogtreecommitdiffstats
path: root/cogs/conversion.py
blob: 6566ece2138ba4e3309d99effc7293b5eaa6dbd4 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
import discord
import requests
from discord.ext import commands
import logging
import os
import subprocess
import mimetypes

logger = logging.getLogger(__name__)

def filetype(filename):
    mime_type, _ = mimetypes.guess_type(filename)
    if mime_type:
        if mime_type.startswith('video/'):
            return "Video"
        elif mime_type.startswith('audio/'):
            return "Audio"
        elif mime_type.startswith('image/'):
            return "Image"
    return "Unknown"

class Conversion(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    @commands.slash_command(name="konwersja", description="konwertuj plik na inny format")
    @discord.option(
        "plik",
        description="plik do konwersji",
        required=True,
        type=discord.Attachment
    )
    @discord.option(
        "format",
        description="format konwersji",
        required=True,
        type=str
    )
    async def convert(self, ctx, plik, output_format, args):
        await ctx.defer()
        # Save files to the temp directory inside the bot's root directory
        bot_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
        temp_dir = os.path.join(bot_dir, "temp")
        if not os.path.exists(temp_dir):
            os.makedirs(temp_dir)
        file_path = os.path.join(temp_dir, plik.filename)
        filename_noext = os.path.splitext(plik.filename)[0]
        await plik.save(file_path)

        input_path = file_path
        output_path = os.path.join(temp_dir, f"{filename_noext}k.{output_format}")
        file_type = filetype(file_path)
        logger.info(f"Conversion started for: {file_type}")
        if file_type == "Video" or file_type == "Audio":
            # Execute ffmpeg command to compress video
            ffmpeg_command = f"ffmpeg -i {input_path} {args} {output_path}"
        elif file_type == "Image":
            img_command = f"magick {input_path} {args} {output_path}"
            ffmpeg_command = img_command
        else:
            await ctx.respond("Plik jest nieobsługiwany", ephemeral=True)
            logger.info("Unsupported file type")
            return

        try:
            subprocess.run(ffmpeg_command, check=True, shell=True)
            # Upload the compressed file
            if os.path.getsize(output_path) > 1024*1024*10:
                try:

                    # Upload to Copyparty
                    with open(output_path, 'rb') as f:
                        files = {
                            'f': (output_path, f, 'application/octet-stream')
                        }
                        headers = {
                            'Cookie': f'cppwd={os.getenv("COPYPARTY_PASSWORD")}'
                        }
                        params = {
                            'j': '1',  # Return JSON response
                            'ck': 'b2'  # Use blake2b checksum
                        }

                        # Ensure the URL ends with a single slash
                        base_url = "https://catbox.2137697.xyz/sperma/"

                        response = requests.post(
                            base_url,
                            files=files,
                            headers=headers,
                            params=params
                        )

                        if response.status_code == 200 or response.status_code == 201:
                            try:
                                result = response.json()
                                if 'fileurl' in result:
                                    dl_url = result['fileurl']
                                    await ctx.followup.send(
                                        f"wysyłon\n"
                                        f"{dl_url}\n"
                                    )
                                else:
                                    await ctx.followup.send(
                                        f"Odpowiedź serwera nie zawiera wymaganych danych: {result}")
                            except ValueError:
                                await ctx.followup.send(f"Nieprawidłowa odpowiedź z serwera: {response.text}")
                        else:
                            error_msg = response.text if response.text else 'Unknown error'
                            await ctx.followup.send(
                                f"nie udało się wysłać pliku (HTTP {response.status_code}): {error_msg}")

                except Exception as upload_error:
                    await ctx.followup.send(f"copyparty mnie nienawidzi :cccc\n {str(upload_error)}")
                    logger.error(f"copyparty upload error: {upload_error}", exc_info=True)
            else:
                await ctx.respond(file=discord.File(output_path))
            logger.info(f"Conversion completed for: {file_type}")
            # Delete compressed file
            os.remove(input_path)
            os.remove(output_path)
        except subprocess.CalledProcessError as e:
            await ctx.respond(f"Conversion failed: {str(e)}", ephemeral=True)
            if os.path.exists(input_path):
                os.remove(input_path)
            if os.path.exists(output_path):
                os.remove(output_path)

def setup(bot):
    bot.add_cog(Conversion(bot))