Ruby

[PHP,Ruby]Instagram Graph API

PHP

<?php
function echo_json_by_filename($filename)
{
    header("Content-Type: application/json; charset=utf-8");
    if(is_readable($filename)) {
        readfile($filename);
    }else{
        echo '{data:[]}';
    }
}
$businessID          = '111111';
$hashTagID           = '17843677603040508';//パスタ
$targetInstaUsername = isset($_GET['u']) ? $_GET['u'] : '';
$targetFileNo        = isset($_GET['no']) ? $_GET['no'] : '';
$apiBaseUrl          = 'https://graph.facebook.com/v5.0/';
$accessToken         = 'abcdefg';
$urlForHashTag       = "{$apiBaseUrl}{$hashTagID}/recent_media?user_id={$businessID}&fields=id,media_type,media_url,permalink,like_count,comments_count&limit=50&access_token={$accessToken}";
$urlForUsername      = "{$apiBaseUrl}{$businessID}?fields=business_discovery.username({$targetInstaUsername}){id,followers_count,media_count,ig_id,media{caption,permalink,username,media_url,media_type,like_count,comments_count,timestamp,id}}&access_token={$accessToken}";
$urls                = array($urlForHashTag,$urlForUsername);
$nos                 = array_keys($urls);
$filename            = dirname(__FILE__) . "/insta{$targetFileNo}.json";
if(empty($targetInstaUsername) || !is_numeric($targetFileNo) || !in_array($targetFileNo,$nos)){
    echo_json_by_filename($filename);
    exit;
}
if(file_exists($filename)){
    $t = filemtime($filename);
    if($t === false || abs($t - time()) < 60){
        echo_json_by_filename($filename);
        exit;
    }
    if(unlink($filename) === false){
        echo_json_by_filename($filename);
        exit;
    }
}
$data = file_get_contents($urls[$targetFileNo]);
file_put_contents($filename,$data);
header("Content-Type: application/json; charset=utf-8");
echo $data;

Ruby

#!/Ruby23-x64/bin/ruby
# coding: utf-8
ENV['SSL_CERT_FILE'] = File.expand_path('/cert/cacert.pem')
require "cgi"
require "net/https"
require "uri"
require "date"
def echo_json_by_filename(filename)
	puts "Content-Type: application/json; charset=utf-8\n\n"
    if File.exist?(filename) then
        File.open(filename, "r") do |f|
          puts f.read
        end
    else
        puts "{data:[]}"
    end
end
cgi = CGI.new
businessID          = "111111"
hashTagID           = "17843677603040508"#パスタ
targetInstaUsername = cgi["u"]
targetFileNo        = cgi["no"]
apiBaseUrl          = "https://graph.facebook.com/v5.0/"
accessToken         = "abcdefg"
urlForHashTag       = apiBaseUrl + hashTagID + "/recent_media?user_id="+businessID+"&fields=id,media_type,media_url,permalink,like_count,comments_count&limit=50&access_token=" + accessToken
urlForUsername      = apiBaseUrl + businessID + "?fields=business_discovery.username("+targetInstaUsername+"){id,followers_count,media_count,ig_id,media{caption,permalink,username,media_url,media_type,like_count,comments_count,timestamp,id}}&access_token=" + accessToken
filename            = "./insta"+targetFileNo+".json"
if targetInstaUsername.empty? || targetFileNo.empty? then
	echo_json_by_filename(filename)
	exit
end
if File.exist?(filename) then
	gap = DateTime.now.to_time - File.mtime(filename)
	if gap < 60 then
		echo_json_by_filename(filename)
		exit
	end
	File.delete(filename)
end
uri = URI.parse urlForUsername
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
req = Net::HTTP::Get.new uri.request_uri
res = http.request req
file = File.open(filename,"w")
file.puts(res.body)
puts "Content-Type: application/json; charset=utf-8\n\n"
puts res.body
exit

[Ruby]formの値を受け取る

formの値を受け取る

サンプル

#!/usr/bin/ruby-1.9.3
# coding: utf-8
require 'cgi'

puts "Content-type: text/plain\n\n"
cgi = CGI.new
keys=cgi.keys
keys.each{|value|
    puts value+" = "+cgi[value]+"\n"
}

[Ruby]ファイルを読み込む

ファイルを読み込む

サンプル

#!/usr/bin/ruby-1.9.3
# coding: utf-8
require 'json'

puts "Content-type: application/json\n\n"

filename="test.txt"
results=Array.new

if File.exist?(filename)
    f = open(filename)
    f.each{|line|
        results.push(line.force_encoding("utf-8"))
    }
    f.close
else
    results.push("no data")
end

puts JSON.generate({'time'=>Time.now.strftime("%Y-%m-%d %H:%M:%S"), 'data'=>results})

[Ruby]MySQLからデータ取得

MySQLからデータ取得

サンプル

#!/usr/bin/ruby-1.9.3
# coding: utf-8
require 'json'
require 'mysql'

puts "Content-type: application/json\n\n"

connection = Mysql.connect('host','user','password','db name')
connection.query("set character set utf8") #文字化けするとき

columns=["ID","post_title","post_date"]
result = connection.query("SELECT "+columns.join(",")+" FROM wp_posts WHERE post_status='publish' ORDER BY ID DESC LIMIT 5")
connection.close

results=Array.new
result.each {|record|
    w = {}
    record.each_with_index{|val,i|
        key = columns[i]
        w[key.force_encoding("utf-8")]=val.force_encoding("utf-8") #文字化けするときforce_encoding
    }
    results.push(w)
}
puts JSON.generate({'time'=>Time.now.strftime("%Y-%m-%d %H:%M:%S"), 'data'=>results})

[Ruby]jsonを出力する

jsonを出力する

サンプル

#coding:utf-8
require 'json'
print("Content-type: application/json\n\n")

print JSON.generate({"time"=>Time.now.strftime("%Y-%m-%d %H:%M:%S"),
                    "user"=>[
                                {"id" => 32, "name"=>"jeff"},
                                {"id" => 56, "name"=>"john"}
                            ]
                    })