Skip to content

Commit

Permalink
v0.2.2: add some utility classes, drop py3.7
Browse files Browse the repository at this point in the history
  • Loading branch information
purarue committed Aug 22, 2023
1 parent 4470d85 commit d720331
Show file tree
Hide file tree
Showing 4 changed files with 138 additions and 4 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/ci.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ jobs:
runs-on: ubuntu-latest
strategy:
matrix:
python-version: [3.7, 3.8, 3.9, "3.10"]
python-version: [3.8, 3.9, "3.10", "3.11"]

steps:
- uses: actions/checkout@v2
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ Later, I can reconstruct whether or not a file was paused/playing based on the e

### Install

Requires `python3.7+`
Requires `python3.8+`

pip install mpv-history-daemon

Expand Down
134 changes: 134 additions & 0 deletions mpv_history_daemon/utils.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
"""
Utility scripts or functions that could be useful for other projects
As these have no dependencies, locating it here makes it easier to use in lots of places
"""

import os
import logging
from typing import Dict, Optional, Tuple, Any, NamedTuple, List

from .events import Media


class MusicMetadata(NamedTuple):
title: str
album: str
artist: str


def music_parse_metadata_from_blob(
data: Dict[str, Any],
strip_whitespace: bool = False,
) -> Optional[MusicMetadata]:
if "title" not in data or "album" not in data or "artist" not in data:
return None
title = data["title"]
album = data["album"]
artist = data["artist"]
if title and artist and album:
if strip_whitespace:
return MusicMetadata(title.strip(), album.strip(), artist.strip())
else:
return MusicMetadata(title, album, artist)
return None


class MediaAllowed:
"""
A helper class to organize/filter media based on prefixes, extensions, and streaming etc.
Typically used to filter out media streams (from your camera), livestreams (watching youtube/twitch) through mpv
And generally just using mpv while editing videos/viewing things in your media folder that arent Movies/TV/Music etc.
allow_prefixes: A list of prefixes that are allowed, like ["/home/user/Music", "/home/user/Videos"]
ignore_prefixes: A list of prefixes that are ignored, like ["/home/user/Downloads", "/home/user/.cache"]
allow_extensions: A list of extensions that are allowed, like [".mp3", ".mp4", ".mkv"]
ignore_extensions: A list of extensions that are ignored, like [".jpg", ".png", ".gif"]
allow_stream: If True, allow streams (like from your camera, youtube etc)
strict: If True, only allow media that is in allow_prefixes and not in ignore_prefixes, warns otherwise
logger: A logger to log to, if None, no logging is done
"""

def __init__(
self,
*,
allow_prefixes: Optional[List[str]] = None,
ignore_prefixes: Optional[List[str]] = None,
allow_extensions: Optional[List[str]] = None,
ignore_extensions: Optional[List[str]] = None,
allow_stream: bool = False,
strict: bool = True,
logger: Optional[logging.Logger] = None,
):
self.allow_prefixes = allow_prefixes if allow_prefixes else []
self.ignored_prefixes = ignore_prefixes if ignore_prefixes else []
self.ignored_prefixes.extend(self.__class__.defualt_ignore())
ignored_ext = ignore_extensions if ignore_extensions else []
self.ignore_extensions = [
self.__class__._fix_extension(ext) for ext in ignored_ext
]
allowed_ext = allow_extensions if allow_extensions else []
self.allow_extensions = [
self.__class__._fix_extension(ext) for ext in allowed_ext
]
self.allow_stream = allow_stream
self.strict = strict
self._logger = logger

@staticmethod
def _fix_extension(ext: str) -> str:
if ext.startswith("."):
return ext.lower()
return f".{ext}".lower()

@classmethod
def defualt_ignore(cls) -> List[str]:
return ["/tmp", "/dev"]

def is_allowed(self, media: Media) -> bool:
# allow/ignore based on streaming
if not self.allow_stream and media.is_stream:
if self._logger:
self._logger.debug(f"Media {media.path} is a stream")
return False

# allow/ignore based on extension
_, ext = os.path.splitext(media.path)
if ext:
ext = ext.lower()
if ext in self.ignore_extensions:
if self._logger:
self._logger.debug(
f"Media {media.path} has an ignored extension {ext}"
)
return False
if self.allow_extensions and ext not in self.allow_extensions:
if self._logger:
self._logger.warning(
f"Media {media.path} has an extension {ext} not in allowed extensions {self.allow_extensions}"
)
return False

if self.allow_prefixes and any(
media.path.startswith(prefix) for prefix in self.allow_prefixes
):
return True

if self.ignored_prefixes and any(
media.path.startswith(prefix) for prefix in self.ignored_prefixes
):
if self._logger:
self._logger.debug(
f"Media {media.path} is in ignore prefixes {self.ignored_prefixes}"
)
return False

if len(self.allow_prefixes) > 0 and self.strict:
if self._logger:
self._logger.warning(
f"Media {media.path} is not in allowed prefixes {self.allow_prefixes}. Add it to allow_prefixes or ignore_prefixes, or set False to automatically allow non-matching paths"
)
return False

return True
4 changes: 2 additions & 2 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
long_description=long_description,
long_description_content_type="text/markdown",
install_requires=requirements,
python_requires=">=3.7",
python_requires=">=3.8",
extras_require={"optional": ["orjson"]},
name=pkg,
packages=find_packages(include=[pkg]),
Expand All @@ -33,5 +33,5 @@
license="http://www.apache.org/licenses/LICENSE-2.0",
scripts=["bin/mpv_history_daemon_restart"],
url="https://github.com/seanbreckenridge/mpv-history-daemon",
version="0.2.1",
version="0.2.2",
)

0 comments on commit d720331

Please sign in to comment.