示例#1
0
 def testDeleteWithDel(self):
     """
     Delete works OK
     """
     ContextManager.set('test', 123)
     del ContextManager.get()['test']
     self.assertEqual(ContextManager.get('test', default=None), None)
 def testDeleteWithDel(self):
     """
     Delete works OK
     """
     ContextManager.set('test', 123)
     del ContextManager.get()['test']
     self.assertEqual(ContextManager.get('test', default=None), None)
示例#3
0
    def _add(self, obj, actions):
        """
        Adds a provided object to the temporary index.
        Actions: ['moved','deleted',..]
        """

        cm_set = ContextManager.get('indico.ext.livesync:actions').setdefault(
            obj, set([]))

        # the context may not be initialized
        if cm_set != None:
            cm_set |= set(actions)
        uid = uniqueId(obj)
        if uid is not None and uid != '':
            ContextManager.get('indico.ext.livesync:ids').setdefault(obj, uid)
示例#4
0
文件: cache.py 项目: pmart123/indico
    def _connect(self):
        """Connect to the CacheClient.

        This method must be called before accessing ``self._client``.
        """
        # Maybe we already have a client in this instance
        if self._client is not None:
            return
        # If not, we might have one from another instance
        self._client = ContextManager.get('GenericCacheClient', None)

        if self._client is not None:
            return

        # If not, create a new one
        backend = Config.getInstance().getCacheBackend()
        if backend == 'memcached':
            self._client = MemcachedCacheClient(
                Config.getInstance().getMemcachedServers())
        elif backend == 'redis':
            self._client = RedisCacheClient(
                Config.getInstance().getRedisCacheURL())
        elif backend == 'files':
            self._client = FileCacheClient(
                Config.getInstance().getXMLCacheDir())
        else:
            self._client = NullCacheClient()

        ContextManager.set('GenericCacheClient', self._client)
示例#5
0
    def _connect(self):
        """Connect to the CacheClient.

        This method must be called before accessing ``self._client``.
        """
        # Maybe we already have a client in this instance
        if self._client is not None:
            return
        # If not, we might have one from another instance
        self._client = ContextManager.get('GenericCacheClient', None)

        if self._client is not None:
            return

        # If not, create a new one
        backend = Config.getInstance().getCacheBackend()
        if backend == 'memcached':
            self._client = MemcachedCacheClient(Config.getInstance().getMemcachedServers())
        elif backend == 'redis':
            self._client = RedisCacheClient(Config.getInstance().getRedisCacheURL())
        elif backend == 'files':
            self._client = FileCacheClient(Config.getInstance().getXMLCacheDir())
        else:
            self._client = NullCacheClient()

        ContextManager.set('GenericCacheClient', self._client)
示例#6
0
 def testDelete(self):
     """
     Delete works OK
     """
     ContextManager.set('test', 123)
     ContextManager.delete('test')
     self.assertEqual(ContextManager.get('test', default=None), None)
示例#7
0
    def _add(self, obj, actions):
        """
        Adds a provided object to the temporary index.
        Actions: ['moved','deleted',..]
        """

        cm_set = ContextManager.get('indico.ext.livesync:actions').setdefault(
            obj, set([]))

        # the context may not be initialized
        if cm_set != None:
            cm_set |= set(actions)
        uid = uniqueId(obj)
        if uid is not None and uid != '':
            ContextManager.get('indico.ext.livesync:ids').setdefault(
                obj, uid)
示例#8
0
    def _setParam(self):

        ContextManager.set("dateChangeNotificationProblems", {})

        if self._pTime < self._target.getStartDate():
            raise ServiceError("ERR-E3", "Date/time of end cannot " + "be lower than data/time of start")
        self._target.setDates(self._target.getStartDate(), self._pTime.astimezone(timezone("UTC")), moveEntries=0)

        dateChangeNotificationProblems = ContextManager.get("dateChangeNotificationProblems")

        if dateChangeNotificationProblems:
            warningContent = []
            for problemGroup in dateChangeNotificationProblems.itervalues():
                warningContent.extend(problemGroup)

            return Warning(
                _("Warning"),
                [
                    _("The end date of your event was changed correctly."),
                    _("However, there were the following problems:"),
                    warningContent,
                ],
            )
        else:
            return None
示例#9
0
    def _setParam(self):

        ContextManager.set('dateChangeNotificationProblems', {})

        if (self._pTime < self._target.getStartDate()):
            raise ServiceError(
                "ERR-E3", "Date/time of end cannot " +
                "be lower than data/time of start")
        self._target.setDates(self._target.getStartDate(),
                              self._pTime.astimezone(timezone("UTC")),
                              moveEntries=0)

        dateChangeNotificationProblems = ContextManager.get(
            'dateChangeNotificationProblems')

        if dateChangeNotificationProblems:
            warningContent = []
            for problemGroup in dateChangeNotificationProblems.itervalues():
                warningContent.extend(problemGroup)

            return Warning(_('Warning'), [
                _('The end date of your event was changed correctly.'),
                _('However, there were the following problems:'),
                warningContent
            ])
        else:
            return None
