Compare commits

..
51 Commits
Author SHA1 Message Date
Gina Häußge 354042b84d Preparing release of 1.2.16 2016-09-23 09:51:45 +02:00
Gina Häußge 26fb208f48 Preparing release of 1.2.16rc2 2016-09-16 12:54:48 +02:00
Gina Häußge 2fc86e095f 1.2.16rc1 was actually pushed out on 2016-09-09, not -08 2016-09-12 12:49:04 +02:00
Gina Häußge 0167015b46 Fix generate/delete API key functionality in user settings
Closes #1491
2016-09-12 12:48:10 +02:00
Gina Häußge 8b99c89acf Return 400 Bad Request if a multipart request lacks the boundary
It's mandatory according to RFC2046, section 5.1

See also #1486
2016-09-12 12:48:10 +02:00
Gina Häußge 0bb6f5215d "prerelease" key might not be in check if tracking stable releases 2016-09-12 09:25:34 +02:00
Gina Häußge 079430e3c8 Preparing release of 1.2.16rc1 2016-09-09 11:52:56 +02:00
Gina Häußge 7efa311b04 Updated the german translation again after adding a sentence 2016-09-09 11:52:54 +02:00
Gina Häußge c6d9575127 Added link to "Using Release Channels" to the SWU settings dialog 2016-09-09 11:34:25 +02:00
Gina Häußge bbe6e44d44 Only use non-postfixed cookie if no postfixed one exists
Example:

  * both "session" and "session_P5000" cookies available: "session" value from "session_P5000"
  * only "session" cookie available: "session" value from "session"
  * only "session_P5000" cookie available: "session" value from "session_P5000"
2016-09-08 15:42:51 +02:00
Gina Häußge 53b74f9caa Only construct HTTP_HOST header from SERVER_NAME and _PORT if it's unset
If HTTP_HOST is set, following PEP333 it takes precedence over SERVER_NAME and
_PORT, so we set those from it.
2016-09-08 15:18:09 +02:00
Gina Häußge a7bd770180 Allow overriding file name sanitization by sub classes of LocalStorage 2016-09-08 12:50:04 +02:00
Gina Häußge 2b22d26eac Fixed a small issue with RFC 5987 headers arriving as unicode in parser
Also added API docs regarding header encoding, incl support for RFC 5987
for filename fields in Content-Disposition headers in multipart/form-data
parts, incl. an example of an upload request with a utf-8 encoded filename.
2016-09-07 18:44:46 +02:00
Gina Häußge 13728c231c Also explicitely support ISO-8859-1 encoded multipart headers
Solves an issue with clients encoding filenames in multipart
 headers in ISO-8859-1, causing an HTTP 500 response code.

 This change makes ISO-8859-1 encoded headers work, sends
 a 400 Bad Request instead of 500 Internal Server Error if the
 request multipart headers cannot be decoded as either UTF-8
 or ISO-8859-1, defines UTF-8 content type for multipart text
 fields in rebuilt body and also adds support for RFC 5987 for the
 multipart file upload "filename" header component.
2016-09-07 17:03:59 +02:00
Gina Häußge 209a88bd6a And consequently yet another update of the german translation 2016-09-07 12:10:34 +02:00
Gina Häußge 2256a1e825 Found an untranslated piece of UI 2016-09-07 12:05:54 +02:00
Gina Häußge 122ec39728 And another update of the german translation 2016-09-07 11:55:31 +02:00
Gina Häußge d4428de9a0 Some rewording 2016-09-07 11:55:17 +02:00
Gina Häußge 536d46f15d Updated german translation 2016-09-07 10:21:21 +02:00
Gina Häußge 62d5f04373 Merge branch 'fix/portRestrictedCookies' into maintenance 2016-09-05 12:11:12 +02:00
Gina Häußge b48af7133e Fixed validator for tornado 2016-09-05 12:10:58 +02:00
Gina Häußge 9a9502b281 "prerelease" might not be in check (chances for that are actually high), don't hiccup on that 2016-09-05 12:09:13 +02:00
Gina Häußge 9d9eb3390d Cookie names are now port specific, based on the request associated with a response
* make sure server_port headers are properly set in reverse proxied scenarios
  * overwrite request and response classes to
    * always apply reverse proxy environment changes (so far missing for tornado
      context)
    * strip cookie name suffixes from cookie names on requests and
    * be sure to set cookie name suffixes for cookie names on responses
    * include script root in path used for cookies
  * some minor refactoring in octoprint.server setup routines
  * removed ReverseProxied class (didn't work for tornado context)
  * add unit tests for the whole reverse proxy, request and response customization
2016-09-05 12:06:56 +02:00
Gina Häußge ce28b637ab Better solution for access to .md files when running from source
The SelectedFileSystemLoader doesn't collect everything and the
kitchen sink from disk...
2016-08-29 17:50:14 +02:00
Gina Häußge 21b7339187 SWU: Move branch config to update check & fix release version detection again 2016-08-26 14:18:17 +02:00
Gina Häußge df1a97b0e1 SWU: Only enforce unequality comparison on release channel switch 2016-08-26 10:40:01 +02:00
Gina Häußge 66da377b64 SWU: Minor fixes in the octoprint check population 2016-08-26 10:19:20 +02:00
Gina Häußge 34e5b5d50f SWU: Sort github releases by version, not publication date
We can't rely on the publication date anymore with the introduction of prerelease
channels, since e.g. a current devel prerelease might have been published
earlier than the latest stable but should still be considered the latest release for
this release channel
2016-08-26 10:18:35 +02:00
Gina Häußge 882cf3a142 SWU: git reset => git reset --hard for forced version 2016-08-25 16:49:18 +02:00
Gina Häußge d9a4ff47b6 Make sure to switch back to master for stable release channel 2016-08-25 16:30:35 +02:00
Gina Häußge d538b3fd38 Adjust swu plugin settings to selected update method 2016-08-25 15:45:25 +02:00
Gina Häußge f8386649bf Fix release channel selector 2016-08-25 13:32:18 +02:00
Gina Häußge b5bc03e711 First throw at release channels
We start out with master (Stable), rc/maintenance (Maintenance) and rc/devel (Devel)
2016-08-25 09:41:12 +02:00
Gina Häußge 0a78c92407 Do access logging via custom request header instead of global flag
We don't want any weird things to happen due to multithreading...
2016-08-18 16:14:03 +02:00
Gina Häußge 60c46a3fc4 Fixed use of preemptive cache exceptions in "unless" implementation 2016-08-18 14:05:12 +02:00
Gina Häußge 8782f77577 Slightly modified logging for cached.gif 2016-08-18 14:01:25 +02:00
Gina Häußge 08f9529c6d Merge remote-tracking branch 'origin/maintenance' into maintenance 2016-08-18 13:58:38 +02:00
Gina Häußge 6499bd160f Only wait for preemptive cache if it's enabled for path & view 2016-08-18 13:56:46 +02:00
Gina Häußge 599098a589 Have intermediary reload only after preliminary caching 2016-08-18 12:27:30 +02:00
Gina Häußge aa57277ff8 Only report files as enqueued for analysis which actually are 2016-08-18 08:39:19 +02:00
Gina Häußge 74a94469b6 Fix an issue with global_get from 3rd party plugins 2016-08-17 14:50:53 +02:00
Gina Häußge 217e54d81c Make sure we are still in printing state before sending next line
We might just have "eaten" a line used for triggering a pause (e.g. an M0)
and thus might not be eligible to send the next line from the streamed file
anymore.

Solves #1448
2016-08-16 09:29:29 +02:00
Gina Häußge b05beb27b5 Don't sanitize . or .. folder names 2016-08-15 16:13:35 +02:00
Gina Häußge d81ec15f43 Improvements in fuzzy print time algorithm
Also use new fuzzy print time in gcode viewer to have some consistency.
2016-08-15 15:42:06 +02:00
Gina Häußge 39372a9475 Also sanitize leading .
That way hidden files that are uploaded will be "de-hidden".

Note that NO "de-hiding" of existing files will take place!
2016-08-15 14:19:36 +02:00
Gina Häußge e8cac14c2f Make sure uploads folder only has sanitized entries
Should make sure stuff doesn't break when people perform manual
file operations on the uploads folder (e.g. uploading files
that don't match the sanitization scheme).

Should solve #1434
2016-08-15 14:19:35 +02:00
Gina Häußge 5bef0926a6 Add [ and ] to valid chars in filenames
See #1434
2016-08-15 14:19:34 +02:00
Gina Häußge 7772fdc7bf Tooltips for state panel 2016-08-15 14:19:33 +02:00
Gina Häußge cd736c44df Improved fuzzy print time display 2016-08-15 14:19:32 +02:00
Gina Häußge 11bdc176a0 Fix minute comparison for dumb estimate fallback
Probably solves the core reason that caused #1428 to be
reported in the first place, totally inaccurate early linear
approximations (when nothing better is available) making
it to the user.

It should now display "Calcuting..." until the approximation
stabilizes OR the configured max percentage or max time without
an estimate are reached.
2016-08-15 14:17:27 +02:00
Gina Häußge fe97a8d6bd maintenance is now 1.2.16.dev 2016-07-30 09:56:49 +02:00
44 changed files with 4189 additions and 1453 deletions

No files matched your search

+32 -13
View File
@@ -1,27 +1,41 @@
Please read the "guidelines for contributing" that are linked ^-- just
up there. Also read the FAQ: https://github.com/foosel/OctoPrint/wiki/FAQ.
READ THE FOLLOWING FIRST:
If not already done, please read the "guidelines for contributing"
that are linked ^-- just up there in the big yellow box. Also read
the FAQ: https://github.com/foosel/OctoPrint/wiki/FAQ.
This is a bug and feature tracker, please only use it to report bugs
or request features within OctoPrint (not OctoPi, not any OctoPrint
plugins and not unofficial OctoPrint versions). Mark requests with
a [Request] prefix in the title please. Fully fill out the bug reporting
template for bug reports.
plugins and not unofficial OctoPrint versions).
Do not seek support here ("I need help with ..."), that belongs on
the mailing list or the G+ community (both linked in the "guidelines
for contributing" linked above, read it!), NOT here.
Mark requests with a "[Request]" prefix in the title please. Fully fill
out the bug reporting template for bug reports (if you don't know where
to find some information - it's all described in the contribution
guidelines linked up there in the big yellow box). Do not delete any
lines from the template but those enclosed in [ and ] - and those please
DO delete, they are only provided for your information and removing them
makes your ticket more readable :)
Thank you!
(Before submitting your ticket, please delete this text up to and
including the line too - it's only here for you, we already know it
by heart ;))
----
#### What were you doing?
[Please be as specific as possible here. The maintainers will need to reproduce
your issue in order to fix it and that is not possible if they don't know
what you did to get it to happen in the first place. If you encountered
a problem with specific files of any sorts, make sure to also include a link to a file
with which to reproduce the problem.]
[Please be as specific as possible here. The maintainers will need to
reproduce your issue in order to fix it and that is not possible if they
don't know what you did to get it to happen in the first place.
If you encountered a problem with specific files of any sorts, make sure
to also include a link to a file with which to reproduce the problem.]
#### What did you expect to happen?
@@ -29,7 +43,7 @@ with which to reproduce the problem.]
#### Branch & Commit or Version of OctoPrint
[Can be found in the lower left corner of the web interface.]
[Can be found in the lower left corner of the web interface. ALWAYS INCLUDE.]
#### Printer model & used firmware incl. version
@@ -41,12 +55,17 @@ with which to reproduce the problem.]
#### Link to octoprint.log
[On gist.github.com or pastebin.com. Always include and never truncate.]
[On gist.github.com or pastebin.com. ALWAYS INCLUDE and never truncate.]
#### Link to contents of terminal tab or serial.log
[On gist.github.com or pastebin.com. If applicable, always include if unsure or
reporting communication issues. Never truncate.]
reporting communication issues. Never truncate.
serial.log is usually not written due to performance reasons and must be
enabled explicitly. Provide at the very least the FULL contents of your
terminal tab at the time of the bug occurrence, even if you do not have
a serial.log.]
#### Link to contents of Javascript console in the browser
+6 -6
View File
@@ -7,20 +7,20 @@
# The file is processed from top to bottom, the first matching line wins. If <tag> or <reference commit> are left out,
# the lookup table does not apply to the matched branches
# master, prerelease and rc shall not use the lookup table, only tags
# master and rc shall not use the lookup table, only tags
master
rc/.*
prerelease
rc
# neither should disconnected checkouts, e.g. 'git checkout <tag>'
HEAD
\(detached.*
# maintenance is currently the branch for preparation of maintenance release 1.2.15
# maintenance is currently the branch for preparation of maintenance release 1.2.16
# so are any fix/... and improve/... branches
maintenance 1.2.15 14969e5508b7b66f38abaf0f96bb7dc5b9ebe929 pep440-dev
fix/.* 1.2.15 14969e5508b7b66f38abaf0f96bb7dc5b9ebe929 pep440-dev
improve/.* 1.2.15 14969e5508b7b66f38abaf0f96bb7dc5b9ebe929 pep440-dev
maintenance 1.2.16 afdb98a92fb5dae2661aa252975933be55bef2c2 pep440-dev
fix/.* 1.2.16 afdb98a92fb5dae2661aa252975933be55bef2c2 pep440-dev
improve/.* 1.2.16 afdb98a92fb5dae2661aa252975933be55bef2c2 pep440-dev
# every other branch is a development branch and thus gets resolved to 1.3.0-dev for now
.* 1.3.0 198d3450d94be1a2 pep440-dev
+29
View File
@@ -1,5 +1,34 @@
# OctoPrint Changelog
## 1.2.16 (2016-09-23)
### Improvements
* [#1434](https://github.com/foosel/OctoPrint/issues/1434): Make sure to sanitize any file names in the upload folder that do not match OctoPrint's file name "sanitization standard" automatically when creating a file listing. This should solve issues with UI functionality like selecting a file for printing or deleting a file to not work with files that were uploaded manually to the ``uploads`` folder. As a side note: Please don't do this, use the ``watched`` folder if you want to SCP/FTP/copy files directly to OctoPrint.
* [#1434](https://github.com/foosel/OctoPrint/issues/1434): Allow `[` and `]` in uploaded file names.
* [#1481](https://github.com/foosel/OctoPrint/issues/1481): Bring back non-fuzzy layer time estimates in the GCODE viewer.
* Improved fuzzy print time displays in the frontend. Rounding now takes overall duration into account - durations over a day will be rounded up/down to half days, durations over an hour will be rounded up/down to half hours, durations over 30min will be rounded to 10min segments, durations below 30min will be rounded up or down to the next minute depending on the seconds and finally if we are talking about less than a minute, durations over 30s will return "less than a minute", durations under 30s will return "a couple of seconds".
* Improved intermediary loading page: Don't report server as ready and reload until preliminary caching has been done, IF preliminary caching will be done.
* Added release channels to OctoPrint's bundled Software Update plugin. You will now be able to subscribe to OctoPrint's `maintenance` or `devel` release candidates in addition to stable versions. [Read more about Release Channels on the wiki](https://github.com/foosel/OctoPrint/wiki/Using-Release-Channels).
* Return a "400 Bad Request" instead of a "500 Internal Server Error" if a `multipart/form-data` request (e.g. a file upload) is sent which lacks the `boundary` field.
### Bug Fixes
* [#1448](https://github.com/foosel/OctoPrint/issues/1448): Don't "eat" first line of the pause script after a pause triggering `M0` but send it to the printer instead
* [#1477](https://github.com/foosel/OctoPrint/issues/1477): Only report files enqueued for analysis which actually are (as in, don't claim to have queued STL files for GCODE analysis)
* [#1478](https://github.com/foosel/OctoPrint/issues/1478): Don't display inaccurate linear estimate ("6 days remaining") until 30 *minutes* have passed, even if nothing else is available. Potentially related to [#1428](https://github.com/foosel/OctoPrint/issues/1428).
* [#1479](https://github.com/foosel/OctoPrint/issues/1479): Make sure set cookies are post fixed with a port specific suffix and that the path they are set on takes the script root from the request into account.
* [#1483](https://github.com/foosel/OctoPrint/issues/1483): Filenames in file uploads may also now be encoded in ISO-8859-1, as defined in [RFC 7230](https://tools.ietf.org/html/rfc7230#section-3.2.4). Solves an issue when sending files with non-ASCII-characters in the file name from Slic3r.
* [#1491](https://github.com/foosel/OctoPrint/issues/1491): Fixed generate/delete API key in the user settings
* [#1492](https://github.com/foosel/OctoPrint/issues/1492): Fixed a bug in the software update plugin depending on the presence of the ``prerelease`` flag which is only present when added manually or using a non stable release channel.
### More information
* [Commits](https://github.com/foosel/OctoPrint/compare/1.2.15...1.2.16)
* Release Candidates:
* [1.2.16rc1](https://github.com/foosel/OctoPrint/releases/tag/1.2.16rc1)
* [1.2.16rc2](https://github.com/foosel/OctoPrint/releases/tag/1.2.16rc2)
## 1.2.15 (2016-07-30)
### Improvements
+44 -29
View File
@@ -63,10 +63,11 @@ available for the maintainers to directly start tackling that problem.
## How to file a bug report
If you encounter an issue with OctoPrint, you are welcome to
[submit a bug report](https://goo.gl/GzkGv9).
[submit a bug report](https://github.com/foosel/OctoPrint/issues/new).
Before you do that for the first time though please take a moment to read the
following section *completely*. Thank you! :)
following section *completely* and also follow the instructions in the
"new issue" form. Thank you! :)
### What should I do before submitting a bug report?
@@ -85,7 +86,7 @@ following section *completely*. Thank you! :)
might have installed**. Report any issues with those in their corresponding
bug tracker (probably linked to from the plugin's homepage).
Finally, **this is also not the right issue tracker if you are running an
Finally, **this is also not the right issue tracker if you are running a
forked version of OctoPrint**. Seek help for such unofficial versions from
the people maintaining them instead.
@@ -123,17 +124,21 @@ following section *completely*. Thank you! :)
### What should I include in a bug report?
Always use the following template (you can remove what's within `[...]`, that's
First of all make sure your use **a descriptive title**. "It doesn't work"
and similar unspecific complaints are NOT descriptive titles.
**Always use the following template** (please remove what's within `[...]`, that's
only provided here as some additional information for you), **even if only adding a
"me too" to an existing ticket**:
#### What were you doing?
[Please be as specific as possible here. The maintainers will need to reproduce
your issue in order to fix it and that is not possible if they don't know
what you did to get it to happen in the first place. If you encountered
a problem with specific files of any sorts, make sure to also include a link to a file
with which to reproduce the problem.]
[Please be as specific as possible here. The maintainers will need to
reproduce your issue in order to fix it and that is not possible if they
don't know what you did to get it to happen in the first place.
If you encountered a problem with specific files of any sorts, make sure
to also include a link to a file with which to reproduce the problem.]
#### What did you expect to happen?
@@ -141,7 +146,7 @@ only provided here as some additional information for you), **even if only addin
#### Branch & Commit or Version of OctoPrint
[Can be found in the lower left corner of the web interface.]
[Can be found in the lower left corner of the web interface. ALWAYS INCLUDE.]
#### Printer model & used firmware incl. version
@@ -153,12 +158,17 @@ only provided here as some additional information for you), **even if only addin
#### Link to octoprint.log
[On gist.github.com or pastebin.com. Always include and never truncate.]
[On gist.github.com or pastebin.com. ALWAYS INCLUDE and never truncate.]
#### Link to contents of terminal tab or serial.log
[On gist.github.com or pastebin.com. If applicable, always include if unsure or
reporting communication issues. Never truncate.]
reporting communication issues. Never truncate.
serial.log is usually not written due to performance reasons and must be
enabled explicitly. Provide at the very least the FULL contents of your
terminal tab at the time of the bug occurrence, even if you do not have
a serial.log.]
#### Link to contents of Javascript console in the browser
@@ -171,7 +181,8 @@ only provided here as some additional information for you), **even if only addin
I have read the FAQ.
Copy-paste this template **completely**. Do not skip any lines!
Copy-paste this template **completely**. Do not skip any lines or the bot
*will* complain!
### Where can I find which version and branch I'm on?
@@ -195,15 +206,16 @@ more information is needed.
One is contained in the **"Terminal" tab** within OctoPrint's UI and is a log
of the last 300 lines of communication with the printer. Please copy-paste
this somewhere (disable auto scroll to make copying the contents easier) -
this *completely* somewhere (disable auto scroll to make copying the contents easier) -
e.g. http://pastebin.com or http://gist.github.com - and include a link in
your bug report.
There is also **OctoPrint's application log file** or in short `octoprint.log`,
which is by default located at `~/.octoprint/logs/octoprint.log` on Linux,
`%APPDATA%\OctoPrint\logs\octoprint.log` on Windows and
`~/Library/Application Support/OctoPrint/logs/octoprint.log` on MacOS. Please
copy-paste this to pastebin or gist as well and include a link in your bug
`~/Library/Application Support/OctoPrint/logs/octoprint.log` on MacOS. You can
also access it directly through OctoPrint via Settings > Logs. Please
copy-paste this *completely* to pastebin or gist as well and include a link in your bug
report.
It might happen that you are asked to provide a more **thorough log of the
@@ -299,14 +311,9 @@ There are three main branches in OctoPrint:
* `master`: The master branch always contains the current stable release. It
is *only* updated on new releases. Will have a version number following
the scheme `x.y.z` (e.g. `1.2.9`) or - if it's absolutely necessary to
add a commit after release to this branch - `x.y.z.post<commits since x.y.z>`
the scheme `<x>.<y>.<z>` (e.g. `1.2.9`) or - if it's absolutely necessary to
add a commit after release to this branch - `<x>.<y>.<z>.post<commits since x.y.z>`
(e.g. `1.2.9.post1`).
* `prerelease`: This branch is only used during the short period where a
future release has "graduated" from the `maintenance` branch and is already
tagged, but still marked on Github as a pre-release. This is mostly used for
update testing just before new releases. Version number follows the scheme
`x.y.z` (e.g. `1.2.9`), just like the `master` branch.
* `maintenance`: Improvements and fixes of the current release that make up
the next release go here. More or less continously updated. You can consider
this a preview of the next release version. It should be very stable at all
@@ -314,7 +321,7 @@ There are three main branches in OctoPrint:
next stable release, so if you want to help out development, running the
`maintenance` branch and reporting back anything you find is a very good way
to do that. Will usually have a version number following the scheme
`x.y.z+1.dev.<commits since increase of z>` for an OctoPrint version of `x.y.z`
`<x>.<y>.<z+1>.dev<commits since increase of z>` for an OctoPrint version of `<x>.<y>.<z>`
(e.g. `1.2.10.dev12`).
* `devel`: Ongoing development of new features that will go into the next bigger
release (MINOR version number increases) will happen on this branch. Usually
@@ -322,8 +329,16 @@ There are three main branches in OctoPrint:
temporarily. Can be considered the "bleeding edge". All PRs should target
*this* branch. Important improvements and fixes from PRs here are backported to
`maintenance` as needed. Will usually have a version number following the
scheme `x.y+1.0.dev<commits since increase of y>` for an OctoPrint version
of `x.y.z` (e.g. `1.3.0.dev123`).
scheme `<x>.<y+1>.0.dev<commits since increase of y>` for a current OctoPrint version
of `<x>.<y>.<z>` (e.g. `1.3.0.dev123`).
* `rc/maintenance`: This branch is reserved for future releases that have graduated from
the `maintenance` branch and are now being pushed on the "Maintenance"
pre release channel for further testing. Version number follows the scheme
`<x>.<y>.<z>rc<n>` (e.g. `1.2.9rc1`).
* `rc/devel`: This branch is reserved for future releases that have graduated from
the `devel` branch and are now being pushed on the "Devel" pre release channel
for further testing. Version number follows the scheme `<x>.<y+1>.0rc<n>` (e.g. `1.3.0rc1`)
for a current stable OctoPrint version of `<x>.<y>.<z>`.
Additionally, from time to time you might see other branches pop up in the repository.
Those usually have one of the following prefixes:
@@ -334,9 +349,6 @@ Those usually have one of the following prefixes:
`maintenance` and `devel` branches.
* `dev/...` or `feature/...`: New functionality under development that is to be merged
into the `devel` branch.
* `rc`: A branch similar in nature to the `prerelease` branch, only that it will be
used to provide current release candidates of the next stable version to be derived
from the `devel` branch.
There is also the `gh-pages` branch, which holds OctoPrint's web page, and a couple of
older development branches that are slowly being migrated or deleted.
@@ -376,6 +388,9 @@ the local version identifier to allow for an exact determination of the active c
tickets as well, explained issue with "me too" red herrings.
* 2016-03-14: Some more requirements for PRs, and a PR template.
* 2016-06-08: New `prerelease` and `rc` branches explained.
* 2016-09-09: New `rc/*` branches explained.
* 2016-09-23: Some more work on "How to file a bug report" based on recent
experiences
## Footnotes
* [1] - If you are wondering why, the problem is that anything that you add
+8 -16
View File
@@ -1,5 +1,4 @@
OctoPrint
=========
# OctoPrint
OctoPrint provides a snappy web interface for controlling a 3D printer (RepRap, Ultimaker, ...). It is Free Software
and released under the [GNU Affero General Public License V3](http://www.gnu.org/licenses/agpl.html).
@@ -22,8 +21,7 @@ might be of more interest for you. You might also want to subscribe to [the mail
or the [G+ Community](https://plus.google.com/communities/102771308349328485741) where there are other active users who might be
able to help you with any questions you might have.
Contributing
------------
## Contributing
Contributions of all kinds are welcome, not only in the form of code but also with regards to the
[official documentation](http://docs.octoprint.org/) or [the public wiki](https://github.com/foosel/OctoPrint/wiki), support
@@ -31,15 +29,14 @@ of other users in the [bug tracker](https://github.com/foosel/OctoPrint/issues),
[the Mailinglist](https://groups.google.com/group/octoprint) or
[the G+ Community](https://plus.google.com/communities/102771308349328485741) and also [financially](http://octoprint.org/support-octoprint/).
If you think something is bad as it is about OctoPrint or its documentation the way it is, please help
If you think something is bad about OctoPrint or its documentation the way it is, please help
in any way to make it better instead of just complaining about it -- this is an Open Source Project
after all :)
For information about how to go about contributions of any kind, please see the project's
[Contribution Guidelines](https://github.com/foosel/OctoPrint/blob/master/CONTRIBUTING.md).
Installation
------------
## Installation
Installation instructions for installing from source for different operating
systems can be found [on the wiki](https://github.com/foosel/OctoPrint/wiki#assorted-guides).
@@ -66,8 +63,7 @@ releases but also be able to automatically upgrade to them from within
OctoPrint, take a look [at the documentation of the Software Update Plugin](https://github.com/foosel/OctoPrint/wiki/Plugin:-Software-Update#making-octoprint-updateable-on-existing-installations)
and at its settings.
Dependencies
------------
## Dependencies
OctoPrint depends on a couple of python modules to do its job. Those are automatically installed when installing
OctoPrint via `setup.py`:
@@ -78,8 +74,7 @@ You should also do this every time after pulling from the repository, since the
OctoPrint currently only supports Python 2.7.
Usage
-----
## Usage
Running the `setup.py` script via
@@ -118,8 +113,7 @@ See `octoprint --help` for further information.
OctoPrint also ships with a `run` script in its source directory. You can also invoke that to start up the server, it
takes the same command line arguments as the `octoprint` script.
Configuration
-------------
## Configuration
If not specified via the commandline, the configfile `config.yaml` for OctoPrint is expected in the settings folder,
which is located at `~/.octoprint` on Linux, at `%APPDATA%/OctoPrint` on Windows and
@@ -130,9 +124,7 @@ A comprehensive overview of all available configuration settings can be found
Please note that the most commonly used configuration settings can also easily
be edited from OctoPrint's settings dialog.
Special Thanks
--------------
## Special Thanks
The development of OctoPrint is sponsored and maintained by [BQ](http://www.bq.com/).
Cross-browser testing services are kindly provided by [BrowserStack](http://www.browserstack.com/).
Profiling is done with the help of [PyVmMonitor](http://www.pyvmmonitor.com).
+8 -4
View File
@@ -1,4 +1,4 @@
# Supporters
# Supporters
Development of this version of OctoPrint wouldn't have been possible without
[financial support by the community](http://octoprint.org/support-octoprint/) -
@@ -12,11 +12,13 @@ thanks to everyone who contributed!
* Arnljot Arntsen
* Aurelio Bernal Ramírez
* Bart Zudell
* Boris Hussein
* Brad Jackson
* Brad Mooneyham
* Brent Fiegle
* Brian E. Tyler
* Charles Mitchell
* Christopher Day
* Christian Petropolis
* COLLE+McVOY
* CreativeTools
@@ -33,6 +35,7 @@ thanks to everyone who contributed!
* J. Eckert
* Jason Galarneau
* Joe Korzeniewski
* Josh Daniels
* Joshua Gregory
* Kaile Riser
* Kale Stedman
@@ -45,11 +48,11 @@ thanks to everyone who contributed!
* Mark Walker
* Masayoshi Mitsui
* Michael McDargh
* Miguel Angel Salmeron
* Mikey
* Miles Flavel
* Mohammed Khorakiwala
* Noe Ruiz
* Patrick McGinnis
* Paul Generes
* Peter Grace
* Peter Schmehl
@@ -64,8 +67,9 @@ thanks to everyone who contributed!
* stefi davis
* Steven Pearson
* Sven Mueller
* Terrance Shaw
* Thomas Hatley
* Thomas Sanladerer
* Trent Shumay
* Xpandedreality
and 844 more wonderful people pledging on the [Patreon campaign](https://patreon.com/foosel)!
and 905 more wonderful people pledging on the [Patreon campaign](https://patreon.com/foosel)!
+43 -11
View File
@@ -161,18 +161,10 @@ Upload file
Content-Disposition: form-data; name="file"; filename="whistle_v2.gcode"
Content-Type: application/octet-stream
;Generated with Cura_SteamEngine 13.11.2
M109 T0 S220.000000
T0
;Sliced at: Wed 11-12-2013 16:53:12
;Basic settings: Layer height: 0.2 Walls: 0.8 Fill: 20
;Print time: #P_TIME#
;Filament used: #F_AMNT#m #F_WGHT#g
;Filament cost: #F_COST#
;M190 S70 ;Uncomment to add your own bed temperature line
;M109 S220 ;Uncomment to add your own temperature line
G21 ;metric values
G90 ;absolute positioning
G21
G90
...
------WebKitFormBoundaryDeC2E3iWbTv1PwMC
Content-Disposition: form-data; name="select"
@@ -188,7 +180,7 @@ Upload file
HTTP/1.1 200 OK
Content-Type: application/json
Location: http://example.com/api/files/sdcard/whistle_.gcode
Location: http://example.com/api/files/sdcard/whistle_v2.gcode
{
"files": {
@@ -208,6 +200,46 @@ Upload file
}
}
},
"done": false
}
**Example with UTF-8 encoded filename following RFC 5987**
.. sourcecode:: http
POST /api/files/local HTTP/1.1
Host: example.com
X-Api-Key: abcdef...
Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryDeC2E3iWbTv1PwMC
------WebKitFormBoundaryDeC2E3iWbTv1PwMC
Content-Disposition: form-data; name="file"; filename*=utf-8''20mm-%C3%BCml%C3%A4ut-b%C3%B6x.gcode
Content-Type: application/octet-stream
M109 T0 S220.000000
T0
G21
G90
...
------WebKitFormBoundaryDeC2E3iWbTv1PwMC--
.. sourcecode:: http
HTTP/1.1 200 OK
Content-Type: application/json
Location: http://example.com/api/files/local/20mm-umlaut-box.gcode
{
"files": {
"local": {
"name": "20mm-umlaut-box",
"origin": "local",
"refs": {
"resource": "http://example.com/api/files/local/whistle_v2.gcode",
"download": "http://example.com/downloads/files/local/whistle_v2.gcode"
}
}
},
"done": true
}
+13 -1
View File
@@ -74,7 +74,19 @@ Encoding
OctoPrint uses UTF-8 as charset.
.. _sec-api-cross-origin:
That also includes headers in ``multipart/form-data`` requests, in order to allow the full UTF-8 range of characters
for uploaded filenames. If a ``multipart/form-data`` sub header cannot be decoded as UTF-8, OctoPrint will also attempt
to decode it as ISO-8859-1.
Additionally, OctoPrint supports replacing the ``filename`` field in the ``Content-Disposition`` header of a
multipart field with a ``filename*`` field following `RFC 5987, Section 3.2 <https://tools.ietf.org/html/rfc5987#section-3.2>`_,
which allows defining the charset used for encoding the filename. If both ``filename`` and ``filename*`` fields are
present, following the recommendation of the RFC ``filename*`` will be used.
For an example on how to send a request utilizing RFC 5987 for the ``filename*`` attribute, see the second example
in :ref:`Upload file <sec-api-fileops-uploadfile>`.
.. _sec-api-general-crossorigin:
Cross-origin requests
=====================
+2 -2
View File
@@ -212,8 +212,8 @@ class FileManager(object):
# we'll use the default printer profile for the backlog since we don't know better
queue_entry = QueueEntry(entry, file_type, storage_type, path, self._printer_profile_manager.get_default())
self._analysis_queue.enqueue(queue_entry, high_priority=False)
counter += 1
if self._analysis_queue.enqueue(queue_entry, high_priority=False):
counter += 1
self._logger.info("Added {counter} items from storage type \"{storage_type}\" to analysis queue".format(**locals()))
def add_storage(self, storage_type, storage_manager):
+2 -1
View File
@@ -68,9 +68,10 @@ class AnalysisQueue(object):
def enqueue(self, entry, high_priority=False):
if not entry.type in self._queues:
return
return False
self._queues[entry.type].enqueue(entry, high_priority=high_priority)
return True
def pause(self):
for queue in self._queues.values():
+48 -7
View File
@@ -10,6 +10,7 @@ import logging
import os
import pylru
import tempfile
import shutil
import octoprint.filemanager
@@ -313,7 +314,7 @@ class LocalFileStorage(StorageInterface):
from slugify import Slugify
self._slugify = Slugify()
self._slugify.safe_chars = "-_.() "
self._slugify.safe_chars = "-_.()[] "
self._old_metadata = None
self._initialize_metadata()
@@ -390,7 +391,7 @@ class LocalFileStorage(StorageInterface):
path = self.sanitize_path(path)
else:
path = self.basefolder
return self._list_folder(path, filter=filter, recursive=recursive)
return self._list_folder(path, entry_filter=filter, recursive=recursive)
def add_folder(self, path, ignore_existing=True):
path, name = self.sanitize(path)
@@ -623,7 +624,11 @@ class LocalFileStorage(StorageInterface):
if "/" in name or "\\" in name:
raise ValueError("name must not contain / or \\")
return self._slugify(name).replace(" ", "_")
result = self._slugify(name).replace(" ", "_")
if result and result != "." and result != ".." and result[0] == ".":
# hidden files under *nix
result = result[1:]
return result
def sanitize_path(self, path):
"""
@@ -631,8 +636,11 @@ class LocalFileStorage(StorageInterface):
relative path elements (e.g. ``..``) and sanitizes folder names using :func:`sanitize_name`. Final path is the
absolute path including leading ``basefolder`` path.
"""
if path[0] == "/" or path[0] == ".":
if path[0] == "/":
path = path[1:]
elif path[0] == "." and path[1] == "/":
path = path[2:]
path_elements = path.split("/")
joined_path = self.basefolder
for path_element in path_elements:
@@ -642,6 +650,30 @@ class LocalFileStorage(StorageInterface):
raise ValueError("path not contained in base folder: {path}".format(**locals()))
return path
def _sanitize_entry(self, entry, path, entry_path):
sanitized = self.sanitize_name(entry)
if sanitized != entry:
# entry is not sanitized yet, let's take care of that
sanitized_path = os.path.join(path, sanitized)
sanitized_name, sanitized_ext = os.path.splitext(sanitized)
counter = 1
while os.path.exists(sanitized_path):
counter += 1
sanitized = self.sanitize_name("{}_({}){}".format(sanitized_name, counter, sanitized_ext))
sanitized_path = os.path.join(path, sanitized)
try:
shutil.move(entry_path, sanitized_path)
self._logger.info("Sanitized \"{}\" to \"{}\"".format(entry_path, sanitized_path))
return sanitized, sanitized_path
except:
self._logger.exception("Error while trying to rename \"{}\" to \"{}\", ignoring file".format(entry_path, sanitized_path))
raise
return entry, entry_path
def path_in_storage(self, path):
if isinstance(path, (tuple, list)):
path = self.join_path(*path)
@@ -881,7 +913,10 @@ class LocalFileStorage(StorageInterface):
if metadata_dirty:
self._save_metadata(path, metadata)
def _list_folder(self, path, filter=None, recursive=True):
def _list_folder(self, path, entry_filter=None, recursive=True, **kwargs):
if entry_filter is None:
entry_filter = kwargs.get("filter", None)
metadata = self._get_metadata(path)
if not metadata:
metadata = dict()
@@ -895,6 +930,12 @@ class LocalFileStorage(StorageInterface):
entry_path = os.path.join(path, entry)
try:
entry, entry_path = self._sanitize_entry(entry, path, entry_path)
except:
# error while trying to rename the file, we'll continue here and ignore it
continue
# file handling
if os.path.isfile(entry_path):
file_type = octoprint.filemanager.get_file_type(entry)
@@ -912,7 +953,7 @@ class LocalFileStorage(StorageInterface):
# TODO extract model hash from source if possible to recreate link
if not filter or filter(entry, entry_data):
if not entry_filter or entry_filter(entry, entry_data):
# only add files passing the optional filter
extended_entry_data = dict()
extended_entry_data.update(entry_data)
@@ -927,7 +968,7 @@ class LocalFileStorage(StorageInterface):
# folder recursion
elif os.path.isdir(entry_path) and recursive:
sub_result = self._list_folder(entry_path, filter=filter)
sub_result = self._list_folder(entry_path, entry_filter=entry_filter)
result[entry] = dict(
name=entry,
type="folder",
+144 -17
View File
@@ -18,7 +18,7 @@ from . import version_checks, updaters, exceptions, util
from octoprint.server.util.flask import restricted_access
from octoprint.server import admin_permission, VERSION, REVISION
from octoprint.server import admin_permission, VERSION, REVISION, BRANCH
from octoprint.util import dict_merge
import octoprint.settings
@@ -138,14 +138,18 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
#~~ SettingsPlugin API
def get_settings_defaults(self):
update_script = os.path.join(self._basefolder, "scripts", "update-octoprint.py")
return {
"checks": {
"octoprint": {
"type": "github_release",
"user": "foosel",
"repo": "OctoPrint",
"update_script": "{{python}} \"{update_script}\" --python=\"{{python}}\" \"{{folder}}\" {{target}}".format(update_script=os.path.join(self._basefolder, "scripts", "update-octoprint.py")),
"restart": "octoprint"
"update_script": "{{python}} \"{update_script}\" --branch={{branch}} --force={{force}} \"{{folder}}\" {{target}}".format(update_script=update_script),
"restart": "octoprint",
"stable_branch": dict(branch="master", name="Stable"),
"prerelease_branches": [dict(branch="rc/maintenance", name="Maintenance RCs"),
dict(branch="rc/devel", name="Devel RCs")]
},
},
"pip_command": None,
@@ -159,6 +163,9 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
if "checks" in data:
del data["checks"]
if "check_providers" in data:
del data["check_providers"]
checks = self._get_configured_checks()
if "octoprint" in checks:
if "checkout_folder" in checks["octoprint"]:
@@ -168,15 +175,40 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
else:
data["octoprint_checkout_folder"] = None
data["octoprint_type"] = checks["octoprint"].get("type", None)
try:
data["octoprint_method"] = self._get_update_method("octoprint", checks["octoprint"])
except exceptions.UnknownUpdateType:
data["octoprint_method"] = "unknown"
stable_branch = None
prerelease_branches = []
branch_mappings = []
if "stable_branch" in checks["octoprint"]:
branch_mappings.append(checks["octoprint"]["stable_branch"])
stable_branch = checks["octoprint"]["stable_branch"]["branch"]
if "prerelease_branches" in checks["octoprint"]:
for mapping in checks["octoprint"]["prerelease_branches"]:
branch_mappings.append(mapping)
prerelease_branches.append(mapping["branch"])
data["octoprint_branch_mappings"] = branch_mappings
data["octoprint_release_channel"] = stable_branch
if checks["octoprint"].get("prerelease", False):
channel = checks["octoprint"].get("prerelease_channel", BRANCH)
if channel in prerelease_branches:
data["octoprint_release_channel"] = channel
else:
data["octoprint_checkout_folder"] = None
data["octoprint_type"] = None
data["octoprint_branch_mappings"] = []
return data
def on_settings_save(self, data):
for key in self.get_settings_defaults():
if key == "checks" or key == "cache_ttl" or key == "octoprint_checkout_folder" or key == "octoprint_type":
if key in ("checks", "cache_ttl", "octoprint_checkout_folder", "octoprint_type", "octoprint_release_channel"):
continue
if key in data:
self._settings.set([key], data[key])
@@ -191,6 +223,11 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
update_type = check.get("type", None)
checkout_folder = check.get("checkout_folder", None)
update_folder = check.get("update_folder", None)
prerelease = check.get("prerelease", False)
prerelease_channel = check.get("prerelease_channel", None)
else:
update_type = checkout_folder = update_folder = prerelease_channel = None
prerelease = False
defaults = dict(
plugins=dict(softwareupdate=dict(
@@ -198,7 +235,9 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
octoprint=dict(
type=update_type,
checkout_folder=checkout_folder,
update_folder=update_folder
update_folder=update_folder,
prerelease=prerelease,
prerelease_channel=prerelease_channel
)
)
))
@@ -214,6 +253,17 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
self._settings.set(["checks", "octoprint", "type"], data["octoprint_type"], defaults=defaults, force=True)
self._refresh_configured_checks = True
if "octoprint_release_channel" in data:
prerelease_branches = self._settings.get(["checks", "octoprint", "prerelease_branches"])
if prerelease_branches and data["octoprint_release_channel"] in [x["branch"] for x in prerelease_branches]:
self._settings.set(["checks", "octoprint", "prerelease"], True, defaults=defaults, force=True)
self._settings.set(["checks", "octoprint", "prerelease_channel"], data["octoprint_release_channel"], defaults=defaults, force=True)
self._refresh_configured_checks = True
else:
self._settings.set(["checks", "octoprint", "prerelease"], False, defaults=defaults, force=True)
self._settings.set(["checks", "octoprint", "prerelease_channel"], None, defaults=defaults, force=True)
self._refresh_configured_checks = True
def get_settings_version(self):
return 4
@@ -346,7 +396,8 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
try:
information, update_available, update_possible = self.get_current_versions(check_targets=check_targets, force=force)
return flask.jsonify(dict(status="updatePossible" if update_available and update_possible else "updateAvailable" if update_available else "current", information=information))
return flask.jsonify(dict(status="updatePossible" if update_available and update_possible else "updateAvailable" if update_available else "current",
information=information))
except exceptions.ConfigurationInvalid as e:
flask.make_response("Update not properly configured, can't proceed: %s" % e.message, 500)
@@ -593,6 +644,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
# one of our updates requires a restart of either type "octoprint" or "environment". Let's see if
# we can actually perform that
restart_command = None
if restart_type == "octoprint":
restart_command = self._settings.global_get(["server", "commands", "serverRestartCommand"])
elif restart_type == "environment":
@@ -700,18 +752,70 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
result["displayName"] = check.get("displayName", gettext("OctoPrint"))
result["displayVersion"] = check.get("displayVersion", "{octoprint_version}")
stable_branch = "master"
release_branches = []
if "stable_branch" in check:
release_branches.append(check["stable_branch"]["branch"])
stable_branch = check["stable_branch"]["branch"]
if "prerelease_branches" in check:
release_branches += [x["branch"] for x in check["prerelease_branches"]]
result["released_version"] = not release_branches or BRANCH in release_branches
if check["type"] == "github_commit":
result["current"] = REVISION if REVISION else "unknown"
else:
result["current"] = VERSION
if check["type"] == "github_release" and (check.get("prerelease", None) or BRANCH != stable_branch):
# we are tracking github releases and are either also tracking prerelease OR are currently installed
# from something that is not the stable (master) branch => we need to change some parameters
# we compare versions fully, not just the base so that we see a difference
# between RCs + stable for the same version release
result["force_base"] = False
if check.get("update_script", None):
# if we are using the update_script, we need to set our update_branch and force
# to install the exact version we requested
if check.get("prerelease", None):
# we are tracking prereleases => we want to be on the correct prerelease channel/branch
channel = check.get("prerelease_channel", None)
if channel:
# if we have a release channel, we also set our update_branch here to our release channel
# in case it's not already set
result["update_branch"] = check.get("update_branch", channel)
# we also force our target version in the update
result["force_exact_version"] = True
else:
# we are not tracking prereleases, but aren't on the stable branch either => switch back
# to stable branch on update
result["update_branch"] = check.get("update_branch", stable_branch)
if BRANCH != result.get("prerelease_channel"):
# we force python unequality check here because that will also allow us to
# downgrade on a prerelease channel change (rc/devel => rc/maintenance)
#
# we detect channel changes by comparing the current branch with the target
# branch of the release channel - unequality means we might have to handle
# a downgrade
result["release_compare"] = "python_unequal"
else:
result["displayName"] = check.get("displayName", target)
result["displayVersion"] = check.get("displayVersion", check.get("current", "unknown"))
if check["type"] in ("github_commit"):
if check["type"] in ("github_commit",):
result["current"] = check.get("current", None)
else:
result["current"] = check.get("current", check.get("displayVersion", None))
if "pip" in result:
if not "pip_command" in check and self._settings.get(["pip_command"]) is not None:
result["pip_command"] = self._settings.get(["pip_command"])
return result
def _get_version_checker(self, target, check):
@@ -737,22 +841,45 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
else:
raise exceptions.UnknownCheckType()
def _get_update_method(self, target, check, valid_methods=None):
"""
Determines the update method for the given target and check.
If ``valid_methods`` is provided, determine method must be contained
therein to be considered valid.
Raises an ``UnknownUpdateType`` exception if method cannot be determined
or validated.
"""
method = None
if "method" in check:
method = check["method"]
else:
if "update_script" in check:
method = "update_script"
elif "pip" in check:
method = "pip"
elif "python_updater" in check:
method = "python_updated"
if method is None or (valid_methods and not method in valid_methods):
raise exceptions.UnknownUpdateType()
return method
def _get_updater(self, target, check):
"""
Retrieves the updater for the given target and check configuration. Will raise an UnknownUpdateType if updater
cannot be determined.
"""
if "update_script" in check:
return updaters.update_script
elif "pip" in check:
if not "pip_command" in check and self._settings.get(["pip_command"]) is not None:
check["pip_command"] = self._settings.get(["pip_command"])
return updaters.pip
elif "python_updater" in check:
return updaters.python_updater
else:
raise exceptions.UnknownUpdateType()
mapping = dict(update_script=updaters.update_script,
pip=updaters.pip,
python_updater=updaters.python_updater)
method = self._get_update_method(target, check, valid_methods=mapping.keys())
return mapping[method]
__plugin_name__ = "Software Update"
__plugin_author__ = "Gina Häußge"
@@ -71,7 +71,7 @@ def _python(args, cwd, python_executable, sudo=False):
return p.returncode, stdout
def update_source(git_executable, folder, target, force=False):
def _rescue_changes(git_executable, folder):
print(">>> Running: git diff --shortstat")
returncode, stdout = _git(["diff", "--shortstat"], folder, git_executable=git_executable)
if returncode != 0:
@@ -91,11 +91,30 @@ def update_source(git_executable, folder, target, force=False):
with open(patch, "wb") as f:
f.write(stdout)
return True
return False
def update_source(git_executable, folder, target, force=False, branch=None):
if _rescue_changes(git_executable, folder):
print(">>> Running: git reset --hard")
returncode, stdout = _git(["reset", "--hard"], folder, git_executable=git_executable)
if returncode != 0:
raise RuntimeError("Could not update, \"git reset --hard\" failed with returncode %d: %s" % (returncode, stdout))
print(">>> Running: git fetch")
returncode, stdout = _git(["fetch"], folder, git_executable=git_executable)
if returncode != 0:
raise RuntimeError("Could not update, \"git fetch\" failed with returncode %d: %s" % (returncode, stdout))
print(stdout)
if branch is not None and branch.strip() != "":
print(">>> Running: git checkout {}".format(branch))
returncode, stdout = _git(["checkout", branch], folder, git_executable=git_executable)
if returncode != 0:
raise RuntimeError("Could not update, \"git checkout\" failed with returncode %d: %s" % (returncode, stdout))
print(">>> Running: git pull")
returncode, stdout = _git(["pull"], folder, git_executable=git_executable)
if returncode != 0:
@@ -103,7 +122,7 @@ def update_source(git_executable, folder, target, force=False):
print(stdout)
if force:
reset_command = ["reset"]
reset_command = ["reset", "--hard"]
reset_command += [target]
print(">>> Running: git %s" % " ".join(reset_command))
@@ -134,18 +153,24 @@ def install_source(python_executable, folder, user=False, sudo=False):
def parse_arguments():
import argparse
boolean_trues = ["true", "yes", "1"]
boolean_falses = ["false", "no", "0"]
parser = argparse.ArgumentParser(prog="update-octoprint.py")
parser.add_argument("--git", action="store", type=str, dest="git_executable",
help="Specify git executable to use")
parser.add_argument("--python", action="store", type=str, dest="python_executable",
help="Specify python executable to use")
parser.add_argument("--force", action="store_true", dest="force",
help="Set this to force the update to only the specified version (nothing newer)")
parser.add_argument("--force", action="store", type=lambda x: x in boolean_trues,
dest="force", default=False,
help="Set this to true to force the update to only the specified version (nothing newer, nothing older)")
parser.add_argument("--sudo", action="store_true", dest="sudo",
help="Install with sudo")
parser.add_argument("--user", action="store_true", dest="user",
help="Install to the user site directory instead of the general site directory")
parser.add_argument("--branch", action="store", type=str, dest="branch", default=None,
help="Specify the branch to make sure is checked out")
parser.add_argument("folder", type=str,
help="Specify the base folder of the OctoPrint installation to update")
parser.add_argument("target", type=str,
@@ -167,13 +192,12 @@ def main():
python_executable = args.python_executable
folder = args.folder
target = args.target
import os
if not os.access(folder, os.W_OK):
raise RuntimeError("Could not update, base folder is not writable")
update_source(git_executable, folder, target, force=args.force)
update_source(git_executable, folder, args.target, force=args.force, branch=args.branch)
install_source(python_executable, folder, user=args.user, sudo=args.sudo)
if __name__ == "__main__":
@@ -21,14 +21,14 @@ $(function() {
self.config_cacheTtl = ko.observable();
self.config_checkoutFolder = ko.observable();
self.config_checkType = ko.observable();
self.config_updateMethod = ko.observable();
self.config_releaseChannel = ko.observable();
self.configurationDialog = $("#settings_plugin_softwareupdate_configurationdialog");
self.confirmationDialog = $("#softwareupdate_confirmation_dialog");
self.config_availableCheckTypes = [
{"key": "github_release", "name": gettext("Release")},
{"key": "git_commit", "name": gettext("Commit")}
];
self.config_availableCheckTypes = ko.observableArray([]);
self.config_availableReleaseChannels = ko.observableArray([]);
self.reloadOverlay = $("#reloadui_overlay");
@@ -97,7 +97,8 @@ $(function() {
softwareupdate: {
cache_ttl: parseInt(self.config_cacheTtl()),
octoprint_checkout_folder: self.config_checkoutFolder(),
octoprint_type: self.config_checkType()
octoprint_type: self.config_checkType(),
octoprint_release_channel: self.config_releaseChannel()
}
}
};
@@ -109,9 +110,28 @@ $(function() {
};
self._copyConfig = function() {
var updateMethod = self.settings.settings.plugins.softwareupdate.octoprint_method();
var availableCheckTypes = [];
if (updateMethod == "update_script" || updateMethod == "python") {
availableCheckTypes = [{"key": "github_release", "name": gettext("Release")},
{"key": "git_commit", "name": gettext("Commit")}];
} else {
availableCheckTypes = [];
}
self.config_availableCheckTypes(availableCheckTypes);
var availableReleaseChannels = [];
_.each(self.settings.settings.plugins.softwareupdate.octoprint_branch_mappings(), function(mapping) {
availableReleaseChannels.push({"key": mapping.branch(), "name": gettext(mapping.name() || mapping.branch())});
});
self.config_availableReleaseChannels(availableReleaseChannels);
self.config_updateMethod(updateMethod);
self.config_cacheTtl(self.settings.settings.plugins.softwareupdate.cache_ttl());
self.config_checkoutFolder(self.settings.settings.plugins.softwareupdate.octoprint_checkout_folder());
self.config_checkType(self.settings.settings.plugins.softwareupdate.octoprint_type());
self.config_releaseChannel(self.settings.settings.plugins.softwareupdate.octoprint_release_channel());
};
self.fromCheckResponse = function(data, ignoreSeen, showIfNothingNew) {
@@ -145,7 +165,7 @@ $(function() {
var octoprint = data.information["octoprint"];
if (octoprint && octoprint.hasOwnProperty("check")) {
var check = octoprint.check;
if (BRANCH != "master" && check["type"] == "github_release") {
if (check["released_version"] === false && check["type"] == "github_release") {
self.octoprintUnreleased(true);
} else {
self.octoprintUnreleased(false);
@@ -153,8 +173,8 @@ $(function() {
var checkoutFolder = (check["checkout_folder"] || "").trim();
var updateFolder = (check["update_folder"] || "").trim();
var checkType = check["type"] || "";
if ((checkType == "github_release" || checkType == "git_commit") && checkoutFolder == "" && updateFolder == "") {
var needsFolder = check["update_script"] || false;
if (needsFolder && checkoutFolder == "" && updateFolder == "") {
self.octoprintUnconfigured(true);
} else {
self.octoprintUnconfigured(false);
@@ -74,18 +74,25 @@
</div>
<div class="modal-body">
<form class="form-horizontal">
<div class="control-group">
<div class="control-group" data-bind="visible: config_updateMethod() == 'update_script' || config_updateMethod() == 'python_updater'">
<label class="control-label">{{ _('OctoPrint checkout folder') }}</label>
<div class="controls">
<input type="text" class="input-block-level" data-bind="value: config_checkoutFolder">
</div>
</div>
<div class="control-group">
<div class="control-group" data-bind="visible: config_availableCheckTypes().length > 0">
<label class="control-label">{{ _('OctoPrint version tracking') }}</label>
<div class="controls">
<select data-bind="value: config_checkType, options: config_availableCheckTypes, optionsText: 'name', optionsValue: 'key'"></select>
</div>
</div>
<div class="control-group" data-bind="visible: config_availableCheckTypes().length > 0 && config_checkType() == 'github_release'">
<label class="control-label">{{ _('OctoPrint Release Channel') }}</label>
<div class="controls">
<select data-bind="value: config_releaseChannel, options: config_availableReleaseChannels, optionsText: 'name', optionsValue: 'key'"></select>
<span class="help-inline">{{ _('Make sure you have read <a href="%(url)s" target="_blank" rel="noreferrer noopener">"Using Release Channels"</a> before switching to a release channel other than "Stable"', url="https://github.com/foosel/OctoPrint/wiki/Using-Release-Channels") }}</span>
</div>
</div>
<div class="control-group">
<label class="control-label">{{ _('Version cache TTL') }}</label>
<div class="controls">
@@ -33,9 +33,11 @@ def perform_update(target, check, target_version):
raise ConfigurationInvalid("checkout_folder and update_folder are missing for update target %s, one is needed" % target)
update_script = check["update_script"]
folder = check["update_folder"] if "update_folder" in check else check["checkout_folder"]
pre_update_script = check["pre_update_script"] if "pre_update_script" in check else None
post_update_script = check["post_update_script"] if "post_update_script" in check else None
update_branch = check.get("update_branch", "")
force_exact_version = check.get("force_exact_version", False)
folder = check.get("update_folder", check["checkout_folder"])
pre_update_script = check.get("pre_update_script", None)
post_update_script = check.get("post_update_script", None)
update_stdout = ""
update_stderr = ""
@@ -56,7 +58,11 @@ def perform_update(target, check, target_version):
### update
try:
update_command = update_script.format(python=sys.executable, folder=folder, target=target_version)
update_command = update_script.format(python=sys.executable,
folder=folder,
target=target_version,
branch=update_branch,
force="true" if force_exact_version else "false")
logger.debug("Target %s, running update script: %s" % (target, update_command))
returncode, stdout, stderr = execute(update_command, cwd=folder)
@@ -14,7 +14,69 @@ RELEASE_URL = "https://api.github.com/repos/{user}/{repo}/releases"
logger = logging.getLogger("octoprint.plugins.softwareupdate.version_checks.github_release")
def _get_latest_release(user, repo, include_prerelease=False):
def _filter_out_latest(releases,
sort_key=None,
include_prerelease=False,
prerelease_channel=None):
"""
Filters out the newest of all matching releases.
Tests:
>>> release_1_2_15 = dict(name="1.2.15", tag_name="1.2.15", html_url="some_url", published_at="2016-07-29T19:53:29Z", prerelease=False, draft=False, target_commitish="prerelease")
>>> release_1_2_16rc1 = dict(name="1.2.16rc1", tag_name="1.2.16rc1", html_url="some_url", published_at="2016-08-29T12:00:00Z", prerelease=True, draft=False, target_commitish="rc/maintenance")
>>> release_1_2_16rc2 = dict(name="1.2.16rc2", tag_name="1.2.16rc2", html_url="some_url", published_at="2016-08-30T12:00:00Z", prerelease=True, draft=False, target_commitish="rc/maintenance")
>>> release_1_2_17rc1 = dict(name="1.2.17rc1", tag_name="1.2.17rc1", html_url="some_url", published_at="2016-08-31T12:00:00Z", prerelease=True, draft=True, target_commitish="rc/maintenance")
>>> release_1_3_0rc1 = dict(name="1.3.0rc1", tag_name="1.3.0rc1", html_url="some_url", published_at="2016-12-12T12:00:00Z", prerelease=True, draft=False, target_commitish="rc/devel")
>>> release_1_4_0rc1 = dict(name="1.4.0rc1", tag_name="1.4.0rc1", html_url="some_url", published_at="2017-12-12T12:00:00Z", prerelease=True, draft=False, target_commitish="rc/future")
>>> releases = [release_1_2_15, release_1_2_16rc1, release_1_2_16rc2, release_1_2_17rc1, release_1_3_0rc1, release_1_4_0rc1]
>>> _filter_out_latest(releases, include_prerelease=False, prerelease_channel=None)
('1.2.15', '1.2.15', 'some_url')
>>> _filter_out_latest(releases, include_prerelease=True, prerelease_channel="rc/maintenance")
('1.2.16rc2', '1.2.16rc2', 'some_url')
>>> _filter_out_latest(releases, include_prerelease=True, prerelease_channel="rc/devel")
('1.3.0rc1', '1.3.0rc1', 'some_url')
>>> _filter_out_latest(releases, include_prerelease=True, prerelease_channel=None)
('1.4.0rc1', '1.4.0rc1', 'some_url')
>>> _filter_out_latest(releases, include_prerelease=True, prerelease_channel="rc/doesntexist")
('1.2.15', '1.2.15', 'some_url')
>>> _filter_out_latest([release_1_2_17rc1])
(None, None, None)
>>> _filter_out_latest([release_1_2_16rc1, release_1_2_16rc2])
(None, None, None)
"""
nothing = None, None, None
if sort_key is None:
sort_key = lambda release: release.get("published_at", None)
# filter out prereleases and drafts
filter_function = lambda rel: not rel["prerelease"] and not rel["draft"]
if include_prerelease:
if prerelease_channel:
filter_function = lambda rel: not rel["draft"] and (
not rel["prerelease"] or rel["target_commitish"] == prerelease_channel)
else:
filter_function = lambda rel: not rel["draft"]
releases = filter(filter_function, releases)
if not releases:
return nothing
# sort by sort_key
releases = sorted(releases, key=sort_key)
# latest release = last in list
latest = releases[-1]
return latest["name"], latest["tag_name"], latest.get("html_url", None)
def _get_latest_release(user, repo, compare_type,
include_prerelease=False,
prerelease_channel=None,
force_base=True):
nothing = None, None, None
r = requests.get(RELEASE_URL.format(user=user, repo=repo))
@@ -27,36 +89,55 @@ def _get_latest_release(user, repo, include_prerelease=False):
releases = r.json()
# sanitize
required_fields = {"name", "tag_name", "html_url", "draft", "prerelease", "published_at"}
required_fields = {"name", "tag_name", "html_url", "draft", "prerelease", "published_at", "target_commitish"}
releases = filter(lambda rel: set(rel.keys()) & required_fields == required_fields,
releases)
# filter out prereleases and drafts
if include_prerelease:
releases = filter(lambda rel: not rel["draft"], releases)
else:
releases = filter(lambda rel: not rel["prerelease"] and not rel["draft"],
releases)
comparable_factory = _get_comparable_factory(compare_type,
force_base=force_base)
sort_key = lambda release: comparable_factory(_get_sanitized_version(release["tag_name"]))
if not releases:
return nothing
# sort by date
comp = lambda a, b: cmp(a.get("published_at", None), b["published_at"])
releases = sorted(releases, cmp=comp)
# latest release = last in list
latest = releases[-1]
return latest["name"], latest["tag_name"], latest.get("html_url", None)
return _filter_out_latest(releases,
sort_key=sort_key,
include_prerelease=include_prerelease,
prerelease_channel=prerelease_channel)
def _get_sanitized_version(version_string):
"""
Removes "-..." prefix from version strings.
Tests:
>>> _get_sanitized_version("1.2.15")
'1.2.15'
>>> _get_sanitized_version("1.2.15-dev12")
'1.2.15'
"""
if "-" in version_string:
version_string = version_string[:version_string.find("-")]
return version_string
def _get_base_from_version_tuple(version_tuple):
"""
Reduces version tuple to base version.
Tests:
>>> _get_base_from_version_tuple(("1", "2", "15"))
('1', '2', '15')
>>> _get_base_from_version_tuple(("1", "2", "15", "*", "dev12"))
('1', '2', '15')
"""
base_version = []
for part in version_tuple:
if part.startswith("*"):
break
base_version.append(part)
return tuple(base_version)
def _get_comparable_version_pkg_resources(version_string, force_base=True):
import pkg_resources
@@ -65,12 +146,7 @@ def _get_comparable_version_pkg_resources(version_string, force_base=True):
if force_base:
if isinstance(version, tuple):
# old setuptools
base_version = []
for part in version:
if part.startswith("*"):
break
base_version.append(part)
version = tuple(base_version)
version = _get_base_from_version_tuple(version)
else:
# new setuptools
version = pkg_resources.parse_version(version.base_version)
@@ -90,32 +166,66 @@ def _get_comparable_version_semantic(version_string, force_base=True):
return version
def _get_sanitized_compare_type(compare_type, custom=None):
if not compare_type in ("python", "python_unequal",
"semantic", "semantic_unequal",
"unequal", "custom") or compare_type == "custom" and custom is None:
compare_type = "python"
return compare_type
def _get_comparable_factory(compare_type, force_base=True):
if compare_type in ("python", "python_unequal"):
return lambda version: _get_comparable_version_pkg_resources(version, force_base=force_base)
elif compare_type in ("semantic", "semantic_unequal"):
return lambda version: _get_comparable_version_semantic(version, force_base=force_base)
else:
return lambda version: version
def _get_comparator(compare_type, custom=None):
if compare_type in ("python", "semantic"):
return lambda a, b: a >= b
elif compare_type == "custom":
return custom
else:
return lambda a, b: a == b
def _is_current(release_information, compare_type, custom=None, force_base=True):
"""
Checks if the provided release information indicates the version being the most current one.
Tests:
>>> _is_current(dict(remote=dict(value=None))
True
>>> _is_current(dict(local=dict(value="1.2.15"), remote=dict(value="1.2.16")))
False
>>> _is_current(dict(local=dict(value="1.2.16dev1"), remote=dict(value="1.2.16dev2")))
True
>>> _is_current(dict(local=dict(value="1.2.16dev1"), remote=dict(value="1.2.16dev2")), force_base=False)
False
>>> _is_current(dict(local=dict(value="1.2.16dev3"), remote=dict(value="1.2.16dev2")), force_base=False)
True
>>> _is_current(dict(local=dict(value="1.2.16dev3"), remote=dict(value="1.2.16dev2")), force_base=False, compare_type="python_unequal")
False
"""
if release_information["remote"]["value"] is None:
return True
if not compare_type in ("python", "semantic", "unequal", "custom") or compare_type == "custom" and custom is None:
compare_type = "python"
compare_type = _get_sanitized_compare_type(compare_type, custom=custom)
comparable_factory = _get_comparable_factory(compare_type, force_base=force_base)
comparator = _get_comparator(compare_type, custom=custom)
sanitized_local = _get_sanitized_version(release_information["local"]["value"])
sanitized_remote = _get_sanitized_version(release_information["remote"]["value"])
try:
if compare_type == "python":
local_version = _get_comparable_version_pkg_resources(sanitized_local, force_base=force_base)
remote_version = _get_comparable_version_pkg_resources(sanitized_remote, force_base=force_base)
return local_version >= remote_version
elif compare_type == "semantic":
local_version = _get_comparable_version_semantic(sanitized_local, force_base=force_base)
remote_version = _get_comparable_version_semantic(sanitized_remote, force_base=force_base)
return local_version >= remote_version
elif compare_type == "custom":
return custom(sanitized_local, sanitized_remote)
else:
return sanitized_local == sanitized_remote
return comparator(comparable_factory(sanitized_local),
comparable_factory(sanitized_remote))
except:
logger.exception("Could not check if version is current due to an error, assuming it is")
return True
@@ -127,12 +237,17 @@ def get_latest(target, check, custom_compare=None):
current = check.get("current", None)
include_prerelease = check.get("prerelease", False)
prerelease_channel = check.get("prerelease_channel", None)
force_base = check.get("force_base", True)
compare_type = _get_sanitized_compare_type(check.get("release_compare", "python"),
custom=custom_compare)
remote_name, remote_tag, release_notes = _get_latest_release(check["user"],
check["repo"],
include_prerelease=include_prerelease)
compare_type = check["release_compare"] if "release_compare" in check else "python"
compare_type,
include_prerelease=include_prerelease,
prerelease_channel=prerelease_channel,
force_base=force_base)
information =dict(
local=dict(name=current, value=current),
+7 -6
View File
@@ -761,15 +761,16 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
printTimeLeft = dumbTotalPrintTime - cleanedPrintTime
printTimeLeftOrigin = "linear"
elif progress > self._timeEstimationForceDumbFromPercent or \
cleanedPrintTime * 60 >= self._timeEstimationForceDumbAfterMin:
# more than x% or y min printed and still no real estimate, ok, we'll use the dumb variant :/
printTimeLeft = dumbTotalPrintTime - cleanedPrintTime
else:
printTimeLeftOrigin = "linear"
if progress > self._timeEstimationForceDumbFromPercent or \
cleanedPrintTime >= self._timeEstimationForceDumbAfterMin * 60:
# more than x% or y min printed and still no real estimate, ok, we'll use the dumb variant :/
printTimeLeft = dumbTotalPrintTime - cleanedPrintTime
if printTimeLeft < 0:
if printTimeLeft is not None and printTimeLeft < 0:
# shouldn't actually happen, but let's make sure
return None, None
printTimeLeft = None
return printTimeLeft, printTimeLeftOrigin
+75 -59
View File
@@ -7,7 +7,7 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms
import uuid
from sockjs.tornado import SockJSRouter
from flask import Flask, g, request, session, Blueprint
from flask import Flask, g, request, session, Blueprint, Request, Response
from flask.ext.login import LoginManager, current_user
from flask.ext.principal import Principal, Permission, RoleNeed, identity_loaded, UserNeed
from flask.ext.babel import Babel, gettext, ngettext
@@ -168,7 +168,7 @@ class Server(object):
util.flask.enable_additional_translations(additional_folders=[s.getBaseFolder("translations")])
# setup app
self._setup_app()
self._setup_app(app)
# setup i18n
self._setup_i18n(app)
@@ -199,9 +199,15 @@ class Server(object):
pluginLifecycleManager = LifecycleManager(pluginManager)
preemptiveCache = PreemptiveCache(os.path.join(s.getBaseFolder("data"), "preemptive_cache_config.yaml"))
# ... and initialize all plugins
def octoprint_plugin_inject_factory(name, implementation):
"""Factory for injections for all OctoPrintPlugins"""
if not isinstance(implementation, octoprint.plugin.OctoPrintPlugin):
# we only care about OctoPrintPlugins
return None
return dict(
plugin_manager=pluginManager,
printer_profile_manager=printerProfileManager,
@@ -217,8 +223,13 @@ class Server(object):
)
def settings_plugin_inject_factory(name, implementation):
"""Factory for additional injections depending on plugin type"""
if not isinstance(implementation, octoprint.plugin.SettingsPlugin):
# we only care about SettingsPlugins
return None
# SettingsPlugin instnances get a PluginSettings instance injected
default_settings = implementation.get_settings_defaults()
get_preprocessors, set_preprocessors = implementation.get_settings_preprocessors()
plugin_settings = octoprint.plugin.plugin_settings(name,
@@ -228,6 +239,8 @@ class Server(object):
return dict(settings=plugin_settings)
def settings_plugin_config_migration_and_cleanup(name, implementation):
"""Take care of migrating and cleaning up any old settings"""
if not isinstance(implementation, octoprint.plugin.SettingsPlugin):
return
@@ -269,6 +282,8 @@ class Server(object):
# setup jinja2
self._setup_jinja2()
# make sure plugin lifecycle events relevant for jinja2 are taken care of
def template_enabled(name, plugin):
if plugin.implementation is None or not isinstance(plugin.implementation, octoprint.plugin.TemplatePlugin):
return
@@ -296,31 +311,12 @@ class Server(object):
try:
clazz = octoprint.util.get_class(userManagerName)
userManager = clazz()
except AttributeError, e:
except AttributeError as e:
self._logger.exception("Could not instantiate user manager {}, falling back to FilebasedUserManager!".format(userManagerName))
userManager = octoprint.users.FilebasedUserManager()
finally:
userManager.enabled = s.getBoolean(["accessControl", "enabled"])
app.wsgi_app = util.ReverseProxied(
app.wsgi_app,
s.get(["server", "reverseProxy", "prefixHeader"]),
s.get(["server", "reverseProxy", "schemeHeader"]),
s.get(["server", "reverseProxy", "hostHeader"]),
s.get(["server", "reverseProxy", "prefixFallback"]),
s.get(["server", "reverseProxy", "schemeFallback"]),
s.get(["server", "reverseProxy", "hostFallback"])
)
secret_key = s.get(["server", "secretKey"])
if not secret_key:
import string
from random import choice
chars = string.ascii_lowercase + string.ascii_uppercase + string.digits
secret_key = "".join(choice(chars) for _ in xrange(32))
s.set(["server", "secretKey"], secret_key)
s.save()
app.secret_key = secret_key
loginManager = LoginManager()
loginManager.session_protection = "strong"
loginManager.user_callback = load_user
@@ -329,18 +325,16 @@ class Server(object):
principals.identity_loaders.appendleft(users.dummy_identity_loader)
loginManager.init_app(app)
if self._host is None:
self._host = s.get(["server", "host"])
if self._port is None:
self._port = s.getInt(["server", "port"])
app.debug = self._debug
# register API blueprint
self._setup_blueprints()
## Tornado initialization starts here
if self._host is None:
self._host = s.get(["server", "host"])
if self._port is None:
self._port = s.getInt(["server", "port"])
ioloop = IOLoop()
ioloop.install()
@@ -357,7 +351,7 @@ class Server(object):
allow_client_caching=False
)
additional_mime_types=dict(mime_type_guesser=mime_type_guesser)
admin_validator = dict(access_validation=util.tornado.access_validation_factory(app, loginManager, util.flask.user_validator))
admin_validator = dict(access_validation=util.tornado.access_validation_factory(app, loginManager, util.flask.admin_validator))
no_hidden_files_validator = dict(path_validation=util.tornado.path_validation_factory(lambda path: not octoprint.util.is_hidden_path(path), status_code=404))
def joined_dict(*dicts):
@@ -382,6 +376,8 @@ class Server(object):
(r"/online.txt", util.tornado.StaticDataHandler, dict(data="online\n")),
(r"/online.gif", util.tornado.StaticDataHandler, dict(data=bytes(base64.b64decode("R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7")), content_type="image/gif"))
]
# fetch additional routes from plugins
for name, hook in pluginManager.get_hooks("octoprint.server.http.routes").items():
try:
result = hook(list(server_routes))
@@ -435,10 +431,13 @@ class Server(object):
self._stop_intermediary_server()
# initialize and bind the server
self._server = util.tornado.CustomHTTPServer(self._tornado_app, max_body_sizes=max_body_sizes, default_max_body_size=s.getInt(["server", "maxSize"]))
self._server.listen(self._port, address=self._host)
eventManager.fire(events.Events.STARTUP)
# auto connect
if s.getBoolean(["serial", "autoconnect"]):
(port, baudrate) = s.get(["serial", "port"]), s.getInt(["serial", "baudrate"])
printer_profile = printerProfileManager.get_default()
@@ -531,7 +530,8 @@ class Server(object):
def _create_socket_connection(self, session):
global printer, fileManager, analysisQueue, userManager, eventManager
return util.sockjs.PrinterStateConnection(printer, fileManager, analysisQueue, userManager, eventManager, pluginManager, session)
return util.sockjs.PrinterStateConnection(printer, fileManager, analysisQueue, userManager,
eventManager, pluginManager, session)
def _check_for_root(self):
if "geteuid" in dir(os) and os.geteuid() == 0:
@@ -635,7 +635,41 @@ class Server(object):
logging.getLogger("SERIAL").setLevel(logging.DEBUG)
logging.getLogger("SERIAL").debug("Enabling serial logging")
def _setup_app(self):
def _setup_app(self, app):
from octoprint.server.util.flask import ReverseProxiedEnvironment, OctoPrintFlaskRequest, OctoPrintFlaskResponse
s = settings()
app.debug = self._debug
secret_key = s.get(["server", "secretKey"])
if not secret_key:
import string
from random import choice
chars = string.ascii_lowercase + string.ascii_uppercase + string.digits
secret_key = "".join(choice(chars) for _ in range(32))
s.set(["server", "secretKey"], secret_key)
s.save()
app.secret_key = secret_key
reverse_proxied = ReverseProxiedEnvironment(
header_prefix=s.get(["server", "reverseProxy", "prefixHeader"]),
header_scheme=s.get(["server", "reverseProxy", "schemeHeader"]),
header_host=s.get(["server", "reverseProxy", "hostHeader"]),
header_server=s.get(["server", "reverseProxy", "serverHeader"]),
header_port=s.get(["server", "reverseProxy", "portHeader"]),
prefix=s.get(["server", "reverseProxy", "prefixFallback"]),
scheme=s.get(["server", "reverseProxy", "schemeFallback"]),
host=s.get(["server", "reverseProxy", "hostFallback"]),
server=s.get(["server", "reverseProxy", "serverFallback"]),
port=s.get(["server", "reverseProxy", "portFallback"])
)
OctoPrintFlaskRequest.environment_wrapper = reverse_proxied
app.request_class = OctoPrintFlaskRequest
app.response_class = OctoPrintFlaskResponse
@app.before_request
def before_request():
g.locale = self._get_locale()
@@ -738,32 +772,10 @@ class Server(object):
loaders = [app.jinja_loader, filesystem_loader]
if octoprint.util.is_running_from_source():
from octoprint.util.jinja import SelectedFileSystemLoader
root = os.path.abspath(os.path.join(os.path.dirname(__file__), "../../.."))
allowed = ["AUTHORS.md", "CHANGELOG.md", "SUPPORTERS.md", "THIRDPARTYLICENSES.md"]
class SourceRootFilesystemLoader(jinja2.FileSystemLoader):
def __init__(self, template_filter, prefix, *args, **kwargs):
jinja2.FileSystemLoader.__init__(self, *args, **kwargs)
self._filter = template_filter
if not prefix.endswith("/"):
prefix += "/"
self._prefix = prefix
def get_source(self, environment, template):
if not template.startswith(self._prefix):
raise jinja2.TemplateNotFound(template)
template = template[len(self._prefix):]
if not self._filter(template):
raise jinja2.TemplateNotFound(template)
return jinja2.FileSystemLoader.get_source(self, environment, template)
def list_templates(self):
templates = jinja2.FileSystemLoader.list_templates(self)
return map(lambda t: self._prefix + t, filter(self._filter, templates))
loaders.append(SourceRootFilesystemLoader(lambda t: t in allowed, "_data/", root))
loaders.append(SelectedFileSystemLoader(root, allowed, prefix="_data/"))
jinja_loader = jinja2.ChoiceLoader(loaders)
app.jinja_loader = jinja_loader
@@ -815,9 +827,13 @@ class Server(object):
self._logger.info("Preemptively caching {} (plugin {}) for {!r}".format(route, plugin, kwargs))
else:
self._logger.info("Preemptively caching {} for {!r}".format(route, kwargs))
headers = kwargs.get("headers", dict())
headers["X-Preemptive-Record"] = "no"
kwargs["headers"] = headers
builder = EnvironBuilder(**kwargs)
with preemptive_cache.disable_access_logging():
app(builder.get_environ(), lambda *a, **kw: None)
app(builder.get_environ(), lambda *a, **kw: None)
except:
self._logger.exception("Error while trying to preemptively cache {} for {!r}".format(route, kwargs))
@@ -950,7 +966,7 @@ class Server(object):
# that might be caused by the user still having the folder open somewhere, let's try again after
# waiting a bit
import time
for n in xrange(3):
for n in range(3):
time.sleep(0.5)
self._logger.debug("Creating {path}: Retry #{retry} after {time}s".format(path=path, retry=n+1, time=(n + 1)*0.5))
try:
-94
View File
@@ -155,97 +155,3 @@ def get_plugin_hash():
plugin_hash = hashlib.sha1()
plugin_hash.update(",".join(ui_plugins))
return plugin_hash.hexdigest()
#~~ reverse proxy compatible WSGI middleware
class ReverseProxied(object):
"""
Wrap the application in this middleware and configure the
front-end server to add these headers, to let you quietly bind
this to a URL other than / and to an HTTP scheme that is
different than what is used locally.
In nginx:
.. code-block:: none
location /myprefix {
proxy_pass http://192.168.0.1:5001;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Scheme $scheme;
proxy_set_header X-Script-Name /myprefix;
}
Alternatively define prefix and scheme via config.yaml:
.. code-block:: yaml
server:
baseUrl: /myprefix
scheme: http
:param app: the WSGI application
:param header_script_name: the HTTP header in the wsgi environment from which to determine the prefix
:param header_scheme: the HTTP header in the wsgi environment from which to determine the scheme
:param header_host: the HTTP header in the wsgi environment from which to determine the host for which to generate external URLs
:param base_url: the prefix to use as fallback if headers are not set
:param scheme: the scheme to use as fallback if headers are not set
:param host: the host to use as fallback if headers are not set
"""
def __init__(self, app, header_prefix="x-script-name", header_scheme="x-scheme", header_host="x-forwarded-host", base_url="", scheme="", host=""):
self.app = app
# headers for prefix & scheme & host, converted to conform to WSGI format
to_wsgi_format = lambda header: "HTTP_" + header.upper().replace("-", "_")
self._header_prefix = to_wsgi_format(header_prefix)
self._header_scheme = to_wsgi_format(header_scheme)
self._header_host = to_wsgi_format(header_host)
# fallback prefix & scheme & host from config
self._fallback_prefix = base_url
self._fallback_scheme = scheme
self._fallback_host = host
def __call__(self, environ, start_response):
# determine prefix
prefix = environ.get(self._header_prefix, "")
if not prefix:
prefix = self._fallback_prefix
# rewrite SCRIPT_NAME and if necessary also PATH_INFO based on prefix
if prefix:
environ["SCRIPT_NAME"] = prefix
path_info = environ["PATH_INFO"]
if path_info.startswith(prefix):
environ["PATH_INFO"] = path_info[len(prefix):]
# determine scheme
scheme = environ.get(self._header_scheme, "")
if scheme and "," in scheme:
# Scheme might be something like "https,https" if doubly-reverse-proxied
# without stripping original scheme header first, make sure to only use
# the first entry in such a case. See #1391.
scheme, _ = map(lambda x: x.strip(), scheme.split(",", 1))
if not scheme:
scheme = self._fallback_scheme
# rewrite wsgi.url_scheme based on scheme
if scheme:
environ["wsgi.url_scheme"] = scheme
# determine host
host = environ.get(self._header_host, "")
if not host:
host = self._fallback_host
# rewrite host header based on host
if host:
environ["HTTP_HOST"] = host
# call wrapped app with rewritten environment
return self.app(environ, start_response)
+246 -25
View File
@@ -219,6 +219,204 @@ def fix_webassets_filtertool():
FilterTool._wrap_cache = fixed_wrap_cache
#~~ WSGI environment wrapper for reverse proxying
class ReverseProxiedEnvironment(object):
@staticmethod
def to_header_candidates(values):
if values is None:
return []
if not isinstance(values, (list, tuple)):
values = [values]
to_wsgi_format = lambda header: "HTTP_" + header.upper().replace("-", "_")
return map(to_wsgi_format, values)
def __init__(self,
header_prefix=None,
header_scheme=None,
header_host=None,
header_server=None,
header_port=None,
prefix=None,
scheme=None,
host=None,
server=None,
port=None):
# sensible defaults
if header_prefix is None:
header_prefix = ["x-script-name"]
if header_scheme is None:
header_scheme = ["x-forwarded-proto", "x-scheme"]
if header_host is None:
header_host = ["x-forwarded-host"]
if header_server is None:
header_server = ["x-forwarded-server"]
if header_port is None:
header_port = ["x-forwarded-port"]
# header candidates
self._headers_prefix = self.to_header_candidates(header_prefix)
self._headers_scheme = self.to_header_candidates(header_scheme)
self._headers_host = self.to_header_candidates(header_host)
self._headers_server = self.to_header_candidates(header_server)
self._headers_port = self.to_header_candidates(header_port)
# fallback prefix & scheme & host from config
self._fallback_prefix = prefix
self._fallback_scheme = scheme
self._fallback_host = host
self._fallback_server = server
self._fallback_port = port
def __call__(self, environ):
def retrieve_header(header_type):
candidates = getattr(self, "_headers_" + header_type, [])
fallback = getattr(self, "_fallback_" + header_type, None)
for candidate in candidates:
value = environ.get(candidate, None)
if value is not None:
return value
else:
return fallback
def host_to_server_and_port(host, scheme):
if host is None:
return None, None
if ":" in host:
server, port = host.split(":", 1)
else:
server = host
port = "443" if scheme == "https" else "80"
return server, port
# determine prefix
prefix = retrieve_header("prefix")
if prefix is not None:
environ["SCRIPT_NAME"] = prefix
path_info = environ["PATH_INFO"]
if path_info.startswith(prefix):
environ["PATH_INFO"] = path_info[len(prefix):]
# determine scheme
scheme = retrieve_header("scheme")
if scheme is not None and "," in scheme:
# Scheme might be something like "https,https" if doubly-reverse-proxied
# without stripping original scheme header first, make sure to only use
# the first entry in such a case. See #1391.
scheme, _ = map(lambda x: x.strip(), scheme.split(",", 1))
if scheme is not None:
environ["wsgi.url_scheme"] = scheme
# determine host
url_scheme = environ["wsgi.url_scheme"]
host = retrieve_header("host")
if host is not None:
# if we have a host, we take server_name and server_port from it
server, port = host_to_server_and_port(host, url_scheme)
environ["HTTP_HOST"] = host
environ["SERVER_NAME"] = server
environ["SERVER_PORT"] = port
elif environ.get("HTTP_HOST", None) is not None:
# if we have a Host header, we use that and make sure our server name and port properties match it
host = environ["HTTP_HOST"]
server, port = host_to_server_and_port(host, url_scheme)
environ["SERVER_NAME"] = server
environ["SERVER_PORT"] = port
else:
# else we take a look at the server and port headers and if we have
# something there we derive the host from it
# determine server - should usually not be used
server = retrieve_header("server")
if server is not None:
environ["SERVER_NAME"] = server
# determine port - should usually not be used
port = retrieve_header("port")
if port is not None:
environ["SERVER_PORT"] = port
# reconstruct host header
if url_scheme == "http" and environ["SERVER_PORT"] == "80" or url_scheme == "https" and environ["SERVER_PORT"] == "443":
# default port for scheme, can be skipped
environ["HTTP_HOST"] = environ["SERVER_NAME"]
else:
environ["HTTP_HOST"] = environ["SERVER_NAME"] + ":" + environ["SERVER_PORT"]
# call wrapped app with rewritten environment
return environ
#~~ request and response versions
from werkzeug.wrappers import cached_property
class OctoPrintFlaskRequest(flask.Request):
environment_wrapper = staticmethod(lambda x: x)
def __init__(self, environ, *args, **kwargs):
# apply environment wrapper to provided WSGI environment
flask.Request.__init__(self, self.environment_wrapper(environ), *args, **kwargs)
@cached_property
def cookies(self):
# strip cookie_suffix from all cookies in the request, return result
cookies = flask.Request.cookies.__get__(self)
result = dict()
desuffixed = dict()
for key, value in cookies.items():
if key.endswith(self.cookie_suffix):
desuffixed[key[:-len(self.cookie_suffix)]] = value
else:
result[key] = value
result.update(desuffixed)
return result
@cached_property
def server_name(self):
"""Short cut to the request's server name header"""
return self.environ.get("SERVER_NAME")
@cached_property
def server_port(self):
"""Short cut to the request's server port header"""
return self.environ.get("SERVER_PORT")
@cached_property
def cookie_suffix(self):
"""
Request specific suffix for set and read cookies
We need this because cookies are not port-specific and we don't want to overwrite our
session and other cookies from one OctoPrint instance on our machine with those of another
one who happens to listen on the same address albeit a different port.
"""
return "_P" + self.server_port
class OctoPrintFlaskResponse(flask.Response):
def set_cookie(self, key, *args, **kwargs):
# restrict cookie path to script root
kwargs["path"] = flask.request.script_root + kwargs.get("path", "/")
# add request specific cookie suffix to name
flask.Response.set_cookie(self, key + flask.request.cookie_suffix, *args, **kwargs)
def delete_cookie(self, key, *args, **kwargs):
# restrict cookie path to script root
kwargs["path"] = flask.request.script_root + kwargs.get("path", "/")
# add request specific cookie suffix to name
flask.Response.delete_cookie(self, key + flask.request.cookie_suffix, *args, **kwargs)
#~~ passive login helper
def passive_login():
@@ -312,6 +510,18 @@ class LessSimpleCache(BaseCache):
return False
return len(self._cache) > self._threshold
def __getitem__(self, key):
return self.get(key)
def __setitem__(self, key, value):
return self.set(key, value)
def __delitem__(self, key):
return self.delete(key)
def __contains__(self, key):
return key in self._cache
_cache = LessSimpleCache()
def cached(timeout=5 * 60, key=lambda: "view:%s" % flask.request.path, unless=None, refreshif=None, unless_response=None):
@@ -358,6 +568,11 @@ def cached(timeout=5 * 60, key=lambda: "view:%s" % flask.request.path, unless=No
return decorator
def is_in_cache(key=lambda: "view:%s" % flask.request.path):
if callable(key):
key = key()
return key in _cache
def cache_check_headers():
return "no-cache" in flask.request.cache_control or "no-cache" in flask.request.pragma
@@ -386,9 +601,8 @@ class PreemptiveCache(object):
self._lock = threading.RLock()
self._logger = logging.getLogger(__name__ + "." + self.__class__.__name__)
self._log_access = True
def record(self, data, unless=None):
def record(self, data, unless=None, root=None):
if callable(unless) and unless():
return
@@ -397,15 +611,28 @@ class PreemptiveCache(object):
entry_data = entry_data()
if entry_data is not None:
from flask import request
self.add_data(request.path, entry_data)
if root is None:
from flask import request
root = request.path
self.add_data(root, entry_data)
@contextlib.contextmanager
def disable_access_logging(self):
with self._lock:
self._log_access = False
yield
self._log_access = True
def has_record(self, data, root=None):
if callable(data):
data = data()
if data is None:
return False
if root is None:
from flask import request
root = request.path
all_data = self.get_data(root)
for existing in all_data:
if self._compare_data(data, existing):
return True
return False
def clean_all_data(self, cleanup_function):
assert callable(cleanup_function)
@@ -467,20 +694,12 @@ class PreemptiveCache(object):
self.set_all_data(all_data)
def add_data(self, root, data):
from octoprint.util import dict_filter
def strip_ignored(d):
return dict_filter(d, lambda k, v: not k.startswith("_"))
def compare(a, b):
return set(strip_ignored(a).items()) == set(strip_ignored(b).items())
def split_matched_and_unmatched(entry, entries):
matched = []
unmatched = []
for e in entries:
if compare(e, entry):
if self._compare_data(e, entry):
matched.append(e)
else:
unmatched.append(e)
@@ -488,12 +707,6 @@ class PreemptiveCache(object):
return matched, unmatched
with self._lock:
if not self._log_access:
self._logger.debug(
"Not updating timestamp and counter for {} and {!r}, currently flagged as disabled".format(root,
data))
return
cache_data = self.get_all_data()
if not root in cache_data:
@@ -522,6 +735,14 @@ class PreemptiveCache(object):
self.set_data(root, [to_persist] + other)
def _compare_data(self, a, b):
from octoprint.util import dict_filter
def strip_ignored(d):
return dict_filter(d, lambda k, v: not k.startswith("_"))
return set(strip_ignored(a).items()) == set(strip_ignored(b).items())
def preemptively_cached(cache, data, unless=None):
def decorator(f):
+89 -8
View File
@@ -104,18 +104,22 @@ class UploadStorageFallbackHandler(tornado.web.RequestHandler):
true
------WebKitFormBoundarypYiSUx63abAmhT5C
Content-Disposition: form-data; name="file.path"
Content-Type: text/plain; charset=utf-8
/tmp/tmpzupkro
------WebKitFormBoundarypYiSUx63abAmhT5C
Content-Disposition: form-data; name="file.name"
Content-Type: text/plain; charset=utf-8
test.gcode
------WebKitFormBoundarypYiSUx63abAmhT5C
Content-Disposition: form-data; name="file.content_type"
Content-Type: text/plain; charset=utf-8
application/octet-stream
------WebKitFormBoundarypYiSUx63abAmhT5C
Content-Disposition: form-data; name="file.size"
Content-Type: text/plain; charset=utf-8
349182
------WebKitFormBoundarypYiSUx63abAmhT5C--
@@ -141,6 +145,9 @@ class UploadStorageFallbackHandler(tornado.web.RequestHandler):
if suffix_type in self._suffixes and suffix is not None:
self._suffixes[suffix_type] = suffix
# multipart boundary
self._multipart_boundary = None
# Parts, files and values will be stored here
self._parts = dict()
self._files = []
@@ -177,7 +184,7 @@ class UploadStorageFallbackHandler(tornado.web.RequestHandler):
if self.is_multipart():
if not self._bytes_left:
# we don't support requests without a content-length
raise tornado.web.HTTPError(400, reason="No Content-Length supplied")
raise tornado.web.HTTPError(400, log_message="No Content-Length supplied")
# extract the multipart boundary
fields = self._content_type.split(";")
@@ -190,7 +197,14 @@ class UploadStorageFallbackHandler(tornado.web.RequestHandler):
self._multipart_boundary = tornado.escape.utf8(v)
break
else:
self._multipart_boundary = None
# RFC2046 section 5.1 (as referred to from RFC 7578) defines the boundary
# parameter as mandatory for multipart requests:
#
# The only mandatory global parameter for the "multipart" media type is
# the boundary parameter, which consists of 1 to 70 characters [...]
#
# So no boundary? 400 Bad Request
raise tornado.web.HTTPError(400, log_message="No multipart boundary supplied")
else:
self._fallback(self.request, b"")
self._finished = True
@@ -272,9 +286,19 @@ class UploadStorageFallbackHandler(tornado.web.RequestHandler):
header = header[header_check:]
# convert to dict
header = tornado.httputil.HTTPHeaders.parse(header.decode("utf-8"))
try:
header = tornado.httputil.HTTPHeaders.parse(header.decode("utf-8"))
except UnicodeDecodeError:
try:
header = tornado.httputil.HTTPHeaders.parse(header.decode("iso-8859-1"))
except:
# looks like we couldn't decode something here neither as UTF-8 nor ISO-8859-1
self._logger.warn("Could not decode multipart headers in request, should be either UTF-8 or ISO-8859-1")
self.send_error(400)
return
disp_header = header.get("Content-Disposition", "")
disposition, disp_params = tornado.httputil._parse_header(disp_header)
disposition, disp_params = _parse_header(disp_header, strip_quotes=False)
if disposition != "form-data":
self._logger.warn("Got a multipart header without form-data content disposition, ignoring that one")
@@ -283,7 +307,22 @@ class UploadStorageFallbackHandler(tornado.web.RequestHandler):
self._logger.warn("Got a multipart header without name, ignoring that one")
return
self._current_part = self._on_part_start(disp_params["name"], header.get("Content-Type", None), filename=disp_params["filename"] if "filename" in disp_params else None)
filename = disp_params.get("filename*", None) # RFC 5987 header present?
if filename is not None:
try:
filename = _extended_header_value(filename)
except:
# parse error, this is not RFC 5987 compliant after all
self._logger.warn("extended filename* value {!r} is not RFC 5987 compliant".format(filename))
self.send_error(400)
return
else:
# no filename* header, just strip quotes from filename header then and be done
filename = _strip_value_quotes(disp_params.get("filename", None))
self._current_part = self._on_part_start(_strip_value_quotes(disp_params["name"]),
header.get("Content-Type", None),
filename=filename)
def _on_part_start(self, name, content_type, filename=None):
"""
@@ -357,7 +396,7 @@ class UploadStorageFallbackHandler(tornado.web.RequestHandler):
"""
self._new_body = b""
for name, part in self._parts.iteritems():
for name, part in self._parts.items():
if "filename" in part:
# add form fields for filename, path, size and content_type for all files contained in the request
if not "path" in part:
@@ -371,11 +410,12 @@ class UploadStorageFallbackHandler(tornado.web.RequestHandler):
if "content_type" in part:
parameters["content_type"] = part["content_type"]
fields = dict((self._suffixes[key], value) for (key, value) in parameters.iteritems())
for n, p in fields.iteritems():
fields = dict((self._suffixes[key], value) for (key, value) in parameters.items())
for n, p in fields.items():
key = name + "." + n
self._new_body += b"--%s\r\n" % self._multipart_boundary
self._new_body += b"Content-Disposition: form-data; name=\"%s\"\r\n" % key
self._new_body += b"Content-Type: text/plain; charset=utf-8\r\n"
self._new_body += b"\r\n"
self._new_body += b"%s\r\n" % p
elif "data" in part:
@@ -430,6 +470,47 @@ class UploadStorageFallbackHandler(tornado.web.RequestHandler):
options = _handle_method
def _parse_header(line, strip_quotes=True):
parts = tornado.httputil._parseparam(';' + line)
key = next(parts)
pdict = {}
for p in parts:
i = p.find('=')
if i >= 0:
name = p[:i].strip().lower()
value = p[i + 1:].strip()
if strip_quotes:
value = _strip_value_quotes(value)
pdict[name] = value
return key, pdict
def _strip_value_quotes(value):
if not value:
return value
if len(value) >= 2 and value[0] == value[-1] == '"':
value = value[1:-1]
value = value.replace('\\\\', '\\').replace('\\"', '"')
return value
def _extended_header_value(value):
if not value:
return value
if value.lower().startswith("iso-8859-1'") or value.lower().startswith("utf-8'"):
# RFC 5987 section 3.2
from urllib import unquote
encoding, _, value = value.split("'", 2)
return unquote(octoprint.util.to_str(value, encoding="iso-8859-1")).decode(encoding)
else:
# no encoding provided, strip potentially present quotes and call it a day
return octoprint.util.to_unicode(_strip_value_quotes(value), encoding="utf-8")
class WsgiInputContainer(object):
"""
A WSGI container for use with Tornado that allows supplying the request body to be used for ``wsgi.input`` in the
+56 -4
View File
@@ -9,7 +9,7 @@ import os
import datetime
from collections import defaultdict
from flask import request, g, url_for, make_response, render_template, send_from_directory, redirect
from flask import request, g, url_for, make_response, render_template, send_from_directory, redirect, abort
import octoprint.plugin
@@ -20,6 +20,7 @@ from octoprint.settings import settings
from octoprint.filemanager import get_all_extensions
import re
import base64
from . import util
@@ -29,14 +30,65 @@ _logger = logging.getLogger(__name__)
_valid_id_re = re.compile("[a-z_]+")
_valid_div_re = re.compile("[a-zA-Z_-]+")
def _preemptive_unless(base_url=None):
if base_url is None:
base_url = request.url_root
cache_disabled = not settings().getBoolean(["devel", "cache", "preemptive"]) \
or base_url in settings().get(["server", "preemptiveCache", "exceptions"]) \
or not (base_url.startswith("http://") or base_url.startswith("https://"))
recording_disabled = request.headers.get("X-Preemptive-Record", "yes") == "no"
return cache_disabled or recording_disabled
def _preemptive_data(path=None, base_url=None):
if path is None:
path = request.path
if base_url is None:
base_url = request.url_root
return dict(path=path,
base_url=base_url,
query_string="l10n={}".format(g.locale.language) if g.locale else "en")
def _cache_key(url=None, locale=None):
if url is None:
url = request.base_url
if locale is None:
locale = g.locale.language if g.locale else "en"
return "view:{}:{}".format(url, locale)
@app.route("/cached.gif")
def in_cache():
url = request.base_url.replace("/cached.gif", "/")
path = request.path.replace("/cached.gif", "/")
key = _cache_key(url)
data = _preemptive_data(path=path)
response = make_response(bytes(base64.b64decode("R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7")))
response.headers["Content-Type"] = "image/gif"
if _preemptive_unless(base_url=url) or not preemptiveCache.has_record(data, root=path):
_logger.info("Preemptive cache not active for path {} and data {!r}, signaling as cached".format(path, data))
return response
elif util.flask.is_in_cache(key):
_logger.info("Found path {} in cache (key: {}), signaling as cached".format(path, key))
return response
else:
_logger.debug("Path {} not yet cached (key: {}), signaling as missing".format(path, key))
return abort(404)
@app.route("/")
@util.flask.preemptively_cached(cache=preemptiveCache,
data=lambda: dict(path=request.path, base_url=request.url_root, query_string="l10n={}".format(g.locale.language) if g.locale else "en"),
unless=lambda: request.url_root in settings().get(["server", "preemptiveCache", "exceptions"]) or not (request.url_root.startswith("http://") or request.url_root.startswith("https://")))
data=_preemptive_data,
unless=_preemptive_unless)
@util.flask.conditional(lambda: _check_etag_and_lastmodified_for_index(), NOT_MODIFIED)
@util.flask.cached(timeout=-1,
refreshif=lambda cached: _validate_cache_for_index(cached),
key=lambda: "view:{}:{}".format(request.base_url, g.locale.language if g.locale else "en"),
key=_cache_key,
unless_response=lambda response: util.flask.cache_check_response_headers(response))
@util.flask.etagged(lambda _: _compute_etag_for_index())
@util.flask.lastmodified(lambda _: _compute_date_for_index())
+13 -9
View File
@@ -46,7 +46,7 @@ def settings(init=False, basedir=None, configfile=None):
(False, default). If this is set to True and the plugin manager has already been initialized, a :class:`ValueError`
will be raised. The same will happen if the plugin manager has not yet been initialized and this is set to
False.
basedir (str): Path of the base directoy for all of OctoPrint's settings, log files, uploads etc. If not set
basedir (str): Path of the base directory for all of OctoPrint's settings, log files, uploads etc. If not set
the default will be used: ``~/.octoprint`` on Linux, ``%APPDATA%/OctoPrint`` on Windows and
``~/Library/Application Support/OctoPrint`` on MacOS.
configfile (str): Path of the configuration file (``config.yaml``) to work on. If not set the default will
@@ -108,12 +108,16 @@ default_settings = {
"firstRun": True,
"secretKey": None,
"reverseProxy": {
"prefixHeader": "X-Script-Name",
"schemeHeader": "X-Scheme",
"hostHeader": "X-Forwarded-Host",
"prefixFallback": "",
"schemeFallback": "",
"hostFallback": ""
"prefixHeader": None,
"schemeHeader": None,
"hostHeader": None,
"serverHeader": None,
"portHeader": None,
"prefixFallback": None,
"schemeFallback": None,
"hostFallback": None,
"serverFallback": None,
"portFallback": None
},
"uploads": {
"maxSize": 1 * 1024 * 1024 * 1024, # 1GB
@@ -874,9 +878,9 @@ class Settings(object):
while len(path) > 1:
key = path.pop(0)
if key in config and key in defaults:
if key in config:
config = config[key]
defaults = defaults[key]
defaults = defaults.get(key, dict())
elif incl_defaults and key in defaults:
config = {}
defaults = defaults[key]
+29 -6
View File
@@ -153,20 +153,26 @@
if (baseUrl[baseUrl.length - 1] != "/") {
baseUrl += "/";
}
var indexCachedUrl = baseUrl + "cached.gif";
var serverOnlineUrl = baseUrl + "online.gif";
var backendOnlineUrl = baseUrl + "intermediary.gif";
var serverTimeout;
var cachedTimeout;
var message = window.document.getElementById("message");
var serverIsOnline = false;
var serverOnlineCallback = function(result) {
var indexCached = false;
var indexCachedCallback = function(result) {
if (result == "load") {
// our online.gif loaded, so the server is up, let's reload
serverIsOnline = true;
if (indexCached) {
return;
}
// our cached.gif loaded, so the index is cached now, let's reload
indexCached = true;
message.className = "pulsate1 green";
message.innerText = "OctoPrint server online, reloading page...";
message.innerText = "OctoPrint server ready, reloading page...";
var reloadUrl = baseUrl + currentQuery + currentFragment;
if (reloadUrl == window.location.href) {
@@ -175,7 +181,21 @@
window.location.href = reloadUrl;
}
} else {
// online.gif still not available, let's look at
// cached.gif still not available, let's look at it again in a second
cachedTimeout = setTimeout(function() {
ping(indexCachedUrl, timeout, indexCachedCallback);
}, 1000)
}
};
var serverIsOnline = false;
var serverOnlineCallback = function(result) {
if (result == "load") {
// our online.gif loaded, so the server is up, let's wait for it to become ready
serverIsOnline = true;
ping(indexCachedUrl, timeout, indexCachedCallback);
} else {
// online.gif still not available, let's look at it again later
var interval = 10;
if (intervals.length) {
interval = intervals.shift();
@@ -204,6 +224,9 @@
if (serverTimeout) {
window.clearTimeout(serverTimeout);
}
if (cachedTimeout) {
window.clearTimeout(cachedTimeout);
}
message.className = "red";
message.innerHTML = "Looks like something went wrong during startup, the server is gone again. You should check <code>octoprint.log</code>.";
+114 -3
View File
@@ -363,7 +363,7 @@ function bytesFromSize(size) {
function formatDuration(seconds) {
if (!seconds) return "-";
if (seconds < 0) return "00:00:00";
if (seconds < 1) return "00:00:00";
var s = seconds % 60;
var m = (seconds % 3600) / 60;
@@ -373,8 +373,7 @@ function formatDuration(seconds) {
}
function formatFuzzyEstimation(seconds, base) {
if (!seconds) return "-";
if (seconds < 0) return "-";
if (!seconds || seconds < 1) return "-";
var m;
if (base != undefined) {
@@ -387,6 +386,118 @@ function formatFuzzyEstimation(seconds, base) {
return m.fromNow(true);
}
function formatFuzzyPrintTime(totalSeconds) {
/**
* Formats a print time estimate in a very fuzzy way.
*
* Accuracy decreases the higher the estimation is:
*
* * less than 30s: "a couple of seconds"
* * 30s to a minute: "less than a minute"
* * 1 to 30min: rounded to full minutes, above 30s is minute + 1 ("27 minutes", "2 minutes")
* * 30min to 40min: "40 minutes"
* * 40min to 50min: "50 minutes"
* * 50min to 1h: "1 hour"
* * 1 to 12h: rounded to half hours, 15min to 45min is ".5", above that hour + 1 ("4 hours", "2.5 hours")
* * 12 to 24h: rounded to full hours, above 30min is hour + 1, over 23.5h is "1 day"
* * Over a day: rounded to half days, 8h to 16h is ".5", above that days + 1 ("1 day", "4 days", "2.5 days")
*/
if (!totalSeconds || totalSeconds < 1) return "-";
var d = moment.duration(totalSeconds, "seconds");
var seconds = d.seconds();
var minutes = d.minutes();
var hours = d.hours();
var days = d.asDays();
var replacements = {
days: days,
hours: hours,
minutes: minutes,
seconds: seconds,
totalSeconds: totalSeconds
};
var text = "-";
if (days >= 1) {
// days
if (hours >= 16) {
replacements.days += 1;
text = gettext("%(days)d days");
} else if (hours >= 8 && hours < 16) {
text = gettext("%(days)d.5 days");
} else {
if (days == 1) {
text = gettext("%(days)d day");
} else {
text = gettext("%(days)d days");
}
}
} else if (hours >= 1) {
// only hours
if (hours < 12) {
if (minutes < 15) {
// less than .15 => .0
if (hours == 1) {
text = gettext("%(hours)d hour");
} else {
text = gettext("%(hours)d hours");
}
} else if (minutes >= 15 && minutes < 45) {
// between .25 and .75 => .5
text = gettext("%(hours)d.5 hours");
} else {
// over .75 => hours + 1
replacements.hours += 1;
text = gettext("%(hours)d hours");
}
} else {
if (hours == 23 && minutes > 30) {
// over 23.5 hours => 1 day
text = gettext("1 day");
} else {
if (minutes > 30) {
// over .5 => hours + 1
replacements.hours += 1;
}
text = gettext("%(hours)d hours");
}
}
} else if (minutes >= 1) {
// only minutes
if (minutes < 2) {
if (seconds < 30) {
text = gettext("a minute");
} else {
text = gettext("2 minutes");
}
} else if (minutes < 30) {
if (seconds > 30) {
replacements.minutes += 1;
}
text = gettext("%(minutes)d minutes");
} else if (minutes <= 40) {
text = gettext("40 minutes");
} else if (minutes <= 50) {
text = gettext("50 minutes");
} else {
text = gettext("1 hour");
}
} else {
// only seconds
if (seconds < 30) {
text = gettext("a couple of seconds");
} else {
text = gettext("less than a minute");
}
}
return _.sprintf(text, replacements);
}
function formatDate(unixTimestamp) {
if (!unixTimestamp) return "-";
return moment.unix(unixTimestamp).format(gettext(/* L10N: Date format */ "YYYY-MM-DD HH:mm"));
@@ -349,12 +349,12 @@ $(function() {
}
}
}
output += gettext("Estimated Print Time") + ": " + formatDuration(data["gcodeAnalysis"]["estimatedPrintTime"]) + "<br>";
output += gettext("Estimated print time") + ": " + formatFuzzyPrintTime(data["gcodeAnalysis"]["estimatedPrintTime"]) + "<br>";
}
if (data["prints"] && data["prints"]["last"]) {
output += gettext("Last Printed") + ": " + formatTimeAgo(data["prints"]["last"]["date"]) + "<br>";
output += gettext("Last printed") + ": " + formatTimeAgo(data["prints"]["last"]["date"]) + "<br>";
if (data["prints"]["last"]["lastPrintTime"]) {
output += gettext("Last Print Time") + ": " + formatDuration(data["prints"]["last"]["lastPrintTime"]);
output += gettext("Last print time") + ": " + formatDuration(data["prints"]["last"]["lastPrintTime"]);
}
}
return output;
@@ -435,7 +435,7 @@ $(function() {
} else {
var output = [];
output.push(gettext("Model size") + ": " + model.width.toFixed(2) + "mm &times; " + model.depth.toFixed(2) + "mm &times; " + model.height.toFixed(2) + "mm");
output.push(gettext("Estimated total print time") + ": " + formatFuzzyEstimation(model.printTime));
output.push(gettext("Estimated total print time") + ": " + formatFuzzyPrintTime(model.printTime));
output.push(gettext("Estimated layer height") + ": " + model.layerHeight.toFixed(2) + gettext("mm"));
output.push(gettext("Layer count") + ": " + model.layersPrinted.toFixed(0) + " " + gettext("printed") + ", " + model.layersTotal.toFixed(0) + " " + gettext("visited"));
@@ -462,17 +462,17 @@ $(function() {
var output = [];
output.push(gettext("Layer number") + ": " + (layer.number + 1));
output.push(gettext("Layer height") + " (mm): " + layer.height);
output.push(gettext("GCODE commands in layer") + ": " + layer.commands);
output.push(gettext("GCODE commands") + ": " + layer.commands);
if (layer.filament != undefined) {
if (layer.filament.length == 1) {
output.push(gettext("Filament used by layer") + ": " + layer.filament[0].toFixed(2) + "mm");
output.push(gettext("Filament") + ": " + layer.filament[0].toFixed(2) + "mm");
} else {
for (var i = 0; i < layer.filament.length; i++) {
output.push(gettext("Filament used by layer") + " (" + gettext("Tool") + " " + i + "): " + layer.filament[i].toFixed(2) + "mm");
output.push(gettext("Filament") + " (" + gettext("Tool") + " " + i + "): " + layer.filament[i].toFixed(2) + "mm");
}
}
}
output.push(gettext("Print time for layer") + ": " + formatFuzzyEstimation(layer.printTime));
output.push(gettext("Estimated print time") + ": " + formatDuration(layer.printTime));
self.ui_layerInfo(output.join("<br>"));
@@ -52,9 +52,9 @@ $(function() {
self.estimatedPrintTimeString = ko.pureComputed(function() {
if (self.lastPrintTime())
return formatFuzzyEstimation(self.lastPrintTime());
return formatFuzzyPrintTime(self.lastPrintTime());
if (self.estimatedPrintTime())
return formatFuzzyEstimation(self.estimatedPrintTime());
return formatFuzzyPrintTime(self.estimatedPrintTime());
return "-";
});
self.byteString = ko.pureComputed(function() {
@@ -78,17 +78,17 @@ $(function() {
if (!self.printTime() || !(self.isPrinting() || self.isPaused())) {
return "-";
} else {
return gettext("Calculating...");
return gettext("Still stabilizing...");
}
} else {
return formatFuzzyEstimation(self.printTimeLeft());
return formatFuzzyPrintTime(self.printTimeLeft());
}
});
self.printTimeLeftOriginString = ko.pureComputed(function() {
var value = self.printTimeLeftOrigin();
switch (value) {
case "linear": {
return gettext("Based on a linear approximation (accuracy highly dependent on the model)");
return gettext("Based on a linear approximation (very low accuracy, especially at the beginning of the print)");
}
case "analysis": {
return gettext("Based on the estimate from analysis of file (medium accuracy)");
@@ -68,6 +68,20 @@ $(function() {
});
};
self.generateApikey = function() {
if (!CONFIG_ACCESS_CONTROL) return;
self.users.generateApikey(self.currentUser().name, function(response) {
self.access_apikey(response.apikey);
});
};
self.deleteApikey = function() {
if (!CONFIG_ACCESS_CONTROL) return;
self.users.deleteApikey(self.currentUser().name, function() {
self.access_apikey(undefined);
});
};
self.updateSettings = function(username, settings, callback) {
if (!CONFIG_ACCESS_CONTROL) return;
@@ -25,8 +25,8 @@
<div class="controls">
<div class="input-append">
<input type="text" class="input-block-level uneditable-input" id="userSettings-access_apikey" data-bind="value: access_apikey, valueUpdate: 'input', attr: {placeholder: '{{ _('N/A') }}'}">
<a class="btn" title="Generate new Apikey" data-bind="click: function() { users.confirmGenerateApikey(); }"><i class="icon-refresh"></i></a>
<a class="btn btn-danger" title="Delete Apikey" data-bind="click: function() { users.confirmDeleteApikey(); }"><i class="icon-trash"></i></a>
<a class="btn" title="Generate new Apikey" data-bind="click: generateApikey"><i class="icon-refresh"></i></a>
<a class="btn btn-danger" title="Delete Apikey" data-bind="click: deleteApikey"><i class="icon-trash"></i></a>
</div>
</div>
+9 -8
View File
@@ -1,15 +1,16 @@
{{ _('Machine State') }}: <strong data-bind="text: stateString"></strong><br>
<span title="{{ _('Current printer state') }}">{{ _('State') }}</span>: <strong data-bind="text: stateString"></strong><br>
<hr>
{{ _('File') }}: <strong data-bind="text: filename"></strong>&nbsp;<strong data-bind="visible: sd">(SD)</strong><br>
{{ _('Timelapse') }}: <strong data-bind="text: timelapseString"></strong><br>
<span title="{{ _('Name of file currently selected for printing') }}">{{ _('File') }}</span>: <strong data-bind="text: filename"></strong>&nbsp;<strong data-bind="visible: sd">(SD)</strong><br>
<span title="{{ _('Current timelapse configuration') }}">{{ _('Timelapse') }}</span>: <strong data-bind="text: timelapseString"></strong><br>
<!-- ko foreach: filament -->
<span data-bind="text: 'Filament (' + name() + '): '"></span><strong data-bind="text: formatFilament(data())"></strong><br>
<span data-bind="text: 'Filament (' + name() + '): ', title: 'Filament usage for ' + name()"></span><strong data-bind="text: formatFilament(data())"></strong><br>
<!-- /ko -->
{{ _('Approx. Total Print Time') }}: <strong data-bind="text: estimatedPrintTimeString"></strong><br>
<span title="{{ _('Estimated total print time base on statical analysis or past prints') }}">{{ _('Approx. Total Print Time') }}</span>: <strong data-bind="text: estimatedPrintTimeString"></strong><br>
<hr>
{{ _('Print Time') }}: <strong data-bind="text: printTimeString"></strong><br>
{{ _('Print Time Left') }}: <strong data-bind="text: printTimeLeftString"></strong> <span id="state_printtimeleft_popover" style="display: none" data-bind="visible: printTimeLeftOrigin, attr: {title: printTimeLeftOriginString}, css: printTimeLeftOriginClass">&#9679;</span><br>
{{ _('Printed') }}: <strong data-bind="text: byteString"></strong><br>
<span title="{{ _('Total print time so far') }}">{{ _('Print Time') }}</span>: <strong data-bind="text: printTimeString"></strong><br>
<span title="{{ _('Estimated time until the print job is done. This is only an estimate and accuracy depends heavily on various factors!') }}">{{ _('Print Time Left') }}</span>: <strong data-bind="text: printTimeLeftString"></strong> <span id="state_printtimeleft_popover" style="display: none" data-bind="visible: printTimeLeftOrigin, attr: {title: printTimeLeftOriginString}, css: printTimeLeftOriginClass">&#9679;</span><br>
<span title="{{ _('Bytes printed vs total bytes of file') }}">{{ _('Printed') }}</span>: <strong data-bind="text: byteString"></strong><br>
<div class="progress progress-text-centered">
<span class="progress-text-back" data-bind="text: progressBarString()"></span>
@@ -17,7 +17,7 @@
<h1>{{ _('Model info') }}</h1>
<p data-bind="html: ui_modelInfo"></p>
<h1>Layer info</h1>
<h1>{{ _('Layer info') }}</h1>
<p data-bind="html: ui_layerInfo"></p>
</div>
<div class="span5">
@@ -62,7 +62,13 @@
</div>
<div class="muted">
<small>{{ _('Note that the time estimates in this tab are calculated by the GCODE viewer in your browser and might differ from the values calculated by the server that are displayed in the "State" and "Files" panels in the sidebar due to slightly different implementations.') }}</small>
<small>{% trans %}
Note that the time and usage values in this tab are <strong>estimated</strong> by the GCODE viewer in your
browser and might differ from the values <strong>estimated</strong> by the server that are displayed in the
"State" and "Files" panels in the sidebar due to slightly different implementations. Also note that these
<strong>estimated</strong> values may be inaccurate since they can also take information present in the
GCODE file into account.
{% endtrans %}</small>
</div>
</div>
<div data-bind="visible: waitForApproval">
File diff suppressed because it is too large. Load diff
+4
View File
@@ -1672,6 +1672,10 @@ class MachineCom(object):
with self._sendNextLock:
while self._active:
# we loop until we've actually enqueued a line for sending
if self._state != self.STATE_PRINTING:
# we are no longer printing, return false
return False
line = self._getNext()
if line is None:
# end of file, return false
+32
View File
@@ -54,6 +54,32 @@ class FilteredFileSystemLoader(FileSystemLoader):
return all(filter_results)
class SelectedFileSystemLoader(FileSystemLoader):
def __init__(self, searchpath, files, prefix=None, **kwargs):
FileSystemLoader.__init__(self, searchpath, **kwargs)
self.files = files
if prefix is not None and not prefix.endswith("/"):
prefix += "/"
self.prefix = prefix
def get_source(self, environment, template):
if not template.startswith(self.prefix):
raise TemplateNotFound(template)
template = template[len(self.prefix):]
if not template in self.files:
raise TemplateNotFound(template)
return FileSystemLoader.get_source(self, environment, template)
def list_templates(self):
return [self._prefixed(f) for f in self.files if any(map(lambda folder: os.path.exists(os.path.join(folder, f)), self.searchpath))]
def _prefixed(self, name):
return self.prefix + name if self.prefix else name
def get_all_template_paths(loader):
def walk_folder(folder):
files = []
@@ -71,6 +97,12 @@ def get_all_template_paths(loader):
result += walk_folder(folder)
return filter(loader.path_filter, result)
elif isinstance(loader, SelectedFileSystemLoader):
result = []
for folder in loader.searchpath:
result += filter(lambda x: os.path.exists(f), [os.path.join(folder, f) for f in loader.files])
return result
elif isinstance(loader, FileSystemLoader):
result = []
for folder in loader.searchpath:
+11
View File
@@ -0,0 +1,11 @@
# coding=utf-8
"""
Unit tests for ``octoprint.server``.
"""
from __future__ import absolute_import
__author__ = "Gina Häußge <osd@foosel.net>"
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__copyright__ = "Copyright (C) 2016 The OctoPrint Project - Released under terms of the AGPLv3 License"
+10
View File
@@ -0,0 +1,10 @@
# coding=utf-8
"""
Unit tests for ``octoprint.server.util``.
"""
from __future__ import absolute_import
__author__ = "Gina Häußge <osd@foosel.net>"
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__copyright__ = "Copyright (C) 2016 The OctoPrint Project - Released under terms of the AGPLv3 License"
+504
View File
@@ -0,0 +1,504 @@
# coding=utf-8
"""
Unit tests for ``octoprint.server.util.flask``.
"""
from __future__ import absolute_import
__author__ = "Gina Häußge <osd@foosel.net>"
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__copyright__ = "Copyright (C) 2016 The OctoPrint Project - Released under terms of the AGPLv3 License"
import unittest
import mock
from ddt import ddt, data, unpack
from octoprint.server.util.flask import ReverseProxiedEnvironment, OctoPrintFlaskRequest, OctoPrintFlaskResponse
standard_environ = {
"HTTP_HOST": "localhost:5000",
"SERVER_NAME": "localhost",
"SERVER_PORT": "5000",
"SCRIPT_NAME": "",
"PATH_INFO": "/",
"wsgi.url_scheme": "http"
}
@ddt
class ReverseProxiedEnvironmentTest(unittest.TestCase):
@data(
# defaults
({},
{}),
# prefix set, path info not prefixed
({
"HTTP_X_SCRIPT_NAME": "/octoprint",
"PATH_INFO": "/static/online.gif"
}, {
"SCRIPT_NAME": "/octoprint"
}),
# prefix set, path info prefixed
({
"HTTP_X_SCRIPT_NAME": "/octoprint",
"PATH_INFO": "/octoprint/static/online.gif",
}, {
"SCRIPT_NAME": "/octoprint",
"PATH_INFO": "/static/online.gif"
}),
# host set
({
"HTTP_X_FORWARDED_HOST": "example.com"
}, {
"HTTP_HOST": "example.com",
"SERVER_NAME": "example.com",
"SERVER_PORT": "80"
}),
# host set with port
({
"HTTP_X_FORWARDED_HOST": "example.com:1234"
}, {
"HTTP_HOST": "example.com:1234",
"SERVER_NAME": "example.com",
"SERVER_PORT": "1234"
}),
# host and scheme set
({
"HTTP_X_FORWARDED_HOST": "example.com",
"HTTP_X_FORWARDED_PROTO": "https"
}, {
"HTTP_HOST": "example.com",
"SERVER_NAME": "example.com",
"SERVER_PORT": "443",
"wsgi.url_scheme": "https"
}),
# host and scheme 2 set
({
"HTTP_X_FORWARDED_HOST": "example.com",
"HTTP_X_SCHEME": "https"
}, {
"HTTP_HOST": "example.com",
"SERVER_NAME": "example.com",
"SERVER_PORT": "443",
"wsgi.url_scheme": "https"
}),
# host, server and port headers set -> only host wins
({
"HTTP_X_FORWARDED_HOST": "example.com",
"HTTP_X_FORWARDED_SERVER": "example2.com",
"HTTP_X_FORWARDED_PORT": "444",
"HTTP_X_FORWARDED_PROTO": "https"
}, {
"HTTP_HOST": "example.com",
"SERVER_NAME": "example.com",
"SERVER_PORT": "443",
"wsgi.url_scheme": "https"
}),
# host set, server and port differ -> updated, standard port
({
"HTTP_HOST": "example.com",
"wsgi.url_scheme": "https",
"SERVER_NAME": "localhost",
"SERVER_PORT": "80"
}, {
"HTTP_HOST": "example.com",
"SERVER_NAME": "example.com",
"SERVER_PORT": "443",
}),
# host set, server and port differ -> updated, non standard port
({
"HTTP_HOST": "example.com:444",
"wsgi.url_scheme": "https",
"SERVER_NAME": "localhost",
"SERVER_PORT": "80"
}, {
"HTTP_HOST": "example.com:444",
"SERVER_NAME": "example.com",
"SERVER_PORT": "444",
}),
# multiple scheme entries -> only use first one
({
"HTTP_X_FORWARDED_PROTO": "https,http",
}, {
"wsgi.url_scheme": "https"
}),
# host = none (should never happen but you never know) -> server & port used for reconstruction
({
"HTTP_HOST": None,
"HTTP_X_FORWARDED_SERVER": "example.com",
"HTTP_X_FORWARDED_PORT": "80"
}, {
"HTTP_HOST": "example.com",
"SERVER_NAME": "example.com",
"SERVER_PORT": "80"
})
)
@unpack
def test_stock(self, environ, expected):
reverse_proxied = ReverseProxiedEnvironment()
merged_environ = dict(standard_environ)
merged_environ.update(environ)
actual = reverse_proxied(merged_environ)
merged_expected = dict(standard_environ)
merged_expected.update(environ)
merged_expected.update(expected)
self.assertDictEqual(merged_expected, actual)
@data(
# server and port headers set -> host derived with port
({
"SERVER_NAME": "example2.com",
"SERVER_PORT": "444",
"HTTP_X_FORWARDED_PROTO": "https"
}, {
"HTTP_HOST": "example2.com:444",
"SERVER_NAME": "example2.com",
"SERVER_PORT": "444",
"wsgi.url_scheme": "https"
}),
# server and port headers set, standard port -> host derived, no port
({
"SERVER_NAME": "example.com",
"SERVER_PORT": "80",
}, {
"HTTP_HOST": "example.com",
"SERVER_NAME": "example.com",
"SERVER_PORT": "80",
}),
# server and port forwarded headers set -> host derived with port
({
"HTTP_X_FORWARDED_SERVER": "example2.com",
"HTTP_X_FORWARDED_PORT": "444",
"HTTP_X_FORWARDED_PROTO": "https"
}, {
"HTTP_HOST": "example2.com:444",
"SERVER_NAME": "example2.com",
"SERVER_PORT": "444",
"wsgi.url_scheme": "https"
}),
# server and port forwarded headers set, standard port -> host derived, no port
({
"HTTP_X_FORWARDED_SERVER": "example.com",
"HTTP_X_FORWARDED_PORT": "80",
}, {
"HTTP_HOST": "example.com",
"SERVER_NAME": "example.com",
"SERVER_PORT": "80",
}),
)
@unpack
def test_nohost(self, environ, expected):
reverse_proxied = ReverseProxiedEnvironment()
merged_environ = dict(standard_environ)
merged_environ.update(environ)
del merged_environ["HTTP_HOST"]
actual = reverse_proxied(merged_environ)
merged_expected = dict(standard_environ)
merged_expected.update(environ)
merged_expected.update(expected)
self.assertDictEqual(merged_expected, actual)
@data(
# prefix overridden
({
"prefix": "fallback_prefix"
}, {
}, {
"SCRIPT_NAME": "fallback_prefix",
}),
# scheme overridden
({
"scheme": "https"
}, {
}, {
"wsgi.url_scheme": "https"
}),
# host overridden, default port
({
"host": "example.com"
}, {
}, {
"HTTP_HOST": "example.com",
"SERVER_NAME": "example.com",
"SERVER_PORT": "80"
}),
# host overridden, included port
({
"host": "example.com:81"
}, {
}, {
"HTTP_HOST": "example.com:81",
"SERVER_NAME": "example.com",
"SERVER_PORT": "81"
}),
# prefix not really overridden, forwarded headers take precedence
({
"prefix": "/octoprint"
}, {
"HTTP_X_SCRIPT_NAME": ""
}, {
}),
# scheme not really overridden, forwarded headers take precedence
({
"scheme": "https"
}, {
"HTTP_X_FORWARDED_PROTO": "http"
}, {
}),
# scheme 2 not really overridden, forwarded headers take precedence
({
"scheme": "https"
}, {
"HTTP_X_SCHEME": "http"
}, {
}),
# host not really overridden, forwarded headers take precedence
({
"host": "example.com:444"
}, {
"HTTP_X_FORWARDED_HOST": "localhost:5000"
}, {
}),
# server not really overridden, forwarded headers take precedence
({
"server": "example.com"
}, {
"HTTP_X_FORWARDED_SERVER": "localhost"
}, {
}),
# port not really overridden, forwarded headers take precedence
({
"port": "444"
}, {
"HTTP_X_FORWARDED_PORT": "5000"
}, {
}),
# server and port not really overridden, Host header wins
({
"server": "example.com",
"port": "80"
}, {
}, {
})
)
@unpack
def test_fallbacks(self, fallbacks, environ, expected):
reverse_proxied = ReverseProxiedEnvironment(**fallbacks)
merged_environ = dict(standard_environ)
merged_environ.update(environ)
actual = reverse_proxied(merged_environ)
merged_expected = dict(standard_environ)
merged_expected.update(environ)
merged_expected.update(expected)
self.assertDictEqual(merged_expected, actual)
@data(
# server overridden
({
"server": "example.com"
}, {
}, {
"HTTP_HOST": "example.com:5000",
"SERVER_NAME": "example.com",
"SERVER_PORT": "5000"
}),
# port overridden, standard port
({
"port": "80"
}, {
}, {
"HTTP_HOST": "localhost",
"SERVER_PORT": "80"
}),
# port overridden, non standard port
({
"port": "81"
}, {
}, {
"HTTP_HOST": "localhost:81",
"SERVER_PORT": "81"
}),
# server and port overridden, default port
({
"server": "example.com",
"port": "80"
}, {
}, {
"HTTP_HOST": "example.com",
"SERVER_NAME": "example.com",
"SERVER_PORT": "80"
}),
# server and port overridden, non default port
({
"server": "example.com",
"port": "81"
}, {
}, {
"HTTP_HOST": "example.com:81",
"SERVER_NAME": "example.com",
"SERVER_PORT": "81"
}),
)
@unpack
def test_fallbacks_nohost(self, fallbacks, environ, expected):
reverse_proxied = ReverseProxiedEnvironment(**fallbacks)
merged_environ = dict(standard_environ)
merged_environ.update(environ)
del merged_environ["HTTP_HOST"]
actual = reverse_proxied(merged_environ)
merged_expected = dict(standard_environ)
merged_expected.update(environ)
merged_expected.update(expected)
self.assertDictEqual(merged_expected, actual)
def test_header_config_ok(self):
result = ReverseProxiedEnvironment.to_header_candidates(["prefix-header1", "prefix-header2"])
self.assertEquals(result, ["HTTP_PREFIX_HEADER1", "HTTP_PREFIX_HEADER2"])
def test_header_config_string(self):
result = ReverseProxiedEnvironment.to_header_candidates("prefix-header")
self.assertEquals(result, ["HTTP_PREFIX_HEADER"])
def test_header_config_none(self):
result = ReverseProxiedEnvironment.to_header_candidates(None)
self.assertEquals(result, [])
##~~
class OctoPrintFlaskRequestTest(unittest.TestCase):
def setUp(self):
self.orig_environment_wrapper = OctoPrintFlaskRequest.environment_wrapper
def tearDown(self):
OctoPrintFlaskRequest.environment_wrapper = staticmethod(self.orig_environment_wrapper)
def test_environment_wrapper(self):
def environment_wrapper(environ):
environ.update({
"TEST": "yes"
})
return environ
OctoPrintFlaskRequest.environment_wrapper = staticmethod(environment_wrapper)
request = OctoPrintFlaskRequest(standard_environ)
self.assertTrue("TEST" in request.environ)
def test_server_name(self):
request = OctoPrintFlaskRequest(standard_environ)
self.assertEquals("localhost", request.server_name)
def test_server_port(self):
request = OctoPrintFlaskRequest(standard_environ)
self.assertEquals("5000", request.server_port)
def test_cookie_suffix(self):
request = OctoPrintFlaskRequest(standard_environ)
self.assertEquals("_P5000", request.cookie_suffix)
def test_cookies(self):
environ = dict(standard_environ)
environ["HTTP_COOKIE"] = "postfixed_P5000=postfixed_value; " \
"postfixed_wrong_P5001=postfixed_wrong_value; " \
"unpostfixed=unpostfixed_value; " \
"both_P5000=both_postfixed_value; " \
"both=both_unpostfixed_value;"
request = OctoPrintFlaskRequest(environ)
cookies = request.cookies
self.assertDictEqual({"postfixed": u"postfixed_value",
"postfixed_wrong_P5001": u"postfixed_wrong_value",
"unpostfixed": u"unpostfixed_value",
"both": u"both_postfixed_value"},
cookies)
##~~
@ddt
class OctoPrintFlaskResponseTest(unittest.TestCase):
@data([None, None],
["/subfolder/", None],
[None, "/some/other/script/root"],
["/subfolder/", "/some/other/script/root"])
@unpack
def test_cookie_set_and_delete(self, path, scriptroot):
environ = dict(standard_environ)
if scriptroot is not None:
environ.update(dict(SCRIPT_NAME=scriptroot))
request = OctoPrintFlaskRequest(environ)
if path:
expected_path = path
else:
expected_path = "/"
if scriptroot:
expected_path = scriptroot + expected_path
if path is not None:
kwargs = dict(path=path)
else:
kwargs = dict()
with mock.patch("flask.request", new=request):
response = OctoPrintFlaskResponse()
# test set_cookie
with mock.patch("flask.Response.set_cookie") as set_cookie_mock:
response.set_cookie("some_key", "some_value", **kwargs)
set_cookie_mock.assert_called_once_with(response, "some_key_P5000", "some_value", path=expected_path)
# test delete_cookie
with mock.patch("flask.Response.delete_cookie") as delete_cookie_mock:
response.delete_cookie("some_key", "some_value", **kwargs)
delete_cookie_mock.assert_called_once_with(response, "some_key_P5000", "some_value", path=expected_path)
+95
View File
@@ -0,0 +1,95 @@
# coding=utf-8
"""
Unit tests for ``octoprint.server.util.tornado``.
"""
from __future__ import absolute_import
__author__ = "Gina Häußge <osd@foosel.net>"
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__copyright__ = "Copyright (C) 2016 The OctoPrint Project - Released under terms of the AGPLv3 License"
import unittest
import mock
from ddt import ddt, data, unpack
##~~ _parse_header
@ddt
class ParseHeaderTest(unittest.TestCase):
@data(
("form-data; filename=test.gco", "form-data", dict(filename="test.gco")),
("form-data; filename=\"test.gco\"", "form-data", dict(filename="test.gco")),
("form-data; filename=test\\\\.gco", "form-data", dict(filename="test\\\\.gco")),
("form-data; filename=\"test\\\\.gco\"", "form-data", dict(filename="test\\.gco"))
)
@unpack
def test_parse_header_strip_quotes(self, value, expected_key, expected_dict):
from octoprint.server.util.tornado import _parse_header
actual_key, actual_dict = _parse_header(value)
self.assertEqual(expected_key, actual_key)
self.assertDictEqual(expected_dict, actual_dict)
@data(
("form-data; filename=test.gco", "form-data", dict(filename="test.gco")),
("form-data; filename=\"test.gco\"", "form-data", dict(filename="\"test.gco\"")),
("form-data; filename=test\\\\.gco", "form-data", dict(filename="test\\\\.gco")),
("form-data; filename=\"test\\\\.gco\"", "form-data", dict(filename="\"test\\\\.gco\"")),
("form-data; filename=iso-8859-1'en'test.gco", "form-data", dict(filename="iso-8859-1'en'test.gco"))
)
@unpack
def test_parse_header_leave_quotes(self, value, expected_key, expected_dict):
from octoprint.server.util.tornado import _parse_header
actual_key, actual_dict = _parse_header(value, strip_quotes=False)
self.assertEqual(expected_key, actual_key)
self.assertDictEqual(expected_dict, actual_dict)
##~~ _strip_value_quotes
@ddt
class StripValueQuotesTest(unittest.TestCase):
@data(
("", ""),
(None, None),
('"test.gco"', "test.gco"),
('"test".gco', '"test".gco'),
("test\\\\.gco", "test\\\\.gco"),
('"test\\\\.gco"', "test\\.gco")
)
@unpack
def test_strip_value_quotes(self, value, expected):
from octoprint.server.util.tornado import _strip_value_quotes
actual = _strip_value_quotes(value)
self.assertEqual(expected, actual)
##~~ _extended_header_value
@ddt
class ExtendedHeaderValueTest(unittest.TestCase):
@data(
(u"", u""),
(None, None),
(u'"quoted-string"', u"quoted-string"),
(u'"qüöted-string"', u"qüöted-string"),
(u"iso-8859-1'en'%A3%20rates", u"£ rates"),
(u"UTF-8''%c2%a3%20and%20%e2%82%ac%20rates", u"£ and € rates"),
('"quoted-string"', u"quoted-string"),
('"qüöted-string"', u"qüöted-string"),
("iso-8859-1'en'%A3%20rates", u"£ rates"),
("UTF-8''%c2%a3%20and%20%e2%82%ac%20rates", u"£ and € rates")
)
@unpack
def test_extended_header_value(self, value, expected):
from octoprint.server.util.tornado import _extended_header_value
actual = _extended_header_value(value)
self.assertEqual(expected, actual)
Binary file not shown.
File diff suppressed because it is too large. Load diff
+215 -99
View File
@@ -6,9 +6,9 @@
#, fuzzy
msgid ""
msgstr ""
"Project-Id-Version: OctoPrint 1.2.14.dev70+gf671006\n"
"Project-Id-Version: OctoPrint 1.2.16.dev44+ge19ecb0\n"
"Report-Msgid-Bugs-To: i18n@octoprint.org\n"
"POT-Creation-Date: 2016-07-28 11:50+0200\n"
"POT-Creation-Date: 2016-09-09 11:35+0200\n"
"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
"Language-Team: LANGUAGE <LL@li.org>\n"
@@ -655,24 +655,24 @@ msgstr ""
#: src/octoprint/plugins/pluginmanager/templates/pluginmanager_settings.jinja2:239
#: src/octoprint/plugins/softwareupdate/templates/softwareupdate.jinja2:26
#: src/octoprint/plugins/softwareupdate/templates/softwareupdate_settings.jinja2:101
#: src/octoprint/plugins/softwareupdate/templates/softwareupdate_settings.jinja2:108
#: src/octoprint/templates/dialogs/confirmation.jinja2:11
#: src/octoprint/templates/dialogs/slicing.jinja2:50
#: src/octoprint/templates/sidebar/state.jinja2:24
#: src/octoprint/templates/sidebar/state.jinja2:25
msgid "Cancel"
msgstr ""
#: src/octoprint/plugins/pluginmanager/templates/pluginmanager_settings.jinja2:240
#: src/octoprint/plugins/softwareupdate/templates/softwareupdate_settings.jinja2:102
#: src/octoprint/plugins/softwareupdate/templates/softwareupdate_settings.jinja2:109
msgid "Save"
msgstr ""
#: src/octoprint/plugins/softwareupdate/__init__.py:394
#: src/octoprint/plugins/softwareupdate/__init__.py:445
msgid "Software Update"
msgstr ""
#: src/octoprint/plugins/softwareupdate/__init__.py:700
#: src/octoprint/server/views.py:165
#: src/octoprint/plugins/softwareupdate/__init__.py:752
#: src/octoprint/server/views.py:217
#: src/octoprint/static/js/app/viewmodels/appearance.js:11
#: src/octoprint/static/js/app/viewmodels/appearance.js:13
#: src/octoprint/static/js/app/viewmodels/appearance.js:18
@@ -681,150 +681,150 @@ msgstr ""
msgid "OctoPrint"
msgstr ""
#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:29
#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:117
msgid "Release"
msgstr ""
#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:30
#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:118
msgid "Commit"
msgstr ""
#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:132
#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:152
#, python-format
msgid "%(name)s: %(version)s"
msgstr ""
#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:135
#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:155
msgid "unknown"
msgstr ""
#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:165
#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:185
msgid "There are updates available for the following components:"
msgstr ""
#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:173
#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:193
#: src/octoprint/plugins/softwareupdate/templates/softwareupdate.jinja2:14
msgid "Release Notes"
msgstr ""
#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:179
#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:199
msgid ""
"Those components marked with <i class=\"icon-ok\"></i> can be updated "
"directly."
msgstr ""
#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:184
#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:204
msgid "Update Available"
msgstr ""
#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:195
#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:215
msgid "Ignore"
msgstr ""
#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:199
#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:219
msgid ""
"You can make this message display again via \"Settings\" > \"Software "
"Update\" > \"Check for update now\""
msgstr ""
#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:203
#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:223
msgid "Update now"
msgstr ""
#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:220
#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:240
msgid "Everything is up-to-date"
msgstr ""
#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:285
#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:305
msgid "Updating..."
msgstr ""
#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:286
#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:306
msgid "Now updating, please wait."
msgstr ""
#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:312
#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:332
msgid "Update not started!"
msgstr ""
#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:313
#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:333
msgid ""
"The update could not be started. Is it already active? Please consult the"
" log for details."
msgstr ""
#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:333
#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:353
msgid "Can't update while printing"
msgstr ""
#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:334
#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:354
msgid ""
"A print job is currently in progress. Updating will be prevented until it"
" is done."
msgstr ""
#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:387
#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:407
#, python-format
msgid "Now updating %(name)s to %(version)s"
msgstr ""
#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:395
#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:415
msgid "Update successful, restarting!"
msgstr ""
#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:396
#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:416
msgid "The update finished successfully and the server will now be restarted."
msgstr ""
#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:407
#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:449
#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:427
#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:469
msgid "Restart failed"
msgstr ""
#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:408
#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:450
#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:428
#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:470
msgid ""
"The server apparently did not restart by itself, you'll have to do it "
"manually. Please consult the log file on what went wrong."
msgstr ""
#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:424
#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:444
msgid "The update finished successfully, please restart OctoPrint now."
msgstr ""
#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:426
#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:446
msgid "The update finished successfully, please reboot the server now."
msgstr ""
#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:430
#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:450
msgid "Update successful, restart required!"
msgstr ""
#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:443
#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:463
msgid ""
"Restarting OctoPrint failed, please restart it manually. You might also "
"want to consult the log file on what went wrong here."
msgstr ""
#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:445
#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:465
msgid ""
"Rebooting the server failed, please reboot it manually. You might also "
"want to consult the log file on what went wrong here."
msgstr ""
#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:463
#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:483
msgid "Update successful!"
msgstr ""
#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:464
#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:484
msgid "The update finished successfully."
msgstr ""
#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:476
#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:496
msgid "Update failed!"
msgstr ""
#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:477
#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:497
msgid ""
"The update did not finish successfully. Please consult the log for "
"details."
@@ -932,116 +932,129 @@ msgid "OctoPrint version tracking"
msgstr ""
#: src/octoprint/plugins/softwareupdate/templates/softwareupdate_settings.jinja2:90
msgid "OctoPrint Release Channel"
msgstr ""
#: src/octoprint/plugins/softwareupdate/templates/softwareupdate_settings.jinja2:93
#, python-format
msgid ""
"Make sure you have read <a href=\"%(url)s\" target=\"_blank\" "
"rel=\"noreferrer noopener\">\"Using Release Channels\"</a> before "
"switching to a release channel other than \"Stable\""
msgstr ""
#: src/octoprint/plugins/softwareupdate/templates/softwareupdate_settings.jinja2:97
msgid "Version cache TTL"
msgstr ""
#: src/octoprint/server/views.py:73
#: src/octoprint/server/views.py:125
msgid "Plugins"
msgstr ""
#: src/octoprint/server/views.py:131
#: src/octoprint/server/views.py:183
msgid "Connection"
msgstr ""
#: src/octoprint/server/views.py:132
#: src/octoprint/server/views.py:184
#: src/octoprint/templates/sidebar/state.jinja2:1
msgid "State"
msgstr ""
#: src/octoprint/server/views.py:133
#: src/octoprint/server/views.py:185
msgid "Files"
msgstr ""
#: src/octoprint/server/views.py:139
#: src/octoprint/server/views.py:191
msgid "Temperature"
msgstr ""
#: src/octoprint/server/views.py:140
#: src/octoprint/server/views.py:192
msgid "Control"
msgstr ""
#: src/octoprint/server/views.py:141
#: src/octoprint/server/views.py:193
msgid "Terminal"
msgstr ""
#: src/octoprint/server/views.py:144
#: src/octoprint/server/views.py:196
msgid "GCode Viewer"
msgstr ""
#: src/octoprint/server/views.py:146
#: src/octoprint/server/views.py:198
#: src/octoprint/templates/sidebar/state.jinja2:4
msgid "Timelapse"
msgstr ""
#: src/octoprint/server/views.py:151
#: src/octoprint/server/views.py:203
msgid "Printer"
msgstr ""
#: src/octoprint/server/views.py:153
#: src/octoprint/server/views.py:205
msgid "Serial Connection"
msgstr ""
#: src/octoprint/server/views.py:154
#: src/octoprint/server/views.py:206
#: src/octoprint/templates/dialogs/settings/printerprofiles.jinja2:1
msgid "Printer Profiles"
msgstr ""
#: src/octoprint/server/views.py:155
#: src/octoprint/server/views.py:207
msgid "Temperatures"
msgstr ""
#: src/octoprint/server/views.py:156
#: src/octoprint/server/views.py:208
msgid "Terminal Filters"
msgstr ""
#: src/octoprint/server/views.py:157
#: src/octoprint/server/views.py:209
msgid "GCODE Scripts"
msgstr ""
#: src/octoprint/server/views.py:159 src/octoprint/server/views.py:161
#: src/octoprint/server/views.py:211 src/octoprint/server/views.py:213
msgid "Features"
msgstr ""
#: src/octoprint/server/views.py:162
#: src/octoprint/server/views.py:214
msgid "Webcam"
msgstr ""
#: src/octoprint/server/views.py:163
#: src/octoprint/server/views.py:215
msgid "API"
msgstr ""
#: src/octoprint/server/views.py:167
#: src/octoprint/server/views.py:219
#: src/octoprint/templates/dialogs/settings/folders.jinja2:2
msgid "Folders"
msgstr ""
#: src/octoprint/server/views.py:168
#: src/octoprint/server/views.py:220
msgid "Appearance"
msgstr ""
#: src/octoprint/server/views.py:169
#: src/octoprint/server/views.py:221
#: src/octoprint/templates/dialogs/settings/logs.jinja2:2
msgid "Logs"
msgstr ""
#: src/octoprint/server/views.py:170
#: src/octoprint/server/views.py:222
msgid "Server"
msgstr ""
#: src/octoprint/server/views.py:173
#: src/octoprint/server/views.py:225
msgid "Access Control"
msgstr ""
#: src/octoprint/server/views.py:179
#: src/octoprint/server/views.py:231
msgid "Access"
msgstr ""
#: src/octoprint/server/views.py:180
#: src/octoprint/server/views.py:232
msgid "Interface"
msgstr ""
#: src/octoprint/static/js/app/dataupdater.js:96
#: src/octoprint/static/js/app/dataupdater.js:131
#: src/octoprint/static/js/app/helpers.js:451
#: src/octoprint/static/js/app/helpers.js:562
#: src/octoprint/templates/overlays/offline.jinja2:6
msgid "Server is offline"
msgstr ""
@@ -1085,12 +1098,82 @@ msgstr ""
msgid "%(hour)02d:%(minute)02d:%(second)02d"
msgstr ""
#: src/octoprint/static/js/app/helpers.js:392
#: src/octoprint/static/js/app/helpers.js:429
#: src/octoprint/static/js/app/helpers.js:436
#, python-format
msgid "%(days)d days"
msgstr ""
#: src/octoprint/static/js/app/helpers.js:431
#, python-format
msgid "%(days)d.5 days"
msgstr ""
#: src/octoprint/static/js/app/helpers.js:434
#, python-format
msgid "%(days)d day"
msgstr ""
#: src/octoprint/static/js/app/helpers.js:445
#, python-format
msgid "%(hours)d hour"
msgstr ""
#: src/octoprint/static/js/app/helpers.js:447
#: src/octoprint/static/js/app/helpers.js:455
#: src/octoprint/static/js/app/helpers.js:466
#, python-format
msgid "%(hours)d hours"
msgstr ""
#: src/octoprint/static/js/app/helpers.js:451
#, python-format
msgid "%(hours)d.5 hours"
msgstr ""
#: src/octoprint/static/js/app/helpers.js:460
msgid "1 day"
msgstr ""
#: src/octoprint/static/js/app/helpers.js:473
msgid "a minute"
msgstr ""
#: src/octoprint/static/js/app/helpers.js:475
msgid "2 minutes"
msgstr ""
#: src/octoprint/static/js/app/helpers.js:481
#, python-format
msgid "%(minutes)d minutes"
msgstr ""
#: src/octoprint/static/js/app/helpers.js:483
msgid "40 minutes"
msgstr ""
#: src/octoprint/static/js/app/helpers.js:485
msgid "50 minutes"
msgstr ""
#: src/octoprint/static/js/app/helpers.js:487
msgid "1 hour"
msgstr ""
#: src/octoprint/static/js/app/helpers.js:492
msgid "a couple of seconds"
msgstr ""
#: src/octoprint/static/js/app/helpers.js:494
msgid "less than a minute"
msgstr ""
#: src/octoprint/static/js/app/helpers.js:503
msgid "YYYY-MM-DD HH:mm"
msgstr ""
#: src/octoprint/static/js/app/helpers.js:410
#: src/octoprint/static/js/app/helpers.js:415
#: src/octoprint/static/js/app/helpers.js:521
#: src/octoprint/static/js/app/helpers.js:526
msgid "off"
msgstr ""
@@ -1178,19 +1261,22 @@ msgstr ""
#: src/octoprint/static/js/app/viewmodels/files.js:343
#: src/octoprint/static/js/app/viewmodels/files.js:348
#: src/octoprint/static/js/app/viewmodels/gcode.js:468
#: src/octoprint/static/js/app/viewmodels/gcode.js:471
msgid "Filament"
msgstr ""
#: src/octoprint/static/js/app/viewmodels/files.js:352
msgid "Estimated Print Time"
#: src/octoprint/static/js/app/viewmodels/gcode.js:475
msgid "Estimated print time"
msgstr ""
#: src/octoprint/static/js/app/viewmodels/files.js:355
msgid "Last Printed"
msgid "Last printed"
msgstr ""
#: src/octoprint/static/js/app/viewmodels/files.js:357
msgid "Last Print Time"
msgid "Last print time"
msgstr ""
#: src/octoprint/static/js/app/viewmodels/files.js:460
@@ -1305,16 +1391,7 @@ msgid "Layer height"
msgstr ""
#: src/octoprint/static/js/app/viewmodels/gcode.js:465
msgid "GCODE commands in layer"
msgstr ""
#: src/octoprint/static/js/app/viewmodels/gcode.js:468
#: src/octoprint/static/js/app/viewmodels/gcode.js:471
msgid "Filament used by layer"
msgstr ""
#: src/octoprint/static/js/app/viewmodels/gcode.js:475
msgid "Print time for layer"
msgid "GCODE commands"
msgstr ""
#: src/octoprint/static/js/app/viewmodels/loginstate.js:22
@@ -1474,11 +1551,13 @@ msgid "Pauses the print job"
msgstr ""
#: src/octoprint/static/js/app/viewmodels/printerstate.js:81
msgid "Calculating..."
msgid "Still stabilizing..."
msgstr ""
#: src/octoprint/static/js/app/viewmodels/printerstate.js:91
msgid "Based on a linear approximation (accuracy highly dependent on the model)"
msgid ""
"Based on a linear approximation (very low accuracy, especially at the "
"beginning of the print)"
msgstr ""
#: src/octoprint/static/js/app/viewmodels/printerstate.js:94
@@ -1510,7 +1589,7 @@ msgid "Continue"
msgstr ""
#: src/octoprint/static/js/app/viewmodels/printerstate.js:146
#: src/octoprint/templates/sidebar/state.jinja2:23
#: src/octoprint/templates/sidebar/state.jinja2:24
msgid "Pause"
msgstr ""
@@ -2095,7 +2174,7 @@ msgstr ""
#: src/octoprint/templates/dialogs/settings/folders.jinja2:47
#: src/octoprint/templates/dialogs/settings/serialconnection.jinja2:69
#: src/octoprint/templates/dialogs/settings/serialconnection.jinja2:90
#: src/octoprint/templates/tabs/gcodeviewer.jinja2:69
#: src/octoprint/templates/tabs/gcodeviewer.jinja2:75
#: src/octoprint/templates/tabs/timelapse.jinja2:13
msgid "Warning"
msgstr ""
@@ -2721,42 +2800,68 @@ msgid "Release SD card"
msgstr ""
#: src/octoprint/templates/sidebar/state.jinja2:1
msgid "Machine State"
msgid "Current printer state"
msgstr ""
#: src/octoprint/templates/sidebar/state.jinja2:3
msgid "Name of file currently selected for printing"
msgstr ""
#: src/octoprint/templates/sidebar/state.jinja2:3
msgid "File"
msgstr ""
#: src/octoprint/templates/sidebar/state.jinja2:4
msgid "Current timelapse configuration"
msgstr ""
#: src/octoprint/templates/sidebar/state.jinja2:8
msgid "Estimated total print time base on statical analysis or past prints"
msgstr ""
#: src/octoprint/templates/sidebar/state.jinja2:8
msgid "Approx. Total Print Time"
msgstr ""
#: src/octoprint/templates/sidebar/state.jinja2:10
msgid "Total print time so far"
msgstr ""
#: src/octoprint/templates/sidebar/state.jinja2:10
msgid "Print Time"
msgstr ""
#: src/octoprint/templates/sidebar/state.jinja2:11
msgid ""
"Estimated time until the print job is done. This is only an estimate and "
"accuracy depends heavily on various factors!"
msgstr ""
#: src/octoprint/templates/sidebar/state.jinja2:11
msgid "Print Time Left"
msgstr ""
#: src/octoprint/templates/sidebar/state.jinja2:12
msgid "Bytes printed vs total bytes of file"
msgstr ""
#: src/octoprint/templates/sidebar/state.jinja2:12
msgid "Printed"
msgstr ""
#: src/octoprint/templates/sidebar/state.jinja2:22
#: src/octoprint/templates/sidebar/state.jinja2:23
msgid "Restart"
msgstr ""
#: src/octoprint/templates/sidebar/state.jinja2:22
#: src/octoprint/templates/sidebar/state.jinja2:23
msgid "Print"
msgstr ""
#: src/octoprint/templates/sidebar/state.jinja2:23
#: src/octoprint/templates/sidebar/state.jinja2:24
msgid "Resume"
msgstr ""
#: src/octoprint/templates/sidebar/state.jinja2:24
#: src/octoprint/templates/sidebar/state.jinja2:25
msgid "Cancels the print job"
msgstr ""
@@ -2838,6 +2943,10 @@ msgstr ""
msgid "Model info"
msgstr ""
#: src/octoprint/templates/tabs/gcodeviewer.jinja2:20
msgid "Layer info"
msgstr ""
#: src/octoprint/templates/tabs/gcodeviewer.jinja2:24
msgid "Renderer options"
msgstr ""
@@ -2876,13 +2985,20 @@ msgstr ""
#: src/octoprint/templates/tabs/gcodeviewer.jinja2:65
msgid ""
"Note that the time estimates in this tab are calculated by the GCODE "
"viewer in your browser and might differ from the values calculated by the"
" server that are displayed in the \"State\" and \"Files\" panels in the "
"sidebar due to slightly different implementations."
"\n"
" Note that the time and usage values in this tab are "
"<strong>estimated</strong> by the GCODE viewer in your\n"
" browser and might differ from the values "
"<strong>estimated</strong> by the server that are displayed in the\n"
" \"State\" and \"Files\" panels in the sidebar due to slightly"
" different implementations. Also note that these\n"
" <strong>estimated</strong> values may be inaccurate since "
"they can also take information present in the\n"
" GCODE file into account.\n"
" "
msgstr ""
#: src/octoprint/templates/tabs/gcodeviewer.jinja2:70
#: src/octoprint/templates/tabs/gcodeviewer.jinja2:76
msgid ""
"<p>\n"
" You've selected <strong data-bind=\"text: "
@@ -2899,7 +3015,7 @@ msgid ""
" </p>"
msgstr ""
#: src/octoprint/templates/tabs/gcodeviewer.jinja2:81
#: src/octoprint/templates/tabs/gcodeviewer.jinja2:87
#, python-format
msgid "Yes, please visualize %(name)s regardless of its size"
msgstr ""