Skip to content

Commit f58c045

Browse files
authored
Merge pull request #1 from MusicBoxRaspberryPi/develop
Initial Release
2 parents 9fb3b00 + 40359af commit f58c045

File tree

15 files changed

+408
-0
lines changed

15 files changed

+408
-0
lines changed

.env.dist

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
CONTAINER_NAME=music_box_api
2+
IMAGE_NAME=music_box
3+
EXPOSED_PORT=8000
4+
5+
SPOTIFY_CLIENT_ID=spotifyclientid
6+
SPOTIFY_CLIENT_SECRET=spotifyclientsecret

.gitignore

Lines changed: 160 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,160 @@
1+
# Byte-compiled / optimized / DLL files
2+
__pycache__/
3+
*.py[cod]
4+
*$py.class
5+
6+
# C extensions
7+
*.so
8+
9+
# Distribution / packaging
10+
.Python
11+
build/
12+
develop-eggs/
13+
dist/
14+
downloads/
15+
eggs/
16+
.eggs/
17+
lib/
18+
lib64/
19+
parts/
20+
sdist/
21+
var/
22+
wheels/
23+
share/python-wheels/
24+
*.egg-info/
25+
.installed.cfg
26+
*.egg
27+
MANIFEST
28+
29+
# PyInstaller
30+
# Usually these files are written by a python script from a template
31+
# before PyInstaller builds the exe, so as to inject date/other infos into it.
32+
*.manifest
33+
*.spec
34+
35+
# Installer logs
36+
pip-log.txt
37+
pip-delete-this-directory.txt
38+
39+
# Unit test / coverage reports
40+
htmlcov/
41+
.tox/
42+
.nox/
43+
.coverage
44+
.coverage.*
45+
.cache
46+
nosetests.xml
47+
coverage.xml
48+
*.cover
49+
*.py,cover
50+
.hypothesis/
51+
.pytest_cache/
52+
cover/
53+
54+
# Translations
55+
*.mo
56+
*.pot
57+
58+
# Django stuff:
59+
*.log
60+
local_settings.py
61+
db.sqlite3
62+
db.sqlite3-journal
63+
64+
# Flask stuff:
65+
instance/
66+
.webassets-cache
67+
68+
# Scrapy stuff:
69+
.scrapy
70+
71+
# Sphinx documentation
72+
docs/_build/
73+
74+
# PyBuilder
75+
.pybuilder/
76+
target/
77+
78+
# Jupyter Notebook
79+
.ipynb_checkpoints
80+
81+
# IPython
82+
profile_default/
83+
ipython_config.py
84+
85+
# pyenv
86+
# For a library or package, you might want to ignore these files since the code is
87+
# intended to run in multiple environments; otherwise, check them in:
88+
# .python-version
89+
90+
# pipenv
91+
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
92+
# However, in case of collaboration, if having platform-specific dependencies or dependencies
93+
# having no cross-platform support, pipenv may install dependencies that don't work, or not
94+
# install all needed dependencies.
95+
#Pipfile.lock
96+
97+
# poetry
98+
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
99+
# This is especially recommended for binary packages to ensure reproducibility, and is more
100+
# commonly ignored for libraries.
101+
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
102+
#poetry.lock
103+
104+
# pdm
105+
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
106+
#pdm.lock
107+
# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
108+
# in version control.
109+
# https://pdm.fming.dev/#use-with-ide
110+
.pdm.toml
111+
112+
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
113+
__pypackages__/
114+
115+
# Celery stuff
116+
celerybeat-schedule
117+
celerybeat.pid
118+
119+
# SageMath parsed files
120+
*.sage.py
121+
122+
# Environments
123+
.env
124+
.venv
125+
env/
126+
venv/
127+
ENV/
128+
env.bak/
129+
venv.bak/
130+
131+
# Spyder project settings
132+
.spyderproject
133+
.spyproject
134+
135+
# Rope project settings
136+
.ropeproject
137+
138+
# mkdocs documentation
139+
/site
140+
141+
# mypy
142+
.mypy_cache/
143+
.dmypy.json
144+
dmypy.json
145+
146+
# Pyre type checker
147+
.pyre/
148+
149+
# pytype static type analyzer
150+
.pytype/
151+
152+
# Cython debug symbols
153+
cython_debug/
154+
155+
# PyCharm
156+
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
157+
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
158+
# and can be added to the global gitignore or merged into this file. For a more nuclear
159+
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
160+
.idea/

Dockerfile

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
FROM python:3.10-slim
2+
3+
WORKDIR /code
4+
5+
COPY ./requirements.txt /code/requirements.txt
6+
RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt
7+
8+
COPY ./app /code/app

app/container.py

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
from dependency_injector import containers, providers
2+
3+
from app.spotify.service import SpotifyService
4+
5+
6+
class Container(containers.DeclarativeContainer):
7+
wiring_config = containers.WiringConfiguration(
8+
packages=[
9+
"app",
10+
]
11+
)
12+
13+
config = providers.Configuration(ini_files=["config.ini"], strict=True)
14+
15+
spotify_service = providers.Singleton(
16+
SpotifyService,
17+
client_id=config.spotify.client_id,
18+
client_secret=config.spotify.client_secret,
19+
redirect_uri=config.spotify.redirect_uri
20+
)

