from utils import unescape
class Google(object):
- def __init__(self):
- pass
-
- # Google shutdown their iGoogle "API",
- #def calc(self, expr):
- # url = 'http://www.google.com/ig/calculator?'
- # url += urlencode({'q': expr})
- # page = HtmlFeed(url) #, fake_ua=True)
- # text = page.html()
- # # Convert to valid JSON: {foo: "1"} -> {"foo" : "1"},
- # # {"foo": "\x25"} -> {"foo": "\u0025"}
- # result = re.sub("([a-z]+):", '"\\1" :', text)
- # # XXX: HACK; using two substitutes instead of one, but I can't into regex
- # result = re.sub('\\\\x([0-9a-f]{2})', '\\u00\\1', result)
- # result = re.sub('\\\\x([0-9a-f]{1})', '\\u000\\1', result)
- #
- # result = unicode(result, 'unicode_escape')
- # result = unescape(result)
- # # Special case: fractions; those are <sup></sup> unicode-slash <sub></sub>
- # result = re.sub(u'<sup>([^<]*)</sup>\u2044<sub>([^<]*)</sub>', ' \\1/\\2', result)
- # # Also un-html-ify <sup>/</sup> because google doesn't send proper plaintext
- # result = re.sub('<sup>([^<]*)</sup>', '^\\1', result)
- # # Same with <sub>.
- # result = re.sub('<sub>([^<]*)</sub>', '_\\1', result)
- # result = json.loads(result.encode('utf-8'))
- # return result
+ def __init__(self, api_key):
+ self.api_key = api_key
def search(self, query, userip=None):
url = 'http://ajax.googleapis.com/ajax/services/search/web?v=1.0&'
json = get_json(url)
return json
- def yt_search(self, query, num=1):
- url = 'https://gdata.youtube.com/feeds/api/videos?v=2&max-results=5&'
- url += urlencode({'q': query})
- xml = XmlFeed(url)
- entry = xml.elements('/feed/entry[%d]' % num)
- if not entry:
+ def yt_search(self, query, num=0, userip=None):
+ url = 'https://www.googleapis.com/youtube/v3/search?part=snippet&order=relevance&type=video&maxResults=5&'
+ parameters = {'q': query, 'key': self.api_key}
+ if userip:
+ parameters['userip'] = userip
+
+ url += urlencode(parameters)
+ js = get_json(url)
+ if not js['items']:
return None
- v = entry[0]
+ video_info = js['items'][num]
+ url = 'https://www.googleapis.com/youtube/v3/videos?&part=contentDetails,statistics&'
+ parameters = {'id': video_info['id']['videoId'], 'key': self.api_key}
+ if userip:
+ parameters['userip'] = userip
+
+ url += urlencode(parameters)
+ js = get_json(url)
+ video_details = js['items'][0]
+ m = re.search(r'P((?:\d)+D)?T?(\d+H)?(\d+M)?(\d+S)?', video_details['contentDetails']['duration'])
+ days, hours, minutes, seconds = map(lambda x: int(x[:-1]) if x else 0, m.groups())
+ stats = video_details['statistics']
+
return {
- 'title': v.text('title'),
- 'duration': v.int('media:group/yt:duration/@seconds'),
- 'uploaded': v.text('media:group/yt:uploaded'),
- 'id': v.text('media:group/yt:videoid'),
- 'rating': v.decimal('gd:rating/@average'),
- 'rate_count': v.int('gd:rating/@numRaters'),
- 'favorite_count': v.int('yt:statistics/@favoriteCount'),
- 'view_count': v.int('yt:statistics/@viewCount'),
- 'liked': v.int('yt:rating/@numLikes'),
- 'disliked': v.int('yt:rating/@numDislikes')
+ 'title': video_info['snippet']['title'],
+ 'duration': 86400 * days + 3600 * hours + 60 * minutes + seconds,
+ 'uploaded': video_info['snippet']['publishedAt'],
+ 'id': video_info['id']['videoId'],
+ 'favorite_count': int(stats['favoriteCount']),
+ 'view_count': int(stats['viewCount']),
+ 'liked': int(stats['likeCount']),
+ 'disliked': int(stats['dislikeCount'])
}
def command_google_search(self, manager, opts, arg, channel, sender, userinfo):
try:
- result = self.google.search(arg, userinfo['ip'] if userinfo['ip'] != '0' else '255.255.255.255')
+ result = self.google.search(arg, userinfo['ip'] if userinfo['ip'] != '0' else None)
except FeedError, e:
self.errormsg(channel, e.msg)
return
def command_google_image_search(self, manager, opts, arg, channel, sender, userinfo):
try:
- result = self.google.image_search(arg, userinfo['ip'] if userinfo['ip'] != '0' else '255.255.255.255')
+ result = self.google.image_search(arg, userinfo['ip'] if userinfo['ip'] != '0' else None)
except FeedError, e:
self.errormsg(channel, e.msg)
return
def command_youtube_search(self, manager, opts, arg, channel, sender, userinfo):
try:
- res = self.google.yt_search(arg)
+ res = self.google.yt_search(arg, userip=userinfo['ip'] if userinfo['ip'] != '0' else None)
except FeedError, e:
self.errormsg(channel, e.msg)
return
return
self.msg(channel, """@sep @bYouTube@b %(title)s @sep @bURL@b %(url)s (%(duration)s) @sep @bViews@b %(views)s @sep \
-@bRating@b %(rating)s/5 - %(votes)s votes @c3@b[+]@b %(liked)s likes @c4@b[-]@b %(disliked)s dislikes @sep""" % {
+@bRating@b @c3@b[+]@b %(liked)s likes @c4@b[-]@b %(disliked)s dislikes @sep""" % {
'title': res['title'],
'url': 'http://www.youtube.com/watch?v=' + res['id'],
'duration': '%s' % format_hms(res['duration']),
'views': format_thousand(res['view_count']),
- 'rating': round(res['rating'], 2) if res['rating'] else 0,
- 'votes': format_thousand(res['rate_count']) if res['rate_count'] else 0,
'liked': format_thousand(res['liked']) if res['liked'] else 0,
'disliked': format_thousand(res['disliked']) if res['disliked'] else 0
})