1 # Copyright (c) Twisted Matrix Laboratories.
2 # See LICENSE for details.
5 """\"I'm Feeling Lucky\" with U{Google<http://google.com>}.
8 from twisted.internet import protocol, reactor, defer
9 from twisted.web import http
11 class GoogleChecker(http.HTTPClient):
13 def connectionMade(self):
14 self.sendCommand('GET', self.factory.url)
15 self.sendHeader('Host', self.factory.host)
16 self.sendHeader('User-Agent', self.factory.agent)
19 def handleHeader(self, key, value):
22 self.factory.gotLocation(value)
24 def handleStatus(self, version, status, message):
26 self.factory.noLocation(ValueError("bad status"))
28 def handleEndHeaders(self):
29 self.factory.noLocation(ValueError("no location"))
31 def handleResponsePart(self, part):
34 def handleResponseEnd(self):
37 def connectionLost(self, reason):
38 self.factory.noLocation(reason)
41 class GoogleCheckerFactory(protocol.ClientFactory):
43 protocol = GoogleChecker
45 def __init__(self, words):
46 self.url = ('/search?q=%s&btnI=%s' %
47 (urllib.quote_plus(' '.join(words)),
48 urllib.quote_plus("I'm Feeling Lucky")))
49 self.agent="Twisted/GoogleChecker"
50 self.host = "www.google.com"
51 self.deferred = defer.Deferred()
53 def clientConnectionFailed(self, _, reason):
54 self.noLocation(reason)
56 def gotLocation(self, location):
58 self.deferred.callback(location)
61 def noLocation(self, error):
63 self.deferred.errback(error)
67 def checkGoogle(words):
68 """Check google for a match.
70 @returns: a Deferred which will callback with a URL or errback with a
73 factory = GoogleCheckerFactory(words)
74 reactor.connectTCP('www.google.com', 80, factory)
75 return factory.deferred