applescript

TurntableでファンのDJが回し始めたらGrowlに通知する

Turntable面白い!

TurntableにはファンになったDJが演奏を始めるとメール通知してくれる機能がありますが、見逃してしまって気付いたころには終わっていることもよくあります。そこでMail.appのルール機能を使ってメールが来たらGrowlに通知するようにしてみました。

  1. mail-turntable-notifier.scptを適当な場所に保存
  2. Mail.appに画像のようなルールを追加。「AppleScript を実行」には1で保存したファイルを選択

スティッキーなどの設定はGrowlの設定にある「Mail.app Rules」から変更してください。

[Mac限定] 指定したTumblrの画像をランダムにダウンロードしてスライドショーを始めるアプリを作りました

作成動機と動作

ある作業をするのにフルスクリーンでTumblrの画像をランダムに表示したくなったので作りました。

ダウンロードを始めてからスライドショーが表示されるまで時間がかかります(250枚で五分くらい?)が幸福が実現します。

指定したTumblrのランダムなページから50枚ずつ画像をダウンロードして、指定した回数それを繰り返します。

スクリーンショット

やっていること

  1. http://tumblr_name.tumblr.com/api/readからXML取得
  2. Rubyで総投稿数と画像URLを抜き出し
  3. curlで一枚ずつダウンロード(サーバに優しい!)
  4. Amazon S3に置かれた画像は拡張子がついていないので、sipsコマンドで拡張子を付加
  5. QuickLookで表示

ダウンロード

Tumblr_Random_Slideshow.app(MediaFire)

必要な物

Mac OS X v10.5以上

Evernoteの検索条件を自動バックアップ。EverQuery

新作AppleScriptの紹介です。

EverQuery - Evernoteの検索条件を保存し、呼び出すAppleScript

簡単に言うと、Evernote Webの「最新の検索」(検索ボックスからアクセスできる過去の検索)や、withEverの「検索履歴」と同じ機能をEvernote for Macで実現するAppleScriptです。つまり、Evernote for Macでの検索条件を保存し、必要なときに呼び出して検索を実行します。

EverQueryは、常に起動しておき、Dockをクリックすることで保存した検索条件を呼び出すことができます。ダウンロードと詳しい使い方はAppleScriptページで。

検索条件の取得方法

検索条件を自動で取得して保存します。

ただし、Evernote Web、withEverと違い、検索条件すべてが保存されるわけではありません。これは検索条件の取得方法が異なるためです。

例えると、メールのプッシュとフェッチの違いです。具体的には、上記2つでは検索の実行をトリガーに検索条件を保存します。一方、EverQueryは一定時間ごとに検索条件の取得を繰り返します。Evernote for Macでは検索の実行をトリガーにAppleScriptを実行することができないためです。(インクリメンタルに検索されることを考えると、検索をトリガーにすることは難しいことが想像できると思います。)

この問題を軽減するには取得間隔を短くすればいいのですが、それも難しい問題です。たとえば、もともとかなり動作が重いアプリケーションであるEvernoteで1秒ごとに検索条件の取得を繰り返すと、動作がより重くなり、まともに使えなくなってしまいます。また、ユーザはそこまで頻繁に検索条件を変更しません。

それを踏まえた上で検索条件の取得間隔を決めます。最初のバージョンでは取得間隔を60秒としました。まだ使い込んでいないため、適切な間隔とは言えません。ぜひ使用した方の意見が欲しいところです。検索条件の変更頻度を学習して自動で間隔を決められたら面白そうですね。

「保存された検索」との違い

Evernoteには「保存された検索」機能があります。「保存された検索」に登録するほどでもないけれど、ちょっと残しておきたいような検索があるでしょう。そんなときにEverQueryがきっと役に立ちます。「保存された検索」との違いは

  1. 複数デバイスで同期されない
  2. 自動保存
  3. 検索条件に名称がつかない
  4. 検索条件の保存が永続的でない
という点です。少し詳しく説明します。

1. 複数デバイスで同期されない

検索条件をEverQueryのアプリケーション内に保存します。そのため、Evernoteの特長である複数デバイスでの同期はできません。

もしかしたらDropboxなどを経由して複数Mac間での同期が可能かもしれませんが、公式にはサポートしません。自己責任でお願いします。

2. 自動保存

検索条件を自動保存します。また「保存ボタン」などの保存する手段がありません。

保存に手間がかかると使わなくなります。そのため、EverQueryは全自動で検索条件を保存する仕様にしました。

3. 検索条件に名称がつかない

自動的に検索条件を取得するため、検索条件に名称はつきません。

検索条件に名称をつけるにはユーザからの入力が必要ですが、なるべくバックグラウンドで実行することを想定しているので、今のところEverQueryの方針と異なります。良い方法が思いつけば実装するかもしれません。

4. 検索条件の保存が永続的でない

検索条件の保存数に上限を設けています。最初のバージョンでは重複を除き15件までの検索条件を保存します。それ以上増える場合は、古い検索条件から自動的に削除されます。

あまりに古い検索条件が残っていても見つけにくく、EverQueryの動作が重くなるため上限を設けました。

AppleScriptを少しでも操作できる人は自身で上限を変更することが可能です。EverQueryをAppleScript エディタ.appで開き、propertyにある「historyNum」(2行目)の値を変更して下さい。ただし、コンパイルするとそれまでの検索条件はリセットされます。

「戻る/進む」機能との違い

ところで、Evernote for Macには同様の機能として「戻る/進む」機能があります。もちろん違いはあります。「戻る/進む」機能はノートごとの閲覧履歴であり、検索条件が保存されるわけではありません。この違いを利用してうまく使い分けることができるはずです。

おわりに

EverQueryは「ログイン時からシャットダウンまで起動し続け、必要なときに使う」ことを想定して作成しました。そのため、Evernoteが起動していなくても問題ありません。ぜひログイン項目に追加して使ってほしいアプリケーションです。

これからもアップデート予定です。要望があれば積極的に取り入れたいと考えています。意見、要望は@s_z_k_3へどうぞ。


EverQuery - Evernoteの検索条件を保存し、呼び出すAppleScript

Recreating OS X media keys on the command line

Place this at ~/mediakeys.scpt (download):

on run argv
    if (count of argv) is greater than 0 then
        set theCommand to item 1 of argv
    else
        set theCommand to ""
    end if
    
    set systemVolume to (output volume of (get volume settings))
    
    if theCommand is equal to "-" then
        set volume output volume systemVolume - 5
    else if theCommand is equal to "--" then
        set volume output volume systemVolume - 10
    else if theCommand is equal to "+" then
        set volume output volume systemVolume + 5
    else if theCommand is equal to "++" then
        set volume output volume systemVolume + 10
    else if theCommand is equal to "mute" then
        set volume output volume 0
    else if theCommand is equal to "unmute" then
        set volume output volume 45
        
    else if appIsRunning("Rdio") then
        tell application "System Events"
            if theCommand is equal to "n" or theCommand is equal to "next" then
                tell application "Rdio" to next track
            else if theCommand is equal to "p" or theCommand is equal to "previous" then
                tell application "Rdio" to previous track
            else
                tell application "Rdio" to playpause
            end if
        end tell
        
    else if appIsRunning("iTunes") then
        tell application "System Events"
            if theCommand is equal to "n" or theCommand is equal to "next" then
                tell application "iTunes" to next track
            else if theCommand is equal to "p" or theCommand is equal to "previous" then
                tell application "iTunes" to previous track
            else
                tell application "iTunes" to playpause
            end if
        end tell
    else
        beep
    end if
end run

on appIsRunning(appName)
    tell application "System Events" to (name of processes) contains appName
end appIsRunning

…and alias it:

alias m="osascript ~/mediakeys.scpt"

Supports iTunes and Rdio, whichever is open. Available commands:

  • m to play or pause
  • m n or m next for next track
  • m p or m previous for previous
  • m + / m ++ to increase system volume by 5 or 10%
  • m - / m -- to decrease
Faster After Effects by renice

After Effects normally drown your mac, especially when you have not a lot of memory. What happen when you renice the process related to After Effects? Machine fly fast.

By renice the process related to After Effects and some related to the system you will have your mac run better. Just launch this script after launching after effects and render a few frames (ram preview, render).

The script will renice the priority of After Effects processes, and some others that will let you not hang After itself. And let you run iTunes, Dropbox without problems when working with After Effects.

DOWNLOAD APPLE SCRIPT / DOWNLOAD MAC APPLESCRIPT APP

Snow Leopard Services... pt3, Google Voice

Seemless integration of Google Voice into Snow…

Select a phone number in any application, right click, select the services sub-menu, and choose either gvDialer or SMSgv to initiate a phone call or send a text message through your Google Voice account.

If texting, a dialog box will pop up for you to type in your message.

Growl will growl (if you’re a growler) upon dialing/sending the message.

The first time you run this the service will ask you to enter your Google Voice account info (it’ll get stored in your Keychain). The services also require a php script to do the heavy lifting and you’ll get asked about installing that to your Home/Library/Services folder.

gvDialerServices.zip

There’s also Quicksilver actions that do the same thing. Once installed:

Activate Quicksilver, and either enter a phone number in QS’s text entry mode, or use QS to search your Address Book and find a phone number.  The point being to get a phone number into QS’s first pane. 

Tab over to QS second pane and type till you see either gvDialer or smsGV (depending on what you want to do, dial or text). and hit enter. If you’re texting a dialog box will appear allowing you to enter your text message.

