forked from albertz/music-player
-
Notifications
You must be signed in to change notification settings - Fork 1
/
SongEdit.py
202 lines (175 loc) · 5.96 KB
/
SongEdit.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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
# -*- coding: utf-8 -*-
# MusicPlayer, https://github.com/albertz/music-player
# Copyright (c) 2012, Albert Zeyer, www.az2000.de
# All rights reserved.
# This code is under the 2-clause BSD license, see License.txt in the root directory of this project.
import utils
from utils import UserAttrib, Event, initBy
import Traits
import gui
# Note: I'm not too happy with all the complicated update handling here...
# In general, the design is ok. But it needs some more specification
# and then some drastic simplification. Most of it should be one-liners.
class SongEdit:
@initBy
def _updateEvent(self): return Event()
def __init__(self, ctx=None):
if not ctx:
import gui
ctx = gui.ctx()
assert ctx, "no gui context"
self.ctx = ctx
self._updateHandler = lambda: self._updateEvent.push()
ctx.curSelectedSong_updateEvent.register(self._updateHandler)
@UserAttrib(type=Traits.Object)
@property
def song(self):
return self.ctx.curSelectedSong
@UserAttrib(type=Traits.EditableText)
def artist(self, updateText=None):
if self.song:
if updateText:
self.song.artist = updateText
return self.song.artist
return ""
@UserAttrib(type=Traits.EditableText)
def title(self, updateText=None):
if self.song:
if updateText:
self.song.title = updateText
return self.song.title
return ""
@staticmethod
def _convertTagsToText(tags):
def txtForTag(tag):
value = tags[tag]
if value >= 1: return tag
return tag + ":" + str(value)
return " ".join(map(txtForTag, sorted(tags.keys())))
@staticmethod
def _convertTextToTags(txt):
pass
# todo...
#@UserAttrib(type=Traits.EditableText)
def tags(self, updateText=None):
if self.song:
return self._convertTagsToText(self.song.tags)
return ""
@staticmethod
def _formatGain(gain):
factor = 10.0 ** (gain / 20.0)
return "%f dB (factor %f)" % (gain, factor)
@UserAttrib(type=Traits.Table(keys=("key", "value")), variableHeight=True)
@property
def metadata(self):
d = dict(self.song.metadata)
for (key,func) in (
("artist",None),
("title",None),
("album",None),
("duration",utils.formatTime),
("url",None),
("rating",None),
("tags",self._convertTagsToText),
("gain",self._formatGain),
("completedCount",None),
("skipCount",None),
("lastPlayedDate",utils.formatDate),
("id",repr),
):
try: value = getattr(self.song, key)
except AttributeError: pass
else:
if func: value = func(value)
if not isinstance(value, (str,unicode)):
value = str(value)
d[key] = utils.convertToUnicode(value)
l = []
for key,value in sorted(d.items()):
l += [{"key": key, "value": value}]
return l
@metadata.setUpdateEvent
@property
def metadata_updateEvent(self): return self.song._updateEvent
def _queryAcoustId(self):
fingerprint = self.song.get("fingerprint_AcoustId", timeout=None)[0]
duration = self.song.get("duration", timeout=None, accuracy=0.5)[0]
import base64
fingerprint = base64.urlsafe_b64encode(fingerprint)
api_url = "http://api.acoustid.org/v2/lookup"
# "8XaBELgH" is the one from the web example from AcoustID.
# "cSpUJKpD" is from the example from pyacoustid
# get an own one here: http://acoustid.org/api-key
client_api_key = "cSpUJKpD"
params = {
'format': 'json',
'client': client_api_key,
'duration': int(duration),
'fingerprint': fingerprint,
'meta': 'recordings recordingids releasegroups releases tracks compress',
}
import urllib
body = urllib.urlencode(params)
import urllib2
req = urllib2.Request(api_url, body)
import contextlib
with contextlib.closing(urllib2.urlopen(req)) as f:
data = f.read()
headers = f.info()
import json
data = json.loads(data)
return data
def queryAcoustIdResults_selectionChangeHandler(self, selection):
self._queryAcoustId_selection = selection
@UserAttrib(type=Traits.Table(keys=("artist", "title", "album", "track", "score")),
selectionChangeHandler=queryAcoustIdResults_selectionChangeHandler)
@property
def queryAcoustIdResults(self):
if getattr(self, "_queryAcoustIdResults_songId", "") != getattr(self.song, "id", ""):
return []
return list(getattr(self, "_queryAcoustIdResults", []))
@queryAcoustIdResults.setUpdateEvent
@initBy
def queryAcoustIdResults_updateEvent(self): return Event()
@UserAttrib(type=Traits.Action, variableWidth=False)
def queryAcoustId(self):
data = self._queryAcoustId()
self._queryAcoustIdResults_songId = self.song.id
self._queryAcoustIdResults = []
for result in data.get("results", []):
for recording in result.get("recordings", []):
for resGroup in recording.get("releasegroups", []):
artist = resGroup["artists"][0]
release = resGroup["releases"][0]
medium = release["mediums"][0]
track = medium["tracks"][0]
if artist["name"] == "Various Artists":
artist = track["artists"][0]
entry = {
"id": result["id"],
"score": result["score"],
"recording-id": recording["id"],
"releasegroup-id": resGroup["id"],
"artist-id": artist["id"],
"artist": artist["name"],
"title": track["title"],
"album": resGroup["title"],
"track": "%i/%i" % (track["position"], medium["track_count"])
}
self._queryAcoustIdResults += [entry]
if not self._queryAcoustIdResults:
self._queryAcoustIdResults += [{"artist":"- None found -","title":"","album":"","track":""}]
self.queryAcoustIdResults_updateEvent.push()
@UserAttrib(type=Traits.Action, variableWidth=False, alignRight=True)
def apply(self):
if getattr(self, "_queryAcoustIdResults_songId", "") != getattr(self.song, "id", ""):
return
sel = getattr(self, "_queryAcoustId_selection", [])
if not sel: return
sel = sel[0]
for key in ("artist","title"):
if not sel[key]: return
for key in ("artist","title","album","track"):
setattr(self.song, key, sel[key])
self._updateEvent.push() # the song is updating itself - but the edit fields aren't atm...
gui.registerCtxRootObj(clazz=SongEdit, name="Song edit", priority=-2, keyShortcut='i')