Compare commits

...
106 Commits
Author SHA1 Message Date
Gina Häußge 0a69dbeddb Preparing release of 1.3.2 2017-03-16 13:08:31 +01:00
Gina Häußge 1c132c39ad Preparing release of 1.3.2rc1 2017-03-10 14:35:11 +01:00
Gina Häußge 7114462024 Fixed python setup.py babel_compile 2017-03-10 14:24:49 +01:00
Gina Häußge 11b96005a9 And some more rewording in CONTRIBUTING.md 2017-03-10 14:00:31 +01:00
Gina Häußge fea6b5096c Some more rewording in the README 2017-03-10 13:53:35 +01:00
Gina Häußge 40e2fa6bf4 Updated README to include safe mode, version badge & some rewording 2017-03-10 13:52:18 +01:00
Gina Häußge 3006bde972 octoprint --safe -> octoprint serve --safe 2017-03-10 13:51:44 +01:00
Gina Häußge c7ae580c54 Updated PR template for whitelisted maintenance branch 2017-03-10 13:35:10 +01:00
Gina Häußge 55762ee71a Documentation updated for safe mode feature 2017-03-10 13:34:55 +01:00
Gina Häußge ebae1b475b Don't apply navbar gradient to dropdown entries 2017-03-10 12:49:21 +01:00
Gina Häußge 61fbde4e51 Manual test plugin for parts of the update mechanism 2017-03-10 12:01:09 +01:00
Gina Häußge 6e793c2ba3 Don't mark "can't clean" messages from setup.py clean as error
Might confuse users to see that marked up like an error when it's
perfectly normal for some kinds of installs simply because the
specific build folders never were created in the first place.
2017-03-10 11:36:49 +01:00
Gina Häußge b38884db63 Removed an obsolete (and broken) method from PipCaller 2017-03-10 11:20:13 +01:00
Gina Häußge a49772fcf3 Removed bits from clean command made redundant by #732
Force --all on stock clean command unless --orig is specified, in
which case "python setup.py clean" behaves like the stock clean
command. Additionally there are now --noeggs to skip egg deletion and
--nopyc to skip pyc deletion.
2017-03-09 18:41:55 +01:00
Gina Häußge 052796d5d2 Merge branch 'feature/inherit-clean' of https://github.com/DanLipsitt/OctoPrint into improve/cleanCommand 2017-03-09 18:40:50 +01:00
Gina Häußge 559238ca3c More solid parsing of line number from resends
Matches:

  * Resend:23
  * Resend:N23
  * Resend:N:23
  * rs 23
  * rs N23
  * rs N:23
  * rs N23 Expected checksum 109

Based on issue reported via PR #300
2017-03-09 17:08:01 +01:00
Gina Häußge fa16037e9a Unit test for M115 response parsing 2017-03-09 16:39:16 +01:00
Gina Häußge d298c3c672 Apply analysis throttle only every n lines
Default n = 100, configurable via config.yaml. Should make analysis a
bit faster while still giving the Pi air to breathe.
2017-03-09 15:38:52 +01:00
Gina Häußge d7b29a8725 Added @kantlivelong to AUTHORS.md 2017-03-09 15:36:26 +01:00
Gina Häußge 136736d307 Reset line numbers if printer sends "start" when operational
Might have been an external reset of the printer we didn't otherwise
detect, and unless we reset the line numbers we'll now be off and run
into resend requests.

