Esempio n. 1
0
def add_user(circle=None, circle_id=None, user=None, user_id=None):
    if user is None:
        user = DBSession.query(User).filter(User.id == user_id).first()
    if circle is None:
        circle = DBSession.query(Circle).filter(Circle.id == circle_id).first()
    circle.users.append(user)
    DBSession.flush()
Esempio n. 2
0
    def after_sha1(self, fname, sha1, force, callback_url, track_id, old_task_id, mail, key, sequence_id, extension, trackname):
        """
        Called after a sha1 where calculated on a file.
        If the sha1 already exist, only the databases operations are done.
        Else the input will go in the second part of the process.
        The input can be 'forced' to be recomputed
        """
        try:
            _input = DBSession.query(Input).filter(Input.sha1 == sha1).first()
            do_process = True
            if util.str2bool(force) and _input is not None:
                handler.track.delete_input(_input.sha1)
                DBSession.delete(_input)
                DBSession.flush()
            elif _input is not None:
                do_process = False
                handler.track.update(track_id=track_id,
                    params={'new_input_id': _input.id})
                handler.track.finalize_track_creation(track_id=track_id)

            if do_process:

                handler.track.update(track_id=track_id, params={'sha1': sha1})
                sequence = DBSession.query(Sequence).filter(Sequence.id == sequence_id).first()
                async = tasks.track_process.delay(mail, key, old_task_id, fname, sha1, callback_url, track_id, sequence.name, extension, trackname, callback_url)

                handler.track.update(track_id=track_id,
                    params={'new_task_id': async.task_id})
            return {'success': 'to second process'}
        except Exception as e:
            etype, value, tb = sys.exc_info()
            traceback.print_exception(etype, value, tb)


            return {'error': str(e)}
Esempio n. 3
0
def can_edit_job(user_id, job_id):
    user = DBSession.query(User).filter(User.id == user_id).first()
    if is_admin(user):
        j = DBSession.query(Job).filter(
            and_(Job.id == job_id, Job.user_id == user_id)).first()
        return j != None
    return True
Esempio n. 4
0
def change_rights(project_id, circle_id, rights=None):
    '''
    Modify the right associated to a project to a group.
    If any right is added, automatically add read right.
    @param project_id : the project id
    @param circle_id : the circle id
    @param rights : the right to update
    '''
    project = DBSession.query(Project).filter(Project.id == project_id).first()
    rc_assocs = get_circle_right_assocs(circle_id, project_id)

    for rc in rc_assocs:
        if rc.circle.id == int(circle_id):
            project._circle_right.remove(rc)
            DBSession.delete(rc)
            DBSession.flush()

    if rights is not None:
        _add_read_right(project, circle_id)
        for right_name in rights:
            if right_name != constants.right_read:
                right = DBSession.query(Right).filter(
                    Right.name == right_name).first()
                cr_assoc = _get_circle_right_assoc(right, circle_id,
                                                   project_id)
                project._circle_right.append(cr_assoc)

    DBSession.add(project)
    DBSession.flush()
Esempio n. 5
0
def change_rights(project_id, circle_id, rights=None):
    '''
    Modify the right associated to a project to a group.
    If any right is added, automatically add read right.
    @param project_id : the project id
    @param circle_id : the circle id
    @param rights : the right to update
    '''
    project = DBSession.query(Project).filter(Project.id == project_id).first()
    rc_assocs = get_circle_right_assocs(circle_id, project_id)
    
    
    for rc in rc_assocs:
        if rc.circle.id == int(circle_id) :
            project._circle_right.remove(rc)
            DBSession.delete(rc)
            DBSession.flush()

    if rights is not None:
        _add_read_right(project, circle_id)
        for right_name in rights:
            if right_name != constants.right_read :
                right = DBSession.query(Right).filter(Right.name == right_name).first()
                cr_assoc = _get_circle_right_assoc(right, circle_id, project_id)
                project._circle_right.append(cr_assoc)

    DBSession.add(project)
    DBSession.flush()
Esempio n. 6
0
    def edit(self, *args, **kw):
        user = handler.user.get_user_in_session(request)
        if request.method == 'GET':
            project_id = args[0]
        else:
            project_id = kw.get('pid')
        debug("check permission", 1)
        if not checker.check_permission(user=user, project_id=project_id, right_id=constants.right_upload_id) and not checker.is_admin(user=user):
            flash('You must have %s permission to edit the project.' % constants.right_upload, 'error')
            raise redirect('/tracks/', {'pid': project_id})
        #if checker.is_admin(user=user):
            #user = DBSession.query(User).join(Project).filter(Project.id == project_id).first()

        widget = form.EditProject(action=url('/projects/edit/%s' % project_id)).req()
        widget.value = {'pid': project_id}
        project = DBSession.query(Project).filter(Project.id == project_id).first()

        # prendre les user tracks du meme sequence id
        tracks = DBSession.query(Track).join(User.tracks).filter(
            and_(User.id == user.id, Track.sequence_id == project.sequence_id,
                not_(Track.id.in_([t.id for t in project.tracks])))
        ).all()

        # prendre les sared tracks du meme sequence id
        shared_tracks = handler.user.shared_tracks(user.id, constants.rights['download']['id'])
        shared_tracks = [t for t in shared_tracks if (t.sequence_id == project.sequence_id and t.id not in [tr.id for tr in project.tracks])]

        tracks.extend(shared_tracks)

        if request.method == 'GET':
            debug("GET", 2)
            widget.child.children[1].value = project.name
            widget.child.children[2].options = [('', '')] + [(t.id, t.name) for t in tracks] + [(t.id, t.name, {'selected': True}) for t in project.tracks]
            return dict(page='tracks', widget=widget, project_id=project_id)
        debug("POST", 2)
        try:
            debug("validate post", 2)
            widget.validate(kw)
        except twc.ValidationError as e:
            debug("error", 2)
            w = e.widget
            w.child.children[1].value = project.name
            w.child.children[2].options = [(t.id, t.name) for t in tracks] + [(t.id, t.name, {'selected': True}) for t in project.tracks]
            return dict(page='tracks', widget=w, project_id=project_id)
        debug("validation passed")
        track_ids = kw.get('tracks', [])
        if not track_ids:
            track_ids = []
        if not isinstance(track_ids, list):
            track_ids = [track_ids]
        if len(track_ids) > 0 and '' in track_ids:
            track_ids.remove('')

        # if the project is shared, some track cannot be removed
        for t in project.tracks:
            if not checker.user_own_track(user.id, track=t) and t.id not in track_ids and t.id in [s.id for s in shared_tracks]:
                track_ids.append(t.id)

        handler.project.e(project_id=project_id, name=kw.get('name'), track_ids=track_ids)
        raise redirect('/tracks/', {'pid': project_id})
Esempio n. 7
0
 def delete_user(self, user_id, sequence_id):
     user = handler.user.get_user_in_session(request)
     s = DBSession.query(Sequence).filter(Sequence.id == sequence_id).first()
     u = DBSession.query(User).filter(User.id == user_id).first()
     s.users.remove(u)
     DBSession.flush()
     raise redirect('/sequences/edit/%s' % sequence_id)
Esempio n. 8
0
 def delete_track(self, sequence_id, track_id):
     user = handler.user.get_user_in_session(request)
     s = DBSession.query(Sequence).filter(Sequence.id == sequence_id).first()
     t = DBSession.query(Track).filter(Track.id == track_id).first()
     s.default_tracks.remove(t)
     DBSession.flush()
     raise redirect('/sequences/edit/%s' % sequence_id)
Esempio n. 9
0
def e(project=None, project_id=None, name=None, track_ids=None, circle_ids=None):
    if project is None:
        project = DBSession.query(Project).filter(Project.id == project_id).first()

    if name is not None:
        project.name = name

    if track_ids is not None:
        project.tracks = []
        for tid in track_ids:
            t = DBSession.query(Track).filter(Track.id == tid).first()
            project.tracks.append(t)

    if circle_ids is not None:
        if not isinstance(circle_ids, list):
            circle_ids = [circle_ids]
        circle_ids = [int(i) for i in circle_ids]
        to_del = []
        for shared in project._circle_right:
            if shared.circle.id not in circle_ids:
                to_del.append(shared)
        for d in to_del:
            DBSession.delete(d)
            project._circle_right.remove(d)
        DBSession.flush()

        shared_ids = [c.id for c in project.shared_circles]
        read_right = DBSession.query(Right).filter(Right.id == constants.rights['read']['id']).first()
        for new_id in circle_ids:
            if new_id not in shared_ids:
                add_right(project=project, circle_id=new_id, right=read_right)
        DBSession.flush()
    DBSession.add(project)
    DBSession.flush()
    return project
Esempio n. 10
0
 def get(self, project_key=None, project_id=None, **kw):
     # get all user projects
     if not project_key and not project_id:
         user = handler.user.get_user_in_session(request)
         projects = DBSession.query(Project).filter(
             Project.user_id == user.id).all()
         return reply.normal(request,
                             'You can upload track on these projects',
                             '/tracks', {'projects': projects})
     project = None
     # get one specific user project
     if project_id is not None and project_id:
         user = handler.user.get_user_in_session(request)
         project = DBSession.query(Project).filter(
             Project.id == int(project_id)).first()
         if project is not None and not project.user_id == user.id:
             reply.error(request, 'Not your project', '/tracks', {})
         return reply.normal(request,
                             'You can upload track on this project',
                             '/tracks', {'project': project})
     # get a project by it's key
     project = DBSession.query(Project).filter(
         Project.key == project_key).first()
     if project is None:
         return reply.error(request, 'Wrong key', '/tracks', {})
     return reply.normal(request, 'You can upload track on this project',
                         '/tracks', {'project': project})
Esempio n. 11
0
 def validation(*args, **kw):
     for arg in args_list:
         if arg not in kw:
             raise Exception('Missing args for the validation %s' % kw)
     user = DBSession.query(User).filter(
         User.email == str(kw['mail'])).first()
     if user.key != str(kw['key']):
         raise Exception('User not valid %s' % kw)
     project = DBSession.query(Project).filter(
         Project.id == int(kw['pid'])).first()
     if project.key != str(kw['pkey']):
         raise Exception('Project not valid %s' % kw)
     job = Job()
     job.user_id = user.id
     job.project_id = project.id
     job.status = 'PENDING'
     job.ext_task_id = kw['task_id']
     job.bioscript_url = handler.job.task_url(kw['task_id'])
     if 'plugin_info' in kw:
         info = json.loads(kw['plugin_info'])
         job.name = info['title']
         job.description = info['description']
     else:
         job.name = 'Job %s from bioscript' % kw['task_id']
         job.description = 'Description available at %s' % handler.job.task_url(
             kw['task_id'])
     DBSession.add(job)
     DBSession.flush()
     return {}
