Esempio n. 1
0
	def RedoSector(self, oldsector):
		try:
			#print dir(oldsector.vehicles)
			self.oldsector.vehicles.remove(self)
			#oldsector.structures.remove(self)
		except:
			pass
			#print '.',
		self.oldsector = Locale.getOnly().getSectorFromXY(self.position.x,self.position.y)
Esempio n. 2
0
def __run(_bundlePath):
    #
    # Initializes the framework, verifies the plug-in & extracts information, then enters a
    # run loop for handling requests.
    #
    global Identifier
    global Debug
    global __bundlePath
    global __pluginModule
    global __logFilePath
    global __requestHandlers
    global LastPrefix

    FirstRun = False
    random.seed()

    # Set up the support file paths
    pmsPath = "%s/Library/Application Support/Plex Media Server" % os.environ[
        "HOME"]
    supportFilesPath = "%s/Plug-in Support" % pmsPath
    frameworkSupportFilesPath = "%s/Framework Support" % pmsPath
    logFilesPath = "%s/Library/Logs/PMS Plugin Logs" % os.environ["HOME"]

    # Make sure framework directories exist
    def checkpath(path):
        try:
            if not os.path.exists(path): os.makedirs(path)
        except:
            pass

    checkpath("%s/Preferences" % supportFilesPath)
    checkpath("%s/Databases" % supportFilesPath)
    checkpath(logFilesPath)
    checkpath(frameworkSupportFilesPath)

    # Set the bundle path
    __bundlePath = _bundlePath.rstrip('/')

    # Add the bundle path to the system path, including any libraries
    if os.path.isdir("%s/Contents" % __bundlePath):
        sys.path.append("%s/Contents" % __bundlePath)
        if os.path.isdir("%s/Contents/Libraries" % __bundlePath):
            sys.path.append("%s/Contents/Libraries" % __bundlePath)
    else:
        print "Couldn't find bundle directory"
        return None

    # Open the Info.plist file
    f = open("%s/Contents/Info.plist" % __bundlePath, "r")
    infoplist = XML.ElementFromString(f.read())
    f.close()
    if infoplist is None:
        print "Couldn't load Info.plist file from plug-in"
        return

    # Get the plug-in identifier
    Identifier = infoplist.xpath(
        '//key[text()="CFBundleIdentifier"]//following-sibling::string/text()'
    )[0]
    if Identifier is None:
        print "Invalid Info.plist file in plug-in"
        return None

    # Set up the log file
    __logFilePath = "%s/%s.log" % (logFilesPath, Identifier)
    if os.path.exists(__logFilePath):
        if os.path.exists("%s.old" % __logFilePath):
            os.remove("%s.old" % __logFilePath)
        os.rename(__logFilePath, "%s.old" % __logFilePath)

    # Now we can start logging
    PMS.Log("(Framework) Bundle verification complete", False)

    # Check whether debugging is enabled
    try:
        _debug = infoplist.xpath(
            '//key[text()="PlexPluginDebug"]//following-sibling::string/text()'
        )[0]
        if _debug == "1":
            Debug = True
            PMS.Log("(Framework) Debugging is enabled")
    except:
        pass

    # Log the system encoding (set during bootstrap)
    PMS.Log("(Framework) Default encoding is " + sys.getdefaultencoding())

    # Set up framework paths
    Prefs.__prefsPath = "%s/Preferences/%s.xml" % (supportFilesPath,
                                                   Identifier)
    Data.__dataPath = "%s/Data/%s" % (supportFilesPath, Identifier)
    Data.__dataItemPath = "%s/DataItems" % Data.__dataPath
    if not os.path.isdir(Data.__dataItemPath):
        FirstRun = True
        os.makedirs(Data.__dataItemPath)
    Resource.__resourcePath = "%s/Contents/Resources" % __bundlePath
    Helper.__helperPath = "%s/Contents/Helpers" % __bundlePath
    Resource.__sharedResourcePath = "%s/Plug-ins/Framework.bundle/Contents/Resources/Versions/1/Resources" % pmsPath
    Database.__databasePath = "%s/Databases/%s.db" % (supportFilesPath,
                                                      Identifier)
    os.chdir(Data.__dataItemPath)
    Locale.SetDefaultLocale()
    PMS.Log("(Framework) Configured framework modules")

    # Attempt to import the plug-in module - if debugging is enabled, don't catch exceptions
    if Debug:
        import Code as _plugin
        PMS.Log("(Framework) Imported plug-in module")
    else:
        try:
            import Code as _plugin
            PMS.Log("(Framework) Imported plug-in module")
        except ImportError:
            PMS.Log("(Framework) Couldn't import plug-in from bundle")
            __exit()
            return

    # Load the list of trusted plug-ins
    _trusted = []
    try:
        _trustedJSON = Resource.LoadShared("trust.json")
        if _trustedJSON:
            _trusted = JSON.ObjectFromString(_trustedJSON)
    except:
        pass

    # Populate the permission lists
    __setupPermissionLists()

    # Register the plug-in with the framework
    __pluginModule = _plugin

    # Check the imported module to make sure nothing untoward is happening!
    if Identifier in _trusted:
        PMS.Log("(Framework) Plug-in is trusted, skipping module check")
    else:
        __scanModules()
        _allowed = []
        for n in PMS.__dict__:
            if n[0] != "_":
                if type(PMS.__dict__[n]).__name__ == "module":
                    _allowed.append(n)
        for n in __modWhitelist:
            _allowed.append(n)
        __checkModule(_plugin, _allowed)
        PMS.Log("(Framework) Checked module imports")

    # Initialize the framework modules
    Dict.__load()
    if not FirstRun:
        __checkFrameworkCompatibility()
    Prefs.__load()
    HTTP.__loadCookieJar()
    HTTP.__loadCache()
    PMS.Log("(Framework) Initialized framework modules")

    # Call the plug-in's Start method
    PMS.Log("(Framework) Attempting to start the plug-in...")
    __call(__pluginModule.Start)
    PMS.Log("(Framework) Plug-in started", False)

    # Start timers
    __startCacheManager(firstRun=FirstRun)

    PMS.Log("(Framework) Entering run loop")
    # Enter a run loop to handle requests
    while True:
        try:
            # Read the input
            path = raw_input()
            path = path.lstrip("GET ").strip()
            LastPrefix = None

            # Read headers
            headers = {}
            stop = False
            while stop == False:
                line = raw_input()
                if len(line) == 1:
                    stop = True
                else:
                    split = string.split(line.strip(), ":", maxsplit=1)
                    if len(split) == 2:
                        headers[split[0].strip()] = split[1].strip()

            # Set the locale
            if headers.has_key("X-Plex-Language"):
                loc = headers["X-Plex-Language"].lower()
                Locale.__loadLocale(loc)

            # Set the version
            if headers.has_key("X-Plex-Version"):
                Client.__setVersion(headers["X-Plex-Version"])

            # Extract arguments
            kwargs = {}
            mpath = path
            if path.find("?") >= 0:
                parts = path.split("?")
                mpath = parts[0]
                args = parts[1].split("&")
                for arg in args:
                    kwarg = arg.split("=")
                    if len(kwarg) == 2:
                        name = urllib.unquote(kwarg[0])
                        value = urllib.unquote(kwarg[1])
                        kwargs[name] = value
            if mpath[-1] == "/":
                mpath = mpath[:-1]

            # Split the path into components and decode.
            pathNouns = path.split('/')
            pathNouns = [urllib.unquote(p) for p in pathNouns]

            # If no input was given, return an error
            if len(pathNouns) <= 1:
                __return("%s\r\n\r\n" % PMS.Error['BadRequest'])

            # Otherwise, attempt to handle the request
            else:
                result = None
                pathNouns.pop(0)
                count = len(pathNouns)
                if pathNouns[-1] == "":
                    pathNouns.pop(len(pathNouns) - 1)
                PMS.Log("(Framework) Handling request :  %s" % path, False)

                # Check for a management request
                if pathNouns[0] == ":":
                    result = __handlePMSRequest(pathNouns, path, **kwargs)

                else:
                    handler = None
                    isPrefixHandler = False

                    # See if there's a prefix handler available
                    for key in __prefixHandlers:
                        if mpath.count(key, 0, len(key)) == 1:
                            LastPrefix = key
                    if mpath in __prefixHandlers:
                        handler = __prefixHandlers[mpath]["handler"]
                        isPrefixHandler = True

                    else:
                        # Check each request handler to see if it handles the current prefix
                        popped = False
                        for key in __requestHandlers:
                            if handler is None:
                                if path.count(key, 0, len(key)) == 1:
                                    # Remove the prefix from the path
                                    keyNounCount = len(key.split('/')) - 1
                                    for i in range(keyNounCount):
                                        pathNouns.pop(0)
                                    count = count - keyNounCount
                                    # Find the request handler
                                    handler = __requestHandlers[key]["handler"]
                                    LastPrefix = key
                                    popped = True

                        # If no path request handler was found, make sure we still pop the prefix so internal requests work
                        for key in __prefixHandlers:
                            if popped == False:
                                if mpath.count(key, 0, len(key)) == 1:
                                    keyNounCount = len(key.split('/')) - 1
                                    for i in range(keyNounCount):
                                        pathNouns.pop(0)
                                    popped = True

                    # Check whether we should handle the request internally
                    handled = False
                    if count > 0:
                        if pathNouns[0] == ":":
                            handled = True
                            result = __handleInternalRequest(
                                pathNouns, path, **kwargs)

                    # Check if the App Store has flagged the plug-in as broken
                    if os.path.exists(
                            os.path.join(frameworkSupportFilesPath,
                                         "%s.broken" % Identifier)):
                        #TODO: Localise this bit, use message from the App Store if available
                        handled = True
                        result = PMS.Objects.MessageContainer(
                            "Please try again later",
                            "This plug-in is currently unavailable")
                        PMS.Log("(Framework) Plug-in is flagged as broken")

                    # If the request hasn't been handled, and we have a valid request handler, call it
                    else:
                        if not handled and handler is not None:
                            if isPrefixHandler:
                                result = handler(**kwargs)
                            else:
                                result = handler(pathNouns, path, **kwargs)

                # If the request wasn't handled, return an error
                if result == None:
                    PMS.Log("(Framework) Request not handled by plug-in",
                            False)
                    response = "%s\r\n\r\n" % PMS.Error['NotFound']

                # If the plugin returned an error, return it to PMS
                elif result in PMS.Error.values():
                    PMS.Log(
                        "(Framework) Plug-in returned an error :  %s" % result,
                        False)
                    response = "%s\r\n" % result

                # Otherwise, check if a valid object was returned, and return the result
                elif __objectManager.ObjectHasBase(result, Objects.Object):
                    PMS.Log("(Framework) Response OK")
                    resultStr = result.Content()
                    resultStatus = result.Status()
                    resultHeaders = result.Headers()
                    if resultStr is not None:
                        resultLen = len(resultStr)
                        if resultLen > 0:
                            resultHeaders += "Content-Length: %i\r\n" % resultLen
                        resultStr = "\r\n%s" % resultStr
                    else:
                        resultStr = ""
                    response = str("%s\r\n%s" %
                                   (resultStatus, resultHeaders)) + str(
                                       resultStr) + str("\r\n")

                __return(response)

        # If a KeyboardInterrupt (SIGINT) is raised, stop the plugin
        except KeyboardInterrupt:
            # Save data & exit
            __saveData()
            __exit()

        except EOFError:
            # Save data & exit
            __saveData()
            __exit()

        # If another exception is raised, deal with the problem
        except:
            __except()
            __return("%s\r\n\r\n" % PMS.Error['InternalError'])

        # Make sure the plugin's data is saved
        finally:
            __saveData()
