diff --git a/.github/pr-validation.yml b/.github/pr-validation.yml index b6644f25c..b44ba7855 100644 --- a/.github/pr-validation.yml +++ b/.github/pr-validation.yml @@ -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: diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 7f6f9689f..bc97af96e 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -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 }}"}' diff --git a/.github/workflows/issue_automation.yml b/.github/workflows/issue_automation.yml index fb59a7d97..facf1ade8 100644 --- a/.github/workflows/issue_automation.yml +++ b/.github/workflows/issue_automation.yml @@ -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, @@ -67,3 +66,91 @@ jobs: # 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: + script: | + const { REMINDER, THANKYOU } = process.env; + const bundleRegex = /\[(octoprint-systeminfo-\d{14}\.zip)\]\(([^)]+)\)/g; + const marker = ""; + + 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 + }); + } + } diff --git a/.github/workflows/pr_automation.yml b/.github/workflows/pr_automation.yml index 659733438..cc411d121 100644 --- a/.github/workflows/pr_automation.yml +++ b/.github/workflows/pr_automation.yml @@ -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 }} diff --git a/.github/workflows/trigger_docs.yml b/.github/workflows/trigger_docs.yml index 492d5ef5b..cb20852fb 100644 --- a/.github/workflows/trigger_docs.yml +++ b/.github/workflows/trigger_docs.yml @@ -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 }}"}' diff --git a/.versioneer-lookup b/.versioneer-lookup index 977aeb0d9..4a882cfe0 100644 --- a/.versioneer-lookup +++ b/.versioneer-lookup @@ -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.6.1 bugfix release +# staging/bugfix is the branch for preparation of the 1.7.1 bugfix release # so are any bug/... branches -staging/bugfix 1.6.1 29484fb2926960279e62881d6ee073c374a2a5fe pep440-dev -bug/.* 1.6.1 29484fb2926960279e62881d6ee073c374a2a5fe pep440-dev +staging/bugfix 1.7.1 ddfd333b6238f3250f9d7ad598031bd0ec8e9734 pep440-dev +bug/.* 1.7.1 ddfd333b6238f3250f9d7ad598031bd0ec8e9734 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 diff --git a/AUTHORS.md b/AUTHORS.md index 7aecc1391..5cf6f796c 100644 --- a/AUTHORS.md +++ b/AUTHORS.md @@ -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 diff --git a/SUPPORTERS.md b/SUPPORTERS.md index dcdf69cf9..36ef22907 100644 --- a/SUPPORTERS.md +++ b/SUPPORTERS.md @@ -9,6 +9,7 @@ thanks to everyone who contributed! * 3D-TECH * 3DPrinterOS * Arnljot Arntsen + * Artillery 3D * Ash King * BigTreeTech * Boris Hussein @@ -18,56 +19,56 @@ thanks to everyone who contributed! * 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 - * 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 @@ -77,4 +78,4 @@ thanks to everyone who contributed! * Ulderico Cirello * Ulrich Kempken -and 2350 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)! diff --git a/THIRDPARTYLICENSES.md b/THIRDPARTYLICENSES.md index 80556b1cb..6b72d4639 100644 --- a/THIRDPARTYLICENSES.md +++ b/THIRDPARTYLICENSES.md @@ -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 diff --git a/docs/api/access.rst b/docs/api/access.rst index 061d9fb00..9379a27cb 100644 --- a/docs/api/access.rst +++ b/docs/api/access.rst @@ -81,7 +81,7 @@ Retrieve a group Retrieves an individual group record. - Will return a :http:statuscode:`200` with a :ref:`group record ` + Will return a :http:statuscode:`200` with a :ref:`group record ` 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 ` + Will return a :http:statuscode:`200` with a :ref:`user record ` as body. Requires either the ``SETTINGS`` permission or to be logged in as the user. diff --git a/docs/api/datamodel.rst b/docs/api/datamodel.rst index bbca4519f..24a10f904 100644 --- a/docs/api/datamodel.rst +++ b/docs/api/datamodel.rst @@ -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 ` - Information from the analysis of the GCODE file, if available. Left out in abridged version. + * - ``prints`` + - 0..1 + - :ref:`Print history information ` + - Information about previous prints of the file. Left out if the file has never been printed. + * - ``statistics`` + - 0..1 + - :ref:`Print statistics information ` + - 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 ` + - :ref:`Needs object ` - Needs assigned to the permission .. _sec-api-datamodel-access-groups: diff --git a/docs/api/files.rst b/docs/api/files.rst index 09e037ebd..3df618d90 100644 --- a/docs/api/files.rst +++ b/docs/api/files.rst @@ -589,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: diff --git a/docs/api/general.rst b/docs/api/general.rst index 0dacead1d..8eaede945 100644 --- a/docs/api/general.rst +++ b/docs/api/general.rst @@ -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 ` 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 ` +That means that any requests without or with an invalid API key targeting other API endpoints than :ref:`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 diff --git a/docs/api/printerprofiles.rst b/docs/api/printerprofiles.rst index fc251ea73..c0b2792e2 100644 --- a/docs/api/printerprofiles.rst +++ b/docs/api/printerprofiles.rst @@ -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 `. + Returns a :http:statuscode:`200` with a :ref:`profile list `. 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.`` - 0..1 - - :ref:`Profile ` + - :ref:`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 ` + - :ref:`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 diff --git a/docs/api/timelapse.rst b/docs/api/timelapse.rst index 000a8190f..66e0bb72e 100644 --- a/docs/api/timelapse.rst +++ b/docs/api/timelapse.rst @@ -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: diff --git a/docs/api/version.rst b/docs/api/version.rst index 61154cced..3072420ab 100644 --- a/docs/api/version.rst +++ b/docs/api/version.rst @@ -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** diff --git a/docs/bundledplugins/action_command_notification.rst b/docs/bundledplugins/action_command_notification.rst index d2b5a005c..549ad2396 100644 --- a/docs/bundledplugins/action_command_notification.rst +++ b/docs/bundledplugins/action_command_notification.rst @@ -39,13 +39,11 @@ Supported action commands notification Displays the notification ```` -.. _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 ` the firmware sent this action command: .. code-block:: none diff --git a/docs/bundledplugins/discovery.rst b/docs/bundledplugins/discovery.rst index 1bc8fac22..d4646e593 100644 --- a/docs/bundledplugins/discovery.rst +++ b/docs/bundledplugins/discovery.rst @@ -118,8 +118,7 @@ Announced Services ZeroConf Service ``_http._tcp`` +++++++++++++++++++++++++++++++ -If :ref:`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 `_ @@ -130,8 +129,7 @@ for more information. ZeroConf Service ``_octoprint._tcp`` ++++++++++++++++++++++++++++++++++++ -If :ref:`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`` diff --git a/docs/bundledplugins/index.rst b/docs/bundledplugins/index.rst index a1d858616..7b8f4ff65 100644 --- a/docs/bundledplugins/index.rst +++ b/docs/bundledplugins/index.rst @@ -20,6 +20,5 @@ Bundled Plugins gcodeviewer.rst logging.rst pluginmanager.rst - printer_safety_check.rst softwareupdate.rst virtual_printer.rst diff --git a/docs/bundledplugins/softwareupdate.rst b/docs/bundledplugins/softwareupdate.rst index 492dfbd4e..574770f2b 100644 --- a/docs/bundledplugins/softwareupdate.rst +++ b/docs/bundledplugins/softwareupdate.rst @@ -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 diff --git a/docs/bundledplugins/tracking.rst b/docs/bundledplugins/tracking.rst index 8c29a3bac..0c5655ed2 100644 --- a/docs/bundledplugins/tracking.rst +++ b/docs/bundledplugins/tracking.rst @@ -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 ` + * ``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: diff --git a/docs/configuration/config_yaml.rst b/docs/configuration/config_yaml.rst index a945a6c2a..0cab1bca5 100644 --- a/docs/configuration/config_yaml.rst +++ b/docs/configuration/config_yaml.rst @@ -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 diff --git a/docs/development/environment.rst b/docs/development/environment.rst index 9f3e05d6b..144e37e71 100644 --- a/docs/development/environment.rst +++ b/docs/development/environment.rst @@ -15,7 +15,6 @@ below. * Prerequisites: * `Python 3.7 `_ including ``pip``, ``setuptools`` and ``virtualenv`` - * `Python 2.7 `_ including ``pip``, ``setuptools`` and ``virtualenv`` * `Git `_ * 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 `_, 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 `_ 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 `_, + 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 `_ 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 `_ 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 `_ - * `Latest *stable* Python 2.7 and Python 3.8 releases from python.org `_ - (at the time of writing those are ``2.7.18`` and ``3.8.7``) + + * `Latest *stable* Python 3 release from python.org `_ * 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 `_ * `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 `_ (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 `_ (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 `_ + * `Windows 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 `_ + + * ``python -m ensurepip --upgrade`` + * Install `virtualenv `_ * ``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 `_ 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 `_ + - 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 + + diff --git a/docs/events/index.rst b/docs/events/index.rst index 71a55d68e..a9b030095 100644 --- a/docs/events/index.rst +++ b/docs/events/index.rst @@ -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 diff --git a/docs/features/gcode_scripts.rst b/docs/features/gcode_scripts.rst index d836d3fad..aa8fb1329 100644 --- a/docs/features/gcode_scripts.rst +++ b/docs/features/gcode_scripts.rst @@ -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 `, 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 `. * ``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:: diff --git a/docs/jsclientlib/index.rst b/docs/jsclientlib/index.rst index 280b3c241..5886f4805 100644 --- a/docs/jsclientlib/index.rst +++ b/docs/jsclientlib/index.rst @@ -89,10 +89,6 @@ connection options (``baseurl`` and ``apikey``) directly in the constructor or s :ref:`Application Key Plugin ` 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 ` - 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 ` to login the - user. .. toctree:: :maxdepth: 3 diff --git a/docs/modules/plugin.rst b/docs/modules/plugin.rst index 681c6c5b2..d464b5c34 100644 --- a/docs/modules/plugin.rst +++ b/docs/modules/plugin.rst @@ -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: diff --git a/docs/modules/printer.rst b/docs/modules/printer.rst index dc652ae70..5fcd54ae4 100644 --- a/docs/modules/printer.rst +++ b/docs/modules/printer.rst @@ -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: diff --git a/docs/modules/settings.rst b/docs/modules/settings.rst index 09582f710..80248cbb9 100644 --- a/docs/modules/settings.rst +++ b/docs/modules/settings.rst @@ -4,4 +4,3 @@ octoprint.settings ------------------ .. automodule:: octoprint.settings - :members: diff --git a/docs/modules/slicing.rst b/docs/modules/slicing.rst index ee3ac9192..12509284d 100644 --- a/docs/modules/slicing.rst +++ b/docs/modules/slicing.rst @@ -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: diff --git a/docs/plugins/hooks.rst b/docs/plugins/hooks.rst index dcbb3b239..1f65e91af 100644 --- a/docs/plugins/hooks.rst +++ b/docs/plugins/hooks.rst @@ -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 ` to implement custom serial-like ports through plugins. @@ -1191,7 +1191,7 @@ octoprint.plugin.softwareupdate.check_config See :ref:`here `. -.. _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.`` 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 ` 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 ` 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 diff --git a/docs/plugins/viewmodels.rst b/docs/plugins/viewmodels.rst index 91759647f..9c9180b04 100644 --- a/docs/plugins/viewmodels.rst +++ b/docs/plugins/viewmodels.rst @@ -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 diff --git a/setup.py b/setup.py index bc25b849f..6c0a87ded 100644 --- a/setup.py +++ b/setup.py @@ -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 diff --git a/src/octoprint/__init__.py b/src/octoprint/__init__.py index 0b7b4f61b..c2e61d2b3 100644 --- a/src/octoprint/__init__.py +++ b/src/octoprint/__init__.py @@ -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"]) diff --git a/src/octoprint/cli/systeminfo.py b/src/octoprint/cli/systeminfo.py index c63fddb6f..76678375c 100644 --- a/src/octoprint/cli/systeminfo.py +++ b/src/octoprint/cli/systeminfo.py @@ -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: diff --git a/src/octoprint/events.py b/src/octoprint/events.py index eb2e0878e..c29e22f50 100644 --- a/src/octoprint/events.py +++ b/src/octoprint/events.py @@ -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" diff --git a/src/octoprint/filemanager/analysis.py b/src/octoprint/filemanager/analysis.py index 11a187de6..89a59816c 100644 --- a/src/octoprint/filemanager/analysis.py +++ b/src/octoprint/filemanager/analysis.py @@ -5,7 +5,7 @@ __author__ = "Gina Häußge " __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: diff --git a/src/octoprint/filemanager/storage.py b/src/octoprint/filemanager/storage.py index 954d18807..7fd8f72e8 100644 --- a/src/octoprint/filemanager/storage.py +++ b/src/octoprint/filemanager/storage.py @@ -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( diff --git a/src/octoprint/filemanager/util.py b/src/octoprint/filemanager/util.py index 1ab1222ed..dd0942d37 100644 --- a/src/octoprint/filemanager/util.py +++ b/src/octoprint/filemanager/util.py @@ -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): diff --git a/src/octoprint/plugin/__init__.py b/src/octoprint/plugin/__init__.py index dbd9e2a3e..17151e34e 100644 --- a/src/octoprint/plugin/__init__.py +++ b/src/octoprint/plugin/__init__.py @@ -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 " __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 diff --git a/src/octoprint/plugin/core.py b/src/octoprint/plugin/core.py index b84a8157e..f60908d31 100644 --- a/src/octoprint/plugin/core.py +++ b/src/octoprint/plugin/core.py @@ -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)) diff --git a/src/octoprint/plugin/types.py b/src/octoprint/plugin/types.py index 7a50727d6..9d8d39ce0 100644 --- a/src/octoprint/plugin/types.py +++ b/src/octoprint/plugin/types.py @@ -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 " __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) ) diff --git a/src/octoprint/plugins/announcements/static/js/announcements.js b/src/octoprint/plugins/announcements/static/js/announcements.js index 75720f39a..dccf4e953 100644 --- a/src/octoprint/plugins/announcements/static/js/announcements.js +++ b/src/octoprint/plugins/announcements/static/js/announcements.js @@ -209,7 +209,6 @@ $(function () { } }) .css({ - "width": "auto", "margin-left": function () { return -($(this).width() / 2); } diff --git a/src/octoprint/plugins/announcements/templates/announcements.jinja2 b/src/octoprint/plugins/announcements/templates/announcements.jinja2 index 670a1bf78..d1744996f 100644 --- a/src/octoprint/plugins/announcements/templates/announcements.jinja2 +++ b/src/octoprint/plugins/announcements/templates/announcements.jinja2 @@ -1,4 +1,4 @@ -