def invokeadaptermethod(self, adapter_id, method_name, **data): """ Public web method, to be used when invoking specific methods from external Adapters/Algorithms. """ algo_group = self.flow_service.get_algo_group_by_identifier(adapter_id) try: adapter_instance = self.flow_service.build_adapter_instance( algo_group) result = self.flow_service.fire_operation( adapter_instance, base.get_logged_user(), base.get_current_project().id, method_name, **data) base.set_info_message("Submit OK!") if isinstance(adapter_instance, ABCDisplayer) and isinstance( result, dict): base.remove_from_session(base.KEY_MESSAGE) result[ABCDisplayer.KEY_IS_ADAPTER] = True result[base.KEY_DISPLAY_MENU] = True result[base.KEY_OPERATION_ID] = adapter_instance.operation_id result[base.KEY_ADAPTER] = adapter_id if KEY_CONTROLLS not in result: result[KEY_CONTROLLS] = None return self.fill_default_attributes(result, algo_group) except OperationException, excep: base.set_warning_message('Problem when submitting data!') self.logger.error( "Invalid method, or wrong parameters when invoking external method on post!" ) self.logger.exception(excep)
def launch_burst(self, launch_mode, burst_name, **data): """ Do the actual burst launch, using the configuration saved in current session. :param launch_mode: new/branch/continue :param burst_name: user-given burst name. It can be empty (case in which we will fill with simulation_x) :param data: kwargs for simulation input parameters. """ burst_config = base.get_from_session(base.KEY_BURST_CONFIG) ## Validate new burst-name if burst_name != 'none_undefined': self._validate_burst_name(burst_name) burst_config.name = burst_name ## Fill all parameters user_id = base.get_logged_user().id data[base.KEY_ADAPTER] = self.cached_simulator_algorithm_id burst_config.update_simulator_configuration(data) burst_config.fk_project = base.get_current_project().id ## Do the asynchronous launch burst_id, burst_name = self.burst_service.launch_burst( burst_config, 0, self.cached_simulator_algorithm_id, user_id, launch_mode) return [burst_id, burst_name]
def deco(*a, **b): """ Allow to get the docstring back""" if hasattr(cherrypy, basecontroller.KEY_SESSION): if basecontroller.get_logged_user(): return func(*a, **b) basecontroller.set_error_message('Login Required!') raise cherrypy.HTTPRedirect('/user')
def storeresultfigure(self, img_type, operation_id, **data): """Create preview for current displayed canvas and store image in current session, for future comparison.""" project = base.get_current_project() user = base.get_logged_user() self.figure_service.store_result_figure(project, user, img_type, operation_id, data['export_data'])
def deco(*a, **b): """ Decorator for public method""" if hasattr(cherrypy, basecontroller.KEY_SESSION): user = basecontroller.get_logged_user() if (user is not None and user.is_administrator() ) or SettingsService.is_first_run(): return func(*a, **b) basecontroller.set_error_message( 'Only Administrators can access this application area!') raise cherrypy.HTTPRedirect('/tvb')
def switchOnlineHelp(self): """ Switch flag that displays online helps """ user = basecontroller.get_logged_user() # Change OnlineHelp Active flag and save user user.switch_online_help_state() self.user_service.edit_user(user) raise cherrypy.HTTPRedirect("/user/profile")
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]: self.import_service.import_project_structure( data[upload_param], bc.get_logged_user().id) except ServicesBaseException, excep: self.logger.warning(excep.message) bc.set_error_message(excep.message)
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") if cherrypy.request.method == 'POST' and save: try: form = EditUserForm() data = form.to_python(data) user = basecontroller.get_logged_user() if KEY_PASSWORD in data and data[KEY_PASSWORD]: user.password = md5(data[KEY_PASSWORD]).hexdigest() if KEY_EMAIL in data and data[KEY_EMAIL]: user.email = data[KEY_EMAIL] old_password = None if 'old_password' in data and data['old_password']: old_password = md5(data['old_password']).hexdigest() self.user_service.edit_user(user, old_password) if old_password: basecontroller.set_info_message("Changes Submitted!") else: basecontroller.set_info_message( "Submitted! No password changed.") except formencode.Invalid, excep: template_specification[ basecontroller.KEY_ERRORS] = excep.unpack_errors() except UsernameException, excep: self.logger.exception(excep) user = basecontroller.get_logged_user() basecontroller.add2session( basecontroller.KEY_USER, self.user_service.get_user_by_id(user.id)) basecontroller.set_error_message( "Could not save changes. Probably wrong old password!!")
def getmemberspage(self, page, project_id=None): """Retrieve a new page of Project members.""" current_name = bc.get_logged_user().username all_users, members, _ = self.user_service.get_users_for_project( current_name, project_id, int(page)) edit_enabled = True if project_id is not None: current_project = self.project_service.find_project(project_id) edit_enabled = ( current_name == current_project.administrator.username) return dict(usersList=all_users, usersMembers=[m.id for m in members], usersCurrentPage=page, editUsersEnabled=edit_enabled)
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 = bc.get_logged_user() is_create = False if project_id is None or not int(project_id): is_create = True data["administrator"] = 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.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 == data['administrator'])) try: if cherrypy.request.method == 'POST' and save: bc.remove_from_session(bc.KEY_PROJECT) bc.remove_from_session(bc.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[bc.KEY_ERRORS] = excep.unpack_errors()
def create_stimulus(self): """ Creates a stimulus from the given data. """ try: context = base.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, base.get_logged_user(), base.get_current_project().id, **context.equation_kwargs) base.set_info_message("The operation for creating the stimulus was successfully launched.") context.selected_stimulus = None except (NameError, ValueError, SyntaxError), _: base.set_error_message("The operation failed due to invalid parameter input.") return False
def create_local_connectivity(self, **kwargs): """ Used for creating and storing a local connectivity. """ context = base.get_from_session(KEY_LCONN_CONTEXT) local_connectivity_creator = self.get_creator_and_interface( LOCAL_CONN_CREATOR_MODULE, LOCAL_CONN_CREATOR_CLASS, LocalConnectivity())[0] self.flow_service.fire_operation(local_connectivity_creator, base.get_logged_user(), base.get_current_project().id, **kwargs) base.set_info_message( "The operation for creating the local connectivity was successfully launched." ) context.reset() return self.step_1()
def create_stimulus(self): """ Creates a stimulus from the given data. """ context = base.get_from_session(KEY_REGION_CONTEXT) local_connectivity_creator = self.get_creator_and_interface( REGION_STIMULUS_CREATOR_MODULE, REGION_STIMULUS_CREATOR_CLASS, StimuliRegion())[0] context.equation_kwargs.update( {'weight': json.dumps(context.get_weights())}) self.flow_service.fire_operation(local_connectivity_creator, base.get_logged_user(), base.get_current_project().id, **context.equation_kwargs) base.set_info_message( "The operation for creating the stimulus was successfully launched." )
def __get_operations_filters(self): """ Filters for VIEW_ALL_OPERATIONS page. Get from session currently selected filters, or build a new set of filters. """ session_filtes = bc.get_from_session(self.KEY_OPERATION_FILTERS) if session_filtes: return session_filtes else: sim_group = self.flow_service.get_algorithm_by_module_and_class( SIMULATOR_MODULE, SIMULATOR_CLASS)[1] new_filters = StaticFiltersFactory.build_operations_filters( sim_group, bc.get_logged_user().id) bc.add2session(self.KEY_OPERATION_FILTERS, new_filters) return new_filters
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 = bc.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)) bc.set_error_message("Could not select project: " + str(selected_project_id))
def readprojectsforlink(self, data_id, return_both=False): """ For a given user return a dictionary in form {project_ID: project_Name}. """ for_link, linked = self.project_service.get_linkable_projects_for_user( bc.get_logged_user().id, data_id) to_link_result, linked_result = None, None current_project = bc.get_current_project() if for_link: to_link_result = {} for project in for_link: if project.id != current_project.id: to_link_result[project.id] = project.name to_link_result = json.dumps(to_link_result) if return_both: if linked: linked_result = {} for project in linked: linked_result[project.id] = project.name return to_link_result, linked_result return to_link_result
def displayresultfigures(self, selected_session='all_sessions'): """ Collect and display saved previews, grouped by session.""" project = base.get_current_project() user = base.get_logged_user() data, all_sessions_info = self.figure_service.retrieve_result_figures( project, user, selected_session) manage_figure_title = "Figures for " + str( selected_session) + " category" if selected_session == 'all_sessions': manage_figure_title = "Figures for all categories" template_specification = dict(mainContent="project/figures_display", title="Stored Visualizer Previews", controlPage=None, displayControl=False, selected_sessions_data=data, all_sessions_info=all_sessions_info, selected_session=selected_session, manageFigureTitle=manage_figure_title) template_specification = self.fill_default_attributes( template_specification, subsection='figures') return template_specification
def prepare_group_launch(self, group_gid, step_key, adapter_key, **data): """ Recieves as input a group gid and an algorithm given by category and id, along with data that gives the name of the required input parameter for the algorithm. Having these generate a range of gid's for all the datatypes in the group and launch a new operation group. """ prj_service = ProjectService() dt_group = prj_service.get_datatypegroup_by_gid(group_gid) datatypes = prj_service.get_datatypes_from_datatype_group(dt_group.id) range_param_name = data['range_param_name'] del data['range_param_name'] data[PARAM_RANGE_1] = range_param_name data[range_param_name] = ','.join([dt.gid for dt in datatypes]) OperationService().group_operation_launch( base.get_logged_user().id, base.get_current_project().id, int(adapter_key), int(step_key), **data) redirect_url = self._compute_back_link('operations', base.get_current_project()) raise cherrypy.HTTPRedirect(redirect_url)
def execute_post(self, project_id, submit_url, success_url, step_key, algo_group, method_name=None, **data): """ Execute HTTP POST on a generic step.""" errors = None adapter_instance = self.flow_service.build_adapter_instance(algo_group) try: if method_name is not None: data['method_name'] = method_name result = self.flow_service.fire_operation(adapter_instance, base.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[ base.KEY_OPERATION_ID] = adapter_instance.operation_id return result else: base.set_error_message( "Invalid result returned from Displayer! Dictionary is expected!" ) else: base.set_info_message(str(result)) raise cherrypy.HTTPRedirect(success_url) except formencode.Invalid, excep: errors = excep.unpack_errors()
def start_dti_pipeline(self, cancel=False, start=False, **data): """ Prepare DTI Pipeline run. """ project_id = basecontroller.get_current_project().id if cherrypy.request.method == 'POST' and cancel: raise cherrypy.HTTPRedirect("/project/editstructure/" + str(project_id)) template_specification = dict( title="Import Connectivity", data=data, section_name='project', subsection_name='pipeline', mainContent="pipeline/get_connectivity", includedResources='project/included_resources') if cherrypy.request.method == 'POST' and start: form = ImportForm() try: data = form.to_python(data) service = DTIPipelineService(data['server_ip'], data['username']) current_project = basecontroller.get_current_project() current_user = basecontroller.get_logged_user() service.fire_pipeline(data['dti_scans'], current_project, current_user, data['threads_number']) okmessage = "Import Started! You will see results after few hours on Data Structure Page!" basecontroller.set_info_message(okmessage) raise cherrypy.HTTPRedirect("/project/editstructure/" + str(project_id)) except formencode.Invalid, excep: basecontroller.set_error_message( "Some parameters are invalid!") template_specification[ basecontroller.KEY_ERRORS] = excep.unpack_errors()
def usermanagement(self, cancel=False, page=1, do_persist=False, **data): """ Display a table used for user management. """ if cancel: raise cherrypy.HTTPRedirect('/user/profile') page = int(page) if cherrypy.request.method == 'POST' and do_persist: not_deleted = 0 for key in data: user_id = int(key.split('_')[1]) if 'delete_' in key: self.user_service.delete_user(user_id) if ("role_" in key) and not (("delete_" + str(user_id)) in data): valid = ("validate_" + str(user_id)) in data user = self.user_service.get_user_by_id(user_id) user.role = data[key] user.validated = valid self.user_service.edit_user(user) not_deleted += 1 # The entire current page was deleted, go to previous page if not_deleted == 0 and page > 1: page -= 1 admin_ = basecontroller.get_logged_user().username user_list, pages_no = self.user_service.retrieve_all_users( admin_, page) template_specification = dict(mainContent="user_management", title="Users management", page_number=page, total_pages=pages_no, userList=user_list, allRoles=UserService.USER_ROLES, data={}) return self.fill_default_attributes(template_specification)
else: basecontroller.set_info_message( "Submitted! No password changed.") except formencode.Invalid, excep: template_specification[ basecontroller.KEY_ERRORS] = excep.unpack_errors() except UsernameException, excep: self.logger.exception(excep) user = basecontroller.get_logged_user() basecontroller.add2session( basecontroller.KEY_USER, self.user_service.get_user_by_id(user.id)) basecontroller.set_error_message( "Could not save changes. Probably wrong old password!!") else: user = basecontroller.get_logged_user() #Update session user since disk size might have changed from last time to profile. user = self.user_service.get_user_by_id(user.id) basecontroller.add2session(basecontroller.KEY_USER, user) return self.fill_default_attributes(template_specification) @cherrypy.expose @ajax_call() @logged() def logout(self): """ Logging out user and clean session """ user = basecontroller.remove_from_session(basecontroller.KEY_USER) if user is not None: self.logger.debug("User " + user.username +
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 = base.get_current_project() user = base.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: base.set_info_message( "The session was successfully updated!") else: base.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: base.set_info_message( "The session was removed successfully!") else: base.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: base.set_info_message("Figure removed successfully!") else: base.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)