To install: download and unzip the following file below, move the two actions smsGV.applescript and gvDialer.applescript to   ~/Library/Application Support/Quicksilver/Actions/   (where ~ means your home folder, and if you don’t already have a folder in Application Support/Quicksilver/ named actions, make one, and put the two files there. Restart Quicksilver and you should be good to go.

gvQSactions.zip

Minimize It For Me!

When I’m at work, I have a second monitor, and I use it for very important, and very lucrative things (more or less).  However, when I’m ready to go home, I no longer need the extra real estate, so I minimize any open window on the second screen, to reopen the next day when I return to work.  

The tragedy is that I have to do all this by hand, and it’s annoying!  Sure, it’s not that annoying or time consuming, but it’s something else I have to do that should be done in a single click…

Enter MinimizeIt!, the super fantastic script I wrote that will automatically send any windows on the second display to the dock.  It has a few limitations, like certain applications that don’t recognize it’s siren song of minimization, but otherwise is rather helpful.

Get it here!

Comments, Questions, Suggestions?  I’m here to help and always looking for feedback!

用AppleScript实现窗口布局器

Blog没怎么写,倒是天天总结AppleScript~ 其实可以写个applescript分类了,呵呵~

最近又折腾一档子 便民 利己小工具,窗口布局器。这名字听起来怪怪的,我也没有怎么仔细想过,姑且先这么叫吧。需求来源是,有时候要对照某个web页面的内容,在另外一个web页面或者其他程序里面写邮件或者做其他事情,这个需求是很多人都有的,工作生活中也很常见。解决办法一般都是移动和缩放两个窗口摆在桌面两边,或者上下两部分,或者两个显示器上。如果有个工具可以方便快捷完成这个操作,那应该不错。今天的“窗口布局器”就完成的这个功能;并且我还借鉴了Windows 7中摸索到的还没有精确确认的neat小功能,WIN+上下左右方向键对窗口进行最大/最小化等操作,最终让今天折腾的窗口布局器和QuickSilver快捷键设置绑定起来,做到最快布局窗口。

功能需求/描述是这样:编写 ResizeRepos.scpt ,通过执行它可将当前窗口尺寸变为全屏幕的高,全屏幕的N分之一宽,并且移动到距离窗口左上角位置最近的(宽度的N分之一的整数倍,0)的坐标。用通俗点的语言就是,假设你想把屏幕分成左右两半,执行ResizeRepos.scpt脚本后,无论你现在打开的是Terminal还是Preview,都会使窗口占据屏幕的一半,是左半边还是右半边取决于窗口原始位置是略靠左还是略靠右。如果已经移动到了屏幕的最左边,再次执行该脚本会将窗口移到最右边,再执行一次会移动回最左边。更为奇妙的是,如果你的桌面足够大,将屏幕分为三份/四份也是可以的。

废话不多说,上代码~~


property _deskwidth : 2048
property _deskheight : 1152
property _segments : 2

on run argv
    if (count argv) is not 0 then
        set _segments to (item 1 of argv) as integer
    end if
    set _cellw to _deskwidth div _segments
    set name_ to the name of (info for (path to frontmost application))
    tell application name_
        set {_posx, _y, _bx, _by} to bounds of front window
        set _newpos to _posx div _cellw * _cellw + _cellw
        if (_newpos ≥ _deskwidth) then
            set _newpos to 0
        end if
        set the bounds of the first window to ¬
        {_newpos, 0, _newpos + _cellw, _deskheight}
    end tell
end run


注:“¬”是折行符号,实际写的时候可以把它连接的两行连起来;“≥”是大于等于号,输入>=即可,保存的时候AppleScript Editor会自动变为≥

解释之:

  • _deskwidth 和 _deskheight 是自己桌面的宽和高,自己根据需要调整;动态获取也是可以的,比如获取宽度就是 set _deskwidth to word 3 of (do shell script "defaults read /Library/Preferences/com.apple.windowserver | grep -w Width") as number;显然自己桌面尺寸不会天天变,我们就不动态获取了;还有就是对于双显/三显/四显的土豪们,请参考 Daring Fireball 06年某文 解释多显虚拟桌面计量的文章,此处不多讨论

  • if (count argv) is not 0 then 一直到if结束,是获取执行时候的参数;我们希望调用的时候调用者告诉脚本是将屏幕划分为两半还是三瓣。。。

  • set name_ to the name of (info for (path to frontmost application)) 此行获取当前程序的名称,下面的tell都是在该程序中进行操作

  • set {_posx, _posy, _botx, _boty} to bounds of front window 获取当前程序的当前窗口左上角xy坐标右下角xy坐标

  • 对获取的xy坐标进行计算,这么简单的就不解释了,然后通过 set the bounds of the first window to {_newpos, 0, _newpos + _cellw, _deskheight} 将新坐标发回给窗口,就设置完成了位置和尺寸

仅仅写完了这个还没有彻底结束,这个script如果只是在Finder里双击运行或者Terminal里命令行执行,就只能修改修改这俩程序的窗口位置和尺寸了。现在我编写了两个脚本split2.sh和split3.sh,各自都只有一行,他们分别是 osascript /Users/kcome/sh/scripts/ResizeRepos.scpt 2 和 osascript /Users/kcome/sh/scripts/ResizeRepos.scpt 3 ;看到了吧,只有最后一个字符不同,第一个就是分两半的方案布局窗口,第二个是分三瓣。

然后进入QuickSilver的Triggers界面,添加项目,Select an item选择刚才写的split2.sh,Action就是默认的Run […],Target随便写一个字符(否则用快捷键启动时候会被询问Target,其实在这里是无用的参数);然后添加保存,指定快捷键,就大功告成了。按下快捷键试试吧?

其实,要说我这博有啥意义的话,我想只有两点,一个是想说AppleScript很强大,基本上发挥自己的想象力,可以完成许许多多的有趣有用功能;另外一个就是,善用google,勇于尝试,我不过是花了一两个小时,搜索了不到十个关键词组,比如“applescript get current desktop size”、“move window by applescript”、“howto get argument in applescript”,加上试验,修改,调试,就完成了这个功能。所以,写程序也不难,让电脑听话也是有趣事:)

参考最多的一篇博文 Applescript: Moving and Resizing Windows

Scripting again

Being struggling with a load of files with dumped from various camcorders. I don’t know of a video file manager but wanted to be able to stream these to my TV via WDLive.

I searched the net for some scripts to help but found nothing that’d do the trick so wrote the following scripts to Create Year folders, move the files based on creation date into the appropriate folder, then create monthly folders and repeat.


Create Year Folder script



set Myyears to {2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011}
tell application “Finder”
set inputFolder to choose folder with prompt “Choose input folder”
repeat with i from 1 to count of Myyears
set newName to item i of Myyears
make new folder at inputFolder with properties {name:newName}
end repeat
end tell

