りんごの備忘録

へなちょこポカ大生のへなちょこブログ

iTunesのポンコツ"アルバムアートワーク入手する"をAppleScriptでマシにする話

同人系のCDだとiTunesの”アルバムアートワークを入手する”を使っても見つかりませんでした,と毎回言われます.自分はそれなりの数のCDを買うのでその度にわざわざ画像を拾って来て,iTunesに貼り付けるのがバカらしく思えて来たのでAppleScriptで試してみました.
すごくテキトーにやってしまったので役に立つか微妙です.

コード
--アルバムの情報取得とSafariを用いた画像検索
tell application "iTunes"
	set theAlbumArtist to item 1 of album artist of selection
	set theAlbum to item 1 of album of selection
	set theArtist to item 1 of artist of selection
	set searchURL to "https://www.google.co.jp/search?q=" & theAlbum & "+" & theAlbumArtist & "&source=lnms&tbm=isch&sa=X" as string
	
	tell application "Safari" to open location searchURL
	
end tell

display dialog "OK?"

--画像検索の検索結果をhtmlで入手
tell application "Safari"
	set html to (source of document 1)
	set the clipboard to html
end tell

--画像情報ごとにリストで分け高さと横幅の取得
set imageInfo to devText(html, "画像検索結果")
set imageInfo to rest of imageInfo
set imageHeight to {}
set imageWidth to {}
--上から20枚の画像の情報を扱う(この20は適当)
repeat with i from 1 to 20
	set end of the imageHeight to (item 1 of devText((item 2 of devText(item i of imageInfo, "\"oh\":")), ","))
end repeat

repeat with i from 1 to 20
	set end of the imageWidth to (item 1 of devText((item 2 of devText(item i of imageInfo, "\"ow\":")), ","))
end repeat

--自分が欲しい画像の条件,(今回は高さ400,横幅400より大きく,高さと横幅の比)
repeat with i from 20 to 1 by -1
	if (item i of imageHeight > 400) and (item i of imageWidth > 400) and (((item i of imageHeight) / (item i of imageWidth) < 1.1) or ((item i of imageHeight) / (item i of imageWidth > 0.9))) then
		--display dialog i & "," & (item i of imageHeight as text) & "," & item i of imageWidth as text
		set getNumber to i
		
	end if
end repeat

set imageUrl to item 1 of devText((item 2 of devText(item getNumber of imageInfo, "\"ou\":\"")), "\"")

set theDestination to "ダウンロードする場所を指定する"
set thePath to theDestination & ":" & theAlbum & ".png"
do shell script "curl -L " & imageUrl & " -o \"" & POSIX path of thePath & "\""
set targetImageFile to thePath
tell application "iTunes"
	set theTrack to selection
	repeat with i in theTrack
		set data of artwork 1 of i to (read (file targetImageFile) as picture)
	end repeat
end tell

--デリミタで分割
on devText(theText, aDelimiter)
	set tmp to AppleScript's text item delimiters
	set AppleScript's text item delimiters to aDelimiter
	set theList to every text item of theText
	set AppleScript's text item delimiters to tmp
	return theList
end devText
使い方

1.iTunesでアルバムアートを適用したいアルバムをcmd + クリックで青色にする.
2.上のコードを実行する.
3.OKと表示されるので画像検索結果でお目当の画像があるか確認してあればOK,なければ検索結果を変えてOKを押す
4.~完~

所感

どうしてもマイナーどころだとアートワークが見つからない可能性もあるのでその時は諦め