Beispiel #1
0
 def remote_gameOver(self, tableid, message, *args):
     """the game is over"""
     def yes(dummy):
         """now that the user clicked the 'game over' prompt away, clean up"""
         if self.game:
             self.game.rotateWinds()
             if Options.csv:
                 gameWinner = max(self.game.players, key=lambda x: x.balance)
                 writer = csv.writer(open(Options.csv,'a'), delimiter=';')
                 if Debug.process:
                     self.game.csvTags.append('MEM:%s' % resource.getrusage(resource.RUSAGE_SELF).ru_maxrss)
                 row = [Options.AI, str(self.game.seed), ','.join(self.game.csvTags)]
                 for player in sorted(self.game.players, key=lambda x: x.name):
                     row.append(player.name.encode('utf-8'))
                     row.append(player.balance)
                     row.append(player.wonCount)
                     row.append(1 if player == gameWinner else 0)
                 writer.writerow(row)
                 del writer
             if self.game.autoPlay and Internal.field:
                 Internal.field.close()
             else:
                 self.game.close().addCallback(Client.quitProgram)
     assert self.table and self.table.tableid == tableid
     if Internal.field:
         # update the balances in the status bar:
         Internal.field.updateGUI()
     logInfo(m18n(message, *args), showDialog=True).addCallback(yes)
Beispiel #2
0
 def stopGamesWithRegex(self):
     """we do not support Regex rules anymore.
     Mark all games using them as finished - until somebody
     complains. So for now always return False"""
     if not self.hasTable('usedrule'):
         return
     usedRegexRulesets = Query("select distinct ruleset from usedrule "
         "where definition not like 'F%' "
         "and definition not like 'O%' "
         "and definition not like 'int%' "
         "and definition not like 'bool%' "
         "and definition<>'' "
         "and definition not like 'XEAST9X%'").records
     usedRegexRulesets = list(unicode(x[0]) for x in usedRegexRulesets)
     if not usedRegexRulesets:
         return
     openRegexGames = Query("select id from game "
         "where endtime is null "
         "and ruleset in (%s)" % ','.join(usedRegexRulesets)).records
     openRegexGames = list(x[0] for x in openRegexGames)
     if not openRegexGames:
         return
     logInfo('Marking games using rules with regular expressions as finished: %s' % openRegexGames)
     for openGame in openRegexGames:
         endtime = datetime.datetime.now().replace(microsecond=0).isoformat()
         Query('update game set endtime=? where id=?',
             list([endtime, openGame]))
Beispiel #3
0
 def stopGamesWithRegex(self):
     """we do not support Regex rules anymore.
     Mark all games using them as finished - until somebody
     complains. So for now always return False"""
     if not self.hasTable('usedrule'):
         return
     usedRegexRulesets = Query("select distinct ruleset from usedrule "
                               "where definition not like 'F%' "
                               "and definition not like 'O%' "
                               "and definition not like 'int%' "
                               "and definition not like 'bool%' "
                               "and definition<>'' "
                               "and definition not like 'XEAST9X%'").records
     usedRegexRulesets = list(unicode(x[0]) for x in usedRegexRulesets)
     if not usedRegexRulesets:
         return
     openRegexGames = Query("select id from game "
                            "where endtime is null "
                            "and ruleset in (%s)" %
                            ','.join(usedRegexRulesets)).records
     openRegexGames = list(x[0] for x in openRegexGames)
     if not openRegexGames:
         return
     logInfo(
         'Marking games using rules with regular expressions as finished: %s'
         % openRegexGames)
     for openGame in openRegexGames:
         endtime = datetime.datetime.now().replace(
             microsecond=0).isoformat()
         Query('update game set endtime=? where id=?',
               list([endtime, openGame]))
Beispiel #4
0
	def getServers(self):
		localServers = dict()
		remoteServers = dict()

		foundServer = False
		
		if self.isAuthenticated():
			data = mc.Http().Get(self.getLibraryUrl())
			if data:
				tree = ElementTree.fromstring(data)
				for child in tree:
					host = child.attrib.get("address", "")
					port = child.attrib.get("port", "")
					accessToken = child.attrib.get("accessToken", "")
					machineIdentifier = child.attrib.get("machineIdentifier", "")
					local = child.attrib.get("owned", "0")

					util.logInfo("MyPlex found %s:%s" % (host,port))
					foundServer = True
					server = PlexServer(host, port, accessToken)
					if not server.isAuthenticated():
						continue
					if local == "1":
						localServers[machineIdentifier] = server
					else:
						remoteServers[machineIdentifier] = server
		
		return localServers, remoteServers, foundServer
