def getVars(self): vars = wcomponents.WTemplated.getVars(self) vars["locator"] = self._subContrib.getLocator().getWebForm() vars["title"] = self._subContrib.getTitle() if isStringHTML(self._subContrib.getDescription()): vars["description"] = self._subContrib.getDescription() else: vars[ "description"] = """<table class="tablepre"><tr><td><pre>%s</pre></td></tr></table>""" % self._subContrib.getDescription( ) vars["dataModifButton"] = "" vars["dataModifButton"] = _( """<input type="submit" class="btn" value="_("modify")">""") vars["reportNumbersTable"] = wcomponents.WReportNumbersTable( self._subContrib, "subcontribution").getHTML() vars["keywords"] = self._subContrib.getKeywords() vars["confId"] = self._subContrib.getConference().getId() vars["contribId"] = self._subContrib.getContribution().getId() vars["subContribId"] = self._subContrib.getId() vars["presenters"] = fossilize(self._subContrib.getSpeakerList(), ISubContribParticipationFullFossil) vars["suggested_authors"] = fossilize( get_authors_from_author_index(self._subContrib.getConference(), 10)) vars["eventType"] = self._subContrib.getConference().getType() return vars
def getVars(self): vars = wcomponents.WTemplated.getVars( self ) slotConveners = [] for entry in self._session.getSchedule().getEntries(): slot = entry.getOwner() conveners = [] for convener in slot.getOwnConvenerList(): conveners.append({'fullName': convener.getFullName(), 'email': convener.getEmail() if self._aw.getUser() else "", 'affiliation' : convener.getAffiliation()}) if conveners: slotConveners.append({'title': slot.getTitle(), 'startDate': slot.getAdjustedStartDate(self._tz), 'endDate': slot.getAdjustedEndDate(self._tz), 'conveners': conveners}) vars["slotConveners"] = slotConveners eventInfo = fossilize(self._session.getConference(), IConferenceEventInfoFossil, tz = self._tz) eventInfo['timetableSession'] = fossilize(self._session, ISessionFossil, tz = self._tz) vars["ttdata"]= schedule.ScheduleToJson.process(self._session.getSchedule(), self._tz, None, days = None, mgmtMode = False) vars["eventInfo"]= eventInfo vars["session"] = vars["target"] = self._session vars["urlICSFile"] = urlHandlers.UHSessionToiCal.getURL(self._session) vars.update(self._getIcalExportParams(self._aw.getUser(), '/export/event/%s/session/%s.ics' % \ (self._session.getConference().getId(), self._session.getId()))) vars["conf"] = self._session.getConference() vars["contributions"] = sorted(self._session.getContributionList(), key=lambda contrib: contrib.getTitle()) return vars
def testFossilizePrimitives(self): "Serializing primitive objects such as strings, integers and floats" self.assertEquals(4, fossilize(4, ISomeFossil)) self.assertEquals('foo', fossilize('foo', ISomeFossil)) self.assertEquals(5.0, fossilize(5.0, ISomeFossil)) self.assertEquals(None, fossilize(None, ISomeFossil))
def getVars(self): vars = WCSPageTemplateBase.getVars( self ) vars["IsSingleBooking"] = not CollaborationTools.getCSBookingClass(self._pluginId)._allowMultiple vars["Conference"] = self._conf isLecture = self._conf.getType() == 'simple_event' vars["IsLecture"] = isLecture underTheLimit = self._conf.getNumberOfContributions() <= self._RecordingRequestOptions["contributionLoadLimit"].getValue() manager = self._conf.getCSBookingManager() user = self._rh._getUser() isManager = user.isAdmin() or RCCollaborationAdmin.hasRights(user=user) or RCCollaborationPluginAdmin.hasRights(user=user, plugins=['RecordingRequest']) booking = manager.getSingleBooking('RecordingRequest') initialChoose = booking is not None and booking._bookingParams['talks'] == 'choose' initialDisplay = (self._conf.getNumberOfContributions() > 0 and underTheLimit) or (booking is not None and initialChoose) vars["InitialChoose"] = initialChoose vars["DisplayTalks"] = initialDisplay vars["isManager"] = isManager talks, rRoomFullNames, rRoomNames, recordingAbleTalks, recordingUnableTalks = getCommonTalkInformation(self._conf) nRecordingCapable = len(recordingAbleTalks) vars["HasRecordingCapableTalks"] = nRecordingCapable > 0 vars["NTalks"] = len(talks) # list of "locationName:roomName" strings vars["RecordingCapableRooms"] = rRoomFullNames vars["NRecordingCapableContributions"] = nRecordingCapable # we check if the event itself is recoring capable (depends on event's room) confLocation = self._conf.getLocation() confRoom = self._conf.getRoom() if confLocation and confRoom and (confLocation.getName() + ":" + confRoom.getName() in rRoomNames): topLevelRecordingCapable = True else: topLevelRecordingCapable = False # Finally, this event is recoring capable if the event itself # or one of its talks are capable or user is admin, collaboration # manager or recording plugin manager vars["RecordingCapable"] = topLevelRecordingCapable or nRecordingCapable > 0 or isManager recordingAbleTalks.sort(key = Contribution.contributionStartDateForSort) talks.sort(key = Contribution.contributionStartDateForSort) fossil_args = dict(tz=self._conf.getTimezone(), units='(hours)_minutes', truncate=True) vars["Contributions"] = fossilize(talks, IContributionRRFossil, **fossil_args) vars["ContributionsAble"] = fossilize(recordingAbleTalks, IContributionRRFossil, **fossil_args) vars["ContributionsUnable"] = fossilize(recordingUnableTalks, IContributionRRFossil, **fossil_args) vars["PostingUrgency"] = postingUrgency vars["linkToEA"] = collaborationUrlHandlers.UHCollaborationElectronicAgreement.getURL(self._conf) vars["agreementName"] = CollaborationTools.getOptionValue("RecordingRequest", "AgreementName") return vars
def testFossilizeStructuresOfPrimitives(self): "Serializing semi-structured data such as lists and dictionaries" self.assertEquals([], fossilize([], ISomeFossil)) self.assertEquals([4, [4, 5, 6], [1]], fossilize([4, (4, 5, 6), set([1])], ISomeFossil)) self.assertEquals({'a':'foo', 2:'bar'}, fossilize({'a':'foo', 2:'bar'}, ISomeFossil)) self.assertEquals({'a':'foo', 2:'bar', 3:5.0}, fossilize({'a':'foo', 2:'bar', 3:5.0}, ISomeFossil))
def testFossilizeDefault(self): "Default fossil" s1 = SimpleClass(10, 20, "foo") d1 = DerivedClass(10, 50, "bar") self.assertEquals(s1.fossilize(), {"_type": "SimpleClass", "_fossil": "simpleFossil1", "b": 20, "c": "FOO"}) self.assertEquals(fossilize(d1), {"_type": "DerivedClass", "_fossil": "simpleFossil1", "b": 50, "c": "BAR"}) self.assertEquals(fossilize([s1, d1]), [fossilize(s1), d1.fossilize()])
def _getAnswer(self): result = self._booking.stopSingleParticipant(self._participant) if isinstance(result, CERNMCUError): return fossilize(result) else: return fossilize(self._booking, ICSBookingBaseConfModifFossil, tz=self._conf.getTimezone())
def testFossilizeDefault(self): "Default fossil" s1 = SimpleClass(10, 20, 'foo') d1 = DerivedClass(10, 50, 'bar') self.assertEquals(s1.fossilize(), {'_type':'SimpleClass', '_fossil':'simpleFossil1', "b": 20, "c":"FOO"}) self.assertEquals(fossilize(d1), {'_type':'DerivedClass', '_fossil':'simpleFossil1', "b": 50, "c":"BAR"}) self.assertEquals(fossilize([s1, d1]), [fossilize(s1), d1.fossilize()])
def _getAnswer(self): #will use IAvatarFossil or IGroupFossil allowedAccesList = fossilize(self._resource.getAllowedToAccessList()) if self._includeFavList and self._user: favList = fossilize(self._user.getPersonalInfo().getBasket().getUsers().values()) return [allowedAccesList, favList] else: return allowedAccesList
def _getAnswer(self): #will use IAvatarFossil or IGroupFossil allowedAccesList = fossilize(self._resource.getAllowedToAccessList()) if self._includeFavList and self._user: favList = fossilize( self._user.getPersonalInfo().getBasket().getUsers().values()) return [allowedAccesList, favList] else: return allowedAccesList
def _getControlUserList(self): if self._kindOfList == "modification": result = fossilize(self._categ.getManagerList()) # get pending users for email in self._categ.getAccessController().getModificationEmail(): pendingUser = {} pendingUser["email"] = email pendingUser["pending"] = True result.append(pendingUser) return result elif self._kindOfList == "confCreation": return fossilize(self._categ.getConferenceCreatorList())
def getVars(self): vars = wcomponents.WTemplated.getVars(self) slotConveners = [] for entry in self._session.getSchedule().getEntries(): slot = entry.getOwner() conveners = [] for convener in slot.getOwnConvenerList(): conveners.append({ 'fullName': convener.getFullName(), 'email': convener.getEmail() if self._aw.getUser() else "", 'affiliation': convener.getAffiliation() }) if conveners: slotConveners.append({ 'title': slot.getTitle(), 'startDate': slot.getAdjustedStartDate(self._tz), 'endDate': slot.getAdjustedEndDate(self._tz), 'conveners': conveners }) vars["slotConveners"] = slotConveners eventInfo = fossilize(self._session.getConference(), IConferenceEventInfoFossil, tz=self._tz) eventInfo['timetableSession'] = fossilize(self._session, ISessionFossil, tz=self._tz) vars["ttdata"] = schedule.ScheduleToJson.process( self._session.getSchedule(), self._tz, None, days=None, mgmtMode=False) vars["eventInfo"] = eventInfo vars["session"] = vars["target"] = self._session vars["urlICSFile"] = urlHandlers.UHSessionToiCal.getURL(self._session) vars.update(self._getIcalExportParams(self._aw.getUser(), '/export/event/%s/session/%s.ics' % \ (self._session.getConference().getId(), self._session.getId()))) vars["conf"] = self._session.getConference() vars["contributions"] = sorted(self._session.getContributionList(), key=lambda contrib: contrib.getTitle()) return vars
def getVars( self ): vars=wcomponents.WTemplated.getVars(self) tz = self._session.getTimezone() vars["timezone"]= tz vars['ttdata'] = json.dumps(schedule.ScheduleToJson.process(self._session.getSchedule(), tz, None, days = None, mgmtMode = True)) eventInfo = fossilize(self._session.getConference(), IConferenceEventInfoFossil, tz=tz) eventInfo['timetableSession'] = fossilize(self._session, ISessionFossil, tz=tz) eventInfo['isCFAEnabled'] = self._session.getConference().getAbstractMgr().isActive() vars['eventInfo'] = json.dumps(eventInfo) return vars
def _getSessionChairList(self, rol): # get the lists we need to iterate if rol == "manager": list = self._session.getManagerList() pendingList = self._session.getAccessController().getModificationEmail() elif rol == "coordinator": list = self._session.getCoordinatorList() pendingList = self._session.getConference().getPendingQueuesMgr().getPendingCoordinatorsKeys() result = [] for sessionChair in list: sessionChairFossil = fossilize(sessionChair) if isinstance(sessionChair, AvatarUserWrapper): isConvener = False if self._session.hasConvenerByEmail(sessionChair.getEmail()): isConvener = True sessionChairFossil['isConvener'] = isConvener result.append(sessionChairFossil) # get pending users for email in pendingList: pendingUser = {} pendingUser["email"] = email pendingUser["pending"] = True pendingUser['_type'] = 'Avatar' result.append(pendingUser) return result
def _getAnswer(self): for fossil in self._userList: user = User.get(int(fossil['id'])) if user is not None: user.is_admin = True admins = User.find(is_admin=True, is_deleted=False).order_by(User.first_name, User.last_name).all() return fossilize([u.as_avatar for u in admins])
def getVars(self): vars = wcomponents.WTemplated.getVars(self) csbm = self._conf.getCSBookingManager() pluginNames = csbm.getEventDisplayPlugins() bookings = csbm.getBookingList(filterByType = pluginNames, notify = True, onlyPublic = True) bookings.sort(key = lambda b: b.getStartDate() or minDatetime()) ongoingBookings = [] scheduledBookings = {} #date, list of bookings for b in bookings: if b.isHappeningNow(): ongoingBookings.append(b) if b.getStartDate() and b.getAdjustedStartDate('UTC') > nowutc(): scheduledBookings.setdefault(b.getAdjustedStartDate(self._tz).date(), []).append(b) keys = scheduledBookings.keys() keys.sort() scheduledBookings = [(date, scheduledBookings[date]) for date in keys] vars["OngoingBookings"] = ongoingBookings vars["ScheduledBookings"] = scheduledBookings vars["all_bookings"] = fossilize(bookings) vars["Timezone"] = self._tz vars["conf"] = self._conf return vars
def getVars(self): vars = wcomponents.WTemplated.getVars(self) authorObj = self._contrib.getAuthorById(self._authorId) if authorObj is None: raise MaKaCError(_("Not found the author: %s") % self._authorId) authorList = self._conf.getAuthorIndex().getByAuthorObj(authorObj) author = None if authorList is not None: author = authorList[0] else: raise MaKaCError(_("Not found the author: %s") % self._authorId) contribList = [] for auth in authorList: contrib = auth.getContribution() if contrib is not None: contribList.append({'title': contrib.getTitle(), 'url': str(urlHandlers.UHContributionDisplay.getURL(auth.getContribution())), 'materials': fossilize(contrib.getAllMaterialList())}) vars["contributions"] = contribList vars["fullName"] = author.getFullName() if self._aw.getUser() is not None: vars["email"] = author.getEmail() vars["address"] = author.getAddress() vars["telephone"] = author.getPhone() vars["fax"] = author.getFax() vars["affiliation"] = author.getAffiliation() return vars
def _serialize_contribution(contrib): return { 'id': contrib.id, 'friendly_id': contrib.friendly_id, 'contributionId': contrib.id, 'title': contrib.title, 'location': contrib.venue_name, 'room': contrib.room_name, 'startDate': Conversion.datetime(contrib.start_dt), 'endDate': Conversion.datetime(contrib.end_dt), 'duration': Conversion.duration(contrib.duration), 'description': contrib.description, 'track': to_unicode(contrib.track.getTitle()) if contrib.track else None, 'session': contrib.session.title if contrib.session else None, 'type': contrib.type.name if contrib.type else None, 'address': contrib.address, 'reviewManager': fossilize(contrib.event_new.as_legacy.getReviewManager(contrib), IReviewManagerFossil) }
def _getAnswer(self): talks = getTalks(self._conf, sort=True) return fossilize(talks, IContributionWithSpeakersFossil, tz=self._conf.getTimezone(), units='(hours)_minutes', truncate=True)
def _getAnswer(self): afm = self._target.getAbstractMgr().getAbstractFieldsMgr() afmDict = dict([(i, fossilize(f)) for i, f in enumerate(afm.getFields())]) cTypes = self._target.getContribTypeList() cTypesDict = dict([(ct.getId(), ct.getName()) for ct in cTypes]) return [afmDict, cTypesDict]
def getVars(self): wvars = wcomponents.WTemplated.getVars(self) minfo = info.HelperMaKaCInfo.getMaKaCInfoInstance() wvars['title'] = minfo.getTitle() wvars['organisation'] = minfo.getOrganisation() wvars['supportEmail'] = Config.getInstance().getSupportEmail() wvars['publicSupportEmail'] = Config.getInstance().getPublicSupportEmail() wvars['noReplyEmail'] = Config.getInstance().getNoReplyEmail() wvars['lang'] = minfo.getLang() wvars['address'] = '' if minfo.getCity() != '': wvars['address'] = minfo.getCity() if minfo.getCountry() != '': if wvars['address'] != '': wvars['address'] = '{0} ({1})'.format(wvars['address'], minfo.getCountry()) else: wvars['address'] = minfo.getCountry() wvars['timezone'] = Config.getInstance().getDefaultTimezone() wvars['systemIconAdmins'] = Config.getInstance().getSystemIconURL('admin') iconDisabled = str(Config.getInstance().getSystemIconURL('disabledSection')) iconEnabled = str(Config.getInstance().getSystemIconURL('enabledSection')) url = urlHandlers.UHAdminSwitchNewsActive.getURL() icon = iconEnabled if minfo.isNewsActive() else iconDisabled wvars['features'] = i18nformat('<a href="{}"><img src="{}" border="0"' 'style="float:left; padding-right: 5px">_("News Pages")</a>').format(url, icon) wvars['administrators'] = fossilize(sorted([u.as_avatar for u in User.find(is_admin=True, is_deleted=False)], key=methodcaller('getStraightFullName'))) wvars['tracker_url'] = urljoin(Config.getInstance().getTrackerURL(), 'api/instance/{}'.format(cephalopod_settings.get('uuid'))) wvars['cephalopod_data'] = {'enabled': cephalopod_settings.get('joined'), 'contact': cephalopod_settings.get('contact_name'), 'email': cephalopod_settings.get('contact_email'), 'url': Config.getInstance().getBaseURL(), 'organisation': minfo.getOrganisation()} return wvars
def getVars(self): wvars = wcomponents.WTemplated.getVars(self) minfo = info.HelperMaKaCInfo.getMaKaCInfoInstance() wvars['title'] = minfo.getTitle() wvars['organisation'] = minfo.getOrganisation() wvars['supportEmail'] = Config.getInstance().getSupportEmail() wvars['publicSupportEmail'] = Config.getInstance().getPublicSupportEmail() wvars['noReplyEmail'] = Config.getInstance().getNoReplyEmail() wvars['lang'] = Config.getInstance().getDefaultLocale() wvars['address'] = '' if minfo.getCity() != '': wvars['address'] = minfo.getCity() if minfo.getCountry() != '': if wvars['address'] != '': wvars['address'] = '{0} ({1})'.format(wvars['address'], minfo.getCountry()) else: wvars['address'] = minfo.getCountry() wvars['timezone'] = Config.getInstance().getDefaultTimezone() wvars['systemIconAdmins'] = Config.getInstance().getSystemIconURL('admin') wvars['administrators'] = fossilize(sorted([u.as_avatar for u in User.find(is_admin=True, is_deleted=False)], key=methodcaller('getStraightFullName'))) wvars['tracker_url'] = urljoin(Config.getInstance().getTrackerURL(), 'api/instance/{}'.format(cephalopod_settings.get('uuid'))) wvars['cephalopod_data'] = {'enabled': cephalopod_settings.get('joined'), 'contact': cephalopod_settings.get('contact_name'), 'email': cephalopod_settings.get('contact_email'), 'url': Config.getInstance().getBaseURL(), 'organisation': minfo.getOrganisation()} return wvars
def _getAnswer(self): event_persons = [] users = searchUsers(self._surName, self._name, self._organisation, self._email, self._exactMatch, self._searchExt) if self._event: fields = { EventPerson.first_name: self._name, EventPerson.last_name: self._surName, EventPerson.email: self._email, EventPerson.affiliation: self._organisation } criteria = [ unaccent_match(col, val, exact=self._exactMatch) for col, val in fields.iteritems() ] event_persons = self._event.persons.filter(*criteria).all() fossilized_users = fossilize( sorted(users, key=lambda av: (av.getStraightFullName(), av.getEmail()))) fossilized_event_persons = map(serialize_event_person, event_persons) unique_users = { to_unicode(user['email']): user for user in chain(fossilized_users, fossilized_event_persons) } return sorted(unique_users.values(), key=lambda x: (to_unicode(x['name']).lower(), to_unicode(x['email'])))
def getVars(self): wvars = WConfDisplayBodyBase.getVars(self) csbm = Catalog.getIdx("cs_bookingmanager_conference").get(self._conf.getId()) pluginNames = csbm.getEventDisplayPlugins() bookings = csbm.getBookingList(filterByType=pluginNames, notify=True, onlyPublic=True) bookings.sort(key=lambda b: b.getStartDate() or minDatetime()) timeless_bookings = [] ongoingBookings = [] scheduledBookings = {} #date, list of bookings for b in bookings: if b.canBeDisplayed(): if not b.hasStartDate(): timeless_bookings.append(b) else: if b.isHappeningNow(): ongoingBookings.append(b) elif b.getStartDate() and b.getAdjustedStartDate('UTC') > nowutc(): scheduledBookings.setdefault(b.getAdjustedStartDate(self._tz).date(), []).append(b) keys = scheduledBookings.keys() keys.sort() scheduledBookings = [(date, scheduledBookings[date]) for date in keys] wvars["body_title"] = self._getTitle() wvars["OngoingBookings"] = ongoingBookings wvars["ScheduledBookings"] = scheduledBookings wvars["timeless_bookings"] = timeless_bookings wvars["all_bookings"] = fossilize(bookings) wvars["Timezone"] = self._tz wvars["conf"] = self._conf return wvars
def getVars(self): vars = wcomponents.WTemplated.getVars(self) authorObj = self._contrib.getAuthorById(self._authorId) not_found = NotFoundError(_("No author with id {} was found").format(self._authorId), title=_("Author not found")) if authorObj is None: raise not_found authorList = self._conf.getAuthorIndex().getByAuthorObj(authorObj) if authorList is None: raise not_found author = authorList[0] contribList = [] for auth in authorList: contrib = auth.getContribution() if contrib is not None: contribList.append({'title': contrib.getTitle(), 'url': str(urlHandlers.UHContributionDisplay.getURL(auth.getContribution())), 'materials': fossilize(contrib.getAllMaterialList())}) vars["contributions"] = contribList vars["fullName"] = author.getFullName() if self._aw.getUser() is not None: vars["email"] = author.getEmail() vars["address"] = author.getAddress() vars["telephone"] = author.getPhone() vars["fax"] = author.getFax() vars["affiliation"] = author.getAffiliation() return vars
def _getSessionChairList(self, rol): # get the lists we need to iterate if rol == "manager": list = self._session.getManagerList() pendingList = self._session.getAccessController( ).getModificationEmail() elif rol == "coordinator": list = self._session.getCoordinatorList() pendingList = self._session.getConference().getPendingQueuesMgr( ).getPendingCoordinatorsKeys() result = [] for sessionChair in list: sessionChairFossil = fossilize(sessionChair) if isinstance(sessionChair, AvatarUserWrapper): isConvener = False if self._session.hasConvenerByEmail(sessionChair.getEmail()): isConvener = True sessionChairFossil['isConvener'] = isConvener result.append(sessionChairFossil) # get pending users for email in pendingList: pendingUser = {} pendingUser["email"] = email pendingUser["pending"] = True pendingUser['_type'] = 'Avatar' result.append(pendingUser) return result
def getVars( self ): vars = wcomponents.WTemplated.getVars( self ) minfo = info.HelperMaKaCInfo.getMaKaCInfoInstance() vars["title"] = minfo.getTitle() vars["organisation"] = minfo.getOrganisation() vars['supportEmail'] = Config.getInstance().getSupportEmail() vars['publicSupportEmail'] = Config.getInstance().getPublicSupportEmail() vars['noReplyEmail'] = Config.getInstance().getNoReplyEmail() vars["lang"] = minfo.getLang() vars["address"] = "" if minfo.getCity() != "": vars["address"] = minfo.getCity() if minfo.getCountry() != "": if vars["address"] != "": vars["address"] = "%s (%s)"%(vars["address"], minfo.getCountry()) else: vars["address"] = "%s"%minfo.getCountry() vars["timezone"] = Config.getInstance().getDefaultTimezone() vars["systemIconAdmins"] = Config.getInstance().getSystemIconURL( "admin" ) iconDisabled = str(Config.getInstance().getSystemIconURL( "disabledSection" )) iconEnabled = str(Config.getInstance().getSystemIconURL( "enabledSection" )) url = urlHandlers.UHAdminSwitchNewsActive.getURL() icon = iconEnabled if minfo.isNewsActive() else iconDisabled vars["features"] = i18nformat("""<a href="%s"><img src="%s" border="0" style="float:left; padding-right: 5px">_("News Pages")</a>""") % (url, icon) vars["administrators"] = fossilize(sorted([u.as_avatar for u in User.find(is_admin=True, is_deleted=False)], key=methodcaller('getStraightFullName'))) return vars
def _getAnswer(self): ah = AvatarHolder() for user in self._userList: spk = conference.SubContribParticipation() spk.setDataFromAvatar(ah.getById(user["id"])) self._subContrib.newSpeaker(spk) return fossilize(self._subContrib.getSpeakerList(), ISubContribParticipationFullFossil)
def _getSubmittersList(self): result = [] for submitter in self._contribution.getSubmitterList(): submitterFossil = fossilize(submitter) if isinstance(submitter, Avatar): isSpeaker = False if self._conf.getType() == "conference": isPrAuthor = False isCoAuthor = False if self._contribution.isPrimaryAuthorByEmail( submitter.getEmail()): isPrAuthor = True if self._contribution.isCoAuthorByEmail( submitter.getEmail()): isCoAuthor = True submitterFossil["isPrAuthor"] = isPrAuthor submitterFossil["isCoAuthor"] = isCoAuthor if self._contribution.isSpeakerByEmail(submitter.getEmail()): isSpeaker = True submitterFossil["isSpeaker"] = isSpeaker result.append(submitterFossil) # get pending users for email in self._contribution.getSubmitterEmailList(): pendingUser = {} pendingUser["email"] = email pendingUser["pending"] = True result.append(pendingUser) return result
def _getSubmittersList(self): result = [] for submitter in self._contribution.getSubmitterList(): submitterFossil = fossilize(submitter) if isinstance(submitter, Avatar): isSpeaker = False if self._conf.getType() == "conference": isPrAuthor = False isCoAuthor = False if self._contribution.isPrimaryAuthorByEmail(submitter.getEmail()): isPrAuthor = True if self._contribution.isCoAuthorByEmail(submitter.getEmail()): isCoAuthor = True submitterFossil["isPrAuthor"] = isPrAuthor submitterFossil["isCoAuthor"] = isCoAuthor if self._contribution.isSpeakerByEmail(submitter.getEmail()): isSpeaker = True submitterFossil["isSpeaker"] = isSpeaker result.append(submitterFossil) # get pending users for email in self._contribution.getSubmitterEmailList(): pendingUser = {} pendingUser["email"] = email pendingUser["pending"] = True result.append(pendingUser) return result
def _getAnswer(self): for reviewer in self._reviewerList: ah = user.AvatarHolder() av = ah.getById(reviewer["id"]) self._conf.getTrackById(self._trackId).addCoordinator(av) return fossilize( self._conf.getTrackById(self._trackId).getCoordinatorList())
def testFossilizingNonFossilizable(self): "Non-Fossilizable objects should be OK to fossilize" self.assertEqual(fossilize(1 + 4j, ISomeFossil), { '_fossil': 'some', '_type': 'complex' })
def getVars(self): vars=WCSPageTemplateBase.getVars( self ) vars["Conference"] = self._conf vars["IsSingleBooking"] = not CollaborationTools.getCSBookingClass(self._pluginName)._allowMultiple isLecture = self._conf.getType() == 'simple_event' vars["IsLecture"] = isLecture underTheLimit = self._conf.getNumberOfContributions() <= self._WebcastRequestOptions["contributionLoadLimit"].getValue() booking = self._conf.getCSBookingManager().getSingleBooking('WebcastRequest') initialChoose = booking is not None and booking._bookingParams['talks'] == 'choose' initialDisplay = (self._conf.getNumberOfContributions() > 0 and underTheLimit) or (booking is not None and initialChoose) vars["DisplayTalks"] = initialDisplay vars["InitialChoose"] = initialChoose talks, webcastCapableRooms, webcastAbleTalks = getCommonTalkInformation(self._conf) nTalks = len(talks) nWebcastCapable = len(webcastAbleTalks) vars["HasWebcastCapableTalks"] = nWebcastCapable > 0 vars["NTalks"] = nTalks #list of "locationName:roomName" strings vars["WebcastCapableRooms"] = webcastCapableRooms vars["NWebcastCapableContributions"] = nWebcastCapable #we see if the event itself is webcast capable (depends on event's room) confLocation = self._conf.getLocation() confRoom = self._conf.getRoom() if confLocation and confRoom and (confLocation.getName() + ":" + confRoom.getName() in webcastCapableRooms): topLevelWebcastCapable = True else: topLevelWebcastCapable = False #Finally, this event is webcast capable if the event itself or one of its talks are vars["WebcastCapable"] = topLevelWebcastCapable or nWebcastCapable > 0 if initialDisplay: webcastAbleTalks.sort(key = Contribution.contributionStartDateForSort) vars["Contributions"] = fossilize(webcastAbleTalks, IContributionWithSpeakersFossil, tz = self._conf.getTimezone(), units = '(hours)_minutes', truncate = True) else: vars["Contributions"] = [] vars["LectureOptions"] = lectureOptions vars["TypesOfEvents"] = typeOfEvents vars["PostingUrgency"] = postingUrgency vars["WebcastPurpose"] = webcastPurpose vars["IntendedAudience"] = intendedAudience vars["SubjectMatter"] = subjectMatter vars["ConsentFormURL"] = self._WebcastRequestOptions["ConsentFormURL"].getValue() return vars
def testFossilizeIterableWrapper(self): "Iterable wrapper (legacy PersistentList, etc...)" s1 = SimpleClass(10, 20, 'foo') iterWrap = IterableWrapper(s1) self.assertEquals(fossilize(iterWrap), [{'_fossil': 'simpleFossil1', 'c': 'FOO', 'b': 20, '_type': 'SimpleClass'}])
def _addMaterialType(self, text, user): from MaKaC.common.fossilize import fossilize from MaKaC.fossils.conference import ILocalFileExtendedFossil, ILinkFossil Logger.get('requestHandler').debug('Adding %s - request %s' % (self._uploadType, request)) mat, newlyCreated = self._getMaterial() # if the material still doesn't exist, create it if newlyCreated: protectedAtResourceLevel = False else: protectedAtResourceLevel = True resources = [] assert self._uploadType == "file" for fileEntry in self._files: resource = LocalFile() resource.setFileName(fileEntry["fileName"]) resource.setFilePath(fileEntry["filePath"]) resource.setDescription(self._description) if self._displayName == "": resource.setName(resource.getFileName()) else: resource.setName(self._displayName) resources.append(resource) status = "OK" info = resources # forcedFileId - in case there is a conflict, use the file that is # already stored repoIDs = [] for i, resource in enumerate(resources): if self._repositoryIds: mat.addResource(resource, forcedFileId=self._repositoryIds[i]) else: mat.addResource(resource, forcedFileId=None) # store the repo id, for files if isinstance(resource, LocalFile) and self._repositoryIds is None: repoIDs.append(resource.getRepositoryId()) if protectedAtResourceLevel: protectedObject = resource else: protectedObject = mat mat.setHidden(self._visibility) mat.setAccessKey(self._password) protectedObject.setProtection(self._statusSelection) for principal in map(principal_from_fossil, self._userList): protectedObject.grantAccess(principal) if self._repositoryIds is None: self._repositoryIds = repoIDs return mat, status, fossilize(info, {"MaKaC.conference.Link": ILinkFossil, "MaKaC.conference.LocalFile": ILocalFileExtendedFossil})
def create_json_error_answer(e): responseBody = { "version": "1.1", "result": None, "error": None } try: responseBody["error"] = fossilize(e) except NonFossilizableException: from MaKaC.errors import MaKaCError responseBody["error"] = fossilize(MaKaCError(e.message)) except Exception, e2: responseBody["error"] = {'code': '', 'message': str(e2)} from MaKaC.common.logger import Logger Logger.get('dev').exception('Exception occurred while fossilizing: {0}'.format(str(e2)))
def _getAnswer( self): ph = PrincipalHolder() for user in self._userList: pr = ph.getById(user["id"]) if pr != None: self._wm.addManager(pr) return fossilize(self._wm.getManagers())
def process(): responseBody = { 'version': '1.1', 'error': None, 'result': None } requestBody = None try: # init/clear fossil cache clearCache() # read request try: requestBody = request.get_json() Logger.get('rpc').info('json rpc request. request: {0}'.format(requestBody)) except BadRequest: raise RequestError('ERR-R1', 'Invalid mime-type.') if not requestBody: raise RequestError('ERR-R2', 'Empty request.') if 'id' in requestBody: responseBody['id'] = requestBody['id'] # run request responseBody['result'] = ServiceRunner().invokeMethod(str(requestBody['method']), requestBody.get('params', [])) except CausedError as e: try: errorInfo = fossilize(e) except NonFossilizableException as e2: # catch Exceptions that are not registered as Fossils # and log them errorInfo = {'code': '', 'message': str(e2)} Logger.get('dev').exception('Exception not registered as fossil') # NoReport errors (i.e. not logged in) shouldn't be logged if not isinstance(e, NoReportError): Logger.get('rpc').exception('Service request failed. ' 'Request text:\r\n{0}\r\n\r\n'.format(requestBody)) if requestBody: params = requestBody.get('params', []) Sanitization._escapeHTML(params) errorInfo["requestInfo"] = { 'method': str(requestBody['method']), 'params': params, 'origin': str(requestBody.get('origin', 'unknown')) } Logger.get('rpc').debug('Arguments: {0}'.format(errorInfo['requestInfo'])) responseBody['error'] = errorInfo try: jsonResponse = dumps(responseBody, ensure_ascii=True) except UnicodeError: Logger.get('rpc').exception('Problem encoding JSON response') # This is to avoid exceptions due to old data encodings (based on iso-8859-1) responseBody['result'] = fix_broken_obj(responseBody['result']) jsonResponse = encode(responseBody) return app.response_class(jsonResponse, mimetype='application/json')
def testFossilizeDict(self): "Fossilize using a dictionary of interfaces" s1 = SimpleClass(10, 20, 'foo') d1 = DerivedClass(10, 50, 'bar') self.assertEquals(fossilize([s1, d1], {"indico.tests.python.unit.MaKaC_tests.common_tests.fossilize_test.SimpleClass": ISimpleFossil2Fossil, "indico.tests.python.unit.MaKaC_tests.common_tests.fossilize_test.DerivedClass": ISimpleFossil1Fossil}), [s1.fossilize(ISimpleFossil2Fossil), d1.fossilize(ISimpleFossil1Fossil)])
def testFossilizeList(self): "Fossilize list of fossilizable classes" d1 = SimpleClass(1, 'a', 'aaa') d2 = SimpleClass(2, 'b', 'bbb') l = [d1, d2] self.assertEquals(fossilize(l, ISimpleFossil1Fossil), [{'_type':'SimpleClass', '_fossil':'simpleFossil1', 'b': 'a', 'c': 'AAA'}, {'_type':'SimpleClass', '_fossil':'simpleFossil1', 'b': 'b', 'c': 'BBB'}] )
def _getAnswer(self): ph = PrincipalHolder() user = ph.getById(self._userId) if user != None: self._group.removeMember(user) else: raise ServiceError("ER-U0", _("Cannot find user with id %s") % self._userId) return fossilize(self._group.getMemberList())
def _getAnswer( self): ph = PrincipalHolder() pr = ph.getById(self._userId) if pr != None: self._wm.removeManager(pr) elif not self._wm.removeManagerById(self._userId): raise ServiceError("ER-U0", _("Cannot find user with id %s") % self._userId) return fossilize(self._wm.getManagers())
def _getResult(self, module): if module.hasObject(self._obj): raise ServiceError("ERR-O3", "Object is already in the list!") module.addObject(self._obj, self._objWeight, datetime.timedelta(days=self._objDelta)) return fossilize(module.getObjectList()[-1], IObservedObjectFossil);
def getVars(self): vars = wcomponents.WTemplated.getVars(self) vars["Conference"] = self._conf csbm = Catalog.getIdx("cs_bookingmanager_conference").get(self._conf.getId()) vars["CSBM"] = csbm allManagers = fossilize(csbm.getAllManagers(), IAvatarFossil) vars["AllManagers"] = sorted(allManagers, cmp = UserComparator.cmpUsers) return vars
def getVars(self): vars = wcomponents.WTemplated.getVars(self) vars["Conference"] = self._conf csbm = self._conf.getCSBookingManager() vars["CSBM"] = csbm allManagers = fossilize(csbm.getAllManagers(), IAvatarFossil) vars["AllManagers"] = sorted(allManagers, cmp = UserComparator.cmpUsers) return vars
def testFossilizeWithAttributes(self): """ Using attributes instead of getters """ s1 = SimpleClass(10, 20, 'foo') d1 = DerivedClass(10, 50, 'bar') self.assertEquals(s1.fossilize(IAttributeFossil), {'_type':'SimpleClass', '_fossil':'attribute', "a": 10, "b": 20, "c":"foo"}) self.assertEquals(fossilize(d1, IAttributeFossil), {'_type':'DerivedClass', '_fossil':'attribute', "a": 10, "b": 50, "c":"bar"})
def _getAnswer(self): user = User.get(self._userId) if user is not None: user.is_admin = False admins = User.find(is_admin=True, is_deleted=False).order_by(User.first_name, User.last_name).all() return fossilize([u.as_avatar for u in admins])
def _getAnswer(self): ah = AvatarHolder() for user in self._userList: if user["id"] != None: self._conf.getAbstractMgr().addAuthorizedSubmitter(ah.getById(user["id"])) else: raise ServiceError("ERR-U0", _("User does not exist.")) return fossilize(self._conf.getAbstractMgr().getAuthorizedSubmitterList())
def _getAnswer(self): ph = PrincipalHolder() for user in self._userList: principal = ph.getById(user["id"]) if principal is None: raise NoReportError(_("The user that you are trying to add does not exist anymore in the database")) self._group.addMember(principal) return fossilize(self._group.getMemberList())
def _getConvenerList(self): result = [] for convener in self._session.getConvenerList(): convFossil = fossilize(convener) convFossil["isManager"] = convener.isSessionManager() convFossil["isCoordinator"] = convener.isSessionCoordinator() result.append(convFossil) return result
def serialize_event_info(event): conf = event.as_legacy event_info = fossilize(conf, IConferenceEventInfoFossil, tz=conf.tz) event_info['sessions'] = { sess.id: serialize_session(sess) for sess in event.sessions } return event_info