1
0
Fork 0
vkontakte_music_search/src/vkontakte_music.coffee

73 lines
2.3 KiB
CoffeeScript
Raw Normal View History

2011-09-15 19:23:42 +00:00
###
* Vkontakte (VK.com) API music search tool
* https://github.com/magnolia-fan/vkontakte_music_search
*
* Copyright 2011, Gregory Eremin
* Licensed under the MIT license.
* https://raw.github.com/magnolia-fan/vkontakte_music_search/master/LICENSE
###
2011-10-12 08:36:20 +00:00
2011-09-26 09:53:35 +00:00
class window.VkontakteMusic
2011-09-15 19:02:34 +00:00
query_results: {}
2011-09-15 14:13:10 +00:00
2011-09-15 19:02:34 +00:00
search: (artist, track, duration, callback, return_all = false) ->
2011-09-15 14:13:10 +00:00
query = this.prepareQuery artist, track
2011-09-15 19:02:34 +00:00
if @query_results[query]? and not return_all
2011-09-15 14:13:10 +00:00
callback @query_results[query]
that = this
VK.Api.call 'audio.search', q: query, (r) ->
2011-09-15 19:02:34 +00:00
results = that.range r.response, artist, track, duration
top_result = null
if results.length > 0
top_result = results[0].url
that.query_results[query] = results
callback if return_all then results else top_result
2011-09-15 14:13:10 +00:00
2011-09-15 19:02:34 +00:00
range: (data, artist, track, duration) ->
if typeof duration is 'string'
duration = duration.split ':'
duration = parseInt(duration[0], 10) * 60 + parseInt(duration[1], 10)
for item, i in data
if typeof item isnt 'object'
continue
2011-10-12 08:36:20 +00:00
item.score = 0
item.artist = this.trim(item.artist)
item.title = this.trim(item.title)
2011-09-15 19:02:34 +00:00
score = 0
if item.artist.length > 0
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.artist.length > 0
if item.title == track
score += 10
else if item.title.split(track).length is 2
score += 5
2011-10-12 08:36:20 +00:00
if duration != 0 and parseInt(item.duration, 10) == duration
2011-09-15 19:02:34 +00:00
score += 15
else
delta = Math.abs parseInt(item.duration, 10) - duration
score += (10 - delta) if delta < 10
data[i].score = score
2011-10-12 08:36:20 +00:00
if data.length > 0
if typeof data[0] isnt 'object'
data.splice(0, 1)
2011-09-15 19:02:34 +00:00
data.sort (a, b) ->
b.score - a.score
data
2011-09-15 14:13:10 +00:00
prepareQuery: (artist, track) ->
artist+" "+track.replace(/\(.*\)/i, '').split('/')[0]
trim: (str) ->
2011-09-15 19:32:23 +00:00
while str.indexOf(' ') isnt -1
2011-10-12 08:36:20 +00:00
str = str.replace(' ', ' ')
2011-09-15 19:32:23 +00:00
if str.charAt(0) is ' '
2011-10-12 08:36:20 +00:00
str = str.substring(1)
2011-09-15 19:32:23 +00:00
if str.charAt(str.length - 1) is ' '
2011-10-12 08:36:20 +00:00
str = str.substring(0, str.length - 1)
2011-09-15 19:32:23 +00:00
str