Esempio n. 12
0
File: plugin.py Progetto: bbcf/pygdv
 def validation(*args, **kw):
     for arg in args_list:
         if arg not in kw:
             raise Exception('Missing args for the validation %s' % kw)
     user = DBSession.query(User).filter(User.email == str(kw['mail'])).first()
     if user.key != str(kw['key']):
         raise Exception('User not valid %s' % kw)
     project = DBSession.query(Project).filter(Project.id == int(kw['pid'])).first()
     if project.key != str(kw['pkey']):
         raise Exception('Project not valid %s' % kw)
     job = Job()
     job.user_id = user.id
     job.project_id = project.id
     job.status = 'PENDING'
     job.ext_task_id = kw['task_id']
     job.bioscript_url = handler.job.task_url(kw['task_id'])
     if 'plugin_info' in kw:
         info = json.loads(kw['plugin_info'])
         job.name = info['title']
         job.description = info['description']
     else:
         job.name = 'Job %s from bioscript' % kw['task_id']
         job.description = 'Description available at %s' % handler.job.task_url(kw['task_id'])
     DBSession.add(job)
     DBSession.flush()
     return {}
Esempio n. 13
0
    def admin(self, **kw):
        # view on a specific project
        grid = datagrid.track_admin_grid
        if kw.has_key('pid'):
            project_id = kw.get('pid')
            project = DBSession.query(Project).filter(Project.id == project_id).first()
            tracks = project.tracks
            kw['upload'] = True

            kw['pn'] = project.name
            track_list = [util.to_datagrid(grid, tracks, "Track Listing", len(tracks)>0)]

        else:
            if 'user_id' in kw:
                tracks = DBSession.query(Track).filter(Track.user_id == kw['user_id']).all()
            else:
                tracks = DBSession.query(Track).all()
            track_list = [util.to_datagrid(grid, tracks, "Track Listing", len(tracks)>0)]
            kw['upload'] = True

        # track list

        t = handler.help.tooltip['admin']

        # project list
        all_projects = DBSession.query(Project).all()
        project_list = [(p.id, p.name,) for p in all_projects]


        return dict(page='tracks', model='track', form_title="new track", track_list=track_list,
            project_list=project_list, shared_project_list=[], value=kw,
            tooltip=t, project_id=kw.get('pid', None), upload=kw.get('upload', None), project_name=kw.get('pn', None))
Esempio n. 14
0
 def delete_track(self, sequence_id, track_id):
     user = handler.user.get_user_in_session(request)
     s = DBSession.query(Sequence).filter(
         Sequence.id == sequence_id).first()
     t = DBSession.query(Track).filter(Track.id == track_id).first()
     s.default_tracks.remove(t)
     DBSession.flush()
     raise redirect('/sequences/edit/%s' % sequence_id)
Esempio n. 15
0
 def delete_user(self, user_id, sequence_id):
     user = handler.user.get_user_in_session(request)
     s = DBSession.query(Sequence).filter(
         Sequence.id == sequence_id).first()
     u = DBSession.query(User).filter(User.id == user_id).first()
     s.users.remove(u)
     DBSession.flush()
     raise redirect('/sequences/edit/%s' % sequence_id)
Esempio n. 16
0
    def edit(self, *args, **kw):
        user = handler.user.get_user_in_session(request)

        # get circle id
        if request.method == 'GET':
            sequence_id = args[0]
        else :
            sequence_id = kw.get('cid')

        sequence_id=int(sequence_id)
        sequence = DBSession.query(Sequence).filter(Sequence.id == sequence_id).first()
        if not sequence:
            abort(404, 'Sequence with id %s not found' % sequence_id)

        if not sequence.public:
            add_user_widget = form.AddUser(action=url('/sequences/edit/%s' % sequence_id)).req()

            if request.method == 'POST':
                # add an user
                mail = kw.get('mail')
                try:
                    add_user_widget.validate({'cid' : sequence_id, 'mail' : mail})
                except twc.ValidationError as e:
                    users = ', '.join(['%s' % u.email for u in sequence.users])
                    default_tracks = ', '.join(['%s' % t.name for t in sequence.default_tracks])
                    kw['cid'] = sequence_id
                    users = sequence.users
                    for u in users:
                        u.__dict__['sid'] = sequence_id
                    widget = e.widget
                    widget.value = kw
                    return dict(page='sequences', users=users, add_user=add_user, add_user_widget=add_user_widget, default_tracks=default_tracks, au_error=True, seq_id=sequence_id)

                to_add = DBSession.query(User).filter(User.email == mail).first()
                if to_add is None:
                    to_add = handler.user.create_tmp_user(mail)
                sequence.users.append(to_add)
                DBSession.flush()

            kw['cid'] = sequence_id
            add_user_widget.value = kw

        else:
            add_user_widget = None

        users = sequence.users
        for u in users:
            u.__dict__['sid'] = sequence_id

        tracks = sequence.default_tracks
        for t in tracks:
            t.__dict__['sid'] = sequence_id

        add_user = util.to_datagrid(datagrid.sequence_user_grid, users, "Users", len(users)>0)

        def_tracks = util.to_datagrid(datagrid.sequence_default_tracks, tracks, "Default tracks", len(tracks)>0)

        return dict(page='sequences', users=users, add_user=add_user, add_user_widget=add_user_widget, default_tracks=def_tracks, au_error=False, seq_id=sequence_id)
