Compare commits

..
Author SHA1 Message Date
Gina Häußge cf69c4500d Merge branch 'commRefactoring' into commRefactoring-commandTracking 2014-12-31 15:56:02 +01:00
Gina Häußge c7c6a08748 Merge branch 'devel' into commRefactoring 2014-12-31 15:55:37 +01:00
Gina Häußge 68e4fca347 Merge branch 'devel' into commRefactoring 2014-12-20 10:15:06 +01:00
Gina Häußge 05ac02770b WIP of command tracking and more intelligent pausing 2014-12-19 23:29:49 +01:00
Gina Häußge 25dc81a5d2 Couple more compatibility fixes to bring this up to par with devel 2014-12-19 23:20:50 +01:00
Gina Häußge 9e27744a05 Fixed some merge errors 2014-12-19 12:40:49 +01:00
Gina Häußge 77df620237 Merge branch 'devel' into commRefactoring
Conflicts:
	src/octoprint/printer/__init__.py
	src/octoprint/server/__init__.py
	src/octoprint/server/api/connection.py
	src/octoprint/util/virtual.py
2014-12-19 12:33:57 +01:00
Gina Häußge a0a6f958d9 Improved cancelling by new lock, should make it even more snappier 2014-11-13 13:08:11 +01:00
Gina Häußge 16d156b530 This should hopefully get cancelling to react a bit snappier again
TODO: figure out why sometimes writetimeouts show up
2014-11-12 17:26:41 +01:00
Gina Häußge 420226b6c0 Added command processing phase "sending" which replaces former phase "sent", which in turn was moved _after_ the command has actually been sent
This solves a deadlock which can occur if a blocking command is denied sending due to buffer restrictions. It couldn't then ever be actually sent after denied once.
2014-11-12 12:38:15 +01:00
Gina Häußge da8e72b0d6 Use a bounded semaphore for properly limiting the max count of items in the queue, also track removed items upon send_queue.clear 2014-11-12 12:35:06 +01:00
Gina Häußge ef13cbecfd Do not delete lines from the send queue upon cancel that were already prepared (got a line number) 2014-11-12 11:50:58 +01:00
Gina Häußge 5910bba30e Define G28 and G29 as blocking commands, since apparently the firmware blocks writes (even buffered ones) while those are active 2014-11-10 19:48:02 +01:00
Gina Häußge 19ba3b1f99 command might be None after hook processors are through with it 2014-11-10 16:39:20 +01:00
Gina Häußge 23bc6b8df7 Added keywords arguments to pause_print to disable toggle and only resume or pause
If the printer is paused and the method is called with only_pause=True, nothing will happen.

If the printer is printing and the method is called with only_resume=True, nothing will happen.
2014-11-10 13:11:46 +01:00
Gina Häußge 69bea0f5b0 Hooks always get the value of with_line_number, no need for a keyword argument there 2014-11-10 13:00:18 +01:00
Gina Häußge 3c53394f4b Plugin manager returned wrong data types when no plugins/hooks where found 2014-11-10 12:58:15 +01:00
Gina Häußge 8741053dfc Merge branch 'dattas-commRefactoring-hook' into commRefactoring 2014-11-10 12:33:39 +01:00
Gina Häußge 8752f70ff3 Added multiple hooks for the individual processing phases, gcode hooks now have to process the parsed command (might be unknown) 2014-11-10 12:33:24 +01:00
Gina Häußge 2b66df39b6 Merge branch 'commRefactoring-hooks' of http://github.com/dattas/OctoPrint into dattas-commRefactoring-hook 2014-11-10 12:23:36 +01:00
Gina Häußge 17bb0e693d Version resource was defined twice 2014-11-10 12:13:42 +01:00
Gina Häußge 94e5b5fdaf Virtual printer did not send repetier-style target temperature messages while heating up 2014-11-10 12:13:18 +01:00
Gina Häußge 497ec5c6b2 RepetierTextualProtocol now makes use of overriding RepRapProtocol.MESSAGE_TEMPERATURE 2014-11-10 12:12:33 +01:00
Gina Häußge eaeae8d5ec Some small refactorings
- _nack_lines, _nack_lock, _nacks_before_resend => _sent_lines, _sent_lock, _sent_before_resend
- some reordering in the message processing
- referal to MESSAGE and COMMAND instances via self.__class__ instead of RepRapProtocol => allows sub classes to override MESSAGE and COMMAND definitions
2014-11-10 12:11:45 +01:00
Gina Häußge 3a05a2653b Fixed issue where peek and pop on send_queue could act on different
entries.

After sending the sent entry is now not removed from the queue by a
pop but an explicit remove instead. Removal maintains the queue's
heap invariant.
2014-11-10 12:07:49 +01:00
Gina Häußge 0ca63017c7 Merge remote-tracking branch 'origin/commRefactoring-rxcache' into commRefactoring-rxcache 2014-11-10 09:23:56 +01:00
Gina Häußge ea3416693c Merge branch 'devel' into commRefactoring-rxcache 2014-11-10 09:22:20 +01:00
Dattas Moonchaser 6dc56af3fa Add octoprint.comm.protocol.gcode hooks 2014-11-08 14:36:57 -07:00
Gina Häußge af297c2031 Merge pull request #643 from dattas/commRefactoring-unknowncmds
commRefactoring-Unknown commands
2014-11-08 19:47:36 +01:00
Dattas Moonchaser 024cf81238 Allow gcode commands to get farther into the processing, but ensure they don't get pushed to the printer 2014-11-08 11:36:31 -07:00
Gina Häußge 9d5a500b25 Cancelling print jobs should now work again 2014-11-07 22:56:49 +01:00
Gina Häußge 4bab1975c8 Funnily enough that clear_for_send was still decremented at the wrong location 2014-11-07 14:26:40 +01:00
Gina Häußge eae4153158 Some performance optimizations
- self._clear_for_send was decremented at wrong location
- added semaphore for use in fill queue processing (max entries 20, fill queue acquires, send queue releases upon send)
- added signal of state for use in fill queue processing, no more sleep-wake-check-loops there
- CommandQueue.peek also was not synchronized

Found a couple of issue to tackle next (see TODOs)
2014-11-07 13:29:11 +01:00
Gina Häußge a92aa96623 Proper clearing of send queue on cancel and proper signaling of print job done when last command gets acknowledged 2014-11-06 18:44:40 +01:00
Gina Häußge ccf0ab3b51 Let's set the default buffer size to something that should fit most configurations
These appear to be the used rx cache sizes:

  - Marlin on AT90USB boards (e.g. Printrboard) => 63 bytes
  - Marlin anywhere else, using MarlinSerial implementation => 127 bytes
  - Repetier by default => 127 bytes
  - Repetier if EXTERNALSERIAL is defined in Configuration => 63 bytes

63 bytes should be pretty much safe in any case, user can increase that if falling into the 127 bytes group.
2014-11-06 14:32:51 +01:00
Gina Häußge 7259c1c2ef Fixed a race condition that made print jobs stall, also fixed temperature reporting and a couple other things
See #568
2014-11-06 14:22:48 +01:00
Gina Häußge d66675c672 Actually forward the protocol and transport options to the protocol and transport instances upon connect...
Yeah, I don't know why that was missing either.
2014-11-06 08:54:05 +01:00
Gina Häußge 38483b0c67 Further work on the communication layer
Write blocks on the serial interface are now handled gracefully (also the write timeout has been set to a more sane value, maybe that can be lowered more?).

I'm still observing some weird "stops" when printing the valentine dragon thingy on a Printrbot Simple, still trying to find out what's happening there exactly.
2014-11-05 15:52:31 +01:00
Gina Häußge 19de4053fe WIP: More work on the communication layer
Split command processing into "queued", "sent" and "acknowledged" events, added command acknowledgement tracking via nack_line queue, using that too for resend implementation

Problem: Deadlock when using a real printer after receiving first "ok" response to "N0 M110 S0" right at the beginning of the print.
2014-11-03 21:37:04 +01:00
Gina Häußge d0ff6d1579 Fix: it should not be possible to access/increment/decrement line numbers concurrently from different threads 2014-10-31 22:06:06 +01:00
Gina Häußge 105b68c807 Move the OK processing at the end of the message receiver for now to make temperature reporting outside of heatup work on Marlin again 2014-10-31 21:45:08 +01:00
Gina Häußge 97a6d8a15e Our transport timeout is a fairly normal thing and no reason for a warn in the log 2014-10-31 21:29:08 +01:00
Gina Häußge 26fa3df4aa Fixed line number generation outside of sending queue (and removed some left-overs) 2014-10-31 21:28:26 +01:00
Gina Häußge 9a336336d7 Removed unused method self._useChecksum 2014-10-31 19:04:12 +01:00
Gina Häußge 047d7f5046 self.disconnect had wrong signature 2014-10-31 19:02:48 +01:00
Gina Häußge 4fc561dab5 Always send checksum by default 2014-10-31 19:02:29 +01:00
Gina Häußge 785ac07de9 Removed self._ping_pong (can be done by setting self._rx_cache_size to 0) and self._rx_cache_fill (can be done by sum(self._nack_lines)), made self._rx_cache_size configurable 2014-10-31 18:51:54 +01:00
Gina Häußge 41c6978880 Changed some things refering to other things changed in devel 2014-10-31 17:59:05 +01:00
Gina Häußge f7ebc4ec11 Merge remote-tracking branch 'presslab-us/commRefactoring-rxcache' into commRefactoring-rxcache 2014-10-31 17:55:36 +01:00
Gina Häußge c06e8f47f0 Fixed queue processing of virtual printer 2014-10-31 17:54:01 +01:00
Gina Häußge dceb5dccd3 Made virtual printer a bit more "lifelike"
Added (configurable) queue for buffered G codes (G0, G1, G2, G3, G28, G29-G32), incoming queue and queue clearing upon resend

Needed for testing stuff for #568
2014-10-31 15:40:01 +01:00
Gina Häußge 7a50138ae3 Merge branch 'devel' into commRefactoring
Conflicts:
	src/octoprint/settings.py
2014-10-31 14:50:59 +01:00
Gina Häußge 43cead8249 Merge branch 'devel' into commRefactoring
Conflicts:
	src/octoprint/printer.py
	src/octoprint/server/api/files.py
2014-10-30 14:21:27 +01:00
Ryan Press 8492944fb5 Fix sign of 'nice' level. 2014-10-29 19:27:50 -07:00
Ryan Press f7433de2bf Fix temperature polling. 2014-10-26 12:51:27 -07:00
Ryan Press bbd46fd3a6 Reimplement missing events in commRefactoring. 2014-10-26 08:57:46 -07:00
Ryan Press 077486c838 Add support for rx cache to increase throughput to printer.
This can be disabled by ticking Ping-Pong in the settings.
2014-10-26 08:56:50 -07:00
Ryan Press baedab5931 Increase nice level in init script for higher priority. 2014-10-26 08:56:07 -07:00
Gina Häußge 36c8f25fd1 Honor paused state and don't eat the clear_for_send flag when not actually sending something 2014-09-17 18:15:10 +02:00
Gina Häußge b3050f1058 If command handler returns, _preprocess_command should return None not "None" 2014-09-17 17:33:58 +02:00
Gina Häußge a04a61f61b M0 command handler needs to return tuple, not just None 2014-09-17 17:23:51 +02:00
Gina Häußge 58204248bb Don't wait for "start" from printer if not configured like that 2014-09-17 17:08:35 +02:00
Gina Häußge a47740ae28 Merge branch 'devel' into commRefactoring 2014-09-15 21:55:35 +02:00
Gina Häußge 48d6a27fad Merge branch 'devel' into commRefactoring 2014-09-03 18:39:36 +02:00
Gina Häußge 5ffcd78f27 Merge remote-tracking branch 'origin/commRefactoring' into commRefactoring 2014-08-30 20:03:23 +02:00
Gina Häußge de9dd77b50 Merge branch 'devel' into commRefactoring 2014-08-30 20:02:36 +02:00
Gina Häußge 51c77be7a2 Don't overwrite query string of webcam URI
If there's a query already present, just append the timestamp to it with a & in between instead of creating a new query.
2014-08-11 22:25:09 +02:00
Gina Häußge f98563cbe9 Merge branch 'devel' into commRefactoring 2014-08-11 18:41:31 +02:00
Gina Häußge 8c8059db30 Protocol and Transport classes are now detected automatically and the one to use can be specified by config, also made standard control commands part of the protocol interface 2014-07-24 14:24:04 +02:00
Gina Häußge fa586426fa Connection handshake should now be more error resilient 2014-07-12 19:55:13 +02:00
Gina Häußge 60a1bf0d43 Merge branch 'devel' into commRefactoring
Conflicts:
	src/octoprint/printer.py
2014-07-12 19:37:38 +02:00
Gina Häußge a48f194350 Repetier protocol specifics, better virtual printer, proper handling of finished print jobs 2014-06-02 00:32:29 +02:00
Gina Häußge 78f0ec94ea SD Upload appears to be working again 2014-06-01 18:43:13 +02:00
Gina Häußge 44f9e756da Merge branch 'devel' into commRefactoring 2014-06-01 11:54:14 +02:00
Gina Häußge 3d992d56cd And even more work, trying to get the SD stuff and the offsets working again, also refactored some things here and there 2014-06-01 11:52:06 +02:00
Gina Häußge 72f7b4627f Merge branch 'devel' into commRefactoring 2014-05-30 18:38:23 +02:00
Gina Häußge 5c1f165079 Connection options, sd initialization and releasing, refactoring ... more work, off I go then 2014-05-29 22:11:11 +02:00
Gina Häußge 95755ba515 Merge branch 'devel' into commRefactoring 2014-05-29 18:01:15 +02:00
Gina Häußge 791e4e26a9 More work, print jobs at least on the virtual printer are starting to work now 2014-05-29 17:40:49 +02:00
Gina Häußge 4d61963894 Merge branch 'devel' into commRefactoring 2014-05-29 13:17:31 +02:00
Gina Häußge 5622a9c565 more work on the comm refactoring, starting to resemble something working again 2014-05-29 13:02:25 +02:00
Gina Häußge 2e5069d5a1 Merge branch 'devel' into commRefactoring 2014-05-29 10:45:30 +02:00
Gina Häußge 4cd692e061 Merge branch 'commRefactoring' of https://github.com/foosel/OctoPrint into commRefactoring
Conflicts:
	src/octoprint/printer.py
2014-05-29 10:40:04 +02:00
Gina Häußge 216a88c00c WIP 2014-05-15 15:19:48 +02:00
Gina Häußge 10f1917589 Merge branch 'devel' into commRefactoring
Conflicts:
	src/octoprint/settings.py
	src/octoprint/util/virtual.py
2014-03-15 20:39:33 +01:00
Gina Häußge 26f7d6e517 Added logging and filtering of non-ASCII filenames of files returned from SD card, still WIP 2014-02-23 11:07:09 +01:00
Gina Häußge b7b2e99ab1 Merge branch 'devel' into commRefactoring 2014-02-17 11:39:21 +01:00
Gina Häußge 0966b231e8 Some more WIP 2014-01-31 11:41:40 +01:00
Gina Häußge 00e1a1962b Started working on new modular comm layer, checking in just for the record, not yet usable 2014-01-27 13:15:15 +01:00
270 changed files with 21512 additions and 36046 deletions

No files matched your search

-21
View File
@@ -1,21 +0,0 @@
# This file is for unifying the coding style for different editors and IDEs
# editorconfig.org
root = true
[*]
end_of_line = lf
charset = utf-8
insert_final_newline = true
trim_trailing_whitespace = true
[**.py]
indent_style = tab
[src/octoprint/static/js/app/**.js]
indent_style = space
indent_size = 4
[.travis.yml]
indent_style = space
indent_size = 2
+3 -3
View File
@@ -2,8 +2,8 @@
language: python
python:
- "2.7"
- "2.7"
install:
- pip install -e .[develop]
- pip install -r requirements.txt
script:
- nosetests tests/
- nosetests
+2 -2
View File
@@ -2,7 +2,7 @@
host = https://www.transifex.com
[octoprint.messages]
file_filter = translations/<lang>/LC_MESSAGES/messages.po
source_file = translations/messages.pot
file_filter = src/octoprint/translations/<lang>/LC_MESSAGES/messages.po
source_file = src/octoprint/translations/messages.pot
source_lang = en
+40 -217
View File
@@ -1,72 +1,30 @@
# OctoPrint Changelog
## 1.2.0 (2015-06-25)
### Note for Upgraders
* The [Cura integration](https://github.com/daid/Cura) has changed in such a way that OctoPrint now calls the
[CuraEngine](https://github.com/Ultimaker/CuraEngine) directly instead of depending on the full Cura installation. See
[the wiki](https://github.com/foosel/OctoPrint/wiki/Plugin:-Cura) for instructions on how to change your setup to
accommodate the new integration.
## 1.2.0 (Unreleased)
### New Features
* OctoPrint now has a [plugin system](http://docs.octoprint.org/en/master/plugins/index.html) which allows extending its
core functionality.
* Plugins may be installed through the new and bundled [Plugin Manager Plugin](https://github.com/foosel/OctoPrint/wiki/Plugin:-Plugin-Manager)
available in OctoPrint's settings. This Plugin Manager also allows browsing and easy installation of plugins
registered on the official [OctoPrint Plugin Repository](http://plugins.octoprint.org).
* For interested developers there is a [tutorial available in the documentation](http://docs.octoprint.org/en/master/plugins/gettingstarted.html)
and also a [cookiecutter template](https://github.com/OctoPrint/cookiecutter-octoprint-plugin) to quickly bootstrap
new plugins.
* Added internationalization of UI. Translations of OctoPrint are being crowd sourced via [Transifex](https://www.transifex.com/projects/p/octoprint/).
Language Packs for both the core application as well as installed plugins can be uploaded through a new management
dialog in Settings > Appearance > Language Packs. A translation into German is included, further language packs
will soon be made available.
* Printer Profiles: Printer properties like print volume, extruder offsets etc are now managed via Printer Profiles. A
connection to a printer will always have a printer profile associated.
* File management now supports STL files as first class citizens (including UI adjustments to allow management of
uploaded STL files including removal and reslicing) and also allows folders (not yet supported by UI). STL files
can be downloaded like GCODE files.
* Slicing has been greatly improved:
* It now allows for a definition of slicing profiles to use for slicing plus overrides which can be defined per slicing
job (defining overrides is not yet part of the UI but it's on the roadmap).
* A new slicing dialog has been added which allows (re-)slicing uploaded STL files (which are now displayed in the file list
as well). The slicing profile and printer profile to use can be specified here as well as the file name to which to
slice to and the action to take after slicing has been completed (none, selecting the sliced GCODE for printing or
starting to print it directly)
* The slicing API allows positioning the model to slice on the print bed (Note: this is not yet available in the UI).
* Slicers themselves are integrated into the system via ``SlicingPlugins``.
* Bundled [Cura Plugin](https://github.com/foosel/OctoPrint/wiki/Plugin:-Cura) allows slicing through CuraEngine up
to and including 15.04. Existing Cura slicing profiles can be imported through the web interface.
The following translations are already available with more in the works:
- Dutch (nl)
- German (de)
- French (fr)
- Hebrew (he)
- Norwegian (no)
- Romanian (ro)
* New file list: Pagination is gone, no more (mobile incompatible) pop overs, instead scrollable and with instant
search
* You can now define a folder (default: `~/.octoprint/watched`) to be watched for newly added GCODE (or -- if slicing
support is enabled -- STL) files to automatically add.
* New type of API key: [App Session Keys](http://docs.octoprint.org/en/master/api/apps.html) for trusted applications
* OctoPrint now has a [plugin system](http://docs.octoprint.org/en/devel/plugins/index.html) which allows extending its
core functionality.
* New type of API key: [App Session Keys](http://docs.octoprint.org/en/devel/api/apps.html) for trusted applications
* Printer Profiles: Printer properties like print volume, extruder offsets etc are now managed via Printer Profiles. A
connection to a printer will always have a printer profile associated.
* OctoPrint now supports `action:...` commands received via debug messages (`// action:...`) from the printer. Currently supported are
- `action:pause`: Pauses the current job in OctoPrint
- `action:resume`: Resumes the current job in OctoPrint
- `action:disconnect`: Disconnects OctoPrint from the printer
Plugins can add supported commands by [hooking](http://docs.octoprint.org/en/master/plugins/hooks.html) into the
``octoprint.comm.protocol.action`` hook
* Mousing over the webcam image in the control tab enables key control mode, allowing you to quickly move the axis of your
printer with your computer's keyboard ([#610](https://github.com/foosel/OctoPrint/pull/610)):
- arrow keys: X and Y axes
- W, S / PageUp, PageDown: Z axes
- Home: Home X and Y axes
- End: Home Z axes
- 1, 2, 3, 4: change step size used (0.1, 1, 10, 100mm)
* Controls for adjusting feed and flow rate factor added to Controls ([#362](https://github.com/foosel/OctoPrint/issues/362))
* Custom controls now also support slider controls
* Custom controls now support a row layout
* Users can now define custom GCODE scripts to run upon starting/pausing/resuming/success/failure of a print or for
custom controls ([#457](https://github.com/foosel/OctoPrint/issues/457), [#347](https://github.com/foosel/OctoPrint/issues/347))
* Bundled [Discovery Plugin](https://github.com/foosel/OctoPrint/wiki/Plugin:-Discovery) allows discovery of OctoPrint
instances via SSDP/UPNP and optionally also via ZeroConf/Bonjour/Avahi.
* Bundled [Software Update Plugin](https://github.com/foosel/OctoPrint/wiki/Plugin:-Software-Update) takes care of notifying
about new OctoPrint releases and also allows updating if configured as such. Plugins may register themselves with the
update notification and application process through a new hook ["octoprint.plugin.softwareupdate.check_config"](https://github.com/foosel/OctoPrint/wiki/Plugin:-Software-Update#octoprintpluginsoftwareupdatecheck_config).
### Improvements
@@ -77,12 +35,26 @@
* Start counting the layers at 1 instead of 0 in the GCODE viewer
* Upgraded [Font Awesome](https://fortawesome.github.io/Font-Awesome/) to version 3.2.1
* Better error reporting for timelapse rendering and system commands
* Custom control can now be defined so that they show a Confirm dialog with configurable text before executing
* Custom control can now be defined so that they show a Confirm dialog with configurable text before executing
([#532](https://github.com/foosel/OctoPrint/issues/532) and [#590](https://github.com/foosel/OctoPrint/pull/590))
* Serial communication: Also interpret lines starting with "!!" as errors
* Slicing has been greatly improved:
* It now allows for a definition of slicing profiles to use for slicing plus overrides which can be defined per slicing
job (defining overrides is not yet part of the UI but it's on the roadmap).
* A new slicing dialog has been added which allows (re-)slicing uploaded STL files (which are now displayed in the file list
as well). This dialog also allows specifying which action to take after slicing has been completed (none, selecting the
sliced GCODE for printing or starting to print it directly)
* Slicers themselves are integrated into the system via ``SlicingPlugins``.
* The [Cura integration](https://github.com/daid/Cura) has changed in such a way that OctoPrint now calls the
[CuraEngine](https://github.com/Ultimaker/CuraEngine) directly instead of depending on the full Cura installation. See
[the wiki](https://github.com/foosel/OctoPrint/wiki/Plugin:-Cura) for instructions on how to change your setup to
accommodate the new integration.
* The "Slicing done" notification is now colored green ([#558](https://github.com/foosel/OctoPrint/issues/558)).
* The slicing API allows positioning the model to slice on the print bed (Note: this is not yet available in the UI).
* File management now supports STL files as first class citizens (including UI adjustments to allow management of
uploaded STL files including removal and reslicing) and also allows folders (not yet supported by UI)
* Also interpret lines starting with "!!" as errors
* Added deletion of pyc files to the `python setup.py clean` command
* Settings now show a QRCode for the API Key ([#637](https://github.com/foosel/OctoPrint/pull/637))
* Username in UI is no longer enclosed in scare quotes ([#595](https://github.com/foosel/OctoPrint/pull/595))
* Username in login dialog is not automatically capitalized on mobile devices anymore ([#639](https://github.com/foosel/OctoPrint/pull/639))
* "Slicing Done" and "Streaming Done" notifications now have a green background ([#558](https://github.com/foosel/OctoPrint/issues/558))
* Files that are currently in use, be it for slicing, printing or whatever, are now tracked and can not be deleted as
@@ -97,196 +69,49 @@
* The server now tracks the modification date of the configuration file and reloads it prior to saving the config if
it has been changed during runtime by external editing, hence no config settings added manually while the server
was running should be overwritten anymore.
* Display a "Please Reload" overlay when a new server version or a change in installed plugins is detected after a
reconnect to the server.
* Automatically hard-reload the UI if upon reconnecting to the server a new version is detected.
* Better handling of errors on the websocket - no more logging of the full stack trace to the log, only a warning
message for now.
* Daemonized OctoPrint now cleans up its pidfile when receiving a TERM signal ([#711](https://github.com/foosel/OctoPrint/issues/711))
* Added serial types for OpenBSD ([#551](https://github.com/foosel/OctoPrint/pull/551))
* Improved behaviour of terminal:
* Disabling autoscrolling now also stops cutting off the log while it's enabled, effectively preventing log lines from
being modified at all ([#735](https://github.com/foosel/OctoPrint/issues/735))
* Applying filters displays ``[...]`` where lines where removed and doesn't cause scrolling on filtered lines
anymore ([#286](https://github.com/foosel/OctoPrint/issues/286))
* Added a link to scroll to the end of the terminal log (useful for when autoscroll is disabled)
* Added a link to select all current contents of the terminal log for easy copy-pasting
* Added a display of how many lines are displayed, how many are filtered and how many are available in total
* Frame rate for timelapses can now be configured per timelapse ([#782](https://github.com/foosel/OctoPrint/pull/782))
* Added an option to specify the amount of encoding threads for FFMPEG ([#785](https://github.com/foosel/OctoPrint/pull/785))
* "Disconnected" screen now is not shown directly after a close of the socket, instead the client first tries to
directly reconnect once, and only if that doesn't work displays the dialog. Should reduce short popups of the dialog
due to shaky network connections and/or weird browser behaviour when downloading things from the UI.
* Development dependencies can now be installed with ``pip -e .[develop]``
* White and transparent colors ;) are supported for the navigation bar ([#789](https://github.com/foosel/OctoPrint/pull/789))
* Drag-n-drop overlay for file uploads now uses the full available screen space, improving usability on high resolution
displays ([#187](https://github.com/foosel/OctoPrint/issues/187))
* OctoPrint server should no longer hang when big changes in the system time happen, e.g. after first contact to an
NTP server on a Raspberry Pi image. Achieved through monkey patching Tornado with
[this PR](https://github.com/tornadoweb/tornado/pull/1290).
* Serial ports matching ``/dev/ttyAMA*`` are not anymore listed by default (this was the reason for a lot of people
running into problems while attempting to connect to their printer on their Raspberry Pis, on which ``/dev/ttyAMA0``
is the OS's serial console by default). Added configuration of additional ports to the Serial Connection section in
the Settings to make it easier for those people who do indeed have their printer connected to ``/dev/ttyAMA0``.
* Better behaviour of the settings dialog on low-width devices, navigation and content also now scroll independently
from each other (see also [#823](https://github.com/foosel/OctoPrint/pull/823))
* Renamed "Temperature Timeout" and "SD Status Timeout" in Settings to "Temperature Interval" and "SD Status Interval"
to better reflect what those values are actually used for.
* Added support for rectangular printer beds with the origin in the center ([#682](https://github.com/foosel/OctoPrint/issues/682)
and [#852](https://github.com/foosel/OctoPrint/pull/852)). Printer profiles now contain a new settings ``volume.origin``
which can either be ``lowerleft`` or ``center``. For circular beds only ``center`` is supported.
* Made baudrate detection a bit more solid, still can't perform wonders.
* Only show configuration options for additional extruders if more than one is available, and don't include offset
configuration for first nozzle which acts as reference for the other offsets ([#677](https://github.com/foosel/OctoPrint/issues/677)).
* Cut off of the temperature graph is now not based on the number of data points any more but on the actual time of the
data points. Anything older than ``n`` minutes will be cut off, with ``n`` defaulting to 30min. This value can be
changed under "Temperatures" in the Settings ([#343](https://github.com/foosel/OctoPrint/issues/343)).
* High-DPI support for the GCode viewer ([#837](https://github.com/foosel/OctoPrint/issues/837)).
* Stop websocket connections from multiplying ([#888](https://github.com/foosel/OctoPrint/pull/888)).
* New setting to rotate webcam by 90° counter clockwise ([#895](https://github.com/foosel/OctoPrint/issues/895) and
[#906](https://github.com/foosel/OctoPrint/pull/906))
* System commands now be set to a) run asynchronized by setting their `async` property to `true` and b) to ignore their
result by setting their `ignore` property to `true`.
* Various improvements of newly introduced features over the course of development:
* File management: The new implementation will migrate metadata from the old one upon first startup after upgrade from
version 1.1.x to 1.2.x. That should speed up initial startup.
* File management: GCODE Analysis backlog processing has been throttled to not take up too many resources on system
startup. Freshly uploaded files should still be analyzed at full speed.
* Plugins: SettingsPlugins may track versions of configuration format stored in `config.yaml`, including a custom
migration method getting called when a mismatch between the currently stored configuration format version and the one
reported by the plugin as current is detected.
* Plugins: Plugins may now have a folder for plugin related data whose path can be retrieved from the plugin itself
via its new method [`get_plugin_data_folder`](http://docs.octoprint.org/en/master/modules/plugin.html#octoprint.plugin.types.OctoPrintPlugin.get_plugin_data_folder).
* Plugin Manager: Don't allow plugin management actions (like installing/uninstalling or enabling/disabling) while the
printer is printing (see also unreproduced issue [#936](https://github.com/foosel/OctoPrint/issues/936)).
* Plugin Manager: More options to try to match up installed plugin packages with discovered plugins.
* Plugin Manager: Display a more friendly message if after the installation of a plugin it could not be correctly
identifier.
* Software Update: Enforce refreshing of available updates after any changes in enabled plugins.
### Bug Fixes
* [#435](https://github.com/foosel/OctoPrint/issues/435) - Always interpret negative duration (e.g. for print time left)
as 0
* [#516](https://github.com/foosel/OctoPrint/issues/516) - Also require API key even if ACL is disabled.
* [#633](https://github.com/foosel/OctoPrint/issues/633) - Correctly interpret temperature lines from multi extruder
setups under Smoothieware
* [#556](https://github.com/foosel/OctoPrint/issues/556) - Allow login of the same user from multiple browsers without
side effects
* [#612](https://github.com/foosel/OctoPrint/issues/612) - Fixed GCODE viewer in zoomed out browsers
* [#633](https://github.com/foosel/OctoPrint/issues/633) - Correctly interpret temperature lines from multi extruder
setups under Smoothieware
* [#680](https://github.com/foosel/OctoPrint/issues/680) - Don't accidentally include a newline from the MIME headers
in the parsed multipart data from file uploads
* [#709](https://github.com/foosel/OctoPrint/issues/709) - Properly initialize time estimation for SD card transfers too
* [#715](https://github.com/foosel/OctoPrint/issues/715) - Fixed an error where Event Triggers of type command caused
and exception to be raised due to a misnamed attribute in the code
* [#717](https://github.com/foosel/OctoPrint/issues/717) - Use ``shutil.move`` instead of ``os.rename`` to avoid cross
device renaming issues
* [#752](https://github.com/foosel/OctoPrint/pull/752) - Fix error in event handlers sending multiple gcode commands.
* [#780](https://github.com/foosel/OctoPrint/issues/780) - Always (re)set file position in SD files to 0 so that reprints
work correctly
* [#784](https://github.com/foosel/OctoPrint/pull/784) - Also include ``requirements.txt`` in files packed up for
``python setup.py sdist``
* [#330](https://github.com/foosel/OctoPrint/issues/330) - Ping pong sending to fix potential acknowledgement errors.
Also affects [#166](https://github.com/foosel/OctoPrint/issues/166), [#470](https://github.com/foosel/OctoPrint/issues/470)
and [#490](https://github.com/foosel/OctoPrint/issues/490). A big thank you to all people involved in these tickets
in getting to the ground of this.
* [#825](https://github.com/foosel/OctoPrint/issues/825) - Fixed "please visualize" button of large GCODE files
* Various fixes of bugs in newly introduced features and improvements:
* [#625](https://github.com/foosel/OctoPrint/pull/625) - Newly added GCODE files were not being added to the analysis
queue
* [#664](https://github.com/foosel/OctoPrint/issues/664) - Fixed jog controls again
* [#677](https://github.com/foosel/OctoPrint/issues/677) - Fixed extruder offsets not being properly editable in
printer profiles
* [#678](https://github.com/foosel/OctoPrint/issues/678) - SockJS endpoints is now referenced by relative URL
using ``url_for``, should solve any issues with IE11.
* [#683](https://github.com/foosel/OctoPrint/issues/683) - Fixed heated bed option not being properly displayed in
printer profiles
* [#685](https://github.com/foosel/OctoPrint/issues/685) - Quoted file name for Timelapse creation to not make
command hiccup on ``~`` in file name
* [#709](https://github.com/foosel/OctoPrint/issues/709) - Fixed file sending to SD card
* [#714](https://github.com/foosel/OctoPrint/issues/714) - Fixed type validation of printer profiles
* Heating up the heated bed (if present) was not properly configured in CuraEngine plugin
* [#720](https://github.com/foosel/OctoPrint/issues/720) - Fixed translation files not being properly copied over
during install
* [#724](https://github.com/foosel/OctoPrint/issues/724) - Fixed timelapse deletion for timelapses with non-ascii
characters in their name
* [#726](https://github.com/foosel/OctoPrint/issues/726) - Fixed ``babel_refresh`` command
* [#759](https://github.com/foosel/OctoPrint/pull/759) - Properly initialize counter for template plugins of type
"generic"
* [#775](https://github.com/foosel/OctoPrint/pull/775) - Error messages in javascript console show the proper name
of the objects
* [#795](https://github.com/foosel/OctoPrint/issues/795) - Allow adding slicing profiles for unconfigured slicers
* [#809](https://github.com/foosel/OctoPrint/issues/809) - Added proper form validation to printer profile editor
* [#824](https://github.com/foosel/OctoPrint/issues/824) - Settings getting lost when switching between panes in
the settings dialog (fix provided by [#879](https://github.com/foosel/OctoPrint/pull/879))
* [#892](https://github.com/foosel/OctoPrint/issues/892) - Preselected baudrate is now properly used for auto detected
serial ports
* [#909](https://github.com/foosel/OctoPrint/issues/909) - Fixed Z-Timelapse for Z changes on ``G1`` moves.
* Fixed another instance of a missing `branch` field in version dicts generated by versioneer (compare
[#634](https://github.com/foosel/OctoPrint/pull/634)). Caused an issue when installing from source archive
downloaded from Github.
* [#931](https://github.com/foosel/OctoPrint/issues/931) - Adjusted `octoprint_setuptools` to be compatible to older
versions of setuptools potentially site-wide installed on hosts.
* [#942](https://github.com/foosel/OctoPrint/issues/942) - Settings can now be saved again after installing a new
plugin. Plugins must not use `super` anymore to call parent implementation of `SettingsPlugin.on_settings_save` but
should instead switch to `SettingsPlugin.on_settings_save(self, ...)`. Settings API will capture related
`TypeErrors` and log a big warning to the log file indicating which plugin caused the problem and needs to be
updated. Also updated all bundled plugins accordingly.
* Software Update: Don't persist more check data than necessary in the configuration. Solves an issue where persisted
information overrode updated check configuration reported by plugins, leading to a "an update is available" loop.
An auto-migration function was added that should remove the redundant data.
* Various fixes without tickets:
* GCODE viewer now doesn't stumble over completely extrusionless GCODE files
* Do not deliver the API key on settings API unless user has admin rights
* Don't hiccup on slic3r filament_diameter comments in GCODE generated for multi extruder setups
* Color code successful or failed print results directly in file list, not just after a reload
* Changing Timelapse post roll activates save button
* Timelapse post roll is loaded properly from config
* Handling of files on the printer's SD card contained in folders now works correctly
* Don't display a "Disconnected" screen when trying to download a timelapse in Firefox
* Fixed handling of SD card files in folders
* Fixed refreshing of timelapse file list upon finished rendering of a new one
* Fixed ``/api/printer`` which wasn't adapter yet to new internal offset data model
* Made initial connection to printer a bit more responsive: Having to wait for the first serial timeout before sending
the first ``M105`` even when not waiting for seeing a "start" caused unnecessary wait times for reaching the
"Operational" state.
* Log cancelled prints only once (thanks to @imrahil for the headsup)
### More information
* [Commits](https://github.com/foosel/OctoPrint/compare/1.1.2...1.2.0)
* Release Candidates:
* [RC1](https://github.com/foosel/OctoPrint/releases/tag/1.2.0-rc1)
* [RC2](https://github.com/foosel/OctoPrint/releases/tag/1.2.0-rc2)
* [RC3](https://github.com/foosel/OctoPrint/releases/tag/1.2.0-rc3)
## 1.1.2 (2015-03-23)
## 1.1.2 (Unreleased)
### Improvements
* Added deletion of `*.pyc` files to `python setup.py clean` command, should help tremendously when switching branches (backported
from [9e014eb](https://github.com/foosel/OctoPrint/commit/9e014eba1feffde11ed0601d9c911b8cac9f3fb0))
* Increased default communication and connection timeouts
* [#706](https://github.com/foosel/OctoPrint/issues/706) - Do not truncate error reported from printer
### Bug Fixes
* [#539](https://github.com/foosel/OctoPrint/issues/539) - Limit maximum number of tools, sanity check tool numbers in
GCODE files against upper limit and refuse to create 10000 tools due to weird slicers. (backported from `devel`)
* [#634](https://github.com/foosel/OctoPrint/pull/634) - Fixed missing `branch` fields in version dicts generated
by versioneer
* [#679](https://github.com/foosel/OctoPrint/issues/679) - Fix error where API state is requested and printer is offline
(backport of [619fe9a](https://github.com/foosel/OctoPrint/commit/619fe9a0e78826bd1524b235a910156439bcb6d7)).
* [#719](https://github.com/foosel/OctoPrint/issues/719) - Properly center print bed in GCODE viewer
* [#780](https://github.com/foosel/OctoPrint/issues/780) - Always (re)set file position in SD files to 0 so that reprints
work correctly (backported from ``devel``)
* [#801](https://github.com/foosel/OctoPrint/issues/801) - Fixed setting of bed temperature offset
* [IRC] - Don't hiccup on slic3r ``filament_diameter`` comments generated for multi extruder setups
* [ML] - Fixed relative URL to SockJS endpoint, wasn't yet using the proper base url
* [IRC] - Don't hiccup on slic3r filament_diameter comments generated for multi extruder setups
* [ML] - Fixed relative URL to sockjs endpoint, wasn't yet using the proper base url
* [unreported] & [#698](https://github.com/foosel/OctoPrint/issues/698) - Generated URLs now take X-Forwarded-Host header
sent by proxies into account for included host and port, also fixed [#698](https://github.com/foosel/OctoPrint/issues/698)
introduced by this
* [unreported] Fixed a bug causing gcodeInterpreter to hiccup on GCODES containing invalid coordinates such as Xnan or
Yinf (backported from `devel`)
* Small fixes for timelapse creation:
- [#344](https://github.com/foosel/OctoPrint/issues/344) - Made timelapses capable of coping with missing captures in between by decrementing the image counter again if there
was an error fetching the latest image from the snapshot URL (backport of [1a7a468](https://github.com/foosel/OctoPrint/commit/1a7a468eb65fdf2a13b4c7a7723280e822c9c34b)
@@ -295,8 +120,6 @@
- [unreported] Synchronize image counter decrementing as well as incrementing to prevent rare race conditions when generating the
image file names
([Commits](https://github.com/foosel/OctoPrint/compare/1.1.1...1.1.2))
## 1.1.1 (2014-10-27)
### Improvements
@@ -319,7 +142,7 @@
### New Features
* New REST API, including User API Keys additionally to the global API key. Please note that **this will break existing
* New REST API, including User API Keys additionally to the global API key. Please note that **this will break existing
API clients** as it replaces the old API (same endpoint). You can find the documentation of the new API at
[docs.octoprint.org](http://docs.octoprint.org/en/1.1.0/api/index.html).
* New Event structure allows more flexibility regarding payload data, configuration files will be migrated automatically.
@@ -344,9 +167,9 @@
* The dimensions of the print bed can now be configured via the Settings ([#396](https://github.com/foosel/OctoPrint/pull/396))
* Target temperature reporting format of Repetier Firmware is now supported as well ([360](https://github.com/foosel/OctoPrint/issues/360))
* Version tracking now based on git tagging and [versioneer](https://github.com/warner/python-versioneer/). Version number,
git commit and branch get reported in the format `<version tag>-<commits since then>-g<commit hash> (<branch> branch)`,
git commit and branch get reported in the format `<version tag>-<commits since then>-g<commit hash> (<branch> branch)`,
e.g. `1.2.0-dev-172-ga48b5de (devel branch)`.
* Made "Center viewport on model" and "Zoom in on model" in the GCODE viewer automatically deselect and de-apply if
* Made "Center viewport on model" and "Zoom in on model" in the GCODE viewer automatically deselect and de-apply if
viewport gets manipulated by the user ([#398](https://github.com/foosel/OctoPrint/issues/398))
* GCODE viewer now interprets inverted axes for printer control and mirrors print bed accordingly ([#431](https://github.com/foosel/OctoPrint/issues/431))
* Added `clean` command to `setup.py`, removes old build artifacts (mostly interesting for developers)
@@ -365,7 +188,7 @@
* [#381](https://github.com/foosel/OctoPrint/issues/381) - Only list those SD files that have an ASCII filename
* Fixed a race condition that could occur when pressing "Print" (File not opened yet, but attempt to read from it)
* [#398](https://github.com/foosel/OctoPrint/issues/398) - Fixed interfering options in GCODE viewer
* [#399](https://github.com/foosel/OctoPrint/issues/399) & [360](https://github.com/foosel/OctoPrint/issues/360) - Leave
* [#399](https://github.com/foosel/OctoPrint/issues/399) & [360](https://github.com/foosel/OctoPrint/issues/360) - Leave
bed temperature unset when not detected (instead of dying a horrible death)
* [#492](https://github.com/foosel/OctoPrint/issues/492) - Fixed a race condition which could lead to an attempt to read
from an already closed serial port, causing an error to be displayed to the user
+10 -37
View File
@@ -1,49 +1,22 @@
Issues, Tickets, however you may call them
------------------------------------------
Read the following short instructions **fully** and **follow them** if you want your ticket to be taken care of and not closed again directly! They are linked on top of every new issue form, so don't say nobody warned you afterwards.
Read the following short instructions **fully** and **follow them** if you want your ticket to be taken care of and not closed again directly!
- **Read the [FAQ](https://github.com/foosel/OctoPrint/wiki/FAQ)**
- Always create **one ticket for one purpose**. So don't mix two or more feature requests, support requests, bugs etc into one ticket. If you do, your ticket will be closed!
- If you want to report a bug, **READ AND FOLLOW [How to file a bug report](https://github.com/foosel/OctoPrint/wiki/How-to-file-a-bug-report)!** Tickets will be automatically checked if they comply with the requirements outlined in that wiki node! Other then what's written in there (**and really EVERYTHING that is written in there!**) you don't have to do anything special with your ticket. Listen to what GitIssueBot might have to say to you!
- Always create **one ticket for one purpose**. So don't mix two or more feature requests, support requests, bugs etc into one ticket. If you do, your ticket will be treated as if only describing the first purpose, the others will be ignored!
- If you want to report a bug, **READ AND FOLLOW [How to file a bug report](https://github.com/foosel/OctoPrint/wiki/How-to-file-a-bug-report)!** Tickets will be automatically checked if they comply with the requirements outlined in that wiki node! Other then what's written in there (**and really EVERYTHING that is written in there!**) you don't have to do anything special with your ticket.
- If you want to post a **request** of any kind (feature request, documentation request, ...), **add [Request] to your issue's title!**
- If you need **support** with a problem of your installation (e.g. if you have problems getting the webcam to work) or have a general **question**, the issue tracker is not the right place. Consult the [Mailinglist](https://groups.google.com/group/octoprint) or the [Google+ Community](https://plus.google.com/communities/102771308349328485741) instead!
- If you are a developer that wants to brainstorm a pull request or possible changes to the plugin system, **add [Brainstorming] to your issue's title!** (see below).
- If you have another reason for creating a ticket that doesn't fit any of the above categories, it's something better suited for the [Mailinglist](https://groups.google.com/group/octoprint) or the [Google+ Community](https://plus.google.com/communities/102771308349328485741).
- If you need **support** with a problem of your installation (e.g. if you have problems getting the webcam to work), **add [Support] to your issue's title!**. Note that for problems like these, the [Mailinglist](https://groups.google.com/group/octoprint) or the [Google+ Community](https://plus.google.com/communities/102771308349328485741) will probably get you help faster!
- If you have a general **question**, **add [Question] to your issue's title!**. Note that for problems like these, the [Mailinglist](https://groups.google.com/group/octoprint) or the [Google+ Community](https://plus.google.com/communities/102771308349328485741) will probably get you help faster!
- If you have another reason for creating a ticket that doesn't fit any of the above categories, think hard if it might not be something better suited for the [Mailinglist](https://groups.google.com/group/octoprint) or the [Google+ Community](https://plus.google.com/communities/102771308349328485741). If you are sure it needs to be reported here, **add [Misc] to your issue's title!**
Following these guidelines (**especially EVERYTHING mentioned in ["How to file a bug report"](https://github.com/foosel/OctoPrint/wiki/How-to-file-a-bug-report)**) is necessary so the tickets stay manageable - you are not the only one with an open issue, so please respect that you have to **play by the rules** so that your problem can be taken care of. Tickets not playing by the rules **will be closed without further investigation!**.
Pull Requests
-------------
1. If you want to add a new feature to OctoPrint, **please always first consider if it wouldn't be better suited for a
plugin.** As a general rule of thumb, any feature that is only of interest to a small sub group should be moved into a
plugin. If the current plugin system doesn't allow you to implement your feature as a plugin, create a "Brainstorming"
ticket to get the discussion going how best to solve *this* in OctoPrint's plugin system - maybe that's the actual PR
you have been waiting for to contribute :)
2. If you plan to make **any large changes to the code or appearance, please open a "Brainstorming" ticket first** so that
we can determine if it's a good time for your specific pull request. It might be that I'm currently in the process of
making heavy changes to the code locations you'd target as well, or your approach doesn't fit the general "project
vision", and that would just cause unnecessary work and frustration for everyone or possibly get the PR rejected.
3. When adding code to OctoPrint, make sure you **follow the current coding style**. That means tabs instead of spaces in the
python files (yes, I know that this goes against PEP-8, I don't care) and space instead of tabs in the Javascript sources,
english language (that means code, variables, comments!), comments where necessary (tell why the code does something like
it does it, structure your code), following the general architecture. If your PR needs to make changes to the Stylesheets,
change the ``.less`` files from which the CSS is compiled. PRs that contain direct changes to the compiled
CSS will be closed.
4. **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 your tested your changes.
5. Please create all pull requests **against the `devel` branch**.
6. Create **one pull request per feature/bug fix**.
7. Create a **custom branch** for your feature/bug fix and use that as base for your pull request. Pull requests directly
against your version of `devel` will be closed.
7. In your pull request's description, **state what your pull request is doing**, 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.
1. Please create all pull requests against the `devel` branch.
2. Create **one pull request per feature/bug fix**.
3. Create a custom branch for your feature/bug fix and use that as base for your pull request. Pull requests directly against your version of `devel` will be closed.
4. In your pull request's description, state what your pull request is doing, as in, what feature does it implement, what bug does it fix.
History
-------
* 2015-01-23: More guidelines for creating pull requests, support/questions redirected to Mailinglist/G+ community
* 2015-01-27: Added another explicit link to the FAQ
-4
View File
@@ -1,8 +1,4 @@
recursive-include src/octoprint/static *
recursive-include src/octoprint/templates *
recursive-include src/octoprint/plugins *
recursive-include src/octoprint/translations *
include versioneer.py
include src/octoprint/_version.py
include README.md
include requirements.txt
+1 -3
View File
@@ -1,8 +1,6 @@
[python: src/octoprint/**.py]
[jinja2: src/octoprint/templates/**.jinja2]
[jinja2: src/octoprint/plugins/**.jinja2]
extensions=jinja2.ext.autoescape, jinja2.ext.with_, webassets.ext.jinja2.AssetsExtension
extensions=jinja2.ext.autoescape, jinja2.ext.with_
[javascript: src/octoprint/static/js/app/**.js]
[javascript: src/octoprint/plugins/**.js]
extract_messages = gettext, ngettext
-54
View File
@@ -1,54 +0,0 @@
/* override table width restrictions */
.wy-table-responsive table td, .wy-table-responsive table th {
/* !important prevents the common CSS stylesheets from
overriding this as on RTD they are loaded after this stylesheet */
white-space: normal !important;
}
.wy-table-responsive {
overflow: visible !important;
}
/* style headlink for code block captions like other headlinks */
.code-block-caption .headerlink {
display: none;
visibility: hidden;
font-size: 14px;
font-family: inherit;
font-style: normal;
font-weight: normal;
line-height: 1;
-webkit-font-smoothing: antialiased;
}
.code-block-caption:hover .headerlink {
display: inline-block;
}
.code-block-caption .headerlink:after {
visibility: visible;
content: "\f0c1";
font-family: FontAwesome;
display: inline-block;
}
/* make whitespace visualization in code listings not appear on same vertical position as dashes */
.highlight .w {
vertical-align: 10%;
}
/* make code tags non-red again */
code,
.rst-content tt {
color: #000 !important;
}
a code,
.rst-content a tt {
color: #2980B9 !important;
}
a:visited code,
.rst-content a:visited tt {
color: #9B59B6 !important;
}
+1 -24
View File
@@ -75,12 +75,6 @@ Issue a connection command
disconnect
Instructs OctoPrint to disconnect from the printer.
fake_ack
Fakes an acknowledgement message for OctoPrint in case one got lost on the serial line and the communication
with the printer since stalled. This should only be used in "emergencies" (e.g. to save prints), the reason
for the lost acknowledgement should always be properly investigated and removed instead of depending on this
"symptom solver".
**Example Connect Request**
.. sourcecode:: http
@@ -120,24 +114,7 @@ Issue a connection command
HTTP/1.1 204 No Content
**Example FakeAck Request**
.. sourcecode:: http
POST /api/connection HTTP/1.1
Host: example.com
Content-Type: application/json
X-Api-Key: abcdef...
{
"command": "fake_ack"
}
.. sourcecode:: http
HTTP/1.1 204 No Content
:json string command: The command to issue, either ``connect``, ``disconnect`` or ``fake_ack``.
:json string command: The command to issue, either ``connect`` or ``disconnect``
:json string port: ``connect`` command: The port to connect to. If left out either the existing ``portPreference``
will be used, or if that is not available OctoPrint will attempt auto detection. Must be part
of the available ports.
+39 -46
View File
@@ -216,10 +216,6 @@ Progress information
File related
============
.. todo::
Update to reflect enhanced data now available.
.. _sec-api-datamodel-files-file:
File information
@@ -237,51 +233,10 @@ File information
- 1
- String
- The name of the file
* - ``type``
- 1
- String
- Type of file. ``model`` or ``machinecode``. Or ``folder`` if it's a folder, in which case the ``children``
node will be populated
Additional properties depend on ``type``. For a ``type`` value of ``folder``, see "Folders". For any other value
see "Files".
Folders
'''''''
.. list-table::
:widths: 15 5 10 30
:header-rows: 1
* - Name
- Multiplicity
- Type
- Description
* - ``children``
- 0..*
- Array of :ref:`File information items <sec-api-datamodel-files-file>`
- Contained children for entries of type ``folder``
Files
'''''
.. list-table::
:widths: 15 5 10 30
:header-rows: 1
* - Name
- Multiplicity
- Type
- Description
* - ``hash``
- 1
- String
- MD5 hash of the file
* - ``size``
- 0..1
- Number
- The size of the file in bytes. Only available for ``local`` files or ``sdcard`` files if the printer
supports file sizes for sd card files.
- The size of the file in bytes. Only available for ``local`` files.
* - ``date``
- 0..1
- Unix timestamp
@@ -299,6 +254,10 @@ Files
- 0..1
- :ref:`GCODE analysis information <sec-api-datamodel-files-gcodeanalysis>`
- Information from the analysis of the GCODE file, if available. Left out in abridged version.
* - ``prints``
- 0..1
- :ref:`Print history <sec-api-datamodel-files-prints>`
- Information regarding prints of this file, if available. Left out in abridged version.
.. _sec-api-datamodel-files-gcodeanalysis:
@@ -331,6 +290,40 @@ GCODE analysis information
- The volume of filament used, in cm³
.. _sec-api-datamodel-files-prints:
Print history
-------------
.. list-table::
:widths: 15 5 10 30
:header-rows: 1
* - Name
- Multiplicity
- Type
- Description
* - ``failure``
- 1
- Number
- The number of failed prints on record for the file
* - ``success``
- 1
- Number
- The number of successful prints on record for the file
* - ``last``
- 0..1
- Object
- Information regarding the last print on record for the file
* - ``last.date``
- 1
- Unix timestamp
- Timestamp when this file was printed last
* - ``last.success``
- 1
- Boolean
- Whether the last print on record was a success (``true``) or not (``false``)
.. _sec-api-datamodel-files-ref:
References
+1 -4
View File
@@ -219,11 +219,8 @@ Upload file
to ``false``.
:form print: Whether to start printing the file directly after upload (``true``) or not (``false``). If set, `select`
is implicitely ``true`` as well. Optional, defaults to ``false``.
:form userdata: [Optional] An optional string that if specified will be interpreted as JSON and then saved along
with the file as metadata (metadata key ``userdata``)
:statuscode 201: No error
:statuscode 400: If no `file` is included in the request, `userdata` was provided but could not be parsed as JSON
or the request is otherwise invalid.
:statuscode 400: If no `file` is included in the request, or the request is otherwise invalid.
:statuscode 404: If `location` is neither ``local`` nor ``sdcard`` or trying to upload to SD card and SD card support
is disabled
:statuscode 409: If the upload of the file would override the file that is currently being printed or if an upload
+3 -3
View File
@@ -1,8 +1,8 @@
.. _sec-api:
########
REST API
########
#################
API Documentation
#################
.. toctree::
:maxdepth: 2
+6 -69
View File
@@ -199,13 +199,8 @@ Issue a print head command
* ``axes``: A list of axes which to home, valid values are one or more of ``x``, ``y``, ``z``.
feedrate
Changes the feedrate factor to apply to the movement's of the axes.
* ``factor``: The new factor, percentage as integer or float (percentage divided by 100) between 50 and 200%.
All of these commands except ``feedrate`` may only be sent if the printer is currently operational and not printing.
Otherwise a :http:statuscode:`409` is returned.
All of these commands may only be sent if the printer is currently operational and not printing. Otherwise a
:http:statuscode:`409` is returned.
Upon success, a status code of :http:statuscode:`204` and an empty body is returned.
@@ -251,34 +246,13 @@ Issue a print head command
HTTP/1.1 204 No Content
**Example feed rate request**
Set the feed rate factor to 105%.
.. sourcecode:: http
POST /api/printer/printhead HTTP/1.1
Host: example.com
Content-Type: application/json
X-Api-Key: abcdef...
{
"command": "feedrate",
"factor": 105
}
.. sourcecode:: http
HTTP/1.1 204 No Content
:json string command: The command to issue, either ``jog`` or ``home``.
:json number x: ``jog`` command: The amount to travel on the X axis in mm.
:json number y: ``jog`` command: The amount to travel on the Y axis in mm.
:json number z: ``jog`` command: The amount to travel on the Z axis in mm.
:json array axes: ``home`` command: The axes which to home, valid values are one or more of ``x``, ``y`` and ``z``.
:json number factor: ``feedrate`` command: The factor to apply to the feed rate, percentage between 50 and 200% as integer or float.
:statuscode 204: No error
:statuscode 400: Invalid axis specified, invalid value for travel amount for a jog command or factor for feed rate or otherwise invalid
:statuscode 400: Invalid axis specified, invalid value for travel amount for a jog command or otherwise invalid
request.
:statuscode 409: If the printer is not operational or currently printing.
@@ -314,10 +288,6 @@ Issue a tool command
* ``amount``: The amount of filament to extrude in mm. May be negative to retract.
flowrate
Changes the flow rate factor to apply to extrusion of the tool.
* ``factor``: The new factor, percentage as integer or float (percentage divided by 100) between 75 and 125%.
All of these commands may only be sent if the printer is currently operational and -- in case of ``select`` and
``extrude`` -- not printing. Otherwise a :http:statuscode:`409` is returned.
@@ -430,35 +400,14 @@ Issue a tool command
HTTP/1.1 204 No Content
**Example flow rate request**
Set the flow rate factor to 95%.
.. sourcecode:: http
POST /api/printer/tool HTTP/1.1
Host: example.com
Content-Type: application/json
X-Api-Key: abcdef...
{
"command": "flowrate",
"factor": 95
}
.. sourcecode:: http
HTTP/1.1 204 No Content
:json string command: The command to issue, either ``target``, ``offset``, ``select`` or ``extrude``.
:json object targets: ``target`` command: The target temperatures to set. Valid properties have to match the format ``tool{n}``.
:json object offsets: ``offset`` command: The offset temperature to set. Valid properties have to match the format ``tool{n}``.
:json object tool: ``select`` command: The tool to select, value has to match the format ``tool{n}``.
:json object amount: ``extrude`` command: The amount of filament to extrude from the currently selected tool.
:json number factor: ``flowrate`` command: The factor to apply to the flow rate, percentage between 75 and 125% as integer or float.
:statuscode 204: No error
:statuscode 400: If ``targets`` or ``offsets`` contains a property or ``tool`` contains a value not matching the format
``tool{n}``, the target/offset temperature, extrusion amount or flow rate factor is not a valid number or outside of
``tool{n}``, the target/offset temperature or extrusion amount is not a valid number or outside of
the supported range, or if the request is otherwise invalid.
:statuscode 409: If the printer is not operational or -- in case of ``select`` or ``extrude`` -- currently printing.
@@ -953,20 +902,8 @@ Arbitrary Command Request
* - ``command``
- 0..1
- String
- Single command to send to the printer, mutually exclusive with ``commands`` and ``script``.
- Single command to send to the printer, mutually exclusive with ``commands``.
* - ``commands``
- 0..*
- Array of String
- Multiple commands to send to the printer (in the given order), mutually exclusive with ``command`` and ``script``.
* - ``script``
- 0..*
- String
- Name of the GCODE script template to send to the printer, mutually exclusive with ``command`` and ``commands``.
* - ``parameters``
- 0..1
- Map of key value pairs
- Key value pairs of parameters to replace in sent commands/provide to the script renderer
* - ``context``
- 0..1
- Map of key value pairs
- (only if ``script`` is set) additional template variables to provide to the script renderer
- Multiple commands to send to the printer (in the given order), mutually exclusive with ``command``.
+2 -2
View File
@@ -65,7 +65,7 @@ Profile list
- :ref:`Profile <sec-api-slicing-datamodel-profile>`
- Information about a profile stored in the system.
.. _sec-api-printerprofiles-datamodel-update:
.. _sec-api-slicing-datamodel-update:
Add or update request
---------------------
@@ -84,7 +84,7 @@ Add or update request
- Information about the profile being added/updated. For adding new profiles, all fields must be populated. For updating
and existing profile, only the values to be overwritten need to be supplied.
.. _sec-api-printerprofiles-datamodel-profile:
.. _sec-api-slicing-datamodel-profile:
Profile
-------
+3 -4
View File
@@ -110,7 +110,7 @@ List Slicing Profiles of a Specific Slicer
:param slicer: The identifying key of the slicer for which to list the available profiles.
:statuscode 200: No error
:statuscode 404: If the ``slicer`` was unknown to the system or not yet configured.
:statuscode 404: If the ``slicer`` was unknown to the system.
.. _sec-api-slicing-listspecific:
@@ -155,7 +155,7 @@ Retrieve Specific Profile
:param slicer: The identifying key of the slicer for which to list the available profiles.
:param name: The identifying key of the profile to retrieve
:statuscode 200: No error
:statuscode 404: If the ``slicer`` or the profile ``key`` was unknown to the system.
:statuscode 404: If the ``slicer`` or the profile was unknown to the system.
.. _sec-api-slicing-add:
@@ -215,8 +215,7 @@ Delete Slicing Profile
.. http:delete:: /api/slicing/(string:slicer)/profiles/(string:key)
Delete the slicing profile identified by ``key`` for the slicer ``slicer``. If the profile doesn't exist, the
request will succeed anyway.
Delete the slicing profile identified by ``key`` for the slicer ``slicer``.
:param slicer: The identifying key of the slicer for which to delete the profile
:param key: The identifying key of the profile to delete
+11 -17
View File
@@ -17,7 +17,6 @@ import sys, os
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
sys.path.insert(0, os.path.abspath('../src/'))
sys.path.append(os.path.abspath('sphinxext'))
import octoprint._version
from datetime import date
@@ -28,12 +27,11 @@ year_current = date.today().year
# -- General configuration -----------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
needs_sphinx = '1.3'
#needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be extensions
# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
extensions = ['codeblockext', 'onlineinclude', 'sphinx.ext.todo', 'sphinx.ext.autodoc', 'sphinxcontrib.httpdomain',
'sphinx.ext.napoleon']
extensions = ['sphinx.ext.todo', 'sphinx.ext.autodoc', 'sphinxcontrib.httpdomain']
todo_include_todos = True
# Add any paths that contain templates here, relative to this directory.
@@ -98,7 +96,6 @@ pygments_style = 'sphinx'
# If true, keep warnings as "system message" paragraphs in the built documents.
#keep_warnings = False
numfig = True
# -- Options for HTML output ---------------------------------------------------
@@ -106,9 +103,9 @@ numfig = True
on_rtd = os.environ.get('READTHEDOCS', None) == 'True'
if not on_rtd: # only import and set the theme if we're building docs locally
import sphinx_rtd_theme
html_theme = 'sphinx_rtd_theme'
html_theme_path = [sphinx_rtd_theme.get_html_theme_path()]
import sphinx_rtd_theme
html_theme = 'sphinx_rtd_theme'
html_theme_path = [sphinx_rtd_theme.get_html_theme_path()]
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
@@ -143,9 +140,6 @@ if not on_rtd: # only import and set the theme if we're building docs locally
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
def setup(app):
app.add_stylesheet("theme_overrides.css")
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
#html_last_updated_fmt = '%b %d, %Y'
@@ -193,7 +187,7 @@ htmlhelp_basename = 'OctoPrintdoc'
# -- Options for LaTeX output --------------------------------------------------
#latex_elements = {
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#'papersize': 'letterpaper',
@@ -202,14 +196,14 @@ htmlhelp_basename = 'OctoPrintdoc'
# Additional stuff for the LaTeX preamble.
#'preamble': '',
#}
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass [howto/manual]).
#latex_documents = [
# ('index', 'OctoPrint.tex', u'OctoPrint Documentation',
# u'Gina Häußge', 'manual'),
#]
latex_documents = [
('index', 'OctoPrint.tex', u'OctoPrint Documentation',
u'Gina Häußge', 'manual'),
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
-829
View File
@@ -1,829 +0,0 @@
.. _sec-configuration-config_yaml:
config.yaml
===========
If not specified via the command line, the main configuration file ``config.yaml`` for OctoPrint is expected in its
settings folder, which unless defined differently via the command line is located at ``~/.octoprint`` on Linux, at
``%APPDATA%/OctoPrint`` on Windows and at ``~/Library/Application Support/OctoPrint`` on MacOS. If the file is not there,
you can just create it - it will only get created by OctoPrint once you save settings that deviate from the default
settings.
Note that many of these settings are available from the "Settings" menu in OctoPrint itself.
.. contents::
.. _sec-configuration-config_yaml-accesscontrol:
Access Control
--------------
Use the following settings to enable access control:
.. code-block:: yaml
accessControl:
# whether to enable access control or not. Defaults to true
enabled: true
# The user manager implementation to use for accessing user information. Currently only a filebased
# user manager is implemented which stores configured accounts in a YAML file (Default: users.yaml
# in the default configuration folder, see below)
userManager: octoprint.users.FilebasedUserManager
# The YAML user file to use. If left out defaults to users.yaml in the default configuration folder.
userFile: /path/to/users.yaml
# If set to true, will automatically log on clients originating from any of the networks defined in
# "localNetworks" as the user defined in "autologinAs". Defaults to false.
autologinLocal: true
# The name of the user to automatically log on clients originating from "localNetworks" as. Must
# be the name of one of your configured users.
autologinAs: someUser
# A list of networks or IPs for which an automatic logon as the user defined in "autologinAs" will
# take place. If available OctoPrint will evaluate the "X-Forwarded-For" HTTP header for determining
# the client's IP address (see https://code.google.com/p/haproxy-docs/wiki/forwardfor on how to
# configure the sending of this header in HAProxy). Defaults to 127.0.0.0/8 (so basically anything
# originating from localhost).
localNetworks:
- 127.0.0.0/8
- 192.168.1.0/24
.. _sec-configuration-config_yaml-api:
API
---
Settings for the REST API:
.. code-block:: yaml
api:
# Whether to enable the API
enabled: True
# Current API key needed for accessing the API
key: ...
# Whether to allow cross origin access to the API or not
allowCrossOrigin: false
# Additional app api keys, see REST API > Apps in the docs
apps:
"some.app.identifier:some_version":
pubkey: <RSA pubkey>
enabled: true
.. _sec-configuration-config_yaml-appearance:
Appearance
----------
Use the following settings to tweak OctoPrint's appearance a bit to better distinguish multiple instances/printers
appearance or to modify the order and presence of the various UI components:
.. code-block:: yaml
appearance:
# Use this to give your printer a name. It will be displayed in the title bar
# (as "<Name> [OctoPrint]") and in the navigation bar (as "OctoPrint: <Name>")
name: My Printer
# Use this to color the navigation bar. Supported colors are red, orange,
# yellow, green, blue, violet and default.
color: default
# Makes the color of the navigation bar "transparent". In case your printer uses
# acrylic for its frame ;)
colorTransparent: false
# Configures the order and availability of the UI components
components:
# Defines the order of the components within their respective containers.
#
# If overridden by the user the resulting order for display will be calculated as
# follows:
#
# - first all components as defined by the user
# - then all enabled core components as define in the default order (see below)
#
# Components not contained within the default order (e.g. from plugins) will be either
# prepended or appended to that result, depending on component type.
#
# Note that a component is not included in the order as defined by the user will still
# be put into the container, according to the default order. To fully disable a
# component, you'll need to add it to the container's disabled list further below.
order:
# order of navbar items
navbar:
- settings
- systemmenu
- login
# order of sidebar items
sidebar:
- connection
- state
- files
# order of tab items
tab:
- temperature
- control
- gcodeviewer
- terminal
- timelapse
# order of settings, if settings plugins are registered gets extended internally by
# section_plugins and all settings plugins
settings
- section_printer
- serial
- printerprofiles
- temperatures
- terminalfilters
- gcodescripts
- section_features
- features
- webcam
- accesscontrol
- api
- section_octoprint
- folders
- appearance
- logs
# order of user settings
usersettings:
- access
- interface
# order of generic templates
generic: []
# Disabled components per container. If a component is included here it will not
# be included in OctoPrint's UI at all. Note that this might mean that critical
# functionality will not be available if no replacement is registered.
disabled:
navbar: [],
sidebar: [],
tab: [],
settings: [],
usersettings: [],
generic: []
# Default language of OctoPrint. If left unset OctoPrint will try to match up available
# languages with the user's browser settings.
defaultLanguage: null
.. note::
By modifying the ``components`` > ``order`` lists you may reorder OctoPrint's UI components as you like. You can also
inject Plugins at another than their default location in their respective container by adding the entry
``plugin_<plugin identifier>`` where you want them to appear.
Example: If you want the tab of the :ref:`Hello World Plugin <sec-plugins-gettingstarted>` to appear as the first tab
in OctoPrint, you'd need to redefine ``components`` > ``order`` > ``tab`` by including something like this in your
``config.yaml``:
.. code-block:: yaml
appearance:
components:
order:
tab:
- plugin_helloworld
OctoPrint will then turn this into the order ``plugin_helloworld``, ``temperature``, ``control``, ``gcodeviewer``,
``terminal``, ``timelapse`` plus any other plugins.
.. _sec-configuration-config_yaml-controls:
Controls
--------
Use the ``controls`` section to add :ref:`custom controls <sec-features-custom_controls>` to the "Controls" tab within
OctoPrint.
.. code-block:: yaml
controls:
- name: Fan
layout: horizontal
children:
- name: Enable Fan
type: parametric_command
command: M106 S%(speed)s
input:
- name: Speed (0-255)
parameter: speed
default: 255
- name: Disable Fan
type: command
command: M107
.. _sec-configuration-config_yaml-devel:
Development settings
--------------------
The following settings are only relevant to you if you want to do OctoPrint development:
.. code-block:: yaml
# Settings only relevant for development
devel:
# Settings for OctoPrint's internal caching
cache:
# Whether to enable caching. Defaults to true. Setting it to false will cause the UI to always
# be fully rerendered on request to / on the server.
enabled: true
# Settings for stylesheet preference. OctoPrint will prefer to use the stylesheet type
# specified here. Usually (on a production install) that will be the compiled css (default).
# Developers may specify less here too.
stylesheet: css
# Settings for OctoPrint's web asset merging and minifying
webassets:
# If set to true, OctoPrint will merge all JS, all CSS and all Less files into one file per type
# to reduce request count. Setting it to false will load all assets individually. Note: if this is set to
# false, no minification will take place regardless of the minify setting below.
bundle: true
# If set to true, OctoPrint will minify its viewmodels (that includes those of plugins). Note: if bundle is
# set to false, no minification will take place either.
minify: true
# Settings for the virtual printer
virtualPrinter:
# Whether to enable the virtual printer and include it in the list of available serial connections.
# Defaults to false.
enabled: true
# Whether to send an additional "ok" after a resend request (like Repetier)
okAfterResend: false
# Whether to force checksums and line number in the communication (like Repetier), if set to true
# printer will only accept commands that come with linenumber and checksum and throw an error for
# lines that don't. Defaults to false
forceChecksum: false
# Whether to send "ok" responses with the line number that gets acknowledged by the "ok". Defaults
# to false.
okWithLinenumber: false
# Number of extruders to simulate on the virtual printer.
numExtruders: 1
# Whether to include the current tool temperature in the M105 output as separate T segment or not.
#
# True: > M105
# < ok T:23.5/0.0 T0:34.3/0.0 T1:23.5/0.0 B:43.2/0.0
# False: > M105
# < ok T0:34.3/0.0 T1:23.5/0.0 B:43.2/0.0
includeCurrentToolInTemps: true
# The maximum movement speeds of the simulated printer's axes, in mm/s
movementSpeed:
x: 6000
y: 6000
z: 200
e: 300
# Whether the simulated printer should also simulate a heated bed or not
hasBed: true
# If enabled, reports the set target temperatures as separate messages from the firmware
#
# True: > M109 S220.0
# < TargetExtr0:220.0
# < ok
# > M105
# < ok T0:34.3 T1:23.5 B:43.2
# False: > M109 S220.0
# < ok
# > M105
# < ok T0:34.3/220.0 T1:23.5/0.0 B:43.2/0.0
repetierStyleTargetTemperature: false
# If enabled, reports the first extruder in M105 responses as T instead of T0
#
# True: > M105
# < ok T:34.3/0.0 T1:23.5/0.0 B:43.2/0.0
# False: > M105
# < ok T0:34.3/0.0 T1:23.5/0.0 B:43.2/0.0
smoothieTemperatureReporting: false
# Whether M20 responses will include filesize or not
#
# True: <filename> <filesize in bytes>
# False: <filename>
extendedSdFileList: false
# Forced pause for retrieving from the outgoing buffer
throttle: 0.01
# Whether to send "wait" responses every "waitInterval" seconds when serial rx buffer is empty
sendWait: false
# Interval in which to send "wait" lines when rx buffer is empty
waitInterval: 1
# Size of the simulated RX buffer in bytes, when it's full a send from OctoPrint's
# side will block
rxBuffer: 64
# Size of
commandBuffer: 4
.. _sec-configuration-config_yaml-events:
Events
------
Use the following settings to add shell/gcode commands to be executed on certain :ref:`events <sec-events>`:
.. code-block:: yaml
events:
subscriptions:
# example event consumer that prints a message to the system log if the printer is disconnected
- event: Disconnected
command: "logger 'Printer got disconnected'"
type: system
# example event consumer that queries printer information from the firmware, prints a "Connected"
# message to the LCD and homes the print head upon established printer connection, disabled though
- event: Connected
command: M115,M117 printer connected!,G28
type: gcode
enabled: False
.. _sec-configuration-config_yaml-feature:
Feature
-------
Use the following settings to enable or disable OctoPrint features:
.. code-block:: yaml
feature:
# Whether to enable the gcode viewer in the UI or not
gCodeVisualizer: true
# Whether to enable the temperature graph in the UI or not
temperatureGraph: true
# Specifies whether OctoPrint should wait for the start response from the printer before trying to send commands
# during connect.
waitForStartOnConnect: false
# Specifies whether OctoPrint should send linenumber + checksum with every printer command. Needed for
# successful communication with Repetier firmware
alwaysSendChecksum: false
# Specifies whether OctoPrint should also send linenumber + checksum with commands that are *not*
# detected as valid GCODE (as in, they do not match the regular expression "^\s*([GM]\d+|T)").
sendChecksumWithUnknownCommands: false
# Specifies whether OctoPrint should also use up acknowledgments ("ok") for commands that are *not*
# detected as valid GCODE (as in, they do not match the regular expression "^\s*([GM]\d+|T)").
unknownCommandsNeedAck: false
# Whether to ignore the first ok after a resend response. Needed for successful communication with
# Repetier firmware
swallowOkAfterResend: false
# Specifies whether support for SD printing and file management should be enabled
sdSupport: true
# Whether to always assume that an SD card is present in the printer.
# Needed by some firmwares which don't report the SD card status properly.
sdAlwaysAvailable: false
# Whether the printer sends repetier style target temperatures in the format
# TargetExtr0:<temperature>
# instead of attaching that information to the regular M105 responses
repetierTargetTemp: false
# Whether to enable external heatup detection (to detect heatup triggered e.g. through the printer's LCD panel or
# while printing from SD) or not. Causes issues with Repetier's "first ok then response" approach to
# communication, so disable for printers running Repetier firmware.
externalHeatupDetection: true
# Whether to enable the keyboard control feature in the control tab
keyboardControl: true
.. _sec-configuration-config_yaml-folder:
Folder
------
Use the following settings to set custom paths for folders used by OctoPrint:
.. code-block:: yaml
folder:
# Absolute path where to store gcode uploads. Defaults to the uploads folder in the OctoPrint settings folder
uploads: /path/to/upload/folder
# Absolute path where to store finished timelapse recordings. Defaults to the timelapse folder in the OctoPrint
# settings dir
timelapse: /path/to/timelapse/folder
# Absolute path where to store temporary timelapse files. Defaults to the timelapse/tmp folder in the OctoPrint
# settings dir
timelapse_tmp: /path/to/timelapse/tmp/folder
# Absolute path where to store log files. Defaults to the logs folder in the OctoPrint settings dir
logs: /path/to/logs/folder
# Absolute path to the virtual printer's simulated SD card. Only useful for development, just ignore
# it otherwise
virtualSd: /path/to/virtualSd/folder
# Absolute path to a folder being watched for new files which then get automatically
# added to OctoPrint (and deleted from that folder). Can e.g. be used to define a folder which
# can then be mounted from remote machines and used as local folder for quickly adding downloaded
# and/or sliced objects to print in the future.
watched: /path/to/watched/folder
# Absolute path to a folder where manually installed plugins may reside
plugins: /path/to/plugins/folder
# Absolute path where to store slicing profiles
slicingProfiles: /path/to/slicingProfiles/folder
# Absolute path where to store printer profiles
printerProfiles: /path/to/printerProfiles/folder
# Absolute path where to store (GCODE) scripts
scripts: /path/to/scripts/folder
.. _sec-configuration-config_yaml-plugins:
Plugin settings
---------------
The ``plugins`` section is where plugins can store their specific settings. It is also where the installed but disabled
plugins are tracked:
.. code-block:: yaml
# Settings for plugins
plugins:
# Identifiers of installed but disabled plugins
_disabled:
- ...
# The rest are individual plugin settings, each tracked by their identifier, e.g.:
some_plugin:
some_setting: true
some_other_setting: false
.. _sec-configuration-config_yaml-printerprofiles:
Printer Profiles
----------------
Defaults settings for printer profiles.
.. code-block:: yaml
# Settings for printer profiles
printerProfiles:
# Name of the printer profile to default to
default: _default
# Default printer profile
defaultProfile:
...
.. _sec-configuration-config_yaml-scripts:
Scripts
-------
Default scripts and snippets. You'd usually not edit the ``config.yaml`` file to adjust those but instead create the
corresponding files in ``~/.octoprint/scripts/``. See :ref:`GCODE Script <sec-features-gcode_scripts>`.
.. code-block:: yaml
# Configured scripts
scripts:
# GCODE scripts and snippets
gcode:
# Script called after OctoPrint connected to the printer.
afterPrinterConnected:
# Script called before a print was started.
beforePrintStarted:
# Script called after a print was cancelled.
afterPrintCancelled: "; disable motors\nM84\n\n;disable all heaters\n{% snippet 'disable_hotends' %}\nM140 S0\n\n;disable fan\nM106 S0"
# Script called after a print was successfully completed.
afterPrintDone:
# Script called after a print was paused.
afterPrintPaused:
# Script called before a print was resumed.
beforePrintResumed:
# Snippets that may be used in scripts
snippets:
disable_hotends: "{% for tool in range(printer_profile.extruder.count) %}M104 T{{ tool }} S0\n{% endfor %}"
.. _sec-configuration-config_yaml-serial:
Serial
------
Use the following settings to configure the serial connection to the printer:
.. code-block:: yaml
serial:
# Use the following option to define the default serial port, defaults to unset (= AUTO)
port: /dev/ttyACM0
# Use the following option to define the default baudrate, defaults to unset (= AUTO)
baudrate: 115200
# Whether to automatically connect to the printer on server startup (if available)
autoconnect: false
# Whether to log whole communication to serial.log (warning: might decrease performance)
log: false
# Timeouts used for the serial connection to the printer, you might want to adjust these if you are
# experiencing connection problems
timeout:
# Timeout for waiting for a response from the currently tested port during autodetect, in seconds.
# Defaults to 0.5 sec
detection: 0.5
# Timeout for waiting to establish a connection with the selected port, in seconds.
# Defaults to 2 sec
connection: 2
# Timeout during serial communication, in seconds.
# Defaults to 5 sec
communication: 5
# Use this to define additional patterns to consider for serial port listing. Must be a valid
# "glob" pattern (see http://docs.python.org/2/library/glob.html). Defaults to not set.
additionalPorts:
- /dev/myPrinterSymlink
.. _sec-configuration-config_yaml-server:
Server
------
Use the following settings to configure the server:
.. code-block:: yaml
server:
# Use this option to define the host to which to bind the server, defaults to "0.0.0.0" (= all interfaces)
host: 0.0.0.0
# 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
firstRun: false
# Secret key for encrypting cookies and such, randomly generated on first run
secretKey: someSecretKey
# Settings if OctoPrint is running behind a reverse proxy (haproxy, nginx, apache, ...).
# These are necessary in order to make OctoPrint generate correct external URLs so
# that AJAX requests and download URLs work.
reverseProxy:
# The request header from which to determine the url prefix under which OctoPrint
# is served by the reverse proxy
prefixHeader: X-Script-Name
# The request header from which to determine the scheme (http or https) under which
# a specific request to OctoPrint was made to the reverse proxy
schemeHeader: X-Scheme
# The request header from which to determine the host under which OctoPrint
# is served by the reverse proxy
hostHeader: X-Forwarded-Host
# Use this option to define an optional url prefix (with a leading /, so absolute to your
# server's root) under which to run OctoPrint. This should only be needed if you want to run
# OctoPrint behind a reverse proxy under a different root endpoint than `/` and can't configure
# said reverse proxy to send a prefix HTTP header (X-Script-Name by default, see above) with
# forwarded requests.
prefixFallback:
# Use this option to define an optional forced scheme (http or https) under which to run
# OctoPrint. This should only be needed if you want to run OctoPrint behind a reverse
# proxy that also does HTTPS determination but can't configure said reverse proxy to
# send a scheme HTTP header (X-Scheme by default, see above) with forwarded requests.
schemeFallback:
# Use this option to define an optional forced host under which to run OctoPrint. This should
# only be needed if you want to run OctoPrint behind a reverse proxy with a different hostname
# than OctoPrint itself but can't configure said reverse proxy to send a host HTTP header
# (X-Forwarded-Host by default, see above) with forwarded requests.
hostFallback:
# Settings for file uploads to OctoPrint, such as maximum allowed file size and
# header suffixes to use for streaming uploads. OctoPrint does some nifty things internally in
# order to allow streaming of large file uploads to the application rather than just storing
# them in memory. For that it needs to do some rewriting of the incoming upload HTTP requests,
# storing the uploaded file to a temporary location on disk and then sending an internal request
# to the application containing the original filename and the location of the temporary file.
uploads:
# Maximum size of uploaded files in bytes, defaults to 1GB.
maxSize: 1073741824
# Suffix used for storing the filename in the file upload headers when streaming uploads.
nameSuffix: name
# Suffix used for storing the path to the temporary file in the file upload headers when
# streaming uploads.
pathSuffix: path
# Maximum size of requests other than file uploads in bytes, defaults to 100KB.
maxSize: 102400
.. note::
If you want to run OctoPrint behind a reverse proxy such as HAProxy or Nginx and use a different base URL than the
server root ``/`` you have two options to achieve this. One approach is using the configuration settings ``baseUrl`` and
``scheme`` mentioned above in which OctoPrint will only work under the configured base URL.
The second and better approach is to make your proxy send a couple of custom headers with each forwarded requests:
* ``X-Script-Name``: should contain your custom baseUrl (absolute server path), e.g. ``/octoprint``
* ``X-Scheme``: should contain your custom URL scheme to use (if different from ``http``), e.g. ``https``
If you use these headers OctoPrint will work both via the reverse proxy as well as when called directly. Take a look
`into OctoPrint's wiki <https://github.com/foosel/OctoPrint/wiki/Reverse-proxy-configuration-examples>`_ for a couple
of examples on how to configure this.
.. _sec-configuration-config_yaml-slicing:
Slicing
-------
Settings for the built-in slicing support:
.. code-block:: yaml
# Slicing settings
slicing:
# Whether to enable slicing support or not
enabled:
# Default slicer to use
defaultSlicer: cura
# Default slicing profiles per slicer
defaultProfiles:
cura: ...
.. _sec-configuration-config_yaml-system:
System
------
Use the following settings to add custom system commands to the "System" dropdown within OctoPrint's top bar.
Commands consist of a name, an action identifier, the commandline to execute and an optional confirmation message to
display before actually executing the command (should be set to False if a confirmation dialog is not desired).
The following example defines a command for shutting down the system under Linux. It assumes that the user under which
OctoPrint is running is allowed to do this without password entry:
.. code-block:: yaml
system:
actions:
- name: Shutdown
action: shutdown
command: sudo shutdown -h now
confirm: You are about to shutdown the system.
You can also add an divider by setting action to divider like this:
.. code-block:: yaml
system:
actions:
- action: divider
.. _sec-configuration-config_yaml-temperature:
Temperature
-----------
Use the following settings to configure temperature profiles which will be displayed in the temperature tab:
.. code-block:: yaml
temperature:
profiles:
- name: ABS
extruder: 210
bed: 100
- name: PLA
extruder: 180
bed: 60
.. _sec-configuration-config_yaml-terminalfilters:
Terminal Filters
----------------
Use the following settings to define a set of terminal filters to display in the terminal tab for filtering certain
lines from the display terminal log.
Use `Javascript regular expressions <https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Regular_Expressions>`_:
.. code-block:: yaml
# A list of filters to display in the terminal tab. Defaults to the filters shown below
terminalFilters:
- name: Suppress M105 requests/responses
regex: '(Send: M105)|(Recv: ok T:)'
- name: Suppress M27 requests/responses
regex: '(Send: M27)|(Recv: SD printing byte)'
.. _sec-configuration-config_yaml-webcam:
Webcam
------
Use the following settings to configure webcam support:
.. code-block:: yaml
webcam:
# Use this option to enable display of a webcam stream in the UI, e.g. via MJPG-Streamer.
# Webcam support will be disabled if not set
stream: http://<stream host>:<stream port>/?action=stream
# Use this option to enable timelapse support via snapshot, e.g. via MJPG-Streamer.
# Timelapse support will be disabled if not set
snapshot: http://<stream host>:<stream port>/?action=snapshot
# Path to ffmpeg binary to use for creating timelapse recordings.
# Timelapse support will be disabled if not set
ffmpeg: /path/to/ffmpeg
# Number of how many threads to instruct ffmpeg to use for encoding. Defaults to 1.
# Should be left at 1 for RPi1.
ffmpegThreads: 1
# The bitrate to use for rendering the timelapse video. This gets directly passed to ffmpeg.
bitrate: 5000k
# Whether to include a "created with OctoPrint" watermark in the generated timelapse movies
watermark: true
# The default timelapse settings.
timelapse:
# The timelapse type. Can be either "off", "zchange" or "timed". Defaults to "off"
type: timed
# Additional options depending on the timelapse type. All timelapses take a postRoll and an fps setting.
options:
# The number of seconds in the rendered video to add after a finished print. The exact way how the
# additional images will be recorded depends on timelapse type. Timed timelapses continue to
# record just like at the beginning, so the recording will continue another
# fps * postRoll * interval seconds. Zchange timelapses will take one final picture and add it fps * postRoll
postRoll: 0
# The framerate at which to render the movie
fps: 25
# Timed timelapses only: The interval which to leave between images in seconds
interval: 2
-12
View File
@@ -1,12 +0,0 @@
.. _sec-configuration:
#############
Configuration
#############
.. toctree::
:maxdepth: 2
yaml.rst
config_yaml.rst
logging_yaml.rst
-100
View File
@@ -1,100 +0,0 @@
.. _sec-configuration-logging_yaml:
logging.yaml
============
The logging configuration file ``logging.yaml`` for OctoPrint is expected in its settings folder, which unless defined
differently on the command line is located at ``~/.octoprint`` on Linux, at ``%APPDATA%/OctoPrint`` on Windows and at
``~/Library/Application Support/OctoPrint`` on MacOS.
You can use it to change the log levels of the individual components within OctoPrint, which might be necessary to help
in debugging issues you are experiencing, or to change the configuration of the logging handlers themselves, e.g. in
order to change size after which to rollover the ``serial.log``.
Changing log levels
-------------------
If you need to change the default logging level within OctoPrint, create the file with a text editor of your choice
(it's usually not there). The general format is this::
logger:
<component>:
level: <loglevel>
with ``<component>`` being the internal OctoPrint component for which to change the loglevel, and ``<loglevel>`` being the
new log level to set. An example for increasing the log level of the events and the file management components to
``DEBUG`` (the highest amount of logging) would be this ``logging.yaml``:
.. code-block:: yaml
logger:
octoprint.events:
level: DEBUG
octoprint.filemanager:
level: DEBUG
A list of important components for which an increase in logging might be interesting follows:
* ``octoprint.events``: the event sub system
* ``octoprint.filemanager``: the file management layer
* ``octoprint.plugin``: the plugin sub system
* ``octoprint.plugins.<plugin>``: the plugin ``<plugin>``, e.g. ``octoprint.plugins.discovery`` to change the log level of
the `Discovery plugin <https://github.com/foosel/OctoPrint/wiki/Plugin:-Discovery>`_ or ``octoprint.plugins.cura``
to change the log level of the `Cura plugin <https://github.com/foosel/OctoPrint/wiki/Plugin:-Cura>`_.
* ``octoprint.slicing``: the slicing sub system
This list will be expanded when deemed necessary.
Changing logging handlers
-------------------------
You can also change the configuration of the logging handlers themselves, e.g. in order to make the ``serial.log`` larger
for debugging long running communications or to change the behaviour of the ``octoprint.log``.
You can find the default configurations of the ``file`` handler used for the ``octoprint.log``, the ``serialFile`` handler
used for the ``serial.log`` and the ``console`` handler used for the output to stdout in YAML format below:
.. code-block:: yaml
handlers:
# stdout
console:
class: logging.StreamHandler
level: DEBUG
formatter: simple
stream: ext://sys.stdout
# octoprint.log
file:
class: logging.handlers.TimedRotatingFileHandler
level: DEBUG
formatter: simple
when: D
backupCount: 1
filename: /path/to/octoprints/logs/octoprint.log
# serial.log
serialFile:
class: logging.handlers.RotatingFileHandler
level: DEBUG
formatter: simple
maxBytes: 2097152 # 2 * 1024 * 1024 = 2 MB in bytes
filename: /path/to/octoprints/logs/serial.log
You can find more information on the used logging handlers in the
`Python documentation on logging handlers <https://docs.python.org/2/library/logging.handlers.html>`_.
Changing logging formatters
---------------------------
The logging formatters can be defined via ``logging.yaml`` as well. The ``simple`` formatter as referenced above is
expressed in YAML as follows:
.. code-block:: yaml
formatters:
simple:
format: "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
The possible keys for the logging format can be found in the
`Python documentation on LogRecord attributes <https://docs.python.org/2/library/logging.html#logrecord-attributes>`_.
-224
View File
@@ -1,224 +0,0 @@
.. _sec-configuration-yaml:
A YAML Primer
=============
Most of OctoPrint's configuration is done under the hood through `YAML <https://en.wikipedia.org/wiki/YAML>`_ files,
which is why it makes sense to shed some light on the basics of this data serialization format.
YAML is a text based format which excels at representing the most common of data structures in an easy and very human
readable way, which is why it was chosen for OctoPrint's configuration files. A text editor is all you need in order
to write YAML configuration files.
.. _sec-configuration-yaml-basic:
Basic Rules
-----------
First of all some basic things to know about working with YAML files:
* Never use tabs outside of quoted strings, especially not for indentation. The tab character is illegal within
YAML files.
* Whitespace and indentation matters and plays an important part in structuring the data, so take special care
to stay consistent here.
* YAML's comments start with a ``#`` and go until the end of the line.
.. _sec-configuration-yaml-types:
Interesting data types
----------------------
You will probably only come across the three most basic types of data within OctoPrint's YAML files: scalars
(such as strings, integers, ...), lists and associated arrays (aka key-value-pairs, aka maps, aka dictionaries).
.. _sec-configuration-yaml-types-scalar:
Scalars
.......
Scalars are the most basic of all data types and are simple string, integer, float or boolean values.
For most scalars you don't need any quotes at all, but if you need to define some piece of data which contains characters
that could be mistaken with YAML syntax you need to quote it in either double ``"`` or single ``'`` quotes for the
YAML file to stay valid. As simple rule of thumb, if your data contains any of these characters ``:-{}[]!#|>&%@`` better
quote it. Also quote it if you want a string but it could be mistaken for a valid number (integer or float) or if
it consists only of "Yes", "No", "yes", "no", "true" or "false", which would be converted to a boolean without quotes.
In double quoted strings if you need to include a literal double quote in your string you can escape it by prefixing
it with a backslash ``\`` (which you can in turn escape by itself). In single quoted strings the single quote character
can be escaped by prefixing it with another single quote, basically doubling it. Backslashes in single quoted strings
do not need to be escaped.
Quoted strings can also span across multiple lines, just indent the following lines. Note that you'll need to add a
completely empty line in order for force a line break, the data will not be actually wrapped across multiple lines
just because you spread its representation across multiple lines.
.. _sec-configuration-yaml-types-scalar-int:
int
'''
.. code-block:: yaml
23
42
.. _sec-configuration-yaml-types-scalar-float:
float
'''''
.. code-block:: yaml
23.5
100.0
.. _sec-configuration-yaml-types-scalar-boolean:
boolean
'''''''
.. code-block:: yaml
true
false
Yes
No
yes
no
.. _sec-configuration-yaml-types-scalar-string:
string
''''''
.. code-block:: yaml
a string
"some quoted string with a : colon and a { bracket and a quote \" and a backslash \\ - phew"
'some single quoted string with a single quote '' and a backslash \ - yay'
"and a multiline string - just because we can we'll make it span
across not two but four YAML lines!
Including this paragraph. But in fact it will only be two lines :)"
"23"
"42.3"
"Yes"
"No"
"true"
"false"
yes and no
true or false
.. _sec-configuration-yaml-types-lists:
Lists
.....
Lists allow to "collect" a number of similar things into one data structure. They are created by prefixing one or more
consecutive lines with a ``-``:
.. code-block:: yaml
- item 1
- 23.42
- 57
- true
Take special care to have all of your list items at the same indentation level!
.. _sec-configuration-yaml-types-dicts:
Dictionaries
............
Dictionaries (aka associative arrays aka maps) allow organizing the data in key value pairs, with the key and the value
being separated through a colon ``:``:
.. sourcecode:: yaml
key: value
anotherkey: another value
.. _sec-configuration-yaml-examples:
Examples
--------
Based on the three types explained above, quite complex data structures are possible (whitespace made visible to
help track indentation):
.. code-block-ext:: yaml
:whitespace:
general:
some_setting: some_value
a_list:
- item 1
- 23.42
- 57
- true
some_flag: true
quoted_string: "This string is quoted because {we have this here} and also > this and : that"
specific:
setting1: value1
setting2:
subsetting21: value11
subsetting22:
- subsubsetting221
- subsubsetting222
- subsubsetting223
the_end: yes
In this example we have a dictionary on the top most "layer" which has three keys, ``general``, ``specific`` and
``the_end``.
``general`` in turn is a dictionary with the keys ``some_setting`` (a string), ``a_list`` (a list with four items,
a string, a float, an int and a boolean), ``some_flag`` (a boolean) and ``quoted_string`` (a -- you guessed it -- string).
``specific`` is also a dictionary, with keys ``setting1`` (a string) and ``setting2``, a dictionary with two keys, one
a string and the other again a list.
Finally, ``the_end`` is just a boolean, since an unquoted ``yes`` evaluates as a boolean value as we saw in the
:ref:`section about boolean scalars above <sec-configuration-yaml-types-scalar-boolean>`.
Don't get confused by the list "dividing" one part of the dictionary under ``general`` from the other -- your mind is
just playing a trick on you due to the list's dashes ``-`` being on the same levels as the dictionary keys. You could
also just add two more spaces to your identation and write that part like this, which makes the structure a bit
clearer (whitespace again made visible to help track indentation):
.. code-block-ext:: yaml
:whitespace:
general:
some_setting: some_value
a_list:
- item 1
- 23.42
- 57
- true
some_flag: true
# ...
Just make sure you follow a consistent way of indenting your files -- YAML is not as strict as Python when it comes to
differing identation variants within the same file (as long as it's still valid), but consistency will help you as
a lot as a human. Ideally you'll use a text editor which highlights white space characters for you (most editors can
be configured this way), this will help tremendously when editing whitespace sensitive syntax such as YAML.
-10
View File
@@ -1,10 +0,0 @@
.. _sec-development:
###########
Development
###########
.. todo::
This is where notes regarding developing OctoPrint will be placed, such as workflow for setting up the
development environment, code guidelines etc.
+10 -14
View File
@@ -1,19 +1,16 @@
.. _sec-events:
######
Events
######
####################
Events Documentation
####################
.. contents::
.. note::
With release of OctoPrint 1.1.0, the payload data has been harmonized, it is now a key-value-map for all events.
Additionally, the format of the placeholders in both system command and gcode command triggers has been changed to
accommodate for this new format. Last but not least, the way of specifying event hooks has changed, OctoPrint no longer
separates hooks into two sections (gcodeCommandTrigger and systemCommandTrigger) but instead event hooks are now typed
to indicate what to do with the command contained.
With release of OctoPrint 1.1.0, the payload data has been harmonized, it is now a key-value-map for all events.
Additionally, the format of the placeholders in both system command and gcode command triggers has been changed to
accommodate for this new format. Last but not least, the way of specifying event hooks has changed, OctoPrint no longer
separates hooks into two sections (gcodeCommandTrigger and systemCommandTrigger) but instead event hooks are now typed
to indicate what to do with the command contained.
.. _sec-events-configuration:
@@ -59,7 +56,7 @@ Example
Placeholders
============
You can use the following generic placeholders in your event hooks:
You can use the following generic placeholders in your events:
* ``{__currentZ}``: the current Z position of the head if known, -1 if not available
* ``{__filename}``: filename of the currently selected file, "NO FILE" if not available
@@ -168,8 +165,7 @@ FileSelected
Payload:
* ``file``: the full path to the file
* ``filename``: the file's name
* ``file``: the file's name
* ``origin``: the origin of the file, either ``local`` or ``sdcard``
FileDeselected
-36
View File
@@ -1,36 +0,0 @@
.. _sec-features-action_commands:
Action Commands
===============
Action commands are a feature defined for the GCODE based RepRap communication protocol. To quote from the
`GCODE node of the RepRap wiki <http://reprap.org/wiki/Gcode#Replies_from_the_RepRap_machine_to_the_host_computer>`_:
The RepRap machine may also send lines that look like this:
**// This is some debugging or other information on a line on its own. It may be sent at any time.**
Such lines will always be preceded by //.
On the latest version of Pronterface and [...] OctoPrint a special comment of the form:
**// action:command**
is allowed to be sent from the firmware[. T]he command can currently be pause, resume or disconnect which will
execute those commands on the host. As this is also a comment other hosts will just ignored these commands.
OctoPrint out of the box supports handling of the above mentioned commands:
pause
When this command is received from the printer, OctoPrint will pause streaming of a current print job just like if the
"Pause" button had been clicked.
resume
When this command is received from the printer, OctoPrint will resume streaming of a current print job just like if
the "Resume" button had been clicked.
disconnect
When this command is Received from the printer, OctoPrint will immediately disconnect from it.
Support for additional commands may be added by plugins by implementing a handler for the
:ref:`octoprint.comm.protocol.action <sec-plugins-hook-comm-protocol-action>` hook.
-281
View File
@@ -1,281 +0,0 @@
.. _sec-features-custom_controls:
Custom Controls
===============
.. contents::
OctoPrint allows you to add custom controls to the "Control" tab of its interface. Control types reach from simple
buttons which trigger sending of one or more lines of GCODE to the printer over more complex controls allowing
parameterization of these commands with values entered by the user to full blown GCODE script templates backed by
`Jinja2 <http://jinja.pocoo.org/>`_.
Custom controls are configured within :ref:`config.yaml <sec-configuration-config_yaml>` in a ``controls`` section which
basically represents a hierarchical structure of all configured custom controls of various types.
.. note::
To make sure that your ``config.yaml`` stays valid when adding custom controls, don't hesitate to take a look at the
:ref:`YAML Primer <sec-configuration-yaml>`.
The following example defines a control for enabling the cooling fan with a variable speed defined by the user
(default 255 and selectable through a slider UI element) and a control for disabling the fan, all within a section named
"Fan", two example controls with multiple commands in a section "Example for multiple commands", a command with printer
feedback evaluation for the result of the M114 "Get Position" gcode inside a section named "Reporting" and finally
a GCODE script including user input.
.. code-block-ext:: yaml
controls:
- name: Fan
layout: horizontal
children:
- name: Enable Fan
command: M106 S%(speed)s
input:
- name: Speed (0-255)
parameter: speed
default: 255
slider:
min: 0
max: 255
- name: Disable Fan
command: M107
- name: Example for multiple commands
children:
- name: Move X (static)
confirm: You are about to move the X axis right by 10mm with 3000mm/s.
commands:
- G91
- G1 X10 F3000
- G90
- name: Move X (parametric)
commands:
- G91
- G1 X%(distance)s F%(speed)s
- G90
input:
- default: 10
name: Distance
parameter: distance
- default: 3000
name: Speed
parameter: speed
- name: Reporting
children:
- name: Get Position
command: M114
regex: "X:([0-9.]+) Y:([0-9.]+) Z:([0-9.]+) E:([0-9.]+)"
template: "Position: X={0}, Y={1}, Z={2}, E={3}"
- name: Fun stuff
children:
- name: Dance
script: custom/dance.gco
input:
- name: Go arounds
parameter: repetitions
slider:
max: 10
min: 1
step: 1
Adding this to ``config.yaml``, restarting the OctoPrint server and switching to the "Control" tab within its
interface yields the visual representation in :numref:`fig-configuration-customcontrols-example`.
.. _fig-configuration-customcontrols-example:
.. figure:: ../images/features-custom_controls-example.png
:align: center
:alt: The rendered output created through the example configuration
The rendered output created through the example configuration
As you can see you have two basic types of control definitions here: controls that actually do something (providing a
button that sends one or more commands to the printer when clicked, displaying output received from the printer) and
controls that just serve as *container* for other controls, the latter being identified by having a ``children``
attribute wrapping more controls.
.. _sec-features-custom_controls-types:
Types
-----
Let's take a closer look at the possible attributes that are available for both basic types.
.. _sec-features-custom_controls-types-containers:
Containers
..........
.. list-table::
:widths: 25 75
* - **Attribute**
- **Description**
* - ``children``
- A list of children controls or containers contained within this container
* - ``name``
- (Optional) A name to display above the container, basically a section header
* - ``layout``
- (Optional) The layout to use for laying out the contained children, either from top to bottom (``vertical``) or
from left to right (``horizontal``). Defaults to a ``vertical`` layout.
.. _sec-features-custom_controls-types-controls:
Controls
........
.. list-table::
:widths: 25 75
* - **Attribute**
- **Description**
* - ``name``
- The name of the control, will be displayed either on the button if it's a control sending a command or as a label
for controls which only display output.
* - ``command``
- (Optional) A single GCODE command to send to the printer. Will be rendered as a button which sends the command to
the printer upon click. The button text will be the value of the ``name`` attribute. Mutually exclusive with
``commands`` and ``script``. The rendered button be disabled if the printer is currently offline or printing or
alternatively if the requirements defined via the ``enabled`` attribute are not met.
* - ``commands``
- (Optional) A list of GCODE commands to send to the printer. Will be rendered as a button which sends the commands
to the printer upon click. The button text will be the value of the ``name`` attribute. Mutually exclusive with
``command`` and ``script``. The rendered button will be disabled if the printer is currently offline or printing
or alternatively if the requirements defined via the ``enabled`` attribute are not met.
* - ``script``
- (Optional) The name of a full blown :ref:`GCODE script <sec-features-gcode_scripts>` to send to the printer.
Will be rendered as a button which sends the script to the printer upon click. The button text will be the value
of the ``name`` attribute. Mutually exclusive with ``command`` and ``commands``. The rendered button will be
disabled if the printer is currently offline or printing or alternatively if the requirements defined via the
``enabled`` attribute are not met.
Values of input parameters will be available in the template context under the ``parameter`` variable (e.g.
an input parameter ``speed`` will be available in the script template as ``parameter.speed``). On top of that all
other variables defined in the :ref:`GCODE template context <sec-features-gcode_scripts-context>` will be available.
:ref:`See below for an example <sec-features-custom_controls-examples-gcode_script>`.
* - ``javascript``
- (Optional) A JavaScript snippet to be executed when the button rendered for ``command`` or ``commands`` is
clicked. This allows to override the direct sending of the command or commands to the printer with more
sophisticated behaviour. The JavaScript snippet is ``eval``'d and processed in a context where the control
it is part of is provided as local variable ``data`` and the ``ControlViewModel`` is available as ``self``.
* - ``enabled``
- (Optional) A JavaScript snippet returning either ``true`` or ``false`` determining whether the control
should be enabled or not. This allow to override the default logic for this (disabled if printer is offline
or currently printing). The JavaScript snippet is ``eval``'d and processed in a context where the control
it is part of is provided as local variable ``data`` and the ``ControlViewModel`` is available as ``self``.
* - ``input``
- (Optional) A list of definitions of input parameters for a ``command`` or ``commands``, to be rendered as
additional input fields. ``command``/``commands`` may contain placeholders to be replaced by the values obtained
from the user for the defined input fields:
.. code-block-ext:: yaml
name: Enable Fan
command: M106 S%(speed)s
input:
- name: Speed (0-255)
parameter: speed
default: 255
slider:
min: 0
max: 255
In OctoPrint's default UI input fields are always rendered left to right (inline).
* - ``input.name``
- Name to display for the input field.
* - ``input.parameter``
- Internal parameter name for the input field, used as a placeholder in ``command``/``commands``.
* - ``input.default``
- Default value for the input field.
* - ``input.slider``
- (Optional) If this attribute is included, instead of an input field a slider control will
be rendered. If you don't want to define any of ``min``, ``max`` or ``step``, write ``slider: {}`` to render
a slider based on default values.
* - ``input.slider.min``
- (Optional) Minimum value of the slider, defaults to 0.
* - ``input.slider.max``
- (Optional) Maximum value of the slider, defaults to 255.
* - ``input.slider.step``
- (Optional) Step size per slider "tick", defaults to 1.
* - ``regex``
- (Optional) A `regular expression <https://docs.python.org/2/library/re.html#regular-expression-syntax>`_ to
match against lines received from the printer to retrieve information from it (e.g. specific output). Together
with ``template`` this allows rendition of received data from the printer within the UI.
* - ``template``
- (Optional) A template to use for rendering the match of ``regex``. May contain placeholders in
`Python Format String Syntax <https://docs.python.org/2/library/string.html#format-string-syntax>`_ for either named
groups within the regex (e.g. ``Temperature: {temperature}`` for a regex ``T:\s*(?P<temperature>\d+(\.\d*)``)
or positional groups within the regex (e.g. ``Position: X={0}, Y={1}, Z={2}, E={3}`` for a regex
``X:([0-9.]+) Y:([0-9.]+) Z:([0-9.]+) E:([0-9.]+)``).
* - ``confirm``
- (Optional) A text to display to the user to confirm his button press. Can be used with sensitive custom controls
like changing EEPROM values in order to prevent accidental clicks. The text will be displayed in a confirmation
dialog like in :numref:`fig-configuration-customcontrols-confirm`.
.. _fig-configuration-customcontrols-confirm:
.. figure:: ../images/features-custom_controls-confirm.png
:align: center
:alt: An example confirmation dialog
An example confirmation dialog
.. _sec-features-custom_controls-examples:
Examples
--------
.. _sec-features-custom_controls-examples-gcode_script:
Parameterized GCODE Script
..........................
.. code-block-ext:: yaml
:caption: Control definition in ~/.octoprint/config.yaml
:name: code-features-custom_controls-example-gcode_script-config_yaml
name: Dance
script: custom/dance.gco
input:
- default: 5
name: Go arounds
parameter: repetitions
slider:
max: 10
min: 1
step: 1
.. code-block-ext:: jinja
:caption: ~/.octoprint/scripts/gcode/custom/dance.gco
:name: code-features-custom_controls-example-gcode_script-dance_gco
{% set center_x = printer_profile.volume.width / 2 %}
{% set center_y = printer_profile.volume.depth / 2 %}
{% set speed_x = printer_profile.axes.x.speed %}
{% set speed_y = printer_profile.axes.y.speed %}
{% set speed_z = printer_profile.axes.z.speed %}
M117 run {{ script.name }}
G4 P500
G1 Z10
G1 X{{ center_x }} Y{{ center_y }} F{{ speed_x }}
M117 let's dance!
G91
G1 X-1 Y-1 F{{ speed_x }}
{% for n in range(parameters.repetitions) %}
M117 and {{ n + 1 }}
{% if n % 2 == 0 %}
G1 Z1 F{{ speed_z }}
G1 Z-2 F{{ speed_z }}
G1 Z1 F{{ speed_z }}
{% endif %}
G1 X2 F{{ speed_x }}
G1 Y2 F{{ speed_y }}
G1 X-2 F{{ speed_x }}
G1 Y-2 F{{ speed_y }}
{% endfor %}
G90
G1 X{{ center_x }} Y{{ center_y }} F{{ speed_x }}
G28 X0 Y0
Note the usage of the ``parameters.repetitions`` template variable in the GCODE script template, which will contain
the value selected by the user for the "Go arounds" slider.
-110
View File
@@ -1,110 +0,0 @@
.. _sec-features-gcode_scripts:
GCODE Scripts
=============
.. contents::
OctoPrint allows you to define custom GCODE scripts to be executed on specified occasions, e.g. when a print
starts, when OctoPrint connects to a printer, or when a :ref:`button defined as a custom control <sec-features-custom_controls>`
is clicked.
Unless :ref:`configured otherwise <sec-configuration-config_yaml-folder>`, OctoPrint expects scripts to be located in
the ``scripts/gcode`` folder in OctoPrint configuration directory (per default ``~/.octoprint`` on Linux, ``%APPDATA%\OctoPrint``
on Windows and ``~/Library/Application Support/OctoPrint`` on MacOS).
These GCODE scripts are backed by the templating engine `Jinja2 <http://jinja.pocoo.org/>`_, allowing more than just
simple "send-as-is" scripts but making use of a full blown templating language in order to create your scripts. To
this end, OctoPrint injects a couple of variables into the :ref:`template rendering context <sec-features-gcode_scripts-context>`
as described below.
.. _sec-features-gcode_scripts-predefined:
Predefined Scripts
------------------
The following GCODE scripts are sent by OctoPrint automatically:
* ``afterPrinterConnected``: Sent after OctoPrint successfully connected to a printer. Defaults to an empty script.
* ``beforePrintStarted``: Sent just before a print job is started. Defaults to an empty script.
* ``afterPrintCancelled``: Sent just after a print job was cancelled. Defaults to the
:ref:`bundled script listed below <sec-features-gcode_scripts-bundled>`.
* ``afterPrintDone``: Sent just after a print job finished. Defaults to an empty script.
* ``afterPrintPaused``: Sent just after a print job was paused. Defaults to an empty script.
* ``beforePrintResumed``: Sent just before a print job is resumed. Defaults to an empty script.
.. note::
Plugins may extend these scripts through :ref:`a hook <sec-plugins-hook-comm-protocol-scripts>`.
.. _sec-features-gcode_scripts-snippets:
Snippets
--------
For making small GCODE snippets reusable in a template (e.g. for :ref:`disabling all hotends <sec-features-gcode_scripts-bundled>`)
there's an additional Jinja template command ``{% snippet '<snippet name>' %}`` available which allows including
snippets stored under ``scripts/gcode/snippets`` in OctoPrint's configuration directory. They fully support
the whole spectrum of the Jinja2 templating language (that includes including other snippets).
.. _sec-features-gcode_scripts-context:
Context
-------
All GCODE scripts have access to the following template variables through the template context:
* ``printer_profile``: The currently selected Printer Profile, including
information such as the extruder count, the build volume size, the filament diameter etc.
* ``script``: An object wrapping the script's type (``gcode``) and name (e.g. ``afterPrintCancelled``) as ``script.type``
and ``script.name`` respectively.
The :ref:`predefined GCODE scripts <sec-features-gcode_scripts-predefined>` are also called with the following additional
template variables:
* ``event``: The payload of the ``Connected``, ``PrintStarted``, ``PrintCancelled``, ``PrintDone``, ``PrintPaused`` or
``PrintResumed`` event. See :ref:`the documentation of events <sec-events-available_events>` for the contained values.
GCODE scripts attached to :ref:`custom controls <sec-features-custom_controls>` are called with the following
additional template variables:
* ``parameters``: The parameters as defined for the custom control, if it has any inputs.
* ``context``: Additional ``context`` included in the definition of the custom control.
.. _sec-features-gcode_scripts-bundled:
Bundled Scripts
---------------
Out of the box, OctoPrint defaults to the following script setup for ``afterPrintCancelled``:
.. code-block:: jinja
:caption: Default ``afterPrintCancelled`` script
; disable motors
M84
;disable all heaters
{% snippet 'disable_hotends' %}
M140 S0
;disable fan
M106 S0
The ``disable_hotends`` snippet is defined as follows:
.. code-block:: jinja
:caption: Default ``disable_hotends`` snippet
{% for tool in range(printer_profile.extruder.count) %}
M104 T{{ tool }} S0
{% endfor %}
As you can see, the ``disable_hotends`` snippet utilizes the ``printer_profile`` context variable in order to
iterate through all available extruders and set their temperature to 0.
.. seealso::
`Jinja Template Designer Documentation <http://jinja.pocoo.org/docs/dev/templates/>`_
Jinja's Template Designer Documentation describes the syntax and semantics of the template language used
also by OctoPrint's GCODE scripts.
-13
View File
@@ -1,13 +0,0 @@
.. _section-features:
********
Features
********
.. toctree::
:maxdepth: 2
custom_controls.rst
gcode_scripts.rst
action_commands.rst
plugins.rst
-70
View File
@@ -1,70 +0,0 @@
.. _sec-features-plugins:
*******
Plugins
*******
Starting with OctoPrint 1.2.0, there's now a plugin system in place which allows to individually
extend OctoPrint's functionality.
Right now plugins can be used to extend OctoPrint's web interface, to execute specific tasks on server startup and
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.
.. _sec-features-plugins-available:
Finding Plugins
===============
The official OctoPrint Plugin Repository can be found at `plugins.octoprint.org <http://plugins.octoprint.org>`_.
Some plugins may also be found in the list provided in `the OctoPrint wiki <https://github.com/foosel/OctoPrint/wiki#plugins>`_
and on the `OctoPrint organization Github page <https://github.com/OctoPrint>`_.
.. _sec-features-plugins-installing:
Installing Plugins
==================
Plugins can be installed through the bundled Plugin Manager, which allows installing plugins available in the
`OctoPrint Plugin Repository <http://plugins.octoprint.org>`_, from a web address or from an uploaded file archive.
Please refer to the documentation of the plugin for additional installations instructions.
Manual Installation
-------------------
If you don't want or can't use the Plugin Manager, plugins may also be installed manually either by copying and
unpacking them into one of the configured plugin folders (regularly those are ``<octoprint source root>/plugins`` and
``<octoprint config folder>/plugins`` [#f1]_ or by installing them as regular python modules via ``pip`` [#f2]_.
For a plugin available on the Python Package Index (PyPi), the process is as simple as issuing a
.. code-block:: bash
pip install <plugin_name>
For plugins not available on PyPi, you'll have to give ``pip`` an URL from which to install the package (e.g. the URL to
a ZIP file of the current master branch of a Github repository hosting a plugin, or even a ``git+https`` URL), example:
.. code-block:: bash
pip install https://github.com/OctoPrint/OctoPrint-Growl/archive/master.zip
See `the pip install documentation <http://pip.readthedocs.org/en/latest/reference/pip_install.html>`_ for what URL
types are possible.
.. _sec-features-plugins-developing:
Developing Plugins
==================
See :ref:`Developing Plugins <sec-plugins>`.
.. rubric:: Footnotes
.. [#f1] For Linux that will be ``~/.octoprint/plugins``, for Windows it will be ``%APPDATA%/OctoPrint/plugins`` and for
Mac ``~/Library/Application Support/OctoPrint``
.. [#f2] Make sure to use the exact same Python installation for installing the plugin that you also used for
installing & running OctoPrint. For OctoPi this means using ``~/oprint/bin/pip`` for installing plugins
instead of just ``pip``.
Binary file not shown.

Before

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 28 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 26 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 32 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 81 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 36 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.9 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 100 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 47 KiB

-309
View File
@@ -1,309 +0,0 @@
<?xml version="1.0"?>
<Document xmlns="http://www.evolus.vn/Namespace/Pencil"><Properties/><Pages><Page><Properties><Property name="name">sidebar</Property><Property name="id">1421408377849_1407</Property><Property name="width">1531</Property><Property name="height">847</Property><Property name="dimBackground"/><Property name="transparentBackground">true</Property><Property name="backgroundColor">#FFFFFFFF</Property><Property name="background">transparent</Property></Properties><Content><g xmlns="http://www.w3.org/2000/svg" p:type="Group" xmlns:p="http://www.evolus.vn/Namespace/Pencil" transform="translate(200,211.5)" id="9c37daabc3ba46d8a8d9392db9c5bfec" p:sizing-gow="533.5" p:sizing-goh="366.5"><g p:type="Shape" p:def="Evolus.Common:RoundedRect" id="db0858b72c864467b215dbf33d56f344" transform="matrix(1,0,0,1,57,-0.5)" p:sizing-ox="58" p:sizing-oy="0.5" p:sizing-ow="264" p:sizing-oh="368"><p:metadata><p:property name="box"><![CDATA[264,368]]></p:property><p:property name="withBlur"><![CDATA[false]]></p:property><p:property name="radius"><![CDATA[0,0]]></p:property><p:property name="textPadding"><![CDATA[0,46]]></p:property><p:property name="fillColor"><![CDATA[#CCCCCCFF]]></p:property><p:property name="strokeColor"><![CDATA[#000000FF]]></p:property><p:property name="strokeStyle"><![CDATA[2|]]></p:property><p:property name="textContent"><![CDATA[
]]></p:property><p:property name="textFont"><![CDATA["Liberation Sans",Arial,sans-serif|normal|normal|13px|none]]></p:property><p:property name="textColor"><![CDATA[#000000FF]]></p:property><p:property name="textAlign"><![CDATA[1,1]]></p:property></p:metadata>
<defs>
<rect width="262" height="366" rx="0" ry="0" x="0" y="0" style="stroke-width: 2; fill: rgb(204, 204, 204); fill-opacity: 1; stroke: rgb(0, 0, 0); stroke-opacity: 1;" p:name="rrRect" id="6a0c5dd8bb904291948a061be156b69a" transform="translate(1,1)"/>
<filter height="1.2558399" y="-0.12792" width="1.06396" x="-0.03198" p:name="shadingFilter" id="47e2c5b978d04acdae01fb06a59a4447">
<feGaussianBlur stdDeviation="1" in="SourceAlpha"/>
</filter>
</defs>
<use xlink:href="#6a0c5dd8bb904291948a061be156b69a" xmlns:xlink="http://www.w3.org/1999/xlink" transform="translate(2, 2)" p:filter="url(#47e2c5b978d04acdae01fb06a59a4447)" style="opacity: 0.5; visibility: hidden; display: none;" p:heavy="true" p:name="bgCopy" id="1bb1baaca7cc44c1b02cd9b42c705cc4"/>
<use xlink:href="#6a0c5dd8bb904291948a061be156b69a" xmlns:xlink="http://www.w3.org/1999/xlink"/>
<foreignObject x="46" y="184" width="172" height="0" p:name="text" id="85bd2e4e256b4cb7842522f2f03f3c81" style="font-family: &quot;Liberation Sans&quot;,Arial,sans-serif; font-size: 13px; font-weight: normal; font-style: normal; text-decoration: none; fill: rgb(0, 0, 0); fill-opacity: 1; color: rgb(0, 0, 0); opacity: 1; text-align: center;"><div xmlns="http://www.w3.org/1999/xhtml">
</div></foreignObject>
</g><g p:type="Shape" p:def="Evolus.Common:RoundedRect" id="76483818cd584af4995434fb28810ce8" transform="matrix(1,0,0,1,73,15.5)" p:sizing-ox="74" p:sizing-oy="16.5" p:sizing-ow="232" p:sizing-oh="112"><p:metadata><p:property name="box"><![CDATA[232,112]]></p:property><p:property name="withBlur"><![CDATA[false]]></p:property><p:property name="radius"><![CDATA[0,0]]></p:property><p:property name="textPadding"><![CDATA[0,14]]></p:property><p:property name="fillColor"><![CDATA[#CCCCCCFF]]></p:property><p:property name="strokeColor"><![CDATA[#000000FF]]></p:property><p:property name="strokeStyle"><![CDATA[2|]]></p:property><p:property name="textContent"><![CDATA[
]]></p:property><p:property name="textFont"><![CDATA["Liberation Sans",Arial,sans-serif|normal|normal|13px|none]]></p:property><p:property name="textColor"><![CDATA[#000000FF]]></p:property><p:property name="textAlign"><![CDATA[1,1]]></p:property></p:metadata>
<defs>
<rect width="230" height="110" rx="0" ry="0" x="0" y="0" style="stroke-width: 2; fill: rgb(204, 204, 204); fill-opacity: 1; stroke: rgb(0, 0, 0); stroke-opacity: 1;" p:name="rrRect" id="3013ddbcc4fa492995a68798edd29384" transform="translate(1,1)"/>
<filter height="1.2558399" y="-0.12792" width="1.06396" x="-0.03198" p:name="shadingFilter" id="d1e4f71d5d584c4791ec9a7c9e5be830">
<feGaussianBlur stdDeviation="1" in="SourceAlpha"/>
</filter>
</defs>
<use xlink:href="#3013ddbcc4fa492995a68798edd29384" xmlns:xlink="http://www.w3.org/1999/xlink" transform="translate(2, 2)" p:filter="url(#d1e4f71d5d584c4791ec9a7c9e5be830)" style="opacity: 0.5; visibility: hidden; display: none;" p:heavy="true" p:name="bgCopy" id="99bedd6f63d44a4a98c846ef4bec10a1"/>
<use xlink:href="#3013ddbcc4fa492995a68798edd29384" xmlns:xlink="http://www.w3.org/1999/xlink"/>
<foreignObject x="14" y="56" width="204" height="0" p:name="text" id="628f108cd2324e66b43059a0f6820ee6" style="font-family: &quot;Liberation Sans&quot;,Arial,sans-serif; font-size: 13px; font-weight: normal; font-style: normal; text-decoration: none; fill: rgb(0, 0, 0); fill-opacity: 1; color: rgb(0, 0, 0); opacity: 1; text-align: center;"><div xmlns="http://www.w3.org/1999/xhtml">
</div></foreignObject>
</g><g p:type="Shape" p:def="Evolus.Common:RoundedRect" id="cab18e5323344976a22116d09ed7f8d9" transform="matrix(1,0,0,1,73,143.5)" p:sizing-ox="74" p:sizing-oy="144.5" p:sizing-ow="232" p:sizing-oh="208"><p:metadata><p:property name="box"><![CDATA[232,208]]></p:property><p:property name="withBlur"><![CDATA[false]]></p:property><p:property name="radius"><![CDATA[0,0]]></p:property><p:property name="textPadding"><![CDATA[0,25.999999999999993]]></p:property><p:property name="fillColor"><![CDATA[#FFFFFFFF]]></p:property><p:property name="strokeColor"><![CDATA[#000000FF]]></p:property><p:property name="strokeStyle"><![CDATA[2|]]></p:property><p:property name="textContent"><![CDATA[
]]></p:property><p:property name="textFont"><![CDATA["Liberation Sans",Arial,sans-serif|normal|normal|13px|none]]></p:property><p:property name="textColor"><![CDATA[#000000FF]]></p:property><p:property name="textAlign"><![CDATA[1,1]]></p:property></p:metadata>
<defs>
<rect width="230" height="206" rx="0" ry="0" x="0" y="0" style="stroke-width: 2; fill: rgb(255, 255, 255); fill-opacity: 1; stroke: rgb(0, 0, 0); stroke-opacity: 1;" p:name="rrRect" id="81f28baf72ac469cbdebdcaeb5aeb243" transform="translate(1,1)"/>
<filter height="1.2558399" y="-0.12792" width="1.06396" x="-0.03198" p:name="shadingFilter" id="d7c2713036ee43909c0c1edc167e270b">
<feGaussianBlur stdDeviation="1" in="SourceAlpha"/>
</filter>
</defs>
<use xlink:href="#81f28baf72ac469cbdebdcaeb5aeb243" xmlns:xlink="http://www.w3.org/1999/xlink" transform="translate(2, 2)" p:filter="url(#d7c2713036ee43909c0c1edc167e270b)" style="opacity: 0.5; visibility: hidden; display: none;" p:heavy="true" p:name="bgCopy" id="825e8e4a336247cba2f89994b72de93e"/>
<use xlink:href="#81f28baf72ac469cbdebdcaeb5aeb243" xmlns:xlink="http://www.w3.org/1999/xlink"/>
<foreignObject x="26" y="104" width="180" height="0" p:name="text" id="5da32f0eb5b64ebc8ed60f5ad52e1693" style="font-family: &quot;Liberation Sans&quot;,Arial,sans-serif; font-size: 13px; font-weight: normal; font-style: normal; text-decoration: none; fill: rgb(0, 0, 0); fill-opacity: 1; color: rgb(0, 0, 0); opacity: 1; text-align: center;"><div xmlns="http://www.w3.org/1999/xhtml">
</div></foreignObject>
</g><g p:type="Shape" p:def="Evolus.Common:RoundedRect" id="5bb69b63f17c4b90bab26e055b40809d" transform="matrix(1,0,0,1,88,52.5)" p:sizing-ox="89" p:sizing-oy="53.5" p:sizing-ow="200" p:sizing-oh="56"><p:metadata><p:property name="box"><![CDATA[200,56]]></p:property><p:property name="withBlur"><![CDATA[false]]></p:property><p:property name="radius"><![CDATA[0,0]]></p:property><p:property name="textPadding"><![CDATA[0,7]]></p:property><p:property name="fillColor"><![CDATA[#FFFFFFFF]]></p:property><p:property name="strokeColor"><![CDATA[#000000FF]]></p:property><p:property name="strokeStyle"><![CDATA[2|5,5]]></p:property><p:property name="textContent"><![CDATA[
]]></p:property><p:property name="textFont"><![CDATA["Liberation Sans",Arial,sans-serif|normal|normal|13px|none]]></p:property><p:property name="textColor"><![CDATA[#000000FF]]></p:property><p:property name="textAlign"><![CDATA[1,1]]></p:property></p:metadata>
<defs>
<rect width="198" height="54" rx="0" ry="0" x="0" y="0" style="stroke-width: 2; fill: rgb(255, 255, 255); fill-opacity: 1; stroke: rgb(0, 0, 0); stroke-opacity: 1; stroke-dasharray: 5, 5;" p:name="rrRect" id="50d1edd378e8475a976ee62cc51e187a" transform="translate(1,1)"/>
<filter height="1.2558399" y="-0.12792" width="1.06396" x="-0.03198" p:name="shadingFilter" id="646abf607f094b84b088ebb2615c88cd">
<feGaussianBlur stdDeviation="1" in="SourceAlpha"/>
</filter>
</defs>
<use xlink:href="#50d1edd378e8475a976ee62cc51e187a" xmlns:xlink="http://www.w3.org/1999/xlink" transform="translate(2, 2)" p:filter="url(#646abf607f094b84b088ebb2615c88cd)" style="opacity: 0.5; visibility: hidden; display: none;" p:heavy="true" p:name="bgCopy" id="ebb65993472448b0827d87c3a3b09450"/>
<use xlink:href="#50d1edd378e8475a976ee62cc51e187a" xmlns:xlink="http://www.w3.org/1999/xlink"/>
<foreignObject x="7" y="28" width="186" height="0" p:name="text" id="1ebe6438f1de49eaab62aa0ac42a63dd" style="font-family: &quot;Liberation Sans&quot;,Arial,sans-serif; font-size: 13px; font-weight: normal; font-style: normal; text-decoration: none; fill: rgb(0, 0, 0); fill-opacity: 1; color: rgb(0, 0, 0); opacity: 1; text-align: center;"><div xmlns="http://www.w3.org/1999/xhtml">
</div></foreignObject>
</g><g p:type="Shape" p:def="Evolus.Common:PlainTextV2" id="253be0b8bade43249b1d0373589b4bde" transform="matrix(1,0,0,1,118,43.5)" p:sizing-ox="117.859375" p:sizing-oy="21.5" p:sizing-ow="79.7890625" p:sizing-oh="28"><p:metadata><p:property name="disabled"><![CDATA[false]]></p:property><p:property name="width"><![CDATA[100,0]]></p:property><p:property name="fixedWidth"><![CDATA[false]]></p:property><p:property name="label"><![CDATA[<name>]]></p:property><p:property name="textColor"><![CDATA[#000000FF]]></p:property><p:property name="textFont"><![CDATA[Open Sans|bold|normal|20px|none]]></p:property><p:property name="textAlign"><![CDATA[0,0]]></p:property></p:metadata>
<rect x="0" y="0" style="fill: none; stroke: none; visibility: hidden; display: none;" p:name="bgRect" id="a00b6941683d4803957395e5c0b93fc5" width="0" height="0"/>
<text xml:space="preserve" p:name="text" id="907a2badd36140fa9e10760dbe67b52d" style="fill: rgb(0, 0, 0); fill-opacity: 1; font-family: Open Sans; font-size: 20px; font-weight: bold; font-style: normal; text-decoration: none;"><tspan x="0" y="0">&lt;name&gt;</tspan></text>
</g><g p:type="Shape" p:def="Evolus.Common:Balloon" id="a7b1d219b2e04f00946f8ad6fb892a70" transform="matrix(1,0,0,1,333,186.5)" p:sizing-ox="305.5" p:sizing-oy="187" p:sizing-ow="200" p:sizing-oh="80"><p:metadata><p:property name="box"><![CDATA[200,80]]></p:property><p:property name="withBlur"><![CDATA[false]]></p:property><p:property name="radius"><![CDATA[8,0]]></p:property><p:property name="leftStart"><![CDATA[0,12]]></p:property><p:property name="leftEnd"><![CDATA[0,33]]></p:property><p:property name="rightStart"><![CDATA[200,12]]></p:property><p:property name="rightEnd"><![CDATA[200,33]]></p:property><p:property name="topStart"><![CDATA[12,0]]></p:property><p:property name="topEnd"><![CDATA[33,0]]></p:property><p:property name="bottomStart"><![CDATA[12,80]]></p:property><p:property name="bottomEnd"><![CDATA[33,80]]></p:property><p:property name="pin"><![CDATA[-28,23]]></p:property><p:property name="fillColor"><![CDATA[#FFFFFFFF]]></p:property><p:property name="strokeColor"><![CDATA[#1B3280FF]]></p:property><p:property name="strokeStyle"><![CDATA[2|]]></p:property><p:property name="textContent"><![CDATA[<span style="font-family: Consolas;">styles_content / styles<br />classes_content / classes</span><br />]]></p:property><p:property name="textFont"><![CDATA["Liberation Sans",Arial,sans-serif|normal|normal|13px|none]]></p:property><p:property name="textColor"><![CDATA[#000000FF]]></p:property><p:property name="textAlign"><![CDATA[1,1]]></p:property></p:metadata>
<defs>
<filter height="1.2558399" y="-0.12792" width="1.06396" x="-0.03198" p:name="imageShading" id="d1b2e26143ba4dc9b5011127eaf859fa">
<feGaussianBlur stdDeviation="1.3325" in="SourceAlpha"/>
</filter>
<g p:name="container" id="1d983e33baff4b5db9814e8bc44d5ff2">
<path transform="translate(0.5 0.5)" style="stroke-width: 2; fill: rgb(255, 255, 255); fill-opacity: 1; stroke: rgb(27, 50, 128); stroke-opacity: 1;" p:name="rect" id="9d05a5c681eb4e8690d7092cfde36dd4" d="M 8 0 L 192 0 C 197.33333333333334 0 200 2.6666666666666665 200 8 L 200 72 C 200 77.33333333333333 197.33333333333334 80 192 80 L 8 80 C 2.6666666666666665 80 0 77.33333333333333 0 72 L 0 33 L -28 23 L 0 12 L 0 8 C 0 2.6666666666666665 2.6666666666666665 0 8 0"/>
</g>
</defs>
<use xlink:href="#1d983e33baff4b5db9814e8bc44d5ff2" xmlns:xlink="http://www.w3.org/1999/xlink" transform="translate(1, 1)" p:filter="url(#d1b2e26143ba4dc9b5011127eaf859fa)" style="opacity: 0.6; visibility: hidden; display: none;" p:heavy="true" p:name="bgCopy" id="0a8c818f34d64855927948dca5fdd21e"/>
<use xlink:href="#1d983e33baff4b5db9814e8bc44d5ff2" xmlns:xlink="http://www.w3.org/1999/xlink"/>
<foreignObject x="8" y="24" width="184" height="33" p:name="text" id="4edecb8e11ca486cad7e10fecaff8778" style="font-family: &quot;Liberation Sans&quot;,Arial,sans-serif; font-size: 13px; font-weight: normal; font-style: normal; text-decoration: none; fill: rgb(0, 0, 0); fill-opacity: 1; color: rgb(0, 0, 0); opacity: 1; text-align: center;"><div xmlns="http://www.w3.org/1999/xhtml"><span style="font-family: Consolas;">styles_content / styles<br />classes_content / classes</span><br /></div></foreignObject>
</g><g p:type="Shape" p:def="Evolus.Common:Balloon" id="c736be040cc84947b5eb28896b2f18b0" transform="matrix(1,0,0,1,333,-0.5)" p:sizing-ox="321.5" p:sizing-oy="0" p:sizing-ow="200" p:sizing-oh="94"><p:metadata><p:property name="box"><![CDATA[200,94]]></p:property><p:property name="withBlur"><![CDATA[false]]></p:property><p:property name="radius"><![CDATA[8,0]]></p:property><p:property name="leftStart"><![CDATA[0,14.100000000000001]]></p:property><p:property name="leftEnd"><![CDATA[0,38.775]]></p:property><p:property name="rightStart"><![CDATA[200,14.100000000000001]]></p:property><p:property name="rightEnd"><![CDATA[200,38.775]]></p:property><p:property name="topStart"><![CDATA[12,0]]></p:property><p:property name="topEnd"><![CDATA[33,0]]></p:property><p:property name="bottomStart"><![CDATA[12,94]]></p:property><p:property name="bottomEnd"><![CDATA[33,94]]></p:property><p:property name="pin"><![CDATA[-12,27.025000000000002]]></p:property><p:property name="fillColor"><![CDATA[#FFFFFFFF]]></p:property><p:property name="strokeColor"><![CDATA[#1B3280FF]]></p:property><p:property name="strokeStyle"><![CDATA[2|]]></p:property><p:property name="textContent"><![CDATA[<span style="font-family: Consolas;">data_bind<br />styles_wrapper / styles<br />classes_wrapper / classes<br /></span>]]></p:property><p:property name="textFont"><![CDATA["Liberation Sans",Arial,sans-serif|normal|normal|13px|none]]></p:property><p:property name="textColor"><![CDATA[#000000FF]]></p:property><p:property name="textAlign"><![CDATA[1,1]]></p:property></p:metadata>
<defs>
<filter height="1.2558399" y="-0.12792" width="1.06396" x="-0.03198" p:name="imageShading" id="da71a006d4af4ce6b8f0dc6b1763b086">
<feGaussianBlur stdDeviation="1.3325" in="SourceAlpha"/>
</filter>
<g p:name="container" id="9352a73150934cfd986e88ce1ab4a93e">
<path transform="translate(0.5 0.5)" style="stroke-width: 2; fill: rgb(255, 255, 255); fill-opacity: 1; stroke: rgb(27, 50, 128); stroke-opacity: 1;" p:name="rect" id="1d692ff756b24c2aafa9c15372494c5d" d="M 8 0 L 192 0 C 197.33333333333334 0 200 2.6666666666666665 200 8 L 200 86 C 200 91.33333333333333 197.33333333333334 94 192 94 L 8 94 C 2.6666666666666665 94 0 91.33333333333333 0 86 L 0 38.775 L -12 27.025000000000002 L 0 14.100000000000001 L 0 8 C 0 2.6666666666666665 2.6666666666666665 0 8 0"/>
</g>
</defs>
<use xlink:href="#9352a73150934cfd986e88ce1ab4a93e" xmlns:xlink="http://www.w3.org/1999/xlink" transform="translate(1, 1)" p:filter="url(#da71a006d4af4ce6b8f0dc6b1763b086)" style="opacity: 0.6; visibility: hidden; display: none;" p:heavy="true" p:name="bgCopy" id="2186895b427e4e0bac628bdbf5b65fe6"/>
<use xlink:href="#9352a73150934cfd986e88ce1ab4a93e" xmlns:xlink="http://www.w3.org/1999/xlink"/>
<foreignObject x="8" y="22" width="184" height="50" p:name="text" id="b02113fca2d14fa783c537fba5d391e6" style="font-family: &quot;Liberation Sans&quot;,Arial,sans-serif; font-size: 13px; font-weight: normal; font-style: normal; text-decoration: none; fill: rgb(0, 0, 0); fill-opacity: 1; color: rgb(0, 0, 0); opacity: 1; text-align: center;"><div xmlns="http://www.w3.org/1999/xhtml"><span style="font-family: Consolas;">data_bind<br />styles_wrapper / styles<br />classes_wrapper / classes<br /></span></div></foreignObject>
</g><g p:type="Shape" p:def="Evolus.Common:PlainTextV2" id="61991a849e7f4c72a857ddebed80da33" transform="matrix(1,0,0,1,89,166.5)" p:sizing-ox="87.3984375" p:sizing-oy="154.5" p:sizing-ow="60" p:sizing-oh="16"><p:metadata><p:property name="disabled"><![CDATA[false]]></p:property><p:property name="width"><![CDATA[100,0]]></p:property><p:property name="fixedWidth"><![CDATA[false]]></p:property><p:property name="label"><![CDATA[template]]></p:property><p:property name="textColor"><![CDATA[#000000FF]]></p:property><p:property name="textFont"><![CDATA[Consolas|normal|normal|13px|none]]></p:property><p:property name="textAlign"><![CDATA[0,0]]></p:property></p:metadata>
<rect x="0" y="0" style="fill: none; stroke: none; visibility: hidden; display: none;" p:name="bgRect" id="6d064b059239458684409f224ccbb316" width="0" height="0"/>
<text xml:space="preserve" p:name="text" id="dadbe69e489042ce8e4eb9fc489ea745" style="fill: rgb(0, 0, 0); fill-opacity: 1; font-family: Consolas; font-size: 13px; font-weight: normal; font-style: normal; text-decoration: none;"><tspan x="0" y="0">template</tspan></text>
</g><g p:type="Shape" p:def="Evolus.Common:PlainTextV2" id="39a78451571e4e14b57426ec83d5c92a" transform="matrix(1,0,0,1,100,75.5)" p:sizing-ox="98.3984375" p:sizing-oy="63.5" p:sizing-ow="109.1640625" p:sizing-oh="16"><p:metadata><p:property name="disabled"><![CDATA[false]]></p:property><p:property name="width"><![CDATA[100,0]]></p:property><p:property name="fixedWidth"><![CDATA[false]]></p:property><p:property name="label"><![CDATA[template_header]]></p:property><p:property name="textColor"><![CDATA[#000000FF]]></p:property><p:property name="textFont"><![CDATA[Consolas|normal|normal|13px|none]]></p:property><p:property name="textAlign"><![CDATA[0,0]]></p:property></p:metadata>
<rect x="0" y="0" style="fill: none; stroke: none; visibility: hidden; display: none;" p:name="bgRect" id="538be6af592e49a686d10f714de79255" width="0" height="0"/>
<text xml:space="preserve" p:name="text" id="bb1be320b027418592c6edf7f319411d" style="fill: rgb(0, 0, 0); fill-opacity: 1; font-family: Consolas; font-size: 13px; font-weight: normal; font-style: normal; text-decoration: none;"><tspan x="0" y="0">template_header</tspan></text>
</g><g p:type="Shape" p:def="Evolus.Common:RoundedRect" id="2f7cafb48e32492193fc2507d4a77a41" transform="matrix(1,0,0,1,88,24.5)" p:sizing-ox="89" p:sizing-oy="25.5" p:sizing-ow="24" p:sizing-oh="24"><p:metadata><p:property name="box"><![CDATA[24,24]]></p:property><p:property name="withBlur"><![CDATA[false]]></p:property><p:property name="radius"><![CDATA[0,0]]></p:property><p:property name="textPadding"><![CDATA[0,3]]></p:property><p:property name="fillColor"><![CDATA[#CCCCCCFF]]></p:property><p:property name="strokeColor"><![CDATA[#FFFFFFFF]]></p:property><p:property name="strokeStyle"><![CDATA[2|]]></p:property><p:property name="textContent"><![CDATA[
]]></p:property><p:property name="textFont"><![CDATA["Liberation Sans",Arial,sans-serif|normal|normal|13px|none]]></p:property><p:property name="textColor"><![CDATA[#000000FF]]></p:property><p:property name="textAlign"><![CDATA[1,1]]></p:property></p:metadata>
<defs>
<rect width="22" height="22" rx="0" ry="0" x="0" y="0" style="stroke-width: 2; fill: rgb(204, 204, 204); fill-opacity: 1; stroke: rgb(255, 255, 255); stroke-opacity: 1;" p:name="rrRect" id="226ab97c12354c4c824fbf94a11a98b0" transform="translate(1,1)"/>
<filter height="1.2558399" y="-0.12792" width="1.06396" x="-0.03198" p:name="shadingFilter" id="8ae0aa26919c481db673739e49601e78">
<feGaussianBlur stdDeviation="1" in="SourceAlpha"/>
</filter>
</defs>
<use xlink:href="#226ab97c12354c4c824fbf94a11a98b0" xmlns:xlink="http://www.w3.org/1999/xlink" transform="translate(2, 2)" p:filter="url(#8ae0aa26919c481db673739e49601e78)" style="opacity: 0.5; visibility: hidden; display: none;" p:heavy="true" p:name="bgCopy" id="13e998ab0f984d15b0b4f7c8f136ac21"/>
<use xlink:href="#226ab97c12354c4c824fbf94a11a98b0" xmlns:xlink="http://www.w3.org/1999/xlink"/>
<foreignObject x="3" y="12" width="18" height="0" p:name="text" id="998c2f0c678e447fa46f5424e9b8a698" style="font-family: &quot;Liberation Sans&quot;,Arial,sans-serif; font-size: 13px; font-weight: normal; font-style: normal; text-decoration: none; fill: rgb(0, 0, 0); fill-opacity: 1; color: rgb(0, 0, 0); opacity: 1; text-align: center;"><div xmlns="http://www.w3.org/1999/xhtml">
</div></foreignObject>
</g><g p:type="Shape" p:def="Evolus.Common:arrow" id="f983474041574164a9ed540858755610" transform="matrix(1,0,0,1,-144,61.5)" p:sizing-ox="16" p:sizing-oy="30.5" p:sizing-ow="72" p:sizing-oh="63"><p:metadata><p:property name="startPin"><![CDATA[160,32]]></p:property><p:property name="endPin" p:connectedShapeId="2f7cafb48e32492193fc2507d4a77a41" p:connectedOutletId="middle-left" p:viax="222" p:viay="-25"><![CDATA[232,-25]]></p:property><p:property name="withStartArrow"><![CDATA[false]]></p:property><p:property name="withEndArrow"><![CDATA[true]]></p:property><p:property name="mode"><![CDATA[curvy]]></p:property><p:property name="detached"><![CDATA[false]]></p:property><p:property name="strokeColor"><![CDATA[#1B3280FF]]></p:property><p:property name="strokeStyle"><![CDATA[2|]]></p:property><p:property name="textContent"><![CDATA[]]></p:property><p:property name="textFont"><![CDATA["Liberation Sans",Arial,sans-serif|normal|normal|13px|none]]></p:property><p:property name="textColor"><![CDATA[#000000FF]]></p:property><p:property name="textAlign"><![CDATA[1,1]]></p:property></p:metadata>
<defs>
<path style="stroke-linejoin: round; fill: none;" p:name="path" id="d96ef38bf8c04e81aec043fef0b2d21c" d="M 160 32 C 160 -14 186 -25 232 -25 M 226 -31 L 232 -25 L 226 -19"/>
</defs>
<use xlink:href="#d96ef38bf8c04e81aec043fef0b2d21c" xmlns:xlink="http://www.w3.org/1999/xlink" stroke-width="10" stroke-opacity="0" stroke="#FF0000"/>
<use xlink:href="#d96ef38bf8c04e81aec043fef0b2d21c" xmlns:xlink="http://www.w3.org/1999/xlink" p:name="outArrow1" id="66e4484f068b49a09813e21c39d8994e" style="stroke: rgb(27, 50, 128); stroke-opacity: 1; stroke-width: 2;"/>
<text p:name="text" id="b0d40ebba7664c20a9a4f1452c86a07d" style="fill: rgb(0, 0, 0); fill-opacity: 1; font-family: &quot;Liberation Sans&quot;,Arial,sans-serif; font-size: 13px; font-weight: normal; font-style: normal; text-decoration: none;">
<textPath xlink:href="#d96ef38bf8c04e81aec043fef0b2d21c" xmlns:xlink="http://www.w3.org/1999/xlink" startOffset="50%" text-anchor="middle" alignment-baseline="middle">
<tspan dy="-4.333333333333333" p:name="textSpan" id="73255d7945434ce9bc661341349735e1" dx="-16"></tspan>
</textPath>
</text>
</g><g p:type="Shape" p:def="Evolus.Common:PlainTextV2" id="86ed3ea65aee42199bac08824c3826a6" transform="matrix(1,0,0,1,1,104.5)" p:sizing-ox="0" p:sizing-oy="92.5" p:sizing-ow="31.140625" p:sizing-oh="16"><p:metadata><p:property name="disabled"><![CDATA[false]]></p:property><p:property name="width"><![CDATA[100,0]]></p:property><p:property name="fixedWidth"><![CDATA[false]]></p:property><p:property name="label"><![CDATA[icon]]></p:property><p:property name="textColor"><![CDATA[#000000FF]]></p:property><p:property name="textFont"><![CDATA[Consolas|normal|normal|13px|none]]></p:property><p:property name="textAlign"><![CDATA[0,0]]></p:property></p:metadata>
<rect x="0" y="0" style="fill: none; stroke: none; visibility: hidden; display: none;" p:name="bgRect" id="a9ecdbb9c77b4ce4928e46b7cfe54dcf" width="0" height="0"/>
<text xml:space="preserve" p:name="text" id="02a5711e99924fc4b34e5730e2a78fa8" style="fill: rgb(0, 0, 0); fill-opacity: 1; font-family: Consolas; font-size: 13px; font-weight: normal; font-style: normal; text-decoration: none;"><tspan x="0" y="0">icon</tspan></text>
</g></g></Content></Page><Page><Properties><Property name="name">tab</Property><Property name="id">1421409530685_8513</Property><Property name="width">1531</Property><Property name="height">847</Property><Property name="dimBackground"/><Property name="transparentBackground">true</Property><Property name="backgroundColor">#FFFFFFFF</Property><Property name="background">transparent</Property></Properties><Content><g xmlns="http://www.w3.org/2000/svg" p:type="Group" xmlns:p="http://www.evolus.vn/Namespace/Pencil" transform="translate(201,144)" id="d8e8f6e0f752428680f67384aa52208f" p:sizing-gow="598.5" p:sizing-goh="310"><g p:type="Shape" p:def="Evolus.Common:RoundedRect" id="9e881048fedf43d6a67dfad7f06548e9" transform="matrix(1,0,0,1,0,47)" p:sizing-ox="1" p:sizing-oy="48" p:sizing-ow="384" p:sizing-oh="264"><p:metadata><p:property name="box"><![CDATA[384,264]]></p:property><p:property name="withBlur"><![CDATA[false]]></p:property><p:property name="radius"><![CDATA[0,0]]></p:property><p:property name="textPadding"><![CDATA[0,33]]></p:property><p:property name="fillColor"><![CDATA[#CCCCCCFF]]></p:property><p:property name="strokeColor"><![CDATA[#000000FF]]></p:property><p:property name="strokeStyle"><![CDATA[2|]]></p:property><p:property name="textContent"><![CDATA[
]]></p:property><p:property name="textFont"><![CDATA["Liberation Sans",Arial,sans-serif|normal|normal|13px|none]]></p:property><p:property name="textColor"><![CDATA[#000000FF]]></p:property><p:property name="textAlign"><![CDATA[1,1]]></p:property></p:metadata>
<defs>
<rect width="382" height="262" rx="0" ry="0" x="0" y="0" style="stroke-width: 2; fill: rgb(204, 204, 204); fill-opacity: 1; stroke: rgb(0, 0, 0); stroke-opacity: 1;" p:name="rrRect" id="12a9d962fb7b4cabbe2795c5e396d6ec" transform="translate(1,1)"/>
<filter height="1.2558399" y="-0.12792" width="1.06396" x="-0.03198" p:name="shadingFilter" id="76b2ce77019f45daad45b48817f65325">
<feGaussianBlur stdDeviation="1" in="SourceAlpha"/>
</filter>
</defs>
<use xlink:href="#12a9d962fb7b4cabbe2795c5e396d6ec" xmlns:xlink="http://www.w3.org/1999/xlink" transform="translate(2, 2)" p:filter="url(#76b2ce77019f45daad45b48817f65325)" style="opacity: 0.5; visibility: hidden; display: none;" p:heavy="true" p:name="bgCopy" id="6ed5bd1e00f648a792981e16e260963e"/>
<use xlink:href="#12a9d962fb7b4cabbe2795c5e396d6ec" xmlns:xlink="http://www.w3.org/1999/xlink"/>
<foreignObject x="33" y="132" width="318" height="0" p:name="text" id="14b2622dcb514c21a19fcf064f8abe55" style="font-family: &quot;Liberation Sans&quot;,Arial,sans-serif; font-size: 13px; font-weight: normal; font-style: normal; text-decoration: none; fill: rgb(0, 0, 0); fill-opacity: 1; color: rgb(0, 0, 0); opacity: 1; text-align: center;"><div xmlns="http://www.w3.org/1999/xhtml">
</div></foreignObject>
</g><g p:type="Shape" p:def="Evolus.Common:RoundedRect" id="fb37074399fd40dc8078a398f9299f3e" transform="matrix(1,0,0,1,16,63)" p:sizing-ox="17" p:sizing-oy="64" p:sizing-ow="352" p:sizing-oh="232"><p:metadata><p:property name="box"><![CDATA[352,232]]></p:property><p:property name="withBlur"><![CDATA[false]]></p:property><p:property name="radius"><![CDATA[0,0]]></p:property><p:property name="textPadding"><![CDATA[0,29]]></p:property><p:property name="fillColor"><![CDATA[#FFFFFFFF]]></p:property><p:property name="strokeColor"><![CDATA[#000000FF]]></p:property><p:property name="strokeStyle"><![CDATA[2|]]></p:property><p:property name="textContent"><![CDATA[
]]></p:property><p:property name="textFont"><![CDATA["Liberation Sans",Arial,sans-serif|normal|normal|13px|none]]></p:property><p:property name="textColor"><![CDATA[#000000FF]]></p:property><p:property name="textAlign"><![CDATA[1,1]]></p:property></p:metadata>
<defs>
<rect width="350" height="230" rx="0" ry="0" x="0" y="0" style="stroke-width: 2; fill: rgb(255, 255, 255); fill-opacity: 1; stroke: rgb(0, 0, 0); stroke-opacity: 1;" p:name="rrRect" id="d8debccd7e4f482b8c04420ef54ffa70" transform="translate(1,1)"/>
<filter height="1.2558399" y="-0.12792" width="1.06396" x="-0.03198" p:name="shadingFilter" id="1eb07f64e796487984ddffea498f79b9">
<feGaussianBlur stdDeviation="1" in="SourceAlpha"/>
</filter>
</defs>
<use xlink:href="#d8debccd7e4f482b8c04420ef54ffa70" xmlns:xlink="http://www.w3.org/1999/xlink" transform="translate(2, 2)" p:filter="url(#1eb07f64e796487984ddffea498f79b9)" style="opacity: 0.5; visibility: hidden; display: none;" p:heavy="true" p:name="bgCopy" id="9b45931ea5e84b15a01479b46dc76b83"/>
<use xlink:href="#d8debccd7e4f482b8c04420ef54ffa70" xmlns:xlink="http://www.w3.org/1999/xlink"/>
<foreignObject x="29" y="116" width="294" height="0" p:name="text" id="6d8d3f3cce8b4da0b0f97ed8a5fce058" style="font-family: &quot;Liberation Sans&quot;,Arial,sans-serif; font-size: 13px; font-weight: normal; font-style: normal; text-decoration: none; fill: rgb(0, 0, 0); fill-opacity: 1; color: rgb(0, 0, 0); opacity: 1; text-align: center;"><div xmlns="http://www.w3.org/1999/xhtml">
</div></foreignObject>
</g><g p:type="Shape" p:def="Evolus.Common:PlainTextV2" id="407ebd46fa5f48f395a7d5a0b8d46d2a" transform="matrix(1,0,0,1,26,83)" p:sizing-ox="24.3984375" p:sizing-oy="71" p:sizing-ow="60" p:sizing-oh="16"><p:metadata><p:property name="disabled"><![CDATA[false]]></p:property><p:property name="width"><![CDATA[100,0]]></p:property><p:property name="fixedWidth"><![CDATA[false]]></p:property><p:property name="label"><![CDATA[template]]></p:property><p:property name="textColor"><![CDATA[#000000FF]]></p:property><p:property name="textFont"><![CDATA[Consolas|normal|normal|13px|none]]></p:property><p:property name="textAlign"><![CDATA[0,0]]></p:property></p:metadata>
<rect x="0" y="0" style="fill: none; stroke: none; visibility: hidden; display: none;" p:name="bgRect" id="efd58ec8f2eb45dcbeea7bb13c573cc5" width="0" height="0"/>
<text xml:space="preserve" p:name="text" id="ba9f30328268467ba17566dbd14ae998" style="fill: rgb(0, 0, 0); fill-opacity: 1; font-family: Consolas; font-size: 13px; font-weight: normal; font-style: normal; text-decoration: none;"><tspan x="0" y="0">template</tspan></text>
</g><g p:type="Shape" p:def="Evolus.Common:trapezoid" id="cb49850d258c4367abbee3628aa93512" transform="matrix(1,0,0,1,0,0)" p:sizing-ox="0" p:sizing-oy="0" p:sizing-ow="119" p:sizing-oh="48"><p:metadata><p:property name="box"><![CDATA[119,48]]></p:property><p:property name="a"><![CDATA[29.750000000000004,0]]></p:property><p:property name="fillColor"><![CDATA[#CCCCCCFF]]></p:property><p:property name="strokeColor"><![CDATA[#000000FF]]></p:property><p:property name="strokeStyle"><![CDATA[2|]]></p:property></p:metadata>
<path style="stroke-linejoin: round; stroke: rgb(0, 0, 0); stroke-opacity: 1; stroke-width: 2; fill: rgb(204, 204, 204); fill-opacity: 1;" p:name="path" id="ac794f7d717045878f0fdebc737e9adc" transform="translate(0,0)" d="M 29.750000000000004 0 L 89.25 0 L 119 48 L 0 48 z"/>
</g><g xmlns="http://www.w3.org/2000/svg" p:type="Shape" xmlns:p="http://www.evolus.vn/Namespace/Pencil" p:def="Evolus.Common:trapezoid" id="b0b14e6d505d4af7a04a05a8cc7fe672" transform="matrix(1,0,0,1,87,0)" p:sizing-ox="87" p:sizing-oy="0" p:sizing-ow="120" p:sizing-oh="48"><p:metadata><p:property name="box"><![CDATA[120,48]]></p:property><p:property name="a"><![CDATA[30,0]]></p:property><p:property name="fillColor"><![CDATA[#CCCCCCFF]]></p:property><p:property name="strokeColor"><![CDATA[#000000FF]]></p:property><p:property name="strokeStyle"><![CDATA[2|]]></p:property></p:metadata>
<path style="stroke-linejoin: round; stroke: rgb(0, 0, 0); stroke-opacity: 1; stroke-width: 2; fill: rgb(204, 204, 204); fill-opacity: 1;" p:name="path" id="5c4e128120224a0f87c3c6f9e98f9183" transform="translate(0,0)" d="M 30 0 L 90 0 L 120 48 L 0 48 z"/>
</g><g xmlns="http://www.w3.org/2000/svg" p:type="Shape" xmlns:p="http://www.evolus.vn/Namespace/Pencil" p:def="Evolus.Common:trapezoid" id="b95ce307dbc04cb297e1d019f1c31d0d" transform="matrix(1,0,0,1,263,0)" p:sizing-ox="263" p:sizing-oy="0" p:sizing-ow="120" p:sizing-oh="48"><p:metadata><p:property name="box"><![CDATA[120,48]]></p:property><p:property name="a"><![CDATA[30,0]]></p:property><p:property name="fillColor"><![CDATA[#CCCCCCFF]]></p:property><p:property name="strokeColor"><![CDATA[#000000FF]]></p:property><p:property name="strokeStyle"><![CDATA[2|]]></p:property></p:metadata>
<path style="stroke-linejoin: round; stroke: rgb(0, 0, 0); stroke-opacity: 1; stroke-width: 2; fill: rgb(204, 204, 204); fill-opacity: 1;" p:name="path" id="58f26895549a4afe87215738aad60c7f" transform="translate(0,0)" d="M 30 0 L 90 0 L 120 48 L 0 48 z"/>
</g><g xmlns="http://www.w3.org/2000/svg" p:type="Shape" xmlns:p="http://www.evolus.vn/Namespace/Pencil" p:def="Evolus.Common:trapezoid" id="dd08c65002d54b4d963c0fc1ddd8da56" transform="matrix(1,0,0,1,175,0)" p:sizing-ox="175" p:sizing-oy="0" p:sizing-ow="120" p:sizing-oh="48"><p:metadata><p:property name="box"><![CDATA[120,48]]></p:property><p:property name="a"><![CDATA[30,0]]></p:property><p:property name="fillColor"><![CDATA[#CCCCCCFF]]></p:property><p:property name="strokeColor"><![CDATA[#000000FF]]></p:property><p:property name="strokeStyle"><![CDATA[2|]]></p:property></p:metadata>
<path style="stroke-linejoin: round; stroke: rgb(0, 0, 0); stroke-opacity: 1; stroke-width: 2; fill: rgb(204, 204, 204); fill-opacity: 1;" p:name="path" id="2ff5fd3ed1174b1ca120e0521506dfdb" transform="translate(0,0)" d="M 30 0 L 90 0 L 120 48 L 0 48 z"/>
</g><g xmlns="http://www.w3.org/2000/svg" p:type="Shape" xmlns:p="http://www.evolus.vn/Namespace/Pencil" p:def="Evolus.Common:PlainTextV2" id="c821784d3f6f4c54a482c9b800303096" transform="matrix(1,0,0,1,196,38)" p:sizing-ox="195.859375" p:sizing-oy="16" p:sizing-ow="79.7890625" p:sizing-oh="28"><p:metadata><p:property name="disabled"><![CDATA[false]]></p:property><p:property name="width"><![CDATA[100,0]]></p:property><p:property name="fixedWidth"><![CDATA[false]]></p:property><p:property name="label"><![CDATA[<name>]]></p:property><p:property name="textColor"><![CDATA[#000000FF]]></p:property><p:property name="textFont"><![CDATA[Open Sans|bold|normal|20px|none]]></p:property><p:property name="textAlign"><![CDATA[0,0]]></p:property></p:metadata>
<rect x="0" y="0" style="fill: none; stroke: none; visibility: hidden; display: none;" p:name="bgRect" id="45c9bc72749f4114b754dd78d39294d9" width="0" height="0"/>
<text xml:space="preserve" p:name="text" id="510af970bf6e4a3299e10d5726dc506b" style="fill: rgb(0, 0, 0); fill-opacity: 1; font-family: Open Sans; font-size: 20px; font-weight: bold; font-style: normal; text-decoration: none;"><tspan x="0" y="0">&lt;name&gt;</tspan></text>
</g><g p:type="Shape" p:def="Evolus.Common:Balloon" id="28819f317c9a44f487d89358bc01d35e" transform="matrix(1,0,0,1,398,0)" p:sizing-ox="284.5" p:sizing-oy="0.5" p:sizing-ow="200" p:sizing-oh="80"><p:metadata><p:property name="box"><![CDATA[200,80]]></p:property><p:property name="withBlur"><![CDATA[false]]></p:property><p:property name="radius"><![CDATA[8,0]]></p:property><p:property name="leftStart"><![CDATA[0,12]]></p:property><p:property name="leftEnd"><![CDATA[0,33]]></p:property><p:property name="rightStart"><![CDATA[200,12]]></p:property><p:property name="rightEnd"><![CDATA[200,33]]></p:property><p:property name="topStart"><![CDATA[12,0]]></p:property><p:property name="topEnd"><![CDATA[33,0]]></p:property><p:property name="bottomStart"><![CDATA[12,80]]></p:property><p:property name="bottomEnd"><![CDATA[33,80]]></p:property><p:property name="pin"><![CDATA[-114,22]]></p:property><p:property name="fillColor"><![CDATA[#FFFFFFFF]]></p:property><p:property name="strokeColor"><![CDATA[#1B3280FF]]></p:property><p:property name="strokeStyle"><![CDATA[2|]]></p:property><p:property name="textContent"><![CDATA[<span style="font-family: Consolas;">data_bind<br />styles_link / styles<br />classes_link / classes</span><br />]]></p:property><p:property name="textFont"><![CDATA["Liberation Sans",Arial,sans-serif|normal|normal|13px|none]]></p:property><p:property name="textColor"><![CDATA[#000000FF]]></p:property><p:property name="textAlign"><![CDATA[1,1]]></p:property></p:metadata>
<defs>
<filter height="1.2558399" y="-0.12792" width="1.06396" x="-0.03198" p:name="imageShading" id="f46117a9847b442a848d6dc6d0f1ca02">
<feGaussianBlur stdDeviation="1.3325" in="SourceAlpha"/>
</filter>
<g p:name="container" id="7e565a2554874c8693bee8c3b1fb4a96">
<path transform="translate(0.5 0.5)" style="stroke-width: 2; fill: rgb(255, 255, 255); fill-opacity: 1; stroke: rgb(27, 50, 128); stroke-opacity: 1;" p:name="rect" id="35606f3a84d34cfabef6fd7995e162c9" d="M 8 0 L 192 0 C 197.33333333333334 0 200 2.6666666666666665 200 8 L 200 72 C 200 77.33333333333333 197.33333333333334 80 192 80 L 8 80 C 2.6666666666666665 80 0 77.33333333333333 0 72 L 0 33 L -114 22 L 0 12 L 0 8 C 0 2.6666666666666665 2.6666666666666665 0 8 0"/>
</g>
</defs>
<use xlink:href="#7e565a2554874c8693bee8c3b1fb4a96" xmlns:xlink="http://www.w3.org/1999/xlink" transform="translate(1, 1)" p:filter="url(#f46117a9847b442a848d6dc6d0f1ca02)" style="opacity: 0.6; visibility: hidden; display: none;" p:heavy="true" p:name="bgCopy" id="fba23d0e302047588af7e9e586dfb238"/>
<use xlink:href="#7e565a2554874c8693bee8c3b1fb4a96" xmlns:xlink="http://www.w3.org/1999/xlink"/>
<foreignObject x="8" y="15" width="184" height="50" p:name="text" id="d94b77112885453db437a00ff25500ca" style="font-family: &quot;Liberation Sans&quot;,Arial,sans-serif; font-size: 13px; font-weight: normal; font-style: normal; text-decoration: none; fill: rgb(0, 0, 0); fill-opacity: 1; color: rgb(0, 0, 0); opacity: 1; text-align: center;"><div xmlns="http://www.w3.org/1999/xhtml"><span style="font-family: Consolas;">data_bind<br />styles_link / styles<br />classes_link / classes</span><br /></div></foreignObject>
</g><g p:type="Shape" p:def="Evolus.Common:Balloon" id="6f1c4f61a1fb4f14a28d1793b958ba0a" transform="matrix(1,0,0,1,397,120)" p:sizing-ox="369.5" p:sizing-oy="120.5" p:sizing-ow="200" p:sizing-oh="80"><p:metadata><p:property name="box"><![CDATA[200,80]]></p:property><p:property name="withBlur"><![CDATA[false]]></p:property><p:property name="radius"><![CDATA[8,0]]></p:property><p:property name="leftStart"><![CDATA[0,12]]></p:property><p:property name="leftEnd"><![CDATA[0,33]]></p:property><p:property name="rightStart"><![CDATA[200,12]]></p:property><p:property name="rightEnd"><![CDATA[200,33]]></p:property><p:property name="topStart"><![CDATA[12,0]]></p:property><p:property name="topEnd"><![CDATA[33,0]]></p:property><p:property name="bottomStart"><![CDATA[12,80]]></p:property><p:property name="bottomEnd"><![CDATA[33,80]]></p:property><p:property name="pin"><![CDATA[-28,23]]></p:property><p:property name="fillColor"><![CDATA[#FFFFFFFF]]></p:property><p:property name="strokeColor"><![CDATA[#1B3280FF]]></p:property><p:property name="strokeStyle"><![CDATA[2|]]></p:property><p:property name="textContent"><![CDATA[<span style="font-family: Consolas;">data_bind<br />styles_content / styles<br />classes_content / classes</span><br />]]></p:property><p:property name="textFont"><![CDATA["Liberation Sans",Arial,sans-serif|normal|normal|13px|none]]></p:property><p:property name="textColor"><![CDATA[#000000FF]]></p:property><p:property name="textAlign"><![CDATA[1,1]]></p:property></p:metadata>
<defs>
<filter height="1.2558399" y="-0.12792" width="1.06396" x="-0.03198" p:name="imageShading" id="acf275ea0a954d79ae41107f58d208ae">
<feGaussianBlur stdDeviation="1.3325" in="SourceAlpha"/>
</filter>
<g p:name="container" id="a75b69e48d5e40f4b6150b1ec2953af3">
<path transform="translate(0.5 0.5)" style="stroke-width: 2; fill: rgb(255, 255, 255); fill-opacity: 1; stroke: rgb(27, 50, 128); stroke-opacity: 1;" p:name="rect" id="eb3218f33a0b49fb8ec0ad9f86d2872a" d="M 8 0 L 192 0 C 197.33333333333334 0 200 2.6666666666666665 200 8 L 200 72 C 200 77.33333333333333 197.33333333333334 80 192 80 L 8 80 C 2.6666666666666665 80 0 77.33333333333333 0 72 L 0 33 L -28 23 L 0 12 L 0 8 C 0 2.6666666666666665 2.6666666666666665 0 8 0"/>
</g>
</defs>
<use xlink:href="#a75b69e48d5e40f4b6150b1ec2953af3" xmlns:xlink="http://www.w3.org/1999/xlink" transform="translate(1, 1)" p:filter="url(#acf275ea0a954d79ae41107f58d208ae)" style="opacity: 0.6; visibility: hidden; display: none;" p:heavy="true" p:name="bgCopy" id="809f63827dbe473db68c768a9299d7be"/>
<use xlink:href="#a75b69e48d5e40f4b6150b1ec2953af3" xmlns:xlink="http://www.w3.org/1999/xlink"/>
<foreignObject x="8" y="15" width="184" height="50" p:name="text" id="31d16c095ee849c791565b6c88b93fad" style="font-family: &quot;Liberation Sans&quot;,Arial,sans-serif; font-size: 13px; font-weight: normal; font-style: normal; text-decoration: none; fill: rgb(0, 0, 0); fill-opacity: 1; color: rgb(0, 0, 0); opacity: 1; text-align: center;"><div xmlns="http://www.w3.org/1999/xhtml"><span style="font-family: Consolas;">data_bind<br />styles_content / styles<br />classes_content / classes</span><br /></div></foreignObject>
</g></g></Content></Page><Page><Properties><Property name="name">settings</Property><Property name="id">1421410253180_3579</Property><Property name="width">1531</Property><Property name="height">847</Property><Property name="dimBackground"/><Property name="transparentBackground">true</Property><Property name="backgroundColor">#FFFFFFFF</Property><Property name="background">transparent</Property></Properties><Content><g xmlns="http://www.w3.org/2000/svg" p:type="Group" xmlns:p="http://www.evolus.vn/Namespace/Pencil" transform="translate(323,143)" id="7395842d34de4079b3029fbb8f377213" p:sizing-gow="769.5" p:sizing-goh="390"><g p:type="Shape" p:def="Evolus.Common:RoundedRect" id="5267d389e1714536a6262df513ff7665" transform="matrix(1,0,0,1,-1,-1)" p:sizing-ox="0" p:sizing-oy="0" p:sizing-ow="144" p:sizing-oh="392"><p:metadata><p:property name="box"><![CDATA[144,392]]></p:property><p:property name="withBlur"><![CDATA[false]]></p:property><p:property name="radius"><![CDATA[0,0]]></p:property><p:property name="textPadding"><![CDATA[0,49]]></p:property><p:property name="fillColor"><![CDATA[#CCCCCCFF]]></p:property><p:property name="strokeColor"><![CDATA[#000000FF]]></p:property><p:property name="strokeStyle"><![CDATA[2|]]></p:property><p:property name="textContent"><![CDATA[
]]></p:property><p:property name="textFont"><![CDATA["Liberation Sans",Arial,sans-serif|normal|normal|13px|none]]></p:property><p:property name="textColor"><![CDATA[#000000FF]]></p:property><p:property name="textAlign"><![CDATA[1,1]]></p:property></p:metadata>
<defs>
<rect width="142" height="390" rx="0" ry="0" x="0" y="0" style="stroke-width: 2; fill: rgb(204, 204, 204); fill-opacity: 1; stroke: rgb(0, 0, 0); stroke-opacity: 1;" p:name="rrRect" id="cb16e9a309e341f1ba7f6440a0483dc7" transform="translate(1,1)"/>
<filter height="1.2558399" y="-0.12792" width="1.06396" x="-0.03198" p:name="shadingFilter" id="54e55b5fad5d4a3995c3806b790f2d05">
<feGaussianBlur stdDeviation="1" in="SourceAlpha"/>
</filter>
</defs>
<use xlink:href="#cb16e9a309e341f1ba7f6440a0483dc7" xmlns:xlink="http://www.w3.org/1999/xlink" transform="translate(2, 2)" p:filter="url(#54e55b5fad5d4a3995c3806b790f2d05)" style="opacity: 0.5; visibility: hidden; display: none;" p:heavy="true" p:name="bgCopy" id="904bde4e72cb4b5aa6cb5b963c339bdf"/>
<use xlink:href="#cb16e9a309e341f1ba7f6440a0483dc7" xmlns:xlink="http://www.w3.org/1999/xlink"/>
<foreignObject x="49" y="196" width="46" height="0" p:name="text" id="e13fe7a85e1a4ca081470478b747bc8c" style="font-family: &quot;Liberation Sans&quot;,Arial,sans-serif; font-size: 13px; font-weight: normal; font-style: normal; text-decoration: none; fill: rgb(0, 0, 0); fill-opacity: 1; color: rgb(0, 0, 0); opacity: 1; text-align: center;"><div xmlns="http://www.w3.org/1999/xhtml">
</div></foreignObject>
</g><g p:type="Shape" p:def="Evolus.Common:RoundedRect" id="00107838b5c846ac87f4bbc67a235524" transform="matrix(1,0,0,1,143,-1)" p:sizing-ox="144" p:sizing-oy="0" p:sizing-ow="416" p:sizing-oh="392"><p:metadata><p:property name="box"><![CDATA[416,392]]></p:property><p:property name="withBlur"><![CDATA[false]]></p:property><p:property name="radius"><![CDATA[0,0]]></p:property><p:property name="textPadding"><![CDATA[0,49]]></p:property><p:property name="fillColor"><![CDATA[#CCCCCCFF]]></p:property><p:property name="strokeColor"><![CDATA[#000000FF]]></p:property><p:property name="strokeStyle"><![CDATA[2|]]></p:property><p:property name="textContent"><![CDATA[
]]></p:property><p:property name="textFont"><![CDATA["Liberation Sans",Arial,sans-serif|normal|normal|13px|none]]></p:property><p:property name="textColor"><![CDATA[#000000FF]]></p:property><p:property name="textAlign"><![CDATA[1,1]]></p:property></p:metadata>
<defs>
<rect width="414" height="390" rx="0" ry="0" x="0" y="0" style="stroke-width: 2; fill: rgb(204, 204, 204); fill-opacity: 1; stroke: rgb(0, 0, 0); stroke-opacity: 1;" p:name="rrRect" id="cbe5e6469a9647b9a54b064a30ee0c35" transform="translate(1,1)"/>
<filter height="1.2558399" y="-0.12792" width="1.06396" x="-0.03198" p:name="shadingFilter" id="8d5eca961f8d499abcbcdb90c9f38da8">
<feGaussianBlur stdDeviation="1" in="SourceAlpha"/>
</filter>
</defs>
<use xlink:href="#cbe5e6469a9647b9a54b064a30ee0c35" xmlns:xlink="http://www.w3.org/1999/xlink" transform="translate(2, 2)" p:filter="url(#8d5eca961f8d499abcbcdb90c9f38da8)" style="opacity: 0.5; visibility: hidden; display: none;" p:heavy="true" p:name="bgCopy" id="34141c77145742d3810b0e7474f6e012"/>
<use xlink:href="#cbe5e6469a9647b9a54b064a30ee0c35" xmlns:xlink="http://www.w3.org/1999/xlink"/>
<foreignObject x="49" y="196" width="318" height="0" p:name="text" id="41ef32306e1e4d9da9165746657a5965" style="font-family: &quot;Liberation Sans&quot;,Arial,sans-serif; font-size: 13px; font-weight: normal; font-style: normal; text-decoration: none; fill: rgb(0, 0, 0); fill-opacity: 1; color: rgb(0, 0, 0); opacity: 1; text-align: center;"><div xmlns="http://www.w3.org/1999/xhtml">
</div></foreignObject>
</g><g p:type="Shape" p:def="Evolus.Common:RoundedRect" id="dfc036f4a3394f48abfd564cd42b2b0e" transform="matrix(1,0,0,1,159,15)" p:sizing-ox="160" p:sizing-oy="16" p:sizing-ow="384" p:sizing-oh="360"><p:metadata><p:property name="box"><![CDATA[384,360]]></p:property><p:property name="withBlur"><![CDATA[false]]></p:property><p:property name="radius"><![CDATA[0,0]]></p:property><p:property name="textPadding"><![CDATA[0,45]]></p:property><p:property name="fillColor"><![CDATA[#FFFFFFFF]]></p:property><p:property name="strokeColor"><![CDATA[#000000FF]]></p:property><p:property name="strokeStyle"><![CDATA[2|]]></p:property><p:property name="textContent"><![CDATA[
]]></p:property><p:property name="textFont"><![CDATA["Liberation Sans",Arial,sans-serif|normal|normal|13px|none]]></p:property><p:property name="textColor"><![CDATA[#000000FF]]></p:property><p:property name="textAlign"><![CDATA[1,1]]></p:property></p:metadata>
<defs>
<rect width="382" height="358" rx="0" ry="0" x="0" y="0" style="stroke-width: 2; fill: rgb(255, 255, 255); fill-opacity: 1; stroke: rgb(0, 0, 0); stroke-opacity: 1;" p:name="rrRect" id="29dc0c2600da465fb63911073183eafe" transform="translate(1,1)"/>
<filter height="1.2558399" y="-0.12792" width="1.06396" x="-0.03198" p:name="shadingFilter" id="451d197a117c48f7a68d1c1be41304e5">
<feGaussianBlur stdDeviation="1" in="SourceAlpha"/>
</filter>
</defs>
<use xlink:href="#29dc0c2600da465fb63911073183eafe" xmlns:xlink="http://www.w3.org/1999/xlink" transform="translate(2, 2)" p:filter="url(#451d197a117c48f7a68d1c1be41304e5)" style="opacity: 0.5; visibility: hidden; display: none;" p:heavy="true" p:name="bgCopy" id="6c260c83376042eda5122f600dac0784"/>
<use xlink:href="#29dc0c2600da465fb63911073183eafe" xmlns:xlink="http://www.w3.org/1999/xlink"/>
<foreignObject x="45" y="180" width="294" height="0" p:name="text" id="cb978529c3144a3085a502964a33bfa4" style="font-family: &quot;Liberation Sans&quot;,Arial,sans-serif; font-size: 13px; font-weight: normal; font-style: normal; text-decoration: none; fill: rgb(0, 0, 0); fill-opacity: 1; color: rgb(0, 0, 0); opacity: 1; text-align: center;"><div xmlns="http://www.w3.org/1999/xhtml">
</div></foreignObject>
</g><g p:type="Shape" p:def="Evolus.Common:RoundedRect" id="f2e9506fa0ed4466890d1042d5ac901e" transform="matrix(1,0,0,1,15,175)" p:sizing-ox="16" p:sizing-oy="176" p:sizing-ow="112" p:sizing-oh="40"><p:metadata><p:property name="box"><![CDATA[112,40]]></p:property><p:property name="withBlur"><![CDATA[false]]></p:property><p:property name="radius"><![CDATA[0,0]]></p:property><p:property name="textPadding"><![CDATA[0,5]]></p:property><p:property name="fillColor"><![CDATA[#CCCCCCFF]]></p:property><p:property name="strokeColor"><![CDATA[#000000FF]]></p:property><p:property name="strokeStyle"><![CDATA[2|]]></p:property><p:property name="textContent"><![CDATA[
]]></p:property><p:property name="textFont"><![CDATA["Liberation Sans",Arial,sans-serif|normal|normal|13px|none]]></p:property><p:property name="textColor"><![CDATA[#000000FF]]></p:property><p:property name="textAlign"><![CDATA[1,1]]></p:property></p:metadata>
<defs>
<rect width="110" height="38" rx="0" ry="0" x="0" y="0" style="stroke-width: 2; fill: rgb(204, 204, 204); fill-opacity: 1; stroke: rgb(0, 0, 0); stroke-opacity: 1;" p:name="rrRect" id="76d805dced5640149e7d9b75b58e9479" transform="translate(1,1)"/>
<filter height="1.2558399" y="-0.12792" width="1.06396" x="-0.03198" p:name="shadingFilter" id="4fc6940222be4d1bb3d1bba581209b59">
<feGaussianBlur stdDeviation="1" in="SourceAlpha"/>
</filter>
</defs>
<use xlink:href="#76d805dced5640149e7d9b75b58e9479" xmlns:xlink="http://www.w3.org/1999/xlink" transform="translate(2, 2)" p:filter="url(#4fc6940222be4d1bb3d1bba581209b59)" style="opacity: 0.5; visibility: hidden; display: none;" p:heavy="true" p:name="bgCopy" id="60a990d0eb9e4ea69c10c41791e58323"/>
<use xlink:href="#76d805dced5640149e7d9b75b58e9479" xmlns:xlink="http://www.w3.org/1999/xlink"/>
<foreignObject x="5" y="20" width="102" height="0" p:name="text" id="54e8a52460b84409b8c52e713918e527" style="font-family: &quot;Liberation Sans&quot;,Arial,sans-serif; font-size: 13px; font-weight: normal; font-style: normal; text-decoration: none; fill: rgb(0, 0, 0); fill-opacity: 1; color: rgb(0, 0, 0); opacity: 1; text-align: center;"><div xmlns="http://www.w3.org/1999/xhtml">
</div></foreignObject>
</g><g xmlns="http://www.w3.org/2000/svg" p:type="Shape" xmlns:p="http://www.evolus.vn/Namespace/Pencil" p:def="Evolus.Common:PlainTextV2" id="3a5c9441f4dd450489ef6c32b84277bb" transform="matrix(1,0,0,1,22,202)" p:sizing-ox="21.859375" p:sizing-oy="180" p:sizing-ow="79.7890625" p:sizing-oh="28"><p:metadata><p:property name="disabled"><![CDATA[false]]></p:property><p:property name="width"><![CDATA[100,0]]></p:property><p:property name="fixedWidth"><![CDATA[false]]></p:property><p:property name="label"><![CDATA[<name>]]></p:property><p:property name="textColor"><![CDATA[#000000FF]]></p:property><p:property name="textFont"><![CDATA[Open Sans|bold|normal|20px|none]]></p:property><p:property name="textAlign"><![CDATA[0,0]]></p:property></p:metadata>
<rect x="0" y="0" style="fill: none; stroke: none; visibility: hidden; display: none;" p:name="bgRect" id="49590ece8832421093f480572615621e" width="0" height="0"/>
<text xml:space="preserve" p:name="text" id="638c493afd75474bba33ba6ed7f6b418" style="fill: rgb(0, 0, 0); fill-opacity: 1; font-family: Open Sans; font-size: 20px; font-weight: bold; font-style: normal; text-decoration: none;"><tspan x="0" y="0">&lt;name&gt;</tspan></text>
</g><g xmlns="http://www.w3.org/2000/svg" p:type="Shape" xmlns:p="http://www.evolus.vn/Namespace/Pencil" p:def="Evolus.Common:PlainTextV2" id="ebd3473021234611aefc9fa212dcc943" transform="matrix(1,0,0,1,175,37)" p:sizing-ox="173.3984375" p:sizing-oy="25" p:sizing-ow="60" p:sizing-oh="16"><p:metadata><p:property name="disabled"><![CDATA[false]]></p:property><p:property name="width"><![CDATA[100,0]]></p:property><p:property name="fixedWidth"><![CDATA[false]]></p:property><p:property name="label"><![CDATA[template]]></p:property><p:property name="textColor"><![CDATA[#000000FF]]></p:property><p:property name="textFont"><![CDATA[Consolas|normal|normal|13px|none]]></p:property><p:property name="textAlign"><![CDATA[0,0]]></p:property></p:metadata>
<rect x="0" y="0" style="fill: none; stroke: none; visibility: hidden; display: none;" p:name="bgRect" id="a7f7b8da20384df091964756d22bd5df" width="0" height="0"/>
<text xml:space="preserve" p:name="text" id="85ffc835cc2f4e8ea41c1857b55af53e" style="fill: rgb(0, 0, 0); fill-opacity: 1; font-family: Consolas; font-size: 13px; font-weight: normal; font-style: normal; text-decoration: none;"><tspan x="0" y="0">template</tspan></text>
</g><g p:type="Shape" p:def="Evolus.Common:Balloon" id="a0d9b8a91b8d4913bc11cca99c86a459" transform="matrix(1,0,0,1,569,15)" p:sizing-ox="541.5" p:sizing-oy="15.5" p:sizing-ow="200" p:sizing-oh="80"><p:metadata><p:property name="box"><![CDATA[200,80]]></p:property><p:property name="withBlur"><![CDATA[false]]></p:property><p:property name="radius"><![CDATA[8,0]]></p:property><p:property name="leftStart"><![CDATA[0,12]]></p:property><p:property name="leftEnd"><![CDATA[0,33]]></p:property><p:property name="rightStart"><![CDATA[200,12]]></p:property><p:property name="rightEnd"><![CDATA[200,33]]></p:property><p:property name="topStart"><![CDATA[12,0]]></p:property><p:property name="topEnd"><![CDATA[33,0]]></p:property><p:property name="bottomStart"><![CDATA[12,80]]></p:property><p:property name="bottomEnd"><![CDATA[33,80]]></p:property><p:property name="pin"><![CDATA[-28,23]]></p:property><p:property name="fillColor"><![CDATA[#FFFFFFFF]]></p:property><p:property name="strokeColor"><![CDATA[#1B3280FF]]></p:property><p:property name="strokeStyle"><![CDATA[2|]]></p:property><p:property name="textContent"><![CDATA[<span style="font-family: Consolas;">data_bind<br />styles_content / styles<br />classes_content / classes<br /></span>]]></p:property><p:property name="textFont"><![CDATA["Liberation Sans",Arial,sans-serif|normal|normal|13px|none]]></p:property><p:property name="textColor"><![CDATA[#000000FF]]></p:property><p:property name="textAlign"><![CDATA[1,1]]></p:property></p:metadata>
<defs>
<filter height="1.2558399" y="-0.12792" width="1.06396" x="-0.03198" p:name="imageShading" id="2f5319b357c84839b3986162a515c00e">
<feGaussianBlur stdDeviation="1.3325" in="SourceAlpha"/>
</filter>
<g p:name="container" id="9c15a0a8bd764d0187e813cd78f906d4">
<path transform="translate(0.5 0.5)" style="stroke-width: 2; fill: rgb(255, 255, 255); fill-opacity: 1; stroke: rgb(27, 50, 128); stroke-opacity: 1;" p:name="rect" id="0f6d812601a94e60b7f5e3f1d859d630" d="M 8 0 L 192 0 C 197.33333333333334 0 200 2.6666666666666665 200 8 L 200 72 C 200 77.33333333333333 197.33333333333334 80 192 80 L 8 80 C 2.6666666666666665 80 0 77.33333333333333 0 72 L 0 33 L -28 23 L 0 12 L 0 8 C 0 2.6666666666666665 2.6666666666666665 0 8 0"/>
</g>
</defs>
<use xlink:href="#9c15a0a8bd764d0187e813cd78f906d4" xmlns:xlink="http://www.w3.org/1999/xlink" transform="translate(1, 1)" p:filter="url(#2f5319b357c84839b3986162a515c00e)" style="opacity: 0.6; visibility: hidden; display: none;" p:heavy="true" p:name="bgCopy" id="4a90c69f97384e74ae968cff348b2ed9"/>
<use xlink:href="#9c15a0a8bd764d0187e813cd78f906d4" xmlns:xlink="http://www.w3.org/1999/xlink"/>
<foreignObject x="8" y="15" width="184" height="50" p:name="text" id="eac648dfa87d4f719c8d271b82f1c930" style="font-family: &quot;Liberation Sans&quot;,Arial,sans-serif; font-size: 13px; font-weight: normal; font-style: normal; text-decoration: none; fill: rgb(0, 0, 0); fill-opacity: 1; color: rgb(0, 0, 0); opacity: 1; text-align: center;"><div xmlns="http://www.w3.org/1999/xhtml"><span style="font-family: Consolas;">data_bind<br />styles_content / styles<br />classes_content / classes<br /></span></div></foreignObject>
</g><g p:type="Shape" p:def="Evolus.Common:Balloon" id="bda1534d936b4b1a8851bd7316333963" transform="matrix(1,0,0,1,137,175)" p:sizing-ox="125.5" p:sizing-oy="175.5" p:sizing-ow="200" p:sizing-oh="80"><p:metadata><p:property name="box"><![CDATA[200,80]]></p:property><p:property name="withBlur"><![CDATA[false]]></p:property><p:property name="radius"><![CDATA[8,0]]></p:property><p:property name="leftStart"><![CDATA[0,12]]></p:property><p:property name="leftEnd"><![CDATA[0,33]]></p:property><p:property name="rightStart"><![CDATA[200,12]]></p:property><p:property name="rightEnd"><![CDATA[200,33]]></p:property><p:property name="topStart"><![CDATA[12,0]]></p:property><p:property name="topEnd"><![CDATA[33,0]]></p:property><p:property name="bottomStart"><![CDATA[12,80]]></p:property><p:property name="bottomEnd"><![CDATA[33,80]]></p:property><p:property name="pin"><![CDATA[-12,23]]></p:property><p:property name="fillColor"><![CDATA[#FFFFFFFF]]></p:property><p:property name="strokeColor"><![CDATA[#1B3280FF]]></p:property><p:property name="strokeStyle"><![CDATA[2|]]></p:property><p:property name="textContent"><![CDATA[<span style="font-family: Consolas;">data_bind<br />styles_link / styles<br />classes_link / classes</span><br />]]></p:property><p:property name="textFont"><![CDATA["Liberation Sans",Arial,sans-serif|normal|normal|13px|none]]></p:property><p:property name="textColor"><![CDATA[#000000FF]]></p:property><p:property name="textAlign"><![CDATA[1,1]]></p:property></p:metadata>
<defs>
<filter height="1.2558399" y="-0.12792" width="1.06396" x="-0.03198" p:name="imageShading" id="7190c91fd5a0498faee46f6a07e4ee36">
<feGaussianBlur stdDeviation="1.3325" in="SourceAlpha"/>
</filter>
<g p:name="container" id="e38975d273874cd7ac31fa1c63716ec1">
<path transform="translate(0.5 0.5)" style="stroke-width: 2; fill: rgb(255, 255, 255); fill-opacity: 1; stroke: rgb(27, 50, 128); stroke-opacity: 1;" p:name="rect" id="72ab543eb28a48e6bedf116266c72fbb" d="M 8 0 L 192 0 C 197.33333333333334 0 200 2.6666666666666665 200 8 L 200 72 C 200 77.33333333333333 197.33333333333334 80 192 80 L 8 80 C 2.6666666666666665 80 0 77.33333333333333 0 72 L 0 33 L -12 23 L 0 12 L 0 8 C 0 2.6666666666666665 2.6666666666666665 0 8 0"/>
</g>
</defs>
<use xlink:href="#e38975d273874cd7ac31fa1c63716ec1" xmlns:xlink="http://www.w3.org/1999/xlink" transform="translate(1, 1)" p:filter="url(#7190c91fd5a0498faee46f6a07e4ee36)" style="opacity: 0.6; visibility: hidden; display: none;" p:heavy="true" p:name="bgCopy" id="f143de029bc146c7a3a7bca494562509"/>
<use xlink:href="#e38975d273874cd7ac31fa1c63716ec1" xmlns:xlink="http://www.w3.org/1999/xlink"/>
<foreignObject x="8" y="15" width="184" height="50" p:name="text" id="9ba09cfb0e0643c69291c6942df8c8c9" style="font-family: &quot;Liberation Sans&quot;,Arial,sans-serif; font-size: 13px; font-weight: normal; font-style: normal; text-decoration: none; fill: rgb(0, 0, 0); fill-opacity: 1; color: rgb(0, 0, 0); opacity: 1; text-align: center;"><div xmlns="http://www.w3.org/1999/xhtml"><span style="font-family: Consolas;">data_bind<br />styles_link / styles<br />classes_link / classes</span><br /></div></foreignObject>
</g></g></Content></Page><Page><Properties><Property name="name">navbar</Property><Property name="id">1421410510071_9693</Property><Property name="width">1531</Property><Property name="height">847</Property><Property name="dimBackground"/><Property name="transparentBackground">true</Property><Property name="backgroundColor">#FFFFFFFF</Property><Property name="background">transparent</Property></Properties><Content><g xmlns="http://www.w3.org/2000/svg" p:type="Group" xmlns:p="http://www.evolus.vn/Namespace/Pencil" transform="translate(126,121)" id="31a617e276fe4161a5e3b70380bb0e34" p:sizing-gow="490.5" p:sizing-goh="78"><g p:type="Shape" p:def="Evolus.Common:RoundedRect" id="fa8da9aed28744f5af9f11285080496c" transform="matrix(1,0,0,1,-1,-1)" p:sizing-ox="0" p:sizing-oy="0" p:sizing-ow="283" p:sizing-oh="80"><p:metadata><p:property name="box"><![CDATA[283,80]]></p:property><p:property name="withBlur"><![CDATA[false]]></p:property><p:property name="radius"><![CDATA[0,0]]></p:property><p:property name="textPadding"><![CDATA[0,10]]></p:property><p:property name="fillColor"><![CDATA[#CCCCCCFF]]></p:property><p:property name="strokeColor"><![CDATA[#000000FF]]></p:property><p:property name="strokeStyle"><![CDATA[2|]]></p:property><p:property name="textContent"><![CDATA[
]]></p:property><p:property name="textFont"><![CDATA["Liberation Sans",Arial,sans-serif|normal|normal|13px|none]]></p:property><p:property name="textColor"><![CDATA[#000000FF]]></p:property><p:property name="textAlign"><![CDATA[1,1]]></p:property></p:metadata>
<defs>
<rect width="281" height="78" rx="0" ry="0" x="0" y="0" style="stroke-width: 2; fill: rgb(204, 204, 204); fill-opacity: 1; stroke: rgb(0, 0, 0); stroke-opacity: 1;" p:name="rrRect" id="ea12bfd96e974a0f8f92afced67bdd6f" transform="translate(1,1)"/>
<filter height="1.2558399" y="-0.12792" width="1.06396" x="-0.03198" p:name="shadingFilter" id="d5043318357b49a1bb219a00f76eddd9">
<feGaussianBlur stdDeviation="1" in="SourceAlpha"/>
</filter>
</defs>
<use xlink:href="#ea12bfd96e974a0f8f92afced67bdd6f" xmlns:xlink="http://www.w3.org/1999/xlink" transform="translate(2, 2)" p:filter="url(#d5043318357b49a1bb219a00f76eddd9)" style="opacity: 0.5; visibility: hidden; display: none;" p:heavy="true" p:name="bgCopy" id="0d42ff0970ff472aa4c006ef85d8e87a"/>
<use xlink:href="#ea12bfd96e974a0f8f92afced67bdd6f" xmlns:xlink="http://www.w3.org/1999/xlink"/>
<foreignObject x="10" y="40" width="263" height="0" p:name="text" id="40018080392b490da490d8b286b95c41" style="font-family: &quot;Liberation Sans&quot;,Arial,sans-serif; font-size: 13px; font-weight: normal; font-style: normal; text-decoration: none; fill: rgb(0, 0, 0); fill-opacity: 1; color: rgb(0, 0, 0); opacity: 1; text-align: center;"><div xmlns="http://www.w3.org/1999/xhtml">
</div></foreignObject>
</g><g p:type="Shape" p:def="Evolus.Common:RoundedRect" id="5b845ca54039496591b80db2010a32bc" transform="matrix(1,0,0,1,122,15)" p:sizing-ox="123" p:sizing-oy="16" p:sizing-ow="144" p:sizing-oh="48"><p:metadata><p:property name="box"><![CDATA[144,48]]></p:property><p:property name="withBlur"><![CDATA[false]]></p:property><p:property name="radius"><![CDATA[0,0]]></p:property><p:property name="textPadding"><![CDATA[0,6]]></p:property><p:property name="fillColor"><![CDATA[#FFFFFFFF]]></p:property><p:property name="strokeColor"><![CDATA[#000000FF]]></p:property><p:property name="strokeStyle"><![CDATA[2|]]></p:property><p:property name="textContent"><![CDATA[
]]></p:property><p:property name="textFont"><![CDATA["Liberation Sans",Arial,sans-serif|normal|normal|13px|none]]></p:property><p:property name="textColor"><![CDATA[#000000FF]]></p:property><p:property name="textAlign"><![CDATA[1,1]]></p:property></p:metadata>
<defs>
<rect width="142" height="46" rx="0" ry="0" x="0" y="0" style="stroke-width: 2; fill: rgb(255, 255, 255); fill-opacity: 1; stroke: rgb(0, 0, 0); stroke-opacity: 1;" p:name="rrRect" id="480225b90d8842139e20649d22caa757" transform="translate(1,1)"/>
<filter height="1.2558399" y="-0.12792" width="1.06396" x="-0.03198" p:name="shadingFilter" id="db76ffd36668492aa45c3dacb4ed2d52">
<feGaussianBlur stdDeviation="1" in="SourceAlpha"/>
</filter>
</defs>
<use xlink:href="#480225b90d8842139e20649d22caa757" xmlns:xlink="http://www.w3.org/1999/xlink" transform="translate(2, 2)" p:filter="url(#db76ffd36668492aa45c3dacb4ed2d52)" style="opacity: 0.5; visibility: hidden; display: none;" p:heavy="true" p:name="bgCopy" id="125928c2b681488ba446768b095a76a5"/>
<use xlink:href="#480225b90d8842139e20649d22caa757" xmlns:xlink="http://www.w3.org/1999/xlink"/>
<foreignObject x="6" y="24" width="132" height="0" p:name="text" id="de5cbf018c224ba3adf8aed52ebc5f77" style="font-family: &quot;Liberation Sans&quot;,Arial,sans-serif; font-size: 13px; font-weight: normal; font-style: normal; text-decoration: none; fill: rgb(0, 0, 0); fill-opacity: 1; color: rgb(0, 0, 0); opacity: 1; text-align: center;"><div xmlns="http://www.w3.org/1999/xhtml">
</div></foreignObject>
</g><g xmlns="http://www.w3.org/2000/svg" p:type="Shape" xmlns:p="http://www.evolus.vn/Namespace/Pencil" p:def="Evolus.Common:PlainTextV2" id="3637818ac51540849a753285e83d950d" transform="matrix(1,0,0,1,132,35)" p:sizing-ox="130.3984375" p:sizing-oy="23" p:sizing-ow="60" p:sizing-oh="16"><p:metadata><p:property name="disabled"><![CDATA[false]]></p:property><p:property name="width"><![CDATA[100,0]]></p:property><p:property name="fixedWidth"><![CDATA[false]]></p:property><p:property name="label"><![CDATA[template]]></p:property><p:property name="textColor"><![CDATA[#000000FF]]></p:property><p:property name="textFont"><![CDATA[Consolas|normal|normal|13px|none]]></p:property><p:property name="textAlign"><![CDATA[0,0]]></p:property></p:metadata>
<rect x="0" y="0" style="fill: none; stroke: none; visibility: hidden; display: none;" p:name="bgRect" id="6f91157aa1354619ab2b7960baeb8cba" width="0" height="0"/>
<text xml:space="preserve" p:name="text" id="638334d0a39b4b39a7e4806254e2e418" style="fill: rgb(0, 0, 0); fill-opacity: 1; font-family: Consolas; font-size: 13px; font-weight: normal; font-style: normal; text-decoration: none;"><tspan x="0" y="0">template</tspan></text>
</g><g p:type="Shape" p:def="Evolus.Common:Balloon" id="c0be16ae150d4dc68b7bffdc19d19262" transform="matrix(1,0,0,1,294,7)" p:sizing-ox="266.5" p:sizing-oy="7.5" p:sizing-ow="196" p:sizing-oh="64"><p:metadata><p:property name="box"><![CDATA[196,64]]></p:property><p:property name="withBlur"><![CDATA[false]]></p:property><p:property name="radius"><![CDATA[7.84,0]]></p:property><p:property name="leftStart"><![CDATA[0,9.84]]></p:property><p:property name="leftEnd"><![CDATA[0,26.400000000000002]]></p:property><p:property name="rightStart"><![CDATA[196,9.84]]></p:property><p:property name="rightEnd"><![CDATA[196,26.400000000000002]]></p:property><p:property name="topStart"><![CDATA[11.76,0]]></p:property><p:property name="topEnd"><![CDATA[32.339999999999996,0]]></p:property><p:property name="bottomStart"><![CDATA[11.76,64]]></p:property><p:property name="bottomEnd"><![CDATA[32.339999999999996,64]]></p:property><p:property name="pin"><![CDATA[-28,18]]></p:property><p:property name="fillColor"><![CDATA[#FFFFFFFF]]></p:property><p:property name="strokeColor"><![CDATA[#1B3280FF]]></p:property><p:property name="strokeStyle"><![CDATA[2|]]></p:property><p:property name="textContent"><![CDATA[<span style="font-family: Consolas;">data_bind<br />styles<br />classes</span><br />]]></p:property><p:property name="textFont"><![CDATA["Liberation Sans",Arial,sans-serif|normal|normal|13px|none]]></p:property><p:property name="textColor"><![CDATA[#000000FF]]></p:property><p:property name="textAlign"><![CDATA[1,1]]></p:property></p:metadata>
<defs>
<filter height="1.2558399" y="-0.12792" width="1.06396" x="-0.03198" p:name="imageShading" id="f3a0f53acfa3492abf13b69eb2bf8e75">
<feGaussianBlur stdDeviation="1.3325" in="SourceAlpha"/>
</filter>
<g p:name="container" id="8eaa88f76ee748fdbb66142e124db376">
<path transform="translate(0.5 0.5)" style="stroke-width: 2; fill: rgb(255, 255, 255); fill-opacity: 1; stroke: rgb(27, 50, 128); stroke-opacity: 1;" p:name="rect" id="e5ed7702279b485f83a84e170232b245" d="M 7.84 0 L 188.16 0 C 193.38666666666666 0 196 2.6133333333333333 196 7.84 L 196 56.16 C 196 61.38666666666667 193.38666666666666 64 188.16 64 L 7.84 64 C 2.6133333333333333 64 0 61.38666666666667 0 56.16 L 0 26.400000000000002 L -28 18 L 0 9.84 L 0 7.84 C 0 2.6133333333333333 2.6133333333333333 0 7.84 0"/>
</g>
</defs>
<use xlink:href="#8eaa88f76ee748fdbb66142e124db376" xmlns:xlink="http://www.w3.org/1999/xlink" transform="translate(1, 1)" p:filter="url(#f3a0f53acfa3492abf13b69eb2bf8e75)" style="opacity: 0.6; visibility: hidden; display: none;" p:heavy="true" p:name="bgCopy" id="e7a7687af8d14f2888d588636e0cd333"/>
<use xlink:href="#8eaa88f76ee748fdbb66142e124db376" xmlns:xlink="http://www.w3.org/1999/xlink"/>
<foreignObject x="7.84" y="7" width="180.32" height="50" p:name="text" id="cdcded6607b7463ea18aa393da7520bc" style="font-family: &quot;Liberation Sans&quot;,Arial,sans-serif; font-size: 13px; font-weight: normal; font-style: normal; text-decoration: none; fill: rgb(0, 0, 0); fill-opacity: 1; color: rgb(0, 0, 0); opacity: 1; text-align: center;"><div xmlns="http://www.w3.org/1999/xhtml"><span style="font-family: Consolas;">data_bind<br />styles<br />classes</span><br /></div></foreignObject>
</g></g></Content></Page></Pages></Document>
+4 -3
View File
@@ -6,16 +6,17 @@ Welcome to OctoPrint's documentation!
:alt: The OctoPrint Logo
:align: right
This is a work in progress. The goal is to document OctoPrint's REST API, event system, configuration etc in a way that
allows different documentation per development branch in Git, which so far did not scale well with the Github-Wiki-based
approach.
Contents
========
.. toctree::
:maxdepth: 2
features/index.rst
configuration/index.rst
api/index.rst
events/index.rst
plugins/index.rst
modules/index.rst
-39
View File
@@ -1,39 +0,0 @@
.. _sec-modules-filemanager:
octoprint.filemanager
---------------------
.. automodule:: octoprint.filemanager
:members:
.. _sec-modules-filemanager-analysis:
octoprint.filemanager.analysis
------------------------------
.. automodule:: octoprint.filemanager.analysis
:members:
.. _sec-modules-filemanager-destinations:
octoprint.filemanager.destinations
----------------------------------
.. automodule:: octoprint.filemanager.destinations
:members:
.. _sec-modules-filemanager-storage:
octoprint.filemanager.storage
-----------------------------
.. automodule:: octoprint.filemanager.storage
:members: StorageInterface, LocalFileStorage
.. _sec-modules-filemanager-util:
octoprint.filemanager.util
--------------------------
.. automodule:: octoprint.filemanager.util
:members:
-16
View File
@@ -1,16 +0,0 @@
.. _sec-modules:
################
Internal Modules
################
.. toctree::
:maxdepth: 3
filemanager.rst
plugin.rst
printer.rst
server.rst
settings.rst
slicing.rst
util.rst
-20
View File
@@ -1,20 +0,0 @@
.. _sec-modules-plugin:
octoprint.plugin
----------------
.. automodule:: octoprint.plugin
.. _sec-modules-plugin-core:
octoprint.plugin.core
---------------------
.. automodule:: octoprint.plugin.core
.. _sec-modules-plugin-types:
octoprint.plugin.types
----------------------
.. automodule:: octoprint.plugin.types
-6
View File
@@ -1,6 +0,0 @@
.. _sec-modules-printer:
octoprint.printer
-----------------
.. automodule:: octoprint.printer
-42
View File
@@ -1,42 +0,0 @@
.. _sec-modules-server:
octoprint.server
----------------
.. automodule:: octoprint.server
:members:
.. _sec-modules-server-util:
octoprint.server.util
---------------------
.. automodule:: octoprint.server.util
:members:
.. _sec-modules-server-util-flask:
octoprint.server.util.flask
---------------------------
.. automodule:: octoprint.server.util.flask
:members:
.. _sec-modules-server-util-sockjs:
octoprint.server.util.sockjs
----------------------------
.. automodule:: octoprint.server.util.sockjs
:members:
.. _sec-modules-server-util-tornado:
octoprint.server.util.tornado
-----------------------------
.. automodule:: octoprint.server.util.tornado
:members:
-6
View File
@@ -1,6 +0,0 @@
.. _sec-modules-settings:
octoprint.settings
------------------
.. automodule:: octoprint.settings
-13
View File
@@ -1,13 +0,0 @@
.. _sec-modules-slicing:
octoprint.slicing
-----------------
.. automodule:: octoprint.slicing
.. _sec-modules-slicing-exceptions:
octoprint.slicing.exceptions
----------------------------
.. automodule:: octoprint.slicing.exceptions
-9
View File
@@ -1,9 +0,0 @@
.. _sec-modules-util:
octoprint.util
--------------
.. automodule:: octoprint.util
:members:
-347
View File
@@ -1,347 +0,0 @@
.. _sec-plugin-concepts:
Concepts
========
.. contents::
:local:
OctoPrint's plugins are `Python Packages <https://docs.python.org/2/tutorial/modules.html#packages>`_ which in their
top-level module define a bunch of :ref:`control properties <sec-plugin-concepts-controlproperties>` defining
metadata (like name, version etc of the plugin) as well as information on how to initialize the plugin and into what
parts of the system the plugin will actually plug in to perform its job.
There are three types of ways a plugin might attach itself to the system, through so called
:ref:`mixin <sec-plugin-concepts-mixins>` implementations, by attaching itself to specified
:ref:`hook <sec-plugin-concepts-hooks>` or by offering :ref:`helper <sec-plugin-concepts-helpers>` functionality to be
used by other plugins.
Plugin mixin implementations will get a bunch of :ref:`properties injected <sec-plugins-concepts-injectedproperties>`
by OctoPrint plugin system to help them work.
.. _sec-plugin-concepts-controlproperties:
Control Properties
------------------
As already mentioned above, plugins are Python packages which provide certain pieces of metadata to tell OctoPrint's
plugin subsystem about themselves. These are simple package attributes defined in the top most package file, e.g.:
.. code-block:: python
import octoprint.plugin
# ...
__plugin_name__ = "My Plugin"
def __plugin_load__():
# whatever you need to do to load your plugin, if anything at all
pass
The following properties are recognized:
``__plugin_name__``
Name of your plugin, optional, overrides the name specified in ``setup.py`` if provided. If neither this property nor
a name from ``setup.py`` is available to the plugin subsystem, the plugin's identifier (= package name) will be
used instead.
``__plugin_version__``
Version of your plugin, optional, overrides the version specified in ``setup.py`` if provided.
``__plugin_description__``
Description of your plugin, optional, overrides the description specified in ``setup.py`` if provided.
``__plugin_author__``
Author of your plugin, optional, overrides the author specified in ``setup.py`` if provided.
``__plugin_url__``
URL of the webpage of your plugin, e.g. the Github repository, optional, overrides the URL specified in ``setup.py`` if
provided.
``__plugin_license__``
License of your plugin, optional, overrides the license specified in ``setup.py`` if provided.
``__plugin_implementation__``
Instance of an implementation of one or more :ref:`plugin mixins <sec-plugins-mixins>`.
``__plugin_hooks__``
Handlers for one or more of the various :ref:`plugin hooks <sec-plugins-hooks>`.
``__plugin_check__``
Method called upon discovery of the plugin by the plugin subsystem, should return ``True`` if the
plugin can be instantiated later on, ``False`` if there are reasons why not, e.g. if dependencies
are missing.
``__plugin_load__``
Method called upon loading of the plugin by the plugin subsystem, can be used to instantiate
plugin implementations, connecting them to hooks etc.
``__plugin_unload__``
Method called upon unloading of the plugin by the plugin subsystem, can be used to do any final clean ups.
``__plugin_enable__``
Method called upon enabling of the plugin by the plugin subsystem. Also see :func:`~octoprint.plugin.core.Plugin.on_plugin_enabled``.
``__plugin_disable__``
Method called upon disabling of the plugin by the plugin subsystem. Also see :func:`~octoprint.plugin.core.Plugin.on_plugin_disabled``.
.. _sec-plugin-concepts-mixins:
Mixins
------
Plugin mixins are the heart of OctoPrint's plugin system. They are :ref:`special base classes <sec-plugins-mixins>`
which are to be subclassed and extended to add functionality to OctoPrint. Plugins declare their instances that
implement one or multiple mixins using the ``__plugin_implementation__`` control property. OctoPrint's plugin core
collects those from the plugins and offers methods to access them based on the mixin type, which get used at multiple
locations within OctoPrint.
Using mixins always follows the pattern of retrieving the matching implementations from the plugin subsystem, then
calling the specific mixin's methods as defined and necessary.
The following snippet taken from OctoPrint's code for example shows how all :class:`~octoprint.plugin.AssetPlugin`
implementations are collected and then all assets they return via their ``get_assets`` methods are retrieved and
merged into one big asset map (differing between javascripts and stylesheets of various types) for use during
rendition of the UI.
.. code-block:: python
:linenos:
asset_plugins = pluginManager.get_implementations(octoprint.plugin.AssetPlugin)
for name, implementation in asset_plugins.items():
all_assets = implementation.get_assets()
if "js" in all_assets:
for asset in all_assets["js"]:
assets["js"].append(url_for('plugin_assets', name=name, filename=asset))
if preferred_stylesheet in all_assets:
for asset in all_assets[preferred_stylesheet]:
assets["stylesheets"].append((preferred_stylesheet, url_for('plugin_assets', name=name, filename=asset)))
else:
for stylesheet in supported_stylesheets:
if not stylesheet in all_assets:
continue
for asset in all_assets[stylesheet]:
assets["stylesheets"].append((stylesheet, url_for('plugin_assets', name=name, filename=asset)))
break
.. seealso::
:ref:`Available Mixins <sec-plugins-mixins>`
An overview of all mixin types available for extending OctoPrint.
:ref:`The Getting Started Guide <sec-plugins-gettingstarted>`
Tutorial on how to write a simple OctoPrint module utilizing mixins for various types of extension.
.. _sec-plugin-concepts-hooks:
Hooks
-----
Hooks are the smaller siblings of mixins, allowing to extend functionality or data processing where a custom mixin type
would be too much overhead. Where mixins are based on classes, hooks are based on methods. Like with the mixin
implementations, plugins inform OctoPrint about hook handlers using a control property, ``__plugin_hooks__``.
Each hook defines a contract detailing the call parameters for the hook handler method and the expected return type.
OctoPrint will call the hook with the define parameters and process the result depending on the hook.
An example for a hook within OctoPrint is ``octoprint.comm.protocol.scripts``, which allows adding additional
lines to OctoPrint's :ref:`GCODE scripts <sec-features-gcode_scripts>`, either as ``prefix`` (before the existing lines)
or as ``postfix`` (after the existing lines).
.. code-block:: python
:linenos:
self._gcode_hooks = self._pluginManager.get_hooks("octoprint.comm.protocol.scripts")
# ...
for hook in self._gcodescript_hooks:
try:
retval = self._gcodescript_hooks[hook](self, "gcode", scriptName)
except:
self._logger.exception("Error while processing gcodescript hook %s" % hook)
else:
if retval is None:
continue
if not isinstance(retval, (list, tuple)) or not len(retval) == 2:
continue
def to_list(data):
if isinstance(data, str):
data = map(str.strip, data.split("\n"))
elif isinstance(data, unicode):
data = map(unicode.strip, data.split("\n"))
if isinstance(data, (list, tuple)):
return list(data)
else:
return None
prefix, suffix = map(to_list, retval)
if prefix:
scriptLines = list(prefix) + scriptLines
if suffix:
scriptLines += list(suffix)
As you can see, the hook's method signature is defined to take the current ``self`` (as in, the current comm layer instance),
the general type of script for which to look for additions ("gcode") and the script name for which to look (e.g.
``beforePrintStarted`` for the GCODE script executed before the beginning of a print job). The hook is expected to
return a 2-tuple of prefix and postfix if has something for either of those, otherwise ``None``. OctoPrint will then take
care to add prefix and suffix as necessary after a small round of preprocessing.
.. note::
At the moment there exists no way to determine the execution order of various hook handlers within OctoPrint,
or to prevent the execution of further handlers down the chain.
This is planned for the very near future though.
Plugins can easily add their own hooks too. For example, the `Software Update Plugin <https://github.com/OctoPrint/OctoPrint-SoftwareUpdate>`_
declares a custom hook "octoprint.plugin.softwareupdate.check_config" which other plugins can add handlers for in order
to register themselves with the Software Update Plugin by returning their own update check configuration.
If you want your hook handler to be an instance method of a mixin implementation of your plugin (for example since you
need access to instance variables handed to your implementation via mixin invocations), you can get this work
by using a small trick. Instead of defining it directly via ``__plugin_hooks__`` utilize the ``__plugin_load__``
property instead, manually instantiate your implementation instance and then add its hook handler method to the
``__plugin_hooks__`` property and itself to the ``__plugin_implementation__`` property. See the following example.
.. onlineinclude:: https://raw.githubusercontent.com/OctoPrint/Plugin-Examples/master/custom_action_command.py
:linenos:
:tab-width: 4
:caption: `custom_action_command.py <https://github.com/OctoPrint/Plugin-Examples/blob/master/custom_action_command.py>`_
:name: sec-plugin-concepts-hooks-example
.. seealso::
:ref:`Available Hooks <sec-plugins-hooks>`
An overview of all hooks defined in OctoPrint itself.
.. _sec-plugin-concepts-helpers:
Helpers
-------
Helpers are methods that plugin can exposed to other plugins in order to make common functionality available on the
system. They are registered with the OctoPrint plugin system through the use of the control property ``__plugin_helpers__``.
An example for providing a couple of helper functions to the system can be found in the
`Discovery Plugin <https://github.com/foosel/OctoPrint/wiki/Plugin:-Discovery>`_,
which provides it's SSDP browsing and Zeroconf browsing and publishing functions as helper methods.
.. code-block:: python
:linenos:
:emphasize-lines: 11-20
:caption: Excerpt from the Discovery Plugin showing the declaration of its exported helpers.
:name: sec-plugin-concepts-helpers-example-export
def __plugin_load__():
if not pybonjour:
# no pybonjour available, we can't use that
logging.getLogger("octoprint.plugins." + __name__).info("pybonjour is not installed, Zeroconf Discovery won't be available")
plugin = DiscoveryPlugin()
global __plugin_implementation__
__plugin_implementation__ = plugin
global __plugin_helpers__
__plugin_helpers__ = dict(
ssdp_browse=plugin.ssdp_browse
)
if pybonjour:
__plugin_helpers__.update(dict(
zeroconf_browse=plugin.zeroconf_browse,
zeroconf_register=plugin.zeroconf_register,
zeroconf_unregister=plugin.zeroconf_unregister
))
An example of how to use helpers can be found in the `Growl Plugin <https://github.com/OctoPrint/OctoPrint-Growl>`_.
Using :meth:`~octoprint.plugin.code.PluginManager.get_helpers` plugins can retrieve exported helper methods and call
them as (hopefully) documented.
.. code-block:: python
:linenos:
:emphasize-lines: 6-8,20
:caption: Excerpt from the Growl Plugin showing utilization of the helpers published by the Discovery Plugin.
:name: sec-plugin-concepts-helpers-example-usage
def on_after_startup(self):
host = self._settings.get(["hostname"])
port = self._settings.getInt(["port"])
password = self._settings.get(["password"])
helpers = self._plugin_manager.get_helpers("discovery", "zeroconf_browse")
if helpers and "zeroconf_browse" in helpers:
self.zeroconf_browse = helpers["zeroconf_browse"]
self.growl, _ = self._register_growl(host, port, password=password)
# ...
def on_api_get(self, request):
if not self.zeroconf_browse:
return flask.jsonify(dict(
browsing_enabled=False
))
browse_results = self.zeroconf_browse("_gntp._tcp", block=True)
growl_instances = [dict(name=v["name"], host=v["host"], port=v["port"]) for v in browse_results]
return flask.jsonify(dict(
browsing_enabled=True,
growl_instances=growl_instances
))
.. _sec-plugins-concepts-injectedproperties:
Injected Properties
-------------------
OctoPrint's plugin subsystem will inject a bunch of properties into each :ref:`mixin implementation <sec-plugin-concepts-mixins>`.
An overview of these properties follows.
``self._identifier``
The plugin's identifier.
``self._plugin_name``
The plugin's name, as taken from either the ``__plugin_name__`` control property or the package info.
``self._plugin_version``
The plugin's version, as taken from either the ``__plugin_version__`` control property or the package info.
``self._basefolder``
The plugin's base folder where it's installed. Can be used to refer to files relative to the plugin's installation
location, e.g. included scripts, templates or assets.
``self._datafolder``
The plugin's additional data folder path. Can be used to store additional files needed for the plugin's operation (cache,
data files etc). Plugins should not access this property directly but instead utilize :func:`~octoprint.plugin.types.OctoPrintPlugin.get_plugin_data_folder`
which will make sure the path actually does exist and if not create it before returning it.
``self._logger``
A `python logger instance <https://docs.python.org/2/library/logging.html>`_ logging to the log target
``octoprint.plugin.<plugin identifier>``.
``self._settings``
The plugin's personalized settings manager, injected only into plugins that include the :class:`~octoprint.plugin.SettingsPlugin` mixin.
An instance of :class:`octoprint.plugin.PluginSettings`.
``self._plugin_manager``
OctoPrint's plugin manager object, an instance of :class:`octoprint.plugin.core.PluginManager`.
``self._printer_profile_manager``
OctoPrint's printer profile manager, an instance of :class:`octoprint.printer.profile.PrinterProfileManager`.
``self._event_bus``
OctoPrint's event bus, an instance of :class:`octoprint.events.EventManager`.
``self._analysis_queue``
OctoPrint's analysis queue for analyzing GCODEs or other files, an instance of :class:`octoprint.filemanager.analysis.AnalysisQueue`.
``self._slicing_manager``
OctoPrint's slicing manager, an instance of :class:`octoprint.slicing.SlicingManager`.
``self._file_manager``
OctoPrint's file manager, an instance of :class:`octoprint.filemanager.FileManager`.
``self._printer``
OctoPrint's printer management object, an instance of :class:`octoprint.printer.PrinterInterface`.
``self._app_session_manager``
OctoPrint's application session manager, an instance of :class:`octoprint.server.util.flask.AppSessionManager`.
.. seealso::
:class:`~octoprint.plugin.core.Plugin` and :class:`~octoprint.plugin.types.OctoPrintPlugin`
Class documentation also containing the properties shared among all mixing implementations.
:ref:`Available Mixins <sec-plugins-mixins>`
Some mixin types trigger the injection of additional properties.
.. _sec-plugins-concept-lifecycle:
Lifecycle
---------
.. image:: ../images/plugins_lifecycle.png
:align: center
:alt: The lifecycle of OctoPrint plugins.
+19
View File
@@ -0,0 +1,19 @@
.. _sec-plugins-developing:
******************
Developing Plugins
******************
.. todo::
A section on how to develop plugins yourself, including a tutorial creating an exemplary plugin as well as
a documentation of the plugin API, will be added in the near future.
.. _sec-plugins-developing-types:
Available plugin types
======================
.. automodule:: octoprint.plugin.types
:members:
:undoc-members:
-49
View File
@@ -1,49 +0,0 @@
.. _sec-plugins-distribution:
Distributing your plugin
========================
You can distribute a plugin with OctoPrint via two ways.
.. contents::
:local:
.. _sec-plugins-distribution-manual:
Manual file distribution
------------------------
You can have your users copy it to OctoPrint's plugin folder (normally located at ``~/.octoprint/plugins`` under Linux,
``%APPDATA%\OctoPrint\plugins`` on Windows and ... on Mac). In this case your plugin will be distributed directly
as a Python module (a single ``.py`` file containing all of your plugin's code directly and named
like your plugin) or a package (a folder named like your plugin + ``__init.py__`` contained within).
.. _sec-plugins-distribution-pip:
Proper packages installable via pip
-----------------------------------
You can have your users install it via ``pip`` and register it for the `entry point <https://pythonhosted.org/setuptools/setuptools.html#dynamic-discovery-of-services-and-plugins>`_ ``octoprint.plugin`` via
your plugin's ``setup.py``, this way it will be found automatically by OctoPrint upon initialization of the
plugin subsystem [#f1]_.
For an example of how the directory structure and related files would look like in this case, please take a
look at the `helloworld example from OctoPrint's example plugins <https://github.com/OctoPrint/Plugin-Examples/tree/master/helloworld>`_.
This variant is highly recommended for pretty much any plugin besides the most basic ones since it also allows
requirements management and pretty much any thing else that Python's setuptools provide to the developer.
.. seealso::
`OctoPrint Plugin Skeleton <https://github.com/OctoPrint/OctoPrint-PluginSkeleton>`_
A basic plugin skeleton providing you with all you need to get started with distributing your plugin as a proper
package. See the :ref:`Getting Started Guide <sec-plugins-gettingstarted>` for an
:ref:`example <sec-plugins-gettingstarted-growingup>` on how to use this.
.. rubric:: Footnotes
.. [#f1] The automatic registration will only work within the same Python installation (this also includes virtual
environments), so make sure to instruct your users to use the exact same Python installation for installing
the plugin that they also used for installing & running OctoPrint. For OctoPi this means using
``~/oprint/bin/pip`` for installing plugins instead of just ``pip``.
File diff suppressed because it is too large. Load diff
-546
View File
@@ -1,546 +0,0 @@
.. _sec-plugins-hooks:
Available plugin hooks
======================
.. note::
All of the hooks below take at least two parameters, ``*args`` and ``**kwargs``. Please make sure those are present.
They will act as placeholders if additional parameters are added to the hooks in the future and will allow
your plugin to stay compatible to OctoPrint without any necessary adjustments from you in these cases.
.. contents::
:local:
.. _sec-plugins-hook-accesscontrol-appkey:
octoprint.accesscontrol.appkey
------------------------------
.. py:function:: hook(*args, **kwargs)
By handling this hook plugins may register additional :ref:`App session key providers <sec-api-apps-sessionkey>`
within the system.
Overrides this to return your additional app information to be used for validating app session keys. You'll
need to return a list of 3-tuples of the format (id, version, public key).
The ``id`` should be the (unique) identifier of the app. Using a domain prefix might make sense here, e.g.
``org.octoprint.example.MyApp``.
``version`` should be a string specifying the version of the app for which the public key is valid. You can
provide the string ``any`` here, in which case the provided public key will be valid for all versions of the
app for which no specific public key is defined.
Finally, the public key is expected to be provided as a PKCS1 string without newlines.
:return: A list of 3-tuples as described above
:rtype: list
.. _sec-plugins-hook-comm-protocol-action:
octoprint.comm.protocol.action
------------------------------
.. py:function:: hook(comm_instance, line, action, *args, **kwargs)
React to a :ref:`action command <sec-features-action_commands>` received from the printer.
Hook handlers may use this to react to react to custom firmware messages. OctoPrint parses the received action
command ``line`` and provides the parsed ``action`` (so anything after ``// action:``) to the hook handler.
No returned value is expected.
**Example:**
Logs if the ``custom`` action (``// action:custom``) is received from the printer's firmware.
.. onlineinclude:: https://raw.githubusercontent.com/OctoPrint/Plugin-Examples/master/custom_action_command.py
:linenos:
:tab-width: 4
:caption: `custom_action_command.py <https://github.com/OctoPrint/Plugin-Examples/blob/master/custom_action_command.py>`_
:param object comm_instance: The :class:`~octoprint.util.comm.MachineCom` instance which triggered the hook.
:param str line: The complete line as received from the printer, format ``// action:<command>``
:param str action: The parsed out action command, so for a ``line`` like ``// action:some_command`` this will be
``some_command``
.. _sec-plugins-hook-comm-protocol-gcode-phase:
octoprint.comm.protocol.gcode.<phase>
-------------------------------------
This describes actually four hooks:
* ``octoprint.comm.protocol.gcode.queuing``
* ``octoprint.comm.protocol.gcode.queued``
* ``octoprint.comm.protocol.gcode.sending``
* ``octoprint.comm.protocol.gcode.sent``
.. py:function:: hook(comm_instance, phase, cmd, cmd_type, gcode, *args, **kwargs)
Pre- and postprocess commands as they progress through the various phases of being sent to the printer. The phases
are the following:
* ``queuing``: This phase is triggered just before the command is added to the send queue of the communication layer. This
corresponds to the moment a command is being read from a file that is currently being printed. Handlers
may suppress or change commands or their command type here.
* ``queued``: This phase is triggered just after the command was added to the send queue of the communication layer.
No manipulation is possible here anymore (returned values will be ignored).
* ``sending``: This phase is triggered just before the command is actually being sent to the printer. Right afterwards
a line number will be assigned and the command will be sent. Handlers may suppress or change commands here. The
command type is not taken into account anymore.
* ``sent``: This phase is triggered just after the command was handed over to the serial connection to the printer.
No manipulation is possible here anymore (returned values will be ignored). A command that reaches the sent phase
must not necessarily have reached the printer yet and it might also still run into communication problems and a
resend might be triggered for it.
Hook handlers may use this to rewrite or completely suppress certain commands before they enter the send queue of
the communication layer or before they are actually sent over the serial port, or to react to the queuing or sending
of commands after the fact. The hook handler will be called with the processing ``phase``, the ``cmd`` to be sent to
the printer as well as the ``cmd_type`` parameter used for enqueuing (OctoPrint will make sure that the send queue
will never contain more than one line with the same ``cmd_type``) and the detected gcode command (if it is one).
Defining a ``cmd_type`` other than None will make sure OctoPrint takes care of only having one command of that type
in its sending queue. Predefined types are ``temperature_poll`` for temperature polling via ``M105`` and
``sd_status_poll`` for polling the SD printing status via ``M27``.
``phase`` will always match the ``<phase>`` part of the implemented hook (e.g. ``octoprint.comm.protocol.gcode.queued``
handlers will always be called with ``phase`` set to ``queued``). This parameter is provided so that plugins may
utilize the same hook for mulitple phases if required.
Handlers are expected to return one of the following result variants:
* ``None``: Don't change anything. Note that Python functions will also automatically return ``None`` if
an empty ``return`` statement is used or just nothing is returned explicitely from the handler. Hence, the following
examples are all falling into this category:
.. code-block:: python
def one(*args, **kwargs):
print("I return None explicitly")
return None
def two(*args, **kwargs):
print("I just return without any values")
return
def three(*args, **kwargs):
print("I don't explicitly return anything at all")
Handlers which do not wish to modify (or suppress) ``cmd`` or ``cmd_type`` at all should use this option.
* A string with the rewritten version of the ``cmd``, e.g. ``return "M110"``. To avoid situations which will be
difficult to debug should the returned command be later changed to ``None`` (with the intent to suppress the
command instead but actually causing ``cmd`` and ``cmd_type`` to just staying as-is), this variant should be
entirely avoided by handlers.
* A 1-tuple consisting of a rewritten version of the ``cmd``, e.g. ``return "M110",``, or ``None`` in order to
suppress the command, e.g. ``return None,``. Handlers which wish to rewrite the command or to suppress it completely
should use this option.
* A 2-tuple consisting of a rewritten version of the ``cmd`` and the ``cmd_type``, e.g. ``return "M105", "temperature_poll"``.
Handlers which wish to rewrite both the command and the command type should use this option.
**Example**
The following hook handler replaces all ``M107`` ("Fan Off", deprecated) with an ``M106 S0`` ("Fan On" with speed
parameter) upon queuing and logs all sent ``M106``.
.. onlineinclude:: https://raw.githubusercontent.com/OctoPrint/Plugin-Examples/master/rewrite_m107.py
:linenos:
:tab-width: 4
:caption: `rewrite_m107.py <https://github.com/OctoPrint/Plugin-Examples/blob/master/rewrite_m107.py>`_
:param object comm_instance: The :class:`~octoprint.util.comm.MachineCom` instance which triggered the hook.
:param str phase: The current phase in the command progression, either ``queuing``, ``queued``, ``sending`` or
``sent``. Will always match the ``<phase>`` of the hook.
:param str cmd: The GCODE command for which the hook was triggered. This is the full command as taken either
from the currently streamed GCODE file or via other means (e.g. user input our status polling).
:param str cmd_type: Type of command, e.g. ``temperature_poll`` for temperature polling or ``sd_status_poll`` for SD
printing status polling.
:param str gcode: Parsed GCODE command, e.g. ``G0`` or ``M110``, may also be None if no known command could be parsed
:return: None, 1-tuple, 2-tuple or string, see the description above for details.
.. _sec-plugins-hook-comm-protocol-scripts:
octoprint.comm.protocol.scripts
-------------------------------
.. py:function:: hook(comm_instance, script_type, script_name, *args, **kwargs)
Return a prefix to prepend and a postfix to append to the script ``script_name`` of type ``type``. Handlers should
make sure to only proceed with returning additional scripts if the ``script_type`` and ``script_name`` match
handled scripts. If not, None should be returned directly.
If the hook handler has something to add to the specified script, it may return a 2-tuple, with the first entry
defining the prefix (what to *prepend* to the script in question) and the last entry defining the postfix (what to
*append* to the script in question). Both prefix and postfix can be None to signify that nothing should be prepended
respectively appended.
The returned entries may be either iterables of script lines or a string including newlines of the script lines (which
will be split by the caller if necessary).
**Example:**
Appends an ``M117 OctoPrint connected`` to the configured ``afterPrinterConnected`` GCODE script.
.. onlineinclude:: https://raw.githubusercontent.com/OctoPrint/Plugin-Examples/master/message_on_connect.py
:linenos:
:tab-width: 4
:caption: `message_on_connect.py <https://github.com/OctoPrint/Plugin-Examples/blob/master/message_on_connect.py>`_
:param MachineCom comm_instance: The :class:`~octoprint.util.comm.MachineCom` instance which triggered the hook.
:param str script_type: The type of the script for which the hook was called, currently only "gcode" is supported here.
:param str script_name: The name of the script for which the hook was called.
:return: A 2-tuple in the form ``(prefix, postfix)`` or None
:rtype: tuple or None
.. _sec-plugins-hook-comm-transport-serial-factory:
octoprint.comm.transport.serial.factory
---------------------------------------
.. py:function:: hook(comm_instance, port, baudrate, read_timeout, *args, **kwargs)
Return a serial object to use as serial connection to the printer. If a handler cannot create a serial object
for the specified ``port`` (and ``baudrate``), it should just return ``None``.
If the hook handler needs to perform state switches (e.g. for autodetection) or other operations on the
:class:`~octoprint.util.comm.MachineCom` instance, it can use the supplied ``comm_instance`` to do so. Plugin
authors should keep in mind however that due to a pending change in the communication layer of
OctoPrint, that interface will change in the future. Authors are advised to follow OctoPrint's development
closely if directly utilizing :class:`~octoprint.util.comm.MachineCom` functionality.
A valid serial instance is expected to provide the following methods, analogue to PySerial's
`serial.Serial <https://pythonhosted.org//pyserial/pyserial_api.html#serial.Serial>`_:
readline(size=None, eol='\n')
Reads a line from the serial connection, compare `serial.Filelike.readline <https://pythonhosted.org//pyserial/pyserial_api.html#serial.FileLike.readline>`_.
write(data)
Writes data to the serial connection, compare `serial.Filelike.write <https://pythonhosted.org//pyserial/pyserial_api.html#serial.FileLike.write>`_.
close()
Closes the serial connection, compare `serial.Serial.close <https://pythonhosted.org//pyserial/pyserial_api.html#serial.Serial.close>`_.
Additionally setting the following attributes need to be supported if baudrate detection is supposed to work:
baudrate
An integer describing the baudrate to use for the serial connection, compare `serial.Serial.baudrate <https://pythonhosted.org//pyserial/pyserial_api.html#serial.Serial.baudrate>`_.
timeout
An integer describing the read timeout on the serial connection, compare `serial.Serial.timeout <https://pythonhosted.org//pyserial/pyserial_api.html#serial.Serial.timeout>`_.
**Example:**
Serial factory similar to the default one which performs auto detection of the serial port if ``port`` is ``None``
or ``AUTO``.
.. code-block:: python
:linenos:
def default(comm_instance, port, baudrate, connection_timeout):
if port is None or port == 'AUTO':
# no known port, try auto detection
comm_instance._changeState(comm_instance.STATE_DETECT_SERIAL)
serial_obj = comm_instance._detectPort(False)
if serial_obj is None:
comm_instance._log("Failed to autodetect serial port")
comm_instance._errorValue = 'Failed to autodetect serial port.'
comm_instance._changeState(comm_instance.STATE_ERROR)
eventManager().fire(Events.ERROR, {"error": comm_instance.getErrorString()})
return None
else:
# connect to regular serial port
comm_instance._log("Connecting to: %s" % port)
if baudrate == 0:
serial_obj = serial.Serial(str(port), 115200, timeout=connection_timeout, writeTimeout=10000, parity=serial.PARITY_ODD)
else:
serial_obj = serial.Serial(str(port), baudrate, timeout=connection_timeout, writeTimeout=10000, parity=serial.PARITY_ODD)
serial_obj.close()
serial_obj.parity = serial.PARITY_NONE
serial_obj.open()
return serial_obj
:param MachineCom comm_instance: The :class:`~octoprint.util.comm.MachineCom` instance which triggered the hook.
:param str port: The port for which to construct a serial instance. May be ``None`` or ``AUTO`` in which case port
auto detection is to be performed.
:param int baudrate: The baudrate for which to construct a serial instance. May be 0 in which case baudrate auto
detection is to be performed.
:param int read_timeout: The read timeout to set on the serial port.
:return: The constructed serial object ready for use, or ``None`` if the handler could not construct the object.
:rtype: A serial instance implementing implementing the methods ``readline(...)``, ``write(...)``, ``close()`` and
optionally ``baudrate`` and ``timeout`` attributes as described above.
.. _sec-plugins-hook-filemanager-extensiontree:
octoprint.filemanager.extension_tree
------------------------------------
.. py:function:: hook(*args, **kwargs)
Return additional entries for the tree of accepted file extensions for uploading/handling by the file manager.
Should return a dictionary to merge with the existing extension tree, adding additional extension groups to
``machinecode`` or ``model`` types.
**Example:**
The following handler would add a new file type "x3g" as accepted ``machinecode`` format, with extensions ``x3g``
and ``s3g``:
.. code-block:: python
:linenos:
def support_x3g_machinecode(*args, **kwargs):
return dict(
machinecode=dict(
x3g=["x3g", "s3g"]
)
)
.. note::
This will only add the supplied extensions to the extension tree, allowing the files to be uploaded and managed
through the file manager. Plugins will need to add further steps to ensure that the files will be processable
in the rest of the system (e.g. handling/preprocessing new machine code file types for printing etc)!
:return: The partial extension tree to merge with the full extension tree.
:rtype: dict
.. _sec-plugins-hook-filemanager-preprocessor:
octoprint.filemanager.preprocessor
----------------------------------
.. py:function:: hook(path, file_object, links=None, printer_profile=None, allow_overwrite=False, *args, **kwargs)
Replace the ``file_object`` used for saving added files to storage by calling :func:`~octoprint.filemanager.util.AbstractFileWrapper.save`.
``path`` will be the future path of the file on the storage. The file's name is accessible via
:attr:`~octoprint.filemanager.util.AbstractFileWrapper.filename`.
``file_object`` will be a subclass of :class:`~octoprint.filemanager.util.AbstractFileWrapper`. Handlers may
access the raw data of the file via :func:`~octoprint.filemanager.util.AbstractFileWrapper.stream`, e.g.
to wrap it further. Handlers which do not wish to handle the `file_object`
**Example**
The following plugin example strips all comments from uploaded/generated GCODE files ending on the name postfix ``_strip``.
.. onlineinclude:: https://raw.githubusercontent.com/OctoPrint/Plugin-Examples/master/strip_all_comments.py
:linenos:
:tab-width: 4
:caption: `strip_all_comments.py <https://github.com/OctoPrint/Plugin-Examples/blob/master/strip_all_comments.py>`_
:param str path: The path on storage the `file_object` is to be stored
:param AbstractFileWrapper file_object: The :class:`~octoprint.filemanager.util.AbstractFileWrapper` instance
representing the file object to store.
:param dict links: The links that are going to be stored with the file.
:param dict printer_profile: The printer profile associated with the file.
:param boolean allow_overwrite: Whether to allow overwriting an existing file named the same or not.
:return: The `file_object` as passed in or None, or a replaced version to use instead for further processing.
:rtype: AbstractFileWrapper or None
.. _sec-plugins-hook-server-http-bodysize:
octoprint.server.http.bodysize
------------------------------
.. py:function:: hook(current_max_body_sizes, *args, **kwargs)
Allows extending the list of custom maximum body sizes on the web server per path and HTTP method with custom entries
from plugins.
Your plugin might need this if you want to allow uploading files larger than 100KB (the default maximum upload size
for anything but the ``/api/files`` endpoint).
``current_max_body_sizes`` will be a (read-only) list of the currently configured maximum body sizes, in case you
want to check from your plugin if you need to even add a new entry.
The hook must return a list of 3-tuples (the list's length can be 0). Each 3-tuple should have the HTTP method
against which to match as first, a regular expression for the path to match against and the maximum body size as
an integer as the third entry.
The path of the route will be prefixed by OctoPrint with ``/plugin/<plugin identifier>/`` (if the path already begins
with a ``/`` that will be stripped first).
**Example**
The following plugin example sets the maximum body size for ``POST`` requests against four custom URLs to 100, 200,
500 and 1024KB. To test its functionality try uploading files larger or smaller than an endpoint's configured maximum
size (as multipart request with the file upload residing in request parameter ``file``) and observe the behaviour.
.. onlineinclude:: https://raw.githubusercontent.com/OctoPrint/Plugin-Examples/master/increase_bodysize.py
:linenos:
:tab-width: 4
:caption: `increase_bodysize.py <https://github.com/OctoPrint/Plugin-Examples/blob/master/increase_bodysize.py>`_
:param list current_max_body_sizes: read-only list of the currently configured maximum body sizes
:return: A list of 3-tuples with additional request specific maximum body sizes as defined above
:rtype: list
.. _sec-plugins-hook-server-http-routes:
octoprint.server.http.routes
----------------------------
.. py:function:: hook(server_routes, *args, **kwargs)
Allows extending the list of routes registered on the web server.
This is interesting for plugins which want to provide their own download URLs which will then be delivered statically
following the same path structure as regular downloads.
``server_routes`` will be a (read-only) list of the currently defined server routes, in case you want to check from
your plugin against that.
The hook must return a list of 3-tuples (the list's length can be 0). Each 3-tuple should have the path of the route
(a string defining its regular expression) as the first, the `RequestHandler <http://tornado.readthedocs.org/en/branch4.0/web.html#request-handlers>`_
class to use for the route as the second and a dictionary with keywords parameters for the defined request handler as
the third entry.
The path of the route will be prefixed by OctoPrint with ``/plugin/<plugin identifier>/`` (if the path already begins
with a ``/`` that will be stripped first).
.. note::
Static routes provided through this hook take precedence over routes defined through blueprints.
If your plugin also implements the :class:`~octoprint.plugin.BlueprintPlugin` mixin and has defined a route for a
view on that which matches one of the paths provided via its ``octoprint.server.http.routes`` hook handler, the
view of the blueprint will thus not be reachable since processing of the request will directly be handed over
to your defined handler class.
**Example**
The following example registers two new routes ``/plugin/add_tornado_route/download`` and ``/plugin/add_tornado_route/forward``
in the webserver which roughly replicate the functionality of ``/downloads/files/local`` and ``/downloads/camera/current``.
.. onlineinclude:: https://raw.githubusercontent.com/OctoPrint/Plugin-Examples/master/add_tornado_route.py
:linenos:
:tab-width: 4
:caption: `add_tornado_route.py <https://github.com/OctoPrint/Plugin-Examples/blob/master/add_tornado_route.py>`_
.. seealso::
:class:`~octoprint.server.util.tornado.LargeResponseHandler`
Customized `tornado.web.StaticFileHandler <http://tornado.readthedocs.org/en/branch4.0/web.html#tornado.web.StaticFileHandler>`_
that allows delivery of the requested resource as attachment and access validation through an optional callback.
:class:`~octoprint.server.util.tornado.UrlForwardHandler`
`tornado.web.RequestHandler <http://tornado.readthedocs.org/en/branch4.0/web.html#request-handlers>`_ that proxies
requests to a preconfigured url and returns the response.
:param list server_routes: read-only list of the currently configured server routes
:return: a list of 3-tuples with additional routes as defined above
:rtype: list
.. _sec-plugins-hook-ui-web-templatetypes:
octoprint.ui.web.templatetypes
------------------------------
.. py:function:: hook(template_sorting, template_rules, *args, **kwargs)
Allows extending the set of supported template types in the web interface. This is interesting for plugins which want
to offer other plugins to hook into their own offered UIs. Handlers must return a list of additional template
specifications in form of 3-tuples.
The first entry of the tuple must be the name of the template type and will be automatically prefixed with
``plugin_<identifier>_``.
The second entry must be a sorting specification that defines how OctoPrint should sort multiple templates injected
through plugins of this template type. The sorting specification should be a dict with the following possible
entries:
.. list-table::
:widths: 5 95
* - **Key**
- **Description**
* - key
- The sorting key within the template config to use for sorting the list of template injections. This may be
``None`` in which case no sorting will be taking place. Defaults to ``name``.
* - add
- Usually irrelevant for custom template types, only listed for the sake of completeness. The method of adding
the sorted list of template injections from plugins to the template injections from the
core. May be ``append`` to append the list, ``prepend`` to prepend the list, or ``custom_append`` or
``custom_prepend`` to append respectively prepend but going so after preprocessing the entries and order data
with custom functions (e.g. to inject additional entries such as the "Plugins" section header in the settings
dialog). For custom template types this defaults to ``append``.
* - custom_add_entries
- Usually irrelevant for custom template types, only listed for the sake of completeness. Custom preprocessor
for the entries provided through plugins, before they are added to the general template entries
context variable for the current template type.
* - custom_add_order
- Usually irrelevant for custom template types, only listed for the sake of completeness. Custom preprocessor
for the template order provided through plugins, before they are added to the general template order
context variable for the current template type.
The third entry must be a rule specification in form of a dict which tells OctoPrint how to process the template
configuration entries provided by :func:`~octoprint.plugin.TemplatePlugin.get_template_configs` by providing
transformation functions of various kinds:
.. list-table::
:widths: 5 95
* - **Key**
- **Description**
* - div
- Function that returns the id of the container for template content if not explicitely provided by the template
config, input parameter is the name of the plugin providing the currently processed template config. If not
provided this defaults to a lambda function of the form ``lambda x: "<plugin identifier>_<template type>_plugin_" + x``
with ``plugin identifier`` being the identifier of the plugin providing the additional template type.
* - template
- Function that returns the default template filename for a template type to attempt to include in case no
template name is explicitly provided by the template config, input parameter is the name of the plugin provifing
the current processed template config. If not provided this defaults to a lambda function of the form
``lambda x: x + "_plugin_<plugin identifier>_<template type>.jinja2"`` with ``plugin identifier`` being the
identifier of the plugin providing the additional template type.
* - to_entry
- Function to transform a template config to the data structure stored in the Jinja context for the injected
template. If not provided this defaults to a lambda function returning a 2-tuple of the ``name`` value of
the template config and the template config itself (``lambda data: (data["name"], data)``)
* - mandatory
- A list of keys that must be included in the template config for this template type. Template configs not containing
all of the keys in this list will be ignored. Defaults to an empty list.
OctoPrint will provide all template configs for custom template types in the Jinja rendering context in the same way
as it provides the template configs for core template types, through the ``templates`` context variable which is a
dict mapping from the template type name (``plugin_<plugin identifier>_<template type>`` for custom ones) to a dict
with ``entries`` and ``order`` values, the first containing a dict of all registered template configs, the latter
an ordered list of all registered template keys of the type in the order they should be rendered. Plugins should
iterate over the ``order`` list and then render each entry utilizing the template entry as provided for the key in
the ``entries`` dict (note that this entry will have the format specified through the ``to_entry`` section in the
template rule).
**Example**
The example consists of two plugins, one providing a custom template type and the other consuming it.
First the provider:
.. onlineinclude:: https://raw.githubusercontent.com/OctoPrint/Plugin-Examples/master/custom_template_provider/__init__.py
:linenos:
:tab-width: 4
:caption: `custom_template_provider/__init__.py <https://github.com/OctoPrint/Plugin-Examples/blob/master/custom_template_provider/__init__.py>`_
.. onlineinclude:: https://raw.githubusercontent.com/OctoPrint/Plugin-Examples/master/custom_template_provider/templates/custom_template_provider_settings.jinja2
:linenos:
:tab-width: 4
:caption: `custom_template_provider/templates/custom_template_provider_settings.jinja2 <https://github.com/OctoPrint/Plugin-Examples/blob/master/custom_template_provider/templates/custom_template_provider_settings.jinja2>`_
Then the consumer:
.. onlineinclude:: https://raw.githubusercontent.com/OctoPrint/Plugin-Examples/master/custom_template_consumer/__init__.py
:linenos:
:tab-width: 4
:caption: `custom_template_consumer/__init__.py <https://github.com/OctoPrint/Plugin-Examples/blob/master/custom_template_consumer/__init__.py>`_
.. onlineinclude:: https://raw.githubusercontent.com/OctoPrint/Plugin-Examples/master/custom_template_consumer/templates/custom_template_consumer_awesometemplate.jinja2
:linenos:
:tab-width: 4
:caption: `custom_template_consumer/templates/custom_template_consumer_awesometemplate.jinja2 <https://github.com/OctoPrint/Plugin-Examples/blob/master/custom_template_consumer/templates/custom_template_consumer_awesometemplate.jinja2>`_
:param dict template_rules: read-only dictionary of currently configured template rules
:param dict template_sorting: read-only dictionary of currentl configured template sorting specifications
:return: a list of 3-tuples (template type, rule, sorting spec)
:rtype: list
+54 -9
View File
@@ -1,15 +1,60 @@
.. _sec-plugins:
##################
#####################
Plugins Documentation
#####################
Starting with OctoPrint 1.2.0, there's now a plugin system in place which allows to individually
extend OctoPrint's functionality.
Right now plugins can be used to extend OctoPrint's settings dialog, to execute specific tasks on server startup and
shutdown, to provide custom (API) endpoints with special functionality, to react on system events or to add support for
additional slicers. More plugin types are planned for the future.
.. _sec-plugins-installation:
Installing Plugins
==================
Plugins can be installed either by unpacking them into one of the configured plugin folders (regularly those are
``<octoprint-root>/plugins`` and ``~/.octoprint/plugins`` or by installing them as regular python modules via ``pip``.
Please refer to the documentation of the plugin for installations instructions.
The latter is the more common case since all currently published plugins not bundled with OctoPrint can and should be installed
this way.
For a plugin available on the Python Package Index (PyPi), the process is as simple as issuing a
.. code-block:: bash
pip install <plugin_name>
For plugins not available on PyPi, you'll have to give ``pip`` an URL from which to install the package (e.g. the URL to
a ZIP file of the current master branch of a Github repository hosting a plugin, or even a ``git+https`` URL), example:
.. code-block:: bash
pip install https://github.com/OctoPrint/OctoPrint-Growl/archive/master.zip
See `the pip install documentation <http://pip.readthedocs.org/en/latest/reference/pip_install.html>`_ for what URL
types are possible.
.. _sec-plugins-available:
Available Plugins
=================
Currently there's no such thing as a centralized plugin repository for available plugins.
Plugins may be found in the lists provided in `the OctoPrint wiki <https://github.com/foosel/OctoPrint/wiki#plugins>`_
and on the `OctoPrint organization Github page <https://github.com/OctoPrint>`_.
Developing Plugins
##################
==================
Please see the following sub topics for information on how to develop your own OctoPrint plugins.
.. toctree::
:maxdepth: 3
:maxdepth: 2
gettingstarted.rst
concepts.rst
distributing.rst
mixins.rst
hooks.rst
viewmodels.rst
developing.rst
-93
View File
@@ -1,93 +0,0 @@
.. _sec-plugins-mixins:
Available plugin mixins
=======================
The following plugin mixins are currently available:
.. contents::
:local:
Please note that all plugin mixins inherit from :class:`~octoprint.plugin.core.Plugin` and
:class:`~octoprint.plugin.types.OctoPrintPlugin`, which also provide attributes of interest to plugin developers.
.. _sec-plugins-mixins-startupplugin:
StartupPlugin
-------------
.. autoclass:: octoprint.plugin.StartupPlugin
:members:
.. _sec-plugins-mixins-shutdownplugin:
ShutdownPlugin
--------------
.. autoclass:: octoprint.plugin.ShutdownPlugin
:members:
.. _sec-plugins-mixins-settingsplugin:
SettingsPlugin
--------------
.. autoclass:: octoprint.plugin.SettingsPlugin
:members:
.. _sec-plugins-mixins-assetplugin:
AssetPlugin
-----------
.. autoclass:: octoprint.plugin.AssetPlugin
:members:
.. _sec-plugins-mixins-templateplugin:
TemplatePlugin
--------------
.. autoclass:: octoprint.plugin.TemplatePlugin
:members:
.. _sec-plugins-mixins-simpleapiplugin:
SimpleApiPlugin
---------------
.. autoclass:: octoprint.plugin.SimpleApiPlugin
:members:
.. _sec-plugins-mixins-blueprintplugin:
BlueprintPlugin
---------------
.. autoclass:: octoprint.plugin.BlueprintPlugin
:members:
.. _sec-plugins-mixins-eventhandlerplugin:
EventHandlerPlugin
------------------
.. autoclass:: octoprint.plugin.EventHandlerPlugin
:members:
.. _sec-plugins-mixins-progressplugin:
ProgressPlugin
--------------
.. autoclass:: octoprint.plugin.ProgressPlugin
:members:
.. _sec-plugins-mixins-slicerplugin:
SlicerPlugin
------------
.. autoclass:: octoprint.plugin.SlicerPlugin
:members:
-224
View File
@@ -1,224 +0,0 @@
.. _sec-plugins-viewmodels:
Viewmodels
==========
.. contents::
:local:
When implementing frontend components, you'll sooner or later want to define your own `KnockoutJS viewmodels <http://knockoutjs.com/>`_
in order to provide custom functionality.
.. _sec-plugins-viewmodels-registering:
Registering custom viewmodels
-----------------------------
Register your viewmodel with OctoPrint's web app by pushing a 3-tuple consisting of your viewmodel's class, a list
of all required dependencies to be injected into the constructor and a list of all elements to bind the viewmodel to.
Example:
.. code-block:: javascript
$(function() {
function MyCustomViewModel(parameters) {
var self = this;
self.loginState = parameters[0]; // requested as first constructor parameter below
// more of your viewmodel's implementation
}
OCTOPRINT_VIEWMODELS.push([
MyCustomViewModel,
["loginStateViewModel"],
["#some_div", "#some_other_div"]
]);
})
.. note::
Each provided binding target may be either a string which will then be passed to jQuery's ``$(...)`` method to resolve
the target, or alternatively directly a jQuery element.
.. _sec-plugins-viewmodels-dependencies:
Dependencies
------------
OctoPrint will try to inject all viewmodel dependencies requested by your viewmodel. In order to do this it will
perform multiple passes iterating over all registered viewmodels and collecting the necessary depedencies prior to
construction. Circular depedencies (A dependens on B, B on C, C on A) naturally cannot be resolved and will cause an
error to be logged to the Javascript console.
OctoPrint's core currently comes with the following viewmodels that your plugin can request for injection:
appearanceViewModel
Viewmodel that holds the appearance settings (name, color and transparency flag).
connectionViewModel
Viewmodel for the connection sidebar entry.
controlViewModel
Viewmodel for the control tab.
gcodeFilesViewModel
Viewmodel for the files sidebar entry.
firstRunViewModel
Viewmodel for the first run dialog.
gcodeViewModel
Viewmodel for the gcode viewer tab.
logViewModel
Viewmodel for the logfile settings dialog.
loginStateViewModel
Viewmodel for the current loginstate of the user, very interesting for plugins that need to
evaluate the current login state or information about the current user, e.g. associated roles.
navigationViewModel
Viewmodel for the navigation bar.
printerProfilesViewModel
Viewmodel for the printer profiles settings dialog.
printerStateViewModel
Viewmodel for the current printer state, very intersting for plugins that need
to know information about the current print job, if the printer is connected, operational etc.
settingsViewModel
Viewmodel for the settings dialog, also holds all settings to be used by other viewmodels, hence
very interesting for plugins as well.
slicingViewModel
Viewmodel for the slicing dialog.
temperatureViewModel
Viewmodel for the temperature tab, also holds current temperature information which
might be interesting for plugins.
terminalViewModel
Viewmodel for the terminal tab, also holds terminal log entries.
timelapseViewModel
Viewmodel for the timelapse tab.
usersViewModel
Viewmodel for the user management in the settings dialog.
userSettingsViewModel
Viewmodel for settings associated with the currently logged in user, used for
the user settings dialog.
Additionally each plugin's viewmodel will be added to the viewmodel map used for resolving dependencies as well, using
the viewmodel's class name with a lower case first character as identifier (so "MyCustomViewModel" will be registered
for dependency injection as "myCustomViewModel").
.. _sec-plugins-viewmodels-callbacks:
Callbacks
---------
OctoPrint's web application will call several callbacks on all registered viewmodels, provided they implement them.
Those are listed below:
onStartup()
Called when the first initialization has been done: All viewmodels are constructed and hence their dependencies
resolved, no bindings have been done yet.
onBeforeBinding()
Called per viewmodel before attempting to bind it to its binding targets.
onAfterBinding()
Called per viewmodel after binding it to its binding targets.
onAllBound(allViewModels)
Called after all viewmodels have been bound, with the list of all viewmodels as the single parameter.
onStartupComplete()
Called after the startup of the web app has been completed.
onServerDisconnect()
Called if a disconnect from the server is detected.
onDataUpdaterReconnect()
Called when the connection to the server has been reestablished after a disconnect.
fromHistoryData(data)
Called when history data is received from the server. Usually that happens only after initial connect in order to
transmit the temperature and terminal log history to the connecting client. Called with the ``data`` as single parameter.
fromCurrentData(data)
Called when current printer status data is received from the server with the ``data`` as single parameter.
onSlicingProgress(slicer, modelPath, machineCodePath, progress)
Called on slicing progress, call rate is once per percentage point of the progress at maximum.
onEvent<EventName>(payload)
Called on firing of an event of type ``EventName``, e.g. ``onEventPrintDone``. See :ref:`the list of available events <sec-events-available_events>`
for the possible events and their payloads.
fromTimelapseData(data)
Called when timelapse configuration data is received from the server. Usually that happens after initial connect.
onDataUpdaterPluginMessage(plugin, message)
Called when a plugin message is pushed from the server with the identifier of the calling plugin as first
and the actual message as the second parameter. Note that the latter might be a full fledged object, depending
on the plugin sending the message. You can use this method to asynchronously push data from your plugin's server
component to it's frontend component.
onUserLoggedIn(user)
Called when a user gets logged into the web app, either passively (upon initial load of the page due to a valid
"Remember Me" cookie) or due to an active completion of the login dialog. The user data of the just logged in user
will be provided as only parameter.
onUserLoggedOut()
Called when a user gets logged out of the web app.
onTabChange(current, previous)
Called before the main tab view switches to a new tab, so `before` the new tab becomes visible. Called with the
current and previous tab's hash (e.g. ``#control``).
onAfterTabChange
Called after the main tab view switches to a new tab, so `after` the new tab becomes visible. Called with the
current and previous tab's hash (e.g. ``#control``).
getAdditionalControls
Your viewmodel may return additional custom control definitions for inclusion on the "Control" tab of OctoPrint's
interface. See :ref:`the custom control feature<sec-features-custom_controls>`.
onSettingsShown
Called when the settings dialog is shown.
onSettingsHidden
Called when the settings dialog is hidden.
onSettingsBeforeSave
Called just before the settings viewmodel is sent to the server. This is useful, for example, if your plugin
needs to compute persisted settings from a custom viewmodel.
onUserSettingsShown
Called when the user settings dialog is shown.
onUserSettingsHidden
Called when the user settings dialog is hidden.
In order to hook into any of those callbacks, just have your viewmodel define a function named accordingly, e.g.
to get called after all viewmodels have been bound during application startup, implement a function ``onAllBound``
on your viewmodel, taking a list of all bound viewmodels:
.. code-block:: javascript
$(function() {
function MyCustomViewModel(parameters) {
var self = this;
// ...
self.onAllBound = function(allViewModels) {
// do something with them
}
// ...
}
OCTOPRINT_VIEWMODELS.push([
MyCustomViewModel,
["loginStateViewModel"],
["#some_div", "#some_other_div"]
]);
})
.. seealso::
`OctoPrint's core viewmodels <https://github.com/foosel/OctoPrint/tree/devel/src/octoprint/static/js/app/viewmodels>`_
OctoPrint's own viewmodels use the same mechanisms for interacting with each other and the web application as
plugins. Their sourcecode is therefore a good point of reference on how to achieve certain things.
`KnockoutJS documentation <http://knockoutjs.com/documentation/introduction.html>`_
OctoPrint makes heavy use of KnockoutJS for building up its web app.
+2
View File
@@ -0,0 +1,2 @@
sphinxcontrib-httpdomain
sphinx_rtd_theme
-258
View File
@@ -1,258 +0,0 @@
# coding=utf-8
from __future__ import absolute_import
__author__ = "Gina Häußge <osd@foosel.net>"
__license__ = 'The MIT License <http://opensource.org/licenses/MIT>'
__copyright__ = "Copyright (C) 2015 Gina Häußge - Released under terms of the MIT License"
from sphinx.directives.code import CodeBlock
import sphinx.highlighting
from sphinx.highlighting import PygmentsBridge
from sphinx.ext import doctest
from sphinx.util.texescape import tex_hl_escape_map_new
from docutils.nodes import General, FixedTextElement, literal_block, container
from docutils.parsers.rst import directives
from six import text_type
from pygments import highlight
from pygments.filters import VisibleWhitespaceFilter, ErrorToken
from pygments.lexers.python import PythonConsoleLexer
from pygments.util import ClassNotFound
def _merge_dict(a, b):
"""
Little helper to merge two dicts a and b on the fly.
"""
result = dict(a)
result.update(b)
return result
class literal_block_ext(General, FixedTextElement):
"""
Custom node which is basically the same as a :class:`literal_block`, just with whitespace support and introduced
in order to be able to have a custom visitor.
"""
@classmethod
def from_literal_block(cls, block):
"""
Factory method constructing an instance exactly copying all attributes over from ``block`` and settings a
custom ``tagname``.
"""
new = literal_block_ext()
for a in ("attributes", "basic_attributes", "child_text_separator", "children", "document", "known_attributes",
"line", "list_attributes", "local_attributes", "parent", "rawsource", "source"):
setattr(new, a, getattr(block, a))
new.tagname = "literal_block_ext"
return new
class CodeBlockExt(CodeBlock):
"""
This is basically an extension of a regular :class:`CodeBlock` directive which just supports an additional option
``whitespace`` which if present will enable (together with everything else in here) to render whitespace in
code blocks.
"""
option_spec = _merge_dict(CodeBlock.option_spec, dict(whitespace=directives.flag))
def run(self):
# get result from parent implementation
code_block = CodeBlock.run(self)
def find_and_wrap_literal_block(node):
"""
Recursive method to turn all literal blocks located within a node into :class:`literal_block_ext`.
"""
if isinstance(node, container):
# container node => handle all children
children = []
for child in node.children:
children.append(find_and_wrap_literal_block(child))
node.children = children
return node
elif isinstance(node, literal_block):
# literal block => replace it
return self._wrap_literal_block(node)
else:
# no idea what that is => leave it alone
return node
# replace all created literal_blocks with literal_block_ext instances
return map(find_and_wrap_literal_block, code_block)
def _wrap_literal_block(self, node):
literal = literal_block_ext.from_literal_block(node)
literal["whitespace"] = "whitespace" in self.options
return literal
class PygmentsBridgeExt(object):
"""
Wrapper for :class:`PygmentsBridge`, delegates everything to the wrapped ``bridge`` but :method:`highlight_block`,
which calls the parent implementation for lexer selection, then
"""
def __init__(self, bridge, whitespace):
self._bridge = bridge
self._whitespace = whitespace
def __getattr__(self, item):
return getattr(self._bridge, item)
def highlight_block(self, source, lang, opts=None, warn=None, force=False, **kwargs):
if not self._whitespace:
return self._bridge.highlight_block(source, lang, opts=opts, warn=warn, force=force, **kwargs)
# We are still here => we need to basically do everything the parent implementation does (and does so in a very
# unextensible way...), but inject the whitespace filter into the used lexer just before the highlighting run
# and remove it afterwards so the lexer can be safely reused.
#
# For this we define a context manager that will allow us to wrap a lexer and modify its filters on the fly to
# include the whitespace filter.
class whitespace(object):
def __init__(self, lexer):
self._lexer = lexer
self._orig_filters = lexer.filters
self._orig_tabsize = lexer.tabsize
def __enter__(self):
new_filters = list(self._orig_filters)
new_filters.append(VisibleWhitespaceFilter(spaces=True, tabs=True, tabsize=self._lexer.tabsize))
self._lexer.filters = new_filters
self._lexer.tabsize = 0
return self._lexer
def __exit__(self, type, value, traceback):
self._lexer.filters = self._orig_filters
self._lexer.tabsize = self._orig_tabsize
# Then a ton of copy-pasted code follows. Sadly, we need to do this since we have no way to inject ourselves
# into the highlighting call otherwise - lexer selection and actual call are tightly coupled in the original
# "highlight_block" method, with no means for external code to inject different functionality.
#
# Unless otherwise marked ("MODIFIED"), any code in this method after this line is copied verbatim from the
# implementation of sphinx.highlighting.PygmentsBridge, released under the Simplified BSD License, the copyright
# lies with the respective authors.
if not isinstance(source, text_type):
source = source.decode()
# find out which lexer to use
if lang in ('py', 'python'):
if source.startswith('>>>'):
# interactive session
lexer = sphinx.highlighting.lexers['pycon']
elif not force:
# maybe Python -- try parsing it
if self.try_parse(source):
lexer = sphinx.highlighting.lexers['python']
else:
lexer = sphinx.highlighting.lexers['none']
else:
lexer = sphinx.highlighting.lexers['python']
elif lang in ('python3', 'py3') and source.startswith('>>>'):
# for py3, recognize interactive sessions, but do not try parsing...
lexer = sphinx.highlighting.lexers['pycon3']
elif lang == 'guess':
try:
lexer = sphinx.highlighting.guess_lexer(source)
except Exception:
lexer = sphinx.highlighting.lexers['none']
else:
if lang in sphinx.highlighting.lexers:
lexer = sphinx.highlighting.lexers[lang]
else:
try:
lexer = sphinx.highlighting.lexers[lang] = sphinx.highlighting.get_lexer_by_name(lang, **opts or {})
except ClassNotFound:
if warn:
warn('Pygments lexer name %r is not known' % lang)
lexer = sphinx.highlighting.lexers['none']
else:
raise
else:
lexer.add_filter('raiseonerror')
if not isinstance(source, text_type):
source = source.decode()
# trim doctest options if wanted
if isinstance(lexer, PythonConsoleLexer) and self._bridge.trim_doctest_flags:
source = doctest.blankline_re.sub('', source)
source = doctest.doctestopt_re.sub('', source)
# highlight via Pygments
formatter = self._bridge.get_formatter(**kwargs)
try:
# MODIFIED: replaced by whitespace wrapped call
with whitespace(lexer) as l:
hlsource = highlight(source, l, formatter)
# /MODIFIED
except ErrorToken:
# this is most probably not the selected language,
# so let it pass unhighlighted
# MODIFIED: replaced by whitespace wrapped call
with whitespace(sphinx.highlighting.lexers["none"]) as l:
hlsource = highlight(source, l, formatter)
# /MODIFIED
if self._bridge.dest == 'html':
return hlsource
else:
if not isinstance(hlsource, text_type): # Py2 / Pygments < 1.6
hlsource = hlsource.decode()
return hlsource.translate(tex_hl_escape_map_new)
class whitespace_highlighter(object):
"""
Context manager for adapting the used highlighter on a translator for a given node's whitespace properties.
"""
def __init__(self, translator, node):
self.translator = translator
self.node = node
self._orig_highlighter = self.translator.highlighter
def __enter__(self):
whitespace = self.node["whitespace"] if "whitespace" in self.node else False
if whitespace:
self.translator.highlighter = PygmentsBridgeExt(self._orig_highlighter, whitespace)
return self.translator
def __exit__(self, exc_type, exc_val, exc_tb):
self.translator.highlighter = self._orig_highlighter
def visit_literal_block_ext(translator, node):
"""
When our custom code block is visited, we temporarily exchange the highlighter used in the translator, call the
visitor for regular literal blocks, then switch back again.
"""
with whitespace_highlighter(translator, node):
translator.visit_literal_block(node)
def depart_literal_block_ext(translator, node):
"""
Just call the depart function for regular literal blocks.
"""
with whitespace_highlighter(translator, node):
translator.depart_literal_block(node)
def setup(app):
# custom directive
app.add_directive("code-block-ext", CodeBlockExt)
# custom node type
handler = (visit_literal_block_ext, depart_literal_block_ext)
app.add_node(literal_block_ext, html=handler, latex=handler, text=handler)
return dict(version="0.1")
-56
View File
@@ -1,56 +0,0 @@
# coding=utf-8
from __future__ import absolute_import
__author__ = "Gina Häußge <osd@foosel.net>"
__license__ = 'The MIT License <http://opensource.org/licenses/MIT>'
__copyright__ = "Copyright (C) 2015 Gina Häußge - Released under terms of the MIT License"
import codecs
import urllib2
from sphinx.directives import LiteralInclude, dedent_lines
cache = dict()
class OnlineIncludeDirective(LiteralInclude):
def read_with_encoding(self, filename, document, codec_info, encoding):
global cache
f = None
try:
if not self.arguments[0] in cache:
f = codecs.StreamReaderWriter(urllib2.urlopen(self.arguments[0]), codec_info[2],
codec_info[3], 'strict')
lines = f.readlines()
cache[self.arguments[0]] = lines
else:
lines = cache[self.arguments[0]]
lines = dedent_lines(lines, self.options.get('dedent'))
return lines
except (IOError, OSError, urllib2.URLError):
return [document.reporter.warning(
'Include file %r not found or reading it failed' % self.arguments[0],
line=self.lineno)]
except UnicodeError:
return [document.reporter.warning(
'Encoding %r used for reading included file %r seems to '
'be wrong, try giving an :encoding: option' %
(encoding, self.arguments[0]))]
finally:
if f is not None:
f.close()
def visit_onlineinclude(translator, node):
translator.visit_literal_block(node)
def depart_onlineinclude(translator, node):
translator.depart_literal_block(node)
def setup(app):
app.add_directive("onlineinclude", OnlineIncludeDirective)
handler = (visit_onlineinclude, depart_onlineinclude)
app.add_node(OnlineIncludeDirective, html=handler, latex=handler, text=handler)
+15
View File
@@ -0,0 +1,15 @@
flask==0.9
werkzeug==0.8.3
tornado==3.0.2
sockjs-tornado>=1.0.0
PyYAML==3.10
Flask-Login==0.2.2
Flask-Principal==0.3.5
netaddr>=0.7.10
mock>=1.0.1
nose>=1.3.0
watchdog
sarge
sphinxcontrib-httpdomain
sphinx_rtd_theme
+6
View File
@@ -0,0 +1,6 @@
mock>=1.0.1
nose>=1.3.0
sphinxcontrib-httpdomain
sphinx_rtd_theme
po2json
ddt
+15 -10
View File
@@ -1,10 +1,15 @@
###
# This file is only here to make sure that something like
#
# pip install -e .[develop]
#
# works as expected. Requirements can be found in setup.py in the
# variables INSTALL_REQUIRES and EXTRA_REQUIRES.
###
.
flask==0.9
werkzeug==0.8.3
tornado==4.0.1
sockjs-tornado>=1.0.0
PyYAML==3.10
Flask-Login==0.2.2
Flask-Principal==0.3.5
Flask-Babel==0.9
pyserial
netaddr
watchdog
sarge
netifaces
pylru
rsa
-4
View File
@@ -15,9 +15,5 @@ DAEMON_ARGS="--port=$PORT"
# Umask of files octoprint generates, Change this to 000 if running octoprint as its own, separate user
UMASK=022
# Process priority, 0 here will result in a priority 20 process.
# -2 ensures Octoprint has a slight priority over user processes.
NICELEVEL=-2
# Should we run at startup?
START=yes
+3 -3
View File
@@ -19,6 +19,7 @@ PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
DESC="Octoprint Daemon"
NAME="Octoprint"
DAEMON=/usr/local/bin/octoprint
NICE=-10
PIDFILE=/var/run/$NAME.pid
PKGNAME=octoprint
SCRIPTNAME=/etc/init.d/$PKGNAME
@@ -72,9 +73,8 @@ do_start()
RETVAL="$?"
if [ $RETVAL != 0 ]; then
start-stop-daemon --start --background --quiet --pidfile $PIDFILE --make-pidfile \
--exec $DAEMON --chuid $OCTOPRINT_USER --user $OCTOPRINT_USER --umask $UMASK --nicelevel=$NICELEVEL \
-- $DAEMON_ARGS
start-stop-daemon --start --background --quiet --pidfile $PIDFILE --make-pidfile --nicelevel $NICE\
--exec $DAEMON --chuid $OCTOPRINT_USER --user $OCTOPRINT_USER --umask $UMASK -- $DAEMON_ARGS
RETVAL="$?"
fi
}
+243 -85
View File
@@ -1,64 +1,7 @@
#!/usr/bin/env python
# coding=utf-8
#!/usr/bin/env python
from setuptools import setup, find_packages
import os
import versioneer
import sys
sys.path.insert(0, os.path.join(os.path.dirname(os.path.realpath(__file__)), "src"))
import octoprint_setuptools
#-----------------------------------------------------------------------------------------------------------------------
# Requirements for our application
INSTALL_REQUIRES = [
"flask>=0.9,<0.11",
"werkzeug==0.8.3",
"tornado==4.0.1",
"sockjs-tornado>=1.0.0",
"PyYAML==3.10",
"Flask-Login==0.2.2",
"Flask-Principal==0.3.5",
"Flask-Babel==0.9",
"Flask-Assets==0.10",
"pyserial",
"netaddr",
"watchdog",
"sarge>=0.1.4",
"netifaces",
"pylru",
"rsa",
"pkginfo",
"requests",
"semantic_version"
]
# Additional requirements for optional install options
EXTRA_REQUIRES = dict(
# Dependencies for developing OctoPrint
develop=[
# Testing dependencies
"mock>=1.0.1",
"nose>=1.3.0",
"ddt",
# Documentation dependencies
"sphinx>=1.3",
"sphinxcontrib-httpdomain",
"sphinx_rtd_theme"
],
# Dependencies for developing OctoPrint plugins
plugins=[
"cookiecutter"
]
)
# Dependency links for any of the aforementioned dependencies
DEPENDENCY_LINKS = []
# Versioneer configuration
versioneer.VCS = 'git'
versioneer.versionfile_source = 'src/octoprint/_version.py'
versioneer.versionfile_build = 'octoprint/_version.py'
@@ -66,21 +9,244 @@ versioneer.tag_prefix = ''
versioneer.parentdir_prefix = ''
versioneer.lookupfile = '.versioneer-lookup'
#-----------------------------------------------------------------------------------------------------------------------
# Anything below here is just command setup and general setup configuration
from setuptools import setup, find_packages, Command
import os
import shutil
import glob
I18N_MAPPING_FILE = "babel.cfg"
I18N_DOMAIN = "messages"
I18N_INPUT_DIRS = "."
I18N_OUTPUT_DIR_PY = os.path.join("src", "octoprint", "translations")
I18N_OUTPUT_DIR_JS = os.path.join("src", "octoprint", "static", "js", "i18n")
I18N_POT_FILE = os.path.join(I18N_OUTPUT_DIR_PY, "messages.pot")
def package_data_dirs(source, sub_folders):
dirs = []
for d in sub_folders:
for dirname, _, files in os.walk(os.path.join(source, d)):
dirname = os.path.relpath(dirname, source)
for f in files:
dirs.append(os.path.join(dirname, f))
return dirs
def _recursively_handle_files(directory, file_matcher, folder_handler=None, file_handler=None):
applied_handler = False
for filename in os.listdir(directory):
path = os.path.join(directory, filename)
if file_handler is not None and file_matcher(filename):
file_handler(path)
applied_handler = True
elif os.path.isdir(path):
sub_applied_handler = _recursively_handle_files(path, file_matcher, folder_handler=folder_handler, file_handler=file_handler)
if sub_applied_handler:
applied_handler = True
if folder_handler is not None:
folder_handler(path, sub_applied_handler)
return applied_handler
class CleanCommand(Command):
description = "clean build artifacts"
user_options = []
boolean_options = []
def initialize_options(self):
pass
def finalize_options(self):
pass
def run(self):
# build folder
if os.path.exists('build'):
print "Deleting build directory"
shutil.rmtree('build')
# eggs
eggs = glob.glob('OctoPrint*.egg-info')
for egg in eggs:
print "Deleting %s directory" % egg
shutil.rmtree(egg)
# pyc files
def delete_folder_if_empty(path, applied_handler):
if not applied_handler:
return
if len(os.listdir(path)) == 0:
shutil.rmtree(path)
print "Deleted %s since it was empty" % path
def delete_file(path):
os.remove(path)
print "Deleted %s" % path
import fnmatch
_recursively_handle_files(
os.path.abspath("src"),
lambda name: fnmatch.fnmatch(name.lower(), "*.pyc"),
folder_handler=delete_folder_if_empty,
file_handler=delete_file
)
# pyc files
def delete_folder_if_empty(path, applied_handler):
if not applied_handler:
return
if len(os.listdir(path)) == 0:
shutil.rmtree(path)
print "Deleted %s since it was empty" % path
def delete_file(path):
os.remove(path)
print "Deleted %s" % path
import fnmatch
_recursively_handle_files(
os.path.abspath("src"),
lambda name: fnmatch.fnmatch(name.lower(), "*.pyc"),
folder_handler=delete_folder_if_empty,
file_handler=delete_file
)
class NewTranslation(Command):
description = "create a new translation"
user_options = [
('locale=', 'l', 'locale for the new translation'),
]
boolean_options = []
def __init__(self, dist, **kw):
from babel.messages import frontend as babel
self.babel_init_messages = babel.init_catalog(dist)
Command.__init__(self, dist, **kw)
def initialize_options(self):
self.locale = None
self.babel_init_messages.initialize_options()
def finalize_options(self):
self.babel_init_messages.locale = self.locale
self.babel_init_messages.input_file = I18N_POT_FILE
self.babel_init_messages.output_dir = I18N_OUTPUT_DIR_PY
self.babel_init_messages.finalize_options()
def run(self):
self.babel_init_messages.run()
class ExtractTranslation(Command):
description = "extract translations"
user_options = []
boolean_options = []
def __init__(self, dist, **kw):
from babel.messages import frontend as babel
self.babel_extract_messages = babel.extract_messages(dist)
Command.__init__(self, dist, **kw)
def initialize_options(self):
self.babel_extract_messages.initialize_options()
def finalize_options(self):
self.babel_extract_messages.mapping_file = I18N_MAPPING_FILE
self.babel_extract_messages.output_file = I18N_POT_FILE
self.babel_extract_messages.input_dirs = I18N_INPUT_DIRS
self.babel_extract_messages.msgid_bugs_address = "i18n@octoprint.org"
self.babel_extract_messages.copyright_holder = "The OctoPrint Project"
self.babel_extract_messages.finalize_options()
def run(self):
self.babel_extract_messages.run()
class RefreshTranslation(Command):
description = "refresh translations"
user_options = [
('locale=', 'l', 'locale for the translation to refresh'),
]
boolean_options = []
def __init__(self, dist, **kw):
from babel.messages import frontend as babel
self.babel_extract_messages = babel.extract_messages(dist)
self.babel_update_messages = babel.update_catalog(dist)
Command.__init__(self, dist, **kw)
def initialize_options(self):
self.locale = None
self.babel_extract_messages.initialize_options()
self.babel_update_messages.initialize_options()
def finalize_options(self):
self.babel_extract_messages.mapping_file = I18N_MAPPING_FILE
self.babel_extract_messages.output_file = I18N_POT_FILE
self.babel_extract_messages.input_dirs = I18N_INPUT_DIRS
self.babel_extract_messages.msgid_bugs_address = "i18n@octoprint.org"
self.babel_extract_messages.copyright_holder = "The OctoPrint Project"
self.babel_extract_messages.finalize_options()
self.babel_update_messages.input_file = I18N_MAPPING_FILE
self.babel_update_messages.output_dir = I18N_OUTPUT_DIR_PY
self.babel_update_messages.locale = self.locale
def run(self):
self.babel_extract_messages.run()
self.babel_update_messages.run()
class CompileTranslation(Command):
description = "compile translations"
user_options = []
boolean_options = []
def __init__(self, dist, **kw):
from babel.messages import frontend as babel
self.babel_compile_messages = babel.compile_catalog(dist)
Command.__init__(self, dist, **kw)
def initialize_options(self):
self.babel_compile_messages.initialize_options()
def finalize_options(self):
self.babel_compile_messages.directory = I18N_OUTPUT_DIR_PY
def run(self):
self.babel_compile_messages.run()
import po2json
for lang_code in os.listdir(I18N_OUTPUT_DIR_PY):
full_path = os.path.join(I18N_OUTPUT_DIR_PY, lang_code)
if os.path.isdir(full_path):
client_po_dir = os.path.join(full_path, "LC_MESSAGES")
po2json.update_js_file(
"%s/%s.po" % (client_po_dir, I18N_DOMAIN),
lang_code,
I18N_OUTPUT_DIR_JS,
I18N_DOMAIN
)
def get_cmdclass():
cmdclass = versioneer.get_cmdclass()
# add clean command
cmdclass.update(dict(clean=octoprint_setuptools.CleanCommand.for_options(source_folder="src", eggs=["OctoPrint*.egg-info"])))
# add translation commands
translation_dir = "translations"
pot_file = os.path.join(translation_dir, "messages.pot")
bundled_dir = os.path.join("src", "octoprint", "translations")
cmdclass.update(octoprint_setuptools.get_babel_commandclasses(pot_file=pot_file, output_dir=translation_dir, pack_name_prefix="OctoPrint-i18n-", pack_path_prefix="", bundled_dir=bundled_dir))
cmdclass.update({
'clean': CleanCommand,
'babel_new': NewTranslation,
'babel_extract': ExtractTranslation,
'babel_refresh': RefreshTranslation,
'babel_compile': CompileTranslation
})
return cmdclass
@@ -116,24 +282,12 @@ def params():
license = "AGPLv3"
packages = find_packages(where="src")
package_dir = {
"": "src"
}
package_data = {
"octoprint": octoprint_setuptools.package_data_dirs('src/octoprint', ['static', 'templates', 'plugins', 'translations'])
}
package_dir = {"octoprint": "src/octoprint"}
package_data = {"octoprint": package_data_dirs('src/octoprint', ['static', 'templates', 'plugins'])}
include_package_data = True
zip_safe = False
install_requires = INSTALL_REQUIRES
extras_require = EXTRA_REQUIRES
dependency_links = DEPENDENCY_LINKS
if os.environ.get('READTHEDOCS', None) == 'True':
# we can't tell read the docs to please perform a pip install -e .[develop], so we help
# it a bit here by explicitly adding the development dependencies, which include our
# documentation dependencies
install_requires = install_requires + extras_require['develop']
install_requires = open("requirements.txt").read().split("\n")
entry_points = {
"console_scripts": [
@@ -141,6 +295,10 @@ def params():
]
}
#scripts = {
# "scripts/octoprint.init": "/etc/init.d/octoprint"
#}
return locals()
setup(**params())
+6
View File
@@ -0,0 +1,6 @@
# coding=utf-8
__author__ = "Gina Häußge <osd@foosel.net>"
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = "Copyright (C) 2014 Gina Häußge - Released under terms of the AGPLv3 License"
+589
View File
@@ -0,0 +1,589 @@
# coding=utf-8
__author__ = "Gina Häußge <osd@foosel.net>"
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = "Copyright (C) 2014 Gina Häußge - Released under terms of the AGPLv3 License"
import logging
import os
import time
from octoprint.events import eventManager, Events
from octoprint.comm.transport import MessageReceiver, StateReceiver, LogReceiver, State as TransportState
from octoprint.filemanager.destinations import FileDestinations
from octoprint.settings import settings
class Protocol(MessageReceiver, StateReceiver, LogReceiver):
def __init__(self, transport_factory, protocol_listener=None):
self._logger = logging.getLogger(__name__)
self._transport = transport_factory(self, self, self)
self._transport_properties = self._transport.get_properties()
self._protocol_listener = protocol_listener
self._state = State.OFFLINE
self._heatup_start_time = None
self._heatup_time_lost = 0.0
self._pause_start_time = None
self._pause_time_lost = 0.0
self._current_file = None
self._current_z = 0.0
self._sd_available = False
self._sd_files = []
self._current_temperature = {}
self._temperature_offsets = {}
self._error = None
def _reset(self):
self._heatup_start_time = None
self._heatup_time_lost = 0.0
self._current_file = None
self._current_z = 0.0
self._sd_available = False
self._sd_files = []
self._current_temperature = {}
self._temperature_offsets = {}
self._error = None
##~~ public
def connect(self, protocol_options, transport_options):
self._transport.connect(transport_options)
def disconnect(self, on_error=False):
if self.is_printing():
payload = None
if self._current_file is not None:
payload = {
"file": self._current_file.getFilename(),
"filename": os.path.basename(self._current_file.getFilename()),
"origin": self._current_file.getFileLocation()
}
eventManager().fire(Events.PRINT_FAILED, payload)
self._transport.disconnect(on_error)
def send_manually(self, command, high_priority=False):
pass
def select_file(self, filename, origin):
pass
def deselect_file(self):
pass
def start_print(self):
if self._current_file is None:
raise ValueError("No file selected for printing")
self._heatup_start_time = None
self._heatup_time_lost = 0.0
self._current_file.start()
self._changeState(State.PRINTING)
eventManager().fire(Events.PRINT_STARTED, {
"file": self._current_file.getFilename(),
"filename": os.path.basename(self._current_file.getFilename()),
"origin": self._current_file.getFileLocation()
})
def pause_print(self, only_pause=None, only_resume=None):
payload = {
"file": self._current_file.getFilename(),
"filename": os.path.basename(self._current_file.getFilename()),
"origin": self._current_file.getFileLocation()
}
if self._state == State.PRINTING and not only_resume:
self._pause_start_time = time.time()
self._changeState(State.PAUSED)
eventManager().fire(Events.PRINT_PAUSED, payload)
elif self._state == State.PAUSED and not only_pause:
if self._pause_start_time:
self._pause_time_lost += time.time() - self._pause_start_time
self._pause_start_time = None
self._changeState(State.PRINTING)
eventManager().fire(Events.PRINT_RESUMED, payload)
def cancel_print(self):
eventManager().fire(Events.PRINT_CANCELLED, {
"file": self._current_file.getFilename(),
"filename": os.path.basename(self._current_file.getFilename()),
"origin": self._current_file.getFileLocation()
})
self._changeState(State.OPERATIONAL)
self._print_cancelled()
if self._protocol_listener is not None:
self._protocol_listener.onPrintjobCancelled(self)
def _print_cancelled(self):
pass
def init_sd(self):
pass
def release_sd(self):
pass
def refresh_sd_files(self):
pass
def add_sd_file(self, path, local, remote):
pass
def remove_sd_file(self, filename):
pass
def get_state(self):
return self._state
def get_current_temperatures(self):
return self._current_temperature
def get_temperature_offsets(self):
result = {}
result.update(self._temperature_offsets)
return result
def set_temperature_offsets(self, new_temperature_offsets):
offsets = {}
offsets.update(new_temperature_offsets)
self._temperature_offsets = offsets
def get_sd_files(self):
return self._sd_files
def get_print_time(self):
if self._current_file is None or self._current_file.getStartTime() is None:
return None
else:
return max(int(time.time() - self._current_file.getStartTime() - self._heatup_time_lost - self._pause_time_lost), 0)
def get_connection_options(self):
return self._transport.get_connection_options()
def get_current_connection(self):
return self._transport.get_current_connection()
##~~ granular state detection for implementations
def is_heating_up(self):
return self._heatup_start_time is not None
def is_printing(self):
return self._state == State.PRINTING or self._state == State.PAUSED
def is_sd_printing(self):
return isinstance(self._current_file, PrintingSdFileInformation) and self.is_busy()
def is_streaming(self):
return self._state == State.STREAMING
def is_busy(self):
return self.is_printing() or self.is_streaming()
def is_operational(self):
return self._state == State.OPERATIONAL
def is_sd_ready(self):
return self._sd_available
##~~ state tracking and reporting to protocol listener
def _changeState(self, newState):
oldState = self._state
self._state = newState
self._stateChanged(newState)
if self._protocol_listener is not None:
self._protocol_listener.onStateChange(self, oldState, newState)
def _stateChanged(self, newState):
pass
def _updateTemperature(self, temperatureData):
self._current_temperature = temperatureData
self._temperatureUpdated(temperatureData)
if self._protocol_listener is not None:
self._protocol_listener.onTemperatureUpdate(self, temperatureData)
def _temperatureUpdated(self, temperatureData):
pass
def _reportProgress(self, completion=None, filepos=None):
if completion is None:
completion = self._getPrintCompletion()
if filepos is None:
filepos = self._getPrintFilepos()
progress = {
"completion": completion,
"filepos": filepos,
"printTime": self.get_print_time()
}
self._progressReported(progress)
if self._protocol_listener is not None:
self._protocol_listener.onProgress(self, progress)
def _progressReported(self, progress):
pass
def _reportZChange(self, z):
old_z = self._current_z
self._current_z = z
self._zChangeReported(z)
if self._protocol_listener is not None:
self._protocol_listener.onZChange(self, old_z, z)
def _zChangeReported(self, newZ):
pass
def _changeSdState(self, sdAvailable):
self._sd_available = sdAvailable
self._sdStateChanged(sdAvailable)
if self._sd_available:
self.refresh_sd_files()
else:
self._sd_files = []
if self._protocol_listener is not None:
self._protocol_listener.onSdStateChange(self, sdAvailable)
def _sdStateChanged(self, sdAvailable):
pass
def _selectFile(self, currentFile):
self._current_file = currentFile
self._fileSelected(currentFile)
if self._protocol_listener is not None:
self._protocol_listener.onFileSelected(self, currentFile.getFilename(), currentFile.getFilesize(), currentFile.getFileLocation())
eventManager().fire(Events.FILE_SELECTED, {
"file": self._current_file.getFilename(),
"origin": self._current_file.getFileLocation()
})
def _fileSelected(self, currentFile):
pass
def _sendSdFiles(self):
self._sdFilesSent()
if self._protocol_listener is not None:
self._protocol_listener.onSdFiles(self, self._sd_files)
def _sdFilesSent(self):
pass
def _finishPrintjob(self):
self._reportProgress(completion=100, filepos=self._current_file.getFilesize())
self._changeState(State.OPERATIONAL)
if self._protocol_listener is not None:
self._protocol_listener.onPrintjobDone(self)
eventManager().fire(Events.PRINT_DONE, {
"file": self._current_file.getFilename(),
"filename": os.path.basename(self._current_file.getFilename()),
"origin": self._current_file.getFileLocation(),
"time": time.time() - self._current_file.getStartTime() if self._current_file.getStartTime() is not None else None
})
self._printJobFinished()
def _printJobFinished(self):
pass
def _startFileTransfer(self, filename, filesize):
self._fileTransferStarted(filename, filesize)
if self._protocol_listener is not None:
self._protocol_listener.onFileTransferStarted(self, filename, filesize)
def _fileTransferStarted(self, filename, filesize):
pass
def _finishFileTransfer(self):
self._changeState(State.OPERATIONAL)
current_file = self._current_file
self._current_file = None
self._fileTransferFinished(current_file)
if self._protocol_listener is not None:
self._protocol_listener.onFileTransferDone(self)
def _fileTransferFinished(self, current_file):
pass
def _addSdFile(self, filename, filesize):
"""
Adds a file to the SD file list
:param filename: the filename to add to the list
:param filesize: the filesize to add to the list, may be None
"""
self._sd_files.append((filename, filesize))
self._sdFileAdded(filename, filesize)
def _sdFileAdded(self, filename, filesize):
"""
Called when a file has been added to the SD file list, can be used by the underyling protocol implementation
to react to that.
:param filename: the filename to add to the list
:param filesize: the filesize to add to the list, may be None
"""
pass
def _addSdFiles(self, files):
"""
Adds a list of files to the SD file list
:param files: the list of file tuples (name, size) to add to the list, size may be None
"""
for f in files:
self._sd_files.append(f)
self._sdFilesAdded(files)
def _sdFilesAdded(self, files):
"""
Called when a list of files has been added to the SD file list, can be used by the underlying protocol
implementation to react to that.
:param files: the file tuples (name, size) added to the list, size may be None
"""
pass
def _resetSdFiles(self):
"""
Resets the SD file list
"""
self._sd_files = []
self._sdFilesReset()
def _sdFilesReset(self):
"""
Called when the list of SD files has been reset, can be used in the underlying protocol implementation to
react to that
"""
pass
def _heatupDetected(self):
"""
Called when the underlying protocol detects the beginning of a heat-up interval.
"""
self._heatup_start_time = time.time()
def _heatupDone(self):
"""
Called when the underlying protocol detects the end of a heat-up interval.
"""
if self._heatup_start_time is not None:
self._heatup_time_lost += time.time() - self._heatup_start_time
self._heatup_start_time = None
def _log_error(self, error):
if self._protocol_listener is not None:
self._protocol_listener.onLogError(self, error)
##~~ StateReceiver
def onStateChangeReceived(self, source, oldState, newState):
if self._transport != source:
return
if newState == TransportState.DETECTING_CONNECTION or newState == TransportState.OPENING_CONNECTION:
self._changeState(State.CONNECTING)
elif newState == TransportState.CONNECTED:
self._changeState(State.CONNECTED)
elif newState == TransportState.DISCONNECTED:
self._changeState(State.OFFLINE)
elif newState == TransportState.DISCONNECTED_WITH_ERROR or newState == TransportState.ERROR:
self.onError(self._transport.getError())
try:
self._transport.disconnect()
except:
# TODO do we need to handle that?
pass
##~~ MessageReceiver
def onError(self, error):
self._changeState(State.ERROR)
self._error = error
eventManager().fire(Events.ERROR, {"error": error})
##~~ LogReceiver
def onLogRx(self, source, rx):
if self._transport != source:
return
if self._protocol_listener is not None:
self._protocol_listener.onLogRx(self, rx)
def onLogTx(self, source, tx):
if self._transport != source:
return
if self._protocol_listener is not None:
self._protocol_listener.onLogTx(self, tx)
def onLogError(self, source, error):
if self._transport != source:
return
self._log_error(error)
##~~ helpers
def _getPrintCompletion(self):
if self._current_file is None:
return None
return self._current_file.getProgress() * 100
def _getPrintFilepos(self):
if self._current_file is None:
return None
return self._current_file.getFilepos()
class ProtocolListener(object):
def onStateChange(self, source, oldState, newState):
pass
def onTemperatureUpdate(self, source, temperatureData):
pass
def onProgress(self, source, progress):
pass
def onZChange(self, source, oldZ, newZ):
pass
def onFileSelected(self, source, filename, filesize, origin):
pass
def onPrintjobStarted(self, source):
pass
def onPrintjobDone(self, source):
pass
def onPrintjobCancelled(self, source):
pass
def onFileTransferStarted(self, source, filename, filesize):
pass
def onFileTransferDone(self, source):
pass
def onSdStateChange(self, source, sdAvailable):
pass
def onSdFiles(self, source, files):
pass
def onLogTx(self, source, tx):
pass
def onLogRx(self, source, rx):
pass
def onLogError(self, source, error):
pass
class State(object):
OFFLINE = "Offline"
CONNECTING = "Connecting"
CONNECTED = "Connected"
OPERATIONAL = "Operational"
PRINTING = "Printing"
STREAMING = "Streaming"
PAUSED = "Paused"
ERROR = "Error"
### Printing file information classes ##################################################################################
class PrintingFileInformation(object):
"""
Encapsulates information regarding the current file being printed: file name, current position, total size and
time the print started.
Allows to reset the current file position to 0 and to calculate the current progress as a floating point
value between 0 and 1.
"""
def __init__(self, filename):
self._filename = filename
self._filepos = 0
self._filesize = None
self._startTime = None
def getStartTime(self):
return self._startTime
def getFilename(self):
return self._filename
def getFilesize(self):
return self._filesize
def getFilepos(self):
return self._filepos
def getFileLocation(self):
return FileDestinations.LOCAL
def getProgress(self):
"""
The current progress of the file, calculated as relation between file position and absolute size. Returns -1
if file size is None or < 1.
"""
if self._filesize is None or not self._filesize > 0:
return -1
return float(self._filepos) / float(self._filesize)
def reset(self):
"""
Resets the current file position to 0.
"""
self._filepos = 0
def start(self):
"""
Marks the print job as started and remembers the start time.
"""
self._startTime = time.time()
class PrintingSdFileInformation(PrintingFileInformation):
"""
Encapsulates information regarding an ongoing print from SD.
"""
def __init__(self, filename, filesize):
PrintingFileInformation.__init__(self, filename)
self._filesize = filesize
def setFilepos(self, filepos):
"""
Sets the current file position.
"""
self._filepos = filepos
def getFileLocation(self):
return FileDestinations.SDCARD
+59
View File
@@ -0,0 +1,59 @@
# coding=utf-8
__author__ = "Gina Häußge <osd@foosel.net>"
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = "Copyright (C) 2014 Gina Häußge - Released under terms of the AGPLv3 License"
import re
from octoprint.comm.protocol.reprap import RepRapProtocol
class RepetierTextualProtocol(RepRapProtocol):
__protocolinfo__ = ("repetier", "RepRap (Repetier Flavor)", False)
MESSAGE_TARGET_TEMPERATURE = staticmethod(lambda line: "TargetExtr" in line or "TargetBed" in line)
MESSAGE_TEMPERATURE = staticmethod(lambda line: RepRapProtocol.MESSAGE_TEMPERATURE(line) or RepetierTextualProtocol.MESSAGE_TARGET_TEMPERATURE(line))
REGEX_POSITIVE_FLOAT = "[+]?[0-9]*\.?[0-9]+"
REGEX_TARGET_EXTRUDER_TEMPERATURE = re.compile("TargetExtr([0-9]+):(%s)" % REGEX_POSITIVE_FLOAT)
REGEX_TARGET_BED_TEMPERATURE = re.compile("TargetBed:(%s)" % REGEX_POSITIVE_FLOAT)
def __init__(self, transport_factory, protocol_listener=None):
RepRapProtocol.__init__(self, transport_factory, protocol_listener)
self._sd_available = True
def _reset(self, from_start=False):
RepRapProtocol._reset(self, from_start=from_start)
self._sd_available = True
def _process_temperatures(self, line):
if RepetierTextualProtocol.MESSAGE_TARGET_TEMPERATURE(line):
match_extr = RepetierTextualProtocol.REGEX_TARGET_EXTRUDER_TEMPERATURE.match(line)
match_bed = RepetierTextualProtocol.REGEX_TARGET_BED_TEMPERATURE.match(line)
current_temperatures = self.get_current_temperatures()
key = None
target = None
try:
if match_extr is not None:
tool_num = int(match_extr.group(1))
key = "tool%d" % tool_num
target = float(match_extr.group(2))
elif match_bed is not None:
key = "bed"
target = float(match_bed.group(1))
except ValueError:
pass
if key is None:
return False
if key in current_temperatures and current_temperatures[key] is not None and isinstance(current_temperatures[key], tuple):
(actual, old_target) = current_temperatures[key]
current_temperatures[key] = (actual, target)
else:
current_temperatures[key] = (None, target)
self._updateTemperature(current_temperatures)
else:
RepRapProtocol._process_temperatures(self, line)
File diff suppressed because it is too large. Load diff
+377
View File
@@ -0,0 +1,377 @@
# coding=utf-8
__author__ = "Gina Häußge <osd@foosel.net>"
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = "Copyright (C) 2014 Gina Häußge - Released under terms of the AGPLv3 License"
import Queue
import re
import heapq
import os
import time
import itertools
from octoprint.comm.protocol import PrintingFileInformation
class GcodeCommand(object):
KNOWN_FLOAT_ATTRIBUTES = ("x", "y", "z", "e", "s", "p", "r")
KNOWN_INT_ATTRIBUTES = ("f", "t", "n")
KNOWN_ATTRIBUTES = KNOWN_FLOAT_ATTRIBUTES + KNOWN_INT_ATTRIBUTES
COMMAND_REGEX = re.compile("^([GMT])(\d+)")
ARGUMENT_REGEX = re.compile("\s+([%s][-+]?\d*\.?\d+|[%s][-+]?\d+)" % ("".join(map(lambda x: x.upper(), KNOWN_FLOAT_ATTRIBUTES)), "".join(map(lambda x: x.upper(), KNOWN_INT_ATTRIBUTES))))
PARAM_REGEX = re.compile("^[GMT]\d+\s+(.*?)$")
@staticmethod
def from_line(line):
line = line.strip()
command = ""
args = {"original": line}
match = GcodeCommand.COMMAND_REGEX.match(line)
if match is None:
args["unknown"] = True
else:
commandType = match.group(1)
commandNumber = int(match.group(2))
command = "%s%d" % (commandType, commandNumber)
if commandType == "T":
args["tool"] = commandNumber
else:
matchedArgs = GcodeCommand.ARGUMENT_REGEX.findall(line)
if len(matchedArgs) == 0:
paramMatch = GcodeCommand.PARAM_REGEX.match(line)
if paramMatch is not None:
args["param"] = paramMatch.group(1)
else:
for arg in matchedArgs:
key = arg[0].lower()
if key in GcodeCommand.KNOWN_INT_ATTRIBUTES:
value = int(arg[1:])
elif key in GcodeCommand.KNOWN_FLOAT_ATTRIBUTES:
value = float(arg[1:])
else:
value = str(arg[1:])
args[key] = value
return GcodeCommand(command, **args)
def __init__(self, command, **kwargs):
self.command = command
self.x = None
self.y = None
self.z = None
self.e = None
self.s = None
self.p = None
self.r = None
self.f = None
self.t = None
self.n = None
self.tool = None
self.original = None
self.param = None
self.progress = None
self.callback = None
self.unknown = False
for key, value in kwargs.iteritems():
if key in GcodeCommand.KNOWN_ATTRIBUTES + ("tool", "original", "param", "progress", "callback", "unknown"):
self.__setattr__(key, value)
def isGetTemperatureCommand(self):
return self.command == "M105"
def isSetTemperatureCommand(self):
return self.command in ("M104", "M140", "M109", "M190")
def isSelectToolCommand(self):
return self.command.startswith("T")
def __repr__(self):
return "GcodeCommand(\"{str}\",progress={progress})".format(str=str(self), progress=self.progress)
def __str__(self):
if self.original is not None:
return self.original
else:
attr = []
for key in GcodeCommand.KNOWN_ATTRIBUTES:
value = self.__getattribute__(key)
if value is not None:
if key in GcodeCommand.KNOWN_INT_ATTRIBUTES:
attr.append("%s%d" % (key.upper(), value))
elif key in GcodeCommand.KNOWN_FLOAT_ATTRIBUTES:
attr.append("%s%f" % (key.upper(), value))
else:
attr.append("%s%r" % (key.upper(), value))
attributeStr = " ".join(attr)
return "%s%s%s" % (self.command.upper(), " " + attributeStr if attributeStr else "", " " + self.param if self.param else "")
class CommandQueueEntry(object):
PRIORITY_RESEND = 1
PRIORITY_HIGH = 2
PRIORITY_NORMAL = 3
def __init__(self, priority, command, line_number=None, command_type=None, prepared=None):
self.priority = priority
self.command = command
self.line_number = line_number
self.command_type = command_type
self._prepared = prepared
self._size = 0
@property
def prepared(self):
return self._prepared
@prepared.setter
def prepared(self, prepared):
self._prepared = prepared
self._size = (len(prepared) + 1) if prepared is not None else 0
@property
def size(self):
return self._size
def __radd__(self, other):
return other + self._size
def __repr__(self):
return "CommandQueueEntry({command},prepared={prepared})".format(command=repr(self.command), prepared=self.prepared)
class SpecialCommandQueueEntry(CommandQueueEntry):
TYPE_JOBDONE = "JobDone"
TYPE_JOBCANCELLED = "JobCancelled"
def __init__(self, type):
CommandQueueEntry.__init__(self, CommandQueueEntry.PRIORITY_NORMAL, None)
self.type = type
def __repr__(self):
return "SpecialCommandQueueEntry(type={type})".format(type=self.type)
class CommandQueue(Queue.Queue):
'''Variant of Queue that retrieves open entries in priority order (lowest first, followed by addition order).
Entries need to be of the form (priority, command). An optional third argument commandType may be given:
(priority, command, commandType), the queue will ensure that only one command of a given commandType will ever
be in the queue.
'''
def _init(self, maxsize):
self.queue = []
self.lookup = {}
self.counter = itertools.count()
import threading
self.clearlock = threading.RLock()
def _qsize(self, len=len):
return len(self.queue)
def _put(self, item, heappush=heapq.heappush):
if not isinstance(item, CommandQueueEntry):
raise ValueError("queue can only take CommandQueueEntries, can't accept %r" % item)
command_type = item.command_type
if command_type is not None:
if command_type not in self.lookup:
self.lookup[command_type] = item
else:
raise TypeAlreadyInQueue()
heappush(self.queue, (item.priority, next(self.counter), item))
def _get(self, heappop=heapq.heappop):
priority, counter, item = heappop(self.queue)
if item.command_type in self.lookup:
del self.lookup[item.command_type]
return item
def _entry_at(self, index):
try:
return self.queue[index]
except IndexError:
return None
def _del(self, entry, heapify=True):
item = entry[2]
try:
self.queue.remove(entry)
if heapify:
heapq.heapify(self.queue)
except ValueError:
# that's ok, the entry probably just got removed already e.g. by print cancelling
pass
if item.command_type in self.lookup:
del self.lookup[item.command_type]
def peek(self):
"""
Returns the left most entry, result is either a tuple (priority, counter, CommandQueueEntry) or None (if queue
was empty).
"""
with self.mutex:
entry = self._entry_at(0)
return entry[2] if entry is not None else None, entry
def remove(self, entry):
with self.mutex:
self._del(entry)
def clear(self, matcher=None):
if matcher is None:
matcher = lambda x: True
cleared = []
with self.clearlock:
for entry in self.queue[:]:
priority, counter, item = entry
if matcher(item):
self._del(entry, heapify=False)
cleared.append(entry)
heapq.heapify(self.queue)
return cleared
def __repr__(self):
return repr(self.queue)
class TypeAlreadyInQueue(Exception):
pass
class PrintingGcodeFileInformation(PrintingFileInformation):
"""
Encapsulates information regarding an ongoing direct print. Takes care of the needed file handle and ensures
that the file is closed in case of an error.
"""
def __init__(self, filename, offsetCallback):
PrintingFileInformation.__init__(self, filename)
self._lineCount = None
self._firstLine = None
self._currentTool = 0
self._offsetCallback = offsetCallback
self._fileHandle = None
if not os.path.exists(self._filename) or not os.path.isfile(self._filename):
raise IOError("File %s does not exist" % self._filename)
self._filesize = os.stat(self._filename).st_size
def start(self):
"""
Opens the file for reading and determines the file size. Start time won't be recorded until 100 lines in
"""
self._filehandle = open(self._filename, "r")
self._lineCount = None
self._startTime = None
def getNext(self):
"""
Retrieves the next line for printing.
"""
if self._filehandle is None:
raise ValueError("File %s is not open for reading" % self._filename)
if self._lineCount is None:
self._lineCount = 0
self._startTime = time.time()
return GcodeCommand.from_line("M110 N0")
try:
command = None
while command is None:
if self._filehandle is None:
# file got closed just now
return None
line = self._filehandle.readline()
if not line:
self._filehandle.close()
self._filehandle = None
command = self._process_command(line)
self._lineCount += 1
self._filepos = self._filehandle.tell()
return command
except Exception as (e):
if self._filehandle is not None:
self._filehandle.close()
self._filehandle = None
raise e
def _process_command(self, line):
# remove all comments and trim the line
if ";" in line:
line = line[0:line.find(";")]
line = line.strip()
if len(line) > 0:
# we still got something left => parse the command
command = GcodeCommand.from_line(line)
if command is None:
return None
if command.isSelectToolCommand():
# track tool changes
self._currentTool = command.tool
elif command.isSetTemperatureCommand() and self._offsetCallback is not None:
# if we have a temperature command and an offset callback, retrieve current offsets
offsets = self._offsetCallback()
# extruder temperature, determine which one and retrieve corresponding offset
if command.command == "M104" or command.command == "M109":
tool_num = self._currentTool
if command.t is not None:
tool_num = command.t
key = "tool%d" % tool_num
# bed temperature
elif command.command == "M140" or command.command == "M190":
key = "bed"
# unknown, should never happen
else:
key = None
if key is not None and key in offsets:
offset = offsets[key]
command.s = command.s + offset
if command.original is not None:
command.original = None
# finally return the processed command
return command
else:
# no command, return None
return None
class StreamingGcodeFileInformation(PrintingGcodeFileInformation):
def __init__(self, path, localFilename, remoteFilename):
PrintingGcodeFileInformation.__init__(self, path, None)
self._localFilename = localFilename
self._remoteFilename = remoteFilename
def start(self):
PrintingGcodeFileInformation.start(self)
self._startTime = time.time()
def getLocalFilename(self):
return self._localFilename
def getRemoteFilename(self):
return self._remoteFilename
+121
View File
@@ -0,0 +1,121 @@
# coding=utf-8
__author__ = "Gina Häußge <osd@foosel.net>"
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = "Copyright (C) 2014 Gina Häußge - Released under terms of the AGPLv3 License"
import logging
from octoprint.events import eventManager, Events
class TransportError(Exception):
pass
class SendTimeout(Exception):
pass
class Transport(object):
def __init__(self, messageReceiver=None, stateReceiver=None, logReceiver=None):
self._transport_logger = logging.getLogger("TRANSPORT")
self._messageReceiver = messageReceiver
self._stateReceiver = stateReceiver
self._logReceiver = logReceiver
self._state = State.DISCONNECTED
self._error = None
self._opt = {}
def get_properties(self):
raise NotImplemented()
def get_connection_options(self):
return []
def get_current_connection(self):
return self._opt
def connect(self, opt):
self._opt = opt
def disconnect(self, onError=False):
if onError:
self.changeState(State.DISCONNECTED_WITH_ERROR)
else:
self.changeState(State.DISCONNECTED)
eventManager().fire(Events.DISCONNECTED)
def send(self, command):
pass
def receive(self):
pass
def changeState(self, newState):
oldState = self._state
self._state = newState
if self._stateReceiver is not None:
self._stateReceiver.onStateChangeReceived(self, oldState, newState)
def onError(self, error):
self.changeState(State.ERROR)
self._error = error
def onTimeout(self):
if self._messageReceiver is not None:
self._messageReceiver.onTimeoutReceived(self)
def getError(self):
return self._error
def logTx(self, tx):
if self._logReceiver is not None:
self._logReceiver.onLogTx(self, tx)
def logRx(self, rx):
if self._logReceiver is not None:
self._logReceiver.onLogRx(self, rx)
def logError(self, error):
if self._logReceiver is not None:
self._logReceiver.onLogError(self, error)
def onMessageReceived(self, message):
if self._messageReceiver is not None:
self._messageReceiver.onMessageReceived(self, message)
class TransportProperties(object):
FLOWCONTROL = "flowControl"
class State(object):
OPENING_CONNECTION = "Opening connection"
DETECTING_CONNECTION = "Detecting connection"
CONNECTED = "Connected"
DISCONNECTED = "Disconnected"
DISCONNECTED_WITH_ERROR = "Disconnected with error"
ERROR = "Error"
class MessageReceiver(object):
def onMessageReceived(self, source, message):
pass
def onTimeoutReceived(self, source):
pass
class StateReceiver(object):
def onStateChangeReceived(self, source, oldState, newState):
pass
class LogReceiver(object):
def onLogTx(self, source, tx):
pass
def onLogRx(self, source, rx):
pass
def onLogError(self, source, error):
pass
@@ -0,0 +1,192 @@
# coding=utf-8
__author__ = "Gina Häußge <osd@foosel.net>"
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = "Copyright (C) 2014 Gina Häußge - Released under terms of the AGPLv3 License"
import os
import glob
import threading
import serial
try:
import _winreg
except:
pass
from . import Transport, TransportProperties, State, SendTimeout, TransportError
from octoprint.util import getExceptionString
from octoprint.util.virtual import VirtualPrinter
from octoprint.settings import settings
from octoprint.events import eventManager, Events
class SerialTransport(Transport):
__transportinfo__ = ("serial", "Serial", False)
def __init__(self, messageReceiver, stateReceiver, logReceiver):
Transport.__init__(self, messageReceiver, stateReceiver, logReceiver)
self._serial = None
self._port = None
self._baudrate = None
self._connectionTimeout = None
self._writeTimeout = None
self._readTimeout = None
self._timeoutCounter = 0
self._maxTimeouts = 20
self._thread = None
def get_properties(self):
return {
TransportProperties.FLOWCONTROL: False
}
def get_connection_options(self):
return {
"port": self.__getSerialList(),
"baudrate": self.__getBaudrateList()
}
def connect(self, opt):
Transport.connect(self, opt)
self._port = opt["port"] if "port" in opt else None
self._baudrate = opt["baudrate"] if "baudrate" in opt else None
self._readTimeout = opt["timeout"]["read"] if "timeout" in opt and "read" in opt["timeout"] else 5.0
self._writeTimeout = opt["timeout"]["write"] if "timeout" in opt and "write" in opt["timeout"] else 0.5
if self._connect():
self._thread = threading.Thread(target=self._monitor, name="SerialTransportMonitor")
self._thread.daemon = True
self._thread.start()
def disconnect(self, onError=False):
try:
if self._serial is not None:
self._serial.close()
finally:
self._serial = None
self._thread = None
Transport.disconnect(self, onError)
def send(self, command):
commandToSend = command + "\n"
try:
self._serial.write(commandToSend)
self._transport_logger.info("Send: %s" % command)
self.logTx(command)
except serial.SerialTimeoutException:
self._transport_logger.warn("Timeout while sending: %s" % command)
self.logError("Serial timeout while writing to serial port, try again later.")
raise SendTimeout()
except:
exceptionString = getExceptionString()
self.logError("Unexpected error while writing serial port: %s" % exceptionString)
self.onError(exceptionString)
self.disconnect(True)
raise TransportError()
def receive(self):
return self._readline()
def _monitor(self):
error = None
while True:
line = self._readline()
if line is None:
error = "Serial connection closed unexpectedly"
break
if line == "":
self._timeoutCounter += 1
self.onTimeout()
if self._maxTimeouts and self._timeoutCounter > self._maxTimeouts:
error = "Printer did not respond at all over %d retries, considering it dead" % self._maxTimeouts
break
else:
self._timeoutCounter = 0
self.onMessageReceived(line.strip())
if error is not None:
self._transport_logger.error(error)
self.logError(error)
self.onError(error)
# TODO further error handling
def _connect(self):
self.changeState(State.OPENING_CONNECTION)
if self._port == "VIRTUAL":
self._serial = VirtualPrinter(read_timeout=self._readTimeout, write_timeout=self._writeTimeout)
self.changeState(State.CONNECTED)
self._transport_logger.debug("Connected to %s" % self._serial)
else:
try:
self._serial = serial.Serial(self._port, self._baudrate, timeout=self._readTimeout, writeTimeout=self._writeTimeout)
self.changeState(State.CONNECTED)
self._transport_logger.debug("Connected to %s" % self._serial)
except:
self.logError("Unexpected error while connecting to serial port: %s %s" % (self._port, getExceptionString()))
self.onError("Failed to open serial port, permissions correct?")
return False
eventManager().fire(Events.CONNECTED, {"port": self._port, "baudrate": self._baudrate})
return True
def _readline(self):
if self._serial is None:
return None
try:
line = self._serial.readline()
except:
exceptionString = getExceptionString()
self.logError("Unexpected error while reading serial port: %s" % exceptionString)
self.onError(exceptionString)
self.disconnect()
return None
if line != "":
loggable_line = unicode(line, "ascii", "replace").encode("ascii", "replace").rstrip()
self._transport_logger.debug("Recv: %s" % loggable_line)
self.logRx(loggable_line)
return line
def __getSerialList(self):
baselist=[]
if os.name == "nt":
try:
key=_winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE,"HARDWARE\\DEVICEMAP\\SERIALCOMM")
i=0
while(1):
baselist+=[_winreg.EnumValue(key,i)[1]]
i+=1
except:
pass
baselist = baselist \
+ glob.glob("/dev/ttyUSB*") \
+ glob.glob("/dev/ttyACM*") \
+ glob.glob("/dev/ttyAMA*") \
+ glob.glob("/dev/tty.usb*") \
+ glob.glob("/dev/cu.*") \
+ glob.glob("/dev/rfcomm*")
additionalPorts = settings().get(["serial", "additionalPorts"])
for additional in additionalPorts:
baselist += glob.glob(additional)
prev = settings().get(["serial", "port"])
if prev in baselist:
baselist.remove(prev)
baselist.insert(0, prev)
if settings().getBoolean(["devel", "virtualPrinter", "enabled"]):
baselist.append("VIRTUAL")
return baselist
def __getBaudrateList(self):
ret = [250000, 230400, 115200, 57600, 38400, 19200, 9600]
prev = settings().getInt(["serial", "baudrate"])
if prev in ret:
ret.remove(prev)
ret.insert(0, prev)
return ret
+5 -7
View File
@@ -4,7 +4,7 @@ Generic linux daemon base class for python 3.x
Originally from http://www.jejik.com/articles/2007/02/a_simple_unix_linux_daemon_in_python/#c35
"""
import sys, os, time, signal
import sys, os, time, atexit, signal
class Daemon:
"""A generic daemon class.
@@ -53,16 +53,14 @@ class Daemon:
os.dup2(se.fileno(), sys.stderr.fileno())
# write pidfile
atexit.register(self.delpid)
pid = str(os.getpid())
with open(self.pidfile,'w+') as f:
f.write(pid + '\n')
# register listener for SIGTERM
signal.signal(signal.SIGTERM, self.term)
def term(self, _signo, _stack_frame):
def delpid(self):
os.remove(self.pidfile)
sys.exit(0)
def start(self):
"""Start the daemon."""
+15 -19
View File
@@ -69,7 +69,6 @@ class Events(object):
CONVEYOR = "Conveyor"
EJECT = "Eject"
E_STOP = "EStop"
REGISTERED_MESSAGE_RECEIVED = "RegisteredMessageReceived"
# Timelapse
CAPTURE_START = "CaptureStart"
@@ -110,25 +109,22 @@ class EventManager(object):
self._worker.start()
def _work(self):
try:
while True:
(event, payload) = self._queue.get(True)
while True:
(event, payload) = self._queue.get(True)
eventListeners = self._registeredListeners[event]
self._logger.debug("Firing event: %s (Payload: %r)" % (event, payload))
eventListeners = self._registeredListeners[event]
self._logger.debug("Firing event: %s (Payload: %r)" % (event, payload))
for listener in eventListeners:
self._logger.debug("Sending action to %r" % listener)
try:
listener(event, payload)
except:
self._logger.exception("Got an exception while sending event %s (Payload: %r) to %s" % (event, payload, listener))
for listener in eventListeners:
self._logger.debug("Sending action to %r" % listener)
try:
listener(event, payload)
except:
self._logger.exception("Got an exception while sending event %s (Payload: %r) to %s" % (event, payload, listener))
octoprint.plugin.call_plugin(octoprint.plugin.types.EventHandlerPlugin,
"on_event",
args=[event, payload])
except:
self._logger.exception("Ooops, the event bus worker loop crashed")
octoprint.plugin.call_plugin(octoprint.plugin.types.EventHandlerPlugin,
"on_event",
args=[event, payload])
def fire(self, event, payload=None):
"""
@@ -305,7 +301,7 @@ class CommandTrigger(GenericEventListener):
else:
commandExecutioner(command)
except subprocess.CalledProcessError, e:
self._logger.warn("Command failed with return code %i: %s" % (e.returncode, str(e)))
self._logger.warn("Command failed with return code %i: %s" % (e.returncode, e.message))
except Exception, ex:
self._logger.exception("Command failed")
@@ -341,7 +337,7 @@ class CommandTrigger(GenericEventListener):
"__now": datetime.datetime.now().isoformat()
}
currentData = self._printer.get_current_data()
currentData = self._printer.getCurrentData()
if "currentZ" in currentData.keys() and currentData["currentZ"] is not None:
params["__currentZ"] = str(currentData["currentZ"])
+53 -80
View File
@@ -8,46 +8,27 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms
import logging
import os
import octoprint.plugin
import octoprint.util
from octoprint.events import eventManager, Events
from octoprint.plugin import plugin_manager, ProgressPlugin
from .destinations import FileDestinations
from .analysis import QueueEntry, AnalysisQueue
from .storage import LocalFileStorage
from .util import AbstractFileWrapper, StreamWrapper, DiskFileWrapper
extensions = dict(
)
def full_extension_tree():
result = dict(
# extensions for 3d model files
model=dict(
stl=["stl"]
),
# extensions for printable machine code
machinecode=dict(
gcode=["gcode", "gco", "g"]
)
# extensions for 3d model files
model=dict(
stl=["stl"]
),
# extensions for printable machine code
machinecode=dict(
gcode=["gcode", "gco", "g"]
)
extension_tree_hooks = octoprint.plugin.plugin_manager().get_hooks("octoprint.filemanager.extension_tree")
for name, hook in extension_tree_hooks.items():
try:
hook_result = hook()
if hook_result is None or not isinstance(hook_result, dict):
continue
result = octoprint.util.dict_merge(result, hook_result)
except:
logging.getLogger(__name__).exception("Exception while retrieving additional extension tree entries from hook {name}".format(name=name))
return result
)
def get_extensions(type, subtree=None):
if not subtree:
subtree = full_extension_tree()
subtree = extensions
for key, value in subtree.items():
if key == type:
@@ -61,7 +42,7 @@ def get_extensions(type, subtree=None):
def get_all_extensions(subtree=None):
if not subtree:
subtree = full_extension_tree()
subtree = extensions
result = []
if isinstance(subtree, dict):
@@ -76,7 +57,7 @@ def get_all_extensions(subtree=None):
def get_path_for_extension(extension, subtree=None):
if not subtree:
subtree = full_extension_tree()
subtree = extensions
for key, value in subtree.items():
if isinstance(value, (list, tuple)) and extension in value:
@@ -88,9 +69,11 @@ def get_path_for_extension(extension, subtree=None):
return None
all_extensions = get_all_extensions()
def valid_extension(extension, type=None):
if not type:
return extension in get_all_extensions()
return extension in all_extensions
else:
extensions = get_extensions(type)
if extensions:
@@ -131,25 +114,10 @@ class FileManager(object):
self._slicing_progress_callbacks = []
self._last_slicing_progress = None
self._progress_plugins = []
self._preprocessor_hooks = dict()
self._progress_plugins = plugin_manager().get_implementations(ProgressPlugin)
def initialize(self):
self.reload_plugins()
def worker():
self._logger.info("Adding backlog items from all storage types to analysis queue...".format(**locals()))
for storage_type, storage_manager in self._storage_managers.items():
self._determine_analysis_backlog(storage_type, storage_manager)
import threading
thread = threading.Thread(target=worker)
thread.daemon = True
thread.start()
def reload_plugins(self):
self._progress_plugins = octoprint.plugin.plugin_manager().get_implementations(octoprint.plugin.ProgressPlugin)
self._preprocessor_hooks = octoprint.plugin.plugin_manager().get_hooks("octoprint.filemanager.preprocessor")
for storage_type, storage_manager in self._storage_managers.items():
self._determine_analysis_backlog(storage_type, storage_manager)
def register_slicingprogress_callback(self, callback):
self._slicing_progress_callbacks.append(callback)
@@ -158,15 +126,13 @@ class FileManager(object):
self._slicing_progress_callbacks.remove(callback)
def _determine_analysis_backlog(self, storage_type, storage_manager):
counter = 0
self._logger.info("Adding backlog items from {storage_type} to analysis queue".format(**locals()))
for entry, path, printer_profile in storage_manager.analysis_backlog:
file_type = get_file_type(path)[-1]
# we'll use the default printer profile for the backlog since we don't know better
queue_entry = QueueEntry(entry, file_type, storage_type, path, self._printer_profile_manager.get_default())
self._analysis_queue.enqueue(queue_entry, high_priority=False)
counter += 1
self._logger.info("Added {counter} items from storage type \"{storage_type}\" to analysis queue".format(**locals()))
def add_storage(self, storage_type, storage_manager):
self._storage_managers[storage_type] = storage_manager
@@ -191,7 +157,7 @@ class FileManager(object):
def slice(self, slicer_name, source_location, source_path, dest_location, dest_path,
position=None, profile=None, printer_profile_id=None, overrides=None, callback=None, callback_args=None):
absolute_source_path = self.path_on_disk(source_location, source_path)
absolute_source_path = self.get_absolute_path(source_location, source_path)
def stlProcessed(source_location, source_path, tmp_path, dest_location, dest_path, start_time, printer_profile_id, callback, callback_args, _error=None, _cancelled=False, _analysis=None):
try:
@@ -203,12 +169,22 @@ class FileManager(object):
source_meta = self.get_metadata(source_location, source_path)
hash = source_meta["hash"]
import io
class Wrapper(object):
def __init__(self, stl_name, temp_path, hash):
self.stl_name = stl_name
self.temp_path = temp_path
self.hash = hash
def save(self, absolute_dest_path):
with open(absolute_dest_path, "w") as d:
d.write(";Generated from {stl_name} {hash}\r".format(**vars(self)))
with open(tmp_path, "r") as s:
import shutil
shutil.copyfileobj(s, d)
links = [("model", dict(name=source_path))]
_, stl_name = self.split_path(source_location, source_path)
file_obj = StreamWrapper(os.path.basename(dest_path),
io.BytesIO(u";Generated from {stl_name} {hash}\n".format(**locals()).encode("ascii", "replace")),
io.FileIO(tmp_path, "rb"))
file_obj = Wrapper(stl_name, temp_path, hash)
printer_profile = self._printer_profile_manager.get(printer_profile_id)
self.add_file(dest_location, dest_path, file_obj, links=links, allow_overwrite=True, printer_profile=printer_profile, analysis=_analysis)
@@ -255,17 +231,18 @@ class FileManager(object):
self._slicing_jobs[dest_job_key] = self._slicing_jobs[source_job_key] = (slicer_name, absolute_source_path, temp_path)
args = (source_location, source_path, temp_path, dest_location, dest_path, start_time, printer_profile_id, callback, callback_args)
self._slicing_manager.slice(slicer_name,
absolute_source_path,
temp_path,
profile,
stlProcessed,
position=position,
callback_args=args,
overrides=overrides,
printer_profile_id=printer_profile_id,
on_progress=self.on_slicing_progress,
on_progress_args=(slicer_name, source_location, source_path, dest_location, dest_path))
return self._slicing_manager.slice(
slicer_name,
absolute_source_path,
temp_path,
profile,
stlProcessed,
position=position,
callback_args=args,
overrides=overrides,
printer_profile_id=printer_profile_id,
on_progress=self.on_slicing_progress,
on_progress_args=(slicer_name, source_location, source_path, dest_location, dest_path))
def on_slicing_progress(self, slicer, source_location, source_path, dest_location, dest_path, _progress=None):
if not _progress:
@@ -280,11 +257,11 @@ class FileManager(object):
if progress_int:
def call_plugins(slicer, source_location, source_path, dest_location, dest_path, progress):
for plugin in self._progress_plugins:
for name, plugin in self._progress_plugins.items():
try:
plugin.on_slicing_progress(slicer, source_location, source_path, dest_location, dest_path, progress)
except:
self._logger.exception("Exception while sending slicing progress to plugin %s" % plugin._identifier)
self._logger.exception("Exception while sending slicing progress to plugin %s" % name)
import threading
thread = threading.Thread(target=call_plugins, args=(slicer, source_location, source_path, dest_location, dest_path, progress_int))
@@ -313,12 +290,8 @@ class FileManager(object):
if printer_profile is None:
printer_profile = self._printer_profile_manager.get_current_or_default()
for hook in self._preprocessor_hooks.values():
hook_file_object = hook(path, file_object, links=links, printer_profile=printer_profile, allow_overwrite=allow_overwrite)
if hook_file_object is not None:
file_object = hook_file_object
file_path = self._storage(destination).add_file(path, file_object, links=links, printer_profile=printer_profile, allow_overwrite=allow_overwrite)
absolute_path = self._storage(destination).path_on_disk(file_path)
absolute_path = self._storage(destination).get_absolute_path(file_path)
if analysis is None:
file_type = get_file_type(absolute_path)
@@ -370,8 +343,8 @@ class FileManager(object):
def remove_additional_metadata(self, destination, path, key):
self._storage(destination).remove_additional_metadata(path, key)
def path_on_disk(self, destination, path):
return self._storage(destination).path_on_disk(path)
def get_absolute_path(self, destination, path):
return self._storage(destination).get_absolute_path(path)
def sanitize(self, destination, path):
return self._storage(destination).sanitize(path)
@@ -388,8 +361,8 @@ class FileManager(object):
def join_path(self, destination, *path):
return self._storage(destination).join_path(*path)
def path_in_storage(self, destination, path):
return self._storage(destination).path_in_storage(path)
def rel_path(self, destination, path):
return self._storage(destination).rel_path(path)
def _storage(self, destination):
if not destination in self._storage_managers:
+10 -122
View File
@@ -11,7 +11,6 @@ import Queue as queue
import os
import threading
import collections
import time
from octoprint.events import Events, eventManager
@@ -19,40 +18,11 @@ import octoprint.util.gcodeInterpreter as gcodeInterpreter
class QueueEntry(collections.namedtuple("QueueEntry", "path, type, location, absolute_path, printer_profile")):
"""
A :class:`QueueEntry` for processing through the :class:`AnalysisQueue`. Wraps the entry's properties necessary
for processing.
Arguments:
path (str): Storage location specific path to the file to analyze.
type (str): Type of file to analyze, necessary to map to the correct :class:`AbstractAnalysisQueue` sub class.
At the moment, only ``gcode`` is supported here.
location (str): Location the file is located on.
absolute_path (str): Absolute path on disk through which to access the file.
printer_profile (PrinterProfile): :class:`PrinterProfile` which to use for analysis.
"""
def __str__(self):
return "{location}:{path}".format(location=self.location, path=self.path)
class AnalysisQueue(object):
"""
OctoPrint's :class:`AnalysisQueue` can manage various :class:`AbstractAnalysisQueue` implementations, mapped
by their machine code type.
At the moment, only the analysis of GCODE files for 3D printing is supported, through :class:`GcodeAnalysisQueue`.
By invoking :meth:`register_finish_callback` it is possible to register oneself as a callback to be invoked each
time the analysis of a queue entry finishes. The call parameters will be the finished queue entry as the first
and the analysis result as the second parameter. It is also possible to remove the registration again by invoking
:meth:`unregister_finish_callback`.
:meth:`enqueue` allows enqueuing :class:`QueueEntry` instances to analyze. If the :attr:`QueueEntry.type` is unknown
(no specific child class of :class:`AbstractAnalysisQueue` is registered for it), nothing will happen. Otherwise the
entry will be enqueued with the type specific analysis queue.
"""
def __init__(self):
self._logger = logging.getLogger(__name__)
self._callbacks = []
@@ -86,24 +56,6 @@ class AnalysisQueue(object):
eventManager().fire(Events.METADATA_ANALYSIS_FINISHED, {"file": entry.path, "result": result})
class AbstractAnalysisQueue(object):
"""
The :class:`AbstractAnalysisQueue` is the parent class of all specific analysis queues such as the
:class:`GcodeAnalysisQueue`. It offers methods to enqueue new entries to analyze and pausing and resuming analysis
processing.
Arguments:
finished_callback (callable): Callback that will be called upon finishing analysis of an entry in the queue.
The callback will be called with the analyzed entry as the first argument and the analysis result as
returned from the queue implementation as the second parameter.
.. automethod:: _do_analysis
.. automethod:: _do_abort
"""
LOW_PRIO = 0
HIGH_PRIO = 100
def __init__(self, finished_callback):
self._logger = logging.getLogger(__name__)
@@ -123,32 +75,16 @@ class AbstractAnalysisQueue(object):
self._worker.start()
def enqueue(self, entry, high_priority=False):
"""
Enqueues an ``entry`` for analysis by the queue.
If ``high_priority`` is True (defaults to False), the entry will be prioritized and hence processed before
other entries in the queue with normal priority.
Arguments:
entry (QueueEntry): The :class:`QueueEntry` to analyze.
high_priority (boolean): Whether to process the provided entry with high priority (True) or not
(False, default)
"""
if high_priority:
self._logger.debug("Adding entry {entry} to analysis queue with high priority".format(entry=entry))
prio = self.__class__.HIGH_PRIO
prio = 0
else:
self._logger.debug("Adding entry {entry} to analysis queue with low priority".format(entry=entry))
prio = self.__class__.LOW_PRIO
prio = 100
self._queue.put((prio, entry))
def pause(self):
"""
Pauses processing of the queue, e.g. when a print is active.
"""
self._logger.debug("Pausing analysis")
self._active.clear()
if self._current is not None:
@@ -156,10 +92,6 @@ class AbstractAnalysisQueue(object):
self._do_abort()
def resume(self):
"""
Resumes processing of the queue, e.g. when a print has finished.
"""
self._logger.debug("Resuming analyzer")
self._active.set()
@@ -177,15 +109,13 @@ class AbstractAnalysisQueue(object):
self._active.wait()
try:
self._analyze(entry, high_priority=(priority == self.__class__.HIGH_PRIO))
self._analyze(entry)
self._queue.task_done()
except gcodeInterpreter.AnalysisAborted:
aborted = entry
self._logger.debug("Running analysis of entry {entry} aborted".format(**locals()))
else:
time.sleep(1.0)
def _analyze(self, entry, high_priority=False):
def _analyze(self, entry):
path = entry.absolute_path
if path is None or not os.path.exists(path):
return
@@ -194,70 +124,28 @@ class AbstractAnalysisQueue(object):
self._current_progress = 0
try:
self._logger.info("Starting analysis of {entry}".format(**locals()))
self._logger.debug("Starting analysis of {entry}".format(**locals()))
eventManager().fire(Events.METADATA_ANALYSIS_STARTED, {"file": entry.path, "type": entry.type})
try:
result = self._do_analysis(high_priority=high_priority)
except TypeError:
result = self._do_analysis()
result = self._do_analysis()
self._logger.debug("Analysis of entry {entry} finished, notifying callback".format(**locals()))
self._finished_callback(self._current, result)
finally:
self._current = None
self._current_progress = None
def _do_analysis(self, high_priority=False):
"""
Performs the actual analysis of the current entry which can be accessed via ``self._current``. Needs to be
overridden by sub classes.
Arguments:
high_priority (bool): Whether the current entry has high priority or not.
Returns:
object: The result of the analysis which will be forwarded to the ``finished_callback`` provided during
construction.
"""
def _do_analysis(self):
return None
def _do_abort(self):
"""
Aborts analysis of the current entry. Needs to be overridden by sub classes.
"""
pass
class GcodeAnalysisQueue(AbstractAnalysisQueue):
"""
A queue to analyze GCODE files. Analysis results are :class:`dict` instances structured as follows:
.. list-table::
:widths: 25 70
- * **Key**
* **Description**
- * ``estimatedPrintTime``
* Estimated time the file take to print, in minutes
- * ``filament``
* Substructure describing estimated filament usage. Keys are ``tool0`` for the first extruder, ``tool1`` for
the second and so on. For each tool extruded length and volume (based on diameter) are provided.
- * ``filament.toolX.length``
* The extruded length in mm
- * ``filament.toolX.volume``
* The extruded volume in cm³
"""
def _do_analysis(self, high_priority=False):
def _do_analysis(self):
try:
def throttle():
time.sleep(0.01)
throttle_callback = throttle
if high_priority:
throttle_callback = None
self._gcode = gcodeInterpreter.gcode()
self._gcode.load(self._current.absolute_path, self._current.printer_profile, throttle=throttle_callback)
self._gcode.load(self._current.absolute_path, self._current.printer_profile)
result = dict()
if self._gcode.totalMoveTimeMinute:
@@ -275,4 +163,4 @@ class GcodeAnalysisQueue(AbstractAnalysisQueue):
def _do_abort(self):
if self._gcode:
self._gcode.abort()
self._gcode.abort()
+300 -485
View File
@@ -13,34 +13,123 @@ import tempfile
import octoprint.filemanager
class StorageInterface(object):
"""
Interface of storage adapters for OctoPrint.
"""
from octoprint.util import safeRename
class StorageInterface(object):
@property
def analysis_backlog(self):
"""
Get an iterator over all items stored in the storage that need to be analysed by the :class:`~octoprint.filemanager.AnalysisQueue`.
The yielded elements are expected as storage specific absolute paths to the respective files. Don't forget
to recurse into folders if your storage adapter supports those.
:return: an iterator yielding all un-analysed files in the storage
"""
# empty generator pattern, yield is intentionally unreachable
return
yield
def file_exists(self, path):
"""
Returns whether the file indicated by ``path`` exists or not.
:param string path: the path to check for existence
:return: ``True`` if the file exists, ``False`` otherwise
"""
raise NotImplementedError()
def list_files(self, path=None, filter=None, recursive=True):
raise NotImplementedError()
def add_folder(self, path, ignore_existing=True):
raise NotImplementedError()
def remove_folder(self, path, recursive=True):
raise NotImplementedError()
def add_file(self, path, file_object, printer_profile=None, links=None, allow_overwrite=False):
raise NotImplementedError()
def remove_file(self, path):
raise NotImplementedError()
def get_metadata(self, path):
raise NotImplementedError()
def add_link(self, path, rel, data):
raise NotImplementedError()
def remove_link(self, path, rel, data):
raise NotImplementedError()
def set_additional_metadata(self, path, key, data, overwrite=False, merge=False):
raise NotImplementedError()
def remove_additional_metadata(self, path, key):
raise NotImplementedError()
def sanitize(self, path):
raise NotImplementedError()
def sanitize_path(self, path):
raise NotImplementedError()
def sanitize_name(self, name):
raise NotImplementedError()
def split_path(self, path):
raise NotImplementedError()
def join_path(self, *path):
raise NotImplementedError()
def rel_path(self, path):
raise NotImplementedError()
def get_absolute_path(self, path):
raise NotImplementedError()
class LocalFileStorage(StorageInterface):
def __init__(self, basefolder, create=False):
self._logger = logging.getLogger(__name__)
self.basefolder = os.path.realpath(os.path.abspath(basefolder))
if not os.path.exists(self.basefolder) and create:
os.makedirs(self.basefolder)
if not os.path.exists(self.basefolder) or not os.path.isdir(self.basefolder):
raise RuntimeError("{basefolder} is not a valid directory".format(**locals()))
import threading
self._metadata_lock = threading.Lock()
self._metadata_cache = pylru.lrucache(10)
@property
def analysis_backlog(self):
for entry in self._analysis_backlog_generator():
yield entry
def _analysis_backlog_generator(self, path=None):
if path is None:
path = self.basefolder
metadata = self._get_metadata(path)
if not metadata:
metadata = dict()
for entry in os.listdir(path):
if entry.startswith(".") or not octoprint.filemanager.valid_file_type(entry):
continue
absolute_path = os.path.join(path, entry)
if os.path.isfile(absolute_path):
if not entry in metadata or not isinstance(metadata[entry], dict) or not "analysis" in metadata[entry]:
printer_profile_rels = self.get_link(absolute_path, "printerprofile")
if printer_profile_rels:
printer_profile_id = printer_profile_rels[0]["id"]
else:
printer_profile_id = None
yield entry, absolute_path, printer_profile_id
elif os.path.isdir(absolute_path):
for sub_entry in self._analysis_backlog_generator(absolute_path):
yield self.join_path(entry, sub_entry[0]), sub_entry[1], sub_entry[2]
def file_exists(self, path):
path, name = self.sanitize(path)
file_path = os.path.join(path, name)
return os.path.exists(file_path) and os.path.isfile(file_path)
def list_files(self, path=None, filter=None, recursive=True):
"""
List all files in storage starting at ``path``. If ``recursive`` is set to True (the default), also dives into
@@ -83,303 +172,14 @@ class StorageInterface(object):
...
}
:param string path: base path from which to recursively list all files, optional, if not supplied listing will start
from root of base folder
:param function filter: a filter that matches the files that are to be returned, may be left out in which case no
filtering will take place
:param bool recursive: will also step into sub folders for building the complete list if set to True
:param path: base path from which to recursively list all files, optional, if not supplied listing will start
from root of base folder
:param filter: a filter that matches the files that are to be returned, may be left out in which case no
filtering will take place
:param recursive: will also step into sub folders for building the complete list if set to True
:return: a dictionary mapping entry names to entry data that represents the whole file list
"""
raise NotImplementedError()
def add_folder(self, path, ignore_existing=True):
"""
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
:return: the sanitized name of the new folder to be used for future references to the folder
"""
raise NotImplementedError()
def remove_folder(self, path, recursive=True):
"""
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
be raised if the folder is not empty (apart from ``.metadata.yaml``) when it's to be removed
"""
raise NotImplementedError()
def add_file(self, path, file_object, printer_profile=None, links=None, allow_overwrite=False):
"""
Adds the file ``file_object`` as ``path``
:param string path: the file's new path, will be sanitized
:param object file_object: a file object that provides a ``save`` method which will be called with the destination path
where the object should then store its contents
:param object printer_profile: the printer profile associated with this file (if any)
:param list links: any links to add with the file
:param bool allow_overwrite: if set to True no error will be raised if the file already exists and the existing file
and its metadata will just be silently overwritten
:return: the sanitized name of the file to be used for future references to it
"""
raise NotImplementedError()
def remove_file(self, path):
"""
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
"""
raise NotImplementedError()
def get_metadata(self, path):
"""
Retrieves the metadata for the file ``path``.
:param path: virtual path to the file for which to retrieve the metadata
:return: the metadata associated with the file
"""
raise NotImplementedError()
def add_link(self, path, rel, data):
"""
Adds a link of relation ``rel`` to file ``path`` with the given ``data``.
The following relation types are currently supported:
* ``model``: adds a link to a model from which the file was created/sliced, expected additional data is the ``name``
and optionally the ``hash`` of the file to link to. If the link can be resolved against another file on the
current ``path``, not only will it be added to the links of ``name`` but a reverse link of type ``machinecode``
refering to ``name`` and its hash will also be added to the linked ``model`` file
* ``machinecode``: adds a link to a file containing machine code created from the current file (model), expected
additional data is the ``name`` and optionally the ``hash`` of the file to link to. If the link can be resolved
against another file on the current ``path``, not only will it be added to the links of ``name`` but a reverse
link of type ``model`` refering to ``name`` and its hash will also be added to the linked ``model`` file.
* ``web``: adds a location on the web associated with this file (e.g. a website where to download a model),
expected additional data is a ``href`` attribute holding the website's URL and optionally a ``retrieved``
attribute describing when the content was retrieved
Note that adding ``model`` links to files identifying as models or ``machinecode`` links to files identifying
as machine code will be refused.
:param path: path of the file for which to add a link
:param rel: type of relation of the link to add (currently ``model``, ``machinecode`` and ``web`` are supported)
:param data: additional data of the link to add
"""
raise NotImplementedError()
def remove_link(self, path, rel, data):
"""
Removes the link consisting of ``rel`` and ``data`` from file ``name`` on ``path``.
:param path: path of the file from which to remove the link
:param rel: type of relation of the link to remove (currently ``model``, ``machinecode`` and ``web`` are supported)
:param data: additional data of the link to remove, must match existing link
"""
raise NotImplementedError()
def set_additional_metadata(self, path, key, data, overwrite=False, merge=False):
"""
Adds additional metadata to the metadata of ``path``. Metadata in ``data`` will be saved under ``key``.
If ``overwrite`` is set and ``key`` already exists in ``name``'s metadata, the current value will be overwritten.
If ``merge`` is set and ``key`` already exists and both ``data`` and the existing data under ``key`` are dictionaries,
the two dictionaries will be merged recursively.
:param path: the virtual path to the file for which to add additional metadata
:param key: key of metadata to add
:param data: metadata to add
:param overwrite: if True and ``key`` already exists, it will be overwritten
:param merge: if True and ``key`` already exists and both ``data`` and the existing data are dictionaries, they
will be merged
"""
raise NotImplementedError()
def remove_additional_metadata(self, path, key):
"""
Removes additional metadata under ``key`` for ``name`` on ``path``
:param path: the virtual path to the file for which to remove the metadata under ``key``
:param key: the key to remove
"""
raise NotImplementedError()
def sanitize(self, path):
"""
Sanitizes the given ``path``, stripping it of all invalid characters. The ``path`` may consist of both
folder and file name, the underlying implementation must separate those if necessary and sanitize individually.
:param string path: the path to sanitize
:return: a 2-tuple containing the sanitized path and file name
"""
raise NotImplementedError()
def sanitize_path(self, path):
"""
Sanitizes the given folder-only ``path``, stripping it of all invalid characters.
:param string path: the path to sanitize
:return: the sanitized path
"""
raise NotImplementedError()
def sanitize_name(self, name):
"""
Sanitizes the given file ``name``, stripping it of all invalid characters.
:param string name: the file name to sanitize
:return: the sanitized name
"""
raise NotImplementedError()
def split_path(self, path):
"""
Split ``path`` into base directory and file name.
:param path: the path to split
:return: a tuple (base directory, file name)
"""
raise NotImplementedError()
def join_path(self, *path):
"""
Join path elements together
:param path: path elements to join
:return: joined representation of the path to be usable as fully qualified path for further operations
"""
raise NotImplementedError()
def path_on_disk(self, path):
"""
Retrieves the path on disk for ``path``.
Note: if the storage is not on disk and there exists no path on disk to refer to it, this method should
raise an :class:`io.UnsupportedOperation`
Opposite of :func:`path_in_storage`.
:param string path: the virtual path for which to retrieve the path on disk
:return: the path on disk to ``path``
"""
raise NotImplementedError()
def path_in_storage(self, path):
"""
Retrieves the equivalent in the storage adapter for ``path``.
Opposite of :func:`path_on_disk`.
:param string path: the path for which to retrieve the storage path
:return: the path in storage to ``path``
"""
raise NotImplementedError()
class LocalFileStorage(StorageInterface):
"""
The ``LocalFileStorage`` is a storage implementation which holds all files, folders and metadata on disk.
Metadata is managed inside ``.metadata.yaml`` files in the respective folders, indexed by the sanitized filenames
stored within the folder. Metadata access is managed through an LRU cache to minimize access overhead.
This storage type implements :func:`path_on_disk`.
"""
def __init__(self, basefolder, create=False):
"""
Initializes a ``LocalFileStorage`` instance under the given ``basefolder``, creating the necessary folder
if necessary and ``create`` is set to ``True``.
:param string basefolder: the path to the folder under which to create the storage
:param bool create: ``True`` if the folder should be created if it doesn't exist yet, ``False`` otherwise
"""
self._logger = logging.getLogger(__name__)
self.basefolder = os.path.realpath(os.path.abspath(basefolder))
if not os.path.exists(self.basefolder) and create:
os.makedirs(self.basefolder)
if not os.path.exists(self.basefolder) or not os.path.isdir(self.basefolder):
raise RuntimeError("{basefolder} is not a valid directory".format(**locals()))
import threading
self._metadata_lock = threading.Lock()
self._metadata_cache = pylru.lrucache(10)
self._old_metadata = None
self._initialize_metadata()
def _initialize_metadata(self):
self._logger.info("Initializing the file metadata for {}...".format(self.basefolder))
old_metadata_path = os.path.join(self.basefolder, "metadata.yaml")
backup_path = os.path.join(self.basefolder, "metadata.yaml.backup")
if os.path.exists(old_metadata_path):
# load the old metadata file
try:
with open(old_metadata_path) as f:
import yaml
self._old_metadata = yaml.safe_load(f)
except:
self._logger.exception("Error while loading old metadata file")
# make sure the metadata is initialized as far as possible
self._list_folder(self.basefolder)
# rename the old metadata file
self._old_metadata = None
try:
import shutil
shutil.move(old_metadata_path, backup_path)
except:
self._logger.exception("Could not rename old metadata.yaml file")
else:
# make sure the metadata is initialized as far as possible
self._list_folder(self.basefolder)
self._logger.info("... file metadata for {} initialized successfully.".format(self.basefolder))
@property
def analysis_backlog(self):
for entry in self._analysis_backlog_generator():
yield entry
def _analysis_backlog_generator(self, path=None):
if path is None:
path = self.basefolder
metadata = self._get_metadata(path)
if not metadata:
metadata = dict()
for entry in os.listdir(path):
if entry.startswith(".") or not octoprint.filemanager.valid_file_type(entry):
continue
absolute_path = os.path.join(path, entry)
if os.path.isfile(absolute_path):
if not entry in metadata or not isinstance(metadata[entry], dict) or not "analysis" in metadata[entry]:
printer_profile_rels = self.get_link(absolute_path, "printerprofile")
if printer_profile_rels:
printer_profile_id = printer_profile_rels[0]["id"]
else:
printer_profile_id = None
yield entry, absolute_path, printer_profile_id
elif os.path.isdir(absolute_path):
for sub_entry in self._analysis_backlog_generator(absolute_path):
yield self.join_path(entry, sub_entry[0]), sub_entry[1], sub_entry[2]
def file_exists(self, path):
path, name = self.sanitize(path)
file_path = os.path.join(path, name)
return os.path.exists(file_path) and os.path.isfile(file_path)
def list_files(self, path=None, filter=None, recursive=True):
if path:
path = self.sanitize_path(path)
else:
@@ -387,6 +187,14 @@ class LocalFileStorage(StorageInterface):
return self._list_folder(path, filter=filter, recursive=recursive)
def add_folder(self, path, ignore_existing=True):
"""
Adds a folder as ``path``. The ``path`` will be sanitized.
:param path: the path of the new folder
:param ignore_existing: if set to True, no error will be raised if the folder to be added already exists
:return: the sanitized name of the new folder to be used for future references to the folder
"""
path, name = self.sanitize(path)
folder_path = os.path.join(path, name)
@@ -396,9 +204,17 @@ class LocalFileStorage(StorageInterface):
else:
os.mkdir(folder_path)
return self.path_in_storage((path, name))
return self.rel_path((path, name))
def remove_folder(self, path, recursive=True):
"""
Removes the folder at ``path``.
:param path: the path of the folder to remove
:param recursive: if set to True, contained folders and files will also be removed, otherwise and error will
be raised if the folder is not empty (apart from ``.metadata.yaml``) when it's to be removed
"""
path, name = self.sanitize(path)
folder_path = os.path.join(path, name)
@@ -415,6 +231,19 @@ class LocalFileStorage(StorageInterface):
shutil.rmtree(folder_path)
def add_file(self, path, file_object, printer_profile=None, links=None, allow_overwrite=False):
"""
Adds the file ``file_object`` as ``path``
:param path: the file's new path, will be sanitized
:param file_object: a file object that provides a ``save`` method which will be called with the destination path
where the object should then store its contents
:param printer_profile: the printer profile associated with this file (if any)
:param links: any links to add with the file
:param allow_overwrite: if set to True no error will be raised if the file already exists and the existing file
and its metadata will just be silently overwritten
:return: the sanitized name of the file to be used for future references to it
"""
path, name = self.sanitize(path)
if not octoprint.filemanager.valid_file_type(name):
raise RuntimeError("{name} is an unrecognized file type".format(**locals()))
@@ -455,9 +284,16 @@ class LocalFileStorage(StorageInterface):
self._add_links(name, path, links)
return self.path_in_storage((path, name))
return self.rel_path((path, name))
def remove_file(self, path):
"""
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 path: path of the file to remove
"""
path, name = self.sanitize(path)
metadata = self._get_metadata(path)
@@ -486,6 +322,13 @@ class LocalFileStorage(StorageInterface):
self._save_metadata(path, metadata)
def get_metadata(self, path):
"""
Retrieves the metadata for the file ``path``.
:param path: virtual path to the file for which to retrieve the metadata
:return: the metadata associated with the file
"""
path, name = self.sanitize(path)
metadata = self._get_metadata(path)
@@ -500,10 +343,43 @@ class LocalFileStorage(StorageInterface):
def add_link(self, path, rel, data):
"""
Adds a link of relation ``rel`` to file ``path`` with the given ``data``.
The following relation types are currently supported:
* ``model``: adds a link to a model from which the file was created/sliced, expected additional data is the ``name``
and optionally the ``hash`` of the file to link to. If the link can be resolved against another file on the
current ``path``, not only will it be added to the links of ``name`` but a reverse link of type ``machinecode``
refering to ``name`` and its hash will also be added to the linked ``model`` file
* ``machinecode``: adds a link to a file containing machine code created from the current file (model), expected
additional data is the ``name`` and optionally the ``hash`` of the file to link to. If the link can be resolved
against another file on the current ``path``, not only will it be added to the links of ``name`` but a reverse
link of type ``model`` refering to ``name`` and its hash will also be added to the linked ``model`` file.
* ``web``: adds a location on the web associated with this file (e.g. a website where to download a model),
expected additional data is a ``href`` attribute holding the website's URL and optionally a ``retrieved``
attribute describing when the content was retrieved
Note that adding ``model`` links to files identifying as models or ``machinecode`` links to files identifying
as machine code will be refused.
:param path: path of the file for which to add a link
:param rel: type of relation of the link to add (currently ``model``, ``machinecode`` and ``web`` are supported)
:param data: additional data of the link to add
"""
path, name = self.sanitize(path)
self._add_links(name, path, [(rel, data)])
def remove_link(self, path, rel, data):
"""
Removes the link consisting of ``rel`` and ``data`` from file ``name`` on ``path``.
:param path: path of the file from which to remove the link
:param rel: type of relation of the link to remove (currently ``model``, ``machinecode`` and ``web`` are supported)
:param data: additional data of the link to remove, must match existing link
"""
path, name = self.sanitize(path)
self._remove_links(name, path, [(rel, data)])
@@ -520,6 +396,22 @@ class LocalFileStorage(StorageInterface):
self._update_history(name, path, index)
def set_additional_metadata(self, path, key, data, overwrite=False, merge=False):
"""
Adds additional metadata to the metadata of ``path``. Metadata in ``data`` will be saved under ``key``.
If ``overwrite`` is set and ``key`` already exists in ``name``'s metadata, the current value will be overwritten.
If ``merge`` is set and ``key`` already exists and both ``data`` and the existing data under ``key`` are dictionaries,
the two dictionaries will be merged recursively.
:param path: the virtual path to the file for which to add additional metadata
:param key: key of metadata to add
:param data: metadata to add
:param overwrite: if True and ``key`` already exists, it will be overwritten
:param merge: if True and ``key`` already exists and both ``data`` and the existing data are dictionaries, they
will be merged
"""
path, name = self.sanitize(path)
metadata = self._get_metadata(path)
metadata_dirty = False
@@ -545,6 +437,13 @@ class LocalFileStorage(StorageInterface):
self._save_metadata(path, metadata)
def remove_additional_metadata(self, path, key):
"""
Removes additional metadata under ``key`` for ``name`` on ``path``
:param path: the virtual path to the file for which to remove the metadata under ``key``
:param key: the key to remove
"""
path, name = self.sanitize(path)
metadata = self._get_metadata(path)
@@ -558,6 +457,13 @@ class LocalFileStorage(StorageInterface):
self._save_metadata(path, metadata)
def split_path(self, path):
"""
Split ``path`` into base directory and file name.
:param path: the path to split
:return: a tuple (base directory, file name)
"""
split = path.split("/")
if len(split) == 1:
return "", split[0]
@@ -565,143 +471,21 @@ class LocalFileStorage(StorageInterface):
return self.join_path(*split[:-1]), split[-1]
def join_path(self, *path):
"""
Join path elements together
:param path: path elements to join
:return: joined representation of the path to be usable as fully qualified path for further operations
"""
return "/".join(path)
def sanitize(self, path):
def get_absolute_path(self, path):
"""
Returns a ``(path, name)`` tuple derived from the provided ``path``.
Retrieves the absolute path on disk for ``path``
``path`` may be:
* a storage path
* an absolute file system path
* a tuple or list containing all individual path elements
* a string representation of the path
* with or without a file name
Note that for a ``path`` without a trailing slash the last part will be considered a file name and
hence be returned at second position. If you only need to convert a folder path, be sure to
include a trailing slash for a string ``path`` or an empty last element for a list ``path``.
Examples::
>>> storage = LocalFileStorage("/some/base/folder")
>>> storage.sanitize("some/folder/and/some file.gco")
("/some/base/folder/some/folder/and", "some_file.gco")
>>> storage.sanitize(("some", "folder", "and", "some file.gco"))
("/some/base/folder/some/folder/and", "some_file.gco")
>>> storage.sanitize("some file.gco")
("/some/base/folder", "some_file.gco")
>>> storage.sanitize(("some file.gco",))
("/some/base/folder", "some_file.gco")
>>> storage.sanitize("")
("/some/base/folder", "")
>>> storage.sanitize("some/folder/with/trailing/slash/")
("/some/base/folder/some/folder/with/trailing/slash", "")
>>> storage.sanitize("some", "folder", "")
("/some/base/folder/some/folder", "")
:param path: the virtual path for which to retrieve the absolute path on disk
:return: the absolute path on disk to ``path``
"""
name = None
if isinstance(path, (str, unicode, basestring)):
if path.startswith(self.basefolder):
path = path[len(self.basefolder):]
path = path.replace(os.path.sep, "/")
path = path.split("/")
if isinstance(path, (list, tuple)):
if len(path) == 1:
name = path[0]
path = "/"
else:
name = path[-1]
path = "/" + self.join_path(*path[:-1])
if not path:
path = "/"
name = self.sanitize_name(name)
path = self.sanitize_path(path)
return path, name
def sanitize_name(self, name):
"""
Raises a :class:`ValueError` for a ``name`` containing ``/`` or ``\``. Otherwise strips any characters from the
given ``name`` that are not any of the ASCII characters, digits, ``-``, ``_``, ``.``, ``(``, ``)`` or space and
replaces and spaces with ``_``.
Examples::
>>> storage = LocalFileStorage("/some/base/folder")
>>> storage.sanitize_name("some_file.gco")
"some_file.gco"
>>> storage.sanitize_name("some_file with (parentheses) and ümläuts and digits 123.gco")
"some_file_with_(parentheses)_and_mluts_and_digits_123.gco"
>>> storage.sanitize_name("pengüino pequeño.stl")
"pengino_pequeo.stl"
>>> storage.sanitize_name("some/folder/still/left.gco")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: name must not contain / or \
>>> storage.sanitize_name("also\\no\\backslashes.gco")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: name must not contain / or \
"""
if name is None:
return None
if "/" in name or "\\" in name:
raise ValueError("name must not contain / or \\")
import string
valid_chars = "-_.() {ascii}{digits}".format(ascii=string.ascii_letters, digits=string.digits)
sanitized_name = ''.join(c for c in name if c in valid_chars)
sanitized_name = sanitized_name.replace(" ", "_")
return sanitized_name
def sanitize_path(self, path):
"""
Ensures that the on disk representation of ``path`` is located under the configured basefolder. Resolves all
relative path elements (e.g. ``..``) and sanitizes folder names using :func:`sanitize_name`. Final path is the
absolute path including leading ``basefolder`` path.
Examples::
>>> storage = LocalFileStorage("/some/base/folder")
>>> storage.sanitize_path("folder/with/subfolder")
"/some/base/folder/folder/with/subfolder"
>>> storage.sanitize_path("folder/with/subfolder/../other/folder")
"/some/base/folder/folder/with/other/folder"
>>> storage.sanitize_path("/folder/with/leading/slash")
"/some/base/folder/folder/with/leading/slash"
>>> storage.sanitize_path(".folder/with/leading/dot")
"/some/base/folder/folder/with/leading/dot
>>> storage.sanitize_path("../../folder/out/of/the/basefolder")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: path not contained in base folder: /some/folder/out/of/the/basefolder
"""
if path[0] == "/" or path[0] == ".":
path = path[1:]
path_elements = path.split("/")
joined_path = self.basefolder
for path_element in path_elements:
joined_path = os.path.join(joined_path, self.sanitize_name(path_element))
path = os.path.realpath(joined_path)
if not path.startswith(self.basefolder):
raise ValueError("path not contained in base folder: {path}".format(**locals()))
return path
def path_in_storage(self, path):
if isinstance(path, (tuple, list)):
path = self.join_path(*path)
if isinstance(path, (str, unicode, basestring)):
if path.startswith(self.basefolder):
path = path[len(self.basefolder):]
path = path.replace(os.path.sep, "/")
if path.startswith("/"):
path = path[1:]
return path
def path_on_disk(self, path):
path, name = self.sanitize(path)
return os.path.join(path, name)
@@ -954,7 +738,12 @@ class LocalFileStorage(StorageInterface):
if entry in metadata and isinstance(metadata[entry], dict):
entry_data = metadata[entry]
else:
entry_data = self._add_basic_metadata(path, entry, save=False, metadata=metadata)
entry_data = dict(
hash=self._create_hash(entry_path),
links=[],
notes=[]
)
metadata[entry] = entry_data
metadata_dirty = True
# TODO extract model hash from source if possible to recreate link
@@ -989,31 +778,6 @@ class LocalFileStorage(StorageInterface):
return result
def _add_basic_metadata(self, path, entry, additional_metadata=None, save=True, metadata=None):
if additional_metadata is None:
additional_metadata = dict()
if metadata is None:
metadata = self._get_metadata(path)
entry_data = dict(
hash=self._create_hash(os.path.join(path, entry)),
links=[],
notes=[]
)
if path == self.basefolder and self._old_metadata is not None and entry in self._old_metadata and "gcodeAnalysis" in self._old_metadata[entry]:
# if there is still old metadata available and that contains an analysis for this file, use it!
entry_data["analysis"] = self._old_metadata[entry]["gcodeAnalysis"]
entry_data.update(additional_metadata)
metadata[entry] = entry_data
if save:
self._save_metadata(path, metadata)
return entry_data
def _create_hash(self, path):
import hashlib
@@ -1027,6 +791,64 @@ class LocalFileStorage(StorageInterface):
return hash.hexdigest()
def sanitize(self, path):
name = None
if isinstance(path, (str, unicode, basestring)):
if path.startswith(self.basefolder):
path = path[len(self.basefolder):]
path = path.replace(os.path.sep, "/")
path = path.split("/")
if isinstance(path, (list, tuple)):
if len(path) == 1:
name = path[0]
path = "/"
else:
name = path[-1]
path = "/" + self.join_path(*path[:-1])
if not path:
path = "/"
name = self.sanitize_name(name)
path = self.sanitize_path(path)
return path, name
def sanitize_name(self, name):
if name is None:
return None
if "/" in name or "\\" in name:
raise ValueError("name must not contain / or \\")
import string
valid_chars = "-_.() {ascii}{digits}".format(ascii=string.ascii_letters, digits=string.digits)
sanitized_name = ''.join(c for c in name if c in valid_chars)
sanitized_name = sanitized_name.replace(" ", "_")
return sanitized_name
def sanitize_path(self, path):
if path[0] == "/" or path[0] == ".":
path = path[1:]
path_elements = path.split("/")
joined_path = self.basefolder
for path_element in path_elements:
joined_path = os.path.join(joined_path, self.sanitize_name(path_element))
path = os.path.realpath(joined_path)
if not path.startswith(self.basefolder):
raise ValueError("path not contained in base folder: {path}".format(**locals()))
return path
def rel_path(self, path):
if isinstance(path, (tuple, list)):
path = self.join_path(*path)
if isinstance(path, (str, unicode, basestring)):
if path.startswith(self.basefolder):
path = path[len(self.basefolder):]
path = path.replace(os.path.sep, "/")
if path.startswith("/"):
path = path[1:]
return path
def _get_metadata(self, path):
if path in self._metadata_cache:
return self._metadata_cache[path]
@@ -1048,22 +870,15 @@ class LocalFileStorage(StorageInterface):
def _save_metadata(self, path, metadata):
metadata_path = os.path.join(path, ".metadata.yaml")
fh, metadata_temporary_path = tempfile.mkstemp()
os.close(fh)
with self._metadata_lock:
try:
import yaml
import shutil
file_obj = tempfile.NamedTemporaryFile(delete=False)
try:
yaml.safe_dump(metadata, stream=file_obj, default_flow_style=False, indent=" ", allow_unicode=True)
file_obj.close()
shutil.move(file_obj.name, metadata_path)
finally:
try:
if os.path.exists(file_obj.name):
os.remove(file_obj.name)
except Exception as e:
self._logger.warn("Could not delete file {}: {}".format(file_obj.name, str(e)))
with open(metadata_temporary_path, "w") as f:
import yaml
yaml.safe_dump(metadata, stream=f, default_flow_style=False, indent=" ", allow_unicode=True)
safeRename(metadata_temporary_path, metadata_path, throw_error=True)
except:
self._logger.exception("Error while writing .metadata.yaml to {path}".format(**locals()))
else:
-239
View File
@@ -1,239 +0,0 @@
# coding=utf-8
from __future__ import absolute_import
__author__ = "Gina Häußge <osd@foosel.net>"
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License"
import io
class AbstractFileWrapper(object):
"""
Wrapper for file representations to save to storages.
Arguments:
filename (str): The file's name
"""
def __init__(self, filename):
self.filename = filename
def save(self, path):
"""
Saves the file's content to the given absolute path.
Arguments:
path (str): The absolute path to where to save the file
"""
raise NotImplementedError()
def stream(self):
"""
Returns a Python stream object (subclass of io.IOBase) representing the file's contents.
Returns:
io.IOBase: The file's contents as a stream.
"""
raise NotImplementedError()
class DiskFileWrapper(AbstractFileWrapper):
"""
An implementation of :class:`.AbstractFileWrapper` that wraps an actual file on disk. The `save` implementations
will either copy the file to the new path (preserving file attributes) or -- if `move` is `True` (the default) --
move the file.
Arguments:
filename (str): The file's name
path (str): The file's absolute path
move (boolean): Whether to move the file upon saving (True, default) or copying.
"""
def __init__(self, filename, path, move=True):
AbstractFileWrapper.__init__(self, filename)
self.path = path
self.move = move
def save(self, path):
import shutil
if self.move:
shutil.move(self.path, path)
else:
shutil.copy2(self.path, path)
def stream(self):
return io.open(self.path, "rb")
class StreamWrapper(AbstractFileWrapper):
"""
A wrapper allowing processing of one or more consecutive streams.
Arguments:
*streams (io.IOBase): One or more streams to process one after another to save to storage.
"""
def __init__(self, filename, *streams):
if not len(streams) > 0:
raise ValueError("Need at least one stream to wrap")
AbstractFileWrapper.__init__(self, filename)
self.streams = streams
def save(self, path):
"""
Will dump the contents of all streams provided during construction into the target file, in the order they were
provided.
"""
import shutil
with open(path, "wb") as dest:
with self.stream() as source:
shutil.copyfileobj(source, dest)
def stream(self):
"""
If more than one stream was provided to the constructor, will return a :class:`.MultiStream` wrapping all
provided streams in the order they were provided, else the first and only stream is returned directly.
"""
if len(self.streams) > 1:
return MultiStream(*self.streams)
else:
return self.streams[0]
class MultiStream(io.RawIOBase):
"""
A stream implementation which when read reads from multiple streams, one after the other, basically concatenating
their contents in the order they are provided to the constructor.
Arguments:
*streams (io.IOBase): One or more streams to concatenate.
"""
def __init__(self, *streams):
io.RawIOBase.__init__(self)
self.streams = streams
self.current_stream = 0
def read(self, n=-1):
if n == 0:
return b''
if len(self.streams) == 0:
return b''
while self.current_stream < len(self.streams):
stream = self.streams[self.current_stream]
result = stream.read(n)
if result is None or len(result) != 0:
return result
else:
self.current_stream += 1
return b''
def readinto(self, b):
n = len(b)
read = self.read(n)
b[:len(read)] = read
return len(read)
def close(self):
for stream in self.streams:
try:
stream.close()
except:
pass
def readable(self, *args, **kwargs):
return True
def seekable(self, *args, **kwargs):
return False
def writable(self, *args, **kwargs):
return False
class LineProcessorStream(io.RawIOBase):
"""
While reading from this stream the provided `input_stream` is read line by line, calling the (overridable) method
:meth:`.process_line` for each read line.
Sub classes can thus modify the contents of the `input_stream` in line, while it is being read.
Arguments:
input_stream (io.IOBase): The stream to process on the fly.
"""
def __init__(self, input_stream):
io.RawIOBase.__init__(self)
self.input_stream = io.BufferedReader(input_stream)
self.leftover = None
def read(self, n=-1):
if n == 0:
return b''
result = b''
while len(result) < n or n == -1:
bytes_left = (n - len(result)) if n != -1 else -1
if self.leftover is not None:
if bytes_left != -1 and bytes_left < len(self.leftover):
result += self.leftover[:bytes_left]
self.leftover = self.leftover[bytes_left:]
break
else:
result += self.leftover
self.leftover = None
processed_line = None
while processed_line is None:
line = self.input_stream.readline()
if not line:
break
processed_line = self.process_line(line)
if processed_line is None:
break
bytes_left = (n - len(result)) if n != -1 else -1
if bytes_left != -1 and bytes_left < len(processed_line):
result += processed_line[:bytes_left]
self.leftover = processed_line[bytes_left:]
break
else:
result += processed_line
return result
def readinto(self, b):
n = len(b)
read = self.read(n)
b[:len(read)] = read
return len(read)
def process_line(self, line):
"""
Called from the `read` Method of this stream with each line read from `self.input_stream`.
By returning ``None`` the line will not be returned from the read stream, effectively being stripped from the
wrapper `input_stream`.
Arguments:
line (str): The line as read from `self.input_stream`
Returns:
str or None: The processed version of the line (might also be multiple lines), or None if the line is to be
stripped from the processed stream.
"""
return line
def close(self):
self.input_stream.close()
def readable(self, *args, **kwargs):
return True
def seekable(self, *args, **kwargs):
return False
def writable(self, *args, **kwargs):
return False
+54 -397
View File
@@ -1,18 +1,4 @@
# coding=utf-8
"""
This module represents OctoPrint's plugin subsystem. This includes management and helper methods as well as the
registered plugin types.
.. autofunction:: plugin_manager
.. autofunction:: plugin_settings
.. autofunction:: call_plugin
.. autoclass:: PluginSettings
:members:
"""
from __future__ import absolute_import
__author__ = "Gina Häußge <osd@foosel.net>"
@@ -20,78 +6,20 @@ __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agp
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
import os
import logging
from octoprint.settings import settings
from octoprint.plugin.core import (PluginInfo, PluginManager, Plugin)
from octoprint.plugin.types import *
from octoprint.util import deprecated
# singleton
_instance = None
def _validate_plugin(phase, plugin_info):
if phase == "after_load":
if plugin_info.implementation is not None and isinstance(plugin_info.implementation, AppPlugin):
# transform app plugin into hook
import warnings
warnings.warn("{name} uses deprecated plugin mixin AppPlugin, use octoprint.accesscontrol.appkey hook instead".format(name=plugin_info.key), DeprecationWarning)
hooks = plugin_info.hooks
if not "octoprint.accesscontrol.appkey" in hooks:
hooks["octoprint.accesscontrol.appkey"] = plugin_info.implementation.get_additional_apps
setattr(plugin_info.instance, PluginInfo.attr_hooks, hooks)
def plugin_manager(init=False, plugin_folders=None, plugin_types=None, plugin_entry_points=None, plugin_disabled_list=None,
plugin_restart_needing_hooks=None, plugin_obsolete_hooks=None, plugin_validators=None):
"""
Factory method for initially constructing and consecutively retrieving the :class:`~octoprint.plugin.core.PluginManager`
singleton.
Arguments:
init (boolean): A flag indicating whether this is the initial call to construct the singleton (True) or not
(False, default). If this is set to True and the plugin manager has already been initialized, a :class:`ValueError`
will be raised. The same will happen if the plugin manager has not yet been initialized and this is set to
False.
plugin_folders (list): A list of folders (as strings containing the absolute path to them) in which to look for
potential plugin modules. If not provided this defaults to the configured ``plugins`` base folder and
``src/plugins`` within OctoPrint's code base.
plugin_types (list): A list of recognized plugin types for which to look for provided implementations. If not
provided this defaults to the plugin types found in :mod:`octoprint.plugin.types` without
:class:`~octoprint.plugin.OctoPrintPlugin`.
plugin_entry_points (list): A list of entry points pointing to modules which to load as plugins. If not provided
this defaults to the entry point ``octoprint.plugin``.
plugin_disabled_list (list): A list of plugin identifiers that are currently disabled. If not provided this
defaults to all plugins for which ``enabled`` is set to ``False`` in the settings.
plugin_restart_needing_hooks (list): A list of hook namespaces which cause a plugin to need a restart in order
be enabled/disabled. Does not have to contain full hook identifiers, will be matched with startswith similar
to logging handlers
plugin_obsolete_hooks (list): A list of hooks that have been declared obsolete. Plugins implementing them will
not be enabled since they might depend on functionality that is no longer available.
plugin_validators (list): A list of additional plugin validators through which to process each plugin.
Returns:
PluginManager: A fully initialized :class:`~octoprint.plugin.core.PluginManager` instance to be used for plugin
management tasks.
Raises:
ValueError: ``init`` was True although the plugin manager was already initialized, or it was False although
the plugin manager was not yet initialized.
"""
def plugin_manager(init=False, plugin_folders=None, plugin_types=None, plugin_entry_points=None, plugin_disabled_list=None):
global _instance
if _instance is not None:
if init:
raise ValueError("Plugin Manager already initialized")
else:
if _instance is None:
if init:
if plugin_folders is None:
plugin_folders = (
settings().getBaseFolder("plugins"),
(os.path.abspath(os.path.join(os.path.dirname(os.path.realpath(__file__)), "..", "plugins")), True)
)
plugin_folders = (settings().getBaseFolder("plugins"), os.path.abspath(os.path.join(os.path.dirname(os.path.realpath(__file__)), "..", "plugins")))
if plugin_types is None:
plugin_types = [StartupPlugin,
ShutdownPlugin,
@@ -107,89 +35,23 @@ def plugin_manager(init=False, plugin_folders=None, plugin_types=None, plugin_en
if plugin_entry_points is None:
plugin_entry_points = "octoprint.plugin"
if plugin_disabled_list is None:
plugin_disabled_list = settings().get(["plugins", "_disabled"])
if plugin_restart_needing_hooks is None:
plugin_restart_needing_hooks = [
"octoprint.server.http"
]
if plugin_obsolete_hooks is None:
plugin_obsolete_hooks = [
"octoprint.comm.protocol.gcode"
]
if plugin_validators is None:
plugin_validators = [
_validate_plugin
]
all_plugin_settings = settings().get(["plugins"])
plugin_disabled_list = []
for key in all_plugin_settings:
if "enabled" in all_plugin_settings[key] and not all_plugin_settings[key]:
plugin_disabled_list.append(key)
_instance = PluginManager(plugin_folders,
plugin_types,
plugin_entry_points,
logging_prefix="octoprint.plugins.",
plugin_disabled_list=plugin_disabled_list,
plugin_restart_needing_hooks=plugin_restart_needing_hooks,
plugin_obsolete_hooks=plugin_obsolete_hooks,
plugin_validators=plugin_validators)
_instance = PluginManager(plugin_folders, plugin_types, plugin_entry_points, plugin_disabled_list=plugin_disabled_list)
else:
raise ValueError("Plugin Manager not initialized yet")
return _instance
def plugin_settings(plugin_key, defaults=None, get_preprocessors=None, set_preprocessors=None):
"""
Factory method for creating a :class:`PluginSettings` instance.
Arguments:
plugin_key (string): The plugin identifier for which to create the settings instance.
defaults (dict): The default settings for the plugin.
get_preprocessors (dict): The getter preprocessors for the plugin.
set_preprocessors (dict): The setter preprocessors for the plugin.
Returns:
PluginSettings: A fully initialized :class:`PluginSettings` instance to be used to access the plugin's
settings
"""
return PluginSettings(settings(), plugin_key, defaults=defaults, get_preprocessors=get_preprocessors, set_preprocessors=set_preprocessors)
def plugin_settings(plugin_key, defaults=None):
return PluginSettings(settings(), plugin_key, defaults=defaults)
def call_plugin(types, method, args=None, kwargs=None, callback=None, error_callback=None):
"""
Helper method to invoke the indicated ``method`` on all registered plugin implementations implementing the
indicated ``types``. Allows providing method arguments and registering callbacks to call in case of success
and/or failure of each call which can be used to return individual results to the calling code.
Example:
.. sourcecode:: python
def my_success_callback(name, plugin, result):
print("{name} was called successfully and returned {result!r}".format(**locals()))
def my_error_callback(name, plugin, exc):
print("{name} raised an exception: {exc!s}".format(**locals()))
octoprint.plugin.call_plugin(
[octoprint.plugin.StartupPlugin],
"on_startup",
args=(my_host, my_port),
callback=my_success_callback,
error_callback=my_error_callback
)
Arguments:
types (list): A list of plugin implementation types to match against.
method (string): Name of the method to call on all matching implementations.
args (tuple): A tuple containing the arguments to supply to the called ``method``. Optional.
kwargs (dict): A dictionary containing the keyword arguments to supply to the called ``method``. Optional.
callback (function): A callback to invoke after an implementation has been called successfully. Will be called
with the three arguments ``name``, ``plugin`` and ``result``. ``name`` will be the plugin identifier,
``plugin`` the plugin implementation instance itself and ``result`` the result returned from the
``method`` invocation.
error_callback (function): A callback to invoke after the call of an implementation resulted in an exception.
Will be called with the three arguments ``name``, ``plugin`` and ``exc``. ``name`` will be the plugin
identifier, ``plugin`` the plugin implementation instance itself and ``exc`` the caught exception.
"""
def call_plugin(types, method, args=None, kwargs=None, callback=None):
if not isinstance(types, (list, tuple)):
types = [types]
if args is None:
@@ -198,82 +60,15 @@ def call_plugin(types, method, args=None, kwargs=None, callback=None, error_call
kwargs = dict()
plugins = plugin_manager().get_implementations(*types)
for plugin in plugins:
for name, plugin in plugins.items():
if hasattr(plugin, method):
try:
result = getattr(plugin, method)(*args, **kwargs)
if callback:
callback(plugin._identifier, plugin, result)
except Exception as exc:
logging.getLogger(__name__).exception("Error while calling plugin %s" % plugin._identifier)
if error_callback:
error_callback(plugin._identifier, plugin, exc)
result = getattr(plugin, method)(*args, **kwargs)
if callback:
callback(name, plugin, result)
class PluginSettings(object):
"""
The :class:`PluginSettings` class is the interface for plugins to their own or globally defined settings.
It provides a couple of convenience methods for directly accessing plugin settings via the regular
:class:`octoprint.settings.Settings` interfaces as well as means to access plugin specific folder locations.
All getter and setter methods will ensure that plugin settings are stored in their correct location within the
settings structure by modifying the supplied paths accordingly.
Arguments:
settings (Settings): The :class:`~octoprint.settings.Settings` instance on which to operate.
plugin_key (str): The plugin identifier of the plugin for which to create this instance.
defaults (dict): The plugin's defaults settings, will be used to determine valid paths within the plugin's
settings structure
.. method:: get(path, merged=False, asdict=False)
Retrieves a raw value from the settings for ``path``, optionally merging the raw value with the default settings
if ``merged`` is set to True.
:param path: The path for which to retrieve the value.
:type path: list, tuple
:param boolean merged: Whether to merge the returned result with the default settings (True) or not (False,
default).
:returns: The retrieved settings value.
:rtype: object
.. method:: get_int(path)
Like :func:`get` but tries to convert the retrieved value to ``int``.
.. method:: get_float(path)
Like :func:`get` but tries to convert the retrieved value to ``float``.
.. method:: get_boolean(path)
Like :func:`get` but tries to convert the retrieved value to ``boolean``.
.. method:: set(path, value, force=False)
Sets the raw value on the settings for ``path``.
:param path: The path for which to retrieve the value.
:type path: list, tuple
:param object value: The value to set.
:param boolean force: If set to True, the modified configuration will even be written back to disk if
the value didn't change.
.. method:: set_int(path, value, force=False)
Like :func:`set` but ensures the value is an ``int`` through attempted conversion before setting it.
.. method:: set_float(path, value, force=False)
Like :func:`set` but ensures the value is an ``float`` through attempted conversion before setting it.
.. method:: set_boolean(path, value, force=False)
Like :func:`set` but ensures the value is an ``boolean`` through attempted conversion before setting it.
"""
def __init__(self, settings, plugin_key, defaults=None, get_preprocessors=None, set_preprocessors=None):
def __init__(self, settings, plugin_key, defaults=None):
self.settings = settings
self.plugin_key = plugin_key
@@ -281,17 +76,6 @@ class PluginSettings(object):
defaults = dict()
self.defaults = dict(plugins=dict())
self.defaults["plugins"][plugin_key] = defaults
self.defaults["plugins"][plugin_key]["_config_version"] = None
if get_preprocessors is None:
get_preprocessors = dict()
self.get_preprocessors = dict(plugins=dict())
self.get_preprocessors["plugins"][plugin_key] = get_preprocessors
if set_preprocessors is None:
set_preprocessors = dict()
self.set_preprocessors = dict(plugins=dict())
self.set_preprocessors["plugins"][plugin_key] = set_preprocessors
def prefix_path(path):
return ['plugins', self.plugin_key] + path
@@ -309,187 +93,60 @@ class PluginSettings(object):
result.extend(args_after)
return result
def add_getter_kwargs(kwargs):
if not "defaults" in kwargs:
kwargs.update(defaults=self.defaults)
if not "preprocessors" in kwargs:
kwargs.update(preprocessors=self.get_preprocessors)
def add_defaults_to_kwargs(kwargs):
kwargs.update(dict(defaults=self.defaults))
return kwargs
def add_setter_kwargs(kwargs):
if not "defaults" in kwargs:
kwargs.update(defaults=self.defaults)
if not "preprocessors" in kwargs:
kwargs.update(preprocessors=self.set_preprocessors)
return kwargs
self.access_methods = {
'get': (lambda args: prefix_path_in_args(args), lambda kwargs: add_defaults_to_kwargs(kwargs)),
'getInt': (lambda args,: prefix_path_in_args(args), lambda kwargs: add_defaults_to_kwargs(kwargs)),
'getFloat': (lambda args,: prefix_path_in_args(args), lambda kwargs: add_defaults_to_kwargs(kwargs)),
'getBoolean': (lambda args,: prefix_path_in_args(args), lambda kwargs: add_defaults_to_kwargs(kwargs)),
'set': (lambda args: prefix_path_in_args(args), lambda kwargs: add_defaults_to_kwargs(kwargs)),
'setInt': (lambda args: prefix_path_in_args(args), lambda kwargs: add_defaults_to_kwargs(kwargs)),
'setFloat': (lambda args: prefix_path_in_args(args), lambda kwargs: add_defaults_to_kwargs(kwargs)),
'setBoolean': (lambda args: prefix_path_in_args(args), lambda kwargs: add_defaults_to_kwargs(kwargs))
}
self.access_methods = dict(
get =("get", prefix_path_in_args, add_getter_kwargs),
get_int =("getInt", prefix_path_in_args, add_getter_kwargs),
get_float =("getFloat", prefix_path_in_args, add_getter_kwargs),
get_boolean=("getBoolean", prefix_path_in_args, add_getter_kwargs),
set =("set", prefix_path_in_args, add_setter_kwargs),
set_int =("setInt", prefix_path_in_args, add_setter_kwargs),
set_float =("setFloat", prefix_path_in_args, add_setter_kwargs),
set_boolean=("setBoolean", prefix_path_in_args, add_setter_kwargs)
)
self.deprecated_access_methods = dict(
getInt ="get_int",
getFloat ="get_float",
getBoolean="get_boolean",
setInt ="set_int",
setFloat ="set_float",
setBoolean="set_boolean"
)
def globalGet(self, path):
return self.settings.get(path)
def global_get(self, path, **kwargs):
"""
Getter for retrieving settings not managed by the plugin itself from the core settings structure. Use this
to access global settings outside of your plugin.
def globalGetInt(self, path):
return self.settings.getInt(path)
Directly forwards to :func:`octoprint.settings.Settings.get`.
"""
return self.settings.get(path, **kwargs)
def globalGetFloat(self, path):
return self.settings.getFloat(path)
def global_get_int(self, path, **kwargs):
"""
Like :func:`global_get` but directly forwards to :func:`octoprint.settings.Settings.getInt`.
"""
return self.settings.getInt(path, **kwargs)
def globalGetBoolean(self, path):
return self.settings.getBoolean(path)
def global_get_float(self, path, **kwargs):
"""
Like :func:`global_get` but directly forwards to :func:`octoprint.settings.Settings.getFloat`.
"""
return self.settings.getFloat(path, **kwargs)
def globalSet(self, path, value):
self.settings.set(path, value)
def global_get_boolean(self, path, **kwargs):
"""
Like :func:`global_get` but directly orwards to :func:`octoprint.settings.Settings.getBoolean`.
"""
return self.settings.getBoolean(path, **kwargs)
def globalSetInt(self, path, value):
self.settings.setInt(path, value)
def global_set(self, path, value, **kwargs):
"""
Setter for modifying settings not managed by the plugin itself on the core settings structure. Use this
to modify global settings outside of your plugin.
def globalSetFloat(self, path, value):
self.settings.setFloat(path, value)
Directly forwards to :func:`octoprint.settings.Settings.set`.
"""
self.settings.set(path, value, **kwargs)
def globalSetBoolean(self, path, value):
self.settings.setBoolean(path, value)
def global_set_int(self, path, value, **kwargs):
"""
Like :func:`global_set` but directly forwards to :func:`octoprint.settings.Settings.setInt`.
"""
self.settings.setInt(path, value, **kwargs)
def globalGetBaseFolder(self, folder_type):
return self.settings.getBaseFolder(folder_type)
def global_set_float(self, path, value, **kwargs):
"""
Like :func:`global_set` but directly forwards to :func:`octoprint.settings.Settings.setFloat`.
"""
self.settings.setFloat(path, value, **kwargs)
def global_set_boolean(self, path, value, **kwargs):
"""
Like :func:`global_set` but directly forwards to :func:`octoprint.settings.Settings.setBoolean`.
"""
self.settings.setBoolean(path, value, **kwargs)
def global_get_basefolder(self, folder_type, **kwargs):
"""
Retrieves a globally defined basefolder of the given ``folder_type``. Directly forwards to
:func:`octoprint.settings.Settings.getBaseFolder`.
"""
return self.settings.getBaseFolder(folder_type, **kwargs)
def get_plugin_logfile_path(self, postfix=None):
"""
Retrieves the path to a logfile specifically for the plugin. If ``postfix`` is not supplied, the logfile
will be named ``plugin_<plugin identifier>.log`` and located within the configured ``logs`` folder. If a
postfix is supplied, the name will be ``plugin_<plugin identifier>_<postfix>.log`` at the same location.
Plugins may use this for specific logging tasks. For example, a :class:`~octoprint.plugin.SlicingPlugin` might
want to create a log file for logging the output of the slicing engine itself if some debug flag is set.
Arguments:
postfix (str): Postfix of the logfile for which to create the path. If set, the file name of the log file
will be ``plugin_<plugin identifier>_<postfix>.log``, if not it will be
``plugin_<plugin identifier>.log``.
Returns:
str: Absolute path to the log file, directly usable by the plugin.
"""
def getPluginLogfilePath(self, postfix=None):
filename = "plugin_" + self.plugin_key
if postfix is not None:
filename += "_" + postfix
filename += ".log"
return os.path.join(self.settings.getBaseFolder("logs"), filename)
@deprecated("PluginSettings.get_plugin_data_folder has been replaced by OctoPrintPlugin.get_plugin_data_folder",
includedoc="Replaced by :func:`~octoprint.plugin.types.OctoPrintPlugin.get_plugin_data_folder`",
since="1.2.0")
def get_plugin_data_folder(self):
path = os.path.join(self.settings.getBaseFolder("data"), self.plugin_key)
if not os.path.isdir(path):
os.makedirs(path)
return path
def __getattr__(self, item):
all_access_methods = self.access_methods.keys() + self.deprecated_access_methods.keys()
if item in all_access_methods:
decorator = None
if item in self.deprecated_access_methods:
new = self.deprecated_access_methods[item]
decorator = deprecated("{old} has been renamed to {new}".format(old=item, new=new), stacklevel=2)
item = new
if item in self.access_methods and hasattr(self.settings, item) and callable(getattr(self.settings, item)):
orig_item = getattr(self.settings, item)
args_mapper, kwargs_mapper = self.access_methods[item]
settings_name, args_mapper, kwargs_mapper = self.access_methods[item]
if hasattr(self.settings, settings_name) and callable(getattr(self.settings, settings_name)):
orig_func = getattr(self.settings, settings_name)
if decorator is not None:
orig_func = decorator(orig_func)
def _func(*args, **kwargs):
return orig_func(*args_mapper(args), **kwargs_mapper(kwargs))
_func.__name__ = item
_func.__doc__ = orig_func.__doc__ if "__doc__" in dir(orig_func) else None
return _func
return getattr(self.settings, item)
##~~ deprecated methods follow
# TODO: Remove with release of 1.3.0
globalGet = deprecated("globalGet has been renamed to global_get",
includedoc="Replaced by :func:`global_get`",
since="1.2.0-dev-546")(global_get)
globalGetInt = deprecated("globalGetInt has been renamed to global_get_int",
includedoc="Replaced by :func:`global_get_int`",
since="1.2.0-dev-546")(global_get_int)
globalGetFloat = deprecated("globalGetFloat has been renamed to global_get_float",
includedoc="Replaced by :func:`global_get_float`",
since="1.2.0-dev-546")(global_get_float)
globalGetBoolean = deprecated("globalGetBoolean has been renamed to global_get_boolean",
includedoc="Replaced by :func:`global_get_boolean`",
since="1.2.0-dev-546")(global_get_boolean)
globalSet = deprecated("globalSet has been renamed to global_set",
includedoc="Replaced by :func:`global_set`",
since="1.2.0-dev-546")(global_set)
globalSetInt = deprecated("globalSetInt has been renamed to global_set_int",
includedoc="Replaced by :func:`global_set_int`",
since="1.2.0-dev-546")(global_set_int)
globalSetFloat = deprecated("globalSetFloat has been renamed to global_set_float",
includedoc="Replaced by :func:`global_set_float`",
since="1.2.0-dev-546")(global_set_float)
globalSetBoolean = deprecated("globalSetBoolean has been renamed to global_set_boolean",
includedoc="Replaced by :func:`global_set_boolean`",
since="1.2.0-dev-546")(global_set_boolean)
globalGetBaseFolder = deprecated("globalGetBaseFolder has been renamed to global_get_basefolder",
includedoc="Replaced by :func:`global_get_basefolder`",
since="1.2.0-dev-546")(global_get_basefolder)
getPluginLogfilePath = deprecated("getPluginLogfilePath has been renamed to get_plugin_logfile_path",
includedoc="Replaced by :func:`get_plugin_logfile_path`",
since="1.2.0-dev-546")(get_plugin_logfile_path)
return lambda *args, **kwargs: orig_item(*args_mapper(args), **kwargs_mapper(kwargs))
else:
return getattr(self.settings, item)
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+131 -96
View File
@@ -16,8 +16,91 @@ import octoprint.util
import octoprint.slicing
import octoprint.settings
default_settings = {
"cura_engine": None,
"default_profile": None,
"debug_logging": False
}
s = octoprint.plugin.plugin_settings("cura", defaults=default_settings)
from .profile import Profile
blueprint = flask.Blueprint("plugin.cura", __name__)
@blueprint.route("/import", methods=["POST"])
def importCuraProfile():
import datetime
import tempfile
from octoprint.server import slicingManager
input_name = "file"
input_upload_name = input_name + "." + s.globalGet(["server", "uploads", "nameSuffix"])
input_upload_path = input_name + "." + s.globalGet(["server", "uploads", "pathSuffix"])
if input_upload_name in flask.request.values and input_upload_path in flask.request.values:
filename = flask.request.values[input_upload_name]
try:
profile_dict = Profile.from_cura_ini(flask.request.values[input_upload_path])
except Exception as e:
return flask.make_response("Something went wrong while converting imported profile: {message}".format(e.message), 500)
elif input_name in flask.request.files:
temp_file = tempfile.NamedTemporaryFile("wb", delete=False)
try:
temp_file.close()
upload = flask.request.files[input_name]
upload.save(temp_file.name)
profile_dict = Profile.from_cura_ini(temp_file.name)
except Exception as e:
return flask.make_response("Something went wrong while converting imported profile: {message}".format(e.message), 500)
finally:
os.remove(temp_file)
filename = upload.filename
else:
return flask.make_response("No file included", 400)
if profile_dict is None:
return flask.make_response("Could not convert Cura profile", 400)
name, _ = os.path.splitext(filename)
# default values for name, display name and description
profile_name = _sanitize_name(name)
profile_display_name = name
profile_description = "Imported from {filename} on {date}".format(filename=filename, date=octoprint.util.getFormattedDateTime(datetime.datetime.now()))
profile_allow_overwrite = False
# overrides
if "name" in flask.request.values:
profile_name = flask.request.values["name"]
if "displayName" in flask.request.values:
profile_display_name = flask.request.values["displayName"]
if "description" in flask.request.values:
profile_description = flask.request.values["description"]
if "allowOverwrite" in flask.request.values:
from octoprint.server.api import valid_boolean_trues
profile_allow_overwrite = flask.request.values["allowOverwrite"] in valid_boolean_trues
slicingManager.save_profile("cura",
profile_name,
profile_dict,
allow_overwrite=profile_allow_overwrite,
display_name=profile_display_name,
description=profile_description)
result = dict(
resource=flask.url_for("api.slicingGetSlicerProfile", slicer="cura", name=profile_name, _external=True),
displayName=profile_display_name,
description=profile_description
)
r = flask.make_response(flask.jsonify(result), 201)
r.headers["Location"] = result["resource"]
return r
class CuraPlugin(octoprint.plugin.SlicerPlugin,
octoprint.plugin.SettingsPlugin,
octoprint.plugin.TemplatePlugin,
@@ -39,84 +122,26 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin,
def on_startup(self, host, port):
# setup our custom logger
cura_logging_handler = logging.handlers.RotatingFileHandler(self._settings.get_plugin_logfile_path(postfix="engine"), maxBytes=2*1024*1024)
cura_logging_handler = logging.handlers.RotatingFileHandler(s.getPluginLogfilePath(postfix="engine"), maxBytes=2*1024*1024)
cura_logging_handler.setFormatter(logging.Formatter("%(asctime)s %(message)s"))
cura_logging_handler.setLevel(logging.DEBUG)
self._cura_logger.addHandler(cura_logging_handler)
self._cura_logger.setLevel(logging.DEBUG if self._settings.get_boolean(["debug_logging"]) else logging.CRITICAL)
self._cura_logger.setLevel(logging.DEBUG if s.getBoolean(["debug_logging"]) else logging.CRITICAL)
self._cura_logger.propagate = False
##~~ BlueprintPlugin API
@octoprint.plugin.BlueprintPlugin.route("/import", methods=["POST"])
def import_cura_profile(self):
import datetime
import tempfile
from octoprint.server import slicingManager
input_name = "file"
input_upload_name = input_name + "." + self._settings.global_get(["server", "uploads", "nameSuffix"])
input_upload_path = input_name + "." + self._settings.global_get(["server", "uploads", "pathSuffix"])
if input_upload_name in flask.request.values and input_upload_path in flask.request.values:
filename = flask.request.values[input_upload_name]
try:
profile_dict = Profile.from_cura_ini(flask.request.values[input_upload_path])
except Exception as e:
self._logger.exception("Error while converting the imported profile")
return flask.make_response("Something went wrong while converting imported profile: {message}".format(message=str(e)), 500)
else:
self._logger.warn("No profile file included for importing, aborting")
return flask.make_response("No file included", 400)
if profile_dict is None:
self._logger.warn("Could not convert profile, aborting")
return flask.make_response("Could not convert Cura profile", 400)
name, _ = os.path.splitext(filename)
# default values for name, display name and description
profile_name = _sanitize_name(name)
profile_display_name = name
profile_description = "Imported from {filename} on {date}".format(filename=filename, date=octoprint.util.get_formatted_datetime(datetime.datetime.now()))
profile_allow_overwrite = False
# overrides
if "name" in flask.request.values:
profile_name = flask.request.values["name"]
if "displayName" in flask.request.values:
profile_display_name = flask.request.values["displayName"]
if "description" in flask.request.values:
profile_description = flask.request.values["description"]
if "allowOverwrite" in flask.request.values:
from octoprint.server.api import valid_boolean_trues
profile_allow_overwrite = flask.request.values["allowOverwrite"] in valid_boolean_trues
try:
slicingManager.save_profile("cura",
profile_name,
profile_dict,
allow_overwrite=profile_allow_overwrite,
display_name=profile_display_name,
description=profile_description)
except octoprint.slicing.ProfileAlreadyExists:
self._logger.warn("Profile {profile_name} already exists, aborting".format(**locals()))
return flask.make_response("A profile named {profile_name} already exists for slicer cura".format(**locals()), 409)
result = dict(
resource=flask.url_for("api.slicingGetSlicerProfile", slicer="cura", name=profile_name, _external=True),
displayName=profile_display_name,
description=profile_description
)
r = flask.make_response(flask.jsonify(result), 201)
r.headers["Location"] = result["resource"]
return r
def get_blueprint(self):
global blueprint
return blueprint
##~~ AssetPlugin API
def get_asset_folder(self):
import os
return os.path.join(os.path.dirname(os.path.realpath(__file__)), "static")
def get_assets(self):
return {
"js": ["js/cura.js"],
@@ -126,29 +151,43 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin,
##~~ SettingsPlugin API
def on_settings_save(self, data):
old_debug_logging = self._settings.get_boolean(["debug_logging"])
octoprint.plugin.SettingsPlugin.on_settings_save(self, data)
new_debug_logging = self._settings.get_boolean(["debug_logging"])
if old_debug_logging != new_debug_logging:
if new_debug_logging:
self._cura_logger.setLevel(logging.DEBUG)
else:
self._cura_logger.setLevel(logging.CRITICAL)
def get_settings_defaults(self):
def on_settings_load(self):
return dict(
cura_engine=None,
default_profile=None,
debug_logging=False
cura_engine=s.get(["cura_engine"]),
default_profile=s.get(["default_profile"]),
debug_logging=s.getBoolean(["debug_logging"])
)
def on_settings_save(self, data):
if "cura_engine" in data and data["cura_engine"]:
s.set(["cura_engine"], data["cura_engine"])
if "default_profile" in data and data["default_profile"]:
s.set(["default_profile"], data["default_profile"])
if "debug_logging" in data:
old_debug_logging = s.getBoolean(["debug_logging"])
new_debug_logging = data["debug_logging"] in octoprint.settings.valid_boolean_trues
if old_debug_logging != new_debug_logging:
if new_debug_logging:
self._cura_logger.setLevel(logging.DEBUG)
else:
self._cura_logger.setLevel(logging.CRITICAL)
s.setBoolean(["debug_logging"], new_debug_logging)
##~~ TemplatePlugin API
def get_template_vars(self):
return dict(
_settings_menu_entry="Cura"
)
def get_template_folder(self):
import os
return os.path.join(os.path.dirname(os.path.realpath(__file__)), "templates")
##~~ SlicerPlugin API
def is_slicer_configured(self):
cura_engine = self._settings.get(["cura_engine"])
cura_engine = s.get(["cura_engine"])
if cura_engine is not None and os.path.exists(cura_engine):
return True
else:
@@ -163,7 +202,7 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin,
)
def get_slicer_default_profile(self):
path = self._settings.get(["default_profile"])
path = s.get(["default_profile"])
if not path:
path = os.path.join(os.path.dirname(os.path.realpath(__file__)), "profiles", "default.profile.yaml")
return self.get_slicer_profile(path)
@@ -184,9 +223,6 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin,
return octoprint.slicing.SlicingProfile(properties["type"], "unknown", profile_dict, display_name=display_name, description=description)
def save_slicer_profile(self, path, profile, allow_overwrite=True, overrides=None):
if os.path.exists(path) and not allow_overwrite:
raise octoprint.slicing.ProfileAlreadyExists("cura", profile.name)
new_profile = Profile.merge_profile(profile.data, overrides=overrides)
if profile.display_name is not None:
@@ -200,7 +236,7 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin,
try:
with self._job_mutex:
if not profile_path:
profile_path = self._settings.get(["default_profile"])
profile_path = s.get(["default_profile"])
if not machinecode_path:
path, _ = os.path.splitext(model_path)
machinecode_path = path + ".gco"
@@ -222,7 +258,7 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin,
engine_settings = self._convert_to_engine(profile_path, printer_profile, posX, posY)
executable = self._settings.get(["cura_engine"])
executable = s.get(["cura_engine"])
if not executable:
return False, "Path to CuraEngine is not configured "
@@ -237,7 +273,6 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin,
self._logger.info("Running %r in %s" % (command, working_dir))
p = sarge.run(command, cwd=working_dir, async=True, stdout=sarge.Capture(), stderr=sarge.Capture())
p.wait_events()
self._slicing_commands[machinecode_path] = p.commands[0]
try:
@@ -384,6 +419,9 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin,
return profile_dict
def _save_profile(self, path, profile, allow_overwrite=True):
if not allow_overwrite and os.path.exists(path):
raise IOError("Cannot overwrite {path}".format(path=path))
import yaml
with open(path, "wb") as f:
yaml.safe_dump(profile, f, default_flow_style=False, indent=" ", allow_unicode=True)
@@ -406,8 +444,5 @@ def _sanitize_name(name):
return sanitized_name.lower()
__plugin_name__ = "CuraEngine"
__plugin_author__ = "Gina Häußge"
__plugin_url__ = "https://github.com/foosel/OctoPrint/wiki/Plugin:-Cura"
__plugin_description__ = "Adds support for slicing via CuraEngine from within OctoPrint"
__plugin_license__ = "AGPLv3"
__plugin_implementation__ = CuraPlugin()
__plugin_version__ = "0.1"
__plugin_implementations__ = [CuraPlugin()]
+14 -23
View File
@@ -6,6 +6,8 @@ __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agp
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
from . import s
import re
class SupportLocationTypes(object):
@@ -346,12 +348,8 @@ class Profile(object):
@classmethod
def from_cura_ini(cls, path):
import logging
logger = logging.getLogger("octoprint.plugin.cura.profile")
import os
if not os.path.exists(path) or not os.path.isfile(path):
logger.warn("Path {path} does not exist or is not a file, cannot import".format(**locals()))
return None
import ConfigParser
@@ -359,7 +357,6 @@ class Profile(object):
try:
config.read(path)
except:
logger.exception("Error while reading profile INI file from {path}".format(**locals()))
return None
arrayified_options = ["print_temperature", "filament_diameter", "start.gcode", "end.gcode"]
@@ -536,7 +533,7 @@ class Profile(object):
elif key == "machine_height":
return self._printer_profile["volume"]["height"]
elif key == "machine_center_is_zero":
return self._printer_profile["volume"]["formFactor"] == "circular" or self._printer_profile["volume"]["origin"] == "center"
return self._printer_profile["volume"]["formFactor"] == "circular"
else:
return None
@@ -565,9 +562,6 @@ class Profile(object):
else:
return 0.0
elif key == "has_heated_bed":
return self._printer_profile["heatedBed"]
elif key.startswith("filament_diameter"):
match = Profile.regex_filament_diameter.match(key)
if not match:
@@ -729,13 +723,13 @@ class Profile(object):
prefix += "M92 E{e_steps}\n" % (e_steps)
temp = self.get_float("print_temperature")
bed_temp = 0
bedTemp = 0
if self.get_boolean("has_heated_bed"):
bed_temp = self.get_float("print_bed_temperature")
include_bed_temp = bed_temp > 0 and not "{print_bed_temperature}" in Profile.regex_strip_comments.sub("", contents)
bedTemp = self.get_float("print_bed_temperature")
include_bed_temps = bedTemp > 0 and not "{print_bed_temperature}" in Profile.regex_strip_comments.sub("", contents)
if include_bed_temp:
prefix += "M140 S{bed_temp}\n".format(bed_temp=bed_temp)
if include_bed_temps:
prefix += "M140 S{print_bed_temperature}\n"
if temp > 0 and not "{print_temperature}" in Profile.regex_strip_comments.sub("", contents):
if extruder_count > 0:
@@ -746,19 +740,16 @@ class Profile(object):
if print_temp > 0:
t = print_temp
return template.format(extruder=extruder, temp=t)
prefix_preheat = ""
prefix_waitheat = ""
for n in xrange(1, extruder_count):
prefix += temp_line(temp, n, "M104 T{extruder} S{temp}\n")
for n in xrange(0, extruder_count):
if n > 0:
prefix_preheat += temp_line(temp, n, "M104 T{extruder} S{temp}\n")
prefix_waitheat += temp_line(temp, n, "M109 T{extruder} S{temp}\n")
prefix += prefix_preheat + prefix_waitheat + "T0\n"
prefix += temp_line(temp, n, "M109 T{extruder} S{temp}\n")
prefix += "T0\n"
else:
prefix += "M109 S{temp}\n".format(temp=temp)
if include_bed_temp:
prefix += "M190 S{bed_temp}\n".format(bed_temp=bed_temp)
if include_bed_temps:
prefix += "M190 S{print_bed_temperature}\n".format(bedTemp=bedTemp)
else:
contents = self.get_gcode_template(key)
+3 -7
View File
@@ -71,7 +71,6 @@ $(function() {
self.placeholderDisplayName(name);
self.placeholderDescription("Imported from " + self.fileName() + " on " + formatDate(new Date().getTime() / 1000));
self.uploadButton.unbind("click");
self.uploadButton.on("click", function() {
var form = {
allowOverwrite: self.profileAllowOverwrite()
@@ -101,7 +100,7 @@ $(function() {
self.profileDescription(undefined);
self.profileAllowOverwrite(true);
$("#settings_plugin_cura_import").modal("hide");
$("#settings-plugin-cura-import").modal("hide");
self.requestData();
self.slicingViewModel.requestData();
}
@@ -184,12 +183,9 @@ $(function() {
self.settings = self.settingsViewModel.settings;
self.requestData();
};
}
// view model class, parameters for constructor, container to bind to
OCTOPRINT_VIEWMODELS.push([
CuraViewModel,
["loginStateViewModel", "settingsViewModel", "slicingViewModel"],
"#settings_plugin_cura"
]);
ADDITIONAL_VIEWMODELS.push([CuraViewModel, ["loginStateViewModel", "settingsViewModel", "slicingViewModel"], document.getElementById("settings_plugin_cura_dialog")]);
});
@@ -1,107 +0,0 @@
<h4>{{ _('General') }}</h4>
<form class="form-horizontal">
<div class="control-group">
<label class="control-label" for="settings-cura-path">{{ _('Path to CuraEngine') }}</label>
<div class="controls">
<input type="text" class="input-block-level" data-bind="value: settings.plugins.cura.cura_engine">
</div>
</div>
<div class="control-group">
<div class="controls">
<label class="checkbox">
<input type="checkbox" data-bind="checked: settings.plugins.cura.debug_logging"> {{ _('Log the output of CuraEngine to plugin_cura_engine.log') }}
</label>
</div>
</div>
</form>
<h4>{{ _('Profiles') }}</h4>
<div class="pull-right">
<small>{{ _('Sort by') }}: <a href="#" data-bind="click: function() { profiles.changeSorting('id'); }">{{ _('Identifier') }} ({{ _('ascending') }})</a> | <a href="#" data-bind="click: function() { profiles.changeSorting('name'); }">{{ _('Name') }} ({{ _('ascending') }})</a></small>
</div>
<table class="table table-striped table-hover table-condensed table-hover">
<thead>
<tr>
<th class="settings_plugin_cura_profiles_key">{{ _('Identifier') }}</th>
<th class="settings_plugin_cura_profiles_name">{{ _('Name') }}</th>
<th class="settings_plugin_cura_profiles_actions">{{ _('Actions') }}</th>
</tr>
</thead>
<tbody data-bind="foreach: profiles.paginatedItems">
<tr data-bind="attr: {title: description}">
<td class="settings_plugin_cura_profiles_key"><span class="icon-star" data-bind="invisible: !isdefault()"></span> <span data-bind="text: key"></span></td>
<td class="settings_plugin_cura_profiles_name" data-bind="text: name"></td>
<td class="settings_plugin_cura_profiles_actions">
<a href="#" class="icon-star" title="{{ _('Make default') }}" data-bind="enable: !isdefault(), css: {disabled: isdefault()}, click: function() { if (!$data.isdefault()) { $root.makeProfileDefault($data); } }"></a>&nbsp;|&nbsp;<a href="#" class="icon-trash" title="{{ _('Delete Profile') }}" data-bind="enable: !isdefault(), css: {disabled: isdefault()}, click: function() { if (!$data.isdefault()) { $root.removeProfile($data); } }"></a>
</td>
</tr>
</tbody>
</table>
<div class="pagination pagination-mini pagination-centered">
<ul>
<li data-bind="css: {disabled: profiles.currentPage() === 0}"><a href="#" data-bind="click: profiles.prevPage">«</a></li>
</ul>
<ul data-bind="foreach: profiles.pages">
<li data-bind="css: { active: $data.number === $root.profiles.currentPage(), disabled: $data.number === -1 }"><a href="#" data-bind="text: $data.text, click: function() { $root.profiles.changePage($data.number); }"></a></li>
</ul>
<ul>
<li data-bind="css: {disabled: profiles.currentPage() === profiles.lastPage()}"><a href="#" data-bind="click: profiles.nextPage">»</a></li>
</ul>
</div>
<button class="btn pull-right" data-bind="click: function() { $root.showImportProfileDialog() }">{{ _('Import Profile...') }}</button>
<div id="settings_plugin_cura_import" class="modal hide fade">
<div class="modal-header">
<a href="#" class="close" data-dismiss="modal" aria-hidden="true">&times;</a>
<h3>{{ _('Import Existing Cura Profile') }}</h3>
</div>
<div class="modal-body">
<form class="form-horizontal">
<div class="control-group">
<label class="control-label">{{ _('Profile ini file') }}</label>
<div class="controls">
<div class="input-prepend">
<span class="btn fileinput-button">
<span>{{ _('Browse...') }}</span>
<input id="settings-cura-import" type="file" name="file" data-url="{{ url_for("plugin.cura.import_cura_profile") }}">
</span>
<span class="add-on" data-bind="text: fileName"></span>
</div>
</div>
</div>
<div class="control-group">
<label class="control-label">{{ _('Identifier') }}</label>
<div class="controls">
<input type="text" class="input-block-level" data-bind="value: profileName, attr: {placeholder: placeholderName}">
</div>
</div>
<div class="control-group">
<label class="control-label">{{ _('Name') }}</label>
<div class="controls">
<input type="text" class="input-block-level" data-bind="value: profileDisplayName, attr: {placeholder: placeholderDisplayName}">
</div>
</div>
<div class="control-group">
<label class="control-label">{{ _('Description') }}</label>
<div class="controls">
<input type="text" class="input-block-level" data-bind="value: profileDescription, attr: {placeholder: placeholderDescription}">
</div>
</div>
<div class="control-group">
<div class="controls">
<label class="checkbox">
<input type="checkbox" data-bind="checked: profileAllowOverwrite"> {{ _('Overwrite existing file') }}
</label>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button class="btn" data-dismiss="modal" aria-hidden="true">{{ _('Abort') }}</button>
<button class="btn btn-primary" id="settings-cura-import-start">{{ _('Confirm') }}</button>
</div>
</div>
@@ -0,0 +1,247 @@
<div id="settings_plugin_cura_dialog" data-bind="allowBindings: true">
<h4>{{ _('General') }}</h4>
<form class="form-horizontal">
<div class="control-group">
<label class="control-label" for="settings-cura-path">{{ _('Path to CuraEngine') }}</label>
<div class="controls">
<input type="text" class="input-block-level" data-bind="value: settings.plugins.cura.cura_engine">
</div>
</div>
<div class="control-group">
<div class="controls">
<label class="checkbox">
<input type="checkbox" data-bind="checked: settings.plugins.cura.debug_logging"> {{ _('Log the output of CuraEngine to plugin_cura_engine.log') }}
</label>
</div>
</div>
</form>
<h4>{{ _('Profiles') }}</h4>
<div class="pull-right">
<small>{{ _('Sort by') }}: <a href="#" data-bind="click: function() { profiles.changeSorting('id'); }">{{ _('Identifier') }} ({{ _('ascending') }})</a> | <a href="#" data-bind="click: function() { profiles.changeSorting('name'); }">{{ _('Name') }} ({{ _('ascending') }})</a></small>
</div>
<table class="table table-striped table-hover table-condensed table-hover">
<thead>
<tr>
<th class="settings_plugin_cura_profiles_key">{{ _('Identifier') }}</th>
<th class="settings_plugin_cura_profiles_name">{{ _('Name') }}</th>
<th class="settings_plugin_cura_profiles_actions">{{ _('Actions') }}</th>
</tr>
</thead>
<tbody data-bind="foreach: profiles.paginatedItems">
<tr data-bind="attr: {title: description}">
<td class="settings_plugin_cura_profiles_key"><span class="icon-star" data-bind="invisible: !isdefault()"></span> <span data-bind="text: key"></span></td>
<td class="settings_plugin_cura_profiles_name" data-bind="text: name"></td>
<td class="settings_plugin_cura_profiles_actions">
<a href="#" class="icon-star" title="{{ _('Make default') }}" data-bind="enable: !isdefault(), css: {disabled: isdefault()}, click: function() { if (!$data.isdefault()) { $root.makeProfileDefault($data); } }"></a>&nbsp;|&nbsp;<a href="#" class="icon-trash" title="{{ _('Delete Profile') }}" data-bind="enable: !isdefault(), css: {disabled: isdefault()}, click: function() { if (!$data.isdefault()) { $root.removeProfile($data); } }"></a>
</td>
</tr>
</tbody>
</table>
<div class="pagination pagination-mini pagination-centered">
<ul>
<li data-bind="css: {disabled: profiles.currentPage() === 0}"><a href="#" data-bind="click: profiles.prevPage">«</a></li>
</ul>
<ul data-bind="foreach: profiles.pages">
<li data-bind="css: { active: $data.number === $root.profiles.currentPage(), disabled: $data.number === -1 }"><a href="#" data-bind="text: $data.text, click: function() { $root.profiles.changePage($data.number); }"></a></li>
</ul>
<ul>
<li data-bind="css: {disabled: profiles.currentPage() === profiles.lastPage()}"><a href="#" data-bind="click: profiles.nextPage">»</a></li>
</ul>
</div>
<button class="btn pull-right" data-bind="click: function() { $root.showImportProfileDialog() }">{{ _('Import Profile...') }}</button>
<div id="settings_plugin_cura_import" class="modal hide fade">
<div class="modal-header">
<a href="#" class="close" data-dismiss="modal" aria-hidden="true">&times;</a>
<h3>{{ _('Import Existing Cura Profile') }}</h3>
</div>
<div class="modal-body">
<form class="form-horizontal">
<div class="control-group">
<label class="control-label">{{ _('Profile ini file') }}</label>
<div class="controls">
<div class="input-prepend">
<span class="btn fileinput-button">
<span>{{ _('Browse...') }}</span>
<input id="settings-cura-import" type="file" name="file" data-url="{{ url_for("plugin.cura.importCuraProfile") }}">
</span>
<span class="add-on" data-bind="text: fileName"></span>
</div>
</div>
</div>
<div class="control-group">
<label class="control-label">{{ _('Identifier') }}</label>
<div class="controls">
<input type="text" class="input-block-level" data-bind="value: profileName, attr: {placeholder: placeholderName}">
</div>
</div>
<div class="control-group">
<label class="control-label">{{ _('Name') }}</label>
<div class="controls">
<input type="text" class="input-block-level" data-bind="value: profileDisplayName, attr: {placeholder: placeholderDisplayName}">
</div>
</div>
<div class="control-group">
<label class="control-label">{{ _('Description') }}</label>
<div class="controls">
<input type="text" class="input-block-level" data-bind="value: profileDescription, attr: {placeholder: placeholderDescription}">
</div>
</div>
<div class="control-group">
<div class="controls">
<label class="checkbox">
<input type="checkbox" data-bind="checked: profileAllowOverwrite"> {{ _('Overwrite existing file') }}
</label>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button class="btn" data-dismiss="modal" aria-hidden="true">{{ _('Abort') }}</button>
<button class="btn btn-primary" id="settings-cura-import-start">{{ _('Confirm') }}</button>
</div>
</div>
<div id="settings_plugin_cura_edit" class="modal hide fade">
<div class="modal-header">
<a href="#" class="close" data-dismiss="modal" aria-hidden="true">&times;</a>
<h3>{{ _('Edit Cura Profile') }}</h3>
</div>
<div class="modal-body">
<div class="tabbable">
<ul class="nav nav-tabs">
<li class="active"><a href="#settings_plugin_cura_edit_general" data-toggle="tab">{{ _('General') }}</a></li>
<li><a href="#settings_plugin_cura_edit_basic" data-toggle="tab">{{ _('Basic') }}</a></li>
<li><a href="#settings_plugin_cura_edit_advanced" data-toggle="tab">{{ _('Advanced') }}</a></li>
<li><a href="#settings_plugin_cura_edit_expert" data-toggle="tab">{{ _('Expert') }}</a></li>
</ul>
<div class="tab-content">
<div class="tab-pane active" id="settings_plugin_cura_edit_general">
<form class="form-horizontal">
<div class="control-group">
<label class="control-label">{{ _('Identifier') }}</label>
<div class="controls">
<input type="text" class="input-block-level">
</div>
</div>
<div class="control-group">
<label class="control-label">{{ _('Name') }}</label>
<div class="controls">
<input type="text" class="input-block-level">
</div>
</div>
<div class="control-group">
<label class="control-label">{{ _('Descripton') }}</label>
<div class="controls">
<input type="text" class="input-block-level">
</div>
</div>
</form>
</div>
<div class="tab-pane" id="settings_plugin_cura_edit_basic">
<form class="form-horizontal">
<fieldset>
<legend>{{ _('Quality') }}</legend>
<div class="control-group">
<label class="control-label">{{ _('Layer height (mm)') }}</label>
<div class="controls">
<input type="text" class="input-block-level">
</div>
</div>
<div class="control-group">
<label class="control-label">{{ _('Shell thickness (mm)') }}</label>
<div class="controls">
<input type="text" class="input-block-level">
</div>
</div>
<div class="controls">
<label class="checkbox">
<input type="checkbox"> {{ _('Enable retraction') }}
</label>
</div>
</fieldset>
<fieldset>
<legend>{{ _('Fill') }}</legend>
<div class="control-group">
<label class="control-label">{{ _('Bottom/top thickness (mm)') }}</label>
<div class="controls">
<input type="text" class="input-block-level">
</div>
</div>
<div class="control-group">
<label class="control-label">{{ _('Fill density (%%)') }}</label>
<div class="controls">
<input type="text" class="input-block-level">
</div>
</div>
</fieldset>
<fieldset>
<legend>{{ _('Speed and Temperature') }}</legend>
<div class="control-group">
<label class="control-label">{{ _('Print speed (mm/s)') }}</label>
<div class="controls">
<input type="text" class="input-block-level">
</div>
</div>
<div class="control-group">
<label class="control-label">{{ _('Print temperature (°C)') }}</label>
<div class="controls">
<input type="text" class="input-block-level">
</div>
</div>
</fieldset>
<fieldset>
<legend>{{ _('Support') }}</legend>
<div class="control-group">
<label class="control-label">{{ _('Support type') }}</label>
<select>
<option value="none">{{ _('None') }}</option>
<option value="buildplate">{{ _('Touching buildplate') }}</option>
<option value="everywhere">{{ _('Everywhere') }}</option>
</select>
</div>
<div class="control-group">
<label class="control-label">{{ _('Platform adhesion type') }}</label>
<select>
<option value="none">{{ _('None') }}</option>
<option value="brim">{{ _('Brim') }}</option>
<option value="raft">{{ _('Raft') }}</option>
</select>
</div>
</fieldset>
<fieldset>
<legend>{{ _('Filament') }}</legend>
<div class="control-group">
<label class="control-label">{{ _('Diameter (mm)') }}</label>
<div class="controls">
<input type="text" class="input-block-level">
</div>
</div>
<div class="control-group">
<label class="control-label">{{ _('Flow (%%)') }}</label>
<div class="controls">
<input type="text" class="input-block-level">
</div>
</div>
</fieldset>
</form>
</div>
<div class="tab-pane" id="settings_plugin_cura_edit_advanced"></div>
<div class="tab-pane" id="settings_plugin_cura_edit_expert"></div>
</div>
</div>
</div>
<div class="modal-footer">
<button class="btn" data-dismiss="modal" aria-hidden="true">{{ _('Abort') }}</button>
<button class="btn btn-primary" data-bind="click: function() { $root.confirmEditProfile() }">{{ _('Confirm') }}</button>
</div>
</div>
</div>
+116 -109
View File
@@ -23,42 +23,117 @@ except:
__plugin_name__ = "Discovery"
__plugin_author__ = "Gina Häußge"
__plugin_url__ = "https://github.com/foosel/OctoPrint/wiki/Plugin:-Discovery"
__plugin_version__ = "0.1"
__plugin_description__ = "Makes the OctoPrint instance discoverable via Bonjour/Avahi/Zeroconf and uPnP"
__plugin_license__ = "AGPLv3"
def __plugin_load__():
def __plugin_init__():
if not pybonjour:
# no pybonjour available, we can't use that
logging.getLogger("octoprint.plugins." + __name__).info("pybonjour is not installed, Zeroconf Discovery won't be available")
plugin = DiscoveryPlugin()
discovery_plugin = DiscoveryPlugin()
global __plugin_implementation__
__plugin_implementation__ = plugin
global __plugin_implementations__
__plugin_implementations__ = [discovery_plugin]
global __plugin_helpers__
__plugin_helpers__ = dict(
ssdp_browse=plugin.ssdp_browse
ssdp_browse=discovery_plugin.ssdp_browse
)
if pybonjour:
__plugin_helpers__.update(dict(
zeroconf_browse=plugin.zeroconf_browse,
zeroconf_register=plugin.zeroconf_register,
zeroconf_unregister=plugin.zeroconf_unregister
zeroconf_browse=discovery_plugin.zeroconf_browse,
zeroconf_register=discovery_plugin.zeroconf_register,
zeroconf_unregister=discovery_plugin.zeroconf_unregister
))
default_settings = {
"publicHost": None,
"publicPort": None,
"pathPrefix": None,
"httpUsername": None,
"httpPassword": None,
"upnpUuid": None,
"zeroConf": [],
"model": {
"name": None,
"description": None,
"number": None,
"url": None,
"serial": None,
"vendor": None,
"vendorUrl": None
}
}
s = octoprint.plugin.plugin_settings("discovery", defaults=default_settings)
def get_uuid():
upnpUuid = s.get(["upnpUuid"])
if upnpUuid is None:
import uuid
upnpUuid = str(uuid.uuid4())
s.set(["upnpUuid"], upnpUuid)
s.save()
return upnpUuid
UUID = get_uuid()
del get_uuid
def get_instance_name():
name = s.globalGet(["appearance", "name"])
if name:
return u"OctoPrint instance \"{}\"".format(name)
else:
import socket
return u"OctoPrint instance on {}".format(socket.gethostname())
#~~ custom blueprint for providing discovery.xml
blueprint = flask.Blueprint("plugin.discovery", __name__, template_folder=os.path.join(os.path.dirname(os.path.realpath(__file__)), "templates"))
@blueprint.route("/discovery.xml")
def discovery():
logging.getLogger("octoprint.plugins." + __name__).debug("Rendering discovery.xml")
modelName = s.get(["model", "name"])
if not modelName:
import octoprint.server
modelName = octoprint.server.DISPLAY_VERSION
vendor = s.get(["model", "vendor"])
vendorUrl = s.get(["model", "vendorUrl"])
if not vendor:
vendor = "The OctoPrint Project"
vendorUrl = "http://www.octoprint.org/"
response = flask.make_response(flask.render_template("discovery.jinja2",
friendlyName=get_instance_name(),
manufacturer=vendor,
manufacturerUrl=vendorUrl,
modelName=modelName,
modelDescription=s.get(["model", "description"]),
modelNumber=s.get(["model", "number"]),
modelUrl=s.get(["model", "url"]),
serialNumber=s.get(["model", "serial"]),
uuid=UUID,
presentationUrl=flask.url_for("index", _external=True)))
response.headers['Content-Type'] = 'application/xml'
return response
class DiscoveryPlugin(octoprint.plugin.StartupPlugin,
octoprint.plugin.ShutdownPlugin,
octoprint.plugin.BlueprintPlugin,
octoprint.plugin.SettingsPlugin):
octoprint.plugin.BlueprintPlugin):
ssdp_multicast_addr = "239.255.255.250"
ssdp_multicast_port = 1900
def __init__(self):
self.logger = logging.getLogger("octoprint.plugins." + __name__)
self.host = None
self.port = None
@@ -72,69 +147,18 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin,
self._ssdp_notify_timeout = 10
self._ssdp_last_notify = 0
##~~ SettingsPlugin API
def get_settings_defaults(self):
return {
"publicHost": None,
"publicPort": None,
"pathPrefix": None,
"httpUsername": None,
"httpPassword": None,
"upnpUuid": None,
"zeroConf": [],
"model": {
"name": None,
"description": None,
"number": None,
"url": None,
"serial": None,
"vendor": None,
"vendorUrl": None
}
}
##~~ BlueprintPlugin API -- used for providing the SSDP device descriptor XML
@octoprint.plugin.BlueprintPlugin.route("/discovery.xml", methods=["GET"])
def discovery(self):
self._logger.debug("Rendering discovery.xml")
modelName = self._settings.get(["model", "name"])
if not modelName:
import octoprint.server
modelName = octoprint.server.DISPLAY_VERSION
vendor = self._settings.get(["model", "vendor"])
vendorUrl = self._settings.get(["model", "vendorUrl"])
if not vendor:
vendor = "The OctoPrint Project"
vendorUrl = "http://www.octoprint.org/"
response = flask.make_response(flask.render_template("discovery.xml.jinja2",
friendlyName=self.get_instance_name(),
manufacturer=vendor,
manufacturerUrl=vendorUrl,
modelName=modelName,
modelDescription=self._settings.get(["model", "description"]),
modelNumber=self._settings.get(["model", "number"]),
modelUrl=self._settings.get(["model", "url"]),
serialNumber=self._settings.get(["model", "serial"]),
uuid=self.get_uuid(),
presentationUrl=flask.url_for("index", _external=True)))
response.headers['Content-Type'] = 'application/xml'
return response
def is_blueprint_protected(self):
return False
def get_blueprint(self):
return blueprint
##~~ StartupPlugin API -- used for registering OctoPrint's Zeroconf and SSDP services upon application startup
def on_startup(self, host, port):
public_host = self._settings.get(["publicHost"])
public_host = s.get(["publicHost"])
if public_host:
host = public_host
public_port = self._settings.get(["publicPort"])
public_port = s.get(["publicPort"])
if public_port:
port = public_port
@@ -142,13 +166,13 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin,
self.port = port
# Zeroconf
self.zeroconf_register("_http._tcp", self.get_instance_name(), txt_record=self._create_http_txt_record_dict())
self.zeroconf_register("_octoprint._tcp", self.get_instance_name(), txt_record=self._create_octoprint_txt_record_dict())
for zeroconf in self._settings.get(["zeroConf"]):
self.zeroconf_register("_http._tcp", get_instance_name(), txt_record=self._create_http_txt_record_dict())
self.zeroconf_register("_octoprint._tcp", get_instance_name(), txt_record=self._create_octoprint_txt_record_dict())
for zeroconf in s.get(["zeroConf"]):
if "service" in zeroconf:
self.zeroconf_register(
zeroconf["service"],
zeroconf["name"] if "name" in zeroconf else self.get_instance_name(),
zeroconf["name"] if "name" in zeroconf else get_instance_name(),
port=zeroconf["port"] if "port" in zeroconf else None,
txt_record=zeroconf["txtRecord"] if "txtRecord" in zeroconf else None
)
@@ -183,7 +207,7 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin,
return
if not name:
name = self.get_instance_name()
name = get_instance_name()
if not port:
port = self.port
@@ -197,7 +221,7 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin,
key = (reg_type, port)
self._sd_refs[key] = pybonjour.DNSServiceRegister(**params)
self._logger.info(u"Registered {name} for {reg_type}".format(**locals()))
self.logger.info(u"Registered {name} for {reg_type}".format(**locals()))
def zeroconf_unregister(self, reg_type, port=None):
"""
@@ -221,9 +245,9 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin,
sd_ref = self._sd_refs[key]
try:
sd_ref.close()
self._logger.debug("Unregistered {reg_type} on port {port}".format(reg_type=reg_type, port=port))
self.logger.debug("Unregistered {reg_type} on port {port}".format(reg_type=reg_type, port=port))
except:
self._logger.exception("Could not unregister {reg_type} on port {port}".format(reg_type=reg_type, port=port))
self.logger.exception("Could not unregister {reg_type} on port {port}".format(reg_type=reg_type, port=port))
def zeroconf_browse(self, service_type, block=True, callback=None, browse_timeout=5, resolve_timeout=5):
"""
@@ -287,7 +311,7 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin,
name = fullname[:fullname.find(service_type) - 1].replace("\\032", " ")
host = hosttarget[:-1]
self._logger.debug("Resolved a result for Zeroconf resolution of {service_type}: {name} @ {host}".format(service_type=service_type, name=name, host=host))
self.logger.debug("Resolved a result for Zeroconf resolution of {service_type}: {name} @ {host}".format(service_type=service_type, name=name, host=host))
result.append(dict(
name=name,
host=host,
@@ -303,7 +327,7 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin,
if not (flags & pybonjour.kDNSServiceFlagsAdd):
return
self._logger.debug("Got a browsing result for Zeroconf resolution of {service_type}, resolving...".format(service_type=service_type))
self.logger.debug("Got a browsing result for Zeroconf resolution of {service_type}, resolving...".format(service_type=service_type))
resolve_ref = pybonjour.DNSServiceResolve(0, interface_index, service_name, regtype, reply_domain, resolve_callback)
try:
@@ -318,7 +342,7 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin,
finally:
resolve_ref.close()
self._logger.debug("Browsing Zeroconf for {service_type}".format(service_type=service_type))
self.logger.debug("Browsing Zeroconf for {service_type}".format(service_type=service_type))
def browse():
sd_ref = pybonjour.DNSServiceBrowse(regtype=service_type, callBack=browse_callback)
@@ -463,16 +487,16 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin,
# determine path entry
path = "/"
if self._settings.get(["pathPrefix"]):
path = self._settings.get(["pathPrefix"])
if s.get(["pathPrefix"]):
path = s.get(["pathPrefix"])
else:
prefix = self._settings.global_get(["server", "reverseProxy", "prefixFallback"])
prefix = s.globalGet(["server", "reverseProxy", "prefixFallback"])
if prefix:
path = prefix
# fetch username and password (if set)
username = self._settings.get(["httpUsername"])
password = self._settings.get(["httpPassword"])
username = s.get(["httpUsername"])
password = s.get(["httpPassword"])
entries = dict(
path=path
@@ -510,10 +534,10 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin,
api=octoprint.server.api.VERSION,
))
modelName = self._settings.get(["model", "name"])
modelName = s.get(["model", "name"])
if modelName:
entries.update(dict(model=modelName))
vendor = self._settings.get(["model", "vendor"])
vendor = s.get(["model", "vendor"])
if vendor:
entries.update(dict(vendor=vendor))
@@ -571,7 +595,7 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin,
location = "http://{addr}:{port}/plugin/discovery/discovery.xml".format(addr=addr, port=self.port)
self._logger.debug("Sending NOTIFY {} via {}".format("alive" if alive else "byebye", addr))
self.logger.debug("Sending NOTIFY {} via {}".format("alive" if alive else "byebye", addr))
notify_message = "".join([
"NOTIFY * HTTP/1.1\r\n",
"Server: Python/2.7\r\n",
@@ -582,7 +606,7 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin,
"USN: uuid:{uuid}::upnp:rootdevice\r\n",
"HOST: {mcast_addr}:{mcast_port}\r\n\r\n"
])
message = notify_message.format(uuid=self.get_uuid(),
message = notify_message.format(uuid=UUID,
location=location,
nts="ssdp:alive" if alive else "ssdp:byebye",
mcast_addr=self.__class__.ssdp_multicast_addr,
@@ -636,7 +660,7 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin,
sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, socket.inet_aton(self.__class__.ssdp_multicast_addr) + socket.inet_aton('0.0.0.0'))
self._logger.info(u"Registered {} for SSDP".format(self.get_instance_name()))
self.logger.info(u"Registered {} for SSDP".format(get_instance_name()))
self._ssdp_notify(alive=True)
@@ -648,11 +672,11 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin,
if not request.error_code and request.command == "M-SEARCH" and request.path == "*" and (request.headers["ST"] == "upnp:rootdevice" or request.headers["ST"] == "ssdp:all") and request.headers["MAN"] == '"ssdp:discover"':
interface_address = octoprint.util.address_for_client(*address)
if not interface_address:
self._logger.warn("Can't determine address to user for client {}, not sending a M-SEARCH reply".format(address))
self.logger.warn("Can't determine address to user for client {}, not sending a M-SEARCH reply".format(address))
continue
message = location_message.format(uuid=self.get_uuid(), location="http://{host}:{port}/plugin/discovery/discovery.xml".format(host=interface_address, port=self.port))
message = location_message.format(uuid=UUID, location="http://{host}:{port}/plugin/discovery/discovery.xml".format(host=interface_address, port=self.port))
sock.sendto(message, address)
self._logger.debug("Sent M-SEARCH reply for {path} and {st} to {address!r}".format(path=request.path, st=request.headers["ST"], address=address))
self.logger.debug("Sent M-SEARCH reply for {path} and {st} to {address!r}".format(path=request.path, st=request.headers["ST"], address=address))
except socket.timeout:
pass
finally:
@@ -663,21 +687,4 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin,
except:
pass
##~~ helpers
def get_uuid(self):
upnpUuid = self._settings.get(["upnpUuid"])
if upnpUuid is None:
import uuid
upnpUuid = str(uuid.uuid4())
self._settings.set(["upnpUuid"], upnpUuid)
self._settings.save()
return upnpUuid
def get_instance_name(self):
name = self._settings.global_get(["appearance", "name"])
if name:
return u"OctoPrint instance \"{}\"".format(name)
else:
import socket
return u"OctoPrint instance on {}".format(socket.gethostname())
@@ -1,565 +0,0 @@
# coding=utf-8
from __future__ import absolute_import
__author__ = "Gina Häußge <osd@foosel.net>"
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License"
import octoprint.plugin
import octoprint.plugin.core
from octoprint.settings import valid_boolean_trues
from octoprint.server.util.flask import restricted_access
from octoprint.server import admin_permission
from octoprint.util.pip import PipCaller, UnknownPip
from flask import jsonify, make_response
from flask.ext.babel import gettext
import logging
import sarge
import sys
import requests
import re
import os
import pkg_resources
class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
octoprint.plugin.TemplatePlugin,
octoprint.plugin.AssetPlugin,
octoprint.plugin.SettingsPlugin,
octoprint.plugin.StartupPlugin,
octoprint.plugin.BlueprintPlugin):
def __init__(self):
self._pending_enable = set()
self._pending_disable = set()
self._pending_install = set()
self._pending_uninstall = set()
self._pip_caller = None
self._repository_available = False
self._repository_plugins = []
self._repository_cache_path = None
self._repository_cache_ttl = 0
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._pip_caller = PipCaller(configured=self._settings.get(["pip"]))
self._pip_caller.on_log_call = self._log_call
self._pip_caller.on_log_stdout = self._log_stdout
self._pip_caller.on_log_stderr = self._log_stderr
##~~ StartupPlugin
def on_startup(self, host, port):
console_logging_handler = logging.handlers.RotatingFileHandler(self._settings.get_plugin_logfile_path(postfix="console"), maxBytes=2*1024*1024)
console_logging_handler.setFormatter(logging.Formatter("%(asctime)s %(message)s"))
console_logging_handler.setLevel(logging.DEBUG)
self._console_logger.addHandler(console_logging_handler)
self._console_logger.setLevel(logging.DEBUG)
self._console_logger.propagate = False
self._repository_available = self._fetch_repository_from_disk()
##~~ SettingsPlugin
def get_settings_defaults(self):
return dict(
repository="http://plugins.octoprint.org/plugins.json",
repository_ttl=24*60,
pip=None
)
def on_settings_save(self, data):
octoprint.plugin.SettingsPlugin.on_settings_save(self, data)
self._repository_cache_ttl = self._settings.get_int(["repository_ttl"]) * 60
self._pip_caller.refresh = True
##~~ AssetPlugin
def get_assets(self):
return dict(
js=["js/pluginmanager.js"],
css=["css/pluginmanager.css"],
less=["less/pluginmanager.less"]
)
##~~ TemplatePlugin
def get_template_configs(self):
return [
dict(type="settings", name=gettext("Plugin Manager"), template="pluginmanager_settings.jinja2", custom_bindings=True)
]
##~~ BlueprintPlugin
@octoprint.plugin.BlueprintPlugin.route("/upload_archive", methods=["POST"])
@restricted_access
@admin_permission.require(403)
def upload_archive(self):
import flask
input_name = "file"
input_upload_path = input_name + "." + self._settings.global_get(["server", "uploads", "pathSuffix"])
input_upload_name = input_name + "." + self._settings.global_get(["server", "uploads", "nameSuffix"])
if input_upload_path not in flask.request.values or input_upload_name not in flask.request.values:
return flask.make_response("No file included", 400)
upload_path = flask.request.values[input_upload_path]
upload_name = flask.request.values[input_upload_name]
import tempfile
import shutil
import os
archive = tempfile.NamedTemporaryFile(delete=False, suffix="-{upload_name}".format(**locals()))
try:
archive.close()
shutil.copy(upload_path, archive.name)
return self.command_install(path=archive.name, force="force" in flask.request.values and flask.request.values["force"] in valid_boolean_trues)
finally:
try:
os.remove(archive.name)
except Exception as e:
self._logger.warn("Could not remove temporary file {path} again: {message}".format(path=archive.name, message=str(e)))
##~~ SimpleApiPlugin
def get_api_commands(self):
return {
"install": ["url"],
"uninstall": ["plugin"],
"enable": ["plugin"],
"disable": ["plugin"],
"refresh_repository": []
}
def on_api_get(self, request):
if not admin_permission.can():
return make_response("Insufficient rights", 403)
plugins = self._plugin_manager.plugins
result = []
for name, plugin in plugins.items():
result.append(self._to_external_representation(plugin))
if "refresh_repository" in request.values and request.values["refresh_repository"] in valid_boolean_trues:
self._repository_available = self._refresh_repository()
return jsonify(plugins=result, repository=dict(available=self._repository_available, plugins=self._repository_plugins), os=self._get_os(), octoprint=self._get_octoprint_version())
def on_api_command(self, command, data):
if not admin_permission.can():
return make_response("Insufficient rights", 403)
if self._printer.is_printing() or self._printer.is_paused():
# do not update while a print job is running
return make_response("Printer is currently printing or paused", 409)
if command == "install":
url = data["url"]
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,
reinstall=plugin_name)
elif command == "uninstall":
plugin_name = data["plugin"]
if not plugin_name in self._plugin_manager.plugins:
return make_response("Unknown plugin: %s" % plugin_name, 404)
plugin = self._plugin_manager.plugins[plugin_name]
return self.command_uninstall(plugin)
elif command == "enable" or command == "disable":
plugin_name = data["plugin"]
if not plugin_name in self._plugin_manager.plugins:
return make_response("Unknown plugin: %s" % plugin_name, 404)
plugin = self._plugin_manager.plugins[plugin_name]
return self.command_toggle(plugin, command)
def command_install(self, url=None, path=None, force=False, reinstall=None):
if url is not None:
pip_args = ["install", sarge.shell_quote(url)]
elif path is not None:
pip_args = ["install", path]
else:
raise ValueError("Either url or path must be provided")
all_plugins_before = self._plugin_manager.find_plugins()
success_string = "Successfully installed"
failure_string = "Could not install"
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)
else:
if force:
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)
try:
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._send_result_notification("install", result)
return jsonify(result)
# The final output of a pip install command looks something like this:
#
# Successfully installed OctoPrint-Plugin-1.0 Dependency-One-0.1 Dependency-Two-9.3
#
# or this:
#
# 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.
#
# 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.
#
# Known issue: This might return the wrong plugin if more than one plugin was installed through this
# command (e.g. due to pulling in another plugin as dependency). It should be safe for now though to
# consider this a rare corner case. Once it becomes a real problem we'll just extend the plugin manager
# so that it can report on more than one installed plugin.
result_line = result_line.strip()
if not result_line.startswith(success_string):
result = dict(result=False, 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")
self._send_result_notification("install", result)
return jsonify(result)
self._plugin_manager.mark_plugin(new_plugin_key, uninstalled=False)
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)
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._send_result_notification("install", result)
return jsonify(result)
def command_uninstall(self, plugin):
if plugin.key == "pluginmanager":
return make_response("Can't uninstall Plugin Manager", 400)
if plugin.bundled:
return make_response("Bundled plugins cannot be uninstalled", 400)
if plugin.origin is None:
self._logger.warn(u"Trying to uninstall plugin {plugin} but origin is unknown".format(**locals()))
return make_response("Could not uninstall plugin, its origin is unknown")
if plugin.origin.type == "entry_point":
# plugin is installed through entry point, need to use pip to uninstall it
origin = plugin.origin[3]
if origin is None:
origin = plugin.origin[2]
pip_args = ["uninstall", "--yes", origin]
try:
self._call_pip(pip_args)
except:
self._logger.exception(u"Could not uninstall plugin via pip")
return make_response("Could not uninstall plugin via pip, see the log for more details", 500)
elif plugin.origin.type == "folder":
import os
import shutil
full_path = os.path.realpath(plugin.location)
if os.path.isdir(full_path):
# plugin is installed via a plugin folder, need to use rmtree to get rid of it
self._log_stdout(u"Deleting plugin from {folder}".format(folder=plugin.location))
shutil.rmtree(full_path)
elif os.path.isfile(full_path):
self._log_stdout(u"Deleting plugin from {file}".format(file=plugin.location))
os.remove(full_path)
if full_path.endswith(".py"):
pyc_file = "{full_path}c".format(**locals())
if os.path.isfile(pyc_file):
os.remove(pyc_file)
else:
self._logger.warn(u"Trying to uninstall plugin {plugin} but origin is unknown ({plugin.origin.type})".format(**locals()))
return make_response("Could not uninstall plugin, its origin is unknown")
needs_restart = self._plugin_manager.is_restart_needing_plugin(plugin)
needs_refresh = plugin.implementation and isinstance(plugin.implementation, octoprint.plugin.ReloadNeedingPlugin)
self._plugin_manager.mark_plugin(plugin.key, uninstalled=True)
if not needs_restart:
try:
self._plugin_manager.disable_plugin(plugin.key, plugin=plugin)
except octoprint.plugin.core.PluginLifecycleException as e:
self._logger.exception(u"Problem disabling plugin {name}".format(name=plugin.key))
result = dict(result=False, uninstalled=True, disabled=False, unloaded=False, reason=e.reason)
self._send_result_notification("uninstall", result)
return jsonify(result)
try:
self._plugin_manager.unload_plugin(plugin.key)
except octoprint.plugin.core.PluginLifecycleException as e:
self._logger.exception(u"Problem unloading plugin {name}".format(name=plugin.key))
result = dict(result=False, uninstalled=True, disabled=True, unloaded=False, reason=e.reason)
self._send_result_notification("uninstall", result)
return jsonify(result)
self._plugin_manager.reload_plugins()
result = dict(result=True, needs_restart=needs_restart, needs_refresh=needs_refresh, plugin=self._to_external_representation(plugin))
self._send_result_notification("uninstall", result)
return jsonify(result)
def command_toggle(self, plugin, command):
if plugin.key == "pluginmanager":
return make_response("Can't enable/disable Plugin Manager", 400)
needs_restart = self._plugin_manager.is_restart_needing_plugin(plugin)
needs_refresh = plugin.implementation and isinstance(plugin.implementation, octoprint.plugin.ReloadNeedingPlugin)
pending = ((command == "disable" and plugin.key in self._pending_enable) or (command == "enable" and plugin.key in self._pending_disable))
needs_restart_api = needs_restart and not pending
needs_refresh_api = needs_refresh and not pending
try:
if command == "disable":
self._mark_plugin_disabled(plugin, needs_restart=needs_restart)
elif command == "enable":
self._mark_plugin_enabled(plugin, needs_restart=needs_restart)
except octoprint.plugin.core.PluginLifecycleException as e:
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))
else:
result = dict(result=True, needs_restart=needs_restart_api, needs_refresh=needs_refresh_api, plugin=self._to_external_representation(plugin))
self._send_result_notification(command, result)
return jsonify(result)
def _send_result_notification(self, action, result):
notification = dict(type="result", action=action)
notification.update(result)
self._plugin_manager.send_plugin_message(self._identifier, notification)
def _call_pip(self, args):
if self._pip_caller is None or not self._pip_caller.available:
raise RuntimeError(u"No pip available, can't operate".format(**locals()))
return self._pip_caller.execute(*args)
def _log_call(self, *lines):
self._log(lines, prefix=" ", stream="call")
def _log_stdout(self, *lines):
self._log(lines, prefix=">", stream="stdout")
def _log_stderr(self, *lines):
self._log(lines, prefix="!", stream="stderr")
def _log(self, lines, prefix=None, stream=None, strip=True):
if strip:
lines = map(lambda x: x.strip(), lines)
self._plugin_manager.send_plugin_message(self._identifier, dict(type="loglines", loglines=[dict(line=line, stream=stream) for line in lines]))
for line in lines:
self._console_logger.debug(u"{prefix} {line}".format(**locals()))
def _mark_plugin_enabled(self, plugin, needs_restart=False):
disabled_list = list(self._settings.global_get(["plugins", "_disabled"]))
if plugin.key in disabled_list:
disabled_list.remove(plugin.key)
self._settings.global_set(["plugins", "_disabled"], disabled_list)
self._settings.save(force=True)
if not needs_restart:
self._plugin_manager.enable_plugin(plugin.key)
else:
if plugin.key in self._pending_disable:
self._pending_disable.remove(plugin.key)
elif not plugin.enabled and plugin.key not in self._pending_enable:
self._pending_enable.add(plugin.key)
def _mark_plugin_disabled(self, plugin, needs_restart=False):
disabled_list = list(self._settings.global_get(["plugins", "_disabled"]))
if not plugin.key in disabled_list:
disabled_list.append(plugin.key)
self._settings.global_set(["plugins", "_disabled"], disabled_list)
self._settings.save(force=True)
if not needs_restart:
self._plugin_manager.disable_plugin(plugin.key)
else:
if plugin.key in self._pending_enable:
self._pending_enable.remove(plugin.key)
elif plugin.enabled and plugin.key not in self._pending_disable:
self._pending_disable.add(plugin.key)
def _fetch_repository_from_disk(self):
repo_data = None
if os.path.isfile(self._repository_cache_path):
import time
mtime = os.path.getmtime(self._repository_cache_path)
if mtime + self._repository_cache_ttl >= time.time() > mtime:
try:
import json
with open(self._repository_cache_path) as f:
repo_data = json.load(f)
self._logger.info("Loaded plugin repository data from disk, was still valid")
except:
self._logger.exception("Error while loading repository data from {}".format(self._repository_cache_path))
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)
self._logger.info("Loaded plugin repository data from {}".format(repository_url))
except Exception as e:
self._logger.exception("Could not fetch plugins from repository at {repository_url}: {message}".format(repository_url=repository_url, message=str(e)))
return None
repo_data = r.json()
try:
import json
with open(self._repository_cache_path, "w+b") as f:
json.dump(repo_data, f)
except Exception as e:
self._logger.exception("Error while saving repository data to {}: {}".format(self._repository_cache_path, str(e)))
return repo_data
def _refresh_repository(self, repo_data=None):
if repo_data is None:
repo_data = self._fetch_repository_from_url()
if repo_data is None:
return False
current_os = self._get_os()
octoprint_version = self._get_octoprint_version()
if "-" in octoprint_version:
octoprint_version = octoprint_version[:octoprint_version.find("-")]
def map_repository_entry(entry):
result = dict(entry)
result["is_compatible"] = dict(
octoprint=True,
os=True
)
if "compatibility" in entry:
if "octoprint" in entry["compatibility"] and entry["compatibility"]["octoprint"] is not None and len(entry["compatibility"]["octoprint"]):
import semantic_version
for octo_compat in entry["compatibility"]["octoprint"]:
s = semantic_version.Spec("=={}".format(octo_compat))
if semantic_version.Version(octoprint_version) in s:
break
else:
result["is_compatible"]["octoprint"] = False
if "os" in entry["compatibility"] and entry["compatibility"]["os"] is not None and len(entry["compatibility"]["os"]):
result["is_compatible"]["os"] = current_os in entry["compatibility"]["os"]
return result
self._repository_plugins = map(map_repository_entry, repo_data)
return True
def _get_os(self):
if sys.platform == "win32":
return "windows"
elif sys.platform == "linux2":
return "linux"
elif sys.platform == "darwin":
return "macos"
else:
return "unknown"
def _get_octoprint_version(self):
from octoprint._version import get_versions
return get_versions()["version"]
def _to_external_representation(self, plugin):
return dict(
key=plugin.key,
name=plugin.name,
description=plugin.description,
author=plugin.author,
version=plugin.version,
url=plugin.url,
license=plugin.license,
bundled=plugin.bundled,
enabled=plugin.enabled,
pending_enable=(not plugin.enabled and plugin.key in self._pending_enable),
pending_disable=(plugin.enabled and plugin.key in self._pending_disable),
pending_install=(plugin.key in self._pending_install),
pending_uninstall=(plugin.key in self._pending_uninstall)
)
__plugin_name__ = "Plugin Manager"
__plugin_author__ = "Gina Häußge"
__plugin_url__ = "https://github.com/foosel/OctoPrint/wiki/Plugin:-Plugin-Manager"
__plugin_description__ = "Allows installing and managing OctoPrint plugins"
__plugin_license__ = "AGPLv3"
__plugin_implementation__ = PluginManagerPlugin()
@@ -1 +0,0 @@
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}
Binary file not shown.

Before

Width:  |  Height:  |  Size: 24 KiB

@@ -1,615 +0,0 @@
$(function() {
function PluginManagerViewModel(parameters) {
var self = this;
self.loginState = parameters[0];
self.settingsViewModel = parameters[1];
self.printerState = parameters[2];
self.plugins = new ItemListHelper(
"plugin.pluginmanager.installedplugins",
{
"name": function (a, b) {
// sorts ascending
if (a["name"].toLocaleLowerCase() < b["name"].toLocaleLowerCase()) return -1;
if (a["name"].toLocaleLowerCase() > b["name"].toLocaleLowerCase()) return 1;
return 0;
}
},
{
},
"name",
[],
[],
5
);
self.repositoryplugins = new ItemListHelper(
"plugin.pluginmanager.repositoryplugins",
{
"title": function (a, b) {
// sorts ascending
if (a["title"].toLocaleLowerCase() < b["title"].toLocaleLowerCase()) return -1;
if (a["title"].toLocaleLowerCase() > b["title"].toLocaleLowerCase()) return 1;
return 0;
},
"published": function (a, b) {
// sorts descending
if (a["published"].toLocaleLowerCase() > b["published"].toLocaleLowerCase()) return -1;
if (a["published"].toLocaleLowerCase() < b["published"].toLocaleLowerCase()) return 1;
return 0;
}
},
{
"filter_installed": function(plugin) {
return !self.installed(plugin);
},
"filter_incompatible": function(plugin) {
return plugin.is_compatible.octoprint && plugin.is_compatible.os;
}
},
"title",
["filter_installed", "filter_incompatible"],
[],
0
);
self.uploadElement = $("#settings_plugin_pluginmanager_repositorydialog_upload");
self.uploadButton = $("#settings_plugin_pluginmanager_repositorydialog_upload_start");
self.repositoryAvailable = ko.observable(false);
self.repositorySearchQuery = ko.observable();
self.repositorySearchQuery.subscribe(function() {
self.performRepositorySearch();
});
self.installUrl = ko.observable();
self.uploadFilename = ko.observable();
self.loglines = ko.observableArray([]);
self.installedPlugins = ko.observableArray([]);
self.working = ko.observable(false);
self.workingTitle = ko.observable();
self.workingDialog = undefined;
self.workingOutput = undefined;
self.enableManagement = ko.computed(function() {
return !self.printerState.isPrinting();
});
self.enableToggle = function(data) {
return self.enableManagement() && data.key != 'pluginmanager';
};
self.enableUninstall = function(data) {
return self.enableManagement() && !data.bundled && data.key != 'pluginmanager' && !data.pending_uninstall;
};
self.enableRepoInstall = function(data) {
return self.enableManagement() && self.isCompatible(data);
};
self.invalidUrl = ko.computed(function() {
var url = self.installUrl();
return url !== undefined && url.trim() != "" && !(_.startsWith(url.toLocaleLowerCase(), "http://") || _.startsWith(url.toLocaleLowerCase(), "https://"));
});
self.enableUrlInstall = ko.computed(function() {
var url = self.installUrl();
return self.enableManagement() && url !== undefined && url.trim() != "" && !self.invalidUrl();
});
self.invalidArchive = ko.computed(function() {
var name = self.uploadFilename();
return name !== undefined && !(_.endsWith(name.toLocaleLowerCase(), ".zip") || _.endsWith(name.toLocaleLowerCase(), ".tar.gz") || _.endsWith(name.toLocaleLowerCase(), ".tgz") || _.endsWith(name.toLocaleLowerCase(), ".tar"));
});
self.enableArchiveInstall = ko.computed(function() {
var name = self.uploadFilename();
return self.enableManagement() && name !== undefined && name.trim() != "" && !self.invalidArchive();
});
self.uploadElement.fileupload({
dataType: "json",
maxNumberOfFiles: 1,
autoUpload: false,
add: function(e, data) {
if (data.files.length == 0) {
return false;
}
self.uploadFilename(data.files[0].name);
self.uploadButton.unbind("click");
self.uploadButton.bind("click", function() {
self._markWorking(gettext("Installing plugin..."), gettext("Installing plugin from uploaded archive..."));
data.submit();
return false;
});
},
done: function(e, data) {
self._markDone();
self.uploadButton.unbind("click");
self.uploadFilename("");
},
fail: function(e, data) {
new PNotify({
title: gettext("Something went wrong"),
text: gettext("Please consult octoprint.log for details"),
type: "error",
hide: false
});
self._markDone();
self.uploadButton.unbind("click");
self.uploadFilename("");
}
});
self.performRepositorySearch = function() {
var query = self.repositorySearchQuery();
if (query !== undefined && query.trim() != "") {
self.repositoryplugins.changeSearchFunction(function(entry) {
return entry && (entry["title"].toLocaleLowerCase().indexOf(query) > -1 || entry["description"].toLocaleLowerCase().indexOf(query) > -1);
});
} else {
self.repositoryplugins.resetSearch();
}
};
self.fromResponse = function(data) {
self._fromPluginsResponse(data.plugins);
self._fromRepositoryResponse(data.repository)
};
self._fromPluginsResponse = function(data) {
var installedPlugins = [];
_.each(data, function(plugin) {
installedPlugins.push(plugin.key);
});
self.installedPlugins(installedPlugins);
self.plugins.updateItems(data);
};
self._fromRepositoryResponse = function(data) {
self.repositoryAvailable(data.available);
if (data.available) {
self.repositoryplugins.updateItems(data.plugins);
} else {
self.repositoryplugins.updateItems([]);
}
};
self.requestData = function(includeRepo) {
if (!self.loginState.isAdmin()) {
return;
}
$.ajax({
url: API_BASEURL + "plugin/pluginmanager" + ((includeRepo) ? "?refresh_repository=true" : ""),
type: "GET",
dataType: "json",
success: self.fromResponse
});
};
self.togglePlugin = function(data) {
if (!self.loginState.isAdmin()) {
return;
}
if (!self.enableManagement()) {
return;
}
if (data.key == "pluginmanager") return;
var command = self._getToggleCommand(data);
var payload = {plugin: data.key};
self._postCommand(command, payload, function(response) {
self.requestData();
}, function() {
new PNotify({
title: gettext("Something went wrong"),
text: gettext("Please consult octoprint.log for details"),
type: "error",
hide: false
})
});
};
self.showRepository = function() {
self.repositoryDialog.modal("show");
};
self.pluginDetails = function(data) {
window.open(data.page);
};
self.installFromRepository = function(data) {
if (!self.loginState.isAdmin()) {
return;
}
if (!self.enableManagement()) {
return;
}
if (self.installed(data)) {
self.installPlugin(data.archive, data.title, data.id);
} else {
self.installPlugin(data.archive, data.title, undefined);
}
};
self.installPlugin = function(url, name, reinstall) {
if (!self.loginState.isAdmin()) {
return;
}
if (!self.enableManagement()) {
return;
}
if (url === undefined) {
url = self.installUrl();
}
if (!url) return;
var workTitle, workText;
if (!reinstall) {
workTitle = gettext("Installing plugin...");
if (name) {
workText = _.sprintf(gettext("Installing plugin \"%(name)s\" from %(url)s..."), {url: url, name: name});
} else {
workText = _.sprintf(gettext("Installing plugin from %(url)s..."), {url: url});
}
} else {
workTitle = gettext("Reinstalling plugin...");
workText = _.sprintf(gettext("Reinstalling plugin \"%(name)s\" from %(url)s..."), {url: url, name: name});
}
self._markWorking(workTitle, workText);
var command = "install";
var payload = {url: url};
if (reinstall) {
payload["plugin"] = reinstall;
payload["force"] = true;
}
self._postCommand(command, payload, function(response) {
self.requestData();
self._markDone();
self.installUrl("");
}, function() {
new PNotify({
title: gettext("Something went wrong"),
text: gettext("Please consult octoprint.log for details"),
type: "error",
hide: false
});
self._markDone();
});
};
self.uninstallPlugin = function(data) {
if (!self.loginState.isAdmin()) {
return;
}
if (!self.enableManagement()) {
return;
}
if (data.bundled) return;
if (data.key == "pluginmanager") return;
self._markWorking(gettext("Uninstalling plugin..."), _.sprintf(gettext("Uninstalling plugin \"%(name)s\""), {name: data.name}));
var command = "uninstall";
var payload = {plugin: data.key};
self._postCommand(command, payload, function(response) {
self.requestData();
self._markDone();
}, function() {
new PNotify({
title: gettext("Something went wrong"),
text: gettext("Please consult octoprint.log for details"),
type: "error",
hide: false
});
self._markDone();
});
};
self.refreshRepository = function() {
if (!self.loginState.isAdmin()) {
return;
}
self.requestData(true);
};
self.installed = function(data) {
return _.includes(self.installedPlugins(), data.id);
};
self.isCompatible = function(data) {
return data.is_compatible.octoprint && data.is_compatible.os;
};
self.installButtonText = function(data) {
return self.isCompatible(data) ? (self.installed(data) ? gettext("Reinstall") : gettext("Install")) : gettext("Incompatible");
};
self._displayNotification = function(response, titleSuccess, textSuccess, textRestart, textReload, titleError, textError) {
if (response.result) {
if (response.needs_restart) {
new PNotify({
title: titleSuccess,
text: textRestart,
hide: false
});
} else if (response.needs_refresh) {
new PNotify({
title: titleSuccess,
text: textReload,
confirm: {
confirm: true,
buttons: [{
text: gettext("Reload now"),
click: function () {
location.reload(true);
}
}]
},
buttons: {
closer: false,
sticker: false
},
hide: false
})
} else {
new PNotify({
title: titleSuccess,
text: textSuccess,
type: "success",
hide: false
})
}
} else {
new PNotify({
title: titleError,
text: textError,
type: "error",
hide: false
});
}
};
self._postCommand = function (command, data, successCallback, failureCallback, alwaysCallback, timeout) {
var payload = _.extend(data, {command: command});
var params = {
url: API_BASEURL + "plugin/pluginmanager",
type: "POST",
dataType: "json",
data: JSON.stringify(payload),
contentType: "application/json; charset=UTF-8",
success: function(response) {
if (successCallback) successCallback(response);
},
error: function() {
if (failureCallback) failureCallback();
},
complete: function() {
if (alwaysCallback) alwaysCallback();
}
};
if (timeout != undefined) {
params.timeout = timeout;
}
$.ajax(params);
};
self._markWorking = function(title, line) {
self.working(true);
self.workingTitle(title);
self.loglines.removeAll();
self.loglines.push({line: line, stream: "message"});
self.workingDialog.modal("show");
};
self._markDone = function() {
self.working(false);
self.loglines.push({line: gettext("Done!"), stream: "message"});
self._scrollWorkingOutputToEnd();
};
self._scrollWorkingOutputToEnd = function() {
self.workingOutput.scrollTop(self.workingOutput[0].scrollHeight - self.workingOutput.height());
};
self._getToggleCommand = function(data) {
return ((!data.enabled || data.pending_disable) && !data.pending_enable) ? "enable" : "disable";
};
self.toggleButtonCss = function(data) {
var icon = self._getToggleCommand(data) == "enable" ? "icon-circle-blank" : "icon-circle";
var disabled = (self.enableToggle(data)) ? "" : " disabled";
return icon + disabled;
};
self.toggleButtonTitle = function(data) {
return self._getToggleCommand(data) == "enable" ? gettext("Enable Plugin") : gettext("Disable Plugin");
};
self.onBeforeBinding = function() {
self.settings = self.settingsViewModel.settings;
};
self.onUserLoggedIn = function(user) {
if (user.admin) {
self.requestData();
}
};
self.onStartup = function() {
self.workingDialog = $("#settings_plugin_pluginmanager_workingdialog");
self.workingOutput = $("#settings_plugin_pluginmanager_workingdialog_output");
self.repositoryDialog = $("#settings_plugin_pluginmanager_repositorydialog");
$("#settings_plugin_pluginmanager_repositorydialog_list").slimScroll({
height: "306px",
size: "5px",
distance: "0",
railVisible: true,
alwaysVisible: true,
scrollBy: "102px"
});
};
self.onDataUpdaterPluginMessage = function(plugin, data) {
if (plugin != "pluginmanager") {
return;
}
if (!self.loginState.isAdmin()) {
return;
}
if (!data.hasOwnProperty("type")) {
return;
}
var messageType = data.type;
if (messageType == "loglines" && self.working()) {
_.each(data.loglines, function(line) {
self.loglines.push(line);
});
self._scrollWorkingOutputToEnd();
} else if (messageType == "result") {
var titleSuccess, textSuccess, textRestart, textReload, titleError, textError;
var action = data.action;
var name = "Unknown";
if (action == "install") {
var unknown = false;
if (data.hasOwnProperty("plugin")) {
if (data.plugin == "unknown") {
unknown = true;
} else {
name = data.plugin.name;
}
}
if (unknown) {
titleSuccess = _.sprintf(gettext("Plugin installed"));
textSuccess = gettext("A plugin was installed successfully, however it was impossible to detect which one. Please Restart OctoPrint to make sure everything will be registered properly");
textRestart = textSuccess;
textReload = textSuccess;
} else if (data.was_reinstalled) {
titleSuccess = _.sprintf(gettext("Plugin \"%(name)s\" reinstalled"), {name: name});
textSuccess = gettext("The plugin was reinstalled successfully");
textRestart = gettext("The plugin was reinstalled successfully, however a restart of OctoPrint is needed for that to take effect.");
textReload = gettext("The plugin was reinstalled successfully, however a reload of the page is needed for that to take effect.");
} else {
titleSuccess = _.sprintf(gettext("Plugin \"%(name)s\" installed"), {name: name});
textSuccess = gettext("The plugin was installed successfully");
textRestart = gettext("The plugin was installed successfully, however a restart of OctoPrint is needed for that to take effect.");
textReload = gettext("The plugin was installed successfully, however a reload of the page is needed for that to take effect.");
}
titleError = gettext("Something went wrong");
var url = "unknown";
if (data.hasOwnProperty("url")) {
url = data.url;
}
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});
} else {
textError = _.sprintf(gettext("Installing the plugin from URL \"%(url)s\" failed: %(reason)s"), {reason: data.reason, url: url});
}
} else {
if (data.was_reinstalled) {
textError = _.sprintf(gettext("Reinstalling the plugin from URL \"%(url)s\" failed, please see the log for details."), {url: url});
} else {
textError = _.sprintf(gettext("Installing the plugin from URL \"%(url)s\" failed, please see the log for details."), {url: url});
}
}
} else if (action == "uninstall") {
if (data.hasOwnProperty("plugin")) {
name = data.plugin.name;
}
titleSuccess = _.sprintf(gettext("Plugin \"%(name)s\" uninstalled"), {name: name});
textSuccess = gettext("The plugin was uninstalled successfully");
textRestart = gettext("The plugin was uninstalled successfully, however a restart of OctoPrint is needed for that to take effect.");
textReload = gettext("The plugin was uninstalled successfully, however a reload of the page is needed for that to take effect.");
titleError = gettext("Something went wrong");
if (data.hasOwnProperty("reason")) {
textError = _.sprintf(gettext("Uninstalling the plugin failed: %(reason)s"), {reason: data.reason});
} else {
textError = gettext("Uninstalling the plugin failed, please see the log for details.");
}
} else if (action == "enable") {
if (data.hasOwnProperty("plugin")) {
name = data.plugin.name;
}
titleSuccess = _.sprintf(gettext("Plugin \"%(name)s\" enabled"), {name: name});
textSuccess = gettext("The plugin was enabled successfully.");
textRestart = gettext("The plugin was enabled successfully, however a restart of OctoPrint is needed for that to take effect.");
textReload = gettext("The plugin was enabled successfully, however a reload of the page is needed for that to take effect.");
titleError = gettext("Something went wrong");
if (data.hasOwnProperty("reason")) {
textError = _.sprintf(gettext("Toggling the plugin failed: %(reason)s"), {reason: data.reason});
} else {
textError = gettext("Toggling the plugin failed, please see the log for details.");
}
} else if (action == "disable") {
if (data.hasOwnProperty("plugin")) {
name = data.plugin.name;
}
titleSuccess = _.sprintf(gettext("Plugin \"%(name)s\" disabled"), {name: name});
textSuccess = gettext("The plugin was disabled successfully.");
textRestart = gettext("The plugin was disabled successfully, however a restart of OctoPrint is needed for that to take effect.");
textReload = gettext("The plugin was disabled successfully, however a reload of the page is needed for that to take effect.");
titleError = gettext("Something went wrong");
if (data.hasOwnProperty("reason")) {
textError = _.sprintf(gettext("Toggling the plugin failed: %(reason)s"), {reason: data.reason});
} else {
textError = gettext("Toggling the plugin failed, please see the log for details.");
}
} else {
return;
}
self._displayNotification(data, titleSuccess, textSuccess, textRestart, textReload, titleError, textError);
self.requestData();
}
};
}
// view model class, parameters for constructor, container to bind to
ADDITIONAL_VIEWMODELS.push([PluginManagerViewModel, ["loginStateViewModel", "settingsViewModel", "printerStateViewModel"], "#settings_plugin_pluginmanager"]);
});
@@ -1,103 +0,0 @@
table {
th, td {
&.settings_plugin_plugin_manager_plugins_name {
text-overflow: ellipsis;
text-align: left;
}
&.settings_plugin_plugin_manager_plugins_actions {
text-align: center;
width: 80px;
a {
text-decoration: none;
color: #000;
&.disabled {
color: #ccc;
cursor: default;
}
}
}
}
}
#settings_plugin_pluginmanager_repositorydialog {
.slimScrollDiv {
margin-bottom: 20px;
}
h4 {
position: relative;
a.dropdown-toggle {
color: inherit;
text-decoration: none;
font-size: 14px;
}
ul.dropdown-menu {
font-size: 14px;
}
}
.form-search {
text-align: center;
margin-bottom: 5px !important;
}
.form-inline {
padding: 5px;
padding-right: 10px;
margin-bottom: 0;
.help-block {
margin-bottom: 0;
font-size: 85%;
}
}
#settings_plugin_pluginmanager_repositorydialog_unavailable {
overflow: hidden;
width: 100%;
height: 300px;
background-image: url("../img/repo_unavailable.png");
text-align: center;
display: table;
div {
display: table-cell;
vertical-align: middle;
}
}
#settings_plugin_pluginmanager_repositorydialog_list {
overflow: hidden;
width: auto;
height: 300px;
.entry {
border-bottom: 1px solid #ddd;
padding: 5px;
padding-right: 10px;
}
}
}
#settings_plugin_pluginmanager_workingdialog_output {
.message {
font-weight: bold;
}
.stdout {
color: #333333;
}
.stderr {
color: #990000;
}
.call {
color: #000099;
}
}
@@ -1,154 +0,0 @@
{% macro pluginmanager_printing() %}
<div class="alert" data-bind="visible: !enableManagement()">
{{ _('Take note that all plugin management functionality is disabled while your printer is printing.') }}
</div>
{% endmacro %}
{{ pluginmanager_printing() }}
<h3>{{ _('Installed Plugins') }}</h3>
<table class="table table-striped table-hover table-condensed table-hover">
<thead>
<tr>
<th class="settings_plugin_plugin_manager_plugins_name">{{ _('Name') }}</th>
<th class="settings_plugin_plugin_manager_plugins_actions">{{ _('Actions') }}</th>
</tr>
</thead>
<tbody data-bind="foreach: plugins.paginatedItems">
<tr>
<td class="settings_plugin_plugin_manager_plugins_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') }}" class="icon-th-large" data-bind="visible: bundled"></i> <i title="Restart needed" class="icon-refresh" data-bind="visible: pending_enable || pending_disable || pending_uninstall"></i> <i title="Uninstalled" class="icon-remove" data-bind="visible: pending_uninstall"></i></div>
<div><small class="muted" data-bind="text: description">&nbsp;</small></div>
<div data-bind="css: {muted: !enabled}">
<small data-bind="visible: url"><i class="icon-home"></i> <a data-bind="attr: {href: url}">{{ _('Homepage') }}</a></small>
<small data-bind="visible: license"><i class="icon-legal"></i> <span data-bind="text: license"></span></small>
<small data-bind="visible: author"><i class="icon-user"></i> <span data-bind="text: author"></span></small>
<small>&nbsp;</small>
</div>
</td>
<td class="settings_plugin_plugin_manager_plugins_actions">
<a href="#" data-bind="css: $root.toggleButtonCss($data), attr: {title: $root.toggleButtonTitle($data)}, enable: $root.enableToggle($data), click: function() { $root.togglePlugin($data) }"></a>&nbsp;|&nbsp;<a href="#" class="icon-trash" title="{{ _('Uninstall Plugin') }}" data-bind="css: {disabled: !$root.enableUninstall($data)}, enable: $root.enableUninstall($data), click: function() { $root.uninstallPlugin($data) }"></a>
</td>
</tr>
</tbody>
</table>
<div class="pagination pagination-mini pagination-centered">
<ul>
<li data-bind="css: {disabled: plugins.currentPage() === 0}"><a href="#" data-bind="click: plugins.prevPage">«</a></li>
</ul>
<ul data-bind="foreach: plugins.pages">
<li data-bind="css: { active: $data.number === $root.plugins.currentPage(), disabled: $data.number === -1 }"><a href="#" data-bind="text: $data.text, click: function() { $root.plugins.changePage($data.number); }"></a></li>
</ul>
<ul>
<li data-bind="css: {disabled: plugins.currentPage() === plugins.lastPage()}"><a href="#" data-bind="click: plugins.nextPage">»</a></li>
</ul>
</div>
<button class="btn btn-block" data-bind="click: $root.showRepository">{{ _('Get More...') }}</button>
<div id="settings_plugin_pluginmanager_workingdialog" class="modal hide fade">
<div class="modal-header">
<a href="#" class="close" data-dismiss="modal" aria-hidden="true">&times;</a>
<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>
</div>
<div class="modal-footer">
<button class="btn" data-dismiss="modal" data-bind="enable: !$root.working()" aria-hidden="true">{{ _('Close') }}</button>
</div>
</div>
<div id="settings_plugin_pluginmanager_repositorydialog" class="modal hide fade">
<div class="modal-header">
<a href="#" class="close" data-dismiss="modal" aria-hidden="true">&times;</a>
<h3>{{ _('Install new Plugins...') }}</h3>
</div>
<div class="modal-body">
{{ pluginmanager_printing() }}
<h4 style="position: relative">
{{ _('... from the <a href="%(url)s" target="_blank">Plugin Repository</a>', url='http://plugins.octoprint.org') }}
<a class="dropdown-toggle pull-right" data-toggle="dropdown" href="#">
<span class="icon-wrench"></span>
<ul class="dropdown-menu pull-right">
<li><a href="#" data-bind="click: function() { repositoryplugins.changeSorting('title'); }"><i class="icon-ok" data-bind="style: {visibility: repositoryplugins.currentSorting() == 'title' ? 'visible' : 'hidden'}"></i> {{ _('Sort by title') }} ({{ _('ascending') }})</a></li>
<li><a href="#" data-bind="click: function() { repositoryplugins.changeSorting('published'); }"><i class="icon-ok" data-bind="style: {visibility: repositoryplugins.currentSorting() == 'published' ? 'visible' : 'hidden'}"></i> {{ _('Sort by publication date') }} ({{ _('descending') }})</a></li>
<li class="divider"></li>
<li><a href="#" data-bind="click: function() { repositoryplugins.toggleFilter('filter_installed'); }"><i class="icon-ok" data-bind="style: {visibility: _.contains(repositoryplugins.currentFilters(), 'filter_installed') ? 'visible' : 'hidden'}"></i> {{ _('Only show uninstalled plugins') }}</a></li>
<li><a href="#" data-bind="click: function() { repositoryplugins.toggleFilter('filter_incompatible'); }"><i class="icon-ok" data-bind="style: {visibility: _.contains(repositoryplugins.currentFilters(), 'filter_incompatible') ? 'visible' : 'hidden'}"></i> {{ _('Only show compatible plugins') }}</a></li>
<li class="divider"></li>
<li><a href="#" data-bind="click: function() { refreshRepository(); }"><i class="icon-refresh"></i> {{ _('Refresh list from repository') }}</a></li>
</ul>
</a>
</h4>
<form class="form-search">
<input type="text" class="input-block search-query" data-bind="value: repositorySearchQuery, valueUpdate: 'input'" placeholder="{{ _('Search...') }}">
</form>
<div data-bind="visible: repositoryAvailable()">
<div id="settings_plugin_pluginmanager_repositorydialog_list" data-bind="slimScrolledForeach: repositoryplugins.paginatedItems">
<div class="entry">
<div class="row-fluid">
<div class="span9">
<div><span data-bind="text: title"></span></div>
<div><small class="muted" data-bind="text: description">&nbsp;</small></div>
<div>
<small data-bind="visible: page"><i class="icon-info"></i> <a data-bind="attr: {href: page}" target="_blank">{{ _('Details') }}</a></small>
<small data-bind="visible: homepage"><i class="icon-home"></i> <a data-bind="attr: {href: homepage}" target="_blank">{{ _('Homepage') }}</a></small>
<small data-bind="visible: license"><i class="icon-legal"></i> <span data-bind="text: license"></span></small>
<small data-bind="visible: author"><i class="icon-user"></i> <span data-bind="text: author"></span></small>
<small>&nbsp;</small>
</div>
</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>
</div>
</div>
</div>
</div>
<div id="settings_plugin_pluginmanager_repositorydialog_unavailable" data-bind="visible: !repositoryAvailable()">
<div>
<p>
<strong>{{ _('Sadly the repository is currently not available') }}</strong>
</p>
<p>
<small>{{ _('Is your OctoPrint installation connected to the internet?') }}</small>
</p>
</div>
</div>
<h4>{{ _('... from URL') }}</h4>
<form class="form-inline">
<div class="control-group row-fluid" data-bind="css: {error: invalidUrl}">
<div class="span9">
<input type="text" class="input-block-level" data-bind="value: installUrl, valueUpdate: 'input'" placeholder="{{ _('Enter URL...') }}" >
</div>
<button class="btn btn-primary span3" data-bind="enable: enableUrlInstall, css: {disabled: !enableUrlInstall()}, click: function() { if (enableUrlInstall()) { $root.installPlugin(); } }">{{ _('Install') }}</button>
</div>
<span class="help-block" data-bind="visible: invalidUrl">{{ _('This does not look like a valid "http://" or "https://" URL.') }}</span>
</form>
<h4>{{ _('... from an uploaded archive') }}</h4>
<form class="form-inline">
<div class="control-group row-fluid" data-bind="css: {error: invalidArchive}">
<div class="input-prepend span9">
<span class="btn fileinput-button">
<span>{{ _('Browse...') }}</span>
<input id="settings_plugin_pluginmanager_repositorydialog_upload" type="file" name="file" data-url="{{ url_for("plugin.pluginmanager.upload_archive") }}">
</span>
<span class="add-on add-on-limited text-left" data-bind="text: uploadFilename, attr: {title: uploadFilename}"></span>
</div>
<button id="settings_plugin_pluginmanager_repositorydialog_upload_start" class="btn btn-primary span3" data-bind="enable: enableArchiveInstall, css: {disabled: !enableArchiveInstall()}, click: function(){}">{{ _('Install') }}</button>
</div>
<span class="help-block" data-bind="visible: invalidArchive">{{ _('This does not look like a valid plugin archive. Valid plugin archives should be either zip files or tarballs and have the extension ".zip", ".tar.gz", ".tgz" or ".tar"') }}</span>
</form>
</div>
<div class="modal-footer">
<button class="btn" data-dismiss="modal" aria-hidden="true">{{ _('Close') }}</button>
</div>
</div>
@@ -1,600 +0,0 @@
# coding=utf-8
from __future__ import absolute_import
__author__ = "Gina Häußge <osd@foosel.net>"
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
import octoprint.plugin
import flask
import os
import threading
import time
from . import version_checks, updaters, exceptions, util
from octoprint.server.util.flask import restricted_access
from octoprint.server import admin_permission
from octoprint.util import dict_merge
import octoprint.settings
##~~ Plugin
class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
octoprint.plugin.SettingsPlugin,
octoprint.plugin.AssetPlugin,
octoprint.plugin.TemplatePlugin):
def __init__(self):
self._update_in_progress = False
self._configured_checks_mutex = threading.Lock()
self._configured_checks = None
self._refresh_configured_checks = False
self._version_cache = dict()
self._version_cache_ttl = 0
self._version_cache_path = None
self._version_cache_dirty = False
def initialize(self):
self._version_cache_ttl = self._settings.get_int(["cache_ttl"]) * 60
self._version_cache_path = os.path.join(self.get_plugin_data_folder(), "versioncache.yaml")
self._load_version_cache()
def refresh_checks(name, plugin):
self._refresh_configured_checks = True
self._send_client_message("update_versions")
self._plugin_lifecycle_manager.add_callback("enabled", refresh_checks)
self._plugin_lifecycle_manager.add_callback("disabled", refresh_checks)
def _get_configured_checks(self):
with self._configured_checks_mutex:
if self._refresh_configured_checks or self._configured_checks is None:
self._refresh_configured_checks = False
self._configured_checks = self._settings.get(["checks"], merged=True)
update_check_hooks = self._plugin_manager.get_hooks("octoprint.plugin.softwareupdate.check_config")
for name, hook in update_check_hooks.items():
try:
hook_checks = hook()
except:
self._logger.exception("Error while retrieving update information from plugin {name}".format(**locals()))
else:
for key, data in hook_checks.items():
if key in self._configured_checks:
data = dict_merge(data, self._configured_checks[key])
self._configured_checks[key] = data
return self._configured_checks
def _load_version_cache(self):
if not os.path.isfile(self._version_cache_path):
return
import yaml
try:
with open(self._version_cache_path) as f:
data = yaml.safe_load(f)
except:
self._logger.exception("Error while loading version cache from disk")
else:
self._version_cache = data
self._version_cache_dirty = False
self._logger.info("Loaded version cache from disk")
def _save_version_cache(self):
import tempfile
import yaml
import shutil
file_obj = tempfile.NamedTemporaryFile(delete=False)
try:
yaml.safe_dump(self._version_cache, stream=file_obj, default_flow_style=False, indent=" ", allow_unicode=True)
file_obj.close()
shutil.move(file_obj.name, self._version_cache_path)
self._version_cache_dirty = False
self._logger.info("Saved version cache to disk")
finally:
try:
if os.path.exists(file_obj.name):
os.remove(file_obj.name)
except Exception as e:
self._logger.warn("Could not delete file {}: {}".format(file_obj.name, str(e)))
#~~ SettingsPlugin API
def get_settings_defaults(self):
return {
"checks": {
"octoprint": {
"type": "github_release",
"user": "foosel",
"repo": "OctoPrint",
"update_script": "{{python}} \"{update_script}\" --python=\"{{python}}\" \"{{folder}}\" {{target}}".format(update_script=os.path.join(self._basefolder, "scripts", "update-octoprint.py")),
"restart": "octoprint"
},
},
"octoprint_restart_command": None,
"environment_restart_command": None,
"pip_command": None,
"cache_ttl": 24 * 60,
}
def on_settings_save(self, data):
octoprint.plugin.SettingsPlugin.on_settings_save(self, data)
self._version_cache_ttl = self._settings.get_int(["cache_ttl"]) * 60
def get_settings_version(self):
return 2
def on_settings_migrate(self, target, current=None):
if current is None:
# there might be some left over data from the time we still persisted everything to settings,
# even the stuff that shouldn't be persisted but always provided by the hook - let's
# clean up
configured_checks = self._settings.get(["checks"], incl_defaults=False)
if configured_checks is None:
configured_checks = dict()
# take care of the octoprint entry
if "octoprint" in configured_checks:
octoprint_check = dict(configured_checks["octoprint"])
if "type" in octoprint_check and not octoprint_check["type"] == "github_commit":
deletables=["current"]
else:
deletables=[]
octoprint_check = self._clean_settings_check("octoprint", octoprint_check, self.get_settings_defaults()["checks"]["octoprint"], delete=deletables, save=False)
# and the hooks
update_check_hooks = self._plugin_manager.get_hooks("octoprint.plugin.softwareupdate.check_config")
for name, hook in update_check_hooks.items():
try:
hook_checks = hook()
except:
self._logger.exception("Error while retrieving update information from plugin {name}".format(**locals()))
else:
for key, data in hook_checks.items():
if key in configured_checks:
settings_check = dict(configured_checks[key])
merged = dict_merge(data, settings_check)
if "type" in merged and not merged["type"] == "github_commit":
deletables = ["current", "displayVersion"]
else:
deletables = []
self._clean_settings_check(key, settings_check, data, delete=deletables, save=False)
elif current == 1:
configured_checks = self._settings.get(["checks"], incl_defaults=False)
if configured_checks is None:
return
if "octoprint" in configured_checks and "octoprint" in configured_checks["octoprint"]:
# that's a circular reference, back to defaults
dummy_defaults = dict(plugins=dict())
dummy_defaults["plugins"][self._identifier] = dict(checks=dict())
dummy_defaults["plugins"][self._identifier]["checks"]["octoprint"] = None
self._settings.set(["checks", "octoprint"], None, defaults=dummy_defaults)
self._settings.save()
def _clean_settings_check(self, key, data, defaults, delete=None, save=True):
if delete is None:
delete = []
for k, v in data.items():
if k in defaults and defaults[k] == data[k]:
del data[k]
for k in delete:
if k in data:
del data[k]
dummy_defaults = dict(plugins=dict())
dummy_defaults["plugins"][self._identifier] = dict(checks=dict())
dummy_defaults["plugins"][self._identifier]["checks"][key] = defaults
if len(data):
self._settings.set(["checks", key], data, defaults=dummy_defaults)
else:
self._settings.set(["checks", key], None, defaults=dummy_defaults)
if save:
self._settings.save()
return data
#~~ BluePrint API
@octoprint.plugin.BlueprintPlugin.route("/check", methods=["GET"])
@restricted_access
def check_for_update(self):
if "check" in flask.request.values:
check_targets = map(str.strip, flask.request.values["check"].split(","))
else:
check_targets = None
if "force" in flask.request.values and flask.request.values["force"] in octoprint.settings.valid_boolean_trues:
force = True
else:
force = False
try:
information, update_available, update_possible = self.get_current_versions(check_targets=check_targets, force=force)
return flask.jsonify(dict(status="updatePossible" if update_available and update_possible else "updateAvailable" if update_available else "current", information=information))
except exceptions.ConfigurationInvalid as e:
flask.make_response("Update not properly configured, can't proceed: %s" % e.message, 500)
@octoprint.plugin.BlueprintPlugin.route("/update", methods=["POST"])
@restricted_access
@admin_permission.require(403)
def perform_update(self):
if self._printer.is_printing() or self._printer.is_paused():
# do not update while a print job is running
return flask.make_response("Printer is currently printing or paused", 409)
if not "application/json" in flask.request.headers["Content-Type"]:
return flask.make_response("Expected content-type JSON", 400)
json_data = flask.request.json
if "check" in json_data:
check_targets = map(str.strip, json_data["check"])
else:
check_targets = None
if "force" in json_data and json_data["force"] in octoprint.settings.valid_boolean_trues:
force = True
else:
force = False
to_be_checked, checks = self.perform_updates(check_targets=check_targets, force=force)
return flask.jsonify(dict(order=to_be_checked, checks=checks))
#~~ Asset API
def get_assets(self):
return dict(
css=["css/softwareupdate.css"],
js=["js/softwareupdate.js"],
less=["less/softwareupdate.less"]
)
##~~ TemplatePlugin API
def get_template_configs(self):
return [
dict(type="settings", name="Software Update")
]
#~~ Updater
def get_current_versions(self, check_targets=None, force=False):
"""
Retrieves the current version information for all defined check_targets. Will retrieve information for all
available targets by default.
:param check_targets: an iterable defining the targets to check, if not supplied defaults to all targets
"""
checks = self._get_configured_checks()
if check_targets is None:
check_targets = checks.keys()
update_available = False
update_possible = False
information = dict()
for target, check in checks.items():
if not target in check_targets:
continue
try:
target_information, target_update_available, target_update_possible = self._get_current_version(target, check, force=force)
if target_information is None:
continue
except exceptions.UnknownCheckType:
self._logger.warn("Unknown update check type for %s" % target)
continue
target_information = dict_merge(dict(local=dict(name="unknown", value="unknown"), remote=dict(name="unknown", value="unknown")), target_information)
update_available = update_available or target_update_available
update_possible = update_possible or (target_update_possible and target_update_available)
information[target] = dict(updateAvailable=target_update_available, updatePossible=target_update_possible, information=target_information)
if "displayName" in check:
information[target]["displayName"] = check["displayName"]
if "displayVersion" in check:
from octoprint._version import get_versions
octoprint_version = get_versions()["version"]
local_name = target_information["local"]["name"]
local_value = target_information["local"]["value"]
information[target]["displayVersion"] = check["displayVersion"].format(octoprint_version=octoprint_version, local_name=local_name, local_value=local_value)
if self._version_cache_dirty:
self._save_version_cache()
return information, update_available, update_possible
def _get_current_version(self, target, check, force=False):
"""
Determines the current version information for one target based on its check configuration.
"""
if target in self._version_cache and not force:
timestamp, information, update_available, update_possible = self._version_cache[target]
if timestamp + self._version_cache_ttl >= time.time() > timestamp:
# we also check that timestamp < now to not get confused too much by clock changes
return information, update_available, update_possible
information = dict()
update_available = False
try:
version_checker = self._get_version_checker(target, check)
information, is_current = version_checker.get_latest(target, check)
if information is not None and not is_current:
update_available = True
except exceptions.UnknownCheckType:
self._logger.warn("Unknown check type %s for %s" % (check["type"], target))
update_possible = False
except:
self._logger.exception("Could not check %s for updates" % target)
update_possible = False
else:
try:
updater = self._get_updater(target, check)
update_possible = updater.can_perform_update(target, check)
except:
update_possible = False
self._version_cache[target] = (time.time(), information, update_available, update_possible)
self._version_cache_dirty = True
return information, update_available, update_possible
def _send_client_message(self, message_type, data=None):
self._plugin_manager.send_plugin_message("softwareupdate", dict(type=message_type, data=data))
def perform_updates(self, check_targets=None, force=False):
"""
Performs the updates for the given check_targets. Will update all possible targets by default.
:param check_targets: an iterable defining the targets to update, if not supplied defaults to all targets
"""
checks = self._get_configured_checks()
if check_targets is None:
check_targets = checks.keys()
to_be_updated = sorted(set(check_targets) & set(checks.keys()))
if "octoprint" in to_be_updated:
to_be_updated.remove("octoprint")
tmp = ["octoprint"] + to_be_updated
to_be_updated = tmp
updater_thread = threading.Thread(target=self._update_worker, args=(checks, to_be_updated, force))
updater_thread.daemon = False
updater_thread.start()
return to_be_updated, dict((key, check["displayName"] if "displayName" in check else key) for key, check in checks.items() if key in to_be_updated)
def _update_worker(self, checks, check_targets, force):
restart_type = None
try:
self._update_in_progress = True
target_results = dict()
error = False
### iterate over all configured targets
for target in check_targets:
if not target in checks:
continue
check = checks[target]
if "enabled" in check and not check["enabled"]:
continue
if not target in check_targets:
continue
target_error, target_result = self._perform_update(target, check, force)
error = error or target_error
if target_result is not None:
target_results[target] = target_result
if "restart" in check:
target_restart_type = check["restart"]
elif "pip" in check:
target_restart_type = "octoprint"
# if our update requires a restart we have to determine which type
if restart_type is None or (restart_type == "octoprint" and target_restart_type == "environment"):
restart_type = target_restart_type
finally:
# we might have needed to update the config, so we'll save that now
self._settings.save()
# also, we are now longer updating
self._update_in_progress = False
if error:
# if there was an unignorable error, we just return error
self._send_client_message("error", dict(results=target_results))
else:
self._save_version_cache()
# otherwise the update process was a success, but we might still have to restart
if restart_type is not None and restart_type in ("octoprint", "environment"):
# one of our updates requires a restart of either type "octoprint" or "environment". Let's see if
# we can actually perform that
restart_command = self._settings.get(["%s_restart_command" % restart_type])
if restart_command is not None:
self._send_client_message("restarting", dict(restart_type=restart_type, results=target_results))
try:
self._perform_restart(restart_command)
except exceptions.RestartFailed:
self._send_client_message("restart_failed", dict(restart_type=restart_type, results=target_results))
else:
# we don't have this restart type configured, we'll have to display a message that a manual
# restart is needed
self._send_client_message("restart_manually", dict(restart_type=restart_type, results=target_results))
else:
self._send_client_message("success", dict(results=target_results))
def _perform_update(self, target, check, force):
information, update_available, update_possible = self._get_current_version(target, check)
if not update_available and not force:
return False, None
if not update_possible:
self._logger.warn("Cannot perform update for %s, update type is not fully configured" % target)
return False, None
# determine the target version to update to
target_version = information["remote"]["value"]
target_error = False
### The actual update procedure starts here...
try:
self._logger.info("Starting update of %s to %s..." % (target, target_version))
self._send_client_message("updating", dict(target=target, version=target_version))
updater = self._get_updater(target, check)
if updater is None:
raise exceptions.UnknownUpdateType()
update_result = updater.perform_update(target, check, target_version)
target_result = ("success", update_result)
self._logger.info("Update of %s to %s successful!" % (target, target_version))
except exceptions.UnknownUpdateType:
self._logger.warn("Update of %s can not be performed, unknown update type" % target)
self._send_client_message("update_failed", dict(target=target, version=target_version, reason="Unknown update type"))
return False, None
except Exception as e:
self._logger.exception("Update of %s can not be performed" % target)
if not "ignorable" in check or not check["ignorable"]:
target_error = True
if isinstance(e, exceptions.UpdateError):
target_result = ("failed", e.data)
self._send_client_message("update_failed", dict(target=target, version=target_version, reason=e.data))
else:
target_result = ("failed", None)
self._send_client_message("update_failed", dict(target=target, version=target_version, reason="unknown"))
else:
# make sure that any external changes to config.yaml are loaded into the system
self._settings.load()
# persist the new version if necessary for check type
if check["type"] == "github_commit":
dummy_default = dict(plugins=dict())
dummy_default["plugins"][self._identifier] = dict(checks=dict())
dummy_default["plugins"][self._identifier]["checks"][target] = dict(current=None)
self._settings.set(["checks", target, "current"], target_version, defaults=dummy_default)
# we have to save here (even though that makes us save quite often) since otherwise the next
# load will overwrite our changes we just made
self._settings.save()
del self._version_cache[target]
self._version_cache_dirty = True
return target_error, target_result
def _perform_restart(self, restart_command):
"""
Performs a restart using the supplied restart_command.
"""
self._logger.info("Restarting...")
try:
util.execute(restart_command)
except exceptions.ScriptError as e:
self._logger.exception("Error while restarting")
self._logger.warn("Restart stdout:\n%s" % e.stdout)
self._logger.warn("Restart stderr:\n%s" % e.stderr)
raise exceptions.RestartFailed()
def _get_version_checker(self, target, check):
"""
Retrieves the version checker to use for given target and check configuration. Will raise an UnknownCheckType
if version checker cannot be determined.
"""
if not "type" in check:
raise exceptions.ConfigurationInvalid("no check type defined")
if target == "octoprint":
from octoprint._version import get_versions
from flask.ext.babel import gettext
check["displayName"] = gettext("OctoPrint")
check["displayVersion"] = "{octoprint_version}"
check["current"] = get_versions()["version"]
check_type = check["type"]
if check_type == "github_release":
return version_checks.github_release
elif check_type == "github_commit":
return version_checks.github_commit
elif check_type == "git_commit":
return version_checks.git_commit
elif check_type == "commandline":
return version_checks.commandline
elif check_type == "python_checker":
return version_checks.python_checker
else:
raise exceptions.UnknownCheckType()
def _get_updater(self, target, check):
"""
Retrieves the updater for the given target and check configuration. Will raise an UnknownUpdateType if updater
cannot be determined.
"""
if "update_script" in check:
return updaters.update_script
elif "pip" in check:
if not "pip_command" in check and self._settings.get(["pip_command"]) is not None:
check["pip_command"] = self._settings.get(["pip_command"])
return updaters.pip
elif "python_updater" in check:
return updaters.python_updater
else:
raise exceptions.UnknownUpdateType()
__plugin_name__ = "Software Update"
__plugin_author__ = "Gina Häußge"
__plugin_url__ = "https://github.com/foosel/OctoPrint/wiki/Plugin:-Software-Update"
__plugin_description__ = "Allows receiving update notifications and performing updates of OctoPrint and plugins"
__plugin_license__ = "AGPLv3"
def __plugin_load__():
global __plugin_implementation__
__plugin_implementation__ = SoftwareUpdatePlugin()
global __plugin_helpers__
__plugin_helpers__ = dict(
version_checks=version_checks,
updaters=updaters,
exceptions=exceptions,
util=util
)
@@ -1,37 +0,0 @@
# coding=utf-8
from __future__ import absolute_import
__author__ = "Gina Häußge <osd@foosel.net>"
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
class NoUpdateAvailable(Exception):
pass
class UpdateAlreadyInProgress(Exception):
pass
class UnknownUpdateType(Exception):
pass
class UnknownCheckType(Exception):
pass
class UpdateError(Exception):
def __init__(self, message, data):
self.message = message
self.data = data
class ScriptError(Exception):
def __init__(self, returncode, stdout, stderr):
self.returncode = returncode
self.stdout = stdout
self.stderr = stderr
class RestartFailed(Exception):
pass
class ConfigurationInvalid(Exception):
pass
@@ -1,180 +0,0 @@
#!/bin/env python
from __future__ import absolute_import
__author__ = "Gina Haeussge <osd@foosel.net>"
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
import errno
import subprocess
import sys
def _get_git_executables():
GITS = ["git"]
if sys.platform == "win32":
GITS = ["git.cmd", "git.exe"]
return GITS
def _git(args, cwd, hide_stderr=False, verbose=False, git_executable=None):
if git_executable is not None:
commands = [git_executable]
else:
commands = _get_git_executables()
for c in commands:
try:
p = subprocess.Popen([c] + args, cwd=cwd, stdout=subprocess.PIPE,
stderr=(subprocess.PIPE if hide_stderr
else None))
break
except EnvironmentError:
e = sys.exc_info()[1]
if e.errno == errno.ENOENT:
continue
if verbose:
print("unable to run %s" % args[0])
print(e)
return None, None
else:
if verbose:
print("unable to find command, tried %s" % (commands,))
return None, None
stdout = p.communicate()[0].strip()
if sys.version >= '3':
stdout = stdout.decode()
if p.returncode != 0:
if verbose:
print("unable to run %s (error)" % args[0])
return p.returncode, stdout
def _python(args, cwd, python_executable, sudo=False):
command = [python_executable] + args
if sudo:
command = ["sudo"] + command
try:
p = subprocess.Popen(command, cwd=cwd, stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
except:
return None, None
stdout = p.communicate()[0].strip()
if sys.version >= "3":
stdout = stdout.decode()
return p.returncode, stdout
def update_source(git_executable, folder, target, force=False):
print(">>> Running: git diff --shortstat")
returncode, stdout = _git(["diff", "--shortstat"], folder, git_executable=git_executable)
if returncode != 0:
raise RuntimeError("Could not update, \"git diff\" failed with returncode %d: %s" % (returncode, stdout))
if stdout and stdout.strip():
# we got changes in the working tree, maybe from the user, so we'll now rescue those into a patch
import time
import os
timestamp = time.strftime("%Y%m%d%H%M")
patch = os.path.join(folder, "%s-preupdate.patch" % timestamp)
print(">>> Running: git diff and saving output to %s" % timestamp)
returncode, stdout = _git(["diff"], folder, git_executable=git_executable)
if returncode != 0:
raise RuntimeError("Could not update, installation directory was dirty and state could not be persisted as a patch to %s" % patch)
with open(patch, "wb") as f:
f.write(stdout)
print(">>> Running: git reset --hard")
returncode, stdout = _git(["reset", "--hard"], folder, git_executable=git_executable)
if returncode != 0:
raise RuntimeError("Could not update, \"git reset --hard\" failed with returncode %d: %s" % (returncode, stdout))
print(">>> Running: git pull")
returncode, stdout = _git(["pull"], folder, git_executable=git_executable)
if returncode != 0:
raise RuntimeError("Could not update, \"git pull\" failed with returncode %d: %s" % (returncode, stdout))
print(stdout)
if force:
reset_command = ["reset"]
reset_command += [target]
print(">>> Running: git %s" % " ".join(reset_command))
returncode, stdout = _git(reset_command, folder, git_executable=git_executable)
if returncode != 0:
raise RuntimeError("Error while updating, \"git %s\" failed with returncode %d: %s" % (" ".join(reset_command), returncode, stdout))
print(stdout)
def install_source(python_executable, folder, user=False, sudo=False):
print(">>> Running: python setup.py clean")
returncode, stdout = _python(["setup.py", "clean"], folder, python_executable)
if returncode != 0:
print("\"python setup.py clean\" failed with returncode %d: %s" % (returncode, stdout))
print("Continuing anyways")
print(stdout)
print(">>> Running: python setup.py install")
args = ["setup.py", "install"]
if user:
args.append("--user")
returncode, stdout = _python(args, folder, python_executable, sudo=sudo)
if returncode != 0:
raise RuntimeError("Could not update, \"python setup.py install\" failed with returncode %d: %s" % (returncode, stdout))
print(stdout)
def parse_arguments():
import argparse
parser = argparse.ArgumentParser(prog="update-octoprint.py")
parser.add_argument("--git", action="store", type=str, dest="git_executable",
help="Specify git executable to use")
parser.add_argument("--python", action="store", type=str, dest="python_executable",
help="Specify python executable to use")
parser.add_argument("--force", action="store_true", dest="force",
help="Set this to force the update to only the specified version (nothing newer)")
parser.add_argument("--sudo", action="store_true", dest="sudo",
help="Install with sudo")
parser.add_argument("--user", action="store_true", dest="user",
help="Install to the user site directory instead of the general site directory")
parser.add_argument("folder", type=str,
help="Specify the base folder of the OctoPrint installation to update")
parser.add_argument("target", type=str,
help="Specify the commit or tag to which to update")
args = parser.parse_args()
return args
def main():
args = parse_arguments()
git_executable = None
if args.git_executable:
git_executable = args.git_executable
python_executable = sys.executable
if args.python_executable:
python_executable = args.python_executable
folder = args.folder
target = args.target
import os
if not os.access(folder, os.W_OK):
raise RuntimeError("Could not update, base folder is not writable")
update_source(git_executable, folder, target, force=args.force)
install_source(python_executable, folder, user=args.user, sudo=args.sudo)
if __name__ == "__main__":
main()
@@ -1 +0,0 @@
td.settings_plugin_softwareupdate_column_update{width:16px}
@@ -1,451 +0,0 @@
$(function() {
function SoftwareUpdateViewModel(parameters) {
var self = this;
self.loginState = parameters[0];
self.printerState = parameters[1];
self.settings = parameters[2];
self.popup = undefined;
self.updateInProgress = false;
self.waitingForRestart = false;
self.restartTimeout = undefined;
self.currentlyBeingUpdated = [];
self.config_restartCommand = ko.observable();
self.config_rebootCommand = ko.observable();
self.config_cacheTtl = ko.observable();
self.configurationDialog = $("#settings_plugin_softwareupdate_configurationdialog");
self.versions = new ItemListHelper(
"plugin.softwareupdate.versions",
{
"name": function(a, b) {
// sorts ascending, puts octoprint first
if (a.key.toLocaleLowerCase() == "octoprint") return -1;
if (b.key.toLocaleLowerCase() == "octoprint") return 1;
if (a.displayName.toLocaleLowerCase() < b.displayName.toLocaleLowerCase()) return -1;
if (a.displayName.toLocaleLowerCase() > b.displayName.toLocaleLowerCase()) return 1;
return 0;
}
},
{},
"name",
[],
[],
5
);
self.onUserLoggedIn = function() {
self.performCheck();
};
self._showPopup = function(options, eventListeners) {
self._closePopup();
self.popup = new PNotify(options);
if (eventListeners) {
var popupObj = self.popup.get();
_.each(eventListeners, function(value, key) {
popupObj.on(key, value);
})
}
};
self._updatePopup = function(options) {
if (self.popup === undefined) {
self._showPopup(options);
} else {
self.popup.update(options);
}
};
self._closePopup = function() {
if (self.popup !== undefined) {
self.popup.remove();
}
};
self.showPluginSettings = function() {
self._copyConfig();
self.configurationDialog.modal();
};
self.savePluginSettings = function() {
var data = {
plugins: {
softwareupdate: {
octoprint_restart_command: self.config_restartCommand(),
environment_restart_command: self.config_rebootCommand(),
cache_ttl: parseInt(self.config_cacheTtl())
}
}
};
self.settings.saveData(data, function() { self.configurationDialog.modal("hide"); self._copyConfig(); });
};
self._copyConfig = function() {
self.config_restartCommand(self.settings.settings.plugins.softwareupdate.octoprint_restart_command());
self.config_rebootCommand(self.settings.settings.plugins.softwareupdate.environment_restart_command());
self.config_cacheTtl(self.settings.settings.plugins.softwareupdate.cache_ttl());
};
self.fromCheckResponse = function(data, ignoreSeen, showIfNothingNew) {
var versions = [];
_.each(data.information, function(value, key) {
value["key"] = key;
if (!value.hasOwnProperty("displayName") || value.displayName == "") {
value.displayName = value.key;
}
if (!value.hasOwnProperty("displayVersion") || value.displayVersion == "") {
value.displayVersion = value.information.local.name;
}
versions.push(value);
});
self.versions.updateItems(versions);
if (data.status == "updateAvailable" || data.status == "updatePossible") {
var text = gettext("There are updates available for the following components:");
text += "<ul>";
_.each(self.versions.items(), function(update_info) {
if (update_info.updateAvailable) {
var displayName = update_info.key;
if (update_info.hasOwnProperty("displayName")) {
displayName = update_info.displayName;
}
text += "<li>" + displayName + (update_info.updatePossible ? " <i class=\"icon-ok\"></i>" : "") + "</li>";
}
});
text += "</ul>";
text += "<small>" + gettext("Those components marked with <i class=\"icon-ok\"></i> can be updated directly.") + "</small>";
var options = {
title: gettext("Update Available"),
text: text,
hide: false
};
var eventListeners = {};
if (data.status == "updatePossible" && self.loginState.isAdmin()) {
// if user is admin, add action buttons
options["confirm"] = {
confirm: true,
buttons: [{
text: gettext("Ignore"),
click: function() {
self._markNotificationAsSeen(data.information);
self._showPopup({
text: gettext("You can make this message display again via \"Settings\" > \"SoftwareUpdate\" > \"Check for update now\"")
});
}
}, {
text: gettext("Update now"),
addClass: "btn-primary",
click: self.update
}]
};
options["buttons"] = {
closer: false,
sticker: false
};
}
if (ignoreSeen || !self._hasNotificationBeenSeen(data.information)) {
self._showPopup(options, eventListeners);
}
} else if (data.status == "current") {
if (showIfNothingNew) {
self._showPopup({
title: gettext("Everything is up-to-date"),
hide: false,
type: "success"
});
} else {
self._closePopup();
}
}
};
self.performCheck = function(showIfNothingNew, force, ignoreSeen) {
if (!self.loginState.isUser()) return;
var url = PLUGIN_BASEURL + "softwareupdate/check";
if (force) {
url += "?force=true";
}
$.ajax({
url: url,
type: "GET",
dataType: "json",
success: function(data) {
self.fromCheckResponse(data, ignoreSeen, showIfNothingNew);
}
});
};
self._markNotificationAsSeen = function(data) {
if (!Modernizr.localstorage)
return false;
localStorage["plugin.softwareupdate.seen_information"] = JSON.stringify(self._informationToRemoteVersions(data));
};
self._hasNotificationBeenSeen = function(data) {
if (!Modernizr.localstorage)
return false;
if (localStorage["plugin.softwareupdate.seen_information"] == undefined)
return false;
var knownData = JSON.parse(localStorage["plugin.softwareupdate.seen_information"]);
var freshData = self._informationToRemoteVersions(data);
var hasBeenSeen = true;
_.each(freshData, function(value, key) {
if (!_.has(knownData, key) || knownData[key] != freshData[key]) {
hasBeenSeen = false;
}
});
return hasBeenSeen;
};
self._informationToRemoteVersions = function(data) {
var result = {};
_.each(data, function(value, key) {
result[key] = value.information.remote.value;
});
return result;
};
self.performUpdate = function(force) {
self.updateInProgress = true;
var options = {
title: gettext("Updating..."),
text: gettext("Now updating, please wait."),
icon: "icon-cog icon-spin",
hide: false,
buttons: {
closer: false,
sticker: false
}
};
self._showPopup(options);
$.ajax({
url: PLUGIN_BASEURL + "softwareupdate/update",
type: "POST",
dataType: "json",
contentType: "application/json; charset=UTF-8",
data: JSON.stringify({force: (force == true)}),
error: function() {
self.updateInProgress = false;
self._showPopup({
title: gettext("Update not started!"),
text: gettext("The update could not be started. Is it already active? Please consult the log for details."),
type: "error",
hide: false,
buttons: {
sticker: false
}
});
},
success: function(data) {
self.currentlyBeingUpdated = data.checks;
}
});
};
self.update = function(force) {
if (self.updateInProgress) return;
if (!self.loginState.isAdmin()) return;
force = (force == true);
if (self.printerState.isPrinting()) {
self._showPopup({
title: gettext("Can't update while printing"),
text: gettext("A print job is currently in progress. Updating will be prevented until it is done."),
type: "error"
});
} else {
$("#confirmation_dialog .confirmation_dialog_message").text(gettext("This will update your OctoPrint installation and restart the server."));
$("#confirmation_dialog .confirmation_dialog_acknowledge").unbind("click");
$("#confirmation_dialog .confirmation_dialog_acknowledge").click(function(e) {
e.preventDefault();
$("#confirmation_dialog").modal("hide");
self.performUpdate(force);
});
$("#confirmation_dialog").modal("show");
}
};
self.onServerDisconnect = function() {
if (self.restartTimeout !== undefined) {
clearTimeout(self.restartTimeout);
}
return true;
};
self.onDataUpdaterReconnect = function() {
if (self.waitingForRestart) {
self.waitingForRestart = false;
var options = {
title: gettext("Restart successful!"),
text: gettext("The server was restarted successfully. The page will now reload automatically."),
type: "success",
hide: false
};
self._showPopup(options);
self.updateInProgress = false;
var delay = 5 + Math.floor(Math.random() * 5) + 1;
setTimeout(function() {location.reload(true);}, delay * 1000);
}
};
self.onDataUpdaterPluginMessage = function(plugin, data) {
if (plugin != "softwareupdate") {
return;
}
var messageType = data.type;
var messageData = data.data;
var options = undefined;
switch (messageType) {
case "updating": {
console.log(JSON.stringify(messageData));
var name = self.currentlyBeingUpdated[messageData.target];
if (name == undefined) {
name = messageData.target;
}
self._updatePopup({
text: _.sprintf(gettext("Now updating %(name)s to %(version)s"), {name: name, version: messageData.version})
});
break;
}
case "restarting": {
console.log(JSON.stringify(messageData));
options = {
title: gettext("Update successful, restarting!"),
text: gettext("The update finished successfully and the server will now be restarted."),
type: "success",
hide: false,
buttons: {
sticker: false
}
};
self.waitingForRestart = true;
self.restartTimeout = setTimeout(function() {
self._showPopup({
title: gettext("Restart failed"),
text: gettext("The server apparently did not restart by itself, you'll have to do it manually. Please consult the log file on what went wrong."),
type: "error",
hide: false,
buttons: {
sticker: false
}
});
self.waitingForRestart = false;
}, 20000);
break;
}
case "restart_manually": {
console.log(JSON.stringify(messageData));
var restartType = messageData.restart_type;
var text = gettext("The update finished successfully, please restart OctoPrint now.");
if (restartType == "environment") {
text = gettext("The update finished successfully, please reboot the server now.");
}
options = {
title: gettext("Update successful, restart required!"),
text: text,
type: "success",
hide: false,
buttons: {
sticker: false
}
};
self.updateInProgress = false;
break;
}
case "restart_failed": {
var restartType = messageData.restart_type;
var text = gettext("Restarting OctoPrint failed, please restart it manually. You might also want to consult the log file on what went wrong here.");
if (restartType == "environment") {
text = gettext("Rebooting the server failed, please reboot it manually. You might also want to consult the log file on what went wrong here.");
}
options = {
title: gettext("Restart failed"),
test: gettext("The server apparently did not restart by itself, you'll have to do it manually. Please consult the log file on what went wrong."),
type: "error",
hide: false,
buttons: {
sticker: false
}
};
self.waitingForRestart = false;
self.updateInProgress = false;
break;
}
case "success": {
options = {
title: gettext("Update successful!"),
text: gettext("The update finished successfully."),
type: "success",
hide: false,
buttons: {
sticker: false
}
};
self.updateInProgress = false;
break;
}
case "error": {
self._showPopup({
title: gettext("Update failed!"),
text: gettext("The update did not finish successfully. Please consult the log for details."),
type: "error",
hide: false,
buttons: {
sticker: false
}
});
self.updateInProgress = false;
break;
}
case "update_versions": {
self.performCheck();
break;
}
}
if (options != undefined) {
self._showPopup(options);
}
};
}
// view model class, parameters for constructor, container to bind to
ADDITIONAL_VIEWMODELS.push([SoftwareUpdateViewModel, ["loginStateViewModel", "printerStateViewModel", "settingsViewModel"], document.getElementById("settings_plugin_softwareupdate")]);
});
Loaded 100 of 270 files, more files were not shown because too many files have changed in this diff. Show more