Пример #1
0
def apiLanguage(ret_name=None):
    langDict = {'Bulgarian': 'bg', 'Chinese': 'zh', 'Croatian': 'hr', 'Czech': 'cs', 'Danish': 'da', 'Dutch': 'nl', 'English': 'en', 'Finnish': 'fi', 'French': 'fr', 'German': 'de', 'Greek': 'el', 'Hebrew': 'he', 'Hungarian': 'hu', 'Italian': 'it', 'Japanese': 'ja', 'Korean': 'ko', 'Norwegian': 'no', 'Polish': 'pl', 'Portuguese': 'pt', 'Romanian': 'ro', 'Russian': 'ru', 'Serbian': 'sr', 'Slovak': 'sk', 'Slovenian': 'sl', 'Spanish': 'es', 'Swedish': 'sv', 'Thai': 'th', 'Turkish': 'tr', 'Ukrainian': 'uk'}

    trakt = ['bg','cs','da','de','el','en','es','fi','fr','he','hr','hu','it','ja','ko','nl','no','pl','pt','ro','ru','sk','sl','sr','sv','th','tr','uk','zh']
    tvdb = ['en','sv','no','da','fi','nl','de','it','es','fr','pl','hu','el','tr','ru','he','ja','pt','zh','cs','sl','hr','ko']
    youtube = ['gv', 'gu', 'gd', 'ga', 'gn', 'gl', 'ty', 'tw', 'tt', 'tr', 'ts', 'tn', 'to', 'tl', 'tk', 'th', 'ti', 'tg', 'te', 'ta', 'de', 'da', 'dz', 'dv', 'qu', 'zh', 'za', 'zu', 'wa', 'wo', 'jv', 'ja', 'ch', 'co', 'ca', 'ce', 'cy', 'cs', 'cr', 'cv', 'cu', 'ps', 'pt', 'pa', 'pi', 'pl', 'mg', 'ml', 'mn', 'mi', 'mh', 'mk', 'mt', 'ms', 'mr', 'my', 've', 'vi', 'is', 'iu', 'it', 'vo', 'ii', 'ik', 'io', 'ia', 'ie', 'id', 'ig', 'fr', 'fy', 'fa', 'ff', 'fi', 'fj', 'fo', 'ss', 'sr', 'sq', 'sw', 'sv', 'su', 'st', 'sk', 'si', 'so', 'sn', 'sm', 'sl', 'sc', 'sa', 'sg', 'se', 'sd', 'lg', 'lb', 'la', 'ln', 'lo', 'li', 'lv', 'lt', 'lu', 'yi', 'yo', 'el', 'eo', 'en', 'ee', 'eu', 'et', 'es', 'ru', 'rw', 'rm', 'rn', 'ro', 'be', 'bg', 'ba', 'bm', 'bn', 'bo', 'bh', 'bi', 'br', 'bs', 'om', 'oj', 'oc', 'os', 'or', 'xh', 'hz', 'hy', 'hr', 'ht', 'hu', 'hi', 'ho', 'ha', 'he', 'uz', 'ur', 'uk', 'ug', 'aa', 'ab', 'ae', 'af', 'ak', 'am', 'an', 'as', 'ar', 'av', 'ay', 'az', 'nl', 'nn', 'no', 'na', 'nb', 'nd', 'ne', 'ng', 'ny', 'nr', 'nv', 'ka', 'kg', 'kk', 'kj', 'ki', 'ko', 'kn', 'km', 'kl', 'ks', 'kr', 'kw', 'kv', 'ku', 'ky']

    name = setting('api.language')
    if name[-1].isupper():
        try: name = xbmc.getLanguage(xbmc.ENGLISH_NAME).split(' ')[0]
        except: pass
    try: name = langDict[name]
    except: name = 'en'
    lang = {'trakt': name} if name in trakt else {'trakt': 'en'}
    lang['tvdb'] = name if name in tvdb else 'en'
    lang['youtube'] = name if name in youtube else 'en'

    if ret_name:
        lang['trakt'] = [i[0] for i in langDict.iteritems() if i[1] == lang['trakt']][0]
        lang['tvdb'] = [i[0] for i in langDict.iteritems() if i[1] == lang['tvdb']][0]
        lang['youtube'] = [i[0] for i in langDict.iteritems() if i[1] == lang['youtube']][0]

    return lang
Пример #2
0
def show_about():
    if kodi.get_setting("disable_about") == "true":
        return
    interval = int(kodi.get_setting("last_about"))
    if interval == 0:
        interval = 5
        try:
            import xbmc

            KODI_LANGUAGE = xbmc.getLanguage()
        except:
            KODI_LANGUAGE = "English"
        path = kodi.vfs.join(kodi.get_path(),
                             "resources/language/%s/github_help.txt",
                             KODI_LANGUAGE)
        if not kodi.vfs.exists(path):
            path = kodi.vfs.join(kodi.get_path(),
                                 "resources/language/English/github_help.txt")
        text = kodi.vfs.read_file(path)
        kodi.dialog_textbox("GitHub Browser Instructions", text)
    else:
        interval -= 1
    kodi.set_setting("last_about", interval)
Пример #3
0
def _get_default_audio_language(manifest):
    channelList = {'1.0': '1', '2.0': '2'}
    channelListDolby = {'5.1': '6', '7.1': '8'}

    # Read language in kodi settings
    audio_language = common.json_rpc('Settings.GetSettingValue',
                                     {'setting': 'locale.audiolanguage'})
    audio_language = xbmc.convertLanguage(
        audio_language['value'].encode('utf-8'), xbmc.ISO_639_1)
    audio_language = audio_language if audio_language else xbmc.getLanguage(
        xbmc.ISO_639_1, False)
    audio_language = audio_language if audio_language else 'en'

    # Try to find the preferred language with the right channels
    if g.ADDON.getSettingBool('enable_dolby_sound'):
        for index, audio_track in enumerate(manifest['audio_tracks']):
            if audio_track['language'] == audio_language and audio_track[
                    'channels'] in channelListDolby:
                return index
    # If dolby audio track not exists check other channels list
    for index, audio_track in enumerate(manifest['audio_tracks']):
        if audio_track['language'] == audio_language and audio_track[
                'channels'] in channelList:
            return index

    # If there is no matches to preferred language, try to sets the original language track as default
    # Check if the dolby audio track in selected language exists
    if g.ADDON.getSettingBool('enable_dolby_sound'):
        for index, audio_track in enumerate(manifest['audio_tracks']):
            if audio_track['isNative'] and audio_track[
                    'channels'] in channelListDolby:
                return index
    # If dolby audio track not exists check other channels list
    for index, audio_track in enumerate(manifest['audio_tracks']):
        if audio_track['isNative'] and audio_track['channels'] in channelList:
            return index
    return 0