Esempio n. 3
0
def __run(_bundlePath):
  #
  # Initializes the plugin framework, verifies the plugin & extracts information, then enters a
  # run loop for handling requests. 
  #
  global BundlePath
  global ResourcesPath
  global Identifier
  global DataPath
  global Debug
  
  global __pluginModule
  global __prefs
  global __prefsPath
  global __databasePath
  global __logFilePath
  global __requestHandlers
  
  if sys.platform == "win32":
    if 'PLEXLOCALAPPDATA' in os.environ:
      key = 'PLEXLOCALAPPDATA'
    else:
      key = 'LOCALAPPDATA'
    supportFilesPath = os.path.join(os.environ[key], "Plex Media Server", "Plug-in Support")
    logFilesPath = os.path.join(os.environ[key], "Plex Media Server", "Logs", "PMS Plugin Logs")
  else:
    supportFilesPath = os.environ["HOME"] + "/Library/Application Support/Plex Media Server/Plug-in Support"
    logFilesPath = os.environ["HOME"] + "/Library/Logs/Plex Media Server/PMS Plugin Logs/"
  
  def checkpath(path):
    try:
      if not os.path.exists(path): os.makedirs(path)
    except:
      pass
  
  checkpath(supportFilesPath + "/Preferences")
  checkpath(supportFilesPath + "/Databases")
  checkpath(logFilesPath)
  
  # Set the bundle path variable
  BundlePath = _bundlePath.rstrip('/')
  ResourcesPath = BundlePath + "/Contents/Resources"
  
  # Add the bundle path to the system path
  if os.path.isdir(BundlePath + "/Contents"):
    sys.path.append(BundlePath + "/Contents")
    if os.path.isdir(BundlePath + "/Contents/Libraries"):
      sys.path.append(BundlePath + "/Contents/Libraries")
  else:
    print "Couldn't find bundle directory"
    return None
  
  # Open the Info.plist file
  infoplist = XML.ElementFromFile((BundlePath + "/Contents/Info.plist"))
  if infoplist is None:
    print "Couldn't load Info.plist file from plugin"
    return

  # Get the plugin identifier
  Identifier = infoplist.xpath('//key[text()="CFBundleIdentifier"]//following-sibling::string/text()')[0]
  if Identifier is None:
    print "Invalid Info.plist file in plugin"
    return None
    
  # Set up the log file
  __logFilePath = logFilesPath + Identifier + ".log"
  if os.path.exists(__logFilePath):
    if os.path.exists(__logFilePath + ".old"):
      os.remove(__logFilePath + ".old")
    os.rename(__logFilePath, __logFilePath + ".old")
  
  # Show a big warning message - Framework v0 is deprecated!!
  Log.Add("(Framework) Deprecated version\n\nNOTICE: This version of the Plex Media Framework is deprecated and is no longer supported.\nPlease migrate your code to a newer version. More information can be found at http://dev.plexapp.com/\n")
  
  Log.Add("(Framework) Plugin initialized", False)
  
  # Check whether debugging is enabled
  try:
    _debug = infoplist.xpath('//key[text()="PlexPluginDebug"]//following-sibling::string/text()')[0]
    if _debug == "1":
      Debug = True
      Log.Add("(Framework) Debugging is enabled")
  except: pass
  
  # Create the data path if it doesn't already exist
  DataPath = supportFilesPath + "/Data/" + Identifier
  if not os.path.isdir(DataPath):
    os.makedirs(DataPath)
  
  # Change directory to the data path
  os.chdir(DataPath)
  
  # If a preference file exists, load it
  __prefsPath = supportFilesPath + "/Preferences/" + Identifier + ".xml"
  defaultsPath = BundlePath + "/Contents/Defaults.xml"
  if os.path.exists(__prefsPath):
    __prefs = XML.ElementFromFile(__prefsPath)
    Log.Add("(Framework) Loaded user preferences")

  # Otherwise, try to apply the defaults file
  elif os.path.exists(defaultsPath):
    __prefs = XML.ElementFromFile(defaultsPath)
    Log.Add("(Framework) Loaded default preferences")
    
  # If no preferences were loaded, create an empty preferences element
  else:
    __prefs = XML.Element("PluginPreferences")
  
  # Load the plugin's dictionary file
  LoadDict()
  
  # Load the plugin's localization strings
  Locale.__loadDefaults()
  # TODO: Retrieve locale info from PMS for overriding default dict strings 
  # Locale.__loadLocale(loc)
  
  # Set the database file path
  __databasePath = supportFilesPath + "/Databases/" + Identifier + ".db"
  
  # Initialize the plugin's CookieJar
  HTTP.__loadCookieJar()
  Log.Add("(Framework) Loaded cookie jar")
  
  if HTTP_TIMEOUT_VAR_NAME in os.environ:
    HTTP.SetTimeout(float(os.environ[HTTP_TIMEOUT_VAR_NAME]))
  else:
    HTTP.SetTimeout(HTTP_DEFAULT_TIMEOUT)
  
  # Attempt to import the plugin module - if debugging is enabled, don't catch exceptions
  if Debug:
    import Code as _plugin
    Log.Add("(Framework) Imported plugin module")
  else:
    try:
      import Code as _plugin
      Log.Add("(Framework) Imported plugin module")
    except ImportError:
      Log.Add("(Framework) Couldn't import plugin from bundle")
      return
  
  __pluginModule = _plugin
  
  # Call the plugin's Start method
  Log.Add("(Framework) Attempting to start the plugin...")
  __call(_plugin.Start)
  Log.Add("(Framework) Plugin started", False)


  Log.Add("(Framework) Entering run loop")
  # Enter a run loop to handle requests
  while True:
    try:
      # Read the input
      path = raw_input()
      
      # Strip GET from the start of the path
      path = path.lstrip("GET ").strip()
      
      # Split the path into components and decode.
      pathNouns = path.replace('?query=', '/').split('/')
      pathNouns = [urllib.unquote(p) for p in pathNouns]
      
      # If no input was given, return an error
      if len(pathNouns) <= 1:
        sys.stdout.write("%s\r\n\r\n" % PMS.Error['BadRequest'])
        sys.stdout.flush()
        
      # Otherwise, attempt to handle the request
      else:
        Response['Content-Type'] = 'application/xml'
        Response['Status'] = '200 OK'
        Response["Headers"] = ""
        result = None
        pathNouns.pop(0)
        count = len(pathNouns)
        if pathNouns[count-1] == "":
          count = count - 1
          pathNouns.pop(len(pathNouns)-1)
          
        Log.Add("(Framework) Handling request :  " + path, False)
        
        # Check for a management request
        if pathNouns[0] == ":":
          result = __handlePMSRequest(pathNouns, count)

        else:  
          # Check each request handler to see if it handles the current prefix
          handler = None
          for key in __requestHandlers:
            if handler is None:
              if path.count(key, 0, len(key)) == 1:
                # Remove the prefix from the path
                keyNounCount = len(key.split('/')) - 1
                for i in range(keyNounCount):
                  pathNouns.pop(0)
                count = count - keyNounCount
                # Find the request handler
                handler = __requestHandlers[key]["handler"]
                
          # Check whether we should handle the request internally
          handled = False
          if count > 0:
            if pathNouns[0] == ":":
              handled = True
              result = __handleInternalRequest(pathNouns, count)
    
          # If the request hasn't been handled, and we have a valid request handler, call it
          if not handled and handler is not None:
            result = handler(pathNouns, count)
        
        # If the request wasn't handled, return an error
        if result == None:
          Log.Add("(Framework) Request not handled by plugin", False)
          response = "%s\r\n\r\n" % PMS.Error['NotFound']
          
        # If the plugin returned an error, return it to PMS
        elif result in PMS.Error.values():
          Log.Add("(Framework) Plug-in returned an error :  %s" % result, False)
          response = result + "\r\n"
          
        # Otherwise, return the result
        else:
          Log.Add("(Framework) Response OK")
          response = "%s\r\nContent-Type: %s\r\nContent-Length: %i\r\n%s\r\n%s\r\n" % \
            (Response["Status"], str(Response['Content-Type']), len(result), Response["Headers"], result)

        sys.stdout.write(response)
        sys.stdout.flush()
    
    # If a KeyboardInterrupt (SIGINT) is raised, stop the plugin
    except KeyboardInterrupt:
      # Commit any changes to the database and close it
      if DB.__db is not None:
        DB.Commit()
        DB.__db.close()
      # Save the dictionary
      SaveDict()
      # Exit
      sys.exit()
    
    except EOFError:
      # Commit any changes to the database and close it
      if DB.__db is not None:
        DB.Commit()
        DB.__db.close()
      Log.Add("(Framework) Plugin stopped")
      sys.exit()
          
    # If another exception is raised, deal with the problem
    except:
      # If in debug mode, print the traceback, otherwise report an internal error
      if Debug:
        Log.Add("(Framework) An exception happened:\n%s" % traceback.format_exc())
      else:
        Log.Add("(Framework) An internal error occurred", False)
      sys.stdout.write("%s\r\n\r\n" % PMS.Error['InternalError'])
      sys.stdout.flush()
    
    # Make sure the plugin's dictionary is saved
    finally:
      SaveDict()
