Skip to content

Instantly share code, notes, and snippets.

@hubgit
Created April 5, 2009 17:22
Show Gist options
  • Save hubgit/90488 to your computer and use it in GitHub Desktop.
Save hubgit/90488 to your computer and use it in GitHub Desktop.
Vattoz resolver for Playdar
#!/usr/bin/php
<?php
$in = fopen('php://STDIN','r');
// report our settings before entering the main query loop:
send_reply(get_settings());
// main loop: wait for a query, try and find match and reply.
while (!feof($in)){
// read $len bytes for the actual payload and assume it's a JSON object.
$len = unpack('N', fread($in, 4));
$q = json_decode(fread($in, $len[1]));
if (!is_object($q))
continue;
$results = get_matches($q);
// don't reply with anything if there were no matches:
if (empty($results))
continue;
send_reply((object) array(
'_msgtype' => 'results',
'qid' => $q->qid,
'results' => $results,
));
}
// put a 4-byte big-endian int first, denoting length of message
function send_reply($obj){
$str = str_replace('\/','/',json_encode($obj)); // i think json_spirit rejects \/ even tho it's valid json. doh.
print pack('N', strlen($str)) . $str;
}
function get_matches($q){
$params = array(
'query' => sprintf('"%s" "%s"', $q->artist, $q->track),
);
$url = 'http://www.vattoz.com/Services/Search.aspx';
$json = file_get_contents($url, NULL, stream_context_create(array('http' => array('method' => 'POST', 'content' => http_build_query($params)))));
$json = str_replace('"', '\"', $json);
$json = preg_replace('/\\\\./', '', $json); // something's causing errors in PHP's json_decode
$json = str_replace(array(":'", "',", "' ,"), array(':"', '",', '",'), $json);
$json = str_replace(array('id:', 'title:', 'duration:'), array('"id":', '"title":', '"duration":'), $json); // fix invalid JSON
$data = json_decode($json);
if (!is_array($data) || empty($data))
return array();
$items = array();
foreach ($data as $item){
preg_match('/(.+?)\s+-\s+(.+)/', $item->title, $matches);
$output = (object) array(
'artist' => empty($matches) ? $q->artist : $matches[1],
'track' => empty($matches) ? $q->track : $matches[2],
'album' => 'Unknown',
'mimetype' => 'audio/mpeg',
'source' => 'Vattoz',
'url' => sprintf('http://www.vattoz.com/Services/Get.aspx?fn=%s.mp3', $item->id),
'bitrate' => 128, // hardcoded
'duration' => $item->duration,
'size' => round((($item->duration / 60) * 1024 * 1024)),
);
if (!empty($matches) && strtolower($output->artist) == strtolower($q->artist) && strtolower($output->track) == strtolower($q->track))
$output->score = (float) 1.0;
else
$output->score = (float) 0.5;
$items[] = $output;
}
return $items;
}
// settings for this resolver, reported when we start:
function get_settings(){
return (object) array(
'_msgtype' => 'settings',
'name' => 'Vattoz resolver script',
'targettime' => 2000, // ms
'weight' => 50, // 1-100. higher means preferable.
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment