File size: 6,201 Bytes
333c51a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
import { NextRequest, NextResponse } from "next/server";
import { db } from "@/lib/db";
import ZAI from "z-ai-web-dev-sdk";

// Reglas de censura por plataforma y categoría
const DEFAULT_CENSOR_RULES = [
  // YouTube
  { platform: "youtube", category: "nudity", rule: "No se permite desnudez ni contenido sexual", severity: "high", autoAction: "remove" },
  { platform: "youtube", category: "violence", rule: "Violencia gráfica no permitida sin advertencia", severity: "medium", autoAction: "warn" },
  { platform: "youtube", category: "hate_speech", rule: "No se permite discurso de odio", severity: "high", autoAction: "remove" },
  
  // TikTok
  { platform: "tiktok", category: "nudity", rule: "Cero tolerancia para desnudez", severity: "high", autoAction: "remove" },
  { platform: "tiktok", category: "violence", rule: "Sin violencia gráfica", severity: "high", autoAction: "remove" },
  { platform: "tiktok", category: "self_harm", rule: "No contenido de autolesión", severity: "high", autoAction: "remove" },
  { platform: "tiktok", category: "dangerous", rule: "No desafíos peligrosos", severity: "high", autoAction: "remove" },
  
  // Instagram
  { platform: "instagram", category: "nudity", rule: "No desnudez, excepto arte con moderación", severity: "high", autoAction: "blur" },
  { platform: "instagram", category: "violence", rule: "Sin violencia gráfica", severity: "high", autoAction: "remove" },
  
  // Twitter/X
  { platform: "twitter", category: "illegal", rule: "No contenido ilegal", severity: "high", autoAction: "remove" },
  { platform: "twitter", category: "sensitive", rule: "Marcar como contenido sensible", severity: "low", autoAction: "warn" },
];

// GET - Obtener reglas de censura
export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url);
    const platform = searchParams.get("platform");

    let rules;
    if (platform) {
      rules = await db.censorRule.findMany({
        where: { platform, isActive: true }
      });
      
      // Si no hay reglas en BD, usar las por defecto
      if (rules.length === 0) {
        rules = DEFAULT_CENSOR_RULES.filter(r => r.platform === platform);
      }
    } else {
      rules = await db.censorRule.findMany({
        where: { isActive: true }
      });
      
      if (rules.length === 0) {
        rules = DEFAULT_CENSOR_RULES;
      }
    }

    return NextResponse.json({
      success: true,
      rules
    });

  } catch (error) {
    console.error("Error fetching censor rules:", error);
    return NextResponse.json(
      { success: false, error: "Error al obtener reglas de censura" },
      { status: 500 }
    );
  }
}

// POST - Analizar contenido para censura
export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const { content, type, platform } = body;

    if (!content) {
      return NextResponse.json(
        { success: false, error: "Contenido requerido para análisis" },
        { status: 400 }
      );
    }

    const zai = await ZAI.create();

    // Usar IA para analizar el contenido
    const analysisPrompt = `Analiza el siguiente ${type || "contenido"} para verificar si cumple con las normas de la plataforma ${platform || "general"}.

Contenido a analizar:
${content.substring(0, 2000)}

Responde SOLO en formato JSON:
{
  "safe": true/false,
  "flags": [
    {"category": "categoría", "reason": "razón", "severity": "low/medium/high"}
  ],
  "recommendations": ["recomendación1", "recomendación2"],
  "platformCompatible": ["plataforma1", "plataforma2"]
}`;

    const completion = await zai.chat.completions.create({
      messages: [
        {
          role: "system",
          content: `Eres un moderador de contenido experto. Tu trabajo es analizar contenido para verificar si cumple con las políticas de diferentes plataformas. Sé estricto pero justo. Considera:

1. YouTube: Familiar, sin desnudez, violencia moderada con advertencia
2. TikTok: Para todos los públicos, sin contenido peligroso
3. Instagram: Sin desnudez (excepto arte), sin violencia gráfica
4. Twitter: Más permisivo pero marca contenido sensible
5. General: Apropiado para todo público`
        },
        { role: "user", content: analysisPrompt }
      ],
      temperature: 0.3,
    });

    const response = completion.choices[0]?.message?.content || "";
    
    // Parsear respuesta
    let analysis;
    try {
      const jsonMatch = response.match(/\{[\s\S]*\}/);
      if (jsonMatch) {
        analysis = JSON.parse(jsonMatch[0]);
      } else {
        analysis = {
          safe: true,
          flags: [],
          recommendations: [],
          platformCompatible: [platform || "general"]
        };
      }
    } catch {
      analysis = {
        safe: true,
        flags: [],
        recommendations: [],
        platformCompatible: [platform || "general"]
      };
    }

    return NextResponse.json({
      success: true,
      analysis,
      originalContent: content.substring(0, 200)
    });

  } catch (error) {
    console.error("Error analyzing content:", error);
    return NextResponse.json(
      { success: false, error: "Error al analizar contenido" },
      { status: 500 }
    );
  }
}

// PUT - Añadir regla de censura personalizada
export async function PUT(request: NextRequest) {
  try {
    const body = await request.json();
    const { platform, category, rule, severity, autoAction } = body;

    if (!platform || !category || !rule) {
      return NextResponse.json(
        { success: false, error: "Plataforma, categoría y regla son requeridos" },
        { status: 400 }
      );
    }

    const censorRule = await db.censorRule.create({
      data: {
        platform,
        category,
        rule,
        severity: severity || "medium",
        autoAction: autoAction || "warn"
      }
    });

    return NextResponse.json({
      success: true,
      rule: censorRule,
      message: "Regla de censura creada"
    });

  } catch (error) {
    console.error("Error creating censor rule:", error);
    return NextResponse.json(
      { success: false, error: "Error al crear regla de censura" },
      { status: 500 }
    );
  }
}