Esempio n. 17
0
def get_permissions(admin):
    '''
    Get the right permissions for an user.
    @param admin : True if the user is an admin.
    @type admin : a boolean.
    '''
    if admin :
        return DBSession.query(Permission).all()
    return DBSession.query(Permission).filter(Permission.name != 'admin').all()
Esempio n. 18
0
def get_permissions(admin):
    '''
    Get the right permissions for an user.
    @param admin : True if the user is an admin.
    @type admin : a boolean.
    '''
    if admin:
        return DBSession.query(Permission).all()
    return DBSession.query(Permission).filter(Permission.name != 'admin').all()
Esempio n. 19
0
 def delete_user(self, id, user_id):
     user = handler.user.get_user_in_session(request)
     if not checker.user_own_circle(user.id, id):
         flash('you have no rights to delete users from this circle: you are not the creator of it')
         raise redirect('/circles')
     circle = DBSession.query(Circle).filter(Circle.id == id).first()
     to_delete = DBSession.query(User).filter(User.id == user_id).first()
     circle.users.remove(to_delete)
     DBSession.flush()
     raise redirect('/circles/edit/%s' % id)
Esempio n. 20
0
def add_right(project=None, project_id=None, circle=None, circle_id=None, right=None, right_id=None):
    if project is None:
        project = DBSession.query(Project).filter(Project.id == project_id).first()
    if circle_id is None:
        circle_id = circle.id
    if right is None:
        right = DBSession.query(Right).filter(Right.id == right_id).first()

    cr_assoc = _get_circle_right_assoc(right, circle_id, project.id)
    project._circle_right.append(cr_assoc)
Esempio n. 21
0
    def index(self, came_from='/'):
        '''
        Redirect user on tequila page in order to log him
        '''
        if tg.config.get('authentication.disable').lower() in ['t', 'true']:
            print constants.admin_user_email()

            environ = request.environ
            authentication_plugins = environ['repoze.who.plugins']
            identifier = authentication_plugins['ticket']
            secret = identifier.secret
            cookiename = identifier.cookie_name
            remote_addr = environ['REMOTE_ADDR']
            user = DBSession.query(User).filter(
                User.email == constants.admin_user_email()).first()
            admins = tg.config.get('admin.mails')
            group_admins = DBSession.query(Group).filter(
                Group.id == constants.group_admins_id).first()
            if user.email in admins:
                user not in group_admins.users and group_admins.users.append(
                    user)
            else:
                user in group_admins.users and group_admins.users.remove(user)
            DBSession.flush()
            userdata = "%s|%s" % (user.id, user in group_admins.users)

            ticket = auth_tkt.AuthTicket(secret,
                                         user.email,
                                         remote_addr,
                                         tokens=token,
                                         user_data=userdata,
                                         time=None,
                                         cookie_name=cookiename,
                                         secure=True)

            val = ticket.cookie_value()
            # set it in the cookies
            response.set_cookie(cookiename,
                                value=val,
                                max_age=None,
                                path='/',
                                domain=None,
                                secure=False,
                                httponly=False,
                                comment=None,
                                expires=None,
                                overwrite=False)
            raise redirect(came_from)

        u = resolve_relative_url(url(), request.environ)
        res = tequila.create_request(u + '/login/auth', 'tequila.epfl.ch')
        raise redirect(
            'https://tequila.epfl.ch/cgi-bin/tequila/requestauth?request' +
            res)
Esempio n. 22
0
def user_own_circle(user_id, circle_id):
    '''
    Look if the user own the circle.
    '''
    circle = DBSession.query(Circle).filter(Circle.id == circle_id).first()
    if circle.creator_id == user_id:
        return True
    if circle.admin:
        user = DBSession.query(User).filter(User.id == user_id).first()
        admin_group = DBSession.query(Group).filter(Group.name == constants.group_admins).first()
        return user in admin_group.users
    return False
Esempio n. 23
0
    def save(self, project_id, color, description, locations):
        user = handler.user.get_user_in_session(request)

        if not checker.check_permission(user=user,
                                        project_id=project_id,
                                        right_id=constants.right_upload_id):
            flash(
                'You must have %s permission to delete the project.' %
                constants.right_upload, 'error')
            return {'save': 'failed'}

        #print "save %s, color %s, desc %s loc %s" % (project_id, color, description, locations)
        ''' For the moment, there is only one selection per project'''
        sel = DBSession.query(Selection).filter(
            Selection.project_id == project_id).first()
        if sel is None:
            sel = Selection()
            sel.project_id = project_id

        sel.description = description
        sel.color = color
        DBSession.add(sel)
        DBSession.flush()

        locations_ids = []
        # add locations
        for loc in json.loads(locations):
            obj = None
            if 'id' in loc:
                obj = DBSession.query(Location).join(
                    Selection.locations).filter(
                        and_(Selection.id == sel.id,
                             Location.id == loc.get('id'))).first()

            if obj is None:
                obj = Location()

            obj.chromosome = loc.get('chr')
            obj.start = loc.get('start')
            obj.end = loc.get('end')
            obj.description = loc.get('desc', 'No description')
            obj.selection = sel
            DBSession.add(obj)
            DBSession.flush()
            locations_ids.append(obj.id)
        # remove not saved ones
        loc_to_remove = DBSession.query(Location).filter(
            not_(Location.id.in_(locations_ids))).all()
        for l in loc_to_remove:
            DBSession.delete(l)
        DBSession.flush()
        return {"saved": "ok"}
