1
0
Fork 0
oldhaven/app/coffeescripts/vkontakte.coffee

93 lines
2.4 KiB
CoffeeScript

class Vkontakte
qr: []
constructor: (@api_id) ->
init: ->
VK.init
apiId: @api_id
nameTransportPath: '/xd_receiver.html'
VK.Auth.getLoginStatus this.authInfo
authInfo: (response) ->
if typeof response isnt 'undefined' and response.session
session.setVkParams response.session
$('#vk_login, .auth_notice').hide()
$('#vk_logout').css display: 'block'
$('#search_field').focus() if $('#search_field').length > 0
session.query '/user/auth', {}, (ar) ->
if ar.newbie
VK.Api.call 'getVariable', key: 1281, (r) ->
Session.query '/user/update', name: r.response, (ar2) ->
session.user = ar2.user
$('#header-container .hello .greating')
.text 'Hi there, ' +(if session.user.name then session.user.name else '%username%')+ '!'
else
session.user = ar.user
$('#header-container .hello .greating')
.text 'Hi there, ' +( if session.user.name then session.user.name else '%username%')+ '!'
else
$('#vk_login, .auth_notice').css display: 'block'
$('#vk_logout').hide()
loadTracksData: (artist, track, duration, callback) ->
track_prepared = track.replace(/\(.*\)/i, '').split('/')[0];
query = artist +' '+ track_prepared;
if @qr[query]?
callback @qr[query]
else
VK.Api.call 'audio.search', q: query, (r) ->
url = this.matchPerfectResult r.response, artist, track, duration
@qr[query] = url;
callback url
matchPerfectResult: (data, artist, track, duration) ->
duration = duration.split ':'
duration = parseInt(duration[0], 10) * 60 + parseInt(duration[1], 10)
best_score = 0;
best_result = null;
for item in data
score = 0;
item.artist = item.artist.trim();
item.title = item.title.trim();
if item.artist == artist
score += 10
else if item.artist.split(artist).length is 2
score += 5
else if item.title.split(artist).length is 2
score += 4
if item.title == track
score += 10
else if item.title.split(track).length is 2
score += 5
if parseInt(item.duration, 10) == duration
score += 15
else
delta = Math.abs parseInt(item.duration, 10) - duration
score += (10 - delta) if delta < 10
if score > best_score
best_score = score
best_result = item
if score is 35
return best_result.url
return best_result.url
$ ->
$('#vk_login').click ->
VK.Auth.login vkontakte.authInfo, 8
$('#vk_logout').click ->
VK.Auth.logout vkontakte.authInfo