/usr/lib/listen/cover_manager.py is in listen 0.6.5-9.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
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 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 | # -*- coding: utf-8 -*-
# vim: ts=4
###
#
# Listen is the legal property of mehdi abaakouk <theli48@gmail.com>
# Copyright (c) 2006 Mehdi Abaakouk
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 as
# published by the Free Software Foundation
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
#
###
import os
from urllib import quote
import fnmatch
import re
import gobject
import gtk
from mutagen.id3 import ID3
from config import config
import utils
from logger import Logger
from library import ListenDB
from xdg_support import get_xdg_cache_file, get_xdg_pixmap_file
from proxy import discover_http_proxy
from vfs import download, urlopen, get_uri_from_path
import amazon
proxy=discover_http_proxy()
if proxy.has_key("http"):
amazon.setProxy(proxy["http"])
REINIT_COVER_TO_SKIP_TIME = 100*60*30
COVER_SIZE = {"x":70,"y":70}
COVER_SAVE_SIZE = {"x":300,"y":300}
BROWSER_COVER_SIZE = {"x":40,"y":40}
KEEP_COVER_IN_MEMORY=True
"""
Glob patterns used to look for local cover images
The list is searched in this order
"""
COVER_PATTERNS = [
"cover.jpg", "cover.png",
"*front*.jpg", "*front*.png",
"*cover*.jpg", "*cover*.png",
"*album*.jpg", "*album*.png",
"folder.jpg", "folder.png",
".folder.jpg", ".folder.png",
"*artist*.jpg", "*artist*.png",
"*.jpg","*.png",
]
class ListenCoverManager(Logger):
COVER_PIXBUF = {}
COVER_TO_SKIP = []
def __init__(self):
gobject.timeout_add(REINIT_COVER_TO_SKIP_TIME, self.reinit_skip_cover)
self.DEFAULT_COVER = get_xdg_pixmap_file("listen_cover.png")
self.DEFAULT_COVER_PIXBUF = {
(40,40): gtk.gdk.pixbuf_new_from_file_at_size(self.DEFAULT_COVER,40,40),
(COVER_SIZE["x"],COVER_SIZE["y"]): gtk.gdk.pixbuf_new_from_file_at_size(self.DEFAULT_COVER,COVER_SIZE["x"],COVER_SIZE["y"]),
(BROWSER_COVER_SIZE["x"],BROWSER_COVER_SIZE["y"]): gtk.gdk.pixbuf_new_from_file_at_size(self.DEFAULT_COVER,BROWSER_COVER_SIZE["x"],BROWSER_COVER_SIZE["y"])
}
"""
List of album covers that I have already tried
to download on amazon website and which failed
this list is reinitialized every 30min
"""
def reinit_skip_cover(self):
self.COVER_TO_SKIP = []
"""
Return the name of the cover file without extention
"""
def get_cover_search_str(self,song):
#if not self.get_type() in sType.podcast and self.get_str("artist")!="":
# art=self.get_str("artist")+"+"
album = ""
if song.get_str("album")!="": album+=song.get_str("album")
cover_path = album.replace(os.sep,"")
cover_path = utils.filter_info_song(cover_path).encode('utf-8')
return cover_path
def get_pixbuf_from_album(self,album,x=None,y=None):
x = (x or BROWSER_COVER_SIZE["x"])
y = (y or BROWSER_COVER_SIZE["y"])
""" Only used in the browser """
filename = album.replace(os.sep,"")
filename = utils.filter_info_song(filename).encode('utf-8')
filename = get_xdg_cache_file("cover/%s.jpg"%filename)
if not os.path.exists(filename): filename = self.DEFAULT_COVER
if not self.COVER_PIXBUF.has_key((filename,x,y)) :
#print "I:Song:Load pixbuf",filename
try:
pixbuf = gtk.gdk.pixbuf_new_from_file_at_size(filename,x,y)
except gobject.GError:
self.logwarn("failed to load %s, try deleted it...",filename)
try: os.unlink(filename)
except: pass
pixbuf = None
elif KEEP_COVER_IN_MEMORY:
pixbuf = self.COVER_PIXBUF[(filename,x,y)]
else:
pixbuf = None
if not pixbuf:
if not self.DEFAULT_COVER_PIXBUF.has_key((x,y)):
self.DEFAULT_COVER_PIXBUF[(x,y)] = gtk.gdk.pixbuf_new_from_file_at_size(self.DEFAULT_COVER,x,y)
pixbuf = self.DEFAULT_COVER_PIXBUF[(x,y)]
if KEEP_COVER_IN_MEMORY:
self.COVER_PIXBUF[(filename,x,y)] = pixbuf
return pixbuf
def remove_pixbuf_from_cache(self,album,x=None,y=None):
filename = album.replace(os.sep,"")
filename = utils.filter_info_song(filename).encode('utf-8')
filename = get_xdg_cache_file("cover/%s.jpg"%filename)
for info in self.COVER_PIXBUF.keys():
if filename == info[0]:
del self.COVER_PIXBUF[info]
"""
Return path of the local album art
It can not exist
"""
def has_cover(self,song):
cover = self.get_cover(song, False)
return cover != self.DEFAULT_COVER and os.path.exists(cover)
def get_cover_path(self,song):
if ListenDB.song_has_capability(song,"nocover"):
return self.DEFAULT_COVER
return get_xdg_cache_file("cover/"+self.get_cover_search_str(song)+".jpg")
def get_pixbuf_from_song(self,song,x,y,try_web=True):
filename = self.get_cover(song,try_web)
if not self.COVER_PIXBUF.has_key((filename,x,y)) :
try:
pixbuf = gtk.gdk.pixbuf_new_from_file_at_size(filename,x,y)
except gobject.GError:
self.logwarn("failed to load %s in a pixbuf",filename)
try: os.unlink(filename)
except: pass
pixbuf = None
elif KEEP_COVER_IN_MEMORY:
pixbuf = self.COVER_PIXBUF[(filename,x,y)]
else:
pixbuf = None
if not pixbuf:
if not self.DEFAULT_COVER_PIXBUF.has_key((x,y)):
self.DEFAULT_COVER_PIXBUF[(x,y)] = gtk.gdk.pixbuf_new_from_file_at_size(self.DEFAULT_COVER,x,y)
pixbuf = self.DEFAULT_COVER_PIXBUF[(x,y)]
if KEEP_COVER_IN_MEMORY:
self.COVER_PIXBUF[(filename,x,y)] = pixbuf
return pixbuf
"""
Return path of the existing album art to display
Or default cover if not found
Must be ONLY use in a thread
because it use amazon to get cover and if they don't have internet connection listen freeze
"""
def get_cover(self,song, try_web=True):
default_image_path = self.DEFAULT_COVER
art = self.get_cover_search_str(song)
image_path = get_xdg_cache_file("cover/%s.jpg"%art)
image_path_disable = get_xdg_cache_file("cover/%s.jpg.#disable#"%art)
if ListenDB.song_has_capability(song,"nocover") or \
not song.get("album") or \
os.path.exists(image_path_disable) or \
image_path in self.COVER_TO_SKIP or \
( not song.get("artist") and song.get_type() == "lastfmradio") :
#self.loginfo("media not authorized to have cover: %s",image_path)
return default_image_path
# cover already exist
if os.path.exists(image_path): return image_path
# retrieve cover from mp3 tag """
if song.get_scheme() == "file" and song.get_ext() in [".mp3",".tta"]:
#self.logdebug("trying mp3 tag")
found = False
f = None
try:
f = file(image_path,"wb+")
tag = ID3(song.get_path())
for frame in tag.getall("APIC"):
found = True
#print len(frame.data)
f.write(frame.data)
f.flush()
f.seek(0, 0)
except:
if f: f.close()
else:
if f: f.close()
if found and self.cleanup_cover(song, image_path):
self.logdebug("cover found in mp3 tag: %s",image_path)
return image_path
# search in local directory of the file
if song.get("uri") != None and song.get_scheme() == "file" :
filename = song.get_path()
path = filename[:filename.rfind("/")]
if os.path.exists(path):
list_file = os.listdir(path)
for pattern in COVER_PATTERNS:
matches = fnmatch.filter(list_file, pattern)
if matches:
self.logdebug("trying local directory (%s)",matches)
""" in case of multiple matches, sort by lenght then by order """
matches = sorted(matches, lambda a,b: (len(a)-len(b))*10+cmp(a,b))
if self.cleanup_cover(song, path+"/"+matches[0], image_path):
self.logdebug("cover found in local directory: %s",image_path)
return image_path
# Check on webservice
if not config.getboolean("setting","offline") and try_web:
try:
ret = False
# try url cover tag
if song.get("album_cover_url"):
ret = download(song.get("album_cover_url"), get_uri_from_path(image_path))
if ret and self.cleanup_cover(song, image_path):
self.logdebug("cover found in album_cover_url tag: %s",image_path)
return image_path
# try lastfm
lastfm_url = "http://ws.audioscrobbler.com/1.0/album/%s/%s/info.xml"%(quote(song.get_str("artist").encode("utf-8")),quote(song.get_str("album").encode("utf-8")))
self.logdebug("trying lastfm (url:%s)"%lastfm_url)
try:
fp = urlopen(lastfm_url)
except:
pass
self.logexception("failed to retrieve %s",lastfm_url)
else:
res_exp = re.search("<large>(.*)</large>",fp.read(),re.S)
if res_exp:
lastfm_img_url = res_exp.group(1)
if lastfm_img_url.find("noimage") == -1:
ret = download(lastfm_img_url, get_uri_from_path(image_path) )
if ret and self.cleanup_cover(song, get_uri_from_path(image_path)):
self.logdebug("cover found on lastfm: %s",image_path)
return image_path
# try amazon
self.logdebug("trying amazon (search:%s)"%utils.remove_accents(art))
try:
pages = amazon.ItemSearch(utils.remove_accents(art), "Music", \
Condition="All", MerchantId="All", Availability=None, \
ResponseGroup="Images,Request" )
p = pages.next()
except:
pass
self.logexception("failed to search on amazon")
else:
if hasattr(p, "LargeImage"):
ret = download(p.LargeImage.URL, get_uri_from_path(image_path))
if ret and self.cleanup_cover(song, image_path):
self.logdebug("cover found on amazon: %s",image_path)
return image_path
except:
self.logexception("Exception not catched while retrieve cover")
# cover not exist at all, not looking for it anymore
self.COVER_TO_SKIP.append(image_path)
# No cover found
self.remove_cover(song)
if try_web:
self.logdebug("cover not found %s (web:%s)", image_path, try_web )
return default_image_path
"""
Delete album cover from harddisk
"""
def remove_cover(self,song):
if ListenDB.song_has_capability(song,"nocover"): return
image_path = self.get_cover_path(song)
if image_path in self.COVER_TO_SKIP:
del self.COVER_TO_SKIP[self.COVER_TO_SKIP.index(image_path)]
if os.path.exists(image_path):
os.unlink(image_path)
self.remove_pixbuf_from_cache(song.get_sortable("album"))
def cleanup_cover(self, song, old_path, path=None):
if not path: path = old_path
# Change resolution
if not os.path.exists(old_path):
self.logwarn("file %s does not exist !", old_path)
return False
try: pixbuf = gtk.gdk.pixbuf_new_from_file_at_size(old_path, COVER_SAVE_SIZE["x"], COVER_SAVE_SIZE["y"])
except gobject.GError:
self.logwarn("image %s have a incorrect format", old_path)
return False
else:
# Check cover is not a big black image
str_pixbuf = pixbuf.get_pixels()
if str_pixbuf.count("\x00") > len(str_pixbuf)/2 or str_pixbuf.count("\xff") > len(str_pixbuf)/2 :
return False
else:
if os.path.exists(path): os.unlink(path)
pixbuf.save(path, "jpeg", {"quality":"85"})
del pixbuf
# Change property album to update UI
ListenDB.set_property(song,{"album":song.get("album")})
return True
CoverManager = ListenCoverManager()
|