File size: 1,942 Bytes
1f1b4db
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import xml.etree.ElementTree as ET
from pathlib import Path
from typing import Optional, List


class APIKeyManager:
    def __init__(self, config_path: str = "config/api_keys.xml"):
        self.config_path = Path(config_path)
        self._api_keys: List[str] = []
        self._load_keys()

    def _load_keys(self):
        """Load API keys from XML file"""
        if not self.config_path.exists():
            self._create_default_config()

        tree = ET.parse(self.config_path)
        root = tree.getroot()

        self._api_keys = [key.text for key in root.findall("key")]

    def _create_default_config(self):
        """Create default XML config file"""
        self.config_path.parent.mkdir(parents=True, exist_ok=True)

        root = ET.Element("api_keys")
        tree = ET.ElementTree(root)
        tree.write(self.config_path, encoding="utf-8", xml_declaration=True)

    def get_key(self, index: int = 0) -> Optional[str]:
        """Get API key by index"""
        try:
            return self._api_keys[index]
        except IndexError:
            return None

    def add_key(self, api_key: str):
        """Add new API key"""
        root = ET.parse(self.config_path).getroot()
        new_key = ET.SubElement(root, "key")
        new_key.text = api_key

        tree = ET.ElementTree(root)
        tree.write(self.config_path, encoding="utf-8", xml_declaration=True)

        self._api_keys.append(api_key)

    def remove_key(self, index: int):
        """Remove API key by index"""
        root = ET.parse(self.config_path).getroot()
        keys = root.findall("key")

        if 0 <= index < len(keys):
            root.remove(keys[index])
            tree = ET.ElementTree(root)
            tree.write(self.config_path, encoding="utf-8", xml_declaration=True)

            self._api_keys.pop(index)

    def list_keys(self) -> List[str]:
        """List all API keys"""
        return self._api_keys.copy()