def on_child(f, token, path, entries): # abort if the user has changed the directory inbetween if (token != self.__token): return False profile_now = time.time() if (f): #self.set_message("Loading") # (%d items)" % len(self.get_files())) entries.append(f) try: self.__add_file(f) self.emit_event(self.EVENT_FOLDER_PROGRESS, self.get_current_folder(), f) except: print logging.stacktrace() else: message = self.get_current_folder().message if (message): self.set_message(message) else: self.set_message("") # mark folder as complete self.__path_stack[-1][1] = _STATUS_OK self.invalidate() self.emit_event(self.EVENT_FOLDER_COMPLETE, self.get_current_folder()) # now is a good time to collect garbage import gc gc.collect() #end if # give visual feedback while loading the visible part of a folder if (len(entries) == 16 or not f): #not f or len(entries) == 12): profile_now3 = time.time() self.invalidate() self.render() logging.profile(profile_now3, "[browser] rendered list view") #while (gtk.events_pending()): # gtk.main_iteration(True) #end if # don't block UI while loading non-local folders #t = int((time.time() - open_time) * 10) if (time.time() > open_time + 3 and len(entries) % 2 == 0): while (gtk.events_pending()): gtk.main_iteration(False) if (not f): # last item has been reached logging.profile(open_time, "[browser] loaded %d items", len(entries)) return False else: # continue loading next item #logging.profile(profile_now, "[browser] added %dth item", # len(entries)) return True
def __load_components(self, mod): """ Loads the components of the given module. """ syspath = sys.path[:] sys.path = [mod._syspath] + syspath logging.debug("loading module [%s]", mod.__file__) try: classes = mod.get_classes() except AttributeError: classes = [] except: logging.error(logging.stacktrace()) classes = [] for c in classes: try: logging.debug("creating [%s]" % c.__name__) comp = c() #comp._attach_to_message_bus() self.__components.append(comp) except: logging.error("could not instantiate class [%s]:\n%s" % (`c`, logging.stacktrace())) #end for try: device_classes = mod.get_devices() except AttributeError: device_classes = [] except: logging.error(logging.stacktrace()) device_classes = [] for c in device_classes: try: logging.debug("adding device [%s]" % c.__name__) comp = c() #comp._attach_to_message_bus() self.__devices.append(comp) except: logging.error("could not instantiate class [%s]:\n%s" % (`c`, logging.stacktrace())) #end for sys.path = syspath
def __parse_genres(self, data): """ Parses the list of genres. """ self.call_service(msgs.UI_ACT_SHOW_INFO, "SHOUTcast made it illegal for free software to access\n" \ "their full directory.\n" \ "You will only get the Top 10 stations listed per genre.") genres = [] soup = BeautifulSoup(data) radiopicker = soup.find("div", {"id": "radiopicker"}) #print radiopicker if (radiopicker): for genre_tag in radiopicker.findAll("li", {"class": "prigen"}): #print genre_tag name = genre_tag.a.contents[0] name = name.replace("&", "&") genres.append(name) #end for #end if if (not genres): self.__current_folder.message = "genre list not available" logging.error("SHOUTcast genre listing download failed:\n%s", logging.stacktrace()) genres.sort() return genres
def __parse_genres(self, data): """ Parses the list of genres. """ genres = [] soup = BeautifulSoup(data) tagcloud = soup.find("ul", {"class": "tag-cloud"}) #print tagcloud if (tagcloud): for genre_tag in tagcloud.findAll("a", {"class": "tag"}): #print genre_tag name = genre_tag["title"] href = genre_tag["href"] genres.append((name, href)) #end for #end if if (not genres): self.__current_folder.message = "genre list not available" logging.error("icecast genre listing download failed:\n%s", logging.stacktrace()) genres.sort(lambda a, b: cmp(a[0], b[0])) return genres
def __get_thumbnail_path(self, f): """ Returns the full path for the thumbnail for the given file. """ md5 = f.thumbnail_md5 thumb_fallback = os.path.join(self.__THUMB_FOLDER, md5 + ".jpg") if (not self.__STORE_ON_MEDIUM): return thumb_fallback else: medium = f.medium if (not medium or medium == "/"): return thumb_fallback else: prefix = os.path.join(medium, ".mediabox", "thumbnails") if (not os.path.exists(prefix)): try: os.makedirs(prefix) except: logging.error( "could not create thumbnails directory:" "%s\n%s", prefix, logging.stacktrace()) return thumb_fallback #end if #end if thumb = os.path.join(prefix, md5 + ".jpg") return thumb
def __process_event_body(self, event_instance, body, uuid): if (not uuid in self.__handlers): event_instance.send_answer("HTTP/1.1 412 Precondition Failed") return #print "BODY", body prop_set = MiniXML(body).get_dom() prop = prop_set.get_child() for change in prop.get_children(): signal_name = "changed::" + change.get_name().lower() # notify all subscribers for cb in self.__handlers[uuid]: try: signal_value = change.get_child().get_value() except: import traceback; traceback.print_exc() signal_value = "" try: cb(signal_name, signal_value) except: logging.error(logging.stacktrace()) #end for logging.debug("[upnp gena] signal emitted: %s = %s", signal_name, signal_value) event_instance.send_answer("HTTP/1.1 200 OK")
def handle_HTTPSERVER_SVC_BIND_UDP(self, owner, addr, port): if ((addr, port) in self.__listeners): return "address already in use" try: sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.bind((addr, port)) except: logging.error("[httpserv] error binding to %s:%d\n%s", addr, port, logging.stacktrace()) return "could not bind to address" self.__listeners[(addr, port)] = _Listener(owner, sock, None) t = threading.Thread(target = self.__listen_for_dgram, args = [addr, port, sock, owner]) t.setDaemon(True) t.start() logging.info("[httpserv] bound to UDP %s:%d", addr, port) return ""
def __on_collect_values(self, sock, cond, buf): if (cond == gobject.IO_HUP): self.__collect_handler = None self.__maybe_eof = 1 self.__stop_mplayer() return False else: buf[0] += self.__read() buf[0] = buf[0].replace("\r", "\n") idx = buf[0].find("\n") while (idx >= 0): line = buf[0][:idx] buf[0] = buf[0][idx + 1:] try: self.__parse_value(line) except: logging.error("error parsing mplayer output: %s\n%s", line, logging.stacktrace()) idx = buf[0].find("\n") #end while return True
def __save_stations(self): """ Saves the current list of radio stations. """ try: maemostations.save_stations(self.__stations) except: logging.error("could not save list of radio stations:\n%s" \ % logging.stacktrace())
def __save_bookmarks(self): if (not self.__is_dirty): return locations = [f.full_path for f in self.__items] try: open(_BOOKMARK_FILE, "w").write("\n".join(locations)) except: logging.error("could not save bookmarks\n%s", logging.stacktrace()) return self.__is_dirty = False
def __parse_stations(self, data, genre): """ Parses the list of stations. """ stations = [] soup = BeautifulSoup(data) resulttable = soup.find("div", {"id": "resulttable"}) if (resulttable): for entry in resulttable.findAll("div", {"class": "dirlist"}): #print entry station = File(self) a_tag = entry.find("a", {"class": "playbutton playimage"}) playing_tag = entry.find("div", {"class": "playingtext"}) bitrate_tag = entry.find("div", {"class": "dirbitrate"}) type_tag = entry.find("div", {"class": "dirtype"}) if (not a_tag or not playing_tag or not bitrate_tag or not type_tag): continue station.resource = a_tag["href"] station.name = a_tag["title"] now_playing = playing_tag["title"] bitrate = bitrate_tag.contents[0].strip() typename = type_tag.contents[0].strip() if (typename == "MP3"): station.mimetype = "audio/mpeg" elif (typename == "AAC+"): station.mimetype = "audio/mp4" else: station.mimetype = "audio/x-unknown" station.path = File.pack_path("/" + urlquote.quote(genre, ""), station.name, bitrate, station.mimetype, station.resource, genre) station.info = "Bitrate: %s kb\n" \ "Now playing: %s" % (bitrate, now_playing) station.icon = theme.shoutcast_station.get_path() stations.append(station) #end for #end if if (not stations): self.__current_folder.message = "station list not available" logging.error("SHOUTcast station listing download failed\n%s", logging.stacktrace()) stations.sort() return stations
def write_user_mapping(): try: fd = open(_PLAYERS_MAPPING_FILE2, "w") except: logging.error("could not write players.mapping:\n%s", logging.stacktrace()) return for mt, backend in _MAPPING_TABLE.items(): fd.write("%s %s\n" % (mt, backend)) fd.close()
def __start_xine(self): bus = maemo.get_session_bus() try: obj = bus.get_object(_SERVICE_NAME, _OBJECT_PATH) self.__player = dbus.Interface(obj, _PLAYER_IFACE) self.__player.connect_to_signal("aspect_changed", self.__on_aspect_changed) self.__player.connect_to_signal("end_of_stream", self.__on_end_of_stream) except: logging.error("cannot start Xine backend:\n%s", logging.stacktrace())
def __load_stations(self): """ Loads the configured radio stations. """ try: stations = maemostations.get_stations() except: logging.error("could not load list of radio stations:\n%s" \ % logging.stacktrace()) stations = [] for freq, name in stations: self.__add_station(freq, name)
def __parse_stations(self, data, genre): """ Parses the XML list of stations. """ stations = [] try: dtree = ElementTree.parse(StringIO(data)) for i in dtree.getiterator(): if i.tag == "station": # build station object station = File(self) bitrate = "-" now_playing = "-" for j,n in i.items(): if j == "name": station.name = n elif j == "ct": now_playing = n elif j == "id": station.resource = _SHOUTCAST_BASE + "/sbin/shoutcast-playlist.pls?rn=%s&file=filename.pls" % n elif j == "br": bitrate = n elif j == "mt": station.mimetype = n station.path = "/" + genre + "/" + \ self.__encode_station(station.name, bitrate, station.mimetype, station.resource, genre) station.info = "Bitrate: %s kb\n" \ "Now playing: %s" % (bitrate, now_playing) station.icon = theme.shoutcast_station stations.append(station) except: self.call_service(msgs.UI_ACT_SHOW_INFO, "An error occured while loading the list of stations.\n" \ "Check your internet connection and try again.") logging.error("SHOUTcast station listing download failed\n%s", logging.stacktrace()) stations.sort() return stations
def __init__(self, schema): # the current context self.__context = msgs.INPUT_EV_CONTEXT_BROWSER # the current event self.__event = None # table: (key, context) -> (event, context) self.__mapping = {} try: logging.debug("parsing schema") self.__parse_schema(schema) logging.debug("parsing schema done") except: logging.error("syntax error in schema:\n%s\n%s", schema, logging.stacktrace())
def __load_bookmarks(self): self.__needs_reload = False self.__items = [] try: lines = open(_BOOKMARK_FILE, "r").readlines() except: logging.error("could not load bookmarks\n%s", logging.stacktrace()) return for line in lines: f = self.call_service(msgs.CORE_SVC_GET_FILE, line.strip()) if (f): self.__items.append(f) #end for self.__is_dirty = False
def __make_station(self, s): try: name, bitrate, mimetype, location, genre = self.__decode_station(s) except: logging.error("error decoding iradio path: %s\n%s", path, logging.stacktrace()) return None f = File(self) f.name = name f.info = "Bitrate: %s kb" % bitrate f.resource = location f.path = "/" + urlquote.quote(genre, "") + "/" + s f.mimetype = mimetype f.icon = theme.shoutcast_station.get_path() return f
def __make_station(self, s): try: prefix, name, bitrate, mimetype, location, genre = File.unpack_path( s) except: logging.error("error decoding iradio path: %s\n%s", path, logging.stacktrace()) return None f = File(self) f.name = name f.info = "Bitrate: %s kb" % bitrate f.resource = location f.path = s f.mimetype = mimetype f.icon = theme.shoutcast_station.get_path() return f
def __load_lyrics(self, lrc_path): """ Loads the given LRC file. """ try: data = open(lrc_path).read() #data = self.__decode(open(lrc_path).read()) lines = [l for l in data.splitlines() if l.startswith("[")] except: logging.error("error loading lyrics file '%s'\n%s", lrc_path, logging.stacktrace()) lines = [] lines = self.__decode("\n".join(lines)).splitlines() for line in lines: self.__parse_line(line) self.__lyrics.sort(lambda a, b: cmp(a[0], b[0]))
def __load_module(self, path): """ Loads and returns the module from the given path. Returns None if the module could not be loaded. """ syspath = sys.path[:] sys.path = [os.path.dirname(path)] + syspath try: mod = __import__(os.path.basename(path)) mod._syspath = os.path.dirname(path) sys.path = syspath return mod except: logging.error("could not load component [%s]:\n%s" \ % (path, logging.stacktrace())) sys.path = syspath return None
def send_event(self, src, event, *args): if (logging.is_level(logging.DEBUG)): logging.debug("*** %s%s ***", msgs._id_to_name(event), ` args ` [:30]) try: handlers = self.__handlers[event] except: handlers = [] for handler in handlers: try: handler(*args) except: logging.error("error during event call: %s\n%s", msgs._id_to_name(event), logging.stacktrace()) #end for """
def call_service(self, svc, *args): if (logging.is_level(logging.DEBUG)): logging.debug("*** %s%s ***", msgs._id_to_name(svc), ` args ` [:30]) try: handlers = self.__handlers[svc] except: handlers = [] for handler in handlers: try: return handler(*args) except: logging.error("error during service call: %s\n%s", msgs._id_to_name(svc), logging.stacktrace()) #end for """
def handle_COM_EV_APP_STARTED(self): logging.profile(values.START_TIME, "[app] startup complete") # load state try: path, play_files, play_folder, current_file = state.load( _STATEFILE) path_stack = [] for p in path: f = self.call_service(msgs.CORE_SVC_GET_FILE, p) if (f): path_stack.append(f) self.emit_message(msgs.CORE_EV_FOLDER_VISITED, f) #end if #end for self.__browser.set_path_stack(path_stack) #self.__play_files = [ self.call_service(msgs.CORE_SVC_GET_FILE, p) # for p in play_files # if self.call_service(msgs.CORE_SVC_GET_FILE, p) ] self.__play_folder = self.call_service(msgs.CORE_SVC_GET_FILE, play_folder) self.__current_file = self.call_service(msgs.CORE_SVC_GET_FILE, current_file) except: logging.warning("could not restore navigator state:\n%s", logging.stacktrace()) self.__arr.set_visible(True) self.render() if (values.uri and (values.uri.startswith("http://") or os.path.exists(values.uri))): ext = os.path.splitext(values.uri)[1] mimetype = mimetypes.ext_to_mimetype(ext) f = self.call_service( msgs.CORE_SVC_GET_FILE, "adhoc://" + File.pack_path("/", values.uri, mimetype)) self.__load_file(f, True)
def _set_thumbnail(self, f, pbuf): """ Saves the given pixbuf as thumbnail for the given file. Thumbnailers may use this method for caching thumbnails. """ # always scale down large thumbnails if (pbuf.get_width() > 200 or pbuf.get_height() > 200): _PBUF.fill(0x00000000) pixbuftools.fit_pbuf(_PBUF, pbuf, 0, 0, 200, 200, True) pbuf = _PBUF #end if path = self.__get_thumbnail_path(f) try: pbuf.save(path, "jpeg") return path except: logging.error("cannot save thumbnail:\n%s", logging.stacktrace()) return ""
def get_file(self, path): try: name, location = self.__decode_path(path) except: logging.error("error decoding iradio path: %s\n%s", path, logging.stacktrace()) return None f = File(self) f.name = name f.info = location f.path = path f.resource = location if (location.endswith(".ram") or location.endswith(".rm")): f.mimetype = "application/vnd.rn-realmedia" else: f.mimetype = "audio/x-unknown" f.icon = theme.iradio_device return f
def __get_video(self, f): """ Returns the video URL. """ if (f.resource == _REGION_BLOCKED): self.emit_message(msgs.UI_ACT_SHOW_INFO, "This video is not available in your country.") return ("", "") try: fmts = self.__get_flv(f.resource) except: logging.error("could not retrieve video\n%s", logging.stacktrace()) return "" #if (not 18 in fmts): fmts.append(18) f_ids = fmts.keys() f_ids.sort(formats.comparator) # filter out incompatible formats if (platforms.MAEMO5): f_ids = [f for f in f_ids if f in _N900_FORMAT_WHITELIST] elif (platforms.MAEMO4): f_ids = [f for f in f_ids if f in _N8x0_FORMAT_WHITELIST] # retrieve high-quality version, if desired if (len(f_ids) > 1): qtype = self.__ask_for_quality(f_ids) elif (len(f_ids) == 1): qtype = f_ids[0] else: qtype = 5 print "Requested Video Quality:", qtype flv = fmts[qtype] ext = "." + formats.get_container(qtype) logging.info("found FLV: %s", flv) return flv + "&ext=" + ext
def __parse_genres(self, data): """ Parses the XML list of genres. """ genres = [] try: dtree = ElementTree.parse(StringIO(data)) for i in dtree.getiterator(): if i.tag == "genre": for j,n in i.items(): if j == "name": genres.append(n) except: self.call_service(msgs.UI_ACT_SHOW_INFO, "An error occured while loading the list of genres.\n" \ "Check your internet connection and try again.") logging.error("SHOUTcast genre listing download failed:\n%s", logging.stacktrace()) genres.sort() return genres
def __load_index(self): """ Deserializes the index from file. """ try: import cPickle fd = open(_INDEX_FILE, "rb") except: return try: magic, data = cPickle.load(fd) except: logging.error(logging.stacktrace()) return finally: fd.close() # ignore the file if it isn't compatible if (magic == _MAGIC): self.__current_id, self.__entries, self.__indices = data self.__is_dirty = False
def load(self, f): self.__lyrics = "" self.__have_cover = False stopwatch = logging.stopwatch() self.__player = self.call_service(msgs.MEDIA_SVC_GET_OUTPUT) self.__player.connect_status_changed(self.__on_change_player_status) self.__player.connect_volume_changed(self.__on_change_player_volume) self.__player.connect_position_changed(self.__on_update_position) self.__player.connect_tag_discovered(self.__on_discovered_tags) self.__player.connect_error(self.__on_error) logging.profile(stopwatch, "[audioplayer] connected audio output") try: stopwatch = logging.stopwatch() self.__context_id = self.__player.load_audio(f) logging.profile(stopwatch, "[audioplayer] loaded media file: %s", f) except: logging.error("error loading media file: %s\n%s", f, logging.stacktrace()) stopwatch = logging.stopwatch() self.__current_file = f logging.profile(stopwatch, "[audioplayer] loaded track info") # load bookmarks self.__progress.set_bookmarks(media_bookmarks.get_bookmarks(f)) self.emit_message(msgs.MEDIA_EV_LOADED, self, f) t = threading.Thread(target = self.__load_track_info, args = [f]) t.setDaemon(True) gobject.idle_add(lambda *x:t.start() and False) if (self.__offscreen_buffer): self.render_buffered(self.__offscreen_buffer)