Move the files into the year folders

tell application “Finder”
set inputFolder to choose folder with prompt “Choose input folder”
set MyFiles to files of inputFolder
repeat with i from 1 to count of MyFiles
set MyFile to item i of MyFiles
set Mydate to creation date of MyFile
set Myyear to year of Mydate
set Destinationfolder to (1st folder of inputFolder whose name starts
With Myyear)
move MyFile to Destinationfolder
end repeat
end tell

Create Monthly Folders


set MyMonths to {“January”, “February”, “March”, “April”, “May”, “June”, “July”, “August”, “September”, “October”, “November”, “December”}
tell application “Finder”
set inputFolder to choose folder with prompt “Choose input folder”
repeat with i from 1 to count of MyMonths
set newName to item i of MyMonths
make new folder at inputFolder with properties {name:newName}
end repeat
end tell

Move the files into the monthly folders

tell application “Finder”
set inputFolder to choose folder with prompt “Choose input folder”
set MyFiles to files of inputFolder
repeat with i from 1 to count of MyFiles
set MyFile to item i of MyFiles
set Mydate to creation date of MyFile
set Mymonth to month of Mydate as string
set Destinationfolder to (1st folder of inputFolder whose name is Mymonth)
move MyFile to Destinationfolder
end repeat
end tell

How to make iCal play nice with Sparrow

It’s no secret I love Sparrow. I’ve been using it since it was in beta and I’m a very happy customer.

Abandoning Apple Mail for a third party e-mail application however does come with it’s quirks. Apple was nice enough to not respect the “Default e-mail reader” setting (which is in Apple Mail itself btw) in many of it’s applications including iCal. I’m a quite heavy iCal user and have been annoyed with this ever since I switched over to Sparrow.

What basically happens is that whenever you have an e-mail reminder set in one of your calendar entries iCal will launch Apple Mail to send you this reminder. Even-though you might not be using Apple Mail. This is especially annoying if you have never even opened or set-up mail and therefor have no e-mail accounts there. Luckily this behavior is modifiable trough Applescript.

Today I was pointed to this blog post showing how to interact with Sparrow trough Applescript. I immediately hacked together a script to fix my issues with iCal. And I am happy to report it works like a charm and my iCal now finally sends e-mails trough Sparrow. Check out the project on github. Many thanks go out to @dinh_viet_hoa for making this possible.

EDIT: I hope my explanation on how to install it is clear enough. If you have any questions or suggestion feel free to hit me up in twitter or github

Control Growl and Notification Center via Alfred.app

Update:
This extension is also available for Alfred 2.
http://blog.kudusch.de/post/45504491057



Just a small extension to control Growl.app and Mountain Lions Notification Center within Alfred.
You’ll need version +1.3 of Growl.

You can use the following keywords:

Pause Growl + Notification Center : p/pause
Resume Growl + Notification Center : resume/r
Pause Growl : gr/growl
Pause or resume Notification Center : nc
Close all growl notifications : c/close
Shows the rollup : show/s
Hides the rollup : hide/h
Enables the incoming network : enable/e
Disables the incoming network : disable/d
Shows the current status of Growl : status/stat
Restarts Growl : restart/res
Settings : settings
Lists these commands : help/?

Or change them in the settings dialog:

Just download this extension, install it and it’s ready to use.


This extension is written in AppleScript.
If you experience any troubles with this, hit me on twitter.
Enjoy.

Changelog:
v1.3.1
-New icon, keyword and name
-The status dialog now shows Notification Center’s
-Resolved a bug where Notification Center wouldn’t react properly to the “pause” or “resume” keywords
-Moved the location for the settings plist (resolves issues with Alfred Sync)

v1.3
-Added Notifications Center support
-Settings

v1.2.2
-Added notification after commands

v1.2.1
-Minor bugfixes
-Changed help text

v1.2
-Added command to restart Growl

v1.1
-Added shorter keywords
-Added „status“-keyword
-Added an icon to the help and status windows


If you don’t have the Alfred Powerpack or you don’t want to use Alfred for this task, you can find the source code of the extension here: https://snipt.net/Kudusch/control-notification-center-and-growlapp/

