Proxy fully operational; Initial API requests to Genius

This commit is contained in:
James Barnsley
2017-10-06 09:07:28 +13:00
parent 54149d9af4
commit b285d5c1a3
10 changed files with 71 additions and 33 deletions

View File

@ -563,7 +563,7 @@ class IrisCore(object):
req = urllib2.Request(url, data_encoded) req = urllib2.Request(url, data_encoded)
try: try:
response = urllib2.urlopen(req, timeout=15).read() response = urllib2.urlopen(req, timeout=30).read()
response_dict = json.loads(response) response_dict = json.loads(response)
self.spotify_token = response_dict self.spotify_token = response_dict
@ -626,9 +626,12 @@ class IrisCore(object):
target_request_headers = {} target_request_headers = {}
# Adjust headers # Adjust headers
target_request_headers["Accept-Language"] = "*"
target_request_headers["Accept-Encoding"] = "deflate" target_request_headers["Accept-Encoding"] = "deflate"
if "Content-Type" in target_request_headers: if "Content-Type" in target_request_headers:
del target_request_headers["Content-Type"] del target_request_headers["Content-Type"]
if "Host" in target_request_headers:
del target_request_headers["Host"]
# Our request includes data, so make sure we POST the data # Our request includes data, so make sure we POST the data
if ('data' in data and data['data']): if ('data' in data and data['data']):
@ -636,10 +639,17 @@ class IrisCore(object):
# No data, so just a simple GET request # No data, so just a simple GET request
else: else:
# Strip out our origin content-length otherwise this confuses
# the target server as content-length doesn't apply to GET requests
if "Content-Length" in target_request_headers:
del target_request_headers["Content-Length"]
target_request = urllib2.Request(data['url'], headers=target_request_headers) target_request = urllib2.Request(data['url'], headers=target_request_headers)
# Now actually attempt the request
try: try:
target_response = urllib2.urlopen(target_request, timeout=15) target_response = urllib2.urlopen(target_request, timeout=30)
target_response_body = target_response.read() target_response_body = target_response.read()
try: try:
@ -654,7 +664,6 @@ class IrisCore(object):
} }
except urllib2.HTTPError as e: except urllib2.HTTPError as e:
self.raven_client.captureException()
return { return {
'status': 0, 'status': 0,
'message': 'Could not complete proxy request', 'message': 'Could not complete proxy request',
@ -665,7 +674,6 @@ class IrisCore(object):
} }
except urllib2.URLError as e: except urllib2.URLError as e:
self.raven_client.captureException()
return { return {
'status': 0, 'status': 0,
'message': 'Could not complete proxy request', 'message': 'Could not complete proxy request',
@ -673,3 +681,12 @@ class IrisCore(object):
'response_code': int(e.code), 'response_code': int(e.code),
'original_request': data 'original_request': data
} }
else:
return {
'status': 0,
'message': 'Could not complete proxy request',
'source': 'proxy_request',
'response_code': null,
'original_request': data
}

View File

@ -122,11 +122,18 @@ class HttpHandler(tornado.web.RequestHandler):
def set_default_headers(self): def set_default_headers(self):
self.set_header("Access-Control-Allow-Origin", "*") self.set_header("Access-Control-Allow-Origin", "*")
self.set_header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization, Client-Security-Token, Accept-Encoding")
def initialize(self, core, config): def initialize(self, core, config):
self.core = core self.core = core
self.config = config self.config = config
# Options request
# This is a preflight request for CORS requests
def options(self, slug=None):
self.set_status(204)
self.finish()
def get(self, slug=None): def get(self, slug=None):
# make sure the method exists # make sure the method exists

View File

@ -19,13 +19,17 @@ export default class TrackInfoModal extends React.Component{
} }
render(){ render(){
var track = this.props.current_track; if (this.props.current_track){
var track = this.props.current_track;
} else {
var track = null
}
return ( return (
<div> <div>
<h1>Track info</h1> <h1>Track info</h1>
<h2 className="grey-text">{track.name} by <ArtistSentence artists={track.artists} /></h2> {track ? <h2 className="grey-text">{track.name} by <ArtistSentence artists={track.artists} /></h2> : null}
{track.annotations ? track.annotations.id : "No annotations"} {track && track.annotations ? track.annotations.id : "No annotations"}
</div> </div>
) )
} }

View File

