Last active
August 29, 2015 14:25
-
-
Save shinchit/ca2fe2b7e3a507d5c3ea to your computer and use it in GitHub Desktop.
[MovableType] [DataAPI] 画像タイプのカスタムフィールドを持つエントリーをData APIを使って投稿する
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/perl -w | |
use strict; | |
use warnings; | |
use LWP::UserAgent; | |
use HTTP::Request::Common; | |
use JSON; | |
use URI::Escape; | |
use Data::Dumper; | |
use Encode; | |
my $api_url = 'http://localhost/cgi-bin/mt/mt-data-api.cgi'; | |
my $blog_id = 1; | |
my $res; | |
my $json; | |
my $token; | |
my $lwp = LWP::UserAgent->new; | |
$lwp->timeout(20); | |
# authentication | |
$res = $lwp->post( | |
"$api_url/v1/authentication",{ | |
username => '[MTのログインアカウント名を指定]', | |
password => '[指定したアカウントのパスワードを指定]', | |
clientId => 'test', # 任意の文字列を指定する | |
} | |
); | |
$json = from_json($res->content); | |
$token = $json->{accessToken}; | |
if(! $token){ | |
print 'error authentication'; | |
return; | |
} | |
# 画像を投稿(アップロード)する | |
my $img_ep = "$api_url/v2/sites/$blog_id/assets/upload"; # 画像(厳密にはAsset)をアップロードするエントリーポイント | |
my $request = POST($img_ep, Content_Type => 'form-data', 'X-MT-Authorization' => "MTAuth accessToken=$token", Content => | |
{ | |
path => '', | |
file => ['/Users/takahiro/Desktop/IMG_1498.jpg'], # サンプルとしてデスクトップに置いたIMG_1498.jpgという画像を投稿(アップロード)する | |
autoRenameIfExists => 'true', | |
} | |
); | |
$res = $lwp->request($request); | |
$json = from_json($res->content); | |
# check status | |
if (! &check_status($json)) { exit; } | |
# 記事を投稿する(画像タイプのカスタムフィールドを持ち、そのカスタムフィールドには先に投稿した画像を紐付ける) | |
my $ep = "$api_url/v2/sites/$blog_id/entries"; # 記事を投稿するエントリーポイント | |
$request = POST($ep, 'X-MT-Authorization' => "MTAuth accessToken=$token"); | |
my $params = { | |
entry => encode_json({ | |
title => 'title - test(asset: ' . $json->{id} . ')', | |
status => 'Publish', | |
customFields => [ | |
{ | |
basename => 'custimg', | |
value => sprintf(qq{<form mt:asset-id='%d' class='mt-enclosure mt-enclosure-%s' style='display: inline'><a href="%s"><img src="%s"/ width="500"></a></form>}, $json->{id}, $json->{class}, $json->{url}, $json->{url}), | |
}, | |
], | |
}) | |
}; | |
$request->content(join('&', map{$_.'='.$params->{$_}} keys %$params)); | |
$res = $lwp->request($request); | |
$json = from_json($res->content); | |
# check_status | |
if (! &check_status($json)) { exit; } | |
# Data APIからのレスポンスをチェックして、不正であれば詳細メッセージ等を表示する | |
sub check_status { | |
my $json = shift; | |
if(! $json->{id}){ | |
my $message = $json->{ error }->{ message }; | |
$message =~ s/\\x{([0-9a-z]+)}/chr(hex($1))/ge; | |
print $json->{error}->{code}; | |
print ':'; | |
print $message; | |
return 0; | |
} | |
return 1; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment