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 def add_profile(output
, path
, id, target
, profile
, code
=None):
26 return "{} {} {}".format(
27 title
.get("vendor", ""), title
["model"], title
.get("variant", "")
31 for image
in profile
["images"]:
32 images
.append({"name": image
["name"], "type": image
["type"]})
35 target
= profile
["target"]
37 for entry
in profile
["titles"]:
38 title
= get_title(entry
)
41 sys
.stderr
.write("Empty title. Skip title for {} in {}\n".format(id, path
))
45 Some devices are in ar71xx and ath79. But use TP-LINK" and "TP-Link".
46 E.g: `TP-LINK Archer C7 v5` and `TP-Link Archer C7 v5`
47 To be able to detect this, we need to make "same" titles identical.
49 if title
.startswith("TP-LINK "):
50 title
= "TP-Link {}".format(title
[8:])
52 # device is a duplicate, try to differentiate by target
53 if title
in output
["models"]:
54 title
= "{} ({})".format(title
, target
)
56 output
["models"][title
] = {"id": id, "target": target
, "images": images
}
59 output
["models"][title
]["code"] = code
62 # accepts {<file-path>: <file-content>}
63 def merge_profiles(profiles
, download_url
):
67 for profile
in profiles
:
68 obj
= json
.loads(profile
["file_content"])
70 if obj
["metadata_version"] != SUPPORTED_METADATA_VERSION
:
72 "{} has unsupported metadata version: {} => skip\n".format(
73 profile
["file_path"], obj
["metadata_version"]
78 code
= obj
.get("version_code", obj
.get("version_commit"))
79 file_path
= profile
["file_path"]
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"]:
100 add_profile(output
, file_path
, obj
["id"], obj
["target"], obj
, code
)
101 except json
.decoder
.JSONDecodeError
as e
:
102 sys
.stderr
.write("Skip {}\n {}\n".format(file_path
, e
))
103 except KeyError as e
:
104 sys
.stderr
.write("Abort on {}\n Missing key {}\n".format(file_path
, e
))
110 def update_config(config_path
, versions
):
112 with
open(str(config_path
), "r", encoding
="utf-8") as file:
113 content
= file.read()
115 content
= re
.sub("versions:[\\s]*{[^}]*}", "versions: {}".format(versions
), content
)
116 with
open(str(config_path
), "w+") as file:
121 Scrape profiles.json using links like https://downloads.openwrt.org/releases/19.07.3/targets/?json
122 Merge into overview.json files.
129 www_path
= args
.www_path
130 config_path
= "{}/config.js".format(www_path
)
131 data_path
= "{}/data".format(www_path
)
134 def handle_release(target
):
136 with urllib
.request
.urlopen("{}/?json".format(target
)) as file:
137 array
= json
.loads(file.read().decode("utf-8"))
138 for profile
in filter(lambda x
: x
.endswith("/profiles.json"), array
):
139 with urllib
.request
.urlopen("{}/{}".format(target
, profile
)) as file:
142 "file_path": "{}/{}".format(target
, profile
),
143 "file_content": file.read().decode("utf-8"),
148 if not os
.path
.isfile(config_path
):
149 print("file not found: {}".format(config_path
))
153 with urllib
.request
.urlopen(url
) as infile
:
154 for path
in re
.findall(r
"href=[\"']?([^'\" >]+)", str(infile.read())):
155 if not path.startswith("/") and path.endswith("targets
/"):
156 release = path.strip("/").split("/")[-2]
157 download_url = "{}/{}/{{target}
}".format(url, path)
159 profiles = handle_release("{}/{}".format(url, path))
160 output = merge_profiles(profiles, download_url)
162 os.makedirs("{}/{}".format(data_path, release), exist_ok=True)
163 # write overview.json
165 "{}/{}/overview
.json
".format(data_path, release), "w
"
168 json.dump(output, outfile, indent=" ", sort_keys=True)
170 json.dump(output, outfile, sort_keys=True)
172 versions[release] = "data
/{}/overview
.json
".format(release)
174 update_config(config_path, versions)
178 Scrape profiles.json using wget (slower but more generic).
179 Merge into overview.json files.
184 def scrape_wget(args):
186 www_path = args.www_path
187 config_path = "{}/config
.js
".format(www_path)
188 data_path = "{}/data
".format(www_path)
191 with tempfile.TemporaryDirectory() as tmp_dir:
192 # download all profiles.json files
194 "wget
-c
-r
-P
{} -A
'profiles.json' --reject
-regex
'kmods|packages' --no
-parent
{}".format(
199 # delete empty folders
200 os.system("find
{}/* -type d
-empty
-delete
".format(tmp_dir))
202 # create overview.json files
203 for path in glob.glob("{}/*/snapshots
".format(tmp_dir)) + glob.glob(
204 "{}/*/releases
/*".format(tmp_dir)
206 release = os.path.basename(path)
207 base = path[len(tmp_dir) + 1 :]
210 for ppath in Path(path).rglob("profiles
.json
"):
211 with open(str(ppath), "r
", encoding="utf
-8") as file:
213 {"file_path
": str(ppath), "file_content
": file.read()}
216 if len(profiles) == 0:
219 versions[release] = "data
/{}/overview
.json
".format(release)
221 output = merge_profiles(
222 profiles, "https
://{}/targets
/{{target}
}".format(base)
224 os.makedirs("{}/{}".format(data_path, release), exist_ok=True)
226 # write overview.json
227 with open("{}/{}/overview
.json
".format(data_path, release), "w
") as outfile:
229 json.dump(output, outfile, indent=" ", sort_keys=True)
231 json.dump(output, outfile, sort_keys=True)
233 update_config(config_path, versions)
237 Find and merge json files for a single release.
242 input_paths = args.input_path
243 # OpenWrt JSON device files
247 with open(str(path), "r
", encoding="utf
-8") as file:
248 profiles.append({"file_path
": str(path), "file_content
": file.read()})
250 for path in input_paths:
251 if os.path.isdir(path):
252 for filepath in Path(path).rglob("*.json
"):
255 if not path.endswith(".json
"):
256 sys.stderr.write("Folder does
not exists
: {}\n".format(path))
260 output = merge_profiles(profiles, args.download_url)
263 json.dump(output, sys.stdout, indent=" ", sort_keys=True)
265 json.dump(output, sys.stdout, sort_keys=True)
269 Scan local directory for releases with profiles.json.
270 Merge into overview.json files.
276 # firmware selector config
277 config_path = "{}/config
.js
".format(args.www_path)
278 # the overview.json files are placed here
279 data_path = "{}/data
".format(args.www_path)
282 # args.images_path => args.releases_path
284 for path in Path(args.images_path).rglob("profiles
.json
"):
285 with open(str(path), "r
", encoding="utf
-8") as file:
286 content = file.read()
287 obj = json.loads(content)
288 release = obj["version_number
"]
289 releases.setdefault(release, []).append(
290 {"file_path
": str(path), "file_content
": content}
293 for release, profiles in releases.items():
294 output = merge_profiles(profiles, args.download_url)
296 versions[release] = "data
/{}/overview
.json
".format(release)
297 os.makedirs("{}/{}".format(data_path, release), exist_ok=True)
299 # write overview.json
300 with open("{}/{}/overview
.json
".format(data_path, release), "w
") as outfile:
302 json.dump(output, outfile, indent=" ", sort_keys=True)
304 json.dump(output, outfile, sort_keys=True)
306 update_config(config_path, versions)
310 parser = argparse.ArgumentParser()
312 "--formatted
", action="store_true
", help="Output formatted JSON data
."
314 subparsers = parser.add_subparsers(dest="action
")
315 subparsers.required = True
317 parser_merge = subparsers.add_parser(
318 "merge
", help="Search
for profiles
.json files
and output an overview
.json
."
320 parser_merge.add_argument(
323 help="Input folder that
is traversed
for OpenWrt JSON device files
.",
325 parser_merge.add_argument(
329 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
).",
332 parser_scrape = subparsers.add_parser("scrape
", help="Scrape webpage
for releases
.")
333 parser_scrape.add_argument(
334 "domain
", help="Domain to scrape
. E
.g
. https
://downloads
.openwrt
.org
"
336 parser_scrape.add_argument("www_path
", help="Path the config
.js
file is in.")
337 parser_scrape.add_argument(
338 "--use
-wget
", action="store_true
", help="Use wget to scrape the site
."
341 parser_scan = subparsers.add_parser("scan
", help="Scan directory
for releases
.")
342 parser_scan.add_argument(
343 "download_url
", help="Download
for images
. E
.g
. https
://downloads
.openwrt
.org
"
345 parser_scan.add_argument("images_path
", help="Directory to scan
for releases
.")
346 parser_scan.add_argument("www_path
", help="Path the config
.js
file is in.")
348 args = parser.parse_args()
350 if args.action == "merge
":
353 if args.action == "scan
":
356 if args.action == "scrape
":
363 if __name__ == "__main__
":