Menu

Skip to content
AppleScriptの穴
  • Home
  • Products
  • Books
  • Docs
  • Events
  • Forum
  • About This Blog
  • License
  • 仕事依頼

AppleScriptの穴

Useful & Practical AppleScript archive. Click '★Click Here to Open This Script' Link to download each AppleScript

カテゴリー: REST API

Recruit Tech Small Talk API

Posted on 6月 25, 2018 by Takaaki Naganoya

Recruit techのA3RT機械学習ソリューションAPIのひとつ、「Small Talk API」を呼び出すAppleScriptです。

エンタメ用に機械学習させたお手軽日本語チャットボット作成用のAPIとのこと。APIの説明ページからAPI Keyを取得して本リストに記載して実行させてみてください。

「おはよう」に「おはよう」で返したり、質問に質問で返すような「使えないチャットボットAPI」ですが、雑談系チャットボットに過剰な期待をするのは間違いなので、こんなもんなんでしょう。

AppleScript名:Recruit Tech Talk API
— Created 2018-06-13 by Takaaki Naganoya
— 2018 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"

set apiKeyStr to getAPIKey() of me
set targText to text returned of (display dialog "Input Some text" default answer "")

set sText to "curl -X POST -d ’apikey=" & apiKeyStr & "’ –data-urlencode ’query=" & targText & "’ ’https://api.a3rt.recruit-tech.co.jp/talk/v1/smalltalk’"
set aRes to do shell script sText
set jsonString to current application’s NSString’s stringWithString:aRes
set jsonData to jsonString’s dataUsingEncoding:(current application’s NSUTF8StringEncoding)
set aJsonDict to current application’s NSJSONSerialization’s JSONObjectWithData:jsonData options:0 |error|:(missing value)
set aRec to aJsonDict as record
–>  {​​​​​status:0, ​​​​​message:"ok", ​​​​​results:{​​​​​​​{​​​​​​​​​perplexity:0.834903951818, ​​​​​​​​​reply:"何の事でしょう?"​​​​​​​}​​​​​}​​​}
–>  {​​​​​status:2000, ​​​​​message:"empty reply"​​​}

set curStat to status of aRec
if curStat is not equal to 0 then return false
set theAns to (aJsonDict’s valueForKeyPath:"results.reply") as list of string or string
say theAns using "Otoya" –"Kyoko" or "Otoya"

on getAPIKey()
  return "XXXXxxxXxxXXXxXXXxXxxXXxxxXxXxXX"
end getAPIKey

★Click Here to Open This Script 

Posted in Network REST API | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

Call Postmark’s spam detection API

Posted on 6月 21, 2018 by Takaaki Naganoya

PostmarkのSpamAssassin REST APIを呼び出してメールのスパム判定を行うAppleScriptです。

NSURLSessionを用いてPOST methodのREST APIを呼び出しています。

メール本文のソーステキストを渡すと、スパム度のスコアを計算して返してくれます。パラメータの「options」で「short」か「long」を指定でき、最終的な評価値のみ知りたい場合には前者を、詳細情報を知りたい場合には後者を指定することになります。

すでにMail.appにスパム判定の機能が標準搭載されているため、スパムフィルタ単体で利用する用途というのは減ってきましたが、メールの送信前にスパムフィルタに引っかからないかをチェックしておく(メールマガジン作成時など)ためには「あったほうが便利」な処理です。

本APIを利用するのに、事前のユーザー登録やAPI Keyを取得する必要はありません。このリストを実行するとそのまま結果が得られます。Mail.appのメッセージのソースを渡すのもたいして手間はかかりません。

ただし、本APIは継続して提供される保証もありませんし、トラブルが発生して動作が止まっていた場合に対処してくれたりはしません。実際の業務ほかシビアな用途で利用するのはためらわれるものがあります。

ローカルにSpamSieveをインストールしてAppleScriptで呼び出すと同様にスパム評価値を計算してくれるので、メールのSPAM判定のための用途にはこれも検討に値するでしょう。

AppleScript名:Call Postmark’s spam API
— Created 2018-06-20 by Takaaki Naganoya
— 2018 Piyomaru Software
use AppleScript version "2.5"
use scripting additions
use framework "Foundation"

property |NSURL| : a reference to current application’s |NSURL|
property NSString : a reference to current application’s NSString
property NSURLSession : a reference to current application’s NSURLSession
property NSJSONSerialization : a reference to current application’s NSJSONSerialization
property NSMutableURLRequest : a reference to current application’s NSMutableURLRequest
property NSUTF8StringEncoding : a reference to current application’s NSUTF8StringEncoding
property NSURLSessionConfiguration : a reference to current application’s NSURLSessionConfiguration

property retData : missing value
property retCode : 0
property retHeaders : 0

set aBody to "raw dump of email"

–https://spamcheck.postmarkapp.com/doc/
set aURL to "https://spamcheck.postmarkapp.com/filter"
set aRec to {email:aBody, options:"long"}

set aRESTres to callRestPOSTAPIAndParseResults(aURL, aRec, 10) of me
set aRESTcode to retCode of aRESTres
–> 200

set aRESTheader to retHeaders of aRESTres
set aRESTres to retData of aRESTres
–> {success:true, rules:{{score:"1.2", |description|:"Missing To: header"}, {score:"-0.0", |description|:"Informational: message was not relayed via SMTP"}, {score:"1.4", |description|:"Missing Date: header"}, {score:"1.8", |description|:"Missing Subject: header"}, {score:"2.3", |description|:"Message appears to have no textual parts and no Subject: text"}, {score:"0.1", |description|:"Missing Message-Id: header"}, {score:"-0.0", |description|:"Informational: message has no Received headers"}, {score:"1.0", |description|:"Missing From: header"}, {score:"0.0", |description|:"Message appears to be missing most RFC-822 headers"}}, score:"7.9", report:" …."}

on callRestPOSTAPIAndParseResults(reqURLStr as string, aRec as record, timeoutSec as integer)
  set retData to missing value
  
set retCode to 0
  
set retHeaders to {}
  
  
set aURL to |NSURL|’s URLWithString:reqURLStr
  
set aRequest to NSMutableURLRequest’s requestWithURL:aURL
  
aRequest’s setHTTPMethod:"POST"
  
aRequest’s setCachePolicy:(current application’s NSURLRequestReloadIgnoringLocalCacheData)
  
aRequest’s setHTTPShouldHandleCookies:false
  
aRequest’s setTimeoutInterval:timeoutSec
  
–aRequest’s setValue:"gzip" forHTTPHeaderField:"Content-Encoding"–Does not work with this API & Method
  
aRequest’s setValue:"application/json" forHTTPHeaderField:"Accept"
  
aRequest’s setValue:"application/json; charset=UTF-8" forHTTPHeaderField:"Content-Type"
  
  
set dataJson to current application’s NSJSONSerialization’s dataWithJSONObject:aRec options:0 |error|:(missing value)
  
aRequest’s setHTTPBody:dataJson
  
  
set aConfig to NSURLSessionConfiguration’s defaultSessionConfiguration()
  
set aSession to NSURLSession’s sessionWithConfiguration:aConfig delegate:(me) delegateQueue:(missing value)
  
set aTask to aSession’s dataTaskWithRequest:aRequest
  
  
set hitF to false
  
aTask’s resume() –Start URL Session
  
  
repeat (1000 * timeoutSec) times
    if retData is not equal to missing value then
      set hitF to true
      
exit repeat
    end if
    
delay ("0.001" as real)
  end repeat
  
  
if hitF = false then error "REST API Timeout Error"
  
  
return {retData:retData, retCode:retCode, retHeaders:retHeaders}
end callRestPOSTAPIAndParseResults

on URLSession:tmpSession dataTask:tmpTask didReceiveData:tmpData
  set aRes to tmpTask’s response()
  
set retCode to aRes’s statusCode()
  
set retHeaders to aRes’s allHeaderFields()
  
  
set resStr to NSString’s alloc()’s initWithData:tmpData encoding:(NSUTF8StringEncoding)
  
set jsonString to NSString’s stringWithString:(resStr)
  
  
set jsonData to jsonString’s dataUsingEncoding:(NSUTF8StringEncoding)
  
set aJsonDict to NSJSONSerialization’s JSONObjectWithData:jsonData options:0 |error|:(missing value)
  
  
set retData to aJsonDict as list of string or string –as anything
end URLSession:dataTask:didReceiveData:

★Click Here to Open This Script 

Posted in JSON Network Record REST API URL | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

GET method REST API v4.1

Posted on 6月 17, 2018 by Takaaki Naganoya

Web上のREST APIを、NSURLSessionを用いて呼び出すAppleScriptの改良版です。

status code、Response Header、処理結果をそれぞれ返すように改良してみました。これで、実際のプログラムに組み込むことができるようになりました。

Response Headerの各フィールドはスペースやハイフンを含んでいたりするので、CocoaのNSDictionaryからAppleScriptのrecordに変換すると値が取り出せなくなってしまいます。

そのため、NSDictionaryのまま返すようにしています。

AppleScript名:GET method REST API v4.1
— Created 2018-06-16 by Takaaki Naganoya
— 2018 Piyomaru Software
use AppleScript version "2.5"
use scripting additions
use framework "Foundation"

property |NSURL| : a reference to current application’s |NSURL|
property NSString : a reference to current application’s NSString
property NSURLSession : a reference to current application’s NSURLSession
property NSJSONSerialization : a reference to current application’s NSJSONSerialization
property NSMutableURLRequest : a reference to current application’s NSMutableURLRequest
property NSUTF8StringEncoding : a reference to current application’s NSUTF8StringEncoding
property NSURLSessionConfiguration : a reference to current application’s NSURLSessionConfiguration

property retData : missing value
property retCode : 0
property retHeaders : 0

set reqURLStr to "http://jsonplaceholder.typicode.com/posts"
set aRESTres to callRestGETAPIAndParseResults(reqURLStr, 10) of me
set aRESTcode to retCode of aRESTres
–> 200

set aRESTheader to retHeaders of aRESTres
–>  (NSDictionary) {​​​​​Content-Type:"application/json; charset=utf-8", ​​​​​Pragma:"no-cache", ​​​​​X-Powered-By:"Express", ​​​​​Set-Cookie:"__cfduid=dc7a11359ba7f9518366108f4c2e2d7fb1529215907; expires=Mon, 17-Jun-19 06:11:47 GMT; path=/; domain=.typicode.com; HttpOnly", ​​​​​Server:"cloudflare", ​​​​​Via:"1.1 vegur", ​​​​​Content-Encoding:"gzip", ​​​​​Expires:"Sun, 17 Jun 2018 15:21:12 GMT", ​​​​​CF-Cache-Status:"HIT", ​​​​​Transfer-Encoding:"Identity", ​​​​​Cache-Control:"public, max-age=14400", ​​​​​Date:"Sun, 17 Jun 2018 11:21:12 GMT", ​​​​​Access-Control-Allow-Credentials:"true", ​​​​​Connection:"keep-alive", ​​​​​CF-RAY:"42c5219eb6f2a5cc-NRT", ​​​​​Etag:"W/"6b80-Ybsq/K6GwwqrYkAsFxqDXGC7DoM"", ​​​​​Vary:"Origin, Accept-Encoding", ​​​​​X-Content-Type-Options:"nosniff"​​​}