Esempio n. 24
0
def user_own_circle(user_id, circle_id):
    '''
    Look if the user own the circle.
    '''
    circle = DBSession.query(Circle).filter(Circle.id == circle_id).first()
    if circle.creator_id == user_id:
        return True
    if circle.admin:
        user = DBSession.query(User).filter(User.id == user_id).first()
        admin_group = DBSession.query(Group).filter(
            Group.name == constants.group_admins).first()
        return user in admin_group.users
    return False
Esempio n. 25
0
 def link(self, track_id, *args, **kw):
     user = handler.user.get_user_in_session(request)
     trac = DBSession.query(Track).filter(Track.id == track_id).first()
     if not checker.can_download(user, trac):
         flash("You haven't the right to download any tracks which is not yours", 'error')
         raise redirect('/tracks/')
     track = DBSession.query(Track).filter(Track.id == track_id).first()
     if track.status == constants.ERROR:
         flash("The track processing failed. You cannot download it.", 'error')
         raise redirect('/tracks/')
     response.content_type = 'application/x-sqlite3'
     response.headerlist.append(('Content-Disposition', 'attachment;filename=%s.sqlite' % track.name))
     return open(track.path).read()
Esempio n. 26
0
def get_rights(project=None, project_id=None, user=None, user_id=None):
    if project is None:
        project = DBSession.query(Project).filter(Project.id == project_id).first()
    if user is None:
        user = DBSession.query(User).filter(User.id == user_id).first()

    debug('get rights %s' % project.get_circle_with_right_display)
    r = []
    for circle, rights in project.circles_with_rights.iteritems():
        debug('circle %s with rights %s' % (circle, rights), 1)

        if circle in user.circles:
            r.extend(rights)
    return r
Esempio n. 27
0
    def edit(self, *args, **kw):
        user = handler.user.get_user_in_session(request)

        t = handler.help.tooltip['circledesc']

        # get circle id
        if request.method == 'GET':
            circle_id = args[0]
        else:
            circle_id = kw.get('cid')
        circle_id = int(circle_id)

        if circle_id not in [c.id for c in user.circles_owned]:
            flash('You have no right to edit this circle', 'error')
            raise redirect('/circles/')
        circle = DBSession.query(Circle).filter(Circle.id == circle_id).first()
        widget = form.AddUser(action=url('/circles/edit/%s' % circle_id)).req()

        if request.method == 'POST':
            # add user
            mail = kw.get('mail')
            try:
                widget.validate({'cid': circle_id, 'mail': mail})
            except twc.ValidationError as e:
                for u in circle.users:
                    u.__dict__['cid'] = circle_id
                wrappers = [u for u in circle.users if u.id != user.id]
                data = [util.to_datagrid(datagrid.circle_description_grid, wrappers, grid_display=len(wrappers) > 0)]
                return dict(page='circles', name=circle.name, widget=e.widget, items=data, value=kw, tooltip=t, au_error=True)
            mail = mail.lower()
            to_add = DBSession.query(User).filter(User.email == mail).first()
            if to_add is None:
                to_add = handler.user.create_tmp_user(mail)
            handler.circle.add_user(circle_id=circle_id, user=to_add)

        # build common parameters
        if not checker.user_own_circle(user.id, circle_id):
            flash('you have no right to edit this circle: you are not the creator of it')
            raise redirect('/circles')

        for u in circle.users:
            u.__dict__['cid'] = circle_id
        wrappers = [u for u in circle.users if u.id != user.id]

        data = [util.to_datagrid(datagrid.circle_description_grid, wrappers, grid_display=len(wrappers) > 0)]

        kw['cid'] = circle_id
        widget.value = kw
        return dict(page='circles', name=circle.name, widget=widget, items=data, tooltip=t)
