| OLD | NEW |
| (Empty) |
| 1 # Copyright (c) 2001-2004 Twisted Matrix Laboratories. | |
| 2 # See LICENSE for details. | |
| 3 | |
| 4 # | |
| 5 """\"I'm Feeling Lucky\" with U{Google<http://google.com>}. | |
| 6 """ | |
| 7 import urllib | |
| 8 from twisted.internet import protocol, reactor, defer | |
| 9 from twisted.web import http | |
| 10 | |
| 11 class GoogleChecker(http.HTTPClient): | |
| 12 | |
| 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) | |
| 17 self.endHeaders() | |
| 18 | |
| 19 def handleHeader(self, key, value): | |
| 20 key = key.lower() | |
| 21 if key == 'location': | |
| 22 self.factory.gotLocation(value) | |
| 23 | |
| 24 def handleStatus(self, version, status, message): | |
| 25 if status != '302': | |
| 26 self.factory.noLocation(ValueError("bad status")) | |
| 27 | |
| 28 def handleEndHeaders(self): | |
| 29 self.factory.noLocation(ValueError("no location")) | |
| 30 | |
| 31 def handleResponsePart(self, part): | |
| 32 pass | |
| 33 | |
| 34 def handleResponseEnd(self): | |
| 35 pass | |
| 36 | |
| 37 def connectionLost(self, reason): | |
| 38 self.factory.noLocation(reason) | |
| 39 | |
| 40 | |
| 41 class GoogleCheckerFactory(protocol.ClientFactory): | |
| 42 | |
| 43 protocol = GoogleChecker | |
| 44 | |
| 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() | |
| 52 | |
| 53 def clientConnectionFailed(self, _, reason): | |
| 54 self.noLocation(reason) | |
| 55 | |
| 56 def gotLocation(self, location): | |
| 57 if self.deferred: | |
| 58 self.deferred.callback(location) | |
| 59 self.deferred = None | |
| 60 | |
| 61 def noLocation(self, error): | |
| 62 if self.deferred: | |
| 63 self.deferred.errback(error) | |
| 64 self.deferred = None | |
| 65 | |
| 66 | |
| 67 def checkGoogle(words): | |
| 68 """Check google for a match. | |
| 69 | |
| 70 @returns: a Deferred which will callback with a URL or errback with a | |
| 71 Failure. | |
| 72 """ | |
| 73 factory = GoogleCheckerFactory(words) | |
| 74 reactor.connectTCP('www.google.com', 80, factory) | |
| 75 return factory.deferred | |
| OLD | NEW |