diff --git a/src/octoprint/cli/server.py b/src/octoprint/cli/server.py index 5fed71e5a..dc9ff6cbf 100644 --- a/src/octoprint/cli/server.py +++ b/src/octoprint/cli/server.py @@ -82,7 +82,6 @@ def run_server(basedir, configfile, host, port, debug, allow_root, logging_confi ignore_blacklist=ignore_blacklist, after_safe_mode=log_startup, after_environment_detector=log_register_rollover) - settings, _, safe_mode, event_manager, connectivity_checker, plugin_manager, environment_detector = components except FatalStartupError as e: diff --git a/src/octoprint/plugins/pluginmanager/__init__.py b/src/octoprint/plugins/pluginmanager/__init__.py index 54ae3cb92..835dcba5a 100644 --- a/src/octoprint/plugins/pluginmanager/__init__.py +++ b/src/octoprint/plugins/pluginmanager/__init__.py @@ -459,6 +459,11 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, self._plugin_manager.log_all_plugins() self._logger.info("The plugin was installed successfully: {}, version {}".format(new_plugin.name, new_plugin.version)) + self._event_bus.fire("plugin_pluginmanager_installplugin", dict(id=new_plugin.key, + version=new_plugin.version, + source=source, + source_type=source_type)) + result = dict(result=True, source=source, source_type=source_type, @@ -549,6 +554,9 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, self._plugin_manager.reload_plugins() + self._event_bus.fire("plugin_pluginmanager_uninstallplugin", dict(id=plugin.key, + version=plugin.version)) + result = dict(result=True, needs_restart=needs_restart, needs_refresh=needs_refresh, @@ -667,7 +675,8 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, if strip: lines = map(lambda x: x.strip(), lines) - self._plugin_manager.send_plugin_message(self._identifier, dict(type="loglines", loglines=[dict(line=line, stream=stream) for line in lines])) + self._plugin_manager.send_plugin_message(self._identifier, dict(type="loglines", + loglines=[dict(line=line, stream=stream) for line in lines])) for line in lines: self._console_logger.debug(u"{prefix} {line}".format(**locals())) @@ -686,6 +695,9 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, elif not plugin.enabled and plugin.key not in self._pending_enable: self._pending_enable.add(plugin.key) + self._event_bus.fire("plugin_pluginmanager_enableplugin", dict(id=plugin.key, + version=plugin.version)) + def _mark_plugin_disabled(self, plugin, needs_restart=False): disabled_list = list(self._settings.global_get(["plugins", "_disabled"])) if not plugin.key in disabled_list: @@ -701,6 +713,9 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, elif (plugin.enabled or plugin.forced_disabled or getattr(plugin, "safe_mode_victim", False)) and plugin.key not in self._pending_disable: self._pending_disable.add(plugin.key) + self._event_bus.fire("plugin_pluginmanager_disableplugin", dict(id=plugin.key, + version=plugin.version)) + def _fetch_all_data(self, async=False): def run(): self._repository_available = self._fetch_repository_from_disk() diff --git a/src/octoprint/plugins/tracking/__init__.py b/src/octoprint/plugins/tracking/__init__.py new file mode 100644 index 000000000..08ed7855d --- /dev/null +++ b/src/octoprint/plugins/tracking/__init__.py @@ -0,0 +1,186 @@ +# coding=utf-8 +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) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License" + +import octoprint.plugin + +from flask.ext.babel import gettext + +import requests +import hashlib +import logging + +# noinspection PyCompatibility +import concurrent.futures + +from octoprint.util import RepeatedTimer +from octoprint.util.version import get_octoprint_version_string +from octoprint.events import Events + +TRACKING_URL = "https://tracking.octoprint.org/track/{id}/{event}/?{args}" + +# noinspection PyMissingConstructor +class TrackingPlugin(octoprint.plugin.SettingsPlugin, + octoprint.plugin.EnvironmentDetectionPlugin, + octoprint.plugin.StartupPlugin, + octoprint.plugin.TemplatePlugin, + octoprint.plugin.AssetPlugin, + octoprint.plugin.WizardPlugin, + octoprint.plugin.EventHandlerPlugin): + + def __init__(self): + self._environment = None + self._url = None + self._ping_worker = None + self._executor = concurrent.futures.ThreadPoolExecutor(max_workers=1) + + def initialize(self): + self._init_tracking() + + ##~~ SettingsPlugin + + def get_settings_defaults(self): + return dict(enabled=None, + unique_id=None, + server=TRACKING_URL, + ping=15*60) + + def on_settings_save(self, data): + enabled = self._settings.get([b"enabled"]) + + octoprint.plugin.SettingsPlugin.on_settings_save(self, data) + + if enabled is None and self._settings.get([b"enabled"]): + # tracking was just enabled, let's init it and send a startup event + self._init_tracking() + self._track_startup() + + ##~~ EnvironmentDetectionPlugin + + def on_environment_detected(self, environment, *args, **kwargs): + self._environment = environment + + ##~~ StartupPlugin + + def on_after_startup(self): + self._track_startup() + + ping = self._settings.get_int(["ping"]) + if ping: + self._ping_worker = RepeatedTimer(ping, self._track_ping) + self._ping_worker.start() + + ##~~ EventHandlerPlugin + + def on_event(self, event, payload): + if event.startswith("plugin_pluginmanager_"): + self._track_plugin_event(event, payload) + elif event in (Events.PRINT_STARTED, Events.PRINT_DONE, Events.PRINT_FAILED, Events.PRINT_CANCELLED): + self._track_printjob_event(event, payload) + + ##~~ TemplatePlugin + + def get_template_configs(self): + return [ + dict(type="settings", name=gettext("Anonymous Usage Tracking"), template="tracking_settings.jinja2", custom_bindings=False), + dict(type="wizard", name=gettext("Anonymous Usage Tracking"), template="tracking_wizard.jinja2", custom_bindings=True, mandatory=True) + ] + + ##~~ AssetPlugin + + def get_assets(self): + return dict(js=["js/tracking.js"]) + + ##~~ WizardPlugin + + def is_wizard_required(self): + return self._settings.get([b"enabled"]) is None + + ##~~ helpers + + def _init_tracking(self): + if not self._settings.get_boolean([b"enabled"]): + return + self._init_id() + self._logger.info("Initialized anonymous tracking") + + def _init_id(self): + if self._settings.get_boolean([b"enabled"]) and not self._settings.get([b"unique_id"]): + import uuid + self._settings.set([b"unique_id"], str(uuid.uuid4())) + self._settings.save() + + def _track_startup(self): + self._track("startup", + version=get_octoprint_version_string(), + os=self._environment[b"os"][b"id"]) + + def _track_ping(self): + self._track("ping") + + def _track_plugin_event(self, event, payload): + if event.endswith("_installplugin"): + self._track("install_plugin", plugin=payload.get(b"id"), plugin_version=payload.get(b"version")) + elif event.endswith("_uninstallplugin"): + self._track("uninstall_plugin", plugin=payload.get(b"id"), plugin_version=payload.get(b"version")) + elif event.endswith("_enableplugin"): + self._track("enable_plugin", plugin=payload.get(b"id"), plugin_version=payload.get(b"version")) + elif event.endswith("_disableplugin"): + self._track("disable_plugin", plugin=payload.get(b"id"), plugin_version=payload.get(b"version")) + + def _track_printjob_event(self, event, payload): + sha = hashlib.sha1() + sha.update(payload.get("name")) + + event = None + args = dict(origin=payload.get(b"origin"), file=sha.hexdigest()) + + if event == Events.PRINT_STARTED: + event = "print_started" + elif event == Events.PRINT_DONE: + try: + elapsed = int(payload.get(b"time")) + except ValueError: + elapsed = "unknown" + args[b"elapsed"] = elapsed + event = "print_done" + elif event == Events.PRINT_FAILED: + event = "print_failed" + elif event == Events.PRINT_CANCELLED: + event = "print_cancelled" + + if event is not None: + self._track(event, **args) + + def _track(self, event, **kwargs): + if not self._settings.get_boolean([b"enabled"]): + return + + self._executor.submit(self._do_track, event, **kwargs) + + def _do_track(self, event, **kwargs): + server = self._settings.get([b"server"]) + url = server.format(id=self._settings.get([b"unique_id"]), + event=event, + args="&".join(map(lambda x: "{}={}".format(x[0], x[1]), kwargs.items()))) + + headers = {"User-Agent": "OctoPrint/{}".format(get_octoprint_version_string())} + try: + requests.get(url, + timeout=3.1, + headers=headers) + self._logger.debug("Sent tracking event to {}".format(url)) + except: + if self._logger.isEnabledFor(logging.DEBUG): + self._logger.exception("Error while sending event to anonymous usage tracking".format(url)) + else: + pass + +__plugin_name__ = "Anonymous Usage Tracking" +__plugin_description__ = "Anonymous version and usage tracking, see homepage for details on what gets tracked" +__plugin_homepage__ = "https://tracking.octoprint.org" +__plugin_author__ = "Gina Häußge" + +__plugin_implementation__ = TrackingPlugin() diff --git a/src/octoprint/plugins/tracking/static/js/tracking.js b/src/octoprint/plugins/tracking/static/js/tracking.js new file mode 100644 index 000000000..6855450b6 --- /dev/null +++ b/src/octoprint/plugins/tracking/static/js/tracking.js @@ -0,0 +1,85 @@ +$(function() { + function TrackingViewModel(parameters) { + var self = this; + + self.settingsViewModel = parameters[0]; + + self.setup = ko.observable(false); + + self.decision = ko.observable(); + self.required = false; + self.active = false; + + self.enableTracking = function() { + self.settingsViewModel.settings.plugins.tracking.enabled(true); + self.decision(true); + self._sendData(); + }; + + self.disableTracking = function() { + self.settingsViewModel.settings.plugins.tracking.enabled(false); + self.decision(false); + self._sendData(); + }; + + self.onBeforeWizardTabChange = function(next, current) { + if (!self.required) return true; + + if (!current || !_.startsWith(current, "wizard_plugin_tracking") || self.setup()) { + return true; + } + + self._showDecisionNeededDialog(); + return false; + }; + + self.onBeforeWizardFinish = function() { + if (!self.required) return true; + + if (self.setup()) { + return true; + } + + self._showDecisionNeededDialog(); + return false; + }; + + self.onWizardPreventSettingsRefreshDialog = function() { + return self.active; + }; + + self.onWizardDetails = function(response) { + self.required = response && response.tracking && response.tracking.required; + }; + + self._showDecisionNeededDialog = function() { + showMessageDialog({ + title: gettext("Please set up anonymous usage tracking"), + message: gettext("You haven't yet decided on whether to enable or disable anonymous usage tracking. You need to either enable or disable it before continuing.") + }); + }; + + self._sendData = function() { + var data = { + plugins: { + tracking: { + enabled: self.settingsViewModel.settings.plugins.tracking.enabled() + } + } + }; + + self.active = true; + self.settingsViewModel.saveData(data) + .done(function() { + self.setup(true); + self.active = false; + }); + }; + } + + OCTOPRINT_VIEWMODELS.push([ + TrackingViewModel, + ["settingsViewModel"], + "#wizard_plugin_tracking" + ]); +}); diff --git a/src/octoprint/plugins/tracking/templates/snippets/plugins/tracking/trackingDescription.jinja2 b/src/octoprint/plugins/tracking/templates/snippets/plugins/tracking/trackingDescription.jinja2 new file mode 100644 index 000000000..524a6f4f2 --- /dev/null +++ b/src/octoprint/plugins/tracking/templates/snippets/plugins/tracking/trackingDescription.jinja2 @@ -0,0 +1,10 @@ +{% trans %} +

+ Anonymous usage tracking provides valuable insights into how many instances running what versions of OctoPrint are out there, + whether they are successfully completing print jobs and various other metrics. +

+

+ By enabling it you help to identify problems with new releases and release candidates early on, and to better + tailor OctoPrint's future development to actual use. +

+{% endtrans %} diff --git a/src/octoprint/plugins/tracking/templates/snippets/plugins/tracking/trackingDetails.jinja2 b/src/octoprint/plugins/tracking/templates/snippets/plugins/tracking/trackingDetails.jinja2 new file mode 100644 index 000000000..d1fc0d990 --- /dev/null +++ b/src/octoprint/plugins/tracking/templates/snippets/plugins/tracking/trackingDetails.jinja2 @@ -0,0 +1,4 @@ +

{% trans %} + For details on what gets tracked, please refer to tracking.octoprint.org + and also the Privacy Policy at tracking.octoprint.org. +{% endtrans %}

diff --git a/src/octoprint/plugins/tracking/templates/tracking_settings.jinja2 b/src/octoprint/plugins/tracking/templates/tracking_settings.jinja2 new file mode 100644 index 000000000..4c43e27cc --- /dev/null +++ b/src/octoprint/plugins/tracking/templates/tracking_settings.jinja2 @@ -0,0 +1,21 @@ +

{{ _('Anonymous Usage Tracking') }}

+ +{% include "snippets/plugins/tracking/trackingDescription.jinja2" %} + +
+
+
+ +
+
+
+ +
+ +
+
+
+ +{% include "snippets/plugins/tracking/trackingDetails.jinja2" %} diff --git a/src/octoprint/plugins/tracking/templates/tracking_wizard.jinja2 b/src/octoprint/plugins/tracking/templates/tracking_wizard.jinja2 new file mode 100644 index 000000000..cbc6c12d7 --- /dev/null +++ b/src/octoprint/plugins/tracking/templates/tracking_wizard.jinja2 @@ -0,0 +1,19 @@ +

{{ _('Configure Anonymous Usage Tracking') }}

+ +{% include "snippets/plugins/tracking/trackingDescription.jinja2" %} + +{% include "snippets/plugins/tracking/trackingDetails.jinja2" %} + +
+ {{ _('Disable Anonymous Usage Tracking') }} + {{ _('Enable Anonymous Usage Tracking') }} +
+ +