javascript oleh fazzcode 16 Sep 2026, 00.57

Tiktok Downloader

udah gitu aja simple

Kalo Mau Simple banget ya pake api aja : api.fazzcode.eu.cc

#!/usr/bin/env node
/**
 * SnapTik.fi — TikTok Downloader Scraper
 * 
 * Target : https://snaptik.fi/api/tiktok
 * Method : POST JSON
 * Body   : { url: "https://vt.tiktok.com/..." }
 *
 * Response: metadata + statistics + download links (no_watermark, watermark, mp3)
 *
 * Powered : FazzCodeID
 * RestApi : api.fazzcode.eu.cc
 */

import fs from "node:fs";
import path from "node:path";
import https from "node:https";
import http from "node:http";
import zlib from "node:zlib";
import { pathToFileURL } from "node:url";

// ============================================================
// KONFIGURASI
// ============================================================
const CONFIG = {
  ENDPOINT: "https://snaptik.fi/api/tiktok",
  TIMEOUT_MS: 30_000,
  DOWNLOAD_TIMEOUT_MS: 180_000,
  UA:
    "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 " +
    "(KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36",
  DEFAULT_OUT_DIR: "./downloads",
};

// ============================================================
// LOGGER
// ============================================================
const C = { reset: "\x1b[0m", dim: "\x1b[2m", green: "\x1b[32m", yellow: "\x1b[33m", red: "\x1b[31m", cyan: "\x1b[36m" };
const log = {
  info: (t, m) => console.error(`${C.dim}[${t}]${C.reset} ${m}`),
  ok:   (t, m) => console.error(`${C.green}[${t}]${C.reset} ${m}`),
  warn: (t, m) => console.error(`${C.yellow}[${t}]${C.reset} ${m}`),
  err:  (t, m) => console.error(`${C.red}[${t}]${C.reset} ${m}`),
  hit:  (t, m) => console.error(`${C.cyan}[${t}]${C.reset} ${m}`),
};

// ============================================================
// HTTP
// ============================================================
function request(urlStr, opts = {}) {
  const { method = "GET", headers = {}, body = null, timeout = CONFIG.TIMEOUT_MS, redirects = 5 } = opts;
  return new Promise((resolve, reject) => {
    const parsed = new URL(urlStr);
    const lib = parsed.protocol === "https:" ? https : http;
    const h = { "User-Agent": CONFIG.UA, "Accept-Language": "en-US,en;q=0.9", ...headers };
    const req = lib.request(
      {
        method,
        hostname: parsed.hostname,
        port: parsed.port || (parsed.protocol === "https:" ? 443 : 80),
        path: parsed.pathname + parsed.search,
        headers: h,
      },
      (res) => {
        if (redirects > 0 && res.statusCode >= 300 && res.statusCode < 400 && res.headers.location) {
          res.resume();
          return request(new URL(res.headers.location, urlStr).toString(), { ...opts, redirects: redirects - 1 }).then(resolve, reject);
        }
        const chunks = [];
        res.on("data", (c) => chunks.push(c));
        res.on("end", () => {
          let buf = Buffer.concat(chunks);
          // Handle gzip/deflate
          const enc = (res.headers["content-encoding"] || "").toLowerCase();
          try {
            if (enc === "gzip") buf = zlib.gunzipSync(buf);
            else if (enc === "deflate") buf = zlib.inflateSync(buf);
            else if (enc === "br") buf = zlib.brotliDecompressSync(buf);
          } catch {}
          resolve({
            status: res.statusCode,
            headers: res.headers,
            body: buf.toString("utf-8"),
            buffer: buf,
          });
        });
      }
    );
    req.on("error", reject);
    req.setTimeout(timeout, () => req.destroy(new Error(`Timeout ${timeout}ms`)));
    if (body) req.write(body);
    req.end();
  });
}