set aRESTres to retData of aRESTres
–>
(*
{​​​​​{​​​​​​​body:"quia et suscipit
suscipit recusandae consequuntur expedita et cum
reprehenderit molestiae ut ut quas totam
nostrum rerum est autem sunt rem eveniet architecto", ​​​​​​​id:1, ​​​​​​​title:"sunt aut facere repellat provident occaecati excepturi optio reprehenderit", ​​​​​​​userId:1​​​​​},….}
*)

on callRestGETAPIAndParseResults(reqURLStr as string, timeoutSec as integer)
  set retData to missing value
  
set retCode to 0
  
set retHeaders to {}
  
  
set aURL to |NSURL|’s URLWithString:reqURLStr
  
set aRequest to NSMutableURLRequest’s requestWithURL:aURL
  
aRequest’s setHTTPMethod:"GET"
  
aRequest’s setValue:"gzip" forHTTPHeaderField:"Content-Encoding"
  
aRequest’s setValue:"application/json; charset=UTF-8" forHTTPHeaderField:"Content-Type"
  
  
set aConfig to NSURLSessionConfiguration’s defaultSessionConfiguration()
  
set aSession to NSURLSession’s sessionWithConfiguration:aConfig delegate:(me) delegateQueue:(missing value)
  
set aTask to aSession’s dataTaskWithRequest:aRequest
  
  
set hitF to false
  
aTask’s resume() –Start URL Session
  
  
repeat (1000 * timeoutSec) times
    if retData is not equal to missing value then
      set hitF to true
      
exit repeat
    end if
    
delay ("0.001" as real)
  end repeat
  
  
if hitF = false then error "REST API Timeout Error"
  
  
return {retData:retData, retCode:retCode, retHeaders:retHeaders}
end callRestGETAPIAndParseResults

on URLSession:tmpSession dataTask:tmpTask didReceiveData:tmpData
  set aRes to tmpTask’s response()
  
set retCode to aRes’s statusCode()
  
set retHeaders to aRes’s allHeaderFields()
  
  
set resStr to NSString’s alloc()’s initWithData:tmpData encoding:(NSUTF8StringEncoding)
  
set jsonString to NSString’s stringWithString:(resStr)
  
  
set jsonData to jsonString’s dataUsingEncoding:(NSUTF8StringEncoding)
  
set aJsonDict to NSJSONSerialization’s JSONObjectWithData:jsonData options:0 |error|:(missing value)
  
  
set retData to aJsonDict as list of string or string –as anything
end URLSession:dataTask:didReceiveData:

★Click Here to Open This Script 

Posted in Network REST API | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

GET method REST API v4

Posted on 6月 17, 2018 by Takaaki Naganoya

Web上のREST APIを、NSURLSessionを用いて呼び出すAppleScriptです。

各種REST APIをAppleScriptから呼び出して使うのは、もはや日常的な光景になっていますが、これまでNSURLConnectionを用いていたのが気になっていました。

現在の、Cocoa-BridgeされたAppleScriptではObjective-CのBlocks構文を用いるAPIを呼び出せないために、非同期処理ではなく同期処理を用いる必要があります。NSURLConnectionは明示的に同期処理を呼び出すことができますが、NSURLSessionのサンプルではもれなくBlocks構文が書かれていたので、使えないものかと思っていました。

ただ、それは私・長野谷の単なる思い込みであり、Xcodeでヘッダーファイルを調べてみたらBlocks構文を使わずに書けることがわかったので試してみたものです。呼び出しているのは動作確認用のREST APIで、毎回同じ値を返してきます。

まだ、status codeを受け取れていないので実際の処理に組み込むことはできませんが、きちんと動くコードが書けた意義は大きいでしょう。

AppleScript名:GET method REST API v4
— Created 2018-06-16 by Takaaki Naganoya
— 2018 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"

property |NSURL| : a reference to current application’s |NSURL|
property NSString : a reference to current application’s NSString
property NSURLSession : a reference to current application’s NSURLSession
property NSJSONSerialization : a reference to current application’s NSJSONSerialization
property NSMutableURLRequest : a reference to current application’s NSMutableURLRequest
property NSUTF8StringEncoding : a reference to current application’s NSUTF8StringEncoding
property NSURLSessionConfiguration : a reference to current application’s NSURLSessionConfiguration

property retData : missing value

set retData to missing value

set reqURLStr to "http://jsonplaceholder.typicode.com/posts"
set aRESTres to callRestGETAPIAndParseResults(reqURLStr) of me
–>  
(*
{​​​​​{​​​​​​​body:"quia et suscipit
suscipit recusandae consequuntur expedita et cum
reprehenderit molestiae ut ut quas totam
nostrum rerum est autem sunt rem eveniet architecto", ​​​​​​​id:1, ​​​​​​​title:"sunt aut facere repellat provident occaecati excepturi optio reprehenderit", ​​​​​​​userId:1​​​​​}, ​​​​​{​​​​​​​body:"est rerum tempore vitae
sequi sint nihil reprehenderit dolor beatae ea dolores neque
fugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis"}……}
*)

on callRestGETAPIAndParseResults(reqURLStr)
  set aURL to |NSURL|’s URLWithString:reqURLStr
  
set aRequest to NSMutableURLRequest’s requestWithURL:aURL
  
aRequest’s setHTTPMethod:"GET"
  
aRequest’s setValue:"gzip" forHTTPHeaderField:"Content-Encoding"
  
aRequest’s setValue:"application/json; charset=UTF-8" forHTTPHeaderField:"Content-Type"
  
  
set aConfig to NSURLSessionConfiguration’s defaultSessionConfiguration()
  
set aSession to NSURLSession’s sessionWithConfiguration:aConfig delegate:(me) delegateQueue:(missing value)
  
set aTask to aSession’s dataTaskWithRequest:aRequest
  
  
aTask’s resume() –Start URL Session
  
  
repeat 10000 times
    if retData is not equal to missing value then exit repeat
    
delay ("0.001" as real)
  end repeat
  
  
retData
end callRestGETAPIAndParseResults

on URLSession:tmpSession dataTask:tmpTask didReceiveData:tmpData
  set aStat to (tmpTask’s state()) as list of string or string
  
  
set resStr to NSString’s alloc()’s initWithData:tmpData encoding:(NSUTF8StringEncoding)
  
set jsonString to NSString’s stringWithString:(resStr)
  
  
set jsonData to jsonString’s dataUsingEncoding:(NSUTF8StringEncoding)
  
set aJsonDict to NSJSONSerialization’s JSONObjectWithData:jsonData options:0 |error|:(missing value)
  
  
set retData to aJsonDict as list of string or string
end URLSession:dataTask:didReceiveData:

★Click Here to Open This Script 

Posted in Network REST API | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

Twitterで指定アカウントのタイムラインを取得

Posted on 3月 30, 2018 by Takaaki Naganoya
AppleScript名:Twitterで指定アカウントのタイムラインを取得
— Created 2016-11-22 by Takaaki Naganoya
— 2016 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"

set myConsumerKey to "xXXXXXXXxxXXxXxxxXXxXxXXX"
set myConsumerSecret to "xxxxXXXxXxXXXxXXXxxxXXXXXxxXxxXXXxXXXxxXXxxxXXxxXx"

–認証を行って認証済みのBarer Tokenを取得する
set authedToken to getAuthedTokenFromTwitter(myConsumerKey, myConsumerSecret) of me
if authedToken = missing value then return

–実際のAPI呼び出し
set reqURLStr to "https://api.twitter.com/1.1/statuses/user_timeline.json" –URLの前後に空白などが入らないように!!
set bRec to {|count|:"10", screen_name:"realDonaldTrump"}
set bURL to retURLwithParams(reqURLStr, bRec) of me
set aRes to callRestGETAPIAWithAuth(bURL, authedToken) of me

set aRESCode to responseCode of aRes –Response Code
if aRESCode is not equal to 200 then return false
set aRESHeader to responseHeader of aRes –Response Header

set aRESTres to (json of aRes) as list of string or string
–set timeLine to (aRESTres’s valueForKeyPath:"text") as list
–>  {​​​​​"Many people would like to see @Nigel_Farage represent Great Britain as their Ambassador to the United States. He would do a great job!", ​​​​​"Prior to the election it was well known that I have interests in properties all over the world.Only the crooked media makes this a big deal!", ​​​​​".@transition2017 update and policy plans for the first 100 days. https://t.co/HTgPXfPWeJ", ​​​​​"I have always had a good relationship with Chuck Schumer. He is far smarter than Harry R and has the ability to get things done. Good news!", ​​​​​"General James \"Mad Dog\" Mattis, who is being considered for Secretary of Defense, was very impressive yesterday. A true General’s General!", ​​​​​"I watched parts of @nbcsnl Saturday Night Live last night. It is a totally one-sided, biased show – nothing funny at all. Equal time for us?", ​​​​​"Numerous patriots will be coming to Bedminster today as I continue to fill out the various positions necessary to MAKE AMERICA GREAT AGAIN!", ​​​​​"The cast and producers of Hamilton, which I hear is highly overrated, should immediately apologize to Mike Pence for their terrible behavior", ​​​​​"The Theater must always be a safe and special place.The cast of Hamilton was very rude last night to a very good man, Mike Pence. Apologize!", ​​​​​"Our wonderful future V.P. Mike Pence was harassed last night at the theater by the cast of Hamilton, cameras blazing.This should not happen!"​​​}

–Authenticate APIを呼び出して認証を行う
on getAuthedTokenFromTwitter(aConsumerKey, aConsumerSecret)
  set aURL to "https://api.twitter.com/oauth2/token"
  
set barerToken to aConsumerKey & ":" & aConsumerSecret
  
set aStr to current application’s NSString’s stringWithString:barerToken
  
set aData to aStr’s dataUsingEncoding:(current application’s NSUTF8StringEncoding)
  
set bStr to (aData’s base64EncodedStringWithOptions:0) as string
  
set bStr to current application’s NSString’s stringWithString:("Basic " & bStr)
  
set aRec to {grant_type:"client_credentials"}
  
set a2URL to retURLwithParams(aURL, aRec) of me
  
  
set a2Res to callRestPOSTAPIWithAuth(a2URL, bStr) of me
  
if (responseCode of a2Res) is not equal to 200 then return
  
set aJSON to (json of a2Res)
  
set authedToken to "Bearer " & (aJSON’s valueForKey:"access_token")
  
return authedToken
end getAuthedTokenFromTwitter

on retURLwithParams(aBaseURL, aRec)
  set aDic to current application’s NSMutableDictionary’s dictionaryWithDictionary:aRec
  
  
set aKeyList to (aDic’s allKeys()) as list
  
set aValList to (aDic’s allValues()) as list
  
set aLen to length of aKeyList
  
  
set qList to {}
  
repeat with i from 1 to aLen
    set aName to contents of item i of aKeyList
    
set aVal to contents of item i of aValList
    
set the end of qList to (current application’s NSURLQueryItem’s queryItemWithName:aName value:aVal)
  end repeat
  
  
set aComp to current application’s NSURLComponents’s alloc()’s initWithString:aBaseURL
  
aComp’s setQueryItems:qList
  
set aURL to (aComp’s |URL|()’s absoluteString()) –as text
  
  
return aURL
end retURLwithParams

–POST methodのREST APIを呼ぶ(認証つき)
on callRestPOSTAPIWithAuth(aURL, anAPIkey)
  set aRequest to current application’s NSMutableURLRequest’s requestWithURL:(current application’s |NSURL|’s URLWithString:aURL)
  
aRequest’s setHTTPMethod:"POST"
  
aRequest’s setCachePolicy:(current application’s NSURLRequestReloadIgnoringLocalCacheData)
  
aRequest’s setHTTPShouldHandleCookies:false
  
aRequest’s setTimeoutInterval:60
  
if anAPIkey is not equal to "" then
    aRequest’s setValue:anAPIkey forHTTPHeaderField:"Authorization"
  end if
  
aRequest’s setValue:"gzip" forHTTPHeaderField:"Accept-Encoding"
  
aRequest’s setValue:"application/x-www-form-urlencoded;charset=UTF-8" forHTTPHeaderField:"Accept"
  
  
–CALL REST API
  
set aRes to current application’s NSURLConnection’s sendSynchronousRequest:aRequest returningResponse:(reference) |error|:(missing value)
  
  
–Parse Results
  
set resList to aRes as list
  
  
set bRes to contents of (first item of resList)
  
set resStr to current application’s NSString’s alloc()’s initWithData:bRes encoding:(current application’s NSUTF8StringEncoding)
  
  
set jsonString to current application’s NSString’s stringWithString:resStr
  
set jsonData to jsonString’s dataUsingEncoding:(current application’s NSUTF8StringEncoding)
  
set aJsonDict to current application’s NSJSONSerialization’s JSONObjectWithData:jsonData options:0 |error|:(missing value)
  
  
–Get Response Code & Header
  
set dRes to contents of second item of resList
  
if dRes is not equal to missing value then
    set resCode to (dRes’s statusCode()) as number
    
set resHeaders to (dRes’s allHeaderFields()) as record
  else
    set resCode to 0
    
set resHeaders to {}
  end if
  
  
return {json:aJsonDict, responseCode:resCode, responseHeader:resHeaders}
end callRestPOSTAPIWithAuth

–GET methodのREST APIを呼ぶ(認証つき)
on callRestGETAPIAWithAuth(aURL, anAPIkey)
  set aRequest to current application’s NSMutableURLRequest’s requestWithURL:(current application’s |NSURL|’s URLWithString:aURL)
  
  
aRequest’s setHTTPMethod:"GET"
  
aRequest’s setCachePolicy:(current application’s NSURLRequestReloadIgnoringLocalCacheData)
  
aRequest’s setHTTPShouldHandleCookies:false
  
aRequest’s setTimeoutInterval:60
  
if anAPIkey is not equal to "" then
    aRequest’s setValue:anAPIkey forHTTPHeaderField:"Authorization"
  end if
  
aRequest’s setValue:"gzip" forHTTPHeaderField:"Accept-Encoding"
  
aRequest’s setValue:"application/x-www-form-urlencoded;charset=UTF-8" forHTTPHeaderField:"Accept"
  
  
set aRes to current application’s NSURLConnection’s sendSynchronousRequest:aRequest returningResponse:(reference) |error|:(missing value)
  
set resList to aRes as list
  
  
set bRes to contents of (first item of resList)
  
set resStr to current application’s NSString’s alloc()’s initWithData:bRes encoding:(current application’s NSUTF8StringEncoding)
  
  
set jsonString to current application’s NSString’s stringWithString:resStr
  
set jsonData to jsonString’s dataUsingEncoding:(current application’s NSUTF8StringEncoding)
  
set aJsonDict to current application’s NSJSONSerialization’s JSONObjectWithData:jsonData options:0 |error|:(missing value)
  
  
–Get Response Code & Header
  
set dRes to contents of second item of resList
  
if dRes is not equal to missing value then
    set resCode to (dRes’s statusCode()) as number
    
set resHeaders to (dRes’s allHeaderFields()) as record
  else
    set resCode to 0
    
set resHeaders to {}
  end if
  
  
return {json:aJsonDict, responseCode:resCode, responseHeader:resHeaders}
  
end callRestGETAPIAWithAuth

★Click Here to Open This Script 

Posted in Network REST API | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

Twitterでフォロワーリストの情報を取得する

Posted on 3月 30, 2018 by Takaaki Naganoya
AppleScript名:Twitterでフォロワーリストの情報を取得する
— Created 2016-11-22 by Takaaki Naganoya
— 2016 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"

set myConsumerKey to "xXXXXXXXxxXXxXxxxXXxXxXXX"
set myConsumerSecret to "xxxxXXXxXxXXXxXXXxxxXXXXXxxXxxXXXxXXXxxXXxxxXXxxXx"

–認証を行って認証済みのBarer Tokenを取得する
set authedToken to getAuthedTokenFromTwitter(myConsumerKey, myConsumerSecret) of me
if authedToken = missing value then return

set nextCursor to "0"
set allFolList to current application’s NSMutableArray’s new()

–実際のAPI呼び出し
set reqURLStr to "https://api.twitter.com/1.1/followers/list.json"

repeat 100 times
  if nextCursor = "0" then
    set bRec to {|count|:"200", screen_name:"Piyomaru"}
  else
    set bRec to {|count|:"200", cursor:nextCursor, screen_name:"Piyomaru"}
  end if
  
  
set bURL to retURLwithParams(reqURLStr, bRec) of me
  
set aRes to callRestGETAPIAWithAuth(bURL, authedToken) of me
  
  
set aRESCode to responseCode of aRes –Response Code
  
if aRESCode is not equal to 200 then return false
  
set aRESHeader to responseHeader of aRes –Response Header
  
  
set aRESTres to (json of aRes)
  
set followerList to (aRESTres’s valueForKeyPath:"users") as list
  
allFolList’s addObjectsFromArray:followerList
  
set nextCursor to aRESTres’s valueForKeyPath:"next_cursor_str"
  
  
if (nextCursor as string) = "0" then exit repeat
end repeat

return allFolList

–Authenticate APIを呼び出して認証を行う
on getAuthedTokenFromTwitter(aConsumerKey, aConsumerSecret)
  set aURL to "https://api.twitter.com/oauth2/token"
  
set barerToken to aConsumerKey & ":" & aConsumerSecret
  
set aStr to current application’s NSString’s stringWithString:barerToken
  
set aData to aStr’s dataUsingEncoding:(current application’s NSUTF8StringEncoding)
  
set bStr to (aData’s base64EncodedStringWithOptions:0) as string
  
set bStr to current application’s NSString’s stringWithString:("Basic " & bStr)
  
set aRec to {grant_type:"client_credentials"}
  
set a2URL to retURLwithParams(aURL, aRec) of me
  
  
set a2Res to callRestPOSTAPIWithAuth(a2URL, bStr) of me
  
if (responseCode of a2Res) is not equal to 200 then return
  
set aJSON to (json of a2Res)
  
set authedToken to "Bearer " & (aJSON’s valueForKey:"access_token")
  
return authedToken
end getAuthedTokenFromTwitter

on retURLwithParams(aBaseURL, aRec)
  set aDic to current application’s NSMutableDictionary’s dictionaryWithDictionary:aRec
  
  
set aKeyList to (aDic’s allKeys()) as list
  
set aValList to (aDic’s allValues()) as list
  
set aLen to length of aKeyList
  
  
set qList to {}
  
repeat with i from 1 to aLen
    set aName to contents of item i of aKeyList
    
set aVal to contents of item i of aValList
    
set the end of qList to (current application’s NSURLQueryItem’s queryItemWithName:aName value:aVal)
  end repeat
  
  
set aComp to current application’s NSURLComponents’s alloc()’s initWithString:aBaseURL
  
aComp’s setQueryItems:qList
  
set aURL to (aComp’s |URL|()’s absoluteString()) –as text
  
  
return aURL
end retURLwithParams

–POST methodのREST APIを呼ぶ(認証つき)
on callRestPOSTAPIWithAuth(aURL, anAPIkey)
  set aRequest to current application’s NSMutableURLRequest’s requestWithURL:(current application’s |NSURL|’s URLWithString:aURL)
  
aRequest’s setHTTPMethod:"POST"
  
aRequest’s setCachePolicy:(current application’s NSURLRequestReloadIgnoringLocalCacheData)
  
aRequest’s setHTTPShouldHandleCookies:false
  
aRequest’s setTimeoutInterval:60
  
if anAPIkey is not equal to "" then
    aRequest’s setValue:anAPIkey forHTTPHeaderField:"Authorization"
  end if
  
aRequest’s setValue:"gzip" forHTTPHeaderField:"Accept-Encoding"
  
aRequest’s setValue:"application/x-www-form-urlencoded;charset=UTF-8" forHTTPHeaderField:"Accept"
  
  
–CALL REST API
  
set aRes to current application’s NSURLConnection’s sendSynchronousRequest:aRequest returningResponse:(reference) |error|:(missing value)
  
  
–Parse Results
  
set resList to aRes as list
  
  
set bRes to contents of (first item of resList)
  
set resStr to current application’s NSString’s alloc()’s initWithData:bRes encoding:(current application’s NSUTF8StringEncoding)
  
  
set jsonString to current application’s NSString’s stringWithString:resStr
  
set jsonData to jsonString’s dataUsingEncoding:(current application’s NSUTF8StringEncoding)
  
set aJsonDict to current application’s NSJSONSerialization’s JSONObjectWithData:jsonData options:0 |error|:(missing value)
  
  
–Get Response Code & Header
  
set dRes to contents of second item of resList
  
if dRes is not equal to missing value then
    set resCode to (dRes’s statusCode()) as number
    
set resHeaders to (dRes’s allHeaderFields()) as record
  else
    set resCode to 0
    
set resHeaders to {}
  end if
  
  
return {json:aJsonDict, responseCode:resCode, responseHeader:resHeaders}
end callRestPOSTAPIWithAuth

–GET methodのREST APIを呼ぶ(認証つき)
on callRestGETAPIAWithAuth(aURL, anAPIkey)
  set aRequest to current application’s NSMutableURLRequest’s requestWithURL:(current application’s |NSURL|’s URLWithString:aURL)
  
  
aRequest’s setHTTPMethod:"GET"
  
aRequest’s setCachePolicy:(current application’s NSURLRequestReloadIgnoringLocalCacheData)
  
aRequest’s setHTTPShouldHandleCookies:false
  
aRequest’s setTimeoutInterval:60
  
if anAPIkey is not equal to "" then
    aRequest’s setValue:anAPIkey forHTTPHeaderField:"Authorization"
  end if
  
aRequest’s setValue:"gzip" forHTTPHeaderField:"Accept-Encoding"
  
aRequest’s setValue:"application/x-www-form-urlencoded;charset=UTF-8" forHTTPHeaderField:"Accept"
  
  
set aRes to current application’s NSURLConnection’s sendSynchronousRequest:aRequest returningResponse:(reference) |error|:(missing value)
  
set resList to aRes as list
  
  
set bRes to contents of (first item of resList)
  
set resStr to current application’s NSString’s alloc()’s initWithData:bRes encoding:(current application’s NSUTF8StringEncoding)
  
  
set jsonString to current application’s NSString’s stringWithString:resStr
  
set jsonData to jsonString’s dataUsingEncoding:(current application’s NSUTF8StringEncoding)
  
set aJsonDict to current application’s NSJSONSerialization’s JSONObjectWithData:jsonData options:0 |error|:(missing value)
  
  
–Get Response Code & Header
  
set dRes to contents of second item of resList
  
if dRes is not equal to missing value then
    set resCode to (dRes’s statusCode()) as number
    
set resHeaders to (dRes’s allHeaderFields()) as record
  else
    set resCode to 0
    
set resHeaders to {}
  end if
  
  
return {json:aJsonDict, responseCode:resCode, responseHeader:resHeaders}
  
end callRestGETAPIAWithAuth

★Click Here to Open This Script 

Posted in Network REST API | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

Twitterでフォロワーリストの情報を取得して作成日とscreen_nameを抽出して最終Tweet日を取得

Posted on 3月 30, 2018 by Takaaki Naganoya
AppleScript名:Twitterでフォロワーリストの情報を取得して作成日とscreen_nameを抽出して最終Tweet日を取得
— Created 2016-11-22 by Takaaki Naganoya
— 2016 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"

set myConsumerKey to "xXXXXXXXxxXXxXxxxXXxXxXXX"
set myConsumerSecret to "xxxxXXXxXxXXXxXXXxxxXXXXXxxXxxXXXxXXXxxXXxxxXXxxXx"

–認証を行って認証済みのBarer Tokenを取得する
set authedToken to getAuthedTokenFromTwitter(myConsumerKey, myConsumerSecret) of me
if authedToken = missing value then return

set nextCursor to "0"
set allFolList to current application’s NSMutableArray’s new()

–実際のAPI呼び出し
set reqURLStr to "https://api.twitter.com/1.1/followers/list.json"

repeat 100 times
  if nextCursor = "0" then
    set bRec to {|count|:"200", screen_name:"Piyomaru"}
  else
    set bRec to {|count|:"200", cursor:nextCursor, screen_name:"Piyomaru"}
  end if
  
  
set bURL to retURLwithParams(reqURLStr, bRec) of me
  
set aRes to callRestGETAPIAWithAuth(bURL, authedToken) of me
  
  
set aRESCode to responseCode of aRes –Response Code
  
if aRESCode is not equal to 200 then return false
  
set aRESHeader to responseHeader of aRes –Response Header
  
  
set aRESTres to (json of aRes)
  
set followerList to (aRESTres’s valueForKeyPath:"users") as list
  
allFolList’s addObjectsFromArray:followerList
  
set nextCursor to aRESTres’s valueForKeyPath:"next_cursor_str"
  
  
if (nextCursor as string) = "0" then exit repeat
end repeat

–return allFolList
set creList to (allFolList’s valueForKeyPath:"created_at") as list of string or string
set idList to (allFolList’s valueForKeyPath:"id_str") as list of string or string
set scNameList to (allFolList’s valueForKeyPath:"screen_name") as list of string or string

–Authenticate APIを呼び出して認証を行う
on getAuthedTokenFromTwitter(aConsumerKey, aConsumerSecret)
  set aURL to "https://api.twitter.com/oauth2/token"
  
set barerToken to aConsumerKey & ":" & aConsumerSecret
  
set aStr to current application’s NSString’s stringWithString:barerToken
  
set aData to aStr’s dataUsingEncoding:(current application’s NSUTF8StringEncoding)
  
set bStr to (aData’s base64EncodedStringWithOptions:0) as string
  
set bStr to current application’s NSString’s stringWithString:("Basic " & bStr)
  
set aRec to {grant_type:"client_credentials"}
  
set a2URL to retURLwithParams(aURL, aRec) of me
  
  
set a2Res to callRestPOSTAPIWithAuth(a2URL, bStr) of me
  
if (responseCode of a2Res) is not equal to 200 then return
  
set aJSON to (json of a2Res)
  
set authedToken to "Bearer " & (aJSON’s valueForKey:"access_token")
  
return authedToken
end getAuthedTokenFromTwitter

on retURLwithParams(aBaseURL, aRec)
  set aDic to current application’s NSMutableDictionary’s dictionaryWithDictionary:aRec
  
  
set aKeyList to (aDic’s allKeys()) as list
  
set aValList to (aDic’s allValues()) as list
  
set aLen to length of aKeyList
  
  
set qList to {}
  
repeat with i from 1 to aLen
    set aName to contents of item i of aKeyList
    
set aVal to contents of item i of aValList
    
set the end of qList to (current application’s NSURLQueryItem’s queryItemWithName:aName value:aVal)
  end repeat
  
  
set aComp to current application’s NSURLComponents’s alloc()’s initWithString:aBaseURL
  
aComp’s setQueryItems:qList
  
set aURL to (aComp’s |URL|()’s absoluteString()) –as text
  
  
return aURL
end retURLwithParams

–POST methodのREST APIを呼ぶ(認証つき)
on callRestPOSTAPIWithAuth(aURL, anAPIkey)
  set aRequest to current application’s NSMutableURLRequest’s requestWithURL:(current application’s |NSURL|’s URLWithString:aURL)
  
aRequest’s setHTTPMethod:"POST"
  
aRequest’s setCachePolicy:(current application’s NSURLRequestReloadIgnoringLocalCacheData)
  
aRequest’s setHTTPShouldHandleCookies:false
  
aRequest’s setTimeoutInterval:60
  
if anAPIkey is not equal to "" then
    aRequest’s setValue:anAPIkey forHTTPHeaderField:"Authorization"
  end if
  
aRequest’s setValue:"gzip" forHTTPHeaderField:"Accept-Encoding"
  
aRequest’s setValue:"application/x-www-form-urlencoded;charset=UTF-8" forHTTPHeaderField:"Accept"
  
  
–CALL REST API
  
set aRes to current application’s NSURLConnection’s sendSynchronousRequest:aRequest returningResponse:(reference) |error|:(missing value)
  
  
–Parse Results
  
set resList to aRes as list
  
  
set bRes to contents of (first item of resList)
  
set resStr to current application’s NSString’s alloc()’s initWithData:bRes encoding:(current application’s NSUTF8StringEncoding)
  
  
set jsonString to current application’s NSString’s stringWithString:resStr
  
set jsonData to jsonString’s dataUsingEncoding:(current application’s NSUTF8StringEncoding)
  
set aJsonDict to current application’s NSJSONSerialization’s JSONObjectWithData:jsonData options:0 |error|:(missing value)
  
  
–Get Response Code & Header
  
set dRes to contents of second item of resList
  
if dRes is not equal to missing value then
    set resCode to (dRes’s statusCode()) as number
    
set resHeaders to (dRes’s allHeaderFields()) as record
  else
    set resCode to 0
    
set resHeaders to {}
  end if
  
  
return {json:aJsonDict, responseCode:resCode, responseHeader:resHeaders}
end callRestPOSTAPIWithAuth

–GET methodのREST APIを呼ぶ(認証つき)
on callRestGETAPIAWithAuth(aURL, anAPIkey)
  set aRequest to current application’s NSMutableURLRequest’s requestWithURL:(current application’s |NSURL|’s URLWithString:aURL)
  
  
aRequest’s setHTTPMethod:"GET"
  
aRequest’s setCachePolicy:(current application’s NSURLRequestReloadIgnoringLocalCacheData)
  
aRequest’s setHTTPShouldHandleCookies:false
  
aRequest’s setTimeoutInterval:60
  
if anAPIkey is not equal to "" then
    aRequest’s setValue:anAPIkey forHTTPHeaderField:"Authorization"
  end if
  
aRequest’s setValue:"gzip" forHTTPHeaderField:"Accept-Encoding"
  
aRequest’s setValue:"application/x-www-form-urlencoded;charset=UTF-8" forHTTPHeaderField:"Accept"
  
  
set aRes to current application’s NSURLConnection’s sendSynchronousRequest:aRequest returningResponse:(reference) |error|:(missing value)
  
set resList to aRes as list
  
  
set bRes to contents of (first item of resList)
  
set resStr to current application’s NSString’s alloc()’s initWithData:bRes encoding:(current application’s NSUTF8StringEncoding)
  
  
set jsonString to current application’s NSString’s stringWithString:resStr
  
set jsonData to jsonString’s dataUsingEncoding:(current application’s NSUTF8StringEncoding)
  
set aJsonDict to current application’s NSJSONSerialization’s JSONObjectWithData:jsonData options:0 |error|:(missing value)
  
  
–Get Response Code & Header
  
set dRes to contents of second item of resList
  
if dRes is not equal to missing value then
    set resCode to (dRes’s statusCode()) as number
    
set resHeaders to (dRes’s allHeaderFields()) as record
  else
    set resCode to 0
    
set resHeaders to {}
  end if
  
  
return {json:aJsonDict, responseCode:resCode, responseHeader:resHeaders}
  
end callRestGETAPIAWithAuth

★Click Here to Open This Script 

Posted in Network REST API | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

Twitterでフォロワーリストの情報を取得して作成日とscreen_nameを抽出

Posted on 3月 30, 2018 by Takaaki Naganoya
AppleScript名:Twitterでフォロワーリストの情報を取得して作成日とscreen_nameを抽出
— Created 2016-11-22 by Takaaki Naganoya
— 2016 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"

set myConsumerKey to "xXXXXXXXxxXXxXxxxXXxXxXXX"
set myConsumerSecret to "xxxxXXXxXxXXXxXXXxxxXXXXXxxXxxXXXxXXXxxXXxxxXXxxXx"

–認証を行って認証済みのBarer Tokenを取得する
set authedToken to getAuthedTokenFromTwitter(myConsumerKey, myConsumerSecret) of me
if authedToken = missing value then return

set nextCursor to "0"
set allFolList to current application’s NSMutableArray’s new()

–実際のAPI呼び出し
set reqURLStr to "https://api.twitter.com/1.1/followers/list.json"

repeat 100 times
  if nextCursor = "0" then
    set bRec to {|count|:"200", screen_name:"Piyomaru"}
  else
    set bRec to {|count|:"200", cursor:nextCursor, screen_name:"Piyomaru"}
  end if
  
  
set bURL to retURLwithParams(reqURLStr, bRec) of me
  
set aRes to callRestGETAPIAWithAuth(bURL, authedToken) of me
  
  
set aRESCode to responseCode of aRes –Response Code
  
if aRESCode is not equal to 200 then return false
  
set aRESHeader to responseHeader of aRes –Response Header
  
  
set aRESTres to (json of aRes)
  
set followerList to (aRESTres’s valueForKeyPath:"users") as list
  
allFolList’s addObjectsFromArray:followerList
  
set nextCursor to aRESTres’s valueForKeyPath:"next_cursor_str"
  
  
if (nextCursor as string) = "0" then exit repeat
end repeat

–return allFolList
set creList to (allFolList’s valueForKeyPath:"created_at") as list of string or string
set idList to (allFolList’s valueForKeyPath:"id_str") as list of string or string
set scNameList to (allFolList’s valueForKeyPath:"screen_name") as list of string or string

–Authenticate APIを呼び出して認証を行う
on getAuthedTokenFromTwitter(aConsumerKey, aConsumerSecret)
  set aURL to "https://api.twitter.com/oauth2/token"
  
set barerToken to aConsumerKey & ":" & aConsumerSecret
  
set aStr to current application’s NSString’s stringWithString:barerToken
  
set aData to aStr’s dataUsingEncoding:(current application’s NSUTF8StringEncoding)
  
set bStr to (aData’s base64EncodedStringWithOptions:0) as string
  
set bStr to current application’s NSString’s stringWithString:("Basic " & bStr)
  
set aRec to {grant_type:"client_credentials"}
  
set a2URL to retURLwithParams(aURL, aRec) of me
  
  
set a2Res to callRestPOSTAPIWithAuth(a2URL, bStr) of me
  
if (responseCode of a2Res) is not equal to 200 then return
  
set aJSON to (json of a2Res)
  
set authedToken to "Bearer " & (aJSON’s valueForKey:"access_token")
  
return authedToken
end getAuthedTokenFromTwitter

on retURLwithParams(aBaseURL, aRec)
  set aDic to current application’s NSMutableDictionary’s dictionaryWithDictionary:aRec
  
  
set aKeyList to (aDic’s allKeys()) as list
  
set aValList to (aDic’s allValues()) as list
  
set aLen to length of aKeyList
  
  
set qList to {}
  
repeat with i from 1 to aLen
    set aName to contents of item i of aKeyList
    
set aVal to contents of item i of aValList
    
set the end of qList to (current application’s NSURLQueryItem’s queryItemWithName:aName value:aVal)
  end repeat
  
  
set aComp to current application’s NSURLComponents’s alloc()’s initWithString:aBaseURL
  
aComp’s setQueryItems:qList
  
set aURL to (aComp’s |URL|()’s absoluteString()) –as text
  
  
return aURL
end retURLwithParams

–POST methodのREST APIを呼ぶ(認証つき)
on callRestPOSTAPIWithAuth(aURL, anAPIkey)
  set aRequest to current application’s NSMutableURLRequest’s requestWithURL:(current application’s |NSURL|’s URLWithString:aURL)
  
aRequest’s setHTTPMethod:"POST"
  
aRequest’s setCachePolicy:(current application’s NSURLRequestReloadIgnoringLocalCacheData)
  
aRequest’s setHTTPShouldHandleCookies:false
  
aRequest’s setTimeoutInterval:60
  
if anAPIkey is not equal to "" then
    aRequest’s setValue:anAPIkey forHTTPHeaderField:"Authorization"
  end if
  
aRequest’s setValue:"gzip" forHTTPHeaderField:"Accept-Encoding"
  
aRequest’s setValue:"application/x-www-form-urlencoded;charset=UTF-8" forHTTPHeaderField:"Accept"
  
  
–CALL REST API
  
set aRes to current application’s NSURLConnection’s sendSynchronousRequest:aRequest returningResponse:(reference) |error|:(missing value)
  
  
–Parse Results
  
set resList to aRes as list
  
  
set bRes to contents of (first item of resList)
  
set resStr to current application’s NSString’s alloc()’s initWithData:bRes encoding:(current application’s NSUTF8StringEncoding)
  
  
set jsonString to current application’s NSString’s stringWithString:resStr
  
set jsonData to jsonString’s dataUsingEncoding:(current application’s NSUTF8StringEncoding)
  
set aJsonDict to current application’s NSJSONSerialization’s JSONObjectWithData:jsonData options:0 |error|:(missing value)
  
  
–Get Response Code & Header
  
set dRes to contents of second item of resList
  
if dRes is not equal to missing value then
    set resCode to (dRes’s statusCode()) as number
    
set resHeaders to (dRes’s allHeaderFields()) as record
  else
    set resCode to 0
    
set resHeaders to {}
  end if
  
  
return {json:aJsonDict, responseCode:resCode, responseHeader:resHeaders}
end callRestPOSTAPIWithAuth

–GET methodのREST APIを呼ぶ(認証つき)
on callRestGETAPIAWithAuth(aURL, anAPIkey)
  set aRequest to current application’s NSMutableURLRequest’s requestWithURL:(current application’s |NSURL|’s URLWithString:aURL)
  
  
aRequest’s setHTTPMethod:"GET"
  
aRequest’s setCachePolicy:(current application’s NSURLRequestReloadIgnoringLocalCacheData)
  
aRequest’s setHTTPShouldHandleCookies:false
  
aRequest’s setTimeoutInterval:60
  
if anAPIkey is not equal to "" then
    aRequest’s setValue:anAPIkey forHTTPHeaderField:"Authorization"
  end if
  
aRequest’s setValue:"gzip" forHTTPHeaderField:"Accept-Encoding"
  
aRequest’s setValue:"application/x-www-form-urlencoded;charset=UTF-8" forHTTPHeaderField:"Accept"
  
  
set aRes to current application’s NSURLConnection’s sendSynchronousRequest:aRequest returningResponse:(reference) |error|:(missing value)
  
set resList to aRes as list
  
  
set bRes to contents of (first item of resList)
  
set resStr to current application’s NSString’s alloc()’s initWithData:bRes encoding:(current application’s NSUTF8StringEncoding)
  
  
set jsonString to current application’s NSString’s stringWithString:resStr
  
set jsonData to jsonString’s dataUsingEncoding:(current application’s NSUTF8StringEncoding)
  
set aJsonDict to current application’s NSJSONSerialization’s JSONObjectWithData:jsonData options:0 |error|:(missing value)
  
  
–Get Response Code & Header
  
set dRes to contents of second item of resList
  
if dRes is not equal to missing value then
    set resCode to (dRes’s statusCode()) as number
    
set resHeaders to (dRes’s allHeaderFields()) as record
  else
    set resCode to 0
    
set resHeaders to {}
  end if
  
  
return {json:aJsonDict, responseCode:resCode, responseHeader:resHeaders}
  
end callRestGETAPIAWithAuth

★Click Here to Open This Script 

Posted in Network REST API | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

Microsoft Azure Computer Vision API Version 1.0で画像認識(analyze) v2

Posted on 3月 27, 2018 by Takaaki Naganoya

Microsoft AzureのComputer Vision API Version 1.0(analyze)を呼び出して、画像認識するAppleScriptです。

Microsoft Azureで無料アカウントを取得して「Computer Vision API」を使用する設定にするとAPI Keyが開示されるので、Keyを本Script末尾のハンドラにコピー&ペーストで記入してください。

再掲載時に動作確認してみたら、REST APIのEndpointのURLがMicrosoft Projext OxfordからMicrosoft Azureのものに変更になっていたので、書き換えました。そのぐらいです。

あいかわらず、惚れ惚れするぐらい見事に画像認識してくれて驚かされます。これでWebサイトがわかりやすかったら最高なのに、、、、(ーー;; 

ちなみに、水着の女性の認識率がぶっちぎりで高く、その一方で子供の認識率が低いという趣味に走りまくった特徴があります。学習モデルの偏りがすごくて好感が持てます。顔認識、人物認識はWASP向けに最適化されていて、黄色人種などの有色人種の認識でえっらく苦労していますね。コンピュータには影の部分なので黒いのか、それとも髪が黒くてその部分が黒いのかはわかりません。とくに、われわれ「平たい顔」族の顔認識と、肌が黒い方々の顔認識が大変なようです。物量で乗り切るか、写真撮影の方法に一手間加えるしかありません。


–> {{metadata:{width:450, |format|:”Png”, height:600}, categories:{{|name|:”drink_”, score:0.6875}}, |description|:{tags:{“bottle”, “table”, “indoor”, “wine”, “sitting”, “food”, “glass”, “cup”, “beer”, “top”, “banana”, “wooden”, “computer”, “sandwich”, “counter”, “phone”, “desk”, “refrigerator”, “laying”, “pizza”, “kitchen”, “plate”, “white”}, captions:{{|text|:”a bottle of wine and a glass of beer on a table”, confidence:0.669977619305}}}, requestId:”fa209b50-f693-428b-9502-bb04ae18a612″}}


–> {{metadata:{width:450, |format|:”Png”, height:338}, categories:{{|name|:”others_”, score:0.00390625}, {|name|:”people_”, score:0.40625}}, |description|:{tags:{“cake”, “table”, “indoor”, “thing”, “birthday”, “object”, “food”, “sitting”, “lit”, “chocolate”, “plate”, “decorated”, “top”, “woman”, “covered”, “bowl”, “man”, “holding”, “people”, “standing”}, captions:{{|text|:”a person sitting at a table with a birthday cake with lit candles”, confidence:0.767489416177}}}, requestId:”f8a27ffe-7a0c-44ef-b4d3-403b539f7202″}}


–> {{metadata:{width:450, |format|:”Png”, height:338}, categories:{{|name|:”outdoor_”, score:0.0078125, detail:{landmarks:{}}}, {|name|:”outdoor_waterside”, score:0.2890625, detail:{landmarks:{}}}}, |description|:{tags:{“outdoor”, “sunset”, “building”, “plane”, “airplane”, “runway”, “sitting”, “large”, “track”, “front”, “sun”, “orange”, “cloudy”, “top”, “road”, “train”, “light”, “standing”, “city”, “riding”, “jet”, “red”, “bridge”, “tower”, “man”, “water”, “flying”, “white”, “night”, “parked”, “tarmac”, “blue”, “traffic”, “air”}, captions:{{|text|:”a sunset over a city”, confidence:0.920834312504}}}, requestId:”dce04975-c95a-4d70-9f9d-661ffda12de8″}}


–> {{metadata:{width:450, |format|:”Png”, height:338}, categories:{{|name|:”animal_horse”, score:0.984375}}, |description|:{tags:{“grass”, “outdoor”, “animal”, “bird”, “standing”, “field”, “water”, “white”, “walking”, “small”, “food”, “brown”, “sitting”, “large”, “green”, “grassy”, “parrot”, “river”}, captions:{{|text|:”a bird that is standing in the grass”, confidence:0.958508972922}}}, requestId:”4372eca0-ce0a-484a-ada9-4c49e5490f00″}}


–> {{metadata:{width:450, |format|:”Png”, height:338}, categories:{{|name|:”abstract_net”, score:0.18359375}, {|name|:”abstract_texture”, score:0.53515625}, {|name|:”others_”, score:0.00390625}}, |description|:{tags:{“animal”, “outdoor”, “shellfish”, “snail”, “food”, “bird”, “piece”, “sitting”, “street”, “laying”, “top”, “beach”, “fruit”, “standing”, “slug”, “plate”, “board”, “white”}, captions:{{|text|:”a snail on the ground”, confidence:0.889422773135}}}, requestId:”7edb1788-2887-45d9-bb48-68f78f72ee2c”}}


–> {{metadata:{width:450, |format|:”Png”, height:338}, categories:{{|name|:”dark_fireworks”, score:0.99609375}}, |description|:{tags:{“object”, “fireworks”}, captions:{{|text|:”fireworks in the sky”, confidence:0.542768984765}}}, requestId:”0a2d5b92-27ff-4ac4-a431-14ca2f0454c3″}}


–> {{metadata:{width:1280, |format|:”Jpeg”, height:960}, categories:{{|name|:”others_”, score:0.00390625}, {|name|:”outdoor_”, score:0.01171875, detail:{landmarks:{}}}}, |description|:{tags:{“outdoor”, “person”, “toy”, “thing”, “man”, “white”, “grass”, “standing”, “people”, “field”, “riding”, “jumping”, “doing”, “air”, “holding”, “group”, “trick”, “board”, “statue”, “dog”, “player”, “ramp”}, captions:{{|text|:”a statue of a man”, confidence:0.666301928732}}}, requestId:”45a3a778-c4d5-4b9e-9a0f-480345197fc6″}}

AppleScript名:Microsoft Asure Analyze Image APIで画像認識(analyze) v2
— Created 2017-05-03 by Takaaki Naganoya
— 2017 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"

property |NSURL| : a reference to current application’s |NSURL|
property NSData : a reference to current application’s NSData
property NSString : a reference to current application’s NSString
property NSMutableData : a reference to current application’s NSMutableData
property NSURLQueryItem : a reference to current application’s NSURLQueryItem
property NSURLConnection : a reference to current application’s NSURLConnection
property NSJSONSerialization : a reference to current application’s NSJSONSerialization
property NSURLComponents : a reference to current application’s NSURLComponents
property NSMutableDictionary : a reference to current application’s NSMutableDictionary
property NSMutableURLRequest : a reference to current application’s NSMutableURLRequest
property NSUTF8StringEncoding : a reference to current application’s NSUTF8StringEncoding
property NSURLRequestReloadIgnoringLocalCacheData : a reference to current application’s NSURLRequestReloadIgnoringLocalCacheData

set imgFilePath to POSIX path of (choose file of type {"public.image"} with prompt "Select an Image to Analyze")
set aRes to recogImage(imgFilePath) of me
–>  {{metadata:{width:3264, |format|:"Jpeg", height:2448}, categories:{{|name|:"abstract_", score:0.01171875}, {|name|:"abstract_shape", score:0.4609375}, {|name|:"others_", score:0.0078125}, {|name|:"outdoor_", score:0.046875, detail:{landmarks:{{|name|:"Tokyo Skytree", confidence:0.999957323074}}}}}, |description|:{tags:{"outdoor", "building", "bridge", "large", "water", "top", "tower", "blue", "tall", "riding", "city", "standing", "snow", "train", "man", "clock", "air", "sign", "white", "skiing", "street", "boat", "flying", "group", "people"}, captions:{{|text|:"a close up of Tokyo Skytree", confidence:0.90930354838}}}, requestId:"72909fd5-c0be-47dd-81ce-d626873fcbfe"}}

on recogImage(imgFilePath)
  set reqURLStr to "https://westcentralus.api.cognitive.microsoft.com/vision/v1.0/analyze" –Microsoft Azure (New)
  
–set reqURLStr to "https://api.projectoxford.ai/vision/v1.0/analyze" –Microsoft Project Oxford (OLD)
  
set myAPIkey to retAPIkey() of me –API Key 1
  
  
set aRec to {visualFeatures:"Description", details:"Celebrities", |language|:"en"} –age, gender, headPose, smile, facialHair, glasses
  
set bURL to retURLwithParams(reqURLStr, aRec) of me
  
  
set aRes to callRestPOSTAPIAndParseResultsWithImage(bURL, imgFilePath, myAPIkey) of me
  
set aRESTres to json of aRes
  
set aRESCode to responseCode of aRes
  
set aRESHeader to responseHeader of aRes
  
  
return (aRESTres as list)
end recogImage

–POST methodのREST APIを画像をアップロードしつつ呼ぶ
on callRestPOSTAPIAndParseResultsWithImage(aURL, imgFilePath, anAPIkey)
  –Get Image Contents from file
  
set imgPathStr to NSString’s stringWithString:imgFilePath
  
set imgData to NSData’s dataWithContentsOfFile:imgPathStr
  
set postBody to NSMutableData’s |data|()
  
postBody’s appendData:imgData
  
  
–Request
  
set aRequest to NSMutableURLRequest’s requestWithURL:(|NSURL|’s URLWithString:aURL)
  
aRequest’s setHTTPMethod:"POST"
  
aRequest’s setCachePolicy:(NSURLRequestReloadIgnoringLocalCacheData)
  
aRequest’s setHTTPShouldHandleCookies:false
  
aRequest’s setTimeoutInterval:60
  
aRequest’s setHTTPBody:postBody
  
aRequest’s setValue:"application/octet-stream" forHTTPHeaderField:"Content-Type"
  
aRequest’s setValue:anAPIkey forHTTPHeaderField:"Ocp-Apim-Subscription-Key"
  
  
–CALL REST API
  
set aRes to NSURLConnection’s sendSynchronousRequest:aRequest returningResponse:(reference) |error|:(missing value)
  
  
–Parse Results
  
set resList to aRes as list
  
  
set bRes to contents of (first item of resList)
  
set resStr to NSString’s alloc()’s initWithData:bRes encoding:(NSUTF8StringEncoding)
  
  
set jsonString to NSString’s stringWithString:resStr
  
set jsonData to jsonString’s dataUsingEncoding:(NSUTF8StringEncoding)
  
set aJsonDict to NSJSONSerialization’s JSONObjectWithData:jsonData options:0 |error|:(missing value)
  
  
–Get Response Code
  
set dRes to contents of second item of resList
  
if dRes = missing value then
    set resCode to -1
    
set resHeaders to {}
  else
    set resCode to (dRes’s statusCode()) as integer
    
–Get Response Header
    
set resHeaders to (dRes’s allHeaderFields()) as record
  end if
  
  
return {json:aJsonDict, responseCode:resCode, responseHeader:resHeaders}
  
end callRestPOSTAPIAndParseResultsWithImage

on retURLwithParams(aBaseURL, aRec)
  set aDic to NSMutableDictionary’s dictionaryWithDictionary:aRec
  
  
set aKeyList to (aDic’s allKeys()) as list
  
set aValList to (aDic’s allValues()) as list
  
set aLen to length of aKeyList
  
  
set qList to {}
  
repeat with i from 1 to aLen
    set aName to contents of item i of aKeyList
    
set aVal to contents of item i of aValList
    
set the end of qList to (NSURLQueryItem’s queryItemWithName:aName value:aVal)
  end repeat
  
  
set aComp to NSURLComponents’s alloc()’s initWithString:aBaseURL
  
aComp’s setQueryItems:qList
  
set aURL to (aComp’s |URL|()’s absoluteString()) –as text
  
  
return aURL
end retURLwithParams

on retAPIkey()
  return "xxXXXxXXxxXxXXXXxXXxXxXXXXxXxxXX" –API Primary Key
end retAPIkey

★Click Here to Open This Script 

Posted in Image JSON Network REST API | Tagged 10.11savvy 10.12savvy 10.13savvy | 1 Comment

(GET)駅すぱあとAPIで平均待ち時間「バスのみ探索」

Posted on 3月 17, 2018 by Takaaki Naganoya

ヴァル研究所が提供している、公共交通機関の乗り換え検索アプリケーション「駅すぱあと」のREST APIを呼び出して、バス路線の検索を行うAppleScriptです。


(「47都道府県鉄道路線図」より引用)

掲載の本Scriptをためしてみる場合には、かならずご自分で「駅すぱあとWebサービス スタンダードプラン」90日間無料試用コードを取得してScript末尾にあるハンドラに記入してから実行してください。そのまま実行するとエラーになります。

駅コードで発停留所、着停留所をIDで指定して経路検索を行います。本サンプルでは、関東バスの「中村橋」から、「阿佐ヶ谷駅」までの経路を検索しています。時間については平均待ち時間を適用しているとのこと。

AppleScript名:(GET)駅すぱあとAPIで平均待ち時間バスのみ探索
— Created 2018-03-16 by Takaaki Naganoya
— 2018 Piyomaru Software
use AppleScript version "2.5" –macOS 10.11 or later
use scripting additions
use framework "Foundation"

–http://docs.ekispert.com/v1/api/search/course/bus.html
set aURL to "https://api.ekispert.jp/v1/json/search/course/bus"

set apiKey to retAccessToken() of me
set aRec to {|key|:apiKey, |from|:"45848", |to|:"45507"} –関東バス 「中村橋駅」発、「阿佐ヶ谷」着
set reqURLStr to retURLwithParams(aURL, aRec) of me

set aRes to callRestGETAPIAndParseResults(reqURLStr) of me
set aRESCode to (responseCode of aRes) as integer
if aRESCode is not equal to 200 then return false

set aRESHeader to responseHeader of aRes
set aRESTres to json of aRes as list of string or string

–GET methodのREST APIを呼ぶ
on callRestGETAPIAndParseResults(aURL)
  set aRequest to current application’s NSMutableURLRequest’s requestWithURL:(current application’s |NSURL|’s URLWithString:aURL)
  
aRequest’s setHTTPMethod:"GET"
  
aRequest’s setValue:"gzip" forHTTPHeaderField:"Content-Encoding"
  
  
set aRes to current application’s NSURLConnection’s sendSynchronousRequest:aRequest returningResponse:(reference) |error|:(missing value)
  
set resList to aRes as list
  
  
set bRes to contents of (first item of resList)
  
set resStr to current application’s NSString’s alloc()’s initWithData:bRes encoding:(current application’s NSUTF8StringEncoding)
  
  
set jsonString to current application’s NSString’s stringWithString:resStr
  
set jsonData to jsonString’s dataUsingEncoding:(current application’s NSUTF8StringEncoding)
  
set aJsonDict to current application’s NSJSONSerialization’s JSONObjectWithData:jsonData options:0 |error|:(missing value)
  
  
–Get Response Code & Header
  
set dRes to contents of second item of resList
  
if dRes is not equal to missing value then
    set resCode to (dRes’s statusCode()) as number
    
set resHeaders to (dRes’s allHeaderFields()) as record
  else
    set resCode to 0
    
set resHeaders to {}
  end if
  
  
return {json:aJsonDict, responseCode:resCode, responseHeader:resHeaders}
end callRestGETAPIAndParseResults

on retURLwithParams(aBaseURL, aRec)
  set aDic to current application’s NSMutableDictionary’s dictionaryWithDictionary:aRec
  
set aKeyList to (aDic’s allKeys()) as list
  
set aValList to (aDic’s allValues()) as list
  
set aLen to length of aKeyList
  
  
set qList to {}
  
repeat with i from 1 to aLen
    set aName to contents of item i of aKeyList
    
set aVal to contents of item i of aValList
    
set the end of qList to (current application’s NSURLQueryItem’s queryItemWithName:aName value:aVal)
  end repeat
  
  
set aComp to current application’s NSURLComponents’s alloc()’s initWithString:aBaseURL
  
aComp’s setQueryItems:qList
  
set aURL to (aComp’s |URL|()’s absoluteString()) as text
  
  
return aURL
end retURLwithParams

on retAccessToken()
  return "xxxx_XXxxXXXxxXX" –API Key
end retAccessToken

★Click Here to Open This Script 

Posted in Network REST API | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

(GET)駅すぱあとAPIで経路簡易探索(駅名称指定)

Posted on 3月 17, 2018 by Takaaki Naganoya

ヴァル研究所が提供している、公共交通機関の乗り換え検索アプリケーション「駅すぱあと」のREST APIを呼び出して、駅名から経路検索を行うAppleScriptです。


(「47都道府県鉄道路線図」より引用)

掲載の本Scriptをためしてみる場合には、かならずご自分で「駅すぱあとWebサービス スタンダードプラン」90日間無料試用コードを取得してScript末尾にあるハンドラに記入してから実行してください。そのまま実行するとエラーになります。

駅コードで発駅、経由駅、着駅を指定して経路検索を行います。本サンプルでは、西武池袋線の中村橋駅から、池袋駅を経由して、京急線の羽田空港国内線ターミナル駅までの経路を検索しています。

AppleScript名:(GET)駅すぱあとAPIで経路簡易探索(駅名称指定)
— Created 2018-03-16 by Takaaki Naganoya
— 2018 Piyomaru Software
use AppleScript version "2.5" –macOS 10.11 or later
use scripting additions
use framework "Foundation"

–http://docs.ekispert.com/v1/api/search/course.html
set aURL to "https://api.ekispert.jp/v1/json/search/course"

set apiKey to retAccessToken() of me
set aRec to {|key|:apiKey, |from|:"中村橋", |to|:"池袋", via:"羽田空港国内線ターミナル"} –中村橋駅 発、池袋経由、羽田空港国内線ターミナル 着
set reqURLStr to retURLwithParams(aURL, aRec) of me

set aRes to callRestGETAPIAndParseResults(reqURLStr) of me
set aRESCode to (responseCode of aRes) as integer
if aRESCode is not equal to 200 then return false

set aRESHeader to responseHeader of aRes
set aRESTres to json of aRes as list of string or string

–GET methodのREST APIを呼ぶ
on callRestGETAPIAndParseResults(aURL)
  set aRequest to current application’s NSMutableURLRequest’s requestWithURL:(current application’s |NSURL|’s URLWithString:aURL)
  
aRequest’s setHTTPMethod:"GET"
  
aRequest’s setValue:"gzip" forHTTPHeaderField:"Content-Encoding"
  
  
set aRes to current application’s NSURLConnection’s sendSynchronousRequest:aRequest returningResponse:(reference) |error|:(missing value)
  
set resList to aRes as list
  
  
set bRes to contents of (first item of resList)
  
set resStr to current application’s NSString’s alloc()’s initWithData:bRes encoding:(current application’s NSUTF8StringEncoding)
  
  
set jsonString to current application’s NSString’s stringWithString:resStr
  
set jsonData to jsonString’s dataUsingEncoding:(current application’s NSUTF8StringEncoding)
  
set aJsonDict to current application’s NSJSONSerialization’s JSONObjectWithData:jsonData options:0 |error|:(missing value)
  
  
–Get Response Code & Header
  
set dRes to contents of second item of resList
  
if dRes is not equal to missing value then
    set resCode to (dRes’s statusCode()) as number
    
set resHeaders to (dRes’s allHeaderFields()) as record
  else
    set resCode to 0
    
set resHeaders to {}
  end if
  
  
return {json:aJsonDict, responseCode:resCode, responseHeader:resHeaders}
end callRestGETAPIAndParseResults

on retURLwithParams(aBaseURL, aRec)
  set aDic to current application’s NSMutableDictionary’s dictionaryWithDictionary:aRec
  
set aKeyList to (aDic’s allKeys()) as list
  
set aValList to (aDic’s allValues()) as list
  
set aLen to length of aKeyList
  
  
set qList to {}
  
repeat with i from 1 to aLen
    set aName to contents of item i of aKeyList
    
set aVal to contents of item i of aValList
    
set the end of qList to (current application’s NSURLQueryItem’s queryItemWithName:aName value:aVal)
  end repeat
  
  
set aComp to current application’s NSURLComponents’s alloc()’s initWithString:aBaseURL
  
aComp’s setQueryItems:qList
  
set aURL to (aComp’s |URL|()’s absoluteString()) as text
  
  
return aURL
end retURLwithParams

on retAccessToken()
  return "xxxx_XXxxXXXxxXX" –API Key
end retAccessToken

★Click Here to Open This Script 

Posted in Network REST API | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

(GET)駅すぱあとAPIでデータバージョンを取得

Posted on 3月 17, 2018 by Takaaki Naganoya

ヴァル研究所が提供している、公共交通機関の乗り換え検索アプリケーション「駅すぱあと」のREST APIを呼び出して、データのバージョンを求めるAppleScriptです。

本Scriptをためしてみる場合には、かならずご自分で「駅すぱあとWebサービス スタンダードプラン」の試用コードを取得してScript末尾にあるハンドラに記入してから実行してください。そのまま実行するとエラーになります。

AppleScript名:(GET)駅すぱあとAPIでデータバージョンを取得
— Created 2018-03-16 by Takaaki Naganoya
— 2018 Piyomaru Software
use AppleScript version "2.5" –macOS 10.11 or later
use scripting additions
use framework "Foundation"

set aURL to "https://api.ekispert.jp/v1/json/dataversion"

set apiKey to retAccessToken() of me
set aRec to {|key|:apiKey}
set reqURLStr to retURLwithParams(aURL, aRec) of me

set aRes to callRestGETAPIAndParseResults(reqURLStr) of me
set aRESCode to (responseCode of aRes) as integer
if aRESCode is not equal to 200 then return false

set aRESHeader to responseHeader of aRes
set aRESTres to json of aRes as list of string or string

(*
{​​​​​ResultSet:{​​​​​​​engineVersion:"201803_04a", ​​​​​​​Version:{​​​​​​​​​{​​​​​​​​​​​createType:"Edition", ​​​​​​​​​​​create:"20180304", ​​​​​​​​​​​caption:"知識ベース"​​​​​​​​​}, ​​​​​​​​​{​​​​​​​​​​​createType:"Edition", ​​​​​​​​​​​create:"20180304", ​​​​​​​​​​​caption:"鉄道時刻表"​​​​​​​​​}, ​​​​​​​​​{​​​​​​​​​​​createType:"Date", ​​​​​​​​​​​caption:"JR", ​​​​​​​​​​​createComment:"Now", ​​​​​​​​​​​create:"20180317"​​​​​​​​​}, ​​​​​​​​​{​​​​​​​​​​​createType:"Date", ​​​​​​​​​​​caption:"私鉄", ​​​​​​​​​​​createComment:"Now", ​​​​​​​​​​​create:"20180312"​​​​​​​​​}, ​​​​​​​​​{​​​​​​​​​​​createType:"Edition", ​​​​​​​​​​​caption:"航空時刻表", ​​​​​​​​​​​rangeTo:"20180531", ​​​​​​​​​​​rangeFrom:"20180201", ​​​​​​​​​​​rangeCaption:"有効期間", ​​​​​​​​​​​create:"20180401"​​​​​​​​​}, ​​​​​​​​​{​​​​​​​​​​​createType:"Edition", ​​​​​​​​​​​create:"20180401", ​​​​​​​​​​​caption:"高速・連絡・深夜急行バス"​​​​​​​​​}, ​​​​​​​​​{​​​​​​​​​​​createType:"Edition", ​​​​​​​​​​​create:"20180401", ​​​​​​​​​​​caption:"船"​​​​​​​​​}, ​​​​​​​​​{​​​​​​​​​​​createType:"Date", ​​​​​​​​​​​caption:"得トクきっぷデータ", ​​​​​​​​​​​createComment:"Now", ​​​​​​​​​​​create:"20180201"​​​​​​​​​}, ​​​​​​​​​{​​​​​​​​​​​createType:"HideDay", ​​​​​​​​​​​caption:"住所データ", ​​​​​​​​​​​createComment:"Now", ​​​​​​​​​​​create:"20170101"​​​​​​​​​}​​​​​​​}, ​​​​​​​Copyrights:{​​​​​​​​​companyId:"2", ​​​​​​​​​text:"交承 平成25年68号
JRデータの内容は、株式会社交通新聞社発行の「JR時刻表」2018年3月号に基づいています。
この時刻データを無断で転載・複写し、又は紙媒体、電磁媒体その他いかなる媒体に加工することも禁じます。

JRバスデータの内容は、株式会社交通新聞社作成のデータ平成30年3月分に基づいています。この時刻データを無断転載・複写や電磁媒体等に加工することを禁じます。

名鉄バスの情報は、名鉄バス株式会社作成のデータに基づいています。ただし一部のバス停ポール情報は株式会社ヴァル研究所が自らの責任により加工したものです。

ほか、一部の内容は株式会社ヴァル研究所が自らの責任により加工したものです。
", ​​​​​​​​​company:"株式会社交通新聞社"​​​​​​​}, ​​​​​​​apiVersion:"1.27.0.0"​​​​​}​​​}
*)

–GET methodのREST APIを呼ぶ
on callRestGETAPIAndParseResults(aURL)
  set aRequest to current application’s NSMutableURLRequest’s requestWithURL:(current application’s |NSURL|’s URLWithString:aURL)
  
aRequest’s setHTTPMethod:"GET"
  
aRequest’s setValue:"gzip" forHTTPHeaderField:"Content-Encoding"
  
  
set aRes to current application’s NSURLConnection’s sendSynchronousRequest:aRequest returningResponse:(reference) |error|:(missing value)
  
set resList to aRes as list
  
  
set bRes to contents of (first item of resList)
  
set resStr to current application’s NSString’s alloc()’s initWithData:bRes encoding:(current application’s NSUTF8StringEncoding)
  
  
set jsonString to current application’s NSString’s stringWithString:resStr
  
set jsonData to jsonString’s dataUsingEncoding:(current application’s NSUTF8StringEncoding)
  
set aJsonDict to current application’s NSJSONSerialization’s JSONObjectWithData:jsonData options:0 |error|:(missing value)
  
  
–Get Response Code & Header
  
set dRes to contents of second item of resList
  
if dRes is not equal to missing value then
    set resCode to (dRes’s statusCode()) as number
    
set resHeaders to (dRes’s allHeaderFields()) as record
  else
    set resCode to 0
    
set resHeaders to {}
  end if
  
  
return {json:aJsonDict, responseCode:resCode, responseHeader:resHeaders}
end callRestGETAPIAndParseResults

on retURLwithParams(aBaseURL, aRec)
  set aDic to current application’s NSMutableDictionary’s dictionaryWithDictionary:aRec
  
set aKeyList to (aDic’s allKeys()) as list
  
set aValList to (aDic’s allValues()) as list
  
set aLen to length of aKeyList
  
  
set qList to {}
  
repeat with i from 1 to aLen
    set aName to contents of item i of aKeyList
    
set aVal to contents of item i of aValList
    
set the end of qList to (current application’s NSURLQueryItem’s queryItemWithName:aName value:aVal)
  end repeat
  
  
set aComp to current application’s NSURLComponents’s alloc()’s initWithString:aBaseURL
  
aComp’s setQueryItems:qList
  
set aURL to (aComp’s |URL|()’s absoluteString()) as text
  
  
return aURL
end retURLwithParams

on retAccessToken()
  return "xxxx_XXxxXXXxxXX" –API Key
end retAccessToken

★Click Here to Open This Script 

Posted in Network REST API | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

(GET)駅すぱあとAPIで経路検索

Posted on 3月 16, 2018 by Takaaki Naganoya

ヴァル研究所が提供している、公共交通機関の乗り換え検索アプリケーション「駅すぱあと」のREST APIを呼び出して、経路検索を行うAppleScriptです。


(「47都道府県鉄道路線図」より引用)

掲載の本Scriptをためしてみる場合には、かならずご自分で「駅すぱあとWebサービス スタンダードプラン」90日間無料試用コードを取得してScript末尾にあるハンドラに記入してから実行してください。そのまま実行するとエラーになります。

駅コードで発駅、経由駅、着駅を指定して経路検索を行います。本サンプルでは、西武池袋線の中村橋駅から、池袋駅を経由して、京急線の羽田空港国内線ターミナル駅までの経路を検索しています。

駅すぱあとAPIのドキュメントを読んだかぎりでは、

 ①駅コード(ユニークなコード)で検索
 ②駅名称で検索
 ③緯度経度情報で検索
 ④住所情報を検索
 ⑤地区データで検索

といった検索が可能なようです。まずは、一番重要な駅コードによる検索を調べてみた次第です。

AppleScript名:(GET)駅すぱあとAPIで経路検索
— Created 2018-03-16 by Takaaki Naganoya
— 2018 Piyomaru Software
use AppleScript version "2.5" –macOS 10.11 or later
use scripting additions
use framework "Foundation"

set aURL to "https://api.ekispert.jp/v1/json/search/course/extreme"

set apiKey to retAccessToken() of me
set aRec to {|key|:apiKey, viaList:"22854:22513:22911"} –中村橋駅 発、池袋経由、羽田空港国内線ターミナル 着
set reqURLStr to retURLwithParams(aURL, aRec) of me

set aRes to callRestGETAPIAndParseResults(reqURLStr) of me
set aRESCode to (responseCode of aRes) as integer
if aRESCode is not equal to 200 then return false

set aRESHeader to responseHeader of aRes
set aRESTres to json of aRes as list of string or string

–GET methodのREST APIを呼ぶ
on callRestGETAPIAndParseResults(aURL)
  set aRequest to current application’s NSMutableURLRequest’s requestWithURL:(current application’s |NSURL|’s URLWithString:aURL)
  
aRequest’s setHTTPMethod:"GET"
  
aRequest’s setValue:"gzip" forHTTPHeaderField:"Content-Encoding"
  
  
set aRes to current application’s NSURLConnection’s sendSynchronousRequest:aRequest returningResponse:(reference) |error|:(missing value)
  
set resList to aRes as list
  
  
set bRes to contents of (first item of resList)
  
set resStr to current application’s NSString’s alloc()’s initWithData:bRes encoding:(current application’s NSUTF8StringEncoding)
  
  
set jsonString to current application’s NSString’s stringWithString:resStr
  
set jsonData to jsonString’s dataUsingEncoding:(current application’s NSUTF8StringEncoding)
  
set aJsonDict to current application’s NSJSONSerialization’s JSONObjectWithData:jsonData options:0 |error|:(missing value)
  
  
–Get Response Code & Header
  
set dRes to contents of second item of resList
  
if dRes is not equal to missing value then
    set resCode to (dRes’s statusCode()) as number
    
set resHeaders to (dRes’s allHeaderFields()) as record
  else
    set resCode to 0
    
set resHeaders to {}
  end if
  
  
return {json:aJsonDict, responseCode:resCode, responseHeader:resHeaders}
end callRestGETAPIAndParseResults

on retURLwithParams(aBaseURL, aRec)
  set aDic to current application’s NSMutableDictionary’s dictionaryWithDictionary:aRec
  
set aKeyList to (aDic’s allKeys()) as list
  
set aValList to (aDic’s allValues()) as list
  
set aLen to length of aKeyList
  
  
set qList to {}
  
repeat with i from 1 to aLen
    set aName to contents of item i of aKeyList
    
set aVal to contents of item i of aValList
    
set the end of qList to (current application’s NSURLQueryItem’s queryItemWithName:aName value:aVal)
  end repeat
  
  
set aComp to current application’s NSURLComponents’s alloc()’s initWithString:aBaseURL
  
aComp’s setQueryItems:qList
  
set aURL to (aComp’s |URL|()’s absoluteString()) as text
  
  
return aURL
end retURLwithParams

on retAccessToken()
  return "xxxx_XXxxXXXxxXX" –API Key
end retAccessToken

★Click Here to Open This Script 

Posted in JSON Network REST API | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

(GET)駅すぱあとAPIで駅コード検索

Posted on 3月 16, 2018 by Takaaki Naganoya

ヴァル研究所が提供している、公共交通機関の乗り換え検索アプリケーション「駅すぱあと」のREST APIを呼び出して、駅名称から「駅すぱあと」内部で利用している駅コードを検索するAppleScriptです。


(「47都道府県鉄道路線図」より引用)

「駅すぱあと」はほぼ日本人なら(とくに首都圏に住んでいると)誰でも知っている、電車をはじめとする公共交通機関の乗り換え情報を検索するアプリケーションです。

本来、AppleScriptと相性の良い処理のはずなのですが、Mac版のアプリケーションが最近は提供されておらず、さらに昔のMac版のアプリケーションもAppleScriptに対応していなかったので、長らく接点がありませんでした。

そんな中、「駅すぱあと」のREST APIが試用できるようになっていることを知り、さっそくサインアップして「駅すぱあとWebサービス スタンダードプラン」90日試用コードを取得してみました。掲載の本Scriptをためしてみる場合には、かならずご自分で試用コードを取得してScript末尾にあるハンドラに記入してから実行してください。そのまま実行するとエラーになります。

ドキュメントもよく整備されており、首をひねるような仕様もなく、日本国内で提供されているREST APIとしては非常によく整理されているといえます。

本来はいきなり経路検索を行いたかったのですが、経路検索を行うのに、駅固有のユニークコードである「駅コード」を調べられないと困るので、まずは駅コードから駅名称を調べたり、駅名称から駅コードを調べるAppleScriptを書いてみました(羽田空港からの帰りのバスの中で)。

これで、MacのExcelやFileMaker Pro、Numbersといったアプリケーションの書類上に入れたデータから経路検索を行なってこれらのアプリケーションのデータに返すことができるようになったわけで、応用範囲はきわめて広いといえます。

AppleScript名:(GET)駅すぱあとAPIで駅コード検索
— Created 2018-03-16 by Takaaki Naganoya
— 2018 Piyomaru Software
use AppleScript version "2.5" –macOS 10.11 or later
use scripting additions
use framework "Foundation"

set aURL to "https://api.ekispert.jp/v1/json/station/light"

set apiKey to retAccessToken() of me
set aRec to {|key|:apiKey, |name|:"羽田空港国内線ターミナル", type:"train"}
set reqURLStr to retURLwithParams(aURL, aRec) of me

set aRes to callRestGETAPIAndParseResults(reqURLStr) of me
set aRESCode to (responseCode of aRes) as integer
if aRESCode is not equal to 200 then return false

set aRESHeader to responseHeader of aRes
set aRESTres to (json of aRes) –NSDictionaryで返ってくる

set staCode to (aRESTres’s valueForKeyPath:"ResultSet.Point.Station.code") as list of string or string –as anything
–> 22854

–GET methodのREST APIを呼ぶ
on callRestGETAPIAndParseResults(aURL)
  set aRequest to current application’s NSMutableURLRequest’s requestWithURL:(current application’s |NSURL|’s URLWithString:aURL)
  
aRequest’s setHTTPMethod:"GET"
  
aRequest’s setValue:"gzip" forHTTPHeaderField:"Content-Encoding"
  
  
set aRes to current application’s NSURLConnection’s sendSynchronousRequest:aRequest returningResponse:(reference) |error|:(missing value)
  
set resList to aRes as list
  
  
set bRes to contents of (first item of resList)
  
set resStr to current application’s NSString’s alloc()’s initWithData:bRes encoding:(current application’s NSUTF8StringEncoding)
  
  
set jsonString to current application’s NSString’s stringWithString:resStr
  
set jsonData to jsonString’s dataUsingEncoding:(current application’s NSUTF8StringEncoding)
  
set aJsonDict to current application’s NSJSONSerialization’s JSONObjectWithData:jsonData options:0 |error|:(missing value)
  
  
–Get Response Code & Header
  
set dRes to contents of second item of resList
  
if dRes is not equal to missing value then
    set resCode to (dRes’s statusCode()) as number
    
set resHeaders to (dRes’s allHeaderFields()) as record
  else
    set resCode to 0
    
set resHeaders to {}
  end if
  
  
return {json:aJsonDict, responseCode:resCode, responseHeader:resHeaders}
end callRestGETAPIAndParseResults

on retURLwithParams(aBaseURL, aRec)
  set aDic to current application’s NSMutableDictionary’s dictionaryWithDictionary:aRec
  
set aKeyList to (aDic’s allKeys()) as list
  
set aValList to (aDic’s allValues()) as list
  
set aLen to length of aKeyList
  
  
set qList to {}
  
repeat with i from 1 to aLen
    set aName to contents of item i of aKeyList
    
set aVal to contents of item i of aValList
    
set the end of qList to (current application’s NSURLQueryItem’s queryItemWithName:aName value:aVal)
  end repeat
  
  
set aComp to current application’s NSURLComponents’s alloc()’s initWithString:aBaseURL
  
aComp’s setQueryItems:qList
  
set aURL to (aComp’s |URL|()’s absoluteString()) as text
  
  
return aURL
end retURLwithParams

on retAccessToken()
  return "xxxx_XXxxXXXxxXX" –API Key
end retAccessToken

★Click Here to Open This Script 

Posted in Network REST API | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

(GET)駅すぱあとAPIで駅コードから駅名称を取得

Posted on 3月 16, 2018 by Takaaki Naganoya

ヴァル研究所が提供している、公共交通機関の乗り換え検索アプリケーション「駅すぱあと」のREST APIを呼び出して、「駅すぱあと」内部で利用している駅コードから駅の名称を取得するAppleScriptです。

「駅すぱあと」はほぼ日本人なら(とくに首都圏に住んでいると)誰でも知っている、電車をはじめとする公共交通機関の乗り換え情報を検索するアプリケーションです。


(「47都道府県鉄道路線図」より引用)

本来、AppleScriptと相性の良い処理のはずなのですが、Mac版のアプリケーションが最近は提供されておらず、さらに昔のMac版のアプリケーションもAppleScriptに対応していなかったので、長らく接点がありませんでした。

そんな中、「駅すぱあと」のREST APIが試用できるようになっていることを知り、さっそくサインアップして「駅すぱあとWebサービス スタンダードプラン」90日試用コードを取得してみました。掲載の本Scriptをためしてみる場合には、かならずご自分で試用コードを取得してScript末尾にあるハンドラに記入してから実行してください。そのまま実行するとエラーになります。

「駅すぱあと」のREST APIはドキュメントもよく整備されており、首をひねるような仕様もなく、日本国内で提供されているREST APIとしては非常によく整理されているといえます。

本来はいきなり経路検索を行いたかったのですが、経路検索を行うのに、駅固有のユニークコードである「駅コード」を調べられないと困るので、まずは駅コードから駅名称を調べたり、駅名称から駅コードを調べるAppleScriptを書いてみました(羽田空港からの帰りのバスの中で)。

これで、MacのExcelやFileMaker Pro、Numbersといったアプリケーションの書類上に入れたデータから経路検索を行なってこれらのアプリケーションのデータに返すことができるようになったわけで、応用範囲はきわめて広いといえます。

駅すぱあとAPIのドキュメントについては、1点だけ「format」の説明(結果の取得フォーマットがjsonかXMLかを指定)の説明がわかりづらく、この説明だとformat=jsonといった指定を行なってしまうと思います。

AppleScript名:(GET)駅すぱあとAPIで駅コードから駅名称を取得
— Created 2018-03-16 by Takaaki Naganoya
— 2018 Piyomaru Software
use AppleScript version "2.5" –macOS 10.11 or later
use scripting additions
use framework "Foundation"

set aURL to "https://api.ekispert.jp/v1/json/station"

set apiKey to retAccessToken() of me
set aRec to {|key|:apiKey, code:"25853"}
set reqURLStr to retURLwithParams(aURL, aRec) of me

set aRes to callRestGETAPIAndParseResults(reqURLStr) of me
set aRESCode to (responseCode of aRes) as integer
if aRESCode is not equal to 200 then return false

set aRESHeader to responseHeader of aRes
set aRESTres to (json of aRes) –NSDictionaryで返ってくる

set staCode to aRESTres’s valueForKeyPath:"ResultSet.Point.Station.Name"
–> "大阪"

–GET methodのREST APIを呼ぶ
on callRestGETAPIAndParseResults(aURL)
  set aRequest to current application’s NSMutableURLRequest’s requestWithURL:(current application’s |NSURL|’s URLWithString:aURL)
  
aRequest’s setHTTPMethod:"GET"
  
aRequest’s setValue:"gzip" forHTTPHeaderField:"Content-Encoding"
  
  
set aRes to current application’s NSURLConnection’s sendSynchronousRequest:aRequest returningResponse:(reference) |error|:(missing value)
  
set resList to aRes as list
  
  
set bRes to contents of (first item of resList)
  
set resStr to current application’s NSString’s alloc()’s initWithData:bRes encoding:(current application’s NSUTF8StringEncoding)
  
  
set jsonString to current application’s NSString’s stringWithString:resStr
  
set jsonData to jsonString’s dataUsingEncoding:(current application’s NSUTF8StringEncoding)
  
set aJsonDict to current application’s NSJSONSerialization’s JSONObjectWithData:jsonData options:0 |error|:(missing value)
  
  
–Get Response Code & Header
  
set dRes to contents of second item of resList
  
if dRes is not equal to missing value then
    set resCode to (dRes’s statusCode()) as number
    
set resHeaders to (dRes’s allHeaderFields()) as record
  else
    set resCode to 0
    
set resHeaders to {}
  end if
  
  
return {json:aJsonDict, responseCode:resCode, responseHeader:resHeaders}
end callRestGETAPIAndParseResults

on retURLwithParams(aBaseURL, aRec)
  set aDic to current application’s NSMutableDictionary’s dictionaryWithDictionary:aRec
  
set aKeyList to (aDic’s allKeys()) as list
  
set aValList to (aDic’s allValues()) as list
  
set aLen to length of aKeyList
  
  
set qList to {}
  
repeat with i from 1 to aLen
    set aName to contents of item i of aKeyList
    
set aVal to contents of item i of aValList
    
set the end of qList to (current application’s NSURLQueryItem’s queryItemWithName:aName value:aVal)
  end repeat
  
  
set aComp to current application’s NSURLComponents’s alloc()’s initWithString:aBaseURL
  
aComp’s setQueryItems:qList
  
set aURL to (aComp’s |URL|()’s absoluteString()) as text
  
  
return aURL
end retURLwithParams

on retAccessToken()
  return "xxxx_XXxxXXXxxXX" –API Key
end retAccessToken

★Click Here to Open This Script 

Posted in Network REST API | Tagged 10.11savvy 10.12savvy 10.13savvy | 1 Comment

旅行系サイトごちゃまぜフィード

Posted on 3月 3, 2018 by Takaaki Naganoya

ApitoreのREST API「旅行系サイト ごちゃまぜフィード」を呼び出して、さまざまな旅行系サイトのNews Feedを一括で取得するAppleScriptです。

# Apitoreは2019年5月31日をもってサービスを終了

「旅行系サイト ごちゃまぜフィード」は、30分に1回の頻度でRSSの更新を確認にいきます。REST APIで最新情報が取得できるオンラインクローラーです。

本AppleScript利用のためには、Apitoreにサインアップしてアカウントを作成し、新規プロジェクトを作成(Test AppleScriptとか)。そこに、本APIを利用できるように登録し、「アクセストークン」を取得する必要があります。

アクセストークンを取得せずに掲載状態のまま本AppleScriptを実行してもエラーになります。

取得したアクセストークンを本AppleScript中のretAccessToken()ハンドラ内に記載し、実行してください。

AppleScript名:旅行系サイトごちゃまぜフィード
— Created 2016-10-27 by Takaaki Naganoya
— 2016 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"

set allFeeds to {}

repeat with i from 1 to 100
  set {aRes, maxNum} to getAFeeds(i) of me
  
  
if aRes = false then exit repeat
  
set maxNum to maxNum as number
  
set allFeeds to allFeeds & aRes
  
if (maxNum div 10) ≤ i then
    exit repeat
  end if
end repeat

return allFeeds
–>  
(*
{​​​​​{​​​​​​​author:"", ​​​​​​​sourceTitle:"Compathy Magazine(コンパシーマガジン)", ​​​​​​​title:"【東京美食】 2017壽司必吃!東京壽司推薦攻略TOP18,日式壽司禮儀超強指南", ​​​​​​​link:"https://www.compathy.net/magazine/2017/03/29/tokyosushitop18/", ​​​​​​​pubDate:1.490783697E+12, ​​​​​​​description:"", ​​​​​​​sourceLink:"https://www.compathy.net/magazine"​​​​​},
*)

on getAFeeds(aNum)
  set reqURLStr to "https://api.apitore.com/api/36/feeds/travel"
  
set accessToken to retAccessToken() of me —Access Token
  
set aRec to {access_token:accessToken, page:(aNum as string)}
  
set aURL to retURLwithParams(reqURLStr, aRec) of me
  
  
set aRes to callRestGETAPIAndParseResults(aURL) of me
  
  
set aRESCode to (responseCode of aRes) as integer
  
if aRESCode is not equal to 200 then return {false, false}
  
  
set aRESTres to (json of aRes) as record
  
  
set sentiRes to entries of aRESTres
  
set allNum to num of aRESTres
  
  
return {sentiRes, allNum}
end getAFeeds

–GET methodのREST APIを呼ぶ
on callRestGETAPIAndParseResults(aURL)
  
  
set aRequest to current application’s NSMutableURLRequest’s requestWithURL:(current application’s |NSURL|’s URLWithString:aURL)
  
  
aRequest’s setHTTPMethod:"GET"
  
aRequest’s setCachePolicy:(current application’s NSURLRequestReloadIgnoringLocalCacheData)
  
aRequest’s setHTTPShouldHandleCookies:false
  
aRequest’s setTimeoutInterval:60
  
aRequest’s setValue:"application/json" forHTTPHeaderField:"Accept"
  
aRequest’s setValue:"gzip" forHTTPHeaderField:"Content-Encoding"
  
aRequest’s setValue:"Test AppleScript (gzip)" forHTTPHeaderField:"User-Agent"
  
  
set aRes to current application’s NSURLConnection’s sendSynchronousRequest:aRequest returningResponse:(reference) |error|:(missing value)
  
set resList to aRes as list
  
  
set bRes to contents of (first item of resList)
  
set resStr to current application’s NSString’s alloc()’s initWithData:bRes encoding:(current application’s NSUTF8StringEncoding)
  
  
set jsonString to current application’s NSString’s stringWithString:resStr
  
set jsonData to jsonString’s dataUsingEncoding:(current application’s NSUTF8StringEncoding)
  
set aJsonDict to current application’s NSJSONSerialization’s JSONObjectWithData:jsonData options:0 |error|:(missing value)
  
  
–Get Response Code & Header
  
set dRes to contents of second item of resList
  
if dRes is not equal to missing value then
    set resCode to (dRes’s statusCode()) as number
    
set resHeaders to (dRes’s allHeaderFields()) as record
  else
    set resCode to 0
    
set resHeaders to {}
  end if
  
  
return {json:aJsonDict, responseCode:resCode, responseHeader:resHeaders}
  
end callRestGETAPIAndParseResults

on retURLwithParams(aBaseURL, aRec)
  set aDic to current application’s NSMutableDictionary’s dictionaryWithDictionary:aRec
  
  
set aKeyList to (aDic’s allKeys()) as list
  
set aValList to (aDic’s allValues()) as list
  
set aLen to length of aKeyList
  
  
set qList to {}
  
repeat with i from 1 to aLen
    set aName to contents of item i of aKeyList
    
set aVal to contents of item i of aValList
    
set the end of qList to (current application’s NSURLQueryItem’s queryItemWithName:aName value:aVal)
  end repeat
  
  
set aComp to current application’s NSURLComponents’s alloc()’s initWithString:aBaseURL
  
aComp’s setQueryItems:qList
  
set aURL to (aComp’s |URL|()’s absoluteString()) as text
  
  
return aURL
end retURLwithParams

on retAccessToken()
  return "xxXXXxxX-XxXx-XXXX-xXXX-XXxXXxxXxxXx" –API Tore Access Token
end retAccessToken

★Click Here to Open This Script 

Posted in JSON Network REST API | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

証券情報サイト ごちゃまぜフィード

Posted on 3月 3, 2018 by Takaaki Naganoya

ApitoreのREST API「証券情報サイト ごちゃまぜフィード」を呼び出して、さまざまな証券情報サイトのNews Feedを一括で取得するAppleScriptです。

# Apitoreは2019年5月31日をもってサービスを終了

「証券情報サイト ごちゃまぜフィード」は、30分に1回の頻度でRSSの更新を確認にいきます。REST APIで最新情報が取得できるオンラインクローラーです。

本AppleScript利用のためには、Apitoreにサインアップしてアカウントを作成し、新規プロジェクトを作成(Test AppleScriptとか)。そこに、本APIを利用できるように登録し、「アクセストークン」を取得する必要があります。

アクセストークンを取得せずに掲載状態のまま本AppleScriptを実行してもエラーになります。

取得したアクセストークンを本AppleScript中のretAccessToken()ハンドラ内に記載し、実行してください。

AppleScript名:証券情報サイト ごちゃまぜフィード
— Created 2016-10-27 by Takaaki Naganoya
— 2016 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"

set allFeeds to {}

repeat with i from 1 to 100
  set {aRes, maxNum} to getAFeeds(i) of me
  
  
if aRes = false then exit repeat
  
set maxNum to maxNum as number
  
set allFeeds to allFeeds & aRes
  
if (maxNum div 10) ≤ i then
    exit repeat
  end if
end repeat

return allFeeds
–>  
(*
{​​​​​{​​​​​​​author:"日本インタビュ新聞 Media-IR", ​​​​​​​sourceTitle:"日本インタビュ新聞 株式投資情報", ​​​​​​​title:"アライドレシスホールディングスは「継続企業の前提に関する注記」の記載を解消", ​​​​​​​link:"http://kabu-ir.com/article/448533521.html", ​​​​​​​pubDate:1.490787369E+12, ​​​​​​​description:"■返済期日が延長され、当面の資金繰りの安定化が図られる見込み アライドテレシスホールディングス<6835>(東2)は29日、「継続企業の前提に関する注記」の記載を解消することを発表した。 同社グループは、平成28年12月期連結会計年度で営業利益5億72百万円、当期純利益1億11百万円を計上した。しかし、営業活動によるキャッシュフロー4億6百万円に対し、連結会計年度末における金融機関からの有利子負債残高が74億94百万円と多額であり、平成29年6月30日に期間満了となるシンジケ..", ​​​​​​​sourceLink:"http://kabu-ir.com/"​​​​​}, ​​​​​{​​​​​​​author:"日本インタビュ新聞 Media-IR", ​​​​​​​sourceTitle:"日本インタビュ新聞 株式投資情報", ​​​​​​​title:"ケイティケイは今17年8月期第2四半期と通期業績予想の利益面での上方修正を発表", ​​​​​​​
*)

on getAFeeds(aNum)
  set reqURLStr to "https://api.apitore.com/api/31/feeds/certificate"
  
set accessToken to retAccessToken() of me —Access Token
  
set aRec to {access_token:accessToken, page:(aNum as string)}
  
set aURL to retURLwithParams(reqURLStr, aRec) of me
  
  
set aRes to callRestGETAPIAndParseResults(aURL) of me
  
  
set aRESCode to (responseCode of aRes) as integer
  
if aRESCode is not equal to 200 then return {false, false}
  
  
set aRESTres to (json of aRes) as record
  
  
set sentiRes to entries of aRESTres
  
set allNum to num of aRESTres
  
log allNum
  
  
return {sentiRes, allNum}
end getAFeeds

–GET methodのREST APIを呼ぶ
on callRestGETAPIAndParseResults(aURL)
  
  
set aRequest to current application’s NSMutableURLRequest’s requestWithURL:(current application’s |NSURL|’s URLWithString:aURL)
  
  
aRequest’s setHTTPMethod:"GET"
  
aRequest’s setCachePolicy:(current application’s NSURLRequestReloadIgnoringLocalCacheData)
  
aRequest’s setHTTPShouldHandleCookies:false
  
aRequest’s setTimeoutInterval:60
  
aRequest’s setValue:"application/json" forHTTPHeaderField:"Accept"
  
aRequest’s setValue:"gzip" forHTTPHeaderField:"Content-Encoding"
  
aRequest’s setValue:"Test AppleScript (gzip)" forHTTPHeaderField:"User-Agent"
  
  
set aRes to current application’s NSURLConnection’s sendSynchronousRequest:aRequest returningResponse:(reference) |error|:(missing value)
  
set resList to aRes as list
  
  
set bRes to contents of (first item of resList)
  
set resStr to current application’s NSString’s alloc()’s initWithData:bRes encoding:(current application’s NSUTF8StringEncoding)
  
  
set jsonString to current application’s NSString’s stringWithString:resStr
  
set jsonData to jsonString’s dataUsingEncoding:(current application’s NSUTF8StringEncoding)
  
set aJsonDict to current application’s NSJSONSerialization’s JSONObjectWithData:jsonData options:0 |error|:(missing value)
  
  
–Get Response Code & Header
  
set dRes to contents of second item of resList
  
if dRes is not equal to missing value then
    set resCode to (dRes’s statusCode()) as number
    
set resHeaders to (dRes’s allHeaderFields()) –as record
  else
    set resCode to 0
    
set resHeaders to {}
  end if
  
  
return {json:aJsonDict, responseCode:resCode, responseHeader:resHeaders}
  
end callRestGETAPIAndParseResults

on retURLwithParams(aBaseURL, aRec)
  set aDic to current application’s NSMutableDictionary’s dictionaryWithDictionary:aRec
  
  
set aKeyList to (aDic’s allKeys()) as list
  
set aValList to (aDic’s allValues()) as list
  
set aLen to length of aKeyList
  
  
set qList to {}
  
repeat with i from 1 to aLen
    set aName to contents of item i of aKeyList
    
set aVal to contents of item i of aValList
    
set the end of qList to (current application’s NSURLQueryItem’s queryItemWithName:aName value:aVal)
  end repeat
  
  
set aComp to current application’s NSURLComponents’s alloc()’s initWithString:aBaseURL
  
aComp’s setQueryItems:qList
  
set aURL to (aComp’s |URL|()’s absoluteString()) as text
  
  
return aURL
end retURLwithParams

on retAccessToken()
  return "xxXXXxxX-XxXx-XXXX-xXXX-XXxXXxxXxxXx" –API Tore Access Token
end retAccessToken

★Click Here to Open This Script 

Posted in Network REST API | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

ブログごちゃまぜフィード

Posted on 3月 3, 2018 by Takaaki Naganoya

ApitoreのREST API「ブログ ごちゃまぜフィード」を呼び出して、さまざまな各個人ブログのNews Feedを一括で取得するAppleScriptです。

# Apitoreは2019年5月31日をもってサービスを終了

「ブログ ごちゃまぜフィード」は、30分に1回の頻度でRSSの更新を確認にいきます。REST APIで最新情報が取得できるオンラインクローラーです。

本AppleScript利用のためには、Apitoreにサインアップしてアカウントを作成し、新規プロジェクトを作成(Test AppleScriptとか)。そこに、本APIを利用できるように登録し、「アクセストークン」を取得する必要があります。

アクセストークンを取得せずに掲載状態のまま本AppleScriptを実行してもエラーになります。

取得したアクセストークンを本AppleScript中のretAccessToken()ハンドラ内に記載し、実行してください。

AppleScript名:ブログごちゃまぜフィード
— Created 2016-10-27 by Takaaki Naganoya
— 2016 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"

set allFeeds to {}

repeat with i from 1 to 100
  set {aRes, maxNum} to getAFeeds(i) of me
  
  
if aRes = false then exit repeat
  
set maxNum to maxNum as number
  
set allFeeds to allFeeds & aRes
  
if (maxNum div 10) ≤ i then
    exit repeat
  end if
end repeat

return allFeeds
–>  
(*
{​​​​​{​​​​​​​author:"", ​​​​​​​sourceTitle:"毎日新聞 – ニュース速報(総合)", ​​​​​​​title:"那須雪崩:NHK、被害者写真誤り訂正し謝罪", ​​​​​​​link:"http://rss.rssad.jp/rss/artclk/ZLcY1bpa2mkX/98f49f50f6a89c6d7da908d2f7e604f3?ul=IRi._czqYe8fmPstnpk5g5TZSqz2eXK2XhK5Wl.vDmACS2n47wDHuHkQCrQkxmzyg1uf0aUsQxz8MCNU7hjXjz7r54NW", ​​​​​​​pubDate:1.490796812E+12, ​​​​​​​description:"<p><img border=\"0\" width=\"1\" height=\"1\" src=\"http://rss.rssad.jp/rss/artimg/ZLcY1bpa2mkX/98f49f50f6a89c6d7da908d2f7e604f3\"/></p>", ​​​​​​​sourceLink:"http://mainichi.jp"​​​​​},
*)

on getAFeeds(aNum)
  set reqURLStr to "https://api.apitore.com/api/30/feeds/blog"
  
set accessToken to retAccessToken() of me —Access Token
  
set aRec to {access_token:accessToken, page:(aNum as string)}
  
set aURL to retURLwithParams(reqURLStr, aRec) of me
  
  
set aRes to callRestGETAPIAndParseResults(aURL) of me
  
  
set aRESCode to (responseCode of aRes) as integer
  
if aRESCode is not equal to 200 then return {false, false}
  
  
set aRESTres to (json of aRes) as record
  
  
set sentiRes to entries of aRESTres
  
set allNum to num of aRESTres
  
log allNum
  
  
return {sentiRes, allNum}
end getAFeeds

–GET methodのREST APIを呼ぶ
on callRestGETAPIAndParseResults(aURL)
  
  
set aRequest to current application’s NSMutableURLRequest’s requestWithURL:(current application’s |NSURL|’s URLWithString:aURL)
  
  
aRequest’s setHTTPMethod:"GET"
  
aRequest’s setCachePolicy:(current application’s NSURLRequestReloadIgnoringLocalCacheData)
  
aRequest’s setHTTPShouldHandleCookies:false
  
aRequest’s setTimeoutInterval:60
  
aRequest’s setValue:"application/json" forHTTPHeaderField:"Accept"
  
aRequest’s setValue:"gzip" forHTTPHeaderField:"Content-Encoding"
  
aRequest’s setValue:"Test AppleScript (gzip)" forHTTPHeaderField:"User-Agent"
  
  
set aRes to current application’s NSURLConnection’s sendSynchronousRequest:aRequest returningResponse:(reference) |error|:(missing value)
  
set resList to aRes as list
  
  
set bRes to contents of (first item of resList)
  
set resStr to current application’s NSString’s alloc()’s initWithData:bRes encoding:(current application’s NSUTF8StringEncoding)
  
  
set jsonString to current application’s NSString’s stringWithString:resStr
  
set jsonData to jsonString’s dataUsingEncoding:(current application’s NSUTF8StringEncoding)
  
set aJsonDict to current application’s NSJSONSerialization’s JSONObjectWithData:jsonData options:0 |error|:(missing value)
  
  
–Get Response Code & Header
  
set dRes to contents of second item of resList
  
if dRes is not equal to missing value then
    set resCode to (dRes’s statusCode()) as number
    
set resHeaders to (dRes’s allHeaderFields()) as record
  else
    set resCode to 0
    
set resHeaders to {}
  end if
  
  
return {json:aJsonDict, responseCode:resCode, responseHeader:resHeaders}
  
end callRestGETAPIAndParseResults

on retURLwithParams(aBaseURL, aRec)
  set aDic to current application’s NSMutableDictionary’s dictionaryWithDictionary:aRec
  
  
set aKeyList to (aDic’s allKeys()) as list
  
set aValList to (aDic’s allValues()) as list
  
set aLen to length of aKeyList
  
  
set qList to {}
  
repeat with i from 1 to aLen
    set aName to contents of item i of aKeyList
    
set aVal to contents of item i of aValList
    
set the end of qList to (current application’s NSURLQueryItem’s queryItemWithName:aName value:aVal)
  end repeat
  
  
set aComp to current application’s NSURLComponents’s alloc()’s initWithString:aBaseURL
  
aComp’s setQueryItems:qList
  
set aURL to (aComp’s |URL|()’s absoluteString()) as text
  
  
return aURL
end retURLwithParams

on retAccessToken()
  return "xxXXXxxX-XxXx-XXXX-xXXX-XXxXXxxXxxXx" –API Tore Access Token
end retAccessToken

★Click Here to Open This Script 

Posted in Network REST API | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

デザイン系 ごちゃまぜフィード

Posted on 3月 3, 2018 by Takaaki Naganoya

ApitoreのREST API「デザイン系 ごちゃまぜフィード」を呼び出して、さまざまなオシャレなインテリアとかデザインとかを扱うサイトが提供しているNews Feedを一括で取得するAppleScriptです。

# Apitoreは2019年5月31日をもってサービスを終了

「デザイン系 ごちゃまぜフィード」は、30分に1回の頻度でRSSの更新を確認にいきます。REST APIで最新情報が取得できるオンラインクローラーです。巡回先RSSは以下のとおりです。

・Gurafiku
・HITSPAPER
・K’conf Blog
・CASA BRUTUS
・100%LiFE

本AppleScript利用のためには、Apitoreにサインアップしてアカウントを作成し、新規プロジェクトを作成(Test AppleScriptとか)。そこに、本APIを利用できるように登録し、「アクセストークン」を取得する必要があります。

アクセストークンを取得せずに掲載状態のまま本AppleScriptを実行してもエラーになります。

取得したアクセストークンを本AppleScript中のretAccessToken()ハンドラ内に記載し、実行してください。

AppleScript名:デザイン系 ごちゃまぜフィード
— Created 2016-10-27 by Takaaki Naganoya
— 2016 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"

set allFeeds to {}

repeat with i from 1 to 100
  set {aRes, maxNum} to getAFeeds(i) of me
  
  
if aRes = false then exit repeat
  
set maxNum to maxNum as number
  
set allFeeds to allFeeds & aRes
  
if (maxNum div 10) ≤ i then
    exit repeat
  end if
end repeat

return allFeeds
–>  
(*
{​​​​​{​​​​​​​author:"日本インタビュ新聞 Media-IR", ​​​​​​​sourceTitle:"日本インタビュ新聞 株式投資情報", ​​​​​​​title:"アライドレシスホールディングスは「継続企業の前提に関する注記」の記載を解消", ​​​​​​​link:"http://kabu-ir.com/article/448533521.html", ​​​​​​​pubDate:1.490787369E+12, ​​​​​​​description:"■返済期日が延長され、当面の資金繰りの安定化が図られる見込み アライドテレシスホールディングス<6835>(東2)は29日、「継続企業の前提に関する注記」の記載を解消することを発表した。 同社グループは、平成28年12月期連結会計年度で営業利益5億72百万円、当期純利益1億11百万円を計上した。しかし、営業活動によるキャッシュフロー4億6百万円に対し、連結会計年度末における金融機関からの有利子負債残高が74億94百万円と多額であり、平成29年6月30日に期間満了となるシンジケ..", ​​​​​​​sourceLink:"http://kabu-ir.com/"​​​​​}, ​​​​​{​​​​​​​author:"日本インタビュ新聞 Media-IR", ​​​​​​​sourceTitle:"日本インタビュ新聞 株式投資情報", ​​​​​​​title:"ケイティケイは今17年8月期第2四半期と通期業績予想の利益面での上方修正を発表", ​​​​​​​
*)

on getAFeeds(aNum)
  set reqURLStr to "https://api.apitore.com/api/32/feeds/design"
  
set accessToken to retAccessToken() of me —Access Token
  
set aRec to {access_token:accessToken, page:(aNum as string)}
  
set aURL to retURLwithParams(reqURLStr, aRec) of me
  
  
set aRes to callRestGETAPIAndParseResults(aURL) of me
  
  
set aRESCode to (responseCode of aRes) as integer
  
if aRESCode is not equal to 200 then return {false, false}
  
  
set aRESTres to (json of aRes) as record
  
  
set sentiRes to entries of aRESTres
  
set allNum to num of aRESTres
  
log allNum
  
  
return {sentiRes, allNum}
end getAFeeds

–GET methodのREST APIを呼ぶ
on callRestGETAPIAndParseResults(aURL)
  
  
set aRequest to current application’s NSMutableURLRequest’s requestWithURL:(current application’s |NSURL|’s URLWithString:aURL)
  
  
aRequest’s setHTTPMethod:"GET"
  
aRequest’s setCachePolicy:(current application’s NSURLRequestReloadIgnoringLocalCacheData)
  
aRequest’s setHTTPShouldHandleCookies:false
  
aRequest’s setTimeoutInterval:60
  
aRequest’s setValue:"application/json" forHTTPHeaderField:"Accept"
  
aRequest’s setValue:"gzip" forHTTPHeaderField:"Content-Encoding"
  
aRequest’s setValue:"Test AppleScript (gzip)" forHTTPHeaderField:"User-Agent"
  
  
set aRes to current application’s NSURLConnection’s sendSynchronousRequest:aRequest returningResponse:(reference) |error|:(missing value)
  
set resList to aRes as list
  
  
set bRes to contents of (first item of resList)
  
set resStr to current application’s NSString’s alloc()’s initWithData:bRes encoding:(current application’s NSUTF8StringEncoding)
  
  
set jsonString to current application’s NSString’s stringWithString:resStr
  
set jsonData to jsonString’s dataUsingEncoding:(current application’s NSUTF8StringEncoding)
  
set aJsonDict to current application’s NSJSONSerialization’s JSONObjectWithData:jsonData options:0 |error|:(missing value)
  
  
–Get Response Code & Header
  
set dRes to contents of second item of resList
  
if dRes is not equal to missing value then
    set resCode to (dRes’s statusCode()) as number
    
set resHeaders to (dRes’s allHeaderFields()) as record
  else
    set resCode to 0
    
set resHeaders to {}
  end if
  
  
return {json:aJsonDict, responseCode:resCode, responseHeader:resHeaders}
  
end callRestGETAPIAndParseResults

on retURLwithParams(aBaseURL, aRec)
  set aDic to current application’s NSMutableDictionary’s dictionaryWithDictionary:aRec
  
  
set aKeyList to (aDic’s allKeys()) as list
  
set aValList to (aDic’s allValues()) as list
  
set aLen to length of aKeyList
  
  
set qList to {}
  
repeat with i from 1 to aLen
    set aName to contents of item i of aKeyList
    
set aVal to contents of item i of aValList
    
set the end of qList to (current application’s NSURLQueryItem’s queryItemWithName:aName value:aVal)
  end repeat
  
  
set aComp to current application’s NSURLComponents’s alloc()’s initWithString:aBaseURL
  
aComp’s setQueryItems:qList
  
set aURL to (aComp’s |URL|()’s absoluteString()) as text
  
  
return aURL
end retURLwithParams

on retAccessToken()
  return "xxXXXxxX-XxXx-XXXX-xXXX-XXxXXxxXxxXx" –API Tore Access Token
end retAccessToken

★Click Here to Open This Script 

Posted in Network REST API | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

ゲーム情報サイト ごちゃまぜフィード

Posted on 3月 3, 2018 by Takaaki Naganoya

ApitoreのREST API「ゲーム情報サイト ごちゃまぜフィード」を呼び出して、さまざまなゲーム系サイトのNews Feedを一括で取得するAppleScriptです。

# Apitoreは2019年5月31日をもってサービスを終了

「ゲーム情報サイト ごちゃまぜフィード」は、30分に1回の頻度でRSSの更新を確認にいきます。REST APIで最新情報が取得できるオンラインクローラーです。以下のRSSをチェックしています。

・4Gamer.net 新着
・4Gamer.net 注目の記事のみ
・電撃オンライン
・doope!
・Game*Spark
・ゲームのはなし

本AppleScript利用のためには、Apitoreにサインアップしてアカウントを作成し、新規プロジェクトを作成(Test AppleScriptとか)。そこに、本APIを利用できるように登録し、「アクセストークン」を取得する必要があります。

アクセストークンを取得せずに掲載状態のまま本AppleScriptを実行してもエラーになります。

取得したアクセストークンを本AppleScript中のretAccessToken()ハンドラ内に記載し、実行してください。

AppleScript名:ゲーム情報サイト ごちゃまぜフィード
— Created 2016-10-27 by Takaaki Naganoya
— 2016 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"

set allFeeds to {}

repeat with i from 1 to 100
  set {aRes, maxNum} to getAFeeds(i) of me
  
  
if aRes = false then exit repeat
  
set maxNum to maxNum as number
  
set allFeeds to allFeeds & aRes
  
if (maxNum div 10) ≤ i then
    exit repeat
  end if
end repeat

return allFeeds
–>  
(*
​​​​​{​​​​​​​author:"okome", ​​​​​​​sourceTitle:"doope!", ​​​​​​​title:"Update:Bethesda Game Studiosが開発を手掛けたVaultシム「Fallout Shelter」がSteamに登場、リリースはまもなく", ​​​​​​​link:"http://doope.jp/2017/0363788.html", ​​​​​​​pubDate:1.490796335E+12, ​​​​​​​description:"UPDATE:3月29日23:05 新たにSteamにて本作の配信が開始されました。以下、更新前の本文となります。 今年2月にXbox OneとWin10向けのローンチを果たしたBethesda Game Studios [&#8230;]", ​​​​​​​sourceLink:"http://doope.jp"​​​​​}, ​​​​​{​​​​​​​author:"", ​​​​​​​sourceTitle:"電撃オンライン – 総合ゲーム情報サイト", ​​​​​​​title:"『9時間9人9の扉 善人シボウデス ダブルパック』PS4/PS Vita版の店舗別予約特典を紹介 ", ​​​​​​​link:"http://dengekionline.com/elem/000/001/493/1493825/", ​​​​​​​pubDate:1.490796071E+12, ​​​​​​​description:"<p>『ZERO ESCAPE 9時間9人9の扉 善人シボウデス ダブルパック』のPS4/PS Vita版の店舗別予約特典ではオリジナルステッカーなど登場しています。</p>", ​​​​​​​sourceLink:"http://dengekionline.com/"​​​​​}
*)

on getAFeeds(aNum)
  set reqURLStr to "https://api.apitore.com/api/33/feeds/game"
  
set accessToken to retAccessToken() of me —Access Token
  
set aRec to {access_token:accessToken, page:(aNum as string)}
  
set aURL to retURLwithParams(reqURLStr, aRec) of me
  
  
set aRes to callRestGETAPIAndParseResults(aURL) of me
  
  
set aRESCode to (responseCode of aRes) as integer
  
if aRESCode is not equal to 200 then return {false, false}
  
  
set aRESTres to (json of aRes) as record
  
  
set sentiRes to entries of aRESTres
  
set allNum to num of aRESTres
  
log allNum
  
  
return {sentiRes, allNum}
end getAFeeds

–GET methodのREST APIを呼ぶ
on callRestGETAPIAndParseResults(aURL)
  
  
set aRequest to current application’s NSMutableURLRequest’s requestWithURL:(current application’s |NSURL|’s URLWithString:aURL)
  
  
aRequest’s setHTTPMethod:"GET"
  
aRequest’s setCachePolicy:(current application’s NSURLRequestReloadIgnoringLocalCacheData)
  
aRequest’s setHTTPShouldHandleCookies:false
  
aRequest’s setTimeoutInterval:60
  
aRequest’s setValue:"application/json" forHTTPHeaderField:"Accept"
  
aRequest’s setValue:"gzip" forHTTPHeaderField:"Content-Encoding"
  
aRequest’s setValue:"Test AppleScript (gzip)" forHTTPHeaderField:"User-Agent"
  
  
set aRes to current application’s NSURLConnection’s sendSynchronousRequest:aRequest returningResponse:(reference) |error|:(missing value)
  
set resList to aRes as list
  
  
set bRes to contents of (first item of resList)
  
set resStr to current application’s NSString’s alloc()’s initWithData:bRes encoding:(current application’s NSUTF8StringEncoding)
  
  
set jsonString to current application’s NSString’s stringWithString:resStr
  
set jsonData to jsonString’s dataUsingEncoding:(current application’s NSUTF8StringEncoding)
  
set aJsonDict to current application’s NSJSONSerialization’s JSONObjectWithData:jsonData options:0 |error|:(missing value)
  
  
–Get Response Code & Header
  
set dRes to contents of second item of resList
  
if dRes is not equal to missing value then
    set resCode to (dRes’s statusCode()) as number
    
set resHeaders to (dRes’s allHeaderFields()) as record
  else
    set resCode to 0
    
set resHeaders to {}
  end if
  
  
return {json:aJsonDict, responseCode:resCode, responseHeader:resHeaders}
  
end callRestGETAPIAndParseResults

on retURLwithParams(aBaseURL, aRec)
  set aDic to current application’s NSMutableDictionary’s dictionaryWithDictionary:aRec
  
  
set aKeyList to (aDic’s allKeys()) as list
  
set aValList to (aDic’s allValues()) as list
  
set aLen to length of aKeyList
  
  
set qList to {}
  
repeat with i from 1 to aLen
    set aName to contents of item i of aKeyList
    
set aVal to contents of item i of aValList
    
set the end of qList to (current application’s NSURLQueryItem’s queryItemWithName:aName value:aVal)
  end repeat
  
  
set aComp to current application’s NSURLComponents’s alloc()’s initWithString:aBaseURL
  
aComp’s setQueryItems:qList
  
set aURL to (aComp’s |URL|()’s absoluteString()) as text
  
  
return aURL
end retURLwithParams

on retAccessToken()
  return "xxXXXxxX-XxXx-XXXX-xXXX-XXxXXxxXxxXx" –API Tore Access Token
end retAccessToken

★Click Here to Open This Script 

Posted in Network REST API | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

Post navigation

  • Older posts
  • Newer posts

電子書籍(PDF)をオンラインストアで販売中!

Google Search

Popular posts

  • macOS 13, Ventura(継続更新)
  • アラートダイアログ上にWebViewで3Dコンテンツを表示(WebGL+three.js)v3
  • Xcode 14.2でAppleScript App Templateを復活させる
  • macOS 13 TTS Voice環境に変更
  • UI Browserがgithub上でソース公開され、オープンソースに
  • 2022年に書いた価値あるAppleScript
  • ChatGPTで文章のベクトル化(Embedding)
  • iWork 12.2がリリースされた
  • ChatGPTでchatに対する応答文を取得
  • macOS 13対応アップデート:AppleScript実践的テクニック集(1)GUI Scripting
  • 新発売:CotEditor Scripting Book with AppleScript
  • macOS 14, Sonoma
  • macOS 13でNSNotFoundバグふたたび
  • Finderの隠し命令openVirtualLocationが発見される
  • あのコン過去ログビューワー(暫定版)
  • macOS 13.1アップデートでスクリプトエディタの挙動がようやくまともに
  • Dockアイコンにプログレスバーを追加 v3
  • クリップボードに入った書式つきテキストをプレーン化する「PlainerText」
  • CotEditor v4.4.1+macOS 13の組み合わせで発生している問題
  • 新発売:Mail.app Scripting Book with AppleScript

Tags

10.11savvy (1101) 10.12savvy (1242) 10.13savvy (1390) 10.14savvy (586) 10.15savvy (434) 11.0savvy (278) 12.0savvy (190) 13.0savvy (69) CotEditor (61) Finder (48) iTunes (19) Keynote (99) NSAlert (60) NSArray (51) NSBezierPath (18) NSBitmapImageRep (20) NSBundle (20) NSButton (34) NSColor (51) NSDictionary (27) NSFileManager (23) NSFont (18) NSImage (41) NSJSONSerialization (21) NSMutableArray (62) NSMutableDictionary (21) NSPredicate (36) NSRunningApplication (56) NSScreen (30) NSScrollView (22) NSString (117) NSURL (97) NSURLRequest (23) NSUTF8StringEncoding (30) NSView (33) NSWorkspace (20) Numbers (57) Pages (38) Safari (41) Script Editor (21) WKUserContentController (21) WKUserScript (20) WKUserScriptInjectionTimeAtDocumentEnd (18) WKWebView (23) WKWebViewConfiguration (22)

カテゴリー

  • 2D Bin Packing
  • 3D
  • AirDrop
  • AirPlay
  • Animation
  • AppleScript Application on Xcode
  • beta
  • Bluetooth
  • Books
  • boolean
  • bounds
  • Bug
  • Calendar
  • call by reference
  • Clipboard
  • Code Sign
  • Color
  • Custom Class
  • dialog
  • drive
  • exif
  • file
  • File path
  • filter
  • folder
  • Font
  • Font
  • GAME
  • geolocation
  • GUI
  • GUI Scripting
  • Hex
  • History
  • How To
  • iCloud
  • Icon
  • Image
  • Input Method
  • Internet
  • iOS App
  • JavaScript
  • JSON
  • JXA
  • Keychain
  • Keychain
  • Language
  • Library
  • list
  • Locale
  • Machine Learning
  • Map
  • Markdown
  • Menu
  • Metadata
  • MIDI
  • MIME
  • Natural Language Processing
  • Network
  • news
  • Noification
  • Notarization
  • Number
  • Object control
  • OCR
  • OSA
  • PDF
  • Peripheral
  • PRODUCTS
  • QR Code
  • Raw AppleEvent Code
  • Record
  • rectangle
  • recursive call
  • regexp
  • Release
  • Remote Control
  • Require Control-Command-R to run
  • REST API
  • Review
  • RTF
  • Sandbox
  • Screen Saver
  • Script Libraries
  • sdef
  • search
  • Security
  • selection
  • shell script
  • Shortcuts Workflow
  • Sort
  • Sound
  • Spellchecker
  • Spotlight
  • SVG
  • System
  • Tag
  • Telephony
  • Text
  • Text to Speech
  • timezone
  • Tools
  • Update
  • URL
  • UTI
  • Web Contents Control
  • WiFi
  • XML
  • XML-RPC
  • イベント(Event)
  • 未分類

アーカイブ

  • 2023年11月
  • 2023年10月
  • 2023年9月
  • 2023年8月
  • 2023年7月
  • 2023年6月
  • 2023年5月
  • 2023年4月
  • 2023年3月
  • 2023年2月
  • 2023年1月
  • 2022年12月
  • 2022年11月
  • 2022年10月
  • 2022年9月
  • 2022年8月
  • 2022年7月
  • 2022年6月
  • 2022年5月
  • 2022年4月
  • 2022年3月
  • 2022年2月
  • 2022年1月
  • 2021年12月
  • 2021年11月
  • 2021年10月
  • 2021年9月
  • 2021年8月
  • 2021年7月
  • 2021年6月
  • 2021年5月
  • 2021年4月
  • 2021年3月
  • 2021年2月
  • 2021年1月
  • 2020年12月
  • 2020年11月
  • 2020年10月
  • 2020年9月
  • 2020年8月
  • 2020年7月
  • 2020年6月
  • 2020年5月
  • 2020年4月
  • 2020年3月
  • 2020年2月
  • 2020年1月
  • 2019年12月
  • 2019年11月
  • 2019年10月
  • 2019年9月
  • 2019年8月
  • 2019年7月
  • 2019年6月
  • 2019年5月
  • 2019年4月
  • 2019年3月
  • 2019年2月
  • 2019年1月
  • 2018年12月
  • 2018年11月
  • 2018年10月
  • 2018年9月
  • 2018年8月
  • 2018年7月
  • 2018年6月
  • 2018年5月
  • 2018年4月
  • 2018年3月
  • 2018年2月

https://piyomarusoft.booth.pm/items/301502

メタ情報

  • ログイン
  • 投稿フィード
  • コメントフィード
  • WordPress.org

Forum Posts

  • 人気のトピック
  • 返信がないトピック

メタ情報

  • ログイン
  • 投稿フィード
  • コメントフィード
  • WordPress.org
Proudly powered by WordPress
Theme: Flint by Star Verte LLC