# This file is part of AutoDownloaderVedikaPDF. # Copyright (C) 2025 Andy Cahyono Putra # This program is distributed under the Aladdin Free Public License. # See LICENSE file for more information. import os import re import subprocess import tkinter as tk import tkinter.filedialog as filedialog import tkinter.messagebox as messagebox from tkinter import ttk from bs4 import BeautifulSoup from datetime import datetime, date, timedelta from config_loader import Config from SubModules import auth import mysql.connector import pyttsx3 import requests from playwright.sync_api import sync_playwright import sys import threading from typing import Optional if getattr(sys, "frozen", False): os.environ["PLAYWRIGHT_BROWSERS_PATH"] = os.path.join(sys._MEIPASS, "ms-playwright") cfg = Config() index_counter = {'current': 0} success_count = 0 fail_count = 0 lock = threading.Lock() class Color: RED = '\033[91m' GREEN = '\033[92m' RESET = '\033[0m' # ---------- UTIL DATES & FOLDERS ---------- def parse_ymd(s: str) -> date: return datetime.strptime(s, "%Y-%m-%d").date() def daterange(d1: date, d2: date): cur = d1 while cur <= d2: yield cur cur += timedelta(days=1) def ensure_daily_folders(base_folder: str, start_d: date, end_d: date): os.makedirs(base_folder, exist_ok=True) for d in daterange(start_d, end_d): sub = os.path.join(base_folder, d.strftime("%d")) os.makedirs(sub, exist_ok=True) def extract_date_from_no_rawat(no_rawat: str) -> Optional[date]: try: parts = no_rawat.split("/") if len(parts) < 3: return None y, m, d = int(parts[0]), int(parts[1]), int(parts[2]) return date(y, m, d) except Exception: return None def fetch_identifiers(tanggal_awal, tanggal_akhir): conn = mysql.connector.connect(host=cfg.Database.host, user=cfg.Database.user, password=cfg.Database.password, database=cfg.Database.database) cursor = conn.cursor() query = f""" SELECT no_rawat, tgl_registrasi FROM mlite_veronisa WHERE status = 'Pengajuan' AND tgl_registrasi BETWEEN '{tanggal_awal}' AND '{tanggal_akhir}' """ cursor.execute(query) results = cursor.fetchall() cursor.close() conn.close() return results def render_pdf_with_playwright(html_content, output_path): with sync_playwright() as p: browser = p.chromium.launch() page = browser.new_page() page.set_content(html_content, wait_until='networkidle') page.pdf(path=output_path, format='A4', print_background=True) browser.close() def generate_pdf(username, password, no_rawat, cookies, base_folder, urutan, total, reg_date: Optional[date] = None, max_retry=3): for attempt in range(1, max_retry + 1): try: modified_string = no_rawat.replace("/", "") url = f'{cfg.Url.mlite}/admin/veronisa/pdf/{modified_string}' headers = { 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7', 'Accept-Language': 'id-ID,id;q=0.9,en-US;q=0.8,en;q=0.7', 'Cache-Control': 'max-age=0', 'Connection': 'keep-alive', 'Content-Type': 'application/x-www-form-urlencoded', 'Cookie': cookies, 'DNT': '1', 'Origin': cfg.Url.mlite, 'Referer': cfg.Url.mlite, 'Upgrade-Insecure-Requests': '1', 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36' } payload = f'username={username}&password={password}&login=' response = requests.post(url, headers=headers, data=payload) html = response.text soup = BeautifulSoup(html, 'html.parser') no_sep_value = None no_sep_text = soup.find(text=re.compile(r'No[.\s]?SEP[::]?')) if no_sep_text: match = re.search(r'No\.SEP:\s*(\S+)', no_sep_text) if match: no_sep_value = match.group(1).replace('"', '') td_match_found = False if not no_sep_value: for td in soup.find_all('td'): txt = td.get_text(strip=True) if txt == no_rawat: td_match_found = True break if not no_sep_value and not td_match_found: if attempt == max_retry: path_gagal = os.path.join(base_folder, "Gagal_Download.txt") try: with open(path_gagal, "a", encoding="utf-8") as f: f.write(f"{no_rawat}\n") except Exception: pass return f"{Color.RED}[{urutan}/{total}] GAGAL (x{attempt}): Tidak ada No.SEP dan no_rawat tidak cocok untuk {no_rawat}{Color.RESET}", False continue # === Tentukan folder tujuan === if reg_date is not None: # Pakai HARI dari tgl_registrasi (01..31) target_dir = os.path.join(base_folder, reg_date.strftime("%d")) else: # Fallback: logika lama berdasarkan no_rawat d = extract_date_from_no_rawat(no_rawat) target_dir = base_folder if d is None else os.path.join(base_folder, d.strftime("%d")) os.makedirs(target_dir, exist_ok=True) if no_sep_value: filename = f"{no_sep_value}.pdf" else: filename = f"{modified_string}.pdf" final_pdf = os.path.join(target_dir, filename) temp_pdf = final_pdf.replace(".pdf", "_temp.pdf") render_pdf_with_playwright(html, temp_pdf) result = subprocess.run(['qpdf', '--decode-level=generalized', temp_pdf, final_pdf], capture_output=True, text=True) try: os.remove(temp_pdf) except Exception: pass if result.returncode != 0: if attempt == max_retry: return f"{Color.RED}[{urutan}/{total}] GAGAL : qpdf error untuk {no_sep_value}: {result.stderr}{Color.RESET}", False continue return f"{Color.GREEN}[{urutan}/{total}] PDF siap: {final_pdf}{Color.RESET}", True except Exception as e: if attempt == max_retry: return f"{Color.RED}[{urutan}/{total}] GAGAL : Error generate PDF {no_rawat}: {e}{Color.RESET}", False continue def worker(username, password, cookies, path_folder, results, total): global index_counter, success_count, fail_count for row in results: # row = (no_rawat, tgl_registrasi) no_rawat = row[0] tgl_registrasi = row[1] # Normalisasi reg_date menjadi date reg_date = None if isinstance(tgl_registrasi, date): reg_date = tgl_registrasi elif isinstance(tgl_registrasi, datetime): reg_date = tgl_registrasi.date() elif isinstance(tgl_registrasi, str): try: # sesuaikan format kalau DB kamu beda reg_date = datetime.strptime(tgl_registrasi, "%Y-%m-%d").date() except Exception: reg_date = None with lock: index_counter['current'] += 1 urutan = index_counter['current'] message, success = generate_pdf(username, password, no_rawat, cookies, path_folder, urutan, total, reg_date=reg_date) with lock: if success: success_count += 1 else: fail_count += 1 print(message) with lock: if index_counter['current'] == total: messagebox.showinfo("Info", f"Semua file telah diproses.\nTotal: {total} data\n" f"Berhasil: {success_count}\nGagal: {fail_count}") threading.Thread(target=reprocess_failed, args=(username, password, cookies, path_folder)).start() def reprocess_failed(username, password, cookies, path_folder): try: path_gagal = os.path.join(path_folder, "Gagal_Download.txt") if not os.path.exists(path_gagal): return with open(path_gagal, "r") as f: failed_rawats = [line.strip() for line in f if line.strip()] if not failed_rawats: return print(f"\nMulai ulang download untuk {len(failed_rawats)} file yang gagal...") open(path_gagal, "w").close() for i, no_rawat in enumerate(failed_rawats, start=1): message, success = generate_pdf( username, password, no_rawat, cookies, path_folder, urutan=f"R{i}", total=len(failed_rawats) ) print(message) messagebox.showinfo("Retry Selesai", "Proses ulang file gagal telah selesai.\nSilakan cek hasilnya.") except Exception as e: print(f"[Retry Error] {e}") def kembali_ke_menu(): app.destroy() subprocess.Popen([sys.executable, "main.py"]) def pilih_folder(): selected = filedialog.askdirectory() if selected: entry_folder.delete(0, 'end') # hapus isi lama entry_folder.insert(0, selected) def select_cookies(): file_selected = filedialog.askopenfilename(filetypes=[("Text files", "*.txt")]) if file_selected: entry_cookies.delete(0, 'end') entry_cookies.insert(0, file_selected) def ambil_cookies(): username = entry_username.get() password = entry_password.get() cookies = auth.auth(username, password) if cookies: entry_cookies.delete(0, 'end') entry_cookies.insert(0, cookies) messagebox.showinfo("Cookies", f"Cookies berhasil diambil:\n{cookies}") else: messagebox.showerror("Gagal", "Gagal mengambil cookies.") def process_files(): global index_counter, success_count, fail_count index_counter = {'current': 0} success_count = 0 fail_count = 0 tanggal_awal = entry_tanggal_awal.get().strip() tanggal_akhir = entry_tanggal_akhir.get().strip() cookies = entry_cookies.get() username = entry_username.get() password = entry_password.get() base_folder = entry_folder.get() try: d1 = parse_ymd(tanggal_awal) d2 = parse_ymd(tanggal_akhir) if d1 > d2: messagebox.showerror("Error", "Tanggal awal tidak boleh lebih besar dari tanggal akhir.") return except Exception: messagebox.showerror("Error", "Format tanggal harus YYYY-MM-DD.") return if cookies and os.path.isfile(cookies): try: with open(cookies, 'r') as File: cookies_content = File.read().strip() entry_cookies.delete(0, 'end') entry_cookies.insert(0, cookies_content) cookies = cookies_content except Exception as e: messagebox.showerror("Error", f"Gagal membaca cookies: {e}") return if not os.path.isdir(base_folder): messagebox.showerror("Error", "Folder tidak valid atau belum dipilih.") return ensure_daily_folders(base_folder, d1, d2) results = fetch_identifiers(tanggal_awal, tanggal_akhir) if not results: messagebox.showinfo("Info", "Tidak ada data untuk tanggal tersebut.") return total = len(results) chunks = [results[i::5] for i in range(5)] for chunk in chunks: threading.Thread(target=worker, args=(username, password, cookies, base_folder, chunk, total), daemon=True).start() app = tk.Tk() app.title("Downloader PDF Veronisa") app.geometry("500x400") tk.Label(app, text="Tanggal Awal (YYYY-MM-DD):").grid(row=0, column=0, sticky='e') entry_tanggal_awal = tk.Entry(app) entry_tanggal_awal.grid(row=0, column=1) tk.Label(app, text="Tanggal Akhir (YYYY-MM-DD):").grid(row=1, column=0, sticky='e') entry_tanggal_akhir = tk.Entry(app) entry_tanggal_akhir.grid(row=1, column=1) tk.Label(app, text="Username RS:").grid(row=2, column=0, sticky='e') entry_username = tk.Entry(app) entry_username.grid(row=2, column=1) tk.Label(app, text="Password RS:").grid(row=3, column=0, sticky='e') entry_password = tk.Entry(app, show='*') entry_password.grid(row=3, column=1) tk.Label(app, text="Folder Simpan PDF:").grid(row=4, column=0, sticky='e') entry_folder = tk.Entry(app) entry_folder.grid(row=4, column=1) ttk.Button(app, text="Pilih Folder", command=pilih_folder).grid(row=4, column=2) tk.Label(app, text="Cookies File:").grid(row=5, column=0, sticky='e') entry_cookies = tk.Entry(app) entry_cookies.grid(row=5, column=1) ttk.Button(app, text="Pilih Cookies", command=select_cookies).grid(row=5, column=2) ttk.Button(app, text="Ambil Cookies", command=ambil_cookies).grid(row=5, column=3) ttk.Button(app, text="Proses", command=process_files).grid(row=6, column=1, pady=20) ttk.Button(app, text="⬅ Kembali ke Menu Utama", command=kembali_ke_menu).grid(row=6, column=2, pady=20) app.mainloop()