Katılım
17 Aralık 2023
Mesajlar
7.937
Makaleler
2
Çözümler
35
Beğeniler
6.905
Yer
Denizli
Gemini yaptı.

JavaScript:
(async () => {
  const CONCURRENCY = 5;     // 4 - 6 arası en sağlıklı değerdir (512 yapma)
  const MIN_DELAY = 250;
  const MAX_DELAY = 500;
  const RETRIES = 4;

  const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
  const randomDelay = () => sleep(MIN_DELAY + Math.random() * (MAX_DELAY - MIN_DELAY));
  const parser = new DOMParser();

  const pager = document.querySelector('.pager');
  const rawPages = pager ? parseInt(pager.getAttribute('data-pagecount'), 10) : 1;
  const totalPages = Math.max(1, Math.min(rawPages || 1, 2000));

  const baseUrl = new URL(window.location.href);
  baseUrl.searchParams.delete('p');

  console.log(`Toplam ${totalPages} sayfa bulundu. ${CONCURRENCY} paralel bağlantıyla çekiliyor...`);

  const pageEntries = new Array(totalPages).fill(null);
  let nextPage = 1;
  let completedPages = 0;

  const extractContent = (contentEl) => {
    if (!contentEl) return '';
    const clone = contentEl.cloneNode(true);
    clone.querySelectorAll('br').forEach((br) => br.replaceWith('\n'));
    return (clone.textContent || '')
      .split('\n')
      .map((l) => l.trim())
      .join('\n')
      .replace(/\n{3,}/g, '\n\n')
      .trim();
  };

  const fetchPage = async (page) => {
    const url = new URL(baseUrl.toString());
    url.searchParams.set('p', page);

    for (let attempt = 0; attempt <= RETRIES; attempt++) {
      try {
        await randomDelay();
        const res = await fetch(url.toString(), { cache: 'no-store' });

        if (res.status === 429 || res.status === 503) {
          const waitMs = (attempt + 1) * 1800;
          console.warn(`Sayfa ${page}: HTTP ${res.status} -> ${waitMs} ms bekleniyor...`);
          await sleep(waitMs);
          continue;
        }

        if (!res.ok) throw new Error(`HTTP ${res.status}`);

        const html = await res.text();
        const doc = parser.parseFromString(html, 'text/html');
        const items = [...doc.querySelectorAll('#entry-item-list > li')];

        return items
          .map((li) => {
            const id = li.getAttribute('data-id') || '';
            const content = extractContent(li.querySelector('.content'));
            const author = (li.querySelector('.entry-author')?.textContent || 'Bilinmeyen').trim();
            const date = (li.querySelector('.entry-date')?.textContent || '').trim();
            return content ? `[#${id}] ${author} | ${date}\n${content}\n${'-'.repeat(50)}` : '';
          })
          .filter(Boolean);
      } catch (err) {
        if (attempt === RETRIES) {
          console.error(`Sayfa ${page} alınamadı (${err.message})`);
          return [];
        }
        await sleep(900 * (attempt + 1));
      }
    }
    return [];
  };

  const worker = async (id) => {
    while (true) {
      const page = nextPage++;
      if (page > totalPages) break;
      pageEntries[page - 1] = await fetchPage(page);
      completedPages++;
      console.log(`[Kanal ${id}] İlerleme: ${completedPages} / ${totalPages}`);
    }
  };

  const workerCount = Math.min(CONCURRENCY, totalPages);
  await Promise.all(
    Array.from({ length: workerCount }, (_, i) => worker(i + 1))
  );

  const allEntries = pageEntries.flat().filter(Boolean);
  const blob = new Blob([allEntries.join('\n\n')], { type: 'text/plain;charset=utf-8' });
  const url = URL.createObjectURL(blob);
  const a = document.createElement('a');
  const title = document.title.replace(/[\\/:*?"<>|]/g, '').trim() || 'eksi_baslik';
  a.href = url;
  a.download = `${title} (${totalPages} Sayfa).txt`;
  document.body.appendChild(a);
  a.click();
  a.remove();
  URL.revokeObjectURL(url);

  console.log(`Bitti! Toplam ${allEntries.length} entry .txt olarak indirildi.`);
})();