-
Notifications
You must be signed in to change notification settings - Fork 43
/
generate_from_url.py
134 lines (101 loc) · 4.24 KB
/
generate_from_url.py
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
"""
generate_from_url.py
This script is used to generate an app config file from an Obtainium redirect URL.
"""
from urllib.parse import unquote
import json
import os
from colorama import Fore, init
init(autoreset=True)
APP_URL_PREFIX = "obtainium://app/"
APP_DATA_PATH = "./data/apps/"
def is_obtainium_url(url):
"""Check if the URL is valid."""
return APP_URL_PREFIX in url
def extract_json_from_obtainium_url(url):
"""Extract JSON from the URL."""
raw_json = url.split(APP_URL_PREFIX, 1)[1]
try:
return json.loads(raw_json)
except json.JSONDecodeError:
print(Fore.RED + "Invalid JSON. Please check the URL and try again.")
return None
def create_new_config():
"""Create a new app config file."""
url_input = input("Input URL to extract JSON from: ")
decoded_url = unquote(url_input)
if not is_obtainium_url(decoded_url):
print(Fore.RED + "Invalid URL. Please try again.")
return
app_config_json = extract_json_from_obtainium_url(decoded_url)
if app_config_json is None:
return
new_app_json = {
"configs": [app_config_json],
"icon": None,
"categories": ["other"],
"description": {"en": None}
}
app_file_path = APP_DATA_PATH + new_app_json["configs"][0]["id"] + ".json"
original_app_file_path = app_file_path
existing_files = []
if os.path.exists(app_file_path):
existing_files.append(app_file_path)
suffix = 1
while os.path.exists(f"{original_app_file_path[:-5]}-{suffix}.json"):
existing_files.append(f"{original_app_file_path[:-5]}-{suffix}.json")
suffix += 1
if existing_files:
print(Fore.YELLOW + "The following files already exist:")
for file in existing_files:
print(Fore.YELLOW + file)
user_choice = input("Do you want to add the file anyway with a different name? (y/n): ")
if user_choice.lower() == 'y':
app_file_path = f"{original_app_file_path[:-5]}-{suffix}.json"
else:
print(Fore.RED + "Operation cancelled. Please try updating an existing config instead.")
return
os.makedirs(os.path.dirname(app_file_path), exist_ok=True)
with open(app_file_path, "w", encoding="utf-8") as app_file:
json.dump(new_app_json, app_file, indent=4, ensure_ascii=False)
app_file.write('\n')
print(Fore.GREEN + f"File created at {app_file_path}")
print(Fore.BLUE + "Ensure that you edit the created JSON file to add categories, descriptions and an icon.")
def update_existing_config():
"""Add an additional config to an existing config file."""
url_input = unquote(input("Input URL to extract JSON from: "))
if not is_obtainium_url(url_input):
print(Fore.RED + "Invalid URL. Please try again.")
return
app_file_name_input = input("Input file to add config to: ")
if not app_file_name_input.endswith('.json'):
app_file_name_input += '.json'
app_file_path = APP_DATA_PATH + app_file_name_input
if not os.path.exists(app_file_path):
print(Fore.RED + f"File {app_file_path} does not exist. Please try creating a new config instead.")
return
app_config_json = extract_json_from_obtainium_url(url_input)
if app_config_json is None:
return
with open(app_file_path, "r", encoding="utf-8") as app_file:
existing_app_data = json.load(app_file)
existing_app_data["configs"].append(app_config_json)
for config in existing_app_data["configs"]:
if 'altLabel' not in config:
config['altLabel'] = None
with open(app_file_path, "w", encoding="utf-8") as app_file:
json.dump(existing_app_data, app_file, indent=4, ensure_ascii=False)
print(Fore.GREEN + f"Config added to {app_file_path}")
print(Fore.BLUE + "Ensure that you edit the modified JSON file to add altLabels.")
def main():
"""Main function."""
print("1. Create new app config")
print("2. Add config to already existing app config file")
user_choice = input("Enter your choice: ")
actions = {"1": create_new_config, "2": update_existing_config}
if user_choice in actions:
actions[user_choice]()
else:
print(Fore.RED + "Invalid choice")
if __name__ == "__main__":
main()