app/main.py

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
from fastapi import FastAPI
2+
from pydantic import TypeAdapter
3+
4+
from app.container import Container
5+
from app.spotify.router import spotify_router
6+
from app.system.router import system_router
7+
8+
container = Container()
9+
10+
11+
def create_application() -> FastAPI:
12+
application = FastAPI(
13+
title="MusicBox API",
14+
debug=True
15+
)
16+
17+
application.include_router(system_router)
18+
application.include_router(spotify_router)
19+
20+
return application
21+
22+
23+
if __name__ == "__main__":
24+
import uvicorn
25+
26+
uvicorn.run(
27+
"app.main:create_application",
28+
factory=True,
29+
host=container.config.uvicorn.host(),
30+
port=int(container.config.uvicorn.port()),
31+
log_level=container.config.uvicorn.log_level(),
32+
reload=TypeAdapter(bool).validate_python(container.config.uvicorn.reload()),
33+
)

app/spotify/__init__.py

Whitespace-only changes.

app/spotify/exceptions.py

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
class SpotifyError(Exception):
2+
"""Base class for exceptions in this module."""
3+
pass
4+
5+
6+
class TrackNotFoundError(SpotifyError):
7+
"""Exception raised when a track is not found.
8+
9+
Attributes:
10+
message -- explanation of the error
11+
"""
12+
13+
def __init__(self, message: str):
14+
self.message = message
15+
16+
17+
class DeviceNotFoundError(SpotifyError):
18+
"""Exception raised when a device is not found.
19+
20+
Attributes:
21+
message -- explanation of the error
22+
"""
23+
24+
def __init__(self, message: str):
25+
self.message = message

app/spotify/router.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
from dependency_injector.wiring import inject, Provide
2+
from fastapi import APIRouter, Depends
3+
4+
from app.container import Container
5+
from app.spotify.schemas import Device
6+
from app.spotify.service import SpotifyService
7+
8+
spotify_router = APIRouter()
9+
10+
11+
@spotify_router.get("/devices")
12+
@inject
13+
def get_devices(
14+
spotify_service: SpotifyService = Depends(Provide[Container.spotify_service]),
15+
) -> list[Device]:
16+
return spotify_service.refresh_devices()

app/spotify/schemas.py

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
from pydantic import BaseModel
2+
3+
4+
class Device(BaseModel):
5+
id: str
6+
is_active: bool
7+
is_private_session: bool
8+
is_restricted: bool
9+
name: str
10+
supports_volume: bool
11+
type: str
12+
volume_percent: int
13+
14+
15+
class Track(BaseModel):
16+
id: str
17+
18+
@property
19+
def uri(self):
20+
return f"spotify:track:{self.id}"

app/spotify/service.py

Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
import spotipy
2+
3+
from app.spotify.exceptions import DeviceNotFoundError, TrackNotFoundError
4+
from app.spotify.schemas import Device, Track
5+
6+
7+
class SpotifyService:
8+
def __init__(
9+
self,
10+
client_id: str,
11+
client_secret: str,
12+
redirect_uri: str
13+
) -> None:
14+
self.__api = spotipy.Spotify(
15+
auth_manager=spotipy.SpotifyOAuth(
16+
client_id=client_id,
17+
client_secret=client_secret,
18+
redirect_uri=redirect_uri,
19+
scope="user-read-playback-state,user-modify-playback-state"
20+
)
21+
)
22+
23+
self.__devices = self.__get_devices_from_api()
24+
self.__current_device_index = 0
25+
26+
def play(self, track: Track) -> None:
27+
current_device = self.get_current_device()
28+
if current_device is None:
29+
raise DeviceNotFoundError("No device found")
30+
31+
try:
32+
self.__api.transfer_playback(
33+
device_id=current_device.id,
34+
force_play=False
35+
)
36+
self.__api.start_playback(
37+
device_id=current_device.id,
38+
uris=[track.uri]
39+
)
40+
except spotipy.exceptions.SpotifyException as e:
41+
if "Device not found" in e.msg:
42+
raise DeviceNotFoundError(e.msg)
43+
elif "Invalid track uri" in e.msg:
44+
raise TrackNotFoundError(e.msg)
45+
46+
def refresh_devices(self) -> list[Device]:
47+
self.__devices = self.__get_devices_from_api()
48+
self.__current_device_index = 0
49+
return self.__devices
50+
51+
def next_device(self) -> Device | None:
52+
if len(self.__devices) == 0:
53+
return None
54+
55+
self.__current_device_index = (self.__current_device_index + 1) % len(self.__devices)
56+
return self.get_current_device()
57+
58+
def previous_device(self) -> Device | None:
59+
if len(self.__devices) == 0:
60+
return None
61+
62+
self.__current_device_index = (self.__current_device_index - 1) % len(self.__devices)
63+
return self.get_current_device()
64+
65+
def get_current_device(self) -> Device | None:
66+
if len(self.__devices) == 0:
67+
return None
68+
69+
return self.__devices[self.__current_device_index]
70+
71+
def get_devices(self) -> list[Device]:
72+
print(self.__devices)
73+
return self.__devices
74+
75+
def __get_devices_from_api(self) -> list[Device]:
76+
devices_json = self.__api.devices()["devices"]
77+
return [Device(**device) for device in devices_json]

0 commit comments

Comments
 (0)