Automate via workflows. Add auto-archiving for downgrade. (#581)

This commit is contained in:
Nerivec
2024-10-28 21:38:11 +01:00
committed by GitHub
parent c1c4488759
commit ea2e6693f8
60 changed files with 10052 additions and 323 deletions

32
.github/workflows/ci.yml vendored Normal file
View File

@@ -0,0 +1,32 @@
name: CI
on:
pull_request:
types: [opened, synchronize]
branches: [main]
paths: ['src/**', 'tests/**']
workflow_dispatch:
jobs:
ci:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: pnpm/action-setup@v4
with:
version: 9
- uses: actions/setup-node@v4
with:
node-version: 20
registry-url: https://registry.npmjs.org/
cache: pnpm
- name: Install dependencies
run: pnpm i --frozen-lockfile
- name: Build
run: pnpm run build
- name: Lint
run: |
pnpm run format:check
pnpm run eslint
- name: Test
# NOTE: see jest.config.ts `collectCoverageFrom`
run: pnpm run coverage

41
.github/workflows/concat_cacerts.yml vendored Normal file
View File

@@ -0,0 +1,41 @@
name: Concatenate CA certificates
on:
push:
branches: [main]
paths: ['cacerts/**']
workflow_dispatch:
permissions:
contents: write
jobs:
concat-cacerts:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: pnpm/action-setup@v4
with:
version: 9
- uses: actions/setup-node@v4
with:
node-version: 20
registry-url: https://registry.npmjs.org/
cache: pnpm
- name: Install dependencies
run: pnpm i --frozen-lockfile
- name: Build
run: pnpm run build
- name: Concat CACerts
uses: actions/github-script@v7
with:
script: |
const {concatCaCerts} = await import("${{ github.workspace }}/dist/ghw_concat_cacerts.js")
await concatCaCerts(github, core, context)
- name: Commit changes
run: |
git config --global user.name 'github-actions[bot]'
git config --global user.email 'github-actions[bot]@users.noreply.github.com'
git add .
git commit -m "Concatenate CA certificates" || echo 'Nothing to commit'
git push

View File

@@ -1,30 +0,0 @@
# This workflow executes several linters on changed files based on languages used in your code base whenever
# you push a code or open a pull request.
#
# You can adjust the behavior by modifying this file.
# For more information, see:
# https://github.com/github/super-linter
name: Lint Code Base
on:
push:
branches: [ master ]
pull_request:
branches: [ master ]
jobs:
run-lint:
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v3
with:
# Full git history is needed to get a proper list of changed files within `super-linter`
fetch-depth: 0
- name: Lint Code Base
uses: github/super-linter@v4
env:
VALIDATE_ALL_CODEBASE: false
FILTER_REGEX_INCLUDE: .*.json
DEFAULT_BRANCH: master
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

44
.github/workflows/overwrite_cache.yml vendored Normal file
View File

@@ -0,0 +1,44 @@
name: Overwrite cache
on:
workflow_dispatch:
inputs:
manufacturers:
description: 'Only trigger overwrite for given manufacturers (CSV, no space).'
required: false
default: ''
type: string
permissions:
contents: write
jobs:
overwrite-cache:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: pnpm/action-setup@v4
with:
version: 9
- uses: actions/setup-node@v4
with:
node-version: 20
registry-url: https://registry.npmjs.org/
cache: pnpm
- name: Install dependencies
run: pnpm i --frozen-lockfile
- name: Build
run: pnpm run build
- name: Overwrite cache
uses: actions/github-script@v7
with:
script: |
const {overwriteCache} = await import("${{ github.workspace }}/dist/gwh_overwrite_cache.js")
await overwriteCache(github, core, context, "${{ inputs.manufacturers || '' }}")
- name: Commit changes
run: |
git config --global user.name 'github-actions[bot]'
git config --global user.email 'github-actions[bot]@users.noreply.github.com'
git add .
git commit -m "Cache overwrite" || echo 'Nothing to commit'
git push

View File

@@ -0,0 +1,66 @@
name: Re-Process All Images
on:
workflow_dispatch:
inputs:
remove_not_in_manifest:
description: 'Remove images not found in manifest (if false, will be moved to separate dir instead).'
required: true
default: false
type: boolean
# TODO: remove this and the logic behind it once the first run has been executed to prevent following accidental executions
skip_download_third_parties:
description: 'Skip the step that downloads firmware with 3rd party URLs in manifest (logic should be removed after first run after 2024-10 revamp).'
required: true
default: true
type: boolean
permissions:
contents: write
pull-requests: write
jobs:
reprocess-all-images:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: pnpm/action-setup@v4
with:
version: 9
- uses: actions/setup-node@v4
with:
node-version: 20
registry-url: https://registry.npmjs.org/
cache: pnpm
- name: Install dependencies
run: pnpm i --frozen-lockfile
- name: Build
run: pnpm run build
- name: Create and checkout new branch
id: create_branch
run: |
git config --global user.name 'github-actions[bot]'
git config --global user.email 'github-actions[bot]@users.noreply.github.com'
branch_name="reprocess-$(date +'%Y-%m-%d-%H-%M-%S')"
echo "branch_name=$branch_name" >> $GITHUB_OUTPUT
git checkout -b $branch_name
- name: Reprocess
uses: actions/github-script@v7
env:
NODE_EXTRA_CA_CERTS: cacerts.pem
with:
script: |
const {reProcessAllImages} = await import("${{ github.workspace }}/dist/ghw_reprocess_all_images.js")
await reProcessAllImages(github, core, context, ${{ fromJSON(inputs.remove_not_in_manifest) }}, ${{ fromJSON(inputs.skip_download_third_parties) }})
- name: Commit changes in new branch
run: |
git add .
git commit -m "Re-Processed all images" || echo 'Nothing to commit'
git push -u origin HEAD
- name: Create pull request
uses: actions/github-script@v7
with:
script: |
const {createPRToDefault} = await import("${{ github.workspace }}/dist/ghw_create_pr_to_default.js")
await createPRToDefault(github, core, context, "${{steps.create_branch.outputs.branch_name}}", "Re-Processed all images")

68
.github/workflows/run_autodl.yml vendored Normal file
View File

@@ -0,0 +1,68 @@
name: Run auto download
on:
# schedule:
# # * is a special character in YAML, always quote this string
# - cron: '0 1 * * 1'
workflow_dispatch:
inputs:
prev:
description: 'Get previous firmware versions (if available) instead of latest.'
required: false
default: false
type: boolean
manufacturers:
description: 'Only trigger updates for given manufacturers (CSV, no space).'
required: false
default: ''
type: string
ignore_cache:
description: 'Ignore cached data in .cache for this run.'
required: false
default: false
type: boolean
permissions:
contents: write
jobs:
run-autodl:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: pnpm/action-setup@v4
with:
version: 9
- uses: actions/setup-node@v4
with:
node-version: 20
registry-url: https://registry.npmjs.org/
cache: pnpm
- name: Install dependencies
run: pnpm i --frozen-lockfile
- name: Build
run: pnpm run build
- name: Run Autodl
uses: actions/github-script@v7
env:
NODE_EXTRA_CA_CERTS: cacerts.pem
PREV: ${{ fromJSON(inputs.prev) && '1' || '' }}
IGNORE_CACHE: ${{ fromJSON(inputs.ignore_cache) && '1' || '' }}
with:
script: |
const {runAutodl} = await import("${{ github.workspace }}/dist/ghw_run_autodl.js")
await runAutodl(github, core, context, "${{ inputs.manufacturers || '' }}")
- name: Create Autodl release
uses: actions/github-script@v7
with:
script: |
const {createAutodlRelease} = await import("${{ github.workspace }}/dist/ghw_create_autodl_release.js")
await createAutodlRelease(github, core, context)
- name: Commit changes
run: |
git config --global user.name 'github-actions[bot]'
git config --global user.email 'github-actions[bot]@users.noreply.github.com'
git add .
git commit -m "Autodl update" || echo 'Nothing to commit'
git push

View File

@@ -1,16 +1,23 @@
name: "Close stale issues/pull requests"
name: 'Close stale issues/pull requests'
on:
schedule:
- cron: "0 0 * * *"
schedule:
- cron: '0 0 * * *'
workflow_dispatch:
permissions:
# contents: write # only for delete-branch option
issues: write
pull-requests: write
jobs:
stale:
runs-on: ubuntu-latest
steps:
- uses: actions/stale@v3
with:
repo-token: ${{ secrets.GITHUB_TOKEN }}
stale-issue-message: 'This issue is stale because it has been open 180 days with no activity. Remove stale label or comment or this will be closed in 30 days'
stale-pr-message: 'This pull request is stale because it has been open 180 days with no activity. Remove stale label or comment or this will be closed in 30 days'
days-before-stale: 180
days-before-close: 30
stale:
runs-on: ubuntu-latest
steps:
- uses: actions/stale@v9
with:
repo-token: ${{ secrets.GITHUB_TOKEN }}
stale-issue-message: 'This issue is stale because it has been open 180 days with no activity. Remove stale label or comment or this will be closed in 30 days'
stale-pr-message: 'This pull request is stale because it has been open 180 days with no activity. Remove stale label or comment or this will be closed in 30 days'
exempt-issue-labels: dont-stale
days-before-stale: 180
days-before-close: 30

53
.github/workflows/update_ota_pr.yml vendored Normal file
View File

@@ -0,0 +1,53 @@
name: Update OTA PR
on:
pull_request:
types: [opened, synchronize, reopened, edited, closed]
branches: [main]
paths: ['images/**']
permissions:
contents: write
pull-requests: write
jobs:
update-pr:
runs-on: ubuntu-latest
# don't run if PR was closed without merge, or explicitly disabled
if: |
!contains(github.event.pull_request.labels.*.name, 'ignore-ota-workflow') && (github.event.action != 'closed' || github.event.pull_request.merged == true)
steps:
- uses: actions/checkout@v4
- uses: pnpm/action-setup@v4
with:
version: 9
- uses: actions/setup-node@v4
with:
node-version: 20
registry-url: https://registry.npmjs.org/
cache: pnpm
- name: Install dependencies
run: pnpm i --frozen-lockfile
- name: Build
run: pnpm run build
- name: Get changed files
run: |
files=$(gh pr view ${{ github.event.pull_request.number }} --json files -q '.files[].path' | tr '\n' ',')
echo "files=$files" >> $GITHUB_OUTPUT
id: changed_files
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
- name: Update PR
uses: actions/github-script@v7
with:
script: |
const {updateOtaPR} = await import("${{ github.workspace }}/dist/ghw_update_ota_pr.js")
await updateOtaPR(github, core, context, "${{steps.changed_files.outputs.files}}")
- name: Commit changes on push
if: github.event.pull_request.merged == true
run: |
git config --global user.name 'github-actions[bot]'
git config --global user.email 'github-actions[bot]@users.noreply.github.com'
git add .
git commit -m "Update after PR with OTA images merged" || echo 'Nothing to commit'
git push

16
.gitignore vendored Normal file
View File

@@ -0,0 +1,16 @@
node_modules/
coverage/
dist/
temp/
tmp/
.jest-tmp/
tsconfig.tsbuildinfo
# used by tests
images/jest-tmp
images1/jest-tmp
not-in-manifest-images/jest-tmp
not-in-manifest-images1/jest-tmp
# MacOS indexing files
.DS_Store

10
.prettierignore Normal file
View File

@@ -0,0 +1,10 @@
pnpm-lock.yaml
.cache/
images/
images1/
not-in-manifest-images/
not-in-manifest-images1/
index.json
index1.json
cacerts/
cacerts.pem

26
.prettierrc Normal file
View File

@@ -0,0 +1,26 @@
{
"semi": true,
"trailingComma": "all",
"singleQuote": true,
"printWidth": 150,
"bracketSpacing": false,
"endOfLine": "lf",
"tabWidth": 4,
"importOrder": [
"",
"<TYPES>^(node:)",
"",
"<TYPES>",
"",
"<TYPES>^[.]",
"",
"<BUILTIN_MODULES>",
"",
"<THIRD_PARTY_MODULES>",
"",
"^zigbee",
"",
"^[.]"
],
"plugins": ["@ianvs/prettier-plugin-sort-imports"]
}

674
LICENSE Normal file
View File

@@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.

150
README.md
View File

@@ -1,19 +1,147 @@
# zigbee-OTA
[![Lint Code Base status badge](https://github.com/Koenkk/zigbee-OTA/workflows/Lint%20Code%20Base/badge.svg)](https://github.com/Koenkk/zigbee-OTA/actions/workflows/linter.yml)
A collection of Zigbee OTA files, see the manifest `index.json` for an overview of all available firmware files.
The manifest `index1.json` contains firmware files for downgrade (previous available version, before the one in `index.json`).
A collection of Zigbee OTA files, see `index.json` for an overview of all available firmware files.
> [!IMPORTANT]
> While a downgrade OTA file may be available for a device through automatic archiving in this repository, it does not mean the device will actually allow the downgrade, some will refuse the OTA file.
## Adding new and updating existing OTA files
1. Go to this directory
2. Execute `node scripts/add.js PATH_TO_OTA_FILE_OR_URL`, e.g.:
- `node scripts/add.js ~/Downloads/WhiteLamp-Atmel-Target_0105_5.130.1.30000_0012.sbl-ota`
- `node scripts/add.js http://fds.dc1.philips.com/firmware/ZGB_100B_010D/1107323831/Sensor-ATmega_6.1.1.27575_0012.sbl-ota`
3. Create a PR. Changes will be automatically validated by GitHub.
Create a pull request with the image(s) in their proper subdirectories (manufacturer name) under `images` directory.
## Updating all existing OTA entries (if `add.js` has been changed)
The pull request automation will validate the image. If any error occur, a comment will be posted in the pull request. If the validation succeed, a comment will be posted to inform of the changes that merging the pull request will commit (in a following commit).
1. Go to this directory
2. Execute `node scripts/updateall.js`
3. Create a PR. Changes will be automatically validated by GitHub.
> [!IMPORTANT]
> Do NOT submit images in `images1` directory, the pull request automation will take care of placing the file in the proper folder automatically.
### Example using Github
Fork https://github.com/Koenkk/zigbee-OTA/ on Github.
In your fork, navigate to `images` directory, then to whatever manufacturer is associated with your OTA file(s).
Click on `Add file` dropdown, then `Upload files`.
Add the file(s), a good title, and an optional description (if extra metas required, see below), then pick `Create a new branch for this commit and start a pull request.`, then submit with `Propose changes`.
Then wait for the workflow to validate your file(s).
### Example using the console
Fork https://github.com/Koenkk/zigbee-OTA/ on Github.
```bash
# where `username` is your Github username (to use your fork)
$ git clone --depth 1 https://github.com/username/zigbee-OTA/
$ cd zigbee-OTA
$ git checkout -b my-new-image
# where `manufacturer` is the name of the manufacturer associated with the image (if it does not already exist)
$ mkdir ./images/manufacturer/
$ cp ~/Downloads/my-new-ota.ota ./images/manufacturer/
$ git add .
$ git commit -m "New image for xyz device from abc manufacturer"
$ git push -u origin HEAD
```
Then go on Github, create a pull request from the notification in the repository and wait for the workflow to run the validation process.
### Declaring extra metadata for automatic inclusion in the manifest
If the image(s) added to the pull request require extra metadata in the manifest (usually to avoid conflicts, or to set restrictions), you can declare them in the body of the pull request (the description field of the first post).
Example:
````md
This is the latest OTA file for device XYZ.
```json
{
"modelId": "xyzDevice",
"manufacturerName": ["xyzManufacturer"]
}
```
````
The pull request automation will look for any valid JSON in-between ` ```json ` and ` ``` ` and add these fields to the manifest.
> [!TIP]
> If the validation failed because of something related to the extra metadata, you can edit the pull request body and make the necessary corrections. The automation will re-run when saved.
> [!IMPORTANT]
> Do NOT use code blocks (` ``` `) for anything else in the body to avoid issues. If necessary, add a new comment below it (only the very first post is used for extra metadata detection).
#### Allowed fields
Valid JSON format is expected.
Any field not in this list will be ignored. Any field not matching the required type will result in failure.
###### To place restrictions
- "force": boolean _(ignore `fileVersion` and always present as 'available')_
- "hardwareVersionMax": number
- "hardwareVersionMin": number
- "manufacturerName": array of strings _(target only devices with one of these manufacturer names)_
- "maxFileVersion": number _(target only devices with this version or below)_
- "minFileVersion": number _(target only devices with this version or above)_
- "modelId": string _(target only devices with this model ID)_
###### For record purpose
- "originalUrl": string
- "releaseNotes": string
If the pull request contains multiple files, the metadata is added for all files. If some files require different metadata, add the matching `fileName` to the JSON using an encompassing array instead. It will be used to assign metadata as directed.
Example:
````md
```json
[
{
"fileName": "myotafile-for-xyzdevice.ota",
"modelId": "xyzDevice",
"manufacturerName": ["xyzManufacturer"]
},
{
"fileName": "myotafile-for-abcdevice.ota",
"modelId": "abcDevice",
"manufacturerName": ["abcManufacturer"]
}
]
```
````
### Notes for maintainers
- `images` and `index.json` contain added (PR or auto download) "upgrade" images.
- `images1` and `index1.json` contain automatically archived "downgrade" images (automatically moved from `images`/`index.json` after a merged PR introduced a newer version, or during auto download).
If a manual modification of the manifests is necessary, it should be done in a PR that does not trigger the `update_ota_pr` workflow (no changes in `images/**` directory). As a last resort, the label `ignore-ota-workflow` can be added to prevent the workflow from running.
The metadata structure for images is as below (see above for details on extra metas):
```typescript
interface RepoImageMeta {
//-- automatic from parsed image
imageType: number;
fileVersion: number;
manufacturerCode: number;
fileSize: number;
otaHeaderString: string;
//-- automatic from image file
url: string;
sha512: string;
fileName: string;
//-- extra metas
force?: boolean;
hardwareVersionMin?: number;
hardwareVersionMax?: number;
modelId?: string;
manufacturerName?: string[];
minFileVersion?: number;
maxFileVersion?: number;
originalUrl?: string;
releaseNotes?: string;
}
```

View File

@@ -36,3 +36,48 @@ IQDcGfyXaUl5hjr5YE8m2piXhMcDzHTNbO1RvGgz4r9IswIgFTTw/R85KyfIiW+E
clwJRVSsq8EApeFREenCkRM0EIk=
-----END CERTIFICATE-----
-----BEGIN CERTIFICATE-----
MIICYjCCAemgAwIBAgIUQn+xrKMsCop2IL2YSz/jJpESmuEwCgYIKoZIzj0EAwMw
UDELMAkGA1UEBhMCU0UxGjAYBgNVBAoMEUlLRUEgb2YgU3dlZGVuIEFCMSUwIwYD
VQQDDBxJS0VBIEhvbWUgc21hcnQgT1RBIFRydXN0IENBMB4XDTIzMDQxNzE0MzE0
M1oXDTI1MDQxNjE0MzE0MlowcjELMAkGA1UEBhMCU0UxEjAQBgNVBAgMCUtyb25v
YmVyZzEQMA4GA1UEBwwHRUxNSFVMVDEaMBgGA1UECgwRSUtFQSBvZiBTd2VkZW4g
QUIxITAfBgNVBAMMGCoub3RhLmhvbWVzbWFydC5pa2VhLmNvbTBZMBMGByqGSM49
AgEGCCqGSM49AwEHA0IABOCF+5I/df6W0cNp/mbivUmxW/EHjy7VxvMe8542oy2D
L8Wn3BOqXoRZmTckzfz+xNXX+od84xl2teV66O34PPujfzB9MAwGA1UdEwEB/wQC
MAAwHwYDVR0jBBgwFoAUrRAWZaaubKmqMPHU92uXboPJn8cwHQYDVR0lBBYwFAYI
KwYBBQUHAwIGCCsGAQUFBwMBMB0GA1UdDgQWBBT3eAj6s8wxBTycGMrQK12KXc1t
9TAOBgNVHQ8BAf8EBAMCBaAwCgYIKoZIzj0EAwMDZwAwZAIvYqZL8E0i/CqHX1lf
IVMHYmj0O7LBljE/tXgME+eg/l4r25KGjgK1E2SPuq4U27sCMQCv/VB3MQjdtgoB
MXKMfEKdxdZAXfIDwyFvlXnWlWAEOJQxvfUDdyNiGe1AgZ5aHJ4=
-----END CERTIFICATE-----
-----BEGIN CERTIFICATE-----
MIICGDCCAZ+gAwIBAgIUdfH0KDnENv/dEcxH8iVqGGGDqrowCgYIKoZIzj0EAwMw
SzELMAkGA1UEBhMCU0UxGjAYBgNVBAoMEUlLRUEgb2YgU3dlZGVuIEFCMSAwHgYD
VQQDDBdJS0VBIEhvbWUgc21hcnQgUm9vdCBDQTAgFw0yMTA1MjYxOTAxMDlaGA8y
MDcxMDUxNDE5MDEwOFowSzELMAkGA1UEBhMCU0UxGjAYBgNVBAoMEUlLRUEgb2Yg
U3dlZGVuIEFCMSAwHgYDVQQDDBdJS0VBIEhvbWUgc21hcnQgUm9vdCBDQTB2MBAG
ByqGSM49AgEGBSuBBAAiA2IABIDRUvKGFMUu2zIhTdgfrfNcPULwMlc0TGSrDLBA
oTr0SMMV4044CRZQbl81N4qiuHGhFzCnXapZogkiVuFu7ZqSslsFuELFjc6ZxBjk
Kmud+pQM6QQdsKTE/cS06dA+P6NCMEAwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4E
FgQUcdlEnfX0MyZA4zAdY6CLOye9wfwwDgYDVR0PAQH/BAQDAgGGMAoGCCqGSM49
BAMDA2cAMGQCMG6mFIeB2GCFch3r0Gre4xRH+f5pn/bwLr9yGKywpeWvnUPsQ1KW
ckMLyxbeNPXdQQIwQc2YZDq/Mz0mOkoheTUWiZxK2a5bk0Uz1XuGshXmQvEg5TGy
2kVHW/Mz9/xwpy4u
-----END CERTIFICATE-----
-----BEGIN CERTIFICATE-----
MIICQTCCAcagAwIBAgIUAr5VleESJnRg+J9oehqJc+MGphIwCgYIKoZIzj0EAwMw
SzELMAkGA1UEBhMCU0UxGjAYBgNVBAoMEUlLRUEgb2YgU3dlZGVuIEFCMSAwHgYD
VQQDDBdJS0VBIEhvbWUgc21hcnQgUm9vdCBDQTAeFw0yMTA1MjYxOTE1NDVaFw00
NjA1MjAxOTE1NDRaMFAxCzAJBgNVBAYTAlNFMRowGAYDVQQKDBFJS0VBIG9mIFN3
ZWRlbiBBQjElMCMGA1UEAwwcSUtFQSBIb21lIHNtYXJ0IE9UQSBUcnVzdCBDQTB2
MBAGByqGSM49AgEGBSuBBAAiA2IABC6Db3/cBpl//CmRX7Ur90ikDbpLtaCcvcJT
p72LY585dsMUA7cjZQlAQdNfI7zSr0Y8O9w0dIoqz8HL8G7E/pYChhvQPUgx1avn
6IEtdWLwI0XPPsFtLO8jRJFIsjkeAaNmMGQwEgYDVR0TAQH/BAgwBgEB/wIBADAf
BgNVHSMEGDAWgBRx2USd9fQzJkDjMB1joIs7J73B/DAdBgNVHQ4EFgQUrRAWZaau
bKmqMPHU92uXboPJn8cwDgYDVR0PAQH/BAQDAgGGMAoGCCqGSM49BAMDA2kAMGYC
MQDcIekS7OcwMcLXMtP6rWfZUsJF7iI59t3rEame11vIdY/sFHHWWm07OLJ7gRwg
NpwCMQDhMc3sX2cBD3zZ2zDwCjFBCudhgWLc2eqNy/b5mY+/Ppdp6EX11PZK0Hb9
dZ2TSWM=
-----END CERTIFICATE-----

44
cacerts/ikea_new.pem Normal file
View File

@@ -0,0 +1,44 @@
-----BEGIN CERTIFICATE-----
MIICYjCCAemgAwIBAgIUQn+xrKMsCop2IL2YSz/jJpESmuEwCgYIKoZIzj0EAwMw
UDELMAkGA1UEBhMCU0UxGjAYBgNVBAoMEUlLRUEgb2YgU3dlZGVuIEFCMSUwIwYD
VQQDDBxJS0VBIEhvbWUgc21hcnQgT1RBIFRydXN0IENBMB4XDTIzMDQxNzE0MzE0
M1oXDTI1MDQxNjE0MzE0MlowcjELMAkGA1UEBhMCU0UxEjAQBgNVBAgMCUtyb25v
YmVyZzEQMA4GA1UEBwwHRUxNSFVMVDEaMBgGA1UECgwRSUtFQSBvZiBTd2VkZW4g
QUIxITAfBgNVBAMMGCoub3RhLmhvbWVzbWFydC5pa2VhLmNvbTBZMBMGByqGSM49
AgEGCCqGSM49AwEHA0IABOCF+5I/df6W0cNp/mbivUmxW/EHjy7VxvMe8542oy2D
L8Wn3BOqXoRZmTckzfz+xNXX+od84xl2teV66O34PPujfzB9MAwGA1UdEwEB/wQC
MAAwHwYDVR0jBBgwFoAUrRAWZaaubKmqMPHU92uXboPJn8cwHQYDVR0lBBYwFAYI
KwYBBQUHAwIGCCsGAQUFBwMBMB0GA1UdDgQWBBT3eAj6s8wxBTycGMrQK12KXc1t
9TAOBgNVHQ8BAf8EBAMCBaAwCgYIKoZIzj0EAwMDZwAwZAIvYqZL8E0i/CqHX1lf
IVMHYmj0O7LBljE/tXgME+eg/l4r25KGjgK1E2SPuq4U27sCMQCv/VB3MQjdtgoB
MXKMfEKdxdZAXfIDwyFvlXnWlWAEOJQxvfUDdyNiGe1AgZ5aHJ4=
-----END CERTIFICATE-----
-----BEGIN CERTIFICATE-----
MIICGDCCAZ+gAwIBAgIUdfH0KDnENv/dEcxH8iVqGGGDqrowCgYIKoZIzj0EAwMw
SzELMAkGA1UEBhMCU0UxGjAYBgNVBAoMEUlLRUEgb2YgU3dlZGVuIEFCMSAwHgYD
VQQDDBdJS0VBIEhvbWUgc21hcnQgUm9vdCBDQTAgFw0yMTA1MjYxOTAxMDlaGA8y
MDcxMDUxNDE5MDEwOFowSzELMAkGA1UEBhMCU0UxGjAYBgNVBAoMEUlLRUEgb2Yg
U3dlZGVuIEFCMSAwHgYDVQQDDBdJS0VBIEhvbWUgc21hcnQgUm9vdCBDQTB2MBAG
ByqGSM49AgEGBSuBBAAiA2IABIDRUvKGFMUu2zIhTdgfrfNcPULwMlc0TGSrDLBA
oTr0SMMV4044CRZQbl81N4qiuHGhFzCnXapZogkiVuFu7ZqSslsFuELFjc6ZxBjk
Kmud+pQM6QQdsKTE/cS06dA+P6NCMEAwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4E
FgQUcdlEnfX0MyZA4zAdY6CLOye9wfwwDgYDVR0PAQH/BAQDAgGGMAoGCCqGSM49
BAMDA2cAMGQCMG6mFIeB2GCFch3r0Gre4xRH+f5pn/bwLr9yGKywpeWvnUPsQ1KW
ckMLyxbeNPXdQQIwQc2YZDq/Mz0mOkoheTUWiZxK2a5bk0Uz1XuGshXmQvEg5TGy
2kVHW/Mz9/xwpy4u
-----END CERTIFICATE-----
-----BEGIN CERTIFICATE-----
MIICQTCCAcagAwIBAgIUAr5VleESJnRg+J9oehqJc+MGphIwCgYIKoZIzj0EAwMw
SzELMAkGA1UEBhMCU0UxGjAYBgNVBAoMEUlLRUEgb2YgU3dlZGVuIEFCMSAwHgYD
VQQDDBdJS0VBIEhvbWUgc21hcnQgUm9vdCBDQTAeFw0yMTA1MjYxOTE1NDVaFw00
NjA1MjAxOTE1NDRaMFAxCzAJBgNVBAYTAlNFMRowGAYDVQQKDBFJS0VBIG9mIFN3
ZWRlbiBBQjElMCMGA1UEAwwcSUtFQSBIb21lIHNtYXJ0IE9UQSBUcnVzdCBDQTB2
MBAGByqGSM49AgEGBSuBBAAiA2IABC6Db3/cBpl//CmRX7Ur90ikDbpLtaCcvcJT
p72LY585dsMUA7cjZQlAQdNfI7zSr0Y8O9w0dIoqz8HL8G7E/pYChhvQPUgx1avn
6IEtdWLwI0XPPsFtLO8jRJFIsjkeAaNmMGQwEgYDVR0TAQH/BAgwBgEB/wIBADAf
BgNVHSMEGDAWgBRx2USd9fQzJkDjMB1joIs7J73B/DAdBgNVHQ4EFgQUrRAWZaau
bKmqMPHU92uXboPJn8cwDgYDVR0PAQH/BAQDAgGGMAoGCCqGSM49BAMDA2kAMGYC
MQDcIekS7OcwMcLXMtP6rWfZUsJF7iI59t3rEame11vIdY/sFHHWWm07OLJ7gRwg
NpwCMQDhMc3sX2cBD3zZ2zDwCjFBCudhgWLc2eqNy/b5mY+/Ppdp6EX11PZK0Hb9
dZ2TSWM=
-----END CERTIFICATE-----

33
eslint.config.mjs Normal file
View File

@@ -0,0 +1,33 @@
import eslint from '@eslint/js';
import eslintConfigPrettier from 'eslint-config-prettier';
import tseslint from 'typescript-eslint';
export default tseslint.config(
eslint.configs.recommended,
...tseslint.configs.recommended,
{
files: ['**/*.ts', '**/*.tsx'],
languageOptions: {
ecmaVersion: 'latest',
sourceType: 'script',
parserOptions: {
project: true,
},
},
rules: {
'@typescript-eslint/await-thenable': 'error',
'@typescript-eslint/ban-ts-comment': 'error',
'@typescript-eslint/explicit-function-return-type': 'error',
'@typescript-eslint/no-explicit-any': 'error',
'@typescript-eslint/no-unused-vars': 'error',
'array-bracket-spacing': ['error', 'never'],
'@typescript-eslint/return-await': ['error', 'always'],
'object-curly-spacing': ['error', 'never'],
'@typescript-eslint/no-floating-promises': 'error',
},
},
{
ignores: ['tmp/', 'dist/', 'eslint.config.mjs'],
},
eslintConfigPrettier,
);

1
index1.json Normal file
View File

@@ -0,0 +1 @@
[]

View File

@@ -1,61 +0,0 @@
const assert = require('assert');
const upgradeFileIdentifier = Buffer.from([0x1E, 0xF1, 0xEE, 0x0B]);
function parseSubElement(buffer, position) {
const tagID = buffer.readUInt16LE(position);
const length = buffer.readUInt32LE(position + 2);
const data = buffer.slice(position + 6, position + 6 + length);
return {tagID, length, data};
}
function parseImage(rawBuffer) {
const start = rawBuffer.indexOf(upgradeFileIdentifier);
const buffer = rawBuffer.slice(start);
const header = {
otaUpgradeFileIdentifier: buffer.subarray(0, 4),
otaHeaderVersion: buffer.readUInt16LE(4),
otaHeaderLength: buffer.readUInt16LE(6),
otaHeaderFieldControl: buffer.readUInt16LE(8),
manufacturerCode: buffer.readUInt16LE(10),
imageType: buffer.readUInt16LE(12),
fileVersion: buffer.readUInt32LE(14),
zigbeeStackVersion: buffer.readUInt16LE(18),
otaHeaderString: buffer.toString('utf8', 20, 52),
totalImageSize: buffer.readUInt32LE(52),
};
let headerPos = 56;
if (header.otaHeaderFieldControl & 1) {
header.securityCredentialVersion = buffer.readUInt8(headerPos);
headerPos += 1;
}
if (header.otaHeaderFieldControl & 2) {
header.upgradeFileDestination = buffer.subarray(headerPos, headerPos + 8);
headerPos += 8;
}
if (header.otaHeaderFieldControl & 4) {
header.minimumHardwareVersion = buffer.readUInt16LE(headerPos);
headerPos += 2;
header.maximumHardwareVersion = buffer.readUInt16LE(headerPos);
headerPos += 2;
}
const raw = buffer.slice(0, header.totalImageSize);
assert(Buffer.compare(header.otaUpgradeFileIdentifier, upgradeFileIdentifier) === 0, 'Not an OTA file');
let position = header.otaHeaderLength;
const elements = [];
while (position < header.totalImageSize) {
const element = parseSubElement(buffer, position);
elements.push(element);
position += element.data.length + 6;
}
assert(position === header.totalImageSize, 'Size mismatch');
return {header, elements, raw};
}
module.exports = {
parseImage
};

65
package.json Normal file
View File

@@ -0,0 +1,65 @@
{
"name": "zigbee-ota",
"version": "1.0.0",
"repository": {
"type": "git",
"url": "git+https://github.com/Koenkk/zigbee-OTA.git"
},
"engines": {
"node": ">=20.0.0"
},
"type": "module",
"main": "dist/index.js",
"scripts": {
"build": "tsc",
"start": "node ./dist/index.js",
"format": "prettier --write .",
"format:check": "prettier --check .",
"eslint": "eslint . --max-warnings=0",
"test": "jest test --config=./tests/jest.config.ts --silent --runInBand",
"coverage": "jest test --config=./tests/jest.config.ts --silent --runInBand --coverage"
},
"keywords": [
"zigbee",
"OTA",
"over-the-air",
"zigbee-update"
],
"author": {
"name": "Koen Kanters",
"email": "koenkanters94@gmail.com"
},
"contributors": [
{
"name": "Koen Kanters",
"url": "https://github.com/Koenkk"
},
{
"name": "Nerivec",
"url": "https://github.com/Nerivec"
}
],
"license": "GPL-3.0-or-later",
"description": "",
"dependencies": {
"tar": "^7.4.3"
},
"devDependencies": {
"@actions/core": "^1.11.1",
"@actions/github": "^6.0.0",
"@eslint/core": "^0.7.0",
"@eslint/js": "^9.13.0",
"@ianvs/prettier-plugin-sort-imports": "^4.3.1",
"@octokit/rest": "^21.0.2",
"@types/jest": "^29.5.14",
"@types/node": "^22.8.1",
"eslint": "^9.13.0",
"eslint-config-prettier": "^9.1.0",
"jest": "^29.7.0",
"prettier": "^3.3.3",
"ts-jest": "^29.2.5",
"ts-node": "^10.9.2",
"typescript": "^5.6.3",
"typescript-eslint": "^8.12.0"
}
}

3966
pnpm-lock.yaml generated Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -1,179 +0,0 @@
const path = require('path');
const fs = require('fs');
const crypto = require('crypto');
const tls = require('tls');
const ota = require('../lib/ota');
const filenameOrURL = process.argv[2];
const modelId = process.argv[3];
const baseURL = 'https://github.com/Koenkk/zigbee-OTA/raw/master';
const caCerts = './cacerts.pem';
const manufacturerNameLookup = {
123: 'UHome',
4098: 'Tuya',
4107: 'Hue',
4117: 'Develco',
4129: 'Legrand',
4151: 'Jennic',
4190: 'SchneiderElectric',
4364: 'Osram',
4405: 'DresdenElektronik',
4417: 'Telink',
4420: 'Lutron',
4444: 'Danalock',
4447: 'Lumi',
4448: 'Sengled',
4454: 'Innr',
4456: 'Perenio',
4474: 'Insta',
4476: 'IKEA',
4489: 'Ledvance',
4617: 'Bosch',
4644: 'Namron',
4648: 'Terncy',
4655: 'Inovelli',
4659: 'ThirdReality',
4678: 'Danfoss',
4687: 'Gledopto',
4714: 'EcoDim',
4742: 'Sonoff',
4747: 'NodOn',
4919: 'Datek',
10132: 'ClimaxTechnology',
26214: 'Sprut.device',
4877: 'thirdreality',
4636: 'Aurora',
56085: 'DIY',
5127: '3R',
13379: 'xyzroe',
};
const main = async () => {
if (!filenameOrURL) {
throw new Error('Please provide a filename or URL');
}
const isURL = filenameOrURL.toLowerCase().startsWith("http");
const files = [];
if (isURL) {
const downloadFile = async (url, path) => {
const lib = url.toLowerCase().startsWith("https") ? require('https') : require('http');
const file = fs.createWriteStream(path);
return new Promise((resolve, reject) => {
const ca = [...tls.rootCertificates];
if(fs.existsSync(caCerts)) {
ca.push(fs.readFileSync(caCerts));
}
const request = lib.get(url, { ca }, function(response) {
if (response.statusCode >= 200 && response.statusCode < 300) {
response.pipe(file);
file.on('finish', function() {
file.close(function() {
resolve();
});
});
} else if (response.headers.location) {
resolve(downloadFile(response.headers.location, path));
} else {
reject(new Error(response.statusCode + ' ' + response.statusMessage));
}
});
});
}
const file = path.resolve("temp");
await downloadFile(filenameOrURL, file);
files.push(file);
} else {
const file = path.resolve(filenameOrURL);
if (fs.lstatSync(file).isFile()) {
if (!fs.existsSync(file)) {
throw new Error(`${file} does not exist`);
}
files.push(file);
} else {
const otaExtension = ['.ota', '.zigbee'];
const otasInDirectory = fs.readdirSync(file)
.filter((f) => otaExtension.includes(path.extname(f).toLowerCase()))
.map((f) => path.join(file, f));
files.push(...otasInDirectory);
}
}
for (const file of files) {
const buffer = fs.readFileSync(file);
const parsed = ota.parseImage(buffer);
if (!manufacturerNameLookup[parsed.header.manufacturerCode]) {
throw new Error(`${parsed.header.manufacturerCode} not in manufacturerNameLookup (please add it)`);
}
const manufacturerName = manufacturerNameLookup[parsed.header.manufacturerCode];
const indexJSON = JSON.parse(fs.readFileSync('index.json'));
const destination = path.join('images', manufacturerName, path.basename(file));
const hash = crypto.createHash('sha512');
hash.update(buffer);
const entry = {
fileVersion: parsed.header.fileVersion,
fileSize: parsed.header.totalImageSize,
manufacturerCode: parsed.header.manufacturerCode,
imageType: parsed.header.imageType,
sha512: hash.digest('hex'),
};
if (modelId) {
entry.modelId = modelId;
}
if (isURL) {
entry.url = filenameOrURL;
} else {
const destinationPosix = destination.replace(/\\/g, '/');
entry.url = `${baseURL}/${escape(destinationPosix)}`;
entry.path = destinationPosix;
}
const index = indexJSON.findIndex((i) => {
return i.manufacturerCode === entry.manufacturerCode && i.imageType === entry.imageType && (!i.modelId || i.modelId === entry.modelId)
});
if (index !== -1) {
console.log(`Updated existing entry (${JSON.stringify(entry)})`);
indexJSON[index] = {...indexJSON[index], ...entry};
if (entry.path && entry.path !== destination) {
try {
fs.unlinkSync(path.resolve(entry.path));
} catch (err) {
if (err && err.code != 'ENOENT') {
console.error("Error in call to fs.unlink", err);
throw err;
}
}
}
} else {
console.log(`Added new entry (${JSON.stringify(entry)})`);
indexJSON.push(entry);
}
if (!isURL && file !== path.resolve(destination)) {
if (!fs.existsSync(path.dirname(destination))) {
fs.mkdirSync(path.dirname(destination));
}
fs.copyFileSync(file, destination);
}
fs.writeFileSync('index.json', JSON.stringify(indexJSON, null, ' '));
if (isURL) {
fs.unlinkSync(file);
}
}
}
main();

View File

@@ -1,29 +0,0 @@
const child_process = require('child_process');
const fs = require('fs');
const path = require('path');
const concatCaCerts = (folder = 'cacerts', outputFilename = 'cacerts.pem') => {
const files = fs.readdirSync(folder);
const caCertFiles = files.filter((file) => path.extname(file) === '.pem');
const outputFile = fs.openSync(outputFilename, 'w');
caCertFiles.forEach((caCert) => {
const filePath = path.join(folder, caCert);
const fileContent = fs.readFileSync(filePath, 'utf8');
fs.appendFileSync(outputFile, fileContent + '\n');
});
};
const main = async () => {
concatCaCerts();
const indexJSON = JSON.parse(fs.readFileSync('index.json'));
indexJSON.forEach(entry => {
const result = child_process.execSync(`node ./scripts/add.js "${entry.path || entry.url}" "${entry.modelId || ''}"`, {
cwd: path.dirname(__dirname)
})
console.log(result.toString())
})
}
return main();

95
src/autodl/github.ts Normal file
View File

@@ -0,0 +1,95 @@
import {getJson, getLatestImage, readCacheJson, writeCacheJson} from '../common.js';
import {processFirmwareImage} from '../process_firmware_image.js';
type ReleaseAssetJson = {
url: string;
id: number;
node_id: string;
name: string;
label: null;
uploader: Record<string, unknown>;
content_type: string;
state: string;
size: number;
download_count: number;
created_at: string;
updated_at: string;
browser_download_url: string;
};
type ReleaseJson = {
url: string;
assets_url: string;
upload_url: string;
html_url: string;
id: number;
author: Record<string, unknown>;
node_id: string;
tag_name: string;
target_commitish: string;
name: string;
draft: false;
prerelease: false;
created_at: string;
published_at: string;
assets: ReleaseAssetJson[];
tarball_url: string;
zipball_url: string;
body: string;
reactions: Record<string, unknown>;
};
type ReleasesJson = ReleaseJson[];
type AssetFindPredicate = (value: ReleaseAssetJson, index: number, obj: ReleaseAssetJson[]) => unknown;
function sortByPublishedAt(a: ReleaseJson, b: ReleaseJson): number {
return a.published_at < b.published_at ? -1 : a.published_at > b.published_at ? 1 : 0;
}
function isDifferent(newData: ReleaseAssetJson, cachedData?: ReleaseAssetJson): boolean {
return Boolean(process.env.IGNORE_CACHE) || !cachedData || cachedData.updated_at !== newData.updated_at;
}
export async function writeCache(manufacturer: string, releasesUrl: string): Promise<void> {
const releases = await getJson<ReleasesJson>(manufacturer, releasesUrl);
if (releases?.length) {
writeCacheJson(manufacturer, releases);
}
}
export async function download(manufacturer: string, releasesUrl: string, assetFinders: AssetFindPredicate[]): Promise<void> {
const logPrefix = `[${manufacturer}]`;
const releases = await getJson<ReleasesJson>(manufacturer, releasesUrl);
if (releases?.length) {
const release = getLatestImage(releases, sortByPublishedAt);
if (release) {
const cachedData = readCacheJson<ReleasesJson | undefined>(manufacturer);
const cached = cachedData?.length ? getLatestImage(cachedData, sortByPublishedAt) : undefined;
for (const assetFinder of assetFinders) {
const asset = release.assets.find(assetFinder);
if (asset) {
const cachedAsset = cached?.assets.find(assetFinder);
if (!isDifferent(asset, cachedAsset)) {
console.log(`[${manufacturer}:${asset.name}] No change from last run.`);
continue;
}
await processFirmwareImage(manufacturer, asset.name, asset.browser_download_url, {
manufacturerName: [manufacturer],
releaseNotes: release.html_url,
});
} else {
console.error(`${logPrefix} No image found.`);
}
}
} else {
console.error(`${logPrefix} No release found.`);
}
writeCacheJson(manufacturer, releases);
}
}

76
src/autodl/gmmts.ts Normal file
View File

@@ -0,0 +1,76 @@
import {getJson, readCacheJson, writeCacheJson} from '../common.js';
import {processFirmwareImage} from '../process_firmware_image.js';
type ImagesJsonBuildPart = {
path: string; // .bin
offset: number;
type?: 'app' | 'storage';
ota?: string; // .ota
};
type ImagesJsonBuild = {
chipFamily: string;
target: string;
parts: ImagesJsonBuildPart[];
};
type ImagesJson = {
name: string;
version: string;
home_assistant_domain: string;
funding_url: string;
new_install_prompt_erase: boolean;
builds: ImagesJsonBuild[];
};
const NAME = 'Gmmts';
// const LOG_PREFIX = `[${NAME}]`;
const BASE_URL = 'https://update.gammatroniques.fr/';
const MANIFEST_URL_PATH = `/manifest.json`;
const MODEL_IDS = ['ticmeter'];
function isDifferent(newData: ImagesJson, cachedData?: ImagesJson): boolean {
return Boolean(process.env.IGNORE_CACHE) || !cachedData || cachedData.version !== newData.version;
}
export async function writeCache(): Promise<void> {
for (const modelId of MODEL_IDS) {
const url = `${BASE_URL}${modelId}${MANIFEST_URL_PATH}`;
const page = await getJson<ImagesJson>(NAME, url);
if (page?.builds?.length) {
writeCacheJson(`${NAME}_${modelId}`, page);
}
}
}
export async function download(): Promise<void> {
for (const modelId of MODEL_IDS) {
const logPrefix = `[${NAME}:${modelId}]`;
const url = `${BASE_URL}${modelId}${MANIFEST_URL_PATH}`;
const page = await getJson<ImagesJson>(NAME, url);
if (!page?.builds?.length) {
console.error(`${logPrefix} No image data.`);
continue;
}
const cacheFileName = `${NAME}_${modelId}`;
if (!isDifferent(page, readCacheJson(cacheFileName))) {
console.log(`${logPrefix} No change from last run.`);
continue;
}
writeCacheJson(cacheFileName, page);
const appUrl: ImagesJsonBuildPart | undefined = page.builds[0].parts.find((part) => part.type === 'app');
if (!appUrl || !appUrl.ota) {
console.error(`${logPrefix} No image found.`);
continue;
}
const firmwareFileName = appUrl.ota.split('/').pop()!;
await processFirmwareImage(NAME, firmwareFileName, appUrl.ota, {manufacturerName: [NAME]});
}
}

84
src/autodl/ikea.ts Normal file
View File

@@ -0,0 +1,84 @@
import {getJson, readCacheJson, writeCacheJson} from '../common.js';
import {processFirmwareImage} from '../process_firmware_image.js';
type GatewayImageJson = {
fw_binary_url: string;
fw_filesize: number;
fw_hotfix_version: number;
fw_major_version: number;
fw_minor_version: number;
fw_req_hotfix_version: number;
fw_req_major_version: number;
fw_req_minor_version: number;
fw_type: 0;
fw_update_prio: number;
fw_weblink_relnote: string;
};
type DeviceImageJson = {
fw_binary_url: string;
fw_file_version_LSB: number;
fw_file_version_MSB: number;
fw_filesize: number;
fw_image_type: number;
fw_manufacturer_id: number;
fw_type: 2;
};
type ImagesJson = (GatewayImageJson | DeviceImageJson)[];
const NAME = 'IKEA';
const LOG_PREFIX = `[${NAME}]`;
const PRODUCTION_FIRMWARE_URL = 'http://fw.ota.homesmart.ikea.net/feed/version_info.json';
// const TEST_FIRMWARE_URL = 'http://fw.test.ota.homesmart.ikea.net/feed/version_info.json';
export const RELEASE_NOTES_URL = 'https://ww8.ikea.com/ikeahomesmart/releasenotes/releasenotes.html';
function findInCache(image: DeviceImageJson, cachedData?: ImagesJson): DeviceImageJson | undefined {
// `fw_type` compare ensures always `DeviceImagesJson`
return cachedData?.find(
(d) => d.fw_type == image.fw_type && d.fw_image_type == image.fw_image_type && d.fw_manufacturer_id == image.fw_manufacturer_id,
) as DeviceImageJson | undefined;
}
function isDifferent(newData: DeviceImageJson, cachedData?: DeviceImageJson): boolean {
return (
Boolean(process.env.IGNORE_CACHE) ||
!cachedData ||
cachedData.fw_file_version_LSB !== newData.fw_file_version_LSB ||
cachedData.fw_file_version_MSB !== newData.fw_file_version_MSB
);
}
export async function writeCache(): Promise<void> {
const images = await getJson<ImagesJson>(NAME, PRODUCTION_FIRMWARE_URL);
if (images?.length) {
writeCacheJson(NAME, images);
}
}
export async function download(): Promise<void> {
const images = await getJson<ImagesJson>(NAME, PRODUCTION_FIRMWARE_URL);
if (images?.length) {
const cachedData = readCacheJson<ImagesJson | undefined>(NAME);
for (const image of images) {
if (image.fw_type !== 2) {
// ignore gateway firmware
continue;
}
const firmwareFileName = image.fw_binary_url.split('/').pop()!;
if (!isDifferent(image, findInCache(image, cachedData))) {
console.log(`[${NAME}:${firmwareFileName}] No change from last run.`);
continue;
}
await processFirmwareImage(NAME, firmwareFileName, image.fw_binary_url, {manufacturerName: [NAME], releaseNotes: RELEASE_NOTES_URL});
}
writeCacheJson(NAME, images);
} else {
console.error(`${LOG_PREFIX} No image data.`);
}
}

75
src/autodl/ikea_new.ts Normal file
View File

@@ -0,0 +1,75 @@
import {getJson, readCacheJson, writeCacheJson} from '../common.js';
import {processFirmwareImage} from '../process_firmware_image.js';
import {RELEASE_NOTES_URL} from './ikea.js';
type GatewayImageJson = {
fw_type: 3;
fw_sha3_256: string;
fw_binary_url: string;
fw_update_prio: number;
fw_filesize: number;
fw_minor_version: number;
fw_major_version: number;
fw_hotfix_version: number;
fw_binary_checksum: string;
};
type DeviceImageJson = {
fw_image_type: number;
fw_type: 2;
fw_sha3_256: string;
fw_binary_url: string;
};
type ImagesJson = (GatewayImageJson | DeviceImageJson)[];
// same name as `ikea.ts` to keep everything in same folder
const NAME = 'IKEA';
const CACHE_FILENAME = `${NAME}_new`;
const LOG_PREFIX = `[${NAME}_new]`;
// requires cacerts/ikea_new.pem
const FIRMWARE_URL = 'https://fw.ota.homesmart.ikea.com/check/update/prod';
function findInCache(image: DeviceImageJson, cachedData?: ImagesJson): DeviceImageJson | undefined {
// `fw_type` compare ensures always `DeviceImagesJson`
return cachedData?.find((d) => d.fw_type == image.fw_type && d.fw_image_type == image.fw_image_type) as DeviceImageJson | undefined;
}
function isDifferent(newData: DeviceImageJson, cachedData?: DeviceImageJson): boolean {
return Boolean(process.env.IGNORE_CACHE) || !cachedData || cachedData.fw_sha3_256 !== newData.fw_sha3_256;
}
export async function writeCache(): Promise<void> {
const images = await getJson<ImagesJson>(NAME, FIRMWARE_URL);
if (images?.length) {
writeCacheJson(CACHE_FILENAME, images);
}
}
export async function download(): Promise<void> {
const images = await getJson<ImagesJson>(NAME, FIRMWARE_URL);
if (images?.length) {
const cachedData = readCacheJson<ImagesJson | undefined>(CACHE_FILENAME);
for (const image of images) {
if (image.fw_type !== 2) {
// ignore gateway firmware
continue;
}
const firmwareFileName = image.fw_binary_url.split('/').pop()!;
if (!isDifferent(image, findInCache(image, cachedData))) {
console.log(`[${NAME}:${firmwareFileName}] No change from last run.`);
continue;
}
await processFirmwareImage(NAME, firmwareFileName, image.fw_binary_url, {manufacturerName: [NAME], releaseNotes: RELEASE_NOTES_URL});
}
writeCacheJson(CACHE_FILENAME, images);
} else {
console.error(`${LOG_PREFIX} No image data.`);
}
}

72
src/autodl/inovelli.ts Normal file
View File

@@ -0,0 +1,72 @@
import {getJson, getLatestImage, readCacheJson, writeCacheJson} from '../common.js';
import {processFirmwareImage} from '../process_firmware_image.js';
type DeviceImageJson = {
version: string;
channel: 'beta' | 'production';
firmware: string;
manufacturer_id: number;
image_type: number;
};
type ModelsJson = {
[k: string]: DeviceImageJson[];
};
const NAME = 'Inovelli';
const LOG_PREFIX = `[${NAME}]`;
const FIRMWARE_URL = 'https://files.inovelli.com/firmware/firmware.json';
function sortByVersion(a: DeviceImageJson, b: DeviceImageJson): number {
const aRadix = a.version.match(/[a-fA-F]/) ? 16 : 10;
const bRadix = b.version.match(/[a-fA-F]/) ? 16 : 10;
const aVersion = parseInt(a.version, aRadix);
const bVersion = parseInt(b.version, bRadix);
return aVersion < bVersion ? -1 : aVersion > bVersion ? 1 : 0;
}
function isDifferent(newData: DeviceImageJson, cachedData?: DeviceImageJson): boolean {
return Boolean(process.env.IGNORE_CACHE) || !cachedData || cachedData.version !== newData.version;
}
export async function writeCache(): Promise<void> {
const models = await getJson<ModelsJson>(NAME, FIRMWARE_URL);
if (models) {
writeCacheJson(NAME, models);
}
}
export async function download(): Promise<void> {
const models = await getJson<ModelsJson>(NAME, FIRMWARE_URL);
if (models) {
const cachedData = readCacheJson<ModelsJson | undefined>(NAME);
for (const model in models) {
if (model == '') {
// ignore empty key (bug)
continue;
}
const image = getLatestImage(models[model], sortByVersion);
if (!image) {
continue;
}
const firmwareFileName = image.firmware.split('/').pop()!;
if (cachedData && !isDifferent(image, getLatestImage(cachedData[model], sortByVersion))) {
console.log(`[${NAME}:${firmwareFileName}] No change from last run.`);
continue;
}
await processFirmwareImage(NAME, firmwareFileName, image.firmware, {manufacturerName: [NAME]});
}
writeCacheJson(NAME, models);
} else {
console.error(`${LOG_PREFIX} No image data.`);
}
}

91
src/autodl/jethome.ts Normal file
View File

@@ -0,0 +1,91 @@
import {getJson, readCacheJson, writeCacheJson} from '../common.js';
import {processFirmwareImage} from '../process_firmware_image.js';
type ImageJson = {
vendor: string;
vendor_name: string;
device: string;
device_name: string;
platform: string;
platform_name: string;
latest_firmware: {
release: {
version: string;
date: string;
images: {
'zigbee.ota': {
url: string;
hash: string;
filesize: number;
};
'zigbee.bin': {
url: string;
hash: string;
filesize: number;
};
};
changelog: string;
};
};
};
const NAME = 'Jethome';
const LOG_PREFIX = `[${NAME}]`;
const BASE_URL = 'https://fw.jethome.ru';
const DEVICE_URL = `${BASE_URL}/api/devices/`;
const MODEL_IDS = ['WS7'];
function getCacheFileName(modelId: string): string {
return `${NAME}_${modelId}`;
}
function isDifferent(newData: ImageJson, cachedData?: ImageJson): boolean {
return Boolean(process.env.IGNORE_CACHE) || !cachedData || cachedData.latest_firmware.release.version !== newData.latest_firmware.release.version;
}
export async function writeCache(): Promise<void> {
for (const modelId of MODEL_IDS) {
const url = `${DEVICE_URL}${modelId}/info`;
const image = await getJson<ImageJson>(NAME, url);
if (image?.latest_firmware?.release?.images) {
writeCacheJson(getCacheFileName(modelId), image);
}
}
}
export async function download(): Promise<void> {
for (const modelId of MODEL_IDS) {
const url = `${DEVICE_URL}${modelId}/info`;
const image = await getJson<ImageJson>(NAME, url);
// XXX: this is assumed to always be present even for devices that support OTA but without images yet available?
if (image?.latest_firmware?.release?.images) {
const firmware = image.latest_firmware.release.images['zigbee.ota'];
if (!firmware) {
continue;
}
const firmwareUrl = BASE_URL + firmware.url;
const firmwareFileName = firmwareUrl.split('/').pop()!;
const cacheFileName = getCacheFileName(modelId);
if (!isDifferent(image, readCacheJson(cacheFileName))) {
console.log(`[${NAME}:${firmwareFileName}] No change from last run.`);
continue;
}
writeCacheJson(cacheFileName, image);
await processFirmwareImage(NAME, firmwareFileName, firmwareUrl, {
manufacturerName: [NAME],
releaseNotes: BASE_URL + image.latest_firmware.release.changelog,
});
} else {
console.error(`${LOG_PREFIX} No image data for ${modelId}.`);
continue;
}
}
}

128
src/autodl/ledvance.ts Normal file
View File

@@ -0,0 +1,128 @@
import {getJson, getLatestImage, readCacheJson, writeCacheJson} from '../common.js';
import {processFirmwareImage, ProcessFirmwareImageStatus} from '../process_firmware_image.js';
type FirmwareJson = {
blob: null;
identity: {
company: number;
product: number;
version: {
major: number;
minor: number;
build: number;
revision: number;
};
};
releaseNotes: string;
/** Ledvance's API docs state the checksum should be `sha_256` but it is actually `shA256` */
shA256: string;
name: string;
productName: string;
/**
* The fileVersion in hex is included in the fullName between the `/`, e.g.:
* - PLUG COMPACT EU T/032b3674/PLUG_COMPACT_EU_T-0x00D6-0x032B3674-MF_DIS.OTA
* - A19 RGBW/00102428/A19_RGBW_IMG0019_00102428-encrypted.ota
*/
fullName: string;
extension: string;
released: string;
salesRegion: string;
length: number;
};
type ImagesJson = {
firmwares: FirmwareJson[];
};
type GroupedImagesJson = Record<string, FirmwareJson[]>;
const NAME = 'Ledvance';
const LOG_PREFIX = `[${NAME}]`;
const FIRMWARE_URL = 'https://api.update.ledvance.com/v1/zigbee/firmwares/';
// const UPDATE_CHECK_URL = 'https://api.update.ledvance.com/v1/zigbee/firmwares/newer';
// const UPDATE_CHECK_PARAMS = `?company=${manufCode}&product=${imageType}&version=0.0.0`;
const UPDATE_DOWNLOAD_URL = 'https://api.update.ledvance.com/v1/zigbee/firmwares/download';
/** XXX: getting 429 after a few downloads, force more throttling. Seems to trigger after around ~20 requests. */
const FETCH_FAILED_THROTTLE_MS = 60000;
const FETCH_FAILED_RETRIES = 3;
function groupByProduct(arr: FirmwareJson[]): GroupedImagesJson {
return arr.reduce<GroupedImagesJson>((acc, cur) => {
acc[cur.identity.product] = [...(acc[cur.identity.product] || []), cur];
return acc;
}, {});
}
function sortByReleased(a: FirmwareJson, b: FirmwareJson): number {
return a.released < b.released ? -1 : a.released > b.released ? 1 : 0;
}
function getVersionString(firmware: FirmwareJson): string {
const {major, minor, build, revision} = firmware.identity.version;
return `${major}.${minor}.${build}.${revision}`;
}
function isDifferent(newData: FirmwareJson, cachedData?: FirmwareJson): boolean {
return Boolean(process.env.IGNORE_CACHE) || !cachedData || getVersionString(cachedData) !== getVersionString(newData);
}
export async function writeCache(): Promise<void> {
const images = await getJson<ImagesJson>(NAME, FIRMWARE_URL);
if (images?.firmwares?.length) {
writeCacheJson(NAME, images);
}
}
export async function download(): Promise<void> {
const images = await getJson<ImagesJson>(NAME, FIRMWARE_URL);
if (images?.firmwares?.length) {
const cachedData = readCacheJson<ImagesJson | undefined>(NAME);
const cachedDataByProduct = cachedData?.firmwares?.length ? groupByProduct(cachedData.firmwares) : undefined;
const firmwareByProduct = groupByProduct(images.firmwares);
for (const product in firmwareByProduct) {
const firmware = getLatestImage(firmwareByProduct[product], sortByReleased);
if (!firmware) {
console.error(`${LOG_PREFIX} No image found for ${product}.`);
continue;
}
const fileVersionMatch = /\/(\d|\w+)\//.exec(firmware.fullName);
if (fileVersionMatch == null) {
// ignore possible unsupported patterns
continue;
}
// const fileVersion = parseInt(fileVersionMatch[1], 16);
const firmwareUrl = `${UPDATE_DOWNLOAD_URL}?company=${firmware.identity.company}&product=${firmware.identity.product}&version=${getVersionString(firmware)}`;
const firmwareFileName = firmware.fullName.split('/').pop()!;
if (cachedDataByProduct && !isDifferent(firmware, getLatestImage(cachedDataByProduct[product], sortByReleased))) {
console.log(`[${NAME}:${firmwareFileName}] No change from last run.`);
continue;
}
for (let i = 0; i < FETCH_FAILED_RETRIES; i++) {
const status = await processFirmwareImage(NAME, firmwareFileName, firmwareUrl, {
manufacturerName: [NAME],
// workflow automatically computes sha512
// sha256: firmware.shA256,
releaseNotes: firmware.releaseNotes,
});
if (status === ProcessFirmwareImageStatus.REQUEST_FAILED) {
await new Promise((resolve) => setTimeout(resolve, FETCH_FAILED_THROTTLE_MS));
} else {
break;
}
}
}
writeCacheJson(NAME, images);
} else {
console.error(`${LOG_PREFIX} No image data.`);
}
}

15
src/autodl/lixee.ts Normal file
View File

@@ -0,0 +1,15 @@
import * as github from './github.js';
const NAME = 'Lixee';
const FIRMWARE_URL = 'https://api.github.com/repos/fairecasoimeme/Zlinky_TIC/releases';
/** @see https://github.com/fairecasoimeme/Zlinky_TIC?tab=readme-ov-file#route-or-limited-route-from-v7 */
const FIRMWARE_EXT = '.ota';
const FIRMWARE_LIMITED = `limited${FIRMWARE_EXT}`;
export async function writeCache(): Promise<void> {
await github.writeCache(NAME, FIRMWARE_URL);
}
export async function download(): Promise<void> {
await github.download(NAME, FIRMWARE_URL, [(a): boolean => a.name.endsWith(FIRMWARE_EXT), (a): boolean => a.name.endsWith(FIRMWARE_LIMITED)]);
}

55
src/autodl/salus.ts Normal file
View File

@@ -0,0 +1,55 @@
import {getJson, readCacheJson, writeCacheJson} from '../common.js';
import {processFirmwareImage} from '../process_firmware_image.js';
type ImageJson = {
model: string;
version: string;
url: string;
};
type ImagesJson = {
versions: ImageJson[];
};
const NAME = 'Salus';
const LOG_PREFIX = `[${NAME}]`;
const FIRMWARE_URL = 'https://eu.salusconnect.io/demo/default/status/firmware?timestamp=0';
function findInCache(image: ImageJson, cachedData?: ImagesJson): ImageJson | undefined {
return cachedData?.versions?.find((d) => d.model == image.model);
}
function isDifferent(newData: ImageJson, cachedData?: ImageJson): boolean {
return Boolean(process.env.IGNORE_CACHE) || !cachedData || cachedData.version !== newData.version;
}
export async function writeCache(): Promise<void> {
const images = await getJson<ImagesJson>(NAME, FIRMWARE_URL);
if (images?.versions?.length) {
writeCacheJson(NAME, images);
}
}
export async function download(): Promise<void> {
const images = await getJson<ImagesJson>(NAME, FIRMWARE_URL);
if (images?.versions?.length) {
const cachedData = readCacheJson<ImagesJson | undefined>(NAME);
for (const image of images.versions) {
const archiveUrl = image.url; //.replace(/^http:\/\//, 'https://');
const archiveFileName = archiveUrl.split('/').pop()!;
if (!isDifferent(image, findInCache(image, cachedData))) {
console.log(`[${NAME}:${archiveFileName}] No change from last run.`);
continue;
}
await processFirmwareImage(NAME, archiveFileName, archiveUrl, {manufacturerName: [NAME]}, true, (fileName) => fileName.endsWith('.ota'));
}
writeCacheJson(NAME, images);
} else {
console.error(`${LOG_PREFIX} No image data.`);
}
}

104
src/autodl/ubisys.ts Normal file
View File

@@ -0,0 +1,104 @@
import url from 'url';
import {getLatestImage, getText, readCacheJson, writeCacheJson} from '../common.js';
import {processFirmwareImage} from '../process_firmware_image.js';
type Image = {
fileName: string;
imageType: string;
hardwareVersionMin: number;
hardwareVersionMax: number;
fileVersion: number;
};
type GroupedImages = {
[k: string]: Image[];
};
const NAME = 'Ubisys';
const LOG_PREFIX = `[${NAME}]`;
const FIRMWARE_HTML_URL = 'http://fwu.ubisys.de/smarthome/OTA/release/index';
function groupByImageType(arr: Image[]): GroupedImages {
return arr.reduce<GroupedImages>((acc, cur) => {
acc[cur.imageType] = [...(acc[cur.imageType] || []), cur];
return acc;
}, {});
}
function sortByFileVersion(a: Image, b: Image): number {
return a.fileVersion < b.fileVersion ? -1 : a.fileVersion > b.fileVersion ? 1 : 0;
}
function isDifferent(newData: Image, cachedData?: Image): boolean {
return Boolean(process.env.IGNORE_CACHE) || !cachedData || cachedData.fileVersion !== newData.fileVersion;
}
function parseText(pageText: string): Image[] {
const lines = pageText.split('\n');
const images: Image[] = [];
for (const line of lines) {
// XXX: there are other images on the page that do not match this pattern
const imageMatch = /10F2-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{8})\S*ota1?\.zigbee/gi.exec(line);
if (imageMatch != null) {
images.push({
fileName: imageMatch[0],
imageType: imageMatch[1],
hardwareVersionMin: parseInt(imageMatch[2], 16),
hardwareVersionMax: parseInt(imageMatch[3], 16),
fileVersion: parseInt(imageMatch[4], 16),
});
}
}
return images;
}
export async function writeCache(): Promise<void> {
const pageText = await getText(NAME, FIRMWARE_HTML_URL);
if (pageText?.length) {
const images = parseText(pageText);
writeCacheJson(NAME, images);
}
}
export async function download(): Promise<void> {
const pageText = await getText(NAME, FIRMWARE_HTML_URL);
if (pageText?.length) {
const images = parseText(pageText);
const imagesByType = groupByImageType(images);
const cachedData = readCacheJson<Image[] | undefined>(NAME);
const cachedDataByType = cachedData ? groupByImageType(cachedData) : undefined;
for (const imageType in imagesByType) {
const image = getLatestImage(imagesByType[imageType], sortByFileVersion);
if (!image) {
console.error(`${LOG_PREFIX} No image found for ${imageType}.`);
continue;
}
if (cachedDataByType && !isDifferent(image, getLatestImage(cachedDataByType[imageType], sortByFileVersion))) {
console.log(`[${NAME}:${image.fileName}] No change from last run.`);
continue;
}
// NOTE: removes `index` from url
const firmwareUrl = url.resolve(FIRMWARE_HTML_URL, image.fileName);
await processFirmwareImage(NAME, image.fileName, firmwareUrl, {
manufacturerName: [NAME],
hardwareVersionMin: image.hardwareVersionMin,
hardwareVersionMax: image.hardwareVersionMax,
});
}
writeCacheJson(NAME, images);
} else {
console.error(`${LOG_PREFIX} No image data.`);
}
}

13
src/autodl/xyzroe.ts Normal file
View File

@@ -0,0 +1,13 @@
import * as github from './github.js';
const NAME = 'Xyzroe';
const FIRMWARE_URL = 'https://api.github.com/repos/xyzroe/ZigUSB_C6/releases';
const FIRMWARE_EXT = '.ota';
export async function writeCache(): Promise<void> {
await github.writeCache(NAME, FIRMWARE_URL);
}
export async function download(): Promise<void> {
await github.download(NAME, FIRMWARE_URL, [(a): boolean => a.name.endsWith(FIRMWARE_EXT)]);
}

406
src/common.ts Normal file
View File

@@ -0,0 +1,406 @@
import type {ExtraMetas, ExtraMetasWithFileName, ImageHeader, RepoImageMeta} from './types';
import assert from 'assert';
import {exec} from 'child_process';
import {createHash} from 'crypto';
import {existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync} from 'fs';
import path from 'path';
export const UPGRADE_FILE_IDENTIFIER = Buffer.from([0x1e, 0xf1, 0xee, 0x0b]);
export const BASE_REPO_URL = `https://github.com/Koenkk/zigbee-OTA/raw/`;
export const REPO_BRANCH = 'master';
/** Images used by OTA upgrade process */
export const BASE_IMAGES_DIR = 'images';
/** Images used by OTA downgrade process */
export const PREV_IMAGES_DIR = 'images1';
/** Manifest used by OTA upgrade process */
export const BASE_INDEX_MANIFEST_FILENAME = 'index.json';
/** Manifest used by OTA downgrade process */
export const PREV_INDEX_MANIFEST_FILENAME = 'index1.json';
export const CACHE_DIR = '.cache';
export const TMP_DIR = 'tmp';
/**
* 'ikea_new' first, to prioritize downloads from new URL
*/
export const ALL_AUTODL_MANUFACTURERS = ['gmmts', 'ikea_new', 'ikea', 'inovelli', 'jethome', 'ledvance', 'lixee', 'salus', 'ubisys', 'xyzroe'];
export async function execute(command: string): Promise<string> {
return await new Promise((resolve, reject) => {
exec(command, (error, stdout) => {
if (error) {
reject(error);
} else {
resolve(stdout);
}
});
});
}
export function primitivesArrayEquals(a: (string | number | boolean)[], b: (string | number | boolean)[]): boolean {
return a.length === b.length && a.every((val, index) => val === b[index]);
}
export function computeSHA512(buffer: Buffer): string {
const hash = createHash('sha512');
hash.update(buffer);
return hash.digest('hex');
}
export function getOutDir(folderName: string, basePath: string = BASE_IMAGES_DIR): string {
const outDir = path.join(basePath, folderName);
if (!existsSync(outDir)) {
mkdirSync(outDir, {recursive: true});
}
return outDir;
}
export function getRepoFirmwareFileUrl(folderName: string, fileName: string, basePath: string = BASE_IMAGES_DIR): string {
return BASE_REPO_URL + path.posix.join(REPO_BRANCH, basePath, folderName, fileName);
}
export function writeManifest(fileName: string, firmwareList: RepoImageMeta[]): void {
writeFileSync(fileName, JSON.stringify(firmwareList, undefined, 2), 'utf8');
}
export function readManifest(fileName: string): RepoImageMeta[] {
return JSON.parse(readFileSync(fileName, 'utf8'));
}
export function writeCacheJson<T>(fileName: string, contents: T, basePath: string = CACHE_DIR): void {
writeFileSync(path.join(basePath, `${fileName}.json`), JSON.stringify(contents), 'utf8');
}
export function readCacheJson<T>(fileName: string, basePath: string = CACHE_DIR): T {
const filePath = path.join(basePath, `${fileName}.json`);
return existsSync(filePath) ? JSON.parse(readFileSync(filePath, 'utf8')) : undefined;
}
export function parseImageHeader(buffer: Buffer): ImageHeader {
try {
const header: ImageHeader = {
otaUpgradeFileIdentifier: buffer.subarray(0, 4),
otaHeaderVersion: buffer.readUInt16LE(4),
otaHeaderLength: buffer.readUInt16LE(6),
otaHeaderFieldControl: buffer.readUInt16LE(8),
manufacturerCode: buffer.readUInt16LE(10),
imageType: buffer.readUInt16LE(12),
fileVersion: buffer.readUInt32LE(14),
zigbeeStackVersion: buffer.readUInt16LE(18),
otaHeaderString: buffer.toString('utf8', 20, 52),
totalImageSize: buffer.readUInt32LE(52),
};
let headerPos = 56;
if (header.otaHeaderFieldControl & 1) {
header.securityCredentialVersion = buffer.readUInt8(headerPos);
headerPos += 1;
}
if (header.otaHeaderFieldControl & 2) {
header.upgradeFileDestination = buffer.subarray(headerPos, headerPos + 8);
headerPos += 8;
}
if (header.otaHeaderFieldControl & 4) {
header.minimumHardwareVersion = buffer.readUInt16LE(headerPos);
headerPos += 2;
header.maximumHardwareVersion = buffer.readUInt16LE(headerPos);
headerPos += 2;
}
assert(UPGRADE_FILE_IDENTIFIER.equals(header.otaUpgradeFileIdentifier), `Invalid upgrade file identifier`);
return header;
} catch (error) {
throw new Error(`Not a valid OTA file (${(error as Error).message}).`);
}
}
/**
* Adapted from zigbee-herdsman-converters logic
*/
export function findMatchImage(
image: ImageHeader,
imageList: RepoImageMeta[],
extraMetas: ExtraMetas,
): [index: number, image: RepoImageMeta | undefined] {
const imageIndex = imageList.findIndex(
(i) =>
i.imageType === image.imageType &&
i.manufacturerCode === image.manufacturerCode &&
(!i.minFileVersion || image.fileVersion >= i.minFileVersion) &&
(!i.maxFileVersion || image.fileVersion <= i.maxFileVersion) &&
i.modelId === extraMetas.modelId &&
(!(i.manufacturerName && extraMetas.manufacturerName) || primitivesArrayEquals(i.manufacturerName, extraMetas.manufacturerName)),
);
return [imageIndex, imageIndex === -1 ? undefined : imageList[imageIndex]];
}
export function changeRepoUrl(repoUrl: string, fromDir: string, toDir: string): string {
return repoUrl.replace(path.posix.join(REPO_BRANCH, fromDir), path.posix.join(REPO_BRANCH, toDir));
}
export async function getJson<T>(manufacturer: string, pageUrl: string): Promise<T | undefined> {
const response = await fetch(pageUrl);
if (!response.ok || !response.body) {
console.error(`[${manufacturer}] Invalid response from ${pageUrl} status=${response.status}.`);
return;
}
return (await response.json()) as T;
}
export async function getText(manufacturer: string, pageUrl: string): Promise<string | undefined> {
const response = await fetch(pageUrl);
if (!response.ok || !response.body) {
console.error(`[${manufacturer}] Invalid response from ${pageUrl} status=${response.status}.`);
return;
}
return await response.text();
}
export function getLatestImage<T>(list: T[], compareFn: (a: T, b: T) => number): T | undefined {
const sortedList = list.sort(compareFn);
return sortedList.slice(0, sortedList.length > 1 && process.env.PREV ? -1 : undefined).pop();
}
export const enum ParsedImageStatus {
NEW = 0,
NEWER = 1,
OLDER = 2,
IDENTICAL = 3,
}
export function getParsedImageStatus(parsedImage: ImageHeader, match?: RepoImageMeta): ParsedImageStatus {
if (match) {
if (match.fileVersion > parsedImage.fileVersion) {
return ParsedImageStatus.OLDER;
} else if (match.fileVersion < parsedImage.fileVersion) {
return ParsedImageStatus.NEWER;
} else {
return ParsedImageStatus.IDENTICAL;
}
} else {
return ParsedImageStatus.NEW;
}
}
/**
* Prevent irrelevant metas from being added to manifest.
*
* NOTE: fileName should be deleted before adding to manifest for consistency (always use original file name).
* @param metas
* @returns
*/
export function getValidMetas(metas: Partial<ExtraMetas & ExtraMetasWithFileName & RepoImageMeta>, ignoreFileName: boolean): ExtraMetasWithFileName {
const validMetas: ExtraMetasWithFileName = {};
if (!ignoreFileName) {
if (metas.fileName != undefined) {
if (typeof metas.fileName != 'string') {
throw new Error(`Invalid format for 'fileName', expected 'string' type.`);
}
validMetas.fileName = metas.fileName;
}
}
if (metas.originalUrl != undefined) {
if (typeof metas.originalUrl != 'string') {
throw new Error(`Invalid format for 'originalUrl', expected 'string' type.`);
}
validMetas.originalUrl = metas.originalUrl;
}
if (metas.force != undefined) {
if (typeof metas.force != 'boolean') {
throw new Error(`Invalid format for 'force', expected 'boolean' type.`);
}
validMetas.force = metas.force;
}
if (metas.hardwareVersionMax != undefined) {
if (typeof metas.hardwareVersionMax != 'number') {
throw new Error(`Invalid format for 'hardwareVersionMax', expected 'number' type.`);
}
validMetas.hardwareVersionMax = metas.hardwareVersionMax;
}
if (metas.hardwareVersionMin != undefined) {
if (typeof metas.hardwareVersionMin != 'number') {
throw new Error(`Invalid format for 'hardwareVersionMin', expected 'number' type.`);
}
validMetas.hardwareVersionMin = metas.hardwareVersionMin;
}
if (metas.manufacturerName != undefined) {
if (!Array.isArray(metas.manufacturerName) || metas.manufacturerName.length < 1 || metas.manufacturerName.some((m) => typeof m != 'string')) {
throw new Error(`Invalid format for 'manufacturerName', expected 'array of string' type.`);
}
validMetas.manufacturerName = metas.manufacturerName;
}
if (metas.maxFileVersion != undefined) {
if (typeof metas.maxFileVersion != 'number') {
throw new Error(`Invalid format for 'maxFileVersion', expected 'number' type.`);
}
validMetas.maxFileVersion = metas.maxFileVersion;
}
if (metas.minFileVersion != undefined) {
if (typeof metas.minFileVersion != 'number') {
throw new Error(`Invalid format for 'minFileVersion', expected 'number' type.`);
}
validMetas.minFileVersion = metas.minFileVersion;
}
if (metas.modelId != undefined) {
if (typeof metas.modelId != 'string') {
throw new Error(`Invalid format for 'modelId', expected 'string' type.`);
}
validMetas.modelId = metas.modelId;
}
if (metas.releaseNotes != undefined) {
if (typeof metas.releaseNotes != 'string') {
throw new Error(`Invalid format for 'releaseNotes', expected 'string' type.`);
}
validMetas.releaseNotes = metas.releaseNotes;
}
return validMetas;
}
export function addImageToPrev(
logPrefix: string,
isNewer: boolean,
prevManifest: RepoImageMeta[],
prevMatchIndex: number,
prevMatch: RepoImageMeta,
prevOutDir: string,
firmwareFileName: string,
manufacturer: string,
parsedImage: ImageHeader,
firmwareBuffer: Buffer,
originalUrl: string | undefined,
extraMetas: ExtraMetas,
onBeforeManifestPush: () => void,
): void {
console.log(`${logPrefix} Base manifest has higher version. Adding to prev instead.`);
if (isNewer) {
console.log(`${logPrefix} Removing prev image.`);
prevManifest.splice(prevMatchIndex, 1);
// make sure fileName exists for migration from old system
const prevFileName = prevMatch.fileName ? prevMatch.fileName : prevMatch.url.split('/').pop()!;
rmSync(path.join(prevOutDir, prevFileName), {force: true});
}
onBeforeManifestPush();
prevManifest.push({
fileName: firmwareFileName,
fileVersion: parsedImage.fileVersion,
fileSize: parsedImage.totalImageSize,
originalUrl,
url: getRepoFirmwareFileUrl(manufacturer, firmwareFileName, PREV_IMAGES_DIR),
imageType: parsedImage.imageType,
manufacturerCode: parsedImage.manufacturerCode,
sha512: computeSHA512(firmwareBuffer),
otaHeaderString: parsedImage.otaHeaderString,
...extraMetas,
});
}
export function addImageToBase(
logPrefix: string,
isNewer: boolean,
prevManifest: RepoImageMeta[],
prevOutDir: string,
baseManifest: RepoImageMeta[],
baseMatchIndex: number,
baseMatch: RepoImageMeta,
baseOutDir: string,
firmwareFileName: string,
manufacturer: string,
parsedImage: ImageHeader,
firmwareBuffer: Buffer,
originalUrl: string | undefined,
extraMetas: ExtraMetas,
onBeforeManifestPush: () => void,
): void {
if (isNewer) {
console.log(`${logPrefix} Base manifest has older version ${baseMatch.fileVersion}. Replacing with ${parsedImage.fileVersion}.`);
const [prevMatchIndex, prevMatch] = findMatchImage(parsedImage, prevManifest, extraMetas);
const prevStatus = getParsedImageStatus(parsedImage, prevMatch);
if (prevStatus !== ParsedImageStatus.OLDER && prevStatus !== ParsedImageStatus.NEW) {
console.warn(`${logPrefix} Base image is new/newer but prev image is not older/non-existing.`);
}
if (prevStatus !== ParsedImageStatus.NEW) {
console.log(`${logPrefix} Removing prev image.`);
prevManifest.splice(prevMatchIndex, 1);
// make sure fileName exists for migration from old system
const prevFileName = prevMatch!.fileName ? prevMatch!.fileName : prevMatch!.url.split('/').pop()!;
rmSync(path.join(prevOutDir, prevFileName), {force: true});
}
// relocate base to prev
// make sure fileName exists for migration from old system
const baseFileName = baseMatch.fileName ? baseMatch.fileName : baseMatch.url.split('/').pop()!;
const baseFilePath = path.join(baseOutDir, baseFileName);
// if for some reason the file is no longer present (should not happen), don't add it to prev since link is broken
if (existsSync(baseFilePath)) {
renameSync(baseFilePath, path.join(prevOutDir, baseFileName));
baseMatch!.url = changeRepoUrl(baseMatch.url, BASE_IMAGES_DIR, PREV_IMAGES_DIR);
prevManifest.push(baseMatch);
} else {
console.error(`${logPrefix} Image file '${baseFilePath}' does not exist. Not moving to prev.`);
}
baseManifest.splice(baseMatchIndex, 1);
} else {
console.log(`${logPrefix} Base manifest does not have version ${parsedImage.fileVersion}. Adding.`);
}
onBeforeManifestPush();
baseManifest.push({
fileName: firmwareFileName,
fileVersion: parsedImage.fileVersion,
fileSize: parsedImage.totalImageSize,
originalUrl,
url: getRepoFirmwareFileUrl(manufacturer, firmwareFileName, BASE_IMAGES_DIR),
imageType: parsedImage.imageType,
manufacturerCode: parsedImage.manufacturerCode,
sha512: computeSHA512(firmwareBuffer),
otaHeaderString: parsedImage.otaHeaderString,
...extraMetas,
});
}

29
src/ghw_concat_cacerts.ts Normal file
View File

@@ -0,0 +1,29 @@
import type CoreApi from '@actions/core';
import type {Context} from '@actions/github/lib/context';
import type {Octokit} from '@octokit/rest';
import {readdirSync, readFileSync, writeFileSync} from 'fs';
import path from 'path';
export const CACERTS_DIR = 'cacerts';
export const CACERTS_CONCAT_FILEPATH = 'cacerts.pem';
// eslint-disable-next-line @typescript-eslint/no-unused-vars
export async function concatCaCerts(github: Octokit, core: typeof CoreApi, context: Context): Promise<void> {
let pemContents: string = '';
for (const pem of readdirSync(CACERTS_DIR)) {
if (!pem.endsWith('.pem')) {
continue;
}
core.startGroup(pem);
pemContents += readFileSync(path.join(CACERTS_DIR, pem), 'utf8');
pemContents += '\n';
core.endGroup();
}
writeFileSync(CACERTS_CONCAT_FILEPATH, pemContents, 'utf8');
}

View File

@@ -0,0 +1,89 @@
import type CoreApi from '@actions/core';
import type {Context} from '@actions/github/lib/context';
import type {Octokit} from '@octokit/rest';
import {BASE_IMAGES_DIR, BASE_INDEX_MANIFEST_FILENAME, execute, PREV_IMAGES_DIR, PREV_INDEX_MANIFEST_FILENAME, readManifest} from './common.js';
import {RepoImageMeta} from './types.js';
// about 3 lines
const MAX_RELEASE_NOTES_LENGTH = 380;
function findReleaseNotes(imagePath: string, manifest: RepoImageMeta[]): string | undefined {
const metas = manifest.find((m) => m.url.endsWith(imagePath));
return metas?.releaseNotes;
}
function listItemWithReleaseNotes(imagePath: string, releaseNotes?: string): string {
let listItem = `* ${imagePath}`;
if (releaseNotes) {
let notes = releaseNotes.replace(/[#*\r\n]+/g, '').replaceAll('-', '|');
if (notes.length > MAX_RELEASE_NOTES_LENGTH) {
notes = `${notes.slice(0, MAX_RELEASE_NOTES_LENGTH)}...`;
}
listItem += `
- ${notes}`;
}
return listItem;
}
export async function createAutodlRelease(github: Octokit, core: typeof CoreApi, context: Context): Promise<void> {
const tagName = new Date().toISOString().replace(/[:.]/g, '');
// --exclude-standard => Add the standard Git exclusions: .git/info/exclude, .gitignore in each directory, and the users global exclusion file.
// --others => Show other (i.e. untracked) files in the output.
// -z => \0 line termination on output and do not quote filenames.
const upgradeImagesStr = await execute(`git ls-files --others --exclude-standard --modified -z ${BASE_IMAGES_DIR}`);
const downgradeImagesStr = await execute(`git ls-files --others --exclude-standard --modified -z ${PREV_IMAGES_DIR}`);
core.debug(`git ls-files for ${BASE_IMAGES_DIR}: ${upgradeImagesStr}`);
core.debug(`git ls-files for ${PREV_IMAGES_DIR}: ${downgradeImagesStr}`);
// -1 to remove empty string at end due to \0 termination
const upgradeImages = upgradeImagesStr.split('\0').slice(0, -1);
const downgradeImages = downgradeImagesStr.split('\0').slice(0, -1);
core.info(`Upgrade Images List: ${upgradeImages}`);
core.info(`Downgrade Images List: ${downgradeImages}`);
const baseManifest = readManifest(BASE_INDEX_MANIFEST_FILENAME);
const prevManifest = readManifest(PREV_INDEX_MANIFEST_FILENAME);
let body: string | undefined;
if (upgradeImages.length > 0 || downgradeImages.length > 0) {
body = '';
if (upgradeImages.length > 0) {
const listWithReleaseNotes = upgradeImages.map((v) => listItemWithReleaseNotes(v, findReleaseNotes(v, baseManifest)));
body += `## New upgrade images from automatic download:
${listWithReleaseNotes.join('\n')}
`;
}
if (downgradeImages.length > 0) {
const listWithReleaseNotes = downgradeImages.map((v) => listItemWithReleaseNotes(v, findReleaseNotes(v, prevManifest)));
body += `## New downgrade images from automatic download:
${listWithReleaseNotes.join('\n')}
`;
}
}
await github.rest.repos.createRelease({
owner: context.repo.owner,
repo: context.repo.repo,
tag_name: tagName,
name: tagName,
body,
draft: false,
prerelease: false,
// get changes from PRs
generate_release_notes: true,
make_latest: 'true',
});
}

View File

@@ -0,0 +1,57 @@
import type CoreApi from '@actions/core';
import type {Context} from '@actions/github/lib/context';
import type {Octokit} from '@octokit/rest';
import assert from 'assert';
const IGNORE_OTA_WORKFLOW_LABEL = 'ignore-ota-workflow';
export async function createPRToDefault(
github: Octokit,
core: typeof CoreApi,
context: Context,
fromBranchName: string,
title: string,
): Promise<void> {
assert(context.payload.repository);
assert(fromBranchName);
assert(title);
const base = context.payload.repository.default_branch;
try {
const createdPRResult = await github.rest.pulls.create({
owner: context.repo.owner,
repo: context.repo.repo,
head: fromBranchName,
base,
title,
});
await github.rest.issues.addLabels({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: createdPRResult.data.number,
labels: [IGNORE_OTA_WORKFLOW_LABEL],
});
core.notice(`Created pull request #${createdPRResult.data.number} from branch ${fromBranchName}.`);
} catch (error) {
if (error instanceof Error) {
if (error.message.includes(`No commits between ${base} and ${fromBranchName}`)) {
await github.rest.git.deleteRef({
owner: context.repo.owner,
repo: context.repo.repo,
ref: `heads/${fromBranchName}`,
});
core.notice(`Nothing needed re-processing.`);
// don't fail if no commits
return;
}
}
throw error;
}
}

View File

@@ -0,0 +1,41 @@
import type CoreApi from '@actions/core';
import type {Context} from '@actions/github/lib/context';
import type {Octokit} from '@octokit/rest';
import {existsSync, mkdirSync} from 'fs';
import {ALL_AUTODL_MANUFACTURERS, CACHE_DIR} from './common.js';
export async function overwriteCache(github: Octokit, core: typeof CoreApi, context: Context, manufacturersCSV?: string): Promise<void> {
if (!existsSync(CACHE_DIR)) {
mkdirSync(CACHE_DIR, {recursive: true});
}
const manufacturers = manufacturersCSV ? manufacturersCSV.trim().split(',') : ALL_AUTODL_MANUFACTURERS;
for (const manufacturer of manufacturers) {
// ignore empty strings
if (!manufacturer) {
continue;
}
if (!ALL_AUTODL_MANUFACTURERS.includes(manufacturer)) {
core.error(`Ignoring invalid manufacturer '${manufacturer}'. Expected any of: ${ALL_AUTODL_MANUFACTURERS}.`);
continue;
}
const {writeCache} = await import(`./${manufacturer}.js`);
core.startGroup(manufacturer);
core.info(`[${manufacturer}] Writing cache...`);
try {
await writeCache();
} catch (error) {
core.error((error as Error).message);
core.debug((error as Error).stack!);
}
core.endGroup();
}
}

View File

@@ -0,0 +1,398 @@
import type CoreApi from '@actions/core';
import type {Context} from '@actions/github/lib/context';
import type {Octokit} from '@octokit/rest';
import type {RepoImageMeta} from './types';
import {existsSync, lstatSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, writeFileSync} from 'fs';
import path from 'path';
import {
addImageToBase,
addImageToPrev,
BASE_IMAGES_DIR,
BASE_INDEX_MANIFEST_FILENAME,
BASE_REPO_URL,
computeSHA512,
findMatchImage,
getOutDir,
getParsedImageStatus,
getRepoFirmwareFileUrl,
getValidMetas,
ParsedImageStatus,
parseImageHeader,
PREV_IMAGES_DIR,
PREV_INDEX_MANIFEST_FILENAME,
readManifest,
REPO_BRANCH,
UPGRADE_FILE_IDENTIFIER,
writeManifest,
} from './common.js';
/** These are now handled by autodl */
const IGNORE_3RD_PARTIES = ['https://github.com/fairecasoimeme/', 'https://github.com/xyzroe/'];
const DIR_3RD_PARTIES = {
'https://otau.meethue.com/': 'Hue',
'https://images.tuyaeu.com/': 'Tuya',
'https://tr-zha.s3.amazonaws.com/': 'ThirdReality',
// NOTE: no longer valid / unable to access via script
// 'https://www.elektroimportoren.no/docs/lib/4512772-Firmware-35.ota': 'Namron',
// 'https://deconz.dresden-elektronik.de/': 'DresdenElektronik',
};
export const NOT_IN_BASE_MANIFEST_IMAGES_DIR = 'not-in-manifest-images';
export const NOT_IN_PREV_MANIFEST_IMAGES_DIR = 'not-in-manifest-images1';
export const NOT_IN_MANIFEST_FILENAME = 'not-in-manifest.json';
function ignore3rdParty(meta: RepoImageMeta): boolean {
for (const ignore of IGNORE_3RD_PARTIES) {
if (meta.url.startsWith(ignore)) {
return true;
}
}
return false;
}
function get3rdPartyDir(meta: RepoImageMeta): string | undefined {
for (const key in DIR_3RD_PARTIES) {
if (meta.url.startsWith(key)) {
return DIR_3RD_PARTIES[key as keyof typeof DIR_3RD_PARTIES];
}
}
}
async function download3rdParties(
github: Octokit,
core: typeof CoreApi,
context: Context,
/* istanbul ignore next */
outDirFinder = get3rdPartyDir,
): Promise<void> {
if (!process.env.NODE_EXTRA_CA_CERTS) {
throw new Error(`Download 3rd Parties requires \`NODE_EXTRA_CA_CERTS=cacerts.pem\`.`);
}
const baseManifest = readManifest(BASE_INDEX_MANIFEST_FILENAME);
const baseManifestCopy = baseManifest.slice();
const prevManifest = readManifest(PREV_INDEX_MANIFEST_FILENAME);
let baseImagesAddCount = 0;
let prevImagesAddCount = 0;
for (const meta of baseManifestCopy) {
// just in case
if (!meta.url) {
core.error(`Ignoring malformed ${JSON.stringify(meta)}.`);
baseManifest.splice(baseManifest.indexOf(meta), 1);
continue;
}
if (meta.url.startsWith(BASE_REPO_URL + REPO_BRANCH)) {
core.debug(`Ignoring local URL: ${meta.url}`);
continue;
}
// remove itself from base manifest
baseManifest.splice(baseManifest.indexOf(meta), 1);
if (ignore3rdParty(meta)) {
core.warning(`Removing ignored '${meta.url}'.`);
continue;
}
// reverse add.js logic
const fileName = unescape(meta.url.split('/').pop()!);
const outDirName = outDirFinder(meta);
if (outDirName) {
core.info(`Downloading 3rd party '${fileName}' into '${outDirName}'`);
let firmwareFilePath: string | undefined;
try {
const baseOutDir = getOutDir(outDirName, BASE_IMAGES_DIR);
const prevOutDir = getOutDir(outDirName, PREV_IMAGES_DIR);
const extraMetas = getValidMetas(meta, true);
core.info(`Extra metas for ${fileName}: ${JSON.stringify(extraMetas)}.`);
const firmwareFile = await fetch(meta.url);
if (!firmwareFile.ok || !firmwareFile.body) {
core.error(`Invalid response from ${meta.url} status=${firmwareFile.status}.`);
continue;
}
const firmwareBuffer = Buffer.from(await firmwareFile.arrayBuffer());
// make sure to parse from the actual start of the "spec OTA" portion of the file (e.g. Ikea has non-spec meta before)
const parsedImage = parseImageHeader(firmwareBuffer.subarray(firmwareBuffer.indexOf(UPGRADE_FILE_IDENTIFIER)));
const [baseMatchIndex, baseMatch] = findMatchImage(parsedImage, baseManifest, extraMetas);
const statusToBase = getParsedImageStatus(parsedImage, baseMatch);
switch (statusToBase) {
case ParsedImageStatus.OLDER: {
addImageToPrev(
`[${fileName}]`,
false, // no prev existed before
prevManifest,
-1,
// @ts-expect-error false above prevents issue
undefined,
prevOutDir,
fileName,
outDirName,
parsedImage,
firmwareBuffer,
meta.url,
extraMetas,
() => {
firmwareFilePath = path.join(prevOutDir, fileName);
// write before adding to manifest, in case of failure (throw), manifest won't have a broken link
writeFileSync(firmwareFilePath, firmwareBuffer);
},
);
prevImagesAddCount++;
break;
}
case ParsedImageStatus.IDENTICAL: {
core.warning(`Conflict with image at index \`${baseMatchIndex}\`: ${JSON.stringify(baseMatch)}`);
continue;
}
case ParsedImageStatus.NEWER:
case ParsedImageStatus.NEW: {
addImageToBase(
`[${fileName}]`,
statusToBase === ParsedImageStatus.NEWER,
prevManifest,
prevOutDir,
baseManifest,
baseMatchIndex,
baseMatch!,
baseOutDir,
fileName,
outDirName,
parsedImage,
firmwareBuffer,
meta.url,
extraMetas,
() => {
firmwareFilePath = path.join(baseOutDir, fileName);
// write before adding to manifest, in case of failure (throw), manifest won't have a broken link
writeFileSync(firmwareFilePath, firmwareBuffer);
},
);
baseImagesAddCount++;
break;
}
}
} catch (error) {
core.error(`Ignoring ${fileName}: ${error}`);
/* istanbul ignore next */
if (firmwareFilePath) {
rmSync(firmwareFilePath, {force: true});
}
continue;
}
} else {
core.warning(`Ignoring '${fileName}' with no out dir specified.`);
}
}
writeManifest(PREV_INDEX_MANIFEST_FILENAME, prevManifest);
writeManifest(BASE_INDEX_MANIFEST_FILENAME, baseManifest);
core.info(`Downloaded ${prevImagesAddCount} prev images.`);
core.info(`Downloaded ${baseImagesAddCount} base images.`);
core.info(`Base manifest now contains ${baseManifest.length} images.`);
core.info(`Prev manifest now contains ${prevManifest.length} images.`);
}
function checkImagesAgainstManifests(github: Octokit, core: typeof CoreApi, context: Context, removeNotInManifest: boolean): void {
for (const [manifestName, imagesDir, moveDir] of [
[PREV_INDEX_MANIFEST_FILENAME, PREV_IMAGES_DIR, NOT_IN_PREV_MANIFEST_IMAGES_DIR],
[BASE_INDEX_MANIFEST_FILENAME, BASE_IMAGES_DIR, NOT_IN_BASE_MANIFEST_IMAGES_DIR],
]) {
const manifest = readManifest(manifestName);
const rewriteManifest: RepoImageMeta[] = [];
const missingManifest: RepoImageMeta[] = [];
core.info(`Checking ${manifestName} (currently ${manifest.length} images)...`);
for (const subfolderName of readdirSync(imagesDir)) {
// skip removal of anything not desired while running jest tests
// compare should match data.test.ts > IMAGES_TEST_DIR
/* istanbul ignore if */
if (process.env.JEST_WORKER_ID && subfolderName !== 'jest-tmp') {
continue;
}
const subfolderPath = path.join(imagesDir, subfolderName);
if (lstatSync(subfolderPath).isDirectory()) {
core.startGroup(subfolderPath);
for (const fileName of readdirSync(subfolderPath)) {
const firmwareFilePath = path.join(subfolderPath, fileName);
const fileRelUrl = path.posix.join(imagesDir, subfolderName, fileName);
// previous add.js used escape() for url property
const escFileRelUrl = escape(fileRelUrl);
// take local images only
const inManifest = manifest.filter(
(m) => m.url.startsWith(BASE_REPO_URL + REPO_BRANCH) && (m.url.endsWith(fileRelUrl) || m.url.endsWith(escFileRelUrl)),
);
if (inManifest.length === 0) {
core.warning(`Not found in base manifest: ${firmwareFilePath}.`);
if (removeNotInManifest) {
core.error(`Removing ${firmwareFilePath}.`);
rmSync(firmwareFilePath, {force: true});
} else {
const destDirPath = path.join(moveDir, subfolderName);
if (!existsSync(destDirPath)) {
mkdirSync(destDirPath, {recursive: true});
}
try {
const firmwareBuffer = Buffer.from(readFileSync(firmwareFilePath));
// make sure to parse from the actual start of the "spec OTA" portion of the file (e.g. Ikea has non-spec meta before)
const parsedImage = parseImageHeader(firmwareBuffer.subarray(firmwareBuffer.indexOf(UPGRADE_FILE_IDENTIFIER)));
renameSync(firmwareFilePath, path.join(destDirPath, fileName));
missingManifest.push({
fileName,
fileVersion: parsedImage.fileVersion,
fileSize: parsedImage.totalImageSize,
// originalUrl: meta.url,
url: getRepoFirmwareFileUrl(subfolderName, fileName, imagesDir),
imageType: parsedImage.imageType,
manufacturerCode: parsedImage.manufacturerCode,
sha512: computeSHA512(firmwareBuffer),
otaHeaderString: parsedImage.otaHeaderString,
});
} catch (error) {
core.error(`Removing ${firmwareFilePath}: ${error}`);
rmSync(firmwareFilePath, {force: true});
}
}
} else {
if (inManifest.length !== 1) {
core.warning(`[${fileRelUrl}] found multiple times in ${manifestName} manifest:`);
core.warning(JSON.stringify(inManifest, undefined, 2));
}
for (const meta of inManifest) {
try {
const firmwareBuffer = Buffer.from(readFileSync(firmwareFilePath));
const extraMetas = getValidMetas(meta, true);
// make sure to parse from the actual start of the "spec OTA" portion of the file (e.g. Ikea has non-spec meta before)
const parsedImage = parseImageHeader(firmwareBuffer.subarray(firmwareBuffer.indexOf(UPGRADE_FILE_IDENTIFIER)));
const [, rewriteMatch] = findMatchImage(parsedImage, rewriteManifest, extraMetas);
// only add if not already present
if (!rewriteMatch) {
rewriteManifest.push({
fileName,
fileVersion: parsedImage.fileVersion,
fileSize: parsedImage.totalImageSize,
// originalUrl: meta.url,
url: getRepoFirmwareFileUrl(subfolderName, fileName, imagesDir),
imageType: parsedImage.imageType,
manufacturerCode: parsedImage.manufacturerCode,
sha512: computeSHA512(firmwareBuffer),
otaHeaderString: parsedImage.otaHeaderString,
...extraMetas,
});
}
} catch (error) {
core.error(`Removing ${firmwareFilePath}: ${error}`);
rmSync(firmwareFilePath, {force: true});
}
}
}
}
core.endGroup();
} else {
// subfolderName here would actually be the file name
throw new Error(`Detected file in ${imagesDir} not in subdirectory: ${subfolderName}.`);
}
}
// will not run in case removeNotInManifest is true, since nothing added, `moveDir` will also already have been created
if (missingManifest.length > 0) {
writeManifest(path.join(moveDir, NOT_IN_MANIFEST_FILENAME), missingManifest);
core.error(`${missingManifest.length} images not in ${manifestName} manifest.`);
}
writeManifest(manifestName, rewriteManifest);
core.info(`Rewritten ${manifestName} manifest has ${rewriteManifest.length} images.`);
}
}
/**
*
* @param github
* @param core
* @param context
* @param removeNotInManifest If false, move images to separate directories
* @param skipDownload3rdParties Do not execute the download step
* @param downloadOutDirFinder Used mainly for jest tests
*/
export async function reProcessAllImages(
github: Octokit,
core: typeof CoreApi,
context: Context,
removeNotInManifest: boolean,
skipDownload3rdParties: boolean,
downloadOutDirFinder = get3rdPartyDir,
): Promise<void> {
if (!removeNotInManifest && existsSync(NOT_IN_BASE_MANIFEST_IMAGES_DIR) && readdirSync(NOT_IN_BASE_MANIFEST_IMAGES_DIR).length > 0) {
throw new Error(`${NOT_IN_BASE_MANIFEST_IMAGES_DIR} is not empty. Cannot run.`);
}
if (!removeNotInManifest && existsSync(NOT_IN_PREV_MANIFEST_IMAGES_DIR) && readdirSync(NOT_IN_PREV_MANIFEST_IMAGES_DIR).length > 0) {
throw new Error(`${NOT_IN_PREV_MANIFEST_IMAGES_DIR} is not empty. Cannot run.`);
}
/* istanbul ignore if */
if (!existsSync(BASE_IMAGES_DIR)) {
mkdirSync(BASE_IMAGES_DIR, {recursive: true});
}
/* istanbul ignore if */
if (!existsSync(PREV_IMAGES_DIR)) {
mkdirSync(PREV_IMAGES_DIR, {recursive: true});
}
/* istanbul ignore if */
if (!existsSync(BASE_INDEX_MANIFEST_FILENAME)) {
writeManifest(BASE_INDEX_MANIFEST_FILENAME, []);
}
/* istanbul ignore if */
if (!existsSync(PREV_INDEX_MANIFEST_FILENAME)) {
writeManifest(PREV_INDEX_MANIFEST_FILENAME, []);
}
if (!skipDownload3rdParties) {
await download3rdParties(github, core, context, downloadOutDirFinder);
}
checkImagesAgainstManifests(github, core, context, removeNotInManifest);
}

58
src/ghw_run_autodl.ts Normal file
View File

@@ -0,0 +1,58 @@
import type CoreApi from '@actions/core';
import type {Context} from '@actions/github/lib/context';
import type {Octokit} from '@octokit/rest';
import {existsSync, mkdirSync, rmSync} from 'fs';
import {ALL_AUTODL_MANUFACTURERS, BASE_INDEX_MANIFEST_FILENAME, CACHE_DIR, PREV_INDEX_MANIFEST_FILENAME, TMP_DIR, writeManifest} from './common.js';
export async function runAutodl(github: Octokit, core: typeof CoreApi, context: Context, manufacturersCSV?: string): Promise<void> {
const manufacturers = manufacturersCSV ? manufacturersCSV.trim().split(',') : ALL_AUTODL_MANUFACTURERS;
core.info(`Setup...`);
if (!existsSync(CACHE_DIR)) {
mkdirSync(CACHE_DIR, {recursive: true});
}
if (!existsSync(TMP_DIR)) {
mkdirSync(TMP_DIR, {recursive: true});
}
if (!existsSync(BASE_INDEX_MANIFEST_FILENAME)) {
writeManifest(BASE_INDEX_MANIFEST_FILENAME, []);
}
if (!existsSync(PREV_INDEX_MANIFEST_FILENAME)) {
writeManifest(PREV_INDEX_MANIFEST_FILENAME, []);
}
for (const manufacturer of manufacturers) {
// ignore empty strings
if (!manufacturer) {
continue;
}
if (!ALL_AUTODL_MANUFACTURERS.includes(manufacturer)) {
core.error(`Ignoring invalid manufacturer '${manufacturer}'. Expected any of: ${ALL_AUTODL_MANUFACTURERS}.`);
continue;
}
const {download} = await import(`./autodl/${manufacturer}.js`);
core.startGroup(manufacturer);
try {
await download();
} catch (error) {
core.error((error as Error).message);
core.debug((error as Error).stack!);
}
core.endGroup();
}
core.info(`Teardown...`);
rmSync(TMP_DIR, {recursive: true, force: true});
}

307
src/ghw_update_ota_pr.ts Normal file
View File

@@ -0,0 +1,307 @@
import type CoreApi from '@actions/core';
import type {Context} from '@actions/github/lib/context';
import type {Octokit} from '@octokit/rest';
import type {ExtraMetas, GHExtraMetas} from './types';
import assert from 'assert';
import {readFileSync, renameSync} from 'fs';
import path from 'path';
import {
addImageToBase,
addImageToPrev,
BASE_IMAGES_DIR,
BASE_INDEX_MANIFEST_FILENAME,
execute,
findMatchImage,
getOutDir,
getParsedImageStatus,
getValidMetas,
ParsedImageStatus,
parseImageHeader,
PREV_IMAGES_DIR,
PREV_INDEX_MANIFEST_FILENAME,
readManifest,
UPGRADE_FILE_IDENTIFIER,
writeManifest,
} from './common.js';
const EXTRA_METAS_PR_BODY_START_TAG = '```json';
const EXTRA_METAS_PR_BODY_END_TAG = '```';
function getFileExtraMetas(extraMetas: GHExtraMetas, fileName: string): ExtraMetas {
if (Array.isArray(extraMetas)) {
const fileExtraMetas = extraMetas.find((m) => m.fileName === fileName) ?? {};
/** @see getValidMetas */
delete fileExtraMetas.fileName;
return fileExtraMetas;
}
// not an array, use same metas for all files
return extraMetas;
}
async function parsePRBodyExtraMetas(github: Octokit, core: typeof CoreApi, context: Context): Promise<GHExtraMetas> {
let extraMetas: GHExtraMetas = {};
if (context.payload.pull_request?.body) {
try {
const prBody = context.payload.pull_request.body;
const metasStart = prBody.indexOf(EXTRA_METAS_PR_BODY_START_TAG);
const metasEnd = prBody.lastIndexOf(EXTRA_METAS_PR_BODY_END_TAG);
if (metasStart !== -1 && metasEnd > metasStart) {
const metas = JSON.parse(prBody.slice(metasStart + EXTRA_METAS_PR_BODY_START_TAG.length, metasEnd)) as GHExtraMetas;
core.info(`Extra metas from PR body:`);
core.info(JSON.stringify(metas, undefined, 2));
if (Array.isArray(metas)) {
extraMetas = [];
for (const meta of metas) {
if (!meta.fileName || typeof meta.fileName != 'string') {
core.info(`Ignoring meta in array with missing/invalid fileName:`);
core.info(JSON.stringify(meta, undefined, 2));
continue;
}
extraMetas.push(getValidMetas(meta, false));
}
} else {
extraMetas = getValidMetas(metas, false);
}
}
} catch (error) {
const failureComment = `Invalid extra metas in pull request body: ` + (error as Error).message;
core.error(failureComment);
await github.rest.issues.createComment({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: context.issue.number,
body: failureComment,
});
throw new Error(failureComment);
}
}
return extraMetas;
}
export async function updateOtaPR(github: Octokit, core: typeof CoreApi, context: Context, fileParam: string): Promise<void> {
assert(fileParam, 'No file found in pull request.');
assert(context.payload.pull_request, 'Not a pull request');
const fileParamArr = fileParam.trim().split(',');
// take care of empty strings (GH workflow adds a comma at end), ignore files not stored in images dir
const fileList = fileParamArr.filter((f) => f.startsWith(`${BASE_IMAGES_DIR}/`));
assert(fileList.length > 0, 'No image found in pull request.');
core.info(`Images in pull request: ${fileList}.`);
const fileListWrongDir = fileParamArr.filter((f) => f.startsWith(`${PREV_IMAGES_DIR}/`));
if (fileListWrongDir.length > 0) {
const failureComment = `Detected files in 'images1':
\`\`\`
${fileListWrongDir.join('\n')}
\`\`\`
Please move all files to 'images' (in appropriate subfolders). The pull request will automatically determine the proper location on merge.`;
await github.rest.issues.createComment({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: context.issue.number,
body: failureComment,
});
throw new Error(failureComment);
}
const fileListNoIndex = fileParamArr.filter((f) => f.startsWith(BASE_INDEX_MANIFEST_FILENAME) || f.startsWith(PREV_INDEX_MANIFEST_FILENAME));
if (fileListNoIndex.length > 0) {
const failureComment = `Detected manual changes in ${fileListNoIndex.join(', ')}. Please remove these changes. The pull request will automatically determine the manifests on merge.`;
await github.rest.issues.createComment({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: context.issue.number,
body: failureComment,
});
throw new Error(failureComment);
}
// called at the top, fail early if invalid PR body metas
const extraMetas = await parsePRBodyExtraMetas(github, core, context);
const baseManifest = readManifest(BASE_INDEX_MANIFEST_FILENAME);
const prevManifest = readManifest(PREV_INDEX_MANIFEST_FILENAME);
for (const file of fileList) {
core.startGroup(file);
core.info(`Processing '${file}'...`);
let failureComment: string = '';
try {
const firmwareFileName = path.basename(file);
const manufacturer = file.replace(BASE_IMAGES_DIR, '').replace(firmwareFileName, '').replaceAll('/', '').trim();
if (!manufacturer) {
throw new Error(`\`${file}\` should be in its associated manufacturer subfolder.`);
}
const firmwareBuffer = Buffer.from(readFileSync(file));
const parsedImage = parseImageHeader(firmwareBuffer.subarray(firmwareBuffer.indexOf(UPGRADE_FILE_IDENTIFIER)));
core.info(`[${file}] Parsed image header:`);
core.info(JSON.stringify(parsedImage, undefined, 2));
const fileExtraMetas = getFileExtraMetas(extraMetas, firmwareFileName);
core.info(`[${file}] Extra metas:`);
core.info(JSON.stringify(fileExtraMetas, undefined, 2));
const baseOutDir = getOutDir(manufacturer, BASE_IMAGES_DIR);
const prevOutDir = getOutDir(manufacturer, PREV_IMAGES_DIR);
const [baseMatchIndex, baseMatch] = findMatchImage(parsedImage, baseManifest, fileExtraMetas);
const statusToBase = getParsedImageStatus(parsedImage, baseMatch);
switch (statusToBase) {
case ParsedImageStatus.OLDER: {
// if prev doesn't have a match, move to prev
const [prevMatchIndex, prevMatch] = findMatchImage(parsedImage, prevManifest, fileExtraMetas);
const statusToPrev = getParsedImageStatus(parsedImage, prevMatch);
switch (statusToPrev) {
case ParsedImageStatus.OLDER:
case ParsedImageStatus.IDENTICAL: {
failureComment = `Base manifest has higher version:
\`\`\`json
${JSON.stringify(baseMatch, undefined, 2)}
\`\`\`
and an equal or better match is already present in prev manifest:
\`\`\`json
${JSON.stringify(prevMatch, undefined, 2)}
\`\`\`
Parsed image header:
\`\`\`json
${JSON.stringify(parsedImage, undefined, 2)}
\`\`\``;
break;
}
case ParsedImageStatus.NEWER:
case ParsedImageStatus.NEW: {
addImageToPrev(
`[${file}]`,
statusToPrev === ParsedImageStatus.NEWER,
prevManifest,
prevMatchIndex,
prevMatch!,
prevOutDir,
firmwareFileName,
manufacturer,
parsedImage,
firmwareBuffer,
undefined,
fileExtraMetas,
() => {
// relocate file to prev
renameSync(file, file.replace(`${BASE_IMAGES_DIR}/`, `${PREV_IMAGES_DIR}/`));
},
);
break;
}
}
break;
}
case ParsedImageStatus.IDENTICAL: {
failureComment = `Conflict with image at index \`${baseMatchIndex}\`:
\`\`\`json
${JSON.stringify(baseMatch, undefined, 2)}
\`\`\`
Parsed image header:
\`\`\`json
${JSON.stringify(parsedImage, undefined, 2)}
\`\`\``;
break;
}
case ParsedImageStatus.NEWER:
case ParsedImageStatus.NEW: {
addImageToBase(
`[${file}]`,
statusToBase === ParsedImageStatus.NEWER,
prevManifest,
prevOutDir,
baseManifest,
baseMatchIndex,
baseMatch!,
baseOutDir,
firmwareFileName,
manufacturer,
parsedImage,
firmwareBuffer,
undefined,
fileExtraMetas,
() => {
/* noop */
},
);
break;
}
}
} catch (error) {
failureComment = (error as Error).message;
}
if (failureComment) {
core.error(`[${file}] ` + failureComment);
await github.rest.pulls.createReviewComment({
owner: context.repo.owner,
repo: context.repo.repo,
pull_number: context.issue.number,
body: failureComment,
commit_id: context.payload.pull_request.head.sha,
path: file,
subject_type: 'file',
});
throw new Error(failureComment);
}
core.endGroup();
}
writeManifest(PREV_INDEX_MANIFEST_FILENAME, prevManifest);
writeManifest(BASE_INDEX_MANIFEST_FILENAME, baseManifest);
core.info(`Prev manifest has ${prevManifest.length} images.`);
core.info(`Base manifest has ${baseManifest.length} images.`);
if (!context.payload.pull_request.merged) {
const diff = await execute(`git diff`);
await github.rest.issues.createComment({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: context.issue.number,
body: `Merging this pull request will add these changes in a following commit:
\`\`\`diff
${diff}
\`\`\`
`,
});
}
}

9
src/index.ts Normal file
View File

@@ -0,0 +1,9 @@
export * as common from './common.js';
export {concatCaCerts} from './ghw_concat_cacerts.js';
export {createAutodlRelease} from './ghw_create_autodl_release.js';
export {createPRToDefault} from './ghw_create_pr_to_default.js';
export {overwriteCache} from './ghw_overwrite_cache.js';
export {reProcessAllImages} from './ghw_reprocess_all_images.js';
export {runAutodl} from './ghw_run_autodl.js';
export {updateOtaPR} from './ghw_update_ota_pr.js';
export {processFirmwareImage} from './process_firmware_image.js';

View File

@@ -0,0 +1,5 @@
import {readFileSync} from 'fs';
import {parseImageHeader} from './common.js';
console.log(parseImageHeader(readFileSync(process.argv[2])));

View File

@@ -0,0 +1,221 @@
import type {ExtraMetas} from './types';
import assert from 'assert';
import {readdirSync, readFileSync, renameSync, rmSync, writeFileSync} from 'fs';
import path from 'path';
import {extract} from 'tar';
import {
addImageToBase,
addImageToPrev,
BASE_IMAGES_DIR,
BASE_INDEX_MANIFEST_FILENAME,
findMatchImage,
getOutDir,
getParsedImageStatus,
ParsedImageStatus,
parseImageHeader,
PREV_IMAGES_DIR,
PREV_INDEX_MANIFEST_FILENAME,
readManifest,
TMP_DIR,
UPGRADE_FILE_IDENTIFIER,
writeManifest,
} from './common.js';
export const enum ProcessFirmwareImageStatus {
ERROR = -1,
SUCCESS = 0,
REQUEST_FAILED = 1,
TAR_NO_IMAGE = 2,
}
async function tarExtract(filePath: string, outDir: string, tarImageFinder: (fileName: string) => boolean): Promise<string> {
let outFileName: string | undefined;
try {
console.log(`[${filePath}] Extracting TAR...`);
await extract({file: filePath, cwd: TMP_DIR});
for (const file of readdirSync(TMP_DIR)) {
const archiveFilePath = path.join(TMP_DIR, file);
if (tarImageFinder(file)) {
outFileName = file;
renameSync(archiveFilePath, path.join(outDir, outFileName));
} else {
rmSync(archiveFilePath, {force: true});
}
}
} catch (error) {
console.error(error);
// force throw below, just in case something crashed in-between this being assigned and the end of the try block
outFileName = undefined;
}
// always remove archive file once done
rmSync(filePath, {force: true});
if (!outFileName) {
throw new Error(`No image found in ${filePath}.`);
}
return outFileName;
}
export async function processFirmwareImage(
manufacturer: string,
firmwareFileName: string,
firmwareFileUrl: string,
extraMetas: ExtraMetas = {},
tar: boolean = false,
tarImageFinder?: (fileName: string) => boolean,
): Promise<ProcessFirmwareImageStatus> {
// throttle requests (this is done at the top to ensure always executed)
await new Promise((resolve) => setTimeout(resolve, 300));
let firmwareFilePath: string | undefined;
const logPrefix = `[${manufacturer}:${firmwareFileName}]`;
if (tar && !firmwareFileName.endsWith('.tar.gz')) {
// ignore non-archive
return ProcessFirmwareImageStatus.TAR_NO_IMAGE;
}
const prevManifest = readManifest(PREV_INDEX_MANIFEST_FILENAME);
const baseManifest = readManifest(BASE_INDEX_MANIFEST_FILENAME);
const baseOutDir = getOutDir(manufacturer, BASE_IMAGES_DIR);
const prevOutDir = getOutDir(manufacturer, PREV_IMAGES_DIR);
try {
const firmwareFile = await fetch(firmwareFileUrl);
if (!firmwareFile.ok || !firmwareFile.body) {
console.error(`${logPrefix} Invalid response from ${firmwareFileUrl} status=${firmwareFile.status}.`);
return ProcessFirmwareImageStatus.REQUEST_FAILED;
}
if (tar) {
assert(tarImageFinder, `No image finder function supplied for tar.`);
const archiveBuffer = Buffer.from(await firmwareFile.arrayBuffer());
const archiveFilePath = path.join(baseOutDir, firmwareFileName);
writeFileSync(archiveFilePath, archiveBuffer);
try {
firmwareFileName = await tarExtract(archiveFilePath, baseOutDir, tarImageFinder);
} catch {
console.error(`${logPrefix} No image found for ${firmwareFileUrl}.`);
return ProcessFirmwareImageStatus.TAR_NO_IMAGE;
}
}
const firmwareBuffer = tar ? readFileSync(path.join(baseOutDir, firmwareFileName)) : Buffer.from(await firmwareFile.arrayBuffer());
// make sure to parse from the actual start of the "spec OTA" portion of the file (e.g. Ikea has non-spec meta before)
const parsedImage = parseImageHeader(firmwareBuffer.subarray(firmwareBuffer.indexOf(UPGRADE_FILE_IDENTIFIER)));
const [baseMatchIndex, baseMatch] = findMatchImage(parsedImage, baseManifest, extraMetas);
const statusToBase = getParsedImageStatus(parsedImage, baseMatch);
switch (statusToBase) {
case ParsedImageStatus.OLDER: {
// if prev doesn't have a match, move to prev
const [prevMatchIndex, prevMatch] = findMatchImage(parsedImage, prevManifest, extraMetas);
const statusToPrev = getParsedImageStatus(parsedImage, prevMatch);
switch (statusToPrev) {
case ParsedImageStatus.OLDER:
case ParsedImageStatus.IDENTICAL: {
console.log(
`${logPrefix} Base manifest has higher version and an equal or better match is already present in prev manifest. Ignoring.`,
);
break;
}
case ParsedImageStatus.NEWER:
case ParsedImageStatus.NEW: {
addImageToPrev(
logPrefix,
statusToPrev === ParsedImageStatus.NEWER,
prevManifest,
prevMatchIndex,
prevMatch!,
prevOutDir,
firmwareFileName,
manufacturer,
parsedImage,
firmwareBuffer,
firmwareFileUrl,
extraMetas,
() => {
firmwareFilePath = path.join(prevOutDir, firmwareFileName);
// write before adding to manifest, in case of failure (throw), manifest won't have a broken link
writeFileSync(firmwareFilePath, firmwareBuffer);
},
);
break;
}
}
break;
}
case ParsedImageStatus.IDENTICAL: {
console.log(`${logPrefix} Base manifest already has version ${parsedImage.fileVersion}. Ignoring.`);
break;
}
case ParsedImageStatus.NEWER:
case ParsedImageStatus.NEW: {
addImageToBase(
logPrefix,
statusToBase === ParsedImageStatus.NEWER,
prevManifest,
prevOutDir,
baseManifest,
baseMatchIndex,
baseMatch!,
baseOutDir,
firmwareFileName,
manufacturer,
parsedImage,
firmwareBuffer,
firmwareFileUrl,
extraMetas,
() => {
firmwareFilePath = path.join(baseOutDir, firmwareFileName);
// write before adding to manifest, in case of failure (throw), manifest won't have a broken link
writeFileSync(firmwareFilePath, firmwareBuffer);
},
);
break;
}
}
} catch (error) {
console.error(`${logPrefix} Failed to save firmware file ${firmwareFileName}: ${(error as Error).stack!}.`);
/* istanbul ignore if */
if (firmwareFilePath) {
rmSync(firmwareFilePath, {force: true});
}
return ProcessFirmwareImageStatus.ERROR;
}
writeManifest(PREV_INDEX_MANIFEST_FILENAME, prevManifest);
writeManifest(BASE_INDEX_MANIFEST_FILENAME, baseManifest);
console.log(`Prev manifest has ${prevManifest.length} images.`);
console.log(`Base manifest has ${baseManifest.length} images.`);
return ProcessFirmwareImageStatus.SUCCESS;
}

74
src/types.ts Normal file
View File

@@ -0,0 +1,74 @@
//-- Copied from ZHC
export interface Version {
imageType: number;
manufacturerCode: number;
fileVersion: number;
}
export interface ImageHeader {
otaUpgradeFileIdentifier: Buffer;
otaHeaderVersion: number;
otaHeaderLength: number;
otaHeaderFieldControl: number;
manufacturerCode: number;
imageType: number;
fileVersion: number;
zigbeeStackVersion: number;
otaHeaderString: string;
totalImageSize: number;
securityCredentialVersion?: number;
upgradeFileDestination?: Buffer;
minimumHardwareVersion?: number;
maximumHardwareVersion?: number;
}
export interface ImageElement {
tagID: number;
length: number;
data: Buffer;
}
export interface Image {
header: ImageHeader;
elements: ImageElement[];
raw: Buffer;
}
export interface ImageInfo {
imageType: number;
fileVersion: number;
manufacturerCode: number;
}
// XXX: adjusted from ZHC
export interface ImageMeta {
fileVersion: number;
fileSize: number;
url: string;
force?: boolean;
sha512: string;
otaHeaderString: string;
hardwareVersionMin?: number;
hardwareVersionMax?: number;
}
//-- Copied from ZHC
export interface RepoImageMeta extends ImageInfo, ImageMeta {
fileName: string;
modelId?: string;
manufacturerName?: string[];
minFileVersion?: number;
maxFileVersion?: number;
originalUrl?: string;
releaseNotes?: string;
}
export type ExtraMetas = Omit<
RepoImageMeta,
'fileName' | 'fileVersion' | 'fileSize' | 'url' | 'imageType' | 'manufacturerCode' | 'sha512' | 'otaHeaderString'
>;
export type ExtraMetasWithFileName = Omit<
RepoImageMeta,
'fileName' | 'fileVersion' | 'fileSize' | 'url' | 'imageType' | 'manufacturerCode' | 'sha512' | 'otaHeaderString'
> & {fileName?: string};
export type GHExtraMetas = ExtraMetas | ExtraMetasWithFileName[];

241
tests/data.test.ts Normal file
View File

@@ -0,0 +1,241 @@
/**
* Notes:
*
* - URLs are initially set to 'wherever the file should end up based on version'. For tests requiring special moves, they will need to be swapped.
*
*/
import type {ExtraMetas, RepoImageMeta} from '../src/types';
import {copyFileSync, existsSync, mkdirSync} from 'fs';
import path from 'path';
import * as common from '../src/common';
export const IMAGE_V14_1 = 'ZLinky_router_v14.ota';
export const IMAGE_V14_2 = 'ZLinky_router_v14_limited.ota';
export const IMAGE_V13_1 = 'ZLinky_router_v13.ota';
export const IMAGE_V13_2 = 'ZLinky_router_v13_limited.ota';
export const IMAGE_V12_1 = 'ZLinky_router_v12.ota';
export const IMAGE_V12_2 = 'ZLinky_router_v12_limited.ota';
export const IMAGE_INVALID = 'not-a-valid-file.ota';
export const IMAGE_TAR = '45856_00000006.tar.gz';
export const IMAGE_TAR_OTA = 'Jasco_5_0_1_OnOff_45856_v6.ota';
export const IMAGES_TEST_DIR = 'jest-tmp';
export const BASE_IMAGES_TEST_DIR_PATH = path.join(common.BASE_IMAGES_DIR, IMAGES_TEST_DIR);
export const PREV_IMAGES_TEST_DIR_PATH = path.join(common.PREV_IMAGES_DIR, IMAGES_TEST_DIR);
/**
* - otaUpgradeFileIdentifier: <Buffer 1e f1 ee 0b>,
* - otaHeaderVersion: 256,
* - otaHeaderLength: 56,
* - otaHeaderFieldControl: 0,
* - manufacturerCode: 4151,
* - imageType: 1,
* - fileVersion: 14,
* - zigbeeStackVersion: 2,
* - otaHeaderString: 'OM15081-RTR-JN5189-0000000000000',
* - totalImageSize: 249694
*/
export const IMAGE_V14_1_METAS = {
fileName: IMAGE_V14_1,
fileVersion: 14,
fileSize: 249694,
originalUrl: undefined,
url: `https://github.com/Koenkk/zigbee-OTA/raw/master/images/${IMAGES_TEST_DIR}/${IMAGE_V14_1}`,
imageType: 1,
manufacturerCode: 4151,
sha512: 'cc69b0745c72daf8deda935ba47aa7abd34dfcaaa4bc35bfa0605cd7937b0ecd8582ba0c08110df4f620c8aa87798d201f407d3d7e17198cfef1a4aa13c5013d',
otaHeaderString: 'OM15081-RTR-JN5189-0000000000000',
};
/**
* - otaUpgradeFileIdentifier: <Buffer 1e f1 ee 0b>,
* - otaHeaderVersion: 256,
* - otaHeaderLength: 56,
* - otaHeaderFieldControl: 0,
* - manufacturerCode: 4151,
* - imageType: 2,
* - fileVersion: 14,
* - zigbeeStackVersion: 2,
* - otaHeaderString: 'OM15081-RTR-LIMITED-JN5189-00000',
* - totalImageSize: 249694
*/
export const IMAGE_V14_2_METAS = {
fileName: IMAGE_V14_2,
fileVersion: 14,
fileSize: 249694,
originalUrl: undefined,
url: `https://github.com/Koenkk/zigbee-OTA/raw/master/images/${IMAGES_TEST_DIR}/${IMAGE_V14_2}`,
imageType: 2,
manufacturerCode: 4151,
sha512: 'f851cbff7297ba6223a969ba8da5182f9ef199cf9c8459c8408432e48485c1a8f018f6e1703a42f40143cccd3bf460c0acd92117d899e507a36845f24e970595',
otaHeaderString: 'OM15081-RTR-LIMITED-JN5189-00000',
};
/**
* - otaUpgradeFileIdentifier: <Buffer 1e f1 ee 0b>,
* - otaHeaderVersion: 256,
* - otaHeaderLength: 56,
* - otaHeaderFieldControl: 0,
* - manufacturerCode: 4151,
* - imageType: 1,
* - fileVersion: 13,
* - zigbeeStackVersion: 2,
* - otaHeaderString: 'OM15081-RTR-JN5189-0000000000000',
* - totalImageSize: 245406
*/
export const IMAGE_V13_1_METAS = {
fileName: IMAGE_V13_1,
fileVersion: 13,
fileSize: 245406,
originalUrl: undefined,
url: `https://github.com/Koenkk/zigbee-OTA/raw/master/images1/${IMAGES_TEST_DIR}/${IMAGE_V13_1}`,
imageType: 1,
manufacturerCode: 4151,
sha512: '4d7ab47dcb24e478e0abb35e691222b7691e77ed5a56de3f9c82e8682730649b1a154110b7207d4391c32eae53a869e20878e880fc153dbe046690b870be8486',
otaHeaderString: 'OM15081-RTR-JN5189-0000000000000',
};
/**
* - otaUpgradeFileIdentifier: <Buffer 1e f1 ee 0b>,
* - otaHeaderVersion: 256,
* - otaHeaderLength: 56,
* - otaHeaderFieldControl: 0,
* - manufacturerCode: 4151,
* - imageType: 2,
* - fileVersion: 13,
* - zigbeeStackVersion: 2,
* - otaHeaderString: 'OM15081-RTR-LIMITED-JN5189-00000',
* - totalImageSize: 245406
*/
export const IMAGE_V13_2_METAS = {
fileName: IMAGE_V13_2,
fileVersion: 13,
fileSize: 245406,
originalUrl: undefined,
url: `https://github.com/Koenkk/zigbee-OTA/raw/master/images1/${IMAGES_TEST_DIR}/${IMAGE_V13_2}`,
imageType: 2,
manufacturerCode: 4151,
sha512: 'dd77b28a3b4664e7ad944fcffaa9eca9f3adb0bbe598e12bdd6eece8070a8cdda6792bed378d173dd5b4532b4cdb88cebda0ef0c432c4c4d6581aa9f2bbba54d',
otaHeaderString: 'OM15081-RTR-LIMITED-JN5189-00000',
};
/**
* - otaUpgradeFileIdentifier: <Buffer 1e f1 ee 0b>,
* - otaHeaderVersion: 256,
* - otaHeaderLength: 56,
* - otaHeaderFieldControl: 0,
* - manufacturerCode: 4151,
* - imageType: 1,
* - fileVersion: 12,
* - zigbeeStackVersion: 2,
* - otaHeaderString: 'OM15081-RTR-JN5189-0000000000000',
* - totalImageSize: 245710
*/
export const IMAGE_V12_1_METAS = {
fileName: IMAGE_V12_1,
fileVersion: 12,
fileSize: 245710,
originalUrl: undefined,
url: `https://github.com/Koenkk/zigbee-OTA/raw/master/images1/${IMAGES_TEST_DIR}/${IMAGE_V12_1}`,
imageType: 1,
manufacturerCode: 4151,
sha512: '5d7e0a20141b78b85b4b046e623bc2bba24b28563464fe70227e79d0acdd5c0bde2adbd9d2557bd6cdfef2036d964c35c9e1746a8f1356af3325dd96f7a80e56',
otaHeaderString: 'OM15081-RTR-JN5189-0000000000000',
};
/**
* - otaUpgradeFileIdentifier: <Buffer 1e f1 ee 0b>,
* - otaHeaderVersion: 256,
* - otaHeaderLength: 56,
* - otaHeaderFieldControl: 0,
* - manufacturerCode: 4151,
* - imageType: 2,
* - fileVersion: 12,
* - zigbeeStackVersion: 2,
* - otaHeaderString: 'OM15081-RTR-LIMITED-JN5189-00000',
* - totalImageSize: 245710
*/
export const IMAGE_V12_2_METAS = {
fileName: IMAGE_V12_2,
fileVersion: 12,
fileSize: 245710,
originalUrl: undefined,
url: `https://github.com/Koenkk/zigbee-OTA/raw/master/images1/${IMAGES_TEST_DIR}/${IMAGE_V12_2}`,
imageType: 2,
manufacturerCode: 4151,
sha512: '4e178e56c1559e11734c07abbb95110675df7738f3ca3e5dbc99393325295ff6c66bd63ba55c0ef6043a80608dbec2be7a1e845f31ffd94f1cb63f32f0d48c6e',
otaHeaderString: 'OM15081-RTR-LIMITED-JN5189-00000',
};
/** obviously bogus, just for mocking */
export const IMAGE_INVALID_METAS = {
fileName: IMAGE_INVALID,
fileVersion: 0,
fileSize: 0,
originalUrl: undefined,
url: `https://github.com/Koenkk/zigbee-OTA/raw/master/images/${IMAGES_TEST_DIR}/${IMAGE_INVALID}`,
imageType: 1,
manufacturerCode: 65535,
sha512: 'abcd',
otaHeaderString: 'nothing',
};
/**
* - otaUpgradeFileIdentifier: <Buffer 1e f1 ee 0b>,
* - otaHeaderVersion: 256,
* - otaHeaderLength: 56,
* - otaHeaderFieldControl: 0,
* - manufacturerCode: 4388,
* - imageType: 2,
* - fileVersion: 6,
* - zigbeeStackVersion: 2,
* - otaHeaderString: 'Jasco 45856 image\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00',
* - totalImageSize: 162302
*/
export const IMAGE_TAR_METAS = {
fileName: IMAGE_TAR_OTA,
fileVersion: 6,
fileSize: 162302,
originalUrl: undefined,
url: `https://github.com/Koenkk/zigbee-OTA/raw/master/images/${IMAGES_TEST_DIR}/${IMAGE_TAR_OTA}`,
imageType: 2,
manufacturerCode: 4388,
sha512: '3306332e001eab9d71c9360089d450ea21e2c08bac957b523643c042707887e85db0c510f3480bdbcfcfe2398eeaad88d455f346f1e07841e1d690d8c16dc211',
otaHeaderString: 'Jasco 45856 image\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00',
};
export const getImageOriginalDirPath = (imageName: string): string => {
return path.join('tests', common.BASE_IMAGES_DIR, imageName);
};
export const useImage = (imageName: string, outDir: string = BASE_IMAGES_TEST_DIR_PATH): string => {
const realPath = path.join(outDir, imageName);
if (!existsSync(outDir)) {
mkdirSync(outDir, {recursive: true});
}
copyFileSync(getImageOriginalDirPath(imageName), realPath);
// return as posix for github match
return path.posix.join(BASE_IMAGES_TEST_DIR_PATH.replaceAll('\\', '/'), imageName);
};
export const withExtraMetas = (meta: RepoImageMeta, extraMetas: ExtraMetas): RepoImageMeta => {
return Object.assign({}, structuredClone(meta), extraMetas);
};
export const getAdjustedContent = (fileName: string, content: RepoImageMeta[]): RepoImageMeta[] => {
return content.map((c) => {
if (fileName === common.BASE_INDEX_MANIFEST_FILENAME && c.url.includes(`/${common.PREV_IMAGES_DIR}/`)) {
return withExtraMetas(c, {
// @ts-expect-error override
url: `https://github.com/Koenkk/zigbee-OTA/raw/master/${common.BASE_IMAGES_DIR}/${IMAGES_TEST_DIR}/${c.fileName}`,
});
} else if (fileName === common.PREV_INDEX_MANIFEST_FILENAME && c.url.includes(`${common.BASE_IMAGES_DIR}`)) {
return withExtraMetas(c, {
// @ts-expect-error override
url: `https://github.com/Koenkk/zigbee-OTA/raw/master/${common.PREV_IMAGES_DIR}/${IMAGES_TEST_DIR}/${c.fileName}`,
});
}
return c;
});
};
// required to consider as a 'test suite'
it('passes', () => {});

View File

@@ -0,0 +1,786 @@
import type CoreApi from '@actions/core';
import type {Context} from '@actions/github/lib/context';
import type {RepoImageMeta} from '../src/types';
import {copyFileSync, existsSync, mkdirSync, readFileSync, renameSync, rmSync} from 'fs';
import path from 'path';
import * as common from '../src/common';
import {
NOT_IN_BASE_MANIFEST_IMAGES_DIR,
NOT_IN_MANIFEST_FILENAME,
NOT_IN_PREV_MANIFEST_IMAGES_DIR,
reProcessAllImages,
} from '../src/ghw_reprocess_all_images';
import {
BASE_IMAGES_TEST_DIR_PATH,
getAdjustedContent,
getImageOriginalDirPath,
IMAGE_INVALID,
IMAGE_INVALID_METAS,
IMAGE_V12_1,
IMAGE_V13_1,
IMAGE_V13_1_METAS,
IMAGE_V14_1,
IMAGE_V14_1_METAS,
IMAGES_TEST_DIR,
PREV_IMAGES_TEST_DIR_PATH,
useImage,
withExtraMetas,
} from './data.test';
/** not used */
const github = {};
const core: Partial<typeof CoreApi> = {
debug: console.debug,
info: console.log,
warning: console.warn,
error: console.error,
notice: console.log,
startGroup: jest.fn(),
endGroup: jest.fn(),
};
const context: Partial<Context> = {
payload: {},
repo: {
owner: 'Koenkk',
repo: 'zigbee-OTA',
},
};
const OLD_META_3RD_PARTY_1_REAL_IMAGE = IMAGE_V13_1;
const OLD_META_3RD_PARTY_1_REAL_METAS = IMAGE_V13_1_METAS;
const OLD_META_3RD_PARTY_1_METAS = {
fileVersion: 1124103171,
fileSize: 258104,
manufacturerCode: 4107,
imageType: 256,
sha512: 'c63a1eb02ac030f3a76d9e81a4d48695796457d263bb1dae483688134e550d9846c37a3fd0eab2d4670f12f11b79691a5cf2789af0dbd90d703512496190a0a5',
// mock fileName to trigger mocked fetch properly
url: `https://otau.meethue.com/storage/ZGB_100B_0100/2dcfe6e6-0177-4c81-a1d9-4d2bd2ea1fb7/${OLD_META_3RD_PARTY_1_REAL_IMAGE}`,
};
const OLD_META_3RD_PARTY_2_REAL_IMAGE = IMAGE_V14_1;
const OLD_META_3RD_PARTY_2_REAL_METAS = IMAGE_V14_1_METAS;
const OLD_META_3RD_PARTY_2_METAS = {
fileVersion: 192,
fileSize: 307682,
manufacturerCode: 4417,
imageType: 54179,
modelId: 'TS011F',
sha512: '01939ca4fc790432d2c233e19b2440c1e0248d2ce85c9299e0b88928cb2341de675350ac7b78187a25f06a2768f93db0a17c4ba950b60c82c072e0c0833cfcfb',
// mock fileName to trigger mocked fetch properly
url: `https://images.tuyaeu.com/smart/firmware/upgrade/20220907/${OLD_META_3RD_PARTY_2_REAL_IMAGE}`,
};
const OLD_META_3RD_PARTY_IGNORED_METAS = {
fileVersion: 317,
fileSize: 693230,
manufacturerCode: 13379,
imageType: 4113,
sha512: '66040fb2b2787bf8ebfc75bc3c7356c7d8b966b4c82282bd7393783b8dc453ec2c8dcb4d7c9fe7c0a83d87739bd3677f205d79edddfa4fa2749305ca987887b1',
url: 'https://github.com/xyzroe/ZigUSB_C6/releases/download/317/ZigUSB_C6.ota',
};
const NOT_IN_BASE_MANIFEST_IMAGE_DIR_PATH = path.join(NOT_IN_BASE_MANIFEST_IMAGES_DIR, IMAGES_TEST_DIR);
const NOT_IN_PREV_MANIFEST_IMAGE_DIR_PATH = path.join(NOT_IN_PREV_MANIFEST_IMAGES_DIR, IMAGES_TEST_DIR);
const NOT_IN_BASE_MANIFEST_FILEPATH = path.join(NOT_IN_BASE_MANIFEST_IMAGES_DIR, NOT_IN_MANIFEST_FILENAME);
const NOT_IN_PREV_MANIFEST_FILEPATH = path.join(NOT_IN_PREV_MANIFEST_IMAGES_DIR, NOT_IN_MANIFEST_FILENAME);
// move to tmp dirs in `beforeAll` to allow tests to run (reverted in `afterAll`)
const NOT_IN_PREV_MANIFEST_IMAGES_DIR_TMP = `${NOT_IN_PREV_MANIFEST_IMAGES_DIR}-moved-by-jest`;
const NOT_IN_BASE_MANIFEST_IMAGES_DIR_TMP = `${NOT_IN_BASE_MANIFEST_IMAGES_DIR}-moved-by-jest`;
describe('Github Workflow: Re-Process All Images', () => {
let baseManifest: RepoImageMeta[];
let prevManifest: RepoImageMeta[];
let notInBaseManifest: RepoImageMeta[];
let notInPrevManifest: RepoImageMeta[];
let readManifestSpy: jest.SpyInstance;
let writeManifestSpy: jest.SpyInstance;
let addImageToBaseSpy: jest.SpyInstance;
let addImageToPrevSpy: jest.SpyInstance;
let coreWarningSpy: jest.SpyInstance;
let coreErrorSpy: jest.SpyInstance;
const getManifest = (fileName: string): RepoImageMeta[] => {
if (fileName === common.BASE_INDEX_MANIFEST_FILENAME) {
return baseManifest;
} else if (fileName === common.PREV_INDEX_MANIFEST_FILENAME) {
return prevManifest;
} else if (fileName === path.join(NOT_IN_BASE_MANIFEST_IMAGES_DIR, NOT_IN_MANIFEST_FILENAME)) {
return notInBaseManifest;
} else if (fileName === path.join(NOT_IN_PREV_MANIFEST_IMAGES_DIR, NOT_IN_MANIFEST_FILENAME)) {
return notInPrevManifest;
} else {
throw new Error(`${fileName} not supported`);
}
};
const setManifest = (fileName: string, content: RepoImageMeta[]): void => {
const adjustedContent = getAdjustedContent(fileName, content);
if (fileName === common.BASE_INDEX_MANIFEST_FILENAME) {
baseManifest = adjustedContent;
} else if (fileName === common.PREV_INDEX_MANIFEST_FILENAME) {
prevManifest = adjustedContent;
} else if (fileName === path.join(NOT_IN_BASE_MANIFEST_IMAGES_DIR, NOT_IN_MANIFEST_FILENAME)) {
notInBaseManifest = adjustedContent;
} else if (fileName === path.join(NOT_IN_PREV_MANIFEST_IMAGES_DIR, NOT_IN_MANIFEST_FILENAME)) {
notInPrevManifest = adjustedContent;
} else {
throw new Error(`${fileName} not supported`);
}
};
const resetManifests = (): void => {
baseManifest = [];
prevManifest = [];
};
const withOldMetas = (metas: RepoImageMeta): RepoImageMeta => {
const oldMetas = structuredClone(metas);
delete oldMetas.originalUrl;
// @ts-expect-error mock
delete oldMetas.sha512;
return oldMetas;
};
const expectWriteNoChange = (nth: number, fileName: string): void => {
expect(writeManifestSpy).toHaveBeenNthCalledWith(nth, fileName, getManifest(fileName));
};
beforeAll(() => {
if (existsSync(NOT_IN_PREV_MANIFEST_IMAGES_DIR)) {
renameSync(NOT_IN_PREV_MANIFEST_IMAGES_DIR, NOT_IN_PREV_MANIFEST_IMAGES_DIR_TMP);
}
if (existsSync(NOT_IN_BASE_MANIFEST_IMAGES_DIR)) {
renameSync(NOT_IN_BASE_MANIFEST_IMAGES_DIR, NOT_IN_BASE_MANIFEST_IMAGES_DIR_TMP);
}
});
afterAll(() => {
readManifestSpy.mockRestore();
writeManifestSpy.mockRestore();
addImageToBaseSpy.mockRestore();
addImageToPrevSpy.mockRestore();
coreWarningSpy.mockRestore();
coreErrorSpy.mockRestore();
rmSync(BASE_IMAGES_TEST_DIR_PATH, {recursive: true, force: true});
rmSync(PREV_IMAGES_TEST_DIR_PATH, {recursive: true, force: true});
rmSync(NOT_IN_BASE_MANIFEST_IMAGE_DIR_PATH, {recursive: true, force: true});
rmSync(NOT_IN_PREV_MANIFEST_IMAGE_DIR_PATH, {recursive: true, force: true});
if (existsSync(NOT_IN_PREV_MANIFEST_IMAGES_DIR_TMP)) {
rmSync(NOT_IN_PREV_MANIFEST_IMAGES_DIR, {recursive: true, force: true});
renameSync(NOT_IN_PREV_MANIFEST_IMAGES_DIR_TMP, NOT_IN_PREV_MANIFEST_IMAGES_DIR);
}
if (existsSync(NOT_IN_BASE_MANIFEST_IMAGES_DIR_TMP)) {
rmSync(NOT_IN_BASE_MANIFEST_IMAGES_DIR, {recursive: true, force: true});
renameSync(NOT_IN_BASE_MANIFEST_IMAGES_DIR_TMP, NOT_IN_BASE_MANIFEST_IMAGES_DIR);
}
});
beforeEach(() => {
resetManifests();
readManifestSpy = jest.spyOn(common, 'readManifest').mockImplementation(getManifest);
writeManifestSpy = jest.spyOn(common, 'writeManifest').mockImplementation(setManifest);
addImageToBaseSpy = jest.spyOn(common, 'addImageToBase');
addImageToPrevSpy = jest.spyOn(common, 'addImageToPrev');
coreWarningSpy = jest.spyOn(core, 'warning');
coreErrorSpy = jest.spyOn(core, 'error');
});
afterEach(() => {
rmSync(BASE_IMAGES_TEST_DIR_PATH, {recursive: true, force: true});
rmSync(PREV_IMAGES_TEST_DIR_PATH, {recursive: true, force: true});
rmSync(NOT_IN_BASE_MANIFEST_IMAGE_DIR_PATH, {recursive: true, force: true});
rmSync(NOT_IN_PREV_MANIFEST_IMAGE_DIR_PATH, {recursive: true, force: true});
});
it('failure when moving not in manifest if base out directory is not empty', async () => {
mkdirSync(NOT_IN_BASE_MANIFEST_IMAGE_DIR_PATH, {recursive: true});
copyFileSync(getImageOriginalDirPath(IMAGE_V12_1), path.join(NOT_IN_BASE_MANIFEST_IMAGE_DIR_PATH, IMAGE_V12_1));
await expect(async () => {
// @ts-expect-error mocked as needed
await reProcessAllImages(github, core, context, false, true);
}).rejects.toThrow(expect.objectContaining({message: expect.stringContaining('is not empty')}));
});
it('failure when moving not in manifest if prev out directory is not empty', async () => {
mkdirSync(NOT_IN_PREV_MANIFEST_IMAGE_DIR_PATH, {recursive: true});
copyFileSync(getImageOriginalDirPath(IMAGE_V12_1), path.join(NOT_IN_PREV_MANIFEST_IMAGE_DIR_PATH, IMAGE_V12_1));
await expect(async () => {
// @ts-expect-error mocked as needed
await reProcessAllImages(github, core, context, false, true);
}).rejects.toThrow(expect.objectContaining({message: expect.stringContaining('is not empty')}));
});
it('failure when image not in subdirectory', async () => {
// this is renaming the image to the same as the test dir name for simplicity in code exclusion
const outPath = path.join(common.PREV_IMAGES_DIR, IMAGES_TEST_DIR);
if (!existsSync(common.PREV_IMAGES_DIR)) {
mkdirSync(common.PREV_IMAGES_DIR, {recursive: true});
}
copyFileSync(getImageOriginalDirPath(IMAGE_V12_1), outPath);
await expect(async () => {
// @ts-expect-error mocked as needed
await reProcessAllImages(github, core, context, false, true);
}).rejects.toThrow(
expect.objectContaining({message: expect.stringContaining(`Detected file in ${common.PREV_IMAGES_DIR} not in subdirectory`)}),
);
rmSync(outPath, {force: true});
});
it('removes image not in manifest', async () => {
const imagePath = useImage(IMAGE_V12_1, BASE_IMAGES_TEST_DIR_PATH);
// @ts-expect-error mocked as needed
await reProcessAllImages(github, core, context, true, true);
expect(existsSync(imagePath)).toStrictEqual(false);
expect(readManifestSpy).toHaveBeenCalledTimes(2);
expect(writeManifestSpy).toHaveBeenCalledTimes(2);
expectWriteNoChange(1, common.PREV_INDEX_MANIFEST_FILENAME);
expectWriteNoChange(2, common.BASE_INDEX_MANIFEST_FILENAME);
expect(coreWarningSpy).toHaveBeenCalledWith(expect.stringContaining(`Not found in base manifest:`));
});
it('removes multiple images not in manifest', async () => {
const image1Path = useImage(IMAGE_V13_1, BASE_IMAGES_TEST_DIR_PATH);
const image2Path = useImage(IMAGE_V12_1, BASE_IMAGES_TEST_DIR_PATH);
const image3Path = useImage(IMAGE_V12_1, PREV_IMAGES_TEST_DIR_PATH);
// @ts-expect-error mocked as needed
await reProcessAllImages(github, core, context, true, true);
expect(existsSync(image1Path)).toStrictEqual(false);
expect(existsSync(image2Path)).toStrictEqual(false);
expect(existsSync(image3Path)).toStrictEqual(false);
expect(readManifestSpy).toHaveBeenCalledTimes(2);
expect(writeManifestSpy).toHaveBeenCalledTimes(2);
expectWriteNoChange(1, common.PREV_INDEX_MANIFEST_FILENAME);
expectWriteNoChange(2, common.BASE_INDEX_MANIFEST_FILENAME);
// prev first, then alphabetical
expect(coreWarningSpy).toHaveBeenNthCalledWith(1, expect.stringContaining(`Not found in base manifest:`));
expect(coreWarningSpy).toHaveBeenNthCalledWith(2, expect.stringContaining(`Not found in base manifest:`));
expect(coreWarningSpy).toHaveBeenNthCalledWith(3, expect.stringContaining(`Not found in base manifest:`));
});
it('moves image not in manifest', async () => {
const oldPath = useImage(IMAGE_V12_1, BASE_IMAGES_TEST_DIR_PATH);
// @ts-expect-error mocked as needed
await reProcessAllImages(github, core, context, false, true);
const newPath = path.join(NOT_IN_BASE_MANIFEST_IMAGE_DIR_PATH, IMAGE_V12_1);
expect(existsSync(oldPath)).toStrictEqual(false);
expect(existsSync(newPath)).toStrictEqual(true);
expect(readManifestSpy).toHaveBeenCalledTimes(2);
expect(writeManifestSpy).toHaveBeenCalledTimes(3);
expectWriteNoChange(1, common.PREV_INDEX_MANIFEST_FILENAME);
expect(writeManifestSpy).toHaveBeenNthCalledWith(2, NOT_IN_BASE_MANIFEST_FILEPATH, expect.any(Array));
expectWriteNoChange(3, common.BASE_INDEX_MANIFEST_FILENAME);
});
it('moves multiple images not in manifest', async () => {
const oldPath1 = useImage(IMAGE_V13_1, BASE_IMAGES_TEST_DIR_PATH);
const oldPath2 = useImage(IMAGE_V12_1, BASE_IMAGES_TEST_DIR_PATH);
const oldPath3 = useImage(IMAGE_V12_1, PREV_IMAGES_TEST_DIR_PATH);
// @ts-expect-error mocked as needed
await reProcessAllImages(github, core, context, false, true);
const newPath1 = path.join(NOT_IN_BASE_MANIFEST_IMAGE_DIR_PATH, IMAGE_V13_1);
const newPath2 = path.join(NOT_IN_BASE_MANIFEST_IMAGE_DIR_PATH, IMAGE_V12_1);
const newPath3 = path.join(NOT_IN_PREV_MANIFEST_IMAGE_DIR_PATH, IMAGE_V12_1);
expect(existsSync(newPath1)).toStrictEqual(true);
expect(existsSync(oldPath1)).toStrictEqual(false);
expect(existsSync(newPath2)).toStrictEqual(true);
expect(existsSync(oldPath2)).toStrictEqual(false);
expect(existsSync(newPath3)).toStrictEqual(true);
expect(existsSync(oldPath3)).toStrictEqual(false);
expect(readManifestSpy).toHaveBeenCalledTimes(2);
expect(writeManifestSpy).toHaveBeenCalledTimes(4);
expect(writeManifestSpy).toHaveBeenNthCalledWith(1, NOT_IN_PREV_MANIFEST_FILEPATH, expect.any(Array));
expectWriteNoChange(2, common.PREV_INDEX_MANIFEST_FILENAME);
expect(writeManifestSpy).toHaveBeenNthCalledWith(3, NOT_IN_BASE_MANIFEST_FILEPATH, expect.any(Array));
expectWriteNoChange(4, common.BASE_INDEX_MANIFEST_FILENAME);
});
it('removes invalid not in manifest even if remove disabled', async () => {
const oldPath = useImage(IMAGE_INVALID, BASE_IMAGES_TEST_DIR_PATH);
// @ts-expect-error mocked as needed
await reProcessAllImages(github, core, context, false, true);
expect(existsSync(oldPath)).toStrictEqual(false);
expect(readManifestSpy).toHaveBeenCalledTimes(2);
expect(writeManifestSpy).toHaveBeenCalledTimes(2);
expect(writeManifestSpy).toHaveBeenNthCalledWith(1, common.PREV_INDEX_MANIFEST_FILENAME, []);
expect(writeManifestSpy).toHaveBeenNthCalledWith(2, common.BASE_INDEX_MANIFEST_FILENAME, []);
expect(coreErrorSpy).toHaveBeenCalledWith(expect.stringContaining(`Removing`));
expect(coreErrorSpy).toHaveBeenCalledWith(expect.stringContaining(`Not a valid OTA file`));
expect(coreWarningSpy).toHaveBeenCalledWith(expect.stringContaining(`Not found in base manifest`));
});
it('removes invalid in manifest', async () => {
setManifest(common.BASE_INDEX_MANIFEST_FILENAME, [IMAGE_INVALID_METAS]);
const oldPath = useImage(IMAGE_INVALID, BASE_IMAGES_TEST_DIR_PATH);
// @ts-expect-error mocked as needed
await reProcessAllImages(github, core, context, true, true);
expect(existsSync(oldPath)).toStrictEqual(false);
expect(readManifestSpy).toHaveBeenCalledTimes(2);
expect(writeManifestSpy).toHaveBeenCalledTimes(2);
expect(writeManifestSpy).toHaveBeenNthCalledWith(1, common.PREV_INDEX_MANIFEST_FILENAME, []);
expect(writeManifestSpy).toHaveBeenNthCalledWith(2, common.BASE_INDEX_MANIFEST_FILENAME, []);
expect(coreErrorSpy).toHaveBeenCalledWith(expect.stringContaining(`Removing`));
expect(coreErrorSpy).toHaveBeenCalledWith(expect.stringContaining(`Not a valid OTA file`));
});
it('keeps image and rewrites manifest', async () => {
setManifest(common.BASE_INDEX_MANIFEST_FILENAME, [withOldMetas(IMAGE_V14_1_METAS)]);
const imagePath = useImage(IMAGE_V14_1, BASE_IMAGES_TEST_DIR_PATH);
// @ts-expect-error mocked as needed
await reProcessAllImages(github, core, context, true, true);
expect(existsSync(imagePath)).toStrictEqual(true);
expect(readManifestSpy).toHaveBeenCalledTimes(2);
expect(writeManifestSpy).toHaveBeenCalledTimes(2);
expect(writeManifestSpy).toHaveBeenNthCalledWith(1, common.PREV_INDEX_MANIFEST_FILENAME, []);
expect(writeManifestSpy).toHaveBeenNthCalledWith(2, common.BASE_INDEX_MANIFEST_FILENAME, [IMAGE_V14_1_METAS]);
});
it('keeps image with escaped url and rewrites manifest', async () => {
const oldMetas = withOldMetas(IMAGE_V14_1_METAS);
const fileName = oldMetas.url.split('/').pop()!;
const newName = fileName.replace('.ota', `(%1).ota`);
const baseUrl = oldMetas.url.replace(fileName, '');
oldMetas.url = baseUrl + escape(newName);
setManifest(common.BASE_INDEX_MANIFEST_FILENAME, [oldMetas]);
const imagePath = useImage(IMAGE_V14_1, BASE_IMAGES_TEST_DIR_PATH);
const baseName = path.basename(imagePath);
const renamedPath = imagePath.replace(baseName, newName);
renameSync(imagePath, renamedPath);
console.log(newName, oldMetas.url, renamedPath);
// @ts-expect-error mocked as needed
await reProcessAllImages(github, core, context, true, true);
expect(existsSync(renamedPath)).toStrictEqual(true);
expect(readManifestSpy).toHaveBeenCalledTimes(2);
expect(writeManifestSpy).toHaveBeenCalledTimes(2);
expect(writeManifestSpy).toHaveBeenNthCalledWith(1, common.PREV_INDEX_MANIFEST_FILENAME, []);
const outManifestMetas = withExtraMetas(
IMAGE_V14_1_METAS,
// @ts-expect-error override
{fileName: newName, url: `${baseUrl}${newName}`},
);
delete outManifestMetas.originalUrl;
expect(writeManifestSpy).toHaveBeenNthCalledWith(2, common.BASE_INDEX_MANIFEST_FILENAME, [outManifestMetas]);
});
it('ignores when same images referenced multiple times in manifest', async () => {
const oldMetas1 = withOldMetas(IMAGE_V14_1_METAS);
const oldMetas2 = withOldMetas(IMAGE_V14_1_METAS);
setManifest(common.BASE_INDEX_MANIFEST_FILENAME, [oldMetas1, oldMetas2]);
const image1Path = useImage(IMAGE_V14_1, BASE_IMAGES_TEST_DIR_PATH);
// @ts-expect-error mocked as needed
await reProcessAllImages(github, core, context, true, true);
expect(existsSync(image1Path)).toStrictEqual(true);
expect(readManifestSpy).toHaveBeenCalledTimes(2);
expect(writeManifestSpy).toHaveBeenCalledTimes(2);
expect(writeManifestSpy).toHaveBeenNthCalledWith(1, common.PREV_INDEX_MANIFEST_FILENAME, []);
expect(writeManifestSpy).toHaveBeenNthCalledWith(2, common.BASE_INDEX_MANIFEST_FILENAME, [IMAGE_V14_1_METAS]);
expect(coreWarningSpy).toHaveBeenCalledWith(
expect.stringContaining(`found multiple times in ${common.BASE_INDEX_MANIFEST_FILENAME} manifest`),
);
});
it('keeps same images referenced multiple times in manifest with different extra metas', async () => {
const oldMetas1 = withExtraMetas(withOldMetas(IMAGE_V14_1_METAS), {modelId: 'test1'});
const oldMetas2 = withExtraMetas(withOldMetas(IMAGE_V14_1_METAS), {modelId: 'test2'});
setManifest(common.BASE_INDEX_MANIFEST_FILENAME, [oldMetas1, oldMetas2]);
const image1Path = useImage(IMAGE_V14_1, BASE_IMAGES_TEST_DIR_PATH);
// @ts-expect-error mocked as needed
await reProcessAllImages(github, core, context, true, true);
expect(existsSync(image1Path)).toStrictEqual(true);
expect(readManifestSpy).toHaveBeenCalledTimes(2);
expect(writeManifestSpy).toHaveBeenCalledTimes(2);
expect(writeManifestSpy).toHaveBeenNthCalledWith(1, common.PREV_INDEX_MANIFEST_FILENAME, []);
expect(writeManifestSpy).toHaveBeenNthCalledWith(2, common.BASE_INDEX_MANIFEST_FILENAME, [
withExtraMetas(IMAGE_V14_1_METAS, {modelId: 'test1'}),
withExtraMetas(IMAGE_V14_1_METAS, {modelId: 'test2'}),
]);
expect(coreWarningSpy).toHaveBeenCalledWith(
expect.stringContaining(`found multiple times in ${common.BASE_INDEX_MANIFEST_FILENAME} manifest`),
);
});
describe('downloads', () => {
let fetchSpy: jest.SpyInstance;
let setTimeoutSpy: jest.SpyInstance;
let fetchReturnedStatus: {ok: boolean; status: number; body?: object} = {ok: true, status: 200, body: {}};
const get3rdPartyDir = jest.fn().mockReturnValue(IMAGES_TEST_DIR);
const adaptUrl = (originalUrl: string, manifestName: string): string => {
if (manifestName === common.BASE_INDEX_MANIFEST_FILENAME) {
return originalUrl.replace(`/${common.PREV_IMAGES_DIR}/`, `/${common.BASE_IMAGES_DIR}/`);
} else if (manifestName === common.PREV_INDEX_MANIFEST_FILENAME) {
return originalUrl.replace(`/${common.BASE_IMAGES_DIR}/`, `/${common.PREV_IMAGES_DIR}/`);
} else {
throw new Error(`Not supported: ${manifestName}`);
}
};
afterAll(() => {
fetchSpy.mockRestore();
setTimeoutSpy.mockRestore();
});
beforeEach(() => {
process.env.NODE_EXTRA_CA_CERTS = 'cacerts.pem';
fetchReturnedStatus = {ok: true, status: 200, body: {}};
fetchSpy = jest.spyOn(global, 'fetch').mockImplementation(
// @ts-expect-error mocked as needed
(input) => {
return {
ok: fetchReturnedStatus.ok,
status: fetchReturnedStatus.status,
body: fetchReturnedStatus.body,
arrayBuffer: (): ArrayBuffer => readFileSync(getImageOriginalDirPath((input as string).split('/').pop()!)),
};
},
);
setTimeoutSpy = jest.spyOn(global, 'setTimeout').mockImplementation(
// @ts-expect-error mock
(fn) => {
fn();
},
);
});
it('failure without CA Certificates ENV', async () => {
process.env.NODE_EXTRA_CA_CERTS = '';
await expect(async () => {
// @ts-expect-error mocked as needed
await reProcessAllImages(github, core, context, true, false, get3rdPartyDir);
}).rejects.toThrow(
expect.objectContaining({message: expect.stringContaining(`Download 3rd Parties requires \`NODE_EXTRA_CA_CERTS=cacerts.pem\``)}),
);
});
it('failure with malformed metas', async () => {
setManifest(common.BASE_INDEX_MANIFEST_FILENAME, [
// @ts-expect-error old metas
{
fileVersion: 192,
fileSize: 307682,
manufacturerCode: 4417,
imageType: 54179,
modelId: 'TS011F',
sha512: '01939ca4fc790432d2c233e19b2440c1e0248d2ce85c9299e0b88928cb2341de675350ac7b78187a25f06a2768f93db0a17c4ba950b60c82c072e0c0833cfcfb',
url: '', // not undefined to pass setManifest
},
]);
// @ts-expect-error mocked as needed
await reProcessAllImages(github, core, context, true, false, get3rdPartyDir);
expect(readManifestSpy).toHaveBeenCalledTimes(4);
expect(writeManifestSpy).toHaveBeenCalledTimes(4);
expect(fetchSpy).toHaveBeenCalledTimes(0);
expectWriteNoChange(1, common.PREV_INDEX_MANIFEST_FILENAME);
expectWriteNoChange(2, common.BASE_INDEX_MANIFEST_FILENAME);
expectWriteNoChange(3, common.PREV_INDEX_MANIFEST_FILENAME);
expectWriteNoChange(4, common.BASE_INDEX_MANIFEST_FILENAME);
expect(coreErrorSpy).toHaveBeenCalledWith(expect.stringContaining(`Ignoring malformed`));
});
it('failure from fetch ok', async () => {
setManifest(
common.BASE_INDEX_MANIFEST_FILENAME,
// @ts-expect-error old metas
[OLD_META_3RD_PARTY_1_METAS],
);
fetchReturnedStatus.ok = false;
// @ts-expect-error mocked as needed
await reProcessAllImages(github, core, context, true, false, get3rdPartyDir);
expect(readManifestSpy).toHaveBeenCalledTimes(4);
expect(writeManifestSpy).toHaveBeenCalledTimes(4);
expect(fetchSpy).toHaveBeenCalledTimes(1);
expectWriteNoChange(1, common.PREV_INDEX_MANIFEST_FILENAME);
expectWriteNoChange(2, common.BASE_INDEX_MANIFEST_FILENAME);
expectWriteNoChange(3, common.PREV_INDEX_MANIFEST_FILENAME);
expectWriteNoChange(4, common.BASE_INDEX_MANIFEST_FILENAME);
expect(coreErrorSpy).toHaveBeenCalledWith(
`Invalid response from ${OLD_META_3RD_PARTY_1_METAS.url} status=${fetchReturnedStatus.status}.`,
);
});
it('ignores urls from this repo', async () => {
setManifest(common.BASE_INDEX_MANIFEST_FILENAME, [IMAGE_V14_1_METAS]);
// prevent trigger removal because of missing file
useImage(IMAGE_V14_1, BASE_IMAGES_TEST_DIR_PATH);
// @ts-expect-error mocked as needed
await reProcessAllImages(github, core, context, true, false, get3rdPartyDir);
expect(readManifestSpy).toHaveBeenCalledTimes(4);
expect(writeManifestSpy).toHaveBeenCalledTimes(4);
expect(fetchSpy).toHaveBeenCalledTimes(0);
expectWriteNoChange(1, common.PREV_INDEX_MANIFEST_FILENAME);
expectWriteNoChange(2, common.BASE_INDEX_MANIFEST_FILENAME);
expectWriteNoChange(3, common.PREV_INDEX_MANIFEST_FILENAME);
expectWriteNoChange(4, common.BASE_INDEX_MANIFEST_FILENAME);
});
it('ignores urls with no out dir specified', async () => {
setManifest(common.BASE_INDEX_MANIFEST_FILENAME, [
// @ts-expect-error old metas
{
fileVersion: 192,
fileSize: 307682,
manufacturerCode: 4417,
imageType: 54179,
modelId: 'TS011F',
sha512: '01939ca4fc790432d2c233e19b2440c1e0248d2ce85c9299e0b88928cb2341de675350ac7b78187a25f06a2768f93db0a17c4ba950b60c82c072e0c0833cfcfb',
url: 'https://www.elektroimportoren.no/docs/lib/4512772-Firmware-35.ota',
},
]);
// @ts-expect-error mocked as needed
await reProcessAllImages(github, core, context, true, false);
expect(readManifestSpy).toHaveBeenCalledTimes(4);
expect(writeManifestSpy).toHaveBeenCalledTimes(4);
expect(fetchSpy).toHaveBeenCalledTimes(0);
expectWriteNoChange(1, common.PREV_INDEX_MANIFEST_FILENAME);
expectWriteNoChange(2, common.BASE_INDEX_MANIFEST_FILENAME);
expectWriteNoChange(3, common.PREV_INDEX_MANIFEST_FILENAME);
expectWriteNoChange(4, common.BASE_INDEX_MANIFEST_FILENAME);
expect(coreWarningSpy).toHaveBeenCalledWith(expect.stringContaining(`no out dir specified`));
});
it('ignores invalid OTA file', async () => {
setManifest(common.BASE_INDEX_MANIFEST_FILENAME, [
Object.assign({}, withOldMetas(IMAGE_INVALID_METAS), {
url: `https://images.tuyaeu.com/smart/firmware/upgrade/20220907/${IMAGES_TEST_DIR}/${IMAGE_INVALID}`,
}),
]);
// @ts-expect-error mocked as needed
await reProcessAllImages(github, core, context, true, false, get3rdPartyDir);
expect(readManifestSpy).toHaveBeenCalledTimes(4);
expect(writeManifestSpy).toHaveBeenCalledTimes(4);
expect(fetchSpy).toHaveBeenCalledTimes(1);
expectWriteNoChange(1, common.PREV_INDEX_MANIFEST_FILENAME);
expectWriteNoChange(2, common.BASE_INDEX_MANIFEST_FILENAME);
expectWriteNoChange(3, common.PREV_INDEX_MANIFEST_FILENAME);
expectWriteNoChange(4, common.BASE_INDEX_MANIFEST_FILENAME);
expect(coreErrorSpy).toHaveBeenCalledWith(expect.stringContaining(`Ignoring`));
expect(coreErrorSpy).toHaveBeenCalledWith(expect.stringContaining(`Not a valid OTA file`));
});
it('ignores identical image', async () => {
setManifest(common.BASE_INDEX_MANIFEST_FILENAME, [
IMAGE_V14_1_METAS,
Object.assign({}, withOldMetas(IMAGE_V14_1_METAS), {
url: `https://images.tuyaeu.com/smart/firmware/upgrade/20220907/${IMAGES_TEST_DIR}/${IMAGE_V14_1}`,
}),
]);
// @ts-expect-error mocked as needed
await reProcessAllImages(github, core, context, true, false, get3rdPartyDir);
expect(readManifestSpy).toHaveBeenCalledTimes(4);
expect(writeManifestSpy).toHaveBeenCalledTimes(4);
expect(fetchSpy).toHaveBeenCalledTimes(1);
expect(addImageToBaseSpy).toHaveBeenCalledTimes(0);
expect(addImageToPrevSpy).toHaveBeenCalledTimes(0);
expect(writeManifestSpy).toHaveBeenNthCalledWith(1, common.PREV_INDEX_MANIFEST_FILENAME, []);
expect(writeManifestSpy).toHaveBeenNthCalledWith(2, common.BASE_INDEX_MANIFEST_FILENAME, [IMAGE_V14_1_METAS]);
expect(coreWarningSpy).toHaveBeenCalledWith(expect.stringContaining(`Conflict with image at index \`0\``));
});
it('success without mocked get3rdPartyDir', async () => {
// NOTE: this is using a name (ZLinky_router_v13.ota) and out dir (Hue) that is unlikely to ever be in conflict with actual Hue images
setManifest(
common.BASE_INDEX_MANIFEST_FILENAME,
// @ts-expect-error old metas
[OLD_META_3RD_PARTY_1_METAS],
);
// @ts-expect-error mocked as needed
await reProcessAllImages(github, core, context, true, false);
expect(readManifestSpy).toHaveBeenCalledTimes(4);
expect(writeManifestSpy).toHaveBeenCalledTimes(4);
expect(fetchSpy).toHaveBeenCalledTimes(1);
expect(addImageToBaseSpy).toHaveBeenCalledTimes(1);
expect(writeManifestSpy).toHaveBeenNthCalledWith(1, common.PREV_INDEX_MANIFEST_FILENAME, []);
expect(writeManifestSpy).toHaveBeenNthCalledWith(2, common.BASE_INDEX_MANIFEST_FILENAME, [
withExtraMetas(OLD_META_3RD_PARTY_1_REAL_METAS, {
originalUrl: OLD_META_3RD_PARTY_1_METAS.url,
// @ts-expect-error override
url: adaptUrl(OLD_META_3RD_PARTY_1_REAL_METAS.url, common.BASE_INDEX_MANIFEST_FILENAME).replace(IMAGES_TEST_DIR, 'Hue'),
}),
]);
rmSync(path.join(common.BASE_IMAGES_DIR, 'Hue', OLD_META_3RD_PARTY_1_REAL_IMAGE));
});
it('success with add different metas and ignored', async () => {
setManifest(
common.BASE_INDEX_MANIFEST_FILENAME,
// @ts-expect-error old metas
[OLD_META_3RD_PARTY_1_METAS, OLD_META_3RD_PARTY_2_METAS, OLD_META_3RD_PARTY_IGNORED_METAS],
);
// @ts-expect-error mocked as needed
await reProcessAllImages(github, core, context, true, false, get3rdPartyDir);
expect(get3rdPartyDir).toHaveBeenCalledTimes(2);
expect(get3rdPartyDir).toHaveBeenNthCalledWith(1, OLD_META_3RD_PARTY_1_METAS);
expect(get3rdPartyDir).toHaveBeenNthCalledWith(2, OLD_META_3RD_PARTY_2_METAS);
expect(readManifestSpy).toHaveBeenCalledTimes(4);
expect(writeManifestSpy).toHaveBeenCalledTimes(4);
expect(fetchSpy).toHaveBeenCalledTimes(2);
expect(addImageToBaseSpy).toHaveBeenCalledTimes(2); // adds both, second process moves first to prev
expect(addImageToPrevSpy).toHaveBeenCalledTimes(0);
expect(writeManifestSpy).toHaveBeenNthCalledWith(1, common.PREV_INDEX_MANIFEST_FILENAME, []);
expect(writeManifestSpy).toHaveBeenNthCalledWith(2, common.BASE_INDEX_MANIFEST_FILENAME, [
withExtraMetas(OLD_META_3RD_PARTY_1_REAL_METAS, {
originalUrl: OLD_META_3RD_PARTY_1_METAS.url,
// @ts-expect-error override
url: adaptUrl(OLD_META_3RD_PARTY_1_REAL_METAS.url, common.BASE_INDEX_MANIFEST_FILENAME),
}),
withExtraMetas(OLD_META_3RD_PARTY_2_REAL_METAS, {
originalUrl: OLD_META_3RD_PARTY_2_METAS.url,
// @ts-expect-error override
url: adaptUrl(OLD_META_3RD_PARTY_2_REAL_METAS.url, common.BASE_INDEX_MANIFEST_FILENAME),
modelId: OLD_META_3RD_PARTY_2_METAS.modelId,
}),
]);
expect(coreWarningSpy).toHaveBeenCalledWith(expect.stringContaining(`Removing ignored '${OLD_META_3RD_PARTY_IGNORED_METAS.url}'`));
});
it('success with add+move same and ignored', async () => {
setManifest(
common.BASE_INDEX_MANIFEST_FILENAME,
// @ts-expect-error old metas
[OLD_META_3RD_PARTY_1_METAS, OLD_META_3RD_PARTY_IGNORED_METAS, withExtraMetas(OLD_META_3RD_PARTY_2_METAS, {modelId: undefined})],
);
// @ts-expect-error mocked as needed
await reProcessAllImages(github, core, context, true, false, get3rdPartyDir);
expect(readManifestSpy).toHaveBeenCalledTimes(4);
expect(writeManifestSpy).toHaveBeenCalledTimes(4);
expect(fetchSpy).toHaveBeenCalledTimes(2);
expect(addImageToBaseSpy).toHaveBeenCalledTimes(2); // adds both, second process moves first to prev
expect(addImageToPrevSpy).toHaveBeenCalledTimes(0);
expect(writeManifestSpy).toHaveBeenNthCalledWith(1, common.PREV_INDEX_MANIFEST_FILENAME, [
withExtraMetas(OLD_META_3RD_PARTY_1_REAL_METAS, {
originalUrl: OLD_META_3RD_PARTY_1_METAS.url,
// @ts-expect-error override
url: adaptUrl(OLD_META_3RD_PARTY_1_REAL_METAS.url, common.PREV_INDEX_MANIFEST_FILENAME),
}),
]);
expect(writeManifestSpy).toHaveBeenNthCalledWith(2, common.BASE_INDEX_MANIFEST_FILENAME, [
withExtraMetas(OLD_META_3RD_PARTY_2_REAL_METAS, {
originalUrl: OLD_META_3RD_PARTY_2_METAS.url,
// @ts-expect-error override
url: adaptUrl(OLD_META_3RD_PARTY_2_REAL_METAS.url, common.BASE_INDEX_MANIFEST_FILENAME),
}),
]);
expect(coreWarningSpy).toHaveBeenCalledWith(expect.stringContaining(`Removing ignored '${OLD_META_3RD_PARTY_IGNORED_METAS.url}'`));
});
it('success with add to prev', async () => {
setManifest(common.BASE_INDEX_MANIFEST_FILENAME, [
IMAGE_V14_1_METAS,
// @ts-expect-error old metas
OLD_META_3RD_PARTY_1_METAS,
]);
// prevent trigger removal because of missing file
useImage(IMAGE_V14_1, BASE_IMAGES_TEST_DIR_PATH);
// @ts-expect-error mocked as needed
await reProcessAllImages(github, core, context, true, false, get3rdPartyDir);
expect(readManifestSpy).toHaveBeenCalledTimes(4);
expect(writeManifestSpy).toHaveBeenCalledTimes(4);
expect(fetchSpy).toHaveBeenCalledTimes(1);
expect(addImageToBaseSpy).toHaveBeenCalledTimes(0);
expect(addImageToPrevSpy).toHaveBeenCalledTimes(1);
expect(writeManifestSpy).toHaveBeenNthCalledWith(1, common.PREV_INDEX_MANIFEST_FILENAME, [
withExtraMetas(OLD_META_3RD_PARTY_1_REAL_METAS, {
originalUrl: adaptUrl(OLD_META_3RD_PARTY_1_METAS.url, common.PREV_INDEX_MANIFEST_FILENAME),
}),
]);
expect(writeManifestSpy).toHaveBeenNthCalledWith(2, common.BASE_INDEX_MANIFEST_FILENAME, [IMAGE_V14_1_METAS]);
expect(writeManifestSpy).toHaveBeenNthCalledWith(3, common.PREV_INDEX_MANIFEST_FILENAME, [
withExtraMetas(OLD_META_3RD_PARTY_1_REAL_METAS, {
originalUrl: adaptUrl(OLD_META_3RD_PARTY_1_METAS.url, common.PREV_INDEX_MANIFEST_FILENAME),
}),
]);
expect(writeManifestSpy).toHaveBeenNthCalledWith(4, common.BASE_INDEX_MANIFEST_FILENAME, [IMAGE_V14_1_METAS]);
});
it('success with escaped', async () => {
const oldMetas = structuredClone(OLD_META_3RD_PARTY_1_METAS);
const fileName = oldMetas.url.split('/').pop()!;
const newName = fileName.replace('.ota', `(%1).ota`);
const baseUrl = oldMetas.url.replace(fileName, '');
oldMetas.url = baseUrl + escape(newName);
// @ts-expect-error old metas
setManifest(common.BASE_INDEX_MANIFEST_FILENAME, [oldMetas]);
// link back to existing image from fetch
fetchSpy = jest.spyOn(global, 'fetch').mockImplementationOnce(
// @ts-expect-error mocked as needed
() => {
return {
ok: fetchReturnedStatus.ok,
status: fetchReturnedStatus.status,
body: fetchReturnedStatus.body,
arrayBuffer: (): ArrayBuffer => readFileSync(getImageOriginalDirPath(fileName)),
};
},
);
// @ts-expect-error mocked as needed
await reProcessAllImages(github, core, context, true, false, () => IMAGES_TEST_DIR);
expect(readManifestSpy).toHaveBeenCalledTimes(4);
expect(writeManifestSpy).toHaveBeenCalledTimes(4);
expect(fetchSpy).toHaveBeenCalledTimes(1);
expect(writeManifestSpy).toHaveBeenNthCalledWith(1, common.PREV_INDEX_MANIFEST_FILENAME, []);
const outManifestMetas = withExtraMetas(OLD_META_3RD_PARTY_1_REAL_METAS, {
// @ts-expect-error override
fileName: newName,
originalUrl: oldMetas.url,
url: common.getRepoFirmwareFileUrl(IMAGES_TEST_DIR, newName, common.BASE_IMAGES_DIR),
});
expect(writeManifestSpy).toHaveBeenNthCalledWith(2, common.BASE_INDEX_MANIFEST_FILENAME, [outManifestMetas]);
});
});
});

View File

@@ -0,0 +1,531 @@
import type CoreApi from '@actions/core';
import type {Context} from '@actions/github/lib/context';
import type {Octokit} from '@octokit/rest';
import type {RepoImageMeta} from '../src/types';
import {rmSync} from 'fs';
import * as common from '../src/common';
import {updateOtaPR} from '../src/ghw_update_ota_pr';
import {
BASE_IMAGES_TEST_DIR_PATH,
getAdjustedContent,
IMAGE_INVALID,
IMAGE_V12_1,
IMAGE_V12_1_METAS,
IMAGE_V13_1,
IMAGE_V13_1_METAS,
IMAGE_V14_1,
IMAGE_V14_1_METAS,
IMAGE_V14_2,
IMAGE_V14_2_METAS,
PREV_IMAGES_TEST_DIR_PATH,
useImage,
withExtraMetas,
} from './data.test';
const github = {
rest: {
issues: {
createComment: jest.fn<
ReturnType<Octokit['rest']['issues']['createComment']>,
Parameters<Octokit['rest']['issues']['createComment']>,
unknown
>(),
},
pulls: {
createReviewComment: jest.fn<
ReturnType<Octokit['rest']['pulls']['createReviewComment']>,
Parameters<Octokit['rest']['pulls']['createReviewComment']>,
unknown
>(),
},
},
};
const core: Partial<typeof CoreApi> = {
debug: console.debug,
info: console.log,
warning: console.warn,
error: console.error,
notice: console.log,
startGroup: jest.fn(),
endGroup: jest.fn(),
};
const context: Partial<Context> = {
payload: {
pull_request: {
number: 1,
head: {
sha: 'abcd',
},
},
},
issue: {
owner: 'Koenkk',
repo: 'zigbee-OTA',
number: 1,
},
repo: {
owner: 'Koenkk',
repo: 'zigbee-OTA',
},
};
describe('Github Workflow: Update OTA PR', () => {
let baseManifest: RepoImageMeta[];
let prevManifest: RepoImageMeta[];
let readManifestSpy: jest.SpyInstance;
let writeManifestSpy: jest.SpyInstance;
let addImageToBaseSpy: jest.SpyInstance;
let addImageToPrevSpy: jest.SpyInstance;
const getManifest = (fileName: string): RepoImageMeta[] => {
if (fileName === common.BASE_INDEX_MANIFEST_FILENAME) {
return baseManifest;
} else if (fileName === common.PREV_INDEX_MANIFEST_FILENAME) {
return prevManifest;
} else {
throw new Error(`${fileName} not supported`);
}
};
const setManifest = (fileName: string, content: RepoImageMeta[]): void => {
const adjustedContent = getAdjustedContent(fileName, content);
if (fileName === common.BASE_INDEX_MANIFEST_FILENAME) {
baseManifest = adjustedContent;
} else if (fileName === common.PREV_INDEX_MANIFEST_FILENAME) {
prevManifest = adjustedContent;
} else {
throw new Error(`${fileName} not supported`);
}
};
const resetManifests = (): void => {
baseManifest = [];
prevManifest = [];
};
const withBody = (body: string): Partial<Context> => {
const newContext = structuredClone(context);
newContext.payload!.pull_request!.body = body;
return newContext;
};
const expectNoChanges = (noReadManifest: boolean = false): void => {
if (noReadManifest) {
expect(readManifestSpy).toHaveBeenCalledTimes(0);
} else {
expect(readManifestSpy).toHaveBeenCalledTimes(2);
}
expect(addImageToBaseSpy).toHaveBeenCalledTimes(0);
expect(addImageToPrevSpy).toHaveBeenCalledTimes(0);
expect(writeManifestSpy).toHaveBeenCalledTimes(0);
};
beforeAll(() => {});
afterAll(() => {
readManifestSpy.mockRestore();
writeManifestSpy.mockRestore();
addImageToBaseSpy.mockRestore();
addImageToPrevSpy.mockRestore();
rmSync(BASE_IMAGES_TEST_DIR_PATH, {recursive: true, force: true});
rmSync(PREV_IMAGES_TEST_DIR_PATH, {recursive: true, force: true});
});
beforeEach(() => {
resetManifests();
readManifestSpy = jest.spyOn(common, 'readManifest').mockImplementation(getManifest);
writeManifestSpy = jest.spyOn(common, 'writeManifest').mockImplementation(setManifest);
addImageToBaseSpy = jest.spyOn(common, 'addImageToBase');
addImageToPrevSpy = jest.spyOn(common, 'addImageToPrev');
});
afterEach(() => {
rmSync(BASE_IMAGES_TEST_DIR_PATH, {recursive: true, force: true});
rmSync(PREV_IMAGES_TEST_DIR_PATH, {recursive: true, force: true});
});
// XXX: Util
// it('Get headers', async () => {
// const firmwareBuffer = readFileSync(getImageOriginalDirPath(IMAGE_V14_1));
// console.log(IMAGE_V14_1);
// console.log(JSON.stringify(common.parseImageHeader(firmwareBuffer)));
// console.log(`URL: ${common.getRepoFirmwareFileUrl(IMAGES_TEST_DIR, IMAGE_V14_1, common.BASE_IMAGES_DIR)}`);
// console.log(`SHA512: ${common.computeSHA512(firmwareBuffer)}`);
// })
it('hard failure from outside PR context', async () => {
const fileParam: string = `images/test.ota`;
await expect(async () => {
// @ts-expect-error mock
await updateOtaPR(github, core, {payload: {}}, fileParam);
}).rejects.toThrow(`Not a pull request`);
expectNoChanges(true);
});
it('hard failure without fileParam', async () => {
// NOTE: this path should always be prevented by workflow `paths` filter
const fileParam: string = '';
await expect(async () => {
// @ts-expect-error mock
await updateOtaPR(github, core, context, fileParam);
}).rejects.toThrow(`No file found in pull request.`);
expectNoChanges(true);
});
it('failure with images in images1', async () => {
const fileParam: string = `images1/test2.ota,images/test.ota`;
await expect(async () => {
// @ts-expect-error mock
await updateOtaPR(github, core, context, fileParam);
}).rejects.toThrow(expect.objectContaining({message: expect.stringContaining(`Detected files in 'images1'`)}));
expectNoChanges(true);
expect(github.rest.issues.createComment).toHaveBeenCalledTimes(1);
});
it('failure with edited manifest', async () => {
const fileParam: string = `index.json,images/test.ota`;
await expect(async () => {
// @ts-expect-error mock
await updateOtaPR(github, core, context, fileParam);
}).rejects.toThrow(expect.objectContaining({message: expect.stringContaining(`Detected manual changes in index.json`)}));
expectNoChanges(true);
expect(github.rest.issues.createComment).toHaveBeenCalledTimes(1);
});
it('failure when no subfolder (manufacturer)', async () => {
const fileParam: string = `images/test.ota`;
await expect(async () => {
// @ts-expect-error mock
await updateOtaPR(github, core, context, fileParam);
}).rejects.toThrow(
expect.objectContaining({message: expect.stringContaining(`\`images/test.ota\` should be in its associated manufacturer subfolder.`)}),
);
expectNoChanges(false);
expect(github.rest.pulls.createReviewComment).toHaveBeenCalledTimes(1);
});
it('failure with invalid OTA file', async () => {
const fileParam: string = useImage(IMAGE_INVALID);
await expect(async () => {
// @ts-expect-error mock
await updateOtaPR(github, core, context, fileParam);
}).rejects.toThrow(expect.objectContaining({message: expect.stringContaining(`Not a valid OTA file`)}));
expectNoChanges(false);
expect(github.rest.pulls.createReviewComment).toHaveBeenCalledTimes(1);
});
it('failure with identical OTA file', async () => {
setManifest(common.BASE_INDEX_MANIFEST_FILENAME, [IMAGE_V14_1_METAS]);
const fileParam: string = useImage(IMAGE_V14_1);
await expect(async () => {
// @ts-expect-error mock
await updateOtaPR(github, core, context, fileParam);
}).rejects.toThrow(expect.objectContaining({message: expect.stringContaining(`Conflict with image at index \`0\``)}));
expectNoChanges(false);
expect(github.rest.pulls.createReviewComment).toHaveBeenCalledTimes(1);
});
it('failure with older OTA file that has identical in prev', async () => {
setManifest(common.BASE_INDEX_MANIFEST_FILENAME, [IMAGE_V14_1_METAS]);
setManifest(common.PREV_INDEX_MANIFEST_FILENAME, [IMAGE_V13_1_METAS]);
const fileParam: string = useImage(IMAGE_V13_1);
await expect(async () => {
// @ts-expect-error mock
await updateOtaPR(github, core, context, fileParam);
}).rejects.toThrow(
expect.objectContaining({message: expect.stringContaining(`an equal or better match is already present in prev manifest`)}),
);
expectNoChanges(false);
expect(github.rest.pulls.createReviewComment).toHaveBeenCalledTimes(1);
});
it('failure with older OTA file that has newer in prev', async () => {
setManifest(common.BASE_INDEX_MANIFEST_FILENAME, [IMAGE_V14_1_METAS]);
setManifest(common.PREV_INDEX_MANIFEST_FILENAME, [IMAGE_V13_1_METAS]);
const fileParam: string = useImage(IMAGE_V12_1);
await expect(async () => {
// @ts-expect-error mock
await updateOtaPR(github, core, context, fileParam);
}).rejects.toThrow(
expect.objectContaining({message: expect.stringContaining(`an equal or better match is already present in prev manifest`)}),
);
expectNoChanges(false);
expect(github.rest.pulls.createReviewComment).toHaveBeenCalledTimes(1);
});
it('success into base', async () => {
const fileParam: string = useImage(IMAGE_V14_1);
// @ts-expect-error mock
await updateOtaPR(github, core, context, fileParam);
expect(readManifestSpy).toHaveBeenCalledWith(common.BASE_INDEX_MANIFEST_FILENAME);
expect(readManifestSpy).toHaveBeenCalledWith(common.PREV_INDEX_MANIFEST_FILENAME);
expect(addImageToBaseSpy).toHaveBeenCalledTimes(1);
expect(addImageToPrevSpy).toHaveBeenCalledTimes(0);
expect(writeManifestSpy).toHaveBeenCalledTimes(2);
expect(writeManifestSpy).toHaveBeenCalledWith(common.BASE_INDEX_MANIFEST_FILENAME, [IMAGE_V14_1_METAS]);
});
it('success into prev', async () => {
setManifest(common.BASE_INDEX_MANIFEST_FILENAME, [IMAGE_V14_1_METAS]);
const fileParam: string = useImage(IMAGE_V13_1);
// @ts-expect-error mock
await updateOtaPR(github, core, context, fileParam);
expect(readManifestSpy).toHaveBeenCalledWith(common.BASE_INDEX_MANIFEST_FILENAME);
expect(readManifestSpy).toHaveBeenCalledWith(common.PREV_INDEX_MANIFEST_FILENAME);
expect(addImageToBaseSpy).toHaveBeenCalledTimes(0);
expect(addImageToPrevSpy).toHaveBeenCalledTimes(1);
expect(writeManifestSpy).toHaveBeenCalledTimes(2);
expect(writeManifestSpy).toHaveBeenCalledWith(common.PREV_INDEX_MANIFEST_FILENAME, [IMAGE_V13_1_METAS]);
});
it('success with newer than current without existing prev', async () => {
const fileParam: string = [useImage(IMAGE_V13_1), useImage(IMAGE_V14_1)].join(',');
// @ts-expect-error mock
await updateOtaPR(github, core, context, fileParam);
expect(readManifestSpy).toHaveBeenCalledTimes(2);
expect(addImageToBaseSpy).toHaveBeenCalledTimes(2); // adds both, relocates first during second processing
expect(addImageToPrevSpy).toHaveBeenCalledTimes(0);
expect(writeManifestSpy).toHaveBeenCalledTimes(2);
expect(writeManifestSpy).toHaveBeenCalledWith(common.BASE_INDEX_MANIFEST_FILENAME, [IMAGE_V14_1_METAS]);
expect(writeManifestSpy).toHaveBeenCalledWith(common.PREV_INDEX_MANIFEST_FILENAME, [IMAGE_V13_1_METAS]);
});
it('success with newer than current with existing prev', async () => {
const fileParam: string = [useImage(IMAGE_V12_1), useImage(IMAGE_V13_1), useImage(IMAGE_V14_1)].join(',');
// @ts-expect-error mock
await updateOtaPR(github, core, context, fileParam);
expect(readManifestSpy).toHaveBeenCalledTimes(2);
expect(addImageToBaseSpy).toHaveBeenCalledTimes(3); // adds both, relocates first during second processing
expect(addImageToPrevSpy).toHaveBeenCalledTimes(0);
expect(writeManifestSpy).toHaveBeenCalledTimes(2);
expect(writeManifestSpy).toHaveBeenCalledWith(common.BASE_INDEX_MANIFEST_FILENAME, [IMAGE_V14_1_METAS]);
expect(writeManifestSpy).toHaveBeenCalledWith(common.PREV_INDEX_MANIFEST_FILENAME, [IMAGE_V13_1_METAS]);
});
it('success with older that is newer than prev', async () => {
setManifest(common.PREV_INDEX_MANIFEST_FILENAME, [IMAGE_V12_1_METAS]);
const fileParam: string = [useImage(IMAGE_V14_1), useImage(IMAGE_V13_1)].join(',');
// @ts-expect-error mock
await updateOtaPR(github, core, context, fileParam);
expect(readManifestSpy).toHaveBeenCalledTimes(2);
expect(addImageToBaseSpy).toHaveBeenCalledTimes(1);
expect(addImageToPrevSpy).toHaveBeenCalledTimes(1);
expect(writeManifestSpy).toHaveBeenCalledTimes(2);
expect(writeManifestSpy).toHaveBeenCalledWith(common.BASE_INDEX_MANIFEST_FILENAME, [IMAGE_V14_1_METAS]);
expect(writeManifestSpy).toHaveBeenCalledWith(common.PREV_INDEX_MANIFEST_FILENAME, [IMAGE_V13_1_METAS]);
});
it('success with newer with missing file', async () => {
setManifest(common.BASE_INDEX_MANIFEST_FILENAME, [IMAGE_V13_1_METAS]);
const fileParam: string = [useImage(IMAGE_V14_1)].join(',');
// @ts-expect-error mock
await updateOtaPR(github, core, context, fileParam);
expect(readManifestSpy).toHaveBeenCalledTimes(2);
expect(addImageToBaseSpy).toHaveBeenCalledTimes(1);
expect(addImageToPrevSpy).toHaveBeenCalledTimes(0);
expect(writeManifestSpy).toHaveBeenCalledTimes(2);
expect(writeManifestSpy).toHaveBeenCalledWith(common.BASE_INDEX_MANIFEST_FILENAME, [IMAGE_V14_1_METAS]);
expect(writeManifestSpy).toHaveBeenCalledWith(common.PREV_INDEX_MANIFEST_FILENAME, []);
});
it('success with multiple different files', async () => {
const fileParam: string = [useImage(IMAGE_V14_2), useImage(IMAGE_V14_1)].join(',');
// @ts-expect-error mock
await updateOtaPR(github, core, context, fileParam);
expect(readManifestSpy).toHaveBeenCalledTimes(2);
expect(addImageToBaseSpy).toHaveBeenCalledTimes(2); // adds both, relocates first during second processing
expect(addImageToPrevSpy).toHaveBeenCalledTimes(0);
expect(writeManifestSpy).toHaveBeenCalledTimes(2);
expect(writeManifestSpy).toHaveBeenCalledWith(common.BASE_INDEX_MANIFEST_FILENAME, [IMAGE_V14_2_METAS, IMAGE_V14_1_METAS]);
expect(writeManifestSpy).toHaveBeenCalledWith(common.PREV_INDEX_MANIFEST_FILENAME, []);
});
it('success with extra metas', async () => {
const fileParam: string = useImage(IMAGE_V14_1);
const newContext = withBody(`Text before start tag \`\`\`json {"manufacturerName": ["lixee"]} \`\`\` Text after end tag`);
// @ts-expect-error mock
await updateOtaPR(github, core, newContext, fileParam);
expect(readManifestSpy).toHaveBeenCalledWith(common.BASE_INDEX_MANIFEST_FILENAME);
expect(readManifestSpy).toHaveBeenCalledWith(common.PREV_INDEX_MANIFEST_FILENAME);
expect(addImageToBaseSpy).toHaveBeenCalledTimes(1);
expect(addImageToPrevSpy).toHaveBeenCalledTimes(0);
expect(writeManifestSpy).toHaveBeenCalledTimes(2);
expect(writeManifestSpy).toHaveBeenCalledWith(common.BASE_INDEX_MANIFEST_FILENAME, [
withExtraMetas(IMAGE_V14_1_METAS, {manufacturerName: ['lixee']}),
]);
});
it('success with all extra metas', async () => {
const fileParam: string = useImage(IMAGE_V14_1);
const newContext = withBody(`Text before start tag
\`\`\`json
{
"force": false,
"hardwareVersionMax": 2,
"hardwareVersionMin": 1,
"manufacturerName": ["lixee"],
"maxFileVersion": 5,
"minFileVersion": 3,
"modelId": "bogus",
"releaseNotes": "bugfixes"
}
\`\`\`
Text after end tag`);
// @ts-expect-error mock
await updateOtaPR(github, core, newContext, fileParam);
expect(readManifestSpy).toHaveBeenCalledWith(common.BASE_INDEX_MANIFEST_FILENAME);
expect(readManifestSpy).toHaveBeenCalledWith(common.PREV_INDEX_MANIFEST_FILENAME);
expect(addImageToBaseSpy).toHaveBeenCalledTimes(1);
expect(addImageToPrevSpy).toHaveBeenCalledTimes(0);
expect(writeManifestSpy).toHaveBeenCalledTimes(2);
expect(writeManifestSpy).toHaveBeenCalledWith(common.BASE_INDEX_MANIFEST_FILENAME, [
withExtraMetas(IMAGE_V14_1_METAS, {
force: false,
hardwareVersionMax: 2,
hardwareVersionMin: 1,
manufacturerName: ['lixee'],
maxFileVersion: 5,
minFileVersion: 3,
modelId: 'bogus',
releaseNotes: 'bugfixes',
}),
]);
});
it('failure with invalid extra metas', async () => {
const fileParam: string = useImage(IMAGE_V14_1);
const newContext = withBody(`Text before start tag \`\`\`json {"manufacturerName": "myManuf"} \`\`\` Text after end tag`);
await expect(async () => {
// @ts-expect-error mock
await updateOtaPR(github, core, newContext, fileParam);
}).rejects.toThrow(
expect.objectContaining({message: expect.stringContaining(`Invalid format for 'manufacturerName', expected 'array of string' type.`)}),
);
expectNoChanges(true);
expect(github.rest.issues.createComment).toHaveBeenCalledTimes(1);
});
it.each([
['fileName'],
['originalUrl'],
['force'],
['hardwareVersionMax'],
['hardwareVersionMin'],
['manufacturerName'],
['maxFileVersion'],
['minFileVersion'],
['modelId'],
['releaseNotes'],
])('failure with invalid type for extra meta %s', async (metaName) => {
const fileParam: string = useImage(IMAGE_V14_1);
// use object since no value type is ever expected to be object
const newContext = withBody(`Text before start tag \`\`\`json {"${metaName}": {}} \`\`\` Text after end tag`);
await expect(async () => {
// @ts-expect-error mock
await updateOtaPR(github, core, newContext, fileParam);
}).rejects.toThrow(expect.objectContaining({message: expect.stringContaining(`Invalid format for '${metaName}'`)}));
expectNoChanges(true);
expect(github.rest.issues.createComment).toHaveBeenCalledTimes(1);
});
it('success with multiple files and specific extra metas', async () => {
const fileParam: string = [useImage(IMAGE_V13_1), useImage(IMAGE_V14_1)].join(',');
const newContext = withBody(`Text before start tag
\`\`\`json
[
{"fileName": "${IMAGE_V14_1}", "manufacturerName": ["lixee"], "hardwareVersionMin": 2},
{"fileName": "${IMAGE_V13_1}", "manufacturerName": ["lixee"]}
]
\`\`\`
Text after end tag`);
// @ts-expect-error mock
await updateOtaPR(github, core, newContext, fileParam);
expect(readManifestSpy).toHaveBeenCalledWith(common.BASE_INDEX_MANIFEST_FILENAME);
expect(readManifestSpy).toHaveBeenCalledWith(common.PREV_INDEX_MANIFEST_FILENAME);
expect(addImageToBaseSpy).toHaveBeenCalledTimes(2);
expect(addImageToPrevSpy).toHaveBeenCalledTimes(0);
expect(writeManifestSpy).toHaveBeenCalledTimes(2);
expect(writeManifestSpy).toHaveBeenCalledWith(common.BASE_INDEX_MANIFEST_FILENAME, [
withExtraMetas(IMAGE_V14_1_METAS, {manufacturerName: ['lixee'], hardwareVersionMin: 2}),
]);
expect(writeManifestSpy).toHaveBeenCalledWith(common.PREV_INDEX_MANIFEST_FILENAME, [
withExtraMetas(IMAGE_V13_1_METAS, {manufacturerName: ['lixee']}),
]);
});
it('success with multiple files and specific extra metas, ignore without fileName', async () => {
const fileParam: string = [useImage(IMAGE_V13_1), useImage(IMAGE_V14_1)].join(',');
const newContext = withBody(`Text before start tag
\`\`\`json
[
{"fileName": "${IMAGE_V14_1}", "manufacturerName": ["lixee"], "hardwareVersionMin": 2},
{"manufacturerName": ["lixee"]}
]
\`\`\`
Text after end tag`);
// @ts-expect-error mock
await updateOtaPR(github, core, newContext, fileParam);
expect(readManifestSpy).toHaveBeenCalledWith(common.BASE_INDEX_MANIFEST_FILENAME);
expect(readManifestSpy).toHaveBeenCalledWith(common.PREV_INDEX_MANIFEST_FILENAME);
expect(addImageToBaseSpy).toHaveBeenCalledTimes(2);
expect(addImageToPrevSpy).toHaveBeenCalledTimes(0);
expect(writeManifestSpy).toHaveBeenCalledTimes(2);
expect(writeManifestSpy).toHaveBeenCalledWith(common.BASE_INDEX_MANIFEST_FILENAME, [
withExtraMetas(IMAGE_V14_1_METAS, {manufacturerName: ['lixee'], hardwareVersionMin: 2}),
]);
expect(writeManifestSpy).toHaveBeenCalledWith(common.PREV_INDEX_MANIFEST_FILENAME, [IMAGE_V13_1_METAS]);
});
});

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@@ -0,0 +1 @@
this is not a valid OTA file

216
tests/jest.config.ts Normal file
View File

@@ -0,0 +1,216 @@
/**
* For a detailed explanation regarding each configuration property, visit:
* https://jestjs.io/docs/configuration
*/
// import type {Config} from 'jest';
import {createDefaultEsmPreset, JestConfigWithTsJest} from 'ts-jest';
const defaultEsmPreset = createDefaultEsmPreset();
const config: JestConfigWithTsJest = {
// All imported modules in your tests should be mocked automatically
// automock: false,
// Stop running tests after `n` failures
// bail: 0,
// The directory where Jest should store its cached dependency information
cacheDirectory: '.jest-tmp',
// Automatically clear mock calls, instances, contexts and results before every test
clearMocks: true,
// Indicates whether the coverage information should be collected while executing the test
collectCoverage: false,
// An array of glob patterns indicating a set of files for which coverage information should be collected
collectCoverageFrom: ['src/ghw_update_ota_pr.ts', 'src/process_firmware_image.ts', 'src/ghw_reprocess_all_images.ts'],
// The directory where Jest should output its coverage files
coverageDirectory: 'coverage',
// An array of regexp pattern strings used to skip coverage collection
// coveragePathIgnorePatterns: [
// "\\\\node_modules\\\\"
// ],
// Indicates which provider should be used to instrument code for coverage
coverageProvider: 'babel',
// A list of reporter names that Jest uses when writing coverage reports
coverageReporters: [
// "json",
// "text",
'lcov',
// "clover"
],
// An object that configures minimum threshold enforcement for coverage results
coverageThreshold: {
global: {
branches: 100,
functions: 100,
lines: 100,
statements: 100,
},
},
// A path to a custom dependency extractor
// dependencyExtractor: undefined,
// Make calling deprecated APIs throw helpful error messages
// errorOnDeprecated: false,
// The default configuration for fake timers
// fakeTimers: {
// "enableGlobally": false
// },
// Force coverage collection from ignored files using an array of glob patterns
// forceCoverageMatch: [],
// A path to a module which exports an async function that is triggered once before all test suites
// globalSetup: undefined,
// A path to a module which exports an async function that is triggered once after all test suites
// globalTeardown: undefined,
// A set of global variables that need to be available in all test environments
// globals: {},
// The maximum amount of workers used to run your tests. Can be specified as % or a number. E.g. maxWorkers: 10% will use 10% of your CPU amount + 1 as the maximum worker number. maxWorkers: 2 will use a maximum of 2 workers.
maxWorkers: '50%',
// An array of directory names to be searched recursively up from the requiring module's location
// moduleDirectories: [
// "node_modules"
// ],
// An array of file extensions your modules use
moduleFileExtensions: [
// commonly used first
'ts',
'json',
'js',
'mjs',
'cjs',
'jsx',
'tsx',
'node',
],
// A map from regular expressions to module names or to arrays of module names that allow to stub out resources with a single module
// moduleNameMapper: {},
// An array of regexp pattern strings, matched against all module paths before considered 'visible' to the module loader
// modulePathIgnorePatterns: [],
// Activates notifications for test results
// notify: false,
// An enum that specifies notification mode. Requires { notify: true }
// notifyMode: "failure-change",
// A preset that is used as a base for Jest's configuration
// preset: undefined,
// Run tests from one or more projects
// projects: undefined,
// Use this configuration option to add custom reporters to Jest
// reporters: undefined,
// Automatically reset mock state before every test
// resetMocks: false,
// Reset the module registry before running each individual test
// resetModules: false,
// A path to a custom resolver
// resolver: undefined,
// Automatically restore mock state and implementation before every test
// restoreMocks: false,
// The root directory that Jest should scan for tests and modules within
rootDir: '..',
// A list of paths to directories that Jest should use to search for files in
// roots: [
// "<rootDir>"
// ],
// Allows you to use a custom runner instead of Jest's default test runner
// runner: "jest-runner",
// The paths to modules that run some code to configure or set up the testing environment before each test
// setupFiles: [],
// A list of paths to modules that run some code to configure or set up the testing framework before each test
// setupFilesAfterEnv: [],
// The number of seconds after which a test is considered as slow and reported as such in the results.
// slowTestThreshold: 5,
// A list of paths to snapshot serializer modules Jest should use for snapshot testing
// snapshotSerializers: [],
// The test environment that will be used for testing
// testEnvironment: "jest-environment-node",
// Options that will be passed to the testEnvironment
// testEnvironmentOptions: {},
// Adds a location field to test results
// testLocationInResults: false,
// The glob patterns Jest uses to detect test files
// testMatch: [
// "**/__tests__/**/*.[jt]s?(x)",
// "**/?(*.)+(spec|test).[tj]s?(x)"
// ],
// An array of regexp pattern strings that are matched against all test paths, matched tests are skipped
// testPathIgnorePatterns: [
// "\\\\node_modules\\\\"
// ],
// The regexp pattern or array of patterns that Jest uses to detect test files
// testRegex: [],
// This option allows the use of a custom results processor
// testResultsProcessor: undefined,
// This option allows use of a custom test runner
// testRunner: "jest-circus/runner",
// A map from regular expressions to paths to transformers
// transform: undefined,
// An array of regexp pattern strings that are matched against all source file paths, matched files will skip transformation
// transformIgnorePatterns: [
// "\\\\node_modules\\\\",
// "\\.pnp\\.[^\\\\]+$"
// ],
// An array of regexp pattern strings that are matched against all modules before the module loader will automatically return a mock for them
// unmockedModulePathPatterns: undefined,
// Indicates whether each individual test should be reported during the run
// verbose: undefined,
// An array of regexp patterns that are matched against all source file paths before re-running tests in watch mode
// watchPathIgnorePatterns: [],
// Whether to use watchman for file crawling
// watchman: true,
...defaultEsmPreset,
moduleNameMapper: {
'^(\\.{1,2}/.*)\\.js$': '$1',
},
};
export default config;

View File

@@ -0,0 +1,401 @@
import type {RepoImageMeta} from '../src/types';
import {existsSync, mkdirSync, readFileSync, rmSync} from 'fs';
import * as common from '../src/common';
import {processFirmwareImage, ProcessFirmwareImageStatus} from '../src/process_firmware_image';
import {
BASE_IMAGES_TEST_DIR_PATH,
getAdjustedContent,
getImageOriginalDirPath,
IMAGE_INVALID,
IMAGE_TAR,
IMAGE_TAR_METAS,
IMAGE_V12_1,
IMAGE_V12_1_METAS,
IMAGE_V13_1,
IMAGE_V13_1_METAS,
IMAGE_V14_1,
IMAGE_V14_1_METAS,
IMAGES_TEST_DIR,
PREV_IMAGES_TEST_DIR_PATH,
useImage,
withExtraMetas,
} from './data.test';
describe('Process Firmware Image', () => {
let baseManifest: RepoImageMeta[];
let prevManifest: RepoImageMeta[];
let consoleErrorSpy: jest.SpyInstance;
let consoleLogSpy: jest.SpyInstance;
let readManifestSpy: jest.SpyInstance;
let writeManifestSpy: jest.SpyInstance;
let addImageToBaseSpy: jest.SpyInstance;
let addImageToPrevSpy: jest.SpyInstance;
let fetchSpy: jest.SpyInstance;
let setTimeoutSpy: jest.SpyInstance;
let fetchReturnedStatus: {ok: boolean; status: number; body?: object} = {ok: true, status: 200, body: {}};
const getManifest = (fileName: string): RepoImageMeta[] => {
if (fileName === common.BASE_INDEX_MANIFEST_FILENAME) {
return baseManifest;
} else if (fileName === common.PREV_INDEX_MANIFEST_FILENAME) {
return prevManifest;
} else {
throw new Error(`${fileName} not supported`);
}
};
const setManifest = (fileName: string, content: RepoImageMeta[]): void => {
const adjustedContent = getAdjustedContent(fileName, content);
if (fileName === common.BASE_INDEX_MANIFEST_FILENAME) {
baseManifest = adjustedContent;
} else if (fileName === common.PREV_INDEX_MANIFEST_FILENAME) {
prevManifest = adjustedContent;
} else {
throw new Error(`${fileName} not supported`);
}
};
const resetManifests = (): void => {
baseManifest = [];
prevManifest = [];
};
const withOriginalUrl = (originalUrl: string, meta: RepoImageMeta): RepoImageMeta => {
const newMeta = structuredClone(meta);
newMeta.originalUrl = originalUrl;
return newMeta;
};
const expectNoChanges = (noReadManifest: boolean = false): void => {
if (noReadManifest) {
expect(readManifestSpy).toHaveBeenCalledTimes(0);
} else {
expect(readManifestSpy).toHaveBeenCalledTimes(2);
expect(fetchSpy).toHaveBeenCalledTimes(1);
}
expect(addImageToBaseSpy).toHaveBeenCalledTimes(0);
expect(addImageToPrevSpy).toHaveBeenCalledTimes(0);
expect(writeManifestSpy).toHaveBeenCalledTimes(0);
};
const expectWriteNoChanges = (inBase: boolean = true, inPrev: boolean = true): void => {
if (inBase) {
expect(writeManifestSpy).toHaveBeenNthCalledWith(
1,
common.PREV_INDEX_MANIFEST_FILENAME,
getManifest(common.PREV_INDEX_MANIFEST_FILENAME),
);
}
if (inPrev) {
expect(writeManifestSpy).toHaveBeenNthCalledWith(
2,
common.BASE_INDEX_MANIFEST_FILENAME,
getManifest(common.BASE_INDEX_MANIFEST_FILENAME),
);
}
};
beforeAll(() => {});
afterAll(() => {
consoleErrorSpy.mockRestore();
consoleLogSpy.mockRestore();
readManifestSpy.mockRestore();
writeManifestSpy.mockRestore();
addImageToBaseSpy.mockRestore();
addImageToPrevSpy.mockRestore();
fetchSpy.mockRestore();
setTimeoutSpy.mockRestore();
rmSync(BASE_IMAGES_TEST_DIR_PATH, {recursive: true, force: true});
rmSync(PREV_IMAGES_TEST_DIR_PATH, {recursive: true, force: true});
});
beforeEach(() => {
resetManifests();
fetchReturnedStatus = {ok: true, status: 200, body: {}};
consoleErrorSpy = jest.spyOn(console, 'error');
consoleLogSpy = jest.spyOn(console, 'log');
readManifestSpy = jest.spyOn(common, 'readManifest').mockImplementation(getManifest);
writeManifestSpy = jest.spyOn(common, 'writeManifest').mockImplementation(setManifest);
addImageToBaseSpy = jest.spyOn(common, 'addImageToBase');
addImageToPrevSpy = jest.spyOn(common, 'addImageToPrev');
fetchSpy = jest.spyOn(global, 'fetch').mockImplementation(
// @ts-expect-error mocked as needed
(input) => {
return {
ok: fetchReturnedStatus.ok,
status: fetchReturnedStatus.status,
body: fetchReturnedStatus.body,
arrayBuffer: (): ArrayBuffer => readFileSync(getImageOriginalDirPath(input as string)),
};
},
);
setTimeoutSpy = jest.spyOn(global, 'setTimeout').mockImplementation(
// @ts-expect-error mock
(fn) => {
fn();
},
);
});
afterEach(() => {
rmSync(BASE_IMAGES_TEST_DIR_PATH, {recursive: true, force: true});
rmSync(PREV_IMAGES_TEST_DIR_PATH, {recursive: true, force: true});
});
it('failure with fetch ok', async () => {
fetchReturnedStatus.ok = false;
fetchReturnedStatus.status = 429;
const status = await processFirmwareImage(IMAGES_TEST_DIR, IMAGE_V14_1, IMAGE_V14_1);
expect(status).toStrictEqual(ProcessFirmwareImageStatus.REQUEST_FAILED);
expect(consoleErrorSpy).toHaveBeenCalledWith(
expect.stringContaining(`Invalid response from ${IMAGE_V14_1} status=${fetchReturnedStatus.status}.`),
);
expectNoChanges(false);
});
it('failure with fetch body', async () => {
fetchReturnedStatus.body = undefined;
const status = await processFirmwareImage(IMAGES_TEST_DIR, IMAGE_V14_1, IMAGE_V14_1);
expect(status).toStrictEqual(ProcessFirmwareImageStatus.REQUEST_FAILED);
expect(consoleErrorSpy).toHaveBeenCalledWith(
expect.stringContaining(`Invalid response from ${IMAGE_V14_1} status=${fetchReturnedStatus.status}.`),
);
expectNoChanges(false);
});
it('failure with invalid OTA file', async () => {
const status = await processFirmwareImage(IMAGES_TEST_DIR, IMAGE_INVALID, IMAGE_INVALID);
expect(status).toStrictEqual(ProcessFirmwareImageStatus.ERROR);
expect(consoleErrorSpy).toHaveBeenCalledWith(expect.stringContaining(`Not a valid OTA fil`));
expectNoChanges(false);
});
it('failure with identical OTA file', async () => {
setManifest(common.BASE_INDEX_MANIFEST_FILENAME, [IMAGE_V14_1_METAS]);
const status = await processFirmwareImage(IMAGES_TEST_DIR, IMAGE_V14_1, IMAGE_V14_1);
expect(status).toStrictEqual(ProcessFirmwareImageStatus.SUCCESS);
expect(consoleLogSpy).toHaveBeenCalledWith(expect.stringContaining(`Base manifest already has version`));
expect(writeManifestSpy).toHaveBeenNthCalledWith(1, common.PREV_INDEX_MANIFEST_FILENAME, getManifest(common.PREV_INDEX_MANIFEST_FILENAME));
expect(writeManifestSpy).toHaveBeenNthCalledWith(2, common.BASE_INDEX_MANIFEST_FILENAME, getManifest(common.BASE_INDEX_MANIFEST_FILENAME));
expectWriteNoChanges();
});
it('failure with older OTA file that has identical in prev', async () => {
setManifest(common.BASE_INDEX_MANIFEST_FILENAME, [IMAGE_V14_1_METAS]);
setManifest(common.PREV_INDEX_MANIFEST_FILENAME, [IMAGE_V13_1_METAS]);
const status = await processFirmwareImage(IMAGES_TEST_DIR, IMAGE_V13_1, IMAGE_V13_1);
expect(status).toStrictEqual(ProcessFirmwareImageStatus.SUCCESS);
expect(consoleLogSpy).toHaveBeenCalledWith(expect.stringContaining(`an equal or better match is already present in prev manifest`));
expectWriteNoChanges();
});
it('failure with older OTA file that has newer in prev', async () => {
setManifest(common.BASE_INDEX_MANIFEST_FILENAME, [IMAGE_V14_1_METAS]);
setManifest(common.PREV_INDEX_MANIFEST_FILENAME, [IMAGE_V13_1_METAS]);
const status = await processFirmwareImage(IMAGES_TEST_DIR, IMAGE_V12_1, IMAGE_V12_1);
expect(status).toStrictEqual(ProcessFirmwareImageStatus.SUCCESS);
expect(consoleLogSpy).toHaveBeenCalledWith(expect.stringContaining(`an equal or better match is already present in prev manifest`));
expectWriteNoChanges();
});
it('success into base', async () => {
const status = await processFirmwareImage(IMAGES_TEST_DIR, IMAGE_V14_1, IMAGE_V14_1);
expect(status).toStrictEqual(ProcessFirmwareImageStatus.SUCCESS);
expect(readManifestSpy).toHaveBeenCalledWith(common.BASE_INDEX_MANIFEST_FILENAME);
expect(readManifestSpy).toHaveBeenCalledWith(common.PREV_INDEX_MANIFEST_FILENAME);
expect(addImageToBaseSpy).toHaveBeenCalledTimes(1);
expect(addImageToPrevSpy).toHaveBeenCalledTimes(0);
expect(writeManifestSpy).toHaveBeenCalledTimes(2);
expect(writeManifestSpy).toHaveBeenCalledWith(common.BASE_INDEX_MANIFEST_FILENAME, [withOriginalUrl(IMAGE_V14_1, IMAGE_V14_1_METAS)]);
});
it('success into prev', async () => {
setManifest(common.BASE_INDEX_MANIFEST_FILENAME, [withOriginalUrl(IMAGE_V14_1, IMAGE_V14_1_METAS)]);
const status = await processFirmwareImage(IMAGES_TEST_DIR, IMAGE_V13_1, IMAGE_V13_1);
expect(status).toStrictEqual(ProcessFirmwareImageStatus.SUCCESS);
expect(readManifestSpy).toHaveBeenCalledWith(common.BASE_INDEX_MANIFEST_FILENAME);
expect(readManifestSpy).toHaveBeenCalledWith(common.PREV_INDEX_MANIFEST_FILENAME);
expect(addImageToBaseSpy).toHaveBeenCalledTimes(0);
expect(addImageToPrevSpy).toHaveBeenCalledTimes(1);
expect(writeManifestSpy).toHaveBeenCalledTimes(2);
expectWriteNoChanges(true, false);
expect(writeManifestSpy).toHaveBeenCalledWith(common.PREV_INDEX_MANIFEST_FILENAME, [withOriginalUrl(IMAGE_V13_1, IMAGE_V13_1_METAS)]);
});
it('success with newer than current without existing prev', async () => {
setManifest(common.BASE_INDEX_MANIFEST_FILENAME, [withOriginalUrl(IMAGE_V13_1, IMAGE_V13_1_METAS)]);
useImage(IMAGE_V13_1, BASE_IMAGES_TEST_DIR_PATH);
const status = await processFirmwareImage(IMAGES_TEST_DIR, IMAGE_V14_1, IMAGE_V14_1);
expect(status).toStrictEqual(ProcessFirmwareImageStatus.SUCCESS);
expect(readManifestSpy).toHaveBeenCalledTimes(2);
expect(addImageToBaseSpy).toHaveBeenCalledTimes(1);
expect(addImageToPrevSpy).toHaveBeenCalledTimes(0);
expect(writeManifestSpy).toHaveBeenCalledTimes(2);
expect(writeManifestSpy).toHaveBeenCalledWith(common.BASE_INDEX_MANIFEST_FILENAME, [withOriginalUrl(IMAGE_V14_1, IMAGE_V14_1_METAS)]);
expect(writeManifestSpy).toHaveBeenCalledWith(common.PREV_INDEX_MANIFEST_FILENAME, [withOriginalUrl(IMAGE_V13_1, IMAGE_V13_1_METAS)]);
});
it('success with newer than current with existing prev', async () => {
setManifest(common.BASE_INDEX_MANIFEST_FILENAME, [withOriginalUrl(IMAGE_V13_1, IMAGE_V13_1_METAS)]);
setManifest(common.PREV_INDEX_MANIFEST_FILENAME, [withOriginalUrl(IMAGE_V12_1, IMAGE_V12_1_METAS)]);
useImage(IMAGE_V13_1, BASE_IMAGES_TEST_DIR_PATH);
useImage(IMAGE_V12_1, PREV_IMAGES_TEST_DIR_PATH);
const status = await processFirmwareImage(IMAGES_TEST_DIR, IMAGE_V14_1, IMAGE_V14_1);
expect(status).toStrictEqual(ProcessFirmwareImageStatus.SUCCESS);
expect(readManifestSpy).toHaveBeenCalledTimes(2);
expect(addImageToBaseSpy).toHaveBeenCalledTimes(1);
expect(addImageToPrevSpy).toHaveBeenCalledTimes(0);
expect(writeManifestSpy).toHaveBeenCalledTimes(2);
expect(writeManifestSpy).toHaveBeenCalledWith(common.BASE_INDEX_MANIFEST_FILENAME, [withOriginalUrl(IMAGE_V14_1, IMAGE_V14_1_METAS)]);
expect(writeManifestSpy).toHaveBeenCalledWith(common.PREV_INDEX_MANIFEST_FILENAME, [withOriginalUrl(IMAGE_V13_1, IMAGE_V13_1_METAS)]);
});
it('success with older that is newer than prev', async () => {
setManifest(common.BASE_INDEX_MANIFEST_FILENAME, [withOriginalUrl(IMAGE_V14_1, IMAGE_V14_1_METAS)]);
setManifest(common.PREV_INDEX_MANIFEST_FILENAME, [withOriginalUrl(IMAGE_V12_1, IMAGE_V12_1_METAS)]);
useImage(IMAGE_V14_1, BASE_IMAGES_TEST_DIR_PATH);
useImage(IMAGE_V12_1, PREV_IMAGES_TEST_DIR_PATH);
const status = await processFirmwareImage(IMAGES_TEST_DIR, IMAGE_V13_1, IMAGE_V13_1);
expect(status).toStrictEqual(ProcessFirmwareImageStatus.SUCCESS);
expect(readManifestSpy).toHaveBeenCalledTimes(2);
expect(addImageToBaseSpy).toHaveBeenCalledTimes(0);
expect(addImageToPrevSpy).toHaveBeenCalledTimes(1);
expect(writeManifestSpy).toHaveBeenCalledTimes(2);
expect(writeManifestSpy).toHaveBeenCalledWith(common.BASE_INDEX_MANIFEST_FILENAME, [withOriginalUrl(IMAGE_V14_1, IMAGE_V14_1_METAS)]);
expect(writeManifestSpy).toHaveBeenCalledWith(common.PREV_INDEX_MANIFEST_FILENAME, [withOriginalUrl(IMAGE_V13_1, IMAGE_V13_1_METAS)]);
});
it('success with newer with missing file', async () => {
setManifest(common.BASE_INDEX_MANIFEST_FILENAME, [withOriginalUrl(IMAGE_V13_1, IMAGE_V13_1_METAS)]);
// useImage(IMAGE_V13_1, BASE_IMAGES_TEST_DIR_PATH);
const status = await processFirmwareImage(IMAGES_TEST_DIR, IMAGE_V14_1, IMAGE_V14_1);
expect(status).toStrictEqual(ProcessFirmwareImageStatus.SUCCESS);
expect(readManifestSpy).toHaveBeenCalledTimes(2);
expect(addImageToBaseSpy).toHaveBeenCalledTimes(1);
expect(addImageToPrevSpy).toHaveBeenCalledTimes(0);
expect(writeManifestSpy).toHaveBeenCalledTimes(2);
expect(writeManifestSpy).toHaveBeenCalledWith(common.BASE_INDEX_MANIFEST_FILENAME, [withOriginalUrl(IMAGE_V14_1, IMAGE_V14_1_METAS)]);
expect(writeManifestSpy).toHaveBeenCalledWith(common.PREV_INDEX_MANIFEST_FILENAME, []);
});
it('success with extra metas', async () => {
const status = await processFirmwareImage(IMAGES_TEST_DIR, IMAGE_V14_1, IMAGE_V14_1, {manufacturerName: ['lixee']});
expect(status).toStrictEqual(ProcessFirmwareImageStatus.SUCCESS);
expect(readManifestSpy).toHaveBeenCalledWith(common.BASE_INDEX_MANIFEST_FILENAME);
expect(readManifestSpy).toHaveBeenCalledWith(common.PREV_INDEX_MANIFEST_FILENAME);
expect(addImageToBaseSpy).toHaveBeenCalledTimes(1);
expect(addImageToPrevSpy).toHaveBeenCalledTimes(0);
expect(writeManifestSpy).toHaveBeenCalledTimes(2);
expect(writeManifestSpy).toHaveBeenCalledWith(common.BASE_INDEX_MANIFEST_FILENAME, [
withOriginalUrl(IMAGE_V14_1, withExtraMetas(IMAGE_V14_1_METAS, {manufacturerName: ['lixee']})),
]);
});
it('success with all extra metas', async () => {
const status = await processFirmwareImage(IMAGES_TEST_DIR, IMAGE_V14_1, IMAGE_V14_1, {
originalUrl: `https://example.com/${IMAGE_V14_1}`,
force: false,
hardwareVersionMax: 2,
hardwareVersionMin: 1,
manufacturerName: ['lixee'],
maxFileVersion: 5,
minFileVersion: 3,
modelId: 'bogus',
releaseNotes: 'bugfixes',
});
expect(status).toStrictEqual(ProcessFirmwareImageStatus.SUCCESS);
expect(readManifestSpy).toHaveBeenCalledWith(common.BASE_INDEX_MANIFEST_FILENAME);
expect(readManifestSpy).toHaveBeenCalledWith(common.PREV_INDEX_MANIFEST_FILENAME);
expect(addImageToBaseSpy).toHaveBeenCalledTimes(1);
expect(addImageToPrevSpy).toHaveBeenCalledTimes(0);
expect(writeManifestSpy).toHaveBeenCalledTimes(2);
expect(writeManifestSpy).toHaveBeenCalledWith(common.BASE_INDEX_MANIFEST_FILENAME, [
withOriginalUrl(
`https://example.com/${IMAGE_V14_1}`,
withExtraMetas(IMAGE_V14_1_METAS, {
force: false,
hardwareVersionMax: 2,
hardwareVersionMin: 1,
manufacturerName: ['lixee'],
maxFileVersion: 5,
minFileVersion: 3,
modelId: 'bogus',
releaseNotes: 'bugfixes',
}),
),
]);
});
it('success with tar', async () => {
if (!existsSync(common.TMP_DIR)) {
mkdirSync(common.TMP_DIR, {recursive: true});
}
const status = await processFirmwareImage(IMAGES_TEST_DIR, IMAGE_TAR, IMAGE_TAR, {}, true, (f) => f.endsWith('.ota'));
expect(status).toStrictEqual(ProcessFirmwareImageStatus.SUCCESS);
expect(readManifestSpy).toHaveBeenCalledWith(common.BASE_INDEX_MANIFEST_FILENAME);
expect(readManifestSpy).toHaveBeenCalledWith(common.PREV_INDEX_MANIFEST_FILENAME);
expect(addImageToBaseSpy).toHaveBeenCalledTimes(1);
expect(addImageToPrevSpy).toHaveBeenCalledTimes(0);
expect(writeManifestSpy).toHaveBeenCalledTimes(2);
expect(writeManifestSpy).toHaveBeenCalledWith(common.BASE_INDEX_MANIFEST_FILENAME, [withOriginalUrl(IMAGE_TAR, IMAGE_TAR_METAS)]);
rmSync(common.TMP_DIR, {recursive: true, force: true});
});
it('failure with invalid tar', async () => {
if (!existsSync(common.TMP_DIR)) {
mkdirSync(common.TMP_DIR, {recursive: true});
}
const status = await processFirmwareImage(IMAGES_TEST_DIR, IMAGE_INVALID, IMAGE_INVALID, {}, true, (f) => f.endsWith('.ota'));
expect(status).toStrictEqual(ProcessFirmwareImageStatus.TAR_NO_IMAGE);
expectNoChanges(true);
rmSync(common.TMP_DIR, {recursive: true, force: true});
});
it('failure with extract tar (missing dir)', async () => {
// if (!existsSync(common.TMP_DIR)) {
// mkdirSync(common.TMP_DIR, {recursive: true});
// }
const status = await processFirmwareImage(IMAGES_TEST_DIR, IMAGE_TAR, IMAGE_TAR, {}, true, (f) => f.endsWith('.ota'));
expect(status).toStrictEqual(ProcessFirmwareImageStatus.TAR_NO_IMAGE);
expect(consoleErrorSpy).toHaveBeenCalledWith(expect.objectContaining({syscall: 'chdir', code: 'ENOENT'}));
expectNoChanges(false);
rmSync(common.TMP_DIR, {recursive: true, force: true});
});
});

10
tests/tsconfig.json Normal file
View File

@@ -0,0 +1,10 @@
{
"extends": "../tsconfig",
"include": ["./**/*", "./jest.config.ts"],
"compilerOptions": {
"types": ["jest"],
"rootDir": "..",
"noEmit": true
},
"references": [{"path": ".."}]
}

21
tsconfig.json Normal file
View File

@@ -0,0 +1,21 @@
{
"compilerOptions": {
"strict": true,
"declaration": true,
"module": "ES2022",
"moduleResolution": "node",
"target": "ES2022",
"lib": ["ES2022"],
"outDir": "dist",
"rootDir": "src",
"noUnusedLocals": true,
"esModuleInterop": true,
"noImplicitAny": true,
"noImplicitThis": true,
"composite": true
},
"include": ["./src/**/*", "./eslint.config.mjs"],
"ts-node": {
"esm": true
}
}