Exemplo n.º 1
0
def addTorrent(parameters, remove=False, all=False):
    refreshToken()
    
    if "torrent_file" not in parameters:
        dialog = xbmcgui.Dialog()
        link = dialog.browseSingle(1, 'Select .torrent file', 'files', '.torrent', False, False, 'special://masterprofile/script_data/Kodi Lyrics').decode('utf-8')
    else:
        link=parameters['torrent_file']
    file=open(link, 'rb')
    
    cont=8
    while cont==8:
        headers={"Authorization": "Bearer "+str(xbmcaddon.Addon().getSetting('rd_access'))}
        
        r = requests.put("https://api.real-debrid.com/rest/1.0/torrents/addTorrent", data=file, headers=headers)
        content=json.loads(r.text)
        
        cont=isError(content)
            
    file.close()
    try:
        if remove:
            os.remove(link)
    except:
        util.logError("Unable to remove file '"+link+"'")
    if cont:
        return False
    else:
        return torrentSelect(content['id'], all)
Exemplo n.º 2
0
def refreshToken():
    cj_rd = cookielib.CookieJar()
    opener_rd = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj_rd))
    data_rd = urllib.urlencode({
        'client_id':
        xbmcaddon.Addon().getSetting('rd_id'),
        'client_secret':
        xbmcaddon.Addon().getSetting('rd_secret'),
        'code':
        xbmcaddon.Addon().getSetting('rd_refresh'),
        'grant_type':
        'http://oauth.net/grant_type/device/1.0'
    })

    try:
        resp = opener_rd.open('https://api.real-debrid.com/oauth/v2/token',
                              data_rd)
        content = resp.read()

        credJSON = json.loads(content)

        xbmcaddon.Addon().setSetting('rd_access', credJSON['access_token'])
        xbmcaddon.Addon().setSetting('rd_refresh', credJSON['refresh_token'])

        #util.logError("write complete: "+str(credJSON))
        #util.logError("checking values"+xbmcaddon.Addon().getSetting('rd_access')+" "+xbmcaddon.Addon().getSetting('rd_refresh'))

        authorised = True
    except Exception as e:
        util.logError("Error Refreshing Token: " + str(e))
Exemplo n.º 3
0
def torrentsInfo(id):
    if "False" not in id[1]:
        try:
            refreshToken()
            cj_rd = cookielib.CookieJar()
            opener_rd = urllib2.build_opener(
                urllib2.HTTPCookieProcessor(cj_rd))

            cont = 8
            while cont == 8:
                opener_rd.addheaders = [("Authorization", "Bearer " + str(
                    xbmcaddon.Addon('script.realdebrid.mod').getSetting(
                        'rd_access')))]
                resp = opener_rd.open(
                    "https://api.real-debrid.com/rest/1.0/torrents/info/" +
                    str(id))
                content = json.loads(resp.read())

                cont = isError(content)

            if cont:
                return False
            else:
                return content
        except urllib2.HTTPError as err:
            if err.code == 404:
                util.logError(str(err))
                return False
    return False
Exemplo n.º 4
0
def initDb():
    """open the db, create or update it if needed.
    Returns a dbHandle."""
    dbhandle = QSqlDatabase("QSQLITE")
    if InternalParameters.isServer:
        name = 'kajonggserver.db'
    else:
        name = 'kajongg.db'
    dbpath = InternalParameters.dbPath or appdataDir() + name
    dbhandle.setDatabaseName(dbpath)
    dbExisted = os.path.exists(dbpath)
    if Debug.sql:
        logDebug('%s database %s' % \
            ('using' if dbExisted else 'creating', dbpath))
    # timeout in msec:
    dbhandle.setConnectOptions("QSQLITE_BUSY_TIMEOUT=2000")
    if not dbhandle.open():
        logError('%s %s' % (str(dbhandle.lastError().text()), dbpath))
        sys.exit(1)
    with Transaction(dbhandle=dbhandle):
        if not dbExisted:
            Query.createTables(dbhandle)
        else:
            Query.upgradeDb(dbhandle)
    generateDbIdent(dbhandle)
    return dbhandle
Exemplo n.º 5
0
def hostStatus():
    from collections import OrderedDict

    cj_rd = cookielib.CookieJar()
    opener_rd = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj_rd))
    opener_rd.addheaders = [
        ("Authorization",
         "Bearer " + str(xbmcaddon.Addon().getSetting('rd_access')))
    ]

    error = True
    attempts = 0

    while error:
        try:
            resp = opener_rd.open(
                'https://api.real-debrid.com/rest/1.0/hosts/status')
            content = resp.read()

            credJSON = json.loads(content)
            #util.logError(str(credJSON))
            return credJSON
        except Exception as e:
            e = str(e)
            util.logError("hoststaus error: " + e)
            attempts = attempts + 1
            if attempts > 3:
                error = True
                return False
            elif "Unauthorized" in e:
                refreshToken()
Exemplo n.º 6
0
def delID(parameters):
    util.logError(str(parameters))
    refreshToken()
    headers = {
        "Authorization":
        "Bearer " + str(xbmcaddon.Addon().getSetting('rd_access'))
    }

    if parameters['method'] == "torrent":
        if xbmcgui.Dialog().yesno("Delete torrent?",
                                  line1="Do you want to delete the torret",
                                  line3=parameters['name'].encode('utf-8')):
            r = requests.delete(
                "https://api.real-debrid.com/rest/1.0/torrents/delete/" +
                parameters['id'],
                headers=headers)
            try:
                isError(json.loads(r.text))
            except:
                xbmc.executebuiltin('Container.Refresh')
    else:
        if xbmcgui.Dialog().yesno("Delete link?",
                                  line1="Do you want to delete the link",
                                  line3=parameters['name'].encode('utf-8')):
            util.logError(
                "https://api.real-debrid.com/rest/1.0/downloads/delete/" +
                parameters['id'])
            r = requests.delete(
                "https://api.real-debrid.com/rest/1.0/downloads/delete/" +
                parameters['id'],
                headers=headers)
            try:
                isError(json.loads(r.text))
            except:
                xbmc.executebuiltin('Container.Refresh')
Exemplo n.º 7
0
def unrestrict(parameters):
    cj_rd = cookielib.CookieJar()
    opener_rd = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj_rd))
    opener_rd.addheaders=[("Authorization", "Bearer "+str(xbmcaddon.Addon().getSetting('rd_access')))]
    
    if 'url' in parameters:
        link=parameters['url']
    else:
        link=util.searchDialog("Enter link to unrestrict")
        
    if link:
        data_rd = urllib.urlencode({'link' : link})

        error=True
        attempts=0
        while error:
            try:
                resp = opener_rd.open('https://api.real-debrid.com/rest/1.0/unrestrict/link', data_rd)
                content=resp.read()
                
                credJSON=json.loads(content)
                error=True
                return credJSON
            except Exception as e:
                util.logError("realdebrid error: "+str(e))
                attempts=attempts+1
                if attempts>3:
                    error=True
                    break
                elif "Unauthorized" in e:
                    refreshToken()
    return False
Exemplo n.º 8
0
    def __init__(self, game):
        SelectRuleset.__init__(self)
        self.game = game
        Players.load()
        self.setWindowTitle(m18n('Select four players') + ' - Kajongg')
        self.names = None
        self.nameWidgets = []
        for idx, wind in enumerate(WINDS):
            cbName = QComboBox()
            cbName.manualSelect = False
            # increase width, we want to see the full window title
            cbName.setMinimumWidth(350) # is this good for all platforms?
            cbName.addItems(Players.humanNames.values())
            self.grid.addWidget(cbName, idx+1, 1)
            self.nameWidgets.append(cbName)
            self.grid.addWidget(WindLabel(wind), idx+1, 0)
            cbName.currentIndexChanged.connect(self.slotValidate)

        query = Query("select p0,p1,p2,p3 from game where seed is null and game.id = (select max(id) from game)")
        if len(query.records):
            for pidx, playerId in enumerate(query.records[0]):
                try:
                    playerName = Players.humanNames[playerId]
                    cbName = self.nameWidgets[pidx]
                    playerIdx = cbName.findText(playerName)
                    if playerIdx >= 0:
                        cbName.setCurrentIndex(playerIdx)
                except KeyError:
                    logError('database is inconsistent: player with id %d is in game but not in player' \
                               % playerId)
        self.slotValidate()
Exemplo n.º 9
0
def hostStatus():
    from collections import OrderedDict
    
    cj_rd = cookielib.CookieJar()
    opener_rd = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj_rd))
    opener_rd.addheaders=[("Authorization", "Bearer "+str(xbmcaddon.Addon().getSetting('rd_access')))]

    error=True
    attempts=0
    
    while error:
        try:
            resp = opener_rd.open('https://api.real-debrid.com/rest/1.0/hosts/status')
            content=resp.read()
            
            credJSON=json.loads(content)
            #util.logError(str(credJSON))
            return credJSON
        except Exception as e:
            e=str(e)
            util.logError("hoststaus error: "+e)
            attempts=attempts+1
            if attempts>3:
                error=True
                return False
            elif "Unauthorized" in e:
                refreshToken()
Exemplo n.º 10
0
    def __init__(self, game):
        SelectRuleset.__init__(self)
        self.game = game
        Players.load()
        self.setWindowTitle(m18n('Select four players') + ' - Kajongg')
        self.names = None
        self.nameWidgets = []
        for idx, wind in enumerate(WINDS):
            cbName = QComboBox()
            cbName.manualSelect = False
            # increase width, we want to see the full window title
            cbName.setMinimumWidth(350)  # is this good for all platforms?
            cbName.addItems(Players.humanNames.values())
            self.grid.addWidget(cbName, idx + 1, 1)
            self.nameWidgets.append(cbName)
            self.grid.addWidget(WindLabel(wind), idx + 1, 0)
            cbName.currentIndexChanged.connect(self.slotValidate)

        query = Query(
            "select p0,p1,p2,p3 from game where seed is null and game.id = (select max(id) from game)"
        )
        if len(query.records):
            for pidx, playerId in enumerate(query.records[0]):
                try:
                    playerName = Players.humanNames[playerId]
                    cbName = self.nameWidgets[pidx]
                    playerIdx = cbName.findText(playerName)
                    if playerIdx >= 0:
                        cbName.setCurrentIndex(playerIdx)
                except KeyError:
                    logError('database is inconsistent: player with id %d is in game but not in player' \
                               % playerId)
        self.slotValidate()
Exemplo n.º 11
0
def unrestrict(parameters):
    cj_rd = cookielib.CookieJar()
    opener_rd = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj_rd))
    opener_rd.addheaders=[("Authorization", "Bearer "+str(xbmcaddon.Addon().getSetting('rd_access')))]
    
    if 'url' in parameters:
        link=parameters['url']
    else:
        link=util.searchDialog("Enter link to unrestrict")
        
    if link:
        data_rd = urllib.urlencode({'link' : link})

        error=True
        attempts=0
        while error:
            try:
                resp = opener_rd.open('https://api.real-debrid.com/rest/1.0/unrestrict/link', data_rd)
                content=resp.read()
                
                credJSON=json.loads(content)
                error=True
                return credJSON
            except Exception as e:
                util.logError("realdebrid error: "+str(e))
                attempts=attempts+1
                if attempts>3:
                    error=True
                    break
                elif "Unauthorized" in e:
                    refreshToken()
    return False
Exemplo n.º 12
0
def addTorrent(parameters, remove=False, all=False):
    refreshToken()
    
    if "torrent_file" not in parameters:
        dialog = xbmcgui.Dialog()
        link = dialog.browseSingle(1, 'Select .torrent file', 'files', '.torrent', False, False, 'special://masterprofile/script_data/Kodi Lyrics').decode('utf-8')
    else:
        link=parameters['torrent_file']
    file=open(link, 'rb')
    
    cont=8
    while cont==8:
        headers={"Authorization": "Bearer "+str(xbmcaddon.Addon().getSetting('rd_access'))}
        
        r = requests.put("https://api.real-debrid.com/rest/1.0/torrents/addTorrent", data=file, headers=headers)
        content=json.loads(r.text)
        
        cont=isError(content)
            
    file.close()
    try:
        if remove:
            os.remove(link)
    except:
        util.logError("Unable to remove file '"+link+"'")
    if cont:
        return False
    else:
        return torrentSelect(content['id'], all)
Exemplo n.º 13
0
	def handleRequestError(self, http):
		if http.code == 0 or http.ResultSuccess(): return
		errorMsg = "An error occurred retrieving data from: %s\n%s" % (http.url, http.GetResponseMsg())
		util.logError(errorMsg)
		if http.ResultConnectFailed():
			raise PlexConnectionFailedError()
		raise PlexRequestError(errorMsg, http.code)
Exemplo n.º 14
0
 def __init__(self, cmdList, args=None, dbHandle=None, silent=False, mayFail=False):
     """we take a list of sql statements. Only the last one is allowed to be
     a select statement.
     Do prepared queries by passing a single query statement in cmdList
     and the parameters in args. If args is a list of lists, execute the
     prepared query for every sublist.
     If dbHandle is passed, use that for db access.
     Else if the default dbHandle (Query.dbhandle) is defined, use it."""
     # pylint: disable=R0912
     # pylint says too many branches
     silent |= not Debug.sql
     self.dbHandle = dbHandle or Query.dbhandle
     assert self.dbHandle
     preparedQuery = not isinstance(cmdList, list) and bool(args)
     self.query = QSqlQuery(self.dbHandle)
     self.msg = None
     self.records = []
     if not isinstance(cmdList, list):
         cmdList = list([cmdList])
     self.cmdList = cmdList
     for cmd in cmdList:
         retryCount = 0
         while retryCount < 100:
             self.lastError = None
             if preparedQuery:
                 self.query.prepare(cmd)
                 if not isinstance(args[0], list):
                     args = list([args])
                 for dataSet in args:
                     if not silent:
                         logDebug('%s %s' % (cmd, dataSet))
                     for value in dataSet:
                         self.query.addBindValue(QVariant(value))
                     self.success = self.query.exec_()
                     if not self.success:
                         break
             else:
                 if not silent:
                     logDebug(cmd)
                 self.success = self.query.exec_(cmd)
             if self.success or self.query.lastError().number() not in (5, 6):
                 # 5: database locked, 6: table locked. Where can we get symbols for this?
                 break
             time.sleep(0.1)
             retryCount += 1
         if not self.success:
             self.lastError = unicode(self.query.lastError().text())
             self.msg = 'ERROR in %s: %s' % (self.dbHandle.databaseName(), self.lastError)
             if mayFail:
                 if not silent:
                     logDebug(self.msg)
             else:
                 logError(self.msg)
             return
     self.records = None
     self.fields = None
     if self.query.isSelect():
         self.retrieveRecords()
Exemplo n.º 15
0
def torrents(parameters):
    refreshToken()
    headers = {
        "Authorization":
        "Bearer " +
        str(xbmcaddon.Addon('script.realdebrid').getSetting('rd_access'))
    }
    extras = ast.literal_eval(parameters['extras'])

    data = {
        "offset": extras['offset'],
        "limit": extras['limit'],
        "filter": "active"
    }

    r = requests.get("https://api.real-debrid.com/rest/1.0/torrents",
                     data=data,
                     headers=headers)

    links = json.loads(r.text)
    #util.logError(str(links))
    menu = []
    for item in links:
        if item['status'] == "downloaded":
            #util.logError(str(torrentsInfo(item['id'])))
            name = item['filename']
            url = item['links'][0]
            mode = 5
        elif item['status'] == "downloading":
            name = "[Downloading " + str(
                item['progress']) + "%] " + item['filename']
            url = ""
            mode = ""
        else:
            name = "[" + item['status'] + "] " + item['filename']
            url = ""
            mode = ""
        util.logError("..>" + name)
        menu.append({
            "title": name,
            "url": url,
            "mode": mode,
            "poster": os.path.join(home, '', 'icon.png'),
            "icon": os.path.join(home, '', 'icon.png'),
            "fanart": os.path.join(home, '', 'fanart.jpg'),
            "type": "video",
            "plot": item['host'],
            "method": "torrent",
            "id": item['id'],
            "isFolder": False,
            "playable": False,
            "download": True
        })

    util.addMenuItems(menu)
Exemplo n.º 16
0
 def showEvent(self, dummyEvent):
     """adapt view to content"""
     if not self.model.select():
         logError("PlayerList: select failed")
         sys.exit(1)
     self.view.initView()
     StateSaver(self, self.view.horizontalHeader())
     if not self.view.isColumnHidden(2):
         # we loaded a kajonggrc written by an older kajongg version where this table
         # still had more columns. This should happen only once.
         self.view.hideColumn(2)
         self.view.hideColumn(3)
Exemplo n.º 17
0
 def showEvent(self, dummyEvent):
     """adapt view to content"""
     if not self.model.select():
         logError("PlayerList: select failed")
         sys.exit(1)
     self.view.initView()
     StateSaver(self, self.view.horizontalHeader())
     if not self.view.isColumnHidden(2):
         # we loaded a kajonggrc written by an older kajongg version where this table
         # still had more columns. This should happen only once.
         self.view.hideColumn(2)
         self.view.hideColumn(3)
Exemplo n.º 18
0
def isError(toCheck):
    try:
        if toCheck['error']:
            if toCheck['error_code']==8:
                # need to refresh token
                refreshToken()
                return 8
            else:
                util.alert("Error "+str(toCheck['error_code'])+": "+string.capwords(toCheck['error'].replace("_", " ")))
                util.logError("Error "+str(toCheck['error_code'])+": "+toCheck['error'])
                return True
    except:
       return False
Exemplo n.º 19
0
def isError(toCheck):
    try:
        if toCheck['error']:
            if toCheck['error_code']==8:
                # need to refresh token
                refreshToken()
                return 8
            else:
                util.alert("Error "+str(toCheck['error_code'])+": "+string.capwords(toCheck['error'].replace("_", " ")))
                util.logError("Error "+str(toCheck['error_code'])+": "+toCheck['error'])
                return True
    except:
       return False
Exemplo n.º 20
0
	def __init__(self, filepath):
		self.__configFile = filepath
		self.__tree = None
		self.__isvalid = False
		self.__lastModified = -1
		try:
			if not fileExists(filepath):
				f = open(filepath, 'w')
				f.write('<registry/>')
				f.close()
				self.__lastModified = os.stat(filepath).st_mtime
			self.__tree = ElementTree.parse(filepath)
			self.__isvalid = True
		except IOError:
			#Error creating file.... permissions problem?
			util.logError("Failed to create settings file at %s" % filepath)
Exemplo n.º 21
0
    def updateMovie(self, movie, httphandler, LANG_MPAA):
        if movie["imdbnumber"] == "":
            util.logWarning("%(label)s: no IMDb id" % movie)
        else:
            mpaa = imdbMpaa(movie["imdbnumber"], httphandler, LANG_MPAA)

            formattedRating = ("%s%s" if ":" in FORM_MPAA else "%s %s") % (FORM_MPAA, mpaa.rating())

            if mpaa.error():
                util.logError("%s: problem with MPAA site" % movie["label"])
            elif movie["mpaa"] != formattedRating:
                util.executeJSON('VideoLibrary.SetMovieDetails', {'movieid':movie['movieid'], 'mpaa':formattedRating})
                util.log("%s: updated from %s to %s" % (movie["label"], movie["mpaa"], formattedRating))
                return 1

        return 0
Exemplo n.º 22
0
def torrents(parameters):
    refreshToken()
    headers={"Authorization": "Bearer "+str(xbmcaddon.Addon().getSetting('rd_access'))}
    extras=ast.literal_eval(parameters['extras'])
    
    data={"offset":extras['offset'], "limit":extras['limit'], "filter": "active"}
    
    
    r = requests.get("https://api.real-debrid.com/rest/1.0/torrents", data=data, headers=headers)
    
    links=json.loads(r.text)
    #util.logError(str(links))
    menu=[]
    for item in links:
        if item['status'] == "downloaded":
            #util.logError(str(torrentsInfo(item['id'])))
            name=item['filename']
            url=item['links'][0]
            mode=5
        elif item['status']== "downloading":
            name="[Downloading "+str(item['progress'])+"%] "+item['filename']
            url=""
            mode=""
        else:
            name="["+item['status']+"] "+item['filename']
            url=""
            mode=""
        util.logError("..>"+name)
        menu.append({
            "title": name,
            "url": url,
            "mode": mode, 
            "poster":os.path.join(home, '', 'icon.png'),
            "icon":os.path.join(home, '', 'icon.png'), 
            "fanart":os.path.join(home, '', 'fanart.jpg'),
            "type":"video", 
            "plot":item['host'],
            "method":"torrent",
            "id":item['id'],
            "isFolder":False,
            "playable":False,
            "download":True
        })
   
    util.addMenuItems(menu)
Exemplo n.º 23
0
	def __getServerAttributes(self):
		#Try unencrypted and no access token first
		http = util.Http()
		data = http.Get("http://%s:%s" % (self.host, self.port))
		code = http.GetHttpResponseCode()
			
		if code == -1:
			#Failed to connect, either site is not available or secured
			#Try ssl
			data = http.Get("https://%s:%s" % (self.host, self.port))
			code = http.GetHttpResponseCode()

			if code != -1:
				#Looks like it's secured
				self.isSecure = True

		self.isTokenRequired = (code == 401)
		if code == 401:
			#Permission denied
			if self.getCurrentAccessToken() is None:
				util.logInfo("User access tokens are required to access this server")
				return
			data = http.Get(self.__getRootUrl())
			code = http.GetHttpResponseCode()
			if code == 401:
				#Still an issue even with a token
				util.logError("User token may not be valid - permission denied when accessing the Plex Server")
				return

		if data:
			try:
				tree = ElementTree.fromstring(data)
				self.friendlyName = tree.attrib.get("friendlyName", None)
				self.isMultiuser = tree.attrib.get("multiuser", False)
				self.machineIdentifier = tree.attrib.get("machineIdentifier", None)
				self.platform = tree.attrib.get("platform", None)
				self.platformVersion = tree.attrib.get("platformVersion", None)
				self.transcoderVideoBitrates = tree.attrib.get("transcoderVideoBitrates", None)
				self.transcoderVideoQualities = tree.attrib.get("transcoderVideoQualities", None)
				self.transcoderVideoResolutions = tree.attrib.get("transcoderVideoResolutions", None)
				self.version = tree.attrib.get("version", None)
			except:
				#Wasn't XML data
				util.logError('Accessed server %s:%s but I was unable to process the reponse. Is the Plex server and port correct?' % (self.host, self.port))
				data = None
Exemplo n.º 24
0
    def updateMovie(self, movie):
        if movie["imdbnumber"] == "":
            util.logWarning("%s: no IMDb id" % movie["label"])
        else:
            imdb = imdbMovie(movie["imdbnumber"])

            if imdb.error():
                util.logError("%s: problem with omdbapi.com" % movie["label"])
            elif (imdb.votes() == "0") or (imdb.votes() == "N/A"):
                util.logWarning("%s: no votes available" % movie["label"])
            elif not(imdb.shouldUpdate(movie)):
                util.logDebug("%s: is up to date" % movie["label"])
            else:
                util.executeJSON('VideoLibrary.SetMovieDetails', {'movieid': movie['movieid'], 'rating': float(imdb.rating()), 'votes': imdb.votes()})
                util.log("%s: updated from %s (%s) to %s (%s)" % (movie["label"], movie["rating"], movie["votes"], imdb.rating(), imdb.votes()))
                return 1

        return 0
Exemplo n.º 25
0
 def nextHand(self, dummyResults):
     """next hand: maybe rotate"""
     if not self.game:
         return
     DeferredBlock.garbageCollection()
     for block in DeferredBlock.blocks:
         if block.table == self:
             logError('request left from previous hand: %s' % block.outstandingStr())
     token = self.game.handId() # we need to send the old token until the
                                # clients started the new hand
     rotateWinds = self.game.maybeRotateWinds()
     if self.game.finished():
         self.close('gameOver', m18nE('The game is over!'))
         return
     self.game.sortPlayers()
     playerNames = list((x.wind, x.name) for x in self.game.players)
     self.tellAll(None, Message.ReadyForHandStart, self.startHand,
         source=playerNames, rotateWinds=rotateWinds, token=token)
Exemplo n.º 26
0
	def connect(self):
		#If there is a local address connect to this, otherwise connect to remote address
		#connections = sorted(server['connections'], key=lambda k: k['local'], reverse=True)
		connections = self.__connections
		connected = False
		for conn in connections:
			http = util.Http()
			self.host = conn.host
			self.port = conn.port
			self.protocol = conn.protocol
			url = self.__getRootUrl()
			data = http.Get(url)
			code = http.GetHttpResponseCode()
			util.logDebug('Connecting to server: %s' % url)
			if http.ResultUnauthorised():
				util.logDebug('Unauthorised - token required: %s' % url)
				self.isTokenRequired = True
			elif http.ResultConnectFailed():
				util.logDebug('No such site: %s' % url)
			if not http.ResultSuccess(): continue
			
			util.logInfo("Connected to server: %s" % url)
			try:
				tree = ElementTree.fromstring(data)
				self.friendlyName = tree.attrib.get("friendlyName", None)
				self.machineIdentifier = tree.attrib.get("machineIdentifier", None)
				self.platform = tree.attrib.get("platform", None)
				self.platformVersion = tree.attrib.get("platformVersion", None)
				self.transcoderVideoBitrates = tree.attrib.get("transcoderVideoBitrates", None)
				self.transcoderVideoQualities = tree.attrib.get("transcoderVideoQualities", None)
				self.transcoderVideoResolutions = tree.attrib.get("transcoderVideoResolutions", None)
				self.version = tree.attrib.get("version", None)
				connected = True
				break
			except:
				#Wasn't XML data
				util.logError('Accessed server %s:%s but I was unable to process the reponse. Is the Plex server and port correct?' % (self.host, self.port))
				data = None
			else:
				util.logDebug("Error accessing server: %s return code: %s" % (url, code))
		
		if not connected:
			util.logError("Error accessing server: %s" % self.friendlyName)
		self.isConnected = connected
Exemplo n.º 27
0
    def loadFromDB(cls, gameid, client=None):
        """load game by game id and return a new Game instance"""
        Internal.logPrefix = 'S' if Internal.isServer else 'C'
        qGame = Query("select p0,p1,p2,p3,ruleset,seed from game where id = %d" % gameid)
        if not qGame.records:
            return None
        rulesetId = qGame.records[0][4] or 1
        ruleset = Ruleset.cached(rulesetId)
        Players.load() # we want to make sure we have the current definitions
        game = cls(Game.__getNames(qGame.records[0]), ruleset, gameid=gameid,
                client=client, wantedGame=qGame.records[0][5])
        qLastHand = Query("select hand,rotated from score where game=%d and hand="
            "(select max(hand) from score where game=%d)" % (gameid, gameid))
        if qLastHand.records:
            (game.handctr, game.rotated) = qLastHand.records[0]

        qScores = Query("select player, wind, balance, won, prevailing from score "
            "where game=%d and hand=%d" % (gameid, game.handctr))
        # default value. If the server saved a score entry but our client did not,
        # we get no record here. Should we try to fix this or exclude such a game from
        # the list of resumable games?
        prevailing = 'E'
        for record in qScores.records:
            playerid = record[0]
            wind = str(record[1])
            player = game.players.byId(playerid)
            if not player:
                logError(
                'game %d inconsistent: player %d missing in game table' % \
                    (gameid, playerid))
            else:
                player.getsPayment(record[2])
                player.wind = wind
            if record[3]:
                game.winner = player
            prevailing = record[4]
        game.roundsFinished = WINDS.index(prevailing)
        game.handctr += 1
        game.notRotated += 1
        game.maybeRotateWinds()
        game.sortPlayers()
        game.wall.decorate()
        return game
Exemplo n.º 28
0
def refreshToken():
    cj_rd = cookielib.CookieJar()
    opener_rd = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj_rd))
    data_rd = urllib.urlencode({'client_id' : xbmcaddon.Addon().getSetting('rd_id'), 'client_secret' : xbmcaddon.Addon().getSetting('rd_secret'), 'code': xbmcaddon.Addon().getSetting('rd_refresh'), 'grant_type' : 'http://oauth.net/grant_type/device/1.0'})
    
    try:
        resp = opener_rd.open('https://api.real-debrid.com/oauth/v2/token', data_rd)
        content=resp.read()
        
        credJSON=json.loads(content)
        
        xbmcaddon.Addon().setSetting('rd_access', credJSON['access_token'])
        xbmcaddon.Addon().setSetting('rd_refresh', credJSON['refresh_token'])
        
        #util.logError("write complete: "+str(credJSON))
        #util.logError("checking values"+xbmcaddon.Addon().getSetting('rd_access')+" "+xbmcaddon.Addon().getSetting('rd_refresh'))
        
        authorised=True
    except Exception as e:
        util.logError("Error Refreshing Token: "+str(e))
Exemplo n.º 29
0
def delID(parameters):
    util.logError(str(parameters))
    refreshToken()
    headers={"Authorization": "Bearer "+str(xbmcaddon.Addon().getSetting('rd_access'))}
    
    if parameters['method']=="torrent":
        if xbmcgui.Dialog().yesno("Delete torrent?", line1="Do you want to delete the torret", line3=parameters['name'].encode('utf-8')):
            r = requests.delete("https://api.real-debrid.com/rest/1.0/torrents/delete/"+parameters['id'], headers=headers)
            try:
                isError(json.loads(r.text))
            except:
                xbmc.executebuiltin('Container.Refresh')
    else:
        if xbmcgui.Dialog().yesno("Delete link?", line1="Do you want to delete the link", line3=parameters['name'].encode('utf-8')):
            util.logError("https://api.real-debrid.com/rest/1.0/downloads/delete/"+parameters['id'])
            r = requests.delete("https://api.real-debrid.com/rest/1.0/downloads/delete/"+parameters['id'], headers=headers)
            try:
                isError(json.loads(r.text))
            except:
                xbmc.executebuiltin('Container.Refresh')
Exemplo n.º 30
0
    def updateMovie(self, movie, httphandler, LANG_MPAA):
        if movie["imdbnumber"] == "":
            util.logWarning("%(label)s: no IMDb id" % movie)
        else:
            mpaa = imdbMpaa(movie["imdbnumber"], httphandler, LANG_MPAA)

            formattedRating = ("%s%s" if ":" in FORM_MPAA else
                               "%s %s") % (FORM_MPAA, mpaa.rating())

            if mpaa.error():
                util.logError("%s: problem with MPAA site" % movie["label"])
            elif movie["mpaa"] != formattedRating:
                util.executeJSON('VideoLibrary.SetMovieDetails', {
                    'movieid': movie['movieid'],
                    'mpaa': formattedRating
                })
                util.log("%s: updated from %s to %s" %
                         (movie["label"], movie["mpaa"], formattedRating))
                return 1

        return 0
Exemplo n.º 31
0
 def declareKong(self, player, meldTiles):
     """player declares a Kong, meldTiles is a list"""
     if not player.hasConcealedTiles(meldTiles) and not player.hasExposedPungOf(meldTiles[0]):
         # pylint: disable=W0142
         msg = m18nE('declareKong:%1 wrongly said Kong for meld %2')
         args = (player.name, ''.join(meldTiles))
         logError(m18n(msg, *args))
         logError('declareKong:concealedTileNames:%s' % ''.join(player.concealedTileNames))
         logError('declareKong:concealedMelds:%s' % \
             ' '.join(x.joined for x in player.concealedMelds))
         logError('declareKong:exposedMelds:%s' % \
             ' '.join(x.joined for x in player.exposedMelds))
         self.abort(msg, *args)
         return
     player.exposeMeld(meldTiles)
     self.tellAll(player, Message.DeclaredKong, self.pickKongReplacement, source=meldTiles)
Exemplo n.º 32
0
if mode==1:
    # display the JAV censored specific sub menu
    util.addMenuItems(menu.jamoMenu)
elif mode==2:
    # display the Gravure specific sub menu
    util.addMenuItems(menu.jav68Menu)
elif mode==9:
    if addon.getSetting('download_path')=="":
        util.alert("Please configure download in Add-On Settings")
        exit()
    # simpledownloader taken (and then altered) from specto
    import simpledownloader
    xbmc.executebuiltin( "XBMC.Notification(%s,%s,%i,%s)" % ( parameters['name'].encode("utf-8") + ' - Preparing Download', 'Please Wait', 7000, parameters['poster'].encode("utf-8")))

    url=util.getVideoURL(parameters).replace("?mime=true", "")
    util.logError(url)
    if "openload" in url:
        import urllib2
        url=urllib2.urlopen(url).geturl()
        
    simpledownloader.download(parameters['name'], parameters['poster'], url, parameters['fanart'])
elif mode==11:
    util.jamoMenu('<a>Categories</a>', '<li class="parent">')
elif mode==12:
    util.jamoMenu('<a>Studios</a>', '</ul>')
elif mode==13:
    util.jamoModels(parameters['url'])
elif mode==111:
    util.jamoVideos(parameters)
elif mode==120:
    util.jamoGetSource(parameters)
Exemplo n.º 33
0
elif mode == 2:
    # display the Gravure specific sub menu
    util.addMenuItems(menu.jav68Menu)
elif mode == 9:
    if addon.getSetting('download_path') == "":
        util.alert("Please configure download in Add-On Settings")
        exit()
    # simpledownloader taken (and then altered) from specto
    import simpledownloader
    xbmc.executebuiltin(
        "XBMC.Notification(%s,%s,%i,%s)" %
        (parameters['name'].encode("utf-8") + ' - Preparing Download',
         'Please Wait', 7000, parameters['poster'].encode("utf-8")))

    url = util.getVideoURL(parameters).replace("?mime=true", "")
    util.logError(url)
    if "openload" in url:
        import urllib2
        url = urllib2.urlopen(url).geturl()

    simpledownloader.download(parameters['name'], parameters['poster'], url,
                              parameters['fanart'])
elif mode == 11:
    util.jamoMenu('<a>Categories</a>', '<li class="parent">')
elif mode == 12:
    util.jamoMenu('<a>Studios</a>', '</ul>')
elif mode == 13:
    util.jamoModels(parameters['url'])
elif mode == 111:
    util.jamoVideos(parameters)
elif mode == 120:
Exemplo n.º 34
0
def verifyThread(authData):
    xbmc.executebuiltin('Dialog.Close(10138)') 
    # convert string to JSON
    authJSON=json.loads(authData)
    
    # create dialog with progress to show information
    authMsg="To authorise your RealDebrid account, use a browser to browse to [B]"+authJSON['verification_url']+"[/B] and enter the verification code [B]"+authJSON['user_code']+"[/B]"
    authDialog=util.progressStart("RealDebrid Authentication", authMsg)
    
    authorised=False
    timer=0
    credJSON=""
    while not authorised:
        time.sleep(2)
        timer=timer+2
        
        util.progressUpdate(authDialog, timer, authMsg)
        # check if we need to exit
        if util.progressCancelled(authDialog)==True:
            util.progressStop(authDialog)
            break
        if timer==100:
            util.progressStop(authDialog)
            util.alert("RealDebrid aithentication has timed out. Please try again.")
            break
            
        # all good to carry on lets check auth
        credentials=util.getURL("https://api.real-debrid.com/oauth/v2/device/credentials?client_id="+client_id+"&code="+authJSON['device_code'])
        
        if credentials!=False:
            try:
                if "error" in credentials:
                    util.logError(credentials)
                else:
                    credJSON=json.loads(credentials)
                    #store credentials in settings
                    xbmcaddon.Addon().setSetting('rd_id', credJSON['client_id'])
                    xbmcaddon.Addon().setSetting('rd_secret', credJSON['client_secret'])
                    
                    cj_rd = cookielib.CookieJar()
                    opener_rd = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj_rd))
                    
                    data_rd = urllib.urlencode({'client_id' : credJSON['client_id'], 'client_secret' : credJSON['client_secret'], 'code': authJSON['device_code'], 'grant_type' : 'http://oauth.net/grant_type/device/1.0'})
                    
                    try:
                        #util.logError(str(data_rd))
                    
                        resp = opener_rd.open('https://api.real-debrid.com/oauth/v2/token', data_rd)
                        content=resp.read()
                        
                        credJSON=json.loads(content)
                        
                        xbmcaddon.Addon().setSetting('rd_access', credJSON['access_token'])
                        xbmcaddon.Addon().setSetting('rd_refresh', credJSON['refresh_token'])
                            
                        authorised=True
                    except Exception as e:
                        util.logError(str(e))
            except Exception as e:
                util.logError(str(e))
    # check how we exited loop
    util.progressStop(authDialog)
    if authorised==True:
        util.alert("RealDebrid authenticated.")
        return True
    else:
        util.alert("There was an error authenticating with RealDebrid")
        return False
Exemplo n.º 35
0
import util, menu, time
import ast, json, re, os, urllib
import xbmcaddon, xbmcgui, xbmcvfs, xbmc
#import xbmcplugin, xbmcaddon, xbmcgui

sysarg = str(sys.argv[1])

if xbmcaddon.Addon().getSetting('debug') == "true":
    util.logError("Session ID = " + xbmcaddon.Addon().getSetting('session_id'))

parameters = util.parseParameters()

try:
    mode = int(parameters["mode"])
except:
    mode = None

if mode == 0:
    # load in menus
    util.addMenuItems(getattr(menu, parameters['url']))
elif mode == 1:
    # get series folders
    extras = ast.literal_eval(parameters['extras'])
    series = util.crunchyroll_api(parameters['url'], extras)
    results = json.loads(series)
    if not results['data']:
        util.notify("No results found.")
    else:
        util.buildSeriesMenu(results['data'], extras['filter'],
                             extras['media_type'], extras['limit'],
                             extras['offset'])
Exemplo n.º 36
0
def verifyThread(authData):
    xbmc.executebuiltin('Dialog.Close(10138)')
    # convert string to JSON
    authJSON = json.loads(authData)

    # create dialog with progress to show information
    authMsg = "To authorise your RealDebrid account, use a browser to browse to [B]" + authJSON[
        'verification_url'] + "[/B] and enter the verification code [B]" + authJSON[
            'user_code'] + "[/B]"
    authDialog = util.progressStart("RealDebrid Authentication", authMsg)

    authorised = False
    timer = 0
    credJSON = ""
    while not authorised:
        time.sleep(2)
        timer = timer + 2

        util.progressUpdate(authDialog, timer, authMsg)
        # check if we need to exit
        if util.progressCancelled(authDialog) == True:
            util.progressStop(authDialog)
            break
        if timer == 100:
            util.progressStop(authDialog)
            util.alert(
                "RealDebrid aithentication has timed out. Please try again.")
            break

        # all good to carry on lets check auth
        credentials = util.getURL(
            "https://api.real-debrid.com/oauth/v2/device/credentials?client_id="
            + client_id + "&code=" + authJSON['device_code'])

        if credentials != False:
            try:
                if "error" in credentials:
                    util.logError(credentials)
                else:
                    credJSON = json.loads(credentials)
                    #store credentials in settings
                    xbmcaddon.Addon().setSetting('rd_id',
                                                 credJSON['client_id'])
                    xbmcaddon.Addon().setSetting('rd_secret',
                                                 credJSON['client_secret'])

                    cj_rd = cookielib.CookieJar()
                    opener_rd = urllib2.build_opener(
                        urllib2.HTTPCookieProcessor(cj_rd))

                    data_rd = urllib.urlencode({
                        'client_id':
                        credJSON['client_id'],
                        'client_secret':
                        credJSON['client_secret'],
                        'code':
                        authJSON['device_code'],
                        'grant_type':
                        'http://oauth.net/grant_type/device/1.0'
                    })

                    try:
                        #util.logError(str(data_rd))

                        resp = opener_rd.open(
                            'https://api.real-debrid.com/oauth/v2/token',
                            data_rd)
                        content = resp.read()

                        credJSON = json.loads(content)

                        xbmcaddon.Addon().setSetting('rd_access',
                                                     credJSON['access_token'])
                        xbmcaddon.Addon().setSetting('rd_refresh',
                                                     credJSON['refresh_token'])

                        authorised = True
                    except Exception as e:
                        util.logError(str(e))
            except Exception as e:
                util.logError(str(e))
    # check how we exited loop
    util.progressStop(authDialog)
    if authorised == True:
        util.alert("RealDebrid authenticated.")
        return True
    else:
        util.alert("There was an error authenticating with RealDebrid")
        return False
Exemplo n.º 37
0
    mode=int(parameters["mode"])
except:
    mode=None
  
if mode==1:
    # display the JAV specific sub menu
    util.addMenuItems(menu.javMenu)
elif mode==2:
    # display the Gravure specific sub menu
    util.addMenuItems(menu.gravureMenu)
elif mode==3:
    # lets start searching
    search=util.searchDialog()
    if (search):
        # something has been typed, lets search for it
        util.logError(parameters['url']+"?s="+search)
        util.findVideos(parameters['url']+"?s="+search)
elif mode==4:
    # load the latest of a type
    util.findVideos(parameters["url"])
elif mode==5:
    # a video has been chosen, lets hunt for sources
    util.huntVideo(parameters)
elif mode==6:
    url=util.getVideoURL(parameters)
    util.playMedia(parameters['extras2'], parameters['poster'], url, "Video")
elif mode==7:
    util.addMenuItems(util.getFavourites())
elif mode==8:
    util.addMenuItems(util.getFavourites())
else:
Exemplo n.º 38
0
    from backgroundselector import BackgroundSelector
    from sound import Sound
    from uiwall import UIWall
    from animation import animate, afterCurrentAnimationDo, Animated
    from player import Player, Players
    from game import ScoringGame
    from chat import ChatWindow
    from message import Message

except ImportError as importError:
    NOTFOUND.append('kajongg is not correctly installed: modules: %s' %
                    importError)

if len(NOTFOUND):
    MSG = "\n".join(" * %s" % s for s in NOTFOUND)
    logError(MSG)
    os.popen("kdialog --sorry '%s'" % MSG)
    sys.exit(3)


class PlayConfigTab(QWidget):
    """Display Config tab"""
    def __init__(self, parent):
        super(PlayConfigTab, self).__init__(parent)
        self.setupUi()

    def setupUi(self):
        """layout the window"""
        self.setContentsMargins(0, 0, 0, 0)
        vlayout = QVBoxLayout(self)
        vlayout.setContentsMargins(0, 0, 0, 0)
Exemplo n.º 39
0
def feedme(feed="", type=""):
    h = HTMLParser.HTMLParser()
    colour = [
        "black", "white", "gray", "blue", "teal", "fuchsia", "indigo",
        "turquoise", "cyan", "greenyellow", "lime", "green", "olive", "gold",
        "yello", "lavender", "pink", "magenta", "purple", "maroon",
        "chocolate", "orange", "red", "brown"
    ]
    parameters = util.parseParameters()

    #util.logError(str(parameters))

    try:
        mode = int(parameters["mode"])
    except:
        mode = None

    try:
        offsite = ast.literal_eval(parameters['extras'])
        #util.logError(str(offsite))
        if "site_xml" in offsite:
            feed = offsite['site_xml']
            type = "url"
    except:
        #not set, dont worry about it
        pass

    if mode == None or mode == 0:
        # if we get here list the sites found in the json file
        menu = []
        bits = util.getFile(feed, type)
        counter = 0

        if str(len(bits['sites'])) == "1" and 'folder' not in bits['sites']:
            mode = 1
            parameters['extras'] = str({"site": 0})
        else:
            try:
                folder = ast.literal_eval(parameters['extras'])
                folder = folder['folder']
                for site in bits['sites']:
                    try:
                        if site['folder'].lower() == folder.lower():
                            extras = {}
                            try:
                                extras['site_xml'] = offsite['site_xml']
                            except:
                                pass
                            extras['site'] = counter
                            menu.append({
                                "title": site['name'],
                                "url": site['name'],
                                "mode": "1",
                                "poster": site['poster'],
                                "icon": site['poster'],
                                "fanart": site['fanart'],
                                "type": ADDON_TYPE,
                                "plot": "",
                                "isFolder": True,
                                "extras": extras
                            })

                    except:
                        # site not in a folder
                        pass
                    counter = counter + 1
            except:
                if "folders" in bits:
                    for site in bits['folders']:
                        extras = {}
                        try:
                            extras['site_xml'] = offsite['site_xml']
                        except:
                            pass
                        extras['site'] = counter
                        folder_extras = {}
                        folder_extras['folder'] = site['name']
                        if "url" in site:
                            folder_extras['site_xml'] = site['url']
                            del (folder_extras['folder'])
                        menu.append({
                            "title": site['name'],
                            "url": site['name'],
                            "mode": "0",
                            "poster": site['poster'],
                            "icon": site['poster'],
                            "fanart": site['fanart'],
                            "type": ADDON_TYPE,
                            "plot": "",
                            "isFolder": True,
                            "extras": folder_extras
                        })
                for site in bits['sites']:
                    if "folder" not in site:
                        extras = {}
                        try:
                            extras['site_xml'] = offsite['site_xml']
                        except:
                            pass
                        extras['site'] = counter
                        menu.append({
                            "title": site['name'],
                            "url": site['name'],
                            "mode": "1",
                            "poster": site['poster'],
                            "icon": site['poster'],
                            "fanart": site['fanart'],
                            "type": ADDON_TYPE,
                            "plot": "",
                            "isFolder": True,
                            "extras": extras
                        })
                    counter = counter + 1
            util.addMenuItems(menu)
    if mode == 1:
        # first level within a site, show Latest, Search and any Tags within the specified site
        menu = []
        extras = ast.literal_eval(parameters['extras'])

        try:
            extras['site_xml'] = offsite['site_xml']
        except:
            pass

        bits = util.getFile(feed, type)
        site = bits['sites'][extras['site']]

        if "search_url" not in site and "tags" not in site and len(
                site['items']) == 1:
            mode = 2
            for item in site['items']:
                parameters['url'] = site['items'][item][0]['site_url']
                break

        else:
            for item in site['items'].iterkeys():
                if item.lower() != "search":
                    try:
                        poster = parameters['poster']
                    except:
                        try:
                            poster = site['items'][item][0]['folder_poster']
                            if "http" not in poster and "https" not in poster:
                                poster = os.path.join(HOME, '', poster)
                        except:
                            poster = ""
                    try:
                        fanart = parameters['fanart']
                    except:
                        try:
                            fanart = site['items'][item][0]['folder_fanart']
                            if "http" not in fanart and "https" not in fanart:
                                fanart = os.path.join(HOME, '', fanart)
                        except:
                            fanart = ""
                    extras['level'] = item

                    menu.append({
                        "title":
                        item,
                        "url":
                        urllib.quote_plus(site['items'][item][0]['site_url']),
                        "mode":
                        "2",
                        "poster":
                        poster,
                        "icon":
                        poster,
                        "fanart":
                        fanart,
                        "type":
                        ADDON_TYPE,
                        "plot":
                        "",
                        "isFolder":
                        True,
                        "extras":
                        str(extras)
                    })

            try:
                counter = 0
                for tag in site['tags']:
                    try:
                        poster = parameters['poster']
                    except:
                        poster = ""

                    try:
                        fanart = parameters['fanart']
                    except:
                        fanart = ""
                    extras['tag'] = counter
                    menu.append({
                        "title": tag['name'],
                        "url": tag['url'],
                        "mode": "4",
                        "poster": poster,
                        "icon": poster,
                        "fanart": fanart,
                        "type": ADDON_TYPE,
                        "plot": "",
                        "isFolder": True,
                        "extras": str(extras)
                    })
                    counter = counter + 1
            except:
                pass
            if "search_url" in site:
                try:
                    poster = parameters['poster']
                except:
                    poster = ""

                try:
                    fanart = parameters['fanart']
                except:
                    fanart = ""
                menu.append({
                    "title": "Search",
                    "url": "",
                    "mode": "3",
                    "poster": poster,
                    "icon": poster,
                    "fanart": fanart,
                    "type": ADDON_TYPE,
                    "plot": "",
                    "isFolder": True,
                    "extras": str(extras)
                })
            util.addMenuItems(menu)
    if mode == 2:
        # load the first level of relevant video information
        menu = []
        extras = ast.literal_eval(parameters['extras'])

        try:
            extras['site_xml'] = offsite['site_xml']
        except:
            pass

        bits = util.getFile(feed, type)
        site = bits['sites'][extras['site']]

        if 'pos' in extras:
            pos = extras['pos']
        else:
            pos = 0

        if 'level' in extras:
            level = extras['level']
        else:
            for item in site['items']:
                level = item
                break

        if len(site['items'][level]) > pos + 1:
            # another level is needed
            extras['pos'] = pos + 1
            newMode = "2"
            isFolder = True
        else:
            # on a level where next move is to check for sources
            try:
                if site['items'][level][pos]['play_media'] == "multiple":
                    newMode = "113"
                    isFolder = True
                else:
                    newMode = "111"  # find source
                    isFolder = False
            except:
                # default to play first found
                newMode = "111"  # find source
                isFolder = False

        #util.alert(newMode)
        page = util.get(h.unescape(parameters['url']))
        next = page
        """if parameters['name']=="Next Page >":
            util.logError(str(next))"""

        try:
            if site['items'][level][pos]['global'] != "":
                regex = util.prepare(site['items'][level][pos]['global'])
                matches = re.findall(regex, page)
                if matches:
                    page = matches[0]
        except:
            pass

        regex = util.prepare(site['items'][level][pos]['pattern'])
        matches = re.findall(regex, page)
        if matches:
            counter = 0
            for match in matches:
                try:
                    title = h.unescape(
                        util.replaceParts(
                            site['items'][level][pos]['name'],
                            matches[counter]).replace('\n', '').replace(
                                '\t', '').replace("\\", "").lstrip())
                except:
                    title = ""
                #try:
                #    util.alert(site['items'][level][pos]['url'])
                url = urllib.quote_plus(
                    util.replaceParts(site['items'][level][pos]['url'],
                                      matches[counter]))
                #    util.alert(">>"+url)
                #except:
                #    url=""
                try:
                    poster = util.replaceParts(
                        site['items'][level][pos]['poster'],
                        matches[counter]).encode('utf-8')
                except:
                    poster = ""
                try:
                    fanart = util.replaceParts(
                        site['items'][level][pos]['fanart'],
                        matches[counter]).encode('utf-8')
                except:
                    fanart = ""
                try:
                    plot = util.replaceParts(site['items'][level][pos]['plot'],
                                             matches[counter]).encode('utf-8')
                except:
                    plot = ""

                if isFolder:
                    menu.append({
                        "title": title,
                        "url": url,
                        "mode": newMode,
                        "poster": poster,
                        "icon": poster,
                        "fanart": fanart,
                        "type": ADDON_TYPE,
                        "plot": plot,
                        "isFolder": isFolder,
                        "extras": str(extras)
                    })
                else:
                    menu.append({
                        "title": title,
                        "url": url,
                        "mode": newMode,
                        "poster": poster,
                        "icon": poster,
                        "fanart": fanart,
                        "type": ADDON_TYPE,
                        "plot": plot,
                        "isFolder": isFolder,
                        "isPlayable": "True",
                        "extras": str(extras)
                    })
                counter = counter + 1
        try:
            regex = util.prepare(site['items'][level][pos]['next_pattern'])
            matches = re.findall(regex, next)
            if matches:
                parts = []
                if len(matches) > 1:
                    for match in matches:
                        parts.append(match)
                else:
                    match = matches

                #nextlink=util.execPy(util.replaceParts(site['items'][level][pos]['next_url'], match))
                nextlink = util.replaceParts(
                    site['items'][level][pos]['next_url'], match)
                extras['pos'] = pos

                menu.append({
                    "title": "Next Page >",
                    "url": urllib.quote_plus(nextlink),
                    "mode": "2",
                    "poster": "",
                    "icon": "",
                    "fanart": "",
                    "type": ADDON_TYPE,
                    "plot": plot,
                    "isFolder": True,
                    "extras": str(extras)
                })
        except Exception as e:
            util.logError(str(e))
            pass
        util.addMenuItems(menu)
    elif mode == 3:
        # display the Search dialog and build search results
        menu = []
        extras = ast.literal_eval(parameters['extras'])

        try:
            extras['site_xml'] = offsite['site_xml']
        except:
            pass

        term = util.searchDialog()

        if term:
            bits = util.getFile(feed, type)
            site = bits['sites'][extras['site']]
            pos = 0

            for item in site['items']:
                level = item
                extras['level'] = level
                break

            if len(site['items'][extras['level']]) > pos + 1:
                # another level is needed
                extras['pos'] = 1
                newMode = "2"
                isFolder = True
                isPlayable = True
            else:
                # on a level where next move is to check for sources
                if site['items'][
                        extras['level']][pos]['play_media'] == "multiple":
                    newMode = "113"
                    isFolder = True
                    isPlayable = False
                else:
                    newMode = "111"  # find source
                    isFolder = False
                    isPlayable = True
            if "{{" in site['search_url'] and "}}" in site['search_url']:
                url = util.execPy(site['search_url'].replace("{%}", term))
            else:
                url = site['search_url'].replace("{%}", term)
            util.logError(url)
            page = util.get(url)
            next = page

            try:
                if site['item']['global'] != "":
                    regex = util.prepare(site['item']['global'])
                    matches = re.findall(regex, page)
                    if matches:
                        page = matches[0]
            except:
                pass

            regex = util.prepare(site['items'][level][pos]['pattern'])
            matches = re.findall(regex, page)

            if matches:
                counter = 0
                for match in matches:
                    try:
                        title = h.unescape(
                            util.replaceParts(
                                site['items'][level][pos]['name'],
                                matches[counter]).replace('\n', '').replace(
                                    '\t', '').lstrip().encode('utf-8'))
                    except:
                        title = ""
                    try:
                        url = util.replaceParts(
                            site['items'][level][pos]['url'],
                            matches[counter]).encode('utf-8')
                        #util.logError(url)
                    except:
                        url = ""
                    try:
                        poster = util.replaceParts(
                            site['items'][level][pos]['poster'],
                            matches[counter]).encode('utf-8')
                    except:
                        poster = ""
                    try:
                        fanart = util.replaceParts(
                            site['items'][level][pos]['fanart'],
                            matches[counter]).encode('utf-8')
                    except:
                        fanart = ""
                    try:
                        plot = util.replaceParts(
                            site['items'][level][pos]['plot'],
                            matches[counter]).encode('utf-8')
                    except:
                        plot = ""

                    if isFolder:
                        menu.append({
                            "title": title,
                            "url": url,
                            "mode": newMode,
                            "poster": poster,
                            "icon": poster,
                            "fanart": fanart,
                            "type": ADDON_TYPE,
                            "plot": plot,
                            "isFolder": isFolder,
                            "extras": str(extras)
                        })
                    else:
                        menu.append({
                            "title": title,
                            "url": url,
                            "mode": newMode,
                            "poster": poster,
                            "icon": poster,
                            "fanart": fanart,
                            "type": ADDON_TYPE,
                            "plot": plot,
                            "isFolder": isFolder,
                            "isPlayable": "True",
                            "extras": str(extras)
                        })
                    counter = counter + 1
            try:
                regex = util.prepare(site['items'][level][pos]['next_pattern'])
                matches = re.findall(regex, next)
                if matches:
                    parts = []
                    """for match in matches:
                        parts.append(match)"""

                    if len(matches) > 1:
                        for match in matches:
                            parts.append(match)
                        else:
                            match = matches

                    #nextlink=util.execPy(util.replaceParts(site['items'][level][pos]['next_url'], match))
                    nextlink = util.replaceParts(
                        site['items'][level][pos]['next_url'], match)
                    menu.append({
                        "title": "Next Page >",
                        "url": nextlink,
                        "mode": "2",
                        "poster": "",
                        "icon": "",
                        "fanart": "",
                        "type": ADDON_TYPE,
                        "plot": plot,
                        "isFolder": True,
                        "extras": str(extras)
                    })
            except:
                pass
            util.addMenuItems(menu)
        else:
            return False
    elif mode == 4:
        # show relevant Tag video results
        menu = []

        extras = ast.literal_eval(parameters['extras'])

        try:
            extras['site_xml'] = offsite['site_xml']
        except:
            pass

        bits = util.getFile(feed, type)

        site = bits['sites'][extras['site']]['tags'][extras['tag']]

        page = util.get(parameters['url'])
        next = page

        try:
            if site['item']['global'] != "":
                regex = util.prepare(site['item']['global'])
                matches = re.findall(regex, page)
                if matches:
                    page = matches[0]
        except:
            pass

        regex = util.prepare(site['item']['pattern'])
        matches = re.findall(regex, page)
        if matches:
            counter = 0
            for match in matches:
                try:
                    title = h.unescape(
                        util.replaceParts(site['item']['name'],
                                          matches[counter]).encode('utf-8'))
                except:
                    title = ""
                try:
                    url = util.replaceParts(site['item']['url'],
                                            matches[counter]).encode('utf-8')
                except:
                    url = ""
                try:
                    poster = util.replaceParts(
                        site['item']['poster'],
                        matches[counter]).encode('utf-8')
                except:
                    poster = ""
                try:
                    fanart = util.replaceParts(
                        site['item']['fanart'],
                        matches[counter]).encode('utf-8')
                except:
                    fanart = ""
                try:
                    plot = util.replaceParts(site['item']['plot'],
                                             matches[counter]).encode('utf-8')
                except:
                    plot = ""

                menu.append({
                    "title": title,
                    "url": url,
                    "mode": "2",
                    "poster": poster,
                    "icon": poster,
                    "fanart": fanart,
                    "type": ADDON_TYPE,
                    "plot": plot,
                    "isFolder": True,
                    "extras": extras
                })
                counter = counter + 1
        util.addMenuItems(menu)
    elif mode == 5:
        pass
    elif mode == 111:
        # find playable sources in url
        #util.alert(parameters['url'])

        extras = ast.literal_eval(parameters['extras'])
        bits = util.getFile(feed, type)
        site = bits['sites'][extras['site']]

        try:
            pos = extras['pos']
        except:
            pos = 0

        try:
            selected_video = int(
                site['items'][extras['level']][pos]['play_media']) - 1
        except:
            selected_video = 0

        page = util.get(parameters['url'])

        link = False
        try:
            link = urlresolver.resolve(parameters['url'])
        except Exception as e:
            if str(e).lower() == "sign in to confirm your age":
                util.notify("YouTube Error: Login to confirm age.")
                return False
            else:
                util.notify(str(e))
                return False

        if link:
            # play if url resolver reports true
            util.playMedia(parameters['name'],
                           parameters['poster'],
                           link,
                           force=True)
        elif any(ext in parameters['url'] for ext in filetypes):
            # play if url has a video extension
            util.playMedia(parameters['name'],
                           parameters['poster'],
                           parameters['url'],
                           force=True)
        else:
            #search for video urls
            if "urlresolver" in site and site['urlresolver'].lower(
            ) == "false":
                regex = "\"([^\s]*?\.(:?" + "|".join(filetypes) + "))\""
                matches = re.findall(regex, page)
            else:
                regex = "(\/\/.*?\/embed.*?)[\?\"]"
                matches = re.findall(regex, page)
                regex = "\"((?:http:|https:)?\/\/.*?\/watch.*?)[\"]"
                matches = matches + re.findall(regex, page)
                matches2 = urlresolver.scrape_supported(page)
                #util.alert(str(matches))
                """regex="\"(https?://("+"|".join(supports)+")\..*?)\""
                matches2 = re.findall(regex, page)
                regex="\"((?:http:|https:)?\/\/.*?\/watch.*?)[\"]"
                matches3 = re.findall(regex, page)
                regex = 'https?://(.*?(?:\.googlevideo|(?:plus|drive|get|docs)\.google|google(?:usercontent|drive|apis))\.com)/(.*?(?:videoplayback\?|[\?&]authkey|host/)*.+)'
                matches4 = re.findall(regex, page)
                
                matches2=[ x for x in matches2 if any(sup in x for sup in supports) ]
                matches3=[ x for x in matches3 if any(sup in x for sup in supports) ]"""

                matches = matches + matches2
            util.logError(
                "''''''''''''''''''''''''''''''''''''''''''''''''''''''")
            util.logError(">>>>" + str(matches))
            if isinstance(matches[selected_video], tuple):
                url = matches[selected_video][0]
            else:
                url = matches[selected_video]
            #util.alert(url)
            if "http" not in url:
                url = "http:" + url

            link = urlresolver.resolve(url)

            if link == False:
                link = url

            util.playMedia(parameters['name'], parameters['poster'], link)

    elif mode == 112:
        extras = ast.literal_eval(parameters['extras'])
        bits = util.getFile(feed, type)
        site = bits['sites'][extras['site']]

        page = util.get(parameters['url'])
        """if "urlresolver" in site and site['urlresolver'].lower()=="false":
            regex="\"(.*?\.mp4)\""
            matches = re.findall(regex, page)
            if matches:
                link=matches[0]
        else:"""
        regex = "\"(//\S*?(:?" + ("|".join(filetypes)) + ")\S*?)\""
        matches = re.findall(regex, page)
        if matches:
            url = matches[selected_video][0]
            if "http" not in url:
                link = "http:" + url
        else:
            link = urlresolver.resolve(parameters['url'])
            if not link:
                try:
                    regex = "(\/\/.*?\/embed.*?)[\?\"]"
                    matches = re.findall(regex, page)
                    regex = "\"((?:http:|https:)?\/\/.*?\/watch.*?)[\"]"
                    matches = matches + re.findall(regex, page)
                    regex = 'https?://(.*?(?:\.googlevideo|(?:plus|drive|get|docs)\.google|google(?:usercontent|drive|apis))\.com)/(.*?(?:videoplayback\?|[\?&]authkey|host/)*.+)'
                    matches = matches + re.findall(regex, page)
                    if matches:
                        matches = [
                            x for x in matches
                            if any(sup in x for sup in supports)
                        ]
                        if matches:
                            link = urlresolver.resolve("http:" + matches[0])
                except Exception as e:
                    util.notify(str(e))
        if link:
            import downloader
            downloader.download(
                link,
                os.path.join(xbmcaddon.Addon().getSetting('folder'),
                             parameters['name'] + ".mp4"))
        else:
            util.notify("No video found")
    elif mode == 113:
        menu = []
        extras = ast.literal_eval(parameters['extras'])
        bits = util.getFile(feed, type)
        site = bits['sites'][extras['site']]

        page = util.get(parameters['url'])

        matches = urlresolver.scrape_supported(page)
        #regex="(//\S*?(:?"+("|".join(filetypes))+")\S*?)"
        #matches2 = re.findall(regex, page)
        """regex="(\/\/.*?\/embed.*?)[\?\"]"
        matches2 = re.findall(regex, page)
        regex="\"(https?://("+"|".join(supports)+")\..*?)\""
        matches3 = re.findall(regex, page)
        regex = 'https?://(.*?(?:\.googlevideo|(?:plus|drive|get|docs)\.google|google(?:usercontent|drive|apis))\.com)/(.*?(?:videoplayback\?|[\?&]authkey|host/)*.+)'
        matches4 = re.findall(regex, page)
        
        matches2=[ x for x in matches2 if any(sup in x for sup in supports) ]
        matches3=[ x for x in matches3 if any(sup in x for sup in supports) ]
        
        matches=matches+matches2+matches3+matches4"""

        unique = []
        for match in matches:  #+matches2:
            if isinstance(match, tuple):
                unique.append(match[0])
            else:
                unique.append(match)

        matches = list(set(unique))

        if matches:
            for match in matches:
                if "http" not in match:
                    rl = "http:" + match
                else:
                    rl = match

                menu.append({
                    "title": rl,
                    "url": rl,
                    "mode": "114",
                    "poster": parameters['poster'],
                    "icon": parameters['icon'],
                    "fanart": parameters['fanart'],
                    "type": "",
                    "plot": "",
                    "isFolder": False,
                    "isPlayable": False,
                    "extras": str(extras)
                })
            util.addMenuItems(menu)
    elif mode == 114:
        # find playable sources in url
        #util.alert(parameters['url'])
        urlresolver.relevant_resolvers()
        try:
            link = urlresolver.resolve(str(parameters['url']))
        except Exception as e:
            util.notify(str(e))
            exit()
        if link:
            try:
                util.playMedia(parameters['name'], parameters['poster'], link)
            except:
                util.playMedia(parameters['name'], parameters['poster'],
                               parameters['url'])
Exemplo n.º 40
0
    from tilesetselector import TilesetSelector
    from backgroundselector import BackgroundSelector
    from sound import Sound
    from uiwall import UIWall
    from animation import animate, afterCurrentAnimationDo, Animated
    from player import Player, Players
    from game import ScoringGame
    from chat import ChatWindow
    from message import Message

except ImportError as importError:
    NOTFOUND.append('kajongg is not correctly installed: modules: %s' % importError)

if len(NOTFOUND):
    MSG = "\n".join(" * %s" % s for s in NOTFOUND)
    logError(MSG)
    os.popen("kdialog --sorry '%s'" % MSG)
    sys.exit(3)

class PlayConfigTab( QWidget):
    """Display Config tab"""
    def __init__(self, parent):
        super(PlayConfigTab, self).__init__(parent)
        self.setupUi()

    def setupUi(self):
        """layout the window"""
        self.setContentsMargins(0, 0, 0, 0)
        vlayout = QVBoxLayout(self)
        vlayout.setContentsMargins(0, 0, 0, 0)
        sliderLayout = QHBoxLayout()
Exemplo n.º 41
0
            sg.Multiline(size=(50, 3), key='-comment-')],
        [sg.Text('Date:', size=(10, 1)),
            sg.Spin(dateValues, initial_value=str(util.daysFromNow(1)), key='-date-', size=(28, 1))],
        [sg.Text('Time:', size=(10, 1)),
            sg.InputCombo(hourValues, default_value=8, key='-hour-', size=(4, 1)),
            sg.Text(':'),
            sg.InputCombo(minuteValues, default_value='00', key='-minute-', size=(4, 1)),
            sg.Text(' '),
            sg.InputCombo(periodValues, default_value='AM', key='-period-', size=(4, 1))],
        [sg.Text('Status:', size=(10, 1)),
            sg.InputText(default_text='', key='-status-', disabled=True, size=(52, 1))],
        [sg.Button('Schedule'), sg.Quit()]
    ]

    window = sg.Window('Post scheduler', layout, default_element_size=(60, 1))

    while True:
        event, values = window.read()
        if event in (sg.WIN_CLOSED, 'Quit'):
            break
        if event == 'Schedule':
            status = validate(values)
            setStatus(window, status)

            if not status.startswith('ERROR'):
                postImage(values)

    window.close()
except:
    util.logError(sys.exc_info())