def __save_external_service( self, trans, **kwd ): # Here we save a newly created external_service or save changed # attributes of an existing external_service. params = util.Params( kwd ) external_service_id = params.get( 'id', None ) name = util.restore_text( params.get( 'external_service_name', '' ) ) description = util.restore_text( params.get( 'external_service_description', '' ) ) version = util.restore_text( params.get( 'external_service_version', '' ) ) external_service_type_id = params.get( 'external_service_type_id', '' ) if external_service_id: # We're saving changed attributes of an existing external_service. external_service = trans.sa_session.query( trans.model.ExternalService ).get( trans.security.decode_id( external_service_id ) ) external_service.name = name external_service.description = description external_service.version = version external_service.form_values.content = self.get_form_values( trans, trans.user, external_service.form_definition, **kwd ) trans.sa_session.add( external_service ) trans.sa_session.add( external_service.form_values ) trans.sa_session.flush() else: # We're saving a newly created external_service external_service_type = self.get_external_service_type( trans, external_service_type_id ) external_service = trans.model.ExternalService( name, description, external_service_type_id, version ) external_service.form_definition = external_service_type.form_definition # Get the form values from kwd, some of which may be different than the defaults in the external service # type config because the user could have overwritten them. values = self.get_form_values( trans, trans.user, external_service.form_definition, **kwd ) external_service.form_values = trans.model.FormValues( external_service.form_definition, values ) trans.sa_session.add( external_service ) trans.sa_session.add( external_service.form_definition ) trans.sa_session.add( external_service.form_values ) trans.sa_session.flush() return external_service
def __build_external_service_widgets( self, trans, external_service=None, **kwd ): params = util.Params( kwd ) if external_service: name = external_service.name description = external_service.description version = external_service.version seq_type = external_service.external_service_type_id else: name = util.restore_text( params.get( 'external_service_name', '' ) ) description = util.restore_text( params.get( 'external_service_description', '' ) ) version = util.restore_text( params.get( 'external_service_version', '' ) ) selected_seq_type = params.get( 'external_service_type_id', '' ) if trans.app.external_service_types.all_external_service_types.has_key( selected_seq_type ): seq_type = trans.app.external_service_types.all_external_service_types[ selected_seq_type ].id else: seq_type = 'none' widgets = [ dict( label='Name', widget=TextField( 'external_service_name', 40, name ), helptext='' ), dict( label='Description', widget=TextField( 'external_service_description', 40, description ), helptext='' ), dict( label='Version', widget=TextField( 'external_service_version', 40, version ), helptext='' ) ] # Do not show the external_service_type selectfield when editing a external_service if not external_service: widgets.append( dict( label='External service type', widget=self.__build_external_service_type_select_field( trans, seq_type, visible_external_service_types_only=True ), helptext='') ) return widgets
def create_category( self, trans, **kwd ): params = util.Params( kwd ) message = util.restore_text( params.get( 'message', '' ) ) status = params.get( 'status', 'done' ) name = util.restore_text( params.get( 'name', '' ) ).strip() description = util.restore_text( params.get( 'description', '' ) ).strip() if params.get( 'create_category_button', False ): if not name or not description: message = 'Enter a valid name and a description' status = 'error' elif suc.get_category_by_name( trans, name ): message = 'A category with that name already exists' status = 'error' else: # Create the category category = trans.app.model.Category( name=name, description=description ) trans.sa_session.add( category ) trans.sa_session.flush() message = "Category '%s' has been created" % category.name status = 'done' trans.response.send_redirect( web.url_for( controller='admin', action='manage_categories', message=message, status=status ) ) return trans.fill_template( '/webapps/community/category/create_category.mako', name=name, description=description, message=message, status=status )
def parse_request_tup(self, request_tup, **kwd): redirect_action = util.restore_text(kwd.get('redirect_action', '')) titles = util.restore_text(kwd.get('titles', '')) JobId = util.restore_text(kwd.get('JobId', '')) sample_id = util.restore_text(kwd.get('sample_id', '')) message = util.restore_text(kwd.get('message', '')) status = kwd.get('status', 'done') url, http_method, request_params, response_type = request_tup url = unquote_plus(url) # Handle URLs in which we replace param values, which will look something like: # http://127.0.0.1/getinfo/{id}. replace_with_param = url.find('{') > 0 if replace_with_param: # Handle the special-case {JobId} param. if url.find('{JobId}') > 0: if JobId: url = url.replace('{JobId}', str(JobId)) for key, value in kwd.items(): # Don't attempt to replace if there is nothing with which to do it # or if the value itself should be replaced with something. if value and not value.startswith('{'): replace_str = '{%s}' % key if url.find(replace_str) > 0: url = url.replace(replace_str, value) # Handle request parameters in which we replace param values. for key, val in request_params.items(): if val and val.startswith('{'): replace_key = val.lstrip('{').rstrip('}') if replace_key in kwd: request_params[key] = kwd[replace_key] return url, http_method, request_params, response_type
def edit_component(self, trans, **kwd): params = util.Params(kwd) message = util.restore_text(params.get('message', '')) status = params.get('status', 'done') id = params.get('id', None) if not id: message = "No component ids received for editing" trans.response.send_redirect( web.url_for(controller='admin', action='manage_categories', message=message, status='error')) component = suc.get_component(trans, id) if params.get('edit_component_button', False): new_description = util.restore_text(params.get('description', '')).strip() if component.description != new_description: component.description = new_description trans.sa_session.add(component) trans.sa_session.flush() message = "The information has been saved for the component named <b>%s</b>" % ( component.name) status = 'done' return trans.response.send_redirect( web.url_for(controller='repository_review', action='manage_components', message=message, status=status)) return trans.fill_template( '/webapps/community/repository_review/edit_component.mako', component=component, message=message, status=status)
def create_component(self, trans, **kwd): params = util.Params(kwd) message = util.restore_text(params.get('message', '')) status = params.get('status', 'done') name = util.restore_text(params.get('name', '')) description = util.restore_text(params.get('description', '')) if params.get('create_component_button', False): if not name or not description: message = 'Enter a valid name and a description' status = 'error' elif suc.get_component_by_name(trans, name): message = 'A component with that name already exists' status = 'error' else: component = trans.app.model.Component(name=name, description=description) trans.sa_session.add(component) trans.sa_session.flush() message = "Component '%s' has been created" % component.name status = 'done' trans.response.send_redirect( web.url_for(controller='repository_review', action='manage_components', message=message, status=status)) return trans.fill_template( '/webapps/community/repository_review/create_component.mako', name=name, description=description, message=message, status=status)
def register(self, trans, email=None, username=None, password=None, confirm=None, subscribe=False): """ Register a new user. """ if not trans.app.config.allow_user_creation and not trans.user_is_admin: message = "User registration is disabled. Please contact your local Galaxy administrator for an account." if trans.app.config.error_email_to is not None: message += " Contact: %s" % trans.app.config.error_email_to return None, message if not email or not username or not password or not confirm: return None, "Please provide email, username and password." message = "\n".join([validate_email(trans, email), validate_password(trans, password, confirm), validate_publicname(trans, username)]).rstrip() if message: return None, message email = util.restore_text(email) username = util.restore_text(username) message, status = trans.app.auth_manager.check_registration_allowed(email, username, password) if message: return None, message if subscribe: message = self.send_subscription_email(email) if message: return None, message user = self.create(email=email, username=username, password=password) if self.app.config.user_activation_on: self.send_activation_email(trans, email, username) return user, None
def __get_field( self, index, **kwd ): ''' This method retrieves all the user-entered details of a field and returns a dict. ''' params = util.Params( kwd ) label = util.restore_text( params.get( 'field_label_%i' % index, '' ) ) name = util.restore_text( params.get( 'field_name_%i' % index, '' ) ) helptext = util.restore_text( params.get( 'field_helptext_%i' % index, '' ) ) required = params.get( 'field_required_%i' % index, False ) field_type = util.restore_text( params.get( 'field_type_%i' % index, '' ) ) layout = params.get( 'field_layout_%i' % index, '0' ) default = util.restore_text( params.get( 'field_default_%i' % index, '' ) ) if not name.strip(): name = '%i_field_name' % index if field_type == 'SelectField': options = self.__get_select_field_options(index, **kwd) return { 'name': name, 'label': label, 'helptext': helptext, 'visible': True, 'required': required, 'type': field_type, 'selectlist': options, 'layout': layout, 'default': default } return { 'name': name, 'label': label, 'helptext': helptext, 'visible': True, 'required': required, 'type': field_type, 'layout': layout, 'default': default }
def create_form_definition( self, trans, **kwd ): params = util.Params( kwd ) message = util.restore_text( params.get( 'message', '' ) ) status = params.get( 'status', 'done' ) self.__imported_from_file = False if params.get( 'create_form_button', False ): form_definition, message = self.save_form_definition( trans, form_definition_current_id=None, **kwd ) if not form_definition: return trans.response.send_redirect( web.url_for( controller='forms', action='create_form_definition', message=message, status='error', name=util.restore_text( params.get( 'name', '' ) ), description=util.restore_text( params.get( 'description', '' ) ) )) if self.__imported_from_file: return trans.response.send_redirect( web.url_for( controller='forms', action='edit_form_definition', id=trans.security.encode_id( form_definition.current.id )) ) else: return trans.response.send_redirect( web.url_for( controller='forms', action='edit_form_definition', id=trans.security.encode_id( form_definition.current.id ), add_field_button='Add field', name=form_definition.name, description=form_definition.desc, form_type_select_field=form_definition.type ) ) inputs = [ ( 'Name', TextField( 'name', 40, util.restore_text( params.get( 'name', '' ) ) ) ), ( 'Description', TextField( 'description', 40, util.restore_text( params.get( 'description', '' ) ) ) ), ( 'Type', self.__build_form_types_widget( trans, selected=params.get( 'form_type', 'none' ) ) ), ( 'Import from csv file (Optional)', FileField( 'file_data', 40, '' ) ) ] return trans.fill_template( '/admin/forms/create_form.mako', inputs=inputs, message=message, status=status )
def create(self, trans, payload, **kwd): """ POST /api/libraries Creates a new library. """ if not trans.user_is_admin(): raise HTTPForbidden( detail='You are not authorized to create a new library.') params = util.Params(payload) name = util.restore_text(params.get('name', None)) if not name: raise HTTPBadRequest(detail="Missing required parameter 'name'.") description = util.restore_text(params.get('description', '')) synopsis = util.restore_text(params.get('synopsis', '')) if synopsis in ['None', None]: synopsis = '' library = trans.app.model.Library(name=name, description=description, synopsis=synopsis) root_folder = trans.app.model.LibraryFolder(name=name, description='') library.root_folder = root_folder trans.sa_session.add_all((library, root_folder)) trans.sa_session.flush() encoded_id = trans.security.encode_id(library.id) rval = {} rval['url'] = url_for('library', id=encoded_id) rval['name'] = name rval['id'] = encoded_id return [rval]
def create_category(self, trans, **kwd): params = util.Params(kwd) message = util.restore_text(params.get('message', '')) status = params.get('status', 'done') name = util.restore_text(params.get('name', '')).strip() description = util.restore_text(params.get('description', '')).strip() if params.get('create_category_button', False): if not name or not description: message = 'Enter a valid name and a description' status = 'error' elif suc.get_category_by_name(trans, name): message = 'A category with that name already exists' status = 'error' else: # Create the category category = trans.app.model.Category(name=name, description=description) trans.sa_session.add(category) trans.sa_session.flush() message = "Category '%s' has been created" % category.name status = 'done' trans.response.send_redirect( web.url_for(controller='admin', action='manage_categories', message=message, status=status)) return trans.fill_template( '/webapps/community/category/create_category.mako', name=name, description=description, message=message, status=status)
def create_component( self, trans, **kwd ): params = util.Params( kwd ) message = util.restore_text( params.get( 'message', '' ) ) status = params.get( 'status', 'done' ) name = util.restore_text( params.get( 'name', '' ) ) description = util.restore_text( params.get( 'description', '' ) ) if params.get( 'create_component_button', False ): if not name or not description: message = 'Enter a valid name and a description' status = 'error' elif suc.get_component_by_name( trans, name ): message = 'A component with that name already exists' status = 'error' else: component = trans.app.model.Component( name=name, description=description ) trans.sa_session.add( component ) trans.sa_session.flush() message = "Component '%s' has been created" % component.name status = 'done' trans.response.send_redirect( web.url_for( controller='repository_review', action='manage_components', message=message, status=status ) ) return trans.fill_template( '/webapps/community/repository_review/create_component.mako', name=name, description=description, message=message, status=status )
def edit_component( self, trans, **kwd ): params = util.Params( kwd ) message = util.restore_text( params.get( 'message', '' ) ) status = params.get( 'status', 'done' ) id = params.get( 'id', None ) if not id: message = "No component ids received for editing" trans.response.send_redirect( web.url_for( controller='admin', action='manage_categories', message=message, status='error' ) ) component = suc.get_component( trans, id ) if params.get( 'edit_component_button', False ): new_description = util.restore_text( params.get( 'description', '' ) ).strip() if component.description != new_description: component.description = new_description trans.sa_session.add( component ) trans.sa_session.flush() message = "The information has been saved for the component named <b>%s</b>" % ( component.name ) status = 'done' return trans.response.send_redirect( web.url_for( controller='repository_review', action='manage_components', message=message, status=status ) ) return trans.fill_template( '/webapps/community/repository_review/edit_component.mako', component=component, message=message, status=status )
def create( self, trans, payload, **kwd ): """ create( self, trans, payload, **kwd ) * POST /api/libraries: Creates a new library. Only ``name`` parameter is required. .. note:: Currently, only admin users can create libraries. :param payload: dictionary structure containing:: 'name': the new library's name (required) 'description': the new library's description (optional) 'synopsis': the new library's synopsis (optional) :type payload: dict :returns: detailed library information :rtype: dict :raises: ItemAccessibilityException, RequestParameterMissingException """ params = util.Params( payload ) name = util.restore_text( params.get( 'name', None ) ) if not name: raise exceptions.RequestParameterMissingException( "Missing required parameter 'name'." ) description = util.restore_text( params.get( 'description', '' ) ) synopsis = util.restore_text( params.get( 'synopsis', '' ) ) if synopsis in [ 'None', None ]: synopsis = '' library = self.library_manager.create( trans, name, description, synopsis ) library_dict = self.library_manager.get_library_dict( trans, library ) return library_dict
def manage_user_info(self, trans, cntrller, **kwd): '''Manage a user's login, password, public username, type, addresses, etc.''' params = util.Params(kwd) user_id = params.get('id', None) if user_id: user = trans.sa_session.query(trans.app.model.User).get( trans.security.decode_id(user_id)) else: user = trans.user if not user: raise AssertionError("The user id (%s) is not valid" % str(user_id)) email = util.restore_text(params.get('email', user.email)) username = util.restore_text(params.get('username', '')) if not username: username = user.username message = escape(util.restore_text(params.get('message', ''))) status = params.get('status', 'done') return trans.fill_template('/webapps/tool_shed/user/manage_info.mako', cntrller=cntrller, user=user, email=email, username=username, message=message, status=status)
def parse_request_tup( self, request_tup, **kwd ): redirect_action = util.restore_text( kwd.get( 'redirect_action', '' ) ) titles = util.restore_text( kwd.get( 'titles', '' ) ) JobId = util.restore_text( kwd.get( 'JobId', '' ) ) sample_id = util.restore_text( kwd.get( 'sample_id', '' ) ) message = util.restore_text( kwd.get( 'message', '' ) ) status = kwd.get( 'status', 'done' ) url, http_method, request_params, response_type = request_tup url = unquote_plus( url ) # Handle URLs in which we replace param values, which will look something like: # http://127.0.0.1/getinfo/{id}. replace_with_param = url.find( '{' ) > 0 if replace_with_param: # Handle the special-case {JobId} param. if url.find( '{JobId}' ) > 0: if JobId: url = url.replace( '{JobId}', str( JobId ) ) for key, value in kwd.items(): # Don't attempt to replace if there is nothing with which to do it # or if the value itself should be replaced with something. if value and not value.startswith( '{' ): replace_str = '{%s}' % key if url.find( replace_str ) > 0: url = url.replace( replace_str, value ) # Handle request parameters in which we replace param values. for key, val in request_params.items(): if val and val.startswith( '{' ): replace_key = val.lstrip( '{' ).rstrip( '}' ) if replace_key in kwd: request_params[ key ] = kwd[ replace_key ] return url, http_method, request_params, response_type
def create( self, trans, payload, **kwd ): """ POST /api/libraries Creates a new library. """ if not trans.user_is_admin(): raise HTTPForbidden( detail='You are not authorized to create a new library.' ) params = util.Params( payload ) name = util.restore_text( params.get( 'name', None ) ) if not name: raise HTTPBadRequest( detail="Missing required parameter 'name'." ) description = util.restore_text( params.get( 'description', '' ) ) synopsis = util.restore_text( params.get( 'synopsis', '' ) ) if synopsis in [ 'None', None ]: synopsis = '' library = trans.app.model.Library( name=name, description=description, synopsis=synopsis ) root_folder = trans.app.model.LibraryFolder( name=name, description='' ) library.root_folder = root_folder trans.sa_session.add_all( ( library, root_folder ) ) trans.sa_session.flush() encoded_id = trans.security.encode_id( library.id ) rval = {} rval['url'] = url_for( 'library', id=encoded_id ) rval['name'] = name rval['id'] = encoded_id return rval
def __build_external_service_widgets( self, trans, external_service=None, **kwd ): params = util.Params( kwd ) if external_service: name = external_service.name description = external_service.description version = external_service.version seq_type = external_service.external_service_type_id else: name = util.restore_text( params.get( 'external_service_name', '' ) ) description = util.restore_text( params.get( 'external_service_description', '' ) ) version = util.restore_text( params.get( 'external_service_version', '' ) ) selected_seq_type = params.get( 'external_service_type_id', '' ) if selected_seq_type in trans.app.external_service_types.all_external_service_types: seq_type = trans.app.external_service_types.all_external_service_types[ selected_seq_type ].id else: seq_type = 'none' widgets = [ dict( label='Name', widget=TextField( 'external_service_name', 40, name ), helptext='' ), dict( label='Description', widget=TextField( 'external_service_description', 40, description ), helptext='' ), dict( label='Version', widget=TextField( 'external_service_version', 40, version ), helptext='' ) ] # Do not show the external_service_type selectfield when editing a external_service if not external_service: widgets.append( dict( label='External service type', widget=self.__build_external_service_type_select_field( trans, seq_type, visible_external_service_types_only=True ), helptext='') ) return widgets
def create(self, trans, payload, **kwd): """ create( self, trans, payload, **kwd ) * POST /api/libraries: Creates a new library. Only ``name`` parameter is required. .. note:: Currently, only admin users can create libraries. :param payload: dictionary structure containing:: 'name': the new library's name (required) 'description': the new library's description (optional) 'synopsis': the new library's synopsis (optional) :type payload: dict :returns: detailed library information :rtype: dict :raises: ItemAccessibilityException, RequestParameterMissingException """ params = util.Params(payload) name = util.restore_text(params.get('name', None)) if not name: raise exceptions.RequestParameterMissingException( "Missing required parameter 'name'.") description = util.restore_text(params.get('description', '')) synopsis = util.restore_text(params.get('synopsis', '')) if synopsis in ['None', None]: synopsis = '' library = self.library_manager.create(trans, name, description, synopsis) library_dict = self.library_manager.get_library_dict(trans, library) return library_dict
def get_params(self, kwargs): params = util.Params(kwargs) # set defaults if unset updates = dict(webapp=params.get('webapp', 'galaxy'), message=util.restore_text(params.get('message', '')), status=util.restore_text(params.get('status', 'done'))) params.update(updates) return params
def create( self, trans, payload, **kwd ): """ create( self, trans, payload, **kwd ) * POST /api/repositories: Creates a new repository. Only ``name`` and ``synopsis`` parameters are required. :param payload: dictionary structure containing:: 'name': new repo's name (required) 'synopsis': new repo's synopsis (required) 'description': new repo's description (optional) 'remote_repository_url': new repo's remote repo (optional) 'homepage_url': new repo's homepage url (optional) 'category_ids[]': list of existing encoded TS category ids the new repo should be associated with (optional) 'type': new repo's type, defaults to ``unrestricted`` (optional) :type payload: dict :returns: detailed repository information :rtype: dict :raises: RequestParameterMissingException """ params = util.Params( payload ) name = util.restore_text( params.get( 'name', None ) ) if not name: raise exceptions.RequestParameterMissingException( "Missing required parameter 'name'." ) synopsis = util.restore_text( params.get( 'synopsis', None ) ) if not synopsis: raise exceptions.RequestParameterMissingException( "Missing required parameter 'synopsis'." ) description = util.restore_text( params.get( 'description', '' ) ) remote_repository_url = util.restore_text( params.get( 'remote_repository_url', '' ) ) homepage_url = util.restore_text( params.get( 'homepage_url', '' ) ) category_ids = util.listify( params.get( 'category_ids[]', '' ) ) selected_categories = [ trans.security.decode_id( id ) for id in category_ids ] repo_type = kwd.get( 'type', rt_util.UNRESTRICTED ) if repo_type not in rt_util.types: raise exceptions.RequestParameterInvalidException( 'This repository type is not valid' ) invalid_message = repository_util.validate_repository_name( trans.app, name, trans.user ) if invalid_message: raise exceptions.RequestParameterInvalidException( invalid_message ) repo, message = repository_util.create_repository( app=trans.app, name=name, type=repo_type, description=synopsis, long_description=description, user_id = trans.user.id, category_ids=category_ids, remote_repository_url=remote_repository_url, homepage_url=homepage_url ) return repo.to_dict( view='element', value_mapper=self.__get_value_mapper( trans ) )
def __register(self, trans, email=None, username=None, password=None, subscribe_checked=False, **kwd): """Registers a new user.""" email = util.restore_text(email) username = util.restore_text(username) status = None message = None is_admin = trans.user_is_admin user = self.user_manager.create(email=email, username=username, password=password) if subscribe_checked: # subscribe user to email list if trans.app.config.smtp_server is None: status = "error" message = "Now logged in as " + user.email + ". However, subscribing to the mailing list has failed because mail is not configured for this Galaxy instance. <br>Please contact your local Galaxy administrator." else: body = 'Join Mailing list.\n' to = trans.app.config.mailing_join_addr frm = email subject = 'Join Mailing List' try: util.send_mail(frm, to, subject, body, trans.app.config) except Exception: log.exception( 'Subscribing to the mailing list has failed.') status = "warning" message = "Now logged in as " + user.email + ". However, subscribing to the mailing list has failed." if status != "error": if not is_admin: # The handle_user_login() method has a call to the history_set_default_permissions() method # (needed when logging in with a history), user needs to have default permissions set before logging in trans.handle_user_login(user) trans.log_event("User created a new account") trans.log_event("User logged in") if trans.app.config.user_activation_on: is_activation_sent = self.user_manager.send_activation_email( trans, email, username) if is_activation_sent: message = 'Now logged in as %s.<br>Verification email has been sent to your email address. Please verify it by clicking the activation link in the email.<br>Please check your spam/trash folder in case you cannot find the message.<br><a target="_top" href="%s">Return to the home page.</a>' % ( escape(user.email), url_for('/')) else: status = "error" message = 'Unable to send activation email, please contact your local Galaxy administrator.' if trans.app.config.error_email_to is not None: message += ' Contact: %s' % trans.app.config.error_email_to else: # User activation is OFF, proceed without sending the activation email. message = 'Now logged in as %s.<br><a target="_top" href="%s">Return to the home page.</a>' % ( escape(user.email), url_for('/')) return message, status, user, status is None
def create_role(self, trans, **kwd): params = util.Params(kwd) message = util.restore_text(params.get('message', '')) status = params.get('status', 'done') name = util.restore_text(params.get('name', '')) description = util.restore_text(params.get('description', '')) in_users = util.listify(params.get('in_users', [])) out_users = util.listify(params.get('out_users', [])) in_groups = util.listify(params.get('in_groups', [])) out_groups = util.listify(params.get('out_groups', [])) create_group_for_role = params.get('create_group_for_role', '') create_group_for_role_checked = CheckboxField.is_checked(create_group_for_role) ok = True if params.get('create_role_button', False): if not name or not description: message = "Enter a valid name and a description." status = 'error' ok = False elif trans.sa_session.query(trans.app.model.Role).filter(trans.app.model.Role.table.c.name == name).first(): message = "Role names must be unique and a role with that name already exists, so choose another name." status = 'error' ok = False else: # Create the role role, num_in_groups = trans.app.security_agent.create_role( name, description, in_users, in_groups, create_group_for_role=create_group_for_role_checked) message = "Role '%s' has been created with %d associated users and %d associated groups. " \ % (role.name, len(in_users), num_in_groups) if create_group_for_role_checked: message += 'One of the groups associated with this role is the newly created group with the same name.' trans.response.send_redirect(web.url_for(controller='admin', action='roles', message=util.sanitize_text(message), status='done')) if ok: for user in trans.sa_session.query(trans.app.model.User) \ .filter(trans.app.model.User.table.c.deleted == false()) \ .order_by(trans.app.model.User.table.c.email): out_users.append((user.id, user.email)) for group in trans.sa_session.query(trans.app.model.Group) \ .filter(trans.app.model.Group.table.c.deleted == false()) \ .order_by(trans.app.model.Group.table.c.name): out_groups.append((group.id, group.name)) return trans.fill_template('/webapps/tool_shed/admin/dataset_security/role/role_create.mako', name=name, description=description, in_users=in_users, out_users=out_users, in_groups=in_groups, out_groups=out_groups, create_group_for_role_checked=create_group_for_role_checked, message=message, status=status)
def rename_datasets( self, trans, **kwd ): # This method is called from the DataTransferGrid when a user is renaming 1 or more # SampleDatasets. params = util.Params( kwd ) message = util.restore_text( params.get( 'message', '' ) ) status = params.get( 'status', 'done' ) sample_id = kwd.get( 'sample_id', None ) try: sample = trans.sa_session.query( trans.model.Sample ).get( trans.security.decode_id( sample_id ) ) except: return invalid_id_redirect( trans, 'requests_admin', sample_id, 'sample' ) # id_list is list of SampleDataset ids, which is a subset of all # of the SampleDatasets associated with the Sample. The user may # or may not have selected all of the SampleDatasets for renaming. id_list = util.listify( kwd.get( 'id_list', [] ) ) # Get all of the SampleDatasets sample_datasets = [] for sample_dataset_id in id_list: sample_dataset = trans.sa_session.query( trans.app.model.SampleDataset ).get( trans.security.decode_id( sample_dataset_id ) ) sample_datasets.append( sample_dataset ) if params.get( 'rename_datasets_button', False ): incorrect_dataset_names = [] for sample_dataset in sample_datasets: encoded_id = trans.security.encode_id( sample_dataset.id ) selected_option = util.restore_text( params.get( 'rename_datasets_for_sample_%s' % encoded_id, '' ) ) new_name = util.restore_text( params.get( 'new_name_%s' % encoded_id, '' ) ) if not new_name: incorrect_dataset_names.append( sample_dataset.name ) continue new_name = util.sanitize_for_filename( new_name ) if selected_option == 'none': sample_dataset.name = new_name else: sample_dataset.name = '%s_%s' % ( selected_option, new_name ) trans.sa_session.add( sample_dataset ) trans.sa_session.flush() if len( sample_datasets ) == len( incorrect_dataset_names ): status = 'error' message = 'All datasets renamed incorrectly.' elif len( incorrect_dataset_names ): status = 'done' message = 'Changes saved successfully. The following datasets were renamed incorrectly: %s.' % str( incorrect_dataset_names ) else: message = 'Changes saved successfully.' return trans.fill_template( '/admin/requests/rename_datasets.mako', sample=sample, id_list=id_list, message=message, status=status ) return trans.response.send_redirect( web.url_for( controller='requests_admin', action='manage_datasets', sample_id=sample_id ) )
def get_quota_params(self, kwargs): params = self.get_params(kwargs) updates = dict(name=util.restore_text(params.get('name', '')), description=util.restore_text(params.get('description', '')), amount=util.restore_text(params.get('amount', '').strip()), operation=params.get('operation', ''), default=params.get('default', ''), in_users=util.listify(params.get('in_users', [])), out_users=util.listify(params.get('out_users', [])), in_groups=util.listify(params.get('in_groups', [])), out_groups=util.listify(params.get('out_groups', []))) params.update(updates) return params
def __validate_form( self, **kwd ): ''' This method checks the following text inputs are filled out by the user - the name of form - form type ''' params = util.Params( kwd ) # form name if not util.restore_text( params.name ): return None, 'Form name must be filled.' # form type if util.restore_text( params.form_type_select_field ) == 'none': return None, 'Form type must be selected.' return True, ''
def __get_populated_request_type_widgets(self, trans, **kwd): request_form_definitions = self.get_all_forms( trans, filter=dict(deleted=False), form_type=trans.model.FormDefinition.types.REQUEST) sample_form_definitions = self.get_all_forms( trans, filter=dict(deleted=False), form_type=trans.model.FormDefinition.types.SAMPLE) if not request_form_definitions or not sample_form_definitions: return [], [] params = util.Params(kwd) request_form_id = params.get('request_form_id', 'none') sample_form_id = params.get('sample_form_id', 'none') request_form_id_select_field = build_select_field( trans, objs=request_form_definitions, label_attr='name', select_field_name='request_form_id', selected_value=request_form_id, refresh_on_change=False) sample_form_id_select_field = build_select_field( trans, objs=sample_form_definitions, label_attr='name', select_field_name='sample_form_id', selected_value=sample_form_id, refresh_on_change=False) rt_info_widgets = [ dict(label='Name', widget=TextField('name', 40, util.restore_text(params.get('name', '')))), dict(label='Description', widget=TextField('desc', 40, util.restore_text(params.get('desc', '')))), dict(label='Request form', widget=request_form_id_select_field), dict(label='Sample form', widget=sample_form_id_select_field) ] # Unsaved sample states being defined for this request type rt_states = [] i = 0 while True: if 'state_name_%i' % i in kwd: rt_states.append( (util.restore_text(params.get('state_name_%i' % i, '')), util.restore_text(params.get('state_desc_%i' % i, '')))) i += 1 else: break return rt_info_widgets, rt_states
def create(self, trans, payload, **kwd): """ create( self, trans, payload, **kwd ) * POST /api/libraries: Creates a new library. Only ``name`` parameter is required. .. note:: Currently, only admin users can create libraries. :param payload: dictionary structure containing:: 'name': the new library's name (required) 'description': the new library's description (optional) 'synopsis': the new library's synopsis (optional) :type payload: dict :returns: detailed library information :rtype: dict :raises: ItemAccessibilityException, RequestParameterMissingException """ if not trans.user_is_admin(): raise exceptions.ItemAccessibilityException( 'Only administrators can create libraries.') params = util.Params(payload) name = util.restore_text(params.get('name', None)) if not name: raise exceptions.RequestParameterMissingException( "Missing required parameter 'name'.") description = util.restore_text(params.get('description', '')) synopsis = util.restore_text(params.get('synopsis', '')) if synopsis in ['None', None]: synopsis = '' library = trans.app.model.Library(name=name, description=description, synopsis=synopsis) root_folder = trans.app.model.LibraryFolder(name=name, description='') library.root_folder = root_folder trans.sa_session.add_all((library, root_folder)) trans.sa_session.flush() item = library.to_dict(view='element', value_mapper={ 'id': trans.security.encode_id, 'root_folder_id': trans.security.encode_id }) item['can_user_add'] = True item['can_user_modify'] = True item['can_user_manage'] = True if trans.app.security_agent.library_is_public(library, contents=False): item['public'] = True return item
def get_quota_params(self, kwargs): params = self.get_params(kwargs) updates = dict( name=util.restore_text(params.get('name', '')), description=util.restore_text(params.get('description', '')), amount=util.restore_text(params.get('amount', '').strip()), operation=params.get('operation', ''), default=params.get('default', ''), in_users=util.listify(params.get('in_users', [])), out_users=util.listify(params.get('out_users', [])), in_groups=util.listify(params.get('in_groups', [])), out_groups=util.listify(params.get('out_groups', []))) params.update(updates) return params
def edit_username(self, trans, cntrller, **kwd): params = util.Params(kwd) is_admin = cntrller == 'admin' and trans.user_is_admin() message = util.restore_text(params.get('message', '')) status = params.get('status', 'done') user_id = params.get('user_id', None) if user_id and is_admin: user = trans.sa_session.query(trans.app.model.User).get( trans.security.decode_id(user_id)) else: user = trans.user if user and params.get('change_username_button', False): username = kwd.get('username', '') if username: message = validate_publicname(trans, username, user) if message: status = 'error' else: user.username = username trans.sa_session.add(user) trans.sa_session.flush() message = 'The username has been updated with the changes.' return trans.fill_template('/webapps/tool_shed/user/username.mako', cntrller=cntrller, user=user, username=user.username, message=message, status=status)
def view_editable_request_type(self, trans, **kwd): params = util.Params(kwd) message = util.restore_text(params.get('message', '')) status = params.get('status', 'done') request_type_id = params.get('id', None) try: request_type = trans.sa_session.query(trans.model.RequestType).get( trans.security.decode_id(request_type_id)) except: return invalid_id_redirect(trans, 'request_type', request_type_id, 'request type', action='browse_request_types') # See if we have any associated templates widgets = request_type.get_template_widgets(trans) widget_fields_have_contents = self.widget_fields_have_contents(widgets) # get all the external services selected till now external_service_select_fields_list = [] for index, external_service in enumerate( request_type.external_services): external_service_select_field = self.__build_external_service_select_field( trans, 'external_service_id_%i' % index, external_service) external_service_select_fields_list.append( external_service_select_field) return trans.fill_template( '/admin/request_type/edit_request_type.mako', request_type=request_type, widgets=widgets, widget_fields_have_contents=widget_fields_have_contents, external_service_select_fields_list= external_service_select_fields_list, message=message, status=status)
def user_disk_usage(self, trans, **kwd): message = escape(util.restore_text(kwd.get("message", ""))) specs = sorter("disk_usage", kwd) sort_id = specs.sort_id order = specs.order arrow = specs.arrow if order == "desc": _order = True else: _order = False user_cutoff = int(kwd.get("user_cutoff", 60)) # disk_usage isn't indexed users = sorted( trans.sa_session.query(galaxy.model.User).all(), key=operator.attrgetter(str(sort_id)), reverse=_order ) if user_cutoff: users = users[:user_cutoff] return trans.fill_template( "/webapps/reports/users_user_disk_usage.mako", order=order, arrow=arrow, sort_id=sort_id, users=users, user_cutoff=user_cutoff, message=message, )
def handle_library_params(trans, params, folder_id, replace_dataset=None): # FIXME: the received params has already been parsed by util.Params() by the time it reaches here, # so no complex objects remain. This is not good because it does not allow for those objects to be # manipulated here. The received params should be the original kwd from the initial request. library_bunch = util.bunch.Bunch() library_bunch.replace_dataset = replace_dataset library_bunch.message = params.get('ldda_message', '') # See if we have any template field contents library_bunch.template_field_contents = {} template_id = params.get('template_id', None) library_bunch.folder = trans.sa_session.query( trans.app.model.LibraryFolder).get(trans.security.decode_id(folder_id)) # We are inheriting the folder's info_association, so we may have received inherited contents or we may have redirected # here after the user entered template contents ( due to errors ). if template_id not in [None, 'None']: library_bunch.template = trans.sa_session.query( trans.app.model.FormDefinition).get(template_id) for field in library_bunch.template.fields: field_name = field['name'] if params.get(field_name, False): field_value = util.restore_text(params.get(field_name, '')) library_bunch.template_field_contents[field_name] = field_value else: library_bunch.template = None library_bunch.roles = [] for role_id in util.listify(params.get('roles', [])): role = trans.sa_session.query(trans.app.model.Role).get(role_id) library_bunch.roles.append(role) return library_bunch
def specified_date(self, trans, **kwd): message = util.restore_text(kwd.get('message', '')) # If specified_date is not received, we'll default to the current month specified_date = kwd.get('specified_date', datetime.utcnow().strftime("%Y-%m-%d")) year, month, day = map(int, specified_date.split("-")) start_date = date(year, month, day) end_date = start_date + timedelta(days=1) day_of_month = start_date.strftime("%d") day_label = start_date.strftime("%A") month_label = start_date.strftime("%B") year_label = start_date.strftime("%Y") q = sa.select((sa.func.date_trunc( 'day', sa.func.date( galaxy.model.User.table.c.create_time)).label('date'), galaxy.model.User.table.c.email), whereclause=sa.and_( galaxy.model.User.table.c.create_time >= start_date, galaxy.model.User.table.c.create_time < end_date), from_obj=[galaxy.model.User.table], order_by=[galaxy.model.User.table.c.email]) users = [] for row in q.execute(): users.append((row.email)) return trans.fill_template( '/webapps/reports/registered_users_specified_date.mako', specified_date=start_date, day_label=day_label, month_label=month_label, year_label=year_label, day_of_month=day_of_month, users=users, message=message)
def request_type_permissions(self, trans, **kwd): params = util.Params(kwd) message = util.restore_text(params.get('message', '')) status = params.get('status', 'done') request_type_id = kwd.get('id', '') try: request_type = trans.sa_session.query(trans.model.RequestType).get(trans.security.decode_id(request_type_id)) except: return invalid_id_redirect(trans, 'request_type', request_type_id, 'request type', action='browse_request_types') roles = trans.sa_session.query(trans.model.Role) \ .filter(trans.model.Role.table.c.deleted == false()) \ .order_by(trans.model.Role.table.c.name) if params.get('update_roles_button', False): permissions = {} for k, v in trans.model.RequestType.permitted_actions.items(): in_roles = [trans.sa_session.query(trans.model.Role).get(x) for x in util.listify(params.get(k + '_in', []))] permissions[trans.app.security_agent.get_action(v.action)] = in_roles trans.app.security_agent.set_request_type_permissions(request_type, permissions) trans.sa_session.refresh(request_type) message = "Permissions updated for request type '%s'" % request_type.name return trans.fill_template('/admin/request_type/request_type_permissions.mako', request_type=request_type, roles=roles, status=status, message=message)
def user_disk_usage(self, trans, **kwd): message = escape(util.restore_text(kwd.get('message', ''))) specs = sorter('disk_usage', kwd) sort_id = specs.sort_id order = specs.order arrow = specs.arrow if order == "desc": _order = True else: _order = False user_cutoff = int(kwd.get('user_cutoff', 60)) # disk_usage isn't indexed users = sorted(trans.sa_session.query(galaxy.model.User).all(), key=operator.attrgetter(str(sort_id)), reverse=_order) if user_cutoff: users = users[:user_cutoff] return trans.fill_template( '/webapps/reports/users_user_disk_usage.mako', order=order, arrow=arrow, sort_id=sort_id, users=users, user_cutoff=user_cutoff, message=message)
def user_per_month(self, trans, **kwd): params = util.Params(kwd) message = '' specs = sorter('date', kwd) sort_id = specs.sort_id order = specs.order arrow = specs.arrow _order = specs.exc_order email = util.restore_text(params.get('email', '')) user_id = trans.security.decode_id(params.get('id', '')) q = sa.select( (self.select_month( model.StoredWorkflow.table.c.create_time).label('date'), sa.func.count( model.StoredWorkflow.table.c.id).label('total_workflows')), whereclause=model.StoredWorkflow.table.c.user_id == user_id, from_obj=[model.StoredWorkflow.table], group_by=self.group_by_month( model.StoredWorkflow.table.c.create_time), order_by=[_order]) all_workflows_user_month = sa.select( (self.select_day( model.StoredWorkflow.table.c.create_time).label('date'), model.StoredWorkflow.table.c.id), whereclause=model.StoredWorkflow.table.c.user_id == user_id, from_obj=[model.StoredWorkflow.table]) trends = dict() for workflow in all_workflows_user_month.execute(): workflow_day = int(workflow.date.strftime("%-d")) - 1 workflow_month = int(workflow.date.strftime("%-m")) workflow_month_name = workflow.date.strftime("%B") workflow_year = workflow.date.strftime("%Y") key = str(workflow_month_name + workflow_year) try: trends[key][workflow_day] += 1 except KeyError: workflow_year = int(workflow_year) wday, day_range = calendar.monthrange(workflow_year, workflow_month) trends[key] = [0] * day_range trends[key][workflow_day] += 1 workflows = [] for row in q.execute(): workflows.append( (row.date.strftime("%Y-%m"), row.total_workflows, row.date.strftime("%B"), row.date.strftime("%Y"))) return trans.fill_template( '/webapps/reports/workflows_user_per_month.mako', email=util.sanitize_text(email), order=order, arrow=arrow, sort_id=sort_id, trends=trends, workflows=workflows, message=message)
def user_per_month(self, trans, **kwd): params = util.Params(kwd) message = '' email = util.restore_text(params.get('email', '')) q = sa.select( (sa.func.date_trunc( 'month', sa.func.date( model.Job.table.c.create_time)).label('date'), sa.func.count(model.Job.table.c.id).label('total_jobs')), whereclause=sa.and_( model.Job.table.c.session_id == model.GalaxySession.table.c.id, model.GalaxySession.table.c.user_id == model.User.table.c.id, model.User.table.c.email == email), from_obj=[sa.join(model.Job.table, model.User.table)], group_by=[ sa.func.date_trunc('month', sa.func.date(model.Job.table.c.create_time)) ], order_by=[sa.desc('date')]) jobs = [] for row in q.execute(): jobs.append((row.date.strftime("%Y-%m"), row.total_jobs, row.date.strftime("%B"), row.date.strftime("%Y"))) return trans.fill_template('/webapps/reports/jobs_user_per_month.mako', email=util.sanitize_text(email), jobs=jobs, message=message)
def specified_date( self, trans, **kwd ): message = escape( util.restore_text( kwd.get( 'message', '' ) ) ) # If specified_date is not received, we'll default to the current month specified_date = kwd.get( 'specified_date', datetime.utcnow().strftime( "%Y-%m-%d" ) ) year, month, day = map( int, specified_date.split( "-" ) ) start_date = date( year, month, day ) end_date = start_date + timedelta( days=1 ) day_of_month = start_date.strftime( "%d" ) day_label = start_date.strftime( "%A" ) month_label = start_date.strftime( "%B" ) year_label = start_date.strftime( "%Y" ) q = sa.select( ( self.select_day( galaxy.model.User.table.c.create_time ).label( 'date' ), galaxy.model.User.table.c.email ), whereclause=sa.and_( galaxy.model.User.table.c.create_time >= start_date, galaxy.model.User.table.c.create_time < end_date ), from_obj=[ galaxy.model.User.table ], order_by=[ galaxy.model.User.table.c.email ] ) users = [] for row in q.execute(): users.append( ( row.email ) ) return trans.fill_template( '/webapps/reports/registered_users_specified_date.mako', specified_date=start_date, day_label=day_label, month_label=month_label, year_label=year_label, day_of_month=day_of_month, users=users, message=message )
def specified_month( self, trans, **kwd ): message = escape( util.restore_text( kwd.get( 'message', '' ) ) ) # If specified_date is not received, we'll default to the current month specified_date = kwd.get( 'specified_date', datetime.utcnow().strftime( "%Y-%m-%d" ) ) specified_month = specified_date[ :7 ] year, month = map( int, specified_month.split( "-" ) ) start_date = date( year, month, 1 ) end_date = start_date + timedelta( days=calendar.monthrange( year, month )[1] ) month_label = start_date.strftime( "%B" ) year_label = start_date.strftime( "%Y" ) q = sa.select( ( self.select_day( galaxy.model.User.table.c.create_time ).label( 'date' ), sa.func.count( galaxy.model.User.table.c.id ).label( 'num_users' ) ), whereclause=sa.and_( galaxy.model.User.table.c.create_time >= start_date, galaxy.model.User.table.c.create_time < end_date ), from_obj=[ galaxy.model.User.table ], group_by=self.group_by_day( galaxy.model.User.table.c.create_time ), order_by=[ sa.desc( 'date' ) ] ) users = [] for row in q.execute(): users.append( ( row.date.strftime( "%Y-%m-%d" ), row.date.strftime( "%d" ), row.num_users, row.date.strftime( "%A" ) ) ) return trans.fill_template( '/webapps/reports/registered_users_specified_month.mako', month_label=month_label, year_label=year_label, month=month, users=users, message=message )
def create( self, trans, payload, **kwd ): """ create( trans, payload ) * POST /api/histories: create a new history :type payload: dict :param payload: (optional) dictionary structure containing: * name: the new history's name * current: if passed, set the new history to be the user's 'current' history :rtype: dict :returns: element view of new history """ hist_name = None if payload.get( 'name', None ): hist_name = restore_text( payload['name'] ) new_history = trans.app.model.History( user=trans.user, name=hist_name ) trans.sa_session.add( new_history ) trans.sa_session.flush() #item = new_history.to_dict(view='element', value_mapper={'id':trans.security.encode_id}) item = self.get_history_dict( trans, new_history ) item['url'] = url_for( 'history', id=item['id'] ) #TODO: possibly default to True here - but favor explicit for now (and backwards compat) current = string_as_bool( payload[ 'current' ] ) if 'current' in payload else False if current: trans.history = new_history #TODO: copy own history #TODO: import an importable history #TODO: import from archive return item
def view_editable_request_type(self, trans, **kwd): params = util.Params(kwd) message = util.restore_text(params.get('message', '')) status = params.get('status', 'done') request_type_id = params.get('id', None) try: request_type = trans.sa_session.query(trans.model.RequestType).get(trans.security.decode_id(request_type_id)) except: return invalid_id_redirect(trans, 'request_type', request_type_id, 'request type', action='browse_request_types') # See if we have any associated templates widgets = request_type.get_template_widgets(trans) widget_fields_have_contents = self.widget_fields_have_contents(widgets) # get all the external services selected till now external_service_select_fields_list = [] for index, external_service in enumerate(request_type.external_services): external_service_select_field = self.__build_external_service_select_field(trans, 'external_service_id_%i' % index, external_service) external_service_select_fields_list.append(external_service_select_field) return trans.fill_template('/admin/request_type/edit_request_type.mako', request_type=request_type, widgets=widgets, widget_fields_have_contents=widget_fields_have_contents, external_service_select_fields_list=external_service_select_fields_list, message=message, status=status)
def edit_request_type(self, trans, **kwd): params = util.Params(kwd) message = util.restore_text(params.get('message', '')) status = params.get('status', 'done') request_type_id = params.get('id', None) try: request_type = trans.sa_session.query(trans.model.RequestType).get(trans.security.decode_id(request_type_id)) except: return invalid_id_redirect(trans, 'request_type', request_type_id, 'request type', action='browse_request_types') # See if we have any associated templates widgets = request_type.get_template_widgets(trans) widget_fields_have_contents = self.widget_fields_have_contents(widgets) # get all the external services selected till now external_service_select_fields_list = [] external_services_list = self.__get_external_services(trans, request_type, **kwd) if params.get('edit_request_type_button', False): request_type = self.__save_request_type(trans, action='edit_request_type', **kwd) message = 'Changes made to request type (%s) have been saved' % request_type.name elif params.get('add_external_service_button', False): external_services_list.append(None) elif params.get('remove_external_service_button', False): index = int(kwd['remove_external_service_button'].split(' ')[3]) - 1 del external_services_list[index] for index, external_service in enumerate(external_services_list): external_service_select_field = self.__build_external_service_select_field(trans, 'external_service_id_%i' % index, external_service) external_service_select_fields_list.append(external_service_select_field) return trans.fill_template('/admin/request_type/edit_request_type.mako', request_type=request_type, widgets=widgets, widget_fields_have_contents=widget_fields_have_contents, external_service_select_fields_list=external_service_select_fields_list, message=message, status=status)
def registered_users_per_month(self, trans, **kwd): message = escape(util.restore_text(kwd.get('message', ''))) specs = sorter('date', kwd) sort_id = specs.sort_id order = specs.order arrow = specs.arrow _order = specs.exc_order q = sa.select( (self.select_month( galaxy.model.User.table.c.create_time).label('date'), sa.func.count(galaxy.model.User.table.c.id).label('num_users')), from_obj=[galaxy.model.User.table], group_by=self.group_by_month( galaxy.model.User.table.c.create_time), order_by=[_order]) users = [] for row in q.execute(): users.append((row.date.strftime("%Y-%m"), row.num_users, row.date.strftime("%B"), row.date.strftime("%Y"))) return trans.fill_template( '/webapps/reports/registered_users_per_month.mako', order=order, arrow=arrow, sort_id=sort_id, users=users, message=message)
def last_access_date(self, trans, **kwd): message = util.restore_text(kwd.get('message', '')) not_logged_in_for_days = kwd.get('not_logged_in_for_days', 90) if not not_logged_in_for_days: not_logged_in_for_days = 0 cutoff_time = datetime.utcnow() - timedelta( days=int(not_logged_in_for_days)) now = strftime("%Y-%m-%d %H:%M:%S") users = [] for user in trans.sa_session.query( galaxy.model.User ) \ .filter( galaxy.model.User.table.c.deleted==False ) \ .order_by( galaxy.model.User.table.c.email ): if user.galaxy_sessions: last_galaxy_session = user.galaxy_sessions[0] if last_galaxy_session.update_time < cutoff_time: users.append( (user.email, last_galaxy_session.update_time.strftime("%Y-%m-%d"))) else: # The user has never logged in users.append((user.email, "never logged in")) users = sorted(users, key=operator.itemgetter(1), reverse=True) return trans.fill_template( '/webapps/reports/users_last_access_date.mako', users=users, not_logged_in_for_days=not_logged_in_for_days, message=message)
def specified_month(self, trans, **kwd): message = escape(util.restore_text(kwd.get('message', ''))) # If specified_date is not received, we'll default to the current month specified_date = kwd.get('specified_date', datetime.utcnow().strftime("%Y-%m-%d")) specified_month = specified_date[:7] year, month = map(int, specified_month.split("-")) start_date = date(year, month, 1) end_date = start_date + timedelta( days=calendar.monthrange(year, month)[1]) month_label = start_date.strftime("%B") year_label = start_date.strftime("%Y") q = sa.select( (self.select_day( galaxy.model.User.table.c.create_time).label('date'), sa.func.count(galaxy.model.User.table.c.id).label('num_users')), whereclause=sa.and_( galaxy.model.User.table.c.create_time >= start_date, galaxy.model.User.table.c.create_time < end_date), from_obj=[galaxy.model.User.table], group_by=self.group_by_day(galaxy.model.User.table.c.create_time), order_by=[sa.desc('date')]) users = [] for row in q.execute(): users.append( (row.date.strftime("%Y-%m-%d"), row.date.strftime("%d"), row.num_users, row.date.strftime("%A"))) return trans.fill_template( '/webapps/reports/registered_users_specified_month.mako', month_label=month_label, year_label=year_label, month=month, users=users, message=message)
def edit_username( self, trans, cntrller, **kwd ): params = util.Params( kwd ) is_admin = cntrller == 'admin' and trans.user_is_admin() message = util.restore_text( params.get( 'message', '' ) ) status = params.get( 'status', 'done' ) user_id = params.get( 'user_id', None ) if user_id and is_admin: user = trans.sa_session.query( trans.app.model.User ).get( trans.security.decode_id( user_id ) ) else: user = trans.user if user and params.get( 'change_username_button', False ): username = kwd.get( 'username', '' ) if username: message = validate_publicname( trans, username, user ) if message: status = 'error' else: user.username = username trans.sa_session.add( user ) trans.sa_session.flush() message = 'The username has been updated with the changes.' return trans.fill_template( '/webapps/tool_shed/user/username.mako', cntrller=cntrller, user=user, username=user.username, message=message, status=status )
def history_per_user(self, trans, **kwd): message = escape(util.restore_text(kwd.get('message', ''))) user_cutoff = int(kwd.get('user_cutoff', 60)) sorting = 0 if kwd.get('sorting', 'User') == 'User' else 1 descending = 1 if kwd.get('descending', 'desc') == 'desc' else -1 sorting_functions = [ lambda first, second: descending if first[0].lower() > second[0].lower() else -descending, lambda first, second: descending if first[1] < second[1] else -descending] req = sa.select( (sa.func.count(galaxy.model.History.table.c.id).label('history'), galaxy.model.User.table.c.username.label('username')), from_obj=[sa.outerjoin(galaxy.model.History.table, galaxy.model.User.table)], whereclause=galaxy.model.History.table.c.user_id == galaxy.model.User.table.c.id, group_by=['username'], order_by=[sa.desc('username'), 'history']) histories = [(_.username if _.username is not None else "Unknown", _.history) for _ in req.execute()] histories.sort(sorting_functions[sorting]) if user_cutoff != 0: histories = histories[:user_cutoff] return trans.fill_template('/webapps/reports/history_per_user.mako', histories=histories, user_cutoff=user_cutoff, sorting=sorting, descending=descending, message=message)
def user_per_month( self, trans, **kwd ): params = util.Params( kwd ) message = '' specs = sorter( 'date', kwd ) sort_id = specs.sort_id order = specs.order arrow = specs.arrow _order = specs.exc_order email = util.restore_text( params.get( 'email', '' ) ) user_id = trans.security.decode_id( params.get( 'id', '' ) ) q = sa.select( ( self.select_month( model.StoredWorkflow.table.c.create_time ).label( 'date' ), sa.func.count( model.StoredWorkflow.table.c.id ).label( 'total_workflows' ) ), whereclause=model.StoredWorkflow.table.c.user_id == user_id, from_obj=[ model.StoredWorkflow.table ], group_by=self.group_by_month( model.StoredWorkflow.table.c.create_time ), order_by=[ _order ] ) workflows = [] for row in q.execute(): workflows.append( ( row.date.strftime( "%Y-%m" ), row.total_workflows, row.date.strftime( "%B" ), row.date.strftime( "%Y" ) ) ) return trans.fill_template( '/webapps/reports/workflows_user_per_month.mako', email=util.sanitize_text( email ), order=order, arrow=arrow, sort_id=sort_id, workflows=workflows, message=message )
def registered_users_per_month(self, trans, **kwd): message = escape(util.restore_text(kwd.get('message', ''))) specs = sorter('date', kwd) sort_id = specs.sort_id order = specs.order arrow = specs.arrow _order = specs.exc_order q = sa.select((self.select_month(galaxy.model.User.table.c.create_time).label('date'), sa.func.count(galaxy.model.User.table.c.id).label('num_users')), from_obj=[galaxy.model.User.table], group_by=self.group_by_month(galaxy.model.User.table.c.create_time), order_by=[_order]) users = [] for row in q.execute(): users.append((row.date.strftime("%Y-%m"), row.num_users, row.date.strftime("%B"), row.date.strftime("%Y"))) return trans.fill_template('/webapps/reports/registered_users_per_month.mako', order=order, arrow=arrow, sort_id=sort_id, users=users, message=message)
def create(self, trans, payload, **kwd): """ create( trans, payload ) * POST /api/histories: create a new history :type payload: dict :param payload: (optional) dictionary structure containing: * name: the new history's name * current: if passed, set the new history to be the user's 'current' history * history_id: the id of the history to copy * archive_source: the url that will generate the archive to import * archive_type: 'url' (default) :rtype: dict :returns: element view of new history """ hist_name = None if payload.get('name', None): hist_name = restore_text(payload['name']) #TODO: possibly default to True here - but favor explicit for now (and backwards compat) set_as_current = string_as_bool( payload['current']) if 'current' in payload else False copy_this_history_id = payload.get('history_id', None) if "archive_source" in payload: archive_source = payload["archive_source"] archive_type = payload.get("archive_type", "url") self.queue_history_import(trans, archive_type=archive_type, archive_source=archive_source) return {} new_history = None # if a history id was passed, copy that history if copy_this_history_id: original_history = self.mgrs.histories.get( trans, self._decode_id(trans, copy_this_history_id), check_ownership=False, check_accessible=True) hist_name = hist_name or ("Copy of '%s'" % original_history.name) new_history = original_history.copy(name=hist_name, target_user=trans.user) # otherwise, create a new empty history else: new_history = trans.app.model.History(user=trans.user, name=hist_name) trans.sa_session.add(new_history) trans.sa_session.flush() if set_as_current: trans.history = new_history item = {} item = self.get_history_dict(trans, new_history) item['url'] = url_for('history', id=item['id']) return item
def handle_library_params(trans, params, folder_id, replace_dataset=None): # FIXME: the received params has already been parsed by util.Params() by the time it reaches here, # so no complex objects remain. This is not good because it does not allow for those objects to be # manipulated here. The received params should be the original kwd from the initial request. library_bunch = util.bunch.Bunch() library_bunch.replace_dataset = replace_dataset library_bunch.message = params.get('ldda_message', '') # See if we have any template field contents library_bunch.template_field_contents = {} template_id = params.get('template_id', None) library_bunch.folder = trans.sa_session.query(trans.app.model.LibraryFolder).get(trans.security.decode_id(folder_id)) # We are inheriting the folder's info_association, so we may have received inherited contents or we may have redirected # here after the user entered template contents ( due to errors ). if template_id not in [None, 'None']: library_bunch.template = trans.sa_session.query(trans.app.model.FormDefinition).get(template_id) for field in library_bunch.template.fields: field_name = field['name'] if params.get(field_name, False): field_value = util.restore_text(params.get(field_name, '')) library_bunch.template_field_contents[field_name] = field_value else: library_bunch.template = None library_bunch.roles = [] for role_id in util.listify(params.get('roles', [])): role = trans.sa_session.query(trans.app.model.Role).get(role_id) library_bunch.roles.append(role) return library_bunch
def user_per_month( self, trans, **kwd ): params = util.Params( kwd ) message = '' email = util.restore_text( params.get( 'email', '' ) ) specs = sorter( 'date', kwd ) sort_id = specs.sort_id order = specs.order arrow = specs.arrow _order = specs.exc_order q = sa.select( ( self.select_month( model.Job.table.c.create_time ).label( 'date' ), sa.func.count( model.Job.table.c.id ).label( 'total_jobs' ) ), whereclause=sa.and_( model.Job.table.c.session_id == model.GalaxySession.table.c.id, model.GalaxySession.table.c.user_id == model.User.table.c.id, model.User.table.c.email == email ), from_obj=[ sa.join( model.Job.table, model.User.table ) ], group_by=self.group_by_month( model.Job.table.c.create_time ), order_by=[ _order ] ) jobs = [] for row in q.execute(): jobs.append( ( row.date.strftime( "%Y-%m" ), row.total_jobs, row.date.strftime( "%B" ), row.date.strftime( "%Y" ) ) ) return trans.fill_template( '/webapps/reports/jobs_user_per_month.mako', order=order, arrow=arrow, sort_id=sort_id, id=kwd.get('id'), email=util.sanitize_text( email ), jobs=jobs, message=message )
def reject_request( self, trans, **kwd ): params = util.Params( kwd ) request_id = params.get( 'id', '' ) status = params.get( 'status', 'done' ) message = params.get( 'message', 'done' ) if params.get( 'cancel_reject_button', False ): return trans.response.send_redirect( web.url_for( controller='requests_common', action='view_request', cntrller='requests_admin', id=request_id ) ) try: request = trans.sa_session.query( trans.model.Request ).get( trans.security.decode_id( request_id ) ) except: return invalid_id_redirect( trans, 'requests_admin', request_id ) # Validate comment = util.restore_text( params.get( 'comment', '' ) ) if not comment: status='error' message='A reason for rejecting the request is required.' return trans.fill_template( '/admin/requests/reject.mako', cntrller='requests_admin', request=request, status=status, message=message ) # Create an event with state 'Rejected' for this request event_comment = "Sequencing request marked rejected by %s. Reason: %s " % ( trans.user.email, comment ) event = trans.model.RequestEvent( request, request.states.REJECTED, event_comment ) trans.sa_session.add( event ) trans.sa_session.flush() message='Sequencing request (%s) has been rejected.' % request.name return trans.response.send_redirect( web.url_for( controller='requests_admin', action='browse_requests', status=status, message=message, **kwd ) )