Python twisted.internet.defer.maybeDeferred() Examples

The following are 30 code examples of twisted.internet.defer.maybeDeferred(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module twisted.internet.defer , or try the search function .
Example #1
Source File: protocols.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def validateTo(self, user):
        """
        Validate the address for which a message is destined.

        @type user: L{User}
        @param user: The destination address.

        @rtype: L{Deferred <defer.Deferred>} which successfully fires with
            no-argument callable which returns L{IMessage <smtp.IMessage>}
            provider.
        @return: A deferred which successfully fires with a no-argument
            callable which returns a message receiver for the destination.

        @raise SMTPBadRcpt: When messages cannot be accepted for the
            destination address.
        """
        # XXX - Yick.  This needs cleaning up.
        if self.user and self.service.queue:
            d = self.service.domains.get(user.dest.domain, None)
            if d is None:
                d = relay.DomainQueuer(self.service, True)
        else:
            d = self.service.domains[user.dest.domain]
        return defer.maybeDeferred(d.exists, user) 
Example #2
Source File: server.py    From bitmask-dev with GNU General Public License v3.0 6 votes vote down vote up
def _cbSelectWork(self, mbox, cmdName, tag):
        """
        Callback for selectWork

        * patched to avoid conformance errors due to incomplete UIDVALIDITY
        line.
        * patched to accept deferreds for messagecount and recent count
        """
        if mbox is None:
            self.sendNegativeResponse(tag, 'No such mailbox')
            return
        if '\\noselect' in [s.lower() for s in mbox.getFlags()]:
            self.sendNegativeResponse(tag, 'Mailbox cannot be selected')
            return

        d1 = defer.maybeDeferred(mbox.getMessageCount)
        d2 = defer.maybeDeferred(mbox.getRecentCount)
        d3 = defer.maybeDeferred(mbox.getUIDNext)
        return defer.gatherResults([d1, d2, d3]).addCallback(
            self.__cbSelectWork, mbox, cmdName, tag) 
Example #3
Source File: Events.py    From Timeline with GNU General Public License v3.0 6 votes vote down vote up
def __call__(self, event):
        event = dict(event)
        ra = event['a']
        kw = event['kw']
        if 'ra' in event and self in PacketEventHandler.function_w_rules:
            ra = event['ra']
            kw = event['rkw']

        a = maybeDeferred(self.function, *ra, **kw)
        def err(x):
            a = x.getTraceback().split('\n')
            self.x.logger.error("Error executing method - {} : {}".format(self.function.__name__, x.getErrorMessage() + "["+ a[-2].strip() + ' in ' + a[-4].strip() +"]"))
            x.printDetailedTraceback()

        a.addErrback(err)
        return a 
Example #4
Source File: cftp.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def _dispatchCommand(self, line):
        if ' ' in line:
            command, rest = line.split(' ', 1)
            rest = rest.lstrip()
        else:
            command, rest = line, ''
        if command.startswith('!'): # command
            f = self.cmd_EXEC
            rest = (command[1:] + ' ' + rest).strip()
        else:
            command = command.upper()
            log.msg('looking up cmd %s' % command)
            f = getattr(self, 'cmd_%s' % command, None)
        if f is not None:
            return defer.maybeDeferred(f, rest)
        else:
            errMsg = "No command called `%s'" % (command)
            self._ebCommand(failure.Failure(NotImplementedError(errMsg)))
            self._newLine() 
Example #5
Source File: checkers.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def requestAvatarId(self, credentials):
        """
        Part of the L{ICredentialsChecker} interface.  Called by a portal with
        some credentials to check if they'll authenticate a user.  We check the
        interfaces that the credentials provide against our list of acceptable
        checkers.  If one of them matches, we ask that checker to verify the
        credentials.  If they're valid, we call our L{_cbGoodAuthentication}
        method to continue.

        @param credentials: the credentials the L{Portal} wants us to verify
        """
        ifac = providedBy(credentials)
        for i in ifac:
            c = self.checkers.get(i)
            if c is not None:
                d = defer.maybeDeferred(c.requestAvatarId, credentials)
                return d.addCallback(self._cbGoodAuthentication,
                        credentials)
        return defer.fail(UnhandledCredentials("No checker for %s" % \
            ', '.join(map(reflect.qual, ifac)))) 
Example #6
Source File: filetransfer.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def packet_CLOSE(self, data):
        requestId = data[:4]
        data = data[4:]
        handle, data = getNS(data)
        assert data == b'', 'still have data in CLOSE: %s' % repr(data)
        if handle in self.openFiles:
            fileObj = self.openFiles[handle]
            d = defer.maybeDeferred(fileObj.close)
            d.addCallback(self._cbClose, handle, requestId)
            d.addErrback(self._ebStatus, requestId, b"close failed")
        elif handle in self.openDirs:
            dirObj = self.openDirs[handle][0]
            d = defer.maybeDeferred(dirObj.close)
            d.addCallback(self._cbClose, handle, requestId, 1)
            d.addErrback(self._ebStatus, requestId, b"close failed")
        else:
            self._ebClose(failure.Failure(KeyError()), requestId) 
Example #7
Source File: test_imap.py    From bitmask-dev with GNU General Public License v3.0 6 votes vote down vote up
def _cbTestPartialAppend(self, fetched, infile):
        fetched = list(fetched)
        self.assertTrue(len(fetched) == 1)
        self.assertTrue(len(fetched[0]) == 2)
        uid, msg = fetched[0]
        parsed = self.parser.parse(open(infile))
        expected_body = parsed.get_payload()

        def assert_flags(flags):
            self.assertEqual(
                set((['\\SEEN'])), set(flags))

        def assert_body(body):
            gotbody = body.read()
            self.assertEqual(expected_body, gotbody)

        d = defer.maybeDeferred(msg.getFlags)
        d.addCallback(assert_flags)

        d.addCallback(lambda _: defer.maybeDeferred(msg.getBodyFile))
        d.addCallback(assert_body)
        return d 
Example #8
Source File: imap4.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def login(self, username, password):
        """
        Authenticate with the server using a username and password

        This command is allowed in the Non-Authenticated state.  If the
        server supports the STARTTLS capability and our transport supports
        TLS, TLS is negotiated before the login command is issued.

        A more secure way to log in is to use C{startTLS} or
        C{authenticate} or both.

        @type username: L{str}
        @param username: The username to log in with

        @type password: L{str}
        @param password: The password to log in with

        @rtype: C{Deferred}
        @return: A deferred whose callback is invoked if login is successful
        and whose errback is invoked otherwise.
        """
        d = maybeDeferred(self.getCapabilities)
        d.addCallback(self.__cbLoginCaps, username, password)
        return d 
Example #9
Source File: task.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def __call__(self):
        def cb(result):
            if self.running:
                self._scheduleFrom(self.clock.seconds())
            else:
                d, self._deferred = self._deferred, None
                d.callback(self)

        def eb(failure):
            self.running = False
            d, self._deferred = self._deferred, None
            d.errback(failure)

        self.call = None
        d = defer.maybeDeferred(self.f, *self.a, **self.kw)
        d.addCallback(cb)
        d.addErrback(eb) 
Example #10
Source File: checkers.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def requestAvatarId(self, c):
        try:
            u, p = self.getUser(c.username)
        except KeyError:
            return defer.fail(error.UnauthorizedLogin())
        else:
            up = credentials.IUsernamePassword(c, None)
            if self.hash:
                if up is not None:
                    h = self.hash(up.username, up.password, p)
                    if h == p:
                        return defer.succeed(u)
                return defer.fail(error.UnauthorizedLogin())
            else:
                return defer.maybeDeferred(c.checkPassword, p
                    ).addCallback(self._cbPasswordMatch, u)



# For backwards compatibility
# Allow access as the old name. 
Example #11
Source File: util.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def _runSequentially(callables, stopOnFirstError=False):
    """
    Run the given callables one after the other. If a callable returns a
    Deferred, wait until it has finished before running the next callable.

    @param callables: An iterable of callables that take no parameters.

    @param stopOnFirstError: If True, then stop running callables as soon as
        one raises an exception or fires an errback. False by default.

    @return: A L{Deferred} that fires a list of C{(flag, value)} tuples. Each
        tuple will be either C{(SUCCESS, <return value>)} or C{(FAILURE,
        <Failure>)}.
    """
    results = []
    for f in callables:
        d = defer.maybeDeferred(f)
        try:
            thing = yield d
            results.append((defer.SUCCESS, thing))
        except Exception:
            results.append((defer.FAILURE, Failure()))
            if stopOnFirstError:
                break
    defer.returnValue(results) 
Example #12
Source File: imap4.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def __doCommand(self, tag, handler, args, parseargs, line, uid):
        for (i, arg) in enumerate(parseargs):
            if callable(arg):
                parseargs = parseargs[i+1:]
                maybeDeferred(arg, self, line).addCallback(
                    self.__cbDispatch, tag, handler, args,
                    parseargs, uid).addErrback(self.__ebDispatch, tag)
                return
            else:
                args.append(arg)

        if line:
            # Too many arguments
            raise IllegalClientResponse("Too many arguments for command: " + repr(line))

        if uid is not None:
            handler(uid=uid, *args)
        else:
            handler(*args) 
Example #13
Source File: smtp.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def do_RCPT(self, rest):
        if not self._from:
            self.sendCode(503, "Must have sender before recipient")
            return
        m = self.rcpt_re.match(rest)
        if not m:
            self.sendCode(501, "Syntax error")
            return

        try:
            user = User(m.group('path'), self._helo, self, self._from)
        except AddressError as e:
            self.sendCode(553, str(e))
            return

        d = defer.maybeDeferred(self.validateTo, user)
        d.addCallbacks(
            self._cbToValidate,
            self._ebToValidate,
            callbackArgs=(user,)
        ) 
Example #14
Source File: test_asyncassertions.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def test_assertFailure_masked(self):
        """
        A single wrong assertFailure should fail the whole test.
        """
        class ExampleFailure(Exception):
            pass

        class TC(unittest.TestCase):
            failureException = ExampleFailure
            def test_assertFailure(self):
                d = defer.maybeDeferred(lambda: 1/0)
                self.assertFailure(d, OverflowError)
                self.assertFailure(d, ZeroDivisionError)
                return d

        test = TC('test_assertFailure')
        result = pyunit.TestResult()
        test.run(result)
        self.assertEqual(1, len(result.failures)) 
Example #15
Source File: smtp.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def do_MAIL(self, rest):
        if self._from:
            self.sendCode(503,"Only one sender per message, please")
            return
        # Clear old recipient list
        self._to = []
        m = self.mail_re.match(rest)
        if not m:
            self.sendCode(501, "Syntax error")
            return

        try:
            addr = Address(m.group('path'), self.host)
        except AddressError as e:
            self.sendCode(553, str(e))
            return

        validated = defer.maybeDeferred(self.validateFrom, self._helo, addr)
        validated.addCallbacks(self._cbFromValidate, self._ebFromValidate) 
Example #16
Source File: pop3.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def do_PASS(self, password):
        """
        Handle a PASS command.

        If a USER command was previously received, authenticate the user and
        complete the authorization process with the L{_cbMailbox} callback
        function on success or the L{_ebMailbox} and L{_ebUnexpected} errback
        functions on failure.  If a USER command was not previously received,
        send an error response.

        @type password: L{bytes}
        @param password: A password.
        """
        if self._userIs is None:
            self.failResponse("USER required before PASS")
            return
        user = self._userIs
        self._userIs = None
        d = defer.maybeDeferred(self.authenticateUserPASS, user, password)
        d.addCallbacks(self._cbMailbox, self._ebMailbox, callbackArgs=(user,)
        ).addErrback(self._ebUnexpected) 
Example #17
Source File: pop3.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def do_APOP(self, user, digest):
        """
        Handle an APOP command.

        Perform APOP authentication and complete the authorization process with
        the L{_cbMailbox} callback function on success or the L{_ebMailbox}
        and L{_ebUnexpected} errback functions on failure.

        @type user: L{bytes}
        @param user: A username.

        @type digest: L{bytes}
        @param digest: An MD5 digest string.
        """
        d = defer.maybeDeferred(self.authenticateUserAPOP, user, digest)
        d.addCallbacks(self._cbMailbox, self._ebMailbox, callbackArgs=(user,)
        ).addErrback(self._ebUnexpected) 
Example #18
Source File: common.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def query(self, query, timeout=None):
        try:
            method = self.typeToMethod[query.type]
        except KeyError:
            return defer.fail(failure.Failure(NotImplementedError(
                        str(self.__class__) + " " + str(query.type))))
        else:
            return defer.maybeDeferred(method, query.name.name, timeout) 
Example #19
Source File: imap4.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def do_STATUS(self, tag, mailbox, names):
        mailbox = self._parseMbox(mailbox)
        maybeDeferred(self.account.select, mailbox, 0
            ).addCallback(self._cbStatusGotMailbox, tag, mailbox, names
            ).addErrback(self._ebStatusGotMailbox, tag
            ) 
Example #20
Source File: checkers.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def requestAvatarId(self, credentials):
        d = defer.maybeDeferred(self._sanityCheckKey, credentials)
        d.addCallback(self._checkKey, credentials)
        d.addCallback(self._verifyKey, credentials)
        return d 
Example #21
Source File: test_imap.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def requestAvatarId(self, credentials):
        if credentials.username in self.users:
            return defer.maybeDeferred(
                credentials.checkPassword, self.users[credentials.username]
        ).addCallback(self._cbCheck, credentials.username) 
Example #22
Source File: imap4.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def _listWork(self, tag, ref, mbox, sub, cmdName):
        mbox = self._parseMbox(mbox)
        maybeDeferred(self.account.listMailboxes, ref, mbox
            ).addCallback(self._cbListWork, tag, sub, cmdName
            ).addErrback(self._ebListWork, tag
            ) 
Example #23
Source File: imap4.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def _selectWork(self, tag, name, rw, cmdName):
        if self.mbox:
            self.mbox.removeListener(self)
            cmbx = ICloseableMailbox(self.mbox, None)
            if cmbx is not None:
                maybeDeferred(cmbx.close).addErrback(log.err)
            self.mbox = None
            self.state = 'auth'

        name = self._parseMbox(name)
        maybeDeferred(self.account.select, self._parseMbox(name), rw
            ).addCallback(self._cbSelectWork, cmdName, tag
            ).addErrback(self._ebSelectWork, cmdName, tag
            ) 
Example #24
Source File: imap4.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def do_LOGIN(self, tag, user, passwd):
        if b'LOGINDISABLED' in self.capabilities():
            self.sendBadResponse(tag, b'LOGIN is disabled before STARTTLS')
            return

        maybeDeferred(self.authenticateLogin, user, passwd
            ).addCallback(self.__cbLogin, tag
            ).addErrback(self.__ebLogin, tag
            ) 
Example #25
Source File: test_filetransfer.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def testOpenDirectory(self):
        d = self.client.openDirectory(b'')
        self._emptyBuffers()
        files = []

        def _getFiles(openDir):
            def append(f):
                files.append(f)
                return openDir
            d = defer.maybeDeferred(openDir.next)
            self._emptyBuffers()
            d.addCallback(append)
            d.addCallback(_getFiles)
            d.addErrback(_close, openDir)
            return d

        def _checkFiles(ignored):
            fs = list(list(zip(*files))[0])
            fs.sort()
            self.assertEqual(fs,
                                 [b'.testHiddenFile', b'testDirectory',
                                  b'testRemoveFile', b'testRenameFile',
                                  b'testfile1'])

        def _close(_, openDir):
            d = openDir.close()
            self._emptyBuffers()
            return d

        d.addCallback(_getFiles)
        d.addCallback(_checkFiles)
        return d 
Example #26
Source File: test_cftp.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def stopServer(self):
        if not hasattr(self.server.factory, 'proto'):
            return self._cbStopServer(None)
        self.server.factory.proto.expectedLoseConnection = 1
        d = defer.maybeDeferred(
            self.server.factory.proto.transport.loseConnection)
        d.addCallback(self._cbStopServer)
        return d 
Example #27
Source File: test_cftp.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def _cbStopServer(self, ignored):
        return defer.maybeDeferred(self.server.stopListening) 
Example #28
Source File: filetransfer.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def packet_OPEN(self, data):
        requestId = data[:4]
        data = data[4:]
        filename, data = getNS(data)
        flags ,= struct.unpack('!L', data[:4])
        data = data[4:]
        attrs, data = self._parseAttributes(data)
        assert data == b'', 'still have data in OPEN: %s' % repr(data)
        d = defer.maybeDeferred(self.client.openFile, filename, flags, attrs)
        d.addCallback(self._cbOpenFile, requestId)
        d.addErrback(self._ebStatus, requestId, b"open failed") 
Example #29
Source File: test_mail.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def tearDownDNS(self):
    dl = []
    dl.append(defer.maybeDeferred(self.port.stopListening))
    dl.append(defer.maybeDeferred(self.udpPort.stopListening))
    try:
        self.resolver._parseCall.cancel()
    except:
        pass
    return defer.DeferredList(dl) 
Example #30
Source File: amp.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def _wrapWithSerialization(self, aCallable, command):
        """
        Wrap aCallable with its command's argument de-serialization
        and result serialization logic.

        @param aCallable: a callable with a 'command' attribute, designed to be
        called with keyword arguments.

        @param command: the command class whose serialization to use.

        @return: a 1-arg callable which, when invoked with an AmpBox, will
        deserialize the argument list and invoke appropriate user code for the
        callable's command, returning a Deferred which fires with the result or
        fails with an error.
        """
        def doit(box):
            kw = command.parseArguments(box, self)
            def checkKnownErrors(error):
                key = error.trap(*command.allErrors)
                code = command.allErrors[key]
                desc = str(error.value)
                return Failure(RemoteAmpError(
                        code, desc, key in command.fatalErrors, local=error))
            def makeResponseFor(objects):
                try:
                    return command.makeResponse(objects, self)
                except:
                    # let's helpfully log this.
                    originalFailure = Failure()
                    raise BadLocalReturn(
                        "%r returned %r and %r could not serialize it" % (
                            aCallable,
                            objects,
                            command),
                        originalFailure)
            return maybeDeferred(aCallable, **kw).addCallback(
                makeResponseFor).addErrback(
                checkKnownErrors)
        return doit