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

カテゴリー: Network

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

ニュースサイト ごちゃまぜフィード

Posted on 3月 3, 2018 by Takaaki Naganoya

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

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

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

・Huffington Post Japan
・IBTimes エンタメ・スポーツ
・IBTimes グローバル
・IBTimes マーケット
・IBTimes ライフ
・IBTimes 企業
・IBTimes 経済
・IBTimes IT・サイエンス
・ダイヤモンド・オンライン
・ビジネスジャーナル
・東洋経済オンライン
・毎日新聞
・CNN

本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"

getNewsFeed() of me

on getNewsFeed()
  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
end getNewsFeed

on getAFeeds(aNum)
  set reqURLStr to "https://api.apitore.com/api/34/feeds/news"
  
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:"Ittousai", ​​​​​​​sourceTitle:"Engadget Japanese RSS Feed", ​​​​​​​title:" 速報:サムスンGalaxy S8発表イベント UNPACKED 2017 (ライブ更新ページ)
", ​​​​​​​link:"http://japanese.engadget.com/2017/03/29/galaxy-s8-unpacked-2017/", ​​​​​​​pubDate:1.49079606E+12, ​​​​​​​description:"<p> <img src=\"http://o.aolcdn.com/hss/storage/midas/a009a6b57896291f7e66fe091c6bdf94/205070326/unbox.png\" /> </p>", ​​​​​​​sourceLink:"http://japanese.engadget.com/rss.xml"​​​​​}, ​​​​​
*)

on getAFeeds(aNum)
  set reqURLStr to "https://api.apitore.com/api/35/feeds/tech"
  
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

RSS2JSON

Posted on 3月 3, 2018 by Takaaki Naganoya

ApitoreのREST API「RSS2JSON」を呼び出して、さまざまな種類のRSS(RSS0.9、RSS1.0、RSS2.0、Atomなど)をJSONに変換し、AppleScriptのrecord(record in list)オブジェクトに変換するAppleScriptです。

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

Language-Detectionは、テキストの言語判定を行います。検索機能に言語の絞り込みを付けたい場合や、テキストに対して言語別の処理をしたい場合に利用します。

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

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

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

AppleScript名:RSS2JSON
— Created 2016-10-27 by Takaaki Naganoya
— 2016 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
–use keychainLib : script "keychainLib"

set rssURL to "http://piyocast.com/as/feed/"

set reqURLStr to "https://api.apitore.com/api/28/rome/rss2json"
–set accessToken to getPasswordForAccount("apitore API Key", "maro@piyocast.com") of keychainLib
set accessToken to retAccessToken() of me —Access Token

