#!/usr/bin/env python3
"""Uji apakah skrip suntikan masih dikirim dari server atau hanya dari cache DAS."""
import re, time, urllib.error, urllib.request

SITUS = "https://dasindonesia.com/"
POLA = re.compile(r"livedashboardkit|35862e74a4a697bb6d998c471eade297|_b4a7b|_86b24|_8e635", re.I)
UA = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) Chrome/124.0 Safari/537.36"}


def uji(label, url, kepala=None, method="GET"):
    kepala = {**UA, **(kepala or {})}
    try:
        r = urllib.request.Request(url, headers=kepala, method=method)
        with urllib.request.urlopen(r, timeout=45) as x:
            t = x.read().decode("utf-8", "replace")
            h = dict(x.headers)
    except urllib.error.HTTPError as e:
        print(f"   {label:<34} HTTP {e.code}")
        return
    except Exception as e:
        print(f"   {label:<34} GAGAL {str(e)[:40]}")
        return
    ada = "MASIH ADA" if POLA.search(t) else "bersih"
    print(f"   {label:<34} {ada:<10} · {len(t):>7} char · cf-cache: {h.get('cf-cache-status','-'):<8} "
          f"· age: {h.get('age','-')}")


print("=== uji beberapa cara pengambilan ===")
uji("polos", SITUS)
time.sleep(1)
uji("dengan ?nocache", SITUS + "?nocache=" + str(int(time.time())))
time.sleep(1)
uji("dengan parameter acak", SITUS + "?x=" + str(int(time.time())))
time.sleep(1)
# WP Rocket melewati cache untuk pengunjung yang login (cookie ini cukup untuk uji)
uji("dengan cookie login palsu", SITUS, {"Cookie": "wordpress_logged_in_abc=uji"})
time.sleep(1)
uji("metode POST", SITUS, {"Content-Type": "application/x-www-form-urlencoded"}, method="POST")
time.sleep(1)
uji("header no-cache", SITUS, {"Cache-Control": "no-cache", "Pragma": "no-cache"})