Esempio n. 28
0
File: plugin.py Progetto: bbcf/pygdv
    def callback(self, *args, **kw):
        print kw
        job = DBSession.query(Job).filter(Job.ext_task_id == kw['task_id']).first()
        project = DBSession.query(Project).filter(Project.id == int(kw['pid'])).first()
        if project is None or project.key != str(kw['pkey']):
            raise Exception('Project not valid')
        if job.project_id != project.id:
            raise Exception('Job not valid')

        status = str(kw['status'])
        job.status = status
        if status.lower() in ['error', 'failed']:
            job.traceback = kw['error']
        elif status == 'SUCCESS':
            results = json.loads(kw['results'])
            for result in results:
                bres = Bresults()
                bres.job_id = job.id
                bres.output_type = str(result.get('type', 'not defined'))
                bres.is_file = result.get('is_file', False)
                path = str(result.get('path', ''))
                bres.path = path
                bres.data = str(result.get('value', ''))

                is_track = result.get('type', '') == 'track'
                if is_track:
                    out = os.path.join(filemanager.temporary_directory(), os.path.split(path)[-1])
                    fileinfo = filemanager.FileInfo(inputtype='fsys', inpath=path, outpath=out, admin=False)
                    sequence = project.sequence
                    user = DBSession.query(User).filter(User.key == str(kw['key'])).first()
                    if user.email != str(kw['mail']):
                        raise Exception("Wrong user")
                    user_info = {'id': user.id, 'name': user.name, 'email': user.email}
                    sequence_info = {'id': sequence.id, 'name': sequence.name}

                    t = Track()
                    t.name = fileinfo.trackname
                    t.sequence_id = sequence.id
                    t.user_id = user.id
                    DBSession.add(t)
                    DBSession.flush()
                    async = tasks.new_input.delay(user_info, fileinfo, sequence_info, t.id, project.id)
                    t.task_id = async.task_id
                    bres.track_id = t.id

                bres.is_track = is_track
                DBSession.add(bres)
        DBSession.flush()
        return {}
Esempio n. 29
0
def get_rights(project=None, project_id=None, user=None, user_id=None):
    if project is None:
        project = DBSession.query(Project).filter(
            Project.id == project_id).first()
    if user is None:
        user = DBSession.query(User).filter(User.id == user_id).first()

    debug('get rights %s' % project.get_circle_with_right_display)
    r = []
    for circle, rights in project.circles_with_rights.iteritems():
        debug('circle %s with rights %s' % (circle, rights), 1)

        if circle in user.circles:
            r.extend(rights)
    return r
Esempio n. 30
0
def get_tequila_circle(name):
    '''
    Get the Circle created by Tequila with the specified name
    @param name : the name
    '''
    return DBSession.query(Circle).filter(
        and_(Circle.admin == True, Circle.name == name)).first()
Esempio n. 31
0
def edit(project, name, user_id, sequence_id=None, tracks=None, isPublic=False, circles=None):
    '''
    Like create but edit an existing project.
    '''
    project.name=name
    if sequence_id is not None:
        project.sequence_id = sequence_id
    project.user_id = user_id
    project.is_public = isPublic
    DBSession.add(project)
    DBSession.flush()

    project.tracks = []
    if tracks is not None:
        for track_id in tracks :
            t = DBSession.query(Track).filter(Track.id == track_id).first()
            project.tracks.append(t)
    
   
    if circles is not None: # adding circle with the read permission by default
        project._circle_right = []
        for circle in circles : _add_read_right(project, circle.id)
    
    DBSession.add(project)
    DBSession.flush()
    return project
Esempio n. 32
0
File: user.py Progetto: bbcf/pygdv
def get_user(key, mail):
    '''
    Get the user with the the given mail,
    with the given key.
    '''
    user = DBSession.query(User).filter(and_(User.email == mail, User.key == key)).first()
    return user
Esempio n. 33
0
    def edit(self, track_id, **kw):
        user = handler.user.get_user_in_session(request)
        if track_id is not None:
            if not checker.can_edit_track(user, track_id):
                flash("You haven't the right to edit any tracks which is not yours", 'error')
                raise redirect('/tracks')

        widget = form.EditTrack(action=url('/tracks/edit/%s' % track_id)).req()

        track = DBSession.query(Track).filter(Track.id == track_id).first()

        d = {}
        d['name'] = track.name
        if track.parameters is None or not 'color' in track.parameters:
            cc = constants.default_track_color
        else:
            cc = track.parameters['color']
        d['track_id'] = track_id
        d['color'] = cc
        if 'pid' in kw:
            d['pid'] = kw['pid']
        widget.value = d
        if request.method == 'GET':
            return dict(title='Edit track', page='track', widget=widget, color=cc)

        if request.method == 'POST':
            try:
                widget.validate(kw)
            except twc.ValidationError as e:
                return dict(title='Edit track', page='track', widget=e.widget, color=cc)
        handler.track.edit(track=track, name=kw.get('name', None), color=kw.get('color', None))
        raise redirect('/tracks', {'pid': kw.get('pid', None)})
Esempio n. 34
0
File: plugin.py Progetto: bbcf/pygdv
    def get(self, *args, **kw):
        bsurl = handler.job.bioscript_url
        bsrequesturl = bsurl + '/plugins/fetch?oid=' + kw['oid']
        user = handler.user.get_user_in_session(request)
        project = DBSession.query(Project).filter(Project.id == kw['pid']).first()
        # add private parameters
        pp = {"key": user.key, "mail": user.email, "pid": project.id, "pkey": project.key}
        # add prefill parameters
        tracks = list(project.tracks)
        selections = list(project.selections)
        gtrack = [(json.dumps({'p':handler.track.plugin_link(t), 'n':os.path.split(handler.track.plugin_link(t))[-1]}), t.name) for t in tracks]
        if len(selections) > 0:
            s = selections[0]
            if len(s.locations) > 0:
                gtrack.append((handler.track.plugin_link(s, selection_id=s.id), 'selection'))

        prefill = {'track': gtrack}

        # prepare parameters
        parameters = {
            'key': handler.job.shared_key,
            'bs_private': json.dumps({
                'app': pp,
                'cfg': handler.job.bioscript_config,
                'prefill': prefill
                })
        }
        # TODO fetch tracks & selections
        req = urllib2.urlopen(url=bsrequesturl, data=urllib.urlencode(parameters))
        # display the form in template
        response.headerlist.append(('Access-Control-Allow-Origin', '*'))
        data = req.read()
        return data
