예제 #1
0
class UpdatePassportHook(EventBaseHook):
    PREFIX = "api"
    RE = r'(?P<event>[\w\s]+)/registrant/(?P<registrant_id>[\w\s]+)/updatepassport'
    METHOD_NAME = 'api_update_passport'
    NO_CACHE = True
    COMMIT = True
    HTTP_POST = True

    def _getParams(self):
        super(UpdatePassportHook, self)._getParams()
        raw_passport_info = str(get_query_parameter(self._queryParams, ["passport_info"]))
        self._passport_info = json.loads(raw_passport_info,object_hook=ascii_encode_dict)
        self._secret = get_query_parameter(self._queryParams, ["secret"])
        registrant_id = self._pathParams["registrant_id"]
        self._conf = ConferenceHolder().getById(self._pathParams['event'])
        self._registrant = self._conf.getRegistrantById(registrant_id)

    def _hasAccess(self, aw):
        return (self._conf.canManageRegistration(aw.getUser()) or self._conf.canModify(aw)) \
            and self._secret == self._registrant.getCheckInUUID()

    def api_update_passport(self, aw):
        try:
            self._registrant.updateFromPassportScan(self._passport_info)
            return {"status": "true"}
        except Exception as e:
            return {"status": "false"}
예제 #2
0
파일: api.py 프로젝트: svdoever/indico
 def _checkParams(self):
     event = ConferenceHolder().getById(request.view_args['event_id'], True)
     if event is None:
         raise NotFound("No such event")
     if not event.canManageRegistration(request.oauth.user):
         raise Forbidden()
     self.event = event
예제 #3
0
 def _getParams(self):
     super(CheckInHook, self)._getParams()
     self._check_in = get_query_parameter(self._queryParams, ["checked_in"]) == "yes"
     self._secret = get_query_parameter(self._queryParams, ["secret"])
     registrant_id = self._pathParams["registrant_id"]
     self._conf = ConferenceHolder().getById(self._pathParams['event'])
     self._registrant = self._conf.getRegistrantById(registrant_id)
예제 #4
0
class RHChatSeeLogs(RHChatModifBase):
    """ For the conference modification"""
    _url = wrapUH(UHConfModifChatSeeLogs)

    def _checkParams(self, params):
        RHChatModifBase._checkParams(self, params)
        self._conf = ConferenceHolder().getById(params['confId'])
        self._chatroom = DBHelpers.getChatroom(params['chatroom'])
        self._sdate = params['sdate'] if params.has_key('sdate') else None
        self._edate = params['edate'] if params.has_key('edate') else None
        self._forEvent = bool(
            params['forEvent']) if params.has_key('forEvent') else None
        self._getAll = not self._sdate and not self._edate and not self._forEvent

    def _process(self):
        if self._getAll:
            url = LogLinkGenerator(self._chatroom).generate()
        elif self._forEvent:
            url = LogLinkGenerator(self._chatroom).generate(
                str(self._conf.getStartDate().date()),
                str(self._conf.getEndDate().date()))
        else:
            url = LogLinkGenerator(self._chatroom).generate(
                self._sdate, self._edate)

        req = urllib2.Request(url, None, {'Accept-Charset': 'utf-8'})
        document = urllib2.urlopen(req).read()
        if document is '':
            raise MaKaCError('No logs were found for these dates')
        return document
예제 #5
0
class RegistrantsHook(EventBaseHook):
    RE = r'(?P<event>[\w\s]+)/registrants'
    METHOD_NAME = 'export_registrants'
    NO_CACHE = True

    def _getParams(self):
        super(RegistrantsHook, self)._getParams()
        self._conf_id = self._pathParams['event']
        self._conf = ConferenceHolder().getById(self._conf_id)

    def _hasAccess(self, aw):
        return self._conf.canManageRegistration(aw.getUser()) or self._conf.canModify(aw)

    def export_registrants(self, aw):
        registrants = self._conf.getRegistrantsList()
        registrant_list = []
        for registrant in registrants:
            reg = {
                "registrant_id": registrant.getId(),
                "checked_in": registrant.isCheckedIn(),
                "full_name": registrant.getFullName(title=True, firstNameFirst=True),
                "checkin_secret": registrant.getCheckInUUID(),
            }
            regForm = self._conf.getRegistrationForm()
            reg["personal_data"] = regForm.getPersonalData().getRegistrantValues(registrant)
            registrant_list.append(reg)
        return {"registrants": registrant_list}
예제 #6
0
def cacheDay(dest, day):
    """
    Cache a day, by calling wget in "mirror" mode
    """

    dbi = DBMgr.getInstance()
    dbi.startRequest()

    index = {}

    calIdx = IndexesHolder().getIndex('calendar')

    objs = calIdx.getObjectsInDay(day)

    for confId in objs:

	if confId == '': continue

        obj = ConferenceHolder().getById(confId)
        url = str(urlHandlers.UHConferenceDisplay.getURL(obj))

        savedDirs = re.match(r'http:\/\/(.*)', url).group(1).split('/')

        print "Calling wget for %s..." % url
        os.system(WGET_COMMAND % (confId, url,
                                  os.path.join(dest, confId),
                                  savedDirs[0]))

        print "done!"

        index[confId] = (os.path.join(confId,*savedDirs)+'.html', obj.getTitle())

    dbi.endRequest(False)

    return index
예제 #7
0
def buildCatalog():
    #rc.init_catalog() # Forces index rebuild
    cm = CategoryManager()
    ch = ConferenceHolder()
    totnum = len(ch.getValuesToList())
    curnum = 0
    curper = 0
    
    startFrom = 0
    
    print "Events found:", totnum
        
    for c in ch.getValuesToList():
        if curnum >= startFrom:
            print "___________",curnum,".......confid=",c.getId()                
            rc.fullIndex(c) 
            transaction.commit()
        curnum += 1

        per = int(float(curnum)/float(totnum)*100)
        if per != curper:
            curper = per
            print str(per)+"%"
        
    # Pack it when finished
    print "Packing...."
    db.DBMgr.getInstance().pack()
    print "Done."
예제 #8
0
    def setUp(self):
        super(TestAbstractRecovery, self).setUp()

        self._startDBReq()

        # Get dummy user
        ah = AvatarHolder()
        avatar = ah.getById(0)
        setattr(self, '_avatar', avatar)

        # Create a conference
        category = conference.CategoryManager().getById('0')
        self._conf = category.newConference(self._avatar)
        self._conf.setTimezone('UTC')
        sd = datetime(2011, 11, 1, 10, 0, tzinfo=timezone('UTC'))
        ed = datetime(2011, 11, 1, 18, 0, tzinfo=timezone('UTC'))
        self._conf.setDates(sd, ed)
        ch = ConferenceHolder()
        ch.add(self._conf)

        self._track1 = self._conf.newTrack()
        self._track2 = self._conf.newTrack()
        self._track3 = self._conf.newTrack()
        self._abstract = self._conf.getAbstractMgr().newAbstract(avatar)
        self._abstract.addTrack(self._track1)
        self._abstract.addTrack(self._track2)
        self._abstract.addTrack(self._track3)

        self._stopDBReq()
예제 #9
0
class UpdatePictureHook(EventBaseHook):
    PREFIX = "api"
    RE = r'(?P<event>[\w\s]+)/registrant/(?P<registrant_id>[\w\s]+)/updatepicture'
    METHOD_NAME = 'api_update_picture'
    NO_CACHE = True
    COMMIT = True
    HTTP_POST = True

    def _getParams(self):
        super(UpdatePictureHook, self)._getParams()
        self._picture_payload = get_query_parameter(self._queryParams, ["picture_uri"])
        self._secret = get_query_parameter(self._queryParams, ["secret"])
        registrant_id = self._pathParams["registrant_id"]
        self._conf = ConferenceHolder().getById(self._pathParams['event'])
        self._registrant = self._conf.getRegistrantById(registrant_id)

    def _hasAccess(self, aw):
        return (self._conf.canManageRegistration(aw.getUser()) or self._conf.canModify(aw)) \
            and self._secret == self._registrant.getCheckInUUID()

    def api_update_picture(self, aw):
        try:
            from indico.util.data_uri import DataURI
            uri = DataURI(self._picture_payload)
            path = self._registrant.getPicture().getFilePath()
            data = uri.data
            _file = open(path,'w')
            _file.write(data)
            _file.close()
            return {"status": "true"}
        except:
            return {"status": "false"}
예제 #10
0
def _event_or_shorturl(confId, shorturl_namespace=False, ovw=False):
    from MaKaC.conference import ConferenceHolder
    from MaKaC.common.url import ShortURLMapper

    with DBMgr.getInstance().global_connection():
        ch = ConferenceHolder()
        su = ShortURLMapper()
        if ch.hasKey(confId):
            # For obvious reasons an event id always comes first.
            # If it's used within the short url namespace we redirect to the event namespace, otherwise
            # we call the RH to display the event
            if shorturl_namespace:
                url = UHConferenceDisplay.getURL(ch.getById(confId))
                func = lambda: redirect(url)
            else:
                params = request.args.to_dict()
                params['confId'] = confId
                if ovw:
                    params['ovw'] = 'True'
                func = lambda: conferenceDisplay.RHConferenceDisplay(None).process(params)
        elif (shorturl_namespace or app.config['INDICO_COMPAT_ROUTES']) and su.hasKey(confId):
            if shorturl_namespace:
                # Correct namespace => redirect to the event
                url = UHConferenceDisplay.getURL(su.getById(confId))
                func = lambda: redirect(url)
            else:
                # Old event namespace => 301-redirect to the new shorturl first to get Google etc. to update it
                url = url_for('.shorturl', confId=confId)
                func = lambda: redirect(url, 301)
        else:
            raise NotFound(
                _('The specified event with id or tag "%s" does not exist or has been deleted') % confId)

    return func()
예제 #11
0
def displayList(res, startdate, enddate, repeat, displayCateg, tz):
    text = ""
    ch = ConferenceHolder()
    day = startdate
    days = {}
    found = {}
    while day <= enddate:
        for confId in res:
            c = ch.getById(confId)
            if day.date() >= c.getAdjustedStartDate(tz).date() and day.date(
            ) <= c.getAdjustedEndDate(tz).date() and (repeat == 1
                                                      or not found.has_key(c)):
                if not days.has_key(day):
                    days[day] = []
                days[day].append(c)
                found[c] = 1
        day = day + datetime.timedelta(days=1)
    day = startdate
    while day <= enddate:
        if days.has_key(day):
            text += "<br><b>%s</b>" % day.strftime("%A %B %d, %Y")
            days[day].sort(lambda x, y: cmp(
                x.calculateDayStartTime(day).time(),
                y.calculateDayStartTime(day).time()))
            for c in days[day]:
                text += displayConf(c, displayCateg, day, tz)
        day = day + datetime.timedelta(days=1)
    return text
예제 #12
0
def displayList(res,tz):
  text = """
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<HTML>
<HEAD>
   <TITLE>Forthcoming Seminars</TITLE>
   <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</HEAD>
<BODY LINK="#0000FF" VLINK="#800080">

<H1>
<A HREF="http://www.cern.ch/"><IMG SRC="http://www.cern.ch/CommonImages/Banners/CERNHeadE.gif" ALT="CERN European Laboratory for Particle Physics" NOSAVE BORDER=0 HEIGHT=20 WIDTH=411></A></H1>

<H2>
FORTHCOMING SEMINARS / SEMINAIRES A VENIR</H2>
"""
  ch = ConferenceHolder()
  curDate = None
  for confId in res:
    c = ch.getById(confId)
    if curDate!=c.getAdjustedStartDate(tz):
      curDate = c.getAdjustedStartDate(tz)
      text += "<hr>%s<br>" % curDate.strftime("%A %B %d, %Y")
    text += displayConf(c,tz)
  return text
예제 #13
0
def searchUsers(surName="", name="", organisation="", email="", conferenceId=None, exactMatch=True, searchExt=False):

    if surName != "" or name != "" or organisation != "" or email != "":
        # build criteria
        criteria = {
            "surName": surName,
            "name": name,
            "organisation": organisation,
            "email": email
        }
        # search users
        people = AvatarHolder().match(criteria, exact=exactMatch, searchInAuthenticators=searchExt)

        # search authors
        if conferenceId is not None:
            conference = ConferenceHolder().getById(conferenceId)
            authorIndex = conference.getAuthorIndex()
            authors = authorIndex.match(criteria, exact=exactMatch)
            # merge with users
            users = people
            people = []
            emails = []
            for user in users:
                people.append(user)
                emails.extend(user.getEmails())
            for author in authors:
                if author.getEmail() not in emails:
                    people.append(author)
        return people
    else:
        return []
예제 #14
0
파일: rh.py 프로젝트: jbenito3/indico
class RHChatSeeLogs(RHChatModifBase):
    """For the conference modification"""

    def _checkParams(self, params):
        RHChatModifBase._checkParams(self, params)
        self._conf = ConferenceHolder().getById(params["confId"])
        self._chatroom = DBHelpers.getChatroom(params["chatroom"])
        self._sdate = params["sdate"] if params.has_key("sdate") else None
        self._edate = params["edate"] if params.has_key("edate") else None
        self._forEvent = bool(params["forEvent"]) if params.has_key("forEvent") else None
        self._getAll = not self._sdate and not self._edate and not self._forEvent

    def _process(self):
        if self._getAll:
            url = LogLinkGenerator(self._chatroom).generate()
        elif self._forEvent:
            url = LogLinkGenerator(self._chatroom).generate(
                str(self._conf.getStartDate().date()), str(self._conf.getEndDate().date())
            )
        else:
            url = LogLinkGenerator(self._chatroom).generate(self._sdate, self._edate)

        req = urllib2.Request(url, None, {"Accept-Charset": "utf-8"})
        document = urllib2.urlopen(req).read()
        if document is "":
            raise MaKaCError("No logs were found for these dates")
        return document
예제 #15
0
파일: event.py 프로젝트: OmeGak/indico
def create_event(monkeypatch, monkeypatch_methods, dummy_user, dummy_category, db):
    """Returns a callable which lets you create dummy events"""
    monkeypatch_methods('MaKaC.conference.ConferenceHolder', MockConferenceHolder)
    monkeypatch.setattr('MaKaC.conference.Conference', MockConference)  # for some isinstance checks

    _events = []
    ch = ConferenceHolder()

    def _create_event(id_=None, legacy=False, **kwargs):
        conf = MockConference()
        # we specify `acl_entries` so SA doesn't load it when accessing it for
        # the first time, which would require no_autoflush blocks in some cases
        now = now_utc(exact=False)
        kwargs.setdefault('type_', EventType.meeting)
        kwargs.setdefault('title', u'dummy#{}'.format(id_) if id_ is not None else u'dummy')
        kwargs.setdefault('start_dt', now)
        kwargs.setdefault('end_dt', now + timedelta(hours=1))
        kwargs.setdefault('timezone', 'UTC')
        kwargs.setdefault('category', dummy_category)
        conf.as_event = Event(id=id_, creator=dummy_user, acl_entries=set(), **kwargs)
        db.session.flush()
        conf.id = str(conf.as_event.id)
        ch.add(conf)
        _events.append(conf)
        return conf if legacy else conf.as_event

    yield _create_event

    for event in _events:
        ch.remove(event)
예제 #16
0
    def _getAnswer(self):
        im = indexes.IndexesHolder()
        ch = ConferenceHolder()
        calIdx = im.getIndex("calendar")
        evtIds = calIdx.getObjectsIn(self._sDate, self._eDate)

        evtsByCateg = {}
        for evtId in evtIds:
            try:
                evt = ch.getById(evtId)
                categs = evt.getOwnerList()
                categname = categs[0].getName()
                if not evtsByCateg.has_key(categname):
                    evtsByCateg[categname] = []
                evtsByCateg[categname].append(
                    (
                        evt.getTitle().strip(),
                        evt.getAdjustedStartDate().strftime("%d/%m/%Y %H:%M "),
                        evt.getAdjustedEndDate().strftime("%d/%m/%Y %H:%M "),
                        evt.getTimezone(),
                    )
                )

            except Exception:
                continue
        return evtsByCateg
예제 #17
0
파일: registration.py 프로젝트: Ictp/indico
class RegistrantHook(EventBaseHook):
    RE = r'(?P<event>[\w\s]+)/registrant/(?P<registrant_id>[\w\s]+)'
    NO_CACHE = True

    def _getParams(self):
        super(RegistrantHook, self)._getParams()
        self._secret = get_query_parameter(self._queryParams, ["secret"])
        self._conf = ConferenceHolder().getById(self._pathParams['event'])
        registrant_id = self._pathParams["registrant_id"]
        self._registrant = self._conf.getRegistrantById(registrant_id)
        self._type = "registrant"

    def _hasAccess(self, aw):
        return self._conf.canManageRegistration(aw.getUser()) and self._secret == self._registrant.getCheckInUUID()

    def export_registrant(self, aw):
        registration_date = format_datetime(self._registrant.getAdjustedRegistrationDate(), format="short")
        checkin_date = format_datetime(self._registrant.getAdjustedCheckInDate(), format="short")
        self._registrant.getPayed()
        result = {
            "registrant_id": self._registrant.getId(),
            "full_name": self._registrant.getFullName(title=True, firstNameFirst=True),
            "checked_in": self._registrant.isCheckedIn(),
            "checkin_date": checkin_date if self._registrant.isCheckedIn() else None,
            "registration_date": registration_date,
            "payed": self._registrant.getPayed() if self._conf.getModPay().isActivated() else None,
            "pay_amount": self._registrant.getTotal() if self._conf.getModPay().isActivated() else None
        }
        regForm = self._conf.getRegistrationForm()
        personalData = regForm.getPersonalData().getRegistrantValues(self._registrant)
        result.update(personalData)
        return result
예제 #18
0
    def setUp(self):
        super(TestNotification, self).setUp()

        self._startDBReq()

        # Get dummy user
        ah = AvatarHolder()
        avatar = ah.getById(0)
        setattr(self, '_avatar', avatar)

        # Create a conference
        category = conference.CategoryManager().getById('0')
        self._conf = category.newConference(self._avatar)
        self._conf.setTimezone('UTC')
        sd = datetime(2011, 11, 1, 10, 0, tzinfo=timezone('UTC'))
        ed = datetime(2011, 11, 1, 18, 0, tzinfo=timezone('UTC'))
        self._conf.setDates(sd, ed)
        ch = ConferenceHolder()
        ch.add(self._conf)

        self._track1 = self._conf.newTrack()
        self._track2 = self._conf.newTrack()
        self._track3 = self._conf.newTrack()
        absMgr = self._conf.getAbstractMgr()
        self._contribTypeOral = "oral"
        self._contribTypePoster = "poster"

        self._stopDBReq()
예제 #19
0
    def _indexQuery(self):
        self.cdbmgr.startRequest()

        fromConfId = self.random.choice(self.validConfIds)
        toConfId = self.random.choice(self.validConfIds)
        if int(toConfId) < int(fromConfId):
            fromConfId, toConfId = toConfId, fromConfId
        fromTitle = ConferenceHolder().getById(fromConfId).getTitle()
        toTitle = ConferenceHolder().getById(toConfId).getTitle()

        params = {
            "page": self.random.randint(0, 10),
            "resultsPerPage": 50,
            "indexName": 'all',
            "viewBy": 'conferenceTitle',
            "orderBy": "descending",
            "fromTitle": fromTitle,
            "toTitle": toTitle,
            "sinceDate": '',
            "toDate": '',
            "fromDays": '',
            "toDays": '',
            "onlyPending": False,
            "categoryId": '',
            "conferenceId": ''
        }

        service = CollaborationBookingIndexQuery(params)
        service._checkParams()
        service._getAnswer()

        self.cdbmgr.endRequest()
예제 #20
0
class SetPaidHook(EventBaseHook):
    PREFIX = "api"
    RE = r'(?P<event>[\w\s]+)/registrant/(?P<registrant_id>[\w\s]+)/pay'
    METHOD_NAME = 'api_pay'
    NO_CACHE = True
    COMMIT = True
    HTTP_POST = True

    def _getParams(self):
        super(SetPaidHook, self)._getParams()
        self.auth_key = get_query_parameter(self._queryParams, ["auth_key"])
        self.is_paid = get_query_parameter(self._queryParams, ["is_paid"]) == "yes"
        registrant_id = self._pathParams["registrant_id"]
        self._conf = ConferenceHolder().getById(self._pathParams['event'])
        self._registrant = self._conf.getRegistrantById(registrant_id)
        if not payment_event_settings.get(self._conf, 'enabled'):
            raise HTTPAPIError('E-payment is not enabled')

    def _hasAccess(self, aw):
        return self._conf.canManageRegistration(aw.getUser()) or self._conf.canModify(aw)

    def api_pay(self, aw):
        action = TransactionAction.complete if self._isPayed == '1' else TransactionAction.cancel
        register_transaction(registrant=self._registrant,
                             amount=self._registrant.getTotal(),
                             currency=self._registrant.getCurrency(),
                             action=action)
        return {
            "paid": self._registrant.getPayed(),
            "amount_paid": self._registrant.getTotal()
        }
예제 #21
0
    def setUp(self):
        super(TestNotification, self).setUp()

        self._startDBReq()

        # Get dummy user
        ah = AvatarHolder()
        avatar = ah.getById(0)
        setattr(self, '_avatar', avatar)

        # Create a conference
        category = conference.CategoryManager().getById('0')
        self._conf = category.newConference(self._avatar)
        self._conf.setTimezone('UTC')
        sd = datetime(2011, 11, 1, 10, 0, tzinfo=timezone('UTC'))
        ed = datetime(2011, 11, 1, 18, 0, tzinfo=timezone('UTC'))
        self._conf.setDates(sd, ed)
        ch = ConferenceHolder()
        ch.add(self._conf)

        self._track1 = self._conf.newTrack()
        self._track2 = self._conf.newTrack()
        self._track3 = self._conf.newTrack()
        absMgr = self._conf.getAbstractMgr()
        self._contribTypeOral = "oral"
        self._contribTypePoster = "poster"

        self._stopDBReq()
예제 #22
0
class CheckInHook(EventBaseHook):
    PREFIX = "api"
    RE = r'(?P<event>[\w\s]+)/registrant/(?P<registrant_id>[\w\s]+)/checkin'
    METHOD_NAME = 'api_checkin'
    NO_CACHE = True
    COMMIT = True
    HTTP_POST = True

    def _getParams(self):
        super(CheckInHook, self)._getParams()
        self._check_in = get_query_parameter(self._queryParams, ["checked_in"]) == "yes"
        self._secret = get_query_parameter(self._queryParams, ["secret"])
        registrant_id = self._pathParams["registrant_id"]
        self._conf = ConferenceHolder().getById(self._pathParams['event'])
        self._registrant = self._conf.getRegistrantById(registrant_id)

    def _hasAccess(self, aw):
        return (self._conf.canManageRegistration(aw.getUser()) or self._conf.canModify(aw)) \
            and self._secret == self._registrant.getCheckInUUID()

    def api_checkin(self, aw):
        self._registrant.setCheckedIn(self._check_in)
        checkin_date = format_datetime(self._registrant.getAdjustedCheckInDate(), format="short")

        return {
            "checked_in": self._check_in,
            "checkin_date": checkin_date if self._check_in else None
        }
예제 #23
0
 def _getParams(self):
     super(CollaborationExportHook, self)._getParams()
     self._conf = ConferenceHolder().getById(self._pathParams['confId'],
                                             True)
     if not self._conf:
         raise HTTPAPIError('Conference does not exist.',
                            apache.HTTP_BAD_REQUEST)
예제 #24
0
def create_event(monkeypatch, monkeypatch_methods, dummy_user, db):
    """Returns a callable which lets you create dummy events"""
    monkeypatch_methods('MaKaC.conference.ConferenceHolder',
                        MockConferenceHolder)
    monkeypatch.setattr('MaKaC.conference.Conference',
                        MockConference)  # for some isinstance checks

    _events = []
    ch = ConferenceHolder()

    def _create_event(id_=None, legacy=False):
        conf = MockConference()
        # we specify `acl_entries` so SA doesn't load it when accessing it for
        # the first time, which would require no_autoflush blocks in some cases
        conf.as_event = Event(id=id_, creator=dummy_user, acl_entries=set())
        db.session.flush()
        conf.id = str(conf.as_event.id)
        ch.add(conf)
        _events.append(conf)
        return conf if legacy else conf.as_event

    yield _create_event

    for event in _events:
        ch.remove(event)
예제 #25
0
파일: event.py 프로젝트: florv/indico
def create_event(monkeypatch, monkeypatch_methods, mocker, dummy_user, db):
    """Returns a callable which lets you create dummy events"""
    mocker.patch("MaKaC.conference.CategoryManager")
    monkeypatch_methods("MaKaC.conference.ConferenceHolder", MockConferenceHolder)
    monkeypatch.setattr("MaKaC.conference.Conference", MockConference)  # for some isinstance checks

    _events = []
    ch = ConferenceHolder()

    def _create_event(id_=None, legacy=False, **kwargs):
        conf = MockConference()
        # we specify `acl_entries` so SA doesn't load it when accessing it for
        # the first time, which would require no_autoflush blocks in some cases
        now = now_utc(exact=False)
        kwargs.setdefault("title", u"dummy#{}".format(id_) if id_ is not None else u"dummy")
        kwargs.setdefault("start_dt", now)
        kwargs.setdefault("end_dt", now + timedelta(hours=1))
        kwargs.setdefault("timezone", "UTC")
        conf.as_event = Event(id=id_, creator=dummy_user, acl_entries=set(), category_id=1, **kwargs)
        conf.as_event.category_chain = [1, 0]  # set after __init__ (setting category_id modifies it)
        db.session.flush()
        conf.id = str(conf.as_event.id)
        ch.add(conf)
        _events.append(conf)
        return conf if legacy else conf.as_event

    yield _create_event

    for event in _events:
        ch.remove(event)
예제 #26
0
파일: main.py 프로젝트: jbenito3/indico
def _event_or_shorturl(confId, shorturl_namespace=False, ovw=False):
    from MaKaC.conference import ConferenceHolder
    from MaKaC.common.url import ShortURLMapper

    with DBMgr.getInstance().global_connection():
        ch = ConferenceHolder()
        su = ShortURLMapper()
        if ch.hasKey(confId):
            # For obvious reasons an event id always comes first.
            # If it's used within the short url namespace we redirect to the event namespace, otherwise
            # we call the RH to display the event
            if shorturl_namespace:
                url = UHConferenceDisplay.getURL(ch.getById(confId))
                func = lambda: redirect(url)
            else:
                params = request.args.to_dict()
                params['confId'] = confId
                if ovw:
                    params['ovw'] = 'True'
                func = lambda: conferenceDisplay.RHConferenceDisplay(None).process(params)
        elif (shorturl_namespace or app.config['INDICO_COMPAT_ROUTES']) and su.hasKey(confId):
            if shorturl_namespace:
                # Correct namespace => redirect to the event
                url = UHConferenceDisplay.getURL(su.getById(confId))
                func = lambda: redirect(url)
            else:
                # Old event namespace => 301-redirect to the new shorturl first to get Google etc. to update it
                url = url_for('.shorturl', confId=confId)
                func = lambda: redirect(url, 301)
        else:
            raise NotFound(
                _('The specified event with id or tag "%s" does not exist or has been deleted') % confId)

    return func()
