remove telemetry

+ add docstrings to lyrics functions
This commit is contained in:
mungai-njoroge 2023-11-10 16:18:52 +03:00
parent 89b05ff80c
commit 8b6d10c832
9 changed files with 38 additions and 170 deletions

View File

@ -1,8 +1,8 @@
""" """
Contains all the artist(s) routes. Contains all the artist(s) routes.
""" """
import random
import math import math
import random
from datetime import datetime from datetime import datetime
from flask import Blueprint, request from flask import Blueprint, request
@ -15,29 +15,15 @@ from app.serializers.track import serialize_tracks
from app.store.albums import AlbumStore from app.store.albums import AlbumStore
from app.store.artists import ArtistStore from app.store.artists import ArtistStore
from app.store.tracks import TrackStore from app.store.tracks import TrackStore
from app.telemetry import Telemetry
from app.utils.threading import background
api = Blueprint("artist", __name__, url_prefix="/") api = Blueprint("artist", __name__, url_prefix="/")
ARTIST_VISIT_COUNT = 0
@background
def send_event():
global ARTIST_VISIT_COUNT
ARTIST_VISIT_COUNT += 1
if ARTIST_VISIT_COUNT % 5 == 0:
Telemetry.send_artist_visited()
@api.route("/artist/<artisthash>", methods=["GET"]) @api.route("/artist/<artisthash>", methods=["GET"])
def get_artist(artisthash: str): def get_artist(artisthash: str):
""" """
Get artist data. Get artist data.
""" """
send_event()
limit = request.args.get("limit") limit = request.args.get("limit")
if limit is None: if limit is None:
@ -211,7 +197,6 @@ def get_similar_artists(artisthash: str):
if artist is None: if artist is None:
return {"error": "Artist not found"}, 404 return {"error": "Artist not found"}, 404
# result = LastFMStore.get_similar_artists_for(artist.artisthash)
result = fmdb.get_similar_artists_for(artist.artisthash) result = fmdb.get_similar_artists_for(artist.artisthash)
if result is None: if result is None:

View File

@ -1,4 +1,5 @@
from flask import Blueprint, request from flask import Blueprint, request
from app.lib.lyrics import format_synced_lyrics
from app.plugins.lyrics import Lyrics from app.plugins.lyrics import Lyrics
from app.utils.hashing import create_hash from app.utils.hashing import create_hash
@ -10,6 +11,7 @@ api = Blueprint("lyricsplugin", __name__, url_prefix="/plugins/lyrics")
def search_lyrics(): def search_lyrics():
data = request.get_json() data = request.get_json()
trackhash = data.get("trackhash", "")
title = data.get("title", "") title = data.get("title", "")
artist = data.get("artist", "") artist = data.get("artist", "")
album = data.get("album", "") album = data.get("album", "")
@ -20,7 +22,7 @@ def search_lyrics():
data = finder.search_lyrics_by_title_and_artist(title, artist) data = finder.search_lyrics_by_title_and_artist(title, artist)
if not data: if not data:
return {"downloaded": False} return {"trackhash": trackhash, "lyrics": None}
perfect_match = data[0] perfect_match = data[0]
@ -34,6 +36,12 @@ def search_lyrics():
perfect_match = track perfect_match = track
track_id = perfect_match["track_id"] track_id = perfect_match["track_id"]
downloaded = finder.download_lyrics(track_id, filepath) lrc = finder.download_lyrics(track_id, filepath)
return {"downloaded": downloaded}, 200 if lrc is not None:
lines = lrc.split("\n")
lyrics = format_synced_lyrics(lines)
return {"trackhash": trackhash, "lyrics": lyrics}, 200
return {"trackhash": trackhash, "lyrics": lrc}, 200

View File

