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

カテゴリー: URL

指定アプリケーションの指定言語のstringsファイルの内容をすべて取り出す

Posted on 9月 21, 2019 by Takaaki Naganoya

バンドルIDで指定したアプリケーションのResourcesフォルダ中の、指定ロケールのstringsファイルをすべて読み込んでkeyを取り出すAppleScriptです。

アプリケーション内の指定のローカライズしたメッセージ(テキスト)の内容を取り出すことはできますが、そのためにはキーを知っておく必要があります。そのキーを取り出してローカライズされた文字列を取り出すため、キーを調査してみました。

これをそのまま何かのツールなりScriptに使うというものではなく、いわゆる「下調べ」のためのScriptの部品です。

ほぼ、ありもののルーチンを再利用しただけのプログラムでできていますが、ありものはありもので、数千本のAppleScriptのストックからそれを探し出してくるのも一苦労です。

アプリケーションバンドル内のResourcesフォルダ以下の(各lprojフォルダ以下の)stringsファイルの中身はまんま(シリアライズした)NSDictionaryなので、そのままDictionaryに読み込んでallkey()などのメソッドを実行できます。昔のstringsファイルはテキストファイルだったような気がしますが、テキストファイルだとparseしないといけないんで、ビルド時にparseしておいてDictionaryの状態でファイルに書いておくのは正しいと思います。

Xcode 8あたりから、アプリケーションのローカライズのルールが変更になったようで、基本となる言語環境がBase.lprojになり、英語はen.lprojといった1ローカライズ言語という位置付けに変更になりました。

NSLocalizedStringFromTableInBundleを使ってアクセスしようかとも思ったのですが、こちらはまだ目的を達成できていません。


▲Xcode 11上で実験的に作成したAppleScriptアプリケーションのバンドル構造(左)。ローカライズしていない状態だとEnglishではなくBase.lprojが作成される。右はKeynote.app/Contents/Resources/ja.lprojフォルダの内容。stringsファイルが大量に存在している

AppleScript名:指定アプリケーションの指定言語のstringsファイルの内容をすべて取り出す.scptd
—
–  Created by: Takaaki Naganoya
–  Created on: 2019/09/21
—
–  Copyright © 2019 Piyomaru Software, All Rights Reserved
—
use AppleScript version "2.5"
use scripting additions
use framework "Foundation"

property |NSURL| : a reference to current application’s |NSURL|
property NSArray : a reference to current application’s NSArray
property NSBundle : a reference to current application’s NSBundle
property NSPredicate : a reference to current application’s NSPredicate
property NSDictionary : a reference to current application’s NSDictionary
property NSWorkspace : a reference to current application’s NSWorkspace
property NSFileManager : a reference to current application’s NSFileManager
property NSMutableDictionary : a reference to current application’s NSMutableDictionary
property NSURLTypeIdentifierKey : a reference to current application’s NSURLTypeIdentifierKey
property NSDirectoryEnumerationSkipsHiddenFiles : a reference to current application’s NSDirectoryEnumerationSkipsHiddenFiles
property NSDirectoryEnumerationSkipsPackageDescendants : a reference to current application’s NSDirectoryEnumerationSkipsPackageDescendants

set targID to "com.apple.iWork.Keynote"

set bRes to getLocalizationsFromBundleID(targID) of me
–>  {"de", "he", "en_AU", "ar", "el", "ja", "en", "uk", "es_419", "zh_CN", "es", "da", "it", "sk", "pt_PT", "ms", "sv", "cs", "ko", "Base", "no", "hu", "zh_HK", "tr", "pl", "zh_TW", "en_GB", "vi", "ru", "fr_CA", "fr", "fi", "id", "nl", "th", "pt", "ro", "hr", "hi", "ca"}

set curLang to first item of (choose from list bRes)
set aPath to retPathFromBundleID(targID) of me

set aPath to aPath & "/Contents/Resources/" & curLang & ".lproj"
set sList to getFilepathListByUTI(aPath, "com.apple.xcode.strings-text", "POSIX") of me

set aMDict to NSMutableDictionary’s new()

repeat with i in sList
  set j to contents of i
  
set aDict to (NSDictionary’s alloc()’s initWithContentsOfFile:j)
  (
aMDict’s addEntriesFromDictionary:aDict)
end repeat

return aMDict’s allKeys() as list
–> {"Interactive Bubble Chart", "Rehearse Slideshow", "PMT_ARGUMENT_1", "ACCRINTM_ARGUMENT_4_MODE_0", "Truck_378",….}

on getLocalizationsFromBundleID(aBundleID)
  set aRes to retPathFromBundleID(aBundleID) of me
  
if aRes = false then error "Wrong Bundle ID."
  
return getSpecifiedAppFilesLocalizationListWithDuplication(aRes) of me
end getLocalizationsFromBundleID

–指定アプリケーションファイルの、指定Localeにおけるローカライズ言語リストを求める。重複を許容
on getSpecifiedAppFilesLocalizationListWithDuplication(appPOSIXpath)
  set aURL to (|NSURL|’s fileURLWithPath:appPOSIXpath)
  
set aBundle to NSBundle’s bundleWithURL:aURL
  
set locList to aBundle’s localizations()
  
return locList as list
end getSpecifiedAppFilesLocalizationListWithDuplication

on retPathFromBundleID(aBundleID)
  set aURL to NSWorkspace’s sharedWorkspace()’s URLForApplicationWithBundleIdentifier:aBundleID
  
if aURL = missing value then return false –Error
  
return aURL’s |path|() as string
end retPathFromBundleID

on getFilepathListByUTI(aFolPOSIX, aUTI as string, aFileType as string)
  script spdFile
    property urlList : {}
  end script
  
  
if aFileType is not in {"file", "POSIX"} then return {}
  
  
set aFM to NSFileManager’s defaultManager()
  
set aFolExt to (aFM’s fileExistsAtPath:aFolPOSIX isDirectory:true) as boolean
  
if aFolExt = false then return {} –フォルダ自体が存在しなければヌルリストを返す
  
  
set aURL to |NSURL|’s fileURLWithPath:aFolPOSIX
  
set theOptions to ((NSDirectoryEnumerationSkipsPackageDescendants) as integer) + ((NSDirectoryEnumerationSkipsHiddenFiles) as integer)
  
set urlArray to (aFM’s contentsOfDirectoryAtURL:aURL includingPropertiesForKeys:{} options:theOptions |error|:(missing value))
  
if urlArray = missing value then return {}
  
  
set (urlList of spdFile) to urlArray as list
  
set newList to {}
  
  
repeat with i in (urlList of spdFile)
    set j to POSIX path of i
    
set tmpUTI to my retUTIfromPath(j)
    
set utiRes to my filterUTIList({tmpUTI}, aUTI)
    
    
if utiRes is not equal to {} then
      if aFileType = "POSIX" then
        set the end of newList to j
      else if aFileType = "file" then
        set the end of newList to POSIX file j
      end if
    end if
    
  end repeat
  
  
return newList
end getFilepathListByUTI

–指定のPOSIX pathのファイルのUTIを求める
on retUTIfromPath(aPOSIXPath)
  set aURL to |NSURL|’s fileURLWithPath:aPOSIXPath
  
set {theResult, theValue} to aURL’s getResourceValue:(reference) forKey:NSURLTypeIdentifierKey |error|:(missing value)
  
  
if theResult = true then
    return theValue as string
  else
    return theResult
  end if
end retUTIfromPath

–UTIリストが指定UTIに含まれているかどうか演算を行う
on filterUTIList(aUTIList, aUTIstr)
  set anArray to NSArray’s arrayWithArray:aUTIList
  
set aPred to NSPredicate’s predicateWithFormat_("SELF UTI-CONFORMS-TO %@", aUTIstr)
  
set bRes to (anArray’s filteredArrayUsingPredicate:aPred) as list
  
return bRes
end filterUTIList

★Click Here to Open This Script 

Posted in file Record URL UTI | Tagged 10.12savvy 10.13savvy 10.14savvy NSArray NSBundle NSDictionary NSDirectoryEnumerationSkipsHiddenFiles NSDirectoryEnumerationSkipsPackageDescendants NSFileManager NSMutableDictionary NSPredicate NSURL NSURLTypeIdentifierKey NSWorkspace | Leave a comment

htmlの並列ダウンロード処理

Posted on 9月 13, 2019 by Takaaki Naganoya

Webコンテンツ(HTML)の並列ダウンロードを行うAppleScriptです。

Webコンテンツからデータを抽出する際に、あらかじめ一括でHTMLを並列ダウンロードしておいて、ダウンロードずみのデータを一括処理すると処理時間を大幅に短縮できます。「戦場の絆」Wikiから機体データの表をすべて取得するのに、順次HTMLを取得して抽出していた場合には3〜4分程度かかっていたものを、並列ダウンロードしたのちにデータ処理するように変更すれば、これが十数秒程度にまで高速化できます。

既存のプログラムを修正してHTMLのダウンロード用に仕立ててみました。並列キュー(未処理タスク数)へのアクセスはAppleScriptからはできなかった(実行すると結果が返ってこなかった)のですが、そこに手をつけずに並列処理の完了状態を検出しています。

ダウンロードが完了したデータはlist(配列)に入るので、リクエスト数と完了リクエスト数をループ内でチェックし、完了アイテム数がリクエスト数と同じになれば終了、条件を満たさない場合でも指定のタイムアウト時間を超えたらエラー終了という処理を行なっています。

問題点は、スクリプトエディタ上では実行できるもののScript Debugger上では実行できないことです(結果が返ってきません)。AppleScriptアプレットに書き出して実行してみたところ、結果が返ってきません。ただし、Script Menuからの実行は行えます(macOS 10.12.6、10.13.6、10.14.6で同様)。XcodeのAppleScript Appのプロジェクト内で実行することはできました。

このように、ランタイム環境に実行状況が左右される点にご注意ください。ただし、そうしたマイナス面を補ってあまりあるほどダウンロードは高速です。90ファイル強のダウンロードを数秒で完了(マシン、ネットワーク速度、ダウンロード先サーバーの負荷状況、キャッシュ状態などに左右される、参考値です)するため、ダウンロード後に各HTMLからのデータ抽出も高速に行えます。

AppleScript名:htmlの並列ダウンロード処理
— Created 2019-09-13 by Takaaki Naganoya
— 2019 Piyomaru Software
—
– オリジナル: HTTP からファイルをダウンロードして、ローカルに保存する方法(shintarou_horiのブログ)
— http://shintarou-hori.hatenablog.com/entry/2014/03/15/193604

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 NSOperationQueue : a reference to current application’s NSOperationQueue
property NSInvocationOperation : a reference to current application’s NSInvocationOperation
property NSUTF8StringEncoding : a reference to current application’s NSUTF8StringEncoding

property aTimer : missing value

script spd
  property mList : {}
  
