def add_deadline(context, request): logged_in = authenticated_userid(request) main = get_renderer('../templates/master.pt').implementation() schema = DeadlineSchema() deadlineform = Form(schema, buttons=('submit',),use_ajax=True) if 'dateDue' in request.params: try: controls = request.POST.items() captured = deadlineform.validate(controls) except deform.ValidationFailure, e: deadlineform = e.render() return {'red':'', 'main':main, 'form':deadlineform, 'content':'', 'logged_in':logged_in, 'name':'Add Deadline'} dateDue = calendarstuff.datetime_from_str(request.params['dateDue']) hours = request.params['hours'] sponsored = request.params['sponsored'] appliedClass = request.params['appliedClass'] context.count += 1 deadline = Deadline(dateDue,hours,sponsored,appliedClass,context.count) deadline.__parent__ = context context[str(context.count)] = deadline find_root(context)['activityLogs'].deadline_creation(find_root(request.context)["users"][logged_in],deadline,request.application_url) return {'red':'deadlines/', 'main':main, 'form':'', 'content':"Added a Deadline", 'logged_in':logged_in, 'name':'Redirecting...'}
def add_sponsored_event(context,request): logged_in = authenticated_userid(request) user = find_root(request.context)['users'][logged_in] main = get_renderer('../templates/master.pt').implementation() projectList = find_root(context)["settings"].projects projectTupleList = [] for project in projectList: projectTupleList.append((project,project)) projectTupleTuple=tuple(projectTupleList) #sorry about this. It was more fun than a ListList class SponsoredEventSchema(colander.MappingSchema): completionDate = colander.SchemaNode(colander.Date(),title="Completion Date (YYYY-MM-DD): ") hours = colander.SchemaNode(colander.Float(), title="Number of Hours: ") description = colander.SchemaNode( colander.String(), validator=colander.OneOf([x[0] for x in projectTupleTuple]), widget=deform.widget.RadioChoiceWidget(values=projectTupleTuple), title='Project', description='Select a Project') taskDescription = colander.SchemaNode( colander.String(), title="Description: ", widget=deform.widget.TextAreaWidget(rows=5, cols=40), description='Enter some text') contact = colander.SchemaNode(colander.String(),title="Contact Name: ") contactInfo = colander.SchemaNode(colander.String(),title="Contact Info: ") schema=SponsoredEventSchema() eventform = Form(schema, buttons=('submit',)) if 'taskDescription' in request.params: try: controls = request.POST.items() captured = eventform.validate(controls) except deform.ValidationFailure, e: eventform = e.render() return {'red':'', 'main':main, 'form':eventform, 'content':'', 'logged_in':logged_in, 'name':'Add Sponsored Event', 'TutText': getTutText(user, view='')} completionDate = calendarstuff.datetime_from_str(request.params['completionDate']) hours = request.params['hours'] description = request.params['deformField3'] taskDescription = request.params['taskDescription'] contact = request.params['contact'] contactInfo = request.params['contactInfo'] context.eventcount += 1 user = context.user event = Event("Sponsored","N/A",completionDate,hours,description,taskDescription,contact,contactInfo,user,context.eventcount) event.__parent__ = context context[str(context.eventcount)] = event activitylog = find_root(context)['activityLogs'] activitylog.event_creation(find_root(request.context)["users"][logged_in],event,request.application_url) return {'red':'serviceLogs/'+context.user.username, 'main':main, 'form':'', 'content':"Added sponsored event for "+description, 'logged_in':logged_in, 'name':'Redirecting...', 'TutText': getTutText(user, view='')}
def add_user(context, request): logged_in = authenticated_userid(request) main = get_renderer('../templates/master.pt').implementation() schema = UserSchema() userform = Form(schema, buttons=('submit',),use_ajax=True) if 'username' in request.params: try: controls = request.POST.items() captured = userform.validate(controls) except deform.ValidationFailure, e: userform = e.render() return {'red':'', 'main':main, 'form':userform, 'content':'', 'logged_in':logged_in, 'name':'Add User', 'TutText': getTutText(context, view='')} username = request.params['username'] if username in context: return {'red':'', 'logged_in':logged_in, 'main':main, 'form':'', 'content':'Sorry, the username '+username+' already exists in this system. Please try again, or contact an administrator.', 'name':'Users', 'TutText': getTutText(context, view='')} password = hashlib.sha1(request.params["confirm"].encode('UTF-8')).digest() studentId = request.params['studentId'] firstName = request.params['firstName'] lastName = request.params['lastName'] email = request.params['email'] phone = request.params['phone'] gradYear = request.params['gradYear'] inductionYear = request.params['inductionYear'] user = User(username, password, studentId, firstName = firstName, lastName = lastName, email = email, phone = phone, gradYear = gradYear, inductionYear = inductionYear) user.__parent__ = context context[username] = user serviceLog = ServiceLog(user) serviceLog.__parent__ = find_root(user)['serviceLogs'] find_root(user)['serviceLogs'][username]=serviceLog user.serviceLog = ServiceLog find_root(context)['activityLogs'].user_creation(find_root(request.context)["users"][logged_in],user,request.application_url) return {'red':'users/', 'main':main, 'form':'', 'content':'The user '+firstName+' '+lastName+' was added to the system, with a username of '+username, 'logged_in':logged_in, 'name':'Redirecting...', 'TutText': getTutText(context, view='')}
def csvimport(context,request): logged_in = authenticated_userid(request) main = get_renderer('../templates/master.pt').implementation() schema = TextFieldSchema() importform = Form(schema, buttons=('submit',)) if 'submit' in request.params: inputstring = str(request.params["text"]) inputstring = inputstring.replace("\r","") inputstring = inputstring.replace(", ",",") lines = inputstring.split("\n") inputlist = [] for line in lines: if not line == "": ul = line.split(",") user = User( ul[2], #username hashlib.sha1(ul[8].encode('UTF-8')).digest(), #password, encoded ul[3], #studentID firstName = ul[1], lastName = ul[0], email = ul[4], phone = ul[5], gradYear = ul[6], inductionYear = ul[7] ) username = ul[2] if username in context: return {'red':'', 'logged_in':logged_in, 'main':main, 'form':exportform.render(), 'content':"ERROR: the username "+username+" already exists in this system. Please reassess your input data.", 'name':'Import From CSV', 'TutText': getTutText(context, view='')} user.__parent__ = context context[username] = user serviceLog = ServiceLog(user) serviceLog.__parent__ = find_root(user)['serviceLogs'] find_root(user)['serviceLogs'][username]=serviceLog user.serviceLog = ServiceLog find_root(context)['activityLogs'].user_creation(find_root(request.context)["users"][logged_in],user,request.application_url) return {'red':'users/', 'main':main, 'logged_in':logged_in, 'form':'', 'content':'Imported Users from CSV', 'name':'Redirecting...', 'TutText': getTutText(context, view='')} return {'red':'', 'main':main, 'logged_in':logged_in, 'form':importform.render(), 'content':'', 'name':'Import From CSV', 'TutText': getTutText(context, view='')}
def view_servicelog(context,request): logged_in = authenticated_userid(request) currentuser = find_root(request.context)["users"][logged_in] main = get_renderer('../templates/master.pt').implementation() app = find_root(request.context) if currentuser.isOfficer: if "action" in request.params: for ID in request.params.keys(): if not ID in ['action','comment','note']: event = context[ID] if request.params["action"] == "delete": if event.verified == "Verified": event.user.hours -= float(event.hours) if event.eventType == "Sponsored": event.user.sponsored -= float(event.hours) app['activityLogs'].event_deactivation(currentuser,event,request.application_url) del event.__parent__[str(event.ID)] elif request.params["action"] == "verify": if not event.verified == "Verified": event.user.hours += float(event.hours) if event.eventType == "Sponsored": event.user.sponsored += float(event.hours) event.verified = "Verified" app['activityLogs'].event_verification(currentuser,event,request.application_url) elif request.params["action"] == "flag": if event.verified == "Verified": event.user.hours -= float(event.hours) if event.eventType == "Sponsored": event.user.sponsored -= float(event.hours) event.verified = "Flagged" find_root(context)['activityLogs'].event_flagging(currentuser,event,request.application_url) elif request.params["action"] == "unverify": if event.verified == "Verified": event.user.hours -= float(event.hours) if event.eventType == "Sponsored": event.user.sponsored -= float(event.hours) event.verified = "Unverified" find_root(context)['activityLogs'].event_unverification(currentuser,event,request.application_url) if request.params["comment"]: if event.comment: event.comment += " "+request.params['comment'] else: event.comment = request.params['comment'] permission=True red='' if not logged_in == context.user.username: if not find_root(context)['users'][logged_in].isAdvisor and not find_root(context)['users'][logged_in].isOfficer: permission=False red = 'serviceLogs' userclass = calendarstuff.class_from_year(context.user.gradYear) deadlines = find_root(context)["deadlines"] now = datetime.now() return {'red':red, 'main':main, 'content':context, 'logged_in':logged_in, 'name':'Service Logs', 'isallowed':permission, 'deadlines':deadlines}
def add_independent_event(context, request): logged_in = authenticated_userid(request) main = get_renderer("../templates/master.pt").implementation() schema = IndependentEventSchema() eventform = Form(schema, buttons=("submit",)) if "description" in request.params: try: controls = request.POST.items() captured = eventform.validate(controls) except deform.ValidationFailure, e: eventform = e.render() return { "red": "", "main": main, "form": eventform, "content": "", "logged_in": logged_in, "name": "Add Independent Event", } completionDate = calendarstuff.datetime_from_str(request.params["completionDate"]) hours = request.params["hours"] description = request.params["description"] taskDescription = request.params["taskDescription"] contact = request.params["contact"] contactInfo = request.params["contactInfo"] affects = request.params["affects"] context.eventcount += 1 user = context.user event = Event( "Independent", completionDate, hours, description, taskDescription, contact, contactInfo, user, context.eventcount, affects=affects, ) event.__parent__ = context context[str(context.eventcount)] = event activitylog = find_root(context)["activityLogs"] activitylog.event_creation(find_root(request.context)["users"][logged_in], event, request.application_url) return { "red": "serviceLogs/" + context.user.username, "main": main, "form": "", "content": "Added independent event for " + description, "logged_in": logged_in, "name": "Redirecting...", }
def add_entry(context, request): if 'submit' in request.params: session = DBSession() title = request.params['title'] text = request.params['text'] entry = Entry(title, text) session.add(entry) return HTTPFound(location=request.resource_url(find_root(context))) add_url = request.resource_url(find_root(context), 'add') return {'mode': 'Add', 'title':'', 'text':'', 'add_url':add_url}
def hoursimport(context,request): logged_in = authenticated_userid(request) main = get_renderer('../templates/master.pt').implementation() schema = TextFieldSchema() importform = Form(schema, buttons=('submit',)) if 'submit' in request.params: inputstring = str(request.params["text"]) inputstring = inputstring.replace("\r","") inputstring = inputstring.replace(", ",",") lines = inputstring.split("\n") inputlist = [] for line in lines: if not line == "": rl = line.split(",") for value in rl[1:]: try: value = float(value) except ValueError: return {'red':'', 'logged_in':logged_in, 'main':main, 'form':exportform.render(), 'content':"ERROR: Input data was not a number, and could not be processed. Please reassess your input data.", 'name':'Import Hours From CSV', 'TutText': getTutText(context, view='')} username = rl[0] if not username in context: return {'red':'', 'logged_in':logged_in, 'main':main, 'form':exportform.render(), 'content':"ERROR: the username "+username+" does not exist in this system. Please reassess your input data.", 'name':'Import Hours From CSV', 'TutText': getTutText(context, view='')} context[username].hours = rl[1] context[username].sponsored = rl[2] find_root(context)['activityLogs'].user_edit(context[logged_in],context[username],request.application_url) return {'red':'users/', 'main':main, 'logged_in':logged_in, 'form':'', 'content':'Imported Hours from CSV', 'name':'Redirecting...', 'TutText': getTutText(context, view='')} return {'red':'', 'main':main, 'logged_in':logged_in, 'form':importform.render(), 'content':'', 'name':'Import Hours From CSV', 'TutText': getTutText(context, view='')}
def requirementsimport(context,request): logged_in = authenticated_userid(request) main = get_renderer('../templates/master.pt').implementation() schema = TextFieldSchema() importform = Form(schema, buttons=('submit',)) if 'submit' in request.params: inputstring = str(request.params["text"]) inputstring = inputstring.replace("\r","") inputstring = inputstring.replace(", ",",") lines = inputstring.split("\n") inputlist = [] for line in lines: if not line == "": rl = line.split(",") for value in rl[1:]: if value in ['Yes', 'YES', 'yes', 'Y', 'y']: value = True elif value in ['No', 'NO', 'no', 'N', 'n']: value = False if type(value) != type(True): return {'red':'', 'logged_in':logged_in, 'main':main, 'form':exportform.render(), 'content':"ERROR: Input data was not either 'yes' or 'no', and could not be processed. Please reassess your input data.", 'name':'Import Requirements From CSV', 'TutText': getTutText(context, view='')} username = rl[0] if not username in context: return {'red':'','logged_in':logged_in,'main':main,'form':exportform.render(), 'content':"ERROR: the username "+username+" does not exist in this system. Please reassess your input data.",'name':'Import Requirements From CSV'} context[username].dues = rl[1] context[username].gpa = rl[2] context[username].firstMeeting = rl[3] context[username].secondMeeting = rl[4] context[username].thirdMeeting = rl[5] find_root(context)['activityLogs'].user_edit(context[logged_in],context[username],request.application_url) return {'red':'users/', 'main':main, 'logged_in':logged_in, 'form':'', 'content':'Imported Information from CSV', 'name':'Redirecting...', 'TutText': getTutText(context, view='')} return {'red':'', 'main':main, 'logged_in':logged_in, 'form':importform.render(), 'content':'', 'name':'Import Requirements From CSV', 'TutText': getTutText(context, view='')}
def add_independent_event(context,request): logged_in = authenticated_userid(request) user = find_root(request.context)['users'][logged_in] main = get_renderer('../templates/master.pt').implementation() schema = IndependentEventSchema() eventform = Form(schema, buttons=('submit',)) if 'description' in request.params: try: controls = request.POST.items() captured = eventform.validate(controls) except deform.ValidationFailure, e: eventform = e.render() return {'red':'', 'main':main, 'form':eventform, 'content':'', 'logged_in':logged_in, 'name':'Add Independent Event', 'TutText': getTutText(user, view='')} completionDate = calendarstuff.datetime_from_str(request.params['completionDate']) hours = request.params['hours'] description = request.params['description'] taskDescription = request.params['taskDescription'] contact = request.params['contact'] contactInfo = request.params['contactInfo'] affects = request.params['affects'] type = request.params['type'] context.eventcount += 1 user = context.user event = Event("Independent", type, completionDate, hours, description, taskDescription, contact,contactInfo, user, context.eventcount, affects=affects) event.__parent__ = context context[str(context.eventcount)]=event activitylog=find_root(context)['activityLogs'] activitylog.event_creation(find_root(request.context)["users"][logged_in],event,request.application_url) return {'red':'serviceLogs/'+context.user.username, 'main':main, 'form':'', 'content':"Added independent event for "+description, 'logged_in':logged_in, 'name':'Redirecting...', 'TutText': getTutText(user, view='')}
def discussion_redirect_to_agenda_item(context, request): root = find_root(context) ai = find_interface(context, IAgendaItem) if ai: path = resource_path(ai) query = dict(path = path, content_type='DiscussionPost', sort_index='created', reverse=True, limit=5, #FIXME: this should be globaly configurable? ) docids = root.catalog.search(**query)[1] # set to True if requested post is after the display limit after_limit = False get_metadata = root.catalog.document_map.get_metadata for docid in docids: brain = get_metadata(docid) if brain['uid'] == context.uid: after_limit = True break # post was not found among the displayed posts query = request.GET if not after_limit: query['discussions'] = 'all' url = request.resource_url(ai, query=query, anchor=context.uid) else: url = request.resource_url(ai, query=query, anchor=context.uid) return HTTPFound(location=url) raise NotFound("Couldn't locate Agenda Item from this context.")
def test_event_no_aliases(self): from pyramid.traversal import find_root aliases, mlist = self._makeMailinglist() del find_root(mlist).list_aliases self.failIf(aliases) self._callFUT(mlist, None) self.assertEqual(aliases.items(), [])
def get_vote_schema(self, request = None, api = None): """ Get an instance of the schema that this poll uses. """ root = find_root(self.context) get_metadata = root.catalog.document_map.get_metadata num, results = root.catalog.query(Any('uid', self.context.proposal_uids), sort_index = 'created') proposals = [get_metadata(x) for x in results] #Choices should be something iterable with the contents [(UID for proposal, Title of proposal), <etc...>, ] poll_wf_state = self.context.get_workflow_state() if poll_wf_state == 'ongoing': poll_title = _(u"Vote") else: poll_title = _(u"You can't change your vote now.") schema = colander.Schema(title = poll_title) choices = (('approve', _(u"Approve")), ('deny', _(u"Deny")), ('abstain', _(u"Abstain"))) for proposal in proposals: schema.add(colander.SchemaNode(colander.String(), name = proposal['uid'], missing = u"", title = proposal['title'], validator = colander.OneOf([x[0] for x in choices]), widget = CombinedSimpleWidget(values = choices, proposal = proposal, api = api,))) return schema
def __init__(self, ref, parent): Resource.__init__(self, ref, parent) self.parent = parent root = find_root(self) self.request = root.request self.session = root.request.dbsession self.__actions__ = {}
def mark_content_as_read(context, request): """ This view should be called via javascript. Its not ment to return anything, but rather to make sure the writes when you mark something as read is performed in a separate request. That way it should be a lot less likely for them to fail, and even if they do fail it shouldn't have any effect on the current view. (Other than the fact that they will still be unread) Also, any retry will have to do very little rather than running the full request again. """ userid = authenticated_userid(request) if not userid: #Simply ignore the call, don't raise any exception return {'error': 'unauthorized'} root = find_root(context) catalog = root.catalog i = 0 names = request.params.getall(u'unread[]') for name in names: i += 1 obj = context.get(name, None) if not obj: continue unread = request.registry.queryAdapter(obj, IUnread) if not unread: continue unread.mark_as_read(userid) return {'marked_read': i}
def groupfinder(name, request): """ This method is called on each request to determine which principals a user has. Principals are groups, roles, userid and perhaps Authenticated or similar. This method also calls itself to fetch any local roles for groups. """ if name is None: # Abort for unauthenticated - no reason to use CPU return () result = set() context = request.environ.get("authz_context", getattr(request, "context", None)) if not context: return () inherited_roles = get_roles_registry(request.registry).inheritable() if not name.startswith("group:"): root = find_root(context) groups = root["groups"].get_users_group_principals(name) result.update(groups) # Fetch any local roles for group for group in groups: result.update(groupfinder(group, request)) initial_context = context while context: try: if context == initial_context: result.update([x for x in context.local_roles.get(name, ())]) else: result.update([x for x in context.local_roles.get(name, ()) if x in inherited_roles]) except AttributeError: pass context = context.__parent__ return result
def view(self): song = self.context song = self.context root = find_root(song) if song.timings: words = list(krl_iterator(json.loads(song.timings))) else: words = [] bw = mtbw(words) cards = carder(words, bw*2) divs = divver(cards) return { 'title':song.title, 'artist':song.artist, 'num_likes':song.num_likes, 'liked_by': song.liked_by, 'recordings':song.recordings, 'can_record':self.has_record_permission, 'can_retime':self.has_edit_permission, "stream_url": self.request.resource_url(song, '@@stream'), "stream_type":song.mimetype, "timings": song.timings, "max_framerate": root.max_framerate, 'karaoke_cards':divs, 'mtbw':bw, }
def get_font(self): try: font = traversal.find_resource(traversal.find_root(self.get_model()), self.font) except: return None else: return font
def add_globals(event): ''' add render globals ''' request = event['request'] # event['section'] = request.path.split('/')[1] or 'home' event['user'] = authenticated_userid(request) event['nav'] = find_root(request.context).getnav(request.path)
def login(request): # print("LOGIN SAYS: " + str(request.context)) login_url = resource_url(request.context, request, 'login') referrer = request.url if referrer == login_url: referrer = '/' # never use the login form itself as came_from came_from = request.params.get('came_from', referrer) message = '' login = '' oldpassword = '' main = get_renderer('../templates/master.pt').implementation() if 'form.submitted' in request.params: login = request.params['login'] password = request.params["password"] oldpassword = password password = hashlib.sha1(password.encode('UTF-8')).digest() app = find_root(request.context) USERS = app["users"] if not USERS.get(login): return dict(message = "That username failed. You either made a typo or must register", url = request.application_url + '/login', came_from = came_from, login = login, password = oldpassword, name = 'Login', main = main ) elif USERS.get(login).password != password: return dict(message = "Password incorrect. Either retry or contact administrators", url = request.application_url + '/login', came_from = came_from, login = login, password = oldpassword, name = 'Login', main = main ) elif USERS.get(login).password == password: if not hasattr(USERS.get(login), 'deactivated'): USERS.get(login).deactivated = False if USERS.get(login).deactivated: return dict(message = "You've done something wrong and now this account has been deactivated", url = request.application_url + '/login', came_from = came_from, login = login, password = oldpassword, name = 'Login', main = main ) else: headers = remember(request, login) return HTTPFound(location = came_from, headers = headers) message = 'Failed login' return dict( red = '', message = message, url = request.application_url + '/login', came_from = came_from, login = login, password = oldpassword, name = 'Login', main = main )
def libraries(self, status, biological_replicate_number, technical_replicate_number): if status == 'deleted': return [] # Use root.get_by_uuid instead of embed to get reverse link # specifically. This helps avoid infinite loop since calculated # properties of experiment need to embed replicate. properties = self.upgrade_properties() root = find_root(self) experiment = root.get_by_uuid(properties['experiment']) libraries = set() for rep_uuid in experiment.get_rev_links('replicates'): rep_props = root.get_by_uuid(rep_uuid).upgrade_properties() # Only care (check and add to the list) about non-deleted technical # replicates of this replicate, meaning belonging to the same # biological replicate. if (rep_props['biological_replicate_number'] != biological_replicate_number or rep_props['status'] == 'deleted'): continue if rep_props['technical_replicate_number'] < technical_replicate_number: # Found smaller technical replicate, libraries will be # calculated there rather than here. return [] if 'library' in rep_props: libraries.add(rep_props['library']) # This is the "first" techinical replicate within the isogenic # replciate. Therefore, libraries should be calculated. return list(libraries)
def _name(self, properties): root = find_root(self) analysis_step = root.get_by_uuid(properties['analysis_step']) step_props = analysis_step.upgrade_properties() return u'{}-v-{}-{}'.format(step_props['step_label'], step_props['major_version'], properties['minor_version'])
def __call__(self, node, value): root = find_root(self.context) try: find_resource(root, value) except KeyError: raise colander.Invalid( node, _("Not an existing valid path."))
def deferred_autocompleting_userid_widget(node, kw): context = kw['context'] root = find_root(context) choices = tuple(root.users.keys()) return deform.widget.AutocompleteInputWidget(size=15, values=choices, min_length=1)
def __call__(self, node, value): root = find_root(self.context) userids = tuple(root.users.keys()) if value not in userids: msg = _(u"globally_existing_userid_validation_error", default=u"UserID not found") raise colander.Invalid(node, msg)
def groupfinder(username, request): root = find_root(request.context) if username in root: return username else: # raise KeyError('Unknown user: %s' % username) return None
def at_userid_link(text, obj, request=None): """ Transform @userid to a link. """ users = find_root(obj).users meeting = find_interface(obj, IMeeting) assert meeting if not request: request = get_current_request() def handle_match(matchobj): # The pattern contains a space so we only find usernames that # has a whitespace in front, we save the spaced so we can but # it back after the transformation space, userid = matchobj.group(1, 2) #Force lowercase userid userid = userid.lower() if userid in users: user = users[userid] tag = {} tag['href'] = request.resource_url(meeting, '_userinfo', query={'userid': userid}).replace(request.application_url, '') tag['title'] = user.title tag['class'] = "inlineinfo" return space + HTML.a('@%s' % userid, **tag) else: return space + '@' + userid return re.sub(AT_PATTERN, handle_match, text)
def libraries(self, request, status, biological_replicate_number, technical_replicate_number): if status == 'deleted': return [] # Use root.get_by_uuid instead of embed to get reverse link # specifically. This helps avoid infinite loop since calculated # properties of experiment need to embed replicate. properties = self.upgrade_properties() root = find_root(self) experiment = root.get_by_uuid(properties['experiment']) libraries = set() for rep_uuid in experiment.get_rev_links('replicates'): rep_props = root.get_by_uuid(rep_uuid).upgrade_properties() # Only care (check and add to the list) about non-deleted technical # replicates of this replicate, meaning belonging to the same # biological replicate. if (rep_props['biological_replicate_number'] != biological_replicate_number or rep_props['status'] == 'deleted'): continue if rep_props[ 'technical_replicate_number'] < technical_replicate_number: # Found smaller technical replicate, libraries will be # calculated there rather than here. return [] if 'library' in rep_props: libraries.add(rep_props['library']) # This is the "first" techinical replicate within the isogenic # replciate. Therefore, libraries should be calculated. return [ request.resource_path(root.get_by_uuid(lib)) for lib in libraries ]
def invite_ticket(context, request, va, **kw): """ Render invite ticket email html. Uses ticket as a context. Requires message to be passed as a keyword when using view_action """ #FIXME: Include meeting logo in mail? roles = dict(MEETING_ROLES) meeting = find_interface(context, IMeeting) root = find_root(meeting) assert meeting response = {} response['access_link'] = request.resource_url(meeting, 'ticket', query={ 'email': context.email, 'token': context.token }) response['message'] = kw['message'] response['meeting'] = meeting response['contact_mail'] = meeting.get_field_value('meeting_mail_address') response['sender_profile'] = root.users.get(context.sent_by) response['roles'] = [roles.get(x) for x in context.roles] return render('templates/email/invite_ticket_email.pt', response, request=request)
def discussion_redirect_to_agenda_item(context, request): root = find_root(context) ai = find_interface(context, IAgendaItem) if ai: path = resource_path(ai) query = dict( path=path, content_type='DiscussionPost', sort_index='created', reverse=True, limit=5, #FIXME: this should be globaly configurable? ) docids = root.catalog.search(**query)[1] # set to True if requested post is after the display limit after_limit = False get_metadata = root.catalog.document_map.get_metadata for docid in docids: brain = get_metadata(docid) if brain['uid'] == context.uid: after_limit = True break # post was not found among the displayed posts query = request.GET if not after_limit: query['discussions'] = 'all' url = request.resource_url(ai, query=query, anchor=context.uid) else: url = request.resource_url(ai, query=query, anchor=context.uid) return HTTPFound(location=url) raise NotFound("Couldn't locate Agenda Item from this context.")
def groupfinder(username, request): root = find_root(request.context) if username in root: return username else: #raise KeyError('Unknown user: %s' % username) return None
def set_status(self, new_status, request, parent=True): root = find_root(self) schema = self.type_info.schema properties = self.upgrade_properties() item_id = '{}/'.format(resource_path(self)) current_status = properties.get('status') if not current_status: raise ValidationFailure('body', ['status'], 'No property status') if not self._valid_status(new_status, schema, parent): return False force_transition = asbool(request.params.get('force_transition')) if not self._valid_transition(current_status, new_status, parent, force_transition): return False force_audit = asbool(request.params.get('force_audit')) self._block_on_audits(item_id, force_audit, request, parent, new_status) update = asbool(request.params.get('update')) self._update_status(new_status, current_status, properties, schema, request, item_id, update) request._set_status_considered_paths.add((item_id, current_status, new_status)) logging.warn( 'Considering {} from status {} to status {}'.format(item_id, current_status, new_status) ) block_children = self._calculate_block_children(request, force_transition) child_paths = self._get_child_paths(current_status, new_status, block_children) embedded_properties = request.embed(item_id, '@@embedded') related_objects = self._get_related_object(child_paths, embedded_properties, request) self._set_status_on_related_objects(new_status, related_objects, root, request) return True
def get_searchable_text(context, default): root = find_root(context) catalog = root.catalog registry = get_current_registry() discriminators = list(getattr(registry, 'searchable_text_discriminators', ())) results = set() registry = get_current_registry() for index in registry.catalog_indexhelper['searchable_text'].linked: if index not in catalog: #pragma: no coverage # In case a bad name was linked in searchable_text, no reason to die because of it. continue disc = catalog[index].discriminator if isinstance(disc, string_types): attr_discriminator = _AttrDiscriminator(disc) discriminators.append(attr_discriminator) else: discriminators.append(catalog[index].discriminator) for discriminator in discriminators: res = discriminator(context, default) if res is default: continue if not isinstance(res, string_types): res = str(res) res = res.strip() if res: results.add(res) text = " ".join(results) text = text.strip() return text and text or default
def dereference(self, context): """ Return the :class:`Object` this Reference refers to. ``context`` can be any resource and is simply used to find the root (which in turn is used to resolve the reference). """ root = find_root(context) return root.get_object_for_reference(self)
def antibody_lot_3_4(value, system): # http://redmine.encodedcc.org/issues/380 tagged_ab = { 'eGFP': '59c3efe9-00c6-4b1b-858b-5a208478972c', 'YFP': '8a4e81d-3181-4332-9138-ecc39be4a3ab', 'HA': '77d56f5a-e445-4f2c-83ac-65e00ce50ac1', '3XFLAG': 'f2d60a72-7b9c-422a-a80e-9493640c1d58' } context = system['context'] registry = system['registry'] connection = registry[CONNECTION] root = find_root(context) approvals = [] for link_uuid in connection.get_rev_links(context.model, 'antibody', 'antibody_approval'): approvals.append(root.get_by_uuid(link_uuid)) targets = set() for approval in approvals: target = root.get_by_uuid(approval.properties['target']) tag = target.properties['label'].split('-')[0] if tag in tagged_ab.keys(): targets.add(tagged_ab[tag]) else: targets.add(approval.properties['target']) value['targets'] = list(targets)
def at_userid_link(text, obj, request=None): """ Transform @userid to a link. """ users = find_root(obj).users meeting = find_interface(obj, IMeeting) assert meeting if not request: request = get_current_request() def handle_match(matchobj): # The pattern contains a space so we only find usernames that # has a whitespace in front, we save the spaced so we can but # it back after the transformation space, userid = matchobj.group(1, 2) #Force lowercase userid userid = userid.lower() if userid in users: user = users[userid] tag = {} tag['href'] = request.resource_url(meeting, '_userinfo', query={ 'userid': userid }).replace( request.application_url, '') tag['title'] = user.title tag['class'] = "inlineinfo" return space + HTML.a('@%s' % userid, **tag) else: return space + '@' + userid return re.sub(AT_PATTERN, handle_match, text)
def antibody_lot_3_4(value, system): # http://redmine.encodedcc.org/issues/380 tagged_ab = { 'eGFP': '59c3efe9-00c6-4b1b-858b-5a208478972c', 'YFP': '8a4e81d-3181-4332-9138-ecc39be4a3ab', 'HA': '77d56f5a-e445-4f2c-83ac-65e00ce50ac1', '3XFLAG': 'f2d60a72-7b9c-422a-a80e-9493640c1d58' } context = system['context'] root = find_root(context) approvals = [] for link in context.model.revs: if (link.source.item_type, link.rel) == ('antibody_approval', 'antibody'): approvals.append(root.get_by_uuid(link.source_rid)) targets = set() for approval in approvals: target = root.get_by_uuid(approval.properties['target']) tag = target.properties['label'].split('-')[0] if tag in tagged_ab.keys(): targets.add(tagged_ab[tag]) else: targets.add(approval.properties['target']) value['targets'] = list(targets)
def render_invite_ticket(ticket, request, message="", **kw): """ Render invite ticket email html. Uses ticket as a context. """ assert IInviteTicket.providedBy(ticket) #FIXME: Include meeting logo in mail? roles = dict(security.MEETING_ROLES) meeting = find_interface(ticket, IMeeting) root = find_root(meeting) assert IMeeting.providedBy(meeting) response = {} response['access_link'] = request.resource_url(meeting, 'ticket', query={ 'email': ticket.email, 'token': ticket.token }) response['message'] = message response['meeting'] = meeting response['context'] = ticket response['contact_mail'] = meeting.get_field_value('meeting_mail_address') response['sender_profile'] = root.users.get(ticket.sent_by) response['roles'] = [roles.get(x) for x in ticket.roles] return render('voteit.core:templates/email/invite_ticket_email.pt', response, request=request)
def get_proposal_objects(self): """ Return proposal objects relevant to this poll. Will sort them in specified order. """ agenda_item = self.__parent__ if agenda_item is None: raise ValueError("Can't find any agenda item in the polls lineage") query = Any('uid', tuple(self.proposal_uids)) & Eq( 'type_name', 'Proposal') root = find_root(agenda_item) results = [] for docid in root.catalog.query(query)[1]: path = root.document_map.address_for_docid(docid) obj = find_resource(root, path) # Permission check shouldn't be needed at this point if obj: results.append(obj) if self.proposal_order: proposal_order = self.proposal_order else: meeting = find_interface(self, IMeeting) # During tests, we might not have a real meeting here :) proposal_order = getattr(meeting, 'poll_proposals_default_order', '') key_method = PROPOSAL_ORDER_KEY_METHODS.get( proposal_order, PROPOSAL_ORDER_KEY_METHODS[PROPOSAL_ORDER_DEFAULT]) return sorted(results, key=key_method)
def view_model(context, request): index_url = request.resource_url(find_root(context)) edit_url = request.resource_url(context, 'edit') return {'entry':context, 'project':'alchemy', 'index_url':index_url, 'edit_url':edit_url}
def deferred_user_choices_widget(node, kw): context = kw['context'] root = find_root(context) user_choices = tuple(root['users'].keys()) return deform.widget.AutocompleteInputWidget(size=20, values = user_choices, min_length=1)
def set_status(self, new_status, request, parent=True): root = find_root(self) schema = self.type_info.schema properties = self.upgrade_properties() item_id = '{}/'.format(resource_path(self)) current_status = properties.get('status') if not current_status: raise ValidationFailure('body', ['status'], 'No property status') if not self._valid_status(new_status, schema, parent): return False force_transition = asbool(request.params.get('force_transition')) if not self._valid_transition(current_status, new_status, parent, force_transition): return False force_audit = asbool(request.params.get('force_audit')) self._block_on_audits(item_id, force_audit, request, parent, new_status) update = asbool(request.params.get('update')) self._update_status(new_status, current_status, properties, schema, request, item_id, update) request._set_status_considered_paths.add( (item_id, current_status, new_status)) logging.warn('Considering {} from status {} to status {}'.format( item_id, current_status, new_status)) block_children = self._calculate_block_children( request, force_transition) child_paths = self._get_child_paths(current_status, new_status, block_children) embedded_properties = request.embed(item_id, '@@embedded') related_objects = self._get_related_object(child_paths, embedded_properties, request) self._set_status_on_related_objects(new_status, related_objects, root, request) return True
def claim_ticket(ticket, request, user_identifier): #Is the ticket open? if ticket.get_workflow_state() != 'open': raise HTTPForbidden("Access already granted with this ticket") #Find required resources and do some basic validation meeting = find_interface(ticket, IMeeting) root = find_root(ticket) assert meeting assert root if '@' in user_identifier: user = root['users'].get_user_by_email(user_identifier, None) else: user = root['users'].get(user_identifier, None) if user is None: raise HTTPForbidden("No user could be looked up via: %r" % user_identifier) meeting.add_groups(user.userid, ticket.roles) ticket.claimed_by = user.userid ticket.set_workflow_state(request, 'closed') ticket.closed = utcnow() #If ticket and user profile has the same email, consider that email validated #This will notify and perhaps fetch other tickets as well if user.email == ticket.email: user.email_validated = True return user
def tags(self, value): request = get_current_request() root = find_root(request.context) ctags = IClusterTags(root, None) assert self.cluster if ctags is not None: ctags[self.cluster] = value
def __ac_local_roles__(self): root = find_root(self) experiment = root.get_by_uuid(self.properties['experiment']) lab_uuid = experiment.properties.get('lab') if lab_uuid is None: return None lab_submitters = 'submits_for.%s' % lab_uuid return {lab_submitters: 'role.lab_submitter'}
def biosample_22_23(value, system): # https://encodedcc.atlassian.net/browse/ENCD-4360 biosample_type_name = u'{}_{}'.format(value['biosample_type'], value['biosample_term_id']).replace( ' ', '_').replace(':', '_') value['biosample_ontology'] = str( find_root( system['context'])['biosample-types'][biosample_type_name].uuid)
def _get_lock_service(resource): lockservice = find_service(resource, 'locks') if lockservice is None: registry = get_current_registry() lockservice = registry.content.create('Lock Service') root = find_root(resource) root.add_service('locks', lockservice) return lockservice
def __init__(self, context, request): self.context = context self.request = request self.resource_url = resource_url self.root = find_root(context) self.userid = authenticated_userid(request) self.template_dir = TEMPLATE_DIR self.tag_count = {}
def _name(self, properties): root = find_root(self) organism_uuid = self.organism(properties=properties, return_uuid=True) if not organism_uuid: source = properties['investigated_as'][0].replace(' ', '_') else: organism = root.get_by_uuid(organism_uuid) source = organism.upgrade_properties()['name'] return u'{}-{}'.format(properties['label'], source)
def show_evolve(self): root = find_root(self.request.context) manager = self.EvolutionManager(root, self.request.registry) return dict( unfinished_steps=list(manager.get_unfinished_steps()), finished_steps=list(manager.get_finished_steps_by_value()), format_timestamp=_format_timestamp, )
def test_url_method(self): obj = self._make_obj() request = testing.DummyRequest() request.root = find_root(obj.context) url = obj.url(45, request) self.assertEqual( "https://secure.gravatar.com/avatar/4b3cdf9adfc6258a102ab90eb64565ea?s=45&d=robohash", url, )
def antibody_characterization_14_15(value, system): # https://encodedcc.atlassian.net/browse/ENCD-4360 for char_review in value.get('characterization_reviews', []): biosample_type_name = u'{}_{}'.format( char_review['biosample_type'], char_review['biosample_term_id'] ).replace(' ', '_').replace(':', '_') char_review['biosample_ontology'] = str( find_root(system['context'])['biosample-types'][biosample_type_name].uuid )
def find_box(context): """ Find the box archive, create one if necessary. """ root = find_root(context) box = root.get('box') if not box: root['box'] = box = BoxArchive() return box
def __init__(self, key=None, parent=None, **kwargs): self.__name__ = key self.__parent__ = parent # Reference request self.request = find_root(self).request # Reference app and site self.__app__ = find_interface(self, i.IApp) self.__site__ = find_interface(self, i.ISite) # Assign kwargs to self (used as self.XXX not self['xxx']) for key in kwargs: setattr(self, key, kwargs[key])
def dataset_0_2(value, system): # http://redmine.encodedcc.org/issues/650 context = system['context'] root = find_root(context) if 'files' in value: value['related_files'] = [] for file_uuid in value['files']: item = root.get_by_uuid(file_uuid) if UUID(item.properties['dataset']) != context.uuid: value['related_files'].append(file_uuid) del value['files']
def antibody_characterization_5_6(value, system): # http://redmine.encodedcc.org/issues/2591 context = system['context'] root = find_root(context) publications = root['publications'] if 'references' in value: new_references = [] for ref in value['references']: item = publications[ref] new_references.append(str(item.uuid)) value['references'] = new_references
def dataset_23_24(value, system): # https://encodedcc.atlassian.net/browse/ENCD-4360 classification = value.get('biosample_type') term_id = value.get('biosample_term_id') if classification and term_id: biosample_type_name = u'{}_{}'.format( value['biosample_type'], value['biosample_term_id']).replace(' ', '_').replace(':', '_') value['biosample_ontology'] = str( find_root(system['context'])['biosample-types'] [biosample_type_name].uuid)
def dryrun(self): root = find_root(self.request.context) manager = self.EvolutionManager(root, self.request.registry) complete = manager.evolve(commit=False) if complete: self.request.session.flash('%d evolution steps dry-run' % len(complete)) else: self.request.session.flash('No evolution steps dry-run') return HTTPFound( location=self.request.sdiapi.mgmt_path(self.context, '@@database'))