示例#10
0
def _build_folder_legacy_api_data(folder):
    avatar = ContextManager.get("currentAW").getUser()
    user = avatar.user if avatar else None
    if not folder.can_access(user):
        return None

    resources = [
        _build_attachment_legacy_api_data(attachment)
        for attachment in folder.attachments if attachment.can_access(user)
    ]
    if not resources:  # Skipping empty folders for legacy API
        return None

    type_ = (folder.legacy_mapping.material_id.title()
             if folder.legacy_mapping is not None
             and not folder.legacy_mapping.material_id.isdigit() else
             'Material')
    return {
        '_type': type_,
        '_fossil': 'materialMetadata',
        '_deprecated': True,
        'title': folder.title,
        'id': str(folder.id),
        'resources': resources
    }
示例#11
0
    def cloneEvent(cls, confToClone, params):
        """ we'll clone only the chat rooms created by the user who is cloning the conference """
        conf = params['conf']
        user = params['user']
        options = params['options']
        ContextManager.setdefault('mailHelper', MailHelper())

        if options.get("chatrooms", True):
            crList = DBHelpers().getChatroomList(confToClone)
            ownersList = [cr.getOwner() for cr in crList]
            if PluginsWrapper('InstantMessaging', 'XMPP').isActive():
                 for cr in crList:
                     if user is cr.getOwner():
                         cls()._notify('addConference2Room', {'room':cr, 'conf':conf.getId()})

        ContextManager.get('mailHelper').sendMails()
示例#12
0
    def invokeMethod(self, method, params, req):

        MAX_RETRIES = 10

        # clear the context
        ContextManager.destroy()

        DBMgr.getInstance().startRequest()

        # room booking database
        _startRequestSpecific2RH()

        # notify components that the request has started
        self._notify('requestStarted', req)

        forcedConflicts = Config.getInstance().getForceConflicts()
        retry = MAX_RETRIES
        try:
            while retry > 0:
                if retry < MAX_RETRIES:
                    # notify components that the request is being retried
                    self._notify('requestRetry', req, MAX_RETRIES - retry)

                try:
                    # delete all queued emails
                    GenericMailer.flushQueue(False)

                    DBMgr.getInstance().sync()

                    try:
                        result = processRequest(method, copy.deepcopy(params), req)
                    except MaKaC.errors.NoReportError, e:
                        raise NoReportError(e.getMsg())
                    rh = ContextManager.get('currentRH')

                    # notify components that the request has ended
                    self._notify('requestFinished', req)
                    # Raise a conflict error if enabled. This allows detecting conflict-related issues easily.
                    if retry > (MAX_RETRIES - forcedConflicts):
                        raise ConflictError
                    _endRequestSpecific2RH( True )
                    DBMgr.getInstance().endRequest(True)
                    GenericMailer.flushQueue(True) # send emails
                    if rh._redisPipeline:
                        try:
                            rh._redisPipeline.execute()
                        except RedisError:
                            Logger.get('redis').exception('Could not execute pipeline')
                    break
                except ConflictError:
                    _abortSpecific2RH()
                    DBMgr.getInstance().abort()
                    retry -= 1
                    continue
                except ClientDisconnected:
                    _abortSpecific2RH()
                    DBMgr.getInstance().abort()
                    retry -= 1
                    time.sleep(MAX_RETRIES - retry)
                    continue
示例#13
0
    def _connect(self):
        # Maybe we already have a client in this instance
        if self._client is not None:
            return
        # If not, we might have one from another instance
        self._client = ContextManager.get('GenericCacheClient', None)

        if self._client is not None:
            return

        # If not, create a new one
        backend = Config.getInstance().getCacheBackend()
        if backend == 'memcached':
            import memcache
            self._client = memcache.Client(
                Config.getInstance().getMemcachedServers())
        elif backend == 'redis':
            self._client = RedisCacheClient(
                Config.getInstance().getRedisCacheURL())
        elif backend == 'files':
            self._client = FileCacheClient(
                Config.getInstance().getXMLCacheDir())
        else:
            self._client = NullCacheClient()

        ContextManager.set('GenericCacheClient', self._client)
示例#14
0
    def _getRequestInfo(self):
        rh = ContextManager.get('currentRH', None)
        info = ['Additional information:']

        try:
            info.append('Request: %s' % request.id)
            info.append('URL: %s' % request.url)

            if request.url_rule:
                info.append('Endpoint: {0}'.format(request.url_rule.endpoint))

            info.append('Method: %s' % request.method)
            if rh:
                info.append('Params: %s' % rh._getTruncatedParams())

            if session:
                try:
                    info.append('User: {0}'.format(session.user))
                except POSError:
                    # If the DB connection is closed getting the avatar may fail
                    info.append('User id: {0}'.format(
                        session.get('_avatarId')))
            info.append('IP: %s' % request.remote_addr)
            info.append('User Agent: %s' % request.user_agent)
            info.append('Referer: %s' % (request.referrer or 'n/a'))
        except RuntimeError, e:
            info.append('Not available: %s' % e)
示例#15
0
    def _getRequestInfo(self):
        rh = ContextManager.get('currentRH', None)
        info = ['Additional information:']

        try:
            info.append('Request: %s' % request.id)
            info.append('URL: %s' % request.url)

            if request.url_rule:
                info.append('Endpoint: {0}'.format(request.url_rule.endpoint))

            info.append('Method: %s' % request.method)
            if rh:
                info.append('Params: %s' % rh._getTruncatedParams())

            if session:
                try:
                    info.append('User: {0}'.format(session.user))
                except POSError:
                    # If the DB connection is closed getting the avatar may fail
                    info.append('User id: {0}'.format(session.get('_avatarId')))
            info.append('IP: %s' % request.remote_addr)
            info.append('User Agent: %s' % request.user_agent)
            info.append('Referer: %s' % (request.referrer or 'n/a'))
        except RuntimeError, e:
            info.append('Not available: %s' % e)
 def testDelete(self):
     """
     Delete works OK
     """
     ContextManager.set('test', 123)
     ContextManager.delete('test')
     self.assertEqual(ContextManager.get('test', default=None), None)
示例#17
0
    def __init__(self, **params):
        self._userLoggedIn = params.get("userLoggedIn", False)
        self._target = params.get("target", None)
        self._page = params.get("page", 1)
        self._noQuery = False

        if self._userLoggedIn:
            self._sessionHash = "%s_%s" % (ContextManager.get("currentRH", None)._getSession().getId(), ContextManager.get("currentUser", None).getId())
        else:
            self._sessionHash = 'PUBLIC'

        if type(self._target) == conference.Category:
            # we're dealing with a category
            if self._target.isRoot():
                # perform global search
                self._marcQuery = ''
            else:
                # if not on root, search using path
                self._marcQuery = '650_7:"'+self._buildCategoryHierarchy(self._target)+'*" '

        elif type(self._target) == conference.Conference:
            # we're looking inside an event
            # search for event identifier
            self._marcQuery = 'AND 970__a:"INDICO.%s.*"' % self._target.getId()
            self._searchCategories = False

        else:
            raise Exception("Unknown target type.")
示例#18
0
    def performOperation(cls, operation, conf, room, *args):
        """ The 4 operations of this class are quite the same, so we pass the name of the operation, the conference they belong to,
            the chat room for which we are creating the operation and, finally, a list of the arguments needed for the operation"""

        # get the list of users that will receive emails
        pf = PluginFieldsWrapper('InstantMessaging', 'XMPP')
        userList = list(pf.getOption('additionalEmails'))
        if pf.getOption('sendMailNotifications'):
            userList.extend( [user.getEmail() for user in pf.getOption('admins')] )
        if not len(userList) is 0:
            try:
                cn = ChatroomsNotification(room, userList)
                ContextManager.get('mailHelper').newMail(GenericMailer.sendAndLog, getattr(cn, operation)(*args), \
                                         conf, \
                                         "MaKaC/plugins/InstantMessaging/XMPP/components.py", \
                                         room.getOwner())
            except Exception, e:
                raise ServiceError(message=_('There was an error while contacting the mail server. No notifications were sent: %s'%e))
示例#19
0
    def _invokeMethodSuccess(self):
        rh = ContextManager.get('currentRH')

        flush_after_commit_queue(True)  # run after-commit functions
        GenericMailer.flushQueue(True)  # send emails
        if rh._redisPipeline:
            try:
                rh._redisPipeline.execute()
            except RedisError:
                Logger.get('redis').exception('Could not execute pipeline')
示例#20
0
    def _invokeMethodSuccess(self):
        rh = ContextManager.get('currentRH')

        flush_after_commit_queue(True)  # run after-commit functions
        GenericMailer.flushQueue(True)  # send emails
        if rh._redisPipeline:
            try:
                rh._redisPipeline.execute()
            except RedisError:
                Logger.get('redis').exception('Could not execute pipeline')