@ -3,7 +3,7 @@ from enum import Enum
class AlbumVersionEnum(Enum): class AlbumVersionEnum(Enum):
""" """
Enum for album versions. Enum that registers supported album versions.
""" """
Explicit = ("explicit",) Explicit = ("explicit",)
@ -59,4 +59,7 @@ class AlbumVersionEnum(Enum):
def get_all_keywords(): def get_all_keywords():
"""
Returns a joint string of all album versions.
"""
return "|".join("|".join(i.value) for i in AlbumVersionEnum) return "|".join("|".join(i.value) for i in AlbumVersionEnum)

View File

@ -3,12 +3,11 @@ from tinytag import TinyTag
from app.store.tracks import TrackStore from app.store.tracks import TrackStore
filepath = "/home/cwilvx/Music/Editor's Pick/Bad Day 😢/6 Dogs - Crying in the Rarri.m4a"
# filepath = "/home/cwilvx/Music/90s/Ballads/All-4-One - I Swear.mp3"
filepath = "/home/cwilvx/Music/Afrobeats/Kabusa Oriental Choir/Kabusa Oriental Choir - Bandana.m4a"
def split_line(line: str): def split_line(line: str):
"""
Split a lyrics line into time and lyrics
"""
items = line.split("]") items = line.split("]")
time = items[0].removeprefix("[") time = items[0].removeprefix("[")
lyric = items[1] if len(items) > 1 else "" lyric = items[1] if len(items) > 1 else ""
@ -17,6 +16,9 @@ def split_line(line: str):
def convert_to_milliseconds(time: str): def convert_to_milliseconds(time: str):
"""
Converts a lyrics time string into milliseconds.
"""
try: try:
minutes, seconds = time.split(":") minutes, seconds = time.split(":")
except ValueError: except ValueError:
@ -124,9 +126,9 @@ def check_lyrics_file(filepath: str, trackhash: str):
def test_is_synced(lyrics: list[str]): def test_is_synced(lyrics: list[str]):
# try to split lines and get milliseconds """
# if any passes, return True Tests if the lyric lines passed are synced.
"""
for line in lyrics: for line in lyrics:
time, _ = split_line(line) time, _ = split_line(line)
milliseconds = convert_to_milliseconds(time) milliseconds = convert_to_milliseconds(time)
@ -138,6 +140,9 @@ def test_is_synced(lyrics: list[str]):
def get_extras(filepath: str, keys: list[str]): def get_extras(filepath: str, keys: list[str]):
"""
Get extra tags from an audio file.
"""
tags = TinyTag.get(filepath) tags = TinyTag.get(filepath)
extras = tags.extra extras = tags.extra

View File

@ -10,9 +10,6 @@ from app.db.sqlite.plugins import PluginsMethods
from app.plugins import Plugin, plugin_method from app.plugins import Plugin, plugin_method
from app.settings import Keys, Paths from app.settings import Keys, Paths
# from .base import LRCProvider
# from ..utils import get_best_match
class LRCProvider: class LRCProvider:
""" """
@ -202,12 +199,13 @@ class Lyrics(Plugin):
is_valid = lrc is not None and lrc.replace("\n", "").strip() != "" is_valid = lrc is not None and lrc.replace("\n", "").strip() != ""
if not is_valid: if not is_valid:
return False return None
if is_valid: path = Path(path).with_suffix(".lrc")
path = Path(path).with_suffix(".lrc")
try:
with open(path, "w", encoding="utf-8") as f: with open(path, "w", encoding="utf-8") as f:
f.write(lrc) f.write(lrc)
return True return lrc
except:
return False return lrc

View File

@ -1,76 +0,0 @@
import uuid as UUID
from posthog import Posthog
from app.logger import log
from app.settings import Keys, Paths, Release
from app.utils.hashing import create_hash
from app.utils.network import has_connection
class Telemetry:
"""
Handles sending telemetry data to posthog.
"""
user_id = ""
off = False
@classmethod
def init(cls) -> None:
try:
cls.posthog = Posthog(
project_api_key=Keys.POSTHOG_API_KEY,
host="https://app.posthog.com",
disable_geoip=False,
)
cls.create_userid()
except AssertionError:
cls.disable_telemetry()
@classmethod
def create_userid(cls):
"""
Creates a unique user id for the user and saves it to a file.
"""
uuid_path = Paths.get_app_dir() + "/userid.txt"
try:
with open(uuid_path, "r") as f:
cls.user_id = f.read().strip()
except FileNotFoundError:
uuid = str(UUID.uuid4())
cls.user_id = "user_" + create_hash(uuid, limit=15)
with open(uuid_path, "w") as f:
f.write(cls.user_id)
@classmethod
def disable_telemetry(cls):
cls.off = True
@classmethod
def send_event(cls, event: str):
"""
Sends an event to posthog.
"""
if cls.off:
return
if has_connection():
cls.posthog.capture(cls.user_id, event=f"v{Release.APP_VERSION}-{event}")
@classmethod
def send_app_installed(cls):
"""
Sends an event to posthog when the app is installed.
"""
cls.send_event("app-installed")
@classmethod
def send_artist_visited(cls):
"""
Sends an event to posthog when an artist page is visited.
"""
cls.send_event("artist-page-visited")

View File

@ -3,22 +3,19 @@ This file is used to run the application.
""" """
import logging import logging
import mimetypes import mimetypes
import os
import setproctitle import setproctitle
from flask import request
from app.telemetry import Telemetry
from app.api import create_api from app.api import create_api
from app.arg_handler import HandleArgs from app.arg_handler import HandleArgs
from app.lib.watchdogg import Watcher as WatchDog from app.lib.watchdogg import Watcher as WatchDog
from app.periodic_scan import run_periodic_scans from app.periodic_scan import run_periodic_scans
from app.plugins.register import register_plugins
from app.settings import FLASKVARS, Keys from app.settings import FLASKVARS, Keys
from app.setup import run_setup from app.setup import run_setup
from app.start_info_logger import log_startup_info from app.start_info_logger import log_startup_info
from app.utils.filesystem import get_home_res_path from app.utils.filesystem import get_home_res_path
from app.utils.threading import background from app.utils.threading import background
from app.plugins.register import register_plugins
mimetypes.add_type("text/css", ".css") mimetypes.add_type("text/css", ".css")
@ -80,11 +77,6 @@ def start_watchdog():
WatchDog().run() WatchDog().run()
@background
def init_telemetry():
Telemetry.init()
def run_swingmusic(): def run_swingmusic():
Keys.load() Keys.load()
HandleArgs() HandleArgs()
@ -94,7 +86,6 @@ def run_swingmusic():
register_plugins() register_plugins()
start_watchdog() start_watchdog()
init_telemetry()
setproctitle.setproctitle( setproctitle.setproctitle(
f"swingmusic - {FLASKVARS.FLASK_HOST}:{FLASKVARS.FLASK_PORT}" f"swingmusic - {FLASKVARS.FLASK_HOST}:{FLASKVARS.FLASK_PORT}"

49
poetry.lock generated
View File

@ -1,4 +1,4 @@
# This file is automatically @generated by Poetry 1.5.1 and should not be changed by hand. # This file is automatically @generated by Poetry 1.7.0 and should not be changed by hand.
[[package]] [[package]]
name = "altgraph" name = "altgraph"
@ -48,17 +48,6 @@ docs = ["furo", "myst-parser", "sphinx", "sphinx-notfound-page", "sphinxcontrib-
tests = ["attrs[tests-no-zope]", "zope-interface"] tests = ["attrs[tests-no-zope]", "zope-interface"]
tests-no-zope = ["cloudpickle", "hypothesis", "mypy (>=1.1.1)", "pympler", "pytest (>=4.3.0)", "pytest-mypy-plugins", "pytest-xdist[psutil]"] tests-no-zope = ["cloudpickle", "hypothesis", "mypy (>=1.1.1)", "pympler", "pytest (>=4.3.0)", "pytest-mypy-plugins", "pytest-xdist[psutil]"]
[[package]]
name = "backoff"
version = "2.2.1"
description = "Function decoration for backoff and retry"
optional = false
python-versions = ">=3.7,<4.0"
files = [
{file = "backoff-2.2.1-py3-none-any.whl", hash = "sha256:63579f9a0628e06278f7e47b7d7d5b6ce20dc65c5e96a6f3ca99a6adca0396e8"},
{file = "backoff-2.2.1.tar.gz", hash = "sha256:03f829f5bb1923180821643f8753b0502c3b682293992485b0eef2807afa5cba"},
]
[[package]] [[package]]
name = "black" name = "black"
version = "22.12.0" version = "22.12.0"
@ -777,17 +766,6 @@ files = [
{file = "mccabe-0.7.0.tar.gz", hash = "sha256:348e0240c33b60bbdf4e523192ef919f28cb2c3d7d5c7794f74009290f236325"}, {file = "mccabe-0.7.0.tar.gz", hash = "sha256:348e0240c33b60bbdf4e523192ef919f28cb2c3d7d5c7794f74009290f236325"},
] ]
[[package]]
name = "monotonic"
version = "1.6"
description = "An implementation of time.monotonic() for Python 2 & < 3.3"
optional = false
python-versions = "*"
files = [
{file = "monotonic-1.6-py2.py3-none-any.whl", hash = "sha256:68687e19a14f11f26d140dd5c86f3dba4bf5df58003000ed467e0e2a69bca96c"},
{file = "monotonic-1.6.tar.gz", hash = "sha256:3a55207bcfed53ddd5c5bae174524062935efed17792e9de2ad0205ce9ad63f7"},
]
[[package]] [[package]]
name = "mypy-extensions" name = "mypy-extensions"
version = "1.0.0" version = "1.0.0"
@ -975,29 +953,6 @@ files = [
dev = ["pre-commit", "tox"] dev = ["pre-commit", "tox"]
testing = ["pytest", "pytest-benchmark"] testing = ["pytest", "pytest-benchmark"]
[[package]]
name = "posthog"
version = "3.0.2"
description = "Integrate PostHog into any python application."
optional = false
python-versions = "*"
files = [
{file = "posthog-3.0.2-py2.py3-none-any.whl", hash = "sha256:a8c0af6f2401fbe50f90e68c4143d0824b54e872de036b1c2f23b5abb39d88ce"},
{file = "posthog-3.0.2.tar.gz", hash = "sha256:701fba6e446a4de687c6e861b587e7b7741955ad624bf34fe013c06a0fec6fb3"},
]
[package.dependencies]
backoff = ">=1.10.0"
monotonic = ">=1.5"
python-dateutil = ">2.1"
requests = ">=2.7,<3.0"
six = ">=1.5"
[package.extras]
dev = ["black", "flake8", "flake8-print", "isort", "pre-commit"]
sentry = ["django", "sentry-sdk"]
test = ["coverage", "flake8", "freezegun (==0.3.15)", "mock (>=2.0.0)", "pylint", "pytest"]
[[package]] [[package]]
name = "psutil" name = "psutil"
version = "5.9.5" version = "5.9.5"
@ -1745,4 +1700,4 @@ files = [
[metadata] [metadata]
lock-version = "2.0" lock-version = "2.0"
python-versions = ">=3.10,<3.12" python-versions = ">=3.10,<3.12"
content-hash = "52427f2a27236efb5bcafec3d7db6d2e926dd908593bd595aae5446dfc75ea70" content-hash = "6b0eebfb7c29b88c87c31f6efc13229d17148c9643b6d9e37576e5a23e6c967c"

View File

@ -23,7 +23,6 @@ pendulum = "^2.1.2"
flask-compress = "^1.13" flask-compress = "^1.13"
tabulate = "^0.9.0" tabulate = "^0.9.0"
setproctitle = "^1.3.2" setproctitle = "^1.3.2"
posthog = "^3.0.2"
[tool.poetry.dev-dependencies] [tool.poetry.dev-dependencies]
pylint = "^2.15.5" pylint = "^2.15.5"