File size: 2,253 Bytes
32b00b0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
import os
import json
import uuid
from typing import Dict, Any

class ConfigManager:
    def __init__(self, session_id: str):
        self.session_id = session_id
        self.config_dir = f"/tmp/user_{session_id}"
        self.config_file = os.path.join(self.config_dir, "config.json")
        self.config: Dict[str, Any] = {}
        self.load_configs()

    def load_configs(self):
        self.config = {
            "pixiv_refresh_token": "",
            "output_dir": f"/tmp/user_{self.session_id}/output",
            "default_num_items": 100,
            "default_resize_size": 512,
            "language": "zh"
        }
        if os.path.exists(self.config_file):
            try:
                with open(self.config_file, 'r') as f:
                    self.config.update(json.load(f))
            except Exception as e:
                print(f"Failed to load session config: {e}")

    def save_configs(self):
        os.makedirs(self.config_dir, exist_ok=True)
        try:
            with open(self.config_file, 'w') as f:
                json.dump(self.config, f, indent=2)
        except Exception as e:
            print(f"Failed to save session config: {e}")

    def get_config(self, key: str, default: Any = None) -> Any:
        return self.config.get(key, default)

    def set_config(self, key: str, value: Any):
        self.config[key] = value
        self.save_configs()

    def get_all_configs(self) -> Dict[str, Any]:
        return self.config.copy()

    def export_config(self) -> str:
        export_path = os.path.join(self.config_dir, "config_export.json")
        with open(export_path, 'w') as f:
            json.dump(self.config, f, indent=2)
        return export_path

    def import_config(self, config_file):
        with open(config_file, 'r') as f:
            new_config = json.load(f)
        self.config.update(new_config)
        self.save_configs()
        return "Configuration imported" if self.config.get("language") == "en" else "配置已导入"

    def cleanup(self):
        try:
            shutil.rmtree(self.config_dir, ignore_errors=True)
        except Exception as e:
            print(f"Failed to cleanup session: {e}")