Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6976ac9edd | ||
|
|
2f79d9d226 | ||
|
|
88f8077b77 | ||
|
|
eabff453cd | ||
|
|
6cd6b98c2b | ||
|
|
91ef5480b1 | ||
|
|
419f3370a2 | ||
|
|
1370c7a9cc | ||
|
|
982d121d3b | ||
|
|
67634e4f7c | ||
|
|
3d26e478e3 | ||
|
|
28de87441f | ||
|
|
688a998dd2 | ||
|
|
343631b3c6 | ||
|
|
139b2277d1 | ||
|
|
e8123a6ab1 | ||
|
|
891fd18f0e | ||
|
|
41fe997af4 | ||
|
|
6c21ee32a8 | ||
|
|
bcef804a4a | ||
|
|
39d5446789 | ||
|
|
a161feb106 | ||
|
|
8c74b9e74d | ||
|
|
bc0880711b | ||
|
|
e038cfa4dc | ||
|
|
e700891dba | ||
|
|
080a6e9ccd | ||
|
|
3a13dd9022 | ||
|
|
3d959c1d5f | ||
|
|
354042b84d |
No files matched your search
@@ -1 +1,10 @@
|
||||
src/octoprint/_version.py export-subst
|
||||
|
||||
src/octoprint/static/js/lib/* linguist-vendored
|
||||
src/octoprint/static/less/bootstrap/* linguist-vendored
|
||||
src/octoprint/static/less/font-awesome.less linguist-vendored
|
||||
src/octoprint/static/less/mixins.less linguist-vendored
|
||||
src/octoprint/static/less/variables.less linguist-vendored
|
||||
versioneer.py linguist-vendored
|
||||
|
||||
docs/* linguist-documentation
|
||||
+20
-10
@@ -1,21 +1,31 @@
|
||||
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. 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 :)
|
||||
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?
|
||||
@@ -53,8 +63,8 @@ to also include a link to a file with which to reproduce the problem.]
|
||||
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 contents of your
|
||||
terminal tab at the time of the bug occurence, even if you do not have
|
||||
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
|
||||
|
||||
+4
-4
@@ -16,11 +16,11 @@ prerelease
|
||||
HEAD
|
||||
\(detached.*
|
||||
|
||||
# maintenance is currently the branch for preparation of maintenance release 1.2.16
|
||||
# maintenance is currently the branch for preparation of maintenance release 1.2.17
|
||||
# so are any fix/... and improve/... branches
|
||||
maintenance 1.2.16 afdb98a92fb5dae2661aa252975933be55bef2c2 pep440-dev
|
||||
fix/.* 1.2.16 afdb98a92fb5dae2661aa252975933be55bef2c2 pep440-dev
|
||||
improve/.* 1.2.16 afdb98a92fb5dae2661aa252975933be55bef2c2 pep440-dev
|
||||
maintenance 1.2.17 354042b84d488db38ac1917bb69bd164f4e7f750 pep440-dev
|
||||
fix/.* 1.2.17 354042b84d488db38ac1917bb69bd164f4e7f750 pep440-dev
|
||||
improve/.* 1.2.17 354042b84d488db38ac1917bb69bd164f4e7f750 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
|
||||
+35
-8
@@ -1,19 +1,38 @@
|
||||
# OctoPrint Changelog
|
||||
|
||||
## 1.2.16rc2 (2016-09-16)
|
||||
## 1.2.17 (2016-11-08)
|
||||
|
||||
### Improvements
|
||||
|
||||
* 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.
|
||||
* Files like `config.yaml` etc will now persist their permissions, with a lower and upper permission bounds for sanitization (e.g. removing executable flags on configuration files but keeping group read/write permissions if found).
|
||||
* Log full stack trace on socket connection errors when debug logging for `octoprint.server.util.sockjs` is enabled
|
||||
* ``SettingsPlugin``s may now mark configuration paths as restricted so that they are not returned on the REST API
|
||||
* Updated LESS.js version
|
||||
* Improved the `serial.log` logging handler to roll over serial log on new connections to the printer instead of continuously appending to the same file. Please note that `serial.log` is a debugging tool only and should *not* be left enabled unless you are trying to troubleshoot something in your printer communication.
|
||||
* Split JS/CSS/LESS asset bundles according into asset bundles for core + bundled plugins ("packed_core.{js|css|less}") and third party plugins ("packed_plugins.{js|css|less}"). That will allow the core UI to still function properly even if an installed third party plugin produces invalid JS and therefore causes a parser error for the whole plugin JS file. See [#1544](https://github.com/foosel/OctoPrint/issues/1544) for an example of such a situation.
|
||||
|
||||
### Bug Fixes
|
||||
### Bug fixes
|
||||
|
||||
* [#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.
|
||||
* [#1531](https://github.com/foosel/OctoPrint/issues/1531) - Fixed encoding bug in HTTP request processing triggered by content type headers on form data fields
|
||||
* Fixed forced `config.yaml` save on startup caused by mistakenly assuming that printer parameters were always migrated.
|
||||
* Fixed issue causing ``remember_me`` cookie not to be deleted properly on logout
|
||||
* Fixed broken filter toggling on ``ItemListHelper`` class used for various lists throughout the web interface
|
||||
* Fixed an issue with the preliminary page never reporting that the server is now up if the page generated during preliminary caching had no cache headers set (e.g. because it contained the first run setup wizard)
|
||||
* Fixed a bug causing the update of OctoPrint to not work under certain circumstances: If 1.2.16 was installed and the settings were *never* saved via the "Settings" dialog's "Save", the update of OctoPrint would fail due to a `KeyError` in the updater. Reason is a renamed property, properly switched to when saving the settings.
|
||||
* Fixed the logging subsystem to properly clean up after itself.
|
||||
* Fixed a wrong order in loading JS files on the client introduced in 1.2.17rc2 to make the UI more resilient against broken plugin JS.
|
||||
* Properly handle empty JS file list from plugins. Solves a 500 on OctoPrint instances without any third party plugins installed generated during web asset bundling introduced in 1.2.17rc2.
|
||||
|
||||
([Commits](https://github.com/foosel/OctoPrint/compare/1.2.16rc1...1.2.16rc2))
|
||||
### More information
|
||||
|
||||
## 1.2.16rc1 (2016-09-09)
|
||||
* [Commits](https://github.com/foosel/OctoPrint/compare/1.2.16...1.2.17)
|
||||
* Release Candidates:
|
||||
* [1.2.17rc1](https://github.com/foosel/OctoPrint/releases/tag/1.2.17rc1)
|
||||
* [1.2.17rc2](https://github.com/foosel/OctoPrint/releases/tag/1.2.17rc2)
|
||||
* [1.2.17rc3](https://github.com/foosel/OctoPrint/releases/tag/1.2.17rc3)
|
||||
* [1.2.17rc4](https://github.com/foosel/OctoPrint/releases/tag/1.2.17rc4)
|
||||
|
||||
## 1.2.16 (2016-09-23)
|
||||
|
||||
### Improvements
|
||||
|
||||
@@ -23,6 +42,7 @@
|
||||
* 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
|
||||
|
||||
@@ -31,8 +51,15 @@
|
||||
* [#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.
|
||||
|
||||
([Commits](https://github.com/foosel/OctoPrint/compare/1.2.15...1.2.16rc1))
|
||||
### 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)
|
||||
|
||||
|
||||
+18
-10
@@ -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,7 +124,10 @@ following section *completely*. Thank you! :)
|
||||
|
||||
### What should I include in a bug report?
|
||||
|
||||
Always use the following template (please 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**:
|
||||
|
||||
@@ -162,8 +166,8 @@ only provided here as some additional information for you), **even if only addin
|
||||
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 contents of your
|
||||
terminal tab at the time of the bug occurence, even if you do not have
|
||||
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
|
||||
@@ -177,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?
|
||||
|
||||
@@ -201,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
|
||||
@@ -383,6 +389,8 @@ the local version identifier to allow for an exact determination of the active c
|
||||
* 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
|
||||
|
||||
@@ -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).
|
||||
+15
-13
@@ -7,10 +7,10 @@ thanks to everyone who contributed!
|
||||
## Patreon Patrons
|
||||
|
||||
* 3D Moniak
|
||||
* alephobjects
|
||||
* Aleph Objects, Inc.
|
||||
* Andrew Moorby
|
||||
* Arnljot Arntsen
|
||||
* Aurelio Bernal Ramírez
|
||||
* Aurelio Bernal
|
||||
* Bart Zudell
|
||||
* Boris Hussein
|
||||
* Brad Jackson
|
||||
@@ -30,46 +30,48 @@ thanks to everyone who contributed!
|
||||
* Ernesto Martinez
|
||||
* Exovite
|
||||
* Frank Sander
|
||||
* georgeroblesjr
|
||||
* Gregor Luetolf
|
||||
* Gary Deen
|
||||
* Gary N McKinney
|
||||
* George Robles
|
||||
* Gregor Lütolf
|
||||
* J. Eckert
|
||||
* Jason Galarneau
|
||||
* Joe Korzeniewski
|
||||
* Josh Daniels
|
||||
* Joshua Gregory
|
||||
* Joshua David Gregory
|
||||
* Kaile Riser
|
||||
* Kale Stedman
|
||||
* Kazuhiro Ogura
|
||||
* Korneel Bullens
|
||||
* Kyle Gress
|
||||
* Lamin Kivelä
|
||||
* M Khorakiwala
|
||||
* Makespace Madrid
|
||||
* Mark Lane
|
||||
* Mark Qvist
|
||||
* Mark Walker
|
||||
* Masayoshi Mitsui
|
||||
* Michael McDargh
|
||||
* Mikey
|
||||
* Michael Aumock
|
||||
* Michael McDargh Sr
|
||||
* Miles Flavel
|
||||
* Mohammed Khorakiwala
|
||||
* Nikolai Langer
|
||||
* Noe Ruiz
|
||||
* Patrick McGinnis
|
||||
* Paul Generes
|
||||
* Peter Grace
|
||||
* Peter Schmehl
|
||||
* PRINT3Dforum.com
|
||||
* Robert Gusek
|
||||
* Roger Strolz
|
||||
* Roy Cortes
|
||||
* Samer Najia
|
||||
* SD3D
|
||||
* SeeMeCNC
|
||||
* Shane Ekerbicer
|
||||
* Simon Hallam
|
||||
* Stefan Krister
|
||||
* stefi davis
|
||||
* Steven Pearson
|
||||
* Sven Mueller
|
||||
* Terrance Shaw
|
||||
* Thomas Hatley
|
||||
* Trent Shumay
|
||||
* Xpandedreality
|
||||
|
||||
and 905 more wonderful people pledging on the [Patreon campaign](https://patreon.com/foosel)!
|
||||
and 968 more wonderful people pledging on the [Patreon campaign](https://patreon.com/foosel)!
|
||||
@@ -299,6 +299,8 @@ An overview of these properties follows.
|
||||
The plugin's name, as taken from either the ``__plugin_name__`` control property or the package info.
|
||||
``self._plugin_version``
|
||||
The plugin's version, as taken from either the ``__plugin_version__`` control property or the package info.
|
||||
``self._plugin_info``
|
||||
The :class:`octoprint.plugin.core.PluginInfo` object associated with the plugin.
|
||||
``self._basefolder``
|
||||
The plugin's base folder where it's installed. Can be used to refer to files relative to the plugin's installation
|
||||
location, e.g. included scripts, templates or assets.
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
#!/usr/bin/env python
|
||||
from __future__ import absolute_import
|
||||
|
||||
import sys
|
||||
from octoprint.daemon import Daemon
|
||||
from octoprint.server import Server
|
||||
|
||||
@@ -427,7 +427,7 @@ class FileManager(object):
|
||||
pos=pos,
|
||||
date=time.time())
|
||||
try:
|
||||
with atomic_write(self._recovery_file) as f:
|
||||
with atomic_write(self._recovery_file, max_permissions=0o666) as f:
|
||||
yaml.safe_dump(data, stream=f, default_flow_style=False, indent=" ", allow_unicode=True)
|
||||
except:
|
||||
self._logger.exception("Could not write recovery data to file {}".format(self._recovery_file))
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import
|
||||
|
||||
from . import handlers
|
||||
@@ -0,0 +1,83 @@
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import
|
||||
|
||||
import logging.handlers
|
||||
import os
|
||||
import re
|
||||
import time
|
||||
|
||||
class CleaningTimedRotatingFileHandler(logging.handlers.TimedRotatingFileHandler):
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
logging.handlers.TimedRotatingFileHandler.__init__(self, *args, **kwargs)
|
||||
|
||||
# clean up old files on handler start
|
||||
if self.backupCount > 0:
|
||||
for s in self.getFilesToDelete():
|
||||
os.remove(s)
|
||||
|
||||
|
||||
class SerialLogHandler(logging.handlers.RotatingFileHandler):
|
||||
|
||||
_do_rollover = False
|
||||
_suffix_template = "%Y-%m-%d_%H-%M-%S"
|
||||
_file_pattern = re.compile(r"^\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2}$")
|
||||
|
||||
@classmethod
|
||||
def on_open_connection(cls):
|
||||
cls._do_rollover = True
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
logging.handlers.RotatingFileHandler.__init__(self, *args, **kwargs)
|
||||
self.cleanupFiles()
|
||||
|
||||
def emit(self, record):
|
||||
logging.handlers.RotatingFileHandler.emit(self, record)
|
||||
|
||||
def shouldRollover(self, record):
|
||||
return self.__class__._do_rollover
|
||||
|
||||
def getFilesToDelete(self):
|
||||
"""
|
||||
Determine the files to delete when rolling over.
|
||||
"""
|
||||
dirName, baseName = os.path.split(self.baseFilename)
|
||||
fileNames = os.listdir(dirName)
|
||||
result = []
|
||||
prefix = baseName + "."
|
||||
plen = len(prefix)
|
||||
for fileName in fileNames:
|
||||
if fileName[:plen] == prefix:
|
||||
suffix = fileName[plen:]
|
||||
if self.__class__._file_pattern.match(suffix):
|
||||
result.append(os.path.join(dirName, fileName))
|
||||
result.sort()
|
||||
if len(result) < self.backupCount:
|
||||
result = []
|
||||
else:
|
||||
result = result[:len(result) - self.backupCount]
|
||||
return result
|
||||
|
||||
def cleanupFiles(self):
|
||||
if self.backupCount > 0:
|
||||
for path in self.getFilesToDelete():
|
||||
os.remove(path)
|
||||
|
||||
def doRollover(self):
|
||||
self.__class__._do_rollover = False
|
||||
|
||||
if self.stream:
|
||||
self.stream.close()
|
||||
self.stream = None
|
||||
|
||||
if os.path.exists(self.baseFilename):
|
||||
# figure out creation date/time to use for file suffix
|
||||
t = time.localtime(os.stat(self.baseFilename).st_mtime)
|
||||
dfn = self.baseFilename + "." + time.strftime(self.__class__._suffix_template, t)
|
||||
if os.path.exists(dfn):
|
||||
os.remove(dfn)
|
||||
os.rename(self.baseFilename, dfn)
|
||||
|
||||
self.cleanupFiles()
|
||||
if not self.delay:
|
||||
self.stream = self._open()
|
||||
@@ -902,6 +902,7 @@ class PluginManager(object):
|
||||
identifier=name,
|
||||
plugin_name=plugin.name,
|
||||
plugin_version=plugin.version,
|
||||
plugin_info=plugin,
|
||||
basefolder=os.path.realpath(plugin.location),
|
||||
logger=logging.getLogger(self.logging_prefix + name),
|
||||
))
|
||||
|
||||
@@ -819,11 +819,48 @@ class SettingsPlugin(OctoPrintPlugin):
|
||||
and iterate yourself over all your settings, using the proper retriever methods on the settings manager
|
||||
to retrieve the data in the correct format.
|
||||
|
||||
The default implementation will also replace any paths that have been restricted by your plugin through
|
||||
:func:`~octoprint.plugin.SettingsPlugin.get_settings_restricted_paths` with ``None`` values where necessary.
|
||||
Make sure to do your own restriction if you decide to fully overload this method.
|
||||
|
||||
:return: the current settings of the plugin, as a dictionary
|
||||
"""
|
||||
from flask.ext.login import current_user
|
||||
|
||||
data = self._settings.get_all_data()
|
||||
if self.config_version_key in data:
|
||||
del data[self.config_version_key]
|
||||
|
||||
restricted_paths = self.get_settings_restricted_paths()
|
||||
|
||||
def restrict_path_unless(data, path, condition):
|
||||
if not path:
|
||||
return
|
||||
|
||||
if condition():
|
||||
return
|
||||
|
||||
node = data
|
||||
|
||||
if len(path) > 1:
|
||||
for entry in path[:-1]:
|
||||
if not entry in node:
|
||||
return
|
||||
node = node[entry]
|
||||
|
||||
key = path[-1]
|
||||
if key in node:
|
||||
node[key] = None
|
||||
|
||||
conditions = dict(user=lambda: current_user is not None and not current_user.is_anonymous(),
|
||||
admin=lambda: current_user is not None and not current_user.is_anonymous() and current_user.is_admin(),
|
||||
never=lambda: False)
|
||||
|
||||
for level, condition in conditions.items():
|
||||
paths_for_level = restricted_paths.get(level, [])
|
||||
for path in paths_for_level:
|
||||
restrict_path_unless(data, path, condition)
|
||||
|
||||
return data
|
||||
|
||||
def on_settings_save(self, data):
|
||||
@@ -886,6 +923,60 @@ class SettingsPlugin(OctoPrintPlugin):
|
||||
"""
|
||||
return dict()
|
||||
|
||||
def get_settings_restricted_paths(self):
|
||||
"""
|
||||
Retrieves the list of paths in the plugin's settings which be restricted on the REST API.
|
||||
|
||||
Override this in your plugin's implementation to restrict whether a path should only be returned to logged in
|
||||
users & admins, only to admins, or never on the REST API.
|
||||
|
||||
Return a ``dict`` with the keys ``admin``, ``user``, ``never`` mapping to a list of paths (as tuples or lists of
|
||||
the path elements) for which to restrict access via the REST API accordingly. Paths returned for the ``admin``
|
||||
key will only be available on the REST API when access with admin rights, ``user`` will only be available when accessed
|
||||
as a logged in user. ``never`` will never be returned on the API.
|
||||
|
||||
Example:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
def get_settings_defaults(self):
|
||||
return dict(some=dict(admin_only=dict(path="path", foo="foo"),
|
||||
user_only=dict(path="path", bar="bar")),
|
||||
another=dict(admin_only=dict(path="path"),
|
||||
field="field"),
|
||||
path=dict(to=dict(never=dict(return="return"))))
|
||||
|
||||
def get_settings_restricted_path(self):
|
||||
return dict(admin=[["some", "admin_only", "path], ["another", "admin_only", "path"],
|
||||
user=[["some", "user_only", "path"],],
|
||||
never=[["path", "to", "never", "return"],])
|
||||
|
||||
# this will make the plugin return settings on the REST API like this for an anonymous user
|
||||
#
|
||||
# dict(some=dict(admin_only=dict(path=None, foo="foo"),
|
||||
# user_only=dict(path=None, bar="bar")),
|
||||
# another=dict(admin_only=dict(path=None),
|
||||
# field="field"),
|
||||
# path=dict(to=dict(never=dict(return=None))))
|
||||
#
|
||||
# like this for a logged in user
|
||||
#
|
||||
# dict(some=dict(admin_only=dict(path=None, foo="foo"),
|
||||
# user_only=dict(path="path", bar="bar")),
|
||||
# another=dict(admin_only=dict(path=None),
|
||||
# field="field"),
|
||||
# path=dict(to=dict(never=dict(return=None))))
|
||||
#
|
||||
# and like this for an admin user
|
||||
#
|
||||
# dict(some=dict(admin_only=dict(path="path", foo="foo"),
|
||||
# user_only=dict(path="path", bar="bar")),
|
||||
# another=dict(admin_only=dict(path="path"),
|
||||
# field="field"),
|
||||
# path=dict(to=dict(never=dict(return=None))))
|
||||
"""
|
||||
return dict()
|
||||
|
||||
def get_settings_preprocessors(self):
|
||||
"""
|
||||
Retrieves the plugin's preprocessors to use for preprocessing returned or set values prior to returning/setting
|
||||
|
||||
@@ -46,7 +46,8 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin,
|
||||
|
||||
def on_startup(self, host, port):
|
||||
# setup our custom logger
|
||||
cura_logging_handler = logging.handlers.RotatingFileHandler(self._settings.get_plugin_logfile_path(postfix="engine"), maxBytes=2*1024*1024)
|
||||
from octoprint.logging.handlers import CleaningTimedRotatingFileHandler
|
||||
cura_logging_handler = CleaningTimedRotatingFileHandler(self._settings.get_plugin_logfile_path(postfix="engine"), when="D", backupCount=3)
|
||||
cura_logging_handler.setFormatter(logging.Formatter("%(asctime)s %(message)s"))
|
||||
cura_logging_handler.setLevel(logging.DEBUG)
|
||||
|
||||
@@ -391,7 +392,7 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin,
|
||||
|
||||
def _save_profile(self, path, profile, allow_overwrite=True):
|
||||
import yaml
|
||||
with octoprint.util.atomic_write(path, "wb") as f:
|
||||
with octoprint.util.atomic_write(path, "wb", max_permissions=0o666) as f:
|
||||
yaml.safe_dump(profile, f, default_flow_style=False, indent=" ", allow_unicode=True)
|
||||
|
||||
def _convert_to_engine(self, profile_path, printer_profile, posX, posY):
|
||||
|
||||
@@ -65,7 +65,8 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
##~~ StartupPlugin
|
||||
|
||||
def on_startup(self, host, port):
|
||||
console_logging_handler = logging.handlers.RotatingFileHandler(self._settings.get_plugin_logfile_path(postfix="console"), maxBytes=2*1024*1024)
|
||||
from octoprint.logging.handlers import CleaningTimedRotatingFileHandler
|
||||
console_logging_handler = CleaningTimedRotatingFileHandler(self._settings.get_plugin_logfile_path(postfix="console"), when="D", backupCount=3)
|
||||
console_logging_handler.setFormatter(logging.Formatter("%(asctime)s %(message)s"))
|
||||
console_logging_handler.setLevel(logging.DEBUG)
|
||||
|
||||
|
||||
@@ -129,7 +129,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
octoprint_version = get_versions()["version"]
|
||||
self._version_cache["__version"] = octoprint_version
|
||||
|
||||
with atomic_write(self._version_cache_path) as file_obj:
|
||||
with atomic_write(self._version_cache_path, max_permissions=0o666) as file_obj:
|
||||
yaml.safe_dump(self._version_cache, stream=file_obj, default_flow_style=False, indent=" ", allow_unicode=True)
|
||||
|
||||
self._version_cache_dirty = False
|
||||
|
||||
@@ -35,7 +35,7 @@ def perform_update(target, check, target_version):
|
||||
update_script = check["update_script"]
|
||||
update_branch = check.get("update_branch", "")
|
||||
force_exact_version = check.get("force_exact_version", False)
|
||||
folder = check.get("update_folder", check["checkout_folder"])
|
||||
folder = check.get("update_folder", check.get("checkout_folder")) # either should be set, tested above
|
||||
pre_update_script = check.get("pre_update_script", None)
|
||||
post_update_script = check.get("post_update_script", None)
|
||||
|
||||
|
||||
@@ -332,7 +332,7 @@ class PrinterProfileManager(object):
|
||||
from octoprint.util import atomic_write
|
||||
import yaml
|
||||
try:
|
||||
with atomic_write(path, "wb") as f:
|
||||
with atomic_write(path, "wb", max_permissions=0o666) as f:
|
||||
yaml.safe_dump(profile, f, default_flow_style=False, indent=" ", allow_unicode=True)
|
||||
except Exception as e:
|
||||
self._logger.exception("Error while trying to save profile %s" % profile["id"])
|
||||
|
||||
@@ -194,6 +194,10 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
if self._comm is not None:
|
||||
self._comm.close()
|
||||
self._printerProfileManager.select(profile)
|
||||
|
||||
from octoprint.logging.handlers import SerialLogHandler
|
||||
SerialLogHandler.on_open_connection()
|
||||
|
||||
self._comm = comm.MachineCom(port, baudrate, callbackObject=self, printerProfileManager=self._printerProfileManager)
|
||||
|
||||
def disconnect(self):
|
||||
|
||||
@@ -564,6 +564,9 @@ class Server(object):
|
||||
"formatters": {
|
||||
"simple": {
|
||||
"format": "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
|
||||
},
|
||||
"serial": {
|
||||
"format": "%(asctime)s - %(message)s"
|
||||
}
|
||||
},
|
||||
"handlers": {
|
||||
@@ -574,18 +577,18 @@ class Server(object):
|
||||
"stream": "ext://sys.stdout"
|
||||
},
|
||||
"file": {
|
||||
"class": "logging.handlers.TimedRotatingFileHandler",
|
||||
"class": "octoprint.logging.handlers.CleaningTimedRotatingFileHandler",
|
||||
"level": "DEBUG",
|
||||
"formatter": "simple",
|
||||
"when": "D",
|
||||
"backupCount": "1",
|
||||
"backupCount": 6,
|
||||
"filename": os.path.join(settings().getBaseFolder("logs"), "octoprint.log")
|
||||
},
|
||||
"serialFile": {
|
||||
"class": "logging.handlers.RotatingFileHandler",
|
||||
"class": "octoprint.logging.handlers.SerialLogHandler",
|
||||
"level": "DEBUG",
|
||||
"formatter": "simple",
|
||||
"maxBytes": 2 * 1024 * 1024, # let's limit the serial log to 2MB in size
|
||||
"formatter": "serial",
|
||||
"backupCount": 3,
|
||||
"filename": os.path.join(settings().getBaseFolder("logs"), "serial.log")
|
||||
}
|
||||
},
|
||||
@@ -633,7 +636,6 @@ class Server(object):
|
||||
if settings().getBoolean(["serial", "log"]):
|
||||
# enable debug logging to serial.log
|
||||
logging.getLogger("SERIAL").setLevel(logging.DEBUG)
|
||||
logging.getLogger("SERIAL").debug("Enabling serial logging")
|
||||
|
||||
def _setup_app(self, app):
|
||||
from octoprint.server.util.flask import ReverseProxiedEnvironment, OctoPrintFlaskRequest, OctoPrintFlaskResponse
|
||||
@@ -1013,7 +1015,8 @@ class Server(object):
|
||||
enable_gcodeviewer = settings().getBoolean(["gcodeViewer", "enabled"])
|
||||
preferred_stylesheet = settings().get(["devel", "stylesheet"])
|
||||
|
||||
dynamic_assets = util.flask.collect_plugin_assets(
|
||||
dynamic_core_assets = util.flask.collect_core_assets(enable_gcodeviewer=enable_gcodeviewer)
|
||||
dynamic_plugin_assets = util.flask.collect_plugin_assets(
|
||||
enable_gcodeviewer=enable_gcodeviewer,
|
||||
preferred_stylesheet=preferred_stylesheet
|
||||
)
|
||||
@@ -1049,11 +1052,15 @@ class Server(object):
|
||||
"js/lib/loglevel.min.js",
|
||||
"js/lib/sockjs-0.3.4.min.js"
|
||||
]
|
||||
js_app = dynamic_assets["js"] + [
|
||||
"js/app/dataupdater.js",
|
||||
"js/app/helpers.js",
|
||||
"js/app/main.js",
|
||||
]
|
||||
js_core = dynamic_core_assets["js"] + \
|
||||
dynamic_plugin_assets["bundled"]["js"] + \
|
||||
["js/app/dataupdater.js",
|
||||
"js/app/helpers.js",
|
||||
"js/app/main.js"]
|
||||
js_plugins = dynamic_plugin_assets["external"]["js"]
|
||||
if len(js_plugins) == 0:
|
||||
js_plugins = ["empty"]
|
||||
js_app = js_plugins + js_core
|
||||
|
||||
css_libs = [
|
||||
"css/bootstrap.min.css",
|
||||
@@ -1064,13 +1071,21 @@ class Server(object):
|
||||
"css/jquery.fileupload-ui.css",
|
||||
"css/pnotify.min.css"
|
||||
]
|
||||
css_app = list(dynamic_assets["css"])
|
||||
if len(css_app) == 0:
|
||||
css_app = ["empty"]
|
||||
css_core = list(dynamic_core_assets["css"]) + list(dynamic_plugin_assets["bundled"]["css"])
|
||||
if len(css_core) == 0:
|
||||
css_core = ["empty"]
|
||||
css_plugins = list(dynamic_plugin_assets["external"]["css"])
|
||||
if len(css_plugins) == 0:
|
||||
css_plugins = ["empty"]
|
||||
css_app = css_core + css_plugins
|
||||
|
||||
less_app = list(dynamic_assets["less"])
|
||||
if len(less_app) == 0:
|
||||
less_app = ["empty"]
|
||||
less_core = list(dynamic_core_assets["less"]) + list(dynamic_plugin_assets["bundled"]["less"])
|
||||
if len(less_core) == 0:
|
||||
less_core = ["empty"]
|
||||
less_plugins = list(dynamic_plugin_assets["external"]["less"])
|
||||
if len(less_plugins) == 0:
|
||||
less_plugins = ["empty"]
|
||||
less_app = less_core + less_plugins
|
||||
|
||||
from webassets.filter import register_filter, Filter
|
||||
from webassets.filter.cssrewrite.base import PatternRewriter
|
||||
@@ -1091,7 +1106,7 @@ class Server(object):
|
||||
|
||||
return "{import_with_options}\"{import_url}\";".format(**locals())
|
||||
|
||||
class JsDelimiterBundle(Filter):
|
||||
class JsDelimiterBundler(Filter):
|
||||
name = "js_delimiter_bundler"
|
||||
options = {}
|
||||
def input(self, _in, out, **kwargs):
|
||||
@@ -1099,24 +1114,42 @@ class Server(object):
|
||||
out.write("\n;\n")
|
||||
|
||||
register_filter(LessImportRewrite)
|
||||
register_filter(JsDelimiterBundle)
|
||||
register_filter(JsDelimiterBundler)
|
||||
|
||||
# JS
|
||||
js_libs_bundle = Bundle(*js_libs, output="webassets/packed_libs.js", filters="js_delimiter_bundler")
|
||||
if settings().getBoolean(["devel", "webassets", "minify"]):
|
||||
js_core_bundle = Bundle(*js_core, output="webassets/packed_core.js", filters="rjsmin, js_delimiter_bundler")
|
||||
js_plugins_bundle = Bundle(*js_plugins, output="webassets/packed_plugins.js", filters="rjsmin, js_delimiter_bundler")
|
||||
js_app_bundle = Bundle(*js_app, output="webassets/packed_app.js", filters="rjsmin, js_delimiter_bundler")
|
||||
else:
|
||||
js_core_bundle = Bundle(*js_core, output="webassets/packed_core.js", filters="js_delimiter_bundler")
|
||||
js_plugins_bundle = Bundle(*js_plugins, output="webassets/packed_plugins.js", filters="js_delimiter_bundler")
|
||||
js_app_bundle = Bundle(*js_app, output="webassets/packed_app.js", filters="js_delimiter_bundler")
|
||||
|
||||
# CSS
|
||||
css_libs_bundle = Bundle(*css_libs, output="webassets/packed_libs.css")
|
||||
css_core_bundle = Bundle(*css_core, output="webassets/packed_core.css", filters="cssrewrite")
|
||||
css_plugins_bundle = Bundle(*css_plugins, output="webassets/packed_plugins.css", filters="cssrewrite")
|
||||
css_app_bundle = Bundle(*css_app, output="webassets/packed_app.css", filters="cssrewrite")
|
||||
|
||||
all_less_bundle = Bundle(*less_app, output="webassets/packed_app.less", filters="cssrewrite, less_importrewrite")
|
||||
# LESS
|
||||
less_core_bundle = Bundle(*less_core, output="webassets/packed_core.less", filters="cssrewrite, less_importrewrite")
|
||||
less_plugins_bundle = Bundle(*less_plugins, output="webassets/packed_plugins.less", filters="cssrewrite, less_importrewrite")
|
||||
less_app_bundle = Bundle(*less_app, output="webassets/packed_app.less", filters="cssrewrite, less_importrewrite")
|
||||
|
||||
# asset registration
|
||||
assets.register("js_libs", js_libs_bundle)
|
||||
assets.register("js_core", js_core_bundle)
|
||||
assets.register("js_plugins", js_plugins_bundle)
|
||||
assets.register("js_app", js_app_bundle)
|
||||
assets.register("css_libs", css_libs_bundle)
|
||||
assets.register("css_core", css_core_bundle)
|
||||
assets.register("css_plugins", css_plugins_bundle)
|
||||
assets.register("css_app", css_app_bundle)
|
||||
assets.register("less_app", all_less_bundle)
|
||||
assets.register("less_core", less_core_bundle)
|
||||
assets.register("less_plugins", less_plugins_bundle)
|
||||
assets.register("less_app", less_app_bundle)
|
||||
|
||||
def _start_intermediary_server(self, s):
|
||||
import BaseHTTPServer
|
||||
|
||||
@@ -410,12 +410,13 @@ class OctoPrintFlaskResponse(flask.Response):
|
||||
# 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", "/")
|
||||
def delete_cookie(self, key, path='/', domain=None):
|
||||
flask.Response.delete_cookie(self, key, path=path, domain=domain)
|
||||
|
||||
# we also still might have a cookie left over from before we started prefixing, delete that manually
|
||||
# without any pre processing (no path prefix, no key suffix)
|
||||
flask.Response.set_cookie(self, key, expires=0, max_age=0, path=path, domain=domain)
|
||||
|
||||
# add request specific cookie suffix to name
|
||||
flask.Response.delete_cookie(self, key + flask.request.cookie_suffix, *args, **kwargs)
|
||||
|
||||
#~~ passive login helper
|
||||
|
||||
@@ -467,7 +468,9 @@ class LessSimpleCache(BaseCache):
|
||||
|
||||
def __init__(self, threshold=500, default_timeout=300):
|
||||
BaseCache.__init__(self, default_timeout=default_timeout)
|
||||
self._mutex = threading.RLock()
|
||||
self._cache = {}
|
||||
self._bypassed = set()
|
||||
self.clear = self._cache.clear
|
||||
self._threshold = threshold
|
||||
|
||||
@@ -476,27 +479,35 @@ class LessSimpleCache(BaseCache):
|
||||
now = time.time()
|
||||
for idx, (key, (expires, _)) in enumerate(self._cache.items()):
|
||||
if expires is not None and expires <= now or idx % 3 == 0:
|
||||
self._cache.pop(key, None)
|
||||
with self._mutex:
|
||||
self._cache.pop(key, None)
|
||||
|
||||
def get(self, key):
|
||||
import pickle
|
||||
now = time.time()
|
||||
expires, value = self._cache.get(key, (0, None))
|
||||
with self._mutex:
|
||||
expires, value = self._cache.get(key, (0, None))
|
||||
if expires is None or expires > now:
|
||||
return pickle.loads(value)
|
||||
|
||||
def set(self, key, value, timeout=None):
|
||||
import pickle
|
||||
self._prune()
|
||||
self._cache[key] = (self.calculate_timeout(timeout=timeout),
|
||||
pickle.dumps(value, pickle.HIGHEST_PROTOCOL))
|
||||
|
||||
with self._mutex:
|
||||
self._prune()
|
||||
self._cache[key] = (self.calculate_timeout(timeout=timeout),
|
||||
pickle.dumps(value, pickle.HIGHEST_PROTOCOL))
|
||||
if key in self._bypassed:
|
||||
self._bypassed.remove(key)
|
||||
|
||||
def add(self, key, value, timeout=None):
|
||||
self.set(key, value, timeout=None)
|
||||
self._cache.setdefault(key, self._cache[key])
|
||||
with self._mutex:
|
||||
self.set(key, value, timeout=None)
|
||||
self._cache.setdefault(key, self._cache[key])
|
||||
|
||||
def delete(self, key):
|
||||
self._cache.pop(key, None)
|
||||
with self._mutex:
|
||||
self._cache.pop(key, None)
|
||||
|
||||
def calculate_timeout(self, timeout=None):
|
||||
if timeout is None:
|
||||
@@ -508,7 +519,8 @@ class LessSimpleCache(BaseCache):
|
||||
def over_threshold(self):
|
||||
if self._threshold is None:
|
||||
return False
|
||||
return len(self._cache) > self._threshold
|
||||
with self._mutex:
|
||||
return len(self._cache) > self._threshold
|
||||
|
||||
def __getitem__(self, key):
|
||||
return self.get(key)
|
||||
@@ -520,7 +532,16 @@ class LessSimpleCache(BaseCache):
|
||||
return self.delete(key)
|
||||
|
||||
def __contains__(self, key):
|
||||
return key in self._cache
|
||||
with self._mutex:
|
||||
return key in self._cache
|
||||
|
||||
def set_bypassed(self, key):
|
||||
with self._mutex:
|
||||
self._bypassed.add(key)
|
||||
|
||||
def is_bypassed(self, key):
|
||||
with self._mutex:
|
||||
return key in self._bypassed
|
||||
|
||||
_cache = LessSimpleCache()
|
||||
|
||||
@@ -530,17 +551,20 @@ def cached(timeout=5 * 60, key=lambda: "view:%s" % flask.request.path, unless=No
|
||||
def decorated_function(*args, **kwargs):
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
cache_key = key()
|
||||
|
||||
# bypass the cache if "unless" condition is true
|
||||
if callable(unless) and unless():
|
||||
logger.debug("Cache for {path} bypassed, calling wrapped function".format(path=flask.request.path))
|
||||
_cache.set_bypassed(cache_key)
|
||||
return f(*args, **kwargs)
|
||||
|
||||
# also bypass the cache if it's disabled completely
|
||||
if not settings().getBoolean(["devel", "cache", "enabled"]):
|
||||
logger.debug("Cache for {path} disabled, calling wrapped function".format(path=flask.request.path))
|
||||
_cache.set_bypassed(cache_key)
|
||||
return f(*args, **kwargs)
|
||||
|
||||
cache_key = key()
|
||||
rv = _cache.get(cache_key)
|
||||
|
||||
# only take the value from the cache if we are not required to refresh it from the wrapped function
|
||||
@@ -556,7 +580,8 @@ def cached(timeout=5 * 60, key=lambda: "view:%s" % flask.request.path, unless=No
|
||||
|
||||
# do not store if the "unless_response" condition is true
|
||||
if callable(unless_response) and unless_response(rv):
|
||||
logger.debug("Not caching result for {path}, bypassed".format(path=flask.request.path))
|
||||
logger.debug("Not caching result for {path} (key: {key}), bypassed".format(path=flask.request.path, key=cache_key))
|
||||
_cache.set_bypassed(cache_key)
|
||||
return rv
|
||||
|
||||
# store it in the cache
|
||||
@@ -573,6 +598,11 @@ def is_in_cache(key=lambda: "view:%s" % flask.request.path):
|
||||
key = key()
|
||||
return key in _cache
|
||||
|
||||
def is_cache_bypassed(key=lambda: "view:%s" % flask.request.path):
|
||||
if callable(key):
|
||||
key = key()
|
||||
return _cache.is_bypassed(key)
|
||||
|
||||
def cache_check_headers():
|
||||
return "no-cache" in flask.request.cache_control or "no-cache" in flask.request.pragma
|
||||
|
||||
@@ -682,7 +712,7 @@ class PreemptiveCache(object):
|
||||
|
||||
with self._lock:
|
||||
try:
|
||||
with atomic_write(self.cachefile, "wb") as handle:
|
||||
with atomic_write(self.cachefile, "wb", max_permissions=0o666) as handle:
|
||||
yaml.safe_dump(data, handle,default_flow_style=False, indent=" ", allow_unicode=True)
|
||||
except:
|
||||
self._logger.exception("Error while writing {}".format(self.cachefile))
|
||||
@@ -1104,12 +1134,8 @@ class SettingsCheckUpdater(webassets.updater.BaseUpdater):
|
||||
cache_value = webassets.utils.hash_func(json.dumps(settings().effective_yaml))
|
||||
ctx.cache.set(cache_key, cache_value)
|
||||
|
||||
##~~ plugin assets collector
|
||||
|
||||
def collect_plugin_assets(enable_gcodeviewer=True, preferred_stylesheet="css"):
|
||||
logger = logging.getLogger(__name__ + ".collect_plugin_assets")
|
||||
|
||||
supported_stylesheets = ("css", "less")
|
||||
##~~ core assets collector
|
||||
def collect_core_assets(enable_gcodeviewer=True, preferred_stylesheet="css"):
|
||||
assets = dict(
|
||||
js=[],
|
||||
css=[],
|
||||
@@ -1148,9 +1174,24 @@ def collect_plugin_assets(enable_gcodeviewer=True, preferred_stylesheet="css"):
|
||||
elif preferred_stylesheet == "css":
|
||||
assets["css"].append('css/octoprint.css')
|
||||
|
||||
return assets
|
||||
|
||||
##~~ plugin assets collector
|
||||
|
||||
def collect_plugin_assets(enable_gcodeviewer=True, preferred_stylesheet="css"):
|
||||
logger = logging.getLogger(__name__ + ".collect_plugin_assets")
|
||||
|
||||
supported_stylesheets = ("css", "less")
|
||||
assets = dict(bundled=dict(js=[], css=[], less=[]),
|
||||
external=dict(js=[], css=[], less=[]))
|
||||
|
||||
asset_plugins = octoprint.plugin.plugin_manager().get_implementations(octoprint.plugin.AssetPlugin)
|
||||
for implementation in asset_plugins:
|
||||
name = implementation._identifier
|
||||
is_bundled = implementation._plugin_info.bundled
|
||||
|
||||
asset_key = "bundled" if is_bundled else "external"
|
||||
|
||||
try:
|
||||
all_assets = implementation.get_assets()
|
||||
basefolder = implementation.get_asset_folder()
|
||||
@@ -1168,13 +1209,13 @@ def collect_plugin_assets(enable_gcodeviewer=True, preferred_stylesheet="css"):
|
||||
for asset in all_assets["js"]:
|
||||
if not asset_exists("js", asset):
|
||||
continue
|
||||
assets["js"].append('plugin/{name}/{asset}'.format(**locals()))
|
||||
assets[asset_key]["js"].append('plugin/{name}/{asset}'.format(**locals()))
|
||||
|
||||
if preferred_stylesheet in all_assets:
|
||||
for asset in all_assets[preferred_stylesheet]:
|
||||
if not asset_exists(preferred_stylesheet, asset):
|
||||
continue
|
||||
assets[preferred_stylesheet].append('plugin/{name}/{asset}'.format(**locals()))
|
||||
assets[asset_key][preferred_stylesheet].append('plugin/{name}/{asset}'.format(**locals()))
|
||||
else:
|
||||
for stylesheet in supported_stylesheets:
|
||||
if not stylesheet in all_assets:
|
||||
@@ -1183,7 +1224,7 @@ def collect_plugin_assets(enable_gcodeviewer=True, preferred_stylesheet="css"):
|
||||
for asset in all_assets[stylesheet]:
|
||||
if not asset_exists(stylesheet, asset):
|
||||
continue
|
||||
assets[stylesheet].append('plugin/{name}/{asset}'.format(**locals()))
|
||||
assets[asset_key][stylesheet].append('plugin/{name}/{asset}'.format(**locals()))
|
||||
break
|
||||
|
||||
return assets
|
||||
@@ -203,4 +203,7 @@ class PrinterStateConnection(sockjs.tornado.SockJSConnection, octoprint.printer.
|
||||
try:
|
||||
self.send({type: payload})
|
||||
except Exception as e:
|
||||
self._logger.warn("Could not send message to client %s: %s" % (self._remoteAddress, str(e)))
|
||||
if self._logger.isEnabledFor(logging.DEBUG):
|
||||
self._logger.exception("Could not send message to client {}".format(self._remoteAddress))
|
||||
else:
|
||||
self._logger.warn("Could not send message to client {}: {}".format(self._remoteAddress, e))
|
||||
@@ -361,7 +361,7 @@ class UploadStorageFallbackHandler(tornado.web.RequestHandler):
|
||||
file=handle)
|
||||
|
||||
else:
|
||||
return dict(name=tornado.escape.utf8(name), content_type=content_type, data=b"")
|
||||
return dict(name=tornado.escape.utf8(name), content_type=tornado.escape.utf8(content_type), data=b"")
|
||||
|
||||
def _on_part_data(self, part, data):
|
||||
"""
|
||||
@@ -598,7 +598,7 @@ class WsgiInputContainer(object):
|
||||
|
||||
# determine the request_body to supply as wsgi.input
|
||||
if body is not None:
|
||||
if isinstance(body, (bytes, str)):
|
||||
if isinstance(body, (bytes, str, unicode)):
|
||||
request_body = io.BytesIO(tornado.escape.utf8(body))
|
||||
else:
|
||||
request_body = body
|
||||
|
||||
@@ -77,6 +77,9 @@ def in_cache():
|
||||
elif util.flask.is_in_cache(key):
|
||||
_logger.info("Found path {} in cache (key: {}), signaling as cached".format(path, key))
|
||||
return response
|
||||
elif util.flask.is_cache_bypassed(key):
|
||||
_logger.info("Path {} was bypassed from 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)
|
||||
|
||||
@@ -666,6 +666,7 @@ class Settings(object):
|
||||
printer_parameters = self._config["printerParameters"]
|
||||
|
||||
if "movementSpeed" in printer_parameters or "invertAxes" in printer_parameters:
|
||||
dirty = True
|
||||
default_profile["axes"] = dict(x=dict(), y=dict(), z=dict(), e=dict())
|
||||
if "movementSpeed" in printer_parameters:
|
||||
for axis in ("x", "y", "z", "e"):
|
||||
@@ -679,6 +680,7 @@ class Settings(object):
|
||||
del self._config["printerParameters"]["invertedAxes"]
|
||||
|
||||
if "numExtruders" in printer_parameters or "extruderOffsets" in printer_parameters:
|
||||
dirty = True
|
||||
if not "extruder" in default_profile:
|
||||
default_profile["extruder"] = dict()
|
||||
|
||||
@@ -694,6 +696,7 @@ class Settings(object):
|
||||
del self._config["printerParameters"]["extruderOffsets"]
|
||||
|
||||
if "bedDimensions" in printer_parameters:
|
||||
dirty = True
|
||||
bed_dimensions = printer_parameters["bedDimensions"]
|
||||
if not "volume" in default_profile:
|
||||
default_profile["volume"] = dict()
|
||||
@@ -710,8 +713,6 @@ class Settings(object):
|
||||
default_profile["volume"]["depth"] = bed_dimensions["y"]
|
||||
del self._config["printerParameters"]["bedDimensions"]
|
||||
|
||||
dirty = True
|
||||
|
||||
if dirty:
|
||||
if not "printerProfiles" in self._config:
|
||||
self._config["printerProfiles"] = dict()
|
||||
@@ -842,7 +843,7 @@ class Settings(object):
|
||||
|
||||
from octoprint.util import atomic_write
|
||||
try:
|
||||
with atomic_write(self._configfile, "wb", prefix="octoprint-config-", suffix=".yaml") as configFile:
|
||||
with atomic_write(self._configfile, "wb", prefix="octoprint-config-", suffix=".yaml", permissions=0o600, max_permissions=0o666) as configFile:
|
||||
yaml.safe_dump(self._config, configFile, default_flow_style=False, indent=" ", allow_unicode=True)
|
||||
self._dirty = False
|
||||
except:
|
||||
@@ -1153,7 +1154,7 @@ class Settings(object):
|
||||
path, _ = os.path.split(filename)
|
||||
if not os.path.exists(path):
|
||||
os.makedirs(path)
|
||||
with atomic_write(filename, "wb") as f:
|
||||
with atomic_write(filename, "wb", max_permissions=0o666) as f:
|
||||
f.write(script)
|
||||
|
||||
def _default_basedir(applicationName):
|
||||
|
||||
@@ -228,7 +228,7 @@ function ItemListHelper(listType, supportedSorting, supportedFilters, defaultSor
|
||||
return;
|
||||
|
||||
var filters = self.currentFilters();
|
||||
filters.pop(filter);
|
||||
filters = _.without(filters, filter);
|
||||
self.currentFilters(filters);
|
||||
self._saveCurrentFiltersToLocalStorage();
|
||||
|
||||
|
||||
+17
-9
@@ -1,9 +1,17 @@
|
||||
//
|
||||
// LESS - Leaner CSS v1.3.3
|
||||
// http://lesscss.org
|
||||
//
|
||||
// Copyright (c) 2009-2013, Alexis Sellier
|
||||
// Licensed under the Apache 2.0 License.
|
||||
//
|
||||
(function(e,t){function n(t){return e.less[t.split("/")[1]]}function f(){r.env==="development"?(r.optimization=0,r.watchTimer=setInterval(function(){r.watchMode&&g(function(e,t,n,r,i){t&&S(t.toCSS(),r,i.lastModified)})},r.poll)):r.optimization=3}function m(){var e=document.getElementsByTagName("style");for(var t=0;t<e.length;t++)e[t].type.match(p)&&(new r.Parser({filename:document.location.href.replace(/#.*$/,""),dumpLineNumbers:r.dumpLineNumbers})).parse(e[t].innerHTML||"",function(n,r){var i=r.toCSS(),s=e[t];s.type="text/css",s.styleSheet?s.styleSheet.cssText=i:s.innerHTML=i})}function g(e,t){for(var n=0;n<r.sheets.length;n++)w(r.sheets[n],e,t,r.sheets.length-(n+1))}function y(e,t){var n=b(e),r=b(t),i,s,o,u,a="";if(n.hostPart!==r.hostPart)return"";s=Math.max(r.directories.length,n.directories.length);for(i=0;i<s;i++)if(r.directories[i]!==n.directories[i])break;u=r.directories.slice(i),o=n.directories.slice(i);for(i=0;i<u.length-1;i++)a+="../";for(i=0;i<o.length-1;i++)a+=o[i]+"/";return a}function b(e,t){var n=/^((?:[a-z-]+:)?\/\/(?:[^\/\?#]*\/)|([\/\\]))?((?:[^\/\\\?#]*[\/\\])*)([^\/\\\?#]*)([#\?].*)?$/,r=e.match(n),i={},s=[],o,u;if(!r)throw new Error("Could not parse sheet href - '"+e+"'");if(!r[1]||r[2]){u=t.match(n);if(!u)throw new Error("Could not parse page url - '"+t+"'");r[1]=u[1],r[2]||(r[3]=u[3]+r[3])}if(r[3]){s=r[3].replace("\\","/").split("/");for(o=0;o<s.length;o++)s[o]===".."&&o>0&&(s.splice(o-1,2),o-=2)}return i.hostPart=r[1],i.directories=s,i.path=r[1]+s.join("/"),i.fileUrl=i.path+(r[4]||""),i.url=i.fileUrl+(r[5]||""),i}function w(t,n,i,s){var o=t.contents||{},u=t.files||{},a=b(t.href,e.location.href),f=a.url,c=l&&l.getItem(f),h=l&&l.getItem(f+":timestamp"),p={css:c,timestamp:h},d;r.relativeUrls?r.rootpath?t.entryPath?d=b(r.rootpath+y(a.path,t.entryPath)).path:d=r.rootpath:d=a.path:r.rootpath?d=r.rootpath:t.entryPath?d=t.entryPath:d=a.path,x(f,t.type,function(e,l){v+=e.replace(/@import .+?;/ig,"");if(!i&&p&&l&&(new Date(l)).valueOf()===(new Date(p.timestamp)).valueOf())S(p.css,t),n(null,null,e,t,{local:!0,remaining:s},f);else try{o[f]=e,(new r.Parser({optimization:r.optimization,paths:[a.path],entryPath:t.entryPath||a.path,mime:t.type,filename:f,rootpath:d,relativeUrls:t.relativeUrls,contents:o,files:u,dumpLineNumbers:r.dumpLineNumbers})).parse(e,function(r,i){if(r)return k(r,f);try{n(r,i,e,t,{local:!1,lastModified:l,remaining:s},f),N(document.getElementById("less-error-message:"+E(f)))}catch(r){k(r,f)}})}catch(c){k(c,f)}},function(e,t){throw new Error("Couldn't load "+t+" ("+e+")")})}function E(e){return e.replace(/^[a-z]+:\/\/?[^\/]+/,"").replace(/^\//,"").replace(/\.[a-zA-Z]+$/,"").replace(/[^\.\w-]+/g,"-").replace(/\./g,":")}function S(e,t,n){var r,i=t.href||"",s="less:"+(t.title||E(i));if((r=document.getElementById(s))===null){r=document.createElement("style"),r.type="text/css",t.media&&(r.media=t.media),r.id=s;var o=t&&t.nextSibling||null;(o||document.getElementsByTagName("head")[0]).parentNode.insertBefore(r,o)}if(r.styleSheet)try{r.styleSheet.cssText=e}catch(u){throw new Error("Couldn't reassign styleSheet.cssText.")}else(function(e){r.childNodes.length>0?r.firstChild.nodeValue!==e.nodeValue&&r.replaceChild(e,r.firstChild):r.appendChild(e)})(document.createTextNode(e));if(n&&l){C("saving "+i+" to cache.");try{l.setItem(i,e),l.setItem(i+":timestamp",n)}catch(u){C("failed to save")}}}function x(e,t,n,i){function a(t,n,r){t.status>=200&&t.status<300?n(t.responseText,t.getResponseHeader("Last-Modified")):typeof r=="function"&&r(t.status,e)}var s=T(),u=o?r.fileAsync:r.async;typeof s.overrideMimeType=="function"&&s.overrideMimeType("text/css"),s.open("GET",e,u),s.setRequestHeader("Accept",t||"text/x-less, text/css; q=0.9, */*; q=0.5"),s.send(null),o&&!r.fileAsync?s.status===0||s.status>=200&&s.status<300?n(s.responseText):i(s.status,e):u?s.onreadystatechange=function(){s.readyState==4&&a(s,n,i)}:a(s,n,i)}function T(){if(e.XMLHttpRequest)return new XMLHttpRequest;try{return new ActiveXObject("MSXML2.XMLHTTP.3.0")}catch(t){return C("browser doesn't support AJAX."),null}}function N(e){return e&&e.parentNode.removeChild(e)}function C(e){r.env=="development"&&typeof console!="undefined"&&console.log("less: "+e)}function k(e,t){var n="less-error-message:"+E(t),i='<li><label>{line}</label><pre class="{class}">{content}</pre></li>',s=document.createElement("div"),o,u,a=[],f=e.filename||t,l=f.match(/([^\/]+(\?.*)?)$/)[1];s.id=n,s.className="less-error-message",u="<h3>"+(e.message||"There is an error in your .less file")+"</h3>"+'<p>in <a href="'+f+'">'+l+"</a> ";var c=function(e,t,n){e.extract[t]&&a.push(i.replace(/\{line\}/,parseInt(e.line)+(t-1)).replace(/\{class\}/,n).replace(/\{content\}/,e.extract[t]))};e.stack?u+="<br/>"+e.stack.split("\n").slice(1).join("<br/>"):e.extract&&(c(e,0,""),c(e,1,"line"),c(e,2,""),u+="on line "+e.line+", column "+(e.column+1)+":</p>"+"<ul>"+a.join("")+"</ul>"),s.innerHTML=u,S([".less-error-message ul, .less-error-message li {","list-style-type: none;","margin-rigLine truncated
|
||||
:"#9acd32"}}(n("./tree")),function(e){e.Alpha=function(e){this.value=e},e.Alpha.prototype={toCSS:function(){return"alpha(opacity="+(this.value.toCSS?this.value.toCSS():this.value)+")"},eval:function(e){return this.value.eval&&(this.value=this.value.eval(e)),this}}}(n("../tree")),function(e){e.Anonymous=function(e){this.value=e.value||e},e.Anonymous.prototype={toCSS:function(){return this.value},eval:function(){return this},compare:function(e){if(!e.toCSS)return-1;var t=this.toCSS(),n=e.toCSS();return t===n?0:t<n?-1:1}}}(n("../tree")),function(e){e.Assignment=function(e,t){this.key=e,this.value=t},e.Assignment.prototype={toCSS:function(){return this.key+"="+(this.value.toCSS?this.value.toCSS():this.value)},eval:function(t){return this.value.eval?new e.Assignment(this.key,this.value.eval(t)):this}}}(n("../tree")),function(e){e.Call=function(e,t,n,r){this.name=e,this.args=t,this.index=n,this.filename=r},e.Call.prototype={eval:function(t){var n=this.args.map(function(e){return e.eval(t)}),r;if(this.name in e.functions)try{r=e.functions[this.name].apply(e.functions,n);if(r!=null)return r}catch(i){throw{type:i.type||"Runtime",message:"error evaluating function `"+this.name+"`"+(i.message?": "+i.message:""),index:this.index,filename:this.filename}}return new e.Anonymous(this.name+"("+n.map(function(e){return e.toCSS(t)}).join(", ")+")")},toCSS:function(e){return this.eval(e).toCSS()}}}(n("../tree")),function(e){e.Color=function(e,t){Array.isArray(e)?this.rgb=e:e.length==6?this.rgb=e.match(/.{2}/g).map(function(e){return parseInt(e,16)}):this.rgb=e.split("").map(function(e){return parseInt(e+e,16)}),this.alpha=typeof t=="number"?t:1},e.Color.prototype={eval:function(){return this},toCSS:function(){return this.alpha<1?"rgba("+this.rgb.map(function(e){return Math.round(e)}).concat(this.alpha).join(", ")+")":"#"+this.rgb.map(function(e){return e=Math.round(e),e=(e>255?255:e<0?0:e).toString(16),e.length===1?"0"+e:e}).join("")},operate:function(t,n){var r=[];n instanceof e.Color||(n=n.toColor());for(var i=0;i<3;i++)r[i]=e.operate(t,this.rgb[i],n.rgb[i]);return new e.Color(r,this.alpha+n.alpha)},toHSL:function(){var e=this.rgb[0]/255,t=this.rgb[1]/255,n=this.rgb[2]/255,r=this.alpha,i=Math.max(e,t,n),s=Math.min(e,t,n),o,u,a=(i+s)/2,f=i-s;if(i===s)o=u=0;else{u=a>.5?f/(2-i-s):f/(i+s);switch(i){case e:o=(t-n)/f+(t<n?6:0);break;case t:o=(n-e)/f+2;break;case n:o=(e-t)/f+4}o/=6}return{h:o*360,s:u,l:a,a:r}},toARGB:function(){var e=[Math.round(this.alpha*255)].concat(this.rgb);return"#"+e.map(function(e){return e=Math.round(e),e=(e>255?255:e<0?0:e).toString(16),e.length===1?"0"+e:e}).join("")},compare:function(e){return e.rgb?e.rgb[0]===this.rgb[0]&&e.rgb[1]===this.rgb[1]&&e.rgb[2]===this.rgb[2]&&e.alpha===this.alpha?0:-1:-1}}}(n("../tree")),function(e){e.Comment=function(e,t){this.value=e,this.silent=!!t},e.Comment.prototype={toCSS:function(e){return e.compress?"":this.value},eval:function(){return this}}}(n("../tree")),function(e){e.Condition=function(e,t,n,r,i){this.op=e.trim(),this.lvalue=t,this.rvalue=n,this.index=r,this.negate=i},e.Condition.prototype.eval=function(e){var t=this.lvalue.eval(e),n=this.rvalue.eval(e),r=this.index,i,i=function(e){switch(e){case"and":return t&&n;case"or":return t||n;default:if(t.compare)i=t.compare(n);else{if(!n.compare)throw{type:"Type",message:"Unable to perform comparison",index:r};i=n.compare(t)}switch(i){case-1:return e==="<"||e==="=<";case 0:return e==="="||e===">="||e==="=<";case 1:return e===">"||e===">="}}}(this.op);return this.negate?!i:i}}(n("../tree")),function(e){e.Dimension=function(e,t){this.value=parseFloat(e),this.unit=t||null},e.Dimension.prototype={eval:function(){return this},toColor:function(){return new e.Color([this.value,this.value,this.value])},toCSS:function(){var e=this.value+this.unit;return e},operate:function(t,n){return new e.Dimension(e.operate(t,this.value,n.value),this.unit||n.unit)},compare:function(t){return t instanceof e.Dimension?t.value>this.value?-1:t.value<this.value?1:t.unit&&this.unit!==t.unit?-1:0:-1}}}(n("../tree")),function(e){e.Directive=function(t,n){this.name=t,Array.isArray(n)?(this.ruleset=new e.Ruleset([],n),this.ruleset.allowImports=!0):this.value=n},e.Directive.prototype={toCSS:function(e,t){return this.ruleset?(this.ruleset.root=!0,this.name+(t.compress?"{":" {\n ")+this.ruleset.toCSS(e,t).trim().replace(/\n/g,"\n ")+(t.compress?"}":"\n}\n")):this.name+" "+this.value.toCSS()+";\n"},eval:function(t){var n=this;return this.ruleset&&(t.frames.unshift(this),n=new e.Directive(this.name),n.ruleset=this.ruleset.eval(t),t.frames.shift()),n},variable:function(t){return e.Ruleset.prototype.variable.call(this.ruleset,t)},find:function(){return e.Ruleset.prototype.find.apply(this.ruleset,arguments)},rulesets:function(){return e.Ruleset.prototype.rulesets.apply(this.ruleset)}}}(n("../tree")),function(e){e.Element=function(t,n,r){this.combinator=t instanceof e.Combinator?t:new e.Combinator(t),typeof n=="string"?this.value=n.trim():n?this.value=n:thisLine truncated
|
||||
/*!
|
||||
* Less - Leaner CSS v2.7.1
|
||||
* http://lesscss.org
|
||||
*
|
||||
* Copyright (c) 2009-2016, Alexis Sellier <self@cloudhead.net>
|
||||
* Licensed under the Apache-2.0 License.
|
||||
*
|
||||
*/
|
||||
|
||||
/** * @license Apache-2.0
|
||||
*/
|
||||
|
||||
!function(a){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=a();else if("function"==typeof define&&define.amd)define([],a);else{var b;b="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this,b.less=a()}}(function(){return function a(b,c,d){function e(g,h){if(!c[g]){if(!b[g]){var i="function"==typeof require&&require;if(!h&&i)return i(g,!0);if(f)return f(g,!0);var j=new Error("Cannot find module '"+g+"'");throw j.code="MODULE_NOT_FOUND",j}var k=c[g]={exports:{}};b[g][0].call(k.exports,function(a){var c=b[g][1][a];return e(c?c:a)},k,k.exports,a,b,c,d)}return c[g].exports}for(var f="function"==typeof require&&require,g=0;d.length>g;g++)e(d[g]);return e}({1:[function(a,b,c){var d=a("./utils").addDataAttr,e=a("./browser");b.exports=function(a,b){d(b,e.currentScript(a)),void 0===b.isFileProtocol&&(b.isFileProtocol=/^(file|(chrome|safari)(-extension)?|resource|qrc|app):/.test(a.location.protocol)),b.async=b.async||!1,b.fileAsync=b.fileAsync||!1,b.poll=b.poll||(b.isFileProtocol?1e3:1500),b.env=b.env||("127.0.0.1"==a.location.hostname||"0.0.0.0"==a.location.hostname||"localhost"==a.location.hostname||a.location.port&&a.location.port.length>0||b.isFileProtocol?"development":"production");var c=/!dumpLineNumbers:(comments|mediaquery|all)/.exec(a.location.hash);c&&(b.dumpLineNumbers=c[1]),void 0===b.useFileCache&&(b.useFileCache=!0),void 0===b.onReady&&(b.onReady=!0)}},{"./browser":3,"./utils":10}],2:[function(a,b,c){function d(a){a.filename&&console.warn(a),e.async||h.removeChild(i)}a("promise/polyfill.js");var e=window.less||{};a("./add-default-options")(window,e);var f=b.exports=a("./index")(window,e);window.less=f;var g,h,i;e.onReady&&(/!watch/.test(window.location.hash)&&f.watch(),e.async||(g="body { display: none !important }",h=document.head||document.getElementsByTagName("head")[0],i=document.createElement("style"),i.type="text/css",i.styleSheet?i.styleSheet.cssText=g:i.appendChild(document.createTextNode(g)),h.appendChild(i)),f.registerStylesheetsImmediately(),f.pageLoadFinished=f.refresh("development"===f.env).then(d,d))},{"./add-default-options":1,"./index":8,"promise/polyfill.js":97}],3:[function(a,b,c){var d=a("./utils");b.exports={createCSS:function(a,b,c){var e=c.href||"",f="less:"+(c.title||d.extractId(e)),g=a.getElementById(f),h=!1,i=a.createElement("style");i.setAttribute("type","text/css"),c.media&&i.setAttribute("media",c.media),i.id=f,i.styleSheet||(i.appendChild(a.createTextNode(b)),h=null!==g&&g.childNodes.length>0&&i.childNodes.length>0&&g.firstChild.nodeValue===i.firstChild.nodeValue);var j=a.getElementsByTagName("head")[0];if(null===g||h===!1){var k=c&&c.nextSibling||null;k?k.parentNode.insertBefore(i,k):j.appendChild(i)}if(g&&h===!1&&g.parentNode.removeChild(g),i.styleSheet)try{i.styleSheet.cssText=b}catch(l){throw new Error("Couldn't reassign styleSheet.cssText.")}},currentScript:function(a){var b=a.document;return b.currentScript||function(){var a=b.getElementsByTagName("script");return a[a.length-1]}()}}},{"./utils":10}],4:[function(a,b,c){b.exports=function(a,b,c){var d=null;if("development"!==b.env)try{d="undefined"==typeof a.localStorage?null:a.localStorage}catch(e){}return{setCSS:function(a,b,e,f){if(d){c.info("saving "+a+" to cache.");try{d.setItem(a,f),d.setItem(a+":timestamp",b),e&&d.setItem(a+":vars",JSON.stringify(e))}catch(g){c.error('failed to save "'+a+'" to local storage for caching.')}}},getCSS:function(a,b,c){var e=d&&d.getItem(a),f=d&&d.getItem(a+":timestamp"),g=d&&d.getItem(a+":vars");return c=c||{},f&&b.lastModified&&new Date(b.lastModified).valueOf()===new Date(f).valueOf()&&(!c&&!g||JSON.stringify(c)===g)?e:void 0}}}},{}],5:[function(a,b,c){var d=a("./utils"),e=a("./browser");b.exports=function(a,b,c){function f(b,f){var g,h,i="less-error-message:"+d.extractId(f||""),j='<li><label>{line}</label><pre class="{class}">{content}</pre></li>',k=a.document.createElement("div"),l=[],m=b.filename||f,n=m.match(/([^\/]+(\?.*)?)$/)[1];k.id=i,k.className="less-error-message",h="<h3>"+(b.type||"Syntax")+"Error: "+(b.message||"There is an error in your .less file")+'</h3><p>in <a href="'+m+'">'+n+"</a> ";var o=function(a,b,c){void 0!==a.extract[b]&&l.push(j.replace(/\{line\}/,(parseInt(a.line,10)||0)+(b-1)).replace(/\{class\}/,c).replace(/\{content\}/,a.extract[b]))};b.extract&&(o(b,0,""),o(b,1,"line"),o(b,2,""),h+="on line "+b.line+", column "+(b.column+1)+":</p><ul>"+l.join("")+"</ul>"),b.stack&&(b.extract||c.logLevel>=4)&&(h+="<br/>Stack Trace</br />"+b.stack.split("\n").slice(1).join("<br/>")),k.innerHTML=h,e.createCSS(a.document,[".less-error-message ul, .less-error-message li {","list-style-type: none;","margin-right: 15px;","padding: 4px 0;","margin: 0;","}",".less-error-message label {","font-size: 12px;","margin-right: 15px;","padding: 4px 0;","color: #cc7777;","}",".less-error-message pre {","color: #dd6666;","padding: 4px 0;","margin: 0;","display: inline-block;","}",".less-error-message pre.line {","cLine truncated
|
||||
}})},{"../tree/anonymous":46,"../tree/javascript":63,"../tree/quoted":73,"./function-registry":22}],28:[function(a,b,c){b.exports=function(b){var c=a("../tree/dimension"),d=a("../tree/color"),e=a("../tree/expression"),f=a("../tree/quoted"),g=a("../tree/url"),h=a("./function-registry");h.add("svg-gradient",function(a){function b(){throw{type:"Argument",message:"svg-gradient expects direction, start_color [start_position], [color position,]..., end_color [end_position] or direction, color list"}}var h,i,j,k,l,m,n,o,p="linear",q='x="0" y="0" width="1" height="1"',r={compress:!1},s=a.toCSS(r);switch(2==arguments.length?(2>arguments[1].value.length&&b(),h=arguments[1].value):3>arguments.length?b():h=Array.prototype.slice.call(arguments,1),s){case"to bottom":i='x1="0%" y1="0%" x2="0%" y2="100%"';break;case"to right":i='x1="0%" y1="0%" x2="100%" y2="0%"';break;case"to bottom right":i='x1="0%" y1="0%" x2="100%" y2="100%"';break;case"to top right":i='x1="0%" y1="100%" x2="100%" y2="0%"';break;case"ellipse":case"ellipse at center":p="radial",i='cx="50%" cy="50%" r="75%"',q='x="-50" y="-50" width="101" height="101"';break;default:throw{type:"Argument",message:"svg-gradient direction must be 'to bottom', 'to right', 'to bottom right', 'to top right' or 'ellipse at center'"}}for(j='<?xml version="1.0" ?><svg xmlns="http://www.w3.org/2000/svg" version="1.1" width="100%" height="100%" viewBox="0 0 1 1" preserveAspectRatio="none"><'+p+'Gradient id="gradient" gradientUnits="userSpaceOnUse" '+i+">",k=0;h.length>k;k+=1)h[k]instanceof e?(l=h[k].value[0],m=h[k].value[1]):(l=h[k],m=void 0),l instanceof d&&((0===k||k+1===h.length)&&void 0===m||m instanceof c)||b(),n=m?m.toCSS(r):0===k?"0%":"100%",o=l.alpha,j+='<stop offset="'+n+'" stop-color="'+l.toRGB()+'"'+(1>o?' stop-opacity="'+o+'"':"")+"/>";return j+="</"+p+"Gradient><rect "+q+' fill="url(#gradient)" /></svg>',j=encodeURIComponent(j),j="data:image/svg+xml,"+j,new g(new f("'"+j+"'",j,!1,this.index,this.currentFileInfo),this.index,this.currentFileInfo)})}},{"../tree/color":50,"../tree/dimension":56,"../tree/expression":59,"../tree/quoted":73,"../tree/url":80,"./function-registry":22}],29:[function(a,b,c){var d=a("../tree/keyword"),e=a("../tree/detached-ruleset"),f=a("../tree/dimension"),g=a("../tree/color"),h=a("../tree/quoted"),i=a("../tree/anonymous"),j=a("../tree/url"),k=a("../tree/operation"),l=a("./function-registry"),m=function(a,b){return a instanceof b?d.True:d.False},n=function(a,b){if(void 0===b)throw{type:"Argument",message:"missing the required second argument to isunit."};if(b="string"==typeof b.value?b.value:b,"string"!=typeof b)throw{type:"Argument",message:"Second argument to isunit should be a unit or a string."};return a instanceof f&&a.unit.is(b)?d.True:d.False},o=function(a){var b=Array.isArray(a.value)?a.value:Array(a);return b};l.addMultiple({isruleset:function(a){return m(a,e)},iscolor:function(a){return m(a,g)},isnumber:function(a){return m(a,f)},isstring:function(a){return m(a,h)},iskeyword:function(a){return m(a,d)},isurl:function(a){return m(a,j)},ispixel:function(a){return n(a,"px")},ispercentage:function(a){return n(a,"%")},isem:function(a){return n(a,"em")},isunit:n,unit:function(a,b){if(!(a instanceof f))throw{type:"Argument",message:"the first argument to unit must be a number"+(a instanceof k?". Have you forgotten parenthesis?":"")};return b=b?b instanceof d?b.value:b.toCSS():"",new f(a.value,b)},"get-unit":function(a){return new i(a.unit)},extract:function(a,b){return b=b.value-1,o(a)[b]},length:function(a){return new f(o(a).length)}})},{"../tree/anonymous":46,"../tree/color":50,"../tree/detached-ruleset":55,"../tree/dimension":56,"../tree/keyword":65,"../tree/operation":71,"../tree/quoted":73,"../tree/url":80,"./function-registry":22}],30:[function(a,b,c){var d=a("./contexts"),e=a("./parser/parser"),f=a("./plugins/function-importer");b.exports=function(a){var b=function(a,b){this.rootFilename=b.filename,this.paths=a.paths||[],this.contents={},this.contentsIgnoredChars={},this.mime=a.mime,this.error=null,this.context=a,this.queue=[],this.files={}};return b.prototype.push=function(b,c,g,h,i){var j=this;this.queue.push(b);var k=function(a,c,d){j.queue.splice(j.queue.indexOf(b),1);var e=d===j.rootFilename;h.optional&&a?i(null,{rules:[]},!1,null):(j.files[d]=c,a&&!j.error&&(j.error=a),i(a,c,e,d))},l={relativeUrls:this.context.relativeUrls,entryPath:g.entryPath,rootpath:g.rootpath,rootFilename:g.rootFilename},m=a.getFileManager(b,g.currentDirectory,this.context,a);if(!m)return void k({message:"Could not find a file-manager for "+b});c&&(b=m.tryAppendExtension(b,h.plugin?".js":".less"));var n=function(a){var b=a.filename,c=a.contents.replace(/^\uFEFF/,"");l.currentDirectory=m.getPath(b),l.relativeUrls&&(l.rootpath=m.join(j.context.rootpath||"",m.pathDiff(l.currentDirectory,l.entryPath)),!m.isPathAbsolute(l.rootpath)&&m.alwaysMakePathsAbsolute()&&(l.rootpath=m.join(l.entryPath,l.rootpath))),l.filename=b;var i=new d.Parse(j.context);i.processImports=Line truncated
|
||||
f={add:function(a,b){g[a]=b},addMultiple:function(a){Object.keys(a).forEach(function(b){g[b]=a[b]})}};try{c=new Function("functions","tree","fileInfo",a),c(f,e,this.fileInfo)}catch(h){b(new d({message:"Plugin evaluation error: '"+h.name+": "+h.message.replace(/["]/g,"'")+"'",filename:this.fileInfo.filename}),null)}b(null,{functions:g})}},{"../less-error":32,"../tree":62}],41:[function(a,b,c){var d;b.exports=function(b,c,e){var f=function(b,e,g){if("function"==typeof e&&(g=e,e={}),!g){d||(d="undefined"==typeof Promise?a("promise"):Promise);var h=this;return new d(function(a,c){f.call(h,b,e,function(b,d){b?c(b):a(d)})})}this.parse(b,e,function(a,b,d,e){if(a)return g(a);var f;try{var h=new c(b,d);f=h.toCSS(e)}catch(a){return g(a)}g(null,f)})};return f}},{promise:void 0}],42:[function(a,b,c){b.exports=function(a,b){var c=function(a){this.options=a};return c.prototype.toCSS=function(b,c,d){var e=new a({contentsIgnoredCharsMap:d.contentsIgnoredChars,rootNode:b,contentsMap:d.contents,sourceMapFilename:this.options.sourceMapFilename,sourceMapURL:this.options.sourceMapURL,outputFilename:this.options.sourceMapOutputFilename,sourceMapBasepath:this.options.sourceMapBasepath,sourceMapRootpath:this.options.sourceMapRootpath,outputSourceFiles:this.options.outputSourceFiles,sourceMapGenerator:this.options.sourceMapGenerator,sourceMapFileInline:this.options.sourceMapFileInline}),f=e.toCSS(c);return this.sourceMap=e.sourceMap,this.sourceMapURL=e.sourceMapURL,this.options.sourceMapInputFilename&&(this.sourceMapInputFilename=e.normalizeFilename(this.options.sourceMapInputFilename)),f+this.getCSSAppendage()},c.prototype.getCSSAppendage=function(){var a=this.sourceMapURL;if(this.options.sourceMapFileInline){if(void 0===this.sourceMap)return"";a="data:application/json;base64,"+b.encodeBase64(this.sourceMap)}return a?"/*# sourceMappingURL="+a+" */":""},c.prototype.getExternalSourceMap=function(){return this.sourceMap},c.prototype.setExternalSourceMap=function(a){this.sourceMap=a},c.prototype.isInline=function(){return this.options.sourceMapFileInline},c.prototype.getSourceMapURL=function(){return this.sourceMapURL},c.prototype.getOutputFilename=function(){return this.options.sourceMapOutputFilename},c.prototype.getInputFilename=function(){return this.sourceMapInputFilename},c}},{}],43:[function(a,b,c){b.exports=function(a){var b=function(b){this._css=[],this._rootNode=b.rootNode,this._contentsMap=b.contentsMap,this._contentsIgnoredCharsMap=b.contentsIgnoredCharsMap,b.sourceMapFilename&&(this._sourceMapFilename=b.sourceMapFilename.replace(/\\/g,"/")),this._outputFilename=b.outputFilename,this.sourceMapURL=b.sourceMapURL,b.sourceMapBasepath&&(this._sourceMapBasepath=b.sourceMapBasepath.replace(/\\/g,"/")),b.sourceMapRootpath?(this._sourceMapRootpath=b.sourceMapRootpath.replace(/\\/g,"/"),"/"!==this._sourceMapRootpath.charAt(this._sourceMapRootpath.length-1)&&(this._sourceMapRootpath+="/")):this._sourceMapRootpath="",this._outputSourceFiles=b.outputSourceFiles,this._sourceMapGeneratorConstructor=a.getSourceMapGenerator(),this._lineNumber=0,this._column=0};return b.prototype.normalizeFilename=function(a){return a=a.replace(/\\/g,"/"),this._sourceMapBasepath&&0===a.indexOf(this._sourceMapBasepath)&&(a=a.substring(this._sourceMapBasepath.length),"\\"!==a.charAt(0)&&"/"!==a.charAt(0)||(a=a.substring(1))),(this._sourceMapRootpath||"")+a},b.prototype.add=function(a,b,c,d){if(a){var e,f,g,h,i;if(b){var j=this._contentsMap[b.filename];this._contentsIgnoredCharsMap[b.filename]&&(c-=this._contentsIgnoredCharsMap[b.filename],0>c&&(c=0),j=j.slice(this._contentsIgnoredCharsMap[b.filename])),j=j.substring(0,c),f=j.split("\n"),h=f[f.length-1]}if(e=a.split("\n"),g=e[e.length-1],b)if(d)for(i=0;e.length>i;i++)this._sourceMapGenerator.addMapping({generated:{line:this._lineNumber+i+1,column:0===i?this._column:0},original:{line:f.length+i,column:0===i?h.length:0},source:this.normalizeFilename(b.filename)});else this._sourceMapGenerator.addMapping({generated:{line:this._lineNumber+1,column:this._column},original:{line:f.length,column:h.length},source:this.normalizeFilename(b.filename)});1===e.length?this._column+=g.length:(this._lineNumber+=e.length-1,this._column=g.length),this._css.push(a)}},b.prototype.isEmpty=function(){return 0===this._css.length},b.prototype.toCSS=function(a){if(this._sourceMapGenerator=new this._sourceMapGeneratorConstructor({file:this._outputFilename,sourceRoot:null}),this._outputSourceFiles)for(var b in this._contentsMap)if(this._contentsMap.hasOwnProperty(b)){var c=this._contentsMap[b];this._contentsIgnoredCharsMap[b]&&(c=c.slice(this._contentsIgnoredCharsMap[b])),this._sourceMapGenerator.setSourceContent(this.normalizeFilename(b),c)}if(this._rootNode.genCSS(a,this),this._css.length>0){var d,e=JSON.stringify(this._sourceMapGenerator.toJSON());this.sourceMapURL?d=this.sourceMapURL:this._sourceMapFilename&&(d=this._sourceMapFilename),this.sourceMapURL=d,this.sourceMap=e}return this._css.join("")},b}},{}],44:[function(a,b,c){var dLine truncated
|
||||
this._setVisibilityToReplacement(C),Array.prototype.push.apply(u,C)}catch(D){throw{message:D.message,index:this.index,filename:this.currentFileInfo.filename,stack:D.stack}}if(v)return u}throw n?{type:"Runtime",message:"No matching definition was found for `"+this.format(t)+"`",index:this.index,filename:this.currentFileInfo.filename}:{type:"Name",message:this.selector.toCSS().trim()+" is undefined",index:this.index,filename:this.currentFileInfo.filename}},h.prototype._setVisibilityToReplacement=function(a){var b,c;if(this.blocksVisibility())for(b=0;a.length>b;b++)c=a[b],c.addVisibilityBlock()},h.prototype.format=function(a){return this.selector.toCSS().trim()+"("+(a?a.map(function(a){var b="";return a.name&&(b+=a.name+":"),b+=a.value.toCSS?a.value.toCSS():"???"}).join(", "):"")+")"},b.exports=h},{"../functions/default":20,"./mixin-definition":68,"./node":70,"./selector":77}],68:[function(a,b,c){var d=a("./selector"),e=a("./element"),f=a("./ruleset"),g=a("./rule"),h=a("./expression"),i=a("../contexts"),j=function(a,b,c,f,g,h,i){this.name=a,this.selectors=[new d([new e(null,a,this.index,this.currentFileInfo)])],this.params=b,this.condition=f,this.variadic=g,this.arity=b.length,this.rules=c,this._lookups={};var j=[];this.required=b.reduce(function(a,b){return!b.name||b.name&&!b.value?a+1:(j.push(b.name),a)},0),this.optionalParameters=j,this.frames=h,this.copyVisibilityInfo(i),this.allowRoot=!0};j.prototype=new f,j.prototype.type="MixinDefinition",j.prototype.evalFirst=!0,j.prototype.accept=function(a){this.params&&this.params.length&&(this.params=a.visitArray(this.params)),this.rules=a.visitArray(this.rules),this.condition&&(this.condition=a.visit(this.condition))},j.prototype.evalParams=function(a,b,c,d){var e,j,k,l,m,n,o,p,q=new f(null,null),r=this.params.slice(0),s=0;if(b.frames&&b.frames[0]&&b.frames[0].functionRegistry&&(q.functionRegistry=b.frames[0].functionRegistry.inherit()),b=new i.Eval(b,[q].concat(b.frames)),c)for(c=c.slice(0),s=c.length,k=0;s>k;k++)if(j=c[k],n=j&&j.name){for(o=!1,l=0;r.length>l;l++)if(!d[l]&&n===r[l].name){d[l]=j.value.eval(a),q.prependRule(new g(n,j.value.eval(a))),o=!0;break}if(o){c.splice(k,1),k--;continue}throw{type:"Runtime",message:"Named argument for "+this.name+" "+c[k].name+" not found"}}for(p=0,k=0;r.length>k;k++)if(!d[k]){if(j=c&&c[p],n=r[k].name)if(r[k].variadic){for(e=[],l=p;s>l;l++)e.push(c[l].value.eval(a));q.prependRule(new g(n,new h(e).eval(a)))}else{if(m=j&&j.value)m=m.eval(a);else{if(!r[k].value)throw{type:"Runtime",message:"wrong number of arguments for "+this.name+" ("+s+" for "+this.arity+")"};m=r[k].value.eval(b),q.resetCache()}q.prependRule(new g(n,m)),d[k]=m}if(r[k].variadic&&c)for(l=p;s>l;l++)d[l]=c[l].value.eval(a);p++}return q},j.prototype.makeImportant=function(){var a=this.rules?this.rules.map(function(a){return a.makeImportant?a.makeImportant(!0):a}):this.rules,b=new j(this.name,this.params,a,this.condition,this.variadic,this.frames);return b},j.prototype.eval=function(a){return new j(this.name,this.params,this.rules,this.condition,this.variadic,this.frames||a.frames.slice(0))},j.prototype.evalCall=function(a,b,c){var d,e,j=[],k=this.frames?this.frames.concat(a.frames):a.frames,l=this.evalParams(a,new i.Eval(a,k),b,j);return l.prependRule(new g("@arguments",new h(j).eval(a))),d=this.rules.slice(0),e=new f(null,d),e.originalRuleset=this,e=e.eval(new i.Eval(a,[this,l].concat(k))),c&&(e=e.makeImportant()),e},j.prototype.matchCondition=function(a,b){return!this.condition||this.condition.eval(new i.Eval(b,[this.evalParams(b,new i.Eval(b,this.frames?this.frames.concat(b.frames):b.frames),a,[])].concat(this.frames||[]).concat(b.frames)))},j.prototype.matchArgs=function(a,b){var c,d=a&&a.length||0,e=this.optionalParameters,f=a?a.reduce(function(a,b){return e.indexOf(b.name)<0?a+1:a},0):0;if(this.variadic){if(this.required-1>f)return!1}else{if(this.required>f)return!1;if(d>this.params.length)return!1}c=Math.min(f,this.arity);for(var g=0;c>g;g++)if(!this.params[g].name&&!this.params[g].variadic&&a[g].value.eval(b).toCSS()!=this.params[g].value.eval(b).toCSS())return!1;return!0},b.exports=j},{"../contexts":11,"./element":58,"./expression":59,"./rule":74,"./ruleset":76,"./selector":77}],69:[function(a,b,c){var d=a("./node"),e=a("./operation"),f=a("./dimension"),g=function(a){this.value=a};g.prototype=new d,g.prototype.type="Negative",g.prototype.genCSS=function(a,b){b.add("-"),this.value.genCSS(a,b)},g.prototype.eval=function(a){return a.isMathOn()?new e("*",[new f(-1),this.value]).eval(a):new g(this.value.eval(a))},b.exports=g},{"./dimension":56,"./node":70,"./operation":71}],70:[function(a,b,c){var d=function(){};d.prototype.toCSS=function(a){var b=[];return this.genCSS(a,{add:function(a,c,d){b.push(a)},isEmpty:function(){return 0===b.length}}),b.join("")},d.prototype.genCSS=function(a,b){b.add(this.value)},d.prototype.accept=function(a){this.value=a.visit(this.value)},d.prototype.eval=function(){return this},d.prototype._operate=function(a,b,c,d){switch(b){caLine truncated
|
||||
this.variableImports.push(a)},d.prototype.tryRun=function(){this._currentDepth++;try{for(;;){for(;this.imports.length>0;){var a=this.imports[0];if(!a.isReady)return;this.imports=this.imports.slice(1),a.callback.apply(null,a.args)}if(0===this.variableImports.length)break;var b=this.variableImports[0];this.variableImports=this.variableImports.slice(1),b()}}finally{this._currentDepth--}0===this._currentDepth&&this._onSequencerEmpty&&this._onSequencerEmpty()},b.exports=d},{}],86:[function(a,b,c){var d=a("../contexts"),e=a("./visitor"),f=a("./import-sequencer"),g=function(a,b){this._visitor=new e(this),this._importer=a,this._finish=b,this.context=new d.Eval,this.importCount=0,this.onceFileDetectionMap={},this.recursionDetector={},this._sequencer=new f(this._onSequencerEmpty.bind(this))};g.prototype={isReplacing:!1,run:function(a){try{this._visitor.visit(a)}catch(b){this.error=b}this.isFinished=!0,this._sequencer.tryRun()},_onSequencerEmpty:function(){this.isFinished&&this._finish(this.error)},visitImport:function(a,b){var c=a.options.inline;if(!a.css||c){var e=new d.Eval(this.context,this.context.frames.slice(0)),f=e.frames[0];this.importCount++,a.isVariableImport()?this._sequencer.addVariableImport(this.processImportNode.bind(this,a,e,f)):this.processImportNode(a,e,f)}b.visitDeeper=!1},processImportNode:function(a,b,c){var d,e=a.options.inline;try{d=a.evalForImport(b)}catch(f){f.filename||(f.index=a.index,f.filename=a.currentFileInfo.filename),a.css=!0,a.error=f}if(!d||d.css&&!e)this.importCount--,this.isFinished&&this._sequencer.tryRun();else{d.options.multiple&&(b.importMultiple=!0);for(var g=void 0===d.css,h=0;c.rules.length>h;h++)if(c.rules[h]===a){c.rules[h]=d;break}var i=this.onImported.bind(this,d,b),j=this._sequencer.addImport(i);this._importer.push(d.getPath(),g,d.currentFileInfo,d.options,j)}},onImported:function(a,b,c,d,e,f){c&&(c.filename||(c.index=a.index,c.filename=a.currentFileInfo.filename),this.error=c);var g=this,h=a.options.inline,i=a.options.plugin,j=a.options.optional,k=e||f in g.recursionDetector;if(b.importMultiple||(a.skip=k?!0:function(){return f in g.onceFileDetectionMap?!0:(g.onceFileDetectionMap[f]=!0,!1)}),!f&&j&&(a.skip=!0),d&&(a.root=d,a.importedFilename=f,!h&&!i&&(b.importMultiple||!k))){g.recursionDetector[f]=!0;var l=this.context;this.context=b;try{this._visitor.visit(d)}catch(c){this.error=c}this.context=l}g.importCount--,g.isFinished&&g._sequencer.tryRun()},visitRule:function(a,b){"DetachedRuleset"===a.value.type?this.context.frames.unshift(a):b.visitDeeper=!1},visitRuleOut:function(a){"DetachedRuleset"===a.value.type&&this.context.frames.shift()},visitDirective:function(a,b){this.context.frames.unshift(a)},visitDirectiveOut:function(a){this.context.frames.shift()},visitMixinDefinition:function(a,b){this.context.frames.unshift(a)},visitMixinDefinitionOut:function(a){this.context.frames.shift()},visitRuleset:function(a,b){this.context.frames.unshift(a)},visitRulesetOut:function(a){this.context.frames.shift()},visitMedia:function(a,b){this.context.frames.unshift(a.rules[0])},visitMediaOut:function(a){this.context.frames.shift()}},b.exports=g},{"../contexts":11,"./import-sequencer":85,"./visitor":91}],87:[function(a,b,c){var d={Visitor:a("./visitor"),ImportVisitor:a("./import-visitor"),MarkVisibleSelectorsVisitor:a("./set-tree-visibility-visitor"),ExtendVisitor:a("./extend-visitor"),JoinSelectorVisitor:a("./join-selector-visitor"),ToCSSVisitor:a("./to-css-visitor")};b.exports=d},{"./extend-visitor":84,"./import-visitor":86,"./join-selector-visitor":88,"./set-tree-visibility-visitor":89,"./to-css-visitor":90,"./visitor":91}],88:[function(a,b,c){var d=a("./visitor"),e=function(){this.contexts=[[]],this._visitor=new d(this)};e.prototype={run:function(a){return this._visitor.visit(a)},visitRule:function(a,b){b.visitDeeper=!1},visitMixinDefinition:function(a,b){b.visitDeeper=!1},visitRuleset:function(a,b){var c,d=this.contexts[this.contexts.length-1],e=[];this.contexts.push(e),a.root||(c=a.selectors,c&&(c=c.filter(function(a){return a.getIsOutput()}),a.selectors=c.length?c:c=null,c&&a.joinSelectors(e,d,c)),c||(a.rules=null),a.paths=e)},visitRulesetOut:function(a){this.contexts.length=this.contexts.length-1},visitMedia:function(a,b){var c=this.contexts[this.contexts.length-1];a.rules[0].root=0===c.length||c[0].multiMedia},visitDirective:function(a,b){var c=this.contexts[this.contexts.length-1];a.rules&&a.rules.length&&(a.rules[0].root=a.isRooted||0===c.length||null)}},b.exports=e},{"./visitor":91}],89:[function(a,b,c){var d=function(a){this.visible=a};d.prototype.run=function(a){this.visit(a)},d.prototype.visitArray=function(a){if(!a)return a;var b,c=a.length;for(b=0;c>b;b++)this.visit(a[b]);return a},d.prototype.visit=function(a){return a?a.constructor===Array?this.visitArray(a):!a.blocksVisibility||a.blocksVisibility()?a:(this.visible?a.ensureVisibility():a.ensureInvisibility(),a.accept(this),a):a},b.exports=d},{}],90:[function(a,b,c){var d=a("../tree"),e=a("./visitor"),f=function(Line truncated
|
||||
@@ -1,11 +1,4 @@
|
||||
{% assets "js_libs" %}
|
||||
<script type="text/javascript" src="{{ ASSET_URL }}"></script>
|
||||
{% endassets %}
|
||||
|
||||
{% assets "js_app" %}
|
||||
<script type="text/javascript" src="{{ ASSET_URL }}"></script>
|
||||
{% endassets %}
|
||||
|
||||
{% if g.locale %}
|
||||
<script type="text/javascript" src="{{ url_for('localeJs', locale=g.locale, domain='messages') }}"></script>
|
||||
{% endif %}
|
||||
{% assets "js_libs" %}<script type="text/javascript" src="{{ ASSET_URL }}"></script>{% endassets %}
|
||||
{% assets "js_plugins" %}<script type="text/javascript" src="{{ ASSET_URL }}"></script>{% endassets %}
|
||||
{% assets "js_core" %}<script type="text/javascript" src="{{ ASSET_URL }}"></script>{% endassets %}
|
||||
{% if g.locale %}<script type="text/javascript" src="{{ url_for('localeJs', locale=g.locale, domain='messages') }}"></script>{% endif %}
|
||||
@@ -1,13 +1,6 @@
|
||||
{% assets "css_libs" %}
|
||||
<link href="{{ ASSET_URL }}" rel="stylesheet" media="screen">
|
||||
{% endassets %}
|
||||
|
||||
{% assets "css_app" %}
|
||||
<link href="{{ ASSET_URL }}" rel="stylesheet" media="screen">
|
||||
{% endassets %}
|
||||
|
||||
{% assets "less_app" %}
|
||||
<link href="{{ ASSET_URL }}" rel="stylesheet/less" type="text/css" media="screen">
|
||||
{% endassets %}
|
||||
|
||||
{% assets "css_libs" %}<link href="{{ ASSET_URL }}" rel="stylesheet" media="screen">{% endassets %}
|
||||
{% assets "css_core" %}<link href="{{ ASSET_URL }}" rel="stylesheet" media="screen">{% endassets %}
|
||||
{% assets "css_plugins" %}<link href="{{ ASSET_URL }}" rel="stylesheet" media="screen">{% endassets %}
|
||||
{% assets "less_core" %}<link href="{{ ASSET_URL }}" rel="stylesheet/less" type="text/css" media="screen">{% endassets %}
|
||||
{% assets "less_plugins" %}<link href="{{ ASSET_URL }}" rel="stylesheet/less" type="text/css" media="screen">{% endassets %}
|
||||
<script src="{{ url_for('static', filename='js/lib/less.min.js') }}" type="text/javascript"></script>
|
||||
@@ -1,4 +1,5 @@
|
||||
# coding=utf-8
|
||||
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'
|
||||
|
||||
@@ -234,7 +234,7 @@ class FilebasedUserManager(UserManager):
|
||||
"settings": user._settings
|
||||
}
|
||||
|
||||
with atomic_write(self._userfile, "wb") as f:
|
||||
with atomic_write(self._userfile, "wb", permissions=0o600, max_permissions=0o666) as f:
|
||||
yaml.safe_dump(data, f, default_flow_style=False, indent=" ", allow_unicode=True)
|
||||
self._dirty = False
|
||||
self._load()
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import
|
||||
|
||||
"""
|
||||
This module bundles commonly used utility methods or helper classes that are used in multiple places withing
|
||||
OctoPrint's source code.
|
||||
@@ -693,12 +695,17 @@ def address_for_client(host, port):
|
||||
|
||||
|
||||
@contextlib.contextmanager
|
||||
def atomic_write(filename, mode="w+b", prefix="tmp", suffix=""):
|
||||
def atomic_write(filename, mode="w+b", prefix="tmp", suffix="", permissions=0o644, max_permissions=0o777):
|
||||
if os.path.exists(filename):
|
||||
permissions |= os.stat(filename).st_mode
|
||||
permissions &= max_permissions
|
||||
|
||||
temp_config = tempfile.NamedTemporaryFile(mode=mode, prefix=prefix, suffix=suffix, delete=False)
|
||||
try:
|
||||
yield temp_config
|
||||
finally:
|
||||
temp_config.close()
|
||||
os.chmod(temp_config.name, permissions)
|
||||
shutil.move(temp_config.name, filename)
|
||||
|
||||
|
||||
|
||||
@@ -83,13 +83,16 @@ class TestAtomicWrite(unittest.TestCase):
|
||||
|
||||
@mock.patch("shutil.move")
|
||||
@mock.patch("tempfile.NamedTemporaryFile")
|
||||
def test_atomic_write(self, mock_tempfile, mock_move):
|
||||
@mock.patch("os.chmod")
|
||||
@mock.patch("os.path.exists")
|
||||
def test_atomic_write(self, mock_exists, mock_chmod, mock_tempfile, mock_move):
|
||||
"""Tests the regular basic "good" case."""
|
||||
|
||||
# setup
|
||||
mock_file = mock.MagicMock()
|
||||
mock_file.name = "tempfile.tmp"
|
||||
mock_tempfile.return_value = mock_file
|
||||
mock_exists.return_value = False
|
||||
|
||||
# test
|
||||
with octoprint.util.atomic_write("somefile.yaml") as f:
|
||||
@@ -99,11 +102,14 @@ class TestAtomicWrite(unittest.TestCase):
|
||||
mock_tempfile.assert_called_once_with(mode="w+b", prefix="tmp", suffix="", delete=False)
|
||||
mock_file.write.assert_called_once_with("test")
|
||||
mock_file.close.assert_called_once_with()
|
||||
mock_chmod.assert_called_once_with("tempfile.tmp", 0o644)
|
||||
mock_move.assert_called_once_with("tempfile.tmp", "somefile.yaml")
|
||||
|
||||
@mock.patch("shutil.move")
|
||||
@mock.patch("tempfile.NamedTemporaryFile")
|
||||
def test_atomic_write_error_on_write(self, mock_tempfile, mock_move):
|
||||
@mock.patch("os.chmod")
|
||||
@mock.patch("os.path.exists")
|
||||
def test_atomic_write_error_on_write(self, mock_exists, mock_chmod, mock_tempfile, mock_move):
|
||||
"""Tests the error case where something in the wrapped code fails."""
|
||||
|
||||
# setup
|
||||
@@ -111,6 +117,7 @@ class TestAtomicWrite(unittest.TestCase):
|
||||
mock_file.name = "tempfile.tmp"
|
||||
mock_file.write.side_effect = RuntimeError()
|
||||
mock_tempfile.return_value = mock_file
|
||||
mock_exists.return_value = False
|
||||
|
||||
# test
|
||||
try:
|
||||
@@ -124,16 +131,20 @@ class TestAtomicWrite(unittest.TestCase):
|
||||
mock_tempfile.assert_called_once_with(mode="w+b", prefix="tmp", suffix="", delete=False)
|
||||
mock_file.close.assert_called_once_with()
|
||||
self.assertFalse(mock_move.called)
|
||||
self.assertFalse(mock_chmod.called)
|
||||
|
||||
@mock.patch("shutil.move")
|
||||
@mock.patch("tempfile.NamedTemporaryFile")
|
||||
def test_atomic_write_error_on_move(self, mock_tempfile, mock_move):
|
||||
@mock.patch("os.chmod")
|
||||
@mock.patch("os.path.exists")
|
||||
def test_atomic_write_error_on_move(self, mock_exists, mock_chmod, mock_tempfile, mock_move):
|
||||
"""Tests the error case where the final move fails."""
|
||||
# setup
|
||||
mock_file = mock.MagicMock()
|
||||
mock_file.name = "tempfile.tmp"
|
||||
mock_tempfile.return_value = mock_file
|
||||
mock_move.side_effect = RuntimeError()
|
||||
mock_exists.return_value = False
|
||||
|
||||
# test
|
||||
try:
|
||||
@@ -147,16 +158,20 @@ class TestAtomicWrite(unittest.TestCase):
|
||||
mock_tempfile.assert_called_once_with(mode="w+b", prefix="tmp", suffix="", delete=False)
|
||||
mock_file.close.assert_called_once_with()
|
||||
self.assertTrue(mock_move.called)
|
||||
self.assertTrue(mock_chmod.called)
|
||||
|
||||
@mock.patch("shutil.move")
|
||||
@mock.patch("tempfile.NamedTemporaryFile")
|
||||
def test_atomic_write_parameters(self, mock_tempfile, mock_move):
|
||||
@mock.patch("os.chmod")
|
||||
@mock.patch("os.path.exists")
|
||||
def test_atomic_write_parameters(self, mock_exists, mock_chmod, mock_tempfile, mock_move):
|
||||
"""Tests that the open parameters are propagated properly."""
|
||||
|
||||
# setup
|
||||
mock_file = mock.MagicMock()
|
||||
mock_file.name = "tempfile.tmp"
|
||||
mock_tempfile.return_value = mock_file
|
||||
mock_exists.return_value = False
|
||||
|
||||
# test
|
||||
with octoprint.util.atomic_write("somefile.yaml", mode="w", prefix="foo", suffix="bar") as f:
|
||||
@@ -165,6 +180,87 @@ class TestAtomicWrite(unittest.TestCase):
|
||||
# assert
|
||||
mock_tempfile.assert_called_once_with(mode="w", prefix="foo", suffix="bar", delete=False)
|
||||
mock_file.close.assert_called_once_with()
|
||||
mock_chmod.assert_called_once_with("tempfile.tmp", 0o644)
|
||||
mock_move.assert_called_once_with("tempfile.tmp", "somefile.yaml")
|
||||
|
||||
|
||||
@mock.patch("shutil.move")
|
||||
@mock.patch("tempfile.NamedTemporaryFile")
|
||||
@mock.patch("os.chmod")
|
||||
@mock.patch("os.path.exists")
|
||||
def test_atomic_custom_permissions(self, mock_exists, mock_chmod, mock_tempfile, mock_move):
|
||||
"""Tests that custom permissions may be set."""
|
||||
|
||||
# setup
|
||||
mock_file = mock.MagicMock()
|
||||
mock_file.name = "tempfile.tmp"
|
||||
mock_tempfile.return_value = mock_file
|
||||
mock_exists.return_value = False
|
||||
|
||||
# test
|
||||
with octoprint.util.atomic_write("somefile.yaml", permissions=0o755) as f:
|
||||
f.write("test")
|
||||
|
||||
# assert
|
||||
mock_tempfile.assert_called_once_with(mode="w+b", prefix="tmp", suffix="", delete=False)
|
||||
mock_file.close.assert_called_once_with()
|
||||
mock_chmod.assert_called_once_with("tempfile.tmp", 0o755)
|
||||
mock_move.assert_called_once_with("tempfile.tmp", "somefile.yaml")
|
||||
|
||||
@mock.patch("shutil.move")
|
||||
@mock.patch("tempfile.NamedTemporaryFile")
|
||||
@mock.patch("os.chmod")
|
||||
@mock.patch("os.path.exists")
|
||||
@mock.patch("os.stat")
|
||||
def test_atomic_permissions_combined(self, mock_stat, mock_exists, mock_chmod, mock_tempfile, mock_move):
|
||||
"""Tests that the permissions of an existing file are combined with the requested permissions."""
|
||||
|
||||
# setup
|
||||
mock_file = mock.MagicMock()
|
||||
mock_file.name = "tempfile.tmp"
|
||||
mock_tempfile.return_value = mock_file
|
||||
mock_exists.return_value = True
|
||||
|
||||
mock_stat_result = mock.MagicMock()
|
||||
mock_stat_result.st_mode = 0o666
|
||||
mock_stat.return_value = mock_stat_result
|
||||
|
||||
# test
|
||||
with octoprint.util.atomic_write("somefile.yaml", permissions=0o755) as f:
|
||||
f.write("test")
|
||||
|
||||
# assert
|
||||
mock_tempfile.assert_called_once_with(mode="w+b", prefix="tmp", suffix="", delete=False)
|
||||
mock_file.close.assert_called_once_with()
|
||||
mock_chmod.assert_called_once_with("tempfile.tmp", 0o777) # 0o755 | 0o666
|
||||
mock_move.assert_called_once_with("tempfile.tmp", "somefile.yaml")
|
||||
|
||||
@mock.patch("shutil.move")
|
||||
@mock.patch("tempfile.NamedTemporaryFile")
|
||||
@mock.patch("os.chmod")
|
||||
@mock.patch("os.path.exists")
|
||||
@mock.patch("os.stat")
|
||||
def test_atomic_permissions_limited(self, mock_stat, mock_exists, mock_chmod, mock_tempfile, mock_move):
|
||||
"""Tests that max_permissions limit the combined file permissions."""
|
||||
|
||||
# setup
|
||||
mock_file = mock.MagicMock()
|
||||
mock_file.name = "tempfile.tmp"
|
||||
mock_tempfile.return_value = mock_file
|
||||
mock_exists.return_value = True
|
||||
|
||||
mock_stat_result = mock.MagicMock()
|
||||
mock_stat_result.st_mode = 0o755
|
||||
mock_stat.return_value = mock_stat_result
|
||||
|
||||
# test
|
||||
with octoprint.util.atomic_write("somefile.yaml", permissions=0o600, max_permissions=0o666) as f:
|
||||
f.write("test")
|
||||
|
||||
# assert
|
||||
mock_tempfile.assert_called_once_with(mode="w+b", prefix="tmp", suffix="", delete=False)
|
||||
mock_file.close.assert_called_once_with()
|
||||
mock_chmod.assert_called_once_with("tempfile.tmp", 0o644) # (0o600 | 0o755) & 0o666 = 0o755 & 0o666
|
||||
mock_move.assert_called_once_with("tempfile.tmp", "somefile.yaml")
|
||||
|
||||
|
||||
|
||||
Reference in new issue
Block a user