File size: 9,686 Bytes
6256f9a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
const express = require('express');
const axios = require('axios');
const cheerio = require('cheerio');

// Mengimpor library lain sesuai request kamu (walau belum dipakai di fungsi utama)
const path = require('path');
const FormData = require('form-data');
const fs = require('fs');
const crypto = require('crypto');
const { v4: uuidv4 } = require('uuid');
// const fetch = require('node-fetch');
// const { OpenAI } = require('openai');

const app = express();
const PORT = 7860; // Port Wajib untuk Hugging Face Spaces

class komiku {
    constructor() {
        this.baseUrl = 'https://komiku.org';
        this.headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
            'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8',
            'Accept-Language': 'id-ID,id;q=0.9,en-US;q=0.8,en;q=0.7',
            'Referer': 'https://komiku.org/',
            'Cache-Control': 'no-cache'
        };
    }

    async searchManga(query) {
        try {
            const response = await axios.get(`${this.baseUrl}/`, {
                params: { s: query, post_type: 'manga' },
                headers: this.headers
            });
            const $ = cheerio.load(response.data);
            const results = [];
            $('.daftar .bge, .daftar .kan, .list-update .bge').each((i, el) => {
                const title = $(el).find('.judul2 a, h3 a').text().trim();
                const url = $(el).find('.judul2 a, h3 a').attr('href');
                const image = $(el).find('img').attr('src');
                const type = $(el).find('.tipe, .type').text().trim();
                const description = $(el).find('p').text().trim();
                
                if (title && title.toLowerCase().includes(query.toLowerCase())) {
                    results.push({
                        title,
                        url: url ? (url.startsWith('http') ? url : this.baseUrl + url) : null,
                        image: image ? (image.startsWith('http') ? image : 'https:' + image) : null,
                        type: type || 'Manga',
                        description: description || 'No description available'
                    });
                }
            });
            return results;
        } catch (error) {
            console.error('Search error:', error.message);
            return [];
        }
    }

    async getMangaDetail(url) {
        try {
            const response = await axios.get(url, { headers: this.headers });
            const $ = cheerio.load(response.data);
            const title = $('#Judul h1 span').first().text().trim() || $('h1.entry-title').text().trim();
            const altTitle = $('.j2').text().trim().replace(':', '').trim();
            const cover = $('.ims img').attr('src') || $('.thumb img').attr('src');
            const author = $('.inftable tr:contains("Pengarang") td:last-child, .inftable tr:contains("Author") td:last-child').text().trim();
            const status = $('.inftable tr:contains("Status") td:last-child').text().trim();
            const type = $('.inftable tr:contains("Jenis Komik") td:last-child, .inftable tr:contains("Type") td:last-child').text().trim();
            const genres = [];
            
            $('.genre li a, .genres a').each((i, el) => {
                const genre = $(el).text().trim();
                if (genre && !genre.includes('Genre')) genres.push(genre);
            });

            const synopsis = $('.desc, .sinopsis, .entry-content p').first().text().trim();
            const chapters = [];
            
            $('#daftarChapter tr, .chapter-list li, .clstyle li').each((i, el) => {
                if (i === 0 && $(el).is('tr')) return;
                const chapterEl = $(el).find('.judulseries a, .chapter-title a, a');
                const chapterTitle = chapterEl.text().trim();
                const chapterUrl = chapterEl.attr('href');
                const views = $(el).find('.pembaca i, .views').text().trim();
                const date = $(el).find('.tanggalseries, .date').text().trim();
                
                if (chapterTitle && chapterUrl) {
                    chapters.push({
                        title: chapterTitle,
                        url: chapterUrl.startsWith('http') ? chapterUrl : this.baseUrl + chapterUrl,
                        views: views ? parseInt(views.replace(/[^0-9]/g, '')) || 0 : 0,
                        date: date || 'Unknown'
                    });
                }
            });

            chapters.sort((a, b) => {
                const numA = parseFloat(a.title.replace(/[^0-9.]/g, ''));
                const numB = parseFloat(b.title.replace(/[^0-9.]/g, ''));
                return numB - numA;
            });

            const firstChapterUrl = chapters.length > 0 ? chapters[chapters.length - 1].url : null;
            const latestChapterUrl = chapters.length > 0 ? chapters[0].url : null;

            return {
                title, altTitle: altTitle || title,
                cover: cover ? (cover.startsWith('http') ? cover : 'https:' + cover) : null,
                author: author || 'Unknown', status: status || 'Ongoing',
                type: type || 'Manga', genres: [...new Set(genres)],
                synopsis: synopsis || 'No synopsis available',
                chapters: chapters.slice(0, 10), totalChapters: chapters.length,
                firstChapterUrl, latestChapterUrl
            };
        } catch (error) {
            console.error('Detail error:', error.message);
            return null;
        }
    }

    async getChapterImages(url) {
        try {
            const response = await axios.get(url, { headers: this.headers });
            const $ = cheerio.load(response.data);
            const title = $('#Judul h1').text().trim() || $('h1.entry-title').text().trim();
            const seriesTitle = $('a[rel="tag"]').first().text().trim() || $('.series a').first().text().trim();
            const seriesUrl = $('a[rel="tag"]').first().attr('href') || $('.series a').first().attr('href');
            
            const images = [];
            $('#Baca_Komik img, .chapter-image img, .reader-area img').each((i, el) => {
                const imgUrl = $(el).attr('src') || $(el).attr('data-src') || $(el).attr('data-lazy-src');
                if (imgUrl && imgUrl.startsWith('http')) {
                    images.push({ url: imgUrl, page: i + 1, alt: $(el).attr('alt') || `Page ${i + 1}` });
                }
            });

            const prevChapter = $('a[aria-label="Prev"], a.prev, a:contains("Sebelumnya")').attr('href');
            const nextChapter = $('a[aria-label="Next"], a.next, a:contains("Selanjutnya")').attr('href');

            return {
                title: title || 'Unknown Chapter',
                series: {
                    title: seriesTitle || 'Unknown Series',
                    url: seriesUrl ? (seriesUrl.startsWith('http') ? seriesUrl : this.baseUrl + seriesUrl) : null
                },
                images: images.length > 0 ? images : [],
                totalImages: images.length,
                navigation: {
                    prev: prevChapter ? (prevChapter.startsWith('http') ? prevChapter : this.baseUrl + prevChapter) : null,
                    next: nextChapter ? (nextChapter.startsWith('http') ? nextChapter : this.baseUrl + nextChapter) : null
                }
            };
        } catch (error) {
            console.error('Chapter error:', error.message);
            return null;
        }
    }

    async getAll(query) {
        const search = await this.searchManga(query);
        if (search.length === 0) {
            const fallbackDetail = await this.getMangaDetail(`https://komiku.org/manga/${query}-id/`);
            if (fallbackDetail) {
                const chapter = await this.getChapterImages(fallbackDetail.latestChapterUrl);
                return {
                    query,
                    search: [{
                        title: fallbackDetail.title, url: `https://komiku.org/manga/${query}-id/`,
                        image: fallbackDetail.cover, type: fallbackDetail.type,
                        description: fallbackDetail.synopsis.substring(0, 200)
                    }],
                    detail: fallbackDetail, chapter
                };
            }
            return { query, search: [], detail: null, chapter: null, message: 'No results found' };
        }

        const mangaUrl = search[0].url;
        const detail = await this.getMangaDetail(mangaUrl);
        const chapter = detail ? await this.getChapterImages(detail.latestChapterUrl) : null;

        return { query, search: search.slice(0, 5), detail, chapter };
    }
}

const scraper = new komiku();

// Endpoint halaman utama
app.get('/', (req, res) => {
    res.send(`
        <h1>Scraper API is Running</h1>
        <p>Gunakan endpoint <code>/api/scrape?query=nama_komik</code></p>
        <p>Contoh: <a href="/api/scrape?query=boruto">/api/scrape?query=boruto</a></p>
    `);
});

// Endpoint untuk menjalankan scraper
app.get('/api/scrape', async (req, res) => {
    const query = req.query.query;
    
    if (!query) {
        return res.status(400).json({ error: "Parameter 'query' dibutuhkan!" });
    }

    try {
        const result = await scraper.getAll(query);
        res.json(result);
    } catch (error) {
        res.status(500).json({ error: error.message });
    }
});

// Start Server
app.listen(PORT, () => {
    console.log(`Server jalan di port ${PORT}`);
});