]> jfr.im git - irc/rizon/acid.git/commitdiff
Updated .yt command to youtube v3 api
authorMartin Sileno <redacted>
Tue, 21 Apr 2015 21:22:45 +0000 (23:22 +0200)
committerMartin Sileno <redacted>
Tue, 21 Apr 2015 21:22:45 +0000 (23:22 +0200)
pyva/config.example.ini
pyva/pyva/src/main/python/internets/api/google.py
pyva/pyva/src/main/python/internets/cmd_user.py
pyva/pyva/src/main/python/internets/internets.py

index 2d0ffec44b554e3d583271d92279a2c7fe7dd052..e454a67cfa5f9de08e9f7030c781548f0ad42969 100644 (file)
@@ -58,6 +58,7 @@ key_lastfm: xxx
 key_fml: xxx
 key_wolframalpha: xxx
 key_steam: xxx
+key_google: xxx
 
 [limitserv]
 nick: Limitserv
index 24fb58c827a0954beffca4c50c65e656c91b6096..660a73ca7e1ceada5adad6c53568d159d7a02e30 100644 (file)
@@ -5,32 +5,8 @@ from feed import HtmlFeed, XmlFeed, get_json
 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&'
@@ -50,24 +26,37 @@ class Google(object):
                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'])
                        }
index 7e0dedb29b5147ccf37f305496047364f78d2ba6..3afbea1e5d531eab71f71d602d1008ca215e36b4 100644 (file)
@@ -259,7 +259,7 @@ def command_calc(self, manager, opts, arg, channel, sender, userinfo):
 
 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 '255.255.255.255')
        except FeedError, e:
                self.errormsg(channel, e.msg)
                return
@@ -269,13 +269,11 @@ def command_youtube_search(self, manager, opts, arg, channel, sender, userinfo):
                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
                        })
index 7d4226e2f6f9335962c68160c61a0746e1625b01..8196639c7371d67bdae7c75f1b1399aef15bfbdf 100644 (file)
@@ -113,7 +113,7 @@ class internets(
                        except Exception, err:
                                self.log.exception('Error initializing internets bing API (%s)' % err)
                        self.nsp = calc.NumericStringParser()
-                       self.google = google.Google()
+                       self.google = google.Google(self.config.get('internets', 'key_google'))
                        self.imdb = imdb.Imdb()
                        self.ipinfo = ipinfo.IpInfo(self.config.get('internets', 'key_ipinfodb'))
                        self.lastfm = lastfm.LastFm(self.config.get('internets', 'key_lastfm'))