示例#21
0
    def getVars(self):
        from MaKaC.plugins.Collaboration.handlers import RCCollaborationAdmin
        from MaKaC.webinterface.rh.admins import RCAdmin

        vars = wcomponents.WTemplated.getVars(self)
        user = ContextManager.get("currentUser")
        vars["user"] = user
        vars["IsAdmin"] = RCAdmin.hasRights(self._rh)
        vars["IsCollaborationAdmin"] = RCCollaborationAdmin.hasRights(user)
        return vars
示例#22
0
    def getVars(self):
        from MaKaC.plugins.Collaboration.handlers import RCCollaborationAdmin
        from MaKaC.webinterface.rh.admins import RCAdmin

        vars = wcomponents.WTemplated.getVars(self)
        user = ContextManager.get("currentUser")
        vars["user"] = user
        vars["IsAdmin"] = RCAdmin.hasRights(self._rh)
        vars["IsCollaborationAdmin"] = RCCollaborationAdmin.hasRights(user)
        return vars
示例#23
0
文件: mail.py 项目: wtakase/indico
 def flushQueue(cls, send):
     queue = ContextManager.get('emailQueue', None)
     if not queue:
         return
     if send:
         # send all emails
         for mail in queue:
             cls._send(mail)
     # clear the queue no matter if emails were sent or not
     del queue[:]
示例#24
0
 def flushQueue(cls, send):
     queue = ContextManager.get('emailQueue', None)
     if not queue:
         return
     if send:
         # send all emails
         for mail in queue:
             cls._send(mail)
     # clear the queue no matter if emails were sent or not
     del queue[:]
示例#25
0
 def _getRequestInfo(self):
     rh = ContextManager.get('currentRH', None)
     if not rh:
         return ''
     info = ['Additional information:']
     info.append('URL: %s' % rh.getRequestURL())
     info.append('Params: %s' % rh._getTruncatedParams())
     info.append('IP: %s' % rh._req.remote_ip)
     info.append('User Agent: %s' % rh._req.headers_in.get('User-Agent', 'n/a'))
     info.append('Referer: %s' % rh._req.headers_in.get('Referer', 'n/a'))
     return '\n\n%s' % '\n'.join(info)
示例#26
0
    def testWithThreads(self):
        t1 = threading.Thread(target=self.thread1)
        t2 = threading.Thread(target=self.thread2)

        t1.start()
        t2.start()

        t1.join()
        t2.join()

        self.assertEquals(ContextManager.get('samevariable').__class__, ContextManager.DummyContext)
示例#27
0
 def _getRequestInfo(self):
     rh = ContextManager.get('currentRH', None)
     if not rh:
         return ''
     info = ['Additional information:']
     info.append('URL: %s' % rh.getRequestURL())
     info.append('Params: %s' % rh._getTruncatedParams())
     info.append('IP: %s' % rh._req.remote_ip)
     info.append('User Agent: %s' % rh._req.headers_in.get('User-Agent', 'n/a'))
     info.append('Referer: %s' % rh._req.headers_in.get('Referer', 'n/a'))
     return '\n\n%s' % '\n'.join(info)
示例#28
0
class ConferenceStartEndDateTimeModification(ConferenceModifBase):
    """ Conference start date/time modification
        When changing the start date / time, the _setParam method will be called by DateTimeModificationBase's _handleSet method.
        The _setParam method will return None (if there are no problems),
        or a Warning object if the event start date change was OK but there were side problems,
        such as an object observing the event start date change could not perform its task
        (Ex: a videoconference booking could not be moved in time according with the conference's time change)
        For this, it will check the 'dateChangeNotificationProblems' context variable.
    """
    def _checkParams(self):

        ConferenceModifBase._checkParams(self)

        pm = ParameterManager(self._params.get('value'),
                              timezone=self._conf.getTimezone())

        self._startDate = pm.extract('startDate', pType=datetime.datetime)
        self._endDate = pm.extract('endDate', pType=datetime.datetime)

    def _getAnswer(self):

        ContextManager.set('dateChangeNotificationProblems', {})

        if (self._startDate > self._endDate):
            raise ServiceError(
                "ERR-E3", "Date/time of start cannot " +
                "be greater than date/time of end")

        try:
            self._target.setDates(self._startDate,
                                  self._endDate,
                                  moveEntries=1)
        except TimingError, e:
            raise ServiceError("ERR-E2", e.getMsg())

        dateChangeNotificationProblems = ContextManager.get(
            'dateChangeNotificationProblems')

        if dateChangeNotificationProblems:

            warningContent = []
            for problemGroup in dateChangeNotificationProblems.itervalues():
                warningContent.extend(problemGroup)

            return Warning(_('Warning'), [
                _('The start date of your event was changed correctly.'),
                _('However, there were the following problems:'),
                warningContent
            ])

        else:
            return self._params.get('value')
示例#29
0
    def requestFinished(self, obj, req):

        sm = SyncManager.getDBInstance()
        cm = ContextManager.get('indico.ext.livesync:actions')
        cm_ids = ContextManager.get('indico.ext.livesync:ids')

        timestamp = int_timestamp(nowutc())

        # if the returned context is a dummy one, there's nothing to do
        if cm.__class__ == DummyDict:
            return

        # Insert the elements from the temporary index
        # into the permanent one (MPT)
        for obj, actions in cm.iteritems():
            objId = cm_ids[obj]
            for action in actions:
                Logger.get('ext.livesync').debug((objId, action))
                # TODO: remove redundant items
            if not sm.objectExcluded(obj):
                sm.add(timestamp,
                       ActionWrapper(timestamp, obj, actions, objId))
示例#30
0
    def requestFinished(self, obj, req):

        sm = SyncManager.getDBInstance()
        cm = ContextManager.get('indico.ext.livesync:actions')
        cm_ids = ContextManager.get('indico.ext.livesync:ids')

        timestamp = int_timestamp(nowutc())

        # if the returned context is a dummy one, there's nothing to do
        if cm.__class__ == DummyDict:
            return

        # Insert the elements from the temporary index
        # into the permanent one (MPT)
        for obj, actions in cm.iteritems():
            objId = cm_ids[obj]
            for action in actions:
                Logger.get('ext.livesync').debug((objId, action))
                # TODO: remove redundant items
            if not sm.objectExcluded(obj):
                sm.add(timestamp, ActionWrapper(timestamp, obj, actions,
                                                objId))
示例#31
0
    def testNotifyNewContentExpandsSlotUp(self):
        """ When a slot grows up (new content), proper notification is triggered  """

        #        import rpdb2; rpdb2.start_embedded_debugger_interactive_password()

        self.testNewContentExpandsSlotUp()

        ops = ContextManager.get('autoOps')

        self.assert_(len(ops) == 3)

        op1 = ops[0]
        op2 = ops[1]
示例#32
0
    def testNotifyNewContentExpandsSlotDown(self):
        """ When a slot grows down (new content), proper notification is triggered  """

        self.testNewContentExpandsSlotDown()

        ops = ContextManager.get('autoOps')

        self.assert_(len(ops) == 4)

        op1 = ops[0]
        op2 = ops[1]
        op3 = ops[0]
        op4 = ops[1]
示例#33
0
    def testNotifyNewContentExpandsSlotUp(self):
        """ When a slot grows up (new content), proper notification is triggered  """

#        import rpdb2; rpdb2.start_embedded_debugger_interactive_password()

        self.testNewContentExpandsSlotUp()

        ops = ContextManager.get('autoOps')

        self.assert_(len(ops) == 3)

        op1 = ops[0]
        op2 = ops[1]
示例#34
0
    def testWithThreads(self):
        t1 = threading.Thread(target=self.thread1)
        t2 = threading.Thread(target=self.thread2)

        t1.start()
        t2.start()

        t1.join()
        t2.join()

        self.assertEquals(
            ContextManager.get('samevariable').__class__,
            ContextManager.DummyContext)
示例#35
0
    def testWithThreads(self):
        "Thread safety"

        t1 = threading.Thread(target=self.thread1)
        t2 = threading.Thread(target=self.thread2)

        t1.start()
        t2.start()

        t1.join()
        t2.join()

        self.assertEquals(ContextManager.get("samevariable").__class__, DummyDict)
示例#36
0
    def testNotifyNewContentExpandsSlotDown(self):
        """ When a slot grows down (new content), proper notification is triggered  """

        self.testNewContentExpandsSlotDown()

        ops = ContextManager.get('autoOps')

        self.assert_(len(ops) == 4)

        op1 = ops[0]
        op2 = ops[1]
        op3 = ops[0]
        op4 = ops[1]
示例#37
0
文件: mail.py 项目: wtakase/indico
    def send(cls, notification, skipQueue=False):
        if isinstance(notification, dict):
            # Wrap a raw dictionary in a notification class
            from MaKaC.webinterface.mail import GenericNotification
            notification = GenericNotification(notification)
        # enqueue emails if we have a rh and do not skip queuing, otherwise send immediately
        rh = ContextManager.get('currentRH', None)
        mailData = cls._prepare(notification)

        if mailData:
            if skipQueue or not rh:
                cls._send(mailData)
            else:
                ContextManager.setdefault('emailQueue', []).append(mailData)
示例#38
0
    def send(cls, notification, skipQueue=False):
        if isinstance(notification, dict):
            # Wrap a raw dictionary in a notification class
            from MaKaC.webinterface.mail import GenericNotification
            notification = GenericNotification(notification)
        # enqueue emails if we have a rh and do not skip queuing, otherwise send immediately
        rh = ContextManager.get('currentRH', None)
        mailData = cls._prepare(notification)

        if mailData:
            if skipQueue or not rh:
                cls._send(mailData)
            else:
                ContextManager.setdefault('emailQueue', []).append(mailData)
