3 Tool to create overview.json files and update the config.js.
6 from pathlib
import Path
16 SUPPORTED_METADATA_VERSION
= 1
18 assert sys
.version_info
>= (3, 5), "Python version too old. Python >=3.5.0 needed."
21 # accepts {<file-path>: <file-content>}
22 def merge_profiles(profiles
, download_url
):
30 return "{} {} {}".format(
31 title
.get("vendor", ""), title
["model"], title
.get("variant", "")
34 def add_profile(path
, id, target
, profile
, code
=None):
36 for image
in profile
["images"]:
37 images
.append({"name": image
["name"], "type": image
["type"]})
40 target
= profile
["target"]
42 for entry
in profile
["titles"]:
43 title
= get_title(entry
)
47 "Empty title. Skip title for {} in {}\n".format(id, path
)
52 Some devices are in ar71xx and ath79. But use TP-LINK" and "TP-Link".
53 E.g: `TP-LINK Archer C7 v5` and `TP-Link Archer C7 v5`
54 To be able to detect this, we need to make "same" titles identical.
56 if title
.startswith("TP-LINK "):
57 title
= "TP-Link {}".format(title
[8:])
59 # device is a duplicate, try to differentiate by target
60 if title
in output
["models"]:
61 title
= "{} ({})".format(title
, target
)
63 output
["models"][title
] = {"id": id, "target": target
, "images": images
}
66 output
["models"][title
]["code"] = code
68 for path
, content
in profiles
.items():
69 obj
= json
.loads(content
)
71 if obj
["metadata_version"] != SUPPORTED_METADATA_VERSION
:
73 "{} has unsupported metadata version: {} => skip\n".format(
74 path
, obj
["metadata_version"]
79 code
= obj
.get("version_code", obj
.get("version_commit"))
81 if "version_code" not in output
:
82 output
= {"version_code": code
, "download_url": download_url
, "models": {}}
84 # if we have mixed codes/commits, store in device object
85 if output
["version_code"] == code
:
90 for id in obj
["profiles"]:
91 add_profile(path
, id, obj
.get("target"), obj
["profiles"][id], code
)
93 add_profile(path
, obj
["id"], obj
["target"], obj
, code
)
94 except json
.decoder
.JSONDecodeError
as e
:
95 sys
.stderr
.write("Skip {}\n {}\n".format(path
, e
))
97 sys
.stderr
.write("Abort on {}\n Missing key {}\n".format(path
, e
))
103 def update_config(config_path
, versions
):
105 with
open(str(config_path
), "r", encoding
="utf-8") as file:
106 content
= file.read()
108 content
= re
.sub("versions:[\\s]*{[^}]*}", "versions: {}".format(versions
), content
)
109 with
open(str(config_path
), "w+") as file:
114 Scrape profiles.json using links like https://downloads.openwrt.org/releases/19.07.3/targets/?json
115 Merge into overview.json files.
122 www_path
= args
.www_path
123 config_path
= "{}/config.js".format(www_path
)
124 data_path
= "{}/data".format(www_path
)
127 def handle_release(target
):
129 with urllib
.request
.urlopen("{}/?json".format(target
)) as file:
130 array
= json
.loads(file.read().decode("utf-8"))
131 for profile
in filter(lambda x
: x
.endswith("/profiles.json"), array
):
132 with urllib
.request
.urlopen("{}/{}".format(target
, profile
)) as file:
133 profiles
["{}/{}".format(target
, profile
)] = file.read().decode(
138 if not os
.path
.isfile(config_path
):
139 print("file not found: {}".format(config_path
))
143 with urllib
.request
.urlopen(url
) as infile
:
144 for path
in re
.findall(r
"href=[\"']?([^'\" >]+)", str(infile.read())):
145 if not path.startswith("/") and path.endswith("targets
/"):
146 release = path.strip("/").split("/")[-2]
147 download_url = "{}/{}/{{target}
}".format(url, path)
149 profiles = handle_release("{}/{}".format(url, path))
150 output = merge_profiles(profiles, download_url)
152 os.makedirs("{}/{}".format(data_path, release), exist_ok=True)
153 # write overview.json
155 "{}/{}/overview
.json
".format(data_path, release), "w
"
158 json.dump(output, outfile, indent=" ", sort_keys=True)
160 json.dump(output, outfile, sort_keys=True)
162 versions[release] = "data
/{}/overview
.json
".format(release)
164 update_config(config_path, versions)
168 Scrape profiles.json using wget (slower but more generic).
169 Merge into overview.json files.
174 def scrape_wget(args):
176 www_path = args.www_path
177 config_path = "{}/config
.js
".format(www_path)
178 data_path = "{}/data
".format(www_path)
181 with tempfile.TemporaryDirectory() as tmp_dir:
182 # download all profiles.json files
184 "wget
-c
-r
-P
{} -A
'profiles.json' --reject
-regex
'kmods|packages' --no
-parent
{}".format(
189 # delete empty folders
190 os.system("find
{}/* -type d
-empty
-delete
".format(tmp_dir))
192 # create overview.json files
193 for path in glob.glob("{}/*/snapshots
".format(tmp_dir)) + glob.glob(
194 "{}/*/releases
/*".format(tmp_dir)
196 release = os.path.basename(path)
197 base = path[len(tmp_dir) + 1 :]
200 for ppath in Path(path).rglob("profiles
.json
"):
201 with open(str(ppath), "r
", encoding="utf
-8") as file:
202 profiles[ppath] = file.read()
204 if len(profiles) == 0:
207 versions[release] = "data
/{}/overview
.json
".format(release)
209 output = merge_profiles(
210 profiles, "https
://{}/targets
/{{target}
}".format(base)
212 os.makedirs("{}/{}".format(data_path, release), exist_ok=True)
214 # write overview.json
215 with open("{}/{}/overview
.json
".format(data_path, release), "w
") as outfile:
217 json.dump(output, outfile, indent=" ", sort_keys=True)
219 json.dump(output, outfile, sort_keys=True)
221 update_config(config_path, versions)
225 Find and merge json files for a single release.
230 input_paths = args.input_path
231 # OpenWrt JSON device files
235 with open(str(path), "r
", encoding="utf
-8") as file:
236 profiles[path] = file.read()
238 for path in input_paths:
239 if os.path.isdir(path):
240 for filepath in Path(path).rglob("*.json
"):
243 if not path.endswith(".json
"):
244 sys.stderr.write("Folder does
not exists
: {}\n".format(path))
248 output = merge_profiles(profiles, args.download_url)
251 json.dump(output, sys.stdout, indent=" ", sort_keys=True)
253 json.dump(output, sys.stdout, sort_keys=True)
257 Scan local directory for releases with profiles.json.
258 Merge into overview.json files.
264 # firmware selector config
265 config_path = "{}/config
.js
".format(args.www_path)
266 # the overview.json files are placed here
267 data_path = "{}/data
".format(args.www_path)
270 # args.images_path => args.releases_path
272 for path in Path(args.images_path).rglob("profiles
.json
"):
273 with open(str(path), "r
", encoding="utf
-8") as file:
274 content = file.read()
275 obj = json.loads(content)
276 release = obj["version_number
"]
277 releases.setdefault(release, {})[path] = content
279 for release, profiles in releases.items():
280 output = merge_profiles(profiles, args.download_url)
282 versions[release] = "data
/{}/overview
.json
".format(release)
283 os.makedirs("{}/{}".format(data_path, release), exist_ok=True)
285 # write overview.json
286 with open("{}/{}/overview
.json
".format(data_path, release), "w
") as outfile:
288 json.dump(output, outfile, indent=" ", sort_keys=True)
290 json.dump(output, outfile, sort_keys=True)
292 update_config(config_path, versions)
296 parser = argparse.ArgumentParser()
298 "--formatted
", action="store_true
", help="Output formatted JSON data
."
300 subparsers = parser.add_subparsers(dest="action
")
301 subparsers.required = True
303 parser_merge = subparsers.add_parser(
304 "merge
", help="Search
for profiles
.json files
and output an overview
.json
."
306 parser_merge.add_argument(
309 help="Input folder that
is traversed
for OpenWrt JSON device files
.",
311 parser_merge.add_argument(
315 help="Link to get the image
from. May contain {target}
(replaced by e
.g
. ath79
/generic
), {version}
(replace by the version key
from config
.js
) and {commit}
(git commit
in hex notation
).",
318 parser_scrape = subparsers.add_parser("scrape
", help="Scrape webpage
for releases
.")
319 parser_scrape.add_argument(
320 "domain
", help="Domain to scrape
. E
.g
. https
://downloads
.openwrt
.org
"
322 parser_scrape.add_argument("www_path
", help="Path the config
.js
file is in.")
323 parser_scrape.add_argument(
324 "--use
-wget
", action="store_true
", help="Use wget to scrape the site
."
327 parser_scan = subparsers.add_parser("scan
", help="Scan directory
for releases
.")
328 parser_scan.add_argument(
329 "download_url
", help="Download
for images
. E
.g
. https
://downloads
.openwrt
.org
"
331 parser_scan.add_argument("images_path
", help="Directory to scan
for releases
.")
332 parser_scan.add_argument("www_path
", help="Path the config
.js
file is in.")
334 args = parser.parse_args()
336 if args.action == "merge
":
339 if args.action == "scan
":
342 if args.action == "scrape
":
349 if __name__ == "__main__
":