~davidc3/ubuntu-rest-scopes/testing-newyorktimes

« back to all changes in this revision

Viewing changes to src/scopes/grooveshark.py

  • Committer: David Callé
  • Date: 2014-02-11 09:16:57 UTC
  • mfrom: (3.1.15 ubuntu-rest-scopes)
  • Revision ID: davidc@framli.eu-20140211091657-2759quotvgxqg318
Merge trunk, fix conflitcts, add secrets config

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright 2014 Canonical
 
2
# All Rights Reserved
 
3
 
 
4
"""The Grooveshark scope."""
 
5
 
 
6
import urllib
 
7
import json
 
8
import hmac
 
9
 
 
10
from urllib2 import urlopen, Request
 
11
 
 
12
from ..scopes import SimpleApp
 
13
 
 
14
SEARCH_URI = 'https://api.grooveshark.com/ws3.php?sig='
 
15
 
 
16
DEFAULT_COUNTRY = {'CC1': 0,
 
17
                   'CC2': 0,
 
18
                   'CC3': 0,
 
19
                   'CC4': 0,
 
20
                   'DMA': 0,
 
21
                   'ID': 0,
 
22
                   'IPR': 0}
 
23
 
 
24
CLIENT_IP = '173.194.42.19'
 
25
 
 
26
 
 
27
class APIError(Exception):
 
28
    """ API errors catcher """
 
29
 
 
30
 
 
31
def api_call(method, api_utils, client_ip=CLIENT_IP, **parameters):
 
32
    """ Call the Grooveshark API """
 
33
    data = {}
 
34
    data['method'] = method
 
35
    data['parameters'] = parameters
 
36
    data['header'] = {'wsKey': api_utils['key']}
 
37
    data_str = json.dumps(data).encode("utf-8")
 
38
    sig = hmac.new(api_utils['secret'], data_str).hexdigest()
 
39
    headers = {'X-Client-IP': client_ip}
 
40
    req = Request(SEARCH_URI+sig, data_str,
 
41
                  headers=headers)
 
42
    response = urlopen(req)
 
43
    response_data = response.read()
 
44
    result = json.loads(response_data.decode("utf-8"))
 
45
    if 'errors' in result:
 
46
        error = result.get('errors')[0]
 
47
        raise APIError("Error: %r" % (error,))
 
48
    return result
 
49
 
 
50
# Override category renderer
 
51
RENDERER_MUSIC = {
 
52
    "schema-version": 1,
 
53
    'template': {'category-layout': 'grid', 'card-size': 'medium'},
 
54
    'components': {'title': 'title',
 
55
                   'art': 'art',
 
56
                   'subtitle': 'artist'},
 
57
}
 
58
 
 
59
# Declare categories
 
60
SONGS_CATEGORY = {
 
61
    'id': 'cat_0',
 
62
    'title': 'Songs',
 
63
    'render_template': json.dumps(RENDERER_MUSIC),
 
64
    'icon': "FIXME",
 
65
}
 
66
ALBUMS_CATEGORY = {
 
67
    'id': 'cat_1',
 
68
    'title': 'Albums',
 
69
    'render_template': json.dumps(RENDERER_MUSIC),
 
70
    'icon': "FIXME",
 
71
}
 
72
 
 
73
 
 
74
class App(SimpleApp):
 
75
    """The Grooveshark app."""
 
76
 
 
77
    def __init__(self, *args, **kwargs):
 
78
        super(App, self).__init__(*args, **kwargs)
 
79
        self.api_utils = {'key': self.config['secrets'].get('api_key'),
 
80
                          'secret': self.config['secrets'].get('api_secret')}
 
81
 
 
82
    def search(self, **kwargs):
 
83
        """Do the search."""
 
84
        query = kwargs['query']
 
85
        limit = kwargs['limit']
 
86
        form_factor = kwargs['platform']
 
87
        yield dict(category=SONGS_CATEGORY)
 
88
        yield dict(category=ALBUMS_CATEGORY)
 
89
        if form_factor == "phone":
 
90
            base_uri = 'http://html5.grooveshark.com'
 
91
        else:
 
92
            base_uri = 'http://grooveshark.com'
 
93
        albums = {'result': {'albums': []}}
 
94
        songs = {'result': {'songs': []}}
 
95
 
 
96
        if not query.strip():
 
97
            songs = api_call("getPopularSongsMonth",
 
98
                             self.api_utils,
 
99
                             client_ip=CLIENT_IP, limit=limit)
 