property resList : {}
end script

set (mList of spd) to {}
set (resList of spd) to {}
set baseURL to "https://w.atwiki.jp/senjounokizuna/pages/"

set numList to {25, 1594, 890, 70, 1669, 82, 1717, 997, 1080, 1614, 1712, 159, 1311, 1694, 1752, 1263}

set urlList to {}
repeat with i in numList
  set the end of urlList to (baseURL & i as string) & ".html"
end repeat

set aLen to length of urlList
set paramObj to {urls:urlList, timeOutSec:60}

–set (resList of spd) to downloadHTMLConcurrently(urlList, 60) of me
my performSelectorOnMainThread:"downloadHTMLConcurrently:" withObject:(paramObj) waitUntilDone:true
return length of (mList of spd)

on downloadHTMLConcurrently:paramObj
  set urlList to (urls of paramObj) as list
  
set timeOutS to (timeOutSec of paramObj) as real
  
set aLen to length of urlList
  
  
repeat with i in urlList
    set j to contents of i
    
set aURL to (|NSURL|’s URLWithString:j)
    
set aQueue to NSOperationQueue’s new()
    
set aOperation to (NSInvocationOperation’s alloc()’s initWithTarget:me selector:"execDL:" object:aURL)
    (
aQueue’s addOperation:aOperation)
  end repeat
  
  
–Check Completion
  
set compF to false
  
set loopTimes to (timeOutS * 10)
  
repeat loopTimes times
    if length of (mList of spd) = aLen then
      set compF to true
      
exit repeat
    end if
    
delay 0.1
  end repeat
  
  
if compF = false then error "Concurrent download timed out"
end downloadHTMLConcurrently:

on execDL:theURL
  set receiveData to NSData’s alloc()’s initWithContentsOfURL:theURL
  
if receiveData = missing value then
    return
  end if
  
  
set aFileName to theURL’s |lastPathComponent|()
  
my performSelectorOnMainThread:"saveData:" withObject:{receiveData, aFileName} waitUntilDone:false
end execDL:

on saveData:theDataArray
  copy theDataArray to {theData, saveFileName}
  
set aCon to NSString’s alloc()’s initWithData:theData encoding:NSUTF8StringEncoding
  
set the end of (mList of spd) to {fileName:saveFileName as string, contentsData:aCon as string}
end saveData:

★Click Here to Open This Script 

Posted in list Network URL | Tagged 10.12savvy 10.13savvy 10.14savvy NSData NSInvocationOperation NSOperationQueue NSString NSURL NSUTF8StringEncoding | Leave a comment

display table Script Library

Posted on 9月 7, 2019 by Takaaki Naganoya

2D List(二次元配列)データを気軽に表UIでプレビューするUser Interfaceを提供するdisplay table Script Library+サンプルコードです。

–> Download displayTable.scptd (To ~/Library/Script Libraries/)

表UIを提供する部品としては、Shane StanleyのMyriad Tables Libが存在しており、ひじょうに充実した機能を備えているため、同様でかつ機能が低いものを提供する必要はないはずです。

ですが、同ライブラリはバンドル内にFrameworkを含んでおり、SIPによる機能制限でそのままではmacOS 10.14以降の環境ではこのライブラリを(スクリプトエディタでは)呼べないなどの問題があります。ホームディレクトリ以下のFrameworkのバイナリを呼べないわけです。Script Debuggerを使ったり、アプレットとして書き出せばクリアできるものの、利用シーンが限定されるきらいがありました(このあたり、GUIなしのsdefつきアプリケーションとして仕立ててライブラリのバンドル内に入れれば回避できるのではないかと思っていますが、どうなりますやら)。

そこで、2D List(二次元配列)データのプレビューなど、最低限の機能をそなえたライブラリを(主に自分用に)作ってみたものです。もともと、NSTableViewで表示するためには2D List(2次元配列)ではなくRecord in List(行ごとに各フィールドが属性ラベルの付いたRecord)になっている必要があります。この、2D List → Record in Listの変換処理が面倒なので、その部分を中心に、汎用部品として使えるように機能をまとめてみました。

NSTableViewの各セルのタイトルをRecord in Listの各ラベル値に設定しており、上記のデータは、

(NSArray) {
	{
		ダッシュ時間:"2.2cnt",
		ダッシュ距離:"?m",
		タックルダメージ:"20",
		ダッシュ速度:"208km/h",
		ジャンプ速度:"167km/h",
		硬直時間:"38f",
		セッティング名:"旋(旋回)    ",
		アーマー値:"284",
		歩行速度:"100km/h",
		旋回速度:"10.9rpm",
		備考:""
	},

...........

	{
		ダッシュ時間:"2.1cnt",
		ダッシュ距離:"?m",
		タックルダメージ:"20",
		ダッシュ速度:"180km/h",
		ジャンプ速度:"144km/h",
		硬直時間:"38f",
		セッティング名:"装(装甲)    ",
		アーマー値:"343",
		歩行速度:"100km/h",
		旋回速度:" 9.7rpm",
		備考:""
	}
}

という、日本語の属性ラベルのついたRecord(Dictionary)に変換・表示しています。

dialog上のアイコン表示部品を画像のプレビュー用に使ってみたりと、例によって好き放題やっていますが、アイコン関連のファイルパス/URLを指定しなければ通常の動作を行います。

AppleScript名:display table by list sample
—
–  Created by: Takaaki Naganoya
–  Created on: 2019/08/25
—
–  Copyright © 2019 jp.piyomarusoft, All Rights Reserved
—
use AppleScript version "2.5" — El Capitan (10.11) or later
use framework "Foundation"
use scripting additions

use easyTable : script "display table by list"

set msURL to "http://web.gundam-kizuna.jp/sp/image/index/img/p/QBP89Z-T_2o62sJWBQC7BSsw08wZuZ28keecHZs9Io4"

set aList to {{"旋(旋回) ", "284", "208km/h", "2.2cnt", "?m", "167km/h", "10.9rpm", "38f", "20", "100km/h", ""}, {"硬(硬直減) ", "286", "206km/h", "2.1cnt", "?m", "165km/h", "10.3rpm", "34f", "20", "100km/h", ""}, {"歩(歩行) ", "293", "206km/h", "2.2cnt", "?m", "165km/h", "10.3rpm", "38f", "20", "111km/h", ""}, {"跳(ジャンプ)", "263", "202km/h", "2.1cnt", "?m", "183km/h", "10.3rpm", "39f", "20", "100km/h", ""}, {"走(ダッシュ)", "248", "224km/h", "2.3cnt", "?m", "161km/h", "10.3rpm", "40f", "20", "100km/h", ""}, {"機(機動) ", "243", "216km/h", "2.2cnt", "?m", "177km/h", "10.6rpm", "39f", "20", "100km/h", ""}, {"推(ブースト)", "296", "196km/h", "2.4cnt", "?m", "157km/h", "10.0rpm", "38f", "20", "100km/h", ""}, {"突(タックル)", "298", "190km/h", "2.1cnt", "?m", "152km/h", " 9.7rpm", "38f", "30", "100km/h", ""}, {"装(装甲) ", "343", "180km/h", "2.1cnt", "?m", "144km/h", " 9.7rpm", "38f", "20", "100km/h", ""}}

set fLabels to {"セッティング名", "アーマー値", "ダッシュ速度", "ダッシュ時間", "ダッシュ距離", "ジャンプ速度", "旋回速度", "硬直時間", "タックルダメージ", "歩行速度", "備考"}

set aRes to (display table by list aList main message "項目の選択" sub message "適切なものを以下からえらんでください" size {1200, 400} labels fLabels icon msURL timed out 5)

★Click Here to Open This Script 

Posted in GUI Script Libraries sdef URL | Tagged 10.12savvy 10.13savvy 10.14savvy | Leave a comment

display youtube Script Libraryをアップデート

Posted on 9月 7, 2019 by Takaaki Naganoya

一発芸、出落ちと呼ばれた「display youtube」Script libraryをアップデート(v2.0)しました。

Download display youtube_v2.scptd (To ~/Library/Script Libraries/)

アップデート内容:
・AppleScript用語辞書内にサンプルScript(すぐに使えるScriptリンク内蔵)を掲載した
・start fromオプションを新設。再生開始位置を秒数で指定できるようにした
・エラーメッセージ内容をより親切にした

利用条件:
・YouTubeのムービーを視聴可能な程度のインターネット接続回線に接続していること
・macOS 10.11以降。実際の確認はmacOS 10.12以降。未確認ながら10.10上でも動作するはず

display youtubeライブラリの用語辞書を読むには、スクリプトエディタ上で、


▲「ウィンドウ」から「ライブラリ」を実行


▲「ライブラリ」パレットに「display youtube」ライブラリファイルをドラッグ&ドロップ。このライブラリパレット上のdisplay youtubeをダブルクリックすると用語辞書が表示されます


▲starts from無指定時(冒頭から再生)


▲starts from 24(冒頭から24秒の箇所から再生)


▲starts from 290(冒頭から290秒の箇所から再生)

YouTube上のオンラインゲームのリプレイムービーを視聴するような場合には、ムービー内容のうちスキップしたい場所とか「ここだけ見たい」という箇所は固定で決まっています(プログラムから書き出してYouTubeにアップロードするため)。そこで、再生開始ポジションを明示的に指定できると便利かと思われました。

ほかにも、いろいろと追加すると便利そうな機能はあります(未実装)。

いくつかボタンをダイアログ上に追加表示して、指定の秒数の箇所に頭出しするとか、表示内容のキャプチャーを撮るとかです(WkWebViewの表示内容を画像としてキャプチャする方法がぜんぜん不明。ウィンドウごとPDFとしてキャプチャしても撮れないし)。

コンピュータにスマホの機能で満足してしまうユーザーが多い昨今、ダイアログという箱庭的なUser Interface上にちょっとした便利機能を表示して使えるようにすると、それなりに満足できるユーザーが多いのではないかという仮説のもとに作成してみましたが、どんなもんでしょうか。

ちなみに、このリプレイムービーで自分はジオンの2番機でザクキャノンに搭乗。拠点を叩きつつ僚機にチャットで指示を送って、チームワークの力で勝利しました。

AppleScript名:display youtube sample
—
–  Created by: Takaaki Naganoya
–  Created on: 2019/08/25
—
–  Copyright © 2019 jp.piyomarusoft, All Rights Reserved
—
use AppleScript version "2.5" — El Capitan (10.11) or later
use framework "Foundation"
use scripting additions
use utbLib : script "display youtube"

set aURL to "https://www.youtube.com/watch?v=GP_tVXTYdmY"
display youtube main message "Replay Movie" sub message "My Senjo No Kizuna replay movie on YouTube" with URL aURL with size {900, 600} starts from 24

★Click Here to Open This Script 

Posted in Network Script Libraries sdef URL | 1 Comment