Solves #1676
2017-03-09 14:35:07 +01:00
Shawn Bruce 5d1a0eaa16 Only reset scroll position for settings content. (Fixes #1812)
(cherry picked from commit 5c81833)
2017-03-09 11:57:08 +01:00
Gina Häußge 2d9c16e859 Allow PRs against maintenance for bug fixes 2017-03-09 11:49:55 +01:00
Andy Werner 8a4934e6f8 Fix an issue in user settings
* UserSettings: crashed if overwrite an existing key with primitive value by same key with complex value. Also reduced number of calls to user.get_setting()

* Updated tests

(cherry picked from commit b75b53d)
2017-03-08 18:11:36 +01:00
Gina Häußge a0e5f79483 Only load file into GCODE viewer when that is actually visible
Reduces needed bandwidth on page load, might help to mitigate
bandwidth related issues described in #1241.
2017-03-08 18:03:16 +01:00
Gina Häußge ef6159cc96 Applied text changes proposed by @seigel in #1735 2017-03-06 15:51:14 +01:00
Gina Häußge ab42cc2a7f Better error resilience against garbage history data from plugins
See #1805
2017-03-06 15:32:30 +01:00
Gina Häußge 01cffafe77 Fixed documentation of printer profile API
Closes #1732
2017-03-06 14:36:43 +01:00
Gina Häußge d8f2630fd4 Don't call onUserLoggedIn/Out on user reload 2017-03-06 14:11:41 +01:00
Gina Häußge 811c91955c Fix for new user settings getting lost until restart
On reload of the user settings a new user object was created but not
updated on the associated session user(s). That let to session user
(s) still referring to the old user instances with the only partially
updated user settings.

Behaviour changed such that on a reload of the users from file
(including user settings) all registered session users will now get
their reference updated as well.

Also made modelling of user id to session id a bit less redundant.
2017-03-06 14:02:39 +01:00
Gina Häußge 01ebf8fba7 Fix for two timing sensitive unit tests 2017-03-06 11:54:03 +01:00
Gina Häußge 2dcd6e02b1 Remove webapp headers to play nice with Safari's session handling
Solves #1792
2017-03-06 11:37:00 +01:00
Gina Häußge d845257cf4 Fixed caching of main page
Got broken by 62890ef73a
2017-03-01 18:28:37 +01:00
Gina Häußge c765e6e228 Revert "Only do lookup by userid if session is None"
This reverts commit f02fac20ed.

The commit turned out to nuke the "remember me" functionality.
2017-03-01 15:49:19 +01:00
Gina Häußge 20e1219d9e Virtual printer: configurable ok format 2017-03-01 15:48:36 +01:00
Gina Häußge 14120f732b Only check if we need to close login dropdown if it's open 2017-02-28 10:00:51 +01:00
Gina Häußge b7e2b0f794 Fixed login dropdown not auto closing on click outside of it
When two wrongs make one right...
2017-02-28 09:54:36 +01:00
Gina Häußge f02fac20ed Only do lookup by userid if session is None 2017-02-27 15:51:24 +01:00
Gina Häußge 755bcaa311 Add current path to "Back" button in file list
Closes #1712
2017-02-24 15:05:26 +01:00
Gina Häußge aab98a7c9f Disable "Slice" button when printing and local slicer is selected
Solves #1631
2017-02-24 13:21:33 +01:00
Gina Häußge 3a984d41ff Remove color option in printer profile editor
We don't use it anywhere and its presence keeps confusing users. Kept
in the model since we might want to use it at some later time.

Closes #1790
2017-02-24 12:38:37 +01:00
Gina Häußge 28d01e2fa6 Disable external heatup detection until firmware is detected 2017-02-24 12:32:05 +01:00
Gina Häußge 2198add8e6 SWU: Refresh cache on startup & prevent concurrent refresh & fix hash 2017-02-24 11:56:02 +01:00
Gina Häußge 1de307e15d Log version, safe mode & plugins to log on log roll over
We want to make sure that information is ALWAYS in each and every log.
2017-02-24 10:53:16 +01:00
Gina Häußge aab7b7f797 Timelapse: ignore both z-hop flanks but allow z-hop to next layer
Former implementation tested for z-hop rising flank and anything that
is falling. That however causes issues with z-hop directly followed
by layer change (diff is not z-hop size but negative, image hence not
captured).

Instead of testing for positive flank == z-hop and any negative flank,
we now test for absolute value == z-hop.

Solves #1777
2017-02-23 17:17:38 +01:00
Gina Häußge 162e8c50d3 Fixed CSS and LESS bundling for core vs plugins vs all 2017-02-23 17:05:42 +01:00
Gina Häußge 636d8e0faa Eventhandling: Wait for command to finish before triggering next
Should solve #733
2017-02-23 16:50:04 +01:00
Gina Häußge 62890ef73a Fix a bunch of caching issues
Cache was not invalidated on change of:

  * snapshot URL presence
  * system menu entry presence
  * gcode viewer enabled/disabled
  * changes in access control availability

Refactored cache setup to add enable_timelapse, enable_gcodeviewer
and enable_accesscontrol to ETag calculation, removed system menu
check. Template filtering will now be done based on the values of
these flags at render time, not before.

See also #1776 for a related ticket.
2017-02-23 14:49:47 +01:00
Gina Häußge 79af90dd6a Make sure we don't try to use an empty logging.yaml
Fixes #1560
2017-02-22 18:25:12 +01:00
Gina Häußge d15262e7cc Fixed wrong replacement for __progress placeholder in events
Data reported from printer backend is already percent, multiplying it
with 100 again produces wrong values.
2017-02-22 17:58:21 +01:00
Gina Häußge 41f0ed0124 Move announcements between system and login 2017-02-22 15:20:07 +01:00
Gina Häußge ff595a7e31 Move notifications down a bit
See discussion in #1741
2017-02-22 15:19:04 +01:00
Gina Häußge 444312d7d9 Free up some space in the navbar
* Use only icons for settings and system entries
  * Limit length of login entry to 100px
  * Limit length of instance name to 250px
  * Removed "OctoPrint" text if instance name is set

See discussion in #1741
2017-02-22 15:17:39 +01:00
Gina Häußge c3740dd59d Added development dependencies to THIRDPARTYLICENSES 2017-02-21 17:14:39 +01:00
Gina Häußge c203d79434 Remove empty-folder-filter
Doesn't really add anything and only causes issues for people.

Solves #1671
2017-02-21 17:06:26 +01:00
Gina Häußge 6dce2bc250 Added missing entries to THIRDPARTYLICENSES.md 2017-02-21 17:02:05 +01:00
Gina Häußge cad66fcea7 Added @ghulands to AUTHORS.md 2017-02-21 16:55:17 +01:00
Gina Häußge ed46d9967a Adjusted docs of slicing API to match implementation
Follow-up to PR #1748
2017-02-21 14:17:14 +01:00
Eyal Soha 6aae0017c4 add sameDevice to SlicingViewModel
(cherry picked from commit fea0791)
2017-02-21 14:15:02 +01:00
Eyal Soha ebe93f9a6d add same device to the slicing API
(cherry picked from commit ce38ef6)
2017-02-21 14:14:54 +01:00
Greg Hulands a16680b453 Issue #1780: Safari Webcam Fix.
(cherry picked from commit e82efd2)
2017-02-21 14:13:26 +01:00
Gina Häußge 9f963696c8 Interpret wait during connect fully as ok
Otherwise we might switch to connected state but lack an
acknowledgement to send the next lines and stay in a wait cycle.

Also related to #1770
2017-02-20 12:44:42 +01:00
Gina Häußge 7f0eb8d895 Hex-escape unprintable characters in terminal tab
If there's any binary going over the line like null bytes, we want to
see that here too.
2017-02-20 12:05:38 +01:00
Gina Häußge e1eaf4eb8e comm: More resilience against garbage on the line during connect
* leading and trailing null bytes will now be stripped
  * while connecting, a "wait" will also trigger switch to connected
    state - relevant when connecting without reset and initial "ok" for
    M110 gets mangled
  * extended virtual printer by new options to test the above:
      * mangled "ok" can now be injected via "preparedOks" setting and
        prepare_ok DEBUG command
      * simulated reset lines on beginning ("start" etc) now only sent
        if new setting "simulateReset" is true

Should fix #1770
2017-02-20 11:57:47 +01:00
Gina Häußge b8cbe02b7a Fixed docs for config.yaml and settings 2017-02-17 13:52:16 +01:00
Gina Häußge 4cc410133b Fixed description of a setting 2017-02-17 13:52:16 +01:00
Gina Häußge 216f05d553 Hibernate communication with printer during active G4 on Repetier
Should hopefully solve #1506
2017-02-17 13:52:16 +01:00
Gina Häußge 7beabf953c Fixed user unit tests 2017-02-17 13:43:47 +01:00
Gina Häußge b7c078f429 Fixed size checking in watchdog growth check
It helps to actually update the last checked file size on each
iteration 🤦‍♀️

Related to #1760
2017-02-17 13:05:23 +01:00
Gina Häußge 7331bc2bf5 Ensure file from watched folder is stable in size before upload
Additional fix for #1760
2017-02-16 19:30:58 +01:00
Gina Häußge 59f49f392e Refactored upload/watched to use file check methods in PrinterInterface
Extracted methods to check if modification of a file is possible and
to determine if a specific file is currently select to take care of
denying upload and re-selecting file after upload.

Refactored watched folder handler to use the same methods and mirror
behaviour of file upload via API.

Should solve #1760
2017-02-16 19:29:21 +01:00
Gina Häußge 997e0b510b Abort file analysis if file is about to be overwritten 2017-02-16 16:52:30 +01:00
Gina Häußge 1f9b8f40cd Enqueue copied/moved files/folders for analysis
Fixes #1775
2017-02-15 17:35:42 +01:00
Gina Häußge 8630ec5beb Fix some bugs in the client lib refactoring
* Endless recursion on file delete as reported in #1738
  * Broken implementation of .move
  * Broken definition of .pathForEntry, .entryForPath,
    .pathForElement and .elementByPath
2017-02-15 16:15:35 +01:00
Gina Häußge e8349d6593 Always create a user session for requests with an API key
API endpoints that were not decorated with restricted_access so far did
not properly create a user session for cookie-less requests with an API
key only.

That meant that flask.current_user stayed an anonymous user, even with
the global admin API key. In case of /api/settings that meant that even
with the global admin API key it was not possible to read settings that
are admin-only (like the API key for example) or user-only.

This has now been rectified by moving the session creation into a
different before_request handler that is registered globally on all API
endpoints, meaning that an API key will now always lead to a user
session to be created, regardless of the requirements of the API
endpoint in question. Additionally the CORS handling was extracted
as well as the API key presence enforcement.

BlueprintPlugins will now also get the CORS and session-from-API-Key
treatment if they do not declare their endpoints as restricted.

Might solve the API key "n/a" issue filed in #1751, but since the cause
of that isn't identified yet that's not sure.
2017-02-15 13:12:35 +01:00
Gina Häußge 9b457cce9e Fixed user settings API 2017-02-15 11:38:33 +01:00
Gina Häußge b2229ae24a SWU: Ignore empty or None configs 2017-02-14 15:03:20 +01:00
Gina Häußge 189c842881 dict_merge should not hiccup on None values 2017-02-14 15:02:33 +01:00
Gina Häußge 6963e5e495 SWU: We need to do that overwrite protection differently
Only replace data from config.yaml with merged results once everything
trying to overwrite stuff is filtered out.
2017-02-14 12:52:07 +01:00
Gina Häußge 7b6642f7c2 SWU: Better resilience against overwriting of update configs
Don't allow overwriting of "octoprint" config through plugins, don't
allow overwriting of already registered configs unless id to register
matches plugin identifier (in which case the already registered config
was probably a case of a copy-paste-error from another plugin).
2017-02-14 11:14:03 +01:00
Gina Häußge 5d97dc4b40 Better resilience against broken software update configs
Fixes #1773
2017-02-14 10:42:02 +01:00
Paul de Vries b453897ea3 Upgrade LESS.min.js from 2.7.1 to 2.7.2
This will fix the broken contrast function introduced in 2.7.1

This commit will only affect the contrast function
See more @ https://github.com/less/less.js/compare/v2.7.1...v2.7.2#diff-8c2e50ef84a06711745a46e22c67d631
2017-02-05 14:45:10 +01:00
Gina Häußge 54a9a7b906 Use codecs.open for translation po files 2017-01-26 17:22:51 +01:00
Gina Häußge a3f24c59e9 Don't render untranslated strings to messages.js 2017-01-26 17:22:07 +01:00
Gina Häußge 42f4fad257 Fixed minor doc issue 2017-01-26 15:00:06 +01:00
Gina Häußge eaadf8743b Allow multiple instances of the JS client
We now have a global OctoPrintClient, which is the class from which
all clients are derived, and a global OctoPrint, which is a single
instance already setup and ready to use in case we only need one.

It would be cleaner to have clients create that singular instance
themselves, but we need to maintain backward compatibility for now
with how we established the client to work with the 1.3.0 release.

New clients can be create with

    client = new OctoPrintClient({ /* options */ });

Alternatively the options can be left out and set at a later point:

    client = new OctoPrintClient();
    /* ... */
    client.options = { /* options */ };

Individual client components register themselves with OctoPrintClient
via OctoPrintClient.registerComponent(name, component) from the
component JS files. Just like before their instances are then
available in the individual client instances under "<client>.<name>",
 e.g. "OctoPrint.files".

Plugin components register themselves with OctoPrintClient via
OctoPrintClient.registerPluginComponent(name, component) from the
component JS files. Just like before their instances are then
available in the individual client instances under "<client>.plugins
.<name>", e.g. "OctoPrint.plugins.softwareupdate".

This should make it possible to create dashboard pages utilizing the
JS client that monitor the status of multiple OctoPrint instances,
without workarounds such as having to swap out the options globally
before each request.

See #1681 for the corresponding discussion.
2017-01-26 14:59:56 +01:00
Gina Häußge b0cd742bf4 Fix UMD pattern 2017-01-26 14:59:54 +01:00
Gina Häußge 7ab3eabe0f Support for shared nozzle setups
Support multi-extruder setups that share a single nozzle and heater,
like the E3D Cyclops, Diamon hotend or probably the upcoming Prusa Mk2
multi-extruder upgrade.

The Control tab will still allow tool switching and extruding for
the configured extruders, the Temperature tab will only display
one hotend temperature though.

Printer profiles have been extended by a new option
extruder.sharedNozzle that defaults to False. Extruder offsets are
not displayed in the profile editor if that setting is checked and
reset to (0,0).
2017-01-26 13:33:42 +01:00
Gina Häußge 8f3b6dca79 Fix stupid typo 2017-01-25 16:21:15 +01:00
Gina Häußge 29a2c6abec Allow new locales to be provided by plugins
Core translations still win over plugin translations, but at least
this way it's possible to provide full blown translations via plugins.
2017-01-25 16:02:25 +01:00
Gina Häußge 9a464e01d8 Merge branch 'master' into maintenance 2017-01-25 12:53:49 +01:00
Gina Häußge 37966644aa Upped version numbers for branches 2017-01-25 12:50:50 +01:00
Gina Häußge 9250cd0c3b Whitespace, comments & added @eyal0 to AUTHORS.md
(cherry picked from commit c7f67cc)
2017-01-24 11:38:52 +01:00
Eyal Soha 6b2f28240e Ignore a leading v or V in github release tags.
This fixes foosel/OctoPrint#1723 .

(cherry picked from commit f1c3829)
2017-01-24 11:38:46 +01:00
Gina Häußge c8dfe363bc Only offer daemon subcommand on linux 2017-01-20 17:10:59 +01:00
Gina Häußge e20fcd9ce5 Merge branch 'rc/maintenance' into maintenance 2017-01-20 16:28:42 +01:00
Gina Häußge 88a8bdf7b3 Add "Restart in safe mode" system menu entry 2017-01-20 14:27:06 +01:00
Gina Häußge a948050c54 SWU: Fixed update configs without restart 2017-01-19 14:07:04 +01:00
Gina Häußge 0d76df2cd5 SWU: Fixed python_checker and python_updater 2017-01-19 14:06:33 +01:00
Gina Häußge 3b5c2fe519 SWU: Config version 4 didn't properly migrate old commands -> version 5 2017-01-19 12:33:45 +01:00
Gina Häußge 6f5ee4d291 Fixed doctests of software update version checks 2017-01-19 12:33:44 +01:00
Gina Häußge 507ddde9dd Improved error resilience in plugin repository handling 2017-01-19 12:33:43 +01:00
Gina Häußge a646fff5ff Fix persistence of config version on settings migration 2017-01-19 12:33:27 +01:00
Gina Häußge 6268e27dd7 Fix settings not allowing to delete values not in defaults anymore 2017-01-19 12:33:25 +01:00
Gina Häußge caa84d7918 Don't kill manual software update configs during migration
See lengthy comment in source added through this commit for details.
2017-01-19 12:11:01 +01:00
Gina Häußge 6bd788a83f Always define pixfmt for timelapse in video filter chain
Apparently having a chain AND the pix_fmt parameter
produces issues with higher resolutions.

Should fix #1317
2017-01-17 13:03:27 +01:00
Dan Lipsitt 4683fa3d25 Inherit clean command so that it supports the usual flags.
This changes the semantics of setup.py slightly. '--all' needs to be
passed in order to delete everything that is deleted by previous
versions. Some additional build files may also be deleted.
2015-01-16 16:22:34 -08:00
136 changed files with 6947 additions and 3590 deletions

No files matched your search

+24 -13
View File
@@ -15,10 +15,17 @@ for contributing" linked above, read it!), NOT here.
Mark requests with a "[Request]" prefix in the title please. Fully fill
out the bug reporting template for bug reports (if you don't know where
to find some information - it's all described in the contribution
guidelines linked up there in the big yellow box). Do not delete any
lines from the template but those enclosed in [ and ] - and those please
DO delete, they are only provided for your information and removing them
makes your ticket more readable :)
guidelines linked up there in the big yellow box).
When reporting a bug do NOT delete any lines from the template but
those enclosed in [ and ] - and those please DO delete, they are
only provided for your information and removing them makes your
ticket more readable :)
Make sure any bug you want to repor tis still present with the CURRENT
OctoPrint version and that it does not vanish when you start OctoPrint
in safe mode - how to do that is also explained in the contribution
guidelines linked up there in the big yellow box.
Thank you!
@@ -30,28 +37,31 @@ by heart ;))
#### What were you doing?
[Please be as specific as possible here. The maintainers will need to
reproduce your issue in order to fix it and that is not possible if they
don't know what you did to get it to happen in the first place.
[Please describe the steps to reproduce your issue. Be as specific as
possible here. The maintainers will need to reproduce your issue in
order to fix it and that is not possible if they don't know what you
did to get it to happen in the first place.
If you encountered a problem with specific files of any sorts, make sure
to also include a link to a file with which to reproduce the problem.]
#### What did you expect to happen?
#### What happened instead?
#### What did you expect to happen and what happened instead?
#### Branch & Commit or Version of OctoPrint
[Can be found in the lower left corner of the web interface. ALWAYS INCLUDE.]
#### Operating System running OctoPrint
[OctoPi, Linux, Windows, MacOS, something else? With version please.]
#### Printer model & used firmware incl. version
[If applicable, always include if unsure.]
#### Browser and Version of Browser, Operating System running Browser
[If applicable, always include if unsure.]
[If applicable, always include if unsure or reporting UI issues.]
#### Link to octoprint.log
@@ -60,7 +70,8 @@ to also include a link to a file with which to reproduce the problem.]
#### Link to contents of terminal tab or serial.log
[On gist.github.com or pastebin.com. If applicable, always include if unsure or
reporting communication issues. Never truncate.
reporting any kind of communication issues between OctoPrint and your printer.
Never truncate.
serial.log is usually not written due to performance reasons and must be
enabled explicitly. Provide at the very least the FULL contents of your
@@ -72,7 +83,7 @@ a serial.log.]
[On gist.github.com or pastebin.com or alternatively a screenshot. If applicable -
always include if unsure or reporting UI issues.]
#### Screenshot(s) showing the problem:
#### Screenshot(s) or video(s) showing the problem:
[If applicable. Always include if unsure or reporting UI issues.]
+4 -3
View File
@@ -14,14 +14,15 @@ checklist:
made sure your changes don't interfere with current development by
talking it through with the maintainers, e.g. through a
Brainstorming ticket
* [ ] Your PR targets OctoPrint's devel branch (not master,
maintenance or anything else)
* [ ] Your PR targets OctoPrint's devel branch, or maintenance if it's
a bug fix for an issue present in the current stable version (no PRs
against master or anything else)
* [ ] Your PR was opened from a custom branch on your repository
(no PRs from your version of master, maintenance or devel please),
e.g. dev/my_new_feature
* [ ] Your PR only contains relevant changes: no unrelated files,
no dead code, ideally only one commit - rebase your PR if necessary!
* [ ] Your changes follow the coding style
* [ ] Your changes follow the existing coding style
* [ ] If your changes include style sheets: You have modified the
.less source files, not the .css files (those are generated with
lessc)
+4 -4
View File
@@ -16,11 +16,11 @@ prerelease
HEAD
\(detached.*
# maintenance is currently the branch for preparation of maintenance release 1.3.1
# maintenance is currently the branch for preparation of maintenance release 1.3.2
# so are any fix/... and improve/... branches
maintenance 1.3.1 7f5d03d0549bcbd26f40e7e4a3297ea5204fb1cc pep440-dev
fix/.* 1.3.1 7f5d03d0549bcbd26f40e7e4a3297ea5204fb1cc pep440-dev
improve/.* 1.3.1 7f5d03d0549bcbd26f40e7e4a3297ea5204fb1cc pep440-dev
maintenance 1.3.2 6393de8c7d42a8bbddcab7cdbb6530ea88a8c82d pep440-dev
fix/.* 1.3.2 6393de8c7d42a8bbddcab7cdbb6530ea88a8c82d pep440-dev
improve/.* 1.3.2 6393de8c7d42a8bbddcab7cdbb6530ea88a8c82d pep440-dev
# every other branch is a development branch and thus gets resolved to 1.4.0-dev for now
.* 1.4.0 7f5d03d0549bcbd26f40e7e4a3297ea5204fb1cc pep440-dev
+4
View File
@@ -75,6 +75,10 @@ date of first contribution):
* [Clemens Niemeyer](https://github.com/clemniem)
* ["I-am-me"](https://github.com/I-am-me)
* [Noah Martin](https://github.com/noahsmartin)
* [Eyal Soha](https://github.com/eyal0)
* [Greg Hulands](https://github.com/ghulands)
* [Andreas Werner](https://github.com/gallore)
* [Shawn Bruce](https://github.com/kantlivelong)
OctoPrint started off as a fork of [Cura](https://github.com/daid/Cura) by
[Daid Braam](https://github.com/daid). Parts of its communication layer and
+86
View File
@@ -1,9 +1,94 @@
# OctoPrint Changelog
## 1.3.2 (2017-03-16)
### Note for plugin authors
**If you maintain a plugin that extends OctoPrint's [JavaScript Client Library](http://docs.octoprint.org/en/master/jsclientlib/index.html)** like demonstrated in e.g. the bundled Software Update Plugin you'll need to update the way you register your plugin to depend on `OctoPrintClient` and registering your extension as shown [here](https://github.com/foosel/OctoPrint/blob/6e793c2/src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js#L1-L84) instead of directly writing to `OctoPrint.plugins` (like it was still done [here](https://github.com/foosel/OctoPrint/blob/23744cd/src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js#L1-L81)). That way your extensions will be available on all instances of `OctoPrintClient`, not just the global instance `OctoPrint` that gets created on startup of the core web interface.
If all you plugin does with regards to JavaScript is registering a custom view model and you have no idea what I'm talking about regarding extending the client library, no action is necessary. This heads-up is really only relevant if you extended the JavaScript Client Library.
### Improvements
- [#732](https://github.com/foosel/OctoPrint/pull/732) - Have OctoPrint's `python setup.py clean` build on stock
`python setup.py clean` for better compatibility with packaging systems
- [#1506](https://github.com/foosel/OctoPrint/issues/1506) - Better handle really long "dwell"/`G4` commands on Repetier firmware (as for example apparently recommended to use with Wanhao D6 and similar printers for nozzle cooling) by actively stalling communication from OctoPrint's side as well. That way we no longer run into a communication timeout produced by a 5min dwell immediately happily acknowledged by the printer with an `ok`.
- [#1542](https://github.com/foosel/OctoPrint/issues/1542) - Support for multi-extruder setups with a shared single nozzle and heater (e.g. E3D Cyclops, Diamond hotend, etc).
- [#1676](https://github.com/foosel/OctoPrint/issues/1676) - Trigger line number reset when connected to printer and seeing `start` message. This should fix issues with printer communication when printer resets but reset goes otherwise undetected.
- [#1681](https://github.com/foosel/OctoPrint/issues/1681) - Support for connecting to multiple OctoPrint instances via the [JavaScript Client Library](http://docs.octoprint.org/en/master/jsclientlib/index.html).
- [#1712](https://github.com/foosel/OctoPrint/issues/1712) - Display current folder name in file list if in sub folder.
- [#1723](https://github.com/foosel/OctoPrint/issues/1723) - Ignore leading `v` or `V` on plugin version numbers for version checks in plugin manager and software updater (see also [#1724](https://github.com/foosel/OctoPrint/pull/1724))
- [#1770](https://github.com/foosel/OctoPrint/issues/1770) - Better resilience against null bytes received from the printer for whatever reason.
- [#1770](https://github.com/foosel/OctoPrint/issues/1770) - Detect printer as connected even when only receiving a `wait` instead of `ok`. Should solve issues with initial connect where printer sends garbage over the line that eats/covers the `ok` if printer also sends regular `wait` messages when idle.
- [#1780](https://github.com/foosel/OctoPrint/issues/1780) - Work around for Safari re-opening one copy of the webcam stream after the other and eating up bandwidth unnecessarily (see also [#1786](https://github.com/foosel/OctoPrint/issues/1786))
- [#1790](https://github.com/foosel/OctoPrint/issues/1790) - Removed unused "color" property from printer profile editor.
- [#1805](https://github.com/foosel/OctoPrint/issues/1805) - Better error resilience against invalid print history data from plugins that replace the printer communication.
- Better error resilience in Plugin Manager against wonky version data in repository file.
- Added a "Restart in safe mode" system menu entry that will always be available if the restart command is configured
- CLI: Only offer `daemon` sub command on Linux (since that it's the only OS it works on)
- Less throttling of analysis of GCODE files from the analysis backlog. Should still leave Pi and friends air to breathe but allow a slightly faster processing of the backlog.
- Added an explanation of safe mode to the docs.
- Log OctoPrint version & plugin list when detecting log rollover.
- Allow `UiPlugin`s to define additional fields for ETag generation.
- Allow `UiPlugin`s utilizing OctoPrint's stock templates to filter out what they don't need.
- Locales contained in `translations` of plugins will now be registered with the system. That way it's possible to provide translations for the full application through plugins.
- Abort file analysis if file is about to be overwritten
- Software Update Plugin: Refresh cache on startup, prevent concurrent refresh
- More solid parsing of request line number for resend requests. Should improve compatibility with Teacup firmwares. Based on issue reported via PR [#300](https://github.com/foosel/OctoPrint/pull/300)
### Bug fixes
- [#733](https://github.com/foosel/OctoPrint/issues/733) - Fixed multiple event handler commands running concurrently. Now they run one after the other, as expected.
- [#1317](https://github.com/foosel/OctoPrint/issues/1317) - Fixed a color distortion issue when rendering timelapses from higher resolution source snapshots that also need to be rotated by adjusting `ffmpeg` parameters to avoid an unexpected behaviour when a pixel format and a filter chain are required for processing.
- [#1560](https://github.com/foosel/OctoPrint/issues/1560) - Make sure we don't try to use an empty `logging.yaml`
- [#1631](https://github.com/foosel/OctoPrint/issues/1631) - Disable "Slice" button in slice dialog if a print is ongoing and a slicer is selected that runs on the same device as OctoPrint. The server would already deny such requests (simply due to performance reasons), but the UI didn't properly reflect that yet.
- [#1671](https://github.com/foosel/OctoPrint/issues/1671) - Removed "Hide empty folders" option from file list. Didn't really add value and caused usability issues.
- [#1771](https://github.com/foosel/OctoPrint/issues/1771) - Fixed `_config_version` in plugin settings not being properly updated.
- [#1732](https://github.com/foosel/OctoPrint/issues/1732) - Fixed a bug in the documentation for the printer profile API
- [#1760](https://github.com/foosel/OctoPrint/issues/1760) - Fixed missing reselect of selected file when updating via the watched folder, causing wrong progress percentages to be reported.
- [#1765](https://github.com/foosel/OctoPrint/issues/1765) - Fixed watched folder not waiting with file move until file stopped growing, causing wrong progress percentages to be reported.
- [#1777](https://github.com/foosel/OctoPrint/issues/1777) - Fixed z-change based timelapses with Slic3r generated z-hops not properly triggering snapshots.
- [#1792](https://github.com/foosel/OctoPrint/issues/1792) - Don't tell Safari we are "web-app-capable" because that means it will throw away all cookies and the user will have to constantly log in again when using a desktop shortcut for the OctoPrint instance.
- [#1812](https://github.com/foosel/OctoPrint/issues/1812) - Don't scroll up navigation in settings when switching between settings screens, very annoying on smaller resolutions (see also [#1814](https://github.com/foosel/OctoPrint/pull/1814))
- Fix settings helper not allowing to delete values for keys that are present in the local config but not in the defaults.
- Fix wrong replacement value for `__progress` in registered command line or GCODE [event handlers](http://docs.octoprint.org/en/master/events/index.html).
- Various fixes in the Software Update Plugin:
- Don't remove manual software update configurations on settings migration.
- Properly delete old restart/reboot commands that are now defined globally since config version 4. An issue with the settings helper prevented us from properly deleting them during migration to version 4.
- Fixed `python_checker` version check method and `python_updater` update method.
- Fixed update configs without a restart of any kind causing an issue due to an undefined variable.
- Fixed broken doctests.
- Upgrade LESS.min.js from 2.7.1 to 2.7.2 to fix the broken contrast function
- Always create a new user session for requests with an API key
- Fixed an error when reading all user settings via the API
- Fixed a bunch of caching issues for the page, was not properly updated on change of snapshot URL presence, system menu entry presence, gcode viewer enabled/disabled, changes in access control availability.
- Fixed wrong bundling of core and plugin assets
- Software Update Plugin: Fixed wrong ETag calculation
- Disable external heatup detection until firmware is detected
- Fixed login dropdown not closing on click outside of it
- Fixed new user settings getting lost until restart
- Don't call `onUserLoggedIn`/`onUserLoggedOut` on user reload
### More information
- [Commits](https://github.com/foosel/OctoPrint/compare/1.3.1...1.3.2)
- Release Candidates:
- [1.3.2rc1](https://github.com/foosel/OctoPrint/releases/tag/1.3.2rc1)
## 1.3.1 (2017-01-25)
### Note for upgraders
#### If you installed OctoPrint manually and used the included init script, you need to update that
The init script so far shipped with OctoPrint contained a [bug](https://github.com/foosel/OctoPrint/issues/1657) that causes issues with OctoPrint 1.3.0 and higher. Please update your init script to the fixed version OctoPrint now ships under `scripts`:
```
sudo cp /path/to/OctoPrint/scripts/octoprint.init /etc/init.d/octoprint
```
If you are running OctoPi, this does **not** apply to you and you do not need to do anything here!
#### Change in stock terminal filter configuration
1.3.1 fixes an issue with the two terminal filters for suppressing temperature and SD status messages and adds a new filter for filtering out firmware `wait` messages. These changes will only be active automatically though for stock terminal filter configurations. If you have customized your terminal filters, you'll need to apply these changes manually under "Settings > Terminal filters":
@@ -23,6 +108,7 @@
- New "Suppress wait responses" filter: `Recv: wait`
### Bug fixes
- [#1344](https://github.com/foosel/OctoPrint/issues/1344) - Fix ProgressBarPlugins to not correctly be triggered for 0% (second try, this time hopefully for good).
- [#1637](https://github.com/foosel/OctoPrint/issues/1637) - Fix issue preventing a folder to be deleted that has a name which is a common prefix of the file currently being printed.
- [#1641](https://github.com/foosel/OctoPrint/issues/1641) - Fix issue with `octoprint --daemon` not working.
+28 -20
View File
@@ -93,11 +93,15 @@ following section *completely* and also follow the instructions in the
2. Please make sure to **test out the current version** of OctoPrint to see
whether the problem you are encountering still exists, and **test without
any non-bundled plugins enabled** to make sure it's not a misbehaving
plugin causing the issue at hand.
any third-party plugins enabled** to make sure it's not a misbehaving
plugin causing the issue at hand. For that please restart OctoPrint in
**safe mode**, either by selecting "Restart OctoPrint in safe mode" from
the "System" menu, or by starting OctoPrint from the command line with
`octoprint serve --safe`. Then try to reproduce your issue. Find out
more about safe mode in the [docs](http://docs.octoprint.org/en/master/features/safemode.html).
If you are feeling up to it you might also want to try the current development
version of OctoPrint (if you aren't already). Refer to the [FAQ](https://github.com/foosel/OctoPrint/wiki/FAQ)
You might also want to try the current development version of OctoPrint
(if you aren't already). Refer to the [FAQ](https://github.com/foosel/OctoPrint/wiki/FAQ)
for information on how to do this.
3. The problem still exists? Then please **look through the
@@ -258,17 +262,18 @@ See [the corresponding chapter in the documentation](http://docs.octoprint.org/e
just cause unnecessary work and frustration for everyone or
possibly get the PR rejected.
3. Create your pull request **from a custom branch** on your end (e.g.
`dev/myNewFeature`)[1] **against the `devel` branch**. Create **one pull request
per feature/bug fix**. If your PR contains an important bug fix, we will
make sure to backport it to the `maintenance` branch to also include it in
the next release.
4. Make sure there are **only relevant changes** included in your PR. No
`dev/myNewFeature`)[1].
4. Create your pull request **only against the `maintenance` or `devel` branch**:
* if it's a bug fix for a bug in the current stable version: `maintenance` branch
* otherwise: `devel` branch
5. Create **one pull request per feature/bug fix**.
6. Make sure there are **only relevant changes** included in your PR. No
changes to unrelated files, no additional files that don't belong (e.g.
commits of your full virtual environment). Make sure your PR consists
**ideally of only one commit** (use git's rebase and squash functionality).
5. Make sure you **follow the current coding style**. This means:
7. Make sure you **follow the current coding style**. This means:
* Tabs instead of spaces in the Python files[2]
* Spaces instead of tabs in the Javascript sources
* Spaces instead of tabs in the JavaScript sources
* English language (code, variables, comments, ...)
* Comments where necessary: Tell *why* the code does something like it does
it, structure your code
@@ -277,22 +282,22 @@ See [the corresponding chapter in the documentation](http://docs.octoprint.org/e
``.less`` files from which the CSS is compiled.
* Make sure you do not add dead code (e.g. commented out left-overs
from experiments).
6. Ensure your changes **pass the existing unit tests**. PRs that break
8. Ensure your changes **pass the existing unit tests**. PRs that break
those cannot be accepted.
7. **Test your changes thoroughly**. That also means testing with usage
9. **Test your changes thoroughly**. That also means testing with usage
scenarios you don't normally use, e.g. if you only use access control, test
without and vice versa. If you only test with your printer, test with the
virtual printer and vice versa. State in your pull request how you tested
your changes. Ideally **add unit tests** - OctoPrint severely lacks in that
department, but we are trying to change that, so any new code already covered
with a test suite helps a lot!
8. In your pull request's description, **state what your pull request does**,
as in, what feature does it implement, what bug does it fix. The more
thoroughly you explain your intent behind the PR here, the higher the
chances it will get merged fast. There is a template provided below
that can help you here.
9. Don't forget to **add yourself to the [AUTHORS](./AUTHORS.md)
file** :)
10. In your pull request's description, **state what your pull request does**,
as in, what feature does it implement, what bug does it fix. The more
thoroughly you explain your intent behind the PR here, the higher the
chances it will get merged fast. There is a template provided below
that can help you here.
11. Don't forget to **add yourself to the [AUTHORS](./AUTHORS.md)
file** :)
Template to use for Pull Request descriptions:
@@ -397,6 +402,9 @@ the local version identifier to allow for an exact determination of the active c
* 2016-09-23: Some more work on "How to file a bug report" based on recent
experiences
* 2017-01-25: Fixed a typo
* 2017-03-09: Allow PRs against `maintenance` branch for bugs in stable.
* 2017-03-10: Reproduce bugs in safe mode to make sure they are really caused
by OctoPrint itself and not a misbehaving plugin.
## Footnotes
* [1] - If you are wondering why, the problem is that anything that you add
+19 -12
View File
@@ -1,6 +1,8 @@
# OctoPrint
OctoPrint provides a snappy web interface for controlling a 3D printer (RepRap, Ultimaker, ...). It is Free Software
[![GitHub version](https://badge.fury.io/gh/foosel%2FOctoPrint.svg)](https://badge.fury.io/gh/foosel%2FOctoPrint)
OctoPrint provides a snappy web interface for controlling consumer 3D printers. It is Free Software
and released under the [GNU Affero General Public License V3](http://www.gnu.org/licenses/agpl.html).
Its website can be found at [octoprint.org](http://octoprint.org).
@@ -33,7 +35,7 @@ If you think something is bad about OctoPrint or its documentation the way it is
in any way to make it better instead of just complaining about it -- this is an Open Source Project
after all :)
For information about how to go about contributions of any kind, please see the project's
For information about how to go about submitting bug reports or pull requests, please see the project's
[Contribution Guidelines](https://github.com/foosel/OctoPrint/blob/master/CONTRIBUTING.md).
## Installation
@@ -41,7 +43,7 @@ For information about how to go about contributions of any kind, please see the
Installation instructions for installing from source for different operating
systems can be found [on the wiki](https://github.com/foosel/OctoPrint/wiki#assorted-guides).
If you want to run OctoPrint on a Raspberry Pi you might want to take a look at [OctoPi](https://github.com/guysoft/OctoPi)
If you want to run OctoPrint on a Raspberry Pi, you might want to take a look at [OctoPi](https://github.com/guysoft/OctoPi)
which is a custom SD card image that includes OctoPrint plus dependencies.
The generic steps that should basically be done regardless of operating system
@@ -59,7 +61,7 @@ for details.
After installation, please make sure you follow the first-run wizard and set up
access control as necessary. If you want to not only be notified about new
releases but also be able to automatically upgrade to them from within
releases, but also be able to automatically upgrade to them from within
OctoPrint, take a look [at the documentation of the Software Update Plugin](https://github.com/foosel/OctoPrint/wiki/Plugin:-Software-Update#making-octoprint-updateable-on-existing-installations)
and at its settings.
@@ -70,7 +72,7 @@ OctoPrint via `setup.py`:
python setup.py install
You should also do this every time after pulling from the repository, since the dependencies might have changed.
You should do this every time after pulling from the repository, since the dependencies may have changed.
OctoPrint currently only supports Python 2.7.
@@ -81,8 +83,8 @@ Running the `setup.py` script via
python setup.py install
installs the `octoprint` script in your Python installation's scripts folder
(which depending on whether you installed OctoPrint globally or into a virtual env will be on your `PATH` or not). The
following usage examples assume that said `octoprint` script is on your `PATH`.
(which, depending on whether you installed OctoPrint globally or into a virtual env, will be in your `PATH` or not). The
following usage examples assume that the `octoprint` script is on your `PATH`.
You can start the server via
@@ -95,7 +97,7 @@ to only listen on the local interface on port 8080, the command line would be
octoprint serve --host=127.0.0.1 --port=8080
Alternatively, the host and port on which to bind can be defined via the configuration.
Alternatively, the host and port on which to bind can be defined via the config file.
If you want to run OctoPrint as a daemon (only supported on Linux), use
@@ -103,19 +105,24 @@ If you want to run OctoPrint as a daemon (only supported on Linux), use
If you do not supply a custom pidfile location via `--pid PIDFILE`, it will be created at `/tmp/octoprint.pid`.
You can also specify the configfile or the base directory (for basing off the `uploads`, `timelapse` and `logs` folders),
You can also specify the config file or the base directory (for basing off the `uploads`, `timelapse` and `logs` folders),
e.g.:
octoprint serve --config /path/to/another/config.yaml --basedir /path/to/my/basedir
See `octoprint --help` for further information.
To start OctoPrint in safe mode - which disables all third party plugins that do not come bundled with OctoPrint - use
the ``--safe`` flag:
OctoPrint also ships with a `run` script in its source directory. You can also invoke that to start up the server, it
octoprint serve --safe
See `octoprint --help` for more information on the available command line parameters.
OctoPrint also ships with a `run` script in its source directory. You can invoke it to start the server. It
takes the same command line arguments as the `octoprint` script.
## Configuration
If not specified via the commandline, the configfile `config.yaml` for OctoPrint is expected in the settings folder,
If not specified via the command line, the config file `config.yaml` for OctoPrint is expected in the settings folder,
which is located at `~/.octoprint` on Linux, at `%APPDATA%/OctoPrint` on Windows and
at `~/Library/Application Support/OctoPrint` on MacOS.
+5 -6
View File
@@ -10,14 +10,12 @@ thanks to everyone who contributed!
* Aleph Objects, Inc.
* Andrew Moorby
* Arnljot Arntsen
* Aurelio Bernal
* Boris Hussein
* Brad Jackson
* Brent Fiegle
* Brian E. Tyler
* Christopher Day
* Christian Petropolis
* COLLE+McVOY
* CreativeTools
* D Brian Kimmel
* DeltaMaker 3D Printers
@@ -29,10 +27,11 @@ thanks to everyone who contributed!
* Gary Deen
* Gary N McKinney
* George Robles
* J. Eckert
* James Seigel
* Jamie R McGuigan
* Jamie van Dyke
* Jeff Moe
* Josh Daniels
* Joshua David Gregory
* Kaile Riser
* Kale Stedman
* Kazuhiro Ogura
@@ -44,6 +43,7 @@ thanks to everyone who contributed!
* Masayoshi Mitsui
* Michael Aumock
* Miles Flavel
* Mohammed khorakiwala
* Noe Ruiz
* Patrick McGinnis
* Peter Grace
@@ -58,11 +58,10 @@ thanks to everyone who contributed!
* Simon Hallam
* Stefan Krister
* Stephane Schittly
* Steven Pearson
* Sven Mueller
* Terrance Shaw
* Thomas Hatley
* Timeshell.ca
* Trent Shumay
and 1016 more wonderful people pledging on the [Patreon campaign](https://patreon.com/foosel)!
and 1041 more wonderful people pledging on the [Patreon campaign](https://patreon.com/foosel)!
+14
View File
@@ -34,6 +34,7 @@
* [appdirs](http://github.com/ActiveState/appdirs): MIT
* [Awesome-Slugify](https://pypi.python.org/pypi/awesome-slugify): GPLv3
* [chainmap](https://bitbucket.org/jeunice/chainmap): Python
* [Click](http://click.pocoo.org/): BSD
* [feedparser](https://github.com/kurtmckee/feedparser): BSD
* [Flask](http://flask.pocoo.org/): BSD
@@ -42,6 +43,7 @@
* [Flask-Login](https://github.com/maxcountryman/flask-login): MIT
* [Flask-Markdown](http://github.com/dcolish/flask-markdown): BSD
* [Flask-Principal](http://packages.python.org/Flask-Principal/): MIT
* [future](https://python-future.org/): MIT
* [netaddr](https://github.com/drkjam/netaddr/): BSD
* [netifaces](https://bitbucket.org/al45tair/netifaces): MIT
* [pkginfo](http://pypi.python.org/pypi/pkginfo/): Python
@@ -52,7 +54,19 @@
* [requests](http://python-requests.org/): Apache License 2.0
* [rsa](http://stuvel.eu/rsa): Apache License 2.0
* [sarge](http://sarge.readthedocs.org/): BSD
* [scandir](https://github.com/benhoyt/scandir): BSD
* [semantic_version](https://github.com/rbarrois/python-semanticversion): BSD
* [SockJS-Tornado](http://github.com/mrjoes/sockjs-tornado/): MIT
* [Tornado](http://www.tornadoweb.org/): Apache License 2.0
* [watchdog](http://github.com/gorakhargosh/watchdog): Apache License 2.0
* [websocket-client](https://github.com/liris/websocket-client): LGPLv3
## Development (testing, documentation generation, etc)
* [ddt](https://github.com/txels/ddt): MIT
* [mock](https://github.com/testing-cabal/mock): BSD
* [nose](http://pythonhosted.org/nose/): LGPL
* [pypandoc](https://github.com/bebraw/pypandoc): MIT
* [Sphinx](http://sphinx-doc.org/): BSD
* [sphinxcontrib-httpdomain](https://bitbucket.org/birkenfeld/sphinx-contrib/src/default/httpdomain/): BSD
* [sphinx_rtd_theme](https://github.com/snide/sphinx_rtd_theme/): BSD
+113 -76
View File
@@ -34,90 +34,92 @@ Retrieve all printer profiles
HTTP/1.1 200 OK
Content-Type: application/json
[
{
"id": "_default",
"name": "Default",
"color": "default",
"model": "Generic RepRap Printer",
"default": true,
"current": true,
"resource": "http://example.com/api/printerprofiles/_default",
"volume": {
"formFactor": "rectangular",
"origin": "lowerleft",
"width": 200,
"depth": 200,
"height": 200
},
"heatedBed": true,
"axes": {
"x": {
"speed": 6000,
"inverted": false
{
"profiles": [
{
"id": "_default",
"name": "Default",
"color": "default",
"model": "Generic RepRap Printer",
"default": true,
"current": true,
"resource": "http://example.com/api/printerprofiles/_default",
"volume": {
"formFactor": "rectangular",
"origin": "lowerleft",
"width": 200,
"depth": 200,
"height": 200
},
"y": {
"speed": 6000,
"inverted": false
"heatedBed": true,
"axes": {
"x": {
"speed": 6000,
"inverted": false
},
"y": {
"speed": 6000,
"inverted": false
},
"z": {
"speed": 200,
"inverted": false
},
"e": {
"speed": 300,
"inverted": false
}
},
"z": {
"speed": 200,
"inverted": false
},
"e": {
"speed": 300,
"inverted": false
"extruder": {
"count": 1,
"offsets": [
{"x": 0.0, "y": 0.0}
]
}
},
"extruder": {
"count": 1,
"offsets": [
{"x": 0.0, "y": 0.0}
]
}
},
{
"id": "my_profile",
"name": "My Profile",
"color": "default",
"model": "My Custom Printer",
"default": false,
"current": false,
"resource": "http://example.com/api/printerprofiles/my_profile",
"volume": {
"formFactor": "rectangular",
"origin": "lowerleft",
"width": 200,
"depth": 200,
"height": 200
},
"heatedBed": true,
"axes": {
"x": {
"speed": 6000,
"inverted": false
{
"id": "my_profile",
"name": "My Profile",
"color": "default",
"model": "My Custom Printer",
"default": false,
"current": false,
"resource": "http://example.com/api/printerprofiles/my_profile",
"volume": {
"formFactor": "rectangular",
"origin": "lowerleft",
"width": 200,
"depth": 200,
"height": 200
},
"y": {
"speed": 6000,
"inverted": false
"heatedBed": true,
"axes": {
"x": {
"speed": 6000,
"inverted": false
},
"y": {
"speed": 6000,
"inverted": false
},
"z": {
"speed": 200,
"inverted": false
},
"e": {
"speed": 300,
"inverted": false
}
},
"z": {
"speed": 200,
"inverted": false
},
"e": {
"speed": 300,
"inverted": false
"extruder": {
"count": 1,
"offsets": [
{"x": 0.0, "y": 0.0}
]
}
},
"extruder": {
"count": 1,
"offsets": [
{"x": 0.0, "y": 0.0}
]
}
},
]
]
}
.. _sec-api-printerprofiles-add:
@@ -537,6 +539,41 @@ Profile
- 0..1
- ``float``
- The height of the print volume
* - ``volume.custom_box``
- 0..1
- ``boolean`` or ``object``
- If the printer has a custom bounding box where the print head can be safely moved to, exceeding the defined print
volume, that bounding box will be defined here. Otherwise (safe area == print volume) this value will be ``false``.
* - ``volume.custom_box.min_x``
- 0..1
- ``float``
- Minimum X coordinate defining the safe custom bounding box. Smaller value than the minimum X coordinate of the
print volume.
* - ``volume.custom_box.max_x``
- 0..1
- ``float``
- Maximum X coordinate defining the safe custom bounding box. Larger value than the maximum X coordinate of the
print volume.
* - ``volume.custom_box.min_y``
- 0..1
- ``float``
- Minimum Y coordinate defining the safe custom bounding box. Smaller value than the minimum Y coordinate of the
print volume.
* - ``volume.custom_box.max_y``
- 0..1
- ``float``
- Maximum Y coordinate defining the safe custom bounding box. Larger value than the maximum Y coordinate of the
print volume.
* - ``volume.custom_box.min_z``
- 0..1
- ``float``
- Minimum Z coordinate defining the safe custom bounding box. Smaller value than the minimum Z coordinate of the
print volume.
* - ``volume.custom_box.max_z``
- 0..1
- ``float``
- Maximum Z coordinate defining the safe custom bounding box. Larger value than the maximum Z coordinate of the
print volume.
* - ``heatedBed``
- 0..1
- ``boolean``
+6
View File
@@ -133,6 +133,12 @@ mapped from the same fields in ``config.yaml`` unless otherwise noted:
-
* - ``feature.modelSizeDetection``
-
* - ``feature.firmwareDetection``
-
* - ``feature.printCancelConfirmation``
-
* - ``feature.blockWhileDwelling``
-
* - ``folder.uploads``
-
* - ``folder.timelapse``
+6 -1
View File
@@ -268,9 +268,14 @@ Slicer
- ``string``
- Identifier of the slicer
* - ``displayName``
- 0..1
- 1
- ``string``
- Display name of the slicer
* - ``sameDevice``
- 1
- ``boolean``
- Whether the slicer runs on the same device as OctoPrint (``true``) and hence can't be used while printing,
or not (``false``)
* - ``default``
- 1
- ``boolean``
+9 -2
View File
@@ -43,6 +43,13 @@ Installing pybonjour
OctoPi versions 0.12.0 and later already come with pybonjour installed and ready to go,
you don't need to perform these steps there.
.. note::
Currently there are no releases for pybonjour available on the Python Package Index PyPI. The latest pybonjour
release is still available in the `Google Code Archive <https://storage.googleapis.com/google-code-archive-downloads/v2/code.google.com/pybonjour/pybonjour-1.1.1.tar.gz>`_.
Since that URL is hilariously long though, a shortened version is provided with https://goo.gl/SxQZ06 and
used in the installation instructions below.
In order for the Zeroconf discovery to work, the
`pybonjour package <https://pypi.python.org/pypi/pybonjour>`_ needs to be available
to the Python installation running OctoPrint.
@@ -52,7 +59,7 @@ into some folder ``~/OctoPrint``. You executed ``python setup.py install`` withi
virtualenv in the same folder called ``venv``. In order to install ``pybonjour``
so it will be available to OctoPrint you'll need to do the following::
venv/bin/pip install pybonjour
venv/bin/pip install https://goo.gl/SxQZ06
**Linux users:** You'll need to install an additional dependency for this to work, the
libdnssd compatibility layer for libavahi. On Debian/Ubuntu that can be achieved with::
@@ -71,7 +78,7 @@ The plugin supports the following configuration keys:
optional, if not set the port OctoPrint itself was started under will be used
* ``pathPrefix``: Path prefix OctoPrint is running under, optional, if not
set ``/`` will be used
* ``useSsl``: ``true``if OctoPrint should be called via HTTPS, ``false`` otherwise
* ``useSsl``: ``true`` if OctoPrint should be called via HTTPS, ``false`` otherwise
* ``httpUsername``: HTTP Basic Auth username OctoPrint is reachable with, optional
* ``httpPassword``: HTTP Basic Auth password OctoPrint is reachable with, optional
* ``upnpUuid``: uPNP UUID used for SSDP service announcements, usually you will
+125 -16
View File
@@ -519,6 +519,23 @@ Use the following settings to enable or disable OctoPrint features:
# If ignoredIdenticalResends is true, how many consecutive identical resends to ignore
identicalResendsCount: 7
# Whether to support F on its own as a valid GCODE command (true) or not (false)
supportFAsCommand: false
# Whether to enable model size detection and warning (true) or not (false)
modelSizeDetection: true
# Whether to attempt to auto detect the firmware of the printer and adjust settings
# accordingly (true) or not and rely on manual configuration (false)
firmwareDetection: true
# Whether to show a confirmation on print cancelling (true) or not (false)
printCancelConfirmation: true
# Whether to block all sending to the printer while a G4 (dwell) command is active (true, repetier)
# or not (false)
blockWhileDwelling: false
.. _sec-configuration-config_yaml-folder:
Folder
@@ -565,6 +582,45 @@ Use the following settings to set custom paths for folders used by OctoPrint:
# Absolute path where to store (GCODE) scripts
scripts: /path/to/scripts/folder
.. _sec-configuration-config_yaml-gcodeanalysis:
GCODE Analysis
--------------
Settings pertaining to the server side GCODE analysis implementation.
.. code-block:: yaml
# Maximum number of extruders to support/to sanity check for
maxExtruders: 10
# Pause between each processed GCODE line in normal priority mode, seconds
throttle_normalprio: 0.01
# Pause between each processed GCODE line in high priority mode (e.g. on fresh
# uploads), seconds
throttle_highprio: 0.0
.. _sec-configuration-config_yaml-gcodeviewer:
GCODE Viewer
------------
Settings pertaining to the built in GCODE Viewer.
.. code-block:: yaml
# Whether to enable the GCODE viewer in the UI
enabled: true
# Maximum size a GCODE file may have on mobile devices to automatically be loaded
# into the viewer, defaults to 2MB
mobileSizeThreshold: 2097152
# Maximum size a GCODE file may have to automatically be loaded into the viewer,
# defaults to 20MB
sizeThreshold: 20971520
.. _sec-configuration-config_yaml-plugins:
Plugin settings
@@ -679,8 +735,34 @@ Use the following settings to configure the serial connection to the printer:
connection: 2
# Timeout during serial communication, in seconds.
# Defaults to 5 sec
communication: 5
# Defaults to 30 sec
communication: 30
# Timeout after which to query temperature when no target is set
temperature: 5
# Timeout after which to query temperature when a target is set
temperatureTargetSet: 2
# Timeout after which to query the SD status while SD printing
sdStatus: 1
# Maximum number of consecutive communication timeouts after which the printer will be considered
# dead and OctoPrint disconnects with an error.
maxCommunicationTimeouts:
# max. timeouts when the printer is idle
idle: 2
# max. timeouts when the printer is printing
printing: 5
# max. timeouts when a long running command is active
long: 5
# Maximum number of write attempts to serial during which nothing can be written before the communication
# with the printer is considered dead and OctoPrint will disconnect with an error
maxWritePasses:
# 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.
@@ -702,6 +784,7 @@ Use the following settings to configure the serial connection to the printer:
- G32
- M400
- M226
- M600
# Commands which need to always be send with a checksum. Defaults to only M110
checksumRequiringCommands:
@@ -746,10 +829,14 @@ Use the following settings to configure the server:
# Use this option to define the port to which to bind the server, defaults to 5000
port: 5000
# If this option is true, OctoPrint will show the First Run dialog and set it to false after that
# completes
# If this option is true, OctoPrint will show the First Run wizard and set the setting to
# false after that completes
firstRun: false
# If this option is true, OctoPrint will enable safe mode on the next server start and
# reset the setting to false
startOnceInSafeMode: false
# Secret key for encrypting cookies and such, randomly generated on first run
secretKey: someSecretKey
@@ -944,10 +1031,12 @@ Use `Javascript regular expressions <https://developer.mozilla.org/en/docs/Web/J
# 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)'
- name: Suppress temperature messages
regex: '(Send: (N\d+\s+)?M105)|(Recv: ok T:)'
- name: Suppress SD status messages
regex: '(Send: (N\d+\s+)?M27)|(Recv: SD printing byte)'
- name: Suppress wait responses
regex: 'Recv: wait'
.. _sec-configuration-config_yaml-webcam:
@@ -981,22 +1070,42 @@ Use the following settings to configure webcam support:
# Whether to include a "created with OctoPrint" watermark in the generated timelapse movies
watermark: true
# Whether to flip the webcam horizontally
flipH: false
# Whether to flip the webcam vertically
flipV: false
# Whether to rotate the webcam 90° counter clockwise
rotate90: false
# The default timelapse settings.
timelapse:
# The timelapse type. Can be either "off", "zchange" or "timed". Defaults to "off"
type: timed
# The framerate at which to render the movie
fps: 25
# 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
# 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
# Timed timelapses only: Whether to capture the snapshots for the post roll (true) or just copy
# the last captured snapshot from the print over and over again (false)
capturePostRoll: true
# ZChange timelapses only: Z-hop height during retractions to ignore for capturing snapshots
retractionZHop: 0.0
# After how many days unrendered timelapses will be deleted
cleanTmpAfterDays: 7
+3
View File
@@ -67,10 +67,13 @@ All GCODE scripts have access to the following template variables through the te
There are a couple of additional template variables available for the following specific scripts:
* ``afterPrintPaused`` and ``beforePrintResumed``
* ``pause_position``: Position reported by the printer via ``M114`` immediately before the print was paused. Consists
of ``x``, ``y``, ``z`` and ``e`` coordinates as received by the printer and tracked values for ``f`` and current tool
``t`` taken from commands sent through OctoPrint.
* ``afterPrintCancelled``
* ``cancel_position``: Position reported by the printer via ``M114`` immediately before the print was cancelled.
Consists of ``x``, ``y``, ``z`` and ``e`` coordinates as received by the printer and tracked values for ``f`` and
current tool ``t`` taken from commands sent through OctoPrint.
+1
View File
@@ -16,3 +16,4 @@ Features
gcode_scripts.rst
action_commands.rst
plugins.rst
safemode.rst
+10
View File
@@ -11,6 +11,16 @@ Right now plugins can be used to extend OctoPrint's web interface, to execute sp
shutdown, to provide custom (API) endpoints or whole user interfaces with special functionality, to react to system
events or progress reports or to add support for additional slicers. More plugin types are planned for the future.
.. note::
Since a plugin might not function properly and cause issues that are hard to diagnose or outright disrupt server
functionality, you might want to be able to start OctoPrint without any third party plugins enabled. This is also
very important when reporting bugs in OctoPrint, to ensure that what you are observing is actually a bug in
OctoPrint and not in any of your installed third party plugins.
To do that, OctoPrint has a built-in safe mode that disables all plugins not shipped as part of OctoPrint. You can
read more on how to enable that :ref:`here <sec-features-safemode>`.
.. _sec-features-plugins-available:
Finding Plugins
+64
View File
@@ -0,0 +1,64 @@
.. _sec-features-safemode:
*********
Safe mode
*********
With the advent of support for plugins in OctoPrint, it quickly became apparent that some of the bugs
reported on OctoPrint's bug tracker were actually bugs with installed third party plugins instead of
OctoPrint itself.
To allow an easier identification of these cases, OctoPrint 1.3.0 introduced safe mode. Starting
OctoPrint in safe mode disables all plugins that are not bundled with OctoPrint, allowing to easier
identify most cases where a third party plugin is the culprit of an observed issue.
Additionally, OctoPrint allows uninstalling plugins in this mode, allowing recovery from cases where
a third party plugin causes the server to not start up or the web interface to not render or function
correctly anymore.
.. _sec-features-safemode-how:
How to start OctoPrint in safe mode
===================================
There exist three ways to start OctoPrint in safe mode:
* since OctoPrint 1.3.2: by selecting "Restart OctoPrint in safe mode" from the "System" menu,
if the "Restart OctoPrint" server command has been correctly configured (see :numref:`fig-features-safemode-systemmenu`).
* by starting OctoPrint with the command line parameter ``--safe``, e.g. ``octoprint serve --safe``
* by setting the option ``server.startOnceInSafeMode`` in :ref:`config.yaml <sec-configuration-config_yaml>`
to ``true`` and restarting
The last two options will have OctoPrint enable safe mode only for the next server start - once you
restart OctoPrint again, safe mode will be disabled again.
.. _fig-features-safemode-systemmenu:
.. figure:: ../images/features-safemode-systemmenu.png
:align: center
:alt: "Restart OctoPrint in safe mode" in the "System" menu
"Restart OctoPrint in safe mode" in the "System" menu
.. _sec-features-safemode-differences:
Differences of safe mode vs normal operation mode
=================================================
When OctoPrint is running in safe mode the following changes to its normal operation mode apply:
* OctoPrint will not enable any of the installed third party plugins. OctoPrint considers all plugins third
party plugins that do not ship with OctoPrint's sources, so any plugins installed either via `pip` or
into OctoPrint's plugin folder at ``~/.octoprint/plugins`` (Linux), ``%APPDATA%/OctoPrint`` (Windows) and
``~/Library/Application Support/OctoPrint`` (MacOS).
* OctoPrint will still allow to uninstall third party plugins through the built-in Plugin Manager.
* OctoPrint will still allow to disable (bundled) plugins that are still enabled.
* OctoPrint will not allow to enable third party plugins.
* OctoPrint's web interface will display a notification to remind you that it is running in
safe mode.
.. _fig-features-safemode-notification:
.. figure:: ../images/features-safemode-notification.png
:align: center
:alt: Safe mode notification
Safe mode notification
Binary file not shown.

After

Width:  |  Height:  |  Size: 38 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 33 KiB

+99 -41
View File
@@ -1,29 +1,45 @@
.. sec-jsclientlib-base:
.. _sec-jsclientlib-base:
:mod:`OctoPrint`
----------------
:mod:`OctoPrintClient`
----------------------
.. js:data:: OctoPrint.options
.. js:class:: OctoPrintClient([options])
The client library's options.
Instantiates a new instance of the client library. Note that by default there's always an instance registered
globally called ``OctoPrint``.
``OctoPrint.options.apikey``
:param object options: An optional object of options to set :js:attr:`OctoPrintClient.options` to.
.. js:attribute:: OctoPrintClient.options
The client library instance's options. The following keys are currently supported:
``apikey``
The API Key to use for requests against the OctoPrint API. Should usually be
the anonymous UI API Key provided on the socket.
``OctoPrint.options.baseurl``
``baseurl``
The base URL of the OctoPrint API
``OctoPrint.options.locale``
``locale``
The locale to set in ``X-Locale`` headers on API requests. Useful for API
endpoints that might return localized content.
.. js:data:: OctoPrint.plugins
.. js:attribute:: OctoPrintClient.plugins
Registration of client library components provided by plugins.
OctoPrint plugins should always register their library exports
in this object, using their plugin identifier as key.
OctoPrint plugins should always register their client classes here using their plugin identifier as key via
:js:func:`OctoPrintClient.registerPluginComponent`.
.. note::
The registration mechanism has changed slightly with OctoPrint 1.3.2 due to an otherwise unsolvable issue with
allowing multiple clients to exist concurrently and still keeping the existing architecture intact.
The old mechanism works fine as long as you are only planning to offer your plugin client implementation on the
default client instance ``OctoPrint``, however if you also want to support additional clients you'll need to
use the implementation and registration approach as described below.
**Example:**
@@ -31,19 +47,26 @@
(function (global, factory) {
if (typeof define === "function" && define.amd) {
define(["OctoPrint"], factory);
define(["OctoPrintClient"], factory);
} else {
factory(window.OctoPrint);
factory(window.OctoPrintClient);
}
})(window || this, function(OctoPrint) {
var exports = {};
})(window || this, function(OctoPrintClient) {
var MyPluginClient = function(base) {
this.base = base;
};
// fill exports
MyPluginClient.prototype.someFunction = function() {
// do something
};
OctoPrint.plugins.myplugin = exports
// further define API
OctoPrintClient.registerPluginComponent("myplugin", MyPluginClient);
return MyPluginClient;
});
.. js:function:: OctoPrint.getBaseUrl()
.. js:function:: OctoPrintClient.getBaseUrl()
Returns the canonical base URL to use for OctoPrint's API. Uses the current value of
:js:data:`OctoPrint.options.baseurl <OctoPrint.options>`. If that doesn't end in a ``/``,
@@ -51,7 +74,7 @@
:returns string: The base url to use to access OctoPrint's API.
.. js:function:: OctoPrint.getRequestHeaders(additional)
.. js:function:: OctoPrintClient.getRequestHeaders(additional)
Generates a dictionary of HTTP headers to use for API requests against OctoPrint with all
necessary headers and any additionally provided ones.
@@ -62,7 +85,7 @@
:param object additional: Additional headers to add to the request.
:returns object: HTTP headers to use for requests.
.. js:function:: OctoPrint.ajax(method, url, opts)
.. js:function:: OctoPrintClient.ajax(method, url, opts)
Performs an AJAX request against the OctoPrint API, utilizing `jQuery's own ajax function <http://api.jquery.com/jquery.ajax/>`_.
@@ -87,7 +110,7 @@
:param object opts: Additional options to use for the request, see above for details (optional)
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.ajaxWithData(method, url, data, opts)
.. js:function:: OctoPrintClient.ajaxWithData(method, url, data, opts)
Performs an AJAX request against the OctoPrint API, including the provided ``data`` in the body of the request.
@@ -99,7 +122,7 @@
:param object opts: Additonal options to use for the request (optional)
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.get(url, opts)
.. js:function:: OctoPrintClient.get(url, opts)
Performs a ``GET`` request against ``url``.
@@ -116,7 +139,7 @@
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.getWithQuery(url, data, opts)
.. js:function:: OctoPrintClient.getWithQuery(url, data, opts)
Performs a ``GET`` request against ``url`` using the provided ``data`` as URL query.
@@ -132,7 +155,7 @@
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.post(url, data, opts)
.. js:function:: OctoPrintClient.post(url, data, opts)
Performs a ``POST`` request against ``url`` using the provided ``data`` as request body.
@@ -152,7 +175,7 @@
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.postJson(url, data, opts)
.. js:function:: OctoPrintClient.postJson(url, data, opts)
Performs a ``POST`` request against ``url`` using the provided ``data`` object as request body
after serializing it to JSON.
@@ -172,33 +195,33 @@
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.put(url, data, opts)
.. js:function:: OctoPrintClient.put(url, data, opts)
Performs ``PUT`` request against ``url`` using the provided ``data`` as request body.
See :js:func:`OctoPrint.post` for details.
.. js:function:: OctoPrint.putJson(url, data, opts)
.. js:function:: OctoPrintClient.putJson(url, data, opts)
Performs ``PUT`` request against ``url`` using the provided ``data`` as request body after
serializing it to JSON.
See :js:func:`OctoPrint.postJson` for details.
.. js:function:: OctoPrint.patch(url, data, opts)
.. js:function:: OctoPrintClient.patch(url, data, opts)
Performs ``PATCH`` request against ``url`` using the provided ``data`` as request body.
See :js:func:`OctoPrint.post` for details.
.. js:function:: OctoPrint.patchJson(url, data, opts)
.. js:function:: OctoPrintClient.patchJson(url, data, opts)
Performs ``PATCH`` request against ``url`` using the provided ``data`` as request body after
serializing it to JSON.
See :js:func:`OctoPrint.postJson` for details.
.. js:function:: OctoPrint.delete(url, opts)
.. js:function:: OctoPrintClient.delete(url, opts)
Performs a ``DELETE`` request against ``url``.
@@ -206,7 +229,7 @@
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.download(url, opts)
.. js:function:: OctoPrintClient.download(url, opts)
Downloads a file from ``url``, returning the response body as data type ``text``.
@@ -218,7 +241,7 @@
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.upload(url, file, filename, additional)
.. js:function:: OctoPrintClient.upload(url, file, filename, additional)
Uploads a ``file`` to ``url`` using a ``multipart/form-data`` ``POST`` request.
@@ -286,7 +309,7 @@
:param string filename: An optional file name to use for the upload
:param object additional: An optional object of additional key/value pairs to set on the uploaded form data
.. js:function:: OctoPrint.issueCommand(url, command, payload, opts)
.. js:function:: OctoPrintClient.issueCommand(url, command, payload, opts)
Issues a command against an OctoPrint command API endpoint.
@@ -318,7 +341,7 @@
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.getSimpleApiUrl(plugin)
.. js:function:: OctoPrintClient.getSimpleApiUrl(plugin)
Returns the proper URL for the endpoint of a :class:`~octoprint.plugin.SimpleApiPlugin`, based on the
plugin identifier.
@@ -333,7 +356,7 @@
:param string plugin: The identifier of the plugin for which to return the URL
:returns string: The URL to use as endpoint
.. js:function:: OctoPrint.simpleApiGet(plugin, opts)
.. js:function:: OctoPrintClient.simpleApiGet(plugin, opts)
Performs a ``GET`` request against the endpoint of a :class:`~octoprint.plugin.SimpleApiPlugin` with
identifier ``plugin``.
@@ -349,7 +372,7 @@
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.simpleApiCommand(plugin, command, payload, opts)
.. js:function:: OctoPrintClient.simpleApiCommand(plugin, command, payload, opts)
Performs the API command ``command`` against the endpoint of a :class:`~octoprint.plugin.SimpleApiPlugin` with
identifier ``plugin``, including the optional ``payload``.
@@ -370,7 +393,7 @@
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.getBlueprintUrl(plugin)
.. js:function:: OctoPrintClient.getBlueprintUrl(plugin)
Returns the proper base URL for blueprint endpoints of a :class:`~octoprint.plugin.BlueprintPlugin` with
identifier ``plugin``.
@@ -382,11 +405,15 @@
// prints "plugin/myplugin/"
console.log(OctoPrint.getBlueprintUrl("myplugin"));
.. js:function:: OctoPrint.createRejectedDeferred()
.. js:function:: OctoPrintClient.createRejectedDeferred()
Static method.
Shortcut for creating a rejected `jQuery Deferred <http://api.jquery.com/category/deferred-object/>`_.
.. js:function:: OctoPrint.createCustomException(name)
.. js:function:: OctoPrintClient.createCustomException(name)
Static method.
Creates a custom exception class. ``name`` may be either a function in which case it will be used
as constructor for the new exception class, or a string, in which case a constructor with proper
@@ -397,9 +424,40 @@
.. code-block:: javascript
MyCustomException = OctoPrint.createCustomException("MyCustomException");
MyCustomException = OctoPrintClient.createCustomException("MyCustomException");
throw new MyCustomException("Something went horribly wrong!");
.. js:class:: OctoPrint.InvalidArgumentError
.. js:function:: OctoPrintClient.registerPluginComponent(identifier, clientClass)
Static method.
Registers the plugin client component ``clientClass`` under the name ``identifier`` on the
:js:attr:`OctoPrintClient.plugins` registry.
``clientClass`` must have a constructor that follows the signature ``ClientClass(base)`` and in which it sets
the attribute ``base`` on the instance to:
.. code-block:: javascript
var MyPluginClient = function(base) {
this.base = base;
}
Each :js:class:`OctoPrintClient` will create its own instance of registered plugin classes and make them available
under :js:attr:`OctoPrintClient.plugins`. It will inject itself into those instances in order to allow plugin
clients to access its functionality via ``this.base``:
.. code-block:: javascript
MyPluginClient.prototype.doSomething = function(data, opts) {
return this.base.simpleApiCommand("myplugin", "doSomething", data, opts);
};
:param string identifier: The identifier of the plugin for which ``clientClass`` is the client
:param class clientClass: The client class to register. Constructor must follow the signature ``ClientClass(base)``
where ``base`` will be assigned to the instance as ``this.base`` and be the :js:class:`OctoPrintClient`
instance to use for API calls etc via ``this.base``.
.. js:class:: OctoPrintClient.InvalidArgumentError
Exception to use when functions are called with invalid arguments.
+6 -6
View File
@@ -1,9 +1,9 @@
.. sec-jsclientlib-browser:
.. _sec-jsclientlib-browser:
:mod:`OctoPrint.browser`
------------------------
:mod:`OctoPrintClient.browser`
------------------------------
.. js:function:: OctoPrint.browser.login(username, password, remember, opts)
.. js:function:: OctoPrintClient.browser.login(username, password, remember, opts)
Logs the browser into OctoPrint, using the provided ``username`` and
``password`` as credentials. If ``remember`` is set to ``true``, the session
@@ -24,7 +24,7 @@
:param object opts: Additional request options
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.browser.passiveLogin(opts)
.. js:function:: OctoPrintClient.browser.passiveLogin(opts)
Tries to perform a passive login into OctoPrint, using existing session data
stored in the browser's cookies.
@@ -32,7 +32,7 @@
:param object opts: Additional request options
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.browser.logout(opts)
.. js:function:: OctoPrintClient.browser.logout(opts)
Logs the browser out of OctoPrint.
+7 -7
View File
@@ -1,9 +1,9 @@
.. sec-jsclientlib-connection:
.. _sec-jsclientlib-connection:
:mod:`OctoPrint.connection`
---------------------------
:mod:`OctoPrintClient.connection`
---------------------------------
.. js:function:: OctoPrint.connection.getSettings(opts)
.. js:function:: OctoPrintClient.connection.getSettings(opts)
Retrieves the available connection options for connection to a printer.
@@ -12,7 +12,7 @@
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.connection.connect(data, opts)
.. js:function:: OctoPrintClient.connection.connect(data, opts)
Connects to the printer, optionally using the provided connection ``data`` as parameters.
@@ -30,7 +30,7 @@
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.connection.disconnect(opts)
.. js:function:: OctoPrintClient.connection.disconnect(opts)
Disconnects from the printer.
@@ -39,7 +39,7 @@
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.connection.fakeAck(opts)
.. js:function:: OctoPrintClient.connection.fakeAck(opts)
Triggers a fake acknowledgement (``ok``) on the printer.
+8 -8
View File
@@ -1,16 +1,16 @@
.. sec-jsclientlib-control:
.. _sec-jsclientlib-control:
:mod:`OctoPrint.control`
------------------------
:mod:`OctoPrintClient.control`
------------------------------
.. js:function:: OctoPrint.control.getCustomControls(opts)
.. js:function:: OctoPrintClient.control.getCustomControls(opts)
Retrieves the defined custom controls from the server.
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.control.sendGcode(commands, opts)
.. js:function:: OctoPrintClient.control.sendGcode(commands, opts)
Sends the provided ``commands`` to the printer.
@@ -21,7 +21,7 @@
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.control.sendGcodeWithParameters(commands, parameters, opts)
.. js:function:: OctoPrintClient.control.sendGcodeWithParameters(commands, parameters, opts)
Sends the provided ``commands`` to the printer, replacing contained placeholders with
the provided ``parameters`` first.
@@ -34,7 +34,7 @@
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.control.sendGcodeScript(script, context, opts)
.. js:function:: OctoPrintClient.control.sendGcodeScript(script, context, opts)
Sends the provided ``script`` to the printer, enhancing the template with the
specified ``context``.
@@ -44,7 +44,7 @@
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.control.sendGcodeScriptWithParameters(script, context, parameters, opts)
.. js:function:: OctoPrintClient.control.sendGcodeScriptWithParameters(script, context, parameters, opts)
Sends the provided ``script`` to the printer, enhancing the template with the
specified ``context`` and ``parameters``.
+16 -16
View File
@@ -1,9 +1,9 @@
.. sec-jsclientlib-files:
.. _sec-jsclientlib-files:
:mod:`OctoPrint.files`
----------------------
:mod:`OctoPrintClient.files`
----------------------------
.. js:function:: OctoPrint.files.get(location, filename, opts)
.. js:function:: OctoPrintClient.files.get(location, filename, opts)
Retrieves information about the file ``filename`` at ``location``.
@@ -14,7 +14,7 @@
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.files.list(recursively, opts)
.. js:function:: OctoPrintClient.files.list(recursively, opts)
Retrieves a list of all files from the server.
@@ -56,7 +56,7 @@
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.files.listForLocation(location, recursively, opts)
.. js:function:: OctoPrintClient.files.listForLocation(location, recursively, opts)
Retrieves a list of all files stored at the specified ``location`` from the server.
@@ -73,7 +73,7 @@
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.files.select(location, path, print, opts)
.. js:function:: OctoPrintClient.files.select(location, path, print, opts)
Selects a file at ``location`` named ``filename`` for printing. If ``print`` is supplied and
truthy, also starts printing the file immediately.
@@ -86,7 +86,7 @@
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.files.slice(location, path, parameters, opts)
.. js:function:: OctoPrintClient.files.slice(location, path, parameters, opts)
Slices a file at ``location`` called ``filename``, using the supplied slice command ``parameters``.
@@ -98,7 +98,7 @@
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.files.delete(location, path, opts)
.. js:function:: OctoPrintClient.files.delete(location, path, opts)
Deletes the file or folder at ``location`` and ``path``.
@@ -109,7 +109,7 @@
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.files.copy(location, path, destination, opts)
.. js:function:: OctoPrintClient.files.copy(location, path, destination, opts)
Copies file or folder ``path`` on ``location`` to new parent folder ``destination`` on ``location``.
@@ -129,7 +129,7 @@
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.files.move(location, filename, destination, opts)
.. js:function:: OctoPrintClient.files.move(location, filename, destination, opts)
Moves file or folder ``path`` on ``location`` to new parent folder ``destination`` on ``location``.
@@ -149,7 +149,7 @@
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.files.createFolder(location, name, path, opts)
.. js:function:: OctoPrintClient.files.createFolder(location, name, path, opts)
Creates a new folder ``name`` on ``location``. If ``path`` is provided and not empty the folder
will be created as a new child of it.
@@ -173,7 +173,7 @@
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.files.upload(location, file, data)
.. js:function:: OctoPrintClient.files.upload(location, file, data)
Uploads a ``file`` to the specified ``location``.
@@ -200,7 +200,7 @@
:param object or string file: The file to upload, see :js:func:`OctoPrint.upload` for more details
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.files.download(location, path, opts)
.. js:function:: OctoPrintClient.files.download(location, path, opts)
Downloads the file at ``path`` in ``location``.
@@ -222,7 +222,7 @@
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.files.pathForEntry(entry)
.. js:function:: OctoPrintClient.files.pathForEntry(entry)
Utility function to retrieve the path within its location for a given ``entry``.
@@ -242,7 +242,7 @@
:param object entry: The entry object for which to retrieve the path
:returns string: The path of the entry within its location
.. js:function:: OctoPrint.files.entryForPath(path, root)
.. js:function:: OctoPrintClient.files.entryForPath(path, root)
Utility function to retrieve an entry by its ``path`` based on an entry tree provided by its
``root``.
+35
View File
@@ -43,6 +43,41 @@ because the library depends on those to be available (as ``$`` and ``_``). You c
Note that all components depend on the ``base`` component to be present, so if you are only including a select
number of components, make sure to at the very least include that one to be able to utilize the client.
When you import the client library as described above, a global variable ``OctoPrint`` will become available, which is
a prepared instance of the ``OctoPrintClient`` class the library assembles from registered components. You can directly
used that singular ``OctoPrint`` instance if you only need to talk to one OctoPrint server:
.. code-block:: javascript
OctoPrint.options.baseurl = "http://example.com/octoprint/"
OctoPrint.options.apikey = "apikey";
OctoPrint.files.list()
.done(function(response) {
// do something with the response
});
If you want to access multiple servers, you should however instead instantiate your own clients. You can provide the
connection options (``baseurl`` and ``apikey``) directly in the constructor or set them later:
.. code-block:: javascript
var client1 = new OctoPrintClient({baseurl: "http://example.com/octoprint1/", apikey: "apikey1"});
var client2 = new OctoPrintClient();
client2.options.baseurl = "http://example.com/octoprint2/";
client2.options.apikey = "apikey2";
client1.files.list()
.done(function(response) {
// do something with the response for server 1
});
client2.files.list()
.done(function(response) {
// do something with the response for server 2
});
.. seealso::
`OctoPrint-ForceLogin <https://github.com/OctoPrint/OctoPrint-ForceLogin>`_
+10 -10
View File
@@ -1,9 +1,9 @@
.. sec-jsclientlib-job:
.. _sec-jsclientlib-job:
:mod:`OctoPrint.job`
--------------------
:mod:`OctoPrintClient.job`
--------------------------
.. js:function:: OctoPrint.job.get(opts)
.. js:function:: OctoPrintClient.job.get(opts)
Retrieves information about the current job.
@@ -12,7 +12,7 @@
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.job.start(opts)
.. js:function:: OctoPrintClient.job.start(opts)
Starts the current job.
@@ -21,7 +21,7 @@
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.job.cancel(opts)
.. js:function:: OctoPrintClient.job.cancel(opts)
Cancels the current job.
@@ -30,7 +30,7 @@
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.job.restart(opts)
.. js:function:: OctoPrintClient.job.restart(opts)
Restarts the current job. This is equivalent to cancelling and immediately restarting
the job.
@@ -53,7 +53,7 @@
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.job.pause(opts)
.. js:function:: OctoPrintClient.job.pause(opts)
Pauses the current job if it's running, does nothing if it's already paused.
@@ -62,7 +62,7 @@
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.job.resume(opts)
.. js:function:: OctoPrintClient.job.resume(opts)
Resumes the current job if it's currently pause, does nothing if it's running.
@@ -71,7 +71,7 @@
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.job.togglePause(opts)
.. js:function:: OctoPrintClient.job.togglePause(opts)
Resumes a paused and pauses a running job.
+6 -6
View File
@@ -1,28 +1,28 @@
.. sec-jsclientlib-languages:
.. _sec-jsclientlib-languages:
:mod:`OctoPrint.languages`
--------------------------
:mod:`OctoPrintClient.languages`
--------------------------------
.. note::
All methods here require that the used API token or a the existing browser session
has admin rights.
.. js:function:: OctoPrint.languages.list(opts)
.. js:function:: OctoPrintClient.languages.list(opts)
Retrieves a list of available language packs.
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.languages.upload(file)
.. js:function:: OctoPrintClient.languages.upload(file)
Uploads a language pack.
:param object or string file: The file to upload, see :js:func:`OctoPrint.upload` for more details
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.languages.delete(locale, pack, opts)
.. js:function:: OctoPrintClient.languages.delete(locale, pack, opts)
Deletes the language pack ``pack`` for the specified locale ``locale``.
+6 -6
View File
@@ -1,14 +1,14 @@
.. sec-jsclientlib-logs:
.. _sec-jsclientlib-logs:
:mod:`OctoPrint.logs`
---------------------
:mod:`OctoPrintClient.logs`
---------------------------
.. note::
All methods here require that the used API token or a the existing browser session
has admin rights.
.. js:function:: OctoPrint.logs.list(opts)
.. js:function:: OctoPrintClient.logs.list(opts)
Retrieves a list of log files.
@@ -17,7 +17,7 @@
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.logs.delete(path, opts)
.. js:function:: OctoPrintClient.logs.delete(path, opts)
Deletes the specified log ``path``.
@@ -27,7 +27,7 @@
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.logs.download(path, opts)
.. js:function:: OctoPrintClient.logs.download(path, opts)
Downloads the specified log ``file``.
+20 -20
View File
@@ -1,7 +1,7 @@
.. sec-jsclientlib-printer:
.. _sec-jsclientlib-printer:
:mod:`OctoPrint.printer`
------------------------
:mod:`OctoPrintClient.printer`
------------------------------
.. note::
@@ -15,7 +15,7 @@
.. contents::
:local:
.. js:function:: OctoPrint.printer.getFullState(flags, opts)
.. js:function:: OctoPrintClient.printer.getFullState(flags, opts)
Retrieves the full printer state, including temperature information, sd state and general
printer state.
@@ -34,7 +34,7 @@
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.printer.getToolState(flags, opts)
.. js:function:: OctoPrintClient.printer.getToolState(flags, opts)
Retrieves the current printer extruder state/temperature information, and optionally also the temperature
history.
@@ -52,7 +52,7 @@
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.printer.setToolTargetTemperatures(targets, opts)
.. js:function:: OctoPrintClient.printer.setToolTargetTemperatures(targets, opts)
Sets the given temperatures on the printer's extruders.
@@ -72,7 +72,7 @@
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.printer.setToolTemperatureOffsets(offsets, opts)
.. js:function:: OctoPrintClient.printer.setToolTemperatureOffsets(offsets, opts)
Sets the given temperature offsets for the printer's extruders.
@@ -93,7 +93,7 @@
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.printer.selectTool(tool, opts)
.. js:function:: OctoPrintClient.printer.selectTool(tool, opts)
Selects the printer's current extruder.
@@ -119,7 +119,7 @@
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.printer.extrude(amount, opts)
.. js:function:: OctoPrintClient.printer.extrude(amount, opts)
Extrudes or retracts ``amount`` mm of filament on the currently selected extruder.
@@ -140,7 +140,7 @@
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.printer.setFlowrate(factor, opts)
.. js:function:: OctoPrintClient.printer.setFlowrate(factor, opts)
Sets the current flowrate multiplier.
@@ -152,7 +152,7 @@
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.printer.getBedState(data, opts)
.. js:function:: OctoPrintClient.printer.getBedState(data, opts)
Retrieves the current printer bed state/temperature information, and optionally also the temperature
history.
@@ -170,7 +170,7 @@
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.printer.setBedTargetTemperature(target, opts)
.. js:function:: OctoPrintClient.printer.setBedTargetTemperature(target, opts)
Sets the given temperature on the printer's heated bed (if available).
@@ -190,7 +190,7 @@
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.printer.setBedTemperatureOffset(offset, opts)
.. js:function:: OctoPrintClient.printer.setBedTemperatureOffset(offset, opts)
Sets the given temperature offset for the printer's heated bed (if available).
@@ -210,7 +210,7 @@
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.printer.jog(amounts, opts)
.. js:function:: OctoPrintClient.printer.jog(amounts, opts)
Jogs the specified axes by the specified ``amounts``.
@@ -237,7 +237,7 @@
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.printer.home(axes, opts)
.. js:function:: OctoPrintClient.printer.home(axes, opts)
Homes the specified ``axes``.
@@ -263,7 +263,7 @@
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.printer.setFeedrate(factor, opts)
.. js:function:: OctoPrintClient.printer.setFeedrate(factor, opts)
Sets the feedrate multiplier to use.
@@ -275,7 +275,7 @@
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.printer.getSdState(opts)
.. js:function:: OctoPrintClient.printer.getSdState(opts)
Retrieves the current ready state of the printer's SD card.
@@ -284,7 +284,7 @@
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.printer.initSd(opts)
.. js:function:: OctoPrintClient.printer.initSd(opts)
Instructs the printer to initialize its SD card (if present).
@@ -293,7 +293,7 @@
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.printer.refreshSd(opts)
.. js:function:: OctoPrintClient.printer.refreshSd(opts)
Instructs the printer to refresh the list of files on the SD card (if present).
@@ -302,7 +302,7 @@
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.printer.releaseSd(opts)
.. js:function:: OctoPrintClient.printer.releaseSd(opts)
Instructs the printer to release its SD card (if present).
+8 -8
View File
@@ -1,22 +1,22 @@
.. sec-jsclientlib-printerprofiles:
.. _sec-jsclientlib-printerprofiles:
:mod:`OctoPrint.printerprofiles`
--------------------------------
:mod:`OctoPrintClient.printerprofiles`
--------------------------------------
.. js:function:: OctoPrint.printerprofiles.list(opts)
.. js:function:: OctoPrintClient.printerprofiles.list(opts)
Retrieves a list of all configured printer profiles.
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.printerprofiles.get(id, opts)
.. js:function:: OctoPrintClient.printerprofiles.get(id, opts)
:param string id: The identifier of the profile to retrieve
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.printerprofiles.add(profile, additional, opts)
.. js:function:: OctoPrintClient.printerprofiles.add(profile, additional, opts)
Adds a new profile to OctoPrint.
@@ -25,7 +25,7 @@
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.printerprofiles.update(id, profile, opts)
.. js:function:: OctoPrintClient.printerprofiles.update(id, profile, opts)
Updates an existing profile in OctoPrint.
@@ -34,7 +34,7 @@
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.printerprofiles.delete(id, opts)
.. js:function:: OctoPrintClient.printerprofiles.delete(id, opts)
Deletes a profile in OctoPrint.
+7 -7
View File
@@ -1,16 +1,16 @@
.. sec-jsclientlib-settings:
.. _sec-jsclientlib-settings:
:mod:`OctoPrint.settings`
-------------------------
:mod:`OctoPrintClient.settings`
-------------------------------
.. js:function:: OctoPrint.settings.get(opts)
.. js:function:: OctoPrintClient.settings.get(opts)
Retrieves the current settings.
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.settings.save(settings, opts)
.. js:function:: OctoPrintClient.settings.save(settings, opts)
Saves the provided ``settings``.
@@ -18,7 +18,7 @@
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.settings.getPluginSettings(plugin, opts)
.. js:function:: OctoPrintClient.settings.getPluginSettings(plugin, opts)
Retrieves the settings of the specified ``plugin``.
@@ -26,7 +26,7 @@
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.settings.savePluginSettings(plugin, settings, opts)
.. js:function:: OctoPrintClient.settings.savePluginSettings(plugin, settings, opts)
Saves the ``settings`` for the specified ``plugin``.
+9 -9
View File
@@ -1,16 +1,16 @@
.. sec-jsclientlib-slicing:
.. _sec-jsclientlib-slicing:
:mod:`OctoPrint.slicing`
------------------------
:mod:`OctoPrintClient.slicing`
------------------------------
.. js:function:: OctoPrint.slicing.listAllSlicersAndProfiles(opts)
.. js:function:: OctoPrintClient.slicing.listAllSlicersAndProfiles(opts)
Retrieves a list of all slicers and their available slicing profiles.
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.slicing.listProfilesForSlicer(slicer, opts)
.. js:function:: OctoPrintClient.slicing.listProfilesForSlicer(slicer, opts)
Retrieves of all slicing profiles for the specified ``slicer``.
@@ -18,7 +18,7 @@
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.slicing.getProfileForSlicer(slicer, profileId, opts)
.. js:function:: OctoPrintClient.slicing.getProfileForSlicer(slicer, profileId, opts)
Retrieves the slicing profile with ``profileId`` for the specified ``slicer``.
@@ -27,7 +27,7 @@
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.slicing.addProfileForSlicer(slicer, profileId, profile, opts)
.. js:function:: OctoPrintClient.slicing.addProfileForSlicer(slicer, profileId, profile, opts)
Adds the profile with identifier ``profileId`` to the specified ``slicer``, using the provided ``profile`` data.
@@ -37,7 +37,7 @@
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.slicing.updateProfileForSlicer(slicer, profileId, profile, opts)
.. js:function:: OctoPrintClient.slicing.updateProfileForSlicer(slicer, profileId, profile, opts)
Updates the profile ``profileId`` for ``slicer`` with the provided ``profile`` data.
@@ -47,7 +47,7 @@
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.slicing.deleteProfileForSlicer(slicer, profileId, opts)
.. js:function:: OctoPrintClient.slicing.deleteProfileForSlicer(slicer, profileId, opts)
Deletes the profile ``profileId`` for ``slicer``.
+15 -15
View File
@@ -1,24 +1,24 @@
.. sec-jsclientlib-socket:
.. _sec-jsclientlib-socket:
:mod:`OctoPrint.socket`
-----------------------
:mod:`OctoPrintClient.socket`
-----------------------------
.. js:data:: OctoPrint.socket.options
.. js:attribute:: OctoPrintClient.socket.options
The socket client's options.
``OctoPrint.socket.options.timeouts``
``OctoPrintClient.socket.options.timeouts``
A list of consecutive timeouts after which to attempt reconnecting to a
disconnected sockets, in seconds. Defaults to ``[1, 1, 2, 3, 5, 8, 13, 20, 40, 100]``.
The default setting here makes the client slowly back off after the first couple of very
fast connection attempts don't succeed, and give up after 10 tries.
``OctoPrint.socket.options.rateSlidingWindowSize``
``OctoPrintClient.socket.options.rateSlidingWindowSize``
Number of last rate measurements to take into account for timing analysis and
communication throttling. See :ref:`Communication Throttling <sec-jsclient-socket-throttling>`
below.
.. js:function:: OctoPrint.socket.connect(opts)
.. js:function:: OctoPrintClient.socket.connect(opts)
Connects the socket client to OctoPrint's `SockJS <http://sockjs.org/>`_ socket.
@@ -27,15 +27,15 @@
:param object opts: Additional options for the SockJS constructor.
.. js:function:: OctoPrint.socket.reconnect()
.. js:function:: OctoPrintClient.socket.reconnect()
Reconnects the socket client. If the socket is currently connected it will be disconnected first.
.. js:function:: OctoPrint.socket.disconnect()
.. js:function:: OctoPrintClient.socket.disconnect()
Disconnects the socket client.
.. js:function:: OctoPrint.socket.onMessage(message, handler)
.. js:function:: OctoPrintClient.socket.onMessage(message, handler)
Registers the ``handler`` for messages of type ``message``.
@@ -60,7 +60,7 @@
:param string message: The type of message for which to register
:param function handler: The handler function
.. js:function:: OctoPrint.socket.sendMessage(type, payload)
.. js:function:: OctoPrintClient.socket.sendMessage(type, payload)
Sends a message of type ``type`` with the provided ``payload`` to the server.
@@ -70,7 +70,7 @@
:param string type: Type of message to send
:param object payload: Payload to send
.. js:function:: OctoPrint.socket.onRateTooLow(measured, minimum)
.. js:function:: OctoPrintClient.socket.onRateTooLow(measured, minimum)
Called by the socket client when the measured message round trip times have been lower than
the current lower processing limit over the full sliding window, indicating that messages
@@ -82,7 +82,7 @@
:param Number measured: Maximal measured message round trip time
:param Number minimum: Lower round trip time limit for keeping the rate
.. js:function:: OctoPrint.socket.onRateTooHigh(measured, maximum)
.. js:function:: OctoPrintClient.socket.onRateTooHigh(measured, maximum)
Called by the socket client when the last measured round trip time was higher than the
current upper procesisng limit, indicating that the messages are now processed slower than
@@ -94,11 +94,11 @@
:param Number measured: Measured message round trip time
:param Number minimum: Upper round trip time limit for keeping the rate
.. js:function:: OctoPrint.socket.increaseRate()
.. js:function:: OctoPrintClient.socket.increaseRate()
Instructs the server to increase the message rate by 500ms.
.. js:function:: OctoPrint.socket.decreaseRate()
.. js:function:: OctoPrintClient.socket.decreaseRate()
Instructs the server to decrease the message rate by 500ms.
+5 -5
View File
@@ -1,21 +1,21 @@
.. sec-jsclientlib-system:
:mod:`OctoPrint.system`
-----------------------
:mod:`OctoPrintClient.system`
-----------------------------
.. note::
All methods here require that the used API token or a the existing browser session
has admin rights.
.. js:function:: OctoPrint.system.getCommands(opts)
.. js:function:: OctoPrintClient.system.getCommands(opts)
Retrieves a list of configured system commands for both ``core`` and ``custom`` sources.
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.system.getCommandsForSource(source, opts)
.. js:function:: OctoPrintClient.system.getCommandsForSource(source, opts)
Retrieves a list of system commands, limiting it to the specified ``source``, which might be
either ``core`` or ``custom``.
@@ -23,7 +23,7 @@
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.system.executeCommand(source, action, opts)
.. js:function:: OctoPrintClient.system.executeCommand(source, action, opts)
Executes command ``action`` on ``source``.
+13 -13
View File
@@ -1,9 +1,9 @@
.. sec-jsclientlib-timelapse:
.. _sec-jsclientlib-timelapse:
:mod:`OctoPrint.timelapse`
--------------------------
:mod:`OctoPrintClient.timelapse`
--------------------------------
.. js:function:: OctoPrint.timelapse.get(unrendered, opts)
.. js:function:: OctoPrintClient.timelapse.get(unrendered, opts)
Get a list of all timelapses and the current timelapse config.
@@ -13,7 +13,7 @@
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.timelapse.list(opts)
.. js:function:: OctoPrintClient.timelapse.list(opts)
Get the lists of rendered and unrendered timelapses. The returned promis
will be resolved with an object containing the properties ``rendered``
@@ -23,21 +23,21 @@
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.timelapse.listRendered(opts)
.. js:function:: OctoPrintClient.timelapse.listRendered(opts)
Get the list of rendered timelapses.
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.timelapse.listUnrendered(opts)
.. js:function:: OctoPrintClient.timelapse.listUnrendered(opts)
Get the list of unrendered timelapses.
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.timelapse.download(filename, opts)
.. js:function:: OctoPrintClient.timelapse.download(filename, opts)
Download the rendered timelapse ``filename``.
@@ -45,7 +45,7 @@
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.timelapse.delete(filename, opts)
.. js:function:: OctoPrintClient.timelapse.delete(filename, opts)
Delete the rendered timelapse ``filename``.
@@ -53,7 +53,7 @@
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.timelapse.deleteUnrendered(name, opts)
.. js:function:: OctoPrintClient.timelapse.deleteUnrendered(name, opts)
Delete the unrendered timelapse ``name``.
@@ -61,7 +61,7 @@
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.timelapse.renderUnrendered(name, opts)
.. js:function:: OctoPrintClient.timelapse.renderUnrendered(name, opts)
Render the unrendered timelapse ``name``.
@@ -69,14 +69,14 @@
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.timelapse.getConfig(opts)
.. js:function:: OctoPrintClient.timelapse.getConfig(opts)
Get the current timelapse configuration.
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.timelapse.saveConfig(config, opts)
.. js:function:: OctoPrintClient.timelapse.saveConfig(config, opts)
Save the timelapse configuration.
+13 -13
View File
@@ -1,7 +1,7 @@
.. sec-jsclientlib-users:
.. _sec-jsclientlib-users:
:mod:`OctoPrint.users`
----------------------
:mod:`OctoPrintClient.users`
----------------------------
.. note::
@@ -9,7 +9,7 @@
has admin rights *or* corresponds to the user to be modified. Some methods
definitely require admin rights.
.. js:function:: OctoPrint.users.list(opts)
.. js:function:: OctoPrintClient.users.list(opts)
Get a list of all registered users.
@@ -18,7 +18,7 @@
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.users.get(name, opts)
.. js:function:: OctoPrintClient.users.get(name, opts)
Get information about a specific user.
@@ -26,7 +26,7 @@
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.users.add(user, opts)
.. js:function:: OctoPrintClient.users.add(user, opts)
Add a new user.
@@ -36,7 +36,7 @@
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.users.update(name, active, admin, opts)
.. js:function:: OctoPrintClient.users.update(name, active, admin, opts)
Update an existing user.
@@ -48,7 +48,7 @@
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.users.delete(name, opts)
.. js:function:: OctoPrintClient.users.delete(name, opts)
Delete an existing user.
@@ -58,7 +58,7 @@
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.users.changePassword(name, password, opts)
.. js:function:: OctoPrintClient.users.changePassword(name, password, opts)
Change the password for a user.
@@ -67,7 +67,7 @@
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.users.generateApiKey(name, opts)
.. js:function:: OctoPrintClient.users.generateApiKey(name, opts)
Generate a new API key for a user.
@@ -75,7 +75,7 @@
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.users.resetApiKey(name, opts)
.. js:function:: OctoPrintClient.users.resetApiKey(name, opts)
Reset the API key for a user to being unset.
@@ -83,7 +83,7 @@
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.users.getSettings(name, opts)
.. js:function:: OctoPrintClient.users.getSettings(name, opts)
Get the settings for a user.
@@ -91,7 +91,7 @@
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.users.saveSettings(name, settings, opts)
.. js:function:: OctoPrintClient.users.saveSettings(name, settings, opts)
Save the settings for a user.
+7 -7
View File
@@ -1,14 +1,14 @@
.. sec-jsclientlib-util:
.. _sec-jsclientlib-util:
:mod:`OctoPrint.util`
---------------------
:mod:`OctoPrintClient.util`
---------------------------
.. note::
All methods here require that the used API token or a the existing browser session
has admin rights.
.. js:function:: OctoPrint.util.test(command, parameters, opts)
.. js:function:: OctoPrintClient.util.test(command, parameters, opts)
Execute a :ref:`test command <sec-api-util-test>`.
@@ -19,7 +19,7 @@
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.util.testPath(path, additional, opts)
.. js:function:: OctoPrintClient.util.testPath(path, additional, opts)
Test the provided ``path`` for existance. More test criteria supported by the :ref:`path test command <sec-api-util-test-path>`
can be provided via the ``additional`` object.
@@ -59,7 +59,7 @@
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.util.testExecutable(path, opts)
.. js:function:: OctoPrintClient.util.testExecutable(path, opts)
Shortcut to test if a provided ``path`` exists and is executable by OctoPrint.
@@ -95,7 +95,7 @@
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.util.testUrl(url, additional, opts)
.. js:function:: OctoPrintClient.util.testUrl(url, additional, opts)
Test if a URL can be accessed. More test criteria supported by the :ref:`URL test command <sec-api-util-test-url>`
can be provided via the ``additional`` object.
+5 -5
View File
@@ -1,21 +1,21 @@
.. sec-jsclientlib-wizard:
.. _sec-jsclientlib-wizard:
:mod:`OctoPrint.wizard`
-----------------------
:mod:`OctoPrintClient.wizard`
-----------------------------
.. note::
All methods here require that the used API token or a the existing browser session
has admin rights.
.. js:function:: OctoPrint.wizard.get(opts)
.. js:function:: OctoPrintClient.wizard.get(opts)
Retrieve additional data about registered wizards.
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrint.wizard.finish(handled, opts)
.. js:function:: OctoPrintClient.wizard.finish(handled, opts)
Inform wizards that the wizard dialog has been finished.
+11 -5
View File
@@ -58,7 +58,8 @@ class FatalStartupError(BaseException):
def init_platform(basedir, configfile, use_logging_file=True, logging_file=None,
logging_config=None, debug=False, verbosity=0, uncaught_logger=None,
uncaught_handler=None, safe_mode=False, after_preinit_logging=None,
after_settings=None, after_logging=None, after_safe_mode=None):
after_settings=None, after_logging=None, after_safe_mode=None,
after_plugin_manager=None):
kwargs = dict()
logger, recorder = preinit_logging(debug, verbosity, uncaught_logger, uncaught_handler)
@@ -94,6 +95,11 @@ def init_platform(basedir, configfile, use_logging_file=True, logging_file=None,
after_safe_mode(**kwargs)
plugin_manager = init_pluginsystem(settings, safe_mode=safe_mode)
kwargs["plugin_manager"] = plugin_manager
if callable(after_plugin_manager):
after_plugin_manager(**kwargs)
return settings, logger, safe_mode, plugin_manager
@@ -176,7 +182,7 @@ def init_logging(settings, use_logging_file=True, logging_file=None, default_con
"stream": "ext://sys.stdout"
},
"file": {
"class": "octoprint.logging.handlers.CleaningTimedRotatingFileHandler",
"class": "octoprint.logging.handlers.OctoPrintLogHandler",
"level": "DEBUG",
"formatter": "simple",
"when": "D",
@@ -221,6 +227,7 @@ def init_logging(settings, use_logging_file=True, logging_file=None, default_con
if verbosity > 2:
default_config["root"]["level"] = "DEBUG"
config = default_config
if use_logging_file:
# further logging configuration from file...
if logging_file is None:
@@ -233,9 +240,8 @@ def init_logging(settings, use_logging_file=True, logging_file=None, default_con
config_from_file = yaml.safe_load(f)
# we merge that with the default config
config = dict_merge(default_config, config_from_file)
else:
config = default_config
if config_from_file is not None and isinstance(config_from_file, dict):
config = dict_merge(default_config, config_from_file)
# configure logging globally
return set_logging_config(config, debug, verbosity, uncaught_logger, uncaught_handler)
+6 -2
View File
@@ -7,6 +7,7 @@ __copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms
import click
import octoprint
import sys
#~~ click context
@@ -159,8 +160,11 @@ def octo(ctx, **kwargs):
"start|stop|restart\" is deprecated, please use "
"\"octoprint daemon start|stop|restart\" from now on")
from octoprint.cli.server import daemon_command
ctx.invoke(daemon_command, command=daemon, **kwargs)
if sys.platform == "linux2":
from octoprint.cli.server import daemon_command
ctx.invoke(daemon_command, command=daemon, **kwargs)
else:
click.echo("Sorry, daemon mode is only supported under Linux right now")
else:
click.echo("Starting the server via \"octoprint\" is deprecated, "
"please use \"octoprint serve\" from now on.")
+89 -62
View File
@@ -17,20 +17,24 @@ def run_server(basedir, configfile, host, port, debug, allow_root, logging_confi
from octoprint import init_platform, __display_version__, FatalStartupError
def log_startup(recorder=None, safe_mode=None, **kwargs):
from octoprint.logging import get_divider_line
logger = logging.getLogger("octoprint.server")
logger.info(get_divider_line("*"))
logger.info("Starting OctoPrint {}".format(__display_version__))
if safe_mode:
logger.info("Starting in SAFE MODE. Third party plugins will be disabled!")
if recorder and len(recorder):
logger.info("--- Logged during platform initialization: ---")
logger.info(get_divider_line("-", "Logged during platform initialization:"))
from octoprint.logging.handlers import CombinedLogHandler
handler = CombinedLogHandler(*logging.getLogger().handlers)
recorder.setTarget(handler)
recorder.flush()
logger.info("----------------------------------------------")
logger.info(get_divider_line("-"))
from octoprint import urllib3_ssl
if not urllib3_ssl:
@@ -41,6 +45,30 @@ def run_server(basedir, configfile, host, port, debug, allow_root, logging_confi
"update to a Python version >= 2.7.9 or alternatively "
"install PyOpenSSL plus its dependencies. For details see "
"https://urllib3.readthedocs.org/en/latest/security.html#openssl-pyopenssl")
logger.info(get_divider_line("*"))
def log_register_rollover(safe_mode=None, plugin_manager=None, **kwargs):
from octoprint.logging import get_handler, log_to_handler, get_divider_line
from octoprint.logging.handlers import OctoPrintLogHandler
def rollover_callback():
handler = get_handler("file")
if handler is None:
return
logger = logging.getLogger("octoprint.server")
def _log(message, level=logging.INFO):
log_to_handler(logger, handler, level, message)
_log(get_divider_line("-", "Log roll over detected"))
_log("OctoPrint {}".format(__display_version__))
if safe_mode:
_log("SAFE MODE is active. Third party plugins are disabled!")
plugin_manager.log_all_plugins(only_to_handler=handler)
_log(get_divider_line("-"))
OctoPrintLogHandler.registerRolloverCallback(rollover_callback)
try:
settings, _, safe_mode, plugin_manager = init_platform(basedir,
@@ -50,7 +78,8 @@ def run_server(basedir, configfile, host, port, debug, allow_root, logging_confi
verbosity=verbosity,
uncaught_logger=__name__,
safe_mode=safe_mode,
after_safe_mode=log_startup)
after_safe_mode=log_startup,
after_plugin_manager=log_register_rollover)
except FatalStartupError as e:
click.echo(e.message, err=True)
click.echo("There was a fatal error starting up OctoPrint.", err=True)
@@ -121,75 +150,73 @@ def serve_command(ctx, **kwargs):
allow_root, logging, verbosity, safe_mode)
@server_commands.command(name="daemon")
@server_options
@daemon_options
@standard_options(hidden=True)
@click.argument("command", type=click.Choice(["start", "stop", "restart", "status"]),
metavar="start|stop|restart|status")
@click.pass_context
def daemon_command(ctx, command, **kwargs):
"""
Starts, stops or restarts in daemon mode.
if sys.platform == "linux2":
# we only support daemon mode under Linux
Please note that daemon mode is only supported under Linux right now.
"""
@server_commands.command(name="daemon")
@server_options
@daemon_options
@standard_options(hidden=True)
@click.argument("command", type=click.Choice(["start", "stop", "restart", "status"]),
metavar="start|stop|restart|status")
@click.pass_context
def daemon_command(ctx, command, **kwargs):
"""
Starts, stops or restarts in daemon mode.
def get_value(key):
return get_ctx_obj_option(ctx, key, kwargs.get(key))
Please note that daemon mode is only supported under Linux right now.
"""
host = get_value("host")
port = get_value("port")
logging = get_value("logging")
allow_root = get_value("allow_root")
debug = get_value("debug")
pid = get_value("pid")
def get_value(key):
return get_ctx_obj_option(ctx, key, kwargs.get(key))
basedir = get_value("basedir")
configfile = get_value("configfile")
verbosity = get_value("verbosity")
safe_mode = get_value("safe_mode")
host = get_value("host")
port = get_value("port")
logging = get_value("logging")
allow_root = get_value("allow_root")
debug = get_value("debug")
pid = get_value("pid")
if sys.platform == "darwin" or sys.platform == "win32":
click.echo("Sorry, daemon mode is only supported under Linux right now",
file=sys.stderr)
sys.exit(2)
basedir = get_value("basedir")
configfile = get_value("configfile")
verbosity = get_value("verbosity")
safe_mode = get_value("safe_mode")
if pid is None:
click.echo("No path to a pidfile set",
file=sys.stderr)
sys.exit(1)
if pid is None:
click.echo("No path to a pidfile set",
file=sys.stderr)
sys.exit(1)
from octoprint.daemon import Daemon
class OctoPrintDaemon(Daemon):
def __init__(self, pidfile, basedir, configfile, host, port, debug, allow_root, logging_config, verbosity, safe_mode):
Daemon.__init__(self, pidfile)
from octoprint.daemon import Daemon
class OctoPrintDaemon(Daemon):
def __init__(self, pidfile, basedir, configfile, host, port, debug, allow_root, logging_config, verbosity, safe_mode):
Daemon.__init__(self, pidfile)
self._basedir = basedir
self._configfile = configfile
self._host = host
self._port = port
self._debug = debug
self._allow_root = allow_root
self._logging_config = logging_config
self._verbosity = verbosity
self._safe_mode = safe_mode
self._basedir = basedir
self._configfile = configfile
self._host = host
self._port = port
self._debug = debug
self._allow_root = allow_root
self._logging_config = logging_config
self._verbosity = verbosity
self._safe_mode = safe_mode
def run(self):
run_server(self._basedir, self._configfile, self._host, self._port, self._debug,
self._allow_root, self._logging_config, self._verbosity, self._safe_mode,
octoprint_daemon=self)
def run(self):
run_server(self._basedir, self._configfile, self._host, self._port, self._debug,
self._allow_root, self._logging_config, self._verbosity, self._safe_mode,
octoprint_daemon=self)
octoprint_daemon = OctoPrintDaemon(pid, basedir, configfile, host, port, debug, allow_root, logging, verbosity,
safe_mode)
octoprint_daemon = OctoPrintDaemon(pid, basedir, configfile, host, port, debug, allow_root, logging, verbosity,
safe_mode)
if command == "start":
octoprint_daemon.start()
elif command == "stop":
octoprint_daemon.stop()
elif command == "restart":
octoprint_daemon.restart()
elif command == "status":
octoprint_daemon.status()
if command == "start":
octoprint_daemon.start()
elif command == "stop":
octoprint_daemon.stop()
elif command == "restart":
octoprint_daemon.restart()
elif command == "status":
octoprint_daemon.status()
+24 -17
View File
@@ -332,24 +332,31 @@ class CommandTrigger(GenericEventListener):
self._executeGcodeCommand(command, debug=debug)
def _executeSystemCommand(self, command, debug=False):
def commandExecutioner(command):
def commandExecutioner(cmd):
if debug:
self._logger.info("Executing system command: %s" % command)
self._logger.info("Executing system command: {}".format(cmd))
else:
self._logger.info("Executing a system command")
# we run this with shell=True since we have to trust whatever
# our admin configured as command and since we want to allow
# shell-alike handling here...
subprocess.Popen(command, shell=True)
subprocess.check_call(cmd, shell=True)
try:
if isinstance(command, (list, tuple, set)):
for c in command:
commandExecutioner(c)
else:
commandExecutioner(command)
except subprocess.CalledProcessError as e:
self._logger.warn("Command failed with return code %i: %s" % (e.returncode, str(e)))
except:
self._logger.exception("Command failed")
def process():
try:
if isinstance(command, (list, tuple, set)):
for c in command:
commandExecutioner(c)
else:
commandExecutioner(command)
except subprocess.CalledProcessError as e:
self._logger.warn("Command failed with return code %i: %s" % (e.returncode, str(e)))
except:
self._logger.exception("Command failed")
t = threading.Thread(target=process)
t.daemon = True
t.start()
def _executeGcodeCommand(self, command, debug=False):
commands = [command]
@@ -397,7 +404,7 @@ class CommandTrigger(GenericEventListener):
currentData = self._printer.get_current_data()
if "currentZ" in currentData.keys() and currentData["currentZ"] is not None:
if "currentZ" in currentData and currentData["currentZ"] is not None:
params["__currentZ"] = str(currentData["currentZ"])
if "job" in currentData and "file" in currentData["job"] and "name" in currentData["job"]["file"] \
@@ -405,9 +412,9 @@ class CommandTrigger(GenericEventListener):
params["__filename"] = currentData["job"]["file"]["name"]
params["__filepath"] = currentData["job"]["file"]["path"]
params["__fileorigin"] = currentData["job"]["file"]["origin"]
if "progress" in currentData.keys() and currentData["progress"] is not None \
and "completion" in currentData["progress"].keys() and currentData["progress"]["completion"] is not None:
params["__progress"] = str(round(currentData["progress"]["completion"] * 100))
if "progress" in currentData and currentData["progress"] is not None \
and "completion" in currentData["progress"] and currentData["progress"]["completion"] is not None:
params["__progress"] = str(round(currentData["progress"]["completion"]))
# now add the payload keys as well
if isinstance(payload, dict):
+32 -6
View File
@@ -205,17 +205,26 @@ class FileManager(object):
# callback was not registered
pass
def _determine_analysis_backlog(self, storage_type, storage_manager):
def _determine_analysis_backlog(self, storage_type, storage_manager, root=None, high_priority=False):
counter = 0
for entry, path, printer_profile in storage_manager.analysis_backlog:
backlog_generator = storage_manager.analysis_backlog
if root is not None:
backlog_generator = storage_manager.analysis_backlog_for_path(path=root)
for entry, path, printer_profile in backlog_generator:
file_type = get_file_type(path)[-1]
file_name = storage_manager.split_path(path)
# we'll use the default printer profile for the backlog since we don't know better
queue_entry = QueueEntry(file_name, entry, file_type, storage_type, path, self._printer_profile_manager.get_default())
if self._analysis_queue.enqueue(queue_entry, high_priority=False):
if self._analysis_queue.enqueue(queue_entry, high_priority=high_priority):
counter += 1
self._logger.info("Added {counter} items from storage type \"{storage_type}\" to analysis queue".format(**locals()))
if root:
self._logger.info("Added {counter} items from storage type \"{storage_type}\" and root \"{root}\" to analysis queue".format(**locals()))
else:
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
@@ -396,6 +405,10 @@ class FileManager(object):
if hook_file_object is not None:
file_object = hook_file_object
queue_entry = self._analysis_queue_entry(destination, path)
self._analysis_queue.dequeue(queue_entry)
file_path = self._storage(destination).add_file(path, file_object, links=links, printer_profile=printer_profile, allow_overwrite=allow_overwrite)
if analysis is None:
@@ -415,13 +428,21 @@ class FileManager(object):
eventManager().fire(Events.UPDATED_FILES, dict(type="printables"))
def copy_file(self, destination, source, dst):
self._storage(destination).copy_file(source, dst)
path = self._storage(destination).copy_file(source, dst)
if not self.has_analysis(destination, path):
queue_entry = self._analysis_queue_entry(destination, path)
if queue_entry:
self._analysis_queue.enqueue(queue_entry)
eventManager().fire(Events.UPDATED_FILES, dict(type="printables"))
def move_file(self, destination, source, dst):
queue_entry = self._analysis_queue_entry(destination, source)
self._analysis_queue.dequeue(queue_entry)
self._storage(destination).move_file(source, dst)
path = self._storage(destination).move_file(source, dst)
if not self.has_analysis(destination, path):
queue_entry = self._analysis_queue_entry(destination, path)
if queue_entry:
self._analysis_queue.enqueue(queue_entry)
eventManager().fire(Events.UPDATED_FILES, dict(type="printables"))
def add_folder(self, destination, path, ignore_existing=True):
@@ -438,15 +459,20 @@ class FileManager(object):
def copy_folder(self, destination, source, dst):
self._storage(destination).copy_folder(source, dst)
self._determine_analysis_backlog(destination, self._storage(destination), root=dst)
eventManager().fire(Events.UPDATED_FILES, dict(type="printables"))
def move_folder(self, destination, source, dst):
self._analysis_queue.dequeue_folder(destination, source)
self._analysis_queue.pause()
self._storage(destination).move_folder(source, dst)
self._determine_analysis_backlog(destination, self._storage(destination), root=dst)
self._analysis_queue.resume()
eventManager().fire(Events.UPDATED_FILES, dict(type="printables"))
def has_analysis(self, destination, path):
return self._storage(destination).has_analysis(path)
def get_metadata(self, destination, path):
return self._storage(destination).get_metadata(path)
+5 -2
View File
@@ -308,9 +308,12 @@ class GcodeAnalysisQueue(AbstractAnalysisQueue):
def _do_analysis(self, high_priority=False):
try:
throttle = settings().getFloat(["gcodeAnalysis", "throttle_highprio"]) if high_priority else settings().getFloat(["gcodeAnalysis", "throttle_normalprio"])
throttle_lines = settings().getInt(["gcodeAnalysis", "throttle_lines"])
if throttle > 0:
def throttle_callback():
time.sleep(throttle)
def throttle_callback(filePos, readBytes):
if filePos % throttle_lines == 0:
# only apply throttle every 100 lines
time.sleep(throttle)
else:
throttle_callback = None
+45 -1
View File
@@ -44,6 +44,11 @@ class StorageInterface(object):
return
yield
def analysis_backlog_for_path(self, path=None):
# empty generator pattern, yield is intentionally unreachable
return
yield
def last_modified(self, path=None, recursive=False):
"""
Get the last modification date of the specified ``path`` or ``path``'s subtree.
@@ -174,6 +179,8 @@ class StorageInterface(object):
:param string source: path to the source folder
:param string destination: path to destination
:return: the path in the storage to the copy of the folder
"""
raise NotImplementedError()
@@ -183,6 +190,8 @@ class StorageInterface(object):
:param string source: path to the source folder
:param string destination: path to destination
:return: the new path in the storage to the folder
"""
raise NotImplementedError()
@@ -216,6 +225,8 @@ class StorageInterface(object):
:param string source: path to the source file
:param string destination: path to destination
:return: the path in the storage to the copy of the file
"""
raise NotImplementedError()
@@ -225,6 +236,16 @@ class StorageInterface(object):
:param string source: path to the source file
:param string destination: path to destination
:return: the new path in the storage to the file
"""
raise NotImplementedError()
def has_analysis(self, path):
"""
Returns whether the file at path has been analysed yet
:param path: virtual path to the file for which to retrieve the metadata
"""
raise NotImplementedError()
@@ -462,7 +483,10 @@ class LocalFileStorage(StorageInterface):
@property
def analysis_backlog(self):
for entry in self._analysis_backlog_generator():
return self.analysis_backlog_for_path()
def analysis_backlog_for_path(self, path=None):
for entry in self._analysis_backlog_generator(path):
yield entry
def _analysis_backlog_generator(self, path=None):
@@ -604,6 +628,8 @@ class LocalFileStorage(StorageInterface):
except Exception as e:
raise StorageError("Could not copy %s in %s to %s in %s" % (source_data["name"], source_data["path"], destination_data["name"], destination_data["path"]), cause=e)
return self.path_in_storage(destination_data["fullpath"])
def move_folder(self, source, destination):
source_data, destination_data = self._get_source_destination_data(source, destination)
@@ -614,6 +640,8 @@ class LocalFileStorage(StorageInterface):
self._delete_metadata(source_data["fullpath"])
return self.path_in_storage(destination_data["fullpath"])
def add_file(self, path, file_object, printer_profile=None, links=None, allow_overwrite=False):
path, name = self.sanitize(path)
if not octoprint.filemanager.valid_file_type(name):
@@ -687,6 +715,8 @@ class LocalFileStorage(StorageInterface):
self._copy_metadata_entry(source_data["path"], source_data["name"],
destination_data["path"], destination_data["name"])
return self.path_in_storage(destination_data["fullpath"])
def move_file(self, source, destination, allow_overwrite=False):
source_data, destination_data = self._get_source_destination_data(source, destination)
@@ -699,6 +729,12 @@ class LocalFileStorage(StorageInterface):
destination_data["path"], destination_data["name"],
delete_source=True)
return self.path_in_storage(destination_data["fullpath"])
def has_analysis(self, path):
metadata = self.get_metadata(path)
return "analysis" in metadata
def get_metadata(self, path):
path, name = self.sanitize(path)
return self._get_metadata_entry(path, name)
@@ -946,7 +982,15 @@ class LocalFileStorage(StorageInterface):
continue
printer_profile = history_entry["printerProfile"]
if not printer_profile:
continue
print_time = history_entry["printTime"]
try:
print_time = float(print_time)
except:
self._logger.warn("Invalid print time value found in print history for {} in {}/.metadata.yaml: {!r}".format(name, path, print_time))
continue
if not printer_profile in former_print_times:
former_print_times[printer_profile] = []
+134 -1
View File
@@ -1,4 +1,137 @@
# coding=utf-8
from __future__ import absolute_import
from . import handlers
from octoprint.logging import handlers
def log_to_handler(logger, handler, level, msg, exc_info=None, extra=None, *args):
"""
Logs to the provided handler only.
Arguments:
logger: logger to log to
handler: handler to restrict logging to
level: level to log at
msg: message to log
exc_info: optional exception info
extra: optional extra data
*args: log args
"""
from logging import _srcfile
import sys
# this is just the same as logging.Logger._log
if _srcfile:
# IronPython doesn't track Python frames, so findCaller raises an
# exception on some versions of IronPython. We trap it here so that
# IronPython can use logging.
try:
fn, lno, func = logger.findCaller()
except ValueError:
fn, lno, func = "(unknown file)", 0, "(unknown function)"
else:
fn, lno, func = "(unknown file)", 0, "(unknown function)"
if exc_info:
if not isinstance(exc_info, tuple):
exc_info = sys.exc_info()
record = logger.makeRecord(logger.name, level, fn, lno, msg, args, exc_info, func, extra)
# and this is a mixture of logging.Logger.handle and logging.Logger.callHandlers
if (not logger.disabled) and logger.filter(record):
if record.levelno >= handler.level:
handler.handle(record)
def get_handler(name, logger=None):
"""
Retrieves the handler named ``name``.
If optional ``logger`` is provided, search will be
limited to that logger, otherwise the root logger will be
searched.
Arguments:
name: the name of the handler to look for
logger: (optional) the logger to search in, root logger if not provided
Returns:
the handler if it could be found, None otherwise
"""
import logging
if logger is None:
logger = logging.getLogger()
for handler in logger.handlers:
if handler.get_name() == name:
return handler
return None
def get_divider_line(c, message=None, length=78, indent=3):
"""
Generate a divider line for logging, optionally with included message.
Examples:
>>> get_divider_line("-")
'------------------------------------------------------------------------------'
>>> get_divider_line("=", length=10)
'=========='
>>> get_divider_line("-", message="Hi", length=10)
'--- Hi ---'
>>> get_divider_line("-", message="A slightly longer text")
'--- A slightly longer text ---------------------------------------------------'
>>> get_divider_line("-", message="A slightly longer text", indent=5)
'----- A slightly longer text -------------------------------------------------'
>>> get_divider_line("-", message="Hello World!", length=10)
'--- Hello World!'
>>> get_divider_line(None)
Traceback (most recent call last):
...
AssertionError: c is not text
>>> get_divider_line("´`")
Traceback (most recent call last):
...
AssertionError: c is not a single character
>>> get_divider_line("-", message=3)
Traceback (most recent call last):
...
AssertionError: message is not text
>>> get_divider_line("-", length="hello")
Traceback (most recent call last):
...
AssertionError: length is not an int
>>> get_divider_line("-", indent="hi")
Traceback (most recent call last):
...
AssertionError: indent is not an int
Arguments:
c: character to use for the line
message: message to print in the line
length: length of the line
indent: indentation of message in line
Returns:
formatted divider line
"""
assert isinstance(c, (str, unicode, bytes)), "c is not text"
assert len(c) == 1, "c is not a single character"
assert isinstance(length, int), "length is not an int"
assert isinstance(indent, int), "indent is not an int"
if message is None:
return c * length
assert isinstance(message, (str, unicode, bytes)), "message is not text"
space = length - 2 * (indent + 1)
if space >= len(message):
return c * indent + " " + message + " " + c * (length - indent - 2 - len(message))
else:
return c * indent + " " + message
+15
View File
@@ -17,6 +17,21 @@ class CleaningTimedRotatingFileHandler(logging.handlers.TimedRotatingFileHandler
os.remove(s)
class OctoPrintLogHandler(CleaningTimedRotatingFileHandler):
rollover_callbacks = []
@classmethod
def registerRolloverCallback(cls, callback, *args, **kwargs):
cls.rollover_callbacks.append((callback, args, kwargs))
def doRollover(self):
CleaningTimedRotatingFileHandler.doRollover(self)
for rcb in self.__class__.rollover_callbacks:
callback, args, kwargs = rcb
callback(*args, **kwargs)
class SerialLogHandler(logging.handlers.RotatingFileHandler):
_do_rollover = False
+20 -11
View File
@@ -1062,21 +1062,30 @@ class PluginManager(object):
return True
def log_all_plugins(self, show_bundled=True, bundled_str=(" (bundled)", ""), show_location=True, location_str=" = {location}", show_enabled=True, enabled_str=(" ", "!")):
def log_all_plugins(self, show_bundled=True, bundled_str=(" (bundled)", ""), show_location=True,
location_str=" = {location}", show_enabled=True, enabled_str=(" ", "!"),
only_to_handler=None):
all_plugins = self.enabled_plugins.values() + self.disabled_plugins.values()
def _log(message, level=logging.INFO):
if only_to_handler is not None:
import octoprint.logging
octoprint.logging.log_to_handler(self.logger, only_to_handler, level, message, [])
else:
self.logger.log(level, message)
if len(all_plugins) <= 0:
self.logger.info("No plugins available")
_log("No plugins available")
else:
self.logger.info("{count} plugin(s) registered with the system:\n{plugins}".format(count=len(all_plugins), plugins="\n".join(
map(lambda x: "| " + x.long_str(show_bundled=show_bundled,
bundled_strs=bundled_str,
show_location=show_location,
location_str=location_str,
show_enabled=show_enabled,
enabled_strs=enabled_str),
sorted(self.plugins.values(), key=lambda x: str(x).lower()))
)))
formatted_plugins = "\n".join(map(lambda x: "| " + x.long_str(show_bundled=show_bundled,
bundled_strs=bundled_str,
show_location=show_location,
location_str=location_str,
show_enabled=show_enabled,
enabled_strs=enabled_str),
sorted(self.plugins.values(), key=lambda x: str(x).lower())))
_log("{count} plugin(s) registered with the system:\n{plugins}".format(count=len(all_plugins),
plugins=formatted_plugins))
def get_plugin(self, identifier, require_enabled=True):
"""
+35 -1
View File
@@ -746,6 +746,21 @@ class UiPlugin(OctoPrintPlugin, SortablePlugin):
"""
return None
def get_ui_additional_etag(self, default_additional):
"""
Allows to provide a list of additional fields to use for ETag generation.
By default the same list will be returned that is also used in the stock UI (and injected
via the parameter ``default_additional``).
Arguments:
default_additional (list): The list of default fields added to the ETag of the default UI
Returns:
(list): A list of additional fields for the ETag generation, or None
"""
return default_additional
def get_ui_custom_lastmodified(self):
"""
Allows to calculate the LastModified differently than using the most recent modification
@@ -806,6 +821,25 @@ class UiPlugin(OctoPrintPlugin, SortablePlugin):
"""
return False
def get_ui_custom_template_filter(self, default_template_filter):
"""
Allows to specify a custom template filter to use for filtering the template contained in the
``render_kwargs`` provided to the templating sub system.
Only relevant for UiPlugins that actually utilize the stock templates of OctoPrint.
By default simply returns the provided ``default_template_filter``.
Arguments:
default_template_filter (callable): The default template filter used by the default UI
Returns:
(callable) A filter function accepting the ``template_type`` and ``template_key`` of a template
and returning ``True`` to keep it and ``False`` to filter it out. If ``None`` is returned, no
filtering will take place.
"""
return default_template_filter
class WizardPlugin(OctoPrintPlugin, ReloadNeedingPlugin):
"""
The ``WizardPlugin`` mixin allows plugins to report to OctoPrint whether
@@ -1515,7 +1549,7 @@ class SettingsPlugin(OctoPrintPlugin):
path=dict(to=dict(never=dict(return="return"))))
def get_settings_restricted_path(self):
return dict(admin=[["some", "admin_only", "path], ["another", "admin_only", "path"],
return dict(admin=[["some", "admin_only", "path"], ["another", "admin_only", "path"],
user=[["some", "user_only", "path"],],
never=[["path", "to", "never", "return"],])
+25 -14
View File
@@ -34,6 +34,10 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
ARCHIVE_EXTENSIONS = (".zip", ".tar.gz", ".tgz", ".tar")
OPERATING_SYSTEMS = dict(windows=["win32"],
linux=["linux2"],
macos=["darwin"])
pip_inapplicable_arguments = dict(uninstall=["--user"])
def __init__(self):
@@ -609,10 +613,10 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
)
if "compatibility" in entry:
if "octoprint" in entry["compatibility"] and entry["compatibility"]["octoprint"] is not None and len(entry["compatibility"]["octoprint"]):
if "octoprint" in entry["compatibility"] and entry["compatibility"]["octoprint"] is not None and isinstance(entry["compatibility"]["octoprint"], (list, tuple)) and len(entry["compatibility"]["octoprint"]):
result["is_compatible"]["octoprint"] = self._is_octoprint_compatible(octoprint_version, entry["compatibility"]["octoprint"])
if "os" in entry["compatibility"] and entry["compatibility"]["os"] is not None and len(entry["compatibility"]["os"]):
if "os" in entry["compatibility"] and entry["compatibility"]["os"] is not None and isinstance(entry["compatibility"]["os"], (list, tuple)) and len(entry["compatibility"]["os"]):
result["is_compatible"]["os"] = self._is_os_compatible(current_os, entry["compatibility"]["os"])
return result
@@ -626,12 +630,15 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
"""
for octo_compat in compatibility_entries:
if not any(octo_compat.startswith(c) for c in ("<", "<=", "!=", "==", ">=", ">", "~=", "===")):
octo_compat = ">={}".format(octo_compat)
try:
if not any(octo_compat.startswith(c) for c in ("<", "<=", "!=", "==", ">=", ">", "~=", "===")):
octo_compat = ">={}".format(octo_compat)
s = next(pkg_resources.parse_requirements("OctoPrint" + octo_compat))
if octoprint_version in s:
break
s = next(pkg_resources.parse_requirements("OctoPrint" + octo_compat))
if octoprint_version in s:
break
except:
self._logger.exception("Something is wrong with this compatibility string for OctoPrint: {}".format(octo_compat))
else:
return False
@@ -641,15 +648,12 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
"""
Tests if the ``current_os`` matches any of the provided ``compatibility_entries``.
"""
return current_os in compatibility_entries
return current_os in filter(lambda x: x in self.__class__.OPERATING_SYSTEMS.keys(), compatibility_entries)
def _get_os(self):
if sys.platform == "win32":
return "windows"
elif sys.platform == "linux2":
return "linux"
elif sys.platform == "darwin":
return "macos"
for identifier, platforms in self.__class__.OPERATING_SYSTEMS.items():
if sys.platform in platforms:
return identifier
else:
return "unknown"
@@ -663,6 +667,13 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
octoprint_version_string = octoprint_version_string[:octoprint_version_string.find("-")]
octoprint_version = pkg_resources.parse_version(octoprint_version_string)
# A leading v is common in github release tags and old setuptools doesn't remove it. While OctoPrint's
# versions should never contains such a prefix, we'll make sure to have stuff behave the same
# regardless of setuptools version anyhow.
if octoprint_version and isinstance(octoprint_version, tuple) and octoprint_version[0].lower() == "*v":
octoprint_version = octoprint_version[1:]
if base:
if isinstance(octoprint_version, tuple):
# old setuptools
@@ -1,68 +1,71 @@
(function (global, factory) {
if (typeof define === "function" && define.amd) {
define(["OctoPrint"], factory);
define(["OctoPrintClient"], factory);
} else {
factory(window.OctoPrint);
factory(global.OctoPrintClient);
}
})(window || this, function(OctoPrint) {
var exports = {};
exports.get = function(refresh, opts) {
return OctoPrint.get(OctoPrint.getSimpleApiUrl("pluginmanager") + ((refresh) ? "?refresh_repository=true" : ""), opts);
})(this, function(OctoPrintClient) {
var OctoPrintPluginManagerClient = function(base) {
this.base = base;
};
exports.getWithRefresh = function(opts) {
return exports.get(true, opts);
OctoPrintPluginManagerClient.prototype.get = function(refresh, opts) {
return this.base.get(this.base.getSimpleApiUrl("pluginmanager") + ((refresh) ? "?refresh_repository=true" : ""), opts);
};
exports.getWithoutRefresh = function(opts) {
return exports.get(false, opts);
OctoPrintPluginManagerClient.prototype.getWithRefresh = function(opts) {
return this.get(true, opts);
};
exports.install = function(pluginUrl, dependencyLinks, opts) {
OctoPrintPluginManagerClient.prototype.getWithoutRefresh = function(opts) {
return this.get(false, opts);
};
OctoPrintPluginManagerClient.prototype.install = function(pluginUrl, dependencyLinks, opts) {
var data = {
url: pluginUrl,
dependency_links: !!dependencyLinks
};
return OctoPrint.simpleApiCommand("pluginmanager", "install", data, opts);
return this.base.simpleApiCommand("pluginmanager", "install", data, opts);
};
exports.reinstall = function(plugin, pluginUrl, dependencyLinks, opts) {
OctoPrintPluginManagerClient.prototype.reinstall = function(plugin, pluginUrl, dependencyLinks, opts) {
var data = {
url: pluginUrl,
dependency_links: !!dependencyLinks,
reinstall: plugin,
force: true
};
return OctoPrint.simpleApiCommand("pluginmanager", "install", data, opts);
return this.base.simpleApiCommand("pluginmanager", "install", data, opts);
};
exports.uninstall = function(plugin, opts) {
OctoPrintPluginManagerClient.prototype.uninstall = function(plugin, opts) {
var data = {
plugin: plugin
};
return OctoPrint.simpleApiCommand("pluginmanager", "uninstall", data, opts);
return this.base.simpleApiCommand("pluginmanager", "uninstall", data, opts);
};
exports.enable = function(plugin, opts) {
OctoPrintPluginManagerClient.prototype.enable = function(plugin, opts) {
var data = {
plugin: plugin
};
return OctoPrint.simpleApiCommand("pluginmanager", "enable", data, opts);
return this.base.simpleApiCommand("pluginmanager", "enable", data, opts);
};
exports.disable = function(plugin, opts) {
OctoPrintPluginManagerClient.prototype.disable = function(plugin, opts) {
var data = {
plugin: plugin
};
return OctoPrint.simpleApiCommand("pluginmanager", "disable", data, opts);
return this.base.simpleApiCommand("pluginmanager", "disable", data, opts);
};
exports.upload = function(file) {
return OctoPrint.upload(OctoPrint.getBlueprintUrl("pluginmanager") + "upload_archive", file);
OctoPrintPluginManagerClient.prototype.upload = function(file) {
return this.base.upload(this.base.getBlueprintUrl("pluginmanager") + "upload_archive", file);
};
OctoPrint.plugins.pluginmanager = exports;
OctoPrintClient.registerPluginComponent("pluginmanager", OctoPrintPluginManagerClient);
return OctoPrintPluginManagerClient;
});
$(function() {
+155 -84
View File
@@ -21,7 +21,7 @@ from . import version_checks, updaters, exceptions, util, cli
from octoprint.server.util.flask import restricted_access, with_revalidation_checking, check_etag
from octoprint.server import admin_permission, VERSION, REVISION, BRANCH
from octoprint.util import dict_merge
from octoprint.util import dict_merge, to_unicode
import octoprint.settings
@@ -40,6 +40,8 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
self._configured_checks = None
self._refresh_configured_checks = False
self._get_versions_mutex = threading.Lock()
self._version_cache = dict()
self._version_cache_ttl = 0
self._version_cache_path = None
@@ -70,24 +72,62 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
self._console_logger.setLevel(logging.DEBUG)
self._console_logger.propagate = False
def on_after_startup(self):
# refresh cache now if necessary so it's faster once the user connects to the instance
self.get_current_versions()
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")
check_providers = self._settings.get(["check_providers"], merged=True)
effective_configs = dict()
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():
for key, default_config in hook_checks.items():
if key in effective_configs or key == "octoprint":
if key == name:
self._logger.warn("Software update hook {} provides check for itself but that was already registered by {} - overwriting that third party registration now!".format(name, check_providers.get(key, "unknown hook")))
else:
self._logger.warn("Software update hook {} tried to overwrite config for check {} but that was already configured elsewhere".format(name, key))
continue
check_providers[key] = name
yaml_config = dict()
effective_config = default_config
if key in self._configured_checks:
data = dict_merge(data, self._configured_checks[key])
self._configured_checks[key] = data
yaml_config = self._configured_checks[key]
effective_config = dict_merge(default_config, yaml_config)
# Make sure there's nothing persisted in that check that shouldn't be persisted
#
# This used to be part of the settings migration (version 2) due to a bug - it can't
# stay there though since it interferes with manual entries to the checks not
# originating from within a plugin. Hence we do that step now here.
if "type" not in effective_config or effective_config["type"] != "github_commit":
deletables = ["current", "displayVersion"]
else:
deletables = []
self._clean_settings_check(key, yaml_config, default_config, delete=deletables, save=False)
if effective_config:
effective_configs[key] = effective_config
else:
self._logger.warn("Update for {} is empty or None, ignoring it".format(key))
# finally set all our internal representations to our processed results
for key, config in effective_configs.items():
self._configured_checks[key] = config
self._settings.set(["check_providers"], check_providers)
self._settings.save()
@@ -287,11 +327,18 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
self._refresh_configured_checks = True
def get_settings_version(self):
return 4
return 5
def on_settings_migrate(self, target, current=None):
if current is None or current < 4:
if current == 4:
# config version 4 didn't correctly remove the old settings for octoprint_restart_command
# and environment_restart_command
self._settings.set(["environment_restart_command"], None)
self._settings.set(["octoprint_restart_command"], None)
if current is None or current < 5:
# config version 4 and higher moves octoprint_restart_command and
# environment_restart_command to the core configuration
@@ -315,50 +362,27 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
if current is None or current == 2:
# No config version and config version 2 need the same fix, stripping
# accidentally persisted data off the checks
# accidentally persisted data off the checks.
#
# We used to do the same processing for the plugin entries too here, but that interfered
# with manual configuration entries. Stuff got deleted that wasn't supposed to be deleted.
#
# The problem is that we don't know if an entry we are looking at and which didn't come through
# a plugin hook is simply an entry from a now uninstalled/unactive plugin, or if it was something
# manually configured by the user. So instead of just blindly removing anything that doesn't
# come from a plugin here we instead clean up anything that indeed comes from a plugin
# during run time and leave everything else as is in the hopes that will not cause trouble.
#
# We still handle the "octoprint" entry here though.
configured_checks = self._settings.get(["checks"], incl_defaults=False)
if configured_checks is None:
configured_checks = dict()
check_keys = configured_checks.keys()
# take care of the octoprint entry
if "octoprint" in configured_checks:
if configured_checks is not None and "octoprint" in configured_checks:
octoprint_check = dict(configured_checks["octoprint"])
if "type" not in octoprint_check or octoprint_check["type"] != "github_commit":
deletables=["current", "displayName", "displayVersion"]
else:
deletables=[]
octoprint_check = self._clean_settings_check("octoprint", octoprint_check, self.get_settings_defaults()["checks"]["octoprint"], delete=deletables, save=False)
check_keys.remove("octoprint")
# 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" not in merged or merged["type"] != "github_commit":
deletables = ["current", "displayVersion"]
else:
deletables = []
self._clean_settings_check(key, settings_check, data, delete=deletables, save=False)
check_keys.remove(key)
# and anything that's left over we'll just remove now
for key in check_keys:
dummy_defaults = dict(plugins=dict())
dummy_defaults["plugins"][self._identifier] = dict(checks=dict())
dummy_defaults["plugins"][self._identifier]["checks"][key] = None
self._settings.set(["checks", key], None, defaults=dummy_defaults)
self._clean_settings_check("octoprint", octoprint_check, self.get_settings_defaults()["checks"]["octoprint"], delete=deletables, save=False)
elif current == 1:
# config version 1 had the error that the octoprint check got accidentally
@@ -377,6 +401,10 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
self._settings.set(["checks", "octoprint"], None, defaults=dummy_defaults)
def _clean_settings_check(self, key, data, defaults, delete=None, save=True):
if not data:
# nothing to do
return data
if delete is None:
delete = []
@@ -416,6 +444,15 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
def view():
try:
information, update_available, update_possible = self.get_current_versions(check_targets=check_targets, force=force)
# we don't want to transfer python_checker or python_updater values through json - replace with True
for key, data in information.items():
if "check" in data:
if "python_checker" in data["check"]:
data["check"]["python_checker"] = True
if "python_updater" in data["check"]:
data["check"]["python_updater"] = True
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:
@@ -522,54 +559,70 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
update_possible = False
information = dict()
for target, check in checks.items():
if not target in check_targets:
continue
# we don't want to do the same work twice, so let's use a lock
with self._get_versions_mutex:
for target, check in checks.items():
if not target in check_targets:
continue
try:
populated_check = self._populated_check(target, check)
target_information, target_update_available, target_update_possible = self._get_current_version(target, populated_check, force=force)
if target_information is None:
target_information = dict()
except exceptions.UnknownCheckType:
self._logger.warn("Unknown update check type for target {}: {}".format(target, check.get("type", "<n/a>")))
continue
if not check:
continue
target_information = dict_merge(dict(local=dict(name="unknown", value="unknown"), remote=dict(name="unknown", value="unknown", release_notes=None)), target_information)
try:
populated_check = self._populated_check(target, check)
target_information, target_update_available, target_update_possible = self._get_current_version(target, populated_check, force=force)
if target_information is None:
target_information = dict()
except exceptions.UnknownCheckType:
self._logger.warn("Unknown update check type for target {}: {}".format(target, check.get("type", "<n/a>")))
continue
update_available = update_available or target_update_available
update_possible = update_possible or (target_update_possible and target_update_available)
target_information = dict_merge(dict(local=dict(name="unknown", value="unknown"), remote=dict(name="unknown", value="unknown", release_notes=None)), target_information)
local_name = target_information["local"]["name"]
local_value = target_information["local"]["value"]
update_available = update_available or target_update_available
update_possible = update_possible or (target_update_possible and target_update_available)
release_notes = None
if target_information and target_information["remote"] and target_information["remote"]["value"]:
if "release_notes" in populated_check and populated_check["release_notes"]:
release_notes = populated_check["release_notes"]
elif "release_notes" in target_information["remote"]:
release_notes = target_information["remote"]["release_notes"]
local_name = target_information["local"]["name"]
local_value = target_information["local"]["value"]
if release_notes:
release_notes = release_notes.format(octoprint_version=VERSION,
target_name=target_information["remote"]["name"],
target_version=target_information["remote"]["value"])
release_notes = None
if target_information and target_information["remote"] and target_information["remote"]["value"]:
if "release_notes" in populated_check and populated_check["release_notes"]:
release_notes = populated_check["release_notes"]
elif "release_notes" in target_information["remote"]:
release_notes = target_information["remote"]["release_notes"]
information[target] = dict(updateAvailable=target_update_available,
updatePossible=target_update_possible,
information=target_information,
displayName=populated_check["displayName"],
displayVersion=populated_check["displayVersion"].format(octoprint_version=VERSION, local_name=local_name, local_value=local_value),
check=populated_check,
releaseNotes=release_notes)
if release_notes:
release_notes = release_notes.format(octoprint_version=VERSION,
target_name=target_information["remote"]["name"],
target_version=target_information["remote"]["value"])
if self._version_cache_dirty:
self._save_version_cache()
information[target] = dict(updateAvailable=target_update_available,
updatePossible=target_update_possible,
information=target_information,
displayName=populated_check["displayName"],
displayVersion=populated_check["displayVersion"].format(octoprint_version=VERSION, local_name=local_name, local_value=local_value),
check=populated_check,
releaseNotes=release_notes)
if self._version_cache_dirty:
self._save_version_cache()
return information, update_available, update_possible
def _get_check_hash(self, check):
def dict_to_sorted_repr(d):
lines = []
for key in sorted(d.keys()):
value = d[key]
if isinstance(value, dict):
lines.append("{!r}: {}".format(key, dict_to_sorted_repr(value)))
else:
lines.append("{!r}: {!r}".format(key, value))
return "{" + ", ".join(lines) + "}"
hash = hashlib.md5()
hash.update(repr(check))
hash.update(dict_to_sorted_repr(check))
return hash.hexdigest()
def _get_current_version(self, target, check, force=False):
@@ -677,6 +730,8 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
target_restart_type = check["restart"]
elif "pip" in check:
target_restart_type = "octoprint"
else:
target_restart_type = None
# if our update requires a restart we have to determine which type
if restart_type is None or (restart_type == "octoprint" and target_restart_type == "environment"):
@@ -807,8 +862,16 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
if target == "octoprint":
from flask.ext.babel import gettext
result["displayName"] = check.get("displayName", gettext("OctoPrint"))
result["displayVersion"] = check.get("displayVersion", "{octoprint_version}")
result["displayName"] = to_unicode(check.get("displayName"), errors="replace")
if result["displayName"] is None:
# displayName missing or set to None
result["displayName"] = to_unicode(gettext("OctoPrint"), errors="replace")
result["displayVersion"] = to_unicode(check.get("displayVersion"), errors="replace")
if result["displayVersion"] is None:
# displayVersion missing or set to None
result["displayVersion"] = u"{octoprint_version}"
stable_branch = "master"
release_branches = []
@@ -863,8 +926,16 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
result["release_compare"] = "python_unequal"
else:
result["displayName"] = check.get("displayName", target)
result["displayVersion"] = check.get("displayVersion", check.get("current", "unknown"))
result["displayName"] = to_unicode(check.get("displayName"), errors="replace")
if result["displayName"] is None:
# displayName missing or None
result["displayName"] = to_unicode(target, errors="replace")
result["displayVersion"] = to_unicode(check.get("displayVersion", check.get("current")), errors="replace")
if result["displayVersion"] is None:
# displayVersion AND current missing or None
result["displayVersion"] = u"unknown"
if check["type"] in ("github_commit",):
result["current"] = check.get("current", None)
else:
@@ -930,7 +1001,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
elif "pip" in check:
method = "pip"
elif "python_updater" in check:
method = "python_updated"
method = "python_updater"
if method is None or (valid_methods and not method in valid_methods):
raise exceptions.UnknownUpdateType()
@@ -1,17 +1,19 @@
(function (global, factory) {
if (typeof define === "function" && define.amd) {
define(["OctoPrint"], factory);
define(["OctoPrintClient"], factory);
} else {
factory(window.OctoPrint);
factory(global.OctoPrintClient);
}
})(window || this, function(OctoPrint) {
var exports = {};
})(this, function(OctoPrintClient) {
var OctoPrintSoftwareUpdateClient = function(base) {
this.base = base;
var url = OctoPrint.getBlueprintUrl("softwareupdate");
var checkUrl = url + "check";
var updateUrl = url + "update";
var url = this.base.getBlueprintUrl("softwareupdate");
this.checkUrl = url + "check";
this.updateUrl = url + "update";
};
exports.checkEntries = function(entries, force, opts) {
OctoPrintSoftwareUpdateClient.prototype.checkEntries = function(entries, force, opts) {
if (arguments.length == 1 && _.isObject(arguments[0])) {
var params = arguments[0];
entries = params.entries;
@@ -31,20 +33,20 @@
if (entries && entries.length) {
data.check = entries.join(",");
}
return OctoPrint.getWithQuery(checkUrl, data, opts);
return this.base.getWithQuery(this.checkUrl, data, opts);
};
exports.check = function(force, opts) {
OctoPrintSoftwareUpdateClient.prototype.check = function(force, opts) {
if (arguments.length == 1 && _.isObject(arguments[0])) {
var params = arguments[0];
force = params.force;
opts = params.opts;
}
return exports.checkEntries({entries: [], force: force, opts: opts});
return this.checkEntries({entries: [], force: force, opts: opts});
};
exports.update = function(entries, force, opts) {
OctoPrintSoftwareUpdateClient.prototype.update = function(entries, force, opts) {
if (arguments.length == 1 && _.isObject(arguments[0])) {
var params = arguments[0];
entries = params.entries;
@@ -61,10 +63,10 @@
entries: entries,
force: !!force
};
return OctoPrint.postJson(updateUrl, data, opts);
return this.base.postJson(this.updateUrl, data, opts);
};
exports.updateAll = function(force, opts) {
OctoPrintSoftwareUpdateClient.prototype.updateAll = function(force, opts) {
if (arguments.length == 1 && _.isObject(arguments[0])) {
var params = arguments[0];
force = params.force;
@@ -74,10 +76,11 @@
var data = {
force: !!force
};
return OctoPrint.postJson(updateUrl, data, opts);
return this.base.postJson(this.updateUrl, data, opts);
};
OctoPrint.plugins.softwareupdate = exports;
OctoPrintClient.registerPluginComponent("softwareupdate", OctoPrintSoftwareUpdateClient);
return OctoPrintSoftwareUpdateClient;
});
$(function() {
@@ -702,7 +705,10 @@ $(function() {
}
};
self._forcedStdoutLine = /You are using pip version .*?, however version .*? is available\.|You should consider upgrading via the '.*?' command\./;
self._forcedStdoutPatterns = ["You are using pip version .*?, however version .*? is available\.",
"You should consider upgrading via the '.*?' command\.",
"'.*?' does not exist -- can't clean it"];
self._forcedStdoutLine = new RegExp(self._forcedStdoutPatterns.join("|"));
self._preprocessLine = function(line) {
if (line.stream == "stderr" && line.line.match(self._forcedStdoutLine)) {
line.stream = "stdout";
@@ -7,8 +7,8 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms
def can_perform_update(target, check):
return "python_updater" in check and check["python_updater"] is not None
return "python_updater" in check and check["python_updater"] is not None and hasattr(check["python_updater"], "perform_update")
def perform_update(target, check, target_version, log_cb=None):
return check["python_updater"].perform_update(target, check, target_version, log_cb=None)
return check["python_updater"].perform_update(target, check, target_version, log_cb=log_cb)
@@ -12,10 +12,11 @@ from ..exceptions import ConfigurationInvalid
from ..util import execute
def get_latest(target, check):
if not "command" in check:
raise ConfigurationInvalid("Update configuration for %s of type commandline needs command defined" % target)
command = check.get("command")
if command is None:
raise ConfigurationInvalid("Update configuration for {} of type commandline needs command set and not None".format(target))
returncode, stdout, stderr = execute(check["command"], evaluate_returncode=False)
returncode, stdout, stderr = execute(command, evaluate_returncode=False)
# We expect command line check commands to
#
@@ -48,10 +48,9 @@ def _git(args, cwd, hide_stderr=False):
def get_latest(target, check):
if not "checkout_folder" in check:
raise ConfigurationInvalid("Update configuration for %s needs checkout_folder" % target)
checkout_folder = check["checkout_folder"]
checkout_folder = check.get("checkout_folder")
if checkout_folder is None:
raise ConfigurationInvalid("Update configuration for {} of type git_commit needs checkout_folder set and not None".format(target))
returncode, _ = _git(["fetch"], checkout_folder)
if returncode != 0:
@@ -85,4 +84,4 @@ def get_latest(target, check):
logger = logging.getLogger("octoprint.plugins.softwareupdate.version_checks.git_commit")
logger.debug("Target: %s, local: %s, remote: %s" % (target, local_commit, remote_commit))
return information, is_current
return information, is_current
@@ -31,11 +31,14 @@ def _get_latest_commit(user, repo, branch):
def get_latest(target, check):
if "user" not in check or "repo" not in check:
raise ConfigurationInvalid("Update configuration for %s of type github_commit needs all of user and repo" % target)
user = check.get("user")
repo = check.get("repo")
if user is None or repo is None:
raise ConfigurationInvalid("Update configuration for {} of type github_commit needs user and repo set and not None".format(target))
branch = "master"
if "branch" in check:
if "branch" in check and check["branch"] is not None:
branch = check["branch"]
current = None
@@ -8,8 +8,6 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms
import requests
import logging
from ..exceptions import ConfigurationInvalid
RELEASE_URL = "https://api.github.com/repos/{user}/{repo}/releases"
logger = logging.getLogger("octoprint.plugins.softwareupdate.version_checks.github_release")
@@ -117,12 +115,14 @@ def _get_sanitized_version(version_string):
Removes "-..." prefix from version strings.
Tests:
>>> _get_sanitized_version(None)
>>> _get_sanitized_version("1.2.15")
'1.2.15'
>>> _get_sanitized_version("1.2.15-dev12")
'1.2.15'
"""
if "-" in version_string:
if version_string is not None and "-" in version_string:
version_string = version_string[:version_string.find("-")]
return version_string
@@ -152,6 +152,10 @@ def _get_comparable_version_pkg_resources(version_string, force_base=True):
version = pkg_resources.parse_version(version_string)
# A leading v is common in github release tags and old setuptools doesn't remove it.
if version and isinstance(version, tuple) and version[0].lower() == "*v":
version = version[1:]
if force_base:
if isinstance(version, tuple):
# old setuptools
@@ -207,18 +211,20 @@ def _is_current(release_information, compare_type, custom=None, force_base=True)
Tests:
>>> _is_current(dict(remote=dict(value=None))
>>> _is_current(dict(remote=dict(value=None)), "python")
True
>>> _is_current(dict(local=dict(value="1.2.15"), remote=dict(value="1.2.16")))
>>> _is_current(dict(local=dict(value="1.2.15"), remote=dict(value="1.2.16")), "python")
False
>>> _is_current(dict(local=dict(value="1.2.16dev1"), remote=dict(value="1.2.16dev2")))
>>> _is_current(dict(local=dict(value="1.2.16dev1"), remote=dict(value="1.2.16dev2")), "python")
True
>>> _is_current(dict(local=dict(value="1.2.16dev1"), remote=dict(value="1.2.16dev2")), force_base=False)
>>> _is_current(dict(local=dict(value="1.2.16dev1"), remote=dict(value="1.2.16dev2")), "python", force_base=False)
False
>>> _is_current(dict(local=dict(value="1.2.16dev3"), remote=dict(value="1.2.16dev2")), force_base=False)
>>> _is_current(dict(local=dict(value="1.2.16dev3"), remote=dict(value="1.2.16dev2")), "python", force_base=False)
True
>>> _is_current(dict(local=dict(value="1.2.16dev3"), remote=dict(value="1.2.16dev2")), force_base=False, compare_type="python_unequal")
>>> _is_current(dict(local=dict(value="1.2.16dev3"), remote=dict(value="1.2.16dev2")), "python_unequal", force_base=False)
False
>>> _is_current(dict(local=dict(value="1.3.0.post1+g1014712"), remote=dict(value="1.3.0")), "python")
True
"""
@@ -241,10 +247,14 @@ def _is_current(release_information, compare_type, custom=None, force_base=True)
def get_latest(target, check, custom_compare=None):
if not "user" in check or not "repo" in check:
raise ConfigurationInvalid("github_release update configuration for %s needs user and repo set" % target)
from ..exceptions import ConfigurationInvalid
user = check.get("user", None)
repo = check.get("repo", None)
current = check.get("current", None)
if user is None or repo is None or current is None:
raise ConfigurationInvalid("Update configuration for {} of type github_release needs all of user, repo and current set and not None".format(target))
include_prerelease = check.get("prerelease", False)
prerelease_channel = check.get("prerelease_channel", None)
force_base = check.get("force_base", True)
@@ -8,7 +8,8 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms
from ..exceptions import ConfigurationInvalid
def get_latest(target, check, full_data=False):
if not "python_checker" in check:
raise ConfigurationInvalid("Update configuration for %s of type commandline needs command defined" % target)
python_checker = check.get("python_checker")
if python_checker is None or not hasattr(python_checker, "get_latest"):
raise ConfigurationInvalid("Update configuration for {} of type python_checker needs python_checker defined and have an attribute \"get_latest\"".format(target))
return check["python_checker"].get_latest(target, check, full_data=full_data)
@@ -25,6 +25,8 @@ class VirtualPrinter(object):
sleep_after_regex = re.compile("sleep_after ([GMTF]\d+) (\d+)")
sleep_after_next_regex = re.compile("sleep_after_next ([GMTF]\d+) (\d+)")
custom_action_regex = re.compile("action_custom ([a-zA-Z0-9_]+)(\s+.*)?")
prepare_ok_regex = re.compile("prepare_ok (.*)")
send_regex = re.compile("send (.*)")
def __init__(self, seriallog_handler=None, read_timeout=5.0, write_timeout=10.0):
import logging
@@ -50,12 +52,23 @@ class VirtualPrinter(object):
self.outgoing = queue.Queue()
self.buffered = queue.Queue(maxsize=settings().getInt(["devel", "virtualPrinter", "commandBuffer"]))
for item in ['start\n', 'Marlin: Virtual Marlin!\n', '\x80\n', 'SD card ok\n']:
self._send(item)
if settings().getBoolean(["devel", "virtualPrinter", "simulateReset"]):
for item in ['start\n', 'Marlin: Virtual Marlin!\n', '\x80\n', 'SD card ok\n']:
self._send(item)
self._prepared_oks = []
prepared = settings().get(["devel", "virtualPrinter", "preparedOks"])
if prepared and isinstance(prepared, list):
for prep in prepared:
self._prepared_oks.append(prep)
self.currentExtruder = 0
self.temp = [0.0] * settings().getInt(["devel", "virtualPrinter", "numExtruders"])
self.targetTemp = [0.0] * settings().getInt(["devel", "virtualPrinter", "numExtruders"])
self.extruderCount = settings().getInt(["devel", "virtualPrinter", "numExtruders"])
self.sharedNozzle = settings().getBoolean(["devel", "virtualPrinter", "sharedNozzle"])
self.temperatureCount = (1 if self.sharedNozzle else self.extruderCount)
self.temp = [0.0] * self.temperatureCount
self.targetTemp = [0.0] * self.temperatureCount
self.lastTempAt = time.time()
self.bedTemp = 1.0
self.bedTargetTemp = 1.0
@@ -88,6 +101,7 @@ class VirtualPrinter(object):
self._supportF = settings().getBoolean(["devel", "virtualPrinter", "supportF"])
self._sendWait = settings().getBoolean(["devel", "virtualPrinter", "sendWait"])
self._sendBusy = settings().getBoolean(["devel", "virtualPrinter", "sendBusy"])
self._waitInterval = settings().getFloat(["devel", "virtualPrinter", "waitInterval"])
self._echoOnM117 = settings().getBoolean(["devel", "virtualPrinter", "echoOnM117"])
@@ -96,6 +110,8 @@ class VirtualPrinter(object):
self._firmwareName = settings().get(["devel", "virtualPrinter", "firmwareName"])
self._okFormatString = settings().get(["devel", "virtualPrinter", "okFormatString"])
self.currentLine = 0
self.lastN = 0
@@ -301,8 +317,10 @@ class VirtualPrinter(object):
##~~ command implementations
def _gcode_T(self, code, data):
self.currentExtruder = int(code)
self._send("Active Extruder: %d" % self.currentExtruder)
t = int(code)
if 0 <= t <= self.extruderCount:
self.currentExtruder = t
self._send("Active Extruder: %d" % self.currentExtruder)
def _gcode_F(self, code, data):
if self._supportF:
@@ -378,7 +396,7 @@ class VirtualPrinter(object):
def _gcode_M114(self, data):
output = "X:{} Y:{} Z:{} E:{} Count: A:{} B:{} C:{}".format(self._lastX, self._lastY, self._lastZ, self._lastE, int(self._lastX*100), int(self._lastY*100), int(self._lastZ*100))
if not self._okBeforeCommandOutput:
output = "ok " + output
output = "{} {}".format(self._ok(), output)
self._send(output)
return True
@@ -445,6 +463,24 @@ class VirtualPrinter(object):
_gcode_G2 = _gcode_G0
_gcode_G3 = _gcode_G0
def _gcode_G4(self, data):
matchS = re.search('S([0-9]+)', data)
matchP = re.search('P([0-9]+)', data)
_timeout = 0
if matchP:
_timeout = float(matchP.group(1)) / 1000.0
elif matchS:
_timeout = float(matchS.group(1))
if self._sendBusy:
until = time.time() + _timeout
while time.time() < until:
time.sleep(1.0)
self._send("busy:processing")
else:
time.sleep(_timeout)
##~~ further helpers
def _calculate_checksum(self, line):
@@ -473,7 +509,7 @@ class VirtualPrinter(object):
def request_resend():
self._send("Resend:%d" % expected)
self._send("ok")
self._send(self._ok())
if settings().getBoolean(["devel", "virtualPrinter", "repetierStyleResends"]):
request_resend()
@@ -513,6 +549,9 @@ class VirtualPrinter(object):
| Triggers a resend error with a checksum mismatch
drop_connection
| Drops the serial connection
prepare_ok <broken ok>
| Will cause <broken ok> to be enqueued for use,
| will be used instead of actual "ok"
# Reply Timing / Sleeping
@@ -521,7 +560,12 @@ class VirtualPrinter(object):
sleep_after <str:command> <int:seconds>
| Sleeps <seconds> s after each execution of <command>
sleep_after_next <str:command> <int:seconds>
| Sleeps <seconds> s after execution of <command>
| Sleeps <seconds> s after execution of next <command>
# Misc
send <str:message>
| Sends back <message>
"""
for line in usage.split("\n"):
self._send("echo: {}".format(line.strip()))
@@ -550,6 +594,8 @@ class VirtualPrinter(object):
sleep_after_match = VirtualPrinter.sleep_after_regex.match(data)
sleep_after_next_match = VirtualPrinter.sleep_after_next_regex.match(data)
custom_action_match = VirtualPrinter.custom_action_regex.match(data)
prepare_ok_match = VirtualPrinter.prepare_ok_regex.match(data)
send_match = VirtualPrinter.send_regex.match(data)
if sleep_match is not None:
interval = int(sleep_match.group(1))
@@ -570,6 +616,11 @@ class VirtualPrinter(object):
params = custom_action_match.group(2)
params = params.strip() if params is not None else ""
self._send("// action:{action} {params}".format(**locals()).strip())
elif prepare_ok_match is not None:
ok = prepare_ok_match.group(1)
self._prepared_oks.append(ok)
elif send_match is not None:
self._send(send_match.group(1))
except:
pass
@@ -628,7 +679,7 @@ class VirtualPrinter(object):
includeOk = not self._okBeforeCommandOutput
# send simulated temperature data
if settings().getInt(["devel", "virtualPrinter", "numExtruders"]) > 1:
if self.temperatureCount > 1:
allTemps = []
for i in range(len(self.temp)):
allTemps.append((i, self.temp[i], self.targetTemp[i]))
@@ -659,7 +710,7 @@ class VirtualPrinter(object):
output += " @:64\n"
if includeOk:
output = "ok " + output
output = "{} {}".format(self._ok(), output)
self._send(output)
def _parseHotendCommand(self, line, wait=False, support_r=False):
@@ -672,7 +723,7 @@ class VirtualPrinter(object):
except:
pass
if tool >= settings().getInt(["devel", "virtualPrinter", "numExtruders"]):
if tool >= self.temperatureCount:
return
try:
@@ -1033,11 +1084,7 @@ class VirtualPrinter(object):
def _sendOk(self):
if self.outgoing is None:
return
if settings().getBoolean(["devel", "virtualPrinter", "okWithLinenumber"]):
self._send("ok %d" % self.lastN)
else:
self._send("ok")
self._send(self._ok())
def _sendWaitAfterTimeout(self, timeout=5):
time.sleep(timeout)
@@ -1048,6 +1095,13 @@ class VirtualPrinter(object):
if self.outgoing is not None:
self.outgoing.put(line)
def _ok(self):
ok = self._okFormatString
if self._prepared_oks:
ok = self._prepared_oks.pop(0)
return ok.format(ok, lastN=self.lastN, buffer=self.buffered.maxsize - self.buffered.qsize())
class CharCountingQueue(queue.Queue):
def __init__(self, maxsize, name=None):
+59
View File
@@ -25,6 +25,7 @@ import re
from octoprint.settings import settings
from octoprint.util import deprecated
from octoprint.filemanager import FileDestinations
@deprecated(message="get_connection_options has been replaced by PrinterInterface.get_connection_options",
@@ -227,6 +228,64 @@ class PrinterInterface(object):
"""
raise NotImplementedError()
def can_modify_file(self, path, sd):
"""
Determines whether the ``path`` (on the printer's SD if ``sd`` is True) may be modified (updated or deleted)
or not.
A file that is currently being printed is not allowed to be modified. Any other file or the current file
when it is not being printed is fine though.
.. since:: 1.3.2
.. warning::
This was introduced in 1.3.2 to work around an issue when updating a file that is already selected.
I'm not 100% sure at this point if this is the best approach to solve this issue, so if you decide
to depend on this particular method in this interface, be advised that it might vanish in future
versions!
Arguments:
path (str): path in storage of the file to check
sd (bool): True if to check against SD storage, False otherwise
Returns:
(bool) True if the file may be modified, False otherwise
"""
return not (self.is_current_file(path, sd) and (self.is_printing() or self.is_paused()))
def is_current_file(self, path, sd):
"""
Returns whether the provided ``path`` (on the printer's SD if ``sd`` is True) is the currently selected
file for printing.
.. since:: 1.3.2
.. warning::
This was introduced in 1.3.2 to work around an issue when updating a file that is already selected.
I'm not 100% sure at this point if this is the best approach to solve this issue, so if you decide
to depend on this particular method in this interface, be advised that it might vanish in future
versions!
Arguments:
path (str): path in storage of the file to check
sd (bool): True if to check against SD storage, False otherwise
Returns:
(bool) True if the file is currently selected, False otherwise
"""
current_job = self.get_current_job()
if current_job is not None and "file" in current_job:
current_job_file = current_job["file"]
if "path" in current_job_file and "origin" in current_job_file:
current_file_path = current_job_file["path"]
current_file_origin = current_job_file["origin"]
return path == current_file_path and sd == (current_file_origin == FileDestinations.SDCARD)
return False
def select_file(self, path, sd, printAfterSelect=False, pos=None):
"""
Selects the specified ``path`` for printing, specifying if the file is to be found on the ``sd`` or not.
+22 -3
View File
@@ -124,7 +124,10 @@ class PrinterProfileManager(object):
- Extruder offsets relative to first extruder, list of (x, y) tuples, first is always (0,0)
* - ``extruder.nozzleDiameter``
- ``float``
- Diameter of the printer nozzle
- Diameter of the printer nozzle(s)
* - ``extruder.sharedNozzle``
- ``boolean``
- Whether there's only one nozzle shared among all extruders (true) or one nozzle per extruder (false).
* - ``axes``
- ``dict``
- Information about the printer axes
@@ -185,7 +188,8 @@ class PrinterProfileManager(object):
offsets = [
(0, 0)
],
nozzleDiameter = 0.4
nozzleDiameter = 0.4,
sharedNozzle = False
),
axes=dict(
x = dict(speed=6000, inverted=False),
@@ -390,6 +394,13 @@ class PrinterProfileManager(object):
def _load_default(self):
default_overrides = settings().get(["printerProfiles", "defaultProfile"])
if self._migrate_profile(default_overrides):
try:
settings().set(["printerProfiles", "defaultProfile"], default_overrides)
settings().save()
except:
self._logger.exception("Tried to save default profile after migrating it while loading, ran into exception")
profile = self._ensure_valid_profile(dict_merge(copy.deepcopy(self.__class__.default), default_overrides))
if not profile:
self._logger.warn("Invalid default profile after applying overrides")
@@ -424,6 +435,14 @@ class PrinterProfileManager(object):
profile["volume"]["custom_box"] = False
modified = True
if "extruder" in profile and not "sharedNozzle" in profile["extruder"]:
profile["extruder"]["sharedNozzle"] = False
modified = True
if "extruder" in profile and "sharedNozzle" in profile["extruder"] and profile["extruder"]["sharedNozzle"]:
profile["extruder"]["offsets"] = [(0.0, 0.0)]
modified = True
return modified
def _ensure_valid_profile(self, profile):
@@ -462,7 +481,7 @@ class PrinterProfileManager(object):
return False
# convert booleans
for path in (("axes", "x", "inverted"), ("axes", "y", "inverted"), ("axes", "z", "inverted")):
for path in (("axes", "x", "inverted"), ("axes", "y", "inverted"), ("axes", "z", "inverted"), ("extruder", "sharedNozzle")):
try:
convert_value(profile, path, bool)
except Exception as e:
+24 -12
View File
@@ -66,6 +66,8 @@ import octoprint.util
import octoprint.filemanager.storage
import octoprint.filemanager.analysis
import octoprint.slicing
from octoprint.server.util import enforceApiKeyRequestHandler, loginFromApiKeyRequestHandler, corsRequestHandler, \
corsResponseHandler
from octoprint.server.util.flask import PreemptiveCache
from . import util
@@ -263,7 +265,7 @@ class Server(object):
return dict(settings=plugin_settings)
def settings_plugin_config_migration_and_cleanup(name, implementation):
def settings_plugin_config_migration_and_cleanup(identifier, implementation):
"""Take care of migrating and cleaning up any old settings"""
if not isinstance(implementation, octoprint.plugin.SettingsPlugin):
@@ -276,7 +278,7 @@ class Server(object):
stored_version = implementation._settings.get_int([octoprint.plugin.SettingsPlugin.config_version_key])
if stored_version is None or stored_version < settings_version:
settings_migrator(settings_version, stored_version)
implementation._settings.set_int([octoprint.plugin.SettingsPlugin.config_version_key], settings_version)
implementation._settings.set_int([octoprint.plugin.SettingsPlugin.config_version_key], settings_version, force=True)
implementation.on_settings_cleanup()
implementation._settings.save()
@@ -365,9 +367,14 @@ class Server(object):
as_attachment=True,
allow_client_caching=False
)
additional_mime_types=dict(mime_type_guesser=mime_type_guesser)
admin_validator = dict(access_validation=util.tornado.access_validation_factory(app, loginManager, util.flask.admin_validator))
no_hidden_files_validator = dict(path_validation=util.tornado.path_validation_factory(lambda path: not octoprint.util.is_hidden_path(path), status_code=404))
user_validator = dict(access_validation=util.tornado.access_validation_factory(app, loginManager, util.flask.user_validator))
no_hidden_files_validator = dict(path_validation=util.tornado.path_validation_factory(lambda path: not octoprint.util.is_hidden_path(path),
status_code=404))
def joined_dict(*dicts):
if not len(dicts):
@@ -392,9 +399,9 @@ class Server(object):
download_handler_kwargs,
admin_validator)),
# camera snapshot
(r"/downloads/camera/current", util.tornado.UrlProxyHandler, dict(url=self._settings.get(["webcam", "snapshot"]),
as_attachment=True,
access_validation=util.tornado.access_validation_factory(app, loginManager, util.flask.user_validator))),
(r"/downloads/camera/current", util.tornado.UrlProxyHandler, joined_dict(dict(url=self._settings.get(["webcam", "snapshot"]),
as_attachment=True),
user_validator)),
# generated webassets
(r"/static/webassets/(.*)", util.tornado.LargeResponseHandler, dict(path=os.path.join(self._settings.getBaseFolder("generated"), "webassets"))),
@@ -894,8 +901,13 @@ class Server(object):
return
if plugin.is_blueprint_protected():
from octoprint.server.util import apiKeyRequestHandler, corsResponseHandler
blueprint.before_request(apiKeyRequestHandler)
blueprint.before_request(corsRequestHandler)
blueprint.before_request(enforceApiKeyRequestHandler)
blueprint.before_request(loginFromApiKeyRequestHandler)
blueprint.after_request(corsResponseHandler)
else:
blueprint.before_request(corsRequestHandler)
blueprint.before_request(loginFromApiKeyRequestHandler)
blueprint.after_request(corsResponseHandler)
url_prefix = "/plugin/{name}".format(name=name)
@@ -1137,12 +1149,12 @@ class Server(object):
if len(css_core) == 0:
css_core_bundle = Bundle(*[])
else:
css_core_bundle = Bundle(*css_app, output="webassets/packed_core.css", filters="cssrewrite")
css_core_bundle = Bundle(*css_core, output="webassets/packed_core.css", filters="cssrewrite")
if len(css_plugins) == 0:
css_plugins_bundle = Bundle(*[])
else:
css_plugins_bundle = Bundle(*css_app, output="webassets/packed_plugins.css", filters="cssrewrite")
css_plugins_bundle = Bundle(*css_plugins, output="webassets/packed_plugins.css", filters="cssrewrite")
if len(css_app) == 0:
css_app_bundle = Bundle(*[])
@@ -1153,12 +1165,12 @@ class Server(object):
if len(less_core) == 0:
less_core_bundle = Bundle(*[])
else:
less_core_bundle = Bundle(*less_app, output="webassets/packed_core.less", filters="cssrewrite, less_importrewrite")
less_core_bundle = Bundle(*less_core, output="webassets/packed_core.less", filters="cssrewrite, less_importrewrite")
if len(less_plugins) == 0:
less_plugins_bundle = Bundle(*[])
else:
less_plugins_bundle = Bundle(*less_app, output="webassets/packed_plugins.less", filters="cssrewrite, less_importrewrite")
less_plugins_bundle = Bundle(*less_plugins, output="webassets/packed_plugins.less", filters="cssrewrite, less_importrewrite")
if len(less_app) == 0:
less_app_bundle = Bundle(*[])
+5 -3
View File
@@ -19,7 +19,7 @@ import octoprint.server
import octoprint.plugin
from octoprint.server import admin_permission, NO_CONTENT
from octoprint.settings import settings as s, valid_boolean_trues
from octoprint.server.util import noCachingExceptGetResponseHandler, apiKeyRequestHandler, corsResponseHandler
from octoprint.server.util import noCachingExceptGetResponseHandler, enforceApiKeyRequestHandler, loginFromApiKeyRequestHandler, corsRequestHandler, corsResponseHandler
from octoprint.server.util.flask import restricted_access, get_json_command_from_request, passive_login
@@ -45,7 +45,9 @@ VERSION = "0.1"
api.after_request(noCachingExceptGetResponseHandler)
api.before_request(apiKeyRequestHandler)
api.before_request(corsRequestHandler)
api.before_request(enforceApiKeyRequestHandler)
api.before_request(loginFromApiKeyRequestHandler)
api.after_request(corsResponseHandler)
#~~ data from plugins
@@ -153,7 +155,7 @@ def wizardFinish():
if name in handled:
seen_wizards[name] = implementation.get_wizard_version()
except:
logging.getLogger(__name__).exceptino("There was an error finishing the wizard for {}, ignoring".format(name))
logging.getLogger(__name__).exception("There was an error finishing the wizard for {}, ignoring".format(name))
s().set(["server", "seenWizards"], seen_wizards)
s().save()
+9 -17
View File
@@ -289,17 +289,6 @@ def uploadGcodeFile(target):
if not printer.is_sd_ready():
return make_response("Can not upload to SD card, not yet initialized", 409)
# determine current job
currentPath = None
currentFilename = None
currentOrigin = None
currentJob = printer.get_current_job()
if currentJob is not None and "file" in currentJob.keys():
currentJobFile = currentJob["file"]
if currentJobFile is not None and "name" in currentJobFile.keys() and "origin" in currentJobFile.keys() and currentJobFile["name"] is not None and currentJobFile["origin"] is not None:
currentPath, currentFilename = fileManager.sanitize(FileDestinations.LOCAL, currentJobFile["name"])
currentOrigin = currentJobFile["origin"]
# determine future filename of file to be uploaded, abort if it can't be uploaded
try:
# FileDestinations.LOCAL = should normally be target, but can't because SDCard handling isn't implemented yet
@@ -316,8 +305,13 @@ def uploadGcodeFile(target):
futurePath = fileManager.sanitize_path(FileDestinations.LOCAL, request.values["path"])
# prohibit overwriting currently selected file while it's being printed
if futurePath == currentPath and futureFilename == currentFilename and target == currentOrigin and (printer.is_printing() or printer.is_paused()):
return make_response("Trying to overwrite file that is currently being printed: %s" % currentFilename, 409)
futureFullPath = fileManager.join_path(FileDestinations.LOCAL, futurePath, futureFilename)
futureFullPathInStorage = fileManager.path_in_storage(FileDestinations.LOCAL, futureFullPath)
if not printer.can_modify_file(futureFullPathInStorage, sd):
return make_response("Trying to overwrite file that is currently being printed: %s" % futureFullPath, 409)
reselect = printer.is_current_file(futureFullPathInStorage, sd)
def fileProcessingFinished(filename, absFilename, destination):
"""
@@ -342,13 +336,11 @@ def uploadGcodeFile(target):
Selects the just uploaded file if either selectAfterUpload or printAfterSelect are True, or if the
exact file is already selected, such reloading it.
"""
if octoprint.filemanager.valid_file_type(added_file, "gcode") and (selectAfterUpload or printAfterSelect or (currentFilename == filename and currentOrigin == destination)):
if octoprint.filemanager.valid_file_type(added_file, "gcode") and (selectAfterUpload or printAfterSelect or reselect):
printer.select_file(absFilename, destination == FileDestinations.SDCARD, printAfterSelect)
futureFullPath = fileManager.join_path(FileDestinations.LOCAL, futurePath, futureFilename)
try:
added_file = fileManager.add_file(FileDestinations.LOCAL, futureFullPath, upload, allow_overwrite=True)
added_file = fileManager.add_file(FileDestinations.LOCAL, futureFullPathInStorage, upload, allow_overwrite=True)
except octoprint.filemanager.storage.StorageError as e:
if e.code == octoprint.filemanager.storage.StorageError.INVALID_FILE:
return make_response("Could not upload the file \"{}\", invalid type".format(upload.filename), 400)
+54 -52
View File
@@ -126,7 +126,8 @@ def getSettings():
"ignoreIdenticalResends": s.getBoolean(["feature", "ignoreIdenticalResends"]),
"modelSizeDetection": s.getBoolean(["feature", "modelSizeDetection"]),
"firmwareDetection": s.getBoolean(["feature", "firmwareDetection"]),
"printCancelConfirmation": s.getBoolean(["feature", "printCancelConfirmation"])
"printCancelConfirmation": s.getBoolean(["feature", "printCancelConfirmation"]),
"blockWhileDwelling": s.getBoolean(["feature", "blockWhileDwelling"])
},
"serial": {
"port": connectionOptions["portPreference"],
@@ -266,14 +267,14 @@ def _saveSettings(data):
# is changed, added or removed here
if "api" in data.keys():
if "enabled" in data["api"].keys(): s.setBoolean(["api", "enabled"], data["api"]["enabled"])
if "key" in data["api"].keys(): s.set(["api", "key"], data["api"]["key"], True)
if "allowCrossOrigin" in data["api"].keys(): s.setBoolean(["api", "allowCrossOrigin"], data["api"]["allowCrossOrigin"])
if "enabled" in data["api"]: s.setBoolean(["api", "enabled"], data["api"]["enabled"])
if "key" in data["api"] and data["api"]["key"] and data["api"]["key"] != "n/a": s.set(["api", "key"], data["api"]["key"], True)
if "allowCrossOrigin" in data["api"]: s.setBoolean(["api", "allowCrossOrigin"], data["api"]["allowCrossOrigin"])
if "appearance" in data.keys():
if "name" in data["appearance"].keys(): s.set(["appearance", "name"], data["appearance"]["name"])
if "color" in data["appearance"].keys(): s.set(["appearance", "color"], data["appearance"]["color"])
if "colorTransparent" in data["appearance"].keys(): s.setBoolean(["appearance", "colorTransparent"], data["appearance"]["colorTransparent"])
if "name" in data["appearance"]: s.set(["appearance", "name"], data["appearance"]["name"])
if "color" in data["appearance"]: s.set(["appearance", "color"], data["appearance"]["color"])
if "colorTransparent" in data["appearance"]: s.setBoolean(["appearance", "colorTransparent"], data["appearance"]["colorTransparent"])
if "defaultLanguage" in data["appearance"]: s.set(["appearance", "defaultLanguage"], data["appearance"]["defaultLanguage"])
if "showFahrenheitAlso" in data["appearance"]: s.setBoolean(["appearance", "showFahrenheitAlso"], data["appearance"]["showFahrenheitAlso"])
@@ -281,47 +282,48 @@ def _saveSettings(data):
if "defaultExtrusionLength" in data["printer"]: s.setInt(["printerParameters", "defaultExtrusionLength"], data["printer"]["defaultExtrusionLength"])
if "webcam" in data.keys():
if "streamUrl" in data["webcam"].keys(): s.set(["webcam", "stream"], data["webcam"]["streamUrl"])
if "snapshotUrl" in data["webcam"].keys(): s.set(["webcam", "snapshot"], data["webcam"]["snapshotUrl"])
if "ffmpegPath" in data["webcam"].keys(): s.set(["webcam", "ffmpeg"], data["webcam"]["ffmpegPath"])
if "bitrate" in data["webcam"].keys(): s.set(["webcam", "bitrate"], data["webcam"]["bitrate"])
if "ffmpegThreads" in data["webcam"].keys(): s.setInt(["webcam", "ffmpegThreads"], data["webcam"]["ffmpegThreads"])
if "watermark" in data["webcam"].keys(): s.setBoolean(["webcam", "watermark"], data["webcam"]["watermark"])
if "flipH" in data["webcam"].keys(): s.setBoolean(["webcam", "flipH"], data["webcam"]["flipH"])
if "flipV" in data["webcam"].keys(): s.setBoolean(["webcam", "flipV"], data["webcam"]["flipV"])
if "rotate90" in data["webcam"].keys(): s.setBoolean(["webcam", "rotate90"], data["webcam"]["rotate90"])
if "streamUrl" in data["webcam"]: s.set(["webcam", "stream"], data["webcam"]["streamUrl"])
if "snapshotUrl" in data["webcam"]: s.set(["webcam", "snapshot"], data["webcam"]["snapshotUrl"])
if "ffmpegPath" in data["webcam"]: s.set(["webcam", "ffmpeg"], data["webcam"]["ffmpegPath"])
if "bitrate" in data["webcam"]: s.set(["webcam", "bitrate"], data["webcam"]["bitrate"])
if "ffmpegThreads" in data["webcam"]: s.setInt(["webcam", "ffmpegThreads"], data["webcam"]["ffmpegThreads"])
if "watermark" in data["webcam"]: s.setBoolean(["webcam", "watermark"], data["webcam"]["watermark"])
if "flipH" in data["webcam"]: s.setBoolean(["webcam", "flipH"], data["webcam"]["flipH"])
if "flipV" in data["webcam"]: s.setBoolean(["webcam", "flipV"], data["webcam"]["flipV"])
if "rotate90" in data["webcam"]: s.setBoolean(["webcam", "rotate90"], data["webcam"]["rotate90"])
if "feature" in data.keys():
if "gcodeViewer" in data["feature"].keys(): s.setBoolean(["gcodeViewer", "enabled"], data["feature"]["gcodeViewer"])
if "sizeThreshold" in data["feature"].keys(): s.setInt(["gcodeViewer", "sizeThreshold"], data["feature"]["sizeThreshold"])
if "mobileSizeThreshold" in data["feature"].keys(): s.setInt(["gcodeViewer", "mobileSizeThreshold"], data["feature"]["mobileSizeThreshold"])
if "temperatureGraph" in data["feature"].keys(): s.setBoolean(["feature", "temperatureGraph"], data["feature"]["temperatureGraph"])
if "waitForStart" in data["feature"].keys(): s.setBoolean(["feature", "waitForStartOnConnect"], data["feature"]["waitForStart"])
if "alwaysSendChecksum" in data["feature"].keys(): s.setBoolean(["feature", "alwaysSendChecksum"], data["feature"]["alwaysSendChecksum"])
if "neverSendChecksum" in data["feature"].keys(): s.setBoolean(["feature", "neverSendChecksum"], data["feature"]["neverSendChecksum"])
if "sdSupport" in data["feature"].keys(): s.setBoolean(["feature", "sdSupport"], data["feature"]["sdSupport"])
if "sdRelativePath" in data["feature"].keys(): s.setBoolean(["feature", "sdRelativePath"], data["feature"]["sdRelativePath"])
if "sdAlwaysAvailable" in data["feature"].keys(): s.setBoolean(["feature", "sdAlwaysAvailable"], data["feature"]["sdAlwaysAvailable"])
if "swallowOkAfterResend" in data["feature"].keys(): s.setBoolean(["feature", "swallowOkAfterResend"], data["feature"]["swallowOkAfterResend"])
if "repetierTargetTemp" in data["feature"].keys(): s.setBoolean(["feature", "repetierTargetTemp"], data["feature"]["repetierTargetTemp"])
if "externalHeatupDetection" in data["feature"].keys(): s.setBoolean(["feature", "externalHeatupDetection"], data["feature"]["externalHeatupDetection"])
if "keyboardControl" in data["feature"].keys(): s.setBoolean(["feature", "keyboardControl"], data["feature"]["keyboardControl"])
if "gcodeViewer" in data["feature"]: s.setBoolean(["gcodeViewer", "enabled"], data["feature"]["gcodeViewer"])
if "sizeThreshold" in data["feature"]: s.setInt(["gcodeViewer", "sizeThreshold"], data["feature"]["sizeThreshold"])
if "mobileSizeThreshold" in data["feature"]: s.setInt(["gcodeViewer", "mobileSizeThreshold"], data["feature"]["mobileSizeThreshold"])
if "temperatureGraph" in data["feature"]: s.setBoolean(["feature", "temperatureGraph"], data["feature"]["temperatureGraph"])
if "waitForStart" in data["feature"]: s.setBoolean(["feature", "waitForStartOnConnect"], data["feature"]["waitForStart"])
if "alwaysSendChecksum" in data["feature"]: s.setBoolean(["feature", "alwaysSendChecksum"], data["feature"]["alwaysSendChecksum"])
if "neverSendChecksum" in data["feature"]: s.setBoolean(["feature", "neverSendChecksum"], data["feature"]["neverSendChecksum"])
if "sdSupport" in data["feature"]: s.setBoolean(["feature", "sdSupport"], data["feature"]["sdSupport"])
if "sdRelativePath" in data["feature"]: s.setBoolean(["feature", "sdRelativePath"], data["feature"]["sdRelativePath"])
if "sdAlwaysAvailable" in data["feature"]: s.setBoolean(["feature", "sdAlwaysAvailable"], data["feature"]["sdAlwaysAvailable"])
if "swallowOkAfterResend" in data["feature"]: s.setBoolean(["feature", "swallowOkAfterResend"], data["feature"]["swallowOkAfterResend"])
if "repetierTargetTemp" in data["feature"]: s.setBoolean(["feature", "repetierTargetTemp"], data["feature"]["repetierTargetTemp"])
if "externalHeatupDetection" in data["feature"]: s.setBoolean(["feature", "externalHeatupDetection"], data["feature"]["externalHeatupDetection"])
if "keyboardControl" in data["feature"]: s.setBoolean(["feature", "keyboardControl"], data["feature"]["keyboardControl"])
if "pollWatched" in data["feature"]: s.setBoolean(["feature", "pollWatched"], data["feature"]["pollWatched"])
if "ignoreIdenticalResends" in data["feature"]: s.setBoolean(["feature", "ignoreIdenticalResends"], data["feature"]["ignoreIdenticalResends"])
if "modelSizeDetection" in data["feature"]: s.setBoolean(["feature", "modelSizeDetection"], data["feature"]["modelSizeDetection"])
if "firmwareDetection" in data["feature"]: s.setBoolean(["feature", "firmwareDetection"], data["feature"]["firmwareDetection"])
if "printCancelConfirmation" in data["feature"]: s.setBoolean(["feature", "printCancelConfirmation"], data["feature"]["printCancelConfirmation"])
if "blockWhileDwelling" in data["feature"]: s.setBoolean(["feature", "blockWhileDwelling"], data["feature"]["blockWhileDwelling"])
if "serial" in data.keys():
if "autoconnect" in data["serial"].keys(): s.setBoolean(["serial", "autoconnect"], data["serial"]["autoconnect"])
if "port" in data["serial"].keys(): s.set(["serial", "port"], data["serial"]["port"])
if "baudrate" in data["serial"].keys(): s.setInt(["serial", "baudrate"], data["serial"]["baudrate"])
if "timeoutConnection" in data["serial"].keys(): s.setFloat(["serial", "timeout", "connection"], data["serial"]["timeoutConnection"])
if "timeoutDetection" in data["serial"].keys(): s.setFloat(["serial", "timeout", "detection"], data["serial"]["timeoutDetection"])
if "timeoutCommunication" in data["serial"].keys(): s.setFloat(["serial", "timeout", "communication"], data["serial"]["timeoutCommunication"])
if "timeoutTemperature" in data["serial"].keys(): s.setFloat(["serial", "timeout", "temperature"], data["serial"]["timeoutTemperature"])
if "timeoutTemperatureTargetSet" in data["serial"].keys(): s.setFloat(["serial", "timeout", "temperatureTargetSet"], data["serial"]["timeoutTemperatureTargetSet"])
if "timeoutSdStatus" in data["serial"].keys(): s.setFloat(["serial", "timeout", "sdStatus"], data["serial"]["timeoutSdStatus"])
if "autoconnect" in data["serial"]: s.setBoolean(["serial", "autoconnect"], data["serial"]["autoconnect"])
if "port" in data["serial"]: s.set(["serial", "port"], data["serial"]["port"])
if "baudrate" in data["serial"]: s.setInt(["serial", "baudrate"], data["serial"]["baudrate"])
if "timeoutConnection" in data["serial"]: s.setFloat(["serial", "timeout", "connection"], data["serial"]["timeoutConnection"])
if "timeoutDetection" in data["serial"]: s.setFloat(["serial", "timeout", "detection"], data["serial"]["timeoutDetection"])
if "timeoutCommunication" in data["serial"]: s.setFloat(["serial", "timeout", "communication"], data["serial"]["timeoutCommunication"])
if "timeoutTemperature" in data["serial"]: s.setFloat(["serial", "timeout", "temperature"], data["serial"]["timeoutTemperature"])
if "timeoutTemperatureTargetSet" in data["serial"]: s.setFloat(["serial", "timeout", "temperatureTargetSet"], data["serial"]["timeoutTemperatureTargetSet"])
if "timeoutSdStatus" in data["serial"]: s.setFloat(["serial", "timeout", "sdStatus"], data["serial"]["timeoutSdStatus"])
if "additionalPorts" in data["serial"] and isinstance(data["serial"]["additionalPorts"], (list, tuple)): s.set(["serial", "additionalPorts"], data["serial"]["additionalPorts"])
if "additionalBaudrates" in data["serial"] and isinstance(data["serial"]["additionalBaudrates"], (list, tuple)): s.set(["serial", "additionalBaudrates"], data["serial"]["additionalBaudrates"])
if "longRunningCommands" in data["serial"] and isinstance(data["serial"]["longRunningCommands"], (list, tuple)): s.set(["serial", "longRunningCommands"], data["serial"]["longRunningCommands"])
@@ -336,7 +338,7 @@ def _saveSettings(data):
if "maxTimeoutsLong" in data["serial"]: s.setInt(["serial", "maxCommunicationTimeouts", "long"], data["serial"]["maxTimeoutsLong"])
oldLog = s.getBoolean(["serial", "log"])
if "log" in data["serial"].keys(): s.setBoolean(["serial", "log"], data["serial"]["log"])
if "log" in data["serial"]: s.setBoolean(["serial", "log"], data["serial"]["log"])
if oldLog and not s.getBoolean(["serial", "log"]):
# disable debug logging to serial.log
logging.getLogger("SERIAL").debug("Disabling serial logging")
@@ -347,22 +349,22 @@ def _saveSettings(data):
logging.getLogger("SERIAL").debug("Enabling serial logging")
if "folder" in data.keys():
if "uploads" in data["folder"].keys(): s.setBaseFolder("uploads", data["folder"]["uploads"])
if "timelapse" in data["folder"].keys(): s.setBaseFolder("timelapse", data["folder"]["timelapse"])
if "timelapseTmp" in data["folder"].keys(): s.setBaseFolder("timelapse_tmp", data["folder"]["timelapseTmp"])
if "logs" in data["folder"].keys(): s.setBaseFolder("logs", data["folder"]["logs"])
if "watched" in data["folder"].keys(): s.setBaseFolder("watched", data["folder"]["watched"])
if "uploads" in data["folder"]: s.setBaseFolder("uploads", data["folder"]["uploads"])
if "timelapse" in data["folder"]: s.setBaseFolder("timelapse", data["folder"]["timelapse"])
if "timelapseTmp" in data["folder"]: s.setBaseFolder("timelapse_tmp", data["folder"]["timelapseTmp"])
if "logs" in data["folder"]: s.setBaseFolder("logs", data["folder"]["logs"])
if "watched" in data["folder"]: s.setBaseFolder("watched", data["folder"]["watched"])
if "temperature" in data.keys():
if "profiles" in data["temperature"].keys(): s.set(["temperature", "profiles"], data["temperature"]["profiles"])
if "cutoff" in data["temperature"].keys(): s.setInt(["temperature", "cutoff"], data["temperature"]["cutoff"])
if "profiles" in data["temperature"]: s.set(["temperature", "profiles"], data["temperature"]["profiles"])
if "cutoff" in data["temperature"]: s.setInt(["temperature", "cutoff"], data["temperature"]["cutoff"])
if "terminalFilters" in data.keys():
s.set(["terminalFilters"], data["terminalFilters"])
if "system" in data.keys():
if "actions" in data["system"].keys(): s.set(["system", "actions"], data["system"]["actions"])
if "events" in data["system"].keys(): s.set(["system", "events"], data["system"]["events"])
if "actions" in data["system"]: s.set(["system", "actions"], data["system"]["actions"])
if "events" in data["system"]: s.set(["system", "events"], data["system"]["events"])
if "scripts" in data:
if "gcode" in data["scripts"] and isinstance(data["scripts"]["gcode"], dict):
@@ -373,9 +375,9 @@ def _saveSettings(data):
if "server" in data:
if "commands" in data["server"]:
if "systemShutdownCommand" in data["server"]["commands"].keys(): s.set(["server", "commands", "systemShutdownCommand"], data["server"]["commands"]["systemShutdownCommand"])
if "systemRestartCommand" in data["server"]["commands"].keys(): s.set(["server", "commands", "systemRestartCommand"], data["server"]["commands"]["systemRestartCommand"])
if "serverRestartCommand" in data["server"]["commands"].keys(): s.set(["server", "commands", "serverRestartCommand"], data["server"]["commands"]["serverRestartCommand"])
if "systemShutdownCommand" in data["server"]["commands"]: s.set(["server", "commands", "systemShutdownCommand"], data["server"]["commands"]["systemShutdownCommand"])
if "systemRestartCommand" in data["server"]["commands"]: s.set(["server", "commands", "systemRestartCommand"], data["server"]["commands"]["systemRestartCommand"])
if "serverRestartCommand" in data["server"]["commands"]: s.set(["server", "commands", "serverRestartCommand"], data["server"]["commands"]["serverRestartCommand"])
if "diskspace" in data["server"]:
if "warning" in data["server"]["diskspace"]: s.setInt(["server", "diskspace", "warning"], data["server"]["diskspace"]["warning"])
if "critical" in data["server"]["diskspace"]: s.setInt(["server", "diskspace", "critical"], data["server"]["diskspace"]["critical"])
+3
View File
@@ -43,6 +43,8 @@ def _etag(configured, lm=None):
else:
hash.update(repr(sorted(slicingManager.registered_slicers)))
hash.update("v2") # increment version if we change the API format
return hash.hexdigest()
@@ -72,6 +74,7 @@ def slicingListAll():
result[slicer] = dict(
key=slicer,
displayName=slicer_impl.get_slicer_properties()["name"],
sameDevice=slicer_impl.get_slicer_properties()["same_device"],
default=default_slicer == slicer,
configured=slicer_impl.is_slicer_configured(),
profiles=_getSlicingProfilesData(slicer),
+26 -7
View File
@@ -72,9 +72,19 @@ def executeSystemCommand(source, command):
if not "command" in command_spec:
return make_response("Command {}:{} does not define a command to execute, can't proceed".format(source, command), 500)
async = command_spec["async"] if "async" in command_spec else False
ignore = command_spec["ignore"] if "ignore" in command_spec else False
do_async = command_spec.get("async", False)
do_ignore = command_spec.get("ignore", False)
logger.info("Performing command for {}:{}: {}".format(source, command, command_spec["command"]))
try:
if "before" in command_spec and callable(command_spec["before"]):
command_spec["before"]()
except Exception as e:
if not do_ignore:
error = "Command \"before\" failed: {}".format(str(e))
logger.warn(error)
return make_response(error, 500)
try:
# we run this with shell=True since we have to trust whatever
# our admin configured as command and since we want to allow
@@ -83,9 +93,9 @@ def executeSystemCommand(source, command):
stdout=sarge.Capture(),
stderr=sarge.Capture(),
shell=True,
async=async)
if not async:
if not ignore and p.returncode != 0:
async=do_async)
if not do_async:
if not do_ignore and p.returncode != 0:
returncode = p.returncode
stdout_text = p.stdout.text
stderr_text = p.stderr.text
@@ -94,7 +104,7 @@ def executeSystemCommand(source, command):
logger.warn(error)
return make_response(error, 500)
except Exception as e:
if not ignore:
if not do_ignore:
error = "Command failed: {}".format(str(e))
logger.warn(error)
return make_response(error, 500)
@@ -126,6 +136,10 @@ def _get_command_spec(source, action):
def _get_core_command_specs():
def enable_safe_mode():
s().set(["server", "startOnceInSafeMode"], True)
s().save()
commands = collections.OrderedDict(
shutdown=dict(
command=s().get(["server", "commands", "systemShutdownCommand"]),
@@ -138,7 +152,12 @@ def _get_core_command_specs():
restart=dict(
command=s().get(["server", "commands", "serverRestartCommand"]),
name=gettext("Restart OctoPrint"),
confirm=gettext("You are about to restart the OctoPrint server."))
confirm=gettext("You are about to restart the OctoPrint server.")),
restart_safe=dict(
command=s().get(["server", "commands", "serverRestartCommand"]),
name=gettext("Restart OctoPrint in safe mode"),
confirm=gettext("You are about to restart the OctoPrint server in safe mode."),
before=enable_safe_mode)
)
available_commands = collections.OrderedDict()
+36 -27
View File
@@ -10,6 +10,8 @@ import octoprint.timelapse
import octoprint.server
from octoprint.users import ApiUser
from octoprint.util import deprecated
import flask as _flask
from . import flask
@@ -18,51 +20,58 @@ from . import tornado
from . import watchdog
def apiKeyRequestHandler():
def enforceApiKeyRequestHandler():
"""
``before_request`` handler for blueprints for which all requests need to be made supplying an API key.
This may be the UI_API_KEY, in which case the underlying request processing will directly take place, or it may be
the global, an app specific or a user specific one. In any case it has to be present and must be valid, so anything
other than the above types will result in the application denying the request.
``before_request`` handler for blueprints which makes sure an API key is provided
"""
import octoprint.server
if _flask.request.method == 'OPTIONS' and settings().getBoolean(["api", "allowCrossOrigin"]):
return optionsAllowOrigin(_flask.request)
if _flask.request.method == 'OPTIONS':
# we ignore OPTIONS requests here
return
if _flask.request.endpoint == "static" or _flask.request.endpoint.endswith(".static"):
if _flask.request.endpoint and (_flask.request.endpoint == "static" or _flask.request.endpoint.endswith(".static")):
# no further handling for static resources
return
apikey = get_api_key(_flask.request)
if apikey is None:
# no api key => 401
return _flask.make_response("No API key provided", 401)
if apikey == octoprint.server.UI_API_KEY:
# ui api key => continue regular request processing
return
if not settings().getBoolean(["api", "enabled"]):
if apikey != octoprint.server.UI_API_KEY and not settings().getBoolean(["api", "enabled"]):
# api disabled => 401
return _flask.make_response("API disabled", 401)
if apikey == settings().get(["api", "key"]):
# global api key => continue regular request processing
return
apiKeyRequestHandler = deprecated("apiKeyRequestHandler has been renamed to enforceApiKeyRequestHandler")(enforceApiKeyRequestHandler)
if octoprint.server.appSessionManager.validate(apikey):
# app session key => continue regular request processing
return
user = get_user_for_apikey(apikey)
if user is not None:
# user specific api key => continue regular request processing
return
def loginFromApiKeyRequestHandler():
"""
``before_request`` handler for blueprints which creates a login session for the provided api key (if available)
# invalid api key => 401
return _flask.make_response("Invalid API key", 401)
UI_API_KEY and app session keys are handled as anonymous keys here and ignored.
"""
apikey = get_api_key(_flask.request)
if apikey and apikey != octoprint.server.UI_API_KEY and not octoprint.server.appSessionManager.validate(apikey):
user = get_user_for_apikey(apikey)
if user is not None and _flask.ext.login.login_user(user, remember=False):
_flask.ext.principal.identity_changed.send(_flask.current_app._get_current_object(),
identity=_flask.ext.principal.Identity(user.get_id()))
else:
return _flask.make_response("Invalid API key", 401)
def corsRequestHandler():
"""
``before_request`` handler for blueprints which sets CORS headers for OPTIONS requests if enabled
"""
if _flask.request.method == 'OPTIONS' and settings().getBoolean(["api", "allowCrossOrigin"]):
# reply to OPTIONS request for CORS headers
return optionsAllowOrigin(_flask.request)
def corsResponseHandler(resp):
+15 -32
View File
@@ -62,12 +62,18 @@ def enable_additional_translations(default_locale="en", additional_folders=None)
continue
if filter(lambda x: x.name.endswith('.mo'), scandir(locale_dir)):
result.append(Locale.parse(entry.name))
if not result:
result.append(Locale.parse(self._default_locale))
return result
dirs = additional_folders + [os.path.join(self.app.root_path, 'translations')]
# translations from plugins
plugins = octoprint.plugin.plugin_manager().enabled_plugins
for name, plugin in plugins.items():
plugin_translation_dir = os.path.join(plugin.location, 'translations')
if not os.path.isdir(plugin_translation_dir):
continue
dirs.append(plugin_translation_dir)
result = [Locale.parse(default_locale)]
for dir in dirs:
@@ -104,20 +110,20 @@ def enable_additional_translations(default_locale="en", additional_folders=None)
else:
if isinstance(plugin_translations, support.Translations):
translations = translations.merge(plugin_translations)
logger.debug("Using translation folder {dirname} for locale {locale} of plugin {name}".format(**locals()))
logger.debug("Using translation plugin folder {dirname} from plugin {name} for locale {locale}".format(**locals()))
break
else:
logger.debug("No translations for locale {locale} for plugin {name}".format(**locals()))
logger.debug("No translations for locale {locale} from plugin {name}".format(**locals()))
# core translations
dirs = additional_folders + [os.path.join(ctx.app.root_path, 'translations')]
for dirname in dirs:
core_translations = support.Translations.load(dirname, [locale])
if isinstance(core_translations, support.Translations):
logger.debug("Using translation folder {dirname} for locale {locale} of core translations".format(**locals()))
logger.debug("Using translation core folder {dirname} for locale {locale}".format(**locals()))
break
else:
logger.debug("No core translations for locale {locale}")
logger.debug("No translations for locale {} in core folders".format(locale))
translations = translations.merge(core_translations)
ctx.babel_translations = translations
@@ -1083,20 +1089,13 @@ def restricted_access(func):
"""
If you decorate a view with this, it will ensure that first setup has been
done for OctoPrint's Access Control plus that any conditions of the
login_required decorator are met. It also allows to login using the masterkey or any
of the user's apikeys if API access is enabled globally and for the decorated view.
login_required decorator are met (possibly through a session already created
by octoprint.server.util.apiKeyRequestHandler earlier in the request processing).
If OctoPrint's Access Control has not been setup yet (indicated by the "firstRun"
flag from the settings being set to True and the userManager not indicating
that it's user database has been customized from default), the decorator
will cause a HTTP 403 status code to be returned by the decorated resource.
If the API key matches the UI API key, the result of calling login_required for the
view will be returned (browser session mode).
Otherwise the API key will be attempted to be resolved to a user. If that is
successful the user will be logged in and the view will be called directly.
Otherwise a HTTP 401 status code will be returned.
"""
@functools.wraps(func)
def decorated_view(*args, **kwargs):
@@ -1104,23 +1103,7 @@ def restricted_access(func):
if settings().getBoolean(["server", "firstRun"]) and settings().getBoolean(["accessControl", "enabled"]) and (octoprint.server.userManager is None or not octoprint.server.userManager.hasBeenCustomized()):
return flask.make_response("OctoPrint isn't setup yet", 403)
apikey = octoprint.server.util.get_api_key(flask.request)
if apikey == octoprint.server.UI_API_KEY:
# UI API key => call regular login_required decorator, we are using browser sessions here
return flask.ext.login.login_required(func)(*args, **kwargs)
# try to determine user for key
user = octoprint.server.util.get_user_for_apikey(apikey)
if user is None:
# no user or no key => go away
return flask.make_response("Invalid API key", 401)
if not flask.ext.login.login_user(user, remember=False):
# user for API key could not be logged in => go away
return flask.make_response("Invalid API key", 401)
flask.ext.principal.identity_changed.send(flask.current_app._get_current_object(), identity=flask.ext.principal.Identity(user.get_id()))
return func(*args, **kwargs)
return flask.ext.login.login_required(func)(*args, **kwargs)
return decorated_view
+45 -18
View File
@@ -7,6 +7,8 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms
import logging
import os
import time
import threading
import watchdog.events
import octoprint.filemanager
@@ -32,39 +34,64 @@ class GcodeWatchdogHandler(watchdog.events.PatternMatchingEventHandler):
try:
file_wrapper = octoprint.filemanager.util.DiskFileWrapper(os.path.basename(path), path)
# determine current job
currentFilename = None
currentOrigin = None
currentJob = self._printer.get_current_job()
if currentJob is not None and "file" in currentJob.keys():
currentJobFile = currentJob["file"]
if "name" in currentJobFile.keys() and "origin" in currentJobFile.keys():
currentFilename = currentJobFile["name"]
currentOrigin = currentJobFile["origin"]
# determine future filename of file to be uploaded, abort if it can't be uploaded
try:
futureFilename = self._file_manager.sanitize_name(octoprint.filemanager.FileDestinations.LOCAL, file_wrapper.filename)
futurePath, futureFilename = self._file_manager.sanitize(octoprint.filemanager.FileDestinations.LOCAL, file_wrapper.filename)
except:
futurePath = None
futureFilename = None
if futureFilename is None or (len(self._file_manager.registered_slicers) == 0 and not octoprint.filemanager.valid_file_type(futureFilename)):
return
# prohibit overwriting currently selected file while it's being printed
if futureFilename == currentFilename and currentOrigin == octoprint.filemanager.FileDestinations.LOCAL and self._printer.is_printing() or self._printer.is_paused():
futureFullPath = self._file_manager.join_path(octoprint.filemanager.FileDestinations.LOCAL, futurePath, futureFilename)
futureFullPathInStorage = self._file_manager.path_in_storage(octoprint.filemanager.FileDestinations.LOCAL, futureFullPath)
if not self._printer.can_modify_file(futureFullPathInStorage, False):
return
self._file_manager.add_file(octoprint.filemanager.FileDestinations.LOCAL,
file_wrapper.filename,
file_wrapper,
allow_overwrite=True)
reselect = self._printer.is_current_file(futureFullPathInStorage, False)
added_file = self._file_manager.add_file(octoprint.filemanager.FileDestinations.LOCAL,
file_wrapper.filename,
file_wrapper,
allow_overwrite=True)
if os.path.exists(path):
try:
os.remove(path)
except:
self._logger.exception("Error while trying to clear a file from the watched folder")
pass
if reselect:
self._printer.select_file(self._file_manager.path_on_disk(octoprint.filemanager.FileDestinations.LOCAL,
added_file),
False)
except:
self._logger.exception("There was an error while processing the file {} in the watched folder".format(path))
def on_created(self, event):
self._upload(event.src_path)
thread = threading.Thread(target=self._repeatedly_check, args=(event.src_path,))
thread.daemon = True
thread.start()
def _repeatedly_check(self, path, interval=1, stable=5):
last_size = os.stat(path).st_size
countdown = stable
while True:
new_size = os.stat(path).st_size
if new_size == last_size:
self._logger.debug("File at {} is no longer growing, counting down: {}".format(path, countdown))
countdown -= 1
if countdown <= 0:
break
else:
self._logger.debug("File at {} is still growing (last: {}, new: {}), waiting...".format(path, last_size, new_size))
countdown = stable
last_size = new_size
time.sleep(interval)
self._logger.debug("File at {} is stable, moving it".format(path))
self._upload(path)
+80 -33
View File
@@ -7,6 +7,7 @@ __copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms
import os
import datetime
import codecs
from collections import defaultdict
from flask import request, g, url_for, make_response, render_template, send_from_directory, redirect, abort
@@ -173,7 +174,27 @@ def index():
_templates[locale], _plugin_names, _plugin_vars = _process_templates()
now = datetime.datetime.utcnow()
render_kwargs = _get_render_kwargs(_templates[locale], _plugin_names, _plugin_vars, now)
enable_accesscontrol = userManager.enabled
enable_gcodeviewer = settings().getBoolean(["gcodeViewer", "enabled"])
enable_timelapse = bool(settings().get(["webcam", "snapshot"]) and settings().get(["webcam", "ffmpeg"]))
def default_template_filter(template_type, template_key):
if template_type == "navbar":
return template_key != "login" or enable_accesscontrol
elif template_type == "tab":
return (template_key != "gcodeviewer" or enable_gcodeviewer) and \
(template_key != "timelapse" or enable_timelapse)
elif template_type == "settings":
return template_key != "accesscontrol" or enable_accesscontrol
elif template_type == "usersettings":
return enable_accesscontrol
else:
return True
default_additional_etag = [enable_accesscontrol,
enable_gcodeviewer,
enable_timelapse]
def get_preemptively_cached_view(key, view, data=None, additional_request_data=None, additional_unless=None):
if (data is None and additional_request_data is None) or g.locale is None:
@@ -189,7 +210,10 @@ def index():
data=d,
unless=unless)(view)
def get_cached_view(key, view, additional_key_data=None, additional_files=None, custom_files=None, custom_etag=None, custom_lastmodified=None):
def get_cached_view(key, view, additional_key_data=None, additional_files=None, additional_etag=None, custom_files=None, custom_etag=None, custom_lastmodified=None):
if additional_etag is None:
additional_etag = []
def cache_key():
return _cache_key(key, additional_key_data=additional_key_data)
@@ -199,11 +223,11 @@ def index():
lastmodified_ok = util.flask.check_lastmodified(lastmodified)
etag_ok = util.flask.check_etag(compute_etag(files=files,
lastmodified=lastmodified,
additional=cache_key()))
additional=[cache_key()] + additional_etag))
return lastmodified_ok and etag_ok
def validate_cache(cached):
etag_different = compute_etag(additional=cache_key()) != cached.get_etag()[0]
etag_different = compute_etag(additional=[cache_key()] + additional_etag) != cached.get_etag()[0]
return force_refresh or etag_different
def collect_files():
@@ -272,12 +296,12 @@ def index():
if lastmodified:
hash.update(lastmodified)
for add in additional:
hash.update(add)
hash.update(str(add))
return hash.hexdigest()
decorated_view = view
decorated_view = util.flask.lastmodified(lambda _: compute_lastmodified())(decorated_view)
decorated_view = util.flask.etagged(lambda _: compute_etag(additional=cache_key()))(decorated_view)
decorated_view = util.flask.etagged(lambda _: compute_etag(additional=[cache_key()] + additional_etag))(decorated_view)
decorated_view = util.flask.cached(timeout=-1,
refreshif=validate_cache,
key=cache_key,
@@ -292,7 +316,8 @@ def index():
additional_files=p.get_ui_additional_tracked_files,
custom_files=p.get_ui_custom_tracked_files,
custom_etag=p.get_ui_custom_etag,
custom_lastmodified=p.get_ui_custom_lastmodified)
custom_lastmodified=p.get_ui_custom_lastmodified,
additional_etag=p.get_ui_additional_etag(default_additional_etag))
if preemptive_cache_enabled and p.get_ui_preemptive_caching_enabled():
view = get_preemptively_cached_view(p._identifier,
@@ -303,12 +328,30 @@ def index():
else:
view = cached
template_filter = p.get_ui_custom_template_filter(default_template_filter)
if template_filter is not None and callable(template_filter):
filtered_templates = _filter_templates(_templates[locale], template_filter)
else:
filtered_templates = _templates[locale]
render_kwargs = _get_render_kwargs(filtered_templates,
_plugin_names,
_plugin_vars,
now)
return view(now, request, render_kwargs)
def default_view():
wizard = wizard_active(_templates[locale])
enable_accesscontrol = userManager.enabled
filtered_templates = _filter_templates(_templates[locale], default_template_filter)
wizard = wizard_active(filtered_templates)
accesscontrol_active = enable_accesscontrol and userManager.hasBeenCustomized()
render_kwargs = _get_render_kwargs(filtered_templates,
_plugin_names,
_plugin_vars,
now)
render_kwargs.update(dict(
webcamStream=settings().get(["webcam", "stream"]),
enableTemperatureGraph=settings().get(["feature", "temperatureGraph"]),
@@ -330,7 +373,8 @@ def index():
return r
cached = get_cached_view("_default",
make_default_ui)
make_default_ui,
additional_etag=default_additional_etag)
preemptively_cached = get_preemptively_cached_view("_default",
cached,
dict(),
@@ -395,12 +439,7 @@ def _get_render_kwargs(templates, plugin_names, plugin_vars, now):
def _process_templates():
enable_accesscontrol = userManager.enabled
first_run = settings().getBoolean(["server", "firstRun"])
enable_gcodeviewer = settings().getBoolean(["gcodeViewer", "enabled"])
enable_timelapse = (settings().get(["webcam", "snapshot"]) and settings().get(["webcam", "ffmpeg"]))
enable_systemmenu = settings().get(["system"]) is not None and settings().get(["system", "actions"]) is not None
preferred_stylesheet = settings().get(["devel", "stylesheet"])
##~~ prepare templates
@@ -472,12 +511,10 @@ def _process_templates():
# navbar
templates["navbar"]["entries"] = dict(
settings=dict(template="navbar/settings.jinja2", _div="navbar_settings", styles=["display: none"], data_bind="visible: loginState.isAdmin")
settings=dict(template="navbar/settings.jinja2", _div="navbar_settings", styles=["display: none"], data_bind="visible: loginState.isAdmin"),
systemmenu=dict(template="navbar/systemmenu.jinja2", _div="navbar_systemmenu", styles=["display: none"], classes=["dropdown"], data_bind="visible: loginState.isAdmin", custom_bindings=False),
login=dict(template="navbar/login.jinja2", _div="navbar_login", classes=["dropdown"], custom_bindings=False),
)
if enable_accesscontrol:
templates["navbar"]["entries"]["login"] = dict(template="navbar/login.jinja2", _div="navbar_login", classes=["dropdown"], custom_bindings=False)
if enable_systemmenu:
templates["navbar"]["entries"]["systemmenu"] = dict(template="navbar/systemmenu.jinja2", _div="navbar_systemmenu", styles=["display: none"], classes=["dropdown"], data_bind="visible: loginState.isAdmin", custom_bindings=False)
# sidebar
@@ -492,12 +529,10 @@ def _process_templates():
templates["tab"]["entries"] = dict(
temperature=(gettext("Temperature"), dict(template="tabs/temperature.jinja2", _div="temp")),
control=(gettext("Control"), dict(template="tabs/control.jinja2", _div="control")),
gcodeviewer=(gettext("GCode Viewer"), dict(template="tabs/gcodeviewer.jinja2", _div="gcode")),
terminal=(gettext("Terminal"), dict(template="tabs/terminal.jinja2", _div="term")),
timelapse=(gettext("Timelapse"), dict(template="tabs/timelapse.jinja2", _div="timelapse"))
)
if enable_gcodeviewer:
templates["tab"]["entries"]["gcodeviewer"] = (gettext("GCode Viewer"), dict(template="tabs/gcodeviewer.jinja2", _div="gcode"))
if enable_timelapse:
templates["tab"]["entries"]["timelapse"] = (gettext("Timelapse"), dict(template="tabs/timelapse.jinja2", _div="timelapse"))
# settings dialog
@@ -519,21 +554,19 @@ def _process_templates():
section_octoprint=(gettext("OctoPrint"), None),
accesscontrol=(gettext("Access Control"), dict(template="dialogs/settings/accesscontrol.jinja2", _div="settings_users", custom_bindings=False)),
folders=(gettext("Folders"), dict(template="dialogs/settings/folders.jinja2", _div="settings_folders", custom_bindings=False)),
appearance=(gettext("Appearance"), dict(template="dialogs/settings/appearance.jinja2", _div="settings_appearance", custom_bindings=False)),
logs=(gettext("Logs"), dict(template="dialogs/settings/logs.jinja2", _div="settings_logs")),
server=(gettext("Server"), dict(template="dialogs/settings/server.jinja2", _div="settings_server", custom_bindings=False)),
)
if enable_accesscontrol:
templates["settings"]["entries"]["accesscontrol"] = (gettext("Access Control"), dict(template="dialogs/settings/accesscontrol.jinja2", _div="settings_users", custom_bindings=False))
# user settings dialog
if enable_accesscontrol:
templates["usersettings"]["entries"] = dict(
access=(gettext("Access"), dict(template="dialogs/usersettings/access.jinja2", _div="usersettings_access", custom_bindings=False)),
interface=(gettext("Interface"), dict(template="dialogs/usersettings/interface.jinja2", _div="usersettings_interface", custom_bindings=False)),
)
templates["usersettings"]["entries"] = dict(
access=(gettext("Access"), dict(template="dialogs/usersettings/access.jinja2", _div="usersettings_access", custom_bindings=False)),
interface=(gettext("Interface"), dict(template="dialogs/usersettings/interface.jinja2", _div="usersettings_interface", custom_bindings=False)),
)
# wizard
@@ -783,6 +816,19 @@ def _process_template_config(name, implementation, rule, config=None, counter=1)
return data
def _filter_templates(templates, template_filter):
filtered_templates = dict()
for template_type, template_collection in templates.items():
filtered_entries = dict()
for template_key, template_entry in template_collection["entries"].items():
if template_filter(template_type, template_key):
filtered_entries[template_key] = template_entry
filtered_templates[template_type] = dict(order=filter(lambda x: x in filtered_entries,
template_collection["order"]),
entries=filtered_entries)
return filtered_templates
@app.route("/robots.txt")
@util.flask.cached(timeout=-1)
def robotsTxt():
@@ -924,14 +970,15 @@ def _get_translations(locale, domain):
def messages_from_po(path, locale, domain):
messages = dict()
with file(path) as f:
with codecs.open(path, encoding="utf-8") as f:
catalog = read_po(f, locale=locale, domain=domain)
for message in catalog:
message_id = message.id
if isinstance(message_id, (list, tuple)):
message_id = message_id[0]
messages[message_id] = message.string
if message.string:
messages[message_id] = message.string
return messages, catalog.plural_expr
+21 -10
View File
@@ -168,7 +168,6 @@ default_settings = {
"options": {},
"postRoll": 0,
"fps": 25,
"capturePostRoll": True
},
"cleanTmpAfterDays": 7
},
@@ -180,7 +179,8 @@ default_settings = {
"gcodeAnalysis": {
"maxExtruders": 10,
"throttle_normalprio": 0.01,
"throttle_highprio": 0.0
"throttle_highprio": 0.0,
"throttle_lines": 100
},
"feature": {
"temperatureGraph": True,
@@ -203,7 +203,8 @@ default_settings = {
"supportFAsCommand": False,
"modelSizeDetection": True,
"firmwareDetection": True,
"printCancelConfirmation": True
"printCancelConfirmation": True,
"blockWhileDwelling": False
},
"folder": {
"uploads": None,
@@ -243,7 +244,7 @@ default_settings = {
"showFahrenheitAlso": False,
"components": {
"order": {
"navbar": ["settings", "systemmenu", "login", "plugin_announcements"],
"navbar": ["settings", "systemmenu", "plugin_announcements", "login"],
"sidebar": ["connection", "state", "files"],
"tab": ["temperature", "control", "gcodeviewer", "terminal", "timelapse"],
"settings": [
@@ -335,7 +336,6 @@ default_settings = {
"enabled": False,
"okAfterResend": False,
"forceChecksum": False,
"okWithLinenumber": False,
"numExtruders": 1,
"includeCurrentToolInTemps": True,
"includeFilenameInOpened": True,
@@ -356,7 +356,12 @@ default_settings = {
"echoOnM117": True,
"brokenM29": True,
"supportF": False,
"firmwareName": "Virtual Marlin 1.0"
"firmwareName": "Virtual Marlin 1.0",
"sharedNozzle": False,
"sendBusy": False,
"simulateReset": True,
"preparedOks": [],
"okFormatString": "ok"
}
}
}
@@ -551,7 +556,8 @@ class Settings(object):
self._configfile = os.path.join(self._basedir, "config.yaml")
self.load(migrate=True)
if self.get(["api", "key"]) is None:
apikey = self.get(["api", "key"])
if not apikey or apikey == "n/a":
self.set(["api", "key"], ''.join('%02X' % z for z in bytes(uuid.uuid4().bytes)))
self.save(force=True)
@@ -1396,13 +1402,18 @@ class Settings(object):
try:
current = chain.get_by_path(path)
except KeyError:
current = None
try:
default_value = chain.get_by_path(path, only_defaults=True)
in_local = chain.has_path(path, only_local=True)
in_defaults = chain.has_path(path, only_defaults=True)
except KeyError:
if error_on_path:
raise NoSuchSettingsPath()
return
default_value = None
in_local = chain.has_path(path, only_local=True)
in_defaults = chain.has_path(path, only_defaults=True)
if not force and in_defaults and in_local and default_value == value:
try:
+1 -1
View File
@@ -1 +1 @@
.btn{display:inline-block;*display:inline;*zoom:1;padding:4px 12px;margin-bottom:0;font-size:14px;line-height:20px;text-align:center;vertical-align:middle;cursor:pointer;color:#333;text-shadow:0 1px 1px rgba(255,255,255,.75);background-color:#f5f5f5;background-image:-moz-linear-gradient(top,#fff,#e6e6e6);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fff),to(#e6e6e6));background-image:-webkit-linear-gradient(top,#fff,#e6e6e6);background-image:-o-linear-gradient(top,#fff,#e6e6e6);background-image:linear-gradient(to bottom,#fff,#e6e6e6);background-repeat:repeat-x;*background-color:#e6e6e6;filter:progid:DXImageTransform.Microsoft.gradient(enabled=false);border:1px solid #ccc;*border:0;border-bottom-color:#b3b3b3;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;*margin-left:.3em;-webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05);box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05)}.btn.active,.btn.disabled,.btn:active,.btn:focus,.btn:hover,.btn[disabled]{color:#333;background-color:#e6e6e6;*background-color:#d9d9d9}.btn.active,.btn:active{background-color:#ccc \9}.btn:first-child{*margin-left:0}.btn:focus,.btn:hover{color:#333;text-decoration:none;background-position:0 -15px;-webkit-transition:background-position .1s linear;-moz-transition:background-position .1s linear;-o-transition:background-position .1s linear;transition:background-position .1s linear}.btn:focus{outline:#333 dotted thin;outline:-webkit-focus-ring-color auto 5px;outline-offset:-2px}.btn.active,.btn:active{background-image:none;outline:0;-webkit-box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05);box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05)}.btn.disabled,.btn[disabled]{cursor:default;background-image:none;opacity:.65;filter:alpha(opacity=65);-webkit-box-shadow:none;-moz-box-shadow:none;box-shadow:none}.btn-large{padding:11px 19px;font-size:17.5px;-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px}.btn-large [class*=" icon-"],.btn-large [class^=icon-]{margin-top:4px}.btn-small{padding:2px 10px;font-size:11.9px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.btn-small [class*=" icon-"],.btn-small [class^=icon-]{margin-top:0}.btn-mini [class*=" icon-"],.btn-mini [class^=icon-]{margin-top:-1px}.btn-mini{padding:0 6px;font-size:10.5px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.btn-block{display:block;width:100%;padding-left:0;padding-right:0;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}.btn-block+.btn-block{margin-top:5px}input[type=submit].btn-block,input[type=reset].btn-block,input[type=button].btn-block{width:100%}.btn-primary{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,.25);background-color:#006dcc;background-image:-moz-linear-gradient(top,#08c,#04c);background-image:-webkit-gradient(linear,0 0,0 100%,from(#08c),to(#04c));background-image:-webkit-linear-gradient(top,#08c,#04c);background-image:-o-linear-gradient(top,#08c,#04c);background-image:linear-gradient(to bottom,#08c,#04c);background-repeat:repeat-x;border-color:#04c #04c #002a80;border-color:rgba(0,0,0,.1) rgba(0,0,0,.1) rgba(0,0,0,.25);*background-color:#04c;filter:progid:DXImageTransform.Microsoft.gradient(enabled=false)}.btn-primary.active,.btn-primary.disabled,.btn-primary:active,.btn-primary:focus,.btn-primary:hover,.btn-primary[disabled]{color:#fff;background-color:#04c;*background-color:#003bb3}.btn-primary.active,.btn-primary:active{background-color:#039 \9}.btn-warning{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,.25);background-color:#faa732;background-image:-moz-linear-gradient(top,#fbb450,#f89406);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fbb450),to(#f89406));background-image:-webkit-linear-gradient(top,#fbb450,#f89406);background-image:-o-linear-gradient(top,#fbb450,#f89406);background-image:linear-gradient(to bottom,#fbb450,#f89406);background-repeat:repeat-x;border-color:#f89406 #f89406 #ad6704;border-color:rgba(0,0,0,.1) rgba(0,0,0,.1) rgba(0,0,0,.25);*background-color:#f89406;filter:progid:DXImageTransform.Microsoft.gradient(enabled=false)}.btn-warning.active,.btn-warning.disabled,.btn-warning:active,.btn-warning:focus,.btn-warning:hover,.btn-warning[disabled]{color:#fff;background-color:#f89406;*background-color:#df8505}.btn-warning.active,.btn-warning:active{background-color:#c67605 \9}.btn-danger{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,.25);background-color:#da4f49;background-image:-moz-linear-gradient(top,#ee5f5b,#bd362f);background-image:-webkit-gradient(linear,0 0,0 100%,from(#ee5f5b),to(#bd362f));background-image:-webkit-linear-gradient(top,#ee5f5b,#bd362f);background-image:-o-linear-gradient(top,#ee5f5b,#bd362f);background-image:linear-gradient(to bottom,#ee5f5b,#bd362f);background-repeaLine truncated
.btn{display:inline-block;*display:inline;*zoom:1;padding:4px 12px;margin-bottom:0;font-size:14px;line-height:20px;text-align:center;vertical-align:middle;cursor:pointer;color:#333;text-shadow:0 1px 1px rgba(255,255,255,.75);background-color:#f5f5f5;background-image:-moz-linear-gradient(top,#fff,#e6e6e6);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fff),to(#e6e6e6));background-image:-webkit-linear-gradient(top,#fff,#e6e6e6);background-image:-o-linear-gradient(top,#fff,#e6e6e6);background-image:linear-gradient(to bottom,#fff,#e6e6e6);background-repeat:repeat-x;*background-color:#e6e6e6;filter:progid:DXImageTransform.Microsoft.gradient(enabled=false);border:1px solid #ccc;*border:0;border-bottom-color:#b3b3b3;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;*margin-left:.3em;-webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05);box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05)}.btn.active,.btn.disabled,.btn:active,.btn:focus,.btn:hover,.btn[disabled]{color:#333;background-color:#e6e6e6;*background-color:#d9d9d9}.btn.active,.btn:active{background-color:#ccc \9}.btn:first-child{*margin-left:0}.btn:focus,.btn:hover{color:#333;text-decoration:none;background-position:0 -15px;-webkit-transition:background-position .1s linear;-moz-transition:background-position .1s linear;-o-transition:background-position .1s linear;transition:background-position .1s linear}.btn:focus{outline:#333 dotted thin;outline:-webkit-focus-ring-color auto 5px;outline-offset:-2px}.btn.active,.btn:active{background-image:none;outline:0;-webkit-box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05);box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05)}.btn.disabled,.btn[disabled]{cursor:default;background-image:none;opacity:.65;filter:alpha(opacity=65);-webkit-box-shadow:none;-moz-box-shadow:none;box-shadow:none}.btn-large{padding:11px 19px;font-size:17.5px;-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px}.btn-large [class*=" icon-"],.btn-large [class^=icon-]{margin-top:4px}.btn-small{padding:2px 10px;font-size:11.9px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.btn-small [class*=" icon-"],.btn-small [class^=icon-]{margin-top:0}.btn-mini [class*=" icon-"],.btn-mini [class^=icon-]{margin-top:-1px}.btn-mini{padding:0 6px;font-size:10.5px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.btn-block{display:block;width:100%;padding-left:0;padding-right:0;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}.btn-block+.btn-block{margin-top:5px}input[type=submit].btn-block,input[type=reset].btn-block,input[type=button].btn-block{width:100%}.btn-primary{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,.25);background-color:#006dcc;background-image:-moz-linear-gradient(top,#08c,#04c);background-image:-webkit-gradient(linear,0 0,0 100%,from(#08c),to(#04c));background-image:-webkit-linear-gradient(top,#08c,#04c);background-image:-o-linear-gradient(top,#08c,#04c);background-image:linear-gradient(to bottom,#08c,#04c);background-repeat:repeat-x;border-color:#04c #04c #002a80;border-color:rgba(0,0,0,.1) rgba(0,0,0,.1) rgba(0,0,0,.25);*background-color:#04c;filter:progid:DXImageTransform.Microsoft.gradient(enabled=false)}.btn-primary.active,.btn-primary.disabled,.btn-primary:active,.btn-primary:focus,.btn-primary:hover,.btn-primary[disabled]{color:#fff;background-color:#04c;*background-color:#003bb3}.btn-primary.active,.btn-primary:active{background-color:#039 \9}.btn-warning{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,.25);background-color:#faa732;background-image:-moz-linear-gradient(top,#fbb450,#f89406);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fbb450),to(#f89406));background-image:-webkit-linear-gradient(top,#fbb450,#f89406);background-image:-o-linear-gradient(top,#fbb450,#f89406);background-image:linear-gradient(to bottom,#fbb450,#f89406);background-repeat:repeat-x;border-color:#f89406 #f89406 #ad6704;border-color:rgba(0,0,0,.1) rgba(0,0,0,.1) rgba(0,0,0,.25);*background-color:#f89406;filter:progid:DXImageTransform.Microsoft.gradient(enabled=false)}.btn-warning.active,.btn-warning.disabled,.btn-warning:active,.btn-warning:focus,.btn-warning:hover,.btn-warning[disabled]{color:#fff;background-color:#f89406;*background-color:#df8505}.btn-warning.active,.btn-warning:active{background-color:#c67605 \9}.btn-danger{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,.25);background-color:#da4f49;background-image:-moz-linear-gradient(top,#ee5f5b,#bd362f);background-image:-webkit-gradient(linear,0 0,0 100%,from(#ee5f5b),to(#bd362f));background-image:-webkit-linear-gradient(top,#ee5f5b,#bd362f);background-image:-o-linear-gradient(top,#ee5f5b,#bd362f);background-image:linear-gradient(to bottom,#ee5f5b,#bd362f);background-repeaLine truncated
+99 -60
View File
@@ -1,11 +1,58 @@
(function (global, factory) {
if (typeof define === "function" && define.amd) {
define("OctoPrint", ["jquery", "lodash"], factory);
define("OctoPrintClient", ["jquery", "lodash"], factory);
} else {
global.OctoPrint = factory(window.$, window._);
global.OctoPrintClient = factory(global.$, global._);
global.OctoPrint = new global.OctoPrintClient();
}
})(window || this, function($, _) {
var OctoPrint = {};
})(this, function($, _) {
var PluginRegistry = function(base) {
this.base = base;
this.components = {};
};
var OctoPrintClient = function(options) {
this.options = options || {
"baseurl": undefined,
"apikey": undefined,
"locale": undefined
};
this.components = {};
this.plugins = new PluginRegistry(this);
};
OctoPrintClient.registerComponent = function(name, component) {
Object.defineProperty(OctoPrintClient.prototype, name, {
get: function() {
if (this.components[name] !== undefined) {
return this.components[name];
}
var instance = new component(this);
this.components[name] = instance;
return instance;
},
enumerable: false,
configurable: false
});
};
OctoPrintClient.registerPluginComponent = function(name, component) {
Object.defineProperty(PluginRegistry.prototype, name, {
get: function() {
if (this.components[name] !== undefined) {
return this.components[name];
}
var instance = new component(this.base);
this.components[name] = instance;
return instance;
},
enumerable: false,
configurable: false
});
};
var noCache = function(opts) {
opts = opts || {};
@@ -44,36 +91,28 @@
return params;
};
OctoPrint.options = {
"baseurl": undefined,
"apikey": undefined,
"locale": undefined
};
OctoPrint.plugins = {};
OctoPrint.getBaseUrl = function() {
var url = OctoPrint.options.baseurl;
OctoPrintClient.prototype.getBaseUrl = function() {
var url = this.options.baseurl;
if (!_.endsWith(url, "/")) {
url = url + "/";
}
return url;
};
OctoPrint.getRequestHeaders = function(additional) {
OctoPrintClient.prototype.getRequestHeaders = function(additional) {
additional = additional || {};
var headers = $.extend({}, additional);
headers["X-Api-Key"] = OctoPrint.options.apikey;
headers["X-Api-Key"] = this.options.apikey;
if (OctoPrint.options.locale !== undefined) {
headers["X-Locale"] = OctoPrint.options.locale;
if (this.options.locale !== undefined) {
headers["X-Locale"] = this.options.locale;
}
return headers;
};
OctoPrint.ajax = function(method, url, opts) {
OctoPrintClient.prototype.ajax = function(method, url, opts) {
opts = opts || {};
method = opts.method || method || "GET";
@@ -81,11 +120,11 @@
var urlToCall = url;
if (!_.startsWith(url, "http://") && !_.startsWith(url, "https://")) {
urlToCall = OctoPrint.getBaseUrl() + url;
urlToCall = this.getBaseUrl() + url;
opts.url = urlToCall;
}
var headers = OctoPrint.getRequestHeaders(opts.headers);
var headers = this.getRequestHeaders(opts.headers);
var params = $.extend({}, opts);
params.type = method;
@@ -95,67 +134,67 @@
return $.ajax(urlToCall, params);
};
OctoPrint.ajaxWithData = function(method, url, data, opts) {
OctoPrintClient.prototype.ajaxWithData = function(method, url, data, opts) {
opts = opts || {};
var params = $.extend({}, opts);
params.data = data;
return OctoPrint.ajax(method, url, params);
return this.ajax(method, url, params);
};
OctoPrint.get = function(url, opts) {
return OctoPrint.ajax("GET", url, opts);
OctoPrintClient.prototype.get = function(url, opts) {
return this.ajax("GET", url, opts);
};
OctoPrint.getWithQuery = function(url, data, opts) {
return OctoPrint.ajaxWithData("GET", url, data, opts);
OctoPrintClient.prototype.getWithQuery = function(url, data, opts) {
return this.ajaxWithData("GET", url, data, opts);
};
OctoPrint.post = function(url, data, opts) {
return OctoPrint.ajaxWithData("POST", url, data, noCache(opts));
OctoPrintClient.prototype.post = function(url, data, opts) {
return this.ajaxWithData("POST", url, data, noCache(opts));
};
OctoPrint.postForm = function(url, data, opts) {
OctoPrintClient.prototype.postForm = function(url, data, opts) {
var form = new FormData();
_.each(data, function(value, key) {
form.append(key, value);
});
return OctoPrint.post(url, form, contentTypeFalse(noProcessData(opts)));
return this.post(url, form, contentTypeFalse(noProcessData(opts)));
};
OctoPrint.postJson = function(url, data, opts) {
return OctoPrint.post(url, JSON.stringify(data), contentTypeJson(opts));
OctoPrintClient.prototype.postJson = function(url, data, opts) {
return this.post(url, JSON.stringify(data), contentTypeJson(opts));
};
OctoPrint.put = function(url, data, opts) {
return OctoPrint.ajaxWithData("PUT", url, data, noCache(opts));
OctoPrintClient.prototype.put = function(url, data, opts) {
return this.ajaxWithData("PUT", url, data, noCache(opts));
};
OctoPrint.putJson = function(url, data, opts) {
return OctoPrint.put(url, JSON.stringify(data), contentTypeJson(opts));
OctoPrintClient.prototype.putJson = function(url, data, opts) {
return this.put(url, JSON.stringify(data), contentTypeJson(opts));
};
OctoPrint.patch = function(url, data, opts) {
return OctoPrint.ajaxWithData("PATCH", url, data, noCache(opts));
OctoPrintClient.prototype.patch = function(url, data, opts) {
return this.ajaxWithData("PATCH", url, data, noCache(opts));
};
OctoPrint.patchJson = function(url, data, opts) {
return OctoPrint.patch(url, JSON.stringify(data), contentTypeJson(opts));
OctoPrintClient.prototype.patchJson = function(url, data, opts) {
return this.patch(url, JSON.stringify(data), contentTypeJson(opts));
};
OctoPrint.delete = function(url, opts) {
return OctoPrint.ajax("DELETE", url, opts);
OctoPrintClient.prototype.delete = function(url, opts) {
return this.ajax("DELETE", url, opts);
};
OctoPrint.download = function(url, opts) {
OctoPrintClient.prototype.download = function(url, opts) {
var params = $.extend({}, opts || {});
params.dataType = "text";
return OctoPrint.get(url, params);
return this.get(url, params);
};
OctoPrint.upload = function(url, file, filename, additional) {
OctoPrintClient.prototype.upload = function(url, file, filename, additional) {
additional = additional || {};
var fileData;
@@ -220,11 +259,11 @@
deferred.notify({loaded: e.loaded, total: e.total});
});
var headers = OctoPrint.getRequestHeaders();
var headers = this.getRequestHeaders();
var urlToCall = url;
if (!_.startsWith(url, "http://") && !_.startsWith(url, "https://")) {
urlToCall = OctoPrint.getBaseUrl() + url;
urlToCall = this.getBaseUrl() + url;
}
request.open("POST", urlToCall);
@@ -236,38 +275,38 @@
return deferred.promise();
};
OctoPrint.issueCommand = function(url, command, payload, opts) {
OctoPrintClient.prototype.issueCommand = function(url, command, payload, opts) {
payload = payload || {};
var data = $.extend({}, payload);
data.command = command;
return OctoPrint.postJson(url, data, opts);
return this.postJson(url, data, opts);
};
OctoPrint.getSimpleApiUrl = function(plugin) {
OctoPrintClient.prototype.getSimpleApiUrl = function(plugin) {
return "api/plugin/" + plugin;
};
OctoPrint.simpleApiGet = function(plugin, opts) {
return OctoPrint.get(OctoPrint.getSimpleApiUrl(plugin), opts);
OctoPrintClient.prototype.simpleApiGet = function(plugin, opts) {
return this.get(OctoPrintClient.prototype.getSimpleApiUrl(plugin), opts);
};
OctoPrint.simpleApiCommand = function(plugin, command, payload, opts) {
return OctoPrint.issueCommand(OctoPrint.getSimpleApiUrl(plugin), command, payload, opts);
OctoPrintClient.prototype.simpleApiCommand = function(plugin, command, payload, opts) {
return this.issueCommand(OctoPrintClient.prototype.getSimpleApiUrl(plugin), command, payload, opts);
};
OctoPrint.getBlueprintUrl = function(plugin) {
OctoPrintClient.prototype.getBlueprintUrl = function(plugin) {
return "plugin/" + plugin + "/";
};
OctoPrint.createRejectedDeferred = function() {
OctoPrintClient.createRejectedDeferred = function() {
var deferred = $.Deferred();
deferred.reject(arguments);
return deferred;
};
OctoPrint.createCustomException = function(name) {
OctoPrintClient.createCustomException = function(name) {
var constructor;
if (_.isFunction(name)) {
@@ -286,7 +325,7 @@
return constructor;
};
OctoPrint.InvalidArgumentError = OctoPrint.createCustomException("InvalidArgumentError");
OctoPrintClient.InvalidArgumentError = OctoPrintClient.createCustomException("InvalidArgumentError");
return OctoPrint;
return OctoPrintClient;
});
+25 -20
View File
@@ -1,29 +1,34 @@
(function (global, factory) {
if (typeof define === "function" && define.amd) {
define(["OctoPrint"], factory);
define(["OctoPrintClient"], factory);
} else {
factory(window.OctoPrint);
factory(global.OctoPrintClient);
}
})(window || this, function(OctoPrint) {
})(this, function(OctoPrintClient) {
var loginUrl = "api/login";
var logoutUrl = "api/logout";
OctoPrint.browser = {
login: function(username, password, remember, opts) {
var data = {
user: username,
pass: password,
remember: !!remember
};
return OctoPrint.postJson(loginUrl, data, opts);
},
passiveLogin: function(opts) {
return OctoPrint.postJson(loginUrl, {passive: true}, opts);
},
logout: function(opts) {
return OctoPrint.postJson(logoutUrl, {}, opts);
}
var OctoPrintBrowserClient = function(base) {
this.base = base;
};
OctoPrintBrowserClient.prototype.login = function(username, password, remember, opts) {
var data = {
user: username,
pass: password,
remember: !!remember
};
return this.base.postJson(loginUrl, data, opts);
};
OctoPrintBrowserClient.prototype.passiveLogin = function(opts) {
return this.base.postJson(loginUrl, {passive: true}, opts);
};
OctoPrintBrowserClient.prototype.logout = function(opts) {
return this.base.postJson(logoutUrl, {}, opts);
};
OctoPrintClient.registerComponent("browser", OctoPrintBrowserClient);
return OctoPrintBrowserClient;
});
@@ -1,27 +1,32 @@
(function (global, factory) {
if (typeof define === "function" && define.amd) {
define(["OctoPrint"], factory);
define(["OctoPrintClient"], factory);
} else {
factory(window.OctoPrint);
factory(global.OctoPrintClient);
}
})(window || this, function(OctoPrint) {
})(this, function(OctoPrintClient) {
var url = "api/connection";
OctoPrint.connection = {
getSettings: function(opts) {
return OctoPrint.get(url, opts);
},
var OctoPrintConnectionClient = function(base) {
this.base = base;
};
connect: function(data, opts) {
return OctoPrint.issueCommand(url, "connect", data || {}, opts);
},
OctoPrintConnectionClient.prototype.getSettings = function(opts) {
return this.base.get(url, opts);
};
disconnect: function(opts) {
return OctoPrint.issueCommand(url, "disconnect", {}, opts);
},
OctoPrintConnectionClient.prototype.connect = function(data, opts) {
return this.base.issueCommand(url, "connect", data || {}, opts);
};
fakeAck: function(opts) {
return OctoPrint.issueCommand(url, "fake_ack", {}, opts);
}
}
OctoPrintConnectionClient.prototype.disconnect = function(opts) {
return this.base.issueCommand(url, "disconnect", {}, opts);
};
OctoPrintConnectionClient.prototype.fakeAck = function(opts) {
return this.base.issueCommand(url, "fake_ack", {}, opts);
};
OctoPrintClient.registerComponent("connection", OctoPrintConnectionClient);
return OctoPrintConnectionClient;
});
+23 -21
View File
@@ -1,14 +1,22 @@
(function (global, factory) {
if (typeof define === "function" && define.amd) {
define(["OctoPrint"], factory);
define(["OctoPrintClient"], factory);
} else {
factory(window.OctoPrint);
factory(global.OctoPrintClient);
}
})(window || this, function(OctoPrint) {
})(this, function(OctoPrintClient) {
var customUrl = "api/printer/command/custom";
var commandUrl = "api/printer/command";
var sendGcodeWithParameters = function(commands, parameters, opts) {
var OctoPrintControlClient = function(base) {
this.base = base;
};
OctoPrintControlClient.prototype.getCustomControls = function (opts) {
return this.base.get(customUrl, opts);
};
OctoPrintControlClient.prototype.sendGcodeWithParameters = function(commands, parameters, opts) {
commands = commands || [];
parameters = parameters || {};
@@ -16,38 +24,32 @@
commands = [commands];
}
return OctoPrint.postJson(commandUrl, {
return this.base.postJson(commandUrl, {
commands: commands,
parameters: parameters
}, opts);
};
var sendGcodeScriptWithParameters = function(script, context, parameters, opts) {
OctoPrintControlClient.prototype.sendGcodeScriptWithParameters = function(script, context, parameters, opts) {
script = script || "";
context = context || {};
parameters = parameters || {};
return OctoPrint.postJson(commandUrl, {
return this.base.postJson(commandUrl, {
script: script,
context: context,
parameters: parameters
}, opts);
};
OctoPrint.control = {
sendGcodeWithParameters: sendGcodeWithParameters,
sendGcodeScriptWithParameters: sendGcodeScriptWithParameters,
OctoPrintControlClient.prototype.sendGcode = function (commands, opts) {
return this.sendGcodeWithParameters(commands, undefined, opts);
};
getCustomControls: function (opts) {
return OctoPrint.get(customUrl, opts);
},
OctoPrintControlClient.prototype.sendGcodeScript = function (script, context, opts) {
return this.sendGcodeScriptWithParameters(script, context, undefined, opts);
};
sendGcode: function (commands, opts) {
return sendGcodeWithParameters(commands, undefined, opts);
},
sendGcodeScript: function (script, context, opts) {
return sendGcodeScriptWithParameters(script, context, undefined, opts);
}
}
OctoPrintClient.registerComponent("control", OctoPrintControlClient);
return OctoPrintControlClient;
});
+103 -106
View File
@@ -1,16 +1,17 @@
(function (factory) {
'use strict';
(function (global, factory) {
if (typeof define === 'function' && define.amd) {
// Register as an anonymous AMD module:
define(["OctoPrint", "jquery", "lodash"], factory);
define(["OctoPrintClient", "jquery", "lodash"], factory);
} else {
// Browser globals:
factory(window.OctoPrint, window.jQuery, window._);
factory(global.OctoPrintClient, global.$, global._);
}
})(function(OctoPrint, $, _) {
})(this, function(OctoPrintClient, $, _) {
var url = "api/files";
var downloadUrl = "downloads/files";
var OctoPrintFilesClient = function(base) {
this.base = base;
};
var resourceForLocation = function(location) {
return url + "/" + location;
};
@@ -27,15 +28,6 @@
return resourceForLocation(location) + "/" + filename;
};
var issueEntryCommand = function(location, entryname, command, data, opts) {
var url = resourceForEntry(location, entryname);
return OctoPrint.issueCommand(url, command, data, opts);
};
var getEntry = function(location, entryname, opts) {
return OctoPrint.get(resourceForEntry(location, entryname), opts);
};
var preProcessList = function(response) {
var recursiveCheck = function(element, index, list) {
if (!element.hasOwnProperty("parent")) element.parent = { children: list, parent: undefined };
@@ -56,7 +48,88 @@
_.each(response.files, recursiveCheck);
};
var pathForEntry = function(entry) {
OctoPrintFilesClient.prototype.get = function(location, entryname, opts) {
return this.base.get(resourceForEntry(location, entryname), opts);
};
OctoPrintFilesClient.prototype.list = function (recursively, force, opts) {
recursively = recursively || false;
force = force || false;
var query = {};
if (recursively) {
query.recursive = recursively;
}
if (force) {
query.force = force;
}
return this.base.getWithQuery(url, query, opts)
.done(preProcessList);
};
OctoPrintFilesClient.prototype.listForLocation = function (location, recursively, opts) {
recursively = recursively || false;
return this.base.getWithQuery(resourceForLocation(location), {recursive: recursively}, opts)
.done(preProcessList);
};
OctoPrintFilesClient.prototype.issueEntryCommand = function(location, entryname, command, data, opts) {
var url = resourceForEntry(location, entryname);
return this.base.issueCommand(url, command, data, opts);
};
OctoPrintFilesClient.prototype.select = function (location, path, print, opts) {
print = print || false;
var data = {
print: print
};
return this.issueEntryCommand(location, path, "select", data, opts);
};
OctoPrintFilesClient.prototype.slice = function (location, path, parameters, opts) {
return this.issueEntryCommand(location, path, "slice",
parameters || {}, opts);
};
OctoPrintFilesClient.prototype.delete = function (location, path, opts) {
return this.base.delete(resourceForEntry(location, path), opts);
};
OctoPrintFilesClient.prototype.copy = function(location, path, destination, opts) {
return this.issueEntryCommand(location, path, "copy", { destination: destination }, opts);
};
OctoPrintFilesClient.prototype.move = function(location, path, destination, opts) {
return this.issueEntryCommand(location, path, "move", { destination: destination }, opts);
};
OctoPrintFilesClient.prototype.createFolder = function (location, name, path, opts) {
var data = {foldername: name};
if (path !== undefined && path !== "") {
data.path = path;
}
return this.base.postForm(resourceForLocation(location), data, opts);
};
OctoPrintFilesClient.prototype.upload = function (location, file, data) {
data = data || {};
var filename = data.filename || undefined;
if (data.userdata && typeof data.userdata === "object") {
data.userdata = JSON.stringify(userdata);
}
return this.base.upload(resourceForLocation(location), file, filename, data);
};
OctoPrintFilesClient.prototype.download = function(location, path, opts) {
return this.base.download(downloadForEntry(location, path), opts);
};
OctoPrintFilesClient.prototype.pathForEntry = function(entry) {
if (!entry || !entry.hasOwnProperty("parent") || entry.parent == undefined) {
return "";
}
@@ -72,7 +145,7 @@
return recursivePath(entry.parent, entry.name);
};
var entryForPath = function(path, root) {
OctoPrintFilesClient.prototype.entryForPath = function(path, root) {
if (_.isArray(root)) {
root = {children: root};
}
@@ -99,94 +172,18 @@
return recursiveSearch(path.split("/"), root);
};
OctoPrint.files = {
get: getEntry,
OctoPrintFilesClient.prototype.pathForElement = function(element) {
// TODO Remove in 1.4.x
log.warn("pathForElement has been renamed to pathForEntry, please use that instead");
return this.pathForEntry(element);
};
list: function (recursively, force, opts) {
recursively = recursively || false;
force = force || false;
OctoPrintFilesClient.prototype.elementByPath = function(location, startElement) {
// TODO Remove in 1.4.x
log.warn("elementByPath has been renamed to entryForPath, please use that instead");
return this.entryForPath(location, startElement);
};
var query = {};
if (recursively) {
query.recursive = recursively;
}
if (force) {
query.force = force;
}
return OctoPrint.getWithQuery(url, query, opts)
.done(preProcessList);
},
listForLocation: function (location, recursively, opts) {
recursively = recursively || false;
return OctoPrint.getWithQuery(resourceForLocation(location), {recursive: recursively}, opts)
.done(preProcessList);
},
select: function (location, path, print, opts) {
print = print || false;
var data = {
print: print
};
return issueEntryCommand(location, path, "select", data, opts);
},
slice: function (location, path, parameters, opts) {
return issueEntryCommand(location, path, "slice",
parameters || {}, opts);
},
delete: function (location, path, opts) {
return OctoPrint.delete(resourceForEntry(location, path), opts);
},
copy: function(location, path, destination, opts) {
return issueEntryCommand(location, path, "copy", { destination: destination }, opts);
},
move: function(location, path, destination, opts) {
return issueEntryCommand(location, path, "move", { destination: destination }, opts);
},
createFolder: function (location, name, path, opts) {
var data = {foldername: name};
if (path !== undefined && path !== "") {
data.path = path;
}
return OctoPrint.postForm(resourceForLocation(location), data, opts);
},
upload: function (location, file, data) {
data = data || {};
var filename = data.filename || undefined;
if (data.userdata && typeof data.userdata === "object") {
data.userdata = JSON.stringify(userdata);
}
return OctoPrint.upload(resourceForLocation(location), file, filename, data);
},
download: function (location, path, opts) {
return OctoPrint.download(downloadForEntry(location, path), opts);
},
pathForEntry: pathForEntry,
entryForPath: entryForPath,
pathForElement: function(element) {
// TODO Remove in 1.4.x
log.warn("OctoPrint.files.pathForElement has been renamed to OctoPrint.files.pathForEntry, please use that instead");
return pathForEntry(element);
},
elementByPath: function(location, startElement) {
// TODO Remove in 1.4.x
log.warn("OctoPrint.files.elementByPath has been renamed to OctoPrint.files.entryForPath, please use that instead");
return entryForPath(location, startElement);
}
}
OctoPrintClient.registerComponent("files", OctoPrintFilesClient);
return OctoPrintFilesClient;
});
+39 -28
View File
@@ -1,42 +1,53 @@
(function (global, factory) {
if (typeof define === "function" && define.amd) {
define(["OctoPrint"], factory);
define(["OctoPrintClient"], factory);
} else {
factory(window.OctoPrint);
factory(global.OctoPrintClient);
}
})(window || this, function(OctoPrint) {
})(this, function(OctoPrintClient) {
var url = "api/job";
var issueCommand = function(command, payload, opts) {
var OctoPrintJobClient = function(base) {
this.base = base;
};
OctoPrintJobClient.prototype.issueCommand = function(command, payload, opts) {
if (arguments.length == 2) {
opts = payload;
payload = {};
}
return OctoPrint.issueCommand(url, command, payload, opts);
return this.base.issueCommand(url, command, payload, opts);
};
OctoPrint.job = {
get: function(opts) {
return OctoPrint.get(url, opts);
},
start: function(opts) {
return issueCommand("start", opts);
},
restart: function(opts) {
return issueCommand("restart", opts);
},
pause: function(opts) {
return issueCommand("pause", {"action": "pause"}, opts);
},
resume: function(opts) {
return issueCommand("pause", {"action": "resume"}, opts)
},
togglePause: function(opts) {
return issueCommand("pause", {"action": "toggle"}, opts);
},
cancel: function(opts) {
return issueCommand("cancel", opts);
}
}
OctoPrintJobClient.prototype.get = function(opts) {
return OctoPrint.get(url, opts);
};
OctoPrintJobClient.prototype.start = function(opts) {
return this.issueCommand("start", opts);
};
OctoPrintJobClient.prototype.restart = function(opts) {
return this.issueCommand("restart", opts);
};
OctoPrintJobClient.prototype.pause = function(opts) {
return this.issueCommand("pause", {"action": "pause"}, opts);
};
OctoPrintJobClient.prototype.resume = function(opts) {
return this.issueCommand("pause", {"action": "resume"}, opts)
};
OctoPrintJobClient.prototype.togglePause = function(opts) {
return this.issueCommand("pause", {"action": "toggle"}, opts);
};
OctoPrintJobClient.prototype.cancel = function(opts) {
return this.issueCommand("cancel", opts);
};
OctoPrintClient.registerComponent("job", OctoPrintJobClient);
return OctoPrintJobClient;
});
+21 -14
View File
@@ -1,22 +1,29 @@
(function (global, factory) {
if (typeof define === "function" && define.amd) {
define(["OctoPrint"], factory);
define(["OctoPrintClient"], factory);
} else {
factory(window.OctoPrint);
factory(global.OctoPrintClient);
}
})(window || this, function(OctoPrint) {
})(this, function(OctoPrintClient) {
var url = "api/languages";
OctoPrint.languages = {
list: function(opts) {
return OctoPrint.get(url, opts);
},
upload: function(file) {
return OctoPrint.upload(url, file);
},
delete: function(locale, pack, opts) {
var packUrl = url + "/" + locale + "/" + pack;
return OctoPrint.delete(packUrl, opts);
}
var OctoPrintLanguagesClient = function(base) {
this.base = base;
};
OctoPrintLanguagesClient.prototype.list = function(opts) {
return this.base.get(url, opts);
};
OctoPrintLanguagesClient.prototype.upload = function(file) {
return this.base.upload(url, file);
};
OctoPrintLanguagesClient.prototype.delete = function(locale, pack, opts) {
var packUrl = url + "/" + locale + "/" + pack;
return this.base.delete(packUrl, opts);
};
OctoPrintClient.registerComponent("languages", OctoPrintLanguagesClient);
return OctoPrintLanguagesClient;
});
+21 -16
View File
@@ -1,25 +1,30 @@
(function (global, factory) {
if (typeof define === "function" && define.amd) {
define(["OctoPrint"], factory);
define(["OctoPrintClient"], factory);
} else {
factory(window.OctoPrint);
factory(global.OctoPrintClient);
}
})(window || this, function(OctoPrint) {
})(this, function(OctoPrintClient) {
var url = "api/logs";
OctoPrint.logs = {
list: function(opts) {
return OctoPrint.get(url, opts);
},
var OctoPrintLogsClient = function(base) {
this.base = base;
};
delete: function(file, opts) {
var fileUrl = url + "/" + file;
return OctoPrint.delete(fileUrl, opts);
},
OctoPrintLogsClient.prototype.list = function(opts) {
return this.base.get(url, opts);
};
download: function(file, opts) {
var fileUrl = url + "/" + file;
return OctoPrint.download(fileUrl, opts);
}
}
OctoPrintLogsClient.prototype.delete = function(file, opts) {
var fileUrl = url + "/" + file;
return this.base.delete(fileUrl, opts);
};
OctoPrintLogsClient.prototype.download = function(file, opts) {
var fileUrl = url + "/" + file;
return this.base.download(fileUrl, opts);
};
OctoPrintClient.registerComponent("logs", OctoPrintLogsClient);
return OctoPrintLogsClient;
});
+186 -181
View File
@@ -1,210 +1,215 @@
(function (global, factory) {
if (typeof define === "function" && define.amd) {
define(["OctoPrint"], factory);
define(["OctoPrintClient"], factory);
} else {
factory(window.OctoPrint);
factory(global.OctoPrintClient);
}
})(window || this, function(OctoPrint) {
})(this, function(OctoPrintClient) {
var url = "api/printer";
var printheadUrl = url + "/printhead";
var toolUrl = url + "/tool";
var bedUrl = url + "/bed";
var sdUrl = url + "/sd";
var issuePrintheadCommand = function (command, payload, opts) {
return OctoPrint.issueCommand(printheadUrl, command, payload, opts);
var OctoPrintPrinterClient = function(base) {
this.base = base;
};
var issueToolCommand = function (command, payload, opts) {
return OctoPrint.issueCommand(toolUrl, command, payload, opts);
OctoPrintPrinterClient.prototype.issuePrintheadCommand = function (command, payload, opts) {
return this.base.issueCommand(printheadUrl, command, payload, opts);
};
var issueBedCommand = function (command, payload, opts) {
return OctoPrint.issueCommand(bedUrl, command, payload, opts);
OctoPrintPrinterClient.prototype.issueToolCommand = function (command, payload, opts) {
return this.base.issueCommand(toolUrl, command, payload, opts);
};
var issueSdCommand = function (command, payload, opts) {
return OctoPrint.issueCommand(sdUrl, command, payload, opts);
OctoPrintPrinterClient.prototype.issueBedCommand = function (command, payload, opts) {
return this.base.issueCommand(bedUrl, command, payload, opts);
};
OctoPrint.printer = {
getFullState: function (flags, opts) {
flags = flags || {};
OctoPrintPrinterClient.prototype.issueSdCommand = function (command, payload, opts) {
return this.base.issueCommand(sdUrl, command, payload, opts);
};
var history = flags.history || undefined;
var limit = flags.limit || undefined;
var exclude = flags.exclude || undefined;
OctoPrintPrinterClient.prototype.getFullState = function (flags, opts) {
flags = flags || {};
var getUrl = url;
if (history || exclude) {
getUrl += "?";
if (history) {
getUrl += "history=true&";
if (limit) {
getUrl += "limit=" + limit + "&";
}
}
var history = flags.history || undefined;
var limit = flags.limit || undefined;
var exclude = flags.exclude || undefined;
if (exclude) {
getUrl += "exclude=" + exclude.join(",") + "&";
}
}
return OctoPrint.get(getUrl, opts);
},
getToolState: function (flags, opts) {
flags = flags || {};
var history = flags.history || undefined;
var limit = flags.limit || undefined;
var getUrl = toolUrl;
var getUrl = url;
if (history || exclude) {
getUrl += "?";
if (history) {
getUrl += "?history=true";
getUrl += "history=true&";
if (limit) {
getUrl += "&limit=" + limit;
getUrl += "limit=" + limit + "&";
}
}
return OctoPrint.get(getUrl, opts);
},
getBedState: function (flags, opts) {
flags = flags || {};
var history = flags.history || undefined;
var limit = flags.limit || undefined;
var getUrl = bedUrl;
if (history) {
getUrl += "?history=true";
if (limit) {
getUrl += "&limit=" + limit;
}
if (exclude) {
getUrl += "exclude=" + exclude.join(",") + "&";
}
return OctoPrint.get(getUrl, opts);
},
getSdState: function (opts) {
return OctoPrint.get(sdUrl, opts);
},
jog: function (params, opts) {
params = params || {};
var absolute = params.absolute || false;
var payload = {absolute: absolute};
if (params.x) payload.x = params.x;
if (params.y) payload.y = params.y;
if (params.z) payload.z = params.z;
if (params.speed !== undefined) payload.speed = params.speed;
return issuePrintheadCommand("jog", payload, opts);
},
home: function (axes, opts) {
axes = axes || [];
var payload = {
axes: axes
};
return issuePrintheadCommand("home", payload, opts);
},
setFeedrate: function (factor, opts) {
factor = factor || 100;
var payload = {
factor: factor
};
return issuePrintheadCommand("feedrate", payload, opts);
},
setToolTargetTemperatures: function (targets, opts) {
targets = targets || {};
var payload = {
targets: targets
};
return issueToolCommand("target", payload, opts);
},
setToolTemperatureOffsets: function (offsets, opts) {
offsets = offsets || {};
var payload = {
offsets: offsets
};
return issueToolCommand("offset", payload, opts);
},
selectTool: function (tool, opts) {
tool = tool || undefined;
var payload = {
tool: tool
};
return issueToolCommand("select", payload, opts);
},
extrude: function (amount, opts) {
amount = amount || undefined;
var payload = {
amount: amount
};
return issueToolCommand("extrude", payload, opts);
},
setFlowrate: function (factor, opts) {
factor = factor || 100;
var payload = {
factor: factor
};
return issueToolCommand("flowrate", payload, opts);
},
setBedTargetTemperature: function (target, opts) {
target = target || 0;
var payload = {
target: target
};
return issueBedCommand("target", payload, opts);
},
setBedTemperatureOffset: function (offset, opts) {
offset = offset || 0;
var payload = {
offset: offset
};
return issueBedCommand("offset", payload, opts);
},
initSd: function (opts) {
return issueSdCommand("init", {}, opts);
},
refreshSd: function (opts) {
return issueSdCommand("refresh", {}, opts);
},
releaseSd: function (opts) {
return issueSdCommand("release", {}, opts);
}
}
return this.base.get(getUrl, opts);
};
OctoPrintPrinterClient.prototype.getToolState = function (flags, opts) {
flags = flags || {};
var history = flags.history || undefined;
var limit = flags.limit || undefined;
var getUrl = toolUrl;
if (history) {
getUrl += "?history=true";
if (limit) {
getUrl += "&limit=" + limit;
}
}
return this.base.get(getUrl, opts);
};
OctoPrintPrinterClient.prototype.getBedState = function (flags, opts) {
flags = flags || {};
var history = flags.history || undefined;
var limit = flags.limit || undefined;
var getUrl = bedUrl;
if (history) {
getUrl += "?history=true";
if (limit) {
getUrl += "&limit=" + limit;
}
}
return this.base.get(getUrl, opts);
};
OctoPrintPrinterClient.prototype.getSdState = function (opts) {
return this.base.get(sdUrl, opts);
};
OctoPrintPrinterClient.prototype.jog = function (params, opts) {
params = params || {};
var absolute = params.absolute || false;
var payload = {absolute: absolute};
if (params.x) payload.x = params.x;
if (params.y) payload.y = params.y;
if (params.z) payload.z = params.z;
if (params.speed !== undefined) payload.speed = params.speed;
return this.issuePrintheadCommand("jog", payload, opts);
};
OctoPrintPrinterClient.prototype.home = function (axes, opts) {
axes = axes || [];
var payload = {
axes: axes
};
return this.issuePrintheadCommand("home", payload, opts);
};
OctoPrintPrinterClient.prototype.setFeedrate = function (factor, opts) {
factor = factor || 100;
var payload = {
factor: factor
};
return this.issuePrintheadCommand("feedrate", payload, opts);
};
OctoPrintPrinterClient.prototype.setToolTargetTemperatures = function (targets, opts) {
targets = targets || {};
var payload = {
targets: targets
};
return this.issueToolCommand("target", payload, opts);
};
OctoPrintPrinterClient.prototype.setToolTemperatureOffsets = function (offsets, opts) {
offsets = offsets || {};
var payload = {
offsets: offsets
};
return this.issueToolCommand("offset", payload, opts);
};
OctoPrintPrinterClient.prototype.selectTool = function (tool, opts) {
tool = tool || undefined;
var payload = {
tool: tool
};
return this.issueToolCommand("select", payload, opts);
};
OctoPrintPrinterClient.prototype.extrude = function (amount, opts) {
amount = amount || undefined;
var payload = {
amount: amount
};
return this.issueToolCommand("extrude", payload, opts);
};
OctoPrintPrinterClient.prototype.setFlowrate = function (factor, opts) {
factor = factor || 100;
var payload = {
factor: factor
};
return this.issueToolCommand("flowrate", payload, opts);
};
OctoPrintPrinterClient.prototype.setBedTargetTemperature = function (target, opts) {
target = target || 0;
var payload = {
target: target
};
return this.issueBedCommand("target", payload, opts);
};
OctoPrintPrinterClient.prototype.setBedTemperatureOffset = function (offset, opts) {
offset = offset || 0;
var payload = {
offset: offset
};
return this.issueBedCommand("offset", payload, opts);
};
OctoPrintPrinterClient.prototype.initSd = function (opts) {
return this.issueSdCommand("init", {}, opts);
};
OctoPrintPrinterClient.prototype.refreshSd = function (opts) {
return this.issueSdCommand("refresh", {}, opts);
};
OctoPrintPrinterClient.prototype.releaseSd = function (opts) {
return this.issueSdCommand("release", {}, opts);
};
OctoPrintClient.registerComponent("printer", OctoPrintPrinterClient);
return OctoPrintPrinterClient;
});
@@ -1,46 +1,51 @@
(function (global, factory) {
if (typeof define === "function" && define.amd) {
define(["OctoPrint", "jquery"], factory);
define(["OctoPrintClient", "jquery"], factory);
} else {
factory(window.OctoPrint, window.$);
factory(global.OctoPrintClient, global.$);
}
})(window || this, function(OctoPrint, $) {
})(this, function(OctoPrintClient, $) {
var url = "api/printerprofiles";
var profileUrl = function(profile) {
return url + "/" + profile;
};
OctoPrint.printerprofiles = {
list: function (opts) {
return OctoPrint.get(url, opts);
},
var OctoPrintPrinterProfileClient = function(base) {
this.base = base;
};
add: function (profile, basedOn, opts) {
profile = profile || {};
OctoPrintPrinterProfileClient.prototype.list = function (opts) {
return this.base.get(url, opts);
};
var data = {profile: profile};
if (basedOn) {
data.basedOn = basedOn;
}
OctoPrintPrinterProfileClient.prototype.add = function (profile, basedOn, opts) {
profile = profile || {};
return OctoPrint.postJson(url, data, opts);
},
get: function (id, opts) {
return OctoPrint.get(profileUrl(id), opts);
},
update: function (id, profile, opts) {
profile = profile || {};
var data = {profile: profile};
return OctoPrint.patchJson(profileUrl(id), data, opts);
},
delete: function (id, opts) {
return OctoPrint.delete(profileUrl(id), opts);
var data = {profile: profile};
if (basedOn) {
data.basedOn = basedOn;
}
}
return this.base.postJson(url, data, opts);
};
OctoPrintPrinterProfileClient.prototype.get = function (id, opts) {
return this.base.get(profileUrl(id), opts);
};
OctoPrintPrinterProfileClient.prototype. update = function (id, profile, opts) {
profile = profile || {};
var data = {profile: profile};
return this.base.patchJson(profileUrl(id), data, opts);
};
OctoPrintPrinterProfileClient.prototype.delete = function (id, opts) {
return this.base.delete(profileUrl(id), opts);
};
OctoPrintClient.registerComponent("printerprofiles", OctoPrintPrinterProfileClient);
return OctoPrintPrinterProfileClient;
});
+31 -29
View File
@@ -1,43 +1,45 @@
(function (global, factory) {
if (typeof define === "function" && define.amd) {
define(["OctoPrint", "jquery"], factory);
define(["OctoPrintClient", "jquery"], factory);
} else {
factory(window.OctoPrint, window.$);
factory(global.OctoPrintClient, global.$);
}
})(window || this, function(OctoPrint, $) {
})(this, function(OctoPrintClient, $) {
var url = "api/settings";
var get = function(opts) {
return OctoPrint.get(url, opts);
var OctoPrintSettingsClient = function(base) {
this.base = base;
};
var save = function(settings, opts) {
OctoPrintSettingsClient.prototype.get = function(opts) {
return this.base.get(url, opts);
};
OctoPrintSettingsClient.prototype.save = function(settings, opts) {
settings = settings || {};
return OctoPrint.postJson(url, settings, opts);
return this.base.postJson(url, settings, opts);
};
OctoPrint.settings = {
get: get,
save: save,
OctoPrintSettingsClient.prototype.getPluginSettings = function (plugin, opts) {
return this.get(opts)
.then(function (settings, statusText, request) {
if (!settings.plugins || !settings.plugins[plugin]) {
return $.Deferred()
.reject(request, "dataerror", "No settings for plugin " + plugin)
.promise();
} else {
return settings.plugins[plugin];
}
});
};
getPluginSettings: function (plugin, opts) {
return get(opts)
.then(function (settings, statusText, request) {
if (!settings.plugins || !settings.plugins[plugin]) {
return $.Deferred()
.reject(request, "dataerror", "No settings for plugin " + plugin)
.promise();
} else {
return settings.plugins[plugin];
}
});
},
OctoPrintSettingsClient.prototype.savePluginSettings = function (plugin, settings, opts) {
var data = {};
data["plugins"] = {};
data["plugins"][plugin] = settings;
return this.save(data, opts);
};
savePluginSettings: function (plugin, settings, opts) {
var data = {};
data["plugins"] = {};
data["plugins"][plugin] = settings;
return save(data, opts);
}
}
OctoPrintClient.registerComponent("settings", OctoPrintSettingsClient);
return OctoPrintSettingsClient;
});
+30 -25
View File
@@ -1,10 +1,10 @@
(function (global, factory) {
if (typeof define === "function" && define.amd) {
define(["OctoPrint"], factory);
define(["OctoPrintClient"], factory);
} else {
factory(window.OctoPrint);
factory(global.OctoPrintClient);
}
})(window || this, function(OctoPrint) {
})(this, function(OctoPrintClient) {
var url = "api/slicing";
var slicerUrl = function(slicer) {
@@ -15,31 +15,36 @@
return slicerUrl(slicer) + "/profiles/" + profileId;
};
OctoPrint.slicing = {
listAllSlicersAndProfiles: function(opts) {
return OctoPrint.get(url, opts);
},
var OctoPrintSlicingClient = function(base) {
this.base = base;
};
listProfilesForSlicer: function(slicer, opts) {
return OctoPrint.get(slicerUrl(slicer) + "/profiles", opts);
},
OctoPrintSlicingClient.prototype.listAllSlicersAndProfiles = function(opts) {
return this.base.get(url, opts);
};
getProfileForSlicer: function(slicer, profileId, opts) {
return OctoPrint.get(profileUrl(slicer, profileId), opts);
},
OctoPrintSlicingClient.prototype.listProfilesForSlicer = function(slicer, opts) {
return this.base.get(slicerUrl(slicer) + "/profiles", opts);
};
addProfileForSlicer: function(slicer, profileId, profile, opts) {
profile = profile || {};
return OctoPrint.putJson(profileUrl(slicer, profileId), profile, opts);
},
OctoPrintSlicingClient.prototype.getProfileForSlicer = function(slicer, profileId, opts) {
return this.base.get(profileUrl(slicer, profileId), opts);
};
updateProfileForSlicer: function(slicer, profileId, profile, opts) {
profile = profile || {};
return OctoPrint.patchJson(profileUrl(slicer, profileId), profile, opts);
},
OctoPrintSlicingClient.prototype.addProfileForSlicer = function(slicer, profileId, profile, opts) {
profile = profile || {};
return this.base.putJson(profileUrl(slicer, profileId), profile, opts);
};
deleteProfileForSlicer: function(slicer, profileId, opts) {
return OctoPrint.delete(profileUrl(slicer, profileId), opts);
}
}
OctoPrintSlicingClient.prototype.updateProfileForSlicer = function(slicer, profileId, profile, opts) {
profile = profile || {};
return this.base.patchJson(profileUrl(slicer, profileId), profile, opts);
};
OctoPrintSlicingClient.prototype.deleteProfileForSlicer = function(slicer, profileId, opts) {
return this.base.delete(profileUrl(slicer, profileId), opts);
};
OctoPrintClient.registerComponent("slicing", OctoPrintSlicingClient);
return OctoPrintSlicingClient;
});
+102 -100
View File
@@ -1,59 +1,33 @@
(function (global, factory) {
if (typeof define === "function" && define.amd) {
define(["OctoPrint", "jquery", "lodash", "sockjs"], factory);
define(["OctoPrintClient", "jquery", "lodash", "sockjs"], factory);
} else {
factory(window.OctoPrint, window.$, window._, window.SockJS);
factory(global.OctoPrintClient, global.$, global._, global.SockJS);
}
})(window || this, function(OctoPrint, $, _, SockJS) {
var exports = {};
exports.options = {
timeouts: [0, 1, 1, 2, 3, 5, 8, 13, 20, 40, 100],
rateSlidingWindowSize: 20
};
})(this, function(OctoPrintClient, $, _, SockJS) {
var normalClose = 1000;
var socket = undefined;
var reconnecting = false;
var reconnectTrial = 0;
var registeredHandlers = {};
var OctoPrintSocketClient = function(base) {
this.base = base;
var rateThrottleFactor = 1;
var rateBase = 500;
var rateLastMeasurements = [];
this.options = {
timeouts: [0, 1, 1, 2, 3, 5, 8, 13, 20, 40, 100],
rateSlidingWindowSize: 20
};
var onOpen = function() {
reconnecting = false;
reconnectTrial = 0;
this.socket = undefined;
this.reconnecting = false;
this.reconnectTrial = 0;
this.registeredHandlers = {};
this.rateThrottleFactor = 1;
this.rateBase = 500;
this.rateLastMeasurements = [];
};
var onClose = function(e) {
if (e.code == normalClose) {
return;
}
if (exports.onReconnectAttempt(reconnectTrial)) {
return;
}
if (reconnectTrial < exports.options.timeouts.length) {
var timeout = exports.options.timeouts[reconnectTrial];
setTimeout(exports.reconnect, timeout * 1000);
reconnectTrial++;
} else {
exports.onReconnectFailed();
}
};
var onMessage = function(msg) {
_.each(msg.data, function(data, key) {
propagateMessage(key, data);
});
};
var propagateMessage = function(event, data) {
if (!registeredHandlers.hasOwnProperty(event)) {
OctoPrintSocketClient.prototype.propagateMessage = function(event, data) {
if (!this.registeredHandlers.hasOwnProperty(event)) {
return;
}
@@ -61,14 +35,14 @@
var eventObj = {event: event, data: data};
var catchAllHandlers = registeredHandlers["*"];
var catchAllHandlers = this.registeredHandlers["*"];
if (catchAllHandlers && catchAllHandlers.length) {
_.each(catchAllHandlers, function(handler) {
handler(eventObj);
});
}
var handlers = registeredHandlers[event];
var handlers = this.registeredHandlers[event];
if (handlers && handlers.length) {
_.each(handlers, function(handler) {
handler(eventObj);
@@ -76,100 +50,128 @@
}
var end = new Date().getTime();
analyzeTiming(end - start);
this.analyzeTiming(end - start);
};
var analyzeTiming = function(measurement) {
while (rateLastMeasurements.length >= exports.options.rateSlidingWindowSize) {
rateLastMeasurements.shift();
OctoPrintSocketClient.prototype.analyzeTiming = function(measurement) {
while (this.rateLastMeasurements.length >= this.options.rateSlidingWindowSize) {
this.rateLastMeasurements.shift();
}
rateLastMeasurements.push(measurement);
this.rateLastMeasurements.push(measurement);
var processingLimit = rateThrottleFactor * rateBase;
var processingLimit = this.rateThrottleFactor * this.rateBase;
if (measurement > processingLimit) {
exports.onRateTooHigh(measurement, processingLimit);
} else if (rateThrottleFactor > 1) {
var maxProcessingTime = Math.max.apply(null, rateLastMeasurements);
var lowerProcessingLimit = (rateThrottleFactor - 1) * rateBase;
this.onRateTooHigh(measurement, processingLimit);
} else if (this.rateThrottleFactor > 1) {
var maxProcessingTime = Math.max.apply(null, this.rateLastMeasurements);
var lowerProcessingLimit = (this.rateThrottleFactor - 1) * this.rateBase;
if (maxProcessingTime < lowerProcessingLimit) {
exports.onRateTooLow(maxProcessingTime, lowerProcessingLimit);
this.onRateTooLow(maxProcessingTime, lowerProcessingLimit);
}
}
};
var increaseRate = function() {
if (rateThrottleFactor <= 1) {
rateThrottleFactor = 1;
OctoPrintSocketClient.prototype.increaseRate = function() {
if (this.rateThrottleFactor <= 1) {
this.rateThrottleFactor = 1;
return;
}
rateThrottleFactor--;
sendThrottleFactor();
this.rateThrottleFactor--;
this.sendThrottleFactor();
};
var decreaseRate = function() {
rateThrottleFactor++;
sendThrottleFactor();
OctoPrintSocketClient.prototype.decreaseRate = function() {
this.rateThrottleFactor++;
this.sendThrottleFactor();
};
var sendThrottleFactor = function() {
sendMessage("throttle", rateThrottleFactor);
OctoPrintSocketClient.prototype.sendThrottleFactor = function() {
this.sendMessage("throttle", this.rateThrottleFactor);
};
var sendMessage = function(type, payload) {
OctoPrintSocketClient.prototype.sendMessage = function(type, payload) {
var data = {};
data[type] = payload;
socket.send(JSON.stringify(data));
this.socket.send(JSON.stringify(data));
};
exports.connect = function(opts) {
OctoPrintSocketClient.prototype.connect = function(opts) {
opts = opts || {};
exports.disconnect();
this.disconnect();
var url = OctoPrint.options.baseurl;
var url = this.base.options.baseurl;
if (!_.endsWith(url, "/")) {
url += "/";
}
socket = new SockJS(url + "sockjs", undefined, opts);
socket.onopen = onOpen;
socket.onclose = onClose;
socket.onmessage = onMessage;
var self = this;
var onOpen = function() {
self.reconnecting = false;
self.reconnectTrial = 0;
};
var onClose = function(e) {
if (e.code == normalClose) {
return;
}
if (self.onReconnectAttempt(self.reconnectTrial)) {
return;
}
if (self.reconnectTrial < self.options.timeouts.length) {
var timeout = self.options.timeouts[self.reconnectTrial];
setTimeout(function() { self.reconnect() }, timeout * 1000);
self.reconnectTrial++;
} else {
self.onReconnectFailed();
}
};
var onMessage = function(msg) {
_.each(msg.data, function(data, key) {
self.propagateMessage(key, data);
});
};
this.socket = new SockJS(url + "sockjs", undefined, opts);
this.socket.onopen = onOpen;
this.socket.onclose = onClose;
this.socket.onmessage = onMessage;
};
exports.reconnect = function() {
exports.disconnect();
socket = undefined;
exports.connect();
OctoPrintSocketClient.prototype.reconnect = function() {
this.disconnect();
this.socket = undefined;
this.connect();
};
exports.disconnect = function() {
if (socket != undefined) {
socket.close();
OctoPrintSocketClient.prototype.disconnect = function() {
if (this.socket != undefined) {
this.socket.close();
}
};
exports.onMessage = function(message, handler) {
if (!registeredHandlers.hasOwnProperty(message)) {
registeredHandlers[message] = [];
OctoPrintSocketClient.prototype.onMessage = function(message, handler) {
if (!this.registeredHandlers.hasOwnProperty(message)) {
this.registeredHandlers[message] = [];
}
registeredHandlers[message].push(handler);
return exports;
this.registeredHandlers[message].push(handler);
return this;
};
exports.onReconnectAttempt = function(trial) {};
exports.onReconnectFailed = function() {};
OctoPrintSocketClient.prototype.onReconnectAttempt = function(trial) {};
OctoPrintSocketClient.prototype.onReconnectFailed = function() {};
exports.onRateTooLow = function(measured, minimum) {
increaseRate();
OctoPrintSocketClient.prototype.onRateTooLow = function(measured, minimum) {
this.increaseRate();
};
exports.onRateTooHigh = function(measured, maximum) {
decreaseRate();
OctoPrintSocketClient.prototype.onRateTooHigh = function(measured, maximum) {
this.decreaseRate();
};
exports.increaseRate = increaseRate;
exports.decreaseRate = decreaseRate;
exports.sendMessage = sendMessage;
OctoPrint.socket = exports;
OctoPrintClient.registerComponent("socket", OctoPrintSocketClient);
return OctoPrintSocketClient;
});
+20 -15
View File
@@ -1,24 +1,29 @@
(function (global, factory) {
if (typeof define === "function" && define.amd) {
define(["OctoPrint"], factory);
define(["OctoPrintClient"], factory);
} else {
factory(window.OctoPrint);
factory(global.OctoPrintClient);
}
})(window || this, function(OctoPrint) {
})(this, function(OctoPrintClient) {
var url = "api/system";
var commandUrl = "api/system/commands";
OctoPrint.system = {
getCommands: function (opts) {
return OctoPrint.get(commandUrl, opts);
},
getCommandsForSource: function (source, opts) {
return OctoPrint.get(commandUrl + "/" + source, opts);
},
executeCommand: function (source, action, opts) {
return OctoPrint.postJson(commandUrl + "/" + source + "/" + action, {}, opts);
}
var OctoPrintSystemClient = function(base) {
this.base = base;
};
OctoPrintSystemClient.prototype.getCommands = function (opts) {
return this.base.get(commandUrl, opts);
};
OctoPrintSystemClient.prototype.getCommandsForSource = function (source, opts) {
return this.base.get(commandUrl + "/" + source, opts);
};
OctoPrintSystemClient.prototype.executeCommand = function (source, action, opts) {
return this.base.postJson(commandUrl + "/" + source + "/" + action, {}, opts);
};
OctoPrintClient.registerComponent("system", OctoPrintSystemClient);
return OctoPrintSystemClient;
});
+74 -71
View File
@@ -1,10 +1,10 @@
(function (global, factory) {
if (typeof define === "function" && define.amd) {
define(["OctoPrint", "jquery"], factory);
define(["OctoPrintClient", "jquery"], factory);
} else {
factory(window.OctoPrint, window.$);
factory(global.OctoPrintClient, global.$);
}
})(window || this, function(OctoPrint, $) {
})(this, function(OctoPrintClient, $) {
var url = "api/timelapse";
var downloadUrl = "downloads/timelapse";
@@ -21,93 +21,96 @@
return url + "/unrendered/" + name;
};
var getTimelapseData = function (unrendered, opts) {
var OctoPrintTimelapseClient = function(base) {
this.base = base;
};
OctoPrintTimelapseClient.prototype.get = function (unrendered, opts) {
if (unrendered) {
opts = opts || {};
opts.data = {unrendered: unrendered};
}
return OctoPrint.get(url, opts);
return this.base.get(url, opts);
};
OctoPrint.timelapse = {
get: getTimelapseData,
OctoPrintTimelapseClient.prototype.list = function(opts) {
var deferred = $.Deferred();
list: function(opts) {
var deferred = $.Deferred();
this.get(true, opts)
.done(function (response, status, request) {
deferred.resolve({
rendered: response.files,
unrendered: response.unrendered
}, status, request);
})
.fail(function () {
deferred.reject.apply(null, arguments);
});
getTimelapseData(true, opts)
.done(function (response, status, request) {
deferred.resolve({
rendered: response.files,
unrendered: response.unrendered
}, status, request);
})
.fail(function () {
deferred.reject.apply(null, arguments);
});
return deferred.promise();
};
return deferred.promise();
},
OctoPrintTimelapseClient.prototype.listRendered = function (opts) {
var deferred = $.Deferred();
listRendered: function (opts) {
var deferred = $.Deferred();
this.get(false, opts)
.done(function (response, status, request) {
deferred.resolve(response.files, status, request);
})
.fail(function () {
deferred.reject.apply(null, arguments);
});
getTimelapseData(false, opts)
.done(function (response, status, request) {
deferred.resolve(response.files, status, request);
})
.fail(function () {
deferred.reject.apply(null, arguments);
});
return deferred.promise();
};
return deferred.promise();
},
OctoPrintTimelapseClient.prototype.listUnrendered = function (opts) {
var deferred = $.Deferred();
listUnrendered: function (opts) {
var deferred = $.Deferred();
this.get(true, opts)
.done(function (response, status, request) {
deferred.resolve(response.unrendered, status, request);
})
.fail(function () {
deferred.reject.apply(null, arguments);
});
getTimelapseData(true, opts)
.done(function (response, status, request) {
deferred.resolve(response.unrendered, status, request);
})
.fail(function () {
deferred.reject.apply(null, arguments);
});
return deferred.promise();
};
return deferred.promise();
},
OctoPrintTimelapseClient.prototype.download = function (filename, opts) {
return this.base.download(timelapseDownloadUrl(filename), opts);
};
download: function (filename, opts) {
return OctoPrint.download(timelapseDownloadUrl(filename), opts);
},
OctoPrintTimelapseClient.prototype.delete = function (filename, opts) {
return this.base.delete(timelapseUrl(filename), opts);
};
delete: function (filename, opts) {
return OctoPrint.delete(timelapseUrl(filename), opts);
},
OctoPrintTimelapseClient.prototype.deleteUnrendered = function(name, opts) {
return this.base.delete(unrenderedTimelapseUrl(name), opts);
};
deleteUnrendered: function(name, opts) {
return OctoPrint.delete(unrenderedTimelapseUrl(name), opts);
},
OctoPrintTimelapseClient.prototype.renderUnrendered = function(name, opts) {
return this.base.issueCommand(unrenderedTimelapseUrl(name), "render");
};
renderUnrendered: function(name, opts) {
return OctoPrint.issueCommand(unrenderedTimelapseUrl(name), "render");
},
OctoPrintTimelapseClient.prototype.getConfig = function (opts) {
var deferred = $.Deferred();
this.get(false, opts)
.done(function (response, status, request) {
deferred.resolve(response.config, status, request);
})
.fail(function () {
deferred.reject.apply(null, arguments);
});
return deferred.promise();
};
getConfig: function (opts) {
var deferred = $.Deferred();
getTimelapseData(false, opts)
.done(function (response, status, request) {
deferred.resolve(response.config, status, request);
})
.fail(function () {
deferred.reject.apply(null, arguments);
});
return deferred.promise();
},
OctoPrintTimelapseClient.prototype.saveConfig = function (config, opts) {
config = config || {};
return OctoPrint.postJson(url, config, opts);
};
saveConfig: function (config, opts) {
config = config || {};
return OctoPrint.postJson(url, config, opts);
}
}
OctoPrintClient.registerComponent("timelapse", OctoPrintTimelapseClient);
return OctoPrintTimelapseClient;
});
+99 -94
View File
@@ -1,10 +1,10 @@
(function (global, factory) {
if (typeof define === "function" && define.amd) {
define(["OctoPrint"], factory);
define(["OctoPrintClient"], factory);
} else {
factory(window.OctoPrint);
factory(global.OctoPrintClient);
}
})(window || this, function(OctoPrint) {
})(this, function(OctoPrintClient) {
var baseUrl = "api/users";
var url = function() {
@@ -15,96 +15,101 @@
}
};
OctoPrint.users = {
list: function (opts) {
return OctoPrint.get(url(), opts);
},
add: function (user, opts) {
if (!user.name || !user.password) {
throw new OctoPrint.InvalidArgumentError("Both user's name and password need to be set");
}
var data = {
name: user.name,
password: user.password,
active: user.hasOwnProperty("active") ? !!user.active : true,
admin: user.hasOwnProperty("admin") ? !!user.admin : false
};
return OctoPrint.postJson(url(), data, opts);
},
get: function (name, opts) {
if (!name) {
throw new OctoPrint.InvalidArgumentError("user name must be set");
}
return OctoPrint.get(url(name), opts);
},
update: function (name, active, admin, opts) {
if (!name) {
throw new OctoPrint.InvalidArgumentError("user name must be set");
}
var data = {
active: !!active,
admin: !!admin
};
return OctoPrint.putJson(url(name), data, opts);
},
delete: function (name, opts) {
if (!name) {
throw new OctoPrint.InvalidArgumentError("user name must be set");
}
return OctoPrint.delete(url(name), opts);
},
changePassword: function (name, password, opts) {
if (!name || !password) {
throw new OctoPrint.InvalidArgumentError("user name and password must be set");
}
var data = {
password: password
};
return OctoPrint.putJson(url(name, "password"), data, opts);
},
generateApiKey: function (name, opts) {
if (!name) {
throw new OctoPrint.InvalidArgumentError("user name must be set");
}
return OctoPrint.postJson(url(name, "apikey"), opts);
},
resetApiKey: function (name, opts) {
if (!name) {
throw new OctoPrint.InvalidArgumentError("user name must be set");
}
return OctoPrint.delete(url(name, "apikey"), opts);
},
getSettings: function (name, opts) {
if (!name) {
throw new OctoPrint.InvalidArgumentError("user name must be set");
}
return OctoPrint.get(url(name, "settings"), opts);
},
saveSettings: function (name, settings, opts) {
if (!name) {
throw new OctoPrint.InvalidArgumentError("user name must be set");
}
settings = settings || {};
return OctoPrint.patchJson(url(name, "settings"), settings, opts);
}
var OctoPrintUserClient = function(base) {
this.base = base;
};
OctoPrintUserClient.prototype.list = function (opts) {
return this.base.get(url(), opts);
};
OctoPrintUserClient.prototype.add = function (user, opts) {
if (!user.name || !user.password) {
throw new OctoPrintClient.InvalidArgumentError("Both user's name and password need to be set");
}
var data = {
name: user.name,
password: user.password,
active: user.hasOwnProperty("active") ? !!user.active : true,
admin: user.hasOwnProperty("admin") ? !!user.admin : false
};
return this.base.postJson(url(), data, opts);
};
OctoPrintUserClient.prototype.get = function (name, opts) {
if (!name) {
throw new OctoPrintClient.InvalidArgumentError("user name must be set");
}
return this.base.get(url(name), opts);
};
OctoPrintUserClient.prototype.update = function (name, active, admin, opts) {
if (!name) {
throw new OctoPrintClient.InvalidArgumentError("user name must be set");
}
var data = {
active: !!active,
admin: !!admin
};
return this.base.putJson(url(name), data, opts);
};
OctoPrintUserClient.prototype.delete = function (name, opts) {
if (!name) {
throw new OctoPrintClient.InvalidArgumentError("user name must be set");
}
return this.base.delete(url(name), opts);
};
OctoPrintUserClient.prototype.changePassword = function (name, password, opts) {
if (!name || !password) {
throw new OctoPrintClient.InvalidArgumentError("user name and password must be set");
}
var data = {
password: password
};
return this.base.putJson(url(name, "password"), data, opts);
};
OctoPrintUserClient.prototype.generateApiKey = function (name, opts) {
if (!name) {
throw new OctoPrintClient.InvalidArgumentError("user name must be set");
}
return this.base.postJson(url(name, "apikey"), opts);
};
OctoPrintUserClient.prototype.resetApiKey = function (name, opts) {
if (!name) {
throw new OctoPrintClient.InvalidArgumentError("user name must be set");
}
return this.base.delete(url(name, "apikey"), opts);
};
OctoPrintUserClient.prototype.getSettings = function (name, opts) {
if (!name) {
throw new OctoPrintClient.InvalidArgumentError("user name must be set");
}
return this.base.get(url(name, "settings"), opts);
};
OctoPrintUserClient.prototype.saveSettings = function (name, settings, opts) {
if (!name) {
throw new OctoPrintClient.InvalidArgumentError("user name must be set");
}
settings = settings || {};
return this.base.patchJson(url(name, "settings"), settings, opts);
};
OctoPrintClient.registerComponent("users", OctoPrintUserClient);
return OctoPrintUserClient;
});
+39 -36
View File
@@ -1,47 +1,50 @@
(function (global, factory) {
if (typeof define === "function" && define.amd) {
define(["OctoPrint", "jquery"], factory);
define(["OctoPrintClient", "jquery"], factory);
} else {
factory(window.OctoPrint, window.$);
factory(global.OctoPrintClient, global.$);
}
})(window || this, function(OctoPrint, $) {
})(this, function(OctoPrint, $) {
var url = "api/util";
var testUrl = url + "/test";
var test = function(command, parameters, opts) {
return OctoPrint.issueCommand(testUrl, command, parameters, opts);
var OctoPrintUtilClient = function(base) {
this.base = base;
};
OctoPrint.util = {
test: test,
testPath: function(path, additional, opts) {
additional = additional || {};
var data = $.extend({}, additional);
data.path = path;
return test("path", data, opts);
},
testExecutable: function(path, additional, opts) {
additional = additional || {};
var data = $.extend({}, additional);
data.path = path;
data.check_type = "file";
data.check_access = "x";
return test("path", data, opts);
},
testUrl: function(url, additional, opts) {
additional = additional || {};
var data = $.extend({}, additional);
data.url = url;
return test("url", data, opts);
}
OctoPrintUtilClient.prototype.test = function(command, parameters, opts) {
return this.base.issueCommand(testUrl, command, parameters, opts);
};
OctoPrintUtilClient.prototype.testPath = function(path, additional, opts) {
additional = additional || {};
var data = $.extend({}, additional);
data.path = path;
return this.test("path", data, opts);
};
OctoPrintUtilClient.prototype.testExecutable = function(path, additional, opts) {
additional = additional || {};
var data = $.extend({}, additional);
data.path = path;
data.check_type = "file";
data.check_access = "x";
return this.test("path", data, opts);
};
OctoPrintUtilClient.prototype.testUrl = function(url, additional, opts) {
additional = additional || {};
var data = $.extend({}, additional);
data.url = url;
return this.test("url", data, opts);
};
OctoPrintClient.registerComponent("util", OctoPrintUtilClient);
return OctoPrintUtilClient;
});
+16 -10
View File
@@ -1,18 +1,24 @@
(function (global, factory) {
if (typeof define === "function" && define.amd) {
define(["OctoPrint"], factory);
define(["OctoPrintClient"], factory);
} else {
factory(window.OctoPrint);
factory(global.OctoPrintClient);
}
})(window || this, function(OctoPrint) {
})(this, function(OctoPrintClient) {
var url = "api/setup/wizard";
OctoPrint.wizard = {
get: function(opts) {
return OctoPrint.get(url, opts);
},
finish: function(handled, opts) {
return OctoPrint.postJson(url, {handled: handled || []}, opts);
}
var OctoPrintWizardClient = function(base) {
this.base = base;
};
OctoPrintWizardClient.prototype.get = function(opts) {
return this.base.get(url, opts);
};
OctoPrintWizardClient.prototype.finish = function(handled, opts) {
return this.base.postJson(url, {handled: handled || []}, opts);
};
OctoPrintClient.registerComponent("wizard", OctoPrintWizardClient);
return OctoPrintWizardClient;
});
+33
View File
@@ -883,3 +883,36 @@ var getQueryParameterByName = function(name, url) {
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
};
/**
* Escapes unprintable ASCII characters in the provided string.
*
* E.g. turns a null byte in the string into "\x00".
*
* Only characters 0 to 31, 127 and 255 will be escaped, that
* should leave printable characters and unicode alone.
*
* Originally based on
* https://gist.github.com/mathiasbynens/1243213#gistcomment-53590
*
* @param str The string to escape
* @returns {string}
*/
var escapeUnprintableCharacters = function(str) {
var result = "";
var index = 0;
var charCode;
while (!isNaN(charCode = str.charCodeAt(index))) {
if (charCode < 32 || charCode == 127 || charCode == 255) {
// special hex chars
result += "\\x" + (charCode > 15 ? "" : "0") + charCode.toString(16)
} else {
// anything else
result += str[index];
}
index++;
}
return result;
};
+4
View File
@@ -158,6 +158,10 @@ $(function() {
PNotify.prototype.options.styling = "bootstrap2";
PNotify.prototype.options.mouse_reset = false;
PNotify.prototype.options.stack.firstpos1 = 40 + 20; // navbar + 20
PNotify.prototype.options.stack.firstpos2 = 20;
PNotify.prototype.options.stack.spacing1 = 20;
PNotify.prototype.options.stack.spacing2 = 20;
PNotify.singleButtonNotify = function(options) {
if (!options.confirm || !options.confirm.buttons || !options.confirm.buttons.length) {
@@ -7,6 +7,13 @@ $(function() {
self.colorTransparent = parameters[0].appearance_colorTransparent;
self.brand = ko.pureComputed(function() {
if (self.name())
return self.name();
else
return gettext("OctoPrint");
});
self.fullbrand = ko.pureComputed(function() {
if (self.name())
return gettext("OctoPrint") + ": " + self.name();
else
@@ -362,9 +362,21 @@ $(function() {
self.onSettingsBeforeSave = self.updateRotatorWidth;
self._isSafari = function() {
var is_chrome = navigator.userAgent.indexOf('Chrome') > -1;
var is_safari = navigator.userAgent.indexOf("Safari") > -1;
return is_safari && !is_chrome;
}
self._disableWebcam = function() {
// only disable webcam stream if tab is out of focus for more than 5s, otherwise we might cause
// more load by the constant connection creation than by the actual webcam stream
// safari bug doesn't release the mjpeg stream, so we just disable this for safari.
if (self._isSafari()) {
return;
}
self.webcamDisableTimeout = setTimeout(function () {
$("#webcam_image").attr("src", "");
}, 5000);
@@ -380,6 +392,12 @@ $(function() {
}
var webcamImage = $("#webcam_image");
var currentSrc = webcamImage.attr("src");
// safari bug doesn't release the mjpeg stream, so we just set it up the once
if (self._isSafari() && currentSrc != undefined) {
return;
}
var newSrc = self.settings.webcam_streamUrl();
if (currentSrc != newSrc) {
if (newSrc.lastIndexOf("?") > -1) {
@@ -113,13 +113,10 @@ $(function() {
},
"model": function(data) {
return data["type"] && (data["type"] == "model" || data["type"] == "folder");
},
"emptyFolder": function(data) {
return data["type"] && (data["type"] != "folder" || data["weight"] > 0);
}
},
"name",
["emptyFolder"],
[],
[["sd", "local"], ["machinecode", "model"]],
0
);
@@ -39,6 +39,8 @@ $(function() {
size: ko.observable(undefined)
};
self.needsLoad = false;
self.renderer_centerModel = ko.observable(false);
self.renderer_centerViewport = ko.observable(false);
self.renderer_zoomOnModel = ko.observable(false);
@@ -174,7 +176,7 @@ $(function() {
currentProfileData = self.settings.printerProfiles.currentProfileData();
}
if (currentProfileData && currentProfileData.extruder && currentProfileData.extruder.offsets()) {
if (currentProfileData && currentProfileData.extruder && currentProfileData.extruder.offsets() && !currentProfileData.extruder.sharedNozzle()) {
var offsets = [];
_.each(currentProfileData.extruder.offsets(), function(offset) {
offsets.push({x: offset[0], y: offset[1]})
@@ -300,6 +302,7 @@ $(function() {
self.loadFile = function(path, date){
self.enableReload(false);
self.needsLoad = false;
if (self.status == "idle" && self.errorCount < 3) {
self.status = "request";
OctoPrint.files.download("local", path)
@@ -401,7 +404,11 @@ $(function() {
self.loadedFileDate = undefined;
} else {
self.waitForApproval(false);
self.loadFile(data.job.file.path, data.job.file.date);
if (self.tabActive) {
self.loadFile(data.job.file.path, data.job.file.date);
} else {
self.needsLoad = true;
}
}
}
}
@@ -573,6 +580,9 @@ $(function() {
self.onTabChange = function(current, previous) {
self.tabActive = current == "#gcode";
if (self.tabActive && self.needsLoad) {
self.loadFile(self.selectedFile.path(), self.selectedFile.date());
}
};
self.shiftLayer = function(value){
@@ -27,13 +27,21 @@ $(function() {
}
});
self.userMenuTitle = ko.pureComputed(function() {
if (self.loggedIn()) {
return _.sprintf(gettext("Logged in as %(name)s"), {name: self.username()});
} else {
return gettext("Login");
}
});
self.reloadUser = function() {
if (self.currentUser() == undefined) {
return;
}
OctoPrint.users.get(self.currentUser().name)
.done(self.fromResponse);
.done(self.updateCurrentUserData);
};
self.requestData = function() {
@@ -44,25 +52,31 @@ $(function() {
self.fromResponse = function(response) {
if (response && response.name) {
self.loggedIn(true);
self.username(response.name);
self.isUser(response.user);
self.isAdmin(response.admin);
self.currentUser(response);
self.updateCurrentUserData(response);
callViewModels(self.allViewModels, "onUserLoggedIn", [response]);
} else {
self.loggedIn(false);
self.username(undefined);
self.isUser(false);
self.isAdmin(false);
self.currentUser(undefined);
self.resetCurrentUserData();
callViewModels(self.allViewModels, "onUserLoggedOut");
}
};
self.updateCurrentUserData = function(data) {
self.username(data.name);
self.isUser(data.user);
self.isAdmin(data.admin);
self.currentUser(data);
};
self.resetCurrentUserData = function() {
self.username(undefined);
self.isUser(false);
self.isAdmin(false);
self.currentUser(undefined);
};
self.login = function(u, p, r) {
var username = u || self.loginUser();
var password = p || self.loginPass();
@@ -128,13 +142,17 @@ $(function() {
});
$("body").on("click", function(e) {
if (!toggle.hasClass("open")) {
return;
}
var anyFormLinkOrButton = $("#login_dropdown_loggedout a, #login_dropdown_loggedin a, #login_dropdown_loggedout button, #login_dropdown_loggedin button");
var dropdown = $("li.dropdown#navbar_login");
var anyLastpassButton = $("#__lpform_login_user, #__lpform_login_pass");
var isLinkOrButton = anyFormLinkOrButton.is(e.target) || anyFormLinkOrButton.has(e.target).length !== 0;
var isDropdown = dropdown.is(e.target) || dropdown.has(e.target).length === 0;
var isLastpass = anyLastpassButton.is(e.target) || anyLastpassButton.has(e.target).length === 0;
var isDropdown = dropdown.is(e.target) || dropdown.has(e.target).length !== 0;
var isLastpass = anyLastpassButton.is(e.target) || anyLastpassButton.has(e.target).length !== 0;
if (isLinkOrButton || !(isDropdown || isLastpass)) {
toggle.removeClass("open");
Loaded 100 of 136 files, more files were not shown because too many files have changed in this diff. Show more