def on_click(self, event): player_uri = self._get_player() if player_uri is None: return try: player = Player(dbus_interface_info={'dbus_uri': player_uri}) except dbus.DBusException: return try: buttons = { 1: 'left', 2: 'middle', 3: 'right', 4: 'wheel_up', 5: 'wheel_down', 6: 'wheel_left', 7: 'wheel_right', 8: 'previous', 9: 'next', } btn_name = buttons[event['button']] action = getattr(self, 'button_' + btn_name) except KeyError: return try: if action == 'play': player.Play() elif action == 'toggle': player.PlayPause() elif action == 'pause': player.Pause() elif action == 'stop': player.Stop() elif action == 'volume_up': player.Volume += self.volume_offset elif action == 'volume_down': player.Volume -= self.volume_offset elif action == 'next': player.Next() elif action == 'previous': player.Previous() elif action == "forward": player.Seek(self.seek_offset * 1000000) elif action == "backward": player.Seek(-self.seek_offset * 1000000) except dbus.DBusException: return
def __getPlayers(self): DBusGMainLoop(set_as_default=True) self.players = [] for uri in get_players_uri(): player = Player(dbus_interface_info={'dbus_uri': uri}) p_status = player.PlaybackStatus title = player.Metadata.get('xesam:title') artist = player.Metadata.get('xesam:artist') album = player.Metadata.get('xesam:album') if title is not None and title != "": artist_str = '' if artist is not None: artist_str = ','.join(artist) self.players.append({ 'status': p_status.lower(), 'title': str(title), 'artist': artist_str, 'album': '' if album is None else str(album), 'player': player }) return self.players
def init_player(): try: # Get MPRIS client for client in get_players_uri(): # If the config specifies to ignore Chrome MPRIS if config.IGNORE_CHROME_MPRIS: # If the first MPRIS client is a Chrome instance if client.startswith('org.mpris.MediaPlayer2.chrome'): continue # Set the MPRIS uri to the active element global uri # pylint: disable=invalid-name uri = client break # Initialize player with URI global player # pylint: disable=invalid-name player = Player(dbus_interface_info={'dbus_uri': uri}) # pylint: disable=unexpected-keyword-arg # Everything worked, the player has been successfully initialized return True except: e = sys.exc_info()[0] # Something went wrong, the player has not been initialized # Returns information about the error return e
def main(self, message): action = 0 DBusGMainLoop(set_as_default=True) for unit in self._actions: if unit[0] in message.tokens: action = unit[1] if action == 0: message.run_next_skill() return uri = next(get_players_uri()) player = Player(dbus_interface_info={'dbus_uri': uri}) if action == 1: player.Play() elif action == 2: player.Pause() elif action == 3: player.PlayPause() elif action == 4: player.Next() elif action == 5: player.Previous() elif action == 6: message.send(player.Metadata) message.send("Action accomplished")
def main(): parser = argparse.ArgumentParser(description='MPRIS to Icecast bridge.') parser.add_argument('url', type=str, help='URL to Icecast server.') parser.add_argument('username', type=str, help='Username') parser.add_argument('password', type=str, help='Password') args = parser.parse_args() DBusGMainLoop(set_as_default=True) uri = next(get_players_uri()) player = Player(dbus_interface_info={'dbus_uri': uri}) player.PropertiesChanged = partial(properties_changed, args.url, (args.username, args.password)) mloop = gi.repository.GLib.MainLoop() mloop.run()
def getbestdbus(): log(time.time(), "Separator", "") log(time.time(), "Log", "Getting Best DBUS Interface\n") for x in get_players_uri(): uri = x player = Player(dbus_interface_info={'dbus_uri': uri}) if player.PlaybackStatus == "Playing": break log(time.time(), "Validation", "✓\n") return player
def _run_loop( fix_metadata: MetadataFixer, whitelist: List[str], scrobbler: Scrobbler ): uri = _get_valid_player_uri(whitelist) print(f"Found player {uri}") player = Player( # pylint: disable=unexpected-keyword-arg dbus_interface_info={"dbus_uri": uri} ) print(f"Listening to player {uri}\n") scrobble_loop = Looper(player, scrobbler, fix_metadata) scrobble_loop.run()
def player(self): try: #test if dbus connection can be used if self._player: self._player.CanControl return self._player except DBusException as e: #try create another connection self.log(logging.DEBUG, 'connection to %s is off, trying reconnect', self.bus_name) self._player = Player(dbus_interface_info={'dbus_uri': self.bus_name}) return self._player
def music(self): no_player = { 'full_text': self.format_down, 'cached_until': time.time() + self.cache_timeout_down, 'color': self.color_down } player_uri = self._get_player() if player_uri is None: return no_player try: player = Player(dbus_interface_info={'dbus_uri': player_uri}) metadata = player.Metadata playback_status = player.PlaybackStatus position = int(player.Position) except dbus.DBusException: return no_player info = player_info(metadata) length = convert_time(info['length']) info['length'] = self.length_format.format(**length) position = convert_time(position) info['position'] = self.position_format.format(**position) if playback_status == 'Playing': full_text = self.format.format(**info) return { 'full_text': full_text, 'cached_until': time.time() + self.cache_timeout, 'color': self.color } elif playback_status == 'Paused': full_text = self.format_paused.format(**info) return { 'full_text': full_text, 'cached_until': time.time() + self.cache_timeout_paused, 'color': self.color_paused } else: full_text = self.format_stopped.format(**info) return { 'full_text': full_text, 'cached_until': time.time() + self.cache_timeout_stopped, 'color': self.color_stopped }
def get_playing_state(): # Get MPRIS client for player in get_players_uri(): # If the config specifies to ignore Chrome MPRIS if config.IGNORE_CHROME_MPRIS: # If the first MPRIS client is a Chrome instance if player.startswith('org.mpris.MediaPlayer2.chrome'): continue # Set the MPRIS uri to the active element uri = player break # Initialize player with URI player = Player(dbus_interface_info={'dbus_uri': uri}) # pylint: disable=unexpected-keyword-arg # Try to add all fields to the playing_state object endpoints = ["TITLE", "ARTIST", "ALBUM", "ART_URI", "LENGTH"] ends_var = ["title", "artist", "album", "artwork", "length"] for endpoint in endpoints: end_var = ends_var[endpoints.index(endpoint)] try: if endpoint == "ARTIST": playing_state[end_var] = str(player.Metadata[getattr(player.Metadata, endpoint)][0]) continue playing_state[end_var] = str(player.Metadata[getattr(player.Metadata, endpoint)]) # Workaround to get working Spotify covers URL if endpoint == "ART_URI" and "open.spotify.com" in str(playing_state[end_var]): playing_state[end_var] = playing_state[end_var].replace('open.spotify.com', 'o.scdn.co') except: pass # Try to add song position to the playing_state object try: if str(player.Position) != "0": playing_state["position"] = str(player.Position) except: pass # Return a stringified JSON object return json.dumps(playing_state)
def get_active_player(): plids = reversed(list(get_players_uri())) player = None ps = None for i in list(plids): p = Player(dbus_interface_info={'dbus_uri': i}) try: ps = p.PlaybackStatus except Exception as e: print(str(e)) continue else: if ps == "Playing" or ps == "Paused": player = p if i.lower().split(".")[-1] in player_assets: current['player'] = i.lower().split(".")[-1] else: current['player'] = 'player' break return player
def now_playing(): current = None history = [] try: with open('playing.json', 'r') as f: j = json.loads(f.read()) current = j['current'] history = j['history'] except: traceback.print_exc() while True: try: uri = next(get_players_uri()) player = Player(dbus_interface_info={'dbus_uri': uri}) track = player.Metadata if track['mpris:trackid'] and ( current is None or track['mpris:trackid'] != current['mpris:trackid']): track['mpris:artUrl'] = track['mpris:artUrl'].replace( 'open.spotify.com', 'i.scdn.co') if current is not None: history.insert(0, current) while len(history) > 100: history.pop(len(history) - 1) current = track with open('playing.json.tmp', 'w') as f: f.write( json.dumps({ 'current': track, 'history': history, })) os.rename('playing.json.tmp', 'playing.json') except: traceback.print_exc() time.sleep(1)
def get_player(self, leaf): return Player(dbus_interface_info={'dbus_uri': leaf.mpris_uri})
from dbus.mainloop.glib import DBusGMainLoop from mpris2 import get_players_uri, Player import gi.repository.GLib import serial import time import sys DBusGMainLoop(set_as_default=True) uri = next(get_players_uri()) song_name = "Example" def another_handler(self, *args, **kw): if (song_name != player.Metadata['xesam:title']): update_song() def update_song(): global song_name metadata = player.Metadata song_name = metadata['xesam:title'] artist_name = artist_name = (metadata['xesam:artist'][0]) arduino.write((song_name + "*" + artist_name + "*").encode()) arduino = serial.Serial('/dev/ttyACM0', 9600) time.sleep(2) player = Player(dbus_interface_info={'dbus_uri': uri}) player.PropertiesChanged = another_handler mloop = gi.repository.GLib.MainLoop() update_song() mloop.run()
print( fg(32, 164, 226) + 'Telegram:' + fg.rs, f"https://telegram.me/share/url?url={url}") for uri in get_players_uri(): app_color = fg(255, 255, 255) if 'spotify' in uri: app = 'Spotify' app_color = fg(30, 215, 96) elif 'chrome' in uri: app = 'Google Chrome' else: app = str(uri).split('.')[-1] meta = Player(dbus_interface_info={'dbus_uri': uri}).Metadata tracks = TrackList(dbus_interface_info={'dbus_uri': uri}) try: print(app_color + '{:-^60}'.format(app) + fg.rs) if 'mpris:artUrl' in meta: art = urlopen(meta['mpris:artUrl']) colors = ColorThief(art).get_color(quality=1) else: colors = (255, 255, 255) print(fg(colors[0], colors[1], colors[2])) if type(meta['xesam:artist']) == dbus.Array: artist = meta['xesam:artist'][0]
def connect_to_all_players(self): for uri in get_players_uri(): p = Player(dbus_interface_info={'dbus_uri': uri}) p.PropertiesChanged = self.properties_changed_cb self.players.append(p)