// ============================================================
// API CLIENT
// ============================================================
export async function fetchTikTok(url) {
  const body = JSON.stringify({ url });

  log.info("POST", `${CONFIG.ENDPOINT}`);
  log.info("BODY", JSON.stringify({ url }));
  const t0 = Date.now();

  const res = await request(CONFIG.ENDPOINT, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      Accept: "application/json, */*",
      Origin: "https://snaptik.fi",
      Referer: "https://snaptik.fi/",
    },
    body,
  });

  const timing = Date.now() - t0;

  if (res.status !== 200) {
    throw new Error(`HTTP ${res.status} - ${res.body.slice(0, 200)}`);
  }

  let data;
  try {
    data = JSON.parse(res.body);
  } catch (e) {
    throw new Error(`Parse JSON gagal: ${e.message}`);
  }

  log.ok("OK", `HTTP 200 (${timing}ms)`);

  return normalizeResponse(data, timing);
}

// ============================================================
// NORMALIZE RESPONSE
// ============================================================
function normalizeResponse(data, timing) {
  const result = {
    success: true,
    status: data.status || null,
    extract_source: data.extract_source || null,
    url: null,
    title: data.title || null,
    description: data.description || null,
    duration: data.duration || null,
    music_duration: data.music_duration || null,
    cover: data.cover || null,
    dynamic_cover: data.dynamic_cover || null,
    audio: data.audio || null,
    artist: data.artist || null,
    author: data.author
      ? {
          nickname: data.author.nickname || null,
          uniqueId: data.author.uniqueId || null,
          signature: data.author.signature || null,
          avatar: data.author.avatar || null,
        }
      : null,
    statistics: data.statistics
      ? {
          play_count: data.statistics.play_count ?? 0,
          digg_count: data.statistics.digg_count ?? 0,
          comment_count: data.statistics.comment_count ?? 0,
          share_count: data.statistics.share_count ?? 0,
        }
      : null,
    downloads: data.download_link
      ? {
          no_watermark: data.download_link.no_watermark || null,
          watermark: data.download_link.watermark || null,
          mp3: data.download_link.mp3 || null,
        }
      : { no_watermark: null, watermark: null, mp3: null },
    timing_ms: timing,
    raw: data,
  };

  // Sukses jika minimal ada 1 download link
  result.success = !!(
    result.downloads.no_watermark ||
    result.downloads.watermark ||
    result.downloads.mp3
  );

  return result;
}

// ============================================================
// DOWNLOAD
// ============================================================
export async function download(url, outPath) {
  log.info("DL", `Mengunduh ${path.basename(outPath)}...`);
  const t0 = Date.now();

  const res = await request(url, {
    timeout: CONFIG.DOWNLOAD_TIMEOUT_MS,
    headers: {
      Referer: "https://snaptik.fi/",
      Accept: "*/*",
    },
  });

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

  fs.mkdirSync(path.dirname(outPath), { recursive: true });
  fs.writeFileSync(outPath, res.buffer);

  const sizeKB = (res.buffer.length / 1024).toFixed(1);
  log.ok("DL", `${path.basename(outPath)} (${sizeKB} KB, ${Date.now() - t0}ms)`);
  return { path: outPath, size: res.buffer.length };
}

