Compare commits

..
1 Commits
Author SHA1 Message Date
Gina Häußge 5e761b6fa9 📝 Fix printer profiles API docs
Phrasing improved and some copy-paste issues resolved as well.

Fixes #4160
2021-06-08 15:39:41 +02:00
147 changed files with 8728 additions and 12083 deletions

No files matched your search

-1
View File
@@ -1,6 +1,5 @@
approve_label: "approved"
problem_label: "needs some work"
ignore_label: "skip validation"
allowed_targets: ["maintenance", "devel", "staging/maintenance", "staging/devel"]
forbidden_sources:
+1 -19
View File
@@ -95,7 +95,7 @@ jobs:
test-e2e:
name: 🧪 E2E tests
needs: build
runs-on: ubuntu-latest
runs-on: ubuntu-16.04
steps:
- name: ⬇ Checkout code
uses: actions/checkout@v2
@@ -176,21 +176,3 @@ jobs:
uses: pypa/gh-action-pypi-publish@master
with:
password: ${{ secrets.pypi_password }}
notify-custopizer-build:
name: 📧 Notify OctoPi-UpToDate
if: github.event_name == 'release'
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": "${{ env.OCTOPRINT_VERSION }}"}'
+5 -92
View File
@@ -1,18 +1,19 @@
name: "Issue Automation"
on:
issues:
types: [opened, edited, closed, reopened, labeled, unlabeled]
types: [opened, edited, closed, reopened]
jobs:
issue-automation:
runs-on: ubuntu-latest
steps:
- uses: actions/github-script@v5
- uses: actions/github-script@v2
with:
github-token: ${{ secrets.GITHUB_TOKEN }}
script: |
let labels = context.payload.issue.labels.map(label => label.name);
let labels = [];
let setLabels = false;
context.payload.issue.labels.forEach(label => { labels.push(label.name) });
switch (context.payload.action) {
@@ -54,7 +55,7 @@ jobs:
}
if (setLabels) {
github.rest.issues.setLabels({
github.issues.setLabels({
issue_number: context.issue.number,
owner: context.repo.owner,
repo: context.repo.repo,
@@ -66,91 +67,3 @@ 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 (!labels.includes("triage")) {
console.log("No label, deleting comment if needed");
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 && comment.body !== text) {
await github.rest.issues.updateComment({
owner: context.repo.owner,
repo: context.repo.repo,
comment_id: comment.id,
body: text
});
} else {
await github.rest.issues.createComment({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: context.issue.number,
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 -30
View File
@@ -1,8 +1,7 @@
name: "Pull Request Automation"
on:
pull_request_target:
#types: ["opened", "synchronize", "reopened", "edited", "labeled", "unlabeled"]
types: ["opened"]
types: ["opened", "synchronize", "reopened", "edited", "labeled", "unlabeled"]
jobs:
pr-automation:
@@ -12,34 +11,6 @@ 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 }}
+1 -1
View File
@@ -14,7 +14,7 @@ jobs:
- name: 🚀 Repository Dispatch
uses: peter-evans/repository-dispatch@v1
with:
token: ${{ secrets.REPODISPATCH_TOKEN }}
token: ${{ secrets.DOCS_ACCESS_TOKEN }}
repository: OctoPrint/docs.octoprint.org
event-type: docs
client-payload: '{"ref": "${{ github.ref }}", "sha": "${{ github.sha }}"}'
+10 -10
View File
@@ -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.6.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.6.0 b7a45b79bf86339f0b28177ac1eaebb56d00ea37 pep440-dev
fix/.* 1.6.0 b7a45b79bf86339f0b28177ac1eaebb56d00ea37 pep440-dev
improve/.* 1.6.0 b7a45b79bf86339f0b28177ac1eaebb56d00ea37 pep440-dev
# staging/bugfix is the branch for preparation of the 1.7.1 bugfix release
# staging/bugfix is the branch for preparation of the 1.6.1 bugfix release
# so are any bug/... branches
staging/bugfix 1.7.1 ddfd333b6238f3250f9d7ad598031bd0ec8e9734 pep440-dev
bug/.* 1.7.1 ddfd333b6238f3250f9d7ad598031bd0ec8e9734 pep440-dev
staging/bugfix 1.6.1 29484fb2926960279e62881d6ee073c374a2a5fe pep440-dev
bug/.* 1.6.1 29484fb2926960279e62881d6ee073c374a2a5fe pep440-dev
# staging/maintenance is currently the branch for preparation of 1.7.0rc4
# staging/maintenance is currently the branch for preparation of 1.6.0rc4
# so is regressionfix/...
staging/maintenance 1.7.0rc4 f31194f75365787f3eb5da61a24f2f8620111f4f pep440-dev
regressionfix/.* 1.7.0rc4 f31194f75365787f3eb5da61a24f2f8620111f4f pep440-dev
staging/maintenance 1.6.0rc4 7054a726bb3dc363a98ec6944b24e07879bb389b pep440-dev
regressionfix/.* 1.6.0rc4 7054a726bb3dc363a98ec6944b24e07879bb389b pep440-dev
# staging/devel is currently inactive (but has the 1.4.1rc4 namespace)
staging/devel 1.4.1rc4 650d54d1885409fa1d411eb54b9e8c7ff428910f pep440-dev
-9
View File
@@ -141,15 +141,6 @@ date of first contribution):
* [Joe Martella](https://github.com/martellaj)
* [Scott Lahteine](https://github.com/thinkyhead)
* [Karthikeyan Singaravelan](https://github.com/tirkarthi)
* [Yvan Rodrigues](https://github.com/TwoRedCells)
* [Elton Law](https://github.com/eltonlaw)
* ["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)
* [Bryan Kenote](https://github.com/bryankenote)
* [Quinn Damerell](https://github.com/QuinnDamerell)
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
+11 -12
View File
@@ -9,7 +9,6 @@ thanks to everyone who contributed!
* 3D-TECH
* 3DPrinterOS
* Arnljot Arntsen
* Artillery 3D
* Ash King
* BigTreeTech
* Boris Hussein
@@ -19,56 +18,56 @@ thanks to everyone who contributed!
* Chris Lynch
* Christian Petropolis
* Christian Wolf
* Christian Würthner
* Christoph Sigrist
* Creality3D
* David Bounds
* D Brian Kimmel
* Dana Voigt
* DeltaMaker 3D Printers
* Dennis Breining
* Dr. Frank Wester
* Dennis Christilaw
* Douglas Floyd
* Eric Betts
* Ernesto Martinez
* Franziska Kunsmann
* George Robles
* Greg Holloway
* Hog Duske
* Itay Shem-tov
* Jeff Moe
* Hopewell Medical Acupuncture Center
* 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
* Peopoly
* Patrick Glyré
* 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
@@ -78,4 +77,4 @@ thanks to everyone who contributed!
* Ulderico Cirello
* Ulrich Kempken
and 2247 more wonderful people pledging on the [Patreon campaign](https://patreon.com/foosel) or via [GitHub Sponsors](https://github.com/users/foosel/sponsorship)!
and 2350 more wonderful people pledging on the [Patreon campaign](https://patreon.com/foosel) or via [GitHub Sponsors](https://github.com/users/foosel/sponsorship)!
+1 -2
View File
@@ -31,9 +31,9 @@
* [Moment.js](http://momentjs.com/): MIT
* [PNotify](http://sciactive.com/pnotify/): GPL, LGPL, MPL (triple licensed)
* [pusher.color.js](http://cache.preserve.io/5g18q0pw/index.html) (original link dead): MIT
* [ResizeSensor.js](https://github.com/procurios/ResizeSensor): MIT
* [SockJS](https://github.com/sockjs/sockjs-client): MIT
* [sprintf-js](http://alexei.ro/): BSD
* [UAParser.js](https://faisalman.github.io/ua-parser-js/): MIT
## Server
@@ -56,7 +56,6 @@
* [monotonic](https://github.com/atdt/monotonic): Apache License 2.0
* [netaddr](https://github.com/drkjam/netaddr/): BSD
* [netifaces](https://bitbucket.org/al45tair/netifaces): MIT
* [pathvalidate](https://pathvalidate.readthedocs.io/en/latest/index.html): MIT
* [pkginfo](http://pypi.python.org/pypi/pkginfo/): Python
* [psutil](https://github.com/giampaolo/psutil): BSD
* [pylru](https://github.com/jlhutch/pylru): GPLv2
+2 -2
View File
@@ -81,7 +81,7 @@ Retrieve a group
Retrieves an individual group record.
Will return a :http:statuscode:`200` with a :ref:`group record <sec-api-access-datamodel-groups-list>`
Will return a :http:statuscode:`200` with a :ref:`group record <sec-api-access-datamodel-groups-grouprecord>`
as body.
Requires the ``SETTINGS`` permission.
@@ -156,7 +156,7 @@ Retrieve a user
Retrieves information about a user.
Will return a :http:statuscode:`200` with a :ref:`user record <sec-api-datamodel-access>`
Will return a :http:statuscode:`200` with a :ref:`user record <sec-api-access-datamodel-users-userrecord>`
as body.
Requires either the ``SETTINGS`` permission or to be logged in as the user.
+1 -65
View File
@@ -365,14 +365,6 @@ 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:
@@ -514,62 +506,6 @@ 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
@@ -660,7 +596,7 @@ Permission record
- Human readable description of the permission
* - ``needs``
- 1
- :ref:`Needs object <sec-api-datamodel-access-needs>`
- :ref:`Needs object <sec-api-access-datamodel-general-needs>`
- Needs assigned to the permission
.. _sec-api-datamodel-access-groups:
-9
View File
@@ -589,15 +589,6 @@ Issue a file command
Requires the ``FILES_SELECT`` permission.
unselect
Unselects the currently selected file for printing.
Upon success, a status code of :http:statuscode:`204` and an empty body is returned. If no file is selected
or there already is an active print job, a :http:statuscode:`409` is returned. If path isn't ``current```
or the filename of the current selection, a :http:statuscode:`400` is returned
Requires the ``FILES_SELECT`` permission.
slice
Slices an STL file into GCODE. Note that this is an asynchronous operation that will take place in the background
after the response has been sent back to the client. Additional parameters are:
+3 -18
View File
@@ -44,7 +44,8 @@ For testing purposes it is also possible to supply the API key via a query param
Please be advised that clients should use the header field variant if at all possible.
If the key is missing or invalid, OctoPrint will treat the request as it would any unauthenticated anonymous request to the endpoint.
That means that any requests without or with an invalid API key targeting other API endpoints than :ref:`Login <sec-api-general-login>`
Consequently, if the bundled :ref:`ForceLogin plugin <sec-bundledplugins-forcelogin>` is active (which is the default), that means
that any requests without or with an invalid API key targeting other API endpoints than :ref:`Login <sec-api-general-login>`
will be denied with a :http:statuscode:`403`.
.. warning::
@@ -133,8 +134,7 @@ check the corresponding checkbox in the API settings dialog.
Support for CORS can be enabled in the "API" settings
.. warning::
.. note::
This means any browser page can send requests to the OctoPrint API. Authorization is still required however.
If CORS is not enabled you will get errors like the following::
@@ -142,15 +142,6 @@ If CORS is not enabled you will get errors like the following::
XMLHttpRequest cannot load http://localhost:8081/api/files. No 'Access-Control-Allow-Origin'
header is present on the requested resource.
.. note::
For security reasons, OctoPrint will not set the ``Access-Control-Allow-Credentials``
header, even if CORS support is enabled. That means that cookies will not be sent by
the browser to OctoPrint, effectively making it impossible to authenticate through
the login mechanism (or reusing an existing login session). When accessing OctoPrint
via CORS, you'll therefore always need to use an API key.
.. _sec-api-general-login:
Login
@@ -174,12 +165,6 @@ Login
mismatch or an unknown user. That was incompatible with basic authentication since it was a wrong use of
the :http:statuscode:`401` code and got therefore changed as part of a bug fix.
.. note::
You cannot use this endpoint to login from a third party page via CORS, see above. You can however use it
to retrieve user information via passive login with an API key (e.g. if you need the ``session`` to authenticate
on the web socket.
:json passive: If present, performs a passive login only, returning information about the current user that's
active either through an existing session or the used API key
:json user: (active login only) Username
-4
View File
@@ -226,10 +226,6 @@ 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:
+1 -1
View File
@@ -8,7 +8,7 @@ Version information
Retrieve information regarding server and API version. Returns a JSON object with three keys, ``api`` containing
the API version, ``server`` containing the server version, ``text`` containing the server version including
the prefix ``OctoPrint`` (to determine that this is indeed a genuine OctoPrint instance).
the prefix ``OctoPrint `` (to determine that this is indeed a genuine OctoPrint instance).
**Example Request**
@@ -39,11 +39,13 @@ Supported action commands
notification <message>
Displays the notification ``<message>``
.. _sec-bundledplugins-action_command_notification-example:
.. _sec-bundledplugins-action_command_prompt-example:
Example communication with the firmware
---------------------------------------
.. _sec-bundledplugins-action_command_prompt-sourcecode:
To display the :ref:`above notification <fig-bundledplugins-action_command_notification-example>` the firmware sent this action command:
.. code-block:: none
+4 -2
View File
@@ -118,7 +118,8 @@ Announced Services
ZeroConf Service ``_http._tcp``
+++++++++++++++++++++++++++++++
OctoPrint will announce itself on the network via ZeroConf
If :ref:`pybonjour <sec-bundledplugins-discovery-firststeps-pybonjour>` is
correctly installed, OctoPrint will announce itself on the network via ZeroConf
as service ``_http._tcp``, with the TXT record containing the standard fields.
See also `this documentation of _http._tcp TXT records <http://www.dns-sd.org/txtrecords.html>`_
@@ -129,7 +130,8 @@ for more information.
ZeroConf Service ``_octoprint._tcp``
++++++++++++++++++++++++++++++++++++
OctoPrint will announce itself on the network via ZeroConf
If :ref:`pybonjour <sec-bundledplugins-discovery-firststeps-pybonjour>` is
correctly installed, OctoPrint will announce itself on the network via ZeroConf
as service ``_octoprint._tcp``. The TXT record may contain the following fields:
* ``path``: path prefix to actual OctoPrint instance, inherited from ``_http._tcp``
+1
View File
@@ -20,5 +20,6 @@ Bundled Plugins
gcodeviewer.rst
logging.rst
pluginmanager.rst
printer_safety_check.rst
softwareupdate.rst
virtual_printer.rst
-5
View File
@@ -197,24 +197,20 @@ types are currently recognized:
* ``prerelease``: ``True`` or ``False``, default ``False``, set to
``True`` to also include releases on Github marked as prerelease.
* ``prerelease_branches``: Prerelease channel definitions, optional. List of:
* ``branch``: Branch associated with the channel, acts as ID
* ``name``: Human readable name of the release channel
* ``commitish``: List of values to check against ``target_commitish``
field in Github release data - release will only be included if the
values match. Defaults to being unset, in which case the ``branch``
will be matched.
.. versionadded:: 1.2.16
* ``stable_branch``: Stable channel definition, optional. Structure:
* ``branch``: Branch associated with the channel, acts as ID
* ``name``: Human readable name of the release channel
* ``commitish``: List of values to check against ``target_commitish``
field in Github release data - release will only be included if the
values match. Defaults to being unset, in which case the ``branch``
will be matched.
.. versionadded:: 1.2.16
* ``prerelease_channel``: Release channel to limit updates to. If set only
those releases will be included if their ``target_commitish`` matches
@@ -222,7 +218,6 @@ types are currently recognized:
included in ``prerelease_channels`` or the ``stable_channel``. Only
taken into account if ``prerelease`` is ``true``.
.. versionadded:: 1.2.16
* ``release_compare``: Method to use to compare between current version
information and release versions on Github. One of ``python`` (version
comparison using ``pkg_resources.parse_version``, newer version detected
+1 -1
View File
@@ -35,7 +35,7 @@ The plugin supports the following configuration keys:
* ``plugin``: Whether to track plugin related events (install, uninstall, ...)
* ``update``: Whether to track update related events (update successful or not, ...)
* ``printer``: Whether to track printer related events (connected, firmware, ...)
* ``printer_safety_check``: Whether to track warnings of the Printer Safety Check plugin
* ``printer_safety_check``: Whether to track warnings of the :ref:`Printer Safety Check <sec-bundledplugins-printer_safety_check>`
* ``throttled``: Whether to track throttle events detected on the underlying system
.. _sec-bundledplugins-tracking-sourcecode:
+3 -8
View File
@@ -708,11 +708,6 @@ Use the following settings to configure the serial connection to the printer:
- M0
- M1
# Commands which should not be sent to the printer and just silently ignored.
# An example of when you may wish to use this could be useful if you wish to manually change a filament on M600,
# by using that as a Pausing command (below)
ignoredCommands:
# Commands which should cause OctoPrint to pause any ongoing prints.
pausingCommands:
- M0
@@ -909,9 +904,9 @@ Use the following settings to configure the server:
# Settings for further configuration of the cookies that OctoPrint sets (login, remember me, ...)
cookies:
# SameSite setting to use on the cookies. Possible values are None, Lax and Strict. Defaults to not set but
# be advised that many browsers now default to Lax unless set as Secure, explicitly setting the cookie type
# here and served over https, which causes issues with embedding OctoPrint in frames.
# SameSite setting to use on the cookies. Possible values are None, Lax and Strict. Defaults to None but
# be advised that browsers will soon force this to Lax unless also being set as Secure and served over
# https, which will cause issues with embedding OctoPrint in frames.
#
# See also https://www.chromestatus.com/feature/5088147346030592,
# https://www.chromestatus.com/feature/5633521622188032 and issue #3482
-103
View File
@@ -271,10 +271,6 @@ 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``
@@ -391,102 +387,3 @@ 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
-5
View File
@@ -607,11 +607,6 @@ 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
+1 -9
View File
@@ -38,8 +38,6 @@ 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::
@@ -72,8 +70,7 @@ 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. The individual properties
follow the common data model for :ref:`printer profiles <sec-api-printerprofiles-datamodel-profile>`.
information such as the extruder count, the build volume size, the filament diameter etc.
* ``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
@@ -110,11 +107,6 @@ 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::
+4
View File
@@ -89,6 +89,10 @@ connection options (``baseurl`` and ``apikey``) directly in the constructor or s
:ref:`Application Key Plugin <sec-bundledplugins-appkeys>`
A bundled plugin that implements an authorization workflow for third party clients. It adds various additional
methods to the JS Client Library.
:ref:`ForceLogin Plugin <sec-bundledplugins-forcelogin>`
A bundled plugin that disables anonymous access to the regular OctoPrint UI by implementing a custom UI and
various hooks. Utilizes the client library's :ref:`browser component <sec-jsclientlib-browser>` to login the
user.
.. toctree::
:maxdepth: 3
+3
View File
@@ -4,6 +4,7 @@ octoprint.plugin
----------------
.. automodule:: octoprint.plugin
:members:
.. _sec-modules-plugin-core:
@@ -11,6 +12,7 @@ octoprint.plugin.core
---------------------
.. automodule:: octoprint.plugin.core
:members:
.. _sec-modules-plugin-types:
@@ -18,3 +20,4 @@ octoprint.plugin.types
----------------------
.. automodule:: octoprint.plugin.types
:members:
+2
View File
@@ -4,6 +4,7 @@ octoprint.printer
-----------------
.. automodule:: octoprint.printer
:members:
.. _sec-modules-printer-profile:
@@ -11,3 +12,4 @@ octoprint.printer.profile
-------------------------
.. automodule:: octoprint.printer.profile
:members:
+1
View File
@@ -4,3 +4,4 @@ octoprint.settings
------------------
.. automodule:: octoprint.settings
:members:
+2
View File
@@ -4,6 +4,7 @@ octoprint.slicing
-----------------
.. automodule:: octoprint.slicing
:members:
.. _sec-modules-slicing-exceptions:
@@ -11,3 +12,4 @@ octoprint.slicing.exceptions
----------------------------
.. automodule:: octoprint.slicing.exceptions
:members:
+8 -108
View File
@@ -931,7 +931,7 @@ octoprint.comm.transport.serial.additional_port_names
.. versionadded:: 1.4.1
Return additional port names (not glob patterns!) to use as a serial connection to the printer. Expected to be
``list`` of ``string``.
``list`` of ``string``s.
Useful in combination with :ref:`octoprint.comm.transport.serial.factory <sec-plugins-hook-comm-transport-serial-factory>`
to implement custom serial-like ports through plugins.
@@ -1191,7 +1191,7 @@ octoprint.plugin.softwareupdate.check_config
See :ref:`here <sec-bundledplugins-softwareupdate-hooks-check_config>`.
.. _sec-plugins-hooks-plugin-printer-additional_state_data:
.. _sec-plugins-hooks-plugin-printer-additional_state_data
octoprint.printer.additional_state_data
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@@ -1201,7 +1201,7 @@ octoprint.printer.additional_state_data
.. versionadded:: 1.5.0
Use this to inject additional data into the data structure returned from the printer backend to the frontend
on the push socket or other registered :class:`octoprint.printer.PrinterCallback`. Anything you return here
on the push socket or other registered :ref:`~octoprint.printer.PrinterCallback`s. Anything you return here
will be located beneath ``plugins.<your plugin id>`` in the resulting initial and current data push structure.
The ``initial`` parameter will be ``True`` if this the additional update sent to the callback. Your handler should
@@ -1430,7 +1430,7 @@ octoprint.server.api.after_request
octoprint.server.api.before_request
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. py:function:: before_request_handlers_hook(*args, **kwargs)
.. py:function:: after_request_handlers_hook(*args, **kwargs)
.. versionadded:: 1.3.10
@@ -1600,6 +1600,8 @@ octoprint.server.sockjs.register
Handlers should return either ``True`` or ``False``. ``True`` signals to proceed with normal registration. ``False``
signals to not register the client.
See the bundled :ref:`Forcelogin Plugin <sec-bundledplugins-forcelogin>` for an example on how to utilize this.
:param object socket: the socket object which is about to be registered
:param object user: the user currently authenticated on the socket - might be None
:return: whether to proceed with registration (``True``) or not (``False``)
@@ -1618,6 +1620,8 @@ octoprint.server.sockjs.emit
Handlers should return either ``True`` to allow the message to be emitted, or ``False`` to prevent it.
See the bundled :ref:`Forcelogin Plugin <sec-bundledplugins-forcelogin>` for an example on how to utilize this.
:param object socket: the socket object on which a message is about to be emitted
:param object user: the user currently authenticated on the socket - might be None
:param string message: the message type about to be emitted
@@ -1625,110 +1629,6 @@ octoprint.server.sockjs.emit
:return: whether to proceed with sending the message (``True``) or not (``False``)
:rtype: boolean
.. _sec-plugins-hook-system-additional_commands:
octoprint.system.additional_commands
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. py:function:: additional_commands_hook(*args, **kwargs)
.. versionadded:: 1.7.0
Allows adding additional system commands into the system menu. Handlers must return
a list of system command definitions, each definition matching the following data
structure:
.. list-table::
:widths: 15 5 10 30
:header-rows: 1
* - Name
- Multiplicity
- Type
- Description
* - ``name``
- 1
- String
- The name to display in the menu.
* - ``action``
- 1
- String
- An identifier for the action, must only consist of lower case a-z, numbers, ``-`` and ``_`` (``[a-z0-9-_]``).
* - ``command``
- 1
- String
- The system command to execute.
* - ``confirm``
- 0..1
- String
- An optional message to show as a confirmation dialog before executing the command.
* - ``async``
- 0..1
- bool
- If ``True``, the command will be run asynchronously and the API call will return immediately after enqueuing it for execution.
* - ``ignore``
- 0..1
- bool
- If ``True``, OctoPrint will ignore the result of the command's (and ``before``'s, if set) execution and return a successful result regardless. Defaults to ``False``.
* - ``debug``
- 0..1
- bool
- If ``True``, the command will generate debug output in the log including the command line that's run. Use with care. Defaults to ``False``
* - ``before``
- 0..1
- callable
- Optional callable to execute before the actual ``command`` is run. If ``ignore`` is false and this fails in any way, the command will not run and an error returned.
.. code-block:: python
def get_additional_commands(*args, **kwargs):
return [
{
"name": "Just a test",
"action": "test",
"command": "logger This is just a test of an OctoPrint system command from a plugin",
"before": lambda: print("Hello World!")
}
]
__plugin_hooks__ = {
"octoprint.system.additional_commands": get_additional_commands
}
:return: a list of command specifications
:rtype: list
.. _sec-plugins-hook-systeminfo-additional_bundle_files:
octoprint.systeminfo.additional_bundle_files
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. py:function:: additional_bundle_files_hook(*args, **kwargs)
.. versionadded:: 1.7.0
Allows bundled plugins to extend the list of files to include in the systeminfo bundle.
Note that this hook will ignore third party plugins. Handlers must return a dictionary
mapping file names in the bundle to either local log paths on disk or a ``callable``
that will be called to generate the file's content inside the bundle.
**Example**
Add a plugin's ``console`` log file to the systeminfo bundle:
.. code-block:: python
def get_additional_bundle_files(*args, **kwargs):
console_log = self._settings.get_plugin_logfile_path(postfix="console")
return {os.path.basename(console_log): console_log}
__plugin_hooks__ = {
"octoprint.systeminfo.additional_bundle_files": get_additional_bundle_files
}
:return: a dictionary mapping bundle file names to bundle file content
:rtype: dict
.. _sec-plugins-hook-timelapse-extensions:
octoprint.timelapse.extensions
-6
View File
@@ -225,12 +225,6 @@ onUserPermissionsChanged(user)
will be provided as only parameter. Note that this may also be triggered for not logged in guests if the guest
group is modified. In this case ``user`` will be undefined.
onBeforePrintStart(callback)
Called before a print is started either by clicking the "Print" button in the state panel or the select & print icon
in the file list. The callback to actually proceed with starting the print is provided as the only parameter. By returning
``false`` from this, plugins may prevent a print from actually starting, optionally starting it at a later date by
calling ``callback`` themselves. This can be used for example to implement an additional confirmation dialog.
onTabChange(next, current)
Called before the main tab view switches to a new tab, so `before` the new tab becomes visible. Called with the
next (changed to) and current (still visible) tab's hash (e.g. ``#control``). Note that ``current`` might be undefined
+30 -37
View File
@@ -25,77 +25,70 @@ SETUP_REQUIRES = ["markdown>=3.1,<3.2"] # newer versions require Python 3
INSTALL_REQUIRES = [
# additional OctoPrint plugins that are maintained on a different release cycle
"OctoPrint-FileCheck>=2021.2.23",
"OctoPrint-FirmwareCheck>=2021.10.11",
"OctoPrint-PiSupport>=2021.10.28",
"OctoPrint-FirmwareCheck>=2021.2.4",
"OctoPrint-PiSupport>=2021.3.26",
# 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
"markupsafe>=1.1,<2.0", # Jinja dependency, newer versions require Python 3
"tornado==5.1.1", # newer versions require Python 3
"markdown>=3.1,<3.2", # newer versions require Python 3
"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
"flask>=1.1.4,<2", # newer versions require Python 3
"Jinja2>=2.11.3,<3", # newer versions require Python 3
"flask>=1.1.2,<2",
"Jinja2>=2.11.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", # newer versions require Python 3
"Flask-Babel>=1.0,<2",
"Flask-Assets>=2.0,<3",
"werkzeug>=1.0.1,<2", # newer versions require Python 3
"itsdangerous>=1.1.0,<2", # newer versions require Python 3
"cachelib>=0.1,<0.2", # newer versions require Python 3
"PyYAML>=5.4.1,<6",
"werkzeug>=1.0.1,<2",
"itsdangerous>=1.1.0,<2",
"cachelib>=0.1,<1",
"PyYAML>=5.3.1,<6",
"pyserial>=3.4,<4",
"netaddr>=0.8,<0.9", # changelog hints at breaking changes on minor version increases
"watchdog==0.10.4", # newer versions require Python 3
"sarge==0.1.6",
"netifaces>=0.11,<1",
"netaddr>=0.7.19,<1",
"watchdog==0.10.4", # watchdog dropped Py>3.6 on 0.10.5 point release...
"sarge==0.1.5post0",
"netifaces>=0.10.9,<1",
"pylru>=1.2,<2",
"pkginfo>=1.7.1,<2",
"requests>=2.26.0,<3",
"pkginfo>=1.5.0.1,<2",
"requests>=2.23.0,<3",
"semantic_version>=2.8.5,<3",
"psutil>=5.8,<6",
"Click>=7.1.2,<8", # newer versions require Python 3
"psutil>=5.7,<6",
"Click>=7.1.2,<8",
"future>=0.18.2,<1",
"websocket-client>=0.59,<1", # newer versions require Python 3
"emoji>=1.4.2,<2",
"sentry-sdk>=1.3.1,<2",
"websocket-client>=0.57,<1",
"wrapt>=1.12.1,<2",
"emoji>=0.5.4,<1",
"sentry-sdk>=0.15.1,<1",
"filetype>=1.0.7,<2",
"zipstream-new>=1.1.8,<1.2",
# vendor bundled dependencies
"unidecode>=0.04.14,<0.05", # dependency of awesome-slugify
"blinker>=1.4,<2", # dependency of flask_principal
]
# Python 2 specific requirements
INSTALL_REQUIRES_PYTHON2 = [
"feedparser>=5.2.1,<6", # newer versions require Python 3
"tornado==5.1.1", # newer versions require Python 3
"futures>=3.3,<4",
"monotonic>=1.6,<2",
"monotonic>=1.5,<2",
"scandir>=1.10,<2",
"chainmap>=1.0.3,<2",
"typing>=3.10.0.0,<4",
"typing>=3.7.4.1,<4",
"enum34>=1.1.10,<1.2",
"frozendict==1.2", # newer versions from different maintainer require Python 3
"colorlog<5", # newer versions require Python 3
# vendor bundled dependencies
"unidecode<1.3", # dependency of awesome-slugify, newer versions require Python 3
"frozendict>=1.2,<2",
]
# Python 3 specific requirements
INSTALL_REQUIRES_PYTHON3 = [
"feedparser>=6.0.8,<7",
"tornado>=6,<7", # tornado < 6 is incompatible with Python 3.10
"zeroconf>=0.33,<0.34", # breaking changes can happen on minor version increases
"immutabledict>=2.1,<3",
"pathvalidate>=2.4.1,<3",
"colorlog>=5.0.1,<6",
# vendor bundled dependencies
"unidecode", # dependency of awesome-slugify, leave w/o range to not cause dependency hell w/ Octolapse deps
"feedparser>=6.0.2,<7",
"zeroconf>=0.24,<0.25",
"immutabledict>=1.2.0,<2",
]
# OSX specific requirements
INSTALL_REQUIRES_OSX = [
"appdirs>=1.4.4,<2",
"appdirs>=1.4.4",
]
# Additional requirements for optional install options
+9 -26
View File
@@ -287,22 +287,11 @@ def init_logging(
# default logging configuration
if default_config is None:
simple_format = "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
default_config = {
"version": 1,
"formatters": {
"simple": {"format": simple_format},
"colored": {
"()": "colorlog.ColoredFormatter",
"format": "%(log_color)s" + simple_format + "%(reset)s",
"reset": True,
"log_colors": {
"DEBUG": "cyan",
"INFO": "white",
"WARNING": "yellow",
"ERROR": "red",
"CRITICAL": "bold_red",
},
"simple": {
"format": "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
},
"serial": {"format": "%(asctime)s - %(message)s"},
"timings": {"format": "%(asctime)s - %(message)s"},
@@ -312,7 +301,7 @@ def init_logging(
"console": {
"class": "octoprint.logging.handlers.OctoPrintStreamHandler",
"level": "DEBUG",
"formatter": "colored",
"formatter": "simple",
"stream": "ext://sys.stdout",
},
"file": {
@@ -745,7 +734,7 @@ def get_plugin_blacklist(settings, connectivity_checker=None):
import yaml
from octoprint.util import bom_aware_open
from octoprint.util.version import is_octoprint_compatible, is_python_compatible
from octoprint.util.version import is_octoprint_compatible
logger = log.getLogger(__name__ + ".startup")
@@ -776,19 +765,13 @@ def get_plugin_blacklist(settings, connectivity_checker=None):
):
continue
if "pythonversions" in entry and not is_python_compatible(
*entry["pythonversions"]
):
continue
if "pluginversions" in entry:
if "version" in entry:
logger.debug(
"Blacklisted plugin: {}, versions: {}".format(
entry["plugin"], ", ".join(entry["pluginversions"])
"Blacklisted plugin: {}, version: {}".format(
entry["plugin"], entry["version"]
)
)
for version in entry["pluginversions"]:
result.append((entry["plugin"], version))
result.append((entry["plugin"], entry["version"]))
elif "versions" in entry:
logger.debug(
"Blacklisted plugin: {}, versions: {}".format(
@@ -796,7 +779,7 @@ def get_plugin_blacklist(settings, connectivity_checker=None):
)
)
for version in entry["versions"]:
result.append((entry["plugin"], "=={}".format(version)))
result.append((entry["plugin"], version))
else:
logger.debug("Blacklisted plugin: {}".format(entry["plugin"]))
result.append(entry["plugin"])
+4 -34
View File
@@ -42,7 +42,7 @@ def get_systeminfo(environment_detector, connectivity_checker, additional_fields
return flattened
def get_systeminfo_bundle(systeminfo, logbase, printer=None, plugin_manager=None):
def get_systeminfo_bundle(systeminfo, logbase, printer=None):
from octoprint.util import to_bytes
systeminfotxt = []
@@ -83,41 +83,13 @@ def get_systeminfo_bundle(systeminfo, logbase, printer=None, plugin_manager=None
for log in (
"octoprint.log",
"serial.log",
"plugin_softwareupdate_console.log",
"plugin_pluginmanager_console.log",
):
logpath = os.path.join(logbase, log)
if os.path.exists(logpath):
z.write(logpath, arcname=log, compress_type=compress_type)
# add additional bundle contents from bundled plugins
if plugin_manager:
for name, hook in plugin_manager.get_hooks(
"octoprint.systeminfo.additional_bundle_files"
).items():
try:
plugin = plugin_manager.get_plugin_info(name)
if not plugin.bundled:
# we only support this for bundled plugins because we don't want
# third party logs to blow up the bundles
continue
logs = hook()
for log, content in logs.items():
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)
elif callable(content):
# content generating callable
z.writestr(log, to_bytes(content()), compress_type=compress_type)
except Exception:
logging.getLogger(__name__).exception(
"Error while retrieving additional bundle contents for plugin {}".format(
name
),
extra={"plugin": name},
)
return z
@@ -168,9 +140,7 @@ def systeminfo_command(ctx, path, **kwargs):
zipfilename = os.path.join(path, get_systeminfo_bundle_name())
click.echo("Writing systeminfo bundle to {}...".format(zipfilename))
z = get_systeminfo_bundle(
systeminfo, settings.getBaseFolder("logs"), plugin_manager=plugin_manager
)
z = get_systeminfo_bundle(systeminfo, settings.getBaseFolder("logs"))
try:
with open(zipfilename, "wb") as f:
for data in z:
-1
View File
@@ -106,7 +106,6 @@ class Events(object):
REGISTERED_MESSAGE_RECEIVED = "RegisteredMessageReceived"
COMMAND_SUPPRESSED = "CommandSuppressed"
INVALID_TOOL_REPORTED = "InvalidToolReported"
FILAMENT_CHANGE = "FilamentChange"
# Timelapse
CAPTURE_START = "CaptureStart"
+1 -16
View File
@@ -5,7 +5,7 @@ __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 logging
try:
@@ -25,20 +25,6 @@ from octoprint.util import get_fully_qualified_classname as fqcn
from octoprint.util import monotonic_time
from octoprint.util.platform import CLOSE_FDS
EMPTY_RESULT = {
"_empty": True,
"printingArea": {
"minX": 0,
"maxX": 0,
"minY": 0,
"maxY": 0,
"minZ": 0,
"maxZ": 0,
},
"dimensions": {"width": 0, "height": 0, "depth": 0},
"filament": {},
}
class QueueEntry(
collections.namedtuple(
@@ -503,7 +489,6 @@ class GcodeAnalysisQueue(AbstractAnalysisQueue):
raise RuntimeError(error.strip())
elif "EMPTY:" in output:
self._logger.info("Result is empty, no extrusions found")
result = copy.deepcopy(EMPTY_RESULT)
elif "RESULTS:" not in output:
raise RuntimeError("No analysis result found")
else:
+20 -14
View File
@@ -24,7 +24,7 @@ from past.builtins import basestring
import octoprint.filemanager
from octoprint.util import atomic_write, is_hidden_path, time_this, to_bytes, to_unicode
from octoprint.util.files import sanitize_filename
from octoprint.util.text import sanitize
class StorageInterface(object):
@@ -468,14 +468,13 @@ class LocalFileStorage(StorageInterface):
This storage type implements :func:`path_on_disk`.
"""
def __init__(self, basefolder, create=False, really_universal=False):
def __init__(self, basefolder, create=False):
"""
Initializes a ``LocalFileStorage`` instance under the given ``basefolder``, creating the necessary folder
if necessary and ``create`` is set to ``True``.
:param string basefolder: the path to the folder under which to create the storage
:param bool create: ``True`` if the folder should be created if it doesn't exist yet, ``False`` otherwise
:param bool really_universal: ``True`` if the file names should be forced to really universal, ``False`` otherwise
:param string basefolder: the path to the folder under which to create the storage
:param bool create: ``True`` if the folder should be created if it doesn't exist yet, ``False`` otherwise
"""
self._logger = logging.getLogger(__name__)
@@ -488,8 +487,6 @@ class LocalFileStorage(StorageInterface):
code=StorageError.INVALID_DIRECTORY,
)
self._really_universal = really_universal
import threading
self._metadata_lock_mutex = threading.RLock()
@@ -1168,10 +1165,22 @@ class LocalFileStorage(StorageInterface):
def sanitize_name(self, name):
"""
Raises a :class:`ValueError` for a ``name`` containing ``/`` or ``\\``. Otherwise
sanitizes the given ``name`` using ``octoprint.files.sanitize_filename``. Also
strips any leading ``.``.
slugifies the given ``name`` by converting it to ASCII, leaving ``-``, ``_``, ``.``,
``(``, and ``)`` as is.
"""
return sanitize_filename(name, really_universal=self._really_universal)
name = to_unicode(name)
if name is None:
return None
if "/" in name or "\\" in name:
raise ValueError("name must not contain / or \\")
result = sanitize(name, safe_chars="-_.()[] ").replace(" ", "_")
if result and result != "." and result != ".." and result[0] == ".":
# hidden files under *nix
result = result[1:]
return result
def sanitize_path(self, path):
"""
@@ -1190,10 +1199,7 @@ class LocalFileStorage(StorageInterface):
path_elements = path.split("/")
joined_path = self.basefolder
for path_element in path_elements:
if path_element == ".." or path_element == ".":
joined_path = os.path.join(joined_path, path_element)
else:
joined_path = os.path.join(joined_path, self.sanitize_name(path_element))
joined_path = os.path.join(joined_path, self.sanitize_name(path_element))
path = os.path.realpath(joined_path)
if not path.startswith(self.basefolder):
raise ValueError(
+2 -2
View File
@@ -83,7 +83,7 @@ class StreamWrapper(AbstractFileWrapper):
A wrapper allowing processing of one or more consecutive streams.
Arguments:
*streams: One or more :py:class:`io.IOBase` streams to process one after another to save to storage.
*streams: One or more :py:`io.IOBase` streams to process one after another to save to storage.
"""
def __init__(self, filename, *streams):
@@ -124,7 +124,7 @@ class MultiStream(io.RawIOBase):
their contents in the order they are provided to the constructor.
Arguments:
*streams: One or more :py:class:`io.IOBase` streams to concatenate.
*streams: One or more :py:`io.IOBase` streams to concatenate.
"""
def __init__(self, *streams):
+3 -3
View File
@@ -1,4 +1,6 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
"""
This module represents OctoPrint's plugin subsystem. This includes management and helper methods as well as the
registered plugin types.
@@ -12,7 +14,6 @@ registered plugin types.
.. autoclass:: PluginSettings
:members:
"""
from __future__ import absolute_import, division, print_function, unicode_literals
__author__ = "Gina Häußge <osd@foosel.net>"
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
@@ -66,8 +67,7 @@ def plugin_manager(
this defaults to the entry point ``octoprint.plugin``.
plugin_disabled_list (list): A list of plugin identifiers that are currently disabled. If not provided this
defaults to all plugins for which ``enabled`` is set to ``False`` in the settings.
plugin_blacklist (list): A list of plugin identifiers/identifier-requirement tuples
that are currently blacklisted.
plugin_blacklist (list): A list of plugin identifiers/identifier-version tuples that are currently blacklisted.
plugin_restart_needing_hooks (list): A list of hook namespaces which cause a plugin to need a restart in order
be enabled/disabled. Does not have to contain full hook identifiers, will be matched with startswith similar
to logging handlers
+193 -220
View File
@@ -1,4 +1,6 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
"""
In this module resides the core data structures and logic of the plugin system.
@@ -18,7 +20,6 @@ In this module resides the core data structures and logic of the plugin system.
:members:
"""
from __future__ import absolute_import, division, print_function, unicode_literals
__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"
@@ -68,182 +69,6 @@ def _load_module(name, spec):
return imp.load_module(name, f, filename, details)
def parse_plugin_metadata(path):
result = {}
logger = logging.getLogger(__name__)
if not path:
return result
if os.path.isdir(path):
path = os.path.join(path, "__init__.py")
if not os.path.isfile(path):
return result
if not path.endswith(".py"):
# we only support parsing plain text source files
return result
logger.debug("Parsing plugin metadata from AST of {}".format(path))
try:
import ast
with io.open(path, "rb") as f:
root = ast.parse(f.read(), filename=path)
assignments = list(
filter(lambda x: isinstance(x, ast.Assign) and x.targets, root.body)
)
function_defs = list(
filter(lambda x: isinstance(x, ast.FunctionDef) and x.name, root.body)
)
all_relevant = assignments + function_defs
def extract_target_ids(node):
return list(
map(
lambda x: x.id,
filter(lambda x: isinstance(x, ast.Name), node.targets),
)
)
def extract_names(node):
if isinstance(node, ast.Assign):
return extract_target_ids(node)
elif isinstance(node, ast.FunctionDef):
return [
node.name,
]
else:
return []
for key in (
ControlProperties.attr_name,
ControlProperties.attr_version,
ControlProperties.attr_author,
ControlProperties.attr_description,
ControlProperties.attr_url,
ControlProperties.attr_license,
ControlProperties.attr_pythoncompat,
):
for a in reversed(assignments):
targets = extract_target_ids(a)
if key in targets:
if isinstance(a.value, ast.Str):
result[key] = a.value.s
elif (
isinstance(a.value, ast.Call)
and hasattr(a.value, "func")
and a.value.func.id == "gettext"
and a.value.args
and isinstance(a.value.args[0], ast.Str)
):
result[key] = a.value.args[0].s
break
for key in (ControlProperties.attr_hidden,):
for a in reversed(assignments):
targets = extract_target_ids(a)
if key in targets:
if isinstance(a.value, ast.Name) and a.value.id in (
"True",
"False",
):
result[key] = bool(a.value.id)
break
for a in reversed(all_relevant):
targets = extract_names(a)
if any(map(lambda x: x in targets, ControlProperties.all())):
result["has_control_properties"] = True
break
except SyntaxError:
raise
except Exception:
logger.exception("Error while parsing AST from {}".format(path))
return result
class ControlProperties(object):
attr_name = "__plugin_name__"
""" Module attribute from which to retrieve the plugin's human readable name. """
attr_description = "__plugin_description__"
""" Module attribute from which to retrieve the plugin's description. """
attr_disabling_DISCOURAGED = "__plugin_disabling_discouraged__"
""" Module attribute from which to retrieve the reason why disabling the plugin is discouraged. Only effective if ``self.bundled`` is True. """
attr_version = "__plugin_version__"
""" Module attribute from which to retrieve the plugin's version. """
attr_author = "__plugin_author__"
""" Module attribute from which to retrieve the plugin's author. """
attr_url = "__plugin_url__"
""" Module attribute from which to retrieve the plugin's website URL. """
attr_license = "__plugin_license__"
""" Module attribute from which to retrieve the plugin's license. """
attr_pythoncompat = "__plugin_pythoncompat__"
"""
Module attribute from which to retrieve the plugin's python compatibility string.
If unset a default of ``>=2.7,<3`` will be assumed, meaning that the plugin will be considered compatible to
Python 2 but not Python 3.
To mark a plugin as Python 3 compatible, a string of ``>=2.7,<4`` is recommended.
Bundled plugins will automatically be assumed to be compatible.
"""
attr_hidden = "__plugin_hidden__"
"""
Module attribute from which to determine if the plugin's hidden or not.
Only evaluated for bundled plugins, in order to hide them from the Plugin Manager
and similar places.
"""
attr_hooks = "__plugin_hooks__"
""" Module attribute from which to retrieve the plugin's provided hooks. """
attr_implementation = "__plugin_implementation__"
""" Module attribute from which to retrieve the plugin's provided mixin implementation. """
attr_helpers = "__plugin_helpers__"
""" Module attribute from which to retrieve the plugin's provided helpers. """
attr_check = "__plugin_check__"
""" Module attribute which to call to determine if the plugin can be loaded. """
attr_load = "__plugin_load__"
""" Module attribute which to call when loading the plugin. """
attr_unload = "__plugin_unload__"
""" Module attribute which to call when unloading the plugin. """
attr_enable = "__plugin_enable__"
""" Module attribute which to call when enabling the plugin. """
attr_disable = "__plugin_disable__"
""" Module attribute which to call when disabling the plugin. """
default_pythoncompat = ">=2.7,<3"
@classmethod
def all(cls):
return [getattr(cls, key) for key in dir(cls) if key.startswith("attr_")]
_EntryPointOrigin = namedtuple(
"EntryPointOrigin", "type, entry_point, module_name, package_name, package_version"
)
@@ -335,6 +160,71 @@ class PluginInfo(object):
license (str): License of the plugin
"""
attr_name = "__plugin_name__"
""" Module attribute from which to retrieve the plugin's human readable name. """
attr_description = "__plugin_description__"
""" Module attribute from which to retrieve the plugin's description. """
attr_disabling_discouraged = "__plugin_disabling_discouraged__"
""" Module attribute from which to retrieve the reason why disabling the plugin is discouraged. Only effective if ``self.bundled`` is True. """
attr_version = "__plugin_version__"
""" Module attribute from which to retrieve the plugin's version. """
attr_author = "__plugin_author__"
""" Module attribute from which to retrieve the plugin's author. """
attr_url = "__plugin_url__"
""" Module attribute from which to retrieve the plugin's website URL. """
attr_license = "__plugin_license__"
""" Module attribute from which to retrieve the plugin's license. """
attr_pythoncompat = "__plugin_pythoncompat__"
"""
Module attribute from which to retrieve the plugin's python compatibility string.
If unset a default of ``>=2.7,<3`` will be assumed, meaning that the plugin will be considered compatible to
Python 2 but not Python 3.
To mark a plugin as Python 3 compatible, a string of ``>=2.7,<4`` is recommended.
Bundled plugins will automatically be assumed to be compatible.
"""
attr_hidden = "__plugin_hidden__"
"""
Module attribute from which to determine if the plugin's hidden or not.
Only evaluated for bundled plugins, in order to hide them from the Plugin Manager
and similar places.
"""
attr_hooks = "__plugin_hooks__"
""" Module attribute from which to retrieve the plugin's provided hooks. """
attr_implementation = "__plugin_implementation__"
""" Module attribute from which to retrieve the plugin's provided mixin implementation. """
attr_helpers = "__plugin_helpers__"
""" Module attribute from which to retrieve the plugin's provided helpers. """
attr_check = "__plugin_check__"
""" Module attribute which to call to determine if the plugin can be loaded. """
attr_load = "__plugin_load__"
""" Module attribute which to call when loading the plugin. """
attr_unload = "__plugin_unload__"
""" Module attribute which to call when unloading the plugin. """
attr_enable = "__plugin_enable__"
""" Module attribute which to call when enabling the plugin. """
attr_disable = "__plugin_disable__"
""" Module attribute which to call when disabling the plugin. """
def __init__(
self,
key,
@@ -538,9 +428,7 @@ class PluginInfo(object):
str: Name of the plugin, fallback is the plugin's identifier.
"""
return self._get_instance_attribute(
ControlProperties.attr_name,
defaults=(self._name, self.key),
incl_metadata=True,
self.__class__.attr_name, defaults=(self._name, self.key), incl_metadata=True
)
@property
@@ -554,9 +442,7 @@ class PluginInfo(object):
str or None: Description of the plugin.
"""
return self._get_instance_attribute(
ControlProperties.attr_description,
default=self._description,
incl_metadata=True,
self.__class__.attr_description, default=self._description, incl_metadata=True
)
@property
@@ -571,7 +457,7 @@ class PluginInfo(object):
"""
return (
self._get_instance_attribute(
ControlProperties.attr_disabling_DISCOURAGED, default=False
self.__class__.attr_disabling_discouraged, default=False
)
if self.bundled
else False
@@ -590,7 +476,7 @@ class PluginInfo(object):
self._version
if self._version is not None
else self._get_instance_attribute(
ControlProperties.attr_version, default=self._version, incl_metadata=True
self.__class__.attr_version, default=self._version, incl_metadata=True
)
)
@@ -604,7 +490,7 @@ class PluginInfo(object):
str or None: Author of the plugin.
"""
return self._get_instance_attribute(
ControlProperties.attr_author, default=self._author, incl_metadata=True
self.__class__.attr_author, default=self._author, incl_metadata=True
)
@property
@@ -617,7 +503,7 @@ class PluginInfo(object):
str or None: Website URL for the plugin.
"""
return self._get_instance_attribute(
ControlProperties.attr_url, default=self._url, incl_metadata=True
self.__class__.attr_url, default=self._url, incl_metadata=True
)
@property
@@ -630,7 +516,7 @@ class PluginInfo(object):
str or None: License of the plugin.
"""
return self._get_instance_attribute(
ControlProperties.attr_license, default=self._license, incl_metadata=True
self.__class__.attr_license, default=self._license, incl_metadata=True
)
@property
@@ -643,7 +529,7 @@ class PluginInfo(object):
str: Python compatibility string of the plugin
"""
return self._get_instance_attribute(
ControlProperties.attr_pythoncompat, default=">=2.7,<3", incl_metadata=True
self.__class__.attr_pythoncompat, default=">=2.7,<3", incl_metadata=True
)
@property
@@ -655,7 +541,7 @@ class PluginInfo(object):
bool: Whether the plugin should be flagged as hidden or not
"""
return self._get_instance_attribute(
ControlProperties.attr_hidden, default=False, incl_metadata=True
self.__class__.attr_hidden, default=False, incl_metadata=True
)
@property
@@ -667,7 +553,7 @@ class PluginInfo(object):
Returns:
dict: Hooks provided by the plugin.
"""
return self._get_instance_attribute(ControlProperties.attr_hooks, default={})
return self._get_instance_attribute(self.__class__.attr_hooks, default={})
@property
def implementation(self):
@@ -679,7 +565,7 @@ class PluginInfo(object):
object: Implementation provided by the plugin.
"""
return self._get_instance_attribute(
ControlProperties.attr_implementation, default=None
self.__class__.attr_implementation, default=None
)
@property
@@ -691,7 +577,7 @@ class PluginInfo(object):
Returns:
dict: Helpers provided by the plugin.
"""
return self._get_instance_attribute(ControlProperties.attr_helpers, default={})
return self._get_instance_attribute(self.__class__.attr_helpers, default={})
@property
def check(self):
@@ -704,7 +590,7 @@ class PluginInfo(object):
otherwise.
"""
return self._get_instance_attribute(
ControlProperties.attr_check, default=lambda: True
self.__class__.attr_check, default=lambda: True
)
@property
@@ -717,7 +603,7 @@ class PluginInfo(object):
callable: Load method for the plugin module.
"""
return self._get_instance_attribute(
ControlProperties.attr_load, default=lambda: True
self.__class__.attr_load, default=lambda: True
)
@property
@@ -730,7 +616,7 @@ class PluginInfo(object):
callable: Unload method for the plugin module.
"""
return self._get_instance_attribute(
ControlProperties.attr_unload, default=lambda: True
self.__class__.attr_unload, default=lambda: True
)
@property
@@ -743,7 +629,7 @@ class PluginInfo(object):
callable: Enable method for the plugin module.
"""
return self._get_instance_attribute(
ControlProperties.attr_enable, default=lambda: True
self.__class__.attr_enable, default=lambda: True
)
@property
@@ -756,7 +642,7 @@ class PluginInfo(object):
callable: Disable method for the plugin module.
"""
return self._get_instance_attribute(
ControlProperties.attr_disable, default=lambda: True
self.__class__.attr_disable, default=lambda: True
)
def _get_instance_attribute(
@@ -784,7 +670,11 @@ class PluginInfo(object):
@property
def control_properties(self):
return ControlProperties.all()
return [
getattr(self.__class__, key)
for key in dir(self.__class__)
if key.startswith("attr_")
]
@property
def looks_like_plugin(self):
@@ -794,14 +684,113 @@ class PluginInfo(object):
return self.parsed_metadata.get("has_control_properties", False)
def _parse_metadata(self):
result = {}
path = self.location
if not path:
return result
if os.path.isdir(path):
path = os.path.join(self.location, "__init__.py")
if not os.path.isfile(path):
return result
if not path.endswith(".py"):
# we only support parsing plain text source files
return result
self._logger.debug(
"Parsing plugin metadata for {} from AST of {}".format(self.key, path)
)
try:
return parse_plugin_metadata(self.location)
import ast
with io.open(path, "rb") as f:
root = ast.parse(f.read(), filename=path)
assignments = list(
filter(lambda x: isinstance(x, ast.Assign) and x.targets, root.body)
)
function_defs = list(
filter(lambda x: isinstance(x, ast.FunctionDef) and x.name, root.body)
)
all_relevant = assignments + function_defs
def extract_target_ids(node):
return list(
map(
lambda x: x.id,
filter(lambda x: isinstance(x, ast.Name), node.targets),
)
)
def extract_names(node):
if isinstance(node, ast.Assign):
return extract_target_ids(node)
elif isinstance(node, ast.FunctionDef):
return [
node.name,
]
else:
return []
for key in (
self.__class__.attr_name,
self.__class__.attr_version,
self.__class__.attr_author,
self.__class__.attr_description,
self.__class__.attr_url,
self.__class__.attr_license,
self.__class__.attr_pythoncompat,
):
for a in reversed(assignments):
targets = extract_target_ids(a)
if key in targets:
if isinstance(a.value, ast.Str):
result[key] = a.value.s
elif (
isinstance(a.value, ast.Call)
and hasattr(a.value, "func")
and a.value.func.id == "gettext"
and a.value.args
and isinstance(a.value.args[0], ast.Str)
):
result[key] = a.value.args[0].s
break
for key in (self.__class__.attr_hidden,):
for a in reversed(assignments):
targets = extract_target_ids(a)
if key in targets:
if isinstance(a.value, ast.Name) and a.value.id in (
"True",
"False",
):
result[key] = bool(a.value.id)
break
for a in reversed(all_relevant):
targets = extract_names(a)
if any(map(lambda x: x in targets, self.control_properties)):
result["has_control_properties"] = True
break
except SyntaxError:
self._logger.exception(
"Invalid syntax in plugin file of plugin {}".format(self.key)
"Invalid syntax in {} for plugin {}".format(path, self.key)
)
self.invalid_syntax = True
return {}
except Exception:
self._logger.exception(
"Error while parsing AST from {} for plugin {}".format(path, self.key)
)
return result
class PluginManager(object):
@@ -848,27 +837,11 @@ class PluginManager(object):
if plugin_considered_bundled is None:
plugin_considered_bundled = []
processed_blacklist = []
for entry in plugin_blacklist:
if isinstance(entry, tuple):
key, version = entry
try:
processed_blacklist.append(
(key, pkg_resources.Requirement.parse(version))
)
except Exception:
self.logger.warning(
"Invalid version requirement {} for blacklist "
"entry {}, ignoring".format(version, key)
)
else:
processed_blacklist.append(entry)
self.plugin_folders = plugin_folders
self.plugin_bases = plugin_bases
self.plugin_entry_points = plugin_entry_points
self.plugin_disabled_list = plugin_disabled_list
self.plugin_blacklist = processed_blacklist
self.plugin_blacklist = plugin_blacklist
self.plugin_restart_needing_hooks = plugin_restart_needing_hooks
self.plugin_obsolete_hooks = plugin_obsolete_hooks
self.plugin_validators = plugin_validators
@@ -1337,7 +1310,7 @@ class PluginManager(object):
def matches_plugin(entry):
if isinstance(entry, (tuple, list)) and len(entry) == 2:
entry_key, entry_version = entry
return entry_key == key and version in entry_version
return entry_key == key and entry_version == version
return False
return any(map(lambda entry: matches_plugin(entry), self.plugin_blacklist))
+5 -4
View File
@@ -1,4 +1,6 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
"""
This module bundles all of OctoPrint's supported plugin implementation types as well as their common parent
class, :class:`OctoPrintPlugin`.
@@ -15,7 +17,6 @@ Please note that the plugin implementation types are documented in the section
:members:
"""
from __future__ import absolute_import, division, print_function, unicode_literals
__author__ = "Gina Häußge <osd@foosel.net>"
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
@@ -672,7 +673,7 @@ class UiPlugin(OctoPrintPlugin, SortablePlugin):
object.
Returns:
bool: ``True`` if the implementation will serve the request,
bool: ``True`` if the the implementation will serve the request,
``False`` otherwise.
"""
return False
@@ -1105,7 +1106,7 @@ class WizardPlugin(OctoPrintPlugin, ReloadNeedingPlugin):
* the current and seen versions are identical
* the current version is None and the seen version is not
* the seen version is not None and the current version is less or equal than the seen one
* the current version is less or equal than the seen one
.. code-block:: none
@@ -1157,7 +1158,7 @@ class WizardPlugin(OctoPrintPlugin, ReloadNeedingPlugin):
return (
(current == seen)
or (current is None and seen is not None)
or (seen is not None and current <= seen)
or (current <= seen)
)
@@ -209,6 +209,7 @@ $(function () {
}
})
.css({
"width": "auto",
"margin-left": function () {
return -($(this).width() / 2);
}
@@ -1,4 +1,4 @@
<div id="plugin_announcements_dialog" class="modal hide fade-in large" tabindex="-1" role="dialog" aria-labelledby="announcements_dialog_label" aria-hidden="true">
<div id="plugin_announcements_dialog" class="modal hide fade large" tabindex="-1" role="dialog" aria-labelledby="announcements_dialog_label" aria-hidden="true">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">&times;</button>
<h3 id="announcements_dialog_label">{{ _('Announcements') }}</h3>
@@ -1,4 +1,4 @@
<div id="plugin_appkeys_keygenerated" class="modal hide fade-in">
<div id="plugin_appkeys_keygenerated" class="modal hide fade">
<div class="modal-header">
<a href="javascript:void(0)" class="close" data-dismiss="modal" aria-hidden="true">&times;</a>
<h3 id="plugin_appkeys_keygenerated_title"></h3>
@@ -79,10 +79,10 @@
<p>{{ _('Create a new backup of the current state.') }}</p>
<form class="form-horizontal" onsubmit="return false;">
<div class="control-group" title="{{ _('All files in the uploads folder and subfolders. These are the files in the Files List, plus any metadata that has been generated for those files.')|edq }}">
<div class="control-group">
<div class="controls">
<label class="checkbox">
<input type="checkbox" data-bind="value: 'uploads', checked: excludeFromBackup"> {{ _('Exclude uploaded files (& associated metadata) from backup') }}
<input type="checkbox" data-bind="value: 'uploads', checked: excludeFromBackup"> {{ _('Exclude uploaded files & metadata from backup') }}
</label>
</div>
</div>
@@ -21,10 +21,10 @@ from octoprint.util.version import (
)
SENTRY_URL_SERVER = (
"https://6600411b6f6b4a959d53037e782a8f73@o118517.ingest.sentry.io/1373987"
"https://6a544965fe6c4c6eb96f7e39352b2924@o118517.ingest.sentry.io/1373987"
)
SENTRY_URL_COREUI = (
"https://72b9fc82150d47bead5c940ccbd05995@o118517.ingest.sentry.io/1374096"
"https://840570e9555741bcb82bd56a084fb46e@o118517.ingest.sentry.io/1374096"
)
SETTINGS_DEFAULTS = {
@@ -1,64 +0,0 @@
# -*- coding: utf-8 -*-
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()
@@ -1,59 +0,0 @@
/*
* 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"]
});
});
@@ -1,65 +0,0 @@
<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">&times;</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>
@@ -60,8 +60,6 @@ $(function () {
self.renderer_showRetracts = ko.observable(true);
self.renderer_showPrinthead = ko.observable(true);
self.renderer_showSegmentStarts = ko.observable(false);
self.renderer_showDebugArcs = ko.observable(false);
self.renderer_chromeArcFix = ko.observable(OctoPrint.coreui.browser.chrome);
self.renderer_showBoundingBox = ko.observable(false);
self.renderer_showLayerBoundingBox = ko.observable(false);
self.renderer_showFullSize = ko.observable(false);
@@ -99,8 +97,6 @@ $(function () {
showRetracts: self.renderer_showRetracts(),
showHead: self.renderer_showPrinthead(),
showSegmentStarts: self.renderer_showSegmentStarts(),
showDebugArcs: self.renderer_showDebugArcs(),
chromeArcFix: self.renderer_chromeArcFix(),
showBoundingBox: self.renderer_showBoundingBox(),
showLayerBoundingBox: self.renderer_showLayerBoundingBox(),
showFullSize: self.renderer_showFullSize(),
@@ -150,8 +146,6 @@ $(function () {
self.renderer_showRetracts.subscribe(self.rendererOptionUpdated);
self.renderer_showPrinthead.subscribe(self.rendererOptionUpdated);
self.renderer_showSegmentStarts.subscribe(self.rendererOptionUpdated);
self.renderer_showDebugArcs.subscribe(self.rendererOptionUpdated);
self.renderer_chromeArcFix.subscribe(self.rendererOptionUpdated);
self.renderer_showBoundingBox.subscribe(self.rendererOptionUpdated);
self.renderer_showLayerBoundingBox.subscribe(self.rendererOptionUpdated);
self.renderer_showFullSize.subscribe(self.rendererOptionUpdated);
@@ -414,8 +408,6 @@ $(function () {
self.renderer_showRetracts(true);
self.renderer_showPrinthead(true);
self.renderer_showSegmentStarts(false);
self.renderer_showDebugArcs(false);
self.renderer_chromeArcFix(OctoPrint.coreui.browser.chrome);
self.renderer_showBoundingBox(false);
self.renderer_showLayerBoundingBox(false);
self.renderer_showFullSize(false);
@@ -469,8 +461,8 @@ $(function () {
max: 1,
step: 1,
value: [0, 1],
enabled: false
//tooltip: "hide"
enabled: false,
tooltip: "hide"
})
.on("slide", self.changeCommandRange);
};
@@ -905,8 +897,6 @@ $(function () {
showRetracts: self.renderer_showRetracts(),
showPrinthead: self.renderer_showPrinthead(),
showSegmentStarts: self.renderer_showSegmentStarts(),
showDebugArcs: self.renderer_showDebugArcs(),
chromeArcFix: self.renderer_chromeArcFix(),
showPrevious: self.renderer_showPrevious(),
showCurrent: self.renderer_showCurrent(),
showNext: self.renderer_showNext(),
@@ -933,10 +923,6 @@ $(function () {
self.renderer_showPrinthead(current["showPrinthead"]);
if (current["showSegmentStarts"] !== undefined)
self.renderer_showSegmentStarts(current["showSegmentStarts"]);
if (current["showDebugArcs"] !== undefined)
self.renderer_showDebugArcs(current["showDebugArcs"]);
if (current["chromeArcFix"] !== undefined)
self.renderer_chromeArcFix(current["chromeArcFix"]);
if (current["showPrevious"] !== undefined)
self.renderer_showPrevious(current["showPrevious"]);
if (current["showCurrent"] !== undefined)
@@ -56,8 +56,6 @@ GCODE.renderer = (function () {
showHead: false,
showSegmentStarts: false,
sizeSegmentStart: 2 * pixelRatio,
showDebugArcs: false,
chromeArcFix: false,
moveModel: true,
zoomInOnModel: false,
@@ -347,80 +345,12 @@ GCODE.renderer = (function () {
};
}
// replace arc for chrome, code from https://stackoverflow.com/a/11689752
var bezierArc = function (x, y, radius, startAngle, endAngle, anticlockwise) {
// Signed length of curve
var signedLength;
var tau = 2 * Math.PI;
if (!anticlockwise && endAngle - startAngle >= tau) {
signedLength = tau;
} else if (anticlockwise && startAngle - endAngle >= tau) {
signedLength = -tau;
} else {
var delta = endAngle - startAngle;
signedLength = delta - tau * Math.floor(delta / tau);
// If very close to a full number of revolutions, make it full
if (Math.abs(delta) > 1e-12 && signedLength < 1e-12) signedLength = tau;
// Adjust if anti-clockwise
if (anticlockwise && signedLength > 0) signedLength = signedLength - tau;
}
// Minimum number of curves; 1 per quadrant.
var minCurves = Math.ceil(Math.abs(signedLength) / (Math.PI / 2));
// Number of curves; square-root of radius (or minimum)
var numCurves = Math.ceil(Math.max(minCurves, Math.sqrt(radius)));
// "Radius" of control points to ensure that the middle point
// of the curve is exactly on the circle radius.
var cpRadius = radius * (2 - Math.cos(signedLength / (numCurves * 2)));
// Angle step per curve
var step = signedLength / numCurves;
// Draw the circle
this.lineTo(x + radius * Math.cos(startAngle), y + radius * Math.sin(startAngle));
for (
var i = 0, a = startAngle + step, a2 = startAngle + step / 2;
i < numCurves;
++i, a += step, a2 += step
)
this.quadraticCurveTo(
x + cpRadius * Math.cos(a2),
y + cpRadius * Math.sin(a2),
x + radius * Math.cos(a),
y + radius * Math.sin(a)
);
};
var applyContextPatches = function () {
if (!ctx.origArc) ctx.origArc = ctx.arc;
ctx.circle = function (x, y, r) {
ctx.origArc(x, y, r, 0, 2 * Math.PI, true);
};
if (navigator.userAgent.toLowerCase().indexOf("chrome") > -1) {
if (renderOptions["chromeArcFix"]) {
ctx.arc = bezierArc;
log.info("Chrome Arc Fix enabled");
} else {
ctx.arc = ctx.origArc;
log.info("Chrome Arc Fix disabled");
}
}
};
var startCanvas = function () {
var jqueryCanvas = $(renderOptions["container"]);
//jqueryCanvas.css("background-color", renderOptions["bgColorOffGrid"]);
canvas = jqueryCanvas[0];
ctx = canvas.getContext("2d");
applyContextPatches();
canvas.style.height = canvas.height + "px";
canvas.style.width = canvas.width + "px";
canvas.height = canvas.height * pixelRatio;
@@ -614,7 +544,7 @@ GCODE.renderer = (function () {
// draw origin
ctx.beginPath();
ctx.circle(0, 0, 2);
ctx.arc(0, 0, 2, 0, Math.PI * 2, true);
ctx.stroke();
ctx.strokeStyle = renderOptions["colorGrid"];
@@ -658,7 +588,7 @@ GCODE.renderer = (function () {
// outline
var r = renderOptions["bed"]["r"];
ctx.circle(0, 0, r);
ctx.arc(0, 0, r, 0, Math.PI * 2, true);
// origin
ctx.moveTo(-1 * r, 0);
@@ -672,7 +602,7 @@ GCODE.renderer = (function () {
// draw origin
ctx.beginPath();
ctx.circle(0, 0, 2);
ctx.arc(0, 0, 2, 0, Math.PI * 2, true);
ctx.stroke();
ctx.strokeStyle = renderOptions["colorGrid"];
@@ -808,17 +738,6 @@ GCODE.renderer = (function () {
ctx.stroke();
};
var drawDebugArc = function (arc, ccw) {
ctx.moveTo(arc.x, arc.y);
ctx.lineTo(arc.startX, arc.startY);
ctx.moveTo(arc.x, arc.y);
ctx.lineTo(arc.endX, arc.endY);
ctx.moveTo(arc.startX, arc.startY);
ctx.lineTo(arc.endX, arc.endY);
ctx.moveTo(arc.startX, arc.startY);
ctx.arc(arc.x, arc.y, arc.r, arc.startAngle, arc.endAngle, ccw);
};
var drawLayer = function (layerNum, fromProgress, toProgress, isNotCurrentLayer) {
log.trace(
"Drawing layer " +
@@ -965,14 +884,14 @@ GCODE.renderer = (function () {
var prevPathType = "fill";
function strokePathIfNeeded(newPathType, strokeStyle) {
if (newPathType !== prevPathType || newPathType === "fill") {
if (prevPathType !== "fill") {
if (newPathType != prevPathType || newPathType == "fill") {
if (prevPathType != "fill") {
ctx.stroke();
}
prevPathType = newPathType;
ctx.beginPath();
if (newPathType !== "fill") {
if (newPathType != "fill") {
ctx.strokeStyle = strokeStyle;
ctx.moveTo(prevX, prevY);
}
@@ -1033,15 +952,14 @@ GCODE.renderer = (function () {
ctx.lineWidth = renderOptions["extrusionWidth"] * lineWidthFactor;
if (cmd.direction !== undefined && cmd.direction !== 0) {
var arc = getArcParams(cmd);
var ccw = cmd.direction < 0; // Y-axis is inverted so direction is also inverted
if (renderOptions["showDebugArcs"] && !isNotCurrentLayer) {
strokePathIfNeeded("debugarc", "#ff0000");
drawDebugArc(arc, ccw);
strokePathIfNeeded("extrude", getColorLineForTool(tool));
}
ctx.arc(arc.x, arc.y, arc.r, arc.startAngle, arc.endAngle, ccw);
ctx.arc(
arc.x,
arc.y,
arc.r,
arc.startAngle,
arc.endAngle,
cmd.direction < 0
); // Y-axis is inverted so direction is also inverted
} else {
ctx.lineTo(x, y);
}
@@ -1081,7 +999,7 @@ GCODE.renderer = (function () {
.alpha(alpha)
.html();
ctx.beginPath();
ctx.circle(prevX, prevY, sizeHeadSpot);
ctx.arc(prevX, prevY, sizeHeadSpot, 0, Math.PI * 2, true);
ctx.fill();
}
};
@@ -1254,7 +1172,6 @@ GCODE.renderer = (function () {
setOption: function (options) {
var mustRefresh = false;
var mustReset = false;
var mustReapplyPatches = false;
var dirty = false;
for (var opt in options) {
if (!renderOptions.hasOwnProperty(opt) || !options.hasOwnProperty(opt))
@@ -1271,8 +1188,7 @@ GCODE.renderer = (function () {
"zoomInOnModel",
"bed",
"invertAxes",
"onViewportChange",
"chromeArcFix"
"onViewportChange"
]) > -1
) {
mustRefresh = true;
@@ -1281,10 +1197,6 @@ GCODE.renderer = (function () {
if ($.inArray(opt, ["bed", "onViewportChange"]) > -1) {
mustReset = true;
}
if ($.inArray(opt, ["chromeArcFix"]) > -1) {
mustReapplyPatches = true;
}
}
if (!dirty) return;
@@ -1292,9 +1204,6 @@ GCODE.renderer = (function () {
if (mustReset) {
resetViewport();
}
if (mustReapplyPatches) {
applyContextPatches();
}
if (mustRefresh) {
this.refresh();
} else {
@@ -17,8 +17,10 @@
</div>
<div class="progress progress-text-centered">
<div class="bar" data-bind="style: { width: ui_progress_percentage() + '%' }"></div>
<span class="progress-text-back" data-bind="css: { 'progress-text-front': (ui_progress_percentage() >= 50), 'progress-text-back': (ui_progress_percentage() < 50) }, text: ui_progress_text()"></span>
<span class="progress-text-back" data-bind="text: ui_progress_text"></span>
<div class="bar" style="width: 0;" data-bind="style: { width: ui_progress_percentage() + '%' }">
<span class="progress-text-front" data-bind="copyWidth: ':parent :parent', text: ui_progress_text"></span>
</div>
</div>
<div class="row-fluid">
@@ -91,13 +93,6 @@
<label class="checkbox">
<input type="checkbox" data-bind="checked: renderer_showSegmentStarts">{{ _('Show segment starts') }}
</label>
<label class="checkbox">
<input type="checkbox" data-bind="checked: renderer_showDebugArcs">{{ _('Show debug arcs') }}
</label>
<label class="checkbox" data-bind="visible: OctoPrint.coreui.browser.chrome">
<input type="checkbox" data-bind="checked: renderer_chromeArcFix">{{ _('Apply arc fix') }} <span class="label">{{ _('Chrome') }}</span>
<span class="help-block">{{ _("See <a href='%(url)s' target='_blank'>issue #4117</a>.", url="https://github.com/OctoPrint/OctoPrint/issues/4117") }}</span>
</label>
</p>
<p>
<label class="checkbox">
@@ -109,7 +109,6 @@ def map_repository_entry(entry):
already_installed_string = "Requirement already satisfied (use --upgrade to upgrade)"
success_string = "Successfully installed"
failure_string = "Could not install"
python_mismatch_string = "requires a different Python:"
class PluginManagerPlugin(
@@ -248,12 +247,6 @@ class PluginManagerPlugin(
},
]
# Additional bundle contents
def get_additional_bundle_files(self, *args, **kwargs):
console_log = self._settings.get_plugin_logfile_path(postfix="console")
return {os.path.basename(console_log): console_log}
##~~ StartupPlugin
def on_after_startup(self):
@@ -965,22 +958,6 @@ class PluginManagerPlugin(
self._send_result_notification("install", result)
return result
if any(map(lambda x: python_mismatch_string in x, stderr)):
self._logger.error(
"Installing the plugin from {} failed, pip reported a Python version mismatch".format(
source
)
)
result = {
"result": False,
"source": source,
"source_type": source_type,
"reason": "Pip reported a Python version mismatch",
"faq": "https://faq.octoprint.org/plugin-python-mismatch",
}
self._send_result_notification("install", result)
return result
try:
result_line = list(
filter(
@@ -1135,42 +1112,6 @@ class PluginManagerPlugin(
destination = os.path.join(self._settings.global_get_basefolder("plugins"), name)
plugin_id, _ = os.path.splitext(name)
# check python compatibility
PYTHON_MISMATCH = {
"result": False,
"source": source,
"source_type": source_type,
"reason": "Plugin could not be installed",
"faq": "https://faq.octoprint.org/plugin-python-mismatch",
}
try:
metadata = octoprint.plugin.core.parse_plugin_metadata(path)
except SyntaxError:
self._logger.exception(
"Installing plugin from {} failed, there's a Python version mismatch".format(
source
)
)
result = PYTHON_MISMATCH
self._send_result_notification("install", result)
return result
pythoncompat = metadata.get(
octoprint.plugin.core.ControlProperties.attr_pythoncompat,
octoprint.plugin.core.ControlProperties.default_pythoncompat,
)
if not is_python_compatible(pythoncompat):
self._logger.exception(
"Installing plugin from {} failed, there's a Python version mismatch".format(
source
)
)
result = PYTHON_MISMATCH
self._send_result_notification("install", result)
return result
# copy plugin
try:
self._log_call("cp {} {}".format(path, destination))
shutil.copy(path, destination)
@@ -2164,7 +2105,6 @@ def __plugin_load__():
"octoprint.ui.web.templatetypes": __plugin_implementation__.get_template_types,
"octoprint.events.register_custom_events": _register_custom_events,
"octoprint.access.permissions": __plugin_implementation__.get_additional_permissions,
"octoprint.systeminfo.additional_bundle_files": __plugin_implementation__.get_additional_bundle_files,
}
global __plugin_helpers__
@@ -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:0px}#settings_plugin_pluginmanager_pluginlist table th.settings_plugin_plugin_manager_plugins_name,#settings_plugin_pluginmanager_pluginlist table td.settings_plugin_plugin_manager_plugins_name{text-overflow:ellipsis;text-align:left}#settings_plugin_pluginmanager_pluginlist table th.settings_plugin_plugin_manager_plugins_name .prop,#settings_plugin_pluginmanager_pluginlist table td.settings_plugin_plugin_manager_plugins_name .prop{white-space:nowrap}#settings_plugin_pluginmanager_pluginlist table th.settings_plugin_plugin_manager_plugins_actions,#settings_plugin_pluginmanager_pluginlist table td.settings_plugin_plugin_manager_plugins_actions{text-align:center;width:80px}#settings_plugin_pluginmanager_pluginlist table th.settings_plugin_plugin_manager_plugins_actions a,#settings_plugin_pluginmanager_pluginlist table td.settings_plugin_plugin_manager_plugins_actions a{text-decoration:none;color:#000}#settings_plugin_pluginmanager_pluginlist table th.settings_plugin_plugin_manager_plugins_actions a.disabled,#settings_plugin_pluginmanager_pluginlist table td.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 th.settings_plugin_plugin_manager_orphans_id,#settings_plugin_pluginmanager_orphanlist table td.settings_plugin_plugin_manager_orphans_id{text-overflow:ellipsis;text-align:left}#settings_plugin_pluginmanager_orphanlist table th.settings_plugin_plugin_manager_orphans_actions,#settings_plugin_pluginmanager_orphanlist table td.settings_plugin_plugin_manager_orphans_actions{text-align:center;width:80px}#settings_plugin_pluginmanager_orphanlist table th.settings_plugin_plugin_manager_orphans_actions a,#settings_plugin_pluginmanager_orphanlist table td.settings_plugin_plugin_manager_orphans_actions a{text-decoration:none;color:#000}#settings_plugin_pluginmanager_orphanlist table th.settings_plugin_plugin_manager_orphans_actions a.disabled,#settings_plugin_pluginmanager_orphanlist table td.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;padding-right:10px;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_unavailable,#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_empty{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_unavailable div,#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_empty 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:bold}#settings_plugin_pluginmanager_workingdialog_output .error{font-weight:bold;color:#990000}#settings_plugin_pluginmanager_workingdialog_output .stdout{color:#333333}#settings_plugin_pluginmanager_workingdialog_output .stderr{color:#990000}#settings_plugin_pluginmanager_workingdialog_output .call{color:#000099}
@@ -50,7 +50,7 @@ $(function () {
return !item.enabled;
}
},
"name",
"popularity",
[],
[
["bundled", "3rdparty"],
@@ -138,7 +138,7 @@ $(function () {
return !plugin.abandoned;
}
},
"popularity",
"title",
["filter_installed", "filter_incompatible"],
[],
0
@@ -424,7 +424,7 @@ $(function () {
self.uploadButton.bind("click", function () {
self._markWorking(
gettext("Installing plugin..."),
gettext("Installing plugin from uploaded file...")
gettext("Installing plugin from uploaded archive...")
);
data.formData = {
dependency_links: self.followDependencyLinks()
@@ -693,15 +693,11 @@ $(function () {
}
OctoPrint.plugins.pluginmanager
.getRepository(!!options.refresh, {ifModified: true})
.getRepository(!!options.refresh)
.fail(function () {
deferred.reject();
})
.done(function (data, status, xhr) {
// Don't update if cached - requires ifModified: true to pass through
// the 304 status, otherwise it fakes it and produces 200 all the time.
if (xhr.status === 304) return;
.done(function (data) {
self.fromRepositoryResponse(data.repository);
self.online(data.online !== undefined ? data.online : true);
deferred.resolveWith(data);
@@ -1217,7 +1213,7 @@ $(function () {
if (response.result) {
self._markDone();
} else {
self._markDone(response.reason, response.faq);
self._markDone(response.reason);
}
self._displayPluginManagementNotification(response, action, plugin);
@@ -1233,8 +1229,7 @@ $(function () {
self.logContents.steps.push({
action: action,
plugin: plugin,
result: response.result,
faq: response.faq
result: response.result
});
var title = gettext("Plugin management log");
@@ -1253,7 +1248,6 @@ $(function () {
steps = steps.slice(steps.length - 5);
}
var negativeResult = false;
_.each(steps, function (step) {
var line = undefined;
@@ -1295,14 +1289,7 @@ $(function () {
? '<i class="fa fa-check"></i>'
: '<i class="fa fa-remove"></i>'
}) +
(step.result === false && step.faq
? ' (<a href="" target="_blank" rel="noopener noreferer">' +
gettext("Why?") +
"</a>)"
: "") +
"</li>";
negativeResult = negativeResult || step.result === false;
});
text += "</ul></p>";
@@ -1394,8 +1381,6 @@ $(function () {
type = "warning";
}
if (negativeResult) type = "error";
var options = {
title: title,
text: text,
@@ -1443,22 +1428,11 @@ $(function () {
self.workingDialog.modal({keyboard: false, backdrop: "static", show: true});
};
self._markDone = function (error, faq) {
self._markDone = function (error) {
self.working(false);
if (error) {
self.loglines.push({line: gettext("Error!"), stream: "error"});
self.loglines.push({line: error, stream: "error"});
if (faq) {
self.loglines.push({
line: _.sprintf(
gettext(
"You can find more info on this issue in the FAQ at %(url)s"
),
{url: faq}
),
stream: "error"
});
}
} else {
self.loglines.push({line: gettext("Done!"), stream: "message"});
}
@@ -2,7 +2,7 @@
}
#settings_plugin_pluginmanager_pluginlist {
height: ~"calc(100vh - 450px)";
height: calc(100vh - 450px);
display: block;
width: auto;
overflow-x: hidden;
@@ -23,8 +23,7 @@
{% macro pluginmanager_throttled() %}
<div class="alert" data-bind="visible: throttled">{% trans %}
The system OctoPrint is running on is currently throttled. Due to that it's not possible to install new
plugins in order to avoid possible issues caused by system instability. Read more on
this in <a href="https://faq.octoprint.org/pi-issues" target="_blank" rel="noopener noreferrer">the FAQ</a>.
plugins in order to avoid possible issues caused by system instability.
{% endtrans %}</div>
{% endmacro %}
@@ -38,7 +37,7 @@
{% macro pluginmanager_requesterror() %}
<div class="alert" data-bind="visible: requestError()">{% trans %}
There appears to have been an error retrieving the plugin data from the backend. Please report this
in the bug tracker & be sure to include all requested information.
in the bug tracker & be sure to include all requested logs.
{% endtrans %}</div>
{% endmacro %}
@@ -62,7 +61,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="{{ url_for('index') }}plugin/pluginmanager/export"><i class="fas fa-download"></i> {{ _('Export') }}</a>
<a class="btn btn-small" href="/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>
@@ -189,7 +188,7 @@
</div>
</div>
<div id="settings_plugin_pluginmanager_workingdialog" class="modal hide fade-in">
<div id="settings_plugin_pluginmanager_workingdialog" class="modal hide fade">
<div class="modal-header">
<h3 data-bind="text: workingTitle"></h3>
</div>
@@ -201,7 +200,7 @@
</div>
</div>
<div id="settings_plugin_pluginmanager_repositorydialog" class="modal hide fade-in">
<div id="settings_plugin_pluginmanager_repositorydialog" class="modal hide fade">
<div class="modal-header">
<a href="#" class="close" data-dismiss="modal" aria-hidden="true">&times;</a>
<h3>{{ _('Install new Plugins...') }}</h3>
@@ -347,7 +346,7 @@
</div>
</div>
<div id="settings_plugin_pluginmanager_configurationdialog" class="modal hide fade-in">
<div id="settings_plugin_pluginmanager_configurationdialog" class="modal hide fade">
<div class="modal-header">
<a href="#" class="close" data-dismiss="modal" aria-hidden="true">&times;</a>
<h3>{{ _('Plugin Configuration') }}</h3>
+58 -327
View File
@@ -1,8 +1,6 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
import datetime
__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"
@@ -44,12 +42,10 @@ from octoprint.util.version import (
from . import cli, exceptions, updaters, util, version_checks
# 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"
# OctoPi 0.15+
MINIMUM_PYTHON = "2.7.9"
MINIMUM_SETUPTOOLS = "39.0.1"
MINIMUM_PIP = "9.0.3"
##~~ Plugin
@@ -70,8 +66,6 @@ class SoftwareUpdatePlugin(
OCTOPRINT_RESTART_TYPES = ("pip", "single_file_plugin")
VALID_RESTART_TYPES = ("octoprint", "environment")
DATA_FORMAT_VERSION = "v4"
CHECK_OVERLAY_KEY = "softwareupdate_check_overlay"
@@ -97,11 +91,6 @@ class SoftwareUpdatePlugin(
self._overlay_cache_ttl = 0
self._overlay_cache_timestamp = None
self._update_log = []
self._update_log_path = None
self._update_log_dirty = False
self._update_log_mutex = threading.RLock()
self._environment_supported = True
self._environment_versions = {}
self._environment_ready = threading.Event()
@@ -124,11 +113,6 @@ class SoftwareUpdatePlugin(
)
self._load_version_cache()
self._update_log_path = os.path.join(
self.get_plugin_data_folder(), "updatelog.yaml"
)
self._load_update_log()
self._overlay_cache_ttl = self._settings.get_int(["check_overlay_ttl"]) * 60
def refresh_checks(name, plugin):
@@ -167,38 +151,6 @@ class SoftwareUpdatePlugin(
},
]
# Additional bundle contents
def get_additional_bundle_files(self, *args, **kwargs):
console_log = self._settings.get_plugin_logfile_path(postfix="console")
def updatelog():
if not self._update_log:
self._load_update_log()
result = []
for entry in self._update_log:
line = "{datetime} - {display_name} - {current_version} -> {target_version} - {success} - {text}".format(
datetime=entry["datetime"].replace("T", " "),
display_name=entry["display_name"],
current_version=entry["current_version"],
target_version=entry["target_version"],
success="SUCCESS" if entry["success"] else "FAILED",
text=entry["text"]
+ (
" (Release notes: {})".format(entry["release_notes"])
if entry["release_notes"]
else ""
),
)
result.append(line)
return "\n".join(result)
return {
os.path.basename(console_log): console_log,
"plugin_softwareupdate_update.log": updatelog,
}
def on_startup(self, host, port):
console_logging_handler = logging.handlers.RotatingFileHandler(
self._settings.get_plugin_logfile_path(postfix="console"),
@@ -548,138 +500,6 @@ class SoftwareUpdatePlugin(
pass
self._version_cache_dirty = True
def _load_update_log(self):
if not os.path.isfile(self._update_log_path):
return
import yaml
try:
with io.open(self._update_log_path, "rt", encoding="utf-8") as f:
data = yaml.safe_load(f)
except Exception:
self._logger.exception("Error while loading update log from disk")
else:
# clean up data older than updatelog_cutoff hours
before_cleanup = len(data)
cutoff = (
datetime.datetime.now()
- datetime.timedelta(minutes=self._settings.get_int(["updatelog_cutoff"]))
).strftime(DATETIME_FORMAT)
data = sorted(
list(
filter(
lambda x: x.get("datetime") and x["datetime"] > cutoff,
data,
)
),
key=lambda x: x["datetime"],
)
cleaned_up = len(data) - before_cleanup
if cleaned_up:
self._logger.info(
"Cleaned up {} old update log entries".format(cleaned_up)
)
with self._update_log_mutex:
self._update_log = data
self._update_log_dirty = False
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(
sorted(self._update_log, key=lambda x: x["datetime"]),
stream=file_obj,
default_flow_style=False,
indent=2,
allow_unicode=True,
)
self._update_log_dirty = False
self._logger.info("Saved update log to disk")
def _add_update_log_entry(
self,
target,
current_version,
target_version,
success,
text,
display_name=None,
release_notes="",
save=True,
):
if display_name is None:
display_name = target
with self._update_log_mutex:
self._update_log.append(
{
"datetime": datetime.datetime.now().strftime(DATETIME_FORMAT),
"target": target,
"current_version": current_version,
"target_version": target_version,
"display_name": display_name,
"release_notes": release_notes if release_notes else "",
"success": success,
"text": text,
},
)
self._update_log_dirty = True
if save:
self._save_update_log()
def _is_octoprint_outdated_and_can_update(self):
checks = self._get_configured_checks()
check = checks.get("octoprint", None)
if not check:
return False
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
def get_settings_defaults(self):
@@ -724,14 +544,13 @@ class SoftwareUpdatePlugin(
},
},
"pip_command": None,
"cache_ttl": 24 * 60, # 1 day
"cache_ttl": 24 * 60,
"notify_users": True,
"ignore_throttled": False,
"minimum_free_storage": 150,
"check_overlay_url": "https://plugins.octoprint.org/update_check_overlay.json",
"check_overlay_py2_url": "https://plugins.octoprint.org/update_check_overlay_py2.json",
"check_overlay_ttl": 6 * 60, # 6 hours
"updatelog_cutoff": 30 * 24 * 60, # 30 days
"check_overlay_ttl": 6 * 60,
"credentials": {
"github": None,
"bitbucket_user": None,
@@ -787,7 +606,6 @@ class SoftwareUpdatePlugin(
else:
data["octoprint_checkout_folder"] = None
data["octoprint_type"] = None
data["octoprint_release_channel"] = None
# ~~ pip check settings
@@ -1104,43 +922,10 @@ class SoftwareUpdatePlugin(
# ~~ BluePrint API
@octoprint.plugin.BlueprintPlugin.route("/updatelog", methods=["GET"])
@no_firstrun_access
@Permissions.ADMIN.require(403)
def get_update_log(self):
def view():
return flask.jsonify(updatelog=list(reversed(self._update_log)))
def etag(lm=None):
hash = hashlib.sha1()
def hash_update(value):
value = value.encode("utf-8")
hash.update(value)
hash_update(repr(self._update_log))
return hash.hexdigest()
def lastmodified():
if os.path.exists(self._update_log_path):
return os.stat(self._update_log_path).st_mtime
else:
return 0
return with_revalidation_checking(
etag_factory=etag, lastmodified_factory=lastmodified
)(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()
and not self._settings.global_get(["server", "firstRun"])
):
flask.abort(403)
request_data = flask.request.values
if "targets" in request_data or "check" in request_data:
@@ -1290,13 +1075,9 @@ class SoftwareUpdatePlugin(
)(view)()
@octoprint.plugin.BlueprintPlugin.route("/update", methods=["POST"])
@no_firstrun_access
@Permissions.PLUGIN_SOFTWAREUPDATE_UPDATE.require(403)
def perform_update(self):
if (
not Permissions.PLUGIN_SOFTWAREUPDATE_UPDATE.can()
and not self._settings.global_get(["server", "firstRun"])
):
flask.abort(403)
throttled = self._get_throttled()
if (
throttled
@@ -1447,61 +1228,20 @@ class SoftwareUpdatePlugin(
def get_template_configs(self):
from flask_babel import gettext
templates = [
{"type": "settings", "name": gettext("Software Update")},
]
if self._is_wizard_update_required():
templates.append(
{
"type": "wizard",
"name": gettext("Update?"),
"template": "softwareupdate_wizard_update.jinja2",
"suffix": "_update",
}
)
if self._is_settings_wizard_required():
templates.append(
{
"type": "wizard",
"name": gettext("Software Update"),
"template": "softwareupdate_wizard_settings.jinja2",
"suffix": "_settings",
}
)
return templates
return [{"type": "settings", "name": gettext("Software Update")}]
##~~ WizardPlugin API
def _is_wizard_update_required(self):
firstrun = self._settings.global_get(["server", "firstRun"])
return (
firstrun
and self._is_octoprint_outdated_and_can_update()
and not self._is_settings_wizard_required()
)
def _is_settings_wizard_required(self):
def is_wizard_required(self):
checks = self._get_configured_checks()
check = checks.get("octoprint", None)
checkout_folder = self._get_octoprint_checkout_folder(checks=checks)
return check and check.get("method") == "update_script" and not checkout_folder
def is_wizard_required(self):
return self._is_wizard_update_required() or self._is_settings_wizard_required()
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
return (
check
and "method" in check
and check["method"] == "update_script"
and not checkout_folder
)
##~~ EventHandlerPlugin API
@@ -1536,8 +1276,6 @@ class SoftwareUpdatePlugin(
if check_targets is None:
check_targets = list(checks.keys())
# TODO: caching doesn't take check_targets into account!
update_available = False
update_possible = False
information = {}
@@ -1634,9 +1372,28 @@ class SoftwareUpdatePlugin(
local_name = target_information["local"]["name"]
local_value = target_information["local"]["value"]
release_notes = self._get_release_notes(
target_information, populated_check
)
release_notes = None
if (
target_information
and target_information["remote"]
and target_information["remote"]["value"]
):
if (
"release_notes" in populated_check
and populated_check["release_notes"]
):
release_notes = populated_check["release_notes"]
elif "release_notes" in target_information["remote"]:
release_notes = target_information["remote"][
"release_notes"
]
if release_notes:
release_notes = release_notes.format(
octoprint_version=VERSION,
target_name=target_information["remote"]["name"],
target_version=target_information["remote"]["value"],
)
information[target] = {
"updateAvailable": target_update_available,
@@ -1705,24 +1462,6 @@ class SoftwareUpdatePlugin(
return information, update_available, update_possible
def _get_release_notes(self, information, populated_check):
release_notes = None
if information and information["remote"] and information["remote"]["value"]:
if populated_check.get("release_notes"):
release_notes = populated_check["release_notes"]
elif "release_notes" in information["remote"]:
release_notes = information["remote"]["release_notes"]
if release_notes:
release_notes = release_notes.format(
octoprint_version=VERSION,
target_name=information["remote"]["name"],
target_version=information["remote"]["value"],
)
return release_notes
def _get_check_hash(self, check):
def dict_to_sorted_repr(d):
lines = []
@@ -1946,7 +1685,15 @@ class SoftwareUpdatePlugin(
if target_result is not None:
target_results[target] = target_result
target_restart_type = self._get_restart_type(check)
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
# if our update requires a restart we have to determine which type
if restart_type is None or (
@@ -1959,9 +1706,6 @@ class SoftwareUpdatePlugin(
# we might have needed to update the config, so we'll save that now
self._settings.save()
# we also need to save our update log changes
self._save_update_log()
# also, we are now longer updating
self._update_in_progress = False
@@ -1977,7 +1721,16 @@ 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 = self._get_restart_command(restart_type)
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"]
)
if restart_command:
self._send_client_message(
"restarting",
@@ -2006,22 +1759,8 @@ class SoftwareUpdatePlugin(
information, update_available, update_possible, _, _ = self._get_current_version(
target, check, online=online, credentials=credentials
)
populated_check = self._populated_check(target, check)
def add_update_log(success, text):
self._add_update_log_entry(
target,
information["local"]["value"],
information["remote"]["value"],
success,
text,
display_name=populated_check["displayName"],
release_notes=self._get_release_notes(information, populated_check),
save=False,
)
if not update_available and not force:
add_update_log(False, "Target is already up to date")
return False, None
if not update_possible:
@@ -2030,7 +1769,6 @@ class SoftwareUpdatePlugin(
target
)
)
add_update_log(False, "Update not possible, missing information")
return False, None
if not information.get("compatible", True):
@@ -2039,7 +1777,6 @@ class SoftwareUpdatePlugin(
target
)
)
add_update_log(False, "Update is incompatible")
return False, None
# determine the target version to update to
@@ -2070,6 +1807,7 @@ class SoftwareUpdatePlugin(
### The actual update procedure starts here...
populated_check = self._populated_check(target, check)
try:
self._logger.info(
"Starting update of {} to {}...".format(target, target_version)
@@ -2108,7 +1846,6 @@ class SoftwareUpdatePlugin(
"reason": "Unknown update type",
},
)
add_update_log(False, "Update failed, unknown update type")
return False, None
except exceptions.CannotUpdateOffline:
@@ -2125,8 +1862,6 @@ class SoftwareUpdatePlugin(
"reason": "No internet connection",
},
)
add_update_log(False, "No internet connection")
return False, None
except Exception as e:
self._logger.exception(
@@ -2160,7 +1895,6 @@ class SoftwareUpdatePlugin(
"reason": "unknown",
},
)
add_update_log(False, "Update failed")
else:
# make sure that any external changes to config.yaml are loaded into the system
@@ -2172,8 +1906,6 @@ class SoftwareUpdatePlugin(
del self._version_cache[target]
self._version_cache_dirty = True
add_update_log(True, "Update successful")
return target_error, target_result
def _persist_check_current(self, target, check, current):
@@ -2477,5 +2209,4 @@ def __plugin_load__():
"octoprint.cli.commands": cli.commands,
"octoprint.events.register_custom_events": _register_custom_events,
"octoprint.access.permissions": __plugin_implementation__.get_additional_permissions,
"octoprint.systeminfo.additional_bundle_files": __plugin_implementation__.get_additional_bundle_files,
}
@@ -12,7 +12,6 @@
this.checkUrl = url + "check";
this.updateUrl = url + "update";
this.configureUrl = url + "configure";
this.updatelogUrl = url + "updatelog";
};
OctoPrintSoftwareUpdateClient.prototype.checkEntries = function (
@@ -89,10 +88,6 @@
return this.base.postJson(this.configureUrl, data, opts);
};
OctoPrintSoftwareUpdateClient.prototype.getUpdatelog = function (opts) {
return this.base.get(this.updatelogUrl, opts);
};
OctoPrintClient.registerPluginComponent(
"softwareupdate",
OctoPrintSoftwareUpdateClient
@@ -1 +1 @@
#settings_plugin_softwareupdate_updatelist{display:block;width:auto;overflow-x:hidden;padding-right:2px;margin-bottom:1em}div.swupdate-advanced{margin-bottom:5px}td.settings_plugin_softwareupdate_column_update{width:16px}td.settings_plugin_softwareupdate_column_update a{text-decoration:none;color:#000}td.settings_plugin_softwareupdate_column_information .line{display:block}td.settings_plugin_softwareupdate_column_information .settings_plugin_softwareupdate_release_channel{line-height:20px;height:20px;font-size:9px;margin-bottom:0;vertical-align:baseline}#settings_plugin_softwareupdate_updatelog_list .line{display:block}#settings_plugin_softwareupdate_updatelog_list td.settings_plugin_softwareupdate_column_datetime{width:150px}#settings_plugin_softwareupdate_workingdialog_output{font-size:.8em}#settings_plugin_softwareupdate_workingdialog_output .message{font-weight:700}#settings_plugin_softwareupdate_workingdialog_output .separator{font-weight:700;color:#666}#settings_plugin_softwareupdate_workingdialog_output .stdout{color:#333}#settings_plugin_softwareupdate_workingdialog_output .stderr{color:#900}#settings_plugin_softwareupdate_workingdialog_output .call{color:#009}#settings_plugin_softwareupdate_workingdialog_output .message_error{font-weight:700;color:#900}.softwareupdate_notification ul{margin:10px 0 10px 25px}.softwareupdate_notification ul .name{text-overflow:ellipsis;white-space:nowrap;overflow:hidden;display:block}
#settings_plugin_softwareupdate_updatelist{display:block;width:auto;overflow-x:hidden;padding-right:2px;margin-bottom:1em}div.swupdate-advanced{margin-bottom:5px}td.settings_plugin_softwareupdate_column_update{width:16px}td.settings_plugin_softwareupdate_column_update a{text-decoration:none;color:#000}td.settings_plugin_softwareupdate_column_information .line{display:block}td.settings_plugin_softwareupdate_column_information .settings_plugin_softwareupdate_release_channel{line-height:20px;height:20px;font-size:9px;margin-bottom:0;vertical-align:baseline}#settings_plugin_softwareupdate_workingdialog_output{font-size:.8em}#settings_plugin_softwareupdate_workingdialog_output .message{font-weight:700}#settings_plugin_softwareupdate_workingdialog_output .separator{font-weight:700;color:#666}#settings_plugin_softwareupdate_workingdialog_output .stdout{color:#333}#settings_plugin_softwareupdate_workingdialog_output .stderr{color:#900}#settings_plugin_softwareupdate_workingdialog_output .call{color:#009}#settings_plugin_softwareupdate_workingdialog_output .message_error{font-weight:700;color:#900}.softwareupdate_notification ul{margin:10px 0 10px 25px}.softwareupdate_notification ul .name{text-overflow:ellipsis;white-space:nowrap;overflow:hidden;display:block}
@@ -131,14 +131,6 @@ $(function () {
0
);
self.octoprintData = {
item: undefined,
current: ko.observable("unknown"),
available: ko.observable("unknown")
};
self.updatelog = ko.observableArray([]);
self.availableAndPossible = ko.pureComputed(function () {
return _.filter(self.versions.items(), function (info) {
return info.updateAvailable && info.updatePossible;
@@ -169,10 +161,6 @@ $(function () {
} else {
self._closePopup();
}
if (self.loginState.hasPermission(self.access.permissions.ADMIN)) {
self.requestUpdatelog();
}
};
self._showPopup = function (options, eventListeners, singleButtonNotify) {
@@ -306,79 +294,68 @@ $(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]);
});
};
return information;
};
self.fromCheckResponse = function (data, ignoreSeen, showIfNothingNew) {
self.cacheTimestamp(data.timestamp);
var versions = [];
_.each(data.information, function (value, key) {
self._enrichInformation(key, value);
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]);
});
};
versions.push(value);
});
self.versions.updateItems(versions);
@@ -579,16 +556,6 @@ $(function () {
});
};
self.fromUpdatelogResponse = function (response) {
self.updatelog(response.updatelog);
};
self.requestUpdatelog = function () {
OctoPrint.plugins.softwareupdate
.getUpdatelog()
.done(self.fromUpdatelogResponse);
};
self.iconTitleForEntry = function (data) {
if (data.updatePossible) {
return "";
@@ -688,7 +655,12 @@ $(function () {
};
self.performUpdate = function (force, items) {
if (!self.updateAccess()) return;
if (
!self.loginState.hasPermission(
self.access.permissions.PLUGIN_SOFTWAREUPDATE_UPDATE
)
)
return;
if (self.printerState.isPrinting()) return;
self.updateInProgress = true;
@@ -745,16 +717,13 @@ $(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.updateAccess()) {
if (
self.updateInProgress ||
!self.loginState.hasPermission(
self.access.permissions.PLUGIN_SOFTWAREUPDATE_UPDATE
)
) {
self._updateClicked = false;
return;
}
@@ -850,10 +819,8 @@ $(function () {
self._showWorkingDialog = function (title) {
if (
!(
self.loginState.hasPermission(
self.access.permissions.PLUGIN_SOFTWAREUPDATE_CHECK
) || CONFIG_FIRST_RUN
!self.loginState.hasPermission(
self.access.permissions.PLUGIN_SOFTWAREUPDATE_CHECK
)
) {
return;
@@ -930,21 +897,6 @@ $(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;
@@ -1187,8 +1139,7 @@ $(function () {
elements: [
"#settings_plugin_softwareupdate",
"#softwareupdate_confirmation_dialog",
"#wizard_plugin_softwareupdate_update",
"#wizard_plugin_softwareupdate_settings"
"#wizard_plugin_softwareupdate"
]
});
});
@@ -33,16 +33,6 @@ td.settings_plugin_softwareupdate_column_information {
}
}
#settings_plugin_softwareupdate_updatelog_list {
.line {
display: block;
}
td.settings_plugin_softwareupdate_column_datetime {
width: 150px;
}
}
#settings_plugin_softwareupdate_workingdialog_output {
font-size: 0.8em;
@@ -59,9 +59,6 @@
before trying to update. Take a look at the displayed warning in the navigation bar to learn about what is
wrong and to get hints on how to solve the problem.
</p>
<p>
Read more on this in <a href="https://faq.octoprint.org/pi-issues" target="_blank" rel="noopener noreferrer">the FAQ</a>.
</p>
{% endtrans %}</div>
<div class="alert" data-bind="visible: printerState.isPrinting()">{% trans %}
<p>
@@ -73,85 +70,54 @@
</p>
{% endtrans %}</div>
<ul class="nav nav-pills">
<li class="active">
<a href="#settings_plugin_softwareupdate_updates" data-toggle="tab">{{ _('Current versions') }}</a>
</li>
<li>
<a href="#settings_plugin_softwareupdate_updatelog" data-toggle="tab">{{ _('Update log') }}</a>
</li>
</ul>
<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>
<button class="btn btn-small" data-bind="click: function() { $root.showPluginSettings(); }" title="{{ _('Plugin Configuration')|edq }}"><i class="fas fa-wrench"></i></button>
</div>
<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>
<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>
<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}">
<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>
<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">
<a href="javascript:void(0)" data-bind="click: function() { $root.update(false, [$data]) }, visible: $root.enableUpdate() && updateAvailable && updatePossible" class="btn btn-primary pull-right">{{ _('Update') }}</a>
<strong data-bind="text: displayName"></strong>: <span data-bind="text: displayVersion"></span> <span data-bind="invisible: updatePossible"><i class="fas fa-exclamation-triangle" data-bind="css: {'fa-unlink': !online && information && information.needs_online, 'fa-exclamation-triangle': !(!online && information && information.needs_online)}, attr: {title: $root.iconTitleForEntry($data)}"></i></span><br>
<small data-bind="visible: compatible" class="muted">
<span data-bind="visible: releaseChannels && releaseChannels.available" class="line">{{ _('Release Channel:') }} <select class="settings_plugin_softwareupdate_release_channel" data-bind="visible: releaseChannels && releaseChannels.available, value: releaseChannels.current, options: releaseChannels.available, optionsText: 'name', optionsValue: 'channel'"></select> <a href="https://faq.octoprint.org/using-release-channels" target="_blank"><i class="fas fa-question-circle"></i></a></span>
<span class="line">{{ _('Installed:') }} <span data-bind="text: information.local.name"></span></span>
<span class="line">{{ _('Available:') }} <span data-bind="text: information.remote.name"></span></span>
<span class="line" data-bind="visible: releaseNotes">{{ _('Release Notes:') }} <a data-bind="attr: {href: releaseNotes}, text: releaseNotes" target="_blank" rel="noreferrer noopener"></a></span>
<span class="line text-error" data-bind="visible: error, text: $root.errorTextForEntry($data)"></span>
</small>
<small data-bind="visible: !compatible">
<span class="line text-error">{{ _('Newer versions of this plugin are not compatible to this setup.') }}</span>
</small>
</td>
</tr>
</tbody>
</table>
</div>
</div>
<div class="tab-pane" id="settings_plugin_softwareupdate_updatelog">
<h3>{{ _('Update log') }}</h3>
<div id="settings_plugin_softwareupdate_updatelog_list">
<table class="table table-striped table-hover table-condensed table-hover">
<tbody data-bind="foreach: updatelog">
<tr>
<td class="settings_plugin_softwareupdate_column_datetime" data-bind="text: datetime"></td>
<td>
<span class="line" data-bind="css: { 'text-error': !success, 'text-success': success }"><strong data-bind="text: display_name"></strong> <span data-bind="text: current_version"></span> ➡ <span data-bind="text: target_version"></span></span>
<span class="line" data-bind="text: text"></span>
<span class="line" data-bind="visible: release_notes"><a data-bind="attr: {href: release_notes}" target="_blank" rel="noreferrer noopener">{{ _('Release Notes') }}</a></span>
</td>
</tr>
</tbody>
</table>
</div>
<small>{{ _('Please note that the update log will only contain entries for updates performed through OctoPrint\'s Software Update plugin.') }}</small>
<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}">
<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>
<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">
<a href="javascript:void(0)" data-bind="click: function() { $root.update(false, [$data]) }, visible: $root.enableUpdate() && updateAvailable && updatePossible" class="btn btn-primary pull-right">{{ _('Update') }}</a>
<strong data-bind="text: displayName"></strong>: <span data-bind="text: displayVersion"></span> <span data-bind="invisible: updatePossible"><i class="fas fa-exclamation-triangle" data-bind="css: {'fa-unlink': !online && information && information.needs_online, 'fa-exclamation-triangle': !(!online && information && information.needs_online)}, attr: {title: $root.iconTitleForEntry($data)}"></i></span><br>
<small data-bind="visible: compatible" class="muted">
<span data-bind="visible: releaseChannels && releaseChannels.available" class="line">{{ _('Release Channel:') }} <select class="settings_plugin_softwareupdate_release_channel" data-bind="visible: releaseChannels && releaseChannels.available, value: releaseChannels.current, options: releaseChannels.available, optionsText: 'name', optionsValue: 'channel'"></select> <a href="https://faq.octoprint.org/using-release-channels" target="_blank"><i class="fas fa-question-circle"></i></a></span>
<span class="line">{{ _('Installed:') }} <span data-bind="text: information.local.name"></span></span>
<span class="line">{{ _('Available:') }} <span data-bind="text: information.remote.name"></span></span>
<span class="line" data-bind="visible: releaseNotes">{{ _('Release Notes:') }} <a data-bind="attr: {href: releaseNotes}, text: releaseNotes" target="_blank" rel="noreferrer noopener"></a></span>
<span class="line text-error" data-bind="visible: error, text: $root.errorTextForEntry($data)"></span>
</small>
<small data-bind="visible: !compatible">
<span class="line text-error">{{ _('Newer versions of this plugin are not compatible to this setup.') }}</span>
</small>
</td>
</tr>
</tbody>
</table>
</div>
<div id="settings_plugin_softwareupdate_configurationdialog" class="modal hide fade-in">
<div id="settings_plugin_softwareupdate_configurationdialog" class="modal hide fade">
<div class="modal-header">
<a href="#" class="close" data-dismiss="modal" aria-hidden="true">&times;</a>
<h3>{{ _('Plugin Configuration') }}</h3>
@@ -198,14 +164,14 @@
</div>
</div>
<div id="settings_plugin_softwareupdate_workingdialog" class="modal hide fade-in">
<div id="settings_plugin_softwareupdate_workingdialog" class="modal hide fade">
<div class="modal-header">
<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: $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>
<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>
</div>
<div class="modal-footer">
<button class="btn" data-dismiss="modal" data-bind="enable: !$root.working()" aria-hidden="true">{{ _('Close') }}</button>
@@ -1,9 +0,0 @@
<h3>{{ _('Update?') }}</h3>
{% trans %}<p>
You are about to set up OctoPrint <span data-bind="text: octoprintData.current"></span>
but <span data-bind="text: octoprintData.available"></span> is available. It is strongly
recommended to update to the latest version before you continue.
</p>{% endtrans %}
<a href="javascript:void(0)" data-bind="click: function() { $root.update(false, [$root.octoprintData.item]) }" class="btn btn-primary btn-block">{{ _('Update') }}</a>
+1 -35
View File
@@ -38,7 +38,6 @@ class TrackingPlugin(
octoprint.plugin.AssetPlugin,
octoprint.plugin.WizardPlugin,
octoprint.plugin.EventHandlerPlugin,
octoprint.plugin.SimpleApiPlugin,
):
def __init__(self):
self._environment = None
@@ -77,7 +76,6 @@ class TrackingPlugin(
"printer_safety_check": True,
"throttled": True,
"slicing": True,
"webui_load": True,
},
}
@@ -96,26 +94,6 @@ class TrackingPlugin(
# tracking was just enabled, let's start up tracking
self._start_tracking()
##~~ SimpleApiPlugin
def get_api_commands(self):
return {"track": ["event", "payload"]}
def on_api_command(self, command, data):
if command != "track":
return
event = data.pop("event")
if event == "webui_load":
payload = data.get("payload", {})
browser_name = payload.get("browser_name")
browser_version = payload.get("browser_version")
os_name = payload.get("os_name")
os_version = payload.get("os_version")
if all((browser_name, browser_version, os_name, os_version)):
self._track_webui_load(browser_name, browser_version, os_name, os_version)
##~~ EnvironmentDetectionPlugin
def on_environment_detected(self, environment, *args, **kwargs):
@@ -213,7 +191,7 @@ class TrackingPlugin(
##~~ AssetPlugin
def get_assets(self):
return {"js": ["js/usage.js"], "clientjs": ["clientjs/usage.js"]}
return {"js": ["js/usage.js"]}
##~~ WizardPlugin
@@ -302,18 +280,6 @@ class TrackingPlugin(
self._track("shutdown")
def _track_webui_load(self, browser_name, browser_version, os_name, os_version):
if not self._settings.get_boolean(["events", "webui_load"]):
return
self._track(
"webui_load",
browser_name=browser_name,
browser_version=browser_version,
os_name=os_name,
os_version=os_version,
)
def _track_plugin_event(self, event, payload):
if not self._settings.get_boolean(["events", "plugin"]):
return
@@ -1,23 +0,0 @@
(function (global, factory) {
if (typeof define === "function" && define.amd) {
define(["OctoPrintClient"], factory);
} else {
factory(global.OctoPrintClient);
}
})(this, function (OctoPrintClient) {
var OctoPrintTrackingClient = function (base) {
this.base = base;
};
OctoPrintTrackingClient.prototype.track = function (event, payload, opts) {
return this.base.simpleApiCommand(
"tracking",
"track",
{event: event, payload: payload},
opts
);
};
OctoPrintClient.registerPluginComponent("tracking", OctoPrintTrackingClient);
return OctoPrintTrackingClient;
});
@@ -10,15 +10,6 @@ $(function () {
self.active = ko.observable();
self.required = false;
self.onStartupComplete = function () {
OctoPrint.plugins.tracking.track("webui_load", {
browser_name: OctoPrint.coreui.browser.browser_name,
browser_version: OctoPrint.coreui.browser.browser_version,
os_name: OctoPrint.coreui.browser.os_name,
os_version: OctoPrint.coreui.browser.os_version
});
};
self.enableUsage = function () {
self.settingsViewModel.settings.plugins.tracking.enabled(true);
self.decision(true);
@@ -52,9 +52,6 @@
<label class="checkbox">
<input type="checkbox" data-bind="checked: settings.plugins.tracking.events.slicing"> {{ _('Onboard slicing actions') }}
</label>
<label class="checkbox">
<input type="checkbox" data-bind="checked: settings.plugins.tracking.events.webui_load"> {{ _('Web interface load') }}
</label>
</div>
</div>
</form>
@@ -30,7 +30,7 @@ class VirtualPrinterPlugin(
"smoothieTemperatureReporting": False,
"klipperTemperatureReporting": False,
"reprapfwM114": False,
"sdFiles": {"size": True, "longname": False, "longname_quoted": True},
"sdFiles": {"size": True, "longname": False},
"throttle": 0.01,
"sendWait": True,
"waitInterval": 1.0,
@@ -54,9 +54,7 @@ class VirtualPrinterPlugin(
"capabilities": {
"AUTOREPORT_TEMP": True,
"AUTOREPORT_SD_STATUS": True,
"AUTOREPORT_POS": False,
"EMERGENCY_PARSER": True,
"EXTENDED_M20": False,
},
"m114FormatString": "X:{x} Y:{y} Z:{z} E:{e[current]} Count: A:{a} B:{b} C:{c}",
"m105TargetFormatString": "{heater}:{actual:.2f}/ {target:.2f}",
@@ -188,7 +188,6 @@ class VirtualPrinter(object):
self._temperature_reporter = None
self._sdstatus_reporter = None
self._pos_reporter = None
self.current_line = 0
self.lastN = 0
@@ -608,7 +607,7 @@ class VirtualPrinter(object):
def _gcode_M20(self, data):
# type: (str) -> None
if self._sdCardReady:
self._listSd(incl_long="L" in data)
self._listSd()
# noinspection PyUnusedLocal
def _gcode_M21(self, data):
@@ -705,7 +704,26 @@ class VirtualPrinter(object):
# noinspection PyUnusedLocal
def _gcode_M114(self, data):
# type: (str) -> bool
output = self._generatePositionOutput()
m114FormatString = self._settings.get(["m114FormatString"])
e = {index: value for index, value in enumerate(self._lastE)}
e["current"] = self._lastE[self.currentExtruder]
e["all"] = " ".join(
[
"E{}:{}".format(num, self._lastE[self.currentExtruder])
for num in range(self.extruderCount)
]
)
output = m114FormatString.format(
x=self._lastX,
y=self._lastY,
z=self._lastZ,
e=e,
f=self._lastF,
a=int(self._lastX * 100),
b=int(self._lastY * 100),
c=int(self._lastZ * 100),
)
if not self._okBeforeCommandOutput:
ok = self._ok()
if ok:
@@ -732,22 +750,6 @@ class VirtualPrinter(object):
except AttributeError:
self._send("echo:")
def _gcode_M154(self, data):
# type: (str) -> None
matchS = re.search(r"S([0-9]+)", data)
if matchS is not None:
interval = int(matchS.group(1))
if self._pos_reporter is not None:
self._pos_reporter.cancel()
if interval > 0:
self._pos_reporter = RepeatedTimer(
interval, lambda: self._send(self._generatePositionOutput())
)
self._pos_reporter.start()
else:
self._pos_reporter = None
def _gcode_M155(self, data):
# type: (str) -> None
matchS = re.search(r"S([0-9]+)", data)
@@ -1413,13 +1415,10 @@ class VirtualPrinter(object):
except Exception:
self._logger.exception("While handling %r", data)
def _listSd(self, incl_long=False):
def _listSd(self):
if self._settings.get_boolean(["sdFiles", "size"]):
if self._settings.get_boolean(["sdFiles", "longname"]) or incl_long:
if self._settings.get_boolean(["sdFiles", "longname_quoted"]):
line = '{dosname} {size} "{name}"'
else:
line = "{dosname} {size} {name}"
if self._settings.get_boolean(["sdFiles", "longname"]):
line = "{dosname} {size} {name}"
else:
line = "{dosname} {size}"
else:
@@ -1499,29 +1498,6 @@ class VirtualPrinter(object):
else:
self._send("Not SD printing")
def _generatePositionOutput(self):
# type: () -> str
m114FormatString = self._settings.get(["m114FormatString"])
e = {index: value for index, value in enumerate(self._lastE)}
e["current"] = self._lastE[self.currentExtruder]
e["all"] = " ".join(
[
"E{}:{}".format(num, self._lastE[self.currentExtruder])
for num in range(self.extruderCount)
]
)
output = m114FormatString.format(
x=self._lastX,
y=self._lastY,
z=self._lastZ,
e=e,
f=self._lastF,
a=int(self._lastX * 100),
b=int(self._lastY * 100),
c=int(self._lastZ * 100),
)
return output
def _generateTemperatureOutput(self):
# type: () -> str
if self._settings.get_boolean(["repetierStyleTargetTemperature"]):
+2 -1
View File
@@ -1,4 +1,6 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
"""
This module defines the interface for communicating with a connected printer.
@@ -14,7 +16,6 @@ abstracted version of the actual printer communication.
.. autoclass:: PrinterCallback
:members:
"""
from __future__ import absolute_import, division, print_function, unicode_literals
__author__ = "Gina Häußge <osd@foosel.net>"
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
+2 -1
View File
@@ -1,4 +1,6 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
"""
This module contains printer profile related code.
@@ -139,7 +141,6 @@ A printer profile is a ``dict`` of the following structure:
.. autoclass:: InvalidProfileError
"""
from __future__ import absolute_import, division, print_function, unicode_literals
__author__ = "Gina Häußge <osd@foosel.net>"
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
+15 -13
View File
@@ -516,7 +516,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
)
)
command = "G0 {}".format(
command = "G1 {}".format(
" ".join(["{}{}".format(axis.upper(), amt) for axis, amt in axes.items()])
)
@@ -1191,8 +1191,6 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
statisticalTotalPrintTime,
statisticalTotalPrintTimeType,
)
if printTimeLeft is not None:
printTimeLeft = int(printTimeLeft)
except Exception:
self._logger.exception(
"Error while estimating print time via {}".format(estimator)
@@ -1333,29 +1331,33 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
self._logger.exception("Error generating fileData")
fileData = None
if fileData is not None:
if fileData.get("display"):
if "display" in fileData:
display_name = fileData["display"]
if isinstance(fileData.get("analysis"), dict):
if estimatedPrintTime is None and fileData["analysis"].get(
"estimatedPrintTime"
if "analysis" in fileData:
if (
estimatedPrintTime is None
and "estimatedPrintTime" in fileData["analysis"]
):
estimatedPrintTime = fileData["analysis"][
"estimatedPrintTime"
]
if fileData["analysis"].get("filament"):
if "filament" in fileData["analysis"]:
filament = fileData["analysis"]["filament"]
if isinstance(fileData.get("statistics"), dict):
if "statistics" in fileData:
printer_profile = (
self._printerProfileManager.get_current_or_default()["id"]
)
if printer_profile in fileData["statistics"].get(
"averagePrintTime", {}
if (
"averagePrintTime" in fileData["statistics"]
and printer_profile
in fileData["statistics"]["averagePrintTime"]
):
averagePrintTime = fileData["statistics"]["averagePrintTime"][
printer_profile
]
if printer_profile in fileData["statistics"].get(
"lastPrintTime", {}
if (
"lastPrintTime" in fileData["statistics"]
and printer_profile in fileData["statistics"]["lastPrintTime"]
):
lastPrintTime = fileData["statistics"]["lastPrintTime"][
printer_profile
+6 -11
View File
@@ -410,10 +410,7 @@ class Server(object):
storage_managers[
octoprint.filemanager.FileDestinations.LOCAL
] = octoprint.filemanager.storage.LocalFileStorage(
self._settings.getBaseFolder("uploads"),
really_universal=self._settings.getBoolean(
["feature", "enforceReallyUniversalFilenames"]
),
self._settings.getBaseFolder("uploads")
)
fileManager = octoprint.filemanager.FileManager(
@@ -1348,16 +1345,14 @@ class Server(object):
ReverseProxiedEnvironment,
)
app.config["TEMPLATES_AUTO_RELOAD"] = True
app.config["JSONIFY_PRETTYPRINT_REGULAR"] = False
# we must not set this before TEMPLATES_AUTO_RELOAD is set to True or that won't take
app.debug = self._debug
s = settings()
# setup octoprint's flask json serialization/deserialization
app.json_encoder = OctoPrintJsonEncoder
s = settings()
app.debug = self._debug
app.config["TEMPLATES_AUTO_RELOAD"] = True
app.config["JSONIFY_PRETTYPRINT_REGULAR"] = False
secret_key = s.get(["server", "secretKey"])
if not secret_key:
@@ -2058,11 +2053,11 @@ class Server(object):
"js/lib/moment-with-locales.min.js",
"js/lib/pusher.color.min.js",
"js/lib/detectmobilebrowser.js",
"js/lib/ua-parser.min.js",
"js/lib/md5.min.js",
"js/lib/bootstrap-slider-knockout-binding.js",
"js/lib/loglevel.min.js",
"js/lib/sockjs.min.js",
"js/lib/ResizeSensor.js",
"js/lib/hls.js",
"js/lib/less.js",
]
+23 -62
View File
@@ -37,11 +37,6 @@ 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 = {}
@@ -330,7 +325,7 @@ def _getFileList(
"resource": url_for(
".readGcodeFile",
target=FileDestinations.SDCARD,
filename=urlquote(f["name"]),
filename=f["name"],
_external=True,
)
},
@@ -392,7 +387,7 @@ def _getFileList(
"resource": url_for(
".readGcodeFile",
target=FileDestinations.LOCAL,
filename=urlquote(path + file_or_folder["name"]),
filename=path + file_or_folder["name"],
_external=True,
)
}
@@ -446,14 +441,14 @@ def _getFileList(
"resource": url_for(
".readGcodeFile",
target=FileDestinations.LOCAL,
filename=urlquote(file_or_folder["path"]),
filename=file_or_folder["path"],
_external=True,
),
"download": url_for("index", _external=True)
+ "downloads/files/"
+ FileDestinations.LOCAL
+ "/"
+ urlquote(file_or_folder["path"]),
+ file_or_folder["path"],
}
result.append(file_or_folder)
@@ -692,7 +687,7 @@ def uploadGcodeFile(target):
location = url_for(
".readGcodeFile",
target=FileDestinations.LOCAL,
filename=urlquote(filename),
filename=filename,
_external=True,
)
files.update(
@@ -707,7 +702,7 @@ def uploadGcodeFile(target):
+ "downloads/files/"
+ FileDestinations.LOCAL
+ "/"
+ urlquote(filename),
+ filename,
},
}
}
@@ -717,7 +712,7 @@ def uploadGcodeFile(target):
location = url_for(
".readGcodeFile",
target=FileDestinations.SDCARD,
filename=urlquote(sdFilename),
filename=sdFilename,
_external=True,
)
files.update(
@@ -769,7 +764,7 @@ def uploadGcodeFile(target):
location = url_for(
".readGcodeFile",
target=FileDestinations.LOCAL,
filename=urlquote(added_folder),
filename=added_folder,
_external=True,
)
folder = {
@@ -799,7 +794,6 @@ def gcodeFileCommand(filename, target):
# valid file commands, dict mapping command name to mandatory parameters
valid_commands = {
"select": [],
"unselect": [],
"slice": [],
"analyse": [],
"copy": ["destination"],
@@ -848,26 +842,6 @@ def gcodeFileCommand(filename, target):
filenameToSelect = fileManager.path_on_disk(target, filename)
printer.select_file(filenameToSelect, sd, printAfterLoading, user)
elif command == "unselect":
with Permissions.FILES_SELECT.require(403):
if not printer.is_ready():
return make_response(
"Printer is already printing, cannot unselect current file", 409
)
_, currentFilename = _getCurrentFile()
if currentFilename is None:
return make_response(
"Cannot unselect current file when there is no file selected", 409
)
if filename != currentFilename and filename != "current":
return make_response(
"Only the currently selected file can be unselected", 400
)
printer.unselect_file()
elif command == "slice":
with Permissions.SLICE.require(403):
if not _verifyFileExists(target, filename):
@@ -1039,10 +1013,7 @@ def gcodeFileCommand(filename, target):
abort(404, description="Unknown profile")
location = url_for(
".readGcodeFile",
target=target,
filename=urlquote(full_path),
_external=True,
".readGcodeFile", target=target, filename=full_path, _external=True
)
result = {
"name": destination,
@@ -1055,7 +1026,7 @@ def gcodeFileCommand(filename, target):
+ "downloads/files/"
+ target
+ "/"
+ urlquote(full_path),
+ full_path,
},
}
@@ -1096,25 +1067,18 @@ def gcodeFileCommand(filename, target):
target, dst_path, fileManager.sanitize_name(target, dst_name)
)
# Check for exception thrown by _verifyFolderExists, if outside the root directory
try:
if (
_verifyFolderExists(target, destination)
and sanitized_destination != filename
):
# destination is an existing folder and not ourselves (= display rename), we'll assume we are supposed
# to move filename to this folder under the same name
destination = fileManager.join_path(target, destination, name)
if (
_verifyFolderExists(target, destination)
and sanitized_destination != filename
):
# destination is an existing folder and not ourselves (= display rename), we'll assume we are supposed
# to move filename to this folder under the same name
destination = fileManager.join_path(target, destination, name)
if _verifyFileExists(target, destination) or _verifyFolderExists(
target, destination
):
abort(409, description="File or folder does already exist")
except Exception:
abort(
409, description="Exception thrown by storage, bad folder/file name?"
)
if _verifyFileExists(target, destination) or _verifyFolderExists(
target, destination
):
abort(409, description="File or folder does already exist")
is_file = fileManager.file_exists(target, filename)
is_folder = fileManager.folder_exists(target, filename)
@@ -1162,10 +1126,7 @@ def gcodeFileCommand(filename, target):
fileManager.move_folder(target, filename, destination)
location = url_for(
".readGcodeFile",
target=target,
filename=urlquote(destination),
_external=True,
".readGcodeFile", target=target, filename=destination, _external=True
)
result = {
"name": name,
@@ -1179,7 +1140,7 @@ def gcodeFileCommand(filename, target):
+ "downloads/files/"
+ target
+ "/"
+ urlquote(destination)
+ destination
)
r = make_response(jsonify(result), 201)
+3 -43
View File
@@ -6,7 +6,6 @@ __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
from flask import abort, jsonify, request
from flask_login import current_user
@@ -24,7 +23,6 @@ from octoprint.settings import settings, valid_boolean_trues
FOLDER_TYPES = ("uploads", "timelapse", "timelapse_tmp", "logs", "watched")
FOLDER_MAPPING = {"timelapseTmp": "timelapse_tmp"}
TIMELAPSE_BITRATE_PATTERN = re.compile(r"\d+[KMGTPEZY]?i?B?", flags=re.IGNORECASE)
def _lastmodified():
@@ -141,7 +139,6 @@ def getSettings():
"flipH": s.getBoolean(["webcam", "flipH"]),
"flipV": s.getBoolean(["webcam", "flipV"]),
"rotate90": s.getBoolean(["webcam", "rotate90"]),
"cacheBuster": s.getBoolean(["webcam", "cacheBuster"]),
},
"feature": {
"temperatureGraph": s.getBoolean(["feature", "temperatureGraph"]),
@@ -167,7 +164,6 @@ def getSettings():
"port": connectionOptions["portPreference"],
"baudrate": connectionOptions["baudratePreference"],
"exclusive": s.getBoolean(["serial", "exclusive"]),
"lowLatency": s.getBoolean(["serial", "lowLatency"]),
"portOptions": connectionOptions["ports"],
"baudrateOptions": connectionOptions["baudrates"],
"autoconnect": s.getBoolean(["serial", "autoconnect"]),
@@ -191,7 +187,6 @@ def getSettings():
"timeoutSdStatusAutoreport": s.getFloat(
["serial", "timeout", "sdStatusAutoreport"]
),
"timeoutPosAutoreport": s.getFloat(["serial", "timeout", "posAutoreport"]),
"timeoutBaudrateDetectionPause": s.getFloat(
["serial", "timeout", "baudrateDetectionPause"]
),
@@ -206,7 +201,6 @@ def getSettings():
"longRunningCommands": s.get(["serial", "longRunningCommands"]),
"checksumRequiringCommands": s.get(["serial", "checksumRequiringCommands"]),
"blockedCommands": s.get(["serial", "blockedCommands"]),
"ignoredCommands": s.get(["serial", "ignoredCommands"]),
"pausingCommands": s.get(["serial", "pausingCommands"]),
"emergencyCommands": s.get(["serial", "emergencyCommands"]),
"helloCommand": s.get(["serial", "helloCommand"]),
@@ -252,14 +246,10 @@ def getSettings():
"capAutoreportSdStatus": s.getBoolean(
["serial", "capabilities", "autoreport_sdstatus"]
),
"capAutoreportPos": s.getBoolean(
["serial", "capabilities", "autoreport_pos"]
),
"capBusyProtocol": s.getBoolean(["serial", "capabilities", "busy_protocol"]),
"capEmergencyParser": s.getBoolean(
["serial", "capabilities", "emergency_parser"]
),
"capExtendedM20": s.getBoolean(["serial", "capabilities", "extended_m20"]),
"resendRatioThreshold": s.getInt(["serial", "resendRatioThreshold"]),
"resendRatioStart": s.getInt(["serial", "resendRatioStart"]),
},
@@ -587,14 +577,8 @@ def _saveSettings(data):
abort(400, description="Invalid webcam.ffmpegCommandline setting")
else:
s.set(["webcam", "ffmpegCommandline"], commandline)
if "bitrate" in data["webcam"] and data["webcam"]["bitrate"]:
bitrate = str(data["webcam"]["bitrate"])
if not TIMELAPSE_BITRATE_PATTERN.match(bitrate):
abort(
400,
description="Invalid webcam.bitrate setting, needs to be a valid ffmpeg bitrate",
)
s.set(["webcam", "bitrate"], bitrate)
if "bitrate" in data["webcam"]:
s.set(["webcam", "bitrate"], data["webcam"]["bitrate"])
if "ffmpegThreads" in data["webcam"]:
s.setInt(["webcam", "ffmpegThreads"], data["webcam"]["ffmpegThreads"])
if "ffmpegVideoCodec" in data["webcam"] and data["webcam"][
@@ -609,8 +593,6 @@ def _saveSettings(data):
s.setBoolean(["webcam", "flipV"], data["webcam"]["flipV"])
if "rotate90" in data["webcam"]:
s.setBoolean(["webcam", "rotate90"], data["webcam"]["rotate90"])
if "cacheBuster" in data["webcam"]:
s.setBoolean(["webcam", "cacheBuster"], data["webcam"]["cacheBuster"])
if "feature" in data:
if "temperatureGraph" in data["feature"]:
@@ -661,7 +643,7 @@ def _saveSettings(data):
if "runAt" in data["gcodeAnalysis"]:
s.set(["gcodeAnalysis", "runAt"], data["gcodeAnalysis"]["runAt"])
if "bedZ" in data["gcodeAnalysis"]:
s.setFloat(["gcodeAnalysis", "bedZ"], data["gcodeAnalysis"]["bedZ"])
s.setBoolean(["gcodeAnalysis", "bedZ"], data["gcodeAnalysis"]["bedZ"])
if "serial" in data:
if "autoconnect" in data["serial"]:
@@ -672,8 +654,6 @@ def _saveSettings(data):
s.setInt(["serial", "baudrate"], data["serial"]["baudrate"])
if "exclusive" in data["serial"]:
s.setBoolean(["serial", "exclusive"], data["serial"]["exclusive"])
if "lowLatency" in data["serial"]:
s.setBoolean(["serial", "lowLatency"], data["serial"]["lowLatency"])
if "timeoutConnection" in data["serial"]:
s.setFloat(
["serial", "timeout", "connection"],
@@ -734,12 +714,6 @@ def _saveSettings(data):
data["serial"]["timeoutSdStatusAutoreport"],
min=0.0,
)
if "timeoutPosAutoreport" in data["serial"]:
s.setFloat(
["serial", "timeout", "posAutoreport"],
data["serial"]["timeoutPosAutoreport"],
min=0.0,
)
if "timeoutBaudrateDetectionPause" in data["serial"]:
s.setFloat(
["serial", "timeout", "baudrateDetectionPause"],
@@ -789,10 +763,6 @@ def _saveSettings(data):
data["serial"]["blockedCommands"], (list, tuple)
):
s.set(["serial", "blockedCommands"], data["serial"]["blockedCommands"])
if "ignoredCommands" in data["serial"] and isinstance(
data["serial"]["ignoredCommands"], (list, tuple)
):
s.set(["serial", "ignoredCommands"], data["serial"]["ignoredCommands"])
if "pausingCommands" in data["serial"] and isinstance(
data["serial"]["pausingCommands"], (list, tuple)
):
@@ -922,11 +892,6 @@ def _saveSettings(data):
["serial", "capabilities", "autoreport_sdstatus"],
data["serial"]["capAutoreportSdStatus"],
)
if "capAutoreportPos" in data["serial"]:
s.setBoolean(
["serial", "capabilities", "autoreport_pos"],
data["serial"]["capAutoreportPos"],
)
if "capBusyProtocol" in data["serial"]:
s.setBoolean(
["serial", "capabilities", "busy_protocol"],
@@ -937,11 +902,6 @@ def _saveSettings(data):
["serial", "capabilities", "emergency_parser"],
data["serial"]["capEmergencyParser"],
)
if "capExtendedM20" in data["serial"]:
s.setBoolean(
["serial", "capabilities", "extended_m20"],
data["serial"]["capExtendedM20"],
),
if "resendRatioThreshold" in data["serial"]:
s.setInt(
["serial", "resendRatioThreshold"], data["serial"]["resendRatioThreshold"]
+4 -52
View File
@@ -6,7 +6,6 @@ __copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms
import collections
import logging
import re
import threading
import psutil
@@ -16,7 +15,6 @@ from flask_babel import gettext
from octoprint.access.permissions import Permissions
from octoprint.logging import prefix_multilines
from octoprint.plugin import plugin_manager
from octoprint.server import NO_CONTENT
from octoprint.server.api import api
from octoprint.server.util.flask import get_remote_address, no_firstrun_access
@@ -100,7 +98,6 @@ def performSystemAction():
def retrieveSystemCommands():
return jsonify(
core=_to_client_specs(_get_core_command_specs()),
plugin=_to_client_specs(_get_plugin_command_specs()),
custom=_to_client_specs(_get_custom_command_specs()),
)
@@ -113,8 +110,6 @@ def retrieveSystemCommandsForSource(source):
specs = _get_core_command_specs()
elif source == "custom":
specs = _get_custom_command_specs()
elif source == "plugin":
specs = _get_plugin_command_specs()
else:
abort(404)
@@ -230,8 +225,6 @@ def _get_command_spec(source, action):
return _get_core_command_spec(action)
elif source == "custom":
return _get_custom_command_spec(action)
elif source == "plugin":
return _get_plugin_command_spec(action)
else:
return None
@@ -295,50 +288,6 @@ def _get_core_command_spec(action):
return available_actions[action]
_plugin_action_regex = re.compile(r"[a-z0-9_-]+")
def _get_plugin_command_specs(plugin=None):
specs = collections.OrderedDict()
hooks = plugin_manager().get_hooks("octoprint.system.additional_commands")
if plugin is not None:
if plugin in hooks:
hooks = {plugin: hooks[plugin]}
else:
hooks = {}
for name, hook in hooks.items():
try:
plugin_specs = hook()
for spec in plugin_specs:
action = spec.get("action")
if (
not action
or action == "divider"
or not _plugin_action_regex.match(action)
):
continue
action = name.lower() + ":" + action
copied = dict(spec)
copied["source"] = "plugin"
copied["action"] = action
specs[action] = copied
except Exception:
logging.getLogger(__name__).exception(
"Error while fetching additional actions from plugin {}".format(name),
extra={"plugin": name},
)
return specs
def _get_plugin_command_spec(action):
plugin = action.split(":", 1)[0]
available_actions = _get_plugin_command_specs(plugin=plugin)
return available_actions.get(action)
def _get_custom_command_specs():
specs = collections.OrderedDict()
dividers = 0
@@ -358,7 +307,10 @@ def _get_custom_command_specs():
def _get_custom_command_spec(action):
available_actions = _get_custom_command_specs()
return available_actions.get(action)
if action not in available_actions:
return None
return available_actions[action]
class CommandFailed(Exception):
+2 -7
View File
@@ -24,11 +24,6 @@ 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
@@ -145,7 +140,7 @@ def getTimelapseData():
finished_list = []
for f in files:
output = dict(f)
output["url"] = url_for("index") + "downloads/timelapse/" + urlquote(f["name"])
output["url"] = url_for("index") + "downloads/timelapse/" + f["name"]
finished_list.append(output)
result = {
@@ -165,7 +160,7 @@ def getTimelapseData():
@Permissions.TIMELAPSE_DOWNLOAD.require(403)
def downloadTimelapse(filename):
return redirect_to_tornado(
request, url_for("index") + "downloads/timelapse/" + urlquote(filename)
request, url_for("index") + "downloads/timelapse/" + filename
)
+3 -4
View File
@@ -567,10 +567,8 @@ class OctoPrintFlaskResponse(flask.Response):
if samesite is not None:
samesite = samesite.lower()
if samesite == "none":
# Must be string "None"
samesite = "None"
if samesite not in ("None", "strict", "lax"):
# If NoneType, the cookie is not set
samesite = None
if samesite not in (None, "strict", "lax"):
samesite = None
kwargs["samesite"] = samesite
@@ -1704,6 +1702,7 @@ def collect_core_assets(preferred_stylesheet="css"):
assets["js"] = [
"js/app/bindings/allowbindings.js",
"js/app/bindings/contextmenu.js",
"js/app/bindings/copywidth.js",
"js/app/bindings/invisible.js",
"js/app/bindings/popover.js",
"js/app/bindings/qrcode.js",
+1 -4
View File
@@ -27,7 +27,6 @@ from octoprint.access.users import LoginStatusListener
from octoprint.events import Events
from octoprint.settings import settings
from octoprint.util.json import dump as json_dump
from octoprint.util.version import get_python_version_string
class ThreadSafeSession(octoprint.vendor.sockjs.tornado.session.Session):
@@ -99,12 +98,11 @@ 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") in ("backup", "softwareupdate")
if payload.get("plugin") == "backup"
and settings().getBoolean(["server", "firstRun"])
else [Permissions.STATUS],
"*": [Permissions.STATUS],
@@ -223,7 +221,6 @@ class PrinterStateConnection(
"version": octoprint.server.VERSION,
"display_version": octoprint.server.DISPLAY_VERSION,
"branch": octoprint.server.BRANCH,
"python_version": get_python_version_string(),
"plugin_hash": plugin_hash.hexdigest(),
"config_hash": config_hash,
"debug": octoprint.server.debug,
+1 -5
View File
@@ -1571,7 +1571,6 @@ class SystemInfoBundleHandler(CorsSupportMixin, tornado.web.RequestHandler):
from octoprint.server import (
connectivityChecker,
environmentDetector,
pluginManager,
printer,
safe_mode,
)
@@ -1588,10 +1587,7 @@ class SystemInfoBundleHandler(CorsSupportMixin, tornado.web.RequestHandler):
)
z = get_systeminfo_bundle(
systeminfo,
settings().getBaseFolder("logs"),
printer=printer,
plugin_manager=pluginManager,
systeminfo, settings().getBaseFolder("logs"), printer=printer
)
self.set_header("Content-Type", "application/zip")
+31 -31
View File
@@ -1,4 +1,6 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
"""
This module represents OctoPrint's settings management. Within this module the default settings for the core
application are defined and the instance of the :class:`Settings` is held, which offers getter and setter
@@ -16,7 +18,6 @@ of various types and the configuration file itself.
:members:
:undoc-members:
"""
from __future__ import absolute_import, division, print_function, unicode_literals
__author__ = "Gina Häußge <osd@foosel.net>"
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
@@ -109,7 +110,6 @@ default_settings = {
"port": None,
"baudrate": None,
"exclusive": True,
"lowLatency": False,
"autoconnect": False,
"log": False,
"timeout": {
@@ -123,7 +123,6 @@ default_settings = {
"temperatureAutoreport": 2,
"sdStatus": 1,
"sdStatusAutoreport": 1,
"posAutoreport": 5,
"resendOk": 0.5,
"baudrateDetectionPause": 1.0,
"positionLogWait": 10.0,
@@ -136,7 +135,6 @@ default_settings = {
"blacklistedBaudrates": [],
"longRunningCommands": ["G4", "G28", "G29", "G30", "G32", "M400", "M226", "M600"],
"blockedCommands": ["M0", "M1"],
"ignoredCommands": [],
"pausingCommands": ["M0", "M1", "M25"],
"emergencyCommands": ["M112", "M108", "M410"],
"checksumRequiringCommands": ["M110"],
@@ -178,10 +176,8 @@ default_settings = {
"capabilities": {
"autoreport_temp": True,
"autoreport_sdstatus": True,
"autoreport_pos": True,
"busy_protocol": True,
"emergency_parser": True,
"extended_m20": True,
},
"resendRatioThreshold": 10,
"resendRatioStart": 100,
@@ -261,7 +257,7 @@ default_settings = {
"flipH": False,
"flipV": False,
"rotate90": False,
"ffmpegCommandline": '{ffmpeg} -r {fps} -i "{input}" -vcodec {videocodec} -threads {threads} -b:v {bitrate} -f {containerformat} -y {filters} "{output}"',
"ffmpegCommandline": '{ffmpeg} -r {fps} -i "{input}" -vcodec {videocodec} -threads {threads} -b {bitrate} -f {containerformat} -y {filters} "{output}"',
"timelapse": {
"type": "off",
"options": {},
@@ -269,7 +265,6 @@ default_settings = {
"fps": 25,
},
"cleanTmpAfterDays": 7,
"cacheBuster": False,
},
"gcodeAnalysis": {
"maxExtruders": 10,
@@ -290,7 +285,6 @@ default_settings = {
"uploadOverwriteConfirmation": True,
"autoUppercaseBlacklist": ["M117", "M118"],
"g90InfluencesExtruder": False,
"enforceReallyUniversalFilenames": False,
},
"folder": {
"uploads": None,
@@ -375,7 +369,6 @@ default_settings = {
"plugin_pluginmanager",
"plugin_softwareupdate",
"plugin_announcements",
"plugin_eventmanager",
"plugin_backup",
"plugin_tracking",
"plugin_errortracking",
@@ -383,7 +376,6 @@ default_settings = {
],
"usersettings": ["access", "interface"],
"wizard": [
"plugin_softwareupdate_update",
"plugin_backup",
"plugin_corewizard_acl",
"plugin_corewizard_onlinecheck",
@@ -440,10 +432,6 @@ default_settings = {
"name": "Suppress SD status messages",
"regex": r"(Send: (N\d+\s+)?M27)|(Recv: SD printing byte)|(Recv: Not SD printing)",
},
{
"name": "Suppress position messages",
"regex": r"(Send:\s+(N\d+\s+)?M114)|(Recv:\s+(ok\s+)?X:[+-]?([0-9]*[.])?[0-9]+\s+Y:[+-]?([0-9]*[.])?[0-9]+\s+Z:[+-]?([0-9]*[.])?[0-9]+\s+E\d*:[+-]?([0-9]*[.])?[0-9]+).*",
},
{"name": "Suppress wait responses", "regex": r"Recv: wait"},
{
"name": "Suppress processing responses",
@@ -757,17 +745,11 @@ class Settings(object):
def sanity_check_folders(self, folders=None):
if folders is None:
folders = default_settings["folder"].keys()
folder_map = {}
for folder in folders:
folder_map[folder] = self.getBaseFolder(
folder, check_writable=True, deep_check_writable=True
self.getBaseFolder(
folder, check_writable=True, deep_check_writable=True, log_error=True
)
# validate uniqueness of folder paths
if len(folder_map.values()) != len(set(folder_map.values())):
raise DuplicateFolderPaths(folders)
def _get_default_folder(self, type):
folder = default_settings["folder"][type]
if folder is None:
@@ -1054,6 +1036,7 @@ class Settings(object):
if migrate:
self._migrate_config()
self._validate_config()
self._forget_hashes()
@@ -1651,6 +1634,15 @@ class Settings(object):
return True
return False
def _validate_config(self):
# validate uniqueness of folder paths
folder_keys = self.get(["folder"], merged=True).keys()
folders = {
folder_key: self.getBaseFolder(folder_key) for folder_key in folder_keys
}
if len(folders.values()) != len(set(folders.values())):
raise DuplicateFolderPaths(folders)
def backup(self, suffix=None, path=None, ext=None, hidden=False):
import shutil
@@ -1912,6 +1904,7 @@ class Settings(object):
type,
create=True,
allow_fallback=True,
log_error=False,
check_writable=True,
deep_check_writable=False,
):
@@ -1932,20 +1925,23 @@ class Settings(object):
create=create,
check_writable=check_writable,
deep_check_writable=deep_check_writable,
log_error=log_error,
)
except Exception:
if folder != default_folder and allow_fallback:
self._logger.exception(
"Invalid configured {} folder at {}, attempting to "
"fall back on default folder at {}".format(
type, folder, default_folder
if log_error:
self._logger.error(
"Invalid configured {} folder at {}, attempting to "
"fall back on default folder at {}".format(
type, folder, default_folder
)
)
)
_validate_folder(
default_folder,
create=create,
check_writable=check_writable,
deep_check_writable=deep_check_writable,
log_error=log_error,
)
folder = default_folder
@@ -2223,7 +2219,9 @@ def _default_basedir(applicationName):
return os.path.expanduser(os.path.join("~", "." + applicationName.lower()))
def _validate_folder(folder, create=True, check_writable=True, deep_check_writable=False):
def _validate_folder(
folder, create=True, check_writable=True, deep_check_writable=False, log_error=False
):
logger = logging.getLogger(__name__)
if not os.path.exists(folder):
@@ -2236,7 +2234,8 @@ def _validate_folder(folder, create=True, check_writable=True, deep_check_writab
try:
os.makedirs(folder)
except Exception:
logger.exception("Could not create {}".format(folder))
if log_error:
logger.exception("Could not create {}".format(folder))
raise IOError(
"Folder for type {} at {} does not exist and creation failed".format(
type, folder
@@ -2268,5 +2267,6 @@ def _validate_folder(folder, create=True, check_writable=True, deep_check_writab
f.write("test")
os.remove(testfile)
except Exception:
logger.exception("Could not write test file to {}".format(testfile))
if log_error:
logger.exception("Could not write test file to {}".format(folder))
raise IOError(error)
+2 -1
View File
@@ -1,4 +1,6 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
"""
In this module the slicing support of OctoPrint is encapsulated.
@@ -11,7 +13,6 @@ In this module the slicing support of OctoPrint is encapsulated.
.. autoclass:: SlicingManager
:members:
"""
from __future__ import absolute_import, division, print_function, unicode_literals
__author__ = "Gina Häußge <osd@foosel.net>"
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
+2 -1
View File
@@ -1,4 +1,6 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
"""
Slicing related exceptions.
@@ -25,7 +27,6 @@ Slicing related exceptions.
:show-inheritance:
"""
from __future__ import absolute_import, division, print_function, unicode_literals
__author__ = "Gina Häußge <osd@foosel.net>"
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
+1 -1
View File
@@ -1 +1 @@
.btn{display:inline-block;*display:inline;*zoom:1;padding:4px 12px;margin-bottom:0;font-size:14px;line-height:20px;text-align:center;vertical-align:middle;cursor:pointer;color:#333;text-shadow:0 1px 1px rgba(255,255,255,.75);background-color:#f5f5f5;background-image:-moz-linear-gradient(top,#fff,#e6e6e6);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fff),to(#e6e6e6));background-image:-webkit-linear-gradient(top,#fff,#e6e6e6);background-image:-o-linear-gradient(top,#fff,#e6e6e6);background-image:linear-gradient(to bottom,#fff,#e6e6e6);background-repeat:repeat-x;*background-color:#e6e6e6;filter:progid:DXImageTransform.Microsoft.gradient(enabled=false);border:1px solid #ccc;*border:0;border-bottom-color:#b3b3b3;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;*margin-left:.3em;-webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05);box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05)}.btn.active,.btn.disabled,.btn:active,.btn:focus,.btn:hover,.btn[disabled]{color:#333;background-color:#e6e6e6;*background-color:#d9d9d9}.btn.active,.btn:active{background-color:#ccc \9}.btn:first-child{*margin-left:0}.btn:focus,.btn:hover{color:#333;text-decoration:none;background-position:0 -15px;-webkit-transition:background-position .1s linear;-moz-transition:background-position .1s linear;-o-transition:background-position .1s linear;transition:background-position .1s linear}.btn:focus{outline:#333 dotted thin;outline:-webkit-focus-ring-color auto 5px;outline-offset:-2px}.btn.active,.btn:active{background-image:none;outline:0;-webkit-box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05);box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05)}.btn.disabled,.btn[disabled]{cursor:default;background-image:none;opacity:.65;filter:alpha(opacity=65);-webkit-box-shadow:none;-moz-box-shadow:none;box-shadow:none}.btn-large{padding:11px 19px;font-size:17.5px;-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px}.btn-large [class*=" icon-"],.btn-large [class^=icon-]{margin-top:4px}.btn-small{padding:2px 10px;font-size:11.9px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.btn-small [class*=" icon-"],.btn-small [class^=icon-]{margin-top:0}.btn-mini [class*=" icon-"],.btn-mini [class^=icon-]{margin-top:-1px}.btn-mini{padding:0 6px;font-size:10.5px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.btn-block{display:block;width:100%;padding-left:0;padding-right:0;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}.btn-block+.btn-block{margin-top:5px}input[type=submit].btn-block,input[type=reset].btn-block,input[type=button].btn-block{width:100%}.btn-primary{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,.25);background-color:#006dcc;background-image:-moz-linear-gradient(top,#08c,#04c);background-image:-webkit-gradient(linear,0 0,0 100%,from(#08c),to(#04c));background-image:-webkit-linear-gradient(top,#08c,#04c);background-image:-o-linear-gradient(top,#08c,#04c);background-image:linear-gradient(to bottom,#08c,#04c);background-repeat:repeat-x;border-color:#04c #04c #002a80;border-color:rgba(0,0,0,.1) rgba(0,0,0,.1) rgba(0,0,0,.25);*background-color:#04c;filter:progid:DXImageTransform.Microsoft.gradient(enabled=false)}.btn-primary.active,.btn-primary.disabled,.btn-primary:active,.btn-primary:focus,.btn-primary:hover,.btn-primary[disabled]{color:#fff;background-color:#04c;*background-color:#003bb3}.btn-primary.active,.btn-primary:active{background-color:#039 \9}.btn-warning{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,.25);background-color:#faa732;background-image:-moz-linear-gradient(top,#fbb450,#f89406);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fbb450),to(#f89406));background-image:-webkit-linear-gradient(top,#fbb450,#f89406);background-image:-o-linear-gradient(top,#fbb450,#f89406);background-image:linear-gradient(to bottom,#fbb450,#f89406);background-repeat:repeat-x;border-color:#f89406 #f89406 #ad6704;border-color:rgba(0,0,0,.1) rgba(0,0,0,.1) rgba(0,0,0,.25);*background-color:#f89406;filter:progid:DXImageTransform.Microsoft.gradient(enabled=false)}.btn-warning.active,.btn-warning.disabled,.btn-warning:active,.btn-warning:focus,.btn-warning:hover,.btn-warning[disabled]{color:#fff;background-color:#f89406;*background-color:#df8505}.btn-warning.active,.btn-warning:active{background-color:#c67605 \9}.btn-danger{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,.25);background-color:#da4f49;background-image:-moz-linear-gradient(top,#ee5f5b,#bd362f);background-image:-webkit-gradient(linear,0 0,0 100%,from(#ee5f5b),to(#bd362f));background-image:-webkit-linear-gradient(top,#ee5f5b,#bd362f);background-image:-o-linear-gradient(top,#ee5f5b,#bd362f);background-image:linear-gradient(to bottom,#ee5f5b,#bd362f);background-repeaLine truncated
.btn{display:inline-block;*display:inline;*zoom:1;padding:4px 12px;margin-bottom:0;font-size:14px;line-height:20px;text-align:center;vertical-align:middle;cursor:pointer;color:#333;text-shadow:0 1px 1px rgba(255,255,255,.75);background-color:#f5f5f5;background-image:-moz-linear-gradient(top,#fff,#e6e6e6);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fff),to(#e6e6e6));background-image:-webkit-linear-gradient(top,#fff,#e6e6e6);background-image:-o-linear-gradient(top,#fff,#e6e6e6);background-image:linear-gradient(to bottom,#fff,#e6e6e6);background-repeat:repeat-x;*background-color:#e6e6e6;filter:progid:DXImageTransform.Microsoft.gradient(enabled=false);border:1px solid #ccc;*border:0;border-bottom-color:#b3b3b3;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;*margin-left:.3em;-webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05);box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05)}.btn.active,.btn.disabled,.btn:active,.btn:focus,.btn:hover,.btn[disabled]{color:#333;background-color:#e6e6e6;*background-color:#d9d9d9}.btn.active,.btn:active{background-color:#ccc \9}.btn:first-child{*margin-left:0}.btn:focus,.btn:hover{color:#333;text-decoration:none;background-position:0 -15px;-webkit-transition:background-position .1s linear;-moz-transition:background-position .1s linear;-o-transition:background-position .1s linear;transition:background-position .1s linear}.btn:focus{outline:#333 dotted thin;outline:-webkit-focus-ring-color auto 5px;outline-offset:-2px}.btn.active,.btn:active{background-image:none;outline:0;-webkit-box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05);box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05)}.btn.disabled,.btn[disabled]{cursor:default;background-image:none;opacity:.65;filter:alpha(opacity=65);-webkit-box-shadow:none;-moz-box-shadow:none;box-shadow:none}.btn-large{padding:11px 19px;font-size:17.5px;-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px}.btn-large [class*=" icon-"],.btn-large [class^=icon-]{margin-top:4px}.btn-small{padding:2px 10px;font-size:11.9px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.btn-small [class*=" icon-"],.btn-small [class^=icon-]{margin-top:0}.btn-mini [class*=" icon-"],.btn-mini [class^=icon-]{margin-top:-1px}.btn-mini{padding:0 6px;font-size:10.5px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.btn-block{display:block;width:100%;padding-left:0;padding-right:0;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}.btn-block+.btn-block{margin-top:5px}input[type=submit].btn-block,input[type=reset].btn-block,input[type=button].btn-block{width:100%}.btn-primary{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,.25);background-color:#006dcc;background-image:-moz-linear-gradient(top,#08c,#04c);background-image:-webkit-gradient(linear,0 0,0 100%,from(#08c),to(#04c));background-image:-webkit-linear-gradient(top,#08c,#04c);background-image:-o-linear-gradient(top,#08c,#04c);background-image:linear-gradient(to bottom,#08c,#04c);background-repeat:repeat-x;border-color:#04c #04c #002a80;border-color:rgba(0,0,0,.1) rgba(0,0,0,.1) rgba(0,0,0,.25);*background-color:#04c;filter:progid:DXImageTransform.Microsoft.gradient(enabled=false)}.btn-primary.active,.btn-primary.disabled,.btn-primary:active,.btn-primary:focus,.btn-primary:hover,.btn-primary[disabled]{color:#fff;background-color:#04c;*background-color:#003bb3}.btn-primary.active,.btn-primary:active{background-color:#039 \9}.btn-warning{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,.25);background-color:#faa732;background-image:-moz-linear-gradient(top,#fbb450,#f89406);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fbb450),to(#f89406));background-image:-webkit-linear-gradient(top,#fbb450,#f89406);background-image:-o-linear-gradient(top,#fbb450,#f89406);background-image:linear-gradient(to bottom,#fbb450,#f89406);background-repeat:repeat-x;border-color:#f89406 #f89406 #ad6704;border-color:rgba(0,0,0,.1) rgba(0,0,0,.1) rgba(0,0,0,.25);*background-color:#f89406;filter:progid:DXImageTransform.Microsoft.gradient(enabled=false)}.btn-warning.active,.btn-warning.disabled,.btn-warning:active,.btn-warning:focus,.btn-warning:hover,.btn-warning[disabled]{color:#fff;background-color:#f89406;*background-color:#df8505}.btn-warning.active,.btn-warning:active{background-color:#c67605 \9}.btn-danger{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,.25);background-color:#da4f49;background-image:-moz-linear-gradient(top,#ee5f5b,#bd362f);background-image:-webkit-gradient(linear,0 0,0 100%,from(#ee5f5b),to(#bd362f));background-image:-webkit-linear-gradient(top,#ee5f5b,#bd362f);background-image:-o-linear-gradient(top,#ee5f5b,#bd362f);background-image:linear-gradient(to bottom,#ee5f5b,#bd362f);background-repeaLine truncated
@@ -0,0 +1,48 @@
ko.bindingHandlers.copyWidth = {
init: function (element, valueAccessor, allBindings, viewModel, bindingContext) {
var node = ko.bindingHandlers.copyWidth._getReferenceNode(element, valueAccessor);
ko.bindingHandlers.copyWidth._setWidth(node, element);
ko.bindingHandlers.copyWidth._addResizeSensor(node, element);
},
update: function (element, valueAccessor, allBindings, viewModel, bindingContext) {
var node = ko.bindingHandlers.copyWidth._getReferenceNode(element, valueAccessor);
ko.bindingHandlers.copyWidth._setWidth(node, element);
ko.bindingHandlers.copyWidth._addResizeSensor(node, element);
},
_setWidth: function (node, element) {
var width = node.width();
if (!width) return;
if ($(element).width() === width) return;
element.style.width = width + "px";
},
_getReferenceNode: function (element, valueAccessor) {
var value = ko.utils.unwrapObservable(valueAccessor());
if (!value) return;
var parts = value.split(" ");
var node = $(element);
while (parts.length > 0) {
var part = parts.shift();
if (part === ":parent") {
node = node.parent();
} else {
var selector = part;
if (parts.length > 0) {
selector += " " + parts.join(" ");
}
node = $(selector, node);
break;
}
}
return node;
},
_addResizeSensor: function (node, element) {
if (element.copyWidthSensor) {
element.copyWidthSensor.detach();
delete element.copyWidthSensor;
}
element.copyWidthSensor = new ResizeSensor(node, function () {
ko.bindingHandlers.copyWidth._setWidth(node, element);
});
}
};
@@ -1,14 +1,8 @@
ko.bindingHandlers.invisible = {
init: function (element, valueAccessor, allBindings, viewModel, bindingContext) {
var val = ko.utils.unwrapObservable(valueAccessor());
if (!valueAccessor()) return;
ko.bindingHandlers.style.update(element, function () {
return {visibility: val ? "hidden" : "visible"};
});
},
update: function (element, valueAccessor, allBindings, viewModel, bindingContext) {
var val = ko.utils.unwrapObservable(valueAccessor());
ko.bindingHandlers.style.update(element, function () {
return {visibility: val ? "hidden" : "visible"};
return {visibility: "hidden"};
});
}
};
@@ -426,11 +426,5 @@
});
};
OctoPrintClient.escapePath = function (path) {
return _.map(path.split("/"), function (p) {
return encodeURIComponent(p);
}).join("/");
};
return OctoPrintClient;
});
+4 -4
View File
@@ -14,19 +14,19 @@
};
var resourceForLocation = function (location) {
return url + "/" + OctoPrintClient.escapePath(location);
return url + "/" + location;
};
var downloadForLocation = function (location) {
return downloadUrl + "/" + OctoPrintClient.escapePath(location);
return downloadUrl + "/" + location;
};
var downloadForEntry = function (location, filename) {
return downloadForLocation(location) + "/" + OctoPrintClient.escapePath(filename);
return downloadForLocation(location) + "/" + filename;
};
var resourceForEntry = function (location, filename) {
return resourceForLocation(location) + "/" + OctoPrintClient.escapePath(filename);
return resourceForLocation(location) + "/" + filename;
};
var preProcessList = function (response) {
@@ -11,15 +11,15 @@
var bulkDownloadUrl = "downloads/timelapses";
var timelapseUrl = function (filename) {
return url + "/" + OctoPrintClient.escapePath(filename);
return url + "/" + filename;
};
var timelapseDownloadUrl = function (filename) {
return downloadUrl + "/" + OctoPrintClient.escapePath(filename);
return downloadUrl + "/" + filename;
};
var unrenderedTimelapseUrl = function (name) {
return url + "/unrendered/" + OctoPrintClient.escapePath(name);
return url + "/unrendered/" + name;
};
var OctoPrintTimelapseClient = function (base) {
@@ -18,7 +18,6 @@ function DataUpdater(allViewModels, connectCallback, disconnectCallback) {
self._lastProcessingTimesSize = 20;
self._safeModePopup = undefined;
self._python2Popup = undefined;
self.increaseThrottle = function () {
self.setThrottle(self._throttleFactor + 1);
@@ -172,10 +171,7 @@ function DataUpdater(allViewModels, connectCallback, disconnectCallback) {
VERSION = data["version"];
DISPLAY_VERSION = data["display_version"];
BRANCH = data["branch"];
PYTHON_VERSION = data["python_version"];
$("span.version").text(DISPLAY_VERSION);
$("span.python_version").text(PYTHON_VERSION);
// update connectivity state
ONLINE = data["online"];
@@ -234,22 +230,6 @@ function DataUpdater(allViewModels, connectCallback, disconnectCallback) {
});
}
// process python version
if (self._python2Popup) self._python2Popup.remove();
if (PYTHON_VERSION && PYTHON_VERSION.startsWith("2.")) {
self._python2Popup = new PNotify({
title: gettext("You are still running Python 2"),
text: _.sprintf(
gettext(
"<p>Python 2 is end-of-life as of January 1st 2020. While OctoPrint currently still supports running under Python 2, a future version will remove support and require Python 3. You should upgrade as soon as possible!</p><p>Please refer to the FAQ for recommended update workflows:</p>"
) +
"<p><a href='https://faq.octoprint.org/python3-update' target='_blank' rel='noopener noreferer'>How to migrate to Python 3</a></p>",
{reason: _.escape(reason)}
),
hide: false
});
}
// if the offline overlay is still showing, now's a good time to
// hide it, plus reload the camera feed if it's currently displayed
if ($("#offline_overlay").is(":visible")) {
+13 -16
View File
@@ -755,7 +755,7 @@ function showMessageDialog(msg, options) {
var modal = $("<div></div>").addClass("modal hide");
if (!nofade) {
modal.addClass("fade-in");
modal.addClass("fade");
}
modal
.append($("<div></div>").addClass("modal-header").append(modalHeader))
@@ -845,7 +845,7 @@ function showConfirmationDialog(msg, onacknowledge, options) {
var modal = $("<div></div>").addClass("modal hide");
if (!nofade) {
modal.addClass("fade-in");
modal.addClass("fade");
}
var buttons = $("<div></div>").addClass("modal-footer").append(cancelButton);
@@ -963,7 +963,7 @@ function showSelectionDialog(options) {
// create modal and do final wiring up
var modal = $("<div></div>").addClass("modal hide");
if (!nofade) {
modal.addClass("fade-in");
modal.addClass("fade");
}
if (!cancel) {
modal.data("backdrop", "static").data("keyboard", "false");
@@ -1060,14 +1060,18 @@ function showProgressModal(options, promise) {
var progress = $('<div class="progress progress-text-centered"></div>');
var progressBar = $('<div class="bar"></div>').addClass(barClassSuccess);
var progressText = $('<span class="progress-text-back"></span>');
var progressTextBack = $('<span class="progress-text-back"></span>');
var progressTextFront = $('<span class="progress-text-front"></span>').width(
progress.width()
);
if (max === undefined) {
progress.addClass("progress-striped active");
progressBar.width("100%");
}
progress.append(progressBar).append(progressText);
progressBar.append(progressTextFront);
progress.append(progressTextBack).append(progressBar);
var button = $('<button class="btn">' + buttonText + "</button>")
.prop("disabled", true)
@@ -1088,7 +1092,7 @@ function showProgressModal(options, promise) {
}
var modal = $("<div></div>")
.addClass("modal hide fade-in")
.addClass("modal hide fade")
.addClass(dialogClass)
.append($("<div></div>").addClass("modal-header").append(modalHeader))
.append(modalBody)
@@ -1123,16 +1127,9 @@ function showProgressModal(options, promise) {
// update progress bar
progressBar.width(String(value) + "%");
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");
}
progressTextFront.text(short);
progressTextBack.text(short);
progressTextFront.width(progress.width());
// if not successful, apply failure class
if (!success && !progressBar.hasClass(barClassFailure)) {
+1 -12
View File
@@ -42,12 +42,7 @@ $(function () {
opera: false,
mobile: false,
desktop: false,
browser_name: "unknown",
browser_version: "unknown",
os_name: "unknown",
os_version: "unknown"
desktop: false
},
viewmodels: {},
startedUp: false
@@ -123,12 +118,6 @@ $(function () {
exports.browser.mobile = $.browser.mobile;
exports.browser.desktop = !exports.browser.mobile;
var uap = UAParser();
exports.browser.browser_name = uap.browser.name;
exports.browser.browser_version = uap.browser.version;
exports.browser.os_name = uap.os.name;
exports.browser.os_version = uap.os.version;
if (exports.browser.safari) {
$("html").addClass("safari");
}
@@ -46,6 +46,7 @@ $(function () {
}
})
.css({
"width": "auto",
"margin-left": function () {
return -($(this).width() / 2);
}
@@ -156,6 +156,7 @@ $(function () {
}
})
.css({
"width": "auto",
"margin-left": function () {
return -($(this).width() / 2);
}
@@ -200,6 +201,7 @@ $(function () {
}
})
.css({
"width": "auto",
"margin-left": function () {
return -($(this).width() / 2);
}
@@ -563,6 +565,7 @@ $(function () {
}
})
.css({
"width": "auto",
"margin-left": function () {
return -($(this).width() / 2);
}
@@ -604,6 +607,7 @@ $(function () {
}
})
.css({
"width": "auto",
"margin-left": function () {
return -($(this).width() / 2);
}
@@ -513,11 +513,6 @@ $(function () {
clearTimeout(self.webcamDisableTimeout);
}
// IF disabled then we dont need to do anything
if (self.settings.webcam_webcamEnabled() == false) {
return;
}
// Determine stream type and switch to corresponding webcam.
var streamType = determineWebcamStreamType(self.settings.webcam_streamUrl());
if (streamType == "mjpg") {
@@ -693,14 +688,12 @@ $(function () {
var newSrc = self.settings.webcam_streamUrl();
if (currentSrc != newSrc) {
if (self.settings.webcam_cacheBuster()) {
if (newSrc.lastIndexOf("?") > -1) {
newSrc += "&";
} else {
newSrc += "?";
}
newSrc += new Date().getTime();
if (newSrc.lastIndexOf("?") > -1) {
newSrc += "&";
} else {
newSrc += "?";
}
newSrc += new Date().getTime();
self.webcamLoaded(false);
self.webcamError(false);
@@ -714,12 +707,7 @@ $(function () {
self._switchToHlsWebcam = function () {
var video = document.getElementById("webcam_hls");
// Check for native playback options: https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/canPlayType
if (
video != null &&
typeof video.canPlayType != undefined &&
video.canPlayType("application/vnd.apple.mpegurl") == "probably"
) {
if (video.canPlayType("application/vnd.apple.mpegurl")) {
video.src = self.settings.webcam_streamUrl();
} else if (Hls.isSupported()) {
var hls = new Hls();
+55 -121
View File
@@ -9,8 +9,6 @@ $(function () {
self.printerProfiles = parameters[4];
self.access = parameters[5];
self.allViewModels = undefined;
self.filesListVisible = ko.observable(true);
self.showInternalFilename = ko.observable(true);
@@ -85,20 +83,6 @@ $(function () {
self.moveEntry = ko.observable({name: "", display: "", path: ""}); // is there a better way to do this?
self.moveSource = ko.observable(undefined);
self.moveDestination = ko.observable(undefined);
self.moveSourceFilename = ko.observable(undefined);
self.moveDestinationFilename = ko.observable(undefined);
self.moveDestinationFullpath = ko.pureComputed(function () {
// Join the paths for renaming
if (self.moveSourceFilename() != self.moveDestinationFilename()) {
if (self.moveDestination() === "/") {
return self.moveDestination() + self.moveDestinationFilename();
} else {
return self.moveDestination() + "/" + self.moveDestinationFilename();
}
} else {
return self.moveDestination();
}
});
self.moveError = ko.observable("");
self.folderList = ko.observableArray(["/"]);
@@ -119,7 +103,6 @@ $(function () {
self.allItems = ko.observable(undefined);
self.currentPath = ko.observable("");
self.uploadProgressText = ko.observable();
self.uploadProgressPercentage = ko.observable();
// list style incl. persistence
var listStyleStorageKey = "gcodeFiles.currentListStyle";
@@ -180,22 +163,18 @@ $(function () {
listHelperExclusiveFilters.push(SUPPORTED_FILETYPES);
}
var sortByName = function (a, b) {
// sorts ascending
if (a["display"].toLowerCase() < b["display"].toLowerCase()) return -1;
if (a["display"].toLowerCase() > b["display"].toLowerCase()) return 1;
return 0;
};
self.listHelper = new ItemListHelper(
"gcodeFiles",
{
name: sortByName,
name: function (a, b) {
// sorts ascending
if (a["display"].toLowerCase() < b["display"].toLowerCase())
return -1;
if (a["display"].toLowerCase() > b["display"].toLowerCase()) return 1;
return 0;
},
upload: function (a, b) {
// sorts descending
if (a["date"] === undefined && b["date"] === undefined) {
return sortByName(a, b);
}
if (b["date"] === undefined || a["date"] > b["date"]) return -1;
if (a["date"] === undefined || a["date"] < b["date"]) return 1;
return 0;
@@ -631,32 +610,13 @@ $(function () {
return;
}
var proceed = function (p) {
var prevented = false;
var callback = function () {
OctoPrint.files.select(data.origin, data.path, p);
};
if (p) {
callViewModels(self.allViewModels, "onBeforePrintStart", function (
method
) {
prevented = prevented || method(callback) === false;
});
}
if (!prevented) {
callback();
}
};
if (
printAfterLoad &&
self.listHelper.isSelected(data) &&
self.enablePrint(data)
) {
// file was already selected, just start the print job
self.printerState.print();
OctoPrint.job.start();
} else {
// select file, start print job (if requested and within dimensions)
var withinPrintDimensions = self.evaluatePrintDimensions(data, true);
@@ -671,12 +631,12 @@ $(function () {
cancel: gettext("No"),
proceed: gettext("Yes"),
onproceed: function () {
proceed(print);
OctoPrint.files.select(data.origin, data.path, print);
},
nofade: true
});
} else {
proceed(print);
OctoPrint.files.select(data.origin, data.path, print);
}
}
};
@@ -715,8 +675,6 @@ $(function () {
self.moveError("");
self.moveSource(current);
self.moveDestination(current);
self.moveSourceFilename(entry.name);
self.moveDestinationFilename(entry.name);
self.moveDialog.modal("show");
};
@@ -965,72 +923,60 @@ $(function () {
self.getAdditionalData = function (data) {
var output = "";
if (data["gcodeAnalysis"]) {
if (data["gcodeAnalysis"]["dimensions"]) {
var dimensions = data["gcodeAnalysis"]["dimensions"];
output +=
gettext("Model size") +
": " +
_.sprintf(
"%(width).2fmm &times; %(depth).2fmm &times; %(height).2fmm",
dimensions
);
output += "<br>";
}
if (
data["gcodeAnalysis"]["_empty"] ||
!data["gcodeAnalysis"]["dimensions"] ||
(data["gcodeAnalysis"]["dimensions"]["width"] === 0 &&
data["gcodeAnalysis"]["dimensions"]["depth"] === 0 &&
data["gcodeAnalysis"]["dimensions"]["height"] === 0)
data["gcodeAnalysis"]["filament"] &&
typeof data["gcodeAnalysis"]["filament"] === "object"
) {
output += gettext("Model contains no extrusion.<br>");
} else {
if (data["gcodeAnalysis"]["dimensions"]) {
var dimensions = data["gcodeAnalysis"]["dimensions"];
var filament = data["gcodeAnalysis"]["filament"];
if (_.keys(filament).length === 1) {
output +=
gettext("Model size") +
gettext("Filament") +
": " +
_.sprintf(
"%(width).2fmm &times; %(depth).2fmm &times; %(height).2fmm",
dimensions
);
output += "<br>";
}
if (
data["gcodeAnalysis"]["filament"] &&
typeof data["gcodeAnalysis"]["filament"] === "object"
) {
var filament = data["gcodeAnalysis"]["filament"];
if (_.keys(filament).length === 1) {
formatFilament(
data["gcodeAnalysis"]["filament"]["tool" + 0]
) +
"<br>";
} else if (_.keys(filament).length > 1) {
_.each(filament, function (f, k) {
if (
!_.startsWith(k, "tool") ||
!f ||
!f.hasOwnProperty("length") ||
f["length"] <= 0
)
return;
output +=
gettext("Filament") +
": " +
formatFilament(
data["gcodeAnalysis"]["filament"]["tool" + 0]
) +
" (" +
gettext("Tool") +
" " +
k.substr("tool".length) +
"): " +
formatFilament(f) +
"<br>";
} else if (_.keys(filament).length > 1) {
_.each(filament, function (f, k) {
if (
!_.startsWith(k, "tool") ||
!f ||
!f.hasOwnProperty("length") ||
f["length"] <= 0
)
return;
output +=
gettext("Filament") +
" (" +
gettext("Tool") +
" " +
k.substr("tool".length) +
"): " +
formatFilament(f) +
"<br>";
});
}
});
}
output +=
gettext("Estimated print time") +
": " +
(self.settingsViewModel.appearance_fuzzyTimes()
? formatFuzzyPrintTime(
data["gcodeAnalysis"]["estimatedPrintTime"]
)
: formatDuration(
data["gcodeAnalysis"]["estimatedPrintTime"]
)) +
"<br>";
}
output +=
gettext("Estimated print time") +
": " +
(self.settingsViewModel.appearance_fuzzyTimes()
? formatFuzzyPrintTime(
data["gcodeAnalysis"]["estimatedPrintTime"]
)
: formatDuration(data["gcodeAnalysis"]["estimatedPrintTime"])) +
"<br>";
}
if (data["prints"] && data["prints"]["last"]) {
output +=
@@ -1344,7 +1290,6 @@ $(function () {
self.uploadProgress.addClass("progress-striped").addClass("active");
self.uploadProgressBar.css("width", "100%");
if (payload.progressAvailable) {
self.uploadProgressPercentage(percentage);
self.uploadProgressText(
_.sprintf(gettext("Slicing ... (%(percentage)d%%)"), {percentage: 0})
);
@@ -1359,21 +1304,18 @@ $(function () {
percentage: Math.round(progress)
})
);
self.uploadProgressPercentage(Math.round(progress));
};
self.onEventSlicingCancelled = function (payload) {
self.uploadProgress.removeClass("progress-striped").removeClass("active");
self.uploadProgressBar.css("width", "0%");
self.uploadProgressText("");
self.uploadProgressPercentage(0);
};
self.onEventSlicingDone = function (payload) {
self.uploadProgress.removeClass("progress-striped").removeClass("active");
self.uploadProgressBar.css("width", "0%");
self.uploadProgressText("");
self.uploadProgressPercentage(0);
new PNotify({
title: gettext("Slicing done"),
@@ -1395,7 +1337,6 @@ $(function () {
self.uploadProgress.removeClass("progress-striped").removeClass("active");
self.uploadProgressBar.css("width", "0%");
self.uploadProgressText("");
self.uploadProgressPercentage(0);
var html = _.sprintf(
gettext("Could not slice %(stl)s to %(gcode)s: %(reason)s"),
@@ -1424,7 +1365,6 @@ $(function () {
self.onEventTransferStarted = function (payload) {
self.uploadProgress.addClass("progress-striped").addClass("active");
self.uploadProgressBar.css("width", "100%");
self.uploadProgressPercentage(100);
self.uploadProgressText(gettext("Streaming ..."));
};
@@ -1432,7 +1372,6 @@ $(function () {
self.uploadProgress.removeClass("progress-striped").removeClass("active");
self.uploadProgressBar.css("width", "0");
self.uploadProgressText("");
self.uploadProgressPercentage(0);
new PNotify({
title: gettext("Streaming done"),
@@ -1456,7 +1395,6 @@ $(function () {
self.uploadProgress.removeClass("progress-striped").removeClass("active");
self.uploadProgressBar.css("width", "0");
self.uploadProgressText("");
self.uploadProgressPercentage(0);
new PNotify({
title: gettext("Streaming failed"),
@@ -1515,7 +1453,6 @@ $(function () {
self._setProgressBar = function (percentage, text, active) {
self.uploadProgressBar.css("width", percentage + "%");
self.uploadProgressText(text);
self.uploadProgressPercentage(percentage);
if (active) {
self.uploadProgress.addClass("progress-striped active");
@@ -1740,9 +1677,6 @@ $(function () {
self.settingsViewModel.settings.appearance.showInternalFilename()
);
};
self.onAllBound = function (allViewModels) {
self.allViewModels = allViewModels;
};
}
OCTOPRINT_VIEWMODELS.push({
@@ -676,6 +676,7 @@ $(function () {
}
})
.css({
"width": "auto",
"margin-left": function () {
return -($(this).width() / 2);
}
@@ -6,8 +6,6 @@ $(function () {
self.settings = parameters[1];
self.access = parameters[2];
self.allViewModels = undefined;
self.stateString = ko.observable(undefined);
self.errorString = ko.observable(undefined);
self.hasErrorString = ko.pureComputed(function () {
@@ -435,25 +433,8 @@ $(function () {
}
});
} else {
var proceed = function (p) {
var prevented = false;
var callback = function () {
OctoPrint.job.start();
};
callViewModels(self.allViewModels, "onBeforePrintStart", function (
method
) {
prevented = prevented || method(callback) === false;
});
if (!prevented) {
callback();
}
};
if (!self.settings.feature_printStartConfirmation()) {
proceed();
OctoPrint.job.start();
} else {
showConfirmationDialog({
message: gettext(
@@ -462,7 +443,9 @@ $(function () {
question: gettext("Do you want to start the print job now?"),
cancel: gettext("No"),
proceed: gettext("Yes"),
onproceed: proceed,
onproceed: function () {
OctoPrint.job.start();
},
nofade: true
});
}
@@ -496,10 +479,6 @@ $(function () {
});
}
};
self.onAllBound = function (allViewModels) {
self.allViewModels = allViewModels;
};
}
OCTOPRINT_VIEWMODELS.push({
Loaded 100 of 147 files, more files were not shown because too many files have changed in this diff. Show more