Skip to content

Commit

Permalink
Add event call if possible
Browse files Browse the repository at this point in the history
  • Loading branch information
Gustry committed Sep 2, 2024
1 parent 067f3ed commit afa13ee
Show file tree
Hide file tree
Showing 2 changed files with 137 additions and 6 deletions.
27 changes: 21 additions & 6 deletions pg_metadata/pg_metadata.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,7 @@
__license__ = "GPL version 3"
__email__ = "info@3liz.org"


from qgis.core import QgsApplication
from qgis.core import Qgis, QgsApplication, QgsMessageLog
from qgis.PyQt.QtCore import QCoreApplication, Qt, QTranslator, QUrl
from qgis.PyQt.QtGui import QDesktopServices, QIcon
from qgis.PyQt.QtWidgets import QAction, QMessageBox
Expand Down Expand Up @@ -33,7 +32,8 @@ def __init__(self):
self.dock_action = None
self.help_action = None

setup_logger('pg_metadata')
self.plugin_name = "pg_metadata"
setup_logger(self.plugin_name)

locale, file_path = setup_translation(
folder=plugin_path("i18n"), file_pattern="pgmetadata_{}.qm")
Expand All @@ -55,7 +55,20 @@ def initGui(self):
""" Build the plugin GUI. """
self.initProcessing()

self.check_invalid_connection_names()
valid = self.check_invalid_connection_names()
if valid <= 1:
from pg_metadata.plausible import Plausible

# noinspection PyBroadException
try:
plausible = Plausible()
plausible.request_stat_event()
except Exception as e:
QgsMessageLog.logMessage(
f"Error while calling the stats API : \"{e}\"",
self.plugin_name,
Qgis.Warning,
)

icon = QIcon(resources_path('icons', 'icon.png'))

Expand All @@ -78,13 +91,13 @@ def initGui(self):
iface.registerLocatorFilter(self.locator_filter)

@staticmethod
def check_invalid_connection_names():
def check_invalid_connection_names() -> int:
""" Check for invalid connection names in the QgsSettings. """
valid, invalid = validate_connections_names()
n_invalid = len(invalid)

if n_invalid == 0:
return
return len(valid)

invalid_text = ', '.join(invalid)
msg = QMessageBox()
Expand All @@ -105,6 +118,8 @@ def check_invalid_connection_names():
if clicked == QMessageBox.No:
iface.messageBar().pushInfo('PgMetadata', tr(f'Keeping {n_invalid} invalid connections.'))

return len(valid)

@staticmethod
def open_help():
""" Open the online help. """
Expand Down
116 changes: 116 additions & 0 deletions pg_metadata/plausible.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
__copyright__ = 'Copyright 2024, 3Liz'
__license__ = 'GPL version 3'
__email__ = 'info@3liz.org'

import json
import logging
import os
import platform

from qgis.core import Qgis, QgsNetworkAccessManager
from qgis.PyQt.QtCore import QByteArray, QDateTime, QUrl
from qgis.PyQt.QtNetwork import QNetworkRequest

from pg_metadata.qgis_plugin_tools.tools.version import version

MIN_SECONDS = 3600
ENV_SKIP_STATS = "3LIZ_SKIP_STATS"
PLAUSIBLE_URL_PROD = "https://bourbon.3liz.com/api/event"
LOGGER = logging.getLogger('pg_metadata')

# For testing purpose, to test.
# Similar to QGIS dashboard
# https://feed.qgis.org/metabase/public/dashboard/df81071d-4c75-45b8-a698-97b8649d7228
# We only collect data listed in the list below
# and the country according to IP address.
# The IP is not stored by Plausible Community Edition https://github.com/plausible/analytics
# Plausible is GDPR friendly https://plausible.io/data-policy
# The User-Agent is set by QGIS Desktop itself


def to_bool(input_string: str) -> bool:
if isinstance(input_string, bool):
return input_string
return input_string.lower() in ['true', '1', 't', 'y', 'yes',]


class Plausible:

def __init__(self):
""" Constructor. """
self.previous_date = None

def request_stat_event(self) -> bool:
""" Check and make the request if possible. """
current = QDateTime().currentDateTimeUtc()
if self._request_stat_event(current):
if self._send_stat_event():
self.previous_date = current
return True
return False

def _request_stat_event(self, current: QDateTime) -> bool:
""" Request to send an event to the API. """
if to_bool(os.getenv(ENV_SKIP_STATS, False)):
# Disabled by environment variable
return False

if to_bool(os.getenv("CI", False)):
# If running on CI, do not send stats
return False

if version() in ('master', 'dev'):
return False

if self.previous_date and self.previous_date.secsTo(current) < MIN_SECONDS:
# Not more than one request per hour
# It's done at plugin startup anyway
return False

return True

def _send_stat_event(self) -> bool:
""" Send stats event to the API. """
# Qgis.QGIS_VERSION → 3.34.6-Prizren
# noinspection PyUnresolvedReferences
qgis_version_full = Qgis.QGIS_VERSION.split('-')[0]
# qgis_version_full → 3.34.6
qgis_version_branch = '.'.join(qgis_version_full.split('.')[0:2])
# qgis_version_branch → 3.34

python_version_full = platform.python_version()
# python_version_full → 3.10.12
python_version_branch = '.'.join(python_version_full.split('.')[0:2])
# python_version_branch → 3.10

data = dict({
"props": {
# Plugin version
"plugin-version": version(),
# QGIS
"qgis-version-full": qgis_version_full,
"qgis-version-branch": qgis_version_branch,
# Python
"python-version-full": python_version_full,
"python-version-branch": python_version_branch,
},
"url": PLAUSIBLE_URL_PROD,
"name": "pgmetadata-desktop",
})

data["domain"] = "pgmetadata.desktop"

request = QNetworkRequest()
# noinspection PyArgumentList
request.setUrl(QUrl(PLAUSIBLE_URL_PROD))

# Only turn ON for debug purpose, temporary !
extra_debug = False
if extra_debug:
request.setRawHeader(b"X-Debug-Request", b"true")
request.setRawHeader(b"X-Forwarded-For", b"127.0.0.1")
request.setHeader(QNetworkRequest.ContentTypeHeader, "application/json")

# noinspection PyArgumentList
QgsNetworkAccessManager.instance().post(request, QByteArray(str.encode(json.dumps(data))))
return True

0 comments on commit afa13ee

Please sign in to comment.