Skip to content

Instantly share code, notes, and snippets.

@hubgit
Created April 5, 2009 18:37
Show Gist options
  • Save hubgit/90502 to your computer and use it in GitHub Desktop.
Save hubgit/90502 to your computer and use it in GitHub Desktop.
Amazon resolver for Playdar (30 sec clips only)
#!/usr/bin/php
<?php
define('AWSACCESSID', '1SVFNCKVJ7JWK2NPG002');
$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(
'Service' => 'AWSECommerceService',
'AWSAccessKeyId' => AWSACCESSID,
'Operation' => 'ItemSearch',
'SearchIndex' => 'MP3Downloads',
'Author' => $q->artist,
'Title' => $q->track,
'ResponseGroup' => 'ItemAttributes',
'TagsPerPage' => 3 , // 3 results
);
$xml = simplexml_load_string(file_get_contents('http://ecs.amazonaws.com/onca/xml?' . http_build_query($params)));
if (!is_object($xml) || empty($xml->Items->Item))
return array();
$items = array();
foreach ($xml->Items->Item as $item){
if ((string) $item->ItemAttributes->ProductGroup != 'Digital Music Track')
continue;
$meta = $item->ItemAttributes;
$output = (object) array(
'artist' => (string) $meta->Creator,
'track' => (string) $meta->Title,
'album' => $meta->Label ? (string) $meta->Label : 'Unknown',
'source' => 'Amazon',
'url' => 'http://www.amazon.com/gp/dmusic/get_sample_url.html?DownloadLocation=WEBSITE&ie=UTF8&ASIN=' . (string) $item->ASIN,
'mimetype' => 'audio/mpeg',
'bitrate' => 128,
'duration' => 30,
'size' => 524288, // (30 / 60) * 1024 * 1024,
);
if (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' => 'Amazon MP3 clips 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