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年2月

ANSI Colorの色名称でTerminalの文字色を変更

Posted on 2月 27, 2018 by Takaaki Naganoya

ANSI Colorの名称一覧から名前をえらんで、Terminalの文字色を変更するAppleScriptです。

これにどの程度の意味があるのかさっぱり分からないのですが、ANSI Colorで文字色を指定する趣味の人もいるということで、世界の広さを感じます。

–> Demo Movie


▲Select ANSI color name


▲Before


▲After

AppleScript名:ANSI Colorの色名称でTerminalの文字色を変更
— Created 2018-02-06 by Takaaki Naganoya
— 2018 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "AppKit"

–Dark
–set ansiColTable to {{colName:"Black", colVal:{0, 0, 0}}, {colName:"Red", colVal:{34166, 0, 712}}, {colName:"Green", colVal:{5182, 39392, 620}}, {colName:"Yellow", colVal:{34811, 35431, 1086}}, {colName:"Blue", colVal:{0, 0, 39429}}, {colName:"White", colVal:{49207, 49511, 49827}}, {colName:"Magenta", colVal:{41397, 0, 41833}}, {colName:"Cyan", colVal:{4997, 38685, 41818}}}

–Light
set ansiColTable to {{colName:"Black", colVal:{21352, 21356, 21351}}, {colName:"Red", colVal:{56616, 0, 1392}}, {colName:"Green", colVal:{7241, 55116, 1162}}, {colName:"Yellow", colVal:{57396, 58567, 2377}}, {colName:"Blue", colVal:{0, 0, 65416}}, {colName:"White", colVal:{49207, 49511, 49827}}, {colName:"Magenta", colVal:{56440, 0, 57441}}, {colName:"Cyan", colVal:{7416, 58001, 57206}}}

set tmpColorList to filterAnAttribute(ansiColTable, "colName") of me
set aTargColor to choose from list tmpColorList with prompt "choose ANSI color name"
if aTargColor = {} or aTargColor = false then return

set targColorName to contents of first item of aTargColor

set aRes to filterListUsingPredicate(ansiColTable, "colName ==[c] %@", targColorName)
if aRes = missing value then return

set colList to colVal of aRes

tell application "Terminal"
  set normal text color of window 1 to colList
  
–set background color of window 1 to colList
end tell

on filterListUsingPredicate(aList as list, aPredicateStr as string, targStr as string)
  set setKey to current application’s NSMutableSet’s setWithArray:aList
  
set aPredicate to current application’s NSPredicate’s predicateWithFormat_(aPredicateStr, targStr)
  
set aRes to (setKey’s filteredSetUsingPredicate:aPredicate)
  
return (aRes’s allObjects()) as list of string or string
end filterListUsingPredicate

on filterAnAttribute(aList as list, anAttr as string)
  set anArray to current application’s NSArray’s arrayWithArray:aList
  
set valList to anArray’s valueForKeyPath:anAttr
  
return valList as list of string or string –as anything
end filterAnAttribute

★Click Here to Open This Script 

Posted in Color | Tagged 10.11savvy 10.12savvy 10.13savvy Terminal | Leave a comment

POST method REST API__Sendgrid_Send v1

Posted on 2月 26, 2018 by Takaaki Naganoya

メールの高速大量送信サービス「SendGrid」のREST API経由でメールの送信を行うAppleScriptです。

試用にあたっては、SendGridにサインアップして試用アカウントを取得してください。この試用アカウントで実運用を行わないことがアカウト取得の前提条件となっています(かなり念押しされました、、、)。

アクセストークンを取得したら、本リスト内のretAccessTokenハンドラ内にペーストしてください。本リストを掲載状態のままAccessTokenが伏字の状態で実行しても、メール送信は行えません。

気になるメールの転送速度ですが、本AppleScriptではだいたい1通あたり0.1秒程度です。Mail.app経由で一般的なプロバイダのメールサーバーを経由して送るよりは10倍程度高速ですが、APIの呼び方をチューニングすることで、さらにこの10倍ぐらいの高速送信は行えるようになります。

AppleScript名:POST method REST API__Sendgrid_Send v1
— Created 2017-05-23 by Takaaki Naganoya
— 2017 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"

set a1Dat to current application’s NSDate’s timeIntervalSinceReferenceDate()
repeat with i from 1 to 10
  set aSubject to "ぴよまるさんからの新しいおしらせ" & i as string
  
set aBody to "ぴよまるさんこんばんわ" & i as string
  
set toAddress to "maro@piyocast.com"
  
set fromAddress to "piyomarusoft@mac.com"
  
set aRes to sendMailViaSendGrid(aSubject, aBody, toAddress, fromAddress) of me
end repeat
set b1Dat to current application’s NSDate’s timeIntervalSinceReferenceDate()
set c1Dat to (b1Dat – a1Dat) as real
return c1Dat

on sendMailViaSendGrid(aSubject, aBody, toAddress, fromAddress)
  set accessToken to "Bearer " & retAccessToken() —Access Token
  
set reqURLStr to "https://api.sendgrid.com/v3/mail/send"
  
set aRec to {personalizations:{{|to|:{{email:toAddress}}, subject:aSubject}}, |from|:{email:fromAddress, |name|:"ぴよ まるお"}, content:{{type:"text/plain", value:aBody}}}
  
set aRes to callRestPOSTAPIAndParseResults(reqURLStr, accessToken, aRec) of me
  
set aRESTres to json of aRes
  
set aRESCode to (responseCode of aRes) as integer
  
return (aRESCode = 202) –リクエスト成立ならtrueが返る( )
end sendMailViaSendGrid

–POST methodのREST APIを呼ぶ
on callRestPOSTAPIAndParseResults(aURL, anAPIkey, aRec)
  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
  
aRequest’s setValue:anAPIkey forHTTPHeaderField:"Authorization"
  
aRequest’s setValue:"application/json" forHTTPHeaderField:"Content-Type"
  
aRequest’s setValue:"gzip" forHTTPHeaderField:"Content-Encoding"
  
set dataJson to current application’s NSJSONSerialization’s dataWithJSONObject:aRec options:0 |error|:(missing value)
  
aRequest’s setHTTPBody:dataJson
  
  
–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
  
set dRes to contents of second item of resList
  
set resCode to (dRes’s statusCode()) as integer
  
  
–Get Response Header
  
