|
| 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