示例#39
0
    def _getRequestInfo(self):
        rh = ContextManager.get('currentRH', None)
        info = ['Additional information:']

        try:
            info.append('URL: %s' % request.url)
            info.append('Endpoint: %s' % request.url_rule.endpoint)
            info.append('Method: %s' % request.method)
            if rh:
                info.append('Params: %s' % rh._getTruncatedParams())
            info.append('IP: %s' % request.remote_addr)
            info.append('User Agent: %s' % request.user_agent)
            info.append('Referer: %s' % (request.referrer or 'n/a'))
        except RuntimeError, e:
            info.append('Not available: %s' % e)
示例#40
0
    def getVars( self ):
        """Returns a dictionary containing the TPL variables that will
            be passed at the TPL formating time. For this class, it will
            return the configuration user defined variables.
           Classes inheriting from this one will have to take care of adding
            their variables to the ones returned by this method.
        """
        self._rh = ContextManager.get('currentRH', None)

        cfg = Config.getInstance()
        vars = cfg.getTPLVars()

        for paramName in self.__params:
            vars[ paramName ] = self.__params[ paramName ]

        return vars
示例#41
0
    def getVars(self):
        """Returns a dictionary containing the TPL variables that will
            be passed at the TPL formating time. For this class, it will
            return the configuration user defined variables.
           Classes inheriting from this one will have to take care of adding
            their variables to the ones returned by this method.
        """
        self._rh = ContextManager.get('currentRH', None)

        cfg = Config.getInstance()
        vars = cfg.getTPLVars()

        for paramName in self.__params:
            vars[paramName] = self.__params[paramName]

        return vars
示例#42
0
文件: util.py 项目: hennogous/indico
def _build_folder_api_data(folder):
    avatar = ContextManager.get("currentAW").getUser()
    user = avatar.user if avatar else None
    if not folder.can_view(user):
        return None

    return {
        '_type': 'folder',
        'id': folder.id,
        'title': folder.title,
        'description': folder.description,
        'attachments': [_build_attachment_api_data(attachment)
                        for attachment in folder.attachments
                        if attachment.can_access(user)],
        'default_folder': folder.is_default
    }
示例#43
0
    def _connect(self):
        # Maybe we already have a client in this instance
        if self._client is not None:
            return
        # If not, we might have one from another instance
        self._client = ContextManager.get('GenericCacheClient', None)
        if self._client is not None:
            return
        # If not, create a new one
        backend = Config.getInstance().getCacheBackend()
        if backend == 'memcached':
            import memcache
            self._client = memcache.Client(Config.getInstance().getMemcachedServers())
        else:
            self._client = FileCacheClient(Config.getInstance().getXMLCacheDir())

        ContextManager.set('GenericCacheClient', self._client)
示例#44
0
    def getHTML(self, params=None):
        """Returns the HTML resulting of formating the text contained in
            the corresponding TPL file with the variables returned by the
            getVars method.
            Params:
                params -- additional paramters received from the caller
        """

        self._rh = ContextManager.get('currentRH', None)
        if self.tplId == None:
            self.tplId = self.__class__.__name__[1:]
        self._setTPLFile()
        self.__params = {}
        if params != None:
            self.__params = params

        # include context help info, if it exists
        helpText = None
        if os.path.exists(self.helpFile):
            try:
                fh = open(self.helpFile, "r")
                helpText = fh.read()
                fh.close()
            except exceptions.IOError:
                pass

        vars = self.getVars()

        vars['__rh__'] = self._rh
        vars['self_'] = self

        tempHTML = templateEngine.render(self.tplFile, vars, self)

        if helpText == None:
            return tempHTML
        else:
            try:
                return ContextHelp().merge(self.tplId, tempHTML, helpText)
            except etree.LxmlError, e:
                if tempHTML.strip() == '':
                    raise MaKaCError(
                        _("Template " + str(self.tplId) +
                          " produced empty output, and it has a .wohl file. Error: "
                          + str(e)))
                else:
                    raise
示例#45
0
文件: util.py 项目: pmart123/indico
def _build_folder_api_data(folder):
    avatar = ContextManager.get("currentAW").getUser()
    user = avatar.user if avatar else None
    if not folder.can_view(user):
        return None

    return {
        '_type': 'folder',
        'id': folder.id,
        'title': folder.title,
        'description': folder.description,
        'attachments': [_build_attachment_api_data(attachment)
                        for attachment in folder.attachments
                        if attachment.can_access(user)],
        'default_folder': folder.is_default,
        'is_protected': folder.is_protected
    }
示例#46
0
    def getHTML( self, params=None ):
        """Returns the HTML resulting of formating the text contained in
            the corresponding TPL file with the variables returned by the
            getVars method.
            Params:
                params -- additional paramters received from the caller
        """

        self._rh = ContextManager.get('currentRH', None)
        if self.tplId == None:
            self.tplId = self.__class__.__name__[1:]
        self._setTPLFile()
        self.__params = {}
        if params != None:
            self.__params = params

        # include context help info, if it exists
        helpText = None
        if os.path.exists(self.helpFile):
            try:
                fh = open( self.helpFile, "r")
                helpText = fh.read()
                fh.close()
            except exceptions.IOError:
                pass

        vars = self.getVars()

        vars['__rh__'] = self._rh
        vars['self_'] = self

        tempHTML = templateEngine.render(self.tplFile, vars, self)

        if helpText == None:
            return tempHTML
        else:
            try:
                return ContextHelp().merge(self.tplId, tempHTML, helpText)
            except etree.LxmlError, e:
                if tempHTML.strip() == '':
                    raise MaKaCError(_("Template " + str(self.tplId) + " produced empty output, and it has a .wohl file. Error: " + str(e)))
                else:
                    raise
示例#47
0
    def _getResults(self, number):

        params = copy.copy(self._filteredParams)
        params['target'] = self._target.getId()

        queryHash = self._getQueryHash(params)

        Logger.get('search').debug('Hashing %s to %s' % (params, queryHash))

        # ATTENTION: _getStartingRecord will set self._page to 1,
        # if there's a cache miss
        start, cachedObj = self._getStartingRecord(queryHash, self._page)

        # get the access wrapper, so we can check user access privileges
        user = ContextManager.get("currentRH", None).getAW()

        results, numHits, shortResult, record = self._loadBatchOfRecords(user, number, start)

        self._cacheNextStartingRecord(queryHash, self._page, record, cachedObj)

        return (numHits, shortResult, record, results)
示例#48
0
    def _getResults(self, number):

        params = copy.copy(self._filteredParams)
        params['target'] = self._target.getId()

        queryHash = self._getQueryHash(params)

        Logger.get('search').debug('Hashing %s to %s' % (params, queryHash))

        # ATTENTION: _getStartingRecord will set self._page to 1,
        # if there's a cache miss
        start, cachedObj = self._getStartingRecord(queryHash, self._page)

        # get the access wrapper, so we can check user access privileges
        user = ContextManager.get("currentRH", None).getAW()

        results, numHits, shortResult, record = self._loadBatchOfRecords(user, number, start)

        self._cacheNextStartingRecord(queryHash, self._page, record, cachedObj)

        return (numHits, shortResult, record, results)
示例#49
0
文件: util.py 项目: hennogous/indico
def _build_folder_legacy_api_data(folder):
    avatar = ContextManager.get("currentAW").getUser()
    user = avatar.user if avatar else None
    if not folder.can_access(user):
        return None

    resources = [_build_attachment_legacy_api_data(attachment)
                 for attachment in folder.attachments
                 if attachment.can_access(user)]
    if not resources:  # Skipping empty folders for legacy API
        return None

    type_ = (folder.legacy_mapping.material_id.title()
             if folder.legacy_mapping is not None and not folder.legacy_mapping.material_id.isdigit()
             else 'Material')
    return {
        '_type': type_,
        '_fossil': 'materialMetadata',
        '_deprecated': True,
        'title': folder.title,
        'id': str(folder.id),
        'resources': resources
    }
示例#50
0
    def testContainsFalse(self):
        "__contains__ will return false"

        self.assertEquals('utest' in ContextManager.get(), False)
示例#51
0
    def getRooms( *args, **kwargs ):
        """ Documentation in base class. """

        roomsBTree = Room.getRoot()
        location = kwargs.get( 'location' )

        if kwargs.get( 'allFast' ) == True:
            return [ room for room in roomsBTree.values() if room.isActive and (not location or room.locationName == location) ]

        if kwargs.get( 'reallyAllFast' ) == True:
            return [ room for room in roomsBTree.values() if (not location or room.locationName == location) ]

        if len( kwargs ) == 0:
            ret_lst = []
            for room in roomsBTree.values():
                ret_lst.append( room )

        roomID = kwargs.get( 'roomID' )
        roomName = kwargs.get( 'roomName' )
        roomEx = kwargs.get( 'roomExample' )
        resvEx = kwargs.get( 'resvExample' )
        freeText = kwargs.get( 'freeText' )
        available = kwargs.get( 'available' )
        countOnly = kwargs.get( 'countOnly' )
        minCapacity = kwargs.get( 'minCapacity' )
        location = kwargs.get( 'location' )
        ownedBy = kwargs.get( 'ownedBy' )
        customAtts = kwargs.get( 'customAtts' )