set resHeaders to (dRes’s allHeaderFields()) as record
  
  
return {json:aJsonDict, responseCode:resCode, responseHeader:resHeaders}
end callRestPOSTAPIAndParseResults

on retAccessToken()
  return "XX.XxX_XXxxXXxxxxxxXxXXXx.xXXXxXXXxXXXxXXxXxxxXXXxXXxxxXXXXxxxXxXxXXx"
end retAccessToken

★Click Here to Open This Script 

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

Mail.appで送信元を明示的に指定しつつメール送信

Posted on 2月 26, 2018 by Takaaki Naganoya

Mail.appで送信元の氏名および送信先の氏名を明示的に指定しつつメール送信を行うAppleScriptです。

Mail.appの操作Scriptはやればやるだけ課題が見えてくるので、ほどほどのところで止めています。メールアカウントについて、1つしかアカウントを登録していなければデフォルトのメールアカウントでを前提にメール送信すればいいはずですが、複数のアカウントを登録しているケースが多いので、アカウントを指定する処理を書いてみました。

メールの大量連続送信については、1990年代からずっとAppleScriptで行なっていますが、途中で知り合いが盛大にやらかした(短時間で大量のメール送信を行なってさまざまなプロバイダのメールサーバーをコケさせかけた)影響もあって、日本国内のネットワークでは単位時間内に所定の本数を超えるメール送信を行うと、プロバイダからすぐにメール送信のリレーを止められ、その後しばらくメール送信を行えなくなるのが「お約束」となっています。

# だいたい、1秒に1通以上(1分に60通以上)送信すると疑われます。

かくして、メールの大量一括送信をScriptで行う場合には、ある程度「待ち時間」を入れつつ送信するか、REST API経由でSendGridのサービスを呼び出してメーラー以外でメール送信を行うあたりが落とし所になっています。

AppleScript名:Mail.appで送信元を明示的に指定しつつメール送信

–本来、メールアカウントのnameがわかっていれば、わざわざリストから選択する必要はない
tell application "Mail"
  set aList to name of every account
  
set aaSel to choose from list aList
  
if aaSel = {} or aaSel = false then return
  
set aSel to first item of aaSel
end tell

log aSel

set mRes to makeAMailWithSpecifiedAccount("メールのタイトルだよ100", "テストメールの本文だよ100", "送信者の名前だよ", "送付先氏名", "nobody@piyocast.com", aSel) of me

on makeAMailWithSpecifiedAccount(theSubject, theBody, myName, yourName, yourAddress, myAccountName)
  tell application "Mail"
    –Account check
    
set anAccount to account myAccountName
    
set aProp to enabled of anAccount
    
if aProp is not equal to true then return false –アカウントが有効でなかった場合はエラーに
    
    
set eList to (email addresses of anAccount)
    
if eList = {} then return false –アカウントにメールアドレスの登録がなかった場合はエラーに(ねんのため)
    
set myEmail to first item of eList
    
    
–Make Sender
    
set theSender to myName & "<" & myEmail & ">"
    
    
–Make Message & Send
    
set newMessage to make new outgoing message with properties {sender:theSender, subject:theSubject, content:theBody & return & return, visible:false}
    
tell newMessage
      set visible to false
      
make new to recipient at end of to recipients with properties {name:yourName, address:yourAddress} –受取人の指定
      
send –メール送信
    end tell
  end tell
  
  
return true
end makeAMailWithSpecifiedAccount

★Click Here to Open This Script 

Posted in 未分類 | Tagged 10.11savvy 10.12savvy 10.13savvy Mail | 1 Comment

選択中のメール本文のSHA3チェックサムを計算

Posted on 2月 26, 2018 by Takaaki Naganoya

Mail.appで選択中のメール本文のSHA3チェックサムを計算するAppleScriptです。

macOS VistaことmacOS 10.13。もう、10.13.xのバージョン中に状況が好転するような気配がまったくしないこのOS。2018年6月のWWDCで次の10.14を発表して「アップデート間隔を伸ばす」と言ったところで、同じCEO、同じスタッフ、同じ開発期間でまた2018年10月にリリースするとかいったら「同じことの繰り返し」になるのではないかと戦々恐々としています。

macOS 10.13のMail.appでメールの文字化けなどが報告されているため、実際に同じ文面のメールのチェックサムを10.12と10.13で比較するためにこのAppleScriptを書いてみました。

結果は、とくに文字化けもなく同じチェックサム値が得られたものの、OSごと勝手にクラッシュしてシャットダウンするとか、Mail.appのルールが着信したてのメールに効かない時があるとか、Finderが不安定だとか、日本語入力時に辞書の用例が表示されると選択した候補で変換候補を確定できないとか、日本語入力時に確定後も変換ウィンドウが消えないとか、いまだにけっこうムチャクチャなOSです。

–> SHA3Kit.framework

AppleScript名:選択中のメール本文のSHA3チェックサムを計算
— Created 2017-02-25 by Takaaki Naganoya
— 2018 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "SHA3Kit" –https://github.com/jaeggerr/NSString-SHA3

set aMailBody to getSelectedMailBody() of me
if aMailBody = false then error "No Selection"

set origData to (current application’s NSString’s stringWithString:aMailBody)
set aHash1 to (origData’s sha3:256) as string
–> "C69C8E08D1E6A8DA53C4E00D02D5DB5C2937722730CF63C1EC44E59B57A3B03F"

on getSelectedMailBody()
  tell application "Mail"
    set aaSel to selection
    
if aaSel = {} or aaSel = "" then return false
    
    
set aSel to first item of aaSel
    
    
set aCon to content of aSel
    
return aCon
  end tell
end getSelectedMailBody

★Click Here to Open This Script 

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

選択中のメール本文のHexダンプを取得

Posted on 2月 26, 2018 by Takaaki Naganoya
AppleScript名:選択中のメール本文のHexダンプを取得
— Created 2017-02-25 by Takaaki Naganoya
— 2018 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"

set aMailBody to getSelectedMailBody() of me
if aMailBody = false then error "No Selection"

set theNSString to current application’s NSString’s stringWithString:aMailBody
set aList to hexDumpString(theNSString) of me
return aList

on getSelectedMailBody()
  tell application "Mail"
    set aaSel to selection
    
if aaSel = {} or aaSel = "" then return false
    
    
set aSel to first item of aaSel
    
    
set aCon to content of aSel
    
return aCon
  end tell
end getSelectedMailBody

on hexDumpString(theNSString)
  set theNSData to theNSString’s dataUsingEncoding:(current application’s NSUTF8StringEncoding)
  
set theString to (theNSData’s |description|()’s uppercaseString())
  
  
–Remove "<" ">" characters in head and tail
  
set tLength to (theString’s |length|()) – 2
  
set aRange to current application’s NSMakeRange(1, tLength)
  
set theString2 to theString’s substringWithRange:aRange
  
  
–Replace Space Characters
  
set aString to current application’s NSString’s stringWithString:theString2
  
set bString to aString’s stringByReplacingOccurrencesOfString:" " withString:""
  
  
set aResList to splitString(bString, 2)
  
–> {​​​​​"E3", ​​​​​"81", ​​​​​"82", ​​​​​"E3", ​​​​​"81", ​​​​​"84", ​​​​​"E3", ​​​​​"81", ​​​​​"86", ​​​​​"E3", ​​​​​"81", ​​​​​"88", ​​​​​"E3", ​​​​​"81", ​​​​​"8A"​​​}
  
  
return aResList
end hexDumpString

–Split NSString in specified aNum characters
on splitString(aText, aNum)
  set aStr to current application’s NSString’s stringWithString:aText
  
if aStr’s |length|() ≤ aNum then return aText
  
  
set anArray to current application’s NSMutableArray’s new()
  
set mStr to current application’s NSMutableString’s stringWithString:aStr
  
  
set aRange to current application’s NSMakeRange(0, aNum)
  
  
repeat while (mStr’s |length|()) > 0
    if (mStr’s |length|()) < aNum then
      anArray’s addObject:(current application’s NSString’s stringWithString:mStr)
      
mStr’s deleteCharactersInRange:(current application’s NSMakeRange(0, mStr’s |length|()))
    else
      anArray’s addObject:(mStr’s substringWithRange:aRange)
      
mStr’s deleteCharactersInRange:aRange
    end if
  end repeat
  
  
return (current application’s NSArray’s arrayWithArray:anArray) as list
end splitString

★Click Here to Open This Script 

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

SeleniumでWebサーバー接続のじっけん

Posted on 2月 26, 2018 by Takaaki Naganoya

–> Selenium.framework

AppleScript名:SeleniumでWebサーバー接続テストのじっけん
— Created 2018-02-26 by Takaaki Naganoya
— 2018 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "Selenium" –https://github.com/appium/selenium-objective-c

set aCap to current application’s SECapabilities’s new()
aCap’s setPlatform:"Mac"
aCap’s setBrowserName:"Safari"
aCap’s setVersion:"11.0.3"

–set anIP to ((current application’s NSHost’s hostWithName:"www.apple.com")’s address()) as string

set {errorF, aRes} to current application’s SERemoteWebDriver’s alloc()’s initWithServerAddress:"0.0.0.0" |port|:8080 desiredCapabilities:aCap requiredCapabilities:(missing value) |error|:(reference)

if errorF = missing value then
  return aRes’s |description|() as list of string or string
  
–>  "Error Domain=NSURLErrorDomain Code=-1004 \"サーバに接続できませんでした。\" UserInfo={NSUnderlyingError=0x6000022459d0 {Error Domain=kCFErrorDomainCFNetwork Code=-1004 \"サーバに接続できませんでした。\" UserInfo={NSErrorFailingURLStringKey=http://0.0.0.0:8080/wd/hub/status, NSErrorFailingURLKey=http://0.0.0.0:8080/wd/hub/status, _kCFStreamErrorCodeKey=61, _kCFStreamErrorDomainKey=1, NSLocalizedDescription=サーバに接続できませんでした。}}, NSErrorFailingURLStringKey=http://0.0.0.0:8080/wd/hub/status, NSErrorFailingURLKey=http://0.0.0.0:8080/wd/hub/status, _kCFStreamErrorDomainKey=1, _kCFStreamErrorCodeKey=61, NSLocalizedDescription=サーバに接続できませんでした。}"
end if

★Click Here to Open This Script 

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

Pages書類からPDF書き出し v2

Posted on 2月 25, 2018 by Takaaki Naganoya
AppleScript名:Pages書類からPDF書き出し v2
— Created 2017-03-28 by Takaaki Naganoya
— 2017 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"

set tmpPath to (path to desktop) as string
set aRes to exportPagesDocToPDF(tmpPath)

–Pages書類からPDF書き出し
on exportPagesDocToPDF(targFolderPath as string)
  tell application "Pages"
    set dCount to count every document
    
if dCount = 0 then
      return false
    end if
    
set aPath to file of document 1
  end tell
  
  
set curPath to (current application’s NSString’s stringWithString:(POSIX path of aPath))’s lastPathComponent()’s stringByDeletingPathExtension()’s stringByAppendingString:".pdf"
  
set outPath to (targFolderPath & curPath)
  
  
  
tell application "Pages"
    set anOpt to {class:export options, image quality:Best}
    
export document 1 to file outPath as PDF with properties anOpt
  end tell
end exportPagesDocToPDF

★Click Here to Open This Script 

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

Keynote書類からPDF書き出し v2

Posted on 2月 25, 2018 by Takaaki Naganoya
AppleScript名:Keynote書類からPDF書き出し v2
— Created 2017-01-21 by Takaaki Naganoya
— 2017 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"

set tmpPath to (path to desktop) as string
set aRes to exportKeynoteDocToPDF(tmpPath)

–Keynote書類からPDF書き出し
on exportKeynoteDocToPDF(targFolderPath as string)
  
  
tell application "Keynote"
    set dCount to count every document
    
if dCount = 0 then
      return false
    end if
    
set aPath to file of document 1
  end tell
  
  
set curPath to (current application’s NSString’s stringWithString:(POSIX path of aPath))’s lastPathComponent()’s stringByDeletingPathExtension()’s stringByAppendingString:".pdf"
  
set outPath to (targFolderPath & curPath)
  
  
tell application "Keynote"
    set anOpt to {class:export options, export style:IndividualSlides, all stages:false, skipped slides:true, PDF image quality:Best}
    
export document 1 to file outPath as PDF with properties anOpt
  end tell
  
  
return (outPath as alias)
  
end exportKeynoteDocToPDF

★Click Here to Open This Script 

Keynote Control 1

Keynote Control 2

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

Numbers書類からPDF書き出し v2

