.dotfiles/configs/waybar/mediaplayer.py

131 lines
3.8 KiB
Python
Raw Normal View History

2021-11-02 18:26:26 +01:00
#!/usr/bin/env python3
import argparse
import logging
import sys
import signal
import gi
import json
2021-11-22 18:45:44 +01:00
from os.path import expanduser
2021-11-02 18:26:26 +01:00
gi.require_version('Playerctl', '2.0')
from gi.repository import Playerctl, GLib
logger = logging.getLogger(__name__)
2021-11-22 18:45:44 +01:00
def write_output(text, player):
2021-11-02 18:26:26 +01:00
logger.info('Writing output')
2021-11-22 18:45:44 +01:00
output = {'text': text.replace("\n", " ").strip(),
'class': 'custom-' + player.props.player_name,
'alt': player.props.player_name}
2021-11-02 18:26:26 +01:00
sys.stdout.write(json.dumps(output) + '\n')
sys.stdout.flush()
2021-11-24 14:29:06 +01:00
def on_play(player, _, manager):
2021-11-02 18:26:26 +01:00
logger.info('Received new playback status')
on_metadata(player, player.props.metadata, manager)
2021-11-24 14:29:06 +01:00
def on_metadata(player, metadata, _):
2021-11-02 18:26:26 +01:00
logger.info('Received new metadata')
track_info = ''
if player.props.player_name == 'spotify' and \
'mpris:trackid' in metadata.keys() and \
':ad:' in player.props.metadata['mpris:trackid']:
track_info = 'AD PLAYING'
elif player.get_artist() != '' and player.get_title() != '':
track_info = '{artist} - {title}'.format(artist=player.get_artist(),
title=player.get_title())
else:
track_info = player.get_title()
if player.props.status != 'Playing' and track_info:
track_info = '' + track_info
2021-11-22 18:45:44 +01:00
write_output(track_info, player)
2021-11-02 18:26:26 +01:00
def on_player_appeared(manager, player, selected_player=None):
if player is not None and (selected_player is None or player.name == selected_player):
init_player(manager, player)
else:
logger.debug("New player appeared, but it's not the selected player, skipping")
def on_player_vanished(manager, player):
logger.info('Player has vanished')
sys.stdout.write('\n')
sys.stdout.flush()
def init_player(manager, name):
logger.debug('Initialize player: {player}'.format(player=name.name))
player = Playerctl.Player.new_from_name(name)
player.connect('playback-status', on_play, manager)
player.connect('metadata', on_metadata, manager)
manager.manage_player(player)
on_metadata(player, player.props.metadata, manager)
def signal_handler(sig, frame):
logger.debug('Received signal to stop, exiting')
sys.stdout.write('\n')
sys.stdout.flush()
2021-11-22 18:45:44 +01:00
# loop.quit()
2021-11-02 18:26:26 +01:00
sys.exit(0)
def parse_arguments():
parser = argparse.ArgumentParser()
# Increase verbosity with every occurrence of -v
parser.add_argument('-v', '--verbose', action='count', default=0)
# Define for which player we're listening
parser.add_argument('--player')
return parser.parse_args()
def main():
arguments = parse_arguments()
# Initialize logging
2022-01-17 14:48:30 +01:00
# LOG=expanduser("~")+"/.dotfiles/configs/waybar/media.log"
# logging.basicConfig(level=logging.DEBUG, filename=LOG,
# format='%(name)s %(levelname)s %(message)s')
2021-11-02 18:26:26 +01:00
# Logging is set by default to WARN and higher.
# With every occurrence of -v it's lowered by one
logger.setLevel(max((3 - arguments.verbose) * 10, 0))
2021-11-10 13:09:54 +01:00
logger.setLevel(0)
2021-11-02 18:26:26 +01:00
# Log the sent command line arguments
logger.debug('Arguments received {}'.format(vars(arguments)))
manager = Playerctl.PlayerManager()
loop = GLib.MainLoop()
manager.connect('name-appeared', lambda *args: on_player_appeared(*args, arguments.player))
manager.connect('player-vanished', on_player_vanished)
signal.signal(signal.SIGINT, signal_handler)
signal.signal(signal.SIGTERM, signal_handler)
for player in manager.props.player_names:
if arguments.player is not None and arguments.player != player.name:
logger.debug('{player} is not the filtered player, skipping it'
.format(player=player.name)
)
continue
init_player(manager, player)
loop.run()
2021-11-22 18:45:44 +01:00
2021-11-02 18:26:26 +01:00
if __name__ == '__main__':
main()