指定URLのMS名を取得する v2b

Posted on 9月 4, 2019 by Takaaki Naganoya

edama2さんから投稿していただいた、指定URLの初出の指定タグ要素を抽出するAppleScriptです。

戦場の絆Wiki上の指定ページ上の指定タグでマークされたテキストを取得します。

ブログを見ていて思いつき、前に作りかけていたのを清書して送ります。

名前は「指定URLのMS名を取得するv2b」です。
内容はWKWebviewでページを読み込んで、javascriptで要素を取得しています。
前の二つよりスマートではありませんが、こんなやり方もあるってことで...

色々書き換えているうちに元がないですが、元ネタはapplescriptの穴からです。

プログラムも短いわけではなく、処理速度も速いわけでもなく(自分の環境で9秒ぐらい)、ただ見ただけだと「????」という内容ですが、本プログラムの価値は処理対象ではなく、

AppleScriptからWkWebViewに対して任意のJavaScriptを実行して処理しているサンプルである

という1点に尽きます。これはー、セキュリティ上のしばりがきつくて、けっこう大変なんですよ(遠い目)。

以前、WKWebView上にYouTubeの指定URLのムービーを表示するというScriptを掲載したことがありますが、本当はこの上でJavaScriptを実行して指定の再生ポジションに再生位置をジャンプさせるといった処理を行いたかったのですが、WKWebView相手に(任意の)JavaScriptを実行させられず、時間切れで諦めたことがありました(そして絶賛放置中)。なるほど、こう書くんですねー。

あとは、

tell AppleScript

