Ejemplo n.º 1
0
def _get_player_uri(whitelist: List[str]) -> Optional[str]:
    for uri in get_players_uri():
        name = _removeprefix(uri, URI_PREFIX)
        if any(_matches_rule(r, name) for r in whitelist):
            return uri

    return None
Ejemplo n.º 2
0
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
Ejemplo n.º 3
0
 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
Ejemplo n.º 4
0
    def initialize(self):
        # Grab the first URI in the list. This will just grab whatever media player happens to be first.
        try:
            uri = next(mpris2.get_players_uri())
            self.mediaPlayer = mpris2.Player(
                dbus_interface_info={'dbus_uri': uri})
        except StopIteration:
            pass

        self.log.info("Multimedia Control started. Controlling URI: " +
                      str(uri))

        # Bind to the various audio service messages
        self.add_event('mycroft.audio.service.play',
                       self.handler_mycroft_audio_service_play)
        self.add_event('mycroft.audio.service.stop',
                       self.handler_mycroft_audio_service_stop)
        self.add_event('mycroft.audio.service.pause',
                       self.handler_mycroft_audio_service_pause)
        self.add_event('mycroft.audio.service.resume',
                       self.handler_mycroft_audio_service_resume)
        self.add_event('mycroft.audio.service.next',
                       self.handler_mycroft_audio_service_next)
        self.add_event('mycroft.audio.service.prev',
                       self.handler_mycroft_audio_service_prev)
Ejemplo n.º 5
0
    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")
Ejemplo n.º 6
0
def get_player():
    uris = list(mpris2.get_players_uri())

    if len(uris) == 0:
        raise Exception("No Mpris2 player detected. Are you sure you're running Spotify?")

    if len(uris) == 1:
        match = uris[0]
    else:
        match = None
        for u in uris:
            if u.split('.')[-1] == "spotify":
                match = u
                break
        if match is None:
            print("Mpris2 players were found be not spotify. Please select a player:")
            for i, u in enumerate(uris):
                print("[%d] %s" % (i, u))

            while match is None:
                inp = input("Enter number: ")
                try:
                    inp = int(inp)
                except Exception as e:
                    print("%s is not a integer." % inp)
                if inp < 0 or inp >= len(uris):
                    print("%d is not a valid option." % inp)
                else:
                    match = uris[inp]

    return mpris2.Player(dbus_interface_info={'dbus_uri': match}), match
Ejemplo n.º 7
0
    def _get_player(self):
        if self.player_name:
            return 'org.mpris.MediaPlayer2.' + self.player_name

        # fetch all players
        players_uri = list(get_players_uri())
        if players_uri:
            return players_uri[0]
        return None
Ejemplo n.º 8
0
    def _get_players(self):
        for player in get_players_uri():
            try:
                # str(player) helps avoid to use dbus.Str(*) as dict key
                self._add_player(str(player))
            except DBusException:
                continue

        self._set_player()
Ejemplo n.º 9
0
	def __init__(self):
		# Try to connect to DBus
		try:
			uri = next(get_players_uri())
			self.player = Player(dbus_interface_info={'dbus_uri': uri})
		except StopIteration:
			self.commandOK = False
		else:
			self.commandOK = True
Ejemplo n.º 10
0
    def _get_player(self):
        if self.player_name:
            return 'org.mpris.MediaPlayer2.' + self.player_name

        # fetch all players
        players_uri = list(get_players_uri())
        if players_uri:
            return players_uri[0]
        return None
Ejemplo n.º 11
0
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
Ejemplo n.º 12
0
    def update_media_players(self):
        changed = False
        first_app = None
        first_playing_app = None
        uris = [str(uri) for uri in mpris2.get_players_uri()]

        removed_uris = set(self.app_by_player_uri).difference(uris)
        for uri in removed_uris:
            LOG.debug("Removed uri %r", uri)
            app = self.app_by_player_uri.pop(uri)
            app.remove_player()
            changed = True

        for uri in uris:
            if uri not in self.app_by_player_uri:
                self.add_player_uri(uri)
                changed = True
            app = self.app_by_player_uri[uri]
            if first_app is None:
                first_app = app
            if first_playing_app is None:
                if app.playback_status != PlaybackStatus.STOPPED:
                    first_playing_app = app
            else:
                if (
                    app.playback_status == PlaybackStatus.PLAYING
                    and first_playing_app.playback_status == PlaybackStatus.PAUSED
                ):
                    first_playing_app = app

        if first_playing_app is None:
            pass
        elif self.playing_app is None:
            self.playing_app = first_playing_app
            LOG.debug("Current player: %r", self.playing_app)
        elif (
            first_playing_app.playback_status == PlaybackStatus.PLAYING
            and self.playing_app.playback_status != PlaybackStatus.PLAYING
        ):
            self.playing_app = first_playing_app
            LOG.debug("Changed current player to: %r", self.playing_app)

        playback_status_list = [a.playback_status for a in self.app_list]
        if playback_status_list != self.playback_status_list:
            changed = True

        return changed
Ejemplo n.º 13
0
 def try_connect(self):
     """
     Sets self.player to a player and sets the prop_changed_handler
     if there is a mpris player on dbus or sets self.player to None
     """
     log("Try to connect to player", min_verbosity=4)
     uris = list(mpris2.get_players_uri())
     if len(uris):
         self.player = mpris2.Player(dbus_interface_info={
             'dbus_uri': uris[0]  # connects to the first player
         })
         self.player.PropertiesChanged = self.prop_changed_handler
         log("Connected to player", min_verbosity=4)
     else:
         log("Can't connect. No MPRIS player available",
             min_verbosity=4, error=True)
         self.player = None
Ejemplo n.º 14
0
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()
Ejemplo n.º 15
0
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)
Ejemplo n.º 16
0
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
Ejemplo n.º 17
0
def _configure_whitelist() -> List[str]:
    names = [_removeprefix(uri, URI_PREFIX) for uri in get_players_uri()]
    available = "\n".join(f"{i}. {x}" for i, x in enumerate(names, start=1))
    print(f"Currently available players:\n{available}\n")
    print("Please provide a whitelist of valid players:")
    whitelist = []

    for i in count(start=1):
        entry = input(f"{i}. ")
        if entry == "":
            break
        whitelist.append(entry)

    print("")

    if whitelist != []:
        with open(CONFIG_PATH, "a") as f:
            f.write(f"\nwhitelist = {json.dumps(whitelist, indent=4)}\n")
        print(f"Configuration saved to:\n{CONFIG_PATH}\n")

    return whitelist
Ejemplo n.º 18
0
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)
Ejemplo n.º 19
0
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()
Ejemplo n.º 20
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)
Ejemplo n.º 21
0
    def __init__(self, player_str):

        global app_desc
        global __version__

        player_uri = None
        player_uris = list(mpris2.get_players_uri())
        for uri in player_uris:
            if player_str in uri:
                player_uri = uri
                break
        if not player_uri:
            print('ERROR: No dbus players matched "{}"'.format(player_str))
            if player_uris:
                print('Available Player URIs:')
                for uri in player_uris:
                    print(' - {}'.format(uri))
            else:
                print('(No available player URIs found)')
            sys.exit(1)

        self.player = mpris2.Player(
            dbus_interface_info={'dbus_uri': player_uri})
        self.status = '(unknown)'
        self.trackid = None
        self.cur_pos = 0
        self.length = 0
        self.title = 'n/a'
        self.artist = 'n/a'
        self.album = 'n/a'

        main_header = urwid.Text('{} v{}'.format(app_desc, __version__),
                                 wrap='clip')
        header_widget = urwid.Padding(urwid.AttrMap(main_header,
                                                    'main_header'))

        labels = urwid.Pile([])
        values = urwid.Pile([])

        max_len = 0
        self.status_text = urwid.Text('', wrap='clip')
        self.status_attr = None
        self.artist_text = urwid.Text('', wrap='clip')
        self.album_text = urwid.Text('', wrap='clip')
        self.song_text = urwid.Text('', wrap='clip')
        self.position_text = urwid.Text('', wrap='clip')
        for label, val, is_status in [
            ('Connected to:', urwid.Text(player_uri, wrap='clip'), False),
            ('Status:', self.status_text, True),
            ('', urwid.Text(''), False),
            ('Album:', self.album_text, False),
            ('Artist:', self.artist_text, False),
            ('Song:', self.song_text, False),
            ('Position:', self.position_text, False),
        ]:
            if len(label) > max_len:
                max_len = len(label)
            attr_map = urwid.AttrMap(val, 'value')
            if is_status:
                self.status_attr = attr_map
            labels.contents.append(
                (urwid.AttrMap(urwid.Text(label, align='right'),
                               'label'), ('pack', None)))
            values.contents.append((attr_map, ('pack', None)))

        cols = urwid.Columns([(max_len, labels), values], dividechars=1)
        main_padding = urwid.Padding(cols, left=3, right=3)
        main_filler = urwid.Filler(main_padding, top=1, bottom=1)
        main_pile = urwid.Pile([])
        main_pile.contents.append((main_filler, ('weight', 1)))
        keys = []
        for key, label in [
            (TUIPlayer.KEY_PAUSE, 'play/pause'),
            ('{}/{}'.format(TUIPlayer.KEY_PREV,
                            TUIPlayer.KEY_NEXT), 'prev/next'),
            (TUIPlayer.KEY_STOP, 'stop'),
            (TUIPlayer.KEY_QUIT, 'quit'),
            ('{}/{}'.format(TUIPlayer.KEY_REV, TUIPlayer.KEY_FWD), 'rev/fwd'),
        ]:
            keys.append('[{}] {}'.format(key, label))
        main_pile.contents.append(
            (urwid.AttrMap(urwid.Text(', '.join(keys), wrap='clip'),
                           'keys'), ('pack', None)))
        main_box = urwid.LineBox(main_pile)
        main_frame = urwid.Frame(main_box, header_widget)

        palette = [('main_header', 'white', 'dark blue'),
                   ('label', 'yellow', 'black'), ('value', 'white', 'black'),
                   ('keys', 'light green', 'black'),
                   ('stopped', 'light red', 'black'),
                   ('paused', 'light blue', 'black'),
                   ('playing', 'light green', 'black'),
                   (None, 'white', 'black')]

        self.loop = urwid.MainLoop(
            main_frame,
            palette=palette,
            input_filter=self.input_filter,
        )
Ejemplo n.º 22
0
#!/usr/bin/env python
"""
Ugly hacky glue script for controlling any MPRIS2-compliant player with
multimedia keys. Depends on the ``mpris2`` Python package.

    mpris2-remote.py (PlayPause|Stop|Next|Previous)
"""
import sys

import mpris2

# Find player
uri = next(mpris2.get_players_uri())
# Connect to player
player = mpris2.Player(dbus_interface_info={'dbus_uri': uri})
# Get method name
assert len(sys.argv) == 2, 'Usage: mpris2-remote.py <method>'
method = sys.argv[1]
assert method in {'PlayPause', 'Stop', 'Next', 'Previous'}
# Call method
getattr(player, method)()
Ejemplo n.º 23
0
def PrintShareLink(artist, title, url):
    text = quote(title + " by " + artist)
    url = quote(url)

    print(
        fg(29, 161, 242) + 'Twitter:' + fg.rs,
        f"https://twitter.com/intent/tweet?hashtags=NowPlaying&related=spotify&text={text}&url={url}"
    )

    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)