def search_lyrics(self, arg=None, menuw=None): box = PopupBox(text=_('Searching lyrics...')) box.show() result_code = -1 try: url = "http://api.leoslyrics.com/api_search.php?auth=%s&artist=%s&songtitle=%s"%( LEOLYRICS_AUTH, urllib.quote(self.item.info['artist'].encode('utf-8')), urllib.quote(self.item.info['title'].encode('utf-8'))) logger.log( 9, url) info = urllib2.urlopen(url).read() result_code = re.search('.+<response code="(\d)">.+',info).group(1) except: print "Error searching for artist/title." box.destroy() if result_code == '0': #ok #get the hid filter_info = re.search('.+hid="(.+)" exactMatch="true".+', info) if filter_info: # there is a exact match self.fetch_lyric(arg=filter_info.group(1), menuw=menuw) else: # open a submenu with choices self.show_choices(menuw=menuw, info= info) else: box = PopupBox(text=_('Lyrics not found, sorry...')) box.show() time.sleep(2) box.destroy()
def fetchheadlinesfromurl(self): headlines = [] popup = PopupBox(text=_('Fetching headlines...')) popup.show() try: # parse the document doc = util.feedparser.parse(self.url) if doc.status < 400: for entry in doc['entries']: try: title = Unicode(entry.title) link = Unicode(entry.link) if entry.has_key('content') and len(entry['content']) >= 1: description = Unicode(entry['content'][0].value) else: description = Unicode(entry['summary_detail'].value) headlines.append((title, link, description)) except AttributeError: pass else: logger.debug('Error %s, getting %r', doc.status, self.url) #write the file if len(headlines) > 0: pfile = os.path.join(self.cachedir, 'headlines-%i' % self.location_index) util.save_pickle(headlines, pfile) finally: popup.destroy() return headlines
def cover_create(self, arg=None, menuw=None): """ create cover file for the item """ import directory box = PopupBox(text= _('getting data...')) box.show() #filename = os.path.splitext(self.item.filename)[0] if self.item.type == 'audiocd': filename = '%s/disc/metadata/%s.jpg' % (config.OVERLAY_DIR, self.item.info['id']) elif self.item.type == 'dir': filename = os.path.join(self.item.dir, 'cover.jpg') else: filename = '%s/cover.jpg' % (os.path.dirname(self.item.filename)) fp = urllib2.urlopen(str(arg)) m = vfs.open(filename,'wb') m.write(fp.read()) m.close() fp.close() # try to crop the image to avoid ugly borders try: image = imlib2.open(filename) width, height = image.size image.crop((2, 2), (width-4, height-4)).save(filename) util.cache_image(filename) except Exception, why: logger.warning(why)
def cover_search_file(self, arg=None, menuw=None): """ search Amazon for this item """ logger.debug('cover_search_file(arg=%r, menuw=%r)', arg, menuw) box = PopupBox(text=_('searching Amazon...')) box.show() album = self.item.getattr('album') if not album: album = self.item.getattr('title') artist = self.item.getattr('artist') # Maybe the search string need encoding to config.LOCALE search_string = '%s %s' % (artist.encode(config.AMAZON_QUERY_ENCODING), album.encode(config.AMAZON_QUERY_ENCODING)) search_string = re.sub('[\(\[].*[\)\]]', '', search_string) logger.debug('search_string=%r', search_string) try: cover = amazon.ItemSearch(search_string, SearchIndex='Music', ResponseGroup='Images,ItemAttributes') except amazon.AWSException, why: box.destroy() title = '\n'.join([artist, album]) dict_tmp = { 'artist': artist, 'album': album } print '%(artist)s - %(album)s' % (dict_tmp) print '%r' % why box = PopupBox(text=artist+'\n'+album+'\n'+why[:40]) box.show() time.sleep(2) box.destroy() return
def create_podcast_submenu(self, arg=None, menuw=None, image=None): popup = PopupBox(text=_("Fetching podcasts...")) popup.show() url = arg[1] p = podcast() p.open_rss(url) p.rss_title() p.rss_count() image = os.path.join(config.APODCAST_DIR, arg[0], "cover.jpg") podcast_items = [] for pc_location in range(p.rss.count): p.rss_item(pc_location) podcast_item = ApodcastItem() podcast_item.name = p.title podcast_item.url = p.enclosure podcast_item.type = "audio" podcast_item.description = p.description podcast_item.image = image podcast_item.mplayer_options = "" podcast_item.filename = os.path.join(config.APODCAST_DIR, arg[0], os.path.split(p.enclosure)[1]) podcast_item.network_play = 1 podcast_item.length = 0 podcast_item.remain = 0 podcast_item.elapsed = 0 podcast_item.info = {"album": "", "artist": "", "trackno": "", "title": ""} podcast_items += [podcast_item] popup.destroy() if len(podcast_items) == 0: podcast_items += [menu.MenuItem(_("No Podcast locations found"), menwu.back_one_menu, 0)] podcast_sub_menu = menu.Menu(_("AUDIO PODCAST"), podcast_items) menuw.pushmenu(podcast_sub_menu) menuw.refresh()
def show_choices(self, menuw, info): items = [] soup = BeautifulStoneSoup(info,selfClosingTags=['feat']) results = soup.findAll('result') for result in results[:20]: # for performance reasons show the first possibilities only, # the more sensible hits are at the beginning of the list hid = result['hid'] title = result.titleTag.string.replace('&', '&') artist = result.artistTag.nameTag.string.replace('&','&') items.append(menu.MenuItem('%s - %s' % (title, artist), action=self.fetch_lyric, arg=hid)) if len(items) > 0: msgtext = _('No exact match. ') msgtext+= _('Here are some sugestions.') box = PopupBox(text = msgtext) box.show() time.sleep(2) box.destroy() choices_menu = menu.Menu(_('Choices'), items) menuw.pushmenu(choices_menu) else: box = PopupBox(text= _('Lyrics not found, sorry...')) box.show() time.sleep(3) box.destroy()
def cover_create(self, arg=None, menuw=None): """ create cover file for the item """ import directory box = PopupBox(text=_('getting data...')) box.show() #filename = os.path.splitext(self.item.filename)[0] if self.item.type == 'audiocd': filename = '%s/disc/metadata/%s.jpg' % (config.OVERLAY_DIR, self.item.info['id']) elif self.item.type == 'dir': filename = os.path.join(self.item.dir, 'cover.jpg') else: filename = '%s/cover.jpg' % (os.path.dirname(self.item.filename)) fp = urllib2.urlopen(str(arg)) m = vfs.open(filename, 'wb') m.write(fp.read()) m.close() fp.close() # try to crop the image to avoid ugly borders try: image = imlib2.open(filename) width, height = image.size image.crop((2, 2), (width - 4, height - 4)).save(filename) util.cache_image(filename) except Exception, why: logger.warning(why)
def create_podcast_menu(self, arg=None, menuw=None): popup = PopupBox(text=_("Fetching podcast...")) popup.show() podcast_menu_items = [] for location in config.APODCAST_LOCATIONS: url = location[1] image_path = os.path.join(config.APODCAST_DIR, location[0], "cover.jpg") if self.check_logo(image_path): p = podcast() p.open_rss(url) p.rss_title() name = p.rss_title image_url = p.rss_image self.download(image_url, image_path) if len(config.APODCAST_DIR) == 0: podcast_items += [menu.MenuItem(_("Set APODCAST_DIR in local_conf.py"), menwu.back_one_menu, 0)] podcast_menu_items += [ menu.MenuItem(_(location[0]), action=self.create_podcast_submenu, arg=location, image=image_path) ] popup.destroy() podcast_main_menu = menu.Menu(_("AUDIO PODCAST"), podcast_menu_items) menuw.pushmenu(podcast_main_menu) menuw.refresh()
def getMameItemInfoList(mame_files, mame_cmd): items = [] rm_files = [] print "Call MAME command : %s" % mame_cmd # Only build the cache if it doesn't exis. if not os.path.isfile(config.GAMES_MAME_CACHE): waitmsg = PopupBox(text=_('Generating MAME cache, please wait.')) waitmsg.show() mame_ok = updateMameRomList(mame_cmd) waitmsg.destroy() if not mame_ok: return (mame_files, []) mameRomList = getMameRomList() roms = mameRomList.getMameRoms() for romfile in mame_files: key = os.path.splitext(os.path.basename(romfile))[0] if roms.has_key(key): rom = roms[key] info = { 'manufacturer': rom.manufacturer, 'name': rom.name, 'description': rom.description, 'year': rom.year, 'cloneof': rom.cloneof, 'romof': rom.romof } items += [(rom.description, romfile, None, info)] rm_files.append(romfile) return (rm_files, items)
def download_play(self, arg=None, menuw=None): pop = PopupBox("Descargando programa") pop.show() video = VideoItem(_fetch_image(arg["flv"]), self) pop.destroy() video.image = _fetch_image(arg["image"]) video.menuw = menuw video.play()
def get_feed_menu(self, feed): service = gdata.service.GDataService(server='gdata.youtube.com') gfeed = service.GetFeed(feed) box = PopupBox(text=_('Loading video list')) box.show() menu = YoutubeVideoMenu(service, gfeed, self) box.destroy() return menu
def __init__(self, file, parent='osd', text=' ', left=None, top=None, width=500, height=350, bg_color=None, fg_color=None, icon=None, border=None, bd_color=None, bd_width=None): handler = None self.file = file self.filetext = open(self.file, 'rb').read() PopupBox.__init__(self, text, handler, top, left, width, height, icon, None, None, parent) myfont = self.osd.getfont(config.OSD_DEFAULT_FONTNAME, config.OSD_DEFAULT_FONTSIZE) surf_w = myfont.stringsize('AAAAAAAAAA' * 8) data = self.osd.drawstringframed(self.filetext, 0, 0, surf_w, 1000000, myfont, align_h='left', align_v='top', fgcolor=self.osd.COL_BLACK, mode='hard', layer='')[1] (ret_x0, ret_y0, ret_x1, ret_y1) = data surf_h = ret_y1 - ret_y0 if height > surf_h: surf_h = height surf = pygame.Surface((surf_w, surf_h), 0, 32) bg_c = self.bg_color.get_color_sdl() surf.fill(bg_c) self.osd.drawstringframed(self.filetext, 0, 0, surf_w, surf_h, myfont, align_h='left', align_v='top', fgcolor=self.osd.COL_BLACK, mode='hard', layer=surf) self.pb = RegionScroller(surf, 50, 50, width=width, height=height) self.add_child(self.pb)
def make_menu(self, arg=None, menuw=None): try: menuw.pushmenu(menu.Menu('Albums', [ AlbumItem(x, self, self.service) for x in self.service.getAlbums()])) except MusicIPException, x: pop = PopupBox(text=_(str(x))) pop.show() time.sleep(2) pop.destroy() return
def make_menu(self, arg=None, menuw=None): try: menuw.pushmenu(menu.Menu(self.name, [ Playlist('All', getAudioItemsLazily(self, self.service.getSongs, filter=self.name), self)] + [ AlbumItem(x, self, self.service) for x in self.service.getAlbums(filter=self.name, extended=True)])) except MusicIPException, x: pop = PopupBox(text=_(str(x))) pop.show() time.sleep(2) pop.destroy() return
def wikisubtitles_download(self, arg=None, menuw=None): "Download subtitle .srt" import directory box = PopupBox(text=_('Downloading subtitle, please wait..')) box.show() urllib.urlretrieve(arg,self.srtdownload) box.destroy() box = PopupBox(text=_('Subtitle downloaded')) box.show() time.sleep(2) box.destroy() self.wikisubtitles_menu_back(menuw)
def EndCall(self, arg, menuw): popup = PopupBox(text=_('Ending conversation..')) popup.show() try: #arg.Finish() self.parent.skype.GetCallObject().Finish() while not (self.parent.skype.IsTerminated()): pass finally: popup.destroy() menuw.back_one_menu(arg='reload') return
def stop_burning(self, arg, menuw=None): logger.debug('stop_burning(arg=%r, menuw=%r)', arg, menuw) pop = PopupBox(text=_('Interrupting burning process...')) pop.show() self.thread_burn.stop() pop.destroy() if menuw: menuw.back_one_menu(arg='reload') menuw.refresh AlertBox(text=_('Backup interrupted')).show()
def __init__(self, lines, file=None, parent='osd', text=' ', left=None, top=None, width=500, height=350, bg_color=None, fg_color=None, icon=None, border=None, bd_color=None, bd_width=None): """ Initialise a LogScroll instance @param left: x coordinate. Integer @param top: y coordinate. Integer @param width: Integer @param height: Integer @param text: String to print. @param bg_color: Background color (Color) @param fg_color: Foreground color (Color) @param icon: icon @param border: Border @param bd_color: Border color (Color) @param bd_width: Border width Integer """ handler = None self.lines = file is not None and open(file, 'rb').read() or lines PopupBox.__init__(self, text, handler, top, left, width, height, icon, None, None, parent) myfont = self.osd.getfont(config.OSD_DEFAULT_FONTNAME, config.OSD_DEFAULT_FONTSIZE) import pprint pprint.pprint(myfont.__dict__) surf_w = myfont.stringsize('AAAAAAAAAA'*8) data = self.osd.drawstringframed('\n'.join(self.lines), 0, 0, surf_w, 1000000, myfont, align_h='left', align_v='top', fgcolor=self.osd.COL_BLACK, mode='hard', layer='')[1] (ret_x0,ret_y0, ret_x1, ret_y1) = data surf_h = ret_y1 - ret_y0 if height>surf_h: surf_h=height surf = pygame.Surface((surf_w, surf_h), 0, 32) bg_c = self.bg_color.get_color_sdl() surf.fill(bg_c) y = 0 for line in self.lines: colour = self.osd.COL_BLACK if line.startswith('<so> '): colour = self.osd.COL_WHITE elif line.startswith('<se> '): colour = self.osd.COL_ORANGE line = line[4:] self.osd.drawstringframed(line, 0, y, surf_w, surf_h, myfont, align_h='left', align_v='top', fgcolor=colour, mode='hard', layer=surf) #y += myfont.ptsize + 1 y += myfont.height self.pb = RegionScroller(surf, 50, 50, width=width, height=height) self.add_child(self.pb)
def file_play_all_by_artist(self, arg=None, menuw=None): kwargs = {} try: if self.item.type == 'audio': songInfo = self.service.getSongInfo(file=self.item.filename) filenames = self.service.getSongs(artist=songInfo['artist']) else: print 'Bad file type', self.item.type, self.item.filename, 'for MusicIP mix' except MusicIPException, x: pop = PopupBox(text=_(str(x))) pop.show() time.sleep(2) pop.destroy() return
def save_changes(self, arg=None, menuw=None): """ Save favorite """ _debug_('save_changes(arg=%r, menuw=%r)' % (arg, menuw), 2) # this can take some time, as it means although to update the schedule msgtext = _('Saving the changes to this favorite.')+'\n'+_('This may take some time.') pop = PopupBox(text=msgtext) pop.show() if self.fav_action == 'edit': # first we remove the old favorite (result, msg) = self.recordclient.removeFavoriteNow(self.origname) elif self.fav_action =='add': result = True if result: # create a new edited favorite (result, msg) = self.recordclient.addEditedFavoriteNow(self.fav.name, self.fav.title, self.fav.channel, self.fav.dow, self.fav.mod, self.fav.priority, self.fav.allowDuplicates, self.fav.onlyNew) if result: if menuw: menuw.delete_submenu() if self.fav_action == 'add': menuw.refresh(reload=1) self.fav_action = 'edit' pop.destroy() else: pop.destroy() # it is important to show the user this error, # because that means the favorite is removed, # and must be created again msgtext=_('Save failed, favorite was lost')+(':\n%s' % msg) AlertBox(text=msgtext).show()
def updateData(self): """update the cache data from the 1click service @note: the elocation is not updated as it is static """ logger.log( 9, 'updateData()') if GUI: popup = PopupBox(text=_('Fetching Weather for %s...') % self.popupParam) popup.show() if not os.path.isfile(self.cacheElocation): try: elocationData = wget(self.url_eloc) self.elocationData = elocationData except Exception, why: logger.warning('Failed to get extended location data for %s: %s', self.location, why)
def updateData(self): """update the cache data from the 1click service @note: the elocation is not updated as it is static """ _debug_('updateData()', 2) if GUI: popup = PopupBox(text=_('Fetching Weather for %s...') % self.popupParam) popup.show() if not os.path.isfile(self.cacheElocation): try: elocationData = wget(self.url_eloc) self.elocationData = elocationData except Exception, error: print 'Failed to get extended location data for %s: %s' % (self.location, error)
def make_menu(self, arg=None, menuw=None): entries = [] pop = PopupBox("Creando menu de programas") pop.show() for name in self.programacion.sort_by_title(): programa = self.programacion.programas[name] # makes a menu for each item entries.append(MenuPrograma(programa, self)) # plays directly # entries.append(ProgramaVideoItem(programa['nombre'],programa,self)) pop.destroy() menuw.pushmenu(menu.Menu(self.programa, entries))
def file_mix(self, arg=None, menuw=None): kwargs = {} try: if self.item.type == 'playlist': filenames = self.service.getMix(playlist=self.item.filename) elif self.item.type == 'audio': filenames = self.service.getMix(song=self.item.filename) else: print 'Bad file type', self.item.type, self.item.filename, 'for MusicIP mix' except MusicIPException, x: pop = PopupBox(text=_(str(x))) pop.show() time.sleep(2) pop.destroy() return
def generate_common_stream_list( object, idfilm ): items = [] box = PopupBox(text=_('Recuperation des types de bande annonces disponibles')) box.show() streamlist = get_movie_sheet( idfilm ) if streamlist: for title, streamurl in streamlist: items.append(TrailerVideoItem(title, streamurl, object)) else: items.append( menu.MenuItem('Pas de bande annonce dispo', None, None) ) box.destroy() return items
def updateMap(self): """ Update the weather map """ _debug_('updateMap()', 2) # obtain radar map if self.mapuri: try: if GUI: popup = PopupBox(text=_('Fetching Radar Map for %s...') % self.popupParam) popup.show() try: self.weatherMapData = wget(self.mapuri) self.saveMapToCache() except Exception, error: print 'Cannot download the map for "%s" from %s: %s' % (self.location, self.mapuri, error) return finally:
def updateMap(self): """ Update the weather map """ logger.log( 9, 'updateMap()') # obtain radar map if self.mapuri: try: if GUI: popup = PopupBox(text=_('Fetching Radar Map for %s...') % self.popupParam) popup.show() try: self.weatherMapData = wget(self.mapuri) self.saveMapToCache() except Exception, why: logger.warning('Cannot download the map for "%s" from %s: %s', self.location, self.mapuri, why) return finally:
def updateData(self): """update the cache data from the 1click service @note: the elocation is not updated as it is static """ logger.log(9, 'updateData()') if GUI: popup = PopupBox(text=_('Fetching Weather for %s...') % self.popupParam) popup.show() if not os.path.isfile(self.cacheElocation): try: elocationData = wget(self.url_eloc) self.elocationData = elocationData except Exception, why: logger.warning( 'Failed to get extended location data for %s: %s', self.location, why)
def __init__(self, item, menuw=None): PlayerGUI.__init__(self, item, menuw) self.visible = menuw and True or False self.menuw = menuw self.item = item self.player = None self.running = False self.item.title = None self.item.artist = None self.box = None self.downl_time = 30 if not os.path.exists(self.item.filename): background = BGDownload(self.item.url, self.item.filename) background.start() popup = PopupBox(text=_("Buffering podcast...")) popup.show() time.sleep(10) # 10s. buffering time popup.destroy()
def flashpopup(self, arg=None, menuw=None): """ start popup and execute command """ if self.stoposd: if self.use_wm: os.system(self.spawnwm) else: popup_string=_("Running Command...") pop = PopupBox(text=popup_string) pop.show() if self.stoposd: self.rc.suspend() workapp = CommandChild(self.cmd, 'command', 1, self.stoposd) while workapp.isAlive(): # make sure all callbacks in rc are running if not self.stoposd: self.rc.poll() # wait some time time.sleep(0.5) if workapp.outfd: workapp.outfd.close() if self.stoposd: if self.use_wm: os.system(self.killwm) time.sleep(0.5) else: pop.destroy() workapp.stop() if self.stoposd: self.rc.resume() message = '' if workapp.status: message = _('Command Failed') else: message = _('Command Completed') if not self.stoposd and self.stdout: CommandOptions(workapp.logbuffer, workapp.logfilename, text=message).show()
def updateMap(self): """ Update the weather map """ logger.log(9, 'updateMap()') # obtain radar map if self.mapuri: try: if GUI: popup = PopupBox(text=_('Fetching Radar Map for %s...') % self.popupParam) popup.show() try: self.weatherMapData = wget(self.mapuri) self.saveMapToCache() except Exception, why: logger.warning( 'Cannot download the map for "%s" from %s: %s', self.location, self.mapuri, why) return finally:
def __load(self): pfile = os.path.join(cachedir, "data") if os.path.isfile(pfile) == 0: popup = PopupBox(text=_("Downloading stream links")) popup.show() self.getNations() self.getCategories() popup.destroy() util.fileops.save_pickle(self.mainArray, pfile) else: if abs(time.time() - os.path.getmtime(pfile)) > MAX_CACHE_AGE: popup = PopupBox(text=_("Downloading stream links")) popup.show() self.getNations() self.getCategories() popup.destroy() util.fileops.save_pickle(self.mainArray, pfile) self.mainArray = util.fileops.read_pickle(pfile) self.nation_tv = self.mainArray["nation_tv"] self.nation_list = self.mainArray["nation_list"] self.categories_tv = self.mainArray["categories_tv"]
def video_list(parent, title, user): """Get the video list for a specific user""" _debug_('video_list(parent=%r, title=%r, user=%r)' % (parent, title, user), 2) items = [] feed = 'http://gdata.youtube.com/feeds/users/' + user + '/uploads?orderby=updated' service = gdata.service.GDataService(server='gdata.youtube.com') box = PopupBox(text=_('Loading video list')) box.show() for video in service.GetFeed(feed).entry: date = video.published.text.split('T') if video.link[1].href.find('watch?v=') >= 0: id = video.link[1].href.split('watch?v='); elif video.link[0].href.find('watch?v=') >= 0: id = video.link[0].href.split('watch?v='); else: continue mi = menu.MenuItem(date[0] + ' ' + video.title.text, parent.downloadvideo, id[1]) mi.arg = (video.title.text, id[1]) text = util.htmlenties2txt(video.content) mi.description = re.search('<span>([^\<]*)<',text).group(1) tempimage = re.search('src="([^\"]*)"',text).group(1) file = config.YOUTUBE_DIR + '/' + id[1].replace('-','_') + '.jpg' if not os.path.exists(file): aimage = urllib.urlretrieve(tempimage,file) mi.image = file items.append(mi) box.destroy() return items
def fetchheadlinesfromurl(self): headlines = [] popup = PopupBox(text=_('Fetching headlines...')) popup.show() try: # parse the document doc = util.feedparser.parse(self.url) if doc.status < 400: for entry in doc['entries']: try: title = Unicode(entry.title) link = Unicode(entry.link) if entry.has_key('content') and len( entry['content']) >= 1: description = Unicode(entry['content'][0].value) else: description = Unicode( entry['summary_detail'].value) headlines.append((title, link, description)) except AttributeError: pass else: logger.debug('Error %s, getting %r', doc.status, self.url) #write the file if len(headlines) > 0: pfile = os.path.join(self.cachedir, 'headlines-%i' % self.location_index) util.save_pickle(headlines, pfile) finally: popup.destroy() return headlines
def search_for_programs(self, menuw, text): pop = PopupBox(text=_('Searching, please wait...')) pop.show() (result, matches) = self.findMatches(text) pop.destroy() items = [] if result: _debug_('search found %s matches' % len(matches)) f = lambda a, b: cmp(a.start, b.start) matches.sort(f) for prog in matches: items.append(ProgramItem(self, prog, context='search')) else: if matches == 'no matches': msgtext = _('No matches found for %s') % text AlertBox(text=msgtext).show() return AlertBox(text=_('Cannot find program: %s') % matches).show() return search_menu = Menu(_('Search Results'), items, item_types='tv program menu') menuw.pushmenu(search_menu) menuw.refresh()
def generate_common_menu(parent, title_box, page_prefix): items = [] #Start grabbing from DVD/Movies of last week current = datetime.date.today() - datetime.timedelta(days=7) for week in [0, 1, 2, 3, 4, 5, 6]: # Compute a new date for the week newdate = current + datetime.timedelta(days=(week * 7)) # Show some progress box = PopupBox(text=_(title_box + '\nSemaine du ' + newdate.strftime("%d/%m/%Y"))) box.show() filehtml = page_prefix + newdate.strftime("%Y") + \ newdate.strftime("%m") + newdate.strftime("%d") + ".html" #print "URL to fetch : %s" % filehtml trailers = get_movie_list_week(CAC_URL + filehtml) for title, idfilm in trailers: items.append( menu.MenuItem( '%s' % (title + " (" + newdate.strftime("%d/%m/%Y") + ")"), parent.play_video, (title, idfilm))) box.destroy() return items
def selected_quality(self, arg, menuw): api, show, season, episode, host, quality = arg self.video_item = None self.menuw = menuw self.file_object = episode self.selected_host = host self.selected_quality = quality config.VIDEO_SHOW_DATA_DIR = '/media/disk/video' self.file_path = os.path.join(config.VIDEO_SHOW_DATA_DIR, self.get_filename(episode)) box = PopupBox(text='Starting download... will start playing shortly') box.show() time.sleep(2) box.destroy() if os.path.exists(self.file_path): # TODO: check file completition? self.play() return url_open = UrlOpen() url = self.file_object.get_subtitle_url(quality=self.selected_quality) filename = self.file_path.replace(".mp4", ".srt") url_open(url, filename=filename) print episode.file_hosts[host][quality] self.gui_manager.background_task(self.pre_download, self.play) self.downloader = Downloaders.get(host, self.gui_manager, episode.file_hosts[host][quality]) self.downloader.process_url(None, self.file_path)
def flashpopup(self, arg=None, menuw=None): """ start popup and execute command """ if self.stoposd: if self.use_wm: os.system(self.spawnwm) else: popup_string = _("Running Command...") pop = PopupBox(text=popup_string) pop.show() workapp = CommandChild(self.cmd, 'command', 1, self.stoposd) while workapp.isAlive(): # make sure all callbacks in rc are running rc.poll() # wait some time time.sleep(0.5) if self.stoposd: if self.use_wm: os.system(self.killwm) time.sleep(0.5) else: pop.destroy() workapp.stop() message = '' if workapp.status: message = _('Command Failed') else: message = _('Command Completed') if not self.stoposd and self.stdout: CommandOptions(text=message).show()
def create_podcast_menu(self, arg=None, menuw=None): popup = PopupBox(text=_('Fetching podcasts...')) popup.show() podcast_menu_items = [] for location in config.APODCAST_LOCATIONS: url = location[1] image_path = config.APODCAST_DIR + '/' + location[ 0] + '/' + 'cover.jpg' if self.check_logo(image_path): p = podcast() p.open_rss(url) p.rss_title() name = p.rss_title image_url = p.rss_image self.download(image_url, image_path) if (len(config.APODCAST_DIR) == 0): podcast_items += [ menu.MenuItem(_('Set APODCAST_DIR in local_conf.py'), menwu.goto_prev_page, 0) ] podcast_menu_items += [ menu.MenuItem(_(location[0]), action=self.create_podcast_submenu, arg=location, image=image_path) ] popup.destroy() podcast_main_menu = menu.Menu(_('AUDIO PODCAST'), podcast_menu_items) rc.app(None) menuw.pushmenu(podcast_main_menu) menuw.refresh()
def image_list(parent, title, user): """Get the image list for a specific user""" logger.log( 9, 'image_list(parent=%r, title=%r, user=%r)', parent, title, user) items = [] web = 'http://www.flickr.com/services/rest/?method=flickr.people.getPublicPhotos&user_id=' + user + \ '&format=json&api_key=' + config.FLICKR_KEY + '&per_page=' + str(config.FLICKR_LIMIT) + \ '&page=1&extras=original_format' url=urllib.urlopen(web) flickr=url.read() flickr=flickr.replace("jsonFlickrApi(",""); data = json.read(flickr[:-1]) for foto in data['photos']['photo']: #items.append(ImageItem(y[1],parent,foto["title"])) mi = menu.MenuItem(foto["title"], parent.showimage, 0) mi.arg = (foto["title"],"http://farm3.static.flickr.com/" + foto["server"] + "/" + \ foto["id"] + "_" + foto["originalsecret"] + "_o.jpg",foto["id"]) imagen = 'http://farm3.static.flickr.com/' + foto['server'] + '/' + foto['id'] + '_' + foto['secret'] + '_m.jpg' file = config.FLICKR_DIR + '/' + foto['id'].replace('-','_') + '_t.jpg' if not os.path.exists(file): box = PopupBox(_('Downloading thumbnail for picture "') + foto['title'] + '"', width=800) box.show() urllib.urlretrieve(imagen,file) box.destroy() mi.image = file items.append(mi) return items
def filmaffinity_create_fxd(self, arg=None, menuw=None): """ create fxd file for the item """ box = PopupBox(text=_('Fetching movie information')) box.show() #if this exists we got a cdrom/dvdrom if self.item.media and self.item.media.devicename: devicename = self.item.media.devicename else: devicename = None self.getFilmAffinityPage(arg[0]) if self.disc_set: self.setDiscset(devicename, None) else: if self.item.subitems: for i in range(len(self.item.subitems)): video = makeVideo('file', 'f%s' % i, os.path.basename(self.item.subitems[i].filename), device=devicename) self.setVideo(video) else: video = makeVideo('file', 'f1', os.path.basename(self.item.filename), device=devicename) self.setVideo(video) self.setFxdFile(os.path.splitext(self.item.filename)[0]) self.writeFxd() self.filmaffinity_menu_back(menuw) box.destroy()
def generate_common_menu(parent, title_box, page_prefix): items = [] #Start grabbing from DVD/Movies of last week current = datetime.date.today() - datetime.timedelta(days=7) for week in [0, 1, 2, 3, 4, 5, 6]: # Compute a new date for the week newdate = current + datetime.timedelta(days=(week*7)) # Show some progress box = PopupBox(text=_(title_box+'\nSemaine du '+newdate.strftime("%d/%m/%Y"))) box.show() filehtml = page_prefix + newdate.strftime("%Y") + \ newdate.strftime("%m") + newdate.strftime("%d") + ".html" #print "URL to fetch : %s" % filehtml trailers = get_movie_list_week(CAC_URL + filehtml) for title, idfilm in trailers: items.append(menu.MenuItem('%s' % (title + " (" + newdate.strftime("%d/%m/%Y") + ")"), parent.play_video, (title, idfilm) ) ) box.destroy() return items
def download_play(self, arg=None, menuw=None): pop = PopupBox("Descargando programa") pop.show() video = VideoItem(_fetch_image(arg['flv']), self) pop.destroy() video.image = _fetch_image(arg['image']) video.menuw = menuw video.play()
def __init__(self, loglines, logfilename, parent='osd', text=None, handler=None, left=None, top=None, width=600, height=300, bg_color=None, fg_color=None, icon=None, border=None, bd_color=None, bd_width=None, vertical_expansion=1): if not text: text = _('Command finished') PopupBox.__init__(self, text, handler, top, left, width, height, icon, vertical_expansion, None, parent) items_height = 40 self.loglines = loglines self.logfilename = logfilename self.num_shown_items = 2 self.results = ListBox(width=(self.width-2*self.h_margin), height=self.num_shown_items*items_height, show_v_scrollbar=0) self.results.y_scroll_interval = self.results.items_height = items_height self.add_child(self.results) self.results.add_item(text=_('OK'), value='ok') if loglines or logfilename: self.results.add_item(text=_('Show output'), value='out') self.results.toggle_selected_index(0)
def __init__(self, parent='osd', text=None, handler=None, left=None, top=None, width=600, height=300, bg_color=None, fg_color=None, icon=None, border=None, bd_color=None, bd_width=None, vertical_expansion=1): if not text: text = _('Command finished') #PopupBox.__init__(self, text, handler=handler, x=top, y=left, width=width, height=height) PopupBox.__init__(self, text, handler, top, left, width, height, icon, vertical_expansion, None, parent) items_height = 40 self.num_shown_items = 3 self.results = ListBox(width=(self.width - 2 * self.h_margin), height=self.num_shown_items * items_height, show_v_scrollbar=0) self.results.y_scroll_interval = self.results.items_height = items_height self.add_child(self.results) self.results.add_item(text=_('OK'), value='ok') if islog('err'): self.results.add_item(text=_('Show Stderr'), value='err') if islog('out'): self.results.add_item(text=_('Show Stdout'), value='out') self.results.toggle_selected_index(0)
def imdb_search(self, arg=None, menuw=None): """ search imdb for this item """ fxd = FxdImdb() box = PopupBox(text=_('searching IMDB...')) box.show() items = [] try: duplicates = [] if self.disc_set: self.searchstring = self.item.media.label else: self.searchstring = self.item.name for id, name, year, type in fxd.guessImdb(self.searchstring, self.disc_set): try: for i in self.item.parent.play_items: if i.name == name: if not i in duplicates: duplicates.append(i) except: pass try: #items.append(menu.MenuItem('%s (%s, %s)' % (htmlenties2txt(name), year, type), items.append( menu.MenuItem('%s (%s, %s)' % (name, year, type), self.imdb_create_fxd, (id, year))) except UnicodeError, e: print e # if filename had a season/episode letsĀ“ grab it self.season = fxd.season self.episode = fxd.episode
def create_job(self, menuw=None, arg=None): _debug_('create_job(self, arg=%r, menuw=%r)' % (arg, menuw), 1) profile = arg #we are going to create a job and send it to the encoding server, this can take some time while analyzing box = PopupBox(text=_('Please wait, analyzing video...')) box.show() (status, resp) = initEncodeJob(self.source, self.output, self.title) _debug_('initEncodeJob:status:%s resp:%s' % (status, resp)) box.destroy() if not status: self.error(resp) return idnr = resp (status, resp) = setContainer(idnr, profile['container']) _debug_('setContainer:status:%s resp:%s' % (status, resp)) if not status: self.error(resp) return multipass = profile['numpasses'] > 1 (status, resp) = setVideoCodec(idnr, profile['videocodec'], 0, multipass, profile['videobitrate']) _debug_('setVideoCodec:status:%s resp:%s' % (status, resp)) if not status: self.error(resp) return (status, resp) = setAudioCodec(idnr, profile['audiocodec'], profile['audiobitrate']) _debug_('setAudioCodec:status:%s resp:%s' % (status, resp)) if not status: self.error(resp) return #(status, resp) = setVideoFilters(idnr, vfilters) #_debug_('setVideoFilters:status:%s resp:%s' % (status, resp)) #And finally, qeue and start the job (status, resp) = queueIt(idnr, True) _debug_('queueIt:status:%s resp:%s' % (status, resp)) if not status: self.error(resp) return self.menuw = menuw AlertBox(width=400, height=200, text=_('Encoding started'), handler=self.mopup).show() _debug_('boe')
def fetchheadlinesfromurl(self): """ this fetches the headlines (title, link and description) from the url. Here the parsing of the xml is done """ headlines = [] # create Reader object reader = Sax2.Reader() popup = PopupBox(text=_('Fetching headlines...')) popup.show() # parse the document try: myfile = urllib.urlopen(self.url) doc = reader.fromStream(myfile) items = doc.getElementsByTagName('item') for item in items: title = '' link = '' description = '' if item.hasChildNodes(): for c in item.childNodes: if c.localName == 'title': title = c.firstChild.data if c.localName == 'description': description = c.firstChild.data ################################# # Ajout pour identifier le lien de la video if self.mode == 'youtube': if c.localName == 'link': link = 'youtube:' + c.firstChild.data else: if c.localName == 'enclosure': attrs = c.attributes for attrName in attrs.keys(): attrNode = attrs.get(attrName) attrValue = attrNode.nodeValue if 'url' in attrName: link = attrValue if title: headlines.append((title, link, description)) except: #unreachable or url error _debug_('could not open %s' % self.url, DERROR) pass #write the file if len(headlines) > 0: pfile = os.path.join(self.cachedir, 'itv-%i' % self.location_index) util.save_pickle(headlines, pfile) popup.destroy() return headlines
def __init__(self, start_time, player, menuw): _debug_( 'TVGuide.__init__(start_time=%r, player=%r, menuw=%r)' % (start_time, player, menuw), 2) Item.__init__(self) # get skin definitions of the TVGuide self.n_items, self.hours_per_page = skin.items_per_page(('tv', self)) # end of visible guide stop_time = start_time + self.hours_per_page * 60 * 60 # constructing the guide takes some time msgtext = _('Preparing the program guide') guide = tv.epg_xmltv.get_guide(PopupBox(text=msgtext)) # getting channels channels = guide.get_programs(start_time + 1, stop_time - 1) if not channels: AlertBox(text=_('TV Guide is corrupt!')).show() return # select the first available program selected = None for chan in channels: if chan.programs: self.selected = chan.programs[0] break self.recordclient = RecordClient() self.col_time = 30 # each col represents 30 minutes self.n_cols = (stop_time - start_time) / 60 / self.col_time self.player = player self.type = 'tv' self.menuw = menuw self.visible = True self.select_time = start_time self.last_update = 0 self.lastinput_value = None self.lastinput_time = None self.update_schedules(force=True) self.event_context = 'tvmenu' self.rebuild(start_time, stop_time, guide.chan_list[0].id, selected) menuw.pushmenu(self)
def showimage(self, arg=None, menuw=None): """Save in file and watch it""" logger.log( 9, 'showimage(arg=%r, menuw=%r)', arg, menuw) file = config.FLICKR_DIR + "/" + arg[2].replace("-","_") + ".jpg" if not os.path.exists(file): box = PopupBox(_("Downloading picture \"") + arg[0] + '"', width=600) box.show() urllib.urlretrieve(arg[1],file) box.destroy() imgitem = ImageItem(file, self, arg[0]) imgitem.menuw=menuw imgitem.view(menuw=menuw)
def make_menu(self, arg=None, menuw=None): try: menuw.pushmenu( menu.Menu('Albums', [ AlbumItem(x, self, self.service) for x in self.service.getAlbums() ])) except MusicIPException, x: pop = PopupBox(text=_(str(x))) pop.show() time.sleep(2) pop.destroy() return
def stop_burning(self, arg, menuw=None): _debug_('stop_burning(self, arg, menuw=None)') pop = PopupBox(text=_('Interrupting burning process...')) pop.show() self.thread_burn.stop() pop.destroy() if menuw: menuw.back_one_menu(arg='reload') menuw.refresh AlertBox(text=_('Backup interrupted')).show()