mirror of
https://github.com/lrnselfreliance/wrolpi.git
synced 2026-11-25 01:16:18 -05:00
Add ESP32 firmware flasher
Browser-based ESP32/ESP8266 flasher (esptool-js + Web Serial); nothing is uploaded to WROLPi, the flash is written straight to the device over USB. Firmware sources (themed, tabbed): a saved set, the WROLPi media directory, or a local file. Local files can be dropped anywhere on the page, which jumps to the "Add from computer" dropzone. The media picker searches .bin files by path and can detect the connected chip to filter firmware to matching images. - Indexed file_group.suffix + path filter for fast .bin search (alembic migration backfills via split_path_stem_and_suffix) - modules/flasher: chip detection from ESP image headers, /search endpoint, and flasher.yaml saved configurations (/configs CRUD) - Flash progress modal with ETA, connect timeout, boot-mode hint, auto- scrolling logs Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
parent
fcb64fed13
commit
c95afc7f62
25 changed files with 2063 additions and 14 deletions
69
alembic/versions/d4e6f8a0c2b5_file_group_suffix.py
Normal file
69
alembic/versions/d4e6f8a0c2b5_file_group_suffix.py
Normal file
|
|
@ -0,0 +1,69 @@
|
|||
"""file_group_suffix
|
||||
|
||||
Add the `suffix` column to the `file_group` table. This stores the lowercased suffix of the primary file
|
||||
(e.g. ".bin") so searches can filter by file type using an index, rather than relying on full-text tokens.
|
||||
|
||||
`suffix` is populated at ingest time alongside `mimetype` (wrolpi.files.lib._upsert_files and
|
||||
FileGroup.from_paths). Existing rows are backfilled here using the same `split_path_stem_and_suffix` logic so
|
||||
special multi-part suffixes like ".info.json" are stored correctly (not a naive ".json").
|
||||
|
||||
Revision ID: d4e6f8a0c2b5
|
||||
Revises: c3d5f7a9b1e2
|
||||
Create Date: 2026-07-01
|
||||
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = 'd4e6f8a0c2b5'
|
||||
down_revision = 'c3d5f7a9b1e2'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
# Backfill in batches to bound memory on low-RAM devices (e.g. Raspberry Pi).
|
||||
BATCH_SIZE = 5000
|
||||
|
||||
|
||||
def upgrade():
|
||||
op.add_column('file_group', sa.Column('suffix', sa.String(), nullable=True))
|
||||
op.create_index('ix_file_group_suffix', 'file_group', ['suffix'])
|
||||
|
||||
# Backfill existing rows using the same suffix logic used at ingest time so the stored value matches what
|
||||
# future refreshes would produce (including WROLPi special suffixes like ".info.json").
|
||||
from wrolpi.files.lib import split_path_stem_and_suffix
|
||||
conn = op.get_bind()
|
||||
last_id = 0
|
||||
while True:
|
||||
rows = conn.execute(
|
||||
sa.text('SELECT id, primary_path FROM file_group WHERE id > :last_id ORDER BY id LIMIT :limit'),
|
||||
{'last_id': last_id, 'limit': BATCH_SIZE},
|
||||
).fetchall()
|
||||
if not rows:
|
||||
break
|
||||
|
||||
ids, suffixes = [], []
|
||||
for row_id, primary_path in rows:
|
||||
suffix = (split_path_stem_and_suffix(primary_path)[1] or '').lower() or None
|
||||
if suffix:
|
||||
ids.append(row_id)
|
||||
suffixes.append(suffix)
|
||||
|
||||
if ids:
|
||||
conn.execute(
|
||||
sa.text('''
|
||||
UPDATE file_group AS fg
|
||||
SET suffix = v.suffix
|
||||
FROM (SELECT unnest(cast(:ids AS integer[])) AS id,
|
||||
unnest(cast(:suffixes AS text[])) AS suffix) AS v
|
||||
WHERE fg.id = v.id
|
||||
'''),
|
||||
{'ids': ids, 'suffixes': suffixes},
|
||||
)
|
||||
|
||||
last_id = rows[-1][0]
|
||||
|
||||
|
||||
def downgrade():
|
||||
op.drop_index('ix_file_group_suffix', table_name='file_group')
|
||||
op.drop_column('file_group', 'suffix')
|
||||
140
app/package-lock.json
generated
140
app/package-lock.json
generated
|
|
@ -14,6 +14,7 @@
|
|||
"@testing-library/react": "^13.4.0",
|
||||
"@testing-library/user-event": "^13.5.0",
|
||||
"cypress": "^13.15.2",
|
||||
"esptool-js": "^0.6.0",
|
||||
"lodash": "^4.18.1",
|
||||
"maplibre-gl": "^5.24.0",
|
||||
"mathjs": "^15.2.0",
|
||||
|
|
@ -106,6 +107,7 @@
|
|||
"version": "7.20.12",
|
||||
"resolved": "https://registry.npmjs.org/@babel/core/-/core-7.20.12.tgz",
|
||||
"integrity": "sha512-XsMfHovsUYHFMdrIHkZphTN/2Hzzi78R08NuHfDBehym2VsPDL6Zn/JAD/JQdnRvbSsbQc4mVaU1m6JgtTEElg==",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@ampproject/remapping": "^2.1.0",
|
||||
"@babel/code-frame": "^7.18.6",
|
||||
|
|
@ -902,6 +904,7 @@
|
|||
"version": "7.18.6",
|
||||
"resolved": "https://registry.npmjs.org/@babel/plugin-syntax-flow/-/plugin-syntax-flow-7.18.6.tgz",
|
||||
"integrity": "sha512-LUbR+KNTBWCUAqRG9ex5Gnzu2IOkt8jRJbHHXFT9q+L9zm7M/QQbEqXyw1n1pohYvOyWC8CjeyjrSaIwiYjK7A==",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@babel/helper-plugin-utils": "^7.18.6"
|
||||
},
|
||||
|
|
@ -1463,6 +1466,7 @@
|
|||
"version": "7.20.13",
|
||||
"resolved": "https://registry.npmjs.org/@babel/plugin-transform-react-jsx/-/plugin-transform-react-jsx-7.20.13.tgz",
|
||||
"integrity": "sha512-MmTZx/bkUrfJhhYAYt3Urjm+h8DQGrPrnKQ94jLo7NLuOU+T89a7IByhKmrb8SKhrIYIQ0FN0CHMbnFRen4qNw==",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@babel/helper-annotate-as-pure": "^7.18.6",
|
||||
"@babel/helper-module-imports": "^7.18.6",
|
||||
|
|
@ -3377,6 +3381,7 @@
|
|||
"version": "2.11.6",
|
||||
"resolved": "https://registry.npmjs.org/@popperjs/core/-/core-2.11.6.tgz",
|
||||
"integrity": "sha512-50/17A98tWUfQ176raKiOGXuYpLyyVMkxxG6oylzL3BPOlA6ADGdK7EYunSa4I064xerltq9TGXs8HmOk5E+vw==",
|
||||
"peer": true,
|
||||
"funding": {
|
||||
"type": "opencollective",
|
||||
"url": "https://opencollective.com/popperjs"
|
||||
|
|
@ -4164,6 +4169,7 @@
|
|||
"resolved": "https://registry.npmjs.org/@types/react/-/react-18.3.27.tgz",
|
||||
"integrity": "sha512-cisd7gxkzjBKU2GgdYrTdtQx1SORymWyaAFhaxQPK9bYO9ot3Y5OikQRvY0VYQtvwjeQnizCINJAenh/V7MK2w==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@types/prop-types": "*",
|
||||
"csstype": "^3.2.2"
|
||||
|
|
@ -4174,6 +4180,7 @@
|
|||
"resolved": "https://registry.npmjs.org/@types/react-dom/-/react-dom-18.3.7.tgz",
|
||||
"integrity": "sha512-MEe3UeoENYVFXzoXEWsvcpg6ZvlrFNlOQ7EOsvhI3CfAXwzPfO8Qwuxd40nepsYKqyyVQnTdEfv68q91yLcKrQ==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"peerDependencies": {
|
||||
"@types/react": "^18.0.0"
|
||||
}
|
||||
|
|
@ -4297,6 +4304,7 @@
|
|||
"version": "5.50.0",
|
||||
"resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-5.50.0.tgz",
|
||||
"integrity": "sha512-vwksQWSFZiUhgq3Kv7o1Jcj0DUNylwnIlGvKvLLYsq8pAWha6/WCnXUeaSoNNha/K7QSf2+jvmkxggC1u3pIwQ==",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@typescript-eslint/scope-manager": "5.50.0",
|
||||
"@typescript-eslint/type-utils": "5.50.0",
|
||||
|
|
@ -4348,6 +4356,7 @@
|
|||
"version": "5.50.0",
|
||||
"resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-5.50.0.tgz",
|
||||
"integrity": "sha512-KCcSyNaogUDftK2G9RXfQyOCt51uB5yqC6pkUYqhYh8Kgt+DwR5M0EwEAxGPy/+DH6hnmKeGsNhiZRQxjH71uQ==",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@typescript-eslint/scope-manager": "5.50.0",
|
||||
"@typescript-eslint/types": "5.50.0",
|
||||
|
|
@ -4678,6 +4687,7 @@
|
|||
"version": "8.15.0",
|
||||
"resolved": "https://registry.npmjs.org/acorn/-/acorn-8.15.0.tgz",
|
||||
"integrity": "sha512-NZyJarBfL7nWwIq+FDL6Zp/yHEhePMNnnJ0y3qfieCrmNvYct8uvtiV41UvlSe6apAfk0fY1FbWx+NwfmpvtTg==",
|
||||
"peer": true,
|
||||
"bin": {
|
||||
"acorn": "bin/acorn"
|
||||
},
|
||||
|
|
@ -4800,6 +4810,7 @@
|
|||
"version": "6.14.0",
|
||||
"resolved": "https://registry.npmjs.org/ajv/-/ajv-6.14.0.tgz",
|
||||
"integrity": "sha512-IWrosm/yrn43eiKqkfkHis7QioDleaXQHdDVPKg0FSwwd/DuvyX79TZnFOnYpB7dcsFAMmtFztZuXPDvSePkFw==",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"fast-deep-equal": "^3.1.1",
|
||||
"fast-json-stable-stringify": "^2.0.0",
|
||||
|
|
@ -5106,6 +5117,12 @@
|
|||
"node": ">= 4.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/atob-lite": {
|
||||
"version": "2.0.0",
|
||||
"resolved": "https://registry.npmjs.org/atob-lite/-/atob-lite-2.0.0.tgz",
|
||||
"integrity": "sha512-LEeSAWeh2Gfa2FtlQE1shxQ8zi5F9GHarrGKz08TMdODD5T4eH6BMsvtnhbWZ+XQn+Gb6om/917ucvRu7l7ukw==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/attr-accept": {
|
||||
"version": "2.2.2",
|
||||
"resolved": "https://registry.npmjs.org/attr-accept/-/attr-accept-2.2.2.tgz",
|
||||
|
|
@ -5657,6 +5674,7 @@
|
|||
"url": "https://github.com/sponsors/ai"
|
||||
}
|
||||
],
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"baseline-browser-mapping": "^2.9.0",
|
||||
"caniuse-lite": "^1.0.30001759",
|
||||
|
|
@ -6454,6 +6472,7 @@
|
|||
"version": "8.18.0",
|
||||
"resolved": "https://registry.npmjs.org/ajv/-/ajv-8.18.0.tgz",
|
||||
"integrity": "sha512-PlXPeEWMXMZ7sPYOHqmDyCJzcfNrUr3fGNKtezX14ykXOEIvyK81d+qydx89KY5O71FKMPaQ2vBfBFI5NHR63A==",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"fast-deep-equal": "^3.1.3",
|
||||
"fast-uri": "^3.0.1",
|
||||
|
|
@ -6740,6 +6759,7 @@
|
|||
"resolved": "https://registry.npmjs.org/cypress/-/cypress-13.15.2.tgz",
|
||||
"integrity": "sha512-ARbnUorjcCM3XiPwgHKuqsyr5W9Qn+pIIBPaoilnoBkLdSC2oLQjV1BUpnmc7KR+b7Avah3Ly2RMFnfxr96E/A==",
|
||||
"hasInstallScript": true,
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@cypress/request": "^3.0.6",
|
||||
"@cypress/xvfb": "^1.2.4",
|
||||
|
|
@ -7506,6 +7526,7 @@
|
|||
"version": "2.4.1",
|
||||
"resolved": "https://registry.npmjs.org/enquirer/-/enquirer-2.4.1.tgz",
|
||||
"integrity": "sha512-rRqJg/6gd538VHvR3PSrdRBb/1Vy2YfzHqzvbhGIQpDRKIa4FgV/54b5Q1xYSxOOwKvjXweS26E0Q+nAMwp2pQ==",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"ansi-colors": "^4.1.1",
|
||||
"strip-ansi": "^6.0.1"
|
||||
|
|
@ -7785,6 +7806,7 @@
|
|||
"version": "8.33.0",
|
||||
"resolved": "https://registry.npmjs.org/eslint/-/eslint-8.33.0.tgz",
|
||||
"integrity": "sha512-WjOpFQgKK8VrCnAtl8We0SUOy/oVZ5NHykyMiagV1M9r8IFpIJX7DduK6n1mpfhlG7T1NLWm2SuD8QB7KFySaA==",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@eslint/eslintrc": "^1.4.1",
|
||||
"@humanwhocodes/config-array": "^0.11.8",
|
||||
|
|
@ -8198,6 +8220,7 @@
|
|||
"version": "8.18.0",
|
||||
"resolved": "https://registry.npmjs.org/ajv/-/ajv-8.18.0.tgz",
|
||||
"integrity": "sha512-PlXPeEWMXMZ7sPYOHqmDyCJzcfNrUr3fGNKtezX14ykXOEIvyK81d+qydx89KY5O71FKMPaQ2vBfBFI5NHR63A==",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"fast-deep-equal": "^3.1.3",
|
||||
"fast-uri": "^3.0.1",
|
||||
|
|
@ -8422,6 +8445,17 @@
|
|||
"node": ">=4"
|
||||
}
|
||||
},
|
||||
"node_modules/esptool-js": {
|
||||
"version": "0.6.0",
|
||||
"resolved": "https://registry.npmjs.org/esptool-js/-/esptool-js-0.6.0.tgz",
|
||||
"integrity": "sha512-ZyuSBXvmS+4DRKM6GrDHfCscnq3YSNlRfM+Zw0DoS7uC3SdkyC262s/ji4MjDYVmMH8SE2BiYx3/dZ1J23Xiew==",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"atob-lite": "^2.0.0",
|
||||
"pako": "^2.1.0",
|
||||
"tslib": "^2.4.1"
|
||||
}
|
||||
},
|
||||
"node_modules/esquery": {
|
||||
"version": "1.4.0",
|
||||
"resolved": "https://registry.npmjs.org/esquery/-/esquery-1.4.0.tgz",
|
||||
|
|
@ -10689,6 +10723,7 @@
|
|||
"version": "27.5.1",
|
||||
"resolved": "https://registry.npmjs.org/jest/-/jest-27.5.1.tgz",
|
||||
"integrity": "sha512-Yn0mADZB89zTtjkPJEXwrac3LHudkQMR+Paqa8uxJHCBr9agxztUifWCyiYrjhMPBoUVBjyny0I7XH6ozDr7QQ==",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@jest/core": "^27.5.1",
|
||||
"import-local": "^3.0.2",
|
||||
|
|
@ -13383,6 +13418,7 @@
|
|||
"version": "8.18.0",
|
||||
"resolved": "https://registry.npmjs.org/ajv/-/ajv-8.18.0.tgz",
|
||||
"integrity": "sha512-PlXPeEWMXMZ7sPYOHqmDyCJzcfNrUr3fGNKtezX14ykXOEIvyK81d+qydx89KY5O71FKMPaQ2vBfBFI5NHR63A==",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"fast-deep-equal": "^3.1.3",
|
||||
"fast-uri": "^3.0.1",
|
||||
|
|
@ -13913,6 +13949,22 @@
|
|||
"node": ">=6"
|
||||
}
|
||||
},
|
||||
"node_modules/pako": {
|
||||
"version": "2.2.0",
|
||||
"resolved": "https://registry.npmjs.org/pako/-/pako-2.2.0.tgz",
|
||||
"integrity": "sha512-zJq6RP/5q+TO2OpFV3FHzlPnFjmkb7Nc99a5SNjJE+uu/PkpChs+NIZSSzbBoD+6kjiISXjfYdwj1ZRQ81dz/w==",
|
||||
"funding": [
|
||||
{
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/puzrin"
|
||||
},
|
||||
{
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/nodeca"
|
||||
}
|
||||
],
|
||||
"license": "(MIT AND Zlib)"
|
||||
},
|
||||
"node_modules/param-case": {
|
||||
"version": "3.0.4",
|
||||
"resolved": "https://registry.npmjs.org/param-case/-/param-case-3.0.4.tgz",
|
||||
|
|
@ -14223,6 +14275,7 @@
|
|||
"url": "https://tidelift.com/funding/github/npm/postcss"
|
||||
}
|
||||
],
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"nanoid": "^3.3.4",
|
||||
"picocolors": "^1.0.0",
|
||||
|
|
@ -15281,6 +15334,7 @@
|
|||
"version": "6.0.11",
|
||||
"resolved": "https://registry.npmjs.org/postcss-selector-parser/-/postcss-selector-parser-6.0.11.tgz",
|
||||
"integrity": "sha512-zbARubNdogI9j7WY4nQJBiNqQf3sLS3wCP4WfOidu+p28LofJqDH1tcXypGrcmMHhDk2t9wGhCsYe/+szLTy1g==",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"cssesc": "^3.0.0",
|
||||
"util-deprecate": "^1.0.2"
|
||||
|
|
@ -15470,6 +15524,7 @@
|
|||
"version": "15.8.1",
|
||||
"resolved": "https://registry.npmjs.org/prop-types/-/prop-types-15.8.1.tgz",
|
||||
"integrity": "sha512-oj87CgZICdulUohogVAR7AjlC0327U4el4L6eAvOqCeudMDVU0NThNaV+b9Df4dXgSP1gXMTnPdhfe/2qDH5cg==",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"loose-envify": "^1.4.0",
|
||||
"object-assign": "^4.1.1",
|
||||
|
|
@ -15677,6 +15732,7 @@
|
|||
"version": "18.2.0",
|
||||
"resolved": "https://registry.npmjs.org/react/-/react-18.2.0.tgz",
|
||||
"integrity": "sha512-/3IjMdb2L9QbBdWiW5e3P2/npwMBaU9mHCSCUzNln0ZCYbcfTsGbTJrU/kGemdH2IWmB2ioZ+zkxtmq6g09fGQ==",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"loose-envify": "^1.1.0"
|
||||
},
|
||||
|
|
@ -15830,6 +15886,7 @@
|
|||
"version": "18.2.0",
|
||||
"resolved": "https://registry.npmjs.org/react-dom/-/react-dom-18.2.0.tgz",
|
||||
"integrity": "sha512-6IMTriUmvsjHUjNtEDudZfuDQUoWXVxKHhlEGSk81n4YFS+r/Kl99wXiwlVXtPBtJenozv2P+hxDsw9eA7Xo6g==",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"loose-envify": "^1.1.0",
|
||||
"scheduler": "^0.23.0"
|
||||
|
|
@ -15931,6 +15988,7 @@
|
|||
"version": "0.11.0",
|
||||
"resolved": "https://registry.npmjs.org/react-refresh/-/react-refresh-0.11.0.tgz",
|
||||
"integrity": "sha512-F27qZr8uUqwhWZboondsPx8tnC3Ct3SxZA3V5WyEvujRyyNv0VYPhoBg1gZ8/MV5tubQp76Trw8lTv9hzRBa+A==",
|
||||
"peer": true,
|
||||
"engines": {
|
||||
"node": ">=0.10.0"
|
||||
}
|
||||
|
|
@ -16445,6 +16503,7 @@
|
|||
"version": "2.80.0",
|
||||
"resolved": "https://registry.npmjs.org/rollup/-/rollup-2.80.0.tgz",
|
||||
"integrity": "sha512-cIFJOD1DESzpjOBl763Kp1AH7UE/0fcdHe6rZXUdQ9c50uvgigvW97u3IcSeBwOkgqL/PXPBktBCh0KEu5L8XQ==",
|
||||
"peer": true,
|
||||
"bin": {
|
||||
"rollup": "dist/bin/rollup"
|
||||
},
|
||||
|
|
@ -16720,6 +16779,7 @@
|
|||
"version": "2.1.5",
|
||||
"resolved": "https://registry.npmjs.org/semantic-ui-react/-/semantic-ui-react-2.1.5.tgz",
|
||||
"integrity": "sha512-nIqmmUNpFHfovEb+RI2w3E2/maZQutd8UIWyRjf1SLse+XF51hI559xbz/sLN3O6RpLjr/echLOOXwKCirPy3Q==",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@babel/runtime": "^7.10.5",
|
||||
"@fluentui/react-component-event-listener": "~0.63.0",
|
||||
|
|
@ -17807,6 +17867,7 @@
|
|||
"version": "8.18.0",
|
||||
"resolved": "https://registry.npmjs.org/ajv/-/ajv-8.18.0.tgz",
|
||||
"integrity": "sha512-PlXPeEWMXMZ7sPYOHqmDyCJzcfNrUr3fGNKtezX14ykXOEIvyK81d+qydx89KY5O71FKMPaQ2vBfBFI5NHR63A==",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"fast-deep-equal": "^3.1.3",
|
||||
"fast-uri": "^3.0.1",
|
||||
|
|
@ -17878,7 +17939,8 @@
|
|||
"node_modules/three": {
|
||||
"version": "0.184.0",
|
||||
"resolved": "https://registry.npmjs.org/three/-/three-0.184.0.tgz",
|
||||
"integrity": "sha512-wtTRjG92pM5eUg/KuUnHsqSAlPM296brTOcLgMRqEeylYTh/CdtvKUvCyyCQTzFuStieWxvZb8mVTMvdPyUpxg=="
|
||||
"integrity": "sha512-wtTRjG92pM5eUg/KuUnHsqSAlPM296brTOcLgMRqEeylYTh/CdtvKUvCyyCQTzFuStieWxvZb8mVTMvdPyUpxg==",
|
||||
"peer": true
|
||||
},
|
||||
"node_modules/three-stdlib": {
|
||||
"version": "2.17.2",
|
||||
|
|
@ -18126,6 +18188,7 @@
|
|||
"version": "0.21.3",
|
||||
"resolved": "https://registry.npmjs.org/type-fest/-/type-fest-0.21.3.tgz",
|
||||
"integrity": "sha512-t0rzBq87m3fVcduHDUFhKmyyX+9eo6WQjZvf51Ea/M0Q7+T374Jp1aUiyUl0GKxp8M/OETVHSDvmkyPgvX+X2w==",
|
||||
"peer": true,
|
||||
"engines": {
|
||||
"node": ">=10"
|
||||
},
|
||||
|
|
@ -18179,6 +18242,7 @@
|
|||
"resolved": "https://registry.npmjs.org/typescript/-/typescript-4.9.5.tgz",
|
||||
"integrity": "sha512-1FXk9E2Hm+QzZQ7z+McJiHL4NW1F2EzMu9Nq9i3zAaGqibafqYwCVU6WyWAuyQRRzOlxou8xZSyXLEN8oKj24g==",
|
||||
"license": "Apache-2.0",
|
||||
"peer": true,
|
||||
"bin": {
|
||||
"tsc": "bin/tsc",
|
||||
"tsserver": "bin/tsserver"
|
||||
|
|
@ -18489,6 +18553,7 @@
|
|||
"version": "5.105.0",
|
||||
"resolved": "https://registry.npmjs.org/webpack/-/webpack-5.105.0.tgz",
|
||||
"integrity": "sha512-gX/dMkRQc7QOMzgTe6KsYFM7DxeIONQSui1s0n/0xht36HvrgbxtM1xBlgx596NbpHuQU8P7QpKwrZYwUX48nw==",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@types/eslint-scope": "^3.7.7",
|
||||
"@types/estree": "^1.0.8",
|
||||
|
|
@ -18558,6 +18623,7 @@
|
|||
"version": "8.18.0",
|
||||
"resolved": "https://registry.npmjs.org/ajv/-/ajv-8.18.0.tgz",
|
||||
"integrity": "sha512-PlXPeEWMXMZ7sPYOHqmDyCJzcfNrUr3fGNKtezX14ykXOEIvyK81d+qydx89KY5O71FKMPaQ2vBfBFI5NHR63A==",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"fast-deep-equal": "^3.1.3",
|
||||
"fast-uri": "^3.0.1",
|
||||
|
|
@ -18607,6 +18673,7 @@
|
|||
"version": "4.11.1",
|
||||
"resolved": "https://registry.npmjs.org/webpack-dev-server/-/webpack-dev-server-4.11.1.tgz",
|
||||
"integrity": "sha512-lILVz9tAUy1zGFwieuaQtYiadImb5M3d+H+L1zDYalYoDl0cksAB1UNyuE5MMWJrG6zR1tXkCP2fitl7yoUJiw==",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@types/bonjour": "^3.5.9",
|
||||
"@types/connect-history-api-fallback": "^1.3.5",
|
||||
|
|
@ -18661,6 +18728,7 @@
|
|||
"version": "8.18.0",
|
||||
"resolved": "https://registry.npmjs.org/ajv/-/ajv-8.18.0.tgz",
|
||||
"integrity": "sha512-PlXPeEWMXMZ7sPYOHqmDyCJzcfNrUr3fGNKtezX14ykXOEIvyK81d+qydx89KY5O71FKMPaQ2vBfBFI5NHR63A==",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"fast-deep-equal": "^3.1.3",
|
||||
"fast-uri": "^3.0.1",
|
||||
|
|
@ -18773,6 +18841,7 @@
|
|||
"version": "8.18.0",
|
||||
"resolved": "https://registry.npmjs.org/ajv/-/ajv-8.18.0.tgz",
|
||||
"integrity": "sha512-PlXPeEWMXMZ7sPYOHqmDyCJzcfNrUr3fGNKtezX14ykXOEIvyK81d+qydx89KY5O71FKMPaQ2vBfBFI5NHR63A==",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"fast-deep-equal": "^3.1.3",
|
||||
"fast-uri": "^3.0.1",
|
||||
|
|
@ -19055,6 +19124,7 @@
|
|||
"version": "8.18.0",
|
||||
"resolved": "https://registry.npmjs.org/ajv/-/ajv-8.18.0.tgz",
|
||||
"integrity": "sha512-PlXPeEWMXMZ7sPYOHqmDyCJzcfNrUr3fGNKtezX14ykXOEIvyK81d+qydx89KY5O71FKMPaQ2vBfBFI5NHR63A==",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"fast-deep-equal": "^3.1.3",
|
||||
"fast-uri": "^3.0.1",
|
||||
|
|
@ -19499,6 +19569,7 @@
|
|||
"version": "7.20.12",
|
||||
"resolved": "https://registry.npmjs.org/@babel/core/-/core-7.20.12.tgz",
|
||||
"integrity": "sha512-XsMfHovsUYHFMdrIHkZphTN/2Hzzi78R08NuHfDBehym2VsPDL6Zn/JAD/JQdnRvbSsbQc4mVaU1m6JgtTEElg==",
|
||||
"peer": true,
|
||||
"requires": {
|
||||
"@ampproject/remapping": "^2.1.0",
|
||||
"@babel/code-frame": "^7.18.6",
|
||||
|
|
@ -20041,6 +20112,7 @@
|
|||
"version": "7.18.6",
|
||||
"resolved": "https://registry.npmjs.org/@babel/plugin-syntax-flow/-/plugin-syntax-flow-7.18.6.tgz",
|
||||
"integrity": "sha512-LUbR+KNTBWCUAqRG9ex5Gnzu2IOkt8jRJbHHXFT9q+L9zm7M/QQbEqXyw1n1pohYvOyWC8CjeyjrSaIwiYjK7A==",
|
||||
"peer": true,
|
||||
"requires": {
|
||||
"@babel/helper-plugin-utils": "^7.18.6"
|
||||
}
|
||||
|
|
@ -20386,6 +20458,7 @@
|
|||
"version": "7.20.13",
|
||||
"resolved": "https://registry.npmjs.org/@babel/plugin-transform-react-jsx/-/plugin-transform-react-jsx-7.20.13.tgz",
|
||||
"integrity": "sha512-MmTZx/bkUrfJhhYAYt3Urjm+h8DQGrPrnKQ94jLo7NLuOU+T89a7IByhKmrb8SKhrIYIQ0FN0CHMbnFRen4qNw==",
|
||||
"peer": true,
|
||||
"requires": {
|
||||
"@babel/helper-annotate-as-pure": "^7.18.6",
|
||||
"@babel/helper-module-imports": "^7.18.6",
|
||||
|
|
@ -21733,7 +21806,8 @@
|
|||
"@popperjs/core": {
|
||||
"version": "2.11.6",
|
||||
"resolved": "https://registry.npmjs.org/@popperjs/core/-/core-2.11.6.tgz",
|
||||
"integrity": "sha512-50/17A98tWUfQ176raKiOGXuYpLyyVMkxxG6oylzL3BPOlA6ADGdK7EYunSa4I064xerltq9TGXs8HmOk5E+vw=="
|
||||
"integrity": "sha512-50/17A98tWUfQ176raKiOGXuYpLyyVMkxxG6oylzL3BPOlA6ADGdK7EYunSa4I064xerltq9TGXs8HmOk5E+vw==",
|
||||
"peer": true
|
||||
},
|
||||
"@react-three/fiber": {
|
||||
"version": "8.16.5",
|
||||
|
|
@ -22311,6 +22385,7 @@
|
|||
"version": "18.3.27",
|
||||
"resolved": "https://registry.npmjs.org/@types/react/-/react-18.3.27.tgz",
|
||||
"integrity": "sha512-cisd7gxkzjBKU2GgdYrTdtQx1SORymWyaAFhaxQPK9bYO9ot3Y5OikQRvY0VYQtvwjeQnizCINJAenh/V7MK2w==",
|
||||
"peer": true,
|
||||
"requires": {
|
||||
"@types/prop-types": "*",
|
||||
"csstype": "^3.2.2"
|
||||
|
|
@ -22320,6 +22395,7 @@
|
|||
"version": "18.3.7",
|
||||
"resolved": "https://registry.npmjs.org/@types/react-dom/-/react-dom-18.3.7.tgz",
|
||||
"integrity": "sha512-MEe3UeoENYVFXzoXEWsvcpg6ZvlrFNlOQ7EOsvhI3CfAXwzPfO8Qwuxd40nepsYKqyyVQnTdEfv68q91yLcKrQ==",
|
||||
"peer": true,
|
||||
"requires": {}
|
||||
},
|
||||
"@types/react-reconciler": {
|
||||
|
|
@ -22440,6 +22516,7 @@
|
|||
"version": "5.50.0",
|
||||
"resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-5.50.0.tgz",
|
||||
"integrity": "sha512-vwksQWSFZiUhgq3Kv7o1Jcj0DUNylwnIlGvKvLLYsq8pAWha6/WCnXUeaSoNNha/K7QSf2+jvmkxggC1u3pIwQ==",
|
||||
"peer": true,
|
||||
"requires": {
|
||||
"@typescript-eslint/scope-manager": "5.50.0",
|
||||
"@typescript-eslint/type-utils": "5.50.0",
|
||||
|
|
@ -22465,6 +22542,7 @@
|
|||
"version": "5.50.0",
|
||||
"resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-5.50.0.tgz",
|
||||
"integrity": "sha512-KCcSyNaogUDftK2G9RXfQyOCt51uB5yqC6pkUYqhYh8Kgt+DwR5M0EwEAxGPy/+DH6hnmKeGsNhiZRQxjH71uQ==",
|
||||
"peer": true,
|
||||
"requires": {
|
||||
"@typescript-eslint/scope-manager": "5.50.0",
|
||||
"@typescript-eslint/types": "5.50.0",
|
||||
|
|
@ -22714,7 +22792,8 @@
|
|||
"acorn": {
|
||||
"version": "8.15.0",
|
||||
"resolved": "https://registry.npmjs.org/acorn/-/acorn-8.15.0.tgz",
|
||||
"integrity": "sha512-NZyJarBfL7nWwIq+FDL6Zp/yHEhePMNnnJ0y3qfieCrmNvYct8uvtiV41UvlSe6apAfk0fY1FbWx+NwfmpvtTg=="
|
||||
"integrity": "sha512-NZyJarBfL7nWwIq+FDL6Zp/yHEhePMNnnJ0y3qfieCrmNvYct8uvtiV41UvlSe6apAfk0fY1FbWx+NwfmpvtTg==",
|
||||
"peer": true
|
||||
},
|
||||
"acorn-globals": {
|
||||
"version": "6.0.0",
|
||||
|
|
@ -22801,6 +22880,7 @@
|
|||
"version": "6.14.0",
|
||||
"resolved": "https://registry.npmjs.org/ajv/-/ajv-6.14.0.tgz",
|
||||
"integrity": "sha512-IWrosm/yrn43eiKqkfkHis7QioDleaXQHdDVPKg0FSwwd/DuvyX79TZnFOnYpB7dcsFAMmtFztZuXPDvSePkFw==",
|
||||
"peer": true,
|
||||
"requires": {
|
||||
"fast-deep-equal": "^3.1.1",
|
||||
"fast-json-stable-stringify": "^2.0.0",
|
||||
|
|
@ -23017,6 +23097,11 @@
|
|||
"resolved": "https://registry.npmjs.org/at-least-node/-/at-least-node-1.0.0.tgz",
|
||||
"integrity": "sha512-+q/t7Ekv1EDY2l6Gda6LLiX14rU9TV20Wa3ofeQmwPFZbOMo9DXrLbOjFaaclkXKWidIaopwAObQDqwWtGUjqg=="
|
||||
},
|
||||
"atob-lite": {
|
||||
"version": "2.0.0",
|
||||
"resolved": "https://registry.npmjs.org/atob-lite/-/atob-lite-2.0.0.tgz",
|
||||
"integrity": "sha512-LEeSAWeh2Gfa2FtlQE1shxQ8zi5F9GHarrGKz08TMdODD5T4eH6BMsvtnhbWZ+XQn+Gb6om/917ucvRu7l7ukw=="
|
||||
},
|
||||
"attr-accept": {
|
||||
"version": "2.2.2",
|
||||
"resolved": "https://registry.npmjs.org/attr-accept/-/attr-accept-2.2.2.tgz",
|
||||
|
|
@ -23418,6 +23503,7 @@
|
|||
"version": "4.28.1",
|
||||
"resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.28.1.tgz",
|
||||
"integrity": "sha512-ZC5Bd0LgJXgwGqUknZY/vkUQ04r8NXnJZ3yYi4vDmSiZmC/pdSN0NbNRPxZpbtO4uAfDUAFffO8IZoM3Gj8IkA==",
|
||||
"peer": true,
|
||||
"requires": {
|
||||
"baseline-browser-mapping": "^2.9.0",
|
||||
"caniuse-lite": "^1.0.30001759",
|
||||
|
|
@ -23959,6 +24045,7 @@
|
|||
"version": "8.18.0",
|
||||
"resolved": "https://registry.npmjs.org/ajv/-/ajv-8.18.0.tgz",
|
||||
"integrity": "sha512-PlXPeEWMXMZ7sPYOHqmDyCJzcfNrUr3fGNKtezX14ykXOEIvyK81d+qydx89KY5O71FKMPaQ2vBfBFI5NHR63A==",
|
||||
"peer": true,
|
||||
"requires": {
|
||||
"fast-deep-equal": "^3.1.3",
|
||||
"fast-uri": "^3.0.1",
|
||||
|
|
@ -24167,6 +24254,7 @@
|
|||
"version": "13.15.2",
|
||||
"resolved": "https://registry.npmjs.org/cypress/-/cypress-13.15.2.tgz",
|
||||
"integrity": "sha512-ARbnUorjcCM3XiPwgHKuqsyr5W9Qn+pIIBPaoilnoBkLdSC2oLQjV1BUpnmc7KR+b7Avah3Ly2RMFnfxr96E/A==",
|
||||
"peer": true,
|
||||
"requires": {
|
||||
"@cypress/request": "^3.0.6",
|
||||
"@cypress/xvfb": "^1.2.4",
|
||||
|
|
@ -24730,6 +24818,7 @@
|
|||
"version": "2.4.1",
|
||||
"resolved": "https://registry.npmjs.org/enquirer/-/enquirer-2.4.1.tgz",
|
||||
"integrity": "sha512-rRqJg/6gd538VHvR3PSrdRBb/1Vy2YfzHqzvbhGIQpDRKIa4FgV/54b5Q1xYSxOOwKvjXweS26E0Q+nAMwp2pQ==",
|
||||
"peer": true,
|
||||
"requires": {
|
||||
"ansi-colors": "^4.1.1",
|
||||
"strip-ansi": "^6.0.1"
|
||||
|
|
@ -24948,6 +25037,7 @@
|
|||
"version": "8.33.0",
|
||||
"resolved": "https://registry.npmjs.org/eslint/-/eslint-8.33.0.tgz",
|
||||
"integrity": "sha512-WjOpFQgKK8VrCnAtl8We0SUOy/oVZ5NHykyMiagV1M9r8IFpIJX7DduK6n1mpfhlG7T1NLWm2SuD8QB7KFySaA==",
|
||||
"peer": true,
|
||||
"requires": {
|
||||
"@eslint/eslintrc": "^1.4.1",
|
||||
"@humanwhocodes/config-array": "^0.11.8",
|
||||
|
|
@ -25323,6 +25413,7 @@
|
|||
"version": "8.18.0",
|
||||
"resolved": "https://registry.npmjs.org/ajv/-/ajv-8.18.0.tgz",
|
||||
"integrity": "sha512-PlXPeEWMXMZ7sPYOHqmDyCJzcfNrUr3fGNKtezX14ykXOEIvyK81d+qydx89KY5O71FKMPaQ2vBfBFI5NHR63A==",
|
||||
"peer": true,
|
||||
"requires": {
|
||||
"fast-deep-equal": "^3.1.3",
|
||||
"fast-uri": "^3.0.1",
|
||||
|
|
@ -25394,6 +25485,16 @@
|
|||
"resolved": "https://registry.npmjs.org/esprima/-/esprima-4.0.1.tgz",
|
||||
"integrity": "sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A=="
|
||||
},
|
||||
"esptool-js": {
|
||||
"version": "0.6.0",
|
||||
"resolved": "https://registry.npmjs.org/esptool-js/-/esptool-js-0.6.0.tgz",
|
||||
"integrity": "sha512-ZyuSBXvmS+4DRKM6GrDHfCscnq3YSNlRfM+Zw0DoS7uC3SdkyC262s/ji4MjDYVmMH8SE2BiYx3/dZ1J23Xiew==",
|
||||
"requires": {
|
||||
"atob-lite": "^2.0.0",
|
||||
"pako": "^2.1.0",
|
||||
"tslib": "^2.4.1"
|
||||
}
|
||||
},
|
||||
"esquery": {
|
||||
"version": "1.4.0",
|
||||
"resolved": "https://registry.npmjs.org/esquery/-/esquery-1.4.0.tgz",
|
||||
|
|
@ -26993,6 +27094,7 @@
|
|||
"version": "27.5.1",
|
||||
"resolved": "https://registry.npmjs.org/jest/-/jest-27.5.1.tgz",
|
||||
"integrity": "sha512-Yn0mADZB89zTtjkPJEXwrac3LHudkQMR+Paqa8uxJHCBr9agxztUifWCyiYrjhMPBoUVBjyny0I7XH6ozDr7QQ==",
|
||||
"peer": true,
|
||||
"requires": {
|
||||
"@jest/core": "^27.5.1",
|
||||
"import-local": "^3.0.2",
|
||||
|
|
@ -28964,6 +29066,7 @@
|
|||
"version": "8.18.0",
|
||||
"resolved": "https://registry.npmjs.org/ajv/-/ajv-8.18.0.tgz",
|
||||
"integrity": "sha512-PlXPeEWMXMZ7sPYOHqmDyCJzcfNrUr3fGNKtezX14ykXOEIvyK81d+qydx89KY5O71FKMPaQ2vBfBFI5NHR63A==",
|
||||
"peer": true,
|
||||
"requires": {
|
||||
"fast-deep-equal": "^3.1.3",
|
||||
"fast-uri": "^3.0.1",
|
||||
|
|
@ -29331,6 +29434,11 @@
|
|||
"resolved": "https://registry.npmjs.org/p-try/-/p-try-2.2.0.tgz",
|
||||
"integrity": "sha512-R4nPAVTAU0B9D35/Gk3uJf/7XYbQcyohSKdvAxIRSNghFl4e71hVoGnBNQz9cWaXxO2I10KTC+3jMdvvoKw6dQ=="
|
||||
},
|
||||
"pako": {
|
||||
"version": "2.2.0",
|
||||
"resolved": "https://registry.npmjs.org/pako/-/pako-2.2.0.tgz",
|
||||
"integrity": "sha512-zJq6RP/5q+TO2OpFV3FHzlPnFjmkb7Nc99a5SNjJE+uu/PkpChs+NIZSSzbBoD+6kjiISXjfYdwj1ZRQ81dz/w=="
|
||||
},
|
||||
"param-case": {
|
||||
"version": "3.0.4",
|
||||
"resolved": "https://registry.npmjs.org/param-case/-/param-case-3.0.4.tgz",
|
||||
|
|
@ -29556,6 +29664,7 @@
|
|||
"version": "8.4.21",
|
||||
"resolved": "https://registry.npmjs.org/postcss/-/postcss-8.4.21.tgz",
|
||||
"integrity": "sha512-tP7u/Sn/dVxK2NnruI4H9BG+x+Wxz6oeZ1cJ8P6G/PZY0IKk4k/63TDsQf2kQq3+qoJeLm2kIBUNlZe3zgb4Zg==",
|
||||
"peer": true,
|
||||
"requires": {
|
||||
"nanoid": "^3.3.4",
|
||||
"picocolors": "^1.0.0",
|
||||
|
|
@ -30139,6 +30248,7 @@
|
|||
"version": "6.0.11",
|
||||
"resolved": "https://registry.npmjs.org/postcss-selector-parser/-/postcss-selector-parser-6.0.11.tgz",
|
||||
"integrity": "sha512-zbARubNdogI9j7WY4nQJBiNqQf3sLS3wCP4WfOidu+p28LofJqDH1tcXypGrcmMHhDk2t9wGhCsYe/+szLTy1g==",
|
||||
"peer": true,
|
||||
"requires": {
|
||||
"cssesc": "^3.0.0",
|
||||
"util-deprecate": "^1.0.2"
|
||||
|
|
@ -30278,6 +30388,7 @@
|
|||
"version": "15.8.1",
|
||||
"resolved": "https://registry.npmjs.org/prop-types/-/prop-types-15.8.1.tgz",
|
||||
"integrity": "sha512-oj87CgZICdulUohogVAR7AjlC0327U4el4L6eAvOqCeudMDVU0NThNaV+b9Df4dXgSP1gXMTnPdhfe/2qDH5cg==",
|
||||
"peer": true,
|
||||
"requires": {
|
||||
"loose-envify": "^1.4.0",
|
||||
"object-assign": "^4.1.1",
|
||||
|
|
@ -30435,6 +30546,7 @@
|
|||
"version": "18.2.0",
|
||||
"resolved": "https://registry.npmjs.org/react/-/react-18.2.0.tgz",
|
||||
"integrity": "sha512-/3IjMdb2L9QbBdWiW5e3P2/npwMBaU9mHCSCUzNln0ZCYbcfTsGbTJrU/kGemdH2IWmB2ioZ+zkxtmq6g09fGQ==",
|
||||
"peer": true,
|
||||
"requires": {
|
||||
"loose-envify": "^1.1.0"
|
||||
}
|
||||
|
|
@ -30548,6 +30660,7 @@
|
|||
"version": "18.2.0",
|
||||
"resolved": "https://registry.npmjs.org/react-dom/-/react-dom-18.2.0.tgz",
|
||||
"integrity": "sha512-6IMTriUmvsjHUjNtEDudZfuDQUoWXVxKHhlEGSk81n4YFS+r/Kl99wXiwlVXtPBtJenozv2P+hxDsw9eA7Xo6g==",
|
||||
"peer": true,
|
||||
"requires": {
|
||||
"loose-envify": "^1.1.0",
|
||||
"scheduler": "^0.23.0"
|
||||
|
|
@ -30624,7 +30737,8 @@
|
|||
"react-refresh": {
|
||||
"version": "0.11.0",
|
||||
"resolved": "https://registry.npmjs.org/react-refresh/-/react-refresh-0.11.0.tgz",
|
||||
"integrity": "sha512-F27qZr8uUqwhWZboondsPx8tnC3Ct3SxZA3V5WyEvujRyyNv0VYPhoBg1gZ8/MV5tubQp76Trw8lTv9hzRBa+A=="
|
||||
"integrity": "sha512-F27qZr8uUqwhWZboondsPx8tnC3Ct3SxZA3V5WyEvujRyyNv0VYPhoBg1gZ8/MV5tubQp76Trw8lTv9hzRBa+A==",
|
||||
"peer": true
|
||||
},
|
||||
"react-router": {
|
||||
"version": "7.16.0",
|
||||
|
|
@ -30993,6 +31107,7 @@
|
|||
"version": "2.80.0",
|
||||
"resolved": "https://registry.npmjs.org/rollup/-/rollup-2.80.0.tgz",
|
||||
"integrity": "sha512-cIFJOD1DESzpjOBl763Kp1AH7UE/0fcdHe6rZXUdQ9c50uvgigvW97u3IcSeBwOkgqL/PXPBktBCh0KEu5L8XQ==",
|
||||
"peer": true,
|
||||
"requires": {
|
||||
"fsevents": "~2.3.2"
|
||||
}
|
||||
|
|
@ -31178,6 +31293,7 @@
|
|||
"version": "2.1.5",
|
||||
"resolved": "https://registry.npmjs.org/semantic-ui-react/-/semantic-ui-react-2.1.5.tgz",
|
||||
"integrity": "sha512-nIqmmUNpFHfovEb+RI2w3E2/maZQutd8UIWyRjf1SLse+XF51hI559xbz/sLN3O6RpLjr/echLOOXwKCirPy3Q==",
|
||||
"peer": true,
|
||||
"requires": {
|
||||
"@babel/runtime": "^7.10.5",
|
||||
"@fluentui/react-component-event-listener": "~0.63.0",
|
||||
|
|
@ -32007,6 +32123,7 @@
|
|||
"version": "8.18.0",
|
||||
"resolved": "https://registry.npmjs.org/ajv/-/ajv-8.18.0.tgz",
|
||||
"integrity": "sha512-PlXPeEWMXMZ7sPYOHqmDyCJzcfNrUr3fGNKtezX14ykXOEIvyK81d+qydx89KY5O71FKMPaQ2vBfBFI5NHR63A==",
|
||||
"peer": true,
|
||||
"requires": {
|
||||
"fast-deep-equal": "^3.1.3",
|
||||
"fast-uri": "^3.0.1",
|
||||
|
|
@ -32058,7 +32175,8 @@
|
|||
"three": {
|
||||
"version": "0.184.0",
|
||||
"resolved": "https://registry.npmjs.org/three/-/three-0.184.0.tgz",
|
||||
"integrity": "sha512-wtTRjG92pM5eUg/KuUnHsqSAlPM296brTOcLgMRqEeylYTh/CdtvKUvCyyCQTzFuStieWxvZb8mVTMvdPyUpxg=="
|
||||
"integrity": "sha512-wtTRjG92pM5eUg/KuUnHsqSAlPM296brTOcLgMRqEeylYTh/CdtvKUvCyyCQTzFuStieWxvZb8mVTMvdPyUpxg==",
|
||||
"peer": true
|
||||
},
|
||||
"three-stdlib": {
|
||||
"version": "2.17.2",
|
||||
|
|
@ -32260,7 +32378,8 @@
|
|||
"type-fest": {
|
||||
"version": "0.21.3",
|
||||
"resolved": "https://registry.npmjs.org/type-fest/-/type-fest-0.21.3.tgz",
|
||||
"integrity": "sha512-t0rzBq87m3fVcduHDUFhKmyyX+9eo6WQjZvf51Ea/M0Q7+T374Jp1aUiyUl0GKxp8M/OETVHSDvmkyPgvX+X2w=="
|
||||
"integrity": "sha512-t0rzBq87m3fVcduHDUFhKmyyX+9eo6WQjZvf51Ea/M0Q7+T374Jp1aUiyUl0GKxp8M/OETVHSDvmkyPgvX+X2w==",
|
||||
"peer": true
|
||||
},
|
||||
"type-is": {
|
||||
"version": "1.6.18",
|
||||
|
|
@ -32297,7 +32416,8 @@
|
|||
"typescript": {
|
||||
"version": "4.9.5",
|
||||
"resolved": "https://registry.npmjs.org/typescript/-/typescript-4.9.5.tgz",
|
||||
"integrity": "sha512-1FXk9E2Hm+QzZQ7z+McJiHL4NW1F2EzMu9Nq9i3zAaGqibafqYwCVU6WyWAuyQRRzOlxou8xZSyXLEN8oKj24g=="
|
||||
"integrity": "sha512-1FXk9E2Hm+QzZQ7z+McJiHL4NW1F2EzMu9Nq9i3zAaGqibafqYwCVU6WyWAuyQRRzOlxou8xZSyXLEN8oKj24g==",
|
||||
"peer": true
|
||||
},
|
||||
"unbox-primitive": {
|
||||
"version": "1.0.2",
|
||||
|
|
@ -32524,6 +32644,7 @@
|
|||
"version": "5.105.0",
|
||||
"resolved": "https://registry.npmjs.org/webpack/-/webpack-5.105.0.tgz",
|
||||
"integrity": "sha512-gX/dMkRQc7QOMzgTe6KsYFM7DxeIONQSui1s0n/0xht36HvrgbxtM1xBlgx596NbpHuQU8P7QpKwrZYwUX48nw==",
|
||||
"peer": true,
|
||||
"requires": {
|
||||
"@types/eslint-scope": "^3.7.7",
|
||||
"@types/estree": "^1.0.8",
|
||||
|
|
@ -32556,6 +32677,7 @@
|
|||
"version": "8.18.0",
|
||||
"resolved": "https://registry.npmjs.org/ajv/-/ajv-8.18.0.tgz",
|
||||
"integrity": "sha512-PlXPeEWMXMZ7sPYOHqmDyCJzcfNrUr3fGNKtezX14ykXOEIvyK81d+qydx89KY5O71FKMPaQ2vBfBFI5NHR63A==",
|
||||
"peer": true,
|
||||
"requires": {
|
||||
"fast-deep-equal": "^3.1.3",
|
||||
"fast-uri": "^3.0.1",
|
||||
|
|
@ -32619,6 +32741,7 @@
|
|||
"version": "8.18.0",
|
||||
"resolved": "https://registry.npmjs.org/ajv/-/ajv-8.18.0.tgz",
|
||||
"integrity": "sha512-PlXPeEWMXMZ7sPYOHqmDyCJzcfNrUr3fGNKtezX14ykXOEIvyK81d+qydx89KY5O71FKMPaQ2vBfBFI5NHR63A==",
|
||||
"peer": true,
|
||||
"requires": {
|
||||
"fast-deep-equal": "^3.1.3",
|
||||
"fast-uri": "^3.0.1",
|
||||
|
|
@ -32656,6 +32779,7 @@
|
|||
"version": "4.11.1",
|
||||
"resolved": "https://registry.npmjs.org/webpack-dev-server/-/webpack-dev-server-4.11.1.tgz",
|
||||
"integrity": "sha512-lILVz9tAUy1zGFwieuaQtYiadImb5M3d+H+L1zDYalYoDl0cksAB1UNyuE5MMWJrG6zR1tXkCP2fitl7yoUJiw==",
|
||||
"peer": true,
|
||||
"requires": {
|
||||
"@types/bonjour": "^3.5.9",
|
||||
"@types/connect-history-api-fallback": "^1.3.5",
|
||||
|
|
@ -32692,6 +32816,7 @@
|
|||
"version": "8.18.0",
|
||||
"resolved": "https://registry.npmjs.org/ajv/-/ajv-8.18.0.tgz",
|
||||
"integrity": "sha512-PlXPeEWMXMZ7sPYOHqmDyCJzcfNrUr3fGNKtezX14ykXOEIvyK81d+qydx89KY5O71FKMPaQ2vBfBFI5NHR63A==",
|
||||
"peer": true,
|
||||
"requires": {
|
||||
"fast-deep-equal": "^3.1.3",
|
||||
"fast-uri": "^3.0.1",
|
||||
|
|
@ -32938,6 +33063,7 @@
|
|||
"version": "8.18.0",
|
||||
"resolved": "https://registry.npmjs.org/ajv/-/ajv-8.18.0.tgz",
|
||||
"integrity": "sha512-PlXPeEWMXMZ7sPYOHqmDyCJzcfNrUr3fGNKtezX14ykXOEIvyK81d+qydx89KY5O71FKMPaQ2vBfBFI5NHR63A==",
|
||||
"peer": true,
|
||||
"requires": {
|
||||
"fast-deep-equal": "^3.1.3",
|
||||
"fast-uri": "^3.0.1",
|
||||
|
|
|
|||
|
|
@ -9,6 +9,7 @@
|
|||
"@testing-library/react": "^13.4.0",
|
||||
"@testing-library/user-event": "^13.5.0",
|
||||
"cypress": "^13.15.2",
|
||||
"esptool-js": "^0.6.0",
|
||||
"lodash": "^4.18.1",
|
||||
"maplibre-gl": "^5.24.0",
|
||||
"mathjs": "^15.2.0",
|
||||
|
|
|
|||
|
|
@ -25,6 +25,7 @@ import {TagsProvider} from "./Tags";
|
|||
import {ZimRoute} from "./components/Zim";
|
||||
import {PlaylistsRoute} from "./components/Playlists";
|
||||
import {DocsRoute} from "./components/Docs";
|
||||
import {FlasherRoute} from "./components/Flasher";
|
||||
import ErrorBoundary from "./components/ErrorBoundary";
|
||||
import {KeyboardShortcutsProvider} from "./components/KeyboardShortcutsProvider";
|
||||
|
||||
|
|
@ -107,6 +108,7 @@ const router = createBrowserRouter(createRoutesFromElements(<Route
|
|||
<Route path='zim/*' element={<ErrorBoundary><ZimRoute/></ErrorBoundary>}/>
|
||||
<Route path='playlists/*' element={<ErrorBoundary><PlaylistsRoute/></ErrorBoundary>}/>
|
||||
<Route path='files/*' element={<ErrorBoundary><FilesRoute/></ErrorBoundary>}/>
|
||||
<Route path='flasher/*' element={<ErrorBoundary><FlasherRoute/></ErrorBoundary>}/>
|
||||
</Route>));
|
||||
|
||||
export default function App() {
|
||||
|
|
|
|||
|
|
@ -1212,8 +1212,14 @@ export async function deleteDownload(downloadId) {
|
|||
}
|
||||
}
|
||||
|
||||
export async function filesSearch(offset, limit, searchStr, mimetypes, model, tagNames, headline, months, fromYear, toYear, anyTag, order) {
|
||||
export async function filesSearch(offset, limit, searchStr, mimetypes, model, tagNames, headline, months, fromYear, toYear, anyTag, order, suffix, path) {
|
||||
const body = {search_str: searchStr, offset: parseInt(offset), limit: parseInt(limit), any_tag: anyTag};
|
||||
if (suffix) {
|
||||
body['suffix'] = suffix;
|
||||
}
|
||||
if (path) {
|
||||
body['path'] = path;
|
||||
}
|
||||
if (mimetypes) {
|
||||
body['mimetypes'] = mimetypes;
|
||||
}
|
||||
|
|
@ -1257,6 +1263,51 @@ export async function filesSearch(offset, limit, searchStr, mimetypes, model, ta
|
|||
}
|
||||
}
|
||||
|
||||
export async function flasherSearch(chip, path) {
|
||||
// Search .bin firmware, filtered to ESP images for the given chip (from connecting to the device).
|
||||
const body = {};
|
||||
if (chip) body['chip'] = chip;
|
||||
if (path) body['path'] = path;
|
||||
const response = await apiPost(`${API_URI}/flasher/search`, body);
|
||||
if (response.ok) {
|
||||
const data = await response.json();
|
||||
return [data['file_groups'], data['totals']['file_groups']];
|
||||
}
|
||||
const message = await getErrorMessage(response, 'Cannot search firmware. See server logs.');
|
||||
toast({type: 'error', title: 'Unable to search firmware', description: message, time: 5000});
|
||||
return [null, null];
|
||||
}
|
||||
|
||||
export async function getFlasherConfigs() {
|
||||
// Return the user's saved firmware flashing configurations.
|
||||
const response = await apiGet(`${API_URI}/flasher/configs`);
|
||||
if (response.ok) {
|
||||
const data = await response.json();
|
||||
return data['configurations'] || [];
|
||||
}
|
||||
return [];
|
||||
}
|
||||
|
||||
export async function saveFlasherConfig(name, files, eraseAll) {
|
||||
const response = await apiPost(`${API_URI}/flasher/configs`, {name, files, erase_all: eraseAll});
|
||||
if (!response.ok) {
|
||||
const message = await getErrorMessage(response, 'Cannot save configuration. See server logs.');
|
||||
toast({type: 'error', title: 'Unable to save configuration', description: message, time: 5000});
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
export async function deleteFlasherConfig(name) {
|
||||
const response = await apiDelete(`${API_URI}/flasher/configs/${encodeURIComponent(name)}`);
|
||||
if (!response.ok) {
|
||||
const message = await getErrorMessage(response, 'Cannot delete configuration. See server logs.');
|
||||
toast({type: 'error', title: 'Unable to delete configuration', description: message, time: 5000});
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
export async function refreshFiles(paths) {
|
||||
let response;
|
||||
if (Array.isArray(paths) && paths.length > 0) {
|
||||
|
|
|
|||
866
app/src/components/Flasher.js
Normal file
866
app/src/components/Flasher.js
Normal file
|
|
@ -0,0 +1,866 @@
|
|||
import React, {useContext, useEffect, useLayoutEffect, useRef, useState} from 'react';
|
||||
import {Route, Routes} from "react-router";
|
||||
import {Checkbox, Label, Message, Select, Button as SButton, Icon as SIcon} from "semantic-ui-react";
|
||||
import {ESPLoader, Transport} from "esptool-js";
|
||||
import {useDropzone} from "react-dropzone";
|
||||
import _ from "lodash";
|
||||
import {encodeMediaPath, humanFileSize, PageContainer, useTitle} from "./Common";
|
||||
import {
|
||||
Button,
|
||||
darkTheme,
|
||||
Divider,
|
||||
Form,
|
||||
Header,
|
||||
Icon,
|
||||
List,
|
||||
Loader,
|
||||
Modal,
|
||||
Progress,
|
||||
Segment,
|
||||
Tab,
|
||||
Table,
|
||||
TextArea
|
||||
} from "./Theme";
|
||||
import {ThemeContext} from "../contexts/contexts";
|
||||
import {deleteFlasherConfig, filesSearch, flasherSearch, getFlasherConfigs, saveFlasherConfig} from "../api";
|
||||
|
||||
// The suffix used to find flashable ESP32 firmware in the media directory.
|
||||
const FIRMWARE_SUFFIX = '.bin';
|
||||
|
||||
// esptool-js reports a chip description like "ESP32-S2 (revision v0.0)"; take the family before " (".
|
||||
export function chipFamily(description) {
|
||||
return (description || '').split(' (')[0].trim() || null;
|
||||
}
|
||||
|
||||
// Flashing happens entirely in the browser using the Web Serial API; nothing is uploaded to WROLPi. esptool-js is
|
||||
// bundled into the frontend build, so this works fully offline once the page has loaded.
|
||||
|
||||
const BAUD_OPTIONS = [
|
||||
{key: '115200', value: 115200, text: '115200 (safe)'},
|
||||
{key: '230400', value: 230400, text: '230400'},
|
||||
{key: '460800', value: 460800, text: '460800'},
|
||||
{key: '921600', value: 921600, text: '921600 (fast)'},
|
||||
];
|
||||
|
||||
// Web Serial is only available in a secure context (HTTPS or localhost) on Chromium-based browsers.
|
||||
export function webSerialSupported() {
|
||||
return typeof navigator !== 'undefined' && 'serial' in navigator;
|
||||
}
|
||||
|
||||
function readFileAsUint8Array(file) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const reader = new FileReader();
|
||||
reader.onload = () => resolve(new Uint8Array(reader.result));
|
||||
reader.onerror = () => reject(reader.error);
|
||||
reader.readAsArrayBuffer(file);
|
||||
});
|
||||
}
|
||||
|
||||
// Load a firmware entry's bytes. Local files are read from disk; media entries are fetched from the WROLPi
|
||||
// media directory over HTTP. Both return a Uint8Array as esptool-js expects.
|
||||
async function readEntryBytes(item) {
|
||||
if (item.file) {
|
||||
return readFileAsUint8Array(item.file);
|
||||
}
|
||||
const resp = await fetch(`/media/${encodeMediaPath(item.mediaPath)}`);
|
||||
if (!resp.ok) {
|
||||
throw new Error(`Failed to fetch ${item.name} from the media directory (${resp.status})`);
|
||||
}
|
||||
const buffer = await resp.arrayBuffer();
|
||||
return new Uint8Array(buffer);
|
||||
}
|
||||
|
||||
// A flash offset must be a 0x-prefixed hex string, e.g. "0x0" or "0x10000".
|
||||
const HEX_OFFSET_RE = /^0x[0-9a-f]+$/i;
|
||||
|
||||
export function isValidHexOffset(value) {
|
||||
return HEX_OFFSET_RE.test((value || '').trim());
|
||||
}
|
||||
|
||||
// Parse a validated hex flash offset like "0x10000" or "0x0" into a number.
|
||||
export function parseAddress(value) {
|
||||
const trimmed = (value || '').trim();
|
||||
if (trimmed === '') {
|
||||
throw new Error('Flash offset is required');
|
||||
}
|
||||
if (!isValidHexOffset(trimmed)) {
|
||||
throw new Error(`Invalid flash offset (expected a hex value like 0x10000): ${value}`);
|
||||
}
|
||||
return parseInt(trimmed, 16);
|
||||
}
|
||||
|
||||
// Rough estimate of how long flashing will take, in seconds. Serial is 8N1 (10 bits per byte), so the link
|
||||
// carries ~baud/10 bytes/sec; esptool-js compresses the image (~0.6x), which roughly offsets SLIP framing and
|
||||
// flash-write overhead, making raw bytes / (baud/10) a reasonable ballpark.
|
||||
export function estimateFlashSeconds(totalBytes, baudrate) {
|
||||
if (!totalBytes || !baudrate) {
|
||||
return 0;
|
||||
}
|
||||
return totalBytes / (baudrate / 10);
|
||||
}
|
||||
|
||||
// Format a duration in seconds as e.g. "45s" or "2m 5s".
|
||||
export function humanDuration(seconds) {
|
||||
if (!seconds || !isFinite(seconds) || seconds <= 0) {
|
||||
return null;
|
||||
}
|
||||
const total = Math.round(seconds);
|
||||
const minutes = Math.floor(total / 60);
|
||||
const secs = total % 60;
|
||||
return minutes > 0 ? `${minutes}m ${secs}s` : `${secs}s`;
|
||||
}
|
||||
|
||||
// Reject if `promise` doesn't settle within `ms`. esptool-js's connect can hang indefinitely when a board is
|
||||
// not in download mode; this guarantees the caller always gets a result so the UI can recover.
|
||||
export function withTimeout(promise, ms, message) {
|
||||
let timer;
|
||||
const timeout = new Promise((_, reject) => {
|
||||
timer = setTimeout(() => reject(new Error(message)), ms);
|
||||
});
|
||||
// Swallow a late rejection from the raced promise so it doesn't surface as an unhandled rejection.
|
||||
promise.catch(() => {
|
||||
});
|
||||
return Promise.race([promise, timeout]).finally(() => clearTimeout(timer));
|
||||
}
|
||||
|
||||
// How long to wait for a device to connect before giving up (esptool-js retries can otherwise stall the UI).
|
||||
const CONNECT_TIMEOUT_MS = 30_000;
|
||||
|
||||
// A read-only log TextArea that auto-scrolls to the newest output — but only when the user is already at the
|
||||
// bottom, so scrolling up to read earlier lines isn't yanked back down. Starts at the bottom on mount (e.g. when
|
||||
// a modal opens).
|
||||
function AutoScrollLog({value, ...props}) {
|
||||
const containerRef = useRef(null);
|
||||
const atBottomRef = useRef(true);
|
||||
|
||||
const getTextArea = () => containerRef.current && containerRef.current.querySelector('textarea');
|
||||
|
||||
const handleScroll = (e) => {
|
||||
const el = e.target;
|
||||
// Treat "within a few px of the bottom" as at-bottom so it re-sticks when the user scrolls back down.
|
||||
atBottomRef.current = el.scrollHeight - el.scrollTop - el.clientHeight < 20;
|
||||
};
|
||||
|
||||
useLayoutEffect(() => {
|
||||
const el = getTextArea();
|
||||
if (el && atBottomRef.current) {
|
||||
el.scrollTop = el.scrollHeight;
|
||||
}
|
||||
}, [value]);
|
||||
|
||||
return <div ref={containerRef}>
|
||||
<TextArea readOnly value={value} onScroll={handleScroll} {...props}/>
|
||||
</div>;
|
||||
}
|
||||
|
||||
export function FlasherPage() {
|
||||
useTitle('Flasher');
|
||||
const {t, theme} = useContext(ThemeContext);
|
||||
|
||||
// Each entry is {name, size, address, file?: File, mediaPath?: string}. A local file has `file`; a media
|
||||
// firmware has `mediaPath`. Default offset 0x0 suits a single merged firmware image.
|
||||
const [files, setFiles] = useState([]);
|
||||
const [baudrate, setBaudrate] = useState(115200);
|
||||
const [eraseAll, setEraseAll] = useState(false);
|
||||
|
||||
// Media-directory firmware picker.
|
||||
const [mediaFilter, setMediaFilter] = useState('');
|
||||
const [mediaResults, setMediaResults] = useState([]);
|
||||
const [mediaLoading, setMediaLoading] = useState(false);
|
||||
// When set (e.g. "ESP32-S2"), the picker only shows firmware for that chip (detected from the device).
|
||||
const [deviceChip, setDeviceChip] = useState(null);
|
||||
const deviceChipRef = useRef(null); // Mirror for the debounced fetch closure.
|
||||
|
||||
const [connected, setConnected] = useState(false);
|
||||
const [connecting, setConnecting] = useState(false);
|
||||
const [flashing, setFlashing] = useState(false);
|
||||
const [chip, setChip] = useState('');
|
||||
const [progress, setProgress] = useState(null); // {fileIndex, percent}
|
||||
const [error, setError] = useState('');
|
||||
// Set when a connection attempt fails, so we can remind the user to put the board into download/boot mode.
|
||||
const [bootHint, setBootHint] = useState(false);
|
||||
const [log, setLog] = useState('');
|
||||
const [logOpen, setLogOpen] = useState(false);
|
||||
const [flashOpen, setFlashOpen] = useState(false);
|
||||
|
||||
// Which firmware-source tab is active (controlled so a file drop can switch to "Add from computer").
|
||||
const [activeTab, setActiveTab] = useState(0);
|
||||
|
||||
// Saved firmware configurations (flasher.yaml).
|
||||
const [savedConfigs, setSavedConfigs] = useState([]);
|
||||
const [saveModalOpen, setSaveModalOpen] = useState(false);
|
||||
const [saveName, setSaveName] = useState('');
|
||||
|
||||
const transportRef = useRef(null);
|
||||
const esploaderRef = useRef(null);
|
||||
const logRef = useRef('');
|
||||
|
||||
const appendLog = (data) => {
|
||||
logRef.current += data;
|
||||
setLog(logRef.current);
|
||||
};
|
||||
|
||||
// esptool-js writes progress/status through this terminal interface.
|
||||
const terminal = {
|
||||
clean: () => {
|
||||
logRef.current = '';
|
||||
setLog('');
|
||||
},
|
||||
writeLine: (data) => appendLog(data + '\n'),
|
||||
write: (data) => appendLog(data),
|
||||
};
|
||||
|
||||
// Disabled while connecting or flashing (also gates the dropzone below).
|
||||
const busy = connecting || flashing;
|
||||
|
||||
// First entry added defaults to offset 0x0 (a single merged image); later parts default to blank so the user
|
||||
// must set their offset deliberately.
|
||||
const nextDefaultAddress = (prev, idx) => (prev.length === 0 && idx === 0 ? '0x0' : '');
|
||||
|
||||
// Add local File objects to the firmware list. Shared by the file input and drag-and-drop.
|
||||
const addFiles = (selected) => {
|
||||
if (selected.length > 0) {
|
||||
setFiles(prev => [
|
||||
...prev,
|
||||
...selected.map((file, idx) => ({
|
||||
file,
|
||||
name: file.name,
|
||||
size: file.size,
|
||||
address: nextDefaultAddress(prev, idx),
|
||||
})),
|
||||
]);
|
||||
}
|
||||
};
|
||||
|
||||
// The "Add from computer" tab (index 2 in firmwarePanes) hosts the dropzone; a drop anywhere on the page or a
|
||||
// click on the zone lands here.
|
||||
const COMPUTER_TAB_INDEX = 2;
|
||||
const onDrop = React.useCallback((droppedFiles) => {
|
||||
// Only take .bin firmware; anything else dropped is ignored.
|
||||
const bins = (droppedFiles || []).filter(file => file.name.toLowerCase().endsWith(FIRMWARE_SUFFIX));
|
||||
if (bins.length > 0) {
|
||||
addFiles(bins);
|
||||
setActiveTab(COMPUTER_TAB_INDEX);
|
||||
}
|
||||
}, []); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
// The dropzone root wraps the whole page so firmware can be dropped anywhere. noClick/noKeyboard because the
|
||||
// page has its own controls; the file dialog is opened explicitly via open() from the dropzone in the tab.
|
||||
const {getRootProps, getInputProps, isDragActive, open} = useDropzone({
|
||||
onDrop,
|
||||
disabled: busy,
|
||||
noClick: true,
|
||||
noKeyboard: true,
|
||||
});
|
||||
|
||||
// While the user drags a file over the page, jump to the "Add from computer" tab so the drop target is shown.
|
||||
useEffect(() => {
|
||||
if (isDragActive) {
|
||||
setActiveTab(COMPUTER_TAB_INDEX);
|
||||
}
|
||||
}, [isDragActive]);
|
||||
|
||||
const handleAddMediaFile = (result) => {
|
||||
setFiles(prev => [
|
||||
...prev,
|
||||
{
|
||||
mediaPath: result.primary_path,
|
||||
name: result.name || result.primary_path,
|
||||
size: result.size,
|
||||
address: nextDefaultAddress(prev, 0),
|
||||
},
|
||||
]);
|
||||
};
|
||||
|
||||
// Fetch firmware for the picker. `pathFilter` is a case-insensitive match against the full file path (so
|
||||
// "bffb" lists the firmware inside that directory). When `chip` is set, only ESP images for that chip are
|
||||
// returned (server inspects each file's header); otherwise all .bin files are listed.
|
||||
const fetchMediaFirmware = React.useCallback(async (pathFilter, chip) => {
|
||||
setMediaLoading(true);
|
||||
try {
|
||||
let fileGroups;
|
||||
if (chip) {
|
||||
[fileGroups] = await flasherSearch(chip, pathFilter || null);
|
||||
} else {
|
||||
[fileGroups] = await filesSearch(0, 50, null, null, null, null,
|
||||
false, null, null, null, false, null, FIRMWARE_SUFFIX, pathFilter || null);
|
||||
}
|
||||
setMediaResults(fileGroups || []);
|
||||
} catch (e) {
|
||||
// Surface connectivity errors instead of showing the empty "no firmware found" state, which would
|
||||
// be indistinguishable from genuinely having no firmware.
|
||||
setError(e && e.message ? e.message : String(e));
|
||||
setBootHint(false);
|
||||
setMediaResults([]);
|
||||
} finally {
|
||||
setMediaLoading(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
// Auto-fetch on page load.
|
||||
useEffect(() => {
|
||||
fetchMediaFirmware('', null);
|
||||
}, [fetchMediaFirmware]);
|
||||
|
||||
// Debounce filter changes so we don't fire a request on every keystroke. Reads the device chip from a ref
|
||||
// so the (once-created) debounced function always uses the current filter.
|
||||
const debouncedFetch = useRef(_.debounce((value) => fetchMediaFirmware(value, deviceChipRef.current), 400)).current;
|
||||
// Cancel any pending debounced fetch on unmount so it can't setState on a gone component.
|
||||
useEffect(() => () => debouncedFetch.cancel(), [debouncedFetch]);
|
||||
const handleMediaFilterChange = (value) => {
|
||||
setMediaFilter(value);
|
||||
debouncedFetch(value);
|
||||
};
|
||||
|
||||
const applyDeviceChip = (chip) => {
|
||||
deviceChipRef.current = chip;
|
||||
setDeviceChip(chip);
|
||||
fetchMediaFirmware(mediaFilter, chip);
|
||||
};
|
||||
|
||||
// Saved firmware configurations.
|
||||
const fetchSavedConfigs = React.useCallback(async () => {
|
||||
setSavedConfigs(await getFlasherConfigs());
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
fetchSavedConfigs();
|
||||
}, [fetchSavedConfigs]);
|
||||
|
||||
// Media firmware entries that can be persisted (local computer files have no stable path, so are excluded).
|
||||
const saveableFiles = files.filter(item => item.mediaPath);
|
||||
|
||||
const handleSaveConfig = async () => {
|
||||
const name = saveName.trim();
|
||||
if (!name) {
|
||||
return;
|
||||
}
|
||||
const payload = saveableFiles.map(item => ({
|
||||
path: item.mediaPath, address: item.address, name: item.name, size: item.size,
|
||||
}));
|
||||
if (await saveFlasherConfig(name, payload, eraseAll)) {
|
||||
setSaveModalOpen(false);
|
||||
setSaveName('');
|
||||
await fetchSavedConfigs();
|
||||
}
|
||||
};
|
||||
|
||||
// Load a saved configuration into the firmware list, replacing the current selection.
|
||||
const handleLoadConfig = (configuration) => {
|
||||
setFiles((configuration.files || []).map(f => ({
|
||||
mediaPath: f.path,
|
||||
address: f.address || '',
|
||||
name: f.name || (f.path || '').split('/').pop(),
|
||||
size: f.size,
|
||||
})));
|
||||
setEraseAll(!!configuration.erase_all);
|
||||
};
|
||||
|
||||
const handleDeleteConfig = async (name) => {
|
||||
if (await deleteFlasherConfig(name)) {
|
||||
await fetchSavedConfigs();
|
||||
}
|
||||
};
|
||||
|
||||
const handleAddressChange = (index, value) => {
|
||||
setFiles(prev => prev.map((item, i) => i === index ? {...item, address: value} : item));
|
||||
};
|
||||
|
||||
const handleRemoveFile = (index) => {
|
||||
setFiles(prev => prev.filter((_, i) => i !== index));
|
||||
};
|
||||
|
||||
// Open the serial port and detect the chip. Returns the chip description string (e.g. "ESP32-S2 (...)").
|
||||
const connectAndDetect = async () => {
|
||||
const port = await navigator.serial.requestPort();
|
||||
const transport = new Transport(port, true);
|
||||
// Store the transport before main() so a failure below still reaches disconnect() and releases the
|
||||
// serial port (otherwise the port stays locked until the page is refreshed).
|
||||
transportRef.current = transport;
|
||||
const esploader = new ESPLoader({transport, baudrate, terminal});
|
||||
// esptool-js can hang forever if the board is not in download mode; bound it so the UI always recovers.
|
||||
const chipDescription = await withTimeout(esploader.main(), CONNECT_TIMEOUT_MS,
|
||||
'Timed out waiting for the device to respond.');
|
||||
esploaderRef.current = esploader;
|
||||
setChip(chipDescription);
|
||||
setConnected(true);
|
||||
return chipDescription;
|
||||
};
|
||||
|
||||
const handleConnectError = async (e) => {
|
||||
// A user cancelling the browser's device picker throws; treat that quietly.
|
||||
if (e && e.name === 'NotFoundError') {
|
||||
appendLog('No device selected.\n');
|
||||
} else {
|
||||
const detail = e && e.message ? e.message : String(e);
|
||||
setError(detail);
|
||||
// A connect/sync failure is usually the board not being in download mode; remind the user.
|
||||
setBootHint(true);
|
||||
// Also record it in the log, which otherwise freezes at "Connecting..." with no indication of failure.
|
||||
appendLog(`\nConnection failed: ${detail}\n`);
|
||||
}
|
||||
await disconnect();
|
||||
};
|
||||
|
||||
const handleConnect = async () => {
|
||||
setError('');
|
||||
setBootHint(false);
|
||||
setConnecting(true);
|
||||
try {
|
||||
await connectAndDetect();
|
||||
} catch (e) {
|
||||
await handleConnectError(e);
|
||||
} finally {
|
||||
setConnecting(false);
|
||||
}
|
||||
};
|
||||
|
||||
// Layman flow: (re)detect the connected device and filter the firmware list to its chip. Always releases any
|
||||
// existing connection and prompts for the port again, so swapping to a different ESP device is detected fresh.
|
||||
const handleFilterByDevice = async () => {
|
||||
setError('');
|
||||
setBootHint(false);
|
||||
setConnecting(true);
|
||||
try {
|
||||
await disconnect();
|
||||
const family = chipFamily(await connectAndDetect());
|
||||
if (family) {
|
||||
applyDeviceChip(family);
|
||||
}
|
||||
} catch (e) {
|
||||
await handleConnectError(e);
|
||||
} finally {
|
||||
setConnecting(false);
|
||||
}
|
||||
};
|
||||
|
||||
const disconnect = async () => {
|
||||
try {
|
||||
if (transportRef.current) {
|
||||
await transportRef.current.disconnect();
|
||||
}
|
||||
} catch (e) {
|
||||
// Ignore disconnect errors; the device may already be gone.
|
||||
}
|
||||
transportRef.current = null;
|
||||
esploaderRef.current = null;
|
||||
setConnected(false);
|
||||
setChip('');
|
||||
setProgress(null);
|
||||
};
|
||||
|
||||
const handleFlash = async () => {
|
||||
if (!esploaderRef.current || files.length === 0) {
|
||||
return;
|
||||
}
|
||||
setError('');
|
||||
setBootHint(false);
|
||||
setFlashOpen(true);
|
||||
setFlashing(true);
|
||||
setProgress({fileIndex: 0, percent: 0});
|
||||
try {
|
||||
const fileArray = [];
|
||||
for (const item of files) {
|
||||
const address = parseAddress(item.address);
|
||||
const data = await readEntryBytes(item);
|
||||
fileArray.push({data, address});
|
||||
}
|
||||
await esploaderRef.current.writeFlash({
|
||||
fileArray,
|
||||
// 'keep' preserves the flash parameters baked into the firmware image, which is correct for
|
||||
// bring-your-own merged binaries.
|
||||
flashSize: 'keep',
|
||||
flashMode: 'keep',
|
||||
flashFreq: 'keep',
|
||||
eraseAll,
|
||||
compress: true,
|
||||
reportProgress: (fileIndex, written, total) => {
|
||||
setProgress({fileIndex, percent: total ? Math.round((written / total) * 100) : 0});
|
||||
},
|
||||
});
|
||||
appendLog('\nFlash complete! Resetting device...\n');
|
||||
await esploaderRef.current.after('hard_reset');
|
||||
} catch (e) {
|
||||
setError(e && e.message ? e.message : String(e));
|
||||
setBootHint(false);
|
||||
} finally {
|
||||
setFlashing(false);
|
||||
}
|
||||
};
|
||||
|
||||
if (!webSerialSupported()) {
|
||||
return <PageContainer>
|
||||
<Header as='h1'>Flasher</Header>
|
||||
<Message icon warning>
|
||||
<SIcon name='warning sign'/>
|
||||
<Message.Content>
|
||||
<Message.Header>Web Serial is not available</Message.Header>
|
||||
<p>Flashing requires the Web Serial API, which is only available in Chromium-based browsers
|
||||
(Chrome, Edge, Brave) served over a secure connection (HTTPS or <code>localhost</code>).</p>
|
||||
<p>Open this page in Chrome or Edge over <code>https://</code> to flash your device. Firefox
|
||||
and iOS are not supported.</p>
|
||||
</Message.Content>
|
||||
</Message>
|
||||
</PageContainer>;
|
||||
}
|
||||
|
||||
// Every firmware file must have a valid hex offset before flashing is allowed.
|
||||
const offsetsValid = files.length > 0 && files.every(item => isValidHexOffset(item.address));
|
||||
|
||||
// Estimated flash time from the total firmware size and the selected baud rate.
|
||||
const totalFlashBytes = files.reduce((sum, item) => sum + (item.size || 0), 0);
|
||||
const flashEtaText = humanDuration(estimateFlashSeconds(totalFlashBytes, baudrate));
|
||||
|
||||
// The nested tab menu isn't inverted automatically; give it the inverted style in dark mode so it matches.
|
||||
const tabMenu = theme === darkTheme ? {inverted: true, attached: true} : {attached: true};
|
||||
|
||||
// The firmware source is chosen via three tabs (see the ordered array below).
|
||||
const computerPane = {
|
||||
menuItem: 'Add from computer',
|
||||
render: () => <Tab.Pane>
|
||||
{/* Clickable drop target (files may also be dropped anywhere on the page, which routes here). */}
|
||||
<Segment
|
||||
placeholder
|
||||
onClick={busy ? undefined : open}
|
||||
style={{
|
||||
cursor: busy ? 'default' : 'pointer',
|
||||
textAlign: 'center',
|
||||
...(isDragActive ? {outline: '2px dashed #2185d0', outlineOffset: '-2px'} : {}),
|
||||
}}
|
||||
>
|
||||
<Header icon {...t}>
|
||||
<Icon name='microchip'/>
|
||||
{isDragActive
|
||||
? <>Drop <code>.bin</code> firmware to add it</>
|
||||
: <>Click here, or drop <code>.bin</code> firmware here</>}
|
||||
</Header>
|
||||
</Segment>
|
||||
<p {...t} style={{marginTop: '1em', opacity: 0.8}}>
|
||||
A single merged image is flashed at offset <code>0x0</code>. For multi-part firmware, add each
|
||||
part and set its offset (e.g. bootloader <code>0x1000</code>, partitions <code>0x8000</code>,
|
||||
app <code>0x10000</code>).
|
||||
</p>
|
||||
</Tab.Pane>,
|
||||
};
|
||||
const wrolpiPane = {
|
||||
menuItem: 'Choose from your WROLPi',
|
||||
render: () => <Tab.Pane>
|
||||
<p {...t} style={{opacity: 0.8}}>
|
||||
Not sure which file you need? Plug in your device and let WROLPi show only the firmware that
|
||||
matches it.
|
||||
</p>
|
||||
{/* Always available so a user who swaps to a different ESP device can re-detect it. */}
|
||||
<Button
|
||||
icon labelPosition='left'
|
||||
loading={connecting}
|
||||
disabled={busy}
|
||||
onClick={handleFilterByDevice}
|
||||
>
|
||||
<Icon name='usb'/>
|
||||
{deviceChip ? 'Detect a different device' : 'Filter files by detecting device'}
|
||||
</Button>
|
||||
{deviceChip &&
|
||||
<Message info>
|
||||
{/* Plain (non-inverted) icon: Message backgrounds are light, so a themed white icon
|
||||
vanishes. */}
|
||||
<SIcon name='microchip'/>
|
||||
Showing firmware for <b>{deviceChip}</b>.
|
||||
<SButton size='tiny' compact onClick={() => applyDeviceChip(null)}
|
||||
disabled={busy} style={{marginLeft: '1em'}}>
|
||||
Show all firmware
|
||||
</SButton>
|
||||
</Message>}
|
||||
<Form style={{marginTop: '1em'}}>
|
||||
<Form.Input
|
||||
fluid
|
||||
icon='search'
|
||||
placeholder='Filter firmware by path (e.g. a folder name)...'
|
||||
value={mediaFilter}
|
||||
disabled={busy}
|
||||
onChange={(e, {value}) => handleMediaFilterChange(value)}
|
||||
/>
|
||||
</Form>
|
||||
<div style={{marginTop: '1em'}}>
|
||||
{mediaLoading
|
||||
? <Loader active inline='centered'/>
|
||||
: (mediaResults.length === 0
|
||||
? <p {...t} style={{opacity: 0.7}}>
|
||||
No <code>.bin</code> firmware found
|
||||
{deviceChip ? ` for ${deviceChip}` : ' in your media directory'}
|
||||
{mediaFilter ? ' matching that filter.' : '.'}
|
||||
</p>
|
||||
: <List divided relaxed selection>
|
||||
{mediaResults.map(result => <List.Item
|
||||
key={result.primary_path}
|
||||
onClick={busy ? undefined : () => handleAddMediaFile(result)}
|
||||
style={busy ? {opacity: 0.5} : {cursor: 'pointer'}}
|
||||
>
|
||||
<List.Icon name='plus' verticalAlign='middle'/>
|
||||
<List.Content>
|
||||
<List.Header>
|
||||
{result.name || result.primary_path}
|
||||
{result.esp_kind &&
|
||||
<Label size='tiny'
|
||||
color={result.esp_kind === 'factory' ? 'green' : 'grey'}
|
||||
style={{marginLeft: '0.5em'}}>
|
||||
{result.esp_kind}
|
||||
</Label>}
|
||||
</List.Header>
|
||||
<List.Description {...t}>
|
||||
{result.primary_path} — {humanFileSize(result.size)}
|
||||
{result.esp_chip && ` — ${result.esp_chip}`}
|
||||
</List.Description>
|
||||
</List.Content>
|
||||
</List.Item>)}
|
||||
</List>)}
|
||||
</div>
|
||||
</Tab.Pane>,
|
||||
};
|
||||
const savedPane = {
|
||||
menuItem: 'Saved Firmwares',
|
||||
render: () => <Tab.Pane>
|
||||
<p {...t} style={{opacity: 0.8}}>
|
||||
Configure the firmware files and offsets, then save them as a named set to re-flash later
|
||||
(e.g. a Meshtastic T-Deck: firmware at <code>0x0</code>, littlefs at <code>0xc90000</code>).
|
||||
</p>
|
||||
{savedConfigs.length > 0
|
||||
? <List divided relaxed selection>
|
||||
{savedConfigs.map(configuration => <List.Item key={configuration.name}>
|
||||
<List.Content floated='right'>
|
||||
<Button icon='trash' size='mini' color='red' disabled={busy}
|
||||
onClick={() => handleDeleteConfig(configuration.name)}/>
|
||||
</List.Content>
|
||||
<List.Icon name='save' verticalAlign='middle'/>
|
||||
<List.Content onClick={busy ? undefined : () => handleLoadConfig(configuration)}
|
||||
style={busy ? {} : {cursor: 'pointer'}}>
|
||||
<List.Header>{configuration.name}</List.Header>
|
||||
<List.Description {...t}>
|
||||
{(configuration.files || []).length} file(s)
|
||||
{configuration.erase_all ? ' — erases flash' : ''}
|
||||
</List.Description>
|
||||
</List.Content>
|
||||
</List.Item>)}
|
||||
</List>
|
||||
: <p {...t} style={{opacity: 0.7}}>No saved configurations yet.</p>}
|
||||
<Button icon labelPosition='left' disabled={busy || saveableFiles.length === 0}
|
||||
onClick={() => setSaveModalOpen(true)} style={{marginTop: '0.5em'}}>
|
||||
<Icon name='save'/>
|
||||
Save current firmware
|
||||
</Button>
|
||||
</Tab.Pane>,
|
||||
};
|
||||
// Tab order: saved sets first, then the media picker, then a local file.
|
||||
const firmwarePanes = [savedPane, wrolpiPane, computerPane];
|
||||
|
||||
return <div {...getRootProps()}>
|
||||
{/* The dropzone root wraps the whole page: firmware .bin files can be dropped anywhere and are routed to
|
||||
the "Add from computer" tab. noClick is set, so this wrapper never opens the file dialog itself. */}
|
||||
<input {...getInputProps()}/>
|
||||
<PageContainer>
|
||||
<Header as='h1'>Flasher</Header>
|
||||
<p {...t}>
|
||||
Flash firmware onto an ESP32/ESP8266 device directly from your browser over USB. Choose one or more
|
||||
firmware <code>.bin</code> files — from your computer or from your WROLPi's media directory —
|
||||
connect your device, then flash. The flash happens entirely in your browser and is written straight to
|
||||
the device over USB.
|
||||
</p>
|
||||
|
||||
{/* Connection errors render inside the Connect segment (below), where the user just clicked. Other
|
||||
errors show here at the top. */}
|
||||
{error && !bootHint && <Message error onDismiss={() => setError('')}>
|
||||
<Message.Header>Error</Message.Header>
|
||||
<p>{error}</p>
|
||||
</Message>}
|
||||
|
||||
<Segment>
|
||||
<Header as='h3'>1. Firmware files</Header>
|
||||
<Tab
|
||||
menu={tabMenu}
|
||||
panes={firmwarePanes}
|
||||
activeIndex={activeTab}
|
||||
onTabChange={(e, {activeIndex}) => setActiveTab(activeIndex)}
|
||||
/>
|
||||
|
||||
{/* The selected firmware is shown below the source tabs so it stays visible regardless of which tab
|
||||
(computer / WROLPi / saved) the user is on. */}
|
||||
{files.length > 0 && <>
|
||||
<Divider/>
|
||||
<Header as='h4'>Selected firmware</Header>
|
||||
<Table compact unstackable>
|
||||
<Table.Header>
|
||||
<Table.Row>
|
||||
<Table.HeaderCell>File</Table.HeaderCell>
|
||||
<Table.HeaderCell width={4}>Flash offset</Table.HeaderCell>
|
||||
<Table.HeaderCell width={1}/>
|
||||
</Table.Row>
|
||||
</Table.Header>
|
||||
<Table.Body>
|
||||
{files.map((item, index) => <Table.Row key={`${item.name}-${index}`}>
|
||||
<Table.Cell>
|
||||
<Icon name={item.mediaPath ? 'database' : 'file'}/>
|
||||
{item.name} <span style={{opacity: 0.6}}>({humanFileSize(item.size)})</span>
|
||||
</Table.Cell>
|
||||
<Table.Cell>
|
||||
<Form.Input
|
||||
fluid
|
||||
size='small'
|
||||
placeholder='0x10000'
|
||||
value={item.address}
|
||||
disabled={busy}
|
||||
error={!isValidHexOffset(item.address)}
|
||||
onChange={(e, {value}) => handleAddressChange(index, value)}
|
||||
/>
|
||||
</Table.Cell>
|
||||
<Table.Cell textAlign='center'>
|
||||
<Button icon='trash' size='mini' color='red' disabled={busy}
|
||||
onClick={() => handleRemoveFile(index)}/>
|
||||
</Table.Cell>
|
||||
</Table.Row>)}
|
||||
</Table.Body>
|
||||
</Table>
|
||||
</>}
|
||||
</Segment>
|
||||
|
||||
<Modal open={saveModalOpen} onClose={() => setSaveModalOpen(false)} size='tiny'>
|
||||
<Modal.Header>Save firmware configuration</Modal.Header>
|
||||
<Modal.Content>
|
||||
<Form onSubmit={handleSaveConfig}>
|
||||
<Form.Input
|
||||
autoFocus
|
||||
label='Name'
|
||||
placeholder='e.g. T-Deck Meshtastic UI'
|
||||
value={saveName}
|
||||
onChange={(e, {value}) => setSaveName(value)}
|
||||
/>
|
||||
<p {...t} style={{opacity: 0.8}}>
|
||||
Saving {saveableFiles.length} firmware file(s) from your WROLPi. An existing configuration
|
||||
with the same name will be replaced.
|
||||
</p>
|
||||
</Form>
|
||||
</Modal.Content>
|
||||
<Modal.Actions>
|
||||
<SButton onClick={() => setSaveModalOpen(false)}>Cancel</SButton>
|
||||
<Button primary disabled={!saveName.trim()} onClick={handleSaveConfig}>Save</Button>
|
||||
</Modal.Actions>
|
||||
</Modal>
|
||||
|
||||
<Segment>
|
||||
<Header as='h3'>2. Connect</Header>
|
||||
<Form>
|
||||
<Form.Field>
|
||||
<label>Baud rate</label>
|
||||
<Select
|
||||
options={BAUD_OPTIONS}
|
||||
value={baudrate}
|
||||
disabled={connected || busy}
|
||||
onChange={(e, {value}) => setBaudrate(value)}
|
||||
/>
|
||||
</Form.Field>
|
||||
{connected &&
|
||||
<Message positive>
|
||||
<SIcon name='usb'/> Connected to <b>{chip}</b>
|
||||
</Message>}
|
||||
{connected
|
||||
? <Button color='grey' disabled={busy} onClick={disconnect}>Disconnect</Button>
|
||||
: <Button primary loading={connecting} disabled={busy} onClick={handleConnect}>
|
||||
Connect Device
|
||||
</Button>}
|
||||
<Button icon labelPosition='left' disabled={!log} onClick={() => setLogOpen(true)}>
|
||||
<Icon name='terminal'/> Logs
|
||||
</Button>
|
||||
</Form>
|
||||
{/* Rendered outside <Form> so Semantic's ".ui.form .error.message { display:none }" rule doesn't
|
||||
hide it, and here (not at the top) so it is visible right where the user clicked Connect. */}
|
||||
{error && bootHint && <Message error onDismiss={() => {
|
||||
setError('');
|
||||
setBootHint(false);
|
||||
}} style={{marginTop: '1em'}}>
|
||||
<Message.Header>Could not connect to the device</Message.Header>
|
||||
<p>{error}</p>
|
||||
<p>
|
||||
Many ESP boards must be put into <b>download mode</b> manually before flashing. Hold the
|
||||
{' '}<b>BOOT</b> (or <b>IO0</b>) button, briefly press <b>RESET</b> (<b>EN</b>), then release
|
||||
BOOT and try again. Also check the USB cable is a data cable and no other tab has the port
|
||||
open.
|
||||
</p>
|
||||
</Message>}
|
||||
</Segment>
|
||||
|
||||
<Segment>
|
||||
<Header as='h3'>3. Flash</Header>
|
||||
<Form>
|
||||
<Form.Field>
|
||||
<Checkbox
|
||||
label='Erase all flash before writing'
|
||||
checked={eraseAll}
|
||||
disabled={busy}
|
||||
onChange={(e, {checked}) => setEraseAll(checked)}
|
||||
/>
|
||||
</Form.Field>
|
||||
<Button
|
||||
color='red'
|
||||
loading={flashing}
|
||||
disabled={!connected || flashing || files.length === 0 || !offsetsValid}
|
||||
onClick={handleFlash}
|
||||
>
|
||||
<Icon name='lightning'/> Flash Device
|
||||
</Button>
|
||||
{offsetsValid && flashEtaText &&
|
||||
<span {...t} style={{marginLeft: '1em', opacity: 0.8}}>
|
||||
Estimated time: ~{flashEtaText} at {baudrate.toLocaleString()} baud
|
||||
</span>}
|
||||
{files.length > 0 && !offsetsValid &&
|
||||
<p {...t} style={{marginTop: '0.5em', opacity: 0.8}}>
|
||||
Every firmware file needs a valid hex flash offset (e.g. <code>0x0</code> or{' '}
|
||||
<code>0x10000</code>).
|
||||
</p>}
|
||||
</Form>
|
||||
</Segment>
|
||||
|
||||
<Modal
|
||||
open={flashOpen}
|
||||
onClose={() => !flashing && setFlashOpen(false)}
|
||||
closeOnDimmerClick={!flashing}
|
||||
size='fullscreen'
|
||||
>
|
||||
<Modal.Header>{flashing ? 'Flashing device…' : 'Flash complete'}</Modal.Header>
|
||||
<Modal.Content scrolling>
|
||||
{progress !== null &&
|
||||
<Progress percent={progress.percent} progress indicating={flashing} autoSuccess>
|
||||
{flashing ? `Writing file ${progress.fileIndex + 1} of ${files.length}` : 'Done'}
|
||||
</Progress>}
|
||||
{flashing && flashEtaText &&
|
||||
<p {...t} style={{opacity: 0.8}}>
|
||||
Estimated total time: ~{flashEtaText} at {baudrate.toLocaleString()} baud. Keep this tab
|
||||
open and do not unplug the device.
|
||||
</p>}
|
||||
<AutoScrollLog
|
||||
value={log || 'Starting…'}
|
||||
style={{fontFamily: 'monospace', width: '100%', minHeight: '60vh', whiteSpace: 'pre'}}
|
||||
/>
|
||||
</Modal.Content>
|
||||
<Modal.Actions>
|
||||
<Button onClick={() => setFlashOpen(false)} disabled={flashing}>Close</Button>
|
||||
</Modal.Actions>
|
||||
</Modal>
|
||||
|
||||
<Modal open={logOpen} onClose={() => setLogOpen(false)} size='fullscreen'>
|
||||
<Modal.Header>Flasher Log</Modal.Header>
|
||||
<Modal.Content scrolling>
|
||||
<AutoScrollLog
|
||||
value={log || 'No activity yet.'}
|
||||
style={{fontFamily: 'monospace', width: '100%', minHeight: '70vh', whiteSpace: 'pre'}}
|
||||
/>
|
||||
</Modal.Content>
|
||||
<Modal.Actions>
|
||||
<Button onClick={() => setLogOpen(false)}>Close</Button>
|
||||
</Modal.Actions>
|
||||
</Modal>
|
||||
</PageContainer>
|
||||
</div>;
|
||||
}
|
||||
|
||||
export function FlasherRoute() {
|
||||
return <Routes>
|
||||
<Route path='/' exact element={<FlasherPage/>}/>
|
||||
</Routes>;
|
||||
}
|
||||
299
app/src/components/Flasher.test.js
Normal file
299
app/src/components/Flasher.test.js
Normal file
|
|
@ -0,0 +1,299 @@
|
|||
import React from 'react';
|
||||
import {fireEvent, render, screen, waitFor} from '@testing-library/react';
|
||||
|
||||
// esptool-js ships untranspiled ESM which Jest will not transform; mock it so importing Flasher.js is safe.
|
||||
// Real classes (not jest.fn mock impls) so `new ESPLoader()` reliably yields an instance with main()/after().
|
||||
// The ESPLoader mock reports an ESP32-S2 so the connect/detect flow can be exercised.
|
||||
jest.mock('esptool-js', () => ({
|
||||
__esModule: true,
|
||||
ESPLoader: class {
|
||||
async main() {
|
||||
return 'ESP32-S2 (revision v0.0)';
|
||||
}
|
||||
|
||||
async after() {
|
||||
}
|
||||
},
|
||||
Transport: class {
|
||||
async disconnect() {
|
||||
}
|
||||
},
|
||||
}));
|
||||
|
||||
// Flasher fetches media firmware on mount; mock the API so tests don't hit the network.
|
||||
jest.mock('../api', () => ({
|
||||
filesSearch: jest.fn().mockResolvedValue([[], 0]),
|
||||
flasherSearch: jest.fn().mockResolvedValue([[], 0]),
|
||||
getFlasherConfigs: jest.fn().mockResolvedValue([]),
|
||||
saveFlasherConfig: jest.fn().mockResolvedValue(true),
|
||||
deleteFlasherConfig: jest.fn().mockResolvedValue(true),
|
||||
}));
|
||||
|
||||
import {filesSearch, flasherSearch, getFlasherConfigs} from '../api';
|
||||
import {
|
||||
chipFamily,
|
||||
estimateFlashSeconds,
|
||||
FlasherPage,
|
||||
humanDuration,
|
||||
isValidHexOffset,
|
||||
parseAddress,
|
||||
webSerialSupported,
|
||||
withTimeout,
|
||||
} from './Flasher';
|
||||
|
||||
describe('withTimeout', () => {
|
||||
it('resolves when the promise settles before the timeout', async () => {
|
||||
await expect(withTimeout(Promise.resolve('ok'), 50, 'too slow')).resolves.toBe('ok');
|
||||
});
|
||||
|
||||
it('rejects with the message when the promise stalls (e.g. a hung connect)', async () => {
|
||||
await expect(withTimeout(new Promise(() => {}), 10, 'too slow')).rejects.toThrow('too slow');
|
||||
});
|
||||
});
|
||||
|
||||
describe('estimateFlashSeconds', () => {
|
||||
it('estimates from total bytes and baud rate (8N1: baud/10 bytes/sec)', () => {
|
||||
// 115200 baud -> 11520 bytes/sec. 115200 bytes -> ~10s.
|
||||
expect(estimateFlashSeconds(115200, 115200)).toBeCloseTo(10, 5);
|
||||
// Faster baud -> proportionally less time.
|
||||
expect(estimateFlashSeconds(115200, 921600)).toBeCloseTo(1.25, 5);
|
||||
});
|
||||
|
||||
it('returns 0 for missing size or baud', () => {
|
||||
expect(estimateFlashSeconds(0, 115200)).toBe(0);
|
||||
expect(estimateFlashSeconds(1000, 0)).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('humanDuration', () => {
|
||||
it('formats seconds and minutes', () => {
|
||||
expect(humanDuration(45)).toBe('45s');
|
||||
expect(humanDuration(60)).toBe('1m 0s');
|
||||
expect(humanDuration(125)).toBe('2m 5s');
|
||||
});
|
||||
|
||||
it('returns null for non-positive or invalid input', () => {
|
||||
expect(humanDuration(0)).toBeNull();
|
||||
expect(humanDuration(-5)).toBeNull();
|
||||
expect(humanDuration(Infinity)).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('chipFamily', () => {
|
||||
it('extracts the chip family from an esptool-js description', () => {
|
||||
expect(chipFamily('ESP32-S2 (revision v0.0)')).toBe('ESP32-S2');
|
||||
expect(chipFamily('ESP32-S3')).toBe('ESP32-S3');
|
||||
expect(chipFamily('ESP32 (revision 3)')).toBe('ESP32');
|
||||
});
|
||||
|
||||
it('returns null for empty input', () => {
|
||||
expect(chipFamily('')).toBeNull();
|
||||
expect(chipFamily(null)).toBeNull();
|
||||
expect(chipFamily(undefined)).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('isValidHexOffset', () => {
|
||||
it('accepts 0x-prefixed hex strings', () => {
|
||||
expect(isValidHexOffset('0x0')).toBe(true);
|
||||
expect(isValidHexOffset('0x10000')).toBe(true);
|
||||
expect(isValidHexOffset('0XABCDEF')).toBe(true);
|
||||
expect(isValidHexOffset(' 0x8000 ')).toBe(true);
|
||||
});
|
||||
|
||||
it('rejects non-hex, un-prefixed, and empty values', () => {
|
||||
expect(isValidHexOffset('')).toBe(false);
|
||||
expect(isValidHexOffset(' ')).toBe(false);
|
||||
expect(isValidHexOffset('10000')).toBe(false); // missing 0x prefix
|
||||
expect(isValidHexOffset('0x')).toBe(false); // no digits
|
||||
expect(isValidHexOffset('0xZZ')).toBe(false); // not hex
|
||||
expect(isValidHexOffset('nope')).toBe(false);
|
||||
expect(isValidHexOffset('0x1000 extra')).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('parseAddress', () => {
|
||||
it('parses valid hex offsets', () => {
|
||||
expect(parseAddress('0x0')).toBe(0);
|
||||
expect(parseAddress('0x1000')).toBe(0x1000);
|
||||
expect(parseAddress('0X10000')).toBe(0x10000);
|
||||
expect(parseAddress(' 0x8000 ')).toBe(0x8000);
|
||||
});
|
||||
|
||||
it('rejects empty offsets', () => {
|
||||
expect(() => parseAddress('')).toThrow(/required/);
|
||||
expect(() => parseAddress(' ')).toThrow(/required/);
|
||||
});
|
||||
|
||||
it('rejects non-hex offsets', () => {
|
||||
expect(() => parseAddress('nope')).toThrow(/Invalid/);
|
||||
expect(() => parseAddress('0xZZ')).toThrow(/Invalid/);
|
||||
expect(() => parseAddress('65536')).toThrow(/Invalid/); // decimal is no longer accepted
|
||||
});
|
||||
});
|
||||
|
||||
describe('webSerialSupported', () => {
|
||||
const original = Object.getOwnPropertyDescriptor(global.navigator, 'serial');
|
||||
|
||||
afterEach(() => {
|
||||
if (original) {
|
||||
Object.defineProperty(global.navigator, 'serial', original);
|
||||
} else {
|
||||
delete global.navigator.serial;
|
||||
}
|
||||
});
|
||||
|
||||
it('is false when navigator.serial is missing', () => {
|
||||
delete global.navigator.serial;
|
||||
expect(webSerialSupported()).toBe(false);
|
||||
});
|
||||
|
||||
it('is true when navigator.serial is present', () => {
|
||||
Object.defineProperty(global.navigator, 'serial', {value: {}, configurable: true});
|
||||
expect(webSerialSupported()).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
// The firmware sources live behind three tabs; click a tab's menu item to reveal its pane. PageContainer renders
|
||||
// both breakpoints (fresnel Media), so the menu item appears twice — clicking the first is enough.
|
||||
function switchTab(name) {
|
||||
fireEvent.click(screen.getAllByText(name)[0]);
|
||||
}
|
||||
|
||||
describe('FlasherPage', () => {
|
||||
const original = Object.getOwnPropertyDescriptor(global.navigator, 'serial');
|
||||
|
||||
beforeEach(() => {
|
||||
filesSearch.mockClear();
|
||||
filesSearch.mockResolvedValue([[], 0]);
|
||||
flasherSearch.mockClear();
|
||||
flasherSearch.mockResolvedValue([[], 0]);
|
||||
getFlasherConfigs.mockClear();
|
||||
getFlasherConfigs.mockResolvedValue([]);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
if (original) {
|
||||
Object.defineProperty(global.navigator, 'serial', original);
|
||||
} else {
|
||||
delete global.navigator.serial;
|
||||
}
|
||||
});
|
||||
|
||||
// PageContainer renders both the mobile and desktop breakpoints (fresnel Media), so each label appears twice.
|
||||
it('warns when Web Serial is unavailable', () => {
|
||||
delete global.navigator.serial;
|
||||
render(<FlasherPage/>);
|
||||
expect(screen.getAllByText('Web Serial is not available').length).toBeGreaterThan(0);
|
||||
// The flashing controls must not render on an unsupported browser.
|
||||
expect(screen.queryByText('Connect Device')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders the flasher controls when Web Serial is available', () => {
|
||||
Object.defineProperty(global.navigator, 'serial', {value: {}, configurable: true});
|
||||
render(<FlasherPage/>);
|
||||
expect(screen.getAllByText('Connect Device').length).toBeGreaterThan(0);
|
||||
// "Add from computer" is now a non-default tab; switch to it to reveal the dropzone.
|
||||
switchTab('Add from computer');
|
||||
expect(screen.getAllByText(/Click here/).length).toBeGreaterThan(0);
|
||||
// Flash button is disabled until a device is connected and a file is added.
|
||||
expect(screen.getAllByText('Flash Device')[0].closest('button')).toBeDisabled();
|
||||
});
|
||||
|
||||
it('fetches media firmware by suffix on load and lists results', async () => {
|
||||
Object.defineProperty(global.navigator, 'serial', {value: {}, configurable: true});
|
||||
filesSearch.mockResolvedValue([[
|
||||
{primary_path: 'software/MALVEKE.ino.bin', name: 'MALVEKE.ino.bin', size: 1024},
|
||||
], 1]);
|
||||
render(<FlasherPage/>);
|
||||
// Media firmware is fetched on mount filtered to the .bin suffix (the `suffix` positional arg).
|
||||
await waitFor(() => expect(filesSearch).toHaveBeenCalled());
|
||||
const call = filesSearch.mock.calls[0];
|
||||
// filesSearch(offset, limit, searchStr, mimetypes, model, tagNames, headline, months, fromYear, toYear,
|
||||
// anyTag, order, suffix, path)
|
||||
expect(call[12]).toBe('.bin');
|
||||
// The result is listed for the user to add, under the "Choose from your WROLPi" tab.
|
||||
switchTab('Choose from your WROLPi');
|
||||
expect((await screen.findAllByText('MALVEKE.ino.bin')).length).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it('offers the detect-device filter button', () => {
|
||||
Object.defineProperty(global.navigator, 'serial', {value: {}, configurable: true});
|
||||
render(<FlasherPage/>);
|
||||
switchTab('Choose from your WROLPi');
|
||||
expect(screen.getAllByText('Filter files by detecting device').length).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it('lists saved firmware configurations fetched on load', async () => {
|
||||
Object.defineProperty(global.navigator, 'serial', {value: {}, configurable: true});
|
||||
getFlasherConfigs.mockResolvedValue([
|
||||
{name: 'T-Deck MUI', erase_all: true, files: [{path: 'a.bin', address: '0x0'}]},
|
||||
]);
|
||||
render(<FlasherPage/>);
|
||||
await waitFor(() => expect(getFlasherConfigs).toHaveBeenCalled());
|
||||
// "Saved Firmwares" is always visible as a tab label; its contents appear once the tab is active.
|
||||
expect((await screen.findAllByText('Saved Firmwares')).length).toBeGreaterThan(0);
|
||||
switchTab('Saved Firmwares');
|
||||
expect((await screen.findAllByText('T-Deck MUI')).length).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it('reminds the user about boot/download mode when connecting fails', async () => {
|
||||
// A non-cancel connect failure (e.g. board not in download mode) should surface the reminder.
|
||||
Object.defineProperty(global.navigator, 'serial',
|
||||
{value: {requestPort: jest.fn().mockRejectedValue(new Error('Failed to connect'))}, configurable: true});
|
||||
render(<FlasherPage/>);
|
||||
fireEvent.click(screen.getAllByText('Connect Device')[0].closest('button'));
|
||||
expect((await screen.findAllByText(/download mode/i)).length).toBeGreaterThan(0);
|
||||
expect((await screen.findAllByText(/Could not connect to the device/i)).length).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it('does not show the boot-mode reminder when the user cancels the port picker', async () => {
|
||||
// Cancelling the browser picker throws NotFoundError, which is not a real failure.
|
||||
const notFound = Object.assign(new Error('No port selected'), {name: 'NotFoundError'});
|
||||
Object.defineProperty(global.navigator, 'serial',
|
||||
{value: {requestPort: jest.fn().mockRejectedValue(notFound)}, configurable: true});
|
||||
render(<FlasherPage/>);
|
||||
fireEvent.click(screen.getAllByText('Connect Device')[0].closest('button'));
|
||||
await waitFor(() => expect(navigator.serial.requestPort).toHaveBeenCalled());
|
||||
expect(screen.queryByText(/download mode/i)).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('detects the device and filters firmware by its chip', async () => {
|
||||
Object.defineProperty(global.navigator, 'serial',
|
||||
{value: {requestPort: jest.fn().mockResolvedValue({})}, configurable: true});
|
||||
flasherSearch.mockResolvedValue([[
|
||||
{primary_path: 'software/s2.bin', name: 's2.bin', size: 1024, esp_chip: 'ESP32-S2', esp_kind: 'app'},
|
||||
], 1]);
|
||||
|
||||
render(<FlasherPage/>);
|
||||
switchTab('Choose from your WROLPi');
|
||||
fireEvent.click(screen.getAllByText('Filter files by detecting device')[0].closest('button'));
|
||||
|
||||
// The detected chip (ESP32-S2, parsed from the esptool description) is used to filter firmware.
|
||||
await waitFor(() => expect(flasherSearch).toHaveBeenCalledWith('ESP32-S2', null));
|
||||
// The active filter is shown, and only the matching firmware is listed.
|
||||
expect((await screen.findAllByText('ESP32-S2', {exact: false})).length).toBeGreaterThan(0);
|
||||
expect((await screen.findAllByText('s2.bin')).length).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it('adds dropped .bin files and switches to the Add-from-computer tab', async () => {
|
||||
Object.defineProperty(global.navigator, 'serial', {value: {}, configurable: true});
|
||||
render(<FlasherPage/>);
|
||||
|
||||
// Default tab is "Saved Firmwares"; the computer dropzone is not shown yet.
|
||||
expect(screen.queryByText(/Click here/)).not.toBeInTheDocument();
|
||||
|
||||
const binFile = new File([new Uint8Array([0xe9, 0, 0])], 'dropped.bin');
|
||||
const txtFile = new File(['nope'], 'notes.txt');
|
||||
// The dropzone root wraps the whole page; a drop on any descendant bubbles up to it. react-dropzone
|
||||
// requires dataTransfer.types to include 'Files' before it reads the dropped files.
|
||||
const target = screen.getAllByText('1. Firmware files')[0];
|
||||
fireEvent.drop(target, {dataTransfer: {files: [binFile, txtFile], types: ['Files']}});
|
||||
|
||||
// The .bin is added (shown in the selected-firmware table) and the .txt is ignored.
|
||||
expect((await screen.findAllByText('dropped.bin')).length).toBeGreaterThan(0);
|
||||
expect(screen.queryByText('notes.txt')).not.toBeInTheDocument();
|
||||
// The drop switches to the "Add from computer" tab, revealing its dropzone.
|
||||
expect(screen.getAllByText(/Click here/).length).toBeGreaterThan(0);
|
||||
});
|
||||
});
|
||||
|
|
@ -56,6 +56,7 @@ const allLinks = [
|
|||
{text: 'Playlists', to: '/playlists', key: 'playlists'},
|
||||
{text: 'Zim', to: '/zim', key: 'zim'},
|
||||
{text: 'Inventory', to: '/inventory', key: 'inventory'},
|
||||
{text: 'Flasher', to: '/flasher', key: 'flasher'},
|
||||
{to: '/more/otp', text: 'One Time Pad', key: 'otp', end: true},
|
||||
{to: '/more/vin', text: 'VIN Decoder', key: 'vin', end: true},
|
||||
{to: '/more/calculators', text: 'Calculators', key: 'calculators', end: true},
|
||||
|
|
|
|||
0
modules/flasher/__init__.py
Normal file
0
modules/flasher/__init__.py
Normal file
55
modules/flasher/api.py
Normal file
55
modules/flasher/api.py
Normal file
|
|
@ -0,0 +1,55 @@
|
|||
import asyncio
|
||||
from http import HTTPStatus
|
||||
from urllib.parse import unquote
|
||||
|
||||
from sanic import Blueprint, Request, response
|
||||
from sanic_ext import validate
|
||||
from sanic_ext.extensions.openapi import openapi
|
||||
|
||||
from modules.flasher import lib, schema
|
||||
from modules.flasher.config import get_flasher_config
|
||||
from wrolpi.api_utils import json_response
|
||||
|
||||
flasher_bp = Blueprint('Flasher', '/api/flasher')
|
||||
|
||||
|
||||
@flasher_bp.post('/search')
|
||||
@openapi.definition(
|
||||
summary='Search .bin firmware and filter to ESP images (optionally for a specific chip)',
|
||||
body=schema.FlasherSearchRequest,
|
||||
)
|
||||
@validate(schema.FlasherSearchRequest)
|
||||
async def post_flasher_search(_: Request, body: schema.FlasherSearchRequest):
|
||||
# Reading many firmware headers touches the disk; run off the event loop.
|
||||
file_groups, total = await asyncio.to_thread(
|
||||
lib.search_esp_firmware, body.chip, body.path, body.limit)
|
||||
return json_response(dict(file_groups=file_groups, totals=dict(file_groups=total)), HTTPStatus.OK)
|
||||
|
||||
|
||||
@flasher_bp.get('/configs')
|
||||
@openapi.definition(summary='List saved firmware flashing configurations')
|
||||
async def get_flasher_configs(_: Request):
|
||||
return json_response(dict(configurations=get_flasher_config().configurations), HTTPStatus.OK)
|
||||
|
||||
|
||||
@flasher_bp.post('/configs')
|
||||
@openapi.definition(
|
||||
summary='Save (add or replace by name) a firmware flashing configuration',
|
||||
body=schema.FlasherSaveConfigRequest,
|
||||
)
|
||||
@validate(schema.FlasherSaveConfigRequest)
|
||||
async def save_flasher_config(_: Request, body: schema.FlasherSaveConfigRequest):
|
||||
try:
|
||||
configuration = get_flasher_config().save_configuration(body.name, body.files, body.erase_all)
|
||||
except ValueError as e:
|
||||
return response.json({'error': str(e)}, HTTPStatus.BAD_REQUEST)
|
||||
return json_response(dict(configuration=configuration), HTTPStatus.CREATED)
|
||||
|
||||
|
||||
@flasher_bp.delete('/configs/<name:str>')
|
||||
@openapi.definition(summary='Delete a saved firmware flashing configuration by name')
|
||||
async def delete_flasher_config(_: Request, name: str):
|
||||
name = unquote(name)
|
||||
if get_flasher_config().delete_configuration(name):
|
||||
return response.empty()
|
||||
return response.json({'error': f'No saved configuration named {name!r}'}, HTTPStatus.NOT_FOUND)
|
||||
86
modules/flasher/config.py
Normal file
86
modules/flasher/config.py
Normal file
|
|
@ -0,0 +1,86 @@
|
|||
"""A YAML config storing the user's saved firmware flashing configurations.
|
||||
|
||||
Each saved configuration is a named set of firmware files (media-relative paths) and their flash offsets, plus
|
||||
whether to erase the flash first. This lets a user configure a multi-part flash once (e.g. a Meshtastic T-Deck:
|
||||
firmware at 0x0, littlefs at 0xc90000) and re-load it later with one click.
|
||||
"""
|
||||
from dataclasses import dataclass, field
|
||||
from typing import List
|
||||
|
||||
from wrolpi.common import ConfigFile, logger
|
||||
|
||||
logger = logger.getChild(__name__)
|
||||
|
||||
|
||||
@dataclass
|
||||
class FlasherConfigValidator:
|
||||
version: int = None
|
||||
configurations: list = field(default_factory=list)
|
||||
|
||||
|
||||
class FlasherConfig(ConfigFile):
|
||||
file_name = 'flasher.yaml'
|
||||
default_config = dict(
|
||||
version=0,
|
||||
configurations=[],
|
||||
)
|
||||
validator = FlasherConfigValidator
|
||||
|
||||
def import_config(self, file=None, send_events=False):
|
||||
super().import_config(file, send_events)
|
||||
# YAML-only config (no database); a successful read is a successful import.
|
||||
self.successful_import = True
|
||||
|
||||
@property
|
||||
def configurations(self) -> List[dict]:
|
||||
return list(self._config.get('configurations', []))
|
||||
|
||||
@configurations.setter
|
||||
def configurations(self, value: List[dict]):
|
||||
# ConfigFile.update() validates, stores, and triggers a background save.
|
||||
self.update({'configurations': value})
|
||||
|
||||
def save_configuration(self, name: str, files: List[dict], erase_all: bool = False) -> dict:
|
||||
"""Add or replace (by name) a saved configuration. Returns the stored configuration."""
|
||||
name = (name or '').strip()
|
||||
if not name:
|
||||
raise ValueError('Configuration name is required')
|
||||
# Keep only the fields we persist for each file.
|
||||
stored_files = [
|
||||
dict(
|
||||
path=f.get('path'),
|
||||
address=f.get('address'),
|
||||
name=f.get('name'),
|
||||
size=f.get('size'),
|
||||
)
|
||||
for f in files
|
||||
]
|
||||
configuration = dict(name=name, erase_all=bool(erase_all), files=stored_files)
|
||||
# Replace any existing configuration with the same name, then keep the list sorted by name.
|
||||
configurations = [c for c in self.configurations if c.get('name') != name]
|
||||
configurations.append(configuration)
|
||||
configurations.sort(key=lambda c: (c.get('name') or '').lower())
|
||||
self.configurations = configurations
|
||||
return configuration
|
||||
|
||||
def delete_configuration(self, name: str) -> bool:
|
||||
"""Delete a saved configuration by name. Returns True if one was removed."""
|
||||
configurations = self.configurations
|
||||
remaining = [c for c in configurations if c.get('name') != name]
|
||||
if len(remaining) == len(configurations):
|
||||
return False
|
||||
self.configurations = remaining
|
||||
return True
|
||||
|
||||
|
||||
FLASHER_CONFIG: FlasherConfig = FlasherConfig()
|
||||
|
||||
# Test override (see get_flasher_config).
|
||||
TEST_FLASHER_CONFIG = None
|
||||
|
||||
|
||||
def get_flasher_config() -> FlasherConfig:
|
||||
global TEST_FLASHER_CONFIG
|
||||
if isinstance(TEST_FLASHER_CONFIG, ConfigFile):
|
||||
return TEST_FLASHER_CONFIG
|
||||
return FLASHER_CONFIG
|
||||
71
modules/flasher/conftest.py
Normal file
71
modules/flasher/conftest.py
Normal file
|
|
@ -0,0 +1,71 @@
|
|||
import struct
|
||||
|
||||
import pytest
|
||||
|
||||
from modules.flasher.lib import ESP_IMAGE_MAGIC, APP_DESC_MAGIC, PARTITION_TABLE_MAGIC, read_esp_image_info
|
||||
|
||||
|
||||
def build_esp_image(chip_id: int = 0x0000, kind: str = 'app', size: int = 2048) -> bytes:
|
||||
"""Build a byte string with a realistic ESP image header for testing.
|
||||
|
||||
The bytes are padded with 0xFF (like real flash) and contain the magic numbers at the offsets the flasher
|
||||
inspects, so tests exercise the same detection path as real firmware.
|
||||
|
||||
@param chip_id: The value written to the extended image header (offset 0x0C). See ESP_CHIP_IDS.
|
||||
@param kind: One of:
|
||||
- 'app': application image (header + esp_app_desc magic at 0x20).
|
||||
- 'factory': full merged image, ESP32-S3/C3 style (bootloader header at 0x0, partition table at 0x8000).
|
||||
- 'factory_s2': full merged image, ESP32/ESP32-S2 style (padding, bootloader header at 0x1000, PT at 0x8000).
|
||||
- 'bootloader': a bare second-stage bootloader (header at 0x0, no app descriptor, no partition table).
|
||||
- 'not_esp': not an ESP image at all (no 0xE9 magic).
|
||||
"""
|
||||
needs_partition_table = kind in ('factory', 'factory_s2')
|
||||
if needs_partition_table:
|
||||
size = max(size, 0x8100)
|
||||
|
||||
if kind == 'not_esp':
|
||||
# Realistic non-ESP binary (e.g. a filesystem image or game data): varied bytes so it is detected as
|
||||
# binary, not text. A uniform 0xFF fill is misdetected as text/plain by libmagic and breaks indexing.
|
||||
return bytes((i * 7 + 13) & 0xFF for i in range(size))
|
||||
|
||||
# ESP images pad gaps with 0xFF like real flash; the image header makes them detect as binary.
|
||||
data = bytearray(b'\xff' * size)
|
||||
|
||||
def write_image_header(base: int):
|
||||
data[base] = ESP_IMAGE_MAGIC
|
||||
data[base + 1] = 0x03 # segment_count
|
||||
data[base + 2] = 0x02 # spi_mode (dio)
|
||||
data[base + 3] = 0x2f # spi_speed/size
|
||||
# entry_addr (4..7) left as 0xFF; chip_id is a uint16 little-endian at base + 0x0C.
|
||||
struct.pack_into('<H', data, base + 0x0C, chip_id)
|
||||
|
||||
header_base = 0x1000 if kind == 'factory_s2' else 0x0
|
||||
write_image_header(header_base)
|
||||
|
||||
if kind == 'app':
|
||||
# esp_app_desc magic follows the image + first segment header at 0x20.
|
||||
struct.pack_into('<I', data, 0x20, APP_DESC_MAGIC)
|
||||
elif needs_partition_table:
|
||||
# A full/merged image has the partition table at flash offset 0x8000.
|
||||
data[0x8000] = PARTITION_TABLE_MAGIC[0]
|
||||
data[0x8001] = PARTITION_TABLE_MAGIC[1]
|
||||
|
||||
return bytes(data)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def make_esp_image(test_directory):
|
||||
"""Write a semi-real ESP firmware .bin (with correct header magic numbers) into the media directory.
|
||||
|
||||
Usage: ``make_esp_image('software/fw.bin', chip_id=0x0002, kind='app')`` -> returns the created Path.
|
||||
"""
|
||||
# The header reader is lru_cached; clear it so a reused path can't return a stale result across tests.
|
||||
read_esp_image_info.cache_clear()
|
||||
|
||||
def _make(relative_path: str, chip_id: int = 0x0000, kind: str = 'app', size: int = 2048):
|
||||
path = test_directory / relative_path
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_bytes(build_esp_image(chip_id=chip_id, kind=kind, size=size))
|
||||
return path
|
||||
|
||||
return _make
|
||||
129
modules/flasher/lib.py
Normal file
129
modules/flasher/lib.py
Normal file
|
|
@ -0,0 +1,129 @@
|
|||
"""Inspect ESP firmware images so the Flasher can filter files by the connected device's chip.
|
||||
|
||||
An Espressif firmware image begins with a one-byte magic (0xE9) followed by an image header. The extended
|
||||
header records which chip the image was built for (``chip_id`` at offset 0x0C). We read only the first few KB
|
||||
of a file to determine its target chip and what kind of image it is, without loading the whole firmware.
|
||||
"""
|
||||
import functools
|
||||
import pathlib
|
||||
from typing import List, Optional, Tuple
|
||||
|
||||
from wrolpi.common import get_media_directory, logger
|
||||
|
||||
logger = logger.getChild(__name__)
|
||||
|
||||
# esptool ``chip_id`` (extended image header, offset 0x0C) -> chip name. Names match esptool-js so the value
|
||||
# reported by the browser after connecting can be compared directly.
|
||||
ESP_CHIP_IDS = {
|
||||
0x0000: 'ESP32',
|
||||
0x0002: 'ESP32-S2',
|
||||
0x0005: 'ESP32-C3',
|
||||
0x0009: 'ESP32-S3',
|
||||
0x000C: 'ESP32-C2',
|
||||
0x000D: 'ESP32-C6',
|
||||
0x0010: 'ESP32-H2',
|
||||
0x0011: 'ESP32-C5',
|
||||
0x0012: 'ESP32-P4',
|
||||
}
|
||||
|
||||
ESP_IMAGE_MAGIC = 0xE9 # First byte of an ESP image header (app or bootloader).
|
||||
APP_DESC_MAGIC = 0xABCD5432 # esp_app_desc_t magic, sits at 0x20 in an application image.
|
||||
PARTITION_TABLE_MAGIC = (0xAA, 0x50) # First two bytes of a partition-table entry, always at flash offset 0x8000.
|
||||
|
||||
# Read enough to cover: an app/bootloader header at 0x0, the ESP32/ESP32-S2 "factory" bootloader at 0x1000, and
|
||||
# the partition table at 0x8000 (which distinguishes a full/merged "factory" image from a bare app or bootloader).
|
||||
_HEADER_READ_SIZE = 0x8100
|
||||
|
||||
|
||||
def _u16(data: bytes, offset: int) -> int:
|
||||
return data[offset] | (data[offset + 1] << 8)
|
||||
|
||||
|
||||
def _u32(data: bytes, offset: int) -> int:
|
||||
return data[offset] | (data[offset + 1] << 8) | (data[offset + 2] << 16) | (data[offset + 3] << 24)
|
||||
|
||||
|
||||
@functools.lru_cache(maxsize=10_000)
|
||||
def read_esp_image_info(path: pathlib.Path) -> dict:
|
||||
"""Read an ESP firmware image's header to determine its target chip and kind.
|
||||
|
||||
Returns a dict: ``{'is_esp_image': bool, 'chip': str|None, 'chip_id': int|None, 'kind': str}`` where ``kind``
|
||||
is one of ``app`` (application image), ``factory`` (full flashable image with a partition table),
|
||||
``bootloader`` (a bare second-stage bootloader), or ``not_esp_image``.
|
||||
|
||||
Only the first few KB of the file are read. Cached because firmware files are immutable in practice and this
|
||||
is called for many files per request.
|
||||
"""
|
||||
result = dict(is_esp_image=False, chip=None, chip_id=None, kind='not_esp_image')
|
||||
try:
|
||||
with open(path, 'rb') as fh:
|
||||
head = fh.read(_HEADER_READ_SIZE)
|
||||
except OSError as e:
|
||||
logger.debug(f'Could not read firmware header from {path}: {e}')
|
||||
return result
|
||||
|
||||
# The image header is at 0x0 for an app/bootloader (and for factory images on chips whose bootloader lives
|
||||
# at 0x0, e.g. ESP32-S3/C3). On the ESP32 and ESP32-S2 a "factory" merged image pads 0x0..0x1000 and puts
|
||||
# the bootloader header at 0x1000.
|
||||
base = None
|
||||
if len(head) > 0x0D and head[0] == ESP_IMAGE_MAGIC:
|
||||
base = 0x0
|
||||
elif len(head) > 0x100D and head[0x1000] == ESP_IMAGE_MAGIC:
|
||||
base = 0x1000
|
||||
if base is None:
|
||||
return result
|
||||
|
||||
chip_id = _u16(head, base + 0x0C)
|
||||
result['is_esp_image'] = True
|
||||
result['chip_id'] = chip_id
|
||||
result['chip'] = ESP_CHIP_IDS.get(chip_id)
|
||||
|
||||
# An application image carries the esp_app_desc magic right after its header (only true for app-only images;
|
||||
# in a factory image offset 0x20 is bootloader/padding). A full/merged image instead has the partition
|
||||
# table at 0x8000. Check app-desc first so a coincidental byte pattern at 0x8000 can't mislabel an app.
|
||||
has_app_desc = len(head) >= 0x24 and _u32(head, 0x20) == APP_DESC_MAGIC
|
||||
has_partition_table = (len(head) >= 0x8002
|
||||
and head[0x8000] == PARTITION_TABLE_MAGIC[0]
|
||||
and head[0x8001] == PARTITION_TABLE_MAGIC[1])
|
||||
if has_app_desc:
|
||||
result['kind'] = 'app'
|
||||
elif has_partition_table:
|
||||
result['kind'] = 'factory'
|
||||
else:
|
||||
result['kind'] = 'bootloader'
|
||||
return result
|
||||
|
||||
|
||||
def _resolve_media_path(primary_path) -> pathlib.Path:
|
||||
"""Resolve a search result's primary_path (relative or absolute) to an absolute path on disk."""
|
||||
path = pathlib.Path(primary_path)
|
||||
return path if path.is_absolute() else get_media_directory() / path
|
||||
|
||||
|
||||
def search_esp_firmware(chip: Optional[str] = None, path: Optional[str] = None,
|
||||
limit: int = 1000) -> Tuple[List[dict], int]:
|
||||
"""Search for ``.bin`` firmware and return only ESP images, annotated with their detected chip/kind.
|
||||
|
||||
@param chip: If provided, only return images built for this chip (e.g. "ESP32-S2").
|
||||
@param path: Case-insensitive partial match against the file path (same as file search).
|
||||
@param limit: Maximum number of candidate .bin files to inspect.
|
||||
"""
|
||||
from wrolpi.files.lib import search_files
|
||||
|
||||
file_groups, _ = search_files(None, limit, 0, suffix='.bin', path=path)
|
||||
|
||||
results = []
|
||||
for file_group in file_groups:
|
||||
info = read_esp_image_info(_resolve_media_path(file_group['primary_path']))
|
||||
if not info['is_esp_image']:
|
||||
# Skip non-ESP .bin files (filesystem images, game installers, STM32 firmware, etc.).
|
||||
continue
|
||||
if chip and info['chip'] != chip:
|
||||
continue
|
||||
results.append({
|
||||
**file_group,
|
||||
'esp_chip': info['chip'],
|
||||
'esp_chip_id': info['chip_id'],
|
||||
'esp_kind': info['kind'],
|
||||
})
|
||||
return results, len(results)
|
||||
20
modules/flasher/schema.py
Normal file
20
modules/flasher/schema.py
Normal file
|
|
@ -0,0 +1,20 @@
|
|||
from dataclasses import dataclass, field
|
||||
from typing import List, Optional
|
||||
|
||||
|
||||
@dataclass
|
||||
class FlasherSearchRequest:
|
||||
# Only return firmware built for this chip (e.g. "ESP32-S2"). Null returns all ESP firmware.
|
||||
chip: Optional[str] = None
|
||||
# Case-insensitive partial match against the file path.
|
||||
path: Optional[str] = None
|
||||
limit: Optional[int] = 1000
|
||||
|
||||
|
||||
@dataclass
|
||||
class FlasherSaveConfigRequest:
|
||||
# The name of the saved configuration (added, or replaced if the name already exists).
|
||||
name: str
|
||||
# The firmware files to flash: [{path, address, name, size}, ...].
|
||||
files: List[dict] = field(default_factory=list)
|
||||
erase_all: bool = False
|
||||
0
modules/flasher/test/__init__.py
Normal file
0
modules/flasher/test/__init__.py
Normal file
156
modules/flasher/test/test_flasher.py
Normal file
156
modules/flasher/test/test_flasher.py
Normal file
|
|
@ -0,0 +1,156 @@
|
|||
import pathlib
|
||||
from http import HTTPStatus
|
||||
|
||||
import pytest
|
||||
|
||||
from modules.flasher.lib import read_esp_image_info, search_esp_firmware
|
||||
|
||||
|
||||
@pytest.mark.parametrize('chip_id,kind,expected_chip,expected_kind', [
|
||||
(0x0000, 'app', 'ESP32', 'app'),
|
||||
(0x0002, 'app', 'ESP32-S2', 'app'),
|
||||
(0x0009, 'app', 'ESP32-S3', 'app'),
|
||||
(0x0005, 'app', 'ESP32-C3', 'app'),
|
||||
(0x000D, 'app', 'ESP32-C6', 'app'),
|
||||
(0x0000, 'factory_s2', 'ESP32', 'factory'), # ESP32/S2 layout: bootloader at 0x1000
|
||||
(0x0009, 'factory', 'ESP32-S3', 'factory'), # S3 layout: bootloader at 0x0, partition table at 0x8000
|
||||
(0x0000, 'bootloader', 'ESP32', 'bootloader'),
|
||||
])
|
||||
def test_read_esp_image_info(make_esp_image, chip_id, kind, expected_chip, expected_kind):
|
||||
"""The header reader identifies the target chip and image kind from realistic header bytes."""
|
||||
path = make_esp_image('software/fw.bin', chip_id=chip_id, kind=kind)
|
||||
info = read_esp_image_info(path)
|
||||
assert info['is_esp_image'] is True
|
||||
assert info['chip'] == expected_chip
|
||||
assert info['chip_id'] == chip_id
|
||||
assert info['kind'] == expected_kind
|
||||
|
||||
|
||||
def test_read_esp_image_info_not_esp(make_esp_image):
|
||||
"""A .bin that is not an ESP image (no 0xE9 magic) is reported as such."""
|
||||
path = make_esp_image('software/data.bin', kind='not_esp')
|
||||
info = read_esp_image_info(path)
|
||||
assert info == dict(is_esp_image=False, chip=None, chip_id=None, kind='not_esp_image')
|
||||
|
||||
|
||||
def test_read_esp_image_info_unknown_chip(make_esp_image):
|
||||
"""An ESP image with an unrecognized chip_id is still detected as an image, with chip=None."""
|
||||
path = make_esp_image('software/fw.bin', chip_id=0x7777, kind='app')
|
||||
info = read_esp_image_info(path)
|
||||
assert info['is_esp_image'] is True
|
||||
assert info['chip'] is None
|
||||
assert info['chip_id'] == 0x7777
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_search_esp_firmware_filters_by_chip(async_client, test_session, make_esp_image, refresh_files):
|
||||
"""search_esp_firmware returns only ESP images matching the requested chip, annotated with chip/kind."""
|
||||
make_esp_image('software/esp32-app.bin', chip_id=0x0000, kind='app')
|
||||
make_esp_image('software/s2-app.bin', chip_id=0x0002, kind='app')
|
||||
make_esp_image('software/s3-factory.bin', chip_id=0x0009, kind='factory')
|
||||
make_esp_image('software/s3-app.bin', chip_id=0x0009, kind='app')
|
||||
# A non-ESP .bin (e.g. a filesystem image or game installer) must never be returned.
|
||||
make_esp_image('software/littlefs.bin', kind='not_esp')
|
||||
|
||||
await refresh_files()
|
||||
|
||||
def names(results):
|
||||
# search_esp_firmware (lib layer) returns primary_path as an absolute Path; compare by basename.
|
||||
return sorted(pathlib.Path(r['primary_path']).name for r in results)
|
||||
|
||||
# Filter to ESP32-S3: only the two S3 images, never the non-ESP file.
|
||||
s3, total = search_esp_firmware(chip='ESP32-S3')
|
||||
assert total == 2
|
||||
assert names(s3) == ['s3-app.bin', 's3-factory.bin']
|
||||
assert {r['esp_chip'] for r in s3} == {'ESP32-S3'}
|
||||
assert {r['esp_kind'] for r in s3} == {'app', 'factory'}
|
||||
|
||||
# Filter to ESP32-S2: just the one.
|
||||
s2, total = search_esp_firmware(chip='ESP32-S2')
|
||||
assert total == 1
|
||||
assert names(s2) == ['s2-app.bin']
|
||||
|
||||
# No chip: all ESP images, excluding the non-ESP .bin.
|
||||
all_esp, total = search_esp_firmware()
|
||||
assert total == 4
|
||||
assert 'littlefs.bin' not in names(all_esp)
|
||||
|
||||
# A chip with no matching firmware returns nothing.
|
||||
_, total = search_esp_firmware(chip='ESP32-H2')
|
||||
assert total == 0
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_flasher_search_api(async_client, test_session, make_esp_image, refresh_files):
|
||||
"""The /api/flasher/search endpoint filters by chip and supports the path filter."""
|
||||
make_esp_image('software/marauder/esp32.bin', chip_id=0x0000, kind='app')
|
||||
make_esp_image('software/marauder/s3.bin', chip_id=0x0009, kind='app')
|
||||
make_esp_image('software/other/s3.bin', chip_id=0x0009, kind='app')
|
||||
|
||||
await refresh_files()
|
||||
|
||||
# Filter by chip.
|
||||
request, response = await async_client.post('/api/flasher/search', json=dict(chip='ESP32-S3'))
|
||||
assert response.status_code == HTTPStatus.OK
|
||||
got = sorted(fg['primary_path'] for fg in response.json['file_groups'])
|
||||
assert got == ['software/marauder/s3.bin', 'software/other/s3.bin']
|
||||
assert response.json['totals']['file_groups'] == 2
|
||||
|
||||
# Filter by chip AND path (the flasher's detect + folder filter combined).
|
||||
request, response = await async_client.post('/api/flasher/search',
|
||||
json=dict(chip='ESP32-S3', path='marauder'))
|
||||
assert response.status_code == HTTPStatus.OK
|
||||
got = [fg['primary_path'] for fg in response.json['file_groups']]
|
||||
assert got == ['software/marauder/s3.bin']
|
||||
assert response.json['file_groups'][0]['esp_chip'] == 'ESP32-S3'
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_flasher_saved_configs_api(async_client, test_session, test_directory):
|
||||
"""Saved firmware configurations can be created, listed, replaced, deleted, and are persisted to YAML."""
|
||||
# Initially empty.
|
||||
request, response = await async_client.get('/api/flasher/configs')
|
||||
assert response.status_code == HTTPStatus.OK
|
||||
assert response.json['configurations'] == []
|
||||
|
||||
# Save a multi-part configuration (like a Meshtastic T-Deck).
|
||||
body = dict(name='T-Deck MUI', erase_all=True, files=[
|
||||
dict(path='software/firmware-t-deck-tft.bin', address='0x0', name='firmware-t-deck-tft.bin', size=100),
|
||||
dict(path='software/littlefs-t-deck-tft.bin', address='0xc90000', name='littlefs-t-deck-tft.bin', size=200),
|
||||
])
|
||||
request, response = await async_client.post('/api/flasher/configs', json=body)
|
||||
assert response.status_code == HTTPStatus.CREATED
|
||||
|
||||
# It is listed with its files and offsets.
|
||||
request, response = await async_client.get('/api/flasher/configs')
|
||||
configs = response.json['configurations']
|
||||
assert len(configs) == 1
|
||||
assert configs[0]['name'] == 'T-Deck MUI'
|
||||
assert configs[0]['erase_all'] is True
|
||||
assert [f['address'] for f in configs[0]['files']] == ['0x0', '0xc90000']
|
||||
|
||||
# It is persisted to flasher.yaml.
|
||||
assert (test_directory / 'config/flasher.yaml').is_file()
|
||||
|
||||
# Saving the same name replaces it (still one configuration).
|
||||
body2 = dict(name='T-Deck MUI', files=[dict(path='software/other.bin', address='0x0')])
|
||||
request, response = await async_client.post('/api/flasher/configs', json=body2)
|
||||
assert response.status_code == HTTPStatus.CREATED
|
||||
request, response = await async_client.get('/api/flasher/configs')
|
||||
configs = response.json['configurations']
|
||||
assert len(configs) == 1
|
||||
assert [f['path'] for f in configs[0]['files']] == ['software/other.bin']
|
||||
|
||||
# An empty name is rejected.
|
||||
request, response = await async_client.post('/api/flasher/configs', json=dict(name=' ', files=[]))
|
||||
assert response.status_code == HTTPStatus.BAD_REQUEST
|
||||
|
||||
# Delete it (name is URL-encoded).
|
||||
request, response = await async_client.delete('/api/flasher/configs/T-Deck%20MUI')
|
||||
assert response.status_code == HTTPStatus.NO_CONTENT
|
||||
request, response = await async_client.get('/api/flasher/configs')
|
||||
assert response.json['configurations'] == []
|
||||
|
||||
# Deleting a missing configuration 404s.
|
||||
request, response = await async_client.delete('/api/flasher/configs/nope')
|
||||
assert response.status_code == HTTPStatus.NOT_FOUND
|
||||
|
|
@ -1141,6 +1141,10 @@ def get_all_configs() -> Dict[str, ConfigFile]:
|
|||
if map_pins_config := get_map_pins_config():
|
||||
all_configs[map_pins_config.file_name] = map_pins_config
|
||||
|
||||
from modules.flasher.config import get_flasher_config
|
||||
if flasher_config := get_flasher_config():
|
||||
all_configs[flasher_config.file_name] = flasher_config
|
||||
|
||||
from wrolpi.collections.config import get_playlists_config
|
||||
if playlists_config := get_playlists_config():
|
||||
all_configs[playlists_config.file_name] = playlists_config
|
||||
|
|
@ -1238,6 +1242,16 @@ async def import_all_db_configs() -> dict[str, bool]:
|
|||
logger.warning(f'Failed to import map pins config: {e}')
|
||||
results['map_pins'] = False
|
||||
|
||||
# Flasher saved firmware configurations (YAML-only, no DB)
|
||||
try:
|
||||
from modules.flasher.config import get_flasher_config
|
||||
get_flasher_config().import_config()
|
||||
results['flasher'] = True
|
||||
logger.debug('flasher config imported')
|
||||
except Exception as e:
|
||||
logger.warning(f'Failed to import flasher config: {e}')
|
||||
results['flasher'] = False
|
||||
|
||||
return results
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -34,6 +34,7 @@ def attach_shared_contexts(app: Sanic):
|
|||
app.shared_ctx.archive_downloader_config = manager.dict()
|
||||
app.shared_ctx.download_cache_config = manager.dict()
|
||||
app.shared_ctx.map_pins_config = manager.dict()
|
||||
app.shared_ctx.flasher_config = manager.dict()
|
||||
# Shared dicts.
|
||||
app.shared_ctx.refresh = manager.dict()
|
||||
app.shared_ctx.uploaded_files = manager.dict()
|
||||
|
|
@ -277,3 +278,9 @@ def initialize_configs_contexts(app: Sanic):
|
|||
MAP_PINS_CONFIG.initialize(app.shared_ctx.map_pins_config)
|
||||
except Exception as e:
|
||||
logger.error(f'Failed to initialize in-memory map pins config: {e}')
|
||||
|
||||
try:
|
||||
from modules.flasher.config import FLASHER_CONFIG
|
||||
FLASHER_CONFIG.initialize(app.shared_ctx.flasher_config)
|
||||
except Exception as e:
|
||||
logger.error(f'Failed to initialize in-memory flasher config: {e}')
|
||||
|
|
|
|||
|
|
@ -165,7 +165,7 @@ async def post_search_files(_: Request, body: schema.FilesSearchRequest):
|
|||
with timer('Searching all files', 'info', logger__=logger):
|
||||
file_groups, total = lib.search_files(body.search_str, body.limit, body.offset, body.mimetypes, body.model,
|
||||
body.tag_names, body.headline, body.months, body.from_year, body.to_year,
|
||||
body.any_tag, body.order, body.url)
|
||||
body.any_tag, body.order, body.url, body.suffix, body.path)
|
||||
return json_response(dict(file_groups=file_groups, totals=dict(file_groups=total)))
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -700,7 +700,8 @@ def _upsert_files(files: List[pathlib.Path], idempotency: datetime.datetime,
|
|||
modification_datetime = from_timestamp(max(i.stat().st_mtime for i in group))
|
||||
size = sum(i.stat().st_size for i in group)
|
||||
files = json.dumps(_paths_to_files_dict(group))
|
||||
values[primary_path] = (modification_datetime, mimetype, size, files)
|
||||
suffix = (split_path_stem_and_suffix(primary_path)[1] or '').lower() or None
|
||||
values[primary_path] = (modification_datetime, mimetype, size, files, suffix)
|
||||
non_primary_files = {i for i in group if i != primary_path}
|
||||
except NoPrimaryFile:
|
||||
# Cannot find primary path, create a `file_group` for each file.
|
||||
|
|
@ -711,7 +712,8 @@ def _upsert_files(files: List[pathlib.Path], idempotency: datetime.datetime,
|
|||
modification_datetime = from_timestamp(primary_path.stat().st_mtime)
|
||||
size = primary_path.stat().st_size
|
||||
files = json.dumps(_paths_to_files_dict([primary_path]))
|
||||
values[primary_path] = (modification_datetime, mimetype, size, files)
|
||||
suffix = (split_path_stem_and_suffix(primary_path)[1] or '').lower() or None
|
||||
values[primary_path] = (modification_datetime, mimetype, size, files, suffix)
|
||||
|
||||
values = [(str(primary_path),
|
||||
str(primary_path.parent), # directory
|
||||
|
|
@ -721,7 +723,8 @@ def _upsert_files(files: List[pathlib.Path], idempotency: datetime.datetime,
|
|||
values = mogrify(curs, values)
|
||||
stmt = f'''
|
||||
INSERT INTO file_group
|
||||
(primary_path, directory, indexed, idempotency, modification_datetime, mimetype, size, files)
|
||||
(primary_path, directory, indexed, idempotency, modification_datetime, mimetype, size, files,
|
||||
suffix)
|
||||
VALUES {values}
|
||||
ON CONFLICT (primary_path) DO UPDATE
|
||||
SET
|
||||
|
|
@ -730,6 +733,8 @@ def _upsert_files(files: List[pathlib.Path], idempotency: datetime.datetime,
|
|||
modification_datetime=EXCLUDED.modification_datetime,
|
||||
mimetype=EXCLUDED.mimetype,
|
||||
size=EXCLUDED.size,
|
||||
-- Always keep suffix current so suffix search works even for already-indexed files.
|
||||
suffix=EXCLUDED.suffix,
|
||||
files=(
|
||||
-- Do not overwrite files unless the files have changed and need to be re-indexed.
|
||||
CASE
|
||||
|
|
@ -1026,7 +1031,7 @@ async def search_directories_by_name(session: Session, name: str, excluded: List
|
|||
def search_files(search_str: str, limit: int, offset: int, mimetypes: List[str] = None, model: str = None,
|
||||
tag_names: List[str] = None, headline: bool = False, months: List[int] = None,
|
||||
from_year: int = None, to_year: int = None, any_tag: bool = False, order: str = None,
|
||||
url: str = None) -> \
|
||||
url: str = None, suffix: str = None, path: str = None) -> \
|
||||
Tuple[List[dict], int]:
|
||||
"""Search the FileGroup table.
|
||||
|
||||
|
|
@ -1046,6 +1051,8 @@ def search_files(search_str: str, limit: int, offset: int, mimetypes: List[str]
|
|||
@param months: A list of integers representing the index of the month of the year, starting at 1.
|
||||
@param order: Used to change results from most relevant to recently viewed.
|
||||
@param url: Filter by URL using case-insensitive partial match (ILIKE).
|
||||
@param suffix: Only return files whose primary file has this suffix (e.g. ".bin"), case-insensitive.
|
||||
@param path: Filter by primary_path using case-insensitive partial match (ILIKE).
|
||||
"""
|
||||
params = dict(offset=offset, limit=limit, search_str=search_str, url_search_str=f'%{search_str}%')
|
||||
wheres = []
|
||||
|
|
@ -1072,6 +1079,16 @@ def search_files(search_str: str, limit: int, offset: int, mimetypes: List[str]
|
|||
params['url_filter'] = f'%{url}%'
|
||||
wheres.append('fg.url ILIKE %(url_filter)s')
|
||||
|
||||
if suffix:
|
||||
# Suffix is stored lowercased with a leading dot; normalize the caller's value to match the index.
|
||||
normalized = suffix if suffix.startswith('.') else f'.{suffix}'
|
||||
params['suffix'] = normalized.lower()
|
||||
wheres.append('fg.suffix = %(suffix)s')
|
||||
|
||||
if path:
|
||||
params['path_filter'] = f'%{path}%'
|
||||
wheres.append('fg.primary_path ILIKE %(path_filter)s')
|
||||
|
||||
if search_str and headline:
|
||||
headline = ''',
|
||||
ts_headline(fg.title, websearch_to_tsquery(%(search_str)s)) AS "title_headline",
|
||||
|
|
|
|||
|
|
@ -104,6 +104,7 @@ class FileGroup(ModelHelper, Base):
|
|||
published_datetime = Column(TZDateTime) # the date the creator published this file
|
||||
published_modified_datetime = Column(TZDateTime) # the date the publisher modified this file
|
||||
size = Column(BigInteger, default=lambda: 0)
|
||||
suffix = Column(String, index=True) # lowercased suffix of the primary_path (e.g. ".bin"), for indexed filtering
|
||||
title = Column(String) # user-displayable title
|
||||
url = Column(String) # the location where this file can be downloaded.
|
||||
viewed = Column(TZDateTime) # the most recent time a User viewed this file.
|
||||
|
|
@ -498,7 +499,8 @@ class FileGroup(ModelHelper, Base):
|
|||
@classmethod
|
||||
def from_paths(cls, session: Session, *paths: pathlib.Path) -> 'FileGroup':
|
||||
"""Create a new FileGroup which contains the provided file paths."""
|
||||
from wrolpi.files.lib import get_primary_file, get_mimetype, sanitize_filename_surrogates
|
||||
from wrolpi.files.lib import get_primary_file, get_mimetype, sanitize_filename_surrogates, \
|
||||
split_path_stem_and_suffix
|
||||
|
||||
# Sanitize any paths with invalid UTF-8 characters (renames files on disk if needed)
|
||||
paths = tuple(sanitize_filename_surrogates(p) for p in paths)
|
||||
|
|
@ -533,6 +535,8 @@ class FileGroup(ModelHelper, Base):
|
|||
file_group.modification_datetime = from_timestamp(max(i.stat().st_mtime for i in paths))
|
||||
file_group.size = sum(i.stat().st_size for i in paths)
|
||||
file_group.mimetype = get_mimetype(file_group.primary_path)
|
||||
# Store the lowercased suffix so searches can filter by file type using the indexed column.
|
||||
file_group.suffix = (split_path_stem_and_suffix(primary_path)[1] or '').lower() or None
|
||||
logger.trace(f'FileGroup.from_paths: {file_group}')
|
||||
|
||||
return file_group
|
||||
|
|
|
|||
|
|
@ -42,6 +42,8 @@ class FilesSearchRequest:
|
|||
any_tag: bool = False
|
||||
order: Optional[str] = None
|
||||
url: Optional[str] = None # Filter by URL (partial match)
|
||||
suffix: Optional[str] = None # Filter by primary file suffix (e.g. ".bin"), case-insensitive exact match
|
||||
path: Optional[str] = None # Filter by primary_path (case-insensitive partial match)
|
||||
|
||||
def __post_init__(self):
|
||||
if self.any_tag and self.tag_names:
|
||||
|
|
|
|||
|
|
@ -285,6 +285,50 @@ async def test_files_search(test_session, async_client, make_files_structure, as
|
|||
await assert_files_search('nothing', [])
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_files_search_by_suffix(test_session, async_client, make_files_structure):
|
||||
"""Files can be filtered by their primary file's suffix (used by the firmware flasher to find .bin files)."""
|
||||
files = [
|
||||
'software/MALVEKE.ino.bin',
|
||||
'software/bffb/esp32_marauder.ino.bootloader.bin',
|
||||
'software/firmware-heltec.uf2',
|
||||
'software/firmware-r1-neo.uf2',
|
||||
'notes.txt',
|
||||
]
|
||||
created = make_files_structure(files)
|
||||
for path in created:
|
||||
path.write_bytes(b'\x00\x01\x02\x03')
|
||||
|
||||
request, response = await async_client.post('/api/files/refresh')
|
||||
assert response.status_code == HTTPStatus.NO_CONTENT
|
||||
|
||||
async def search(**kwargs):
|
||||
request, response = await async_client.post('/api/files/search', json=kwargs)
|
||||
assert response.status_code == HTTPStatus.OK
|
||||
return sorted(fg['primary_path'] for fg in response.json['file_groups'])
|
||||
|
||||
# Exact suffix match, normalized whether or not a leading dot is given, and case-insensitive.
|
||||
assert await search(suffix='.bin') == ['software/MALVEKE.ino.bin',
|
||||
'software/bffb/esp32_marauder.ino.bootloader.bin']
|
||||
assert await search(suffix='bin') == ['software/MALVEKE.ino.bin',
|
||||
'software/bffb/esp32_marauder.ino.bootloader.bin']
|
||||
assert await search(suffix='.BIN') == ['software/MALVEKE.ino.bin',
|
||||
'software/bffb/esp32_marauder.ino.bootloader.bin']
|
||||
assert await search(suffix='.uf2') == ['software/firmware-heltec.uf2', 'software/firmware-r1-neo.uf2']
|
||||
assert await search(suffix='.txt') == ['notes.txt']
|
||||
# A suffix that matches nothing returns no results.
|
||||
assert await search(suffix='.gguf') == []
|
||||
|
||||
# The `path` filter matches anywhere in the primary_path (case-insensitive), so a directory name works.
|
||||
assert await search(path='bffb') == ['software/bffb/esp32_marauder.ino.bootloader.bin']
|
||||
assert await search(path='BFFB') == ['software/bffb/esp32_marauder.ino.bootloader.bin']
|
||||
assert await search(path='software/') == ['software/MALVEKE.ino.bin',
|
||||
'software/bffb/esp32_marauder.ino.bootloader.bin',
|
||||
'software/firmware-heltec.uf2', 'software/firmware-r1-neo.uf2']
|
||||
# `suffix` and `path` combine (the firmware picker sends both).
|
||||
assert await search(suffix='.bin', path='bffb') == ['software/bffb/esp32_marauder.ino.bootloader.bin']
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_files_search_attaches_doc_section_hint(async_client, test_session, test_directory,
|
||||
example_epub, refresh_files):
|
||||
|
|
|
|||
|
|
@ -260,6 +260,33 @@ async def test_refresh_files(async_client, test_session, make_files_structure, a
|
|||
assert_file_groups([{'primary_path': 'bar.txt', 'indexed': True}])
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_refresh_populates_suffix(async_client, test_session, make_files_structure, refresh_files):
|
||||
"""A refresh populates `file_group.suffix` for every file it discovers.
|
||||
|
||||
Regression: suffix is path-derived metadata (like mimetype) and must be set when the FileGroup is
|
||||
upserted during discovery, not deferred to content-indexing. Deferring it meant a file that got marked
|
||||
indexed through a path that skipped that step ended up indexed with a NULL suffix and was invisible to
|
||||
suffix search (the firmware flasher's media picker)."""
|
||||
make_files_structure([
|
||||
'software/firmware.bin',
|
||||
'software/bffb/esp32_marauder.ino.bootloader.bin',
|
||||
'notes.txt',
|
||||
])
|
||||
|
||||
await refresh_files()
|
||||
|
||||
file_groups = test_session.query(FileGroup).all()
|
||||
# Suffix is set for every file the moment it is discovered, and every row is indexed.
|
||||
assert all(fg.indexed for fg in file_groups)
|
||||
suffixes = {fg.primary_path.name: fg.suffix for fg in file_groups}
|
||||
assert suffixes == {
|
||||
'firmware.bin': '.bin',
|
||||
'esp32_marauder.ino.bootloader.bin': '.bin',
|
||||
'notes.txt': '.txt',
|
||||
}
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_file_group_location(async_client, test_session, make_files_structure, refresh_files):
|
||||
"""FileGroup can return the URL necessary to preview the FileGroup."""
|
||||
|
|
|
|||
|
|
@ -15,6 +15,7 @@ from vininfo.details._base import VinDetails
|
|||
|
||||
from modules.archive.api import archive_bp
|
||||
from modules.docs.api import docs_bp
|
||||
from modules.flasher.api import flasher_bp
|
||||
from modules.inventory import inventory_bp
|
||||
from modules.map.api import map_bp
|
||||
from modules.videos.api import videos_bp
|
||||
|
|
@ -52,6 +53,7 @@ api_app.blueprint(collection_bp) # Unified collection endpoints
|
|||
api_app.blueprint(config_bp)
|
||||
api_app.blueprint(docs_bp)
|
||||
api_app.blueprint(files_bp)
|
||||
api_app.blueprint(flasher_bp)
|
||||
api_app.blueprint(inventory_bp)
|
||||
api_app.blueprint(map_bp)
|
||||
api_app.blueprint(videos_bp)
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue