nixos-config/home-manager/modules/polybar/scripts/polybar-playerctl

87 lines
2.2 KiB
Text
Raw Normal View History

2022-11-11 11:54:21 +01:00
#!/usr/bin/env python3
import os
import sys
import gi
from gi.repository import GLib
# Check Playerctl version
gi.require_version("Playerctl", "2.0")
2022-11-11 11:54:21 +01:00
from gi.repository import Playerctl
def player_status_str(status):
if status == Playerctl.PlaybackStatus.PLAYING:
return "Playing"
2022-11-11 11:54:21 +01:00
elif status == Playerctl.PlaybackStatus.PAUSED:
return "Paused"
2022-11-11 11:54:21 +01:00
elif status == Playerctl.PlaybackStatus.STOPPED:
return "Stopped"
2022-11-11 11:54:21 +01:00
else:
return "Unknown"
2022-11-11 11:54:21 +01:00
def now_playing_str(artist, title):
if artist == None and title == None:
return "No music information"
2022-11-11 11:54:21 +01:00
elif artist == None:
return title
else:
return f"{artist} - {title}"
2022-11-11 11:54:21 +01:00
players = Playerctl.list_players()
if len(players) == 0:
print("No players found")
exit(0)
homedir = os.environ["HOME"]
player_file = f"{homedir}/.playerctl_player"
current_player_name = ""
2022-11-11 11:54:21 +01:00
if os.path.isfile(player_file):
with open(player_file, mode="r") as file:
2022-11-11 11:54:21 +01:00
current_player_name = file.read()
player_found = False
player_changed = False
player_index = 0
for (index, p) in enumerate(players):
if p.instance == current_player_name:
player_found = True
player_index = index
break
if not player_found:
player = Playerctl.Player.new_from_name(players[0])
else:
player = Playerctl.Player.new_from_name(players[player_index])
if len(sys.argv) == 1:
out = f'ﱘ [{player.get_property("player-name")}] '
if player.props.playback_status == Playerctl.PlaybackStatus.PLAYING:
out += now_playing_str(player.get_artist(), player.get_title())
else:
out += player_status_str(player.get_property("playback_status"))
2022-11-11 11:54:21 +01:00
print(out)
elif sys.argv[1] == "next-player":
2022-11-11 11:54:21 +01:00
player_changed = True
player_index += 1
if player_index == len(players):
player_index = 0
player = Playerctl.Player.new_from_name(players[player_index])
elif sys.argv[1] == "play-pause":
2022-11-11 11:54:21 +01:00
player.play_pause()
elif sys.argv[1] == "next":
2022-11-11 11:54:21 +01:00
player.next()
elif sys.argv[1] == "previous":
2022-11-11 11:54:21 +01:00
player.previous()
if player_changed or not player_found:
with open(player_file, mode="w") as file:
file.write(player.get_property("player-instance"))
2022-11-11 11:54:21 +01:00
file.flush()