def register(self, cancel=False, **data): """ This register form send an e-mail to the user and to the site admin. """ template_specification = dict(mainContent="register", title="Register", data=data) redirect = False if cherrypy.request.method == 'POST': if cancel: raise cherrypy.HTTPRedirect('/user') try: okmessage = self._create_user(**data) common.set_info_message(okmessage) redirect = True except formencode.Invalid as excep: template_specification[common.KEY_ERRORS] = excep.unpack_errors() redirect = False except Exception as excep1: self.logger.error("Could not create user:"******"username"]) self.logger.exception(excep1) common.set_error_message("We are very sorry, but we could not create your user. Most probably is " "because it was impossible to sent emails. Please try again later...") redirect = False if redirect: #Redirect to login page, with some success message to display raise cherrypy.HTTPRedirect('/user') else: #Stay on the same page return self.fill_default_attributes(template_specification)
def settings(self, save_settings=False, **data): """Main settings page submit and get""" template_specification = dict(mainContent="settings/system_settings", title="System Settings") if save_settings: try: form = SettingsForm() data = form.to_python(data) isrestart, isreset = self.settingsservice.save_settings(**data) if isrestart: thread = threading.Thread(target=self._restart_services, kwargs={'should_reset': isreset}) thread.start() common.add2session(common.KEY_IS_RESTART, True) common.set_important_message('Please wait until TVB is restarted properly!') raise cherrypy.HTTPRedirect('/tvb') # Here we will leave the same settings page to be displayed. # It will continue reloading when CherryPy restarts. except formencode.Invalid as excep: template_specification[common.KEY_ERRORS] = excep.unpack_errors() except InvalidSettingsException as excep: self.logger.error('Invalid settings! Exception %s was raised' % (str(excep))) common.set_error_message(excep.message) template_specification.update({'keys_order': self.settingsservice.KEYS_DISPLAY_ORDER, 'config_data': self.settingsservice.configurable_keys, common.KEY_FIRST_RUN: TvbProfile.is_first_run()}) return self.fill_default_attributes(template_specification)
def index(self): current_user_id = self.simulator_context.logged_user.id # In case the number of dynamics gets big we should add a filter in the ui. dynamics = dao.get_dynamics_for_user(current_user_id) if not dynamics: return self.no_dynamics_page() sim_config = self.simulator_context.simulator connectivity = sim_config.connectivity if connectivity is None: msg = 'You have to select a connectivity before setting up the region Model. ' common.set_error_message(msg) raise ValueError(msg) current_project = common.get_current_project() conn_idx = load.load_entity_by_gid(connectivity) params = ConnectivityViewer.get_connectivity_parameters(conn_idx, current_project.name, str(conn_idx.fk_from_operation)) burst_config = self.simulator_context.burst_config params.update({ 'title': 'Model parameters', 'mainContent': 'burst/model_param_region', 'isSingleMode': True, 'submit_parameters_url': '/burst/modelparameters/regions/submit_model_parameters', 'dynamics': dynamics, 'dynamics_json': self._dynamics_json(dynamics), 'initial_dynamic_ids': burst_config.dynamic_ids }) return self.fill_default_attributes(params, 'regionmodel')
def execute_post(self, project_id, submit_url, step_key, algorithm, **data): """ Execute HTTP POST on a generic step.""" errors = None adapter_instance = ABCAdapter.build_adapter(algorithm) try: result = self.flow_service.fire_operation(adapter_instance, common.get_logged_user(), project_id, **data) # Store input data in session, for informing user of it. step = self.flow_service.get_category_by_id(step_key) if not step.rawinput: self.context.add_adapter_to_session(None, None, copy.deepcopy(data)) if isinstance(adapter_instance, ABCDisplayer): if isinstance(result, dict): result[common.KEY_OPERATION_ID] = adapter_instance.operation_id return result else: common.set_error_message("Invalid result returned from Displayer! Dictionary is expected!") else: if isinstance(result, list): result = "Launched %s operations." % len(result) common.set_important_message(str(result)) except formencode.Invalid, excep: errors = excep.unpack_errors()
def create_new(self, cancel=False, **data): """ Create new user with data submitted from UI. """ if cancel: raise cherrypy.HTTPRedirect('/user/usermanagement') template_specification = dict(mainContent="create_new", title="Create New", data=data) redirect = False if cherrypy.request.method == 'POST': try: data[KEY_COMMENT] = "Created by administrator." # User is created by administrator, should be validated automatically, and credentials # should be sent to user by email. email_msg = """A TVB account was just created for you by an administrator. \n Your credentials are username=%s, password=%s. \n You can log in here: %s. """ % (data[KEY_USERNAME], data[KEY_PASSWORD], TvbProfile.current.web.BASE_URL) self._create_user(email_msg=email_msg, validated=True, **data) common.set_info_message("New user created successfully.") redirect = True except formencode.Invalid as excep: template_specification[common.KEY_ERRORS] = excep.unpack_errors() except Exception as excep: self.logger.exception(excep) common.set_error_message("We are very sorry, but we could not create your user. Most probably is " "because it was impossible to sent emails. Please try again later...") if redirect: raise cherrypy.HTTPRedirect('/user/usermanagement') else: return self.fill_default_attributes(template_specification)
def register(self, cancel=False, **data): """ This register form send an e-mail to the user and to the site admin. """ template_specification = dict(mainContent="user/register", title="Register", data=data) redirect = False if cherrypy.request.method == 'POST': if cancel: raise cherrypy.HTTPRedirect('/user') try: okmessage = self._create_user(**data) common.set_info_message(okmessage) redirect = True except formencode.Invalid as excep: template_specification[ common.KEY_ERRORS] = excep.unpack_errors() redirect = False except Exception as excep1: self.logger.error("Could not create user:"******"username"]) self.logger.exception(excep1) common.set_error_message( "We are very sorry, but we could not create your user. Most probably is " "because it was impossible to sent emails. Please try again later..." ) redirect = False if redirect: # Redirect to login page, with some success message to display raise cherrypy.HTTPRedirect('/user') else: # Stay on the same page return self.fill_default_attributes(template_specification)
def profile(self, logout=False, save=False, **data): """ Display current user's profile page. On POST: logout, or save password/email. """ if cherrypy.request.method == "POST" and logout: raise cherrypy.HTTPRedirect("/user/logout") template_specification = dict(mainContent="profile", title="User Profile") user = common.get_logged_user() if cherrypy.request.method == "POST" and save: try: form = EditUserForm() data = form.to_python(data) if data.get(KEY_PASSWORD): user.password = md5(data[KEY_PASSWORD]).hexdigest() if data.get(KEY_EMAIL): user.email = data[KEY_EMAIL] old_password = None if data.get("old_password"): old_password = md5(data["old_password"]).hexdigest() self.user_service.edit_user(user, old_password) if old_password: common.set_info_message("Changes Submitted!") else: common.set_info_message("Submitted! No password changed.") except formencode.Invalid, excep: template_specification[common.KEY_ERRORS] = excep.unpack_errors() except UsernameException, excep: self.logger.exception(excep) user = common.get_logged_user() common.add2session(common.KEY_USER, self.user_service.get_user_by_id(user.id)) common.set_error_message("Could not save changes. Probably wrong old password!!")
def recoverpassword(self, cancel=False, **data): """ This form should reset a password for a given userName/email and send a notification message to that email. """ template_specification = dict(mainContent="user/recover_password", title="Recover password", data=data) redirect = False if cherrypy.request.method == 'POST': if cancel: raise cherrypy.HTTPRedirect('/user') form = RecoveryForm() try: data = form.to_python(data) okmessage = self.user_service.reset_password(**data) common.set_info_message(okmessage) redirect = True except formencode.Invalid as excep: template_specification[ common.KEY_ERRORS] = excep.unpack_errors() redirect = False except UsernameException as excep1: self.logger.exception("Could not reset password!") common.set_error_message(excep1.message) redirect = False if redirect: # Redirect to login page, with some success message to display raise cherrypy.HTTPRedirect('/user') else: # Stay on the same page return self.fill_default_attributes(template_specification)
def settings(self, save_settings=False, **data): """Main settings page submit and get""" template_specification = dict( mainContent="../settings/system_settings", title="System Settings") if save_settings: try: form = SettingsForm() data = form.to_python(data) isrestart, isreset = self.settingsservice.save_settings(**data) if isrestart: thread = threading.Thread(target=self._restart_services, kwargs={'should_reset': isreset}) thread.start() common.add2session(common.KEY_IS_RESTART, True) common.set_important_message( 'Please wait until TVB is restarted properly!') raise cherrypy.HTTPRedirect('/tvb') # Here we will leave the same settings page to be displayed. # It will continue reloading when CherryPy restarts. except formencode.Invalid, excep: template_specification[ common.KEY_ERRORS] = excep.unpack_errors() except InvalidSettingsException, excep: self.logger.error( 'Invalid settings! Exception %s was raised' % (str(excep))) common.set_error_message(excep.message)
def load_burst_from_json(self, **data): """Upload Burst from previously exported JSON file""" self.logger.debug("Uploading ..." + str(data)) try: upload_param = "uploadedfile" if upload_param in data and data[upload_param]: upload_param = data[upload_param] if isinstance(upload_param, FieldStorage) or isinstance( upload_param, Part): if not upload_param.file: raise BurstServiceException( "Please select a valid JSON file.") upload_param = upload_param.file.read() upload_param = json.loads(upload_param) prj_id = common.get_current_project().id importer = ImportService() burst_entity = importer.load_burst_entity(upload_param, prj_id) common.add2session(common.KEY_BURST_CONFIG, burst_entity) except Exception as excep: self.logger.warning(excep.message) common.set_error_message(excep.message) raise cherrypy.HTTPRedirect('/burst/')
def step_1(self): """ Used for generating the interface which allows the user to define a stimulus. """ current_surface_stim = common.get_from_session(KEY_SURFACE_STIMULI) project_id = common.get_current_project().id surface_stim_selector_form = StimulusSurfaceSelectorForm(project_id) surface_stim_selector_form.surface_stimulus.data = current_surface_stim.gid.hex surface_stim_creator_form = SurfaceStimulusCreatorForm(self.possible_spatial_equations, self.possible_temporal_equations, project_id) if not hasattr(current_surface_stim, 'surface') or not current_surface_stim.surface: default_surface_index = try_get_last_datatype(project_id, SurfaceIndex, SurfaceStimulusCreatorForm.get_filters()) if default_surface_index is None: common.set_error_message(self.MSG_MISSING_SURFACE) current_surface_stim.surface = uuid.uuid4() else: current_surface_stim.surface = uuid.UUID(default_surface_index.gid) surface_stim_creator_form.fill_from_trait(current_surface_stim) surface_stim_selector_form.display_name.data = common.get_from_session(KEY_SURFACE_STIMULI_NAME) template_specification = dict(title="Spatio temporal - Surface stimulus") template_specification['surfaceStimulusSelectForm'] = self.render_spatial_form(surface_stim_selector_form) template_specification['surfaceStimulusCreateForm'] = self.render_spatial_form(surface_stim_creator_form) self.plotted_equation_prefixes = { self.SURFACE_FIELD: surface_stim_creator_form.surface.name, self.DISPLAY_NAME_FIELD: surface_stim_selector_form.display_name.name } template_specification['mainContent'] = 'spatial/stimulus_surface_step1_main' template_specification['baseUrl'] = self.base_url template_specification['spatialFieldsPrefixes'] = json.dumps(self.plotted_equation_prefixes) template_specification['next_step_url'] = '/spatial/stimulus/surface/step_1_submit' template_specification['definedFocalPoints'] = current_surface_stim.focal_points_triangles.tolist() template_specification = self._add_extra_fields_to_interface(template_specification) return self.fill_default_attributes(template_specification)
def index(self, **data): """ Login page (with or without messages). """ template_specification = dict(mainContent="user/login", title="Login", data=data) if cherrypy.request.method == 'POST': form = LoginForm() try: data = form.to_python(data) username = data[KEY_USERNAME] password = data[KEY_PASSWORD] user = self.user_service.check_login(username, password) if user is not None: common.add2session(common.KEY_USER, user) common.set_info_message('Welcome ' + username) self.logger.debug("User " + username + " has just logged in!") if user.selected_project is not None: prj = user.selected_project prj = ProjectService().find_project(prj) self._mark_selected(prj) raise cherrypy.HTTPRedirect('/user/profile') else: common.set_error_message( 'Wrong username/password, or user not yet validated...' ) self.logger.debug("Wrong username " + username + " !!!") except formencode.Invalid as excep: template_specification[ common.KEY_ERRORS] = excep.unpack_errors() return self.fill_default_attributes(template_specification)
def index(self): current_user_id = common.get_logged_user().id # In case the number of dynamics gets big we should add a filter in the ui. dynamics = dao.get_dynamics_for_user(current_user_id) if not dynamics: return self.no_dynamics_page() burst_config = common.get_from_session(common.KEY_BURST_CONFIG) des = SerializationManager(burst_config) connectivity = des.get_connectivity() if connectivity is None: msg = 'You have to select a connectivity before setting up the region Model. ' common.set_error_message(msg) raise ValueError(msg) params = ConnectivityViewer.get_connectivity_parameters(connectivity) params.update({ 'title': 'Model parameters', 'mainContent': 'burst/model_param_region', 'isSingleMode': True, 'submit_parameters_url': '/burst/modelparameters/regions/submit_model_parameters', 'dynamics': dynamics, 'dynamics_json': self._dynamics_json(dynamics), 'initial_dynamic_ids': json.dumps(burst_config.dynamic_ids) }) return self.fill_default_attributes(params, 'regionmodel')
def create_new(self, cancel=False, **data): """ Create new user with data submitted from UI. """ if cancel: raise cherrypy.HTTPRedirect('/user/usermanagement') template_specification = dict(mainContent="create_new", title="Create New", data=data) redirect = False if cherrypy.request.method == 'POST': try: data[KEY_COMMENT] = "Created by administrator." # User is created by administrator, should be validated automatically, and credentials # should be sent to user by email. email_msg = """A TVB account was just created for you by an administrator. Your credentials are username=%s, password=%s.""" % ( data[KEY_USERNAME], data[KEY_PASSWORD]) self._create_user(email_msg=email_msg, validated=True, **data) common.set_info_message("New user created successfully.") redirect = True except formencode.Invalid, excep: template_specification[ common.KEY_ERRORS] = excep.unpack_errors() except Exception, excep: self.logger.exception(excep) common.set_error_message( "We are very sorry, but we could not create your user. Most probably is " "because it was impossible to sent emails. Please try again later..." )
def deco(*a, **b): try: return func(*a, **b) except common.NotAllowed as ex: log = get_logger(_LOGGER_NAME) log.error(str(ex)) if redirect: common.set_error_message(str(ex)) raise cherrypy.HTTPRedirect(ex.redirect_url) else: raise cherrypy.HTTPError(ex.status, str(ex)) except cherrypy.HTTPRedirect as ex: if redirect: raise else: log = get_logger(_LOGGER_NAME) log.warn('Redirect converted to error: ' + str(ex)) # should we do this? Are browsers following redirects in ajax? raise cherrypy.HTTPError(500, str(ex)) except Exception: log = get_logger(_LOGGER_NAME) log.exception('An unexpected exception appeared') if redirect: # set a default error message if one has not been set already if not common.has_error_message(): common.set_error_message("An unexpected exception appeared. Please check the log files.") raise cherrypy.HTTPRedirect("/tvb?error=True") else: raise
def create_stimulus(self): """ Creates a stimulus from the given data. """ try: current_surface_stim = common.get_from_session(KEY_SURFACE_STIMULI) surface_stimulus_creator = ABCAdapter.build_adapter_from_class( SurfaceStimulusCreator) self.operation_service.fire_operation( surface_stimulus_creator, common.get_logged_user(), common.get_current_project().id, view_model=current_surface_stim) common.set_important_message( "The operation for creating the stimulus was successfully launched." ) except (NameError, ValueError, SyntaxError): common.set_error_message( "The operation failed due to invalid parameter input.") return False except Exception as ex: common.set_error_message(ex) return False return True
def settings(self, save_settings=False, **data): """Main settings page submit and get""" template_specification = dict(mainContent="../settings/system_settings", title="System Settings") if save_settings: try: form = SettingsForm() data = form.to_python(data) isrestart, isreset = self.settingsservice.save_settings(**data) if isrestart: thread = threading.Thread(target=self._restart_services, kwargs={'should_reset': isreset}) thread.start() common.add2session(common.KEY_IS_RESTART, True) common.set_important_message('Please wait until TVB is restarted properly!') raise cherrypy.HTTPRedirect('/tvb') # Here we will leave the same settings page to be displayed. # It will continue reloading when CherryPy restarts. except formencode.Invalid as excep: template_specification[common.KEY_ERRORS] = excep.unpack_errors() except InvalidSettingsException as excep: self.logger.error('Invalid settings! Exception %s was raised' % (str(excep))) common.set_error_message(excep.message) template_specification.update({'keys_order': self.settingsservice.KEYS_DISPLAY_ORDER, 'config_data': self.settingsservice.configurable_keys, common.KEY_FIRST_RUN: TvbProfile.is_first_run()}) return self.fill_default_attributes(template_specification)
def index(self): current_user_id = common.get_logged_user().id # In case the number of dynamics gets big we should add a filter in the ui. dynamics = dao.get_dynamics_for_user(current_user_id) if not dynamics: return self.no_dynamics_page() sim_config = common.get_from_session(common.KEY_SIMULATOR_CONFIG) connectivity = sim_config.connectivity if connectivity is None: msg = 'You have to select a connectivity before setting up the region Model. ' common.set_error_message(msg) raise ValueError(msg) current_project = common.get_current_project() file_handler = FilesHelper() conn_idx = dao.get_datatype_by_gid(connectivity.hex) conn_path = file_handler.get_project_folder(current_project, str(conn_idx.fk_from_operation)) params = ConnectivityViewer.get_connectivity_parameters(conn_idx, conn_path) burst_config = common.get_from_session(common.KEY_BURST_CONFIG) params.update({ 'title': 'Model parameters', 'mainContent': 'burst/model_param_region', 'isSingleMode': True, 'submit_parameters_url': '/burst/modelparameters/regions/submit_model_parameters', 'dynamics': dynamics, 'dynamics_json': self._dynamics_json(dynamics), 'initial_dynamic_ids': burst_config.dynamic_ids }) return self.fill_default_attributes(params, 'regionmodel')
def load_burst_from_json(self, **data): """Upload Burst from previously exported JSON file""" self.logger.debug("Uploading ..." + str(data)) try: upload_param = "uploadedfile" if upload_param in data and data[upload_param]: upload_param = data[upload_param] if isinstance(upload_param, FieldStorage) or isinstance(upload_param, Part): if not upload_param.file: raise BurstServiceException("Please select a valid JSON file.") upload_param = upload_param.file.read() upload_param = json.loads(upload_param) prj_id = common.get_current_project().id importer = ImportService() burst_entity = importer.load_burst_entity(upload_param, prj_id) common.add2session(common.KEY_BURST_CONFIG, burst_entity) except Exception as excep: self.logger.warning(excep.message) common.set_error_message(excep.message) raise cherrypy.HTTPRedirect('/burst/')
def viewall(self, create=False, page=1, selected_project_id=None, **_): """ Display all existent projects. Choose one project to work with. """ page = int(page) if cherrypy.request.method == 'POST' and create: raise cherrypy.HTTPRedirect('/project/editone') current_user_id = common.get_logged_user().id ## Select project if user choose one. if selected_project_id is not None: try: selected_project = self.project_service.find_project( selected_project_id) self._mark_selected(selected_project) except ProjectServiceException as excep: self.logger.error(excep) self.logger.warning("Could not select project: " + str(selected_project_id)) common.set_error_message("Could not select project: " + str(selected_project_id)) # Prepare template response prjs, pages_no = self.project_service.retrieve_projects_for_user( current_user_id, page) template_specification = dict(mainContent="project/viewall", title="Available TVB Projects", projectsList=prjs, page_number=page, total_pages=pages_no) return self.fill_default_attributes(template_specification, 'list')
def step_2(self): """ Generate the required template dictionary for the second step. """ current_region_stimulus = common.get_from_session(KEY_REGION_STIMULUS) region_stim_selector_form = StimulusRegionSelectorForm(common.get_current_project().id) region_stim_selector_form.region_stimulus.data = current_region_stimulus.gid.hex region_stim_selector_form.display_name.data = common.get_from_session(KEY_REGION_STIMULUS_NAME) template_specification = dict(title="Spatio temporal - Region stimulus") template_specification['mainContent'] = 'spatial/stimulus_region_step2_main' template_specification['next_step_url'] = '/spatial/stimulus/region/step_2_submit' template_specification['regionStimSelectorForm'] = self.render_adapter_form(region_stim_selector_form) default_weights = current_region_stimulus.weight if len(default_weights) == 0: selected_connectivity = ABCAdapter.load_entity_by_gid(current_region_stimulus.connectivity.hex) if selected_connectivity is None: common.set_error_message(self.MSG_MISSING_CONNECTIVITY) default_weights = numpy.array([]) else: default_weights = StimuliRegion.get_default_weights(selected_connectivity.number_of_regions) template_specification['baseUrl'] = self.base_url self.plotted_equation_prefixes = { self.DISPLAY_NAME_FIELD: region_stim_selector_form.display_name.name } template_specification['fieldsWithEvents'] = json.dumps(self.plotted_equation_prefixes) template_specification['node_weights'] = json.dumps(default_weights.tolist()) template_specification[common.KEY_PARAMETERS_CONFIG] = False template_specification.update(self.display_connectivity(current_region_stimulus.connectivity.hex)) return self.fill_default_attributes(template_specification)
def index(self, **data): """ Login page (with or without messages). """ template_specification = dict(mainContent="login", title="Login", data=data) if cherrypy.request.method == 'POST': form = LoginForm() try: data = form.to_python(data) username = data[KEY_USERNAME] password = data[KEY_PASSWORD] user = self.user_service.check_login(username, password) if user is not None: common.add2session(common.KEY_USER, user) common.set_info_message('Welcome ' + username) self.logger.debug("User " + username + " has just logged in!") if user.selected_project is not None: prj = user.selected_project prj = ProjectService().find_project(prj) self._mark_selected(prj) raise cherrypy.HTTPRedirect('/user/profile') else: common.set_error_message('Wrong username/password, or user not yet validated...') self.logger.debug("Wrong username " + username + " !!!") except formencode.Invalid as excep: template_specification[common.KEY_ERRORS] = excep.unpack_errors() return self.fill_default_attributes(template_specification)
def recoverpassword(self, cancel=False, **data): """ This form should reset a password for a given userName/email and send a notification message to that email. """ template_specification = dict(mainContent="recover_password", title="Recover password", data=data) redirect = False if cherrypy.request.method == 'POST': if cancel: raise cherrypy.HTTPRedirect('/user') form = RecoveryForm() try: data = form.to_python(data) okmessage = self.user_service.reset_password(**data) common.set_info_message(okmessage) redirect = True except formencode.Invalid as excep: template_specification[common.KEY_ERRORS] = excep.unpack_errors() redirect = False except UsernameException as excep1: self.logger.exception("Could not reset password!") common.set_error_message(excep1.message) redirect = False if redirect: #Redirect to login page, with some success message to display raise cherrypy.HTTPRedirect('/user') else: #Stay on the same page return self.fill_default_attributes(template_specification)
def get_data_from_burst_configuration(self): """ Returns the model and surface instances from the burst configuration. """ des = SerializationManager( common.get_from_session(common.KEY_BURST_CONFIG)) ### Read from session current burst-configuration if des.conf is None: return None, None if des.has_model_pse_ranges(): common.set_error_message( "When configuring model parameters you are not allowed to specify range values." ) raise cherrypy.HTTPRedirect("/burst/") try: model, integrator = des.make_model_and_integrator() except Exception: self.logger.exception( "Some of the provided parameters have an invalid value.") common.set_error_message( "Some of the provided parameters have an invalid value.") raise cherrypy.HTTPRedirect("/burst/") surface = des.get_surface() return model, surface
def execute_post(self, project_id, submit_url, step_key, algorithm, **data): """ Execute HTTP POST on a generic step.""" errors = None adapter_instance = ABCAdapter.build_adapter(algorithm) try: result = self.flow_service.fire_operation(adapter_instance, common.get_logged_user(), project_id, **data) # Store input data in session, for informing user of it. step = self.flow_service.get_category_by_id(step_key) if not step.rawinput: self.context.add_adapter_to_session(None, None, copy.deepcopy(data)) if isinstance(adapter_instance, ABCDisplayer): if isinstance(result, dict): result[common. KEY_OPERATION_ID] = adapter_instance.operation_id return result else: common.set_error_message( "Invalid result returned from Displayer! Dictionary is expected!" ) else: if isinstance(result, list): result = "Launched %s operations." % len(result) common.set_important_message(str(result)) except formencode.Invalid, excep: errors = excep.unpack_errors()
def getfiltereddatatypes(self, name, parent_div, tree_session_key, filters): """ Given the name from the input tree, the dataType required and a number of filters, return the available dataType that satisfy the conditions imposed. """ previous_tree = self.context.get_session_tree_for_key(tree_session_key) if previous_tree is None: common.set_error_message("Adapter Interface not in session for filtering!") raise cherrypy.HTTPRedirect("/tvb?error=True") current_node = self._get_node(previous_tree, name) if current_node is None: raise Exception("Could not find node :" + name) datatype = current_node[ABCAdapter.KEY_DATATYPE] filters = json.loads(filters) availablefilter = json.loads(FilterChain.get_filters_for_type(datatype)) for i, filter_ in enumerate(filters[FILTER_FIELDS]): #Check for filter input of type 'date' as these need to be converted if filter_ in availablefilter and availablefilter[filter_][FILTER_TYPE] == 'date': try: temp_date = string2date(filters[FILTER_VALUES][i], False) filters[FILTER_VALUES][i] = temp_date except ValueError: raise #In order for the filter object not to "stack up" on multiple calls to #this method, create a deepCopy to work with if ABCAdapter.KEY_CONDITION in current_node: new_filter = copy.deepcopy(current_node[ABCAdapter.KEY_CONDITION]) else: new_filter = FilterChain() new_filter.fields.extend(filters[FILTER_FIELDS]) new_filter.operations.extend(filters[FILTER_OPERATIONS]) new_filter.values.extend(filters[FILTER_VALUES]) #Get dataTypes that match the filters from DB then populate with values values, total_count = InputTreeManager().populate_option_values_for_dtype( common.get_current_project().id, datatype, new_filter, self.context.get_current_step() ) #Create a dictionary that matches what the template expects parameters = {ABCAdapter.KEY_NAME: name, ABCAdapter.KEY_FILTERABLE: availablefilter, ABCAdapter.KEY_TYPE: ABCAdapter.TYPE_SELECT, ABCAdapter.KEY_OPTIONS: values, ABCAdapter.KEY_DATATYPE: datatype} if total_count > MAXIMUM_DATA_TYPES_DISPLAYED: parameters[KEY_WARNING] = WARNING_OVERFLOW if ABCAdapter.KEY_REQUIRED in current_node: parameters[ABCAdapter.KEY_REQUIRED] = current_node[ABCAdapter.KEY_REQUIRED] if len(values) > 0 and string2bool(str(parameters[ABCAdapter.KEY_REQUIRED])): parameters[ABCAdapter.KEY_DEFAULT] = str(values[-1][ABCAdapter.KEY_VALUE]) previous_selected = self.context.get_current_default(name) if previous_selected in [str(vv['value']) for vv in values]: parameters[ABCAdapter.KEY_DEFAULT] = previous_selected template_specification = {"inputRow": parameters, "disabled": False, "parentDivId": parent_div, common.KEY_SESSION_TREE: tree_session_key} return self.fill_default_attributes(template_specification)
def getfiltereddatatypes(self, name, parent_div, tree_session_key, filters): """ Given the name from the input tree, the dataType required and a number of filters, return the available dataType that satisfy the conditions imposed. """ previous_tree = self.context.get_session_tree_for_key(tree_session_key) if previous_tree is None: common.set_error_message("Adapter Interface not in session for filtering!") raise cherrypy.HTTPRedirect("/tvb?error=True") current_node = self._get_node(previous_tree, name) if current_node is None: raise Exception("Could not find node :" + name) datatype = current_node[ABCAdapter.KEY_DATATYPE] filters = json.loads(filters) availablefilter = json.loads(FilterChain.get_filters_for_type(datatype)) for i, filter_ in enumerate(filters[FILTER_FIELDS]): # Check for filter input of type 'date' as these need to be converted if filter_ in availablefilter and availablefilter[filter_][FILTER_TYPE] == 'date': try: temp_date = string2date(filters[FILTER_VALUES][i], False) filters[FILTER_VALUES][i] = temp_date except ValueError: raise # In order for the filter object not to "stack up" on multiple calls to # this method, create a deepCopy to work with if ABCAdapter.KEY_CONDITION in current_node: new_filter = copy.deepcopy(current_node[ABCAdapter.KEY_CONDITION]) else: new_filter = FilterChain() new_filter.fields.extend(filters[FILTER_FIELDS]) new_filter.operations.extend(filters[FILTER_OPERATIONS]) new_filter.values.extend(filters[FILTER_VALUES]) # Get dataTypes that match the filters from DB then populate with values values, total_count = InputTreeManager().populate_option_values_for_dtype( common.get_current_project().id, datatype, new_filter, self.context.get_current_step()) # Create a dictionary that matches what the template expects parameters = {ABCAdapter.KEY_NAME: name, ABCAdapter.KEY_FILTERABLE: availablefilter, ABCAdapter.KEY_TYPE: ABCAdapter.TYPE_SELECT, ABCAdapter.KEY_OPTIONS: values, ABCAdapter.KEY_DATATYPE: datatype} if total_count > MAXIMUM_DATA_TYPES_DISPLAYED: parameters[KEY_WARNING] = WARNING_OVERFLOW if ABCAdapter.KEY_REQUIRED in current_node: parameters[ABCAdapter.KEY_REQUIRED] = current_node[ABCAdapter.KEY_REQUIRED] if len(values) > 0 and string2bool(str(parameters[ABCAdapter.KEY_REQUIRED])): parameters[ABCAdapter.KEY_DEFAULT] = str(values[-1][ABCAdapter.KEY_VALUE]) previous_selected = self.context.get_current_default(name) if previous_selected in [str(vv['value']) for vv in values]: parameters[ABCAdapter.KEY_DEFAULT] = previous_selected template_specification = {"inputRow": parameters, "disabled": False, "parentDivId": parent_div, common.KEY_SESSION_TREE: tree_session_key} return self.fill_default_attributes(template_specification)
def _remove_project(self, project_id): """Private method for removing project.""" try: self.project_service.remove_project(project_id) except ServicesBaseException, exc: self.logger.error("Could not delete project!") self.logger.exception(exc) common.set_error_message(exc.message)
def step_1(self): """ Generate the required template dictionary for the first step. """ current_stimuli_region = common.get_from_session(KEY_REGION_STIMULUS) selected_stimulus_gid = current_stimuli_region.gid.hex project_id = common.get_current_project().id region_stim_selector_form = StimulusRegionSelectorForm(project_id) region_stim_selector_form.region_stimulus.data = selected_stimulus_gid region_stim_selector_form.display_name.data = common.get_from_session( KEY_REGION_STIMULUS_NAME) region_stim_creator_form = RegionStimulusCreatorForm( self.equation_choices, project_id) if not hasattr( current_stimuli_region, 'connectivity') or not current_stimuli_region.connectivity: conn = try_get_last_datatype(project_id, ConnectivityIndex) if conn is None: current_stimuli_region.connectivity = uuid.uuid4() common.set_error_message(self.MSG_MISSING_CONNECTIVITY) else: current_stimuli_region.connectivity = uuid.UUID(conn.gid) region_stim_creator_form.fill_from_trait(current_stimuli_region) template_specification = dict( title="Spatio temporal - Region stimulus") template_specification[ 'mainContent'] = 'spatial/stimulus_region_step1_main' template_specification['isSingleMode'] = True template_specification[ 'regionStimSelectorForm'] = self.render_spatial_form( region_stim_selector_form) template_specification[ 'regionStimCreatorForm'] = self.render_spatial_form( region_stim_creator_form) template_specification['baseUrl'] = '/spatial/stimulus/region' self.plotted_equation_prefixes = { self.CONNECTIVITY_FIELD: region_stim_creator_form.connectivity.name, self.TEMPORAL_FIELD: region_stim_creator_form.temporal.name, self.TEMPORAL_PARAMS_FIELD: region_stim_creator_form.temporal_params.name[1:], self.DISPLAY_NAME_FIELD: region_stim_selector_form.display_name.name } template_specification['fieldsWithEvents'] = json.dumps( self.plotted_equation_prefixes) template_specification[ 'next_step_url'] = '/spatial/stimulus/region/step_1_submit' template_specification['anyScaling'] = 0 template_specification = self._add_extra_fields_to_interface( template_specification) return self.fill_default_attributes(template_specification)
def editone(self, project_id=None, cancel=False, save=False, delete=False, **data): """ Create or change Project. When project_id is empty we create a new entity, otherwise we are to edit and existent one. """ if cherrypy.request.method == 'POST' and cancel: raise cherrypy.HTTPRedirect('/project') if cherrypy.request.method == 'POST' and delete: self._remove_project(project_id) raise cherrypy.HTTPRedirect('/project/viewall') current_user = common.get_logged_user() is_create = False if project_id is None or not int(project_id): is_create = True data["administrator"] = current_user.display_name admin_username = current_user.username else: current_project = self.project_service.find_project(project_id) if not save: # Only when we do not have submitted data, # populate fields with initial values for edit. data = dict(name=current_project.name, description=current_project.description) data["administrator"] = current_project.administrator.display_name admin_username = current_project.administrator.username self._mark_selected(current_project) data["project_id"] = project_id template_specification = dict(mainContent="project/editone", data=data, isCreate=is_create, title="Create new project" if is_create else "Edit " + data["name"], editUsersEnabled=(current_user.username == admin_username)) try: if cherrypy.request.method == 'POST' and save: data = EditForm().to_python(data) saved_project = self.project_service.store_project(current_user, is_create, project_id, **data) if StorageInterface.encryption_enabled() and is_create: project_folder = StorageInterface().get_project_folder(saved_project.name) StorageInterface.sync_folders(project_folder) shutil.rmtree(project_folder) self._mark_selected(saved_project) raise cherrypy.HTTPRedirect('/project/viewall') except formencode.Invalid as excep: self.logger.debug(str(excep)) template_specification[common.KEY_ERRORS] = excep.unpack_errors() except ProjectServiceException as excep: self.logger.debug(str(excep)) common.set_error_message(excep.message) raise cherrypy.HTTPRedirect('/project/viewall') all_users, members, pages = self.user_service.get_users_for_project(current_user.username, project_id) template_specification['usersList'] = all_users template_specification['usersMembers'] = [m.id for m in members] template_specification['usersPages'] = pages template_specification['usersCurrentPage'] = 1 return self.fill_default_attributes(template_specification, 'properties')
def projectupload(self, **data): """Upload Project from TVB ZIP.""" self.logger.debug("Uploading ..." + str(data)) try: upload_param = "uploadedfile" if upload_param in data and data[upload_param]: import_service = ImportService() import_service.import_project_structure(data[upload_param], common.get_logged_user().id) except ServicesBaseException, excep: self.logger.warning(excep.message) common.set_error_message(excep.message)
def updatemetadata(self, **data): """ Submit MetaData edited for DataType(Group) or Operation(Group). """ try: self.project_service.update_metadata(data) except ServicesBaseException as excep: self.logger.error("Could not execute MetaData update!") self.logger.exception(excep) common.set_error_message(excep.message) return excep.message
def _remove_project(self, project_id): """Private method for removing project.""" try: self.project_service.remove_project(project_id) except ServicesBaseException as exc: self.logger.error("Could not delete project!") self.logger.exception(exc) common.set_error_message(exc.message) prj = common.get_current_project() if prj is not None and prj.id == int(project_id): SimulatorContext().clean_project_data_from_session()
def updatemetadata(self, **data): """ Submit MetaData edited for DataType(Group) or Operation(Group). """ try: self.project_service.update_metadata(data) except ServicesBaseException, excep: self.logger.error("Could not execute MetaData update!") self.logger.exception(excep) common.set_error_message(excep.message) return excep.message
def validate(self, name): """ A link to this page will be sent to the administrator to validate the registration of each user. """ success = self.user_service.validate_user(name) if not success: common.set_error_message("Problem validating user:"******"!! Please check logs.") self.logger.error("Problem validating user " + name) else: common.set_info_message("User Validated successfully and notification email sent!") raise cherrypy.HTTPRedirect('/tvb')
def index(self, **data): """ Login page (with or without messages). """ template_specification = dict(mainContent="user/login", title="Login", data=data) self._set_base_url() if cherrypy.request.method == 'POST': keycloak_login = TvbProfile.current.KEYCLOAK_LOGIN_ENABLED form = LoginForm() if not keycloak_login else KeycloakLoginForm() try: data = form.to_python(data) if keycloak_login: auth_token = data[KEY_AUTH_TOKEN] kc_user_info = AuthorizationManager( TvbProfile.current.KEYCLOAK_WEB_CONFIG ).get_keycloak_instance().userinfo(auth_token) user = self.user_service.get_external_db_user(kc_user_info) else: username = data[KEY_USERNAME] password = data[KEY_PASSWORD] user = self.user_service.check_login(username, password) if user is not None: common.add2session(common.KEY_USER, user) common.set_info_message('Welcome ' + user.display_name) self.logger.debug("User " + user.username + " has just logged in!") if user.selected_project is not None: prj = user.selected_project prj = ProjectService().find_project(prj) self._mark_selected(prj) raise cherrypy.HTTPRedirect('/user/profile') elif not keycloak_login: common.set_error_message( 'Wrong username/password, or user not yet validated...' ) self.logger.debug("Wrong username " + username + " !!!") else: common.set_error_message( 'Your account is not validated. Please contact us at [email protected] for more details' ) self.logger.debug("Invalidated account") template_specification[common.KEY_ERRORS] = { 'invalid_user': True } except formencode.Invalid as excep: template_specification[ common.KEY_ERRORS] = excep.unpack_errors() return self.fill_default_attributes(template_specification)
def _update_figure(self, figure_id, **data): """ Updates the figure details to the given data. """ try: data = EditPreview().to_python(data) self.figure_service.edit_result_figure(figure_id, **data) common.set_info_message('Figure details updated successfully.') return True except formencode.Invalid, excep: self.logger.debug(excep) common.set_error_message(excep.message) return False
def _update_figure(self, figure_id, **data): """ Updates the figure details to the given data. """ try: data = EditPreview().to_python(data) self.figure_service.edit_result_figure(figure_id, **data) common.set_info_message('Figure details updated successfully.') return True except formencode.Invalid as excep: self.logger.debug(excep) common.set_error_message(excep.message) return False
def step_1(self, do_reset=0, **kwargs): """ Generate the html for the first step of the local connectivity page. :param do_reset: Boolean telling to start from empty page or not :param kwargs: not actually used, but parameters are still submitted from UI since we just\ use the same js function for this. """ project_id = common.get_current_project().id if int(do_reset) == 1: new_lconn = LocalConnectivityCreatorModel() default_surface_index = try_get_last_datatype(project_id, SurfaceIndex, LocalConnectivityCreatorForm.get_filters()) if default_surface_index: new_lconn.surface = uuid.UUID(default_surface_index.gid) else: # Surface is required in model and we should keep it like this, but we also want to new_lconn.surface = uuid.uuid4() common.set_error_message(self.MSG_MISSING_SURFACE) common.add2session(KEY_LCONN, new_lconn) current_lconn = common.get_from_session(KEY_LCONN) existent_lcon_form = self.algorithm_service.prepare_adapter_form(form_instance=LocalConnectivitySelectorForm(), project_id=common.get_current_project().id) existent_lcon_form.existentEntitiesSelect.data = current_lconn.gid.hex configure_lcon_form = self.algorithm_service.prepare_adapter_form( form_instance=LocalConnectivityCreatorForm(), project_id=common.get_current_project().id) configure_lcon_form.fill_from_trait(current_lconn) current_lconn.equation = configure_lcon_form.spatial.value() template_specification = dict(title="Surface - Local Connectivity") template_specification['mainContent'] = 'spatial/local_connectivity_step1_main' template_specification['inputList'] = self.render_spatial_form(configure_lcon_form) template_specification['displayCreateLocalConnectivityBtn'] = True template_specification['loadExistentEntityUrl'] = LOAD_EXISTING_URL template_specification['resetToDefaultUrl'] = RELOAD_DEFAULT_PAGE_URL template_specification['existentEntitiesInputList'] = self.render_spatial_form(existent_lcon_form) template_specification['submit_parameters_url'] = '/spatial/localconnectivity/create_local_connectivity' template_specification['equationViewerUrl'] = '/spatial/localconnectivity/get_equation_chart' template_specification['baseUrl'] = self.base_url self.plotted_equation_prefixes = {self.SURFACE_FIELD: configure_lcon_form.surface.name, self.EQUATION_FIELD: configure_lcon_form.spatial.name, self.CUTOFF_FIELD: configure_lcon_form.cutoff.name, self.DISPLAY_NAME_FIELD: configure_lcon_form.display_name.name, self.EQUATION_PARAMS_FIELD: configure_lcon_form.spatial.subform_field.name[1:]} template_specification['equationsPrefixes'] = json.dumps(self.plotted_equation_prefixes) template_specification['next_step_url'] = '/spatial/localconnectivity/step_2' return self.fill_default_attributes(template_specification)
def execute_post(self, project_id, submit_url, step_key, algorithm, **data): """ Execute HTTP POST on a generic step.""" errors = None adapter_instance = ABCAdapter.build_adapter(algorithm) try: form = adapter_instance.get_form()(project_id=project_id) if 'fill_defaults' in data: form.fill_from_post_plus_defaults(data) else: form.fill_from_post(data) view_model = None if form.validate(): try: view_model = form.get_view_model()() form.fill_trait(view_model) self.context.add_view_model_to_session(view_model) except NotImplementedError: self.logger.exception("Form and/or ViewModel not fully implemented for " + str(form)) raise InvalidFormValues("Invalid form inputs! Could not find a model for this form!", error_dict=form.get_errors_dict()) else: raise InvalidFormValues("Invalid form inputs! Could not fill algorithm from the given inputs!", error_dict=form.get_errors_dict()) adapter_instance.submit_form(form) if issubclass(type(adapter_instance), ABCDisplayer): adapter_instance.current_project_id = project_id adapter_instance.user_id = common.get_logged_user().id result = adapter_instance.launch(view_model) if isinstance(result, dict): return result else: common.set_error_message("Invalid result returned from Displayer! Dictionary is expected!") return {} result = self.operation_services.fire_operation(adapter_instance, common.get_logged_user(), project_id, view_model=view_model) if isinstance(result, list): result = "Launched %s operations." % len(result) common.set_important_message(str(result)) except formencode.Invalid as excep: errors = excep.unpack_errors() common.set_error_message("Invalid form inputs") self.logger.warning("Invalid form inputs %s" % errors) except (OperationException, LaunchException, TraitValueError) as excep1: self.logger.exception("Error while executing a Launch procedure:" + excep1.message) common.set_error_message(excep1.message) except InvalidFormValues as excep2: message, errors = excep2.display_full_errors() common.set_error_message(message) self.logger.warning("%s \n %s" % (message, errors)) template_specification = self.get_template_for_adapter(project_id, step_key, algorithm, submit_url) if (errors is not None) and (template_specification is not None): template_specification[common.KEY_ERRORS] = errors return template_specification
def execute_post(self, project_id, submit_url, step_key, algorithm, **data): """ Execute HTTP POST on a generic step.""" errors = None adapter_instance = ABCAdapter.build_adapter(algorithm) try: result = self.flow_service.fire_operation(adapter_instance, common.get_logged_user(), project_id, **data) # Store input data in session, for informing user of it. step = self.flow_service.get_category_by_id(step_key) if not step.rawinput: self.context.add_adapter_to_session(None, None, copy.deepcopy(data)) if isinstance(adapter_instance, ABCDisplayer): if isinstance(result, dict): result[common. KEY_OPERATION_ID] = adapter_instance.operation_id return result else: common.set_error_message( "Invalid result returned from Displayer! Dictionary is expected!" ) else: if isinstance(result, list): result = "Launched %s operations." % len(result) common.set_important_message(str(result)) except formencode.Invalid as excep: errors = excep.unpack_errors() except OperationException as excep1: self.logger.exception("Error while executing a Launch procedure:" + excep1.message) common.set_error_message(excep1.message) previous_step = self.context.get_current_substep() should_reset = previous_step is None or data.get( common.KEY_ADAPTER) != previous_step template_specification = self.get_template_for_adapter( project_id, step_key, algorithm, submit_url, should_reset) if (errors is not None) and (template_specification is not None): template_specification[common.KEY_ERRORS] = errors template_specification[ common.KEY_OPERATION_ID] = adapter_instance.operation_id return template_specification
def create_stimulus(self): """ Creates a stimulus from the given data. """ try: context = common.get_from_session(KEY_SURFACE_CONTEXT) surface_stimulus_creator = self.get_creator_and_interface(SURFACE_STIMULUS_CREATOR_MODULE, SURFACE_STIMULUS_CREATOR_CLASS, StimuliSurface())[0] self.flow_service.fire_operation(surface_stimulus_creator, common.get_logged_user(), common.get_current_project().id, **context.equation_kwargs) common.set_important_message("The operation for creating the stimulus was successfully launched.") context.selected_stimulus = None except (NameError, ValueError, SyntaxError), _: common.set_error_message("The operation failed due to invalid parameter input.") return False
def viewall(self, create=False, page=1, selected_project_id=None, **_): """ Display all existent projects. Choose one project to work with. """ page = int(page) if cherrypy.request.method == 'POST' and create: raise cherrypy.HTTPRedirect('/project/editone') current_user_id = common.get_logged_user().id ## Select project if user choose one. if selected_project_id is not None: try: selected_project = self.project_service.find_project(selected_project_id) self._mark_selected(selected_project) except ProjectServiceException, excep: self.logger.error(excep) self.logger.warning("Could not select project: " + str(selected_project_id)) common.set_error_message("Could not select project: " + str(selected_project_id))
def profile(self, logout=False, save=False, **data): """ Display current user's profile page. On POST: logout, or save password/email. """ if cherrypy.request.method == 'POST' and logout: raise cherrypy.HTTPRedirect('/user/logout') template_specification = dict(mainContent="profile", title="User Profile") user = common.get_logged_user() if cherrypy.request.method == 'POST' and save: try: form = EditUserForm() data = form.to_python(data) if data.get(KEY_PASSWORD): user.password = md5(data[KEY_PASSWORD]).hexdigest() if data.get(KEY_EMAIL): user.email = data[KEY_EMAIL] old_password = None if data.get('old_password'): old_password = md5(data['old_password']).hexdigest() self.user_service.edit_user(user, old_password) if old_password: common.set_info_message("Changes Submitted!") else: common.set_info_message("Submitted! No password changed.") except formencode.Invalid as excep: template_specification[common.KEY_ERRORS] = excep.unpack_errors() except UsernameException as excep: self.logger.exception(excep) user = common.get_logged_user() common.add2session(common.KEY_USER, self.user_service.get_user_by_id(user.id)) common.set_error_message("Could not save changes. Probably wrong old password!!") else: #Update session user since disk size might have changed from last time to profile. user = self.user_service.get_user_by_id(user.id) common.add2session(common.KEY_USER, user) template_specification['user_used_disk_human'] = format_bytes_human( self.user_service.compute_user_generated_disk_size(user.id)) return self.fill_default_attributes(template_specification)
def get_data_from_burst_configuration(self): """ Returns the model and surface instances from the burst configuration. """ des = SerializationManager(common.get_from_session(common.KEY_BURST_CONFIG)) ### Read from session current burst-configuration if des.conf is None: return None, None if des.has_model_pse_ranges(): common.set_error_message("When configuring model parameters you are not allowed to specify range values.") raise cherrypy.HTTPRedirect("/burst/") try: model, integrator = des.make_model_and_integrator() except Exception: self.logger.exception("Some of the provided parameters have an invalid value.") common.set_error_message("Some of the provided parameters have an invalid value.") raise cherrypy.HTTPRedirect("/burst/") surface = des.get_surface() return model, surface
def settings(self, save_settings=False, **data): """Main settings page submit and get""" template_specification = dict(mainContent="../settings/system_settings", title="System Settings") if save_settings: try: form = SettingsForm() data = form.to_python(data) isrestart, isreset = self.settingsservice.save_settings(**data) if isrestart: thread = threading.Thread(target=self._restart_services, kwargs={'should_reset': isreset}) thread.start() common.add2session(common.KEY_IS_RESTART, True) common.set_important_message('Please wait until TVB is restarted properly!') raise cherrypy.HTTPRedirect('/tvb') # Here we will leave the same settings page to be displayed. # It will continue reloading when CherryPy restarts. except formencode.Invalid, excep: template_specification[common.KEY_ERRORS] = excep.unpack_errors() except InvalidSettingsException, excep: self.logger.error('Invalid settings! Exception %s was raised' % (str(excep))) common.set_error_message(excep.message)
def recoverpassword(self, cancel=False, **data): """ This form should reset a password for a given userName/email and send a notification message to that email. """ template_specification = dict(mainContent="recover_password", title="Recover password", data=data) redirect = False if cherrypy.request.method == "POST": if cancel: raise cherrypy.HTTPRedirect("/user") form = RecoveryForm() try: data = form.to_python(data) okmessage = self.user_service.reset_password(**data) common.set_info_message(okmessage) redirect = True except formencode.Invalid, excep: template_specification[common.KEY_ERRORS] = excep.unpack_errors() redirect = False except UsernameException, excep1: self.logger.exception("Could not reset password!") common.set_error_message(excep1.message) redirect = False
def execute_post(self, project_id, submit_url, step_key, algorithm, **data): """ Execute HTTP POST on a generic step.""" errors = None adapter_instance = ABCAdapter.build_adapter(algorithm) try: result = self.flow_service.fire_operation(adapter_instance, common.get_logged_user(), project_id, **data) # Store input data in session, for informing user of it. step = self.flow_service.get_category_by_id(step_key) if not step.rawinput: self.context.add_adapter_to_session(None, None, copy.deepcopy(data)) if isinstance(adapter_instance, ABCDisplayer): if isinstance(result, dict): result[common.KEY_OPERATION_ID] = adapter_instance.operation_id return result else: common.set_error_message("Invalid result returned from Displayer! Dictionary is expected!") else: if isinstance(result, list): result = "Launched %s operations." % len(result) common.set_important_message(str(result)) except formencode.Invalid as excep: errors = excep.unpack_errors() except OperationException as excep1: self.logger.exception("Error while executing a Launch procedure:" + excep1.message) common.set_error_message(excep1.message) previous_step = self.context.get_current_substep() should_reset = previous_step is None or data.get(common.KEY_ADAPTER) != previous_step template_specification = self.get_template_for_adapter(project_id, step_key, algorithm, submit_url, should_reset) if (errors is not None) and (template_specification is not None): template_specification[common.KEY_ERRORS] = errors template_specification[common.KEY_OPERATION_ID] = adapter_instance.operation_id return template_specification
def register(self, cancel=False, **data): """ This register form send an e-mail to the user and to the site admin. """ template_specification = dict(mainContent="register", title="Register", data=data) redirect = False if cherrypy.request.method == "POST": if cancel: raise cherrypy.HTTPRedirect("/user") try: okmessage = self._create_user(**data) common.set_info_message(okmessage) redirect = True except formencode.Invalid, excep: template_specification[common.KEY_ERRORS] = excep.unpack_errors() redirect = False except Exception, excep1: self.logger.error("Could not create user:"******"username"]) self.logger.exception(excep1) common.set_error_message( "We are very sorry, but we could not create your user. Most probably is " "because it was impossible to sent emails. Please try again later..." ) redirect = False
def editresultfigures(self, remove_figure=False, rename_session=False, remove_session=False, **data): """ This method knows how to handle the following actions: remove figure, update figure, remove session and update session. """ project = common.get_current_project() user = common.get_logged_user() redirect_url = '/project/figure/displayresultfigures' if "selected_session" in data and data["selected_session"] is not None and len(data["selected_session"]): redirect_url += '/' + data["selected_session"] del data["selected_session"] figure_id = None if "figure_id" in data: figure_id = data["figure_id"] del data["figure_id"] if cherrypy.request.method == 'POST' and rename_session: successfully_updated = True if "old_session_name" in data and "new_session_name" in data: figures_dict, _ = self.figure_service.retrieve_result_figures(project, user, data["old_session_name"]) for _key, value in figures_dict.iteritems(): for figure in value: new_data = {"name": figure.name, "session_name": data["new_session_name"]} success = self._update_figure(figure.id, **new_data) if not success: successfully_updated = False if successfully_updated: common.set_info_message("The session was successfully updated!") else: common.set_error_message("The session was not successfully updated! " "There could be some figures that still refer to the old session.") elif cherrypy.request.method == 'POST' and remove_session: successfully_removed = True if "old_session_name" in data: figures_dict, _ = self.figure_service.retrieve_result_figures(project, user, data["old_session_name"]) for _key, value in figures_dict.iteritems(): for figure in value: success = self.figure_service.remove_result_figure(figure.id) if not success: successfully_removed = False if successfully_removed: common.set_info_message("The session was removed successfully!") else: common.set_error_message("The session was not entirely removed!") elif cherrypy.request.method == 'POST' and remove_figure and figure_id is not None: success = self.figure_service.remove_result_figure(figure_id) if success: common.set_info_message("Figure removed successfully!") else: common.set_error_message("Figure could not be removed!") elif figure_id is not None: self._update_figure(figure_id, **data) raise cherrypy.HTTPRedirect(redirect_url)
template_specification = dict(mainContent="project/editone", data=data, isCreate=is_create, title="Create new project" if is_create else "Edit " + data["name"], editUsersEnabled=(current_user.username == data['administrator'])) try: if cherrypy.request.method == 'POST' and save: common.remove_from_session(common.KEY_PROJECT) common.remove_from_session(common.KEY_CACHED_SIMULATOR_TREE) self._persist_project(data, project_id, is_create, current_user) raise cherrypy.HTTPRedirect('/project/viewall') except formencode.Invalid, excep: self.logger.debug(str(excep)) template_specification[common.KEY_ERRORS] = excep.unpack_errors() except ProjectServiceException, excep: self.logger.debug(str(excep)) common.set_error_message(excep.message) raise cherrypy.HTTPRedirect('/project/viewall') all_users, members, pages = self.user_service.get_users_for_project(current_user.username, project_id) template_specification['usersList'] = all_users template_specification['usersMembers'] = [m.id for m in members] template_specification['usersPages'] = pages template_specification['usersCurrentPage'] = 1 return self.fill_default_attributes(template_specification, 'properties') @expose_fragment('project/project_members') def getmemberspage(self, page, project_id=None): """Retrieve a new page of Project members.""" current_name = common.get_logged_user().username all_users, members, _ = self.user_service.get_users_for_project(current_name, project_id, int(page))