Пример #4
0
 def get_Weather(self, url, param):
     if xbmc.getLanguage() == 'German':
         header = {
             "Host": "www.google.com",
             "User-Agent":
             "Mozilla/5.0 (Windows; U; Windows NT 5.1; de; rv:1.8.1.11) Gecko/20071127 Firefox/2.0.0.11",
             "Accept": "*/*",
             "Accept-Language": "de-de,de",
             "Accept-Charset": "ISO-8859-1,utf-8;q=0.7,*;q=0.7",
             "Keep-Alive": "300",
             "Proxy-Connection": "keep-alive",
             "Referer": url
         }
     else:
         header = {
             "Host": "www.google.com",
             "User-Agent":
             "Mozilla/5.0 (Windows; U; Windows NT 5.1; de; rv:1.8.1.11) Gecko/20071127 Firefox/2.0.0.11",
             "Accept": "*/*",
             "Accept-Language": "en-en,en",
             "Accept-Charset": "ISO-8859-1,utf-8;q=0.7,*;q=0.7",
             "Keep-Alive": "300",
             "Proxy-Connection": "keep-alive",
             "Referer": url
         }
     params = param
     body = ''
     self.sTargetUrl = "http://www.google.com/ig/api"
     print self.sTargetUrl + params
     if self._request("GET", params, header, body) != True:
         return False
     data = self.sData
     fName = file
     f = open(TEMPFOLDER + "weather.xml", 'wb')
     f.write(data)
     f.close()
     return self.sData
Пример #5
0
import xbmc

lang = xbmc.getLanguage(xbmc.ISO_639_1, region=True)
lang = (lang or 'en-GB').split('-')
lang[1] = (lang[1] or 'GB').lower()
LANG = '_'.join(lang)
try:
    module = __import__('resources.lib.translation.' + LANG, fromlist=[LANG])
    trans = dict(getattr(module, LANG))

    def _(key):
        return trans[key]
except ImportError:
    import xbmcaddon

    def _(msgctxt):
        return xbmcaddon.Addon().getLocalizedString(msgctxt)
Пример #6
0
def make_visitor():
    from pyga.requests import Visitor
    visitor = Visitor()
    visitor.user_agent = get_user_agent()
    visitor.locale = xbmc.getLanguage()
    return visitor
Пример #7
0
 def GetLanguage(self, *args, **kwargs):
     return xbmc.getLanguage(*args, **kwargs)
Пример #8
0
__version__    = __addon__.getAddonInfo('version')
__language__   = __addon__.getLocalizedString
__resource__   = xbmc.translatePath(os.path.join(__cwd__, 'resources', 'lib'))

sys.path.append (__resource__)

from utilities import *
from wunderground import wundergroundapi

WUNDERGROUND_LOC = 'http://autocomplete.wunderground.com/aq?query=%s&format=JSON'
WEATHER_FEATURES = 'hourly/conditions/forecast10day/astronomy/almanac/alerts/satellite'
FORMAT           = 'json'
DEBUG            = __addon__.getSetting('Debug')
WEATHER_ICON     = xbmc.translatePath('special://temp/weather/%s.png').decode("utf-8")
WEATHER_WINDOW   = xbmcgui.Window(12600)
LANGUAGE         = xbmc.getLanguage().lower()
SPEEDUNIT        = xbmc.getRegion('speedunit')
TEMPUNIT         = unicode(xbmc.getRegion('tempunit'),encoding='utf-8')
TIMEFORMAT       = xbmc.getRegion('meridiem')
DATEFORMAT       = xbmc.getRegion('dateshort')
MAXDAYS          = 6

socket.setdefaulttimeout(10)

def log(txt):
    if DEBUG == 'true':
        if isinstance (txt,str):
            txt = txt.decode("utf-8")
        message = u'%s: %s' % (__addonid__, txt)
        xbmc.log(msg=message.encode("utf-8"), level=xbmc.LOGDEBUG)
Пример #9
0
class RatingParser:
    SYSTEM_RATING_REs = {
        # 'MPAA': r'(?i)^Rated\s(?P<rating>Unrated|NR|PG-13|PG|G|R|NC-17)',
        'BBFC': r'(?i)^UK(?:\s+|:)(?P<rating>Uc|U|12A|12|PG|15|R18|18)',
        'FSK':
        r'(?i)^(?:FSK|Germany)(?:\s+|:)(?P<rating>0|6|12|16|18|Unrated)',
        'DEJUS':
        r'(?i)(?P<rating>Livre|10 Anos|12 Anos|14 Anos|16 Anos|18 Anos)'
    }

    RATING_REs = {
        'MPAA': r'(?i)(?P<rating>Unrated|NR|PG-13|PG|G|R|NC-17)',
        'BBFC': r'(?i)(?P<rating>Uc|U|12A|12|PG|15|R18|18)',
        'FSK': r'(?i)(?P<rating>0|6|12|16|18|Unrated)',
        'DEJUS':
        r'(?i)(?P<rating>Livre|10 Anos|12 Anos|14 Anos|16 Anos|18 Anos)'
    }

    SYSTEM_RATING_REs.update(cinemavision.ratings.getRegExs('kodi'))
    RATING_REs.update(cinemavision.ratings.getRegExs())

    LANGUAGE = xbmc.getLanguage(xbmc.ISO_639_1, region=True)

    def __init__(self):
        kodiutil.DEBUG_LOG('Language: {0}'.format(self.LANGUAGE))
        self.setRatingDefaults()

    def setRatingDefaults(self):
        ratingSystem = kodiutil.getSetting('rating.system.default', 'MPAA')

        if not ratingSystem:
            try:
                countryCode = self.LANGUAGE.split('-')[1].strip()
                if countryCode:
                    cinemavision.ratings.setCountry(countryCode)
            except IndexError:
                pass
            except:
                kodiutil.ERROR()
        else:
            cinemavision.ratings.setDefaultRatingSystem(ratingSystem)

    def getActualRatingFromMPAA(self, rating, debug=False):
        if debug:
            kodiutil.DEBUG_LOG('Rating from Kodi: {0}'.format(
                kodiutil.strRepr(rating)))

        if not rating:
            return 'UNKNOWN:NR'

        # Try a definite match
        for system, ratingRE in self.SYSTEM_RATING_REs.items():
            m = re.search(ratingRE, rating)
            if m:
                return '{0}:{1}'.format(system, m.group('rating'))

        rating = rating.upper().replace('RATED', '').strip(': ')

        # Try to match against default system if set
        defaultSystem = cinemavision.ratings.DEFAULT_RATING_SYSTEM
        if defaultSystem and defaultSystem in self.RATING_REs:
            m = re.search(self.RATING_REs[defaultSystem], rating)
            if m:
                return '{0}:{1}'.format(defaultSystem, m.group('rating'))

        # Try to extract rating from know ratings systems
        for system, ratingRE in self.RATING_REs.items():
            m = re.search(ratingRE, rating)
            if m:
                return m.group('rating')

        # Just return what we have
        return rating
