
import os
import time
import requests
import subprocess

# 配置信息
CHECK_URL = "https://zidian.shanghewan.cn/file/print_queue.txt"
PRINT_DIR = "./print_jobs"

if not os.path.exists(PRINT_DIR):
    os.makedirs(PRINT_DIR)

print("紫电远程打印客户端已启动，正在监听任务...")

def get_print_task():
    try:
        resp = requests.get(CHECK_URL, timeout=10)
        if resp.status_code == 200:
            return resp.text.strip()
    except:
        pass
    return None

while True:
    task_url = get_print_task()
    if task_url and task_url.startswith("http"):
        print(f"检测到新任务: {task_url}")
        try:
            filename = task_url.split("/")[-1]
            local_path = os.path.join(PRINT_DIR, filename)
            
            # 下载文件
            r = requests.get(task_url)
            with open(local_path, 'wb') as f:
                f.write(r.content)
            
            # 调用系统打印
            print(f"正在打印: {local_path}")
            if os.name == 'nt':
                os.startfile(local_path, "print")
            else:
                subprocess.run(["lp", local_path])
                
            # 清除任务标记（这里需要服务器配合，暂时模拟）
            print("任务处理完成")
            
        except Exception as e:
            print(f"处理任务失败: {e}")
            
    time.sleep(30)