Esempio n. 35
0
    def search(self, project_id, term, *args, **kw):
        project = DBSession.query(Project).filter(Project.id == project_id).first()
        sequence = project.sequence
        default = sequence.default_tracks
        if default is None or len(default) < 1:
            return {}
        t = default[0]
        chrs = {}
        with track.load(t.path, 'sql', readonly=True) as t:
            gene_name_alias = t.find_column_name(['name', 'gene_name', 'gene name', 'gname', 'Name', 'product'])
            try:
                for row in t.search({gene_name_alias: term}, [gene_name_alias, 'start', 'end']):
                    chr, name, start, stop = row
                    if chr not in chrs:
                        chrs[chr] = {}

                    names = chrs[chr]
                    if name in names:
                        old = names[name]
                        start = min(old[0], start)
                        stop = max(old[1], stop)
                    names[name] = [start, stop]
            except Exception:
                return {}

        #result[chr].append([name, start, stop])
        result = {}
        for chr, names in chrs.iteritems():
            result[chr] = []
            for k, v in names.iteritems():
                result[chr].append([k, v[0], v[1]])

        return result
Esempio n. 36
0
def add_right(project=None,
              project_id=None,
              circle=None,
              circle_id=None,
              right=None,
              right_id=None):
    if project is None:
        project = DBSession.query(Project).filter(
            Project.id == project_id).first()
    if circle_id is None:
        circle_id = circle.id
    if right is None:
        right = DBSession.query(Right).filter(Right.id == right_id).first()

    cr_assoc = _get_circle_right_assoc(right, circle_id, project.id)
    project._circle_right.append(cr_assoc)
Esempio n. 37
0
def edit(project,
         name,
         user_id,
         sequence_id=None,
         tracks=None,
         isPublic=False,
         circles=None):
    '''
    Like create but edit an existing project.
    '''
    project.name = name
    if sequence_id is not None:
        project.sequence_id = sequence_id
    project.user_id = user_id
    project.is_public = isPublic
    DBSession.add(project)
    DBSession.flush()

    project.tracks = []
    if tracks is not None:
        for track_id in tracks:
            t = DBSession.query(Track).filter(Track.id == track_id).first()
            project.tracks.append(t)

    if circles is not None:  # adding circle with the read permission by default
        project._circle_right = []
        for circle in circles:
            _add_read_right(project, circle.id)

    DBSession.add(project)
    DBSession.flush()
    return project
Esempio n. 38
0
def _add_read_right(project, circle_id):    
    '''
    Add the ``read`` right to the project % circle specified without flushing
    '''
    read_right = DBSession.query(Right).filter(Right.name == constants.right_read).first()
    cr_assoc = _get_circle_right_assoc(read_right, circle_id, project.id)
    project._circle_right.append(cr_assoc)
Esempio n. 39
0
File: worker.py Progetto: bbcf/pygdv
 def new_selection(self, project_id, s, job_name, job_description, *args, **kw):
     '''
     Called by the browser. Transform a selection to a new track;
     '''
     user = handler.user.get_user_in_session(request)
     sels = json.loads(s)
     
     project = DBSession.query(Project).filter(Project.id == project_id).first()
     if project is None :
         return {'error' : "project id %s doesn't exist" % project_id}
     path = track.common.temporary_path()
     
     with track.new(path, 'sql') as t:
         t.fields = simple_fields
         for chromosome in sels:
             t.write(chromosome, ((marquee['start'], marquee['end'], 0, '', 0 , '') for marquee in sels[chromosome]))
         t.datatype = constants.FEATURES
         t.assembly = project.sequence.name
         
     task_id, track_id = handler.track.create_track(user.id, project.sequence, f=path, trackname='%s %s' 
                                      % (job_name, job_description), project=project)
     if task_id  == constants.NOT_SUPPORTED_DATATYPE :
         return {'error' : "not supported datatype" % project_id}
     
     job_id = handler.job.new_sel(user.id, project.id, job_description, job_name, task_id=task_id)
     return {'job_id' : job_id,
             'job_name' : job_name,
             'job_description' : job_description,
             'status' : 'RUNNING'}
Esempio n. 40
0
def remove_sharing(project=None, project_id=None):
    if project is None:
        project = DBSession.query(Project).filter(
            Project.id == project_id).first()
    for rc in project._circle_right:
        DBSession.delete(rc)
    DBSession.flush()
Esempio n. 41
0
def add_new_sequence(sequence):
    '''
    Method called when a new sequence is created on GDV.
    It should import fast from JBrowse
    '''
    print 'add new sequence'
    file_url = Assembly(sequence).get_sqlite_url()
    print file_url
    out = os.path.join(filemanager.temporary_directory(), 'Genes.sql')
    fileinfo = filemanager.FileInfo(inputtype='url',
        inpath=file_url, trackname='Genes', extension='sql', outpath=out, admin=True)
    print fileinfo
    user = DBSession.query(User).filter(User.key == constants.admin_user_key()).first()
    user_info = {'id': user.id, 'name': user.name, 'email': user.email}
    sequence_info = {'id': sequence.id, 'name': sequence.name}

    # track
    t = Track()
    t.name = fileinfo.trackname
    t.sequence_id = sequence.id
    t.user_id = user.id
    DBSession.add(t)
    DBSession.flush()
    # send task
    async = tasks.new_input.delay(user_info, fileinfo, sequence_info, t.id)
    t.task_id = async.task_id
    DBSession.add(t)

    sequence.default_tracks.append(t)
    DBSession.add(sequence)
    DBSession.flush()
Esempio n. 42
0
def delete(project=None, project_id=None):
    if project is None:
        project = DBSession.query(Project).filter(
            Project.id == project_id).first()
    remove_sharing(project=project)
    DBSession.delete(project)
    DBSession.flush()
Esempio n. 43
0
 def get(self, selection_id):
     sel = DBSession.query(Selection).filter(
         Selection.id == selection_id).first()
     b = ''
     for loc in sel.locations:
         b += '%s\t%s\t%s' % (loc.chromosome, loc.start, loc.end)
     return b
Esempio n. 44
0
def get_user(key, mail):
    '''
    Get the user with the the given mail,
    with the given key.
    '''
    user = DBSession.query(User).filter(
        and_(User.email == mail, User.key == key)).first()
    return user
Esempio n. 45
0
def get_circle_right_assocs(circle_id, project_id):
    '''
    Get the ``RightCircleAssociation`` corresponding
    to the circle_id & project_id given
    '''
    return DBSession.query(RightCircleAssociation).filter(
        and_(RightCircleAssociation.circle_id == circle_id,
             RightCircleAssociation.project_id == project_id)).all()
Esempio n. 46
0
def _add_read_right(project, circle_id):
    '''
    Add the ``read`` right to the project % circle specified without flushing
    '''
    read_right = DBSession.query(Right).filter(
        Right.name == constants.right_read).first()
    cr_assoc = _get_circle_right_assoc(read_right, circle_id, project.id)
    project._circle_right.append(cr_assoc)
Esempio n. 47
0
File: job.py Progetto: bbcf/pygdv
 def delete(self, _id):
     user = handler.user.get_user_in_session(request)
     if not checker.can_edit_job(user.id, _id):
         return {'error': "You have don't have the right to delete this job"}
     job = DBSession.query(Job).filter(Job.id == _id).first()
     # TODO delete results (DB + filesystem)
     DBSession.delete(job)
     raise redirect('/jobs')
Esempio n. 48
0
def get_circle_right_assocs(circle_id, project_id):
    '''
    Get the ``RightCircleAssociation`` corresponding
    to the circle_id & project_id given
    '''
    return DBSession.query(RightCircleAssociation).filter(
                        and_(RightCircleAssociation.circle_id == circle_id,
                            RightCircleAssociation.project_id == project_id)).all()
Esempio n. 49
0
File: worker.py Progetto: bbcf/pygdv
 def status(self, job_id, *args, **kw):
     try :
         job_id = int(job_id)
         job = DBSession.query(Job).filter(Job.id == job_id).first()
         return {'job_id' : job.id, 'status' : job.status, 'output' : job.output, 'error' : job.traceback}
     except ValueError:
         pass
     return {}
Esempio n. 50
0
def add_tracks(project, track_ids):
    '''
    Add a list of track to the project specified.
    '''
    for track_id in track_ids:
        track_ = DBSession.query(Track).filter(Track.id == track_id).first()
        project.tracks.append(track_)
    DBSession.add(project)
    DBSession.flush()
Esempio n. 51
0
def copy(user_id, project_id):
    project = DBSession.query(Project).filter(Project.id == project_id).first()
    ts = []
    for to_copy in project.tracks:
        ts.append(track.copy_track(user_id, to_copy))
    create('copied ' + project.name,
           project.sequence_id,
           user_id,
           tracks=[t.id for t in ts])
Esempio n. 52
0
def add_tracks(project, track_ids):
    '''
    Add a list of track to the project specified.
    '''
    for track_id in track_ids:
        track_ = DBSession.query(Track).filter(Track.id == track_id).first()
        project.tracks.append(track_)
    DBSession.add(project)
    DBSession.flush()
Esempio n. 53
0
 def copy(self, track_id):
     user = handler.user.get_user_in_session(request)
     if not checker.can_download_track(user.id, track_id):
         return reply.error(request, 'You have no right to copy this track in your profile.', './', {})
     t = DBSession.query(Track).filter(Track.id == track_id).first()
     if not t:
         return reply.error(request, 'No track with this id.', './', {})
     handler.track.copy_track(user.id, t)
     return reply.normal(request, 'Copy successfull', './', {})
Esempio n. 54
0
 def new(self, *args, **kw):
     new_form = form.NewProject(action=url('/projects/create')).req()
     species = DBSession.query(Species).all()
     sp_opts = [(sp.id, sp.name) for sp in species]
     new_form.child.children[2].options = sp_opts
     mapping = json.dumps(dict([(sp.id, [(seq.id, seq.name) for seq in sp.sequences
                                 if seq.public or handler.genrep.checkright(seq, user)]) for sp in species]))
     new_form.value = {'smapping': mapping}
     return dict(page='projects', widget=new_form)