-
Notifications
You must be signed in to change notification settings - Fork 15
/
one-click.py
executable file
·422 lines (377 loc) · 15.3 KB
/
one-click.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
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
#
# SPDX-License-Identifier: GPL-3.0-or-later
#
# Massage the latest KOReader/Plato releases into "one-click" install bundles.
#
##
import sys
# We need Python >= 3.7 (as we're passing a pathlib.Path to shutil.make_archive)
if sys.version_info < (3, 7):
raise SystemExit("This script requires Python 3.7+")
from bs4 import BeautifulSoup
from email.utils import parsedate
from github import Github
from io import DEFAULT_BUFFER_SIZE
import logging
from natsort import natsorted
import os
from pathlib import Path
import re
import requests
import shutil
import tarfile
from tempfile import gettempdir
from time import mktime
from tqdm import tqdm
import zipfile
# Set up a logger for shutil.make_archive
logging.basicConfig(level=logging.WARNING)
logger = logging.getLogger("KFMon")
# Half-assed attempt at sanitizing tar members, at least until https://github.com/python/cpython/issues/73974 goes somewhere...
# Based on https://gist.github.com/Kasimir123/9bdc38f2eac9a19f83ef6cc52c7ce82e
def is_within_directory(directory, target):
abs_directory = os.path.abspath(directory)
abs_target = os.path.abspath(target)
prefix = os.path.commonprefix([abs_directory, abs_target])
return prefix == abs_directory
def checked_tar_extractall(tar, path=".", **kwargs):
for member in tar.getmembers():
member_path = os.path.join(path, member.name)
if not is_within_directory(path, member_path):
raise RuntimeError("Path traversal in tarball")
return tar.extractall(path, **kwargs)
# Mimic shutil.unpack_archive's signature
def checked_unpack_archive(filename, extract_dir):
# We use Pathlib everywhere
if filename.suffix == ".zip":
with zipfile.ZipFile(filename) as zipf:
# zipfile doesn't raise an error, but will silently strip leading / & ..
zipf.extractall(extract_dir)
else:
with tarfile.open(filename) as tarf:
checked_tar_extractall(tarf, extract_dir)
# We'll need the current KFMon install package first
print("* Looking for the latest KFMon install package . . .")
kfm = Path("Kobo")
kfmon_package = None
# There *should* only ever be one, but assume I might do something stupid later down the road...
for kfmon in kfm.glob("KFMon-v*.zip"):
print("* Found {}".format(kfmon.name))
kfmon_package = kfmon.resolve(strict=True)
# Remember its mtime
kfmon_date = kfmon.stat().st_mtime
# And the version
kfmon_version = re.search(r"KFMon-v(.+?)\.zip", kfmon.name).group(1)
if kfmon_package is None:
raise SystemExit("Couldn't find a KFMon install package!")
# We'll be doing as much as possible through the GitHub API, possibly authenticated
gh = Github(os.getenv("GH_API_ACCESS_TOK"))
# Get the latest NickelMenu release
print("* Looking for the latest NickelMenu release . . .")
nickelmenu = gh.get_repo("pgaskin/NickelMenu")
latest_nickelmenu = nickelmenu.get_latest_release()
nickelmenu_version = latest_nickelmenu.tag_name
nickelmenu_url = None
print("Looking at NickelMenu {} ...".format(nickelmenu_version))
# NOTE: We're using customized builds w/ the auto-uninstaller built-in
nickelmenu_url = "https://nm.storage.pgaskin.net/artifacts/tag/{}/with-NM_UNINSTALL_CONFIGDIR/KoboRoot.tgz".format(nickelmenu_version)
if nickelmenu_url is None:
raise SystemExit("Couldn't find the latest NickelMenu package!")
latest_nickelmenu = None
nickelmenu = None
# Get the latest Plato release
print("* Looking for the latest Plato release . . .")
plato = gh.get_repo("baskerville/plato")
latest_plato = plato.get_latest_release()
plato_version = latest_plato.tag_name
plato_url = None
print("Looking at Plato {} ...".format(plato_version))
for asset in latest_plato.get_assets():
if asset.name == "plato-{}.zip".format(plato_version):
plato_url = asset.browser_download_url
break
if plato_url is None:
raise SystemExit("Couldn't find the latest Plato package!")
latest_plato = None
plato = None
# Get the latest KOReader release
print("* Looking for the latest KOReader release . . .")
koreader = gh.get_repo("koreader/koreader")
latest_koreader = koreader.get_latest_release()
# Try to pickup a hotfix release if there's one...
latest_ko_tag = koreader.get_tags()[0].name
koreader_version = latest_koreader.tag_name
koreader_url = None
# Loop over assets until we find the Kobo package ;)
for asset in latest_koreader.get_assets():
if asset.name == "koreader-kobo-{}.zip".format(koreader_version):
koreader_url = asset.browser_download_url
break
elif asset.name == "koreader-kobo-{}.zip".format(latest_ko_tag):
koreader_url = asset.browser_download_url
koreader_version = latest_ko_tag
break
if koreader_url is None:
raise SystemExit("Couldn't find the latest KOReader package!")
latest_koreader = None
koreader = None
# Get the latest KOReader nightly
print("* Looking for the latest KOReader nightly . . .")
koreader_nightly_version = None
# NOTE: We're opting for a crawl of the nighlies, instead of parsing the koreader-kobo-latest-nightly.zsync file...
koreader_nightly_url = "http://build.koreader.rocks/download/nightly/"
r = requests.get(koreader_nightly_url)
if r.status_code != 200:
raise SystemExit("Couldn't crawl KOReader's nightlies!")
# That's a simple directory listing, so we'll have to scrape it...
soup = BeautifulSoup(r.text, "lxml")
# We're of course concerned with the links
ko_nightlies = []
for link in soup.find_all("a"):
# We want the link, minus the final /
if link.get("href") != "../":
ko_nightlies.append(link.get("href")[:-1])
# Sort that to find the latest one, but we'll walk them all backwards until we find one that contains a Kobo build,
# in case the latest nightlies were only cooked for a subset of platforms...
for nightly in natsorted(ko_nightlies, key=lambda x: x.replace('.', '~'), reverse=True):
print("Looking at KOReader {} ...".format(nightly))
r = requests.get(koreader_nightly_url + nightly)
if r.status_code != 200:
raise SystemExit("Couldn't crawl KOReader's nightly!")
# And look for a Kobo build in there...
soup = BeautifulSoup(r.text, "lxml")
for link in soup.find_all("a"):
if "koreader-kobo" in link.get("href"):
koreader_nightly_version = nightly
break
# If we found a Kobo nightly, we're done!
if koreader_nightly_version:
break
if koreader_nightly_version is None:
raise SystemExit("Couldn't find the latest KOReader nightly!")
soup = None
# We can build the proper URL!
koreader_nightly_url = "{}{}/koreader-kobo-{}.zip".format(koreader_nightly_url, koreader_nightly_version, koreader_nightly_version)
# We'll want to tame down the version...
koreader_nightly_version = koreader_nightly_version.split("-g")[0]
# Recap what we found
print("\nNickelMenu: {}\n{}\n\nKOReader Release {}:\n{}\nKOReader Nightly {}:\n{}\n\nPlato {}:\n{}\n".format(nickelmenu_version, nickelmenu_url, koreader_version, koreader_url, koreader_nightly_version, koreader_nightly_url, plato_version, plato_url))
gh = None
# Do we want to use KOReader stable or nightly?
if len(sys.argv) > 1:
print("* Using the latest nightly instead of the latest release for KOReader!\n")
koreader_version = koreader_nightly_version
koreader_url = koreader_nightly_url
# Let's start building our one-click packages...
# We'll work in a temporary directory, one that's hosted on a tmpfs (at least on my end ;p)...
tmpdir = Path(gettempdir())
t = Path(tmpdir / "KFMon")
t.mkdir(parents=True, exist_ok=True)
# Start with NickelMenu, because we'll merge it into KFMon's KoboRoot
print("* Downloading NickelMenu")
nm = Path(t / "NickelMenu")
nm.mkdir(parents=True, exist_ok=True)
nm_main = Path(nm / "NickelMenu.tgz")
with requests.get(nickelmenu_url, stream=True) as r:
if r.status_code != 200:
raise SystemExit("Couldn't download the latest NickelMenu release!")
# We'll restore its mtime later...
nickelmenu_date = mktime(parsedate(r.headers["Last-Modified"]))
clen = int(r.headers.get("Content-Length", 0))
wrote = 0
with nm_main.open(mode="w+b") as f:
with tqdm(total=clen, unit='B', unit_scale=True, unit_divisor=1024) as pbar:
for data in r.iter_content(chunk_size=DEFAULT_BUFFER_SIZE):
written = f.write(data)
wrote += written
pbar.update(written)
if clen != 0 and wrote != clen:
raise SystemExit("Wrote {} bytes to disk instead of the {} expected!".format(wrote, clen))
# Unpack both KFMon & NM
print("* Merging NickelMenu with KFMon")
checked_unpack_archive(kfmon_package, nm)
# Merge both KoboRoot tarballs...
nm_kobo = Path(nm / "KOBOROOT")
checked_unpack_archive(nm / ".kobo/KoboRoot.tgz", nm_kobo)
checked_unpack_archive(nm_main, nm_kobo)
merged_koboroot = Path(nm / "KoboRoot")
shutil.make_archive(merged_koboroot, format="gztar", root_dir=nm_kobo, base_dir=".", owner="root", group="root", logger=logger)
# Update to the actual filename created by make_archive
merged_koboroot = merged_koboroot.with_name("KoboRoot.tar.gz")
# Where the NickelMenu config shards live
nm_cfg = Path("nm")
# Start with Plato
print("\n* Creating a one-click package for Plato . . .")
# It'll be staged in its own directory
pl = Path(t / "Plato")
# Download both packages...
print("* Downloading original package")
pl_main = Path(t / "Plato.zip")
with requests.get(plato_url, stream=True) as r:
if r.status_code != 200:
raise SystemExit("Couldn't download the latest Plato release!")
# We'll restore its mtime later...
plato_date = mktime(parsedate(r.headers["Last-Modified"]))
clen = int(r.headers.get("Content-Length", 0))
wrote = 0
with pl_main.open(mode="w+b") as f:
with tqdm(total=clen, unit='B', unit_scale=True, unit_divisor=1024) as pbar:
for data in r.iter_content(chunk_size=DEFAULT_BUFFER_SIZE):
written = f.write(data)
wrote += written
pbar.update(written)
if clen != 0 and wrote != clen:
raise SystemExit("Wrote {} bytes to disk instead of the {} expected!".format(wrote, clen))
# Stage KFMon first
print("* Staging it . . .")
checked_unpack_archive(kfmon_package, pl)
# Filter out KOReader config & icons
Path(pl / ".adds/kfmon/config/koreader.ini").unlink()
Path(pl / "koreader.png").unlink()
# Use the KFMon + NM KoboRoot
shutil.copyfile(merged_koboroot, pl / ".kobo/KoboRoot.tgz")
# Add the relevant NM configs
nm_dir = Path(pl / ".adds/nm")
nm_dir.mkdir(parents=True, exist_ok=True)
shutil.copy2(nm_cfg / "kfmon", nm_dir / "kfmon")
shutil.copy2(nm_cfg / "plato", nm_dir / "plato")
# Then stage Plato
pl_dir = Path(pl / ".adds/plato")
pl_dir.mkdir(parents=True, exist_ok=True)
checked_unpack_archive(pl_main, pl_dir)
# Finally, zip it up!
print("* Bundling it . . .")
pl_basename = "OCP-Plato-{}".format(plato_version)
pl_zip = Path(t / pl_basename)
shutil.make_archive(pl_zip, format="zip", root_dir=pl, base_dir=".", logger=logger)
# And restore Plato's original mtime...
pl_zip = pl_zip.with_name("{}.zip".format(pl_basename))
os.utime(pl_zip, times=(plato_date, plato_date))
# Cleanup behind us
shutil.rmtree(pl)
pl = None
# Do KOReader next
print("\n* Creating a one-click package for KOReader . . .")
# It'll be staged in its own directory
ko = Path(t / "KOReader")
# Download the package
print("* Downloading original package")
ko_main = Path(t / "KOReader.zip")
with requests.get(koreader_url, stream=True) as r:
if r.status_code != 200:
raise SystemExit("Couldn't download the latest KOReader release!")
# We'll restore its mtime later...
koreader_date = mktime(parsedate(r.headers["Last-Modified"]))
clen = int(r.headers.get("Content-Length", 0))
wrote = 0
with ko_main.open(mode="w+b") as f:
with tqdm(total=clen, unit='B', unit_scale=True, unit_divisor=1024) as pbar:
for data in r.iter_content(chunk_size=DEFAULT_BUFFER_SIZE):
written = f.write(data)
wrote += written
pbar.update(written)
if clen != 0 and wrote != clen:
raise SystemExit("Wrote {} bytes to disk instead of the {} expected!".format(wrote, clen))
# Stage KFMon first
print("* Staging it . . .")
checked_unpack_archive(kfmon_package, ko)
# Filter out Plato config & icons
Path(ko / ".adds/kfmon/config/plato.ini").unlink()
Path(ko / "icons/plato.png").unlink()
Path(ko / "icons").rmdir()
# Use the KFMon + NM KoboRoot
shutil.copyfile(merged_koboroot, ko / ".kobo/KoboRoot.tgz")
# Add the relevant NM configs
nm_dir = Path(ko / ".adds/nm")
nm_dir.mkdir(parents=True, exist_ok=True)
shutil.copy2(nm_cfg / "kfmon", nm_dir / "kfmon")
shutil.copy2(nm_cfg / "koreader", nm_dir / "koreader")
# Then stage KOReader
checked_unpack_archive(ko_main, ko / ".adds")
# Filter out some extraneous stuff (old fmon relics)
Path(ko / ".adds" / "koreader.png").unlink()
# Finally, zip it up!
print("* Bundling it . . .")
ko_basename = "OCP-KOReader-{}".format(koreader_version)
ko_zip = Path(t / ko_basename)
shutil.make_archive(ko_zip, format="zip", root_dir=ko, base_dir=".", logger=logger)
# And restore KOReader's original mtime...
ko_zip = ko_zip.with_name("{}.zip".format(ko_basename))
os.utime(ko_zip, times=(koreader_date, koreader_date))
# Cleanup behind us
shutil.rmtree(ko)
ko = None
# And while we're there, I guess we can do both at once ;)
print("\n* Creating a one-click package for Plato + KOReader . . .")
pk = Path(t / "Both")
# Stage KFMon first
print("* Staging it . . .")
checked_unpack_archive(kfmon_package, pk)
# Use the KFMon + NM KoboRoot
shutil.copyfile(merged_koboroot, pk / ".kobo/KoboRoot.tgz")
# Add the relevant NM configs
nm_dir = Path(pk / ".adds/nm")
nm_dir.mkdir(parents=True, exist_ok=True)
shutil.copy2(nm_cfg / "kfmon", nm_dir / "kfmon")
shutil.copy2(nm_cfg / "koreader", nm_dir / "koreader")
shutil.copy2(nm_cfg / "plato", nm_dir / "plato")
# Then Plato
pl_dir = Path(pk / ".adds/plato")
pl_dir.mkdir(parents=True, exist_ok=True)
checked_unpack_archive(pl_main, pl_dir)
# Then KOReader
checked_unpack_archive(ko_main, pk / ".adds")
# Filter out some extraneous stuff
Path(pk / ".adds" / "koreader.png").unlink()
# Finally, zip it up!
print("* Bundling it . . .")
pk_basename = "OCP-Plato-{}_KOReader-{}".format(plato_version, koreader_version)
pk_zip = Path(t / pk_basename)
shutil.make_archive(pk_zip, format="zip", root_dir=pk, base_dir=".", logger=logger)
# And restore KFMon's original mtime...
pk_zip = pk_zip.with_name("{}.zip".format(pk_basename))
os.utime(pk_zip, times=(kfmon_date, kfmon_date))
# Cleanup behind us
shutil.rmtree(pk)
pk = None
# Also filter the KFMon standalone package for post-update OCP fixups (i.e., without any configs).
print("\n* Creating a one-click package for KFMon . . .")
kf = Path(t / "OCP-KFMon")
# Stage KFMon
print("* Staging it . . .")
checked_unpack_archive(kfmon_package, kf)
# Use the KFMon + NM KoboRoot
shutil.copyfile(merged_koboroot, kf / ".kobo/KoboRoot.tgz")
# Filter out configs & icons
Path(kf / ".adds/kfmon/config/koreader.ini").unlink()
Path(kf / "koreader.png").unlink()
Path(kf / ".adds/kfmon/config/plato.ini").unlink()
Path(kf / "icons/plato.png").unlink()
Path(kf / "icons").rmdir()
# For the odd duck out there that also removes those...
Path(kf / ".adds/kfmon/config/kfmon-log.ini").unlink()
# NOTE: Can't remove that, as it's used by the install script as a sentinel file for the safety checks!
#Path(kf / "kfmon.png").unlink()
# Finally, zip it up!
print("* Bundling it . . .")
kf_basename = "OCP-KFMon-{}".format(kfmon_version)
kf_zip = Path(t / kf_basename)
shutil.make_archive(kf_zip, format="zip", root_dir=kf, base_dir=".", logger=logger)
# And restore KFMon's original mtime...
kf_zip = kf_zip.with_name("{}.zip".format(kf_basename))
os.utime(kf_zip, times=(kfmon_date, kfmon_date))
# Cleanup behind us
shutil.rmtree(kf)
kf = None
# Final cleanup
shutil.rmtree(nm)
nm = None
ko_main.unlink()
pl_main.unlink()
# Print a recap
print("\n* Here are the packages we created:\n")
for ocp in t.glob("*.zip"):
oneclick_package = ocp.resolve(strict=True)
print(oneclick_package)