Esempio n. 4
0
def F(key, *args): return Locale.LocalStringWithFormat(key, *args)
def E(string): return String.Encode(string)
Esempio n. 5
0
def L(string): return Locale.LocalString(string)
def F(key, *args): return Locale.LocalStringWithFormat(key, *args)
def __run(_bundlePath):
  #
  # Initializes the plugin framework, verifies the plugin & extracts information, then enters a
  # run loop for handling requests. 
  #
  global BundlePath
  global ResourcesPath
  global Identifier
  global DataPath
  global Debug
  
  global __pluginModule
  global __prefs
  global __prefsPath
  global __databasePath
  global __logFilePath
  global __requestHandlers
  
  if sys.platform == "win32":
    if 'PLEXLOCALAPPDATA' in os.environ:
      key = 'PLEXLOCALAPPDATA'
    else:
      key = 'LOCALAPPDATA'
    supportFilesPath = os.path.join(os.environ[key], "Plex Media Server", "Plug-in Support")
    logFilesPath = os.path.join(os.environ[key], "Plex Media Server", "Logs", "PMS Plugin Logs")
  else:
    supportFilesPath = os.environ["HOME"] + "/Library/Application Support/Plex Media Server/Plug-in Support"
    logFilesPath = os.environ["HOME"] + "/Library/Logs/PMS Plugin Logs/"
  
  def checkpath(path):
    try:
      if not os.path.exists(path): os.makedirs(path)
    except:
      pass
  
  checkpath(supportFilesPath + "/Preferences")
  checkpath(supportFilesPath + "/Databases")
  checkpath(logFilesPath)
  
  # Set the bundle path variable
  BundlePath = _bundlePath.rstrip('/')
  ResourcesPath = BundlePath + "/Contents/Resources"
  
  # Add the bundle path to the system path
  if os.path.isdir(BundlePath + "/Contents"):
    sys.path.append(BundlePath + "/Contents")
    if os.path.isdir(BundlePath + "/Contents/Libraries"):
      sys.path.append(BundlePath + "/Contents/Libraries")
  else:
    print "Couldn't find bundle directory"
    return None
  
  # Open the Info.plist file
  infoplist = XML.ElementFromFile((BundlePath + "/Contents/Info.plist"))
  if infoplist is None:
    print "Couldn't load Info.plist file from plugin"
    return

  # Get the plugin identifier
  Identifier = infoplist.xpath('//key[text()="CFBundleIdentifier"]//following-sibling::string/text()')[0]
  if Identifier is None:
    print "Invalid Info.plist file in plugin"
    return None
    
  # Set up the log file
  __logFilePath = logFilesPath + Identifier + ".log"
  if os.path.exists(__logFilePath):
    if os.path.exists(__logFilePath + ".old"):
      os.remove(__logFilePath + ".old")
    os.rename(__logFilePath, __logFilePath + ".old")
  
  # Show a big warning message - Framework v0 is deprecated!!
  Log.Add("(Framework) Deprecated version\n\nNOTICE: This version of the Plex Media Framework is deprecated and is no longer supported.\nPlease migrate your code to a newer version. More information can be found at http://dev.plexapp.com/\n")
  
  Log.Add("(Framework) Plugin initialized", False)
  
  # Check whether debugging is enabled
  try:
    _debug = infoplist.xpath('//key[text()="PlexPluginDebug"]//following-sibling::string/text()')[0]
    if _debug == "1":
      Debug = True
      Log.Add("(Framework) Debugging is enabled")
  except: pass
  
  # Create the data path if it doesn't already exist
  DataPath = supportFilesPath + "/Data/" + Identifier
  if not os.path.isdir(DataPath):
    os.makedirs(DataPath)
  
  # Change directory to the data path
  os.chdir(DataPath)
  
  # If a preference file exists, load it
  __prefsPath = supportFilesPath + "/Preferences/" + Identifier + ".xml"
  defaultsPath = BundlePath + "/Contents/Defaults.xml"
  if os.path.exists(__prefsPath):
    __prefs = XML.ElementFromFile(__prefsPath)
    Log.Add("(Framework) Loaded user preferences")

  # Otherwise, try to apply the defaults file
  elif os.path.exists(defaultsPath):
    __prefs = XML.ElementFromFile(defaultsPath)
    Log.Add("(Framework) Loaded default preferences")
    
  # If no preferences were loaded, create an empty preferences element
  else:
    __prefs = XML.Element("PluginPreferences")
  
  # Load the plugin's dictionary file
  LoadDict()
  
  # Load the plugin's localization strings
  Locale.__loadDefaults()
  # TODO: Retrieve locale info from PMS for overriding default dict strings 
  # Locale.__loadLocale(loc)
  
  # Set the database file path
  __databasePath = supportFilesPath + "/Databases/" + Identifier + ".db"
  
  # Initialize the plugin's CookieJar
  HTTP.__loadCookieJar()
  Log.Add("(Framework) Loaded cookie jar")
  
  if HTTP_TIMEOUT_VAR_NAME in os.environ:
    HTTP.SetTimeout(float(os.environ[HTTP_TIMEOUT_VAR_NAME]))
  else:
    HTTP.SetTimeout(HTTP_DEFAULT_TIMEOUT)
  
  # Attempt to import the plugin module - if debugging is enabled, don't catch exceptions
  if Debug:
    import Code as _plugin
    Log.Add("(Framework) Imported plugin module")
  else:
    try:
      import Code as _plugin
      Log.Add("(Framework) Imported plugin module")
    except ImportError:
      Log.Add("(Framework) Couldn't import plugin from bundle")
      return
  
  __pluginModule = _plugin
  
  # Call the plugin's Start method
  Log.Add("(Framework) Attempting to start the plugin...")
  __call(_plugin.Start)
  Log.Add("(Framework) Plugin started", False)


  Log.Add("(Framework) Entering run loop")
  # Enter a run loop to handle requests
  while True:
    try:
      # Read the input
      path = raw_input()
      
      # Strip GET from the start of the path
      path = path.lstrip("GET ").strip()
      
      # Split the path into components and decode.
      pathNouns = path.replace('?query=', '/').split('/')
      pathNouns = [urllib.unquote(p) for p in pathNouns]
      
      # If no input was given, return an error
      if len(pathNouns) <= 1:
        sys.stdout.write("%s\r\n\r\n" % PMS.Error['BadRequest'])
        sys.stdout.flush()
        
      # Otherwise, attempt to handle the request
      else:
        Response['Content-Type'] = 'application/xml'
        Response['Status'] = '200 OK'
        Response["Headers"] = ""
        result = None
        pathNouns.pop(0)
        count = len(pathNouns)
        if pathNouns[count-1] == "":
          count = count - 1
          pathNouns.pop(len(pathNouns)-1)
          
        Log.Add("(Framework) Handling request :  " + path, False)
        
        # Check for a management request
        if pathNouns[0] == ":":
          result = __handlePMSRequest(pathNouns, count)

        else:  
          # Check each request handler to see if it handles the current prefix
          handler = None
          for key in __requestHandlers:
            if handler is None:
              if path.count(key, 0, len(key)) == 1:
                # Remove the prefix from the path
                keyNounCount = len(key.split('/')) - 1
                for i in range(keyNounCount):
                  pathNouns.pop(0)
                count = count - keyNounCount
                # Find the request handler
                handler = __requestHandlers[key]["handler"]
                
          # Check whether we should handle the request internally
          handled = False
          if count > 0:
            if pathNouns[0] == ":":
              handled = True
              result = __handleInternalRequest(pathNouns, count)
    
          # If the request hasn't been handled, and we have a valid request handler, call it
          if not handled and handler is not None:
            result = handler(pathNouns, count)
        
        # If the request wasn't handled, return an error
        if result == None:
          Log.Add("(Framework) Request not handled by plugin", False)
          response = "%s\r\n\r\n" % PMS.Error['NotFound']
          
        # If the plugin returned an error, return it to PMS
        elif result in PMS.Error.values():
          Log.Add("(Framework) Plug-in returned an error :  %s" % result, False)
          response = result + "\r\n"
          
        # Otherwise, return the result
        else:
          Log.Add("(Framework) Response OK")
          response = "%s\r\nContent-Type: %s\r\nContent-Length: %i\r\n%s\r\n%s\r\n" % \
            (Response["Status"], str(Response['Content-Type']), len(result), Response["Headers"], result)

        sys.stdout.write(response)
        sys.stdout.flush()
    
    # If a KeyboardInterrupt (SIGINT) is raised, stop the plugin
    except KeyboardInterrupt:
      # Commit any changes to the database and close it
      if DB.__db is not None:
        DB.Commit()
        DB.__db.close()
      # Save the dictionary
      SaveDict()
      # Exit
      sys.exit()
    
    except EOFError:
      # Commit any changes to the database and close it
      if DB.__db is not None:
        DB.Commit()
        DB.__db.close()
      Log.Add("(Framework) Plugin stopped")
      sys.exit()
          
    # If another exception is raised, deal with the problem
    except:
      # If in debug mode, print the traceback, otherwise report an internal error
      if Debug:
        Log.Add("(Framework) An exception happened:\n%s" % traceback.format_exc())
      else:
        Log.Add("(Framework) An internal error occurred", False)
      sys.stdout.write("%s\r\n\r\n" % PMS.Error['InternalError'])
      sys.stdout.flush()
    
    # Make sure the plugin's dictionary is saved
    finally:
      SaveDict()
