File size: 4,315 Bytes
568802f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
const puppeteer = require('puppeteer');
const fetch = require('node-fetch');

/**

 * Logika utama Scraper & Generator

 */
async function generateHeartsync(prompt) {
  const browser = await puppeteer.launch({
    headless: true,
    executablePath: '/usr/bin/google-chrome-stable', // Path default di linux
    args: [
      '--no-sandbox',
      '--disable-setuid-sandbox',
      '--disable-dev-shm-usage',
      '--disable-accelerated-2d-canvas',
      '--no-first-run',
      '--no-zygote',
      '--single-process', // Penting untuk menghemat RAM di Space gratisan
      '--disable-gpu'
    ]
  });
  const page = await browser.newPage();

  return new Promise(async (resolve, reject) => {
    try {
      // 1. Bypass CroxyProxy
      await page.goto('https://www.croxyproxy.com/', { waitUntil: 'networkidle2' });
      const targetUrl = 'https://heartsync-nsfw-uncensored-photo.hf.space/';
      await page.waitForSelector('#url');
      await page.type('#url', targetUrl);

      await Promise.all([
        page.click('#requestSubmit'),
        page.waitForNavigation({ waitUntil: 'networkidle0' }),
      ]);

      await new Promise(r => setTimeout(r, 5000));

      // 2. Ekstraksi Sesi
      const currentUrl = page.url();
      const urlObj = new URL(currentUrl);
      const proxyBase = `${urlObj.protocol}//${urlObj.host}`;
      const cpoToken = urlObj.searchParams.get('__cpo');

      if (!cpoToken) throw new Error("Gagal mengambil token __cpo!");

      const cookies = await page.cookies();
      const cookieString = cookies.map(c => `${c.name}=${c.value}`).join('; ');
      const userAgent = await page.evaluate(() => navigator.userAgent);
      const session_hash = Math.random().toString(36).substring(2);

      const headers = {
        "Content-Type": "application/json",
        "Cookie": cookieString,
        "User-Agent": userAgent,
        "Referer": currentUrl,
        "Accept": "*/*"
      };

      // 3. Join Antrean (fn_index: 2 sesuai file test1.js)
      const joinRes = await fetch(`${proxyBase}/gradio_api/queue/join?__cpo=${cpoToken}`, {
        method: "POST",
        headers,
        body: JSON.stringify({
          data: [prompt, 1024, 1024, 18, 0, true, 4],
          fn_index: 2,
          trigger_id: 19,
          session_hash: session_hash
        })
      });

      const joinData = await joinRes.json();
      if (!joinData.event_id) throw new Error("Gagal join antrean!");

      // 4. Listen Stream Data
      const streamRes = await fetch(`${proxyBase}/gradio_api/queue/data?session_hash=${session_hash}&__cpo=${cpoToken}`, { headers });

      streamRes.body.on('data', (chunk) => {
        const lines = chunk.toString().split("\n\n");
        for (const line of lines) {
          if (!line.startsWith("data: ")) continue;

          try {
            const json = JSON.parse(line.replace("data: ", ""));

            if (json.msg === "process_completed") {
              if (json.success) {
                // Mapping URL hasil generate
                const urls = json.output.data[0].map(img => img.image?.url || img.url);
                browser.close();
                resolve(urls);
              } else {
                throw new Error(json.output.error || "Gagal proses di server Gradio.");
              }
            }
          } catch (e) {
            // Parsing error biasanya karena chunk data terpotong, biarkan sampai chunk berikutnya
          }
        }
      });

    } catch (err) {
      if (browser) await browser.close();
      reject(err);
    }
  });
}

// Export untuk sistem Plug-and-Play Fastify
module.exports = {
  path: '/huggingface1',
  method: 'GET',
  handler: async (request, reply) => {
    const { prompt } = request.query;

    if (!prompt) {
      return reply.status(400).send({ status: "error", message: "Query prompt harus diisi!" });
    }

    try {
      const images = await generateHeartsync(prompt);
      return {
        status: "success",
        plugin: "heartsync_v2",
        prompt: prompt,
        results: images
      };
    } catch (err) {
      return reply.status(500).send({
        status: "error",
        message: err.message
      });
    }
  }
};