// ============================================================
// UTIL
// ============================================================
function sanitizeFilename(name) {
  return String(name || "tiktok")
    .replace(/[\/\\:*?"<>|]/g, "_")
    .replace(/\s+/g, " ")
    .trim()
    .slice(0, 80) || "tiktok";
}

function formatNumber(n) {
  if (n == null) return "-";
  if (n >= 1_000_000) return `${(n / 1_000_000).toFixed(1)}M`;
  if (n >= 1_000) return `${(n / 1_000).toFixed(1)}K`;
  return String(n);
}

function formatDuration(sec) {
  if (sec == null) return "-";
  const m = Math.floor(sec / 60);
  const s = sec % 60;
  return m > 0 ? `${m}m ${s}s` : `${s}s`;
}

// ============================================================
// CLI
// ============================================================
function printBanner(url) {
  console.error("╭──────────────────────────────────────────╮");
  console.error("│  SnapTik.fi TikTok Downloader            │");
  console.error("╰──────────────────────────────────────────╯");
  console.error(`  URL: ${url}\n`);
}

function printSummary(r) {
  console.error("");
  console.error(`${C.cyan}╭─────────────────────────────────────╮${C.reset}`);
  console.error(`${C.cyan}│           VIDEO INFO                │${C.reset}`);
  console.error(`${C.cyan}╰─────────────────────────────────────╯${C.reset}`);
  console.error(`  📝 Title      : ${r.title || "-"}`);
  console.error(`  👤 Author     : ${r.author?.nickname || "-"} (@${r.author?.uniqueId || "?"})`);
  console.error(`  ⏱️  Duration   : ${formatDuration(r.duration)}`);
  console.error(`  🎵 Music      : ${formatDuration(r.music_duration)}`);
  if (r.statistics) {
    console.error(`  👁️  Play       : ${formatNumber(r.statistics.play_count)}`);
    console.error(`  ❤️  Likes      : ${formatNumber(r.statistics.digg_count)}`);
    console.error(`  💬 Comments   : ${formatNumber(r.statistics.comment_count)}`);
    console.error(`  🔄 Shares     : ${formatNumber(r.statistics.share_count)}`);
  }
  console.error("");
  console.error(`  📥 Download links:`);
  console.error(`     • No Watermark : ${r.downloads.no_watermark ? "✅" : "❌"}`);
  console.error(`     • Watermark    : ${r.downloads.watermark ? "✅" : "❌"}`);
  console.error(`     • MP3          : ${r.downloads.mp3 ? "✅" : "❌"}`);
  console.error("");
}

function parseArgs(argv) {
  const args = argv.slice(2);
  const flags = { download: false, type: "no_watermark", outDir: CONFIG.DEFAULT_OUT_DIR };
  const positional = [];

  for (let i = 0; i < args.length; i++) {
    const a = args[i];
    if (a === "-d" || a === "--download") flags.download = true;
    else if (a === "-o" || a === "--out-dir") flags.outDir = args[++i];
    else if (a === "--type") flags.type = args[++i];
    else if (a.startsWith("--type=")) flags.type = a.slice(7);
    else if (a.startsWith("--out-dir=")) flags.outDir = a.slice(10);
    else if (a.startsWith("--json")) flags.json = true;
    else if (!a.startsWith("-")) positional.push(a);
  }
  return { positional, flags };
}

async function main() {
  const { positional, flags } = parseArgs(process.argv);

  if (positional.length === 0) {
    console.error("Usage:");
    console.error("  node filekamu.js <tiktok-url>");
    process.exit(1);
  }

  const url = positional[0];
  printBanner(url);

  const result = await fetchTikTok(url);

  // Output
  if (flags.json) {
    console.log(JSON.stringify(result, null, 2));
  } else {
    printSummary(result);
    console.log(JSON.stringify({
      success: result.success,
      title: result.title,
      author: result.author?.uniqueId,
      duration: result.duration,
      statistics: result.statistics,
      downloads: result.downloads,
    }, null, 2));
  }

  // Download
  if (flags.download && result.success) {
    const type = flags.type || "no_watermark";
    const dlUrl = result.downloads[type];
    if (!dlUrl) {
      log.err("DL", `Tipe "${type}" tidak tersedia`);
    } else {
      const ext = type === "mp3" ? "mp3" : "mp4";
      const baseName = sanitizeFilename(
        result.title || `tiktok_${result.author?.uniqueId || "video"}`
      );
      const filename = `${baseName}_${type}.${ext}`;
      const outPath = path.join(flags.outDir, filename);

      try {
        await download(dlUrl, outPath);
      } catch (e) {
        log.err("DL", e.message);
      }
    }
  }

  process.exit(result.success ? 0 : 1);
}

const isMain = process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href;
if (isMain) main().catch((e) => { console.error("Fatal:", e); process.exit(1); });
Discussion

Thread

Belum ada komentarJadilah yang pertama membuka diskusi.