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

月: 2018年3月

file URL文字列からPOSIX pathに変換 v2

Posted on 3月 31, 2018 by Takaaki Naganoya

“file://”ではじまるfile URL文字列からPOSIX pathに変換するAppleScriptの改修版です。

たまたまScripting Bridge経由でFinder上の選択中のファイル一覧を取得したら、”file://”ではじまる文字列が返ってきて、Cocoaに変換する機能がないか調べたものの….ない。

・・・と思ったら「あるよ」というのを教えてもらいました。

下調べして「path()」でNSURLから変換できるというのは調査してあったんですが、試行錯誤する中でうまくいかなかった記憶が…..結果的には教えていただいた方法で無事変換できた次第です。

AppleScript名:file URL文字列からPOSIX pathに変換 v2
use AppleScript version "2.4"
use framework "Foundation"
use scripting additions

set aStr to "file:///Users/me/Desktop/%E3%82%B9%E3%82%AF%E3%83%AA%E3%83%BC%E3%83%B3%E3%82%B7%E3%83%A7%E3%83%83%E3%83%88%202018-03-12%2015.22.44.png"

set aURL to (current application’s |NSURL|’s URLWithString:aStr)
set aPOSIX to aURL’s |path|() as string

★Click Here to Open This Script 

Posted in File path Text URL | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

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

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

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

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

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

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

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

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

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

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

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

★Click Here to Open This Script 

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

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

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

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

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

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

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

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

return allFolList

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

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

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

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

★Click Here to Open This Script 

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

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

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

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

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

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

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

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

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

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

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

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

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

★Click Here to Open This Script 

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

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

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

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

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

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

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

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

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

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

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

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

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

★Click Here to Open This Script 

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

パラメータを指定してdateオブジェクトを作成

Posted on 3月 30, 2018 by Takaaki Naganoya
AppleScript名:パラメータを指定してdateオブジェクトを作成
— Created 2017-09-22 by Takaaki Naganoya
— 2017 Piyomaru Software
use AppleScript version "2.5"
use scripting additions
use framework "Foundation"

set a to getDateInternational(2012, 2, 28) of me
–> date "2012年2月28日火曜日 0:00:00"

set b to getDateInternationalYMDhms(2012, 2, 28, 1, 2, 3) of me
–> date "2012年2月28日火曜日 1:02:03"

–現在のカレンダーで指定年月のdate objectを返す(年、月、日、時、分、秒)
on getDateInternationalYMDhms(aYear, aMonth, aDay, anHour, aMinute, aSecond)
  set theNSCalendar to current application’s NSCalendar’s currentCalendar()
  
set theDate to theNSCalendar’s dateWithEra:1 |year|:aYear |month|:aMonth |day|:aDay hour:anHour minute:aMinute |second|:aSecond nanosecond:0
  
return theDate as date
end getDateInternationalYMDhms

–現在のカレンダーで指定年月のdate objectを返す(年、月、日)
on getDateInternational(aYear, aMonth, aDay)
  set theNSCalendar to current application’s NSCalendar’s currentCalendar()
  
set theDate to theNSCalendar’s dateWithEra:1 |year|:aYear |month|:aMonth |day|:aDay hour:0 minute:0 |second|:0 nanosecond:0
  
return theDate as date
end getDateInternational

★Click Here to Open This Script 

Posted in Calendar Text | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

MMMM dd yyyyの文字列をdateに変換

Posted on 3月 30, 2018 by Takaaki Naganoya

基礎的なScriptです。文字列で形式を指定した日付文字列を認識してAppleScriptのdateオブジェクトに変換するAppleScriptです。

「as list of string or string」の行は「as anything」が解釈されて(macOS 10.13まで)このようになるわけですが、macOS 10.14からは「as anything」(スクリプトエディタ)、「as any」(Script Debugger)と解釈されます。

本プログラムであれば、「as date」と書いておくと問題がないでしょう。

AppleScript名:MMMM dd yyyyの文字列をdateに変換.scptd
—
–  Created by: Takaaki Naganoya
–  Created on: 2018/03/23
—
–  Copyright © 2018 Piyomaru Software, All Rights Reserved
—

use AppleScript version "2.4" — Yosemite (10.10) or later
use framework "Foundation"
use scripting additions

set tmpDate to "2014-09-14 15:45:00"
set tmpD1 to dateFromStringWithDateFormat(tmpDate, "yyyy-MM-dd HH:mm:ss") of me
–> date "2014年9月14日日曜日 15:45:00"