Yet more scripting

Have been ripping some of my audio DVDs and unfortunately don’t have software to automagically tag the files. I use Tag to tag my FLAC files but it’s a but laborious by hand so wrote a script to rename the files with the track names, etc which can be guessed by Tag

The script prompts for Band Name, Album and track list
The first two can be typed or pasted into the dialog
The track list should be pasted, I normally prepare a text file with each track listed on a line (press enter after each line)

It will check with you before renaming the files that the match is correct

Use it at your own risk and would suggest you try on copies of files first


Code Begins

============================
–Get Band Name
display dialog “Please enter band name” default answer “” buttons {“Ok”} default button 1
copy the result as list to {text_returned, button_pressed}
set Band to item 1 of result
–Get Album Name
display dialog “Please enter album name” default answer “” buttons {“Ok”} default button 1
copy the result as list to {text_returned, button_pressed}
set Album to item 1 of result
–insert file suffix
display dialog “Please enter File suffix e.g. flac, Mp3” default answer “” buttons {“Ok”} default button 1
copy the result as list to {text_returned, button_pressed}
set Suffix to “.” & item 1 of result
–Get Tracklisting
display dialog “Please Paste in track list” default answer “
” buttons {“Ok”} default button 1
copy the result as list to {text_returned, button_pressed}
set MyTrackList to item 1 of result
–Create New File Nameswith the format
–Band-Album-tTrackNumber-TrackName.Suffix
set TrackCount to count of paragraphs in MyTrackList
set MyTracks to {}
repeat with i from 1 to TrackCount
set MyTrackName to Band & “-” & Album & “-t” & i & “-” & (paragraph i of MyTrackList) & Suffix
copy MyTrackName to end of MyTracks
end repeat
–Now we have a track listing
MyTracks
–Identify the files we are about to rename
tell application “Finder”
set MyFiles to selection
set MyFileNames to {}
repeat with i from 1 to count of MyFiles
copy name of (item i of MyFiles) to end of MyFileNames
end repeat
end tell
–Now we have the file names
MyFileNames
–Create Checklist for review before renaming the files
set Checklist to {}
repeat with i from 1 to TrackCount
set Checkitem to item i of MyFileNames & “ will convert to ” & item i of MyTracks
copy Checkitem to end of Checklist
end repeat
display dialog (choose from list Checklist)
if button returned of result is “ok” then
tell application “Finder”
set MyFiles to selection
repeat with i from 1 to count of MyFiles
set name of item i of MyFiles to item i of MyTracks
end repeat
end tell
end if
==============================

Code Ends

Starting a VPN if it is not connected via AppleScript

Launching a VPN if it is not connected on OS X:

tell application "System Events"
  tell current location of network preferences
    set VPNservice to service "My VPN" -- name of your VPN
    set isConnected to connected of current configuration of VPNservice
    if not isConnected then connect VPNservice
  end tell
end tell

…prefect for automating “things” in Proxi.

Translate words or phrases between languages inside your AppleScript.

 

This handler translates a string variable from one language to another. I couldn’t find anything useful on the web so I had to write my own. It’s by far the most comprehensive handler I’ve written so there may be a few bugs. If you find one, please leave a comment.

Instructions on how to use the handler are in the comment sections of the script. If you can’t get it to work, let me know.

Credits for the switchText handler go to the various MacScripter members in this post.

The script is after the break.

Keep reading

dl.dropbox.com
Get Hardware Info!

If you manage users, or support your friends and family, it can be helpful to quickly get information about their Mac.  It’s not too difficult to ask them how much hard drive space they have free, or how much RAM their machine has, but getting stuff like their MAC address or serial number is tricky.

Hence the above script, which will do all that for you!  The user simply runs the app, which will prompt them for an email.  They put in your email address, or whoever needs to receive the info, and then off it goes.  

Here’s what it grabs:

MAC Address 
Serial Number
Model Number
Network/Shared Name

Sure, there are other important items, and it’s a fairly easy edit to add others, but again, my main goal was to get the information it’s difficult to describe getting to the non-geek inclined.

Comments, Questions, Suggestions?  I’m here to help and always looking for feedback!