100
        else:
 
101
            albums = api_call("getAlbumSearchResults",
 
102
                              self.api_utils,
 
103
                              client_ip=CLIENT_IP,
 
104
                              query=query, limit=limit)
 
105
            songs = api_call("getSongSearchResults",
 
106
                             self.api_utils,
 
107
                             client_ip=CLIENT_IP,
 
108
                             query=query, limit=10,
 
109
                             country=DEFAULT_COUNTRY)
 
110
 
 
111
        for i in albums['result']['albums']:
 
112
            if i['AlbumName'].strip().lower() != query.strip().lower():
 
113
                continue
 
114
            album_name_parsed = urllib.quote(i['AlbumName'])
 
115
            album_uri = '%(uri)s/#/album/%(aname)s/%(aid)s' \
 
116
                % dict(uri=base_uri,
 
117
                       aname=album_name_parsed,
 
118
                       aid=str(i['AlbumID']))
 
119
            if i.get('CoverArtFilename') and \
 
120
                    len(i.get('CoverArtFilename')) > 0:
 
121
                icon = 'http://beta.grooveshark.com/static/' \
 
122
                    'amazonart/m%(cover)s' \
 
123
                    % dict(cover=str(i['CoverArtFilename']))
 
124
            else:
 
125
                icon = 'http://beta.grooveshark.com/static/' \
 
126
                    'amazonart/m%(aid)s.jpg' \
 
127
                    % dict(aid=str(i['AlbumID']))
 
128
            yield dict(result={'uri': album_uri,
 
129
                               'title': i['AlbumName'],
 
130
                               'album': i['AlbumName'],
 
131
                               'artist': i['ArtistName'],
 
132
                               'album_id': str(i['AlbumID']),
 
133
                               'album_uri': album_uri,
 
134
                               'art': icon,
 
135
                               'form_factor': form_factor,
 
136
                               'cat_id': 'cat_1'})
 
137
 
 
138
        for i in songs['result']['songs']:
 
139
            album_name_parsed = urllib.quote(i['AlbumName'])
 
140
            album_uri = '%(uri)s/#/album/%(aname)s/%(aid)s' \
 
141
                % dict(uri=base_uri,
 
142
                       aname=album_name_parsed,
 
143
                       aid=str(i['AlbumID']))
 
144
            if i.get('CoverArtFilename') and \
 
145
                    len(i.get('CoverArtFilename')) > 0:
 
146
                icon = 'http://beta.grooveshark.com/static/' \
 
147
                    'amazonart/m%(aid)s' \
 
148
                    % dict(aid=str(i['CoverArtFilename']))
 
149
            else:
 
150
                icon = 'http://beta.grooveshark.com/static/' \
 
151
                    'amazonart/m%(aid)s.jpg' \
 
152
                    % dict(aid=str(i['AlbumID']))
 
153
            yield dict(result={'uri': album_uri,
 
154
                               'title': i['SongName'],
 
155
                               'album': i['AlbumName'],
 
156
                               'artist': i['ArtistName'],
 
157
                               'album_id': str(i['AlbumID']),
 
158
                               'song_id': str(i['SongID']),
 
159
                               'art': icon,
 
160
                               'form_factor': form_factor,
 
161
                               'cat_id': 'cat_0'})
 
162
 
 
163
    def preview(self, **kwargs):
 
164
        """Do the preview."""
 
165
        result = kwargs['result']
 
166
        try:
 
167
            song = api_call("getSongURLFromSongID",
 
168
                            client_ip=CLIENT_IP,
 
169
                            songID=result['song_id'])
 
170
            if self.result['form_factor'] == "phone":
 
171
                action_uri = song['url'].replace('/grooveshark.com/s',
 
172
                                                 '/html5.grooveshark.com/s')
 
173
        except:
 
174
            action_uri = result['uri']
 
175
 
 
176
        # yield a 'header' widget
 
177
        yield {
 
178
            'id': 'header',
 
179
            'type': 'header',
 
180
            'title': result['title'],
 
181
            'art': result['art'],
 
182
            'subtitle': result['artist'],
 
183
        }
 
184
        # add an 'actions' widget
 
185
        yield {
 
186
            'id': 'buttons',
 
187
            'type': 'actions',
 
188
            'actions': [{'label': 'Grooveshark',
 
189
                        'uri': action_uri}]
 
190
        }