#        responsibleID = kwargs.get( 'responsibleID' )
        pendingBlockings = kwargs.get( 'pendingBlockings' )

        ret_lst = []
        counter = 0
        if roomID != None:
            return roomsBTree.get( roomID )
        if roomName != None:
            for room in roomsBTree.itervalues():
                if room.name == roomName:
                    if location == None or room.locationName == location:
                        return room
            return None

        for room in roomsBTree.itervalues():
            # Apply all conditions =========
            if location != None:
                if room.locationName != location:
                    continue
            if roomEx != None:
                if not qbeMatch( roomEx, room, Room.__attrSpecialEqual, minCapacity = minCapacity ):
                    continue
                if not room.__hasEquipment( roomEx.getEquipment() ):
                    continue
            if freeText != None:
                if not room.__hasFreeText( freeText.split() ):
                    continue
            if resvEx != None:
                resvEx.room = room
                aval = room.isAvailable( resvEx )
                if aval != available:
                    continue
                blockState = resvEx.getBlockingConflictState(ContextManager.get('currentUser'))
                if blockState == 'active':
                    continue
                elif blockState == 'pending' and pendingBlockings:
                    continue
            if ownedBy != None:
                if not room.isOwnedBy( ownedBy ):
                    continue
            if customAtts is not None:
                if not hasattr(room, "customAtts"):
                    continue
                discard = False
                for condition in customAtts:
                    attName = condition["name"]
                    allowEmpty = condition.get("allowEmpty", False)
                    filter = condition.get("filter", None)
                    if not attName in room.customAtts:
                        discard = True
                        break
                    elif not allowEmpty and str(room.customAtts[attName]).strip() == "":
                        discard = True
                        break
                    elif not filter(room.customAtts[attName]):
                        discard = True
                        break
                if discard:
                    continue

            # All conditions are met: add room to the results
            counter += 1
            if not countOnly:
                ret_lst.append( room )

        #print "Found %d rooms." % counter
        if countOnly:
            return counter
        else:
            return ret_lst
示例#52
0
文件: conference.py 项目: fph/indico
        # first sanity check
        if (self._startDate > self._endDate):
            raise ServiceError("ERR-E3",
                               "Date/time of start cannot "
                               "be greater than date/time of end")

        # catch TimingErrors that can be returned by the algorithm
        try:
            with track_time_changes():
                self._target.setDates(self._startDate, self._endDate, moveEntries=moveEntries)
        except TimingError, e:
            raise TimingNoReportError(e.getMessage(),
                                      title=_("Cannot set event dates"),
                                      explanation=e.getExplanation())

        dateChangeNotificationProblems = ContextManager.get('dateChangeNotificationProblems')

        if dateChangeNotificationProblems:

            warningContent = []
            for problemGroup in dateChangeNotificationProblems.itervalues():
                warningContent.extend(problemGroup)

            w = Warning(_('Warning'), [_('The start date of your event was changed correctly. '
                                       'However, there were the following problems:'),
                                       warningContent])

            return ResultWithWarning(self._params.get('value'), w).fossilize()

        else:
            return self._params.get('value')
示例#53
0
    def testDoubleSetWorks(self):
        "Two consecutive set() operations over the same attribute"

        ContextManager.set('test2', 65)
        ContextManager.set('test2', 66)
        self.assertEquals(ContextManager.get('test2'), 66)
 def currentUserDetails(cls, caption):
     if not 'currentUser' in ContextManager.get():
         return ""
     user = ContextManager.get('currentUser')
     return cls.userDetails(caption, user)
示例#55
0
    def __init__(self, tpl_name=None):
        if tpl_name is not None:
            self.tplId = tpl_name

        self._rh = ContextManager.get('currentRH', None)
示例#56
0
 def thread1(self):
     ContextManager.set('samevariable', 'a')
     time.sleep(2)
     self.assertEquals(ContextManager.get('samevariable'), 'a')
示例#57
0
 def thread2(self):
     time.sleep(1)
     ContextManager.set('samevariable', 'b')
     self.assertEquals(ContextManager.get('samevariable'), 'b')
示例#58
0
    def testReturnsDummyDict(self):
        "Return a DummyDict in case the attribute is not defined"

        self.assertEquals(ContextManager.get('test').__class__, DummyDict)
示例#59
0
    def testGetDefault(self):
        "get() should support a default argument"

        self.assertEquals(ContextManager.get('utest', 'foo'), 'foo')
示例#60
0
    def testGetSilent(self):
        "get() shouldn't fail, but return a DummyDict instead"

        self.assertEquals(ContextManager.get('utest').__class__, DummyDict)