ってなんなんでしょう(^ー^;; 初めて見かける記述のオンパレードがけっこうショッキングです。

自分は「癖のないプログラムを読みやすく書く派」を自称していますが、日本国内にも割と海外のScripterに紹介したい(変わった)人たちがいて、edama2さんとMacLab.さんはその中に必ず入ってくる人たちでしょう。

AppleScript名:指定URLのMS名を取得する v2b.scpt
—
–  Created by: edama2
–  Created on: 2019/09/04
—
use AppleScript
use scripting additions
use framework "Foundation"
use framework "WebKit"

property _js_result : ""

on run
  my main()
end run

on main()
  set my _js_result to ""
  
  
set aURL to "https://w.atwiki.jp/senjounokizuna/pages/1650.html"
  
set myJs to "var result = document.getElementsByTagName(’h3’)[0].innerHTML;
  webkit.messageHandlers.oreore.postMessage(result);"
–>返信用に必要
  
set paramObj to {targetURL:aURL, javascript:myJs}
  
  
my performSelectorOnMainThread:"makeWebContents:" withObject:(paramObj) waitUntilDone:true
  
  
return my _js_result as text
end main

on makeWebContents:paramObj
  
  
set {targetURL:aURL, javascript:myJs} to paramObj
  
  
# 下準備
  
set thisURL to current application’s |NSURL|’s URLWithString:aURL
  
set theRequest to current application’s NSURLRequest’s requestWithURL:thisURL
  
set aConf to current application’s WKWebViewConfiguration’s new()
  
  
#javascriptからname を取り出す
  
set myJs to myJs as text
  
tell AppleScript
    set tmp to text item delimiters
    
set text item delimiters to "webkit.messageHandlers."
    
set stringList to myJs’s text items
    
set aText2 to stringList’s item 2
    
set text item delimiters to ".postMessage("
    
set stringList2 to aText2’s text items
    
set scriptName to stringList2’s item 1
    
set text item delimiters to tmp
  end tell
  
  
#ページ読み込み後に実行するjavascriptの仕込み
  
set userScript to current application’s WKUserScript’s alloc()’s initWithSource:myJs injectionTime:(current application’s WKUserScriptInjectionTimeAtDocumentEnd) forMainFrameOnly:true
  
tell current application’s WKUserContentController’s new()
    addUserScript_(userScript)
    
addScriptMessageHandler_name_(me, scriptName)
    
aConf’s setUserContentController:it
  end tell
  
  
#WebViewを作成&読み込み
  
tell (current application’s WKWebView’s alloc()’s initWithFrame:(current application’s CGRectZero) configuration:aConf)
    setNavigationDelegate_(me)
    
loadRequest_(theRequest)
    
    
set hitF to false
    
repeat (minutes * 1000) times
      set isLoading to isLoading() as boolean
      
if not isLoading then
        set hitF to true
        
exit repeat
      end if
      
delay "0.001" as real
    end repeat
    
  end tell
  
  
return hitF
end makeWebContents:

#javascriptの結果を受信
on userContentController:myUserContentController didReceiveScriptMessage:aMessage
  set my _js_result to aMessage’s body() as text
  
return my _js_result
end userContentController:didReceiveScriptMessage:

★Click Here to Open This Script 

Posted in JavaScript URL | Tagged 10.12savvy 10.13savvy 10.14savvy NSURL NSURLRequest WKUserContentController WKUserScript WKWebView WKWebViewConfiguration | Leave a comment

Safariで表示中のPageの選択中の文字を含む表データを取得

Posted on 9月 3, 2019 by Takaaki Naganoya

Safari上で一部のテキストを選択した「表」のデータをHTMLReaderフレームワークを利用してparseし、2D Listとして取得するAppleScriptです。

Web上の表データをそのまま利用したいケースが多々あります。こんな小さなデータではなく、数百個にわたる表データをインポートして使いたいというケースです。

そのときに作った部品を転用して、より一般的な用途に使えるようにしたのが本Scriptです。ただし、さまざまな用途に使って鍛えたというものでもなく、AppleのWebドキュメントやWikiの内容の抽出など、割と「規則性の高そうなコンテンツ」で利用してみました。

本来は、複数ページの特定の表を指定してデータを取得する用途に用いているものなので、本Scriptのように「選択中の文字列を含む表」といった、のどかな使い方はしません。動作内容がわかりやすいように作り変えたためにこのような仕様になっています。

どこぞのオンラインストアの諸元をまとめた表をWeb上からくすねてくる、とかいう用途だと、割と表が込み入って(JavaScriptを仕込んでソートし直せるようにしてあるとか)いるケースがあるので、どのページのどの表にでもあまねく利用できるという種類のものではありません。

–> Download HTMLReader.framework(To ~/Library/Frameworks)

HTMLReader.frameworkを利用するためには、macOS 10.14以降だとSIPを解除するかScript Debugger上で動かすか、AppleScriptアプレット内に組み込んで実行することになります。

AppleScript名:Safariで表示中のPageの選択中の文字を含む表データを取得.scptd
— Created 2019-09-02 by Takaaki Naganoya
— 2019 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "HTMLReader" –https://github.com/nolanw/HTMLReader

property NSString : a reference to current application’s NSString
property HTMLDocument : a reference to current application’s HTMLDocument
property NSMutableArray : a reference to current application’s NSMutableArray

tell application "Safari"
  set dList to every document –Sometimes "count every document"causes error
  
if length of dList = 0 then return
  
  
–Get URL
  
tell front document
    set aURL to URL
  end tell
  
  
–Get Selected Text
  
set aRes to do JavaScript "var selObj = window.getSelection();
  var selStr = (selObj).getRangeAt(0);
  unescape(selStr);"
in front document
  
  
if aRes = "" then return
end tell

set aRes to filterATableAndPaseCells(aURL, aRes) of me
–> {{"Objective-C and AppleScript class", "Attributes (script term, if different)", "Relationships"}, {"NSObjectImplements the item AppleScript class. For any scriptable Objective-C class that inherits from NSObject, the AppleScript class it implements inherits from the item class (and inherits the class property and the properties property).", "class name (class), properties", ""}, {"NSApplicationImplements the application AppleScript class.", "name, active flag (frontMost), version", "documents, windows (both accessible as ordered relationship)"}, {"NSDocumentImplements the document AppleScript class.", "location of the document’s on-disk representation (path); last component of filename (name); edited flag (modified)", ""}, {"NSWindowImplements the window AppleScript class.", "title (name); various binary-state attributes: closeable, floating, miniaturized, modal, resizable, titled, visible, zoomable", "document"}}

on filterATableAndPaseCells(aURL, aKeyword)
  set aData to (do shell script "curl " & aURL)
  
set aHTML to current application’s HTMLDocument’s documentWithString:(aData as string)
  
  
–Table要素をリストアップ
  
set eList to (aHTML’s nodesMatchingSelector:"table")
  
  
–Table要素のうちSafari上で選択中の文字列を含むものをサーチ(指定データを含むものを抽出)
  
set hitF to false
  
repeat with i in eList
    set cellList to i’s children()’s array()
    
set htmlSource to i’s serializedFragment() as string –HTML source
    
    
if htmlSource contains aKeyword then
      set hitF to true
      
exit repeat
    end if
  end repeat
  
if hitF = false then return false
  
  
–Count columns of Table Header
  
set aTableHeader to (i’s nodesMatchingSelector:"tr")’s firstObject()
  
set hList to aTableHeader’s nodesMatchingSelector:"th"
  
set hStrList to {}
  
repeat with i1 in hList
    set the end of hStrList to i1’s textContent() as string
  end repeat
  
set hLen to length of hStrList –count columns
  
  
–Acquire whole table body contents
  
set aTableBody to (i’s nodesMatchingSelector:"tbody")’s firstObject()
  
set bList to aTableBody’s nodesMatchingSelector:"td"
  
set bbList to {}
  
repeat with i2 in bList
    set the end of bbList to i2’s textContent() as string
  end repeat
  
  
set tbList to makeList1DTo2D(bbList, hLen) of me
  
  
return {hStrList} & tbList
end filterATableAndPaseCells

–1D Listを2D化
on makeList1DTo2D(orig1DList, aMax)
  set tbList to {}
  
set tmpList to {}
  
set aCount to 1
  
  
repeat with i3 in orig1DList
    set j to contents of i3
    
set the end of tmpList to j
    
    
if aCount ≥ aMax then
      set aCount to 1
      
set the end of tbList to tmpList
      
set tmpList to {}
    else
      set aCount to aCount + 1
    end if
  end repeat
  
  
return tbList
end makeList1DTo2D

★Click Here to Open This Script 

Posted in JavaScript Text URL | Tagged 10.12savvy 10.13savvy 10.14savvy HTMLDocument NSMutableArray NSString Safari | 1 Comment

指定URLのMS名を取得する v2a

Posted on 9月 3, 2019 by Takaaki Naganoya

Shane Stanleyが「HTMLをXMLと見立ててアクセスすれば外部フレームワークなしに処理できて簡単だよ」と、送ってくれたサンプルScriptです。

2つの意味で焦りました。

(1)指定URLの内容をダウンロードするのに、「initWithContentsOfURL:」で処理
(2)この調子で処理したら、お手軽にREST APIも呼べそうな雰囲気

いろいろ考えさせられる内容でもあります。こういう「それ自体で何か製品を構成できるほどのサイズの処理じゃないけど、何かに絶対に使ってますよね」的な処理をBlogで公開しておくことのメリットを感じつつ、XML処理とか正規表現の処理が個人的に不得意なので、とても参考になります。

自分の用途が残念な(そんなに生産的でもなく趣味的な、という意味で)ものだったので、恐縮するばかりですー(オンラインゲームの機体のデータをWikiからまるごと引っこ抜くというものだったので)。

AppleScript名:get a title.scptd
—
–  Created by: Shane Stanley
–  Created on: 2019/09/03
—
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"

— classes, constants, and enums used
property NSXMLDocumentTidyHTML : a reference to 512
property NSXMLDocument : a reference to current application’s NSXMLDocument
property NSString : a reference to current application’s NSString
property |NSURL| : a reference to current application’s |NSURL|
property HTMLDocument : a reference to current application’s HTMLDocument
property NSMutableArray : a reference to current application’s NSMutableArray

set aURL to "https://w.atwiki.jp/senjounokizuna/pages/1650.html"
set aRes to getTitleFromAURL(aURL) of me
–> "ジム・スナイパー  RGM-79(G)"

on getTitleFromAURL(aURL)
  set theNSURL to |NSURL|’s URLWithString:aURL
  
set {theXML, theError} to NSXMLDocument’s alloc()’s initWithContentsOfURL:theNSURL options:NSXMLDocumentTidyHTML |error|:(reference)
  
if theXML is missing value then error theError’s localizedDescription() as text
  
repeat with i from 2 to 7 by 1
    set theNodes to (theXML’s nodesForXPath:("//h" & i) |error|:(missing value))
    
if theNodes’s |count|() is not 0 then return (theNodes’s firstObject()’s stringValue()) as text
  end repeat
  
error "Header is missing"
end getTitleFromAURL

★Click Here to Open This Script 

Posted in Text URL XML | Tagged 10.12savvy 10.13savvy 10.14savvy HTMLDocument NSMutableArray NSString NSURL NSXMLDocument NSXMLDocumentTidyHTML | Leave a comment

指定URLのMS名を取得する v2

Posted on 9月 3, 2019 by Takaaki Naganoya

指定URLの初出の指定タグ要素を抽出するAppleScriptです。

たまたま、戦場の絆Wikiから各種データを自動で抽出するAppleScriptを書いたときについでに作った、各ページのh2タグで囲まれた機種名を取り出す処理部分です。


▲このデータだけ機種名がh3タグでマークされていて、例外を吸収するために汎用性を高めたのが本ルーチン

Webサイトからのデータ取り出しは割と重要な技術です。それを容易に可能にするHTMLReaderのようなFrameworkは、とても重要なパーツといえます。HTMLReaderがなければ、こんな簡単に処理することはできなかったでしょう(この些細な処理を、ではなくやりたい処理全体に対しての評価)。

# WebスクレイピングはScripter必須の技術なので、Safari/ChromeでDOMアクセス派や正規表現でソースから抽出派、XMLとして解釈してXPathでアクセスする派などいろいろありそうですが、自分はHTMLReaderを使って楽をしてデータを取り出す派 といえます

特定のURL上のHTMLの特定のタグ要素のデータを抜き出すという処理であり、かならずしもどのサイトでも万能に処理できるというわけでもありません。ただ、Wikiのような管理プログラムでコンテンツを生成しているサイトから各種データを抜き出すのは、生成されるHTMLの規則性が高くて例外が少ないため、割と簡単です。

HTMLReaderをAppleScriptから呼び出し、表データを2D Listとして解釈するなど、データ取り出しが簡単にできるようになったことは意義深いと思われます。

macOS 10.13まではスクリプトエディタ/Script Debugger上でScriptを直接実行できます。macOS 10.14以降ではSIPを解除するか、Script Debugger上で実行するか、本記事に添付したようなアプレット(バンドル内にFramework同梱)を実行する必要があります。

HTMLReaderについては、Frameworkにするよりもアプリケーション化してsdefをつけて、AppleEvent経由で呼び出す専用のバックグラウンドアプリケーションにすることも考えるべきかもしれません。ただ、すべての機能についてsdefをかぶせるためには、「こういうパターンで処理すると便利」という例をみつけてまとめる必要があります。つまり、sdefをかぶせると返り値はAppleScript的なデータに限定されるため、何らかの処理が完結した状態にする必要があります。

–> Download tagElementPicker.zip (Code Signed executable Applet)

–> Download HTMLReader.framework (To ~/Library/Frameworks)

Webコンテンツのダウンロードは、本ルーチンではcurlコマンドで実装していますが、いろいろ試してみたところ現時点で暫定的にこれがベストという判断を行っています。

もともと、macOS 10.7でURL Access Scriptingが廃止になったため、Webアクセスのための代替手段を確保することはScritperの間では優先順位の高い調査項目でした。

curlコマンドはその代替手段の中でも最有力ではあったものの、macOS 10.10以降のAppleScript処理系自体のScripting Bridge対応にともない、NSURLConnectionを用いたアクセスも試してきました。同期処理できて、Blocks構文の記述が必須ではないため、実装のための難易度がCocoa系のサービスでは一番低かったからです。

ただし、NSURLConnection自体がDeprecated扱いになり、後継のNSURLSessionを用いた処理を模索。いろいろ書いているうちに、処理内容がapplescript-stdlibのWebモジュールと酷似した内容になってきた(もともと同ライブラリではNSURLSessionを用いていたため)ので、この機能のためだけにapplescript-stdlibを組み込んで使ってみたりもしました。

しかし、applescript-stdlibのWebモジュールは連続して呼び出すと処理が止まるという代物であり、実際のプログラムに組み込んで使うのは「不可能」でした。1つのURLを処理するには問題はないものの、数百個のURLを処理させると止まることを確認しています。おまけに処理本体にも自分自身のsdefを用いた記述を行っているためメンテナンス性が最悪で、中身をいじくることは(自分には)無理です。

# applescript-stdlibのWebモジュールではUserAgent名がサイト側の想定しているものに該当せずアクセスを拒否されたのか、Webモジュール側の内部処理がまずいのかまでは原因追求できていません。連続処理を行うと止まるという症状を確認しているだけです

NSURLSessionによる処理については、applescript-stdlibのWebモジュールを参考にしつつもう少し書き慣れる必要がある一方で、いろいろモジュール単位で差し替えて試行錯誤したところ、curlコマンドは遅くなったり処理が止まったりすることもなく利用できています。

それでも、curlコマンド以外の選択肢を用意しておくことは重要であるため、NSURLSessionも引き続き追いかけておきたいところです。

AppleScript名:指定URLのMS名を取得する v2.scptd
— Created 2019-09-02 by Takaaki Naganoya
— 2019 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "HTMLReader" –https://github.com/nolanw/HTMLReader

property NSString : a reference to current application’s NSString
property HTMLDocument : a reference to current application’s HTMLDocument
property NSMutableArray : a reference to current application’s NSMutableArray

set aURL to "https://w.atwiki.jp/senjounokizuna/pages/1650.html"
set aRes to getTitleFromAURL(aURL) of me
–> "ジム・スナイパー  RGM-79(G)"

on getTitleFromAURL(aURL)
  set aData to (do shell script "curl " & aURL)
  
set aHTML to current application’s HTMLDocument’s documentWithString:(aData as string)
  
  
–Levelの高いHeader Tagから順次低い方にサーチして返す
  
repeat with i from 2 to 7 by 1
    set aHeaderTag to "h" & i as string
    
set eList to (aHTML’s nodesMatchingSelector:aHeaderTag)
    
    
if (eList as list) is not equal to {} then
      return (eList’s firstObject()’s textContent()) as string
    end if
  end repeat
  
  
error "Header is missing"
end getTitleFromAURL

★Click Here to Open This Script 

Posted in Text URL | Tagged 10.12savvy 10.13savvy 10.14savvy HTMLDocument NSMutableArray NSString | Leave a comment

display YouTube Script Library

Posted on 8月 25, 2019 by Takaaki Naganoya

アラートダイアログ上で指定URLのYouTubeムービーを再生表示するAppleScriptライブラリ+呼び出しサンプルです。

用途はお察しですが、あまり実用性をねらったものではありません。

–> Download display youtube.scptd (To ~/Library/Script Libraries/)

この、「display youtube」という用語が微妙にGoogleの商標を侵害していそうなので、用語辞書内で説明して逃げを打っていますがどんなもんでしょうか。

display youtubeコマンドにURLを指定すると、

https://www.youtube.com/watch?v=XXXXXXXX

という表記のURLを、ライブラリ内部で、

https://www.youtube.com/embed/XXXXXXXX

と書き換えて表示しています。また、組み込み再生用のオプションと、高解像度表示用のオプションを追加で指定しています。

AppleScript名:display youtube sample
—
–  Created by: Takaaki Naganoya
–  Created on: 2019/08/25
—
–  Copyright © 2019 jp.piyomarusoft, All Rights Reserved
—
use AppleScript version "2.4" — Yosemite (10.10) or later
use framework "Foundation"
use scripting additions
use utbLib : script "display youtube"

set aURL to "https://www.youtube.com/watch?v=GP_tVXTYdmY"
display youtube main message "Replay Movie" sub message "My Senjo No Kizuna replay movie on YouTube" with URL aURL with size {600, 400}

set bURL to "https://www.youtube.com/embed/GP_tVXTYdmY"
display youtube main message "Replay Movie" sub message "My Senjo No Kizuna replay movie on YouTube" with URL bURL with size {900, 600}

★Click Here to Open This Script 

Posted in dialog GUI OSA sdef URL | Tagged 10.12savvy 10.13savvy 10.14savvy | 1 Comment

display location Script Library

Posted on 8月 25, 2019 by Takaaki Naganoya

指定の緯度・経度情報の場所を4つの異なる表示倍率の地図でダイアログ表示するAppleScriptライブラリ+呼び出しサンプルです。

–> Download display location.scptd (To ~/Library/Script Libraries/)

サンプルScriptでは、指定のIPアドレスの位置情報をipinfo.io上で調べて表示しています。

本ライブラリは、掲載サンプルのように「display multiple map」コマンドを提供するもので、地図.appに頼らずにAppleScriptだけで簡単な地図表示UIを利用できるようにします。

AppleScript名:display location sample
—
–  Created by: Takaaki Naganoya
–  Created on: 2019/08/25
—
–  Copyright © 2019 jp.piyomarusoft, All Rights Reserved
—
use AppleScript version "2.4" — Yosemite (10.10) or later
use framework "Foundation"
use framework "AppKit"
use scripting additions
use dispLoc : script "display location"

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

set anIP to "193.228.57.200"
set locList to getGeoLocationByIPinfo(anIP) of me

display multiple map main message "侵略場所の表示" sub message "今回の地球侵略の目的地は、地球上の以下の場所になります" with location locList with size {900, 600}

–http://ipinfo.io/developers
on getGeoLocationByIPinfo(myIP)
  set aURL to "http://ipinfo.io/" & myIP
  
set aRes to callRestGETAPIAndParseResults(aURL, 10) of me
  
  
if aRes = missing value then
    error "Network Error"
  end if
  
set aInfo to loc of aRes
  
set aPos to offset of "," in aInfo
  
set aLatitude to text 1 thru (aPos – 1) of aInfo
  
set aLongitude to text (aPos + 1) thru -1 of aInfo
  
  
return {aLatitude, aLongitude}
end getGeoLocationByIPinfo

on callRestGETAPIAndParseResults(reqURLStr as string, timeoutSec as integer)
  set tmpData to (do shell script "curl -X GET \"" & reqURLStr & "\"")
  
set jsonString to NSString’s stringWithString:tmpData
  
set jsonData to jsonString’s dataUsingEncoding:(NSUTF8StringEncoding)
  
set aJsonDict to NSJSONSerialization’s JSONObjectWithData:jsonData options:0 |error|:(missing value)
  
if aJsonDict = missing value then return false
  
return (aJsonDict as record)
end callRestGETAPIAndParseResults

★Click Here to Open This Script 

Posted in geolocation GUI JSON Network sdef URL | Tagged 10.12savvy 10.13savvy 10.14savvy | Leave a comment

アラートダイアログ上にTextViewを表示

Posted on 7月 8, 2019 by Takaaki Naganoya

アラートダイアログ上にTextViewを表示して、指定のテキストを閲覧するAppleScriptです。

とくにこれといって何か表示するものを思いつかなかったので、自分自身のソースコードを取得して表示しています。スクリプトエディタやScript Debugger上で実行した場合には自分自身のソースコードをテキストビュー上で表示します。

読み取り専用のスクリプトやアプレットで実行している場合にはソースコードを取得できません。何か適宜自分で表示させたいテキストを与えてみてください。

AppleScript名:アラートダイアログ上にTexViewを表示
— Created 2019-07-02 by Takaaki Naganoya
— 2019 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "AppKit"
use framework "OSAKit"

property |NSURL| : a reference to current application’s |NSURL|
property NSFont : a reference to current application’s NSFont
property NSView : a reference to current application’s NSView
property NSAlert : a reference to current application’s NSAlert
property NSColor : a reference to current application’s NSColor
property NSTextView : a reference to current application’s NSTextView
property NSScrollView : a reference to current application’s NSScrollView
property NSRunningApplication : a reference to current application’s NSRunningApplication
property OSAScript : a reference to current application’s OSAScript

property returnCode : 0

–Get Self Source Code (a kind of joke)
set mePath to path to me
set asStr to getASsourceFor(mePath) of me

set paramObj to {myMessage:"Main Message", mySubMessage:"Sub information", mes1:(asStr), mesWidth:400, mesHeight:200, fontName:"HiraginoSans-W3", fontSize:11.0}

–my dispTextViewWithAlertdialog:paramObj–for debug
my performSelectorOnMainThread:"dispTextViewWithAlertdialog:" withObject:paramObj waitUntilDone:true

on dispTextViewWithAlertdialog:paramObj
  –Receive Parameters
  
set aMainMes to (myMessage of paramObj) as string –Main Message
  
set aSubMes to (mySubMessage of paramObj) as string –Sub Message
  
set mesStr to (mes1 of paramObj) as string –Text Input field 1 Label
  
set aWidth to (mesWidth of paramObj) as integer –TextView width
  
set aHeight to (mesHeight of paramObj) as integer –TextView height
  
set aFontName to (fontName of paramObj) as string –TextView font name
  
set aFontSize to (fontSize of paramObj) as real –TextView font size
  
  
— Create a TextView with Scroll View
  
set aScroll to NSScrollView’s alloc()’s initWithFrame:(current application’s NSMakeRect(0, 0, aWidth, aHeight))
  
set aView to NSTextView’s alloc()’s initWithFrame:(current application’s NSMakeRect(0, 0, aWidth, aHeight))
  
aView’s setRichText:true
  
aView’s useAllLigatures:true
  
aView’s setTextColor:(current application’s NSColor’s cyanColor()) –cyanColor
  
aView’s setFont:(current application’s NSFont’s fontWithName:aFontName |size|:aFontSize)
  
set aColor to current application’s NSColor’s colorWithDeviceRed:0.0 green:0.0 blue:0.0 alpha:0.5
  
aView’s setBackgroundColor:aColor
  
aView’s setString:mesStr
  
aScroll’s setDocumentView:aView
  
aView’s enclosingScrollView()’s setHasVerticalScroller:true
  
  
— set up alert
  
set theAlert to NSAlert’s alloc()’s init()
  
tell theAlert
    its setMessageText:aMainMes
    
its setInformativeText:aSubMes
    
its addButtonWithTitle:"OK"
    
its addButtonWithTitle:"Cancel"
    
its setAccessoryView:aScroll
  end tell
  
  
— show alert in modal loop
  
NSRunningApplication’s currentApplication()’s activateWithOptions:0
  
my performSelectorOnMainThread:"doModal:" withObject:(theAlert) waitUntilDone:true
  
if (my returnCode as number) = 1001 then error number -128
end dispTextViewWithAlertdialog:

on doModal:aParam
  set (my returnCode) to aParam’s runModal()
end doModal:

–指定AppleScriptファイルのソースコードを取得する(実行専用Scriptからは取得できない)
— Original Created 2014-02-23 Shane Stanley
on getASsourceFor(anAlias as {alias, string})
  set aURL to |NSURL|’s fileURLWithPath:(POSIX path of anAlias)
  
set theScript to OSAScript’s alloc()’s initWithContentsOfURL:aURL |error|:(missing value)
  
  
if theScript is equal to missing value then
    error "Compile Error" — handle error
  else
    set sourceText to theScript’s source()
  end if
  
  
return sourceText as string
end getASsourceFor

★Click Here to Open This Script 

Posted in Color file File path Font GUI Text URL | Tagged 10.11savvy 10.12savvy 10.13savvy 10.14savvy NSAlert NSColor NSFont NSRunningApplication NSScrollView NSTextView NSURL OSAScript | Leave a comment

URLにリソースが存在するかチェック v5(NSURLSession)

Posted on 5月 24, 2019 by Takaaki Naganoya

指定URLの存在確認を行うAppleScriptです。

以前はNSURLConnectionを使って確認するものを使っていましたが、NSURLSessionへと移行しようかというところ。

もちろん、shellのcurlコマンドを使えば数行で済んでしまいますが、そこをあえてCocoaの機能を利用して、というよりはちょっと前に書いたREST API呼び出しのサブルーチンが絶好調で動いているので、これをそのまま流用してみました。

ライブラリ化して自分のScriptのバンドル内に入れておくとか、~/Library/Script Librariesフォルダに入れておくとか、そういう使い方になると思います。自分でもわざわざこれだけの機能のために、これだけの量のコードをゼロから書くことは……めったにありません。

AppleScript名:URLにリソースが存在するかチェック(curl版)_v2
set aURL to "http://www.apple.com/jp/"
set aRes to chekURLExistence(aURL) of me

on chekURLExistence(aURL)
  try
    set aRes to do shell script ("/usr/bin/curl -LI " & aURL)
  on error
    return false
  end try
  
return ((aRes contains "HTTP/1.1 200") or (aRes contains "HTTP/2 200")) as boolean
end chekURLExistence

★Click Here to Open This Script 

AppleScript名:URLにリソースが存在するかチェック v5(NSURLSession)
— Created 2019-05-24 by Takaaki Naganoya
— 2019 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"

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

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

set aURL to "http://piyocast.com/as/"
set uRes to chekURLExistence(aURL) of me
–> true

on chekURLExistence(aURL as string)
  set webRes to callRestGETAPIAndParseResults(aURL, 5) of me
  
return ((retCode of webRes) as integer = 200)
end chekURLExistence

— 指定URLにファイル(画像など)が存在するかチェック
–> {存在確認結果(boolean), レスポンスヘッダー(NSDictionary), データ(NSData)}
on callRestGETAPIAndParseResults(reqURLStr as string, timeOutSec as real)
  set (my retData) to false
  
set (my retCode) to 0
  
set (my retHeaders) to {}
  
set (my drecF) to false
  
  
set aURL to |NSURL|’s URLWithString:reqURLStr
  
set aRequest to NSMutableURLRequest’s requestWithURL:aURL
  
aRequest’s setHTTPMethod:"GET"
  
aRequest’s setValue:"gzip" forHTTPHeaderField:"Content-Encoding"
  
aRequest’s setValue:"application/json; charset=UTF-8" forHTTPHeaderField:"Content-Type"
  
  
set aConfig to NSURLSessionConfiguration’s defaultSessionConfiguration()
  
set aSession to NSURLSession’s sessionWithConfiguration:aConfig delegate:(me) delegateQueue:(missing value)
  
set aTask to aSession’s dataTaskWithRequest:aRequest
  
  
set hitF to false
  
aTask’s resume() –Start URL Session
  
  
repeat (1000 * timeOutSec) times
    if (my drecF) = true then
      set hitF to true
      
exit repeat
    end if
    
delay ("0.001" as real)
  end repeat
  
  
if hitF = false then error "REST API Timeout Error"
  
  
return {retData:retData, retCode:retCode, retHeaders:retHeaders}
end callRestGETAPIAndParseResults

on URLSession:tmpSession dataTask:tmpTask didReceiveData:tmpData
  parseSessionResults(tmpSession, tmpTask, tmpData) of me
  
set (my drecF) to true
end URLSession:dataTask:didReceiveData:

–ないとエラーになるので足した。とくに何もしていない
on URLSession:tmpSession dataTask:tmpTask willCacheResponse:cacheRes completionHandler:aHandler
  —
end URLSession:dataTask:willCacheResponse:completionHandler:

on parseSessionResults(aSession, aTask, tmpData)
  set aRes to aTask’s response()
  
set (my retCode) to aRes’s statusCode()
  
set (my retHeaders) to aRes’s allHeaderFields()
  
  
set resStr to NSString’s alloc()’s initWithData:tmpData encoding:(NSUTF8StringEncoding)
  
set jsonString to NSString’s stringWithString:(resStr)
  
  
set jsonData to jsonString’s dataUsingEncoding:(NSUTF8StringEncoding)
  
set aJsonDict to NSJSONSerialization’s JSONObjectWithData:jsonData options:0 |error|:(missing value)
  
  
set (my retData) to aJsonDict as anything
end parseSessionResults

★Click Here to Open This Script 

Posted in Network Record URL | Tagged 10.12savvy 10.13savvy 10.14savvy NSJSONSerialization NSMutableURLRequest NSString NSURL NSURLSession NSURLSessionConfiguration NSUTF8StringEncoding | Leave a comment

GET method REST API v4.3

Posted on 5月 1, 2019 by Takaaki Naganoya

クラウド系のサービスを呼び出すためのAPIとして一般的なREST APIを呼び出すAppleScriptの最新版(のスケルトン)です。

# v4.2からv4.3にバージョンアップしました(2019/05/02)

macOS 10.10でほぼすべてのAppleScriptランタイムでCocoaの機能が利用できるようになったため、Cocoaの機能を利用してクラウド系サービスを呼び出すことを、割と早い時期から調査していました。

「ほぼすべて」と書いているのは、アプリケーション内蔵のScript Menu(iTunesとか)や、Folder Actionなどの独特なランタイム、あるいはMessages(旧称iChat)のメッセージ受信イベントから呼び出されるAppleScriptランタイムなど、それぞれのアプリケーション独自で実装している処理系についてはCocoaの機能が使えるかどうかは保証のかぎりではないからです。

明確に、当初からクラウドと機械学習をAppleScriptから利用するために、苦労してCocoaの機能を追いかけてきたわけです。その途中でいろいろサードパーティのFrameworkを呼び出せたりして、期待よりも大きな成果を手にしている昨今です。OSの内部機能を直接利用できることのメリットは、処理速度や詳細な情報取得など枚挙にいとまがありません(日本語の慣用句表現なので翻訳しにくいかも?)。

話をクラウドにもどしましょう。REST APIを呼び出すには、同期で実行されるNSURLConnectionを使うのが最も簡単で確実でした。

しかし、同APIは非推奨(近い将来に廃止される)という位置付けになったため、その代わりを探す必要に迫られました。すでにNSURLConnectionを用いて記述したREST API呼び出しのScriptが大量に存在していたからです。

代替APIとしてNSURLSessionが提示されましたが、こちらは非同期実行のみで同期実行モードはありません。いろいろ実験してみたものの、数回に1回ぐらい、サーバーからの応答をつかまえ損ねることがあり、処理時間もNSURLConnection版より長くかかります。

このため、「do shell script経由でcurlコマンドを使って回避するか?」といった回避策を検討していたところです。

そんな中、冗談半分でNSURLSessionを利用したバージョンをほんの少し修正してみたところ、いままでの不安定さが嘘のように安定して結果を得られるようになってきました。これはいい兆候です。

ただし、同時に問題点も見つかってきました。macOS標準装備のScript Editor上で実行する分には問題ないのですが、Script Debugger上で実行すると、macOS 10.12/10.13/10.14共通でサーバーからの応答を取得できず、タイムアウトエラーになります。

初回掲載時(v4.2)にはScript Debugger上でデータ受信を検出できないという問題がありました。データの受信用のプロパティがmissing valueでなければデータを受信した、という判定ロジックがうまく動いていない(どういう仕組みかはわからないものの、missing valueと判断され続けた? ラベル値とproperty名でコンフリクト起こしたかも?)現象が見られました。そこで、データの受信プロパティとデータ受信完了検出のプロパティを明確に分けて判定してみたところ、Script DebuggerやmacOS 10.14上でも問題なく動作することを確認しました。

AppleScript名:GET method REST API v4.3
— Created 2019-05-01 by Takaaki Naganoya
— 2019 Piyomaru Software
use AppleScript version "2.5"
use scripting additions
use framework "Foundation"
use framework "AppKit"

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

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

set reqURLStr to "http://jsonplaceholder.typicode.com/posts"
set aRESTres to callRestGETAPIAndParseResults(reqURLStr, 10) of me
–return retData of aRESTres

set aRESTcode to retCode of aRESTres
–return aRESTcode
–> 200

return retHeaders as record
–> {|content-type|:"application/json; charset=utf-8", Pragma:"no-cache", |x-powered-by|:"Express", |set-cookie|:"__cfduid=dd8b4572e0a59951cc7cf7a1120c368541554964103; expires=Fri, 10-Apr-20 06:28:23 GMT; path=/; domain=.typicode.com; HttpOnly", Server:"cloudflare", Via:"1.1 vegur", |content-encoding|:"gzip", Expires:"Wed, 01 May 2019 15:27:42 GMT", |cf-cache-status|:"HIT", |transfer-encoding|:"Identity", |cache-control|:"public, max-age=14400", |date|:"Wed, 01 May 2019 11:27:42 GMT", |access-control-allow-credentials|:"true", Connection:"keep-alive", |cf-ray|:"4d016861ac759413-NRT", Etag:"W/\"6b80-Ybsq/K6GwwqrYkAsFxqDXGC7DoM\"", Vary:"Origin, Accept-Encoding", |x-content-type-options|:"nosniff"}

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

on URLSession:tmpSession dataTask:tmpTask didReceiveData:tmpData
  parseSessionResults(tmpSession, tmpTask, tmpData) of me
  
set (my drecF) to true
end URLSession:dataTask:didReceiveData:

–ないとエラーになるので足した。とくに何もしていない
on URLSession:tmpSession dataTask:tmpTask willCacheResponse:cacheRes completionHandler:aHandler
  —
end URLSession:dataTask:willCacheResponse:completionHandler:

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

★Click Here to Open This Script 

Posted in REST API URL | Tagged 10.11savvy 10.12savvy 10.13savvy 10.14savvy NSJSONSerialization NSMutableURLRequest NSString NSURL NSURLSession NSURLSessionConfiguration | 3 Comments

各種GUI要素なしでSafari上に新規ウィンドウ表示

Posted on 4月 29, 2019 by Takaaki Naganoya

Safari上で操作ボタンなどのGUI要素を表示しないで新規ウィンドウ表示するAppleScriptです。

1つのウィンドウを表示するのはすぐにできましたが、複数表示が大変でした(ーー; 結局、適宜delayコマンドで時間待ちをする必要があったのでした。やれやれー。

現時点で用途はまったく不明なのですが、いつか必要になることもあるでしょう(そういうの多いな!)。「resizable=no」という指定をしているのに、ウィンドウがリサイズできるあたりはご愛嬌。

ちなみに、Safariのdocumentが1つ以上存在することを前提条件としていますが、そこは省略して明示していません(初心者がひっかかりがちな「不明確な前提条件」なのですが本説明をもってかえさせていただきます)。

Twitter上でロシアのMacユーザーが「だれかAppleScriptについて教えてくれー」と言っていたので、「Google翻訳の範囲でなら(込み入った話でなければ)いいぞ」と返信したら、マンツーマンでやりとり。

初のロシア人とのチャットです。

本ScriptのおおもとになったAppleScriptをAlfred.appを使ってキーボードショートカットで呼び出していたそうで、1アクションから1つのサイトをオープンするだけなのが不満で、複数のサイト(URL)をオープンするように変更したかったとのこと。

Google翻訳を使ってコミュニケーションしてみて、いろいろ理解しました。

(1)ロシア人、とっても普通

(2)話した相手がプログラミングわからない人だったので、いろいろ追加で話をされたが、プログラマーが一番嫌がる内容(最初からゴール地点が設定されていない)になってきたので「ここから先は仕事としてならやるが、ギャラなしだったらやらない」と明言して打ち切り

(3)Google翻訳を通じて「ロシア語に翻訳できない表現」がいろいろあって焦る。おそらく、英語ほどには日本語との間の翻訳の用例が多く蓄積されておらず、翻訳できなかったものと想像。一応、日本語→ロシア語に翻訳してから、その文章を再度日本語に再翻訳してチェック。トンでもない表現に翻訳されて驚愕するも、何例か日本語の表現を変えてリトライ

あとから振り返って考えると、「日本語からロシア語に翻訳するより、英語からロシア語に翻訳した方がよかった」、「ダスビダーニャ(До свидания)って挨拶は知っていたのに使えなかったよ、ハラショー」といったところでしょうか。

あとは、固定でプログラム中にURLのデータを入れておかないで、外部ファイル……たとえばNumbers書類上のデータであるとか、DragThingのURLランチャーに登録してある現在選択中のタブからURLを取得してオープンするとかいった処理が考えられると「お、頑張ったね」というレベルでしょうか。

AppleScript名:各種GUI要素なしでSafari上に新規ウィンドウ表示
set aURLstr to "http://piyocast.com/as"

tell application "Safari"
  tell front document
    set jsStr to "open(’" & aURLstr & "’, ’test’,’scrollbars=no,resizable=no,status=no,location=no," & "toolbar=no,menubar=no,width=1024,height=720,left=0,top=0’);"
    
do JavaScript jsStr
  end tell
end tell

★Click Here to Open This Script 

AppleScript名:各種GUI要素なしでSafari上に新規ウィンドウを複数表示
set aURLarray to {"http://piyocast.com/as", "http://www.apple.com", "http://www.microsoft.com"}

repeat with i in aURLarray
  set j to contents of i
  
openNewWindowWithoutGUIElements(j) of me
  
delay 3
end repeat

on openNewWindowWithoutGUIElements(aURLstr)
  set aNum to random number from 1 to 999
  
tell application "Safari"
    tell front document
      set jsStr to ("open(’" & aURLstr & "’, ’test" & aNum as string) & "’,’scrollbars=no,resizable=no,status=no,location=no," & "toolbar=no,menubar=no,width=1024,height=720,left=0,top=0’);"
      
do JavaScript jsStr
    end tell
  end tell
end openNewWindowWithoutGUIElements

★Click Here to Open This Script 

Posted in JavaScript list URL | Tagged 10.11savvy 10.12savvy 10.13savvy 10.14savvy Safari | Leave a comment

Google Sheets URLから正規表現でIDを抽出 v2

Posted on 4月 18, 2019 by Takaaki Naganoya

文字列で与えられたGoogle SpreadSheetsのURLから正規表現の機能を用いてSheets IDを抽出するAppleScriptです。

初回掲載時の内容にShane Stanleyから「長さが0の文字列」(zero length string)に対応できていないので、変更したほうがいいよ、という助言をもらったので書き換えました(Thanks Shane!)。

AppleScript名:Google Sheets URLから正規表現でIDを抽出 v2
— Created 2019-04-18 by Takaaki Naganoya
— Modified 2019-04-19 by Shane Stanley
use AppleScript version "2.5" –macOS 10.11 or later
use scripting additions
use framework "Foundation"

property NSString : a reference to current application’s NSString
property NSRegularExpressionSearch : a reference to current application’s NSRegularExpressionSearch

–https://developers.google.com/sheets/guides/concepts?hl=ja
set aURLText to "https://docs.google.com/spreadsheets/d/1qpyC0XzvTcKT6EISywvqESX3A0MwQoFDE8p-Bll4hps/edit#gid=0
"

set sheetsID to (stripGoogleSheetsIDFromURL(aURLText) of me) as string
–> "1qpyC0XzvTcKT6EISywvqESX3A0MwQoFDE8p-Bll4hps"

set aURLText to "" –Zero Length String
set sheetsID to (stripGoogleSheetsIDFromURL(aURLText) of me) as string
–> ""

on stripGoogleSheetsIDFromURL(aText as string)
  set sStrHead to "/spreadsheets/d/"
  
set regStr to sStrHead & "([a-zA-Z0-9-_]+)"
  
  
set anNSString to NSString’s stringWithString:aText
  
set aRange to anNSString’s rangeOfString:regStr options:(NSRegularExpressionSearch)
  
  
–if aRange = {location:0, length:0} then return ""–v1
  
if |length| of aRange = 0 then return "" –Prepare for zero length strings(Thanks Shane!)
  
  
set bStr to anNSString’s substringWithRange:aRange
  
set theString to bStr’s stringByReplacingOccurrencesOfString:sStrHead withString:"" options:(NSRegularExpressionSearch) range:{location:0, |length|:length of sStrHead}
  
  
return theString as string
end stripGoogleSheetsIDFromURL

★Click Here to Open This Script 

Posted in regexp Text URL | Tagged 10.11savvy 10.12savvy 10.13savvy 10.14savvy NSRegularExpressionSearch NSString | Leave a comment

FireFoxでURLをオープン(URLの間接指定)

Posted on 3月 31, 2019 by Takaaki Naganoya

FireFoxで指定URLをオープンするAppleScriptです。

FireFoxのAppleScript対応機能は、指定のURLをオープンさせるだけです。しかも、AppleScript用語辞書からアクセスできないという体たらく。2004年ごろに出回っていたサンプルScriptがそのまま最新のバージョンでも動きました。

FireFoxのAppleScript用語辞書を見てもdo javascript的な命令はないですし、ほぼ何もできない内容です(ダミーといってもいいでしょう)。なので、これをスクリプタブルだとはとても言えません。AppleScriptからコントロールする用途でFireFoxを用いることに意味はありません。

いろいろ試していたら、FireFoxが起動していない状態で本Scriptを実行すると、実行が完了しないという問題が報告されました。追試してみるとそのとおりです。あらかじめ、起動しておくなりactivateしておくなどの処理が必要です。

AppleScript名:FireFoxでURLをオープン(URLの間接指定)
set aURL to "http://piyocast.com/as"

tell application "Firefox"
  «event WWW!OURL» aURL
end tell

★Click Here to Open This Script 

Posted in Internet Raw AppleEvent Code URL | Tagged 10.11savvy 10.12savvy 10.13savvy 10.14savvy FireFox | Leave a comment

アラートダイアログ上にWebViewを表示

Posted on 3月 5, 2019 by Takaaki Naganoya

アラートダイアログ上にWKWebViewを表示するAppleScriptです。

テストのためにYouTubeのムービーの自動再生URL(戦場の絆のリプレイムービー)をオープンしています。


▲Table ViewとWeb Viewを組み合わせて、所定の場所にYouTubeムービーの頭出しを行う試作品を作ってみたものの、JavaScript経由でWKWebViewをコントロールするのが難しくて頓挫

本来であれば、WkWebViewに対してJavaScript経由でさまざまな操作を行いたいところですが、オープン中のWebコンテンツに対して新たなJavaScriptのインスタンスを生成してセキュリティチェックを行なって、実際に実行を行うのが(自分には)少々難しく感じました。WkWebViewだとあまり凝った制御はできない印象です。Safariをコントロールするほうが自由度が高いところ。

WkWebViewを「自由にこづきまわして操作できる部品」として使うためには、素のままのWkWebViewではない何かを使ったほうがいいのかも?

AppleScript名:アラートダイアログ上にWebViewを表示.scptd
—
–  Created by: Takaaki Naganoya
–  Created on: 2019/03/02
—
–  Copyright © 2019 Piyomaru Software, All Rights Reserved
—
use AppleScript version "2.4" — Yosemite (10.10) or later
use framework "Foundation"
use framework "AppKit"
use framework "WebKit"
use scripting additions

property |NSURL| : a reference to current application’s |NSURL|
property NSAlert : a reference to current application’s NSAlert
property NSColor : a reference to current application’s NSColor
property NSString : a reference to current application’s NSString
property NSScreen : a reference to current application’s NSScreen
property NSButton : a reference to current application’s NSButton
property WKWebView : a reference to current application’s WKWebView
property NSScrollView : a reference to current application’s NSScrollView
property WKUserScript : a reference to current application’s WKUserScript
property NSURLRequest : a reference to current application’s NSURLRequest
property NSRunningApplication : a reference to current application’s NSRunningApplication
property NSUTF8StringEncoding : a reference to current application’s NSUTF8StringEncoding
property NSBackingStoreBuffered : a reference to current application’s NSBackingStoreBuffered
property WKUserContentController : a reference to current application’s WKUserContentController
property NSMomentaryLightButton : a reference to current application’s NSMomentaryLightButton
property WKWebViewConfiguration : a reference to current application’s WKWebViewConfiguration
property NSAlertSecondButtonReturn : a reference to current application’s NSAlertSecondButtonReturn
property WKUserScriptInjectionTimeAtDocumentEnd : a reference to current application’s WKUserScriptInjectionTimeAtDocumentEnd

property theResult : 0
property returnCode : 0
property theDataSource : {}

set aURL to "https://www.youtube.com/embed/GP_tVXTYdmY?autoplay=1&hd=1"
set paramObj to {myMessage:"Browse a Replay", mySubMessage:"Browse Senjo-No-Kizuna Replay Movie", targURL:aURL}
my performSelectorOnMainThread:"browseWebContents:" withObject:(paramObj) waitUntilDone:true

on browseWebContents:paramObj
  set aMainMes to myMessage of paramObj
  
set aSubMes to mySubMessage of paramObj
  
set tmpURL to (targURL of paramObj)
  
  
set aWidth to 600
  
set aHeight to 450
  
  
–WebViewをつくる
  
set aConf to WKWebViewConfiguration’s alloc()’s init()
  
  
–指定URLのJavaScriptをFetch
  
set jsSource to my fetchJSSourceString(tmpURL)
  
set userScript to WKUserScript’s alloc()’s initWithSource:jsSource injectionTime:(WKUserScriptInjectionTimeAtDocumentEnd) forMainFrameOnly:true
  
set userContentController to WKUserContentController’s alloc()’s init()
  
userContentController’s addUserScript:(userScript)
  
aConf’s setUserContentController:userContentController
  
  
set aWebView to WKWebView’s alloc()’s initWithFrame:(current application’s NSMakeRect(0, 0, aWidth, aHeight – 100)) configuration:aConf
  
aWebView’s setNavigationDelegate:me
  
aWebView’s setUIDelegate:me
  
aWebView’s setTranslatesAutoresizingMaskIntoConstraints:true
  
  
set bURL to |NSURL|’s URLWithString:tmpURL
  
set aReq to NSURLRequest’s requestWithURL:bURL
  
aWebView’s loadRequest:aReq –Webコンテンツのローディング
  
  
— set up alert  
  
set theAlert to NSAlert’s alloc()’s init()
  
tell theAlert
    its setMessageText:aMainMes
    
its setInformativeText:aSubMes
    
its addButtonWithTitle:"OK"
    
its addButtonWithTitle:"Cancel"
    
its setAccessoryView:aWebView
  end tell
  
  
— show alert in modal loop
  
NSRunningApplication’s currentApplication()’s activateWithOptions:0
  
my performSelectorOnMainThread:"doModal:" withObject:(theAlert) waitUntilDone:true
  
  
–Stop Web View Action
  
set bURL to |NSURL|’s URLWithString:"about:blank"
  
set bReq to NSURLRequest’s requestWithURL:bURL
  
aWebView’s loadRequest:bReq
  
  
if (my returnCode as number) = 1001 then error number -128
end browseWebContents:

on doModal:aParam
  set (my returnCode) to aParam’s runModal()
end doModal:

on viewDidLoad:aNotification
  return true
end viewDidLoad:

on fetchJSSourceString(aURL)
  set jsURL to |NSURL|’s URLWithString:aURL
  
set jsSourceString to NSString’s stringWithContentsOfURL:jsURL encoding:(NSUTF8StringEncoding) |error|:(missing value)
  
return jsSourceString
end fetchJSSourceString

★Click Here to Open This Script 

Posted in Internet URL | Tagged 10.11savvy 10.12savvy 10.13savvy NSAlert NSAlertSecondButtonReturn NSBackingStoreBuffered NSButton NSColor NSMomentaryLightButton NSRunningApplication NSScreen NSString NSURL NSURLRequest NSUTF8StringEncoding WKUserContentController WKUserScript WKUserScriptInjectionTimeAtDocumentEnd WKWebView WKWebViewConfiguration | Leave a comment

「戦場の絆」の日本国内の設置店舗数をカウント

Posted on 3月 3, 2019 by Takaaki Naganoya

アーケードゲーム「戦場の絆」が設置されている日本国内のゲームセンターの件数をカウントするAppleScriptです。

指定ページを取得し、本文内容をプレーンテキスト化して正規表現でデータ抽出して加算を行うという処理内容です。

部品がありきたりなので、新規作成部分はほとんどありません(メイン部分だけ)。

AppleScript名:戦場の絆の日本国内の設置店舗数をカウント.scptd
—
–  Created by: Takaaki Naganoya
–  Created on: 2019/03/03
—
–  Copyright © 2019 Piyomaru Software, All Rights Reserved
—
use AppleScript version "2.4" — Yosemite (10.10) or later
use framework "Foundation"
use framework "AppKit"
use scripting additions

property NSArray : a reference to current application’s NSArray
property NSString : a reference to current application’s NSString
property NSPredicate : a reference to current application’s NSPredicate
property NSURLQueryItem : a reference to current application’s NSURLQueryItem
property NSAttributedString : a reference to current application’s NSAttributedString
property NSURLComponents : a reference to current application’s NSURLComponents
property NSMutableDictionary : a reference to current application’s NSMutableDictionary
property NSUnicodeStringEncoding : a reference to current application’s NSUnicodeStringEncoding

set aTotal to 0

–「戦場の絆」公式ページに掲載されている店舗一覧の都道府県別コード
set areaList to {"JP-01", "JP-02", "JP-03", "JP-04", "JP-05", "JP-06", "JP-07", "JP-08", "JP-09", "JP-10", "JP-11", "JP-12", "JP-13", "JP-14", "JP-15", "JP-16", "JP-17", "JP-18", "JP-19", "JP-20", "JP-21", "JP-22", "JP-23", "JP-24", "JP-25", "JP-26", "JP-27", "JP-28", "JP-29", "JP-30", "JP-31", "JP-32", "JP-33", "JP-34", "JP-35", "JP-36", "JP-37", "JP-38", "JP-39", "JP-40", "JP-41", "JP-42", "JP-43", "JP-44", "JP-45", "JP-46", "JP-47"}

–「戦場の絆」公式ページに掲載されている店舗一覧のBase URL
set baseURL to "https://gundam-kizuna.jp/locations/list"

–都道府県コードでループ
repeat with i in areaList
  –店舗一覧の都道府県別ページをダウンロード
  
set j to contents of i
  
set aRec to {area:j}
  
set aRes to retURLwithParams(baseURL, aRec) of me
  
set shellText to "curl -s " & aRes
  
set htmlRes to (do shell script shellText)
  
set aPlainText to (HTMLDecode(htmlRes) of me)
  
  
–店舗件数が入っている箇所を抽出して加算
  
set aList to paragraphs of aPlainText
  
set anArray to (NSArray’s arrayWithArray:aList)
  
set aPred to (NSPredicate’s predicateWithFormat:"SELF MATCHES ’[0-9]{1,3}件の店舗が見つかりました。’")
  
set bRes to (anArray’s filteredArrayUsingPredicate:aPred) as list
  
  
if bRes is not equal to {} then
    set a to repChar(contents of first item of bRes, "件の店舗が見つかりました。", "") of me
    
try
      set aNum to a as integer
      
set aTotal to aTotal + aNum
    on error
      log {"Error in ", j}
    end try
  end if
end repeat

return aTotal
–> 622 (2019/3/3)

(*
set countryList to {"HKG", "TWN"}–香港と台湾の店舗のコード
set baseURL2 to "https://gundam-kizuna.jp/locations/list"
*)

–パラメータつきURLを作成
on retURLwithParams(aBaseURL as string, aRec as record)
  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 bLen to length of aValList
  
if aLen is not equal to bLen then return false
  
  
set qList to {}
  
repeat with i from 1 to aLen
    set aName to (contents of item i of aKeyList) as string
    
set aVal to (contents of item i of aValList) as string
    
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

–テキストをHTMLとして解釈しプレーンテキスト化
on HTMLDecode(HTMLString)
  set theString to NSString’s stringWithString:HTMLString
  
set theData to theString’s dataUsingEncoding:(current application’s NSUnicodeStringEncoding)
  
set attStr to NSAttributedString’s alloc()’s initWithHTML:theData documentAttributes:(missing value)
  
set aStr to attStr’s |string|()
  
return aStr as string
end HTMLDecode

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

★Click Here to Open This Script 

Posted in list regexp Text URL | Tagged 10.11savvy 10.12savvy 10.13savvy NSArray NSAttributedString NSMutableDictionary NSPredicate NSString NSUnicodeStringEncoding NSURLComponents NSURLQueryItem | Leave a comment

YouTubeムービーの状態を取得、操作

Posted on 2月 16, 2019 by Takaaki Naganoya

Safari上で表示中のYouTubeのムービーの再生状態を取得、再生/停止のトグル動作を行うなどのAppleScriptです。

追記(2021/7/31):pausedの属性を取得できていないですね。YouTube側に変更があったのか…?
追記(2022/1/21):YouTube側の仕様がかわって、ムービープレイヤーに対する操作が通りません。x倍速再生が便利だったのですが…

macOS標準搭載のスクリプトメニューに入れて呼び出しています。

AppleScript名:Safariの最前面のウィンドウで再生中のYouTubeムービーの状態を取得する
–Get YouTube Movie status
tell application "Safari"
  tell front document
    set aRes to (do JavaScript "document.querySelector(’#movie_player video’).paused;")
  end tell
end tell

★Click Here to Open This Script 

AppleScript名:Safariの最前面のウィンドウで再生中のYouTubeムービーを再生_停止をトグル切り替え
–Toggle Youtube play/pause
tell application "Safari"
  tell front document
    set aRes to (do JavaScript "document.querySelector(’#movie_player .ytp-play-button’).click();")
  end tell
end tell

★Click Here to Open This Script 

AppleScript名:Safariの最前面のウィンドウでオープン中のYouTubeムービーを再生
tell application "Safari"
  tell front document
    set aURL to URL
    
–最前面のウィンドウがYouTubeの場合のみ処理
    
if aURL begins with "https://www.youtube.com/" then
      set aRes to (do JavaScript "document.querySelector(’#movie_player video’).paused;")
      
if aRes = true then
        –停止中(一時停止中)の場合のみ再生操作
        (
do JavaScript "document.querySelector(’#movie_player .ytp-play-button’).click();")
      end if
    end if
  end tell
end tell

★Click Here to Open This Script 

AppleScript名:Safariの最前面のウィンドウでオープン中のYouTubeムービーの再生フレームの冒頭からの時間を取得
tell application "Safari"
  tell front document
    set aURL to URL
    
–最前面のウィンドウがYouTubeの場合のみ処理
    
if aURL begins with "https://www.youtube.com/" then
      set tRes to (do JavaScript "document.querySelector(’#movie_player video’).getCurrentTime();")
    end if
  end tell
end tell

★Click Here to Open This Script 

AppleScript名:Safariの最前面のウィンドウでオープン中のYouTubeムービーの再生ポジションを変更
tell application "Safari"
  tell front document
    set aURL to URL
    
–最前面のウィンドウがYouTubeの場合のみ処理
    
if aURL begins with "https://www.youtube.com/" then
      set tRes to (do JavaScript "document.querySelector(’#movie_player video’).currentTime =300;")
    end if
  end tell
end tell

★Click Here to Open This Script 

AppleScript名:Safariの最前面のウィンドウでオープン中のYouTubeムービーのdurationを取得
tell application "Safari"
  tell front document
    set aURL to URL
    
–最前面のウィンドウがYouTubeの場合のみ処理
    
if aURL begins with "https://www.youtube.com/" then
      set tRes to (do JavaScript "document.querySelector(’#movie_player video’).duration;")
    end if
  end tell
end tell

★Click Here to Open This Script 

Posted in JavaScript URL Web Contents Control | Tagged 10.11savvy 10.12savvy 10.13savvy 10.14savvy Safari | 3 Comments

Automator Actionを実行

Posted on 1月 24, 2019 by Takaaki Naganoya

指定のAutomator Action(拡張子「.workflow」)を実行するAppleScriptです。

PDFKitをさんざんこづき回しても、指定のPDFに任意のすかし(Watermark)を入れるのが自分にはできなかったので、AutomatorのActionにそういうのが標準装備されているから、それを使えばいいんじゃないかと思い出し、Automator Workflowを直接実行するやりかたを調べて実行してみました。

# これは、Cocoaの機能を呼び出して実行しているものであって、Automatorアプリケーションを呼び出すとか、/usr/bin/automatorを呼び出すやり方などもあります

まだ、パラメータを指定してはいないので、パラメータを指定できるようにするとなおいいと思います。

AppleScript名:Automator Actionを実行.scptd
—
–  Created by: Takaaki Naganoya
–  Created on: 2019/01/22
—
–  Copyright © 2019 Piyomaru Software, All Rights Reserved
—
use AppleScript version "2.5" — El Capitan (10.11) or later
use framework "Foundation"
use framework "Automator"
use scripting additions

property |NSURL| : a reference to current application’s |NSURL|

set aURL to |NSURL|’s fileURLWithPath:(POSIX path of (choose file with prompt "Choose Automator Action" of type {"com.apple.automator-workflow"}))

set aWKres to current application’s AMWorkflow’s runWorkflowAtURL:aURL withInput:(missing value) |error|:(reference)

★Click Here to Open This Script 

Posted in file URL | Tagged 10.11savvy 10.12savvy 10.13savvy 10.14savvy AMWorkflow Automator NSURL | Leave a comment

Post navigation

  • Older posts
  • Newer posts

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

Google Search

Popular posts

  • 開発機としてM2 Mac miniが来たのでガチレビュー
  • macOS 13.6.5 AS系のバグ、一切直らず
  • CotEditorで2つの書類の行単位での差分検出
  • Apple純正マウス、キーボードのバッテリー残量取得
  • macOS 15, Sequoia
  • 初心者がつまづきやすい「log」コマンド
  • 指定のWordファイルをPDFに書き出す
  • Adobe AcrobatをAppleScriptから操作してPDF圧縮
  • メキシカンハットの描画
  • 与えられた文字列の1D Listのすべての順列組み合わせパターン文字列を返す v3(ベンチマーク用)
  • Pages本執筆中に、2つの書類モード切り替えに気がついた
  • 2023年に書いた価値あるAppleScript
  • Pixelmator Pro v3.6.4でAppleScriptからの操作時の挙動に違和感が
  • AdobeがInDesign v19.4からPOSIX pathを採用
  • Safariで「プロファイル」機能を使うとAppleScriptの処理に影響
  • Cocoa Scripting Course 続刊計画
  • Numbersで選択範囲のセルの前後の空白を削除
  • macOS 14.xでScript Menuの実行速度が大幅に下がるバグ
  • NaturalLanguage.frameworkでNLEmbeddingの処理が可能な言語をチェック
  • AppleScriptによる並列処理

Tags

10.11savvy (1102) 10.12savvy (1243) 10.13savvy (1392) 10.14savvy (587) 10.15savvy (438) 11.0savvy (283) 12.0savvy (207) 13.0savvy (177) 14.0savvy (127) 15.0savvy (104) CotEditor (64) Finder (51) iTunes (19) Keynote (115) NSAlert (61) NSArray (51) NSBitmapImageRep (20) NSBundle (20) NSButton (34) NSColor (53) NSDictionary (28) NSFileManager (23) NSFont (21) NSImage (41) NSJSONSerialization (21) NSMutableArray (63) NSMutableDictionary (22) NSPredicate (36) NSRunningApplication (56) NSScreen (30) NSScrollView (22) NSString (119) NSURL (98) NSURLRequest (23) NSUTF8StringEncoding (30) NSView (33) NSWorkspace (20) Numbers (74) Pages (54) Safari (44) Script Editor (27) WKUserContentController (21) WKUserScript (20) WKWebView (23) WKWebViewConfiguration (22)

カテゴリー

  • 2D Bin Packing
  • 3D
  • AirDrop
  • AirPlay
  • Animation
  • AppleScript Application on Xcode
  • Beginner
  • Benchmark
  • beta
  • Bluetooth
  • Books
  • boolean
  • bounds
  • Bug
  • Calendar
  • call by reference
  • check sum
  • Clipboard
  • Cocoa-AppleScript Applet
  • Code Sign
  • Color
  • Custom Class
  • dialog
  • diff
  • drive
  • Droplet
  • 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
  • Localize
  • Machine Learning
  • Map
  • Markdown
  • Menu
  • Metadata
  • MIDI
  • MIME
  • Natural Language Processing
  • Network
  • news
  • Noification
  • Notarization
  • Number
  • Object control
  • OCR
  • OSA
  • parallel processing
  • 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)
  • 未分類

アーカイブ

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

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

メタ情報

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

Forum Posts

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

メタ情報

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