set aRec to {access_token:accessToken, rss:rssURL}
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 list of string or string –as anything
–> {|description|:"Useful & Practical AppleScript archive", author:missing value, link:"http://piyocast.com/as", |log|:"", pubDate:1.520068773E+12, title:"AppleScript Hole", entries:{{author:"Takaaki Naganoya", title:"(GET)国土地理院APIで現在位置の標高を取得する", pubDate:1.519998541E+12, |description|:"<p>国土地理院のREST API「標高API」を呼んで、現在位置の標高を取得するAppleScriptです。 現在位置の取得のためにMac本体のWiFiがオンになっている必要があります。 AppleScript名:(GET) &#8230; <a href=\"http://piyocast.com/as/archives/2545\" class=\"more-link\"><span class=\"screen-reader-text\">\"(GET)国土地理院APIで現在位置の標高を取得する\"の</span>続きを読む</a></p><p>投稿 <a rel=\"nofollow\" href=\"http://piyocast.com/as/archives/2545\">(GET)国土地理院APIで現在位置の標高を取得する</a> は <a rel=\"nofollow\" href=\"http://piyocast.com/as\">AppleScript Hole</a> に最初に表示されました。</p>", link:"http://piyocast.com/as/archives/2545"}, ….

–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

(GET)国土地理院APIで現在位置の標高を取得する

Posted on 3月 2, 2018 by Takaaki Naganoya

国土地理院のREST API「標高API」を呼んで、現在位置の標高を取得するAppleScriptです。

現在位置の取得のためにMac本体のWiFiがオンになっている必要があります。

AppleScript名:(GET)国土地理院APIで現在位置の標高を取得する
— Created 2016-10-29 by Takaaki Naganoya
— 2016 Piyomaru Software
use AppleScript version "2.5"
use scripting additions
use framework "Foundation"
use framework "CoreLocation"
use framework "CoreWLAN"
–http://maps.gsi.go.jp/development/api.html

property locationManager : missing value
property curLatitude : 0
property curLongitude : 0

set reqURLStr to "http://cyberjapandata2.gsi.go.jp/general/dem/scripts/getelevation.php"

–現在地の緯度、経度情報を取得する
set {aLat, aLong} to getCurrentLocation() of me

set aRec to {lon:aLong as string, lat:aLat as string, outtype:"JSON"}
set aURL to retURLwithParams(reqURLStr, aRec) of me
set aRes to callRestGETAPIAndParseResults(aURL) of me

set aRESTres to (json of aRes) as record
return aRESTres
–>  {​​​​​hsrc:"5m(レーザ)", ​​​​​elevation:40.4​​​}

–set aRESCode to responseCode of aRes
–>  200

–set aRESHeader to responseHeader of aRes
–>  {​​​​​Server:"Apache/2.4.10 (Debian) PHP/5.6.19", ​​​​​Content-Type:"application/json; charset=utf-8", ​​​​​X-Powered-By:"PHP/5.6.19", ​​​​​Connection:"Keep-Alive", ​​​​​Access-Control-Allow-Origin:"*", ​​​​​Date:"Sat, 29 Oct 2016 10:53:14 GMT", ​​​​​Content-Encoding:"gzip", ​​​​​Content-Length:"71", ​​​​​Keep-Alive:"timeout=5, max=100", ​​​​​Vary:"Accept-Encoding"​​​}

–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"
  
  
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 urlencodeStr(aStr)
  set aString to current application’s NSString’s stringWithString:aStr
  
set aString to (aString’s stringByAddingPercentEncodingWithAllowedCharacters:(current application’s NSCharacterSet’s URLQueryAllowedCharacterSet())) as text
  
return aString
end urlencodeStr

on getCurrentLocation()
  activeWiFiPower() of me
  
  
set locationManager to current application’s CLLocationManager’s alloc()’s init()
  
  
set locE to locationManager’s locationServicesEnabled()
  
if (locE as boolean) = true then
    locationManager’s setDelegate:me
    
locationManager’s setDesiredAccuracy:(current application’s kCLLocationAccuracyNearestTenMeters)
    
locationManager’s setDistanceFilter:500
    
locationManager’s startUpdatingLocation()
  else
    return false –error in init
  end if
  
  
set hitF to false
  
repeat 3000 times
    if {curLatitude, curLongitude} is not equal to {0, 0} then
      set hitF to true
      
exit repeat
    end if
    
delay 0.01
  end repeat
  
  
if hitF = false then return false
  
return {curLatitude, curLongitude}
  
end getCurrentLocation

—-以下、curLocationLibの内容

on locationManager:manager didUpdateLocations:locations
  
  
–Listing 1-3 Processing an incoming location event
  
set location to (locations’s lastObject())
  
set eventDate to (location’s timestamp())
  
set howRecent to (eventDate’s timeIntervalSinceNow())
  
  
–Calc ABS
  
set howRecent to howRecent as real
  
set howRecent to absNum(howRecent)
  
log howRecent
  
  
if howRecent < 15.0 then
    
    
set alt to location’s altitude
    
–>  (NSNumber) 46.356517791748
    
    
set aSpeed to location’s speed
    
–>  (NSNumber) -1.0
    
    
set aCourse to location’s course –North:0, East:90, South:180, West:270
    
–>  (NSNumber) -1.0
    
    
–By Shane Stanley
    
set theDescription to location’s |description|()
    
–> (NSString) "<+35.xxxxx,+139.xxxxxx> +/- 65.00m (speed -1.00 mps / course -1.00) @ 2015/03/04 8時56分41秒 日本標準時"
    
    
set anNSScanner to current application’s NSScanner’s scannerWithString:theDescription
    
anNSScanner’s setCharactersToBeSkipped:(current application’s NSCharacterSet’s characterSetWithCharactersInString:"<,")
    
set {theResult, aLat} to anNSScanner’s scanDouble:(reference)
    
set {theResult, aLng} to anNSScanner’s scanDouble:(reference)
    
    
copy {aLat, aLng} to {my curLatitude, my curLongitude}
    
  else
    log {"stopUpdatingLocation"}
    
locationManager’s stopUpdatingLocation()
  end if
  
end locationManager:didUpdateLocations:

on locationManager:anCLLocationManager didFailWithError:anNSError
  display dialog (anNSError’s localizedDescription() as text)
end locationManager:didFailWithError:

on absNum(aNum)
  if aNum > 0 then
    return aNum
  else
    return (aNum * -1)
  end if
end absNum

—Activate WiFi Power

on activeWiFiPower()
  set dName to getWiFiDeviceName() of me
  
set aInterface to current application’s CWInterface’s alloc()’s initWithInterfaceName:dName
  
set aPowerStat to (aInterface’s powerOn()) as boolean
  
if aPowerStat = false then
    set wRes to aInterface’s setPower:true |error|:(missing value)
    
if wRes = missing value then
      error "Can’t power on WiFi Interface."
    end if
  end if
end activeWiFiPower

–指定ハードウェアポートのデバイス名を取得する
on getWiFiDeviceName()
  set v2 to system attribute "sys2" –> 4
  
if v2 ≤ 6 then
    set hardWareName to "AirPort" –Under Mac OS X 10.6.8
    
set aMesStr to "Current AirPort Network: "
  else if v2 ≥ 7 then
    set hardWareName to "Wi-Fi" –Mac OS X 10.7 or later
    
set aMesStr to "Current Wi-Fi Network: "
  else
    display dialog "error"
  end if
  
  
set dName to getHardwareDeviceName(hardWareName) of me
  
return dName
end getWiFiDeviceName

–指定ハードウェアポートのデバイス名を取得する
on getHardwareDeviceName(targName)
  set sRes to do shell script "/usr/sbin/networksetup -listallhardwareports"
  
log sRes
  
set sList to paragraphs of sRes
  
set s1List to items 2 thru -1 of sList
  
  
set s2List to {}
  
repeat with i in s1List
    set j to contents of i
    
if j is equal to "VLAN Configurations" then
      exit repeat
    end if
    
set the end of s2List to j
  end repeat
  
  
–ネットワークポート関連のレコードを作成
  
set s3List to {}
  
set aLen to length of s2List
  
repeat with i from 1 to aLen by 4
    set a1Item to contents of item i of s2List
    
set a1Item to repChar(a1Item, "Hardware Port: ", "") of me
    
    
set a2Item to contents of item (i + 1) of s2List
    
set a2Item to repChar(a2Item, "Device: ", "") of me
    
    
set a3Item to contents of item (i + 2) of s2List
    
set a3Item to repChar(a3Item, "Ethernet Address: ", "") of me
    
    
set the end of s3List to {hardwarePort:a1Item, device:a2Item, ethernetAddress:a3Item}
  end repeat
  
  
repeat with i in s3List
    set j1 to hardwarePort of i
    
set j2 to device of i
    
if j1 is equal to targName then
      return j2
    end if
  end repeat
  
  
return ""
  
end getHardwareDeviceName

–文字置換ルーチン
on repChar(origText, targStr, repStr)
  set {txdl, AppleScript’s text item delimiters} to {AppleScript’s text item delimiters, targStr}
  
set temp to text items of origText
  
set AppleScript’s text item delimiters to repStr
  
set res to temp as text
  
set AppleScript’s text item delimiters to txdl
  
return res
end repChar

★Click Here to Open This Script 

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

じゃらんAPIで宿情報を検索する

Posted on 3月 2, 2018 by Takaaki Naganoya

じゃらんの宿表示 Web API経由でリクエストした宿泊情報を返すAppleScriptです。

利用のためには、じゃらんにアカウント登録を行い、アクセスキーを取得。取得したキーをretAccessKey()ハンドラ中に記入することが必要です。

AppleScript名:じゃらんAPIで宿情報を検索する
— Created 2016-11-20 by Takaaki Naganoya
— 2016 Piyomaru Software
use AppleScript version "2.5"
use scripting additions
use framework "Foundation"

–http://www.jalan.net/jw/jwp0100/jww0102.do

property dictStack : missing value — stack to hold array of dictionaries
property textInProgress : "" — string to collect text as it is found
property anError : missing value — if we get an error, store it here

set reqURLStr to "http://jws.jalan.net/APIAdvance/HotelSearch/V1/"

set aKey to retAccessKey() of me

–横浜みなとみらい地区で2016年11月21日宿泊の1室、大人2名で宿泊可能な施設
set aRec to {|key|:aKey, s_area:"140202", stay_date:"20180421", room_count:"1", adult_num:"2", sc_num:"0"}
–日付を「過去」に設定すると結果が返ってこない点に注意

set aURL to retURLwithParams(reqURLStr, aRec) of me
set aRes to callRestGETAPIAndParseResults(aURL) of me
set aRESCode to responseCode of aRes
if aRESCode is not equal to 200 then return false
set aRESHeader to responseHeader of aRes
set aXMLres to (xml of aRes)
set aNameRes to (aXMLres’s valueForKeyPath:"Results.Hotel.HotelName.contents") as list
–>  {"ホテルルートイン横浜馬車道", "ホテル エディット 横濱", "ホテル アイマーレ 横浜伊勢佐木町", "ホテルパセラの森 横浜関内", "横浜 マンダリンホテル", "ホテルモントレ横浜", "ヨコハマホステルヴィレッジ林会館", "スターホテル横浜", "アパホテル<横浜関内>", "リゾートカプセル桜木町(BBHホテルグループ)"}

–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"
  
  
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 aXmlRec to my makeRecordWithXML:resStr
  
  
  
–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 {xml:aXmlRec, 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 retAccessKey()
  return "xxxXXXXXXXXXxX" –じゃらんAPIキー
end retAccessKey

on urlencodeStr(aStr)
  set aString to current application’s NSString’s stringWithString:aStr
  
set aString to (aString’s stringByAddingPercentEncodingWithAllowedCharacters:(current application’s NSCharacterSet’s URLQueryAllowedCharacterSet())) as text
  
return aString
end urlencodeStr

——–XMLParse Lib

on makeRecordWithXML:xmlString
  set my dictStack to current application’s NSMutableArray’s array() — empty mutable array
  
set anEmpty to current application’s NSMutableDictionary’s |dictionary|()
  (
my dictStack)’s addObject:anEmpty — add empty mutable dictionary
  
set my textInProgress to current application’s NSMutableString’s |string|() — empty mutable string
  
  
set anNSString to current application’s NSString’s stringWithString:xmlString
  
set theData to anNSString’s dataUsingEncoding:(current application’s NSUTF8StringEncoding)
  
  
set theNSXMLParser to current application’s NSXMLParser’s alloc()’s initWithData:theData
  
  
theNSXMLParser’s setDelegate:me
  
  
set theResult to theNSXMLParser’s parse()
  
if theResult then — went OK, get first item on stack
    return ((my dictStack)’s firstObject()) –as record
  else
    error (my anError’s localizedDescription() as text)
  end if
end makeRecordWithXML:

— this is an XML parser delegate method. Called when new element found
on parser:anNSXMLParser didStartElement:elementName namespaceURI:aString qualifiedName:qName attributes:aRecord
  set parentDict to my dictStack’s lastObject()
  
set childDict to current application’s NSMutableDictionary’s |dictionary|()
  
if aRecord’s |count|() > 0 then
    childDict’s setValue:aRecord forKey:"attributes"
  end if
  
  
set existingValue to parentDict’s objectForKey:elementName
  
  
if existingValue is not missing value then
    if (existingValue’s isKindOfClass:(current application’s NSMutableArray)) as boolean then
      set theArray to existingValue
    else
      set theArray to current application’s NSMutableArray’s arrayWithObject:existingValue
      
parentDict’s setObject:theArray forKey:elementName
    end if
    
    
theArray’s addObject:childDict
  else
    parentDict’s setObject:childDict forKey:elementName
  end if
  
  (
my dictStack)’s addObject:childDict
end parser:didStartElement:namespaceURI:qualifiedName:attributes:

— this is an XML parser delegate method. Called at the end of an element
on parser:anNSXMLParser didEndElement:elementName namespaceURI:aString qualifiedName:qName
  if my textInProgress’s |length|() > 0 then
    set dictInProgress to my dictStack’s lastObject()
    
dictInProgress’s setObject:textInProgress forKey:"contents"
    
set my textInProgress to current application’s NSMutableString’s |string|()
  end if
  
  
my dictStack’s removeLastObject()
end parser:didEndElement:namespaceURI:qualifiedName:

— this is an XML parser delegate method. Called when string is found. May be called repeatedly
on parser:anNSXMLParser foundCharacters:aString
  if (aString’s stringByTrimmingCharactersInSet:(current application’s NSCharacterSet’s whitespaceAndNewlineCharacterSet()))’s |length|() > 0 then
    (my textInProgress)’s appendString:aString
  end if
end parser:foundCharacters:

— this is an XML parser delegate method. Called when there’s an error
on parser:anNSXMLParser parseErrorOccurred:anNSError
  set my anError to anNSError
end parser:parseErrorOccurred:

★Click Here to Open This Script 

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

Language Detection -53 languages- langdetect

Posted on 3月 2, 2018 by Takaaki Naganoya

ApitoreのREST API「Language Detection -53 languages-」を呼び出して、指定したテキストの言語(日本語とか英語とか)を推定するAppleScriptです。

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

Language-Detectionは、テキストの言語判定を行います。検索機能に言語の絞り込みを付けたい場合や、テキストに対して言語別の処理をしたい場合に利用します。

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

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

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

本REST APIを評価した感想は、言語判定可能なテキスト分量がやや長め(俳句や短歌程度だとダメ。Twitter投稿ぐらいの文字数があれば大丈夫)でありつつ、APIに突っ込める文字の長さに制限があるため、対象のテキストをすべて渡すのではなく、テキストの一部を抜粋して評価を行うのが適しているように思われました。

AppleScript名:Language Detection -53 languages- langdetect
— Created 2016-10-27 by Takaaki Naganoya
— 2016 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"

set targStr to "This is a pen. This is an apple. This is applepen."

set reqURLStr to "https://api.apitore.com/api/22/langdetect/get"
set accessToken to retAccessToken() of me

set aRec to {access_token:accessToken, |text|:targStr}
set aURL to retURLwithParams(reqURLStr, aRec) of me

set aRes to callRestGETAPIAndParseResults(aURL) of me
set aRESCode to (responseCode of aRes)
set aRESTres to (json of aRes)

return aRESTres 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 setCachePolicy:(current application’s NSURLRequestReloadIgnoringLocalCacheData)
  
aRequest’s setHTTPShouldHandleCookies:false
  
aRequest’s setTimeoutInterval:60
  
aRequest’s setValue:"application/json" 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 callRestGETAPIAndParseResults

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

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

★Click Here to Open This Script 

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

Wikipediaの任意の項目の本文に入っているURLがリンク切れになっていないかどうかチェック v2

Posted on 2月 27, 2018 by Takaaki Naganoya
AppleScript名:Wikipediaの任意の項目の本文に入っているURLがリンク切れになっていないかどうかチェック v2
— Created 2017-03-29 by Takaaki Naganoya
— 2017 Piyomaru Software
use AppleScript version "2.5"
use scripting additions
use framework "Foundation"
–https://www.mediawiki.org/wiki/API:Main_page/ja

set aKeyword to "AppleScript"

set aStr to getBody(aKeyword) of me

–ものすごく大甘な転送検出
if aStr begins with "#転送" then
  set bStr to detectForwarding(aStr) of me
  
–転送先のキーワードで再度処理
  
set aStr to getBody(bStr) of me
end if

set aRes to extractURLsAndValidateThem(aStr) of me
–>  {​​​​​safeURL:27, ​​​​​forwardedURL:19, ​​​​​brokenURL:0, ​​​​​brokenURLs:{}​​​}

on detectForwarding(aStr)
  if aStr begins with "#転送" then
    set aRes to parseByDelim(aStr, {"[[", "]]"}) of me
    
–>  {​​​​​"#転送 ", ​​​​​"MacOS", ​​​​​""​​​}
    
return item 2 of aRes –エラーチェックはやっていない。大甘
  else
    return aStr
  end if
end detectForwarding

on extractURLsAndValidateThem(aStr)
  set urlList to extractLinksFromNaturalText(aStr) of me as list
  
  
set okList to {}
  
set fwList to {}
  
set ngList to {}
  
  
repeat with i in urlList
    set j to contents of i
    
set aTarg to j’s absoluteString() as string
    
set {exRes, headerRes, aData, resURL} to checkURLResourceExistence(j, 30) of me
    
    
if exRes = false then
      –URL取得時に連続するスペースをURLの一部として誤解して取得するケースがあるので、クリーニングしてリトライ  
      
set bStr to cleaningURLStr(aTarg) of me
      
      
if bStr = false then
        –クリーニング対象文字列がなかった。本当にダメだった
        
set the end of ngList to aTarg
      else
        –リトライ(タイムアウト条件も緩和)
        
set bURL to (current application’s |NSURL|’s URLWithString:bStr)
        
set {exRes, headerRes, aData, resURL} to checkURLResourceExistence(bURL, 60) of me
        
        
if exRes = false then
          –やっぱりダメでした。ごめんなさい(T_T)
          
set the end of ngList to bStr
        else if resURL is not equal to bStr then
          –URLがForwardされていた
          
set the end of fwList to bStr
        else
          –OKだった(リクエストしたURLとリプライURLが同じ、そこに何かの同名のファイルが存在した)
          
set the end of okList to bStr
        end if
        
      end if
      
    else if resURL is not equal to aTarg then
      –URLがForwardされていた
      
set the end of fwList to aTarg
    else
      –OKだった(リクエストしたURLとリプライURLが同じ、そこに何かの同名のファイルが存在した)
      
set the end of okList to aTarg
    end if
    
  end repeat
  
  
set resList to {safeURL:length of okList, forwardedURL:length of fwList, brokenURL:length of ngList, brokenURLs:ngList}
  
return resList
end extractURLsAndValidateThem

on cleaningURLStr(aStr)
  set anOffset to offset of "%20" in aStr
  
if anOffset = 0 then return false
  
set bStr to text 1 thru (anOffset – 1) of aStr
  
return bStr
end cleaningURLStr

on getBody(aKeyword)
  –set reqURLStr to "https://en.wikipedia.org/w/api.php"–English Version
  
set reqURLStr to "https://jp.wikipedia.org/w/api.php" –Japanese Version
  
  
set aRec to {action:"query", titles:aKeyword, |prop|:"revisions", rvprop:"content", |format|:"json"}
  
–set aRec to {action:"query", titles:"AppleScript|Mac OS X|Objective-C", |prop|:"revisions", rvprop:"content", |format|:"json"}
  
set aURL to retURLwithParams(reqURLStr, aRec) of me
  
set aRes to callRestGETAPIAndParseResults(aURL) of me
  
  
set aRESTres to (json of aRes)
  
–> {query:{pages:{2954:{pageid:2954, title:"AppleScript", revisions:{{contentformat:"text/x-wiki", *:"{{Infobox プログラミング言語|名前 = AppleScript ……., contentmodel:"wikitext"}}, ns:0}}}, batchcomplete:""}
  
  
–最初にヒットしたものだけを返す(同じ名前の項目が複数存在した場合でも)
  
set aRes to (aRESTres’s valueForKeyPath:"query.pages")
  
set aKeyStr to (aRes’s allKeys()’s firstObject()) as string
  
set aKeyPath to aKeyStr & ".revisions.*"
  
  
set aBody to (aRes’s valueForKeyPath:aKeyPath)’s firstObject() as string
  
return aBody
end getBody

–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"
  
  
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 urlencodeStr(aStr)
  set aString to current application’s NSString’s stringWithString:aStr
  
set aString to (aString’s stringByAddingPercentEncodingWithAllowedCharacters:(current application’s NSCharacterSet’s URLQueryAllowedCharacterSet())) as text
  
return aString
end urlencodeStr

— 指定URLにファイル(画像など)が存在するかチェック
–> {存在確認結果(boolean), レスポンスヘッダー(NSDictionary), データ(NSData), 最終的なURLの文字列}
on checkURLResourceExistence(aURL, timeOutSec as real)
  set aRequest to (current application’s NSURLRequest’s requestWithURL:aURL cachePolicy:(current application’s NSURLRequestUseProtocolCachePolicy) timeoutInterval:timeOutSec)
  
set aRes to (current application’s NSURLConnection’s sendSynchronousRequest:aRequest returningResponse:(reference) |error|:(missing value))
  
  
set dRes to (first item of (aRes as list))
  
set bRes to (second item of (aRes as list))
  
  
  
if bRes = missing value then
    set hRes to {}
    
set aResCode to -1 –error
    
return {false, hRes, dRes, missing value}
  else
    set resURL to ((|URL| of bRes)’s |absoluteURL|()’s absoluteString()) as string
  end if
  
–set resURL to ((|URL| of bRes)’s |absoluteURL|()’s absoluteString()) as string
  
  
if bRes is not equal to missing value then
    set hRes to (bRes’s allHeaderFields())
    
set aResCode to (bRes’s statusCode()) as integer
  else
    set hRes to {}
    
set aResCode to -1 –error
  end if
  
  
return {(aResCode = 200), hRes, dRes, resURL}
end checkURLResourceExistence

on extractLinksFromNaturalText(aString)
  set anNSString to current application’s NSString’s stringWithString:aString
  
  
set {theDetector, theError} to current application’s NSDataDetector’s dataDetectorWithTypes:(current application’s NSTextCheckingTypeLink) |error|:(reference)
  
  
set theMatches to theDetector’s matchesInString:anNSString options:0 range:{0, anNSString’s |length|()}
  
set theResults to theMatches’s valueForKey:"URL"
  
  
return theResults as list
end extractLinksFromNaturalText

on parseByDelim(aData, aDelim)
  set curDelim to AppleScript’s text item delimiters
  
set AppleScript’s text item delimiters to aDelim
  
set dList to text items of aData
  
set AppleScript’s text item delimiters to curDelim
  
return dList
end parseByDelim

★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
  • UI Browserがgithub上でソース公開され、オープンソースに
  • macOS 13 TTS Voice環境に変更
  • Xcode 14.2でAppleScript App Templateを復活させる
  • 2022年に書いた価値あるAppleScript
  • ChatGPTで文章のベクトル化(Embedding)
  • 新発売:AppleScriptからSiriを呼び出そう!
  • iWork 12.2がリリースされた
  • 従来と異なるmacOS 13の性格?
  • 新発売:CotEditor Scripting Book with AppleScript
  • macOS 13対応アップデート:AppleScript実践的テクニック集(1)GUI Scripting
  • AS関連データの取り扱いを容易にする(はずの)privateDataTypeLib
  • macOS 13でNSNotFoundバグふたたび
  • macOS 12.5.1、11.6.8でFinderのselectionでスクリーンショット画像をopenできない問題
  • ChatGPTでchatに対する応答文を取得
  • 新発売:iWork Scripting Book with AppleScript
  • Finderの隠し命令openVirtualLocationが発見される
  • macOS 13.1アップデートでスクリプトエディタの挙動がようやくまともに
  • あのコン過去ログビューワー(暫定版)

Tags

10.11savvy (1101) 10.12savvy (1242) 10.13savvy (1390) 10.14savvy (586) 10.15savvy (434) 11.0savvy (277) 12.0savvy (185) 13.0savvy (55) CotEditor (60) Finder (47) iTunes (19) Keynote (98) 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 (56) Pages (37) Safari (41) Script Editor (20) 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年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