Compare commits

..
232 Commits
Author SHA1 Message Date
Gina Häußge d60c5a631a 🔖 Prepare release of 1.7.2 2021-11-02 17:31:00 +01:00
Gina Häußge 444fe44d48 🐛 Fix double encoding of file resources
`url_for` seems to be doing the encoding already after all,
so we must not do it as well.

Fixes #4293
2021-11-02 17:19:32 +01:00
Gina Häußge 7d5474cb3d 🔖 staging/bugfix is now 1.7.2.dev 2021-11-01 16:30:21 +01:00
Gina Häußge 945825f03f Merge branch 'master' of github.com:OctoPrint/OctoPrint into master 2021-11-01 15:47:03 +01:00
Gina Häußge 1bd19e3fd5 🔖 Prepare release of 1.7.1 2021-11-01 14:32:07 +01:00
Gina Häußge fd8a72a77a 🥅 Default to lowLatency=False for now
Apparently some printers/printer connections really don't like the
attempt to set the low latency flag, as in, it fails, handled gracefully,
but then the connection is broken regardless.

We'll disable it by default for now, and tackle this properly in 1.8.0.
2021-11-01 11:09:11 +01:00
Gina Häußge dfe7dc7a78 🐛 URL escape timelapse file names as well
It turns out those are also affected by #4267
2021-10-29 17:28:35 +02:00
Gina Häußge 16086741b8 🐛 Better fix for #4267
New helper OctoPrintClient.escapePath, does the equivalent
of x.split("/").map(e => escapeURIComponent(e)).join("/").

Used in the files API client.
2021-10-29 17:28:35 +02:00
Gina Häußge 3bbd3f7a3e 🐛 URL encode all uploaded file names
Otherwise a # in the URL might be treated as a fragment and lead to
resource mismatches.

Closes #4267
2021-10-29 11:20:56 +02:00
Quinn DamerellandGina Häußge 995c8aa0c6 🐛 PMGR: Fix bug in default sort of plugins from the repo (#4273)
Related to #4031

Co-authored-by: Gina Häußge <gina@octoprint.org>
2021-10-29 11:20:39 +02:00
Gina Häußge e3999ca5bb Merge branch 'master' into staging/bugfix 2021-10-29 11:20:11 +02:00
Gina Häußge 4a9e573107 👷‍♂️ Fix comment syntax in workflow step
JS uses `//`, not `#` ...
2021-10-27 22:58:45 +02:00
Gina Häußge 58dc515990 Merge pull request #4285 from OctoPrint/meta/rephrase-bundle-reminder
👷‍♂️ Rephrase the bundle reminder
2021-10-27 22:56:02 +02:00
Gina Häußge d3e92db8a8 👷‍♂️ Rephrase the bundle reminder
And doing this as a PR to test the PR label fix from earlier today...
2021-10-27 22:54:21 +02:00
Gina Häußge 450d5bb9ae 👷‍♂️ Fix PR automation
Labels weren't refreshed properly in a step, causing
labeling to be reverted and thereby causing issues 
in a later step.
2021-10-27 12:57:01 +02:00
Gina Häußge 5444c46777 Merge pull request #4282 from OctoPrint/meta/issue-bundle-reminder
Add reminder for issues w/o bundles
2021-10-27 11:40:29 +02:00
Charlie Powell e451493c0d ✏️ Add missing minDelay timelapse data model entry 2021-10-26 20:16:42 +01:00
Gina Häußge 2a247672a6 👷 Add reminder for issues w/o bundles
Will add a reminder if an issue is labeled 'triage' and now bundle
is detected.

Will go away if issue is no longer labeled 'triage' or edited to fix the
problem.
2021-10-26 19:45:17 +02:00
Gina Häußge 1ae017954b Merge branch 'master' into staging/bugfix 2021-10-14 16:57:35 +02:00
Gina Häußge 1b04c08a1a 🔖 staging/bugfix is now 1.7.1.dev 2021-10-12 11:29:38 +02:00
Gina Häußge ddfd333b62 Merge branch 'master' into staging/bugfix 2021-10-12 11:28:26 +02:00
Gina Häußge 03d3dfb496 💚 Hopefully fix E2E
ubuntu-latest *should* work I hope.
2021-10-11 15:50:43 +02:00
Gina Häußge 027d8f8069 Merge branch 'master' of github.com:OctoPrint/OctoPrint into master 2021-10-11 15:45:40 +02:00
Gina Häußge 098db891cb Merge branch 'rc/maintenance' into master 2021-10-11 15:05:36 +02:00
Gina Häußge 1120dc94a1 ⬆️ Update OctoPrint-FirmwareCheck
2021.8.11 had a compatibility issue with Python 2.
2021-10-11 15:00:28 +02:00
Gina Häußge 76299089b3 Merge branch 'rc/maintenance' into master 2021-10-11 11:56:13 +02:00
Gina Häußge e90a95b714 💥 Deprecate OctoPi 0.15 environment
On OctoPi 0.15 OctoPrint 1.7.0+ will refuse to update.

Reason: yet another dependency no longer building in
this ancient environment. We'll allow an upgrade to 1.7.0
because we cannot retroactively warn people about this
anymore, but from here on out that's it.

OctoPi 0.15 was released in 2018, I think it's fair to
expect people to update, especially with the available
backup and restore functionality.
2021-10-11 11:54:52 +02:00
Gina Häußge b7b832383f 📌 Pin wrapt to 1.12.*
Newer versions than 1.12 no longer build on OctoPi 0.15
2021-10-11 11:48:54 +02:00
Gina Häußge d362685bcb Merge branch 'rc/maintenance' into master 2021-10-11 11:13:31 +02:00
Gina Häußge b65bcf27ce Merge branch 'staging/maintenance' into rc/maintenance 2021-10-11 11:13:27 +02:00
Gina Häußge 04664467b4 🔖 Preparing release of 1.7.0 2021-10-11 11:12:01 +02:00
Gina Häußge cffcecc2bb 📝 Fix a doc formatting issue
RST can be so annoying sometimes...
2021-10-08 15:12:00 +02:00
Gina Häußge fd685a0197 Merge pull request #4245 from bryankenote/osx-setup-doc
Add step to osx development setup documentation
2021-10-08 15:06:18 +02:00
Bryan Kenote 217f1cdf5f add self to authors 2021-10-08 15:04:25 +02:00
Bryan Kenote c1a7f999db add pip install step to osx documentation 2021-10-08 15:03:27 +02:00
Gina Häußge 5f7679b11b 👷 Add target branch labels to PRs 2021-09-14 18:55:46 +02:00
Gina Häußge 6050fad5ba 🔖 staging/maintenance is now 1.7.0rc4.dev 2021-09-13 13:59:07 +02:00
Gina Häußge f31194f753 🔖 Preparing release of 1.7.0rc3 2021-09-13 11:48:11 +02:00
Gina Häußge 16a7ce0c88 🐛 Fix URL for plugin list export
Needed baseurl prefix.

Closes #4231
2021-09-13 09:49:53 +02:00
Gina Häußge de2b95537c Merge branch 'staging/maintenance' of github.com:OctoPrint/OctoPrint into staging/maintenance 2021-09-13 09:42:32 +02:00
Gina Häußge 53d73182de 🐛 Set autocapitalize=none on login form
Closes #4226
2021-09-13 09:42:23 +02:00
Charlie Powell 0e1ada7a0e ✏️ Add missing tool change scripts documentation 2021-09-09 14:51:58 +02:00
Charlie Powell 18c3e6660f 🐛 Remove CSS width: auto on announcements dialog, breaks things
This makes the width of the modal really narrow when it is first opened & on certain screen sizes, removing this line appears to fix the issues.

Closes #4216
2021-09-09 14:49:56 +02:00
Gina Häußge 0bba8be6dc 🐛 Convert showProgressDialog to #4105 changes
Fixes #4210
2021-09-09 12:22:30 +02:00
Gina Häußge 4bdf904eeb ⬇️ Keep unidecode < 1.3 on Python 2
1.3 as released on Sep 6th requires Python 3
2021-09-09 11:41:39 +02:00
Gina Häußge 5fc22593f9 🐛 swu: Remove active class
Closes #4207
2021-08-11 15:08:45 +02:00
Gina Häußge c21961113d 🔖 staging/maintenance is now 1.7.0rc3.dev 2021-08-11 14:57:58 +02:00
Gina Häußge d71de9003d 🔖 Preparing release of 1.7.0rc2 2021-08-11 12:20:07 +02:00
Gina Häußge 8740c5a826 🎨 eventmgr: Replace tabs with spaces 2021-08-09 10:34:37 +02:00
Gina Häußge cdcbb13102 💄 eventmgr: Use faster fade-in animation
Closes #4204
2021-08-09 10:34:24 +02:00
Gina Häußge 2f266f9974 🐛 printTimeLeft may be None
So we need to check for that first before we try to
convert to an int.

Regression.

Closes #4202
2021-08-09 10:18:18 +02:00
Gina Häußge a7d4c5f2df 🐛 Change latency mode setting logic
We should only ever attempt to set it if we are supposed
to set it to True. Otherwise there's no need to do
anything really and risk running into issues.

Closes #4203
2021-08-09 10:04:48 +02:00
Gina Häußge 3a7f539fd5 👷 Fix version sent to custopizer build 2021-08-05 12:29:38 +02:00
Gina Häußge b8417d838c 🔖 staging/maintenance is now 1.7.0rc2.dev 2021-08-04 15:49:00 +02:00
Gina Häußge 3fe45661cd 💬 Fix a translation 2021-08-04 12:54:49 +02:00
Gina Häußge 3c3f55e0c1 🔖 Preparing release of 1.7.0rc1 2021-08-04 11:54:23 +02:00
Gina Häußge 70d07889e2 💚 emoji update changed wolf_face to wolf 2021-08-03 12:03:05 +02:00
Gina Häußge d61705aace 🐛 SWU: Fix first run update
It was actually not working at all any more. The new approach
should perform better, cause less duplication and overall
be cleaner.
2021-08-03 11:40:39 +02:00
Gina Häußge 4d2e7f1ddd ⬆️ Upgrade several dependencies 2021-08-03 11:40:39 +02:00
Gina Häußge a8660c9ef2 🐛 Fix log coloring 2021-08-03 11:40:39 +02:00
jneilliiiandGina Häußge 4d60b6b604 Update src/octoprint/plugins/eventmanager/templates/eventmanager_settings.jinja2
Co-authored-by: Gina Häußge <gina@octoprint.org>
2021-08-02 11:01:17 +02:00
jneilliiiandGina Häußge 36e5ded017 Update src/octoprint/plugins/eventmanager/templates/eventmanager_settings.jinja2
Co-authored-by: Gina Häußge <gina@octoprint.org>
2021-08-02 11:01:17 +02:00
jneilliiiandGina Häußge a62fc00f3a Update src/octoprint/plugins/eventmanager/__init__.py
Co-authored-by: Gina Häußge <gina@octoprint.org>
2021-08-02 11:01:17 +02:00
jneilliii 18281a9ebd precommit again 2021-08-02 11:01:17 +02:00
jneilliii e158b82983 refactor for name and suggested edits 2021-08-02 11:01:17 +02:00
jneilliii 9bbce7caf4 additional localization 2021-08-02 11:01:17 +02:00
jneilliii 122a6667ea add localization, per @cp2004 2021-08-02 11:01:17 +02:00
jneilliii 51b4375ed7 order events in settings 2021-08-02 11:01:17 +02:00
jneilliii 17c3d6e57a added an events bundled plugin for managing event settings 2021-08-02 11:01:17 +02:00
Gina Häußge 52e105416d 🥅 Better error handling of resend history issues
Not a fix for #4194, but at least a less fatal handling.
2021-07-26 16:49:49 +02:00
Gina Häußge cc60f457f8 Merge branch 'master' into maintenance 2021-07-26 11:39:44 +02:00
Charlie Powell 19388fc11f ✏️ Add link to data model for printer profiles for gcode scripts
Closes #3603
2021-07-26 11:08:17 +02:00
Charlie Powell 464f0cd83f ✏️ Additional file information properties documented
Closes #2682
2021-07-26 11:06:35 +02:00
Ben SychaandGina Häußge 161e21fe0f Apply suggestions from code review to fix RST formatting
Co-authored-by: Gina Häußge <gina@octoprint.org>
2021-07-20 18:56:51 +02:00
Ben SychaandCharlie Powell e993405785 Apply suggestions from code review
Fix typos and remove irrelevant line

Co-authored-by: Charlie Powell <31997505+cp2004@users.noreply.github.com>
2021-07-20 18:56:51 +02:00
Ben Sycha 323d7ecb0d 📝 add instructions for setting up vscode IDE 2021-07-20 18:56:51 +02:00
Gina Häußge 037519eebd 📝 Add version added to new event 2021-07-20 11:21:54 +02:00
Ian Wilt f7e53a4a50 Shouldn't have been apostrophes oops 2021-07-19 15:09:50 +02:00
Ian Wilt 07040b103f Added event FilamentChange 2021-07-19 15:09:50 +02:00
GitHub Nightly Merge Action e74041bc93 Merge branch 'master' into maintenance 2021-07-16 00:05:28 +00:00
Gina Häußge 5700695ef3 👷 Back to allowed_targets, but nerf bot 2021-07-15 17:43:32 +02:00
Gina Häußge e004a24bf0 👷 Switch to PR target deny list 2021-07-15 17:31:50 +02:00
Gina Häußge 3985d10e04 👷 Add ignore label to PR validation config 2021-07-15 17:01:06 +02:00
Gina Häußge f62867de47 🐛 Fix ko invisible binding 2021-07-13 15:39:29 +02:00
Gina Häußge 5cde163f2b ✨ SWU: Offer to update in first run wizard
This will now be the very first step of the first run
wizard, IF OctoPrint is detected as outdated.

Implements #3936
2021-07-07 18:27:23 +02:00
Gina Häußge 32a52bdb0f 🐛 Fix a bug in wizard ignored calculation (Py3 only?)
If seen was None and current was not, there would be an
error due to comparing an int with None.
2021-07-07 18:04:07 +02:00
Gina Häußge 7d22354566 🐛 Fix less vs CSS3 calc 2021-07-06 19:45:58 +02:00
Gina Häußge 974cde5294 🐛 swu: Fix a bug in log line generation 2021-07-06 17:41:25 +02:00
Gina Häußge 6618be9e84 📝 Document new (bundle only) hook 2021-07-06 16:39:06 +02:00
Gina Häußge fc106e5918 ✨ New hook for bundled plugins to add to systeminfo bundles
SWU and PMGR make use of that to add console logs. SWU
now also adds the update log as plugin_softwareupdate_update.log.

Also improved caching and sorting behaviour on SWU update log.
2021-07-06 16:14:45 +02:00
Gina Häußge 8bb3312bba ✨ swu: one month update log
Implements #4065
2021-07-06 11:57:33 +02:00
Charlie PowellandGina Häußge 9f77502214 ♻️ Improve logic in analysis dimensions test
Co-Authored-By: Gina Häußge <83657+foosel@users.noreply.github.com>
2021-07-05 15:48:08 +02:00
Gina Häußge 1e16e9052c ✨ Include webcamd.log & haproxy.log in sysinfo bundle 2021-07-05 11:57:23 +02:00
Gina Häußge d73d530600 ✨ Colored console output 2021-07-02 16:24:30 +02:00
cp2004 c355318f1a 🐛 Fix files with no dimensions breaking the files UI
I had a response like
```
"date": 1614624977,
      "display": "Misc_-_Happy_Birthday_1.gcode",
      "gcodeAnalysis": {
        "analysisPending": false
      },
      "hash": "20af558d1fc68865333892cd9d0536293120e3b7",
      "name": "Misc_-_Happy_Birthday_1.gcode",
      "origin": "local",
      "path": "Misc_-_Happy_Birthday_1.gcode",
```
Can't go 3 levels deep in JS without checking that the object exists, which apparently in some cases it doesn't.
2021-06-30 23:28:05 +01:00
Gina Häußge f63f177c78 👷 Add repodispatch for OctoPi-UpToDate
Also update docs build secret name
2021-06-30 15:25:32 +02:00
Gina Häußge df08459ede 🥅 Some more sanity checking of FFMPEG params 2021-06-23 12:16:39 +02:00
Gina Häußge 87ddc8468c ♻️ Switch to b:v for bitrate
Seems more fitting to do add a stream selector for the video stream
based on the ffmpeg docs and #4059

Closes #4059
2021-06-23 12:16:39 +02:00
Gina Häußge d774122023 🥅 Protect against invalid bitrate values 2021-06-23 12:16:39 +02:00
GitHub Nightly Merge Action 02c2e9e983 Merge branch 'master' into maintenance 2021-06-23 00:05:29 +00:00
Gina Häußge 146c83152d 🚸 Add FAQ link to throttled messages
Closes #4069
2021-06-22 19:03:46 +02:00
Gina Häußge 8bf25c33e5 🚸 Remove artifical upper limit on extruder count
It was only cosmetic in nature anyhow, and kinda misleading.

Closes #4149
2021-06-22 18:44:53 +02:00
Gina Häußge 85f6fa0182 📝 Clarify cookies vs CORS
Closes #4174
2021-06-22 17:40:24 +02:00
cp2004 c8f7f25e21 ✏️ 🐛 Fix autodoc duplication issues
Now we fixed the docstrings, they are defining what is documented out of a module, so we don't need to include members in the top level file.
2021-06-21 16:27:21 +02:00
cp2004 e1657d5e3e ✏️ 🐛 Fix a bunch of general doc issues
Solves
2021-06-21 16:27:21 +02:00
cp2004 05cd0211ff ✏️ 🐛 Move some future imports below docstrings
This broke sphinx autodoc, it would not pick up the module-level docstrings. In most cases, this was not really a problem but printer profiles documentation was missing quite a lot.
2021-06-21 16:27:21 +02:00
cp2004 7a13ec1edc 🐛 Fix G90/G91 feature label
Introduced by #4116, seems I should have paid more attention and not just experimented in the devtools.
2021-06-21 15:21:26 +02:00
cp2004 599d80ad7b ⬆️ Upgrade Tornado for Python 3 only
Python 3.10 introduces a backwards incompatible change around collections and collections.abcs, which tornado was impacted by.

According to Tornado's release notes https://www.tornadoweb.org/en/stable/releases/v6.0.0.html seem like there is not much else to worry about, and the devel branch has already  upgraded it.

Would be good to get this tested by someone else using Python 3.10 and some plugins, and also some Python 2 installs.

See also #4043 for the other collections-related changes.
2021-06-21 15:20:44 +02:00
Gina Häußge c3a796ae4c ✨ New hook: octoprint.system.additional_commands
Allows to inject additional commands into the system menu from plugins.

Implements #4143
2021-06-15 19:44:52 +02:00
Gina Häußge b0917feba7 ✨ New frontend callback "onBeforePrintStart"
Can be used to hook into and prevent the start of a print job via click
on "Start" in the print state or click on select & print in the file
list.
2021-06-15 11:35:29 +02:00
Gina Häußge cae4f1a0b7 🚸 Show annoying notification if Py2 is detected
As suggested in #4166
2021-06-14 16:28:57 +02:00
Gina Häußge 1fb243099c 💬 pmgr: Fix wording of a message 2021-06-14 15:56:01 +02:00
Gina Häußge 45cf5ddf44 🥅 pmgr: Better handling of python version mismatch
Users now get a meaningful error message in both the plugin install log
as well as a clickable FAQ link in the plugin management log
notification.

Works for pip and single file installs.

Implements #4166
2021-06-14 15:55:05 +02:00
Gina Häußge bb6b694fa7 ♻️ Extract octoprint.plugin.core.parse_plugin_metadata
This way our plugin AST parser routine becomes reusable in things like
the plugin manager.
2021-06-14 15:53:06 +02:00
Gina Häußge 6dd92f234f 🚸 Recovery: Focus on sys info bundle instead of text dump
Follow-up to d19acf892a
2021-06-14 11:25:16 +02:00
Gina Häußge 6f2c8c1e2b 🐛 Fix TEMPLATES_AUTO_RELOAD not being honored
Now stuff should reload properly again on change.
2021-06-14 11:21:47 +02:00
Gina Häußge e98a5df858 🚸 Special metadata output for empty files
Instead of zero dimensions and bounding box we now just say "Model
contains no extrusion."

That should hopefully make it clear. Works for new analysis results with
`_empty` flag as well as analysis results with all 0 dimensions.

See also #4162
2021-06-14 11:01:52 +02:00
Gina Häußge 054b856839 🐛 Set empty analysis result for empty files
That way they won't get added to the backlog again on every single
server startup.

Fixes #4162
2021-06-14 10:59:41 +02:00
Gina Häußge d19acf892a 🚸 Make bundle download more visible
Many users are still copy/pasting the textual system info dump and
forget to share the bundle. Rephrase the request to target the bundle
and hide the info dump behind a More area. Also link to the bundle
viewer.
2021-06-11 12:15:26 +02:00
Gina Häußge df5f456072 🔊 Improve logging of folder config issues
See #4167
2021-06-10 18:09:10 +02:00
cp2004 f9543773ec 🐛 Missed dialog for fade in
Missed the 'reload settings' dialog when sorting out the animations, missed one
2021-06-09 15:48:35 +02:00
GitHub Nightly Merge Action 0a018dd2c4 Merge branch 'master' into maintenance 2021-06-09 00:05:38 +00:00
Gina Häußge 4c1152c70b 📝 Fix printer profiles API docs
Phrasing improved and some copy-paste issues resolved as well.

Fixes #4160
2021-06-08 15:53:17 +02:00
ldursw 7955fbd269 Fix code style 2021-06-08 15:28:24 +02:00
ldursw b60c1092a4 Add arc calculation to gcode interpreter 2021-06-08 15:28:24 +02:00
Gina Häußge 6fc97f8f30 🐛 tracking: Fix a rename error 2021-05-26 18:18:52 +02:00
Gina Häußge c37c64a742 ✨ tracking: Track browser/OS of webui on load
Can of course be disabled.

Better implementation of #4148

Thanks you @apbarratt!
2021-05-26 17:11:42 +02:00
Gina Häußge e6860aaec6 ✨ CoreUI: Add browser/browser OS name & version to detection 2021-05-26 17:09:58 +02:00
Gina Häußge fcf45f7d59 ✨ Support position autoreporting
Includes proper handling auf cancel/pause situation, where we use the
position report as a signal that all movement has ended and the position
report should be used for final cancel/pause position, adds a new
terminal filter and also takes care of capability report evaluation and
proper interval setting via M154.

cc @thinkyhead - the cancel/pause situation worried me, so I took a look
how to solve it and that meant the implementation was already done as
well. Hope you don't hold it against me to tackle this myself after all.
2021-05-25 19:50:06 +02:00
Gina Häußge e11cd882e6 Merge branch 'maintenance' of github.com:OctoPrint/OctoPrint into maintenance 2021-05-25 11:16:27 +02:00
Gina Häußge 88921542ef ✨ Send M20 L if detected as supported
Also support quoted long names, which apparently are sent by some
firmwares? Make a suggestion for a format that is universally parseable,
document it on the reprep wiki, people STILL find a way to be
incompatible to it. I can't even...

Anyhow. See https://community.octoprint.org/t/adding-support-for-m20-l/34402
2021-05-25 11:15:43 +02:00
Stevil Knevil 1c70931e12 Wrapped text for translation 2021-05-21 10:43:11 +02:00
Stevil Knevil 8e15dffca0 Added helptext 2021-05-21 10:43:11 +02:00
Stevil Knevil e9ea4c4d95 Improved wording around backup message 2021-05-21 10:43:11 +02:00
Gina Häußge 9cf0802bf2 💚 Fix a typo in a unit test 2021-05-20 15:21:11 +02:00
Gina Häußge f1ea8a3a02 Merge branch 'master' into maintenance 2021-05-20 14:35:35 +02:00
Gina Häußge 8db57f72ab 📝 Remove a left over 2021-05-20 14:34:54 +02:00
Gina Häußge 86c2b60a4d Merge branch 'master' into maintenance 2021-05-20 12:13:24 +02:00
Gina Häußge 3c9fa3eff2 📝 Update dev env docs
We need to update the links to the py2 windows files. Also make py2
environment instructions optional across the board, they really should
only be relevant for maintenance going forward.
2021-05-20 12:11:00 +02:00
Gina Häußge f912adcd33 ✨ Support unicode file names on Py3
If we are on py3 and thus can rely on pathvalidate, we'll now no longer
slugify uploaded files names, but try to keep them as close to the
original name as possible, including unicode and emoji and whatnot. This
requires the underlying file system to support this, so just in case the
old behaviour can be enforced by setting the config flag
feature.enforceReallyUniversalFilenames to true.

Closes #4078
2021-05-20 10:36:01 +02:00
Gina Häußge ecf56b6658 🔥 Remove deprecated octoprint.util.get_free_bytes 2021-05-19 17:56:08 +02:00
Gina Häußge 1f4d22affb Merge remote-tracking branch 'origin/maintenance' into maintenance 2021-05-18 14:42:50 +02:00
Gina Häußge 5d326e9c57 🥅 Ensure int for printTimeLeft from plugins
See #4084
2021-05-18 14:42:24 +02:00
Gina Häußge e4fff3ff4f Merge branch 'master' into maintenance 2021-05-18 14:40:36 +02:00
Gina Häußge 884ccee5f8 📝 Fix some doc bugs
Closes #4084
2021-05-18 12:38:45 +02:00
Gina Häußge ac07c77276 Merge pull request #4135 from eyal0/patch-6
bedZ should be a float
2021-05-18 11:37:07 +02:00
Gina Häußge c838436d77 Merge pull request #4136 from cp2004/fix/samesite-none
🐛 Fix SameSite=None cookie
2021-05-18 11:35:37 +02:00
Gina Häußge f2845855dd Merge pull request #4137 from oliof/patch-1
Update messages.po
2021-05-18 11:33:36 +02:00
Gina Häußge bce1b028c9 Merge pull request #4128 from StevilKnevil/improve/ignored_commands
Improve/ignored commands
2021-05-18 11:31:33 +02:00
Harald Wagener d153bad51b Update messages.po
tiny grammar fix.
2021-05-13 11:25:06 +02:00
cp2004 d83d4b1528 📝 Adjust/clarify docs 2021-05-12 16:45:27 +01:00
cp2004 2c03ecdfff 🐛 Fix SameSite=None cookie
When passing Python's NoneType down to Werkzeug, it uses this logic:

```python
if samesite is not None:
    samesite = samesite.title()

    if samesite not in {"Strict", "Lax", "None"}:
        raise ValueError("SameSite must be 'Strict', 'Lax', or 'None'.")
```

This means that when OctoPrint converted any strings 'None' into NoneType,
they would not show up in the Set-Cookie header.

Investigation: https://community.octoprint.org/t/unable-to-log-into-octoprint-through-an-iframe-on-home-assistant/33977/20?u=charlie_powell

Link to werkzeug source: https://github.com/pallets/werkzeug/blob/1dde4b1790f9c46b7122bb8225e6b48a5b22a615/src/werkzeug/http.py#L1213-L1217

Docs, while not explicitly clear, here: https://werkzeug.palletsprojects.com/en/1.0.x/http/?highlight=dump_cookie#werkzeug.http.dump_cookie
2021-05-12 16:30:44 +01:00
Eyal 7234b26d2a bedZ should be a float 2021-05-11 09:34:16 -06:00
Gina Häußge 0ad9690abd Merge pull request #4132 from cp2004/improve/pgmr-cache-no-render
⚡ Don't re-render the plugin repository if notmodified
2021-05-11 16:56:54 +02:00
Gina Häußge fa8d4f7c58 Merge branch 'maintenance' of github.com:OctoPrint/OctoPrint into maintenance 2021-05-10 16:39:07 +02:00
Gina Häußge 6810a2c00f Merge branch 'master' into maintenance 2021-05-10 16:38:59 +02:00
Gina Häußge 6053cad832 💚 Update cypress dependencies 2021-05-10 16:37:33 +02:00
Gina Häußge 2087c3da54 🔖 staging/bugfix is now 1.6.2.dev 2021-05-10 15:40:37 +02:00
Gina Häußge 8b319e9637 🔖 Preparing release of 1.6.1 2021-05-10 11:44:33 +02:00
cp2004 e403e8cc75 ⚡ Don't re-render the plugin repository if notmodified
Closes #4131
2021-05-09 16:58:39 +01:00
Gina Häußge 3b3a2a9732 Merge pull request #4129 from cp2004/patch-6
💄  Remove smaller button in software update
2021-05-07 23:41:43 +02:00
Charlie Powell 9f1a53b315 💄 Remove smaller button in software update
Small annoyance - it doesn't *need* to be any larger, but the text buttons look too small up there. As a result I removed the small class from the icon button to make it line up.
2021-05-07 22:32:19 +01:00
Gina Häußge 8354e0c200 Merge pull request #4125 from kantlivelong/doc_fix
Fix typo in docs for octoprint.server.api.before_request
2021-05-07 16:49:59 +02:00
Gina Häußge ae60033551 ✨ Use low latency flag on serial port
Might improve serial performance.

Implements #4099
2021-05-07 16:19:06 +02:00
Gina Häußge f69ab86524 🐛 Get rid of an unnecessary overflow: hidden
Fixes #4092
2021-05-07 15:34:52 +02:00
Gina Häußge 7131738987 💬 Rephrase GCODE scripts description
Apparently "after establishing the connection to the printer" could be
misunderstood, see #4126
2021-05-07 12:12:52 +02:00
Stevil Knevil 98454a2827 Updated Authors.md 2021-05-06 17:45:41 +01:00
Stevil Knevil 7765e9afa9 Implemented ignored commands 2021-05-06 17:33:55 +01:00
Gina Häußge a0db794bd6 Merge branch 'staging/bugfix' into maintenance
# Conflicts:
#	src/octoprint/plugins/gcodeviewer/static/js/viewer/renderer.js
2021-05-06 12:38:36 +02:00
Gina Häußge e1f8a82dc2 🥅 GCV: Work around for Chrome bug
Chrome's canvas arc method seems to produce wrong results in case of
extremely large radii combined with extremely small enclosed angles. So
in case of Chrome we'll now default to a replacement function
approximating the arc with bezier curves. This can however be disabled
via the advanced options.

Additionally, another debug visualization option was added that shows
the arcs with their center points and segment borders.

Closes #4117
2021-05-06 12:32:28 +02:00
Shawn Bruce 513b9b951c Fix typo in docs for octoprint.server.api.before_request 2021-05-05 11:51:31 -04:00
Gina Häußge 0580b0fa73 Merge pull request #4103 from cp2004/improve/dialog-fade
💄 Improve all dialog animations
2021-05-04 19:17:49 +02:00
Gina Häußge 0ce1c0537c Merge pull request #4124 from cp2004/improve/disable-cache-buster
✨  Add option to disable cache busting on webcam URL
2021-05-04 18:23:51 +02:00
cp2004 78042648ee 💄 Make label line up with checkbox label 2021-05-04 15:49:39 +01:00
cp2004 3319624e82 🐛 Fix height of the webcam test modal
An interesting condition of when the correct positioning was calculated - with the animation, often the webcam stream loaded fast enough that it was before the animation was finished. Now there is no animation (from jQuery) then we hit a timing problem.

Yes, it is hardcoded but so is the modal width.
2021-05-04 15:39:44 +01:00
cp2004 6725bbfa47 ✨ Add option to disable cache busting on webcam URL
See #4107
2021-05-04 15:00:51 +01:00
Gina Häußge 4842835ec5 Merge pull request #4122 from cp2004/fix/random-files-span
🐛 Remove random debug span
2021-05-04 14:05:46 +02:00
cp2004 8f77a8fcda 🐛 Remove old debug code from showInternalFilename
Well that shouldn't have been there.
No one noticed it though
2021-05-04 12:48:04 +01:00
Gina Häußge 0cb987a8bd 🥅 Prevent SD refresh while printing
Part 2 of fixing #4119
2021-05-03 12:07:51 +02:00
Gina Häußge 58fd13b238 🐛 Fix refresh timeout
It's in SECONDS, not milliseconds 🤦‍♀️

Part 1 of fixing #4119
2021-05-03 11:54:12 +02:00
Gina Häußge 19c39588e6 🐛 GCV: Fix dragging w/ center origin & bed changes
Minor refactoring to get rid of three problems. Not only is #4115 as
introduced by 886c3d9449 fixed but changes
to the bed dimensions after printer profile change now trigger a proper
viewport reset (zoom & translation) and there's now also a button to
reset the viewport to a sensible default should you get completely lost
in the viewer canvas.

Closes #4115
2021-05-03 11:06:24 +02:00
GitHub Nightly Merge Action 6b11d0b528 Merge branch 'master' into maintenance 2021-04-30 00:06:34 +00:00
Gina Häußge 2180d856b9 Merge pull request #4116 from cp2004/patch-5
✏️  Marlin 2 uses G90 influences extruder
2021-04-29 12:54:29 +02:00
Gina Häußge 2494736d5f 🔖 staging/bugfix is now 1.6.1.dev 2021-04-29 12:48:18 +02:00
Gina Häußge e42d49d88c Merge branch 'master' into staging/bugfix 2021-04-29 12:46:55 +02:00
Gina Häußge 25abe0562d 👷 Switch issue form to system info bundles 2021-04-29 12:32:33 +02:00
Gina Häußge 2b8f1d7340 Revert "👷 Roll back to issue template (temporarily)"
This reverts commit 1a251c94
2021-04-29 10:45:10 +02:00
cp2004 3a80aa7881 💄 Hopefully the last one 2021-04-28 23:18:17 +01:00
cp2004 93f5fd2eff 🐛 width: auto breaks things 2021-04-28 23:06:46 +01:00
cp2004 4c46247989 💄 Missed some dialogs 2021-04-28 23:03:18 +01:00
cp2004 99fb6cfee7 Merge remote-tracking branch 'upstream/maintenance' into improve/dialog-fade 2021-04-28 22:23:22 +01:00
Charlie Powell 8435039e64 ✏️ Marlin 2 uses G90 influences extruder
Closes #4101

🎨 pretty
2021-04-28 22:17:04 +01:00
cp2004 6248f3bd6b ⚡ Reduce animation duration slightly
Feels a bit snappier, but still enough animation.

Easily configurable if it needs adjusting.
2021-04-28 22:08:53 +01:00
cp2004 fd86369cc6 💄 Apply to all core dialogs
I tried to find them all.... Hopefully got them.
2021-04-28 22:03:04 +01:00
Gina Häußge 0c5b2fbf36 📝 Fix markdown of authors list 2021-04-28 17:18:59 +02:00
Gina Häußge 877fe18297 Merge pull request #4114 from sparxooo/filefolder-rename
File/Folder renaming in OctoPrint web UI
2021-04-28 16:53:25 +02:00
Gina Häußge c9bdd10fb8 Merge branch 'maintenance' into filefolder-rename 2021-04-28 16:44:33 +02:00
Gina Häußge 73776c04f4 Merge pull request #4111 from eltonlaw/gh-3505/add-unselect-to-files-api
/api/files: add unselect file command
2021-04-28 16:43:43 +02:00
Gina Häußge e03f28999f Merge pull request #4105 from LazeMSS/Improve/RemoveResizeSensor
Removed the ResizeSensor to prevent constant resizing events.
2021-04-28 16:26:57 +02:00
GitHub Nightly Merge Action 42bd85586b Merge branch 'master' into maintenance 2021-04-28 00:12:11 +00:00
Gina Häußge b1b7200d63 📝 We are currently back on the bug report template 2021-04-27 16:11:13 +02:00
Gina Häußge 6ad8f6b2f4 📝 Update Contribution Guidelines w/ Systeminfo Bundles 2021-04-27 16:10:47 +02:00
Gina Häußge f3be7a488e Merge branch 'maintenance' of github.com:OctoPrint/OctoPrint into maintenance 2021-04-27 11:37:12 +02:00
Gina Häußge f8d6c64ddb Merge branch 'master' into maintenance 2021-04-27 11:36:53 +02:00
sparxooo 5c9c92750f Added rename functionality to OctoPrint web UI 2021-04-27 03:23:21 +01:00
GitHub Nightly Merge Action e26d711e86 Merge branch 'master' into maintenance 2021-04-27 00:12:00 +00:00
Gina Häußge d8976e1ba3 Merge branch 'staging/maintenance' into maintenance 2021-04-26 15:41:03 +02:00
Gina Häußge e11da95a52 Merge branch 'staging/maintenance' into maintenance 2021-04-26 14:46:44 +02:00
Elton Law 8c4020eac1 /api/files: add unselect command
Adding the `unselect` right next to where the `select` is implemented.
There are two ways of unselecting, 1) using the selected filename,
2) using special word `current`

    POST /api/files/local/whistle_v2.gcode
    POST /api/files/local/current
2021-04-25 03:11:37 -04:00
LazeMSS ed87ea751b Forgot pre-commit 2021-04-21 13:25:39 +02:00
LazeMSS fcbff23fcb Removed the ResizeSensor to prevent constant resizing events.
It should still look and feel almost the same just using css + knockout
2021-04-21 12:35:56 +02:00
GitHub Nightly Merge Action 9616508bb5 Merge branch 'master' into maintenance 2021-04-21 00:48:51 +00:00
cp2004 e818c0d8d3 💄 Improve settings dialog animations 2021-04-19 22:40:14 +01:00
Gina Häußge 0a9820acbe Merge pull request #4098 from TwoRedCells/G0-jogging
Use G0 for jogging.
2021-04-19 18:14:12 +02:00
Gina Häußge c1721ee9c4 Merge branch 'master' into maintenance 2021-04-19 17:38:45 +02:00
Yvan Rodrigues 372a6d64ef Use G0 for jogging. 2021-04-16 14:22:14 -04:00
Gina Häußge 17958a460d ✨ Blacklist: support pythonversions & pluginversions
Also deprecate plain versions key.

That way we can now easier define blacklisted version ranges and also
limit blacklisting to specific python versions (on top of OctoPrint and
plugin versions).
2021-04-15 17:31:15 +02:00
Gina Häußge 61ed63d233 Merge branch 'staging/maintenance' into maintenance 2021-04-14 15:35:09 +02:00
Gina Häußge 33c3166e0b Merge pull request #4088 from LazeMSS/bugfix/webcamControlBug 2021-04-13 15:47:17 +02:00
Gina Häußge 4bf87fea39 Merge pull request #4089 from jugmac00/patch-1 2021-04-13 15:46:30 +02:00
GitHub Nightly Merge Action a79bac252b Merge branch 'master' into maintenance 2021-04-13 00:52:56 +00:00
Jürgen Gmach 7c32c44cbd fix typo 2021-04-10 09:30:24 +02:00
LazeMSS 38c0c31ada more lint 2021-04-10 01:08:44 +02:00
LazeMSS 33e1f6cac8 Fixed js lint 2021-04-10 00:38:43 +02:00
LazeMSS d25a9f94b8 Improved error handling and missing check for disable webcam 2021-04-09 23:30:30 +02:00
Gina Häußge 216568d24f 🐛 Fix non deterministic sorting bug
If folders are empty (no upload date) & sorted by upload, Chrome would
produce arbitrary sorting orders. The sorting now falls back on sorting
by name in such cases.

Closes #4073
2021-04-08 13:53:34 +02:00
Gina Häußge bcf57aaeb7 🥅 Protect against invalid analysis & stats
Fixes #4074
2021-04-07 15:32:37 +02:00
Gina Häußge a3c5c75b12 Merge pull request #4075 from cp2004/fix/control-icon-centering
🐛  Fix the centering of icons in the control tab buttons
2021-04-07 12:05:11 +02:00
cp2004 3158a04728 🐛 Fix the centering of icons in the control tab buttons 2021-04-02 17:07:52 +01:00
GitHub Nightly Merge Action e6e1517714 Merge branch 'master' into maintenance 2021-04-01 00:49:44 +00:00
Gina Häußge 6fb72edd38 🔖 maintenance is 1.7.0.dev 2021-03-30 14:25:24 +02:00
Gina Häußge 2b74a7f603 🔖 staging/bugfix is now 1.5.4.dev 2021-01-19 11:42:48 +01:00
153 changed files with 14629 additions and 9019 deletions

No files matched your search

