Merge branch 'devel' of github.com:foosel/OctoPrint into dev/permission
This commit is contained in:
commit
ed6bdf97d1
109 files changed
+6396
-2707
No files matched your search
+38
-10
@@ -1,8 +1,10 @@
|
||||
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.
|
||||
aka the Contribution Guidelines 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
|
||||
@@ -14,11 +16,18 @@ 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 :)
|
||||
to find some information - it's all described in the Contribution
|
||||
Guidelines linked up there in the big yellow box).
|
||||
|
||||
When reporting a bug 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 :)
|
||||
|
||||
Make sure any bug you want to report is still present with the CURRENT
|
||||
OctoPrint version and that it does not vanish when you start OctoPrint
|
||||
in safe mode - how to do that is also explained in the Contribution
|
||||
Guidelines linked up there in the big yellow box.
|
||||
|
||||
Thank you!
|
||||
|
||||
@@ -34,6 +43,12 @@ by heart ;))
|
||||
reproduce your issue in order to fix it and that is not possible if they
|
||||
don't know what you did to get it to happen in the first place.
|
||||
|
||||
Ideally provide exact steps to follow in order to reproduce your problem:
|
||||
|
||||
1. ...
|
||||
2. ...
|
||||
3. ...
|
||||
|
||||
If you encountered a problem with specific files of any sorts, make sure
|
||||
to also include a link to a file with which to reproduce the problem.]
|
||||
|
||||
@@ -41,10 +56,20 @@ to also include a link to a file with which to reproduce the problem.]
|
||||
|
||||
#### What happened instead?
|
||||
|
||||
#### Did the same happen when running OctoPrint in safe mode?
|
||||
|
||||
[Try to reproduce your problem in safe mode. You can find information
|
||||
on how to enable safe mode in the Contribution Guidelines.]
|
||||
|
||||
#### Branch & Commit or Version of OctoPrint
|
||||
|
||||
[Can be found in the lower left corner of the web interface. ALWAYS INCLUDE.]
|
||||
|
||||
#### Operating System running OctoPrint
|
||||
|
||||
[OctoPi, Linux, Windows, MacOS, something else? With version please.
|
||||
OctoPi's version can be found in /etc/octopi_version]
|
||||
|
||||
#### Printer model & used firmware incl. version
|
||||
|
||||
[If applicable, always include if unsure.]
|
||||
@@ -55,7 +80,8 @@ to also include a link to a file with which to reproduce the problem.]
|
||||
|
||||
#### Link to octoprint.log
|
||||
|
||||
[On gist.github.com or pastebin.com. ALWAYS INCLUDE and never truncate.]
|
||||
[On gist.github.com or pastebin.com. ALWAYS INCLUDE and never truncate.
|
||||
The Contribution Guidelines tell you where to find that.]
|
||||
|
||||
#### Link to contents of terminal tab or serial.log
|
||||
|
||||
@@ -70,9 +96,11 @@ a serial.log.]
|
||||
#### Link to contents of Javascript console in the browser
|
||||
|
||||
[On gist.github.com or pastebin.com or alternatively a screenshot. If applicable -
|
||||
always include if unsure or reporting UI issues.]
|
||||
always include if unsure or reporting UI issues.
|
||||
|
||||
#### Screenshot(s) showing the problem:
|
||||
The Contribution Guidelines tell you where to find that.]
|
||||
|
||||
#### Screenshot(s)/video(s) showing the problem:
|
||||
|
||||
[If applicable. Always include if unsure or reporting UI issues.]
|
||||
|
||||
|
||||
@@ -14,14 +14,15 @@ checklist:
|
||||
made sure your changes don't interfere with current development by
|
||||
talking it through with the maintainers, e.g. through a
|
||||
Brainstorming ticket
|
||||
* [ ] Your PR targets OctoPrint's devel branch (not master,
|
||||
maintenance or anything else)
|
||||
* [ ] Your PR targets OctoPrint's devel branch, or maintenance if it's
|
||||
a bug fix for an issue present in the current stable version (no PRs
|
||||
against master or anything else)
|
||||
* [ ] Your PR was opened from a custom branch on your repository
|
||||
(no PRs from your version of master, maintenance or devel please),
|
||||
e.g. dev/my_new_feature
|
||||
* [ ] Your PR only contains relevant changes: no unrelated files,
|
||||
no dead code, ideally only one commit - rebase your PR if necessary!
|
||||
* [ ] Your changes follow the coding style
|
||||
* [ ] Your changes follow the existing coding style
|
||||
* [ ] If your changes include style sheets: You have modified the
|
||||
.less source files, not the .css files (those are generated with
|
||||
lessc)
|
||||
|
||||
+4
-4
@@ -16,11 +16,11 @@ prerelease
|
||||
HEAD
|
||||
\(detached.*
|
||||
|
||||
# maintenance is currently the branch for preparation of maintenance release 1.3.2
|
||||
# maintenance is currently the branch for preparation of maintenance release 1.3.3
|
||||
# so are any fix/... and improve/... branches
|
||||
maintenance 1.3.2 6393de8c7d42a8bbddcab7cdbb6530ea88a8c82d pep440-dev
|
||||
fix/.* 1.3.2 6393de8c7d42a8bbddcab7cdbb6530ea88a8c82d pep440-dev
|
||||
improve/.* 1.3.2 6393de8c7d42a8bbddcab7cdbb6530ea88a8c82d pep440-dev
|
||||
maintenance 1.3.3 0a69dbeddb301d5a32827a3f0d561f875df24234 pep440-dev
|
||||
fix/.* 1.3.3 0a69dbeddb301d5a32827a3f0d561f875df24234 pep440-dev
|
||||
improve/.* 1.3.3 0a69dbeddb301d5a32827a3f0d561f875df24234 pep440-dev
|
||||
|
||||
# every other branch is a development branch and thus gets resolved to 1.4.0-dev for now
|
||||
.* 1.4.0 7f5d03d0549bcbd26f40e7e4a3297ea5204fb1cc pep440-dev
|
||||
@@ -78,6 +78,9 @@ date of first contribution):
|
||||
* [Noah Martin](https://github.com/noahsmartin)
|
||||
* [Eyal Soha](https://github.com/eyal0)
|
||||
* [Greg Hulands](https://github.com/ghulands)
|
||||
* [Andreas Werner](https://github.com/gallore)
|
||||
* [Shawn Bruce](https://github.com/kantlivelong)
|
||||
* [Claudiu Ceia] (https://github.com/ClaudiuCeia)
|
||||
|
||||
OctoPrint started off as a fork of [Cura](https://github.com/daid/Cura) by
|
||||
[Daid Braam](https://github.com/daid). Parts of its communication layer and
|
||||
|
||||
@@ -1,9 +1,94 @@
|
||||
# OctoPrint Changelog
|
||||
|
||||
## 1.3.2 (2017-03-16)
|
||||
|
||||
### Note for plugin authors
|
||||
|
||||
**If you maintain a plugin that extends OctoPrint's [JavaScript Client Library](http://docs.octoprint.org/en/master/jsclientlib/index.html)** like demonstrated in e.g. the bundled Software Update Plugin you'll need to update the way you register your plugin to depend on `OctoPrintClient` and registering your extension as shown [here](https://github.com/foosel/OctoPrint/blob/6e793c2/src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js#L1-L84) instead of directly writing to `OctoPrint.plugins` (like it was still done [here](https://github.com/foosel/OctoPrint/blob/23744cd/src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js#L1-L81)). That way your extensions will be available on all instances of `OctoPrintClient`, not just the global instance `OctoPrint` that gets created on startup of the core web interface.
|
||||
|
||||
If all you plugin does with regards to JavaScript is registering a custom view model and you have no idea what I'm talking about regarding extending the client library, no action is necessary. This heads-up is really only relevant if you extended the JavaScript Client Library.
|
||||
|
||||
### Improvements
|
||||
|
||||
- [#732](https://github.com/foosel/OctoPrint/pull/732) - Have OctoPrint's `python setup.py clean` build on stock
|
||||
`python setup.py clean` for better compatibility with packaging systems
|
||||
- [#1506](https://github.com/foosel/OctoPrint/issues/1506) - Better handle really long "dwell"/`G4` commands on Repetier firmware (as for example apparently recommended to use with Wanhao D6 and similar printers for nozzle cooling) by actively stalling communication from OctoPrint's side as well. That way we no longer run into a communication timeout produced by a 5min dwell immediately happily acknowledged by the printer with an `ok`.
|
||||
- [#1542](https://github.com/foosel/OctoPrint/issues/1542) - Support for multi-extruder setups with a shared single nozzle and heater (e.g. E3D Cyclops, Diamond hotend, etc).
|
||||
- [#1676](https://github.com/foosel/OctoPrint/issues/1676) - Trigger line number reset when connected to printer and seeing `start` message. This should fix issues with printer communication when printer resets but reset goes otherwise undetected.
|
||||
- [#1681](https://github.com/foosel/OctoPrint/issues/1681) - Support for connecting to multiple OctoPrint instances via the [JavaScript Client Library](http://docs.octoprint.org/en/master/jsclientlib/index.html).
|
||||
- [#1712](https://github.com/foosel/OctoPrint/issues/1712) - Display current folder name in file list if in sub folder.
|
||||
- [#1723](https://github.com/foosel/OctoPrint/issues/1723) - Ignore leading `v` or `V` on plugin version numbers for version checks in plugin manager and software updater (see also [#1724](https://github.com/foosel/OctoPrint/pull/1724))
|
||||
- [#1770](https://github.com/foosel/OctoPrint/issues/1770) - Better resilience against null bytes received from the printer for whatever reason.
|
||||
- [#1770](https://github.com/foosel/OctoPrint/issues/1770) - Detect printer as connected even when only receiving a `wait` instead of `ok`. Should solve issues with initial connect where printer sends garbage over the line that eats/covers the `ok` if printer also sends regular `wait` messages when idle.
|
||||
- [#1780](https://github.com/foosel/OctoPrint/issues/1780) - Work around for Safari re-opening one copy of the webcam stream after the other and eating up bandwidth unnecessarily (see also [#1786](https://github.com/foosel/OctoPrint/issues/1786))
|
||||
- [#1790](https://github.com/foosel/OctoPrint/issues/1790) - Removed unused "color" property from printer profile editor.
|
||||
- [#1805](https://github.com/foosel/OctoPrint/issues/1805) - Better error resilience against invalid print history data from plugins that replace the printer communication.
|
||||
- Better error resilience in Plugin Manager against wonky version data in repository file.
|
||||
- Added a "Restart in safe mode" system menu entry that will always be available if the restart command is configured
|
||||
- CLI: Only offer `daemon` sub command on Linux (since that it's the only OS it works on)
|
||||
- Less throttling of analysis of GCODE files from the analysis backlog. Should still leave Pi and friends air to breathe but allow a slightly faster processing of the backlog.
|
||||
- Added an explanation of safe mode to the docs.
|
||||
- Log OctoPrint version & plugin list when detecting log rollover.
|
||||
- Allow `UiPlugin`s to define additional fields for ETag generation.
|
||||
- Allow `UiPlugin`s utilizing OctoPrint's stock templates to filter out what they don't need.
|
||||
- Locales contained in `translations` of plugins will now be registered with the system. That way it's possible to provide translations for the full application through plugins.
|
||||
- Abort file analysis if file is about to be overwritten
|
||||
- Software Update Plugin: Refresh cache on startup, prevent concurrent refresh
|
||||
- More solid parsing of request line number for resend requests. Should improve compatibility with Teacup firmwares. Based on issue reported via PR [#300](https://github.com/foosel/OctoPrint/pull/300)
|
||||
|
||||
### Bug fixes
|
||||
|
||||
- [#733](https://github.com/foosel/OctoPrint/issues/733) - Fixed multiple event handler commands running concurrently. Now they run one after the other, as expected.
|
||||
- [#1317](https://github.com/foosel/OctoPrint/issues/1317) - Fixed a color distortion issue when rendering timelapses from higher resolution source snapshots that also need to be rotated by adjusting `ffmpeg` parameters to avoid an unexpected behaviour when a pixel format and a filter chain are required for processing.
|
||||
- [#1560](https://github.com/foosel/OctoPrint/issues/1560) - Make sure we don't try to use an empty `logging.yaml`
|
||||
- [#1631](https://github.com/foosel/OctoPrint/issues/1631) - Disable "Slice" button in slice dialog if a print is ongoing and a slicer is selected that runs on the same device as OctoPrint. The server would already deny such requests (simply due to performance reasons), but the UI didn't properly reflect that yet.
|
||||
- [#1671](https://github.com/foosel/OctoPrint/issues/1671) - Removed "Hide empty folders" option from file list. Didn't really add value and caused usability issues.
|
||||
- [#1771](https://github.com/foosel/OctoPrint/issues/1771) - Fixed `_config_version` in plugin settings not being properly updated.
|
||||
- [#1732](https://github.com/foosel/OctoPrint/issues/1732) - Fixed a bug in the documentation for the printer profile API
|
||||
- [#1760](https://github.com/foosel/OctoPrint/issues/1760) - Fixed missing reselect of selected file when updating via the watched folder, causing wrong progress percentages to be reported.
|
||||
- [#1765](https://github.com/foosel/OctoPrint/issues/1765) - Fixed watched folder not waiting with file move until file stopped growing, causing wrong progress percentages to be reported.
|
||||
- [#1777](https://github.com/foosel/OctoPrint/issues/1777) - Fixed z-change based timelapses with Slic3r generated z-hops not properly triggering snapshots.
|
||||
- [#1792](https://github.com/foosel/OctoPrint/issues/1792) - Don't tell Safari we are "web-app-capable" because that means it will throw away all cookies and the user will have to constantly log in again when using a desktop shortcut for the OctoPrint instance.
|
||||
- [#1812](https://github.com/foosel/OctoPrint/issues/1812) - Don't scroll up navigation in settings when switching between settings screens, very annoying on smaller resolutions (see also [#1814](https://github.com/foosel/OctoPrint/pull/1814))
|
||||
- Fix settings helper not allowing to delete values for keys that are present in the local config but not in the defaults.
|
||||
- Fix wrong replacement value for `__progress` in registered command line or GCODE [event handlers](http://docs.octoprint.org/en/master/events/index.html).
|
||||
- Various fixes in the Software Update Plugin:
|
||||
- Don't remove manual software update configurations on settings migration.
|
||||
- Properly delete old restart/reboot commands that are now defined globally since config version 4. An issue with the settings helper prevented us from properly deleting them during migration to version 4.
|
||||
- Fixed `python_checker` version check method and `python_updater` update method.
|
||||
- Fixed update configs without a restart of any kind causing an issue due to an undefined variable.
|
||||
- Fixed broken doctests.
|
||||
- Upgrade LESS.min.js from 2.7.1 to 2.7.2 to fix the broken contrast function
|
||||
- Always create a new user session for requests with an API key
|
||||
- Fixed an error when reading all user settings via the API
|
||||
- Fixed a bunch of caching issues for the page, was not properly updated on change of snapshot URL presence, system menu entry presence, gcode viewer enabled/disabled, changes in access control availability.
|
||||
- Fixed wrong bundling of core and plugin assets
|
||||
- Software Update Plugin: Fixed wrong ETag calculation
|
||||
- Disable external heatup detection until firmware is detected
|
||||
- Fixed login dropdown not closing on click outside of it
|
||||
- Fixed new user settings getting lost until restart
|
||||
- Don't call `onUserLoggedIn`/`onUserLoggedOut` on user reload
|
||||
|
||||
### More information
|
||||
|
||||
- [Commits](https://github.com/foosel/OctoPrint/compare/1.3.1...1.3.2)
|
||||
- Release Candidates:
|
||||
- [1.3.2rc1](https://github.com/foosel/OctoPrint/releases/tag/1.3.2rc1)
|
||||
|
||||
## 1.3.1 (2017-01-25)
|
||||
|
||||
### Note for upgraders
|
||||
|
||||
#### If you installed OctoPrint manually and used the included init script, you need to update that
|
||||
|
||||
The init script so far shipped with OctoPrint contained a [bug](https://github.com/foosel/OctoPrint/issues/1657) that causes issues with OctoPrint 1.3.0 and higher. Please update your init script to the fixed version OctoPrint now ships under `scripts`:
|
||||
|
||||
```
|
||||
sudo cp /path/to/OctoPrint/scripts/octoprint.init /etc/init.d/octoprint
|
||||
```
|
||||
|
||||
If you are running OctoPi, this does **not** apply to you and you do not need to do anything here!
|
||||
|
||||
#### Change in stock terminal filter configuration
|
||||
|
||||
1.3.1 fixes an issue with the two terminal filters for suppressing temperature and SD status messages and adds a new filter for filtering out firmware `wait` messages. These changes will only be active automatically though for stock terminal filter configurations. If you have customized your terminal filters, you'll need to apply these changes manually under "Settings > Terminal filters":
|
||||
@@ -23,6 +108,7 @@
|
||||
- New "Suppress wait responses" filter: `Recv: wait`
|
||||
|
||||
### Bug fixes
|
||||
|
||||
- [#1344](https://github.com/foosel/OctoPrint/issues/1344) - Fix ProgressBarPlugins to not correctly be triggered for 0% (second try, this time hopefully for good).
|
||||
- [#1637](https://github.com/foosel/OctoPrint/issues/1637) - Fix issue preventing a folder to be deleted that has a name which is a common prefix of the file currently being printed.
|
||||
- [#1641](https://github.com/foosel/OctoPrint/issues/1641) - Fix issue with `octoprint --daemon` not working.
|
||||
|
||||
+54
-25
@@ -93,11 +93,15 @@ following section *completely* and also follow the instructions in the
|
||||
|
||||
2. Please make sure to **test out the current version** of OctoPrint to see
|
||||
whether the problem you are encountering still exists, and **test without
|
||||
any non-bundled plugins enabled** to make sure it's not a misbehaving
|
||||
plugin causing the issue at hand.
|
||||
any third-party plugins enabled** to make sure it's not a misbehaving
|
||||
plugin causing the issue at hand. For that please restart OctoPrint in
|
||||
**safe mode**, either by selecting "Restart OctoPrint in safe mode" from
|
||||
the "System" menu, or by starting OctoPrint from the command line with
|
||||
`octoprint serve --safe`. Then try to reproduce your issue. Find out
|
||||
more about safe mode in the [docs](http://docs.octoprint.org/en/master/features/safemode.html).
|
||||
|
||||
If you are feeling up to it you might also want to try the current development
|
||||
version of OctoPrint (if you aren't already). Refer to the [FAQ](https://github.com/foosel/OctoPrint/wiki/FAQ)
|
||||
You might also want to try the current development version of OctoPrint
|
||||
(if you aren't already). Refer to the [FAQ](https://github.com/foosel/OctoPrint/wiki/FAQ)
|
||||
for information on how to do this.
|
||||
|
||||
3. The problem still exists? Then please **look through the
|
||||
@@ -138,6 +142,12 @@ only provided here as some additional information for you), **even if only addin
|
||||
reproduce your issue in order to fix it and that is not possible if they
|
||||
don't know what you did to get it to happen in the first place.
|
||||
|
||||
Ideally provide exact steps to follow in order to reproduce your problem:
|
||||
|
||||
1. ...
|
||||
2. ...
|
||||
3. ...
|
||||
|
||||
If you encountered a problem with specific files of any sorts, make sure
|
||||
to also include a link to a file with which to reproduce the problem.]
|
||||
|
||||
@@ -145,10 +155,20 @@ only provided here as some additional information for you), **even if only addin
|
||||
|
||||
#### What happened instead?
|
||||
|
||||
#### Did the same happen when running OctoPrint in safe mode?
|
||||
|
||||
[Try to reproduce your problem in safe mode. You can find information
|
||||
on how to enable safe mode in the Contribution Guidelines.]
|
||||
|
||||
#### Branch & Commit or Version of OctoPrint
|
||||
|
||||
[Can be found in the lower left corner of the web interface. ALWAYS INCLUDE.]
|
||||
|
||||
#### Operating System running OctoPrint
|
||||
|
||||
[OctoPi, Linux, Windows, MacOS, something else? With version please,
|
||||
OctoPi's version can be found in /etc/octopi_version]
|
||||
|
||||
#### Printer model & used firmware incl. version
|
||||
|
||||
[If applicable, always include if unsure.]
|
||||
@@ -159,7 +179,8 @@ only provided here as some additional information for you), **even if only addin
|
||||
|
||||
#### Link to octoprint.log
|
||||
|
||||
[On gist.github.com or pastebin.com. ALWAYS INCLUDE and never truncate.]
|
||||
[On gist.github.com or pastebin.com. ALWAYS INCLUDE and never truncate.
|
||||
The Contribution Guidelines tell you where to find that.]
|
||||
|
||||
#### Link to contents of terminal tab or serial.log
|
||||
|
||||
@@ -174,16 +195,19 @@ only provided here as some additional information for you), **even if only addin
|
||||
#### Link to contents of Javascript console in the browser
|
||||
|
||||
[On gist.github.com or pastebin.com or alternatively a screenshot. If applicable -
|
||||
always include if unsure or reporting UI issues.]
|
||||
always include if unsure or reporting UI issues.
|
||||
|
||||
#### Screenshot(s) showing the problem:
|
||||
The Contribution Guidelines tell you where to find that.]
|
||||
|
||||
#### Screenshot(s)/video(s) showing the problem:
|
||||
|
||||
[If applicable. Always include if unsure or reporting UI issues.]
|
||||
|
||||
I have read the FAQ.
|
||||
|
||||
Copy-paste this template **completely**. Do not skip any lines or the bot
|
||||
*will* complain!
|
||||
Copy-paste this template **completely** (or use the version that gets pre-filled
|
||||
into the "new issue" form). Do not skip any lines or the bot *will* complain! Provide
|
||||
all requested information or your ticket will be closed.
|
||||
|
||||
### Where can I find which version and branch I'm on?
|
||||
|
||||
@@ -258,17 +282,18 @@ See [the corresponding chapter in the documentation](http://docs.octoprint.org/e
|
||||
just cause unnecessary work and frustration for everyone or
|
||||
possibly get the PR rejected.
|
||||
3. Create your pull request **from a custom branch** on your end (e.g.
|
||||
`dev/myNewFeature`)[1] **against the `devel` branch**. Create **one pull request
|
||||
per feature/bug fix**. If your PR contains an important bug fix, we will
|
||||
make sure to backport it to the `maintenance` branch to also include it in
|
||||
the next release.
|
||||
4. Make sure there are **only relevant changes** included in your PR. No
|
||||
`dev/myNewFeature`)[1].
|
||||
4. Create your pull request **only against the `maintenance` or `devel` branch**:
|
||||
* if it's a bug fix for a bug in the current stable version: `maintenance` branch
|
||||
* otherwise: `devel` branch
|
||||
5. Create **one pull request per feature/bug fix**.
|
||||
6. Make sure there are **only relevant changes** included in your PR. No
|
||||
changes to unrelated files, no additional files that don't belong (e.g.
|
||||
commits of your full virtual environment). Make sure your PR consists
|
||||
**ideally of only one commit** (use git's rebase and squash functionality).
|
||||
5. Make sure you **follow the current coding style**. This means:
|
||||
7. Make sure you **follow the current coding style**. This means:
|
||||
* Tabs instead of spaces in the Python files[2]
|
||||
* Spaces instead of tabs in the Javascript sources
|
||||
* Spaces instead of tabs in the JavaScript sources
|
||||
* English language (code, variables, comments, ...)
|
||||
* Comments where necessary: Tell *why* the code does something like it does
|
||||
it, structure your code
|
||||
@@ -277,22 +302,22 @@ See [the corresponding chapter in the documentation](http://docs.octoprint.org/e
|
||||
``.less`` files from which the CSS is compiled.
|
||||
* Make sure you do not add dead code (e.g. commented out left-overs
|
||||
from experiments).
|
||||
6. Ensure your changes **pass the existing unit tests**. PRs that break
|
||||
8. Ensure your changes **pass the existing unit tests**. PRs that break
|
||||
those cannot be accepted.
|
||||
7. **Test your changes thoroughly**. That also means testing with usage
|
||||
9. **Test your changes thoroughly**. That also means testing with usage
|
||||
scenarios you don't normally use, e.g. if you only use access control, test
|
||||
without and vice versa. If you only test with your printer, test with the
|
||||
virtual printer and vice versa. State in your pull request how you tested
|
||||
your changes. Ideally **add unit tests** - OctoPrint severely lacks in that
|
||||
department, but we are trying to change that, so any new code already covered
|
||||
with a test suite helps a lot!
|
||||
8. In your pull request's description, **state what your pull request does**,
|
||||
as in, what feature does it implement, what bug does it fix. The more
|
||||
thoroughly you explain your intent behind the PR here, the higher the
|
||||
chances it will get merged fast. There is a template provided below
|
||||
that can help you here.
|
||||
9. Don't forget to **add yourself to the [AUTHORS](./AUTHORS.md)
|
||||
file** :)
|
||||
10. In your pull request's description, **state what your pull request does**,
|
||||
as in, what feature does it implement, what bug does it fix. The more
|
||||
thoroughly you explain your intent behind the PR here, the higher the
|
||||
chances it will get merged fast. There is a template provided below
|
||||
that can help you here.
|
||||
11. Don't forget to **add yourself to the [AUTHORS](./AUTHORS.md)
|
||||
file** :)
|
||||
|
||||
Template to use for Pull Request descriptions:
|
||||
|
||||
@@ -397,6 +422,10 @@ the local version identifier to allow for an exact determination of the active c
|
||||
* 2016-09-23: Some more work on "How to file a bug report" based on recent
|
||||
experiences
|
||||
* 2017-01-25: Fixed a typo
|
||||
* 2017-03-09: Allow PRs against `maintenance` branch for bugs in stable.
|
||||
* 2017-03-10: Reproduce bugs in safe mode to make sure they are really caused
|
||||
by OctoPrint itself and not a misbehaving plugin.
|
||||
* 2017-03-27: Added safe mode section to ticket template.
|
||||
|
||||
## Footnotes
|
||||
* [1] - If you are wondering why, the problem is that anything that you add
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
# OctoPrint
|
||||
|
||||
OctoPrint provides a snappy web interface for controlling a 3D printer (RepRap, Ultimaker, ...). It is Free Software
|
||||
[](https://badge.fury.io/gh/foosel%2FOctoPrint)
|
||||
|
||||
OctoPrint provides a snappy web interface for controlling consumer 3D printers. It is Free Software
|
||||
and released under the [GNU Affero General Public License V3](http://www.gnu.org/licenses/agpl.html).
|
||||
|
||||
Its website can be found at [octoprint.org](http://octoprint.org).
|
||||
@@ -33,7 +35,7 @@ If you think something is bad about OctoPrint or its documentation the way it is
|
||||
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
|
||||
For information about how to go about submitting bug reports or pull requests, please see the project's
|
||||
[Contribution Guidelines](https://github.com/foosel/OctoPrint/blob/master/CONTRIBUTING.md).
|
||||
|
||||
## Installation
|
||||
@@ -41,7 +43,7 @@ For information about how to go about contributions of any kind, please see the
|
||||
Installation instructions for installing from source for different operating
|
||||
systems can be found [on the wiki](https://github.com/foosel/OctoPrint/wiki#assorted-guides).
|
||||
|
||||
If you want to run OctoPrint on a Raspberry Pi you might want to take a look at [OctoPi](https://github.com/guysoft/OctoPi)
|
||||
If you want to run OctoPrint on a Raspberry Pi, you might want to take a look at [OctoPi](https://github.com/guysoft/OctoPi)
|
||||
which is a custom SD card image that includes OctoPrint plus dependencies.
|
||||
|
||||
The generic steps that should basically be done regardless of operating system
|
||||
@@ -59,7 +61,7 @@ for details.
|
||||
|
||||
After installation, please make sure you follow the first-run wizard and set up
|
||||
access control as necessary. If you want to not only be notified about new
|
||||
releases but also be able to automatically upgrade to them from within
|
||||
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.
|
||||
|
||||
@@ -70,7 +72,7 @@ OctoPrint via `setup.py`:
|
||||
|
||||
python setup.py install
|
||||
|
||||
You should also do this every time after pulling from the repository, since the dependencies might have changed.
|
||||
You should do this every time after pulling from the repository, since the dependencies may have changed.
|
||||
|
||||
OctoPrint currently only supports Python 2.7.
|
||||
|
||||
@@ -81,8 +83,8 @@ Running the `setup.py` script via
|
||||
python setup.py install
|
||||
|
||||
installs the `octoprint` script in your Python installation's scripts folder
|
||||
(which depending on whether you installed OctoPrint globally or into a virtual env will be on your `PATH` or not). The
|
||||
following usage examples assume that said `octoprint` script is on your `PATH`.
|
||||
(which, depending on whether you installed OctoPrint globally or into a virtual env, will be in your `PATH` or not). The
|
||||
following usage examples assume that the `octoprint` script is on your `PATH`.
|
||||
|
||||
You can start the server via
|
||||
|
||||
@@ -95,7 +97,7 @@ to only listen on the local interface on port 8080, the command line would be
|
||||
|
||||
octoprint serve --host=127.0.0.1 --port=8080
|
||||
|
||||
Alternatively, the host and port on which to bind can be defined via the configuration.
|
||||
Alternatively, the host and port on which to bind can be defined via the config file.
|
||||
|
||||
If you want to run OctoPrint as a daemon (only supported on Linux), use
|
||||
|
||||
@@ -103,19 +105,24 @@ If you want to run OctoPrint as a daemon (only supported on Linux), use
|
||||
|
||||
If you do not supply a custom pidfile location via `--pid PIDFILE`, it will be created at `/tmp/octoprint.pid`.
|
||||
|
||||
You can also specify the configfile or the base directory (for basing off the `uploads`, `timelapse` and `logs` folders),
|
||||
You can also specify the config file or the base directory (for basing off the `uploads`, `timelapse` and `logs` folders),
|
||||
e.g.:
|
||||
|
||||
octoprint serve --config /path/to/another/config.yaml --basedir /path/to/my/basedir
|
||||
|
||||
See `octoprint --help` for further information.
|
||||
To start OctoPrint in safe mode - which disables all third party plugins that do not come bundled with OctoPrint - use
|
||||
the ``--safe`` flag:
|
||||
|
||||
OctoPrint also ships with a `run` script in its source directory. You can also invoke that to start up the server, it
|
||||
octoprint serve --safe
|
||||
|
||||
See `octoprint --help` for more information on the available command line parameters.
|
||||
|
||||
OctoPrint also ships with a `run` script in its source directory. You can invoke it to start the server. It
|
||||
takes the same command line arguments as the `octoprint` script.
|
||||
|
||||
## Configuration
|
||||
|
||||
If not specified via the commandline, the configfile `config.yaml` for OctoPrint is expected in the settings folder,
|
||||
If not specified via the command line, the config file `config.yaml` for OctoPrint is expected in the settings folder,
|
||||
which is located at `~/.octoprint` on Linux, at `%APPDATA%/OctoPrint` on Windows and
|
||||
at `~/Library/Application Support/OctoPrint` on MacOS.
|
||||
|
||||
|
||||
+5
-6
@@ -10,14 +10,12 @@ thanks to everyone who contributed!
|
||||
* Aleph Objects, Inc.
|
||||
* Andrew Moorby
|
||||
* Arnljot Arntsen
|
||||
* Aurelio Bernal
|
||||
* Boris Hussein
|
||||
* Brad Jackson
|
||||
* Brent Fiegle
|
||||
* Brian E. Tyler
|
||||
* Christopher Day
|
||||
* Christian Petropolis
|
||||
* COLLE+McVOY
|
||||
* CreativeTools
|
||||
* D Brian Kimmel
|
||||
* DeltaMaker 3D Printers
|
||||
@@ -29,10 +27,11 @@ thanks to everyone who contributed!
|
||||
* Gary Deen
|
||||
* Gary N McKinney
|
||||
* George Robles
|
||||
* J. Eckert
|
||||
* James Seigel
|
||||
* Jamie R McGuigan
|
||||
* Jamie van Dyke
|
||||
* Jeff Moe
|
||||
* Josh Daniels
|
||||
* Joshua David Gregory
|
||||
* Kaile Riser
|
||||
* Kale Stedman
|
||||
* Kazuhiro Ogura
|
||||
@@ -44,6 +43,7 @@ thanks to everyone who contributed!
|
||||
* Masayoshi Mitsui
|
||||
* Michael Aumock
|
||||
* Miles Flavel
|
||||
* Mohammed khorakiwala
|
||||
* Noe Ruiz
|
||||
* Patrick McGinnis
|
||||
* Peter Grace
|
||||
@@ -58,11 +58,10 @@ thanks to everyone who contributed!
|
||||
* Simon Hallam
|
||||
* Stefan Krister
|
||||
* Stephane Schittly
|
||||
* Steven Pearson
|
||||
* Sven Mueller
|
||||
* Terrance Shaw
|
||||
* Thomas Hatley
|
||||
* Timeshell.ca
|
||||
* Trent Shumay
|
||||
|
||||
and 1016 more wonderful people pledging on the [Patreon campaign](https://patreon.com/foosel)!
|
||||
and 1041 more wonderful people pledging on the [Patreon campaign](https://patreon.com/foosel)!
|
||||
+113
-76
@@ -34,90 +34,92 @@ Retrieve all printer profiles
|
||||
HTTP/1.1 200 OK
|
||||
Content-Type: application/json
|
||||
|
||||
[
|
||||
{
|
||||
"id": "_default",
|
||||
"name": "Default",
|
||||
"color": "default",
|
||||
"model": "Generic RepRap Printer",
|
||||
"default": true,
|
||||
"current": true,
|
||||
"resource": "http://example.com/api/printerprofiles/_default",
|
||||
"volume": {
|
||||
"formFactor": "rectangular",
|
||||
"origin": "lowerleft",
|
||||
"width": 200,
|
||||
"depth": 200,
|
||||
"height": 200
|
||||
},
|
||||
"heatedBed": true,
|
||||
"axes": {
|
||||
"x": {
|
||||
"speed": 6000,
|
||||
"inverted": false
|
||||
{
|
||||
"profiles": [
|
||||
{
|
||||
"id": "_default",
|
||||
"name": "Default",
|
||||
"color": "default",
|
||||
"model": "Generic RepRap Printer",
|
||||
"default": true,
|
||||
"current": true,
|
||||
"resource": "http://example.com/api/printerprofiles/_default",
|
||||
"volume": {
|
||||
"formFactor": "rectangular",
|
||||
"origin": "lowerleft",
|
||||
"width": 200,
|
||||
"depth": 200,
|
||||
"height": 200
|
||||
},
|
||||
"y": {
|
||||
"speed": 6000,
|
||||
"inverted": false
|
||||
"heatedBed": true,
|
||||
"axes": {
|
||||
"x": {
|
||||
"speed": 6000,
|
||||
"inverted": false
|
||||
},
|
||||
"y": {
|
||||
"speed": 6000,
|
||||
"inverted": false
|
||||
},
|
||||
"z": {
|
||||
"speed": 200,
|
||||
"inverted": false
|
||||
},
|
||||
"e": {
|
||||
"speed": 300,
|
||||
"inverted": false
|
||||
}
|
||||
},
|
||||
"z": {
|
||||
"speed": 200,
|
||||
"inverted": false
|
||||
},
|
||||
"e": {
|
||||
"speed": 300,
|
||||
"inverted": false
|
||||
"extruder": {
|
||||
"count": 1,
|
||||
"offsets": [
|
||||
{"x": 0.0, "y": 0.0}
|
||||
]
|
||||
}
|
||||
},
|
||||
"extruder": {
|
||||
"count": 1,
|
||||
"offsets": [
|
||||
{"x": 0.0, "y": 0.0}
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "my_profile",
|
||||
"name": "My Profile",
|
||||
"color": "default",
|
||||
"model": "My Custom Printer",
|
||||
"default": false,
|
||||
"current": false,
|
||||
"resource": "http://example.com/api/printerprofiles/my_profile",
|
||||
"volume": {
|
||||
"formFactor": "rectangular",
|
||||
"origin": "lowerleft",
|
||||
"width": 200,
|
||||
"depth": 200,
|
||||
"height": 200
|
||||
},
|
||||
"heatedBed": true,
|
||||
"axes": {
|
||||
"x": {
|
||||
"speed": 6000,
|
||||
"inverted": false
|
||||
{
|
||||
"id": "my_profile",
|
||||
"name": "My Profile",
|
||||
"color": "default",
|
||||
"model": "My Custom Printer",
|
||||
"default": false,
|
||||
"current": false,
|
||||
"resource": "http://example.com/api/printerprofiles/my_profile",
|
||||
"volume": {
|
||||
"formFactor": "rectangular",
|
||||
"origin": "lowerleft",
|
||||
"width": 200,
|
||||
"depth": 200,
|
||||
"height": 200
|
||||
},
|
||||
"y": {
|
||||
"speed": 6000,
|
||||
"inverted": false
|
||||
"heatedBed": true,
|
||||
"axes": {
|
||||
"x": {
|
||||
"speed": 6000,
|
||||
"inverted": false
|
||||
},
|
||||
"y": {
|
||||
"speed": 6000,
|
||||
"inverted": false
|
||||
},
|
||||
"z": {
|
||||
"speed": 200,
|
||||
"inverted": false
|
||||
},
|
||||
"e": {
|
||||
"speed": 300,
|
||||
"inverted": false
|
||||
}
|
||||
},
|
||||
"z": {
|
||||
"speed": 200,
|
||||
"inverted": false
|
||||
},
|
||||
"e": {
|
||||
"speed": 300,
|
||||
"inverted": false
|
||||
"extruder": {
|
||||
"count": 1,
|
||||
"offsets": [
|
||||
{"x": 0.0, "y": 0.0}
|
||||
]
|
||||
}
|
||||
},
|
||||
"extruder": {
|
||||
"count": 1,
|
||||
"offsets": [
|
||||
{"x": 0.0, "y": 0.0}
|
||||
]
|
||||
}
|
||||
},
|
||||
]
|
||||
]
|
||||
}
|
||||
|
||||
|
||||
.. _sec-api-printerprofiles-add:
|
||||
@@ -537,6 +539,41 @@ Profile
|
||||
- 0..1
|
||||
- ``float``
|
||||
- The height of the print volume
|
||||
* - ``volume.custom_box``
|
||||
- 0..1
|
||||
- ``boolean`` or ``object``
|
||||
- If the printer has a custom bounding box where the print head can be safely moved to, exceeding the defined print
|
||||
volume, that bounding box will be defined here. Otherwise (safe area == print volume) this value will be ``false``.
|
||||
* - ``volume.custom_box.min_x``
|
||||
- 0..1
|
||||
- ``float``
|
||||
- Minimum X coordinate defining the safe custom bounding box. Smaller value than the minimum X coordinate of the
|
||||
print volume.
|
||||
* - ``volume.custom_box.max_x``
|
||||
- 0..1
|
||||
- ``float``
|
||||
- Maximum X coordinate defining the safe custom bounding box. Larger value than the maximum X coordinate of the
|
||||
print volume.
|
||||
* - ``volume.custom_box.min_y``
|
||||
- 0..1
|
||||
- ``float``
|
||||
- Minimum Y coordinate defining the safe custom bounding box. Smaller value than the minimum Y coordinate of the
|
||||
print volume.
|
||||
* - ``volume.custom_box.max_y``
|
||||
- 0..1
|
||||
- ``float``
|
||||
- Maximum Y coordinate defining the safe custom bounding box. Larger value than the maximum Y coordinate of the
|
||||
print volume.
|
||||
* - ``volume.custom_box.min_z``
|
||||
- 0..1
|
||||
- ``float``
|
||||
- Minimum Z coordinate defining the safe custom bounding box. Smaller value than the minimum Z coordinate of the
|
||||
print volume.
|
||||
* - ``volume.custom_box.max_z``
|
||||
- 0..1
|
||||
- ``float``
|
||||
- Maximum Z coordinate defining the safe custom bounding box. Larger value than the maximum Z coordinate of the
|
||||
print volume.
|
||||
* - ``heatedBed``
|
||||
- 0..1
|
||||
- ``boolean``
|
||||
|
||||
@@ -68,6 +68,23 @@ Save settings
|
||||
// ...
|
||||
}
|
||||
|
||||
.. _sec-api-settings-generateapikey:
|
||||
|
||||
Regenerate the system wide API key
|
||||
==================================
|
||||
|
||||
.. http:post:: /api/settings/apikey
|
||||
|
||||
Generates a new system wide API key.
|
||||
|
||||
Does not expect a body. Will return the generated API key as ``apikey``
|
||||
property in the JSON object contained in the response body.
|
||||
|
||||
Requires admin rights.
|
||||
|
||||
:status 200: No error
|
||||
:status 403: No admin rights
|
||||
|
||||
.. _sec-api-settings-datamodel:
|
||||
|
||||
Data model
|
||||
@@ -87,6 +104,9 @@ mapped from the same fields in ``config.yaml`` unless otherwise noted:
|
||||
-
|
||||
* - ``api.key``
|
||||
- Only maps to ``api.key`` in ``config.yaml`` if request is sent with admin rights, set to ``n/a`` otherwise.
|
||||
Starting with OctoPrint 1.3.3 setting this field via :ref:`the API <sec-api-settings-save>` is not possible,
|
||||
only :ref:`regenerting it <sec-api-settings-generateapikey>` is supported. Setting a custom value is only
|
||||
possible through `config.yaml`.
|
||||
* - ``api.allowCrossOrigin``
|
||||
-
|
||||
* - ``appearance.name``
|
||||
|
||||
@@ -43,6 +43,13 @@ Installing pybonjour
|
||||
OctoPi versions 0.12.0 and later already come with pybonjour installed and ready to go,
|
||||
you don't need to perform these steps there.
|
||||
|
||||
.. note::
|
||||
|
||||
Currently there are no releases for pybonjour available on the Python Package Index PyPI. The latest pybonjour
|
||||
release is still available in the `Google Code Archive <https://storage.googleapis.com/google-code-archive-downloads/v2/code.google.com/pybonjour/pybonjour-1.1.1.tar.gz>`_.
|
||||
Since that URL is hilariously long though, a shortened version is provided with https://goo.gl/SxQZ06 and
|
||||
used in the installation instructions below.
|
||||
|
||||
In order for the Zeroconf discovery to work, the
|
||||
`pybonjour package <https://pypi.python.org/pypi/pybonjour>`_ needs to be available
|
||||
to the Python installation running OctoPrint.
|
||||
@@ -52,7 +59,7 @@ into some folder ``~/OctoPrint``. You executed ``python setup.py install`` withi
|
||||
virtualenv in the same folder called ``venv``. In order to install ``pybonjour``
|
||||
so it will be available to OctoPrint you'll need to do the following::
|
||||
|
||||
venv/bin/pip install pybonjour
|
||||
venv/bin/pip install https://goo.gl/SxQZ06
|
||||
|
||||
**Linux users:** You'll need to install an additional dependency for this to work, the
|
||||
libdnssd compatibility layer for libavahi. On Debian/Ubuntu that can be achieved with::
|
||||
@@ -71,7 +78,7 @@ The plugin supports the following configuration keys:
|
||||
optional, if not set the port OctoPrint itself was started under will be used
|
||||
* ``pathPrefix``: Path prefix OctoPrint is running under, optional, if not
|
||||
set ``/`` will be used
|
||||
* ``useSsl``: ``true``if OctoPrint should be called via HTTPS, ``false`` otherwise
|
||||
* ``useSsl``: ``true`` if OctoPrint should be called via HTTPS, ``false`` otherwise
|
||||
* ``httpUsername``: HTTP Basic Auth username OctoPrint is reachable with, optional
|
||||
* ``httpPassword``: HTTP Basic Auth password OctoPrint is reachable with, optional
|
||||
* ``upnpUuid``: uPNP UUID used for SSDP service announcements, usually you will
|
||||
|
||||
@@ -829,10 +829,14 @@ Use the following settings to configure the server:
|
||||
# Use this option to define the port to which to bind the server, defaults to 5000
|
||||
port: 5000
|
||||
|
||||
# If this option is true, OctoPrint will show the First Run dialog and set it to false after that
|
||||
# completes
|
||||
# If this option is true, OctoPrint will show the First Run wizard and set the setting to
|
||||
# false after that completes
|
||||
firstRun: false
|
||||
|
||||
# If this option is true, OctoPrint will enable safe mode on the next server start and
|
||||
# reset the setting to false
|
||||
startOnceInSafeMode: false
|
||||
|
||||
# Secret key for encrypting cookies and such, randomly generated on first run
|
||||
secretKey: someSecretKey
|
||||
|
||||
|
||||
+62
-7
@@ -152,7 +152,7 @@ File handling
|
||||
-------------
|
||||
|
||||
Upload
|
||||
A file has been uploaded.
|
||||
A file has been uploaded through the web interface.
|
||||
|
||||
Payload:
|
||||
* ``name``: the file's name
|
||||
@@ -165,19 +165,74 @@ Upload
|
||||
|
||||
Still available for reasons of backwards compatibility. Will be removed with 1.4.0.
|
||||
|
||||
FileAdded
|
||||
A file has been added to a storage.
|
||||
|
||||
Payload:
|
||||
* ``storage``: the storage's identifier
|
||||
* ``path``: the file's path within its storage location
|
||||
* ``name``: the file's name
|
||||
* ``type``: the file's type, a list of the path within the type hierarchy, e.g. ``["machinecode", "gcode"]`` or
|
||||
``["model", "stl"]``
|
||||
|
||||
.. note::
|
||||
|
||||
A copied file triggers this for its new path. A moved file first triggers ``FileRemoved`` for its original
|
||||
path and then ``FileAdded`` for the new one.
|
||||
|
||||
FileRemoved
|
||||
A file has been removed from a storage.
|
||||
|
||||
Payload:
|
||||
* ``storage``: the storage's identifier
|
||||
* ``path``: the file's path within its storage location
|
||||
* ``name``: the file's name
|
||||
* ``type``: the file's type, a list of the path within the type hierarchy, e.g. ``["machinecode", "gcode"]`` or
|
||||
``["model", "stl"]``
|
||||
|
||||
.. note::
|
||||
|
||||
A moved file first triggers ``FileRemoved`` for its original path and then ``FileAdded`` for the new one.
|
||||
|
||||
FolderAdded
|
||||
A folder has been added to a storage.
|
||||
|
||||
Payload:
|
||||
* ``storage``: the storage's identifier
|
||||
* ``path``: the folders's path within its storage location
|
||||
* ``name``: the folders's name
|
||||
|
||||
.. note::
|
||||
|
||||
A copied folder triggers this for its new path. A moved folder first triggers ``FolderRemoved`` for its original
|
||||
path and then ``FolderAdded`` for the new one.
|
||||
|
||||
FolderRemoved
|
||||
A folder has been removed from a storage.
|
||||
|
||||
Payload:
|
||||
* ``storage``: the storage's identifier
|
||||
* ``path``: the folders's path within its storage location
|
||||
* ``name``: the folders's name
|
||||
|
||||
.. note::
|
||||
|
||||
A moved folder first triggers ``FolderRemoved`` for its original path and then ``FolderAdded`` for the new one.
|
||||
|
||||
UpdatedFiles
|
||||
A file list was modified.
|
||||
|
||||
Payload:
|
||||
|
||||
* ``type``: the type of file list that was modified. Currently only ``printables`` and ``gcode`` (DEPRECATED) are supported here.
|
||||
* ``type``: the type of file list that was modified. Only ``printables`` is supported here. See the deprecation
|
||||
note below.
|
||||
|
||||
.. note::
|
||||
.. deprecated:: 1.2.0
|
||||
|
||||
The ``gcode`` modification type has been superceeded by ``printables``. It is currently still available for
|
||||
reasons of backwards compatibility and will also be sent on modification of ``printables``. It will however
|
||||
be removed with 1.4.0.
|
||||
|
||||
The type ``gcode`` has been renamed to ``printables`` with the introduction of a new file management layer that
|
||||
supports STL files as first class citizens as well. For reasons of backwards compatibility the ``UpdatedFiles``
|
||||
event for printable files will be fired twice, once with ``type`` set to ``gcode``, once set to ``printables``.
|
||||
Support for the ``gcode`` type will be removed in the next release after version 1.2.0.
|
||||
|
||||
MetadataAnalysisStarted
|
||||
The metadata analysis of a file has started.
|
||||
|
||||
@@ -16,3 +16,4 @@ Features
|
||||
gcode_scripts.rst
|
||||
action_commands.rst
|
||||
plugins.rst
|
||||
safemode.rst
|
||||
@@ -11,6 +11,16 @@ Right now plugins can be used to extend OctoPrint's web interface, to execute sp
|
||||
shutdown, to provide custom (API) endpoints or whole user interfaces with special functionality, to react to system
|
||||
events or progress reports or to add support for additional slicers. More plugin types are planned for the future.
|
||||
|
||||
.. note::
|
||||
|
||||
Since a plugin might not function properly and cause issues that are hard to diagnose or outright disrupt server
|
||||
functionality, you might want to be able to start OctoPrint without any third party plugins enabled. This is also
|
||||
very important when reporting bugs in OctoPrint, to ensure that what you are observing is actually a bug in
|
||||
OctoPrint and not in any of your installed third party plugins.
|
||||
|
||||
To do that, OctoPrint has a built-in safe mode that disables all plugins not shipped as part of OctoPrint. You can
|
||||
read more on how to enable that :ref:`here <sec-features-safemode>`.
|
||||
|
||||
.. _sec-features-plugins-available:
|
||||
|
||||
Finding Plugins
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
.. _sec-features-safemode:
|
||||
|
||||
*********
|
||||
Safe mode
|
||||
*********
|
||||
|
||||
With the advent of support for plugins in OctoPrint, it quickly became apparent that some of the bugs
|
||||
reported on OctoPrint's bug tracker were actually bugs with installed third party plugins instead of
|
||||
OctoPrint itself.
|
||||
|
||||
To allow an easier identification of these cases, OctoPrint 1.3.0 introduced safe mode. Starting
|
||||
OctoPrint in safe mode disables all plugins that are not bundled with OctoPrint, allowing to easier
|
||||
identify most cases where a third party plugin is the culprit of an observed issue.
|
||||
|
||||
Additionally, OctoPrint allows uninstalling plugins in this mode, allowing recovery from cases where
|
||||
a third party plugin causes the server to not start up or the web interface to not render or function
|
||||
correctly anymore.
|
||||
|
||||
.. _sec-features-safemode-how:
|
||||
|
||||
How to start OctoPrint in safe mode
|
||||
===================================
|
||||
|
||||
There exist three ways to start OctoPrint in safe mode:
|
||||
|
||||
* since OctoPrint 1.3.2: by selecting "Restart OctoPrint in safe mode" from the "System" menu,
|
||||
if the "Restart OctoPrint" server command has been correctly configured (see :numref:`fig-features-safemode-systemmenu`).
|
||||
* by starting OctoPrint with the command line parameter ``--safe``, e.g. ``octoprint serve --safe``
|
||||
* by setting the option ``server.startOnceInSafeMode`` in :ref:`config.yaml <sec-configuration-config_yaml>`
|
||||
to ``true`` and restarting
|
||||
|
||||
The last two options will have OctoPrint enable safe mode only for the next server start - once you
|
||||
restart OctoPrint again, safe mode will be disabled again.
|
||||
|
||||
.. _fig-features-safemode-systemmenu:
|
||||
.. figure:: ../images/features-safemode-systemmenu.png
|
||||
:align: center
|
||||
:alt: "Restart OctoPrint in safe mode" in the "System" menu
|
||||
|
||||
"Restart OctoPrint in safe mode" in the "System" menu
|
||||
|
||||
.. _sec-features-safemode-differences:
|
||||
|
||||
Differences of safe mode vs normal operation mode
|
||||
=================================================
|
||||
|
||||
When OctoPrint is running in safe mode the following changes to its normal operation mode apply:
|
||||
|
||||
* OctoPrint will not enable any of the installed third party plugins. OctoPrint considers all plugins third
|
||||
party plugins that do not ship with OctoPrint's sources, so any plugins installed either via `pip` or
|
||||
into OctoPrint's plugin folder at ``~/.octoprint/plugins`` (Linux), ``%APPDATA%/OctoPrint`` (Windows) and
|
||||
``~/Library/Application Support/OctoPrint`` (MacOS).
|
||||
* OctoPrint will still allow to uninstall third party plugins through the built-in Plugin Manager.
|
||||
* OctoPrint will still allow to disable (bundled) plugins that are still enabled.
|
||||
* OctoPrint will not allow to enable third party plugins.
|
||||
* OctoPrint's web interface will display a notification to remind you that it is running in
|
||||
safe mode.
|
||||
|
||||
.. _fig-features-safemode-notification:
|
||||
.. figure:: ../images/features-safemode-notification.png
|
||||
:align: center
|
||||
:alt: Safe mode notification
|
||||
|
||||
Safe mode notification
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 38 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 33 KiB |
@@ -35,6 +35,13 @@
|
||||
:param object opts: Additional options for the request
|
||||
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
|
||||
|
||||
.. js:function:: OctoPrintClient.settings.generateApiKey(opts)
|
||||
|
||||
Generate a new system wide API key.
|
||||
|
||||
:param object opts: Additional options for the request
|
||||
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
|
||||
|
||||
.. seealso::
|
||||
|
||||
:ref:`Settings API <sec-api-settings>`
|
||||
|
||||
@@ -922,3 +922,35 @@ octoprint.ui.web.templatetypes
|
||||
:param dict template_sorting: read-only dictionary of currently configured template sorting specifications
|
||||
:return: a list of 3-tuples (template type, rule, sorting spec)
|
||||
:rtype: list
|
||||
|
||||
.. _sec-plugins-hook-timelapse-capture-pre:
|
||||
|
||||
octoprint.timelapse.capture.pre
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
.. py:function:: capture_pre_hook(filename)
|
||||
|
||||
Perform specific actions prior to capturing a timelapse frame.
|
||||
|
||||
``filename`` will be the future path of the frame to be saved.
|
||||
|
||||
:param str filename: The future path of the frame to be saved.
|
||||
:return: None
|
||||
:rtype: None
|
||||
|
||||
.. _sec-plugins-hook-timelapse-capture-post:
|
||||
|
||||
octoprint.timelapse.capture.post
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
.. py:function:: capture_post_hook(filename, success)
|
||||
|
||||
Perform specific actions after capturing a timelapse frame.
|
||||
|
||||
``filename`` will be the path of the frame that should have been saved.
|
||||
``sucesss`` indicates whether the capture was successful or not.
|
||||
|
||||
:param str filename: The path of the frame that should have been saved.
|
||||
:param boolean success: Indicates whether the capture was successful or not.
|
||||
:return: None
|
||||
:rtype: None
|
||||
@@ -44,7 +44,8 @@ INSTALL_REQUIRES = [
|
||||
"chainmap>=1.0.2,<1.1",
|
||||
"future>=0.15,<0.16",
|
||||
"scandir>=1.3,<1.4",
|
||||
"websocket-client>=0.40,<0.41"
|
||||
"websocket-client>=0.40,<0.41",
|
||||
"python-dateutil>=2.6,<2.7"
|
||||
]
|
||||
|
||||
if sys.platform == "darwin":
|
||||
|
||||
@@ -160,11 +160,11 @@ def octo(ctx, **kwargs):
|
||||
"start|stop|restart\" is deprecated, please use "
|
||||
"\"octoprint daemon start|stop|restart\" from now on")
|
||||
|
||||
if sys.platform == "linux2":
|
||||
if sys.platform.startswith("linux") or sys.platform.startswith("freebsd"):
|
||||
from octoprint.cli.server import daemon_command
|
||||
ctx.invoke(daemon_command, command=daemon, **kwargs)
|
||||
else:
|
||||
click.echo("Sorry, daemon mode is only supported under Linux right now")
|
||||
click.echo("Sorry, daemon mode is not supported under your operating system right now")
|
||||
else:
|
||||
click.echo("Starting the server via \"octoprint\" is deprecated, "
|
||||
"please use \"octoprint serve\" from now on.")
|
||||
|
||||
+51
-24
@@ -29,6 +29,7 @@ def client_commands():
|
||||
|
||||
|
||||
@client_commands.group("client", context_settings=dict(ignore_unknown_options=True))
|
||||
@click.option("--apikey", "-a", type=click.STRING)
|
||||
@click.option("--host", "-h", type=click.STRING)
|
||||
@click.option("--port", "-p", type=click.INT)
|
||||
@click.option("--httpuser", type=click.STRING)
|
||||
@@ -36,11 +37,29 @@ def client_commands():
|
||||
@click.option("--https", is_flag=True)
|
||||
@click.option("--prefix", type=click.STRING)
|
||||
@click.pass_context
|
||||
def client(ctx, host, port, httpuser, httppass, https, prefix):
|
||||
def client(ctx, apikey, host, port, httpuser, httppass, https, prefix):
|
||||
"""Basic API client."""
|
||||
try:
|
||||
ctx.obj.settings = init_settings(get_ctx_obj_option(ctx, "basedir", None), get_ctx_obj_option(ctx, "configfile", None))
|
||||
octoprint_client.init_client(ctx.obj.settings, https=https, httpuser=httpuser, httppass=httppass, host=host, port=port, prefix=prefix)
|
||||
if not host or not port or not apikey:
|
||||
settings = init_settings(get_ctx_obj_option(ctx, "basedir", None), get_ctx_obj_option(ctx, "configfile", None))
|
||||
|
||||
if not host:
|
||||
host = settings.get(["server", "host"])
|
||||
host = host if host != "0.0.0.0" else "127.0.0.1"
|
||||
if not port:
|
||||
port = settings.getInt(["server", "port"])
|
||||
|
||||
if not apikey:
|
||||
apikey = settings.get(["api", "key"])
|
||||
|
||||
baseurl = octoprint_client.build_base_url(https=https,
|
||||
httpuser=httpuser,
|
||||
httppass=httppass,
|
||||
host=host,
|
||||
port=port,
|
||||
prefix=prefix)
|
||||
|
||||
ctx.obj.client = octoprint_client.Client(baseurl, apikey)
|
||||
except FatalStartupError as e:
|
||||
click.echo(e.message, err=True)
|
||||
click.echo("There was a fatal error initializing the client.", err=True)
|
||||
@@ -60,27 +79,30 @@ def log_response(response, status_code=True, body=True, headers=False):
|
||||
|
||||
@client.command("get")
|
||||
@click.argument("path")
|
||||
def get(path):
|
||||
@click.pass_context
|
||||
def get(ctx, path):
|
||||
"""Performs a GET request against the specified server path."""
|
||||
r = octoprint_client.get(path)
|
||||
r = ctx.obj.client.get(path)
|
||||
log_response(r)
|
||||
|
||||
|
||||
@client.command("post_json")
|
||||
@click.argument("path")
|
||||
@click.argument("data", type=JsonStringParamType())
|
||||
def post_json(path, data):
|
||||
@click.pass_context
|
||||
def post_json(ctx, path, data):
|
||||
"""POSTs JSON data to the specified server path."""
|
||||
r = octoprint_client.post_json(path, data)
|
||||
r = ctx.obj.client.post_json(path, data)
|
||||
log_response(r)
|
||||
|
||||
|
||||
@client.command("patch_json")
|
||||
@click.argument("path")
|
||||
@click.argument("data", type=JsonStringParamType())
|
||||
def patch_json(path, data):
|
||||
@click.pass_context
|
||||
def patch_json(ctx, path, data):
|
||||
"""PATCHes JSON data to the specified server path."""
|
||||
r = octoprint_client.patch(path, data, encoding="json")
|
||||
r = ctx.obj.client.patch(path, data, encoding="json")
|
||||
log_response(r)
|
||||
|
||||
|
||||
@@ -89,7 +111,8 @@ def patch_json(path, data):
|
||||
@click.argument("file_path", type=click.Path(exists=True, dir_okay=False, resolve_path=True))
|
||||
@click.option("--json", is_flag=True)
|
||||
@click.option("--yaml", is_flag=True)
|
||||
def post_from_file(path, file_path, json_flag, yaml_flag):
|
||||
@click.pass_context
|
||||
def post_from_file(ctx, path, file_path, json_flag, yaml_flag):
|
||||
"""POSTs JSON data to the specified server path."""
|
||||
if json_flag or yaml_flag:
|
||||
if json_flag:
|
||||
@@ -100,12 +123,12 @@ def post_from_file(path, file_path, json_flag, yaml_flag):
|
||||
with open(file_path, "rb") as fp:
|
||||
data = yaml.safe_load(fp)
|
||||
|
||||
r = octoprint_client.post_json(path, data)
|
||||
r = ctx.obj.client.post_json(path, data)
|
||||
else:
|
||||
with open(file_path, "rb") as fp:
|
||||
data = fp.read()
|
||||
|
||||
r = octoprint_client.post(path, data)
|
||||
r = ctx.obj.client.post(path, data)
|
||||
|
||||
log_response(r)
|
||||
|
||||
@@ -117,13 +140,14 @@ def post_from_file(path, file_path, json_flag, yaml_flag):
|
||||
@click.option("--int", "-i", "int_params", multiple=True, nargs=2, type=click.Tuple([unicode, int]))
|
||||
@click.option("--float", "-f", "float_params", multiple=True, nargs=2, type=click.Tuple([unicode, float]))
|
||||
@click.option("--bool", "-b", "bool_params", multiple=True, nargs=2, type=click.Tuple([unicode, bool]))
|
||||
def command(path, command, str_params, int_params, float_params, bool_params):
|
||||
@click.pass_context
|
||||
def command(ctx, path, command, str_params, int_params, float_params, bool_params):
|
||||
"""Sends a JSON command to the specified server path."""
|
||||
data = dict()
|
||||
params = str_params + int_params + float_params + bool_params
|
||||
for param in params:
|
||||
data[param[0]] = param[1]
|
||||
r = octoprint_client.post_command(path, command, additional=data)
|
||||
r = ctx.obj.client.post_command(path, command, additional=data)
|
||||
log_response(r, body=False)
|
||||
|
||||
|
||||
@@ -133,26 +157,29 @@ def command(path, command, str_params, int_params, float_params, bool_params):
|
||||
@click.option("--parameter", "-P", "params", multiple=True, nargs=2, type=click.Tuple([unicode, unicode]))
|
||||
@click.option("--file-name", type=click.STRING)
|
||||
@click.option("--content-type", type=click.STRING)
|
||||
def upload(path, file_path, params, file_name, content_type):
|
||||
@click.pass_context
|
||||
def upload(ctx, path, file_path, params, file_name, content_type):
|
||||
"""Uploads the specified file to the specified server path."""
|
||||
data = dict()
|
||||
for param in params:
|
||||
data[param[0]] = param[1]
|
||||
|
||||
r = octoprint_client.upload(path, file_path, additional=data, file_name=file_name, content_type=content_type)
|
||||
r = ctx.obj.client.upload(path, file_path, additional=data, file_name=file_name, content_type=content_type)
|
||||
log_response(r)
|
||||
|
||||
|
||||
@client.command("delete")
|
||||
@click.argument("path")
|
||||
def delete(path):
|
||||
@click.pass_context
|
||||
def delete(ctx, path):
|
||||
"""Sends a DELETE request to the specified server path."""
|
||||
r = octoprint_client.delete(path)
|
||||
r = ctx.obj.client.delete(path)
|
||||
log_response(r)
|
||||
|
||||
|
||||
@client.command("listen")
|
||||
def listen():
|
||||
@click.pass_context
|
||||
def listen(ctx):
|
||||
def on_connect(ws):
|
||||
click.echo(">>> Connected!")
|
||||
|
||||
@@ -168,11 +195,11 @@ def listen():
|
||||
def on_message(ws, message_type, message_payload):
|
||||
click.echo("Message: {}, Payload: {}".format(message_type, json.dumps(message_payload)))
|
||||
|
||||
socket = octoprint_client.connect_socket(on_connect=on_connect,
|
||||
on_close=on_close,
|
||||
on_error=on_error,
|
||||
on_heartbeat=on_heartbeat,
|
||||
on_message=on_message)
|
||||
socket = ctx.obj.client.create_socket(on_connect=on_connect,
|
||||
on_close=on_close,
|
||||
on_error=on_error,
|
||||
on_heartbeat=on_heartbeat,
|
||||
on_message=on_message)
|
||||
|
||||
click.echo(">>> Waiting for client to exit")
|
||||
try:
|
||||
|
||||
@@ -150,8 +150,8 @@ def serve_command(ctx, **kwargs):
|
||||
allow_root, logging, verbosity, safe_mode)
|
||||
|
||||
|
||||
if sys.platform == "linux2":
|
||||
# we only support daemon mode under Linux
|
||||
if sys.platform.startswith("linux") or sys.platform.startswith("freebsd"):
|
||||
# we only support daemon mode under Linux and FreeBSD for now
|
||||
|
||||
@server_commands.command(name="daemon")
|
||||
@server_options
|
||||
|
||||
@@ -53,6 +53,11 @@ class Events(object):
|
||||
METADATA_ANALYSIS_FINISHED = "MetadataAnalysisFinished"
|
||||
METADATA_STATISTICS_UPDATED = "MetadataStatisticsUpdated"
|
||||
|
||||
FILE_ADDED = "FileAdded",
|
||||
FILE_REMOVED = "FileRemoved",
|
||||
FOLDER_ADDED = "FolderAdded",
|
||||
FOLDER_REMOVED = "FolderRemoved",
|
||||
|
||||
# SD Upload
|
||||
TRANSFER_STARTED = "TransferStarted"
|
||||
TRANSFER_DONE = "TransferDone"
|
||||
@@ -350,7 +355,10 @@ class CommandTrigger(GenericEventListener):
|
||||
else:
|
||||
commandExecutioner(command)
|
||||
except subprocess.CalledProcessError as e:
|
||||
self._logger.warn("Command failed with return code %i: %s" % (e.returncode, str(e)))
|
||||
if debug:
|
||||
self._logger.warn("Command failed with return code {}: {}".format(e.returncode, str(e)))
|
||||
else:
|
||||
self._logger.warn("Command failed with return code {}, enable debug logging on target 'octoprint.events' for details".format(e.returncode))
|
||||
except:
|
||||
self._logger.exception("Command failed")
|
||||
|
||||
|
||||
@@ -409,30 +409,47 @@ class FileManager(object):
|
||||
queue_entry = self._analysis_queue_entry(destination, path)
|
||||
self._analysis_queue.dequeue(queue_entry)
|
||||
|
||||
file_path = self._storage(destination).add_file(path, file_object, links=links, printer_profile=printer_profile, allow_overwrite=allow_overwrite)
|
||||
path_in_storage = self._storage(destination).add_file(path, file_object, links=links, printer_profile=printer_profile, allow_overwrite=allow_overwrite)
|
||||
|
||||
if analysis is None:
|
||||
queue_entry = self._analysis_queue_entry(destination, file_path, printer_profile=printer_profile)
|
||||
queue_entry = self._analysis_queue_entry(destination, path_in_storage, printer_profile=printer_profile)
|
||||
if queue_entry:
|
||||
self._analysis_queue.enqueue(queue_entry, high_priority=True)
|
||||
else:
|
||||
self._add_analysis_result(destination, path, analysis)
|
||||
|
||||
_, name = self._storage(destination).split_path(path_in_storage)
|
||||
eventManager().fire(Events.FILE_ADDED, dict(storage=destination,
|
||||
path=path_in_storage,
|
||||
name=name,
|
||||
type=get_file_type(name)))
|
||||
eventManager().fire(Events.UPDATED_FILES, dict(type="printables"))
|
||||
return file_path
|
||||
return path_in_storage
|
||||
|
||||
def remove_file(self, destination, path):
|
||||
queue_entry = self._analysis_queue_entry(destination, path)
|
||||
self._analysis_queue.dequeue(queue_entry)
|
||||
self._storage(destination).remove_file(path)
|
||||
|
||||
_, name = self._storage(destination).split_path(path)
|
||||
eventManager().fire(Events.FILE_REMOVED, dict(storage=destination,
|
||||
path=path,
|
||||
name=name,
|
||||
type=get_file_type(name)))
|
||||
eventManager().fire(Events.UPDATED_FILES, dict(type="printables"))
|
||||
|
||||
def copy_file(self, destination, source, dst):
|
||||
path = self._storage(destination).copy_file(source, dst)
|
||||
if not self.has_analysis(destination, path):
|
||||
queue_entry = self._analysis_queue_entry(destination, path)
|
||||
path_in_storage = self._storage(destination).copy_file(source, dst)
|
||||
if not self.has_analysis(destination, path_in_storage):
|
||||
queue_entry = self._analysis_queue_entry(destination, path_in_storage)
|
||||
if queue_entry:
|
||||
self._analysis_queue.enqueue(queue_entry)
|
||||
|
||||
_, name = self._storage(destination).split_path(path_in_storage)
|
||||
eventManager().fire(Events.FILE_ADDED, dict(storage=destination,
|
||||
path=path_in_storage,
|
||||
name=name,
|
||||
type=get_file_type(name)))
|
||||
eventManager().fire(Events.UPDATED_FILES, dict(type="printables"))
|
||||
|
||||
def move_file(self, destination, source, dst):
|
||||
@@ -443,23 +460,52 @@ class FileManager(object):
|
||||
queue_entry = self._analysis_queue_entry(destination, path)
|
||||
if queue_entry:
|
||||
self._analysis_queue.enqueue(queue_entry)
|
||||
|
||||
source_path_in_storage = self._storage(destination).path_in_storage(source)
|
||||
_, source_name = self._storage(destination).split_path(source_path_in_storage)
|
||||
dst_path_in_storage = self._storage(destination).path_in_storage(dst)
|
||||
_, dst_name = self._storage(destination).split_path(dst_path_in_storage)
|
||||
|
||||
eventManager().fire(Events.FILE_REMOVED, dict(storage=destination,
|
||||
path=source_path_in_storage,
|
||||
name=source_name,
|
||||
type=get_file_type(source_name)))
|
||||
eventManager().fire(Events.FILE_ADDED, dict(storage=destination,
|
||||
path=dst_path_in_storage,
|
||||
name=dst_name,
|
||||
type=get_file_type(dst_name)))
|
||||
eventManager().fire(Events.UPDATED_FILES, dict(type="printables"))
|
||||
|
||||
def add_folder(self, destination, path, ignore_existing=True):
|
||||
folder_path = self._storage(destination).add_folder(path, ignore_existing=ignore_existing)
|
||||
path_in_storage = self._storage(destination).add_folder(path, ignore_existing=ignore_existing)
|
||||
|
||||
_, name = self._storage(destination).split_path(path_in_storage)
|
||||
eventManager().fire(Events.FOLDER_ADDED, dict(storage=destination,
|
||||
path=path_in_storage,
|
||||
name=name))
|
||||
eventManager().fire(Events.UPDATED_FILES, dict(type="printables"))
|
||||
return folder_path
|
||||
return path_in_storage
|
||||
|
||||
def remove_folder(self, destination, path, recursive=True):
|
||||
self._analysis_queue.dequeue_folder(destination, path)
|
||||
self._analysis_queue.pause()
|
||||
self._storage(destination).remove_folder(path, recursive=recursive)
|
||||
self._analysis_queue.resume()
|
||||
|
||||
_, name = self._storage(destination).split_path(path)
|
||||
eventManager().fire(Events.FOLDER_REMOVED, dict(storage=destination,
|
||||
path=path,
|
||||
name=name))
|
||||
eventManager().fire(Events.UPDATED_FILES, dict(type="printables"))
|
||||
|
||||
def copy_folder(self, destination, source, dst):
|
||||
self._storage(destination).copy_folder(source, dst)
|
||||
path_in_storage = self._storage(destination).copy_folder(source, dst)
|
||||
self._determine_analysis_backlog(destination, self._storage(destination), root=dst)
|
||||
|
||||
_, name = self._storage(destination).split_path(path_in_storage)
|
||||
eventManager().fire(Events.FOLDER_ADDED, dict(storage=destination,
|
||||
path=path_in_storage,
|
||||
name=name))
|
||||
eventManager().fire(Events.UPDATED_FILES, dict(type="printables"))
|
||||
|
||||
def move_folder(self, destination, source, dst):
|
||||
@@ -468,6 +514,18 @@ class FileManager(object):
|
||||
self._storage(destination).move_folder(source, dst)
|
||||
self._determine_analysis_backlog(destination, self._storage(destination), root=dst)
|
||||
self._analysis_queue.resume()
|
||||
|
||||
source_path_in_storage = self._storage(destination).path_in_storage(source)
|
||||
_, source_name = self._storage(destination).split_path(source_path_in_storage)
|
||||
dst_path_in_storage = self._storage(destination).path_in_storage(destination)
|
||||
_, dst_name = self._storage(destination).split_path(dst_path_in_storage)
|
||||
|
||||
eventManager().fire(Events.FOLDER_REMOVED, dict(storage=destination,
|
||||
path=source_path_in_storage,
|
||||
name=source_name))
|
||||
eventManager().fire(Events.FOLDER_ADDED, dict(storage=destination,
|
||||
path=dst_path_in_storage,
|
||||
name=dst_name))
|
||||
eventManager().fire(Events.UPDATED_FILES, dict(type="printables"))
|
||||
|
||||
def has_analysis(self, destination, path):
|
||||
|
||||
@@ -308,9 +308,12 @@ class GcodeAnalysisQueue(AbstractAnalysisQueue):
|
||||
def _do_analysis(self, high_priority=False):
|
||||
try:
|
||||
throttle = settings().getFloat(["gcodeAnalysis", "throttle_highprio"]) if high_priority else settings().getFloat(["gcodeAnalysis", "throttle_normalprio"])
|
||||
throttle_lines = settings().getInt(["gcodeAnalysis", "throttle_lines"])
|
||||
if throttle > 0:
|
||||
def throttle_callback():
|
||||
time.sleep(throttle)
|
||||
def throttle_callback(filePos, readBytes):
|
||||
if filePos % throttle_lines == 0:
|
||||
# only apply throttle every 100 lines
|
||||
time.sleep(throttle)
|
||||
else:
|
||||
throttle_callback = None
|
||||
|
||||
|
||||
@@ -29,7 +29,6 @@ class StorageInterface(object):
|
||||
Interface of storage adapters for OctoPrint.
|
||||
"""
|
||||
|
||||
|
||||
@property
|
||||
def analysis_backlog(self):
|
||||
"""
|
||||
@@ -155,7 +154,9 @@ class StorageInterface(object):
|
||||
|
||||
def add_folder(self, path, ignore_existing=True):
|
||||
"""
|
||||
Adds a folder as ``path``. The ``path`` will be sanitized.
|
||||
Adds a folder as ``path``
|
||||
|
||||
The ``path`` will be sanitized.
|
||||
|
||||
:param string path: the path of the new folder
|
||||
:param bool ignore_existing: if set to True, no error will be raised if the folder to be added already exists
|
||||
@@ -165,7 +166,7 @@ class StorageInterface(object):
|
||||
|
||||
def remove_folder(self, path, recursive=True):
|
||||
"""
|
||||
Removes the folder at ``path``.
|
||||
Removes the folder at ``path``
|
||||
|
||||
:param string path: the path of the folder to remove
|
||||
:param bool recursive: if set to True, contained folders and files will also be removed, otherwise and error will
|
||||
@@ -212,7 +213,9 @@ class StorageInterface(object):
|
||||
|
||||
def remove_file(self, path):
|
||||
"""
|
||||
Removes the file at ``path``. Will also take care of deleting the corresponding entries
|
||||
Removes the file at ``path``
|
||||
|
||||
Will also take care of deleting the corresponding entries
|
||||
in the metadata and deleting all links pointing to the file.
|
||||
|
||||
:param string path: path of the file to remove
|
||||
@@ -486,6 +489,9 @@ class LocalFileStorage(StorageInterface):
|
||||
return self.analysis_backlog_for_path()
|
||||
|
||||
def analysis_backlog_for_path(self, path=None):
|
||||
if path:
|
||||
path = self.sanitize_path(path)
|
||||
|
||||
for entry in self._analysis_backlog_generator(path):
|
||||
yield entry
|
||||
|
||||
@@ -982,7 +988,15 @@ class LocalFileStorage(StorageInterface):
|
||||
continue
|
||||
|
||||
printer_profile = history_entry["printerProfile"]
|
||||
if not printer_profile:
|
||||
continue
|
||||
|
||||
print_time = history_entry["printTime"]
|
||||
try:
|
||||
print_time = float(print_time)
|
||||
except:
|
||||
self._logger.warn("Invalid print time value found in print history for {} in {}/.metadata.yaml: {!r}".format(name, path, print_time))
|
||||
continue
|
||||
|
||||
if not printer_profile in former_print_times:
|
||||
former_print_times[printer_profile] = []
|
||||
|
||||
@@ -71,6 +71,9 @@ class PluginInfo(object):
|
||||
attr_description = '__plugin_description__'
|
||||
""" Module attribute from which to retrieve the plugin's description. """
|
||||
|
||||
attr_disabling_discouraged = '__plugin_disabling_discouraged__'
|
||||
""" Module attribute from which to retrieve the reason why disabling the plugin is discouraged. Only effective if ``self.bundled`` is True. """
|
||||
|
||||
attr_version = '__plugin_version__'
|
||||
""" Module attribute from which to retrieve the plugin's version. """
|
||||
|
||||
@@ -294,6 +297,19 @@ class PluginInfo(object):
|
||||
"""
|
||||
return self._get_instance_attribute(self.__class__.attr_description, default=self._description)
|
||||
|
||||
@property
|
||||
def disabling_discouraged(self):
|
||||
"""
|
||||
Reason why disabling of this plugin is discouraged. Only evaluated for bundled plugins! Will be taken from
|
||||
the disabling_discouraged attribute of the plugin module as defined in :attr:`attr_disabling_discouraged` if
|
||||
available. False if unset or plugin not bundled.
|
||||
|
||||
Returns:
|
||||
str or None: Reason why disabling this plugin is discouraged (only for bundled plugins)
|
||||
"""
|
||||
return self._get_instance_attribute(self.__class__.attr_disabling_discouraged, default=False) if self.bundled \
|
||||
else False
|
||||
|
||||
@property
|
||||
def version(self):
|
||||
"""
|
||||
|
||||
@@ -1549,7 +1549,7 @@ class SettingsPlugin(OctoPrintPlugin):
|
||||
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"],
|
||||
return dict(admin=[["some", "admin_only", "path"], ["another", "admin_only", "path"],
|
||||
user=[["some", "user_only", "path"],],
|
||||
never=[["path", "to", "never", "return"],])
|
||||
|
||||
|
||||
@@ -18,6 +18,8 @@ import threading
|
||||
import feedparser
|
||||
import flask
|
||||
|
||||
from collections import OrderedDict
|
||||
|
||||
from octoprint.access.permissions import Permissions
|
||||
from octoprint.server.util.flask import restricted_access, with_revalidation_checking, check_etag
|
||||
from flask_babel import gettext
|
||||
@@ -44,35 +46,64 @@ class AnnouncementPlugin(octoprint.plugin.AssetPlugin,
|
||||
# SettingsPlugin
|
||||
|
||||
def get_settings_defaults(self):
|
||||
return dict(channels=dict(_important=dict(name="Important OctoPrint Announcements",
|
||||
priority=1,
|
||||
type="rss",
|
||||
url="http://octoprint.org/feeds/important.xml"),
|
||||
_news=dict(name="OctoPrint News",
|
||||
priority=2,
|
||||
type="rss",
|
||||
url="http://octoprint.org/feeds/news.xml"),
|
||||
_releases=dict(name="OctoPrint Release Announcements",
|
||||
settings = dict(channels=dict(_important=dict(name="Important Announcements",
|
||||
description="Important announcements about OctoPrint.",
|
||||
priority=1,
|
||||
type="rss",
|
||||
url="http://octoprint.org/feeds/important.xml"),
|
||||
_releases=dict(name="Release Announcements",
|
||||
description="Announcements of new releases and release candidates of OctoPrint.",
|
||||
priority=2,
|
||||
type="rss",
|
||||
url="http://octoprint.org/feeds/releases.xml"),
|
||||
_blog=dict(name="On the OctoBlog",
|
||||
description="Development news, community spotlights, OctoPrint On Air episodes and more from the official OctoBlog.",
|
||||
priority=2,
|
||||
type="rss",
|
||||
url="http://octoprint.org/feeds/releases.xml"),
|
||||
_spotlight=dict(name="OctoPrint Community Spotlights",
|
||||
priority=2,
|
||||
type="rss",
|
||||
url="http://octoprint.org/feeds/spotlight.xml"),
|
||||
_octopi=dict(name="OctoPi Announcements",
|
||||
priority=2,
|
||||
type="rss",
|
||||
url="http://octoprint.org/feeds/octopi.xml"),
|
||||
_plugins=dict(name="New Plugins in the Repository",
|
||||
priority=2,
|
||||
type="rss",
|
||||
url="http://plugins.octoprint.org/feed.xml")),
|
||||
enabled_channels=[],
|
||||
forced_channels=["_important"],
|
||||
ttl=6*60,
|
||||
display_limit=3,
|
||||
summary_limit=300)
|
||||
url="http://octoprint.org/feeds/octoblog.xml"),
|
||||
_plugins=dict(name="New Plugins in the Repository",
|
||||
description="Announcements of new plugins released on the official Plugin Repository.",
|
||||
priority=2,
|
||||
type="rss",
|
||||
url="http://plugins.octoprint.org/feed.xml"),
|
||||
_octopi=dict(name="OctoPi News",
|
||||
description="News around OctoPi, the Raspberry Pi image including OctoPrint.",
|
||||
priority=2,
|
||||
type="rss",
|
||||
url="http://octoprint.org/feeds/octopi.xml")),
|
||||
enabled_channels=[],
|
||||
forced_channels=["_important"],
|
||||
channel_order=["_important", "_releases", "_blog", "_plugins", "_octopi"],
|
||||
ttl=6*60,
|
||||
display_limit=3,
|
||||
summary_limit=300)
|
||||
settings["enabled_channels"] = settings["channels"].keys()
|
||||
return settings
|
||||
|
||||
def get_settings_version(self):
|
||||
return 1
|
||||
|
||||
def on_settings_migrate(self, target, current):
|
||||
if current is None:
|
||||
# first version had different default feeds and only _important enabled by default
|
||||
channels = self._settings.get(["channels"])
|
||||
if "_news" in channels:
|
||||
del channels["_news"]
|
||||
if "_spotlight" in channels:
|
||||
del channels["_spotlight"]
|
||||
self._settings.set(["channels"], channels)
|
||||
|
||||
enabled = self._settings.get(["enabled_channels"])
|
||||
add_blog = False
|
||||
if "_news" in enabled:
|
||||
add_blog = True
|
||||
enabled.remove("_news")
|
||||
if "_spotlight" in enabled:
|
||||
add_blog = True
|
||||
enabled.remove("_spotlight")
|
||||
if add_blog and not "_blog" in enabled:
|
||||
enabled.append("_blog")
|
||||
self._settings.set(["enabled_channels"], enabled)
|
||||
|
||||
# AssetPlugin
|
||||
|
||||
@@ -97,7 +128,7 @@ class AnnouncementPlugin(octoprint.plugin.AssetPlugin,
|
||||
def get_channel_data(self):
|
||||
from octoprint.settings import valid_boolean_trues
|
||||
|
||||
result = dict()
|
||||
result = []
|
||||
|
||||
force = flask.request.values.get("force", "false") in valid_boolean_trues
|
||||
|
||||
@@ -118,15 +149,17 @@ class AnnouncementPlugin(octoprint.plugin.AssetPlugin,
|
||||
last = entries[0]["published"]
|
||||
self._mark_read_until(key, last)
|
||||
|
||||
result[key] = dict(channel=data["name"],
|
||||
result.append(dict(key=key,
|
||||
channel=data["name"],
|
||||
url=data["url"],
|
||||
description=data.get("description", ""),
|
||||
priority=data.get("priority", 2),
|
||||
enabled=key in enabled or key in forced,
|
||||
forced=key in forced,
|
||||
data=entries,
|
||||
unread=unread)
|
||||
unread=unread))
|
||||
|
||||
return flask.jsonify(result)
|
||||
return flask.jsonify(channels=result)
|
||||
|
||||
def etag():
|
||||
import hashlib
|
||||
@@ -141,11 +174,11 @@ class AnnouncementPlugin(octoprint.plugin.AssetPlugin,
|
||||
|
||||
return hash.hexdigest()
|
||||
|
||||
def condition():
|
||||
return check_etag(etag())
|
||||
def condition(lm, etag):
|
||||
return check_etag(etag)
|
||||
|
||||
return with_revalidation_checking(etag_factory=lambda *args, **kwargs: etag(),
|
||||
condition=lambda *args, **kwargs: condition(),
|
||||
condition=lambda lm, etag: condition(lm, etag),
|
||||
unless=lambda: force)(view)()
|
||||
|
||||
@octoprint.plugin.BlueprintPlugin.route("/channels/<channel>", methods=["POST"])
|
||||
@@ -208,9 +241,13 @@ class AnnouncementPlugin(octoprint.plugin.AssetPlugin,
|
||||
with self._cached_channel_configs_mutex:
|
||||
if self._cached_channel_configs is None or force:
|
||||
configs = self._settings.get(["channels"], merged=True)
|
||||
result = dict()
|
||||
for key, config in configs.items():
|
||||
if "url" not in config or "name" not in config:
|
||||
order = self._settings.get(["channel_order"])
|
||||
all_keys = order + [key for key in sorted(configs.keys()) if not key in order]
|
||||
|
||||
result = OrderedDict()
|
||||
for key in all_keys:
|
||||
config = configs.get(key)
|
||||
if config is None or "url" not in config or "name" not in config:
|
||||
# strip invalid entries
|
||||
continue
|
||||
result[self._slugify(key)] = config
|
||||
@@ -374,4 +411,9 @@ def _strip_tags(text):
|
||||
|
||||
|
||||
__plugin_name__ = "Announcement Plugin"
|
||||
__plugin_author__ = "Gina Häußge"
|
||||
__plugin_description__ = "Announcements all around OctoPrint"
|
||||
__plugin_disabling_discouraged__ = gettext("Without this plugin you might miss important announcements "
|
||||
"regarding security or other critical issues concerning OctoPrint.")
|
||||
__plugin_license__ = "AGPLv3"
|
||||
__plugin_implementation__ = AnnouncementPlugin()
|
||||
@@ -1 +1 @@
|
||||
table td.settings_plugin_announcements_channels_name,table th.settings_plugin_announcements_channels_name{text-overflow:ellipsis;text-align:left}table td.settings_plugin_announcements_channels_actions,table th.settings_plugin_announcements_channels_actions{text-align:center;width:80px}table td.settings_plugin_announcements_channels_actions a,table th.settings_plugin_announcements_channels_actions a{text-decoration:none;color:#000}table td.settings_plugin_announcements_channels_actions a.disabled,table th.settings_plugin_announcements_channels_actions a.disabled{color:#ccc;cursor:default}#plugin_announcements_dialog .unread{font-weight:700}#plugin_announcements_dialog article{padding-right:20px}#plugin_announcements_dialog article.read{opacity:.5}#plugin_announcements_dialog article.read:hover{opacity:1}#plugin_announcements_dialog article .actions{background-color:#f5f5f5;border-radius:2px;padding:2px 5px;margin-top:5px}#plugin_announcements_dialog article .actions .markread{float:right}#plugin_announcements_dialog article .actions a{color:#000}
|
||||
table td.settings_plugin_announcements_channels_name,table th.settings_plugin_announcements_channels_name{text-overflow:ellipsis;text-align:left}table td.settings_plugin_announcements_channels_actions,table th.settings_plugin_announcements_channels_actions{text-align:center;width:80px}table td.settings_plugin_announcements_channels_actions a,table th.settings_plugin_announcements_channels_actions a{text-decoration:none;color:#000}table td.settings_plugin_announcements_channels_actions a.disabled,table th.settings_plugin_announcements_channels_actions a.disabled{color:#ccc;cursor:default}#plugin_announcements_dialog .unread{font-weight:700}#plugin_announcements_dialog article{padding-right:20px}#plugin_announcements_dialog article.read{opacity:.5}#plugin_announcements_dialog article.read:hover{opacity:1}#plugin_announcements_dialog article .actions{background-color:#f5f5f5;border-radius:2px;padding:2px 5px;margin-top:5px}#plugin_announcements_dialog article .actions .markread{float:right}#plugin_announcements_dialog article .actions a{color:#000}#plugin_announcements_dialog .modal-footer .configurelink{float:left}
|
||||
@@ -120,12 +120,13 @@ $(function() {
|
||||
};
|
||||
|
||||
self.fromResponse = function(data) {
|
||||
if (!self.loginState.isAdmin()) return;
|
||||
|
||||
var currentTab = $("li.active a", self.announcementDialogTabs).attr("href");
|
||||
|
||||
var unread = 0;
|
||||
var channels = [];
|
||||
_.each(data, function(value, key) {
|
||||
value.key = key;
|
||||
_.each(data.channels, function(value) {
|
||||
value.last = value.data.length ? value.data[0].published : undefined;
|
||||
value.count = value.data.length;
|
||||
unread += value.unread;
|
||||
@@ -140,6 +141,8 @@ $(function() {
|
||||
};
|
||||
|
||||
self.showAnnouncementDialog = function(channel) {
|
||||
if (!self.loginState.isAdmin()) return;
|
||||
|
||||
self.announcementDialogContent.scrollTop(0);
|
||||
|
||||
if (!self.announcementDialog.hasClass("in")) {
|
||||
@@ -172,6 +175,8 @@ $(function() {
|
||||
};
|
||||
|
||||
self.displayAnnouncements = function(channels) {
|
||||
if (!self.loginState.isAdmin()) return;
|
||||
|
||||
var displayLimit = self.settings.settings.plugins.announcements.display_limit();
|
||||
var maxLength = self.settings.settings.plugins.announcements.summary_limit();
|
||||
|
||||
@@ -222,7 +227,7 @@ $(function() {
|
||||
}
|
||||
var rest = newItems.length - displayedItems.length;
|
||||
|
||||
var text = "<ul>";
|
||||
var text = "<ul style='margin-top: 10px; margin-bottom: 10px'>";
|
||||
_.each(displayedItems, function(item) {
|
||||
var limitedSummary = stripParagraphs(item.summary_without_images.trim());
|
||||
if (limitedSummary.length > maxLength) {
|
||||
@@ -239,6 +244,8 @@ $(function() {
|
||||
text += gettext(_.sprintf("... and %(rest)d more.", {rest: rest}));
|
||||
}
|
||||
|
||||
text += "<small>" + gettext("You can edit your announcement subscriptions under Settings > Announcements.") + "</small>";
|
||||
|
||||
var options = {
|
||||
title: channel,
|
||||
text: text,
|
||||
@@ -284,10 +291,25 @@ $(function() {
|
||||
});
|
||||
};
|
||||
|
||||
self.hideAnnouncements = function() {
|
||||
_.each(self.channelNotifications, function(notification, key) {
|
||||
notification.remove();
|
||||
});
|
||||
self.channelNotifications = {};
|
||||
};
|
||||
|
||||
self.configureAnnouncements = function() {
|
||||
self.settings.show("settings_plugin_announcements");
|
||||
};
|
||||
|
||||
self.onUserLoggedIn = function() {
|
||||
self.retrieveData();
|
||||
};
|
||||
|
||||
self.onUserLoggedOut = function() {
|
||||
self.hideAnnouncements();
|
||||
};
|
||||
|
||||
self.onStartup = function() {
|
||||
self.announcementDialog = $("#plugin_announcements_dialog");
|
||||
self.announcementDialogContent = $("#plugin_announcements_dialog_content");
|
||||
|
||||
@@ -53,4 +53,10 @@ table {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.modal-footer {
|
||||
.configurelink {
|
||||
float: left;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -11,7 +11,7 @@
|
||||
<!-- ko foreach: {data: channels.items, afterAdd: setupTabLink} -->
|
||||
<!-- ko if: $data.enabled || $data.forced -->
|
||||
<li>
|
||||
<a data-toggle="tab" target="_blank" data-bind="text: $data.channel + ' (' + $data.unread + '/' + $data.count + ')', attr: {href: '#plugin_announcements_dialog_channel_' + $data.key}, css: {unread: $data.unread}"></a>
|
||||
<a data-toggle="tab" target="_blank" data-bind="text: $data.channel, attr: {href: '#plugin_announcements_dialog_channel_' + $data.key, title: $data.description}, css: {unread: $data.unread}"></a>
|
||||
</li>
|
||||
<!-- /ko -->
|
||||
<!-- /ko -->
|
||||
@@ -40,6 +40,7 @@
|
||||
</div>
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<button class="btn btn-block" data-dismiss="modal" aria-hidden="true">{{ _('Close') }}</button>
|
||||
<button class="btn configurelink" data-bind="click: configureAnnouncements"><i class="icon-wrench"></i></button>
|
||||
<button class="btn" data-dismiss="modal" aria-hidden="true">{{ _('Close') }}</button>
|
||||
</div>
|
||||
</div>
|
||||
@@ -10,7 +10,8 @@
|
||||
<tbody data-bind="foreach: channels.paginatedItems">
|
||||
<tr>
|
||||
<td class="settings_plugin_announcements_channels_name">
|
||||
<div data-bind="text: channel, css: {muted: !enabled}"></div>
|
||||
<div data-bind="css: {muted: !enabled}"><strong data-bind="text: channel"></strong></div>
|
||||
<div data-bind="text: description, css: {muted: !enabled}"></div>
|
||||
<div><small class="muted" data-bind="text: url"> </small></div>
|
||||
</td>
|
||||
<td class="settings_plugin_announcements_channels_actions">
|
||||
|
||||
@@ -173,5 +173,9 @@ class CoreWizardPlugin(octoprint.plugin.AssetPlugin,
|
||||
|
||||
|
||||
__plugin_name__ = "Core Wizard"
|
||||
__plugin_author__ = "Gina Häußge"
|
||||
__plugin_description__ = "Provides wizard dialogs for core components and functionality"
|
||||
__plugin_disabling_discouraged__ = gettext("Without this plugin OctoPrint will no longer be able to perform "
|
||||
"setup steps that might be required after an update.")
|
||||
__plugin_license__ = "AGPLv3"
|
||||
__plugin_implementation__ = CoreWizardPlugin()
|
||||
@@ -505,7 +505,7 @@ def _get_usage_from_length(filament_length, filament_diameter):
|
||||
|
||||
__plugin_name__ = "CuraEngine (<= 15.04)"
|
||||
__plugin_author__ = "Gina Häußge"
|
||||
__plugin_url__ = "https://github.com/foosel/OctoPrint/wiki/Plugin:-Cura"
|
||||
__plugin_url__ = "http://docs.octoprint.org/en/master/bundledplugins/cura.html"
|
||||
__plugin_description__ = "Adds support for slicing via CuraEngine versions up to and including version 15.04 from within OctoPrint"
|
||||
__plugin_license__ = "AGPLv3"
|
||||
__plugin_implementation__ = CuraPlugin()
|
||||
|
||||
@@ -12,6 +12,7 @@ The SSDP/UPNP implementations has been largely inspired by https://gist.github.c
|
||||
import logging
|
||||
import os
|
||||
import flask
|
||||
from flask_babel import gettext
|
||||
from builtins import range
|
||||
|
||||
import octoprint.plugin
|
||||
@@ -25,8 +26,10 @@ except:
|
||||
|
||||
__plugin_name__ = "Discovery"
|
||||
__plugin_author__ = "Gina Häußge"
|
||||
__plugin_url__ = "https://github.com/foosel/OctoPrint/wiki/Plugin:-Discovery"
|
||||
__plugin_url__ = "http://docs.octoprint.org/en/master/bundledplugins/discovery.html"
|
||||
__plugin_description__ = "Makes the OctoPrint instance discoverable via Bonjour/Avahi/Zeroconf and uPnP"
|
||||
__plugin_disabling_discouraged__ = gettext("Without this plugin your OctoPrint instance will no longer be "
|
||||
"discoverable on the network via Bonjour and uPnP.")
|
||||
__plugin_license__ = "AGPLv3"
|
||||
|
||||
def __plugin_load__():
|
||||
|
||||
@@ -17,6 +17,7 @@ from octoprint.util.pip import LocalPipCaller
|
||||
|
||||
from flask import jsonify, make_response
|
||||
from flask_babel import gettext
|
||||
from collections import OrderedDict
|
||||
|
||||
import logging
|
||||
import sarge
|
||||
@@ -24,6 +25,9 @@ import sys
|
||||
import re
|
||||
import os
|
||||
import pkg_resources
|
||||
import copy
|
||||
import dateutil.parser
|
||||
import time
|
||||
|
||||
class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
octoprint.plugin.TemplatePlugin,
|
||||
@@ -53,12 +57,19 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
self._repository_cache_path = None
|
||||
self._repository_cache_ttl = 0
|
||||
|
||||
self._notices = dict()
|
||||
self._notices_available = False
|
||||
self._notices_cache_path = None
|
||||
self._notices_cache_ttl = 0
|
||||
|
||||
self._console_logger = None
|
||||
|
||||
def initialize(self):
|
||||
self._console_logger = logging.getLogger("octoprint.plugins.pluginmanager.console")
|
||||
self._repository_cache_path = os.path.join(self.get_plugin_data_folder(), "plugins.json")
|
||||
self._repository_cache_ttl = self._settings.get_int(["repository_ttl"]) * 60
|
||||
self._notices_cache_path = os.path.join(self.get_plugin_data_folder(), "notices.json")
|
||||
self._notices_cache_ttl = self._settings.get_int(["notices_ttl"]) * 60
|
||||
|
||||
self._pip_caller = LocalPipCaller(force_user=self._settings.get_boolean(["pip_force_user"]))
|
||||
self._pip_caller.on_log_call = self._log_call
|
||||
@@ -84,6 +95,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
self._console_logger.propagate = False
|
||||
|
||||
self._repository_available = self._fetch_repository_from_disk()
|
||||
self._notices_available = self._fetch_notices_from_disk()
|
||||
|
||||
##~~ SettingsPlugin
|
||||
|
||||
@@ -91,6 +103,8 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
return dict(
|
||||
repository="http://plugins.octoprint.org/plugins.json",
|
||||
repository_ttl=24*60,
|
||||
notices="http://plugins.octoprint.org/notices.json",
|
||||
notices_ttl=6*60,
|
||||
pip_args=None,
|
||||
pip_force_user=False,
|
||||
dependency_links=False,
|
||||
@@ -101,6 +115,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
octoprint.plugin.SettingsPlugin.on_settings_save(self, data)
|
||||
|
||||
self._repository_cache_ttl = self._settings.get_int(["repository_ttl"]) * 60
|
||||
self._notices_cache_ttl = self._settings.get_int(["notices_ttl"]) * 60
|
||||
self._pip_caller.force_user = self._settings.get_boolean(["pip_force_user"])
|
||||
|
||||
##~~ AssetPlugin
|
||||
@@ -192,6 +207,10 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
if refresh_repository:
|
||||
self._repository_available = self._refresh_repository()
|
||||
|
||||
refresh_notices = request.values.get("refresh_notices", "false") in valid_boolean_trues
|
||||
if refresh_notices:
|
||||
self._notices_available = self._refresh_notices()
|
||||
|
||||
def view():
|
||||
return jsonify(plugins=self._get_plugins(),
|
||||
repository=dict(
|
||||
@@ -217,6 +236,8 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
hash.update(repr(self._get_plugins()))
|
||||
hash.update(str(self._repository_available))
|
||||
hash.update(repr(self._repository_plugins))
|
||||
hash.update(str(self._notices_available))
|
||||
hash.update(repr(self._notices))
|
||||
hash.update(repr(safe_mode))
|
||||
return hash.hexdigest()
|
||||
|
||||
@@ -225,7 +246,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
|
||||
return with_revalidation_checking(etag_factory=lambda *args, **kwargs: etag(),
|
||||
condition=lambda *args, **kwargs: condition(),
|
||||
unless=lambda: refresh_repository)(view)()
|
||||
unless=lambda: refresh_repository or refresh_notices)(view)()
|
||||
|
||||
def on_api_command(self, command, data):
|
||||
if not Permissions.SETTINGS.can():
|
||||
@@ -240,7 +261,8 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
plugin_name = data["plugin"] if "plugin" in data else None
|
||||
return self.command_install(url=url,
|
||||
force="force" in data and data["force"] in valid_boolean_trues,
|
||||
dependency_links="dependency_links" in data and data["dependency_links"] in valid_boolean_trues,
|
||||
dependency_links="dependency_links" in data
|
||||
and data["dependency_links"] in valid_boolean_trues,
|
||||
reinstall=plugin_name)
|
||||
|
||||
elif command == "uninstall":
|
||||
@@ -261,37 +283,84 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
|
||||
def command_install(self, url=None, path=None, force=False, reinstall=None, dependency_links=False):
|
||||
if url is not None:
|
||||
pip_args = ["install", sarge.shell_quote(url)]
|
||||
source = url
|
||||
source_type = "url"
|
||||
already_installed_check = lambda line: url in line
|
||||
|
||||
elif path is not None:
|
||||
pip_args = ["install", sarge.shell_quote(path)]
|
||||
path = os.path.abspath(path)
|
||||
path_url = "file://" + path
|
||||
if os.sep != "/":
|
||||
# windows gets special handling
|
||||
path = path.replace(os.sep, "/").lower()
|
||||
path_url = "file:///" + path
|
||||
|
||||
source = path
|
||||
source_type = "path"
|
||||
already_installed_check = lambda line: path_url in line.lower() # lower case in case of windows
|
||||
|
||||
else:
|
||||
raise ValueError("Either URL or path must be provided")
|
||||
|
||||
self._logger.info("Installing plugin from {}".format(source))
|
||||
pip_args = ["install", sarge.shell_quote(source)]
|
||||
|
||||
if dependency_links or self._settings.get_boolean(["dependency_links"]):
|
||||
pip_args.append("--process-dependency-links")
|
||||
|
||||
all_plugins_before = self._plugin_manager.find_plugins()
|
||||
all_plugins_before = self._plugin_manager.find_plugins(existing=dict())
|
||||
|
||||
already_installed_string = "Requirement already satisfied (use --upgrade to upgrade)"
|
||||
success_string = "Successfully installed"
|
||||
failure_string = "Could not install"
|
||||
|
||||
try:
|
||||
returncode, stdout, stderr = self._call_pip(pip_args)
|
||||
|
||||
# pip's output for a package that is already installed looks something like any of these:
|
||||
#
|
||||
# Requirement already satisfied (use --upgrade to upgrade): OctoPrint-Plugin==1.0 from \
|
||||
# https://example.com/foobar.zip in <lib>
|
||||
# Requirement already satisfied (use --upgrade to upgrade): OctoPrint-Plugin in <lib>
|
||||
# Requirement already satisfied (use --upgrade to upgrade): OctoPrint-Plugin==1.0 from \
|
||||
# file:///tmp/foobar.zip in <lib>
|
||||
# Requirement already satisfied (use --upgrade to upgrade): OctoPrint-Plugin==1.0 from \
|
||||
# file:///C:/Temp/foobar.zip in <lib>
|
||||
#
|
||||
# If we detect any of these matching what we just tried to install, we'll need to trigger a second
|
||||
# install with reinstall flags.
|
||||
|
||||
if not force and any(map(lambda x: x.strip().startswith(already_installed_string) and already_installed_check(x),
|
||||
stdout)):
|
||||
self._logger.info("Plugin to be installed from {} was already installed, forcing a reinstall".format(source))
|
||||
self._log_message("Looks like the plugin was already installed. Forcing a reinstall.")
|
||||
force = True
|
||||
except:
|
||||
self._logger.exception("Could not install plugin from %s" % url)
|
||||
return make_response("Could not install plugin from URL, see the log for more details", 500)
|
||||
else:
|
||||
if force:
|
||||
# We don't use --upgrade here because that will also happily update all our dependencies - we'd rather
|
||||
# do that in a controlled manner
|
||||
pip_args += ["--ignore-installed", "--force-reinstall", "--no-deps"]
|
||||
try:
|
||||
returncode, stdout, stderr = self._call_pip(pip_args)
|
||||
except:
|
||||
self._logger.exception("Could not install plugin from %s" % url)
|
||||
return make_response("Could not install plugin from URL, see the log for more details", 500)
|
||||
self._logger.exception("Could not install plugin from {}".format(source))
|
||||
return make_response("Could not install plugin from source {}, see the log for more details"
|
||||
.format(source), 500)
|
||||
|
||||
try:
|
||||
result_line = filter(lambda x: x.startswith(success_string) or x.startswith(failure_string), stdout)[-1]
|
||||
result_line = filter(lambda x: x.startswith(success_string) or x.startswith(failure_string),
|
||||
stdout)[-1]
|
||||
except IndexError:
|
||||
result = dict(result=False, reason="Could not parse output from pip")
|
||||
self._logger.error("Installing the plugin from {} failed, could not parse output from pip. "
|
||||
"See plugin_pluginmanager_console.log for generated output".format(source))
|
||||
result = dict(result=False,
|
||||
source=source,
|
||||
source_type=source_type,
|
||||
reason="Could not parse output from pip, see plugin_pluginmanager_console.log "
|
||||
"for generated output")
|
||||
self._send_result_notification("install", result)
|
||||
return jsonify(result)
|
||||
|
||||
@@ -304,8 +373,8 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
# Successfully installed OctoPrint-Plugin Dependency-One Dependency-Two
|
||||
# Cleaning up...
|
||||
#
|
||||
# So we'll need to fetch the "Successfully installed" line, strip the "Successfully" part, then split by whitespace
|
||||
# and strip to get all installed packages.
|
||||
# So we'll need to fetch the "Successfully installed" line, strip the "Successfully" part, then split
|
||||
# by whitespace and strip to get all installed packages.
|
||||
#
|
||||
# We then need to iterate over all known plugins and see if either the package name or the package name plus
|
||||
# version number matches one of our installed packages. If it does, that's our installed plugin.
|
||||
@@ -317,58 +386,54 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
|
||||
result_line = result_line.strip()
|
||||
if not result_line.startswith(success_string):
|
||||
result = dict(result=False, reason="Pip did not report successful installation")
|
||||
self._logger.error("Installing the plugin from {} failed, pip did not report successful installation"
|
||||
.format(source))
|
||||
result = dict(result=False,
|
||||
source=source,
|
||||
source_type=source_type,
|
||||
reason="Pip did not report successful installation")
|
||||
self._send_result_notification("install", result)
|
||||
return jsonify(result)
|
||||
|
||||
installed = map(lambda x: x.strip(), result_line[len(success_string):].split(" "))
|
||||
all_plugins_after = self._plugin_manager.find_plugins(existing=dict(), ignore_uninstalled=False)
|
||||
|
||||
for key, plugin in all_plugins_after.items():
|
||||
if plugin.origin is None or plugin.origin.type != "entry_point":
|
||||
continue
|
||||
|
||||
package_name = plugin.origin.package_name
|
||||
package_version = plugin.origin.package_version
|
||||
versioned_package = "{package_name}-{package_version}".format(**locals())
|
||||
|
||||
if package_name in installed or versioned_package in installed:
|
||||
# exact match, we are done here
|
||||
new_plugin_key = key
|
||||
new_plugin = plugin
|
||||
break
|
||||
|
||||
else:
|
||||
# it might still be a version that got stripped by python's package resources, e.g. 1.4.5a0 => 1.4.5a
|
||||
found = False
|
||||
|
||||
for inst in installed:
|
||||
if inst.startswith(versioned_package):
|
||||
found = True
|
||||
break
|
||||
|
||||
if found:
|
||||
new_plugin_key = key
|
||||
new_plugin = plugin
|
||||
break
|
||||
else:
|
||||
self._logger.warn("The plugin was installed successfully, but couldn't be found afterwards to initialize properly during runtime. Please restart OctoPrint.")
|
||||
result = dict(result=True, url=url, needs_restart=True, needs_refresh=True, was_reinstalled=False, plugin="unknown")
|
||||
new_plugin = self._find_installed_plugin(installed, plugins=all_plugins_after)
|
||||
if new_plugin is None:
|
||||
self._logger.warn("The plugin was installed successfully, but couldn't be found afterwards to "
|
||||
"initialize properly during runtime. Please restart OctoPrint.")
|
||||
result = dict(result=True,
|
||||
source=source,
|
||||
source_type=source_type,
|
||||
needs_restart=True,
|
||||
needs_refresh=True,
|
||||
was_reinstalled=False,
|
||||
plugin="unknown")
|
||||
self._send_result_notification("install", result)
|
||||
return jsonify(result)
|
||||
|
||||
self._plugin_manager.reload_plugins()
|
||||
needs_restart = self._plugin_manager.is_restart_needing_plugin(new_plugin) or new_plugin_key in all_plugins_before or reinstall is not None
|
||||
needs_refresh = new_plugin.implementation and isinstance(new_plugin.implementation, octoprint.plugin.ReloadNeedingPlugin)
|
||||
needs_restart = self._plugin_manager.is_restart_needing_plugin(new_plugin) \
|
||||
or new_plugin.key in all_plugins_before \
|
||||
or reinstall is not None
|
||||
needs_refresh = new_plugin.implementation \
|
||||
and isinstance(new_plugin.implementation, octoprint.plugin.ReloadNeedingPlugin)
|
||||
|
||||
is_reinstall = self._plugin_manager.is_plugin_marked(new_plugin_key, "uninstalled")
|
||||
self._plugin_manager.mark_plugin(new_plugin_key,
|
||||
is_reinstall = self._plugin_manager.is_plugin_marked(new_plugin.key, "uninstalled")
|
||||
self._plugin_manager.mark_plugin(new_plugin.key,
|
||||
uninstalled=False,
|
||||
installed=not is_reinstall and needs_restart)
|
||||
|
||||
self._plugin_manager.log_all_plugins()
|
||||
|
||||
result = dict(result=True, url=url, needs_restart=needs_restart, needs_refresh=needs_refresh, was_reinstalled=new_plugin_key in all_plugins_before or reinstall is not None, plugin=self._to_external_representation(new_plugin))
|
||||
self._logger.info("The plugin was installed successfully: {}, version {}".format(new_plugin.name, new_plugin.version))
|
||||
result = dict(result=True,
|
||||
source=source,
|
||||
source_type=source_type,
|
||||
needs_restart=needs_restart,
|
||||
needs_refresh=needs_refresh,
|
||||
was_reinstalled=new_plugin.key in all_plugins_before or reinstall is not None,
|
||||
plugin=self._to_external_plugin(new_plugin))
|
||||
self._send_result_notification("install", result)
|
||||
return jsonify(result)
|
||||
|
||||
@@ -448,7 +513,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
|
||||
self._plugin_manager.reload_plugins()
|
||||
|
||||
result = dict(result=True, needs_restart=needs_restart, needs_refresh=needs_refresh, plugin=self._to_external_representation(plugin))
|
||||
result = dict(result=True, needs_restart=needs_restart, needs_refresh=needs_refresh, plugin=self._to_external_plugin(plugin))
|
||||
self._send_result_notification("uninstall", result)
|
||||
return jsonify(result)
|
||||
|
||||
@@ -473,13 +538,49 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
self._logger.exception(u"Problem toggling enabled state of {name}: {reason}".format(name=plugin.key, reason=e.reason))
|
||||
result = dict(result=False, reason=e.reason)
|
||||
except octoprint.plugin.core.PluginNeedsRestart:
|
||||
result = dict(result=True, needs_restart=True, needs_refresh=True, plugin=self._to_external_representation(plugin))
|
||||
result = dict(result=True,
|
||||
needs_restart=True,
|
||||
needs_refresh=True,
|
||||
plugin=self._to_external_plugin(plugin))
|
||||
else:
|
||||
result = dict(result=True, needs_restart=needs_restart_api, needs_refresh=needs_refresh_api, plugin=self._to_external_representation(plugin))
|
||||
result = dict(result=True,
|
||||
needs_restart=needs_restart_api,
|
||||
needs_refresh=needs_refresh_api,
|
||||
plugin=self._to_external_plugin(plugin))
|
||||
|
||||
self._send_result_notification(command, result)
|
||||
return jsonify(result)
|
||||
|
||||
def _find_installed_plugin(self, packages, plugins=None):
|
||||
if plugins is None:
|
||||
plugins = self._plugin_manager.find_plugins(existing=dict(), ignore_uninstalled=False)
|
||||
|
||||
for key, plugin in plugins.items():
|
||||
if plugin.origin is None or plugin.origin.type != "entry_point":
|
||||
continue
|
||||
|
||||
package_name = plugin.origin.package_name
|
||||
package_version = plugin.origin.package_version
|
||||
versioned_package = "{package_name}-{package_version}".format(**locals())
|
||||
|
||||
if package_name in packages or versioned_package in packages:
|
||||
# exact match, we are done here
|
||||
return plugin
|
||||
|
||||
else:
|
||||
# it might still be a version that got stripped by python's package resources, e.g. 1.4.5a0 => 1.4.5a
|
||||
found = False
|
||||
|
||||
for inst in packages:
|
||||
if inst.startswith(versioned_package):
|
||||
found = True
|
||||
break
|
||||
|
||||
if found:
|
||||
return plugin
|
||||
|
||||
return None
|
||||
|
||||
def _send_result_notification(self, action, result):
|
||||
notification = dict(type="result", action=action)
|
||||
notification.update(result)
|
||||
@@ -572,7 +673,6 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
return self._refresh_repository(repo_data=repo_data)
|
||||
|
||||
def _fetch_repository_from_url(self):
|
||||
import requests
|
||||
repository_url = self._settings.get(["repository"])
|
||||
try:
|
||||
r = requests.get(repository_url)
|
||||
@@ -602,7 +702,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
octoprint_version = self._get_octoprint_version(base=True)
|
||||
|
||||
def map_repository_entry(entry):
|
||||
result = dict(entry)
|
||||
result = copy.deepcopy(entry)
|
||||
|
||||
if not "follow_dependency_links" in result:
|
||||
result["follow_dependency_links"] = False
|
||||
@@ -624,6 +724,69 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
self._repository_plugins = map(map_repository_entry, repo_data)
|
||||
return True
|
||||
|
||||
def _fetch_notices_from_disk(self):
|
||||
notice_data = None
|
||||
if os.path.isfile(self._notices_cache_path):
|
||||
import time
|
||||
mtime = os.path.getmtime(self._notices_cache_path)
|
||||
if mtime + self._notices_cache_ttl >= time.time() > mtime:
|
||||
try:
|
||||
import json
|
||||
with open(self._notices_cache_path) as f:
|
||||
notice_data = json.load(f)
|
||||
self._logger.info("Loaded notices from disk, was still valid")
|
||||
except:
|
||||
self._logger.exception("Error while loading notices from {}".format(self._notices_cache_path))
|
||||
|
||||
return self._refresh_notices(notice_data=notice_data)
|
||||
|
||||
def _fetch_notices_from_url(self):
|
||||
notices_url = self._settings.get(["notices"])
|
||||
try:
|
||||
r = requests.get(notices_url)
|
||||
self._logger.info("Loaded plugin notices data from {}".format(notices_url))
|
||||
except Exception as e:
|
||||
self._logger.exception("Could not fetch notices from {notices_url}: {message}".format(notices_url=notices_url, message=str(e)))
|
||||
return None
|
||||
|
||||
notice_data = r.json()
|
||||
|
||||
try:
|
||||
import json
|
||||
with octoprint.util.atomic_write(self._notices_cache_path, "wb") as f:
|
||||
json.dump(notice_data, f)
|
||||
except Exception as e:
|
||||
self._logger.exception("Error while saving notices to {}: {}".format(self._notices_cache_path, str(e)))
|
||||
return notice_data
|
||||
|
||||
def _refresh_notices(self, notice_data=None):
|
||||
if notice_data is None:
|
||||
notice_data = self._fetch_notices_from_url()
|
||||
if notice_data is None:
|
||||
return False
|
||||
|
||||
notices = dict()
|
||||
for notice in notice_data:
|
||||
if not "plugin" in notice or not "text" in notice or not "date" in notice:
|
||||
continue
|
||||
|
||||
key = notice["plugin"]
|
||||
|
||||
try:
|
||||
parsed_date = dateutil.parser.parse(notice["date"])
|
||||
notice["timestamp"] = parsed_date.timetuple()
|
||||
except Exception as e:
|
||||
self._logger.warn("Error while parsing date {!r} for plugin notice "
|
||||
"of plugin {}, ignoring notice: {}".format(notice["date"], key, str(e)))
|
||||
continue
|
||||
|
||||
if not key in notices:
|
||||
notices[key] = []
|
||||
notices[key].append(notice)
|
||||
|
||||
self._notices = notices
|
||||
return True
|
||||
|
||||
def _is_octoprint_compatible(self, octoprint_version, compatibility_entries):
|
||||
"""
|
||||
Tests if the current ``octoprint_version`` is compatible to any of the provided ``compatibility_entries``.
|
||||
@@ -694,18 +857,19 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
|
||||
hidden = self._settings.get(["hidden"])
|
||||
result = []
|
||||
for name, plugin in plugins.items():
|
||||
if name in hidden:
|
||||
for key, plugin in plugins.items():
|
||||
if key in hidden:
|
||||
continue
|
||||
result.append(self._to_external_representation(plugin))
|
||||
result.append(self._to_external_plugin(plugin))
|
||||
|
||||
return result
|
||||
|
||||
def _to_external_representation(self, plugin):
|
||||
def _to_external_plugin(self, plugin):
|
||||
return dict(
|
||||
key=plugin.key,
|
||||
name=plugin.name,
|
||||
description=plugin.description,
|
||||
disabling_discouraged=gettext(plugin.disabling_discouraged) if plugin.disabling_discouraged else False,
|
||||
author=plugin.author,
|
||||
version=plugin.version,
|
||||
url=plugin.url,
|
||||
@@ -719,12 +883,45 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
pending_disable=((plugin.enabled or getattr(plugin, "safe_mode_enabled", False)) and plugin.key in self._pending_disable),
|
||||
pending_install=(self._plugin_manager.is_plugin_marked(plugin.key, "installed")),
|
||||
pending_uninstall=(self._plugin_manager.is_plugin_marked(plugin.key, "uninstalled")),
|
||||
origin=plugin.origin.type
|
||||
origin=plugin.origin.type,
|
||||
notifications = self._get_notifications(plugin)
|
||||
)
|
||||
|
||||
def _get_notifications(self, plugin):
|
||||
key = plugin.key
|
||||
if not plugin.enabled:
|
||||
return
|
||||
|
||||
if key not in self._notices:
|
||||
return
|
||||
|
||||
octoprint_version = self._get_octoprint_version(base=True)
|
||||
plugin_notifications = self._notices.get(key, [])
|
||||
|
||||
def filter_relevant(notification):
|
||||
return "text" in notification and "date" in notification and \
|
||||
("versions" not in notification or plugin.version in notification["versions"]) and \
|
||||
("octoversions" not in notification or self._is_octoprint_compatible(octoprint_version, notification["octoversions"]))
|
||||
|
||||
def map_notification(notification):
|
||||
return self._to_external_notification(key, notification)
|
||||
|
||||
return filter(lambda x: x is not None,
|
||||
map(map_notification,
|
||||
filter(filter_relevant,
|
||||
plugin_notifications)))
|
||||
|
||||
def _to_external_notification(self, key, notification):
|
||||
return dict(key=key,
|
||||
date=time.mktime(notification["timestamp"]),
|
||||
text=notification["text"],
|
||||
link=notification.get("link"),
|
||||
versions=notification.get("versions", []),
|
||||
important=notification.get("important", False))
|
||||
|
||||
__plugin_name__ = "Plugin Manager"
|
||||
__plugin_author__ = "Gina Häußge"
|
||||
__plugin_url__ = "https://github.com/foosel/OctoPrint/wiki/Plugin:-Plugin-Manager"
|
||||
__plugin_url__ = "http://docs.octoprint.org/en/master/bundledplugins/pluginmanager.html"
|
||||
__plugin_description__ = "Allows installing and managing OctoPrint plugins"
|
||||
__plugin_license__ = "AGPLv3"
|
||||
|
||||
|
||||
@@ -1 +1 @@
|
||||
table th.settings_plugin_plugin_manager_plugins_name,table td.settings_plugin_plugin_manager_plugins_name{text-overflow:ellipsis;text-align:left}table th.settings_plugin_plugin_manager_plugins_actions,table td.settings_plugin_plugin_manager_plugins_actions{text-align:center;width:80px}table th.settings_plugin_plugin_manager_plugins_actions a,table td.settings_plugin_plugin_manager_plugins_actions a{text-decoration:none;color:#000}table th.settings_plugin_plugin_manager_plugins_actions a.disabled,table td.settings_plugin_plugin_manager_plugins_actions a.disabled{color:#ccc;cursor:default}#settings_plugin_pluginmanager_repositorydialog .slimScrollDiv{margin-bottom:20px}#settings_plugin_pluginmanager_repositorydialog h4{position:relative}#settings_plugin_pluginmanager_repositorydialog h4 a.dropdown-toggle{color:inherit;text-decoration:none;font-size:14px}#settings_plugin_pluginmanager_repositorydialog h4 ul.dropdown-menu{font-size:14px}#settings_plugin_pluginmanager_repositorydialog .form-search{text-align:center;margin-bottom:5px!important}#settings_plugin_pluginmanager_repositorydialog .form-inline{padding:5px;padding-right:10px;margin-bottom:0}#settings_plugin_pluginmanager_repositorydialog .form-inline .help-block{margin-bottom:0;font-size:85%}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_unavailable{overflow:hidden;width:100%;height:300px;background-image:url("../img/repo_unavailable.png");text-align:center;display:table}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_unavailable div{display:table-cell;vertical-align:middle}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_list{overflow:hidden;width:auto;height:300px}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_list .entry{border-bottom:1px solid #ddd;padding:5px;padding-right:10px}#settings_plugin_pluginmanager_workingdialog_output .message{font-weight:bold}#settings_plugin_pluginmanager_workingdialog_output .stdout{color:#333}#settings_plugin_pluginmanager_workingdialog_output .stderr{color:#900}#settings_plugin_pluginmanager_workingdialog_output .call{color:#009}
|
||||
table td.settings_plugin_plugin_manager_plugins_name,table th.settings_plugin_plugin_manager_plugins_name{text-overflow:ellipsis;text-align:left}table td.settings_plugin_plugin_manager_plugins_actions,table th.settings_plugin_plugin_manager_plugins_actions{text-align:center;width:80px}table td.settings_plugin_plugin_manager_plugins_actions a,table th.settings_plugin_plugin_manager_plugins_actions a{text-decoration:none;color:#000}table td.settings_plugin_plugin_manager_plugins_actions a.disabled,table th.settings_plugin_plugin_manager_plugins_actions a.disabled{color:#ccc;cursor:default}#settings_plugin_pluginmanager_repositorydialog .slimScrollDiv{margin-bottom:20px}#settings_plugin_pluginmanager_repositorydialog h4{position:relative}#settings_plugin_pluginmanager_repositorydialog h4 a.dropdown-toggle{color:inherit;text-decoration:none;font-size:14px}#settings_plugin_pluginmanager_repositorydialog h4 ul.dropdown-menu{font-size:14px}#settings_plugin_pluginmanager_repositorydialog .form-search{text-align:center;margin-bottom:5px!important}#settings_plugin_pluginmanager_repositorydialog .form-inline{padding:5px 10px 5px 5px;margin-bottom:0}#settings_plugin_pluginmanager_repositorydialog .form-inline .help-block{margin-bottom:0;font-size:85%}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_unavailable{overflow:hidden;width:100%;height:300px;background-image:url(../img/repo_unavailable.png);text-align:center;display:table}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_unavailable div{display:table-cell;vertical-align:middle}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_list{overflow:hidden;width:auto;height:300px}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_list .entry{border-bottom:1px solid #ddd;padding:5px 10px 5px 5px}#settings_plugin_pluginmanager_workingdialog_output .message{font-weight:700}#settings_plugin_pluginmanager_workingdialog_output .error{font-weight:700;color:#900}#settings_plugin_pluginmanager_workingdialog_output .stdout{color:#333}#settings_plugin_pluginmanager_workingdialog_output .stderr{color:#900}#settings_plugin_pluginmanager_workingdialog_output .call{color:#009}
|
||||
@@ -10,7 +10,20 @@
|
||||
};
|
||||
|
||||
OctoPrintPluginManagerClient.prototype.get = function(refresh, opts) {
|
||||
return this.base.get(this.base.getSimpleApiUrl("pluginmanager") + ((refresh) ? "?refresh_repository=true" : ""), opts);
|
||||
var refresh_repo, refresh_notices;
|
||||
if (_.isPlainObject(refresh)) {
|
||||
refresh_repo = refresh.repo || false;
|
||||
refresh_notices = refresh.notices || false;
|
||||
} else {
|
||||
refresh_repo = refresh;
|
||||
refresh_notices = false;
|
||||
}
|
||||
|
||||
var query = [];
|
||||
if (refresh_repo) query.push("refresh_repository=true");
|
||||
if (refresh_notices) query.push("refresh_notices=true");
|
||||
|
||||
return this.base.get(this.base.getSimpleApiUrl("pluginmanager") + ((query.length) ? "?" + query.join("&") : ""), opts);
|
||||
};
|
||||
|
||||
OctoPrintPluginManagerClient.prototype.getWithRefresh = function(opts) {
|
||||
@@ -80,6 +93,8 @@ $(function() {
|
||||
|
||||
self.config_repositoryUrl = ko.observable();
|
||||
self.config_repositoryTtl = ko.observable();
|
||||
self.config_noticesUrl = ko.observable();
|
||||
self.config_noticesTtl = ko.observable();
|
||||
self.config_pipAdditionalArgs = ko.observable();
|
||||
self.config_pipForceUser = ko.observable();
|
||||
|
||||
@@ -186,6 +201,20 @@ $(function() {
|
||||
});
|
||||
|
||||
self.notifications = [];
|
||||
self.noticeNotifications = [];
|
||||
self.hiddenNoticeNotifications = {};
|
||||
self.noticeCount = ko.observable(0);
|
||||
|
||||
self.noticeCountText = ko.pureComputed(function() {
|
||||
var count = self.noticeCount();
|
||||
if (count == 0) {
|
||||
return gettext("There are no plugin notices. Great!");
|
||||
} else if (count == 1) {
|
||||
return gettext("There is a plugin notice for one of your installed plugins.");
|
||||
} else {
|
||||
return _.sprintf(gettext("There are %(count)d plugin notices for one or more of your installed plugins."), {count: count});
|
||||
}
|
||||
});
|
||||
|
||||
self.enableManagement = ko.pureComputed(function() {
|
||||
return !self.printerState.isPrinting();
|
||||
@@ -251,7 +280,13 @@ $(function() {
|
||||
});
|
||||
},
|
||||
done: function(e, data) {
|
||||
self._markDone();
|
||||
var response = data.result;
|
||||
if (response.result) {
|
||||
self._markDone();
|
||||
} else {
|
||||
self._markDone(response.reason);
|
||||
}
|
||||
|
||||
self.uploadButton.unbind("click");
|
||||
self.uploadFilename(undefined);
|
||||
},
|
||||
@@ -262,7 +297,7 @@ $(function() {
|
||||
type: "error",
|
||||
hide: false
|
||||
});
|
||||
self._markDone();
|
||||
self._markDone("Could not install plugin, unknown error.");
|
||||
self.uploadButton.unbind("click");
|
||||
self.uploadFilename(undefined);
|
||||
}
|
||||
@@ -281,19 +316,36 @@ $(function() {
|
||||
return false;
|
||||
};
|
||||
|
||||
self.fromResponse = function(data) {
|
||||
self._fromPluginsResponse(data.plugins);
|
||||
self._fromRepositoryResponse(data.repository);
|
||||
self._fromPipResponse(data.pip);
|
||||
self.fromResponse = function(data, options) {
|
||||
self._fromPluginsResponse(data.plugins, options);
|
||||
self._fromRepositoryResponse(data.repository, options);
|
||||
self._fromPipResponse(data.pip, options);
|
||||
|
||||
self.safeMode(data.safe_mode || false);
|
||||
};
|
||||
|
||||
self._fromPluginsResponse = function(data) {
|
||||
self._fromPluginsResponse = function(data, options) {
|
||||
var evalNotices = options.eval_notices || false;
|
||||
var ignoreNoticeHidden = options.ignore_notice_hidden || false;
|
||||
var ignoreNoticeIgnored = options.ignore_notice_ignored || false;
|
||||
|
||||
if (evalNotices) self._removeAllNoticeNotifications();
|
||||
|
||||
var installedPlugins = [];
|
||||
var noticeCount = 0;
|
||||
_.each(data, function(plugin) {
|
||||
installedPlugins.push(plugin.key);
|
||||
|
||||
if (evalNotices && plugin.notifications && plugin.notifications.length) {
|
||||
_.each(plugin.notifications, function(notification) {
|
||||
noticeCount++;
|
||||
if (!ignoreNoticeIgnored && self._isNoticeNotificationIgnored(plugin.key, notification.date)) return;
|
||||
if (!ignoreNoticeHidden && self._isNoticeNotificationHidden(plugin.key, notification.date)) return;
|
||||
self._showPluginNotification(plugin, notification);
|
||||
});
|
||||
}
|
||||
});
|
||||
if (evalNotices) self.noticeCount(noticeCount);
|
||||
self.installedPlugins(installedPlugins);
|
||||
self.plugins.updateItems(data);
|
||||
};
|
||||
@@ -325,13 +377,28 @@ $(function() {
|
||||
}
|
||||
};
|
||||
|
||||
self.requestData = function(includeRepo) {
|
||||
self.requestData = function(options) {
|
||||
if (!self.loginState.hasPermission(self.permissions.SETTINGS)) {
|
||||
return;
|
||||
}
|
||||
|
||||
OctoPrint.plugins.pluginmanager.get(includeRepo)
|
||||
.done(self.fromResponse);
|
||||
if (!_.isPlainObject(options)) {
|
||||
options = {
|
||||
refresh_repo: options,
|
||||
refresh_notices: false,
|
||||
eval_notices: false
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
options.refresh_repo = options.refresh_repo || false;
|
||||
options.refresh_notices = options.refresh_notices || false;
|
||||
options.eval_notices = options.eval_notices || false;
|
||||
|
||||
OctoPrint.plugins.pluginmanager.get({repo: options.refresh_repo, notices: options.refresh_notices})
|
||||
.done(function(data) {
|
||||
self.fromResponse(data, options);
|
||||
});
|
||||
};
|
||||
|
||||
self.togglePlugin = function(data) {
|
||||
@@ -345,7 +412,9 @@ $(function() {
|
||||
|
||||
if (data.key == "pluginmanager") return;
|
||||
|
||||
var onSuccess = self.requestData,
|
||||
var onSuccess = function() {
|
||||
self.requestData();
|
||||
},
|
||||
onError = function() {
|
||||
new PNotify({
|
||||
title: gettext("Something went wrong"),
|
||||
@@ -361,9 +430,26 @@ $(function() {
|
||||
.done(onSuccess)
|
||||
.fail(onError);
|
||||
} else {
|
||||
OctoPrint.plugins.pluginmanager.disable(data.key)
|
||||
.done(onSuccess)
|
||||
.fail(onError);
|
||||
var perform = function() {
|
||||
OctoPrint.plugins.pluginmanager.disable(data.key)
|
||||
.done(onSuccess)
|
||||
.fail(onError);
|
||||
};
|
||||
|
||||
if (data.disabling_discouraged) {
|
||||
var message = _.sprintf(gettext("You are about to disable \"%(name)s\"."), {name: data.name})
|
||||
+ "</p><p>" + data.disabling_discouraged;
|
||||
showConfirmationDialog({
|
||||
title: gettext("This is not recommended"),
|
||||
message: message,
|
||||
question: gettext("Do you still want to disable it?"),
|
||||
cancel: gettext("Keep enabled"),
|
||||
proceed: gettext("Disable anyway"),
|
||||
onproceed: perform
|
||||
})
|
||||
} else {
|
||||
perform();
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
@@ -419,20 +505,23 @@ $(function() {
|
||||
}
|
||||
self._markWorking(workTitle, workText);
|
||||
|
||||
var onSuccess = function() {
|
||||
var onSuccess = function(response) {
|
||||
if (response.result) {
|
||||
self._markDone();
|
||||
} else {
|
||||
self._markDone(response.reason)
|
||||
}
|
||||
self.requestData();
|
||||
self.installUrl("");
|
||||
},
|
||||
onError = function() {
|
||||
self._markDone("Could not install plugin, unknown error, please consult octoprint.log for details");
|
||||
new PNotify({
|
||||
title: gettext("Something went wrong"),
|
||||
text: gettext("Please consult octoprint.log for details"),
|
||||
type: "error",
|
||||
hide: false
|
||||
});
|
||||
},
|
||||
onAlways = function() {
|
||||
self._markDone();
|
||||
};
|
||||
|
||||
if (reinstall) {
|
||||
@@ -463,7 +552,9 @@ $(function() {
|
||||
self._markWorking(gettext("Uninstalling plugin..."), _.sprintf(gettext("Uninstalling plugin \"%(name)s\""), {name: data.name}));
|
||||
|
||||
OctoPrint.plugins.pluginmanager.uninstall(data.key)
|
||||
.done(self.requestData)
|
||||
.done(function() {
|
||||
self.requestData();
|
||||
})
|
||||
.fail(function() {
|
||||
new PNotify({
|
||||
title: gettext("Something went wrong"),
|
||||
@@ -481,8 +572,23 @@ $(function() {
|
||||
if (!self.loginState.hasPermission(self.permissions.SETTINGS)) {
|
||||
return;
|
||||
}
|
||||
self.requestData({refresh_repo: true});
|
||||
};
|
||||
|
||||
self.requestData(true);
|
||||
self.refreshNotices = function() {
|
||||
if (!self.loginState.isAdmin()) {
|
||||
return;
|
||||
}
|
||||
|
||||
self.requestData({refresh_notices: true, eval_notices: true, ignore_notice_hidden: true, ignore_notice_ignored: true});
|
||||
};
|
||||
|
||||
self.reshowNotices = function() {
|
||||
if (!self.loginState.isAdmin()) {
|
||||
return;
|
||||
}
|
||||
|
||||
self.requestData({eval_notices: true, ignore_notice_hidden: true, ignore_notice_ignored: true});
|
||||
};
|
||||
|
||||
self.showPluginSettings = function() {
|
||||
@@ -503,6 +609,18 @@ $(function() {
|
||||
repositoryTtl = null;
|
||||
}
|
||||
|
||||
var notices = self.config_noticesUrl();
|
||||
if (notices != undefined && notices.trim() == "") {
|
||||
notices = null;
|
||||
}
|
||||
|
||||
var noticesTtl;
|
||||
try {
|
||||
noticesTtl = parseInt(self.config_noticesTtl());
|
||||
} catch (ex) {
|
||||
noticesTtl = null;
|
||||
}
|
||||
|
||||
var pipArgs = self.config_pipAdditionalArgs();
|
||||
if (pipArgs != undefined && pipArgs.trim() == "") {
|
||||
pipArgs = null;
|
||||
@@ -513,6 +631,8 @@ $(function() {
|
||||
pluginmanager: {
|
||||
repository: repository,
|
||||
repository_ttl: repositoryTtl,
|
||||
notices: notices,
|
||||
notices_ttl: noticesTtl,
|
||||
pip_args: pipArgs,
|
||||
pip_force_user: self.config_pipForceUser()
|
||||
}
|
||||
@@ -521,13 +641,15 @@ $(function() {
|
||||
self.settingsViewModel.saveData(data, function() {
|
||||
self.configurationDialog.modal("hide");
|
||||
self._copyConfig();
|
||||
self.refreshRepository();
|
||||
self.requestData({refresh_repo: true, refresh_notices: true, eval_notices: true});
|
||||
});
|
||||
};
|
||||
|
||||
self._copyConfig = function() {
|
||||
self.config_repositoryUrl(self.settingsViewModel.settings.plugins.pluginmanager.repository());
|
||||
self.config_repositoryTtl(self.settingsViewModel.settings.plugins.pluginmanager.repository_ttl());
|
||||
self.config_noticesUrl(self.settingsViewModel.settings.plugins.pluginmanager.notices());
|
||||
self.config_noticesTtl(self.settingsViewModel.settings.plugins.pluginmanager.notices_ttl());
|
||||
self.config_pipAdditionalArgs(self.settingsViewModel.settings.plugins.pluginmanager.pip_args());
|
||||
self.config_pipForceUser(self.settingsViewModel.settings.plugins.pluginmanager.pip_force_user());
|
||||
};
|
||||
@@ -541,7 +663,7 @@ $(function() {
|
||||
};
|
||||
|
||||
self.installButtonText = function(data) {
|
||||
return self.isCompatible(data) ? (self.installed(data) ? gettext("Reinstall") : gettext("Install")) : gettext("Incompatible");
|
||||
return self.isCompatible(data) ? (self.installed(data) ? gettext("Reinstall") : gettext("Install")) : (data.disabled ? gettext("Disabled") : gettext("Incompatible"));
|
||||
};
|
||||
|
||||
self._displayNotification = function(response, titleSuccess, textSuccess, textRestart, textReload, titleError, textError) {
|
||||
@@ -655,9 +777,14 @@ $(function() {
|
||||
self.workingDialog.modal({keyboard: false, backdrop: "static", show: true});
|
||||
};
|
||||
|
||||
self._markDone = function() {
|
||||
self._markDone = function(error) {
|
||||
self.working(false);
|
||||
self.loglines.push({line: gettext("Done!"), stream: "message"});
|
||||
if (error) {
|
||||
self.loglines.push({line: gettext("Error!"), stream: "error"});
|
||||
self.loglines.push({line: error, stream: "error"})
|
||||
} else {
|
||||
self.loglines.push({line: gettext("Done!"), stream: "message"});
|
||||
}
|
||||
self._scrollWorkingOutputToEnd();
|
||||
};
|
||||
|
||||
@@ -690,13 +817,189 @@ $(function() {
|
||||
}
|
||||
};
|
||||
|
||||
self.showPluginNotifications = function(plugin) {
|
||||
if (!plugin.notifications || plugin.notifications.length == 0) return;
|
||||
|
||||
self._removeAllNoticeNotificationsForPlugin(plugin.key);
|
||||
_.each(plugin.notifications, function(notification) {
|
||||
self._showPluginNotification(plugin, notification);
|
||||
});
|
||||
};
|
||||
|
||||
self.showPluginNotificationsLinkText = function(plugins) {
|
||||
if (!plugins.notifications || plugins.notifications.length == 0) return;
|
||||
|
||||
var count = plugins.notifications.length;
|
||||
var importantCount = _.filter(plugins.notifications, function(notification) { return notification.important }).length;
|
||||
if (count > 1) {
|
||||
if (importantCount) {
|
||||
return _.sprintf(gettext("There are %(count)d notices (%(important)d marked as important) available regarding this plugin - click to show!"), {count: count, important: importantCount});
|
||||
} else {
|
||||
return _.sprintf(gettext("There are %(count)d notices available regarding this plugin - click to show!"), {count: count});
|
||||
}
|
||||
} else {
|
||||
if (importantCount) {
|
||||
return gettext("There is an important notice available regarding this plugin - click to show!");
|
||||
} else {
|
||||
return gettext("There is a notice available regarding this plugin - click to show!");
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
self._showPluginNotification = function(plugin, notification) {
|
||||
var name = plugin.name;
|
||||
var version = plugin.version;
|
||||
|
||||
var important = notification.important;
|
||||
var link = notification.link;
|
||||
|
||||
var title;
|
||||
if (important) {
|
||||
title = _.sprintf(gettext("Important notice regarding plugin \"%(name)s\""), {name: name});
|
||||
} else {
|
||||
title = _.sprintf(gettext("Notice regarding plugin \"%(name)s\""), {name: name});
|
||||
}
|
||||
|
||||
var text = "";
|
||||
|
||||
if (notification.versions && notification.versions.length > 0) {
|
||||
var versions = _.map(notification.versions, function(v) { return (v == version) ? "<strong>" + v + "</strong>" : v; }).join(", ");
|
||||
text += "<small>" + _.sprintf(gettext("Affected versions: %(versions)s"), {versions: versions}) + "</small>";
|
||||
} else {
|
||||
text += "<small>" + gettext("Affected versions: all") + "</small>";
|
||||
}
|
||||
|
||||
text += "<p>" + notification.text + "</p>";
|
||||
if (link) {
|
||||
text += "<p><a href='" + link + "' target='_blank'>" + gettext("Read more...") + "</a></p>";
|
||||
}
|
||||
|
||||
var beforeClose = function(notification) {
|
||||
if (!self.noticeNotifications[plugin.key]) return;
|
||||
self.noticeNotifications[plugin.key] = _.without(self.noticeNotifications[plugin.key], notification);
|
||||
};
|
||||
|
||||
var options = {
|
||||
title: title,
|
||||
text: text,
|
||||
type: (important) ? "error" : "notice",
|
||||
before_close: beforeClose,
|
||||
hide: false,
|
||||
confirm: {
|
||||
confirm: true,
|
||||
buttons: [{
|
||||
text: gettext("Later"),
|
||||
click: function(notice) {
|
||||
self._hideNoticeNotification(plugin.key, notification.date);
|
||||
notice.remove();
|
||||
notice.get().trigger("pnotify.cancel", notice);
|
||||
}
|
||||
}, {
|
||||
text: gettext("Mark read"),
|
||||
click: function(notice) {
|
||||
self._ignoreNoticeNotification(plugin.key, notification.date);
|
||||
notice.remove();
|
||||
notice.get().trigger("pnotify.cancel", notice);
|
||||
}
|
||||
}]
|
||||
},
|
||||
buttons: {
|
||||
sticker: false,
|
||||
closer: false
|
||||
}
|
||||
};
|
||||
|
||||
if (!self.noticeNotifications[plugin.key]) {
|
||||
self.noticeNotifications[plugin.key] = [];
|
||||
}
|
||||
self.noticeNotifications[plugin.key].push(new PNotify(options));
|
||||
};
|
||||
|
||||
self._removeAllNoticeNotifications = function() {
|
||||
_.each(_.keys(self.noticeNotifications), function(key) {
|
||||
self._removeAllNoticeNotificationsForPlugin(key);
|
||||
});
|
||||
};
|
||||
|
||||
self._removeAllNoticeNotificationsForPlugin = function(key) {
|
||||
if (!self.noticeNotifications[key] || !self.noticeNotifications[key].length) return;
|
||||
_.each(self.noticeNotifications[key], function(notification) {
|
||||
notification.remove();
|
||||
});
|
||||
};
|
||||
|
||||
self._hideNoticeNotification = function(key, date) {
|
||||
if (!self.hiddenNoticeNotifications[key]) {
|
||||
self.hiddenNoticeNotifications[key] = [];
|
||||
}
|
||||
if (!_.contains(self.hiddenNoticeNotifications[key], date)) {
|
||||
self.hiddenNoticeNotifications[key].push(date);
|
||||
}
|
||||
};
|
||||
|
||||
self._isNoticeNotificationHidden = function(key, date) {
|
||||
if (!self.hiddenNoticeNotifications[key]) return false;
|
||||
return _.any(_.map(self.hiddenNoticeNotifications[key], function(d) { return date == d; }));
|
||||
};
|
||||
|
||||
var noticeLocalStorageKey = "plugin.pluginmanager.seen_notices";
|
||||
self._ignoreNoticeNotification = function(key, date) {
|
||||
if (!Modernizr.localstorage)
|
||||
return false;
|
||||
if (!self.loginState.isAdmin())
|
||||
return false;
|
||||
|
||||
var currentString = localStorage[noticeLocalStorageKey];
|
||||
var current;
|
||||
if (currentString === undefined) {
|
||||
current = {};
|
||||
} else {
|
||||
current = JSON.parse(currentString);
|
||||
}
|
||||
if (!current[self.loginState.username()]) {
|
||||
current[self.loginState.username()] = {};
|
||||
}
|
||||
if (!current[self.loginState.username()][key]) {
|
||||
current[self.loginState.username()][key] = [];
|
||||
}
|
||||
|
||||
if (!_.contains(current[self.loginState.username()][key], date)) {
|
||||
current[self.loginState.username()][key].push(date);
|
||||
localStorage[noticeLocalStorageKey] = JSON.stringify(current);
|
||||
}
|
||||
};
|
||||
|
||||
self._isNoticeNotificationIgnored = function(key, date) {
|
||||
if (!Modernizr.localstorage)
|
||||
return false;
|
||||
|
||||
if (localStorage[noticeLocalStorageKey] == undefined)
|
||||
return false;
|
||||
|
||||
var knownData = JSON.parse(localStorage[noticeLocalStorageKey]);
|
||||
|
||||
if (!self.loginState.isAdmin())
|
||||
return true;
|
||||
|
||||
var userData = knownData[self.loginState.username()];
|
||||
if (userData === undefined)
|
||||
return false;
|
||||
|
||||
return userData[key] && _.contains(userData[key], date);
|
||||
};
|
||||
|
||||
self.onBeforeBinding = function() {
|
||||
self.settings = self.settingsViewModel.settings;
|
||||
};
|
||||
|
||||
self.onUserLoggedIn = function(user) {
|
||||
<<<<<<< HEAD
|
||||
if (self.permissions.hasPermission(self.permissions.SETTINGS, user.permissions)) {
|
||||
self.requestData();
|
||||
=======
|
||||
if (user.admin) {
|
||||
self.requestData({eval_notices: true});
|
||||
>>>>>>> d1d94624236153c7a2cc7072d0527c6516f0daf7
|
||||
} else {
|
||||
self.onUserLoggedOut();
|
||||
}
|
||||
@@ -788,22 +1091,42 @@ $(function() {
|
||||
}
|
||||
|
||||
titleError = gettext("Something went wrong");
|
||||
var url = "unknown";
|
||||
if (data.hasOwnProperty("url")) {
|
||||
url = data.url;
|
||||
var source = "unknown";
|
||||
if (data.hasOwnProperty("source")) {
|
||||
source = data.source;
|
||||
}
|
||||
var sourceType = "unknown";
|
||||
if (data.hasOwnProperty("source_type")) {
|
||||
sourceType = data.source_type;
|
||||
}
|
||||
|
||||
if (data.hasOwnProperty("reason")) {
|
||||
if (data.was_reinstalled) {
|
||||
textError = _.sprintf(gettext("Reinstalling the plugin from URL \"%(url)s\" failed: %(reason)s"), {reason: data.reason, url: url});
|
||||
if (sourceType == "path") {
|
||||
textError = _.sprintf(gettext("Reinstalling the plugin from file failed: %(reason)s"), {reason: data.reason});
|
||||
} else {
|
||||
textError = _.sprintf(gettext("Reinstalling the plugin from \"%(source)s\" failed: %(reason)s"), {reason: data.reason, source: source});
|
||||
}
|
||||
} else {
|
||||
textError = _.sprintf(gettext("Installing the plugin from URL \"%(url)s\" failed: %(reason)s"), {reason: data.reason, url: url});
|
||||
if (sourceType == "path") {
|
||||
textError = _.sprintf(gettext("Installing the plugin from file failed: %(reason)s"), {reason: data.reason});
|
||||
} else {
|
||||
textError = _.sprintf(gettext("Installing the plugin from \"%(source)s\" failed: %(reason)s"), {reason: data.reason, source: source});
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if (data.was_reinstalled) {
|
||||
textError = _.sprintf(gettext("Reinstalling the plugin from URL \"%(url)s\" failed, please see the log for details."), {url: url});
|
||||
if (sourceType == "path") {
|
||||
textError = gettext("Reinstalling the plugin from file failed, please see the log for details.");
|
||||
} else {
|
||||
textError = _.sprintf(gettext("Reinstalling the plugin from \"%(source)s\" failed, please see the log for details."), {source: source});
|
||||
}
|
||||
} else {
|
||||
textError = _.sprintf(gettext("Installing the plugin from URL \"%(url)s\" failed, please see the log for details."), {url: url});
|
||||
if (sourceType == "path") {
|
||||
textError = gettext("Installing the plugin from file failed, please see the log for details.");
|
||||
} else {
|
||||
textError = _.sprintf(gettext("Installing the plugin from \"%(source)s\" failed, please see the log for details."), {source: source});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -89,6 +89,11 @@ table {
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
.error {
|
||||
font-weight: bold;
|
||||
color: #990000;
|
||||
}
|
||||
|
||||
.stdout {
|
||||
color: #333333;
|
||||
}
|
||||
|
||||
@@ -40,7 +40,8 @@
|
||||
<tbody data-bind="foreach: plugins.paginatedItems">
|
||||
<tr>
|
||||
<td class="settings_plugin_plugin_manager_plugins_name">
|
||||
<div data-bind="css: {muted: !enabled}"><span data-bind="text: name"></span> <span data-bind="visible: version">(<span data-bind="text: version"></span>)</span> <i title="{{ _('Bundled with OctoPrint') }}" class="icon-th-large" data-bind="visible: bundled"></i> <i class="icon-lock" title="{{ _('Cannot be uninstalled through OctoPrint') }}" data-bind="visible: !managable"></i> <i title="{{ _('Restart of OctoPrint needed for changes to take effect') }}" class="icon-refresh" data-bind="visible: pending_enable || pending_disable || pending_install || pending_uninstall"></i> <i title="{{ _('Pending install') }}" class="icon-plus" data-bind="visible: pending_install"></i> <i title="{{ _('Pending uninstall') }}" class="icon-minus" data-bind="visible: pending_uninstall"></i> <i title="{{ _('Disabled due to safe mode') }}" class="icon-medkit" data-bind="visible: safe_mode_victim"></i></div>
|
||||
<div data-bind="css: {muted: !enabled}"><span data-bind="text: name"></span> <span data-bind="visible: version">(<span data-bind="text: version"></span>)</span> <i title="{{ _('Bundled with OctoPrint') }}" class="icon-th-large" data-bind="visible: bundled"></i> <i class="icon-lock" title="{{ _('Cannot be uninstalled through OctoPrint') }}" data-bind="visible: !managable"></i> <i title="{{ _('Restart of OctoPrint needed for changes to take effect') }}" class="icon-refresh" data-bind="visible: pending_enable || pending_disable || pending_install || pending_uninstall"></i> <i title="{{ _('Pending install') }}" class="icon-plus" data-bind="visible: pending_install"></i> <i title="{{ _('Pending uninstall') }}" class="icon-minus" data-bind="visible: pending_uninstall"></i> <i title="{{ _('Disabled due to safe mode') }}" class="icon-medkit" data-bind="visible: safe_mode_victim"></i> <i class="icon-exclamation-sign" title="{{ _('There are notices available regarding this plugin') }}" data-bind="visible: notifications && notifications.length"></i></div>
|
||||
<div data-bind="visible: notifications && notifications.length"><a href="javascript:void(0)" class="text-error" style="text-decoration: underline" data-bind="click: function() { $root.showPluginNotifications($data) }, text: $root.showPluginNotificationsLinkText($data)"></a></div>
|
||||
<div><small class="muted" data-bind="text: description"> </small></div>
|
||||
<div data-bind="css: {muted: !enabled}">
|
||||
<small data-bind="visible: url"><i class="icon-home"></i> <a data-bind="attr: {href: url}" target="_blank" rel="noreferrer noopener">{{ _('Homepage') }}</a></small>
|
||||
@@ -72,7 +73,7 @@
|
||||
<div class="muted" data-bind="visible: pipAvailable()">
|
||||
<div>
|
||||
<small>
|
||||
<a href="#" class="muted" onclick="$(this).children('i.toggle-arrow').toggleClass('icon-caret-right icon-caret-down').parent().parent().parent().next().slideToggle('fast')">
|
||||
<a href="javascript:void(0)" class="muted" onclick="$(this).children('i.toggle-arrow').toggleClass('icon-caret-right icon-caret-down').parent().parent().parent().next().slideToggle('fast')">
|
||||
<i class="toggle-arrow icon-caret-right"></i> Using pip of "<span data-bind="text: pipPython"></span>", Version <span data-bind="text: pipVersion"></span>
|
||||
</a>
|
||||
</small>
|
||||
@@ -86,12 +87,28 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="muted">
|
||||
<div>
|
||||
<small>
|
||||
<a href="javascript:void(0)" class="muted" onclick="$(this).children('i.toggle-arrow').toggleClass('icon-caret-right icon-caret-down').parent().parent().parent().next().slideToggle('fast')">
|
||||
<i class="toggle-arrow icon-caret-right"></i> <span data-bind="text: noticeCountText"></span>
|
||||
</a>
|
||||
</small>
|
||||
</div>
|
||||
<div class="hide">
|
||||
<small>
|
||||
<!-- ko if: noticeCount() > 0 --><a href="javascript:void(0)" data-bind="click: function() { reshowNotices(); }">{{ _('Reshow current notices') }}</a> ·<!-- /ko -->
|
||||
<a href="javascript:void(0)" data-bind="click: function() { refreshNotices(); }">{{ _('Refresh notices from repository') }}</a>
|
||||
</small>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div id="settings_plugin_pluginmanager_workingdialog" class="modal hide fade">
|
||||
<div class="modal-header">
|
||||
<h3 data-bind="text: workingTitle"></h3>
|
||||
</div>
|
||||
<div class="modal-body">
|
||||
<pre id="settings_plugin_pluginmanager_workingdialog_output" class="terminal pre-scrollable" style="height: 170px" data-bind="foreach: loglines"><span data-bind="text: line, css: {stdout: stream == 'stdout', stderr: stream == 'stderr', call: stream == 'call', message: stream == 'message'}"></span><br></pre>
|
||||
<pre id="settings_plugin_pluginmanager_workingdialog_output" class="terminal pre-scrollable" style="height: 170px" data-bind="foreach: loglines"><span data-bind="text: line, css: {stdout: stream == 'stdout', stderr: stream == 'stderr', call: stream == 'call', message: stream == 'message', error: stream == 'error'}"></span><br></pre>
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<button class="btn" data-dismiss="modal" data-bind="enable: !$root.working()" aria-hidden="true">{{ _('Close') }}</button>
|
||||
@@ -146,6 +163,7 @@
|
||||
</div>
|
||||
<div class="span3">
|
||||
<button class="btn btn-primary btn-block" data-bind="enable: $root.enableRepoInstall($data), css: {disabled: !$root.enableRepoInstall($data)}, click: function() { if ($root.enableRepoInstall($data)) { $root.installFromRepository($data); } else { return false; } }"><i class="icon-add"></i> <span data-bind="text: $root.installButtonText($data)"></span></button>
|
||||
<div data-bind="visible: $data.disabled !== undefined" style="text-align: center"><small><a data-bind="attr: {href: page}" target="_blank">{{ _('"Why?"') }}</a></small></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -237,6 +255,24 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<legend>{{ _('Notices configuration') }}</legend>
|
||||
|
||||
<div class="control-group" title="{{ _('URL of the Notices source to use. You should normally not have to change this.') }}">
|
||||
<label class="control-label">{{ _('Notices URL') }}</label>
|
||||
<div class="controls">
|
||||
<input type="text" class="input-block-level" data-bind="value: config_noticesUrl">
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group" title="{{ _('How long to cache notices, in minutes. You should normally not have to change this.') }}">
|
||||
<label class="control-label">{{ _('Notices cache TTL') }}</label>
|
||||
<div class="controls">
|
||||
<div class="input-append">
|
||||
<input type="number" class="input-mini" data-bind="value: config_noticesTtl">
|
||||
<span class="add-on">min</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<legend>{{ _('pip configuration') }}</legend>
|
||||
|
||||
<div class="control-group" title="{{ _('Additional arguments for the pip command. You should normally not have to change this.') }}">
|
||||
|
||||
@@ -18,6 +18,7 @@ import hashlib
|
||||
|
||||
from . import version_checks, updaters, exceptions, util, cli
|
||||
|
||||
from flask_babel import gettext
|
||||
|
||||
from octoprint.server.util.flask import restricted_access, with_revalidation_checking, check_etag
|
||||
from octoprint.server import VERSION, REVISION, BRANCH
|
||||
@@ -214,6 +215,8 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
"check_providers": {},
|
||||
|
||||
"cache_ttl": 24 * 60,
|
||||
|
||||
"notify_users": True
|
||||
}
|
||||
|
||||
def on_settings_load(self):
|
||||
@@ -261,7 +264,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
|
||||
def on_settings_save(self, data):
|
||||
for key in self.get_settings_defaults():
|
||||
if key in ("checks", "cache_ttl", "octoprint_checkout_folder", "octoprint_type", "octoprint_release_channel"):
|
||||
if key in ("checks", "cache_ttl", "notify_user", "octoprint_checkout_folder", "octoprint_type", "octoprint_release_channel"):
|
||||
continue
|
||||
if key in data:
|
||||
self._settings.set([key], data[key])
|
||||
@@ -270,6 +273,9 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
self._settings.set_int(["cache_ttl"], data["cache_ttl"])
|
||||
self._version_cache_ttl = self._settings.get_int(["cache_ttl"]) * 60
|
||||
|
||||
if "notify_users" in data:
|
||||
self._settings.set_boolean(["notify_users"], data["notify_users"])
|
||||
|
||||
checks = self._get_configured_checks()
|
||||
if "octoprint" in checks:
|
||||
check = checks["octoprint"]
|
||||
@@ -1041,8 +1047,11 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
|
||||
__plugin_name__ = "Software Update"
|
||||
__plugin_author__ = "Gina Häußge"
|
||||
__plugin_url__ = "https://github.com/foosel/OctoPrint/wiki/Plugin:-Software-Update"
|
||||
__plugin_url__ = "http://docs.octoprint.org/en/master/bundledplugins/softwareupdate.html"
|
||||
__plugin_description__ = "Allows receiving update notifications and performing updates of OctoPrint and plugins"
|
||||
__plugin_disabling_discouraged__ = gettext("Without this plugin OctoPrint will no longer be able to "
|
||||
"update itself or any of your installed plugins which might put "
|
||||
"your system at risk.")
|
||||
__plugin_license__ = "AGPLv3"
|
||||
def __plugin_load__():
|
||||
global __plugin_implementation__
|
||||
|
||||
@@ -113,6 +113,7 @@ $(function() {
|
||||
self.octoprintUnreleased = ko.observable();
|
||||
|
||||
self.config_cacheTtl = ko.observable();
|
||||
self.config_notifyUsers = ko.observable();
|
||||
self.config_checkoutFolder = ko.observable();
|
||||
self.config_checkType = ko.observable();
|
||||
self.config_updateMethod = ko.observable();
|
||||
@@ -154,9 +155,20 @@ $(function() {
|
||||
self.performCheck();
|
||||
};
|
||||
|
||||
self._showPopup = function(options, eventListeners) {
|
||||
self.onUserLoggedOut = function() {
|
||||
self._closePopup();
|
||||
self.popup = new PNotify(options);
|
||||
};
|
||||
|
||||
self._showPopup = function(options, eventListeners, singleButtonNotify) {
|
||||
singleButtonNotify = singleButtonNotify || false;
|
||||
|
||||
self._closePopup();
|
||||
|
||||
if (singleButtonNotify) {
|
||||
self.popup = PNotify.singleButtonNotify(options);
|
||||
} else {
|
||||
self.popup = new PNotify(options);
|
||||
}
|
||||
|
||||
if (eventListeners) {
|
||||
var popupObj = self.popup.get();
|
||||
@@ -193,6 +205,7 @@ $(function() {
|
||||
plugins: {
|
||||
softwareupdate: {
|
||||
cache_ttl: parseInt(self.config_cacheTtl()),
|
||||
notify_users: self.config_notifyUsers(),
|
||||
octoprint_checkout_folder: self.config_checkoutFolder(),
|
||||
octoprint_type: self.config_checkType(),
|
||||
octoprint_release_channel: self.config_releaseChannel()
|
||||
@@ -232,6 +245,7 @@ $(function() {
|
||||
|
||||
self.config_updateMethod(updateMethod);
|
||||
self.config_cacheTtl(self.settings.settings.plugins.softwareupdate.cache_ttl());
|
||||
self.config_notifyUsers(self.settings.settings.plugins.softwareupdate.notify_users());
|
||||
self.config_checkoutFolder(self.settings.settings.plugins.softwareupdate.octoprint_checkout_folder());
|
||||
self.config_checkType(self.settings.settings.plugins.softwareupdate.octoprint_type());
|
||||
self.config_releaseChannel(self.settings.settings.plugins.softwareupdate.octoprint_release_channel());
|
||||
@@ -289,6 +303,8 @@ $(function() {
|
||||
}
|
||||
}
|
||||
|
||||
if (!self.loginState.isAdmin() && !self.settings.settings.plugins.softwareupdate.notify_users()) return;
|
||||
|
||||
if (data.status == "updateAvailable" || data.status == "updatePossible") {
|
||||
var text = "<div class='softwareupdate_notification'>" + gettext("There are updates available for the following components:");
|
||||
|
||||
@@ -304,7 +320,11 @@ $(function() {
|
||||
});
|
||||
text += "</ul>";
|
||||
|
||||
text += "<small>" + gettext("Those components marked with <i class=\"icon-ok\"></i> can be updated directly.") + "</small>";
|
||||
text += "<p><small>" + gettext("Those components marked with <i class=\"icon-ok\"></i> can be updated directly.") + "</small></p>";
|
||||
|
||||
if (!self.loginState.isAdmin()) {
|
||||
text += "<p><small>" + gettext("To have updates applied, get in touch with an administrator of this OctoPrint instance.") + "</small></p>";
|
||||
}
|
||||
|
||||
text += "</div>";
|
||||
|
||||
@@ -315,8 +335,9 @@ $(function() {
|
||||
};
|
||||
var eventListeners = {};
|
||||
|
||||
var singleButtonNotify = false;
|
||||
if (data.status == "updatePossible" && self.loginState.isAdmin()) {
|
||||
// if user is admin, add action buttons
|
||||
// if update is possible and user is admin, add action buttons for ignore and update
|
||||
options["confirm"] = {
|
||||
confirm: true,
|
||||
buttons: [{
|
||||
@@ -337,10 +358,27 @@ $(function() {
|
||||
closer: false,
|
||||
sticker: false
|
||||
};
|
||||
} else {
|
||||
// if update is not possible or user is not admin, only add ignore button
|
||||
options["confirm"] = {
|
||||
confirm: true,
|
||||
buttons: [{
|
||||
text: gettext("Ignore"),
|
||||
click: function(notice) {
|
||||
notice.remove();
|
||||
self._markNotificationAsSeen(data.information);
|
||||
}
|
||||
}]
|
||||
};
|
||||
options["buttons"] = {
|
||||
closer: false,
|
||||
sticker: false
|
||||
};
|
||||
singleButtonNotify = true;
|
||||
}
|
||||
|
||||
if ((ignoreSeen || !self._hasNotificationBeenSeen(data.information)) && !OctoPrint.coreui.wizardOpen) {
|
||||
self._showPopup(options, eventListeners);
|
||||
self._showPopup(options, eventListeners, singleButtonNotify);
|
||||
}
|
||||
} else if (data.status == "current") {
|
||||
if (showIfNothingNew) {
|
||||
@@ -356,7 +394,9 @@ $(function() {
|
||||
};
|
||||
|
||||
self.performCheck = function(showIfNothingNew, force, ignoreSeen) {
|
||||
if (!self.loginState.hasPermission(self.permissions.SETTINGS)) return;
|
||||
|
||||
if (!self.loginState.hasPermission(self.permissions.SETTINGS) && !self.settings.settings.plugins.softwareupdate.notify_users()) return;
|
||||
|
||||
self.checking(true);
|
||||
OctoPrint.plugins.softwareupdate.check(force)
|
||||
.done(function(data) {
|
||||
@@ -370,7 +410,18 @@ $(function() {
|
||||
self._markNotificationAsSeen = function(data) {
|
||||
if (!Modernizr.localstorage)
|
||||
return false;
|
||||
localStorage["plugin.softwareupdate.seen_information"] = JSON.stringify(self._informationToRemoteVersions(data));
|
||||
if (!self.loginState.isUser())
|
||||
return false;
|
||||
|
||||
var currentString = localStorage["plugin.softwareupdate.seen_information"];
|
||||
var current;
|
||||
if (currentString === undefined) {
|
||||
current = {};
|
||||
} else {
|
||||
current = JSON.parse(currentString);
|
||||
}
|
||||
current[self.loginState.username()] = self._informationToRemoteVersions(data);
|
||||
localStorage["plugin.softwareupdate.seen_information"] = JSON.stringify(current);
|
||||
};
|
||||
|
||||
self._hasNotificationBeenSeen = function(data) {
|
||||
@@ -381,11 +432,19 @@ $(function() {
|
||||
return false;
|
||||
|
||||
var knownData = JSON.parse(localStorage["plugin.softwareupdate.seen_information"]);
|
||||
|
||||
if (!self.loginState.isUser())
|
||||
return true;
|
||||
|
||||
var userData = knownData[self.loginState.username()];
|
||||
if (userData === undefined)
|
||||
return false;
|
||||
|
||||
var freshData = self._informationToRemoteVersions(data);
|
||||
|
||||
var hasBeenSeen = true;
|
||||
_.each(freshData, function(value, key) {
|
||||
if (!_.has(knownData, key) || knownData[key] != freshData[key]) {
|
||||
if (!_.has(userData, key) || userData[key] != freshData[key]) {
|
||||
hasBeenSeen = false;
|
||||
}
|
||||
});
|
||||
@@ -401,6 +460,8 @@ $(function() {
|
||||
};
|
||||
|
||||
self.performUpdate = function(force, items) {
|
||||
if (!self.loginState.isAdmin()) return;
|
||||
|
||||
self.updateInProgress = true;
|
||||
|
||||
var options = {
|
||||
@@ -706,7 +767,10 @@ $(function() {
|
||||
}
|
||||
};
|
||||
|
||||
self._forcedStdoutLine = /You are using pip version .*?, however version .*? is available\.|You should consider upgrading via the '.*?' command\./;
|
||||
self._forcedStdoutPatterns = ["You are using pip version .*?, however version .*? is available\.",
|
||||
"You should consider upgrading via the '.*?' command\.",
|
||||
"'.*?' does not exist -- can't clean it"];
|
||||
self._forcedStdoutLine = new RegExp(self._forcedStdoutPatterns.join("|"));
|
||||
self._preprocessLine = function(line) {
|
||||
if (line.stream == "stderr" && line.line.match(self._forcedStdoutLine)) {
|
||||
line.stream = "stdout";
|
||||
|
||||
@@ -86,6 +86,14 @@
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group">
|
||||
<div class="controls">
|
||||
<label class="checkbox">
|
||||
<input type="checkbox" data-bind="checked: config_notifyUsers"> {{ _('Show update notifications to users') }}
|
||||
<span class="help-block">{{ _('If you uncheck this, only logged in admins will see update notifications. Update notifications shown to users do not include the "Update now" button.') }}</span>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
|
||||
@@ -25,7 +25,8 @@ class VirtualPrinter(object):
|
||||
sleep_after_regex = re.compile("sleep_after ([GMTF]\d+) (\d+)")
|
||||
sleep_after_next_regex = re.compile("sleep_after_next ([GMTF]\d+) (\d+)")
|
||||
custom_action_regex = re.compile("action_custom ([a-zA-Z0-9_]+)(\s+.*)?")
|
||||
prepare_ok_regex = re.compile("prepare_ok (.*)?")
|
||||
prepare_ok_regex = re.compile("prepare_ok (.*)")
|
||||
send_regex = re.compile("send (.*)")
|
||||
|
||||
def __init__(self, seriallog_handler=None, read_timeout=5.0, write_timeout=10.0):
|
||||
import logging
|
||||
@@ -107,8 +108,11 @@ class VirtualPrinter(object):
|
||||
|
||||
self._brokenM29 = settings().getBoolean(["devel", "virtualPrinter", "brokenM29"])
|
||||
|
||||
self._m115FormatString = settings().get(["devel", "virtualPrinter", "m115FormatString"])
|
||||
self._firmwareName = settings().get(["devel", "virtualPrinter", "firmwareName"])
|
||||
|
||||
self._okFormatString = settings().get(["devel", "virtualPrinter", "okFormatString"])
|
||||
|
||||
self.currentLine = 0
|
||||
self.lastN = 0
|
||||
|
||||
@@ -398,7 +402,7 @@ class VirtualPrinter(object):
|
||||
return True
|
||||
|
||||
def _gcode_M115(self, data):
|
||||
output = "FIRMWARE_NAME:{} PROTOCOL_VERSION:1.0".format(self._firmwareName)
|
||||
output = self._m115FormatString.format(firmware_name=self._firmwareName)
|
||||
self._send(output)
|
||||
|
||||
def _gcode_M117(self, data):
|
||||
@@ -558,6 +562,11 @@ class VirtualPrinter(object):
|
||||
| Sleeps <seconds> s after each execution of <command>
|
||||
sleep_after_next <str:command> <int:seconds>
|
||||
| Sleeps <seconds> s after execution of next <command>
|
||||
|
||||
# Misc
|
||||
|
||||
send <str:message>
|
||||
| Sends back <message>
|
||||
"""
|
||||
for line in usage.split("\n"):
|
||||
self._send("echo: {}".format(line.strip()))
|
||||
@@ -587,6 +596,7 @@ class VirtualPrinter(object):
|
||||
sleep_after_next_match = VirtualPrinter.sleep_after_next_regex.match(data)
|
||||
custom_action_match = VirtualPrinter.custom_action_regex.match(data)
|
||||
prepare_ok_match = VirtualPrinter.prepare_ok_regex.match(data)
|
||||
send_match = VirtualPrinter.send_regex.match(data)
|
||||
|
||||
if sleep_match is not None:
|
||||
interval = int(sleep_match.group(1))
|
||||
@@ -610,6 +620,8 @@ class VirtualPrinter(object):
|
||||
elif prepare_ok_match is not None:
|
||||
ok = prepare_ok_match.group(1)
|
||||
self._prepared_oks.append(ok)
|
||||
elif send_match is not None:
|
||||
self._send(send_match.group(1))
|
||||
except:
|
||||
pass
|
||||
|
||||
@@ -1073,11 +1085,7 @@ class VirtualPrinter(object):
|
||||
def _sendOk(self):
|
||||
if self.outgoing is None:
|
||||
return
|
||||
|
||||
if settings().getBoolean(["devel", "virtualPrinter", "okWithLinenumber"]):
|
||||
self._send("{} {}".format(self._ok(), self.lastN))
|
||||
else:
|
||||
self._send(self._ok())
|
||||
self._send(self._ok())
|
||||
|
||||
def _sendWaitAfterTimeout(self, timeout=5):
|
||||
time.sleep(timeout)
|
||||
@@ -1089,10 +1097,11 @@ class VirtualPrinter(object):
|
||||
self.outgoing.put(line)
|
||||
|
||||
def _ok(self):
|
||||
ok = "ok"
|
||||
ok = self._okFormatString
|
||||
if self._prepared_oks:
|
||||
ok = self._prepared_oks.pop(0)
|
||||
return ok
|
||||
|
||||
return ok.format(ok, lastN=self.lastN, buffer=self.buffered.maxsize - self.buffered.qsize())
|
||||
|
||||
class CharCountingQueue(queue.Queue):
|
||||
|
||||
|
||||
@@ -292,11 +292,15 @@ class PrinterInterface(object):
|
||||
Optionally can also directly start the print after selecting the file.
|
||||
|
||||
Arguments:
|
||||
path (str): The path to select for printing. Either an absolute path (local file) or a
|
||||
filename (SD card).
|
||||
sd (boolean): Indicates whether the file is on the SD card or not.
|
||||
path (str): The path to select for printing. Either an absolute path or relative path to a local file in
|
||||
the uploads folder or a filename on the printer's SD card.
|
||||
sd (boolean): Indicates whether the file is on the printer's SD card or not.
|
||||
printAfterSelect (boolean): Indicates whether a print should be started
|
||||
after the file is selected.
|
||||
|
||||
Raises:
|
||||
InvalidFileLocation: if an absolute path was provided and not contained within local storage or
|
||||
doesn't exist
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
@@ -586,3 +590,6 @@ class PrinterCallback(object):
|
||||
class UnknownScript(Exception):
|
||||
def __init__(self, name, *args, **kwargs):
|
||||
self.name = name
|
||||
|
||||
class InvalidFileLocation(Exception):
|
||||
pass
|
||||
@@ -204,6 +204,37 @@ class PrinterProfileManager(object):
|
||||
self._folder = settings().getBaseFolder("printerProfiles")
|
||||
self._logger = logging.getLogger(__name__)
|
||||
|
||||
self._migrate_old_default_profile()
|
||||
self._verify_default_available()
|
||||
|
||||
def _migrate_old_default_profile(self):
|
||||
default_overrides = settings().get(["printerProfiles", "defaultProfile"])
|
||||
if not default_overrides:
|
||||
return
|
||||
|
||||
if self.exists("_default"):
|
||||
return
|
||||
|
||||
default_overrides["id"] = "_default"
|
||||
self.save(default_overrides)
|
||||
|
||||
settings().set(["printerProfiles", "defaultProfile"], None)
|
||||
settings().save()
|
||||
|
||||
def _verify_default_available(self):
|
||||
default_id = settings().get(["printerProfile", "default"])
|
||||
if default_id is None:
|
||||
default_id = "_default"
|
||||
|
||||
if not self.exists(default_id):
|
||||
if not self.exists("_default"):
|
||||
self._logger.error("Selected default profile {} and _default do not exist, creating _default again and setting it as default".format(default_id))
|
||||
self.save(self.__class__.default, allow_overwrite=True, make_default=True)
|
||||
else:
|
||||
self._logger.error("Selected default profile {} does not exists, resetting to _default".format(default_id))
|
||||
settings().set(["printerProfiles", "default"], "_default")
|
||||
settings().save()
|
||||
|
||||
def select(self, identifier):
|
||||
if identifier is None or not self.exists(identifier):
|
||||
self._current = self.get_default()
|
||||
@@ -220,9 +251,7 @@ class PrinterProfileManager(object):
|
||||
|
||||
def get(self, identifier):
|
||||
try:
|
||||
if identifier == "_default":
|
||||
return self._load_default()
|
||||
elif self.exists(identifier):
|
||||
if self.exists(identifier):
|
||||
return self._load_from_path(self._get_profile_path(identifier))
|
||||
else:
|
||||
return None
|
||||
@@ -230,10 +259,10 @@ class PrinterProfileManager(object):
|
||||
return None
|
||||
|
||||
def remove(self, identifier):
|
||||
if identifier == "_default":
|
||||
return False
|
||||
if self._current is not None and self._current["id"] == identifier:
|
||||
return False
|
||||
elif settings().get(["printerProfiles", "default"]) == identifier:
|
||||
return False
|
||||
return self._remove_from_path(self._get_profile_path(identifier))
|
||||
|
||||
def save(self, profile, allow_overwrite=False, make_default=False):
|
||||
@@ -246,21 +275,16 @@ class PrinterProfileManager(object):
|
||||
|
||||
identifier = self._sanitize(identifier)
|
||||
profile["id"] = identifier
|
||||
|
||||
self._migrate_profile(profile)
|
||||
profile = dict_sanitize(profile, self.__class__.default)
|
||||
profile = dict_merge(self.__class__.default, profile)
|
||||
|
||||
if identifier == self.__class__.default["id"]:
|
||||
default_profile = dict_merge(self._load_default(), profile)
|
||||
if not self._ensure_valid_profile(default_profile):
|
||||
raise InvalidProfileError()
|
||||
self._save_to_path(self._get_profile_path(identifier), profile, allow_overwrite=allow_overwrite)
|
||||
|
||||
settings().set(["printerProfiles", "defaultProfile"], default_profile, defaults=dict(printerProfiles=dict(defaultProfile=self.__class__.default)))
|
||||
if make_default:
|
||||
settings().set(["printerProfiles", "default"], identifier)
|
||||
settings().save()
|
||||
else:
|
||||
self._save_to_path(self._get_profile_path(identifier), profile, allow_overwrite=allow_overwrite)
|
||||
|
||||
if make_default:
|
||||
settings().set(["printerProfiles", "default"], identifier)
|
||||
settings().save()
|
||||
|
||||
if self._current is not None and self._current["id"] == identifier:
|
||||
self.select(identifier)
|
||||
@@ -268,8 +292,7 @@ class PrinterProfileManager(object):
|
||||
|
||||
def is_default_unmodified(self):
|
||||
default = settings().get(["printerProfiles", "default"])
|
||||
default_overrides = settings().get(["printerProfiles", "defaultProfile"])
|
||||
return (default is None or default == self.__class__.default["id"]) and not default_overrides
|
||||
return default is None or default == "_default" or not self.exists("_default")
|
||||
|
||||
@property
|
||||
def profile_count(self):
|
||||
@@ -288,7 +311,7 @@ class PrinterProfileManager(object):
|
||||
if profile is not None:
|
||||
return profile
|
||||
|
||||
return self._load_default()
|
||||
return copy.deepcopy(self.__class__.default)
|
||||
|
||||
def set_default(self, identifier):
|
||||
all_identifiers = self._load_all_identifiers().keys()
|
||||
@@ -310,8 +333,6 @@ class PrinterProfileManager(object):
|
||||
def exists(self, identifier):
|
||||
if identifier is None:
|
||||
return False
|
||||
elif identifier == "_default":
|
||||
return True
|
||||
else:
|
||||
path = self._get_profile_path(identifier)
|
||||
return os.path.exists(path) and os.path.isfile(path)
|
||||
@@ -321,23 +342,20 @@ class PrinterProfileManager(object):
|
||||
results = dict()
|
||||
for identifier, path in all_identifiers.items():
|
||||
try:
|
||||
if identifier == "_default":
|
||||
profile = self._load_default()
|
||||
else:
|
||||
profile = self._load_from_path(path)
|
||||
profile = self._load_from_path(path)
|
||||
except InvalidProfileError:
|
||||
continue
|
||||
|
||||
if profile is None:
|
||||
continue
|
||||
|
||||
results[identifier] = dict_merge(self._load_default(), profile)
|
||||
results[identifier] = dict_merge(self.__class__.default, profile)
|
||||
return results
|
||||
|
||||
def _load_all_identifiers(self):
|
||||
results = dict(_default=None)
|
||||
results = dict()
|
||||
for entry in scandir(self._folder):
|
||||
if is_hidden_path(entry.name) or not entry.name.endswith(".profile") or entry.name == "_default.profile":
|
||||
if is_hidden_path(entry.name) or not entry.name.endswith(".profile"):
|
||||
continue
|
||||
|
||||
if not entry.is_file():
|
||||
@@ -392,21 +410,6 @@ class PrinterProfileManager(object):
|
||||
except:
|
||||
return False
|
||||
|
||||
def _load_default(self):
|
||||
default_overrides = settings().get(["printerProfiles", "defaultProfile"])
|
||||
if self._migrate_profile(default_overrides):
|
||||
try:
|
||||
settings().set(["printerProfiles", "defaultProfile"], default_overrides)
|
||||
settings().save()
|
||||
except:
|
||||
self._logger.exception("Tried to save default profile after migrating it while loading, ran into exception")
|
||||
|
||||
profile = self._ensure_valid_profile(dict_merge(copy.deepcopy(self.__class__.default), default_overrides))
|
||||
if not profile:
|
||||
self._logger.warn("Invalid default profile after applying overrides")
|
||||
return copy.deepcopy(self.__class__.default)
|
||||
return profile
|
||||
|
||||
def _get_profile_path(self, identifier):
|
||||
return os.path.join(self._folder, "%s.profile" % identifier)
|
||||
|
||||
|
||||
+170
-135
@@ -19,7 +19,7 @@ from octoprint import util as util
|
||||
from octoprint.events import eventManager, Events
|
||||
from octoprint.filemanager import FileDestinations, NoSuchStorage
|
||||
from octoprint.plugin import plugin_manager, ProgressPlugin
|
||||
from octoprint.printer import PrinterInterface, PrinterCallback, UnknownScript
|
||||
from octoprint.printer import PrinterInterface, PrinterCallback, UnknownScript, InvalidFileLocation
|
||||
from octoprint.printer.estimation import TimeEstimationHelper
|
||||
from octoprint.settings import settings
|
||||
from octoprint.util import comm as comm
|
||||
@@ -70,6 +70,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
self._sdFilelistAvailable = threading.Event()
|
||||
self._streamingFinishedCallback = None
|
||||
|
||||
self._selectedFileMutex = threading.RLock()
|
||||
self._selectedFile = None
|
||||
self._timeEstimationData = None
|
||||
self._timeEstimationStatsWeighingUntil = settings().getFloat(["estimation", "printTime", "statsWeighingUntil"])
|
||||
@@ -155,24 +156,28 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
#~~ callback from metadata analysis event
|
||||
|
||||
def _on_event_MetadataAnalysisFinished(self, event, data):
|
||||
if self._selectedFile:
|
||||
self._setJobData(self._selectedFile["filename"],
|
||||
self._selectedFile["filesize"],
|
||||
self._selectedFile["sd"])
|
||||
with self._selectedFileMutex:
|
||||
if self._selectedFile:
|
||||
self._setJobData(self._selectedFile["filename"],
|
||||
self._selectedFile["filesize"],
|
||||
self._selectedFile["sd"])
|
||||
|
||||
def _on_event_MetadataStatisticsUpdated(self, event, data):
|
||||
self._setJobData(self._selectedFile["filename"],
|
||||
self._selectedFile["filesize"],
|
||||
self._selectedFile["sd"])
|
||||
with self._selectedFileMutex:
|
||||
if self._selectedFile:
|
||||
self._setJobData(self._selectedFile["filename"],
|
||||
self._selectedFile["filesize"],
|
||||
self._selectedFile["sd"])
|
||||
|
||||
#~~ progress plugin reporting
|
||||
|
||||
def _reportPrintProgressToPlugins(self, progress):
|
||||
if progress is None or not self._selectedFile or not "sd" in self._selectedFile or not "filename" in self._selectedFile:
|
||||
return
|
||||
with self._selectedFileMutex:
|
||||
if progress is None or not self._selectedFile or not "sd" in self._selectedFile or not "filename" in self._selectedFile:
|
||||
return
|
||||
|
||||
storage = "sdcard" if self._selectedFile["sd"] else "local"
|
||||
filename = self._selectedFile["filename"]
|
||||
storage = "sdcard" if self._selectedFile["sd"] else "local"
|
||||
filename = self._selectedFile["filename"]
|
||||
|
||||
def call_plugins(storage, filename, progress):
|
||||
for plugin in self._progressPlugins:
|
||||
@@ -381,6 +386,8 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
self._logger.info("Cannot load file: printer not connected or currently busy")
|
||||
return
|
||||
|
||||
self._validateJob(path, sd)
|
||||
|
||||
recovery_data = self._fileManager.get_recovery_data()
|
||||
if recovery_data:
|
||||
# clean up recovery data if we just selected a different file than is logged in that
|
||||
@@ -394,7 +401,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
self._printAfterSelect = printAfterSelect
|
||||
self._posAfterSelect = pos
|
||||
self._comm.selectFile("/" + path if sd else path, sd)
|
||||
self._setProgressData(completion=0)
|
||||
self._updateProgressData()
|
||||
self._setCurrentZ(None)
|
||||
|
||||
def unselect_file(self):
|
||||
@@ -402,15 +409,16 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
return
|
||||
|
||||
self._comm.unselectFile()
|
||||
self._setProgressData(completion=0)
|
||||
self._updateProgressData()
|
||||
self._setCurrentZ(None)
|
||||
|
||||
def get_file_position(self):
|
||||
if self._comm is None:
|
||||
return None
|
||||
|
||||
if self._selectedFile is None:
|
||||
return None
|
||||
with self._selectedFileMutex:
|
||||
if self._selectedFile is None:
|
||||
return None
|
||||
|
||||
return self._comm.getFilePosition()
|
||||
|
||||
@@ -421,21 +429,23 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
"""
|
||||
if self._comm is None or not self._comm.isOperational() or self._comm.isPrinting():
|
||||
return
|
||||
if self._selectedFile is None:
|
||||
return
|
||||
with self._selectedFileMutex:
|
||||
if self._selectedFile is None:
|
||||
return
|
||||
|
||||
# we are happy if the average of the estimates stays within 60s of the prior one
|
||||
threshold = settings().getFloat(["estimation", "printTime", "stableThreshold"])
|
||||
rolling_window = None
|
||||
countdown = None
|
||||
|
||||
if self._selectedFile["sd"]:
|
||||
# we are interesting in a rolling window of roughly the last 15s, so the number of entries has to be derived
|
||||
# by that divided by the sd status polling interval
|
||||
rolling_window = 15 / settings().get(["serial", "timeout", "sdStatus"])
|
||||
with self._selectedFileMutex:
|
||||
if self._selectedFile["sd"]:
|
||||
# we are interesting in a rolling window of roughly the last 15s, so the number of entries has to be derived
|
||||
# by that divided by the sd status polling interval
|
||||
rolling_window = 15 / settings().get(["serial", "timeout", "sdStatus"])
|
||||
|
||||
# we are happy when one rolling window has been stable
|
||||
countdown = rolling_window
|
||||
# we are happy when one rolling window has been stable
|
||||
countdown = rolling_window
|
||||
self._timeEstimationData = TimeEstimationHelper(rolling_window=rolling_window,
|
||||
threshold=threshold,
|
||||
countdown=countdown)
|
||||
@@ -443,7 +453,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
self._fileManager.delete_recovery_data()
|
||||
|
||||
self._lastProgressReport = None
|
||||
self._setProgressData(completion=0)
|
||||
self._updateProgressData()
|
||||
self._setCurrentZ(None)
|
||||
self._comm.startPrint(pos=pos)
|
||||
|
||||
@@ -478,18 +488,10 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
if self._comm is None:
|
||||
return
|
||||
|
||||
# tell comm layer to cancel - will also trigger our cancelled handler
|
||||
# for further processing
|
||||
self._comm.cancelPrint()
|
||||
|
||||
# reset progress, height, print time
|
||||
self._setCurrentZ(None)
|
||||
self._setProgressData()
|
||||
|
||||
# mark print as failure
|
||||
if self._selectedFile is not None:
|
||||
self._fileManager.log_print(FileDestinations.SDCARD if self._selectedFile["sd"] else FileDestinations.LOCAL, self._selectedFile["filename"], time.time(), self._comm.getPrintTime(), False, self._printerProfileManager.get_current_or_default()["id"])
|
||||
payload = self._payload_for_print_job_event()
|
||||
eventManager().fire(Events.PRINT_FAILED, payload)
|
||||
|
||||
def get_state_string(self, state=None):
|
||||
if self._comm is None:
|
||||
return "Offline"
|
||||
@@ -559,7 +561,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
return self._comm is not None and self._comm.isError()
|
||||
|
||||
def is_ready(self):
|
||||
return self.is_operational() and not self._comm.isStreaming()
|
||||
return self.is_operational() and not self.is_printing() and not self._comm.isStreaming()
|
||||
|
||||
def is_sd_ready(self):
|
||||
if not settings().getBoolean(["feature", "sdSupport"]) or self._comm is None:
|
||||
@@ -662,7 +664,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
|
||||
return result
|
||||
|
||||
def _setProgressData(self, completion=None, filepos=None, printTime=None, printTimeLeft=None):
|
||||
def _updateProgressData(self, completion=None, filepos=None, printTime=None, printTimeLeft=None):
|
||||
self._stateMonitor.set_progress(dict(completion=int(completion * 100) if completion is not None else None,
|
||||
filepos=filepos,
|
||||
printTime=int(printTime) if printTime is not None else None,
|
||||
@@ -682,10 +684,11 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
|
||||
statisticalTotalPrintTime = None
|
||||
statisticalTotalPrintTimeType = None
|
||||
if self._selectedFile and "estimatedPrintTime" in self._selectedFile \
|
||||
and self._selectedFile["estimatedPrintTime"]:
|
||||
statisticalTotalPrintTime = self._selectedFile["estimatedPrintTime"]
|
||||
statisticalTotalPrintTimeType = self._selectedFile.get("estimatedPrintTimeType", None)
|
||||
with self._selectedFileMutex:
|
||||
if self._selectedFile and "estimatedPrintTime" in self._selectedFile \
|
||||
and self._selectedFile["estimatedPrintTime"]:
|
||||
statisticalTotalPrintTime = self._selectedFile["estimatedPrintTime"]
|
||||
statisticalTotalPrintTimeType = self._selectedFile.get("estimatedPrintTimeType", None)
|
||||
|
||||
printTimeLeft, printTimeLeftOrigin = self._estimatePrintTimeLeft(progress, printTime, cleanedPrintTime, statisticalTotalPrintTime, statisticalTotalPrintTimeType)
|
||||
|
||||
@@ -841,90 +844,101 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
|
||||
self._stateMonitor.add_temperature(data)
|
||||
|
||||
def _setJobData(self, filename, filesize, sd):
|
||||
if filename is not None:
|
||||
if sd:
|
||||
name_in_storage = filename
|
||||
if name_in_storage.startswith("/"):
|
||||
name_in_storage = name_in_storage[1:]
|
||||
path_in_storage = name_in_storage
|
||||
path_on_disk = None
|
||||
else:
|
||||
path_in_storage = self._fileManager.path_in_storage(FileDestinations.LOCAL, filename)
|
||||
path_on_disk = self._fileManager.path_on_disk(FileDestinations.LOCAL, filename)
|
||||
_, name_in_storage = self._fileManager.split_path(FileDestinations.LOCAL, path_in_storage)
|
||||
self._selectedFile = {
|
||||
"filename": path_in_storage,
|
||||
"filesize": filesize,
|
||||
"sd": sd,
|
||||
"estimatedPrintTime": None
|
||||
}
|
||||
else:
|
||||
self._selectedFile = None
|
||||
self._stateMonitor.set_job_data({
|
||||
"file": {
|
||||
"name": None,
|
||||
"path": None,
|
||||
"origin": None,
|
||||
"size": None,
|
||||
"date": None
|
||||
},
|
||||
"estimatedPrintTime": None,
|
||||
"averagePrintTime": None,
|
||||
"lastPrintTime": None,
|
||||
"filament": None,
|
||||
})
|
||||
def _validateJob(self, filename, sd):
|
||||
if sd:
|
||||
return
|
||||
|
||||
estimatedPrintTime = None
|
||||
lastPrintTime = None
|
||||
averagePrintTime = None
|
||||
date = None
|
||||
filament = None
|
||||
if path_on_disk:
|
||||
# Use a string for mtime because it could be float and the
|
||||
# javascript needs to exact match
|
||||
if not sd:
|
||||
date = int(os.stat(path_on_disk).st_mtime)
|
||||
path_on_disk = self._fileManager.path_on_disk(FileDestinations.LOCAL, filename)
|
||||
if os.path.isabs(filename) and not filename == path_on_disk:
|
||||
raise InvalidFileLocation("{} is not located within local storage, cannot select for printing".format(filename))
|
||||
if not os.path.isfile(path_on_disk):
|
||||
raise InvalidFileLocation("{} does not exist in local storage, cannot select for printing".format(filename))
|
||||
|
||||
try:
|
||||
fileData = self._fileManager.get_metadata(FileDestinations.SDCARD if sd else FileDestinations.LOCAL, path_on_disk)
|
||||
except:
|
||||
fileData = None
|
||||
if fileData is not None:
|
||||
if "analysis" in fileData:
|
||||
if estimatedPrintTime is None and "estimatedPrintTime" in fileData["analysis"]:
|
||||
estimatedPrintTime = fileData["analysis"]["estimatedPrintTime"]
|
||||
if "filament" in fileData["analysis"].keys():
|
||||
filament = fileData["analysis"]["filament"]
|
||||
if "statistics" in fileData:
|
||||
printer_profile = self._printerProfileManager.get_current_or_default()["id"]
|
||||
if "averagePrintTime" in fileData["statistics"] and printer_profile in fileData["statistics"]["averagePrintTime"]:
|
||||
averagePrintTime = fileData["statistics"]["averagePrintTime"][printer_profile]
|
||||
if "lastPrintTime" in fileData["statistics"] and printer_profile in fileData["statistics"]["lastPrintTime"]:
|
||||
lastPrintTime = fileData["statistics"]["lastPrintTime"][printer_profile]
|
||||
def _setJobData(self, filename, filesize, sd):
|
||||
with self._selectedFileMutex:
|
||||
if filename is not None:
|
||||
if sd:
|
||||
name_in_storage = filename
|
||||
if name_in_storage.startswith("/"):
|
||||
name_in_storage = name_in_storage[1:]
|
||||
path_in_storage = name_in_storage
|
||||
path_on_disk = None
|
||||
else:
|
||||
path_in_storage = self._fileManager.path_in_storage(FileDestinations.LOCAL, filename)
|
||||
path_on_disk = self._fileManager.path_on_disk(FileDestinations.LOCAL, filename)
|
||||
_, name_in_storage = self._fileManager.split_path(FileDestinations.LOCAL, path_in_storage)
|
||||
self._selectedFile = {
|
||||
"filename": path_in_storage,
|
||||
"filesize": filesize,
|
||||
"sd": sd,
|
||||
"estimatedPrintTime": None
|
||||
}
|
||||
else:
|
||||
self._selectedFile = None
|
||||
self._stateMonitor.set_job_data({
|
||||
"file": {
|
||||
"name": None,
|
||||
"path": None,
|
||||
"origin": None,
|
||||
"size": None,
|
||||
"date": None
|
||||
},
|
||||
"estimatedPrintTime": None,
|
||||
"averagePrintTime": None,
|
||||
"lastPrintTime": None,
|
||||
"filament": None,
|
||||
})
|
||||
return
|
||||
|
||||
if averagePrintTime is not None:
|
||||
self._selectedFile["estimatedPrintTime"] = averagePrintTime
|
||||
self._selectedFile["estimatedPrintTimeType"] = "average"
|
||||
elif estimatedPrintTime is not None:
|
||||
# TODO apply factor which first needs to be tracked!
|
||||
self._selectedFile["estimatedPrintTime"] = estimatedPrintTime
|
||||
self._selectedFile["estimatedPrintTimeType"] = "analysis"
|
||||
estimatedPrintTime = None
|
||||
lastPrintTime = None
|
||||
averagePrintTime = None
|
||||
date = None
|
||||
filament = None
|
||||
if path_on_disk:
|
||||
# Use a string for mtime because it could be float and the
|
||||
# javascript needs to exact match
|
||||
if not sd:
|
||||
date = int(os.stat(path_on_disk).st_mtime)
|
||||
|
||||
self._stateMonitor.set_job_data({
|
||||
"file": {
|
||||
"name": name_in_storage,
|
||||
"path": path_in_storage,
|
||||
"origin": FileDestinations.SDCARD if sd else FileDestinations.LOCAL,
|
||||
"size": filesize,
|
||||
"date": date
|
||||
},
|
||||
"estimatedPrintTime": estimatedPrintTime,
|
||||
"averagePrintTime": averagePrintTime,
|
||||
"lastPrintTime": lastPrintTime,
|
||||
"filament": filament,
|
||||
})
|
||||
try:
|
||||
fileData = self._fileManager.get_metadata(FileDestinations.SDCARD if sd else FileDestinations.LOCAL, path_on_disk)
|
||||
except:
|
||||
fileData = None
|
||||
if fileData is not None:
|
||||
if "analysis" in fileData:
|
||||
if estimatedPrintTime is None and "estimatedPrintTime" in fileData["analysis"]:
|
||||
estimatedPrintTime = fileData["analysis"]["estimatedPrintTime"]
|
||||
if "filament" in fileData["analysis"].keys():
|
||||
filament = fileData["analysis"]["filament"]
|
||||
if "statistics" in fileData:
|
||||
printer_profile = self._printerProfileManager.get_current_or_default()["id"]
|
||||
if "averagePrintTime" in fileData["statistics"] and printer_profile in fileData["statistics"]["averagePrintTime"]:
|
||||
averagePrintTime = fileData["statistics"]["averagePrintTime"][printer_profile]
|
||||
if "lastPrintTime" in fileData["statistics"] and printer_profile in fileData["statistics"]["lastPrintTime"]:
|
||||
lastPrintTime = fileData["statistics"]["lastPrintTime"][printer_profile]
|
||||
|
||||
if averagePrintTime is not None:
|
||||
self._selectedFile["estimatedPrintTime"] = averagePrintTime
|
||||
self._selectedFile["estimatedPrintTimeType"] = "average"
|
||||
elif estimatedPrintTime is not None:
|
||||
# TODO apply factor which first needs to be tracked!
|
||||
self._selectedFile["estimatedPrintTime"] = estimatedPrintTime
|
||||
self._selectedFile["estimatedPrintTimeType"] = "analysis"
|
||||
|
||||
self._stateMonitor.set_job_data({
|
||||
"file": {
|
||||
"name": name_in_storage,
|
||||
"path": path_in_storage,
|
||||
"origin": FileDestinations.SDCARD if sd else FileDestinations.LOCAL,
|
||||
"size": filesize,
|
||||
"date": date
|
||||
},
|
||||
"estimatedPrintTime": estimatedPrintTime,
|
||||
"averagePrintTime": averagePrintTime,
|
||||
"lastPrintTime": lastPrintTime,
|
||||
"filament": filament,
|
||||
})
|
||||
|
||||
def _sendInitialStateUpdate(self, callback):
|
||||
try:
|
||||
@@ -977,9 +991,10 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
|
||||
# forward relevant state changes to gcode manager
|
||||
if oldState == comm.MachineCom.STATE_PRINTING:
|
||||
if self._selectedFile is not None:
|
||||
if state == comm.MachineCom.STATE_CLOSED or state == comm.MachineCom.STATE_ERROR or state == comm.MachineCom.STATE_CLOSED_WITH_ERROR:
|
||||
self._fileManager.log_print(FileDestinations.SDCARD if self._selectedFile["sd"] else FileDestinations.LOCAL, self._selectedFile["filename"], time.time(), self._comm.getPrintTime(), False, self._printerProfileManager.get_current_or_default()["id"])
|
||||
with self._selectedFileMutex:
|
||||
if self._selectedFile is not None:
|
||||
if state == comm.MachineCom.STATE_CLOSED or state == comm.MachineCom.STATE_ERROR or state == comm.MachineCom.STATE_CLOSED_WITH_ERROR:
|
||||
self._fileManager.log_print(FileDestinations.SDCARD if self._selectedFile["sd"] else FileDestinations.LOCAL, self._selectedFile["filename"], time.time(), self._comm.getPrintTime(), False, self._printerProfileManager.get_current_or_default()["id"])
|
||||
self._analysisQueue.resume() # printing done, put those cpu cycles to good use
|
||||
elif state == comm.MachineCom.STATE_PRINTING:
|
||||
self._analysisQueue.pause() # do not analyse files while printing
|
||||
@@ -988,7 +1003,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
if self._comm is not None:
|
||||
self._comm = None
|
||||
|
||||
self._setProgressData(completion=0)
|
||||
self._updateProgressData()
|
||||
self._setCurrentZ(None)
|
||||
self._setJobData(None, None, None)
|
||||
self._printerProfileManager.deselect()
|
||||
@@ -1054,6 +1069,10 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
must_be_set=False)
|
||||
|
||||
def on_comm_print_job_done(self):
|
||||
self._updateProgressData()
|
||||
self._stateMonitor.set_state({"text": self.get_state_string(), "flags": self._getStateFlags()})
|
||||
self._fileManager.delete_recovery_data()
|
||||
|
||||
payload = self._payload_for_print_job_event()
|
||||
if payload:
|
||||
payload["time"] = self._comm.getPrintTime()
|
||||
@@ -1062,23 +1081,38 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
context=dict(event=payload),
|
||||
must_be_set=False)
|
||||
|
||||
self._fileManager.log_print(FileDestinations.SDCARD if self._selectedFile["sd"] else FileDestinations.LOCAL, self._selectedFile["filename"], time.time(), self._comm.getPrintTime(), True, self._printerProfileManager.get_current_or_default()["id"])
|
||||
self._setProgressData(completion=1.0, filepos=self._selectedFile["filesize"], printTime=self._comm.getPrintTime(), printTimeLeft=0)
|
||||
self._stateMonitor.set_state({"text": self.get_state_string(), "flags": self._getStateFlags()})
|
||||
self._fileManager.delete_recovery_data()
|
||||
self._fileManager.log_print(payload["origin"],
|
||||
payload["path"],
|
||||
time.time(),
|
||||
payload["time"],
|
||||
True,
|
||||
self._printerProfileManager.get_current_or_default()["id"])
|
||||
|
||||
def on_comm_print_job_failed(self):
|
||||
payload = self._payload_for_print_job_event()
|
||||
eventManager().fire(Events.PRINT_FAILED, payload)
|
||||
|
||||
def on_comm_print_job_cancelled(self):
|
||||
self._setCurrentZ(None)
|
||||
self._updateProgressData()
|
||||
|
||||
payload = self._payload_for_print_job_event(position=self._comm.cancel_position.as_dict() if self._comm and self._comm.cancel_position else None)
|
||||
if payload:
|
||||
payload["time"] = self._comm.getPrintTime()
|
||||
|
||||
eventManager().fire(Events.PRINT_CANCELLED, payload)
|
||||
self.script("afterPrintCancelled",
|
||||
context=dict(event=payload),
|
||||
must_be_set=False)
|
||||
|
||||
self._fileManager.log_print(payload["origin"],
|
||||
payload["path"],
|
||||
time.time(),
|
||||
payload["time"],
|
||||
False,
|
||||
self._printerProfileManager.get_current_or_default()["id"])
|
||||
eventManager().fire(Events.PRINT_FAILED, payload)
|
||||
|
||||
def on_comm_print_job_paused(self):
|
||||
payload = self._payload_for_print_job_event(position=self._comm.pause_position.as_dict() if self._comm and self._comm.pause_position else None)
|
||||
if payload:
|
||||
@@ -1099,7 +1133,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
self._sdStreaming = True
|
||||
|
||||
self._setJobData(filename, filesize, True)
|
||||
self._setProgressData(completion=0.0, filepos=0, printTime=0)
|
||||
self._updateProgressData()
|
||||
self._stateMonitor.set_state({"text": self.get_state_string(), "flags": self._getStateFlags()})
|
||||
|
||||
def on_comm_file_transfer_done(self, filename):
|
||||
@@ -1112,7 +1146,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
|
||||
self._setCurrentZ(None)
|
||||
self._setJobData(None, None, None)
|
||||
self._setProgressData()
|
||||
self._updateProgressData()
|
||||
self._stateMonitor.set_state({"text": self.get_state_string(), "flags": self._getStateFlags()})
|
||||
|
||||
def on_comm_force_disconnect(self):
|
||||
@@ -1128,12 +1162,13 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
|
||||
def _payload_for_print_job_event(self, location=None, print_job_file=None, position=None):
|
||||
if print_job_file is None:
|
||||
selected_file = self._selectedFile
|
||||
if not selected_file:
|
||||
return dict()
|
||||
with self._selectedFileMutex:
|
||||
selected_file = self._selectedFile
|
||||
if not selected_file:
|
||||
return dict()
|
||||
|
||||
print_job_file = selected_file.get("filename", None)
|
||||
location = FileDestinations.SDCARD if selected_file.get("sd", False) else FileDestinations.LOCAL
|
||||
print_job_file = selected_file.get("filename", None)
|
||||
location = FileDestinations.SDCARD if selected_file.get("sd", False) else FileDestinations.LOCAL
|
||||
|
||||
if not print_job_file or not location:
|
||||
return dict()
|
||||
|
||||
@@ -211,8 +211,10 @@ class Server(object):
|
||||
eventManager = events.eventManager()
|
||||
analysisQueue = octoprint.filemanager.analysis.AnalysisQueue()
|
||||
slicingManager = octoprint.slicing.SlicingManager(self._settings.getBaseFolder("slicingProfiles"), printerProfileManager)
|
||||
|
||||
storage_managers = dict()
|
||||
storage_managers[octoprint.filemanager.FileDestinations.LOCAL] = octoprint.filemanager.storage.LocalFileStorage(self._settings.getBaseFolder("uploads"))
|
||||
|
||||
fileManager = octoprint.filemanager.FileManager(analysisQueue, slicingManager, printerProfileManager, initial_storage_managers=storage_managers)
|
||||
appSessionManager = util.flask.AppSessionManager()
|
||||
pluginLifecycleManager = LifecycleManager(pluginManager)
|
||||
@@ -1106,11 +1108,20 @@ class Server(object):
|
||||
"js/lib/jquery/jquery.slimscroll.min.js",
|
||||
"js/lib/jquery/jquery.qrcode.min.js",
|
||||
"js/lib/jquery/jquery.bootstrap.wizard.js",
|
||||
"js/lib/pnotify/pnotify.core.min.js",
|
||||
"js/lib/pnotify/pnotify.buttons.min.js",
|
||||
"js/lib/pnotify/pnotify.callbacks.min.js",
|
||||
"js/lib/pnotify/pnotify.confirm.min.js",
|
||||
"js/lib/pnotify/pnotify.desktop.min.js",
|
||||
"js/lib/pnotify/pnotify.history.min.js",
|
||||
"js/lib/pnotify/pnotify.mobile.min.js",
|
||||
"js/lib/pnotify/pnotify.nonblock.min.js",
|
||||
"js/lib/pnotify/pnotify.reference.min.js",
|
||||
"js/lib/pnotify/pnotify.tooltip.min.js",
|
||||
"js/lib/moment-with-locales.min.js",
|
||||
"js/lib/pusher.color.min.js",
|
||||
"js/lib/detectmobilebrowser.js",
|
||||
"js/lib/md5.min.js",
|
||||
"js/lib/pnotify.min.js",
|
||||
"js/lib/bootstrap-slider-knockout-binding.js",
|
||||
"js/lib/loglevel.min.js",
|
||||
"js/lib/sockjs.min.js" if minify else "js/lib/sockjs.js"
|
||||
@@ -1152,7 +1163,9 @@ class Server(object):
|
||||
"css/bootstrap-tabdrop.css",
|
||||
"css/font-awesome.min.css",
|
||||
"css/jquery.fileupload-ui.css",
|
||||
"css/pnotify.min.css"
|
||||
"css/pnotify.core.min.css",
|
||||
"css/pnotify.buttons.min.css",
|
||||
"css/pnotify.history.min.css"
|
||||
]
|
||||
css_core = list(dynamic_core_assets["css"]) + list(dynamic_plugin_assets["bundled"]["css"])
|
||||
css_plugins = list(dynamic_plugin_assets["external"]["css"])
|
||||
|
||||
@@ -65,7 +65,7 @@ def _create_lastmodified(path, recursive):
|
||||
return None
|
||||
|
||||
|
||||
def _create_etag(path, recursive, lm=None):
|
||||
def _create_etag(path, filter, recursive, lm=None):
|
||||
if lm is None:
|
||||
lm = _create_lastmodified(path, recursive)
|
||||
|
||||
@@ -74,6 +74,7 @@ def _create_etag(path, recursive, lm=None):
|
||||
|
||||
hash = hashlib.sha1()
|
||||
hash.update(str(lm))
|
||||
hash.update(str(filter))
|
||||
hash.update(str(recursive))
|
||||
|
||||
if path.endswith("/files") or path.endswith("/files/sdcard"):
|
||||
@@ -86,20 +87,18 @@ def _create_etag(path, recursive, lm=None):
|
||||
@api.route("/files", methods=["GET"])
|
||||
@Permissions.FILE_PERMISSION.require(403)
|
||||
@with_revalidation_checking(etag_factory=lambda lm=None: _create_etag(request.path,
|
||||
request.values.get("filter", False),
|
||||
request.values.get("recursive", False),
|
||||
lm=lm),
|
||||
lastmodified_factory=lambda: _create_lastmodified(request.path,
|
||||
request.values.get("recursive", False)),
|
||||
unless=lambda: request.values.get("force", False) or request.values.get("_refresh", False))
|
||||
def readGcodeFiles():
|
||||
filter = request.values.get("filter", "false") in valid_boolean_trues
|
||||
filter = request.values.get("filter", False)
|
||||
recursive = request.values.get("recursive", "false") in valid_boolean_trues
|
||||
force = request.values.get("force", "false") in valid_boolean_trues
|
||||
|
||||
if force:
|
||||
_clear_file_cache()
|
||||
|
||||
files = _getFileList(FileDestinations.LOCAL, filter=filter, recursive=recursive)
|
||||
files = _getFileList(FileDestinations.LOCAL, filter=filter, recursive=recursive, allow_from_cache=not force)
|
||||
files.extend(_getFileList(FileDestinations.SDCARD))
|
||||
|
||||
usage = psutil.disk_usage(settings().getBaseFolder("uploads"))
|
||||
@@ -109,6 +108,7 @@ def readGcodeFiles():
|
||||
@api.route("/files/<string:origin>", methods=["GET"])
|
||||
@Permissions.DOWNLOAD.require(403)
|
||||
@with_revalidation_checking(etag_factory=lambda lm=None: _create_etag(request.path,
|
||||
request.values.get("filter", False),
|
||||
request.values.get("recursive", False),
|
||||
lm=lm),
|
||||
lastmodified_factory=lambda: _create_lastmodified(request.path,
|
||||
@@ -118,17 +118,11 @@ def readGcodeFilesForOrigin(origin):
|
||||
if origin not in [FileDestinations.LOCAL, FileDestinations.SDCARD]:
|
||||
return make_response("Unknown origin: %s" % origin, 404)
|
||||
|
||||
filter = request.values.get("filter", False)
|
||||
recursive = request.values.get("recursive", "false") in valid_boolean_trues
|
||||
force = request.values.get("force", "false") in valid_boolean_trues
|
||||
|
||||
if force:
|
||||
with _file_cache_mutex:
|
||||
try:
|
||||
del _file_cache[origin]
|
||||
except KeyError:
|
||||
pass
|
||||
|
||||
files = _getFileList(origin, recursive=recursive)
|
||||
files = _getFileList(origin, filter=filter, recursive=recursive, allow_from_cache=not force)
|
||||
|
||||
if origin == FileDestinations.LOCAL:
|
||||
usage = psutil.disk_usage(settings().getBaseFolder("uploads"))
|
||||
@@ -148,7 +142,7 @@ def _getFileDetails(origin, path, recursive=True):
|
||||
return None
|
||||
|
||||
|
||||
def _getFileList(origin, path=None, filter=None, recursive=False):
|
||||
def _getFileList(origin, path=None, filter=None, recursive=False, allow_from_cache=True):
|
||||
if origin == FileDestinations.SDCARD:
|
||||
sdFileList = printer.get_sd_files()
|
||||
|
||||
@@ -173,11 +167,12 @@ def _getFileList(origin, path=None, filter=None, recursive=False):
|
||||
filter_func = lambda entry, entry_data: octoprint.filemanager.valid_file_type(entry, type=filter)
|
||||
|
||||
with _file_cache_mutex:
|
||||
files, lastmodified = _file_cache.get("{}:{}:{}:{}".format(origin, path, recursive, filter), ([], None))
|
||||
if lastmodified is None or lastmodified < fileManager.last_modified(origin, path=path, recursive=recursive):
|
||||
cache_key = "{}:{}:{}:{}".format(origin, path, recursive, filter)
|
||||
files, lastmodified = _file_cache.get(cache_key, ([], None))
|
||||
if not allow_from_cache or lastmodified is None or lastmodified < fileManager.last_modified(origin, path=path, recursive=recursive):
|
||||
files = fileManager.list_files(origin, path=path, filter=filter_func, recursive=recursive)[origin].values()
|
||||
lastmodified = fileManager.last_modified(origin, path=path, recursive=recursive)
|
||||
_file_cache["{}:{}:{}:{}".format(origin, path, recursive, filter)] = (files, lastmodified)
|
||||
_file_cache[cache_key] = (files, lastmodified)
|
||||
|
||||
def analyse_recursively(files, path=None):
|
||||
if path is None:
|
||||
|
||||
@@ -112,8 +112,14 @@ def printerProfilesGet(identifier):
|
||||
@restricted_access
|
||||
@Permissions.SETTINGS.require(403)
|
||||
def printerProfilesDelete(identifier):
|
||||
if printerProfileManager.get_current_or_default()["id"] == identifier:
|
||||
return make_response("Cannot delete currently selected profile: %s" % identifier, 409)
|
||||
current_profile = printerProfileManager.get_current()
|
||||
if current_profile and current_profile["id"] == identifier:
|
||||
return make_response("Cannot delete currently selected profile: {}".format(identifier), 409)
|
||||
|
||||
default_profile = printerProfileManager.get_default()
|
||||
if default_profile and default_profile["id"] == identifier:
|
||||
return make_response("Cannot delete default profile: {}".format(identifier), 409)
|
||||
|
||||
printerProfileManager.remove(identifier)
|
||||
return NO_CONTENT
|
||||
|
||||
|
||||
@@ -15,7 +15,7 @@ from octoprint.events import eventManager, Events
|
||||
from octoprint.settings import settings, valid_boolean_trues
|
||||
|
||||
from octoprint.server import admin_permission, printer
|
||||
from octoprint.server.api import api
|
||||
from octoprint.server.api import api, NO_CONTENT
|
||||
from octoprint.server.util.flask import restricted_access, with_revalidation_checking
|
||||
from octoprint.access.permissions import Permissions
|
||||
|
||||
@@ -84,7 +84,7 @@ def getSettings():
|
||||
data = {
|
||||
"api": {
|
||||
"enabled": s.getBoolean(["api", "enabled"]),
|
||||
"key": s.get(["api", "key"]) if admin_permission.can() else "n/a",
|
||||
"key": s.get(["api", "key"]) if admin_permission.can() else None,
|
||||
"allowCrossOrigin": s.get(["api", "allowCrossOrigin"])
|
||||
},
|
||||
"appearance": {
|
||||
@@ -262,6 +262,23 @@ def setSettings():
|
||||
_saveSettings(data)
|
||||
return getSettings()
|
||||
|
||||
|
||||
@api.route("/settings/apikey", methods=["POST"])
|
||||
@restricted_access
|
||||
@admin_permission.require(403)
|
||||
def generateApiKey():
|
||||
apikey = settings().generateApiKey()
|
||||
return jsonify(apikey=apikey)
|
||||
|
||||
|
||||
@api.route("/settings/apikey", methods=["DELETE"])
|
||||
@restricted_access
|
||||
@admin_permission.require(403)
|
||||
def deleteApiKey():
|
||||
settings().deleteApiKey()
|
||||
return NO_CONTENT
|
||||
|
||||
|
||||
def _saveSettings(data):
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -271,14 +288,13 @@ def _saveSettings(data):
|
||||
# is changed, added or removed here
|
||||
|
||||
if "api" in data.keys():
|
||||
if "enabled" in data["api"].keys(): s.setBoolean(["api", "enabled"], data["api"]["enabled"])
|
||||
if "key" in data["api"].keys(): s.set(["api", "key"], data["api"]["key"], True)
|
||||
if "allowCrossOrigin" in data["api"].keys(): s.setBoolean(["api", "allowCrossOrigin"], data["api"]["allowCrossOrigin"])
|
||||
if "enabled" in data["api"]: s.setBoolean(["api", "enabled"], data["api"]["enabled"])
|
||||
if "allowCrossOrigin" in data["api"]: s.setBoolean(["api", "allowCrossOrigin"], data["api"]["allowCrossOrigin"])
|
||||
|
||||
if "appearance" in data.keys():
|
||||
if "name" in data["appearance"].keys(): s.set(["appearance", "name"], data["appearance"]["name"])
|
||||
if "color" in data["appearance"].keys(): s.set(["appearance", "color"], data["appearance"]["color"])
|
||||
if "colorTransparent" in data["appearance"].keys(): s.setBoolean(["appearance", "colorTransparent"], data["appearance"]["colorTransparent"])
|
||||
if "name" in data["appearance"]: s.set(["appearance", "name"], data["appearance"]["name"])
|
||||
if "color" in data["appearance"]: s.set(["appearance", "color"], data["appearance"]["color"])
|
||||
if "colorTransparent" in data["appearance"]: s.setBoolean(["appearance", "colorTransparent"], data["appearance"]["colorTransparent"])
|
||||
if "defaultLanguage" in data["appearance"]: s.set(["appearance", "defaultLanguage"], data["appearance"]["defaultLanguage"])
|
||||
if "showFahrenheitAlso" in data["appearance"]: s.setBoolean(["appearance", "showFahrenheitAlso"], data["appearance"]["showFahrenheitAlso"])
|
||||
|
||||
@@ -286,31 +302,31 @@ def _saveSettings(data):
|
||||
if "defaultExtrusionLength" in data["printer"]: s.setInt(["printerParameters", "defaultExtrusionLength"], data["printer"]["defaultExtrusionLength"])
|
||||
|
||||
if "webcam" in data.keys():
|
||||
if "streamUrl" in data["webcam"].keys(): s.set(["webcam", "stream"], data["webcam"]["streamUrl"])
|
||||
if "snapshotUrl" in data["webcam"].keys(): s.set(["webcam", "snapshot"], data["webcam"]["snapshotUrl"])
|
||||
if "ffmpegPath" in data["webcam"].keys(): s.set(["webcam", "ffmpeg"], data["webcam"]["ffmpegPath"])
|
||||
if "bitrate" in data["webcam"].keys(): s.set(["webcam", "bitrate"], data["webcam"]["bitrate"])
|
||||
if "ffmpegThreads" in data["webcam"].keys(): s.setInt(["webcam", "ffmpegThreads"], data["webcam"]["ffmpegThreads"])
|
||||
if "watermark" in data["webcam"].keys(): s.setBoolean(["webcam", "watermark"], data["webcam"]["watermark"])
|
||||
if "flipH" in data["webcam"].keys(): s.setBoolean(["webcam", "flipH"], data["webcam"]["flipH"])
|
||||
if "flipV" in data["webcam"].keys(): s.setBoolean(["webcam", "flipV"], data["webcam"]["flipV"])
|
||||
if "rotate90" in data["webcam"].keys(): s.setBoolean(["webcam", "rotate90"], data["webcam"]["rotate90"])
|
||||
if "streamUrl" in data["webcam"]: s.set(["webcam", "stream"], data["webcam"]["streamUrl"])
|
||||
if "snapshotUrl" in data["webcam"]: s.set(["webcam", "snapshot"], data["webcam"]["snapshotUrl"])
|
||||
if "ffmpegPath" in data["webcam"]: s.set(["webcam", "ffmpeg"], data["webcam"]["ffmpegPath"])
|
||||
if "bitrate" in data["webcam"]: s.set(["webcam", "bitrate"], data["webcam"]["bitrate"])
|
||||
if "ffmpegThreads" in data["webcam"]: s.setInt(["webcam", "ffmpegThreads"], data["webcam"]["ffmpegThreads"])
|
||||
if "watermark" in data["webcam"]: s.setBoolean(["webcam", "watermark"], data["webcam"]["watermark"])
|
||||
if "flipH" in data["webcam"]: s.setBoolean(["webcam", "flipH"], data["webcam"]["flipH"])
|
||||
if "flipV" in data["webcam"]: s.setBoolean(["webcam", "flipV"], data["webcam"]["flipV"])
|
||||
if "rotate90" in data["webcam"]: s.setBoolean(["webcam", "rotate90"], data["webcam"]["rotate90"])
|
||||
|
||||
if "feature" in data.keys():
|
||||
if "gcodeViewer" in data["feature"].keys(): s.setBoolean(["gcodeViewer", "enabled"], data["feature"]["gcodeViewer"])
|
||||
if "sizeThreshold" in data["feature"].keys(): s.setInt(["gcodeViewer", "sizeThreshold"], data["feature"]["sizeThreshold"])
|
||||
if "mobileSizeThreshold" in data["feature"].keys(): s.setInt(["gcodeViewer", "mobileSizeThreshold"], data["feature"]["mobileSizeThreshold"])
|
||||
if "temperatureGraph" in data["feature"].keys(): s.setBoolean(["feature", "temperatureGraph"], data["feature"]["temperatureGraph"])
|
||||
if "waitForStart" in data["feature"].keys(): s.setBoolean(["feature", "waitForStartOnConnect"], data["feature"]["waitForStart"])
|
||||
if "alwaysSendChecksum" in data["feature"].keys(): s.setBoolean(["feature", "alwaysSendChecksum"], data["feature"]["alwaysSendChecksum"])
|
||||
if "neverSendChecksum" in data["feature"].keys(): s.setBoolean(["feature", "neverSendChecksum"], data["feature"]["neverSendChecksum"])
|
||||
if "sdSupport" in data["feature"].keys(): s.setBoolean(["feature", "sdSupport"], data["feature"]["sdSupport"])
|
||||
if "sdRelativePath" in data["feature"].keys(): s.setBoolean(["feature", "sdRelativePath"], data["feature"]["sdRelativePath"])
|
||||
if "sdAlwaysAvailable" in data["feature"].keys(): s.setBoolean(["feature", "sdAlwaysAvailable"], data["feature"]["sdAlwaysAvailable"])
|
||||
if "swallowOkAfterResend" in data["feature"].keys(): s.setBoolean(["feature", "swallowOkAfterResend"], data["feature"]["swallowOkAfterResend"])
|
||||
if "repetierTargetTemp" in data["feature"].keys(): s.setBoolean(["feature", "repetierTargetTemp"], data["feature"]["repetierTargetTemp"])
|
||||
if "externalHeatupDetection" in data["feature"].keys(): s.setBoolean(["feature", "externalHeatupDetection"], data["feature"]["externalHeatupDetection"])
|
||||
if "keyboardControl" in data["feature"].keys(): s.setBoolean(["feature", "keyboardControl"], data["feature"]["keyboardControl"])
|
||||
if "gcodeViewer" in data["feature"]: s.setBoolean(["gcodeViewer", "enabled"], data["feature"]["gcodeViewer"])
|
||||
if "sizeThreshold" in data["feature"]: s.setInt(["gcodeViewer", "sizeThreshold"], data["feature"]["sizeThreshold"])
|
||||
if "mobileSizeThreshold" in data["feature"]: s.setInt(["gcodeViewer", "mobileSizeThreshold"], data["feature"]["mobileSizeThreshold"])
|
||||
if "temperatureGraph" in data["feature"]: s.setBoolean(["feature", "temperatureGraph"], data["feature"]["temperatureGraph"])
|
||||
if "waitForStart" in data["feature"]: s.setBoolean(["feature", "waitForStartOnConnect"], data["feature"]["waitForStart"])
|
||||
if "alwaysSendChecksum" in data["feature"]: s.setBoolean(["feature", "alwaysSendChecksum"], data["feature"]["alwaysSendChecksum"])
|
||||
if "neverSendChecksum" in data["feature"]: s.setBoolean(["feature", "neverSendChecksum"], data["feature"]["neverSendChecksum"])
|
||||
if "sdSupport" in data["feature"]: s.setBoolean(["feature", "sdSupport"], data["feature"]["sdSupport"])
|
||||
if "sdRelativePath" in data["feature"]: s.setBoolean(["feature", "sdRelativePath"], data["feature"]["sdRelativePath"])
|
||||
if "sdAlwaysAvailable" in data["feature"]: s.setBoolean(["feature", "sdAlwaysAvailable"], data["feature"]["sdAlwaysAvailable"])
|
||||
if "swallowOkAfterResend" in data["feature"]: s.setBoolean(["feature", "swallowOkAfterResend"], data["feature"]["swallowOkAfterResend"])
|
||||
if "repetierTargetTemp" in data["feature"]: s.setBoolean(["feature", "repetierTargetTemp"], data["feature"]["repetierTargetTemp"])
|
||||
if "externalHeatupDetection" in data["feature"]: s.setBoolean(["feature", "externalHeatupDetection"], data["feature"]["externalHeatupDetection"])
|
||||
if "keyboardControl" in data["feature"]: s.setBoolean(["feature", "keyboardControl"], data["feature"]["keyboardControl"])
|
||||
if "pollWatched" in data["feature"]: s.setBoolean(["feature", "pollWatched"], data["feature"]["pollWatched"])
|
||||
if "ignoreIdenticalResends" in data["feature"]: s.setBoolean(["feature", "ignoreIdenticalResends"], data["feature"]["ignoreIdenticalResends"])
|
||||
if "modelSizeDetection" in data["feature"]: s.setBoolean(["feature", "modelSizeDetection"], data["feature"]["modelSizeDetection"])
|
||||
@@ -319,15 +335,15 @@ def _saveSettings(data):
|
||||
if "blockWhileDwelling" in data["feature"]: s.setBoolean(["feature", "blockWhileDwelling"], data["feature"]["blockWhileDwelling"])
|
||||
|
||||
if "serial" in data.keys():
|
||||
if "autoconnect" in data["serial"].keys(): s.setBoolean(["serial", "autoconnect"], data["serial"]["autoconnect"])
|
||||
if "port" in data["serial"].keys(): s.set(["serial", "port"], data["serial"]["port"])
|
||||
if "baudrate" in data["serial"].keys(): s.setInt(["serial", "baudrate"], data["serial"]["baudrate"])
|
||||
if "timeoutConnection" in data["serial"].keys(): s.setFloat(["serial", "timeout", "connection"], data["serial"]["timeoutConnection"])
|
||||
if "timeoutDetection" in data["serial"].keys(): s.setFloat(["serial", "timeout", "detection"], data["serial"]["timeoutDetection"])
|
||||
if "timeoutCommunication" in data["serial"].keys(): s.setFloat(["serial", "timeout", "communication"], data["serial"]["timeoutCommunication"])
|
||||
if "timeoutTemperature" in data["serial"].keys(): s.setFloat(["serial", "timeout", "temperature"], data["serial"]["timeoutTemperature"])
|
||||
if "timeoutTemperatureTargetSet" in data["serial"].keys(): s.setFloat(["serial", "timeout", "temperatureTargetSet"], data["serial"]["timeoutTemperatureTargetSet"])
|
||||
if "timeoutSdStatus" in data["serial"].keys(): s.setFloat(["serial", "timeout", "sdStatus"], data["serial"]["timeoutSdStatus"])
|
||||
if "autoconnect" in data["serial"]: s.setBoolean(["serial", "autoconnect"], data["serial"]["autoconnect"])
|
||||
if "port" in data["serial"]: s.set(["serial", "port"], data["serial"]["port"])
|
||||
if "baudrate" in data["serial"]: s.setInt(["serial", "baudrate"], data["serial"]["baudrate"])
|
||||
if "timeoutConnection" in data["serial"]: s.setFloat(["serial", "timeout", "connection"], data["serial"]["timeoutConnection"])
|
||||
if "timeoutDetection" in data["serial"]: s.setFloat(["serial", "timeout", "detection"], data["serial"]["timeoutDetection"])
|
||||
if "timeoutCommunication" in data["serial"]: s.setFloat(["serial", "timeout", "communication"], data["serial"]["timeoutCommunication"])
|
||||
if "timeoutTemperature" in data["serial"]: s.setFloat(["serial", "timeout", "temperature"], data["serial"]["timeoutTemperature"])
|
||||
if "timeoutTemperatureTargetSet" in data["serial"]: s.setFloat(["serial", "timeout", "temperatureTargetSet"], data["serial"]["timeoutTemperatureTargetSet"])
|
||||
if "timeoutSdStatus" in data["serial"]: s.setFloat(["serial", "timeout", "sdStatus"], data["serial"]["timeoutSdStatus"])
|
||||
if "additionalPorts" in data["serial"] and isinstance(data["serial"]["additionalPorts"], (list, tuple)): s.set(["serial", "additionalPorts"], data["serial"]["additionalPorts"])
|
||||
if "additionalBaudrates" in data["serial"] and isinstance(data["serial"]["additionalBaudrates"], (list, tuple)): s.set(["serial", "additionalBaudrates"], data["serial"]["additionalBaudrates"])
|
||||
if "longRunningCommands" in data["serial"] and isinstance(data["serial"]["longRunningCommands"], (list, tuple)): s.set(["serial", "longRunningCommands"], data["serial"]["longRunningCommands"])
|
||||
@@ -342,7 +358,7 @@ def _saveSettings(data):
|
||||
if "maxTimeoutsLong" in data["serial"]: s.setInt(["serial", "maxCommunicationTimeouts", "long"], data["serial"]["maxTimeoutsLong"])
|
||||
|
||||
oldLog = s.getBoolean(["serial", "log"])
|
||||
if "log" in data["serial"].keys(): s.setBoolean(["serial", "log"], data["serial"]["log"])
|
||||
if "log" in data["serial"]: s.setBoolean(["serial", "log"], data["serial"]["log"])
|
||||
if oldLog and not s.getBoolean(["serial", "log"]):
|
||||
# disable debug logging to serial.log
|
||||
logging.getLogger("SERIAL").debug("Disabling serial logging")
|
||||
@@ -353,22 +369,22 @@ def _saveSettings(data):
|
||||
logging.getLogger("SERIAL").debug("Enabling serial logging")
|
||||
|
||||
if "folder" in data.keys():
|
||||
if "uploads" in data["folder"].keys(): s.setBaseFolder("uploads", data["folder"]["uploads"])
|
||||
if "timelapse" in data["folder"].keys(): s.setBaseFolder("timelapse", data["folder"]["timelapse"])
|
||||
if "timelapseTmp" in data["folder"].keys(): s.setBaseFolder("timelapse_tmp", data["folder"]["timelapseTmp"])
|
||||
if "logs" in data["folder"].keys(): s.setBaseFolder("logs", data["folder"]["logs"])
|
||||
if "watched" in data["folder"].keys(): s.setBaseFolder("watched", data["folder"]["watched"])
|
||||
if "uploads" in data["folder"]: s.setBaseFolder("uploads", data["folder"]["uploads"])
|
||||
if "timelapse" in data["folder"]: s.setBaseFolder("timelapse", data["folder"]["timelapse"])
|
||||
if "timelapseTmp" in data["folder"]: s.setBaseFolder("timelapse_tmp", data["folder"]["timelapseTmp"])
|
||||
if "logs" in data["folder"]: s.setBaseFolder("logs", data["folder"]["logs"])
|
||||
if "watched" in data["folder"]: s.setBaseFolder("watched", data["folder"]["watched"])
|
||||
|
||||
if "temperature" in data.keys():
|
||||
if "profiles" in data["temperature"].keys(): s.set(["temperature", "profiles"], data["temperature"]["profiles"])
|
||||
if "cutoff" in data["temperature"].keys(): s.setInt(["temperature", "cutoff"], data["temperature"]["cutoff"])
|
||||
if "profiles" in data["temperature"]: s.set(["temperature", "profiles"], data["temperature"]["profiles"])
|
||||
if "cutoff" in data["temperature"]: s.setInt(["temperature", "cutoff"], data["temperature"]["cutoff"])
|
||||
|
||||
if "terminalFilters" in data.keys():
|
||||
s.set(["terminalFilters"], data["terminalFilters"])
|
||||
|
||||
if "system" in data.keys():
|
||||
if "actions" in data["system"].keys(): s.set(["system", "actions"], data["system"]["actions"])
|
||||
if "events" in data["system"].keys(): s.set(["system", "events"], data["system"]["events"])
|
||||
if "actions" in data["system"]: s.set(["system", "actions"], data["system"]["actions"])
|
||||
if "events" in data["system"]: s.set(["system", "events"], data["system"]["events"])
|
||||
|
||||
if "scripts" in data:
|
||||
if "gcode" in data["scripts"] and isinstance(data["scripts"]["gcode"], dict):
|
||||
@@ -379,9 +395,9 @@ def _saveSettings(data):
|
||||
|
||||
if "server" in data:
|
||||
if "commands" in data["server"]:
|
||||
if "systemShutdownCommand" in data["server"]["commands"].keys(): s.set(["server", "commands", "systemShutdownCommand"], data["server"]["commands"]["systemShutdownCommand"])
|
||||
if "systemRestartCommand" in data["server"]["commands"].keys(): s.set(["server", "commands", "systemRestartCommand"], data["server"]["commands"]["systemRestartCommand"])
|
||||
if "serverRestartCommand" in data["server"]["commands"].keys(): s.set(["server", "commands", "serverRestartCommand"], data["server"]["commands"]["serverRestartCommand"])
|
||||
if "systemShutdownCommand" in data["server"]["commands"]: s.set(["server", "commands", "systemShutdownCommand"], data["server"]["commands"]["systemShutdownCommand"])
|
||||
if "systemRestartCommand" in data["server"]["commands"]: s.set(["server", "commands", "systemRestartCommand"], data["server"]["commands"]["systemRestartCommand"])
|
||||
if "serverRestartCommand" in data["server"]["commands"]: s.set(["server", "commands", "serverRestartCommand"], data["server"]["commands"]["serverRestartCommand"])
|
||||
if "diskspace" in data["server"]:
|
||||
if "warning" in data["server"]["diskspace"]: s.setInt(["server", "diskspace", "warning"], data["server"]["diskspace"]["warning"])
|
||||
if "critical" in data["server"]["diskspace"]: s.setInt(["server", "diskspace", "critical"], data["server"]["diskspace"]["critical"])
|
||||
|
||||
@@ -203,43 +203,37 @@ def setTimelapseConfig():
|
||||
return make_response("Invalid value for fps: %d" % fps, 400)
|
||||
|
||||
if "interval" in data:
|
||||
config["options"] = {
|
||||
"interval": 10
|
||||
}
|
||||
|
||||
try:
|
||||
interval = int(data["interval"])
|
||||
except ValueError:
|
||||
return make_response("Invalid value for interval: %r" % data["interval"])
|
||||
return make_response("Invalid value for interval: %r" % data["interval"], 400)
|
||||
else:
|
||||
if interval > 0:
|
||||
config["options"]["interval"] = interval
|
||||
else:
|
||||
return make_response("Invalid value for interval: %d" % interval)
|
||||
return make_response("Invalid value for interval: %d" % interval, 400)
|
||||
|
||||
if "capturePostRoll" in data:
|
||||
config["options"]["capturePostRoll"] = True
|
||||
try:
|
||||
capturePostRoll = bool(data["capturePostRoll"])
|
||||
except ValueError:
|
||||
return make_response("Invalid value for capturePostRoll: %r" % data["capturePostRoll"])
|
||||
return make_response("Invalid value for capturePostRoll: %r" % data["capturePostRoll"], 400)
|
||||
else:
|
||||
config["options"]["capturePostRoll"] = capturePostRoll
|
||||
if capturePostRoll >= 0:
|
||||
config["options"]["capturePostRoll"] = capturePostRoll
|
||||
else:
|
||||
return make_response("Invalid value for capturePostRoll: %d" % capturePostRoll, 400)
|
||||
|
||||
if "retractionZHop" in data:
|
||||
config["options"] = {
|
||||
"retractionZHop": 0
|
||||
}
|
||||
|
||||
try:
|
||||
retractionZHop = float(data["retractionZHop"])
|
||||
except ValueError:
|
||||
return make_response("Invalid value for retraction Z-Hop: %r" % data["retractionZHop"])
|
||||
return make_response("Invalid value for retraction Z-Hop: %r" % data["retractionZHop"], 400)
|
||||
else:
|
||||
if retractionZHop >= 0:
|
||||
config["options"]["retractionZHop"] = retractionZHop
|
||||
else:
|
||||
return make_response("Invalid value for retraction Z-Hop: %d" % retractionZHop)
|
||||
return make_response("Invalid value for retraction Z-Hop: %d" % retractionZHop, 400)
|
||||
|
||||
|
||||
if admin_permission.can() and "save" in data and data["save"] in valid_boolean_trues:
|
||||
|
||||
@@ -301,7 +301,7 @@ def index():
|
||||
|
||||
decorated_view = view
|
||||
decorated_view = util.flask.lastmodified(lambda _: compute_lastmodified())(decorated_view)
|
||||
decorated_view = util.flask.etagged(lambda _: compute_etag(additional=cache_key()))(decorated_view)
|
||||
decorated_view = util.flask.etagged(lambda _: compute_etag(additional=[cache_key()] + additional_etag))(decorated_view)
|
||||
decorated_view = util.flask.cached(timeout=-1,
|
||||
refreshif=validate_cache,
|
||||
key=cache_key,
|
||||
|
||||
@@ -179,7 +179,8 @@ default_settings = {
|
||||
"gcodeAnalysis": {
|
||||
"maxExtruders": 10,
|
||||
"throttle_normalprio": 0.01,
|
||||
"throttle_highprio": 0.0
|
||||
"throttle_highprio": 0.0,
|
||||
"throttle_lines": 100
|
||||
},
|
||||
"feature": {
|
||||
"temperatureGraph": True,
|
||||
@@ -228,8 +229,7 @@ default_settings = {
|
||||
"cutoff": 30
|
||||
},
|
||||
"printerProfiles": {
|
||||
"default": None,
|
||||
"defaultProfile": {}
|
||||
"default": None
|
||||
},
|
||||
"printerParameters": {
|
||||
"pauseTriggers": [],
|
||||
@@ -339,7 +339,6 @@ default_settings = {
|
||||
"enabled": False,
|
||||
"okAfterResend": False,
|
||||
"forceChecksum": False,
|
||||
"okWithLinenumber": False,
|
||||
"numExtruders": 1,
|
||||
"includeCurrentToolInTemps": True,
|
||||
"includeFilenameInOpened": True,
|
||||
@@ -364,7 +363,9 @@ default_settings = {
|
||||
"sharedNozzle": False,
|
||||
"sendBusy": False,
|
||||
"simulateReset": True,
|
||||
"preparedOks": []
|
||||
"preparedOks": [],
|
||||
"okFormatString": "ok",
|
||||
"m115FormatString": "FIRMWARE_NAME: {firmware_name} PROTOCOL_VERSION:1.0"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -559,9 +560,9 @@ class Settings(object):
|
||||
self._configfile = os.path.join(self._basedir, "config.yaml")
|
||||
self.load(migrate=True)
|
||||
|
||||
if self.get(["api", "key"]) is None:
|
||||
self.set(["api", "key"], ''.join('%02X' % z for z in bytes(uuid.uuid4().bytes)))
|
||||
self.save(force=True)
|
||||
apikey = self.get(["api", "key"])
|
||||
if not apikey or apikey == "n/a":
|
||||
self.generateApiKey()
|
||||
|
||||
self._script_env = self._init_script_templating()
|
||||
|
||||
@@ -1500,6 +1501,17 @@ class Settings(object):
|
||||
with atomic_write(filename, "wb", max_permissions=0o666) as f:
|
||||
f.write(script)
|
||||
|
||||
def generateApiKey(self):
|
||||
apikey = ''.join('%02X' % z for z in bytes(uuid.uuid4().bytes))
|
||||
self.set(["api", "key"], apikey)
|
||||
self.save(force=True)
|
||||
return apikey
|
||||
|
||||
def deleteApiKey(self):
|
||||
self.set(["api", "key"], None)
|
||||
self.save(force=True)
|
||||
|
||||
|
||||
def _default_basedir(applicationName):
|
||||
# taken from http://stackoverflow.com/questions/1084697/how-do-i-store-desktop-application-data-in-a-cross-platform-way-for-python
|
||||
if sys.platform == "darwin":
|
||||
|
||||
@@ -1 +1 @@
|
||||
.btn{display:inline-block;padding:4px 12px;margin-bottom:0;font-size:14px;line-height:20px;text-align:center;vertical-align:middle;cursor:pointer;color:#333;text-shadow:0 1px 1px rgba(255,255,255,.75);background-color:#f5f5f5;background-image:-moz-linear-gradient(top,#fff,#e6e6e6);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fff),to(#e6e6e6));background-image:-webkit-linear-gradient(top,#fff,#e6e6e6);background-image:-o-linear-gradient(top,#fff,#e6e6e6);background-image:linear-gradient(to bottom,#fff,#e6e6e6);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffffff', endColorstr='#ffe6e6e6', GradientType=0);border-color:#e6e6e6 #e6e6e6 #bfbfbf;border-color:rgba(0,0,0,.1) rgba(0,0,0,.1) rgba(0,0,0,.25);filter:progid:DXImageTransform.Microsoft.gradient(enabled=false);border:1px solid #ccc;border-bottom-color:#b3b3b3;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;-webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05);box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05)}.btn.active,.btn.disabled,.btn:active,.btn:focus,.btn:hover,.btn[disabled]{color:#333;background-color:#e6e6e6}.btn.active,.btn:active{background-color:#ccc\9}.btn:focus,.btn:hover{color:#333;text-decoration:none;background-position:0 -15px;-webkit-transition:background-position .1s linear;-moz-transition:background-position .1s linear;-o-transition:background-position .1s linear;transition:background-position .1s linear}.btn:focus{outline:thin dotted #333;outline:5px auto -webkit-focus-ring-color;outline-offset:-2px}.btn.active,.btn:active{background-image:none;outline:0;-webkit-box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05);box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05)}.btn.disabled,.btn[disabled]{cursor:default;background-image:none;opacity:.65;filter:alpha(opacity=65);-webkit-box-shadow:none;-moz-box-shadow:none;box-shadow:none}.btn-large{padding:11px 19px;font-size:17.5px;-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px}.btn-large [class*=" icon-"],.btn-large [class^=icon-]{margin-top:4px}.btn-small{padding:2px 10px;font-size:11.9px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.btn-small [class*=" icon-"],.btn-small [class^=icon-]{margin-top:0}.btn-mini [class*=" icon-"],.btn-mini [class^=icon-]{margin-top:-1px}.btn-mini{padding:0 6px;font-size:10.5px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.btn-block{display:block;width:100%;padding-left:0;padding-right:0;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}.btn-block+.btn-block{margin-top:5px}input[type=submit].btn-block,input[type=reset].btn-block,input[type=button].btn-block{width:100%}.btn-danger.active,.btn-info.active,.btn-inverse.active,.btn-primary.active,.btn-success.active,.btn-warning.active{color:rgba(255,255,255,.75)}.btn-primary{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,.25);background-color:#006dcc;background-image:-moz-linear-gradient(top,#08c,#04c);background-image:-webkit-gradient(linear,0 0,0 100%,from(#08c),to(#04c));background-image:-webkit-linear-gradient(top,#08c,#04c);background-image:-o-linear-gradient(top,#08c,#04c);background-image:linear-gradient(to bottom,#08c,#04c);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff0088cc', endColorstr='#ff0044cc', GradientType=0);border-color:#04c #04c #002a80;border-color:rgba(0,0,0,.1) rgba(0,0,0,.1) rgba(0,0,0,.25);filter:progid:DXImageTransform.Microsoft.gradient(enabled=false)}.btn-primary.active,.btn-primary.disabled,.btn-primary:active,.btn-primary:focus,.btn-primary:hover,.btn-primary[disabled]{color:#fff;background-color:#04c}.btn-primary.active,.btn-primary:active{background-color:#039\9}.btn-warning{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,.25);background-color:#faa732;background-image:-moz-linear-gradient(top,#fbb450,#f89406);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fbb450),to(#f89406));background-image:-webkit-linear-gradient(top,#fbb450,#f89406);background-image:-o-linear-gradient(top,#fbb450,#f89406);background-image:linear-gradient(to bottom,#fbb450,#f89406);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#fffbb450', endColorstr='#fff89406', GradientType=0);border-color:#f89406 #f89406 #ad6704;border-color:rgba(0,0,0,.1) rgba(0,0,0,.1) rgba(0,0,0,.25);filter:progid:DXImageTransform.Microsoft.gradient(enabled=false)}.btn-warning.active,.btn-warning.disabled,.btn-warning:active,.btn-warning:focus,.btn-warning:hover,.btn-warning[disabled]{color:#fff;background-color:#f89406}.btn-warning.active,.btn-warning:active{background-color:#c67605\9}.btn-danger{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,.25);backLine truncated
|
||||
.btn{display:inline-block;padding:4px 12px;margin-bottom:0;font-size:14px;line-height:20px;text-align:center;vertical-align:middle;cursor:pointer;color:#333;text-shadow:0 1px 1px rgba(255,255,255,.75);background-color:#f5f5f5;background-image:-moz-linear-gradient(top,#fff,#e6e6e6);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fff),to(#e6e6e6));background-image:-webkit-linear-gradient(top,#fff,#e6e6e6);background-image:-o-linear-gradient(top,#fff,#e6e6e6);background-image:linear-gradient(to bottom,#fff,#e6e6e6);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffffff', endColorstr='#ffe6e6e6', GradientType=0);border-color:#e6e6e6 #e6e6e6 #bfbfbf;border-color:rgba(0,0,0,.1) rgba(0,0,0,.1) rgba(0,0,0,.25);filter:progid:DXImageTransform.Microsoft.gradient(enabled=false);border:1px solid #ccc;border-bottom-color:#b3b3b3;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;-webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05);box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05)}.btn.active,.btn.disabled,.btn:active,.btn:focus,.btn:hover,.btn[disabled]{color:#333;background-color:#e6e6e6}.btn.active,.btn:active{background-color:#ccc\9}.btn:focus,.btn:hover{color:#333;text-decoration:none;background-position:0 -15px;-webkit-transition:background-position .1s linear;-moz-transition:background-position .1s linear;-o-transition:background-position .1s linear;transition:background-position .1s linear}.btn:focus{outline:thin dotted #333;outline:5px auto -webkit-focus-ring-color;outline-offset:-2px}.btn.active,.btn:active{background-image:none;outline:0;-webkit-box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05);box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05)}.btn.disabled,.btn[disabled]{cursor:default;background-image:none;opacity:.65;filter:alpha(opacity=65);-webkit-box-shadow:none;-moz-box-shadow:none;box-shadow:none}.btn-large{padding:11px 19px;font-size:17.5px;-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px}.btn-large [class*=" icon-"],.btn-large [class^=icon-]{margin-top:4px}.btn-small{padding:2px 10px;font-size:11.9px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.btn-small [class*=" icon-"],.btn-small [class^=icon-]{margin-top:0}.btn-mini [class*=" icon-"],.btn-mini [class^=icon-]{margin-top:-1px}.btn-mini{padding:0 6px;font-size:10.5px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.btn-block{display:block;width:100%;padding-left:0;padding-right:0;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}.btn-block+.btn-block{margin-top:5px}input[type=submit].btn-block,input[type=reset].btn-block,input[type=button].btn-block{width:100%}.btn-danger.active,.btn-info.active,.btn-inverse.active,.btn-primary.active,.btn-success.active,.btn-warning.active{color:rgba(255,255,255,.75)}.btn-primary{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,.25);background-color:#006dcc;background-image:-moz-linear-gradient(top,#08c,#04c);background-image:-webkit-gradient(linear,0 0,0 100%,from(#08c),to(#04c));background-image:-webkit-linear-gradient(top,#08c,#04c);background-image:-o-linear-gradient(top,#08c,#04c);background-image:linear-gradient(to bottom,#08c,#04c);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff0088cc', endColorstr='#ff0044cc', GradientType=0);border-color:#04c #04c #002a80;border-color:rgba(0,0,0,.1) rgba(0,0,0,.1) rgba(0,0,0,.25);filter:progid:DXImageTransform.Microsoft.gradient(enabled=false)}.btn-primary.active,.btn-primary.disabled,.btn-primary:active,.btn-primary:focus,.btn-primary:hover,.btn-primary[disabled]{color:#fff;background-color:#04c}.btn-primary.active,.btn-primary:active{background-color:#039\9}.btn-warning{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,.25);background-color:#faa732;background-image:-moz-linear-gradient(top,#fbb450,#f89406);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fbb450),to(#f89406));background-image:-webkit-linear-gradient(top,#fbb450,#f89406);background-image:-o-linear-gradient(top,#fbb450,#f89406);background-image:linear-gradient(to bottom,#fbb450,#f89406);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#fffbb450', endColorstr='#fff89406', GradientType=0);border-color:#f89406 #f89406 #ad6704;border-color:rgba(0,0,0,.1) rgba(0,0,0,.1) rgba(0,0,0,.25);filter:progid:DXImageTransform.Microsoft.gradient(enabled=false)}.btn-warning.active,.btn-warning.disabled,.btn-warning:active,.btn-warning:focus,.btn-warning:hover,.btn-warning[disabled]{color:#fff;background-color:#f89406}.btn-warning.active,.btn-warning:active{background-color:#c67605\9}.btn-danger{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,.25);backLine truncated
|
||||
@@ -0,0 +1 @@
|
||||
.ui-pnotify-closer,.ui-pnotify-sticker{float:right;margin-left:.2em}
|
||||
@@ -0,0 +1 @@
|
||||
.ui-pnotify{top:25px;right:25px;position:absolute;height:auto;z-index:9999}html>body>.ui-pnotify{position:fixed}.ui-pnotify .ui-pnotify-shadow{-webkit-box-shadow:0 2px 10px rgba(50,50,50,.5);-moz-box-shadow:0 2px 10px rgba(50,50,50,.5);box-shadow:0 2px 10px rgba(50,50,50,.5)}.ui-pnotify-container{background-position:0 0;padding:.8em;height:100%;margin:0}.ui-pnotify-container.ui-pnotify-sharp{-webkit-border-radius:0;-moz-border-radius:0;border-radius:0}.ui-pnotify-title{display:block;margin-bottom:.4em;margin-top:0}.ui-pnotify-text{display:block}.ui-pnotify-icon,.ui-pnotify-icon span{display:block;float:left;margin-right:.2em}.ui-pnotify.stack-bottomleft,.ui-pnotify.stack-topleft{left:25px;right:auto}.ui-pnotify.stack-bottomleft,.ui-pnotify.stack-bottomright{bottom:25px;top:auto}
|
||||
@@ -0,0 +1 @@
|
||||
.ui-pnotify-history-container{position:absolute;top:0;right:18px;width:70px;border-top:none;padding:0;-webkit-border-top-left-radius:0;-moz-border-top-left-radius:0;border-top-left-radius:0;-webkit-border-top-right-radius:0;-moz-border-top-right-radius:0;border-top-right-radius:0;z-index:10000}.ui-pnotify-history-container.ui-pnotify-history-fixed{position:fixed}.ui-pnotify-history-container .ui-pnotify-history-header{padding:2px;text-align:center}.ui-pnotify-history-container button{cursor:pointer;display:block;width:100%}.ui-pnotify-history-container .ui-pnotify-history-pulldown{display:block;margin:0 auto}
|
||||
-1
@@ -1 +0,0 @@
|
||||
.ui-pnotify{top:25px;right:25px;position:absolute;height:auto;z-index:9999}html>body>.ui-pnotify{position:fixed}.ui-pnotify .ui-pnotify-shadow{-webkit-box-shadow:0 2px 10px rgba(50,50,50,.5);-moz-box-shadow:0 2px 10px rgba(50,50,50,.5);box-shadow:0 2px 10px rgba(50,50,50,.5)}.ui-pnotify-container{background-position:0 0;padding:.8em;height:100%;margin:0}.ui-pnotify-sharp{-webkit-border-radius:0;-moz-border-radius:0;border-radius:0}.ui-pnotify-title{display:block;margin-bottom:.4em;margin-top:0}.ui-pnotify-text{display:block}.ui-pnotify-icon,.ui-pnotify-icon span{display:block;float:left;margin-right:.2em}.ui-pnotify.stack-bottomleft,.ui-pnotify.stack-topleft{left:25px;right:auto}.ui-pnotify.stack-bottomleft,.ui-pnotify.stack-bottomright{bottom:25px;top:auto}.ui-pnotify-closer,.ui-pnotify-sticker{float:right;margin-left:.2em}.ui-pnotify-history-container{position:absolute;top:0;right:18px;width:70px;border-top:none;padding:0;-webkit-border-top-left-radius:0;-moz-border-top-left-radius:0;border-top-left-radius:0;-webkit-border-top-right-radius:0;-moz-border-top-right-radius:0;border-top-right-radius:0;z-index:10000}.ui-pnotify-history-container.ui-pnotify-history-fixed{position:fixed}.ui-pnotify-history-container .ui-pnotify-history-header{padding:2px;text-align:center}.ui-pnotify-history-container button{cursor:pointer;display:block;width:100%}.ui-pnotify-history-container .ui-pnotify-history-pulldown{display:block;margin:0 auto}
|
||||
@@ -6,6 +6,7 @@
|
||||
}
|
||||
})(this, function(OctoPrintClient, $) {
|
||||
var url = "api/settings";
|
||||
var apiKeyUrl = url + "/apikey";
|
||||
|
||||
var OctoPrintSettingsClient = function(base) {
|
||||
this.base = base;
|
||||
@@ -40,6 +41,10 @@
|
||||
return this.save(data, opts);
|
||||
};
|
||||
|
||||
OctoPrintSettingsClient.prototype.generateApiKey = function (opts) {
|
||||
return this.base.postJson(apiKeyUrl, opts);
|
||||
};
|
||||
|
||||
OctoPrintClient.registerComponent("settings", OctoPrintSettingsClient);
|
||||
return OctoPrintSettingsClient;
|
||||
});
|
||||
@@ -27,10 +27,6 @@
|
||||
};
|
||||
|
||||
OctoPrintSocketClient.prototype.propagateMessage = function(event, data) {
|
||||
if (!this.registeredHandlers.hasOwnProperty(event)) {
|
||||
return;
|
||||
}
|
||||
|
||||
var start = new Date().getTime();
|
||||
|
||||
var eventObj = {event: event, data: data};
|
||||
|
||||
@@ -162,6 +162,12 @@ function ItemListHelper(listType, supportedSorting, supportedFilters, defaultSor
|
||||
return undefined;
|
||||
};
|
||||
|
||||
self.resetPage = function() {
|
||||
if (self.currentPage() > self.lastPage()) {
|
||||
self.currentPage(self.lastPage());
|
||||
}
|
||||
};
|
||||
|
||||
//~~ searching
|
||||
|
||||
self.changeSearchFunction = function(searchFunction) {
|
||||
@@ -670,10 +676,163 @@ function showConfirmationDialog(msg, onacknowledge, options) {
|
||||
return modal;
|
||||
}
|
||||
|
||||
/**
|
||||
* Shows a progress modal depending on a supplied promise.
|
||||
*
|
||||
* Will listen to the supplied promise, update the progress on .progress events and
|
||||
* enabling the close button and (optionally) closing the dialog on promise resolve.
|
||||
*
|
||||
* The calling code should call "notify" on the deferred backing the promise and supply
|
||||
* two parameters: the text to display on the progress bar and the optional output field and
|
||||
* a boolean value indicating whether the operation behind that update was successful or not.
|
||||
* Non-successful progress updates will remove the barClassSuccess class from the progress bar and
|
||||
* apply the barClassFailure class and also apply the outputClassFailure to the produced line
|
||||
* in the output.
|
||||
*
|
||||
* To determine the progress, calling code should supply the prognosed maximum number of
|
||||
* progress events. An internal counter will increment on each progress event and used together
|
||||
* with the max value to calculate the percentage to display on the progress bar.
|
||||
*
|
||||
* If no max value is set, the progress bar will show a striped animation at 100% fill status
|
||||
* to visualize "unknown but ongoing" status.
|
||||
*
|
||||
* Available options:
|
||||
*
|
||||
* * title: the title of the modal, defaults to "Progress"
|
||||
* * message: the message of the modal, defaults to ""
|
||||
* * buttonText: the text on the close button, defaults to "Close"
|
||||
* * max: maximum number of expected progress events (when 100% will be reached), defaults
|
||||
* to undefined
|
||||
* * close: whether to close the dialog on completion, defaults to false
|
||||
* * output: whether to display the progress texts in an output field, defaults to false
|
||||
* * dialogClass: additional class to apply to the dialog div
|
||||
* * barClassSuccess: additional class for the progress bar while all progress events are
|
||||
* successful
|
||||
* * barClassFailure: additional class for the progress bar when a progress event was
|
||||
* unsuccessful
|
||||
* * outputClassSuccess: additional class for successful output lines
|
||||
* * outputClassFailure: additional class for unsuccessful output lines
|
||||
*
|
||||
* @param options modal options
|
||||
* @param promise promise to monitor
|
||||
* @returns {*|jQuery} the modal object
|
||||
*/
|
||||
function showProgressModal(options, promise) {
|
||||
var title = options.title || gettext("Progress");
|
||||
var message = options.message || "";
|
||||
var buttonText = options.button || gettext("Close");
|
||||
var max = options.max || undefined;
|
||||
var close = options.close || false;
|
||||
var output = options.output || false;
|
||||
|
||||
var dialogClass = options.dialogClass || "";
|
||||
var barClassSuccess = options.barClassSuccess || "";
|
||||
var barClassFailure = options.barClassFailure || "bar-danger";
|
||||
var outputClassSuccess = options.outputClassSuccess || "";
|
||||
var outputClassFailure = options.outputClassFailure || "text-error";
|
||||
|
||||
var modalHeader = $('<h3>' + title + '</h3>');
|
||||
var paragraph = $('<p>' + message + '</p>');
|
||||
|
||||
var progress = $('<div class="progress progress-text-centered"></div>');
|
||||
var progressBar = $('<div class="bar"></div>')
|
||||
.addClass(barClassSuccess);
|
||||
var progressTextBack = $('<span class="progress-text-back"></span>');
|
||||
var progressTextFront = $('<span class="progress-text-front"></span>')
|
||||
.width(progress.width());
|
||||
|
||||
if (max == undefined) {
|
||||
progress.addClass("progress-striped active");
|
||||
progressBar.width("100%");
|
||||
}
|
||||
|
||||
progressBar
|
||||
.append(progressTextFront);
|
||||
progress
|
||||
.append(progressTextBack)
|
||||
.append(progressBar);
|
||||
|
||||
var button = $('<button class="btn">' + buttonText + '</button>')
|
||||
.prop("disabled", true)
|
||||
.attr("data-dismiss", "modal")
|
||||
.attr("aria-hidden", "true");
|
||||
|
||||
var modalBody = $('<div></div>')
|
||||
.addClass('modal-body')
|
||||
.append(paragraph)
|
||||
.append(progress);
|
||||
|
||||
var pre;
|
||||
if (output) {
|
||||
pre = $("<pre class='terminal pre-scrollable' style='height: 70px; font-size: 0.8em'></pre>");
|
||||
modalBody.append(pre);
|
||||
}
|
||||
|
||||
var modal = $('<div></div>')
|
||||
.addClass('modal hide fade')
|
||||
.addClass(dialogClass)
|
||||
.append($('<div></div>').addClass('modal-header').append(modalHeader))
|
||||
.append(modalBody)
|
||||
.append($('<div></div>').addClass('modal-footer').append(button));
|
||||
modal.modal({keyboard: false, backdrop: "static", show: true});
|
||||
|
||||
var counter = 0;
|
||||
promise
|
||||
.progress(function(text, success) {
|
||||
var value;
|
||||
|
||||
if (max === undefined || max <= 0) {
|
||||
value = 100;
|
||||
} else {
|
||||
counter++;
|
||||
value = Math.max(Math.min(counter * 100 / max, 100), 0);
|
||||
}
|
||||
|
||||
// update progress bar
|
||||
progressBar.width(String(value) + "%");
|
||||
progressTextFront.text(text);
|
||||
progressTextBack.text(text);
|
||||
progressTextFront.width(progress.width());
|
||||
|
||||
// if not successful, apply failure class
|
||||
if (!success && !progressBar.hasClass(barClassFailure)) {
|
||||
progressBar
|
||||
.removeClass(barClassSuccess)
|
||||
.addClass(barClassFailure);
|
||||
}
|
||||
|
||||
if (output && pre) {
|
||||
if (success) {
|
||||
pre.append($("<span class='" + outputClassSuccess + "'>" + text + "</span><br>"));
|
||||
} else {
|
||||
pre.append($("<span class='" + outputClassFailure + "'>" + text + "</span><br>"));
|
||||
}
|
||||
pre.scrollTop(pre[0].scrollHeight - pre.height());
|
||||
}
|
||||
})
|
||||
.done(function() {
|
||||
button.prop("disabled", false);
|
||||
if (close) {
|
||||
modal.modal("hide");
|
||||
}
|
||||
})
|
||||
.fail(function() {
|
||||
button.prop("disabled", false);
|
||||
});
|
||||
|
||||
return modal;
|
||||
}
|
||||
|
||||
function showReloadOverlay() {
|
||||
$("#reloadui_overlay").show();
|
||||
}
|
||||
|
||||
function wrapPromiseWithAlways(p) {
|
||||
var deferred = $.Deferred();
|
||||
p.always(function() { deferred.resolve.apply(deferred, arguments); });
|
||||
return deferred.promise();
|
||||
}
|
||||
|
||||
function commentableLinesToArray(lines) {
|
||||
return splitTextToArray(lines, "\n", true, function(item) {return !_.startsWith(item, "#")});
|
||||
}
|
||||
|
||||
@@ -40,6 +40,8 @@ $(function() {
|
||||
size: ko.observable(undefined)
|
||||
};
|
||||
|
||||
self.needsLoad = false;
|
||||
|
||||
self.renderer_centerModel = ko.observable(false);
|
||||
self.renderer_centerViewport = ko.observable(false);
|
||||
self.renderer_zoomOnModel = ko.observable(false);
|
||||
@@ -301,6 +303,7 @@ $(function() {
|
||||
|
||||
self.loadFile = function(path, date){
|
||||
self.enableReload(false);
|
||||
self.needsLoad = false;
|
||||
if (self.status == "idle" && self.errorCount < 3) {
|
||||
self.status = "request";
|
||||
OctoPrint.files.download("local", path)
|
||||
@@ -402,7 +405,11 @@ $(function() {
|
||||
self.loadedFileDate = undefined;
|
||||
} else {
|
||||
self.waitForApproval(false);
|
||||
self.loadFile(data.job.file.path, data.job.file.date);
|
||||
if (self.tabActive) {
|
||||
self.loadFile(data.job.file.path, data.job.file.date);
|
||||
} else {
|
||||
self.needsLoad = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -574,6 +581,9 @@ $(function() {
|
||||
|
||||
self.onTabChange = function(current, previous) {
|
||||
self.tabActive = current == "#gcode";
|
||||
if (self.tabActive && self.needsLoad) {
|
||||
self.loadFile(self.selectedFile.path(), self.selectedFile.date());
|
||||
}
|
||||
};
|
||||
|
||||
self.shiftLayer = function(value){
|
||||
|
||||
@@ -46,7 +46,7 @@ $(function() {
|
||||
}
|
||||
|
||||
OctoPrint.users.get(self.currentUser().name)
|
||||
.done(self.fromResponse);
|
||||
.done(self.updateCurrentUserData);
|
||||
};
|
||||
|
||||
self.requestData = function() {
|
||||
@@ -57,31 +57,37 @@ $(function() {
|
||||
self.fromResponse = function(response) {
|
||||
if (response && response.name) {
|
||||
self.loggedIn(true);
|
||||
self.username(response.name);
|
||||
self.usergroups(response.groups);
|
||||
self.userpermissions(response.permissions);
|
||||
self.isUser(self.hasPermission("User"));
|
||||
self.isAdmin(self.hasPermission("Admin"));
|
||||
|
||||
self.currentUser(response);
|
||||
|
||||
self.updateCurrentUserData(response);
|
||||
callViewModels(self.allViewModels, "onUserLoggedIn", [response]);
|
||||
} else {
|
||||
self.loggedIn(false);
|
||||
self.username(undefined);
|
||||
OctoPrint.groups.get("Guests").done(function(group) {
|
||||
self.usergroups([group]);
|
||||
});
|
||||
self.userpermissions([]);
|
||||
self.isUser(false);
|
||||
self.isAdmin(false);
|
||||
|
||||
self.currentUser(undefined);
|
||||
|
||||
self.resetCurrentUserData();
|
||||
callViewModels(self.allViewModels, "onUserLoggedOut");
|
||||
}
|
||||
};
|
||||
|
||||
self.updateCurrentUserData = function(data) {
|
||||
self.username(data.name);
|
||||
self.usergroups(data.groups);
|
||||
self.userpermissions(data.permissions);
|
||||
self.isUser(self.hasPermission("User"));
|
||||
self.isAdmin(self.hasPermission("Admin"));
|
||||
|
||||
self.currentUser(data);
|
||||
};
|
||||
|
||||
self.resetCurrentUserData = function() {
|
||||
self.username(undefined);
|
||||
OctoPrint.groups.get("Guests").done(function(group) {
|
||||
self.usergroups([group]);
|
||||
});
|
||||
self.userpermissions([]);
|
||||
self.isUser(false);
|
||||
self.isAdmin(false);
|
||||
|
||||
self.currentUser(undefined);
|
||||
};
|
||||
|
||||
self.login = function(u, p, r) {
|
||||
var username = u || self.loginUser();
|
||||
var password = p || self.loginPass();
|
||||
@@ -147,13 +153,17 @@ $(function() {
|
||||
});
|
||||
|
||||
$("body").on("click", function(e) {
|
||||
if (!toggle.hasClass("open")) {
|
||||
return;
|
||||
}
|
||||
|
||||
var anyFormLinkOrButton = $("#login_dropdown_loggedout a, #login_dropdown_loggedin a, #login_dropdown_loggedout button, #login_dropdown_loggedin button");
|
||||
var dropdown = $("li.dropdown#navbar_login");
|
||||
var anyLastpassButton = $("#__lpform_login_user, #__lpform_login_pass");
|
||||
|
||||
var isLinkOrButton = anyFormLinkOrButton.is(e.target) || anyFormLinkOrButton.has(e.target).length !== 0;
|
||||
var isDropdown = dropdown.is(e.target) || dropdown.has(e.target).length === 0;
|
||||
var isLastpass = anyLastpassButton.is(e.target) || anyLastpassButton.has(e.target).length === 0;
|
||||
var isDropdown = dropdown.is(e.target) || dropdown.has(e.target).length !== 0;
|
||||
var isLastpass = anyLastpassButton.is(e.target) || anyLastpassButton.has(e.target).length !== 0;
|
||||
|
||||
if (isLinkOrButton || !(isDropdown || isLastpass)) {
|
||||
toggle.removeClass("open");
|
||||
|
||||
@@ -444,6 +444,14 @@ $(function() {
|
||||
self.updateProfile(profile);
|
||||
};
|
||||
|
||||
self.canMakeDefault = function(data) {
|
||||
return !data.isdefault();
|
||||
};
|
||||
|
||||
self.canRemove = function(data) {
|
||||
return !data.iscurrent() && !data.isdefault();
|
||||
};
|
||||
|
||||
self.requestData = function() {
|
||||
OctoPrint.printerprofiles.list()
|
||||
.done(self.fromResponse);
|
||||
@@ -482,9 +490,9 @@ $(function() {
|
||||
}
|
||||
self.requestData();
|
||||
})
|
||||
.fail(function() {
|
||||
.fail(function(xhr) {
|
||||
var text = gettext("There was unexpected error while saving the printer profile, please consult the logs.");
|
||||
new PNotify({title: gettext("Saving failed"), text: text, type: "error", hide: false});
|
||||
new PNotify({title: gettext("Could not add profile"), text: text, type: "error", hide: false});
|
||||
})
|
||||
.always(function() {
|
||||
self.requestInProgress(false);
|
||||
@@ -492,18 +500,28 @@ $(function() {
|
||||
};
|
||||
|
||||
self.removeProfile = function(data) {
|
||||
self.requestInProgress(true);
|
||||
OctoPrint.printerprofiles.delete(data.id, {url: data.resource})
|
||||
.done(function() {
|
||||
self.requestData();
|
||||
})
|
||||
.fail(function() {
|
||||
var text = gettext("There was unexpected error while removing the printer profile, please consult the logs.");
|
||||
new PNotify({title: gettext("Saving failed"), text: text, type: "error", hide: false});
|
||||
})
|
||||
.always(function() {
|
||||
self.requestInProgress(false);
|
||||
});
|
||||
var perform = function() {
|
||||
self.requestInProgress(true);
|
||||
OctoPrint.printerprofiles.delete(data.id, {url: data.resource})
|
||||
.done(function() {
|
||||
self.requestData();
|
||||
})
|
||||
.fail(function(xhr) {
|
||||
var text;
|
||||
if (xhr.status == 409) {
|
||||
text = gettext("Cannot delete the default profile or the currently active profile.");
|
||||
} else {
|
||||
text = gettext("There was unexpected error while removing the printer profile, please consult the logs.");
|
||||
}
|
||||
new PNotify({title: gettext("Could not delete profile"), text: text, type: "error", hide: false});
|
||||
})
|
||||
.always(function() {
|
||||
self.requestInProgress(false);
|
||||
});
|
||||
};
|
||||
|
||||
showConfirmationDialog(_.sprintf(gettext("You are about to delete the printer profile \"%(name)s\"."), {name: data.name}),
|
||||
perform);
|
||||
};
|
||||
|
||||
self.updateProfile = function(profile, callback) {
|
||||
@@ -521,7 +539,7 @@ $(function() {
|
||||
})
|
||||
.fail(function() {
|
||||
var text = gettext("There was unexpected error while updating the printer profile, please consult the logs.");
|
||||
new PNotify({title: gettext("Saving failed"), text: text, type: "error", hide: false});
|
||||
new PNotify({title: gettext("Could not update profile"), text: text, type: "error", hide: false});
|
||||
})
|
||||
.always(function() {
|
||||
self.requestInProgress(false);
|
||||
|
||||
@@ -311,10 +311,6 @@ $(function() {
|
||||
});
|
||||
};
|
||||
|
||||
self.onSettingsShown = function() {
|
||||
self.requestData();
|
||||
};
|
||||
|
||||
self.onSettingsHidden = function() {
|
||||
self.webcam_ffmpegPathReset();
|
||||
};
|
||||
@@ -421,6 +417,19 @@ $(function() {
|
||||
self.settingsDialog.modal("hide");
|
||||
};
|
||||
|
||||
self.generateApiKey = function() {
|
||||
if (!CONFIG_ACCESS_CONTROL) return;
|
||||
|
||||
showConfirmationDialog(gettext("This will generate a new API Key. The old API Key will cease to function immediately."),
|
||||
function() {
|
||||
OctoPrint.settings.generateApiKey()
|
||||
.done(function(response) {
|
||||
self.api_key(response.apikey);
|
||||
self.requestData();
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
self.showTranslationManager = function() {
|
||||
self.translationManagerDialog.modal();
|
||||
return false;
|
||||
@@ -816,7 +825,7 @@ $(function() {
|
||||
};
|
||||
|
||||
self._resetScrollPosition = function() {
|
||||
$('.scrollable', self.settingsDialog).scrollTop(0);
|
||||
$('#settings_dialog_content', self.settingsDialog).scrollTop(0);
|
||||
};
|
||||
|
||||
self.selectTab = function(tab) {
|
||||
@@ -835,6 +844,16 @@ $(function() {
|
||||
// better refresh them now
|
||||
self.requestData();
|
||||
};
|
||||
|
||||
self.onUserLoggedIn = function() {
|
||||
// we might have other user rights now, refresh
|
||||
self.requestData();
|
||||
};
|
||||
|
||||
self.onUserLoggedOut = function() {
|
||||
// we might have other user rights now, refresh
|
||||
self.requestData();
|
||||
}
|
||||
}
|
||||
|
||||
OCTOPRINT_VIEWMODELS.push([
|
||||
|
||||
@@ -30,6 +30,13 @@ $(function() {
|
||||
self.isReady = ko.observable(undefined);
|
||||
self.isLoading = ko.observable(undefined);
|
||||
|
||||
self.markedForFileDeletion = ko.observableArray([]);
|
||||
self.markedForUnrenderedDeletion = ko.observableArray([]);
|
||||
|
||||
self.isTemporary = ko.pureComputed(function() {
|
||||
return self.isDirty() && !self.persist();
|
||||
});
|
||||
|
||||
self.isBusy = ko.pureComputed(function() {
|
||||
return self.isPrinting() || self.isPaused();
|
||||
});
|
||||
@@ -66,6 +73,9 @@ $(function() {
|
||||
self.timelapseCapturePostRoll.subscribe(function() {
|
||||
self.isDirty(true);
|
||||
});
|
||||
self.persist.subscribe(function() {
|
||||
self.isDirty(true);
|
||||
});
|
||||
|
||||
// initialize list helper
|
||||
self.listHelper = new ItemListHelper(
|
||||
@@ -138,12 +148,17 @@ $(function() {
|
||||
var config = response.config;
|
||||
if (config === undefined) return;
|
||||
|
||||
self.timelapseType(config.type);
|
||||
// timelapses & unrendered
|
||||
self.listHelper.updateItems(response.files);
|
||||
self.listHelper.resetPage();
|
||||
if (response.unrendered) {
|
||||
self.unrenderedListHelper.updateItems(response.unrendered);
|
||||
self.unrenderedListHelper.resetPage();
|
||||
}
|
||||
|
||||
// timelapse config
|
||||
self.timelapseType(config.type);
|
||||
|
||||
if (config.type == "timed") {
|
||||
if (config.interval != undefined && config.interval > 0) {
|
||||
self.timelapseTimedInterval(config.interval);
|
||||
@@ -200,14 +215,135 @@ $(function() {
|
||||
self.isLoading(data.flags.loading);
|
||||
};
|
||||
|
||||
self.markFilesOnPage = function() {
|
||||
self.markedForFileDeletion(_.uniq(self.markedForFileDeletion().concat(_.map(self.listHelper.paginatedItems(), "name"))));
|
||||
};
|
||||
|
||||
self.markAllFiles = function() {
|
||||
self.markedForFileDeletion(_.map(self.listHelper.allItems, "name"));
|
||||
};
|
||||
|
||||
self.clearMarkedFiles = function() {
|
||||
self.markedForFileDeletion.removeAll();
|
||||
};
|
||||
|
||||
self.removeFile = function(filename) {
|
||||
OctoPrint.timelapse.delete(filename)
|
||||
.done(self.requestData);
|
||||
var perform = function() {
|
||||
OctoPrint.timelapse.delete(filename)
|
||||
.done(function() {
|
||||
self.markedForFileDeletion.remove(filename);
|
||||
self.requestData()
|
||||
});
|
||||
};
|
||||
|
||||
showConfirmationDialog(_.sprintf(gettext("You are about to delete timelapse file \"%(name)s\"."), {name: filename}),
|
||||
perform)
|
||||
};
|
||||
|
||||
self.removeMarkedFiles = function() {
|
||||
var perform = function() {
|
||||
self._bulkRemove(self.markedForFileDeletion(), "files")
|
||||
.done(function() {
|
||||
self.markedForFileDeletion.removeAll();
|
||||
});
|
||||
};
|
||||
|
||||
showConfirmationDialog(_.sprintf(gettext("You are about to delete %(count)d timelapse files."), {count: self.markedForFileDeletion().length}),
|
||||
perform);
|
||||
};
|
||||
|
||||
self.markUnrenderedOnPage = function() {
|
||||
self.markedForUnrenderedDeletion(_.uniq(self.markedForUnrenderedDeletion().concat(_.map(self.unrenderedListHelper.paginatedItems(), "name"))));
|
||||
};
|
||||
|
||||
self.markAllUnrendered = function() {
|
||||
self.markedForUnrenderedDeletion(_.map(self.unrenderedListHelper.allItems, "name"));
|
||||
};
|
||||
|
||||
self.clearMarkedUnrendered = function() {
|
||||
self.markedForUnrenderedDeletion.removeAll();
|
||||
};
|
||||
|
||||
self.removeUnrendered = function(name) {
|
||||
OctoPrint.timelapse.deleteUnrendered(name)
|
||||
.done(self.requestData);
|
||||
var perform = function() {
|
||||
OctoPrint.timelapse.deleteUnrendered(name)
|
||||
.done(function() {
|
||||
self.markedForUnrenderedDeletion.remove(name);
|
||||
self.requestData();
|
||||
});
|
||||
};
|
||||
|
||||
showConfirmationDialog(_.sprintf(gettext("You are about to delete unrendered timelapse \"%(name)s\"."), {name: name}),
|
||||
perform)
|
||||
};
|
||||
|
||||
self.removeMarkedUnrendered = function() {
|
||||
var perform = function() {
|
||||
self._bulkRemove(self.markedForUnrenderedDeletion(), "unrendered")
|
||||
.done(function() {
|
||||
self.markedForUnrenderedDeletion.removeAll();
|
||||
});
|
||||
};
|
||||
|
||||
showConfirmationDialog(_.sprintf(gettext("You are about to delete %(count)d unrendered timelapses."), {count: self.markedForUnrenderedDeletion().length}),
|
||||
perform);
|
||||
};
|
||||
|
||||
self._bulkRemove = function(files, type) {
|
||||
var title, message, handler;
|
||||
|
||||
if (type == "files") {
|
||||
title = gettext("Deleting timelapse files");
|
||||
message = _.sprintf(gettext("Deleting %(count)d timelapse files..."), {count: files.length});
|
||||
handler = function(filename) {
|
||||
return OctoPrint.timelapse.delete(filename)
|
||||
.done(function() {
|
||||
deferred.notify(_.sprintf(gettext("Deleted %(filename)s..."), {filename: filename}), true);
|
||||
})
|
||||
.fail(function() {
|
||||
deferred.notify(_.sprintf(gettext("Deletion of %(filename)s failed, continuing..."), {filename: filename}), false);
|
||||
});
|
||||
}
|
||||
} else if (type == "unrendered") {
|
||||
title = gettext("Deleting unrendered timelapses");
|
||||
message = _.sprintf(gettext("Deleting %(count)d unrendered timelapses..."), {count: files.length});
|
||||
handler = function(filename) {
|
||||
return OctoPrint.timelapse.deleteUnrendered(filename)
|
||||
.done(function() {
|
||||
deferred.notify(_.sprintf(gettext("Deleted %(filename)s..."), {filename: filename}), true);
|
||||
})
|
||||
.fail(function() {
|
||||
deferred.notify(_.sprintf(gettext("Deletion of %(filename)s failed, continuing..."), {filename: filename}), false);
|
||||
});
|
||||
}
|
||||
} else {
|
||||
return;
|
||||
}
|
||||
|
||||
var deferred = $.Deferred();
|
||||
|
||||
var promise = deferred.promise();
|
||||
|
||||
var options = {
|
||||
title: title,
|
||||
message: message,
|
||||
max: files.length,
|
||||
output: true
|
||||
};
|
||||
showProgressModal(options, promise);
|
||||
|
||||
var requests = [];
|
||||
_.each(files, function(filename) {
|
||||
var request = handler(filename);
|
||||
requests.push(request)
|
||||
});
|
||||
$.when.apply($, _.map(requests, wrapPromiseWithAlways))
|
||||
.done(function() {
|
||||
deferred.resolve();
|
||||
self.requestData();
|
||||
});
|
||||
|
||||
return promise;
|
||||
};
|
||||
|
||||
self.renderUnrendered = function(name) {
|
||||
|
||||
@@ -71,16 +71,32 @@ $(function() {
|
||||
|
||||
self.generateApikey = function() {
|
||||
if (!CONFIG_ACCESS_CONTROL) return;
|
||||
self.users.generateApikey(self.currentUser().name, function(response) {
|
||||
self.access_apikey(response.apikey);
|
||||
});
|
||||
|
||||
var generate = function() {
|
||||
self.users.generateApikey(self.currentUser().name)
|
||||
.done(function(response) {
|
||||
self.access_apikey(response.apikey);
|
||||
});
|
||||
};
|
||||
|
||||
if (self.access_apikey()) {
|
||||
showConfirmationDialog(gettext("This will generate a new API Key. The old API Key will cease to function immediately."),
|
||||
generate);
|
||||
} else {
|
||||
generate();
|
||||
}
|
||||
};
|
||||
|
||||
self.deleteApikey = function() {
|
||||
if (!CONFIG_ACCESS_CONTROL) return;
|
||||
self.users.deleteApikey(self.currentUser().name, function() {
|
||||
self.access_apikey(undefined);
|
||||
});
|
||||
if (!self.access_apikey()) return;
|
||||
|
||||
showConfirmationDialog(gettext("This will delete the API Key. It will cease to to function immediately."), function() {
|
||||
self.users.deleteApikey(self.currentUser().name)
|
||||
.done(function() {
|
||||
self.access_apikey(undefined);
|
||||
});
|
||||
})
|
||||
};
|
||||
|
||||
self.updateSettings = function(username, settings) {
|
||||
|
||||
-54
@@ -1,54 +0,0 @@
|
||||
/*
|
||||
PNotify 2.0.1 sciactive.com/pnotify/
|
||||
(C) 2014 Hunter Perrin
|
||||
license GPL/LGPL/MPL
|
||||
*/
|
||||
(function(c){"function"===typeof define&&define.amd?define("pnotify",["jquery"],c):c(jQuery)})(function(c){var p={dir1:"down",dir2:"left",push:"bottom",spacing1:25,spacing2:25,context:c("body")},f,g,h=c(window),m=function(){g=c("body");PNotify.prototype.options.stack.context=g;h=c(window);h.bind("resize",function(){f&&clearTimeout(f);f=setTimeout(function(){PNotify.positionAll(!0)},10)})};PNotify=function(b){this.parseOptions(b);this.init()};c.extend(PNotify.prototype,{version:"2.0.1",options:{title:!1,
|
||||
title_escape:!1,text:!1,text_escape:!1,styling:"bootstrap3",addclass:"",cornerclass:"",auto_display:!0,width:"300px",min_height:"16px",type:"notice",icon:!0,opacity:1,animation:"fade",animate_speed:"slow",position_animate_speed:500,shadow:!0,hide:!0,delay:8E3,mouse_reset:!0,remove:!0,insert_brs:!0,destroy:!0,stack:p},modules:{},runModules:function(b,a){var c,e;for(e in this.modules)if(c="object"===typeof a&&e in a?a[e]:a,"function"===typeof this.modules[e][b])this.modules[e][b](this,"object"===typeof this.options[e]?
|
||||
this.options[e]:{},c)},state:"initializing",timer:null,styles:null,elem:null,container:null,title_container:null,text_container:null,animating:!1,timerHide:!1,init:function(){var b=this;this.modules={};c.extend(!0,this.modules,PNotify.prototype.modules);this.styles="object"===typeof this.options.styling?this.options.styling:PNotify.styling[this.options.styling];this.elem=c("<div />",{"class":"ui-pnotify "+this.options.addclass,css:{display:"none"},mouseenter:function(a){if(b.options.mouse_reset&&
|
||||
"out"===b.animating){if(!b.timerHide)return;b.cancelRemove()}b.options.hide&&b.options.mouse_reset&&b.cancelRemove()},mouseleave:function(a){b.options.hide&&b.options.mouse_reset&&b.queueRemove();PNotify.positionAll()}});this.container=c("<div />",{"class":this.styles.container+" ui-pnotify-container "+("error"===this.options.type?this.styles.error:"info"===this.options.type?this.styles.info:"success"===this.options.type?this.styles.success:this.styles.notice)}).appendTo(this.elem);""!==this.options.cornerclass&&
|
||||
this.container.removeClass("ui-corner-all").addClass(this.options.cornerclass);this.options.shadow&&this.container.addClass("ui-pnotify-shadow");!1!==this.options.icon&&c("<div />",{"class":"ui-pnotify-icon"}).append(c("<span />",{"class":!0===this.options.icon?"error"===this.options.type?this.styles.error_icon:"info"===this.options.type?this.styles.info_icon:"success"===this.options.type?this.styles.success_icon:this.styles.notice_icon:this.options.icon})).prependTo(this.container);this.title_container=
|
||||
c("<h4 />",{"class":"ui-pnotify-title"}).appendTo(this.container);!1===this.options.title?this.title_container.hide():this.options.title_escape?this.title_container.text(this.options.title):this.title_container.html(this.options.title);this.text_container=c("<div />",{"class":"ui-pnotify-text"}).appendTo(this.container);!1===this.options.text?this.text_container.hide():this.options.text_escape?this.text_container.text(this.options.text):this.text_container.html(this.options.insert_brs?String(this.options.text).replace(/\n/g,
|
||||
"<br />"):this.options.text);"string"===typeof this.options.width&&this.elem.css("width",this.options.width);"string"===typeof this.options.min_height&&this.container.css("min-height",this.options.min_height);PNotify.notices="top"===this.options.stack.push?c.merge([this],PNotify.notices):c.merge(PNotify.notices,[this]);"top"===this.options.stack.push&&this.queuePosition(!1,1);this.options.stack.animation=!1;this.runModules("init");this.options.auto_display&&this.open();return this},update:function(b){var a=
|
||||
this.options;this.parseOptions(a,b);this.options.cornerclass!==a.cornerclass&&this.container.removeClass("ui-corner-all "+a.cornerclass).addClass(this.options.cornerclass);this.options.shadow!==a.shadow&&(this.options.shadow?this.container.addClass("ui-pnotify-shadow"):this.container.removeClass("ui-pnotify-shadow"));!1===this.options.addclass?this.elem.removeClass(a.addclass):this.options.addclass!==a.addclass&&this.elem.removeClass(a.addclass).addClass(this.options.addclass);!1===this.options.title?
|
||||
this.title_container.slideUp("fast"):this.options.title!==a.title&&(this.options.title_escape?this.title_container.text(this.options.title):this.title_container.html(this.options.title),!1===a.title&&this.title_container.slideDown(200));!1===this.options.text?this.text_container.slideUp("fast"):this.options.text!==a.text&&(this.options.text_escape?this.text_container.text(this.options.text):this.text_container.html(this.options.insert_brs?String(this.options.text).replace(/\n/g,"<br />"):this.options.text),
|
||||
!1===a.text&&this.text_container.slideDown(200));this.options.type!==a.type&&this.container.removeClass(this.styles.error+" "+this.styles.notice+" "+this.styles.success+" "+this.styles.info).addClass("error"===this.options.type?this.styles.error:"info"===this.options.type?this.styles.info:"success"===this.options.type?this.styles.success:this.styles.notice);if(this.options.icon!==a.icon||!0===this.options.icon&&this.options.type!==a.type)this.container.find("div.ui-pnotify-icon").remove(),!1!==this.options.icon&&
|
||||
c("<div />",{"class":"ui-pnotify-icon"}).append(c("<span />",{"class":!0===this.options.icon?"error"===this.options.type?this.styles.error_icon:"info"===this.options.type?this.styles.info_icon:"success"===this.options.type?this.styles.success_icon:this.styles.notice_icon:this.options.icon})).prependTo(this.container);this.options.width!==a.width&&this.elem.animate({width:this.options.width});this.options.min_height!==a.min_height&&this.container.animate({minHeight:this.options.min_height});this.options.opacity!==
|
||||
a.opacity&&this.elem.fadeTo(this.options.animate_speed,this.options.opacity);this.options.hide?a.hide||this.queueRemove():this.cancelRemove();this.queuePosition(!0);this.runModules("update",a);return this},open:function(){this.state="opening";this.runModules("beforeOpen");var b=this;this.elem.parent().length||this.elem.appendTo(this.options.stack.context?this.options.stack.context:g);"top"!==this.options.stack.push&&this.position(!0);"fade"===this.options.animation||"fade"===this.options.animation.effect_in?
|
||||
this.elem.show().fadeTo(0,0).hide():1!==this.options.opacity&&this.elem.show().fadeTo(0,this.options.opacity).hide();this.animateIn(function(){b.queuePosition(!0);b.options.hide&&b.queueRemove();b.state="open";b.runModules("afterOpen")});return this},remove:function(b){this.state="closing";this.timerHide=!!b;this.runModules("beforeClose");var a=this;this.timer&&(window.clearTimeout(this.timer),this.timer=null);this.animateOut(function(){a.state="closed";a.runModules("afterClose");a.queuePosition(!0);
|
||||
a.options.remove&&a.elem.detach();a.runModules("beforeDestroy");if(a.options.destroy&&null!==PNotify.notices){var b=c.inArray(a,PNotify.notices);-1!==b&&PNotify.notices.splice(b,1)}a.runModules("afterDestroy")});return this},get:function(){return this.elem},parseOptions:function(b,a){this.options=c.extend(!0,{},PNotify.prototype.options);this.options.stack=PNotify.prototype.options.stack;var n=[b,a],e,f;for(f in n){e=n[f];if("undefined"==typeof e)break;if("object"!==typeof e)this.options.text=e;else for(var d in e)this.modules[d]?
|
||||
c.extend(!0,this.options[d],e[d]):this.options[d]=e[d]}},animateIn:function(b){this.animating="in";var a;a="undefined"!==typeof this.options.animation.effect_in?this.options.animation.effect_in:this.options.animation;"none"===a?(this.elem.show(),b()):"show"===a?this.elem.show(this.options.animate_speed,b):"fade"===a?this.elem.show().fadeTo(this.options.animate_speed,this.options.opacity,b):"slide"===a?this.elem.slideDown(this.options.animate_speed,b):"function"===typeof a?a("in",b,this.elem):this.elem.show(a,
|
||||
"object"===typeof this.options.animation.options_in?this.options.animation.options_in:{},this.options.animate_speed,b);this.elem.parent().hasClass("ui-effects-wrapper")&&this.elem.parent().css({position:"fixed",overflow:"visible"});"slide"!==a&&this.elem.css("overflow","visible");this.container.css("overflow","hidden")},animateOut:function(b){this.animating="out";var a;a="undefined"!==typeof this.options.animation.effect_out?this.options.animation.effect_out:this.options.animation;"none"===a?(this.elem.hide(),
|
||||
b()):"show"===a?this.elem.hide(this.options.animate_speed,b):"fade"===a?this.elem.fadeOut(this.options.animate_speed,b):"slide"===a?this.elem.slideUp(this.options.animate_speed,b):"function"===typeof a?a("out",b,this.elem):this.elem.hide(a,"object"===typeof this.options.animation.options_out?this.options.animation.options_out:{},this.options.animate_speed,b);this.elem.parent().hasClass("ui-effects-wrapper")&&this.elem.parent().css({position:"fixed",overflow:"visible"});"slide"!==a&&this.elem.css("overflow",
|
||||
"visible");this.container.css("overflow","hidden")},position:function(b){var a=this.options.stack,c=this.elem;c.parent().hasClass("ui-effects-wrapper")&&(c=this.elem.css({left:"0",top:"0",right:"0",bottom:"0"}).parent());"undefined"===typeof a.context&&(a.context=g);if(a){"number"!==typeof a.nextpos1&&(a.nextpos1=a.firstpos1);"number"!==typeof a.nextpos2&&(a.nextpos2=a.firstpos2);"number"!==typeof a.addpos2&&(a.addpos2=0);var e="none"===c.css("display");if(!e||b){var f,d={},k;switch(a.dir1){case "down":k=
|
||||
"top";break;case "up":k="bottom";break;case "left":k="right";break;case "right":k="left"}b=parseInt(c.css(k).replace(/(?:\..*|[^0-9.])/g,""));isNaN(b)&&(b=0);"undefined"!==typeof a.firstpos1||e||(a.firstpos1=b,a.nextpos1=a.firstpos1);var l;switch(a.dir2){case "down":l="top";break;case "up":l="bottom";break;case "left":l="right";break;case "right":l="left"}f=parseInt(c.css(l).replace(/(?:\..*|[^0-9.])/g,""));isNaN(f)&&(f=0);"undefined"!==typeof a.firstpos2||e||(a.firstpos2=f,a.nextpos2=a.firstpos2);
|
||||
if("down"===a.dir1&&a.nextpos1+c.height()>(a.context.is(g)?h.height():a.context.prop("scrollHeight"))||"up"===a.dir1&&a.nextpos1+c.height()>(a.context.is(g)?h.height():a.context.prop("scrollHeight"))||"left"===a.dir1&&a.nextpos1+c.width()>(a.context.is(g)?h.width():a.context.prop("scrollWidth"))||"right"===a.dir1&&a.nextpos1+c.width()>(a.context.is(g)?h.width():a.context.prop("scrollWidth")))a.nextpos1=a.firstpos1,a.nextpos2+=a.addpos2+("undefined"===typeof a.spacing2?25:a.spacing2),a.addpos2=0;if(a.animation&&
|
||||
a.nextpos2<f)switch(a.dir2){case "down":d.top=a.nextpos2+"px";break;case "up":d.bottom=a.nextpos2+"px";break;case "left":d.right=a.nextpos2+"px";break;case "right":d.left=a.nextpos2+"px"}else"number"===typeof a.nextpos2&&c.css(l,a.nextpos2+"px");switch(a.dir2){case "down":case "up":c.outerHeight(!0)>a.addpos2&&(a.addpos2=c.height());break;case "left":case "right":c.outerWidth(!0)>a.addpos2&&(a.addpos2=c.width())}if("number"===typeof a.nextpos1)if(a.animation&&(b>a.nextpos1||d.top||d.bottom||d.right||
|
||||
d.left))switch(a.dir1){case "down":d.top=a.nextpos1+"px";break;case "up":d.bottom=a.nextpos1+"px";break;case "left":d.right=a.nextpos1+"px";break;case "right":d.left=a.nextpos1+"px"}else c.css(k,a.nextpos1+"px");(d.top||d.bottom||d.right||d.left)&&c.animate(d,{duration:this.options.position_animate_speed,queue:!1});switch(a.dir1){case "down":case "up":a.nextpos1+=c.height()+("undefined"===typeof a.spacing1?25:a.spacing1);break;case "left":case "right":a.nextpos1+=c.width()+("undefined"===typeof a.spacing1?
|
||||
25:a.spacing1)}}return this}},queuePosition:function(b,a){f&&clearTimeout(f);a||(a=10);f=setTimeout(function(){PNotify.positionAll(b)},a);return this},cancelRemove:function(){this.timer&&window.clearTimeout(this.timer);"closing"===this.state&&(this.elem.stop(!0),this.state="open",this.animating="in",this.elem.css("height","auto").animate({width:this.options.width,opacity:this.options.opacity},"fast"));return this},queueRemove:function(){var b=this;this.cancelRemove();this.timer=window.setTimeout(function(){b.remove(!0)},
|
||||
isNaN(this.options.delay)?0:this.options.delay);return this}});c.extend(PNotify,{notices:[],removeAll:function(){c.each(PNotify.notices,function(){this.remove&&this.remove()})},positionAll:function(b){f&&clearTimeout(f);f=null;c.each(PNotify.notices,function(){var a=this.options.stack;a&&(a.nextpos1=a.firstpos1,a.nextpos2=a.firstpos2,a.addpos2=0,a.animation=b)});c.each(PNotify.notices,function(){this.position()})},styling:{jqueryui:{container:"ui-widget ui-widget-content ui-corner-all",notice:"ui-state-highlight",
|
||||
notice_icon:"ui-icon ui-icon-info",info:"",info_icon:"ui-icon ui-icon-info",success:"ui-state-default",success_icon:"ui-icon ui-icon-circle-check",error:"ui-state-error",error_icon:"ui-icon ui-icon-alert"},bootstrap2:{container:"alert",notice:"",notice_icon:"icon-exclamation-sign",info:"alert-info",info_icon:"icon-info-sign",success:"alert-success",success_icon:"icon-ok-sign",error:"alert-error",error_icon:"icon-warning-sign"},bootstrap3:{container:"alert",notice:"alert-warning",notice_icon:"glyphicon glyphicon-exclamation-sign",
|
||||
info:"alert-info",info_icon:"glyphicon glyphicon-info-sign",success:"alert-success",success_icon:"glyphicon glyphicon-ok-sign",error:"alert-danger",error_icon:"glyphicon glyphicon-warning-sign"}}});PNotify.styling.fontawesome=c.extend({},PNotify.styling.bootstrap3);c.extend(PNotify.styling.fontawesome,{notice_icon:"fa fa-exclamation-circle",info_icon:"fa fa-info",success_icon:"fa fa-check",error_icon:"fa fa-warning"});document.body?m():c(m);return PNotify});
|
||||
(function(c){"function"===typeof define&&define.amd?define("pnotify.buttons",["jquery","pnotify"],c):c(jQuery,PNotify)})(function(c,e){e.prototype.options.buttons={closer:!0,closer_hover:!0,sticker:!0,sticker_hover:!0,labels:{close:"Close",stick:"Stick"}};e.prototype.modules.buttons={myOptions:null,closer:null,sticker:null,init:function(a,b){var d=this;this.myOptions=b;a.elem.on({mouseenter:function(b){!d.myOptions.sticker||a.options.nonblock&&a.options.nonblock.nonblock||d.sticker.trigger("pnotify_icon").css("visibility",
|
||||
"visible");!d.myOptions.closer||a.options.nonblock&&a.options.nonblock.nonblock||d.closer.css("visibility","visible")},mouseleave:function(a){d.myOptions.sticker_hover&&d.sticker.css("visibility","hidden");d.myOptions.closer_hover&&d.closer.css("visibility","hidden")}});this.sticker=c("<div />",{"class":"ui-pnotify-sticker",css:{cursor:"pointer",visibility:b.sticker_hover?"hidden":"visible"},click:function(){a.options.hide=!a.options.hide;a.options.hide?a.queueRemove():a.cancelRemove();c(this).trigger("pnotify_icon")}}).bind("pnotify_icon",
|
||||
function(){c(this).children().removeClass(a.styles.pin_up+" "+a.styles.pin_down).addClass(a.options.hide?a.styles.pin_up:a.styles.pin_down)}).append(c("<span />",{"class":a.styles.pin_up,title:b.labels.stick})).prependTo(a.container);(!b.sticker||a.options.nonblock&&a.options.nonblock.nonblock)&&this.sticker.css("display","none");this.closer=c("<div />",{"class":"ui-pnotify-closer",css:{cursor:"pointer",visibility:b.closer_hover?"hidden":"visible"},click:function(){a.remove(!1);d.sticker.css("visibility",
|
||||
"hidden");d.closer.css("visibility","hidden")}}).append(c("<span />",{"class":a.styles.closer,title:b.labels.close})).prependTo(a.container);(!b.closer||a.options.nonblock&&a.options.nonblock.nonblock)&&this.closer.css("display","none")},update:function(a,b){this.myOptions=b;!b.closer||a.options.nonblock&&a.options.nonblock.nonblock?this.closer.css("display","none"):b.closer&&this.closer.css("display","block");!b.sticker||a.options.nonblock&&a.options.nonblock.nonblock?this.sticker.css("display",
|
||||
"none"):b.sticker&&this.sticker.css("display","block");this.sticker.trigger("pnotify_icon");b.sticker_hover?this.sticker.css("visibility","hidden"):a.options.nonblock&&a.options.nonblock.nonblock||this.sticker.css("visibility","visible");b.closer_hover?this.closer.css("visibility","hidden"):a.options.nonblock&&a.options.nonblock.nonblock||this.closer.css("visibility","visible")}};c.extend(e.styling.jqueryui,{closer:"ui-icon ui-icon-close",pin_up:"ui-icon ui-icon-pin-w",pin_down:"ui-icon ui-icon-pin-s"});
|
||||
c.extend(e.styling.bootstrap2,{closer:"icon-remove",pin_up:"icon-pause",pin_down:"icon-play"});c.extend(e.styling.bootstrap3,{closer:"glyphicon glyphicon-remove",pin_up:"glyphicon glyphicon-pause",pin_down:"glyphicon glyphicon-play"});c.extend(e.styling.fontawesome,{closer:"fa fa-times",pin_up:"fa fa-pause",pin_down:"fa fa-play"})});
|
||||
(function(d){"function"===typeof define&&define.amd?define("pnotify.confirm",["jquery","pnotify"],d):d(jQuery,PNotify)})(function(d,e){e.prototype.options.confirm={confirm:!1,prompt:!1,prompt_class:"",prompt_default:"",prompt_multi_line:!1,align:"right",buttons:[{text:"Ok",addClass:"",promptTrigger:!0,click:function(b,a){b.remove();b.get().trigger("pnotify.confirm",[b,a])}},{text:"Cancel",addClass:"",click:function(b){b.remove();b.get().trigger("pnotify.cancel",b)}}]};e.prototype.modules.confirm=
|
||||
{container:null,prompt:null,init:function(b,a){this.container=d('<div style="margin-top:5px;clear:both;" />').css("text-align",a.align).appendTo(b.container);a.confirm||a.prompt?this.makeDialog(b,a):this.container.hide()},update:function(b,a){a.confirm?(this.makeDialog(b,a),this.container.show()):this.container.hide().empty()},afterOpen:function(b,a){a.prompt&&this.prompt.focus()},makeDialog:function(b,a){var e=!1,h=this,f,c;this.container.empty();a.prompt&&(this.prompt=d("<"+(a.prompt_multi_line?
|
||||
'textarea rows="5"':'input type="text"')+' style="margin-bottom:5px;clear:both;" />').addClass(b.styles.input+" "+a.prompt_class).val(a.prompt_default).appendTo(this.container));for(var k in a.buttons){f=a.buttons[k];e?this.container.append(" "):e=!0;c=d('<button type="button" />').addClass(b.styles.btn+" "+f.addClass).text(f.text).appendTo(this.container).on("click",function(g){return function(){"function"==typeof g.click&&g.click(b,a.prompt?h.prompt.val():null)}}(f));a.prompt&&!a.prompt_multi_line&&
|
||||
f.promptTrigger&&this.prompt.keypress(function(b){return function(a){13==a.keyCode&&b.click()}}(c));b.styles.text&&c.wrapInner('<span class="'+b.styles.text+'"></span>');b.styles.btnhover&&c.hover(function(a){return function(){a.addClass(b.styles.btnhover)}}(c),function(a){return function(){a.removeClass(b.styles.btnhover)}}(c));if(b.styles.btnactive)c.on("mousedown",function(a){return function(){a.addClass(b.styles.btnactive)}}(c)).on("mouseup",function(a){return function(){a.removeClass(b.styles.btnactive)}}(c));
|
||||
if(b.styles.btnfocus)c.on("focus",function(a){return function(){a.addClass(b.styles.btnfocus)}}(c)).on("blur",function(a){return function(){a.removeClass(b.styles.btnfocus)}}(c))}}};d.extend(e.styling.jqueryui,{btn:"ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only",btnhover:"ui-state-hover",btnactive:"ui-state-active",btnfocus:"ui-state-focus",input:"",text:"ui-button-text"});d.extend(e.styling.bootstrap2,{btn:"btn",input:""});d.extend(e.styling.bootstrap3,{btn:"btn btn-default",
|
||||
input:"form-control"});d.extend(e.styling.fontawesome,{btn:"btn btn-default",input:"form-control"})});
|
||||
(function(e){"function"===typeof define&&define.amd?define("pnotify.desktop",["jquery","pnotify"],e):e(jQuery,PNotify)})(function(e,d){var c,f=function(a,b){f="Notification"in window?function(a,b){return new Notification(a,b)}:"mozNotification"in navigator?function(a,b){return navigator.mozNotification.createNotification(a,b.body,b.icon).show()}:"webkitNotifications"in window?function(a,b){return window.webkitNotifications.createNotification(b.icon,a,b.body)}:function(a,b){return null};return f(a,
|
||||
b)};d.prototype.options.desktop={desktop:!1,icon:null,tag:null};d.prototype.modules.desktop={tag:null,icon:null,genNotice:function(a,b){this.icon=null===b.icon?"http://sciactive.com/pnotify/includes/desktop/"+a.options.type+".png":!1===b.icon?null:b.icon;if(null===this.tag||null!==b.tag)this.tag=null===b.tag?"PNotify-"+Math.round(1E6*Math.random()):b.tag;a.desktop=f(a.options.title,{icon:this.icon,body:a.options.text,tag:this.tag});"close"in a.desktop||(a.desktop.close=function(){a.desktop.cancel()});
|
||||
a.desktop.onclick=function(){a.elem.trigger("click")};a.desktop.onclose=function(){"closing"!==a.state&&"closed"!==a.state&&a.remove()}},init:function(a,b){b.desktop&&(c=d.desktop.checkPermission(),0==c&&this.genNotice(a,b))},update:function(a,b,d){0==c&&b.desktop&&this.genNotice(a,b)},beforeOpen:function(a,b){0==c&&b.desktop&&a.elem.css({left:"-10000px",display:"none"})},afterOpen:function(a,b){0==c&&b.desktop&&(a.elem.css({left:"-10000px",display:"none"}),"show"in a.desktop&&a.desktop.show())},
|
||||
beforeClose:function(a,b){0==c&&b.desktop&&a.elem.css({left:"-10000px",display:"none"})},afterClose:function(a,b){0==c&&b.desktop&&(a.elem.css({left:"-10000px",display:"none"}),a.desktop.close())}};d.desktop={permission:function(){"undefined"!==typeof Notification&&"requestPermission"in Notification?Notification.requestPermission():"webkitNotifications"in window&&window.webkitNotifications.requestPermission()},checkPermission:function(){return"undefined"!==typeof Notification&&"permission"in Notification?
|
||||
"granted"==Notification.permission?0:1:"webkitNotifications"in window?window.webkitNotifications.checkPermission():1}};c=d.desktop.checkPermission()});
|
||||
(function(a){"function"===typeof define&&define.amd?define("pnotify.history",["jquery","pnotify"],a):a(jQuery,PNotify)})(function(a,b){var d,f;a(function(){a("body").on("pnotify.history-all",function(){a.each(b.notices,function(){this.modules.history.inHistory&&(this.elem.is(":visible")?this.options.hide&&this.queueRemove():this.open&&this.open())})}).on("pnotify.history-last",function(){var a="top"===b.prototype.options.stack.push,c=a?0:-1,e;do{e=-1===c?b.notices.slice(c):b.notices.slice(c,c+1);
|
||||
if(!e[0])return!1;c=a?c+1:c-1}while(!e[0].modules.history.inHistory||e[0].elem.is(":visible"));e[0].open&&e[0].open()})});b.prototype.options.history={history:!0,menu:!1,fixed:!0,maxonscreen:Infinity,labels:{redisplay:"Redisplay",all:"All",last:"Last"}};b.prototype.modules.history={inHistory:!1,init:function(b,c){b.options.destroy=!1;this.inHistory=c.history;if(c.menu&&"undefined"===typeof d){d=a("<div />",{"class":"ui-pnotify-history-container "+b.styles.hi_menu,mouseleave:function(){d.animate({top:"-"+
|
||||
f+"px"},{duration:100,queue:!1})}}).append(a("<div />",{"class":"ui-pnotify-history-header",text:c.labels.redisplay})).append(a("<button />",{"class":"ui-pnotify-history-all "+b.styles.hi_btn,text:c.labels.all,mouseenter:function(){a(this).addClass(b.styles.hi_btnhov)},mouseleave:function(){a(this).removeClass(b.styles.hi_btnhov)},click:function(){a(this).trigger("pnotify.history-all");return!1}})).append(a("<button />",{"class":"ui-pnotify-history-last "+b.styles.hi_btn,text:c.labels.last,mouseenter:function(){a(this).addClass(b.styles.hi_btnhov)},
|
||||
mouseleave:function(){a(this).removeClass(b.styles.hi_btnhov)},click:function(){a(this).trigger("pnotify.history-last");return!1}})).appendTo("body");var e=a("<span />",{"class":"ui-pnotify-history-pulldown "+b.styles.hi_hnd,mouseenter:function(){d.animate({top:"0"},{duration:100,queue:!1})}}).appendTo(d);console.log(e.offset());f=e.offset().top+2;d.css({top:"-"+f+"px"});c.fixed&&d.addClass("ui-pnotify-history-fixed")}},update:function(b,a){this.inHistory=a.history;a.fixed&&d?d.addClass("ui-pnotify-history-fixed"):
|
||||
d&&d.removeClass("ui-pnotify-history-fixed")},beforeOpen:function(d,c){if(b.notices&&b.notices.length>c.maxonscreen){var e;e="top"!==d.options.stack.push?b.notices.slice(0,b.notices.length-c.maxonscreen):b.notices.slice(c.maxonscreen,b.notices.length);a.each(e,function(){this.remove&&this.remove()})}}};a.extend(b.styling.jqueryui,{hi_menu:"ui-state-default ui-corner-bottom",hi_btn:"ui-state-default ui-corner-all",hi_btnhov:"ui-state-hover",hi_hnd:"ui-icon ui-icon-grip-dotted-horizontal"});a.extend(b.styling.bootstrap2,
|
||||
{hi_menu:"well",hi_btn:"btn",hi_btnhov:"",hi_hnd:"icon-chevron-down"});a.extend(b.styling.bootstrap3,{hi_menu:"well",hi_btn:"btn btn-default",hi_btnhov:"",hi_hnd:"glyphicon glyphicon-chevron-down"});a.extend(b.styling.fontawesome,{hi_menu:"well",hi_btn:"btn btn-default",hi_btnhov:"",hi_hnd:"fa fa-chevron-down"})});
|
||||
@@ -0,0 +1,7 @@
|
||||
(function(c){"object"===typeof exports&&"undefined"!==typeof module?module.exports=c(require("jquery"),require("pnotify")):"function"===typeof define&&define.amd?define("pnotify.buttons",["jquery","pnotify"],c):c(jQuery,PNotify)})(function(c,e){e.prototype.options.buttons={closer:!0,closer_hover:!0,sticker:!0,sticker_hover:!0,show_on_nonblock:!1,labels:{close:"Close",stick:"Stick"}};e.prototype.modules.buttons={myOptions:null,closer:null,sticker:null,init:function(a,b){var d=this;this.myOptions=b;
|
||||
a.elem.on({mouseenter:function(b){!d.myOptions.sticker||a.options.nonblock&&a.options.nonblock.nonblock&&!d.myOptions.show_on_nonblock||d.sticker.trigger("pnotify_icon").css("visibility","visible");!d.myOptions.closer||a.options.nonblock&&a.options.nonblock.nonblock&&!d.myOptions.show_on_nonblock||d.closer.css("visibility","visible")},mouseleave:function(a){d.myOptions.sticker_hover&&d.sticker.css("visibility","hidden");d.myOptions.closer_hover&&d.closer.css("visibility","hidden")}});this.sticker=
|
||||
c("<div />",{"class":"ui-pnotify-sticker",css:{cursor:"pointer",visibility:b.sticker_hover?"hidden":"visible"},click:function(){a.options.hide=!a.options.hide;a.options.hide?a.queueRemove():a.cancelRemove();c(this).trigger("pnotify_icon")}}).bind("pnotify_icon",function(){c(this).children().removeClass(a.styles.pin_up+" "+a.styles.pin_down).addClass(a.options.hide?a.styles.pin_up:a.styles.pin_down)}).append(c("<span />",{"class":a.styles.pin_up,title:b.labels.stick})).prependTo(a.container);(!b.sticker||
|
||||
a.options.nonblock&&a.options.nonblock.nonblock&&!b.show_on_nonblock)&&this.sticker.css("display","none");this.closer=c("<div />",{"class":"ui-pnotify-closer",css:{cursor:"pointer",visibility:b.closer_hover?"hidden":"visible"},click:function(){a.remove(!1);d.sticker.css("visibility","hidden");d.closer.css("visibility","hidden")}}).append(c("<span />",{"class":a.styles.closer,title:b.labels.close})).prependTo(a.container);(!b.closer||a.options.nonblock&&a.options.nonblock.nonblock&&!b.show_on_nonblock)&&
|
||||
this.closer.css("display","none")},update:function(a,b){this.myOptions=b;!b.closer||a.options.nonblock&&a.options.nonblock.nonblock&&!b.show_on_nonblock?this.closer.css("display","none"):b.closer&&this.closer.css("display","block");!b.sticker||a.options.nonblock&&a.options.nonblock.nonblock&&!b.show_on_nonblock?this.sticker.css("display","none"):b.sticker&&this.sticker.css("display","block");this.sticker.trigger("pnotify_icon");b.sticker_hover?this.sticker.css("visibility","hidden"):a.options.nonblock&&
|
||||
a.options.nonblock.nonblock&&!b.show_on_nonblock||this.sticker.css("visibility","visible");b.closer_hover?this.closer.css("visibility","hidden"):a.options.nonblock&&a.options.nonblock.nonblock&&!b.show_on_nonblock||this.closer.css("visibility","visible")}};c.extend(e.styling.brighttheme,{closer:"brighttheme-icon-closer",pin_up:"brighttheme-icon-sticker",pin_down:"brighttheme-icon-sticker brighttheme-icon-stuck"});c.extend(e.styling.jqueryui,{closer:"ui-icon ui-icon-close",pin_up:"ui-icon ui-icon-pin-w",
|
||||
pin_down:"ui-icon ui-icon-pin-s"});c.extend(e.styling.bootstrap2,{closer:"icon-remove",pin_up:"icon-pause",pin_down:"icon-play"});c.extend(e.styling.bootstrap3,{closer:"glyphicon glyphicon-remove",pin_up:"glyphicon glyphicon-pause",pin_down:"glyphicon glyphicon-play"});c.extend(e.styling.fontawesome,{closer:"fa fa-times",pin_up:"fa fa-pause",pin_down:"fa fa-play"})});
|
||||
@@ -0,0 +1,2 @@
|
||||
(function(b){"object"===typeof exports&&"undefined"!==typeof module?module.exports=b(require("jquery"),require("pnotify")):"function"===typeof define&&define.amd?define("pnotify.callbacks",["jquery","pnotify"],b):b(jQuery,PNotify)})(function(b,a){var c=a.prototype.init,d=a.prototype.open,e=a.prototype.remove;a.prototype.init=function(){this.options.before_init&&this.options.before_init(this.options);c.apply(this,arguments);this.options.after_init&&this.options.after_init(this)};a.prototype.open=function(){var a;
|
||||
this.options.before_open&&(a=this.options.before_open(this));!1!==a&&(d.apply(this,arguments),this.options.after_open&&this.options.after_open(this))};a.prototype.remove=function(a){var b;this.options.before_close&&(b=this.options.before_close(this,a));!1!==b&&(e.apply(this,arguments),this.options.after_close&&this.options.after_close(this,a))}});
|
||||
@@ -0,0 +1,6 @@
|
||||
(function(d){"object"===typeof exports&&"undefined"!==typeof module?module.exports=d(require("jquery"),require("pnotify")):"function"===typeof define&&define.amd?define("pnotify.confirm",["jquery","pnotify"],d):d(jQuery,PNotify)})(function(d,e){e.prototype.options.confirm={confirm:!1,prompt:!1,prompt_class:"",prompt_default:"",prompt_multi_line:!1,align:"right",buttons:[{text:"Ok",addClass:"",promptTrigger:!0,click:function(b,a){b.remove();b.get().trigger("pnotify.confirm",[b,a])}},{text:"Cancel",
|
||||
addClass:"",click:function(b){b.remove();b.get().trigger("pnotify.cancel",b)}}]};e.prototype.modules.confirm={container:null,prompt:null,init:function(b,a){this.container=d('<div style="margin-top:5px;clear:both;" />').css("text-align",a.align).appendTo(b.container);a.confirm||a.prompt?this.makeDialog(b,a):this.container.hide()},update:function(b,a){a.confirm?(this.makeDialog(b,a),this.container.show()):this.container.hide().empty()},afterOpen:function(b,a){a.prompt&&this.prompt.focus()},makeDialog:function(b,
|
||||
a){var e=!1,h=this,f,c;this.container.empty();a.prompt&&(this.prompt=d("<"+(a.prompt_multi_line?'textarea rows="5"':'input type="text"')+' style="margin-bottom:5px;clear:both;" />').addClass(b.styles.input+" "+a.prompt_class).val(a.prompt_default).appendTo(this.container));for(var k in a.buttons){f=a.buttons[k];e?this.container.append(" "):e=!0;c=d('<button type="button" />').addClass(b.styles.btn+" "+f.addClass).text(f.text).appendTo(this.container).on("click",function(g){return function(){"function"==
|
||||
typeof g.click&&g.click(b,a.prompt?h.prompt.val():null)}}(f));a.prompt&&!a.prompt_multi_line&&f.promptTrigger&&this.prompt.keypress(function(b){return function(a){13==a.keyCode&&b.click()}}(c));b.styles.text&&c.wrapInner('<span class="'+b.styles.text+'"></span>');b.styles.btnhover&&c.hover(function(a){return function(){a.addClass(b.styles.btnhover)}}(c),function(a){return function(){a.removeClass(b.styles.btnhover)}}(c));if(b.styles.btnactive)c.on("mousedown",function(a){return function(){a.addClass(b.styles.btnactive)}}(c)).on("mouseup",
|
||||
function(a){return function(){a.removeClass(b.styles.btnactive)}}(c));if(b.styles.btnfocus)c.on("focus",function(a){return function(){a.addClass(b.styles.btnfocus)}}(c)).on("blur",function(a){return function(){a.removeClass(b.styles.btnfocus)}}(c))}}};d.extend(e.styling.jqueryui,{btn:"ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only",btnhover:"ui-state-hover",btnactive:"ui-state-active",btnfocus:"ui-state-focus",input:"",text:"ui-button-text"});d.extend(e.styling.bootstrap2,
|
||||
{btn:"btn",input:""});d.extend(e.styling.bootstrap3,{btn:"btn btn-default",input:"form-control"});d.extend(e.styling.fontawesome,{btn:"btn btn-default",input:"form-control"})});
|
||||
@@ -0,0 +1,33 @@
|
||||
/*
|
||||
PNotify 2.1.0 sciactive.com/pnotify/
|
||||
(C) 2015 Hunter Perrin
|
||||
license GPL/LGPL/MPL
|
||||
*/
|
||||
(function(c){"object"===typeof exports&&"undefined"!==typeof module?module.exports=c(require("jquery")):"function"===typeof define&&define.amd?define("pnotify",["jquery"],c):c(jQuery)})(function(c){var q={dir1:"down",dir2:"left",push:"bottom",spacing1:25,spacing2:25,context:c("body")},e,f,h=c(window),p=function(){f=c("body");PNotify.prototype.options.stack.context=f;h=c(window);h.bind("resize",function(){e&&clearTimeout(e);e=setTimeout(function(){PNotify.positionAll(!0)},10)})};PNotify=function(b){this.parseOptions(b);
|
||||
this.init()};c.extend(PNotify.prototype,{version:"2.1.0",options:{title:!1,title_escape:!1,text:!1,text_escape:!1,styling:"brighttheme",addclass:"",cornerclass:"",auto_display:!0,width:"300px",min_height:"16px",type:"notice",icon:!0,opacity:1,animation:"fade",animate_speed:"slow",position_animate_speed:500,shadow:!0,hide:!0,delay:8E3,mouse_reset:!0,remove:!0,insert_brs:!0,destroy:!0,stack:q},modules:{},runModules:function(b,a){var m,c;for(c in this.modules)if(m="object"===typeof a&&c in a?a[c]:a,
|
||||
"function"===typeof this.modules[c][b])this.modules[c][b](this,"object"===typeof this.options[c]?this.options[c]:{},m)},state:"initializing",timer:null,styles:null,elem:null,container:null,title_container:null,text_container:null,animating:!1,timerHide:!1,init:function(){var b=this;this.modules={};c.extend(!0,this.modules,PNotify.prototype.modules);this.styles="object"===typeof this.options.styling?this.options.styling:PNotify.styling[this.options.styling];this.elem=c("<div />",{"class":"ui-pnotify "+
|
||||
this.options.addclass,css:{display:"none"},"aria-live":"assertive",mouseenter:function(a){if(b.options.mouse_reset&&"out"===b.animating){if(!b.timerHide)return;b.cancelRemove()}b.options.hide&&b.options.mouse_reset&&b.cancelRemove()},mouseleave:function(a){b.options.hide&&b.options.mouse_reset&&"out"!==b.animating&&b.queueRemove();PNotify.positionAll()}});this.container=c("<div />",{"class":this.styles.container+" ui-pnotify-container "+("error"===this.options.type?this.styles.error:"info"===this.options.type?
|
||||
this.styles.info:"success"===this.options.type?this.styles.success:this.styles.notice),role:"alert"}).appendTo(this.elem);""!==this.options.cornerclass&&this.container.removeClass("ui-corner-all").addClass(this.options.cornerclass);this.options.shadow&&this.container.addClass("ui-pnotify-shadow");!1!==this.options.icon&&c("<div />",{"class":"ui-pnotify-icon"}).append(c("<span />",{"class":!0===this.options.icon?"error"===this.options.type?this.styles.error_icon:"info"===this.options.type?this.styles.info_icon:
|
||||
"success"===this.options.type?this.styles.success_icon:this.styles.notice_icon:this.options.icon})).prependTo(this.container);this.title_container=c("<h4 />",{"class":"ui-pnotify-title"}).appendTo(this.container);!1===this.options.title?this.title_container.hide():this.options.title_escape?this.title_container.text(this.options.title):this.title_container.html(this.options.title);this.text_container=c("<div />",{"class":"ui-pnotify-text"}).appendTo(this.container);!1===this.options.text?this.text_container.hide():
|
||||
this.options.text_escape?this.text_container.text(this.options.text):this.text_container.html(this.options.insert_brs?String(this.options.text).replace(/\n/g,"<br />"):this.options.text);"string"===typeof this.options.width&&this.elem.css("width",this.options.width);"string"===typeof this.options.min_height&&this.container.css("min-height",this.options.min_height);PNotify.notices="top"===this.options.stack.push?c.merge([this],PNotify.notices):c.merge(PNotify.notices,[this]);"top"===this.options.stack.push&&
|
||||
this.queuePosition(!1,1);this.options.stack.animation=!1;this.runModules("init");this.options.auto_display&&this.open();return this},update:function(b){var a=this.options;this.parseOptions(a,b);this.options.cornerclass!==a.cornerclass&&this.container.removeClass("ui-corner-all "+a.cornerclass).addClass(this.options.cornerclass);this.options.shadow!==a.shadow&&(this.options.shadow?this.container.addClass("ui-pnotify-shadow"):this.container.removeClass("ui-pnotify-shadow"));!1===this.options.addclass?
|
||||
this.elem.removeClass(a.addclass):this.options.addclass!==a.addclass&&this.elem.removeClass(a.addclass).addClass(this.options.addclass);!1===this.options.title?this.title_container.slideUp("fast"):this.options.title!==a.title&&(this.options.title_escape?this.title_container.text(this.options.title):this.title_container.html(this.options.title),!1===a.title&&this.title_container.slideDown(200));!1===this.options.text?this.text_container.slideUp("fast"):this.options.text!==a.text&&(this.options.text_escape?
|
||||
this.text_container.text(this.options.text):this.text_container.html(this.options.insert_brs?String(this.options.text).replace(/\n/g,"<br />"):this.options.text),!1===a.text&&this.text_container.slideDown(200));this.options.type!==a.type&&this.container.removeClass(this.styles.error+" "+this.styles.notice+" "+this.styles.success+" "+this.styles.info).addClass("error"===this.options.type?this.styles.error:"info"===this.options.type?this.styles.info:"success"===this.options.type?this.styles.success:
|
||||
this.styles.notice);if(this.options.icon!==a.icon||!0===this.options.icon&&this.options.type!==a.type)this.container.find("div.ui-pnotify-icon").remove(),!1!==this.options.icon&&c("<div />",{"class":"ui-pnotify-icon"}).append(c("<span />",{"class":!0===this.options.icon?"error"===this.options.type?this.styles.error_icon:"info"===this.options.type?this.styles.info_icon:"success"===this.options.type?this.styles.success_icon:this.styles.notice_icon:this.options.icon})).prependTo(this.container);this.options.width!==
|
||||
a.width&&this.elem.animate({width:this.options.width});this.options.min_height!==a.min_height&&this.container.animate({minHeight:this.options.min_height});this.options.opacity!==a.opacity&&this.elem.fadeTo(this.options.animate_speed,this.options.opacity);this.options.hide?a.hide||this.queueRemove():this.cancelRemove();this.queuePosition(!0);this.runModules("update",a);return this},open:function(){this.state="opening";this.runModules("beforeOpen");var b=this;this.elem.parent().length||this.elem.appendTo(this.options.stack.context?
|
||||
this.options.stack.context:f);"top"!==this.options.stack.push&&this.position(!0);"fade"===this.options.animation||"fade"===this.options.animation.effect_in?this.elem.show().fadeTo(0,0).hide():1!==this.options.opacity&&this.elem.show().fadeTo(0,this.options.opacity).hide();this.animateIn(function(){b.queuePosition(!0);b.options.hide&&b.queueRemove();b.state="open";b.runModules("afterOpen")});return this},remove:function(b){this.state="closing";this.timerHide=!!b;this.runModules("beforeClose");var a=
|
||||
this;this.timer&&(window.clearTimeout(this.timer),this.timer=null);this.animateOut(function(){a.state="closed";a.runModules("afterClose");a.queuePosition(!0);a.options.remove&&a.elem.detach();a.runModules("beforeDestroy");if(a.options.destroy&&null!==PNotify.notices){var b=c.inArray(a,PNotify.notices);-1!==b&&PNotify.notices.splice(b,1)}a.runModules("afterDestroy")});return this},get:function(){return this.elem},parseOptions:function(b,a){this.options=c.extend(!0,{},PNotify.prototype.options);this.options.stack=
|
||||
PNotify.prototype.options.stack;for(var m=[b,a],g,e=0;e<m.length;e++){g=m[e];if("undefined"==typeof g)break;if("object"!==typeof g)this.options.text=g;else for(var d in g)this.modules[d]?c.extend(!0,this.options[d],g[d]):this.options[d]=g[d]}},animateIn:function(b){this.animating="in";var a;a="undefined"!==typeof this.options.animation.effect_in?this.options.animation.effect_in:this.options.animation;"none"===a?(this.elem.show(),b()):"show"===a?this.elem.show(this.options.animate_speed,b):"fade"===
|
||||
a?this.elem.show().fadeTo(this.options.animate_speed,this.options.opacity,b):"slide"===a?this.elem.slideDown(this.options.animate_speed,b):"function"===typeof a?a("in",b,this.elem):this.elem.show(a,"object"===typeof this.options.animation.options_in?this.options.animation.options_in:{},this.options.animate_speed,b);this.elem.parent().hasClass("ui-effects-wrapper")&&this.elem.parent().css({position:"fixed",overflow:"visible"});"slide"!==a&&this.elem.css("overflow","visible");this.container.css("overflow",
|
||||
"hidden")},animateOut:function(b){this.animating="out";var a;a="undefined"!==typeof this.options.animation.effect_out?this.options.animation.effect_out:this.options.animation;"none"===a?(this.elem.hide(),b()):"show"===a?this.elem.hide(this.options.animate_speed,b):"fade"===a?this.elem.fadeOut(this.options.animate_speed,b):"slide"===a?this.elem.slideUp(this.options.animate_speed,b):"function"===typeof a?a("out",b,this.elem):this.elem.hide(a,"object"===typeof this.options.animation.options_out?this.options.animation.options_out:
|
||||
{},this.options.animate_speed,b);this.elem.parent().hasClass("ui-effects-wrapper")&&this.elem.parent().css({position:"fixed",overflow:"visible"});"slide"!==a&&this.elem.css("overflow","visible");this.container.css("overflow","hidden")},position:function(b){var a=this.options.stack,c=this.elem;c.parent().hasClass("ui-effects-wrapper")&&(c=this.elem.css({left:"0",top:"0",right:"0",bottom:"0"}).parent());"undefined"===typeof a.context&&(a.context=f);if(a){"number"!==typeof a.nextpos1&&(a.nextpos1=a.firstpos1);
|
||||
"number"!==typeof a.nextpos2&&(a.nextpos2=a.firstpos2);"number"!==typeof a.addpos2&&(a.addpos2=0);var e="none"===c.css("display");if(!e||b){var n,d={},k;switch(a.dir1){case "down":k="top";break;case "up":k="bottom";break;case "left":k="right";break;case "right":k="left"}b=parseInt(c.css(k).replace(/(?:\..*|[^0-9.])/g,""));isNaN(b)&&(b=0);"undefined"!==typeof a.firstpos1||e||(a.firstpos1=b,a.nextpos1=a.firstpos1);var l;switch(a.dir2){case "down":l="top";break;case "up":l="bottom";break;case "left":l=
|
||||
"right";break;case "right":l="left"}n=parseInt(c.css(l).replace(/(?:\..*|[^0-9.])/g,""));isNaN(n)&&(n=0);"undefined"!==typeof a.firstpos2||e||(a.firstpos2=n,a.nextpos2=a.firstpos2);if("down"===a.dir1&&a.nextpos1+c.height()>(a.context.is(f)?h.height():a.context.prop("scrollHeight"))||"up"===a.dir1&&a.nextpos1+c.height()>(a.context.is(f)?h.height():a.context.prop("scrollHeight"))||"left"===a.dir1&&a.nextpos1+c.width()>(a.context.is(f)?h.width():a.context.prop("scrollWidth"))||"right"===a.dir1&&a.nextpos1+
|
||||
c.width()>(a.context.is(f)?h.width():a.context.prop("scrollWidth")))a.nextpos1=a.firstpos1,a.nextpos2+=a.addpos2+("undefined"===typeof a.spacing2?25:a.spacing2),a.addpos2=0;if(a.animation&&a.nextpos2<n)switch(a.dir2){case "down":d.top=a.nextpos2+"px";break;case "up":d.bottom=a.nextpos2+"px";break;case "left":d.right=a.nextpos2+"px";break;case "right":d.left=a.nextpos2+"px"}else"number"===typeof a.nextpos2&&c.css(l,a.nextpos2+"px");switch(a.dir2){case "down":case "up":c.outerHeight(!0)>a.addpos2&&
|
||||
(a.addpos2=c.height());break;case "left":case "right":c.outerWidth(!0)>a.addpos2&&(a.addpos2=c.width())}if("number"===typeof a.nextpos1)if(a.animation&&(b>a.nextpos1||d.top||d.bottom||d.right||d.left))switch(a.dir1){case "down":d.top=a.nextpos1+"px";break;case "up":d.bottom=a.nextpos1+"px";break;case "left":d.right=a.nextpos1+"px";break;case "right":d.left=a.nextpos1+"px"}else c.css(k,a.nextpos1+"px");(d.top||d.bottom||d.right||d.left)&&c.animate(d,{duration:this.options.position_animate_speed,queue:!1});
|
||||
switch(a.dir1){case "down":case "up":a.nextpos1+=c.height()+("undefined"===typeof a.spacing1?25:a.spacing1);break;case "left":case "right":a.nextpos1+=c.width()+("undefined"===typeof a.spacing1?25:a.spacing1)}}return this}},queuePosition:function(b,a){e&&clearTimeout(e);a||(a=10);e=setTimeout(function(){PNotify.positionAll(b)},a);return this},cancelRemove:function(){this.timer&&window.clearTimeout(this.timer);"closing"===this.state&&(this.elem.stop(!0),this.state="open",this.animating="in",this.elem.css("height",
|
||||
"auto").animate({width:this.options.width,opacity:this.options.opacity},"fast"));return this},queueRemove:function(){var b=this;this.cancelRemove();this.timer=window.setTimeout(function(){b.remove(!0)},isNaN(this.options.delay)?0:this.options.delay);return this}});c.extend(PNotify,{notices:[],removeAll:function(){c.each(PNotify.notices,function(){this.remove&&this.remove(!1)})},positionAll:function(b){e&&clearTimeout(e);e=null;if(PNotify.notices&&PNotify.notices.length)c.each(PNotify.notices,function(){var a=
|
||||
this.options.stack;a&&(a.nextpos1=a.firstpos1,a.nextpos2=a.firstpos2,a.addpos2=0,a.animation=b)}),c.each(PNotify.notices,function(){this.position()});else{var a=PNotify.prototype.options.stack;a&&(delete a.nextpos1,delete a.nextpos2)}},styling:{brighttheme:{container:"brighttheme",notice:"brighttheme-notice",notice_icon:"brighttheme-icon-notice",info:"brighttheme-info",info_icon:"brighttheme-icon-info",success:"brighttheme-success",success_icon:"brighttheme-icon-success",error:"brighttheme-error",
|
||||
error_icon:"brighttheme-icon-error"},jqueryui:{container:"ui-widget ui-widget-content ui-corner-all",notice:"ui-state-highlight",notice_icon:"ui-icon ui-icon-info",info:"",info_icon:"ui-icon ui-icon-info",success:"ui-state-default",success_icon:"ui-icon ui-icon-circle-check",error:"ui-state-error",error_icon:"ui-icon ui-icon-alert"},bootstrap2:{container:"alert",notice:"",notice_icon:"icon-exclamation-sign",info:"alert-info",info_icon:"icon-info-sign",success:"alert-success",success_icon:"icon-ok-sign",
|
||||
error:"alert-error",error_icon:"icon-warning-sign"},bootstrap3:{container:"alert",notice:"alert-warning",notice_icon:"glyphicon glyphicon-exclamation-sign",info:"alert-info",info_icon:"glyphicon glyphicon-info-sign",success:"alert-success",success_icon:"glyphicon glyphicon-ok-sign",error:"alert-danger",error_icon:"glyphicon glyphicon-warning-sign"}}});PNotify.styling.fontawesome=c.extend({},PNotify.styling.bootstrap3);c.extend(PNotify.styling.fontawesome,{notice_icon:"fa fa-exclamation-circle",info_icon:"fa fa-info",
|
||||
success_icon:"fa fa-check",error_icon:"fa fa-warning"});document.body?p():c(p);return PNotify});
|
||||
@@ -0,0 +1,5 @@
|
||||
(function(e){"object"===typeof exports&&"undefined"!==typeof module?module.exports=e(require("jquery"),require("pnotify")):"function"===typeof define&&define.amd?define("pnotify.desktop",["jquery","pnotify"],e):e(jQuery,PNotify)})(function(e,d){var c,f=function(a,b){f="Notification"in window?function(a,b){return new Notification(a,b)}:"mozNotification"in navigator?function(a,b){return navigator.mozNotification.createNotification(a,b.body,b.icon).show()}:"webkitNotifications"in window?function(a,b){return window.webkitNotifications.createNotification(b.icon,
|
||||
a,b.body)}:function(a,b){return null};return f(a,b)};d.prototype.options.desktop={desktop:!1,fallback:!0,icon:null,tag:null};d.prototype.modules.desktop={tag:null,icon:null,genNotice:function(a,b){this.icon=null===b.icon?"http://sciactive.com/pnotify/includes/desktop/"+a.options.type+".png":!1===b.icon?null:b.icon;if(null===this.tag||null!==b.tag)this.tag=null===b.tag?"PNotify-"+Math.round(1E6*Math.random()):b.tag;a.desktop=f(a.options.title,{icon:this.icon,body:a.options.text,tag:this.tag});!("close"in
|
||||
a.desktop)&&"cancel"in a.desktop&&(a.desktop.close=function(){a.desktop.cancel()});a.desktop.onclick=function(){a.elem.trigger("click")};a.desktop.onclose=function(){"closing"!==a.state&&"closed"!==a.state&&a.remove()}},init:function(a,b){b.desktop&&(c=d.desktop.checkPermission(),0!==c?b.fallback||(a.options.auto_display=!1):this.genNotice(a,b))},update:function(a,b,d){0!==c&&b.fallback||!b.desktop||this.genNotice(a,b)},beforeOpen:function(a,b){0!==c&&b.fallback||!b.desktop||a.elem.css({left:"-10000px",
|
||||
display:"none"})},afterOpen:function(a,b){0!==c&&b.fallback||!b.desktop||(a.elem.css({left:"-10000px",display:"none"}),"show"in a.desktop&&a.desktop.show())},beforeClose:function(a,b){0!==c&&b.fallback||!b.desktop||a.elem.css({left:"-10000px",display:"none"})},afterClose:function(a,b){0!==c&&b.fallback||!b.desktop||(a.elem.css({left:"-10000px",display:"none"}),"close"in a.desktop&&a.desktop.close())}};d.desktop={permission:function(){"undefined"!==typeof Notification&&"requestPermission"in Notification?
|
||||
Notification.requestPermission():"webkitNotifications"in window&&window.webkitNotifications.requestPermission()},checkPermission:function(){return"undefined"!==typeof Notification&&"permission"in Notification?"granted"===Notification.permission?0:1:"webkitNotifications"in window?0==window.webkitNotifications.checkPermission()?0:1:1}};c=d.desktop.checkPermission()});
|
||||
@@ -0,0 +1,6 @@
|
||||
(function(b){"object"===typeof exports&&"undefined"!==typeof module?module.exports=b(require("jquery"),require("pnotify")):"function"===typeof define&&define.amd?define("pnotify.history",["jquery","pnotify"],b):b(jQuery,PNotify)})(function(b,a){var c,e;b(function(){b("body").on("pnotify.history-all",function(){b.each(a.notices,function(){this.modules.history.inHistory&&(this.elem.is(":visible")?this.options.hide&&this.queueRemove():this.open&&this.open())})}).on("pnotify.history-last",function(){var b=
|
||||
"top"===a.prototype.options.stack.push,d=b?0:-1,c;do{c=-1===d?a.notices.slice(d):a.notices.slice(d,d+1);if(!c[0])return!1;d=b?d+1:d-1}while(!c[0].modules.history.inHistory||c[0].elem.is(":visible"));c[0].open&&c[0].open()})});a.prototype.options.history={history:!0,menu:!1,fixed:!0,maxonscreen:Infinity,labels:{redisplay:"Redisplay",all:"All",last:"Last"}};a.prototype.modules.history={inHistory:!1,init:function(a,d){a.options.destroy=!1;this.inHistory=d.history;d.menu&&"undefined"===typeof c&&(c=b("<div />",
|
||||
{"class":"ui-pnotify-history-container "+a.styles.hi_menu,mouseleave:function(){c.animate({top:"-"+e+"px"},{duration:100,queue:!1})}}).append(b("<div />",{"class":"ui-pnotify-history-header",text:d.labels.redisplay})).append(b("<button />",{"class":"ui-pnotify-history-all "+a.styles.hi_btn,text:d.labels.all,mouseenter:function(){b(this).addClass(a.styles.hi_btnhov)},mouseleave:function(){b(this).removeClass(a.styles.hi_btnhov)},click:function(){b(this).trigger("pnotify.history-all");return!1}})).append(b("<button />",
|
||||
{"class":"ui-pnotify-history-last "+a.styles.hi_btn,text:d.labels.last,mouseenter:function(){b(this).addClass(a.styles.hi_btnhov)},mouseleave:function(){b(this).removeClass(a.styles.hi_btnhov)},click:function(){b(this).trigger("pnotify.history-last");return!1}})).appendTo("body"),e=b("<span />",{"class":"ui-pnotify-history-pulldown "+a.styles.hi_hnd,mouseenter:function(){c.animate({top:"0"},{duration:100,queue:!1})}}).appendTo(c).offset().top+2,c.css({top:"-"+e+"px"}),d.fixed&&c.addClass("ui-pnotify-history-fixed"))},
|
||||
update:function(b,a){this.inHistory=a.history;a.fixed&&c?c.addClass("ui-pnotify-history-fixed"):c&&c.removeClass("ui-pnotify-history-fixed")},beforeOpen:function(c,d){if(a.notices&&a.notices.length>d.maxonscreen){var e;e="top"!==c.options.stack.push?a.notices.slice(0,a.notices.length-d.maxonscreen):a.notices.slice(d.maxonscreen,a.notices.length);b.each(e,function(){this.remove&&this.remove()})}}};b.extend(a.styling.jqueryui,{hi_menu:"ui-state-default ui-corner-bottom",hi_btn:"ui-state-default ui-corner-all",
|
||||
hi_btnhov:"ui-state-hover",hi_hnd:"ui-icon ui-icon-grip-dotted-horizontal"});b.extend(a.styling.bootstrap2,{hi_menu:"well",hi_btn:"btn",hi_btnhov:"",hi_hnd:"icon-chevron-down"});b.extend(a.styling.bootstrap3,{hi_menu:"well",hi_btn:"btn btn-default",hi_btnhov:"",hi_hnd:"glyphicon glyphicon-chevron-down"});b.extend(a.styling.fontawesome,{hi_menu:"well",hi_btn:"btn btn-default",hi_btnhov:"",hi_hnd:"fa fa-chevron-down"})});
|
||||
@@ -0,0 +1 @@
|
||||
(function(a){"object"===typeof exports&&"undefined"!==typeof module?module.exports=a(require("jquery"),require("pnotify")):"function"===typeof define&&define.amd?define("pnotify.mobile",["jquery","pnotify"],a):a(jQuery,PNotify)})(function(a,b){});
|
||||
@@ -0,0 +1,6 @@
|
||||
(function(f){"object"===typeof exports&&"undefined"!==typeof module?module.exports=f(require("jquery"),require("pnotify")):"function"===typeof define&&define.amd?define("pnotify.nonblock",["jquery","pnotify"],f):f(jQuery,PNotify)})(function(f,l){var m=/^on/,n=/^(dbl)?click$|^mouse(move|down|up|over|out|enter|leave)$|^contextmenu$/,p=/^(focus|blur|select|change|reset)$|^key(press|down|up)$/,q=/^(scroll|resize|(un)?load|abort|error)$/,h=function(b,a){var c;b=b.toLowerCase();document.createEvent&&this.dispatchEvent?
|
||||
(b=b.replace(m,""),b.match(n)?(f(this).offset(),c=document.createEvent("MouseEvents"),c.initMouseEvent(b,a.bubbles,a.cancelable,a.view,a.detail,a.screenX,a.screenY,a.clientX,a.clientY,a.ctrlKey,a.altKey,a.shiftKey,a.metaKey,a.button,a.relatedTarget)):b.match(p)?(c=document.createEvent("UIEvents"),c.initUIEvent(b,a.bubbles,a.cancelable,a.view,a.detail)):b.match(q)&&(c=document.createEvent("HTMLEvents"),c.initEvent(b,a.bubbles,a.cancelable)),c&&this.dispatchEvent(c)):(b.match(m)||(b="on"+b),c=document.createEventObject(a),
|
||||
this.fireEvent(b,c))},e,d=function(b,a,c){b.elem.css("display","none");var g=document.elementFromPoint(a.clientX,a.clientY);b.elem.css("display","block");var d=f(g),k=d.css("cursor");"auto"===k&&"A"===g.tagName&&(k="pointer");b.elem.css("cursor","auto"!==k?k:"default");e&&e.get(0)==g||(e&&(h.call(e.get(0),"mouseleave",a.originalEvent),h.call(e.get(0),"mouseout",a.originalEvent)),h.call(g,"mouseenter",a.originalEvent),h.call(g,"mouseover",a.originalEvent));h.call(g,c,a.originalEvent);e=d};l.prototype.options.nonblock=
|
||||
{nonblock:!1,nonblock_opacity:0.2};l.prototype.modules.nonblock={myOptions:null,init:function(b,a){var c=this;this.myOptions=a;b.elem.on({mouseenter:function(a){c.myOptions.nonblock&&a.stopPropagation();c.myOptions.nonblock&&b.elem.stop().animate({opacity:c.myOptions.nonblock_opacity},"fast")},mouseleave:function(a){c.myOptions.nonblock&&a.stopPropagation();e=null;b.elem.css("cursor","auto");c.myOptions.nonblock&&"out"!==b.animating&&b.elem.stop().animate({opacity:b.options.opacity},"fast")},mouseover:function(a){c.myOptions.nonblock&&
|
||||
a.stopPropagation()},mouseout:function(a){c.myOptions.nonblock&&a.stopPropagation()},mousemove:function(a){c.myOptions.nonblock&&(a.stopPropagation(),d(b,a,"onmousemove"))},mousedown:function(a){c.myOptions.nonblock&&(a.stopPropagation(),a.preventDefault(),d(b,a,"onmousedown"))},mouseup:function(a){c.myOptions.nonblock&&(a.stopPropagation(),a.preventDefault(),d(b,a,"onmouseup"))},click:function(a){c.myOptions.nonblock&&(a.stopPropagation(),d(b,a,"onclick"))},dblclick:function(a){c.myOptions.nonblock&&
|
||||
(a.stopPropagation(),d(b,a,"ondblclick"))}})},update:function(b,a){this.myOptions=a}}});
|
||||
@@ -0,0 +1,4 @@
|
||||
(function(c){"object"===typeof exports&&"undefined"!==typeof module?module.exports=c(require("jquery"),require("pnotify")):"function"===typeof define&&define.amd?define("pnotify.reference",["jquery","pnotify"],c):c(jQuery,PNotify)})(function(c,d){d.prototype.options.reference={putThing:!1,labels:{text:"Spin Around"}};d.prototype.modules.reference={thingElem:null,init:function(b,a){var d=this;a.putThing&&(this.thingElem=c('<button style="float:right;" class="btn btn-default" type="button" disabled><i class="'+
|
||||
b.styles.athing+'" /> '+a.labels.text+"</button>").appendTo(b.container),b.container.append('<div style="clear: right; line-height: 0;" />'),b.elem.on({mouseenter:function(b){d.thingElem.prop("disabled",!1)},mouseleave:function(b){d.thingElem.prop("disabled",!0)}}),this.thingElem.on("click",function(){var a=0,c=setInterval(function(){a+=10;360==a&&(a=0,clearInterval(c));b.elem.css({"-moz-transform":"rotate("+a+"deg)","-webkit-transform":"rotate("+a+"deg)","-o-transform":"rotate("+a+"deg)","-ms-transform":"rotate("+
|
||||
a+"deg)",filter:"progid:DXImageTransform.Microsoft.BasicImage(rotation="+a/360*4+")"})},20)}))},update:function(b,a,c){a.putThing&&this.thingElem?this.thingElem.show():!a.putThing&&this.thingElem&&this.thingElem.hide();this.thingElem&&this.thingElem.find("i").attr("class",b.styles.athing)},beforeOpen:function(b,a){},afterOpen:function(b,a){},beforeClose:function(b,a){},afterClose:function(b,a){},beforeDestroy:function(b,a){},afterDestroy:function(b,a){}};c.extend(d.styling.jqueryui,{athing:"ui-icon ui-icon-refresh"});
|
||||
c.extend(d.styling.bootstrap2,{athing:"icon-refresh"});c.extend(d.styling.bootstrap3,{athing:"glyphicon glyphicon-refresh"});c.extend(d.styling.fontawesome,{athing:"fa fa-refresh"})});
|
||||
@@ -0,0 +1 @@
|
||||
(function(a){"object"===typeof exports&&"undefined"!==typeof module?module.exports=a(require("jquery"),require("pnotify")):"function"===typeof define&&define.amd?define("pnotify.tooltip",["jquery","pnotify"],a):a(jQuery,PNotify)})(function(a,b){});
|
||||
@@ -94,11 +94,11 @@ body {
|
||||
}
|
||||
|
||||
.nav {
|
||||
li.dropdown.open>.dropdown-toggle, li.dropdown.active>.dropdown-toggle, li.dropdown.open.active>.dropdown-toggle {
|
||||
>li.dropdown.open>.dropdown-toggle, >li.dropdown.active>.dropdown-toggle, >li.dropdown.open.active>.dropdown-toggle {
|
||||
// invert for dropdown
|
||||
.navbar-background-color(fade(@bottom, @gradientalpha), fade(@top, @gradientalpha), @image);
|
||||
}
|
||||
li>a:hover {
|
||||
>li>a:hover {
|
||||
// darken for hover
|
||||
@darkenedTop: darken(@top, 5%);
|
||||
@darkenedBottom: darken(@bottom, 5%);
|
||||
@@ -311,6 +311,16 @@ table {
|
||||
}
|
||||
|
||||
// timelapse files
|
||||
&.timelapse_files_checkbox,
|
||||
&.timelapse_unrendered_checkbox {
|
||||
text-align: center;
|
||||
width: 10px;
|
||||
|
||||
input[type="checkbox"] {
|
||||
margin-top: 0;
|
||||
}
|
||||
}
|
||||
|
||||
&.timelapse_files_name,
|
||||
&.timelapse_unrendered_name {
|
||||
text-overflow: ellipsis;
|
||||
@@ -1021,6 +1031,15 @@ textarea.block {
|
||||
text-decoration: underline;
|
||||
}
|
||||
|
||||
.btn-mini .caret, .btn-small .caret {
|
||||
margin-top: 8px;
|
||||
}
|
||||
|
||||
.dropdown-menu-right {
|
||||
right: 0;
|
||||
left: auto;
|
||||
}
|
||||
|
||||
/** Styles for Bootstrap Slider */
|
||||
|
||||
.slider {
|
||||
|
||||
@@ -16,10 +16,14 @@
|
||||
<div class="control-group">
|
||||
<label class="control-label" for="settings-apiKey">{{ _('API Key') }}</label>
|
||||
<div class="controls">
|
||||
<input type="text" class="input-block-level" data-bind="value: api_key, valueUpdate: 'afterkeydown'" id="settings-apikey">
|
||||
<div class="input-append">
|
||||
<input type="text" class="input-block-level" disabled="disabled" id="settings-apikey" data-bind="value: api_key, attr: {placeholder: '{{ _('N/A') }}'}">
|
||||
<button class="btn" title="Generate new API Key" data-bind="click: generateApiKey, enable: api_key"><i class="icon-refresh"></i></button>
|
||||
</div>
|
||||
<span class="help-block">{{ _('Please note that changes to the API key are applied immediately, without having to "Save" first.') }}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group">
|
||||
<div class="control-group" data-bind="visible: api_key">
|
||||
<label class="control-label">{{ _('QR Code') }}</label>
|
||||
<div class="controls">
|
||||
<div data-bind="qrcode: {text: api_key, size: 180}"></div>
|
||||
|
||||
@@ -39,7 +39,7 @@
|
||||
<div class="control-group">
|
||||
<div class="controls">
|
||||
<label class="checkbox">
|
||||
<input type="checkbox" data-bind="checked: appearance_showFahrenheitAlso" id="settings-appearanceShowFahrenheitAlso"> {{ _('Show temperatures in Fahrenheit as well as Celcius') }}
|
||||
<input type="checkbox" data-bind="checked: appearance_showFahrenheitAlso" id="settings-appearanceShowFahrenheitAlso"> {{ _('Show temperatures in Fahrenheit as well as Celsius') }}
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
@@ -51,6 +51,13 @@
|
||||
<h3>{{ _('Manage Language Packs...') }}</h3>
|
||||
</div>
|
||||
<div class="modal-body">
|
||||
<p>
|
||||
<strong>{{ _('There is currently no central repository for language packs like there is for plugins - any help to change that is appreciated!') }}</strong>
|
||||
</p>
|
||||
<p>
|
||||
{{ _('Until a repository is available, please see <a href="%(url)s" target="_blank" >the wiki</a> for language packs provided by the community.', url = "https://github.com/foosel/OctoPrint/wiki#language-packs") }}
|
||||
</p>
|
||||
|
||||
<h4>{{ _('Available Language Packs') }}</h4>
|
||||
|
||||
<div data-bind="visible: languagePacksAvailable()">
|
||||
|
||||
@@ -24,14 +24,14 @@
|
||||
<label class="control-label" for="userSettings-access_apikey">{{ _('Current API Key') }}</label>
|
||||
<div class="controls">
|
||||
<div class="input-append">
|
||||
<input type="text" class="input-block-level uneditable-input" id="userSettings-access_apikey" data-bind="value: access_apikey, valueUpdate: 'input', attr: {placeholder: '{{ _('N/A') }}'}">
|
||||
<a class="btn" title="Generate new Apikey" data-bind="click: generateApikey"><i class="icon-refresh"></i></a>
|
||||
<a class="btn btn-danger" title="Delete Apikey" data-bind="click: deleteApikey"><i class="icon-trash"></i></a>
|
||||
<input type="text" class="input-block-level" disabled="disabled" id="userSettings-access_apikey" data-bind="value: access_apikey, attr: {placeholder: '{{ _('N/A') }}'}">
|
||||
<button class="btn" title="Generate new API Key" data-bind="click: generateApikey"><i class="icon-refresh"></i></button>
|
||||
<button class="btn btn-danger" title="Delete API Key" data-bind="click: deleteApikey, enable: access_apikey"><i class="icon-trash"></i></button>
|
||||
</div>
|
||||
|
||||
<span class="help-block">{{ _('Please note that changes to the API key are applied immediately, without having to "Confirm" first.') }}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group">
|
||||
<div class="control-group" data-bind="visible: access_apikey">
|
||||
<label class="control-label">{{ _('QR Code') }}</label>
|
||||
<div class="controls">
|
||||
<div data-bind="qrcode: {text: access_apikey, size: 150}"></div>
|
||||
|
||||
@@ -8,10 +8,6 @@
|
||||
<link rel="apple-touch-icon" sizes="114x114" href="{{ url_for('static', filename='img/apple-touch-icon-114x114.png') }}">
|
||||
<link rel="apple-touch-icon" sizes="144x144" href="{{ url_for('static', filename='img/apple-touch-icon-144x144.png') }}">
|
||||
|
||||
<meta name="apple-mobile-web-app-capable" content="yes">
|
||||
<meta name="mobile-web-app-capable" content="yes">
|
||||
<meta name="apple-mobile-web-app-status-bar-style" content="black">
|
||||
|
||||
{% include 'stylesheets.jinja2' %}
|
||||
{% include 'initscript.jinja2' %}
|
||||
</head>
|
||||
|
||||
@@ -11,7 +11,7 @@
|
||||
web interface now by clicking the button below.
|
||||
{% endtrans %}</p>
|
||||
<p>
|
||||
<a class="btn btn-primary btn-large" title="{{ _('Reload now') }}" href="javascript:void(0)" onclick="location.reload(true); return false;">{{ _('Reload now') }}</a>
|
||||
<button class="btn btn-primary btn-large" title="{{ _('Reload now') }}" onclick="var event = arguments[0] || window.event; var source = event.target || event.srcElement; if (source.disabled) return; source.disabled = true; source.className += ' disabled'; source.firstChild.style.display = ''; location.reload(true); return false;"><i class="icon-spinner icon-spin" style="display: none"></i> {{ _('Reload now') }}</button>
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -23,7 +23,6 @@
|
||||
<li><a href="#" data-bind="click: function() { $root.listHelper.toggleFilter('sd'); }"><i class="icon-ok" data-bind="style: {visibility: _.contains(listHelper.currentFilters(), 'sd') ? 'visible' : 'hidden'}"></i> {{ _('Only show files stored on SD') }}</a></li>
|
||||
{% endif %}
|
||||
<li class="divider"></li>
|
||||
<li><a href="#" data-bind="click: function() { $root.listHelper.toggleFilter('emptyFolder'); }"><i class="icon-ok" data-bind="style: {visibility: _.contains(listHelper.currentFilters(), 'emptyFolder') ? 'visible' : 'hidden'}"></i> {{ _('Hide folders without files') }}</a></li>
|
||||
<li><a href="#" data-bind="click: function() { $root.listHelper.toggleFilter('printed'); }"><i class="icon-ok" data-bind="style: {visibility: _.contains(listHelper.currentFilters(), 'printed') ? 'visible' : 'hidden'}"></i> {{ _('Hide successfully printed files') }}</a></li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
@@ -8,10 +8,10 @@
|
||||
</thead>
|
||||
<tbody data-bind="foreach: printerProfiles.profiles.paginatedItems">
|
||||
<tr data-bind="attr: {title: name}">
|
||||
<td class="settings_printerProfiles_profiles_name"><span class="icon-star" data-bind="invisible: !isdefault()"></span> <span data-bind="text: name"></span></td>
|
||||
<td class="settings_printerProfiles_profiles_name"><span class="icon-star" data-bind="invisible: !isdefault()"></span> <span data-bind="text: name, style: { 'font-weight': iscurrent() ? 'bold' : 'normal' }"></span></td>
|
||||
<td class="settings_printerProfiles_profiles_model" data-bind="text: model"></td>
|
||||
<td class="settings_printerProfiles_profiles_action">
|
||||
<a href="#" class="icon-star" title="{{ _('Set as default profile') }}" data-bind="click: function() { $root.printerProfiles.makeDefault($data); }, css: {disabled: $root.printerProfiles.requestInProgress()}, enabled: !$root.printerProfiles.requestInProgress()"></a> | <a href="#" class="icon-pencil" title="{{ _('Edit Profile') }}" data-bind="click: function() { $root.printerProfiles.showEditProfileDialog($data); }, css: {disabled: $root.printerProfiles.requestInProgress()}, enabled: !$root.printerProfiles.requestInProgress()"></a> | <a href="#" class="icon-trash" title="{{ _('Delete Profile') }}" data-bind="click: function() { $root.printerProfiles.removeProfile($data); }, css: {disabled: $root.printerProfiles.requestInProgress()}, enabled: !$root.printerProfiles.requestInProgress()"></a>
|
||||
<a href="#" class="icon-star" title="{{ _('Set as default profile') }}" data-bind="click: function() { $root.printerProfiles.makeDefault($data); }, css: {disabled: !$root.printerProfiles.canMakeDefault($data) || $root.printerProfiles.requestInProgress()}, enabled: $root.printerProfile.canMakeDefault($data) && !$root.printerProfiles.requestInProgress()"></a> | <a href="#" class="icon-pencil" title="{{ _('Edit Profile') }}" data-bind="click: function() { $root.printerProfiles.showEditProfileDialog($data); }, css: {disabled: $root.printerProfiles.requestInProgress()}, enabled: !$root.printerProfiles.requestInProgress()"></a> | <a href="#" class="icon-trash" title="{{ _('Delete Profile') }}" data-bind="click: function() { $root.printerProfiles.removeProfile($data); }, css: {disabled: !$root.printerProfiles.canRemove($data) || $root.printerProfiles.requestInProgress()}, enabled: $root.printerProfiles.canRemove($data) && !$root.printerProfiles.requestInProgress()"></a>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
|
||||
@@ -13,6 +13,14 @@
|
||||
<span class="help-block" data-bind="visible: timelapseType() == 'zchange'"><span class="label label-warning">{{ _('Warning') }}</span> {{ _('Do not use with spiralized ("Joris") vases or similar continuous Z models.') }}</span>
|
||||
<span class="help-block" data-bind="visible: timelapseType() == 'zchange'"><span class="label label-info">{{ _('Note') }}</span> {% trans %}Does not work when printing from the printer's SD Card (no way to detect the change in Z reliably). Use "Timed" mode for those prints instead.{% endtrans %}</span>
|
||||
|
||||
<div id="webcam_timelapse_timedsettings" data-bind="visible: intervalInputEnabled">
|
||||
<label for="webcam_timelapse_interval">{{ _('Interval between snapshots (in seconds)') }}</label>
|
||||
<div class="input-append">
|
||||
<input type="text" class="input-mini" id="webcam_timelapse_interval" data-bind="value: timelapseTimedInterval, valueUpdate: 'afterkeydown', enable: isOperational() && !isPrinting() && loginState.isUser()">
|
||||
<span class="add-on">{{ _('sec') }}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<label for="webcam_timelapse_fps">{{ _('Timelapse frame rate (in frames per second)') }}</label>
|
||||
<div class="input-append">
|
||||
<input type="text" class="input-mini" id="webcam_timelapse_fps" data-bind="value: timelapseFps, valueUpdate: 'afterkeydown', enable: isOperational() && !isPrinting() && loginState.isUser() && timelapseTypeSelected()">
|
||||
@@ -31,15 +39,6 @@
|
||||
</label>
|
||||
</div>
|
||||
|
||||
|
||||
<div id="webcam_timelapse_timedsettings" data-bind="visible: intervalInputEnabled">
|
||||
<label for="webcam_timelapse_interval">{{ _('Interval') }}</label>
|
||||
<div class="input-append">
|
||||
<input type="text" class="input-mini" id="webcam_timelapse_interval" data-bind="value: timelapseTimedInterval, valueUpdate: 'afterkeydown', enable: isOperational() && !isPrinting() && loginState.isUser()">
|
||||
<span class="add-on">{{ _('sec') }}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div id="webcam_timelapse_retractionsettings" data-bind="visible: timelapseType() == 'zchange'">
|
||||
<label for="webcam_timelapse_retractionZHop">{{ _('Retraction Z-Hop (in mm)') }}</label>
|
||||
<div class="input-append">
|
||||
@@ -52,22 +51,44 @@
|
||||
<div data-bind="visible: loginState.isAdmin">
|
||||
<label class="checkbox">
|
||||
<input type="checkbox" data-bind="checked: persist"> {{ _('Save as default') }}
|
||||
<span class="help-block">{{ _('Check this to make your selected timelapse mode and options persist across restarts.') }}</span>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<button class="btn" data-bind="click: save, enable: saveButtonEnabled">{{ _('Save config') }}</button>
|
||||
<button class="btn" data-bind="click: save, enable: saveButtonEnabled">{{ _('Save changes') }}</button>
|
||||
<span class="help-inline" data-bind="visible: saveButtonEnabled">{{ _('You have unsaved changes.') }}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<h1>{{ _('Finished Timelapses') }}</h1>
|
||||
|
||||
<div class="pull-right">
|
||||
<small>{{ _('Sort by') }}: <a href="javascript:void(0)" data-bind="click: function() { listHelper.changeSorting('name'); }">{{ _('Name') }} ({{ _('ascending') }})</a> | <a href="javascript:void(0)" data-bind="click: function() { listHelper.changeSorting('creation'); }">{{ _('Creation date') }} ({{ _('descending') }})</a> | <a href="javascript:void(0)" data-bind="click: function() { listHelper.changeSorting('size'); }">{{ _('Size') }} ({{ _('descending') }})</a></small>
|
||||
<div class="btn-group">
|
||||
<button class="btn btn-small dropdown-toggle" data-toggle="dropdown"><i class="icon-wrench"></i> <span class="caret"></span></button>
|
||||
<ul class="dropdown-menu dropdown-menu-right">
|
||||
<li><a href="javascript:void(0)" data-bind="click: function() { listHelper.changeSorting('name'); }"><i class="icon-ok" data-bind="style: {visibility: listHelper.currentSorting() == 'name' ? 'visible' : 'hidden'}"></i> {{ _('Sort by name') }} ({{ _('ascending') }})</a></li>
|
||||
<li><a href="javascript:void(0)" data-bind="click: function() { listHelper.changeSorting('creation'); }"><i class="icon-ok" data-bind="style: {visibility: listHelper.currentSorting() == 'creation' ? 'visible' : 'hidden'}"></i> {{ _('Sort by creation date') }} ({{ _('descending') }})</a></li>
|
||||
<li><a href="javascript:void(0)" data-bind="click: function() { listHelper.changeSorting('size'); }"><i class="icon-ok" data-bind="style: {visibility: listHelper.currentSorting() == 'size' ? 'visible' : 'hidden'}"></i> {{ _('Sort by file size') }} ({{ _('descending') }})</a></li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
<div class="pull-left">
|
||||
<div class="btn-group">
|
||||
<button class="btn btn-small dropdown-toggle" data-toggle="dropdown"><i class="icon-check-empty"></i> <span class="caret"></span></button>
|
||||
<ul class="dropdown-menu">
|
||||
<li><a href="javascript:void(0)" data-bind="click: markFilesOnPage">{{ _('Select all on this page') }}</a></li>
|
||||
<li><a href="javascript:void(0)" data-bind="click: markAllFiles">{{ _('Select all') }}</a></li>
|
||||
<li class="divider"></li>
|
||||
<li><a href="javascript:void(0)" data-bind="click: clearMarkedFiles">{{ _('Clear selection') }}</a></li>
|
||||
</ul>
|
||||
</div>
|
||||
<button class="btn btn-small" data-bind="click: removeMarkedFiles, enable: markedForFileDeletion().length > 0">{{ _('Delete selected') }}</button>
|
||||
</div>
|
||||
<table class="table table-striped table-hover table-condensed table-hover" id="timelapse_files">
|
||||
<thead>
|
||||
<tr>
|
||||
<th class="timelapse_files_checkbox"></th>
|
||||
<th class="timelapse_files_name">{{ _('Name') }}</th>
|
||||
<th class="timelapse_files_size">{{ _('Size') }}</th>
|
||||
<th class="timelapse_files_action">{{ _('Action') }}</th>
|
||||
@@ -75,6 +96,7 @@
|
||||
</thead>
|
||||
<tbody data-bind="foreach: listHelper.paginatedItems">
|
||||
<tr data-bind="attr: {title: name}">
|
||||
<td class="timelapse_files_checkbox"><input type="checkbox" data-bind="value: name, checked: $root.markedForFileDeletion"></td>
|
||||
<td class="timelapse_files_name" data-bind="text: name"></td>
|
||||
<td class="timelapse_files_size" data-bind="text: size"></td>
|
||||
<td class="timelapse_files_action"><a href="javascript:void(0)" class="icon-trash" data-bind="click: function() { if ($root.loginState.isUser()) { $parent.removeFile($data.name); } else { return; } }, css: {disabled: !$root.loginState.isUser()}"></a> | <a href="javascript:void(0)" class="icon-download" data-bind="attr: {href: url}"></a></td>
|
||||
@@ -96,9 +118,22 @@
|
||||
<div data-bind="visible: unrenderedListHelper.allSize">
|
||||
<div><small><a href="javascript:void(0)" class="muted" onclick="$(this).children().toggleClass('icon-caret-right icon-caret-down').parent().parent().parent().next().slideToggle('fast')"><i class="icon-caret-right"></i> {{ _('Unrendered Timelapses') }}</a></small></div>
|
||||
<div class="hide">
|
||||
<div class="pull-left">
|
||||
<div class="btn-group">
|
||||
<button class="btn btn-small dropdown-toggle" data-toggle="dropdown"><i class="icon-check-empty"></i> <span class="caret"></span></button>
|
||||
<ul class="dropdown-menu">
|
||||
<li><a href="javascript:void(0)" data-bind="click: markUnrenderedOnPage">{{ _('Select all on this page') }}</a></li>
|
||||
<li><a href="javascript:void(0)" data-bind="click: markAllUnrendered">{{ _('Select all') }}</a></li>
|
||||
<li class="divider"></li>
|
||||
<li><a href="javascript:void(0)" data-bind="click: clearMarkedUnrendered">{{ _('Clear selection') }}</a></li>
|
||||
</ul>
|
||||
</div>
|
||||
<button class="btn btn-small" data-bind="click: removeMarkedUnrendered, enable: markedForUnrenderedDeletion().length > 0">{{ _('Delete selected') }}</button>
|
||||
</div>
|
||||
<table class="table table-striped table-hover table-condensed table-hover" id="timelapse_unrendered">
|
||||
<thead>
|
||||
<tr>
|
||||
<th class="timelapse_unrendered_checkbox"></th>
|
||||
<th class="timelapse_unrendered_name">{{ _('Name') }}</th>
|
||||
<th class="timelapse_unrendered_count">{{ _('Frames') }}</th>
|
||||
<th class="timelapse_unrendered_size">{{ _('Size') }}</th>
|
||||
@@ -107,6 +142,7 @@
|
||||
</thead>
|
||||
<tbody data-bind="foreach: unrenderedListHelper.paginatedItems">
|
||||
<tr data-bind="attr: {title: name}">
|
||||
<td class="timelapse_unrendered_checkbox"><input type="checkbox" data-bind="value: name, checked: $root.markedForUnrenderedDeletion"></td>
|
||||
<td class="timelapse_unrendered_name" data-bind="text: name"></td>
|
||||
<td class="timelapse_unrendered_count" data-bind="text: count"></td>
|
||||
<td class="timelapse_unrendered_size" data-bind="text: size"></td>
|
||||
|
||||
@@ -17,6 +17,7 @@ except ImportError:
|
||||
import Queue as queue
|
||||
import requests
|
||||
|
||||
import octoprint.plugin
|
||||
import octoprint.util as util
|
||||
|
||||
from octoprint.settings import settings
|
||||
@@ -294,18 +295,23 @@ def configure_timelapse(config=None, persist=False):
|
||||
|
||||
if type is None or "off" == type:
|
||||
current = None
|
||||
|
||||
elif "zchange" == type:
|
||||
retractionZHop = 0
|
||||
if "options" in config and "retractionZHop" in config["options"] and config["options"]["retractionZHop"] > 0:
|
||||
retractionZHop = config["options"]["retractionZHop"]
|
||||
|
||||
current = ZTimelapse(post_roll=postRoll, retraction_zhop=retractionZHop, fps=fps)
|
||||
|
||||
elif "timed" == type:
|
||||
interval = 10
|
||||
if "options" in config and "interval" in config["options"] and config["options"]["interval"] > 0:
|
||||
interval = config["options"]["interval"]
|
||||
capture_post_roll = True
|
||||
|
||||
capture_post_roll = False
|
||||
if "options" in config and "capturePostRoll" in config["options"] and isinstance(config["options"]["capturePostRoll"], bool):
|
||||
capture_post_roll = config["options"]["capturePostRoll"]
|
||||
|
||||
current = TimedTimelapse(post_roll=postRoll, interval=interval, fps=fps, capture_post_roll=capture_post_roll)
|
||||
|
||||
notify_callbacks(current)
|
||||
@@ -339,6 +345,11 @@ class Timelapse(object):
|
||||
|
||||
self._fps = fps
|
||||
|
||||
|
||||
self._pluginManager = octoprint.plugin.plugin_manager()
|
||||
self._pre_capture_hooks = self._pluginManager.get_hooks("octoprint.timelapse.capture.pre")
|
||||
self._post_capture_hooks = self._pluginManager.get_hooks("octoprint.timelapse.capture.post")
|
||||
|
||||
self._capture_mutex = threading.Lock()
|
||||
self._capture_queue = queue.Queue()
|
||||
self._capture_queue_active = True
|
||||
@@ -548,6 +559,13 @@ class Timelapse(object):
|
||||
entry["callback"](*args, **kwargs)
|
||||
|
||||
def _perform_capture(self, filename, onerror=None):
|
||||
# pre-capture hook
|
||||
for name, hook in self._pre_capture_hooks.items():
|
||||
try:
|
||||
hook(filename)
|
||||
except:
|
||||
self._logger.exception("Error while processing hook {name}.".format(**locals()))
|
||||
|
||||
eventManager().fire(Events.CAPTURE_START, dict(file=filename))
|
||||
try:
|
||||
self._logger.debug("Going to capture {} from {}".format(filename, self._snapshot_url))
|
||||
@@ -563,17 +581,31 @@ class Timelapse(object):
|
||||
self._logger.debug("Image {} captured from {}".format(filename, self._snapshot_url))
|
||||
except Exception as e:
|
||||
self._logger.exception("Could not capture image {} from {}".format(filename, self._snapshot_url))
|
||||
self._capture_errors += 1
|
||||
success = False
|
||||
else:
|
||||
self._capture_success += 1
|
||||
success = True
|
||||
|
||||
# post-capture hook
|
||||
for name, hook in self._post_capture_hooks.items():
|
||||
try:
|
||||
hook(filename, success)
|
||||
except:
|
||||
self._logger.exception("Error while processing hook {name}.".format(**locals()))
|
||||
|
||||
# handle events and onerror call
|
||||
if success:
|
||||
eventManager().fire(Events.CAPTURE_DONE, dict(file=filename))
|
||||
return True
|
||||
else:
|
||||
if callable(onerror):
|
||||
onerror()
|
||||
eventManager().fire(Events.CAPTURE_FAILED, dict(file=filename,
|
||||
error=str(e),
|
||||
url=self._snapshot_url))
|
||||
self._capture_errors += 1
|
||||
return False
|
||||
else:
|
||||
eventManager().fire(Events.CAPTURE_DONE, dict(file=filename))
|
||||
self._capture_success += 1
|
||||
return True
|
||||
|
||||
|
||||
def _copying_postroll(self):
|
||||
with self._capture_mutex:
|
||||
|
||||
Binary file not shown.
File diff suppressed because it is too large.
Load diff
+30
-24
@@ -26,7 +26,7 @@ class UserManager(object):
|
||||
def __init__(self):
|
||||
self._logger = logging.getLogger(__name__)
|
||||
self._session_users_by_session = dict()
|
||||
self._session_users_by_userid = dict()
|
||||
self._sessionids_by_userid = dict()
|
||||
self._enabled = True
|
||||
|
||||
@property
|
||||
@@ -61,9 +61,10 @@ class UserManager(object):
|
||||
self._session_users_by_session[user.get_session()] = user
|
||||
|
||||
userid = user.get_id()
|
||||
if not userid in self._session_users_by_userid:
|
||||
self._session_users_by_userid[userid] = []
|
||||
self._session_users_by_userid[userid].append(user)
|
||||
if not userid in self._sessionids_by_userid:
|
||||
self._sessionids_by_userid[userid] = set()
|
||||
|
||||
self._sessionids_by_userid[userid].add(user.get_session())
|
||||
|
||||
self._logger.debug("Logged in user: %r" % user)
|
||||
|
||||
@@ -80,15 +81,16 @@ class UserManager(object):
|
||||
return
|
||||
|
||||
userid = user.get_id()
|
||||
if userid in self._session_users_by_userid:
|
||||
users_by_userid = self._session_users_by_userid[userid]
|
||||
for u in users_by_userid:
|
||||
if u.get_session() == user.get_session():
|
||||
users_by_userid.remove(u)
|
||||
break
|
||||
sessionid = user.get_session()
|
||||
|
||||
if user.get_session() in self._session_users_by_session:
|
||||
del self._session_users_by_session[user.get_session()]
|
||||
if userid in self._sessionids_by_userid:
|
||||
try:
|
||||
self._sessionids_by_userid[userid].remove(sessionid)
|
||||
except KeyError:
|
||||
pass
|
||||
|
||||
if sessionid in self._session_users_by_session:
|
||||
del self._session_users_by_session[sessionid]
|
||||
|
||||
self._logger.debug("Logged out user: %r" % user)
|
||||
|
||||
@@ -177,13 +179,12 @@ class UserManager(object):
|
||||
pass
|
||||
|
||||
def removeUser(self, username):
|
||||
if username in self._session_users_by_userid:
|
||||
users = self._session_users_by_userid[username]
|
||||
sessions = [user.get_session() for user in users if isinstance(user, SessionUser)]
|
||||
if username in self._sessionids_by_userid:
|
||||
sessions = self._sessionids_by_userid[username]
|
||||
for session in sessions:
|
||||
if session in self._session_users_by_session:
|
||||
del self._session_users_by_session[session]
|
||||
del self._session_users_by_userid[username]
|
||||
del self._sessionids_by_userid[username]
|
||||
|
||||
def findUser(self, userid=None, session=None):
|
||||
if session is not None and session in self._session_users_by_session:
|
||||
@@ -234,7 +235,11 @@ class FilebasedUserManager(UserManager):
|
||||
settings = dict()
|
||||
if "settings" in attributes:
|
||||
settings = attributes["settings"]
|
||||
|
||||
self._users[name] = User(name, attributes["password"], attributes["active"], permissions, groups, apikey=apikey, settings=settings)
|
||||
for sessionid in self._sessionids_by_userid.get(name, set()):
|
||||
if sessionid in self._session_users_by_session:
|
||||
self._session_users_by_session[sessionid].update_user(self._users[name])
|
||||
else:
|
||||
self._customized = False
|
||||
|
||||
@@ -386,9 +391,8 @@ class FilebasedUserManager(UserManager):
|
||||
raise UnknownUser(username)
|
||||
|
||||
user = self._users[username]
|
||||
current = user.get_setting(key)
|
||||
if not current or current != value:
|
||||
old_value = user.get_setting(key)
|
||||
old_value = user.get_setting(key)
|
||||
if not old_value or old_value != value:
|
||||
user.set_setting(key, value)
|
||||
self._dirty = self._dirty or old_value != value
|
||||
self._save()
|
||||
@@ -557,7 +561,7 @@ class User(UserMixin):
|
||||
self._permissions = permissions
|
||||
self._apikey = apikey
|
||||
|
||||
if not settings:
|
||||
if settings is None:
|
||||
settings = dict()
|
||||
self._settings = settings
|
||||
|
||||
@@ -704,7 +708,7 @@ class User(UserMixin):
|
||||
def _get_setting(self, path):
|
||||
s = self._settings
|
||||
for p in path:
|
||||
if p in s:
|
||||
if isinstance(s, dict) and p in s:
|
||||
s = s[p]
|
||||
else:
|
||||
return None
|
||||
@@ -717,7 +721,7 @@ class User(UserMixin):
|
||||
s[p] = dict()
|
||||
|
||||
if not isinstance(s[p], dict):
|
||||
return False
|
||||
s[p] = dict()
|
||||
|
||||
s = s[p]
|
||||
|
||||
@@ -746,7 +750,6 @@ class AnonymousUser(AnonymousUserMixin):
|
||||
class SessionUser(User):
|
||||
def __init__(self, user):
|
||||
self._user = user
|
||||
User.__init__(self, user._username, user._passwordHash, user._active, user._permissions, user._groups, user._apikey, user._settings)
|
||||
|
||||
import string
|
||||
import random
|
||||
@@ -756,7 +759,7 @@ class SessionUser(User):
|
||||
self._created = time.time()
|
||||
|
||||
def __getattribute__(self, item):
|
||||
if item in ("get_session", "_user", "_session", "_created"):
|
||||
if item in ("get_session", "update_user", "_user", "_session", "_created"):
|
||||
return object.__getattribute__(self, item)
|
||||
else:
|
||||
return getattr(object.__getattribute__(self, "_user"), item)
|
||||
@@ -770,6 +773,9 @@ class SessionUser(User):
|
||||
def get_session(self):
|
||||
return self._session
|
||||
|
||||
def update_user(self, user):
|
||||
self._user = user
|
||||
|
||||
def __repr__(self):
|
||||
return "SessionUser(id=%s,name=%s,active=%r,user=%r,admin=%r,session=%s,created=%s)" % (self.get_id(), self.get_name(), bool(self.is_active), bool(self.is_user), bool(self.is_admin), self._session, self._created)
|
||||
|
||||
|
||||
+197
-135
@@ -127,6 +127,9 @@ Groups will be as follows:
|
||||
regex_firmware_splitter = re.compile("\s*([A-Z0-9_]+):")
|
||||
"""Regex to use for splitting M115 responses."""
|
||||
|
||||
regex_resend_linenumber = re.compile("(N|N:)?(?P<n>%s)" % regex_int_pattern)
|
||||
"""Regex to use for request line numbers in resend requests"""
|
||||
|
||||
def serialList():
|
||||
baselist=[]
|
||||
if os.name=="nt":
|
||||
@@ -390,7 +393,7 @@ class MachineCom(object):
|
||||
self._currentFile = None
|
||||
|
||||
# multithreading locks
|
||||
self._sendNextLock = threading.Lock()
|
||||
self._jobLock = threading.RLock()
|
||||
self._sendingLock = threading.RLock()
|
||||
|
||||
# monitoring thread
|
||||
@@ -746,41 +749,42 @@ class MachineCom(object):
|
||||
self._pauseWaitTimeLost = 0.0
|
||||
|
||||
try:
|
||||
self._currentFile.start()
|
||||
with self._jobLock:
|
||||
self._currentFile.start()
|
||||
|
||||
self._changeState(self.STATE_PRINTING)
|
||||
self._changeState(self.STATE_PRINTING)
|
||||
|
||||
self.resetLineNumbers()
|
||||
self.resetLineNumbers()
|
||||
|
||||
self._callback.on_comm_print_job_started()
|
||||
self._callback.on_comm_print_job_started()
|
||||
|
||||
if self.isSdFileSelected():
|
||||
#self.sendCommand("M26 S0") # setting the sd pos apparently sometimes doesn't work, so we re-select
|
||||
# the file instead
|
||||
if self.isSdFileSelected():
|
||||
#self.sendCommand("M26 S0") # setting the sd pos apparently sometimes doesn't work, so we re-select
|
||||
# the file instead
|
||||
|
||||
# make sure to ignore the "file selected" later on, otherwise we'll reset our progress data
|
||||
self._ignore_select = True
|
||||
self.sendCommand("M23 {filename}".format(filename=self._currentFile.getFilename()))
|
||||
if pos is not None and isinstance(pos, int) and pos > 0:
|
||||
self._currentFile.setFilepos(pos)
|
||||
self.sendCommand("M26 S{}".format(pos))
|
||||
# make sure to ignore the "file selected" later on, otherwise we'll reset our progress data
|
||||
self._ignore_select = True
|
||||
self.sendCommand("M23 {filename}".format(filename=self._currentFile.getFilename()))
|
||||
if pos is not None and isinstance(pos, int) and pos > 0:
|
||||
self._currentFile.setFilepos(pos)
|
||||
self.sendCommand("M26 S{}".format(pos))
|
||||
else:
|
||||
self._currentFile.setFilepos(0)
|
||||
|
||||
self.sendCommand("M24")
|
||||
|
||||
self._sd_status_timer = RepeatedTimer(self._timeout_intervals.get("sdStatus", 1.0), self._poll_sd_status, run_first=True)
|
||||
self._sd_status_timer.start()
|
||||
else:
|
||||
self._currentFile.setFilepos(0)
|
||||
if pos is not None and isinstance(pos, int) and pos > 0:
|
||||
self._currentFile.seek(pos)
|
||||
|
||||
self.sendCommand("M24")
|
||||
line = self._getNext()
|
||||
if line is not None:
|
||||
self.sendCommand(line)
|
||||
|
||||
self._sd_status_timer = RepeatedTimer(self._timeout_intervals.get("sdStatus", 1.0), self._poll_sd_status, run_first=True)
|
||||
self._sd_status_timer.start()
|
||||
else:
|
||||
if pos is not None and isinstance(pos, int) and pos > 0:
|
||||
self._currentFile.seek(pos)
|
||||
|
||||
line = self._getNext()
|
||||
if line is not None:
|
||||
self.sendCommand(line)
|
||||
|
||||
# now make sure we actually do something, up until now we only filled up the queue
|
||||
self._sendFromQueue()
|
||||
# now make sure we actually do something, up until now we only filled up the queue
|
||||
self._sendFromQueue()
|
||||
except:
|
||||
self._logger.exception("Error while trying to start printing")
|
||||
self._errorValue = get_exception_string()
|
||||
@@ -789,17 +793,18 @@ class MachineCom(object):
|
||||
|
||||
def startFileTransfer(self, filename, localFilename, remoteFilename):
|
||||
if not self.isOperational() or self.isBusy():
|
||||
logging.info("Printer is not operation or busy")
|
||||
logging.info("Printer is not operational or busy")
|
||||
return
|
||||
|
||||
self.resetLineNumbers()
|
||||
with self._jobLock:
|
||||
self.resetLineNumbers()
|
||||
|
||||
self._currentFile = StreamingGcodeFileInformation(filename, localFilename, remoteFilename)
|
||||
self._currentFile.start()
|
||||
self._currentFile = StreamingGcodeFileInformation(filename, localFilename, remoteFilename)
|
||||
self._currentFile.start()
|
||||
|
||||
self.sendCommand("M28 %s" % remoteFilename)
|
||||
eventManager().fire(Events.TRANSFER_STARTED, {"local": localFilename, "remote": remoteFilename})
|
||||
self._callback.on_comm_file_transfer_started(remoteFilename, self._currentFile.getFilesize())
|
||||
self.sendCommand("M28 %s" % remoteFilename)
|
||||
eventManager().fire(Events.TRANSFER_STARTED, {"local": localFilename, "remote": remoteFilename})
|
||||
self._callback.on_comm_file_transfer_started(remoteFilename, self._currentFile.getFilesize())
|
||||
|
||||
def selectFile(self, filename, sd):
|
||||
if self.isBusy():
|
||||
@@ -838,18 +843,6 @@ class MachineCom(object):
|
||||
# we aren't even printing, nothing to cancel...
|
||||
return
|
||||
|
||||
self._changeState(self.STATE_OPERATIONAL)
|
||||
|
||||
if self.isSdFileSelected():
|
||||
self.sendCommand("M25") # pause print
|
||||
self.sendCommand("M27") # get current byte position in file
|
||||
self.sendCommand("M26 S0") # reset position in file to byte 0
|
||||
if self._sd_status_timer is not None:
|
||||
try:
|
||||
self._sd_status_timer.cancel()
|
||||
except:
|
||||
pass
|
||||
|
||||
def _on_M400_sent():
|
||||
# we don't call on_print_job_cancelled on our callback here
|
||||
# because we do this only after our M114 has been answered
|
||||
@@ -857,7 +850,20 @@ class MachineCom(object):
|
||||
self._record_cancel_position = True
|
||||
self.sendCommand("M114")
|
||||
|
||||
self.sendCommand("M400", on_sent=_on_M400_sent)
|
||||
with self._jobLock:
|
||||
self._changeState(self.STATE_OPERATIONAL)
|
||||
|
||||
if self.isSdFileSelected():
|
||||
self.sendCommand("M25") # pause print
|
||||
self.sendCommand("M27") # get current byte position in file
|
||||
self.sendCommand("M26 S0") # reset position in file to byte 0
|
||||
if self._sd_status_timer is not None:
|
||||
try:
|
||||
self._sd_status_timer.cancel()
|
||||
except:
|
||||
pass
|
||||
|
||||
self.sendCommand("M400", on_sent=_on_M400_sent)
|
||||
|
||||
def _pause_preparation_done(self):
|
||||
self._callback.on_comm_print_job_paused()
|
||||
@@ -869,41 +875,42 @@ class MachineCom(object):
|
||||
if not self._currentFile:
|
||||
return
|
||||
|
||||
if not pause and self.isPaused():
|
||||
if self._pauseWaitStartTime:
|
||||
self._pauseWaitTimeLost = self._pauseWaitTimeLost + (time.time() - self._pauseWaitStartTime)
|
||||
self._pauseWaitStartTime = None
|
||||
with self._jobLock:
|
||||
if not pause and self.isPaused():
|
||||
if self._pauseWaitStartTime:
|
||||
self._pauseWaitTimeLost = self._pauseWaitTimeLost + (time.time() - self._pauseWaitStartTime)
|
||||
self._pauseWaitStartTime = None
|
||||
|
||||
self._changeState(self.STATE_PRINTING)
|
||||
self._callback.on_comm_print_job_resumed()
|
||||
self._changeState(self.STATE_PRINTING)
|
||||
self._callback.on_comm_print_job_resumed()
|
||||
|
||||
if self.isSdFileSelected():
|
||||
self.sendCommand("M24")
|
||||
self.sendCommand("M27")
|
||||
else:
|
||||
line = self._getNext()
|
||||
if line is not None:
|
||||
self.sendCommand(line)
|
||||
if self.isSdFileSelected():
|
||||
self.sendCommand("M24")
|
||||
self.sendCommand("M27")
|
||||
else:
|
||||
line = self._getNext()
|
||||
if line is not None:
|
||||
self.sendCommand(line)
|
||||
|
||||
# now make sure we actually do something, up until now we only filled up the queue
|
||||
self._sendFromQueue()
|
||||
# now make sure we actually do something, up until now we only filled up the queue
|
||||
self._sendFromQueue()
|
||||
|
||||
elif pause and self.isPrinting():
|
||||
if not self._pauseWaitStartTime:
|
||||
self._pauseWaitStartTime = time.time()
|
||||
elif pause and self.isPrinting():
|
||||
if not self._pauseWaitStartTime:
|
||||
self._pauseWaitStartTime = time.time()
|
||||
|
||||
self._changeState(self.STATE_PAUSED)
|
||||
if self.isSdFileSelected():
|
||||
self.sendCommand("M25") # pause print
|
||||
self._changeState(self.STATE_PAUSED)
|
||||
if self.isSdFileSelected():
|
||||
self.sendCommand("M25") # pause print
|
||||
|
||||
def _on_M400_sent():
|
||||
# we don't call on_print_job_paused on our callback here
|
||||
# because we do this only after our M114 has been answered
|
||||
# by the firmware
|
||||
self._record_pause_position = True
|
||||
self.sendCommand("M114")
|
||||
def _on_M400_sent():
|
||||
# we don't call on_print_job_paused on our callback here
|
||||
# because we do this only after our M114 has been answered
|
||||
# by the firmware
|
||||
self._record_pause_position = True
|
||||
self.sendCommand("M114")
|
||||
|
||||
self.sendCommand("M400", on_sent=_on_M400_sent)
|
||||
self.sendCommand("M400", on_sent=_on_M400_sent)
|
||||
|
||||
def getSdFiles(self):
|
||||
return self._sdFiles
|
||||
@@ -1145,7 +1152,7 @@ class MachineCom(object):
|
||||
# a response to an M105 or an M114
|
||||
self._handle_ok()
|
||||
needs_further_handling = "T:" in line or "T0:" in line or "B:" in line or "C:" in line or \
|
||||
"X:" in line or "FIRMWARE_NAME:" in line
|
||||
"X:" in line or "NAME:" in line
|
||||
handled = (line == "wait" or line == "ok" or not needs_further_handling)
|
||||
|
||||
# process resends
|
||||
@@ -1232,13 +1239,29 @@ class MachineCom(object):
|
||||
pass
|
||||
|
||||
##~~ firmware name & version
|
||||
elif "FIRMWARE_NAME:" in line:
|
||||
elif "NAME:" in line:
|
||||
# looks like a response to M115
|
||||
data = parse_firmware_line(line)
|
||||
firmware_name = data.get("FIRMWARE_NAME")
|
||||
self._logger.info("Printer reports firmware name \"{}\"".format(firmware_name))
|
||||
|
||||
if firmware_name is None:
|
||||
# Malyan's "Marlin compatible firmware" isn't actually Marlin compatible and doesn't even
|
||||
# report its firmware name properly in response to M115. Wonderful - why stick to established
|
||||
# protocol when you can do your own thing, right?
|
||||
#
|
||||
# Example: NAME: Malyan VER: 2.9 MODEL: M200 HW: HA02
|
||||
#
|
||||
# We do a bit of manual fiddling around here to circumvent that issue and get ourselves a
|
||||
# reliable firmware name (NAME + VER) out of the Malyan M115 response.
|
||||
name = data.get("NAME")
|
||||
ver = data.get("VER")
|
||||
if "malyan" in name.lower() and ver:
|
||||
firmware_name = name.strip() + " " + ver.strip()
|
||||
|
||||
if not self._firmwareInfoReceived and firmware_name:
|
||||
firmware_name = firmware_name.strip()
|
||||
self._logger.info("Printer reports firmware name \"{}\"".format(firmware_name))
|
||||
|
||||
if "repetier" in firmware_name.lower():
|
||||
self._logger.info("Detected Repetier firmware, enabling relevant features for issue free communication")
|
||||
|
||||
@@ -1257,6 +1280,16 @@ class MachineCom(object):
|
||||
self._logger.info("Detected RepRapFirmware, enabling relevant features for issue free communication")
|
||||
self._sdRelativePath = True
|
||||
|
||||
elif "malyan" in firmware_name.lower():
|
||||
self._logger.info("Detected Malyan firmware, enabling relevant features for issue free communication")
|
||||
|
||||
self._alwaysSendChecksum = True
|
||||
|
||||
sd_always_available = self._sdAlwaysAvailable
|
||||
self._sdAlwaysAvailable = True
|
||||
if not sd_always_available and not self._sdAvailable:
|
||||
self.initSdCard()
|
||||
|
||||
self._firmwareInfoReceived = True
|
||||
|
||||
##~~ SD Card handling
|
||||
@@ -1393,6 +1426,18 @@ class MachineCom(object):
|
||||
self._log("There was a timeout while trying to connect to the printer")
|
||||
self.close(wait=False)
|
||||
|
||||
### Operational (idle or busy)
|
||||
elif self._state in (self.STATE_OPERATIONAL,
|
||||
self.STATE_PRINTING,
|
||||
self.STATE_PAUSED,
|
||||
self.STATE_TRANSFERING_FILE):
|
||||
if line == "start": # exact match, to be on the safe side
|
||||
message = "Printer sent 'start' while already operational. External reset? " \
|
||||
"Resetting line numbers to be on the safe side"
|
||||
self._log(message)
|
||||
self._logger.warn(message)
|
||||
self.resetLineNumbers()
|
||||
|
||||
except:
|
||||
self._logger.exception("Something crashed inside the serial connection loop, please report this in OctoPrint's bug tracker:")
|
||||
|
||||
@@ -1829,7 +1874,7 @@ class MachineCom(object):
|
||||
return line
|
||||
|
||||
def _sendNext(self):
|
||||
with self._sendNextLock:
|
||||
with self._jobLock:
|
||||
while self._active:
|
||||
# we loop until we've actually enqueued a line for sending
|
||||
if self._state != self.STATE_PRINTING:
|
||||
@@ -1851,13 +1896,7 @@ class MachineCom(object):
|
||||
|
||||
def _handleResendRequest(self, line):
|
||||
try:
|
||||
lineToResend = None
|
||||
try:
|
||||
lineToResend = int(line.replace("N:", " ").replace("N", " ").replace(":", " ").split()[-1])
|
||||
except:
|
||||
if "rs" in line:
|
||||
lineToResend = int(line.split()[1])
|
||||
|
||||
lineToResend = parse_resend_line(line)
|
||||
if lineToResend is None:
|
||||
return False
|
||||
|
||||
@@ -2599,6 +2638,7 @@ class PrintingGcodeFileInformation(PrintingFileInformation):
|
||||
PrintingFileInformation.__init__(self, filename)
|
||||
|
||||
self._handle = None
|
||||
self._handle_mutex = threading.RLock()
|
||||
|
||||
self._offsets_callback = offsets_callback
|
||||
self._current_tool_callback = current_tool_callback
|
||||
@@ -2610,76 +2650,80 @@ class PrintingGcodeFileInformation(PrintingFileInformation):
|
||||
self._read_lines = 0
|
||||
|
||||
def seek(self, offset):
|
||||
if self._handle is None:
|
||||
return
|
||||
with self._handle_mutex:
|
||||
if self._handle is None:
|
||||
return
|
||||
|
||||
self._handle.seek(offset)
|
||||
self._pos = self._handle.tell()
|
||||
self._read_lines = 0
|
||||
self._handle.seek(offset)
|
||||
self._pos = self._handle.tell()
|
||||
self._read_lines = 0
|
||||
|
||||
def start(self):
|
||||
"""
|
||||
Opens the file for reading and determines the file size.
|
||||
"""
|
||||
PrintingFileInformation.start(self)
|
||||
self._handle = bom_aware_open(self._filename, encoding="utf-8", errors="replace")
|
||||
self._pos = self._handle.tell()
|
||||
if self._handle.encoding.endswith("-sig"):
|
||||
# Apparently we found an utf-8 bom in the file.
|
||||
# We need to add its length to our pos because it will
|
||||
# be stripped transparently and we'll have no chance
|
||||
# catching that.
|
||||
import codecs
|
||||
self._pos += len(codecs.BOM_UTF8)
|
||||
self._read_lines = 0
|
||||
with self._handle_mutex:
|
||||
self._handle = bom_aware_open(self._filename, encoding="utf-8", errors="replace")
|
||||
self._pos = self._handle.tell()
|
||||
if self._handle.encoding.endswith("-sig"):
|
||||
# Apparently we found an utf-8 bom in the file.
|
||||
# We need to add its length to our pos because it will
|
||||
# be stripped transparently and we'll have no chance
|
||||
# catching that.
|
||||
import codecs
|
||||
self._pos += len(codecs.BOM_UTF8)
|
||||
self._read_lines = 0
|
||||
|
||||
def close(self):
|
||||
"""
|
||||
Closes the file if it's still open.
|
||||
"""
|
||||
PrintingFileInformation.close(self)
|
||||
if self._handle is not None:
|
||||
try:
|
||||
self._handle.close()
|
||||
except:
|
||||
pass
|
||||
self._handle = None
|
||||
with self._handle_mutex:
|
||||
if self._handle is not None:
|
||||
try:
|
||||
self._handle.close()
|
||||
except:
|
||||
pass
|
||||
self._handle = None
|
||||
|
||||
def getNext(self):
|
||||
"""
|
||||
Retrieves the next line for printing.
|
||||
"""
|
||||
if self._handle is None:
|
||||
raise ValueError("File %s is not open for reading" % self._filename)
|
||||
with self._handle_mutex:
|
||||
if self._handle is None:
|
||||
raise ValueError("File %s is not open for reading" % self._filename)
|
||||
|
||||
try:
|
||||
offsets = self._offsets_callback() if self._offsets_callback is not None else None
|
||||
current_tool = self._current_tool_callback() if self._current_tool_callback is not None else None
|
||||
try:
|
||||
offsets = self._offsets_callback() if self._offsets_callback is not None else None
|
||||
current_tool = self._current_tool_callback() if self._current_tool_callback is not None else None
|
||||
|
||||
processed = None
|
||||
while processed is None:
|
||||
if self._handle is None:
|
||||
# file got closed just now
|
||||
self._pos = self._size
|
||||
self._report_stats()
|
||||
return None
|
||||
processed = None
|
||||
while processed is None:
|
||||
if self._handle is None:
|
||||
# file got closed just now
|
||||
self._pos = self._size
|
||||
self._report_stats()
|
||||
return None
|
||||
|
||||
# we need to manually keep track of our pos here since
|
||||
# codecs' readline will make our handle's tell not
|
||||
# return the actual number of bytes read, but also the
|
||||
# already buffered bytes (for detecting the newlines)
|
||||
line = self._handle.readline()
|
||||
self._pos += len(line.encode("utf-8"))
|
||||
# we need to manually keep track of our pos here since
|
||||
# codecs' readline will make our handle's tell not
|
||||
# return the actual number of bytes read, but also the
|
||||
# already buffered bytes (for detecting the newlines)
|
||||
line = self._handle.readline()
|
||||
self._pos += len(line.encode("utf-8"))
|
||||
|
||||
if not line:
|
||||
self.close()
|
||||
processed = self._process(line, offsets, current_tool)
|
||||
self._read_lines += 1
|
||||
return processed
|
||||
except Exception as e:
|
||||
self.close()
|
||||
self._logger.exception("Exception while processing line")
|
||||
raise e
|
||||
if not line:
|
||||
self.close()
|
||||
processed = self._process(line, offsets, current_tool)
|
||||
self._read_lines += 1
|
||||
return processed
|
||||
except Exception as e:
|
||||
self.close()
|
||||
self._logger.exception("Exception while processing line")
|
||||
raise e
|
||||
|
||||
def _process(self, line, offsets, current_tool):
|
||||
return process_gcode_line(line, offsets=offsets, current_tool=current_tool)
|
||||
@@ -3003,6 +3047,24 @@ def parse_firmware_line(line):
|
||||
result[key] = value
|
||||
return result
|
||||
|
||||
def parse_resend_line(line):
|
||||
"""
|
||||
Parses the provided resend line and returns requested line number.
|
||||
|
||||
Args:
|
||||
line (str): the line to parse
|
||||
|
||||
Returns:
|
||||
int or None: the extracted line number to resend, or None if no number could be extracted
|
||||
"""
|
||||
|
||||
match = regex_resend_linenumber.search(line)
|
||||
if match is not None:
|
||||
return int(match.group("n"))
|
||||
|
||||
return None
|
||||
|
||||
|
||||
def gcode_command_for_cmd(cmd):
|
||||
"""
|
||||
Tries to parse the provided ``cmd`` and extract the GCODE command identifier from it (e.g. "G0" for "G0 X10.0").
|
||||
|
||||
@@ -221,7 +221,7 @@ class gcode(object):
|
||||
self._reenqueue = reenqueue
|
||||
|
||||
def _load(self, gcodeFile, printer_profile, throttle=None):
|
||||
filePos = 0
|
||||
lineNo = 0
|
||||
readBytes = 0
|
||||
pos = Vector3D(0.0, 0.0, 0.0)
|
||||
posOffset = Vector3D(0.0, 0.0, 0.0)
|
||||
@@ -245,18 +245,18 @@ class gcode(object):
|
||||
for line in gcodeFile:
|
||||
if self._abort:
|
||||
raise AnalysisAborted(reenqueue=self._reenqueue)
|
||||
filePos += 1
|
||||
lineNo += 1
|
||||
readBytes += len(line)
|
||||
|
||||
if isinstance(gcodeFile, (file)):
|
||||
percentage = float(readBytes) / float(self._fileSize)
|
||||
elif isinstance(gcodeFile, (list)):
|
||||
percentage = float(filePos) / float(len(gcodeFile))
|
||||
percentage = float(lineNo) / float(len(gcodeFile))
|
||||
else:
|
||||
percentage = None
|
||||
|
||||
try:
|
||||
if self.progressCallback is not None and (filePos % 1000 == 0) and percentage is not None:
|
||||
if self.progressCallback is not None and (lineNo % 1000 == 0) and percentage is not None:
|
||||
self.progressCallback(percentage)
|
||||
except:
|
||||
pass
|
||||
@@ -444,7 +444,7 @@ class gcode(object):
|
||||
totalExtrusion.append(0.0)
|
||||
|
||||
if throttle is not None:
|
||||
throttle()
|
||||
throttle(lineNo, readBytes)
|
||||
if self.progressCallback is not None:
|
||||
self.progressCallback(100.0)
|
||||
|
||||
|
||||
@@ -370,10 +370,6 @@ class PipCaller(CommandlineCaller):
|
||||
def _preprocess_lines(self, *lines):
|
||||
return map(self._preprocess, lines)
|
||||
|
||||
@staticmethod
|
||||
def _convert_lines(lines):
|
||||
return map(PipCaller._convert_line, lines)
|
||||
|
||||
@staticmethod
|
||||
def _preprocess(text):
|
||||
"""
|
||||
|
||||
+120
-150
@@ -8,8 +8,15 @@ __copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms
|
||||
import requests
|
||||
import time
|
||||
|
||||
apikey = None
|
||||
baseurl = None
|
||||
|
||||
def build_base_url(https=False, httpuser=None, httppass=None, host=None, port=None, prefix=None):
|
||||
protocol = "https" if https else "http"
|
||||
httpauth = "{}:{}@".format(httpuser, httppass) if httpuser and httppass else ""
|
||||
host = host if host else "127.0.0.1"
|
||||
port = ":{}".format(port) if port else ":5000"
|
||||
prefix = prefix if prefix else ""
|
||||
|
||||
return "{}://{}{}{}{}".format(protocol, httpauth, host, port, prefix)
|
||||
|
||||
|
||||
class SocketTimeout(BaseException):
|
||||
@@ -202,183 +209,146 @@ class SocketClient(object):
|
||||
# a reconnect, that's a failure
|
||||
return False
|
||||
|
||||
class Client(object):
|
||||
|
||||
def build_base_url(https=False, httpuser=None, httppass=None, host=None, port=None, prefix=None):
|
||||
protocol = "https" if https else "http"
|
||||
httpauth = "{}:{}@".format(httpuser, httppass) if httpuser and httppass else ""
|
||||
host = host if host else "127.0.0.1"
|
||||
port = ":{}".format(port) if port else ":5000"
|
||||
prefix = prefix if prefix else ""
|
||||
def __init__(self, baseurl, apikey):
|
||||
self.baseurl = baseurl
|
||||
self.apikey = apikey
|
||||
|
||||
return "{}://{}{}{}{}".format(protocol, httpauth, host, port, prefix)
|
||||
def prepare_request(self, method=None, path=None, params=None):
|
||||
url = None
|
||||
if self.baseurl:
|
||||
while path.startswith("/"):
|
||||
path = path[1:]
|
||||
url = self.baseurl + "/" + path
|
||||
return requests.Request(method=method, url=url, params=params, headers={"X-Api-Key": self.apikey}).prepare()
|
||||
|
||||
def request(self, method, path, data=None, files=None, encoding=None, params=None):
|
||||
s = requests.Session()
|
||||
request = self.prepare_request(method, path, params=params)
|
||||
if data or files:
|
||||
if encoding == "json":
|
||||
request.prepare_body(None, None, json=data)
|
||||
else:
|
||||
request.prepare_body(data, files=files)
|
||||
response = s.send(request)
|
||||
return response
|
||||
|
||||
def init_client(settings, https=False, httpuser=None, httppass=None, host=None, port=None, prefix=None):
|
||||
"""
|
||||
Initializes the API client with the provided settings.
|
||||
def get(self, path, params=None):
|
||||
return self.request("GET", path, params=params)
|
||||
|
||||
Basically a convenience method to set ``apikey`` and ``baseurl`` from settings
|
||||
and/or command line arguments.
|
||||
def post(self, path, data, encoding=None, params=None):
|
||||
return self.request("POST", path, data=data, encoding=encoding, params=params)
|
||||
|
||||
Arguments:
|
||||
settings (octoprint.settings.Settings): A :class:`~octoprint.settings.Settings` instance to use
|
||||
for client configuration
|
||||
https (bool): Whether to connect via HTTPS (True) or not (False, default)
|
||||
httpuser (str or None): HTTP Basic Auth username to use. No Basic Auth will be
|
||||
used if unset.
|
||||
httppass (str or None): HTTP Basic Auth password to use. No Basic Auth will be
|
||||
used if unset.
|
||||
host (str or None): Host to connect to, overrides data from settings if set.
|
||||
port (int or None): Port to connect to, overrides data from settings if set.
|
||||
prefix (str or None): Path prefix, overrides data from settings if set.
|
||||
"""
|
||||
settings_host = settings.get(["server", "host"])
|
||||
settings_port = settings.getInt(["server", "port"])
|
||||
settings_apikey = settings.get(["api", "key"])
|
||||
def post_json(self, path, data, params=None):
|
||||
return self.post(path, data, encoding="json", params=params)
|
||||
|
||||
global apikey, baseurl
|
||||
apikey = settings_apikey
|
||||
baseurl = build_base_url(https=https,
|
||||
httpuser=httpuser,
|
||||
httppass=httppass,
|
||||
host=host or settings_host if settings_host != "0.0.0.0" else "127.0.0.1",
|
||||
port=port or settings_port,
|
||||
prefix=prefix)
|
||||
def post_command(self, path, command, additional=None):
|
||||
data = dict(command=command)
|
||||
if additional:
|
||||
data.update(additional)
|
||||
return self.post_json(path, data, params=data)
|
||||
|
||||
def prepare_request(method=None, path=None, params=None):
|
||||
url = None
|
||||
if baseurl:
|
||||
while path.startswith("/"):
|
||||
path = path[1:]
|
||||
url = baseurl + "/" + path
|
||||
return requests.Request(method=method, url=url, params=params, headers={"X-Api-Key": apikey}).prepare()
|
||||
def upload(self, path, file_path, additional=None, file_name=None, content_type=None, params=None):
|
||||
import os
|
||||
|
||||
def request(method, path, data=None, files=None, encoding=None, params=None):
|
||||
s = requests.Session()
|
||||
request = prepare_request(method, path, params=params)
|
||||
if data or files:
|
||||
if encoding == "json":
|
||||
request.prepare_body(None, None, json=data)
|
||||
else:
|
||||
request.prepare_body(data, files=files)
|
||||
response = s.send(request)
|
||||
return response
|
||||
if not os.path.isfile(file_path):
|
||||
raise ValueError("{} cannot be uploaded since it is not a file".format(file_path))
|
||||
|
||||
def get(path, params=None):
|
||||
return request("GET", path, params=params)
|
||||
if file_name is None:
|
||||
file_name = os.path.basename(file_path)
|
||||
|
||||
def post(path, data, encoding=None, params=None):
|
||||
return request("POST", path, data=data, encoding=encoding, params=params)
|
||||
with open(file_path, "rb") as fp:
|
||||
if content_type:
|
||||
files = dict(file=(file_name, fp, content_type))
|
||||
else:
|
||||
files = dict(file=(file_name, fp))
|
||||
|
||||
def post_json(path, data, params=None):
|
||||
return post(path, data, encoding="json", params=params)
|
||||
response = self.request("POST", path, data=additional, files=files, params=params)
|
||||
|
||||
def post_command(path, command, additional=None):
|
||||
data = dict(command=command)
|
||||
if additional:
|
||||
data.update(additional)
|
||||
return post_json(path, data, params=data)
|
||||
return response
|
||||
|
||||
def upload(path, file_path, additional=None, file_name=None, content_type=None, params=None):
|
||||
import os
|
||||
def delete(self, path, params=None):
|
||||
return self.request("DELETE", path, params=params)
|
||||
|
||||
if not os.path.isfile(file_path):
|
||||
raise ValueError("{} cannot be uploaded since it is not a file".format(file_path))
|
||||
def patch(self, path, data, encoding=None, params=None):
|
||||
return self.request("PATCH", path, data=data, encoding=encoding, params=params)
|
||||
|
||||
if file_name is None:
|
||||
file_name = os.path.basename(file_path)
|
||||
def put(self, path, data, encoding=None, params=None):
|
||||
return self.request("PUT", path, data=data, encoding=encoding, params=params)
|
||||
|
||||
with open(file_path, "rb") as fp:
|
||||
if content_type:
|
||||
files = dict(file=(file_name, fp, content_type))
|
||||
else:
|
||||
files = dict(file=(file_name, fp))
|
||||
def create_socket(self, **kwargs):
|
||||
import uuid
|
||||
import random
|
||||
import json
|
||||
|
||||
response = request("POST", path, data=additional, files=files, params=params)
|
||||
# creates websocket URL for SockJS according to
|
||||
# - http://sockjs.github.io/sockjs-protocol/sockjs-protocol-0.3.3.html#section-37
|
||||
# - http://sockjs.github.io/sockjs-protocol/sockjs-protocol-0.3.3.html#section-50
|
||||
url = "ws://{}/sockjs/{:0>3d}/{}/websocket".format(
|
||||
self.baseurl[self.baseurl.find("//") + 2:], # host + port + prefix, but no protocol
|
||||
random.randrange(0, stop=999), # server_id
|
||||
uuid.uuid4() # session_id
|
||||
)
|
||||
use_ssl = self.baseurl.startswith("https:")
|
||||
|
||||
return response
|
||||
on_open_cb = kwargs.get("on_open", None)
|
||||
on_heartbeat_cb = kwargs.get("on_heartbeat", None)
|
||||
on_message_cb = kwargs.get("on_message", None)
|
||||
on_close_cb = kwargs.get("on_close", None)
|
||||
on_error_cb = kwargs.get("on_error", None)
|
||||
daemon = kwargs.get("daemon", True)
|
||||
|
||||
def delete(path, params=None):
|
||||
return request("DELETE", path, params=params)
|
||||
def on_message(ws, message):
|
||||
message_type = message[0]
|
||||
|
||||
def patch(path, data, encoding=None, params=None):
|
||||
return request("PATCH", path, data=data, encoding=encoding, params=params)
|
||||
|
||||
def put(path, data, encoding=None, params=None):
|
||||
return request("PUT", path, data=data, encoding=encoding, params=params)
|
||||
|
||||
def connect_socket(**kwargs):
|
||||
import uuid
|
||||
import random
|
||||
import json
|
||||
|
||||
# creates websocket URL for SockJS according to
|
||||
# - http://sockjs.github.io/sockjs-protocol/sockjs-protocol-0.3.3.html#section-37
|
||||
# - http://sockjs.github.io/sockjs-protocol/sockjs-protocol-0.3.3.html#section-50
|
||||
url = "ws://{}/sockjs/{:0>3d}/{}/websocket".format(
|
||||
baseurl[baseurl.find("//") + 2:], # host + port + prefix, but no protocol
|
||||
random.randrange(0, stop=999), # server_id
|
||||
uuid.uuid4() # session_id
|
||||
)
|
||||
use_ssl = baseurl.startswith("https:")
|
||||
|
||||
on_open_cb = kwargs.get("on_open", None)
|
||||
on_heartbeat_cb = kwargs.get("on_heartbeat", None)
|
||||
on_message_cb = kwargs.get("on_message", None)
|
||||
on_close_cb = kwargs.get("on_close", None)
|
||||
on_error_cb = kwargs.get("on_error", None)
|
||||
daemon = kwargs.get("daemon", True)
|
||||
|
||||
def on_message(ws, message):
|
||||
message_type = message[0]
|
||||
|
||||
if message_type == "h":
|
||||
# "heartbeat" message
|
||||
if callable(on_heartbeat_cb):
|
||||
on_heartbeat_cb(ws)
|
||||
if message_type == "h":
|
||||
# "heartbeat" message
|
||||
if callable(on_heartbeat_cb):
|
||||
on_heartbeat_cb(ws)
|
||||
return
|
||||
elif message_type == "o":
|
||||
# "open" message
|
||||
return
|
||||
elif message_type == "c":
|
||||
# "close" message
|
||||
return
|
||||
elif message_type == "o":
|
||||
# "open" message
|
||||
return
|
||||
elif message_type == "c":
|
||||
# "close" message
|
||||
return
|
||||
|
||||
if not callable(on_message_cb):
|
||||
return
|
||||
if not callable(on_message_cb):
|
||||
return
|
||||
|
||||
message_body = message[1:]
|
||||
if not message_body:
|
||||
return
|
||||
message_body = message[1:]
|
||||
if not message_body:
|
||||
return
|
||||
|
||||
data = json.loads(message_body)
|
||||
data = json.loads(message_body)
|
||||
|
||||
if message_type == "m":
|
||||
data = [data,]
|
||||
if message_type == "m":
|
||||
data = [data,]
|
||||
|
||||
for d in data:
|
||||
for internal_type, internal_message in d.items():
|
||||
on_message_cb(ws, internal_type, internal_message)
|
||||
for d in data:
|
||||
for internal_type, internal_message in d.items():
|
||||
on_message_cb(ws, internal_type, internal_message)
|
||||
|
||||
def on_open(ws):
|
||||
if callable(on_open_cb):
|
||||
on_open_cb(ws)
|
||||
def on_open(ws):
|
||||
if callable(on_open_cb):
|
||||
on_open_cb(ws)
|
||||
|
||||
def on_close(ws):
|
||||
if callable(on_close_cb):
|
||||
on_close_cb(ws)
|
||||
def on_close(ws):
|
||||
if callable(on_close_cb):
|
||||
on_close_cb(ws)
|
||||
|
||||
def on_error(ws, error):
|
||||
if callable(on_error_cb):
|
||||
on_error_cb(ws, error)
|
||||
def on_error(ws, error):
|
||||
if callable(on_error_cb):
|
||||
on_error_cb(ws, error)
|
||||
|
||||
socket = SocketClient(url,
|
||||
use_ssl=use_ssl,
|
||||
daemon=daemon,
|
||||
on_open=on_open,
|
||||
on_message=on_message,
|
||||
on_close=on_close,
|
||||
on_error=on_error)
|
||||
socket.connect()
|
||||
socket = SocketClient(url,
|
||||
use_ssl=use_ssl,
|
||||
daemon=daemon,
|
||||
on_open=on_open,
|
||||
on_message=on_message,
|
||||
on_close=on_close,
|
||||
on_error=on_error)
|
||||
socket.connect()
|
||||
|
||||
return socket
|
||||
return socket
|
||||
Loaded 100 of 109 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user