def __init__(self, first_reaction_text, prompt, directories=[], first_reaction=True): """ This constructor contains a dictionary with Jarvis Actions (what Jarvis can do). In alphabetically order. """ Cmd.__init__(self) command = " ".join(sys.argv[1:]).strip() self.first_reaction = first_reaction self.first_reaction_text = first_reaction_text self.prompt = prompt if (command): self.first_reaction = False self.first_reaction_text = "" self.prompt = "" # Register do_quit() function to SIGINT signal (Ctrl-C) signal.signal(signal.SIGINT, self.interrupt_handler) self.memory = Memory() self.scheduler = schedule.Scheduler() self._api = JarvisAPI(self) self.say = self._api.say # Remember voice settings self.enable_voice = self._api.get_data('enable_voice') self.speech_rate = self._api.get_data('speech_rate') if not self.speech_rate: self.speech_rate = 120 # what if the platform does not have any engines, travis doesn't have sapi5 acc to me try: gtts_status = self._api.get_data('gtts_status') self.speech = create_voice(self, gtts_status, rate=self.speech_rate) except Exception as e: self.say("Voice not supported", Fore.RED) self.say(str(e), Fore.RED) self.fixed_responses = { "what time is it": "clock", "where am i": "pinpoint", } self._plugin_manager = PluginManager() for directory in directories: self._plugin_manager.add_directory(directory) if (not command): self._init_plugin_info() self._activate_plugins() if self.first_reaction: self._api.say(self.first_reaction_text)
def start_manager_threads(): """Start a PluginManager thread for each item in plugin_instance_list """ for plugin in plugin_instance_list: thread = PluginManager(plugin, Session) thread.start() thread_list.append(thread)
def OnApply(self, event): """ Method called by PreferenceGUI class. - Active plug-in through pluginmanager - Write the plug-in list in the DEVSimPy config file """ ### list of plug-in names which are to write in DEVSimPy config file pluginsList = [] ### all listed plug-ins for i in range(self.GetItemCount()): module = self.GetPyData(i)[0] if inspect.ismodule(module): ### plug-in file path path = module.__file__ ### built-in module coming from empty module create by error manager if path: ### get abspath and exclude .pyc name,ext = os.path.splitext(os.path.basename(path)) ### if plug-in is checked, we activate it if self.IsChecked(i): pluginsList.append(name) PluginManager.enable_plugin(name) else: PluginManager.disable_plugin(name) ### config file writing self.mainW.cfg.Write('active_plugins', str(pluginsList)) self.mainW.cfg.Flush()
def Importing(self, root, basename): """ Importing module and set pydata object """ # check the loaded module during the start of plug-ins module = PluginManager.load_plugins(basename) ### if module is exception (or tuple) if not inspect.ismodule(module): error = str(module) module = types.ModuleType(basename) module.__doc__ = error module.__file__ = None index = self.MyInsertItem(root, basename) if index is not None: if module.__file__ != None: ### only module to be activated is checked if basename in self.active_plugins_list: self.CheckItem(index, True) self.SetItemImage(index,1) else: PluginManager.disable_plugin(basename) else: self.SetItemImage(index, 2) #### pyData setting self.SetPyData(index, (module, None))
def __init__(self, first_reaction_text, prompt, directories=[], first_reaction=True, enable_voice=False): """ This constructor contains a dictionary with Jarvis Actions (what Jarvis can do). In alphabetically order. """ Cmd.__init__(self) self.first_reaction = first_reaction self.first_reaction_text = first_reaction_text self.prompt = prompt self.enable_voice = enable_voice # Register do_quit() function to SIGINT signal (Ctrl-C) signal.signal(signal.SIGINT, self.interrupt_handler) self.memory = Memory() self.scheduler = schedule.Scheduler() self.speech = create_voice() self.fixed_responses = { "what time is it": "clock", "where am i": "pinpoint", } self._api = JarvisAPI(self) self._plugin_manager = PluginManager() for directory in directories: self._plugin_manager.add_directory(directory) self._activate_plugins() self._init_plugin_info()
def OnViewLog(self, event): """ When View button is clicked """ # The simulation verbose event occurs PluginManager.trigger_event('START_SIM_VERBOSE', parent=self) # The activity tracking event occurs PluginManager.trigger_event('VIEW_ACTIVITY_REPORT', parent=self, master=self.current_master)
def GetModule(self, rcp: bool=False)->types.ModuleType: """ Return module from zip file corresponding to the amd or cmd model. It used when the tree library is created. If the module refered by self.fn is already imported, its returned else its imported using zipimport """ # if necessary, recompile (for update after editing code source of model) #if rcp: recompile(module_name) PluginManager.trigger_event("IMPORT_STRATEGIES", fn=self.fn) fullname = "".join([os.path.basename(os.path.dirname(self.fn)), getPythonModelFileName(self.fn).split('.py')[0]]) return self.ImportModule() if fullname not in sys.modules else sys.modules[fullname]
def __init__(self, first_reaction_text, prompt, directories=[], first_reaction=True, enable_voice=False): """ This constructor contains a dictionary with Jarvis Actions (what Jarvis can do). In alphabetically order. """ Cmd.__init__(self) self.first_reaction = first_reaction self.first_reaction_text = first_reaction_text self.prompt = prompt self.enable_voice = enable_voice # Register do_quit() function to SIGINT signal (Ctrl-C) signal.signal(signal.SIGINT, self.interrupt_handler) self.memory = Memory() self.scheduler = schedule.Scheduler() self.speech = create_voice() self.actions = [ { "check": ("ram", "weather", "time", "forecast") }, "directions", "help", "how_are_you", "near", "pinpoint", "umbrella", { "update": ("location", "system") }, "weather", ] self.fixed_responses = { "what time is it": "clock", "where am i": "pinpoint", "how are you": "how_are_you" } self._api = JarvisAPI(self) self._plugin_manager = PluginManager() for directory in directories: self._plugin_manager.add_directory(directory) self._activate_plugins()
def start(): r = redis.Redis(host="127.0.0.1", port=6379, db=0) # load the plugins for every device plugin_manager = PluginManager() plugin_manager.LoadAllPlugin() plugins = {} for device in r.lrange("devices", 0, -1): protocol = r.get("protocol:%s" % device) plugin = plugin_manager.GetPluginByName(protocol.title()) host = r.get("ip:%s" % device) port = r.get("port:%s" % device) plugin.init(host, port) plugins[device] = plugin while True: print 'in start' for device in r.lrange("devices", 0, -1): addr = r.get("addr:%s" % device) for spot in r.lrange("spots:%s" % device, 0, -1): command = r.get("device:%s:spot:%s:%s" % (device, spot[1:], 'command')) cmd_param = r.get("device:%s:spot:%s:%s" % (device, spot[1:], 'cmd_param')) cmd_length = r.get("device:%s:spot:%s:%s" % (device, spot[1:], 'cmd_length')) ratio = r.get("device:%s:spot:%s:%s" % (device, spot[1:], 'ratio')) value = plugins[device].get(addr, command, cmd_param, cmd_length) if value is None: print 'device:%s:spot:%s get error' % (device, spot) continue if spot[0] == 'A': value_type = r.get("device:%s:spot:%s:%s" % (device, spot[1:], 'value_type')) precision = r.get("device:%s:spot:%s:%s" % (device, spot[1:], 'precision')) min_value = r.get("device:%s:spot:%s:%s" % (device, spot[1:], 'min_value')) max_value = r.get("device:%s:spot:%s:%s" % (device, spot[1:], 'max_value')) value, status = plugins[device].transformAnalog(value, ratio, value_type, precision, min_value, max_value) elif spot[0] == 'D': mapper = r.get("device:%s:spot:%s:%s" % (device, spot[1:], 'mapper')) value, status = plugins[device].transformDigit(value, ratio, mapper) r.set("device:%s:spot:%s:value" % (device, spot[1:]), value) r.set("device:%s:spot:%s:status" % (device, spot[1:]), status) time.sleep(2) """
def send(self, d, msg): """ Dispatch messages to the right method. """ if isinstance(d, CoupledDEVS): CS = CoupledSolver() r = CS.receive(d, msg) else: AS = AtomicSolver() r = AS.receive(d, msg) PluginManager.trigger_event("SIM_BLINK", model=d, msg=msg) PluginManager.trigger_event("SIM_TEST", model=d, msg=msg) return r
def simulate(self, T=100000000): """ """ master = self._simulator.getMaster() send = self._simulator.send #clock = master.myTimeAdvance # Initialize the model --- set the simulation clock to 0. send(master, (0, [], 0)) clock = master.myTimeAdvance ### ref to cpu time evaluation t_start = time.time() ### if suspend, we could store the future ref old_cpu_time = 0 ### stoping condition depend on the ntl (no time limit for the simulation) condition = lambda clock: HasActiveChild( getFlatImmChildrenList(master, []) ) if self._simulator.ntl else clock <= T # Main loop repeatedly sends $(*,\,t)$ messages to the model's root DEVS. while condition(clock) and self._simulator.end_flag == False: ##Optional sleep if self._simulator.thread_sleep: time.sleep(self._simulator._sleeptime) elif self._simulator.thread_suspend: ### Optional suspend while self._simulator.thread_suspend: time.sleep(1.0) old_cpu_time = self._simulator.cpu_time t_start = time.time() else: # The SIM_VERBOSE event occurs PluginManager.trigger_event("SIM_VERBOSE", clock=clock) send(master, (1, {}, clock)) clock = master.myTimeAdvance self._simulator.cpu_time = old_cpu_time + (time.time() - t_start) self._simulator.terminate()
def __init__(self, pluginManager, parent = None): """ Constructor @param pluginManager reference to the plugin manager object @param parent parent of this dialog (QWidget) """ QWidget.__init__(self, parent) self.setupUi(self) if pluginManager is None: # started as external plugin deinstaller self.__pluginManager = PluginManager(doLoadPlugins = False) self.__external = True else: self.__pluginManager = pluginManager self.__external = False self.pluginDirectoryCombo.addItem(self.trUtf8("User plugins directory"), QVariant(self.__pluginManager.getPluginDir("user"))) globalDir = self.__pluginManager.getPluginDir("global") if globalDir is not None and os.access(globalDir, os.W_OK): self.pluginDirectoryCombo.addItem(self.trUtf8("Global plugins directory"), QVariant(globalDir))
def ChangeButtonLabel(self, btn, new_label): """ Change the label of the Log button depending on the active plug-in """ ### if activity plug-in is enabled if PluginManager.is_enable('start_activity_tracking'): self._btn4.SetLabel("Activity")
def go(self, text_dump_filename, template_information, pdf_file_with_path, output_file_with_path): logger = Logger.getLogger() olb = ObjectLayoutContainer.getInstance() olb.parse_pdf(pdf_file_with_path, text_dump_filename) try: template_file_name = TemplateChoser.get_template_name( template_information) except Exception as ex: logger.error(str(ex)) return plugin_manager = None plugin_name = self._get_plugin_name(template_file_name) if plugin_name is not None: plugin_manager = PluginManager.getInstance() plugin_manager.load_plugin(plugin_name) logger.info('Loaded plugin %s', plugin_name) dict_of_field_values = FieldExtractor.extract_fields( template_file_name) self._transform_field_values(plugin_manager, dict_of_field_values) dict_of_line_items = LineItemExtractor.extract_line_items( template_file_name) self._transform_lineitem_values(plugin_manager, dict_of_line_items) check_status = Checker.check_total(plugin_manager, template_file_name, dict_of_field_values, dict_of_line_items) if len(dict_of_field_values) > 0 or len(dict_of_line_items) > 0 or len( check_status) > 0: extracted_data = {} if len(dict_of_field_values) > 0: extracted_data["fields"] = dict_of_field_values if len(dict_of_line_items) > 0: extracted_data["lineitems"] = dict_of_line_items if len(check_status) > 0: extracted_data["checkstatus"] = check_status logger.info("Check Status Match = %s", str(check_status["match_status"])) returned_extraced_value = self._invoke_post_processor( plugin_manager, extracted_data) with io.open(output_file_with_path, 'w', encoding='utf-8') as f: f.write( str( json.dumps(returned_extraced_value, ensure_ascii=False, indent=4)))
def __init__(self, pluginManager, pluginFileNames, parent = None): """ Constructor @param pluginManager reference to the plugin manager object @param pluginFileNames list of plugin files suggested for installation (QStringList) @param parent parent of this dialog (QWidget) """ QWidget.__init__(self, parent) self.setupUi(self) if pluginManager is None: # started as external plugin installer self.__pluginManager = PluginManager(doLoadPlugins = False) self.__external = True else: self.__pluginManager = pluginManager self.__external = False self.__backButton = \ self.buttonBox.addButton(self.trUtf8("< Back"), QDialogButtonBox.ActionRole) self.__nextButton = \ self.buttonBox.addButton(self.trUtf8("Next >"), QDialogButtonBox.ActionRole) self.__finishButton = \ self.buttonBox.addButton(self.trUtf8("Install"), QDialogButtonBox.ActionRole) self.__closeButton = self.buttonBox.button(QDialogButtonBox.Close) self.__cancelButton = self.buttonBox.button(QDialogButtonBox.Cancel) userDir = self.__pluginManager.getPluginDir("user") if userDir is not None: self.destinationCombo.addItem(self.trUtf8("User plugins directory"), QVariant(userDir)) globalDir = self.__pluginManager.getPluginDir("global") if globalDir is not None and os.access(globalDir, os.W_OK): self.destinationCombo.addItem(self.trUtf8("Global plugins directory"), QVariant(globalDir)) self.__installedDirs = [] self.__installedFiles = [] self.__restartNeeded = False downloadDir = QDir(Preferences.getPluginManager("DownloadPath")) for pluginFileName in pluginFileNames: fi = QFileInfo(pluginFileName) if fi.isRelative(): pluginFileName = QFileInfo(downloadDir, fi.fileName()).absoluteFilePath() self.archivesList.addItem(pluginFileName) self.archivesList.sortItems() self.__currentIndex = 0 self.__selectPage()
def __init__(self, first_reaction_text, prompt, directories=[], first_reaction=True, enable_voice=False): """ This constructor contains a dictionary with Jarvis Actions (what Jarvis can do). In alphabetically order. """ Cmd.__init__(self) self.first_reaction = first_reaction self.first_reaction_text = first_reaction_text self.prompt = prompt self.enable_voice = enable_voice # Register do_quit() function to SIGINT signal (Ctrl-C) signal.signal(signal.SIGINT, self.interrupt_handler) self.memory = Memory() self.scheduler = schedule.Scheduler() # what if the platform does not have any engines, travis doesn't have sapi5 acc to me try: self.speech = create_voice() except Exception as e: print_say("Voice not supported", self, Fore.RED) print_say(str(e), self, Fore.RED) self.fixed_responses = { "what time is it": "clock", "where am i": "pinpoint", } self._api = JarvisAPI(self) self._plugin_manager = PluginManager() for directory in directories: self._plugin_manager.add_directory(directory) self._activate_plugins() self._init_plugin_info()
def verifyPluginAvailability(self, process_name): plugin_manager = PluginManager() plugin_found_flag = 0 for plugin in plugin_manager.plugins: if plugin.__class__.__name__ == process_name: plugin_found_flag = 1 break if plugin_found_flag == 0: print "No plugin found for {0} process logs".format(process_name) sys.exit(0) return plugin
def init_once(self): print "Starting " + ENV_VARS.package + " v" + ENV_VARS.version JabberConnection.__init__(self) gnome.init(ENV_VARS.package, ENV_VARS.version) self.pman = PluginManager() self.resources = ResourceManager() self.__load_resources() ld = LoginDlg(1) ld.evtDoConnect = self.startup ld.evtCancel = self.quit ld.show() ## Show us more info if we are debugging if __debug__: self.session.evtTransmitXML.connect(self.__on_transmit_xml) self.session.evtRecvXML.connect(self.__on_recv_xml) self.session.evtPresenceRequest.connect(self.__on_presence_request)
def __init__(self): try: logger.info('Initializing directories...') dirs = self.init_dirs() os.chdir(dirs.user_cache_dir) logger.debug('* Cache: ' + dirs.user_cache_dir) logger.info('* Data: ' + dirs.user_data_dir) plugin_dirs = [] plugin_dirs.append(os.path.join(self.program_dir, 'plugins')) plugin_dirs.append(os.path.join(dirs.user_data_dir, 'plugins')) for d in plugin_dirs: logger.info('* Plugins: ' + d) print('') logger.info('Initializing configuration...') conf_file_path = os.path.join(dirs.user_data_dir, 'fbnotify.conf') logger.info('* File: ' + conf_file_path) self.conf = Config(conf_file_path) print('') logger.info('Initializing feed...') self.feed = Feed(self.conf.feed.url) print('') logger.info('Initializing plugins...') logger.debug('* Blacklisted: ' + str(self.conf.program.plugin_blacklist)) self.plugin_man = PluginManager(plugin_dirs, self.conf.program.plugin_blacklist) self.plugin_man.load_by_role('notify') self.plugin_man.load_by_role('list') self.plugin_man.load_by_role('status') self.plugin_context = self.plugin_man.messaging.register_plugin(self, 'fbnotify') print('') logger.debug('Work dir: ' + os.getcwd()) print except Exception as e: logger.error(traceback.format_exc()) self.bad_stop()
def __init__(self): self.plugin_path = DEFAULT_PLUGIN_PATH self.config_ctxt = config.get_config_context() self.event_manager_url = self.config_ctxt['setup']['em_url'] self.is_central = self.config_ctxt['type']['central_facility'] self.site_id = None self.msg_queue = Queue() self.event_code_dict = {} self.instrument_ids = [] self.continue_processing_events = True self.cert_verify = self.config_ctxt['setup']['cert_verify'] self.info = {'site': self.config_ctxt['setup']['site']} self.plugin_managers = [PluginManager({ 'site': self.config_ctxt['setup']['site'], 'config_id': instrument_name }, instrument) for instrument_name, instrument in self.config_ctxt['agent']['instrument_list'].items()] #Set up logging log_path = os.environ.get("LOG_PATH") if log_path is None: log_path = "/vagrant/logs/" # Logs to the main log logging.basicConfig( format='%(levelname)s:%(asctime)s:%(module)s:%(lineno)d: %(message)s', filename='%scombined.log' % log_path, filemode='a', level=logging.DEBUG) # Logs to the agent log self.agent_logger = logging.getLogger(__name__) agent_handler = logging.FileHandler("%sagent_server.log" % log_path, mode="a") agent_handler.setFormatter(logging.Formatter('%(levelname)s:%(asctime)s:%(module)s:%(lineno)d: %(message)s')) self.agent_logger.addHandler(agent_handler) # Add agent handler to the main werkzeug logger logging.getLogger("werkzeug").addHandler(agent_handler) self.agent_logger.info(self.info)
def execIntTransition(m): """ """ ts = m.ts.Get() if m.timeNext != INFINITY: m.outputFnc() m.elapsed = ts - m.timeLast m.intTransition() m.timeLast = ts m.myTimeAdvance = m.timeAdvance() m.timeNext = m.timeLast + m.myTimeAdvance if m.myTimeAdvance != INFINITY: m.myTimeAdvance += ts m.elapsed = 0.0 # The SIM_VERBOSE event occurs PluginManager.trigger_event("SIM_VERBOSE", model=m, msg=0) PluginManager.trigger_event("SIM_BLINK", model=m, msg=[1]) PluginManager.trigger_event("SIM_TEST", model=m, msg=[1])
def receive(aDEVS, msg): # For any received message, the time {\tt t} (time at which the message # is sent) is the second item in the list {\tt msg}. t = msg[2] # $(*,\,t)$ message --- triggers internal transition and returns # $(y,\,t)$ message for parent coupled-DEVS: if msg[0] == 1: if t != aDEVS.timeNext: Error("Bad synchronization...1", 1) # First call the output function, which (amongst other things) rebuilds # the output dictionnary {\tt myOutput}: aDEVS.myOutput = {} aDEVS.outputFnc() aDEVS.elapsed = t - aDEVS.timeLast aDEVS.intTransition() aDEVS.timeLast = t aDEVS.myTimeAdvance = aDEVS.timeAdvance() aDEVS.timeNext = aDEVS.timeLast + aDEVS.myTimeAdvance if aDEVS.myTimeAdvance != INFINITY: aDEVS.myTimeAdvance += t aDEVS.elapsed = 0 # The SIM_VERBOSE event occurs PluginManager.trigger_event("SIM_VERBOSE", model=aDEVS, msg=0) # Return the DEVS' output to the parent coupled-DEVS (rather than # sending $(y,\,t)$ message). return aDEVS.myOutput # ${x,\,t)$ message --- triggers external transition, where $x$ is the # input dictionnary to the DEVS: elif isinstance(msg[0], dict): if not (aDEVS.timeLast <= t <= aDEVS.timeNext): Error("Bad synchronization...2", 1) aDEVS.myInput = msg[0] # update elapsed time. This is necessary for the call to the external # transition function, which is used to update the DEVS' state. aDEVS.elapsed = t - aDEVS.timeLast aDEVS.extTransition() # Udpate time variables: aDEVS.timeLast = t aDEVS.myTimeAdvance = aDEVS.timeAdvance() aDEVS.timeNext = aDEVS.timeLast + aDEVS.myTimeAdvance if aDEVS.myTimeAdvance != INFINITY: aDEVS.myTimeAdvance += t aDEVS.elapsed = 0 # The SIM_VERBOSE event occurs PluginManager.trigger_event("SIM_VERBOSE", model=aDEVS, msg=1) # $(i,\,t)$ message --- sets origin of time at {\tt t}: elif msg[0] == 0: aDEVS.timeLast = t - aDEVS.elapsed aDEVS.myTimeAdvance = aDEVS.timeAdvance() aDEVS.timeNext = aDEVS.timeLast + aDEVS.myTimeAdvance if aDEVS.myTimeAdvance != INFINITY: aDEVS.myTimeAdvance += t else: Error("Unrecognized message", 1)
class CmdInterpreter(Cmd): # We use this variable at Breakpoint #1. # We use this in order to allow Jarvis say "Hi", only at the first # interaction. # This can be used to store user specific data def __init__( self, first_reaction_text, prompt, directories=[], first_reaction=True): """ This constructor contains a dictionary with Jarvis Actions (what Jarvis can do). In alphabetically order. """ Cmd.__init__(self) command = " ".join(sys.argv[1:]).strip() self.first_reaction = first_reaction self.first_reaction_text = first_reaction_text self.prompt = prompt if (command): self.first_reaction = False self.first_reaction_text = "" self.prompt = "" # Register do_quit() function to SIGINT signal (Ctrl-C) signal.signal(signal.SIGINT, self.interrupt_handler) self.memory = Memory() self.scheduler = schedule.Scheduler() self._api = JarvisAPI(self) self.say = self._api.say # Remember voice settings self.enable_voice = self._api.get_data('enable_voice') self.speech_rate = self._api.get_data('speech_rate') if not self.speech_rate: self.speech_rate = 120 # what if the platform does not have any engines, travis doesn't have sapi5 acc to me try: gtts_status = self._api.get_data('gtts_status') self.speech = create_voice( self, gtts_status, rate=self.speech_rate) except Exception as e: self.say("Voice not supported", Fore.RED) self.say(str(e), Fore.RED) self.fixed_responses = {"what time is it": "clock", "where am i": "pinpoint", } self._plugin_manager = PluginManager() for directory in directories: self._plugin_manager.add_directory(directory) if (not command): self._init_plugin_info() self._activate_plugins() self._api.say(self.first_reaction_text) def _init_plugin_info(self): plugin_status_formatter = { "disabled": len(self._plugin_manager.get_disabled()), "enabled": self._plugin_manager.get_number_plugins_loaded(), "red": Fore.RED, "blue": Fore.BLUE, "reset": Fore.RESET } plugin_status = "{red}{enabled} {blue}plugins loaded" if plugin_status_formatter['disabled'] > 0: plugin_status += " {red}{disabled} {blue}plugins disabled. More information: {red}status\n" plugin_status += Fore.RESET self.first_reaction_text += plugin_status.format( **plugin_status_formatter) def _activate_plugins(self): """Generate do_XXX, help_XXX and (optionally) complete_XXX functions""" for (plugin_name, plugin) in self._plugin_manager.get_plugins().items(): self._plugin_update_completion(plugin, plugin_name) run_catch = catch_all_exceptions(plugin.run) setattr( CmdInterpreter, "do_" + plugin_name, partial( run_catch, self)) setattr( CmdInterpreter, "help_" + plugin_name, partial( self._api.say, plugin.get_doc())) plugin.init(self._api) def _plugin_update_completion(self, plugin, plugin_name): """Return True if completion is available""" completions = [i for i in plugin.complete()] if len(completions) > 0: def complete(completions): def _complete_impl(self, text, line, begidx, endidx): return [i for i in completions if i.startswith(text)] return _complete_impl setattr( CmdInterpreter, "complete_" + plugin_name, complete(completions)) def get_api(self): return self._api def close(self): """Closing Jarvis.""" '''Stop the spinner if it is already running''' if self._api.is_spinner_running(): self._api.spinner_stop('Some error has occured') quotes = ['As always sir, a great pleasure watching you work', 'Test complete. Preparing to power down and begin diagnostics...'] self.say(random.choice(quotes), Fore.RED) self.scheduler.stop_all() sys.exit() def execute_once(self, command): self.get_api().eval(command) sys.exit() def error(self): """Jarvis let you know if an error has occurred.""" self.say("I could not identify your command...", Fore.RED) def interrupt_handler(self, signal, frame): """Closes Jarvis on SIGINT signal. (Ctrl-C)""" self.close() def do_status(self, s): """Prints plugin status status""" count_enabled = self._plugin_manager.get_number_plugins_loaded() count_disabled = len(self._plugin_manager.get_disabled()) self.say( "{} Plugins enabled, {} Plugins disabled.".format( count_enabled, count_disabled)) if "short" not in s and count_disabled > 0: self.say("") for disabled, reason in self._plugin_manager.get_disabled().items(): self.say( "{:<20}: {}".format( disabled, " OR ".join(reason))) def do_help(self, arg): if arg: Cmd.do_help(self, arg) else: self.say("") headerString = "These are valid commands for Jarvis" formatString = "Format: command ([aliases for command])" self.say(headerString) self.say(formatString, Fore.BLUE) pluginDict = self._plugin_manager.get_plugins() uniquePlugins = {} for key in pluginDict.keys(): plugin = pluginDict[key] if(plugin not in uniquePlugins.keys()): uniquePlugins[plugin.get_name()] = plugin helpOutput = [] for name in sorted(uniquePlugins.keys()): if (name == "help"): continue try: aliasString = ", ".join(uniquePlugins[name].alias()) if (aliasString != ""): pluginOutput = "* " + name + " (" + aliasString + ")" helpOutput.append(pluginOutput) else: helpOutput.append("* " + name) except AttributeError: helpOutput.append("* " + name) Cmd.columnize(self, helpOutput) def help_status(self): self.say("Prints info about enabled or disabled plugins") self.say("Use \"status short\" to omit detailed information.")
def __init__(self): #declaration des variables global choice, temp, plugins, chaines, programs, fichiers, DLlist chaines = '' programs = '' fichiers = '' temp = 0 choice = "" selectedPlugin = '' selectedChaine = '' selectedProgram = '' DLlist = [] ################################################ # Instanciations + initialisation de variables # ################################################ # On instancie le plugin manager self.pluginManager = PluginManager() # On instancie le gestionnaire de preferences self.preferences = Preferences() # On instancie le gestionnaire de download self.downloader = Downloader() # On recupere l'instance de API self.api = API.getInstance() # # On instancie le gestionnaire d'historique # self.historique = Historique() # Si aucun plugin n'est active, on ouvre la fenetre des preferences if (len(self.preferences.getPreference("pluginsActifs")) == 0): choice = 'p' self.api.pluginRafraichirAuto() # On met en place la liste des plugins dans API plugins = self.preferences.getPreference("pluginsActifs") plugins.sort() # On actualise tous les plugins self.api.pluginRafraichirAuto() #boucle qui raffraichit l'affichage apres chaque interaction utilisateur while choice != 'exit': #ouverture du menu de preferences if choice == 'p' or choice == 'P': prefs() # On met en place la liste des plugins dans API plugins = self.preferences.getPreference("pluginsActifs") plugins.sort() # On actualise tous les plugins self.api.pluginRafraichirAuto() #ouverture du menu de telechargement elif choice == 't' or choice == 'T': dl(DLlist) #ouverture de l'invite de fermeture elif choice == 'q' or choice == 'Q': quitter() #actualisation de l'affichage ecran elif choice == 'i' or choice == 'I': info() #actualisation de l'affichage ecran elif choice == 'a' or choice == 'A': header(selectedPlugin, selectedChaine, selectedProgram) print "\n\n\n\n\t\tRafraichissement\n\n\n" self.api.pluginRafraichirAuto() #recharger les listes if len(selectedProgram) != 0: fichiers = self.api.getPluginListeFichiers( selectedPlugin, selectedProgram) elif len(selectedChaine) != 0: programs = self.api.getPluginListeEmissions( selectedPlugin, selectedChaine) elif len(selectedPlugin) != 0: chaines = self.api.getPluginListeChaines(selectedPlugin) elif len(selectedPlugin) == 0 and len( selectedChaine) == 0 and len(selectedProgram) == 0: plugins = self.preferences.getPreference("pluginsActifs") plugins.sort() #mise a jour de l'affichage header(selectedPlugin, selectedChaine, selectedProgram) print "\n\n\n\n\t\tVeuillez patientez pendant la mise a jour des informations\n\n\n" time.sleep(1) show(selectedPlugin, selectedChaine, selectedProgram, temp) elif choice == 'r' or choice == 'R': temp = 0 if len(selectedProgram) != 0: selectedProgram = "" elif len(selectedChaine) != 0: selectedChaine = "" if len(chaines) == 1: selectedPlugin = "" elif len(selectedPlugin) != 0: selectedPlugin = "" elif choice.isdigit() and int(choice) >= 0: choice = 10 * temp + int(choice) if len(selectedPlugin) == 0 and len(plugins) > choice: temp = 0 selectedPlugin = plugins[choice] chaines = self.api.getPluginListeChaines(selectedPlugin) if len(chaines) == 1: header(selectedPlugin, '', '') print "Une seule chaine :", chaines time.sleep(0.5) selectedChaine = chaines[0] programs = self.api.getPluginListeEmissions( selectedPlugin, selectedChaine) elif len(selectedChaine) == 0 and len(chaines) > choice: temp = 0 selectedChaine = chaines[choice] programs = self.api.getPluginListeEmissions( selectedPlugin, selectedChaine) elif len(selectedProgram) == 0 and len(programs) > choice: selectedProgram = programs[choice] header(selectedPlugin, selectedChaine, selectedProgram) print "\n\n\n\n\t\tVeuillez patientez pendant le chargement des informations\n\n\n" fichiers = self.api.getPluginListeFichiers( selectedPlugin, selectedProgram) if len(fichiers) == 0: header(selectedPlugin, selectedChaine, selectedProgram) print "\n\n\n\n\n\n\n\t\tAucun fichier dans le programme :", selectedProgram time.sleep(1) selectedProgram = '' else: temp = 0 elif len(selectedPlugin) != 0 and len( selectedChaine) != 0 and len( selectedProgram) != 0 and len(fichiers) > choice: header(selectedPlugin, selectedChaine, selectedProgram) if fichiers[choice] not in DLlist: print "\n\n\n\n\n\n\najout", fichiers[ choice].nom, "a la liste de telechargement\n\n\n\n\n\n\n\n\n" DLlist.append(fichiers[choice]) else: print "\n\n\n\n\n\n\n\t\tFichier deja dans la liste de telechargement\n\n\n\n\n\n\n\n\n" time.sleep(1) os.system(['clear', 'cls'][os.name == 'nt']) elif choice == '*': # if len(selectedPlugin)==0: # temp=0 # selectedPlugin = 'None' # chaines = self.api.getPluginListeChaines() # elif len(selectedChaine)==0: # temp=0 # selectedChaine='None' # programs = self.api.getPluginListeEmissions(selectedPlugin,selectedChaine) # el if len(selectedProgram) == 0: selectedProgram = 'Tous' header(selectedPlugin, selectedChaine, selectedProgram) print "\n\n\n\n\t\tVeuillez patientez pendant le chargement des informations\n\n\n" # for choice in range(len(programs)) : fichiers = self.api.getPluginListeFichiers( selectedPlugin, None) #programs[choice]) elif len(selectedPlugin) != 0 and len( selectedChaine) != 0 and len(selectedProgram) != 0: header(selectedPlugin, selectedChaine, selectedProgram) for choice in range(len(fichiers)): if fichiers[int(choice)] not in DLlist: header(selectedPlugin, selectedChaine, selectedProgram) print "\n\n\n\n\t\tajout", fichiers[int( choice)].nom, "a la liste de telechargement" DLlist.append(fichiers[int(choice)]) else: print "\t\tFichier deja dans la liste de telechargement" time.sleep(0.5) #afficher la suite de la liste elif choice == '+': if len(selectedPlugin) == 0: if len(plugins) > temp * 10 + 10: temp += 1 elif len(selectedChaine) == 0: if len(chaines) > temp * 10 + 10: temp += 1 elif len(selectedProgram) == 0: if len(programs) > temp * 10 + 10: temp += 1 elif len(selectedPlugin) != 0 and len( selectedChaine) != 0 and len(selectedProgram) != 0: if len(fichiers) > temp * 10 + 10: temp += 1 #afficher le debut de la liste elif choice == '-': if temp != 0: temp -= 1 show(selectedPlugin, selectedChaine, selectedProgram, temp) choice = '' # if not choice:choice=raw_input("\n\t\tEntrez votre choix : ") if not choice: choice = getch()
class PluginUninstallWidget(QWidget, Ui_PluginUninstallDialog): """ Class implementing a dialog for plugin deinstallation. """ def __init__(self, pluginManager, parent = None): """ Constructor @param pluginManager reference to the plugin manager object @param parent parent of this dialog (QWidget) """ QWidget.__init__(self, parent) self.setupUi(self) if pluginManager is None: # started as external plugin deinstaller self.__pluginManager = PluginManager(doLoadPlugins = False) self.__external = True else: self.__pluginManager = pluginManager self.__external = False self.pluginDirectoryCombo.addItem(self.trUtf8("User plugins directory"), QVariant(self.__pluginManager.getPluginDir("user"))) globalDir = self.__pluginManager.getPluginDir("global") if globalDir is not None and os.access(globalDir, os.W_OK): self.pluginDirectoryCombo.addItem(self.trUtf8("Global plugins directory"), QVariant(globalDir)) @pyqtSignature("int") def on_pluginDirectoryCombo_currentIndexChanged(self, index): """ Private slot to populate the plugin name combo upon a change of the plugin area. @param index index of the selected item (integer) """ pluginDirectory = unicode(self.pluginDirectoryCombo\ .itemData(index).toString()) pluginNames = self.__pluginManager.getPluginModules(pluginDirectory) pluginNames.sort() self.pluginNameCombo.clear() for pluginName in pluginNames: fname = "%s.py" % os.path.join(pluginDirectory, pluginName) self.pluginNameCombo.addItem(pluginName, QVariant(fname)) self.buttonBox.button(QDialogButtonBox.Ok)\ .setEnabled(not self.pluginNameCombo.currentText().isEmpty()) @pyqtSignature("") def on_buttonBox_accepted(self): """ Private slot to handle the accepted signal of the button box. """ if self.__uninstallPlugin(): self.emit(SIGNAL("accepted()")) def __uninstallPlugin(self): """ Private slot to uninstall the selected plugin. @return flag indicating success (boolean) """ pluginDirectory = unicode(self.pluginDirectoryCombo\ .itemData(self.pluginDirectoryCombo.currentIndex())\ .toString()) pluginName = unicode(self.pluginNameCombo.currentText()) pluginFile = unicode(self.pluginNameCombo\ .itemData(self.pluginNameCombo.currentIndex())\ .toString()) if not self.__pluginManager.unloadPlugin(pluginName, pluginDirectory): KQMessageBox.critical(None, self.trUtf8("Plugin Uninstallation"), self.trUtf8("""<p>The plugin <b>%1</b> could not be unloaded.""" """ Aborting...</p>""").arg(pluginName), QMessageBox.StandardButtons(\ QMessageBox.Ok)) return False if not pluginDirectory in sys.path: sys.path.insert(2, pluginDirectory) module = imp.load_source(pluginName, pluginFile) if not hasattr(module, "packageName"): KQMessageBox.critical(None, self.trUtf8("Plugin Uninstallation"), self.trUtf8("""<p>The plugin <b>%1</b> has no 'packageName' attribute.""" """ Aborting...</p>""").arg(pluginName), QMessageBox.StandardButtons(\ QMessageBox.Ok)) return False package = getattr(module, "packageName") if package is None: package = "None" packageDir = "" else: packageDir = os.path.join(pluginDirectory, package) if hasattr(module, "prepareUninstall"): module.prepareUninstall() internalPackages = [] if hasattr(module, "internalPackages"): # it is a comma separated string internalPackages = [p.strip() for p in module.internalPackages.split(",")] del module # clean sys.modules self.__pluginManager.removePluginFromSysModules( pluginName, package, internalPackages) try: if packageDir and os.path.exists(packageDir): shutil.rmtree(packageDir) fnameo = "%so" % pluginFile if os.path.exists(fnameo): os.remove(fnameo) fnamec = "%sc" % pluginFile if os.path.exists(fnamec): os.remove(fnamec) os.remove(pluginFile) except OSError, err: KQMessageBox.critical(None, self.trUtf8("Plugin Uninstallation"), self.trUtf8("""<p>The plugin package <b>%1</b> could not be""" """ removed. Aborting...</p>""" """<p>Reason: %2</p>""").arg(packageDir).arg(str(err)), QMessageBox.StandardButtons(\ QMessageBox.Ok)) return False KQMessageBox.information(None, self.trUtf8("Plugin Uninstallation"), self.trUtf8("""<p>The plugin <b>%1</b> was uninstalled successfully""" """ from %2.</p>""")\ .arg(pluginName).arg(pluginDirectory), QMessageBox.StandardButtons(\ QMessageBox.Ok)) return True
class PluginInstallWidget(QWidget, Ui_PluginInstallDialog): """ Class implementing the Plugin installation dialog. """ def __init__(self, pluginManager, pluginFileNames, parent = None): """ Constructor @param pluginManager reference to the plugin manager object @param pluginFileNames list of plugin files suggested for installation (QStringList) @param parent parent of this dialog (QWidget) """ QWidget.__init__(self, parent) self.setupUi(self) if pluginManager is None: # started as external plugin installer self.__pluginManager = PluginManager(doLoadPlugins = False) self.__external = True else: self.__pluginManager = pluginManager self.__external = False self.__backButton = \ self.buttonBox.addButton(self.trUtf8("< Back"), QDialogButtonBox.ActionRole) self.__nextButton = \ self.buttonBox.addButton(self.trUtf8("Next >"), QDialogButtonBox.ActionRole) self.__finishButton = \ self.buttonBox.addButton(self.trUtf8("Install"), QDialogButtonBox.ActionRole) self.__closeButton = self.buttonBox.button(QDialogButtonBox.Close) self.__cancelButton = self.buttonBox.button(QDialogButtonBox.Cancel) userDir = self.__pluginManager.getPluginDir("user") if userDir is not None: self.destinationCombo.addItem(self.trUtf8("User plugins directory"), QVariant(userDir)) globalDir = self.__pluginManager.getPluginDir("global") if globalDir is not None and os.access(globalDir, os.W_OK): self.destinationCombo.addItem(self.trUtf8("Global plugins directory"), QVariant(globalDir)) self.__installedDirs = [] self.__installedFiles = [] self.__restartNeeded = False downloadDir = QDir(Preferences.getPluginManager("DownloadPath")) for pluginFileName in pluginFileNames: fi = QFileInfo(pluginFileName) if fi.isRelative(): pluginFileName = QFileInfo(downloadDir, fi.fileName()).absoluteFilePath() self.archivesList.addItem(pluginFileName) self.archivesList.sortItems() self.__currentIndex = 0 self.__selectPage() def restartNeeded(self): """ Public method to check, if a restart of the IDE is required. @return flag indicating a restart is required (boolean) """ return self.__restartNeeded def __createArchivesList(self): """ Private method to create a list of plugin archive names. @return list of plugin archive names (QStringList) """ archivesList = QStringList() for row in range(self.archivesList.count()): archivesList.append(self.archivesList.item(row).text()) return archivesList def __selectPage(self): """ Private method to show the right wizard page. """ self.wizard.setCurrentIndex(self.__currentIndex) if self.__currentIndex == 0: self.__backButton.setEnabled(False) self.__nextButton.setEnabled(self.archivesList.count() > 0) self.__finishButton.setEnabled(False) self.__closeButton.hide() self.__cancelButton.show() elif self.__currentIndex == 1: self.__backButton.setEnabled(True) self.__nextButton.setEnabled(self.destinationCombo.count() > 0) self.__finishButton.setEnabled(False) self.__closeButton.hide() self.__cancelButton.show() else: self.__backButton.setEnabled(True) self.__nextButton.setEnabled(False) self.__finishButton.setEnabled(True) self.__closeButton.hide() self.__cancelButton.show() msg = self.trUtf8("Plugin ZIP-Archives:\n%1\n\nDestination:\n%2 (%3)")\ .arg(self.__createArchivesList().join("\n"))\ .arg(self.destinationCombo.currentText())\ .arg(self.destinationCombo.itemData(self.destinationCombo.currentIndex())\ .toString() ) self.summaryEdit.setPlainText(msg) @pyqtSignature("") def on_addArchivesButton_clicked(self): """ Private slot to select plugin ZIP-archives via a file selection dialog. """ dn = Preferences.getPluginManager("DownloadPath") archives = KQFileDialog.getOpenFileNames(\ self, self.trUtf8("Select plugin ZIP-archives"), dn, self.trUtf8("Plugin archive (*.zip)")) if not archives.isEmpty(): matchflags = Qt.MatchFixedString if not Utilities.isWindowsPlatform(): matchflags |= Qt.MatchCaseSensitive for archive in archives: if len(self.archivesList.findItems(archive, matchflags)) == 0: # entry not in list already self.archivesList.addItem(archive) self.archivesList.sortItems() self.__nextButton.setEnabled(self.archivesList.count() > 0) @pyqtSignature("") def on_archivesList_itemSelectionChanged(self): """ Private slot called, when the selection of the archives list changes. """ self.removeArchivesButton.setEnabled(len(self.archivesList.selectedItems()) > 0) @pyqtSignature("") def on_removeArchivesButton_clicked(self): """ Private slot to remove archives from the list. """ for archiveItem in self.archivesList.selectedItems(): itm = self.archivesList.takeItem(self.archivesList.row(archiveItem)) del itm self.__nextButton.setEnabled(self.archivesList.count() > 0) @pyqtSignature("QAbstractButton*") def on_buttonBox_clicked(self, button): """ Private slot to handle the click of a button of the button box. """ if button == self.__backButton: self.__currentIndex -= 1 self.__selectPage() elif button == self.__nextButton: self.__currentIndex += 1 self.__selectPage() elif button == self.__finishButton: self.__finishButton.setEnabled(False) self.__installPlugins() self.__closeButton.show() self.__cancelButton.hide() def __installPlugins(self): """ Private method to install the selected plugin archives. @return flag indicating success (boolean) """ res = True self.summaryEdit.clear() for archive in self.__createArchivesList(): self.summaryEdit.append(self.trUtf8("Installing %1 ...").arg(archive)) ok, msg, restart = self.__installPlugin(archive) res = res and ok if ok: self.summaryEdit.append(self.trUtf8(" ok")) else: self.summaryEdit.append(msg) if restart: self.__restartNeeded = True self.summaryEdit.append("\n") if res: self.summaryEdit.append(self.trUtf8(\ """The plugins were installed successfully.""")) else: self.summaryEdit.append(self.trUtf8(\ """Some plugins could not be installed.""")) return res def __installPlugin(self, archiveFilename): """ Private slot to install the selected plugin. @param archiveFilename name of the plugin archive file (string or QString) @return flag indicating success (boolean), error message upon failure (QString) and flag indicating a restart of the IDE is required (boolean) """ installedPluginName = "" archive = unicode(archiveFilename) destination = \ unicode(self.destinationCombo.itemData(self.destinationCombo.currentIndex())\ .toString()) # check if archive is a local url url = urlparse.urlparse(archive) if url[0].lower() == 'file': archive = url[2] # check, if the archive exists if not os.path.exists(archive): return False, \ self.trUtf8("""<p>The archive file <b>%1</b> does not exist. """ """Aborting...</p>""").arg(archive), \ False # check, if the archive is a valid zip file if not zipfile.is_zipfile(archive): return False, \ self.trUtf8("""<p>The file <b>%1</b> is not a valid plugin """ """ZIP-archive. Aborting...</p>""").arg(archive), \ False # check, if the destination is writeable if not os.access(destination, os.W_OK): return False, \ self.trUtf8("""<p>The destination directory <b>%1</b> is not """ """writeable. Aborting...</p>""").arg(destination), \ False zip = zipfile.ZipFile(archive, "r") # check, if the archive contains a valid plugin pluginFound = False pluginFileName = "" for name in zip.namelist(): if self.__pluginManager.isValidPluginName(name): installedPluginName = name[:-3] pluginFound = True pluginFileName = name break if not pluginFound: return False, \ self.trUtf8("""<p>The file <b>%1</b> is not a valid plugin """ """ZIP-archive. Aborting...</p>""").arg(archive), \ False # parse the plugin module's plugin header pluginSource = zip.read(pluginFileName) packageName = "" internalPackages = [] needsRestart = False for line in pluginSource.splitlines(): if line.startswith("packageName"): tokens = line.split("=") if tokens[0].strip() == "packageName" and \ tokens[1].strip()[1:-1] != "__core__": if tokens[1].strip()[0] in ['"', "'"]: packageName = tokens[1].strip()[1:-1] else: if tokens[1].strip() == "None": packageName = "None" elif line.startswith("internalPackages"): tokens = line.split("=") token = tokens[1].strip()[1:-1] # it is a comma separated string internalPackages = [p.strip() for p in token.split(",")] elif line.startswith("needsRestart"): tokens = line.split("=") needsRestart = tokens[1].strip() == "True" elif line.startswith("# End-Of-Header"): break if not packageName: return False, \ self.trUtf8("""<p>The plugin module <b>%1</b> does not contain """ """a 'packageName' attribute. Aborting...</p>""")\ .arg(pluginFileName), \ False # check, if it is a plugin, that collides with others if not os.path.exists(os.path.join(destination, pluginFileName)) and \ packageName != "None" and \ os.path.exists(os.path.join(destination, packageName)): return False, \ self.trUtf8("""<p>The plugin package <b>%1</b> exists. """ """Aborting...</p>""")\ .arg(os.path.join(destination, packageName)), \ False if os.path.exists(os.path.join(destination, pluginFileName)) and \ packageName != "None" and \ not os.path.exists(os.path.join(destination, packageName)): return False, \ self.trUtf8("""<p>The plugin module <b>%1</b> exists. """ """Aborting...</p>""")\ .arg(os.path.join(destination, pluginFileName)), \ False activatePlugin = False if not self.__external: activatePlugin = \ not self.__pluginManager.isPluginLoaded(installedPluginName) or \ (self.__pluginManager.isPluginLoaded(installedPluginName) and \ self.__pluginManager.isPluginActive(installedPluginName)) # try to unload a plugin with the same name self.__pluginManager.unloadPlugin(installedPluginName, destination) # uninstall existing plugin first to get clean conditions self.__uninstallPackage(destination, pluginFileName, packageName) # clean sys.modules reload_ = self.__pluginManager.removePluginFromSysModules( installedPluginName, packageName, internalPackages) # now do the installation self.__installedDirs = [] self.__installedFiles = [] try: if packageName != "None": packageDirs = ["%s/" % packageName, "%s\\" % packageName] namelist = zip.namelist() namelist.sort() tot = len(namelist) prog = 0 self.progress.setMaximum(tot) QApplication.processEvents() for name in namelist: self.progress.setValue(prog) QApplication.processEvents() prog += 1 if name == pluginFileName or \ name.startswith("%s/" % packageName) or \ name.startswith("%s\\" % packageName): outname = name.replace("/", os.sep) outname = os.path.join(destination, outname) if outname.endswith("/") or outname.endswith("\\"): # it is a directory entry outname = outname[:-1] if not os.path.exists(outname): self.__makedirs(outname) else: # it is a file d = os.path.dirname(outname) if not os.path.exists(d): self.__makedirs(d) f = open(outname, "wb") f.write(zip.read(name)) f.close() self.__installedFiles.append(outname) self.progress.setValue(tot) # now compile user interface files compileUiFiles(os.path.join(destination, packageName), True) else: outname = os.path.join(destination, pluginFileName) f = open(outname, "wb") f.write(pluginSource) f.close() self.__installedFiles.append(outname) except os.error, why: self.__rollback() return False, \ self.trUtf8("Error installing plugin. Reason: %1").arg(str(why)), \ False except IOError, why: self.__rollback() return False, \ self.trUtf8("Error installing plugin. Reason: %1").arg(str(why)), \ False
def OnOk(self, event): """ When Run button is clicked """ assert (self.master is not None) if self._value.GetValidator().Validate(self._value) or self.ntl: ### pour prendre en compte les simulations multiples sans relancer un SimulationDialog ### si le thread n'est pas lancé (pas pendant un suspend) if self.thread is not None and not self.thread.thread_suspend: diagram = self.master.getBlockModel() diagram.Clean() self.current_master = Container.Diagram.makeDEVSInstance( diagram) else: self.current_master = self.master if isinstance(self.parent, wx.Panel): # redirection du stdout ici dans le cas du Panel (sinon dans OnSimulation) mainW = self.parent.GetTopLevelParent() sys.stdout = mainW.stdioWin ### test si le modele et bien charge if (self.current_master == None) or (self.current_master.getComponentSet() == []): return self.MsgBoxEmptyModel() ### dont erase the gauge if ntl if not self.ntl: # stockage du temps de simulation dans le master self.current_master.FINAL_TIME = float(self._value.GetValue()) self._gauge.SetValue(0) ### if _gauge is wx.Slider #self._gauge.SetMax(self.current_master.FINAL_TIME) self.statusbar.SetBackgroundColour('') printOnStatusBar(self.statusbar, {1: ""}) if self.statusbar.GetFieldsCount() > 2: printOnStatusBar(self.statusbar, {2: ""}) if (self.thread is None) or (not self.timer.IsRunning()): PluginManager.trigger_event("START_BLINK", parent=self, master=self.current_master) PluginManager.trigger_event("START_TEST", parent=self, master=self.current_master) ### The START_ACTIVITY_TRACKING event occurs PluginManager.trigger_event("START_ACTIVITY_TRACKING", parent=self, master=self.current_master) ### The START_ACTIVITY_TRACKING event occurs PluginManager.trigger_event("START_STATE_TRAJECTORY", parent=self, master=self.current_master) ### The START_CONCURRENT_SIMULATION event occurs PluginManager.trigger_event("START_CONCURRENT_SIMULATION", parent=self, master=self.current_master) ### future call is required because the simulator is flattened during the execution of the strategy 3 wx.FutureCall(1, PluginManager.trigger_event, 'START_DIAGRAM', parent=self, master=self.current_master) ### clear all log file for fn in [ f for f in os.listdir(gettempdir()) if f.endswith('.devsimpy.log') ]: os.remove(os.path.join(gettempdir(), fn)) self.thread = simulator_factory(self.current_master, self.selected_strategy, self.prof, self.ntl, self.verbose, self.dynamic_structure_flag, self.real_time_flag) self.thread.setName(self.title) ### si le modele n'a pas de couplage, ou si pas de generateur: alors pas besoin de simuler if self.thread.end_flag: self.OnTimer(event) else: self.timer.Start(100) ### timer for real time if self.real_time_flag: self.t = timer() else: ### for back simulation #self.thread.s = shelve.open(self.thread.f.name+'.db',flag='r') #self.thread.model = self.thread.s['s'][str(float(self._gauge.GetValue()))] ### restart the hiding gauge if self.ntl: self._gauge.Show() ### restart thread self.thread.resume_thread() self.Interact(False) if self.count >= 100: return
def __init__( self ): self.pluginManager = PluginManager() self.home = os.path.expanduser( "~" ) self.fichierConfiguration = self.home + "/.tvdownloader/conf/tvdownloader" self.chargerConfiguration()
def __init__(self, plugin_dir, plugins=()): config = {} default_directory = plugin_dir self.directories = config.get("directories", (default_directory,)) logger.info("========DirectoryPlugManager========%s", plugins) PluginManager.__init__(self, plugins)
class Notifier: ''' main class ''' program_dir = os.path.dirname(os.path.realpath(__file__)) plugin_man = None plugin_context = None conf = None feed = None do_refresh = False def __init__(self): try: logger.info('Initializing directories...') dirs = self.init_dirs() os.chdir(dirs.user_cache_dir) logger.debug('* Cache: ' + dirs.user_cache_dir) logger.info('* Data: ' + dirs.user_data_dir) plugin_dirs = [] plugin_dirs.append(os.path.join(self.program_dir, 'plugins')) plugin_dirs.append(os.path.join(dirs.user_data_dir, 'plugins')) for d in plugin_dirs: logger.info('* Plugins: ' + d) print('') logger.info('Initializing configuration...') conf_file_path = os.path.join(dirs.user_data_dir, 'fbnotify.conf') logger.info('* File: ' + conf_file_path) self.conf = Config(conf_file_path) print('') logger.info('Initializing feed...') self.feed = Feed(self.conf.feed.url) print('') logger.info('Initializing plugins...') logger.debug('* Blacklisted: ' + str(self.conf.program.plugin_blacklist)) self.plugin_man = PluginManager(plugin_dirs, self.conf.program.plugin_blacklist) self.plugin_man.load_by_role('notify') self.plugin_man.load_by_role('list') self.plugin_man.load_by_role('status') self.plugin_context = self.plugin_man.messaging.register_plugin(self, 'fbnotify') print('') logger.debug('Work dir: ' + os.getcwd()) print except Exception as e: logger.error(traceback.format_exc()) self.bad_stop() def start(self): ''' main loop ''' try: while True: logger.info('Updating...' + ' [' + email.utils.formatdate(time.mktime(time.localtime()), True) + ']') # Update the feed self.plugin_man.messaging.send( 'status', status='updating', description='Updating' ) new_items = None try: new_items = self.feed.get_new_items() except IOError: # Error self.plugin_man.messaging.send( 'status', status='error', description='Unable to load feed URL' ) self.adjust_interval(0) # If new items are loaded if new_items is not None: self.plugin_man.messaging.send( 'status', status='idle', description='Waiting' ) self.notify_items(new_items) self.adjust_interval(len(new_items)) # Wait count = 0 while count < self.conf.feed.check_interval: time.sleep(0.25) count += 0.25 self.plugin_context.receive() if self.do_refresh: break self.do_refresh = False print('') except KeyboardInterrupt: print('') logger.info('Stopped') self.stop() except Exception as e: logger.error(traceback.format_exc()) self.bad_stop() self.bad_stop(); def plugin_receive(self, channel, message): # Receiving a message from the 'fbnotify' channel if 'quit' in message: logger.debug('Quit requested') self.stop() elif 'refresh' in message: logger.debug('Refresh requested') self.do_refresh = True def bad_stop(self): ''' bad things happened, so bad that the application must stop ''' logger.error('Bad Exit!') self.stop() def stop(self): ''' stop the application ''' if self.plugin_man: logger.info('Unloading all plugins...') self.plugin_man.unload_all() logger.info('Exit') quit() def notify_items(self, items): ''' shows notifications about items ''' n = len(items) n_new_notifications = '{0} new notification{1}'.format(n, '' if n == 1 else 's') logger.info(n_new_notifications) if n == 0: return # Update item list self.plugin_man.messaging.send( 'list', items = items ) if n > 1: # Many notifications if self.conf.notification.itemize >= n: # Show individual notifications interval = self.conf.notification.item_interval for item in sorted(items, key=lambda x: x.dt): if item.image_path == None: self.notify(item.text, self.format_time(item.dt), timeout=interval, link=item.link) else: self.notify(item.text, self.format_time(item.dt), icon='file://' + item.image_path, timeout=interval, link=item.link) time.sleep(interval + 1) else: # Declare multiple notifications dt = items[n-1].dt # Earliest notification date self.notify(n_new_notifications, self.format_time(dt), link='www.facebook.com/notifications') else: # Single notification item = items[0] if self.conf.notification.show_content: if item.image_path == None: self.notify(item.text, self.format_time(item.dt), link=item.link) else: self.notify(item.text, self.format_time(item.dt), icon='file://' + item.image_path, link=item.link) else: self.notify(n_new_notifications, self.format_time(item.dt)) def notify(self, title, body, icon=icons.xdg_icon, timeout=10, link=None): ''' requests to show a notification ''' logger.debug('Notify: ' + title + ' ' + body) # This will send a message to any plugin # listening to the 'notify' channel self.plugin_man.messaging.send( 'notify', title = title, body = body, icon = icon, timeout = timeout, link = link ) def adjust_interval(self, new): ''' automatically adjust the feed check interval ''' if self.conf.feed.dynamic_interval: ci = self.conf.feed.check_interval if new: min_interval = 15 # 15 seconds if ci > min_interval: ci = ci * 1/5 if ci < min_interval: ci = min_interval logger.info('Decreased check interval to {0}s'.format(ci)) else: max_interval = 60 * 20 # 20 minutes if ci < max_interval: ci = ci * 8/7 if ci > max_interval: ci = max_interval logger.info('Increased check interval to {0}s'.format(ci)) self.conf.feed.check_interval = ci def init_dirs(self): ''' creates, if not existing, application directories ''' dirs = appdirs.AppDirs('fbnotify', 'Kalabasa') conf_dir = dirs.user_data_dir cache_dir = dirs.user_cache_dir if not os.path.isdir(conf_dir): logger.info('Created configuration directory ' + conf_dir) os.makedirs(conf_dir) if not os.path.isdir(cache_dir): logger.info('Created cache directory ' + cache_dir) os.makedirs(cache_dir) return dirs def format_time(self, then): ''' Formats relative time to the specified time ''' now = datetime.now() if then >= now: text = 'Just now' else: delta = now - then if delta.days >= 1: text = '{0} day{1} ago'.format(delta.days, '' if delta.days == 1 else 's') elif delta.seconds >= 3600: hours = delta.seconds / 3600 text = '{0} hour{1} ago'.format(hours, '' if hours == 1 else 's') elif delta.seconds >= 60: minutes = delta.seconds / 60 text = '{0} minute{1} ago'.format(minutes, '' if minutes == 1 else 's') elif delta.seconds >= 30: text = '{0} second{1} ago'.format(delta.seconds, '' if delta.seconds == 1 else 's') else: text = 'Just now' return text
def setUp(self): HoneypotBase.read_config() self.thread = PluginManager(Plugin(), HoneypotBase.Session) self.thread.start() time.sleep(.1)
class PreferencesDialog(QtGui.QDialog): ## Constructeur # @param signaux Lanceur de signaux def __init__(self, parent, signaux): # Appel au constructeur de la classe mere QtGui.QDialog.__init__(self, parent) self.preferences = Preferences() self.pluginManager = PluginManager() self.signaux = signaux ########### # Fenetre # ########### ### # Reglages de la fenetre principale ### # Nom de la fenetre self.setWindowTitle(u"Préférences") # Dimensions la fenetre self.resize(280, 340) # Mise en place de son icone self.setWindowIcon(QtGui.QIcon("ico/gtk-preferences.svg")) ### # Mise en place des widgets dans la fenetre ### # Layout de grille principal self.gridLayout = QtGui.QGridLayout(self) # Font pour les titres fontTitres = QtGui.QFont() fontTitres.setPointSize(11) fontTitres.setWeight(75) fontTitres.setBold(True) # # Choix du repertoire telechargement # # Label self.labelRepertoire = QtGui.QLabel(self) self.labelRepertoire.setFont(fontTitres) self.labelRepertoire.setText(u"Répertoire de téléchargement :") # Repertoire de telechargement self.lineEditRepertoireTelechargement = QtGui.QLineEdit(self) # Bouton pour ouvrir la fenetre de selection de repertoire self.pushButtonSelectionDossier = QtGui.QPushButton(self) self.pushButtonSelectionDossier.setIcon( QtGui.QIcon("ico/gtk-folder.svg")) # # Choix du plugin par defaut # # Label self.labelPluginDefaut = QtGui.QLabel(self) self.labelPluginDefaut.setFont(fontTitres) self.labelPluginDefaut.setText(u"Plugin par défaut :") # Liste de choix du plugin par defaut self.comboBoxPluginDefaut = QtGui.QComboBox(self) # # Choix des plugins a activer # # Label self.labelPlugins = QtGui.QLabel(self) self.labelPlugins.setFont(fontTitres) self.labelPlugins.setText("Plugins actifs :") # Liste des plugins self.listWidgetPlugin = QtGui.QListWidget(self) # # Choix des parametres Internet # # Label self.labelInternet = QtGui.QLabel(self) self.labelInternet.setFont(fontTitres) self.labelInternet.setText(u"Paramètres Internet :") # Layout formulaire self.layoutInternet = QtGui.QFormLayout() # SpinBox pour choisir le timeOut self.spinBoxTimeOut = QtGui.QSpinBox() self.spinBoxTimeOut.setMinimum(1) self.spinBoxTimeOut.setMaximum(60) self.layoutInternet.addRow(u"Time out (en s) :", self.spinBoxTimeOut) # SpinBox pour choisir le nombre de threads max self.spinBoxNbThread = QtGui.QSpinBox() self.spinBoxNbThread.setMinimum(1) self.spinBoxNbThread.setMaximum(100) self.layoutInternet.addRow(u"Nombre de threads max :", self.spinBoxNbThread) # Bouton pour enregistrer/annuler les preferences self.buttonBox = QtGui.QDialogButtonBox(self) self.buttonBox.addButton("Enregistrer", QtGui.QDialogButtonBox.AcceptRole) self.buttonBox.addButton("Fermer", QtGui.QDialogButtonBox.RejectRole) # On ajoute le tout au layout self.gridLayout.addWidget(self.labelRepertoire, 0, 0, 1, 2) self.gridLayout.addWidget(self.lineEditRepertoireTelechargement, 1, 0, 1, 1) self.gridLayout.addWidget(self.pushButtonSelectionDossier, 1, 1, 1, 1) self.gridLayout.addWidget(self.labelPluginDefaut, 2, 0, 1, 2) self.gridLayout.addWidget(self.comboBoxPluginDefaut, 3, 0, 1, 2) self.gridLayout.addWidget(self.labelPlugins, 4, 0, 1, 2) self.gridLayout.addWidget(self.listWidgetPlugin, 5, 0, 1, 2) self.gridLayout.addWidget(self.labelInternet, 6, 0, 1, 2) self.gridLayout.addLayout(self.layoutInternet, 7, 0, 1, 2) self.gridLayout.addWidget(self.buttonBox, 8, 0, 1, 2) ### # Signaux provenants de l'interface ### QtCore.QObject.connect(self.pushButtonSelectionDossier, QtCore.SIGNAL("clicked()"), self.afficherSelecteurDossier) QtCore.QObject.connect(self.buttonBox, QtCore.SIGNAL("accepted()"), self.enregistrerPreferences) QtCore.QObject.connect(self.buttonBox, QtCore.SIGNAL("rejected()"), self.reject) ## Methode pour afficher la fenetre des preferences def afficher(self): # On met en place dans le textEdit le repertoire self.lineEditRepertoireTelechargement.setText( stringToQstring( self.preferences.getPreference("repertoireTelechargement"))) # On met en place le plugin par defaut self.remplirPluginParDefaut() # On met en place la liste des plugins self.afficherPlugins() # On met en place les valeurs des SpinBox self.spinBoxTimeOut.setValue(self.preferences.getPreference("timeOut")) self.spinBoxNbThread.setValue( self.preferences.getPreference("nbThreadMax")) # On affiche la fenetre self.exec_() ## Methode pour enregistrer les preferences du logiciel def enregistrerPreferences(self): # On sauvegarde les valeurs des SpinBox self.preferences.setPreference("nbThreadMax", self.spinBoxNbThread.value()) self.preferences.setPreference("timeOut", self.spinBoxTimeOut.value()) # On sauvegarde les plugins actifs self.sauvegarderPlugins() # On sauvegarde le plugin par defaut self.preferences.setPreference( "pluginParDefaut", qstringToString(self.comboBoxPluginDefaut.currentText())) # On sauvegarde le repertoire de telechargement self.preferences.setPreference( "repertoireTelechargement", qstringToString(self.lineEditRepertoireTelechargement.text())) # On sauvegarde dans le fichier self.preferences.sauvegarderConfiguration() # On masque la fenetre self.hide() #################################################################### # Methodes qui gerent l'emplacement de telechargement des fichiers # #################################################################### ## Methode qui affiche le selecteur de dossier def afficherSelecteurDossier(self): rep = QtGui.QFileDialog.getExistingDirectory( None, u"Sélectionnez le répertoire de téléchargement", self.lineEditRepertoireTelechargement.text(), QtGui.QFileDialog.ShowDirsOnly) # Si le repertoire existe if (os.path.isdir(rep)): self.lineEditRepertoireTelechargement.setText( rep) # On modifie la zone de texte qui affiche le repertoire ################################################ # Methodes qui gerent la partie plugins actifs # ################################################ ## Methode qui liste les plugins actif dans le listWidgetPlugin def afficherPlugins(self): # On recupere les listes de plugins listePluginsDisponibles = self.pluginManager.getListeSites() listePluginsDisponibles.sort() # On trie cette liste listePluginsActives = self.preferences.getPreference("pluginsActifs") # On remet a 0 le listWidget self.listWidgetPlugin.clear() # On affiche les plugins for plugin in listePluginsDisponibles: # On met en place l'item self.listWidgetPlugin.addItem( self.creerItem(plugin, plugin in listePluginsActives)) ## Methode qui remplie la combo box du plugin par defaut def remplirPluginParDefaut(self): # On efface la liste self.comboBoxPluginDefaut.clear() # On ajoute les plugins actifs for plugin in self.preferences.getPreference("pluginsActifs"): self.comboBoxPluginDefaut.addItem(stringToQstring(plugin)) # On selectionne le plugin par defaut index = self.comboBoxPluginDefaut.findText( stringToQstring(self.preferences.getPreference("pluginParDefaut"))) if (index != -1): self.comboBoxPluginDefaut.setCurrentIndex(index) ## Methode qui sauvegarde les plugins actifs def sauvegarderPlugins(self): # On liste les plugins actifs liste = [] for i in range(self.listWidgetPlugin.count()): # Pour chaque ligne if (self.listWidgetPlugin.item(i).checkState() == QtCore.Qt.Checked ): # Si elle est selectionnee liste.append( qstringToString(self.listWidgetPlugin.item(i).text())) # On met cela en place dans les preferences self.preferences.setPreference("pluginsActifs", liste) # On relance l'actualisation de l'affichage self.signaux.signal("actualiserListesDeroulantes") #################### # Autres methodes # #################### ## Methode qui creer une element pour un listeWidget # @param texte Texte de l'element # @param checkBox Si la checkBox de l'element est cochee ou non # @return L'element cree def creerItem(self, texte, checkBox=False): # On cree l'item avec le texte item = QtGui.QListWidgetItem(stringToQstring(texte)) # On centre le texte item.setTextAlignment(QtCore.Qt.AlignCenter) # L'item ne doit pas etre modifiable item.setFlags(item.flags() & ~QtCore.Qt.ItemIsEditable) # L'item doit avoir sa checkBox cochee ? if (checkBox): item.setCheckState(QtCore.Qt.Checked) else: item.setCheckState(QtCore.Qt.Unchecked) # On renvoie l'item return item
class CmdInterpreter(Cmd): # We use this variable at Breakpoint #1. # We use this in order to allow Jarvis say "Hi", only at the first # interaction. # This can be used to store user specific data def __init__(self, first_reaction_text, prompt, directories=[], first_reaction=True, enable_voice=False): """ This constructor contains a dictionary with Jarvis Actions (what Jarvis can do). In alphabetically order. """ Cmd.__init__(self) self.first_reaction = first_reaction self.first_reaction_text = first_reaction_text self.prompt = prompt self.enable_voice = enable_voice # Register do_quit() function to SIGINT signal (Ctrl-C) signal.signal(signal.SIGINT, self.interrupt_handler) self.memory = Memory() self.scheduler = schedule.Scheduler() self.speech = create_voice() self.fixed_responses = { "what time is it": "clock", "where am i": "pinpoint", } self._api = JarvisAPI(self) self._plugin_manager = PluginManager() for directory in directories: self._plugin_manager.add_directory(directory) self._activate_plugins() self._init_plugin_info() def _init_plugin_info(self): plugin_status_formatter = { "disabled": len(self._plugin_manager.get_disabled()), "enabled": self._plugin_manager.get_number_plugins_loaded(), "red": Fore.RED, "blue": Fore.BLUE, "reset": Fore.RESET } plugin_status = "{red}{enabled} {blue}plugins loaded" if plugin_status_formatter['disabled'] > 0: plugin_status += " {red}{disabled} {blue}plugins disabled. More information: {red}status\n" plugin_status += Fore.RESET self.first_reaction_text += plugin_status.format( **plugin_status_formatter) def _activate_plugins(self): """Generate do_XXX, help_XXX and (optionally) complete_XXX functions""" for (plugin_name, plugin) in self._plugin_manager.get_plugins().items(): self._plugin_update_completion(plugin, plugin_name) run_catch = catch_all_exceptions(plugin.run) setattr(CmdInterpreter, "do_" + plugin_name, partial(run_catch, self)) setattr(CmdInterpreter, "help_" + plugin_name, partial(self._api.say, plugin.get_doc())) plugin.init(self._api) def _plugin_update_completion(self, plugin, plugin_name): """Return True if completion is available""" completions = [i for i in plugin.complete()] if len(completions) > 0: def complete(completions): def _complete_impl(self, text, line, begidx, endidx): return [i for i in completions if i.startswith(text)] return _complete_impl setattr(CmdInterpreter, "complete_" + plugin_name, complete(completions)) def get_api(self): return self._api def close(self): """Closing Jarvis.""" print_say("Goodbye, see you later!", self, Fore.RED) self.scheduler.stop_all() exit() def completedefault(self, text, line, begidx, endidx): """Default completion""" return [i for i in self.actions if i.startswith(text)] def error(self): """Jarvis let you know if an error has occurred.""" print_say("I could not identify your command...", self, Fore.RED) def get_completions(self, command, text): """Returns a list with the completions of a command.""" dict_target = [ item for item in self.actions if type(item) == dict and command in item ][0] completions_list = dict_target[command] return [i for i in completions_list if i.startswith(text) and i != ''] def interrupt_handler(self, signal, frame): """Closes Jarvis on SIGINT signal. (Ctrl-C)""" self.close() def do_status(self, s): """Prints plugin status status""" count_enabled = self._plugin_manager.get_number_plugins_loaded() count_disabled = len(self._plugin_manager.get_disabled()) print_say( "{} Plugins enabled, {} Plugins disabled.".format( count_enabled, count_disabled), self) if "short" not in s and count_disabled > 0: print_say("", self) for disabled, reason in self._plugin_manager.get_disabled().items( ): print_say("{:<20}: {}".format(disabled, "OR ".join(reason)), self) def help_status(self): print_say("Prints info about enabled or disabled plugins", self) print_say("Use \"status short\" to omit detailed information.", self)
class Preferences( object ): # Instance de la classe (singleton) instance = None ## Surcharge de la methode de construction standard (pour mettre en place le singleton) def __new__( self, *args, **kwargs ): if( self.instance is None ): self.instance = super( Preferences, self ).__new__( self ) return self.instance ## Constructeur def __init__( self ): self.pluginManager = PluginManager() self.home = os.path.expanduser( "~" ) self.fichierConfiguration = self.home + "/.tvdownloader/conf/tvdownloader" self.chargerConfiguration() ## Methode qui charge les preferences du logiciel def chargerConfiguration( self ): # Parametres par defaut self.preferencesParDefault = { "repertoireTelechargement" : self.home + "/TVDownloader", "pluginsActifs" : [], "pluginParDefaut" : "", "tailleFenetre" : [ 500, 500 ], "timeOut" : 5, "nbThreadMax" : 20 } if os.path.exists( self.fichierConfiguration ): # Si le fichier existe, on le charge # On recupere les preferences dans le fichier fichier = open( self.fichierConfiguration, "r" ) self.preferences = pickle.load( fichier ) fichier.close() # On verifie qu'il ne nous manque pas une preference # Si c'est le cas, on prend sa valeur par defaut for elmt in self.preferencesParDefault.keys(): if not self.preferences.has_key( elmt ): self.preferences[ elmt ] = self.preferencesParDefault[ elmt ] else: # Sinon, on utilise les parametres par defaut self.preferences = self.preferencesParDefault # On active les plugins qui doivent etre actifs for plugin in self.preferences[ "pluginsActifs" ]: self.pluginManager.activerPlugin( plugin ) # On cree le repertoire de telechargement s'il n'existe pas if( not os.path.isdir( self.preferences[ "repertoireTelechargement" ] ) ): os.makedirs( self.preferences[ "repertoireTelechargement" ] ) # On applique les preferences self.appliquerPreferences() ## Methode qui applique certaines preferences du logiciel # Seuls les preferences des classes qui utilise le singleton sont applquees def appliquerPreferences( self ): Navigateur.timeOut = self.preferences[ "timeOut" ] Navigateur.maxThread = self.preferences[ "nbThreadMax" ] ## Methode qui sauvegarde les preferences du logiciel def sauvegarderConfiguration( self ): # On applique les preferences self.appliquerPreferences() # On sauvegarde les preferences dans le fichier de configuration fichier = open( self.fichierConfiguration, "w" ) pickle.dump( self.preferences, fichier ) fichier.close() ## Methode qui renvoit une preference du logiciel # @param nomPreference Nom de la preference a renvoyer # @return Valeur de cette preference def getPreference( self, nomPreference ): try: return self.preferences[ nomPreference ] except KeyError: logger.warn( "preference %s inconnue" %( nomPreference ) ) return None ## Methode qui met en place la valeur d'une preference # @param nomPreference Nom de la preference dont on va mettre en place la valeur # @param valeur Valeur a mettre en place def setPreference( self, nomPreference, valeur ): # Si on sauvegarde une nouvelle liste de plugin if( nomPreference == "pluginsActifs" ): nouvelleListe = valeur ancienneListe = self.preferences[ "pluginsActifs" ] # Pour chaque element dans l'union des 2 listes for elmt in ( set( nouvelleListe ).union( set( ancienneListe ) ) ): if( ( elmt in ancienneListe ) and not ( elmt in nouvelleListe ) ): self.pluginManager.desactiverPlugin( elmt ) elif( ( elmt in nouvelleListe ) and not ( elmt in ancienneListe ) ): self.pluginManager.activerPlugin( elmt ) # Dans tous les cas, on sauvegarde la preference self.preferences[ nomPreference ] = valeur
def LoadAllPlugin(): PluginManager.LoadAllPlugin()
from PluginManager import PluginManager import discord import traceback import re print("Starting JithBot") print("Starting Discord Client") # Creates a discord client, which we will use to connect and interact with the server. # All methods with @client.event annotations are event handlers for this client. client = discord.Client() print("Loading plugins") # Loads and initializes the plugin manager for the bot pm = PluginManager("plugins", client) pm.load_plugins() pm.register_events() print("Plugins loaded and registered") @client.event async def on_ready(): """ Event handler, fires when the bot has connected and is logged in """ print('Logged in as ' + client.user.name + " (" + client.user.id + ")") # Change nickname to nickname in configuration for instance in client.servers: await client.change_nickname(instance.me, pm.botPreferences.nickName) await client.change_presence( game=discord.Game(name='Evolving into a sentient being', type=0))
def StartAllPlugin(): PluginManager.StartAllPlugin()
class PreferencesDialog( QtGui.QDialog ): ## Constructeur def __init__( self, parent ): # Appel au constructeur de la classe mere QtGui.QDialog.__init__( self, parent ) self.preferences = Preferences() self.pluginManager = PluginManager() ########### # Fenetre # ########### ### # Reglages de la fenetre principale ### # Nom de la fenetre self.setWindowTitle( u"Préférences" ) # Dimensions la fenetre self.resize( 325, 510 ) # Mise en place de son icone self.setWindowIcon( QtGui.QIcon( "ico/gtk-preferences.svg" ) ) ### # Mise en place des widgets dans la fenetre ### # Layout du dialog (il ne contiendra que la scroll area) self.layoutPrincipal = QtGui.QVBoxLayout( self ) # Scroll Area (elle ne contiendra que le widget central) self.scrollArea = QtGui.QScrollArea( self ) self.layoutPrincipal.addWidget( self.scrollArea ) # Widget central self.widgetCentral = QtGui.QWidget( self.scrollArea ) # Layout de grillequi contient les elements self.gridLayout = QtGui.QGridLayout( self.widgetCentral ) # Font pour les titres fontTitres = QtGui.QFont() fontTitres.setPointSize( 11 ) fontTitres.setWeight( 75 ) fontTitres.setBold( True ) # # Choix du repertoire telechargement # # Label self.labelRepertoire = QtGui.QLabel( self ) self.labelRepertoire.setFont( fontTitres ) self.labelRepertoire.setText( u"Répertoire de téléchargement :" ) # Repertoire de telechargement self.lineEditRepertoireTelechargement = QtGui.QLineEdit( self ) # Bouton pour ouvrir la fenetre de selection de repertoire self.pushButtonSelectionDossier = QtGui.QPushButton( self ) self.pushButtonSelectionDossier.setIcon( QtGui.QIcon( "ico/gtk-folder.svg" ) ) # # Choix du plugin par defaut # # Label self.labelPluginDefaut = QtGui.QLabel( self ) self.labelPluginDefaut.setFont( fontTitres ) self.labelPluginDefaut.setText( u"Plugin par défaut :" ) # Liste de choix du plugin par defaut self.comboBoxPluginDefaut = QtGui.QComboBox( self ) # # Choix des plugins a activer # # Label self.labelPlugins = QtGui.QLabel( self ) self.labelPlugins.setFont( fontTitres ) self.labelPlugins.setText( "Plugins actifs :" ) # Liste des plugins self.listWidgetPlugin = QtGui.QListWidget( self ) # # Choix des parametres Internet # # Label self.labelInternet = QtGui.QLabel( self ) self.labelInternet.setFont( fontTitres ) self.labelInternet.setText( u"Paramètres Internet :" ) # Layout formulaire self.layoutInternet = QtGui.QFormLayout() # SpinBox pour choisir le timeOut self.spinBoxTimeOut = QtGui.QSpinBox() self.spinBoxTimeOut.setMinimum( 1 ) self.spinBoxTimeOut.setMaximum( 60 ) self.layoutInternet.addRow( u"Time out (en s) :", self.spinBoxTimeOut ) # SpinBox pour choisir le nombre de threads max self.spinBoxNbThread = QtGui.QSpinBox() self.spinBoxNbThread.setMinimum( 1 ) self.spinBoxNbThread.setMaximum( 100 ) self.layoutInternet.addRow( u"Nombre de threads max :", self.spinBoxNbThread ) # Bouton pour enregistrer/annuler les preferences self.buttonBox = QtGui.QDialogButtonBox( self ) self.buttonBox.addButton( "Enregistrer", QtGui.QDialogButtonBox.AcceptRole ) self.buttonBox.addButton( "Fermer", QtGui.QDialogButtonBox.RejectRole ) # On ajoute le tout au layout self.gridLayout.addWidget( self.labelRepertoire, 0, 0, 1, 2 ) self.gridLayout.addWidget( self.lineEditRepertoireTelechargement, 1, 0, 1, 1 ) self.gridLayout.addWidget( self.pushButtonSelectionDossier, 1, 1, 1, 1 ) self.gridLayout.addWidget( self.labelPluginDefaut, 2, 0, 1, 2 ) self.gridLayout.addWidget( self.comboBoxPluginDefaut, 3, 0, 1, 2 ) self.gridLayout.addWidget( self.labelPlugins, 4, 0, 1, 2 ) self.gridLayout.addWidget( self.listWidgetPlugin, 5, 0, 1, 2 ) self.gridLayout.addWidget( self.labelInternet, 6, 0, 1, 2 ) self.gridLayout.addLayout( self.layoutInternet, 7, 0, 1, 2 ) # Les boutons sont ajoutes au layout principal self.layoutPrincipal.addWidget( self.buttonBox ) # On adapte la taille du widget self.widgetCentral.adjustSize() # On ajoute le widget central a la scroll area self.scrollArea.setWidget( self.widgetCentral ) ### # Signaux provenants de l'interface ### QtCore.QObject.connect( self.pushButtonSelectionDossier, QtCore.SIGNAL( "clicked()" ), self.afficherSelecteurDossier ) QtCore.QObject.connect( self.buttonBox, QtCore.SIGNAL( "accepted()" ), self.enregistrerPreferences ) QtCore.QObject.connect( self.buttonBox, QtCore.SIGNAL( "rejected()" ), self.reject ) ## Methode pour afficher la fenetre des preferences def afficher( self ): # On met en place dans le textEdit le repertoire self.lineEditRepertoireTelechargement.setText( stringToQstring( self.preferences.getPreference( "repertoireTelechargement" ) ) ) # On met en place le plugin par defaut self.remplirPluginParDefaut() # On met en place la liste des plugins self.afficherPlugins() # On met en place les valeurs des SpinBox self.spinBoxTimeOut.setValue( self.preferences.getPreference( "timeOut" ) ) self.spinBoxNbThread.setValue( self.preferences.getPreference( "nbThreadMax" ) ) # On affiche la fenetre self.exec_() ## Methode pour enregistrer les preferences du logiciel def enregistrerPreferences( self ): # On sauvegarde les valeurs des SpinBox self.preferences.setPreference( "nbThreadMax", self.spinBoxNbThread.value() ) self.preferences.setPreference( "timeOut", self.spinBoxTimeOut.value() ) # On sauvegarde les plugins actifs self.sauvegarderPlugins() # On sauvegarde le plugin par defaut self.preferences.setPreference( "pluginParDefaut", qstringToString( self.comboBoxPluginDefaut.currentText() ) ) # On sauvegarde le repertoire de telechargement self.preferences.setPreference( "repertoireTelechargement", qstringToString( self.lineEditRepertoireTelechargement.text() ) ) # On sauvegarde dans le fichier self.preferences.sauvegarderConfiguration() # On masque la fenetre self.hide() #################################################################### # Methodes qui gerent l'emplacement de telechargement des fichiers # #################################################################### ## Methode qui affiche le selecteur de dossier def afficherSelecteurDossier( self ): rep = QtGui.QFileDialog.getExistingDirectory( None, u"Sélectionnez le répertoire de téléchargement", self.lineEditRepertoireTelechargement.text(), QtGui.QFileDialog.ShowDirsOnly ) # Si le repertoire existe if( os.path.isdir( qstringToString( rep ) ) ): self.lineEditRepertoireTelechargement.setText( rep ) # On modifie la zone de texte qui affiche le repertoire ################################################ # Methodes qui gerent la partie plugins actifs # ################################################ ## Methode qui liste les plugins actif dans le listWidgetPlugin def afficherPlugins( self ): # On recupere les listes de plugins listePluginsDisponibles = self.pluginManager.getListeSites() listePluginsDisponibles.sort() # On trie cette liste listePluginsActives = self.preferences.getPreference( "pluginsActifs" ) # On remet a 0 le listWidget self.listWidgetPlugin.clear() # On affiche les plugins for plugin in listePluginsDisponibles: # On met en place l'item self.listWidgetPlugin.addItem( self.creerItem( plugin, plugin in listePluginsActives ) ) ## Methode qui remplie la combo box du plugin par defaut def remplirPluginParDefaut( self ): # On efface la liste self.comboBoxPluginDefaut.clear() # On ajoute les plugins actifs for plugin in self.preferences.getPreference( "pluginsActifs" ): self.comboBoxPluginDefaut.addItem( stringToQstring( plugin ) ) # On selectionne le plugin par defaut index = self.comboBoxPluginDefaut.findText( stringToQstring( self.preferences.getPreference( "pluginParDefaut" ) ) ) if( index != -1 ): self.comboBoxPluginDefaut.setCurrentIndex( index ) ## Methode qui sauvegarde les plugins actifs def sauvegarderPlugins( self ): # On liste les plugins actifs liste = [] for i in range( self.listWidgetPlugin.count() ): # Pour chaque ligne if( self.listWidgetPlugin.item( i ).checkState() == QtCore.Qt.Checked ): # Si elle est selectionnee liste.append( qstringToString( self.listWidgetPlugin.item( i ).text() ) ) # On met cela en place dans les preferences self.preferences.setPreference( "pluginsActifs", liste ) # On relance l'actualisation de l'affichage self.emit( QtCore.SIGNAL( "actualiserListesDeroulantes()" ) ) #################### # Autres methodes # #################### ## Methode qui creer une element pour un listeWidget # @param texte Texte de l'element # @param checkBox Si la checkBox de l'element est cochee ou non # @return L'element cree def creerItem( self, texte, checkBox = False ): # On cree l'item avec le texte item = QtGui.QListWidgetItem( stringToQstring( texte ) ) # On centre le texte item.setTextAlignment( QtCore.Qt.AlignCenter ) # L'item ne doit pas etre modifiable item.setFlags( item.flags() & ~QtCore.Qt.ItemIsEditable ) # L'item doit avoir sa checkBox cochee ? if( checkBox ): item.setCheckState( QtCore.Qt.Checked ) else: item.setCheckState( QtCore.Qt.Unchecked ) # On renvoie l'item return item
def __init__(self): from API import API from APIPrive import APIPrive from PluginManager import PluginManager ################################################ # Instanciations + initialisation de variables # ################################################ # On instancie le plugin manager self.pluginManager = PluginManager() # On instancie le gestionnaire de preferences et sa fenetre self.preferences = Preferences() # On instancie le gestionnaire de download self.downloader = Downloader() # On instancie seulement les plugins qui sont selectionnes dans les preferences #~ self.pluginManager.activerPlugins( self.preferences.getPreference( "pluginsActifs" ) ) # On recupere l'instance de API self.api = API.getInstance() # On met en place la liste des plugins dans API current=0 global choice choice='' while choice!='r' and choice!='R': # self.api.setListeInstance( getattr( self.pluginManager, "listeInstances" ) ) pluginsActifs = self.pluginManager.listeInstances plugins = self.pluginManager.getListeSites() plugins.sort() rep= self.preferences.getPreference( "repertoireTelechargement" ) # if choice.isdigit() and int(choice) < int(len(plugins)-10*current): print int(choice)+int(10*current) # elif choice.isdigit() and int(choice) > int(len(plugins)-10*current): print int(choice)+int(10*current) if choice=='q' or choice=='Q': quitter() elif choice.isdigit() and int(choice) < int(len(plugins)-10*current): if plugins[int(choice)+10*current] in pluginsActifs: self.pluginManager.desactiverPlugin(plugins[int(choice)+10*current]) print int(choice)+10*current, else: self.pluginManager.activerPlugin(plugins[int(choice)+10*current]) print int(choice)+10*current, elif choice=='m' or choice =='M': os.system(['clear','cls'][os.name == 'nt']) header ('','','Repertoire de telechargement') choice=raw_input('\n\n\n\n\n\n\n\tVeuillez saisir un repertoire valide\n\n\t\t') if not os.path.isdir(choice): os.system(['clear','cls'][os.name == 'nt']) header ('','','Repertoire de telechargement') print "\n\n\n\n\n\n\n\trepertoire ",choice," inexistant\n\n\t\tRepertoire courant:",rep else : os.system(['clear','cls'][os.name == 'nt']) header ('','','Repertoire de telechargement') rep=choice print "\n\n\n\n\n\n\n\tModification du repertoire de telechargement :\n\n\t\tNouveau repertoire :",choice self.preferences.setPreference( "repertoireTelechargement", str(rep)) time.sleep(1) elif choice=='+': if len(plugins)>current*15+15: current+=1 elif choice=='-': if current!=0: current-=1 #affichage a l'ecran de la liste header ('','','Menus des options') print " Repertoire de telechargement :",rep for i in range(10) : if i+10*current<len(plugins): print "\n ",i,":",plugins[i+10*current], if len(plugins[i+10*current])<=8:print"\t\t", elif len(plugins[i+10*current])<=15:print"\t", for j in pluginsActifs: if j==plugins[i+10*current]: print "actif", else: print "" print "\n\n m:modifier le repertoire de telechargement +/-:afficher les autres plugins" footer() choice=getch()
def __init__( self, parent ): # Appel au constructeur de la classe mere QtGui.QDialog.__init__( self, parent ) self.preferences = Preferences() self.pluginManager = PluginManager() ########### # Fenetre # ########### ### # Reglages de la fenetre principale ### # Nom de la fenetre self.setWindowTitle( u"Préférences" ) # Dimensions la fenetre self.resize( 325, 510 ) # Mise en place de son icone self.setWindowIcon( QtGui.QIcon( "ico/gtk-preferences.svg" ) ) ### # Mise en place des widgets dans la fenetre ### # Layout du dialog (il ne contiendra que la scroll area) self.layoutPrincipal = QtGui.QVBoxLayout( self ) # Scroll Area (elle ne contiendra que le widget central) self.scrollArea = QtGui.QScrollArea( self ) self.layoutPrincipal.addWidget( self.scrollArea ) # Widget central self.widgetCentral = QtGui.QWidget( self.scrollArea ) # Layout de grillequi contient les elements self.gridLayout = QtGui.QGridLayout( self.widgetCentral ) # Font pour les titres fontTitres = QtGui.QFont() fontTitres.setPointSize( 11 ) fontTitres.setWeight( 75 ) fontTitres.setBold( True ) # # Choix du repertoire telechargement # # Label self.labelRepertoire = QtGui.QLabel( self ) self.labelRepertoire.setFont( fontTitres ) self.labelRepertoire.setText( u"Répertoire de téléchargement :" ) # Repertoire de telechargement self.lineEditRepertoireTelechargement = QtGui.QLineEdit( self ) # Bouton pour ouvrir la fenetre de selection de repertoire self.pushButtonSelectionDossier = QtGui.QPushButton( self ) self.pushButtonSelectionDossier.setIcon( QtGui.QIcon( "ico/gtk-folder.svg" ) ) # # Choix du plugin par defaut # # Label self.labelPluginDefaut = QtGui.QLabel( self ) self.labelPluginDefaut.setFont( fontTitres ) self.labelPluginDefaut.setText( u"Plugin par défaut :" ) # Liste de choix du plugin par defaut self.comboBoxPluginDefaut = QtGui.QComboBox( self ) # # Choix des plugins a activer # # Label self.labelPlugins = QtGui.QLabel( self ) self.labelPlugins.setFont( fontTitres ) self.labelPlugins.setText( "Plugins actifs :" ) # Liste des plugins self.listWidgetPlugin = QtGui.QListWidget( self ) # # Choix des parametres Internet # # Label self.labelInternet = QtGui.QLabel( self ) self.labelInternet.setFont( fontTitres ) self.labelInternet.setText( u"Paramètres Internet :" ) # Layout formulaire self.layoutInternet = QtGui.QFormLayout() # SpinBox pour choisir le timeOut self.spinBoxTimeOut = QtGui.QSpinBox() self.spinBoxTimeOut.setMinimum( 1 ) self.spinBoxTimeOut.setMaximum( 60 ) self.layoutInternet.addRow( u"Time out (en s) :", self.spinBoxTimeOut ) # SpinBox pour choisir le nombre de threads max self.spinBoxNbThread = QtGui.QSpinBox() self.spinBoxNbThread.setMinimum( 1 ) self.spinBoxNbThread.setMaximum( 100 ) self.layoutInternet.addRow( u"Nombre de threads max :", self.spinBoxNbThread ) # Bouton pour enregistrer/annuler les preferences self.buttonBox = QtGui.QDialogButtonBox( self ) self.buttonBox.addButton( "Enregistrer", QtGui.QDialogButtonBox.AcceptRole ) self.buttonBox.addButton( "Fermer", QtGui.QDialogButtonBox.RejectRole ) # On ajoute le tout au layout self.gridLayout.addWidget( self.labelRepertoire, 0, 0, 1, 2 ) self.gridLayout.addWidget( self.lineEditRepertoireTelechargement, 1, 0, 1, 1 ) self.gridLayout.addWidget( self.pushButtonSelectionDossier, 1, 1, 1, 1 ) self.gridLayout.addWidget( self.labelPluginDefaut, 2, 0, 1, 2 ) self.gridLayout.addWidget( self.comboBoxPluginDefaut, 3, 0, 1, 2 ) self.gridLayout.addWidget( self.labelPlugins, 4, 0, 1, 2 ) self.gridLayout.addWidget( self.listWidgetPlugin, 5, 0, 1, 2 ) self.gridLayout.addWidget( self.labelInternet, 6, 0, 1, 2 ) self.gridLayout.addLayout( self.layoutInternet, 7, 0, 1, 2 ) # Les boutons sont ajoutes au layout principal self.layoutPrincipal.addWidget( self.buttonBox ) # On adapte la taille du widget self.widgetCentral.adjustSize() # On ajoute le widget central a la scroll area self.scrollArea.setWidget( self.widgetCentral ) ### # Signaux provenants de l'interface ### QtCore.QObject.connect( self.pushButtonSelectionDossier, QtCore.SIGNAL( "clicked()" ), self.afficherSelecteurDossier ) QtCore.QObject.connect( self.buttonBox, QtCore.SIGNAL( "accepted()" ), self.enregistrerPreferences ) QtCore.QObject.connect( self.buttonBox, QtCore.SIGNAL( "rejected()" ), self.reject )
class CmdInterpreter(Cmd): # We use this variable at Breakpoint #1. # We use this in order to allow Jarvis say "Hi", only at the first # interaction. # This can be used to store user specific data def __init__(self, first_reaction_text, prompt, directories=[], first_reaction=True, enable_voice=False): """ This constructor contains a dictionary with Jarvis Actions (what Jarvis can do). In alphabetically order. """ Cmd.__init__(self) self.first_reaction = first_reaction self.first_reaction_text = first_reaction_text self.prompt = prompt self.enable_voice = enable_voice # Register do_quit() function to SIGINT signal (Ctrl-C) signal.signal(signal.SIGINT, self.interrupt_handler) self.memory = Memory() self.scheduler = schedule.Scheduler() self.speech = create_voice() self.actions = [ { "check": ("ram", "weather", "time", "forecast") }, "directions", "help", "how_are_you", "near", "pinpoint", "umbrella", { "update": ("location", "system") }, "weather", ] self.fixed_responses = { "what time is it": "clock", "where am i": "pinpoint", "how are you": "how_are_you" } self._api = JarvisAPI(self) self._plugin_manager = PluginManager() for directory in directories: self._plugin_manager.add_directory(directory) self._activate_plugins() def _activate_plugins(self): """Generate do_XXX, help_XXX and (optionally) complete_XXX functions""" for (plugin_name, plugin) in self._plugin_manager.get_all().items(): completions = self._plugin_update_action(plugin, plugin_name) if completions is not None: def complete(completions): def _complete_impl(self, text, line, begidx, endidx): return [i for i in completions if i.startswith(text)] return _complete_impl setattr(CmdInterpreter, "complete_" + plugin_name, complete(completions)) setattr(CmdInterpreter, "do_" + plugin_name, partial(plugin.run, self._api)) setattr(CmdInterpreter, "help_" + plugin_name, partial(self._api.say, plugin.get_doc())) if hasattr(plugin.__class__, "init") and callable( getattr(plugin.__class__, "init")): plugin.init(self._api) def _plugin_update_action(self, plugin, plugin_name): """Return True if completion is available""" complete = plugin.complete() if complete is not None: # add plugin with completion # Dictionary: # { plugin_name : list of completions } complete = [x for x in complete] self.actions.append({plugin_name: complete}) return complete else: # add plugin without completion # plugin name only self.actions.append(plugin_name) return None def close(self): """Closing Jarvis.""" print_say("Goodbye, see you later!", self, Fore.RED) self.scheduler.stop_all() exit() def completedefault(self, text, line, begidx, endidx): """Default completion""" return [i for i in self.actions if i.startswith(text)] def error(self): """Jarvis let you know if an error has occurred.""" print_say("I could not identify your command...", self, Fore.RED) def get_completions(self, command, text): """Returns a list with the completions of a command.""" dict_target = [ item for item in self.actions if type(item) == dict and command in item ][0] completions_list = dict_target[command] return [i for i in completions_list if i.startswith(text) and i != ''] def interrupt_handler(self, signal, frame): """Closes Jarvis on SIGINT signal. (Ctrl-C)""" self.close() def do_calculate(self, s): """Jarvis will get your calculations done!""" tempt = s.replace(" ", "") if len(tempt) > 1: evaluator.calc(tempt, self) else: print_say("Error: Not in correct format", self, Fore.RED) def help_calculate(self): """Print help about calculate command.""" print_say("Jarvis will get your calculations done!", self) print_say("-- Example:", self) print_say("\tcalculate 3 + 5", self) def do_check(self, s): """Checks your system's RAM stats.""" # if s == "ram": if "ram" in s: system("free -lm") # if s == "time" elif "time" in s: timeIn.main(self, s) elif "forecast" in s: forecast.main(self, s) # if s == "weather" elif "weather" in s: try: weatherIn.main(self, s) except ConnectionError: print(CONNECTION_ERROR_MSG) def help_check(self): """Prints check command help.""" print_say("ram: checks your system's RAM stats.", self) print_say("time: checks the current time in any part of the globe.", self) print_say( "weather in *: checks the current weather in any part of the globe.", self) print_say("forecast: checks the weather forecast for the next 7 days.", self) print_say("-- Examples:", self) print_say("\tcheck ram", self) print_say("\tcheck time in Manchester (UK)", self) print_say("\tcheck weather in Canada", self) print_say("\tcheck forecast", self) print_say("\tcheck forecast in Madrid", self) # add here more prints def complete_check(self, text, line, begidx, endidx): """Completions for check command""" return self.get_completions("check", text) def do_directions(self, data): """Get directions about a destination you are interested to.""" try: directions_to.main(data) except ValueError: print("Please enter destination") except ConnectionError: print(CONNECTION_ERROR_MSG) def help_directions(self): """Prints help about directions command""" print_say("Get directions about a destination you are interested to.", self) print_say("-- Example:", self) print_say("\tdirections to the Eiffel Tower", self) def do_how_are_you(self, s): """Jarvis will inform you about his status.""" print_say("I am fine, How about you?", self, Fore.BLUE) def help_how_are_you(self): """Print info about how_are_you command""" print_say("Jarvis will inform you about his status.", self) def do_near(self, data): """Jarvis can find what is near you!""" near_me.main(data) def help_near(self): """Print help about near command.""" print_say("Jarvis can find what is near you!", self) print_say("-- Examples:", self) print_say("\trestaurants near me", self) print_say("\tmuseums near the eiffel tower", self) def do_pinpoint(self, s): """Jarvis will pinpoint your location.""" try: mapps.locate_me() except ConnectionError: print(CONNECTION_ERROR_MSG) def help_pinpoint(self): """Print help about pinpoint command.""" print_say("Jarvis will pinpoint your location.", self) def do_umbrella(self, s): """If you're leaving your place, Jarvis will inform you if you might need an umbrella or not""" s = 'umbrella' try: weather_pinpoint.main(self.memory, self, s) except ConnectionError: print(CONNECTION_ERROR_MSG) def help_umbrella(self): """Print info about umbrella command.""" print_say( "If you're leaving your place, Jarvis will inform you if you might need an umbrella or not.", self, Fore.BLUE) def do_update(self, s): """Updates location or system.""" if "location" in s: location = self.memory.get_data('city') loc_str = str(location) print_say("Your current location is set to " + loc_str, self) print_say("What is your new location?", self) i = input() self.memory.update_data('city', i) self.memory.save() elif "system" in s: update_system() def help_update(self): """Prints help about update command""" print_say("location: Updates location.", self) print_say("system: Updates system.", self) def complete_update(self, text, line, begidx, endidx): """Completions for update command""" return self.get_completions("update", text) def do_weather(self, s): """Get information about today's weather.""" try: word = s.strip() if (len(word) > 1): weatherIn.main(self, s) else: weather_pinpoint.main(self.memory, self, s) except ConnectionError: print(CONNECTION_ERROR_MSG) def help_weather(self): """Prints help about weather command.""" print_say( "Get information about today's weather in your current location.", self)
def __init__(self, parent, signaux): # Appel au constructeur de la classe mere QtGui.QDialog.__init__(self, parent) self.preferences = Preferences() self.pluginManager = PluginManager() self.signaux = signaux ########### # Fenetre # ########### ### # Reglages de la fenetre principale ### # Nom de la fenetre self.setWindowTitle(u"Préférences") # Dimensions la fenetre self.resize(280, 340) # Mise en place de son icone self.setWindowIcon(QtGui.QIcon("ico/gtk-preferences.svg")) ### # Mise en place des widgets dans la fenetre ### # Layout de grille principal self.gridLayout = QtGui.QGridLayout(self) # Font pour les titres fontTitres = QtGui.QFont() fontTitres.setPointSize(11) fontTitres.setWeight(75) fontTitres.setBold(True) # # Choix du repertoire telechargement # # Label self.labelRepertoire = QtGui.QLabel(self) self.labelRepertoire.setFont(fontTitres) self.labelRepertoire.setText(u"Répertoire de téléchargement :") # Repertoire de telechargement self.lineEditRepertoireTelechargement = QtGui.QLineEdit(self) # Bouton pour ouvrir la fenetre de selection de repertoire self.pushButtonSelectionDossier = QtGui.QPushButton(self) self.pushButtonSelectionDossier.setIcon( QtGui.QIcon("ico/gtk-folder.svg")) # # Choix du plugin par defaut # # Label self.labelPluginDefaut = QtGui.QLabel(self) self.labelPluginDefaut.setFont(fontTitres) self.labelPluginDefaut.setText(u"Plugin par défaut :") # Liste de choix du plugin par defaut self.comboBoxPluginDefaut = QtGui.QComboBox(self) # # Choix des plugins a activer # # Label self.labelPlugins = QtGui.QLabel(self) self.labelPlugins.setFont(fontTitres) self.labelPlugins.setText("Plugins actifs :") # Liste des plugins self.listWidgetPlugin = QtGui.QListWidget(self) # # Choix des parametres Internet # # Label self.labelInternet = QtGui.QLabel(self) self.labelInternet.setFont(fontTitres) self.labelInternet.setText(u"Paramètres Internet :") # Layout formulaire self.layoutInternet = QtGui.QFormLayout() # SpinBox pour choisir le timeOut self.spinBoxTimeOut = QtGui.QSpinBox() self.spinBoxTimeOut.setMinimum(1) self.spinBoxTimeOut.setMaximum(60) self.layoutInternet.addRow(u"Time out (en s) :", self.spinBoxTimeOut) # SpinBox pour choisir le nombre de threads max self.spinBoxNbThread = QtGui.QSpinBox() self.spinBoxNbThread.setMinimum(1) self.spinBoxNbThread.setMaximum(100) self.layoutInternet.addRow(u"Nombre de threads max :", self.spinBoxNbThread) # Bouton pour enregistrer/annuler les preferences self.buttonBox = QtGui.QDialogButtonBox(self) self.buttonBox.addButton("Enregistrer", QtGui.QDialogButtonBox.AcceptRole) self.buttonBox.addButton("Fermer", QtGui.QDialogButtonBox.RejectRole) # On ajoute le tout au layout self.gridLayout.addWidget(self.labelRepertoire, 0, 0, 1, 2) self.gridLayout.addWidget(self.lineEditRepertoireTelechargement, 1, 0, 1, 1) self.gridLayout.addWidget(self.pushButtonSelectionDossier, 1, 1, 1, 1) self.gridLayout.addWidget(self.labelPluginDefaut, 2, 0, 1, 2) self.gridLayout.addWidget(self.comboBoxPluginDefaut, 3, 0, 1, 2) self.gridLayout.addWidget(self.labelPlugins, 4, 0, 1, 2) self.gridLayout.addWidget(self.listWidgetPlugin, 5, 0, 1, 2) self.gridLayout.addWidget(self.labelInternet, 6, 0, 1, 2) self.gridLayout.addLayout(self.layoutInternet, 7, 0, 1, 2) self.gridLayout.addWidget(self.buttonBox, 8, 0, 1, 2) ### # Signaux provenants de l'interface ### QtCore.QObject.connect(self.pushButtonSelectionDossier, QtCore.SIGNAL("clicked()"), self.afficherSelecteurDossier) QtCore.QObject.connect(self.buttonBox, QtCore.SIGNAL("accepted()"), self.enregistrerPreferences) QtCore.QObject.connect(self.buttonBox, QtCore.SIGNAL("rejected()"), self.reject)
class TestHttpPlugin(TestCase): def setUp(self): HoneypotBase.read_config() self.thread = PluginManager(Plugin(), HoneypotBase.Session) self.thread.start() time.sleep(.1) def tearDown(self): self.thread.stop() def test_insert_valid_record_1(self): record = Plugin.Http(ip_address='41.161.65.153', command='GET', path='/', version=1.0, headers=None, time=None, feature= Plugin().get_feature('41.161.65.153')) self.assertTrue(Plugin.insert_record(Plugin(), record, HoneypotBase.Session())) def test_insert_record_where_address_is_null(self): record = Plugin.Http(ip_address=None, command='GET', path='/index.htm', version=1.1, headers=None, time=None, feature=None) self.assertFalse(Plugin.insert_record(Plugin(), record, HoneypotBase.Session())) def test_insert_record_where_feature_is_unknown(self): record = Plugin.Http(ip_address='localhost', command='POST', path='/index.htm', version=6, headers=None, time=None, feature=Plugin().get_feature('localhost')) self.assertTrue(Plugin.insert_record(Plugin(), record, HoneypotBase.Session())) def test_insert_valid_record_3(self): record = Plugin.Http(ip_address='181.161.28.209', command='POST', path='/', version=6, headers=None, time=None, feature='181.161.28.209') self.assertTrue(Plugin.insert_record(Plugin(), record, HoneypotBase.Session())) def test_insert_record_where_path_is_none(self): record = Plugin.Http(ip_address='177.82.42.192', command='POST', path=None, version=6, headers=None, time=None, feature=Plugin().get_feature('177.82.42.192')) self.assertTrue(Plugin.insert_record(Plugin(), record, HoneypotBase.Session())) def test_insert_record_where_command_is_none(self): record = Plugin.Http(ip_address='177.82.42.192', command=None, path=None, version=6, headers=None, time=None, feature=Plugin().get_feature('177.82.42.192')) self.assertTrue(Plugin.insert_record(Plugin(), record, HoneypotBase.Session())) def test_insert_record_where_command_isnt_supported(self): record = Plugin.Http(ip_address='177.82.42.192', command='get', path=None, version=6, headers=None, time=None, feature=Plugin().get_feature('177.82.42.192')) self.assertTrue(Plugin.insert_record(Plugin(), record, HoneypotBase.Session())) def test_response_unsupported_method(self): conn = HTTPConnection('localhost', 80, True) conn.request(None, "/") res = conn.getresponse() res.read() conn.close() self.assertEqual(res.status, 501) def test_response(self): conn = HTTPConnection('localhost', 80, True) conn.request("GET", None) res = conn.getresponse() res.read() conn.close() self.assertEqual(res.status, 400) def test_response1(self): conn = HTTPConnection('localhost', 80, True) conn.request("GET", "") res = conn.getresponse() res.read() conn.close() self.assertEqual(res.status, 400) def test_response_1(self): conn = HTTPConnection('localhost', 80, True) conn.request("DELETE", None) res = conn.getresponse() res.read() conn.close() self.assertEqual(res.status, 400) def test_response_2(self): conn = HTTPConnection('localhost', 80, True) conn.request("POST", None) res = conn.getresponse() res.read() conn.close() self.assertEqual(res.status, 400) def test_response_valid_request(self): conn = HTTPConnection('localhost', 80, True) conn.request("GET", "/") res = conn.getresponse() res.read() conn.close() self.assertEqual(res.status, 400) def test_response_bad_status_line(self): conn = HTTPConnection('localhost', 80, True) conn.request("get", "/") res = conn.getresponse() res.read() conn.close() self.assertEqual(res.status, 501)