set tmpDate to "August 19, 2018 15:45:00"
set tmpD2 to dateFromStringWithDateFormat(tmpDate, "MMMM dd, yyyy HH:mm:ss") of me
–> date "2018年8月19日日曜日 15:45:00"

return {tmpD1, tmpD2}

on dateFromStringWithDateFormat(dateString, dateFormat)
  set dStr to current application’s NSString’s stringWithString:dateString
  
set dateFormatStr to current application’s NSString’s stringWithString:dateFormat
  
  
set aDateFormatter to current application’s NSDateFormatter’s alloc()’s init()
  
aDateFormatter’s setDateFormat:dateFormatStr
  
aDateFormatter’s setLocale:(current application’s NSLocale’s alloc()’s initWithLocaleIdentifier:"en_US_POSIX")
  
  
set aDestDate to (aDateFormatter’s dateFromString:dStr)
  
  
return aDestDate as list of string or string
end dateFromStringWithDateFormat

★Click Here to Open This Script 

Posted in Calendar Text | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

Twitter APIの日付フォーマットをAppleScriptのdateに変換する

Posted on 3月 30, 2018 by Takaaki Naganoya

Twitter APIの日付フォーマットの文字列をAppleScriptのdateオブジェクトに変換するAppleScriptです。

TwitterのREST APIから返ってくる日付フォーマットの文字列を変換しようとしてハマったのでメモしておきました。

AppleScript名:Twitter APIの日付フォーマットをAppleScriptのdateに変換する.scptd
—
–  Created by: Takaaki Naganoya
–  Created on: 2018/03/30
—
–  Copyright © 2018 Piyomaru Software, All Rights Reserved
—
use AppleScript version "2.5" — El Capitan (10.11) or later
use framework "Foundation"
use scripting additions

property NSString : a reference to current application’s NSString
property NSLocale : a reference to current application’s NSLocale
property NSDateFormatter : a reference to current application’s NSDateFormatter

set a to "Fri Mar 30 11:03:57 +0000 2018"

set aDF to NSDateFormatter’s alloc()’s init()
aDF’s setDateFormat:"EEE MMM dd HH:mm:ss Z yyyy"
aDF’s setLocale:(NSLocale’s alloc()’s initWithLocaleIdentifier:"en_US_POSIX")
set aResDate to aDF’s dateFromString:a
set aDateO to aResDate as date
–> date "2018年3月30日金曜日 20:03:57"

★Click Here to Open This Script 

Posted in Calendar Text | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

Numbersの選択中の表を取得してMarkdown書式の表に変換する v2

Posted on 3月 30, 2018 by Takaaki Naganoya

Numbers上の選択中のテーブルの内容をMarkdown形式のデータに書き出して、書き出したデータをMacDownでオープンしてHTMLのソース文字列を取得するAppleScriptです。

Numbersの表の内容をHTMLに書き出すのに、2D Arrayの内容を直接HTML Tableに変換するScriptが手元に見当たらなかったので、いったんMarkdown書類を経由させてみました。

