Created
September 18, 2012 08:19
-
-
Save jankuca/3741984 to your computer and use it in GitHub Desktop.
VKontakte Audio Search
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
goog.provide('VKontakte'); | |
goog.require('goog.crypt.Md5'); | |
VKontakte = function (user_id, app_id, app_secret) { | |
this.user_id_ = user_id; | |
this.app_id_ = app_id; | |
this.app_secret_ = app_secret; | |
}; | |
VKontakte.API_ENDPOINT = 'http://api.vk.com/api.php'; | |
VKontakte.prototype.search = function (artist, track, callback) { | |
var uri = this.getSearchURI_(artist, track); | |
this.request_('GET', uri, function (status, response) { | |
if (status === 0) { | |
callback(new Error('No Internet connection'), null); | |
} else { | |
var result = response[1]; | |
if (!result) { | |
callback(new Error('No audio'), null); | |
} else { | |
callback(null, result.audio.url); | |
} | |
} | |
}); | |
}; | |
VKontakte.prototype.getSearchURI_ = function (artist, track) { | |
var q = artist + ' ' + track; | |
var params = { | |
'method': 'audio.search', | |
'q': q.toLowerCase(), | |
'sort': 2, | |
'test_mode': 1, | |
'api_id': this.app_id_, | |
'format': 'json', | |
'count': 10 | |
}; | |
params['sig'] = this.generateApiRequestSignature_(params); | |
return VKontakte.API_ENDPOINT + this.createSearchString_(params); | |
}; | |
VKontakte.prototype.generateApiRequestSignature_ = function (params) { | |
var input = this.user_id_; | |
// Keys are required to be ordered alphabetically. | |
Object.keys(params).sort().forEach(function (key) { | |
input += key + '=' + params[key]; | |
}); | |
input += this.app_secret_; | |
var md5 = new goog.crypt.Md5(); | |
md5.update(input); | |
return md5.digest().map(function (digit) { | |
return digit.toString(16); | |
}).join(''); | |
}; | |
VKontakte.prototype.createSearchString_ = function (params) { | |
var parts = []; | |
var encode = window.encodeURIComponent; | |
for (var key in params) { | |
if (params.hasOwnProperty(key)) { | |
parts.push(key + '=' + encode(params[key])); | |
} | |
} | |
return '?' + parts.join('&'); | |
}; | |
VKontakte.prototype.request_ = function (method, uri, callback) { | |
var xhr = new XMLHttpRequest(); | |
xhr.open(method, uri, true); | |
xhr.onreadystatechange = function () { | |
if (xhr.readyState === 4) { | |
var response = {}; | |
try { | |
response = JSON.parse(xhr.responseText); | |
} finally { | |
callback(xhr.statusCode, response.response || response); | |
} | |
} | |
}; | |
xhr.send(null); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment