add telemetry using posthog

+ move build variables into a python file
+ rewrite logic to check if there's an internet connection
+ move IS_BUILD into settings
+ update pyintaller to 6.0.0
+ update other packages to latest
This commit is contained in:
mungai-njoroge
2023-09-25 20:27:20 +03:00
parent 50ebead026
commit ba88cf4a23
12 changed files with 456 additions and 215 deletions
+2
View File
@@ -15,6 +15,7 @@ from app.serializers.track import serialize_tracks
from app.store.albums import AlbumStore
from app.store.artists import ArtistStore
from app.store.tracks import TrackStore
from app import telemetry
api = Blueprint("artist", __name__, url_prefix="/")
@@ -24,6 +25,7 @@ def get_artist(artisthash: str):
"""
Get artist data.
"""
telemetry.send_artist_visited()
limit = request.args.get("limit")
if limit is None:
+22 -19
View File
@@ -3,19 +3,14 @@ Handles arguments passed to the program.
"""
import os.path
import sys
from configparser import ConfigParser
import PyInstaller.__main__ as bundler
from app import settings
from app.logger import log
from app.print_help import HELP_MESSAGE
from app.utils.wintools import is_windows
from app.utils.xdg_utils import get_xdg_config_dir
config = ConfigParser()
config.read("runtime.config.ini")
ALLARGS = settings.ALLARGS
ARGS = sys.argv[1:]
@@ -38,23 +33,31 @@ class HandleArgs:
"""
Runs Pyinstaller.
"""
if settings.IS_BUILD:
log.error("ERROR: You can't build here!")
return
# get last.fm api key from env
last_fm_key = settings.Keys.LASTFM_API
posthog_key = settings.Keys.POSTHOG_API_KEY
# if the key is not in env, exit
if not last_fm_key:
log.error("ERROR: LASTFM_API_KEY not set in environment")
sys.exit(0)
if not posthog_key:
log.error("ERROR: POSTHOG_API_KEY not set in environment")
sys.exit(0)
if ALLARGS.build in ARGS:
with open("runtime.config.ini", "w", encoding="utf-8") as file:
config["DEFAULT"]["BUILD"] = "True"
with open("./app/configs.py", "w", encoding="utf-8") as file:
# copy the api key to the config file
config["DEFAULT"]["LASTFM_API_KEY"] = last_fm_key
config.write(file)
_s = ";" if is_windows() else ":"
line1 = f'LASTFM_API_KEY = "{last_fm_key}"\n'
line2 = f'POSTHOG_API_KEY = "{posthog_key}"\n'
file.write(line1)
file.write(line2)
bundler.run(
[
@@ -63,19 +66,19 @@ class HandleArgs:
"--name",
"swingmusic",
"--clean",
f"--add-data=assets{_s}assets",
f"--add-data=client{_s}client",
f"--add-data=runtime.config.ini{_s}.",
f"--add-data=assets:assets",
f"--add-data=client:client",
f"--icon=assets/logo-fill.ico",
"-y",
]
)
# revert build to False and remove the api key for dev mode
with open("runtime.config.ini", "w", encoding="utf-8") as file:
config["DEFAULT"]["BUILD"] = "False"
config["DEFAULT"]["LASTFM_API_KEY"] = ""
config.write(file)
with open("./app/configs.py", "w", encoding="utf-8") as file:
line1 = "LASTFM_API_KEY = ''\n"
line2 = "POSTHOG_API_KEY = ''\n"
file.write(line1)
file.write(line2)
sys.exit(0)
+2
View File
@@ -0,0 +1,2 @@
LASTFM_API_KEY = ''
POSTHOG_API_KEY = ''
+5 -4
View File
@@ -9,7 +9,8 @@ from tqdm import tqdm
from app import settings
from app.db.sqlite.favorite import SQLiteFavoriteMethods as favdb
from app.db.sqlite.lastfm.similar_artists import SQLiteLastFMSimilarArtists as lastfmdb
from app.db.sqlite.lastfm.similar_artists import \
SQLiteLastFMSimilarArtists as lastfmdb
from app.db.sqlite.settings import SettingsSQLMethods as sdb
from app.db.sqlite.tracks import SQLiteTrackMethods
from app.lib.albumslib import validate_albums
@@ -26,7 +27,7 @@ from app.store.albums import AlbumStore
from app.store.artists import ArtistStore
from app.store.tracks import TrackStore
from app.utils.filesystem import run_fast_scandir
from app.utils.network import Ping
from app.utils.network import has_connection
get_all_tracks = SQLiteTrackMethods.get_all_tracks
insert_many_tracks = SQLiteTrackMethods.insert_many_tracks
@@ -92,7 +93,7 @@ class Populate:
tried_to_download_new_images = False
if Ping()():
if has_connection():
tried_to_download_new_images = True
try:
CheckArtistImages(instance_key)
@@ -107,7 +108,7 @@ class Populate:
if tried_to_download_new_images:
ProcessArtistColors(instance_key=instance_key)
if Ping()():
if has_connection():
try:
FetchSimilarArtistsLastFM(instance_key)
except PopulateCancelledError as e:
+15
View File
@@ -2,10 +2,18 @@
Contains default configs
"""
import os
import sys
from typing import Any
from app import configs
join = os.path.join
if getattr(sys, "frozen", False) and hasattr(sys, "_MEIPASS"):
IS_BUILD = True
else:
IS_BUILD = False
class Release:
APP_VERSION = "1.3.0"
@@ -224,3 +232,10 @@ class TCOLOR:
class Keys:
# get last fm api key from os environment
LASTFM_API = os.environ.get("LASTFM_API_KEY")
POSTHOG_API_KEY = os.environ.get("POSTHOG_API_KEY")
@classmethod
def load(cls):
if IS_BUILD:
cls.LASTFM_API = configs.LASTFM_API_KEY
cls.POSTHOG_API_KEY = configs.POSTHOG_API_KEY
+4 -13
View File
@@ -5,29 +5,20 @@ create the config directory and copy the assets to the app directory.
import os
import shutil
from configparser import ConfigParser
from app import settings
from app.utils.filesystem import get_home_res_path
config = ConfigParser()
config_path = get_home_res_path("runtime.config.ini")
config.read(config_path)
IS_BUILD = config["DEFAULT"]["BUILD"] == "True"
if IS_BUILD:
settings.Keys.LASTFM_API = config["DEFAULT"]["LASTFM_API_KEY"]
class CopyFiles:
"""Copies assets to the app directory."""
"""
Copies assets to the app directory.
"""
def __init__(self) -> None:
assets_dir = "assets"
if IS_BUILD:
if settings.IS_BUILD:
assets_dir = get_home_res_path("assets")
files = [
+56
View File
@@ -0,0 +1,56 @@
import sys
import uuid as UUID
from posthog import Posthog
from app.settings import Paths, Keys
from app.utils.hashing import create_hash
from app.utils.network import has_connection
from app.logger import log
USER_ID = ""
try:
posthog = Posthog(
project_api_key=Keys.POSTHOG_API_KEY,
host="https://app.posthog.com",
disable_geoip=False,
timeout=30,
)
except AssertionError:
log.error("ERROR: POSTHOG_API_KEY not set in environment")
sys.exit(0)
def create_userid():
"""
Creates a unique user id for the user and saves it to a file.
"""
uuid_path = Paths.get_app_dir() + "/userid.txt"
global USER_ID
try:
with open(uuid_path, "r") as f:
USER_ID = f.read().strip()
except FileNotFoundError:
uuid = str(UUID.uuid4())
USER_ID = "user_" + create_hash(uuid, limit=15)
with open(uuid_path, "w") as f:
f.write(USER_ID)
def send_event(event: str):
"""
Sends an event to posthog.
"""
global USER_ID
if has_connection():
posthog.capture(USER_ID, event=f"v1.3.0-{event}")
def send_artist_visited():
"""
Sends an event to posthog when an artist page is visited.
"""
send_event("artist-page-visited")
+10 -12
View File
@@ -1,19 +1,18 @@
import requests
import socket as Socket
class Ping:
def has_connection(host="8.8.8.8", port=53, timeout=3):
"""
Checks if there is a connection to the internet by pinging google.com
Host: 8.8.8.8 (google-public-dns-a.google.com)
OpenPort: 53/tcp
Service: domain (DNS/TCP)
"""
@staticmethod
def __call__() -> bool:
try:
requests.get("https://google.com", timeout=10)
return True
except (requests.exceptions.ConnectionError, requests.Timeout):
return False
try:
Socket.setdefaulttimeout(timeout)
Socket.socket(Socket.AF_INET, Socket.SOCK_STREAM).connect((host, port))
return True
except Socket.error as ex:
return False
def get_ip():
@@ -26,4 +25,3 @@ def get_ip():
soc.close()
return ip_address