MarkdownのレンダラーのFrameworkもいくつかチェックはしていますが、なぜかどれもこれもTableタグをサポートしていません(ーー;;

AppleScript名:Numbersの選択範囲を取得してMarkdown書式の表に変換する v2
— Created 2016-05-12 by Takaaki Naganoya
— Modified 2018-03-29 by Takaaki Naganoya
— 2018 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"

property NSUUID : a reference to current application’s NSUUID
property NSString : a reference to current application’s NSString
property NSFileManager : a reference to current application’s NSFileManager

set htmlRes to selectedNumbersTableToHTML() of me

–選択中のNumbersのワークシート上で選択中のテーブルのデータをHTML化
on selectedNumbersTableToHTML()
  set aSeparator to "|"
  
set aCell to ":—" –Align Left Tag
  
set aLineTerminator to return
  
  
–Numbersの選択範囲からExcel仕様で2Dリストを返す
  
set aSel to get2DListFromNumbersSelection() of me
  
if aSel = "" then
    tell current application
      display dialog "Numbersのワークシート上で何も選択されていません" with icon 2 buttons {"OK"} default button 1 with title "選択範囲エラー"
      
return false
    end tell
  end if
  
  
–選択範囲の横幅チェック、ヘッダー部のデータ作成
  
set colNum to length of (contents of first item of aSel)
  
set sepList to {}
  
repeat colNum times
    set end of sepList to aCell
  end repeat
  
  
–ヘッダーセパレータを配列の2番目に挿入する
  
set newList to insListItem(aSel, sepList, 2) of me
  
  
–Markdown書式の表を文字列で作成する
  
set outStr to ""
  
repeat with i in newList
    set outStr to outStr & retStrFromArrayWithDelimiter(contents of i, aSeparator) of me & aLineTerminator
  end repeat
  
  
–Desktopにmarkdown書類を書き出してMacDownでオープンしてHTMLソースを取得する
  
set targFol to POSIX path of (path to desktop)
  
set fRes to savePlainText(targFol, outStr, "md") of me
  
  
tell application "MacDown"
    open ((POSIX file fRes) as alias)
    
    
tell front document
      set aProp to properties
      
set aHtmlDat to html of aProp
      
close
    end tell
  end tell
  
  
–デスクトップフォルダ上に作成したMarkdown書類を削除する
  
set aRes to deleteItemAt(fRes) of me
  
  
return aHtmlDat
end selectedNumbersTableToHTML

–指定のリスト(2次元配列)に、要素(1次元配列)を、指定箇所(1はじまり)にインサートする
on insListItem(aList as list, insList as list, insertItemNum as integer)
  set newList to {}
  
set itemCounter to 1
  
repeat with i in aList
    if itemCounter = insertItemNum then
      set the end of newList to insList
    end if
    
set end of newList to (contents of i)
    
set itemCounter to itemCounter + 1
  end repeat
  
return newList
end insListItem

–リストを指定デリミタをはさんでテキスト化
on retStrFromArrayWithDelimiter(aList as list, aDelim as string)
  set anArray to current application’s NSArray’s arrayWithArray:aList
  
set aRes to anArray’s componentsJoinedByString:aDelim
  
return aRes as text
end retStrFromArrayWithDelimiter

on retArrowText(aList as list, aDelim as string) –自分のASでよく使うハンドラ名称なので、同じものを用意
  return my retStrFromArrayWithDelimiter(aList, aDelim)
end retArrowText

–テキストを指定デリミタでリスト化
on parseByDelim(aData, aDelim)
  set aText to current application’s NSString’s stringWithString:aData
  
set aList to aText’s componentsSeparatedByString:aDelim
  
return aList as list
end parseByDelim

on get2DListFromNumbersSelection()
  –Numbersで選択範囲を縦に区切ったリストを返す
  
tell application "Numbers"
    tell front document
      tell active sheet
        set theTable to first table whose class of selection range is range
        
tell theTable
          try
            set selList to value of every cell of selection range –選択範囲のデータを取得
          on error
            return "" –何も選択されてなかった場合
          end try
          
          
set selName to name of selection range –選択範囲のrange情報を取得
          
set {s1, s2} to parseByDelim(selName, ":") of me
          
          
–始点の情報を取得する
          
set s1Row to (address of row of range s1) as integer
          
set s1Column to (address of column of range s1) as integer
          
          
–終点の情報を取得する
          
set s2Row to (address of row of range s2) as integer
          
set s2Column to (address of column of range s2) as integer
          
          
–選択範囲の情報を取得する
          
set selHeight to s2Row – s1Row + 1 –高さ(Height of selection range)
          
set selWidth to s2Column – s1Column + 1 –幅(Width of selection range)
          
        end tell
      end tell
    end tell
  end tell
  
  
set aLen to length of selList
  
set aaLen to selHeight
  
  
set bList to {}
  
repeat with i from 1 to aaLen
    set aHoriList to {}
    
    
repeat with ii from 1 to selWidth
      set j1 to ii + (i – 1) * selWidth
      
set tmpCon to contents of item j1 of selList
      
      
set aClass to class of tmpCon
      
if aClass = number or aClass = integer or aClass = real then
        set tmpCon to tmpCon as integer
      end if
      
      
set the end of aHoriList to tmpCon
    end repeat
    
    
set the end of bList to aHoriList
  end repeat
  
  
return bList
  
end get2DListFromNumbersSelection

–プレーンテキストを指定フォルダ(POSIX path)にUTF-8で書き出し
on savePlainText(targFol, aString, aExt)
  set aString to current application’s NSString’s stringWithString:aString
  
  
set theName to (NSUUID’s UUID()’s UUIDString())
  
set thePath to NSString’s stringWithString:targFol
  
set thePath to (thePath’s stringByAppendingPathComponent:theName)’s stringByAppendingPathExtension:aExt
  
  
set aRes to aString’s writeToFile:thePath atomically:false encoding:(current application’s NSUTF8StringEncoding) |error|:(missing value)
  
  
if aRes as boolean = true then
    return thePath as string
  else
    return false
  end if
end savePlainText

–指定のPOSIX pathのファイルを削除
on deleteItemAt(aPosixPath)
  set theNSFileManager to NSFileManager’s defaultManager()
  
set theResult to theNSFileManager’s removeItemAtPath:(aPosixPath) |error|:(missing value)
  
return (theResult as integer = 1) as boolean
end deleteItemAt

★Click Here to Open This Script 

Posted in Markdown Text | Tagged 10.11savvy 10.12savvy 10.13savvy MacDown Numbers | Leave a comment

file URL文字列からPOSIX pathに変換

Posted on 3月 29, 2018 by Takaaki Naganoya

“file://”ではじまるfile URL文字列からPOSIX pathに変換するAppleScriptです。

たまたまScripting Bridge経由でFinder上の選択中のファイル一覧を取得したら、”file://”ではじまる文字列が返ってきて、Cocoaに変換する機能がないか調べたものの….ない。

というわけで、とりあえず作ってみました。

AppleScript名:file URL文字列からPOSIX pathに変換
— Created 2018-03-29 by Takaaki Naganoya
— 2018 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"

set aStr to "file:///Users/me/Desktop/%E3%82%B9%E3%82%AF%E3%83%AA%E3%83%BC%E3%83%B3%E3%82%B7%E3%83%A7%E3%83%83%E3%83%88%202018-03-12%2015.22.44.png"

set bStr to convfileURLStringtoPOSIXpath(aStr) of me
–>  "/Users/me/Desktop/スクリーンショット 2018-03-12 15.22.44.png"

on convfileURLStringtoPOSIXpath(aURLencodedStr)
  set aStr to current application’s NSString’s stringWithString:aURLencodedStr
  
set aDecoded to (aStr’s stringByRemovingPercentEncoding()) as string
  
if aDecoded begins with "file:///" then
    return text (length of "file:///") thru -1 of aDecoded
  else
    return aDecoded
  end if
end convfileURLStringtoPOSIXpath

★Click Here to Open This Script 

Posted in File path Text | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

指定PDFの全ページからリンクアノテーションのURLを取得してURLを書きかえる

Posted on 3月 28, 2018 by Takaaki Naganoya

指定PDFの全ページのURLリンクアノテーションのURLを書き換えるAppleScriptです。

URL Linkアノテーションを添付したPDFに対して、Linkアノテーションのboundsを取得して削除し、同じboundsの異なるURLへのリンクアノテーションを作成して保存します。

Keynote、Pages、NumbersのiWorkアプリケーションにはオブジェクトに対してリンクを付加し、URLを指定することができるようになっていますが、URLスキームはhttpがデフォルトで指定されています。

Pages上でURLスキームを指定できたら、それはそれで使い道がいろいろありそうですが、リクエストを出してもここはhttp(かmailto)以外は有効になる気配がありません。

そこで、URLだけダミーのものをこれらのiWorkアプリケーション上で割り振っておいていったんPDF書き出しを行い、書き出されたPDFのLinkアノテーションをあとでAppleScriptから書き換えることで、任意のURLリンクを埋め込むのと同じことができるようになるだろう、と考えて実験してみました。

ただ、1つのグラフィックオブジェクトに対してKeynote上でリンクを付与してPDF書き出しすると、Keynoteがオブジェクトの領域を細分化してリンクを作成するようです。文字とグラフィックにリンクを指定しただけなのに、やたらと大量のリンクアノテーションが検出されるので、念のためにチェックしてみたらこんな(↓)感じでした。

AppleScript名:指定PDFの全ページからリンクアノテーションのURLを取得してURLを書きかえる
— Created 2017-06-08 by Takaaki Naganoya
— Modified 2018-03-14 by Takaaki Naganoya
— 2017, 2018 Piyomaru Software
use AppleScript version "2.5"
use scripting additions
use framework "Foundation"
use framework "Quartz"

property |NSURL| : a reference to current application’s |NSURL|
property PDFActionURL : a reference to current application’s PDFActionURL
property PDFDocument : a reference to current application’s PDFDocument
property PDFAnnotationLink : a reference to current application’s PDFAnnotationLink

set aPOSIX to POSIX path of (choose file of type {"com.adobe.pdf"} with prompt "Choose a PDF with Annotation")
set linkList to replaceLinkURLFromPDF(aPOSIX, "http://www.apple.com/jp", "applescript://com.apple.scripteditor?action=new&script=display%20dialog%20%22TEST%22") of me

on replaceLinkURLFromPDF(aPOSIX, origURL, toURL)
  set v2 to system attribute "sys2" –> case: macOS 10.12 =12
  
  
set aURL to (|NSURL|’s fileURLWithPath:aPOSIX)
  
set aPDFdoc to PDFDocument’s alloc()’s initWithURL:aURL
  
set pCount to aPDFdoc’s pageCount()
  
  
–PDFのページ(PDFPage)でループ
  
repeat with ii from 0 to (pCount – 1)
    set tmpPage to (aPDFdoc’s pageAtIndex:ii) –PDFPage
    
    
set anoList to (tmpPage’s annotations()) as list
    
if anoList is not equal to {missing value} then –指定PDF中にAnotationが存在した
      
      
–対象PDFPage内で検出されたAnnotationでループ
      
repeat with i in anoList
        if v2 < 13 then
          set aType to (i’s type()) as string –to macOS Sierra (10.10, 10.11 & 10.12)
        else
          set aType to (i’s |Type|()) as string –macOS High Sierra (10.13) or later
        end if
        
        
–Link Annotationの削除と同様のサイズでLink Annotationの新規作成
        
if aType = "Link" then
          set tmpURL to (i’s |URL|()’s absoluteString()) as string
          
          
if tmpURL = origURL then
            set theBounds to i’s |bounds|() –削除する前にLink Annotationの位置情報を取得
            
–> {origin:{x:78.65625, y:454.7188}, size:{width:96.96875, height:4.0937}}
            
            (
tmpPage’s removeAnnotation:i) –PDFPageから指定のLink Annotationを削除  
            
            
set theLink to (PDFAnnotationLink’s alloc()’s initWithBounds:theBounds)
            
set theAction to (PDFActionURL’s alloc()’s initWithURL:(current application’s |NSURL|’s URLWithString:toURL))
            (
theLink’s setMouseUpAction:theAction)
            (
tmpPage’s addAnnotation:theLink)
            
            
log {ii + 1, theBounds, origURL}
          end if
        end if
      end repeat
    end if
  end repeat
  
  
return (aPDFdoc’s writeToFile:aPOSIX) as boolean
end replaceLinkURLFromPDF

★Click Here to Open This Script 

Posted in file PDF URL | Tagged 10.11savvy 10.12savvy 10.13savvy | 1 Comment

Keynote, Pages, Numbersがアップデート

Posted on 3月 28, 2018 by Takaaki Naganoya

Keynote、Pages、Numbersがアップデートしました。

 Keynote:v7.3.1 –> v8.0.0
 Pages:v6.3.1 –> v 7.0.0
 Numbers:v4.3.1 –> v5.0.0

NumbersのCSV書き出し機能が強化・変更されたとのことなので、これまでNumbersで複数のシートを含む書類をCSV書き出ししたときの挙動とやや変わる可能性があります。

AppleScript用語辞書については、Pagesにのみ変更があります。これまで用語辞書には「ePub」と書かれていましたが、「EPUB」に変更されました。

また、PagesのEPUB書き出し設定(export options)で「fixed layout」という項目(boolean)が増えました。

Posted in 未分類 | Tagged 10.12savvy 10.13savvy Keynote Numbers Pages | 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

デスクトップ以下のスクリーンキャプチャファイルの一覧を取得 v2

Posted on 3月 26, 2018 by Takaaki Naganoya

指定フォルダ以下に存在するファイルのうち条件に合うものをSpotlightの機能を用いて抽出するAppleScriptです。デスクトップフォルダ以下にあるスクリーンキャプチャを検索します。

Spotlight検索にはShane Stanleyの「Metadata Lib」のバージョン2.0を使用しています。インストールしていない環境では動かないので、事前に~/Library/Script Libraries/フォルダにインストールしておいてください。

Metadata Libはv1.xではAppleScript用語辞書がついていませんでしたが、v2.xではAppleScript用語辞書(sdef)が追加され、いわゆる英単語っぽい表記でパラメータを指定できるようになりました。

再掲載にあたってv2.0の表記に書き換えてみました。

AppleScript名:デスクトップ以下のスクリーンキャプチャファイルの一覧を取得 v2
— Created 2017-09-23 by Takaaki Naganoya
— 2017 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use mdLib : script "Metadata Lib" version "2.0.0"

set theFolder to path to desktop
set sStr to "kMDItemIsScreenCapture == %@"
set fRes to perform search in folders {theFolder} predicate string sStr search arguments {true}

return fRes

★Click Here to Open This Script 

Posted in Spotlight | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

Metadata Lib v2.0の命令をひととおりチェック

Posted on 3月 26, 2018 by Takaaki Naganoya
AppleScript名:Metadata Lib v2.0の命令をひととおりチェック
— Created 2017-09-23 by Takaaki Naganoya
— 2017 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use mdLib : script "Metadata Lib" version "2.0.0" –https://www.macosxautomation.com/applescript/apps/

–mdfind
set theFolder to path to desktop
set sStr to "kMDItemResolutionHeightDPI == %@ && kMDItemResolutionWidthDPI == %@ && NOT (kMDItemContentTypeTree contains %@)"
set fRes to perform search in folders {theFolder} predicate string sStr search arguments {144, 144, "com.apple.icns"}
log fRes
–> {"/Users/me/Desktop/From Desktop 2018.1.9/FromDesktop/スクリーンショット 2015-12-18 13.02.14.png"}

–scope strings
set aRes to metadata scope strings
log aRes
–> {"kMDQueryScopeHome", "kMDQueryScopeNetwork", "kMDQueryScopeComputer", "kMDQueryScopeAllIndexed", "kMDQueryScopeComputerIndexed", "kMDQueryScopeNetworkIndexed"}
–https://developer.apple.com/documentation/coreservices/file_metadata/mdquery/query_search_scope_keys?preferredLanguage=occ

–mdls
set aFile to choose file with prompt ""
set aRes to fetch metadata for item aFile
log aRes
–> {kMDItemFSCreatorCode:0, kMDItemFSFinderFlags:0, kMDItemFSContentChangeDate:date "2018年3月14日水曜日 1:32:07", kMDItemFSName:"0261F5E3-9BE4-4007-B7D8-10E56E13FB24.dot", kMDItemDisplayName:"0261F5E3-9BE4-4007-B7D8-10E56E13FB24.dot", kMDItemFSInvisible:false, kMDItemFSSize:2506, kMDItemFSOwnerUserID:504, kMDItemDateAdded:date "2018年3月14日水曜日 1:32:07", kMDItemPhysicalSize:4096, kMDItemKind:"Microsoft Word 97 – 2004 テンプレート (.dot)", _kMDItemOwnerUserID:504, kMDItemContentTypeTree:{"public.item", "public.data", "com.microsoft.word.dot"}, kMDItemFSTypeCode:0, kMDItemFSIsExtensionHidden:false, kMDItemLogicalSize:2506, kMDItemFSLabel:0, kMDItemContentModificationDate:date "2018年3月14日水曜日 1:32:07", kMDItemUseCount:2, kMDItemContentType:"com.microsoft.word.dot", kMDItemFSOwnerGroupID:80, kMDItemContentCreationDate:date "2018年3月14日水曜日 1:32:07", kMDItemUsedDates:{date "2018年3月14日水曜日 0:00:00"}, kMDItemFSCreationDate:date "2018年3月14日水曜日 1:32:07"}

–既存のsavedsearchから情報を読み取る
set sFile to choose file of type {"com.apple.finder.smart-folder"} with prompt "Select saved search file (purple folder icon)" default location (path to home folder)
search strings from saved search (POSIX path of sFile)
–> {"((_kMDItemGroupId = 11) && (kMDItemContentCreationDate > 489942000))", "_kMDItemGroupId == \"11\" AND kMDItemContentCreationDate > \"489942000\""}

★Click Here to Open This Script 

Posted in Spotlight | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

デスクトップ上のRetina解像度の画像でICNS以外のものを検索 v2

Posted on 3月 26, 2018 by Takaaki Naganoya

指定フォルダ以下に存在するファイルのうち条件に合うものをSpotlightの機能を用いて抽出するAppleScriptです。デスクトップフォルダ以下にあるRetina解像度の画像(144 x 144dpi)で、ファイル形式がICNS「以外のもの」を検索します。

Spotlight検索にはShane Stanleyの「Metadata Lib」のバージョン2.0を使用しています。インストールしていない環境では動かないので、事前に~/Library/Script Libraries/フォルダにインストールしておいてください。

Metadata Libはv1.xではAppleScript用語辞書がついていませんでしたが、v2.xではAppleScript用語辞書(sdef)が追加され、いわゆる英単語っぽい表記でパラメータを指定できるようになりました。

再掲載にあたってv2.0の表記に書き換えてみました。

AppleScript名:デスクトップ上のRetina解像度の画像でICNS以外のものを検索 v2
— Created 2017-09-23 by Takaaki Naganoya
— 2017 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use mdLib : script "Metadata Lib" version "2.0.0" –https://www.macosxautomation.com/applescript/apps/

set theFolder to path to desktop
–v1.x
–set fRes to mdLib’s searchFolders:{theFolder} searchString:"kMDItemResolutionHeightDPI == %@ && kMDItemResolutionWidthDPI == %@ && NOT (kMDItemContentTypeTree contains %@)" searchArgs:{144, 144, "com.apple.icns"}
–> {"/Users/me/Desktop/FromDesktop/スクリーンショット 2015-12-18 13.02.14.png", "/Users/me/Desktop/FromDesktop/conicon.png", "/Users/me/Desktop/FromDesktop/スクリーンショット 2015-08-14 18.08.41.png"}

–v2.x
set sStr to "kMDItemResolutionHeightDPI == %@ && kMDItemResolutionWidthDPI == %@ && NOT (kMDItemContentTypeTree contains %@)"
set fRes to perform search in folders {theFolder} predicate string sStr search arguments {144, 144, "com.apple.icns"}
–> {"/Users/me/Desktop/From Desktop 2018.1.9/FromDesktop/スクリーンショット 2015-12-18 13.02.14.png"}

★Click Here to Open This Script 

Posted in Spotlight | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

POSIX path stringを与えると、ファイル名の重複を検出&名称回避を行って、ファイル名のみを返す

Posted on 3月 23, 2018 by Takaaki Naganoya

POSIX pathのフルパスの文字列(quoteなし)を与えると、そのファイルを実際に作成した場合に指定のパスに同名のファイルが存在するかどうか重複検出を行い、重複するものがあった場合には重複回避してファイル名を返すAppleScriptです。

# 一部ミスがあるものを掲載していたので、書き換えておきました

ファイルの新規保存を行う際に、安全に新しい名称を指定できるよう、重複検出および重複回避を行います。

デスクトップ上に、

  test.jpg
  test_1.jpg

というファイルがあった場合に、本Scriptで「test.jpg」を指定すると、同じ名前のファイルがデスクトップに存在するものと判定されて、名称の衝突回避を行います。

回避するためにファイル名の末尾に「_」+番号を付けて回避を行いますが、すでに「test_1.jpg」が存在するために、本Scriptではさらに名称回避を行なって「test_2.jpg」の文字列を返します。

子番号については、1〜65535の範囲で追加するようにしています。常識的にこれだけ指定しておけば大丈夫だろう、ということであってとくに上限に意味はありません。

AppleScript名:POSIX path stringを与えると、ファイル名の重複を検出&名称回避を行って、ファイル名のみを返す v2
— Created 2020-08-15 by Takaaki Naganoya
— 2015-2020 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"

property NSString : a reference to current application’s NSString
property NSFileManager : a reference to current application’s NSFileManager
property NSOrderedSame : a reference to current application’s NSOrderedSame

set newPath to POSIX path of (choose file name)

set ab to chkExistPOSIXpathAndIncrementChildNumber(newPath) of me

–POSIX path stringを与えると、ファイル名の重複を検出して、ファイル名の名称回避を行って、ファイル名のみを返す
on chkExistPOSIXpathAndIncrementChildNumber(aPOSIX as string)
  set aStr to NSString’s stringWithString:aPOSIX
  
  
–ファイルパス(フルパス)からファイル名部分を取得
  
set bStr to aStr’s lastPathComponent()
  
–> "P0000_000.csv"
  
  
–ファイル名から拡張子を取得
  
set cStr to (bStr’s pathExtension()) as string
  
–> "csv"
  
  
–ファイル名から拡張子を削除
  
set dStr to (bStr’s stringByDeletingPathExtension()) as string
  
–> "P0000_000"
  
  
–ファイルパス(フルパス)から親フォルダを取得(ただし末尾はスラッシュになっていない)
  
set eStr to (aStr’s stringByDeletingLastPathComponent()) as string
  
–>  "/Users/me/Desktop"
  
  
set aManager to NSFileManager’s defaultManager()
  
set aRes to (aManager’s fileExistsAtPath:aStr) as boolean
  
if aRes = false then
    –ファイル名の衝突がなかった場合
    
return bStr as string
  end if
  
  
set hitF to false
  
repeat with i from 1 to 65535
    
    
set tmpPath to (eStr & "/" & dStr & "_" & (i as string) & "." & cStr)
    
set tmpStr to (NSString’s stringWithString:tmpPath)
    
set aRes to (aManager’s fileExistsAtPath:tmpStr) as boolean
    
set bRes to ((tmpStr’s caseInsensitiveCompare:eStr) is not equal to (NSOrderedSame)) as boolean
    
    
if {aRes, bRes} = {false, true} then
      set hitF to true
      
exit repeat
    end if
    
  end repeat
  
  
if hitF = false then return false
  
  
–ファイルパス(フルパス)からファイル名部分を取得
  
set returnFileName to tmpStr’s lastPathComponent()
  
return (returnFileName as string)
  
end chkExistPOSIXpathAndIncrementChildNumber

★Click Here to Open This Script 

Posted in file | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

指定フォルダ内の指定文字列を含むファイル名のファイルをPOSIX pathのlistで抽出する

Posted on 3月 21, 2018 by Takaaki Naganoya
AppleScript名:指定フォルダ内の指定文字列を含むファイル名のファイルをPOSIX pathのlistで抽出する
— Created 2017-09-12 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 NSPredicate : a reference to current application’s NSPredicate
property NSFileManager : a reference to current application’s NSFileManager
property NSMutableArray : a reference to current application’s NSMutableArray
property NSURLIsDirectoryKey : a reference to current application’s NSURLIsDirectoryKey
property NSDirectoryEnumerationSkipsHiddenFiles : a reference to current application’s NSDirectoryEnumerationSkipsHiddenFiles
property NSDirectoryEnumerationSkipsPackageDescendants : a reference to current application’s NSDirectoryEnumerationSkipsPackageDescendants
property NSDirectoryEnumerationSkipsSubdirectoryDescendants : a reference to current application’s NSDirectoryEnumerationSkipsSubdirectoryDescendants

set aFol to POSIX path of (choose folder with prompt "Choose folder" default location (path to desktop folder))
set pRes to my getFilesByIncludedStringInName:"スクリーン" fromDirectory:aFol exceptPackages:true
–> {"/Users/me/Desktop/スクリーンショット 2018-02-28 14.01.09.png", "/Users/me/Desktop/スクリーンショット 2018-02-28 14.01.11.png", …}

–指定フォルダ内の指定文字列を含むファイル名のファイルをPOSIX pathのlistで抽出する
on getFilesByIncludedStringInName:(fileNameStr as string) fromDirectory:(sourceFolder) exceptPackages:(packageF as boolean)
  set fileManager to NSFileManager’s defaultManager()
  
set aURL to |NSURL|’s fileURLWithPath:sourceFolder
  
set theOptions to ((NSDirectoryEnumerationSkipsPackageDescendants) as integer) + ((NSDirectoryEnumerationSkipsHiddenFiles) as integer) + ((NSDirectoryEnumerationSkipsSubdirectoryDescendants) as integer)
  
set directoryContents to fileManager’s contentsOfDirectoryAtURL:aURL includingPropertiesForKeys:{} options:theOptions |error|:(missing value)
  
set findPredicates to NSPredicate’s predicateWithFormat_("lastPathComponent CONTAINS %@", fileNameStr)
  
set foundItemList to directoryContents’s filteredArrayUsingPredicate:findPredicates
  
  
–Remove Folders From found URL Array
  
set anArray to NSMutableArray’s alloc()’s init()
  
repeat with i in foundItemList
    set j to contents of i
    
set {theResult, isDirectory} to (j’s getResourceValue:(reference) forKey:(NSURLIsDirectoryKey) |error|:(missing value))
    
    
–Collect files
    
if (isDirectory as boolean = false) then
      (anArray’s addObject:j)
      
    else if (packageF = false) then
      –Allow Package files?
      
set {theResult, isPackage} to (j’s getResourceValue:(reference) forKey:(current application’s NSURLIsPackageKey) |error|:(missing value))
      
if (isPackage as boolean) = true then
        (anArray’s addObject:j)
      end if
    end if
    
  end repeat
  
  
return (anArray’s valueForKey:"path") as list
end getFilesByIncludedStringInName:fromDirectory:exceptPackages:

★Click Here to Open This Script 

Posted in file | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

フォルダの存在確認

Posted on 3月 20, 2018 by Takaaki Naganoya
AppleScript名:フォルダの存在確認
— Created 2017-10-31 by Takaaki Naganoya
— 2017 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "AppKit"

set bPath to POSIX path of (choose folder)
set bExt to current application’s NSFileManager’s defaultManager()’s fileExistsAtPath:bPath isDirectory:true
–> true

★Click Here to Open This Script 

AppleScript名:フォルダの存在確認(OLD Style AS)
set aFolder to choose folder

tell application "Finder"
  set aRes to exists of aFolder
  
–> true
end tell

★Click Here to Open This Script 

Posted in folder | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

ファイルの存在確認

Posted on 3月 20, 2018 by Takaaki Naganoya
AppleScript名:ファイルの存在確認
— Created 2017-10-31 by Takaaki Naganoya
— 2017 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "AppKit"

set aPath to POSIX path of (choose file)
set aExt to current application’s NSFileManager’s defaultManager()’s fileExistsAtPath:aPath
–> true

★Click Here to Open This Script 

AppleScript名:ファイルの存在確認(OLD Style AS)
set aFile to choose file

tell application "Finder"
  set aRes to exists of aFile
  
–> true
end tell

★Click Here to Open This Script 

Posted in file | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

Post navigation

  • Older 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