tetsunosukeのnotebook

tetsunosukeのメモです

iKnowの学習状況の数値をはてなグラフに投げる(ちょっと適当)

Flashのバッヂ見ていて気づいたんだけど、要はRSS形式のものを読んでいるんですね。
なのでそれを使ってWSSEヘッダ作ってはてなグラフAPIに投げて終わり。

<?php
require_once 'HTTP/Request.php';
// はてなID/PW
$hatena_id = 'はてなID';
$hatena_pw = 'パスワード';

// グラフ名
$hatena_graphname = "iKnow::Dictation";

// iKnowユーザ名
$iknow_id = 'tetsunosuke';
$type = "dictation"; //

// はてなグラフAPI
$hatena_api_url = "http://graph.hatena.ne.jp/api/data";


/* main */
$wsse_header = create_wsse_header($hatena_id, $hatena_pw);

$value = get_progress($iknow_id, $type);
echo $value;

post_graphdata($wsse_header, $hatena_graphname, $value);



/**
 * WSSEヘッダー生成
 */
function create_wsse_header($hatena_id, $hatena_pw)
{
    //$nonce = pack('H*', sha1(md5(time().rand().posix_getpid())));
    $nonce = pack('H*', sha1(md5(time().rand())));
    $created = date('Y-m-d\TH:i:s\Z');
    $digest = base64_encode(sha1($nonce . $created . $hatena_pw, true));
    return sprintf('UsernameToken Username="%s", PasswordDigest="%s", Nonce="%s", Created="%s"',
                    $hatena_id, $digest, base64_encode($nonce), $created);
}


/**
 * はてなグラフにデータ送信
 */
function post_graphdata($wsse, $name, $value)
{
    global $hatena_api_url;
    $req = new HTTP_Request($hatena_api_url);
    $req->setMethod(HTTP_REQUEST_METHOD_POST);
    $req->addHeader('X-WSSE', $wsse);
    $req->addPostData("graphname", $name);
    $req->addPostData("value", $value);
    $res = $req->sendRequest();
    if (PEAR::isError($res)) {
        die($res->getMessage());
    }
    if( $req->getResponseCode() === 201){ echo "OK";}
}

/**
 * 進捗のRSSを読み込んで値取得
 */
function get_progress($id, $type)
{
    // http://www.iknow.co.jp/assets/rss/user/tetsunosuke/dictation_badge.rss
    $rss = 'http://www.iknow.co.jp/assets/rss/user/' . $id . '/' . $type . '_badge.rss';
   
   
    /** RSSを取得して解析してvalueを返す **/
    $result = getContents($rss);
    $obj = simplexml_load_string( getContents($rss) );
    return $obj->channel->item[1]->description;
}

/**
 * リモートからデータの取得
 */
function getContents($url)
{
    $req = new HTTP_Request($url);
    $res = $req->sendRequest();
    if(PEAR::isError($res)){
        return "";
    }
   
    return $req->getResponseBody();
}