Example #1
0
def reindexCategoryNameAndConferenceTitle(dbi, prevVersion):
    """
    Indexing Conference Title and Category Name
    """
    IndexesHolder().removeById('conferenceTitle')
    IndexesHolder().removeById('categoryName')
    confTitleIdx = IndexesHolder().getIndex('conferenceTitle')
    categNameIdx = IndexesHolder().getIndex('categoryName')
    dbi.commit()

    iterator = (x[1]
                for x in console.conferenceHolderIterator(ConferenceHolder(),
                                                          deepness='event'))
    confTitleIdx.clear()
    confTitleIdx.initialize(iterator)

    categNameIdx.clear()
    db.session.commit()
    categNameIdx.initialize(CategoryManager().itervalues())
Example #2
0
    def __init__(self, startDate, endDate, confId, contribId=None):
        """
        Builds the map of generators to fill this object's variables before
        fossilization.
        """

        PiwikReportBase.__init__(self)
        report = BaseReportGenerator

        self._conf = ConferenceHolder().getById(confId)
        self._confId = confId
        self._contribId = contribId
        self._buildDateRange(startDate, endDate)
        self._contributions = []

        params = {
            'startDate': self._startDate,
            'endDate': self._endDate,
            'confId': confId
        }

        if contribId:
            params['contribId'] = contribId

        # This report only has need for images and values, not for widgets.
        self._reportGenerators = {
            'values': {
                'visits':
                report(pq.PiwikQueryMetricConferenceVisits, params),
                'uniqueVisits':
                report(pq.PiwikQueryMetricConferenceUniqueVisits, params),
                'visitLength':
                report(pq.PiwikQueryMetricConferenceVisitLength, params),
                'referrers':
                report(pq.PiwikQueryMetricConferenceReferrers, params),
                'peakDate':
                report(pq.PiwikQueryMetricConferencePeakDateAndVisitors,
                       params)
            }
        }

        self._buildReports()
        self._buildConferenceContributions()
Example #3
0
 def initialize(self, dbi=None):
     """ Cleans the indexes, and then indexes all the vidyo bookings from all the conferences
         WARNING: obviously, this can potentially take a while
     """
     i = 0
     self.clear()
     for conf in ConferenceHolder().getList():
         idx = Catalog.getIdx("cs_bookingmanager_conference")
         if idx is None:
             idx = Catalog.create_idx("cs_bookingmanager_conference")
         csbm = idx.get(conf.getId())
         for booking in csbm.getBookingList():
             if booking.getType() == "Vidyo" and booking.isCreated():
                 self.indexBooking(booking)
         i += 1
         if dbi and i % 100 == 0:
             dbi.commit()
     if dbi:
         dbi.commit()
Example #4
0
def create_event(monkeypatch_methods):
    """Returns a callable which lets you create dummy events"""
    monkeypatch_methods('MaKaC.conference.ConferenceHolder',
                        MockConferenceHolder)

    _events = []
    ch = ConferenceHolder()

    def _create_event(id_):
        event = MockConference()
        event.id = id_
        ch.add(event)
        _events.append(event)
        return event

    yield _create_event

    for event in _events:
        ch.remove(event)
Example #5
0
 def _getIdsForRemoveBooking(self):
     n = 0
     self.cdbmgr.startRequest()
     while n == 0:
         counter = 0
         confId = self.random.choice(self.confsWithBookings)
         testBookings = ConferenceHolder().getById(
             confId).getCSBookingManager()._bookingsByType.get(
                 "DummyPlugin", [])  #list of booking ids
         n = len(testBookings)
         if n > 0:
             bookingId = self.random.choice(testBookings)
         else:
             counter += 1
             if counter > 100:
                 self.fail(
                     "Could not found a good conference for remove booking")
     self.cdbmgr.endRequest()
     return confId, bookingId
Example #6
0
 def linked_object(self):
     """Returns the linked object."""
     from MaKaC.conference import CategoryManager, ConferenceHolder
     if self.link_type == LinkType.category:
         return CategoryManager().getById(self.category_id, True)
     event = ConferenceHolder().getById(self.event_id, True)
     if event is None:
         return None
     if self.link_type == LinkType.event:
         return event
     elif self.link_type == LinkType.session:
         return event.getSessionById(self.session_id)
     elif self.link_type == LinkType.contribution:
         return event.getContributionById(self.contribution_id)
     elif self.link_type == LinkType.subcontribution:
         contribution = event.getContributionById(self.contribution_id)
         if contribution is None:
             return None
         return contribution.getSubContributionById(self.subcontribution_id)
Example #7
0
    def setUp(self):
        super(TestTasks, self).setUp()
        self._startDBReq()

        PluginsHolder().updateAllPluginInfo()
        PluginsHolder().getPluginType('calendaring').setActive(True)
        PluginsHolder().getPluginType('calendaring').getPlugin(
            'outlook').setActive(True)

        # Create two dummy users
        ah = AvatarHolder()
        self._avatar1 = Avatar()
        self._avatar1.setName("fake-1")
        self._avatar1.setSurName("fake1")
        self._avatar1.setOrganisation("fake1")
        self._avatar1.setEmail("*****@*****.**")
        ah.add(self._avatar1)
        self._avatar2 = Avatar()
        self._avatar2.setName("fake-2")
        self._avatar2.setSurName("fake2")
        self._avatar2.setOrganisation("fake2")
        self._avatar2.setEmail("*****@*****.**")
        ah.add(self._avatar2)

        # Create two dummy conferences
        category = conf.CategoryManager().getById('0')
        ch = ConferenceHolder()

        self._conf1 = category.newConference(self._avatar1)
        self._conf1.setTimezone('UTC')
        sd1 = datetime(2012, 12, 1, 10, 0, tzinfo=timezone('UTC'))
        ed1 = datetime(2012, 12, 1, 18, 0, tzinfo=timezone('UTC'))
        self._conf1.setDates(sd1, ed1)
        ch.add(self._conf1)

        self._conf2 = category.newConference(self._avatar2)
        self._conf2.setTimezone('UTC')
        sd2 = datetime(2012, 12, 10, 11, 0, tzinfo=timezone('UTC'))
        ed2 = datetime(2012, 12, 11, 13, 0, tzinfo=timezone('UTC'))
        self._conf2.setDates(sd2, ed2)
        ch.add(self._conf2)

        self._stopDBReq()
Example #8
0
 def _getParams(self):
     super(AttachmentsExportHook, self)._getParams()
     event = self._obj = ConferenceHolder().getById(self._pathParams['event_id'], True)
     if event is None:
         raise HTTPAPIError('No such event', 404)
     session_id = self._pathParams.get('session_id')
     if session_id:
         session = self._obj = event.getSessionById(session_id)
         if session is None:
             raise HTTPAPIError("No such session", 404)
     contribution_id = self._pathParams.get('contribution_id')
     if contribution_id:
         contribution = self._obj = event.getContributionById(contribution_id)
         if contribution is None:
             raise HTTPAPIError("No such contribution", 404)
     subcontribution_id = self._pathParams.get('subcontribution_id')
     if subcontribution_id:
         subcontribution = self._obj = contribution.getSubContributionById(subcontribution_id)
         if subcontribution is None:
             raise HTTPAPIError("No such subcontribution", 404)
Example #9
0
def updateCatalog():    
    # Search for recently modified Conferences. This is very time consuming....
    results = []
    i=0
    for conf in ConferenceHolder().getValuesToList():
        i+=1
        confId = conf.getId()


        
        if 1:
            keyw = conf.getKeywords().split("\n")
            for keyword in keyw:
                if not(keyword in results) and not(keyword.startswith('smr')) and not(keyword.startswith('expparts')) and not(keyword.startswith('siscode')) and keyword != '':
                    results.append(keyword)
    
    results.sort()        
    print results 

    print "Done."
Example #10
0
    def indexAll(self, index_names=None, dbi=None):
        """ Indexes all the bookings from all the conferences
            WARNING: obviously, this can potentially take a while
        """

        i = 0

        for cid, conf in ConferenceHolder()._getIdx().iteritems():
            csbm = Catalog.getIdx("cs_bookingmanager_conference").get(
                conf.getId())
            if csbm is None: continue
            #note: probably not the most efficient implementation since _indexBooking is getting the list
            #      of indexes where each booking should be indexed on every iteration
            for booking in csbm.getBookingList():
                csbm._indexBooking(booking, index_names=index_names)
            i += 1
            if dbi and i % 1000 == 999:
                dbi.commit()
        if dbi:
            dbi.commit()
Example #11
0
def buildCache(ids):
    i = 1
    for id in ids:
        DBMgr.getInstance().startRequest()
        try:
            conf = ConferenceHolder().getById(id)
        except:
            print "conf %s not found"
            continue
        j = 1
        for cont in conf.getContributionList():
            print "conf %d:%s - contrib %d:%s"%(i, conf.getId(), j, cont.getId())
            og = outputGenerator(AccessWrapper())
            x = og.contribToXMLMarc21(cont, 1, overrideCache=True)
            for subCont in cont.getSubContributionList():
                print "conf %d:%s - contrib %d:%s - subContrib:%s"%(i, conf.getId(), j, cont.getId(), subCont.getId())
                y = og.subContribToXMLMarc21(subCont, 1, overrideCache=True)
            j += 1
        i += 1
        DBMgr.getInstance().endRequest()
Example #12
0
def update_event_data(avatar, categ, data):
    attendance_roles = set([
        'conference_participant', 'contribution_submission',
        'abstract_submitter', 'registration_registrant', 'evaluation_submitter'
    ])
    links = avatar_links.get_links(avatar)
    ch = ConferenceHolder()
    attended = filter(
        None,
        (ch.getById(eid, True)
         for eid, roles in links.iteritems() if attendance_roles & roles))
    attended = [e for e in attended if e.getOwner() == categ]
    # Count common chairpersons and attendants
    chair_count = data.setdefault('chair_count', Counter())
    participant_count = data.setdefault('participant_count', Counter())
    for event in attended:
        for ch in event.getChairList():
            chair_count[ch.getEmail()] += 1
        for part in event.getParticipation().getParticipantList():
            participant_count[part.getEmail()] += 1
Example #13
0
def create_event(category,
                 event_type,
                 data,
                 add_creator_as_manager=True,
                 features=None):
    """Create a new event.

    :param category: The category in which to create the event
    :param event_type: An `EventType` value
    :param data: A dict containing data used to populate the event
    :param add_creator_as_manager: Whether the creator (current user)
                                   should be added as a manager
    :param features: A list of features that will be enabled for the
                     event. If set, only those features will be used
                     and the default feature set for the event type
                     will be ignored.
    """
    from MaKaC.conference import Conference, ConferenceHolder
    conf = Conference()
    event = Event(category=category, type_=event_type)
    ConferenceHolder().add(conf, event)
    data.setdefault('creator', session.user)
    theme = data.pop('theme', None)
    person_link_data = data.pop('person_link_data', {})
    event.populate_from_dict(data)
    db.session.flush()
    event.person_link_data = person_link_data
    if theme is not None:
        layout_settings.set(event, 'timetable_theme', theme)
    if add_creator_as_manager:
        with event.logging_disabled:
            event.update_principal(event.creator, full_access=True)
    if features is not None:
        features_event_settings.set(event, 'enabled', features)
    db.session.flush()
    signals.event.created.send(event)
    logger.info('Event %r created in %r by %r ', event, category, session.user)
    event.log(EventLogRealm.event, EventLogKind.positive, 'Event',
              'Event created', session.user)
    db.session.flush()
    return event
Example #14
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,
                                      forceWithoutExtAuth=(not searchExt))
        # search authors
        if conferenceId != None:
            try:
                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)
            except Exception:
                pass
        return people
    else:
        return []