Beispiel #5
0
 def serverListening(self):
     """is somebody listening on that port?"""
     if self.useSocket and os.name != 'nt':
         sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
         sock.settimeout(1)
         try:
             sock.connect(socketName())
         except socket.error as exception:
             if os.path.exists(socketName()):
                 # try again, avoiding a race
                 try:
                     sock.connect(socketName())
                 except socket.error as exception:
                     if removeIfExists(socketName()):
                         logInfo(m18n('removed stale socket <filename>%1</filename>', socketName()))
                     logInfo('socket error:%s' % str(exception))
                     return False
                 else:
                     return True
         else:
             return True
     else:
         sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
         sock.settimeout(1)
         try:
             sock.connect((self.dlg.host, self.dlg.port))
         except socket.error:
             return False
         else:
             return True
Beispiel #6
0
	def MyPlex(cls, deviceXmlElement):
		device = deviceXmlElement
		server = cls()
		server.friendlyName = device.attrib.get('name')
		util.logInfo("MyPlex found server: %s" % server.friendlyName)
		server.platform = device.attrib.get('platform')
		server.platformVersion = device.attrib.get('platformVersion')
		server.machineIdentifier = device.attrib.get('clientIdentifier')
		server.accessToken = device.attrib.get('accessToken')
		server.httpsRequired = device.attrib.get('httpsRequired') == '1'
		server.appearsOffline = device.attrib.get('presence') == '0'
		server.remoteTitle = device.attrib.get('sourceTitle')
		#server.isLocal = device.attrib.get('owned') == '1'
		server.isLocal = device.attrib.get('home','') != '0'
		server.version = device.attrib.get('productVersion')
		
		for conn in device:
			if conn.tag != 'Connection': continue
			connection = server.addConnection()
			connection.host = conn.attrib.get('address')
			connection.port = conn.attrib.get('port')
			connection.protocol = conn.attrib.get('protocol')
			connection.uri = conn.attrib.get('uri')
			connection.isLocal = conn.attrib.get('local') == '1'
		return server
Beispiel #7
0
 def serverListening(self):
     """is somebody listening on that port?"""
     if self.useSocket and os.name != 'nt':
         sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
         sock.settimeout(1)
         try:
             sock.connect(socketName())
         except socket.error as exception:
             if os.path.exists(socketName()):
                 # try again, avoiding a race
                 try:
                     sock.connect(socketName())
                 except socket.error as exception:
                     if removeIfExists(socketName()):
                         logInfo(
                             m18n(
                                 'removed stale socket <filename>%1</filename>',
                                 socketName()))
                     logInfo('socket error:%s' % str(exception))
                     return False
                 else:
                     return True
         else:
             return True
     else:
         sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
         sock.settimeout(1)
         try:
             sock.connect((self.dlg.host, self.dlg.port))
         except socket.error:
             return False
         else:
             return True
Beispiel #8
0
 def export(self):
     page_count = len(self.urls)
     url_str = '\n'.join(unicode(s) for s in self.urls if s)
     content = util.parseTemplateString(self.SM_CONTENT_TPL, (page_count, url_str))
     util.logInfo( 'Sitemap:' )
     export_file = self.site.generateDeployFilePath('sitemap.xml', assign=True)
     with open(export_file, 'w') as fp:
         fp.write(content)
     util.logInfo( '    => %s', self.site.getRelativePath(export_file) )
Beispiel #9
0
 def requestAvatar(self, avatarId, mind, *interfaces):
     """as the tutorials do..."""
     if not pb.IPerspective in interfaces:
         raise NotImplementedError, "No supported avatar interface"
     avatar = User(avatarId)
     avatar.server = self.server
     avatar.attached(mind)
     logInfo('Connection from IP %s ' % mind.broker.transport.getPeer())
     return pb.IPerspective, avatar, lambda a = avatar:a.detached(mind)
Beispiel #10
0
 def parseCategory(self):
     cate = []
     for c in self.category:
         category = self.site.convertToConfigedCategory(c)
         if category:
             if category not in cate:
                 cate_obj = Category(self.site, category)
                 cate.append(cate_obj)
             else:
                 util.logInfo( "category: '%s' already exists IN '%s'", c, self.site.getRelativePath(self.source) )
         else:
             util.logWarning( "unavailable category: '%s' IN %s", c, self.site.getRelativePath(self.source) )
     self.category = cate
Beispiel #11
0
 def closeTable(self, table, reason, message, *args):
     """close a table"""
     message = message or reason
     logInfo('%s%s ' % (('%s:' % table.game.seed) if table.game else '', m18n(message, *args)), withGamePrefix=None)
     if table.tableid in self.tables:
         tellUsers = table.users if table.game else self.users
         for user in tellUsers:
             self.callRemote(user, reason, table.tableid, message, *args)
         for user in table.users:
             table.delUser(user)
         del self.tables[table.tableid]
     for block in DeferredBlock.blocks[:]:
         if block.table == table:
             DeferredBlock.blocks.remove(block)
Beispiel #12
0
 def _loginReallyFailed(self, failure):
     """login failed, not fixable by adding missing user"""
     msg = self._prettifyErrorMessage(failure)
     if failure.check(CancelledError):
         # show no warning, just leave
         return failure
     if 'Errno 5' in msg:
         # The server is running but something is wrong with it
         if self.useSocket and os.name != 'nt':
             if removeIfExists(socketName()):
                 logInfo(m18n('removed stale socket <filename>%1</filename>', socketName()))
             msg += '\n\n\n' + m18n('Please try again')
     logWarning(msg)
     return failure
Beispiel #13
0
	def getServers(self):
		localServers = dict()
		remoteServers = dict()

		foundServer = False
		
		if self.isAuthenticated():
			url = MyPlexService.SERVERS_URL % self.authenticationToken
			util.logDebug("Finding servers via: "+url)
			data = util.Http().Get(url)
			if data:
				tree = ElementTree.fromstring(data)
				for child in tree:
					host = child.attrib.get("address", "")
					port = child.attrib.get("port", "")
					localAddresses = child.attrib.get("localAddresses", "")
					accessToken = child.attrib.get("accessToken", "")
					machineIdentifier = child.attrib.get("machineIdentifier", "")
					local = child.attrib.get("owned", "0")
					sourceTitle = child.attrib.get("sourceTitle", "")

					util.logInfo("MyPlex found server %s:%s" % (host,port))
					foundServer = True
					server = None
					if local == "1":
						#Try the local addresses
						#TODO: Similiar code exists in the server and this is a bit convoluted....
						if localAddresses:
							localAddresses = localAddresses.split(',')
							util.logInfo("--> Resolving local addresses")
							resolved = False
							for addr in localAddresses:
								http = util.Http()
								util.logDebug("--> Trying local address %s:32400" % addr)
								data = http.Get("http://"+addr+":32400/?X-Plex-Token="+accessToken)
								if http.GetHttpResponseCode() == -1:
									data = http.Get("https://"+addr+":32400/?X-Plex-Token="+accessToken)
								if data:
									tree = ElementTree.fromstring(data)
									localMachineIdentifier = tree.attrib.get("machineIdentifier", "")
									if localMachineIdentifier == machineIdentifier:
										util.logInfo("--> Using local address %s:32400 instead of remote address" % addr)
										server = PlexServer(addr, "32400", accessToken)
										resolved = True
										break
							if not resolved:
								util.logInfo("--> Using remote address %s unable to resolve local address" % host)
								server = PlexServer(host, port, accessToken)

						if server is None or not server.isValid():
							continue
						localServers[machineIdentifier] = server
					else:
						#Remote server found
						server = PlexServer(host, port, accessToken, sourceTitle)
						remoteServers[machineIdentifier] = server
		
		return localServers, remoteServers, foundServer
Beispiel #14
0
 def _loginReallyFailed(self, failure):
     """login failed, not fixable by adding missing user"""
     msg = self._prettifyErrorMessage(failure)
     if failure.check(CancelledError):
         # show no warning, just leave
         return failure
     if 'Errno 5' in msg:
         # The server is running but something is wrong with it
         if self.useSocket and os.name != 'nt':
             if removeIfExists(socketName()):
                 logInfo(
                     m18n('removed stale socket <filename>%1</filename>',
                          socketName()))
             msg += '\n\n\n' + m18n('Please try again')
     logWarning(msg)
     return failure
