This repository has been archived by the owner on Aug 25, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 5
/
cmus.py
96 lines (86 loc) · 3.01 KB
/
cmus.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
import subprocess
import datetime
from i3situation.plugins._plugin import Plugin
__all__ = 'CmusPlugin'
class CmusPlugin(Plugin):
def __init__(self, config):
"""
Possible format options are:
status
file
duration
position
artist
album
title
date
genre
tracknumber
comment
replaygain_track_gain
aaa_mode
continue
play_library
play_sorted
replaygain
replaygain_limit
replaygain_preamp
repeat
repeat_current
shuffle
softvol
vol_left
vol_right
"""
self.options = {'interval': 1, 'format':
'artist - title - position/duration'}
super().__init__(config)
def main(self):
"""
A compulsary function that gets the output of the cmus-remote -Q command
and converts it to unicode in order for it to be processed and finally
output.
"""
try:
# Setting stderr to subprocess.STDOUT seems to stop the error
# message returned by the process from being output to STDOUT.
cmus_output = subprocess.check_output(['cmus-remote', '-Q'],
stderr=subprocess.STDOUT).decode('utf-8')
except subprocess.CalledProcessError:
return self.output(None, None)
if 'duration' in cmus_output:
status = self.convert_cmus_output(cmus_output)
out_string = self.options['format']
for k, v in status.items():
out_string = out_string.replace(k, v)
else:
out_string = None
return self.output(out_string, out_string)
def convert_cmus_output(self, cmus_output):
"""
Change the newline separated string of output data into
a dictionary which can then be used to replace the strings in the config
format.
cmus_output: A string with information about cmus that is newline
seperated. Running cmus-remote -Q in a terminal will show you what
you're dealing with.
"""
cmus_output = cmus_output.split('\n')
cmus_output = [x.replace('tag ', '') for x in cmus_output if not x in '']
cmus_output = [x.replace('set ', '') for x in cmus_output]
status = {}
partitioned = (item.partition(' ') for item in cmus_output)
status = {item[0]: item[2] for item in partitioned}
status['duration'] = self.convert_time(status['duration'])
status['position'] = self.convert_time(status['position'])
return status
def convert_time(self, time):
"""
A helper function to convert seconds into hh:mm:ss for better
readability.
time: A string representing time in seconds.
"""
time_string = str(datetime.timedelta(seconds=int(time)))
if time_string.split(':')[0] == '0':
time_string = time_string.partition(':')[2]
return time_string