1.0
This commit is contained in:
2
.gitignore
vendored
2
.gitignore
vendored
@@ -12,3 +12,5 @@
|
|||||||
# Built Visual Studio Code Extensions
|
# Built Visual Studio Code Extensions
|
||||||
*.vsix
|
*.vsix
|
||||||
|
|
||||||
|
SubModules/massinsert.py
|
||||||
|
SubModules/tes.py
|
||||||
|
|||||||
319
README.md
319
README.md
@@ -1,2 +1,319 @@
|
|||||||
# autodownloaderpdf
|
# AutoDownloaderPDF - JOBS EASIER
|
||||||
|
|
||||||
|
Aplikasi otomasi desktop untuk mengunduh, mengkonversi, dan mengunggah dokumen PDF secara massal dari berbagai sistem online. Tool ini dirancang untuk mempermudah pekerjaan administratif dengan otomasi proses yang berulang-ulang.
|
||||||
|
|
||||||
|
## 📋 Daftar Isi
|
||||||
|
|
||||||
|
- [Fitur Utama](#fitur-utama)
|
||||||
|
- [Persyaratan Sistem](#persyaratan-sistem)
|
||||||
|
- [Instalasi](#instalasi)
|
||||||
|
- [Konfigurasi](#konfigurasi)
|
||||||
|
- [Penggunaan](#penggunaan)
|
||||||
|
- [Struktur Proyek](#struktur-proyek)
|
||||||
|
- [Modul-Modul Tersedia](#modul-modul-tersedia)
|
||||||
|
- [Lisensi](#lisensi)
|
||||||
|
|
||||||
|
## ✨ Fitur Utama
|
||||||
|
|
||||||
|
- **Download Otomatis**: Mengunduh dokumen dari berbagai website secara otomatis
|
||||||
|
- **Konversi PDF**: Mengonversi dokumen ke format PDF dengan rendering browser modern
|
||||||
|
- **Autentikasi Terpusat**: Mengelola login ke multiple sistem (MLite, JKN, dll)
|
||||||
|
- **Operasi Massal**: Mendukung bulk insert dan bulk upload untuk efisiensi
|
||||||
|
- **Upload Terintegrasi**: Mengunggah file yang sudah diproses ke sistem tujuan
|
||||||
|
- **GUI Intuitif**: Antarmuka Tkinter yang user-friendly
|
||||||
|
- **Konfigurasi Fleksibel**: File konfigurasi terpusat untuk kemudahan setup
|
||||||
|
- **Multi-threading**: Dukungan proses paralel untuk performa optimal
|
||||||
|
- **Text-to-Speech Notifications**: Notifikasi audio untuk status operasi
|
||||||
|
|
||||||
|
## 🖥️ Persyaratan Sistem
|
||||||
|
|
||||||
|
### Software Requirements
|
||||||
|
- **Python**: 3.8 atau lebih baru
|
||||||
|
- **OS**: Windows (Primary), Linux/Mac (Partial Support)
|
||||||
|
- **Database**: MySQL/MariaDB
|
||||||
|
|
||||||
|
### Hardware Requirements
|
||||||
|
- RAM: Minimal 2GB (4GB disarankan)
|
||||||
|
- Storage: Minimal 1GB untuk operasi dan cache
|
||||||
|
- Internet: Koneksi stabil diperlukan
|
||||||
|
|
||||||
|
## 📦 Instalasi
|
||||||
|
|
||||||
|
### 1. Clone Repository
|
||||||
|
```bash
|
||||||
|
git clone <repository-url>
|
||||||
|
cd autodownloaderpdf
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2. Buat Virtual Environment (Recommended)
|
||||||
|
```bash
|
||||||
|
python -m venv venv
|
||||||
|
|
||||||
|
# Windows
|
||||||
|
venv\Scripts\activate
|
||||||
|
|
||||||
|
# Linux/Mac
|
||||||
|
source venv/bin/activate
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3. Install Dependencies
|
||||||
|
```bash
|
||||||
|
pip install -r requirements.txt
|
||||||
|
```
|
||||||
|
|
||||||
|
Packages yang diinstal:
|
||||||
|
- **beautifulsoup4**: Web scraping dan parsing HTML
|
||||||
|
- **requests**: HTTP client untuk API calls
|
||||||
|
- **mysql-connector-python**: Koneksi database MySQL
|
||||||
|
- **requests-toolbelt**: Utility untuk HTTP requests
|
||||||
|
- **pyttsx3**: Text-to-speech engine
|
||||||
|
- **playwright**: Browser automation untuk rendering PDF
|
||||||
|
|
||||||
|
### 4. Setup qPDF (REQUIRED)
|
||||||
|
qPDF adalah PDF manipulation utility yang digunakan untuk konversi dan manipulasi file PDF. Instalasi:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Windows (menggunakan Chocolatey)
|
||||||
|
choco install qpdf
|
||||||
|
|
||||||
|
# Linux (Ubuntu/Debian)
|
||||||
|
sudo apt-get install qpdf
|
||||||
|
|
||||||
|
# Linux (Fedora/RHEL)
|
||||||
|
sudo dnf install qpdf
|
||||||
|
|
||||||
|
# Mac
|
||||||
|
brew install qpdf
|
||||||
|
```
|
||||||
|
|
||||||
|
Jika Chocolatey belum terinstall, install terlebih dahulu dengan membuka Command Prompt (Run as Administrator) dan jalankan:
|
||||||
|
```bash
|
||||||
|
@"%SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe" -NoProfile -InputFormat None -ExecutionPolicy Bypass -Command "[System.Net.ServicePointManager]::SecurityProtocol = 3072; iex ((New-Object System.Net.WebClient).DownloadString('https://community.chocolatey.org/install.ps1'))" && SET "PATH=%PATH%;%ALLUSERSPROFILE%\chocolatey\bin"
|
||||||
|
```
|
||||||
|
|
||||||
|
## ⚙️ Konfigurasi
|
||||||
|
|
||||||
|
### File Konfigurasi (app.config)
|
||||||
|
|
||||||
|
Buat file `app.config` di root directory dengan struktur berikut:
|
||||||
|
|
||||||
|
```ini
|
||||||
|
[Database]
|
||||||
|
Host = localhost
|
||||||
|
Port = 3306
|
||||||
|
Database = your_database_name
|
||||||
|
User = your_db_user
|
||||||
|
Password = your_db_password
|
||||||
|
|
||||||
|
[Paths]
|
||||||
|
base_path = /path/to/downloads
|
||||||
|
|
||||||
|
[Url]
|
||||||
|
jknurl = https://jkn.example.com
|
||||||
|
mlite = https://mlite.example.com
|
||||||
|
|
||||||
|
[UserPass]
|
||||||
|
USERNAME = admin_username
|
||||||
|
PASSWORD = admin_password
|
||||||
|
```
|
||||||
|
|
||||||
|
### Load Konfigurasi dalam Code
|
||||||
|
```python
|
||||||
|
from config_loader import Config
|
||||||
|
|
||||||
|
cfg = Config('app.config')
|
||||||
|
print(cfg.Database.host)
|
||||||
|
print(cfg.Url.jkn)
|
||||||
|
```
|
||||||
|
|
||||||
|
## 🚀 Penggunaan
|
||||||
|
|
||||||
|
### Menjalankan Aplikasi
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Jalankan dari command line
|
||||||
|
python main.py
|
||||||
|
|
||||||
|
# Atau jika menggunakan executable (hasil build PyInstaller)
|
||||||
|
JOBS_EASIER.exe
|
||||||
|
```
|
||||||
|
|
||||||
|
### Workflow Dasar
|
||||||
|
|
||||||
|
1. **Autentikasi**: Login ke sistem yang diperlukan (MLite, JKN, dll)
|
||||||
|
2. **Pilih Operasi**: Tentukan jenis operasi yang ingin dilakukan
|
||||||
|
3. **Konfigurasi Parameter**: Sesuaikan pengaturan sesuai kebutuhan
|
||||||
|
4. **Jalankan Proses**: Mulai download/upload dengan monitoring real-time
|
||||||
|
5. **Review Hasil**: Cek status dan log untuk verifikasi
|
||||||
|
|
||||||
|
## 📁 Struktur Proyek
|
||||||
|
|
||||||
|
```
|
||||||
|
autodownloaderpdf/
|
||||||
|
├── main.py # Entry point aplikasi
|
||||||
|
├── config_loader.py # Module untuk load konfigurasi
|
||||||
|
├── app.config # File konfigurasi (buat sendiri)
|
||||||
|
├── requirements.txt # Python dependencies
|
||||||
|
├── LICENSE # Aladdin Free Public License
|
||||||
|
├── README.md # Dokumentasi ini
|
||||||
|
└── SubModules/
|
||||||
|
├── __init__.py
|
||||||
|
├── auth.py # Autentikasi ke berbagai sistem
|
||||||
|
├── veronisa.py # Download dan konversi PDF
|
||||||
|
├── ralan.py # Upload dengan processing
|
||||||
|
├── ralannoupload.py # Processing tanpa upload (Ralan)
|
||||||
|
├── ranap.py # Upload ke sistem RANAP
|
||||||
|
├── ranapnoupload.py # Processing tanpa upload (RANAP)
|
||||||
|
├── massinsert.py # Bulk insert ke database
|
||||||
|
├── massupload.py # Bulk upload ke sistem
|
||||||
|
└── tes.py # Module testing
|
||||||
|
```
|
||||||
|
|
||||||
|
## 🔧 Modul-Modul Tersedia
|
||||||
|
|
||||||
|
### `auth.py` - Autentikasi
|
||||||
|
Menangani login dan manajemen session ke berbagai sistem:
|
||||||
|
- Login ke MLite
|
||||||
|
- Login ke JKN
|
||||||
|
- Manajemen cookies
|
||||||
|
- Penyimpanan credentials terenkripsi
|
||||||
|
|
||||||
|
```python
|
||||||
|
from SubModules import auth
|
||||||
|
|
||||||
|
cookies = auth.auth(username, password)
|
||||||
|
auth.save_cookies_to_file(cookies)
|
||||||
|
```
|
||||||
|
|
||||||
|
### `veronisa.py` - Download & Konversi PDF
|
||||||
|
Fungsi utama untuk download dokumen dan konversi ke PDF:
|
||||||
|
- Web scraping menggunakan BeautifulSoup
|
||||||
|
- Render PDF menggunakan Playwright
|
||||||
|
- Multi-threading untuk performa
|
||||||
|
- Parse tanggal dan folder management
|
||||||
|
|
||||||
|
```python
|
||||||
|
from SubModules import veronisa
|
||||||
|
|
||||||
|
# Jalankan proses download dan konversi
|
||||||
|
veronisa.main_process(start_date, end_date)
|
||||||
|
```
|
||||||
|
|
||||||
|
### `ralan.py` - Upload RALAN
|
||||||
|
Mengunggah dokumen RALAN ke sistem:
|
||||||
|
- Login guest ke JKN
|
||||||
|
- Upload file dengan multipart encoding
|
||||||
|
- Validasi dan error handling
|
||||||
|
|
||||||
|
### `ralannoupload.py` - Processing RALAN (Tanpa Upload)
|
||||||
|
Processing dokumen RALAN tanpa mengunggah hasil
|
||||||
|
|
||||||
|
### `ranap.py` - Upload RANAP
|
||||||
|
Mengunggah dokumen RANAP ke sistem target
|
||||||
|
|
||||||
|
### `ranapnoupload.py` - Processing RANAP (Tanpa Upload)
|
||||||
|
Processing dokumen RANAP tanpa mengunggah hasil
|
||||||
|
|
||||||
|
### `massinsert.py` - Bulk Insert Database
|
||||||
|
Memasukkan data secara massal ke database MySQL
|
||||||
|
|
||||||
|
### `massupload.py` - Bulk Upload Otomatis
|
||||||
|
Mengunggah multiple file dalam satu operasi
|
||||||
|
|
||||||
|
### `tes.py` - Testing Module
|
||||||
|
Module untuk testing dan debugging fitur-fitur
|
||||||
|
|
||||||
|
## 🔐 Keamanan
|
||||||
|
|
||||||
|
- Simpan `app.config` dengan permission terbatas
|
||||||
|
- Jangan simpan password dalam source code
|
||||||
|
- Gunakan environment variables untuk credentials penting
|
||||||
|
- Encrypt cookies sebelum menyimpan di file
|
||||||
|
- Validate user input sebelum diproses
|
||||||
|
|
||||||
|
## 📊 Database Connection
|
||||||
|
|
||||||
|
Aplikasi ini menggunakan MySQL untuk penyimpanan data. Pastikan:
|
||||||
|
|
||||||
|
1. MySQL server sudah berjalan
|
||||||
|
2. Database sudah dibuat dengan schema yang sesuai
|
||||||
|
3. User MySQL memiliki permission yang tepat
|
||||||
|
4. Konfigurasi koneksi sudah benar di `app.config`
|
||||||
|
|
||||||
|
```python
|
||||||
|
import mysql.connector
|
||||||
|
|
||||||
|
# Koneksi otomatis via config_loader
|
||||||
|
conn = mysql.connector.connect(
|
||||||
|
host=cfg.Database.host,
|
||||||
|
user=cfg.Database.user,
|
||||||
|
password=cfg.Database.password,
|
||||||
|
database=cfg.Database.database
|
||||||
|
)
|
||||||
|
```
|
||||||
|
|
||||||
|
## 🐛 Troubleshooting
|
||||||
|
|
||||||
|
### Error: "Module not found"
|
||||||
|
```bash
|
||||||
|
pip install -r requirements.txt
|
||||||
|
```
|
||||||
|
|
||||||
|
### Error: "Config file not found"
|
||||||
|
- Pastikan `app.config` ada di direktori root
|
||||||
|
- Periksa path dan nama file
|
||||||
|
|
||||||
|
### Error: "Database connection failed"
|
||||||
|
- Verifikasi MySQL server berjalan
|
||||||
|
- Cek kredensial di `app.config`
|
||||||
|
- Pastikan database dan user sudah dibuat
|
||||||
|
|
||||||
|
### Error: "Browser/Playwright issue"
|
||||||
|
```bash
|
||||||
|
playwright install
|
||||||
|
```
|
||||||
|
|
||||||
|
### GUI tidak muncul di Linux
|
||||||
|
- Pastikan dependencies GUI sudah terinstall
|
||||||
|
- Coba jalankan dengan display yang sesuai: `DISPLAY=:0 python main.py`
|
||||||
|
|
||||||
|
## 🤝 Kontribusi
|
||||||
|
|
||||||
|
Untuk berkontribusi pada proyek ini:
|
||||||
|
|
||||||
|
1. Fork repository
|
||||||
|
2. Buat feature branch (`git checkout -b feature/AmazingFeature`)
|
||||||
|
3. Commit changes (`git commit -m 'Add some AmazingFeature'`)
|
||||||
|
4. Push ke branch (`git push origin feature/AmazingFeature`)
|
||||||
|
5. Buat Pull Request
|
||||||
|
|
||||||
|
## 📄 Lisensi
|
||||||
|
|
||||||
|
Proyek ini didistribusikan di bawah **Aladdin Free Public License (AFPL)**.
|
||||||
|
|
||||||
|
Lihat file [LICENSE](LICENSE) untuk informasi detail.
|
||||||
|
|
||||||
|
**Copyright © 2025 Andy Cahyono Putra**
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 📞 Dukungan
|
||||||
|
|
||||||
|
Untuk pertanyaan atau issue, silakan:
|
||||||
|
- Buka issue di repository
|
||||||
|
- Hubungi maintainer proyek
|
||||||
|
- Cek dokumentasi dan FAQ
|
||||||
|
|
||||||
|
## 📝 Changelog
|
||||||
|
|
||||||
|
### Version 1.0.0
|
||||||
|
- Initial release
|
||||||
|
- Core features: Download, Convert, Upload
|
||||||
|
- Multi-module architecture
|
||||||
|
- GUI implementation
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
**Last Updated**: 2026-03-06
|
||||||
|
**Status**: Active Development
|
||||||
|
|
||||||
|
|||||||
0
SubModules/__init__.py
Normal file
0
SubModules/__init__.py
Normal file
84
SubModules/auth.py
Normal file
84
SubModules/auth.py
Normal file
@@ -0,0 +1,84 @@
|
|||||||
|
# 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 requests
|
||||||
|
import json
|
||||||
|
import tkinter as tk
|
||||||
|
import tkinter.filedialog as filedialog
|
||||||
|
import tkinter.messagebox as messagebox
|
||||||
|
from tkinter import ttk
|
||||||
|
from config_loader import Config
|
||||||
|
|
||||||
|
cfg = Config()
|
||||||
|
|
||||||
|
def get_site_cookie(session):
|
||||||
|
# Fungsi ini harus mengembalikan cookie awal yang diperlukan untuk autentikasi
|
||||||
|
try:
|
||||||
|
response = session.get(f'{cfg.Url.mlite}/admin/')
|
||||||
|
return response.cookies.get_dict() # Mengembalikan cookie sebagai dictionary
|
||||||
|
except Exception as e:
|
||||||
|
return str(e)
|
||||||
|
|
||||||
|
def auth(username, password):
|
||||||
|
try:
|
||||||
|
url = f'{cfg.Url.mlite}/admin/'
|
||||||
|
payload = {
|
||||||
|
'username': username,
|
||||||
|
'password': password,
|
||||||
|
'login': ''
|
||||||
|
}
|
||||||
|
|
||||||
|
with requests.Session() as session:
|
||||||
|
initial_cookies = get_site_cookie(session)
|
||||||
|
if isinstance(initial_cookies, dict):
|
||||||
|
response = session.post(url, data=payload)
|
||||||
|
if response.ok: # Memeriksa apakah permintaan berhasil
|
||||||
|
cookies = session.cookies.get_dict()
|
||||||
|
return cookies
|
||||||
|
else:
|
||||||
|
return f"Authentication failed: {response.status_code} {response.reason}"
|
||||||
|
else:
|
||||||
|
return initial_cookies
|
||||||
|
except Exception as e:
|
||||||
|
return str(e)
|
||||||
|
|
||||||
|
def save_cookies_to_file(cookies):
|
||||||
|
try:
|
||||||
|
cookie_list = []
|
||||||
|
for key, value in cookies.items():
|
||||||
|
cookie_dict = {
|
||||||
|
"domain": "192.168.1.50", # Ganti dengan domain yang sesuai
|
||||||
|
"hostOnly": True,
|
||||||
|
"httpOnly": False,
|
||||||
|
"name": key,
|
||||||
|
"path": "/",
|
||||||
|
"sameSite": "unspecified",
|
||||||
|
"secure": False,
|
||||||
|
"session": True,
|
||||||
|
"storeId": "0",
|
||||||
|
"value": value
|
||||||
|
}
|
||||||
|
cookie_list.append(cookie_dict)
|
||||||
|
|
||||||
|
# Menyimpan dalam format JSON
|
||||||
|
with open("cookie.txt", "w") as file:
|
||||||
|
json.dump(cookie_list, file, indent=4)
|
||||||
|
|
||||||
|
messagebox.showinfo("Success", "Cookies saved to cookie.txt")
|
||||||
|
except Exception as e:
|
||||||
|
messagebox.showerror("Error", str(e))
|
||||||
|
|
||||||
|
def process():
|
||||||
|
try:
|
||||||
|
username = entry_username.get()
|
||||||
|
password = entry_password.get()
|
||||||
|
cookies = auth(username, password)
|
||||||
|
|
||||||
|
if isinstance(cookies, dict):
|
||||||
|
save_cookies_to_file(cookies)
|
||||||
|
else:
|
||||||
|
messagebox.showerror("Error", cookies)
|
||||||
|
except Exception as e:
|
||||||
|
messagebox.showerror("Error", str(e))
|
||||||
460
SubModules/massupload.py
Normal file
460
SubModules/massupload.py
Normal file
@@ -0,0 +1,460 @@
|
|||||||
|
# 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 requests
|
||||||
|
from datetime import datetime
|
||||||
|
import xml.etree.ElementTree as ET
|
||||||
|
import os
|
||||||
|
from urllib.parse import quote_plus
|
||||||
|
from requests_toolbelt.multipart.encoder import MultipartEncoder
|
||||||
|
import pickle
|
||||||
|
from queue import Queue
|
||||||
|
from config_loader import Config
|
||||||
|
import tkinter as tk
|
||||||
|
import tkinter.filedialog as filedialog
|
||||||
|
import tkinter.messagebox as messagebox
|
||||||
|
from tkinter import ttk
|
||||||
|
import threading
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
import time
|
||||||
|
|
||||||
|
if getattr(sys, "frozen", False):
|
||||||
|
os.environ["PLAYWRIGHT_BROWSERS_PATH"] = os.path.join(sys._MEIPASS, "ms-playwright")
|
||||||
|
|
||||||
|
|
||||||
|
cfg = Config()
|
||||||
|
|
||||||
|
def get_epochtimes():
|
||||||
|
return int(datetime.now().timestamp())
|
||||||
|
|
||||||
|
def save_session(session, filename='session.pkl'):
|
||||||
|
with open(filename, 'wb') as f:
|
||||||
|
pickle.dump(session.cookies.get_dict(), f)
|
||||||
|
|
||||||
|
|
||||||
|
def load_session(session, filename='session.pkl'):
|
||||||
|
if os.path.exists(filename):
|
||||||
|
with open(filename, 'rb') as f:
|
||||||
|
try:
|
||||||
|
cookies_dict = pickle.load(f)
|
||||||
|
if isinstance(cookies_dict, dict):
|
||||||
|
session.cookies.update(cookies_dict)
|
||||||
|
return True
|
||||||
|
else:
|
||||||
|
print("[ERROR] Data session bukan dictionary. Menghapus file session...")
|
||||||
|
except Exception as e:
|
||||||
|
print(f"[ERROR] Gagal memuat session: {e}. File akan dihapus.")
|
||||||
|
try:
|
||||||
|
os.remove(filename)
|
||||||
|
print("[INFO] File session rusak telah dihapus.")
|
||||||
|
except Exception as e:
|
||||||
|
print(f"[ERROR] Gagal menghapus file session: {e}")
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def is_session_valid(session, headers):
|
||||||
|
try:
|
||||||
|
response = session.post(
|
||||||
|
f"{cfg.Url.jkn}/core/getfilelist?time={get_epochtimes()}",
|
||||||
|
headers=headers,
|
||||||
|
data="path=/SHARED&start=0&limit=1"
|
||||||
|
)
|
||||||
|
if response.status_code == 200 and "<entry>" in response.text:
|
||||||
|
return True
|
||||||
|
except Exception as e:
|
||||||
|
print(f"[ERROR] Cek sesi gagal: {e}")
|
||||||
|
return False
|
||||||
|
|
||||||
|
def login_guest(session, username, password, headers):
|
||||||
|
epoch = get_epochtimes()
|
||||||
|
endpoint = f"{cfg.Url.jkn}/core/loginguest?time={epoch}"
|
||||||
|
payload = f"userid={username}&password={password}&passwordType=password&g-recaptcha-response=&tfa=1"
|
||||||
|
response = session.post(endpoint, headers=headers, data=payload)
|
||||||
|
if response.status_code == 200:
|
||||||
|
try:
|
||||||
|
root = ET.fromstring(response.text)
|
||||||
|
message = root.find('.//message')
|
||||||
|
if message is not None:
|
||||||
|
return message.text
|
||||||
|
except ET.ParseError as e:
|
||||||
|
print(f"[XML ERROR] {e}")
|
||||||
|
else:
|
||||||
|
print(f"[HTTP ERROR] {response.status_code}")
|
||||||
|
return None
|
||||||
|
|
||||||
|
def login_2fa(session, username, token_message, token_2fa, headers):
|
||||||
|
epoch = get_epochtimes()
|
||||||
|
endpoint = f"{cfg.Url.jkn}/core/2falogin?time={epoch}"
|
||||||
|
payload = f"userid={username}&code={token_2fa}&token={token_message}&tfa=1"
|
||||||
|
response = session.post(endpoint, headers=headers, data=payload)
|
||||||
|
if response.status_code == 200:
|
||||||
|
try:
|
||||||
|
root = ET.fromstring(response.text)
|
||||||
|
result = root.find('.//result')
|
||||||
|
return result.text == '1'
|
||||||
|
except ET.ParseError as e:
|
||||||
|
print(f"[XML ERROR] {e}")
|
||||||
|
else:
|
||||||
|
print(f"[HTTP ERROR] {response.status_code}")
|
||||||
|
return False
|
||||||
|
|
||||||
|
def get_sharedfolder(session, path, headers):
|
||||||
|
epoch = get_epochtimes()
|
||||||
|
endpoint = f"{cfg.Url.jkn}/core/getfilelist?time={epoch}"
|
||||||
|
payload = f"path={path}&start=0&limit=100&sendcommentinfo=1&sendmetadatasetinfo=1&search=&sortby=name&sortdir=1&sendfavinfo=1&sendaboutinfo=1"
|
||||||
|
response = session.post(endpoint, headers=headers, data=payload)
|
||||||
|
|
||||||
|
if response.status_code == 200:
|
||||||
|
try:
|
||||||
|
root = ET.fromstring(response.text)
|
||||||
|
entries = []
|
||||||
|
for entry in root.findall('.//entry'):
|
||||||
|
entry_type = entry.find('type')
|
||||||
|
name = entry.find('name')
|
||||||
|
fullpath = entry.find('path')
|
||||||
|
if entry_type is not None and entry_type.text == 'dir' and name is not None and fullpath is not None:
|
||||||
|
entries.append({'name': name.text, 'path': fullpath.text})
|
||||||
|
return entries
|
||||||
|
except ET.ParseError as e:
|
||||||
|
print(f"[XML ERROR] {e}")
|
||||||
|
else:
|
||||||
|
print(f"[HTTP ERROR] {response.status_code}")
|
||||||
|
return []
|
||||||
|
|
||||||
|
def navigate_folder(session, current_path, headers):
|
||||||
|
while True:
|
||||||
|
folders = get_sharedfolder(session, current_path, headers)
|
||||||
|
if not folders:
|
||||||
|
print(f"[INFO] Tidak ada folder di {current_path}")
|
||||||
|
return current_path
|
||||||
|
|
||||||
|
print(f"\n[ISI FOLDER: {current_path}]:")
|
||||||
|
for idx, folder in enumerate(folders, 1):
|
||||||
|
print(f"{idx}. {folder['name']}")
|
||||||
|
print("0. Pilih folder ini")
|
||||||
|
|
||||||
|
try:
|
||||||
|
choice = int(input("Pilih nomor folder untuk masuk, atau 0 untuk pilih folder ini: "))
|
||||||
|
if choice == 0:
|
||||||
|
return current_path
|
||||||
|
elif 1 <= choice <= len(folders):
|
||||||
|
selected = folders[choice - 1]
|
||||||
|
current_path = selected['path']
|
||||||
|
else:
|
||||||
|
print("[ERROR] Pilihan tidak valid.")
|
||||||
|
except ValueError:
|
||||||
|
print("[ERROR] Input harus berupa angka.")
|
||||||
|
|
||||||
|
def preload_js_assets(session):
|
||||||
|
js1 = "https://jkn-drive.bpjs-kesehatan.go.id/ui/core/js/9858.2fe9443a.js"
|
||||||
|
js2 = "https://jkn-drive.bpjs-kesehatan.go.id/ui/core/js/1971.022938ab.js"
|
||||||
|
|
||||||
|
headers_js = {
|
||||||
|
'Accept': '*/*',
|
||||||
|
'User-Agent': session.headers['user-agent'],
|
||||||
|
'Referer': js1,
|
||||||
|
}
|
||||||
|
|
||||||
|
try:
|
||||||
|
r1 = session.get(js1, headers=headers_js)
|
||||||
|
r2 = session.get(js2, headers=headers_js)
|
||||||
|
print(f"[INFO] JS preload status: {r1.status_code}, {r2.status_code}")
|
||||||
|
except Exception as e:
|
||||||
|
print(f"[ERROR] Gagal preload JS: {e}")
|
||||||
|
|
||||||
|
def create_remote_folder(session, headers, parent_path, folder_name):
|
||||||
|
epoch = get_epochtimes()
|
||||||
|
encoded_path = quote_plus(parent_path)
|
||||||
|
encoded_name = quote_plus(folder_name)
|
||||||
|
endpoint = f"{cfg.Url.jkn}/core/createfolder?time={epoch}&path={encoded_path}&name={encoded_name}"
|
||||||
|
|
||||||
|
response = session.post(endpoint, headers=headers)
|
||||||
|
if response.status_code == 200:
|
||||||
|
try:
|
||||||
|
root = ET.fromstring(response.text)
|
||||||
|
result = root.find(".//result")
|
||||||
|
if result is not None and result.text == "1":
|
||||||
|
print(f"[INFO] Folder dibuat: {parent_path}/{folder_name}")
|
||||||
|
return True
|
||||||
|
except ET.ParseError:
|
||||||
|
pass
|
||||||
|
return False
|
||||||
|
|
||||||
|
def upload_file(session, headers, local_file_path, remote_path):
|
||||||
|
filename = os.path.basename(local_file_path)
|
||||||
|
try:
|
||||||
|
with open(local_file_path, 'rb') as f:
|
||||||
|
size = os.path.getsize(local_file_path)
|
||||||
|
encoded_path = quote_plus(remote_path)
|
||||||
|
encoded_filename = quote_plus(filename)
|
||||||
|
current_time_iso = datetime.utcnow().isoformat() + "Z"
|
||||||
|
|
||||||
|
endpoint = (
|
||||||
|
f"{cfg.Url.jkn}/core/upload"
|
||||||
|
f"?appname=explorer"
|
||||||
|
f"&filesize={size}"
|
||||||
|
f"&path={encoded_path}"
|
||||||
|
f"&uploadpath="
|
||||||
|
f"&offset=0"
|
||||||
|
f"&date={current_time_iso}"
|
||||||
|
f"&filename={encoded_filename}"
|
||||||
|
f"&complete=1"
|
||||||
|
)
|
||||||
|
|
||||||
|
m = MultipartEncoder(
|
||||||
|
fields={'filedata': (filename, f, "application/pdf")},
|
||||||
|
boundary="----WebKitFormBoundarymZWe6678TZzxezEy"
|
||||||
|
)
|
||||||
|
|
||||||
|
upload_headers = headers.copy()
|
||||||
|
upload_headers['Content-Type'] = m.content_type
|
||||||
|
upload_headers['Referer'] = "https://jkn-drive.bpjs-kesehatan.go.id/ui/core/js/9858.2fe9443a.js"
|
||||||
|
upload_headers['Accept'] = "application/json"
|
||||||
|
|
||||||
|
response = session.post(endpoint, headers=upload_headers, data=m, timeout='30')
|
||||||
|
|
||||||
|
if response.status_code == 200:
|
||||||
|
print(f"[SUKSES] Upload: {filename} ke {remote_path}")
|
||||||
|
time.sleep(1)
|
||||||
|
else:
|
||||||
|
print(f"[GAGAL] Upload: {filename} ke {remote_path} - Status: {response.status_code}")
|
||||||
|
print(response.text)
|
||||||
|
time.sleep(1)
|
||||||
|
except Exception as e:
|
||||||
|
print(f"[ERROR] Gagal membuka atau upload file {filename} ke {remote_path}: {e}")
|
||||||
|
|
||||||
|
def upload_all_files(session, headers, root_path, base_remote_path):
|
||||||
|
if not os.path.isdir(root_path):
|
||||||
|
print(f"[ERROR] Folder lokal tidak ditemukan: {root_path}")
|
||||||
|
return
|
||||||
|
|
||||||
|
start_time = time.time()
|
||||||
|
file_queue = Queue()
|
||||||
|
created_folders = set()
|
||||||
|
folder_lock = threading.Lock()
|
||||||
|
failed_log_path = "upload_gagal.txt"
|
||||||
|
all_files = []
|
||||||
|
|
||||||
|
for subfolder in os.listdir(root_path):
|
||||||
|
subfolder_path = os.path.join(root_path, subfolder)
|
||||||
|
if os.path.isdir(subfolder_path) and subfolder.isdigit():
|
||||||
|
for file in os.listdir(subfolder_path):
|
||||||
|
full_file_path = os.path.join(subfolder_path, file)
|
||||||
|
if os.path.isfile(full_file_path):
|
||||||
|
remote_path = f"{base_remote_path}/{subfolder}".rstrip("/")
|
||||||
|
all_files.append((full_file_path, remote_path))
|
||||||
|
|
||||||
|
total_files = len(all_files)
|
||||||
|
print(f"[INFO] Total file yang akan diupload: {total_files}")
|
||||||
|
|
||||||
|
for item in all_files:
|
||||||
|
file_queue.put(item)
|
||||||
|
|
||||||
|
failed_uploads = []
|
||||||
|
counter_lock = threading.Lock()
|
||||||
|
progress = {'done': 0}
|
||||||
|
|
||||||
|
def worker():
|
||||||
|
while not file_queue.empty():
|
||||||
|
try:
|
||||||
|
full_path, target_remote_path = file_queue.get_nowait()
|
||||||
|
|
||||||
|
with folder_lock:
|
||||||
|
if target_remote_path not in created_folders:
|
||||||
|
existing = get_sharedfolder(session, os.path.dirname(target_remote_path), headers)
|
||||||
|
folder_name = os.path.basename(target_remote_path)
|
||||||
|
if not any(f['name'] == folder_name for f in existing):
|
||||||
|
create_remote_folder(session, headers, os.path.dirname(target_remote_path), folder_name)
|
||||||
|
created_folders.add(target_remote_path)
|
||||||
|
|
||||||
|
with counter_lock:
|
||||||
|
progress['done'] += 1
|
||||||
|
index = progress['done']
|
||||||
|
|
||||||
|
print(f"[{index}/{total_files}] Uploading: {os.path.basename(full_path)} -> {target_remote_path}")
|
||||||
|
result = upload_file(session, headers, full_path, target_remote_path, timeout=30)
|
||||||
|
|
||||||
|
if result is not True:
|
||||||
|
failed_uploads.append(full_path)
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
print(f"[ERROR] Worker exception: {e}")
|
||||||
|
failed_uploads.append(full_path)
|
||||||
|
finally:
|
||||||
|
file_queue.task_done()
|
||||||
|
|
||||||
|
threads = []
|
||||||
|
for _ in range(200):
|
||||||
|
t = threading.Thread(target=worker)
|
||||||
|
t.start()
|
||||||
|
threads.append(t)
|
||||||
|
|
||||||
|
for t in threads:
|
||||||
|
t.join()
|
||||||
|
|
||||||
|
print("[DEBUG] Semua thread selesai.")
|
||||||
|
print("[DEBUG] File queue kosong:", file_queue.empty())
|
||||||
|
|
||||||
|
still_failed = []
|
||||||
|
if failed_uploads:
|
||||||
|
print(f"[RETRY] Mengulangi upload untuk {len(failed_uploads)} file yang gagal...")
|
||||||
|
for full_path in failed_uploads:
|
||||||
|
folder_name = os.path.basename(os.path.dirname(full_path))
|
||||||
|
target_remote_path = f"{base_remote_path}/{folder_name}".rstrip("/")
|
||||||
|
print(f"[RETRY] {os.path.basename(full_path)} -> {target_remote_path}")
|
||||||
|
try:
|
||||||
|
result = upload_file(session, headers, full_path, target_remote_path, timeout=30)
|
||||||
|
if not result:
|
||||||
|
still_failed.append(full_path)
|
||||||
|
except Exception as e:
|
||||||
|
print(f"[ERROR] Retry gagal: {e}")
|
||||||
|
still_failed.append(full_path)
|
||||||
|
|
||||||
|
if still_failed:
|
||||||
|
with open(failed_log_path, "w", encoding="utf-8") as f:
|
||||||
|
for path in still_failed:
|
||||||
|
f.write(path + "\n")
|
||||||
|
print(f"[SELESAI] Setelah retry, {len(still_failed)} file tetap gagal. Cek: {failed_log_path}")
|
||||||
|
else:
|
||||||
|
print("[SELESAI] Semua file berhasil diupload (termasuk retry).")
|
||||||
|
|
||||||
|
duration = time.time() - start_time
|
||||||
|
menit = int(duration // 60)
|
||||||
|
detik = int(duration % 60)
|
||||||
|
print(f"[WAKTU] Upload selesai dalam {menit} menit {detik} detik.")
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
USERNAME = cfg.UserPass.username
|
||||||
|
PASSWORD = cfg.UserPass.password
|
||||||
|
SESSION_FILE = 'session.pkl'
|
||||||
|
|
||||||
|
class JKNApp(tk.Tk):
|
||||||
|
def __init__(self):
|
||||||
|
super().__init__() # Hanya perlu memanggil super() untuk mendefinisikan root
|
||||||
|
self.title("Uploader ke JKN Drive")
|
||||||
|
self.geometry("500x300")
|
||||||
|
|
||||||
|
self.session = requests.Session()
|
||||||
|
self.configure_headers()
|
||||||
|
|
||||||
|
self.remote_path = ""
|
||||||
|
self.local_folder = ""
|
||||||
|
|
||||||
|
self.status = tk.Label(self, text="Status: Siap", anchor="w")
|
||||||
|
self.status.pack(fill=tk.X, pady=5)
|
||||||
|
|
||||||
|
tk.Button(self, text="1. Pilih Folder Lokal", command=self.pilih_folder_lokal).pack(pady=5)
|
||||||
|
tk.Button(self, text="2. Login & Pilih Folder Remote", command=self.login_dan_pilih_folder).pack(pady=5)
|
||||||
|
tk.Button(self, text="3. Upload Semua File", command=self.upload_file).pack(pady=5)
|
||||||
|
tk.Button(self, text="⬅ Kembali ke Menu Utama", command=self.kembali_ke_menu).pack(pady=10)
|
||||||
|
|
||||||
|
def configure_headers(self):
|
||||||
|
self.session.headers.update({
|
||||||
|
'accept': 'application/x-www-form-urlencoded',
|
||||||
|
'accept-language': 'id-ID,id;q=0.9,en-US;q=0.8,en;q=0.7',
|
||||||
|
'content-type': 'application/x-www-form-urlencoded',
|
||||||
|
'dnt': '1',
|
||||||
|
'origin': 'https://jkn-drive.bpjs-kesehatan.go.id',
|
||||||
|
'priority': 'u=1, i',
|
||||||
|
'referer': 'https://jkn-drive.bpjs-kesehatan.go.id/ui/core/index.html',
|
||||||
|
'sec-ch-ua': '"Google Chrome";v="137", "Chromium";v="137", "Not/A)Brand";v="24"',
|
||||||
|
'sec-ch-ua-mobile': '?0',
|
||||||
|
'sec-ch-ua-platform': '"Windows"',
|
||||||
|
'sec-fetch-dest': 'empty',
|
||||||
|
'sec-fetch-mode': 'cors',
|
||||||
|
'sec-fetch-site': 'same-origin',
|
||||||
|
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/137.0.0.0 Safari/537.36',
|
||||||
|
'x-requested-with': 'XMLHttpRequest',
|
||||||
|
'x-xsrf-token': 'NONE'
|
||||||
|
})
|
||||||
|
|
||||||
|
def pilih_folder_lokal(self):
|
||||||
|
folder = filedialog.askdirectory()
|
||||||
|
if folder:
|
||||||
|
self.local_folder = folder
|
||||||
|
self.status.config(text=f"Folder Lokal: {folder}")
|
||||||
|
|
||||||
|
def login_dan_pilih_folder(self):
|
||||||
|
def run():
|
||||||
|
self.status.config(text="Mengecek sesi lama...")
|
||||||
|
if load_session(self.session, SESSION_FILE) and is_session_valid(self.session, self.session.headers):
|
||||||
|
self.status.config(text="Sesi lama valid.")
|
||||||
|
self.selesai_login()
|
||||||
|
else:
|
||||||
|
self.status.config(text="Login ulang diperlukan...")
|
||||||
|
token = login_guest(self.session, USERNAME, PASSWORD, self.session.headers)
|
||||||
|
if not token:
|
||||||
|
self.status.config(text="Login guest gagal.")
|
||||||
|
messagebox.showerror("Login Gagal", "Login guest gagal.")
|
||||||
|
return
|
||||||
|
|
||||||
|
# minta 2FA di thread utama
|
||||||
|
self.after(0, lambda: self.minta_token_2fa(token))
|
||||||
|
|
||||||
|
threading.Thread(target=run).start()
|
||||||
|
|
||||||
|
def minta_token_2fa(self, token_guest):
|
||||||
|
kode = simpledialog.askstring("Token 2FA", "Masukkan kode 2FA dari email/WA:", parent=self)
|
||||||
|
if not kode:
|
||||||
|
messagebox.showinfo("Login dibatalkan", "Token 2FA tidak dimasukkan.")
|
||||||
|
return
|
||||||
|
|
||||||
|
def lanjutkan_login():
|
||||||
|
if login_2fa(self.session, USERNAME, token_guest, kode, self.session.headers):
|
||||||
|
save_session(self.session, SESSION_FILE)
|
||||||
|
self.status.config(text="Login berhasil. Sesi disimpan.")
|
||||||
|
self.selesai_login()
|
||||||
|
else:
|
||||||
|
self.status.config(text="Token 2FA salah.")
|
||||||
|
messagebox.showerror("Login Gagal", "Token 2FA salah.")
|
||||||
|
|
||||||
|
threading.Thread(target=lanjutkan_login).start()
|
||||||
|
|
||||||
|
def selesai_login(self):
|
||||||
|
selected_remote_base = navigate_folder(self.session, "/SHARED/indri.wahyuningsih/UPLOAD_1f1y/RSU BUNDA", self.session.headers)
|
||||||
|
local_folder_name = os.path.basename(self.local_folder.rstrip("/\\"))
|
||||||
|
|
||||||
|
# Cek apakah folder lokal sudah ada di remote
|
||||||
|
existing_folders = get_sharedfolder(self.session, selected_remote_base, self.session.headers)
|
||||||
|
target_folder_path = f"{selected_remote_base}/{local_folder_name}"
|
||||||
|
|
||||||
|
if not any(f["name"] == local_folder_name for f in existing_folders):
|
||||||
|
created = create_remote_folder(self.session, self.session.headers, selected_remote_base, local_folder_name)
|
||||||
|
if not created:
|
||||||
|
self.status.config(text=f"Gagal membuat folder remote: {target_folder_path}")
|
||||||
|
messagebox.showerror("Gagal", f"Folder '{local_folder_name}' tidak bisa dibuat.")
|
||||||
|
return
|
||||||
|
else:
|
||||||
|
print(f"[INFO] Folder remote dibuat: {target_folder_path}")
|
||||||
|
else:
|
||||||
|
print(f"[INFO] Folder remote sudah ada: {target_folder_path}")
|
||||||
|
|
||||||
|
self.remote_path = target_folder_path
|
||||||
|
self.status.config(text=f"Folder Remote: {self.remote_path}")
|
||||||
|
|
||||||
|
|
||||||
|
def upload_file(self):
|
||||||
|
if not self.local_folder or not self.remote_path:
|
||||||
|
messagebox.showwarning("Peringatan", "Pilih folder lokal dan remote terlebih dahulu.")
|
||||||
|
return
|
||||||
|
|
||||||
|
def run():
|
||||||
|
self.status.config(text="Mengunggah file...")
|
||||||
|
upload_all_files(self.session, self.session.headers, self.local_folder, self.remote_path)
|
||||||
|
self.status.config(text="Upload selesai.")
|
||||||
|
|
||||||
|
threading.Thread(target=run).start()
|
||||||
|
|
||||||
|
def kembali_ke_menu(self):
|
||||||
|
self.destroy() # Tutup jendela ini
|
||||||
|
subprocess.Popen([sys.executable, "main.py"]) # Jalankan ulang main.py
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
app = JKNApp()
|
||||||
|
app.mainloop()
|
||||||
339
SubModules/ralan.py
Normal file
339
SubModules/ralan.py
Normal file
@@ -0,0 +1,339 @@
|
|||||||
|
# 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, re, sys, subprocess
|
||||||
|
import requests, mysql.connector
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
from urllib.parse import quote_plus
|
||||||
|
from bs4 import BeautifulSoup
|
||||||
|
from requests_toolbelt.multipart.encoder import MultipartEncoder
|
||||||
|
|
||||||
|
import tkinter as tk
|
||||||
|
import tkinter.filedialog as filedialog
|
||||||
|
import tkinter.messagebox as messagebox
|
||||||
|
import tkinter.simpledialog as simpledialog
|
||||||
|
from tkinter import ttk, Toplevel, Listbox, Scrollbar
|
||||||
|
|
||||||
|
from config_loader import Config
|
||||||
|
from SubModules import auth
|
||||||
|
from playwright.sync_api import sync_playwright
|
||||||
|
|
||||||
|
# ---- Playwright path for frozen exe
|
||||||
|
if getattr(sys, "frozen", False):
|
||||||
|
os.environ["PLAYWRIGHT_BROWSERS_PATH"] = os.path.join(sys._MEIPASS, "ms-playwright")
|
||||||
|
|
||||||
|
cfg = Config()
|
||||||
|
|
||||||
|
def get_epochtimes():
|
||||||
|
return int(datetime.now().timestamp())
|
||||||
|
|
||||||
|
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 login_guest(session, usernameJKN, passwordJKN, headers):
|
||||||
|
epoch = get_epochtimes()
|
||||||
|
endpoint = f"{cfg.Url.jkn}/core/loginguest?time={epoch}"
|
||||||
|
payload = f"userid={usernameJKN}&password={passwordJKN}&passwordType=password&g-recaptcha-response=&tfa=1"
|
||||||
|
r = session.post(endpoint, headers=headers, data=payload)
|
||||||
|
if r.ok:
|
||||||
|
import xml.etree.ElementTree as ET
|
||||||
|
root = ET.fromstring(r.text)
|
||||||
|
msg = root.find('.//message')
|
||||||
|
return msg.text if msg is not None else None
|
||||||
|
return None
|
||||||
|
|
||||||
|
def login_2fa(session, usernameJKN, token_message, token_2fa, headers):
|
||||||
|
epoch = get_epochtimes()
|
||||||
|
endpoint = f"{cfg.Url.jkn}/core/2falogin?time={epoch}"
|
||||||
|
payload = f"userid={usernameJKN}&code={token_2fa}&token={token_message}&tfa=1"
|
||||||
|
r = session.post(endpoint, headers=headers, data=payload)
|
||||||
|
if r.ok:
|
||||||
|
import xml.etree.ElementTree as ET
|
||||||
|
root = ET.fromstring(r.text)
|
||||||
|
result = root.find('.//result')
|
||||||
|
return result is not None and result.text == '1'
|
||||||
|
return False
|
||||||
|
|
||||||
|
def get_sharedfolder(session, path, headers):
|
||||||
|
epoch = get_epochtimes()
|
||||||
|
endpoint = f"{cfg.Url.jkn}/core/getfilelist?time={epoch}"
|
||||||
|
payload = f"path={path}&start=0&limit=100"
|
||||||
|
r = session.post(endpoint, headers=headers, data=payload)
|
||||||
|
entries = []
|
||||||
|
if r.ok:
|
||||||
|
import xml.etree.ElementTree as ET
|
||||||
|
root = ET.fromstring(r.text)
|
||||||
|
for e in root.findall('.//entry'):
|
||||||
|
if e.find('type').text == 'dir':
|
||||||
|
entries.append({'name': e.find('name').text, 'path': e.find('path').text})
|
||||||
|
return entries
|
||||||
|
|
||||||
|
def create_folder(session, headers, parent_path, new_folder_name):
|
||||||
|
epoch = get_epochtimes()
|
||||||
|
endpoint = f"{cfg.Url.jkn}/core/createfolder?time={epoch}"
|
||||||
|
payload = {"name": new_folder_name, "path": parent_path, "date": datetime.now().isoformat()}
|
||||||
|
r = session.post(endpoint, headers=headers, data=payload)
|
||||||
|
return r.ok
|
||||||
|
|
||||||
|
def select_remote_folder(session, headers, base_path=cfg.Paths.base_path):
|
||||||
|
def on_select(_):
|
||||||
|
si = listbox.curselection()
|
||||||
|
if si:
|
||||||
|
new_path = folder_entries[si[0]]['path']
|
||||||
|
refresh_folder(new_path)
|
||||||
|
|
||||||
|
def refresh_folder(current_path_val):
|
||||||
|
nonlocal current_path, folder_entries
|
||||||
|
folder_entries = get_sharedfolder(session, current_path_val, headers)
|
||||||
|
current_path = current_path_val
|
||||||
|
listbox.delete(0, 'end')
|
||||||
|
for f in folder_entries:
|
||||||
|
listbox.insert('end', f['name'])
|
||||||
|
|
||||||
|
def create_new():
|
||||||
|
name = simpledialog.askstring("Nama Folder", "Masukkan nama folder baru:", parent=win)
|
||||||
|
if name and create_folder(session, headers, current_path, name):
|
||||||
|
refresh_folder(current_path)
|
||||||
|
|
||||||
|
selected_path = None
|
||||||
|
current_path = base_path
|
||||||
|
folder_entries = []
|
||||||
|
|
||||||
|
win = Toplevel(app)
|
||||||
|
win.title("Pilih Folder Upload")
|
||||||
|
win.geometry("420x380")
|
||||||
|
|
||||||
|
def go_back():
|
||||||
|
nonlocal current_path
|
||||||
|
if current_path.strip('/') != base_path.strip('/'):
|
||||||
|
parent = '/'.join(current_path.strip('/').split('/')[:-1])
|
||||||
|
parent_path = f'/{parent}/' if parent else base_path
|
||||||
|
refresh_folder(parent_path)
|
||||||
|
|
||||||
|
def choose_folder():
|
||||||
|
nonlocal selected_path
|
||||||
|
selected_path = current_path
|
||||||
|
win.destroy()
|
||||||
|
|
||||||
|
tk.Button(win, text="Kembali", command=go_back).pack(pady=6)
|
||||||
|
sb = Scrollbar(win)
|
||||||
|
sb.pack(side='right', fill='y')
|
||||||
|
listbox = Listbox(win, yscrollcommand=sb.set, width=50)
|
||||||
|
listbox.pack(fill='both', expand=True, padx=8, pady=8)
|
||||||
|
sb.config(command=listbox.yview)
|
||||||
|
listbox.bind("<Double-1>", on_select)
|
||||||
|
tk.Button(win, text="Pilih Folder Ini", command=choose_folder).pack(pady=6)
|
||||||
|
tk.Button(win, text="Buat Folder Baru", command=create_new).pack(pady=6)
|
||||||
|
refresh_folder(current_path)
|
||||||
|
win.wait_window()
|
||||||
|
return selected_path
|
||||||
|
|
||||||
|
def fetch_identifiers(tanggal1):
|
||||||
|
conn = mysql.connector.connect(
|
||||||
|
host=cfg.Database.host, user=cfg.Database.user,
|
||||||
|
password=cfg.Database.password, database=cfg.Database.database)
|
||||||
|
cur = conn.cursor()
|
||||||
|
q = f"""
|
||||||
|
SELECT no_rawat FROM mlite_vedika
|
||||||
|
WHERE status = 'Pengajuan' AND jenis = '2'
|
||||||
|
AND (no_rkm_medis OR no_rawat OR nosep)
|
||||||
|
AND tgl_registrasi BETWEEN '{tanggal1}' AND '{tanggal1}'
|
||||||
|
"""
|
||||||
|
cur.execute(q)
|
||||||
|
rows = cur.fetchall()
|
||||||
|
cur.close(); conn.close()
|
||||||
|
return rows
|
||||||
|
|
||||||
|
def generate_pdf(username, password, no_rawat, cookies, path_folder):
|
||||||
|
"""
|
||||||
|
return: path ke PDF (string) bila sukses; None bila gagal
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
modified = no_rawat.replace("/", "")
|
||||||
|
url = f'{cfg.Url.mlite}/admin/vedika/pdf/{modified}'
|
||||||
|
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='
|
||||||
|
r = requests.post(url, headers=headers, data=payload, timeout=30)
|
||||||
|
html = r.text
|
||||||
|
|
||||||
|
soup = BeautifulSoup(html, 'html.parser')
|
||||||
|
no_sep_value = None
|
||||||
|
no_sep_text = soup.find(string=re.compile(r'No[.\s]?SEP[::]?'))
|
||||||
|
if no_sep_text:
|
||||||
|
m = re.search(r'No\.SEP:\s*(\S+)', no_sep_text)
|
||||||
|
if m:
|
||||||
|
no_sep_value = m.group(1).replace('"', '')
|
||||||
|
|
||||||
|
if not no_sep_value:
|
||||||
|
return None
|
||||||
|
|
||||||
|
filename = f"{no_sep_value}.pdf"
|
||||||
|
final_pdf = os.path.join(path_folder, filename)
|
||||||
|
temp_pdf = final_pdf.replace(".pdf", "_temp.pdf")
|
||||||
|
render_pdf_with_playwright(html, temp_pdf)
|
||||||
|
|
||||||
|
out = subprocess.run(['qpdf', '--decode-level=generalized', temp_pdf, final_pdf],
|
||||||
|
capture_output=True, text=True)
|
||||||
|
try: os.remove(temp_pdf)
|
||||||
|
except: pass
|
||||||
|
return final_pdf if out.returncode == 0 else None
|
||||||
|
except Exception:
|
||||||
|
return None
|
||||||
|
|
||||||
|
def upload_file(session, headers, pdf_path, remote_path):
|
||||||
|
try:
|
||||||
|
with open(pdf_path, 'rb') as f:
|
||||||
|
filename = os.path.basename(pdf_path)
|
||||||
|
size = os.path.getsize(pdf_path)
|
||||||
|
encoded_path = quote_plus(str(remote_path))
|
||||||
|
encoded_filename = quote_plus(str(filename))
|
||||||
|
current_time_iso = datetime.now(timezone.utc).isoformat().replace('+00:00', 'Z')
|
||||||
|
|
||||||
|
endpoint = (
|
||||||
|
f"{cfg.Url.jkn}/core/upload?appname=explorer"
|
||||||
|
f"&filesize={size}&path={encoded_path}&uploadpath=&offset=0"
|
||||||
|
f"&date={current_time_iso}&filename={encoded_filename}&complete=1"
|
||||||
|
)
|
||||||
|
m = MultipartEncoder(fields={'filedata': (filename, f, "application/pdf")})
|
||||||
|
up_headers = headers.copy()
|
||||||
|
up_headers['Content-Type'] = m.content_type
|
||||||
|
up_headers['Accept'] = "application/json"
|
||||||
|
r = session.post(endpoint, headers=up_headers, data=m, timeout=60)
|
||||||
|
return r.ok
|
||||||
|
except Exception:
|
||||||
|
return False
|
||||||
|
|
||||||
|
def select_cookies():
|
||||||
|
p = filedialog.askopenfilename(filetypes=[("Text files", "*.txt")])
|
||||||
|
if p:
|
||||||
|
entry_cookies.delete(0, 'end')
|
||||||
|
entry_cookies.insert(0, p)
|
||||||
|
|
||||||
|
def preload_js_assets(session):
|
||||||
|
try:
|
||||||
|
js1 = f'{cfg.Url.jkn}/ui/core/js/9858.2fe9443a.js'
|
||||||
|
js2 = f'{cfg.Url.jkn}/ui/core/js/1971.022938ab.js'
|
||||||
|
session.get(js1, headers={'Accept': '*/*'})
|
||||||
|
session.get(js2, headers={'Accept': '*/*'})
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
|
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 kembali_ke_menu():
|
||||||
|
app.destroy()
|
||||||
|
subprocess.Popen([sys.executable, "main.py"])
|
||||||
|
|
||||||
|
def process_files():
|
||||||
|
tanggal1 = entry_tanggal1.get()
|
||||||
|
username = entry_username.get()
|
||||||
|
password = entry_password.get()
|
||||||
|
usernameJKN = entry_usernamejkn.get()
|
||||||
|
passwordJKN = entry_passwordjkn.get()
|
||||||
|
cookies = entry_cookies.get()
|
||||||
|
folder_pdf = entry_folder.get()
|
||||||
|
|
||||||
|
if not os.path.isdir(folder_pdf):
|
||||||
|
os.makedirs(folder_pdf, exist_ok=True)
|
||||||
|
|
||||||
|
identifiers = fetch_identifiers(tanggal1)
|
||||||
|
if not identifiers:
|
||||||
|
messagebox.showerror("Error", "Tanggal tidak ditemukan / kosong.")
|
||||||
|
return
|
||||||
|
|
||||||
|
session = requests.Session()
|
||||||
|
session.headers.update({
|
||||||
|
'accept': 'application/x-www-form-urlencoded',
|
||||||
|
'accept-language': 'id-ID,id;q=0.9,en-US;q=0.8,en;q=0.7',
|
||||||
|
'content-type': 'application/x-www-form-urlencoded',
|
||||||
|
'origin': 'https://jkn-drive.bpjs-kesehatan.go.id',
|
||||||
|
'referer': 'https://jkn-drive.bpjs-kesehatan.go.id/ui/core/index.html',
|
||||||
|
'sec-ch-ua': '"Google Chrome";v="135", "Not-A.Brand";v="8", "Chromium";v="135"',
|
||||||
|
'sec-ch-ua-mobile': '?0',
|
||||||
|
'sec-ch-ua-platform': '"Windows"',
|
||||||
|
'sec-fetch-dest': 'empty',
|
||||||
|
'sec-fetch-mode': 'cors',
|
||||||
|
'sec-fetch-site': 'same-origin',
|
||||||
|
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/135.0.0.0 Safari/537.36',
|
||||||
|
'x-requested-with': 'XMLHttpRequest',
|
||||||
|
'X-XSRF-TOKEN': 'NONE'
|
||||||
|
})
|
||||||
|
|
||||||
|
token_message = login_guest(session, usernameJKN, passwordJKN, session.headers)
|
||||||
|
token_2fa = simpledialog.askstring("2FA", "Masukkan kode 2FA:", parent=app)
|
||||||
|
if not token_message or not token_2fa or not login_2fa(session, usernameJKN, token_message, token_2fa, session.headers):
|
||||||
|
messagebox.showerror("Error", "Login 2FA gagal.")
|
||||||
|
return
|
||||||
|
|
||||||
|
remote_folder = select_remote_folder(session, session.headers)
|
||||||
|
if not remote_folder:
|
||||||
|
messagebox.showwarning("Info", "Folder remote belum dipilih.")
|
||||||
|
return
|
||||||
|
|
||||||
|
for (no_rawat,) in identifiers:
|
||||||
|
pdf_path = generate_pdf(username, password, no_rawat, cookies, folder_pdf)
|
||||||
|
if pdf_path:
|
||||||
|
preload_js_assets(session)
|
||||||
|
upload_file(session, session.headers, pdf_path, remote_folder)
|
||||||
|
|
||||||
|
# ---- UI
|
||||||
|
app = tk.Tk()
|
||||||
|
app.title("Downloader dan Uploader PDF JKN DRIVE (Ralan)")
|
||||||
|
app.geometry("560x420")
|
||||||
|
|
||||||
|
tk.Label(app, text="Tanggal (YYYY-MM-DD):").grid(row=0, column=0, sticky='e', padx=6, pady=6)
|
||||||
|
entry_tanggal1 = tk.Entry(app); entry_tanggal1.grid(row=0, column=1, sticky='we', padx=6, pady=6)
|
||||||
|
|
||||||
|
tk.Label(app, text="Username RS:").grid(row=1, column=0, sticky='e', padx=6, pady=6)
|
||||||
|
entry_username = tk.Entry(app); entry_username.grid(row=1, column=1, sticky='we', padx=6, pady=6)
|
||||||
|
|
||||||
|
tk.Label(app, text="Password RS:").grid(row=2, column=0, sticky='e', padx=6, pady=6)
|
||||||
|
entry_password = tk.Entry(app, show='*'); entry_password.grid(row=2, column=1, sticky='we', padx=6, pady=6)
|
||||||
|
|
||||||
|
tk.Label(app, text="Username Drive:").grid(row=3, column=0, sticky='e', padx=6, pady=6)
|
||||||
|
entry_usernamejkn = tk.Entry(app); entry_usernamejkn.grid(row=3, column=1, sticky='we', padx=6, pady=6)
|
||||||
|
|
||||||
|
tk.Label(app, text="Password Drive:").grid(row=4, column=0, sticky='e', padx=6, pady=6)
|
||||||
|
entry_passwordjkn = tk.Entry(app, show='*'); entry_passwordjkn.grid(row=4, column=1, sticky='we', padx=6, pady=6)
|
||||||
|
|
||||||
|
tk.Label(app, text="Folder Simpan PDF:").grid(row=5, column=0, sticky='e', padx=6, pady=6)
|
||||||
|
entry_folder = tk.Entry(app); entry_folder.grid(row=5, column=1, sticky='we', padx=6, pady=6)
|
||||||
|
ttk.Button(app, text="Pilih Folder", command=lambda: entry_folder.insert(0, filedialog.askdirectory())).grid(row=5, column=2, padx=6, pady=6)
|
||||||
|
|
||||||
|
tk.Label(app, text="Cookies File / String:").grid(row=6, column=0, sticky='e', padx=6, pady=6)
|
||||||
|
entry_cookies = tk.Entry(app); entry_cookies.grid(row=6, column=1, sticky='we', padx=6, pady=6)
|
||||||
|
ttk.Button(app, text="Pilih Cookies", command=select_cookies).grid(row=6, column=2, padx=6, pady=6)
|
||||||
|
ttk.Button(app, text="Ambil Cookies", command=ambil_cookies).grid(row=6, column=3, padx=6, pady=6)
|
||||||
|
|
||||||
|
ttk.Button(app, text="Proses", command=process_files).grid(row=7, column=1, pady=20)
|
||||||
|
ttk.Button(app, text="⬅ Kembali ke Menu Utama", command=kembali_ke_menu).grid(row=7, column=2, pady=20)
|
||||||
|
app.grid_columnconfigure(1, weight=1)
|
||||||
|
app.mainloop()
|
||||||
343
SubModules/ralannoupload.py
Normal file
343
SubModules/ralannoupload.py
Normal file
@@ -0,0 +1,343 @@
|
|||||||
|
# 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, TimeoutError as PWTimeoutError
|
||||||
|
import sys
|
||||||
|
import threading
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
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) -> date | None:
|
||||||
|
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 mark_failed(no_rawat: str, base_folder: str):
|
||||||
|
path_gagal = os.path.join(base_folder, "Gagal_Download.txt")
|
||||||
|
os.makedirs(base_folder, exist_ok=True)
|
||||||
|
with open(path_gagal, "a", encoding="utf-8") as f:
|
||||||
|
f.write(f"{no_rawat}\n")
|
||||||
|
|
||||||
|
|
||||||
|
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 FROM mlite_vedika WHERE status = 'Pengajuan'
|
||||||
|
AND jenis = '2' AND (no_rkm_medis OR no_rawat OR nosep )
|
||||||
|
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(args=["--disable-dev-shm-usage"])
|
||||||
|
context = browser.new_context()
|
||||||
|
page = context.new_page()
|
||||||
|
try:
|
||||||
|
page.set_content(html_content, wait_until="domcontentloaded", timeout=90_000)
|
||||||
|
except PWTimeoutError:
|
||||||
|
page.set_content(html_content, wait_until="load", timeout=90_000)
|
||||||
|
page.wait_for_timeout(500)
|
||||||
|
|
||||||
|
page.pdf(path=output_path, format='A4', print_background=True)
|
||||||
|
browser.close()
|
||||||
|
|
||||||
|
|
||||||
|
def generate_pdf(username, password, no_rawat, cookies, base_folder, urutan, total, max_retry=3):
|
||||||
|
for attempt in range(1, max_retry + 1):
|
||||||
|
try:
|
||||||
|
modified_string = no_rawat.replace("/", "")
|
||||||
|
url = f'{cfg.Url.mlite}/admin/vedika/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('"', '')
|
||||||
|
|
||||||
|
if not no_sep_value:
|
||||||
|
if attempt == max_retry:
|
||||||
|
mark_failed(no_rawat, base_folder)
|
||||||
|
return f"{Color.RED}[{urutan}/{total}] GAGAL (x{attempt}): No.SEP tidak ditemukan untuk {no_rawat}{Color.RESET}", False
|
||||||
|
continue
|
||||||
|
|
||||||
|
d = extract_date_from_no_rawat(no_rawat)
|
||||||
|
if d is None:
|
||||||
|
target_dir = base_folder
|
||||||
|
else:
|
||||||
|
target_dir = os.path.join(base_folder, d.strftime("%d"))
|
||||||
|
os.makedirs(target_dir, exist_ok=True)
|
||||||
|
|
||||||
|
filename = f"{no_sep_value}.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:
|
||||||
|
mark_failed(no_rawat, base_folder)
|
||||||
|
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:
|
||||||
|
mark_failed(no_rawat, base_folder)
|
||||||
|
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:
|
||||||
|
no_rawat = row[0]
|
||||||
|
with lock:
|
||||||
|
index_counter['current'] += 1
|
||||||
|
urutan = index_counter['current']
|
||||||
|
|
||||||
|
message, success = generate_pdf(username, password, no_rawat, cookies, path_folder, urutan, total)
|
||||||
|
|
||||||
|
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 Ralan Non Upload")
|
||||||
|
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=0, column=0, sticky='e')
|
||||||
|
entry_tanggal_akhir = tk.Entry(app)
|
||||||
|
entry_tanggal_akhir.grid(row=0, 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()
|
||||||
337
SubModules/ranap.py
Normal file
337
SubModules/ranap.py
Normal file
@@ -0,0 +1,337 @@
|
|||||||
|
# ralan.py — FIXED
|
||||||
|
# This file is part of AutoDownloaderVedikaPDF.
|
||||||
|
# © 2025 Andy Cahyono Putra — Aladdin Free Public License
|
||||||
|
|
||||||
|
import os, re, sys, subprocess
|
||||||
|
import requests, mysql.connector
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
from urllib.parse import quote_plus
|
||||||
|
from bs4 import BeautifulSoup
|
||||||
|
from requests_toolbelt.multipart.encoder import MultipartEncoder
|
||||||
|
|
||||||
|
import tkinter as tk
|
||||||
|
import tkinter.filedialog as filedialog
|
||||||
|
import tkinter.messagebox as messagebox
|
||||||
|
import tkinter.simpledialog as simpledialog
|
||||||
|
from tkinter import ttk, Toplevel, Listbox, Scrollbar
|
||||||
|
|
||||||
|
from config_loader import Config
|
||||||
|
from SubModules import auth
|
||||||
|
from playwright.sync_api import sync_playwright
|
||||||
|
|
||||||
|
# ---- Playwright path for frozen exe
|
||||||
|
if getattr(sys, "frozen", False):
|
||||||
|
os.environ["PLAYWRIGHT_BROWSERS_PATH"] = os.path.join(sys._MEIPASS, "ms-playwright")
|
||||||
|
|
||||||
|
cfg = Config()
|
||||||
|
|
||||||
|
def get_epochtimes():
|
||||||
|
return int(datetime.now().timestamp())
|
||||||
|
|
||||||
|
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 login_guest(session, usernameJKN, passwordJKN, headers):
|
||||||
|
epoch = get_epochtimes()
|
||||||
|
endpoint = f"{cfg.Url.jkn}/core/loginguest?time={epoch}"
|
||||||
|
payload = f"userid={usernameJKN}&password={passwordJKN}&passwordType=password&g-recaptcha-response=&tfa=1"
|
||||||
|
r = session.post(endpoint, headers=headers, data=payload)
|
||||||
|
if r.ok:
|
||||||
|
import xml.etree.ElementTree as ET
|
||||||
|
root = ET.fromstring(r.text)
|
||||||
|
msg = root.find('.//message')
|
||||||
|
return msg.text if msg is not None else None
|
||||||
|
return None
|
||||||
|
|
||||||
|
def login_2fa(session, usernameJKN, token_message, token_2fa, headers):
|
||||||
|
epoch = get_epochtimes()
|
||||||
|
endpoint = f"{cfg.Url.jkn}/core/2falogin?time={epoch}"
|
||||||
|
payload = f"userid={usernameJKN}&code={token_2fa}&token={token_message}&tfa=1"
|
||||||
|
r = session.post(endpoint, headers=headers, data=payload)
|
||||||
|
if r.ok:
|
||||||
|
import xml.etree.ElementTree as ET
|
||||||
|
root = ET.fromstring(r.text)
|
||||||
|
result = root.find('.//result')
|
||||||
|
return result is not None and result.text == '1'
|
||||||
|
return False
|
||||||
|
|
||||||
|
def get_sharedfolder(session, path, headers):
|
||||||
|
epoch = get_epochtimes()
|
||||||
|
endpoint = f"{cfg.Url.jkn}/core/getfilelist?time={epoch}"
|
||||||
|
payload = f"path={path}&start=0&limit=100"
|
||||||
|
r = session.post(endpoint, headers=headers, data=payload)
|
||||||
|
entries = []
|
||||||
|
if r.ok:
|
||||||
|
import xml.etree.ElementTree as ET
|
||||||
|
root = ET.fromstring(r.text)
|
||||||
|
for e in root.findall('.//entry'):
|
||||||
|
if e.find('type').text == 'dir':
|
||||||
|
entries.append({'name': e.find('name').text, 'path': e.find('path').text})
|
||||||
|
return entries
|
||||||
|
|
||||||
|
def create_folder(session, headers, parent_path, new_folder_name):
|
||||||
|
epoch = get_epochtimes()
|
||||||
|
endpoint = f"{cfg.Url.jkn}/core/createfolder?time={epoch}"
|
||||||
|
payload = {"name": new_folder_name, "path": parent_path, "date": datetime.now().isoformat()}
|
||||||
|
r = session.post(endpoint, headers=headers, data=payload)
|
||||||
|
return r.ok
|
||||||
|
|
||||||
|
def select_remote_folder(session, headers, base_path=cfg.Paths.base_path):
|
||||||
|
def on_select(_):
|
||||||
|
si = listbox.curselection()
|
||||||
|
if si:
|
||||||
|
new_path = folder_entries[si[0]]['path']
|
||||||
|
refresh_folder(new_path)
|
||||||
|
|
||||||
|
def refresh_folder(current_path_val):
|
||||||
|
nonlocal current_path, folder_entries
|
||||||
|
folder_entries = get_sharedfolder(session, current_path_val, headers)
|
||||||
|
current_path = current_path_val
|
||||||
|
listbox.delete(0, 'end')
|
||||||
|
for f in folder_entries:
|
||||||
|
listbox.insert('end', f['name'])
|
||||||
|
|
||||||
|
def create_new():
|
||||||
|
name = simpledialog.askstring("Nama Folder", "Masukkan nama folder baru:", parent=win)
|
||||||
|
if name and create_folder(session, headers, current_path, name):
|
||||||
|
refresh_folder(current_path)
|
||||||
|
|
||||||
|
selected_path = None
|
||||||
|
current_path = base_path
|
||||||
|
folder_entries = []
|
||||||
|
|
||||||
|
win = Toplevel(app)
|
||||||
|
win.title("Pilih Folder Upload")
|
||||||
|
win.geometry("420x380")
|
||||||
|
|
||||||
|
def go_back():
|
||||||
|
nonlocal current_path
|
||||||
|
if current_path.strip('/') != base_path.strip('/'):
|
||||||
|
parent = '/'.join(current_path.strip('/').split('/')[:-1])
|
||||||
|
parent_path = f'/{parent}/' if parent else base_path
|
||||||
|
refresh_folder(parent_path)
|
||||||
|
|
||||||
|
def choose_folder():
|
||||||
|
nonlocal selected_path
|
||||||
|
selected_path = current_path
|
||||||
|
win.destroy()
|
||||||
|
|
||||||
|
tk.Button(win, text="Kembali", command=go_back).pack(pady=6)
|
||||||
|
sb = Scrollbar(win)
|
||||||
|
sb.pack(side='right', fill='y')
|
||||||
|
listbox = Listbox(win, yscrollcommand=sb.set, width=50)
|
||||||
|
listbox.pack(fill='both', expand=True, padx=8, pady=8)
|
||||||
|
sb.config(command=listbox.yview)
|
||||||
|
listbox.bind("<Double-1>", on_select)
|
||||||
|
tk.Button(win, text="Pilih Folder Ini", command=choose_folder).pack(pady=6)
|
||||||
|
tk.Button(win, text="Buat Folder Baru", command=create_new).pack(pady=6)
|
||||||
|
refresh_folder(current_path)
|
||||||
|
win.wait_window()
|
||||||
|
return selected_path
|
||||||
|
|
||||||
|
def fetch_identifiers(tanggal1):
|
||||||
|
conn = mysql.connector.connect(
|
||||||
|
host=cfg.Database.host, user=cfg.Database.user,
|
||||||
|
password=cfg.Database.password, database=cfg.Database.database)
|
||||||
|
cur = conn.cursor()
|
||||||
|
q = f"""
|
||||||
|
SELECT no_rawat FROM mlite_vedika WHERE status = 'Pengajuan' AND jenis = '1'
|
||||||
|
AND (no_rkm_medis OR no_rawat OR nosep)
|
||||||
|
AND no_rawat IN (SELECT no_rawat FROM kamar_inap WHERE tgl_keluar BETWEEN '{tanggal1}' AND '{tanggal1}' AND kamar_inap.stts_pulang LIKE '%Pindah%')
|
||||||
|
"""
|
||||||
|
cur.execute(q)
|
||||||
|
rows = cur.fetchall()
|
||||||
|
cur.close(); conn.close()
|
||||||
|
return rows
|
||||||
|
|
||||||
|
def generate_pdf(username, password, no_rawat, cookies, path_folder):
|
||||||
|
"""
|
||||||
|
return: path ke PDF (string) bila sukses; None bila gagal
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
modified = no_rawat.replace("/", "")
|
||||||
|
url = f'{cfg.Url.mlite}/admin/vedika/pdf/{modified}'
|
||||||
|
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='
|
||||||
|
r = requests.post(url, headers=headers, data=payload, timeout=30)
|
||||||
|
html = r.text
|
||||||
|
|
||||||
|
soup = BeautifulSoup(html, 'html.parser')
|
||||||
|
no_sep_value = None
|
||||||
|
no_sep_text = soup.find(string=re.compile(r'No[.\s]?SEP[::]?'))
|
||||||
|
if no_sep_text:
|
||||||
|
m = re.search(r'No\.SEP:\s*(\S+)', no_sep_text)
|
||||||
|
if m:
|
||||||
|
no_sep_value = m.group(1).replace('"', '')
|
||||||
|
|
||||||
|
if not no_sep_value:
|
||||||
|
return None
|
||||||
|
|
||||||
|
filename = f"{no_sep_value}.pdf"
|
||||||
|
final_pdf = os.path.join(path_folder, filename)
|
||||||
|
temp_pdf = final_pdf.replace(".pdf", "_temp.pdf")
|
||||||
|
render_pdf_with_playwright(html, temp_pdf)
|
||||||
|
|
||||||
|
out = subprocess.run(['qpdf', '--decode-level=generalized', temp_pdf, final_pdf],
|
||||||
|
capture_output=True, text=True)
|
||||||
|
try: os.remove(temp_pdf)
|
||||||
|
except: pass
|
||||||
|
return final_pdf if out.returncode == 0 else None
|
||||||
|
except Exception:
|
||||||
|
return None
|
||||||
|
|
||||||
|
def upload_file(session, headers, pdf_path, remote_path):
|
||||||
|
try:
|
||||||
|
with open(pdf_path, 'rb') as f:
|
||||||
|
filename = os.path.basename(pdf_path)
|
||||||
|
size = os.path.getsize(pdf_path)
|
||||||
|
encoded_path = quote_plus(str(remote_path))
|
||||||
|
encoded_filename = quote_plus(str(filename))
|
||||||
|
current_time_iso = datetime.now(timezone.utc).isoformat().replace('+00:00', 'Z')
|
||||||
|
|
||||||
|
endpoint = (
|
||||||
|
f"{cfg.Url.jkn}/core/upload?appname=explorer"
|
||||||
|
f"&filesize={size}&path={encoded_path}&uploadpath=&offset=0"
|
||||||
|
f"&date={current_time_iso}&filename={encoded_filename}&complete=1"
|
||||||
|
)
|
||||||
|
m = MultipartEncoder(fields={'filedata': (filename, f, "application/pdf")})
|
||||||
|
up_headers = headers.copy()
|
||||||
|
up_headers['Content-Type'] = m.content_type
|
||||||
|
up_headers['Accept'] = "application/json"
|
||||||
|
r = session.post(endpoint, headers=up_headers, data=m, timeout=60)
|
||||||
|
return r.ok
|
||||||
|
except Exception:
|
||||||
|
return False
|
||||||
|
|
||||||
|
def select_cookies():
|
||||||
|
p = filedialog.askopenfilename(filetypes=[("Text files", "*.txt")])
|
||||||
|
if p:
|
||||||
|
entry_cookies.delete(0, 'end')
|
||||||
|
entry_cookies.insert(0, p)
|
||||||
|
|
||||||
|
def preload_js_assets(session):
|
||||||
|
try:
|
||||||
|
js1 = f'{cfg.Url.jkn}/ui/core/js/9858.2fe9443a.js'
|
||||||
|
js2 = f'{cfg.Url.jkn}/ui/core/js/1971.022938ab.js'
|
||||||
|
session.get(js1, headers={'Accept': '*/*'})
|
||||||
|
session.get(js2, headers={'Accept': '*/*'})
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
|
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 kembali_ke_menu():
|
||||||
|
app.destroy()
|
||||||
|
subprocess.Popen([sys.executable, "main.py"])
|
||||||
|
|
||||||
|
def process_files():
|
||||||
|
tanggal1 = entry_tanggal1.get()
|
||||||
|
username = entry_username.get()
|
||||||
|
password = entry_password.get()
|
||||||
|
usernameJKN = entry_usernamejkn.get()
|
||||||
|
passwordJKN = entry_passwordjkn.get()
|
||||||
|
cookies = entry_cookies.get()
|
||||||
|
folder_pdf = entry_folder.get()
|
||||||
|
|
||||||
|
if not os.path.isdir(folder_pdf):
|
||||||
|
os.makedirs(folder_pdf, exist_ok=True)
|
||||||
|
|
||||||
|
identifiers = fetch_identifiers(tanggal1)
|
||||||
|
if not identifiers:
|
||||||
|
messagebox.showerror("Error", "Tanggal tidak ditemukan / kosong.")
|
||||||
|
return
|
||||||
|
|
||||||
|
session = requests.Session()
|
||||||
|
session.headers.update({
|
||||||
|
'accept': 'application/x-www-form-urlencoded',
|
||||||
|
'accept-language': 'id-ID,id;q=0.9,en-US;q=0.8,en;q=0.7',
|
||||||
|
'content-type': 'application/x-www-form-urlencoded',
|
||||||
|
'origin': 'https://jkn-drive.bpjs-kesehatan.go.id',
|
||||||
|
'referer': 'https://jkn-drive.bpjs-kesehatan.go.id/ui/core/index.html',
|
||||||
|
'sec-ch-ua': '"Google Chrome";v="135", "Not-A.Brand";v="8", "Chromium";v="135"',
|
||||||
|
'sec-ch-ua-mobile': '?0',
|
||||||
|
'sec-ch-ua-platform': '"Windows"',
|
||||||
|
'sec-fetch-dest': 'empty',
|
||||||
|
'sec-fetch-mode': 'cors',
|
||||||
|
'sec-fetch-site': 'same-origin',
|
||||||
|
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/135.0.0.0 Safari/537.36',
|
||||||
|
'x-requested-with': 'XMLHttpRequest',
|
||||||
|
'X-XSRF-TOKEN': 'NONE'
|
||||||
|
})
|
||||||
|
|
||||||
|
token_message = login_guest(session, usernameJKN, passwordJKN, session.headers)
|
||||||
|
token_2fa = simpledialog.askstring("2FA", "Masukkan kode 2FA:", parent=app)
|
||||||
|
if not token_message or not token_2fa or not login_2fa(session, usernameJKN, token_message, token_2fa, session.headers):
|
||||||
|
messagebox.showerror("Error", "Login 2FA gagal.")
|
||||||
|
return
|
||||||
|
|
||||||
|
remote_folder = select_remote_folder(session, session.headers)
|
||||||
|
if not remote_folder:
|
||||||
|
messagebox.showwarning("Info", "Folder remote belum dipilih.")
|
||||||
|
return
|
||||||
|
|
||||||
|
for (no_rawat,) in identifiers:
|
||||||
|
pdf_path = generate_pdf(username, password, no_rawat, cookies, folder_pdf)
|
||||||
|
if pdf_path:
|
||||||
|
preload_js_assets(session)
|
||||||
|
upload_file(session, session.headers, pdf_path, remote_folder)
|
||||||
|
|
||||||
|
# ---- UI
|
||||||
|
app = tk.Tk()
|
||||||
|
app.title("Downloader dan Uploader PDF JKN DRIVE (Ranap)")
|
||||||
|
app.geometry("560x420")
|
||||||
|
|
||||||
|
tk.Label(app, text="Tanggal (YYYY-MM-DD):").grid(row=0, column=0, sticky='e', padx=6, pady=6)
|
||||||
|
entry_tanggal1 = tk.Entry(app); entry_tanggal1.grid(row=0, column=1, sticky='we', padx=6, pady=6)
|
||||||
|
|
||||||
|
tk.Label(app, text="Username RS:").grid(row=1, column=0, sticky='e', padx=6, pady=6)
|
||||||
|
entry_username = tk.Entry(app); entry_username.grid(row=1, column=1, sticky='we', padx=6, pady=6)
|
||||||
|
|
||||||
|
tk.Label(app, text="Password RS:").grid(row=2, column=0, sticky='e', padx=6, pady=6)
|
||||||
|
entry_password = tk.Entry(app, show='*'); entry_password.grid(row=2, column=1, sticky='we', padx=6, pady=6)
|
||||||
|
|
||||||
|
tk.Label(app, text="Username Drive:").grid(row=3, column=0, sticky='e', padx=6, pady=6)
|
||||||
|
entry_usernamejkn = tk.Entry(app); entry_usernamejkn.grid(row=3, column=1, sticky='we', padx=6, pady=6)
|
||||||
|
|
||||||
|
tk.Label(app, text="Password Drive:").grid(row=4, column=0, sticky='e', padx=6, pady=6)
|
||||||
|
entry_passwordjkn = tk.Entry(app, show='*'); entry_passwordjkn.grid(row=4, column=1, sticky='we', padx=6, pady=6)
|
||||||
|
|
||||||
|
tk.Label(app, text="Folder Simpan PDF:").grid(row=5, column=0, sticky='e', padx=6, pady=6)
|
||||||
|
entry_folder = tk.Entry(app); entry_folder.grid(row=5, column=1, sticky='we', padx=6, pady=6)
|
||||||
|
ttk.Button(app, text="Pilih Folder", command=lambda: entry_folder.insert(0, filedialog.askdirectory())).grid(row=5, column=2, padx=6, pady=6)
|
||||||
|
|
||||||
|
tk.Label(app, text="Cookies File / String:").grid(row=6, column=0, sticky='e', padx=6, pady=6)
|
||||||
|
entry_cookies = tk.Entry(app); entry_cookies.grid(row=6, column=1, sticky='we', padx=6, pady=6)
|
||||||
|
ttk.Button(app, text="Pilih Cookies", command=select_cookies).grid(row=6, column=2, padx=6, pady=6)
|
||||||
|
ttk.Button(app, text="Ambil Cookies", command=ambil_cookies).grid(row=6, column=3, padx=6, pady=6)
|
||||||
|
|
||||||
|
ttk.Button(app, text="Proses", command=process_files).grid(row=7, column=1, pady=20)
|
||||||
|
ttk.Button(app, text="⬅ Kembali ke Menu Utama", command=kembali_ke_menu).grid(row=7, column=2, pady=20)
|
||||||
|
app.grid_columnconfigure(1, weight=1)
|
||||||
|
app.mainloop()
|
||||||
342
SubModules/ranapnoupload.py
Normal file
342
SubModules/ranapnoupload.py
Normal file
@@ -0,0 +1,342 @@
|
|||||||
|
# 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 config_loader import Config
|
||||||
|
from SubModules import auth
|
||||||
|
import mysql.connector
|
||||||
|
import pyttsx3
|
||||||
|
import requests
|
||||||
|
from playwright.sync_api import sync_playwright, TimeoutError as PWTimeoutError
|
||||||
|
import sys
|
||||||
|
import threading
|
||||||
|
from datetime import datetime, timedelta, date
|
||||||
|
|
||||||
|
|
||||||
|
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'
|
||||||
|
|
||||||
|
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) -> date | None:
|
||||||
|
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 mark_failed(no_rawat: str, base_folder: str):
|
||||||
|
"""Append a failed no_rawat to Gagal_Download.txt for retry."""
|
||||||
|
path_gagal = os.path.join(base_folder, "Gagal_Download.txt")
|
||||||
|
os.makedirs(base_folder, exist_ok=True)
|
||||||
|
with open(path_gagal, "a", encoding="utf-8") as f:
|
||||||
|
f.write(f"{no_rawat}\n")
|
||||||
|
|
||||||
|
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 FROM mlite_vedika WHERE status = 'Pengajuan' AND jenis = '1'
|
||||||
|
AND (no_rkm_medis OR no_rawat OR nosep)
|
||||||
|
AND no_rawat IN (SELECT no_rawat FROM kamar_inap WHERE tgl_keluar BETWEEN '{tanggal_awal}' AND '{tanggal_akhir}' AND kamar_inap.stts_pulang LIKE '%Pulang%')
|
||||||
|
"""
|
||||||
|
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(args=["--disable-dev-shm-usage"])
|
||||||
|
context = browser.new_context()
|
||||||
|
page = context.new_page()
|
||||||
|
|
||||||
|
try:
|
||||||
|
page.set_content(html_content, wait_until="domcontentloaded", timeout=90_000)
|
||||||
|
except PWTimeoutError:
|
||||||
|
page.set_content(html_content, wait_until="load", timeout=90_000)
|
||||||
|
page.wait_for_timeout(500)
|
||||||
|
|
||||||
|
page.pdf(path=output_path, format='A4', print_background=True)
|
||||||
|
browser.close()
|
||||||
|
|
||||||
|
def generate_pdf(username, password, no_rawat, cookies, base_folder, urutan, total, max_retry=3):
|
||||||
|
for attempt in range(1, max_retry + 1):
|
||||||
|
try:
|
||||||
|
modified_string = no_rawat.replace("/", "")
|
||||||
|
url = f'{cfg.Url.mlite}/admin/vedika/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('"', '')
|
||||||
|
|
||||||
|
if not no_sep_value:
|
||||||
|
if attempt == max_retry:
|
||||||
|
mark_failed(no_rawat, base_folder)
|
||||||
|
return f"{Color.RED}[{urutan}/{total}] GAGAL (x{attempt}): No.SEP tidak ditemukan untuk {no_rawat}{Color.RESET}", False
|
||||||
|
continue
|
||||||
|
|
||||||
|
d = extract_date_from_no_rawat(no_rawat)
|
||||||
|
if d is None:
|
||||||
|
target_dir = base_folder
|
||||||
|
else:
|
||||||
|
target_dir = os.path.join(base_folder, d.strftime("%d"))
|
||||||
|
os.makedirs(target_dir, exist_ok=True)
|
||||||
|
|
||||||
|
|
||||||
|
filename = f"{no_sep_value}.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:
|
||||||
|
mark_failed(no_rawat, base_folder)
|
||||||
|
return f"{Color.RED}[{urutan}/{total}] GAGAL (x{attempt}): 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:
|
||||||
|
mark_failed(no_rawat, base_folder)
|
||||||
|
return f"{Color.RED}[{urutan}/{total}] GAGAL (x{attempt}): 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:
|
||||||
|
no_rawat = row[0]
|
||||||
|
with lock:
|
||||||
|
index_counter['current'] += 1
|
||||||
|
urutan = index_counter['current']
|
||||||
|
|
||||||
|
message, success = generate_pdf(username, password, no_rawat, cookies, path_folder, urutan, total)
|
||||||
|
|
||||||
|
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) # <<< NEW
|
||||||
|
|
||||||
|
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)).start()
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
app = tk.Tk()
|
||||||
|
app.title("Downloader PDF Ranap Non Upload")
|
||||||
|
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=0, column=0, sticky='e')
|
||||||
|
entry_tanggal_akhir = tk.Entry(app)
|
||||||
|
entry_tanggal_akhir.grid(row=0, 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()
|
||||||
356
SubModules/veronisa.py
Normal file
356
SubModules/veronisa.py
Normal file
@@ -0,0 +1,356 @@
|
|||||||
|
# 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 <td> 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()
|
||||||
19
app.config
Normal file
19
app.config
Normal file
@@ -0,0 +1,19 @@
|
|||||||
|
[Database]
|
||||||
|
Host =
|
||||||
|
Port =
|
||||||
|
Database =
|
||||||
|
User =
|
||||||
|
Password =
|
||||||
|
|
||||||
|
[Paths]
|
||||||
|
base_path = /SHARE/
|
||||||
|
path_wkthmltopdf = C:/Program Files/wkhtmltopdf/bin/wkhtmltopdf.exe
|
||||||
|
|
||||||
|
|
||||||
|
[Url]
|
||||||
|
jknurl = https://jkn-drive.bpjs-kesehatan.go.id
|
||||||
|
mlite = https://mlite.rsubunda.com
|
||||||
|
|
||||||
|
[UserPass]
|
||||||
|
USERNAME =
|
||||||
|
PASSWORD =
|
||||||
35
config_loader.py
Normal file
35
config_loader.py
Normal file
@@ -0,0 +1,35 @@
|
|||||||
|
import configparser
|
||||||
|
import os
|
||||||
|
|
||||||
|
class Config:
|
||||||
|
def __init__(self, config_path='app.config'):
|
||||||
|
self.config = configparser.ConfigParser()
|
||||||
|
self.config.read(config_path)
|
||||||
|
|
||||||
|
self.Database = self.DatabaseConfig(self.config)
|
||||||
|
self.Paths = self.PathsConfig(self.config)
|
||||||
|
self.Url = self.UrlConfig(self.config)
|
||||||
|
self.UserPass = self.UserPassConfig(self.config)
|
||||||
|
|
||||||
|
class DatabaseConfig:
|
||||||
|
def __init__(self, config):
|
||||||
|
self.host = config['Database'].get('Host')
|
||||||
|
self.port = config['Database'].getint('Port')
|
||||||
|
self.database = config['Database'].get('Database')
|
||||||
|
self.user = config['Database'].get('User')
|
||||||
|
self.password = config['Database'].get('Password')
|
||||||
|
|
||||||
|
class PathsConfig:
|
||||||
|
def __init__(self, config):
|
||||||
|
self.base_path = config['Paths'].get('base_path')
|
||||||
|
self.wkhtmlfolder = config['Paths'].get('path_wkthmltopdf')
|
||||||
|
|
||||||
|
class UrlConfig:
|
||||||
|
def __init__(self, config):
|
||||||
|
self.jkn = config['Url'].get('jknurl')
|
||||||
|
self.mlite = config['Url'].get('mlite')
|
||||||
|
|
||||||
|
class UserPassConfig:
|
||||||
|
def __init__(self, config):
|
||||||
|
self.username = config['UserPass'].get('USERNAME')
|
||||||
|
self.password = config['UserPass'].get('PASSWORD')
|
||||||
216
main.py
Normal file
216
main.py
Normal file
@@ -0,0 +1,216 @@
|
|||||||
|
# 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 sys
|
||||||
|
import importlib
|
||||||
|
import signal
|
||||||
|
import ctypes
|
||||||
|
import atexit
|
||||||
|
import tkinter as tk
|
||||||
|
from tkinter import ttk, messagebox
|
||||||
|
from typing import Optional
|
||||||
|
|
||||||
|
APP_TITLE = "JOBS EASIER"
|
||||||
|
APP_SIZE = (520, 340)
|
||||||
|
SPLASH_SIZE = (420, 260)
|
||||||
|
SPLASH_DURATION_MS = 1800
|
||||||
|
SPLASH_STEP_MS = 60
|
||||||
|
LOGO_FILENAME = ""
|
||||||
|
|
||||||
|
if getattr(sys, "frozen", False):
|
||||||
|
os.environ["PLAYWRIGHT_BROWSERS_PATH"] = os.path.join(sys._MEIPASS, "ms-playwright")
|
||||||
|
|
||||||
|
def _safe_exit():
|
||||||
|
try:
|
||||||
|
r = tk._default_root
|
||||||
|
if r:
|
||||||
|
try:
|
||||||
|
for w in list(r.winfo_children()):
|
||||||
|
try:
|
||||||
|
w.destroy()
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
r.destroy()
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
os._exit(0)
|
||||||
|
|
||||||
|
try:
|
||||||
|
signal.signal(signal.SIGINT, lambda s, f: _safe_exit())
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
|
try:
|
||||||
|
HANDLER_ROUTINE = ctypes.WINFUNCTYPE(ctypes.c_bool, ctypes.c_uint)
|
||||||
|
def _console_handler(ctrl_type):
|
||||||
|
_safe_exit()
|
||||||
|
return True
|
||||||
|
ctypes.windll.kernel32.SetConsoleCtrlHandler(HANDLER_ROUTINE(_console_handler), True)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
|
atexit.register(_safe_exit)
|
||||||
|
|
||||||
|
def _bind_close(win: tk.Misc):
|
||||||
|
try:
|
||||||
|
win.protocol("WM_DELETE_WINDOW", _safe_exit)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
|
def resource_path(rel_path: str) -> str:
|
||||||
|
base = getattr(sys, "_MEIPASS", os.path.abspath(os.path.dirname(__file__)))
|
||||||
|
return os.path.join(base, rel_path)
|
||||||
|
|
||||||
|
def center_window(win: tk.Tk, w: int, h: int) -> None:
|
||||||
|
win.update_idletasks()
|
||||||
|
sw = win.winfo_screenwidth()
|
||||||
|
sh = win.winfo_screenheight()
|
||||||
|
x = (sw - w) // 2
|
||||||
|
y = (sh - h) // 3
|
||||||
|
win.geometry(f"{w}x{h}+{x}+{y}")
|
||||||
|
|
||||||
|
class Splash(tk.Toplevel):
|
||||||
|
def __init__(self, parent: tk.Tk, on_finish):
|
||||||
|
super().__init__(parent)
|
||||||
|
self.parent = parent
|
||||||
|
self.on_finish = on_finish
|
||||||
|
self.overrideredirect(True)
|
||||||
|
self.configure(bg="#ffffff")
|
||||||
|
|
||||||
|
wrapper = tk.Frame(self, bg="#ffffff", bd=0, highlightthickness=1, highlightbackground="#e5e5e5")
|
||||||
|
wrapper.pack(fill="both", expand=True, padx=1, pady=1)
|
||||||
|
content = tk.Frame(wrapper, bg="#ffffff", padx=16, pady=16)
|
||||||
|
content.pack(fill="both", expand=True)
|
||||||
|
|
||||||
|
self._logo_img = None
|
||||||
|
logo_path = resource_path(LOGO_FILENAME)
|
||||||
|
if os.path.exists(logo_path):
|
||||||
|
try:
|
||||||
|
self._logo_img = tk.PhotoImage(file=logo_path)
|
||||||
|
tk.Label(content, image=self._logo_img, bg="#ffffff").pack(pady=(4, 10))
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
|
tk.Label(content, text="Auto Downloader Vedika & Veronisa", font=("", 14, "bold"), bg="#ffffff").pack()
|
||||||
|
tk.Label(
|
||||||
|
content,
|
||||||
|
text="© 2025 Andy Cahyono Putra\nAladdin Free Public License",
|
||||||
|
font=("", 9), fg="#555555", bg="#ffffff", justify="center"
|
||||||
|
).pack(pady=(6, 14))
|
||||||
|
|
||||||
|
self.progress = ttk.Progressbar(content, mode="determinate", length=260, maximum=100)
|
||||||
|
self.progress.pack(pady=(0, 8))
|
||||||
|
tk.Label(content, text="Memuat komponen…", font=("", 9), fg="#777777", bg="#ffffff").pack()
|
||||||
|
|
||||||
|
self.update_idletasks()
|
||||||
|
center_window(self, *SPLASH_SIZE)
|
||||||
|
|
||||||
|
_bind_close(self)
|
||||||
|
|
||||||
|
self._elapsed = 0
|
||||||
|
self._tick()
|
||||||
|
|
||||||
|
def _tick(self):
|
||||||
|
total = SPLASH_DURATION_MS
|
||||||
|
step = SPLASH_STEP_MS
|
||||||
|
self._elapsed += step
|
||||||
|
pct = min(int(self._elapsed / total * 100), 100)
|
||||||
|
self.progress["value"] = pct
|
||||||
|
|
||||||
|
if self._elapsed < total:
|
||||||
|
self.after(step, self._tick)
|
||||||
|
else:
|
||||||
|
try:
|
||||||
|
self.destroy()
|
||||||
|
finally:
|
||||||
|
if callable(self.on_finish):
|
||||||
|
self.on_finish()
|
||||||
|
|
||||||
|
def launch_script_module(root: tk.Tk, module_path: str, entrypoint: Optional[str] = None, class_entry: Optional[str] = None):
|
||||||
|
root.withdraw()
|
||||||
|
try:
|
||||||
|
mod = importlib.import_module(module_path)
|
||||||
|
except Exception as e:
|
||||||
|
root.deiconify()
|
||||||
|
messagebox.showerror("Error", f"Gagal mengimpor modul:\n{module_path}\n\n{e}")
|
||||||
|
return
|
||||||
|
|
||||||
|
try:
|
||||||
|
if entrypoint and hasattr(mod, entrypoint):
|
||||||
|
root.destroy()
|
||||||
|
tk._default_root = None
|
||||||
|
getattr(mod, entrypoint)()
|
||||||
|
return
|
||||||
|
|
||||||
|
if class_entry and hasattr(mod, class_entry):
|
||||||
|
cls = getattr(mod, class_entry)
|
||||||
|
root.destroy()
|
||||||
|
tk._default_root = None
|
||||||
|
app = cls()
|
||||||
|
if hasattr(app, "mainloop"):
|
||||||
|
app.mainloop()
|
||||||
|
return
|
||||||
|
root.destroy()
|
||||||
|
tk._default_root = None
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
root.deiconify()
|
||||||
|
messagebox.showerror("Error", f"Gagal menjalankan {module_path}:\n{e}")
|
||||||
|
|
||||||
|
def build_main_menu(root: tk.Tk):
|
||||||
|
root.title(APP_TITLE)
|
||||||
|
|
||||||
|
try:
|
||||||
|
style = ttk.Style()
|
||||||
|
if "vista" in style.theme_names():
|
||||||
|
style.theme_use("vista")
|
||||||
|
elif "clam" in style.theme_names():
|
||||||
|
style.theme_use("clam")
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
|
root.geometry(f"{APP_SIZE[0]}x{APP_SIZE[1]}")
|
||||||
|
center_window(root, *APP_SIZE)
|
||||||
|
|
||||||
|
container = ttk.Frame(root, padding=16)
|
||||||
|
container.pack(fill="both", expand=True)
|
||||||
|
|
||||||
|
title = ttk.Label(
|
||||||
|
container,
|
||||||
|
text="Another Tools To Make Your Jobs Easier — Python Version",
|
||||||
|
wraplength=420,
|
||||||
|
font=("", 11, "bold"),
|
||||||
|
)
|
||||||
|
title.pack(pady=(0, 12))
|
||||||
|
buttons = [
|
||||||
|
("Ranap (Dengan Upload JKN)", lambda: launch_script_module(root, "SubModules.ranap", entrypoint="main")),
|
||||||
|
("Ralan (Dengan Upload JKN)", lambda: launch_script_module(root, "SubModules.ralan", entrypoint="main")),
|
||||||
|
("Mass Upload", lambda: launch_script_module(root, "SubModules.massupload", class_entry="JKNApp")),
|
||||||
|
("Ralan (Tanpa Upload)", lambda: launch_script_module(root, "SubModules.ralannoupload", entrypoint="main")),
|
||||||
|
("Ranap (Tanpa Upload)", lambda: launch_script_module(root, "SubModules.ranapnoupload", class_entry="RanapNonUpload")),
|
||||||
|
("Veronisa", lambda: launch_script_module(root, "SubModules.veronisa")),
|
||||||
|
]
|
||||||
|
for text, cmd in buttons:
|
||||||
|
ttk.Button(container, text=text, command=cmd).pack(pady=6, fill="x")
|
||||||
|
_bind_close(root)
|
||||||
|
root.bind("<Escape>", lambda e: _safe_exit())
|
||||||
|
|
||||||
|
def main():
|
||||||
|
root = tk.Tk()
|
||||||
|
root.withdraw()
|
||||||
|
_bind_close(root)
|
||||||
|
|
||||||
|
def after_splash():
|
||||||
|
build_main_menu(root)
|
||||||
|
root.deiconify()
|
||||||
|
|
||||||
|
Splash(root, on_finish=after_splash)
|
||||||
|
root.mainloop()
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
8
requirements.txt
Normal file
8
requirements.txt
Normal file
@@ -0,0 +1,8 @@
|
|||||||
|
beautifulsoup4
|
||||||
|
requests
|
||||||
|
pdfkit
|
||||||
|
mysql-connector-python
|
||||||
|
tk
|
||||||
|
requests-toolbelt
|
||||||
|
pyttsx3
|
||||||
|
playwright
|
||||||
Reference in New Issue
Block a user