3 Tool to create overview.json files and update the config.js.
6 from pathlib
import Path
16 SUPPORTED_METADATA_VERSION
= 1
19 # accepts {<file-path>: <file-content>}
20 def merge_profiles(profiles
, download_url
):
28 return "{} {} {}".format(
29 title
.get("vendor", ""), title
["model"], title
.get("variant", "")
32 def add_profile(id, target
, profile
, code
=None):
34 for image
in profile
["images"]:
35 images
.append({"name": image
["name"], "type": image
["type"]})
38 target
= profile
["target"]
40 for entry
in profile
["titles"]:
41 title
= get_title(entry
)
44 sys
.stderr
.write("Empty title. Skip title for {}".format(id))
47 output
["models"][title
] = {"id": id, "target": target
, "images": images
}
50 output
["models"][title
]["code"] = code
52 for path
, content
in profiles
.items():
53 obj
= json
.loads(content
)
55 if obj
["metadata_version"] != SUPPORTED_METADATA_VERSION
:
57 "{} has unsupported metadata version: {} => skip".format(
58 path
, obj
["metadata_version"]
63 code
= obj
.get("version_code", obj
.get("version_commit"))
65 if "version_code" not in output
:
66 output
= {"version_code": code
, "download_url": download_url
, "models": {}}
68 # if we have mixed codes/commits, store in device object
69 if output
["version_code"] == code
:
74 for id in obj
["profiles"]:
75 add_profile(id, obj
.get("target"), obj
["profiles"][id], code
)
77 add_profile(obj
["id"], obj
["target"], obj
, code
)
78 except json
.decoder
.JSONDecodeError
as e
:
79 sys
.stderr
.write("Skip {}\n {}\n".format(path
, e
))
81 sys
.stderr
.write("Abort on {}\n Missing key {}\n".format(path
, e
))
87 def update_config(config_path
, versions
):
89 with
open(config_path
, "r") as file:
92 content
= re
.sub("versions:[\\s]*{[^}]*}", "versions: {}".format(versions
), content
)
93 with
open(config_path
, "w+") as file:
98 Scrape profiles.json using links like https://downloads.openwrt.org/releases/19.07.3/targets/?json
99 Merge into overview.json files.
106 selector_path
= args
.selector
107 config_path
= "{}/config.js".format(selector_path
)
108 data_path
= "{}/data".format(selector_path
)
111 def handle_release(target
):
113 with urllib
.request
.urlopen("{}/?json".format(target
)) as file:
114 array
= json
.loads(file.read().decode("utf-8"))
115 for profile
in filter(lambda x
: x
.endswith("/profiles.json"), array
):
116 with urllib
.request
.urlopen("{}/{}".format(target
, profile
)) as file:
117 profiles
["{}/{}".format(target
, profile
)] = file.read()
120 if not os
.path
.isfile(config_path
):
121 print("file not found: {}".format(config_path
))
125 with urllib
.request
.urlopen(url
) as infile
:
126 for path
in re
.findall(r
"href=[\"']?([^'\" >]+)", str(infile.read())):
127 if not path.startswith("/") and path.endswith("targets
/"):
128 release = path.strip("/").split("/")[-2]
129 download_url = "{}/{}/{{target}
}".format(url, path)
131 profiles = handle_release("{}/{}".format(url, path))
132 output = merge_profiles(profiles, download_url)
134 os.makedirs("{}/{}".format(data_path, release), exist_ok=True)
135 # write overview.json
137 "{}/{}/overview
.json
".format(data_path, release), "w
"
140 json.dump(output, outfile, indent=" ", sort_keys=True)
142 json.dump(output, outfile, sort_keys=True)
144 versions[release.upper()] = "data
/{}/overview
.json
".format(release)
146 update_config(config_path, versions)
150 Scrape profiles.json using wget (slower but more generic).
151 Merge into overview.json files.
156 def scrape_wget(args):
158 selector_path = args.selector
159 config_path = "{}/config
.js
".format(selector_path)
160 data_path = "{}/data
".format(selector_path)
163 with tempfile.TemporaryDirectory() as tmp_dir:
164 # download all profiles.json files
166 "wget
-c
-r
-P
{} -A
'profiles.json' --reject
-regex
'kmods|packages' --no
-parent
{}".format(
171 # delete empty folders
172 os.system("find
{}/* -type d
-empty
-delete
".format(tmp_dir))
174 # create overview.json files
175 for path in glob.glob("{}/*/snapshots
".format(tmp_dir)) + glob.glob(
176 "{}/*/releases
/*".format(tmp_dir)
178 release = os.path.basename(path)
179 base = path[len(tmp_dir) + 1 :]
182 for ppath in Path(path).rglob("profiles
.json
"):
183 with open(ppath, "r
") as file:
184 profiles[ppath] = file.read()
186 if len(profiles) == 0:
189 versions[release.upper()] = "data
/{}/overview
.json
".format(release)
191 output = merge_profiles(
192 profiles, "https
://{}/targets
/{{target}
}".format(base)
194 os.makedirs("{}/{}".format(data_path, release), exist_ok=True)
196 # write overview.json
197 with open("{}/{}/overview
.json
".format(data_path, release), "w
") as outfile:
199 json.dump(output, outfile, indent=" ", sort_keys=True)
201 json.dump(output, outfile, sort_keys=True)
203 update_config(config_path, versions)
207 Find and merge json files for a single release.
212 input_paths = args.input_path
213 # OpenWrt JSON device files
217 with open(path, "r
") as file:
218 profiles[path] = file.read()
220 for path in input_paths:
221 if os.path.isdir(path):
222 for filepath in Path(path).rglob("*.json
"):
225 if not path.endswith(".json
"):
226 sys.stderr.write("Folder does
not exists
: {}\n".format(path))
230 output = merge_profiles(profiles, args.download_url)
233 json.dump(output, sys.stdout, indent=" ", sort_keys=True)
235 json.dump(output, sys.stdout, sort_keys=True)
239 Scan local directory for releases with profiles.json.
240 Merge into overview.json files.
246 selector_path = args.selector
247 config_path = "{}/config
.js
".format(selector_path)
248 data_path = "{}/data
".format(selector_path)
251 # create overview.json files
252 for path in glob.glob("{}/snapshots
".format(args.directory)) + glob.glob(
253 "{}/releases
/*".format(args.directory)
255 release = os.path.basename(path)
256 base_dir = path[len(args.directory) + 1 :]
259 for ppath in Path(path).rglob("profiles
.json
"):
260 with open(ppath, "r
") as file:
261 profiles[ppath] = file.read()
263 if len(profiles) == 0:
266 versions[release.upper()] = "data
/{}/overview
.json
".format(release)
268 output = merge_profiles(
269 profiles, "https
://{}/{}/targets
/{{target}
}".format(args.domain, base_dir)
271 os.makedirs("{}/{}".format(data_path, release), exist_ok=True)
273 # write overview.json
274 with open("{}/{}/overview
.json
".format(data_path, release), "w
") as outfile:
276 json.dump(output, outfile, indent=" ", sort_keys=True)
278 json.dump(output, outfile, sort_keys=True)
280 update_config(config_path, versions)
284 parser = argparse.ArgumentParser()
286 "--formatted
", action="store_true
", help="Output formatted JSON data
."
288 subparsers = parser.add_subparsers(dest="action
")
289 subparsers.required = True
291 parser_merge = subparsers.add_parser(
293 help="Create a grid structure with horizontal
and vertical connections
.",
295 parser_merge.add_argument(
298 help="Input folder that
is traversed
for OpenWrt JSON device files
.",
300 parser_merge.add_argument(
304 help="Link to get the image
from. May contain {target}
, {version}
and {commit}
",
307 parser_scrape = subparsers.add_parser("scrape
", help="Scrape webpage
for releases
.")
308 parser_scrape.add_argument(
309 "domain
", help="Domain to scrape
. E
.g
. https
://downloads
.openwrt
.org
"
311 parser_scrape.add_argument("selector
", help="Path the config
.js
file is in.")
312 parser_scrape.add_argument(
313 "--use
-wget
", action="store_true
", help="Use wget to scrape the site
."
316 parser_scan = subparsers.add_parser("scan
", help="Scan directory
for releases
.")
317 parser_scan.add_argument(
319 help="Domain
for download_url attribute
in overview
.json
. E
.g
. https
://downloads
.openwrt
.org
",
321 parser_scan.add_argument("directory
", help="Directory to scan
for releases
.")
322 parser_scan.add_argument("selector
", help="Path the config
.js
file is in.")
324 args = parser.parse_args()
326 if args.action == "merge
":
329 if args.action == "scan
":
332 if args.action == "scrape
":
339 if __name__ == "__main__
":