Esempio n. 7
0
#Anthony Griggs
#HVGC 2018 Game
#Main Game File

from Player import *
from Locale import *
from NPC import *

gCont = "continue"
Pan = Player()

#Define Locales
pParkingE = Locale(
    0,
    "You get your bearings straight. Now what? Perhaps you should check in.",
    "You are in the parking lot.",
    "There doesn't seem many people or cars around, besides you and yours. Is that a good thing?",
    ["Your car"])
pParkingW = Locale(
    1,
    "You begin walking down the parking lot, making your way towards the hotel entrance.",
    "You are in the parking lot",
    "Sunrise Hotel. It gives a nice tropical vibe, doesn't it? Too bad there's no beach nearby!",
    [])
pEntrance = Locale(
    2,
    "You reach the entrance to the hotel. You are eager to check in and officially begin your time off.",
    "You are at the entrance of the hotel.", "", [])
pLobby = Locale(
    3, "You enter the hotel lobby. Quaint.", "You are in the hotel lobby.",
    "Like its name, the lobby of the hotel is themed with a tropical mindset."
Esempio n. 8
0
def L(string):
    return Locale.LocalString(string)
def __run(_bundlePath):
  #
  # Initializes the framework, verifies the plug-in & extracts information, then enters a
  # run loop for handling requests. 
  #
  global Identifier
  global Debug
  global __bundlePath  
  global __pluginModule
  global __logFilePath
  global __requestHandlers
  global LastPrefix
  
  FirstRun = False
  random.seed()
  
  # Set up the support file paths
  if sys.platform == "win32":
    if 'PLEXLOCALAPPDATA' in os.environ:
      key = 'PLEXLOCALAPPDATA'
    else:
      key = 'LOCALAPPDATA'
    pmsPath = os.path.join(os.environ[key], 'Plex Media Server')
    logFilesPath = os.path.join(os.environ[key], "Plex Media Server", "Logs", "PMS Plugin Logs")
  else:
    pmsPath = "%s/Library/Application Support/Plex Media Server" % os.environ["HOME"]
    logFilesPath = "%s/Library/Logs/PMS Plugin Logs" % os.environ["HOME"]
  
  supportFilesPath = "%s/Plug-in Support" % pmsPath
  frameworkSupportFilesPath = "%s/Framework Support" % pmsPath
  
  # Make sure framework directories exist
  def checkpath(path):
    try:
      if not os.path.exists(path): os.makedirs(path)
    except:
      pass
  
  checkpath("%s/Preferences" % supportFilesPath)
  checkpath("%s/Databases" % supportFilesPath)
  checkpath(logFilesPath)
  checkpath(frameworkSupportFilesPath)
    
  # Set the bundle path
  __bundlePath = _bundlePath.rstrip('/')
  
  # Add the bundle path to the system path, including any libraries
  if os.path.isdir("%s/Contents" % __bundlePath):
    sys.path.append("%s/Contents" % __bundlePath)
    if os.path.isdir("%s/Contents/Libraries" % __bundlePath):
      sys.path.append("%s/Contents/Libraries" % __bundlePath)
  else:
    print "Couldn't find bundle directory"
    return None
  
  # Open the Info.plist file
  f = open("%s/Contents/Info.plist" % __bundlePath, "r")
  infoplist = XML.ElementFromString(f.read())
  f.close()
  if infoplist is None:
    print "Couldn't load Info.plist file from plug-in"
    return

  # Get the plug-in identifier
  Identifier = infoplist.xpath('//key[text()="CFBundleIdentifier"]//following-sibling::string/text()')[0]
  if Identifier is None:
    print "Invalid Info.plist file in plug-in"
    return None
    
  # Set up the log file
  __logFilePath = "%s/%s.log" % (logFilesPath, Identifier)
  if os.path.exists(__logFilePath):
    if os.path.exists("%s.old" % __logFilePath):
      os.remove("%s.old" % __logFilePath)
    os.rename(__logFilePath, "%s.old" % __logFilePath)
  
  # Now we can start logging
  PMS.Log("(Framework) Bundle verification complete", False)
  
  # Check whether debugging is enabled
  try:
    _debug = infoplist.xpath('//key[text()="PlexPluginDebug"]//following-sibling::string/text()')[0]
    if _debug == "1":
      Debug = True
      PMS.Log("(Framework) Debugging is enabled")
  except: pass

  # Log the system encoding (set during bootstrap)
  PMS.Log("(Framework) Default encoding is " + sys.getdefaultencoding())

  # Set up framework paths
  Prefs.__prefsPath = "%s/Preferences/%s.xml" % (supportFilesPath, Identifier)
  Data.__dataPath = "%s/Data/%s" % (supportFilesPath, Identifier)
  Data.__dataItemPath = "%s/DataItems" % Data.__dataPath
  if not os.path.isdir(Data.__dataItemPath):
    FirstRun = True
    os.makedirs(Data.__dataItemPath)
  Resource.__resourcePath = "%s/Contents/Resources" % __bundlePath
  Helper.__helperPath = "%s/Contents/Helpers" % __bundlePath
  Resource.__sharedResourcePath = "%s/Plug-ins/Framework.bundle/Contents/Resources/Versions/1/Resources" % pmsPath
  Database.__databasePath = "%s/Databases/%s.db" % (supportFilesPath, Identifier)
  os.chdir(Data.__dataItemPath)
  Locale.SetDefaultLocale()
  PMS.Log("(Framework) Configured framework modules")

  # Attempt to import the plug-in module - if debugging is enabled, don't catch exceptions
  if Debug:
    import Code as _plugin
    PMS.Log("(Framework) Imported plug-in module")
  else:
    try:
      import Code as _plugin
      PMS.Log("(Framework) Imported plug-in module")
    except ImportError:
      PMS.Log("(Framework) Couldn't import plug-in from bundle")
      __exit()
      return
      
  # Load the list of trusted plug-ins
  _trusted = []
  try:
    _trustedJSON = Resource.LoadShared("trust.json")
    if _trustedJSON:
      _trusted = JSON.ObjectFromString(_trustedJSON)
  except:
    pass

  # Populate the permission lists
  __setupPermissionLists()

  # Register the plug-in with the framework
  __pluginModule = _plugin

  # Check the imported module to make sure nothing untoward is happening!
  if Identifier in _trusted:
    PMS.Log("(Framework) Plug-in is trusted, skipping module check")
  else:
    __scanModules()
    _allowed = []
    for n in PMS.__dict__:
      if n[0] != "_":
        if type(PMS.__dict__[n]).__name__ == "module":
          _allowed.append(n)
    for n in __modWhitelist:
      _allowed.append(n)
    __checkModule(_plugin, _allowed)
    PMS.Log("(Framework) Checked module imports")

  # Initialize the framework modules
  Dict.__load()
  if not FirstRun:
    __checkFrameworkCompatibility()
  Prefs.__load()
  HTTP.__loadCookieJar()
  HTTP.__loadCache()
  if HTTP_TIMEOUT_VAR_NAME in os.environ:
    HTTP.SetTimeout(float(os.environ[HTTP_TIMEOUT_VAR_NAME]))
  else:
    HTTP.SetTimeout(HTTP_DEFAULT_TIMEOUT)
  PMS.Log("(Framework) Initialized framework modules")

  # Call the plug-in's Start method
  PMS.Log("(Framework) Attempting to start the plug-in...")
  __call(__pluginModule.Start)
  PMS.Log("(Framework) Plug-in started", False)

  # Start timers
  __startCacheManager(firstRun=FirstRun)
  
  PMS.Log("(Framework) Entering run loop")
  # Enter a run loop to handle requests
  while True:
    try:
      # Read the input
      path = raw_input()
      path = path.lstrip("GET ").strip()
      LastPrefix = None
      
      # Read headers
      headers = {}
      stop = False
      while stop == False:
        line = raw_input()
        if len(line) == 1:
          stop = True
        else:
          split = string.split(line.strip(), ":", maxsplit=1)
          if len(split) == 2:
            headers[split[0].strip()] = split[1].strip()

      # Set the locale
      if headers.has_key("X-Plex-Language"):
        loc = headers["X-Plex-Language"].lower()
        Locale.__loadLocale(loc)
        
      # Set the version
      if headers.has_key("X-Plex-Version"):
        Client.__setVersion(headers["X-Plex-Version"])

      PMS.Request.Headers.clear()
      PMS.Request.Headers.update(headers)
      
      req = urlparse.urlparse(path)
      path = req.path
      qs_args = cgi.parse_qs(req.query)
      kwargs = {}
      if 'function_args' in qs_args:
        try:
          unquoted_args = urllib.unquote(qs_args['function_args'][0])
          decoded_args = PMS.String.Decode(unquoted_args)
          kwargs = cerealizer.loads(decoded_args)
        except:
          PMS.Log(PMS.Plugin.Traceback())
          raise Exception("Unable to deserialize arguments")
      
      for arg_name in qs_args:
        if arg_name != 'function_args':
          kwargs[arg_name] = qs_args[arg_name][0]
      
      # First, try to match a connected route
      rpath = path
      for key in __prefixHandlers:
        if rpath.count(key, 0, len(key)) == 1:
          rpath = rpath[len(key):]
          break
      f, route_kwargs = MatchRoute(rpath)
      
      if f is not None:
        PMS.Log("(Framework) Handling route request :  %s" % path, False)
        route_kwargs.update(kwargs)
        result = f(**route_kwargs)

      # No route, fall back to other path handling methods
      else:
        mpath = path
        
        if mpath[-1] == "/":
          mpath = mpath[:-1]
        
        # Split the path into components and decode.
        pathNouns = path.split('/')
        pathNouns = [urllib.unquote(p) for p in pathNouns]
      
        # If no input was given, return an error
        if len(pathNouns) <= 1:
          __return("%s\r\n\r\n" % PMS.Error['BadRequest'])
        
        # Otherwise, attempt to handle the request
        else:
          result = None
          pathNouns.pop(0)
          count = len(pathNouns)
          if pathNouns[-1] == "":
            pathNouns.pop(len(pathNouns)-1)
          PMS.Log("(Framework) Handling request :  %s" % path, False)
        
          # Check for a management request
          if pathNouns[0] == ":":
            result = __handlePMSRequest(pathNouns, path, **kwargs)

          else:  
            handler = None
            isPrefixHandler = False
          
            # See if there's a prefix handler available
            for key in __prefixHandlers:
              if mpath.count(key, 0, len(key)) == 1:
                LastPrefix = key
            if mpath in __prefixHandlers:
              handler = __prefixHandlers[mpath]["handler"]
              isPrefixHandler = True
            
            else:
              # Check each request handler to see if it handles the current prefix
              popped = False
              for key in __requestHandlers:
                if handler is None:
                  if path.count(key, 0, len(key)) == 1:
                    # Remove the prefix from the path
                    keyNounCount = len(key.split('/')) - 1
                    for i in range(keyNounCount):
                      pathNouns.pop(0)
                    count = count - keyNounCount
                    # Find the request handler
                    handler = __requestHandlers[key]["handler"]
                    LastPrefix = key
                    popped = True
            
              # If no path request handler was found, make sure we still pop the prefix so internal requests work
              for key in __prefixHandlers:
                if popped == False:
                  if mpath.count(key, 0, len(key)) == 1:
                    keyNounCount = len(key.split('/')) - 1
                    for i in range(keyNounCount):
                      pathNouns.pop(0)
                    popped = True

            # Check whether we should handle the request internally
            handled = False
            if count > 0:
              if pathNouns[0] == ":":
                handled = True
                result = __handleInternalRequest(pathNouns, path, **kwargs)
    
          
            # Check if the App Store has flagged the plug-in as broken
            if os.path.exists(os.path.join(frameworkSupportFilesPath, "%s.broken" % Identifier)):
              #TODO: Localise this bit, use message from the App Store if available
              handled = True
              result = PMS.Objects.MessageContainer("Please try again later", "This plug-in is currently unavailable")
              PMS.Log("(Framework) Plug-in is flagged as broken")
          
            # If the request hasn't been handled, and we have a valid request handler, call it
            else:
              if not handled and handler is not None:
                if isPrefixHandler:
                  result = handler(**kwargs)
                else:
                  result = handler(pathNouns, path, **kwargs)
        
      response = None
      
      # If the request wasn't handled, return an error
      if result == None:
        PMS.Log("(Framework) Request not handled by plug-in", False)
        response = "%s\r\n\r\n" % PMS.Error['NotFound']
        
      # If the plugin returned an error, return it to PMS
      elif result in PMS.Error.values():
        PMS.Log("(Framework) Plug-in returned an error :  %s" % result, False)
        response = "%s\r\n\r\n" % result
        
      # Otherwise, check if a valid object was returned, and return the result
      elif __objectManager.ObjectHasBase(result, Objects.Object):
        resultStr = result.Content()
        resultStatus = result.Status()
        resultHeaders = result.Headers()
      
      elif isinstance(result, basestring):
        resultStr = result
        resultStatus = '200 OK'
        resultHeaders = "Content-type: text/plain\r\n"
      
      if resultStr is not None:
        PMS.Log("(Framework) Response OK")
        resultLen = len(resultStr)
        if resultLen > 0:
          resultHeaders += "Content-Length: %i\r\n" % resultLen
          resultStr = "\r\n"+resultStr
        
      else:
        resultStr = ""
        resultStatus = '500 Internal Server Error'
        resultHeaders = ''
        PMS.Log("(Framework) Unknown response type")
        
      if response == None:
        response = str("%s\r\n%s" % (resultStatus, resultHeaders)) + str(resultStr) + str("\r\n")
      
      #PMS.Log("\n---\n"+response+"---\n")
        
      __return(response)
    
    # If a KeyboardInterrupt (SIGINT) is raised, stop the plugin
    except KeyboardInterrupt:
      # Save data & exit
      __saveData()
      __exit()     
    
    except EOFError:
      # Save data & exit
      __saveData()
      __exit()
          
    # If another exception is raised, deal with the problem
    except:
      __except()
      __return("%s\r\n\r\n" % PMS.Error['InternalError'])
    
    # Make sure the plugin's data is saved
    finally:
      __saveData()