Posted on 2月 25, 2018 by Takaaki Naganoya
AppleScript名:Numbers書類からPDF書き出し v2
— Created 2017-03-28 by Takaaki Naganoya
— 2017 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"

set tmpPath to (path to desktop) as string
set aRes to exportNumbersDocToPDF(tmpPath)

–Pages書類からPDF書き出し
on exportNumbersDocToPDF(targFolderPath as string)
  tell application "Numbers"
    set dCount to count every document
    
if dCount = 0 then
      return false
    end if
    
set aPath to file of document 1
  end tell
  
  
set curPath to (current application’s NSString’s stringWithString:(POSIX path of aPath))’s lastPathComponent()’s stringByDeletingPathExtension()’s stringByAppendingString:".pdf"
  
set outPath to (targFolderPath & curPath)
  
  
  
tell application "Numbers"
    set anOpt to {class:export options, image quality:Best}
    
export document 1 to file outPath as PDF with properties anOpt
  end tell
end exportNumbersDocToPDF

★Click Here to Open This Script 

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

Numbers上のデータにもとづいてセル上で色プレビュー

Posted on 2月 25, 2018 by Takaaki Naganoya

–> Demo Movie

AppleScript名:Numbers上のデータにもとづいてセル上で色プレビュー

tell application "Numbers"
  tell front document
    tell active sheet
      tell table 1
        set hCount to header row count
        
set fCount to footer row count
        
        
set aRange to address of row of cell range
        
set bRange to items (1 + hCount) thru ((length of aRange) – fCount) of aRange
        
–> {2, 3, 4, 5, 6}
        
        
repeat with i in bRange
          tell row i
            set vList to value of cells 1 thru 3
            
if vList does not contain missing value then
              set bList to chengeColor255to65535(vList) of me
              
              
ignoring application responses
                tell cell 4
                  set background color to bList
                end tell
              end ignoring
              
            end if
          end tell
        end repeat
      end tell
    end tell
  end tell
end tell

on chengeColor255to65535(aColList)
  set aTmpList to {}
  
repeat with i in aColList
    set the end of aTmpList to i * 256
  end repeat
  
return aTmpList
end chengeColor255to65535

★Click Here to Open This Script 

Posted in Color | Tagged 10.11savvy 10.12savvy 10.13savvy Numbers | Leave a comment

エンコーダーの情報を取得する

Posted on 2月 25, 2018 by Takaaki Naganoya
AppleScript名:エンコーダーの情報を取得する
tell application "iTunes"
  set anEncoder to current encoder
  
set aProp to properties of anEncoder
  
–> {class:encoder, id:63, index:1, name:"AAC Encoder"}
  
  
set encList to every encoder
  
–> {encoder id 63 of application "iTunes", encoder id 60 of application "iTunes", encoder id 61 of application "iTunes", encoder id 62 of application "iTunes", encoder id 59 of application "iTunes"}
  
  
set encnameList to name of every encoder
  
–> {"AAC Encoder", "AIFF Encoder", "Lossless Encoder", "MP3 Encoder", "WAV Encoder"}
  
  
set encPropList to properties of every encoder
  
–> {{class:encoder, id:63, index:1, name:"AAC Encoder"}, {class:encoder, id:60, index:2, name:"AIFF Encoder"}, {class:encoder, id:61, index:3, name:"Lossless Encoder"}, {class:encoder, id:62, index:5, name:"MP3 Encoder"}, {class:encoder, id:59, index:6, name:"WAV Encoder"}}
  
end tell

★Click Here to Open This Script 

iTunes Control

Posted in System | Tagged 10.11savvy 10.12savvy 10.13savvy iTunes | Leave a comment

iTunesライブラリの場所を取得

Posted on 2月 25, 2018 by Takaaki Naganoya
AppleScript名:iTunesライブラリの場所を取得
— Created 2017-01-07 by Takaaki Naganoya
— 2017 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "iTunesLibrary"

set library to current application’s ITLibrary’s libraryWithAPIVersion:"1.0" |error|:(missing value)
if library is equal to missing value then return

set iTunesLibraryLocURL to (library’s musicFolderLocation)’s absoluteString() as string
–>  "file:///Users/me/Music/iTunes/iTunes%20Music/"

set iTunesLibraryLocAlias to (library’s musicFolderLocation) as alias
–>  alias "Cherry:Users:me:Music:iTunes:iTunes Music:"

set iTunesLibraryLocPOSIX to (library’s musicFolderLocation)’s |path|() as string
–>  "/Users/me/Music/iTunes/iTunes Music"

★Click Here to Open This Script 

iTunes Control

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

iTunesライブラリの曲のアーティスト名を集計

Posted on 2月 25, 2018 by Takaaki Naganoya

iTunesライブラリ中の曲のアーティスト名を集計して、曲数が多い順に集計するAppleScriptです。

アーティスト名のFirst NameとLast Nameの間にスペースが存在している場合としていない場合が(iTunes Music Storeからダウンロード購入した曲でも)混在していたので、こうしたデータのゆらぎに対処しています。

6,827曲のライブラリの集計が、筆者の開発環境(MacBook Pro Retina 2012 Core i7 2.66GHz)で2.7秒ぐらいです。

AppleScript名:iTunesライブラリの曲のアーティスト名を集計
— Created 2017-01-07 by Takaaki Naganoya
— 2017 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "iTunesLibrary"

set library to current application’s ITLibrary’s libraryWithAPIVersion:"1.0" |error|:(missing value)
if library is equal to missing value then return

set allTracks to library’s allMediaItems()
set allCount to allTracks’s |count|()

set anEnu to allTracks’s objectEnumerator()
set newArray to current application’s NSMutableArray’s alloc()’s init()

repeat
  set aPL to anEnu’s nextObject()
  
if aPL = missing value then exit repeat
  
try
    set aKind to (aPL’s mediaKind) as integer
    
    
if (aKind as integer) is equal to 2 then –Music, Song
      set plName to aPL’s artist’s |name| as string
      
set pl2Name to (my changeThis:" " toThat:"" inString:plName) –日本語アーティスト名で姓と名の間にスペースが入っているものがある(表記ゆらぎ)ので対策
      
newArray’s addObject:(pl2Name)
    end if
  on error
    set aLoc to (aPL’s location’s |path|()) as string
    
–log aLoc
  end try
end repeat

set aRes to countItemsByItsAppearance(newArray) of me
–>  {​​​​​{​​​​​​​theName:"浜田省吾", ​​​​​​​numberOfTimes:442​​​​​}, ​​​​​{​​​​​​​theName:"B’z", ​​​​​​​numberOfTimes:379​​​​​}, ​​​​​{​​​​​​​theName:"渡辺岳夫・松山祐士", ​​​​​​​numberOfTimes:199​​​​​}, ​​​​​{​​​​​​​theName:"VariousArtists", ​​​​​​​numberOfTimes:192​​​​​}, ​​​​​{​​​​​​​theName:"菅野よう子", ​​​​​​​numberOfTimes:108​​​​​}, ​​​​​{​​​​​​​theName:"布袋寅泰", ​​​​​​​numberOfTimes:100​​​​​}, ​​​​​{​​​​​​​theName:"三枝成彰", ​​​​​​​numberOfTimes:95​​​​​}, ​​​​​{​​​​​​​theName:"宇多田ヒカル", ​​​​​​​numberOfTimes:94​​​​​}, ​​​​​{​​​​​​​theName:"宮川泰", ​​​​​​​numberOfTimes:81​​​​​}, ​​​​​{​​​​​​​theName:"MichaelJackson", ​​​​​​​numberOfTimes:78​​​​​}, ​​​​​{​​​​​​​theName:"稲葉浩志", ​​​​​​​numberOfTimes:73​​​​​}, ​​​​​…

–出現回数で集計
on countItemsByItsAppearance(aList)
  set aSet to current application’s NSCountedSet’s alloc()’s initWithArray:aList
  
set bArray to current application’s NSMutableArray’s array()
  
set theEnumerator to aSet’s objectEnumerator()
  
  
repeat
    set aValue to theEnumerator’s nextObject()
    
if aValue is missing value then exit repeat
    
bArray’s addObject:(current application’s NSDictionary’s dictionaryWithObjects:{aValue, (aSet’s countForObject:aValue)} forKeys:{"theName", "numberOfTimes"})
  end repeat
  
  
–出現回数(numberOfTimes)で降順ソート
  
set theDesc to current application’s NSSortDescriptor’s sortDescriptorWithKey:"numberOfTimes" ascending:false
  
bArray’s sortUsingDescriptors:{theDesc}
  
  
return bArray as list
end countItemsByItsAppearance

on changeThis:findString toThat:repString inString:someText
  set theString to current application’s NSString’s stringWithString:someText
  
set theString to theString’s stringByReplacingOccurrencesOfString:findString withString:repString options:(current application’s NSRegularExpressionSearch) range:{location:0, |length|:length of someText}
  
return theString as text
end changeThis:toThat:inString:

★Click Here to Open This Script 

iTunes Control

Posted in list Record | Tagged 10.11savvy 10.12savvy 10.13savvy ITLibrary iTunes | Leave a comment

なろう小説APIで各カテゴリごとの集計を実行(大カテゴリのみ)

Posted on 2月 24, 2018 by Takaaki Naganoya

–> GZIP.framework

AppleScript名:なろう小説APIで各カテゴリごとの集計を実行(大カテゴリのみ)
— Created 2017-10-10 by Takaaki Naganoya
— 2017 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "GZIP"
–https://github.com/nicklockwood/GZIP
–http://dev.syosetu.com/man/api/
–1日の利用上限は80,000または転送量上限400MByte???

property |NSURL| : a reference to current application’s |NSURL|
property NSString : a reference to current application’s NSString
property NSArray : a reference to current application’s NSArray
property NSUTF8StringEncoding : a reference to current application’s NSUTF8StringEncoding
property NSMutableDictionary : a reference to current application’s NSMutableDictionary
property NSURLQueryItem : a reference to current application’s NSURLQueryItem
property NSURLComponents : a reference to current application’s NSURLComponents
property NSJSONSerialization : a reference to current application’s NSJSONSerialization
property NSMutableURLRequest : a reference to current application’s NSMutableURLRequest
property NSURLConnection : a reference to current application’s NSURLConnection
property NSSortDescriptor : a reference to current application’s NSSortDescriptor
property NSNumber : a reference to current application’s NSNumber
property NSNumberFormatter : a reference to current application’s NSNumberFormatter
property NSNumberFormatterRoundUp : a reference to current application’s NSNumberFormatterRoundUp
property NSNumberFormatterRoundDown : a reference to current application’s NSNumberFormatterRoundDown

set invList to {}

set bgList to {1, 2, 3, 4, 99, 98}
set bigGnereLabel to {"恋愛", "ファンタジー", "文芸", "SF", "その他", "ノンジャンル"}

–全体の件数取得
set aRec to {gzip:"5", out:"json", lim:"1"}
set aRESTres to callNarouAPI(aRec, "1", "1") of me
set wholeCount to (allCount of first item of aRESTres)

–カテゴリごとの集計
repeat with i in bgList
  –repeat with ii in gList
  
set aRec to {gzip:"5", biggenre:i as string, out:"json", lim:"1"}
  
set aRESTres to callNarouAPI(aRec, "1", "1") of me
  
set aTotal to allCount of first item of aRESTres
  
  
if aTotal is not equal to 0 then
    set big to contents of i
    
set bigLabel to getLabelFromNum(bgList, bigGnereLabel, big) of me
    
set aPerCentatge to roundingDownNumStr(((aTotal / wholeCount) * 100), 1) of me
    
set the end of invList to {biggenre:bigLabel, totalNum:aTotal, percentage:aPerCentatge}
  end if
  
–end repeat
end repeat

set bList to sortRecListByLabel(invList, "totalNum", false) of me –降順ソート
–>  {​​​​​{​​​​​​​totalNum:274075, ​​​​​​​percentage:53.1, ​​​​​​​biggenre:"ノンジャンル"​​​​​}, ​​​​​{​​​​​​​totalNum:68890, ​​​​​​​percentage:13.3, ​​​​​​​biggenre:"文芸"​​​​​}, ​​​​​{​​​​​​​totalNum:68426, ​​​​​​​percentage:13.2, ​​​​​​​biggenre:"ファンタジー"​​​​​}, ​​​​​{​​​​​​​totalNum:46165, ​​​​​​​percentage:8.9, ​​​​​​​biggenre:"その他"​​​​​}, ​​​​​{​​​​​​​totalNum:45965, ​​​​​​​percentage:8.9, ​​​​​​​biggenre:"恋愛"​​​​​}, ​​​​​{​​​​​​​totalNum:11733, ​​​​​​​percentage:2.2, ​​​​​​​biggenre:"SF"​​​​​}​​​}

on callNarouAPI(aRec, callFrom, callNum)
  set reqURLStr to "http://api.syosetu.com/novelapi/api/" –通常API
  
  
–set aRec to {gzip:"5", |st|:callFrom as string, out:"json", lim:callNum 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
  
  
set aRESHeader to responseHeader of aRes
  
set aRESTres to (json of aRes) as list
  
end callNarouAPI

–GET methodのREST APIを呼ぶ
on callRestGETAPIAndParseResults(aURL)
  set aRequest to NSMutableURLRequest’s requestWithURL:(|NSURL|’s URLWithString:aURL)
  
aRequest’s setHTTPMethod:"GET"
  
aRequest’s setValue:"gzip" forHTTPHeaderField:"Content-Encoding"
  
  
set aRes to 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 rRes to bRes’s gunzippedData() –From GZIP.framework
  
  
set resStr to NSString’s alloc()’s initWithData:rRes 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 & 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 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 sortRecListByLabel(aRecList as list, aLabelStr as string, ascendF as boolean)
  set aArray to NSArray’s arrayWithArray:aRecList
  
  
set sortDesc to NSSortDescriptor’s alloc()’s initWithKey:aLabelStr ascending:ascendF
  
set sortDescArray to NSArray’s arrayWithObjects:sortDesc
  
set sortedArray to aArray’s sortedArrayUsingDescriptors:sortDescArray
  
  
set bList to sortedArray as list
  
return bList
end sortRecListByLabel

on getLabelFromNum(aList, labelLIst, aNum)
  set aInd to offsetOf(aList, aNum) of me
  
set anItem to contents of item aInd of labelLIst
  
return anItem
end getLabelFromNum

on offsetOf(aList as list, aTarg)
  set aArray to current application’s NSArray’s arrayWithArray:aList
  
set aIndex to aArray’s indexOfObjectIdenticalTo:aTarg
  
return (aIndex + 1)
end offsetOf

on roundingDownNumStr(aNum as string, aDigit as integer)
  set a to NSString’s stringWithString:aNum
  
set aa to a’s doubleValue()
  
set aFormatter to NSNumberFormatter’s alloc()’s init()
  
aFormatter’s setMaximumFractionDigits:aDigit
  
aFormatter’s setRoundingMode:(NSNumberFormatterRoundDown)
  
set aStr to aFormatter’s stringFromNumber:aa
  
return (aStr as text) as real
end roundingDownNumStr

on roundingUpNumStr(aNum as string, aDigit as integer)
  set a to NSString’s stringWithString:aNum
  
set aa to a’s doubleValue()
  
set aFormatter to NSNumberFormatter’s alloc()’s init()
  
aFormatter’s setMaximumFractionDigits:aDigit
  
aFormatter’s setRoundingMode:(NSNumberFormatterRoundUp)
  
set aStr to aFormatter’s stringFromNumber:aa
  
return (aStr as text) as real
end roundingUpNumStr

★Click Here to Open This Script 

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

日の出、日没時刻を計算するv2

Posted on 2月 24, 2018 by Takaaki Naganoya

EDSunriseSetを用いて、指定の位置における日の出、日没時間を計算するAppleScriptです。

–> EDSunriseSet.framework(~/Library/Frameworks)

AppleScript名:日の出、日没時刻を計算するv2
— Created 2017-06-19 by Takaaki Naganoya
— 2017 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "EDSunriseSet" –https://github.com/erndev/EDSunriseSet

set cityRecList to {{kCityName:"Tokyo", kCityLatitude:(35.6894875), kCityLongitude:(139.6917064), kCityTimeZone:"Asia/Tokyo"}}

set dList to {}

repeat with i in cityRecList
  set the end of dList to getSunriseSunset(i) of me
end repeat
return dList
–>  {​​​​​{​​​​​​​sunrise:date "2017年6月21日水曜日 4:25:37", ​​​​​​​sunset:date "2017年6月21日水曜日 19:00:21", ​​​​​​​civilTwilightStart:date "2017年6月21日水曜日 3:55:35", ​​​​​​​civilTwilightEnd:date "2017年6月21日水曜日 19:30:23", ​​​​​​​nauticalTwilightStart:date "2017年6月21日水曜日 3:18:15", ​​​​​​​nauticalTwilightEnd:date "2017年6月21日水曜日 20:07:44", ​​​​​​​astronomicalTwilightStart:date "2017年6月21日水曜日 2:36:45", ​​​​​​​astronomicalTwilightEnd:date "2017年6月21日水曜日 20:49:13", ​​​​​​​cityname:"Tokyo"​​​​​}​​​}

on getSunriseSunset(cityRec)
  set curLocale to current application’s NSLocale’s currentLocale()
  
set curDate to current application’s NSDate’s |date|()
  
  
set aTZ to current application’s NSTimeZone’s alloc()’s initWithName:(kCityName of cityRec)
  
set aSunrizeSunset to current application’s EDSunriseSet’s alloc()’s initWithDate:curDate timezone:aTZ latitude:(kCityLatitude of cityRec) longitude:(kCityLongitude of cityRec)
  
  
–日の出、日没  
  
set aSunRiseDate to (aSunrizeSunset’s sunrise) as date
  
set aSunSetDate to (aSunrizeSunset’s sunset) as date
  
  
–https://en.wikipedia.org/wiki/Twilight
  
–https://ja.wikipedia.org/wiki/薄明
  
  
–市民薄明(常用薄明、第三薄明)
  
set aCivilTwilightStart to (aSunrizeSunset’s civilTwilightStart) as date
  
set aCivilTwilightEnd to (aSunrizeSunset’s civilTwilightEnd) as date
  
  
–航海薄明(第二薄明)
  
set aNauticalTwilightStart to (aSunrizeSunset’s nauticalTwilightStart) as date
  
set aNauticalTwilightEnd to (aSunrizeSunset’s nauticalTwilightEnd) as date
  
  
–天文薄明(第一薄明)
  
set anAstronomicalTwilightStart to (aSunrizeSunset’s astronomicalTwilightStart) as date
  
set anAstronomicalTwilightEnd to (aSunrizeSunset’s astronomicalTwilightEnd) as date
  
  
return {sunrise:aSunRiseDate, sunset:aSunSetDate, civilTwilightStart:aCivilTwilightStart, civilTwilightEnd:aCivilTwilightEnd, nauticalTwilightStart:aNauticalTwilightStart, nauticalTwilightEnd:aNauticalTwilightEnd, astronomicalTwilightStart:anAstronomicalTwilightStart, astronomicalTwilightEnd:anAstronomicalTwilightEnd, cityname:kCityName of cityRec}
end getSunriseSunset

★Click Here to Open This Script 

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

2つの日付の期間を日本語表記でていねいに返す

Posted on 2月 24, 2018 by Takaaki Naganoya
AppleScript名:2つの日付の期間を日本語表記でていねいに返す
— Created 2016-01-17 by Takaaki Naganoya
— 2016 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"

–Date Difference
set sDate to "2016/1/15" –Japanese Date format "YYYY/MM/DD"
set eDate to "2016/1/20" –Japanese Date format "YYYY/MM/DD"
set aDiffStr to retDateDiffStr(sDate, eDate, "/", "/", "", "〜") of me
–> "2016/1/15〜20"

–Month Difference
set sDate to "2016/1/15" –Japanese Date format "YYYY/MM/DD"
set eDate to "2016/2/20" –Japanese Date format "YYYY/MM/DD"
set bDiffStr to retDateDiffStr(sDate, eDate, "年", "月", "日", "〜") of me
–> "2016年1月15日〜2月20日"

–Year Difference
set sDate to "2015/12/15" –Japanese Date format "YYYY/MM/DD"
set eDate to "2016/1/20" –Japanese Date format "YYYY/MM/DD"
set bDiffStr to retDateDiffStr(sDate, eDate, "年", "月", "日", "〜") of me
–> "2015年12月15日〜2016年1月20日"

–2つの日付の期間を日本語表記でていねいに返す
on retDateDiffStr(sDate, eDate, ySeparator, mSeparator, dSeparator, diffSeparator)
  
  
set sDateO to date sDate
  
set eDateO to date eDate
  
  
set diffY to (year of eDateO) – (year of sDateO)
  
set diffM to (month of eDateO) – (month of sDateO)
  
set diffD to (day of eDateO) – (day of sDateO)
  
  
set sYstr to (year of sDateO) as string
  
set sMstr to (month of sDateO as number) as string
  
set sDstr to (day of sDateO) as string
  
  
set eYstr to (year of eDateO) as string
  
set eMstr to (month of eDateO as number) as string
  
set eDstr to (day of eDateO) as string
  
  
if diffY > 0 then
    –Year Difference
    
set outStr to sYstr & ySeparator & sMstr & mSeparator & sDstr & dSeparator & diffSeparator & eYstr & ySeparator & eMstr & mSeparator & eDstr & dSeparator
  else if diffM > 0 then
    –Month Difference
    
set outStr to sYstr & ySeparator & sMstr & mSeparator & sDstr & dSeparator & diffSeparator & eMstr & mSeparator & eDstr & dSeparator
  else if diffD > 0 then
    –Date Difference
    
set outStr to sYstr & ySeparator & sMstr & mSeparator & sDstr & diffSeparator & eDstr & dSeparator
  end if
  
  
return outStr
  
end retDateDiffStr

★Click Here to Open This Script 

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

getMlenInternational_ASOC

Posted on 2月 24, 2018 by Takaaki Naganoya

年と月を数値で指定した対象月の日数を計算するAppleScriptです。国際化対応バージョンです。

AppleScriptで日付(date)関連の処理を行うと、どうしても言語依存してしまいがちです。

つまり、日本語環境で作ったAppleScriptをその他の言語環境に持って行ったときに、あるいは逆に英語圏で作られたAppleScriptでまっさきに書き換える必要が出てくるのが、日付関連処理です(その次ぐらいにApple純正アプリケーションの「過剰ローカライズ」によりAppleScriptのオブジェクト名までローカライズされてしまうので、その点を書き換えるとか)。

日本語環境以外で通じる処理を書くというのは、けっこう練習が必要です。ただ、国際化対応の処理をいったん書いておけば、二度目からはその処理を使い回すだけです。

そんな、言語環境非依存で真っ先に必要になってくる、指定月の日数計算を書いたものです。少なくとも、Mac App Storeに出すアプリケーションを書くのであれば、こうした他の言語環境でも動作するルーチンを整備しておく必要があります。

AppleScript名:getMlenInternational_ASOC
— Created 2015-02-02 by Shane Stanley
— Modified 2015-02-02 by Takaaki Naganoya
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"

set mList to {}
repeat with m from 1 to 12
  set the end of mList to getMlenInternational(2012, m) of me –2012 is a Leap Year–2012年はうるう年
end repeat
mList
–>  {​​​​​31, ​​​​​29, ​​​​​31, ​​​​​30, ​​​​​31, ​​​​​30, ​​​​​31, ​​​​​31, ​​​​​30, ​​​​​31, ​​​​​30, ​​​​​31​​​}

–現在のカレンダーで指定年月の日数を返す
on getMlenInternational(aYear, aMonth)
  –From Shane’s getMlenInternational(ASOC) v1
  
set theNSCalendar to current application’s NSCalendar’s currentCalendar() — do *not* use initWithCalendarIdentifier:
  
set theDate to theNSCalendar’s dateWithEra:1 |year|:aYear |month|:aMonth |day|:1 hour:0 minute:0 |second|:0 nanosecond:0
  
set theResult to theNSCalendar’s rangeOfUnit:(current application’s NSDayCalendarUnit) inUnit:(current application’s NSMonthCalendarUnit) forDate:theDate
  
–>  {location:1, length:31}
  
return |length| of theResult
end getMlenInternational

★Click Here to Open This Script 

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

数値の秒を文字フォーマットして返す

Posted on 2月 24, 2018 by Takaaki Naganoya
AppleScript名:数値の秒を文字フォーマットして返す
— Created 2016-02-09 by Takaaki Naganoya
— 2016 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"

set aStr to formatTimeNum(61) of me
–> "01分 01秒"

set bStr to formatTimeNum(3700) of me
–> "01時間 01分 40秒"

set cStr to formatTimeNum(9100) of me
–> "02時間 31分 40秒"

set dStr to formatTimeNum(720001) of me
–>"200時間 00分 01秒"

set eStr to formatTimeNum(7200001) of me
–>"2000時間 00分 01秒"

–数値の秒を文字フォーマットして返す
on formatTimeNum(a)
  set hourStr to "時間 "
  
set minuteStr to "分 "
  
set secStr to "秒"
  
  
set aRec to separateSec(a) of me
  
set aStr to ""
  
set anHour to hourNum of aRec
  
set aMinute to minuteNum of aRec
  
set aSec to secondNum of aRec
  
  
if anHour > 0 then
    set aStr to aStr & retZeroPaddingText(anHour, 2) of me & hourStr
    
set aStr to aStr & retZeroPaddingText(aMinute, 2) of me & minuteStr
  else if aMinute > 0 then
    set aStr to aStr & retZeroPaddingText(aMinute, 2) of me & minuteStr
  end if
  
set aStr to aStr & retZeroPaddingText(aSec, 2) of me & secStr
  
  
return aStr
end formatTimeNum

—数値の秒を時、分、秒に分解する
on separateSec(a)
  set anHour to a div 3600
  
set b to a – (anHour * 3600)
  
set aMinute to b div 60
  
set c to b – (aMinute * 60)
  
return {hourNum:anHour, minuteNum:aMinute, secondNum:c}
end separateSec

–ゼロパディング
on retZeroPaddingText(aNum as integer, aDigitNum as integer)
  if aNum > (((10 ^ aDigitNum) as integer) – 1) then
    return aNum as string –指定桁数を数値データがオーバーしたら数値を文字化してそのまま返す
  end if
  
set aFormatter to current application’s NSNumberFormatter’s alloc()’s init()
  
aFormatter’s setUsesGroupingSeparator:false
  
aFormatter’s setAllowsFloats:false
  
aFormatter’s setMaximumIntegerDigits:aDigitNum
  
aFormatter’s setMinimumIntegerDigits:aDigitNum
  
aFormatter’s setPaddingCharacter:"0"
  
set aStr to aFormatter’s stringFromNumber:(current application’s NSNumber’s numberWithFloat:aNum)
  
return aStr as string
end retZeroPaddingText

★Click Here to Open This Script 

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

午前午後のローカライズ名称を返す

Posted on 2月 24, 2018 by Takaaki Naganoya
AppleScript名:午前午後のローカライズ名称を返す
— Created 2017-12-19 01:14:42 +0900 by Takaaki Naganoya
— 2017 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"

set bList to getLocalizedAMSymbol("ja_JP") of me
–>  "午前"

set bList to getLocalizedPMSymbol("ja_JP") of me
–>  "午後"

–ローカライズされた午前の名称を返す
on getLocalizedAMSymbol(aLoc)
  set df to current application’s NSDateFormatter’s alloc()’s init()
  
df’s setLocale:(current application’s NSLocale’s localeWithLocaleIdentifier:aLoc)
  
set dayNames to df’s AMSymbol()
  
return dayNames as string
end getLocalizedAMSymbol

–ローカライズされた午後の名称を返す
on getLocalizedPMSymbol(aLoc)
  set df to current application’s NSDateFormatter’s alloc()’s init()
  
df’s setLocale:(current application’s NSLocale’s localeWithLocaleIdentifier:aLoc)
  
set dayNames to df’s PMSymbol()
  
return dayNames as string
end getLocalizedPMSymbol

★Click Here to Open This Script 

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

元号変換v31

Posted on 2月 24, 2018 by Takaaki Naganoya
AppleScript名:元号変換v31
set a to "2010/7/21"
set a to parseDate(a) of me
set {aGengoStr, aGengoNum} to retJapaneseGengo(a) of me
–> {"平成", 22}

on retJapaneseGengo(aDate)
  
  
set aYear to year of aDate
  
set aMonth to month of aDate as number
  
set aDay to day of aDate
  
  
set aStr to retZeroPaddingText(aYear, 4) of me & retZeroPaddingText(aMonth, 2) of me & retZeroPaddingText(aDay, 2) of me
  
  
set aGengo to ""
  
if aStr ≥ "19890108" then
    set aGengo to "平成"
    
set aGengoNum to aYear – 1989 + 1
  else if aStr ≥ "19261225" then
    set aGengo to "昭和"
    
set aGengoNum to aYear – 1926 + 1
  else if aStr ≥ "19120730" then
    set aGengo to "大正"
    
set aGengoNum to aYear – 1912 + 1
  else if aStr ≥ "18680125" then
    set aGengo to "明治"
    
set aGengoNum to aYear – 1868 + 1
  end if
  
  
return {aGengo, aGengoNum}
  
end retJapaneseGengo

–数値にゼロパディングしたテキストを返す
on retZeroPaddingText(aNum, aLen)
  set tText to ("0000000000" & aNum as text)
  
set tCount to length of tText
  
set resText to text (tCount – aLen + 1) thru tCount of tText
  
return resText
end retZeroPaddingText

on parseDate(inStr)
  set aClass to class of inStr
  
if aClass = string then
    try
      set aDate to date inStr
    on error
      return false
    end try
  else if aClass = date then
    set aDate to inStr
    
  end if
  
  
return aDate
  
end parseDate

★Click Here to Open This Script 

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

Post navigation

  • Older posts
  • Newer posts

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

Google Search

Popular posts

  • macOS 13, Ventura(継続更新)
  • アラートダイアログ上にWebViewで3Dコンテンツを表示(WebGL+three.js)v3
  • Xcode 14.2でAppleScript App Templateを復活させる
  • UI Browserがgithub上でソース公開され、オープンソースに
  • macOS 13 TTS Voice環境に変更
  • 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できない問題
  • 新発売:iWork Scripting Book with AppleScript
  • ChatGPTでchatに対する応答文を取得
  • 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 (186) 13.0savvy (59) CotEditor (60) Finder (47) iTunes (19) Keynote (99) NSAlert (60) NSArray (51) NSBezierPath (18) NSBitmapImageRep (20) NSBundle (20) NSButton (34) NSColor (51) NSDictionary (27) NSFileManager (23) NSFont (18) NSImage (41) NSJSONSerialization (21) NSMutableArray (62) NSMutableDictionary (21) NSPredicate (36) NSRunningApplication (56) NSScreen (30) NSScrollView (22) NSString (117) NSURL (97) NSURLRequest (23) NSUTF8StringEncoding (30) NSView (33) NSWorkspace (20) Numbers (57) Pages (38) Safari (41) Script Editor (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