Example #15
0
    def _prepare(self, check=True):
        # Date checks...
        if check:
            from MaKaC.conference import ConferenceHolder
            if not ConferenceHolder().hasKey(self.conf.getId()):
                self.getLogger().warning(
                    "Conference {} no longer exists! Deleting alarm.".format(
                        self.conf.getId()))
                self.conf.removeAlarm(self)
                self.suicide()
            elif self.conf.getStartDate() <= self._getCurrentDateTime():
                self.getLogger().warning(
                    "Conference {} already started. Deleting alarm.".format(
                        self.conf.getId()))
                self.conf.removeAlarm(self)
                self.suicide()
                return False

        # Email
        self.setUpSubject()
        if self.getToAllParticipants():
            if self.conf.getType() == "conference":
                for r in self.conf.getRegistrantsList():
                    self.addToUser(r)
            else:
                for p in self.conf.getParticipation().getParticipantList():
                    self.addToUser(p)

        url = url_for('event.shorturl', self.conf, _external=True)
        self.setText(
            render_template('alarm_email.txt',
                            event=self.conf.fossilize(),
                            url=url,
                            note=self.note,
                            with_agenda=self.confSumary,
                            agenda=[
                                e.fossilize()
                                for e in self.conf.getSchedule().getEntries()
                            ]))

        return True
def sync(confId):
    DBMgr.getInstance().startRequest()
    conf = ConferenceHolder().getById(confId)
    counter = []

    if conf is None:
        raise Exception("Error fetching conference")
    else:
        for abstract in conf.getAbstractMgr().getAbstractList():
            if isinstance(abstract.getCurrentStatus(), AbstractStatusAccepted):
                contrib = abstract.getContribution()
                contrib.setTitle(abstract.getTitle())
                contrib.setDescription(abstract.getField('content'))
                contrib.setField('summary', abstract.getField('summary'))
                contrib.setTrack(abstract.getCurrentStatus().getTrack())
                contrib.setType(abstract.getCurrentStatus().getType())

                for auth1 in contrib.getPrimaryAuthorList()[:]:
                    contrib.removePrimaryAuthor(auth1)
                for auth2 in contrib.getCoAuthorList()[:]:
                    contrib.removeCoAuthor(auth2)
                for auth3 in contrib.getSpeakerList()[:]:
                    contrib.removeSpeaker(auth3)
                for auth in abstract.getAuthorList():
                    c_auth = ContributionParticipation()
                    contrib._setAuthorValuesFromAbstract(c_auth, auth)
                    if abstract.isPrimaryAuthor(auth):
                        contrib.addPrimaryAuthor(c_auth)
                    else:
                        contrib.addCoAuthor(c_auth)
                    if abstract.isSpeaker(auth):
                        contrib.addSpeaker(c_auth)

                # TODO: remove the previous submitter...how???
                submitter = contrib.getAbstract().getSubmitter().getUser()
                contrib._grantSubmission(submitter)
                counter.append(contrib.getId())

    DBMgr.getInstance().endRequest()
    print "%s contributions synchronized (%s)" % (len(counter),
                                                  ', '.join(counter))
Example #17
0
        def _check_index(desc, index, func):
            i = 0
            for ts, confs in index.iteritems():
                for confId in confs:
                    # it has to be in the conference holder
                    if confId not in confIdx:
                        yield "[%s][%s] '%s' not in ConferenceHolder" % (desc, ts, confId)
                    else:

                        conf = ConferenceHolder().getById(confId)
                        try:
                            expectedDate = date2utctimestamp(func(conf))
                        except OverflowError:
                            expectedDate = 'overflow'

                        # ts must be ok
                        if ts != expectedDate:
                            yield "[%s][%s] Conference '%s' has bogus date (should be '%s')" % (desc, ts, confId, expectedDate)
                    if dbi and i % 100 == 99:
                        dbi.sync()
                    i += 1
Example #18
0
    def setUp(self):
        super(TestAuthorSearch, 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._stopDBReq()
Example #19
0
    def inverseCheck(self):
        print "Searching through ConferenceHolder..."

        self.count = 0
        self.err = 0

        for c in ConferenceHolder().getList():
            k = c.getOAIModificationDate().strftime("%Y-%m-%d")
            if self.isVisible(c) and not self.idx._words.has_key(k):
                print "[ERR] Key '%s' not found (conf. %s - %s)!" % (
                    k, c.getId(), c.getOAIModificationDate())
                self.err += 1
            else:
                if self.isVisible(c):
                    self.count += 1

                    if not c in self.idx._words[k]:
                        print "[ERR] Entry for conf. %s not found in %s [OAI modif. date: %s ]!" % (
                            c.getId(), k, c.getOAIModificationDate())
                        self.err += 1

        print "-- %s errors found in %s records" % (self.err, self.count)
Example #20
0
    def event(self, query):
        ch = ConferenceHolder()
        index = IndexesHolder().getById("conferenceTitle")

        def _iterate_objs(query):
            results = index.search(query)
            for id, _ in results:
                event = ch.getById(id)
                if event is not None and event.canAccess(self._aw):
                    yield event

        for event in sorted(itertools.islice(_iterate_objs(query),
                                             self._offset,
                                             self._offset + self._limit),
                            key=self._sortingKeys.get(self._orderBy),
                            reverse=self._descending):
            yield {
                'id': event.getId(),
                'title': event.getTitle(),
                'startDate': event.getStartDate(),
                'hasAnyProtection': event.hasAnyProtection()
            }
Example #21
0
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)
def run4eachConfSlowly():
    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))
                    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()
Example #23
0
def update_menus(dbi):
    links = ('collaboration', 'downloadETicket')
    ch = ConferenceHolder()
    cdmr = ConfDisplayMgrRegistery()
    counter = Counter()

    for __, event in conferenceHolderIterator(ch, deepness='event'):
        menu = cdmr.getDisplayMgr(event).getMenu()
        must_update = False
        for linkname in links:
            if menu.getLinkByName(linkname) is None:
                counter[linkname] += 1
                must_update = True
        if must_update:
            menu.updateSystemLink()
            counter['updated'] += 1
        if counter['updated'] % 100:
            dbi.commit()

    for linkname in links:
        print "{} links missing: {}".format(linkname, counter[linkname])
    success("Event menus updated: {}".format(counter['updated']))
Example #24
0
def displayRSSList(res, req, tz):
    ch = ConferenceHolder()
    rss = xmlGen.XMLGen()
    rss.openTag('rss version="2.0"')
    rss.openTag("channel")
    rss.writeTag("title", "Indico RSS Feed")
    rss.writeTag("link", Config.getInstance().getBaseURL())
    rss.writeTag("description", "Export of some events stored in Indico")
    rss.writeTag("language", "en")
    rss.writeTag("pubDate", nowutc().strftime("%a, %d %b %Y %H:%M:%S %Z"))
    rss.writeTag("category", "")
    rss.writeTag("generator",
                 "CDS Indico %s" % Config.getInstance().getVersion())
    rss.writeTag("webMaster",
                 HelperMaKaCInfo.getMaKaCInfoInstance().getSupportEmail())
    rss.writeTag("ttl", "1440")
    for confId in res:
        c = ch.getById(confId)
        rss = displayRSSConf(c, rss, tz)
    rss.closeTag("channel")
    rss.closeTag("rss")
    return rss.getXml()
Example #25
0
 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
Example #26
0
def displayICalList(res, req):
    filename = "Event.ics"

    # TODO: proper methods in the iCal interface
    # for serializing a sequence of events

    icalBase = ICALBase()
    data = icalBase._printHeader()

    ch = ConferenceHolder()
    for confId in res:
        conf = ch.getById(confId)
        ical = ConferenceToiCal(conf.getConference())
        data += ical.getCore()
    data += icalBase._printFooter()
    req.headers_out["Content-Length"] = "%s" % len(data)
    cfg = Config.getInstance()
    mimetype = cfg.getFileTypeMimeType("ICAL")
    req.content_type = """%s""" % (mimetype)
    req.headers_out[
        "Content-Disposition"] = """inline; filename="%s\"""" % filename
    return data
Example #27
0
def get_object_from_args(args=None):
    """Retrieves an event object from request arguments.

    This utility is meant to be used in cases where the same controller
    can deal with objects attached to various parts of an event which
    use different URLs to indicate which object to use.

    :param args: The request arguments. If unspecified,
                 ``request.view_args`` is used.
    :return: An ``(object_type, event, object)`` tuple.  The event is
             always the :class:`Conference` associated with the object.
             The object may be a `Conference`, `Session`, `Contribution`
             or `SubContribution`.  If the object does not exist,
             ``(object_type, None, None)`` is returned.
    """
    from MaKaC.conference import ConferenceHolder
    if args is None:
        args = request.view_args
    object_type = args['object_type']
    event = ConferenceHolder().getById(args['confId'], True)
    obj = None
    if event is None:
        obj = None
    elif object_type == 'event':
        obj = event
    elif object_type == 'session':
        obj = event.getSessionById(args['sessionId'])
    elif object_type == 'contribution':
        obj = event.getContributionById(args['contribId'])
    elif object_type == 'subcontribution':
        contrib = event.getContributionById(args['contribId'])
        if contrib is not None:
            obj = contrib.getSubContributionById(args['subContId'])
    else:
        raise ValueError('Unexpected object type: {}'.format(object_type))
    if obj is not None:
        return object_type, event, obj
    else:
        return object_type, None, None
Example #28
0
def _event_or_shorturl(confId, shorturl_namespace=False, ovw=False):
    from MaKaC.conference import ConferenceHolder
    from MaKaC.common.url import ShortURLMapper

    func = None
    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().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)
        elif is_legacy_id(confId):
            mapping = LegacyEventMapping.find_first(legacy_event_id=confId)
            if mapping is not None:
                url = url_for('event.conferenceDisplay', confId=mapping.event_id)
                func = lambda: redirect(url, 301)

    if func is None:
        raise NotFound(_('The specified event with id or tag "{}" does not exist or has been deleted').format(confId))
    return func()
Example #29
0
    def setUp(self):
        super(TestProtection, self).setUp()

        with self._context("database"):
            # Create a conference
            category = conference.CategoryManager().getById('0')
            self._conf = category.newConference(self._dummy)
            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._contrib1 = conference.Contribution()
            self._conf.addContribution(self._contrib1)

            self._session1 = conference.Session()
            self._conf.addSession(self._session1)

            self._session2 = conference.Session()
            self._conf.addSession(self._session2)

            self._contrib2 = conference.Contribution()
            self._session1.addContribution(self._contrib2)

            #Now we create the material (id=0) and attach it to the contrib
            self._material = conference.Material()
            self._contrib1.addMaterial( self._material )
            #Now we create a dummy file and attach it to the material
            filePath = os.path.join( os.getcwd(), "test.txt" )
            fh = open(filePath, "w")
            fh.write("hola")
            fh.close()
            self._resource = conference.LocalFile()
            self._resource.setFilePath( filePath )
            self._resource.setFileName( "test.txt" )
            self._material.addResource( self._resource )
Example #30
0
    def __init__(self, catalogName=confCatalog):
        self.catalog = {}
        self.db = db.DBMgr.getInstance().getDBConnection()
        self.ch = ConferenceHolder()

        plugin = PluginsHolder().getPluginType('search').getPlugin("repozer")
        self.iConf = plugin.getOptions()["indexConference"].getValue()
        self.iContrib = plugin.getOptions()["indexContribution"].getValue()
        self.iMat = plugin.getOptions()["indexMaterial"].getValue()

        # init all standard catalogs
        for cat in [confCatalog,contribCatalog,matCatalog]:
            if cat not in self.db.root():
                self.catalogName = cat
                self.init_catalog()        
        
        self.catalogName = catalogName

        # init customized catalog        
        if self.catalogName not in [confCatalog,contribCatalog,matCatalog] and self.catalogName not in self.db.root():
            self.init_catalog()
            
        self.catalog = self.db.root()[self.catalogName]