-136
View File
@@ -1,136 +0,0 @@
---
name: 🐛 Report a bug
about: Create a bug report to help improve OctoPrint
---
<!--
READ THE FOLLOWING FIRST:
If not already done, please read the the Contribution Guidelines that
are linked to the right under "Helpful resources" > "Contributing".
Also read the FAQ: https://faq.octoprint.org
This is a bug and feature tracker, please only use it to report bugs
or request features within OctoPrint (not OctoPi, not any OctoPrint
plugins and not unofficial OctoPrint versions).
Do not seek support here ("I need help with ...", "I have a
question ..."), that belongs on the community forum at
community.octoprint.org, NOT here.
Mark requests with a "[Request]" prefix in the title please. For bug
reports fully fill out the bug reporting template (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).
When reporting a bug do NOT delete ANY lines from the template.
Make sure any bug you want to report is still present with the CURRENT
OctoPrint version and that it does not vanish when you start OctoPrint
in safe mode - how to do that is also explained in the Contribution
Guidelines linked up there in the big yellow box.
Thank you!
-->
#### 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.
Ideally provide exact steps to follow in order to reproduce your problem:
-->
1. Go to '...'
2. Click on '....'
3. Scroll down to '....'
4. See error
<!--
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?
#### Did the same happen when running OctoPrint in safe mode?
<!--
Test if you can reproduce your problem in safe mode. You can find information
on how to enable safe mode in the Contribution Guidelines.
If you can't reproduce in safe mode, this is a bug with one of your
installed third party plugins. Don't open a ticket here!
If you can't test this in safe mode, state why.
-->
#### Version of OctoPrint
<!--
Can be found in the lower left corner of the web interface. ALWAYS INCLUDE.
-->
#### Operating System running OctoPrint
<!--
OctoPi, Linux, Windows, MacOS, something else? With version please.
OctoPi's version can be found in /etc/octopi_version or in the lower left
corner of the web interface.
-->
#### 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.
-->
#### Link to octoprint.log
<!--
Directly uploaded here or on gist.github.com or pastebin.com.
ALWAYS INCLUDE and never truncate.
The Contribution Guidelines tell you where to find that.
-->
#### Link to contents of terminal tab or serial.log
<!--
Directly uploaded here or on gist.github.com or pastebin.com.
If applicable, always include if unsure or reporting communication issues.
Never truncate.
serial.log is usually not written due to performance reasons and must be
enabled explicitly. Provide at the very least the FULL contents of your
terminal tab at the time of the bug occurrence, even if you do not have
a serial.log (which the Contribution Guidelines tell you where to find).
-->
#### Link to contents of Javascript console in the browser
<!--
Directly uploaded here or on gist.github.com or pastebin.com.
If applicable - always include if unsure or reporting UI issues.
The Contribution Guidelines tell you where to find that.
-->
#### Screenshot(s)/video(s) showing the problem:
<!--
If applicable. Always include if unsure or reporting UI issues.
-->
I have read the FAQ.
+130
View File
@@ -0,0 +1,130 @@
name: 🐛 Report a bug
description: Create a bug report to help improve OctoPrint
body:
- type: markdown
attributes:
value: >
**Thank you for wanting to report a bug in OctoPrint!**
If this is the first time you are doing this, please take a few moments to read
through the [Contribution Guidelines](https://github.com/OctoPrint/OctoPrint/blob/master/CONTRIBUTING.md).
Also check out [the FAQ](https://faq.octoprint.org) if your
problem is maybe already covered there.
You are about to report a bug in **OctoPrint**. Do not proceed if your issues
occurs with OctoPi, any third party OctoPrint plugins, unofficial or outdated
OctoPrint versions. If you are unsure of the difference between OctoPrint and
OctoPi, [read this FAQ entry](https://faq.octoprint.org/octoprint-vs-octopi).
Do also not seek support here ("I need help with ...", "I have a
question ...", "Can someone walk me through ..."), that belongs into the
[community forum at community.octoprint.org](https://community.octoprint.org) or on the [Discord server](https://discord.octoprint.org).
And finally, make sure any bug you want to report is still present with the **current**
OctoPrint version and that it does not vanish when you start OctoPrint
in [safe mode](https://docs.octoprint.org/en/master/features/safemode.html) either.
Thank you for your collaboration!
- type: textarea
attributes:
label: The problem
description: >-
Describe the issue you are experiencing here. Tell us what you were trying to do
step by step, and what happened that you did not expect.
Provide a clear and concise description of what the problem is and include as many
details as possible.
placeholder: |
1. ...
2. ...
3. ...
validations:
required: true
- type: dropdown
attributes:
label: Did the issue persist even in safe mode?
description: >-
Testing in safe mode is required to make sure the issue you are reporting is not
caused by a third party plugin. Please see [here](https://docs.octoprint.org/en/master/features/safemode.html)
on how to run OctoPrint in safe mode.
options:
- Yes, it did persist
- No, it did not persist (it's an issue with one of your installed plugins, don't report here)
- I cannot test this issue in safe mode (state why below)
validations:
required: true
- type: input
attributes:
label: If you could not test in safe mode, please state why
description: >-
Issues caused by a third party plugin are a major cause of bugs reported here, so we really need to
rule out that a plugin is at fault here. [Safe mode](https://docs.octoprint.org/en/master/features/safemode.html) is an easy way to do that. Only skip safe mode
if your particular problem *absolutely requires* third party plugins to be enabled. "It would take
too long" is **not** a reason to skip testing in safe mode, neither is "I do not know how to
enable it" as you can find info on that [here](https://docs.octoprint.org/en/master/features/safemode.html).
If you really *cannot* test in safe mode, leave a short explanation as to why.
- type: markdown
attributes:
value: |
## Environment
- type: input
attributes:
label: Version of OctoPrint
description: Can be found in the lower left corner of the web interface.
validations:
required: true
- type: input
attributes:
label: Operating system running OctoPrint
description: >-
OctoPi, Linux, Windows, MacOS, something else? With version please? OctoPi's
version can be found in `/etc/octopi_version` or in the lower left corner of the
web interface.
validations:
required: true
- type: input
attributes:
label: Printer model & used firmware incl. version
description: If applicable, always include if unsure
- type: input
attributes:
label: Browser and version of browser, operating system running browser
description: If applicable, always include if unsure
- type: markdown
attributes:
value: |
## Logs and other files needed for analysis
- type: markdown
attributes:
value: >-
Please also be sure to upload the following files below:
* Systeminfo Bundle: See [here](https://community.octoprint.org/t/what-is-a-systeminfo-bundle-and-how-can-i-obtain-one/29887) if you don't know where to find that. Just attach down below as-is. Note that you'll need at least OctoPrint 1.6.0 for this to be available - we no longer accept bug reports created for older versions than this.
* If you are reporting an issue that involves communicating with you printer, **be sure to enable `serial.log` before reproducing and creating the Systeminfo Bundle**!
* Your browser's JavaScript console, if you are reporting a problem with the
user interface. See [here](https://webmasters.stackexchange.com/questions/8525/how-to-open-the-javascript-console-in-different-browsers) on where to find that.
* If possible, screenshots or videos showing the problem, especially if you
are reporting a problem with the user interface!
* GCODE files with which to reproduce, if you are reporting an issue with
GCODE file analysis or printing behaviour.
Please be aware that unless at least Systeminfo Bundle is included, your bug report
will not be processed and closed after a while.
- type: checkboxes
attributes:
label: Checklist of files to include below
options:
- label: Systeminfo Bundle (always include!)
required: true
- label: Contents of the JavaScript browser console (always include in cases of issues with the user interface)
- label: Screenshots and/or videos showing the problem (always include in case of issues with the user interface)
- label: GCODE file with which to reproduce (always include in case of issues with GCODE analysis or printing behaviour)
- type: textarea
attributes:
label: Additional information & file uploads
+1
View File
@@ -1,5 +1,6 @@
approve_label: "approved"
problem_label: "needs some work"
ignore_label: "skip validation"
allowed_targets: ["maintenance", "devel", "staging/maintenance", "staging/devel"]
forbidden_sources:
+19 -1
View File
@@ -95,7 +95,7 @@ jobs:
test-e2e:
name: 🧪 E2E tests
needs: build
runs-on: ubuntu-16.04
runs-on: ubuntu-latest
steps:
- name: ⬇ Checkout code
uses: actions/checkout@v2
@@ -176,3 +176,21 @@ jobs:
uses: pypa/gh-action-pypi-publish@master
with:
password: ${{ secrets.pypi_password }}
notify-custopizer-build:
name: 📧 Notify OctoPi-UpToDate
if: github.event_name == 'release'
needs: publish-on-pypi
runs-on: ubuntu-latest
steps:
- name: 👀 Determine version
run: |
OCTOPRINT_VERSION=$(echo $GITHUB_REF | cut -d/ -f3)
echo "OCTOPRINT_VERSION=$OCTOPRINT_VERSION" >> $GITHUB_ENV
- name: 🚀 Repository Dispatch
uses: peter-evans/repository-dispatch@v1
with:
token: ${{ secrets.REPODISPATCH_TOKEN }}
repository: OctoPrint/OctoPi-UpToDate
event-type: octoprint_release
client-payload: '{"version": "${{ env.OCTOPRINT_VERSION }}"}'
+95 -8
View File
@@ -1,19 +1,18 @@
name: "Issue Automation"
on:
issues:
types: [opened, edited, closed, reopened]
types: [opened, edited, closed, reopened, labeled, unlabeled]
jobs:
issue-automation:
runs-on: ubuntu-latest
steps:
- uses: actions/github-script@v2
- uses: actions/github-script@v5
with:
github-token: ${{ secrets.GITHUB_TOKEN }}
script: |
let labels = [];
let labels = context.payload.issue.labels.map(label => label.name);
let setLabels = false;
context.payload.issue.labels.forEach(label => { labels.push(label.name) });
switch (context.payload.action) {
@@ -55,7 +54,7 @@ jobs:
}
if (setLabels) {
github.issues.setLabels({
github.rest.issues.setLabels({
issue_number: context.issue.number,
owner: context.repo.owner,
repo: context.repo.repo,
@@ -63,7 +62,95 @@ jobs:
})
}
- uses: OctoPrint/actions/issue-validation@main
if: github.event_name == 'issues' && (github.event.action == 'opened' || github.event.action == 'edited')
#- uses: OctoPrint/actions/issue-validation@main
# if: github.event_name == 'issues' && (github.event.action == 'opened' || github.event.action == 'edited')
# with:
# repo-token: ${{ secrets.GITHUB_TOKEN }}
- uses: actions/github-script@v5
env:
REMINDER: >
Hi @${{ github.event.issue.user.login }}!
It looks like you didn't upload a [system info bundle](https://community.octoprint.org/t/29887) as requested by the template.
A bundle is required to further process your issue. It contains important logs and
system information to be able to put your issue into context and give pointers as to
what has happened.
Please **edit your original post above** and upload **a bundle zip file**. Actually upload the file please and
do not paste some link to a cloud provider, we want to have everything in one place here. Also do
not unpack, repack or otherwise modify the bundle or its name, share it **exactly** like you get it from OctoPrint.
Without the availability of a bundle, your issue will have to be closed.
Thank you for your collaboration.
THANKYOU: >
Thank you @${{ github.event.issue.user.login }} for adding a bundle! Now this can actually get looked at.
with:
repo-token: ${{ secrets.GITHUB_TOKEN }}
script: |
const { REMINDER, THANKYOU } = process.env;
const bundleRegex = /\[(octoprint-systeminfo-\d{14}\.zip)\]\(([^)]+)\)/g;
const marker = "<!-- check_for_bundle -->";
const issueLabels = await github.rest.issues.listLabelsOnIssue({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: context.issue.number
});
let labels = issueLabels.data.map(label => label.name);
const comments = await github.rest.issues.listComments({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: context.issue.number,
})
const comment = comments.data.find(c => c.user.login === "github-actions[bot]" && c.body.includes(marker));
if (!labels.includes("triage")) {
console.log("No label, deleting comment if needed");
if (comment) {
await github.rest.issues.deleteComment({
owner: context.repo.owner,
repo: context.repo.repo,
comment_id: comment.id,
})
}
return;
}
const found = !!context.payload.issue.body.match(bundleRegex);
if (!found) {
console.log("No bundle found, posting/updating reminder");
const text = REMINDER + "\n" + marker;
if (comment && comment.body !== text) {
await github.rest.issues.updateComment({
owner: context.repo.owner,
repo: context.repo.repo,
comment_id: comment.id,
body: text
});
} else {
await github.rest.issues.createComment({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: context.issue.number,
body: text
});
}
} else if (found && comment) {
console.log("Bundle found, saying thanks");
const text = REMINDER.split("\n\n").map(line => `~~${line.trim()}~~`).join("\n\n") + "\n\n" + THANKYOU + "\n" + marker;
if (comment.body !== text) {
await github.rest.issues.updateComment({
owner: context.repo.owner,
repo: context.repo.repo,
comment_id: comment.id,
body: text
});
}
}
+30 -1
View File
@@ -1,7 +1,8 @@
name: "Pull Request Automation"
on:
pull_request_target:
types: ["opened", "synchronize", "reopened", "edited", "labeled", "unlabeled"]
#types: ["opened", "synchronize", "reopened", "edited", "labeled", "unlabeled"]
types: ["opened"]
jobs:
pr-automation:
@@ -11,6 +12,34 @@ jobs:
with:
repo-token: "${{ secrets.GITHUB_TOKEN }}"
- uses: actions/github-script@v5
with:
github-token: ${{ secrets.GITHUB_TOKEN }}
script: |
// fetch a fresh set of labels, they might have changed earlier
const issueLabels = await github.rest.issues.listLabelsOnIssue({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: context.issue.number
});
let labels = issueLabels.data.map(label => label.name);
let setLabels = false;
let target = context.payload.pull_request.base.ref;
if (["maintenance", "devel", "staging/maintenance", "staging/devel", "master"].includes(target)) {
labels.push(`targets ${target}`);
setLabels = true;
}
if (setLabels) {
github.rest.issues.setLabels({
issue_number: context.issue.number,
owner: context.repo.owner,
repo: context.repo.repo,
labels: labels
})
}
- uses: OctoPrint/actions/pr-validation@main
with:
repo-token: ${{ secrets.GITHUB_TOKEN }}
+1 -1
View File
@@ -14,7 +14,7 @@ jobs:
- name: 🚀 Repository Dispatch
uses: peter-evans/repository-dispatch@v1
with:
token: ${{ secrets.DOCS_ACCESS_TOKEN }}
token: ${{ secrets.REPODISPATCH_TOKEN }}
repository: OctoPrint/docs.octoprint.org
event-type: docs
client-payload: '{"ref": "${{ github.ref }}", "sha": "${{ github.sha }}"}'
+10 -10
View File
@@ -18,21 +18,21 @@ prerelease
HEAD
\(detached.*
# maintenance is currently the branch for preparation of maintenance release 1.6.0
# maintenance is currently the branch for preparation of maintenance release 1.7.0
# so are any fix/... and improve/... branches
maintenance 1.6.0 b7a45b79bf86339f0b28177ac1eaebb56d00ea37 pep440-dev
fix/.* 1.6.0 b7a45b79bf86339f0b28177ac1eaebb56d00ea37 pep440-dev
improve/.* 1.6.0 b7a45b79bf86339f0b28177ac1eaebb56d00ea37 pep440-dev
maintenance 1.7.0 07c4630d126617c2ae98a9c23ad49facf7bf0bbd pep440-dev
fix/.* 1.7.0 07c4630d126617c2ae98a9c23ad49facf7bf0bbd pep440-dev
improve/.* 1.7.0 07c4630d126617c2ae98a9c23ad49facf7bf0bbd pep440-dev
# staging/bugfix is the branch for preparation of the 1.5.3 hotfix release
# staging/bugfix is the branch for preparation of the 1.7.2 bugfix release
# so are any bug/... branches
staging/bugfix 1.5.3 e46e8fa17a1553cd0c228a4fa4cfd93e2a9bce7b pep440-dev
bug/.* 1.5.3 e46e8fa17a1553cd0c228a4fa4cfd93e2a9bce7b pep440-dev
staging/bugfix 1.7.2 945825f03fbd2417a009dd33daf9f787aff60211 pep440-dev
bug/.* 1.7.2 945825f03fbd2417a009dd33daf9f787aff60211 pep440-dev
# staging/maintenance is currently the branch for preparation of 1.6.0rc4
# staging/maintenance is currently the branch for preparation of 1.7.0rc4
# so is regressionfix/...
staging/maintenance 1.6.0rc4 7054a726bb3dc363a98ec6944b24e07879bb389b pep440-dev
regressionfix/.* 1.6.0rc4 7054a726bb3dc363a98ec6944b24e07879bb389b pep440-dev
staging/maintenance 1.7.0rc4 f31194f75365787f3eb5da61a24f2f8620111f4f pep440-dev
regressionfix/.* 1.7.0rc4 f31194f75365787f3eb5da61a24f2f8620111f4f pep440-dev
# staging/devel is currently inactive (but has the 1.4.1rc4 namespace)
staging/devel 1.4.1rc4 650d54d1885409fa1d411eb54b9e8c7ff428910f pep440-dev
+9
View File
@@ -141,6 +141,15 @@ date of first contribution):
* [Joe Martella](https://github.com/martellaj)
* [Scott Lahteine](https://github.com/thinkyhead)
* [Karthikeyan Singaravelan](https://github.com/tirkarthi)
* [Yvan Rodrigues](https://github.com/TwoRedCells)
* [Elton Law](https://github.com/eltonlaw)
* ["sparxooo"](https://github.com/sparxooo)
* ["Stevil Knevil"](https://github.com/StevilKnevil)
* [ldursw](https://github.com/ldursw)
* [Ian Wilt](https://github.com/ianwiltdotcom)
* [Ben Sycha](https://github.com/Sycha)
* [Bryan Kenote](https://github.com/bryankenote)
* [Quinn Damerell](https://github.com/QuinnDamerell)
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
+131 -5
View File
@@ -31,7 +31,7 @@ nothing but ticket management.
- **[Read the FAQ](https://faq.octoprint.org)**
- If you want to report a **bug**, [read "How to file a bug report" below](#how-to-file-a-bug-report)
and *[use the provided form](https://github.com/OctoPrint/OctoPrint/issues/new?template=bug_report.yml)*.
and *[use the provided template](#what-should-i-include-in-a-ticket)*.
You do not need to do anything else with your ticket.
- If you want to post a **feature request** or a **documentation request**, add `[Request]`
to your issue's title (e.g. `[Request] Awesome new feature`). A question on how to run/change/setup
@@ -48,6 +48,15 @@ nothing but ticket management.
No matter what kind of ticket you create, never mix two or more "ticket reasons"
into one ticket: One ticket per bug, request, brainstorming thread please.
> 👉 **Note**
>
> A bot is in place that monitors new tickets, automatically
> categorizes them and checks new bug reports for usage of the provided template.
> That bot will only bother you if you open a ticket that appears to be a bug (no
> `[Request]` in the title) without the complete template, and it
> will do that only to ensure that all information needed to solve the issue is
> available for the maintainers to directly start tackling that problem.
## How to file a bug report
If you encounter an issue with OctoPrint, you are welcome to
@@ -109,7 +118,7 @@ following section *completely* and also follow the instructions in the
it is the same as your's, it actually behaves the same as your's. E.g. if someone gives steps
to reproduce his bug that looks like your's, reproduce the bug like that if possible,
and only add a "me too" if you actually can reproduce the same
issue. Also **provide all information like logs, versions, different reproduction steps**
issue. Also **provide all information like Systeminfo Bundle, additional logs & versions, different reproduction steps**
and whatever was additionally requested over the course of the ticket
even if you "only" add to an existing ticket. The more information available regarding a bug, the higher
the chances of reproducing and solving it. But "me too" on an actually unrelated ticket
@@ -126,12 +135,128 @@ there.
First of all make sure your use **a descriptive title**. "It doesn't work"
and similar unspecific complaints are NOT descriptive titles.
Always fill out the [reporting form](https://github.com/OctoPrint/OctoPrint/issues/new?template=bug_report.yml) **completely** and include as much
information as possible.
**Always use the following template, even if only adding a "me too" to an
existing ticket**:
```
<!--
READ THE FOLLOWING FIRST:
If not already done, please read the the Contribution Guidelines that
are linked to the right under "Helpful resources" > "Contributing".
Also read the FAQ: https://faq.octoprint.org
This is a bug and feature tracker, please only use it to report bugs
or request features within OctoPrint (not OctoPi, not any OctoPrint
plugins and not unofficial OctoPrint versions).
Do not seek support here ("I need help with ...", "I have a
question ..."), that belongs on the community forum at
community.octoprint.org, NOT here.
Mark requests with a "[Request]" prefix in the title please. For bug
reports fully fill out the bug reporting template (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).
When reporting a bug do NOT delete ANY lines from the template.
Make sure any bug you want to report is still present with the CURRENT
OctoPrint version and that it does not vanish when you start OctoPrint
in safe mode - how to do that is also explained in the Contribution
Guidelines linked up there in the big yellow box.
Thank you!
-->
#### 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.
Ideally provide exact steps to follow in order to reproduce your problem:
-->
1. Go to '...'
2. Click on '....'
3. Scroll down to '....'
4. See error
<!--
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?
#### Did the same happen when running OctoPrint in safe mode?
<!--
Test if you can reproduce your problem in safe mode. You can find information
on how to enable safe mode in the Contribution Guidelines.
If you can't reproduce in safe mode, this is a bug with one of your
installed third party plugins. Don't open a ticket here!
If you can't test this in safe mode, state why.
-->
#### Version of OctoPrint
<!--
Can be found in the lower left corner of the web interface. ALWAYS INCLUDE.
-->
#### 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.
-->
#### System Info Bundle
<!--
Directly uploaded here. ALWAYS INCLUDE.
The Contribution Guidelines tell you where to find that.
-->
#### Link to contents of Javascript console in the browser
<!--
Directly uploaded here or on gist.github.com or pastebin.com.
If applicable - always include if unsure or reporting UI issues.
The Contribution Guidelines tell you where to find that.
-->
#### Screenshot(s)/video(s) showing the problem:
<!--
If applicable. Always include if unsure or reporting UI issues.
-->
I have read the FAQ.
```
Provide the same kind and amount of information also when you are just adding on to an
existing ticket!
### Where can I find the System Info Bundle?
Please refer to [this FAQ entry](https://community.octoprint.org/t/what-is-a-systeminfo-bundle-and-how-can-i-obtain-one/29887).
### Where can I find which version and branch I'm on?
Please refer to [this FAQ entry](https://community.octoprint.org/t/how-can-i-find-out-the-version-of-octoprint-or-octopi-i-am-running/204/1).
@@ -287,7 +412,8 @@ See [the corresponding chapter in the documentation](https://docs.octoprint.org/
* 2020-09-23: Move branch & versioning into development docs
* 2020-10-07: Introduce `pre-commit`
* 2021-02-04: Issue forms! \o/
* 2020-03-04: Correct issue forms link
* 2021-03-04: Correct issue forms link
* 2021-04-27: Systeminfo Bundles! \o/
## Footnotes
* [1] - If you are wondering why, the problem is that anything that you add
+13 -13
View File
@@ -9,66 +9,66 @@ thanks to everyone who contributed!
* 3D-TECH
* 3DPrinterOS
* Arnljot Arntsen
* Artillery 3D
* Ash King
* Ashley Merrick
* BigTreeTech
* Boris Hussein
* Brad Jackson
* BRANDON ROBERTSON
* BuildBee
* Chris Lynch
* Christian Petropolis
* Christian Wolf
* Christian Würthner
* Christoph Sigrist
* Creality3D
* D Brian Kimmel
* Dana Voigt
* David Bounds
* DeltaMaker 3D Printers
* Dennis Breining
* Dennis Christilaw
* Diana C Rodriguez
* Douglas Floyd
* Dr. Frank Wester
* Eric Betts
* Ernesto Martinez
* Franziska Kunsmann
* George Robles
* Greg Holloway
* Hog Duske
* Hopewell Medical Acupuncture Center
* Itay Shem-tov
* Jeff Moe
* Jeremy Cole
* Joshua Wills
* Julian Melo
* Justin Kaufman
* Kaile Riser
* Kale Stedman
* Kazuhiro Ogura
* Kelly C McNiece
* Kenneth Jiang
* Kurt Wubbels
* Kyle Menigoz
* LA 3D Printer Repair
* Lachlan Bell
* Lee Dohm
* Lefteris Lertas
* LulzBot
* Makespace Madrid
* Mark Walker
* Michael Aumock
* Mike Kershaw
* Miles Flavel
* Mosaic Manufacturing
* Nat Friedman
* Neil R. Goldberg
* Norman Jaffe
* Ory Weaver
* Patrick Glyré
* Peopoly
* Pete Barnwell
* Prof Yuh Wen Chen
* Raise3D
* Randy C. Will
* Ranjib Dey
* Richard McGuire
* Richard Michaud
* Richard Stocks
* Rigid3D
* Robert Gusek
* Ronald Griehsler
* Sacha Telgenhof
* Sebastien Andrivet
* Stefan Krister
* Steve Thompson
@@ -78,4 +78,4 @@ thanks to everyone who contributed!
* Ulderico Cirello
* Ulrich Kempken
and 2341 more wonderful people pledging on the [Patreon campaign](https://patreon.com/foosel) or via [GitHub Sponsors](https://github.com/users/foosel/sponsorship)!
and 2247 more wonderful people pledging on the [Patreon campaign](https://patreon.com/foosel) or via [GitHub Sponsors](https://github.com/users/foosel/sponsorship)!
+2 -1
View File
@@ -31,9 +31,9 @@
* [Moment.js](http://momentjs.com/): MIT
* [PNotify](http://sciactive.com/pnotify/): GPL, LGPL, MPL (triple licensed)
* [pusher.color.js](http://cache.preserve.io/5g18q0pw/index.html) (original link dead): MIT
* [ResizeSensor.js](https://github.com/procurios/ResizeSensor): MIT
* [SockJS](https://github.com/sockjs/sockjs-client): MIT
* [sprintf-js](http://alexei.ro/): BSD
* [UAParser.js](https://faisalman.github.io/ua-parser-js/): MIT
## Server
@@ -56,6 +56,7 @@
* [monotonic](https://github.com/atdt/monotonic): Apache License 2.0
* [netaddr](https://github.com/drkjam/netaddr/): BSD
* [netifaces](https://bitbucket.org/al45tair/netifaces): MIT
* [pathvalidate](https://pathvalidate.readthedocs.io/en/latest/index.html): MIT
* [pkginfo](http://pypi.python.org/pypi/pkginfo/): Python
* [psutil](https://github.com/giampaolo/psutil): BSD
* [pylru](https://github.com/jlhutch/pylru): GPLv2
+2 -2
View File
@@ -81,7 +81,7 @@ Retrieve a group
Retrieves an individual group record.
Will return a :http:statuscode:`200` with a :ref:`group record <sec-api-access-datamodel-groups-grouprecord>`
Will return a :http:statuscode:`200` with a :ref:`group record <sec-api-access-datamodel-groups-list>`
as body.
Requires the ``SETTINGS`` permission.
@@ -156,7 +156,7 @@ Retrieve a user
Retrieves information about a user.
Will return a :http:statuscode:`200` with a :ref:`user record <sec-api-access-datamodel-users-userrecord>`
Will return a :http:statuscode:`200` with a :ref:`user record <sec-api-datamodel-access>`
as body.
Requires either the ``SETTINGS`` permission or to be logged in as the user.
+70 -6
View File
@@ -195,11 +195,11 @@ Job information
- The file that is the target of the current print job
* - ``estimatedPrintTime``
- 0..1
- Integer
- Float
- The estimated print time for the file, in seconds.
* - ``lastPrintTime``
- 0..1
- Integer
- Float
- The print time of the last print of the file, in seconds.
* - ``filament``
- 0..1
@@ -207,7 +207,7 @@ Job information
- Information regarding the estimated filament usage of the print job
* - ``filament.length``
- 0..1
- Integer
- Float
- Length of filament used, in mm
* - ``filament.volume``
- 0..1
@@ -365,6 +365,14 @@ Files
- 0..1
- :ref:`GCODE analysis information <sec-api-datamodel-files-gcodeanalysis>`
- Information from the analysis of the GCODE file, if available. Left out in abridged version.
* - ``prints``
- 0..1
- :ref:`Print history information <sec-api-datamodel-files-prints>`
- Information about previous prints of the file. Left out if the file has never been printed.
* - ``statistics``
- 0..1
- :ref:`Print statistics information <sec-api-datamodel-files-stats>`
- Statistics about the file, based on the previous print times. Left out if the file has never been printed.
.. _sec-api-datamodel-files-fileabridged:
@@ -419,7 +427,7 @@ GCODE analysis information
- Description
* - ``estimatedPrintTime``
- 0..1
- Integer
- Float
- The estimated print time of the file, in seconds
* - ``filament``
- 0..1
@@ -427,7 +435,7 @@ GCODE analysis information
- The estimated usage of filament
* - ``filament.tool{n}.length``
- 0..1
- Integer
- Float
- The length of filament used, in mm
* - ``filament.tool{n}.volume``
- 0..1
@@ -506,6 +514,62 @@ References
- The model from which this file was generated (e.g. an STL, currently not used). Never present for
folders.
.. _sec-api-datamodel-files-prints:
Print History
-------------
.. list-table::
:widths: 15 5 10 30
:header-rows: 1
* - Name
- Multiplicity
- Type
- Description
* - ``success``
- 1
- Number
- Number of successful prints
* - ``failure``
- 1
- Number
- Number of failed prints
* - ``last.date``
- 1
- Unix Timestamp
- Last date this file was printed
* - ``last.printTime``
- 1
- Float
- Last print time in seconds
* - ``last.success``
- 1
- Boolean
- Whether the last print was a success or not
.. _sec-api-datamodel-files-stats:
Print Statistics
----------------
.. list-table::
:widths: 15 5 10 30
:header-rows: 1
* - Name
- Multiplicity
- Type
- Description
* - ``averagePrintTime``
- 1
- Object
- Object that maps printer profile names to the last print time of the file, in seconds
* - ``lastPrintTime``
- 1
- Object
- Object that maps printer profile names to the average print time of the file, in seconds
.. _sec-api-datamodel-access:
Access control
@@ -596,7 +660,7 @@ Permission record
- Human readable description of the permission
* - ``needs``
- 1
- :ref:`Needs object <sec-api-access-datamodel-general-needs>`
- :ref:`Needs object <sec-api-datamodel-access-needs>`
- Needs assigned to the permission
.. _sec-api-datamodel-access-groups:
+14 -1
View File
@@ -15,7 +15,9 @@ Retrieve all files
Retrieve information regarding all files currently available and regarding the disk space still available
locally in the system. The results are cached for performance reasons. If you
want to override the cache, supply the query parameter ``force`` and set it to ``true``.
want to override the cache, supply the query parameter ``force`` and set it to ``true``. Note that
while printing a refresh/override of the cache for files stored on the printer's SD card
is disabled due to bandwidth restrictions on the serial interface.
By default only returns the files and folders in the root directory. If the query parameter ``recursive``
is provided and set to ``true``, returns all files and folders.
@@ -249,6 +251,8 @@ Retrieve files from specific location
Retrieve information regarding the files currently available on the selected `location` and -- if targeting
the ``local`` location -- regarding the disk space still available locally in the system. The results are cached for performance reasons. If you
want to override the cache, supply the query parameter ``force`` and set it to ``true``.
Note that while printing a refresh/override of the cache for files stored on the printer's SD card
is disabled due to bandwidth restrictions on the serial interface.
By default only returns the files and folders in the root directory. If the query parameter ``recursive``
is provided and set to ``true``, returns all files and folders.
@@ -585,6 +589,15 @@ Issue a file command
Requires the ``FILES_SELECT`` permission.
unselect
Unselects the currently selected file for printing.
Upon success, a status code of :http:statuscode:`204` and an empty body is returned. If no file is selected
or there already is an active print job, a :http:statuscode:`409` is returned. If path isn't ``current```
or the filename of the current selection, a :http:statuscode:`400` is returned
Requires the ``FILES_SELECT`` permission.
slice
Slices an STL file into GCODE. Note that this is an asynchronous operation that will take place in the background
after the response has been sent back to the client. Additional parameters are:
+18 -3
View File
@@ -44,8 +44,7 @@ For testing purposes it is also possible to supply the API key via a query param
Please be advised that clients should use the header field variant if at all possible.
If the key is missing or invalid, OctoPrint will treat the request as it would any unauthenticated anonymous request to the endpoint.
Consequently, if the bundled :ref:`ForceLogin plugin <sec-bundledplugins-forcelogin>` is active (which is the default), that means
that any requests without or with an invalid API key targeting other API endpoints than :ref:`Login <sec-api-general-login>`
That means that any requests without or with an invalid API key targeting other API endpoints than :ref:`Login <sec-api-general-login>`
will be denied with a :http:statuscode:`403`.
.. warning::
@@ -134,7 +133,8 @@ check the corresponding checkbox in the API settings dialog.
Support for CORS can be enabled in the "API" settings
.. note::
.. warning::
This means any browser page can send requests to the OctoPrint API. Authorization is still required however.
If CORS is not enabled you will get errors like the following::
@@ -142,6 +142,15 @@ If CORS is not enabled you will get errors like the following::
XMLHttpRequest cannot load http://localhost:8081/api/files. No 'Access-Control-Allow-Origin'
header is present on the requested resource.
.. note::
For security reasons, OctoPrint will not set the ``Access-Control-Allow-Credentials``
header, even if CORS support is enabled. That means that cookies will not be sent by
the browser to OctoPrint, effectively making it impossible to authenticate through
the login mechanism (or reusing an existing login session). When accessing OctoPrint
via CORS, you'll therefore always need to use an API key.
.. _sec-api-general-login:
Login
@@ -165,6 +174,12 @@ Login
mismatch or an unknown user. That was incompatible with basic authentication since it was a wrong use of
the :http:statuscode:`401` code and got therefore changed as part of a bug fix.
.. note::
You cannot use this endpoint to login from a third party page via CORS, see above. You can however use it
to retrieve user information via passive login with an API key (e.g. if you need the ``session`` to authenticate
on the web socket.
:json passive: If present, performs a passive login only, returning information about the current user that's
active either through an existing session or the used API key
:json user: (active login only) Username
+8 -8
View File
@@ -17,9 +17,9 @@ Retrieve all printer profiles
.. http:get:: /api/printerprofiles
Retrieves a list of all configured printer profiles.
Retrieves an object representing all configured printer profiles.
Returns a :http:statuscode:`200` with a list of :ref:`profiles <sec-api-printerprofiles-datamodel-profile>`.
Returns a :http:statuscode:`200` with a :ref:`profile list <sec-api-printerprofiles-datamodel-profilelist>`.
Requires the ``CONNECTION`` permission.
@@ -37,8 +37,8 @@ Retrieve all printer profiles
Content-Type: application/json
{
"profiles": [
{
"profiles": {
"_default": {
"id": "_default",
"name": "Default",
"color": "default",
@@ -80,7 +80,7 @@ Retrieve all printer profiles
]
}
},
{
"my_profile": {
"id": "my_profile",
"name": "My Profile",
"color": "default",
@@ -122,7 +122,7 @@ Retrieve all printer profiles
]
}
},
]
}
}
@@ -457,7 +457,7 @@ Profile list
- Collection of all printer profiles available in the system
* - ``profiles.<profile id>``
- 0..1
- :ref:`Profile <sec-api-slicing-datamodel-profile>`
- :ref:`Profile <sec-api-printerprofiles-datamodel-profile>`
- Information about a profile stored in the system.
.. _sec-api-printerprofiles-datamodel-update:
@@ -475,7 +475,7 @@ Add or update request
- Description
* - ``profiles``
- 1
- :ref:`Profile <sec-api-slicing-datamodel-profile>`
- :ref:`Profile <sec-api-printerprofiles-datamodel-profile>`
- Information about the profile being added/updated. Only the values to be overwritten need to be supplied.
Unset fields will be taken from the base profile, which for add requests will be the
current default profile unless a different base is defined in the ``basedOn`` property
+4
View File
@@ -226,6 +226,10 @@ For timelapse type ``zchange``.
- 1
- float
- Size of retraction Z hop to detect and ignore for z-based snapshots
* - ``minDelay``
- 1
- int
- Snapshots will be rate limited against this interval, to prevent performance issues with vase mode/continuous z prints
.. _sec-api-timelapse-datamodel-config-timed:
+1 -1
View File
@@ -8,7 +8,7 @@ Version information
Retrieve information regarding server and API version. Returns a JSON object with three keys, ``api`` containing
the API version, ``server`` containing the server version, ``text`` containing the server version including
the prefix ``OctoPrint `` (to determine that this is indeed a genuine OctoPrint instance).
the prefix ``OctoPrint`` (to determine that this is indeed a genuine OctoPrint instance).
**Example Request**
@@ -39,13 +39,11 @@ Supported action commands
notification <message>
Displays the notification ``<message>``
.. _sec-bundledplugins-action_command_prompt-example:
.. _sec-bundledplugins-action_command_notification-example:
Example communication with the firmware
---------------------------------------
.. _sec-bundledplugins-action_command_prompt-sourcecode:
To display the :ref:`above notification <fig-bundledplugins-action_command_notification-example>` the firmware sent this action command:
.. code-block:: none
+2 -4
View File
@@ -118,8 +118,7 @@ Announced Services
ZeroConf Service ``_http._tcp``
+++++++++++++++++++++++++++++++
If :ref:`pybonjour <sec-bundledplugins-discovery-firststeps-pybonjour>` is
correctly installed, OctoPrint will announce itself on the network via ZeroConf
OctoPrint will announce itself on the network via ZeroConf
as service ``_http._tcp``, with the TXT record containing the standard fields.
See also `this documentation of _http._tcp TXT records <http://www.dns-sd.org/txtrecords.html>`_
@@ -130,8 +129,7 @@ for more information.
ZeroConf Service ``_octoprint._tcp``
++++++++++++++++++++++++++++++++++++
If :ref:`pybonjour <sec-bundledplugins-discovery-firststeps-pybonjour>` is
correctly installed, OctoPrint will announce itself on the network via ZeroConf
OctoPrint will announce itself on the network via ZeroConf
as service ``_octoprint._tcp``. The TXT record may contain the following fields:
* ``path``: path prefix to actual OctoPrint instance, inherited from ``_http._tcp``
-1
View File
@@ -20,6 +20,5 @@ Bundled Plugins
gcodeviewer.rst
logging.rst
pluginmanager.rst
printer_safety_check.rst
softwareupdate.rst
virtual_printer.rst
+5
View File
@@ -197,20 +197,24 @@ types are currently recognized:
* ``prerelease``: ``True`` or ``False``, default ``False``, set to
``True`` to also include releases on Github marked as prerelease.
* ``prerelease_branches``: Prerelease channel definitions, optional. List of:
* ``branch``: Branch associated with the channel, acts as ID
* ``name``: Human readable name of the release channel
* ``commitish``: List of values to check against ``target_commitish``
field in Github release data - release will only be included if the
values match. Defaults to being unset, in which case the ``branch``
will be matched.
.. versionadded:: 1.2.16
* ``stable_branch``: Stable channel definition, optional. Structure:
* ``branch``: Branch associated with the channel, acts as ID
* ``name``: Human readable name of the release channel
* ``commitish``: List of values to check against ``target_commitish``
field in Github release data - release will only be included if the
values match. Defaults to being unset, in which case the ``branch``
will be matched.
.. versionadded:: 1.2.16
* ``prerelease_channel``: Release channel to limit updates to. If set only
those releases will be included if their ``target_commitish`` matches
@@ -218,6 +222,7 @@ types are currently recognized:
included in ``prerelease_channels`` or the ``stable_channel``. Only
taken into account if ``prerelease`` is ``true``.
.. versionadded:: 1.2.16
* ``release_compare``: Method to use to compare between current version
information and release versions on Github. One of ``python`` (version
comparison using ``pkg_resources.parse_version``, newer version detected
+1 -1
View File
@@ -35,7 +35,7 @@ The plugin supports the following configuration keys:
* ``plugin``: Whether to track plugin related events (install, uninstall, ...)
* ``update``: Whether to track update related events (update successful or not, ...)
* ``printer``: Whether to track printer related events (connected, firmware, ...)
* ``printer_safety_check``: Whether to track warnings of the :ref:`Printer Safety Check <sec-bundledplugins-printer_safety_check>`
* ``printer_safety_check``: Whether to track warnings of the Printer Safety Check plugin
* ``throttled``: Whether to track throttle events detected on the underlying system
.. _sec-bundledplugins-tracking-sourcecode:
+8 -3
View File
@@ -708,6 +708,11 @@ Use the following settings to configure the serial connection to the printer:
- M0
- M1
# Commands which should not be sent to the printer and just silently ignored.
# An example of when you may wish to use this could be useful if you wish to manually change a filament on M600,
# by using that as a Pausing command (below)
ignoredCommands:
# Commands which should cause OctoPrint to pause any ongoing prints.
pausingCommands:
- M0
@@ -904,9 +909,9 @@ Use the following settings to configure the server:
# Settings for further configuration of the cookies that OctoPrint sets (login, remember me, ...)
cookies:
# SameSite setting to use on the cookies. Possible values are None, Lax and Strict. Defaults to None but
# be advised that browsers will soon force this to Lax unless also being set as Secure and served over
# https, which will cause issues with embedding OctoPrint in frames.
# SameSite setting to use on the cookies. Possible values are None, Lax and Strict. Defaults to not set but
# be advised that many browsers now default to Lax unless set as Secure, explicitly setting the cookie type
# here and served over https, which causes issues with embedding OctoPrint in frames.
#
# See also https://www.chromestatus.com/feature/5088147346030592,
# https://www.chromestatus.com/feature/5633521622188032 and issue #3482
+195 -48
View File
@@ -15,7 +15,6 @@ below.
* Prerequisites:
* `Python 3.7 <https://python.org>`_ including ``pip``, ``setuptools`` and ``virtualenv``
* `Python 2.7 <https://python.org>`_ including ``pip``, ``setuptools`` and ``virtualenv``
* `Git <https://git-scm.com>`_
* Checkout the OctoPrint sources from their Git repository:
@@ -23,24 +22,17 @@ below.
* ``git clone https://github.com/OctoPrint/OctoPrint.git``
* Enter the checked out source folder: ``cd OctoPrint``
* Create virtual environments in the checked out source folder for both Python 2 and Python 3 to use for
* Create a virtual environment in the checked out source folder to use for
installing and running OctoPrint and its dependencies. Creating virtual environments avoids potential versioning
issues for the dependencies with system wide installed instances:
* PY3: ``virtualenv --python=python3 venv3``
* PY2: ``virtualenv --python=python2 venv2``
issues for the dependencies with system wide installed instances: ``virtualenv --python=python3 venv3``
.. note::
This assumes that `python2` and `python3` are binaries available directly on your ``PATH``. If your Python 2 and 3
binaries cannot be found on your ``PATH`` like this you'll need to specify the full paths to them here,
e.g. ``virtualenv --python=/path/to/python2/bin/python venv2``
This assumes that the ``python3`` binary is available directly on your ``PATH``. If
it cannot be found on your ``PATH`` like this you'll need to specify the full path here,
e.g. ``virtualenv --python=/path/to/python3/bin/python venv3``
* Activate one of the virtual environments (the Python 3 venv should be considered the
primary one at this point):
* PY3: ``source venv3/bin/activate`` (Linux, macOS) or ``source venv3/Scripts/activate`` (Git Bash under Windows, see below)
* PY2: ``source venv2/bin/activate`` (Linux, macOS) or ``source venv2/Scripts/activate`` (Git Bash under Windows, see below)
* Activate the virtual environment: ``source venv3/bin/activate`` (Linux, macOS) or ``source venv3/Scripts/activate`` (Git Bash under Windows, see below)
* Update ``pip`` in the virtual environment:
@@ -49,7 +41,7 @@ below.
* Install OctoPrint in `"editable" mode <https://pip.pypa.io/en/stable/reference/pip_install/#editable-installs>`_,
including its regular *and* development and plugin development dependencies:
* ``pip install -e '.[develop,plugins]'``
* ``pip install -e '.[develop,plugins,docs]'``
* Set up the pre-commit hooks that make sure any changes you do adhere to the styling rules:
@@ -65,22 +57,34 @@ When the virtual environment is activated you can then:
* run the test suite from the checked out source folder via ``pytest``
* trigger the pre-commit check suite manually from the checked out source folder via
``pre-commit run --hook-stage manual --all-files``
* build the documentation running ``sphinx-build -b html . _build`` in the ``docs``
folder -- the documentation will be available in the newly created ``_build``
directory. You can simply browse it locally by opening ``index.html``
To switch the activated virtual environment, simply activate the new environment as described above.
If a Python 2 environment is also desired (e.g. for maintenance reasons), also do the following extra steps:
To deactivate the virtual environment and return to the system's default Python: ``deactivate``.
* Prerequisites:
If you also want to be able to build the documentation that resides in the ``docs`` subfolder, you need to activate
the *Python 3* environment and install the docs dependencies as well:
* `Python 2.7 <https://python.org>`_ including ``pip``, ``setuptools`` and ``virtualenv``
* ``source venv3/bin/activate`` (Linux, macOS) or ``source venv3/Scripts/activate`` (Git Bash under Windows, see below)
* ``pip install -e '.[develop,plugins,docs]'``
* Create a virtual environment in the checked out source folder for Python 2: ``virtualenv --python=python2 venv2``
Go to the directory `docs` and you can then build the documentation:
.. note::
* ``sphinx-build -b html . _build``
This assumes that the ``python2`` binary is available directly on your ``PATH``. If
it cannot be found on your ``PATH`` like this you'll need to specify the full path here,
e.g. ``virtualenv --python=/path/to/python2/bin/python venv2``
The documentation will be available in the newly created ``_build`` directory. You can simply browse it locally by opening ``index.html``
* Activate the virtual environment: ``source venv2/bin/activate`` (Linux, macOS) or ``source venv2/Scripts/activate`` (Git Bash under Windows, see below)
* Update ``pip`` in the virtual environment:
* ``pip install --upgrade pip``
* Install OctoPrint in `"editable" mode <https://pip.pypa.io/en/stable/reference/pip_install/#editable-installs>`_,
including its regular *and* development and plugin development dependencies:
* ``pip install -e '.[develop,plugins]'``
.. _sec-development-environment-source-linux:
@@ -99,12 +103,6 @@ installed:
sudo apt-get install python python-pip python-dev python-setuptools python-virtualenv python3 python3-virtualenv python3-dev git libyaml-dev build-essential
.. todo::
Using a Linux distribution that doesn't use ``apt``? Please send a
`Pull Request <https://github.com/OctoPrint/OctoPrint/blob/master/CONTRIBUTING.md#pull-requests>`_ to get the necessary
steps into this guide!
Then:
.. code-block:: none
@@ -112,19 +110,43 @@ Then:
cd ~/devel
git clone https://github.com/OctoPrint/OctoPrint.git
cd OctoPrint
virtualenv --python=python2 venv2
virtualenv --python=python3 venv3
source ./venv2/bin/activate
pip install --upgrade pip
pip install -e '.[develop,plugins]'
source ./venv3/bin/activate
pip install --upgrade pip
pip install -e '.[develop,plugins,docs]'
pre-commit install
git config blame.ignoreRevsFile .git-blame-ignore-revs
.. _sec-development-environment-linux-python2:
Optional Python 2 environment
.............................
If a Python 2 environment is also desired:
* On apt based distributions (e.g. Debian, Ubuntu, ...):
.. code-block:: none
sudo apt-get install python2 python2-dev python-pip python-setuptools python-virtualenv
Then:
.. code-block:: none
virtualenv --python=python2 venv2
source ./venv2/bin/activate
pip install --upgrade pip
pip install -e '.[develop,plugins]'
You can then start OctoPrint via ``octoprint`` after activating one of the two virtual environments.
.. todo::
Using a Linux distribution that doesn't use ``apt``? Please send a
`Pull Request <https://github.com/OctoPrint/OctoPrint/blob/master/CONTRIBUTING.md#pull-requests>`_ to get the necessary
steps into this guide!
.. _sec-development-environment-windows:
Windows
@@ -136,20 +158,20 @@ location, please substitute accordingly.
First download & install:
* `Git for Windows <https://git-for-windows.github.io/>`_
* `Latest *stable* Python 2.7 and Python 3.8 releases from python.org <https://www.python.org/downloads/windows/>`_
(at the time of writing those are ``2.7.18`` and ``3.8.7``)
* `Latest *stable* Python 3 release from python.org <https://www.python.org/downloads/windows/>`_
* make sure to have the installer add Python to the ``PATH`` and have it install ``pip`` too
* it's recommended to install Python 2.7 into ``C:\Python27`` and Python 3 into ``C:\Python38`` - if you select
* it's recommended to install Python 3 into ``C:\Python3`` - if you select
different install locations please substitute accordingly
* it's also recommended to have both versions get installed for all users
* it's also recommended to install for all users
* `Microsoft Visual C++ Compiler for Python 2.7 <http://www.microsoft.com/en-us/download/details.aspx?id=44266>`_
* `Build Tools For Visual Studio 2019 <https://visualstudio.microsoft.com/downloads/#build-tools-for-visual-studio-2019>`_
* install "C++ build tools" and ensure the latest versions of "MSVCv142 - VS 2019 C++ x64/x86 build tools" and
"Windows 10 SDK" are checked under individual components.
Open the Git Bash you just installed and in that:
.. code-block:: none
@@ -158,17 +180,38 @@ Open the Git Bash you just installed and in that:
cd /c/Devel
git clone https://github.com/OctoPrint/OctoPrint.git
cd OctoPrint
virtualenv --python=C:\Python27\python.exe venv2
virtualenv --python=C:\Python38\python.exe venv3
source ./venv2/Scripts/activate
python -m pip install --upgrade pip
pip install -e '.[develop,plugins]'
virtualenv --python=C:\Python3\python.exe venv3
source ./venv3/Scripts/activate
pip install --upgrade pip
python -m pip install -e '.[develop,plugins,docs]'
pre-commit install
git config blame.ignoreRevsFile .git-blame-ignore-revs
.. _sec-development-environment-windows-python2:
Optional Python 2 environment
.............................
If a Python 2 environment is also desired, then also download and install
* `Python 2.7.18 MSI installer <https://octoprint.org/files/python-2.7.18.msi>`_ (mirrored on octoprint.org)
* it's recommended to install Python 2.7 into ``C:\Python27`` - if you select
different install locations please substitute accordingly
* it's also recommended to install for all users
* `Microsoft Visual C++ Compiler for Python 2.7 <https://octoprint.org/files/VCForPython27.msi>`_ (mirrored on octoprint.org)
Then:
.. code-block:: none
cd /c/Devel/OctoPrint
virtualenv --python=C:\Python27\python.exe venv2
source ./venv2/Scripts/activate
python -m pip install --upgrade pip
pip install -e '.[develop,plugins]'
.. _sec-development-environment-windows-optional:
Optional but recommended tools
@@ -177,6 +220,7 @@ Optional but recommended tools
These are some tools that are recommended but not required to have on hand:
* `Visual Studio Code <https://code.visualstudio.com/download>`_
* `Windows Terminal <https://github.com/microsoft/terminal>`_
Add the following profile to ``profiles.list`` in the settings, that will allow you to
@@ -227,6 +271,10 @@ You'll need a user account with administrator privileges.
* ``ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"``
* ``brew install python``
* Install `pip <https://pip.pypa.io/en/stable/installation/#supported-methods>`_
* ``python -m ensurepip --upgrade``
* Install `virtualenv <https://virtualenv.pypa.io/>`_
* ``pip install virtualenv``
@@ -265,11 +313,11 @@ PyCharm
- Register virtual environments:
- **(Linux, Windows)** "File" > "Settings ..." > "Project: OctoPrint" > "Project Interpreter" > "Add local ...",
select OctoPrint ``venv2`` folder (e.g. ``~/devel/OctoPrint/venv2`` or ``C:\Devel\OctoPrint\venv2``).
select OctoPrint ``venv3`` folder (e.g. ``~/devel/OctoPrint/venv3`` or ``C:\Devel\OctoPrint\venv3``).
- **(macOS)** "PyCharm" > "Preferences ..." > "Project: OctoPrint" > "Project Interpreter" > "Add ..." >
"Virtualenv Environment > "Existing Environment", select OctoPrint ``venv2`` folder (e.g. ``~/devel/OctoPrint/venv2``).
"Virtualenv Environment > "Existing Environment", select OctoPrint ``venv3`` folder (e.g. ``~/devel/OctoPrint/venv3``).
Repeat for the ``venv3`` folder.
If desired, repeat for the ``venv2`` folder, or any other additional Python venvs.
- Right click "src" in project tree, mark as source folder
- Add Run/Debug Configuration, select "Python":
@@ -334,7 +382,7 @@ PyCharm
* disable "Auto-save edited files to trigger the watched"
* enable "Trigger the watched on external changes"
To switch between Python 2 and 3, all you need to do now is change the Project Default Interpreter and restart
To switch between virtual environments (e.g. Python 3 and 2), all you need to do now is change the Project Default Interpreter and restart
OctoPrint. On current PyCharm versions you can do that right from a small selection field in the footer of the IDE.
Otherwise go through Settings.
@@ -343,3 +391,102 @@ Otherwise go through Settings.
Make sure you are running a PyCharm version of 2016.1 or later, or manually fix
`a debugger bug contained in earlier versions <https://youtrack.jetbrains.com/issue/PY-18365>`_ or plugin management
will not work in your developer install when running OctoPrint from PyCharm in debug mode.
Visual Studio Code (vscode)
---------------------------
- Install Visual Studio Code from `code.visualstudio.com <https://code.visualstudio.com/Download>`_
- Open folder select OctoPrint checkout folder (e.g. ``~/devel/OctoPrint`` or ``C:\Devel\OctoPrint``)
- Create a directory ``.vscode`` if not already present in the root of the project
- Create the following files inside the ``.vscode`` directory
settings.json
.. code-block:: json
{
"python.defaultInterpreterPath": "venv3/bin/python",
"python.formatting.provider": "black",
"python.formatting.blackArgs": [
"--config",
"black.toml"
],
"editor.formatOnSave": true,
"python.sortImports.args": [
"--profile=black",
],
"[python]": {
"editor.codeActionsOnSave": {
"source.organizeImports": true
}
},
"python.linting.pylintEnabled": false,
"python.linting.flake8Enabled": true,
"python.linting.enabled": true
}
tasks.json
.. code-block:: json
{
"version": "2.0.0",
"tasks": [
{
"label": "clean build artifacts",
"type": "shell",
"command": "python ./setup.py clean"
},
{
"label": "build docs",
"type": "shell",
"command": "sphinx-build -b html ./docs ./docs/_build"
}
]
}
launch.json
.. code-block:: json
{
"version": "0.2.0",
"configurations": [
{
"name": "OctoPrint",
"type": "python",
"request": "launch",
"module": "octoprint",
"args": [
"serve",
"--debug"
],
"cwd": "${workspaceFolder}/src",
"preLaunchTask": "clean build artifacts"
}
]
}
In the terminal install the python extension by running this command:
.. code-block:: bash
code --install-extension ms-python.python
In vscode terminal, or with venv active install code formatter black and linter flake8 by running:
.. code-block:: bash
python -m pip install -U black flake8 flake8-bugbear
Summary of vscode config:
* Pressing ``F5`` will now start OctoPrint in debug mode
* Your terminal inside vscode uses the virtual python environment
* Saving a file will run an auto formatter and import sort
* ``Ctrl+Shift+B`` can be used to run the ``build docs`` task to rebuild the documentation
+5
View File
@@ -607,6 +607,11 @@ Eject
EStop
An ``M112`` was sent to the printer through OctoPrint (not triggered when printing from SD!)
FilamentChange
An ``M600``, ``M701`` or ``M702`` was sent to the printer through OctoPrint (not triggered when printing from SD!)
.. versionadded:: 1.7.0
PositionUpdate
The response to an ``M114`` was received by OctoPrint. The payload contains the current position information
parsed from the response and (in the case of the selected tool ``t`` and the current feedrate ``f``) tracked
+9 -1
View File
@@ -38,6 +38,8 @@ The following GCODE scripts are sent by OctoPrint automatically:
* ``afterPrintDone``: Sent just after a print job finished. Defaults to an empty script.
* ``afterPrintPaused``: Sent just after a print job was paused. Defaults to an empty script.
* ``beforePrintResumed``: Sent just before a print job is resumed. Defaults to an empty script.
* ``beforeToolChange``: Sent just before a tool change command (``Tn``) is issued.
* ``afterToolChange``: Sent just after a tool change command (``Tn``) is issued
.. note::
@@ -70,7 +72,8 @@ Context
All GCODE scripts have access to the following template variables through the template context:
* ``printer_profile``: The currently selected :ref:`Printer Profile <sec-modules-printer-profile>`, including
information such as the extruder count, the build volume size, the filament diameter etc.
information such as the extruder count, the build volume size, the filament diameter etc. The individual properties
follow the common data model for :ref:`printer profiles <sec-api-printerprofiles-datamodel-profile>`.
* ``last_position``: Last position reported by the printer via `M114` (might be unset if no `M114` was sent so far!).
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. All of these coordinates might be ``None`` if no
@@ -107,6 +110,11 @@ There are a few additional template variables available for the following specif
* ``cancel_temperature``: Last known temperature values when the print was cancelled. See ``last_temperature`` above
for the structure to expect here.
* ``beforeToolChange`` and ``afterToolChange``
* ``tool.old``: The number of the previous tool
* ``tool.new``: The number of the new tool
.. warning::
-4
View File
@@ -89,10 +89,6 @@ connection options (``baseurl`` and ``apikey``) directly in the constructor or s
:ref:`Application Key Plugin <sec-bundledplugins-appkeys>`
A bundled plugin that implements an authorization workflow for third party clients. It adds various additional
methods to the JS Client Library.
:ref:`ForceLogin Plugin <sec-bundledplugins-forcelogin>`
A bundled plugin that disables anonymous access to the regular OctoPrint UI by implementing a custom UI and
various hooks. Utilizes the client library's :ref:`browser component <sec-jsclientlib-browser>` to login the
user.
.. toctree::
:maxdepth: 3
-3
View File
@@ -4,7 +4,6 @@ octoprint.plugin
----------------
.. automodule:: octoprint.plugin
:members:
.. _sec-modules-plugin-core:
@@ -12,7 +11,6 @@ octoprint.plugin.core
---------------------
.. automodule:: octoprint.plugin.core
:members:
.. _sec-modules-plugin-types:
@@ -20,4 +18,3 @@ octoprint.plugin.types
----------------------
.. automodule:: octoprint.plugin.types
:members:
-2
View File
@@ -4,7 +4,6 @@ octoprint.printer
-----------------
.. automodule:: octoprint.printer
:members:
.. _sec-modules-printer-profile:
@@ -12,4 +11,3 @@ octoprint.printer.profile
-------------------------
.. automodule:: octoprint.printer.profile
:members:
-1
View File
@@ -4,4 +4,3 @@ octoprint.settings
------------------
.. automodule:: octoprint.settings
:members:
-2
View File
@@ -4,7 +4,6 @@ octoprint.slicing
-----------------
.. automodule:: octoprint.slicing
:members:
.. _sec-modules-slicing-exceptions:
@@ -12,4 +11,3 @@ octoprint.slicing.exceptions
----------------------------
.. automodule:: octoprint.slicing.exceptions
:members:
+108 -8
View File
@@ -931,7 +931,7 @@ octoprint.comm.transport.serial.additional_port_names
.. versionadded:: 1.4.1
Return additional port names (not glob patterns!) to use as a serial connection to the printer. Expected to be
``list`` of ``string``s.
``list`` of ``string``.
Useful in combination with :ref:`octoprint.comm.transport.serial.factory <sec-plugins-hook-comm-transport-serial-factory>`
to implement custom serial-like ports through plugins.
@@ -1191,7 +1191,7 @@ octoprint.plugin.softwareupdate.check_config
See :ref:`here <sec-bundledplugins-softwareupdate-hooks-check_config>`.
.. _sec-plugins-hooks-plugin-printer-additional_state_data
.. _sec-plugins-hooks-plugin-printer-additional_state_data:
octoprint.printer.additional_state_data
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@@ -1201,7 +1201,7 @@ octoprint.printer.additional_state_data
.. versionadded:: 1.5.0
Use this to inject additional data into the data structure returned from the printer backend to the frontend
on the push socket or other registered :ref:`~octoprint.printer.PrinterCallback`s. Anything you return here
on the push socket or other registered :class:`octoprint.printer.PrinterCallback`. Anything you return here
will be located beneath ``plugins.<your plugin id>`` in the resulting initial and current data push structure.
The ``initial`` parameter will be ``True`` if this the additional update sent to the callback. Your handler should
@@ -1430,7 +1430,7 @@ octoprint.server.api.after_request
octoprint.server.api.before_request
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. py:function:: after_request_handlers_hook(*args, **kwargs)
.. py:function:: before_request_handlers_hook(*args, **kwargs)
.. versionadded:: 1.3.10
@@ -1600,8 +1600,6 @@ octoprint.server.sockjs.register
Handlers should return either ``True`` or ``False``. ``True`` signals to proceed with normal registration. ``False``
signals to not register the client.
See the bundled :ref:`Forcelogin Plugin <sec-bundledplugins-forcelogin>` for an example on how to utilize this.
:param object socket: the socket object which is about to be registered
:param object user: the user currently authenticated on the socket - might be None
:return: whether to proceed with registration (``True``) or not (``False``)
@@ -1620,8 +1618,6 @@ octoprint.server.sockjs.emit
Handlers should return either ``True`` to allow the message to be emitted, or ``False`` to prevent it.
See the bundled :ref:`Forcelogin Plugin <sec-bundledplugins-forcelogin>` for an example on how to utilize this.
:param object socket: the socket object on which a message is about to be emitted
:param object user: the user currently authenticated on the socket - might be None
:param string message: the message type about to be emitted
@@ -1629,6 +1625,110 @@ octoprint.server.sockjs.emit
:return: whether to proceed with sending the message (``True``) or not (``False``)
:rtype: boolean
.. _sec-plugins-hook-system-additional_commands:
octoprint.system.additional_commands
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. py:function:: additional_commands_hook(*args, **kwargs)
.. versionadded:: 1.7.0
Allows adding additional system commands into the system menu. Handlers must return
a list of system command definitions, each definition matching the following data
structure:
.. list-table::
:widths: 15 5 10 30
:header-rows: 1
* - Name
- Multiplicity
- Type
- Description
* - ``name``
- 1
- String
- The name to display in the menu.
* - ``action``
- 1
- String
- An identifier for the action, must only consist of lower case a-z, numbers, ``-`` and ``_`` (``[a-z0-9-_]``).
* - ``command``
- 1
- String
- The system command to execute.
* - ``confirm``
- 0..1
- String
- An optional message to show as a confirmation dialog before executing the command.
* - ``async``
- 0..1
- bool
- If ``True``, the command will be run asynchronously and the API call will return immediately after enqueuing it for execution.
* - ``ignore``
- 0..1
- bool
- If ``True``, OctoPrint will ignore the result of the command's (and ``before``'s, if set) execution and return a successful result regardless. Defaults to ``False``.
* - ``debug``
- 0..1
- bool
- If ``True``, the command will generate debug output in the log including the command line that's run. Use with care. Defaults to ``False``
* - ``before``
- 0..1
- callable
- Optional callable to execute before the actual ``command`` is run. If ``ignore`` is false and this fails in any way, the command will not run and an error returned.
.. code-block:: python
def get_additional_commands(*args, **kwargs):
return [
{
"name": "Just a test",
"action": "test",
"command": "logger This is just a test of an OctoPrint system command from a plugin",
"before": lambda: print("Hello World!")
}
]
__plugin_hooks__ = {
"octoprint.system.additional_commands": get_additional_commands
}
:return: a list of command specifications
:rtype: list
.. _sec-plugins-hook-systeminfo-additional_bundle_files:
octoprint.systeminfo.additional_bundle_files
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. py:function:: additional_bundle_files_hook(*args, **kwargs)
.. versionadded:: 1.7.0
Allows bundled plugins to extend the list of files to include in the systeminfo bundle.
Note that this hook will ignore third party plugins. Handlers must return a dictionary
mapping file names in the bundle to either local log paths on disk or a ``callable``
that will be called to generate the file's content inside the bundle.
**Example**
Add a plugin's ``console`` log file to the systeminfo bundle:
.. code-block:: python
def get_additional_bundle_files(*args, **kwargs):
console_log = self._settings.get_plugin_logfile_path(postfix="console")
return {os.path.basename(console_log): console_log}
__plugin_hooks__ = {
"octoprint.systeminfo.additional_bundle_files": get_additional_bundle_files
}
:return: a dictionary mapping bundle file names to bundle file content
:rtype: dict
.. _sec-plugins-hook-timelapse-extensions:
octoprint.timelapse.extensions
+6
View File
@@ -225,6 +225,12 @@ onUserPermissionsChanged(user)
will be provided as only parameter. Note that this may also be triggered for not logged in guests if the guest
group is modified. In this case ``user`` will be undefined.
onBeforePrintStart(callback)
Called before a print is started either by clicking the "Print" button in the state panel or the select & print icon
in the file list. The callback to actually proceed with starting the print is provided as the only parameter. By returning
``false`` from this, plugins may prevent a print from actually starting, optionally starting it at a later date by
calling ``callback`` themselves. This can be used for example to implement an additional confirmation dialog.
onTabChange(next, current)
Called before the main tab view switches to a new tab, so `before` the new tab becomes visible. Called with the
next (changed to) and current (still visible) tab's hash (e.g. ``#control``). Note that ``current`` might be undefined
+37 -30
View File
@@ -25,70 +25,77 @@ SETUP_REQUIRES = ["markdown>=3.1,<3.2"] # newer versions require Python 3
INSTALL_REQUIRES = [
# additional OctoPrint plugins that are maintained on a different release cycle
"OctoPrint-FileCheck>=2021.2.23",
"OctoPrint-FirmwareCheck>=2021.2.4",
"OctoPrint-PiSupport>=2021.3.26",
"OctoPrint-FirmwareCheck>=2021.10.11",
"OctoPrint-PiSupport>=2021.10.28",
# the following dependencies are non trivial to update since later versions
# introduce backwards incompatible changes that might affect plugins, or due to
# other observed problems
"markupsafe>=1.1,<2.0", # Jinja dependency, newer versions require Python 3
"tornado==5.1.1", # newer versions require Python 3
"markdown>=3.1,<3.2", # newer versions require Python 3
"regex!=2018.11.6", # avoid broken 2018.11.6. See #2874
"wrapt>=1.12.1,<1.13", # newer versions fail to build on OctoPi 0.15
# anything below this should be checked on releases for new versions
"flask>=1.1.2,<2",
"Jinja2>=2.11.2,<3",
"flask>=1.1.4,<2", # newer versions require Python 3
"Jinja2>=2.11.3,<3", # newer versions require Python 3
"Flask-Login>=0.5,<0.6", # flask-login doesn't use semver & breaks stuff on minor version increases
"Flask-Babel>=1.0,<2",
"Flask-Babel>=1.0,<2", # newer versions require Python 3
"Flask-Assets>=2.0,<3",
"werkzeug>=1.0.1,<2",
"itsdangerous>=1.1.0,<2",
"cachelib>=0.1,<1",
"PyYAML>=5.3.1,<6",
"werkzeug>=1.0.1,<2", # newer versions require Python 3
"itsdangerous>=1.1.0,<2", # newer versions require Python 3
"cachelib>=0.1,<0.2", # newer versions require Python 3
"PyYAML>=5.4.1,<6",
"pyserial>=3.4,<4",
"netaddr>=0.7.19,<1",
"watchdog==0.10.4", # watchdog dropped Py>3.6 on 0.10.5 point release...
"sarge==0.1.5post0",
"netifaces>=0.10.9,<1",
"netaddr>=0.8,<0.9", # changelog hints at breaking changes on minor version increases
"watchdog==0.10.4", # newer versions require Python 3
"sarge==0.1.6",
"netifaces>=0.11,<1",
"pylru>=1.2,<2",
"pkginfo>=1.5.0.1,<2",
"requests>=2.23.0,<3",
"pkginfo>=1.7.1,<2",
"requests>=2.26.0,<3",
"semantic_version>=2.8.5,<3",
"psutil>=5.7,<6",
"Click>=7.1.2,<8",
"psutil>=5.8,<6",
"Click>=7.1.2,<8", # newer versions require Python 3
"future>=0.18.2,<1",
"websocket-client>=0.57,<1",
"wrapt>=1.12.1,<2",
"emoji>=0.5.4,<1",
"sentry-sdk>=0.15.1,<1",
"websocket-client>=0.59,<1", # newer versions require Python 3
"emoji>=1.4.2,<2",
"sentry-sdk>=1.3.1,<2",
"filetype>=1.0.7,<2",
"zipstream-new>=1.1.8,<1.2",
# vendor bundled dependencies
"unidecode>=0.04.14,<0.05", # dependency of awesome-slugify
"blinker>=1.4,<2", # dependency of flask_principal
]
# Python 2 specific requirements
INSTALL_REQUIRES_PYTHON2 = [
"feedparser>=5.2.1,<6", # newer versions require Python 3
"tornado==5.1.1", # newer versions require Python 3
"futures>=3.3,<4",
"monotonic>=1.5,<2",
"monotonic>=1.6,<2",
"scandir>=1.10,<2",
"chainmap>=1.0.3,<2",
"typing>=3.7.4.1,<4",
"typing>=3.10.0.0,<4",
"enum34>=1.1.10,<1.2",
"frozendict>=1.2,<2",
"frozendict==1.2", # newer versions from different maintainer require Python 3
"colorlog<5", # newer versions require Python 3
# vendor bundled dependencies
"unidecode<1.3", # dependency of awesome-slugify, newer versions require Python 3
]
# Python 3 specific requirements
INSTALL_REQUIRES_PYTHON3 = [
"feedparser>=6.0.2,<7",
"zeroconf>=0.24,<0.25",
"immutabledict>=1.2.0,<2",
"feedparser>=6.0.8,<7",
"tornado>=6,<7", # tornado < 6 is incompatible with Python 3.10
"zeroconf>=0.33,<0.34", # breaking changes can happen on minor version increases
"immutabledict>=2.1,<3",
"pathvalidate>=2.4.1,<3",
"colorlog>=5.0.1,<6",
# vendor bundled dependencies
"unidecode", # dependency of awesome-slugify, leave w/o range to not cause dependency hell w/ Octolapse deps
]
# OSX specific requirements
INSTALL_REQUIRES_OSX = [
"appdirs>=1.4.4",
"appdirs>=1.4.4,<2",
]
# Additional requirements for optional install options
+26 -9
View File
@@ -287,11 +287,22 @@ def init_logging(
# default logging configuration
if default_config is None:
simple_format = "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
default_config = {
"version": 1,
"formatters": {
"simple": {
"format": "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
"simple": {"format": simple_format},
"colored": {
"()": "colorlog.ColoredFormatter",
"format": "%(log_color)s" + simple_format + "%(reset)s",
"reset": True,
"log_colors": {
"DEBUG": "cyan",
"INFO": "white",
"WARNING": "yellow",
"ERROR": "red",
"CRITICAL": "bold_red",
},
},
"serial": {"format": "%(asctime)s - %(message)s"},
"timings": {"format": "%(asctime)s - %(message)s"},
@@ -301,7 +312,7 @@ def init_logging(
"console": {
"class": "octoprint.logging.handlers.OctoPrintStreamHandler",
"level": "DEBUG",
"formatter": "simple",
"formatter": "colored",
"stream": "ext://sys.stdout",
},
"file": {
@@ -734,7 +745,7 @@ def get_plugin_blacklist(settings, connectivity_checker=None):
import yaml
from octoprint.util import bom_aware_open
from octoprint.util.version import is_octoprint_compatible
from octoprint.util.version import is_octoprint_compatible, is_python_compatible
logger = log.getLogger(__name__ + ".startup")
@@ -765,13 +776,19 @@ def get_plugin_blacklist(settings, connectivity_checker=None):
):
continue
if "version" in entry:
if "pythonversions" in entry and not is_python_compatible(
*entry["pythonversions"]
):
continue
if "pluginversions" in entry:
logger.debug(
"Blacklisted plugin: {}, version: {}".format(
entry["plugin"], entry["version"]
"Blacklisted plugin: {}, versions: {}".format(
entry["plugin"], ", ".join(entry["pluginversions"])
)
)
result.append((entry["plugin"], entry["version"]))
for version in entry["pluginversions"]:
result.append((entry["plugin"], version))
elif "versions" in entry:
logger.debug(
"Blacklisted plugin: {}, versions: {}".format(
@@ -779,7 +796,7 @@ def get_plugin_blacklist(settings, connectivity_checker=None):
)
)
for version in entry["versions"]:
result.append((entry["plugin"], version))
result.append((entry["plugin"], "=={}".format(version)))
else:
logger.debug("Blacklisted plugin: {}".format(entry["plugin"]))
result.append(entry["plugin"])
+34 -4
View File
@@ -42,7 +42,7 @@ def get_systeminfo(environment_detector, connectivity_checker, additional_fields
return flattened
def get_systeminfo_bundle(systeminfo, logbase, printer=None):
def get_systeminfo_bundle(systeminfo, logbase, printer=None, plugin_manager=None):
from octoprint.util import to_bytes
systeminfotxt = []
@@ -83,13 +83,41 @@ def get_systeminfo_bundle(systeminfo, logbase, printer=None):
for log in (
"octoprint.log",
"serial.log",
"plugin_softwareupdate_console.log",
"plugin_pluginmanager_console.log",
):
logpath = os.path.join(logbase, log)
if os.path.exists(logpath):
z.write(logpath, arcname=log, compress_type=compress_type)
# add additional bundle contents from bundled plugins
if plugin_manager:
for name, hook in plugin_manager.get_hooks(
"octoprint.systeminfo.additional_bundle_files"
).items():
try:
plugin = plugin_manager.get_plugin_info(name)
if not plugin.bundled:
# we only support this for bundled plugins because we don't want
# third party logs to blow up the bundles
continue
logs = hook()
for log, content in logs.items():
if isinstance(content, str):
# log path
if os.path.exists(content) and os.access(content, os.R_OK):
z.write(content, arcname=log, compress_type=compress_type)
elif callable(content):
# content generating callable
z.writestr(log, to_bytes(content()), compress_type=compress_type)
except Exception:
logging.getLogger(__name__).exception(
"Error while retrieving additional bundle contents for plugin {}".format(
name
),
extra={"plugin": name},
)
return z
@@ -140,7 +168,9 @@ def systeminfo_command(ctx, path, **kwargs):
zipfilename = os.path.join(path, get_systeminfo_bundle_name())
click.echo("Writing systeminfo bundle to {}...".format(zipfilename))
z = get_systeminfo_bundle(systeminfo, settings.getBaseFolder("logs"))
z = get_systeminfo_bundle(
systeminfo, settings.getBaseFolder("logs"), plugin_manager=plugin_manager
)
try:
with open(zipfilename, "wb") as f:
for data in z:
+1
View File
@@ -106,6 +106,7 @@ class Events(object):
REGISTERED_MESSAGE_RECEIVED = "RegisteredMessageReceived"
COMMAND_SUPPRESSED = "CommandSuppressed"
INVALID_TOOL_REPORTED = "InvalidToolReported"
FILAMENT_CHANGE = "FilamentChange"
# Timelapse
CAPTURE_START = "CaptureStart"
+16 -1
View File
@@ -5,7 +5,7 @@ __author__ = "Gina Häußge <osd@foosel.net>"
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
import copy
import logging
try:
@@ -25,6 +25,20 @@ from octoprint.util import get_fully_qualified_classname as fqcn
from octoprint.util import monotonic_time
from octoprint.util.platform import CLOSE_FDS
EMPTY_RESULT = {
"_empty": True,
"printingArea": {
"minX": 0,
"maxX": 0,
"minY": 0,
"maxY": 0,
"minZ": 0,
"maxZ": 0,
},
"dimensions": {"width": 0, "height": 0, "depth": 0},
"filament": {},
}
class QueueEntry(
collections.namedtuple(
@@ -489,6 +503,7 @@ class GcodeAnalysisQueue(AbstractAnalysisQueue):
raise RuntimeError(error.strip())
elif "EMPTY:" in output:
self._logger.info("Result is empty, no extrusions found")
result = copy.deepcopy(EMPTY_RESULT)
elif "RESULTS:" not in output:
raise RuntimeError("No analysis result found")
else:
+14 -20
View File
@@ -24,7 +24,7 @@ from past.builtins import basestring
import octoprint.filemanager
from octoprint.util import atomic_write, is_hidden_path, time_this, to_bytes, to_unicode
from octoprint.util.text import sanitize
from octoprint.util.files import sanitize_filename
class StorageInterface(object):
@@ -468,13 +468,14 @@ class LocalFileStorage(StorageInterface):
This storage type implements :func:`path_on_disk`.
"""
def __init__(self, basefolder, create=False):
def __init__(self, basefolder, create=False, really_universal=False):
"""
Initializes a ``LocalFileStorage`` instance under the given ``basefolder``, creating the necessary folder
if necessary and ``create`` is set to ``True``.
:param string basefolder: the path to the folder under which to create the storage
:param bool create: ``True`` if the folder should be created if it doesn't exist yet, ``False`` otherwise
:param string basefolder: the path to the folder under which to create the storage
:param bool create: ``True`` if the folder should be created if it doesn't exist yet, ``False`` otherwise
:param bool really_universal: ``True`` if the file names should be forced to really universal, ``False`` otherwise
"""
self._logger = logging.getLogger(__name__)
@@ -487,6 +488,8 @@ class LocalFileStorage(StorageInterface):
code=StorageError.INVALID_DIRECTORY,
)
self._really_universal = really_universal
import threading
self._metadata_lock_mutex = threading.RLock()
@@ -1165,22 +1168,10 @@ class LocalFileStorage(StorageInterface):
def sanitize_name(self, name):
"""
Raises a :class:`ValueError` for a ``name`` containing ``/`` or ``\\``. Otherwise
slugifies the given ``name`` by converting it to ASCII, leaving ``-``, ``_``, ``.``,
``(``, and ``)`` as is.
sanitizes the given ``name`` using ``octoprint.files.sanitize_filename``. Also
strips any leading ``.``.
"""
name = to_unicode(name)
if name is None:
return None
if "/" in name or "\\" in name:
raise ValueError("name must not contain / or \\")
result = sanitize(name, safe_chars="-_.()[] ").replace(" ", "_")
if result and result != "." and result != ".." and result[0] == ".":
# hidden files under *nix
result = result[1:]
return result
return sanitize_filename(name, really_universal=self._really_universal)
def sanitize_path(self, path):
"""
@@ -1199,7 +1190,10 @@ class LocalFileStorage(StorageInterface):
path_elements = path.split("/")
joined_path = self.basefolder
for path_element in path_elements:
joined_path = os.path.join(joined_path, self.sanitize_name(path_element))
if path_element == ".." or path_element == ".":
joined_path = os.path.join(joined_path, path_element)
else:
joined_path = os.path.join(joined_path, self.sanitize_name(path_element))
path = os.path.realpath(joined_path)
if not path.startswith(self.basefolder):
raise ValueError(
+2 -2
View File
@@ -83,7 +83,7 @@ class StreamWrapper(AbstractFileWrapper):
A wrapper allowing processing of one or more consecutive streams.
Arguments:
*streams: One or more :py:`io.IOBase` streams to process one after another to save to storage.
*streams: One or more :py:class:`io.IOBase` streams to process one after another to save to storage.
"""
def __init__(self, filename, *streams):
@@ -124,7 +124,7 @@ class MultiStream(io.RawIOBase):
their contents in the order they are provided to the constructor.
Arguments:
*streams: One or more :py:`io.IOBase` streams to concatenate.
*streams: One or more :py:class:`io.IOBase` streams to concatenate.
"""
def __init__(self, *streams):
+3 -3
View File
@@ -1,6 +1,4 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
"""
This module represents OctoPrint's plugin subsystem. This includes management and helper methods as well as the
registered plugin types.
@@ -14,6 +12,7 @@ registered plugin types.
.. autoclass:: PluginSettings
:members:
"""
from __future__ import absolute_import, division, print_function, unicode_literals
__author__ = "Gina Häußge <osd@foosel.net>"
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
@@ -67,7 +66,8 @@ def plugin_manager(
this defaults to the entry point ``octoprint.plugin``.
plugin_disabled_list (list): A list of plugin identifiers that are currently disabled. If not provided this
defaults to all plugins for which ``enabled`` is set to ``False`` in the settings.
plugin_blacklist (list): A list of plugin identifiers/identifier-version tuples that are currently blacklisted.
plugin_blacklist (list): A list of plugin identifiers/identifier-requirement tuples
that are currently blacklisted.
plugin_restart_needing_hooks (list): A list of hook namespaces which cause a plugin to need a restart in order
be enabled/disabled. Does not have to contain full hook identifiers, will be matched with startswith similar
to logging handlers
+220 -193
View File
@@ -1,6 +1,4 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
"""
In this module resides the core data structures and logic of the plugin system.
@@ -20,6 +18,7 @@ In this module resides the core data structures and logic of the plugin system.
:members:
"""
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
@@ -69,6 +68,182 @@ def _load_module(name, spec):
return imp.load_module(name, f, filename, details)
def parse_plugin_metadata(path):
result = {}
logger = logging.getLogger(__name__)
if not path:
return result
if os.path.isdir(path):
path = os.path.join(path, "__init__.py")
if not os.path.isfile(path):
return result
if not path.endswith(".py"):
# we only support parsing plain text source files
return result
logger.debug("Parsing plugin metadata from AST of {}".format(path))
try:
import ast
with io.open(path, "rb") as f:
root = ast.parse(f.read(), filename=path)
assignments = list(
filter(lambda x: isinstance(x, ast.Assign) and x.targets, root.body)
)
function_defs = list(
filter(lambda x: isinstance(x, ast.FunctionDef) and x.name, root.body)
)
all_relevant = assignments + function_defs
def extract_target_ids(node):
return list(
map(
lambda x: x.id,
filter(lambda x: isinstance(x, ast.Name), node.targets),
)
)
def extract_names(node):
if isinstance(node, ast.Assign):
return extract_target_ids(node)
elif isinstance(node, ast.FunctionDef):
return [
node.name,
]
else:
return []
for key in (
ControlProperties.attr_name,
ControlProperties.attr_version,
ControlProperties.attr_author,
ControlProperties.attr_description,
ControlProperties.attr_url,
ControlProperties.attr_license,
ControlProperties.attr_pythoncompat,
):
for a in reversed(assignments):
targets = extract_target_ids(a)
if key in targets:
if isinstance(a.value, ast.Str):
result[key] = a.value.s
elif (
isinstance(a.value, ast.Call)
and hasattr(a.value, "func")
and a.value.func.id == "gettext"
and a.value.args
and isinstance(a.value.args[0], ast.Str)
):
result[key] = a.value.args[0].s
break
for key in (ControlProperties.attr_hidden,):
for a in reversed(assignments):
targets = extract_target_ids(a)
if key in targets:
if isinstance(a.value, ast.Name) and a.value.id in (
"True",
"False",
):
result[key] = bool(a.value.id)
break
for a in reversed(all_relevant):
targets = extract_names(a)
if any(map(lambda x: x in targets, ControlProperties.all())):
result["has_control_properties"] = True
break
except SyntaxError:
raise
except Exception:
logger.exception("Error while parsing AST from {}".format(path))
return result
class ControlProperties(object):
attr_name = "__plugin_name__"
""" Module attribute from which to retrieve the plugin's human readable name. """
attr_description = "__plugin_description__"
""" Module attribute from which to retrieve the plugin's description. """
attr_disabling_DISCOURAGED = "__plugin_disabling_discouraged__"
""" Module attribute from which to retrieve the reason why disabling the plugin is discouraged. Only effective if ``self.bundled`` is True. """
attr_version = "__plugin_version__"
""" Module attribute from which to retrieve the plugin's version. """
attr_author = "__plugin_author__"
""" Module attribute from which to retrieve the plugin's author. """
attr_url = "__plugin_url__"
""" Module attribute from which to retrieve the plugin's website URL. """
attr_license = "__plugin_license__"
""" Module attribute from which to retrieve the plugin's license. """
attr_pythoncompat = "__plugin_pythoncompat__"
"""
Module attribute from which to retrieve the plugin's python compatibility string.
If unset a default of ``>=2.7,<3`` will be assumed, meaning that the plugin will be considered compatible to
Python 2 but not Python 3.
To mark a plugin as Python 3 compatible, a string of ``>=2.7,<4`` is recommended.
Bundled plugins will automatically be assumed to be compatible.
"""
attr_hidden = "__plugin_hidden__"
"""
Module attribute from which to determine if the plugin's hidden or not.
Only evaluated for bundled plugins, in order to hide them from the Plugin Manager
and similar places.
"""
attr_hooks = "__plugin_hooks__"
""" Module attribute from which to retrieve the plugin's provided hooks. """
attr_implementation = "__plugin_implementation__"
""" Module attribute from which to retrieve the plugin's provided mixin implementation. """
attr_helpers = "__plugin_helpers__"
""" Module attribute from which to retrieve the plugin's provided helpers. """
attr_check = "__plugin_check__"
""" Module attribute which to call to determine if the plugin can be loaded. """
attr_load = "__plugin_load__"
""" Module attribute which to call when loading the plugin. """
attr_unload = "__plugin_unload__"
""" Module attribute which to call when unloading the plugin. """
attr_enable = "__plugin_enable__"
""" Module attribute which to call when enabling the plugin. """
attr_disable = "__plugin_disable__"
""" Module attribute which to call when disabling the plugin. """
default_pythoncompat = ">=2.7,<3"
@classmethod
def all(cls):
return [getattr(cls, key) for key in dir(cls) if key.startswith("attr_")]
_EntryPointOrigin = namedtuple(
"EntryPointOrigin", "type, entry_point, module_name, package_name, package_version"
)
@@ -160,71 +335,6 @@ class PluginInfo(object):
license (str): License of the plugin
"""
attr_name = "__plugin_name__"
""" Module attribute from which to retrieve the plugin's human readable name. """
attr_description = "__plugin_description__"
""" Module attribute from which to retrieve the plugin's description. """
attr_disabling_discouraged = "__plugin_disabling_discouraged__"
""" Module attribute from which to retrieve the reason why disabling the plugin is discouraged. Only effective if ``self.bundled`` is True. """
attr_version = "__plugin_version__"
""" Module attribute from which to retrieve the plugin's version. """
attr_author = "__plugin_author__"
""" Module attribute from which to retrieve the plugin's author. """
attr_url = "__plugin_url__"
""" Module attribute from which to retrieve the plugin's website URL. """
attr_license = "__plugin_license__"
""" Module attribute from which to retrieve the plugin's license. """
attr_pythoncompat = "__plugin_pythoncompat__"
"""
Module attribute from which to retrieve the plugin's python compatibility string.
If unset a default of ``>=2.7,<3`` will be assumed, meaning that the plugin will be considered compatible to
Python 2 but not Python 3.
To mark a plugin as Python 3 compatible, a string of ``>=2.7,<4`` is recommended.
Bundled plugins will automatically be assumed to be compatible.
"""
attr_hidden = "__plugin_hidden__"
"""
Module attribute from which to determine if the plugin's hidden or not.
Only evaluated for bundled plugins, in order to hide them from the Plugin Manager
and similar places.
"""
attr_hooks = "__plugin_hooks__"
""" Module attribute from which to retrieve the plugin's provided hooks. """
attr_implementation = "__plugin_implementation__"
""" Module attribute from which to retrieve the plugin's provided mixin implementation. """
attr_helpers = "__plugin_helpers__"
""" Module attribute from which to retrieve the plugin's provided helpers. """
attr_check = "__plugin_check__"
""" Module attribute which to call to determine if the plugin can be loaded. """
attr_load = "__plugin_load__"
""" Module attribute which to call when loading the plugin. """
attr_unload = "__plugin_unload__"
""" Module attribute which to call when unloading the plugin. """
attr_enable = "__plugin_enable__"
""" Module attribute which to call when enabling the plugin. """
attr_disable = "__plugin_disable__"
""" Module attribute which to call when disabling the plugin. """
def __init__(
self,
key,
@@ -428,7 +538,9 @@ class PluginInfo(object):
str: Name of the plugin, fallback is the plugin's identifier.
"""
return self._get_instance_attribute(
self.__class__.attr_name, defaults=(self._name, self.key), incl_metadata=True
ControlProperties.attr_name,
defaults=(self._name, self.key),
incl_metadata=True,
)
@property
@@ -442,7 +554,9 @@ class PluginInfo(object):
str or None: Description of the plugin.
"""
return self._get_instance_attribute(
self.__class__.attr_description, default=self._description, incl_metadata=True
ControlProperties.attr_description,
default=self._description,
incl_metadata=True,
)
@property
@@ -457,7 +571,7 @@ class PluginInfo(object):
"""
return (
self._get_instance_attribute(
self.__class__.attr_disabling_discouraged, default=False
ControlProperties.attr_disabling_DISCOURAGED, default=False
)
if self.bundled
else False
@@ -476,7 +590,7 @@ class PluginInfo(object):
self._version
if self._version is not None
else self._get_instance_attribute(
self.__class__.attr_version, default=self._version, incl_metadata=True
ControlProperties.attr_version, default=self._version, incl_metadata=True
)
)
@@ -490,7 +604,7 @@ class PluginInfo(object):
str or None: Author of the plugin.
"""
return self._get_instance_attribute(
self.__class__.attr_author, default=self._author, incl_metadata=True
ControlProperties.attr_author, default=self._author, incl_metadata=True
)
@property
@@ -503,7 +617,7 @@ class PluginInfo(object):
str or None: Website URL for the plugin.
"""
return self._get_instance_attribute(
self.__class__.attr_url, default=self._url, incl_metadata=True
ControlProperties.attr_url, default=self._url, incl_metadata=True
)
@property
@@ -516,7 +630,7 @@ class PluginInfo(object):
str or None: License of the plugin.
"""
return self._get_instance_attribute(
self.__class__.attr_license, default=self._license, incl_metadata=True
ControlProperties.attr_license, default=self._license, incl_metadata=True
)
@property
@@ -529,7 +643,7 @@ class PluginInfo(object):
str: Python compatibility string of the plugin
"""
return self._get_instance_attribute(
self.__class__.attr_pythoncompat, default=">=2.7,<3", incl_metadata=True
ControlProperties.attr_pythoncompat, default=">=2.7,<3", incl_metadata=True
)
@property
@@ -541,7 +655,7 @@ class PluginInfo(object):
bool: Whether the plugin should be flagged as hidden or not
"""
return self._get_instance_attribute(
self.__class__.attr_hidden, default=False, incl_metadata=True
ControlProperties.attr_hidden, default=False, incl_metadata=True
)
@property
@@ -553,7 +667,7 @@ class PluginInfo(object):
Returns:
dict: Hooks provided by the plugin.
"""
return self._get_instance_attribute(self.__class__.attr_hooks, default={})
return self._get_instance_attribute(ControlProperties.attr_hooks, default={})
@property
def implementation(self):
@@ -565,7 +679,7 @@ class PluginInfo(object):
object: Implementation provided by the plugin.
"""
return self._get_instance_attribute(
self.__class__.attr_implementation, default=None
ControlProperties.attr_implementation, default=None
)
@property
@@ -577,7 +691,7 @@ class PluginInfo(object):
Returns:
dict: Helpers provided by the plugin.
"""
return self._get_instance_attribute(self.__class__.attr_helpers, default={})
return self._get_instance_attribute(ControlProperties.attr_helpers, default={})
@property
def check(self):
@@ -590,7 +704,7 @@ class PluginInfo(object):
otherwise.
"""
return self._get_instance_attribute(
self.__class__.attr_check, default=lambda: True
ControlProperties.attr_check, default=lambda: True
)
@property
@@ -603,7 +717,7 @@ class PluginInfo(object):
callable: Load method for the plugin module.
"""
return self._get_instance_attribute(
self.__class__.attr_load, default=lambda: True
ControlProperties.attr_load, default=lambda: True
)
@property
@@ -616,7 +730,7 @@ class PluginInfo(object):
callable: Unload method for the plugin module.
"""
return self._get_instance_attribute(
self.__class__.attr_unload, default=lambda: True
ControlProperties.attr_unload, default=lambda: True
)
@property
@@ -629,7 +743,7 @@ class PluginInfo(object):
callable: Enable method for the plugin module.
"""
return self._get_instance_attribute(
self.__class__.attr_enable, default=lambda: True
ControlProperties.attr_enable, default=lambda: True
)
@property
@@ -642,7 +756,7 @@ class PluginInfo(object):
callable: Disable method for the plugin module.
"""
return self._get_instance_attribute(
self.__class__.attr_disable, default=lambda: True
ControlProperties.attr_disable, default=lambda: True
)
def _get_instance_attribute(
@@ -670,11 +784,7 @@ class PluginInfo(object):
@property
def control_properties(self):
return [
getattr(self.__class__, key)
for key in dir(self.__class__)
if key.startswith("attr_")
]
return ControlProperties.all()
@property
def looks_like_plugin(self):
@@ -684,113 +794,14 @@ class PluginInfo(object):
return self.parsed_metadata.get("has_control_properties", False)
def _parse_metadata(self):
result = {}
path = self.location
if not path:
return result
if os.path.isdir(path):
path = os.path.join(self.location, "__init__.py")
if not os.path.isfile(path):
return result
if not path.endswith(".py"):
# we only support parsing plain text source files
return result
self._logger.debug(
"Parsing plugin metadata for {} from AST of {}".format(self.key, path)
)
try:
import ast
with io.open(path, "rb") as f:
root = ast.parse(f.read(), filename=path)
assignments = list(
filter(lambda x: isinstance(x, ast.Assign) and x.targets, root.body)
)
function_defs = list(
filter(lambda x: isinstance(x, ast.FunctionDef) and x.name, root.body)
)
all_relevant = assignments + function_defs
def extract_target_ids(node):
return list(
map(
lambda x: x.id,
filter(lambda x: isinstance(x, ast.Name), node.targets),
)
)
def extract_names(node):
if isinstance(node, ast.Assign):
return extract_target_ids(node)
elif isinstance(node, ast.FunctionDef):
return [
node.name,
]
else:
return []
for key in (
self.__class__.attr_name,
self.__class__.attr_version,
self.__class__.attr_author,
self.__class__.attr_description,
self.__class__.attr_url,
self.__class__.attr_license,
self.__class__.attr_pythoncompat,
):
for a in reversed(assignments):
targets = extract_target_ids(a)
if key in targets:
if isinstance(a.value, ast.Str):
result[key] = a.value.s
elif (
isinstance(a.value, ast.Call)
and hasattr(a.value, "func")
and a.value.func.id == "gettext"
and a.value.args
and isinstance(a.value.args[0], ast.Str)
):
result[key] = a.value.args[0].s
break
for key in (self.__class__.attr_hidden,):
for a in reversed(assignments):
targets = extract_target_ids(a)
if key in targets:
if isinstance(a.value, ast.Name) and a.value.id in (
"True",
"False",
):
result[key] = bool(a.value.id)
break
for a in reversed(all_relevant):
targets = extract_names(a)
if any(map(lambda x: x in targets, self.control_properties)):
result["has_control_properties"] = True
break
return parse_plugin_metadata(self.location)
except SyntaxError:
self._logger.exception(
"Invalid syntax in {} for plugin {}".format(path, self.key)
"Invalid syntax in plugin file of plugin {}".format(self.key)
)
self.invalid_syntax = True
except Exception:
self._logger.exception(
"Error while parsing AST from {} for plugin {}".format(path, self.key)
)
return result
return {}
class PluginManager(object):
@@ -837,11 +848,27 @@ class PluginManager(object):
if plugin_considered_bundled is None:
plugin_considered_bundled = []
processed_blacklist = []
for entry in plugin_blacklist:
if isinstance(entry, tuple):
key, version = entry
try:
processed_blacklist.append(
(key, pkg_resources.Requirement.parse(version))
)
except Exception:
self.logger.warning(
"Invalid version requirement {} for blacklist "
"entry {}, ignoring".format(version, key)
)
else:
processed_blacklist.append(entry)
self.plugin_folders = plugin_folders
self.plugin_bases = plugin_bases
self.plugin_entry_points = plugin_entry_points
self.plugin_disabled_list = plugin_disabled_list
self.plugin_blacklist = plugin_blacklist
self.plugin_blacklist = processed_blacklist
self.plugin_restart_needing_hooks = plugin_restart_needing_hooks
self.plugin_obsolete_hooks = plugin_obsolete_hooks
self.plugin_validators = plugin_validators
@@ -1310,7 +1337,7 @@ class PluginManager(object):
def matches_plugin(entry):
if isinstance(entry, (tuple, list)) and len(entry) == 2:
entry_key, entry_version = entry
return entry_key == key and entry_version == version
return entry_key == key and version in entry_version
return False
return any(map(lambda entry: matches_plugin(entry), self.plugin_blacklist))
+4 -5
View File
@@ -1,6 +1,4 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
"""
This module bundles all of OctoPrint's supported plugin implementation types as well as their common parent
class, :class:`OctoPrintPlugin`.
@@ -17,6 +15,7 @@ Please note that the plugin implementation types are documented in the section
:members:
"""
from __future__ import absolute_import, division, print_function, unicode_literals
__author__ = "Gina Häußge <osd@foosel.net>"
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
@@ -673,7 +672,7 @@ class UiPlugin(OctoPrintPlugin, SortablePlugin):
object.
Returns:
bool: ``True`` if the the implementation will serve the request,
bool: ``True`` if the implementation will serve the request,
``False`` otherwise.
"""
return False
@@ -1106,7 +1105,7 @@ class WizardPlugin(OctoPrintPlugin, ReloadNeedingPlugin):
* the current and seen versions are identical
* the current version is None and the seen version is not
* the current version is less or equal than the seen one
* the seen version is not None and the current version is less or equal than the seen one
.. code-block:: none
@@ -1158,7 +1157,7 @@ class WizardPlugin(OctoPrintPlugin, ReloadNeedingPlugin):
return (
(current == seen)
or (current is None and seen is not None)
or (current <= seen)
or (seen is not None and current <= seen)
)
@@ -209,7 +209,6 @@ $(function () {
}
})
.css({
"width": "auto",
"margin-left": function () {
return -($(this).width() / 2);
}
@@ -1,4 +1,4 @@
<div id="plugin_announcements_dialog" class="modal hide fade large" tabindex="-1" role="dialog" aria-labelledby="announcements_dialog_label" aria-hidden="true">
<div id="plugin_announcements_dialog" class="modal hide fade-in large" tabindex="-1" role="dialog" aria-labelledby="announcements_dialog_label" aria-hidden="true">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">&times;</button>
<h3 id="announcements_dialog_label">{{ _('Announcements') }}</h3>
@@ -1,4 +1,4 @@
<div id="plugin_appkeys_keygenerated" class="modal hide fade">
<div id="plugin_appkeys_keygenerated" class="modal hide fade-in">
<div class="modal-header">
<a href="javascript:void(0)" class="close" data-dismiss="modal" aria-hidden="true">&times;</a>
<h3 id="plugin_appkeys_keygenerated_title"></h3>
@@ -79,10 +79,10 @@
<p>{{ _('Create a new backup of the current state.') }}</p>
<form class="form-horizontal" onsubmit="return false;">
<div class="control-group">
<div class="control-group" title="{{ _('All files in the uploads folder and subfolders. These are the files in the Files List, plus any metadata that has been generated for those files.')|edq }}">
<div class="controls">
<label class="checkbox">
<input type="checkbox" data-bind="value: 'uploads', checked: excludeFromBackup"> {{ _('Exclude uploaded files & metadata from backup') }}
<input type="checkbox" data-bind="value: 'uploads', checked: excludeFromBackup"> {{ _('Exclude uploaded files (& associated metadata) from backup') }}
</label>
</div>
</div>
@@ -21,10 +21,10 @@ from octoprint.util.version import (
)
SENTRY_URL_SERVER = (
"https://587d00b409ab4a3da3258c9adee29335@o118517.ingest.sentry.io/1373987"
"https://690e174698034bcc95928e6bfa8573f7@o118517.ingest.sentry.io/1373987"
)
SENTRY_URL_COREUI = (
"https://722128c3b0ff45108bbfdfa566762c89@o118517.ingest.sentry.io/1374096"
"https://186f1dc5da7d46ab9d6b6de564d839bb@o118517.ingest.sentry.io/1374096"
)
SETTINGS_DEFAULTS = {
@@ -0,0 +1,64 @@
# -*- coding: utf-8 -*-
from flask_babel import gettext
import octoprint.events
import octoprint.plugin
from octoprint.access import ADMIN_GROUP
class EventManagerPlugin(
octoprint.plugin.SettingsPlugin,
octoprint.plugin.AssetPlugin,
octoprint.plugin.TemplatePlugin,
):
def on_settings_load(self):
my_settings = {
"availableEvents": octoprint.events.all_events(),
"subscriptions": [],
}
events = self._settings.global_get(["events"])
if events:
my_settings["subscriptions"] = events.get("subscriptions", [])
return my_settings
def on_settings_save(self, data):
if type(data.get("subscriptions")) == list:
self._settings.global_set(
["events", "subscriptions"], data.get("subscriptions", [])
)
def get_assets(self):
return {"js": ["js/events.js"]}
def get_template_configs(self):
return [
{
"type": "settings",
"custom_bindings": True,
"name": gettext("Event Manager"),
}
]
def get_additional_permissions(self):
return [
{
"key": "MANAGE",
"name": "Event management",
"description": gettext(
"Allows for the management of event subscriptions."
),
"default_groups": [ADMIN_GROUP],
"roles": ["manage"],
}
]
__plugin_name__ = gettext("Event Manager")
__plugin_pythoncompat__ = ">=2.7,<4"
__plugin_author__ = "jneilliii"
__plugin_license__ = "AGPLv3"
__plugin_description__ = gettext(
"Plugin to configure event subscriptions available in config.yaml."
)
__plugin_implementation__ = EventManagerPlugin()
@@ -0,0 +1,59 @@
/*
* View model for OctoPrint-EventCoordinator
*
* Author: jneilliii
* License: AGPLv3
*/
$(function () {
function eventManagerViewModel(parameters) {
var self = this;
self.settingsViewModel = parameters[0];
self.selectedCommand = ko.observable();
self.eventDetails = function (data) {
if (data === false) {
return {
event: ko.observable(""),
command: ko.observable(""),
type: ko.observable(""),
enabled: ko.observable(true),
debug: ko.observable(false)
};
} else {
if (!data.hasOwnProperty("enabled")) {
data["enabled"] = ko.observable(true);
}
if (!data.hasOwnProperty("debug")) {
data["debug"] = ko.observable(false);
}
return data;
}
};
self.addEvent = function () {
self.selectedCommand(self.eventDetails(false));
self.settingsViewModel.settings.plugins.eventmanager.subscriptions.push(
self.selectedCommand()
);
$("#EventManagerEditor").modal("show");
};
self.editEvent = function (data) {
self.selectedCommand(self.eventDetails(data));
$("#EventManagerEditor").modal("show");
};
self.removeEvent = function (data) {
self.settingsViewModel.settings.plugins.eventmanager.subscriptions.remove(
data
);
};
}
OCTOPRINT_VIEWMODELS.push({
construct: eventManagerViewModel,
dependencies: ["settingsViewModel"],
elements: ["#settings_plugin_eventmanager"]
});
});
@@ -0,0 +1,65 @@
<div class="alert alert-block">
<p>{{ _('For additional information on OctoPrint events please see <a href="%(url)s" target="_blank" rel="noopener noreferer">the official documentation</a>.', url='https://docs.octoprint.org/en/master/events/index.html') }}</p>
<p><strong>{{ _('Warning:') }}</strong> {{ _('For changes to take effect you must restart OctoPrint after saving.') }}</p>
</div>
<div class="row-fluid">
<div class="span4">{{ _('Event') }}</div>
<div class="span6">{{ _('Command') }}</div>
<div class="span2 btn-group">
<button class="btn btn-mini" data-bind="click: addEvent"><i class="fa fa-plus"></i> {{ _('Add') }}</button>
</div>
</div>
<div data-bind="foreach: settingsViewModel.settings.plugins.eventmanager.subscriptions" class="row-fluid">
<div class="row-fluid">
<div class="span4" data-bind="text: event"></div>
<div class="span6" data-bind="text: command"></div>
<div class="span2 btn-group">
<button class="btn btn-mini" data-bind="click: $root.editEvent"><i class="fa fa-pencil"></i></button>
<button class="btn btn-mini btn-danger" data-bind="click: $root.removeEvent"><i class="fa fa-trash-alt"></i></button>
</div>
</div>
</div>
<div id="EventManagerEditor" data-bind="with: selectedCommand" class="modal hide fade-in">
<div class="modal-header">
<a href="#" class="close" data-dismiss="modal" aria-hidden="true">&times;</a>
<h3>{{ _('Command Editor') }}</h3>
</div>
<div class="modal-body">
<div class="control-group">
<label class="control-label">{{ _('Event') }}</label>
<div class="controls">
<select class="input-block-level" data-bind="value: event, options: $root.settingsViewModel.settings.plugins.eventmanager.availableEvents().sort(), optionsCaption: 'Select Event', valueAllowUnset: true"></select>
</div>
</div>
<div class="control-group">
<label class="control-label">{{ _('Command') }}</label>
<div class="controls">
<input type="text" class="input-block-level" data-bind="value: command" />
</div>
</div>
<div class="control-group">
<label class="control-label">{{ _('Type') }}</label>
<div class="controls">
<select data-bind="value: type, options: ['gcode', 'system'], optionsCaption: 'Select Event Type', valueAllowUnset: true"></select>
</div>
</div>
<div class="control-group">
<label class="control-label">{{ _('Enabled') }}</label>
<div class="controls">
<input type="checkbox" data-bind="checked: enabled" />
</div>
</div>
<div class="control-group">
<label class="control-label">{{ _('Debug') }}</label>
<div class="controls">
<input type="checkbox" data-bind="checked: debug" />
</div>
</div>
</div>
<div class="modal-footer">
<div class="row-fluid">
{{ _('Do not forget to save in main settings.') }} <button type="button" class="btn" data-dismiss="modal">{{ _('Close') }}</button>
</div>
</div>
</div>
@@ -60,6 +60,8 @@ $(function () {
self.renderer_showRetracts = ko.observable(true);
self.renderer_showPrinthead = ko.observable(true);
self.renderer_showSegmentStarts = ko.observable(false);
self.renderer_showDebugArcs = ko.observable(false);
self.renderer_chromeArcFix = ko.observable(OctoPrint.coreui.browser.chrome);
self.renderer_showBoundingBox = ko.observable(false);
self.renderer_showLayerBoundingBox = ko.observable(false);
self.renderer_showFullSize = ko.observable(false);
@@ -97,6 +99,8 @@ $(function () {
showRetracts: self.renderer_showRetracts(),
showHead: self.renderer_showPrinthead(),
showSegmentStarts: self.renderer_showSegmentStarts(),
showDebugArcs: self.renderer_showDebugArcs(),
chromeArcFix: self.renderer_chromeArcFix(),
showBoundingBox: self.renderer_showBoundingBox(),
showLayerBoundingBox: self.renderer_showLayerBoundingBox(),
showFullSize: self.renderer_showFullSize(),
@@ -146,6 +150,8 @@ $(function () {
self.renderer_showRetracts.subscribe(self.rendererOptionUpdated);
self.renderer_showPrinthead.subscribe(self.rendererOptionUpdated);
self.renderer_showSegmentStarts.subscribe(self.rendererOptionUpdated);
self.renderer_showDebugArcs.subscribe(self.rendererOptionUpdated);
self.renderer_chromeArcFix.subscribe(self.rendererOptionUpdated);
self.renderer_showBoundingBox.subscribe(self.rendererOptionUpdated);
self.renderer_showLayerBoundingBox.subscribe(self.rendererOptionUpdated);
self.renderer_showFullSize.subscribe(self.rendererOptionUpdated);
@@ -214,6 +220,9 @@ $(function () {
self.settings.printerProfiles
.currentProfileData()
.volume.formFactor.subscribe(self._printerProfileUpdated);
self.settings.printerProfiles
.currentProfileData()
.volume.origin.subscribe(self._printerProfileUpdated);
}
if (self.settings.printerProfiles.currentProfileData().axes) {
self.settings.printerProfiles
@@ -393,6 +402,10 @@ $(function () {
self.clear();
};
self.resetViewport = function () {
GCODE.ui.resetViewport();
};
self.resetOptions = function () {
self.renderer_centerModel(false);
self.renderer_centerViewport(false);
@@ -401,6 +414,8 @@ $(function () {
self.renderer_showRetracts(true);
self.renderer_showPrinthead(true);
self.renderer_showSegmentStarts(false);
self.renderer_showDebugArcs(false);
self.renderer_chromeArcFix(OctoPrint.coreui.browser.chrome);
self.renderer_showBoundingBox(false);
self.renderer_showLayerBoundingBox(false);
self.renderer_showFullSize(false);
@@ -454,8 +469,8 @@ $(function () {
max: 1,
step: 1,
value: [0, 1],
enabled: false,
tooltip: "hide"
enabled: false
//tooltip: "hide"
})
.on("slide", self.changeCommandRange);
};
@@ -890,6 +905,8 @@ $(function () {
showRetracts: self.renderer_showRetracts(),
showPrinthead: self.renderer_showPrinthead(),
showSegmentStarts: self.renderer_showSegmentStarts(),
showDebugArcs: self.renderer_showDebugArcs(),
chromeArcFix: self.renderer_chromeArcFix(),
showPrevious: self.renderer_showPrevious(),
showCurrent: self.renderer_showCurrent(),
showNext: self.renderer_showNext(),
@@ -916,6 +933,10 @@ $(function () {
self.renderer_showPrinthead(current["showPrinthead"]);
if (current["showSegmentStarts"] !== undefined)
self.renderer_showSegmentStarts(current["showSegmentStarts"]);
if (current["showDebugArcs"] !== undefined)
self.renderer_showDebugArcs(current["showDebugArcs"]);
if (current["chromeArcFix"] !== undefined)
self.renderer_chromeArcFix(current["chromeArcFix"]);
if (current["showPrevious"] !== undefined)
self.renderer_showPrevious(current["showPrevious"]);
if (current["showCurrent"] !== undefined)
@@ -56,6 +56,8 @@ GCODE.renderer = (function () {
showHead: false,
showSegmentStarts: false,
sizeSegmentStart: 2 * pixelRatio,
showDebugArcs: false,
chromeArcFix: false,
moveModel: true,
zoomInOnModel: false,
@@ -74,12 +76,18 @@ GCODE.renderer = (function () {
onDragStop: undefined
};
// offset due to dragging
var offsetModelX = 0,
offsetModelY = 0;
// TODO: remove in 1.7.0
var offsetBedX = 0,
offsetBedY = 0;
// scale due to zooming
var scaleX = 1,
scaleY = 1;
var speeds = [];
var speedsByLayer = {};
var currentInvertX = false,
@@ -339,12 +347,80 @@ GCODE.renderer = (function () {
};
}
// replace arc for chrome, code from https://stackoverflow.com/a/11689752
var bezierArc = function (x, y, radius, startAngle, endAngle, anticlockwise) {
// Signed length of curve
var signedLength;
var tau = 2 * Math.PI;
if (!anticlockwise && endAngle - startAngle >= tau) {
signedLength = tau;
} else if (anticlockwise && startAngle - endAngle >= tau) {
signedLength = -tau;
} else {
var delta = endAngle - startAngle;
signedLength = delta - tau * Math.floor(delta / tau);
// If very close to a full number of revolutions, make it full
if (Math.abs(delta) > 1e-12 && signedLength < 1e-12) signedLength = tau;
// Adjust if anti-clockwise
if (anticlockwise && signedLength > 0) signedLength = signedLength - tau;
}
// Minimum number of curves; 1 per quadrant.
var minCurves = Math.ceil(Math.abs(signedLength) / (Math.PI / 2));
// Number of curves; square-root of radius (or minimum)
var numCurves = Math.ceil(Math.max(minCurves, Math.sqrt(radius)));
// "Radius" of control points to ensure that the middle point
// of the curve is exactly on the circle radius.
var cpRadius = radius * (2 - Math.cos(signedLength / (numCurves * 2)));
// Angle step per curve
var step = signedLength / numCurves;
// Draw the circle
this.lineTo(x + radius * Math.cos(startAngle), y + radius * Math.sin(startAngle));
for (
var i = 0, a = startAngle + step, a2 = startAngle + step / 2;
i < numCurves;
++i, a += step, a2 += step
)
this.quadraticCurveTo(
x + cpRadius * Math.cos(a2),
y + cpRadius * Math.sin(a2),
x + radius * Math.cos(a),
y + radius * Math.sin(a)
);
};
var applyContextPatches = function () {
if (!ctx.origArc) ctx.origArc = ctx.arc;
ctx.circle = function (x, y, r) {
ctx.origArc(x, y, r, 0, 2 * Math.PI, true);
};
if (navigator.userAgent.toLowerCase().indexOf("chrome") > -1) {
if (renderOptions["chromeArcFix"]) {
ctx.arc = bezierArc;
log.info("Chrome Arc Fix enabled");
} else {
ctx.arc = ctx.origArc;
log.info("Chrome Arc Fix disabled");
}
}
};
var startCanvas = function () {
var jqueryCanvas = $(renderOptions["container"]);
//jqueryCanvas.css("background-color", renderOptions["bgColorOffGrid"]);
canvas = jqueryCanvas[0];
ctx = canvas.getContext("2d");
applyContextPatches();
canvas.style.height = canvas.height + "px";
canvas.style.width = canvas.width + "px";
canvas.height = canvas.height * pixelRatio;
@@ -357,8 +433,6 @@ GCODE.renderer = (function () {
ctx.lineCap = "round";
trackTransforms(ctx);
ctx.scale(1, -1); // Invert y-axis
// dragging => translating
canvas.addEventListener(
"mousedown",
@@ -395,6 +469,9 @@ GCODE.renderer = (function () {
if (renderOptions["onDrag"] && renderOptions["onDrag"](pt) === false)
return;
ctx.translate(pt.x - dragStart.x, pt.y - dragStart.y);
reRender();
renderOptions["centerViewport"] = false;
renderOptions["zoomInOnModel"] = false;
renderOptions["zoomInOnBed"] = false;
@@ -405,9 +482,6 @@ GCODE.renderer = (function () {
scaleX = 1;
scaleY = 1;
ctx.translate(pt.x - dragStart.x, pt.y - dragStart.y);
reRender();
if (renderOptions["onInternalOptionChange"] !== undefined) {
renderOptions["onInternalOptionChange"]({
centerViewport: false,
@@ -451,6 +525,9 @@ GCODE.renderer = (function () {
// return to old position
ctx.translate(-pt.x, -pt.y);
// render
reRender();
// disable conflicting options
renderOptions["zoomInOnModel"] = false;
renderOptions["zoomInOnBed"] = false;
@@ -461,9 +538,6 @@ GCODE.renderer = (function () {
scaleX = 1;
scaleY = 1;
// render
reRender();
if (renderOptions["onInternalOptionChange"] !== undefined) {
renderOptions["onInternalOptionChange"]({
zoomInOnModel: false,
@@ -540,7 +614,7 @@ GCODE.renderer = (function () {
// draw origin
ctx.beginPath();
ctx.arc(0, 0, 2, 0, Math.PI * 2, true);
ctx.circle(0, 0, 2);
ctx.stroke();
ctx.strokeStyle = renderOptions["colorGrid"];
@@ -584,7 +658,7 @@ GCODE.renderer = (function () {
// outline
var r = renderOptions["bed"]["r"];
ctx.arc(0, 0, r, 0, Math.PI * 2, true);
ctx.circle(0, 0, r);
// origin
ctx.moveTo(-1 * r, 0);
@@ -598,7 +672,7 @@ GCODE.renderer = (function () {
// draw origin
ctx.beginPath();
ctx.arc(0, 0, 2, 0, Math.PI * 2, true);
ctx.circle(0, 0, 2);
ctx.stroke();
ctx.strokeStyle = renderOptions["colorGrid"];
@@ -734,6 +808,17 @@ GCODE.renderer = (function () {
ctx.stroke();
};
var drawDebugArc = function (arc, ccw) {
ctx.moveTo(arc.x, arc.y);
ctx.lineTo(arc.startX, arc.startY);
ctx.moveTo(arc.x, arc.y);
ctx.lineTo(arc.endX, arc.endY);
ctx.moveTo(arc.startX, arc.startY);
ctx.lineTo(arc.endX, arc.endY);
ctx.moveTo(arc.startX, arc.startY);
ctx.arc(arc.x, arc.y, arc.r, arc.startAngle, arc.endAngle, ccw);
};
var drawLayer = function (layerNum, fromProgress, toProgress, isNotCurrentLayer) {
log.trace(
"Drawing layer " +
@@ -880,14 +965,14 @@ GCODE.renderer = (function () {
var prevPathType = "fill";
function strokePathIfNeeded(newPathType, strokeStyle) {
if (newPathType != prevPathType || newPathType == "fill") {
if (prevPathType != "fill") {
if (newPathType !== prevPathType || newPathType === "fill") {
if (prevPathType !== "fill") {
ctx.stroke();
}
prevPathType = newPathType;
ctx.beginPath();
if (newPathType != "fill") {
if (newPathType !== "fill") {
ctx.strokeStyle = strokeStyle;
ctx.moveTo(prevX, prevY);
}
@@ -948,14 +1033,15 @@ GCODE.renderer = (function () {
ctx.lineWidth = renderOptions["extrusionWidth"] * lineWidthFactor;
if (cmd.direction !== undefined && cmd.direction !== 0) {
var arc = getArcParams(cmd);
ctx.arc(
arc.x,
arc.y,
arc.r,
arc.startAngle,
arc.endAngle,
cmd.direction < 0
); // Y-axis is inverted so direction is also inverted
var ccw = cmd.direction < 0; // Y-axis is inverted so direction is also inverted
if (renderOptions["showDebugArcs"] && !isNotCurrentLayer) {
strokePathIfNeeded("debugarc", "#ff0000");
drawDebugArc(arc, ccw);
strokePathIfNeeded("extrude", getColorLineForTool(tool));
}
ctx.arc(arc.x, arc.y, arc.r, arc.startAngle, arc.endAngle, ccw);
} else {
ctx.lineTo(x, y);
}
@@ -995,7 +1081,7 @@ GCODE.renderer = (function () {
.alpha(alpha)
.html();
ctx.beginPath();
ctx.arc(prevX, prevY, sizeHeadSpot, 0, Math.PI * 2, true);
ctx.circle(prevX, prevY, sizeHeadSpot);
ctx.fill();
}
};
@@ -1036,15 +1122,6 @@ GCODE.renderer = (function () {
(renderOptions["bed"]["y"] / 2 -
(layerBounds.minY + layerBounds.maxY) / 2);
}
} else if (
renderOptions["bed"]["circular"] ||
renderOptions["bed"]["centeredOrigin"]
) {
canvasCenter = ctx.transformedPoint(canvas.width / 2, canvas.height / 2);
offsetModelX = canvasCenter.x;
offsetModelY = canvasCenter.y;
offsetBedX = 0;
offsetBedY = 0;
} else {
offsetModelX = 0;
offsetModelY = 0;
@@ -1127,48 +1204,57 @@ GCODE.renderer = (function () {
currentInvertY = invertY;
};
var resetViewport = function () {
ctx.setTransform(1, 0, 0, 1, 0, 0);
ctx.scale(1, -1); // invert y axis
var bedWidth = renderOptions["bed"]["x"];
var bedHeight = renderOptions["bed"]["y"];
if (renderOptions["bed"]["circular"]) {
bedWidth = bedHeight = renderOptions["bed"]["r"] * 2;
}
// Ratio of bed to canvas viewport
var viewportRatio = Math.min(
(canvas.width - 10) / bedWidth,
(canvas.height - 10) / bedHeight
);
// Apply initial translation to center the bed in the viewport
var translationX, translationY;
if (renderOptions["bed"]["circular"] || renderOptions["bed"]["centeredOrigin"]) {
translationX = canvas.width / 2;
translationY = canvas.height / 2;
} else {
translationX = (canvas.width - bedWidth * viewportRatio) / 2;
translationY =
bedHeight * viewportRatio +
(canvas.height - bedHeight * viewportRatio) / 2;
}
ctx.translate(translationX, -translationY);
ctx.scale(viewportRatio, viewportRatio);
// Scaling to apply to move lines and extrusion/retraction markers
lineWidthFactor = 1 / viewportRatio;
offsetModelX = 0;
offsetModelY = 0;
offsetBedX = 0;
offsetBedY = 0;
};
// ***** PUBLIC *******
return {
init: function () {
startCanvas();
resetViewport();
initialized = true;
var bedWidth = renderOptions["bed"]["x"];
var bedHeight = renderOptions["bed"]["y"];
if (renderOptions["bed"]["circular"]) {
bedWidth = bedHeight = renderOptions["bed"]["r"] * 2;
}
// Ratio of bed to canvas viewport
var viewportRatio = Math.min(
(canvas.width - 10) / bedWidth,
(canvas.height - 10) / bedHeight
);
// Apply initial translation to center the bed in the viewport
var translationX, translationY;
if (renderOptions["bed"]["circular"]) {
translationX = canvas.width / 2;
translationY = canvas.height / 2;
} else {
translationX = (canvas.width - bedWidth * viewportRatio) / 2;
translationY =
bedHeight * viewportRatio +
(canvas.height - bedHeight * viewportRatio) / 2;
}
ctx.translate(translationX, -translationY);
ctx.scale(viewportRatio, viewportRatio);
offsetModelX = 0;
offsetModelY = 0;
offsetBedX = 0;
offsetBedY = 0;
// Scaling to apply to move lines and extrusion/retraction markers
lineWidthFactor = 1 / viewportRatio;
},
setOption: function (options) {
var mustRefresh = false;
var mustReset = false;
var mustReapplyPatches = false;
var dirty = false;
for (var opt in options) {
if (!renderOptions.hasOwnProperty(opt) || !options.hasOwnProperty(opt))
@@ -1185,15 +1271,30 @@ GCODE.renderer = (function () {
"zoomInOnModel",
"bed",
"invertAxes",
"onViewportChange"
"onViewportChange",
"chromeArcFix"
]) > -1
) {
mustRefresh = true;
}
if ($.inArray(opt, ["bed", "onViewportChange"]) > -1) {
mustReset = true;
}
if ($.inArray(opt, ["chromeArcFix"]) > -1) {
mustReapplyPatches = true;
}
}
if (!dirty) return;
if (initialized) {
if (mustReset) {
resetViewport();
}
if (mustReapplyPatches) {
applyContextPatches();
}
if (mustRefresh) {
this.refresh();
} else {
@@ -1267,6 +1368,10 @@ GCODE.renderer = (function () {
if (layerNum === undefined) layerNum = layerNumStore;
this.doRender(model, layerNum);
},
resetViewport: function () {
resetViewport();
reRender();
},
getZ: function (layerNum) {
if (!model || !model[layerNum]) {
return "-1";
@@ -177,6 +177,10 @@ GCODE.ui = (function () {
}
},
resetViewport: function () {
GCODE.renderer.resetViewport();
},
updateLayerInfo: function (layerNum) {
switchLayer(layerNum, true);
},
@@ -17,10 +17,8 @@
</div>
<div class="progress progress-text-centered">
<span class="progress-text-back" data-bind="text: ui_progress_text"></span>
<div class="bar" style="width: 0;" data-bind="style: { width: ui_progress_percentage() + '%' }">
<span class="progress-text-front" data-bind="copyWidth: ':parent :parent', text: ui_progress_text"></span>
</div>
<div class="bar" data-bind="style: { width: ui_progress_percentage() + '%' }"></div>
<span class="progress-text-back" data-bind="css: { 'progress-text-front': (ui_progress_percentage() >= 50), 'progress-text-back': (ui_progress_percentage() < 50) }, text: ui_progress_text()"></span>
</div>
<div class="row-fluid">
@@ -74,6 +72,7 @@
<p>
<button class="btn btn-block" data-bind="click: reload, enable: enableReload">{{ _('Reload') }}</button>
<button class="btn btn-block" data-bind="click: resetViewport">{{ _('Reset viewport') }}</button>
</p>
<div class="advanced_options">
@@ -92,6 +91,13 @@
<label class="checkbox">
<input type="checkbox" data-bind="checked: renderer_showSegmentStarts">{{ _('Show segment starts') }}
</label>
<label class="checkbox">
<input type="checkbox" data-bind="checked: renderer_showDebugArcs">{{ _('Show debug arcs') }}
</label>
<label class="checkbox" data-bind="visible: OctoPrint.coreui.browser.chrome">
<input type="checkbox" data-bind="checked: renderer_chromeArcFix">{{ _('Apply arc fix') }} <span class="label">{{ _('Chrome') }}</span>
<span class="help-block">{{ _("See <a href='%(url)s' target='_blank'>issue #4117</a>.", url="https://github.com/OctoPrint/OctoPrint/issues/4117") }}</span>
</label>
</p>
<p>
<label class="checkbox">
@@ -109,6 +109,7 @@ def map_repository_entry(entry):
already_installed_string = "Requirement already satisfied (use --upgrade to upgrade)"
success_string = "Successfully installed"
failure_string = "Could not install"
python_mismatch_string = "requires a different Python:"
class PluginManagerPlugin(
@@ -247,6 +248,12 @@ class PluginManagerPlugin(
},
]
# Additional bundle contents
def get_additional_bundle_files(self, *args, **kwargs):
console_log = self._settings.get_plugin_logfile_path(postfix="console")
return {os.path.basename(console_log): console_log}
##~~ StartupPlugin
def on_after_startup(self):
@@ -958,6 +965,22 @@ class PluginManagerPlugin(
self._send_result_notification("install", result)
return result
if any(map(lambda x: python_mismatch_string in x, stderr)):
self._logger.error(
"Installing the plugin from {} failed, pip reported a Python version mismatch".format(
source
)
)
result = {
"result": False,
"source": source,
"source_type": source_type,
"reason": "Pip reported a Python version mismatch",
"faq": "https://faq.octoprint.org/plugin-python-mismatch",
}
self._send_result_notification("install", result)
return result
try:
result_line = list(
filter(
@@ -1112,6 +1135,42 @@ class PluginManagerPlugin(
destination = os.path.join(self._settings.global_get_basefolder("plugins"), name)
plugin_id, _ = os.path.splitext(name)
# check python compatibility
PYTHON_MISMATCH = {
"result": False,
"source": source,
"source_type": source_type,
"reason": "Plugin could not be installed",
"faq": "https://faq.octoprint.org/plugin-python-mismatch",
}
try:
metadata = octoprint.plugin.core.parse_plugin_metadata(path)
except SyntaxError:
self._logger.exception(
"Installing plugin from {} failed, there's a Python version mismatch".format(
source
)
)
result = PYTHON_MISMATCH
self._send_result_notification("install", result)
return result
pythoncompat = metadata.get(
octoprint.plugin.core.ControlProperties.attr_pythoncompat,
octoprint.plugin.core.ControlProperties.default_pythoncompat,
)
if not is_python_compatible(pythoncompat):
self._logger.exception(
"Installing plugin from {} failed, there's a Python version mismatch".format(
source
)
)
result = PYTHON_MISMATCH
self._send_result_notification("install", result)
return result
# copy plugin
try:
self._log_call("cp {} {}".format(path, destination))
shutil.copy(path, destination)
@@ -2105,6 +2164,7 @@ def __plugin_load__():
"octoprint.ui.web.templatetypes": __plugin_implementation__.get_template_types,
"octoprint.events.register_custom_events": _register_custom_events,
"octoprint.access.permissions": __plugin_implementation__.get_additional_permissions,
"octoprint.systeminfo.additional_bundle_files": __plugin_implementation__.get_additional_bundle_files,
}
global __plugin_helpers__
@@ -1 +1 @@
#settings_plugin_pluginmanager_pluginlist{height:calc(100vh - 450px);display:block;width:auto;overflow-x:hidden;padding-right:2px;margin-bottom:1em;position:relative;border-top:1px solid #eee;padding-top:6px}#settings_plugin_pluginmanager_pluginlist>table{margin-top:0px}#settings_plugin_pluginmanager_pluginlist table th.settings_plugin_plugin_manager_plugins_name,#settings_plugin_pluginmanager_pluginlist table td.settings_plugin_plugin_manager_plugins_name{text-overflow:ellipsis;text-align:left}#settings_plugin_pluginmanager_pluginlist table th.settings_plugin_plugin_manager_plugins_name .prop,#settings_plugin_pluginmanager_pluginlist table td.settings_plugin_plugin_manager_plugins_name .prop{white-space:nowrap}#settings_plugin_pluginmanager_pluginlist table th.settings_plugin_plugin_manager_plugins_actions,#settings_plugin_pluginmanager_pluginlist table td.settings_plugin_plugin_manager_plugins_actions{text-align:center;width:80px}#settings_plugin_pluginmanager_pluginlist table th.settings_plugin_plugin_manager_plugins_actions a,#settings_plugin_pluginmanager_pluginlist table td.settings_plugin_plugin_manager_plugins_actions a{text-decoration:none;color:#000}#settings_plugin_pluginmanager_pluginlist table th.settings_plugin_plugin_manager_plugins_actions a.disabled,#settings_plugin_pluginmanager_pluginlist table td.settings_plugin_plugin_manager_plugins_actions a.disabled{color:#ccc;cursor:default}#settings_plugin_pluginmanager_orphanlist{display:block;width:auto;max-height:400px;overflow-x:hidden;overflow-y:scroll;padding-right:2px;margin-bottom:1em}#settings_plugin_pluginmanager_orphanlist table th.settings_plugin_plugin_manager_orphans_id,#settings_plugin_pluginmanager_orphanlist table td.settings_plugin_plugin_manager_orphans_id{text-overflow:ellipsis;text-align:left}#settings_plugin_pluginmanager_orphanlist table th.settings_plugin_plugin_manager_orphans_actions,#settings_plugin_pluginmanager_orphanlist table td.settings_plugin_plugin_manager_orphans_actions{text-align:center;width:80px}#settings_plugin_pluginmanager_orphanlist table th.settings_plugin_plugin_manager_orphans_actions a,#settings_plugin_pluginmanager_orphanlist table td.settings_plugin_plugin_manager_orphans_actions a{text-decoration:none;color:#000}#settings_plugin_pluginmanager_orphanlist table th.settings_plugin_plugin_manager_orphans_actions a.disabled,#settings_plugin_pluginmanager_orphanlist table td.settings_plugin_plugin_manager_orphans_actions a.disabled{color:#ccc;cursor:default}#settings_plugin_pluginmanager_repositorydialog h4{position:relative}#settings_plugin_pluginmanager_repositorydialog h4 a.dropdown-toggle{color:inherit;text-decoration:none;font-size:14px}#settings_plugin_pluginmanager_repositorydialog h4 ul.dropdown-menu{font-size:14px}#settings_plugin_pluginmanager_repositorydialog .form-search{text-align:center;margin-bottom:5px !important}#settings_plugin_pluginmanager_repositorydialog .form-inline{padding:5px;padding-right:10px;margin-bottom:0}#settings_plugin_pluginmanager_repositorydialog .form-inline .help-block{margin-bottom:0;font-size:85%}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_unavailable,#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_empty{overflow:hidden;width:100%;height:400px;background-image:url("../img/repo_unavailable.png");text-align:center;display:table}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_unavailable div,#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_empty div{display:table-cell;vertical-align:middle}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_list{width:auto;height:400px;overflow-x:hidden;overflow-y:scroll;padding-right:2px}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_list .entry{border-bottom:1px solid #ddd;padding:5px}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_list .entry .meta{white-space:nowrap;text-overflow:ellipsis;overflow:hidden}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_list .entry .stats .prop{white-space:nowrap}#settings_plugin_pluginmanager_workingdialog_output .message{font-weight:bold}#settings_plugin_pluginmanager_workingdialog_output .error{font-weight:bold;color:#990000}#settings_plugin_pluginmanager_workingdialog_output .stdout{color:#333333}#settings_plugin_pluginmanager_workingdialog_output .stderr{color:#990000}#settings_plugin_pluginmanager_workingdialog_output .call{color:#000099}
#settings_plugin_pluginmanager_pluginlist{height:calc(100vh - 450px);display:block;width:auto;overflow-x:hidden;padding-right:2px;margin-bottom:1em;position:relative;border-top:1px solid #eee;padding-top:6px}#settings_plugin_pluginmanager_pluginlist>table{margin-top:0}#settings_plugin_pluginmanager_pluginlist table td.settings_plugin_plugin_manager_plugins_name,#settings_plugin_pluginmanager_pluginlist table th.settings_plugin_plugin_manager_plugins_name{text-overflow:ellipsis;text-align:left}#settings_plugin_pluginmanager_pluginlist table td.settings_plugin_plugin_manager_plugins_name .prop,#settings_plugin_pluginmanager_pluginlist table th.settings_plugin_plugin_manager_plugins_name .prop{white-space:nowrap}#settings_plugin_pluginmanager_pluginlist table td.settings_plugin_plugin_manager_plugins_actions,#settings_plugin_pluginmanager_pluginlist table th.settings_plugin_plugin_manager_plugins_actions{text-align:center;width:80px}#settings_plugin_pluginmanager_pluginlist table td.settings_plugin_plugin_manager_plugins_actions a,#settings_plugin_pluginmanager_pluginlist table th.settings_plugin_plugin_manager_plugins_actions a{text-decoration:none;color:#000}#settings_plugin_pluginmanager_pluginlist table td.settings_plugin_plugin_manager_plugins_actions a.disabled,#settings_plugin_pluginmanager_pluginlist table th.settings_plugin_plugin_manager_plugins_actions a.disabled{color:#ccc;cursor:default}#settings_plugin_pluginmanager_orphanlist{display:block;width:auto;max-height:400px;overflow-x:hidden;overflow-y:scroll;padding-right:2px;margin-bottom:1em}#settings_plugin_pluginmanager_orphanlist table td.settings_plugin_plugin_manager_orphans_id,#settings_plugin_pluginmanager_orphanlist table th.settings_plugin_plugin_manager_orphans_id{text-overflow:ellipsis;text-align:left}#settings_plugin_pluginmanager_orphanlist table td.settings_plugin_plugin_manager_orphans_actions,#settings_plugin_pluginmanager_orphanlist table th.settings_plugin_plugin_manager_orphans_actions{text-align:center;width:80px}#settings_plugin_pluginmanager_orphanlist table td.settings_plugin_plugin_manager_orphans_actions a,#settings_plugin_pluginmanager_orphanlist table th.settings_plugin_plugin_manager_orphans_actions a{text-decoration:none;color:#000}#settings_plugin_pluginmanager_orphanlist table td.settings_plugin_plugin_manager_orphans_actions a.disabled,#settings_plugin_pluginmanager_orphanlist table th.settings_plugin_plugin_manager_orphans_actions a.disabled{color:#ccc;cursor:default}#settings_plugin_pluginmanager_repositorydialog h4{position:relative}#settings_plugin_pluginmanager_repositorydialog h4 a.dropdown-toggle{color:inherit;text-decoration:none;font-size:14px}#settings_plugin_pluginmanager_repositorydialog h4 ul.dropdown-menu{font-size:14px}#settings_plugin_pluginmanager_repositorydialog .form-search{text-align:center;margin-bottom:5px!important}#settings_plugin_pluginmanager_repositorydialog .form-inline{padding:5px 10px 5px 5px;margin-bottom:0}#settings_plugin_pluginmanager_repositorydialog .form-inline .help-block{margin-bottom:0;font-size:85%}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_empty,#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_unavailable{overflow:hidden;width:100%;height:400px;background-image:url(../img/repo_unavailable.png);text-align:center;display:table}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_empty div,#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_unavailable div{display:table-cell;vertical-align:middle}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_list{width:auto;height:400px;overflow-x:hidden;overflow-y:scroll;padding-right:2px}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_list .entry{border-bottom:1px solid #ddd;padding:5px}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_list .entry .meta{white-space:nowrap;text-overflow:ellipsis;overflow:hidden}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_list .entry .stats .prop{white-space:nowrap}#settings_plugin_pluginmanager_workingdialog_output .message{font-weight:700}#settings_plugin_pluginmanager_workingdialog_output .error{font-weight:700;color:#900}#settings_plugin_pluginmanager_workingdialog_output .stdout{color:#333}#settings_plugin_pluginmanager_workingdialog_output .stderr{color:#900}#settings_plugin_pluginmanager_workingdialog_output .call{color:#009}
@@ -50,7 +50,7 @@ $(function () {
return !item.enabled;
}
},
"popularity",
"name",
[],
[
["bundled", "3rdparty"],
@@ -138,7 +138,7 @@ $(function () {
return !plugin.abandoned;
}
},
"title",
"popularity",
["filter_installed", "filter_incompatible"],
[],
0
@@ -424,7 +424,7 @@ $(function () {
self.uploadButton.bind("click", function () {
self._markWorking(
gettext("Installing plugin..."),
gettext("Installing plugin from uploaded archive...")
gettext("Installing plugin from uploaded file...")
);
data.formData = {
dependency_links: self.followDependencyLinks()
@@ -693,11 +693,15 @@ $(function () {
}
OctoPrint.plugins.pluginmanager
.getRepository(!!options.refresh)
.getRepository(!!options.refresh, {ifModified: true})
.fail(function () {
deferred.reject();
})
.done(function (data) {
.done(function (data, status, xhr) {
// Don't update if cached - requires ifModified: true to pass through
// the 304 status, otherwise it fakes it and produces 200 all the time.
if (xhr.status === 304) return;
self.fromRepositoryResponse(data.repository);
self.online(data.online !== undefined ? data.online : true);
deferred.resolveWith(data);
@@ -1213,7 +1217,7 @@ $(function () {
if (response.result) {
self._markDone();
} else {
self._markDone(response.reason);
self._markDone(response.reason, response.faq);
}
self._displayPluginManagementNotification(response, action, plugin);
@@ -1229,7 +1233,8 @@ $(function () {
self.logContents.steps.push({
action: action,
plugin: plugin,
result: response.result
result: response.result,
faq: response.faq
});
var title = gettext("Plugin management log");
@@ -1248,6 +1253,7 @@ $(function () {
steps = steps.slice(steps.length - 5);
}
var negativeResult = false;
_.each(steps, function (step) {
var line = undefined;
@@ -1289,7 +1295,14 @@ $(function () {
? '<i class="fa fa-check"></i>'
: '<i class="fa fa-remove"></i>'
}) +
(step.result === false && step.faq
? ' (<a href="" target="_blank" rel="noopener noreferer">' +
gettext("Why?") +
"</a>)"
: "") +
"</li>";
negativeResult = negativeResult || step.result === false;
});
text += "</ul></p>";
@@ -1381,6 +1394,8 @@ $(function () {
type = "warning";
}
if (negativeResult) type = "error";
var options = {
title: title,
text: text,
@@ -1428,11 +1443,22 @@ $(function () {
self.workingDialog.modal({keyboard: false, backdrop: "static", show: true});
};
self._markDone = function (error) {
self._markDone = function (error, faq) {
self.working(false);
if (error) {
self.loglines.push({line: gettext("Error!"), stream: "error"});
self.loglines.push({line: error, stream: "error"});
if (faq) {
self.loglines.push({
line: _.sprintf(
gettext(
"You can find more info on this issue in the FAQ at %(url)s"
),
{url: faq}
),
stream: "error"
});
}
} else {
self.loglines.push({line: gettext("Done!"), stream: "message"});
}
@@ -2,7 +2,7 @@
}
#settings_plugin_pluginmanager_pluginlist {
height: calc(100vh - 450px);
height: ~"calc(100vh - 450px)";
display: block;
width: auto;
overflow-x: hidden;
@@ -23,7 +23,8 @@
{% macro pluginmanager_throttled() %}
<div class="alert" data-bind="visible: throttled">{% trans %}
The system OctoPrint is running on is currently throttled. Due to that it's not possible to install new
plugins in order to avoid possible issues caused by system instability.
plugins in order to avoid possible issues caused by system instability. Read more on
this in <a href="https://faq.octoprint.org/pi-issues" target="_blank" rel="noopener noreferrer">the FAQ</a>.
{% endtrans %}</div>
{% endmacro %}
@@ -37,7 +38,7 @@
{% macro pluginmanager_requesterror() %}
<div class="alert" data-bind="visible: requestError()">{% trans %}
There appears to have been an error retrieving the plugin data from the backend. Please report this
in the bug tracker & be sure to include all requested logs.
in the bug tracker & be sure to include all requested information.
{% endtrans %}</div>
{% endmacro %}
@@ -61,7 +62,7 @@
<div class="pull-right">
<button class="btn btn-small" data-bind="click: $root.showRepository"><i class="fas fa-plus"></i> {{ _('Get More') }}</button>
<a class="btn btn-small" href="/plugin/pluginmanager/export"><i class="fas fa-download"></i> {{ _('Export') }}</a>
<a class="btn btn-small" href="{{ url_for('index') }}plugin/pluginmanager/export"><i class="fas fa-download"></i> {{ _('Export') }}</a>
<button class="btn btn-small" data-bind="click: function() { $root.showPluginSettings(); }" title="{{ _('Plugin Configuration')|edq }}"><i class="fas fa-wrench"></i></button>
<a class="btn btn-small" data-toggle="collapse" href="#pluginmanager_info" title="{{ _('Info') }}"><i class="fas fa-lg fa-info-circle text-info" data-bind="css: {'text-error': noticeCount() > 0, 'text-info': noticeCount() <=0 }"></i></a>
</div>
@@ -188,7 +189,7 @@
</div>
</div>
<div id="settings_plugin_pluginmanager_workingdialog" class="modal hide fade">
<div id="settings_plugin_pluginmanager_workingdialog" class="modal hide fade-in">
<div class="modal-header">
<h3 data-bind="text: workingTitle"></h3>
</div>
@@ -200,7 +201,7 @@
</div>
</div>
<div id="settings_plugin_pluginmanager_repositorydialog" class="modal hide fade">
<div id="settings_plugin_pluginmanager_repositorydialog" class="modal hide fade-in">
<div class="modal-header">
<a href="#" class="close" data-dismiss="modal" aria-hidden="true">&times;</a>
<h3>{{ _('Install new Plugins...') }}</h3>
@@ -346,7 +347,7 @@
</div>
</div>
<div id="settings_plugin_pluginmanager_configurationdialog" class="modal hide fade">
<div id="settings_plugin_pluginmanager_configurationdialog" class="modal hide fade-in">
<div class="modal-header">
<a href="#" class="close" data-dismiss="modal" aria-hidden="true">&times;</a>
<h3>{{ _('Plugin Configuration') }}</h3>
+327 -58
View File
@@ -1,6 +1,8 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
import datetime
__author__ = "Gina Häußge <osd@foosel.net>"
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
@@ -42,10 +44,12 @@ from octoprint.util.version import (
from . import cli, exceptions, updaters, util, version_checks
# OctoPi 0.15+
MINIMUM_PYTHON = "2.7.9"
MINIMUM_SETUPTOOLS = "39.0.1"
MINIMUM_PIP = "9.0.3"
# OctoPi 0.16+
MINIMUM_PYTHON = "2.7.13"
MINIMUM_SETUPTOOLS = "40.7.1"
MINIMUM_PIP = "19.0.1"
DATETIME_FORMAT = "%Y-%m-%d %H:%M:%S"
##~~ Plugin
@@ -66,6 +70,8 @@ class SoftwareUpdatePlugin(
OCTOPRINT_RESTART_TYPES = ("pip", "single_file_plugin")
VALID_RESTART_TYPES = ("octoprint", "environment")
DATA_FORMAT_VERSION = "v4"
CHECK_OVERLAY_KEY = "softwareupdate_check_overlay"
@@ -91,6 +97,11 @@ class SoftwareUpdatePlugin(
self._overlay_cache_ttl = 0
self._overlay_cache_timestamp = None
self._update_log = []
self._update_log_path = None
self._update_log_dirty = False
self._update_log_mutex = threading.RLock()
self._environment_supported = True
self._environment_versions = {}
self._environment_ready = threading.Event()
@@ -113,6 +124,11 @@ class SoftwareUpdatePlugin(
)
self._load_version_cache()
self._update_log_path = os.path.join(
self.get_plugin_data_folder(), "updatelog.yaml"
)
self._load_update_log()
self._overlay_cache_ttl = self._settings.get_int(["check_overlay_ttl"]) * 60
def refresh_checks(name, plugin):
@@ -151,6 +167,38 @@ class SoftwareUpdatePlugin(
},
]
# Additional bundle contents
def get_additional_bundle_files(self, *args, **kwargs):
console_log = self._settings.get_plugin_logfile_path(postfix="console")
def updatelog():
if not self._update_log:
self._load_update_log()
result = []
for entry in self._update_log:
line = "{datetime} - {display_name} - {current_version} -> {target_version} - {success} - {text}".format(
datetime=entry["datetime"].replace("T", " "),
display_name=entry["display_name"],
current_version=entry["current_version"],
target_version=entry["target_version"],
success="SUCCESS" if entry["success"] else "FAILED",
text=entry["text"]
+ (
" (Release notes: {})".format(entry["release_notes"])
if entry["release_notes"]
else ""
),
)
result.append(line)
return "\n".join(result)
return {
os.path.basename(console_log): console_log,
"plugin_softwareupdate_update.log": updatelog,
}
def on_startup(self, host, port):
console_logging_handler = logging.handlers.RotatingFileHandler(
self._settings.get_plugin_logfile_path(postfix="console"),
@@ -500,6 +548,138 @@ class SoftwareUpdatePlugin(
pass
self._version_cache_dirty = True
def _load_update_log(self):
if not os.path.isfile(self._update_log_path):
return
import yaml
try:
with io.open(self._update_log_path, "rt", encoding="utf-8") as f:
data = yaml.safe_load(f)
except Exception:
self._logger.exception("Error while loading update log from disk")
else:
# clean up data older than updatelog_cutoff hours
before_cleanup = len(data)
cutoff = (
datetime.datetime.now()
- datetime.timedelta(minutes=self._settings.get_int(["updatelog_cutoff"]))
).strftime(DATETIME_FORMAT)
data = sorted(
list(
filter(
lambda x: x.get("datetime") and x["datetime"] > cutoff,
data,
)
),
key=lambda x: x["datetime"],
)
cleaned_up = len(data) - before_cleanup
if cleaned_up:
self._logger.info(
"Cleaned up {} old update log entries".format(cleaned_up)
)
with self._update_log_mutex:
self._update_log = data
self._update_log_dirty = False
self._logger.info("Loaded update log from disk")
def _save_update_log(self):
import yaml
from octoprint.util import atomic_write
with self._update_log_mutex:
with atomic_write(
self._update_log_path, mode="wt", max_permissions=0o666
) as file_obj:
yaml.safe_dump(
sorted(self._update_log, key=lambda x: x["datetime"]),
stream=file_obj,
default_flow_style=False,
indent=2,
allow_unicode=True,
)
self._update_log_dirty = False
self._logger.info("Saved update log to disk")
def _add_update_log_entry(
self,
target,
current_version,
target_version,
success,
text,
display_name=None,
release_notes="",
save=True,
):
if display_name is None:
display_name = target
with self._update_log_mutex:
self._update_log.append(
{
"datetime": datetime.datetime.now().strftime(DATETIME_FORMAT),
"target": target,
"current_version": current_version,
"target_version": target_version,
"display_name": display_name,
"release_notes": release_notes if release_notes else "",
"success": success,
"text": text,
},
)
self._update_log_dirty = True
if save:
self._save_update_log()
def _is_octoprint_outdated_and_can_update(self):
checks = self._get_configured_checks()
check = checks.get("octoprint", None)
if not check:
return False
check = self._populated_check("octoprint", check)
credentials = self._settings.get(["credentials"], merged=True)
_, update_available, update_possible, _, _ = self._get_current_version(
"octoprint", check, credentials=credentials
)
if not update_available or not update_possible:
return False
restart_type = self._get_restart_type(check)
restart_command = self._get_restart_command(restart_type)
return restart_command is not None
def _get_restart_type(self, check):
if check.get("restart") in self.VALID_RESTART_TYPES:
return check["restart"]
elif "pip" in check or check.get("method") in self.OCTOPRINT_RESTART_TYPES:
return "octoprint"
else:
target_restart_type = None
return target_restart_type
def _get_restart_command(self, restart_type):
if restart_type == "octoprint":
return self._settings.global_get(
["server", "commands", "serverRestartCommand"]
)
elif restart_type == "environment":
return self._settings.global_get(
["server", "commands", "systemRestartCommand"]
)
else:
return None
# ~~ SettingsPlugin API
def get_settings_defaults(self):
@@ -544,13 +724,14 @@ class SoftwareUpdatePlugin(
},
},
"pip_command": None,
"cache_ttl": 24 * 60,
"cache_ttl": 24 * 60, # 1 day
"notify_users": True,
"ignore_throttled": False,
"minimum_free_storage": 150,
"check_overlay_url": "https://plugins.octoprint.org/update_check_overlay.json",
"check_overlay_py2_url": "https://plugins.octoprint.org/update_check_overlay_py2.json",
"check_overlay_ttl": 6 * 60,
"check_overlay_ttl": 6 * 60, # 6 hours
"updatelog_cutoff": 30 * 24 * 60, # 30 days
"credentials": {
"github": None,
"bitbucket_user": None,
@@ -606,6 +787,7 @@ class SoftwareUpdatePlugin(
else:
data["octoprint_checkout_folder"] = None
data["octoprint_type"] = None
data["octoprint_release_channel"] = None
# ~~ pip check settings
@@ -922,10 +1104,43 @@ class SoftwareUpdatePlugin(
# ~~ BluePrint API
@octoprint.plugin.BlueprintPlugin.route("/updatelog", methods=["GET"])
@no_firstrun_access
@Permissions.ADMIN.require(403)
def get_update_log(self):
def view():
return flask.jsonify(updatelog=list(reversed(self._update_log)))
def etag(lm=None):
hash = hashlib.sha1()
def hash_update(value):
value = value.encode("utf-8")
hash.update(value)
hash_update(repr(self._update_log))
return hash.hexdigest()
def lastmodified():
if os.path.exists(self._update_log_path):
return os.stat(self._update_log_path).st_mtime
else:
return 0
return with_revalidation_checking(
etag_factory=etag, lastmodified_factory=lastmodified
)(view)()
@octoprint.plugin.BlueprintPlugin.route("/check", methods=["GET"])
@no_firstrun_access
@Permissions.PLUGIN_SOFTWAREUPDATE_CHECK.require(403)
def check_for_update(self):
if (
not Permissions.PLUGIN_SOFTWAREUPDATE_CHECK.can()
and not self._settings.global_get(["server", "firstRun"])
):
flask.abort(403)
request_data = flask.request.values
if "targets" in request_data or "check" in request_data:
@@ -1075,9 +1290,13 @@ class SoftwareUpdatePlugin(
)(view)()
@octoprint.plugin.BlueprintPlugin.route("/update", methods=["POST"])
@no_firstrun_access
@Permissions.PLUGIN_SOFTWAREUPDATE_UPDATE.require(403)
def perform_update(self):
if (
not Permissions.PLUGIN_SOFTWAREUPDATE_UPDATE.can()
and not self._settings.global_get(["server", "firstRun"])
):
flask.abort(403)
throttled = self._get_throttled()
if (
throttled
@@ -1228,20 +1447,61 @@ class SoftwareUpdatePlugin(
def get_template_configs(self):
from flask_babel import gettext
return [{"type": "settings", "name": gettext("Software Update")}]
templates = [
{"type": "settings", "name": gettext("Software Update")},
]
if self._is_wizard_update_required():
templates.append(
{
"type": "wizard",
"name": gettext("Update?"),
"template": "softwareupdate_wizard_update.jinja2",
"suffix": "_update",
}
)
if self._is_settings_wizard_required():
templates.append(
{
"type": "wizard",
"name": gettext("Software Update"),
"template": "softwareupdate_wizard_settings.jinja2",
"suffix": "_settings",
}
)
return templates
##~~ WizardPlugin API
def is_wizard_required(self):
def _is_wizard_update_required(self):
firstrun = self._settings.global_get(["server", "firstRun"])
return (
firstrun
and self._is_octoprint_outdated_and_can_update()
and not self._is_settings_wizard_required()
)
def _is_settings_wizard_required(self):
checks = self._get_configured_checks()
check = checks.get("octoprint", None)
checkout_folder = self._get_octoprint_checkout_folder(checks=checks)
return (
check
and "method" in check
and check["method"] == "update_script"
and not checkout_folder
)
return check and check.get("method") == "update_script" and not checkout_folder
def is_wizard_required(self):
return self._is_wizard_update_required() or self._is_settings_wizard_required()
def get_wizard_version(self):
return 1
def get_wizard_details(self):
result = {}
if self._is_wizard_update_required():
information, _, _ = self.get_current_versions()
data = information.get("octoprint", {})
result["update"] = data
return result
##~~ EventHandlerPlugin API
@@ -1276,6 +1536,8 @@ class SoftwareUpdatePlugin(
if check_targets is None:
check_targets = list(checks.keys())
# TODO: caching doesn't take check_targets into account!
update_available = False
update_possible = False
information = {}
@@ -1372,28 +1634,9 @@ class SoftwareUpdatePlugin(
local_name = target_information["local"]["name"]
local_value = target_information["local"]["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"
]
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 = self._get_release_notes(
target_information, populated_check
)
information[target] = {
"updateAvailable": target_update_available,
@@ -1462,6 +1705,24 @@ class SoftwareUpdatePlugin(
return information, update_available, update_possible
def _get_release_notes(self, information, populated_check):
release_notes = None
if information and information["remote"] and information["remote"]["value"]:
if populated_check.get("release_notes"):
release_notes = populated_check["release_notes"]
elif "release_notes" in information["remote"]:
release_notes = information["remote"]["release_notes"]
if release_notes:
release_notes = release_notes.format(
octoprint_version=VERSION,
target_name=information["remote"]["name"],
target_version=information["remote"]["value"],
)
return release_notes
def _get_check_hash(self, check):
def dict_to_sorted_repr(d):
lines = []
@@ -1685,15 +1946,7 @@ class SoftwareUpdatePlugin(
if target_result is not None:
target_results[target] = target_result
if "restart" in check:
target_restart_type = check["restart"]
elif (
"pip" in check
or check.get("method") in self.OCTOPRINT_RESTART_TYPES
):
target_restart_type = "octoprint"
else:
target_restart_type = None
target_restart_type = self._get_restart_type(check)
# if our update requires a restart we have to determine which type
if restart_type is None or (
@@ -1706,6 +1959,9 @@ class SoftwareUpdatePlugin(
# we might have needed to update the config, so we'll save that now
self._settings.save()
# we also need to save our update log changes
self._save_update_log()
# also, we are now longer updating
self._update_in_progress = False
@@ -1721,16 +1977,7 @@ class SoftwareUpdatePlugin(
# one of our updates requires a restart of either type "octoprint" or "environment". Let's see if
# we can actually perform that
restart_command = None
if restart_type == "octoprint":
restart_command = self._settings.global_get(
["server", "commands", "serverRestartCommand"]
)
elif restart_type == "environment":
restart_command = self._settings.global_get(
["server", "commands", "systemRestartCommand"]
)
restart_command = self._get_restart_command(restart_type)
if restart_command:
self._send_client_message(
"restarting",
@@ -1759,8 +2006,22 @@ class SoftwareUpdatePlugin(
information, update_available, update_possible, _, _ = self._get_current_version(
target, check, online=online, credentials=credentials
)
populated_check = self._populated_check(target, check)
def add_update_log(success, text):
self._add_update_log_entry(
target,
information["local"]["value"],
information["remote"]["value"],
success,
text,
display_name=populated_check["displayName"],
release_notes=self._get_release_notes(information, populated_check),
save=False,
)
if not update_available and not force:
add_update_log(False, "Target is already up to date")
return False, None
if not update_possible:
@@ -1769,6 +2030,7 @@ class SoftwareUpdatePlugin(
target
)
)
add_update_log(False, "Update not possible, missing information")
return False, None
if not information.get("compatible", True):
@@ -1777,6 +2039,7 @@ class SoftwareUpdatePlugin(
target
)
)
add_update_log(False, "Update is incompatible")
return False, None
# determine the target version to update to
@@ -1807,7 +2070,6 @@ class SoftwareUpdatePlugin(
### The actual update procedure starts here...
populated_check = self._populated_check(target, check)
try:
self._logger.info(
"Starting update of {} to {}...".format(target, target_version)
@@ -1846,6 +2108,7 @@ class SoftwareUpdatePlugin(
"reason": "Unknown update type",
},
)
add_update_log(False, "Update failed, unknown update type")
return False, None
except exceptions.CannotUpdateOffline:
@@ -1862,6 +2125,8 @@ class SoftwareUpdatePlugin(
"reason": "No internet connection",
},
)
add_update_log(False, "No internet connection")
return False, None
except Exception as e:
self._logger.exception(
@@ -1895,6 +2160,7 @@ class SoftwareUpdatePlugin(
"reason": "unknown",
},
)
add_update_log(False, "Update failed")
else:
# make sure that any external changes to config.yaml are loaded into the system
@@ -1906,6 +2172,8 @@ class SoftwareUpdatePlugin(
del self._version_cache[target]
self._version_cache_dirty = True
add_update_log(True, "Update successful")
return target_error, target_result
def _persist_check_current(self, target, check, current):
@@ -2209,4 +2477,5 @@ def __plugin_load__():
"octoprint.cli.commands": cli.commands,
"octoprint.events.register_custom_events": _register_custom_events,
"octoprint.access.permissions": __plugin_implementation__.get_additional_permissions,
"octoprint.systeminfo.additional_bundle_files": __plugin_implementation__.get_additional_bundle_files,
}
@@ -12,6 +12,7 @@
this.checkUrl = url + "check";
this.updateUrl = url + "update";
this.configureUrl = url + "configure";
this.updatelogUrl = url + "updatelog";
};
OctoPrintSoftwareUpdateClient.prototype.checkEntries = function (
@@ -88,6 +89,10 @@
return this.base.postJson(this.configureUrl, data, opts);
};
OctoPrintSoftwareUpdateClient.prototype.getUpdatelog = function (opts) {
return this.base.get(this.updatelogUrl, opts);
};
OctoPrintClient.registerPluginComponent(
"softwareupdate",
OctoPrintSoftwareUpdateClient
@@ -1 +1 @@
#settings_plugin_softwareupdate_updatelist{display:block;width:auto;overflow-x:hidden;padding-right:2px;margin-bottom:1em}div.swupdate-advanced{margin-bottom:5px}td.settings_plugin_softwareupdate_column_update{width:16px}td.settings_plugin_softwareupdate_column_update a{text-decoration:none;color:#000}td.settings_plugin_softwareupdate_column_information .line{display:block}td.settings_plugin_softwareupdate_column_information .settings_plugin_softwareupdate_release_channel{line-height:20px;height:20px;font-size:9px;margin-bottom:0;vertical-align:baseline}#settings_plugin_softwareupdate_workingdialog_output{font-size:.8em}#settings_plugin_softwareupdate_workingdialog_output .message{font-weight:700}#settings_plugin_softwareupdate_workingdialog_output .separator{font-weight:700;color:#666}#settings_plugin_softwareupdate_workingdialog_output .stdout{color:#333}#settings_plugin_softwareupdate_workingdialog_output .stderr{color:#900}#settings_plugin_softwareupdate_workingdialog_output .call{color:#009}#settings_plugin_softwareupdate_workingdialog_output .message_error{font-weight:700;color:#900}.softwareupdate_notification ul{margin:10px 0 10px 25px}.softwareupdate_notification ul .name{text-overflow:ellipsis;white-space:nowrap;overflow:hidden;display:block}
#settings_plugin_softwareupdate_updatelist{display:block;width:auto;overflow-x:hidden;padding-right:2px;margin-bottom:1em}div.swupdate-advanced{margin-bottom:5px}td.settings_plugin_softwareupdate_column_update{width:16px}td.settings_plugin_softwareupdate_column_update a{text-decoration:none;color:#000}td.settings_plugin_softwareupdate_column_information .line{display:block}td.settings_plugin_softwareupdate_column_information .settings_plugin_softwareupdate_release_channel{line-height:20px;height:20px;font-size:9px;margin-bottom:0;vertical-align:baseline}#settings_plugin_softwareupdate_updatelog_list .line{display:block}#settings_plugin_softwareupdate_updatelog_list td.settings_plugin_softwareupdate_column_datetime{width:150px}#settings_plugin_softwareupdate_workingdialog_output{font-size:.8em}#settings_plugin_softwareupdate_workingdialog_output .message{font-weight:700}#settings_plugin_softwareupdate_workingdialog_output .separator{font-weight:700;color:#666}#settings_plugin_softwareupdate_workingdialog_output .stdout{color:#333}#settings_plugin_softwareupdate_workingdialog_output .stderr{color:#900}#settings_plugin_softwareupdate_workingdialog_output .call{color:#009}#settings_plugin_softwareupdate_workingdialog_output .message_error{font-weight:700;color:#900}.softwareupdate_notification ul{margin:10px 0 10px 25px}.softwareupdate_notification ul .name{text-overflow:ellipsis;white-space:nowrap;overflow:hidden;display:block}
@@ -131,6 +131,14 @@ $(function () {
0
);
self.octoprintData = {
item: undefined,
current: ko.observable("unknown"),
available: ko.observable("unknown")
};
self.updatelog = ko.observableArray([]);
self.availableAndPossible = ko.pureComputed(function () {
return _.filter(self.versions.items(), function (info) {
return info.updateAvailable && info.updatePossible;
@@ -161,6 +169,10 @@ $(function () {
} else {
self._closePopup();
}
if (self.loginState.hasPermission(self.access.permissions.ADMIN)) {
self.requestUpdatelog();
}
};
self._showPopup = function (options, eventListeners, singleButtonNotify) {
@@ -294,68 +306,79 @@ $(function () {
);
};
self._enrichInformation = function (key, information) {
information["key"] = key;
if (
!information.hasOwnProperty("displayName") ||
information.displayName === ""
) {
information.displayName = information.key;
}
if (
!information.hasOwnProperty("displayVersion") ||
information.displayVersion === ""
) {
information.displayVersion = information.information.local.name;
}
if (
!information.hasOwnProperty("releaseNotes") ||
information.releaseNotes === ""
) {
information.releaseNotes = undefined;
}
var fullNameTemplate = gettext("%(name)s: %(version)s");
information.fullNameLocal = _.sprintf(fullNameTemplate, {
name: _.escape(information.displayName),
version: _.escape(information.displayVersion)
});
var fullNameRemoteVars = {
name: _.escape(information.displayName),
version: gettext("unknown")
};
if (
information.hasOwnProperty("information") &&
information.information.hasOwnProperty("remote") &&
information.information.remote.hasOwnProperty("name")
) {
fullNameRemoteVars.version = _.escape(
information.information.remote.name
);
}
information.fullNameRemote = _.sprintf(fullNameTemplate, fullNameRemoteVars);
if (information.releaseChannels && information.releaseChannels.current) {
information.releaseChannels.current = ko.observable(
information.releaseChannels.current
);
information.releaseChannels.current.subscribe(function (selected) {
var patch = {};
patch[key] = {channel: selected};
OctoPrint.plugins.softwareupdate.configure(patch).done(function () {
self.performCheck(false, false, false, [key]);
});
});
}
information.toggleDisabled = function () {
var patch = {};
patch[key] = {disabled: !information.disabled};
OctoPrint.plugins.softwareupdate.configure(patch).done(function () {
self.performCheck(false, false, false, [key]);
});
};
return information;
};
self.fromCheckResponse = function (data, ignoreSeen, showIfNothingNew) {
self.cacheTimestamp(data.timestamp);
var versions = [];
_.each(data.information, function (value, key) {
value["key"] = key;
if (!value.hasOwnProperty("displayName") || value.displayName === "") {
value.displayName = value.key;
}
if (
!value.hasOwnProperty("displayVersion") ||
value.displayVersion === ""
) {
value.displayVersion = value.information.local.name;
}
if (!value.hasOwnProperty("releaseNotes") || value.releaseNotes === "") {
value.releaseNotes = undefined;
}
var fullNameTemplate = gettext("%(name)s: %(version)s");
value.fullNameLocal = _.sprintf(fullNameTemplate, {
name: _.escape(value.displayName),
version: _.escape(value.displayVersion)
});
var fullNameRemoteVars = {
name: _.escape(value.displayName),
version: gettext("unknown")
};
if (
value.hasOwnProperty("information") &&
value.information.hasOwnProperty("remote") &&
value.information.remote.hasOwnProperty("name")
) {
fullNameRemoteVars.version = _.escape(value.information.remote.name);
}
value.fullNameRemote = _.sprintf(fullNameTemplate, fullNameRemoteVars);
if (value.releaseChannels && value.releaseChannels.current) {
value.releaseChannels.current = ko.observable(
value.releaseChannels.current
);
value.releaseChannels.current.subscribe(function (selected) {
var patch = {};
patch[key] = {channel: selected};
OctoPrint.plugins.softwareupdate
.configure(patch)
.done(function () {
self.performCheck(false, false, false, [key]);
});
});
}
value.toggleDisabled = function () {
var patch = {};
patch[key] = {disabled: !value.disabled};
OctoPrint.plugins.softwareupdate.configure(patch).done(function () {
self.performCheck(false, false, false, [key]);
});
};
self._enrichInformation(key, value);
versions.push(value);
});
self.versions.updateItems(versions);
@@ -556,6 +579,16 @@ $(function () {
});
};
self.fromUpdatelogResponse = function (response) {
self.updatelog(response.updatelog);
};
self.requestUpdatelog = function () {
OctoPrint.plugins.softwareupdate
.getUpdatelog()
.done(self.fromUpdatelogResponse);
};
self.iconTitleForEntry = function (data) {
if (data.updatePossible) {
return "";
@@ -655,12 +688,7 @@ $(function () {
};
self.performUpdate = function (force, items) {
if (
!self.loginState.hasPermission(
self.access.permissions.PLUGIN_SOFTWAREUPDATE_UPDATE
)
)
return;
if (!self.updateAccess()) return;
if (self.printerState.isPrinting()) return;
self.updateInProgress = true;
@@ -717,13 +745,16 @@ $(function () {
return self.update(force, self.availableAndPossibleAndEnabled());
};
self.update = function (force, items) {
if (
self.updateInProgress ||
!self.loginState.hasPermission(
self.updateAccess = function () {
return (
self.loginState.hasPermission(
self.access.permissions.PLUGIN_SOFTWAREUPDATE_UPDATE
)
) {
) || CONFIG_FIRST_RUN
);
};
self.update = function (force, items) {
if (self.updateInProgress || !self.updateAccess()) {
self._updateClicked = false;
return;
}
@@ -819,8 +850,10 @@ $(function () {
self._showWorkingDialog = function (title) {
if (
!self.loginState.hasPermission(
self.access.permissions.PLUGIN_SOFTWAREUPDATE_CHECK
!(
self.loginState.hasPermission(
self.access.permissions.PLUGIN_SOFTWAREUPDATE_CHECK
) || CONFIG_FIRST_RUN
)
) {
return;
@@ -897,6 +930,21 @@ $(function () {
self.performCheck();
};
self.onWizardDetails = function (data) {
if (
data.softwareupdate &&
data.softwareupdate.details &&
data.softwareupdate.details.update
) {
var value = data.softwareupdate.details.update;
self._enrichInformation("octoprint", value);
self.octoprintData.item = value;
self.octoprintData.current(value.information.local.name);
self.octoprintData.available(value.information.remote.name);
}
};
self.onDataUpdaterReconnect = function () {
if (self.waitingForRestart) {
self.waitingForRestart = false;
@@ -1139,7 +1187,8 @@ $(function () {
elements: [
"#settings_plugin_softwareupdate",
"#softwareupdate_confirmation_dialog",
"#wizard_plugin_softwareupdate"
"#wizard_plugin_softwareupdate_update",
"#wizard_plugin_softwareupdate_settings"
]
});
});
@@ -33,6 +33,16 @@ td.settings_plugin_softwareupdate_column_information {
}
}
#settings_plugin_softwareupdate_updatelog_list {
.line {
display: block;
}
td.settings_plugin_softwareupdate_column_datetime {
width: 150px;
}
}
#settings_plugin_softwareupdate_workingdialog_output {
font-size: 0.8em;
@@ -59,6 +59,9 @@
before trying to update. Take a look at the displayed warning in the navigation bar to learn about what is
wrong and to get hints on how to solve the problem.
</p>
<p>
Read more on this in <a href="https://faq.octoprint.org/pi-issues" target="_blank" rel="noopener noreferrer">the FAQ</a>.
</p>
{% endtrans %}</div>
<div class="alert" data-bind="visible: printerState.isPrinting()">{% trans %}
<p>
@@ -70,54 +73,85 @@
</p>
{% endtrans %}</div>
<div class="pull-right">
<button class="btn btn-primary" data-bind="click: function() { $root.updateAll(); }, enable: enableUpdateAll, css: {disabled: !enableUpdateAll}"><i class="fas fa-spinner fa-spin" data-bind="visible: updateInProgress"></i> {{ _('Update all') }}</button>
<button class="btn" data-bind="click: function() { $root.performCheck(true, false, true); }, enable: !checking(), css: {disabled: checking()}"><i class="fas fa-spinner fa-spin" data-bind="visible: checking"></i> {{ _('Check for updates') }}</button>
<button class="btn btn-small" data-bind="click: function() { $root.showPluginSettings(); }" title="{{ _('Plugin Configuration')|edq }}"><i class="fas fa-wrench"></i></button>
</div>
<ul class="nav nav-pills">
<li class="active">
<a href="#settings_plugin_softwareupdate_updates" data-toggle="tab">{{ _('Current versions') }}</a>
</li>
<li>
<a href="#settings_plugin_softwareupdate_updatelog" data-toggle="tab">{{ _('Update log') }}</a>
</li>
</ul>
<h3>{{ _('Current versions') }}</h3>
<div class="tab-content">
<div class="tab-pane active" id="settings_plugin_softwareupdate_updates">
<div class="pull-right">
<button class="btn btn-primary" data-bind="click: function() { $root.updateAll(); }, enable: enableUpdateAll, css: {disabled: !enableUpdateAll}"><i class="fas fa-spinner fa-spin" data-bind="visible: updateInProgress"></i> {{ _('Update all') }}</button>
<button class="btn" data-bind="click: function() { $root.performCheck(true, false, true); }, enable: !checking(), css: {disabled: checking()}"><i class="fas fa-spinner fa-spin" data-bind="visible: checking"></i> {{ _('Check for updates') }}</button>
<button class="btn" data-bind="click: function() { $root.showPluginSettings(); }" title="{{ _('Plugin Configuration')|edq }}"><i class="fas fa-wrench"></i></button>
</div>
<div class="swupdate-advanced">
<div><small><a href="javascript:void(0)" class="muted" onclick="$(this).children().toggleClass('fa-caret-right fa-caret-down').parent().parent().parent().next().slideToggle('fast')"><i class="fas fa-caret-right"></i> {{ _('Advanced options') }}</a></small></div>
<div class="hide">
<small class="muted" style="display: block">{{ _('Last cache refresh:') }} <span data-bind="text: cacheTimestampText"></span></small>
<button class="btn btn-block" data-bind="click: function() { $root.performCheck(true, true, true); }, enable: !checking(), css: {disabled: checking()}"><i class="fas fa-spinner fa-spin" data-bind="visible: checking"></i> {{ _('Force check for update (overrides cache used for update checks)') }}</button>
<button class="btn btn-block btn-danger" data-bind="visible: CONFIG_DEBUG, click: function() { $root.updateAll(true); }, enable: enableUpdate() && !checking(), css: {disabled: !enableUpdate() || checking()}"><i class="fas fa-spinner fa-spin" data-bind="visible: checking"></i> {{ _('Force update all (even if no new versions are available)') }}</button>
<h3>{{ _('Current versions') }}</h3>
<div class="swupdate-advanced">
<div><small><a href="javascript:void(0)" class="muted" onclick="$(this).children().toggleClass('fa-caret-right fa-caret-down').parent().parent().parent().next().slideToggle('fast')"><i class="fas fa-caret-right"></i> {{ _('Advanced options') }}</a></small></div>
<div class="hide">
<small class="muted" style="display: block">{{ _('Last cache refresh:') }} <span data-bind="text: cacheTimestampText"></span></small>
<button class="btn btn-block" data-bind="click: function() { $root.performCheck(true, true, true); }, enable: !checking(), css: {disabled: checking()}"><i class="fas fa-spinner fa-spin" data-bind="visible: checking"></i> {{ _('Force check for update (overrides cache used for update checks)') }}</button>
<button class="btn btn-block btn-danger" data-bind="visible: CONFIG_DEBUG, click: function() { $root.updateAll(true); }, enable: enableUpdate() && !checking(), css: {disabled: !enableUpdate() || checking()}"><i class="fas fa-spinner fa-spin" data-bind="visible: checking"></i> {{ _('Force update all (even if no new versions are available)') }}</button>
</div>
</div>
<div id="settings_plugin_softwareupdate_updatelist">
<table class="table table-striped table-hover table-condensed table-hover">
<tbody data-bind="foreach: versions.paginatedItems">
<tr data-bind="attr: {title: displayName}">
<td class="settings_plugin_softwareupdate_column_update">
<a href="javascript:void(0)" data-bind="visible: compatible, click: toggleDisabled"><i class="far" data-bind="css: { muted: !updateAvailable, 'fa-bell': !disabled, 'fa-bell-slash': disabled }" title="{{ _('Update available')|edq }}"></i></a>
<span data-bind="visible: !compatible" class="muted"><i class="fas fa-power-off" title="{{ _('Not compatible') }}|edq"></i></span>
</td>
<td class="settings_plugin_softwareupdate_column_information">
<a href="javascript:void(0)" data-bind="click: function() { $root.update(false, [$data]) }, visible: $root.enableUpdate() && updateAvailable && updatePossible" class="btn btn-primary pull-right">{{ _('Update') }}</a>
<strong data-bind="text: displayName"></strong>: <span data-bind="text: displayVersion"></span> <span data-bind="invisible: updatePossible"><i class="fas fa-exclamation-triangle" data-bind="css: {'fa-unlink': !online && information && information.needs_online, 'fa-exclamation-triangle': !(!online && information && information.needs_online)}, attr: {title: $root.iconTitleForEntry($data)}"></i></span><br>
<small data-bind="visible: compatible" class="muted">
<span data-bind="visible: releaseChannels && releaseChannels.available" class="line">{{ _('Release Channel:') }} <select class="settings_plugin_softwareupdate_release_channel" data-bind="visible: releaseChannels && releaseChannels.available, value: releaseChannels.current, options: releaseChannels.available, optionsText: 'name', optionsValue: 'channel'"></select> <a href="https://faq.octoprint.org/using-release-channels" target="_blank"><i class="fas fa-question-circle"></i></a></span>
<span class="line">{{ _('Installed:') }} <span data-bind="text: information.local.name"></span></span>
<span class="line">{{ _('Available:') }} <span data-bind="text: information.remote.name"></span></span>
<span class="line" data-bind="visible: releaseNotes">{{ _('Release Notes:') }} <a data-bind="attr: {href: releaseNotes}, text: releaseNotes" target="_blank" rel="noreferrer noopener"></a></span>
<span class="line text-error" data-bind="visible: error, text: $root.errorTextForEntry($data)"></span>
</small>
<small data-bind="visible: !compatible">
<span class="line text-error">{{ _('Newer versions of this plugin are not compatible to this setup.') }}</span>
</small>
</td>
</tr>
</tbody>
</table>
</div>
</div>
<div class="tab-pane" id="settings_plugin_softwareupdate_updatelog">
<h3>{{ _('Update log') }}</h3>
<div id="settings_plugin_softwareupdate_updatelog_list">
<table class="table table-striped table-hover table-condensed table-hover">
<tbody data-bind="foreach: updatelog">
<tr>
<td class="settings_plugin_softwareupdate_column_datetime" data-bind="text: datetime"></td>
<td>
<span class="line" data-bind="css: { 'text-error': !success, 'text-success': success }"><strong data-bind="text: display_name"></strong> <span data-bind="text: current_version"></span> ➡ <span data-bind="text: target_version"></span></span>
<span class="line" data-bind="text: text"></span>
<span class="line" data-bind="visible: release_notes"><a data-bind="attr: {href: release_notes}" target="_blank" rel="noreferrer noopener">{{ _('Release Notes') }}</a></span>
</td>
</tr>
</tbody>
</table>
</div>
<small>{{ _('Please note that the update log will only contain entries for updates performed through OctoPrint\'s Software Update plugin.') }}</small>
</div>
</div>
<div id="settings_plugin_softwareupdate_updatelist">
<table class="table table-striped table-hover table-condensed table-hover">
<tbody data-bind="foreach: versions.paginatedItems">
<tr data-bind="attr: {title: displayName}">
<td class="settings_plugin_softwareupdate_column_update">
<a href="javascript:void(0)" data-bind="visible: compatible, click: toggleDisabled"><i class="far" data-bind="css: { muted: !updateAvailable, 'fa-bell': !disabled, 'fa-bell-slash': disabled }" title="{{ _('Update available')|edq }}"></i></a>
<span data-bind="visible: !compatible" class="muted"><i class="fas fa-power-off" title="{{ _('Not compatible') }}|edq"></i></span>
</td>
<td class="settings_plugin_softwareupdate_column_information">
<a href="javascript:void(0)" data-bind="click: function() { $root.update(false, [$data]) }, visible: $root.enableUpdate() && updateAvailable && updatePossible" class="btn btn-primary pull-right">{{ _('Update') }}</a>
<strong data-bind="text: displayName"></strong>: <span data-bind="text: displayVersion"></span> <span data-bind="invisible: updatePossible"><i class="fas fa-exclamation-triangle" data-bind="css: {'fa-unlink': !online && information && information.needs_online, 'fa-exclamation-triangle': !(!online && information && information.needs_online)}, attr: {title: $root.iconTitleForEntry($data)}"></i></span><br>
<small data-bind="visible: compatible" class="muted">
<span data-bind="visible: releaseChannels && releaseChannels.available" class="line">{{ _('Release Channel:') }} <select class="settings_plugin_softwareupdate_release_channel" data-bind="visible: releaseChannels && releaseChannels.available, value: releaseChannels.current, options: releaseChannels.available, optionsText: 'name', optionsValue: 'channel'"></select> <a href="https://faq.octoprint.org/using-release-channels" target="_blank"><i class="fas fa-question-circle"></i></a></span>
<span class="line">{{ _('Installed:') }} <span data-bind="text: information.local.name"></span></span>
<span class="line">{{ _('Available:') }} <span data-bind="text: information.remote.name"></span></span>
<span class="line" data-bind="visible: releaseNotes">{{ _('Release Notes:') }} <a data-bind="attr: {href: releaseNotes}, text: releaseNotes" target="_blank" rel="noreferrer noopener"></a></span>
<span class="line text-error" data-bind="visible: error, text: $root.errorTextForEntry($data)"></span>
</small>
<small data-bind="visible: !compatible">
<span class="line text-error">{{ _('Newer versions of this plugin are not compatible to this setup.') }}</span>
</small>
</td>
</tr>
</tbody>
</table>
</div>
<div id="settings_plugin_softwareupdate_configurationdialog" class="modal hide fade">
<div id="settings_plugin_softwareupdate_configurationdialog" class="modal hide fade-in">
<div class="modal-header">
<a href="#" class="close" data-dismiss="modal" aria-hidden="true">&times;</a>
<h3>{{ _('Plugin Configuration') }}</h3>
@@ -164,14 +198,14 @@
</div>
</div>
<div id="settings_plugin_softwareupdate_workingdialog" class="modal hide fade">
<div id="settings_plugin_softwareupdate_workingdialog" class="modal hide fade-in">
<div class="modal-header">
<h3 data-bind="text: workingTitle"></h3>
</div>
<div class="modal-body">
<pre id="settings_plugin_softwareupdate_workingdialog_output" class="pre-scrollable pre-output" style="height: 170px; display: none" data-bind="visible: loginState.isAdmin, foreach: loglines"><span data-bind="text: line, css: {stdout: stream == 'stdout', stderr: stream == 'stderr', call: stream == 'call', message: stream == 'message'}"></span></pre>
<p style="display: none" data-bind="visible: !loginState.isAdmin() && $root.working()"><i class="fas fa-spinner fa-spin"></i> {{ _('Update in progress, please wait.') }}</p>
<p style="display: none" data-bind="visible: !loginState.isAdmin() && !$root.working()">{{ _('Update done, please close this window.') }}</p>
<pre id="settings_plugin_softwareupdate_workingdialog_output" class="pre-scrollable pre-output" style="height: 170px; display: none" data-bind="visible: $root.updateAccess(), foreach: loglines"><span data-bind="text: line, css: {stdout: stream == 'stdout', stderr: stream == 'stderr', call: stream == 'call', message: stream == 'message'}"></span></pre>
<p style="display: none" data-bind="visible: !$root.updateAccess() && $root.working()"><i class="fas fa-spinner fa-spin"></i> {{ _('Update in progress, please wait.') }}</p>
<p style="display: none" data-bind="visible: !$root.updateAccess() && !$root.working()">{{ _('Update done, please close this window.') }}</p>
</div>
<div class="modal-footer">
<button class="btn" data-dismiss="modal" data-bind="enable: !$root.working()" aria-hidden="true">{{ _('Close') }}</button>
@@ -0,0 +1,9 @@
<h3>{{ _('Update?') }}</h3>
{% trans %}<p>
You are about to set up OctoPrint <span data-bind="text: octoprintData.current"></span>
but <span data-bind="text: octoprintData.available"></span> is available. It is strongly
recommended to update to the latest version before you continue.
</p>{% endtrans %}
<a href="javascript:void(0)" data-bind="click: function() { $root.update(false, [$root.octoprintData.item]) }" class="btn btn-primary btn-block">{{ _('Update') }}</a>
+35 -1
View File
@@ -38,6 +38,7 @@ class TrackingPlugin(
octoprint.plugin.AssetPlugin,
octoprint.plugin.WizardPlugin,
octoprint.plugin.EventHandlerPlugin,
octoprint.plugin.SimpleApiPlugin,
):
def __init__(self):
self._environment = None
@@ -76,6 +77,7 @@ class TrackingPlugin(
"printer_safety_check": True,
"throttled": True,
"slicing": True,
"webui_load": True,
},
}
@@ -94,6 +96,26 @@ class TrackingPlugin(
# tracking was just enabled, let's start up tracking
self._start_tracking()
##~~ SimpleApiPlugin
def get_api_commands(self):
return {"track": ["event", "payload"]}
def on_api_command(self, command, data):
if command != "track":
return
event = data.pop("event")
if event == "webui_load":
payload = data.get("payload", {})
browser_name = payload.get("browser_name")
browser_version = payload.get("browser_version")
os_name = payload.get("os_name")
os_version = payload.get("os_version")
if all((browser_name, browser_version, os_name, os_version)):
self._track_webui_load(browser_name, browser_version, os_name, os_version)
##~~ EnvironmentDetectionPlugin
def on_environment_detected(self, environment, *args, **kwargs):
@@ -191,7 +213,7 @@ class TrackingPlugin(
##~~ AssetPlugin
def get_assets(self):
return {"js": ["js/usage.js"]}
return {"js": ["js/usage.js"], "clientjs": ["clientjs/usage.js"]}
##~~ WizardPlugin
@@ -280,6 +302,18 @@ class TrackingPlugin(
self._track("shutdown")
def _track_webui_load(self, browser_name, browser_version, os_name, os_version):
if not self._settings.get_boolean(["events", "webui_load"]):
return
self._track(
"webui_load",
browser_name=browser_name,
browser_version=browser_version,
os_name=os_name,
os_version=os_version,
)
def _track_plugin_event(self, event, payload):
if not self._settings.get_boolean(["events", "plugin"]):
return
@@ -0,0 +1,23 @@
(function (global, factory) {
if (typeof define === "function" && define.amd) {
define(["OctoPrintClient"], factory);
} else {
factory(global.OctoPrintClient);
}
})(this, function (OctoPrintClient) {
var OctoPrintTrackingClient = function (base) {
this.base = base;
};
OctoPrintTrackingClient.prototype.track = function (event, payload, opts) {
return this.base.simpleApiCommand(
"tracking",
"track",
{event: event, payload: payload},
opts
);
};
OctoPrintClient.registerPluginComponent("tracking", OctoPrintTrackingClient);
return OctoPrintTrackingClient;
});
@@ -10,6 +10,15 @@ $(function () {
self.active = ko.observable();
self.required = false;
self.onStartupComplete = function () {
OctoPrint.plugins.tracking.track("webui_load", {
browser_name: OctoPrint.coreui.browser.browser_name,
browser_version: OctoPrint.coreui.browser.browser_version,
os_name: OctoPrint.coreui.browser.os_name,
os_version: OctoPrint.coreui.browser.os_version
});
};
self.enableUsage = function () {
self.settingsViewModel.settings.plugins.tracking.enabled(true);
self.decision(true);
@@ -52,6 +52,9 @@
<label class="checkbox">
<input type="checkbox" data-bind="checked: settings.plugins.tracking.events.slicing"> {{ _('Onboard slicing actions') }}
</label>
<label class="checkbox">
<input type="checkbox" data-bind="checked: settings.plugins.tracking.events.webui_load"> {{ _('Web interface load') }}
</label>
</div>
</div>
</form>
@@ -30,7 +30,7 @@ class VirtualPrinterPlugin(
"smoothieTemperatureReporting": False,
"klipperTemperatureReporting": False,
"reprapfwM114": False,
"sdFiles": {"size": True, "longname": False},
"sdFiles": {"size": True, "longname": False, "longname_quoted": True},
"throttle": 0.01,
"sendWait": True,
"waitInterval": 1.0,
@@ -54,7 +54,9 @@ class VirtualPrinterPlugin(
"capabilities": {
"AUTOREPORT_TEMP": True,
"AUTOREPORT_SD_STATUS": True,
"AUTOREPORT_POS": False,
"EMERGENCY_PARSER": True,
"EXTENDED_M20": False,
},
"m114FormatString": "X:{x} Y:{y} Z:{z} E:{e[current]} Count: A:{a} B:{b} C:{c}",
"m105TargetFormatString": "{heater}:{actual:.2f}/ {target:.2f}",
@@ -188,6 +188,7 @@ class VirtualPrinter(object):
self._temperature_reporter = None
self._sdstatus_reporter = None
self._pos_reporter = None
self.current_line = 0
self.lastN = 0
@@ -607,7 +608,7 @@ class VirtualPrinter(object):
def _gcode_M20(self, data):
# type: (str) -> None
if self._sdCardReady:
self._listSd()
self._listSd(incl_long="L" in data)
# noinspection PyUnusedLocal
def _gcode_M21(self, data):
@@ -704,26 +705,7 @@ class VirtualPrinter(object):
# noinspection PyUnusedLocal
def _gcode_M114(self, data):
# type: (str) -> bool
m114FormatString = self._settings.get(["m114FormatString"])
e = {index: value for index, value in enumerate(self._lastE)}
e["current"] = self._lastE[self.currentExtruder]
e["all"] = " ".join(
[
"E{}:{}".format(num, self._lastE[self.currentExtruder])
for num in range(self.extruderCount)
]
)
output = m114FormatString.format(
x=self._lastX,
y=self._lastY,
z=self._lastZ,
e=e,
f=self._lastF,
a=int(self._lastX * 100),
b=int(self._lastY * 100),
c=int(self._lastZ * 100),
)
output = self._generatePositionOutput()
if not self._okBeforeCommandOutput:
ok = self._ok()
if ok:
@@ -750,6 +732,22 @@ class VirtualPrinter(object):
except AttributeError:
self._send("echo:")
def _gcode_M154(self, data):
# type: (str) -> None
matchS = re.search(r"S([0-9]+)", data)
if matchS is not None:
interval = int(matchS.group(1))
if self._pos_reporter is not None:
self._pos_reporter.cancel()
if interval > 0:
self._pos_reporter = RepeatedTimer(
interval, lambda: self._send(self._generatePositionOutput())
)
self._pos_reporter.start()
else:
self._pos_reporter = None
def _gcode_M155(self, data):
# type: (str) -> None
matchS = re.search(r"S([0-9]+)", data)
@@ -1415,10 +1413,13 @@ class VirtualPrinter(object):
except Exception:
self._logger.exception("While handling %r", data)
def _listSd(self):
def _listSd(self, incl_long=False):
if self._settings.get_boolean(["sdFiles", "size"]):
if self._settings.get_boolean(["sdFiles", "longname"]):
line = "{dosname} {size} {name}"
if self._settings.get_boolean(["sdFiles", "longname"]) or incl_long:
if self._settings.get_boolean(["sdFiles", "longname_quoted"]):
line = '{dosname} {size} "{name}"'
else:
line = "{dosname} {size} {name}"
else:
line = "{dosname} {size}"
else:
@@ -1498,6 +1499,29 @@ class VirtualPrinter(object):
else:
self._send("Not SD printing")
def _generatePositionOutput(self):
# type: () -> str
m114FormatString = self._settings.get(["m114FormatString"])
e = {index: value for index, value in enumerate(self._lastE)}
e["current"] = self._lastE[self.currentExtruder]
e["all"] = " ".join(
[
"E{}:{}".format(num, self._lastE[self.currentExtruder])
for num in range(self.extruderCount)
]
)
output = m114FormatString.format(
x=self._lastX,
y=self._lastY,
z=self._lastZ,
e=e,
f=self._lastF,
a=int(self._lastX * 100),
b=int(self._lastY * 100),
c=int(self._lastZ * 100),
)
return output
def _generateTemperatureOutput(self):
# type: () -> str
if self._settings.get_boolean(["repetierStyleTargetTemperature"]):
+1 -2
View File
@@ -1,6 +1,4 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
"""
This module defines the interface for communicating with a connected printer.
@@ -16,6 +14,7 @@ abstracted version of the actual printer communication.
.. autoclass:: PrinterCallback
:members:
"""
from __future__ import absolute_import, division, print_function, unicode_literals
__author__ = "Gina Häußge <osd@foosel.net>"
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
+1 -2
View File
@@ -1,6 +1,4 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
"""
This module contains printer profile related code.
@@ -141,6 +139,7 @@ A printer profile is a ``dict`` of the following structure:
.. autoclass:: InvalidProfileError
"""
from __future__ import absolute_import, division, print_function, unicode_literals
__author__ = "Gina Häußge <osd@foosel.net>"
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
+15 -17
View File
@@ -516,7 +516,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
)
)
command = "G1 {}".format(
command = "G0 {}".format(
" ".join(["{}{}".format(axis.upper(), amt) for axis, amt in axes.items()])
)
@@ -1086,8 +1086,8 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
self._comm.refreshSdFiles(
tags=kwargs.get("tags", set()) | {"trigger:printer.refresh_sd_files"}
)
if blocking:
self._sdFilelistAvailable.wait(kwargs.get("timeout", 10000))
if blocking and not self.is_printing():
self._sdFilelistAvailable.wait(kwargs.get("timeout", 10))
# ~~ state monitoring
@@ -1191,6 +1191,8 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
statisticalTotalPrintTime,
statisticalTotalPrintTimeType,
)
if printTimeLeft is not None:
printTimeLeft = int(printTimeLeft)
except Exception:
self._logger.exception(
"Error while estimating print time via {}".format(estimator)
@@ -1331,33 +1333,29 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
self._logger.exception("Error generating fileData")
fileData = None
if fileData is not None:
if "display" in fileData:
if fileData.get("display"):
display_name = fileData["display"]
if "analysis" in fileData:
if (
estimatedPrintTime is None
and "estimatedPrintTime" in fileData["analysis"]
if isinstance(fileData.get("analysis"), dict):
if estimatedPrintTime is None and fileData["analysis"].get(
"estimatedPrintTime"
):
estimatedPrintTime = fileData["analysis"][
"estimatedPrintTime"
]
if "filament" in fileData["analysis"]:
if fileData["analysis"].get("filament"):
filament = fileData["analysis"]["filament"]
if "statistics" in fileData:
if isinstance(fileData.get("statistics"), dict):
printer_profile = (
self._printerProfileManager.get_current_or_default()["id"]
)
if (
"averagePrintTime" in fileData["statistics"]
and printer_profile
in fileData["statistics"]["averagePrintTime"]
if printer_profile in fileData["statistics"].get(
"averagePrintTime", {}
):
averagePrintTime = fileData["statistics"]["averagePrintTime"][
printer_profile
]
if (
"lastPrintTime" in fileData["statistics"]
and printer_profile in fileData["statistics"]["lastPrintTime"]
if printer_profile in fileData["statistics"].get(
"lastPrintTime", {}
):
lastPrintTime = fileData["statistics"]["lastPrintTime"][
printer_profile
+11 -6
View File
@@ -410,7 +410,10 @@ class Server(object):
storage_managers[
octoprint.filemanager.FileDestinations.LOCAL
] = octoprint.filemanager.storage.LocalFileStorage(
self._settings.getBaseFolder("uploads")
self._settings.getBaseFolder("uploads"),
really_universal=self._settings.getBoolean(
["feature", "enforceReallyUniversalFilenames"]
),
)
fileManager = octoprint.filemanager.FileManager(
@@ -1345,14 +1348,16 @@ class Server(object):
ReverseProxiedEnvironment,
)
s = settings()
app.config["TEMPLATES_AUTO_RELOAD"] = True
app.config["JSONIFY_PRETTYPRINT_REGULAR"] = False
# we must not set this before TEMPLATES_AUTO_RELOAD is set to True or that won't take
app.debug = self._debug
# setup octoprint's flask json serialization/deserialization
app.json_encoder = OctoPrintJsonEncoder
app.debug = self._debug
app.config["TEMPLATES_AUTO_RELOAD"] = True
app.config["JSONIFY_PRETTYPRINT_REGULAR"] = False
s = settings()
secret_key = s.get(["server", "secretKey"])
if not secret_key:
@@ -2053,11 +2058,11 @@ class Server(object):
"js/lib/moment-with-locales.min.js",
"js/lib/pusher.color.min.js",
"js/lib/detectmobilebrowser.js",
"js/lib/ua-parser.min.js",
"js/lib/md5.min.js",
"js/lib/bootstrap-slider-knockout-binding.js",
"js/lib/loglevel.min.js",
"js/lib/sockjs.min.js",
"js/lib/ResizeSensor.js",
"js/lib/hls.js",
"js/lib/less.js",
]
+56 -17
View File
@@ -37,6 +37,11 @@ from octoprint.server.util.flask import (
from octoprint.settings import settings, valid_boolean_trues
from octoprint.util import sv, time_this
try:
from urllib.parse import quote as urlquote
except ImportError:
from urllib import quote as urlquote # noqa: F401
# ~~ GCODE file handling
_file_cache = {}
@@ -448,7 +453,7 @@ def _getFileList(
+ "downloads/files/"
+ FileDestinations.LOCAL
+ "/"
+ file_or_folder["path"],
+ urlquote(file_or_folder["path"]),
}
result.append(file_or_folder)
@@ -702,7 +707,7 @@ def uploadGcodeFile(target):
+ "downloads/files/"
+ FileDestinations.LOCAL
+ "/"
+ filename,
+ urlquote(filename),
},
}
}
@@ -794,6 +799,7 @@ def gcodeFileCommand(filename, target):
# valid file commands, dict mapping command name to mandatory parameters
valid_commands = {
"select": [],
"unselect": [],
"slice": [],
"analyse": [],
"copy": ["destination"],
@@ -842,6 +848,26 @@ def gcodeFileCommand(filename, target):
filenameToSelect = fileManager.path_on_disk(target, filename)
printer.select_file(filenameToSelect, sd, printAfterLoading, user)
elif command == "unselect":
with Permissions.FILES_SELECT.require(403):
if not printer.is_ready():
return make_response(
"Printer is already printing, cannot unselect current file", 409
)
_, currentFilename = _getCurrentFile()
if currentFilename is None:
return make_response(
"Cannot unselect current file when there is no file selected", 409
)
if filename != currentFilename and filename != "current":
return make_response(
"Only the currently selected file can be unselected", 400
)
printer.unselect_file()
elif command == "slice":
with Permissions.SLICE.require(403):
if not _verifyFileExists(target, filename):
@@ -1013,7 +1039,10 @@ def gcodeFileCommand(filename, target):
abort(404, description="Unknown profile")
location = url_for(
".readGcodeFile", target=target, filename=full_path, _external=True
".readGcodeFile",
target=target,
filename=full_path,
_external=True,
)
result = {
"name": destination,
@@ -1026,7 +1055,7 @@ def gcodeFileCommand(filename, target):
+ "downloads/files/"
+ target
+ "/"
+ full_path,
+ urlquote(full_path),
},
}
@@ -1067,18 +1096,25 @@ def gcodeFileCommand(filename, target):
target, dst_path, fileManager.sanitize_name(target, dst_name)
)
if (
_verifyFolderExists(target, destination)
and sanitized_destination != filename
):
# destination is an existing folder and not ourselves (= display rename), we'll assume we are supposed
# to move filename to this folder under the same name
destination = fileManager.join_path(target, destination, name)
# Check for exception thrown by _verifyFolderExists, if outside the root directory
try:
if (
_verifyFolderExists(target, destination)
and sanitized_destination != filename
):
# destination is an existing folder and not ourselves (= display rename), we'll assume we are supposed
# to move filename to this folder under the same name
destination = fileManager.join_path(target, destination, name)
if _verifyFileExists(target, destination) or _verifyFolderExists(
target, destination
):
abort(409, description="File or folder does already exist")
if _verifyFileExists(target, destination) or _verifyFolderExists(
target, destination
):
abort(409, description="File or folder does already exist")
except Exception:
abort(
409, description="Exception thrown by storage, bad folder/file name?"
)
is_file = fileManager.file_exists(target, filename)
is_folder = fileManager.folder_exists(target, filename)
@@ -1126,7 +1162,10 @@ def gcodeFileCommand(filename, target):
fileManager.move_folder(target, filename, destination)
location = url_for(
".readGcodeFile", target=target, filename=destination, _external=True
".readGcodeFile",
target=target,
filename=destination,
_external=True,
)
result = {
"name": name,
@@ -1140,7 +1179,7 @@ def gcodeFileCommand(filename, target):
+ "downloads/files/"
+ target
+ "/"
+ destination
+ urlquote(destination)
)
r = make_response(jsonify(result), 201)
+43 -3
View File
@@ -6,6 +6,7 @@ __license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agp
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
import logging
import re
from flask import abort, jsonify, request
from flask_login import current_user
@@ -23,6 +24,7 @@ from octoprint.settings import settings, valid_boolean_trues
FOLDER_TYPES = ("uploads", "timelapse", "timelapse_tmp", "logs", "watched")
FOLDER_MAPPING = {"timelapseTmp": "timelapse_tmp"}
TIMELAPSE_BITRATE_PATTERN = re.compile(r"\d+[KMGTPEZY]?i?B?", flags=re.IGNORECASE)
def _lastmodified():
@@ -139,6 +141,7 @@ def getSettings():
"flipH": s.getBoolean(["webcam", "flipH"]),
"flipV": s.getBoolean(["webcam", "flipV"]),
"rotate90": s.getBoolean(["webcam", "rotate90"]),
"cacheBuster": s.getBoolean(["webcam", "cacheBuster"]),
},
"feature": {
"temperatureGraph": s.getBoolean(["feature", "temperatureGraph"]),
@@ -164,6 +167,7 @@ def getSettings():
"port": connectionOptions["portPreference"],
"baudrate": connectionOptions["baudratePreference"],
"exclusive": s.getBoolean(["serial", "exclusive"]),
"lowLatency": s.getBoolean(["serial", "lowLatency"]),
"portOptions": connectionOptions["ports"],
"baudrateOptions": connectionOptions["baudrates"],
"autoconnect": s.getBoolean(["serial", "autoconnect"]),
@@ -187,6 +191,7 @@ def getSettings():
"timeoutSdStatusAutoreport": s.getFloat(
["serial", "timeout", "sdStatusAutoreport"]
),
"timeoutPosAutoreport": s.getFloat(["serial", "timeout", "posAutoreport"]),
"timeoutBaudrateDetectionPause": s.getFloat(
["serial", "timeout", "baudrateDetectionPause"]
),
@@ -201,6 +206,7 @@ def getSettings():
"longRunningCommands": s.get(["serial", "longRunningCommands"]),
"checksumRequiringCommands": s.get(["serial", "checksumRequiringCommands"]),
"blockedCommands": s.get(["serial", "blockedCommands"]),
"ignoredCommands": s.get(["serial", "ignoredCommands"]),
"pausingCommands": s.get(["serial", "pausingCommands"]),
"emergencyCommands": s.get(["serial", "emergencyCommands"]),
"helloCommand": s.get(["serial", "helloCommand"]),
@@ -246,10 +252,14 @@ def getSettings():
"capAutoreportSdStatus": s.getBoolean(
["serial", "capabilities", "autoreport_sdstatus"]
),
"capAutoreportPos": s.getBoolean(
["serial", "capabilities", "autoreport_pos"]
),
"capBusyProtocol": s.getBoolean(["serial", "capabilities", "busy_protocol"]),
"capEmergencyParser": s.getBoolean(
["serial", "capabilities", "emergency_parser"]
),
"capExtendedM20": s.getBoolean(["serial", "capabilities", "extended_m20"]),
"resendRatioThreshold": s.getInt(["serial", "resendRatioThreshold"]),
"resendRatioStart": s.getInt(["serial", "resendRatioStart"]),
},
@@ -577,8 +587,14 @@ def _saveSettings(data):
abort(400, description="Invalid webcam.ffmpegCommandline setting")
else:
s.set(["webcam", "ffmpegCommandline"], commandline)
if "bitrate" in data["webcam"]:
s.set(["webcam", "bitrate"], data["webcam"]["bitrate"])
if "bitrate" in data["webcam"] and data["webcam"]["bitrate"]:
bitrate = str(data["webcam"]["bitrate"])
if not TIMELAPSE_BITRATE_PATTERN.match(bitrate):
abort(
400,
description="Invalid webcam.bitrate setting, needs to be a valid ffmpeg bitrate",
)
s.set(["webcam", "bitrate"], bitrate)
if "ffmpegThreads" in data["webcam"]:
s.setInt(["webcam", "ffmpegThreads"], data["webcam"]["ffmpegThreads"])
if "ffmpegVideoCodec" in data["webcam"] and data["webcam"][
@@ -593,6 +609,8 @@ def _saveSettings(data):
s.setBoolean(["webcam", "flipV"], data["webcam"]["flipV"])
if "rotate90" in data["webcam"]:
s.setBoolean(["webcam", "rotate90"], data["webcam"]["rotate90"])
if "cacheBuster" in data["webcam"]:
s.setBoolean(["webcam", "cacheBuster"], data["webcam"]["cacheBuster"])
if "feature" in data:
if "temperatureGraph" in data["feature"]:
@@ -643,7 +661,7 @@ def _saveSettings(data):
if "runAt" in data["gcodeAnalysis"]:
s.set(["gcodeAnalysis", "runAt"], data["gcodeAnalysis"]["runAt"])
if "bedZ" in data["gcodeAnalysis"]:
s.setBoolean(["gcodeAnalysis", "bedZ"], data["gcodeAnalysis"]["bedZ"])
s.setFloat(["gcodeAnalysis", "bedZ"], data["gcodeAnalysis"]["bedZ"])
if "serial" in data:
if "autoconnect" in data["serial"]:
@@ -654,6 +672,8 @@ def _saveSettings(data):
s.setInt(["serial", "baudrate"], data["serial"]["baudrate"])
if "exclusive" in data["serial"]:
s.setBoolean(["serial", "exclusive"], data["serial"]["exclusive"])
if "lowLatency" in data["serial"]:
s.setBoolean(["serial", "lowLatency"], data["serial"]["lowLatency"])
if "timeoutConnection" in data["serial"]:
s.setFloat(
["serial", "timeout", "connection"],
@@ -714,6 +734,12 @@ def _saveSettings(data):
data["serial"]["timeoutSdStatusAutoreport"],
min=0.0,
)
if "timeoutPosAutoreport" in data["serial"]:
s.setFloat(
["serial", "timeout", "posAutoreport"],
data["serial"]["timeoutPosAutoreport"],
min=0.0,
)
if "timeoutBaudrateDetectionPause" in data["serial"]:
s.setFloat(
["serial", "timeout", "baudrateDetectionPause"],
@@ -763,6 +789,10 @@ def _saveSettings(data):
data["serial"]["blockedCommands"], (list, tuple)
):
s.set(["serial", "blockedCommands"], data["serial"]["blockedCommands"])
if "ignoredCommands" in data["serial"] and isinstance(
data["serial"]["ignoredCommands"], (list, tuple)
):
s.set(["serial", "ignoredCommands"], data["serial"]["ignoredCommands"])
if "pausingCommands" in data["serial"] and isinstance(
data["serial"]["pausingCommands"], (list, tuple)
):
@@ -892,6 +922,11 @@ def _saveSettings(data):
["serial", "capabilities", "autoreport_sdstatus"],
data["serial"]["capAutoreportSdStatus"],
)
if "capAutoreportPos" in data["serial"]:
s.setBoolean(
["serial", "capabilities", "autoreport_pos"],
data["serial"]["capAutoreportPos"],
)
if "capBusyProtocol" in data["serial"]:
s.setBoolean(
["serial", "capabilities", "busy_protocol"],
@@ -902,6 +937,11 @@ def _saveSettings(data):
["serial", "capabilities", "emergency_parser"],
data["serial"]["capEmergencyParser"],
)
if "capExtendedM20" in data["serial"]:
s.setBoolean(
["serial", "capabilities", "extended_m20"],
data["serial"]["capExtendedM20"],
),
if "resendRatioThreshold" in data["serial"]:
s.setInt(
["serial", "resendRatioThreshold"], data["serial"]["resendRatioThreshold"]
+52 -4
View File
@@ -6,6 +6,7 @@ __copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms
import collections
import logging
import re
import threading
import psutil
@@ -15,6 +16,7 @@ from flask_babel import gettext
from octoprint.access.permissions import Permissions
from octoprint.logging import prefix_multilines
from octoprint.plugin import plugin_manager
from octoprint.server import NO_CONTENT
from octoprint.server.api import api
from octoprint.server.util.flask import get_remote_address, no_firstrun_access
@@ -98,6 +100,7 @@ def performSystemAction():
def retrieveSystemCommands():
return jsonify(
core=_to_client_specs(_get_core_command_specs()),
plugin=_to_client_specs(_get_plugin_command_specs()),
custom=_to_client_specs(_get_custom_command_specs()),
)
@@ -110,6 +113,8 @@ def retrieveSystemCommandsForSource(source):
specs = _get_core_command_specs()
elif source == "custom":
specs = _get_custom_command_specs()
elif source == "plugin":
specs = _get_plugin_command_specs()
else:
abort(404)
@@ -225,6 +230,8 @@ def _get_command_spec(source, action):
return _get_core_command_spec(action)
elif source == "custom":
return _get_custom_command_spec(action)
elif source == "plugin":
return _get_plugin_command_spec(action)
else:
return None
@@ -288,6 +295,50 @@ def _get_core_command_spec(action):
return available_actions[action]
_plugin_action_regex = re.compile(r"[a-z0-9_-]+")
def _get_plugin_command_specs(plugin=None):
specs = collections.OrderedDict()
hooks = plugin_manager().get_hooks("octoprint.system.additional_commands")
if plugin is not None:
if plugin in hooks:
hooks = {plugin: hooks[plugin]}
else:
hooks = {}
for name, hook in hooks.items():
try:
plugin_specs = hook()
for spec in plugin_specs:
action = spec.get("action")
if (
not action
or action == "divider"
or not _plugin_action_regex.match(action)
):
continue
action = name.lower() + ":" + action
copied = dict(spec)
copied["source"] = "plugin"
copied["action"] = action
specs[action] = copied
except Exception:
logging.getLogger(__name__).exception(
"Error while fetching additional actions from plugin {}".format(name),
extra={"plugin": name},
)
return specs
def _get_plugin_command_spec(action):
plugin = action.split(":", 1)[0]
available_actions = _get_plugin_command_specs(plugin=plugin)
return available_actions.get(action)
def _get_custom_command_specs():
specs = collections.OrderedDict()
dividers = 0
@@ -307,10 +358,7 @@ def _get_custom_command_specs():
def _get_custom_command_spec(action):
available_actions = _get_custom_command_specs()
if action not in available_actions:
return None
return available_actions[action]
return available_actions.get(action)
class CommandFailed(Exception):
+7 -2
View File
@@ -24,6 +24,11 @@ from octoprint.server.util.flask import (
)
from octoprint.settings import settings, valid_boolean_trues
try:
from urllib.parse import quote as urlquote
except ImportError:
from urllib import quote as urlquote # noqa: F401
_DATA_FORMAT_VERSION = "v2"
# ~~ timelapse handling
@@ -140,7 +145,7 @@ def getTimelapseData():
finished_list = []
for f in files:
output = dict(f)
output["url"] = url_for("index") + "downloads/timelapse/" + f["name"]
output["url"] = url_for("index") + "downloads/timelapse/" + urlquote(f["name"])
finished_list.append(output)
result = {
@@ -160,7 +165,7 @@ def getTimelapseData():
@Permissions.TIMELAPSE_DOWNLOAD.require(403)
def downloadTimelapse(filename):
return redirect_to_tornado(
request, url_for("index") + "downloads/timelapse/" + filename
request, url_for("index") + "downloads/timelapse/" + urlquote(filename)
)
+4 -3
View File
@@ -567,8 +567,10 @@ class OctoPrintFlaskResponse(flask.Response):
if samesite is not None:
samesite = samesite.lower()
if samesite == "none":
samesite = None
if samesite not in (None, "strict", "lax"):
# Must be string "None"
samesite = "None"
if samesite not in ("None", "strict", "lax"):
# If NoneType, the cookie is not set
samesite = None
kwargs["samesite"] = samesite
@@ -1702,7 +1704,6 @@ def collect_core_assets(preferred_stylesheet="css"):
assets["js"] = [
"js/app/bindings/allowbindings.js",
"js/app/bindings/contextmenu.js",
"js/app/bindings/copywidth.js",
"js/app/bindings/invisible.js",
"js/app/bindings/popover.js",
"js/app/bindings/qrcode.js",
+4 -1
View File
@@ -27,6 +27,7 @@ from octoprint.access.users import LoginStatusListener
from octoprint.events import Events
from octoprint.settings import settings
from octoprint.util.json import dump as json_dump
from octoprint.util.version import get_python_version_string
class ThreadSafeSession(octoprint.vendor.sockjs.tornado.session.Session):
@@ -98,11 +99,12 @@ class PrinterStateConnection(
"*": [],
}
# TODO: Permissions should be overridable from plugins, this special case stuff here is a hack
_emit_permissions = {
"connected": [],
"reauthRequired": [],
"plugin": lambda payload: []
if payload.get("plugin") == "backup"
if payload.get("plugin") in ("backup", "softwareupdate")
and settings().getBoolean(["server", "firstRun"])
else [Permissions.STATUS],
"*": [Permissions.STATUS],
@@ -221,6 +223,7 @@ class PrinterStateConnection(
"version": octoprint.server.VERSION,
"display_version": octoprint.server.DISPLAY_VERSION,
"branch": octoprint.server.BRANCH,
"python_version": get_python_version_string(),
"plugin_hash": plugin_hash.hexdigest(),
"config_hash": config_hash,
"debug": octoprint.server.debug,
+5 -1
View File
@@ -1571,6 +1571,7 @@ class SystemInfoBundleHandler(CorsSupportMixin, tornado.web.RequestHandler):
from octoprint.server import (
connectivityChecker,
environmentDetector,
pluginManager,
printer,
safe_mode,
)
@@ -1587,7 +1588,10 @@ class SystemInfoBundleHandler(CorsSupportMixin, tornado.web.RequestHandler):
)
z = get_systeminfo_bundle(
systeminfo, settings().getBaseFolder("logs"), printer=printer
systeminfo,
settings().getBaseFolder("logs"),
printer=printer,
plugin_manager=pluginManager,
)
self.set_header("Content-Type", "application/zip")
+31 -31
View File
@@ -1,6 +1,4 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
"""
This module represents OctoPrint's settings management. Within this module the default settings for the core
application are defined and the instance of the :class:`Settings` is held, which offers getter and setter
@@ -18,6 +16,7 @@ of various types and the configuration file itself.
:members:
:undoc-members:
"""
from __future__ import absolute_import, division, print_function, unicode_literals
__author__ = "Gina Häußge <osd@foosel.net>"
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
@@ -110,6 +109,7 @@ default_settings = {
"port": None,
"baudrate": None,
"exclusive": True,
"lowLatency": False,
"autoconnect": False,
"log": False,
"timeout": {
@@ -123,6 +123,7 @@ default_settings = {
"temperatureAutoreport": 2,
"sdStatus": 1,
"sdStatusAutoreport": 1,
"posAutoreport": 5,
"resendOk": 0.5,
"baudrateDetectionPause": 1.0,
"positionLogWait": 10.0,
@@ -135,6 +136,7 @@ default_settings = {
"blacklistedBaudrates": [],
"longRunningCommands": ["G4", "G28", "G29", "G30", "G32", "M400", "M226", "M600"],
"blockedCommands": ["M0", "M1"],
"ignoredCommands": [],
"pausingCommands": ["M0", "M1", "M25"],
"emergencyCommands": ["M112", "M108", "M410"],
"checksumRequiringCommands": ["M110"],
@@ -176,8 +178,10 @@ default_settings = {
"capabilities": {
"autoreport_temp": True,
"autoreport_sdstatus": True,
"autoreport_pos": True,
"busy_protocol": True,
"emergency_parser": True,
"extended_m20": True,
},
"resendRatioThreshold": 10,
"resendRatioStart": 100,
@@ -257,7 +261,7 @@ default_settings = {
"flipH": False,
"flipV": False,
"rotate90": False,
"ffmpegCommandline": '{ffmpeg} -r {fps} -i "{input}" -vcodec {videocodec} -threads {threads} -b {bitrate} -f {containerformat} -y {filters} "{output}"',
"ffmpegCommandline": '{ffmpeg} -r {fps} -i "{input}" -vcodec {videocodec} -threads {threads} -b:v {bitrate} -f {containerformat} -y {filters} "{output}"',
"timelapse": {
"type": "off",
"options": {},
@@ -265,6 +269,7 @@ default_settings = {
"fps": 25,
},
"cleanTmpAfterDays": 7,
"cacheBuster": False,
},
"gcodeAnalysis": {
"maxExtruders": 10,
@@ -285,6 +290,7 @@ default_settings = {
"uploadOverwriteConfirmation": True,
"autoUppercaseBlacklist": ["M117", "M118"],
"g90InfluencesExtruder": False,
"enforceReallyUniversalFilenames": False,
},
"folder": {
"uploads": None,
@@ -369,6 +375,7 @@ default_settings = {
"plugin_pluginmanager",
"plugin_softwareupdate",
"plugin_announcements",
"plugin_eventmanager",
"plugin_backup",
"plugin_tracking",
"plugin_errortracking",
@@ -376,6 +383,7 @@ default_settings = {
],
"usersettings": ["access", "interface"],
"wizard": [
"plugin_softwareupdate_update",
"plugin_backup",
"plugin_corewizard_acl",
"plugin_corewizard_onlinecheck",
@@ -432,6 +440,10 @@ default_settings = {
"name": "Suppress SD status messages",
"regex": r"(Send: (N\d+\s+)?M27)|(Recv: SD printing byte)|(Recv: Not SD printing)",
},
{
"name": "Suppress position messages",
"regex": r"(Send:\s+(N\d+\s+)?M114)|(Recv:\s+(ok\s+)?X:[+-]?([0-9]*[.])?[0-9]+\s+Y:[+-]?([0-9]*[.])?[0-9]+\s+Z:[+-]?([0-9]*[.])?[0-9]+\s+E\d*:[+-]?([0-9]*[.])?[0-9]+).*",
},
{"name": "Suppress wait responses", "regex": r"Recv: wait"},
{
"name": "Suppress processing responses",
@@ -745,11 +757,17 @@ class Settings(object):
def sanity_check_folders(self, folders=None):
if folders is None:
folders = default_settings["folder"].keys()
folder_map = {}
for folder in folders:
self.getBaseFolder(
folder, check_writable=True, deep_check_writable=True, log_error=True
folder_map[folder] = self.getBaseFolder(
folder, check_writable=True, deep_check_writable=True
)
# validate uniqueness of folder paths
if len(folder_map.values()) != len(set(folder_map.values())):
raise DuplicateFolderPaths(folders)
def _get_default_folder(self, type):
folder = default_settings["folder"][type]
if folder is None:
@@ -1036,7 +1054,6 @@ class Settings(object):
if migrate:
self._migrate_config()
self._validate_config()
self._forget_hashes()
@@ -1634,15 +1651,6 @@ class Settings(object):
return True
return False
def _validate_config(self):
# validate uniqueness of folder paths
folder_keys = self.get(["folder"], merged=True).keys()
folders = {
folder_key: self.getBaseFolder(folder_key) for folder_key in folder_keys
}
if len(folders.values()) != len(set(folders.values())):
raise DuplicateFolderPaths(folders)
def backup(self, suffix=None, path=None, ext=None, hidden=False):
import shutil
@@ -1904,7 +1912,6 @@ class Settings(object):
type,
create=True,
allow_fallback=True,
log_error=False,
check_writable=True,
deep_check_writable=False,
):
@@ -1925,23 +1932,20 @@ class Settings(object):
create=create,
check_writable=check_writable,
deep_check_writable=deep_check_writable,
log_error=log_error,
)
except Exception:
if folder != default_folder and allow_fallback:
if log_error:
self._logger.error(
"Invalid configured {} folder at {}, attempting to "
"fall back on default folder at {}".format(
type, folder, default_folder
)
self._logger.exception(
"Invalid configured {} folder at {}, attempting to "
"fall back on default folder at {}".format(
type, folder, default_folder
)
)
_validate_folder(
default_folder,
create=create,
check_writable=check_writable,
deep_check_writable=deep_check_writable,
log_error=log_error,
)
folder = default_folder
@@ -2219,9 +2223,7 @@ def _default_basedir(applicationName):
return os.path.expanduser(os.path.join("~", "." + applicationName.lower()))
def _validate_folder(
folder, create=True, check_writable=True, deep_check_writable=False, log_error=False
):
def _validate_folder(folder, create=True, check_writable=True, deep_check_writable=False):
logger = logging.getLogger(__name__)
if not os.path.exists(folder):
@@ -2234,8 +2236,7 @@ def _validate_folder(
try:
os.makedirs(folder)
except Exception:
if log_error:
logger.exception("Could not create {}".format(folder))
logger.exception("Could not create {}".format(folder))
raise IOError(
"Folder for type {} at {} does not exist and creation failed".format(
type, folder
@@ -2267,6 +2268,5 @@ def _validate_folder(
f.write("test")
os.remove(testfile)
except Exception:
if log_error:
logger.exception("Could not write test file to {}".format(folder))
logger.exception("Could not write test file to {}".format(testfile))
raise IOError(error)
+1 -2
View File
@@ -1,6 +1,4 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
"""
In this module the slicing support of OctoPrint is encapsulated.
@@ -13,6 +11,7 @@ In this module the slicing support of OctoPrint is encapsulated.
.. autoclass:: SlicingManager
:members:
"""
from __future__ import absolute_import, division, print_function, unicode_literals
__author__ = "Gina Häußge <osd@foosel.net>"
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
+1 -2
View File
@@ -1,6 +1,4 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
"""
Slicing related exceptions.
@@ -27,6 +25,7 @@ Slicing related exceptions.
:show-inheritance:
"""
from __future__ import absolute_import, division, print_function, unicode_literals
__author__ = "Gina Häußge <osd@foosel.net>"
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
+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
@@ -1,48 +0,0 @@
ko.bindingHandlers.copyWidth = {
init: function (element, valueAccessor, allBindings, viewModel, bindingContext) {
var node = ko.bindingHandlers.copyWidth._getReferenceNode(element, valueAccessor);
ko.bindingHandlers.copyWidth._setWidth(node, element);
ko.bindingHandlers.copyWidth._addResizeSensor(node, element);
},
update: function (element, valueAccessor, allBindings, viewModel, bindingContext) {
var node = ko.bindingHandlers.copyWidth._getReferenceNode(element, valueAccessor);
ko.bindingHandlers.copyWidth._setWidth(node, element);
ko.bindingHandlers.copyWidth._addResizeSensor(node, element);
},
_setWidth: function (node, element) {
var width = node.width();
if (!width) return;
if ($(element).width() === width) return;
element.style.width = width + "px";
},
_getReferenceNode: function (element, valueAccessor) {
var value = ko.utils.unwrapObservable(valueAccessor());
if (!value) return;
var parts = value.split(" ");
var node = $(element);
while (parts.length > 0) {
var part = parts.shift();
if (part === ":parent") {
node = node.parent();
} else {
var selector = part;
if (parts.length > 0) {
selector += " " + parts.join(" ");
}
node = $(selector, node);
break;
}
}
return node;
},
_addResizeSensor: function (node, element) {
if (element.copyWidthSensor) {
element.copyWidthSensor.detach();
delete element.copyWidthSensor;
}
element.copyWidthSensor = new ResizeSensor(node, function () {
ko.bindingHandlers.copyWidth._setWidth(node, element);
});
}
};
@@ -1,8 +1,14 @@
ko.bindingHandlers.invisible = {
init: function (element, valueAccessor, allBindings, viewModel, bindingContext) {
if (!valueAccessor()) return;
var val = ko.utils.unwrapObservable(valueAccessor());
ko.bindingHandlers.style.update(element, function () {
return {visibility: "hidden"};
return {visibility: val ? "hidden" : "visible"};
});
},
update: function (element, valueAccessor, allBindings, viewModel, bindingContext) {
var val = ko.utils.unwrapObservable(valueAccessor());
ko.bindingHandlers.style.update(element, function () {
return {visibility: val ? "hidden" : "visible"};
});
}
};
@@ -426,5 +426,11 @@
});
};
OctoPrintClient.escapePath = function (path) {
return _.map(path.split("/"), function (p) {
return encodeURIComponent(p);
}).join("/");
};
return OctoPrintClient;
});
+4 -4
View File
@@ -14,19 +14,19 @@
};
var resourceForLocation = function (location) {
return url + "/" + location;
return url + "/" + OctoPrintClient.escapePath(location);
};
var downloadForLocation = function (location) {
return downloadUrl + "/" + location;
return downloadUrl + "/" + OctoPrintClient.escapePath(location);
};
var downloadForEntry = function (location, filename) {
return downloadForLocation(location) + "/" + filename;
return downloadForLocation(location) + "/" + OctoPrintClient.escapePath(filename);
};
var resourceForEntry = function (location, filename) {
return resourceForLocation(location) + "/" + filename;
return resourceForLocation(location) + "/" + OctoPrintClient.escapePath(filename);
};
var preProcessList = function (response) {
@@ -11,15 +11,15 @@
var bulkDownloadUrl = "downloads/timelapses";
var timelapseUrl = function (filename) {
return url + "/" + filename;
return url + "/" + OctoPrintClient.escapePath(filename);
};
var timelapseDownloadUrl = function (filename) {
return downloadUrl + "/" + filename;
return downloadUrl + "/" + OctoPrintClient.escapePath(filename);
};
var unrenderedTimelapseUrl = function (name) {
return url + "/unrendered/" + name;
return url + "/unrendered/" + OctoPrintClient.escapePath(name);
};
var OctoPrintTimelapseClient = function (base) {
@@ -18,6 +18,7 @@ function DataUpdater(allViewModels, connectCallback, disconnectCallback) {
self._lastProcessingTimesSize = 20;
self._safeModePopup = undefined;
self._python2Popup = undefined;
self.increaseThrottle = function () {
self.setThrottle(self._throttleFactor + 1);
@@ -171,7 +172,10 @@ function DataUpdater(allViewModels, connectCallback, disconnectCallback) {
VERSION = data["version"];
DISPLAY_VERSION = data["display_version"];
BRANCH = data["branch"];
PYTHON_VERSION = data["python_version"];
$("span.version").text(DISPLAY_VERSION);
$("span.python_version").text(PYTHON_VERSION);
// update connectivity state
ONLINE = data["online"];
@@ -230,6 +234,22 @@ function DataUpdater(allViewModels, connectCallback, disconnectCallback) {
});
}
// process python version
if (self._python2Popup) self._python2Popup.remove();
if (PYTHON_VERSION && PYTHON_VERSION.startsWith("2.")) {
self._python2Popup = new PNotify({
title: gettext("You are still running Python 2"),
text: _.sprintf(
gettext(
"<p>Python 2 is end-of-life as of January 1st 2020. While OctoPrint currently still supports running under Python 2, a future version will remove support and require Python 3. You should upgrade as soon as possible!</p><p>Please refer to the FAQ for recommended update workflows:</p>"
) +
"<p><a href='https://faq.octoprint.org/python3-update' target='_blank' rel='noopener noreferer'>How to migrate to Python 3</a></p>",
{reason: _.escape(reason)}
),
hide: false
});
}
// if the offline overlay is still showing, now's a good time to
// hide it, plus reload the camera feed if it's currently displayed
if ($("#offline_overlay").is(":visible")) {
+16 -13
View File
@@ -755,7 +755,7 @@ function showMessageDialog(msg, options) {
var modal = $("<div></div>").addClass("modal hide");
if (!nofade) {
modal.addClass("fade");
modal.addClass("fade-in");
}
modal
.append($("<div></div>").addClass("modal-header").append(modalHeader))
@@ -845,7 +845,7 @@ function showConfirmationDialog(msg, onacknowledge, options) {
var modal = $("<div></div>").addClass("modal hide");
if (!nofade) {
modal.addClass("fade");
modal.addClass("fade-in");
}
var buttons = $("<div></div>").addClass("modal-footer").append(cancelButton);
@@ -963,7 +963,7 @@ function showSelectionDialog(options) {
// create modal and do final wiring up
var modal = $("<div></div>").addClass("modal hide");
if (!nofade) {
modal.addClass("fade");
modal.addClass("fade-in");
}
if (!cancel) {
modal.data("backdrop", "static").data("keyboard", "false");
@@ -1060,18 +1060,14 @@ function showProgressModal(options, promise) {
var progress = $('<div class="progress progress-text-centered"></div>');
var progressBar = $('<div class="bar"></div>').addClass(barClassSuccess);
var progressTextBack = $('<span class="progress-text-back"></span>');
var progressTextFront = $('<span class="progress-text-front"></span>').width(
progress.width()
);
var progressText = $('<span class="progress-text-back"></span>');
if (max === undefined) {
progress.addClass("progress-striped active");
progressBar.width("100%");
}
progressBar.append(progressTextFront);
progress.append(progressTextBack).append(progressBar);
progress.append(progressBar).append(progressText);
var button = $('<button class="btn">' + buttonText + "</button>")
.prop("disabled", true)
@@ -1092,7 +1088,7 @@ function showProgressModal(options, promise) {
}
var modal = $("<div></div>")
.addClass("modal hide fade")
.addClass("modal hide fade-in")
.addClass(dialogClass)
.append($("<div></div>").addClass("modal-header").append(modalHeader))
.append(modalBody)
@@ -1127,9 +1123,16 @@ function showProgressModal(options, promise) {
// update progress bar
progressBar.width(String(value) + "%");
progressTextFront.text(short);
progressTextBack.text(short);
progressTextFront.width(progress.width());
progressText.text(short);
if (value < 50 && progressText.hasClass("progress-text-front")) {
progressText
.removeClass("progress-text-front")
.addClass("progress-text-back");
} else if (value >= 50 && progressText.hasClass("progress-text-back")) {
progressText
.removeClass("progress-text-back")
.addClass("progress-text-front");
}
// if not successful, apply failure class
if (!success && !progressBar.hasClass(barClassFailure)) {
+12 -1
View File
@@ -42,7 +42,12 @@ $(function () {
opera: false,
mobile: false,
desktop: false
desktop: false,
browser_name: "unknown",
browser_version: "unknown",
os_name: "unknown",
os_version: "unknown"
},
viewmodels: {},
startedUp: false
@@ -118,6 +123,12 @@ $(function () {
exports.browser.mobile = $.browser.mobile;
exports.browser.desktop = !exports.browser.mobile;
var uap = UAParser();
exports.browser.browser_name = uap.browser.name;
exports.browser.browser_version = uap.browser.version;
exports.browser.os_name = uap.os.name;
exports.browser.os_version = uap.os.version;
if (exports.browser.safari) {
$("html").addClass("safari");
}
@@ -46,7 +46,6 @@ $(function () {
}
})
.css({
"width": "auto",
"margin-left": function () {
return -($(this).width() / 2);
}
Loaded 100 of 153 files, more files were not shown because too many files have changed in this diff. Show more