예제 #27
0
def displayList(res, tz):
    text = """
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<HTML>
<HEAD>
   <TITLE>Forthcoming Seminars</TITLE>
   <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</HEAD>
<BODY LINK="#0000FF" VLINK="#800080">

<H1>
<A HREF="http://www.cern.ch/"><IMG SRC="http://www.cern.ch/CommonImages/Banners/CERNHeadE.gif" ALT="CERN European Laboratory for Particle Physics" NOSAVE BORDER=0 HEIGHT=20 WIDTH=411></A></H1>

<H2>
FORTHCOMING SEMINARS / SEMINAIRES A VENIR</H2>
"""
    ch = ConferenceHolder()
    curDate = None
    for confId in res:
        c = ch.getById(confId)
        if curDate != c.getAdjustedStartDate(tz):
            curDate = c.getAdjustedStartDate(tz)
            text += "<hr>%s<br>" % curDate.strftime("%A %B %d, %Y")
        text += displayConf(c, tz)
    return text
예제 #28
0
파일: api.py 프로젝트: svdoever/indico
class RegistrantsHook(EventBaseHook):
    RE = r'(?P<event>[\w\s]+)/registrants'
    METHOD_NAME = 'export_registrants'
    NO_CACHE = True

    def _getParams(self):
        super(RegistrantsHook, self)._getParams()
        self._conf_id = self._pathParams['event']
        self._conf = ConferenceHolder().getById(self._conf_id)

    def _hasAccess(self, aw):
        return self._conf.canManageRegistration(aw.getUser()) or self._conf.canModify(aw)

    def export_registrants(self, aw):
        registrants = self._conf.getRegistrantsList()
        registrant_list = []
        for registrant in registrants:
            reg = {
                "registrant_id": registrant.getId(),
                "checked_in": registrant.isCheckedIn(),
                "full_name": registrant.getFullName(title=True, firstNameFirst=True),
                "checkin_secret": registrant.getCheckInUUID(),
            }
            regForm = self._conf.getRegistrationForm()
            reg["personal_data"] = regForm.getPersonalData().getRegistrantValues(registrant)
            registrant_list.append(reg)
        return {"registrants": registrant_list}
예제 #29
0
    def setUp(self):
        super(TestAbstractRecovery, self).setUp()

        self._startDBReq()

        # Get dummy user
        ah = AvatarHolder()
        avatar = ah.getById(0)
        setattr(self, '_avatar', avatar)

        # Create a conference
        category = conference.CategoryManager().getById('0')
        self._conf = category.newConference(self._avatar)
        self._conf.setTimezone('UTC')
        sd = datetime(2011, 11, 1, 10, 0, tzinfo=timezone('UTC'))
        ed = datetime(2011, 11, 1, 18, 0, tzinfo=timezone('UTC'))
        self._conf.setDates(sd, ed)
        ch = ConferenceHolder()
        ch.add(self._conf)

        self._track1 = self._conf.newTrack()
        self._track2 = self._conf.newTrack()
        self._track3 = self._conf.newTrack()
        self._abstract = self._conf.getAbstractMgr().newAbstract(avatar)
        self._abstract.addTrack(self._track1)
        self._abstract.addTrack(self._track2)
        self._abstract.addTrack(self._track3)

        self._stopDBReq()
예제 #30
0
def cacheDay(dest, day):
    """
    Cache a day, by calling wget in "mirror" mode
    """

    dbi = DBMgr.getInstance()
    dbi.startRequest()

    index = {}

    calIdx = IndexesHolder().getIndex('calendar')

    objs = calIdx.getObjectsInDay(day)

    for confId in objs:

	if confId == '': continue

        obj = ConferenceHolder().getById(confId)
        url = str(urlHandlers.UHConferenceDisplay.getURL(obj))

        savedDirs = re.match(r'http:\/\/(.*)', url).group(1).split('/')

        print "Calling wget for %s..." % url
        os.system(WGET_COMMAND % (confId, url,
                                  os.path.join(dest, confId),
                                  savedDirs[0]))

        print "done!"

        index[confId] = (os.path.join(confId,*savedDirs)+'.html', obj.getTitle())

    dbi.endRequest(False)

    return index
예제 #31
0
def buildCatalog():
    #rc.init_catalog() # Forces index rebuild
    cm = CategoryManager()
    ch = ConferenceHolder()
    totnum = len(ch.getValuesToList())
    curnum = 0
    curper = 0

    startFrom = 0

    print "Events found:", totnum

    for c in ch.getValuesToList():
        if curnum >= startFrom:
            print "___________", curnum, ".......confid=", c.getId()
            rc.fullIndex(c)
            transaction.commit()
        curnum += 1

        per = int(float(curnum) / float(totnum) * 100)
        if per != curper:
            curper = per
            print str(per) + "%"

    # Pack it when finished
    print "Packing...."
    db.DBMgr.getInstance().pack()
    print "Done."
예제 #32
0
    def setUp(self):
        super(TestAbstractSubmission, self).setUp()

        self._startDBReq()

        # Create few users
        ah = AvatarHolder()
        # Create dummy avatars in obj._avatarN
        self._avatars = []
        for i in xrange(1, 5):
            avatar = Avatar()
            avatar.setName("fake-%d" % i)
            avatar.setSurName("fake")
            avatar.setOrganisation("fake")
            avatar.setLang("en_GB")
            avatar.setEmail("*****@*****.**" % i)
            avatar.setId("fake-%d" % i)
            ah.add(avatar)
            self._avatars.append(avatar)
            setattr(self, '_avatar%d' % i, avatar)

        # Create a conference
        category = conference.CategoryManager().getById('0')
        self._conf = category.newConference(self._avatar1)
        self._conf.setTimezone('UTC')
        sd = datetime(2011, 11, 1, 10, 0, tzinfo=timezone('UTC'))
        ed = datetime(2011, 11, 1, 18, 0, tzinfo=timezone('UTC'))
        self._conf.setDates(sd, ed)
        ch = ConferenceHolder()
        ch.add(self._conf)

        self._stopDBReq()
예제 #33
0
파일: api.py 프로젝트: svdoever/indico
class SetPaidHook(EventBaseHook):
    PREFIX = "api"
    RE = r'(?P<event>[\w\s]+)/registrant/(?P<registrant_id>[\w\s]+)/pay'
    METHOD_NAME = 'api_pay'
    NO_CACHE = True
    COMMIT = True
    HTTP_POST = True

    def _getParams(self):
        super(SetPaidHook, self)._getParams()
        self.auth_key = get_query_parameter(self._queryParams, ["auth_key"])
        self.is_paid = get_query_parameter(self._queryParams, ["is_paid"]) == "yes"
        registrant_id = self._pathParams["registrant_id"]
        self._conf = ConferenceHolder().getById(self._pathParams['event'])
        self._registrant = self._conf.getRegistrantById(registrant_id)
        if not payment_event_settings.get(self._conf, 'enabled'):
            raise HTTPAPIError('E-payment is not enabled')

    def _hasAccess(self, aw):
        return self._conf.canManageRegistration(aw.getUser()) or self._conf.canModify(aw)

    def api_pay(self, aw):
        action = TransactionAction.complete if self._isPayed == '1' else TransactionAction.cancel
        register_transaction(registrant=self._registrant,
                             amount=self._registrant.getTotal(),
                             currency=self._registrant.getCurrency(),
                             action=action)
        return {
            "paid": self._registrant.getPayed(),
            "amount_paid": self._registrant.getTotal()
        }
예제 #34
0
class MaterialEntryRepozer(ConferenceEntryRepozer,RepozerMaterial):

    def __init__(self, fid=None):
        self._fid = fid
        self.confId, self.sessionId, self.talkId, self.materialId = self._fid.split("|") 
        self.ch = ConferenceHolder()
        conf = self.ch.getById(self.confId)
        self.matId, self.resId = self.materialId.split('/')
        if not(self.resId) or self.resId == 'not assigned': self.resId = '0'
        obj = None
        if self.talkId: # Material inside Talk
            if self.sessionId: # Talk inside Session
                s = conf.getSessionById(self.sessionId)
                obj = s.getContributionById(self.talkId)
            else: obj = conf.getContributionById(self.talkId)
        else: obj = conf
        self.mat = None
        if obj: self.mat = obj.getMaterialById(self.matId)        
        self.robj = None
        self.ext = ''
        if self.mat:
            self.res = self.mat.getResourceById(self.resId)
            self.robj = RepozerMaterial(self.res)
            self.ext = self.robj.ext
            
    def isVisible(self, user):
        # Only PUBLIC documents are Indexed
        return True
        
    def getMaterial(self):
        try:
            return self.robj
        except:
            return None
    
    def getTitle(self):
        if not(self.robj):
            return "- NO TITLE -"
        else:
            return self.robj.getTitle()
    
    def getDescription(self):
        return ''
                    
    def getStartDate(self, aw):
        return None

    def getEndDate(self, aw):
        return None
                
    def getTarget(self):
        return self.getMaterial()
        
    def getURL(self):
        suffix = ''
        if self.sessionId: suffix += '/session/' + self.sessionId
        if self.talkId: suffix += '/contribution/' + self.talkId
        suffix += '/material/' + self.materialId + self.ext            
        return self.ch.getById(self.confId).getURL().replace('/e/','/event/') + suffix
예제 #35
0
 def export_timetable(self, aw):
     ch = ConferenceHolder()
     d = {}
     for cid in self._idList:
         conf = ch.getById(cid)
         d[cid] = ScheduleToJson.process(conf.getSchedule(), self._tz.tzname(None),
                                         aw, days=None, mgmtMode=False)
     return d
예제 #36
0
 def call(self):
     cf = ConferenceHolder()
     for conf in cf.getValuesToList():
         csbm = conf.getCSBookingManager()
         csbm._bookings = {}
         csbm._bookingsByType = {}
     collaborationIndex = IndexesHolder().getById("collaboration")
     collaborationIndex.cleanAll()
예제 #37
0
 def _checkParams(self, params):
     RHChatModifBase._checkParams(self, params)
     self._conf = ConferenceHolder().getById(params['confId'])
     self._chatroom = DBHelpers.getChatroom(params['chatroom'])
     self._sdate = params['sdate'] if 'sdate' in params else None
     self._edate = params['edate'] if 'edate' in params else None
     self._forEvent = params.get('forEvent') == '1'
     self._getAll = not self._sdate and not self._edate and not self._forEvent
예제 #38
0
 def call(self):
     cf = ConferenceHolder()
     for conf in cf.getValuesToList():
         csbm = Catalog.getIdx("cs_bookingmanager_conference").get(conf.getId())
         csbm._bookings = {}
         csbm._bookingsByType = {}
     collaborationIndex = IndexesHolder().getById("collaboration")
     collaborationIndex.cleanAll()
예제 #39
0
def migrateConferences(catalog):
    print "Migrating Conferences...",
    ch=ConferenceHolder()
    count=0
    for conf in catalog.dump():
        ch._getIdx()[conf.getId()]=conf
        count+=1
    print "[Done:%s]"%count
예제 #40
0
 def _getParams(self):
     super(UpdatePassportHook, self)._getParams()
     raw_passport_info = str(get_query_parameter(self._queryParams, ["passport_info"]))
     self._passport_info = json.loads(raw_passport_info,object_hook=ascii_encode_dict)
     self._secret = get_query_parameter(self._queryParams, ["secret"])
     registrant_id = self._pathParams["registrant_id"]
     self._conf = ConferenceHolder().getById(self._pathParams['event'])
     self._registrant = self._conf.getRegistrantById(registrant_id)
예제 #41
0
def migrateConferences(catalog):
    print "Migrating Conferences...",
    ch = ConferenceHolder()
    count = 0
    for conf in catalog.dump():
        ch._getIdx()[conf.getId()] = conf
        count += 1
    print "[Done:%s]" % count
예제 #42
0
파일: api.py 프로젝트: jbenito3/indico
 def export_timetable(self, aw):
     ch = ConferenceHolder()
     d = {}
     for cid in self._idList:
         conf = ch.getById(cid)
         d[cid] = ScheduleToJson.process(conf.getSchedule(), self._tz.tzname(None),
                                        aw, days = None, mgmtMode = False)
     return d
예제 #43
0
 def call(self):
     cf = ConferenceHolder()
     for conf in cf.getValuesToList():
         csbm = conf.getCSBookingManager()
         csbm._bookings = {}
         csbm._bookingsByType = {}
     collaborationIndex = IndexesHolder().getById("collaboration")
     collaborationIndex.cleanAll()
예제 #44
0
 def call(self):
     cf = ConferenceHolder()
     for conf in cf.getValuesToList():
         csbm = Catalog.getIdx("cs_bookingmanager_conference").get(conf.getId())
         csbm._bookings = {}
         csbm._bookingsByType = {}
     collaborationIndex = IndexesHolder().getById("collaboration")
     collaborationIndex.cleanAll()
예제 #45
0
def buildCatalog():
    rc.init_catalog() # Forces index rebuild
    cm = CategoryManager()
    ch = ConferenceHolder()
    totnum = len(ch.getValuesToList())
    curnum = 0
    curper = 0
    
    startFrom = 0
    
    print "Events found:", totnum
        
    for c in ch.getValuesToList():
        if curnum >= startFrom:
            #if c and c.getId() == 'a12226':    
            print curnum,".......confid=",c.getId()
            
            
            # CUSTOM CASES FOR ICTP
#             if c.getRoles().find('\r\n') != -1:
#                 c.setRoles(c.getRoles().replace('\r\n',''))
#                 transaction.commit()
#             if c.getId() == 'a0344':
#                 c.setRoles('[{"id":2,"value":"Director(s)","editable":False,"child":[{"id":0,"familyName":"A. Simis"}, {"id":1,"familyName":"N.V. Trung and G. Valla"}]}, {"id":5,"value":"Director(s) & organizer(s)","editable":False,"child":[{"id":0,"familyName":"Scientific Committee: C. Huneke"}, {"id":1,"familyName":"A. Simis"}, {"id":2,"familyName":"B. Sturmfels"}, {"id":3,"familyName":"N.V. Trung"}, {"id":4,"familyName":"G. Valla and J. Verma"}]}, {"id":4,"value":"Organizer(s)","editable":False,"child":[{"id":0,"familyName":"C. Huneke"}, {"id":1,"familyName":"A. Simis"}, {"id":2,"familyName":"N.V. Trung"}, {"id":3,"familyName":"G. Valla and J. Verma"}]}, {"id":1,"value":"Local organizer(s)","editable":False,"child":[{"id":0,"familyName":"Ramadas T. Ramakrishnan"}]}, {"id":1,"value":"Laboratories","editable":False,"child":[{"id":0,"familyName":"no"}]}, {"id":1,"value":"Secretary","editable":False,"child":[{"id":0,"familyName":"A. Bergamo"}]}, {"id":5,"value":"Cosponsor(s)","editable":False,"child":[{"id":0,"familyName":"Research Project -Commutative and Computer Algebra-"}, {"id":1,"familyName":"MIUR"}, {"id":2,"familyName":"and Department of Mathematics"}, {"id":3,"familyName":"University of Genoa - Italy"}]}]')
#                 transaction.commit()
#             if c.getId() == 'a0432':
#                 c.setRoles('[{"id":2,"value":"Organizer(s)","editable":False,"child":[{"id":0,"familyName":"Liceo Ginnasio Statale Francesco Petrarca"}, {"id":1,"familyName":"Trieste; contact: Prof. Marina Mai"}]}]')
#                 transaction.commit()
#             if c.getId() == 'a07198':
#                 c.setRoles('[{"id":4,"value":"Organizer(s)","editable":False,"child":[{"id":0,"familyName":"Prof. G.F. Panza (ICTP - ESP-SAND)"}, {"id":1,"familyName":"Prof. F.M. Mazzolani (University of Naples Federico II)"}, {"id":2,"familyName":"Ing. M. Indirli (ENEA-Bologna)."}]}, {"id":1,"value":"Secretary","editable":False,"child":[{"id":0,"familyName":"G. De Meo"}]}]')
#                 transaction.commit()    
#             if c.getId() == 'a08192':
#                 c.setRoles('[{"id":7,"value":"Organizer(s)","editable":False,"child":[{"id":0,"familyName":"Directors: S. Cozzini"}, {"id":1,"familyName":"P. Giannozzi"}, {"id":2,"familyName":"E. Menendez-Proupin"}, {"id":3,"familyName":"W. Orellana"}, {"id":4,"familyName":"S. ScandoloCo-Organizing Institutions: Universidad Andrés Bello (UNAB)"}, {"id":5,"familyName":"Santiago"}, {"id":6,"familyName":"Chile;Project Anillo ACT/24/2006 - Universidad de Chile -Computer Simulation Lab in Nanobio Systems- INFM - DEMOCRITOS  National Simulation Center"}]}, {"id":1,"value":"Secretary","editable":False,"child":[{"id":0,"familyName":"M. Poropat"}]}, {"id":3,"value":"Collaborations","editable":False,"child":[{"id":0,"familyName":"Universidad Andrés Bello (UNAB)"}, {"id":1,"familyName":"Santiago"}, {"id":2,"familyName":"Chile and Project Anillo ACT/24/2006 - Universidad de Chile -Computer Simulation Lab in Nanobio Systems-"}]}, {"id":2,"value":"Cosponsor(s)","editable":False,"child":[{"id":0,"familyName":"Comisión Nacional de Investigación Científica y Tecnológica (CONICYT)"}, {"id":1,"familyName":"Programa Bicentenario de Ciencia y Tecnología"}]}]')
#                 transaction.commit()     
#             if c.getId() == 'a09174':
#                 c.setRoles('[{"id":4,"value":"Organizer(s)","editable":False,"child":[{"id":0,"familyName":"Directors:  A. Belehaki"}, {"id":1,"familyName":"M. Messerotti"}, {"id":2,"familyName":"G.  Lapenta"}, {"id":3,"familyName":"S. Radicella"}]}, {"id":1,"value":"Laboratories","editable":False,"child":[{"id":0,"familyName":"AGH Infolab (afternoons)"}]}, {"id":1,"value":"Secretary","editable":False,"child":[{"id":0,"familyName":"S. Radosic"}]}, {"id":5,"value":"Cosponsor(s)","editable":False,"child":[{"id":0,"familyName":"EC COST Action ES0803 -Developing Products and Services for Space Weather in Europe-"}, {"id":1,"familyName":"EC FP7 Project SOTERIA -SOLar-TERrestrial Investigations and Archives-"}, {"id":2,"familyName":"National Institute for Astrophysics (INAF) European Space Agency (ESA)"}]}]')
#                 transaction.commit()     
#             if c.getId() == 'a09223':
#                 c.setRoles('[{"id":5,"value":"Organizer(s)","editable":False,"child":[{"id":0,"familyName":"M. Bianchi (University of Rome -Tor Vergata-)"}, {"id":1,"familyName":"S. Ferrara (CERN & INFN)"}, {"id":2,"familyName":"E. Kiritsis (University of Crete)"}, {"id":3,"familyName":"K. Narain (ICTP)"}, {"id":4,"familyName":"S. Randjbar-Daemi (ICTP) and A. Sen (HRI)"}]}, {"id":1,"value":"Secretary","editable":False,"child":[{"id":0,"familyName":"R. Sain"}]}, {"id":1,"value":"Cosponsor(s)","editable":False,"child":[{"id":0,"familyName":"the Asia Pacific Center for Theoretical Physics (APCTP) & the Italian Institute for Nuclear Physics (INFN)"}]}]')
#                 transaction.commit()     
#             if c.getId() == 'a0924':
#                 c.setRoles('[{"id":2,"value":"Organizer(s)","editable":False,"child":[{"id":0,"familyName":"Liceo Ginnasio Statale -F. Petrarca- e Liceo -G. Galilei-"}, {"id":1,"familyName":"Trieste; contacts: Prof. Philip Tarsia and Ms. Renata Grill (Liceo Galilei)."}]}, {"id":1,"value":"Laboratories","editable":False,"child":[{"id":0,"familyName":"LB LAB"}]}]')
#                 transaction.commit()     

                
            rc.index(c, indexMaterial) 
            transaction.commit()
        curnum += 1

        per = int(float(curnum)/float(totnum)*100)
        if per != curper:
            curper = per
            print "______________"+str(per)+"%"
        
    # Pack it when finished
    print "Packing...."
    db.DBMgr.getInstance().pack()
    print "Done."
예제 #46
0
 def _checkParams(self, params):
     RHChatModifBase._checkParams(self, params)
     self._conf = ConferenceHolder().getById(params['confId'])
     self._chatroom = DBHelpers.getChatroom(params['chatroom'])
     self._sdate = params['sdate'] if params.has_key('sdate') else None
     self._edate = params['edate'] if params.has_key('edate') else None
     self._forEvent = bool(
         params['forEvent']) if params.has_key('forEvent') else None
     self._getAll = not self._sdate and not self._edate and not self._forEvent
예제 #47
0
def displayXMLList(res, req, tz, dc=1):
    ch = ConferenceHolder()
    xml = xmlGen.XMLGen()
    xml.openTag("collection")
    for confId in res:
        c = ch.getById(confId)
        xml = displayXMLConf(c, xml, tz, dc)
    xml.closeTag("collection")
    return xml.getXml()
예제 #48
0
def main(argv):
    category = -1
    meeting = -1
    show = 0

    try:
        opts, args = getopt.getopt(argv, "hm:c:s", ["help", "meeting=", "category=", "show"])
    except getopt.GetoptError:
        usage()
        sys.exit(2)
    for opt, arg in opts:
        if opt in ("-h", "--help"):
            usage()
            sys.exit()
        elif opt in ("-s", "--show"):
            show = 1
        elif opt in ("-m", "--meeting"):
            meeting = arg
        elif opt in ("-c", "--category"):
            category = arg

    # Create database instance and open trashcan manager object
    DBMgr.getInstance().startRequest()
    t = TrashCanManager()
    conf = None
    if show:
        for i in t.getList():
            if isinstance(i, Conference):
                if meeting != -1 and i.getId() == meeting:
                    print "[%s]%s" % (i.getId(), i.getTitle())
                elif meeting == -1:
                    print "[%s]%s" % (i.getId(), i.getTitle())
        sys.exit()
    if meeting != -1 and category != -1:
        print "Meeting:%s" % meeting
        print "Category:%s" % category
        for i in t.getList():
            if isinstance(i, Conference):
                if i.getId() == meeting:
                    conf = i
                    break

        if conf:
            # Remove the meeting from conference
            t.remove(conf)
            # Attach meeting to desired category
            cat = CategoryManager().getById(category)
            ConferenceHolder().add(conf)
            cat._addConference(conf)

            # Add Evaluation
            c = ConferenceHolder().getById(meeting)
            from MaKaC.evaluation import Evaluation

            c.setEvaluations([Evaluation(c)])

            DBMgr.getInstance().endRequest()
예제 #49
0
 def _getParams(self):
     super(SetPaidHook, self)._getParams()
     self.auth_key = get_query_parameter(self._queryParams, ["auth_key"])
     self.is_paid = get_query_parameter(self._queryParams, ["is_paid"]) == "yes"
     registrant_id = self._pathParams["registrant_id"]
     self._conf = ConferenceHolder().getById(self._pathParams['event'])
     self._registrant = self._conf.getRegistrantById(registrant_id)
     if not payment_event_settings.get(self._conf, 'enabled'):
         raise HTTPAPIError('E-payment is not enabled')
예제 #50
0
def displayXMLList(res, req, tz, dc=1):
  ch = ConferenceHolder()
  xml = xmlGen.XMLGen()
  xml.openTag("collection")
  for confId in res:
    c = ch.getById(confId)
    xml = displayXMLConf(c,xml,tz,dc)
  xml.closeTag("collection")
  return xml.getXml()
예제 #51
0
def main(argv):
    category = -1
    meeting = -1
    show = 0

    try:
        opts, args = getopt.getopt(argv, "hm:c:s",
                                   ["help", "meeting=", "category=", "show"])
    except getopt.GetoptError:
        usage()
        sys.exit(2)
    for opt, arg in opts:
        if opt in ("-h", "--help"):
            usage()
            sys.exit()
        elif opt in ("-s", "--show"):
            show = 1
        elif opt in ("-m", "--meeting"):
            meeting = arg
        elif opt in ("-c", "--category"):
            category = arg

    #Create database instance and open trashcan manager object
    DBMgr.getInstance().startRequest()
    t = TrashCanManager()
    conf = None
    if (show):
        for i in t.getList():
            if isinstance(i, Conference):
                if meeting != -1 and i.getId() == meeting:
                    print "[%s]%s" % (i.getId(), i.getTitle())
                elif meeting == -1:
                    print "[%s]%s" % (i.getId(), i.getTitle())
        sys.exit()
    if (meeting != -1 and category != -1):
        print "Meeting:%s" % meeting
        print "Category:%s" % category
        for i in t.getList():
            if isinstance(i, Conference):
                if i.getId() == meeting:
                    conf = i
                    break

        if conf:
            #Remove the meeting from conference
            t.remove(conf)
            #Attach meeting to desired category
            cat = CategoryManager().getById(category)
            ConferenceHolder().add(conf)
            cat._addConference(conf)

            #Add Evaluation
            c = ConferenceHolder().getById(meeting)
            from MaKaC.evaluation import Evaluation
            c.setEvaluations([Evaluation(c)])

            DBMgr.getInstance().endRequest()
예제 #52
0
 def call(self):
     """ Warning! Before creating the conferences and the bookings,
         you probably want to comment the lines in collaboration.py
         that actually communicate with the API.
         This should be used to test the Indico DB performance.
     """
     ch = ConferenceHolder()
     for i in xrange(1, 0 + 1):  #ids of events to remove
         c = ch.getById(str(i))
         c.delete()
예제 #53
0
파일: actions.py 프로젝트: Ictp/indico
 def call(self):
     """ Warning! Before creating the conferences and the bookings,
         you probably want to comment the lines in collaboration.py
         that actually communicate with the API.
         This should be used to test the Indico DB performance.
     """
     ch = ConferenceHolder()
     for i in xrange(1, 0+1): #ids of events to remove
         c = ch.getById(str(i))
         c.delete()
def main():
    DBMgr.getInstance().startRequest()
    ch = ConferenceHolder()
    ids = []
    print "Getting conference IDs..."
    for conf in ch.getList():
        ids.append(conf.getId())
    totalNumberConfs = len(ids)
    DBMgr.getInstance().endRequest()
    print "Updating conferences..."
    i = 0
    N_CONF = 10
    cErrorList = []
    while ids:
        if len(ids) >= N_CONF:
            lids = ids[:N_CONF]
            del ids[:N_CONF]
        else:
            lids = ids
            ids = None
        for j in range(10):
            conf = None
            try:
                DBMgr.getInstance().startRequest()
                for id in lids:
                    conf = ch.getById(id)
                    log("check for conference %s: %s/%s" % (conf.getId(), i, totalNumberConfs))
                    for cont in conf.getContributionList():
                        # if not isinstance(cont, AcceptedContribution):
                        if "content" in cont.getFields().keys():
                            if cont.getFields()["content"]:
                                if cont.getFields()["content"] != cont.description:
                                    log(
                                        "  contribution %s : content field no empty and diffrent from description"
                                        % cont.getId()
                                    )
                            else:
                                # cont.setField("content",cont.description)
                                cont.getFields()["content"] = cont.description
                                cont._p_changed = 1
                        else:
                            # cont.setField("content",cont.description)
                            cont.getFields()["content"] = cont.description
                            cont._p_changed = 1
                    i += 1
                DBMgr.getInstance().endRequest()
                print "wait 0.5s..."
                sleep(0.5)
                break
            except Exception, e:
                cErrorList.append(conf)
                i -= N_CONF
                log("error %s, retry %d time(s)" % (e, int(10 - j)))
                sleep(int(j))
                DBMgr.getInstance().abort()
예제 #55
0
파일: api.py 프로젝트: jbenito3/indico
    def contribution(self, idlist):
        ch = ConferenceHolder()
        event = ch.getById(self._eventId)

        def _iterate_objs(objIds):
            for objId in objIds:
                obj = event.getContributionById(objId)
                if obj is not None:
                    yield obj

        return self._process(_iterate_objs(idlist))