Beispiel #15
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
Beispiel #16
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
Beispiel #17
0
	def getServers(self):
		localServers = dict()
		remoteServers = dict()

		foundServer = False
		
		if self.isAuthenticated():
			url = MyPlexService.SERVERS_URL % self.authenticationToken
			util.logDebug("Finding servers via: "+url)
			data = mc.Http().Get(url)
			if data:
				tree = ElementTree.fromstring(data)
				for child in tree:
					host = child.attrib.get("address", "")
					port = child.attrib.get("port", "")
					localAddresses = child.attrib.get("localAddresses", "")
					accessToken = child.attrib.get("accessToken", "")
					machineIdentifier = child.attrib.get("machineIdentifier", "")
					local = child.attrib.get("owned", "0")

					util.logInfo("MyPlex found servers %s:%s" % (host,port))
					foundServer = True
					server = None
					if local == "1":
						#Try the local addresses
						if localAddresses:
							localAddresses = localAddresses.split(',')
							util.logInfo("--> Resolving local addresses")
							resolved = False
							for addr in localAddresses:
								data = mc.Http().Get("http://"+addr+":32400")
								util.logDebug("--> Trying local address %s:32400" % addr)
								if data:
									tree = ElementTree.fromstring(data)
									localMachineIdentifier = tree.attrib.get("machineIdentifier", "")
									if localMachineIdentifier == machineIdentifier:
										util.logInfo("--> Using local address %s:32400 instead of remote address" % addr)
										server = PlexServer(addr, "32400", accessToken)
										resolved = True
										server.isLocal = True
										break
							if not resolved:
								util.logInfo("--> Using remote address unable to resolve local address" % addr)
								server = PlexServer(host, port, accessToken)

						if server is None or not server.isAuthenticated():
							continue
						localServers[machineIdentifier] = server
					else:
						server = PlexServer(host, port, accessToken)
						remoteServers[machineIdentifier] = server
		
		return localServers, remoteServers, foundServer
Beispiel #18
0
 def __init__(self, table, temp=False):
     dummy, dummy, function, dummy = traceback.extract_stack()[-2]
     self.outstanding = 0
     self.calledBy = function
     if not temp:
         self.garbageCollection()
     self.table = table
     self.requests = []
     self.callbackMethod = None
     self.__callbackArgs = None
     self.completed = False
     if not temp:
         DeferredBlock.blocks.append(self)
         if not DeferredBlock.blockWarned:
             if len([x for x in DeferredBlock.blocks if x.table == table]) > 10:
                 DeferredBlock.blockWarned = True
                 logInfo('We have %d DBlocks:' % len(DeferredBlock.blocks))
                 for block in DeferredBlock.blocks:
                     logInfo(str(block))
Beispiel #19
0
 def __init__(self, table, temp=False):
     dummy, dummy, function, dummy = traceback.extract_stack()[-2]
     self.outstanding = 0
     self.calledBy = function
     if not temp:
         self.garbageCollection()
     self.table = table
     self.requests = []
     self.callbackMethod = None
     self.__callbackArgs = None
     self.completed = False
     if not temp:
         DeferredBlock.blocks.append(self)
         if not DeferredBlock.blockWarned:
             if len([x for x in DeferredBlock.blocks if x.table == table
                     ]) > 10:
                 DeferredBlock.blockWarned = True
                 logInfo('We have %d DBlocks:' % len(DeferredBlock.blocks))
                 for block in DeferredBlock.blocks:
                     logInfo(str(block))
Beispiel #20
0
 def requestAvatarId(self, cred): # pylint: disable=R0201
     """get user id from database"""
     args = cred.username.split(SERVERMARK)
     if len(args) > 1:
         if args[0] == 'adduser':
             cred.username = args[1]
             password = args[2]
             with Transaction():
                 query = Query('insert into player(name,password) values(?,?)',
                     list([cred.username.decode('utf-8'), password.decode('utf-8')]))
                 if not query.success:
                     if query.msg.startswith('ERROR: constraint failed') \
                     or 'not unique' in query.msg:
                         template = m18nE('User %1 already exists')
                         logInfo(m18n(template, cred.username))
                         query.msg = srvMessage(template, cred.username)
                     else:
                         logInfo(query.msg)
                     return fail(credError.UnauthorizedLogin(query.msg))
         elif args[1] == 'deluser':
             pass
     query = Query('select id, password from player where name=?',
         list([cred.username.decode('utf-8')]))
     if not len(query.records):
         template = 'Wrong username: %1'
         logInfo(m18n(template, cred.username))
         return fail(credError.UnauthorizedLogin(srvMessage(template, cred.username)))
     userid, password = query.records[0]
     # checkPassword uses md5 which cannot handle unicode strings (python 2.7)
     defer1 = maybeDeferred(cred.checkPassword, password.encode('utf-8'))
     defer1.addCallback(DBPasswordChecker._checkedPassword, userid)
     return defer1
