def __init__(self, registrar): super(Music, self).__init__(registrar) settings = ConfigParser.SafeConfigParser() settings.read(utils.get_plugin_settings_paths(__name__)) hostname = "localhost" port = 6600 try: hostname = settings.get("MPD", "hostname") port = settings.get("MPD", "port") except ConfigParser.NoSectionError: raise plugin.PluginLoadError("'MPD' section in config does not exist.") except ConfigParser.NoOptionError as err: if err.section == "hostname": logger.log("MPD hostname not in settings. " "Using default of '{0}'".format(hostname)) elif err.section == "port": logger.log("MPD port not in settings. " "Using default of '{0}'".format(port)) except TypeError: logger.log("Error loading settings for MPD. Using host and port " "{0}:{1}.".format(hostname, port)) self.client = mpd.MPDClient() self.client.connect(hostname, port) self.version = tuple(int(i) for i in self.client.mpd_version.split('.')) registrar.register_service("play", self.play, {"target": []}, namespace=__name__) registrar.register_service("listen", self.play, {"target": ["listen to"]}, namespace=__name__) registrar.register_service("pause", self.pause, {}, namespace=__name__) registrar.register_service("stop", self.stop, {}, namespace=__name__) registrar.register_service("song", self.song, { "next": ["next"], "previous": ["previous"], }, namespace=__name__)
def __init__(self, registrar): super(Memo, self).__init__(registrar) # Load command settings from a configuration file self.settings = ConfigParser.SafeConfigParser() self.settings.read(utils.get_plugin_settings_paths(__name__)) if not self.settings.has_option('Settings', 'memo_file'): raise plugin.PluginLoadError( "Error: no memo file provided in the config.") usage = ("USAGE: %s message\n" "Appends message to the file specified " "in the configuration file.") registrar.register_service("memo", self.execute, grammar={"memo": []}, usage=usage, namespace=__name__) registrar.register_service("remember", self.execute, grammar={"memo": []}, usage=usage, namespace=__name__)
def execute(self, **kwargs): """Retrieve mail from a GMail account through curl.""" # Load command settings from a configuration file settings = ConfigParser.SafeConfigParser() settings.read(utils.get_plugin_settings_paths(__name__)) try: username = settings.get("Credentials", "username") password = settings.get("Credentials", "password") except ConfigParser.NoOptionError: raise plugin.UnsuccessfulExecution( "Error: username/password " "not provided in settings file.") cmd = ("curl -u {0}:{1} --silent \"https://mail.google.com/mail/" "feed/atom\" | tr -d '\n' | awk -F '<entry>' '{" "for (i=2; i<=NF; i++) {print $i}}' | " "sed -n \"s/<title>\\(.*\)<\\/title.*name>\\(.*\\)" "<\\/name>.*/\\2 - \\1/p\"".format(username, password)) proc = sp.Popen(cmd, stdout=sp.PIPE, stderr=sp.PIPE, shell=True) out, err = proc.communicate() if out == "": out = "No mail." if len(out) == 0: raise plugin.UnsuccessfulExecution(err) return out
def __init__(self, registrar): super(Weather, self).__init__(registrar) self.ttl = 3600 # seconds self.last = None # last weather value recorded, tuple of (location, value) settings = ConfigParser.SafeConfigParser() settings.read(utils.get_plugin_settings_paths(__name__)) try: self.api_key = settings.get("Settings", "wunderground_api_key") except ConfigParser.Error: raise plugin.PluginLoadError("Must provide " "wunderground_api_key in Settings.") self.format = 'F' try: scale = settings.get("Settings", "temp_scale").upper() if scale in ('F', 'C', 'K'): self.format = scale except ConfigParser.Error: pass self.max_cache_distance = 25 try: self.max_cache_distance = int( settings.get("Settings", "max_cache_distance")) except (ConfigParser.Error, TypeError): pass self.CacheItem = namedtuple('CacheItem', ['expires', 'val']) self.locations = {} try: self.locations = dict( (key, value) for key, value in settings.items("Aliases")) except ConfigParser.NoSectionError: logger.log("No section 'Aliases' found in weather config file.") # remove spaces after commas - these would screw up lat/long searches for loc in self.locations: self.locations[loc] = re.sub(',\s*', ',', self.locations[loc]) # dict of location:CacheItem pairs # if current time in sec since epoch is less than ttl, cache has expired # should return val if cache is still valid self.cache = {} grammar = { "when": ["for", "be like"], "where": ["at", "near", "in", 'for'], } registrar.register_service("weather", self.execute, grammar=grammar, usage=""" USAGE: %s [location|alias] Returns the weather for a provided location or alias. If no location is provided, gets the weather data for the last recorded position. """, namespace=__name__)
def test_settings_paths(self): self.assertTrue( any( os.path.isdir(os.path.dirname(fil)) for fil in utils.get_app_settings_paths("module"))) self.assertTrue( any( os.path.isdir(os.path.dirname(fil)) for fil in utils.get_plugin_settings_paths("module")))
def __init__(self, registrar): super(Weather, self).__init__(registrar) self.ttl = 3600 # seconds self.last = None # last weather value recorded, tuple of (location, value) settings = ConfigParser.SafeConfigParser() settings.read(utils.get_plugin_settings_paths(__name__)) try: self.api_key = settings.get("Settings", "wunderground_api_key") except ConfigParser.Error: raise plugin.PluginLoadError("Must provide " "wunderground_api_key in Settings.") self.format = 'F' try: scale = settings.get("Settings", "temp_scale").upper() if scale in ('F', 'C', 'K'): self.format = scale except ConfigParser.Error: pass self.max_cache_distance = 25 try: self.max_cache_distance = int(settings.get("Settings", "max_cache_distance")) except (ConfigParser.Error, TypeError): pass self.CacheItem = namedtuple('CacheItem', ['expires', 'val']) self.locations = {} try: self.locations = dict((key, value) for key, value in settings.items("Aliases")) except ConfigParser.NoSectionError: logger.log("No section 'Aliases' found in weather config file.") # remove spaces after commas - these would screw up lat/long searches for loc in self.locations: self.locations[loc] = re.sub(',\s*', ',', self.locations[loc]) # dict of location:CacheItem pairs # if current time in sec since epoch is less than ttl, cache has expired # should return val if cache is still valid self.cache = {} grammar = { "when": ["for", "be like"], "where": ["at","near","in", 'for'], } registrar.register_service("weather", self.execute, grammar=grammar, usage=""" USAGE: %s [location|alias] Returns the weather for a provided location or alias. If no location is provided, gets the weather data for the last recorded position. """, namespace=__name__)
def execute(self, **kwargs): """Log into Google Latitude and retrieve the user's current location. Keyword arguments: noreverse -- Return the latitude and longitude pair rather than turn it into a human-readable location. (default False) """ settings = ConfigParser.SafeConfigParser() settings.read(utils.get_plugin_settings_paths(__name__)) try: auth = open(settings.get('Settings', 'AUTHPATH'), "r") credentials = pickle.loads(auth.read()) auth.close() except ConfigParser.NoSectionError: raise plugin.UnsuccessfulExecution("'Settings' section missing from " "config file.") except ConfigParser.NoOptionError: raise plugin.UnsuccessfulExecution("Server not authenticated " "with Google Latitude.") except IOError: raise plugin.UnsuccessfulExecution("Error opening authentication file.") http = httplib2.Http() http = credentials.authorize(http) lat = build("latitude", "v1", http=http) data = lat.currentLocation().get(granularity="best").execute() if all(k in data for k in ('latitude', 'longitude')): if kwargs.get("noreverse", False): return "({0}, {1})".format(data['latitude'], data['longitude']) else: ret = self.lookup(data['latitude'], data['longitude']) if ret == None: return "({0}, {1})".format(data['latitude'], data['longitude']) else: return ret else: if 'kind' in data: raise plugin.UnsuccessfulExecution("No latitude data available.") else: raise plugin.UnsuccessfulExecution("Error in Latitude response.")
def __init__(self, registrar): super(Torrent, self).__init__(registrar) self.settings = ConfigParser.SafeConfigParser() self.settings.read(utils.get_plugin_settings_paths(__name__)) registrar.register_service( "torrent", self.execute, grammar={"name": [], "file": ["file"]}, usage=""" USAGE: %s [torrent file | media name | IMDB Link] When provided with a .torrent file, it grabs the file and begins downloading. With an IMDB link, it extracts the movie name and attempts to find the .torrent file closest to what you're looking for. A name does the same, except the media name is provided. """, namespace=__name__, )
def __init__(self, registrar): super(Torrent, self).__init__(registrar) self.settings = ConfigParser.SafeConfigParser() self.settings.read(utils.get_plugin_settings_paths(__name__)) registrar.register_service("torrent", self.execute, grammar={ "name": [], "file": ["file"] }, usage=""" USAGE: %s [torrent file | media name | IMDB Link] When provided with a .torrent file, it grabs the file and begins downloading. With an IMDB link, it extracts the movie name and attempts to find the .torrent file closest to what you're looking for. A name does the same, except the media name is provided. """, namespace=__name__)
def __init__(self, registrar): super(Schedule, self).__init__(registrar) self.settings = ConfigParser.SafeConfigParser() self.settings.read(utils.get_plugin_settings_paths(__name__)) if not self.settings.has_option("Settings", "queue_file"): self.settings.set("Settings", "queue_file", autoplatform.get_existing_file("schedule.queue")) else: if not os.access(self.settings.get("Settings", "queue_file"), os.W_OK): self.settings.set("Settings", "queue_file", None) self.queue = PersistentPriorityQueue( storagefile=self.settings.get("Settings", "queue_file")) if (not self.settings.has_option("Settings", "queue_file") or self.settings.get("Settings", "queue_file") is None): logger.log( "Scheduler could not find an existing queue file and " "no write access to create a new one. Any scheduled tasks " "will disappear once server is stopped.") self.event = threading.Event() thread = threading.Thread(target=self._executionthread) thread.setDaemon(True) thread.start() self.registrar.register_service( "schedule", self.execute, grammar={ "at": ["at"], "in": ["in"], "command": [], }, usage= ("USAGE: schedule WHAT [at WHEN] | [in WHEN]\n" "Schedules a command to be run at a specific time, repeating if\n" "necessary."), namespace=__name__)
def __init__(self, registrar): super(Schedule, self).__init__(registrar) self.settings = ConfigParser.SafeConfigParser() self.settings.read(utils.get_plugin_settings_paths(__name__)) if not self.settings.has_option("Settings", "queue_file"): self.settings.set("Settings", "queue_file", autoplatform.get_existing_file("schedule.queue")) else: if not os.access(self.settings.get("Settings", "queue_file"), os.W_OK): self.settings.set("Settings", "queue_file", None) self.queue = PersistentPriorityQueue( storagefile=self.settings.get("Settings", "queue_file")) if (not self.settings.has_option("Settings", "queue_file") or self.settings.get("Settings", "queue_file") is None): logger.log("Scheduler could not find an existing queue file and " "no write access to create a new one. Any scheduled tasks " "will disappear once server is stopped.") self.event = threading.Event() thread = threading.Thread(target=self._executionthread) thread.setDaemon(True) thread.start() self.registrar.register_service("schedule", self.execute, grammar={ "at": ["at"], "in": ["in"], "command": [], }, usage=("USAGE: schedule WHAT [at WHEN] | [in WHEN]\n" "Schedules a command to be run at a specific time, repeating if\n" "necessary."), namespace=__name__)
def execute(self, **kwargs): """Retrieve mail from a GMail account through curl.""" # Load command settings from a configuration file settings = ConfigParser.SafeConfigParser() settings.read(utils.get_plugin_settings_paths(__name__)) try: username = settings.get("Credentials", "username") password = settings.get("Credentials", "password") except ConfigParser.NoOptionError: raise plugin.UnsuccessfulExecution("Error: username/password " "not provided in settings file.") cmd = ("curl -u {0}:{1} --silent \"https://mail.google.com/mail/" "feed/atom\" | tr -d '\n' | awk -F '<entry>' '{" "for (i=2; i<=NF; i++) {print $i}}' | " "sed -n \"s/<title>\\(.*\)<\\/title.*name>\\(.*\\)" "<\\/name>.*/\\2 - \\1/p\"".format(username, password)) proc = sp.Popen(cmd, stdout=sp.PIPE, stderr=sp.PIPE, shell=True) out, err = proc.communicate() if out == "": out = "No mail." if len(out) == 0: raise plugin.UnsuccessfulExecution(err) return out
def test_settings_paths(self): self.assertTrue(any(os.path.isdir(os.path.dirname(fil)) for fil in utils.get_app_settings_paths("module"))) self.assertTrue(any(os.path.isdir(os.path.dirname(fil)) for fil in utils.get_plugin_settings_paths("module")))