usr bin env python -coding utf8- import socket sys host 127 TODO хост

  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
 97
 98
 99
100
#! /usr/bin/env python
#-*-coding:utf8-*-
import socket, sys
host = '127.0.0.1'#TODO: хост и порт можно будет передавать в аргсах
port = 6600
class Mpd():
def __init__(self):
self.sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
def connect(self, host, port):
try:
self.sock.connect((host, port))
except socket.error:
return None
return self.sock.recv(1024)
def close(self):
self.sock.close()
def __query__(self, s = ''):
self.sock.send(s + '\n')
ss = ''
while 1:
b = self.sock.recv(1024)
ss += b
if len(b) < 1024: break
return ss
def getStatus(self):
time = ''
song = ''
for each in self.__query__('status').split('\n'):
if each.startswith('song: '):
song = each.split(': ')[-1]
elif each.startswith('time: '):
time = each.split(': ')[-1]
return song, (sec2min(time.split(':')[0]), sec2min(time.split(':')[-1])) if time else time
def getSong(self, songid):
i = {}
for each in self.__query__('playlistinfo ' + songid).split('\n'):
e = each.split(': ')
if len(e) == 2:
i[e[0]] = e[1]
return i
def sec2min(time):
return (lambda minsec:'%s:%s' % (minsec[0], '0' + str(minsec[1]) if minsec[1] < 10 else minsec[1]))(divmod(int(time), 60))
keys = {'%artist':'Artist', '%track':'Track', '%time':'Time', '%fulltime':'Fulltime', '%title':'Title', '%album':'Album'}
def printNp(template, song):
endpos = 0
while 1:
t = 1
try:
pos = template.index('$if', endpos)
endpos = template.index('$', pos + 1)
s = template[pos:endpos]
conditions = s[4:s.index(':')]
val = s[s.index(':')+1:]
except ValueError:break
for condition in conditions.split():
if condition == 'and': pass
else:
if '%' + condition not in keys.keys():
t = 0
else:
if keys['%' + condition] not in song.keys():
t = 0
if t:
template = template[:pos] + val + template[endpos + 1:]
else:
template = template[:pos] + template[endpos + 1:]
for key in keys.keys():
if key in template:
val = song[keys[key]] if keys[key] in song.keys() else ''
template = template.replace(key, val)
print template
def main():
template = '%artist$if artist and title: — $%title (%time/%fulltime)' #TODO: темплейт можно будет передавать в аргсах
mpd = Mpd()
if not mpd.connect(host, port):
print 'mpd not running'
return
songid, time = mpd.getStatus()
if not songid or not time:
print 'silence'
return
song = mpd.getSong(songid)
song['Time'] = time[0]
song ['Fulltime'] = time[1]
printNp(template, song)
mpd.close()
if __name__=='__main__':
main()
sys.exit()