Пример #10
0
def plugin_process_info(playdata):
    info = {
        'label1': '',
        'label2': '',
        'description': '',
        'image': '',
        'image_large': '',
        'duration': 0,
        'credits': [],
        'cast': [],
        'director': [],
        'writer': [],
        'genres': [],
        'year': '',
    }

    if check_key(playdata['info'], 'Start') and check_key(
            playdata['info'], 'End'):
        startT = datetime.datetime.fromtimestamp(
            time.mktime(
                time.strptime(playdata['info']['Start'], "%Y-%m-%dT%H:%M:%S")))
        startT = convert_datetime_timezone(startT, "UTC", "UTC")
        endT = datetime.datetime.fromtimestamp(
            time.mktime(
                time.strptime(playdata['info']['End'], "%Y-%m-%dT%H:%M:%S")))
        endT = convert_datetime_timezone(endT, "UTC", "UTC")

        write_file(file='stream_start',
                   data=int(
                       time.mktime(
                           time.strptime(playdata['info']['Start'],
                                         "%Y-%m-%dT%H:%M:%S"))),
                   isJSON=False)
        write_file(file='stream_end',
                   data=int(
                       time.mktime(
                           time.strptime(playdata['info']['End'],
                                         "%Y-%m-%dT%H:%M:%S"))),
                   isJSON=False)

        if check_key(playdata['info'], 'DurationInSeconds'):
            info['duration'] = playdata['info']['DurationInSeconds']
        elif check_key(playdata['info'], 'Duur'):
            info['duration'] = playdata['info']['Duur']
        else:
            info['duration'] = int((endT - startT).total_seconds())

        if xbmc.getLanguage(xbmc.ISO_639_1) == 'nl':
            info[
                'label1'] = '{weekday} {day} {month} {yearhourminute} '.format(
                    weekday=date_to_nl_dag(startT),
                    day=startT.strftime("%d"),
                    month=date_to_nl_maand(startT),
                    yearhourminute=startT.strftime("%Y %H:%M"))
        else:
            info['label1'] = startT.strftime("%A %d %B %Y %H:%M ").capitalize()

    if check_key(playdata['info'], 'Duur'):
        info['duration'] = playdata['info']['Duur']

    if check_key(playdata['info'], 'Title'):
        if len(str(info['label1'])) > 0:
            info['label1'] += " - "

        if len(str(info['label2'])) > 0:
            info['label2'] += " - "

        info['label1'] += playdata['info']['Title']
        info['label2'] += playdata['info']['Title']
    elif check_key(playdata['info'], 'Serie') and check_key(
            playdata['info']['Serie'], 'Titel') and len(
                playdata['info']['Serie']['Titel']):
        if len(str(info['label1'])) > 0:
            info['label1'] += " - "

        if len(str(info['label2'])) > 0:
            info['label2'] += " - "

        info['label1'] += playdata['info']['Serie']['Titel']
        info['label2'] += playdata['info']['Serie']['Titel']

        if check_key(
                playdata['info'],
                'Titel') and len(playdata['info']['Titel']) > 0 and playdata[
                    'info']['Titel'] != playdata['info']['Serie']['Titel']:
            if len(str(info['label1'])) > 0:
                info['label1'] += ": "

            if len(str(info['label2'])) > 0:
                info['label2'] += ": "

            info['label1'] += playdata['info']['Titel']
            info['label2'] += playdata['info']['Titel']

    if check_key(playdata['info'], 'LongDescription'):
        info['description'] = playdata['info']['LongDescription']
    elif check_key(playdata['info'], 'Omschrijving'):
        info['description'] = playdata['info']['Omschrijving']

    if check_key(playdata['info'], 'CoverUrl'):
        info['image'] = playdata['info']['CoverUrl']
        info['image_large'] = playdata['info']['CoverUrl']
    elif check_key(playdata['info'], 'AfbeeldingUrl'):
        info['image'] = playdata['info']['AfbeeldingUrl']
        info['image_large'] = playdata['info']['AfbeeldingUrl']

    if check_key(playdata['info'], 'ChannelTitle'):
        if len(str(info['label2'])) > 0:
            info['label2'] += " - "

        info['label2'] += playdata['info']['ChannelTitle']
    elif check_key(playdata['info'], 'Zender'):
        if len(str(info['label2'])) > 0:
            info['label2'] += " - "

        info['label2'] += playdata['info']['Zender']

    return info
Пример #11
0
import time, datetime
import xbmc, xbmcaddon, xbmcgui, xbmcplugin

addon_handle = int(sys.argv[1])
addon = xbmcaddon.Addon()
dialog = xbmcgui.Dialog()
addon_id = addon.getAddonInfo('id')
addon_name = addon.getAddonInfo('name')
version = addon.getAddonInfo('version')
icon = addon.getAddonInfo('icon')
fanart = addon.getAddonInfo('fanart')
content = addon.getSetting('content')
view_id = addon.getSetting('view_id')
force_view = addon.getSetting('force_view') == 'true'
token = addon.getSetting('token')
language = xbmc.getLanguage(0, False)
country = addon.getSetting('country')
cdn = int(addon.getSetting('server'))
store_creds = addon.getSetting('store_creds') == 'true'
if not store_creds:
    addon.setSetting('email', '')
    addon.setSetting('password', '')

api_base = 'https://isl.dazn.com/misl/'

time_format = '%Y-%m-%dT%H:%M:%SZ'
date_format = '%Y-%m-%d'


def log(msg):
    xbmc.log(str(msg), xbmc.LOGNOTICE)
Пример #12
0
# -*- coding: utf-8 -*-
import xbmc, xbmcaddon, xbmcplugin, xbmcgui
import sys, os, time, datetime, re, platform
import urllib, urllib2, json
import repoCheck

AddonID = "plugin.video.israelive"
Addon = xbmcaddon.Addon(AddonID)
localizedString = Addon.getLocalizedString
xbmcLang = xbmc.getLanguage(0)
if xbmcLang != "he":
    xbmcLang = "en"

libDir = os.path.join(
    Addon.getAddonInfo("path").decode("utf-8"), 'resources', 'lib')
sys.path.insert(0, libDir)
import myFilmon, common, myResolver

filmonOldStrerams = Addon.getSetting("StreramsMethod") == "0"
useRtmp = Addon.getSetting("StreramProtocol") == "1"
__icon__ = 'http://static2.wikia.nocookie.net/__cb20121121053458/spongebob/images/f/f4/Check-icon.png'
__icon2__ = 'https://svn.apache.org/repos/asf/openoffice/symphony/trunk/main/extras/source/gallery/symbols/Sign-QuestionMark02-Red.png'
icon = Addon.getAddonInfo('icon')
AddonName = Addon.getAddonInfo("name")

user_dataDir = xbmc.translatePath(
    Addon.getAddonInfo("profile")).decode("utf-8")
if not os.path.exists(user_dataDir):
    os.makedirs(user_dataDir)

tmpList = os.path.join(user_dataDir, 'tempList.txt')
Пример #13
0
# start script
params = get_params()