Beispiel #21
0
def kajonggServer():
    """start the server"""
    from optparse import OptionParser
    parser = OptionParser()
    defaultPort = InternalParameters.defaultPort()
    parser.add_option('', '--port', dest='port',
        help=m18n('the server will listen on PORT (%d)' % defaultPort),
        type=int, default=defaultPort)
    parser.add_option('', '--socket', dest='socket',
        help=m18n('the server will listen on SOCKET'), default=None)
    parser.add_option('', '--db', dest='dbpath', help=m18n('name of the database'), default=None)
    parser.add_option('', '--local', dest='local', action='store_true',
        help=m18n('start a local game server'), default=False)
    parser.add_option('', '--continue', dest='continueServer', action='store_true',
        help=m18n('do not terminate local game server after last client disconnects'), default=False)
    parser.add_option('', '--debug', dest='debug',
        help=Debug.help())
    (options, args) = parser.parse_args()
    if args and ''.join(args):
        logWarning(m18n('unrecognized arguments:%1', ' '.join(args)))
        sys.exit(2)
    InternalParameters.continueServer |= options.continueServer
    if options.dbpath:
        InternalParameters.dbPath = os.path.expanduser(options.dbpath)
    if options.local:
        InternalParameters.socket = socketName()
    if options.socket:
        InternalParameters.socket = options.socket
    Debug.setOptions(options.debug)
    Query.dbhandle = initDb()
    realm = MJRealm()
    realm.server = MJServer()
    kajonggPortal = portal.Portal(realm, [DBPasswordChecker()])
    # pylint: disable=E1101
    # pylint thinks reactor is missing listen* and run
    loadPredefinedRulesets()
    try:
        if InternalParameters.socket:
            if os.name == 'nt':
                logInfo('local server listening on 127.0.0.1 port %d' % options.port)
                reactor.listenTCP(options.port, pb.PBServerFactory(kajonggPortal),
                    interface='127.0.0.1')
            else:
                logInfo('local server listening on UNIX socket %s' % InternalParameters.socket)
                reactor.listenUNIX(InternalParameters.socket, pb.PBServerFactory(kajonggPortal))
        else:
            logInfo('server listening on port %d' % options.port)
            reactor.listenTCP(options.port, pb.PBServerFactory(kajonggPortal))
    except error.CannotListenError, errObj:
        logWarning(errObj)
Beispiel #22
0
 def stopNowAfterLastDisconnect(self):
     """as the name says"""
     if InternalParameters.socket and not InternalParameters.continueServer \
         and not self.users and reactor.running:
         logInfo('local server terminates. Reason: last client disconnected')
         reactor.stop()
Beispiel #23
0
 def printSelf(self):
     util.logInfo( 'Archives:' )
Beispiel #24
0
 def printSelf(self):
     util.logInfo( 'Category: %s %d %s', self.name, self.count, self.permalink )
Beispiel #25
0
 def printSelf(self):
     util.logInfo( 'Home: %s', self.permalink )
	def testPlexConfig(self):
		#1. Mock Boxee settings file is good
		util.logInfo('#1. Boxee settings file is good')
		tempdir = '__zzz'
		filename = 'registry.xml'
		filepath = os.path.join(os.getcwd(),tempdir)
		fullfilename = os.path.join(filepath,filename)
		os.mkdir(filepath)
		f = open(fullfilename,'w')
		f.write('<registry/>')
		f.close()
		xbmc.setMockProfilePath(filepath)
		config = plexee.PlexeeConfig()
		config.setManualHost('xxx')
		config1 = plexee.PlexeeConfig()
		self.assertEqual('xxx',config1.getManualHost(), 'Use mock Boxee config - Test config reads and writes correctly')
		os.remove(fullfilename)
		os.rmdir(filepath)
		util.logInfo('#1. END - Boxee settings file is good')

		#2. Mock Boxee file not accessible
		util.logInfo('#2. Mock Boxee file not accessible')
		xbmc.setMockProfilePath('.')
		config = plexee.PlexeeConfig()
		config.setManualHost('xxx')
		config1 = plexee.PlexeeConfig()
		self.assertEqual('xxx',config1.getManualHost(), 'Use alternate config - Test config reads and writes correctly')
		util.logInfo('#2. END - Mock Boxee file not accessible')

		#3. Mock Boxee file not accessible, get file again
		util.logInfo('#3. Mock Boxee file not accessible, get file again')
		config = plexee.PlexeeConfig()
		self.assertEqual('xxx',config.getManualHost(), 'Alternate config used again')
		util.logInfo('#3. END - Mock Boxee file not accessible, get file again')
Beispiel #27
0
 def printSelf(self):
     util.logInfo( 'Categories: %s', self.permalink )
Beispiel #28
0
 def export(self):    
     util.logInfo( '  %s [Designated]' % self.site.getRelativePath(self.source) )
     data = {'site': self.site, 'article': self}
     self.site.exportFile(self.exportFilePath, self.layout, data)
Beispiel #29
0
 def __init__(self, site, source, designated):
     super(DesignatedArticle, self).__init__(site, source)
     self.designated = designated
     util.logInfo( 'designated: %s => %s', source, self.designated )
Beispiel #30
0
            if not self.site.isLocalMode:
                return False

        # 检查date
        if not self.checkDateAvailable():
            util.logWarning( "invalid article: date error '%s'", relative_source_path )
            return False

        # 时间超出现在的文章
        if self.date > datetime.now():
            util.logWarning( "date out: %s", relative_source_path)
            return False

        # 不列出的文章
        if len(self.unlisted):
            util.logInfo( "unlisted in [%s]: '%s'", ', '.join(unicode("'" + s + "'") for s in self.unlisted if s), relative_source_path )

        # 检查修改时间
        if self.modify < self.date:
            self.modify = self.date

        # 唯一标识码 发布时间时间戳的后5位
        self.unique = ('%d' % util.timestamp(self.date))[-5:]

        # 解析分类 标签
        self.parseCategory()
        self.parseTag()
        
        # 获取内容
        self.content = ''
        self.summary = ''
Beispiel #31
0
	def playVideoUrl(self, fullUrl, subitem = None, offset=0):
		videoUrl = self.getUrl(self.getRootUrl(), fullUrl)
		data = mc.Http().Get(videoUrl)
		if data:
			tree = ElementTree.fromstring(data)
			videoNode = tree[0]
			playlist = mc.PlayList(mc.PlayList.PLAYLIST_VIDEO)
			playlist.Clear()

			thumbnailUrl = self.getThumbUrl(videoNode.attrib.get("thumb"), 100, 100)
			description = util.cleanString(videoNode.attrib.get("summary",""))
			title = util.cleanString(videoNode.attrib.get("title", "Plex Video"))
			contentRating = util.cleanString(videoNode.attrib.get("contentRating",""))
			
			for part in videoNode.findall("Media/Part"):
				li = mc.ListItem(mc.ListItem.MEDIA_VIDEO_CLIP)
				li.SetTitle(title)
				li.SetLabel(title)
				li.SetPath(self.getUrl(self.getRootUrl(), part.attrib.get("key")))
				li.SetThumbnail(thumbnailUrl)
				li.SetDescription(description, False)
				li.SetContentRating(contentRating)
				
				#TV Episode extras
				mediaType = videoNode.attrib.get("type","movie")
				if mediaType == 'episode':
					li.SetTVShowTitle(util.cleanString(videoNode.attrib.get("grandparentTitle","")))
					li.SetEpisode(int(videoNode.attrib.get('index')))
					li.SetSeason(int(videoNode.attrib.get('parentIndex')))
				
				playlist.Add(li)

			playlist.Play(0)
			
			#ok wait for player to start
			loop = 0
			util.logDebug("Waiting on player")
			while not xbmc.Player().isPlaying():
				xbmc.sleep(1000)
				loop = loop + 1
				if loop > 10:
					break
			
			util.logDebug("Player started...")
			#set any offset
			if offset != 0:
				xbmc.Player().seekTime(offset/1000)

			#Set subtitles
			subtitleKey = ""
			if subitem != None:
				subtitleKey = subitem.GetPath()
				
			if subtitleKey == "":
				import os
				noSubPath = os.path.join(mc.GetApp().GetAppMediaDir(), "media", "no_subs.srt")
				xbmc.Player().setSubtitles(noSubPath)
			else:
				util.logInfo("Setting subtitles to: " + subtitleKey)
				xbmc.Player().setSubtitles(subtitleKey)
			
			#Monitor playback and update progress to plex
			key = videoNode.attrib.get('ratingKey')
			self.monitorPlayback(key, offset)
			
		else:
			return None
Beispiel #32
0
 def printSelf(self):
     util.logInfo( 'Tags: %s', self.permalink )