@ -7,6 +7,7 @@ export function getBroadcasts(){
return (dispatch, getState) => { return (dispatch, getState) => {
var config = { var config = {
method: 'GET', method: 'GET',
timeout: 15000,
url: 'https://gist.githubusercontent.com/jaedb/b677dccf80daf3ccb2ef12e96e495677/raw' url: 'https://gist.githubusercontent.com/jaedb/b677dccf80daf3ccb2ef12e96e495677/raw'
} }
$.ajax(config).then( $.ajax(config).then(

View File

@ -4,7 +4,7 @@ var uiActions = require('../ui/actions')
var helpers = require('../../helpers') var helpers = require('../../helpers')
/** /**
* Send an ajax request to the Spotify API * Send an ajax request
* *
* @param dispatch obj * @param dispatch obj
* @param getState obj * @param getState obj
@ -17,26 +17,33 @@ const sendRequest = (dispatch, getState, endpoint) => {
dispatch(uiActions.startLoading(loader_key, 'genius_'+endpoint)); dispatch(uiActions.startLoading(loader_key, 'genius_'+endpoint));
var config = { var config = {
method: 'GET', method: 'POST',
cache: false, cache: false,
url: 'https://api.genius.com/'+endpoint+'&access_token=2AGP9sfzKQcxfKSZuGa_3lqsDIpuOiTGT7-vhJYcKaaDjHIIA2HICsxXCiC30Xxi' timeout: 15000,
headers: {
Authorization: 'Bearer 2AGP9sfzKQcxfKSZuGa_3lqsDIpuOiTGT7-vhJYcKaaDjHIIA2HICsxXCiC30Xxi'
},
data: JSON.stringify({
url: 'https://api.genius.com/'+endpoint
}),
url: '//'+getState().mopidy.host+':'+getState().mopidy.port+'/iris/http/proxy_request'
}; };
$.ajax(config).then( $.ajax(config).then(
response => { response => {
dispatch(uiActions.stopLoading(loader_key)); dispatch(uiActions.stopLoading(loader_key));
resolve(response.response); resolve(response.response);
}, },
(xhr, status, error) => { (xhr, status, error) => {
dispatch(uiActions.stopLoading(loader_key)); dispatch(uiActions.stopLoading(loader_key));
reject({ reject({
config: config, config: config,
xhr: xhr, xhr: xhr,
status: status, status: status,
error: error error: error
}); });
} }
) )
}) })
} }
@ -49,15 +56,15 @@ export function getTrackInfo(track){
} }
query += track.name; query += track.name;
sendRequest(dispatch, getState, 'search?q='+query) sendRequest(dispatch, getState, 'search?q='+encodeURIComponent(query))
.then( .then(
response => { response => {
if (response.hits && response.hits.length > 0){ if (response.response.hits && response.response.hits.length > 0){
dispatch({ dispatch({
type: 'TRACK_LOADED', type: 'TRACK_LOADED',
key: track.uri, key: track.uri,
track: { track: {
annotations: response.hits[0].result annotations: response.response.hits[0].result
} }
}); });
} }
@ -68,6 +75,6 @@ export function getTrackInfo(track){
error error
)); ));
} }
) );
} }
} }

View File

@ -19,6 +19,7 @@ const sendRequest = ( dispatch, getState, params ) => {
var config = { var config = {
method: 'GET', method: 'GET',
cache: true, cache: true,
timeout: 15000,
url: '//ws.audioscrobbler.com/2.0/?format=json&api_key=4320a3ef51c9b3d69de552ac083c55e3&'+params url: '//ws.audioscrobbler.com/2.0/?format=json&api_key=4320a3ef51c9b3d69de552ac083c55e3&'+params
} }

View File

@ -159,13 +159,13 @@ const MopidyMiddleware = (function(){
var loader_key = helpers.generateGuid() var loader_key = helpers.generateGuid()
store.dispatch(uiActions.startLoading(loader_key, 'mopidy_'+property)) store.dispatch(uiActions.startLoading(loader_key, 'mopidy_'+property))
// Start our 10 second timeout // Start our 15 second timeout
var timeout = setTimeout( var timeout = setTimeout(
function(){ function(){
store.dispatch(uiActions.stopLoading(loader_key)); store.dispatch(uiActions.stopLoading(loader_key));
reject({message: "Request timed out", call: call, value: value}); reject({message: "Request timed out", call: call, value: value});
}, },
10000 15000
); );
mopidyObject(value) mopidyObject(value)

View File

@ -59,7 +59,7 @@ export function sendAuthorization( recipient_connectionid, authorization, me ){
return { return {
type: 'PUSHER_DELIVER_MESSAGE', type: 'PUSHER_DELIVER_MESSAGE',
data: { data: {
to: recipient_connectionid, connection_id: recipient_connectionid,
message: { message: {
type: 'spotify_authorization', type: 'spotify_authorization',
authorization: authorization, authorization: authorization,

View File

@ -63,13 +63,13 @@ const PusherMiddleware = (function(){
store.dispatch(uiActions.startLoading(request_id, 'pusher_'+method)) store.dispatch(uiActions.startLoading(request_id, 'pusher_'+method))
// Start our 10 second timeout // Start our 15 second timeout
var timeout = setTimeout( var timeout = setTimeout(
function(){ function(){
store.dispatch(uiActions.stopLoading(request_id)); store.dispatch(uiActions.stopLoading(request_id));
reject({message: "Request timed out", method: method, data: data}); reject({message: "Request timed out", method: method, data: data});
}, },
10000 15000
); );
// add query to our deferred responses // add query to our deferred responses

View File

@ -33,6 +33,7 @@ const sendRequest = ( dispatch, getState, endpoint, method = 'GET', data = false
method: method, method: method,
url: url, url: url,
cached: true, cached: true,
timeout: 15000,
headers: { headers: {
Authorization: 'Bearer '+ response Authorization: 'Bearer '+ response
} }