diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 7f6f9689f..ae1f20280 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -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/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..7aa92678a 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 # so are any bug/... branches staging/bugfix 1.6.1 29484fb2926960279e62881d6ee073c374a2a5fe pep440-dev bug/.* 1.6.1 29484fb2926960279e62881d6ee073c374a2a5fe 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 34651f849..1016145b9 100644 --- a/AUTHORS.md +++ b/AUTHORS.md @@ -141,6 +141,12 @@ 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) OctoPrint started off as a fork of [Cura](https://github.com/daid/Cura) by 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 da82c02e7..24a10f904 100644 --- a/docs/api/datamodel.rst +++ b/docs/api/datamodel.rst @@ -660,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 9b4db477b..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:: 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/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/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..4b64240e6 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.8.11", + "OctoPrint-PiSupport>=2021.8.2", # 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 # 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", + "websocket-client>=0.59,<1", # newer versions require Python 3 "wrapt>=1.12.1,<2", - "emoji>=0.5.4,<1", - "sentry-sdk>=0.15.1,<1", + "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 @@ -