def onInit(self): try: self.fav_list = self.getControl(6) self.getControl(3).setVisible(False) except: print_exc() self.fav_list = self.getControl(3) if self.getmore == True: self.getControl(5).setLabel(xbmc.getLocalizedString(21452)) else: self.getControl(5).setVisible(False) self.getControl(1).setLabel(self.windowtitle) # Set Cancel label (Kodi 17+) if int( __xbmcversion__ ) >= 17: try: self.getControl(7).setLabel(xbmc.getLocalizedString(222)) except: log( "Unable to set label for control 7" ) for item in self.listing : listitem = xbmcgui.ListItem(label=item.getLabel(), label2=item.getLabel2(), iconImage=item.getProperty( "icon" ), thumbnailImage=item.getProperty( "thumbnail" )) listitem.setProperty( "Addon.Summary", item.getLabel2() ) self.fav_list.addItem( listitem ) self.setFocus(self.fav_list)
def _download_item( self ): try: if ( xbmcgui.Dialog().yesno( self.title, xbmc.getLocalizedString( 30000 ), "", "", xbmc.getLocalizedString( 30020 ), xbmc.getLocalizedString( 30021 ) ) ): self.dialog.create( self.title, xbmc.getLocalizedString( 30002 ), xbmc.getLocalizedString( 30003 ) ) asset_files = [] folders = [ self.args.download_url ] while folders: try: htmlsource = self._get_html_source( self.REPO_URL + folders[ 0 ] ) if ( not htmlsource ): raise items = self._parse_html_source( htmlsource ) if ( not items or items[ "status" ] == "fail" ): raise files, dirs = self._parse_items( items ) for file in files: asset_files.append( "%s/%s" % ( items[ "url" ], file, ) ) for folder in dirs: folders.append( folders[ 0 ] + folder ) folders = folders[ 1 : ] except: folders = [] self._get_files( asset_files ) except: # oops print error message print "ERROR: %s::%s (%d) - %s" % ( self.__class__.__name__, sys.exc_info()[ 2 ].tb_frame.f_code.co_name, sys.exc_info()[ 2 ].tb_lineno, sys.exc_info()[ 1 ], ) self.dialog.close() xbmcgui.Dialog().ok( self.title, xbmc.getLocalizedString( 30030 ) )
def _get_strings( self ): self.localized_string = {} self.localized_string[ 30900 ] = xbmc.getLocalizedString( 30900 ) self.localized_string[ 30901 ] = xbmc.getLocalizedString( 30901 ) self.localized_string[ 30902 ] = xbmc.getLocalizedString( 30902 ) self.localized_string[ 30903 ] = xbmc.getLocalizedString( 30903 ) self.localized_string[ 30905 ] = xbmc.getLocalizedString( 30905 )
def main(self, action_param=None): '''show the NextAired dialog''' weekday = self.date.weekday() self.win.setProperty("NextAired.TodayText", xbmc.getLocalizedString(33006)) self.win.setProperty("NextAired.TomorrowText", xbmc.getLocalizedString(33007)) self.win.setProperty("NextAired.YesterdayText", self.addon.getLocalizedString(32018)) self.win.setProperty("NextAired.TodayDate", self.str_date(self.date, 'DropYear')) self.win.setProperty("NextAired.TomorrowDate", self.str_date(self.tomorrow, 'DropThisYear')) self.win.setProperty("NextAired.YesterdayDate", self.str_date(self.yesterday, 'DropThisYear')) for count in range(0, 7): wdate = self.date if count != weekday: wdate += timedelta(days=(count - weekday + 7) % 7) self.win.setProperty("NextAired.%d.Date" % (count + 1), self.str_date(wdate, 'DropThisYear')) from next_aired_dialog import NextAiredDialog today_style = self.addon.getSetting("TodayStyle") == 'true' scan_days = int(self.addon.getSetting("ScanDays2" if today_style else "ScanDays")) want_yesterday = self.addon.getSetting("WantYesterday") == 'true' eps_list = self.get_nextaired_listing(include_last_episode=want_yesterday) xml = "script-NextAired-TVGuide%s.xml" % (2 if today_style else "") xml_path = self.addon.getAddonInfo('path').decode('utf-8') dialog = NextAiredDialog( xml, xml_path, "Default", listing=eps_list, nice_date=self.nice_date, scan_days=scan_days, today_style=today_style, want_yesterday=want_yesterday) dialog.doModal() del dialog
def onAction(self, act): action = act.getId() if action in ACTION_PREVIOUS_MENU: if self.showingList == False: self.cancelChan() self.hideChanDetails() else: if self.madeChanges == 1: dlg = xbmcgui.Dialog() if dlg.yesno(xbmc.getLocalizedString(190), LANGUAGE(30032)): ADDON_SETTINGS.writeSettings() if CHANNEL_SHARING: realloc = ADDON.getSetting('SettingsFolder') FileAccess.copy(SETTINGS_LOC + '/settings2.xml', realloc + '/settings2.xml') self.close() elif act.getButtonCode() == 61575: # Delete button curchan = self.listcontrol.getSelectedPosition() + 1 if( (self.showingList == True) and (ADDON_SETTINGS.getSetting("Channel_" + str(curchan) + "_type") != "9999") ): dlg = xbmcgui.Dialog() if dlg.yesno(xbmc.getLocalizedString(190), LANGUAGE(30033)): ADDON_SETTINGS.setSetting("Channel_" + str(curchan) + "_type", "9999") self.updateListing(curchan) self.madeChanges = 1
def _get_files( self, asset_files ): """ fetch the files """ try: finished_path = "" for cnt, url in enumerate( asset_files ): items = os.path.split( url ) # TODO: Change this to U: for other than xbox drive = xbmc.translatePath( ( "U:\\%s" % self.args.install, "Q:\\%s" % self.args.install, )[ os.environ.get( "OS", "xbox" ) == "xbox" ] ) path = os.path.join( drive, os.path.sep.join( items[ 0 ].split( "/" )[ self.args.ioffset : ] ).replace( "%20", " " ) ) if ( not finished_path ): finished_path = path file = items[ 1 ].replace( "%20", " " ) pct = int( ( float( cnt ) / len( asset_files ) ) * 100 ) self.dialog.update( pct, "%s %s" % ( xbmc.getLocalizedString( 30005 ), url, ), "%s %s" % ( xbmc.getLocalizedString( 30006 ), path, ), "%s %s" % ( xbmc.getLocalizedString( 30007 ), file, ) ) if ( self.dialog.iscanceled() ): raise if ( not os.path.isdir( path ) ): os.makedirs( path ) url = self.REPO_URL + url fpath = os.path.join( path, file ) urllib.urlretrieve( url.replace( " ", "%20" ), fpath ) except: # oops print error message print "ERROR: %s::%s (%d) - %s" % ( self.__class__.__name__, sys.exc_info()[ 2 ].tb_frame.f_code.co_name, sys.exc_info()[ 2 ].tb_lineno, sys.exc_info()[ 1 ], ) raise else: self.dialog.close() xbmcgui.Dialog().ok( self.title, xbmc.getLocalizedString( 30008 ), finished_path )
def set_list_control(self): '''select correct list (3=small, 6=big with icons)''' # set list id 6 if available for rich dialog if self.richlayout: self.list_control = self.getControl(6) self.getControl(3).setVisible(False) else: self.list_control = self.getControl(3) self.getControl(6).setVisible(False) self.list_control.setEnabled(True) self.list_control.setVisible(True) # enable cancel button self.set_cancel_button() # show get more button if self.getmorebutton: util.debug("[SC] dialog 1") self.getControl(5).setVisible(True) self.getControl(5).setLabel(xbmc.getLocalizedString(21452)) elif not self.multiselect: util.debug("[SC] dialog 2") self.getControl(5).setLabel(xbmc.getLocalizedString(186)) self.getControl(5).setVisible(True) else: util.debug("[SC] dialog 3") self.getControl(5).setVisible(True) self.getControl(5).setEnabled(True)
def ShowManageDialog(self): manage_list = [] listitems = [] tvshow_dbid = str(self.tvshow["general"].get("DBID", "")) title = self.tvshow["general"].get("TVShowTitle", "") # imdb_id = str(self.tvshow["general"].get("imdb_id", "")) # filename = self.tvshow["general"].get("FilenameAndPath", False) if tvshow_dbid: temp_list = [[xbmc.getLocalizedString(413), "RunScript(script.artwork.downloader,mode=gui,mediatype=tv,dbid=" + tvshow_dbid + ")"], [xbmc.getLocalizedString(14061), "RunScript(script.artwork.downloader, mediatype=tv, dbid=" + tvshow_dbid + ")"], [addon.getLocalizedString(32101), "RunScript(script.artwork.downloader,mode=custom,mediatype=tv,dbid=" + tvshow_dbid + ",extrathumbs)"], [addon.getLocalizedString(32100), "RunScript(script.artwork.downloader,mode=custom,mediatype=tv,dbid=" + tvshow_dbid + ")"]] manage_list += temp_list else: manage_list += [[addon.getLocalizedString(32166), "RunScript(special://home/addons/plugin.program.sickbeard/resources/lib/addshow.py," + title + ")"]] # if xbmc.getCondVisibility("system.hasaddon(script.tvtunes)") and tvshow_dbid: # manage_list.append([addon.getLocalizedString(32102), "RunScript(script.tvtunes,mode=solo&tvpath=$ESCINFO[Window.Property(movie.FilenameAndPath)]&tvname=$INFO[Window.Property(movie.TVShowTitle)])"]) if xbmc.getCondVisibility("system.hasaddon(script.libraryeditor)") and tvshow_dbid: manage_list.append([addon.getLocalizedString(32103), "RunScript(script.libraryeditor,DBID=" + tvshow_dbid + ")"]) manage_list.append([xbmc.getLocalizedString(1049), "Addon.OpenSettings(script.extendedinfo)"]) for item in manage_list: listitems.append(item[0]) selection = xbmcgui.Dialog().select(addon.getLocalizedString(32133), listitems) if selection > -1: builtin_list = manage_list[selection][1].split("||") for item in builtin_list: xbmc.executebuiltin(item)
def listchannels(params, url, category): xbmc.output("[channelselector.py] listchannels") # Verifica actualizaciones solo en el primer nivel if xbmcplugin.getSetting("updatecheck2") == "true": xbmc.output("updatecheck2=true") import updater updater.checkforupdates() else: xbmc.output("updatecheck2=false") CHANNELNAME = "kideoschannel" xbmctools.addnewfolder(CHANNELNAME, "ageslist", CHANNELNAME, xbmc.getLocalizedString(30501), "", "", "") xbmctools.addnewfolder(CHANNELNAME, "categorylist", CHANNELNAME, xbmc.getLocalizedString(30502), "", "", "") xbmctools.addnewfolder(CHANNELNAME, "userlist", CHANNELNAME, xbmc.getLocalizedString(30503), "", "", "") xbmctools.addnewfolder("configuracion", "mainlist", "configuracion", xbmc.getLocalizedString(30504), "", "", "") xbmctools.addnewfolder("descargados", "mainlist", "descargados", xbmc.getLocalizedString(30505), "", "", "") # Label (top-right)... xbmcplugin.setPluginCategory(handle=int(sys.argv[1]), category="Canales") # Disable sorting... xbmcplugin.addSortMethod(handle=int(sys.argv[1]), sortMethod=xbmcplugin.SORT_METHOD_NONE) # End of directory... xbmcplugin.endOfDirectory(handle=int(sys.argv[1]), succeeded=True)
def _map_series_data(self, showdetails): '''maps the tvdb data to more kodi compatible format''' result = {} if showdetails: result["title"] = showdetails["seriesName"] result["status"] = showdetails["status"] result["tvdb_status"] = showdetails["status"] result["tvdb_id"] = showdetails["id"] result["network"] = showdetails["network"] result["studio"] = [showdetails["network"]] local_airday, local_airday_short, airday_int = self._get_local_weekday(showdetails["airsDayOfWeek"]) result["airday"] = local_airday result["airday.short"] = local_airday_short result["airday.int"] = airday_int result["airtime"] = self._get_local_time(showdetails["airsTime"]) result["airdaytime"] = "%s %s (%s)" % (result["airday"], result["airtime"], result["network"]) result["airdaytime.short"] = "%s %s" % (result["airday.short"], result["airtime"]) result["airdaytime.label"] = "%s %s - %s %s" % (result["airday"], result["airtime"], xbmc.getLocalizedString(145), result["network"]) result["airdaytime.label.short"] = "%s %s - %s %s" % ( result["airday.short"], result["airtime"], xbmc.getLocalizedString(145), result["network"]) result["votes"] = showdetails["siteRatingCount"] result["rating.tvdb"] = showdetails["siteRating"] # make sure we have a decimal in the rating if len(str(result["rating.tvdb"])) == 1: result["rating.tvdb"] = "%s.0" % result["rating.tvdb"] result["rating"] = result["rating.tvdb"] result["votes.tvdb"] = showdetails["siteRatingCount"] try: result["runtime"] = int(showdetails["runtime"]) * 60 except Exception: pass result["plot"] = showdetails["overview"] result["genre"] = showdetails["genre"] classification = CLASSIFICATION_REGEX.search("/".join(showdetails["genre"])) if isinstance(showdetails["genre"], list) else None result["classification"] = classification.group(1) if classification else 'Scripted' result["firstaired"] = showdetails["firstAired"] result["imdbnumber"] = showdetails["imdbId"] # artwork result["art"] = {} fanarts = self.get_series_fanarts(showdetails["id"]) if fanarts: result["art"]["fanart"] = fanarts[0] result["art"]["fanarts"] = fanarts landscapes = self.get_series_fanarts(showdetails["id"], True) if landscapes: result["art"]["landscapes"] = landscapes result["art"]["landscape"] = landscapes[0] posters = self.get_series_posters(showdetails["id"]) if posters: result["art"]["posters"] = posters result["art"]["poster"] = posters[0] if showdetails.get("banner"): result["art"]["banner"] = "https://thetvdb.com/banners/" + showdetails["banner"] return result
def manual_set_music_artwork(self, details, mediatype): '''manual override artwork options''' from utils import manual_set_artwork if mediatype == "artist" and "artist" in details: header = "%s: %s" % (xbmc.getLocalizedString(13511), details["artist"]) else: header = "%s: %s" % (xbmc.getLocalizedString(13511), xbmc.getLocalizedString(558)) changemade, artwork = manual_set_artwork(details["art"], mediatype, header) # save results if any changes made if changemade: details["art"] = artwork refresh_needed = False download_art = self.metadatautils.addon.getSetting("music_art_download") == "true" download_art_custom = self.metadatautils.addon.getSetting("music_art_download_custom") == "true" # download artwork to music folder if needed if details.get("diskpath") and download_art: details["art"] = download_artwork(details["diskpath"], details["art"]) refresh_needed = True # download artwork to custom folder if needed if details.get("customartpath") and download_art_custom: details["art"] = download_artwork(details["customartpath"], details["art"]) refresh_needed = True # reload skin to make sure new artwork is visible if refresh_needed: xbmc.sleep(500) xbmc.executebuiltin("ReloadSkin()") # return endresult return details
def translateOrderBy( self, rule ): # Load the rules tree = self._load_rules() hasValue = True if rule[ 0 ] == "sorttitle": rule[ 0 ] = "title" if rule[ 0 ] != "random": # Get the field we're ordering by elems = tree.getroot().find( "matches" ).findall( "match" ) for elem in elems: if elem.attrib.get( "name" ) == rule[ 0 ]: match = xbmc.getLocalizedString( int( elem.find( "label" ).text ) ) else: # We'll manually set for random match = xbmc.getLocalizedString( 590 ) # Get localization of direction direction = None elems = tree.getroot().find( "orderby" ).findall( "type" ) for elem in elems: if elem.text == rule[ 1 ]: direction = xbmc.getLocalizedString( int( elem.attrib.get( "label" ) ) ) directionVal = rule[ 1 ] if direction is None: direction = xbmc.getLocalizedString( int( tree.getroot().find( "orderby" ).find( "type" ).attrib.get( "label" ) ) ) directionVal = tree.getroot().find( "orderby" ).find( "type" ).text return [ [ match, rule[ 0 ] ], [ direction, directionVal ] ]
def authenticate( self ): # request a frob frob = self.flickr_auth_getfrob() # if successful finish authenticating if ( frob[ "stat" ] == "ok" ): # create our params dictionary params = { "api_key": self.api_key, "perms": "delete", "frob": frob[ "frob" ][ "_content" ] } # add api_sig to our params dictionary params[ "api_sig" ] = self._signature( params ) # create our url url = u"%s?%s" % ( self.BASE_URL_AUTH, urllib.urlencode( params ), ) # we handle xboix differnetly if ( os.environ.get( "OS", "n/a" ) == "xbox" ): print "XBMC Flicker authorization url: %s" % ( url, ) ok = xbmcgui.Dialog().yesno( xbmc.getLocalizedString( 30907 ), xbmc.getLocalizedString( 30915 ), "", "", xbmc.getLocalizedString( 30913 ), xbmc.getLocalizedString( 30914 ) ) elif ( os.environ.get( "OS", "n/a" ) == "OS X" ): # osx needs special handling os.system( "open \"%s\"" % ( url, ) ) else: # open our webbrowser for user authentication import webbrowser webbrowser.open( url ) # get response from user if ( DEBUG ): ok = raw_input( "Have you authenticated this application? (Y/N): " ) else: ok = xbmcgui.Dialog().yesno( xbmc.getLocalizedString( 30907 ), xbmc.getLocalizedString( 30912 ), "", "", xbmc.getLocalizedString( 30913 ), xbmc.getLocalizedString( 30914 ) ) # return token if ( ok ): # get token authtoken = self.flickr_auth_getToken( frob=frob[ "frob" ][ "_content" ] ) # if successful return token if ( authtoken[ "stat" ] == "ok" ): return authtoken[ "auth" ][ "token" ][ "_content" ] return ""
def select_art(items, manual_select=False, art_type=""): '''select the preferred image from the list''' image = None if manual_select: # show selectdialog to manually select the item results_list = [] # add none and browse entries listitem = xbmcgui.ListItem(label=xbmc.getLocalizedString(231), iconImage="DefaultAddonNone.png") results_list.append(listitem) listitem = xbmcgui.ListItem(label=xbmc.getLocalizedString(1030), iconImage="DefaultFolder.png") results_list.append(listitem) for item in items: labels = [item["contributedby"], item["dateadded"], item["language"], item["source"]] label = " / ".join(labels) listitem = xbmcgui.ListItem(label=label, iconImage=item["thumb"]) results_list.append(listitem) if manual_select and results_list: dialog = DialogSelect("DialogSelect.xml", "", listing=results_list, window_title=art_type) dialog.doModal() selected_item = dialog.result del dialog if selected_item == 0: image = "" if selected_item == 1: # browse for image dialog = xbmcgui.Dialog() image = dialog.browse(2, xbmc.getLocalizedString(1030), 'files', mask='.gif').decode("utf-8") del dialog elif selected_item > 1: # user has selected an image from online results image = items[selected_item - 2]["image"] elif items: # just grab the first item as best match image = items[0]["image"] return image
def onClick(self, controlID): if controlID == 7: if self.destinationTBN and self.img != DEFAULTAUDIOBIG: import shutil try: shutil.copy(self.img, self.destinationTBN) xbmcgui.Dialog().ok(__language__(120), self.destinationTBN) except: printLastError(False) xbmcgui.Dialog().ok(__language__(106), __language__(121)) else: self.newTBN = self.destinationTBN del shutil elif controlID == 8: album = self.tagsmp3.get('album', self.albumname.replace('.mp3', '').replace('.MP3', '')) keyboard = xbmc.Keyboard(album, xbmc.getLocalizedString(16011)) keyboard.doModal() if keyboard.isConfirmed(): albumsearch = keyboard.getText() artist = self.tagsmp3.get('artist', self.albumname.replace('.mp3', '').replace('.MP3', '')) keyboard = xbmc.Keyboard(artist, xbmc.getLocalizedString(16025)) keyboard.doModal() if keyboard.isConfirmed(): artistsearch = keyboard.getText() if not albumsearch == artistsearch: manuelsearch = '%s - %s' % (albumsearch, artistsearch) else: manuelsearch = albumsearch self.img, self.text = exechttpapi.requestOnAllMusic_Com(manuelsearch) if not self.text == self.img: self.setupControls()
def renameItem(self): position = self.getCurrentListPosition() itemInfos = self.fullInfos.get(position) if not itemInfos: return url = itemInfos.get('url') #title = itemInfos.get('title') keyboard = xbmc.Keyboard(os.path.basename(url), xbmc.getLocalizedString(16013)) keyboard.doModal() if keyboard.isConfirmed(): new = keyboard.getText() try: self.fullInfos[position]['url'] = url.replace(os.path.basename(url), new) self.fullInfos[position]['title'] = new os.rename(url, url.replace(os.path.basename(url), new)) try: cover = url.replace('.mp3', '.tbn').replace('.MP3', '.tbn') newcovername = cover.replace(os.path.basename(cover), new.replace('.mp3', '.tbn').replace('.MP3', '.tbn')) os.rename(cover, newcovername) self.fullInfos[position]['ico'] = newcovername self.fullInfos[position]['icoBig'] = newcovername except: printLastError(False) except: xbmcgui.Dialog().ok(xbmc.getLocalizedString(257), __language__(27), __language__(26), __language__(28)) printLastError(False) else: self.addItemsInControlList() self.setCurrentListPosition(position)
def _fetch_hourly_forecast( self ): # exit script if user changed locations if ( self.areacode != xbmc.getInfoLabel( "Window(Weather).Property(AreaCode)" ) ): return # fetch hourly forecast forecasts = self.WeatherClient.fetch_hourly_forecast() # localized long and short date dictionary longdate_dict = { "January": xbmc.getLocalizedString( 21 ), "February": xbmc.getLocalizedString( 22 ), "March": xbmc.getLocalizedString( 23 ), "April": xbmc.getLocalizedString( 24 ), "May": xbmc.getLocalizedString( 25 ), "June": xbmc.getLocalizedString( 26 ), "July": xbmc.getLocalizedString( 27 ), "August": xbmc.getLocalizedString( 28 ), "September": xbmc.getLocalizedString( 29 ), "October": xbmc.getLocalizedString( 30 ), "November": xbmc.getLocalizedString( 31 ), "December": xbmc.getLocalizedString( 32 ) } shortdate_dict = { "January": xbmc.getLocalizedString( 51 ), "February": xbmc.getLocalizedString( 52 ), "March": xbmc.getLocalizedString( 53 ), "April": xbmc.getLocalizedString( 54 ), "May": xbmc.getLocalizedString( 55 ), "June": xbmc.getLocalizedString( 56 ), "July": xbmc.getLocalizedString( 57 ), "August": xbmc.getLocalizedString( 58 ), "September": xbmc.getLocalizedString( 59 ), "October": xbmc.getLocalizedString( 60 ), "November": xbmc.getLocalizedString( 61 ), "December": xbmc.getLocalizedString( 62 ) } # enumerate thru and set the info for count, forecast in enumerate( forecasts ): # set properties self.WEATHER_WINDOW.setProperty( "Hourly.%d.Time" % ( count + 1, ), forecast[ 0 ] ) self.WEATHER_WINDOW.setProperty( "Hourly.%d.LongDate" % ( count + 1, ), "%s %s" % ( longdate_dict.get( forecast[ 1 ].split( " " )[ 0 ], "" ), forecast[ 1 ].split( " " )[ -1 ], ) ) self.WEATHER_WINDOW.setProperty( "Hourly.%d.ShortDate" % ( count + 1, ), "%s %s" % ( shortdate_dict.get( forecast[ 1 ].split( " " )[ 0 ], "" ), forecast[ 1 ].split( " " )[ -1 ], ) ) self.WEATHER_WINDOW.setProperty( "Hourly.%d.OutlookIcon" % ( count + 1, ), forecast[ 2 ] ) self.WEATHER_WINDOW.setProperty( "Hourly.%d.FanartCode" % ( count + 1, ), os.path.splitext( os.path.basename( forecast[ 2 ] ) )[ 0 ] ) self.WEATHER_WINDOW.setProperty( "Hourly.%d.Temperature" % ( count + 1, ), forecast[ 3 ] ) self.WEATHER_WINDOW.setProperty( "Hourly.%d.Outlook" % ( count + 1, ), forecast[ 4 ] ) self.WEATHER_WINDOW.setProperty( "Hourly.%d.FeelsLike" % ( count + 1, ), forecast[ 5 ] ) self.WEATHER_WINDOW.setProperty( "Hourly.%d.Precipitation" % ( count + 1, ), forecast[ 6 ] ) self.WEATHER_WINDOW.setProperty( "Hourly.%d.Humidity" % ( count + 1, ), forecast[ 7 ] ) self.WEATHER_WINDOW.setProperty( "Hourly.%d.WindDirection" % ( count + 1, ), forecast[ 8 ] ) self.WEATHER_WINDOW.setProperty( "Hourly.%d.WindSpeed" % ( count + 1, ), forecast[ 9 ] ) self.WEATHER_WINDOW.setProperty( "Hourly.%d.ShortWindDirection" % ( count + 1, ), forecast[ 10 ] ) self.WEATHER_WINDOW.setProperty( "Hourly.%d.Sunrise" % ( count + 1, ), forecast[ 11 ] ) self.WEATHER_WINDOW.setProperty( "Hourly.%d.Sunset" % ( count + 1, ), forecast[ 12 ] ) # enumerate thru and clear all hourly times for count in range( len( forecasts ), 12 ): # clear any remaining hourly times as some locals do not have all of them self.WEATHER_WINDOW.clearProperty( "Hourly.%d.Time" % ( count + 1, ) ) # use this to hide info until fully fetched self.WEATHER_WINDOW.setProperty( "Hourly.IsFetched", "true" )
def _show_dialog( self ): self.getControl( 20 ).setLabel( self.args.title ) self.getControl( 30 ).setLabel( "%s: %s" % ( xbmc.getLocalizedString( 30603 ), self.settings[ "local" ] ), ) self.getControl( 40 ).setLabel( "%s:" % ( xbmc.getLocalizedString(30602 ), ) ) self.getControl( 50 ).setLabel( "" ) self.getControl( 100 ).reset() self.getControl( 100 ).addItem( xbmc.getLocalizedString( 30601 ) )
def pickFileSystem(): availableFS = ["FAT32", "ext4", "ext3", "ext2", "NTFS", xbmc.getLocalizedString(222)]; # Cancel selected = xbmcgui.Dialog().select(addon.getLocalizedString(50025), availableFS); # Select file system: fileSystem = availableFS[selected]; if fileSystem == xbmc.getLocalizedString(222): # Cancel return None; return fileSystem;
def _mark_watched( self ): try: pDialog.update( -1, xbmc.getLocalizedString( 30502 ), xbmc.getLocalizedString( 30503 ) ) from pysqlite2 import dbapi2 as sqlite import datetime fetch_sql = "SELECT times_watched FROM movies WHERE idMovie=?;" update_sql = "UPDATE movies SET times_watched=?, last_watched=? WHERE idMovie=?;" # connect to the database db = sqlite.connect( self.settings[ "amt_db_path" ] ) # get our cursor object cursor = db.cursor() # we fetch the times watched so we can increment by one cursor.execute( fetch_sql, ( self.args.idMovie, ) ) # increment the times watched times_watched = cursor.fetchone()[ 0 ] + 1 # get todays date last_watched = datetime.date.today() # update the record with our new values cursor.execute( update_sql, ( times_watched, last_watched, self.args.idMovie, ) ) # commit the update db.commit() # close the database db.close() except: # oops print error message print "ERROR: %s::%s (%d) - %s" % ( self.__class__.__name__, sys.exc_info()[ 2 ].tb_frame.f_code.co_name, sys.exc_info()[ 2 ].tb_lineno, sys.exc_info()[ 1 ], )
def __init__( self ): # # Search by movie file... # listitem = xbmcgui.ListItem( xbmc.getLocalizedString(30001), iconImage="DefaultFolder.png" ) xbmcplugin.addDirectoryItem( handle = int(sys.argv[ 1 ]), url = '%s?action=search' % ( sys.argv[ 0 ] ), listitem=listitem, isFolder=True) # # Search for playing movie... # if xbmc.Player().isPlayingVideo() : movie_file = xbmc.Player().getPlayingFile() listitem = xbmcgui.ListItem( xbmc.getLocalizedString(30002), iconImage="DefaultFolder.png" ) xbmcplugin.addDirectoryItem( handle = int(sys.argv[ 1 ]), url = '%s?action=search&movie_file=%s' % ( sys.argv[ 0 ], urllib.quote_plus( movie_file ) ), listitem=listitem, isFolder=True) # # Disable sorting... # xbmcplugin.addSortMethod( handle=int( sys.argv[ 1 ] ), sortMethod=xbmcplugin.SORT_METHOD_NONE ) # # End of list... # xbmcplugin.endOfDirectory( handle=int( sys.argv[ 1 ] ), succeeded=True )
def linkList(movieid): (moviedetails, moviecount) = db.runSQL(SQL.SINGLE_MOVIE % movieid, True) (results, totalcount) = db.runSQL(SQL.MOVIE_LINKS % movieid) u=sys.argv[0]+ \ "?mode="+str(PLAY_ALL_LINKS)+ \ "&movieid="+str(movieid) print "U: " + u l = xbmcgui.ListItem(xbmc.getLocalizedString(30061), iconImage='DefaultFolder.png', thumbnailImage=fixUrl(moviedetails["FrontCover"])) l.setInfo(type="Video", infoLabels={ "TVShowTitle": moviedetails["Title"], "Title": xbmc.getLocalizedString(30061), "Plot": fixHtml(moviedetails["Plot"])}) xbmcplugin.addDirectoryItem(int(sys.argv[1]), u, l, False) for link in results: l = xbmcgui.ListItem(link["Description"], iconImage="DefaultFolder.png", thumbnailImage=fixUrl(moviedetails["FrontCover"])) l.setInfo(type="Video", infoLabels={ "TVShowTitle": moviedetails["Title"], "Title": link["Description"], "Plot": fixHtml(moviedetails["Plot"])}) print "Adding link: " + link["URL"] xbmcplugin.addDirectoryItem(int(sys.argv[1]), fixUrl(link["URL"]), l, False, totalcount)
def _get_customised_settings_string( self, group ): # This function will return the customised settings string for the given group tree = DATA._get_overrides_skin() if tree is not None: elems = tree.findall('settingslabel') for elem in elems: if elem is not None and elem.attrib.get( 'type' ) == group: if self.LEVEL != "": if elem.attrib.get( 'level' ) == self.LEVEL: if elem.text.isdigit(): return xbmc.getLocalizedString( int( elem.text ) ) else: return elem.text else: if 'level' not in elem.attrib: if elem.text.isdigit(): return xbmc.getLocalizedString( int( elem.text ) ) else: return elem.text # If we get here, no string has been specified in overrides.xml if group == "main": return __language__(32035) elif group == "submenu" and self.LEVEL == "": return __language__(32036) elif group == "submenu" and self.LEVEL != "": return "::MENUNAME::" elif group == "reset": return __language__(32037) return "::MENUNAME::"
def _download_item( self, forceInstall=False ): log("> _download_item() forceInstall=%s" % forceInstall) try: if ( forceInstall or xbmcgui.Dialog().yesno( self.title, xbmc.getLocalizedString( 30000 ), "", "", xbmc.getLocalizedString( 30020 ), xbmc.getLocalizedString( 30021 ) ) ): self.dialog.create( self.title, xbmc.getLocalizedString( 30002 ), xbmc.getLocalizedString( 30003 ) ) asset_files = [] folders = [ self.args.download_url.replace( " ", "%20" ) ] while folders: try: htmlsource = readURL( self.REPO_URL + folders[ 0 ] ) if ( not htmlsource ): raise items = self._parse_html_source( htmlsource ) if ( not items or items[ "status" ] == "fail" ): raise files, dirs = self._parse_items( items ) for file in files: asset_files.append( "%s/%s" % ( items[ "url" ], file, ) ) for folder in dirs: folders.append( folders[ 0 ] + folder ) folders = folders[ 1 : ] except: folders = [] finished_path = self._get_files( asset_files ) self.dialog.close() if finished_path and not forceInstall: xbmcgui.Dialog().ok( self.title, xbmc.getLocalizedString( 30008 ), finished_path ) # force list refresh # xbmc.executebuiltin('Container.Refresh') except: # oops print error message print "ERROR: %s::%s (%d) - %s" % ( self.__class__.__name__, sys.exc_info()[ 2 ].tb_frame.f_code.co_name, sys.exc_info()[ 2 ].tb_lineno, sys.exc_info()[ 1 ], ) self.dialog.close() xbmcgui.Dialog().ok( self.title, xbmc.getLocalizedString( 30030 ) ) log("< _download_item()")
def playRTMP(): vid=re.compile('id=(\d+)').findall(common.args.url)[0] smilurl = getsmil(vid) rtmpurl = str(getrtmp()) swfUrl = getswfUrl() link = str(common.getHTML(smilurl)) match=re.compile('<video src="(.+?)"').findall(link) if (common.settings['quality'] == '0'): dia = xbmcgui.Dialog() ret = dia.select(xbmc.getLocalizedString(30004), [xbmc.getLocalizedString(30016),xbmc.getLocalizedString(30017),xbmc.getLocalizedString(30018)]) if (ret == 2): return else: ret = None for playpath in match: playpath = playpath.replace('.flv','') if '_0700' in playpath and (xbmcplugin.getSetting(pluginhandle,"quality") == '1' or '_0700' in playpath and (ret == 0)): item=xbmcgui.ListItem(common.args.name, iconImage='', thumbnailImage='') item.setInfo( type="Video",infoLabels={ "Title": common.args.name}) item.setProperty("SWFPlayer", swfUrl) item.setProperty("PlayPath", playpath) elif '_0500' in playpath and (xbmcplugin.getSetting(pluginhandle,"quality") == '2') or '_0500' in playpath and (ret == 1): item=xbmcgui.ListItem(common.args.name, iconImage='', thumbnailImage='') item.setInfo( type="Video",infoLabels={ "Title": common.args.name}) item.setProperty("SWFPlayer", swfUrl) item.setProperty("PlayPath", playpath) xbmc.Player(xbmc.PLAYER_CORE_DVDPLAYER).play(rtmpurl, item)
def _select(self, addonlist, category, string): listitem = xbmcgui.ListItem(xbmc.getLocalizedString(15109), iconImage='DefaultAddon.png') addonlist.insert(0, listitem) listitem = xbmcgui.ListItem(xbmc.getLocalizedString(21452)) listitem.setProperty('more', 'true') addonlist.append(listitem) num = xbmcgui.Dialog().select(xbmc.getLocalizedString(424), addonlist, useDetails=True) if num == 0: xbmc.executebuiltin('Skin.Reset(%s)' % (string + '.name')) xbmc.executebuiltin('Skin.Reset(%s)' % (string + '.path')) xbmc.executebuiltin('Skin.Reset(%s)' % (string + '.ext')) xbmc.executebuiltin('Skin.Reset(%s)' % (string + '.multi')) elif num > 0: item = addonlist[num] if item.getProperty('more') == 'true': xbmc.executebuiltin('ActivateWindow(AddonBrowser, addons://repository.xbmc.org/kodi.resource.images/,return)') else: name = item.getLabel() addonid = item.getLabel2() extension = '.%s' % item.getProperty('extension') subfolders = item.getProperty('subfolders') xbmc.executebuiltin('Skin.SetString(%s,%s)' % ((string + '.name'), name)) xbmc.executebuiltin('Skin.SetString(%s,%s)' % ((string + '.path'), 'resource://%s/' % addonid)) if subfolders == 'true': xbmc.executebuiltin('Skin.SetBool(%s)' % (string + '.multi')) xbmc.executebuiltin('Skin.Reset(%s)' % (string + '.ext')) else: xbmc.executebuiltin('Skin.Reset(%s)' % (string + '.multi')) xbmc.executebuiltin('Skin.SetString(%s,%s)' % ((string + '.ext'), extension))
def _finalize_download( self, tmp_path ): try: # copy the trailer msg1 = xbmc.getLocalizedString( 30503 ) % ( os.path.split( self.filepath )[ 1 ], ) msg2 = xbmc.getLocalizedString( 30502 ) % ( os.path.split( self.filepath )[ 0 ], ) pDialog.update( -1, msg1, msg2 ) # necessary for dialog to update xbmc.sleep( 50 ) xbmc.executehttpapi( "FileCopy(%s,%s)" % ( tmp_path, self.filepath.encode( "utf-8" ), ) ) # create conf file for better MPlayer playback only when trailer saved on xbox and not progressive if ( not self.filepath.startswith( "smb://" ) and not g_movie_url.endswith( "p.mov" ) and not os.path.isfile( self.filepath + ".conf" ) and os.environ.get( "OS", "xbox" ) == "xbox" ): f = open( self.filepath + ".conf" , "w" ) f.write( "nocache=1" ) f.close() # copy the thumbnail thumbpath = os.path.splitext( self.filepath )[ 0 ] + ".tbn" msg1 = xbmc.getLocalizedString( 30503 ) % ( os.path.split( thumbpath )[ 1 ], ) pDialog.update( -1, msg1, msg2 ) # necessary for dialog to update xbmc.sleep( 50 ) xbmc.executehttpapi( "FileCopy(%s,%s)" % ( g_thumbnail, thumbpath.encode( "utf-8" ), ) ) # we succeeded return True except: print "ERROR: %s::%s (%d) - %s" % ( self.__class__.__name__, sys.exc_info()[ 2 ].tb_frame.f_code.co_name, sys.exc_info()[ 2 ].tb_lineno, sys.exc_info()[ 1 ], ) return False
def flickr_groups_search( self ): #if ( self.settings[ "advanced_groups_query" ] ): # text = xbmcplugin.getSetting( "groups_query_text" ) #else: # get the user input if ( self.args.gq == "" ): self.args.gq = self._get_keyboard( heading=xbmc.getLocalizedString( 30904 ) ) # if keyboard was cancelled or no query entered return None (cancel) if ( self.args.gq == "" ): return None items = [] # perform the query groups = self.client.flickr_groups_search( text=self.args.gq, auth_token=self.authkey, per_page=self.settings[ "perpage" ], page=self.args.page ) if ( groups[ "stat" ] == "ok" ): # get our previous and/or next page item items = self._get_pages( xbmc.getLocalizedString( 30905 ), groups[ "groups" ][ "page" ], groups[ "groups" ][ "pages" ], groups[ "groups" ][ "perpage" ], groups[ "groups" ][ "total" ] ) self.query_thumbnail = "DefaultFolderBig.png" # enumerate through and add the group to our _Info object for group in groups[ "groups" ][ "group" ]: # doesn't return much #info = self.client.flickr_groups_getInfo( group_id=group[ "nsid" ] ) # if full details leave thumbnail blank, so a thumb will be created(sloooooooow) #if ( self.settings[ "full_details" ] ): # thumbnail = "" #else: thumbnail = "DefaultFolderBig.png" # set the default icon icon = "DefaultFolderBig.png" # hack to correct \u0000 characters, TODO: find why unicode() isn't working exec 'title=u"%s"' % ( group[ "name" ].replace( '"', '\\"' ), ) # create the callback url url = self._get_url( title=title, userid=self.args.userid, usernsid=self.args.usernsid, photosetid="", photoid="", groupid=group[ "nsid" ], category="flickr_groups_pools_getPhotos", primary="", secret="", server="", photos=0, page=1, prevpage=0, update_listing=False ) items += [ _Info( title=title, author=title, description="", url=url, icon=icon, thumbnail_url=thumbnail, isFolder=True ) ] return items
def _get_user( self ): try: self.user_id = "" self.user_nsid = "" # if this is first run open settings and authorize self._run_once() # get the users id and token userid = xbmcplugin.getSetting( "user_id" ) self.authtoken = xbmcplugin.getSetting( "authtoken" ) # if user did not edit settings, return if ( userid == "" ): return True # flickr client client = FlickrClient( True ) # find the user Id of the person if ( "@" in userid ): user = client.flickr_people_findByEmail( find_email=userid ) else: user = client.flickr_people_findByUsername( username=userid ) # if user id is valid and no error occurred return True ok = user[ "stat" ] != "fail" # if successful, set our user id and nsid if ( ok ): self.user_id = user[ "user" ][ "id" ] self.user_nsid = user[ "user" ][ "nsid" ] except: # oops print error message print "ERROR: %s::%s (%d) - %s" % ( self.__class__.__name__, sys.exc_info()[ 2 ].tb_frame.f_code.co_name, sys.exc_info()[ 2 ].tb_lineno, sys.exc_info()[ 1 ], ) ok = False # if an error or an invalid id was entered, notify the user if ( not ok ): xbmcgui.Dialog().ok( xbmc.getLocalizedString( 30900 ), xbmc.getLocalizedString( 30901 ), xbmc.getLocalizedString( 30902 ) ) return ok
def CreateDialogYesNo(header="", line1="", nolabel="", yeslabel="", noaction="", yesaction=""): if yeslabel == "": yeslabel = xbmc.getInfoLabel("Window.Property(Dialog.yes.Label)") if yeslabel == "": yeslabel = xbmc.getLocalizedString(107) if nolabel == "": nolabel = xbmc.getInfoLabel("Window.Property(Dialog.no.Label)") if nolabel == "": nolabel = xbmc.getLocalizedString(106) if yesaction == "": yesaction = xbmc.getInfoLabel("Window.Property(Dialog.yes.Builtin)") if noaction == "": noaction = xbmc.getInfoLabel("Window.Property(Dialog.no.Builtin)") dialog = xbmcgui.Dialog() ret = dialog.yesno(heading=header, line1=line1, nolabel=nolabel, yeslabel=yeslabel) # autoclose missing if ret: for builtin in yesaction.split("||"): xbmc.executebuiltin(builtin) xbmc.sleep(30) else: for builtin in noaction.split("||"): xbmc.executebuiltin(builtin) xbmc.sleep(30) xbmc.executebuiltin("ClearProperty(Dialog.yes.Label") xbmc.executebuiltin("ClearProperty(Dialog.no.Label") xbmc.executebuiltin("ClearProperty(Dialog.yes.Builtin") xbmc.executebuiltin("ClearProperty(Dialog.no.Builtin") return ret
def library_createfile(filename, content, *args, **kwargs): """ Create the file and folder structure: filename=.strm file, content= content of file. *args = folders to create. """ path = kwargs.get('basedir', '').replace('\\', '/') # Convert MS-DOS style paths to UNIX style if not path: utils.kodi_log(u'ADD LIBRARY -- No basedir specified!', 2) return for folder in args: folder = utils.validify_filename(folder) path = '{}{}/'.format(path, folder) content = library_cleancontent(content) if kwargs.get('clean_url', True) else content if not content: utils.kodi_log(u'ADD LIBRARY -- No content specified!', 2) return if not filename: utils.kodi_log(u'ADD LIBRARY -- No filename specified!', 2) return if not library_createpath(path): xbmcgui.Dialog().ok( xbmc.getLocalizedString(20444), _addon.getLocalizedString(32122) + ' [B]{}[/B]'.format(path), _addon.getLocalizedString(32123)) utils.kodi_log(u'ADD LIBRARY -- XBMCVFS unable to create path:\n{}'.format(path), 2) return filepath = '{}{}.{}'.format(path, utils.validify_filename(filename), kwargs.get('file_ext', 'strm')) f = xbmcvfs.File(filepath, 'w') f.write(utils.try_encode_string(content)) f.close() utils.kodi_log(u'ADD LIBRARY -- Successfully added:\n{}\n{}'.format(filepath, content), 2) return filepath
def String(code='', source=''): """ This will return the relevant language skin as set in the resources/language folder for your add-on. By default you'll get the language string returned from your current running add-on but if you send through another add-on id you can grab from any add-on or even the built-in kodi language strings. CODE: String(code, [source]) AVAILABLE PARAMS: (*) code - This is the language string code set in your strings.po file. source - By default this is set to a blank string and will use your current add-on id. However if you want to pull the string from another add-on just enter the add-on id in here. If you'd prefer to pull from the built-in kodi resources files just set as 'system'. EXAMPLE CODE: kodi_string = koding.String(code=10140, source='system') koding_string = koding.String(code=30825, source='script.module.python.koding.aio') dialog.ok('SYSTEM STRING','The string [COLOR=dodgerblue]10140[/COLOR] pulled from the default system language resources is:','[COLOR=gold]%s[/COLOR]' % kodi_string) dialog.ok('PYTHON KODING STRING','The string [COLOR=dodgerblue]30825[/COLOR] pulled from the Python Koding language resources is:','[COLOR=gold]%s[/COLOR]' % koding_string) ~""" import xbmcaddon from addons import Caller if source == '': source = Caller() if source != 'system': addon_id = xbmcaddon.Addon(id=source) mystring = addon_id.getLocalizedString(code) else: mystring = xbmc.getLocalizedString(code) return mystring #----------------------------------------------------------------
def special_listener(): ''' Corner cases that needs to be listened to. This is run in a loop within monitor.py ''' player = xbmc.Player() isPlaying = player.isPlaying() count = int(window('emby.external_count') or 0) if (not isPlaying and xbmc.getCondVisibility('Window.IsVisible(DialogContextMenu.xml)') and xbmc.getInfoLabel('Control.GetLabel(1002)') == xbmc.getLocalizedString(12021)): control = int(xbmcgui.Window(10106).getFocusId()) if control == 1002: # Start from beginning LOG.info("Resume dialog: Start from beginning selected.") window('emby.resume.bool', False) else: LOG.info("Resume dialog: Resume selected.") window('emby.resume.bool', True) elif isPlaying and not window('emby.external_check'): time = player.getTime() if time > 1: # Not external player. window('emby.external_check', value="true") window('emby.external_count', value="0") elif count == 120: LOG.info("External player detected.") window('emby.external.bool', True) window('emby.external_check.bool', True) window('emby.external_count', value="0") elif time == 0: window('emby.external_count', value=str(count + 1))
def searchMusicAlbums( self ): log( '|==================================|' ) log( 'searchMusicAlbums().start' ) listItems = [] self.getControl( 191 ).setLabel( '[B]' + xbmc.getLocalizedString(132) + '[/B]' ) # fields: 0=albumID, 1=title, 2=year, 3=genre, 4=artist, 5=thumb, 6=rating albumsSQL = 'SELECT idAlbum, strAlbum, iYear, strGenre, strArtist, strThumb, iRating FROM albumview WHERE strAlbum LIKE "%' + self.SEARCH_STRING + '%"' log( 'searchMusicAlbums().sql = ' + albumsSQL ) albumsXML = xbmc.executehttpapi( "QueryMusicDatabase(%s)" % quote_plus( albumsSQL ), ) albums = re.findall( "<record>(.+?)</record>", albumsXML, re.DOTALL ) results = len( albums ) log( 'searchMusicAlbums().results = ' + str( results ) ) for count, album in enumerate( albums ): fields = re.findall( "<field>(.*?)</field>", album, re.DOTALL ) log( 'searchMusicAlbums().results(%d).title = %s' % ( count + 1, fields[1], ) ) log( 'searchMusicAlbums().results(%d).path = %s' % ( count + 1, 'musicdb://3/' + fields[0], ) ) listItem = xbmcgui.ListItem( fields[1], fields[4], fields[5], fields[5], 'ActivateWindow(MusicLibrary,musicdb://3/' + fields[0] + ')' ) listItem.setProperty( 'icon', fields[5] ) listItem.setProperty( 'artist', fields[4] ) listItem.setProperty( 'year', fields[2] ) listItem.setProperty( 'genre', fields[3] ) listItem.setProperty( 'path', 'musicdb://3/' + fields[0] ) listItem.setProperty( 'content', 'albums' ) listItems.append( listItem ) if results > 0: self.getControl( 171 ).addItems( listItems ) self.getControl( 170 ).setLabel( str( results ) ) self.getControl( 179 ).setVisible( True ) self.CONTENT_FOUND = 'true' log( 'searchMusicAlbums().end' )
def playlists_widgets(): '''skin provided playlists''' widgets = [] import xml.etree.ElementTree as xmltree for playlist_path in [ "special://skin/playlists/", "special://skin/extras/widgetplaylists/", "special://skin/extras/playlists/" ]: if xbmcvfs.exists(playlist_path): log_msg("skinshortcuts widgets processing: %s" % playlist_path) media_array = kodi_json('Files.GetDirectory', { "directory": playlist_path, "media": "files" }) for item in media_array: if item["file"].endswith(".xsp"): playlist = item["file"] contents = xbmcvfs.File(item["file"], 'r') contents_data = contents.read().decode('utf-8') contents.close() xmldata = xmltree.fromstring(contents_data.encode('utf-8')) media_type = "" label = item["label"] for line in xmldata.getiterator(): if line.tag == "smartplaylist": media_type = line.attrib['type'] if line.tag == "name": label = line.text try: languageid = int(label) label = xbmc.getLocalizedString(languageid) except Exception: pass if not media_type: media_type = detect_plugin_content(playlist) widgets.append([label, playlist, media_type]) return widgets
def flickr_users_search(self): if (self.args.uq == ""): # get the users name or email user_id = self._get_keyboard( heading=xbmc.getLocalizedString(30916)) # no entry return None if (user_id == ""): return None # find the user Id of the person if ("@" in user_id): info = self.client.flickr_people_findByEmail( find_email=user_id) else: info = self.client.flickr_people_findByUsername( username=user_id) # if no user was found return None if (info["stat"] != "ok"): return None # set the user query to the actual users id self.args.uq = info["user"]["id"] # we need to set the title to our query self.args.title = user_id # now call the actual flickr method return self.flickr_people_getPublicPhotos()
def set_list_control(self): '''select correct list (3=small, 6=big with icons)''' # set list id 6 if available for rich dialog if self.richlayout: self.list_control = self.getControl(6) self.getControl(3).setVisible(False) else: self.list_control = self.getControl(3) self.getControl(6).setVisible(False) self.list_control.setEnabled(True) self.list_control.setVisible(True) # enable cancel button self.set_cancel_button() # show get more button if self.getmorebutton: self.getControl(5).setVisible(True) self.getControl(5).setLabel(xbmc.getLocalizedString(21452)) elif not self.multiselect: self.getControl(5).setVisible(False)
def process_channel(self, channeldata): '''transform the json received from kodi into something we can use''' item = {} channelname = channeldata["label"] channellogo = self.metadatautils.get_clean_image( channeldata['thumbnail']) if channeldata.get('broadcastnow'): # channel with epg data item = channeldata['broadcastnow'] item["runtime"] = item["runtime"] * 60 item["genre"] = " / ".join(item["genre"]) # del firstaired as it's value doesn't make any sense at all del item["firstaired"] # append artwork if self.enable_artwork: self.metadatautils.extend_dict( item, self.metadatautils.get_pvr_artwork(item["title"], channelname, item["genre"])) else: # channel without epg item = channeldata item["title"] = xbmc.getLocalizedString(161) item["file"] = "plugin://script.skin.helper.service?action=playchannel&channelid=%s"\ % (channeldata["channelid"]) item["channel"] = channelname item["type"] = "channel" item["label"] = channelname item["channelid"] = channeldata["channelid"] if not channellogo: channellogo = self.metadatautils.get_channellogo(channelname) if channellogo: item["art"] = {"thumb": channellogo} item["channellogo"] = channellogo item["isFolder"] = False return item
def __init__(self): # # Open file... # listitem = xbmcgui.ListItem(xbmc.getLocalizedString(30001), iconImage="DefaultFolder.png") ok = xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]), url=sys.argv[0] + '?action=edit', listitem=listitem, isFolder=False) # # Recent files... # try: recent_files = eval(xbmcplugin.getSetting("recent_files")) except: recent_files = [] for file in recent_files: listitem = xbmcgui.ListItem(file, iconImage="DefaultFile.png") xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]), url='%s?action=edit&file=%s' % (sys.argv[0], urllib.quote_plus(file)), listitem=listitem, isFolder=False) # # Disable sorting... # xbmcplugin.addSortMethod(handle=int(sys.argv[1]), sortMethod=xbmcplugin.SORT_METHOD_NONE) # # End of list... # xbmcplugin.endOfDirectory(handle=int(sys.argv[1]), succeeded=True)
def library_addtvshow(basedir=None, folder=None, url=None, tmdb_id=None, tvdb_id=None, imdb_id=None, p_dialog=None): if not basedir or not folder or not url: return seasons = library_cleancontent_replacer(url, 'type=episode', 'type=tv') # Clean-up flatseasons seasons = library_cleancontent(seasons, details='info=seasons') seasons = KodiLibrary().get_directory(seasons) library_create_nfo('tv', tmdb_id, folder, basedir=basedir) s_count = 0 s_total = len(seasons) for season in seasons: s_count += 1 if not season.get('season'): continue # Skip special seasons S00 season_name = '{} {}'.format(xbmc.getLocalizedString(20373), season.get('season')) p_dialog.update((s_count * 100) // s_total, message=u'Adding {} - {} to library...'.format(season.get('showtitle'), season_name)) if p_dialog else None episodes = library_cleancontent_replacer(season.get('file'), 'type=episode', 'type=season') # Clean to prevent flatseasons episodes = library_cleancontent(episodes, details='info=episodes') episodes = KodiLibrary().get_directory(episodes) i_count = 0 i_total = len(episodes) for episode in episodes: i_count += 1 if not episode.get('episode'): continue # Skip special episodes E00 s_num = episode.get('season') e_num = episode.get('episode') episode_name = 'S{:02d}E{:02d} - {}'.format( utils.try_parse_int(s_num), utils.try_parse_int(e_num), utils.validify_filename(episode.get('title'))) if _plugin.get_db_info(info='dbid', tmdbtype='episode', imdb_id=imdb_id, tmdb_id=tmdb_id, season=s_num, episode=e_num): utils.kodi_log(u'Trakt List Add to Library\nFound {} - {} in library. Skipping...'.format(episode.get('showtitle'), episode_name)) p_dialog.update((i_count * 100) // i_total, message=u'Found {} in library. Skipping...'.format(episode_name)) if p_dialog else None continue # Skip added items p_dialog.update((i_count * 100) // i_total, message=u'Adding {} to library...'.format(episode_name)) if p_dialog else None episode_path = library_cleancontent(episode.get('file')) library_createfile(episode_name, episode_path, folder, season_name, basedir=basedir)
def __init__(self, *args, **kwargs): xbmcgui.WindowXMLDialog.__init__(self) self.movieplayer = VideoPlayer(popstack=True) self.id = kwargs.get('id', False) if not self.id: name = kwargs.get('name').decode("utf-8").split(" " + xbmc.getLocalizedString(20347) + " ") name = name[0].strip() names = name.split(" / ") if len(names) > 1: ret = xbmcgui.Dialog().select("Actor Info", names) if ret == -1: return None name = names[ret] self.id = GetPersonID(unidecode(name)) if self.id: self.id = self.id["id"] else: return None xbmc.executebuiltin("ActivateWindow(busydialog)") if self.id: self.person = GetExtendedActorInfo(self.id) youtube_thread = Get_Youtube_Vids_Thread(self.person["general"]["name"], "", "relevance", 15) youtube_thread.start() db_movies = 0 for item in self.person["movie_roles"]: if "DBID" in item: db_movies += 1 self.person["general"]["DBMovies"] = str(db_movies) log("Blur image %s with radius %i" % (self.person["general"]["thumb"], 25)) image, imagecolor = Filter_Image(self.person["general"]["thumb"], 25) self.person["general"]['ImageFilter'] = image self.person["general"]['ImageColor'] = imagecolor youtube_thread.join() self.youtube_vids = youtube_thread.listitems else: Notify(addon.getLocalizedString(32143)) xbmc.executebuiltin("Dialog.Close(busydialog)")
def monitor_userlist(): # Build list choices with busy_dialog(): user_lists = [] user_lists += TraktAPI().get_list_of_lists('users/me/lists', authorize=True, next_page=False) or [] user_lists += TraktAPI().get_list_of_lists('users/likes/lists', authorize=True, next_page=False) or [] saved_lists = get_monitor_userlists() dialog_list = [i['label'] for i in user_lists] preselected = [ x for x, i in enumerate(user_lists) if (i.get('params', {}).get('list_slug'), i.get('params', {}).get('user_slug')) in saved_lists] # Ask user to choose lists indices = xbmcgui.Dialog().multiselect(ADDON.getLocalizedString(32312), dialog_list, preselect=preselected) if indices is None: return # Build the new settings and check that lists aren't over limit added_lists, added_users = [], [] for x in indices: list_slug = user_lists[x].get('params', {}).get('list_slug') user_slug = user_lists[x].get('params', {}).get('user_slug') if get_userlist(user_slug, list_slug, confirm=50): added_lists.append(list_slug) added_users.append(user_slug) # Set the added lists to our settings if not added_lists or not added_users: return added_lists = ' | '.join(added_lists) added_users = ' | '.join(added_users) ADDON.setSettingString('monitor_userlist', added_lists) ADDON.setSettingString('monitor_userslug', added_users) # Update library? if xbmcgui.Dialog().yesno(xbmc.getLocalizedString(653), ADDON.getLocalizedString(32132)): library_autoupdate(list_slugs=added_lists, user_slugs=added_users, busy_spinner=True)
def localize(string_id): """ Retruns a translated UI string from addon localization files. .. note:: :data:`utils.string_map<codequick.utils.string_map>` needs to be populated before you can pass in a string as the reference. :param string_id: The numeric ID or gettext string ID of the localized string :type string_id: str or int :returns: Localized unicode string. :rtype: str :raises Keyword: if a gettext string ID was given but the string is not found in English :file:`strings.po`. :example: >>> Script.localize(30001) "Toutes les vidéos" >>> Script.localize("All Videos") "Toutes les vidéos" """ if isinstance(string_id, (str, unicode_type)): try: numeric_id = string_map[string_id] except KeyError: raise KeyError("no localization found for string id '%s'" % string_id) else: return addon_data.getLocalizedString(numeric_id) elif 30000 <= string_id <= 30999: return addon_data.getLocalizedString(string_id) elif 32000 <= string_id <= 32999: return script_data.getLocalizedString(string_id) else: return xbmc.getLocalizedString(string_id)
def play(params, url, category): xbmc.output("[kideoschannel.py] play") title = urllib.unquote_plus(params.get("title")) thumbnail = urllib.unquote_plus(params.get("thumbnail")) xbmc.output("[kideoschannel.py] play thumbnail=" + thumbnail) plot = urllib.unquote_plus(params.get("plot")) server = urllib.unquote_plus(params.get("server")) # Abre dialogo dialogWait = xbmcgui.DialogProgress() dialogWait.create(xbmc.getLocalizedString(30901), title, plot) # Carga la página de detalle data = scrapertools.cachePage(url) addvideopage(data, params, url, category) # Busca el id del vídeo patron = '<param name\="flashVars" value\="videoId\=([^"]+)"' matches = re.compile(patron, re.DOTALL).findall(data) scrapertools.printMatches(matches) if len(matches) > 0: video_id = matches[0] url = youtube.geturl(video_id) listitem = xbmcgui.ListItem(title, iconImage="DefaultVideo.png", thumbnailImage=thumbnail) listitem.setInfo("video", {"Title": title, "Plot": plot}) # Cierra dialogo dialogWait.close() del dialogWait # Play video with the proper core xbmc.Player().play(url, listitem)
def searchMusicArtists( self ): log( '|==================================|' ) log( 'searchMusicArtists()' ) listItems = [] self.getControl( 191 ).setLabel( '[B]' + xbmc.getLocalizedString(133) + '[/B]' ) # fields: 0=artistID, 1=artist artistsSQL = 'SELECT idArtist, strArtist FROM artist WHERE strArtist LIKE "%' + self.SEARCH_STRING + '%"' artistsXML = xbmc.executehttpapi( "QueryMusicDatabase(%s)" % quote_plus( artistsSQL ), ) artists = re.findall( "<record>(.+?)</record>", artistsXML, re.DOTALL ) results = len( artists ) log( 'searchMusicArtists().results = ' + str( results ) ) for count, artist in enumerate( artists ): fields = re.findall( "<field>(.*?)</field>", artist, re.DOTALL ) thumb_cache, fanart_cache, play_path = self.getCacheThumb( 'artist' + fields[1], '' ) thumb = "special://profile/Thumbnails/Music/Artists/%s" % ( thumb_cache, ) fanart = "special://profile/Thumbnails/Music/Fanart/%s" % ( fanart_cache, ) log( 'searchMusicArtists().results(%d).title: %s' % ( count + 1, fields[1], ) ) log( 'searchMusicArtists().results(%d).path: %s' % ( count + 1, 'musicdb://2/' + fields[0], ) ) listItem = xbmcgui.ListItem( fields[1], fields[1], thumb, thumb ) listItem.setProperty( 'icon', thumb ) listItem.setProperty( 'fanart_image', thumb ) listItem.setProperty( 'path', 'musicdb://2/' + fields[0] ) listItem.setProperty( 'content', 'artists' ) listItems.append( listItem ) if results > 0: self.getControl( 161 ).addItems( listItems ) self.getControl( 160 ).setLabel( str( results ) ) self.getControl( 169 ).setVisible( True ) self.CONTENT_FOUND = 'true' log( 'searchMusicArtists().end' )
def search_users(self): # get the username to search for from the user self.args.username = self._get_keyboard( heading=xbmc.getLocalizedString(30907)) # if blank or the user cancelled the keyboard, return if (not self.args.username): return False, 0 # we need to set the title to our query self.args.title = self.args.username # we need to set the function to users self.args.category = "users" ok, total = self.fetch_videos( BlipTVClient.BASE_VIDEOS_URL, language_code=self.settings["language_code"]) # if exact match was found return results if (total): return ok, total # if no exact match found we search using regular search engine # we need to set the function to videos self.args.category = "videos" # set the search query to the username self.args.vq = self.args.username # empty username self.args.username = "" return self.fetch_videos(BlipTVClient.BASE_VIDEOS_URL, language_code=self.settings["language_code"])
def changePass(item): oldPass = item.getPassword() if oldPass == "" or oldPass == None: oldPass = sutilsxbmc.getStringFromUser( heading=addon.getLocalizedString(50011), hidden=True) # "Enter password" newPass = sutilsxbmc.getConfirmedPassword() success = item.changePassword(oldPass, newPass) if success: xbmcgui.Dialog().ok(addon.getLocalizedString(50012), addon.getLocalizedString(50067)) # Info , Password changed successfully item.setSettings(password="") # deletes old saved password else: xbmcgui.Dialog().ok(xbmc.getLocalizedString(257), addon.getLocalizedString(50068), item.getErrorMessage()) # Error , Failed to change password del oldPass del newPass return
def _download_item(self): try: if (xbmcgui.Dialog().yesno(self.title, xbmc.getLocalizedString(30000), "", "", xbmc.getLocalizedString(30020), xbmc.getLocalizedString(30021))): self.dialog.create(self.title, xbmc.getLocalizedString(30002), xbmc.getLocalizedString(30003)) script_files = [] folders = [self.args.download_url] while folders: try: htmlsource = self._get_html_source(self.BASE_URL + folders[0]) if (not htmlsource): raise items = self._parse_html_source(htmlsource) if (not items or items["status"] == "fail"): raise files, dirs = self._parse_items(items) for file in files: script_files.append("%s/%s" % ( items["items"]["url"], file, )) for folder in dirs: folders.append(folders[0] + folder) folders = folders[1:] except: folders = [] self._get_files(script_files) except: # oops print error message print "ERROR: %s::%s (%d) - %s" % ( self.__class__.__name__, sys.exc_info()[2].tb_frame.f_code.co_name, sys.exc_info()[2].tb_lineno, sys.exc_info()[1], ) self.dialog.close() xbmcgui.Dialog().ok(self.title, xbmc.getLocalizedString(30030))
def setresourceaddon(addontype, skinstring="", header=""): '''helper to let the user choose a resource addon and set that as skin string''' xbmc.executebuiltin("ActivateWindow(busydialog)") cur_value = try_decode(xbmc.getInfoLabel("Skin.String(%s.name)" % skinstring)) listing = [] addon = xbmcaddon.Addon(ADDON_ID) if not header: header = addon.getLocalizedString(32010) # none option listitem = xbmcgui.ListItem(label=addon.getLocalizedString(32001), iconImage="DefaultAddonNone.png") listitem.setProperty("addonid", "none") listing.append(listitem) # custom path listitem = xbmcgui.ListItem(label=addon.getLocalizedString(32009), iconImage="DefaultFolder.png") listitem.setProperty("addonid", "custom") listing.append(listitem) # available resource addons for item in get_resourceaddons(addontype): label2 = "%s: %s" % (xbmc.getLocalizedString(21863), item["author"]) listitem = xbmcgui.ListItem(label=item["name"], label2=label2, iconImage=item["thumbnail"]) listitem.setPath(item["path"]) listitem.setProperty("addonid", item["addonid"]) listing.append(listitem) # special skinhelper paths if addontype == "resource.images.moviegenrefanart": label = addon.getLocalizedString(32019) listitem = xbmcgui.ListItem( label=label, label2="Skin Helper Service", iconImage="special://home/addons/script.skin.helper.service/icon.png") listitem.setPath("plugin://script.skin.helper.service/?action=moviegenrebackground&genre=") listitem.setProperty("addonid", "skinhelper.forgenre") listing.append(listitem) # show select dialog with choices dialog = DialogSelect("DialogSelect.xml", "", listing=listing, windowtitle=header, richlayout=True, getmorebutton=addontype, autofocuslabel=cur_value) dialog.doModal() result = dialog.result del dialog # process selection... if isinstance(result, bool) and result: # refresh listing requested by getmore button del addon return setresourceaddon(addontype, skinstring) elif result: addon_id = result.getProperty("addonid") addon_name = try_decode(result.getLabel()) if addon_id == "none" and skinstring: # None xbmc.executebuiltin('Skin.Reset(%s)' % skinstring) xbmc.executebuiltin('Skin.Reset(%s.ext)' % skinstring) xbmc.executebuiltin('Skin.SetString(%s.name,%s)' % (skinstring, addon_name)) xbmc.executebuiltin('Skin.SetString(%s.label,%s)' % (skinstring, addon_name)) xbmc.executebuiltin('Skin.Reset(%s.path)' % skinstring) xbmc.executebuiltin('Skin.Reset(%s.multi)' % skinstring) else: if addon_id == "custom": # custom path dialog = xbmcgui.Dialog() custom_path = dialog.browse(0, addon.getLocalizedString(32005), 'files') del dialog result.setPath(custom_path) addonpath = try_decode(result.getfilename()) if addonpath: is_multi, extension = get_multi_extension(addonpath) xbmc.executebuiltin('Skin.SetString(%s,%s)' % (skinstring, addonpath)) xbmc.executebuiltin('Skin.SetString(%s.path,%s)' % (skinstring, addonpath)) xbmc.executebuiltin('Skin.SetString(%s.name,%s)' % (skinstring, addon_name)) xbmc.executebuiltin('Skin.SetString(%s.label,%s)' % (skinstring, addon_name)) xbmc.executebuiltin('Skin.SetString(%s.ext,%s)' % (skinstring, extension)) if is_multi: xbmc.executebuiltin('Skin.SetBool(%s.multi)' % skinstring) else: xbmc.executebuiltin('Skin.Reset(%s.multi)' % skinstring) del addon
fday = time.strftime("%A", time.localtime(int(fdate))) set_property('Day%i.Title' % count, str(fday)) #outlook = forecast['daily']['data'][count]['summary'] set_property('Day%i.Outlook' % count, unicode(forecast['daily']['data'][count]['summary'])) weathercode = WEATHER_CODES[str(forecast['daily']['data'][count]['icon']).lower().replace('.gif','')] set_property('Day%i.OutlookIcon' % count, '%s.png' % weathercode) set_property('Day%i.FanartCode' % count, weathercode) count = count + 1 xbmc.log('Version %s Started: %s' % (__version__, sys.argv),level=log_level) set_property('WeatherProvider', __addonname__) set_property('WeatherProviderLogo', xbmc.translatePath(os.path.join(__cwd__, 'resources', 'banner.png'))) if sys.argv[1].startswith('Location'): keyboard = xbmc.Keyboard('', xbmc.getLocalizedString(14024), False) keyboard.doModal() if (keyboard.isConfirmed() and keyboard.getText() != ''): text = keyboard.getText() items, locs, locids = location(text) dialog = xbmcgui.Dialog() if locs != []: selected = dialog.select(xbmc.getLocalizedString(396), items) if selected != -1: __addon__.setSetting(sys.argv[1], locs[selected]) __addon__.setSetting(sys.argv[1] + 'id', locids[selected]) xbmc.log('Selected Location: %s' % locs[selected],level=log_level) else: dialog.ok(__addonname__, xbmc.getLocalizedString(284)) else: location = __addon__.getSetting('Location%s' % sys.argv[1])
def run(self): self.log("Starting") self.chanlist.exitThread = False self.chanlist.readConfig() self.chanlist.sleepTime = 0.1 if self.myOverlay == None: self.log("Overlay not defined. Exiting.") return self.chanlist.myOverlay = self.myOverlay self.fullUpdating = (self.myOverlay.backgroundUpdating == 0) validchannels = 0 for i in range(self.myOverlay.maxChannels): self.chanlist.channels.append(Channel()) if self.myOverlay.channels[i].isValid: validchannels += 1 # Don't load invalid channels if minimum threading mode is on if self.fullUpdating and self.myOverlay.isMaster: if validchannels < self.chanlist.enteredChannelCount: xbmc.executebuiltin("Notification(%s, %s, %d, %s)" % (ADDON_NAME, LANGUAGE(30024), 4000, ICON)) for i in range(self.myOverlay.maxChannels): if self.myOverlay.channels[i].isValid == False: while True: if self.myOverlay.isExiting: self.log("Closing thread") return xbmc.sleep(1000) if self.paused == False: break self.chanlist.channels[i].setAccessTime(self.myOverlay.channels[i].lastAccessTime) try: if self.chanlist.setupChannel(i + 1, True, True, False) == True: while self.paused: if self.myOverlay.isExiting: self.log("IsExiting") return xbmc.sleep(1000) self.myOverlay.channels[i] = self.chanlist.channels[i] if self.myOverlay.channels[i].isValid == True: xbmc.executebuiltin("Notification(%s, %s, %d, %s)" % (ADDON_NAME, xbmc.getLocalizedString(19029) + ' ' + str(i + 1) + ' ' + LANGUAGE(30025), 4000, ICON)) except: self.log("Unknown Channel Creation Exception", xbmc.LOGERROR) self.log(traceback.format_exc(), xbmc.LOGERROR) return ADDON.setSetting('ForceChannelReset', 'false') self.chanlist.sleepTime = 0.3 while True: for i in range(self.myOverlay.maxChannels): modified = True while modified == True and self.myOverlay.channels[i].getTotalDuration() < PREP_CHANNEL_TIME and self.myOverlay.channels[i].Playlist.size() < 16288: # If minimum updating is on, don't attempt to load invalid channels if self.fullUpdating == False and self.myOverlay.channels[i].isValid == False and self.myOverlay.isMaster: break modified = False if self.myOverlay.isExiting: self.log("Closing thread") return xbmc.sleep(2000) curtotal = self.myOverlay.channels[i].getTotalDuration() if self.myOverlay.isMaster: if curtotal > 0: # When appending, many of the channel variables aren't set, so copy them over. # This needs to be done before setup since a rule may use one of the values. # It also needs to be done after since one of them may have changed while being setup. self.chanlist.channels[i].playlistPosition = self.myOverlay.channels[i].playlistPosition self.chanlist.channels[i].showTimeOffset = self.myOverlay.channels[i].showTimeOffset self.chanlist.channels[i].lastAccessTime = self.myOverlay.channels[i].lastAccessTime self.chanlist.channels[i].totalTimePlayed = self.myOverlay.channels[i].totalTimePlayed self.chanlist.channels[i].isPaused = self.myOverlay.channels[i].isPaused self.chanlist.channels[i].mode = self.myOverlay.channels[i].mode # Only allow appending valid channels, don't allow erasing them try: self.chanlist.setupChannel(i + 1, True, False, True) except: self.log("Unknown Channel Appending Exception", xbmc.LOGERROR) self.log(traceback.format_exc(), xbmc.LOGERROR) return self.chanlist.channels[i].playlistPosition = self.myOverlay.channels[i].playlistPosition self.chanlist.channels[i].showTimeOffset = self.myOverlay.channels[i].showTimeOffset self.chanlist.channels[i].lastAccessTime = self.myOverlay.channels[i].lastAccessTime self.chanlist.channels[i].totalTimePlayed = self.myOverlay.channels[i].totalTimePlayed self.chanlist.channels[i].isPaused = self.myOverlay.channels[i].isPaused self.chanlist.channels[i].mode = self.myOverlay.channels[i].mode else: try: self.chanlist.setupChannel(i + 1, True, True, False) except: self.log("Unknown Channel Modification Exception", xbmc.LOGERROR) self.log(traceback.format_exc(), xbmc.LOGERROR) return else: try: # We're not master, so no modifications...just try and load the channel self.chanlist.setupChannel(i + 1, True, False, False) except: self.log("Unknown Channel Loading Exception", xbmc.LOGERROR) self.log(traceback.format_exc(), xbmc.LOGERROR) return self.myOverlay.channels[i] = self.chanlist.channels[i] if self.myOverlay.isMaster: ADDON_SETTINGS.setSetting('Channel_' + str(i + 1) + '_time', str(self.myOverlay.channels[i].totalTimePlayed)) if self.myOverlay.channels[i].getTotalDuration() > curtotal and self.myOverlay.isMaster: modified = True # A do-while loop for the paused state while True: if self.myOverlay.isExiting: self.log("Closing thread") return xbmc.sleep(2000) if self.paused == False: break timeslept = 0 if self.fullUpdating == False and self.myOverlay.isMaster: return # If we're master, wait 30 minutes in between checks. If not, wait 5 minutes. while (timeslept < 1800 and self.myOverlay.isMaster == True) or (timeslept < 300 and self.myOverlay.isMaster == False): if self.myOverlay.isExiting: self.log("IsExiting") return xbmc.sleep(2000) timeslept += 2 self.log("All channels up to date. Exiting thread.")
def get_categories(self, root=True): try: # default categories if (root): categories = ( ( xbmc.getLocalizedString(30950), "users_albums", "", "", True, 0, "album", "", "", True, ), ( xbmc.getLocalizedString(30951), "presets_photos", "", "", True, 0, "photo", "", "", False, ), ( xbmc.getLocalizedString(30952), "presets_users", "", "", True, 0, "album", "", "", False, ), ( xbmc.getLocalizedString(30955), "users_photos", "", "", True, 0, "photo", "", "", True, ), ( xbmc.getLocalizedString(30956), "users_contacts", "", "", True, 0, "user", "", "", True, ), ( xbmc.getLocalizedString(30957), "featured_photos", "", "", True, 0, "photo", "", "", False, ), ( xbmc.getLocalizedString(30958), "recent_photos", "", "", True, 0, "photo", "", "", False, ), ) # photo preset category elif ("category='presets_photos'" in sys.argv[2]): categories = self.get_presets() # user preset category elif ("category='presets_users'" in sys.argv[2]): categories = self.get_presets(True) # user preset category elif ("category='users_contacts'" in sys.argv[2]): categories = self.get_users_contacts() # fill media list ok = self._fill_media_list(categories) except: # oops print error message print "ERROR: %s::%s (%d) - %s" % ( self.__class__.__name__, sys.exc_info()[2].tb_frame.f_code.co_name, sys.exc_info()[2].tb_lineno, sys.exc_info()[1], ) ok = False # set cache to disc cacheToDisc = (ok and not ("category='presets_photos'" in sys.argv[2] or "category='presets_users'" in sys.argv[2])) # send notification we're finished, successfully or unsuccessfully xbmcplugin.endOfDirectory(handle=int(sys.argv[1]), succeeded=ok, cacheToDisc=cacheToDisc)
def get_presets(self, ptype=False): # set category category = ( "photos", "users", )[ptype] # initialize our category tuple categories = () # add our new search item if (ptype): categories += (( xbmc.getLocalizedString(30953), "search_users", "", "", True, 2, "album", "", "", False, ), ) else: categories += (( xbmc.getLocalizedString(30954), "search_photos", "", "", True, 1, "photo", "", "", False, ), ) # fetch saved presets try: # read the queries presets = eval(xbmcplugin.getSetting("presets_%s" % (category, ))) # sort items presets.sort() except: # no presets found presets = [] # enumerate through the presets list and read the query for query in presets: try: # set photo query and user query to empty pq = username = u"" # set thumbnail thumbnail = query.split(" | ")[1].encode("utf-8") # if this is the user presets set username else set photo query if (ptype): username = query.split(" | ")[0].encode("utf-8") else: pq = query.split(" | ")[0].encode("utf-8") # set category category = ( "photos", "users", )[int(xbmcplugin.getSetting("user_search_kind")) == 0 and ptype] # set kind kind = ( "album", "photo", )[category == "photos"] # set access access = ( "all", "private", "public", )[int(xbmcplugin.getSetting("access"))] access = ( access, "public", )[category == "photos"] # add preset to our dictionary categories += (( query.split(" | ")[0].encode("utf-8"), category, pq, username, True, 0, kind, access, thumbnail, False, ), ) except: # oops print error message print "ERROR: %s::%s (%d) - %s" % ( self.__class__.__name__, sys.exc_info()[2].tb_frame.f_code.co_name, sys.exc_info()[2].tb_lineno, sys.exc_info()[1], ) return categories
def LANG(label_id): if 31000 <= label_id <= 33000: return ADDON.getLocalizedString(label_id) else: return xbmc.getLocalizedString(label_id)
def selectview(self, content_type="other", current_view=None, display_none=False): '''reads skinfile with all views to present a dialog to choose from''' cur_view_select_id = None label = "" all_views = [] if display_none: listitem = xbmcgui.ListItem(label="None") listitem.setProperty("id", "None") all_views.append(listitem) # read the special skin views file if sys.version_info.major == 3: views_file = try_decode( xbmcvfs.translatePath('special://skin/extras/views.xml')) else: views_file = try_decode( xbmc.translatePath('special://skin/extras/views.xml')) if xbmcvfs.exists(views_file): doc = parse(views_file) listing = doc.documentElement.getElementsByTagName('view') itemcount = 0 for view in listing: label = xbmc.getLocalizedString( int(view.attributes['languageid'].nodeValue)) viewid = view.attributes['value'].nodeValue mediatypes = view.attributes['type'].nodeValue.lower().split( ",") if label.lower() == current_view.lower( ) or viewid == current_view: cur_view_select_id = itemcount if display_none: cur_view_select_id += 1 if (("all" in mediatypes or content_type.lower() in mediatypes) and (not "!" + content_type.lower() in mediatypes) and not getCondVisibility( "Skin.HasSetting(SkinHelper.view.Disabled.%s)" % viewid)): image = "special://skin/extras/viewthumbs/%s.jpg" % viewid listitem = xbmcgui.ListItem(label=label) listitem.setArt({'icon': image}) listitem.setProperty("viewid", viewid) listitem.setProperty("icon", image) all_views.append(listitem) itemcount += 1 dialog = DialogSelect("DialogSelect.xml", "", listing=all_views, windowtitle=self.addon.getLocalizedString(32012), richlayout=True) dialog.autofocus_id = cur_view_select_id dialog.doModal() result = dialog.result del dialog if result: viewid = result.getProperty("viewid") label = try_decode(result.getLabel()) return (viewid, label) else: return (None, None)
def select_artwork(self, ftv_id, ftv_type, container_refresh=True, blacklist=[]): if ftv_type not in ['movies', 'tv']: return with busy_dialog(): artwork = self.get_artwork_request(ftv_id, ftv_type) if not artwork: return xbmcgui.Dialog().notification( 'FanartTV', ADDON.getLocalizedString(32217).format(ftv_type, ftv_id)) # Choose Type _artwork_types = [ 'poster', 'fanart', 'clearart', 'clearlogo', 'landscape', 'banner' ] _artwork_types.append('discart' if ftv_type == 'movies' else 'characterart') artwork_types = [i for i in _artwork_types if i not in blacklist ] # Remove types that we previously looked for choice = xbmcgui.Dialog().select(xbmc.getLocalizedString(13511), artwork_types) if choice == -1: return # Get artwork of user's choosing artwork_type = artwork_types[choice] artwork_items = self.get_artwork(ftv_id, ftv_type, artwork_type, get_list=True) # If there was not artwork of that type found then blacklist it before re-prompting if not artwork_items: xbmcgui.Dialog().notification( 'FanartTV', ADDON.getLocalizedString(32217).format(ftv_type, ftv_id)) blacklist.append(artwork_types[choice]) return self.select_artwork(ftv_id, ftv_type, container_refresh, blacklist) # Choose artwork from options items = [ ListItem(label=i.get('url'), label2=ADDON.getLocalizedString(32219).format( i.get('lang', ''), i.get('likes', 0), i.get('id', '')), art={ 'thumb': i.get('url') }).get_listitem() for i in artwork_items if i.get('url') ] choice = xbmcgui.Dialog().select(xbmc.getLocalizedString(13511), items, useDetails=True) if choice == -1: # If user hits back go back to main menu rather than exit completely return self.select_artwork(ftv_id, ftv_type, container_refresh, blacklist) # Cache our choice as the best artwork forever since it was selected manually # Some types have have HD and SD variants so set cache for both for i in ARTWORK_TYPES.get(ftv_type, {}).get(artwork_type, []): success = cache.set_cache( artwork_items[choice].get('url'), cache_name='fanart_tv.best.{}.{}.{}.{}'.format( self.language, ftv_id, ftv_type, i), cache_days=10000) if success and container_refresh: xbmc.executebuiltin('Container.Refresh') xbmc.executebuiltin( 'UpdateLibrary(video,/fake/path/to/force/refresh/on/home)')
def lang(self, id): if id >= 30000 and id <= 30999: return self.addon.getLocalizedString(id) else: return xbmc.getLocalizedString(id)
def getRaiSportVideos(self, key, domain, page): videos = [] header = { 'Accept': 'application/json, text/javascript, */*; q=0.01', 'Content-Type': 'application/json; charset=UTF-8', 'Origin': 'https://www.raisport.rai.it', 'Referer': 'https://www.raisport.rai.it/archivio.html', 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.132 Safari/537.36', 'X-Requested-With': 'XMLHttpRequest', } page = int(page) pageSize = 50 payload = { "page": page, "pageSize": pageSize, "filters": { "tematica": [key], "dominio": domain } } postData = json.dumps(payload) req = urllib2.Request(self.RaiSportSearchUrl, postData, header) response = urllib2.urlopen(req) if response.code != 200: return [] data = response.read() j = json.loads(data) if 'hits' in j: h = j['hits'] if 'hits' in h: for hh in h['hits']: if '_source' in hh: news_type = hh['_source']['tipo'] if news_type == 'Video' and 'media' in hh['_source']: relinker_url = hh['_source']['media']['mediapolis'] if 'durata' in hh['_source']['media']: d = hh['_source']['media']['durata'].split(":") duration = int(d[0]) * 3600 + int( d[1]) * 60 + int(d[2]) else: duration = 0 icon = self.RaiSportMainUrl + hh['_source'][ 'immagini']['default'] title = hh['_source']['titolo'] creation_date = hh['_source']['data_creazione'] if 'sommario' in hh['_source']: desc = creation_date + '\n' + hh['_source'][ 'sommario'] else: desc = creation_date params = { 'mode': 'raisport_video', 'title': title, 'url': relinker_url, 'icon': icon, 'duration': duration, 'aired': creation_date, 'desc': desc } videos.append(params) if h['total'] > (page + pageSize): page += pageSize params = { 'mode': 'raisport_subitem', 'title': xbmc.getLocalizedString(33078), 'page': page } videos.append(params) return videos
import os import sys import urllib2 from urlparse import urljoin settings = xbmcaddon.Addon('plugin.video.epgremote') plugin = settings.getAddonInfo('name') if __name__ == '__main__' and len(sys.argv) == 3: server_url = settings.getSetting('server_url') videoId = sys.argv[1] fileName = sys.argv[2] opener = urllib2.build_opener(urllib2.HTTPHandler) dialog = xbmcgui.Dialog() if dialog.yesno(xbmc.getLocalizedString(122).encode('utf_8'), xbmc.getLocalizedString(433).encode('utf_8') % fileName, yeslabel=xbmc.getLocalizedString(117)): progress = xbmcgui.DialogProgress() progress.create(plugin, 'Deleting recorded file...') progress.update(0) try: req = urllib2.Request( urljoin(server_url, '/api/recorded/video?delete_file=1&rec_id=' + videoId)) req.get_method = lambda: 'DELETE' url = opener.open(req) except: xbmc.log('Failed to delete recoded file: %s' % videoId, level=xbmc.LOGERROR)
def select_best_match(results, prefyear="", preftype="", preftitle="", manual_select=False): '''helper to select best match or let the user manually select the best result from the search''' details = {} # score results if one or more preferences are given if results and (prefyear or preftype or preftitle): newdata = [] preftitle = preftitle.lower() for item in results: item["score"] = 0 itemtitle = item["title"] if item.get( "title") else item["name"] itemtitle = itemtitle.lower() itemorgtitle = item["original_title"] if item.get( "original_title") else item["original_name"] itemorgtitle = itemorgtitle.lower() # high score if year matches if prefyear: if item.get("first_air_date" ) and prefyear in item["first_air_date"]: item["score"] += 800 # matches preferred year if item.get("release_date" ) and prefyear in item["release_date"]: item["score"] += 800 # matches preferred year # find exact match on title if preftitle and preftitle == itemtitle: item["score"] += 1000 # exact match! if preftitle and preftitle == itemorgtitle: item["score"] += 1000 # exact match! # match title by replacing some characters if preftitle and get_compare_string( preftitle) == get_compare_string(itemtitle): item["score"] += 750 if preftitle and get_compare_string( preftitle) == get_compare_string(itemorgtitle): item["score"] += 750 # add SequenceMatcher score to the results if preftitle: stringmatchscore = SM( None, preftitle, itemtitle).ratio() + SM( None, preftitle, itemorgtitle).ratio() if stringmatchscore > 1.6: item["score"] += stringmatchscore * 250 # higher score if result ALSO matches our preferred type or native language # (only when we already have a score) if item["score"]: if preftype and (item["media_type"] in preftype) or ( preftype in item["media_type"]): item["score"] += 250 # matches preferred type if item["original_language"] == KODI_LANGUAGE: item["score"] += 500 # native language! if KODI_LANGUAGE.upper() in item.get("origin_country", []): item["score"] += 500 # native language! if KODI_LANGUAGE in item.get("languages", []): item["score"] += 500 # native language! if item["score"] > 500 or manual_select: newdata.append(item) results = sorted(newdata, key=itemgetter("score"), reverse=True) if results and manual_select: # show selectdialog to manually select the item results_list = [] for item in results: title = item["name"] if "name" in item else item["title"] if item.get("premiered"): year = item["premiered"].split("-")[0] else: year = item.get("first_air_date", "").split("-")[0] if item["poster_path"]: thumb = "http://image.tmdb.org/t/p/original%s" % item[ "poster_path"] else: thumb = "" label = "%s (%s) - %s" % (title, year, item["media_type"]) listitem = xbmcgui.ListItem(label=label, iconImage=thumb, label2=item["overview"]) results_list.append(listitem) if manual_select and results_list: dialog = DialogSelect("DialogSelect.xml", "", listing=results_list, window_title="%s - TMDB" % xbmc.getLocalizedString(283)) dialog.doModal() selected_item = dialog.result del dialog if selected_item != -1: details = results[selected_item] else: results = [] if not details and results: # just grab the first item as best match details = results[0] return details