# called when user is searching for subtitles
if params['action'] == 'search':
    item = {}
    item['year'] = xbmc.getInfoLabel("VideoPlayer.Year")
    item['season'] = str(xbmc.getInfoLabel("VideoPlayer.Season"))
    item['episode'] = str(xbmc.getInfoLabel("VideoPlayer.Episode"))
    item['tvshow'] = normalize_string(
        xbmc.getInfoLabel("VideoPlayer.TVshowtitle"))
    item['title'] = normalize_string(
        xbmc.getInfoLabel("VideoPlayer.OriginalTitle"))
    item['path'] = urllib.unquote(
        xbmc.Player().getPlayingFile().decode('utf-8'))
    item['uilang'] = str(xbmc.getLanguage())
    item['langs'] = []
    # get user preferred languages for subtitles
    for lang in urllib.unquote(params['languages']).decode('utf-8').split(","):
        item['langs'].append(xbmc.convertLanguage(lang, xbmc.ISO_639_1))
    log("user langs = %s" % (item['langs']))
    # remove rar:// or stack://
    if (item['path'].find("rar://") > -1):
        item['path'] = os.path.dirname(item['path'][6:])
    elif (item['path'].find("stack://") > -1):
        stackPath = item['path'].split(" , ")
        item['path'] = stackPath[0][8:]
    # call search_subtitles()
    if item['tvshow'] == "":
        search_subtitles(video="movie",
                         name=item['title'],
Пример #14
0
# euTorrents.ph subtitles, based on a mod of Undertext subtitles

import os, sys, re, xbmc, xbmcgui, string, time, urllib, urllib2, cookielib, shutil, fnmatch, uuid
from utilities import languageTranslate, log
_ = sys.modules["__main__"].__language__
__scriptname__ = sys.modules["__main__"].__scriptname__
__addon__ = sys.modules["__main__"].__addon__
__cwd__ = sys.modules["__main__"].__cwd__
__language__ = __addon__.getLocalizedString

main_url = "http://eutorrents.ph/"
debug_pretext = "euTorrents"
subext = ['srt', 'aas', 'ssa', 'sub', 'smi']
sub_ext = ['srt', 'aas', 'ssa', 'sub', 'smi']
packext = ['rar', 'zip']
isLang = xbmc.getLanguage()
#DEBUG ONLY
#log( __name__ ,"%s isLang: '%s'" % (debug_pretext, isLang))

#====================================================================================================================
# Regular expression patterns
#====================================================================================================================
"""
			<tr>
				<td class="lista"><a href="index.php?page=torrent-details&id=0b6431c18917842465b658c2d429cb9f50f9becc" title="My Life in the Air (2008) Ma vie en l'air">My Life in the Air (2008) Ma vie en l'air</a></td>
				<td class="lista"><a href="index.php?page=userdetails&id=94803"><span style='color: #333333'>Sammahel</span></a></td>
				<td class="lista"><img src="images/flag/gb.png" alt="English" /> <a href="download-subtitle.php?subid=3321">English</a></td>
				<td class="lista"><a href="download-subtitle.php?subid=3321"><img src="images/download.gif" border="0" /></a></td>
				<td class="lista"></td>
				<td class="lista">94.93 KB</td>
				<td class="lista">39</td>
Пример #15
0
def get_api_language():
    lang = xbmcaddon.Addon().getSetting('pref_language')
    if lang == "system": lang = xbmc.getLanguage(xbmc.ISO_639_1)
    else: lang = xbmcaddon.Addon().getSetting('pref_language')
    return lang
Пример #16
0
def getAppsWithIcons(additionalDir=""):
    result = {}
    allApps = {}
    language = xbmc.getLanguage(xbmc.ISO_639_1)
    defaultDirs = ["/usr/share/applications/", "~/.local/share/applications/"]
    ignoreCategories = ["GNOME", "GTK"]
    if additionalDir and additionalDir[-1:] != "/":
        additionalDir += "/"
    if additionalDir:
        defaultDirs.append(additionalDir)
    for appDir in defaultDirs:
        if os.path.isdir(appDir):
            for file in sorted(os.listdir(appDir)):
                if file.endswith(".desktop"):
                    entry = {}
                    desktopEntry = False
                    sideCalls = []
                    sideCall = {}
                    entry[Constants.SIDECALLS] = sideCalls
                    entry[Constants.TYPE] = Constants.TYPE_APP
                    for line in open(appDir + os.sep + file):

                        if line.startswith("[Desktop Entry"):
                            #main entry entrance
                            desktopEntry = True
                        if line.startswith("[Desktop Action"):
                            sideCall = {}
                            desktopEntry = False
                            sideCalls.append(sideCall)
                        if line.startswith("Exec"):
                            tempExec = line.split("=")[1][:-1]
                            if "%" in tempExec:
                                tempExec = tempExec[:tempExec.find("%")]
                                tempExecSplit = tempExec.split(" ")
                            if desktopEntry:
                                entry[Constants.ARGS] = tempExecSplit[1:]
                                entry[Constants.EXEC] = tempExecSplit[0]
                                entry[Constants.EXEC] = getFullExecPath(
                                    entry[Constants.EXEC])
                            else:
                                sideCall[Constants.ARGS] = tempExecSplit[1:]
                                sideCall[Constants.EXEC] = tempExecSplit[0]
                                sideCall[Constants.EXEC] = getFullExecPath(
                                    entry[Constants.EXEC])
                        elif line.startswith("Name="):
                            if desktopEntry:
                                if Constants.NAME not in entry:
                                    entry[Constants.NAME] = line.split(
                                        "=")[1][:-1]
                            else:
                                if Constants.NAME not in sideCall:
                                    sideCall[Constants.NAME] = line.split(
                                        "=")[1][:-1]
                        elif line.startswith("Name[" + language + "]"):
                            if desktopEntry:
                                entry[Constants.NAME] = line.split("=")[1][:-1]
                            else:
                                sideCall[Constants.NAME] = line.split(
                                    "=")[1][:-1]
                        elif line.startswith("Icon"):
                            if desktopEntry:
                                entry[Constants.ICON] = line.split("=")[1][:-1]
                            else:
                                sideCall[Constants.ICON] = line.split(
                                    "=")[1][:-1]
                        elif line.startswith("Categories"):
                            categories = line.split("=")[1][:-1].split(";")
                    if Constants.ICON in entry:
                        icon = getBestIcon(entry[Constants.ICON])
                        if icon and icon[-4:] == ".svg":
                            icon = svg2png(icon)
                        entry[Constants.ICON] = icon
                    if entry[Constants.SIDECALLS]:
                        for sideCall in entry[Constants.SIDECALLS]:
                            if Constants.ICON in sideCall:
                                sideCall[Constants.ICON] = getBestIcon(
                                    sideCall[Constants.ICON])
                    allApps[entry[Constants.NAME]] = entry
                    if categories:
                        i = 0
                        for category in categories:
                            if category and category not in ignoreCategories and category[:
                                                                                          8] != "X-GNOME-" and category[:
                                                                                                                        8] != "X-Unity-":
                                addItemToFolder(entry, category, result)
                                i = i + 1
                                if i >= MAX_FOLDER_DEPTH:
                                    break
    addFolder(allApps, Constants.ALL_APPS_FOLDER, result)
    return result
Пример #17
0
def search(payload, method="general"):
    """ Main search entrypoint

    Args:
        payload (dict): Search payload from Elementum.
        method   (str): Type of search, can be ``general``, ``movie``, ``show``, ``season`` or ``anime``

    Returns:
        list: All filtered results in the format Elementum expects
    """
    log.debug("Searching with payload (%s): %s" % (method, repr(payload)))

    if method == 'general':
        if 'query' in payload:
            payload['title'] = payload['query']
            payload['titles'] = {'source': payload['query']}
        else:
            payload = {
                'title': payload,
                'titles': {
                    'source': payload
                },
            }

    payload['titles'] = dict(
        (k.lower(), v) for k, v in payload['titles'].iteritems())

    # If titles[] exists in payload and there are special chars in titles[source]
    #   then we set a flag to possibly modify the search query
    payload['has_special'] = 'titles' in payload and \
                             bool(payload['titles']) and \
                             'source' in payload['titles'] and \
                             any(c in payload['titles']['source'] for c in special_chars)
    if payload['has_special']:
        log.debug(
            "Query title contains special chars, so removing any quotes in the search query"
        )

    if 'proxy_url' not in payload:
        payload['proxy_url'] = ''
    if 'internal_proxy_url' not in payload:
        payload['internal_proxy_url'] = ''
    if 'elementum_url' not in payload:
        payload['elementum_url'] = ''
    if 'silent' not in payload:
        payload['silent'] = False
    if 'skip_auth' not in payload:
        payload['skip_auth'] = False

    global request_time
    global provider_names
    global provider_results
    global available_providers

    provider_names = []
    provider_results = []
    available_providers = 0
    request_time = time.time()

    providers = get_enabled_providers(method)

    if len(providers) == 0:
        if not payload['silent']:
            notify(translation(32060), image=get_icon_path())
        log.error("No providers enabled")
        return []

    log.info(
        "Burstin' with %s" %
        ", ".join([definitions[provider]['name'] for provider in providers]))

    if get_setting('kodi_language', bool):
        kodi_language = xbmc.getLanguage(xbmc.ISO_639_1)
        if not kodi_language:
            log.warning("Kodi returned empty language code...")
        elif 'titles' not in payload or not payload['titles']:
            log.info("No translations available...")
        elif payload['titles'] and kodi_language not in payload['titles']:
            log.info("No '%s' translation available..." % kodi_language)

    p_dialog = xbmcgui.DialogProgressBG()
    if not payload['silent']:
        p_dialog.create('Elementum [COLOR FFFF6B00]Burst[/COLOR]',
                        translation(32061))

    for provider in providers:
        available_providers += 1
        provider_names.append(definitions[provider]['name'])
        task = Thread(target=run_provider, args=(provider, payload, method))
        task.start()

    providers_time = time.time()
    total = float(available_providers)

    # Exit if all providers have returned results or timeout reached, check every 100ms
    while time.time() - providers_time < timeout and available_providers > 0:
        timer = time.time() - providers_time
        log.debug("Timer: %ds / %ds" % (timer, timeout))
        if timer > timeout:
            break
        message = translation(
            32062
        ) % available_providers if available_providers > 1 else translation(
            32063)
        if not payload['silent']:
            p_dialog.update(int((total - available_providers) / total * 100),
                            message=message)
        time.sleep(0.25)

    if not payload['silent']:
        p_dialog.close()
    del p_dialog

    if available_providers > 0:
        message = u', '.join(provider_names)
        message = message + translation(32064)
        log.warning(message.encode('utf-8'))
        if not payload['silent']:
            notify(message, ADDON_ICON)

    log.debug("all provider_results: %s" % repr(provider_results))

    filtered_results = apply_filters(provider_results)

    log.debug("all filtered_results: %s" % repr(filtered_results))

    log.info("Providers returned %d results in %s seconds" %
             (len(filtered_results), round(time.time() - request_time, 2)))

    return filtered_results
Пример #18
0
import urllib.parse
import xbmc
import xbmcaddon
import xbmcgui
import xbmcplugin
import xbmcvfs

addon = xbmcaddon.Addon()
addon_id = addon.getAddonInfo("id")
addon_base = "plugin://" + addon_id
addon_profile_path = xbmcvfs.translatePath(addon.getAddonInfo("profile"))
vfs = VFS(addon_profile_path)
vfs_cache = VFS(os.path.join(addon_profile_path, "cache"))
settings = Settings(addon)
cache = Cache(settings, vfs_cache)
api = ApiV2(settings, xbmc.getLanguage(xbmc.ISO_639_1), cache)
search_history = SearchHistory(settings, vfs)
listItems = Items(addon, addon_base, search_history)


def run():
    url = urllib.parse.urlparse(sys.argv[0])
    path = url.path
    handle = int(sys.argv[1])
    args = urllib.parse.parse_qs(sys.argv[2][1:])
    xbmcplugin.setContent(handle, "songs")

    if path == PATH_ROOT:
        action = args.get("action", None)
        if action is None:
            items = listItems.root()
Пример #19
0
 def gui_language(self):
     language = xbmc.getLanguage().split(' (')[0]
     return xbmc.convertLanguage(language, xbmc.ISO_639_1)
sourcescachedUrl = os.path.join(dataPath, 'sourcesurl.db')

cachemetaFile = os.path.join(dataPath, 'metacache.db')

libcacheFile = os.path.join(dataPath, 'library.db')

metacacheFile = os.path.join(dataPath, 'meta.db')

cacheFile = os.path.join(dataPath, 'cache.db')

cookieDir = os.path.join(dataPath, 'Cookies')

progressDialogBG = xbmcgui.DialogProgressBG()

info_lang = xbmc.getLanguage(xbmc.ISO_639_1)

try:
    makeFile(cookieDir)
except:
    pass


def addonIcon():
    appearance = setting('appearance').lower()
    if appearance in ['-', '']: return addonInfo('icon')
    else:
        return os.path.join(addonPathMedia, 'resources', 'media', appearance,
                            'icon.png')

Пример #21
0
# Percent of playback progress for watching item as partially watched. Anything
# more and item will NOT be marked as partially, but fully watched
MARK_PLAYED_AT = 0.9
# How many seconds of playback do we ignore before marking an item as partially
# watched?
IGNORE_SECONDS_AT_START = 60

_ADDON = Addon()
ADDON_NAME = 'PlexKodiConnect'
ADDON_ID = 'plugin.video.plexkodiconnect'
ADDON_VERSION = _ADDON.getAddonInfo('version')
ADDON_PATH = try_decode(_ADDON.getAddonInfo('path'))
ADDON_FOLDER = try_decode(xbmc.translatePath('special://home'))
ADDON_PROFILE = try_decode(xbmc.translatePath(_ADDON.getAddonInfo('profile')))

KODILANGUAGE = xbmc.getLanguage(xbmc.ISO_639_1)
KODIVERSION = int(xbmc.getInfoLabel("System.BuildVersion")[:2])
KODILONGVERSION = xbmc.getInfoLabel('System.BuildVersion')
KODI_PROFILE = try_decode(xbmc.translatePath("special://profile"))

if xbmc.getCondVisibility('system.platform.osx'):
    DEVICE = "MacOSX"
elif xbmc.getCondVisibility("system.platform.uwp"):
    DEVICE = "Microsoft UWP"
elif xbmc.getCondVisibility('system.platform.atv2'):
    DEVICE = "AppleTV2"
elif xbmc.getCondVisibility('system.platform.ios'):
    DEVICE = "iOS"
elif xbmc.getCondVisibility('system.platform.windows'):
    DEVICE = "Windows"
elif xbmc.getCondVisibility('system.platform.raspberrypi'):
Пример #22
0
 def wizard_set_language(self):
     global lang_str
     global lang_new
     try:
         self.oe.dbg_log('oeWindows::wizard_set_language', 'enter_function',
                         0)
         langCodes = {
             "Bulgarian": "resource.language.bg_bg",
             "Czech": "resource.language.cs_cz",
             "German": "resource.language.de_de",
             "English": "resource.language.en_gb",
             "Spanish": "resource.language.es_es",
             "Basque": "resource.language.eu_es",
             "Finnish": "resource.language.fi_fi",
             "French": "resource.language.fr_fr",
             "Hebrew": "resource.language.he_il",
             "Hungarian": "resource.language.hu_hu",
             "Italian": "resource.language.it_it",
             "Lithuanian": "resource.language.lt_lt",
             "Latvian": "resource.language.lv_lv",
             "Norwegian": "resource.language.nb_no",
             "Dutch": "resource.language.nl_nl",
             "Polish": "resource.language.pl_pl",
             "Portuguese (Brazil)": "resource.language.pt_br",
             "Portuguese": "resource.language.pt_pt",
             "Romanian": "resource.language.ro_ro",
             "Russian": "resource.language.ru_ru",
             "Slovak": "resource.language.sk_sk",
             "Swedish": "resource.language.sv_se",
             "Turkish": "resource.language.tr_tr",
             "Ukrainian": "resource.language.uk_ua"
         }
         languagesList = sorted(list(langCodes.keys()))
         cur_lang = xbmc.getLanguage()
         for index, lang in enumerate(languagesList):
             if cur_lang in lang:
                 langIndex = index
                 break
             else:
                 pass
         selLanguage = xbmcDialog.select(self.oe._(32193),
                                         languagesList,
                                         preselect=langIndex)
         if selLanguage >= 0:
             langKey = languagesList[selLanguage]
             lang_new = langCodes[langKey]
             if lang_new == "resource.language.en_gb":
                 self.oe.write_setting("system", "language", "")
             else:
                 self.oe.write_setting("system", "language", str(lang_new))
             lang_str = 'SetGUILanguage(' + str(lang_new) + ')'
             self.getControl(self.wizWinTitle).setLabel(self.oe._(32300))
             self.set_wizard_title(self.oe._(32301))
             self.set_wizard_text(self.oe._(32302))
             self.oe.winOeMain.set_wizard_button_title(self.oe._(32310))
             self.oe.winOeMain.set_wizard_button_1(langKey, self,
                                                   'wizard_set_language')
             self.showButton(1, 32303)
             self.setFocusId(self.buttons[1]['id'])
         self.oe.dbg_log('oeWindows::wizard_set_language', 'exit_function',
                         0)
     except Exception as e:
         self.oe.dbg_log('oeWindows::wizard_set_language',
                         'ERROR: (' + repr(e) + ')')
Пример #23
0
    def makeFile(path):
        try:
            file = open(path, 'a+')
            file.close()
        except:
            pass


youtube_url = 'plugin://plugin.video.youtube/play/?video_id=%s'

kodiGui = xbmcgui

kodi = xbmc

language = xbmc.getLanguage()

dialogWindow = kodiGui.WindowDialog

addon = xbmcaddon.Addon

progressDialog = xbmcgui.DialogProgress()

bgProgressDialog = xbmcgui.DialogProgressBG

showDialog = xbmcgui.Dialog()

showBusyDialog = xbmcgui.DialogBusy

endDirectory = xbmcplugin.endOfDirectory
Пример #24
0
def plugin_process_info(playdata):
    info = {
        'label1': '',
        'label2': '',
        'description': '',
        'image': '',
        'image_large': '',
        'duration': 0,
        'credits': [],
        'cast': [],
        'director': [],
        'writer': [],
        'genres': [],
        'year': '',
    }

    if check_key(playdata, 'info'):
        if check_key(playdata['info'], 'latestBroadcastEndTime') and check_key(playdata['info'], 'latestBroadcastStartTime'):
            startsplit = int(playdata['info']['latestBroadcastStartTime']) // 1000
            endsplit = int(playdata['info']['latestBroadcastEndTime']) // 1000
            duration = endsplit - startsplit

            startT = datetime.datetime.fromtimestamp(startsplit)
            startT = convert_datetime_timezone(startT, "UTC", "UTC")
            endT = datetime.datetime.fromtimestamp(endsplit)
            endT = convert_datetime_timezone(endT, "UTC", "UTC")

            if xbmc.getLanguage(xbmc.ISO_639_1) == 'nl':
                info['label1'] = '{weekday} {day} {month} {yearhourminute} '.format(weekday=date_to_nl_dag(startT), day=startT.strftime("%d"), month=date_to_nl_maand(startT), yearhourminute=startT.strftime("%Y %H:%M"))
            else:
                info['label1'] = startT.strftime("%A %d %B %Y %H:%M ").capitalize()

        if playdata['title']:
            info['label1'] += playdata['title'] + ' - ' + playdata['info']['title']
        else:
            info['label1'] += playdata['info']['title']

        if check_key(playdata['info'], 'duration'):
            info['duration'] = int(playdata['info']['duration'])
        elif check_key(playdata['info'], 'latestBroadcastStartTime') and check_key(playdata['info'], 'latestBroadcastEndTime'):
            info['duration'] = int(int(playdata['info']['latestBroadcastEndTime']) - int(playdata['info']['latestBroadcastStartTime'])) // 1000

        if check_key(playdata['info'], 'description'):
            info['description'] = playdata['info']['description']

        if check_key(playdata['info'], 'duration'):
            info['duration'] = int(playdata['info']['duration'])

        if check_key(playdata['info'], 'year'):
            info['year'] = int(playdata['info']['year'])

        if check_key(playdata['info'], 'images'):
            info['image'] = get_image("boxart", playdata['info']['images'])
            info['image_large'] = get_image("HighResLandscape", playdata['info']['images'])

            if info['image_large'] == '':
                info['image_large'] = info['image']
            else:
                info['image_large'] += '?w=1920&mode=box'

        if check_key(playdata['info'], 'categories'):
            for categoryrow in playdata['info']['categories']:
                info['genres'].append(categoryrow['title'])

        if check_key(playdata['info'], 'cast'):
            for castrow in playdata['info']['cast']:
                info['cast'].append(castrow)

        if check_key(playdata['info'], 'directors'):
            for directorrow in playdata['info']['directors']:
                info['director'].append(directorrow)

        epcode = ''

        if check_key(playdata['info'], 'seriesNumber'):
            epcode += 'S' + unicode(playdata['info']['seriesNumber'])

        if check_key(playdata['info'], 'seriesEpisodeNumber'):
            epcode += 'E' + unicode(playdata['info']['seriesEpisodeNumber'])

        if check_key(playdata['info'], 'secondaryTitle'):
            info['label2'] = playdata['info']['secondaryTitle']

            if len(epcode) > 0:
                info['label2'] += " (" + epcode + ")"
        else:
            info['label2'] = playdata['info']['title']

        data = api_get_channels()

        try:
            info['label2'] += " - "  + data[unicode(playdata['channel'])]['name']
        except:
            pass

    return info
Пример #25
0
ADDON_NAME = addon.getAddonInfo('name')
VERSION = addon.getAddonInfo('version')
ROOT_PATH = addon.getAddonInfo('path').decode('utf-8')
DATA_PATH = addon.getAddonInfo('profile').decode('utf-8')
ARTWORK = ROOT_PATH + '/resources/artwork/'
SHARED_ARTWORK = vfs.join(
    "special://home",
    "addons/script.module.dudehere.routines/resources/artwork/")

ALLOWED_CALLERS = [
    'plugin.video.theroyalwe', 'plugin.video.ugottoo', 'plugin.video.redbeard',
    'service.walter.sobchak'
]

try:
    KODI_LANGUAGE = xbmc.getLanguage().capitalize()
except:
    KODI_LANGUAGE = 'English'
LANGUAGE_PATH = VFSClass().join(ROOT_PATH,
                                'resources/language/' + KODI_LANGUAGE)


def i18n(id):
    return addon.getLocalizedString(id).encode('utf-8', 'ignore')


QUALITY = enum(LOCAL=9,
               HD1080=8,
               HD720=7,
               HD=6,
               HIGH=5,
Пример #26
0
def plugin_process_watchlist_listing(data, id=None):
    items = []

    if check_key(data, 'listings'):
        for row in data['listings']:
            context = []

            if not check_key(row, 'program'):
                continue

            currow = row['program']

            if not check_key(currow, 'title') or not check_key(row, 'id'):
                continue

            duration = 0

            if check_key(row, 'endTime') and check_key(row, 'startTime'):
                startsplit = int(row['startTime']) // 1000
                endsplit = int(row['endTime']) // 1000
                duration = endsplit - startsplit

                startT = datetime.datetime.fromtimestamp(startsplit)
                startT = convert_datetime_timezone(startT, "UTC", "UTC")
                endT = datetime.datetime.fromtimestamp(endsplit)
                endT = convert_datetime_timezone(endT, "UTC", "UTC")

                if endT < (datetime.datetime.now(pytz.timezone("UTC")) - datetime.timedelta(days=7)):
                    continue

                if xbmc.getLanguage(xbmc.ISO_639_1) == 'nl':
                    label = '{weekday} {day} {month} {yearhourminute} '.format(weekday=date_to_nl_dag(startT), day=startT.strftime("%d"), month=date_to_nl_maand(startT), yearhourminute=startT.strftime("%Y %H:%M"))
                else:
                    label = startT.strftime("%A %d %B %Y %H:%M ").capitalize()

                label += currow['title']
            else:
                label = currow['title']

            data2 = api_get_channels()

            try:
                label += ' ({station})'.format(station=data2[unicode(currow['stationId'])]['name'])
            except:
                pass

            if id:
                context.append((_.ADD_TO_WATCHLIST, 'RunPlugin({context_url})'.format(context_url=plugin.url_for(func_or_url=add_to_watchlist, id=id, type="group")), ))

            channel = ''
            description = ''
            program_image = ''
            program_image_large = ''

            if check_key(currow, 'description'):
                description = currow['description']

            if check_key(currow, 'duration'):
                duration = int(currow['duration'])

            if check_key(currow, 'images'):
                program_image = get_image("boxart", currow['images'])
                program_image_large = get_image("HighResLandscape", currow['images'])

                if program_image_large == '':
                    program_image_large = program_image
                else:
                    program_image_large += '?w=1920&mode=box'

            items.append(plugin.Item(
                label = label,
                info = {
                    'plot': description,
                    'duration': duration,
                    'mediatype': 'video',
                    'sorttitle': label.upper(),
                },
                art = {
                    'thumb': program_image,
                    'fanart': program_image_large
                },
                path = plugin.url_for(func_or_url=play_video, type="program", channel=channel, id=row['id']),
                playable = True,
                context = context
            ))

    return items
Пример #27
0
def api_vod_season(series, id):
    if not api_get_session():
        return None

    season = []

    profile_settings = load_profile(profile_id=1)

    season_url = '{mediaitems_url}?byMediaType=Episode%7CFeatureFilm&byParentId={id}&includeAdult=true&range=1-1000&sort=seriesEpisodeNumber|ASC'.format(
        mediaitems_url=CONST_API_URLS[int(
            profile_settings['v3'])]['mediaitems_url'],
        id=id)
    download = api_download(url=season_url,
                            type='get',
                            headers=None,
                            data=None,
                            json_data=False,
                            return_json=True)
    data = download['data']
    code = download['code']

    if not data or not check_key(data, 'mediaItems'):
        return None

    if sys.version_info >= (3, 0):
        data['mediaItems'] = list(data['mediaItems'])

    for row in data['mediaItems']:
        desc = ''
        image = ''
        label = ''

        if not check_key(row, 'title') or not check_key(row, 'id'):
            continue

        if check_key(row, 'description'):
            desc = row['description']

        if check_key(row, 'duration'):
            duration = int(row['duration'])

        if check_key(row, 'images'):
            program_image = get_image("boxart", row['images'])
            image = get_image("HighResLandscape", row['images'])

            if image == '':
                image = program_image
            else:
                image += '?w=1920&mode=box'

        if check_key(row, 'earliestBroadcastStartTime'):
            startsplit = int(row['earliestBroadcastStartTime']) // 1000

            startT = datetime.datetime.fromtimestamp(startsplit)
            startT = convert_datetime_timezone(startT, "UTC", "UTC")

            if xbmc.getLanguage(xbmc.ISO_639_1) == 'nl':
                label = date_to_nl_dag(startT) + startT.strftime(
                    " %d ") + date_to_nl_maand(startT) + startT.strftime(
                        " %Y %H:%M ") + row['title']
            else:
                label = (startT.strftime("%A %d %B %Y %H:%M ") +
                         row['title']).capitalize()
        else:
            label = row['title']

        season.append({
            'label': label,
            'id': row['id'],
            'start': '',
            'duration': duration,
            'title': row['title'],
            'seasonNumber': '',
            'episodeNumber': '',
            'description': desc,
            'image': image
        })

    return season
Пример #28
0
api_base_url = 'https://meduza.carnet.hr/index.php/api/'
category_image_base_url = 'https://meduza.carnet.hr/uploads/images/categories/'
# api_key == device_id from register (import) device == uid
api_key = addon.getSetting('apikey')

mode = args.get('mode', None)

dir_recommends = addon.getLocalizedString(30201)
dir_categories = addon.getLocalizedString(30202)
dir_channels = addon.getLocalizedString(30203)
dir_search = addon.getLocalizedString(30204)
dir_settings = addon.getLocalizedString(30205)

# get api lang property (en|hr)
active_lang = xbmc.getLanguage()
if active_lang == 'Croatian':
    lang_api_prop = 'naziv'
else:
    lang_api_prop = 'naziv_en'

#category level listitems
if mode is None:
    url = build_url({'mode': 'folder', 'foldername': dir_recommends})
    li = xbmcgui.ListItem(dir_recommends)
    li.setArt({'icon': 'DefaultVideo.png'})
    xbmcplugin.addDirectoryItem(handle=addon_handle,
                                url=url,
                                listitem=li,
                                isFolder=True)
Пример #29
0
    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
"""
import __builtin__

import resources.lib.external.tvdb_api as tvdb_api
import xbmc
import xbmcaddon
from language import get_string as _
from resources.lib.plugin import run_hook
from resources.lib.util.url import get_addon_url

ADDON = xbmcaddon.Addon()
if ADDON.getSetting("language_id") == "system":
    LANG = xbmc.getLanguage(xbmc.ISO_639_1)
else:
    LANG = ADDON.getSetting("language_id")

tvdb = tvdb_api.Tvdb(__builtin__.tvdb_api_key,
                     language=LANG,
                     cache=xbmc.translatePath(ADDON.getAddonInfo("profile")))


def get_context_items(item):
    """generate context menu for item
    Keyword Arguments:
    item -- JenItem to generate menu for
    """
    context = []
    content = item["content"]
Пример #30
0
def process(provider,
            generator,
            filtering,
            verify_name=True,
            verify_size=True):
    """ Method for processing provider results using its generator and Filtering class instance

    Args:
        provider        (str): Provider ID
        generator  (function): Generator method, can be either ``extract_torrents`` or ``extract_from_api``
        filtering (Filtering): Filtering class instance
        verify_name    (bool): Whether to double-check the results' names match the query or not
        verify_size    (bool): Whether to check the results' file sizes
    """
    log.debug("execute_process for %s with %s" % (provider, repr(generator)))
    definition = definitions[provider]

    client = Client()
    token = None
    logged_in = False
    token_auth = False

    if get_setting("use_cloudhole", bool):
        client.clearance = get_setting('clearance')
        client.user_agent = get_setting('user_agent')

    if get_setting('kodi_language', bool):
        kodi_language = xbmc.getLanguage(xbmc.ISO_639_1)
        if kodi_language:
            filtering.kodi_language = kodi_language
        language_exceptions = get_setting('language_exceptions')
        if language_exceptions.strip().lower():
            filtering.language_exceptions = re.split(r',\s?',
                                                     language_exceptions)

    log.debug("[%s] Queries: %s" % (provider, filtering.queries))
    log.debug("[%s] Extras:  %s" % (provider, filtering.extras))

    for query, extra in zip(filtering.queries, filtering.extras):
        log.debug("[%s] Before keywords - Query: %s - Extra: %s" %
                  (provider, repr(query), repr(extra)))
        query = filtering.process_keywords(provider, query)
        extra = filtering.process_keywords(provider, extra)
        log.debug("[%s] After keywords  - Query: %s - Extra: %s" %
                  (provider, repr(query), repr(extra)))
        if not query:
            return filtering.results

        url_search = filtering.url.replace('QUERY', query)
        if extra:
            url_search = url_search.replace('EXTRA', extra)
        else:
            url_search = url_search.replace('EXTRA', '')
        url_search = url_search.replace(' ', definition['separator'])

        # MagnetDL fix...
        url_search = url_search.replace('FIRSTLETTER', query[:1])

        # Creating the payload for POST method
        payload = dict()
        for key, value in filtering.post_data.iteritems():
            if 'QUERY' in value:
                payload[key] = filtering.post_data[key].replace('QUERY', query)
            else:
                payload[key] = filtering.post_data[key]

        # Creating the payload for GET method
        data = None
        if filtering.get_data:
            data = dict()
            for key, value in filtering.get_data.iteritems():
                if 'QUERY' in value:
                    data[key] = filtering.get_data[key].replace('QUERY', query)
                else:
                    data[key] = filtering.get_data[key]

        log.debug("-   %s query: %s" % (provider, repr(query)))
        log.debug("--  %s url_search before token: %s" %
                  (provider, repr(url_search)))
        log.debug("--- %s using POST payload: %s" % (provider, repr(payload)))
        log.debug("----%s filtering with post_data: %s" %
                  (provider, repr(filtering.post_data)))

        # Set search's "title" in filtering to double-check results' names
        if 'filter_title' in definition and definition['filter_title']:
            filtering.filter_title = True
            filtering.title = query

        if token:
            log.info('[%s] Reusing existing token' % provider)
            url_search = url_search.replace('TOKEN', token)
        elif 'token' in definition:
            token_url = definition['base_url'] + definition['token']
            log.debug("Getting token for %s at %s" %
                      (provider, repr(token_url)))
            client.open(token_url.encode('utf-8'))
            try:
                token_data = json.loads(client.content)
            except:
                log.error('%s: Failed to get token for %s' %
                          (provider, repr(url_search)))
                return filtering.results
            log.debug("Token response for %s: %s" %
                      (provider, repr(token_data)))
            if 'token' in token_data:
                token = token_data['token']
                log.debug("Got token for %s: %s" % (provider, repr(token)))
                url_search = url_search.replace('TOKEN', token)
                time.sleep(2)
            else:
                log.warning('%s: Unable to get token for %s' %
                            (provider, repr(url_search)))

        if logged_in:
            log.info("[%s] Reusing previous login" % provider)
        elif token_auth:
            log.info("[%s] Reusing previous token authorization" % provider)
        elif 'private' in definition and definition['private']:
            username = get_setting('%s_username' % provider)
            password = get_setting('%s_password' % provider)
            passkey = get_setting('%s_passkey' % provider)
            if not username and not password and not passkey:
                for addon_name in ('script.magnetic.%s' % provider,
                                   'script.magnetic.%s-mc' % provider):
                    for setting in ('username', 'password'):
                        try:
                            value = xbmcaddon.Addon(addon_name).getSetting(
                                setting)
                            set_setting('%s_%s' % (provider, setting), value)
                            if setting == 'username':
                                username = value
                            if setting == 'password':
                                password = value
                        except:
                            pass

            if passkey:
                logged_in = True
                client.passkey = passkey
                url_search = url_search.replace('PASSKEY', passkey)

            elif 'login_object' in definition and definition['login_object']:
                logged_in = False
                login_object = definition['login_object'].replace(
                    'USERNAME',
                    '"%s"' % username).replace('PASSWORD', '"%s"' % password)

                # TODO generic flags in definitions for those...
                if provider == 'alphareign':
                    client.open(definition['root_url'] +
                                definition['login_path'])
                    if client.content:
                        csrf_name = re.search(
                            r'name="csrf_name" value="(.*?)"', client.content)
                        csrf_value = re.search(
                            r'name="csrf_value" value="(.*?)"', client.content)
                        if csrf_name and csrf_value:
                            login_object = login_object.replace(
                                "CSRF_NAME", '"%s"' % csrf_name.group(1))
                            login_object = login_object.replace(
                                "CSRF_VALUE", '"%s"' % csrf_value.group(1))
                        else:
                            logged_in = True
                if provider == 'hd-torrents':
                    client.open(definition['root_url'] +
                                definition['login_path'])
                    if client.content:
                        csrf_token = re.search(
                            r'name="csrfToken" value="(.*?)"', client.content)
                        if csrf_token:
                            login_object = login_object.replace(
                                'CSRF_TOKEN', '"%s"' % csrf_token.group(1))
                        else:
                            logged_in = True

                if 'token_auth' in definition:
                    # log.debug("[%s] logging in with: %s" % (provider, login_object))
                    if client.open(definition['root_url'] +
                                   definition['token_auth'],
                                   post_data=eval(login_object)):
                        try:
                            token_data = json.loads(client.content)
                        except:
                            log.error('%s: Failed to get token from %s' %
                                      (provider, definition['token_auth']))
                            return filtering.results
                        log.debug("Token response for %s: %s" %
                                  (provider, repr(token_data)))
                        if 'token' in token_data:
                            client.token = token_data['token']
                            log.debug("Auth token for %s: %s" %
                                      (provider, repr(client.token)))
                        else:
                            log.error('%s: Unable to get auth token for %s' %
                                      (provider, repr(url_search)))
                            return filtering.results
                        log.info('[%s] Token auth successful' % provider)
                        token_auth = True
                    else:
                        log.error("[%s] Token auth failed with response: %s" %
                                  (provider, repr(client.content)))
                        return filtering.results
                elif not logged_in and client.login(
                        definition['root_url'] + definition['login_path'],
                        eval(login_object), definition['login_failed']):
                    log.info('[%s] Login successful' % provider)
                    logged_in = True
                elif not logged_in:
                    log.error("[%s] Login failed: %s", provider, client.status)
                    log.debug("[%s] Failed login content: %s", provider,
                              repr(client.content))
                    return filtering.results

                if logged_in:
                    if provider == 'hd-torrents':
                        client.open(definition['root_url'] + '/torrents.php')
                        csrf_token = re.search(
                            r'name="csrfToken" value="(.*?)"', client.content)
                        url_search = url_search.replace(
                            "CSRF_TOKEN", csrf_token.group(1))

        log.info(">  %s search URL: %s" %
                 (definition['name'].rjust(longest), url_search))

        client.open(url_search.encode('utf-8'),
                    post_data=payload,
                    get_data=data)
        filtering.results.extend(
            generate_payload(provider, generator(provider, client), filtering,
                             verify_name, verify_size))
    return filtering.results