Merge branch 'devel' into dev/commRefactoringNG
This commit is contained in:
commit
cb47151646
125 files changed
+11604
-8061
No files matched your search
@@ -1,5 +1,6 @@
|
||||
approve_label: "approved"
|
||||
problem_label: "needs some work"
|
||||
ignore_label: "skip validation"
|
||||
|
||||
allowed_targets: ["maintenance", "devel", "staging/maintenance", "staging/devel"]
|
||||
forbidden_sources:
|
||||
|
||||
@@ -50,7 +50,7 @@ jobs:
|
||||
name: 🧪 Unit tests
|
||||
strategy:
|
||||
matrix:
|
||||
python: ["3.7", "3.8", "3.9"]
|
||||
python: ["3.7", "3.8", "3.9", "3.10"]
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v2
|
||||
@@ -70,7 +70,7 @@ jobs:
|
||||
needs: build
|
||||
strategy:
|
||||
matrix:
|
||||
python: ["3.7", "3.8", "3.9"]
|
||||
python: ["3.7", "3.8", "3.9", "3.10"]
|
||||
installable: ["wheel", "sdist"]
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
@@ -95,7 +95,7 @@ jobs:
|
||||
test-e2e:
|
||||
name: 🧪 E2E tests
|
||||
needs: build
|
||||
runs-on: ubuntu-16.04
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: ⬇ Checkout code
|
||||
uses: actions/checkout@v2
|
||||
@@ -183,10 +183,14 @@ jobs:
|
||||
needs: publish-on-pypi
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: 👀 Determine version
|
||||
run: |
|
||||
OCTOPRINT_VERSION=$(echo $GITHUB_REF | cut -d/ -f3)
|
||||
echo "OCTOPRINT_VERSION=$OCTOPRINT_VERSION" >> $GITHUB_ENV
|
||||
- name: 🚀 Repository Dispatch
|
||||
uses: peter-evans/repository-dispatch@v1
|
||||
with:
|
||||
token: ${{ secrets.REPODISPATCH_TOKEN }}
|
||||
repository: OctoPrint/OctoPi-UpToDate
|
||||
event-type: octoprint_release
|
||||
client-payload: '{"version": "${{ github.ref }}"}'
|
||||
client-payload: '{"version": "${{ env.OCTOPRINT_VERSION }}"}'
|
||||
@@ -1,19 +1,18 @@
|
||||
name: "Issue Automation"
|
||||
on:
|
||||
issues:
|
||||
types: [opened, edited, closed, reopened]
|
||||
types: [opened, edited, closed, reopened, labeled, unlabeled]
|
||||
|
||||
jobs:
|
||||
issue-automation:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/github-script@v2
|
||||
- uses: actions/github-script@v5
|
||||
with:
|
||||
github-token: ${{ secrets.GITHUB_TOKEN }}
|
||||
script: |
|
||||
let labels = [];
|
||||
let labels = context.payload.issue.labels.map(label => label.name);
|
||||
let setLabels = false;
|
||||
context.payload.issue.labels.forEach(label => { labels.push(label.name) });
|
||||
|
||||
switch (context.payload.action) {
|
||||
|
||||
@@ -55,7 +54,7 @@ jobs:
|
||||
}
|
||||
|
||||
if (setLabels) {
|
||||
github.issues.setLabels({
|
||||
github.rest.issues.setLabels({
|
||||
issue_number: context.issue.number,
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
@@ -67,3 +66,96 @@ jobs:
|
||||
# if: github.event_name == 'issues' && (github.event.action == 'opened' || github.event.action == 'edited')
|
||||
# with:
|
||||
# repo-token: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- uses: actions/github-script@v5
|
||||
env:
|
||||
REMINDER: >
|
||||
Hi @${{ github.event.issue.user.login }}!
|
||||
|
||||
|
||||
It looks like you didn't upload a [system info bundle](https://community.octoprint.org/t/29887) as requested by the template.
|
||||
A bundle is required to further process your issue. It contains important logs and
|
||||
system information to be able to put your issue into context and give pointers as to
|
||||
what has happened.
|
||||
|
||||
|
||||
Please **edit your original post above** and upload **a bundle zip file**. Actually upload the file please and
|
||||
do not paste some link to a cloud provider, we want to have everything in one place here. Also do
|
||||
not unpack, repack or otherwise modify the bundle or its name, share it **exactly** like you get it from OctoPrint.
|
||||
|
||||
|
||||
Without the availability of a bundle, your issue will have to be closed.
|
||||
|
||||
|
||||
Thank you for your collaboration.
|
||||
THANKYOU: >
|
||||
Thank you @${{ github.event.issue.user.login }} for adding a bundle! Now this can actually get looked at.
|
||||
with:
|
||||
script: |
|
||||
const { REMINDER, THANKYOU } = process.env;
|
||||
const bundleRegex = /\[(octoprint-systeminfo-\d{14}\.zip)\]\(([^)]+)\)/g;
|
||||
const marker = "<!-- check_for_bundle -->";
|
||||
|
||||
const issueLabels = await github.rest.issues.listLabelsOnIssue({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
issue_number: context.issue.number
|
||||
});
|
||||
let labels = issueLabels.data.map(label => label.name);
|
||||
|
||||
const comments = await github.rest.issues.listComments({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
issue_number: context.issue.number,
|
||||
})
|
||||
const comment = comments.data.find(c => c.user.login === "github-actions[bot]" && c.body.includes(marker));
|
||||
if (comment) {
|
||||
console.log("Found comment, id=" + comment.id);
|
||||
} else {
|
||||
console.log("No comment found");
|
||||
}
|
||||
|
||||
if (!labels.includes("triage") || labels.includes("approved")) {
|
||||
console.log("Deleting comment if it exists...");
|
||||
if (comment) {
|
||||
await github.rest.issues.deleteComment({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
comment_id: comment.id,
|
||||
})
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
const found = !!context.payload.issue.body.match(bundleRegex);
|
||||
|
||||
if (!found) {
|
||||
console.log("No bundle found, posting/updating reminder");
|
||||
const text = REMINDER + "\n" + marker;
|
||||
if (!comment) {
|
||||
await github.rest.issues.createComment({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
issue_number: context.issue.number,
|
||||
body: text
|
||||
});
|
||||
} else if (comment.body !== text) {
|
||||
await github.rest.issues.updateComment({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
comment_id: comment.id,
|
||||
body: text
|
||||
});
|
||||
}
|
||||
} else if (found && comment) {
|
||||
console.log("Bundle found, saying thanks");
|
||||
const text = REMINDER.split("\n\n").map(line => `~~${line.trim()}~~`).join("\n\n") + "\n\n" + THANKYOU + "\n" + marker;
|
||||
if (comment.body !== text) {
|
||||
await github.rest.issues.updateComment({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
comment_id: comment.id,
|
||||
body: text
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,8 @@
|
||||
name: "Pull Request Automation"
|
||||
on:
|
||||
pull_request_target:
|
||||
types: ["opened", "synchronize", "reopened", "edited", "labeled", "unlabeled"]
|
||||
#types: ["opened", "synchronize", "reopened", "edited", "labeled", "unlabeled"]
|
||||
types: ["opened"]
|
||||
|
||||
jobs:
|
||||
pr-automation:
|
||||
@@ -11,6 +12,34 @@ jobs:
|
||||
with:
|
||||
repo-token: "${{ secrets.GITHUB_TOKEN }}"
|
||||
|
||||
- uses: actions/github-script@v5
|
||||
with:
|
||||
github-token: ${{ secrets.GITHUB_TOKEN }}
|
||||
script: |
|
||||
// fetch a fresh set of labels, they might have changed earlier
|
||||
const issueLabels = await github.rest.issues.listLabelsOnIssue({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
issue_number: context.issue.number
|
||||
});
|
||||
let labels = issueLabels.data.map(label => label.name);
|
||||
let setLabels = false;
|
||||
|
||||
let target = context.payload.pull_request.base.ref;
|
||||
if (["maintenance", "devel", "staging/maintenance", "staging/devel", "master"].includes(target)) {
|
||||
labels.push(`targets ${target}`);
|
||||
setLabels = true;
|
||||
}
|
||||
|
||||
if (setLabels) {
|
||||
github.rest.issues.setLabels({
|
||||
issue_number: context.issue.number,
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
labels: labels
|
||||
})
|
||||
}
|
||||
|
||||
- uses: OctoPrint/actions/pr-validation@main
|
||||
with:
|
||||
repo-token: ${{ secrets.GITHUB_TOKEN }}
|
||||
@@ -14,7 +14,7 @@ jobs:
|
||||
strategy:
|
||||
matrix:
|
||||
os: ["ubuntu-latest"]
|
||||
python: ["3.7", "3.8", "3.9"]
|
||||
python: ["3.7", "3.8", "3.9", "3.10"]
|
||||
branch: ["master"]
|
||||
runs-on: ${{ matrix.os }}
|
||||
steps:
|
||||
@@ -49,7 +49,7 @@ jobs:
|
||||
strategy:
|
||||
matrix:
|
||||
os: ["ubuntu-latest"]
|
||||
python: ["3.7", "3.8", "3.9"]
|
||||
python: ["3.7", "3.8", "3.9", "3.10"]
|
||||
runs-on: ${{ matrix.os }}
|
||||
steps:
|
||||
- name: 👀 Determine latest release
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
# ripgrep ignore file
|
||||
|
||||
src/octoprint/static/vendor/
|
||||
src/octoprint/vendor/
|
||||
+10
-10
@@ -18,21 +18,21 @@ prerelease
|
||||
HEAD
|
||||
\(detached.*
|
||||
|
||||
# maintenance is currently the branch for preparation of maintenance release 1.7.0
|
||||
# maintenance is currently the branch for preparation of maintenance release 1.8.0
|
||||
# so are any fix/... and improve/... branches
|
||||
maintenance 1.7.0 07c4630d126617c2ae98a9c23ad49facf7bf0bbd pep440-dev
|
||||
fix/.* 1.7.0 07c4630d126617c2ae98a9c23ad49facf7bf0bbd pep440-dev
|
||||
improve/.* 1.7.0 07c4630d126617c2ae98a9c23ad49facf7bf0bbd pep440-dev
|
||||
maintenance 1.8.0 3fe45661cd79c5137d9d4f5f4adb4d9519bc2084 pep440-dev
|
||||
fix/.* 1.8.0 3fe45661cd79c5137d9d4f5f4adb4d9519bc2084 pep440-dev
|
||||
improve/.* 1.8.0 3fe45661cd79c5137d9d4f5f4adb4d9519bc2084 pep440-dev
|
||||
|
||||
# staging/bugfix is the branch for preparation of the 1.6.1 bugfix release
|
||||
# staging/bugfix is the branch for preparation of the 1.7.3 bugfix release
|
||||
# so are any bug/... branches
|
||||
staging/bugfix 1.6.1 29484fb2926960279e62881d6ee073c374a2a5fe pep440-dev
|
||||
bug/.* 1.6.1 29484fb2926960279e62881d6ee073c374a2a5fe pep440-dev
|
||||
staging/bugfix 1.7.2 d60c5a631aedf2328e4492125d9b86f595e43d00 pep440-dev
|
||||
bug/.* 1.7.2 d60c5a631aedf2328e4492125d9b86f595e43d00 pep440-dev
|
||||
|
||||
# staging/maintenance is currently the branch for preparation of 1.6.0rc4
|
||||
# staging/maintenance is currently the branch for preparation of 1.7.0rc4
|
||||
# so is regressionfix/...
|
||||
staging/maintenance 1.6.0rc4 7054a726bb3dc363a98ec6944b24e07879bb389b pep440-dev
|
||||
regressionfix/.* 1.6.0rc4 7054a726bb3dc363a98ec6944b24e07879bb389b pep440-dev
|
||||
staging/maintenance 1.7.0rc4 f31194f75365787f3eb5da61a24f2f8620111f4f pep440-dev
|
||||
regressionfix/.* 1.7.0rc4 f31194f75365787f3eb5da61a24f2f8620111f4f pep440-dev
|
||||
|
||||
# staging/devel is currently inactive (but has the 1.4.1rc4 namespace)
|
||||
staging/devel 1.4.1rc4 650d54d1885409fa1d411eb54b9e8c7ff428910f pep440-dev
|
||||
|
||||
+12
@@ -146,6 +146,18 @@ date of first contribution):
|
||||
* ["sparxooo"](https://github.com/sparxooo)
|
||||
* ["Stevil Knevil"](https://github.com/StevilKnevil)
|
||||
* [ldursw](https://github.com/ldursw)
|
||||
* [Ian Wilt](https://github.com/ianwiltdotcom)
|
||||
* [Ben Sycha](https://github.com/Sycha)
|
||||
* [John Boiles](https://github.com/johnboiles)
|
||||
* [Adam DeMuri](https://github.com/ademuri)
|
||||
* [Daniel Shenkle](https://github.com/DShenkle)
|
||||
* [Bryan Kenote](https://github.com/bryankenote)
|
||||
* [Quinn Damerell](https://github.com/QuinnDamerell)
|
||||
* [Sven Samoray](https://github.com/thelastWallE)
|
||||
* [Christian Würthner](https://github.com/crysxd)
|
||||
* [Maciej Urbański](https://github.com/rooterkyberian)
|
||||
* [Adam Wolf](https://github.com/adamwolf)
|
||||
* [Carey Metcalfe](https://github.com/pR0Ps)
|
||||
|
||||
OctoPrint started off as a fork of [Cura](https://github.com/daid/Cura) by
|
||||
[Daid Braam](https://github.com/daid). Parts of its communication layer and
|
||||
|
||||
+1
-1
@@ -97,7 +97,7 @@ following section *completely* and also follow the instructions in the
|
||||
**safe mode**, either by selecting "Restart OctoPrint in safe mode" from
|
||||
the "System" menu, or by starting OctoPrint from the command line with
|
||||
`octoprint serve --safe`. Then try to reproduce your issue. Find out
|
||||
more about safe mode in the [docs](http://docs.octoprint.org/en/master/features/safemode.html).
|
||||
more about safe mode in the [docs](https://docs.octoprint.org/en/master/features/safemode.html).
|
||||
|
||||
You might also want to try the current development version of OctoPrint
|
||||
(if you aren't already). Refer to the [FAQ](https://faq.octoprint.org)
|
||||
|
||||
@@ -17,7 +17,7 @@
|
||||
</p>
|
||||
|
||||
OctoPrint provides a snappy web interface for controlling consumer 3D printers. It is Free Software
|
||||
and released under the [GNU Affero General Public License V3](http://www.gnu.org/licenses/agpl.html).
|
||||
and released under the [GNU Affero General Public License V3](https://www.gnu.org/licenses/agpl-3.0.html).
|
||||
|
||||
Its website can be found at [octoprint.org](https://octoprint.org/?utm_source=github&utm_medium=readme).
|
||||
|
||||
@@ -27,7 +27,7 @@ An invite to the Discord server can be found at [discord.octoprint.org](https://
|
||||
|
||||
The FAQ can be accessed by following [faq.octoprint.org](https://faq.octoprint.org/?utm_source=github&utm_medium=readme).
|
||||
|
||||
The documentation is located at [docs.octoprint.org](http://docs.octoprint.org).
|
||||
The documentation is located at [docs.octoprint.org](https://docs.octoprint.org).
|
||||
|
||||
The official plugin repository can be reached at [plugins.octoprint.org](https://plugins.octoprint.org/?utm_source=github&utm_medium=readme).
|
||||
|
||||
@@ -38,14 +38,14 @@ If you enjoy OctoPrint, please consider becoming a regular supporter!**
|
||||
|
||||
You are currently looking at the source code repository of OctoPrint. If you already installed it
|
||||
(e.g. by using the Raspberry Pi targeted distribution [OctoPi](https://github.com/guysoft/OctoPi)) and only
|
||||
want to find out how to use it, [the documentation](http://docs.octoprint.org/) might be of more interest for you. You might also want to subscribe to join
|
||||
want to find out how to use it, [the documentation](https://docs.octoprint.org/) might be of more interest for you. You might also want to subscribe to join
|
||||
[the community forum at community.octoprint.org](https://community.octoprint.org) where there are other active users who might be
|
||||
able to help you with any questions you might have.
|
||||
|
||||
## Contributing
|
||||
|
||||
Contributions of all kinds are welcome, not only in the form of code but also with regards to the
|
||||
[official documentation](http://docs.octoprint.org/), debugging help
|
||||
[official documentation](https://docs.octoprint.org/), debugging help
|
||||
in the [bug tracker](https://github.com/OctoPrint/OctoPrint/issues), support of other users on
|
||||
[the community forum at community.octoprint.org](https://community.octoprint.org) or
|
||||
[the official discord at discord.octoprint.org](https://discord.octoprint.org)
|
||||
@@ -140,7 +140,7 @@ which is located at `~/.octoprint` on Linux, at `%APPDATA%/OctoPrint` on Windows
|
||||
at `~/Library/Application Support/OctoPrint` on MacOS.
|
||||
|
||||
A comprehensive overview of all available configuration settings can be found
|
||||
[in the docs](http://docs.octoprint.org/en/master/configuration/config_yaml.html).
|
||||
[in the docs](https://docs.octoprint.org/en/master/configuration/config_yaml.html).
|
||||
Please note that the most commonly used configuration settings can also easily
|
||||
be edited from OctoPrint's settings dialog.
|
||||
|
||||
|
||||
+12
-11
@@ -9,6 +9,7 @@ thanks to everyone who contributed!
|
||||
* 3D-TECH
|
||||
* 3DPrinterOS
|
||||
* Arnljot Arntsen
|
||||
* Artillery 3D
|
||||
* Ash King
|
||||
* BigTreeTech
|
||||
* Boris Hussein
|
||||
@@ -18,56 +19,56 @@ thanks to everyone who contributed!
|
||||
* Chris Lynch
|
||||
* Christian Petropolis
|
||||
* Christian Wolf
|
||||
* Christian Würthner
|
||||
* Christoph Sigrist
|
||||
* Creality3D
|
||||
* D Brian Kimmel
|
||||
* Dana Voigt
|
||||
* David Bounds
|
||||
* DeltaMaker 3D Printers
|
||||
* Dennis Breining
|
||||
* Dennis Christilaw
|
||||
* Douglas Floyd
|
||||
* Dr. Frank Wester
|
||||
* Eric Betts
|
||||
* Ernesto Martinez
|
||||
* Franziska Kunsmann
|
||||
* George Robles
|
||||
* Greg Holloway
|
||||
* Hog Duske
|
||||
* Hopewell Medical Acupuncture Center
|
||||
* Itay Shem-tov
|
||||
* Jeff Moe
|
||||
* Jeremy Cole
|
||||
* Joshua Wills
|
||||
* Julian Melo
|
||||
* Justin Kaufman
|
||||
* Kaile Riser
|
||||
* Kale Stedman
|
||||
* Kazuhiro Ogura
|
||||
* Kelly C McNiece
|
||||
* Kenneth Jiang
|
||||
* Kurt Wubbels
|
||||
* Kyle Menigoz
|
||||
* LA 3D Printer Repair
|
||||
* Lachlan Bell
|
||||
* Lee Dohm
|
||||
* Lefteris Lertas
|
||||
* LulzBot
|
||||
* Makespace Madrid
|
||||
* Mark Walker
|
||||
* Michael Aumock
|
||||
* Mike Kershaw
|
||||
* Miles Flavel
|
||||
* Mosaic Manufacturing
|
||||
* Nat Friedman
|
||||
* Neil R. Goldberg
|
||||
* Norman Jaffe
|
||||
* Ory Weaver
|
||||
* Patrick Glyré
|
||||
* Peopoly
|
||||
* Pete Barnwell
|
||||
* Prof Yuh Wen Chen
|
||||
* Raise3D
|
||||
* Randy C. Will
|
||||
* Ranjib Dey
|
||||
* Richard McGuire
|
||||
* Richard Michaud
|
||||
* Richard Stocks
|
||||
* Rigid3D
|
||||
* Robert Gusek
|
||||
* Ronald Griehsler
|
||||
* Sacha Telgenhof
|
||||
* Sebastien Andrivet
|
||||
* Stefan Krister
|
||||
* Steve Thompson
|
||||
@@ -77,4 +78,4 @@ thanks to everyone who contributed!
|
||||
* Ulderico Cirello
|
||||
* Ulrich Kempken
|
||||
|
||||
and 2350 more wonderful people pledging on the [Patreon campaign](https://patreon.com/foosel) or via [GitHub Sponsors](https://github.com/users/foosel/sponsorship)!
|
||||
and 2247 more wonderful people pledging on the [Patreon campaign](https://patreon.com/foosel) or via [GitHub Sponsors](https://github.com/users/foosel/sponsorship)!
|
||||
@@ -76,6 +76,7 @@
|
||||
* [watchdog](http://github.com/gorakhargosh/watchdog): Apache License 2.0
|
||||
* [websocket-client](https://github.com/liris/websocket-client): LGPLv3
|
||||
* [wrapt](http://wrapt.readthedocs.org/): BSD
|
||||
* [zipstream-ng](https://github.com/pR0Ps/zipstream-ng): LGPLv3
|
||||
|
||||
## Development (testing, documentation generation, etc)
|
||||
|
||||
|
||||
@@ -365,6 +365,14 @@ Files
|
||||
- 0..1
|
||||
- :ref:`GCODE analysis information <sec-api-datamodel-files-gcodeanalysis>`
|
||||
- Information from the analysis of the GCODE file, if available. Left out in abridged version.
|
||||
* - ``prints``
|
||||
- 0..1
|
||||
- :ref:`Print history information <sec-api-datamodel-files-prints>`
|
||||
- Information about previous prints of the file. Left out if the file has never been printed.
|
||||
* - ``statistics``
|
||||
- 0..1
|
||||
- :ref:`Print statistics information <sec-api-datamodel-files-stats>`
|
||||
- Statistics about the file, based on the previous print times. Left out if the file has never been printed.
|
||||
|
||||
.. _sec-api-datamodel-files-fileabridged:
|
||||
|
||||
@@ -506,6 +514,62 @@ References
|
||||
- The model from which this file was generated (e.g. an STL, currently not used). Never present for
|
||||
folders.
|
||||
|
||||
.. _sec-api-datamodel-files-prints:
|
||||
|
||||
Print History
|
||||
-------------
|
||||
|
||||
.. list-table::
|
||||
:widths: 15 5 10 30
|
||||
:header-rows: 1
|
||||
|
||||
* - Name
|
||||
- Multiplicity
|
||||
- Type
|
||||
- Description
|
||||
* - ``success``
|
||||
- 1
|
||||
- Number
|
||||
- Number of successful prints
|
||||
* - ``failure``
|
||||
- 1
|
||||
- Number
|
||||
- Number of failed prints
|
||||
* - ``last.date``
|
||||
- 1
|
||||
- Unix Timestamp
|
||||
- Last date this file was printed
|
||||
* - ``last.printTime``
|
||||
- 1
|
||||
- Float
|
||||
- Last print time in seconds
|
||||
* - ``last.success``
|
||||
- 1
|
||||
- Boolean
|
||||
- Whether the last print was a success or not
|
||||
|
||||
.. _sec-api-datamodel-files-stats:
|
||||
|
||||
Print Statistics
|
||||
----------------
|
||||
|
||||
.. list-table::
|
||||
:widths: 15 5 10 30
|
||||
:header-rows: 1
|
||||
|
||||
* - Name
|
||||
- Multiplicity
|
||||
- Type
|
||||
- Description
|
||||
* - ``averagePrintTime``
|
||||
- 1
|
||||
- Object
|
||||
- Object that maps printer profile names to the last print time of the file, in seconds
|
||||
* - ``lastPrintTime``
|
||||
- 1
|
||||
- Object
|
||||
- Object that maps printer profile names to the average print time of the file, in seconds
|
||||
|
||||
.. _sec-api-datamodel-access:
|
||||
|
||||
Access control
|
||||
|
||||
+64
-1
@@ -50,7 +50,70 @@ Clients must ignore any unknown messages.
|
||||
|
||||
The data model of the attached payloads is described further below.
|
||||
|
||||
OctoPrint's SockJS socket also accepts two commands from the client to the server.
|
||||
OctoPrint's SockJS socket also accepts three commands from the client to the server.
|
||||
|
||||
* ``subscribe`` (since 1.8.0): With the ``subscribe`` message, clients may selectively
|
||||
subscribe to certain message types. The payload should be a dict of message types with
|
||||
supported keys as follows:
|
||||
|
||||
* ``state``: Either a boolean value indicating whether to generally receive state updates (``current`` and ``history``)
|
||||
or not, or a dict with further options for received state updates. Currently the following options are recognized here:
|
||||
|
||||
* ``logs``: A boolean value whether to include all log lines (``True``, default) or not (``False``). Alternatively a string with
|
||||
a regex pattern can be provided, in which case only log lines matching the pattern will be returned.
|
||||
* ``messages``: Like ``logs`` but for the returned message lines.
|
||||
|
||||
* ``plugins``: Either a boolean value indicating whether to generally receive plugin messages, or a list of plugin
|
||||
identifiers to receive plugin messages for.
|
||||
* ``events``: Either a boolean value indicating whether to generally receive event messages, or a list of event
|
||||
types to receive event messages for.
|
||||
|
||||
If you send a ``subscribe`` message, OctoPrint will default the connection to not subscribe you to anything you did't explicitly
|
||||
request. ``subscribe`` messages do replace previous ones.
|
||||
|
||||
Example for a ``subscribe`` message subscribing only to updates from plugin ``example`` but neither state nor events:
|
||||
|
||||
.. sourcecode:: javascript
|
||||
|
||||
{
|
||||
"subscribe": {
|
||||
"plugins": ["example"]
|
||||
}
|
||||
}
|
||||
|
||||
Example for a ``subscribe`` message subscribing to state, event and plugin updates,
|
||||
but filtering logs in state updates to only contain lines matching ``^Recv: Cap`` and also
|
||||
filtering out all messages:
|
||||
|
||||
.. sourcecode:: javascript
|
||||
|
||||
{
|
||||
"subscribe": {
|
||||
"state": {
|
||||
"logs": "^Recv: Cap",
|
||||
"messages": false
|
||||
},
|
||||
"events": true,
|
||||
"plugins": true
|
||||
}
|
||||
}
|
||||
|
||||
Example for a ``subscribe`` message subscribing only to events of type ``PrintFailed``:
|
||||
|
||||
.. sourcecode:: javascript
|
||||
|
||||
{
|
||||
"subscribe": {
|
||||
"events": ["PrintFailed"]
|
||||
}
|
||||
}
|
||||
|
||||
.. note::
|
||||
|
||||
Per default, OctoPrint will subscribe connecting clients to all state, event and plugin updates
|
||||
without any filtering in place. If you wish to have your more selective subscription active
|
||||
right from the start of your socket session, be sure to send the ``subscribe`` message
|
||||
**before** the ``auth`` message.
|
||||
|
||||
* ``auth`` (since 1.3.10): With the ``auth`` message, clients may associate an
|
||||
existing user session with the socket. That is of special importance to receive
|
||||
|
||||
@@ -226,6 +226,10 @@ For timelapse type ``zchange``.
|
||||
- 1
|
||||
- float
|
||||
- Size of retraction Z hop to detect and ignore for z-based snapshots
|
||||
* - ``minDelay``
|
||||
- 1
|
||||
- int
|
||||
- Snapshots will be rate limited against this interval, to prevent performance issues with vase mode/continuous z prints
|
||||
|
||||
.. _sec-api-timelapse-datamodel-config-timed:
|
||||
|
||||
|
||||
@@ -134,7 +134,7 @@ Open the Git Bash you just installed and in that:
|
||||
cd /c/Devel
|
||||
git clone https://github.com/OctoPrint/OctoPrint.git
|
||||
cd OctoPrint
|
||||
virtualenv --python=C:\Python38\python.exe venv
|
||||
virtualenv --python=C:/Python3/python.exe venv3
|
||||
source ./venv/Scripts/activate
|
||||
python -m pip install --upgrade pip
|
||||
python -m pip install -e '.[develop,plugins,docs]'
|
||||
@@ -199,6 +199,10 @@ You'll need a user account with administrator privileges.
|
||||
* ``ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"``
|
||||
* ``brew install python``
|
||||
|
||||
* Install `pip <https://pip.pypa.io/en/stable/installation/#supported-methods>`_
|
||||
|
||||
* ``python -m ensurepip --upgrade``
|
||||
|
||||
* Install `virtualenv <https://virtualenv.pypa.io/>`_
|
||||
|
||||
* ``pip install virtualenv``
|
||||
@@ -315,3 +319,102 @@ Otherwise go through Settings.
|
||||
Make sure you are running a PyCharm version of 2016.1 or later, or manually fix
|
||||
`a debugger bug contained in earlier versions <https://youtrack.jetbrains.com/issue/PY-18365>`_ or plugin management
|
||||
will not work in your developer install when running OctoPrint from PyCharm in debug mode.
|
||||
|
||||
Visual Studio Code (vscode)
|
||||
---------------------------
|
||||
|
||||
- Install Visual Studio Code from `code.visualstudio.com <https://code.visualstudio.com/Download>`_
|
||||
- Open folder select OctoPrint checkout folder (e.g. ``~/devel/OctoPrint`` or ``C:\Devel\OctoPrint``)
|
||||
|
||||
- Create a directory ``.vscode`` if not already present in the root of the project
|
||||
|
||||
- Create the following files inside the ``.vscode`` directory
|
||||
|
||||
settings.json
|
||||
.. code-block:: json
|
||||
|
||||
{
|
||||
"python.defaultInterpreterPath": "venv3/bin/python",
|
||||
"python.formatting.provider": "black",
|
||||
"python.formatting.blackArgs": [
|
||||
"--config",
|
||||
"black.toml"
|
||||
],
|
||||
"editor.formatOnSave": true,
|
||||
"python.sortImports.args": [
|
||||
"--profile=black",
|
||||
],
|
||||
"[python]": {
|
||||
"editor.codeActionsOnSave": {
|
||||
"source.organizeImports": true
|
||||
}
|
||||
},
|
||||
"python.linting.pylintEnabled": false,
|
||||
"python.linting.flake8Enabled": true,
|
||||
"python.linting.enabled": true
|
||||
}
|
||||
|
||||
tasks.json
|
||||
.. code-block:: json
|
||||
|
||||
{
|
||||
"version": "2.0.0",
|
||||
"tasks": [
|
||||
{
|
||||
"label": "clean build artifacts",
|
||||
"type": "shell",
|
||||
"command": "python ./setup.py clean"
|
||||
},
|
||||
{
|
||||
"label": "build docs",
|
||||
"type": "shell",
|
||||
"command": "sphinx-build -b html ./docs ./docs/_build"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
|
||||
launch.json
|
||||
.. code-block:: json
|
||||
|
||||
{
|
||||
"version": "0.2.0",
|
||||
"configurations": [
|
||||
{
|
||||
"name": "OctoPrint",
|
||||
"type": "python",
|
||||
"request": "launch",
|
||||
"module": "octoprint",
|
||||
"args": [
|
||||
"serve",
|
||||
"--debug"
|
||||
],
|
||||
"cwd": "${workspaceFolder}/src",
|
||||
"preLaunchTask": "clean build artifacts"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
In the terminal install the python extension by running this command:
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
code --install-extension ms-python.python
|
||||
|
||||
In vscode terminal, or with venv active install code formatter black and linter flake8 by running:
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
python -m pip install -U black flake8 flake8-bugbear
|
||||
|
||||
Summary of vscode config:
|
||||
|
||||
* Pressing ``F5`` will now start OctoPrint in debug mode
|
||||
|
||||
* Your terminal inside vscode uses the virtual python environment
|
||||
|
||||
* Saving a file will run an auto formatter and import sort
|
||||
|
||||
* ``Ctrl+Shift+B`` can be used to run the ``build docs`` task to rebuild the documentation
|
||||
|
||||
|
||||
@@ -607,6 +607,11 @@ Eject
|
||||
EStop
|
||||
An ``M112`` was sent to the printer through OctoPrint (not triggered when printing from SD!)
|
||||
|
||||
FilamentChange
|
||||
An ``M600``, ``M701`` or ``M702`` was sent to the printer through OctoPrint (not triggered when printing from SD!)
|
||||
|
||||
.. versionadded:: 1.7.0
|
||||
|
||||
PositionUpdate
|
||||
The response to an ``M114`` was received by OctoPrint. The payload contains the current position information
|
||||
parsed from the response and (in the case of the selected tool ``t`` and the current feedrate ``f``) tracked
|
||||
|
||||
@@ -184,6 +184,7 @@ further down there's also a dedicated list of steps for OctoPi specifically.
|
||||
autologinAs: "<yourUsername>"
|
||||
localNetworks:
|
||||
- "127.0.0.0/8"
|
||||
- "::1/128"
|
||||
- "<yourAddressRange>"
|
||||
|
||||
4. Restart OctoPrint, check that everything works.
|
||||
|
||||
@@ -38,6 +38,8 @@ The following GCODE scripts are sent by OctoPrint automatically:
|
||||
* ``afterPrintDone``: Sent just after a print job finished. Defaults to an empty script.
|
||||
* ``afterPrintPaused``: Sent just after a print job was paused. Defaults to an empty script.
|
||||
* ``beforePrintResumed``: Sent just before a print job is resumed. Defaults to an empty script.
|
||||
* ``beforeToolChange``: Sent just before a tool change command (``Tn``) is issued.
|
||||
* ``afterToolChange``: Sent just after a tool change command (``Tn``) is issued
|
||||
|
||||
.. note::
|
||||
|
||||
@@ -70,7 +72,8 @@ Context
|
||||
All GCODE scripts have access to the following template variables through the template context:
|
||||
|
||||
* ``printer_profile``: The currently selected :ref:`Printer Profile <sec-modules-printer-profile>`, including
|
||||
information such as the extruder count, the build volume size, the filament diameter etc.
|
||||
information such as the extruder count, the build volume size, the filament diameter etc. The individual properties
|
||||
follow the common data model for :ref:`printer profiles <sec-api-printerprofiles-datamodel-profile>`.
|
||||
* ``last_position``: Last position reported by the printer via `M114` (might be unset if no `M114` was sent so far!).
|
||||
Consists of ``x``, ``y``, ``z`` and ``e`` coordinates as received by the printer and tracked values for ``f`` and
|
||||
current tool ``t`` taken from commands sent through OctoPrint. All of these coordinates might be ``None`` if no
|
||||
@@ -107,6 +110,11 @@ There are a few additional template variables available for the following specif
|
||||
* ``cancel_temperature``: Last known temperature values when the print was cancelled. See ``last_temperature`` above
|
||||
for the structure to expect here.
|
||||
|
||||
* ``beforeToolChange`` and ``afterToolChange``
|
||||
|
||||
* ``tool.old``: The number of the previous tool
|
||||
* ``tool.new``: The number of the new tool
|
||||
|
||||
|
||||
.. warning::
|
||||
|
||||
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 36 KiB |
@@ -0,0 +1,4 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!-- Do not edit this file with editors other than diagrams.net -->
|
||||
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" style="background-color: rgb(255, 255, 255);" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" width="800px" height="436px" viewBox="-0.5 -0.5 800 436" content="<mxfile host="app.diagrams.net" modified="2021-11-30T12:48:38.412Z" agent="5.0 (Windows)" version="15.8.7" etag="dRCYf0ldIAGVQo3_ZfcA" type="google"><diagram id="KSxbcLmsFqmVZw95xxym" name="Page-1">7VxZb+M2EP41ebSh2/Zjkj1aYAsskId2nxa0RdtsJFGl6Fy/vqREHbxsyZYdp1sDgaUhRXGObzhDjnPj36cvXwnIt3/gGCY3nhO/3Pifbjz2Cebsi1NeK8p85lWEDUFxRXJbwgN6g4LoCOoOxbCQOlKME4pymbjCWQZXVKIBQvCz3G2NE/FWMX4ONlDqwQkPK5Do1D9RTLeCCy9q6b9BtNnWb3ajRdWSgrqzeFOxBTF+7pD8zzf+PcGYVlfpyz1MuPCQNMMvltZmYgRmtM8D3tzxYhA7UewvHehMfKGIgr7WzMKY8S5uMaFbvMEZSD631DuCd1kM+YgOu9vSNGGXLruEL4j+xcnTWShuf9RNGSWvVVtY3/4QI+hMCL4KvCMrMS1hQhSQDaQWZoSQOQedcYQkvkKcQvZW1oHABFD0JGsXCCPZNP3Eo7eEgNdOhxyjjBadkb9zAusg7H3iR2E1pDB3f6YoRXtgsfcBdlHNob7rMNOSSk2btS7s9AkkO8GzrvUkYWiCsj6Ztea8vWBSpw8UUN6+RklyjxNMygd9p/zwzpTgR2hqser3CRIKX/aqqhZRUPsCIaJASOy5xWOt/m0HijXNpNyOePdKb9ZDegcx05Eq5xox53KboE3GaEtMKU5LUMS33FvxQXKYVRThDed7JXwyuiIdXfOzgOmw8bt+KI9RTUo81qrNDktJscOQ0lhmq+wEg1hTODNbKmuVwAK9gWXZoRS7fweEgldM8pAYNJ+iOC6tIwFLmNyB1eOm9K0dFa/Lz0B41RarwqtZIcU8pUXICDtn6srKqe5O1bk86MSXB8DrdQHpiZqca4qMUcH51pXZrmdckc9bROFDDkpoPLOARtbzko83hkMLFbN3dY/megaXFo3g0haacGB2xbLxZheUjetqQhghJKqvf8hOumlqPHbZdsRaeiBWWpzFmw8PjTx5GXfFOm4PjZQHfCdUlHlaaOT6Fih8MJfv2lB2lM93XcXtj+T3ozM4evc8KYwdr84QvG4xQW84o8AW/TUG0QvZCx3Z54nTBiM7mO0F6uEHFFdwOrIDWwTw0aDtjQVtZ+oEQSBJfRKOg2wlPTsP0vWY7saLEq66nEBJpdE/O76lcsc1OxGau+VslrFC08yuNuK7HKbIQWYcJ0EZnNSRBh/InXr2Yda4lM0arORRvu1WKAas5R5nBeaG2I5geCkfZlKU+V/5Sid/0d+ZJ7sNyn6mIAMbSKbVbVHPhIm0mow8QUauWNXIpSBrqgKTejtgtSPJ6x1hBs59kDEolMNGu7VroKrY5TtIfrmH1MFkCavvuEAUYf5MAte0A8NvSnMDRytOCaZAdNZc9Vj7FrOF4uUMYb4pkm2Ip4Synu4Ca1XH6KmnoYcsHFiwz3wehuHC5TZYCcdRwVUqZFRQdE182njvQ6Zd8iZT343dVWP0bcfS/NkyoD0bQwI3qOBIYNaA8WMPHP83mEVpnsCU4awC5Ifi+niLlrme4uyn8ObtVsUgQVj8dYbLjdsDyXvlpOvzDbfjnIWj5TMQu5Eul5eyEXxcbDPcoUaKQ50bHGpo8KjzMRyqaSf9w5pfneh+JLANcjG/kDf96L7UMAlrMF7GxWuQouS1Gpo1gTSvBOQHfJ41BFYNBOQOzSx7cTTUfTebqXuj7ePxW4+wJAZ19tfytejeyMa7zux3hrAvbKHgmy8cQk55vSYghc+YPHJ/UrXyg1GuaGeXl+Ptm/4ywatH/iJzqpoCwmynmpXT+QuczvSXmMQ8T+KdMpzBpiEHcYyyjXjcZLTvjO1ebwymVaywCP1oFvj72BiUqkfjOluU/c3LTDwnhjlkeW62QpCbA8ooPsIBW1LxK0bsWTQ6djiNMkQRY+ntuBDHSu3ieGyPbpmhYSLvuHr8CmlGky7UaUbo62lGYEgz3GA2Qp6hVDYZDmwPQXEYoEf2phfc+ZxW9Rlj+NiT7PoqrdhXzljq3Ll7jm4qmwrGyJUt1XlHV6HxYqija9AU9YwhXK0kzdele66aNE24vi7LMeo4vdHrOA0nmNdaxxl4V1bHqQoq0CG1y66+Xq3rGj2j2dise4wTUD+aL2Ql3Zx0ADrqCafG+PADnF9m3a8t/ZpXfu9qVv7AMZTQXWzp71OA3hY/lxsbzMJBsW2OkDvyVgW8rzDHKkpp/Yl6rjcd2ZlOGGrayRXRSs2bppNqPdUqovWRQiWLUUMPS2n1GJ6rT9X8O6rckmBdjQkoZQPq4VV/C9D8wMUswFStM54FWOtqrfrvRqF1ZcS16DtScgnXOVbhalndJTVu2qW4Xsz7V2YDKuYDtQSoP+gjFfQXs4HAM9jAsIj12Bo9Y/AotrfPe2QYTec8dHPdIAichdejTE+cEP7Uy/VOCFd71OV1E8CeJXoqDutwt1LTGcryrGAeEP6Gij81/YLE+AOS0A7bY6PfQP+JwYWSuHe3eiU9HKfEtS6OMoBn/BTwf0xZMdW3lPUITLHb9jfx1arU/mcB//O/</diagram></mxfile>"><defs><linearGradient x1="0%" y1="0%" x2="0%" y2="100%" id="mx-gradient-dae8fc-1-7ea6e0-1-s-0"><stop offset="0%" style="stop-color: rgb(218, 232, 252); stop-opacity: 1;"/><stop offset="100%" style="stop-color: rgb(126, 166, 224); stop-opacity: 1;"/></linearGradient><linearGradient x1="0%" y1="0%" x2="0%" y2="100%" id="mx-gradient-ffffff-0.9-ffffff-0.1-s-0"><stop offset="0%" style="stop-color: rgb(255, 255, 255); stop-opacity: 0.9;"/><stop offset="100%" style="stop-color: rgb(255, 255, 255); stop-opacity: 0.1;"/></linearGradient></defs><g><path d="M 464 140 L 464 335 L 434 335 L 434 388.63" fill="none" stroke="rgb(0, 0, 0)" stroke-miterlimit="10" pointer-events="stroke"/><path d="M 434 393.88 L 430.5 386.88 L 434 388.63 L 437.5 386.88 Z" fill="rgb(0, 0, 0)" stroke="rgb(0, 0, 0)" stroke-miterlimit="10" pointer-events="all"/><ellipse cx="434" cy="25" rx="11" ry="11" fill="#000000" stroke="#000000" pointer-events="all"/><path d="M 434 40 L 434 77.76" fill="none" stroke="#000000" stroke-miterlimit="10" pointer-events="stroke"/><path d="M 429.5 69.88 L 434 78.88 L 438.5 69.88" fill="none" stroke="#000000" stroke-miterlimit="10" pointer-events="all"/><g transform="translate(-0.5 -0.5)"><switch><foreignObject style="overflow: visible; text-align: left;" pointer-events="none" width="100%" height="100%" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: flex; align-items: unsafe center; justify-content: unsafe center; width: 1px; height: 1px; padding-top: 56px; margin-left: 435px;"><div style="box-sizing: border-box; font-size: 0px; text-align: center;" data-drawio-colors="color: rgb(0, 0, 0); background-color: #ffffff; "><div style="display: inline-block; font-size: 12px; font-family: Helvetica; color: rgb(0, 0, 0); line-height: 1.2; pointer-events: all; background-color: rgb(255, 255, 255); white-space: nowrap;">load</div></div></div></foreignObject><text x="435" y="59" fill=Line truncated
|
||||
|
After Width: | Height: | Size: 23 KiB |
+1
-1
@@ -7,7 +7,7 @@ Welcome to OctoPrint's documentation!
|
||||
:align: right
|
||||
|
||||
OctoPrint provides a snappy web interface for controlling consumer 3D printers. It is Free Software
|
||||
and released under the `GNU Affero General Public License V3 <http://www.gnu.org/licenses/agpl.html>`_.
|
||||
and released under the `GNU Affero General Public License V3 <https://www.gnu.org/licenses/agpl-3.0.html>`_.
|
||||
|
||||
Its website can be found at `octoprint.org <https://octoprint.org/>`_.
|
||||
|
||||
|
||||
@@ -35,10 +35,23 @@ any :ref:`settings overlays <sec-plugins-controlproperties-plugin_settings_overl
|
||||
|
||||
On disabling a plugin, its hook handlers, helpers, mixin implementations and settings overlays will be de-registered again.
|
||||
|
||||
When a plugin gets enabled, OctoPrint will also call the :func:`on_plugin_enabled` callback on its implementation
|
||||
(if it exists). Likewise, when a plugin gets disabled OctoPrint will call the :func:`on_plugin_disabled` callback on
|
||||
its implementation (again, if it exists).
|
||||
|
||||
Some plugin types require a reload of the frontend or a restart of OctoPrint for enabling/disabling them. You
|
||||
can recognize such plugins by their implementations implementing :class:`~octoprint.plugin.ReloadNeedingPlugin` or
|
||||
:class:`~octoprint.plugin.RestartNeedingPlugin` or providing handlers for one of the hooks marked correspondingly.
|
||||
For these plugins, disabling them will *not* trigger the respective callback at runtime as they will not actually
|
||||
be disabled right away but only marked as such so that they won't even load during the required restart.
|
||||
|
||||
.. image:: ../images/plugins_lifecycle.png
|
||||
Note that uninstalling a plugin through the bundled Plugin Manager will make a plugin first get disabled and
|
||||
then unloaded, but only if it doesn't require a restart. Plugins wishing to react to an uninstall through the
|
||||
Plugin Manager may implement :func:`~octoprint.plugin.types.OctoPrintPlugin.on_plugin_pending_uninstall` (added in OctoPrint 1.8.0) which will always be called by the Plugin Manager,
|
||||
regardless of whether the plugin requires a restart of OctoPrint to be fully uninstalled or not. Please be aware
|
||||
that the Plugin Manager is not the only way to uninstall a plugin from the system, a user may also uninstall it
|
||||
manually through the command line, circumventing Plugin Manager completely.
|
||||
|
||||
.. image:: ../images/plugins_lifecycle.svg
|
||||
:align: center
|
||||
:alt: The lifecycle of OctoPrint plugins.
|
||||
@@ -23,24 +23,22 @@ SETUP_REQUIRES = [
|
||||
INSTALL_REQUIRES = [
|
||||
# additional OctoPrint plugins that are maintained on a different release cycle
|
||||
"OctoPrint-FileCheck>=2021.2.23",
|
||||
"OctoPrint-FirmwareCheck>=2021.2.4",
|
||||
"OctoPrint-PiSupport>=2021.3.26",
|
||||
"OctoPrint-FirmwareCheck>=2021.10.11",
|
||||
"OctoPrint-PiSupport>=2021.10.28",
|
||||
# the following dependencies are non trivial to update since later versions
|
||||
# introduce backwards incompatible changes that might affect plugins, or due to
|
||||
# other observed problems
|
||||
"regex!=2018.11.6", # avoid broken 2018.11.6. See #2874
|
||||
"wrapt>=1.12.1,<1.13", # newer versions fail to build on OctoPi 0.15
|
||||
# anything below this should be checked on releases for new versions
|
||||
"tornado>=6.0.4,<7",
|
||||
"markdown>=3.2.2,<4",
|
||||
"flask>=1.1.2,<2",
|
||||
"Jinja2>=2.11.2,<3",
|
||||
"flask>=2,<3",
|
||||
"Flask-Login>=0.5,<0.6", # flask-login doesn't use semver & breaks stuff on minor version increases
|
||||
"Flask-Babel>=1.0,<2",
|
||||
"Flask-Babel>=2.0,<3",
|
||||
"Flask-Assets>=2.0,<3",
|
||||
"werkzeug>=1.0.1,<2",
|
||||
"itsdangerous>=1.1.0,<2",
|
||||
"cachelib>=0.1,<1",
|
||||
"PyYAML>=5.3.1,<6",
|
||||
"cachelib>=0.2,<0.3",
|
||||
"PyYAML>=5.4.1,<6",
|
||||
"pyserial>=3.4,<4",
|
||||
"netaddr>=0.7.19,<1",
|
||||
"watchdog==1.0.0",
|
||||
@@ -51,30 +49,30 @@ INSTALL_REQUIRES = [
|
||||
"pkginfo>=1.5.0.1,<2",
|
||||
"requests>=2.23.0,<3",
|
||||
"semantic_version>=2.8.5,<3",
|
||||
"psutil>=5.7,<6",
|
||||
"Click>=7.1.2,<8",
|
||||
"feedparser>=6.0.2,<7",
|
||||
"psutil>=5.8,<6",
|
||||
"Click>=8.0.3,<9",
|
||||
"feedparser>=6.0.8,<7",
|
||||
"future>=0.18.2,<1", # not really needed anymore, but leaving in for py2/3 compat plugins
|
||||
"websocket-client>=0.57,<1",
|
||||
"websocket-client>=1.2.1,<2",
|
||||
"wrapt>=1.12.1,<2",
|
||||
"emoji>=0.5.4,<1",
|
||||
"immutabledict>=1.2.0,<2",
|
||||
"sentry-sdk>=0.15.1,<1",
|
||||
"emoji>=1.4.2,<2",
|
||||
"sentry-sdk>=1.5.0,<2",
|
||||
"filetype>=1.0.7,<2",
|
||||
"zeroconf>=0.24,<0.25",
|
||||
"zipstream-new>=1.1.8,<1.2",
|
||||
"zeroconf>=0.33,<0.34", # breaking changes can happen on minor version increases
|
||||
"zipstream-ng>=1.3.1,<2.0.0",
|
||||
"pathvalidate>=2.4.1,<3",
|
||||
"colorlog>=5.0.1,<6",
|
||||
# vendor bundled dependencies
|
||||
"unidecode>=0.04.14,<0.05", # dependency of awesome-slugify
|
||||
"blinker>=1.4,<2", # dependency of flask_principal
|
||||
"unidecode", # dependency of awesome-slugify, leave w/o range to not cause dependency hell w/ Octolapse deps
|
||||
]
|
||||
|
||||
# Additional requirements for optional install options
|
||||
EXTRA_REQUIRES = {
|
||||
"develop": [
|
||||
# Testing dependencies
|
||||
"pytest>=5.4.3,<6",
|
||||
"mock>=4,<5",
|
||||
"pytest>=6.2.5,<7",
|
||||
"pytest-doctest-custom>=1.0.0,<2",
|
||||
"ddt",
|
||||
# pre-commit
|
||||
@@ -230,6 +228,8 @@ def params():
|
||||
"Programming Language :: Python :: 3.6",
|
||||
"Programming Language :: Python :: 3.7",
|
||||
"Programming Language :: Python :: 3.8",
|
||||
"Programming Language :: Python :: 3.9",
|
||||
"Programming Language :: Python :: 3.10",
|
||||
"Programming Language :: Python :: Implementation :: CPython",
|
||||
"Programming Language :: JavaScript",
|
||||
"Topic :: Printing",
|
||||
|
||||
+12
-13
@@ -266,16 +266,16 @@ def init_logging(
|
||||
"formatters": {
|
||||
"simple": {"format": simple_format},
|
||||
"colored": {
|
||||
"class": "colorlog.ColoredFormatter",
|
||||
"format": "%(log_color)s" + simple_format,
|
||||
"()": "colorlog.ColoredFormatter",
|
||||
"format": "%(log_color)s" + simple_format + "%(reset)s",
|
||||
"reset": True,
|
||||
"log_colors": {
|
||||
"DEBUG": "light_white",
|
||||
"DEBUG": "cyan",
|
||||
"INFO": "white",
|
||||
"WARNING": "yellow",
|
||||
"ERROR": "red",
|
||||
"CRITICAL": "bold_red",
|
||||
},
|
||||
"reset": True,
|
||||
},
|
||||
"serial": {"format": "%(asctime)s - %(message)s"},
|
||||
"timings": {"format": "%(asctime)s - %(message)s"},
|
||||
@@ -381,10 +381,9 @@ def init_logging(
|
||||
|
||||
config_from_file = {}
|
||||
if os.path.exists(logging_file) and os.path.isfile(logging_file):
|
||||
import yaml
|
||||
from octoprint.util import yaml
|
||||
|
||||
with open(logging_file, encoding="utf-8") as f:
|
||||
config_from_file = yaml.safe_load(f)
|
||||
config_from_file = yaml.load_from_file(path=logging_file)
|
||||
|
||||
# we merge that with the default config
|
||||
if config_from_file is not None and isinstance(config_from_file, dict):
|
||||
@@ -730,9 +729,7 @@ def get_plugin_blacklist(settings, connectivity_checker=None):
|
||||
import time
|
||||
|
||||
import requests
|
||||
import yaml
|
||||
|
||||
from octoprint.util import bom_aware_open
|
||||
from octoprint.util.version import is_octoprint_compatible, is_python_compatible
|
||||
|
||||
logger = log.getLogger(__name__ + ".startup")
|
||||
@@ -798,8 +795,9 @@ def get_plugin_blacklist(settings, connectivity_checker=None):
|
||||
if os.stat(path).st_mtime + ttl < time.time():
|
||||
return None
|
||||
|
||||
with bom_aware_open(path, encoding="utf-8", mode="rt") as f:
|
||||
result = yaml.safe_load(f)
|
||||
from octoprint.util import yaml
|
||||
|
||||
result = yaml.load_from_file(path=path)
|
||||
|
||||
if isinstance(result, list):
|
||||
return result
|
||||
@@ -812,8 +810,9 @@ def get_plugin_blacklist(settings, connectivity_checker=None):
|
||||
|
||||
if cache is not None:
|
||||
try:
|
||||
with bom_aware_open(cache, encoding="utf-8", mode="wt") as f:
|
||||
yaml.safe_dump(result, f)
|
||||
from octoprint.util import yaml
|
||||
|
||||
yaml.save_to_file(result, path=cache)
|
||||
except Exception as e:
|
||||
logger.info(
|
||||
"Fetched plugin blacklist but couldn't write it to its cache file: %s",
|
||||
|
||||
@@ -6,12 +6,10 @@ import logging
|
||||
import os
|
||||
from functools import partial
|
||||
|
||||
import yaml
|
||||
|
||||
from octoprint.access import ADMIN_GROUP, GUEST_GROUP, READONLY_GROUP, USER_GROUP
|
||||
from octoprint.access.permissions import OctoPrintPermission, Permissions
|
||||
from octoprint.settings import settings
|
||||
from octoprint.util import atomic_write
|
||||
from octoprint.util import atomic_write, yaml
|
||||
from octoprint.vendor.flask_principal import Need, Permission
|
||||
|
||||
GroupNeed = partial(Need, "group")
|
||||
@@ -226,8 +224,7 @@ class FilebasedGroupManager(GroupManager):
|
||||
def _load(self):
|
||||
if os.path.exists(self._groupfile) and os.path.isfile(self._groupfile):
|
||||
try:
|
||||
with open(self._groupfile, encoding="utf-8") as f:
|
||||
data = yaml.safe_load(f)
|
||||
data = yaml.load_from_file(path=self._groupfile)
|
||||
|
||||
if "groups" not in data:
|
||||
groups = data
|
||||
@@ -343,11 +340,7 @@ class FilebasedGroupManager(GroupManager):
|
||||
with atomic_write(
|
||||
self._groupfile, mode="wt", permissions=0o600, max_permissions=0o666
|
||||
) as f:
|
||||
import yaml
|
||||
|
||||
yaml.safe_dump(
|
||||
data, f, default_flow_style=False, indent=2, allow_unicode=True
|
||||
)
|
||||
yaml.save_to_file(data, file=f, pretty=True)
|
||||
self._dirty = False
|
||||
self._load()
|
||||
|
||||
|
||||
@@ -8,7 +8,6 @@ import time
|
||||
import uuid
|
||||
|
||||
import wrapt
|
||||
import yaml
|
||||
from flask_login import AnonymousUserMixin, UserMixin
|
||||
from werkzeug.local import LocalProxy
|
||||
|
||||
@@ -17,7 +16,7 @@ from octoprint.access.permissions import OctoPrintPermission, Permissions
|
||||
from octoprint.settings import settings as s
|
||||
from octoprint.util import atomic_write, deprecated, generate_api_key
|
||||
from octoprint.util import get_fully_qualified_classname as fqcn
|
||||
from octoprint.util import to_bytes
|
||||
from octoprint.util import to_bytes, yaml
|
||||
|
||||
|
||||
class UserManager(GroupChangeListener):
|
||||
@@ -512,64 +511,60 @@ class FilebasedUserManager(UserManager):
|
||||
|
||||
def _load(self):
|
||||
if os.path.exists(self._userfile) and os.path.isfile(self._userfile):
|
||||
# noinspection PyBroadException
|
||||
with open(self._userfile, encoding="utf-8") as f:
|
||||
data = yaml.safe_load(f)
|
||||
data = yaml.load_from_file(path=self._userfile)
|
||||
|
||||
if not data or not isinstance(data, dict):
|
||||
self._logger.fatal(
|
||||
"{} does not contain a valid map of users. Fix "
|
||||
"the file, or remove it, then restart OctoPrint.".format(
|
||||
self._userfile
|
||||
)
|
||||
if not data or not isinstance(data, dict):
|
||||
self._logger.fatal(
|
||||
"{} does not contain a valid map of users. Fix "
|
||||
"the file, or remove it, then restart OctoPrint.".format(
|
||||
self._userfile
|
||||
)
|
||||
raise CorruptUserStorage()
|
||||
)
|
||||
raise CorruptUserStorage()
|
||||
|
||||
for name, attributes in data.items():
|
||||
if not isinstance(attributes, dict):
|
||||
continue
|
||||
for name, attributes in data.items():
|
||||
if not isinstance(attributes, dict):
|
||||
continue
|
||||
|
||||
permissions = []
|
||||
if "permissions" in attributes:
|
||||
permissions = attributes["permissions"]
|
||||
permissions = []
|
||||
if "permissions" in attributes:
|
||||
permissions = attributes["permissions"]
|
||||
|
||||
if "groups" in attributes:
|
||||
groups = set(attributes["groups"])
|
||||
else:
|
||||
groups = {self._group_manager.user_group}
|
||||
if "groups" in attributes:
|
||||
groups = set(attributes["groups"])
|
||||
else:
|
||||
groups = {self._group_manager.user_group}
|
||||
|
||||
# migrate from roles to permissions
|
||||
if "roles" in attributes and "permissions" not in attributes:
|
||||
self._logger.info(
|
||||
"Migrating user {} to new granular permission system".format(
|
||||
name
|
||||
)
|
||||
)
|
||||
|
||||
groups |= set(self._migrate_roles_to_groups(attributes["roles"]))
|
||||
self._dirty = True
|
||||
|
||||
apikey = None
|
||||
if "apikey" in attributes:
|
||||
apikey = attributes["apikey"]
|
||||
settings = {}
|
||||
if "settings" in attributes:
|
||||
settings = attributes["settings"]
|
||||
|
||||
self._users[name] = User(
|
||||
username=name,
|
||||
passwordHash=attributes["password"],
|
||||
active=attributes["active"],
|
||||
permissions=self._to_permissions(*permissions),
|
||||
groups=self._to_groups(*groups),
|
||||
apikey=apikey,
|
||||
settings=settings,
|
||||
# migrate from roles to permissions
|
||||
if "roles" in attributes and "permissions" not in attributes:
|
||||
self._logger.info(
|
||||
f"Migrating user {name} to new granular permission system"
|
||||
)
|
||||
for sessionid in self._sessionids_by_userid.get(name, set()):
|
||||
if sessionid in self._session_users_by_session:
|
||||
self._session_users_by_session[sessionid].update_user(
|
||||
self._users[name]
|
||||
)
|
||||
|
||||
groups |= set(self._migrate_roles_to_groups(attributes["roles"]))
|
||||
self._dirty = True
|
||||
|
||||
apikey = None
|
||||
if "apikey" in attributes:
|
||||
apikey = attributes["apikey"]
|
||||
settings = {}
|
||||
if "settings" in attributes:
|
||||
settings = attributes["settings"]
|
||||
|
||||
self._users[name] = User(
|
||||
username=name,
|
||||
passwordHash=attributes["password"],
|
||||
active=attributes["active"],
|
||||
permissions=self._to_permissions(*permissions),
|
||||
groups=self._to_groups(*groups),
|
||||
apikey=apikey,
|
||||
settings=settings,
|
||||
)
|
||||
for sessionid in self._sessionids_by_userid.get(name, set()):
|
||||
if sessionid in self._session_users_by_session:
|
||||
self._session_users_by_session[sessionid].update_user(
|
||||
self._users[name]
|
||||
)
|
||||
|
||||
if self._dirty:
|
||||
self._save()
|
||||
@@ -601,9 +596,7 @@ class FilebasedUserManager(UserManager):
|
||||
with atomic_write(
|
||||
self._userfile, mode="wt", permissions=0o600, max_permissions=0o666
|
||||
) as f:
|
||||
yaml.safe_dump(
|
||||
data, f, default_flow_style=False, indent=2, allow_unicode=True
|
||||
)
|
||||
yaml.save_to_file(data, file=f, pretty=True)
|
||||
self._dirty = False
|
||||
self._load()
|
||||
|
||||
|
||||
@@ -5,6 +5,8 @@ import sys
|
||||
|
||||
import click
|
||||
|
||||
from octoprint.util import yaml
|
||||
|
||||
click.disable_unicode_literals_warning = True
|
||||
|
||||
# ~~ "octoprint util" commands
|
||||
@@ -94,8 +96,6 @@ def gcode_command(
|
||||
|
||||
import time
|
||||
|
||||
import yaml
|
||||
|
||||
from octoprint.util.gcodeInterpreter import gcode
|
||||
|
||||
throttle_callback = None
|
||||
@@ -151,14 +151,7 @@ def gcode_command(
|
||||
)
|
||||
sys.exit(-1)
|
||||
click.echo("RESULTS:")
|
||||
click.echo(
|
||||
yaml.safe_dump(
|
||||
interpreter.get_result(),
|
||||
default_flow_style=False,
|
||||
indent=2,
|
||||
allow_unicode=True,
|
||||
)
|
||||
)
|
||||
click.echo(yaml.dump(interpreter.get_result(), pretty=True))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
@@ -9,6 +9,7 @@ import click
|
||||
import octoprint_client
|
||||
from octoprint import FatalStartupError, init_settings
|
||||
from octoprint.cli import bulk_options, get_ctx_obj_option
|
||||
from octoprint.util import yaml
|
||||
|
||||
click.disable_unicode_literals_warning = True
|
||||
|
||||
@@ -171,10 +172,7 @@ def post_from_file(ctx, path, file_path, json_flag, yaml_flag, timeout):
|
||||
with open(file_path) as fp:
|
||||
data = json.load(fp)
|
||||
else:
|
||||
import yaml
|
||||
|
||||
with open(file_path) as fp:
|
||||
data = yaml.safe_load(fp)
|
||||
data = yaml.load_from_file(path=file_path)
|
||||
|
||||
r = ctx.obj.client.post_json(path, data, timeout=timeout)
|
||||
else:
|
||||
|
||||
@@ -7,10 +7,10 @@ import logging
|
||||
import pprint
|
||||
|
||||
import click
|
||||
import yaml
|
||||
|
||||
from octoprint import FatalStartupError, init_settings
|
||||
from octoprint.cli import get_ctx_obj_option, standard_options
|
||||
from octoprint.util import yaml
|
||||
|
||||
click.disable_unicode_literals_warning = True
|
||||
|
||||
@@ -214,9 +214,7 @@ def get_command(ctx, path, as_json=False, as_yaml=False, as_raw=False):
|
||||
if as_json:
|
||||
output = json.dumps(value)
|
||||
elif as_yaml:
|
||||
output = yaml.safe_dump(
|
||||
value, default_flow_style=False, indent=2, allow_unicode=True
|
||||
)
|
||||
output = yaml.dump(value, pretty=True)
|
||||
elif as_raw:
|
||||
output = value
|
||||
else:
|
||||
@@ -240,9 +238,7 @@ def effective_command(ctx, as_json=False, as_yaml=False, as_raw=False):
|
||||
if as_json:
|
||||
output = json.dumps(value)
|
||||
elif as_yaml:
|
||||
output = yaml.safe_dump(
|
||||
value, default_flow_style=False, indent=2, allow_unicode=True
|
||||
)
|
||||
output = yaml.dump(value, pretty=True)
|
||||
elif as_raw:
|
||||
output = value
|
||||
else:
|
||||
|
||||
@@ -1,19 +1,22 @@
|
||||
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
|
||||
__copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
__copyright__ = "Copyright (C) 2020 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
|
||||
import datetime
|
||||
import logging
|
||||
import os
|
||||
|
||||
import click
|
||||
import zipstream
|
||||
from zipstream.ng import ZIP_DEFLATED, ZipStream
|
||||
|
||||
from octoprint.cli import init_platform_for_cli, standard_options
|
||||
|
||||
click.disable_unicode_literals_warning = True
|
||||
|
||||
|
||||
def get_systeminfo(environment_detector, connectivity_checker, additional_fields=None):
|
||||
def get_systeminfo(
|
||||
environment_detector, connectivity_checker, settings, additional_fields=None
|
||||
):
|
||||
from octoprint import __version__
|
||||
from octoprint.util import dict_flatten
|
||||
|
||||
@@ -22,10 +25,30 @@ def get_systeminfo(environment_detector, connectivity_checker, additional_fields
|
||||
|
||||
environment_detector.run_detection(notify_plugins=False)
|
||||
|
||||
safe_mode_file = os.path.join(settings.getBaseFolder("data"), "last_safe_mode")
|
||||
last_safe_mode = {"date": "unknown", "reason": "unknown"}
|
||||
try:
|
||||
if os.path.exists(safe_mode_file):
|
||||
with open(safe_mode_file) as f:
|
||||
last_safe_mode["reason"] = f.readline().strip()
|
||||
last_safe_mode["date"] = (
|
||||
datetime.datetime.utcfromtimestamp(
|
||||
os.path.getmtime(safe_mode_file)
|
||||
).isoformat()[:19]
|
||||
+ "Z"
|
||||
)
|
||||
except Exception as ex:
|
||||
logging.getLogger(__name__).error(
|
||||
"Error while retrieving last safe mode information from {}: {}".format(
|
||||
safe_mode_file, ex
|
||||
)
|
||||
)
|
||||
|
||||
systeminfo = {
|
||||
"octoprint": {"version": __version__},
|
||||
"octoprint": {"version": __version__, "last_safe_mode": last_safe_mode},
|
||||
"connectivity": connectivity_checker.as_dict(),
|
||||
"env": environment_detector.environment,
|
||||
"systeminfo": {"generated": datetime.datetime.utcnow().isoformat()[:19] + "Z"},
|
||||
}
|
||||
|
||||
# flatten and filter
|
||||
@@ -42,39 +65,28 @@ def get_systeminfo(environment_detector, connectivity_checker, additional_fields
|
||||
def get_systeminfo_bundle(systeminfo, logbase, printer=None, plugin_manager=None):
|
||||
from octoprint.util import to_bytes
|
||||
|
||||
try:
|
||||
z = ZipStream(compress_type=ZIP_DEFLATED)
|
||||
except RuntimeError:
|
||||
# no zlib support
|
||||
z = ZipStream(sized=True)
|
||||
|
||||
if printer and printer.is_operational():
|
||||
firmware_info = printer.firmware_info
|
||||
if firmware_info:
|
||||
# add firmware to systeminfo so it's included in systeminfo.txt
|
||||
systeminfo["printer.firmware"] = firmware_info["name"]
|
||||
|
||||
# Add printer log, if available
|
||||
if hasattr(printer, "_log"):
|
||||
z.add(to_bytes("\n".join(printer._log)), "terminal.txt")
|
||||
|
||||
# add systeminfo
|
||||
systeminfotxt = []
|
||||
for k in sorted(systeminfo.keys()):
|
||||
systeminfotxt.append("{}: {}".format(k, systeminfo[k]))
|
||||
|
||||
terminaltxt = None
|
||||
if printer and printer.is_operational():
|
||||
firmware_info = printer.firmware_info
|
||||
if firmware_info:
|
||||
systeminfo["printer.firmware"] = firmware_info["name"]
|
||||
|
||||
if hasattr(printer, "_log"):
|
||||
terminaltxt = list(printer._log)
|
||||
|
||||
try:
|
||||
import zlib # noqa: F401
|
||||
|
||||
compress_type = zipstream.ZIP_DEFLATED
|
||||
except ImportError:
|
||||
# no zlib, no compression
|
||||
compress_type = zipstream.ZIP_STORED
|
||||
|
||||
z = zipstream.ZipFile()
|
||||
|
||||
# add systeminfo
|
||||
z.writestr(
|
||||
"systeminfo.txt", to_bytes("\n".join(systeminfotxt)), compress_type=compress_type
|
||||
)
|
||||
|
||||
# add terminal.txt, if available
|
||||
if terminaltxt:
|
||||
z.writestr(
|
||||
"terminal.txt", to_bytes("\n".join(terminaltxt)), compress_type=compress_type
|
||||
)
|
||||
z.add(to_bytes("\n".join(systeminfotxt)), arcname="systeminfo.txt")
|
||||
|
||||
# add logs
|
||||
for log in (
|
||||
@@ -83,7 +95,7 @@ def get_systeminfo_bundle(systeminfo, logbase, printer=None, plugin_manager=None
|
||||
):
|
||||
logpath = os.path.join(logbase, log)
|
||||
if os.path.exists(logpath):
|
||||
z.write(logpath, arcname=log, compress_type=compress_type)
|
||||
z.add_path(logpath, arcname=log)
|
||||
|
||||
# add additional bundle contents from bundled plugins
|
||||
if plugin_manager:
|
||||
@@ -103,10 +115,10 @@ def get_systeminfo_bundle(systeminfo, logbase, printer=None, plugin_manager=None
|
||||
if isinstance(content, str):
|
||||
# log path
|
||||
if os.path.exists(content) and os.access(content, os.R_OK):
|
||||
z.write(content, arcname=log, compress_type=compress_type)
|
||||
z.add_path(content, arcname=log)
|
||||
elif callable(content):
|
||||
# content generating callable
|
||||
z.writestr(log, to_bytes(content()), compress_type=compress_type)
|
||||
z.add(to_bytes(content()), arcname=log)
|
||||
except Exception:
|
||||
logging.getLogger(__name__).exception(
|
||||
"Error while retrieving additional bundle contents for plugin {}".format(
|
||||
@@ -170,8 +182,7 @@ def systeminfo_command(ctx, path, **kwargs):
|
||||
)
|
||||
try:
|
||||
with open(zipfilename, "wb") as f:
|
||||
for data in z:
|
||||
f.write(data)
|
||||
f.writelines(z)
|
||||
except Exception as e:
|
||||
click.echo(str(e), err=True)
|
||||
click.echo(f"There was an error writing to {zipfilename}.", err=True)
|
||||
|
||||
@@ -8,9 +8,9 @@ import sys
|
||||
import threading
|
||||
|
||||
import psutil
|
||||
import yaml
|
||||
|
||||
from octoprint.plugin import EnvironmentDetectionPlugin
|
||||
from octoprint.util import yaml
|
||||
from octoprint.util.platform import get_os
|
||||
from octoprint.util.version import get_python_version_string
|
||||
|
||||
@@ -165,9 +165,7 @@ class EnvironmentDetector:
|
||||
self.run_detection()
|
||||
environment = copy.deepcopy(self._cache)
|
||||
|
||||
dumped_environment = yaml.safe_dump(
|
||||
environment, default_flow_style=False, indent=2, allow_unicode=True
|
||||
).strip()
|
||||
dumped_environment = yaml.dump(environment, pretty=True).strip()
|
||||
environment_lines = "\n".join(
|
||||
map(lambda l: f"| {l}", dumped_environment.split("\n"))
|
||||
)
|
||||
|
||||
@@ -98,6 +98,7 @@ class Events:
|
||||
REGISTERED_MESSAGE_RECEIVED = "RegisteredMessageReceived"
|
||||
COMMAND_SUPPRESSED = "CommandSuppressed"
|
||||
INVALID_TOOL_REPORTED = "InvalidToolReported"
|
||||
FILAMENT_CHANGE = "FilamentChange"
|
||||
|
||||
# Timelapse
|
||||
CAPTURE_START = "CaptureStart"
|
||||
|
||||
@@ -12,6 +12,7 @@ import octoprint.plugin
|
||||
import octoprint.util
|
||||
from octoprint.events import Events, eventManager
|
||||
from octoprint.util import get_fully_qualified_classname as fqcn
|
||||
from octoprint.util import yaml
|
||||
|
||||
from .analysis import AnalysisQueue, QueueEntry # noqa: F401
|
||||
from .destinations import FileDestinations # noqa: F401
|
||||
@@ -941,8 +942,6 @@ class FileManager:
|
||||
def save_recovery_data(self, origin, path, pos):
|
||||
import time
|
||||
|
||||
import yaml
|
||||
|
||||
from octoprint.util import atomic_write
|
||||
|
||||
data = {
|
||||
@@ -953,9 +952,7 @@ class FileManager:
|
||||
}
|
||||
try:
|
||||
with atomic_write(self._recovery_file, mode="wt", max_permissions=0o666) as f:
|
||||
yaml.safe_dump(
|
||||
data, stream=f, default_flow_style=False, indent=2, allow_unicode=True
|
||||
)
|
||||
yaml.save_to_file(data, file=f, pretty=True)
|
||||
except Exception:
|
||||
self._logger.exception(
|
||||
f"Could not write recovery data to file {self._recovery_file}"
|
||||
@@ -976,11 +973,9 @@ class FileManager:
|
||||
if not os.path.isfile(self._recovery_file):
|
||||
return None
|
||||
|
||||
import yaml
|
||||
|
||||
try:
|
||||
with open(self._recovery_file, encoding="utf-8") as f:
|
||||
data = yaml.safe_load(f)
|
||||
data = yaml.load_from_file(path=self._recovery_file)
|
||||
|
||||
if not isinstance(data, dict) or not all(
|
||||
map(lambda x: x in data, ("origin", "path", "pos", "date"))
|
||||
):
|
||||
|
||||
@@ -14,6 +14,7 @@ from octoprint.events import Events, eventManager
|
||||
from octoprint.settings import settings
|
||||
from octoprint.util import dict_merge
|
||||
from octoprint.util import get_fully_qualified_classname as fqcn
|
||||
from octoprint.util import yaml
|
||||
from octoprint.util.platform import CLOSE_FDS
|
||||
|
||||
EMPTY_RESULT = {
|
||||
@@ -401,7 +402,6 @@ class GcodeAnalysisQueue(AbstractAnalysisQueue):
|
||||
import sys
|
||||
|
||||
import sarge
|
||||
import yaml
|
||||
|
||||
if self._current.analysis and all(
|
||||
map(
|
||||
@@ -495,7 +495,7 @@ class GcodeAnalysisQueue(AbstractAnalysisQueue):
|
||||
raise RuntimeError("No analysis result found")
|
||||
else:
|
||||
_, output = output.split("RESULTS:")
|
||||
analysis = yaml.safe_load(output)
|
||||
analysis = yaml.load_from_file(file=output)
|
||||
|
||||
result["printingArea"] = analysis["printing_area"]
|
||||
result["dimensions"] = analysis["dimensions"]
|
||||
|
||||
@@ -12,7 +12,14 @@ from os import scandir, walk
|
||||
import pylru
|
||||
|
||||
import octoprint.filemanager
|
||||
from octoprint.util import atomic_write, is_hidden_path, time_this, to_bytes, to_unicode
|
||||
from octoprint.util import (
|
||||
atomic_write,
|
||||
is_hidden_path,
|
||||
time_this,
|
||||
to_bytes,
|
||||
to_unicode,
|
||||
yaml,
|
||||
)
|
||||
from octoprint.util.files import sanitize_filename
|
||||
|
||||
from . import Storage, StorageError
|
||||
@@ -73,10 +80,7 @@ class LocalFileStorage(Storage):
|
||||
if os.path.exists(old_metadata_path):
|
||||
# load the old metadata file
|
||||
try:
|
||||
with open(old_metadata_path, encoding="utf-8") as f:
|
||||
import yaml
|
||||
|
||||
self._old_metadata = yaml.safe_load(f)
|
||||
self._old_metadata = yaml.load_from_file(path=old_metadata_path)
|
||||
except Exception:
|
||||
self._logger.exception("Error while loading old metadata file")
|
||||
|
||||
@@ -1474,8 +1478,6 @@ class LocalFileStorage(Storage):
|
||||
# we switched to json in 1.3.9 - if we still have yaml here, migrate it now
|
||||
import json
|
||||
|
||||
import yaml
|
||||
|
||||
with self._get_persisted_metadata_lock(path):
|
||||
metadata_path_yaml = os.path.join(path, ".metadata.yaml")
|
||||
metadata_path_json = os.path.join(path, ".metadata.json")
|
||||
@@ -1496,16 +1498,13 @@ class LocalFileStorage(Storage):
|
||||
)
|
||||
return
|
||||
|
||||
with open(metadata_path_yaml, encoding="utf-8") as f:
|
||||
try:
|
||||
metadata = yaml.safe_load(f)
|
||||
except Exception:
|
||||
self._logger.exception(
|
||||
"Error while reading .metadata.yaml from {path}".format(
|
||||
**locals()
|
||||
)
|
||||
)
|
||||
return
|
||||
try:
|
||||
metadata = yaml.load_from_file(path=metadata_path_yaml)
|
||||
except Exception:
|
||||
self._logger.exception(
|
||||
"Error while reading .metadata.yaml from {path}".format(**locals())
|
||||
)
|
||||
return
|
||||
|
||||
if not isinstance(metadata, dict):
|
||||
# looks invalid, ignore it
|
||||
|
||||
@@ -834,11 +834,11 @@ class PluginManager:
|
||||
|
||||
processed_blacklist = []
|
||||
for entry in plugin_blacklist:
|
||||
if isinstance(entry, tuple):
|
||||
if isinstance(entry, (tuple, list)):
|
||||
key, version = entry
|
||||
try:
|
||||
processed_blacklist.append(
|
||||
(key, pkg_resources.Requirement.parse(version))
|
||||
(key, pkg_resources.Requirement.parse(key + version))
|
||||
)
|
||||
except Exception:
|
||||
self.logger.warning(
|
||||
@@ -1324,7 +1324,7 @@ class PluginManager:
|
||||
return entry_key == key and version in entry_version
|
||||
return False
|
||||
|
||||
return any(map(lambda entry: matches_plugin(entry), self.plugin_blacklist))
|
||||
return any(map(matches_plugin, self.plugin_blacklist))
|
||||
|
||||
def reload_plugins(
|
||||
self, startup=False, initialize_implementations=True, force_reload=None
|
||||
@@ -2385,9 +2385,15 @@ class Plugin:
|
||||
pass
|
||||
|
||||
def on_plugin_enabled(self):
|
||||
"""
|
||||
Called by the plugin core when the plugin was enabled. Override this to react to the event.
|
||||
"""
|
||||
pass
|
||||
|
||||
def on_plugin_disabled(self):
|
||||
"""
|
||||
Called by the plugin core when the plugin was disabled. Override this to react to the event.
|
||||
"""
|
||||
pass
|
||||
|
||||
|
||||
|
||||
@@ -123,6 +123,14 @@ class OctoPrintPlugin(Plugin):
|
||||
os.makedirs(self._data_folder)
|
||||
return self._data_folder
|
||||
|
||||
def on_plugin_pending_uninstall(self):
|
||||
"""
|
||||
Called by the plugin manager when the plugin is pending uninstall. Override this to react to the event.
|
||||
|
||||
NOT called during plugin uninstalls triggered outside of OctoPrint!
|
||||
"""
|
||||
pass
|
||||
|
||||
|
||||
class ReloadNeedingPlugin(Plugin):
|
||||
"""
|
||||
@@ -390,6 +398,10 @@ class TemplatePlugin(OctoPrintPlugin, ReloadNeedingPlugin):
|
||||
``TemplatePlugin`` is a :class:`~octoprint.plugin.core.ReloadNeedingPlugin`.
|
||||
"""
|
||||
|
||||
@property
|
||||
def template_folder_key(self):
|
||||
return f"plugin_{self._identifier}"
|
||||
|
||||
def get_template_configs(self):
|
||||
"""
|
||||
Allows configuration of injected navbar, sidebar, tab and settings templates (and also additional templates of
|
||||
|
||||
@@ -209,7 +209,6 @@ $(function () {
|
||||
}
|
||||
})
|
||||
.css({
|
||||
"width": "auto",
|
||||
"margin-left": function () {
|
||||
return -($(this).width() / 2);
|
||||
}
|
||||
|
||||
@@ -4,16 +4,20 @@ import time
|
||||
from collections import defaultdict
|
||||
|
||||
import flask
|
||||
import yaml
|
||||
from flask_babel import gettext
|
||||
|
||||
import octoprint.plugin
|
||||
from octoprint.access import ADMIN_GROUP
|
||||
from octoprint.access import ADMIN_GROUP, USER_GROUP
|
||||
from octoprint.access.permissions import Permissions
|
||||
from octoprint.server import NO_CONTENT, admin_permission, current_user
|
||||
from octoprint.server.util.flask import no_firstrun_access, restricted_access
|
||||
from octoprint.server.util import require_login_with
|
||||
from octoprint.server.util.flask import (
|
||||
add_non_caching_response_headers,
|
||||
no_firstrun_access,
|
||||
restricted_access,
|
||||
)
|
||||
from octoprint.settings import valid_boolean_trues
|
||||
from octoprint.util import ResettableTimer, atomic_write, generate_api_key
|
||||
from octoprint.util import ResettableTimer, atomic_write, generate_api_key, yaml
|
||||
|
||||
CUTOFF_TIME = 10 * 60 # 10min
|
||||
POLL_TIMEOUT = 5 # 5 seconds
|
||||
@@ -121,7 +125,14 @@ class AppKeysPlugin(
|
||||
"roles": ["admin"],
|
||||
"dangerous": True,
|
||||
"default_groups": [ADMIN_GROUP],
|
||||
}
|
||||
},
|
||||
{
|
||||
"key": "GRANT",
|
||||
"name": "Grant access",
|
||||
"description": gettext("Allows to grant app access"),
|
||||
"roles": ["user"],
|
||||
"default_groups": [USER_GROUP],
|
||||
},
|
||||
]
|
||||
|
||||
##~~ TemplatePlugin
|
||||
@@ -165,6 +176,9 @@ class AppKeysPlugin(
|
||||
user_id = data["user"]
|
||||
|
||||
app_token, user_token = self._add_pending_decision(app_name, user_id=user_id)
|
||||
auth_dialog = flask.url_for(
|
||||
"plugin.appkeys.handle_auth_dialog", app_token=app_token, _external=True
|
||||
) + (f"?user={user_id}" if user_id else "")
|
||||
|
||||
self._plugin_manager.send_plugin_message(
|
||||
self._identifier,
|
||||
@@ -175,7 +189,7 @@ class AppKeysPlugin(
|
||||
"user_id": user_id,
|
||||
},
|
||||
)
|
||||
response = flask.jsonify(app_token=app_token)
|
||||
response = flask.jsonify(app_token=app_token, auth_dialog=auth_dialog)
|
||||
response.status_code = 201
|
||||
response.headers["Location"] = flask.url_for(
|
||||
".handle_decision_poll", app_token=app_token, _external=True
|
||||
@@ -200,12 +214,59 @@ class AppKeysPlugin(
|
||||
|
||||
return flask.abort(404)
|
||||
|
||||
@octoprint.plugin.BlueprintPlugin.route("/auth/<app_token>")
|
||||
@no_firstrun_access
|
||||
def handle_auth_dialog(self, app_token):
|
||||
user_id = current_user.get_name()
|
||||
required_user = flask.request.args.get("user", None)
|
||||
|
||||
pendings = self._get_pending_by_app_token(app_token)
|
||||
if not pendings:
|
||||
return flask.abort(404)
|
||||
|
||||
response = require_login_with(
|
||||
permissions=[Permissions.PLUGIN_APPKEYS_GRANT], user_id=required_user
|
||||
)
|
||||
if response:
|
||||
return response
|
||||
|
||||
pending = None
|
||||
for p in pendings:
|
||||
if p.user_id == required_user or (not required_user and p.user_id == user_id):
|
||||
pending = p
|
||||
break
|
||||
else:
|
||||
return flask.abort(404)
|
||||
|
||||
app_id = pending.app_id
|
||||
user_token = pending.user_token
|
||||
redirect_url = flask.request.args.get("redirect", "")
|
||||
|
||||
response = flask.make_response(
|
||||
flask.render_template(
|
||||
"plugin_appkeys/appkeys_authdialog.jinja2",
|
||||
app=app_id,
|
||||
user=user_id,
|
||||
user_token=user_token,
|
||||
redirect_url=redirect_url,
|
||||
theming=[],
|
||||
request_text=gettext(
|
||||
'"<strong>%(app)s</strong>" has requested access to control OctoPrint through the API.'
|
||||
).replace("%(app)s", app_id),
|
||||
)
|
||||
)
|
||||
return add_non_caching_response_headers(response)
|
||||
|
||||
@octoprint.plugin.BlueprintPlugin.route("/decision/<user_token>", methods=["POST"])
|
||||
@restricted_access
|
||||
def handle_decision(self, user_token):
|
||||
data = flask.request.json
|
||||
if "decision" not in data:
|
||||
flask.abort(400, description="No decision provided")
|
||||
|
||||
if not Permissions.PLUGIN_APPKEYS_GRANT.can():
|
||||
flask.abort(403, description="No permission to grant app access")
|
||||
|
||||
decision = data["decision"] in valid_boolean_trues
|
||||
user_id = current_user.get_name()
|
||||
|
||||
@@ -438,8 +499,7 @@ class AppKeysPlugin(
|
||||
return
|
||||
|
||||
try:
|
||||
with open(self._key_path, encoding="utf-8", errors="strict") as f:
|
||||
persisted = yaml.safe_load(f)
|
||||
persisted = yaml.load_from_file(path=self._key_path)
|
||||
except Exception:
|
||||
self._logger.exception(
|
||||
f"Could not load application keys from {self._key_path}"
|
||||
@@ -464,7 +524,7 @@ class AppKeysPlugin(
|
||||
|
||||
try:
|
||||
with atomic_write(self._key_path, mode="wt") as f:
|
||||
yaml.safe_dump(to_persist, f, allow_unicode=True)
|
||||
yaml.save_to_file(to_persist, file=f)
|
||||
except Exception:
|
||||
self._logger.exception(
|
||||
f"Could not write application keys to {self._key_path}"
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
body{padding-top:40px;padding-bottom:40px;background-color:#f5f5f5}#auth-choice,#auth-done,#auth-error,#auth-offline{max-width:300px;padding:19px 29px 29px;margin:0 auto 20px;background-color:#fff;border:1px solid #e5e5e5;-webkit-border-radius:5px;-moz-border-radius:5px;border-radius:5px;-webkit-box-shadow:0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:0 1px 2px rgba(0,0,0,.05);box-shadow:0 1px 2px rgba(0,0,0,.05);text-align:center}.form-auth-heading{margin-bottom:10px}
|
||||
@@ -0,0 +1,91 @@
|
||||
/*
|
||||
* Will get included into the auth dialog, NOT into the regular OctoPrint
|
||||
* web application.
|
||||
*/
|
||||
|
||||
$(function () {
|
||||
var OctoPrint = window.OctoPrint;
|
||||
|
||||
OctoPrint.authui = {
|
||||
startedUp: false
|
||||
};
|
||||
|
||||
var offlineElement = $("#auth-offline");
|
||||
var grantButtonElement = $("#auth-grant");
|
||||
var rejectButtonElement = $("#auth-reject");
|
||||
|
||||
var choiceElement = $("#auth-choice");
|
||||
var doneElement = $("#auth-done");
|
||||
var errorElement = $("#auth-error");
|
||||
|
||||
var showDone = function () {
|
||||
choiceElement.hide();
|
||||
doneElement.show();
|
||||
};
|
||||
var showError = function () {
|
||||
choiceElement.hide();
|
||||
errorElement.show();
|
||||
};
|
||||
var showOffline = function () {
|
||||
choiceElement.hide();
|
||||
offlineElement.show();
|
||||
};
|
||||
|
||||
grantButtonElement.click(function () {
|
||||
errorElement.removeClass("in");
|
||||
|
||||
OctoPrint.plugins.appkeys
|
||||
.decide(USER_TOKEN, true)
|
||||
.done(function () {
|
||||
if (REDIRECT_URL) {
|
||||
window.location.href = REDIRECT_URL;
|
||||
} else {
|
||||
showDone();
|
||||
}
|
||||
})
|
||||
.fail(showError);
|
||||
|
||||
return false;
|
||||
});
|
||||
rejectButtonElement.click(function () {
|
||||
OctoPrint.plugins.appkeys
|
||||
.decide(USER_TOKEN, false)
|
||||
.done(function () {
|
||||
if (REDIRECT_URL) {
|
||||
window.location.href = REDIRECT_URL;
|
||||
} else {
|
||||
showDone();
|
||||
}
|
||||
})
|
||||
.fail(showError);
|
||||
|
||||
return false;
|
||||
});
|
||||
|
||||
OctoPrint.options.baseurl = BASE_URL;
|
||||
|
||||
OctoPrint.socket.onConnected = function () {
|
||||
OctoPrint.browser.passiveLogin().done(function (login) {
|
||||
OctoPrint.socket.sendAuth(login.name, login.session);
|
||||
OctoPrint.authui.startedUp = true;
|
||||
});
|
||||
};
|
||||
|
||||
OctoPrint.socket.onDisconnected = function () {
|
||||
showOffline();
|
||||
};
|
||||
|
||||
OctoPrint.socket.onMessage("plugin", function (event) {
|
||||
if (event.data.plugin !== "appkeys") return;
|
||||
|
||||
var type = event.data.data.type;
|
||||
if (type !== "end_request") return;
|
||||
|
||||
var token = event.data.data.user_token;
|
||||
if (token !== USER_TOKEN) return;
|
||||
|
||||
showDone();
|
||||
});
|
||||
|
||||
OctoPrint.socket.connect();
|
||||
});
|
||||
@@ -0,0 +1,27 @@
|
||||
body {
|
||||
padding-top: 40px;
|
||||
padding-bottom: 40px;
|
||||
background-color: #f5f5f5;
|
||||
}
|
||||
|
||||
#auth-choice,
|
||||
#auth-done,
|
||||
#auth-error,
|
||||
#auth-offline {
|
||||
max-width: 300px;
|
||||
padding: 19px 29px 29px;
|
||||
margin: 0 auto 20px;
|
||||
background-color: #fff;
|
||||
border: 1px solid #e5e5e5;
|
||||
-webkit-border-radius: 5px;
|
||||
-moz-border-radius: 5px;
|
||||
border-radius: 5px;
|
||||
-webkit-box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
|
||||
-moz-box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
|
||||
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.form-auth-heading {
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
<html>
|
||||
<head>
|
||||
<meta name="viewport" content="width=device-width,initial-scale=1">
|
||||
<title>OctoPrint App Authentication</title>
|
||||
|
||||
<link rel="shortcut icon" href="{{ url_for('static', filename='img/tentacle-32x32.png') }}">
|
||||
<link rel="mask-icon" href="{{ url_for('static', filename='img/mask.svg') }}" color="#56BE37">
|
||||
<link rel="mask-icon-theme" href="{{ url_for('static', filename='img/mask-theme.svg') }}" color="#56BE37">
|
||||
<link rel="apple-touch-icon" sizes="114x114" href="{{ url_for('static', filename='img/apple-touch-icon-114x114.png') }}">
|
||||
<link rel="apple-touch-icon" sizes="144x144" href="{{ url_for('static', filename='img/apple-touch-icon-144x144.png') }}">
|
||||
|
||||
<!-- le CSS -->
|
||||
|
||||
<link rel="stylesheet" href="{{ url_for('static', filename='css/bootstrap.min.css') }}">
|
||||
<link rel="stylesheet" href="{{ url_for('static', filename='css/bootstrap-responsive.min.css') }}">
|
||||
<link rel="stylesheet" href="{{ url_for('static', filename='vendor/font-awesome-5.15.1/css/all.min.css') }}">
|
||||
<link rel="stylesheet" href="{{ url_for('static', filename='vendor/font-awesome-5.15.1/css/v4-shims.css') }}">
|
||||
<link rel="stylesheet" href="{{ url_for('plugin.appkeys.static', filename='css/authdialog.css') }}">
|
||||
|
||||
{% for url in theming %}
|
||||
<link rel="stylesheet" href="{{ url }}">
|
||||
{% endfor %}
|
||||
|
||||
<!-- le javascript -->
|
||||
|
||||
<script>
|
||||
var BASE_URL = "{{ url_for('index') }}";
|
||||
var USER_TOKEN = "{{ user_token|e }}";
|
||||
var DECISION_URL = "{{ url_for('plugin.appkeys.handle_decision', user_token=user_token) }}";
|
||||
var REDIRECT_URL = "{{ redirect_url|e }}";
|
||||
</script>
|
||||
<script src="{{ url_for('static', filename='js/lib/jquery/jquery.min.js') }}"></script>
|
||||
<script src="{{ url_for('static', filename='js/lib/sockjs.min.js') }}"></script>
|
||||
<script src="{{ url_for('static', filename='js/lib/bootstrap/bootstrap.js') }}"></script>
|
||||
<script src="{{ url_for('static', filename='js/lib/lodash.min.js') }}"></script>
|
||||
|
||||
{% assets "js_client" %}
|
||||
<script type="text/javascript" src="{{ ASSET_URL }}"></script>
|
||||
{% endassets %}
|
||||
|
||||
<script src="{{ url_for('plugin.appkeys.static', filename='js/authdialog.js') }}"></script>
|
||||
</head>
|
||||
<body>
|
||||
<div class="container">
|
||||
<form id="auth-choice" class="form-auth">
|
||||
<h2 class="form-auth-heading" data-test-id="login-title">{{ _('Access Request') }}</h2>
|
||||
|
||||
<p>{% trans %}Hello {{ user }}!{% endtrans %}</p>
|
||||
<p>{{ request_text }}</p>
|
||||
<p>{% trans %}
|
||||
Do you want to allow access to this application with your user account?
|
||||
{% endtrans %}</p>
|
||||
|
||||
<button class="btn btn-block btn-primary" id="auth-grant" data-test-id="auth-grant" type="submit">{{ _('Allow') }}</button>
|
||||
<button class="btn btn-block" id="auth-reject" data-test-id="auth-reject" type="submit">{{ _('Deny') }}</button>
|
||||
</form>
|
||||
|
||||
<div id="auth-done" class="hide">
|
||||
<p>{% trans %}
|
||||
The access request has been processed. You may now close this tab.
|
||||
{% endtrans %}</p>
|
||||
</div>
|
||||
|
||||
<div id="auth-error" class="hide">
|
||||
<p class="text-error">{% trans %}
|
||||
Something went wrong while processing the access request. You may now close this tab.
|
||||
{% endtrans %}</p>
|
||||
</div>
|
||||
|
||||
<div id="auth-offline" class="hide">
|
||||
<p class="text-error">{% trans %}
|
||||
The server has gone offline. You may now close this tab.
|
||||
{% endtrans %}</p>
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
@@ -10,7 +10,7 @@ from octoprint.events import Events
|
||||
from octoprint.server import NO_CONTENT
|
||||
from octoprint.server.util.flask import no_firstrun_access
|
||||
from octoprint.settings import default_settings
|
||||
from octoprint.util import is_hidden_path, to_bytes
|
||||
from octoprint.util import is_hidden_path, to_bytes, yaml
|
||||
from octoprint.util.pip import create_pip_caller
|
||||
from octoprint.util.platform import is_os_compatible
|
||||
from octoprint.util.version import (
|
||||
@@ -1190,10 +1190,7 @@ class BackupPlugin(
|
||||
on_restore_failed(path)
|
||||
return False
|
||||
|
||||
import yaml
|
||||
|
||||
with open(configfile, encoding="utf-8") as f:
|
||||
configdata = yaml.safe_load(f)
|
||||
configdata = yaml.load_from_file(path=configfile)
|
||||
|
||||
userfile = os.path.join(temp, "basedir", "users.yaml")
|
||||
if not os.path.exists(userfile):
|
||||
|
||||
@@ -108,7 +108,7 @@
|
||||
<p>{{ _('Restore settings & files from an uploaded backup archive.') }}</p>
|
||||
|
||||
{% set plugin_backup_upload_form_id='settings-backup-upload' %}
|
||||
{% include "snippets/plugin/backup/backup_plugin_upload_form.jinja2" %}
|
||||
{% include "snippets/backup_plugin_upload_form.jinja2" %}
|
||||
</div>
|
||||
|
||||
<div data-bind="visible: !restoreSupported()">
|
||||
|
||||
@@ -5,4 +5,4 @@
|
||||
</p>{% endtrans %}
|
||||
|
||||
{% set plugin_backup_upload_form_id='wizard-backup-upload' %}
|
||||
{% include "snippets/plugin/backup/backup_plugin_upload_form.jinja2" %}
|
||||
{% include "snippets/backup_plugin_upload_form.jinja2" %}
|
||||
File renamed without changes.
@@ -786,7 +786,7 @@ class DiscoveryPlugin(
|
||||
|
||||
__plugin_name__ = "Discovery"
|
||||
__plugin_author__ = "Gina Häußge"
|
||||
__plugin_url__ = "http://docs.octoprint.org/en/master/bundledplugins/discovery.html"
|
||||
__plugin_url__ = "https://docs.octoprint.org/en/master/bundledplugins/discovery.html"
|
||||
__plugin_description__ = (
|
||||
"Makes the OctoPrint instance discoverable via Bonjour/Avahi/Zeroconf and uPnP"
|
||||
)
|
||||
|
||||
@@ -18,10 +18,10 @@ from octoprint.util.version import (
|
||||
)
|
||||
|
||||
SENTRY_URL_SERVER = (
|
||||
"https://6a544965fe6c4c6eb96f7e39352b2924@o118517.ingest.sentry.io/1373987"
|
||||
"https://690e174698034bcc95928e6bfa8573f7@o118517.ingest.sentry.io/1373987"
|
||||
)
|
||||
SENTRY_URL_COREUI = (
|
||||
"https://840570e9555741bcb82bd56a084fb46e@o118517.ingest.sentry.io/1374096"
|
||||
"https://186f1dc5da7d46ab9d6b6de564d839bb@o118517.ingest.sentry.io/1374096"
|
||||
)
|
||||
|
||||
SETTINGS_DEFAULTS = {
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
from flask_babel import gettext
|
||||
|
||||
import octoprint.events
|
||||
import octoprint.plugin
|
||||
from octoprint.access import ADMIN_GROUP
|
||||
|
||||
|
||||
class EventManagerPlugin(
|
||||
octoprint.plugin.SettingsPlugin,
|
||||
octoprint.plugin.AssetPlugin,
|
||||
octoprint.plugin.TemplatePlugin,
|
||||
):
|
||||
def on_settings_load(self):
|
||||
my_settings = {
|
||||
"availableEvents": octoprint.events.all_events(),
|
||||
"subscriptions": [],
|
||||
}
|
||||
events = self._settings.global_get(["events"])
|
||||
if events:
|
||||
my_settings["subscriptions"] = events.get("subscriptions", [])
|
||||
return my_settings
|
||||
|
||||
def on_settings_save(self, data):
|
||||
if type(data.get("subscriptions")) == list:
|
||||
self._settings.global_set(
|
||||
["events", "subscriptions"], data.get("subscriptions", [])
|
||||
)
|
||||
|
||||
def get_assets(self):
|
||||
return {"js": ["js/events.js"]}
|
||||
|
||||
def get_template_configs(self):
|
||||
return [
|
||||
{
|
||||
"type": "settings",
|
||||
"custom_bindings": True,
|
||||
"name": gettext("Event Manager"),
|
||||
}
|
||||
]
|
||||
|
||||
def get_additional_permissions(self):
|
||||
return [
|
||||
{
|
||||
"key": "MANAGE",
|
||||
"name": "Event management",
|
||||
"description": gettext(
|
||||
"Allows for the management of event subscriptions."
|
||||
),
|
||||
"default_groups": [ADMIN_GROUP],
|
||||
"roles": ["manage"],
|
||||
}
|
||||
]
|
||||
|
||||
|
||||
__plugin_name__ = gettext("Event Manager")
|
||||
__plugin_pythoncompat__ = ">=2.7,<4"
|
||||
__plugin_author__ = "jneilliii"
|
||||
__plugin_license__ = "AGPLv3"
|
||||
__plugin_description__ = gettext(
|
||||
"Plugin to configure event subscriptions available in config.yaml."
|
||||
)
|
||||
__plugin_implementation__ = EventManagerPlugin()
|
||||
@@ -0,0 +1,59 @@
|
||||
/*
|
||||
* View model for OctoPrint-EventCoordinator
|
||||
*
|
||||
* Author: jneilliii
|
||||
* License: AGPLv3
|
||||
*/
|
||||
$(function () {
|
||||
function eventManagerViewModel(parameters) {
|
||||
var self = this;
|
||||
|
||||
self.settingsViewModel = parameters[0];
|
||||
self.selectedCommand = ko.observable();
|
||||
|
||||
self.eventDetails = function (data) {
|
||||
if (data === false) {
|
||||
return {
|
||||
event: ko.observable(""),
|
||||
command: ko.observable(""),
|
||||
type: ko.observable(""),
|
||||
enabled: ko.observable(true),
|
||||
debug: ko.observable(false)
|
||||
};
|
||||
} else {
|
||||
if (!data.hasOwnProperty("enabled")) {
|
||||
data["enabled"] = ko.observable(true);
|
||||
}
|
||||
if (!data.hasOwnProperty("debug")) {
|
||||
data["debug"] = ko.observable(false);
|
||||
}
|
||||
return data;
|
||||
}
|
||||
};
|
||||
|
||||
self.addEvent = function () {
|
||||
self.selectedCommand(self.eventDetails(false));
|
||||
self.settingsViewModel.settings.plugins.eventmanager.subscriptions.push(
|
||||
self.selectedCommand()
|
||||
);
|
||||
$("#EventManagerEditor").modal("show");
|
||||
};
|
||||
|
||||
self.editEvent = function (data) {
|
||||
self.selectedCommand(self.eventDetails(data));
|
||||
$("#EventManagerEditor").modal("show");
|
||||
};
|
||||
|
||||
self.removeEvent = function (data) {
|
||||
self.settingsViewModel.settings.plugins.eventmanager.subscriptions.remove(
|
||||
data
|
||||
);
|
||||
};
|
||||
}
|
||||
|
||||
OCTOPRINT_VIEWMODELS.push({
|
||||
construct: eventManagerViewModel,
|
||||
dependencies: ["settingsViewModel"],
|
||||
elements: ["#settings_plugin_eventmanager"]
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,65 @@
|
||||
<div class="alert alert-block">
|
||||
<p>{{ _('For additional information on OctoPrint events please see <a href="%(url)s" target="_blank" rel="noopener noreferer">the official documentation</a>.', url='https://docs.octoprint.org/en/master/events/index.html') }}</p>
|
||||
<p><strong>{{ _('Warning:') }}</strong> {{ _('For changes to take effect you must restart OctoPrint after saving.') }}</p>
|
||||
</div>
|
||||
<div class="row-fluid">
|
||||
<div class="span4">{{ _('Event') }}</div>
|
||||
<div class="span6">{{ _('Command') }}</div>
|
||||
<div class="span2 btn-group">
|
||||
<button class="btn btn-mini" data-bind="click: addEvent"><i class="fa fa-plus"></i> {{ _('Add') }}</button>
|
||||
</div>
|
||||
</div>
|
||||
<div data-bind="foreach: settingsViewModel.settings.plugins.eventmanager.subscriptions" class="row-fluid">
|
||||
<div class="row-fluid">
|
||||
<div class="span4" data-bind="text: event"></div>
|
||||
<div class="span6" data-bind="text: command"></div>
|
||||
<div class="span2 btn-group">
|
||||
<button class="btn btn-mini" data-bind="click: $root.editEvent"><i class="fa fa-pencil"></i></button>
|
||||
<button class="btn btn-mini btn-danger" data-bind="click: $root.removeEvent"><i class="fa fa-trash-alt"></i></button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div id="EventManagerEditor" data-bind="with: selectedCommand" class="modal hide fade-in">
|
||||
<div class="modal-header">
|
||||
<a href="#" class="close" data-dismiss="modal" aria-hidden="true">×</a>
|
||||
<h3>{{ _('Command Editor') }}</h3>
|
||||
</div>
|
||||
<div class="modal-body">
|
||||
<div class="control-group">
|
||||
<label class="control-label">{{ _('Event') }}</label>
|
||||
<div class="controls">
|
||||
<select class="input-block-level" data-bind="value: event, options: $root.settingsViewModel.settings.plugins.eventmanager.availableEvents().sort(), optionsCaption: 'Select Event', valueAllowUnset: true"></select>
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group">
|
||||
<label class="control-label">{{ _('Command') }}</label>
|
||||
<div class="controls">
|
||||
<input type="text" class="input-block-level" data-bind="value: command" />
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group">
|
||||
<label class="control-label">{{ _('Type') }}</label>
|
||||
<div class="controls">
|
||||
<select data-bind="value: type, options: ['gcode', 'system'], optionsCaption: 'Select Event Type', valueAllowUnset: true"></select>
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group">
|
||||
<label class="control-label">{{ _('Enabled') }}</label>
|
||||
<div class="controls">
|
||||
<input type="checkbox" data-bind="checked: enabled" />
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group">
|
||||
<label class="control-label">{{ _('Debug') }}</label>
|
||||
<div class="controls">
|
||||
<input type="checkbox" data-bind="checked: debug" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<div class="row-fluid">
|
||||
{{ _('Do not forget to save in main settings.') }} <button type="button" class="btn" data-dismiss="modal">{{ _('Close') }}</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -371,6 +371,7 @@ $(function () {
|
||||
|
||||
self._configureLayerSlider(layerSliderElement);
|
||||
self._configureLayerCommandSlider(commandSliderElement);
|
||||
self._configureContainerElement(containerElement);
|
||||
|
||||
self.settings.firstRequest.done(function () {
|
||||
var initResult = GCODE.ui.init({
|
||||
@@ -475,6 +476,18 @@ $(function () {
|
||||
.on("slide", self.changeCommandRange);
|
||||
};
|
||||
|
||||
self._configureContainerElement = function (containerElement) {
|
||||
// Prevent the default browser action for the mouse wheel down event. The desired behavor is to have the
|
||||
// gocde canvas pan on mouse down + drag, which happens. But if we don't prevent the default action, the browser
|
||||
// will also scroll the entire page.
|
||||
containerElement.mousedown(function (event) {
|
||||
// Middle mouse button
|
||||
if (event.which === 2) {
|
||||
event.preventDefault();
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
self.loadFile = function (path, date) {
|
||||
self.enableReload(false);
|
||||
self.needsLoad = false;
|
||||
|
||||
@@ -617,12 +617,19 @@ GCODE.renderer = (function () {
|
||||
ctx.circle(0, 0, 2);
|
||||
ctx.stroke();
|
||||
|
||||
ctx.strokeStyle = renderOptions["colorGrid"];
|
||||
ctx.lineWidth = lineWidthFactor;
|
||||
|
||||
//~~ grid starting from origin
|
||||
ctx.beginPath();
|
||||
ctx.strokeStyle = renderOptions["colorGrid"];
|
||||
var gridline = 0;
|
||||
for (x = 0; x <= maxX; x += gridStep) {
|
||||
ctx.beginPath();
|
||||
if (gridline % 5 === 0) {
|
||||
// every fifth line, including the center
|
||||
ctx.lineWidth = 1.5 * lineWidthFactor;
|
||||
} else {
|
||||
ctx.lineWidth = lineWidthFactor;
|
||||
}
|
||||
gridline += 1;
|
||||
|
||||
ctx.moveTo(x, minY);
|
||||
ctx.lineTo(x, maxY);
|
||||
|
||||
@@ -630,11 +637,20 @@ GCODE.renderer = (function () {
|
||||
ctx.moveTo(-1 * x, minY);
|
||||
ctx.lineTo(-1 * x, maxY);
|
||||
}
|
||||
ctx.stroke();
|
||||
}
|
||||
ctx.stroke();
|
||||
|
||||
ctx.beginPath();
|
||||
gridline = 0;
|
||||
for (y = 0; y <= maxY; y += gridStep) {
|
||||
ctx.beginPath();
|
||||
if (gridline % 5 === 0) {
|
||||
// every fifth line, including the center
|
||||
ctx.lineWidth = 1.5 * lineWidthFactor;
|
||||
} else {
|
||||
ctx.lineWidth = lineWidthFactor;
|
||||
}
|
||||
gridline += 1;
|
||||
|
||||
ctx.moveTo(minX, y);
|
||||
ctx.lineTo(maxX, y);
|
||||
|
||||
@@ -642,8 +658,8 @@ GCODE.renderer = (function () {
|
||||
ctx.moveTo(minX, -1 * y);
|
||||
ctx.lineTo(maxX, -1 * y);
|
||||
}
|
||||
ctx.stroke();
|
||||
}
|
||||
ctx.stroke();
|
||||
};
|
||||
|
||||
var drawCircularGrid = function () {
|
||||
|
||||
@@ -4,7 +4,6 @@ __copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms
|
||||
import os
|
||||
from os import scandir
|
||||
|
||||
import yaml
|
||||
from flask import abort, jsonify, request, url_for
|
||||
from flask_babel import gettext
|
||||
from werkzeug.exceptions import BadRequest
|
||||
@@ -16,7 +15,7 @@ from octoprint.access.permissions import Permissions
|
||||
from octoprint.server import NO_CONTENT
|
||||
from octoprint.server.util.flask import no_firstrun_access, redirect_to_tornado
|
||||
from octoprint.settings import settings
|
||||
from octoprint.util import is_hidden_path
|
||||
from octoprint.util import is_hidden_path, yaml
|
||||
|
||||
|
||||
class LoggingPlugin(
|
||||
@@ -180,10 +179,7 @@ class LoggingPlugin(
|
||||
|
||||
config_from_file = {}
|
||||
if os.path.exists(logging_file) and os.path.isfile(logging_file):
|
||||
import yaml
|
||||
|
||||
with open(logging_file, encoding="utf-8") as f:
|
||||
config_from_file = yaml.safe_load(f)
|
||||
config_from_file = yaml.load_from_file(path=logging_file)
|
||||
return config_from_file
|
||||
|
||||
def _get_logging_levels(self):
|
||||
@@ -233,9 +229,7 @@ class LoggingPlugin(
|
||||
with octoprint.util.atomic_write(
|
||||
self._get_logging_file(), mode="wt", max_permissions=0o666
|
||||
) as f:
|
||||
yaml.safe_dump(
|
||||
config, f, default_flow_style=False, indent=2, allow_unicode=True
|
||||
)
|
||||
yaml.save_to_file(config, file=f, pretty=True)
|
||||
|
||||
# set runtime logging levels now
|
||||
for logger, level in new_levels.items():
|
||||
|
||||
@@ -1251,6 +1251,14 @@ class PluginManagerPlugin(
|
||||
)
|
||||
abort(500, description="Could not uninstall plugin, its origin is unknown")
|
||||
|
||||
if plugin.implementation:
|
||||
try:
|
||||
plugin.implementation.on_plugin_pending_uninstall()
|
||||
except Exception:
|
||||
self._logger.exception(
|
||||
"Error while calling on_plugin_pending_uninstall on the plugin, proceeding regardless"
|
||||
)
|
||||
|
||||
if plugin.origin.type == "entry_point":
|
||||
# plugin is installed through entry point, need to use pip to uninstall it
|
||||
origin = plugin.origin[3]
|
||||
@@ -2113,7 +2121,7 @@ def _register_custom_events(*args, **kwargs):
|
||||
|
||||
__plugin_name__ = "Plugin Manager"
|
||||
__plugin_author__ = "Gina Häußge"
|
||||
__plugin_url__ = "http://docs.octoprint.org/en/master/bundledplugins/pluginmanager.html"
|
||||
__plugin_url__ = "https://docs.octoprint.org/en/master/bundledplugins/pluginmanager.html"
|
||||
__plugin_description__ = "Allows installing and managing OctoPrint plugins"
|
||||
__plugin_license__ = "AGPLv3"
|
||||
__plugin_pythoncompat__ = ">=2.7,<4"
|
||||
|
||||
@@ -1 +1 @@
|
||||
#settings_plugin_pluginmanager_pluginlist{height:calc(100vh - 450px);display:block;width:auto;overflow-x:hidden;padding-right:2px;margin-bottom:1em;position:relative;border-top:1px solid #eee;padding-top:6px}#settings_plugin_pluginmanager_pluginlist>table{margin-top:0}#settings_plugin_pluginmanager_pluginlist table td.settings_plugin_plugin_manager_plugins_name,#settings_plugin_pluginmanager_pluginlist table th.settings_plugin_plugin_manager_plugins_name{text-overflow:ellipsis;text-align:left}#settings_plugin_pluginmanager_pluginlist table td.settings_plugin_plugin_manager_plugins_name .prop,#settings_plugin_pluginmanager_pluginlist table th.settings_plugin_plugin_manager_plugins_name .prop{white-space:nowrap}#settings_plugin_pluginmanager_pluginlist table td.settings_plugin_plugin_manager_plugins_actions,#settings_plugin_pluginmanager_pluginlist table th.settings_plugin_plugin_manager_plugins_actions{text-align:center;width:80px}#settings_plugin_pluginmanager_pluginlist table td.settings_plugin_plugin_manager_plugins_actions a,#settings_plugin_pluginmanager_pluginlist table th.settings_plugin_plugin_manager_plugins_actions a{text-decoration:none;color:#000}#settings_plugin_pluginmanager_pluginlist table td.settings_plugin_plugin_manager_plugins_actions a.disabled,#settings_plugin_pluginmanager_pluginlist table th.settings_plugin_plugin_manager_plugins_actions a.disabled{color:#ccc;cursor:default}#settings_plugin_pluginmanager_orphanlist{display:block;width:auto;max-height:400px;overflow-x:hidden;overflow-y:scroll;padding-right:2px;margin-bottom:1em}#settings_plugin_pluginmanager_orphanlist table td.settings_plugin_plugin_manager_orphans_id,#settings_plugin_pluginmanager_orphanlist table th.settings_plugin_plugin_manager_orphans_id{text-overflow:ellipsis;text-align:left}#settings_plugin_pluginmanager_orphanlist table td.settings_plugin_plugin_manager_orphans_actions,#settings_plugin_pluginmanager_orphanlist table th.settings_plugin_plugin_manager_orphans_actions{text-align:center;width:80px}#settings_plugin_pluginmanager_orphanlist table td.settings_plugin_plugin_manager_orphans_actions a,#settings_plugin_pluginmanager_orphanlist table th.settings_plugin_plugin_manager_orphans_actions a{text-decoration:none;color:#000}#settings_plugin_pluginmanager_orphanlist table td.settings_plugin_plugin_manager_orphans_actions a.disabled,#settings_plugin_pluginmanager_orphanlist table th.settings_plugin_plugin_manager_orphans_actions a.disabled{color:#ccc;cursor:default}#settings_plugin_pluginmanager_repositorydialog h4{position:relative}#settings_plugin_pluginmanager_repositorydialog h4 a.dropdown-toggle{color:inherit;text-decoration:none;font-size:14px}#settings_plugin_pluginmanager_repositorydialog h4 ul.dropdown-menu{font-size:14px}#settings_plugin_pluginmanager_repositorydialog .form-search{text-align:center;margin-bottom:5px!important}#settings_plugin_pluginmanager_repositorydialog .form-inline{padding:5px 10px 5px 5px;margin-bottom:0}#settings_plugin_pluginmanager_repositorydialog .form-inline .help-block{margin-bottom:0;font-size:85%}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_empty,#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_unavailable{overflow:hidden;width:100%;height:400px;background-image:url(../img/repo_unavailable.png);text-align:center;display:table}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_empty div,#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_unavailable div{display:table-cell;vertical-align:middle}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_list{width:auto;height:400px;overflow-x:hidden;overflow-y:scroll;padding-right:2px}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_list .entry{border-bottom:1px solid #ddd;padding:5px}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_list .entry .meta{white-space:nowrap;text-overflow:ellipsis;overflow:hidden}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_list .entry .stats .prop{white-space:nowrap}#settings_plugin_pluginmanager_workingdialog_output .message{font-weight:700}#settings_plugin_pluginmanager_workingdialog_output .error{font-weight:700;color:#900}#settings_plugin_pluginmanager_workingdialog_output .stdout{color:#333}#settings_plugin_pluginmanager_workingdialog_output .stderr{color:#900}#settings_plugin_pluginmanager_workingdialog_output .call{color:#009}
|
||||
#settings_plugin_pluginmanager_pluginlist{height:calc(100vh - 450px);display:block;width:auto;overflow-x:hidden;padding-right:2px;margin-bottom:1em;position:relative;border-top:1px solid #eee;padding-top:6px}#settings_plugin_pluginmanager_pluginlist>table{margin-top:0}#settings_plugin_pluginmanager_pluginlist table td.settings_plugin_plugin_manager_plugins_checkbox,#settings_plugin_pluginmanager_pluginlist table th.settings_plugin_plugin_manager_plugins_checkbox{text-align:center;width:10px}#settings_plugin_pluginmanager_pluginlist table td.settings_plugin_plugin_manager_plugins_checkbox input[type=checkbox],#settings_plugin_pluginmanager_pluginlist table th.settings_plugin_plugin_manager_plugins_checkbox input[type=checkbox]{margin-top:0}#settings_plugin_pluginmanager_pluginlist table td.settings_plugin_plugin_manager_plugins_name,#settings_plugin_pluginmanager_pluginlist table th.settings_plugin_plugin_manager_plugins_name{text-overflow:ellipsis;text-align:left}#settings_plugin_pluginmanager_pluginlist table td.settings_plugin_plugin_manager_plugins_name .prop,#settings_plugin_pluginmanager_pluginlist table th.settings_plugin_plugin_manager_plugins_name .prop{white-space:nowrap}#settings_plugin_pluginmanager_pluginlist table td.settings_plugin_plugin_manager_plugins_actions,#settings_plugin_pluginmanager_pluginlist table th.settings_plugin_plugin_manager_plugins_actions{text-align:center;width:80px}#settings_plugin_pluginmanager_pluginlist table td.settings_plugin_plugin_manager_plugins_actions a,#settings_plugin_pluginmanager_pluginlist table th.settings_plugin_plugin_manager_plugins_actions a{text-decoration:none;color:#000}#settings_plugin_pluginmanager_pluginlist table td.settings_plugin_plugin_manager_plugins_actions a.disabled,#settings_plugin_pluginmanager_pluginlist table th.settings_plugin_plugin_manager_plugins_actions a.disabled{color:#ccc;cursor:default}#settings_plugin_pluginmanager_orphanlist{display:block;width:auto;max-height:400px;overflow-x:hidden;overflow-y:scroll;padding-right:2px;margin-bottom:1em}#settings_plugin_pluginmanager_orphanlist table td.settings_plugin_plugin_manager_orphans_id,#settings_plugin_pluginmanager_orphanlist table th.settings_plugin_plugin_manager_orphans_id{text-overflow:ellipsis;text-align:left}#settings_plugin_pluginmanager_orphanlist table td.settings_plugin_plugin_manager_orphans_actions,#settings_plugin_pluginmanager_orphanlist table th.settings_plugin_plugin_manager_orphans_actions{text-align:center;width:80px}#settings_plugin_pluginmanager_orphanlist table td.settings_plugin_plugin_manager_orphans_actions a,#settings_plugin_pluginmanager_orphanlist table th.settings_plugin_plugin_manager_orphans_actions a{text-decoration:none;color:#000}#settings_plugin_pluginmanager_orphanlist table td.settings_plugin_plugin_manager_orphans_actions a.disabled,#settings_plugin_pluginmanager_orphanlist table th.settings_plugin_plugin_manager_orphans_actions a.disabled{color:#ccc;cursor:default}#settings_plugin_pluginmanager_repositorydialog h4{position:relative}#settings_plugin_pluginmanager_repositorydialog h4 a.dropdown-toggle{color:inherit;text-decoration:none;font-size:14px}#settings_plugin_pluginmanager_repositorydialog h4 ul.dropdown-menu{font-size:14px}#settings_plugin_pluginmanager_repositorydialog .form-search{text-align:center;margin-bottom:5px!important}#settings_plugin_pluginmanager_repositorydialog .form-inline{padding:5px 10px 5px 5px;margin-bottom:0}#settings_plugin_pluginmanager_repositorydialog .form-inline .help-block{margin-bottom:0;font-size:85%}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_empty,#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_unavailable{overflow:hidden;width:100%;height:400px;background-image:url(../img/repo_unavailable.png);text-align:center;display:table}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_empty div,#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_unavailable div{display:table-cell;vertical-align:middle}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_list{width:auto;height:400px;overflow-x:hidden;overflow-y:scroll;padding-right:2px}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_list .entry{border-bottom:1px solid #ddd;padding:5px}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_list .entry .meta{white-space:nowrap;text-overflow:ellipsis;overflow:hidden}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_list .entry .stats .prop{white-space:nowrap}#settings_plugin_pluginmanager_workingdialog_output .message{font-weight:700}#settings_plugin_pluginmanager_workingdialog_output .error{font-weight:700;color:#900}#settings_plugin_pluginmanager_workingdiLine truncated
|
||||
@@ -50,7 +50,7 @@ $(function () {
|
||||
return !item.enabled;
|
||||
}
|
||||
},
|
||||
"popularity",
|
||||
"name",
|
||||
[],
|
||||
[
|
||||
["bundled", "3rdparty"],
|
||||
@@ -58,6 +58,10 @@ $(function () {
|
||||
],
|
||||
0
|
||||
);
|
||||
self.plugins.currentFilters.subscribe(function () {
|
||||
self.clearPluginsSelection();
|
||||
});
|
||||
self.pluginLookup = {};
|
||||
|
||||
self.repositoryplugins = new ItemListHelper(
|
||||
"plugin.pluginmanager.repositoryplugins",
|
||||
@@ -138,7 +142,7 @@ $(function () {
|
||||
return !plugin.abandoned;
|
||||
}
|
||||
},
|
||||
"title",
|
||||
"popularity",
|
||||
["filter_installed", "filter_incompatible"],
|
||||
[],
|
||||
0
|
||||
@@ -169,6 +173,8 @@ $(function () {
|
||||
0
|
||||
);
|
||||
|
||||
self.selectedPlugins = ko.observableArray([]);
|
||||
|
||||
self.uploadElement = $("#settings_plugin_pluginmanager_repositorydialog_upload");
|
||||
self.uploadButton = $(
|
||||
"#settings_plugin_pluginmanager_repositorydialog_upload_start"
|
||||
@@ -274,14 +280,21 @@ $(function () {
|
||||
return !self.printerState.isBusy();
|
||||
});
|
||||
|
||||
self.enableToggle = function (data) {
|
||||
self.enableBulk = function (data) {
|
||||
return self.enableToggle(data, true) && !data.bundled;
|
||||
};
|
||||
|
||||
self.enableToggle = function (data, ignoreToggling) {
|
||||
var command = self._getToggleCommand(data);
|
||||
var not_safemode_victim = !data.safe_mode_victim;
|
||||
var not_blacklisted = !data.blacklisted;
|
||||
var not_incompatible = !data.incompatible;
|
||||
|
||||
ignoreToggling = !!ignoreToggling;
|
||||
|
||||
return (
|
||||
self.enableManagement() &&
|
||||
!self.toggling() &&
|
||||
(ignoreToggling || !self.toggling()) &&
|
||||
(command === "disable" ||
|
||||
(not_safemode_victim && not_blacklisted && not_incompatible)) &&
|
||||
data.key !== "pluginmanager"
|
||||
@@ -508,7 +521,9 @@ $(function () {
|
||||
|
||||
var installedPlugins = [];
|
||||
var noticeCount = 0;
|
||||
var lookup = {};
|
||||
_.each(data, function (plugin) {
|
||||
lookup[plugin.key] = plugin;
|
||||
installedPlugins.push(plugin.key);
|
||||
|
||||
if (evalNotices && plugin.notifications && plugin.notifications.length) {
|
||||
@@ -537,6 +552,7 @@ $(function () {
|
||||
if (evalNotices) self.noticeCount(noticeCount);
|
||||
self.installedPlugins(installedPlugins);
|
||||
self.plugins.updateItems(data);
|
||||
self.pluginLookup = lookup;
|
||||
};
|
||||
|
||||
self.fromOrphanResponse = function (data) {
|
||||
@@ -802,6 +818,171 @@ $(function () {
|
||||
}
|
||||
};
|
||||
|
||||
self._bulkOperation = function (
|
||||
plugins,
|
||||
title,
|
||||
message,
|
||||
successText,
|
||||
failureText,
|
||||
statusText,
|
||||
callback,
|
||||
alreadyCheck
|
||||
) {
|
||||
var deferred = $.Deferred();
|
||||
var promise = deferred.promise();
|
||||
var options = {
|
||||
title: title,
|
||||
message: _.sprintf(message, {count: plugins.length}),
|
||||
max: plugins.length,
|
||||
output: true
|
||||
};
|
||||
showProgressModal(options, promise);
|
||||
|
||||
var handle = function (key) {
|
||||
var d = $.Deferred();
|
||||
|
||||
var plugin = self.pluginLookup[key];
|
||||
if (!plugin) {
|
||||
deferred.notify(
|
||||
_.sprintf(
|
||||
gettext("Can't resolve plugin with key %(key)s, skipping..."),
|
||||
{key: key}
|
||||
),
|
||||
false
|
||||
);
|
||||
d.reject();
|
||||
return d.promise();
|
||||
}
|
||||
if (!self.enableBulk(plugin)) {
|
||||
deferred.notify(
|
||||
_.sprintf(
|
||||
gettext(
|
||||
"Plugin %(plugin)s doesn't support bulk operations, skipping..."
|
||||
),
|
||||
{plugin: plugin.name || key}
|
||||
),
|
||||
false
|
||||
);
|
||||
d.reject();
|
||||
return d.promise();
|
||||
}
|
||||
if (alreadyCheck(plugin)) {
|
||||
deferred.notify(
|
||||
_.sprintf(
|
||||
gettext(
|
||||
"Plugin %(plugin)s is already %(status)s (or pending), skipping..."
|
||||
),
|
||||
{
|
||||
plugin: plugin.name || key,
|
||||
status: statusText
|
||||
}
|
||||
),
|
||||
true
|
||||
);
|
||||
d.reject();
|
||||
return d.promise();
|
||||
}
|
||||
|
||||
callback(plugin)
|
||||
.done(function () {
|
||||
deferred.notify(
|
||||
_.sprintf(successText, {plugin: plugin.name || key}),
|
||||
true
|
||||
);
|
||||
d.resolve();
|
||||
})
|
||||
.fail(function () {
|
||||
deferred.notify(
|
||||
_.sprintf(failureText, {plugin: plugin.name || key}),
|
||||
false
|
||||
);
|
||||
d.reject();
|
||||
});
|
||||
return d.promise();
|
||||
};
|
||||
|
||||
var operations = [];
|
||||
_.each(plugins, function (key) {
|
||||
operations.push(handle(key));
|
||||
});
|
||||
$.when.apply($, _.map(operations, wrapPromiseWithAlways)).done(function () {
|
||||
deferred.resolve();
|
||||
self.requestPluginData();
|
||||
});
|
||||
return promise;
|
||||
};
|
||||
|
||||
self.enableSelectedPlugins = function () {
|
||||
if (self.selectedPlugins().length === 0) return;
|
||||
|
||||
var callback = function (plugin) {
|
||||
return OctoPrint.plugins.pluginmanager.enable(plugin.key);
|
||||
};
|
||||
var check = function (plugin) {
|
||||
return plugin.enabled || plugin.pending_enable;
|
||||
};
|
||||
|
||||
self.toggling(true);
|
||||
self._bulkOperation(
|
||||
self.selectedPlugins(),
|
||||
gettext("Enabling plugins"),
|
||||
gettext("Enabling %(count)i plugins"),
|
||||
gettext("Enabled plugin %(plugin)s..."),
|
||||
gettext("Enabling plugin %(plugin)s failed, continuing..."),
|
||||
gettext("enabled"),
|
||||
callback,
|
||||
check
|
||||
)
|
||||
.done(function () {
|
||||
self.selectedPlugins([]);
|
||||
})
|
||||
.always(function () {
|
||||
self.toggling(false);
|
||||
});
|
||||
};
|
||||
|
||||
self.disableSelectedPlugins = function () {
|
||||
if (self.selectedPlugins().length === 0) return;
|
||||
|
||||
var callback = function (plugin) {
|
||||
return OctoPrint.plugins.pluginmanager.disable(plugin.key);
|
||||
};
|
||||
var check = function (plugin) {
|
||||
return !plugin.enabled || plugin.pending_disable;
|
||||
};
|
||||
|
||||
self.toggling(true);
|
||||
self._bulkOperation(
|
||||
self.selectedPlugins(),
|
||||
gettext("Disabling plugins"),
|
||||
gettext("Disabling %(count)i plugins"),
|
||||
gettext("Disabled plugin %(plugin)s..."),
|
||||
gettext("Disabling plugin %(plugin)s failed, continuing..."),
|
||||
gettext("disabled"),
|
||||
callback,
|
||||
check
|
||||
)
|
||||
.done(function () {
|
||||
self.selectedPlugins([]);
|
||||
})
|
||||
.always(function () {
|
||||
self.toggling(false);
|
||||
});
|
||||
};
|
||||
|
||||
self.selectAllVisiblePlugins = function () {
|
||||
var selection = [];
|
||||
_.each(self.plugins.paginatedItems(), function (plugin) {
|
||||
if (!self.enableBulk(plugin)) return;
|
||||
selection.push(plugin.key);
|
||||
});
|
||||
self.selectedPlugins(selection);
|
||||
};
|
||||
|
||||
self.clearPluginsSelection = function () {
|
||||
self.selectedPlugins([]);
|
||||
};
|
||||
|
||||
self.showRepository = function () {
|
||||
self.repositoryDialog.modal({
|
||||
minHeight: function () {
|
||||
|
||||
@@ -19,6 +19,15 @@
|
||||
table {
|
||||
th,
|
||||
td {
|
||||
&.settings_plugin_plugin_manager_plugins_checkbox {
|
||||
text-align: center;
|
||||
width: 10px;
|
||||
|
||||
input[type="checkbox"] {
|
||||
margin-top: 0;
|
||||
}
|
||||
}
|
||||
|
||||
&.settings_plugin_plugin_manager_plugins_name {
|
||||
text-overflow: ellipsis;
|
||||
text-align: left;
|
||||
|
||||
@@ -62,7 +62,7 @@
|
||||
|
||||
<div class="pull-right">
|
||||
<button class="btn btn-small" data-bind="click: $root.showRepository"><i class="fas fa-plus"></i> {{ _('Get More') }}</button>
|
||||
<a class="btn btn-small" href="/plugin/pluginmanager/export"><i class="fas fa-download"></i> {{ _('Export') }}</a>
|
||||
<a class="btn btn-small" href="{{ url_for('index') }}plugin/pluginmanager/export"><i class="fas fa-download"></i> {{ _('Export') }}</a>
|
||||
<button class="btn btn-small" data-bind="click: function() { $root.showPluginSettings(); }" title="{{ _('Plugin Configuration')|edq }}"><i class="fas fa-wrench"></i></button>
|
||||
<a class="btn btn-small" data-toggle="collapse" href="#pluginmanager_info" title="{{ _('Info') }}"><i class="fas fa-lg fa-info-circle text-info" data-bind="css: {'text-error': noticeCount() > 0, 'text-info': noticeCount() <=0 }"></i></a>
|
||||
</div>
|
||||
@@ -107,6 +107,16 @@
|
||||
<input type="text" class="input-block search-query pull-left" data-bind="value: listingSearchQuery, valueUpdate: 'input'" placeholder="{{ _('Search...')|edq }}">
|
||||
|
||||
<div class="pull-right">
|
||||
<div class="btn-group">
|
||||
<button class="btn btn-small dropdown-toggle" data-toggle="dropdown"><i class="far fa-square"></i> <span class="caret"></span></button>
|
||||
<ul class="dropdown-menu">
|
||||
<li><a href="javascript:void(0)" data-bind="click: selectAllVisiblePlugins">{{ _('Select all visible') }}</a></li>
|
||||
<li><a href="javascript:void(0)" data-bind="click: clearPluginsSelection">{{ _('Clear selection') }}</a></li>
|
||||
<li class="divider"></li>
|
||||
<li><a href="javascript:void(0)" data-bind="click: disableSelectedPlugins, css: {disabled: selectedPlugins().length == 0}"><i class="fa fa-toggle-off"></i> {{ _('Disable selected') }}</a></li>
|
||||
<li><a href="javascript:void(0)" data-bind="click: enableSelectedPlugins, css: {disabled: selectedPlugins().length == 0}"><i class="fa fa-toggle-on"></i> {{ _('Enable selected') }}</a></li>
|
||||
</ul>
|
||||
</div>
|
||||
<div class="btn-group">
|
||||
<button class="btn btn-small" data-bind="click: function() { plugins.removeFilter('bundled'); plugins.removeFilter('3rdparty'); }, css: {active: !_.contains(plugins.currentFilters(), 'bundled') && !_.contains(plugins.currentFilters(), '3rdparty')}" title="{{ _('Show both bundled and third-party plugins')|edq }}">All</button>
|
||||
<button class="btn btn-small" data-bind="click: function() { plugins.addFilter('bundled') }, css: {active: _.contains(plugins.currentFilters(), 'bundled')}" title="{{ _('Show only bundled plugins')|edq }}">{{ _('Bundled') }}</button>
|
||||
@@ -124,12 +134,17 @@
|
||||
<table class="table table-striped table-hover table-condensed table-hover">
|
||||
<thead>
|
||||
<tr>
|
||||
<th class="settings_plugin_plugin_manager_plugins_checkbox">
|
||||
</th>
|
||||
<th class="settings_plugin_plugin_manager_plugins_name">{{ _('Name') }}</th>
|
||||
<th class="settings_plugin_plugin_manager_plugins_actions">{{ _('Actions') }}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody data-bind="foreach: plugins.paginatedItems">
|
||||
<tr>
|
||||
<td class="settings_plugin_plugin_manager_plugins_checkbox">
|
||||
<input type="checkbox" data-bind="value: key, checked: $root.selectedPlugins, enable: $root.enableBulk($data)" title="{{ _('Bundled and incompatible plugins do not support bulk operations') | edq }}">
|
||||
</td>
|
||||
<td class="settings_plugin_plugin_manager_plugins_name">
|
||||
<div data-bind="css: {muted: !enabled}"><span data-bind="text: name"></span> <span data-bind="visible: version">(<span data-bind="text: version"></span>)</span> <i title="{{ _('Bundled with OctoPrint')|edq }}" class="fas fa-th-large" data-bind="visible: bundled"></i> <i class="fas fa-lock" title="{{ _('Cannot be uninstalled through OctoPrint')|edq }}" data-bind="visible: !managable"></i> <i class="fas fa-bolt" title="{{ _('Incompatible to OctoPrint or the underlying Python environment')|edq }}" data-bind="visible: incompatible"></i> <i title="{{ _('Restart of OctoPrint needed for changes to take effect')|edq }}" class="fas fa-sync" data-bind="visible: pending_enable || pending_disable || pending_install || pending_uninstall"></i> <i title="{{ _('Pending install')|edq }}" class="fas fa-plus" data-bind="visible: pending_install"></i> <i title="{{ _('Pending uninstall')|edq }}" class="fas fa-minus" data-bind="visible: pending_uninstall"></i> <i title="{{ _('Disabled due to safe mode')|edq }}" class="fas fa-medkit" data-bind="visible: safe_mode_victim"></i> <i class="fas fa-exclamation-triangle" title="{{ _('There are notices available regarding this plugin')|edq }}" data-bind="visible: notifications && notifications.length"></i> <i class="fas fa-ban" title="{{ _('This plugin is blacklisted')|edq }}" data-bind="visible: blacklisted"></i></div>
|
||||
<div data-bind="css: {muted: !enabled}">
|
||||
@@ -151,6 +166,7 @@
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<small>{{ _('Please note that bundled and incompatible plugins do not support bulk operations.') }}</small>
|
||||
</div>
|
||||
<div class="tab-pane" id="settings_plugin_pluginmanager_cleanup">
|
||||
<div class="pull-right">
|
||||
|
||||
@@ -27,20 +27,22 @@ from octoprint.server.util.flask import (
|
||||
no_firstrun_access,
|
||||
with_revalidation_checking,
|
||||
)
|
||||
from octoprint.util import dict_merge, get_formatted_size, to_unicode
|
||||
from octoprint.util import dict_merge, get_formatted_size, to_unicode, yaml
|
||||
from octoprint.util.pip import create_pip_caller
|
||||
from octoprint.util.version import (
|
||||
get_comparable_version,
|
||||
get_python_version_string,
|
||||
is_python_compatible,
|
||||
is_released_octoprint_version,
|
||||
is_stable,
|
||||
)
|
||||
|
||||
from . import cli, exceptions, updaters, util, version_checks
|
||||
|
||||
# OctoPi 0.15+
|
||||
MINIMUM_PYTHON = "2.7.9"
|
||||
MINIMUM_SETUPTOOLS = "39.0.1"
|
||||
MINIMUM_PIP = "9.0.3"
|
||||
# OctoPi 0.16+
|
||||
MINIMUM_PYTHON = "2.7.13"
|
||||
MINIMUM_SETUPTOOLS = "40.7.1"
|
||||
MINIMUM_PIP = "19.0.1"
|
||||
|
||||
DATETIME_FORMAT = "%Y-%m-%d %H:%M:%S"
|
||||
|
||||
@@ -60,9 +62,12 @@ class SoftwareUpdatePlugin(
|
||||
|
||||
COMMIT_TRACKING_TYPES = ("github_commit", "bitbucket_commit")
|
||||
CURRENT_TRACKING_TYPES = COMMIT_TRACKING_TYPES + ("etag", "lastmodified", "jsondata")
|
||||
RELEASE_TRACKING_TYPES = ("github_release",)
|
||||
|
||||
OCTOPRINT_RESTART_TYPES = ("pip", "single_file_plugin")
|
||||
|
||||
VALID_RESTART_TYPES = ("octoprint", "environment")
|
||||
|
||||
DATA_FORMAT_VERSION = "v4"
|
||||
|
||||
CHECK_OVERLAY_KEY = "softwareupdate_check_overlay"
|
||||
@@ -463,11 +468,8 @@ class SoftwareUpdatePlugin(
|
||||
if not os.path.isfile(self._version_cache_path):
|
||||
return
|
||||
|
||||
import yaml
|
||||
|
||||
try:
|
||||
with open(self._version_cache_path, encoding="utf-8") as f:
|
||||
data = yaml.safe_load(f)
|
||||
data = yaml.load_from_file(path=self._version_cache_path)
|
||||
timestamp = os.stat(self._version_cache_path).st_mtime
|
||||
except Exception:
|
||||
self._logger.exception("Error while loading version cache from disk")
|
||||
@@ -504,8 +506,6 @@ class SoftwareUpdatePlugin(
|
||||
self._logger.exception("Error parsing in version cache data")
|
||||
|
||||
def _save_version_cache(self):
|
||||
import yaml
|
||||
|
||||
from octoprint._version import get_versions
|
||||
from octoprint.util import atomic_write
|
||||
|
||||
@@ -515,13 +515,7 @@ class SoftwareUpdatePlugin(
|
||||
with atomic_write(
|
||||
self._version_cache_path, mode="wt", max_permissions=0o666
|
||||
) as file_obj:
|
||||
yaml.safe_dump(
|
||||
self._version_cache,
|
||||
stream=file_obj,
|
||||
default_flow_style=False,
|
||||
indent=2,
|
||||
allow_unicode=True,
|
||||
)
|
||||
yaml.save_to_file(self._version_cache, file=file_obj, pretty=True)
|
||||
|
||||
self._version_cache_dirty = False
|
||||
self._version_cache_timestamp = time.time()
|
||||
@@ -539,11 +533,8 @@ class SoftwareUpdatePlugin(
|
||||
if not os.path.isfile(self._update_log_path):
|
||||
return
|
||||
|
||||
import yaml
|
||||
|
||||
try:
|
||||
with open(self._update_log_path, encoding="utf-8") as f:
|
||||
data = yaml.safe_load(f)
|
||||
data = yaml.load_from_file(path=self._update_log_path)
|
||||
except Exception:
|
||||
self._logger.exception("Error while loading update log from disk")
|
||||
else:
|
||||
@@ -573,20 +564,16 @@ class SoftwareUpdatePlugin(
|
||||
self._logger.info("Loaded update log from disk")
|
||||
|
||||
def _save_update_log(self):
|
||||
import yaml
|
||||
|
||||
from octoprint.util import atomic_write
|
||||
|
||||
with self._update_log_mutex:
|
||||
with atomic_write(
|
||||
self._update_log_path, mode="wt", max_permissions=0o666
|
||||
) as file_obj:
|
||||
yaml.safe_dump(
|
||||
yaml.save_to_file(
|
||||
sorted(self._update_log, key=lambda x: x["datetime"]),
|
||||
stream=file_obj,
|
||||
default_flow_style=False,
|
||||
indent=2,
|
||||
allow_unicode=True,
|
||||
file=file_obj,
|
||||
pretty=True,
|
||||
)
|
||||
self._update_log_dirty = False
|
||||
|
||||
@@ -625,15 +612,45 @@ class SoftwareUpdatePlugin(
|
||||
self._save_update_log()
|
||||
|
||||
def _is_octoprint_outdated_and_can_update(self):
|
||||
information, update_available, update_possible = self.get_current_versions()
|
||||
if not update_available or not update_possible or "octoprint" not in information:
|
||||
checks = self._get_configured_checks()
|
||||
check = checks.get("octoprint", None)
|
||||
if not check:
|
||||
return False
|
||||
|
||||
octoprint_information = information["octoprint"]
|
||||
return (
|
||||
octoprint_information["updateAvailable"]
|
||||
and octoprint_information["updatePossible"]
|
||||
check = self._populated_check("octoprint", check)
|
||||
credentials = self._settings.get(["credentials"], merged=True)
|
||||
|
||||
_, update_available, update_possible, _, _ = self._get_current_version(
|
||||
"octoprint", check, credentials=credentials
|
||||
)
|
||||
if not update_available or not update_possible:
|
||||
return False
|
||||
|
||||
restart_type = self._get_restart_type(check)
|
||||
restart_command = self._get_restart_command(restart_type)
|
||||
return restart_command is not None
|
||||
|
||||
def _get_restart_type(self, check):
|
||||
if check.get("restart") in self.VALID_RESTART_TYPES:
|
||||
return check["restart"]
|
||||
elif "pip" in check or check.get("method") in self.OCTOPRINT_RESTART_TYPES:
|
||||
return "octoprint"
|
||||
else:
|
||||
target_restart_type = None
|
||||
|
||||
return target_restart_type
|
||||
|
||||
def _get_restart_command(self, restart_type):
|
||||
if restart_type == "octoprint":
|
||||
return self._settings.global_get(
|
||||
["server", "commands", "serverRestartCommand"]
|
||||
)
|
||||
elif restart_type == "environment":
|
||||
return self._settings.global_get(
|
||||
["server", "commands", "systemRestartCommand"]
|
||||
)
|
||||
else:
|
||||
return None
|
||||
|
||||
# ~~ SettingsPlugin API
|
||||
|
||||
@@ -1087,6 +1104,8 @@ class SoftwareUpdatePlugin(
|
||||
)(view)()
|
||||
|
||||
@octoprint.plugin.BlueprintPlugin.route("/check", methods=["GET"])
|
||||
@no_firstrun_access
|
||||
@Permissions.PLUGIN_SOFTWAREUPDATE_CHECK.require(403)
|
||||
def check_for_update(self):
|
||||
if (
|
||||
not Permissions.PLUGIN_SOFTWAREUPDATE_CHECK.can()
|
||||
@@ -1428,7 +1447,11 @@ class SoftwareUpdatePlugin(
|
||||
|
||||
def _is_wizard_update_required(self):
|
||||
firstrun = self._settings.global_get(["server", "firstRun"])
|
||||
return firstrun and self._is_octoprint_outdated_and_can_update()
|
||||
return (
|
||||
firstrun
|
||||
and self._is_octoprint_outdated_and_can_update()
|
||||
and not self._is_settings_wizard_required()
|
||||
)
|
||||
|
||||
def _is_settings_wizard_required(self):
|
||||
checks = self._get_configured_checks()
|
||||
@@ -1442,6 +1465,14 @@ class SoftwareUpdatePlugin(
|
||||
def get_wizard_version(self):
|
||||
return 1
|
||||
|
||||
def get_wizard_details(self):
|
||||
result = {}
|
||||
if self._is_wizard_update_required():
|
||||
information, _, _ = self.get_current_versions()
|
||||
data = information.get("octoprint", {})
|
||||
result["update"] = data
|
||||
return result
|
||||
|
||||
##~~ EventHandlerPlugin API
|
||||
|
||||
def on_event(self, event, payload):
|
||||
@@ -1501,6 +1532,9 @@ class SoftwareUpdatePlugin(
|
||||
if not check:
|
||||
continue
|
||||
|
||||
if "type" not in check:
|
||||
continue
|
||||
|
||||
try:
|
||||
populated_check = self._populated_check(target, check)
|
||||
future = executor.submit(
|
||||
@@ -1881,15 +1915,7 @@ class SoftwareUpdatePlugin(
|
||||
if target_result is not None:
|
||||
target_results[target] = target_result
|
||||
|
||||
if "restart" in check:
|
||||
target_restart_type = check["restart"]
|
||||
elif (
|
||||
"pip" in check
|
||||
or check.get("method") in self.OCTOPRINT_RESTART_TYPES
|
||||
):
|
||||
target_restart_type = "octoprint"
|
||||
else:
|
||||
target_restart_type = None
|
||||
target_restart_type = self._get_restart_type(check)
|
||||
|
||||
# if our update requires a restart we have to determine which type
|
||||
if restart_type is None or (
|
||||
@@ -1920,16 +1946,7 @@ class SoftwareUpdatePlugin(
|
||||
# one of our updates requires a restart of either type "octoprint" or "environment". Let's see if
|
||||
# we can actually perform that
|
||||
|
||||
restart_command = None
|
||||
if restart_type == "octoprint":
|
||||
restart_command = self._settings.global_get(
|
||||
["server", "commands", "serverRestartCommand"]
|
||||
)
|
||||
elif restart_type == "environment":
|
||||
restart_command = self._settings.global_get(
|
||||
["server", "commands", "systemRestartCommand"]
|
||||
)
|
||||
|
||||
restart_command = self._get_restart_command(restart_type)
|
||||
if restart_command:
|
||||
self._send_client_message(
|
||||
"restarting",
|
||||
@@ -2166,12 +2183,6 @@ class SoftwareUpdatePlugin(
|
||||
result = dict(check)
|
||||
|
||||
if target == "octoprint":
|
||||
|
||||
from octoprint.util.version import (
|
||||
is_released_octoprint_version,
|
||||
is_stable_octoprint_version,
|
||||
)
|
||||
|
||||
displayName = check.get("displayName")
|
||||
if displayName is None:
|
||||
# displayName missing or set to None
|
||||
@@ -2184,13 +2195,6 @@ class SoftwareUpdatePlugin(
|
||||
displayVersion = "{octoprint_version}"
|
||||
result["displayVersion"] = to_unicode(displayVersion, errors="replace")
|
||||
|
||||
stable_branch = "master"
|
||||
release_branches = []
|
||||
if "stable_branch" in check:
|
||||
release_branches.append(check["stable_branch"]["branch"])
|
||||
stable_branch = check["stable_branch"]["branch"]
|
||||
if "prerelease_branches" in check:
|
||||
release_branches += [x["branch"] for x in check["prerelease_branches"]]
|
||||
result["released_version"] = is_released_octoprint_version()
|
||||
|
||||
if check["type"] in self.COMMIT_TRACKING_TYPES:
|
||||
@@ -2198,39 +2202,6 @@ class SoftwareUpdatePlugin(
|
||||
else:
|
||||
result["current"] = VERSION
|
||||
|
||||
if check["type"] == "github_release" and (
|
||||
check.get("prerelease", None) or not is_stable_octoprint_version()
|
||||
):
|
||||
# we are tracking github releases and are either also tracking prerelease OR are currently running
|
||||
# a non stable version => we need to change some parameters
|
||||
|
||||
# we compare versions fully, not just the base so that we see a difference
|
||||
# between RCs + stable for the same version release
|
||||
result["force_base"] = False
|
||||
|
||||
if check.get("prerelease", None):
|
||||
# we are tracking prereleases => we want to be on the correct prerelease channel/branch
|
||||
channel = check.get("prerelease_channel", None)
|
||||
if channel:
|
||||
# if we have a release channel, we also set our update_branch here to our release channel
|
||||
# in case it's not already set
|
||||
result["update_branch"] = check.get("update_branch", channel)
|
||||
|
||||
else:
|
||||
# we are not tracking prereleases, but aren't on the stable branch either => switch back
|
||||
# to stable branch on update
|
||||
result["update_branch"] = check.get(
|
||||
"update_branch", stable_branch
|
||||
)
|
||||
|
||||
if check.get("update_script", None):
|
||||
# we force an exact version & python unequality check, to be able to downgrade
|
||||
result["force_exact_version"] = True
|
||||
result["release_compare"] = "python_unequal"
|
||||
elif check.get("pip", None):
|
||||
# we force python unequality check for pip installs, to be able to downgrade
|
||||
result["release_compare"] = "python_unequal"
|
||||
|
||||
elif target == "pip":
|
||||
import pkg_resources
|
||||
|
||||
@@ -2273,6 +2244,43 @@ class SoftwareUpdatePlugin(
|
||||
"current", check.get("displayVersion", None)
|
||||
)
|
||||
|
||||
if (
|
||||
check["type"] in self.RELEASE_TRACKING_TYPES
|
||||
and result["current"]
|
||||
and (check.get("prerelease", None) or not is_stable(result["current"]))
|
||||
):
|
||||
# we are tracking releases and are either also tracking prerelease OR are currently running
|
||||
# a non stable version => we need to change some parameters
|
||||
|
||||
# we compare versions fully, not just the base so that we see a difference
|
||||
# between RCs + stable for the same version release
|
||||
result["force_base"] = False
|
||||
|
||||
if check["type"] == "github_release":
|
||||
if check.get("prerelease", None):
|
||||
# we are tracking prereleases => we want to be on the correct prerelease channel/branch
|
||||
channel = check.get("prerelease_channel", None)
|
||||
if channel:
|
||||
# if we have a release channel, we also set our update_branch here to our release channel
|
||||
# in case it's not already set
|
||||
result["update_branch"] = check.get("update_branch", channel)
|
||||
|
||||
else:
|
||||
# we are not tracking prereleases, but aren't on the stable branch either => switch back
|
||||
# to stable branch on update
|
||||
result["update_branch"] = check.get(
|
||||
"update_branch",
|
||||
check.get("stable_branch", {"branch": "main"})["branch"],
|
||||
)
|
||||
|
||||
if check.get("update_script", None):
|
||||
# we force an exact version & python unequality check, to be able to downgrade
|
||||
result["force_exact_version"] = True
|
||||
result["release_compare"] = "python_unequal"
|
||||
elif check.get("pip", None):
|
||||
# we force python unequality check for pip installs, to be able to downgrade
|
||||
result["release_compare"] = "python_unequal"
|
||||
|
||||
if result.get("pip", None):
|
||||
if "pip_command" not in result:
|
||||
local_pip_command = self._settings.global_get(
|
||||
@@ -2397,7 +2405,7 @@ def _register_custom_events(*args, **kwargs):
|
||||
|
||||
__plugin_name__ = "Software Update"
|
||||
__plugin_author__ = "Gina Häußge"
|
||||
__plugin_url__ = "http://docs.octoprint.org/en/master/bundledplugins/softwareupdate.html"
|
||||
__plugin_url__ = "https://docs.octoprint.org/en/master/bundledplugins/softwareupdate.html"
|
||||
__plugin_description__ = "Allows receiving update notifications and performing updates of OctoPrint and plugins"
|
||||
__plugin_disabling_discouraged__ = gettext(
|
||||
"Without this plugin OctoPrint will no longer be able to "
|
||||
|
||||
@@ -82,6 +82,10 @@ $(function () {
|
||||
});
|
||||
|
||||
self.enableUpdateAll = ko.pureComputed(function () {
|
||||
return self.enableUpdate() && self.availableAndPossible().length > 0;
|
||||
});
|
||||
|
||||
self.enableUpdateEnabled = ko.pureComputed(function () {
|
||||
return (
|
||||
self.enableUpdate() && self.availableAndPossibleAndEnabled().length > 0
|
||||
);
|
||||
@@ -306,74 +310,90 @@ $(function () {
|
||||
);
|
||||
};
|
||||
|
||||
self._enrichInformation = function (key, information) {
|
||||
information["key"] = key;
|
||||
|
||||
if (
|
||||
!information.hasOwnProperty("displayName") ||
|
||||
information.displayName === ""
|
||||
) {
|
||||
information.displayName = information.key;
|
||||
}
|
||||
if (
|
||||
!information.hasOwnProperty("displayVersion") ||
|
||||
information.displayVersion === ""
|
||||
) {
|
||||
information.displayVersion = information.information.local.name;
|
||||
}
|
||||
if (
|
||||
!information.hasOwnProperty("releaseNotes") ||
|
||||
information.releaseNotes === ""
|
||||
) {
|
||||
information.releaseNotes = undefined;
|
||||
}
|
||||
|
||||
var fullNameTemplate = gettext("%(name)s: %(version)s");
|
||||
information.fullNameLocal = _.sprintf(fullNameTemplate, {
|
||||
name: _.escape(information.displayName),
|
||||
version: _.escape(information.displayVersion)
|
||||
});
|
||||
|
||||
var fullNameRemoteVars = {
|
||||
name: _.escape(information.displayName),
|
||||
version: gettext("unknown")
|
||||
};
|
||||
if (
|
||||
information.hasOwnProperty("information") &&
|
||||
information.information.hasOwnProperty("remote") &&
|
||||
information.information.remote.hasOwnProperty("name")
|
||||
) {
|
||||
fullNameRemoteVars.version = _.escape(
|
||||
information.information.remote.name
|
||||
);
|
||||
}
|
||||
information.fullNameRemote = _.sprintf(fullNameTemplate, fullNameRemoteVars);
|
||||
|
||||
if (information.releaseChannels && information.releaseChannels.current) {
|
||||
information.releaseChannels.current = ko.observable(
|
||||
information.releaseChannels.current
|
||||
);
|
||||
information.releaseChannels.current.subscribe(function (selected) {
|
||||
var patch = {};
|
||||
patch[key] = {channel: selected};
|
||||
OctoPrint.plugins.softwareupdate.configure(patch).done(function () {
|
||||
self.performCheck(false, false, false, [key]);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
information.toggleDisabled = function () {
|
||||
var patch = {};
|
||||
patch[key] = {disabled: !information.disabled};
|
||||
OctoPrint.plugins.softwareupdate.configure(patch).done(function () {
|
||||
self.performCheck(false, false, false, [key]);
|
||||
});
|
||||
};
|
||||
|
||||
information.notificationIconTitle = function () {
|
||||
var update = information.updateAvailable
|
||||
? gettext("Update available")
|
||||
: gettext("Up-to-date");
|
||||
var notifications = information.disabled
|
||||
? gettext("notifications are muted")
|
||||
: gettext("notifications are enabled");
|
||||
|
||||
return update + " (" + notifications + ")";
|
||||
};
|
||||
|
||||
return information;
|
||||
};
|
||||
|
||||
self.fromCheckResponse = function (data, ignoreSeen, showIfNothingNew) {
|
||||
self.cacheTimestamp(data.timestamp);
|
||||
|
||||
var versions = [];
|
||||
_.each(data.information, function (value, key) {
|
||||
value["key"] = key;
|
||||
|
||||
if (!value.hasOwnProperty("displayName") || value.displayName === "") {
|
||||
value.displayName = value.key;
|
||||
}
|
||||
if (
|
||||
!value.hasOwnProperty("displayVersion") ||
|
||||
value.displayVersion === ""
|
||||
) {
|
||||
value.displayVersion = value.information.local.name;
|
||||
}
|
||||
if (!value.hasOwnProperty("releaseNotes") || value.releaseNotes === "") {
|
||||
value.releaseNotes = undefined;
|
||||
}
|
||||
|
||||
var fullNameTemplate = gettext("%(name)s: %(version)s");
|
||||
value.fullNameLocal = _.sprintf(fullNameTemplate, {
|
||||
name: _.escape(value.displayName),
|
||||
version: _.escape(value.displayVersion)
|
||||
});
|
||||
|
||||
var fullNameRemoteVars = {
|
||||
name: _.escape(value.displayName),
|
||||
version: gettext("unknown")
|
||||
};
|
||||
if (
|
||||
value.hasOwnProperty("information") &&
|
||||
value.information.hasOwnProperty("remote") &&
|
||||
value.information.remote.hasOwnProperty("name")
|
||||
) {
|
||||
fullNameRemoteVars.version = _.escape(value.information.remote.name);
|
||||
}
|
||||
value.fullNameRemote = _.sprintf(fullNameTemplate, fullNameRemoteVars);
|
||||
|
||||
if (value.releaseChannels && value.releaseChannels.current) {
|
||||
value.releaseChannels.current = ko.observable(
|
||||
value.releaseChannels.current
|
||||
);
|
||||
value.releaseChannels.current.subscribe(function (selected) {
|
||||
var patch = {};
|
||||
patch[key] = {channel: selected};
|
||||
OctoPrint.plugins.softwareupdate
|
||||
.configure(patch)
|
||||
.done(function () {
|
||||
self.performCheck(false, false, false, [key]);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
value.toggleDisabled = function () {
|
||||
var patch = {};
|
||||
patch[key] = {disabled: !value.disabled};
|
||||
OctoPrint.plugins.softwareupdate.configure(patch).done(function () {
|
||||
self.performCheck(false, false, false, [key]);
|
||||
});
|
||||
};
|
||||
|
||||
if (key === "octoprint") {
|
||||
self.octoprintData.item = value;
|
||||
self.octoprintData.current(value.information.local.name);
|
||||
self.octoprintData.available(value.information.remote.name);
|
||||
}
|
||||
|
||||
self._enrichInformation(key, value);
|
||||
versions.push(value);
|
||||
});
|
||||
self.versions.updateItems(versions);
|
||||
@@ -683,14 +703,7 @@ $(function () {
|
||||
};
|
||||
|
||||
self.performUpdate = function (force, items) {
|
||||
if (
|
||||
!(
|
||||
self.loginState.hasPermission(
|
||||
self.access.permissions.PLUGIN_SOFTWAREUPDATE_UPDATE
|
||||
) || CONFIG_FIRST_RUN
|
||||
)
|
||||
)
|
||||
return;
|
||||
if (!self.updateAccess()) return;
|
||||
if (self.printerState.isPrinting()) return;
|
||||
|
||||
self.updateInProgress = true;
|
||||
@@ -747,15 +760,16 @@ $(function () {
|
||||
return self.update(force, self.availableAndPossibleAndEnabled());
|
||||
};
|
||||
|
||||
self.updateAccess = function () {
|
||||
return (
|
||||
self.loginState.hasPermission(
|
||||
self.access.permissions.PLUGIN_SOFTWAREUPDATE_UPDATE
|
||||
) || CONFIG_FIRST_RUN
|
||||
);
|
||||
};
|
||||
|
||||
self.update = function (force, items) {
|
||||
if (
|
||||
self.updateInProgress ||
|
||||
!(
|
||||
self.loginState.hasPermission(
|
||||
self.access.permissions.PLUGIN_SOFTWAREUPDATE_UPDATE
|
||||
) || CONFIG_FIRST_RUN
|
||||
)
|
||||
) {
|
||||
if (self.updateInProgress || !self.updateAccess()) {
|
||||
self._updateClicked = false;
|
||||
return;
|
||||
}
|
||||
@@ -851,8 +865,10 @@ $(function () {
|
||||
|
||||
self._showWorkingDialog = function (title) {
|
||||
if (
|
||||
!self.loginState.hasPermission(
|
||||
self.access.permissions.PLUGIN_SOFTWAREUPDATE_CHECK
|
||||
!(
|
||||
self.loginState.hasPermission(
|
||||
self.access.permissions.PLUGIN_SOFTWAREUPDATE_CHECK
|
||||
) || CONFIG_FIRST_RUN
|
||||
)
|
||||
) {
|
||||
return;
|
||||
@@ -929,6 +945,21 @@ $(function () {
|
||||
self.performCheck();
|
||||
};
|
||||
|
||||
self.onWizardDetails = function (data) {
|
||||
if (
|
||||
data.softwareupdate &&
|
||||
data.softwareupdate.details &&
|
||||
data.softwareupdate.details.update
|
||||
) {
|
||||
var value = data.softwareupdate.details.update;
|
||||
self._enrichInformation("octoprint", value);
|
||||
|
||||
self.octoprintData.item = value;
|
||||
self.octoprintData.current(value.information.local.name);
|
||||
self.octoprintData.available(value.information.remote.name);
|
||||
}
|
||||
};
|
||||
|
||||
self.onDataUpdaterReconnect = function () {
|
||||
if (self.waitingForRestart) {
|
||||
self.waitingForRestart = false;
|
||||
|
||||
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
@@ -12,7 +12,7 @@
|
||||
If you have a local OctoPrint checkout folder switched to another branch,
|
||||
<strong>simply switching over to "Commit" tracking</strong> will already
|
||||
take care of that. Otherwise please take a look at the
|
||||
<a href="http://docs.octoprint.org/en/master/bundledplugins/softwareupdate.html" target="_blank">Documentation</a>.
|
||||
<a href="https://docs.octoprint.org/en/master/bundledplugins/softwareupdate.html" target="_blank">Documentation</a>.
|
||||
</p>
|
||||
{% endtrans %}</div>
|
||||
<div class="alert" data-bind="visible: !environmentSupported()">{% trans %}
|
||||
@@ -85,28 +85,31 @@
|
||||
<div class="tab-content">
|
||||
<div class="tab-pane active" id="settings_plugin_softwareupdate_updates">
|
||||
<div class="pull-right">
|
||||
<button class="btn btn-primary" data-bind="click: function() { $root.updateAll(); }, enable: enableUpdateAll, css: {disabled: !enableUpdateAll}"><i class="fas fa-spinner fa-spin" data-bind="visible: updateInProgress"></i> {{ _('Update all') }}</button>
|
||||
<button class="btn" data-bind="click: function() { $root.performCheck(true, false, true); }, enable: !checking(), css: {disabled: checking()}"><i class="fas fa-spinner fa-spin" data-bind="visible: checking"></i> {{ _('Check for updates') }}</button>
|
||||
<div class="btn-group">
|
||||
<button class="btn btn-primary" data-bind="click: function() { $root.updateEnabled(); }, enable: enableUpdateEnabled, css: {disabled: !enableUpdateEnabled}" title="{{ _('Update all enabled') | edq }}"><i class="fas fa-spinner fa-spin" data-bind="visible: updateInProgress"></i> {{ _('Update all') }}</button>
|
||||
<button class="btn btn-primary dropdown-toggle" data-toggle="dropdown"><span class="caret"></span></button>
|
||||
<ul class="dropdown-menu">
|
||||
<li><a href="javascript:void(0)" data-bind="click: function() { $root.updateAll(); }, enable: enableUpdateAll, css: {disabled: !enableUpdateAll}" title="{{ _('Update all muted & enabled') | edq }}">{{ _('Update all available') }}</a></li>
|
||||
</ul>
|
||||
</div>
|
||||
<div class="btn-group">
|
||||
<button class="btn" data-bind="click: function() { $root.performCheck(true, false, true); }, enable: !checking(), css: {disabled: checking()}"><i class="fas fa-spinner fa-spin" data-bind="visible: checking"></i> {{ _('Check for updates') }}</button>
|
||||
<button class="btn dropdown-toggle" data-toggle="dropdown"><span class="caret"></span></button>
|
||||
<ul class="dropdown-menu">
|
||||
<li><a href="javascript:void(0)" data-bind="click: function() { $root.performCheck(true, true, true); }, enable: !checking(), css: {disabled: checking()}">{{ _('Force check for updates') }}</a></li>
|
||||
</ul>
|
||||
</div>
|
||||
<button class="btn" data-bind="click: function() { $root.showPluginSettings(); }" title="{{ _('Plugin Configuration')|edq }}"><i class="fas fa-wrench"></i></button>
|
||||
</div>
|
||||
|
||||
<h3>{{ _('Current versions') }}</h3>
|
||||
|
||||
<div class="swupdate-advanced">
|
||||
<div><small><a href="javascript:void(0)" class="muted" onclick="$(this).children().toggleClass('fa-caret-right fa-caret-down').parent().parent().parent().next().slideToggle('fast')"><i class="fas fa-caret-right"></i> {{ _('Advanced options') }}</a></small></div>
|
||||
<div class="hide">
|
||||
<small class="muted" style="display: block">{{ _('Last cache refresh:') }} <span data-bind="text: cacheTimestampText"></span></small>
|
||||
<button class="btn btn-block" data-bind="click: function() { $root.performCheck(true, true, true); }, enable: !checking(), css: {disabled: checking()}"><i class="fas fa-spinner fa-spin" data-bind="visible: checking"></i> {{ _('Force check for update (overrides cache used for update checks)') }}</button>
|
||||
<button class="btn btn-block btn-danger" data-bind="visible: CONFIG_DEBUG, click: function() { $root.updateAll(true); }, enable: enableUpdate() && !checking(), css: {disabled: !enableUpdate() || checking()}"><i class="fas fa-spinner fa-spin" data-bind="visible: checking"></i> {{ _('Force update all (even if no new versions are available)') }}</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div id="settings_plugin_softwareupdate_updatelist">
|
||||
<table class="table table-striped table-hover table-condensed table-hover">
|
||||
<tbody data-bind="foreach: versions.paginatedItems">
|
||||
<tr data-bind="attr: {title: displayName}">
|
||||
<tr>
|
||||
<td class="settings_plugin_softwareupdate_column_update">
|
||||
<a href="javascript:void(0)" data-bind="visible: compatible, click: toggleDisabled"><i class="far" data-bind="css: { muted: !updateAvailable, 'fa-bell': !disabled, 'fa-bell-slash': disabled }" title="{{ _('Update available')|edq }}"></i></a>
|
||||
<a href="javascript:void(0)" data-bind="visible: compatible, click: toggleDisabled"><i class="far" data-bind="css: { muted: !updateAvailable, 'fa-bell': !disabled, 'fa-bell-slash': disabled }, attr: { title: notificationIconTitle() }"></i></a>
|
||||
<span data-bind="visible: !compatible" class="muted"><i class="fas fa-power-off" title="{{ _('Not compatible') }}|edq"></i></span>
|
||||
</td>
|
||||
<td class="settings_plugin_softwareupdate_column_information">
|
||||
@@ -126,9 +129,20 @@
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
<small class="muted">
|
||||
<i class="far fa-bell"></i> = {{ _('Update notifications enabled') }},
|
||||
<i class="far fa-bell-slash"></i> = {{ _('Update notifications muted') }},
|
||||
{{ _('click to toggle') }}.
|
||||
{% trans %}
|
||||
"Update all" will update all items for which updates are availalbe &
|
||||
update notifications are enabled as well, "Update all available" will
|
||||
update all items for which updates are available regardless of update
|
||||
notifications being enabled or muted.
|
||||
{% endtrans %}
|
||||
</small>
|
||||
</div>
|
||||
</div>
|
||||
<div class="tab-pane active" id="settings_plugin_softwareupdate_updatelog">
|
||||
<div class="tab-pane" id="settings_plugin_softwareupdate_updatelog">
|
||||
<h3>{{ _('Update log') }}</h3>
|
||||
|
||||
<div id="settings_plugin_softwareupdate_updatelog_list">
|
||||
@@ -158,11 +172,11 @@
|
||||
</div>
|
||||
<div class="modal-body">
|
||||
<form class="form-horizontal" onsubmit="return false;">
|
||||
{% include "snippets/plugins/softwareupdate/versionTracking.jinja2" %}
|
||||
{% include "snippets/plugins/softwareupdate/trackedBranch.jinja2" %}
|
||||
{% include "snippets/plugins/softwareupdate/checkoutFolder.jinja2" %}
|
||||
{% include "snippets/plugins/softwareupdate/pipTarget.jinja2" %}
|
||||
{% include "snippets/plugins/softwareupdate/pipEnableCheck.jinja2" %}
|
||||
{% include "snippets/versionTracking.jinja2" %}
|
||||
{% include "snippets/trackedBranch.jinja2" %}
|
||||
{% include "snippets/checkoutFolder.jinja2" %}
|
||||
{% include "snippets/pipTarget.jinja2" %}
|
||||
{% include "snippets/pipEnableCheck.jinja2" %}
|
||||
<div class="control-group">
|
||||
<label class="control-label">{{ _('Version cache TTL') }}</label>
|
||||
<div class="controls">
|
||||
@@ -203,9 +217,9 @@
|
||||
<h3 data-bind="text: workingTitle"></h3>
|
||||
</div>
|
||||
<div class="modal-body">
|
||||
<pre id="settings_plugin_softwareupdate_workingdialog_output" class="pre-scrollable pre-output" style="height: 170px; display: none" data-bind="visible: loginState.isAdmin, foreach: loglines"><span data-bind="text: line, css: {stdout: stream == 'stdout', stderr: stream == 'stderr', call: stream == 'call', message: stream == 'message'}"></span></pre>
|
||||
<p style="display: none" data-bind="visible: !loginState.isAdmin() && $root.working()"><i class="fas fa-spinner fa-spin"></i> {{ _('Update in progress, please wait.') }}</p>
|
||||
<p style="display: none" data-bind="visible: !loginState.isAdmin() && !$root.working()">{{ _('Update done, please close this window.') }}</p>
|
||||
<pre id="settings_plugin_softwareupdate_workingdialog_output" class="pre-scrollable pre-output" style="height: 170px; display: none" data-bind="visible: $root.updateAccess(), foreach: loglines"><span data-bind="text: line, css: {stdout: stream == 'stdout', stderr: stream == 'stderr', call: stream == 'call', message: stream == 'message'}"></span></pre>
|
||||
<p style="display: none" data-bind="visible: !$root.updateAccess() && $root.working()"><i class="fas fa-spinner fa-spin"></i> {{ _('Update in progress, please wait.') }}</p>
|
||||
<p style="display: none" data-bind="visible: !$root.updateAccess() && !$root.working()">{{ _('Update done, please close this window.') }}</p>
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<button class="btn" data-dismiss="modal" data-bind="enable: !$root.working()" aria-hidden="true">{{ _('Close') }}</button>
|
||||
|
||||
+3
-3
@@ -7,9 +7,9 @@
|
||||
</p>{% endtrans %}
|
||||
|
||||
<form class="form-horizontal" onsubmit="return false;">
|
||||
{% include "snippets/plugins/softwareupdate/versionTracking.jinja2" %}
|
||||
{% include "snippets/plugins/softwareupdate/checkoutFolder.jinja2" %}
|
||||
{% include "snippets/plugins/softwareupdate/trackedBranch.jinja2" %}
|
||||
{% include "snippets/versionTracking.jinja2" %}
|
||||
{% include "snippets/checkoutFolder.jinja2" %}
|
||||
{% include "snippets/trackedBranch.jinja2" %}
|
||||
</form>
|
||||
|
||||
{% trans %}<p>
|
||||
|
||||
File renamed without changes.
File renamed without changes.
@@ -1,6 +1,6 @@
|
||||
<h3>{{ _('Anonymous Usage Tracking') }}</h3>
|
||||
|
||||
{% include "snippets/plugins/tracking/trackingDescription.jinja2" %}
|
||||
{% include "snippets/trackingDescription.jinja2" %}
|
||||
|
||||
<form class="form-horizontal" onsubmit="return false;">
|
||||
<div class="control-group">
|
||||
@@ -59,4 +59,4 @@
|
||||
</div>
|
||||
</form>
|
||||
|
||||
{% include "snippets/plugins/tracking/trackingDetails.jinja2" %}
|
||||
{% include "snippets/trackingDetails.jinja2" %}
|
||||
@@ -1,8 +1,8 @@
|
||||
<h3>{{ _('Configure Anonymous Usage Tracking') }}</h3>
|
||||
|
||||
{% include "snippets/plugins/tracking/trackingDescription.jinja2" %}
|
||||
{% include "snippets/trackingDescription.jinja2" %}
|
||||
|
||||
{% include "snippets/plugins/tracking/trackingDetails.jinja2" %}
|
||||
{% include "snippets/trackingDetails.jinja2" %}
|
||||
|
||||
<p>
|
||||
{{ _('<strong>Note:</strong> You can always change your decision and also access more granular controls via Settings > Anonymous Usage Tracking.') }}
|
||||
|
||||
@@ -111,6 +111,8 @@ class VirtualPrinterPlugin(
|
||||
"enable_eeprom": True,
|
||||
"support_M503": True,
|
||||
"resend_ratio": 0,
|
||||
"locked": False,
|
||||
"passcode": "1234",
|
||||
}
|
||||
|
||||
def get_settings_version(self):
|
||||
|
||||
@@ -165,6 +165,8 @@ class VirtualPrinter:
|
||||
|
||||
self._capabilities = self._settings.get(["capabilities"], merged=True)
|
||||
|
||||
self._locked = self._settings.get_boolean(["locked"])
|
||||
|
||||
self._temperature_reporter = None
|
||||
self._sdstatus_reporter = None
|
||||
self._pos_reporter = None
|
||||
@@ -185,6 +187,7 @@ class VirtualPrinter:
|
||||
self._calculate_resend_every_n(self._settings.get_int(["resend_ratio"]))
|
||||
|
||||
self._dont_answer = False
|
||||
self._broken_klipper_connection = False
|
||||
|
||||
self._debug_drop_connection = False
|
||||
|
||||
@@ -274,6 +277,7 @@ class VirtualPrinter:
|
||||
self._sleepAfter.clear()
|
||||
|
||||
self._dont_answer = False
|
||||
self._broken_klipper_connection = False
|
||||
|
||||
self._debug_drop_connection = False
|
||||
|
||||
@@ -299,6 +303,8 @@ class VirtualPrinter:
|
||||
for item in self._settings.get(["resetLines"]):
|
||||
self._send(item + "\n")
|
||||
|
||||
self._locked = self._settings.get_boolean(["locked"])
|
||||
|
||||
@property
|
||||
def timeout(self):
|
||||
return self._read_timeout
|
||||
@@ -493,9 +499,19 @@ class VirtualPrinter:
|
||||
# actual command handling
|
||||
command_match = VirtualPrinter.command_regex.match(data)
|
||||
if command_match is not None:
|
||||
if self._broken_klipper_connection:
|
||||
self._send("!! Lost communication with MCU 'mcu'")
|
||||
self._sendOk()
|
||||
continue
|
||||
|
||||
command = command_match.group(0)
|
||||
letter = command_match.group(1)
|
||||
|
||||
if self._locked and command != "M511":
|
||||
self._send("echo:Printer locked! (Unlock with M511 or LCD)")
|
||||
self._sendOk()
|
||||
continue
|
||||
|
||||
try:
|
||||
# if we have a method _gcode_G, _gcode_M or _gcode_T, execute that first
|
||||
letter_handler = f"_gcode_{letter}"
|
||||
@@ -845,6 +861,22 @@ class VirtualPrinter:
|
||||
else:
|
||||
time.sleep(timeout)
|
||||
|
||||
# Passcode Feature - lock with M510, unlock with M511 P<passcode>.
|
||||
# https://marlinfw.org/docs/gcode/M510.html / https://marlinfw.org/docs/gcode/M511.html
|
||||
|
||||
def _gcode_M510(self, data):
|
||||
self._locked = True
|
||||
|
||||
def _gcode_M511(self, data):
|
||||
if self._locked:
|
||||
matchP = re.search(r"P([0-9]+)", data)
|
||||
if matchP:
|
||||
passcode = matchP.group(1)
|
||||
if passcode == self._settings.get(["passcode"]):
|
||||
self._locked = False
|
||||
else:
|
||||
self._send("Incorrect passcode")
|
||||
|
||||
# EEPROM management commands
|
||||
|
||||
def _gcode_M500(self, data):
|
||||
@@ -1212,6 +1244,9 @@ class VirtualPrinter:
|
||||
resend_ratio <int:percentage>
|
||||
| Sets the resend ratio to the given percentage, simulating noisy lines.
|
||||
| Set to 0 to disable noise simulation.
|
||||
toggle_klipper_connection
|
||||
| Toggles the Klipper connection state. If disabled, the printer will
|
||||
| respond to all commands with "!! Lost communication with MCU 'mcu'"
|
||||
|
||||
# Reply Timing / Sleeping
|
||||
|
||||
@@ -1251,6 +1286,8 @@ class VirtualPrinter:
|
||||
self._send("// action:disconnect")
|
||||
elif data == "dont_answer":
|
||||
self._dont_answer = True
|
||||
elif data == "toggle_klipper_connection":
|
||||
self._broken_klipper_connection = not self._broken_klipper_connection
|
||||
elif data == "trigger_resend_lineno":
|
||||
self._prepared_errors.append(
|
||||
lambda cur, last, ln: self._triggerResend(expected=last, actual=last + 1)
|
||||
@@ -1390,6 +1427,8 @@ class VirtualPrinter:
|
||||
dosname = get_dos_filename(
|
||||
entry.name, existing_filenames=list(result.keys())
|
||||
).lower()
|
||||
if entry.name.startswith("."):
|
||||
dosname = "." + dosname
|
||||
result[dosname] = {
|
||||
"name": entry.name,
|
||||
"path": entry.path,
|
||||
|
||||
@@ -150,7 +150,13 @@ import os
|
||||
from os import scandir
|
||||
|
||||
from octoprint.settings import settings
|
||||
from octoprint.util import dict_contains_keys, dict_merge, dict_sanitize, is_hidden_path
|
||||
from octoprint.util import (
|
||||
dict_contains_keys,
|
||||
dict_merge,
|
||||
dict_sanitize,
|
||||
is_hidden_path,
|
||||
yaml,
|
||||
)
|
||||
|
||||
|
||||
class SaveError(Exception):
|
||||
@@ -500,10 +506,7 @@ class PrinterProfileManager:
|
||||
if not os.path.exists(path) or not os.path.isfile(path):
|
||||
return None
|
||||
|
||||
import yaml
|
||||
|
||||
with open(path, encoding="utf-8") as f:
|
||||
profile = yaml.safe_load(f)
|
||||
profile = yaml.load_from_file(path=path)
|
||||
|
||||
if profile is None or not isinstance(profile, dict):
|
||||
raise InvalidProfileError("Profile is None or not a dictionary")
|
||||
@@ -535,15 +538,11 @@ class PrinterProfileManager:
|
||||
"Profile %s already exists and not allowed to overwrite" % profile["id"]
|
||||
)
|
||||
|
||||
import yaml
|
||||
|
||||
from octoprint.util import atomic_write
|
||||
|
||||
try:
|
||||
with atomic_write(path, mode="wt", max_permissions=0o666) as f:
|
||||
yaml.safe_dump(
|
||||
profile, f, default_flow_style=False, indent=2, allow_unicode=True
|
||||
)
|
||||
yaml.save_to_file(profile, file=f, pretty=True)
|
||||
except Exception as e:
|
||||
self._logger.exception(
|
||||
"Error while trying to save profile %s" % profile["id"]
|
||||
|
||||
@@ -14,7 +14,7 @@ import threading
|
||||
import time
|
||||
from collections import namedtuple
|
||||
|
||||
from immutabledict import immutabledict
|
||||
from frozendict import frozendict
|
||||
|
||||
import octoprint.util.json
|
||||
from octoprint import util as util
|
||||
@@ -106,7 +106,7 @@ class Printer(
|
||||
self._logger_job = logging.getLogger(f"{__name__}.job")
|
||||
|
||||
self._dict = (
|
||||
immutabledict
|
||||
frozendict
|
||||
if settings().getBoolean(["devel", "useFrozenDictForPrinterState"])
|
||||
else dict
|
||||
)
|
||||
@@ -251,7 +251,7 @@ class Printer(
|
||||
|
||||
@property
|
||||
def firmware_info(self):
|
||||
return immutabledict(self._firmware_info) if self._firmware_info else None
|
||||
return frozendict(self._firmware_info) if self._firmware_info else None
|
||||
|
||||
# ~~ handling of PrinterCallbacks
|
||||
|
||||
@@ -1038,11 +1038,11 @@ class Printer(
|
||||
return self._protocol.error
|
||||
|
||||
def get_current_data(self, *args, **kwargs):
|
||||
return util.thaw_immutabledict(self._state_monitor.get_current_data())
|
||||
return util.thaw_frozendict(self._state_monitor.get_current_data())
|
||||
|
||||
def get_current_job(self):
|
||||
data = self._state_monitor.get_current_data()
|
||||
return util.thaw_immutabledict(data["job"])
|
||||
return util.thaw_frozendict(data["job"])
|
||||
|
||||
def get_current_temperatures(self, *args, **kwargs):
|
||||
if self._protocol is not None:
|
||||
@@ -1444,6 +1444,8 @@ class Printer(
|
||||
original_estimate,
|
||||
original_estimate_type,
|
||||
)
|
||||
if print_time_left is not None:
|
||||
print_time_left = int(print_time_left)
|
||||
except Exception:
|
||||
self._logger.exception(
|
||||
"Error while estimating print time via {}".format(
|
||||
|
||||
@@ -4,6 +4,7 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms
|
||||
|
||||
import atexit
|
||||
import base64
|
||||
import functools
|
||||
import logging
|
||||
import logging.config
|
||||
import mimetypes
|
||||
@@ -11,6 +12,7 @@ import os
|
||||
import re
|
||||
import signal
|
||||
import sys
|
||||
import time
|
||||
import uuid # noqa: F401
|
||||
from collections import OrderedDict, defaultdict
|
||||
|
||||
@@ -256,8 +258,6 @@ class Server:
|
||||
|
||||
self._lifecycle_callbacks = defaultdict(list)
|
||||
|
||||
self._template_searchpaths = []
|
||||
|
||||
self._intermediary_server = None
|
||||
|
||||
def run(self):
|
||||
@@ -305,6 +305,9 @@ class Server:
|
||||
debug = self._debug
|
||||
safe_mode = self._safe_mode
|
||||
|
||||
if safe_mode:
|
||||
self._log_safe_mode_start(safe_mode)
|
||||
|
||||
if self._v6_only and not octoprint.util.net.HAS_V6:
|
||||
raise RuntimeError(
|
||||
"IPv6 only mode configured but system doesn't support IPv6"
|
||||
@@ -339,6 +342,7 @@ class Server:
|
||||
# monkey patch/fix some stuff
|
||||
util.tornado.fix_json_encode()
|
||||
util.tornado.fix_websocket_check_origin()
|
||||
util.tornado.enable_per_message_deflate_extension()
|
||||
util.flask.fix_flask_jsonify()
|
||||
|
||||
cli_key = self._setup_cli_key()
|
||||
@@ -1266,6 +1270,16 @@ class Server:
|
||||
)
|
||||
self._logger.exception("Stacktrace follows:")
|
||||
|
||||
def _log_safe_mode_start(self, self_mode):
|
||||
self_mode_file = os.path.join(
|
||||
self._settings.getBaseFolder("data"), "last_safe_mode"
|
||||
)
|
||||
try:
|
||||
with open(self_mode_file, "w+", encoding="utf-8") as f:
|
||||
f.write(self_mode)
|
||||
except Exception as ex:
|
||||
self._logger.warn(f"Could not write safe mode file {self_mode_file}: {ex}")
|
||||
|
||||
def _create_socket_connection(self, session):
|
||||
global printer, fileManager, analysisQueue, userManager, eventManager, connectivityChecker
|
||||
return util.sockjs.PrinterStateConnection(
|
||||
@@ -1347,9 +1361,13 @@ class Server:
|
||||
OctoPrintFlaskResponse,
|
||||
OctoPrintJsonEncoder,
|
||||
OctoPrintSessionInterface,
|
||||
PrefixAwareJinjaEnvironment,
|
||||
ReverseProxiedEnvironment,
|
||||
)
|
||||
|
||||
# we must set this here because setting app.debug will access app.jinja_env
|
||||
app.jinja_environment = PrefixAwareJinjaEnvironment
|
||||
|
||||
app.config["TEMPLATES_AUTO_RELOAD"] = True
|
||||
app.config["JSONIFY_PRETTYPRINT_REGULAR"] = False
|
||||
|
||||
@@ -1394,6 +1412,10 @@ class Server:
|
||||
@app.before_request
|
||||
def before_request():
|
||||
g.locale = self._get_locale()
|
||||
|
||||
# used for performance measurement
|
||||
g.start_time = time.monotonic()
|
||||
|
||||
if self._debug and "perfprofile" in request.args:
|
||||
try:
|
||||
from pyinstrument import Profiler
|
||||
@@ -1417,6 +1439,11 @@ class Server:
|
||||
output_html = g.perfprofiler.output_html()
|
||||
return make_response(output_html)
|
||||
|
||||
if hasattr(g, "start_time"):
|
||||
end_time = time.monotonic()
|
||||
duration_ms = int((end_time - g.start_time) * 1000)
|
||||
response.headers.add("Server-Timing", f"app;dur={duration_ms}")
|
||||
|
||||
return response
|
||||
|
||||
from octoprint.util.jinja import MarkdownFilter
|
||||
@@ -1536,12 +1563,9 @@ class Server:
|
||||
|
||||
import octoprint.util.jinja
|
||||
|
||||
filesystem_loader = octoprint.util.jinja.FilteredFileSystemLoader(
|
||||
[], path_filter=lambda x: not octoprint.util.is_hidden_path(x)
|
||||
)
|
||||
filesystem_loader.searchpath = self._template_searchpaths
|
||||
app.jinja_env.prefix_loader = jinja2.PrefixLoader({})
|
||||
|
||||
loaders = [app.jinja_loader, filesystem_loader]
|
||||
loaders = [app.jinja_loader, app.jinja_env.prefix_loader]
|
||||
if octoprint.util.is_running_from_source():
|
||||
from markdown import markdown
|
||||
|
||||
@@ -1556,8 +1580,16 @@ class Server:
|
||||
)
|
||||
)
|
||||
|
||||
jinja_loader = jinja2.ChoiceLoader(loaders)
|
||||
app.jinja_loader = jinja_loader
|
||||
# TODO: Remove this in 2.0.0
|
||||
warning_message = "Loading plugin template '{template}' from '{filename}' without plugin prefix, this is deprecated and will soon no longer be supported."
|
||||
loaders.append(
|
||||
octoprint.util.jinja.WarningLoader(
|
||||
octoprint.util.jinja.PrefixChoiceLoader(app.jinja_env.prefix_loader),
|
||||
warning_message,
|
||||
)
|
||||
)
|
||||
|
||||
app.jinja_loader = jinja2.ChoiceLoader(loaders)
|
||||
|
||||
self._register_template_plugins()
|
||||
|
||||
@@ -1728,14 +1760,27 @@ class Server:
|
||||
)
|
||||
|
||||
def _register_additional_template_plugin(self, plugin):
|
||||
import octoprint.util.jinja
|
||||
|
||||
folder = plugin.get_template_folder()
|
||||
if folder is not None and folder not in self._template_searchpaths:
|
||||
self._template_searchpaths.append(folder)
|
||||
if (
|
||||
folder is not None
|
||||
and plugin.template_folder_key not in app.jinja_env.prefix_loader.mapping
|
||||
):
|
||||
loader = octoprint.util.jinja.FilteredFileSystemLoader(
|
||||
[plugin.get_template_folder()],
|
||||
path_filter=lambda x: not octoprint.util.is_hidden_path(x),
|
||||
)
|
||||
|
||||
app.jinja_env.prefix_loader.mapping[plugin.template_folder_key] = loader
|
||||
|
||||
def _unregister_additional_template_plugin(self, plugin):
|
||||
folder = plugin.get_template_folder()
|
||||
if folder is not None and folder in self._template_searchpaths:
|
||||
self._template_searchpaths.remove(folder)
|
||||
if (
|
||||
folder is not None
|
||||
and plugin.template_folder_key in app.jinja_env.prefix_loader.mapping
|
||||
):
|
||||
del app.jinja_env.prefix_loader.mapping[plugin.template_folder_key]
|
||||
|
||||
def _setup_blueprints(self):
|
||||
# do not remove or the index view won't be found
|
||||
@@ -1743,61 +1788,98 @@ class Server:
|
||||
from octoprint.server.api import api
|
||||
from octoprint.server.util.flask import make_api_error
|
||||
|
||||
blueprints = OrderedDict()
|
||||
blueprints["/api"] = api
|
||||
json_errors = ["/api"]
|
||||
blueprints = [api]
|
||||
api_endpoints = ["/api"]
|
||||
registrators = [
|
||||
functools.partial(app.register_blueprint, api, url_prefix="/api"),
|
||||
]
|
||||
|
||||
# also register any blueprints defined in BlueprintPlugins
|
||||
(
|
||||
blueprint_from_plugins,
|
||||
api_prefixes_from_plugins,
|
||||
blueprints_from_plugins,
|
||||
api_endpoints_from_plugins,
|
||||
registrators_from_plugins,
|
||||
) = self._prepare_blueprint_plugins()
|
||||
blueprints.update(blueprint_from_plugins)
|
||||
json_errors += api_prefixes_from_plugins
|
||||
blueprints += blueprints_from_plugins
|
||||
api_endpoints += api_endpoints_from_plugins
|
||||
registrators += registrators_from_plugins
|
||||
|
||||
# and register a blueprint for serving the static files of asset plugins which are not blueprint plugins themselves
|
||||
blueprints.update(self._prepare_asset_plugins())
|
||||
(
|
||||
blueprints_from_assets,
|
||||
registrators_from_assets,
|
||||
) = self._prepare_asset_plugins()
|
||||
blueprints += blueprints_from_assets
|
||||
registrators += registrators_from_assets
|
||||
|
||||
# make sure all before/after_request hook results are attached as well
|
||||
self._add_plugin_request_handlers_to_blueprints(*blueprints.values())
|
||||
self._add_plugin_request_handlers_to_blueprints(*blueprints)
|
||||
|
||||
# register everything with the system
|
||||
for url_prefix, blueprint in blueprints.items():
|
||||
app.register_blueprint(blueprint, url_prefix=url_prefix)
|
||||
for registrator in registrators:
|
||||
registrator()
|
||||
|
||||
@app.errorhandler(HTTPException)
|
||||
def _handle_api_error(ex):
|
||||
if any(map(lambda x: request.path.startswith(x), json_errors)):
|
||||
if any(map(lambda x: request.path.startswith(x), api_endpoints)):
|
||||
return make_api_error(ex.description, ex.code)
|
||||
else:
|
||||
return ex
|
||||
|
||||
def _prepare_blueprint_plugins(self):
|
||||
blueprints = OrderedDict()
|
||||
api_prefixes = []
|
||||
def register_plugin_blueprint(plugin, blueprint, url_prefix):
|
||||
try:
|
||||
app.register_blueprint(
|
||||
blueprint, url_prefix=url_prefix, name_prefix="plugin"
|
||||
)
|
||||
self._logger.debug(
|
||||
f"Registered API of plugin {plugin} under URL prefix {url_prefix}"
|
||||
)
|
||||
except Exception:
|
||||
self._logger.exception(
|
||||
f"Error while registering blueprint of plugin {plugin}, ignoring it",
|
||||
extra={"plugin": plugin},
|
||||
)
|
||||
|
||||
blueprints = []
|
||||
api_endpoints = []
|
||||
registrators = []
|
||||
|
||||
blueprint_plugins = octoprint.plugin.plugin_manager().get_implementations(
|
||||
octoprint.plugin.BlueprintPlugin
|
||||
)
|
||||
for plugin in blueprint_plugins:
|
||||
try:
|
||||
blueprint, prefix = self._prepare_blueprint_plugin(plugin)
|
||||
api_prefixes += map(
|
||||
lambda x: prefix + x, plugin.get_blueprint_api_prefixes()
|
||||
)
|
||||
blueprints[prefix] = blueprint
|
||||
except Exception:
|
||||
self._logger.exception(
|
||||
"Error while registering blueprint of "
|
||||
"plugin {}, ignoring it".format(plugin._identifier),
|
||||
extra={"plugin": plugin._identifier},
|
||||
)
|
||||
continue
|
||||
blueprint, prefix = self._prepare_blueprint_plugin(plugin)
|
||||
|
||||
return blueprints, api_prefixes
|
||||
blueprints.append(blueprint)
|
||||
api_endpoints += map(
|
||||
lambda x: prefix + x, plugin.get_blueprint_api_prefixes()
|
||||
)
|
||||
registrators.append(
|
||||
functools.partial(
|
||||
register_plugin_blueprint, plugin._identifier, blueprint, prefix
|
||||
)
|
||||
)
|
||||
|
||||
return blueprints, api_endpoints, registrators
|
||||
|
||||
def _prepare_asset_plugins(self):
|
||||
blueprints = OrderedDict()
|
||||
def register_asset_blueprint(plugin, blueprint, url_prefix):
|
||||
try:
|
||||
app.register_blueprint(
|
||||
blueprint, url_prefix=url_prefix, name_prefix="plugin"
|
||||
)
|
||||
self._logger.debug(
|
||||
f"Registered assets of plugin {plugin} under URL prefix {url_prefix}"
|
||||
)
|
||||
except Exception:
|
||||
self._logger.exception(
|
||||
f"Error while registering assets of plugin {plugin}, ignoring it",
|
||||
extra={"plugin": plugin},
|
||||
)
|
||||
|
||||
blueprints = []
|
||||
registrators = []
|
||||
|
||||
asset_plugins = octoprint.plugin.plugin_manager().get_implementations(
|
||||
octoprint.plugin.AssetPlugin
|
||||
@@ -1805,18 +1887,16 @@ class Server:
|
||||
for plugin in asset_plugins:
|
||||
if isinstance(plugin, octoprint.plugin.BlueprintPlugin):
|
||||
continue
|
||||
try:
|
||||
blueprint, prefix = self._prepare_asset_plugin(plugin)
|
||||
blueprints[prefix] = blueprint
|
||||
except Exception:
|
||||
self._logger.exception(
|
||||
"Error while registering assets of plugin "
|
||||
"{}, ignoring it".format(plugin._identifier),
|
||||
extra={"plugin": plugin._identifier},
|
||||
)
|
||||
continue
|
||||
blueprint, prefix = self._prepare_asset_plugin(plugin)
|
||||
|
||||
return blueprints
|
||||
blueprints.append(blueprint)
|
||||
registrators.append(
|
||||
functools.partial(
|
||||
register_asset_blueprint, plugin._identifier, blueprint, prefix
|
||||
)
|
||||
)
|
||||
|
||||
return blueprints, registrators
|
||||
|
||||
def _prepare_blueprint_plugin(self, plugin):
|
||||
name = plugin._identifier
|
||||
@@ -1832,32 +1912,13 @@ class Server:
|
||||
blueprint.before_request(requireLoginRequestHandler)
|
||||
|
||||
url_prefix = f"/plugin/{name}"
|
||||
app.register_blueprint(blueprint, url_prefix=url_prefix)
|
||||
|
||||
if self._logger:
|
||||
self._logger.debug(
|
||||
"Registered API of plugin {name} under URL prefix {url_prefix}".format(
|
||||
name=name, url_prefix=url_prefix
|
||||
)
|
||||
)
|
||||
|
||||
return blueprint, url_prefix
|
||||
|
||||
def _prepare_asset_plugin(self, plugin):
|
||||
name = plugin._identifier
|
||||
|
||||
url_prefix = f"/plugin/{name}"
|
||||
blueprint = Blueprint(
|
||||
"plugin." + name, name, static_folder=plugin.get_asset_folder()
|
||||
)
|
||||
app.register_blueprint(blueprint, url_prefix=url_prefix)
|
||||
|
||||
if self._logger:
|
||||
self._logger.debug(
|
||||
"Registered assets of plugin {name} under URL prefix {url_prefix}".format(
|
||||
name=name, url_prefix=url_prefix
|
||||
)
|
||||
)
|
||||
blueprint = Blueprint(name, name, static_folder=plugin.get_asset_folder())
|
||||
|
||||
return blueprint, url_prefix
|
||||
|
||||
|
||||
@@ -34,6 +34,11 @@ from octoprint.server.util.flask import (
|
||||
from octoprint.settings import settings, valid_boolean_trues
|
||||
from octoprint.util import sv, time_this
|
||||
|
||||
try:
|
||||
from urllib.parse import quote as urlquote
|
||||
except ImportError:
|
||||
from urllib import quote as urlquote # noqa: F401
|
||||
|
||||
# ~~ GCODE file handling
|
||||
|
||||
_file_cache = {}
|
||||
@@ -447,7 +452,7 @@ def _getFileList(
|
||||
+ "downloads/files/"
|
||||
+ FileDestinations.LOCAL
|
||||
+ "/"
|
||||
+ file_or_folder["path"],
|
||||
+ urlquote(file_or_folder["path"]),
|
||||
}
|
||||
|
||||
result.append(file_or_folder)
|
||||
@@ -702,7 +707,7 @@ def uploadGcodeFile(target):
|
||||
+ "downloads/files/"
|
||||
+ FileDestinations.LOCAL
|
||||
+ "/"
|
||||
+ filename,
|
||||
+ urlquote(filename),
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -1029,7 +1034,10 @@ def gcodeFileCommand(filename, target):
|
||||
abort(404, description="Unknown profile")
|
||||
|
||||
location = url_for(
|
||||
".readGcodeFile", target=target, filename=full_path, _external=True
|
||||
".readGcodeFile",
|
||||
target=target,
|
||||
filename=full_path,
|
||||
_external=True,
|
||||
)
|
||||
result = {
|
||||
"name": destination,
|
||||
@@ -1042,7 +1050,7 @@ def gcodeFileCommand(filename, target):
|
||||
+ "downloads/files/"
|
||||
+ target
|
||||
+ "/"
|
||||
+ full_path,
|
||||
+ urlquote(full_path),
|
||||
},
|
||||
}
|
||||
|
||||
@@ -1147,7 +1155,10 @@ def gcodeFileCommand(filename, target):
|
||||
fileManager.move_folder(target, filename, destination)
|
||||
|
||||
location = url_for(
|
||||
".readGcodeFile", target=target, filename=destination, _external=True
|
||||
".readGcodeFile",
|
||||
target=target,
|
||||
filename=destination,
|
||||
_external=True,
|
||||
)
|
||||
result = {
|
||||
"name": name,
|
||||
@@ -1161,7 +1172,7 @@ def gcodeFileCommand(filename, target):
|
||||
+ "downloads/files/"
|
||||
+ target
|
||||
+ "/"
|
||||
+ destination
|
||||
+ urlquote(destination)
|
||||
)
|
||||
|
||||
r = make_response(jsonify(result), 201)
|
||||
|
||||
@@ -17,6 +17,7 @@ from octoprint.plugin import plugin_manager
|
||||
from octoprint.server.api import api
|
||||
from octoprint.server.util.flask import no_firstrun_access
|
||||
from octoprint.settings import settings
|
||||
from octoprint.util import yaml
|
||||
|
||||
|
||||
@api.route("/languages", methods=["GET"])
|
||||
@@ -40,11 +41,8 @@ def getInstalledLanguagePacks():
|
||||
|
||||
meta_path = os.path.join(path, "meta.yaml")
|
||||
if os.path.isfile(meta_path):
|
||||
import yaml
|
||||
|
||||
try:
|
||||
with open(meta_path, encoding="utf-8") as f:
|
||||
meta = yaml.safe_load(f)
|
||||
meta = yaml.load_from_file(path=meta_path)
|
||||
except Exception:
|
||||
logging.getLogger(__name__).exception("Could not load %s", meta_path)
|
||||
pass
|
||||
|
||||
@@ -123,6 +123,7 @@ def getSettings():
|
||||
"streamUrl": s.get(["webcam", "stream"]),
|
||||
"streamRatio": s.get(["webcam", "streamRatio"]),
|
||||
"streamTimeout": s.getInt(["webcam", "streamTimeout"]),
|
||||
"streamWebrtcIceServers": s.get(["webcam", "streamWebrtcIceServers"]),
|
||||
"snapshotUrl": s.get(["webcam", "snapshot"]),
|
||||
"snapshotTimeout": s.getInt(["webcam", "snapshotTimeout"]),
|
||||
"snapshotSslValidation": s.getBoolean(["webcam", "snapshotSslValidation"]),
|
||||
@@ -143,6 +144,7 @@ def getSettings():
|
||||
"keyboardControl": s.getBoolean(["feature", "keyboardControl"]),
|
||||
"pollWatched": s.getBoolean(["feature", "pollWatched"]),
|
||||
"modelSizeDetection": s.getBoolean(["feature", "modelSizeDetection"]),
|
||||
"rememberFileFolder": s.getBoolean(["feature", "rememberFileFolder"]),
|
||||
"printStartConfirmation": s.getBoolean(["feature", "printStartConfirmation"]),
|
||||
"printCancelConfirmation": s.getBoolean(
|
||||
["feature", "printCancelConfirmation"]
|
||||
@@ -251,6 +253,7 @@ def getSettings():
|
||||
"capExtendedM20": s.getBoolean(["serial", "capabilities", "extended_m20"]),
|
||||
"resendRatioThreshold": s.getInt(["serial", "resendRatioThreshold"]),
|
||||
"resendRatioStart": s.getInt(["serial", "resendRatioStart"]),
|
||||
"ignoreEmptyPorts": s.getBoolean(["serial", "ignoreEmptyPorts"]),
|
||||
},
|
||||
"connection": {
|
||||
"protocols": _get_protocol_settings(),
|
||||
@@ -507,9 +510,9 @@ def _saveSettings(data):
|
||||
for folder in FOLDER_TYPES:
|
||||
future[folder] = s.getBaseFolder(folder)
|
||||
if folder in folders:
|
||||
future[folder] = data["folder"][folder]
|
||||
future[folder] = folders[folder]
|
||||
|
||||
for folder in data["folder"]:
|
||||
for folder in folders:
|
||||
if folder not in FOLDER_TYPES:
|
||||
continue
|
||||
for other_folder in FOLDER_TYPES:
|
||||
@@ -587,6 +590,13 @@ def _saveSettings(data):
|
||||
s.set(["webcam", "streamRatio"], data["webcam"]["streamRatio"])
|
||||
if "streamTimeout" in data["webcam"]:
|
||||
s.setInt(["webcam", "streamTimeout"], data["webcam"]["streamTimeout"])
|
||||
if "streamWebrtcIceServers" in data["webcam"] and isinstance(
|
||||
data["webcam"]["streamWebrtcIceServers"], (list, tuple)
|
||||
):
|
||||
s.set(
|
||||
["webcam", "streamWebrtcIceServers"],
|
||||
data["webcam"]["streamWebrtcIceServers"],
|
||||
)
|
||||
if "snapshotUrl" in data["webcam"]:
|
||||
s.set(["webcam", "snapshot"], data["webcam"]["snapshotUrl"])
|
||||
if "snapshotTimeout" in data["webcam"]:
|
||||
@@ -667,6 +677,11 @@ def _saveSettings(data):
|
||||
s.setBoolean(
|
||||
["feature", "modelSizeDetection"], data["feature"]["modelSizeDetection"]
|
||||
)
|
||||
if "rememberFileFolder" in data["feature"]:
|
||||
s.setBoolean(
|
||||
["feature", "rememberFileFolder"],
|
||||
data["feature"]["rememberFileFolder"],
|
||||
)
|
||||
if "printStartConfirmation" in data["feature"]:
|
||||
s.setBoolean(
|
||||
["feature", "printStartConfirmation"],
|
||||
@@ -986,6 +1001,10 @@ def _saveSettings(data):
|
||||
)
|
||||
if "resendRatioStart" in data["serial"]:
|
||||
s.setInt(["serial", "resendRatioStart"], data["serial"]["resendRatioStart"])
|
||||
if "ignoreEmptyPorts" in data["serial"]:
|
||||
s.setBoolean(
|
||||
["serial", "ignoreEmptyPorts"], data["serial"]["ignoreEmptyPorts"]
|
||||
)
|
||||
|
||||
oldLog = s.getBoolean(["serial", "log"])
|
||||
if "log" in data["serial"]:
|
||||
@@ -1182,7 +1201,7 @@ def _saveSettings(data):
|
||||
plugin.on_settings_save(data["plugins"][plugin_id])
|
||||
except TypeError:
|
||||
logger.warning(
|
||||
"Could not save settings for plugin {name} ({version}) since it called super(...)".format(
|
||||
"Could not save settings for plugin {name} ({version}). It may have called super(...)".format(
|
||||
name=plugin._plugin_name, version=plugin._plugin_version
|
||||
)
|
||||
)
|
||||
@@ -1193,7 +1212,8 @@ def _saveSettings(data):
|
||||
"Please contact the plugin's author and ask to update the plugin to use a direct call like"
|
||||
)
|
||||
logger.warning(
|
||||
"octoprint.plugin.SettingsPlugin.on_settings_save(self, data) instead."
|
||||
"octoprint.plugin.SettingsPlugin.on_settings_save(self, data) instead.",
|
||||
exc_info=True,
|
||||
)
|
||||
except Exception:
|
||||
logger.exception(
|
||||
|
||||
@@ -44,6 +44,7 @@ def getSystemInfo():
|
||||
systeminfo = get_systeminfo(
|
||||
environmentDetector,
|
||||
connectivityChecker,
|
||||
s(),
|
||||
{
|
||||
"browser.user_agent": request.headers.get("User-Agent"),
|
||||
"octoprint.safe_mode": safe_mode is not None,
|
||||
|
||||
@@ -21,6 +21,11 @@ from octoprint.server.util.flask import (
|
||||
)
|
||||
from octoprint.settings import settings, valid_boolean_trues
|
||||
|
||||
try:
|
||||
from urllib.parse import quote as urlquote
|
||||
except ImportError:
|
||||
from urllib import quote as urlquote # noqa: F401
|
||||
|
||||
_DATA_FORMAT_VERSION = "v2"
|
||||
|
||||
# ~~ timelapse handling
|
||||
@@ -137,7 +142,7 @@ def getTimelapseData():
|
||||
finished_list = []
|
||||
for f in files:
|
||||
output = dict(f)
|
||||
output["url"] = url_for("index") + "downloads/timelapse/" + f["name"]
|
||||
output["url"] = url_for("index") + "downloads/timelapse/" + urlquote(f["name"])
|
||||
finished_list.append(output)
|
||||
|
||||
result = {
|
||||
@@ -157,7 +162,7 @@ def getTimelapseData():
|
||||
@Permissions.TIMELAPSE_DOWNLOAD.require(403)
|
||||
def downloadTimelapse(filename):
|
||||
return redirect_to_tornado(
|
||||
request, url_for("index") + "downloads/timelapse/" + filename
|
||||
request, url_for("index") + "downloads/timelapse/" + urlquote(filename)
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -365,6 +365,43 @@ def has_permissions(*permissions):
|
||||
return all(map(lambda p: p.can(), permissions))
|
||||
|
||||
|
||||
def require_login_with(permissions=None, user_id=None):
|
||||
"""
|
||||
Requires a login with the given permissions and/or user id.
|
||||
|
||||
Args:
|
||||
permissions: list of all permissions required to pass the check
|
||||
user_id: required user to pass the check
|
||||
|
||||
Returns: a flask redirect response to return if a login is required, or None
|
||||
"""
|
||||
|
||||
from octoprint.server import current_user, userManager
|
||||
|
||||
login_kwargs = {"redirect": _flask.request.script_root + _flask.request.full_path}
|
||||
if (
|
||||
_flask.request.headers.get("X-Preemptive-Recording", "no") == "no"
|
||||
and userManager.has_been_customized()
|
||||
):
|
||||
requires_login = False
|
||||
|
||||
if current_user.is_anonymous:
|
||||
requires_login = True
|
||||
|
||||
if permissions is not None and not has_permissions(*permissions):
|
||||
requires_login = True
|
||||
login_kwargs["permissions"] = ",".join([x.key for x in permissions])
|
||||
|
||||
if user_id is not None and current_user.get_id() != user_id:
|
||||
requires_login = True
|
||||
login_kwargs["user_id"] = user_id
|
||||
|
||||
if requires_login:
|
||||
return _flask.redirect(_flask.url_for("login", **login_kwargs))
|
||||
|
||||
return None
|
||||
|
||||
|
||||
def require_login(*permissions):
|
||||
"""
|
||||
Returns a redirect response to the login view if the permission requirements are
|
||||
|
||||
@@ -14,6 +14,7 @@ from os import scandir
|
||||
import flask
|
||||
import flask.json
|
||||
import flask.sessions
|
||||
import flask.templating
|
||||
import flask_assets
|
||||
import flask_login
|
||||
import netaddr
|
||||
@@ -30,7 +31,7 @@ import octoprint.server
|
||||
import octoprint.vendor.flask_principal as flask_principal
|
||||
from octoprint.events import Events, eventManager
|
||||
from octoprint.settings import settings
|
||||
from octoprint.util import DefaultOrderedDict, deprecated
|
||||
from octoprint.util import DefaultOrderedDict, deprecated, yaml
|
||||
from octoprint.util.json import JsonEncoding
|
||||
from octoprint.util.net import is_lan_address
|
||||
|
||||
@@ -591,6 +592,36 @@ class OctoPrintSessionInterface(flask.sessions.SecureCookieSessionInterface):
|
||||
return super().save_session(app, session, response)
|
||||
|
||||
|
||||
# ~~ jinja environment
|
||||
|
||||
|
||||
class PrefixAwareJinjaEnvironment(flask.templating.Environment):
|
||||
def __init__(self, *args, **kwargs):
|
||||
flask.templating.Environment.__init__(self, *args, **kwargs)
|
||||
self.prefix_loader = None
|
||||
self._cached_templates = {}
|
||||
|
||||
def join_path(self, template, parent):
|
||||
if parent and "/" in parent:
|
||||
prefix, _ = parent.split("/", 1)
|
||||
if template in self._templates_for_prefix(prefix) and not template.startswith(
|
||||
prefix + "/"
|
||||
):
|
||||
return prefix + "/" + template
|
||||
|
||||
return template
|
||||
|
||||
def _templates_for_prefix(self, prefix):
|
||||
if prefix in self._cached_templates:
|
||||
return self._cached_templates[prefix]
|
||||
|
||||
templates = []
|
||||
if prefix in self.prefix_loader.mapping:
|
||||
templates = self.prefix_loader.mapping[prefix].list_templates()
|
||||
self._cached_templates[prefix] = templates
|
||||
return templates
|
||||
|
||||
|
||||
# ~~ passive login helper
|
||||
|
||||
_cached_local_networks = None
|
||||
@@ -1008,13 +1039,10 @@ class PreemptiveCache:
|
||||
return all_data
|
||||
|
||||
def get_all_data(self):
|
||||
import yaml
|
||||
|
||||
cache_data = None
|
||||
with self._lock:
|
||||
try:
|
||||
with open(self.cachefile) as f:
|
||||
cache_data = yaml.safe_load(f)
|
||||
cache_data = yaml.load_from_file(path=self.cachefile)
|
||||
except OSError as e:
|
||||
import errno
|
||||
|
||||
@@ -1037,20 +1065,12 @@ class PreemptiveCache:
|
||||
return cache_data.get(root, list())
|
||||
|
||||
def set_all_data(self, data):
|
||||
import yaml
|
||||
|
||||
from octoprint.util import atomic_write
|
||||
|
||||
with self._lock:
|
||||
try:
|
||||
with atomic_write(self.cachefile, "wt", max_permissions=0o666) as handle:
|
||||
yaml.safe_dump(
|
||||
data,
|
||||
handle,
|
||||
default_flow_style=False,
|
||||
indent=2,
|
||||
allow_unicode=True,
|
||||
)
|
||||
yaml.save_to_file(data, file=handle, pretty=True)
|
||||
except Exception:
|
||||
self._logger.exception(f"Error while writing {self.cachefile}")
|
||||
|
||||
|
||||
@@ -3,6 +3,7 @@ __license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agp
|
||||
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
import logging
|
||||
import re
|
||||
import threading
|
||||
import time
|
||||
|
||||
@@ -96,11 +97,12 @@ class PrinterStateConnection(
|
||||
"*": [],
|
||||
}
|
||||
|
||||
# TODO: Permissions should be overridable from plugins, this special case stuff here is a hack
|
||||
_emit_permissions = {
|
||||
"connected": [],
|
||||
"reauthRequired": [],
|
||||
"plugin": lambda payload: []
|
||||
if payload.get("plugin") == "backup"
|
||||
if payload.get("plugin") in ("backup", "softwareupdate")
|
||||
and settings().getBoolean(["server", "firstRun"])
|
||||
else [Permissions.STATUS],
|
||||
"*": [Permissions.STATUS],
|
||||
@@ -166,6 +168,10 @@ class PrinterStateConnection(
|
||||
|
||||
self._registered = False
|
||||
self._authed = False
|
||||
self._initial_data_sent = False
|
||||
|
||||
self._subscriptions_active = False
|
||||
self._subscriptions = {"state": False, "plugins": [], "events": []}
|
||||
|
||||
@staticmethod
|
||||
def _get_remote_address(info):
|
||||
@@ -309,10 +315,77 @@ class PrinterStateConnection(
|
||||
)
|
||||
)
|
||||
|
||||
elif "subscribe" in message:
|
||||
if not self._subscriptions_active:
|
||||
self._subscriptions_active = True
|
||||
self._logger.debug("Client makes use of subscriptions")
|
||||
|
||||
def list_or_boolean(value):
|
||||
if isinstance(value, list):
|
||||
return value
|
||||
elif isinstance(value, bool):
|
||||
return [] if not value else None
|
||||
else:
|
||||
raise ValueError("value must be a list or boolean")
|
||||
|
||||
def regex_or_boolean(value):
|
||||
if isinstance(value, str):
|
||||
try:
|
||||
return re.compile(value)
|
||||
except Exception:
|
||||
raise ValueError("value must be a valid regex")
|
||||
elif isinstance(value, bool):
|
||||
return value
|
||||
else:
|
||||
raise ValueError("value must be a string or boolean")
|
||||
|
||||
try:
|
||||
subscribe = message["subscribe"]
|
||||
|
||||
state = subscribe.get("state", False)
|
||||
if isinstance(state, bool):
|
||||
if state:
|
||||
state = {"logs": True, "messages": False}
|
||||
elif isinstance(state, dict):
|
||||
logs = regex_or_boolean(state.get("logs", False))
|
||||
messages = regex_or_boolean(state.get("messages", False))
|
||||
state = {
|
||||
"logs": logs,
|
||||
"messages": messages,
|
||||
}
|
||||
|
||||
plugins = list_or_boolean(subscribe.get("plugins", []))
|
||||
events = list_or_boolean(subscribe.get("events", []))
|
||||
|
||||
except ValueError as e:
|
||||
self._logger.warning(
|
||||
"Got invalid subscription message from client {}, ignoring: {!r} ({}) ".format(
|
||||
self._remoteAddress, message["subscribe"], str(e)
|
||||
)
|
||||
)
|
||||
else:
|
||||
old_state = self._subscriptions["state"]
|
||||
self._subscriptions["state"] = state
|
||||
self._subscriptions["plugins"] = plugins
|
||||
self._subscriptions["events"] = events
|
||||
|
||||
if state and not old_state:
|
||||
# trigger initial data
|
||||
self._printer.send_initial_callback(self)
|
||||
elif old_state and not state:
|
||||
self._initial_data_sent = False
|
||||
|
||||
def on_printer_send_current_data(self, data):
|
||||
if not self._user.has_permission(Permissions.STATUS):
|
||||
return
|
||||
|
||||
if self._subscriptions_active and not self._subscriptions["state"]:
|
||||
return
|
||||
|
||||
if not self._initial_data_sent:
|
||||
self._logger.debug("Initial data not yet send, dropping current message")
|
||||
return
|
||||
|
||||
# make sure we rate limit the updates according to our throttle factor
|
||||
with self._held_back_mutex:
|
||||
if self._held_back_current is not None:
|
||||
@@ -338,11 +411,11 @@ class PrinterStateConnection(
|
||||
self._temperatureBacklog = []
|
||||
|
||||
with self._logBacklogMutex:
|
||||
logs = self._logBacklog
|
||||
logs = self._filter_logs(self._logBacklog)
|
||||
self._logBacklog = []
|
||||
|
||||
with self._messageBacklogMutex:
|
||||
messages = self._messageBacklog
|
||||
messages = self._filter_messages(self._messageBacklog)
|
||||
self._messageBacklog = []
|
||||
|
||||
busy_files = [
|
||||
@@ -369,7 +442,7 @@ class PrinterStateConnection(
|
||||
{
|
||||
"serverTime": time.time(),
|
||||
"temps": temperatures,
|
||||
"logs": logs,
|
||||
"logs": self._filter_logs(logs),
|
||||
"messages": messages,
|
||||
"busyFiles": busy_files,
|
||||
}
|
||||
@@ -377,10 +450,32 @@ class PrinterStateConnection(
|
||||
self._emit("current", payload=data)
|
||||
|
||||
def on_printer_send_initial_data(self, data):
|
||||
self._initial_data_sent = True
|
||||
if self._subscriptions_active and not self._subscriptions["state"]:
|
||||
self._logger.debug("Not subscribed to state, dropping history")
|
||||
return
|
||||
|
||||
data_to_send = dict(data)
|
||||
data_to_send["logs"] = self._filter_logs(data_to_send.get("logs", []))
|
||||
data_to_send["messages"] = self._filter_messages(data_to_send.get("messages", []))
|
||||
data_to_send["serverTime"] = time.time()
|
||||
self._emit("history", payload=data_to_send)
|
||||
|
||||
def _filter_state_subscription(self, sub, values):
|
||||
if not self._subscriptions_active or self._subscriptions["state"][sub] is True:
|
||||
return values
|
||||
|
||||
if self._subscriptions["state"][sub] is False:
|
||||
return []
|
||||
|
||||
return [line for line in values if self._subscriptions["state"][sub].search(line)]
|
||||
|
||||
def _filter_logs(self, logs):
|
||||
return self._filter_state_subscription("logs", logs)
|
||||
|
||||
def _filter_messages(self, messages):
|
||||
return self._filter_state_subscription("messages", messages)
|
||||
|
||||
def sendEvent(self, type, payload=None):
|
||||
permissions = self._event_permissions.get(type, self._event_permissions["*"])
|
||||
permissions = [x(self._user) if callable(x) else x for x in permissions]
|
||||
@@ -419,6 +514,13 @@ class PrinterStateConnection(
|
||||
self._emit("renderProgress", {"progress": progress})
|
||||
|
||||
def on_plugin_message(self, plugin, data, permissions=None):
|
||||
if (
|
||||
self._subscriptions_active
|
||||
and self._subscriptions["plugins"] is not None
|
||||
and plugin not in self._subscriptions["plugins"]
|
||||
):
|
||||
return
|
||||
|
||||
self._emit(
|
||||
"plugin", payload={"plugin": plugin, "data": data}, permissions=permissions
|
||||
)
|
||||
@@ -469,6 +571,13 @@ class PrinterStateConnection(
|
||||
self._sendReauthRequired("modified")
|
||||
|
||||
def _onEvent(self, event, payload):
|
||||
if (
|
||||
self._subscriptions_active
|
||||
and self._subscriptions["events"] is not None
|
||||
and event not in self._subscriptions["events"]
|
||||
):
|
||||
return
|
||||
|
||||
self.sendEvent(event, payload)
|
||||
|
||||
def _register(self):
|
||||
|
||||
@@ -20,6 +20,7 @@ import tornado.iostream
|
||||
import tornado.tcpserver
|
||||
import tornado.util
|
||||
import tornado.web
|
||||
from zipstream.ng import ZIP_DEFLATED, ZipStream
|
||||
|
||||
import octoprint.util
|
||||
|
||||
@@ -44,6 +45,18 @@ def fix_json_encode():
|
||||
tornado.escape.json_encode = fixed_json_encode
|
||||
|
||||
|
||||
def enable_per_message_deflate_extension():
|
||||
"""
|
||||
This configures tornado.websocket.WebSocketHandler.get_compression_options to support the permessage-deflate extension
|
||||
to the websocket protocol, minimizing data bandwidth if clients support the extension as well
|
||||
"""
|
||||
|
||||
def get_compression_options(self):
|
||||
return {"compression_level": 1, "mem_level": 1}
|
||||
|
||||
tornado.websocket.WebSocketHandler.get_compression_options = get_compression_options
|
||||
|
||||
|
||||
def fix_websocket_check_origin():
|
||||
"""
|
||||
This fixes tornado.websocket.WebSocketHandler.check_origin to do the same origin check against the Host
|
||||
@@ -1434,32 +1447,28 @@ class StaticZipBundleHandler(CorsSupportMixin, tornado.web.RequestHandler):
|
||||
f'attachment; filename="{self.get_attachment_name()}"',
|
||||
)
|
||||
|
||||
import zipstream
|
||||
|
||||
compress_type = zipstream.ZIP_STORED
|
||||
z = ZipStream(sized=True)
|
||||
if self._compress:
|
||||
try:
|
||||
import zlib # noqa: F401
|
||||
|
||||
compress_type = zipstream.ZIP_DEFLATED
|
||||
except ImportError:
|
||||
# no zlib, no compression
|
||||
z = ZipStream(compress_type=ZIP_DEFLATED)
|
||||
except RuntimeError:
|
||||
# no zlib support
|
||||
pass
|
||||
|
||||
z = zipstream.ZipFile()
|
||||
for f in self.normalize_files(files):
|
||||
# noinspection PyCompatibility
|
||||
name = f.get("name")
|
||||
path = f.get("path")
|
||||
iter = f.get("iter")
|
||||
content = f.get("content")
|
||||
data = f.get("iter") or f.get("content")
|
||||
|
||||
if path:
|
||||
z.write(path, arcname=name, compress_type=compress_type)
|
||||
elif iter and name:
|
||||
z.write_iter(name, iter, compress_type=compress_type)
|
||||
elif content and name:
|
||||
z.writestr(name, content, compress_type=compress_type)
|
||||
z.add_path(path, arcname=name)
|
||||
elif data and name:
|
||||
z.add(data, arcname=name)
|
||||
|
||||
if z.sized:
|
||||
self.set_header("Content-Length", len(z))
|
||||
self.set_header("Last-Modified", z.last_modified)
|
||||
|
||||
for chunk in z:
|
||||
try:
|
||||
@@ -1563,6 +1572,7 @@ class SystemInfoBundleHandler(CorsSupportMixin, tornado.web.RequestHandler):
|
||||
systeminfo = get_systeminfo(
|
||||
environmentDetector,
|
||||
connectivityChecker,
|
||||
settings(),
|
||||
{
|
||||
"browser.user_agent": self.request.headers.get("User-Agent"),
|
||||
"octoprint.safe_mode": safe_mode is not None,
|
||||
@@ -1582,6 +1592,9 @@ class SystemInfoBundleHandler(CorsSupportMixin, tornado.web.RequestHandler):
|
||||
"Content-Disposition",
|
||||
f'attachment; filename="{get_systeminfo_bundle_name()}"',
|
||||
)
|
||||
if z.sized:
|
||||
self.set_header("Content-Length", len(z))
|
||||
self.set_header("Last-Modified", z.last_modified)
|
||||
|
||||
for chunk in z:
|
||||
try:
|
||||
|
||||
@@ -38,7 +38,7 @@ from octoprint.server import ( # noqa: F401
|
||||
preemptiveCache,
|
||||
userManager,
|
||||
)
|
||||
from octoprint.server.util import has_permissions, require_login
|
||||
from octoprint.server.util import has_permissions, require_login_with
|
||||
from octoprint.settings import settings
|
||||
from octoprint.util import sv, to_bytes, to_unicode
|
||||
from octoprint.util.version import get_python_version_string
|
||||
@@ -184,13 +184,18 @@ def login():
|
||||
if not permissions:
|
||||
permissions = [Permissions.STATUS, Permissions.SETTINGS_READ]
|
||||
|
||||
if has_permissions(*permissions):
|
||||
user_id = request.args.get("user_id", "")
|
||||
|
||||
if (not user_id or current_user.get_id() == user_id) and has_permissions(
|
||||
*permissions
|
||||
):
|
||||
return redirect(redirect_url)
|
||||
|
||||
render_kwargs = {
|
||||
"theming": [],
|
||||
"redirect_url": redirect_url,
|
||||
"permission_names": map(lambda x: x.get_name(), permissions),
|
||||
"user_id": user_id,
|
||||
"logged_in": not current_user.is_anonymous,
|
||||
}
|
||||
|
||||
@@ -211,7 +216,7 @@ def login():
|
||||
@app.route("/recovery")
|
||||
@app.route("/recovery/")
|
||||
def recovery():
|
||||
response = require_login(Permissions.ADMIN)
|
||||
response = require_login_with(permissions=[Permissions.ADMIN])
|
||||
if response:
|
||||
return response
|
||||
|
||||
@@ -623,7 +628,7 @@ def index():
|
||||
plugin.implementation, octoprint.plugin.UiPlugin
|
||||
):
|
||||
permissions = plugin.implementation.get_ui_permissions()
|
||||
response = require_login(*permissions)
|
||||
response = require_login_with(permissions=permissions)
|
||||
if not response:
|
||||
response = plugin_view(plugin.implementation)
|
||||
if _logger.isEnabledFor(logging.DEBUG) and isinstance(
|
||||
@@ -633,7 +638,7 @@ def index():
|
||||
"X-Ui-Plugin"
|
||||
] = plugin.implementation._identifier
|
||||
else:
|
||||
response = require_login(*default_permissions)
|
||||
response = require_login_with(permissions=default_permissions)
|
||||
if not response:
|
||||
response = default_view()
|
||||
if _logger.isEnabledFor(logging.DEBUG) and isinstance(response, Response):
|
||||
@@ -649,7 +654,7 @@ def index():
|
||||
if plugin.will_handle_ui(request):
|
||||
# plugin claims responsibility, let it render the UI
|
||||
permissions = plugin.get_ui_permissions()
|
||||
response = require_login(*permissions)
|
||||
response = require_login_with(permissions=permissions)
|
||||
if not response:
|
||||
response = plugin_view(plugin)
|
||||
if response is not None:
|
||||
@@ -672,7 +677,7 @@ def index():
|
||||
extra={"plugin": plugin._identifier},
|
||||
)
|
||||
else:
|
||||
response = require_login(*default_permissions)
|
||||
response = require_login_with(permissions=default_permissions)
|
||||
if not response:
|
||||
response = default_view()
|
||||
if _logger.isEnabledFor(logging.DEBUG) and isinstance(response, Response):
|
||||
@@ -1492,6 +1497,12 @@ def _process_template_config(name, implementation, rule, config=None, counter=1)
|
||||
|
||||
if "template" not in data:
|
||||
data["template"] = rule["template"](name)
|
||||
data["template"] = implementation.template_folder_key + "/" + data["template"]
|
||||
|
||||
if "template_header" in data:
|
||||
data["template_header"] = (
|
||||
implementation.template_folder_key + "/" + data["template_header"]
|
||||
)
|
||||
|
||||
if "name" not in data:
|
||||
data["name"] = implementation._plugin_name
|
||||
|
||||
@@ -20,7 +20,6 @@ __author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
|
||||
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
import copy
|
||||
import fnmatch
|
||||
import logging
|
||||
import os
|
||||
@@ -29,15 +28,17 @@ import time
|
||||
from collections import ChainMap
|
||||
from collections.abc import KeysView
|
||||
|
||||
import yaml
|
||||
import yaml.parser
|
||||
# noinspection PyCompatibilitys
|
||||
from yaml import YAMLError
|
||||
|
||||
from octoprint.util import (
|
||||
CaseInsensitiveSet,
|
||||
atomic_write,
|
||||
deprecated,
|
||||
dict_merge,
|
||||
fast_deepcopy,
|
||||
is_hidden_path,
|
||||
yaml,
|
||||
)
|
||||
|
||||
_APPNAME = "OctoPrint"
|
||||
@@ -89,7 +90,7 @@ default_settings = {
|
||||
"port": None,
|
||||
"baudrate": None,
|
||||
"exclusive": True,
|
||||
"lowLatency": True,
|
||||
"lowLatency": False,
|
||||
"autoconnect": False,
|
||||
"log": False,
|
||||
"timeout": {
|
||||
@@ -165,6 +166,7 @@ default_settings = {
|
||||
},
|
||||
"resendRatioThreshold": 10,
|
||||
"resendRatioStart": 100,
|
||||
"ignoreEmptyPorts": False,
|
||||
# command specific flags
|
||||
"triggerOkForM29": True,
|
||||
},
|
||||
@@ -236,6 +238,7 @@ default_settings = {
|
||||
"stream": None,
|
||||
"streamRatio": "16:9",
|
||||
"streamTimeout": 5,
|
||||
"streamWebrtcIceServers": ["stun:stun.l.google.com:19302"],
|
||||
"snapshot": None,
|
||||
"snapshotTimeout": 5,
|
||||
"snapshotSslValidation": True,
|
||||
@@ -271,6 +274,7 @@ default_settings = {
|
||||
"keyboardControl": True,
|
||||
"pollWatched": False,
|
||||
"modelSizeDetection": True,
|
||||
"rememberFileFolder": False,
|
||||
"printStartConfirmation": False,
|
||||
"printCancelConfirmation": True,
|
||||
"uploadOverwriteConfirmation": True,
|
||||
@@ -363,6 +367,7 @@ default_settings = {
|
||||
"plugin_pluginmanager",
|
||||
"plugin_softwareupdate",
|
||||
"plugin_announcements",
|
||||
"plugin_eventmanager",
|
||||
"plugin_backup",
|
||||
"plugin_tracking",
|
||||
"plugin_errortracking",
|
||||
@@ -530,17 +535,16 @@ class DuplicateFolderPaths(InvalidSettings):
|
||||
|
||||
|
||||
class HierarchicalChainMap(ChainMap):
|
||||
def deep_dict(self, root=None):
|
||||
if root is None:
|
||||
root = self
|
||||
def deep_dict(self):
|
||||
def deep_dict_inner(root):
|
||||
return {
|
||||
key: deep_dict_inner(self.__class__._get_next(key, root))
|
||||
if isinstance(value, dict)
|
||||
else value
|
||||
for key, value in root.items()
|
||||
}
|
||||
|
||||
result = {}
|
||||
for key, value in root.items():
|
||||
if isinstance(value, dict):
|
||||
result[key] = self.deep_dict(root=self.__class__._get_next(key, root))
|
||||
else:
|
||||
result[key] = value
|
||||
return result
|
||||
return deep_dict_inner(self)
|
||||
|
||||
def has_path(self, path, only_local=False, only_defaults=False):
|
||||
if only_defaults:
|
||||
@@ -939,9 +943,7 @@ class Settings:
|
||||
|
||||
@property
|
||||
def effective_yaml(self):
|
||||
import yaml
|
||||
|
||||
return yaml.safe_dump(self.effective)
|
||||
return yaml.dump(self.effective)
|
||||
|
||||
@property
|
||||
def effective_hash(self):
|
||||
@@ -957,9 +959,7 @@ class Settings:
|
||||
|
||||
@property
|
||||
def config_yaml(self):
|
||||
import yaml
|
||||
|
||||
return yaml.safe_dump(self._config)
|
||||
return yaml.dump(self._config)
|
||||
|
||||
@property
|
||||
def config_hash(self):
|
||||
@@ -1011,10 +1011,10 @@ class Settings:
|
||||
if os.path.exists(self._configfile) and os.path.isfile(self._configfile):
|
||||
with open(self._configfile, encoding="utf-8", errors="replace") as f:
|
||||
try:
|
||||
self._config = yaml.safe_load(f)
|
||||
self._config = yaml.load_from_file(file=f)
|
||||
self._mtime = self.last_modified
|
||||
|
||||
except yaml.YAMLError as e:
|
||||
except YAMLError as e:
|
||||
details = str(e)
|
||||
|
||||
if hasattr(e, "problem_mark"):
|
||||
@@ -1078,8 +1078,7 @@ class Settings:
|
||||
|
||||
if isinstance(overlay, str):
|
||||
if os.path.exists(overlay) and os.path.isfile(overlay):
|
||||
with open(overlay, encoding="utf-8", errors="replace") as f:
|
||||
config = yaml.safe_load(f)
|
||||
config = yaml.load_from_file(path=overlay)
|
||||
elif isinstance(overlay, dict):
|
||||
config = overlay
|
||||
else:
|
||||
@@ -1100,7 +1099,7 @@ class Settings:
|
||||
assert isinstance(overlay, dict)
|
||||
|
||||
if key is None:
|
||||
overlay_yaml = yaml.safe_dump(overlay)
|
||||
overlay_yaml = yaml.dump(overlay)
|
||||
import hashlib
|
||||
|
||||
hash = hashlib.md5()
|
||||
@@ -1179,13 +1178,7 @@ class Settings:
|
||||
permissions=0o600,
|
||||
max_permissions=0o666,
|
||||
) as configFile:
|
||||
yaml.safe_dump(
|
||||
self._config,
|
||||
configFile,
|
||||
default_flow_style=False,
|
||||
indent=2,
|
||||
allow_unicode=True,
|
||||
)
|
||||
yaml.save_to_file(self._config, file=configFile)
|
||||
self._dirty = False
|
||||
except Exception:
|
||||
self._logger.exception("Error while saving config.yaml!")
|
||||
@@ -1281,19 +1274,13 @@ class Settings:
|
||||
except KeyError:
|
||||
raise NoSuchSettingsPath()
|
||||
|
||||
if preprocessors is not None:
|
||||
try:
|
||||
preprocessor = self._get_by_path(path, preprocessors)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if callable(preprocessor):
|
||||
value = preprocessor(value)
|
||||
if callable(preprocessor):
|
||||
value = preprocessor(value)
|
||||
|
||||
if do_copy:
|
||||
if isinstance(value, KeysView):
|
||||
value = list(value)
|
||||
value = copy.deepcopy(value)
|
||||
value = fast_deepcopy(value)
|
||||
|
||||
if asdict:
|
||||
results[key] = value
|
||||
|
||||
@@ -426,5 +426,11 @@
|
||||
});
|
||||
};
|
||||
|
||||
OctoPrintClient.escapePath = function (path) {
|
||||
return _.map(path.split("/"), function (p) {
|
||||
return encodeURIComponent(p);
|
||||
}).join("/");
|
||||
};
|
||||
|
||||
return OctoPrintClient;
|
||||
});
|
||||
@@ -14,19 +14,19 @@
|
||||
};
|
||||
|
||||
var resourceForLocation = function (location) {
|
||||
return url + "/" + location;
|
||||
return url + "/" + OctoPrintClient.escapePath(location);
|
||||
};
|
||||
|
||||
var downloadForLocation = function (location) {
|
||||
return downloadUrl + "/" + location;
|
||||
return downloadUrl + "/" + OctoPrintClient.escapePath(location);
|
||||
};
|
||||
|
||||
var downloadForEntry = function (location, filename) {
|
||||
return downloadForLocation(location) + "/" + filename;
|
||||
return downloadForLocation(location) + "/" + OctoPrintClient.escapePath(filename);
|
||||
};
|
||||
|
||||
var resourceForEntry = function (location, filename) {
|
||||
return resourceForLocation(location) + "/" + filename;
|
||||
return resourceForLocation(location) + "/" + OctoPrintClient.escapePath(filename);
|
||||
};
|
||||
|
||||
var preProcessList = function (response) {
|
||||
|
||||
@@ -11,15 +11,15 @@
|
||||
var bulkDownloadUrl = "downloads/timelapses";
|
||||
|
||||
var timelapseUrl = function (filename) {
|
||||
return url + "/" + filename;
|
||||
return url + "/" + OctoPrintClient.escapePath(filename);
|
||||
};
|
||||
|
||||
var timelapseDownloadUrl = function (filename) {
|
||||
return downloadUrl + "/" + filename;
|
||||
return downloadUrl + "/" + OctoPrintClient.escapePath(filename);
|
||||
};
|
||||
|
||||
var unrenderedTimelapseUrl = function (name) {
|
||||
return url + "/unrendered/" + name;
|
||||
return url + "/unrendered/" + OctoPrintClient.escapePath(name);
|
||||
};
|
||||
|
||||
var OctoPrintTimelapseClient = function (base) {
|
||||
|
||||
@@ -344,6 +344,7 @@ function DataUpdater(allViewModels, connectCallback, disconnectCallback) {
|
||||
hide: false
|
||||
});
|
||||
} else if (type === "Error" && payload.error) {
|
||||
severity = "error";
|
||||
switch (payload.reason) {
|
||||
case "firmware": {
|
||||
title = gettext("Error reported by printer");
|
||||
@@ -388,7 +389,13 @@ function DataUpdater(allViewModels, connectCallback, disconnectCallback) {
|
||||
break;
|
||||
}
|
||||
case "autodetect": {
|
||||
// ignore
|
||||
title = gettext("Could not autodetect your printer");
|
||||
text = _.sprintf(
|
||||
gettext(
|
||||
'No working connection parameters could be found. Are you sure your printer is physically connected and supported? Refer to <a href="%(url)s" target="_blank" rel="noopener noreferer">the FAQ</a> for help in debugging this.'
|
||||
),
|
||||
{url: "https://faq.octoprint.org/connection-error"}
|
||||
);
|
||||
break;
|
||||
}
|
||||
default: {
|
||||
@@ -410,7 +417,7 @@ function DataUpdater(allViewModels, connectCallback, disconnectCallback) {
|
||||
self._printerErrorDisconnectNotification = new PNotify({
|
||||
title: title,
|
||||
text: text,
|
||||
type: "error",
|
||||
type: severity,
|
||||
hide: false
|
||||
});
|
||||
}
|
||||
|
||||
@@ -56,9 +56,10 @@ function ItemListHelper(
|
||||
for (var i = 0; i < itemList.length; i++) {
|
||||
if (matcher(itemList[i])) {
|
||||
self.selectedItem(itemList[i]);
|
||||
break;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
};
|
||||
|
||||
self.selectNone = function () {
|
||||
@@ -1060,18 +1061,14 @@ function showProgressModal(options, promise) {
|
||||
|
||||
var progress = $('<div class="progress progress-text-centered"></div>');
|
||||
var progressBar = $('<div class="bar"></div>').addClass(barClassSuccess);
|
||||
var progressTextBack = $('<span class="progress-text-back"></span>');
|
||||
var progressTextFront = $('<span class="progress-text-front"></span>').width(
|
||||
progress.width()
|
||||
);
|
||||
var progressText = $('<span class="progress-text-back"></span>');
|
||||
|
||||
if (max === undefined) {
|
||||
progress.addClass("progress-striped active");
|
||||
progressBar.width("100%");
|
||||
}
|
||||
|
||||
progressBar.append(progressTextFront);
|
||||
progress.append(progressTextBack).append(progressBar);
|
||||
progress.append(progressBar).append(progressText);
|
||||
|
||||
var button = $('<button class="btn">' + buttonText + "</button>")
|
||||
.prop("disabled", true)
|
||||
@@ -1127,9 +1124,16 @@ function showProgressModal(options, promise) {
|
||||
|
||||
// update progress bar
|
||||
progressBar.width(String(value) + "%");
|
||||
progressTextFront.text(short);
|
||||
progressTextBack.text(short);
|
||||
progressTextFront.width(progress.width());
|
||||
progressText.text(short);
|
||||
if (value < 50 && progressText.hasClass("progress-text-front")) {
|
||||
progressText
|
||||
.removeClass("progress-text-front")
|
||||
.addClass("progress-text-back");
|
||||
} else if (value >= 50 && progressText.hasClass("progress-text-back")) {
|
||||
progressText
|
||||
.removeClass("progress-text-back")
|
||||
.addClass("progress-text-front");
|
||||
}
|
||||
|
||||
// if not successful, apply failure class
|
||||
if (!success && !progressBar.hasClass(barClassFailure)) {
|
||||
@@ -1540,6 +1544,10 @@ var copyToClipboard = function (text) {
|
||||
|
||||
var determineWebcamStreamType = function (streamUrl) {
|
||||
if (streamUrl) {
|
||||
if (streamUrl.startsWith("webrtc")) {
|
||||
return "webrtc";
|
||||
}
|
||||
|
||||
var lastDotPosition = streamUrl.lastIndexOf(".");
|
||||
var firstQuotationSignPosition = streamUrl.indexOf("?");
|
||||
if (
|
||||
@@ -1616,3 +1624,82 @@ var deepMerge = function (target, source) {
|
||||
|
||||
return target;
|
||||
};
|
||||
|
||||
var isWebRTCAvailable = function () {
|
||||
return (
|
||||
typeof RTCPeerConnection == "function" &&
|
||||
typeof RTCPeerConnection.prototype.addEventListener == "function" &&
|
||||
typeof RTCPeerConnection.prototype.addTransceiver == "function" &&
|
||||
typeof RTCPeerConnection.prototype.createOffer == "function" &&
|
||||
typeof RTCPeerConnection.prototype.setLocalDescription == "function" &&
|
||||
typeof RTCPeerConnection.prototype.removeEventListener == "function" &&
|
||||
typeof RTCPeerConnection.prototype.addEventListener == "function" &&
|
||||
typeof RTCPeerConnection.prototype.setRemoteDescription == "function"
|
||||
);
|
||||
};
|
||||
|
||||
var negotiateWebRTC = function (streamUrl) {
|
||||
pc.addTransceiver("video", {direction: "recvonly"});
|
||||
pc.addTransceiver("audio", {direction: "recvonly"});
|
||||
return pc
|
||||
.createOffer()
|
||||
.then(function (offer) {
|
||||
return pc.setLocalDescription(offer);
|
||||
})
|
||||
.then(function () {
|
||||
// Wait for ICE gathering to complete
|
||||
return new Promise(function (resolve) {
|
||||
if (pc.iceGatheringState === "complete") {
|
||||
resolve();
|
||||
} else {
|
||||
function checkState() {
|
||||
if (pc.iceGatheringState === "complete") {
|
||||
pc.removeEventListener("icegatheringstatechange", checkState);
|
||||
resolve();
|
||||
}
|
||||
}
|
||||
pc.addEventListener("icegatheringstatechange", checkState);
|
||||
}
|
||||
});
|
||||
})
|
||||
.then(function () {
|
||||
var offer = pc.localDescription;
|
||||
// webrtc://host.com becomes http://host.com
|
||||
// webrtcs://host.com becomes https://host.com
|
||||
streamUrl = "http" + streamUrl.slice("webrtc".length);
|
||||
return $.ajax({
|
||||
url: streamUrl,
|
||||
type: "POST",
|
||||
dataType: "json",
|
||||
data: JSON.stringify({
|
||||
sdp: offer.sdp,
|
||||
type: offer.type
|
||||
}),
|
||||
contentType: "application/json; charset=UTF-8"
|
||||
});
|
||||
})
|
||||
.then(function (response) {
|
||||
return pc.setRemoteDescription(response);
|
||||
})
|
||||
.catch(function (e) {
|
||||
console.error(e);
|
||||
});
|
||||
};
|
||||
|
||||
var startWebRTC = function (videoElement, streamUrl, iceServers) {
|
||||
var config = {
|
||||
sdpSemantics: "unified-plan"
|
||||
};
|
||||
if (iceServers) {
|
||||
config.iceServers = [{urls: iceServers}];
|
||||
}
|
||||
pc = new RTCPeerConnection(config);
|
||||
pc.addEventListener("track", function (evt) {
|
||||
if (evt.track.kind == "video") {
|
||||
videoElement.srcObject = evt.streams[0];
|
||||
}
|
||||
});
|
||||
|
||||
negotiateWebRTC(streamUrl);
|
||||
return pc;
|
||||
};
|
||||
@@ -566,11 +566,38 @@ $(function () {
|
||||
self.isReady = ko.observable(undefined);
|
||||
self.isLoading = ko.observable(undefined);
|
||||
|
||||
self.enableConnect = ko.pureComputed(function () {
|
||||
return self.enablePort() || !self.isErrorOrClosed();
|
||||
});
|
||||
|
||||
self.buttonText = ko.pureComputed(function () {
|
||||
if (self.isErrorOrClosed()) return gettext("Connect");
|
||||
else return gettext("Disconnect");
|
||||
});
|
||||
|
||||
self.portCaption = ko.pureComputed(function () {
|
||||
return self.validPort() ? "AUTO" : gettext("No serial port found");
|
||||
});
|
||||
|
||||
self.validPort = ko.pureComputed(function () {
|
||||
return (
|
||||
self.portOptions().length > 0 ||
|
||||
self.settings.settings.serial.ignoreEmptyPorts()
|
||||
);
|
||||
});
|
||||
|
||||
self.enablePort = ko.pureComputed(function () {
|
||||
return self.validPort() && self.isErrorOrClosed();
|
||||
});
|
||||
|
||||
self.enableSaveSettings = ko.pureComputed(function () {
|
||||
return self.enableConnect() && self.isErrorOrClosed();
|
||||
});
|
||||
|
||||
self.enableAutoConnect = ko.pureComputed(function () {
|
||||
return self.enableConnect() && self.isErrorOrClosed();
|
||||
});
|
||||
|
||||
self.previousIsOperational = undefined;
|
||||
|
||||
self.refreshVisible = ko.observable(true);
|
||||
|
||||
@@ -41,7 +41,9 @@ $(function () {
|
||||
self.webcamLoaded = ko.observable(false);
|
||||
self.webcamMjpgEnabled = ko.observable(false);
|
||||
self.webcamHlsEnabled = ko.observable(false);
|
||||
self.webcamWebRTCEnabled = ko.observable(false);
|
||||
self.webcamError = ko.observable(false);
|
||||
self.webRTCPeerConnection = null;
|
||||
|
||||
self.keycontrolActive = ko.observable(false);
|
||||
self.keycontrolHelpActive = ko.observable(false);
|
||||
@@ -524,6 +526,8 @@ $(function () {
|
||||
self._switchToMjpgWebcam();
|
||||
} else if (streamType == "hls") {
|
||||
self._switchToHlsWebcam();
|
||||
} else if (isWebRTCAvailable() && streamType == "webrtc") {
|
||||
self._switchToWebRTCWebcam();
|
||||
} else {
|
||||
throw "Unknown stream type " + streamType;
|
||||
}
|
||||
@@ -708,6 +712,7 @@ $(function () {
|
||||
|
||||
self.webcamHlsEnabled(false);
|
||||
self.webcamMjpgEnabled(true);
|
||||
self.webcamWebRTCEnabled(false);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -729,6 +734,36 @@ $(function () {
|
||||
|
||||
self.webcamMjpgEnabled(false);
|
||||
self.webcamHlsEnabled(true);
|
||||
self.webcamWebRTCEnabled(false);
|
||||
};
|
||||
|
||||
self._switchToWebRTCWebcam = function () {
|
||||
if (!isWebRTCAvailable()) {
|
||||
return;
|
||||
}
|
||||
var video = document.getElementById("webcam_webrtc");
|
||||
|
||||
// Close any existing, disconnected connection
|
||||
if (
|
||||
self.webRTCPeerConnection != null &&
|
||||
self.webRTCPeerConnection.connectionState != "connected"
|
||||
) {
|
||||
self.webRTCPeerConnection.close();
|
||||
self.webRTCPeerConnection = null;
|
||||
}
|
||||
|
||||
// Open a new connection if necessary
|
||||
if (self.webRTCPeerConnection == null) {
|
||||
self.webRTCPeerConnection = startWebRTC(
|
||||
video,
|
||||
self.settings.webcam_streamUrl(),
|
||||
self.settings.webcam_streamWebrtcIceServers()
|
||||
);
|
||||
}
|
||||
|
||||
self.webcamMjpgEnabled(false);
|
||||
self.webcamHlsEnabled(false);
|
||||
self.webcamWebRTCEnabled(true);
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -117,7 +117,27 @@ $(function () {
|
||||
self.uploadFilename = ko.observable(undefined);
|
||||
|
||||
self.allItems = ko.observable(undefined);
|
||||
|
||||
var optionsLocalStorageKey = "gcodeFiles.options";
|
||||
self._toLocalStorage = function () {
|
||||
saveToLocalStorage(optionsLocalStorageKey, {currentPath: self.currentPath()});
|
||||
};
|
||||
|
||||
self._fromLocalStorage = function () {
|
||||
var data = loadFromLocalStorage(optionsLocalStorageKey);
|
||||
if (
|
||||
data["currentPath"] !== undefined &&
|
||||
self.settingsViewModel.feature_rememberFileFolder()
|
||||
) {
|
||||
self.currentPath(data["currentPath"]);
|
||||
}
|
||||
};
|
||||
|
||||
self.currentPath = ko.observable("");
|
||||
self.currentPath.subscribe(function () {
|
||||
self._toLocalStorage();
|
||||
});
|
||||
|
||||
self.uploadProgressText = ko.observable();
|
||||
self.uploadProgressPercentage = ko.observable();
|
||||
|
||||
@@ -232,6 +252,7 @@ $(function () {
|
||||
listHelperExclusiveFilters,
|
||||
0
|
||||
);
|
||||
self.selectedFile = undefined;
|
||||
|
||||
self.availableFiletypes = ko.pureComputed(function () {
|
||||
var mapping = {
|
||||
@@ -311,34 +332,47 @@ $(function () {
|
||||
);
|
||||
});
|
||||
|
||||
self.printerState.filepath.subscribe(function (newValue) {
|
||||
self.highlightFilename(newValue);
|
||||
});
|
||||
|
||||
self.highlightCurrentFilename = function () {
|
||||
self.highlightFilename(self.printerState.filepath());
|
||||
self.highlightCurrentFile = function () {
|
||||
self.highlightFile(self.selectedFile);
|
||||
};
|
||||
|
||||
self.highlightFilename = function (filename) {
|
||||
if (filename === undefined || filename === null) {
|
||||
self.highlightFile = function (file) {
|
||||
if (!file || !file.origin || !file.path) {
|
||||
self.listHelper.selectNone();
|
||||
return;
|
||||
}
|
||||
|
||||
var result = self.listHelper.selectItem(function (item) {
|
||||
if (item.origin !== file.origin) return false;
|
||||
|
||||
if (item.type === "folder") {
|
||||
return _.startsWith(file.path, item.path + "/");
|
||||
} else {
|
||||
return item.path === file.path;
|
||||
}
|
||||
});
|
||||
if (!result) {
|
||||
if (log.getLevel() <= log.levels.DEBUG) {
|
||||
log.info(
|
||||
"Couldn't find file " +
|
||||
file.origin +
|
||||
":" +
|
||||
file.path +
|
||||
" in current items, not selecting"
|
||||
);
|
||||
}
|
||||
self.listHelper.selectNone();
|
||||
} else {
|
||||
self.listHelper.selectItem(function (item) {
|
||||
if (item.type === "folder") {
|
||||
return _.startsWith(filename, item.path + "/");
|
||||
} else {
|
||||
return item.path === filename;
|
||||
}
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
self.fromCurrentData = function (data) {
|
||||
self._processStateData(data.state);
|
||||
self._processJobData(data.job);
|
||||
};
|
||||
|
||||
self.fromHistoryData = function (data) {
|
||||
self._processStateData(data.state);
|
||||
self._processJobData(data.job);
|
||||
};
|
||||
|
||||
self._processStateData = function (data) {
|
||||
@@ -352,6 +386,21 @@ $(function () {
|
||||
self.isSdReady(data.flags.sdReady);
|
||||
};
|
||||
|
||||
self._processJobData = function (data) {
|
||||
if (!data) return;
|
||||
|
||||
if (
|
||||
self.selectedFile &&
|
||||
self.file &&
|
||||
self.selectedFile.origin === data.file.origin &&
|
||||
self.selectedFile.path === data.file.path
|
||||
)
|
||||
return;
|
||||
|
||||
self.selectedFile = data.file;
|
||||
self.highlightFile(data.file);
|
||||
};
|
||||
|
||||
self._otherRequestInProgress = undefined;
|
||||
self._focus = undefined;
|
||||
self._switchToPath = undefined;
|
||||
@@ -512,7 +561,7 @@ $(function () {
|
||||
self.totalSpace(response.total);
|
||||
}
|
||||
|
||||
self.highlightCurrentFilename();
|
||||
self.highlightCurrentFile();
|
||||
};
|
||||
|
||||
self.changeFolder = function (data) {
|
||||
@@ -525,7 +574,7 @@ $(function () {
|
||||
|
||||
self.currentPath(data.path);
|
||||
self.listHelper.updateItems(data.children);
|
||||
self.highlightCurrentFilename();
|
||||
self.highlightCurrentFile();
|
||||
};
|
||||
|
||||
self.navigateUp = function () {
|
||||
@@ -543,7 +592,7 @@ $(function () {
|
||||
self.currentPath("");
|
||||
self.listHelper.updateItems(self.allItems());
|
||||
}
|
||||
self.highlightCurrentFilename();
|
||||
self.highlightCurrentFile();
|
||||
};
|
||||
|
||||
self.showAddFolderDialog = function () {
|
||||
@@ -652,7 +701,9 @@ $(function () {
|
||||
|
||||
if (
|
||||
printAfterLoad &&
|
||||
self.listHelper.isSelected(data) &&
|
||||
self.listHelper.isSelectedByMatcher(function (item) {
|
||||
return item && item.origin === data.origin && item.path === data.path;
|
||||
}) &&
|
||||
self.enablePrint(data)
|
||||
) {
|
||||
// file was already selected, just start the print job
|
||||
@@ -1248,6 +1299,7 @@ $(function () {
|
||||
self.onUserPermissionsChanged = self.onUserLoggedIn = self.onUserLoggedOut = function () {
|
||||
self.updateButtons();
|
||||
self.requestData();
|
||||
self._fromLocalStorage();
|
||||
};
|
||||
|
||||
self.onStartup = function () {
|
||||
|
||||
@@ -153,6 +153,7 @@ $(function () {
|
||||
self.webcam_streamUrl = ko.observable(undefined);
|
||||
self.webcam_streamRatio = ko.observable(undefined);
|
||||
self.webcam_streamTimeout = ko.observable(undefined);
|
||||
self.webcam_streamWebrtcIceServers = ko.observable(undefined);
|
||||
self.webcam_snapshotUrl = ko.observable(undefined);
|
||||
self.webcam_snapshotTimeout = ko.observable(undefined);
|
||||
self.webcam_snapshotSslValidation = ko.observable(undefined);
|
||||
@@ -172,6 +173,7 @@ $(function () {
|
||||
self.feature_keyboardControl = ko.observable(undefined);
|
||||
self.feature_pollWatched = ko.observable(undefined);
|
||||
self.feature_modelSizeDetection = ko.observable(undefined);
|
||||
self.feature_rememberFileFolder = ko.observable(undefined);
|
||||
self.feature_printStartConfirmation = ko.observable(undefined);
|
||||
self.feature_printCancelConfirmation = ko.observable(undefined);
|
||||
self.feature_uploadOverwriteConfirmation = ko.observable(undefined);
|
||||
@@ -442,6 +444,7 @@ $(function () {
|
||||
);
|
||||
var streamType = determineWebcamStreamType(self.webcam_streamUrl());
|
||||
var webcam_element;
|
||||
var webrtc_peer_connection;
|
||||
if (streamType == "mjpg") {
|
||||
webcam_element = $('<img src="' + self.webcam_streamUrl() + '">');
|
||||
} else if (streamType == "hls") {
|
||||
@@ -456,6 +459,17 @@ $(function () {
|
||||
hls.loadSource(self.webcam_streamUrl());
|
||||
hls.attachMedia(video_element);
|
||||
}
|
||||
} else if (isWebRTCAvailable() && streamType == "webrtc") {
|
||||
webcam_element = $(
|
||||
'<video id="webcam_webrtc" muted autoplay playsinline controls style="width: 100%"/>'
|
||||
);
|
||||
video_element = webcam_element[0];
|
||||
|
||||
webrtc_peer_connection = startWebRTC(
|
||||
video_element,
|
||||
self.webcam_streamUrl(),
|
||||
self.webcam_streamWebrtcIceServers()
|
||||
);
|
||||
} else {
|
||||
throw "Unknown stream type " + streamType;
|
||||
}
|
||||
@@ -471,6 +485,10 @@ $(function () {
|
||||
message: message,
|
||||
onclose: function () {
|
||||
self.testWebcamStreamUrlBusy(false);
|
||||
if (webrtc_peer_connection != null) {
|
||||
webrtc_peer_connection.close();
|
||||
webrtc_peer_connection = null;
|
||||
}
|
||||
}
|
||||
});
|
||||
};
|
||||
@@ -1150,6 +1168,15 @@ $(function () {
|
||||
});
|
||||
return result;
|
||||
}
|
||||
},
|
||||
webcam: {
|
||||
streamWebrtcIceServers: function () {
|
||||
return splitTextToArray(
|
||||
self.webcam_streamWebrtcIceServers(),
|
||||
",",
|
||||
true
|
||||
);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
@@ -1310,6 +1337,11 @@ $(function () {
|
||||
profiles: function (value) {
|
||||
self.temperature_profiles($.extend(true, [], value));
|
||||
}
|
||||
},
|
||||
webcam: {
|
||||
streamWebrtcIceServers: function (value) {
|
||||
self.webcam_streamWebrtcIceServers(value.join(", "));
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
Loaded 100 of 125 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user