Skip to content

Instantly share code, notes, and snippets.

@alphaKAI
Last active August 29, 2015 13:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alphaKAI/9585216 to your computer and use it in GitHub Desktop.
Save alphaKAI/9585216 to your computer and use it in GitHub Desktop.
D言語でTwitter UserStreamしてみた std.jsonでパースしてる
import std.digest.sha,
std.algorithm,
std.datetime,
std.net.curl,
std.base64,
std.array,
std.regex,
std.stdio,
std.json,
std.conv,
std.uri;
ubyte[] hmac_sha1(in string key, in string message){
auto padding(in ubyte[] k){
auto h = (64 < k.length)? sha1Of(k): k;
return h ~ new ubyte[64 - h.length];
}
const k = padding(cast(ubyte[])key);
return sha1Of((k.map!q{cast(ubyte)(a^0x5c)}.array) ~ sha1Of((k.map!q{cast(ubyte)(a^0x36)}.array) ~ cast(ubyte[])message)).dup;
}
string signature(string cks, string ats, string method, string url, string[string] params){
auto query = params.keys.sort.map!(k => k ~ "=" ~ params[k]).join("&");
auto key = [cks, ats].map!encodeComponent.join("&");
auto base = [method, url, query].map!encodeComponent.join("&");
string oauthSignature = encodeComponent(Base64.encode(hmac_sha1(key, base)));
return oauthSignature;
}
void main(){
string url = "https://userstream.twitter.com/1.1/user.json";
string now = Clock.currTime.toUnixTime.to!string;
string consumerKey = "Your ConsumerKey",
consumerKeySecret = "Your ConsumerKeySecret",
accessToken = "Your AccessToken",
accessTokenSecret = "Your AccessTokenSecret";
string[string] params = [
"oauth_consumer_key" : consumerKey,
"oauth_nonce" : "4324yfe",
"oauth_signature_method" : "HMAC-SHA1",
"oauth_timestamp" : now,
"oauth_token" : accessToken,
"oauth_version" : "1.0"];
foreach(key, value; params)
params[key] = encodeComponent(value);
string oauthSignature = signature(consumerKeySecret, accessTokenSecret, "GET", url, params);
params["oauth_signature"] = oauthSignature;
auto authorizeKeys = params.keys.filter!q{a.countUntil("oauth_")==0};
auto authorize = "OAuth " ~ authorizeKeys.map!(k => k ~ "=" ~ params[k]).join(",");
string path = params.keys.map!(k => k ~ "=" ~ params[k]).join("&");
auto http = HTTP();
http.addRequestHeader("Authorization", authorize);
http.method = HTTP.Method.get;
auto st = byLineAsync(url ~ "?" ~ path);
foreach(line; st){
if(match(line.to!string, regex(r"\{.*\}"))){
auto parsed = parseJSON(line.to!string);
if("text" in parsed.object){//tweet
writeln("\r------------------------------------------------------------------------------");
writefln("%s:\n%s", parsed.object["user"].object["name"].str, parsed.object["text"].str);
writeln("------------------------------------------------------------------------------");
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment