31/10/08
AdiumScript: Firefox 3 Current Page v1.2a

Comme dit dans ce précédent billet : AdiumScript: Firefox 3 Current Page, un bug AppleScript[1] dans Firefox 3 empêche les AdiumScripts de récupérer le titre de la page en cours de consultation dans Firefox par Adium… c'est pourquoi j'avais déjà écrit un précédent AdiumScript se basant sur curl[2], cependant la libcurl présente quelques limitations[3] (du moins sur ma machine[4] sous Mac OS X 10.5.5). Ces limitations de la libcurl, la présence du même bug après que plusieurs versions de Firefox se soient succédées et certaines limites inhérentes au mode de rédaction du précédent script m'ont amenés à écrire une nouvelle version du "même" script.
Celui-ci embarque désormais une Universal Binary (compatible Intel et PPC) de wget[5][6] pour récupérer le contenu sur le web. L'utilisation de wget permettant aussi de s'affranchir de certaines limitations en apportant, notamment, le support de HTTPS.
Bien que ce nouvel AdiumScript conserve un mode de fonctionnement similaire au précédent, un certain nombre de nouvelles fonctionnalités ont été apportées dont le support de Growl ; grâce à un script Bash, utilisant osascript, nommé growlnotify[7].
De plus, il est maintenant possible de localiser cet AdiumScript, du moins en ce qui concerne la plupart des messages affichés grâce à Growl.
Structure des fichiers
Firefox3CurrentPage.AdiumScripts |-- Contents | |-- Resources | | |-- English.lproj | | | `-- Localizable.strings | | |-- Firefox3CurrentPage.scpt | | |-- French.lproj | | | `-- Localizable.strings | | |-- fetch-title | | |-- growlnotify | | `-- wget | `-- Resources Disabled `-- Info.plist 5 directories, 7 files
Cette structure est assez similaire à celle de n'importe quel AppleScript, avec notamment la présence des dossiers .lproj dans le dossier Resources.
Firefox3CurrentPage.scpt
(* Firefox3CurrentPage.AdiumScripts Harry-Proton <http://blogosx.homeunix.org/> updated 2008-11-01T22:20:22+01:00 Copyright (C) 2005 Free Software Foundation, Inc. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. *) script Firefox3CurrentPageObj property scriptPath : missing value property bundlePath : missing value property scriptName : "Firefox3CurrentPage.AdiumScripts" property aliasFolder : missing value property UA : "" property firefoxProperties : missing value property cURL : "" property title : "" property processFirefox : 0 property processAdium : 0 on setBunldeProperties() set scriptPath to ((do shell script ("dirname " & quoted form of (POSIX path of (path to me)))) & "/") set aliasFolder to POSIX file scriptPath end setBunldeProperties on setUA() if (processAdium > 0) then tell application "Adium" to ¬ set adiumProperties to (its properties) set UA to (name of adiumProperties & "/" & version of adiumProperties & " (+http://www.adiumx.com)") as string end if end setUA on setFirefoxProperties() tell application "Minefield" to ¬ set firefoxProperties to (properties of window 1) set cURL to «class curl» of firefoxProperties set title to «class pTit» of firefoxProperties end setFirefoxProperties on countProcesses() tell application "System Events" set processFirefox to ¬ ((application processes whose (name is equal to "firefox-bin")) count) as integer set processAdium to ¬ ((application processes whose (name is equal to "Adium")) count) as integer end tell end countProcesses end script script notifier property appName : missing value property gmsg : "" property gtit : "" property appIcon : "Adium" on setAppName() set appName to get scriptName of Firefox3CurrentPageObj end setAppName on notify(tit, msg) set {gmsg, gtit} to {msg, tit} set obj to Firefox3CurrentPageObj setAppName() set args to ¬ {quoted form of (appName), quoted form of (gtit), quoted form of (gmsg), quoted form of (appIcon)} do shell script ((quoted form of (scriptPath of obj & "growlnotify")) & ¬ space & (args as string) & " &> /dev/null &") end notify end script script Wget property UA : "" property cURL : missing value on fetch_title(trgt) set cURL to trgt set obj to Firefox3CurrentPageObj set xbin to (quoted form of scriptPath of obj & "fetch-title") set args to ((quoted form of trgt) & space & (quoted form of UA)) return do shell script xbin & space & (args as string) end fetch_title end script on substitute() set text item delimiters to space tell my Firefox3CurrentPageObj set obj to Firefox3CurrentPageObj setBunldeProperties() countProcesses() setUA() end tell if ((get processFirefox of obj) > 0) then try tell my Firefox3CurrentPageObj to setFirefoxProperties() on error m number n tell my notifier to notify((my localized_string("Error") & space & n), m) end try else tell my notifier notify(my localized_string("Error"), my localized_string("Firefox is not running.")) end tell end if if ((count items of (get title of obj)) < 1) then tell my notifier notify(my localized_string("Fetching"), localized_string("Fetching content from web.")) end tell try tell my Wget set its UA to UA of obj set title of obj to fetch_title(cURL of obj) end tell on error m number n tell my notifier notify(my localized_string("Error") & space & n, m) end tell return (get cURL of obj) end try end if set text item delimiters to return return ("<HTML><a href=\"" & (get cURL of obj) & "\">" & (first text item of title of obj) & "</a></HTML>") as string end substitute on localized_string(str) set obj to Firefox3CurrentPageObj set uFolder to POSIX file (do shell script "cd " & quoted form of (scriptPath of obj) & " && cd ../.. && echo \"$(pwd)\"") tell application "System Events" return get localized string str ¬ from table "Localizable" in bundle alias uFolder end tell end localized_string on run substitute() end run
La partie en AppleScript a été réécrite avec une plus grande orientation objet. Comme on peut le constater, il est nécessaire de faire appel à de nombreuses applications, qui peuvent être en train de fonctionner ou non : Firefox, Adium, Finder[8], System Events, Growl ; et la POO permet, tout en allégeant le code, et en, je l'espère, le rendant plus compréhensible, de limiter les appels redondants à certaines applications ; je pensais principalement au Finder, jusqu'à temps que je ne m'aperçoive qu'il ne semble pas possible de l'utiliser depuis un AdiumScript
; mais aussi à System Events.
Licence
Comme cet AdiumScript embarque avec lui une binaire GNU Wget 1.11.4[9], j'ai choisi de mettre ce script et le reste du bundle sous la même licence.
fetch-title
#!/bin/bash # Time-stamp: <2008-10-31 10:52:26 (blogosx.homeunix.org)> # # Copyright (C) 2005 Free Software Foundation, Inc. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. function fetch-title () { local wget="$(dirname "$0")/wget" function fetch () { local URL="$1" [[ -z "$2" ]] && local UA="$(bash --version | grep -o "version")" || local UA="$2" "$wget" -q -O - "$URL" -U="$UA" --no-check-certificate | cat } function main () { local content=$(fetch "$1" "$2") local charset=$(echo "$content" | egrep -o "charset=([A-z0-9-]+)" | awk -F "=" '{print $2}' | tr [a-z] [A-Z]) local pgtitle=$(echo "$content" | egrep -o "<title>(.*)</title>") [[ -n "$pgtitle" ]] && { pgtitle=$(echo "$pgtitle" | awk -F "<title>" '{print $2}' | awk -F "</title>" '{print $1}') pgtitle=${pgtitle//"'"/"\'"} pgtitle=$(php -r "echo(html_entity_decode('$pgtitle'));") [[ -n "$charset" && "$charset" != 'UTF-8' ]] && { pgtitle=$(echo "$pgtitle" | iconv -f "$charset" -t utf-8) || { echo "$pgtitle" >&1 exit 1 } } echo "${pgtitle}" } || { echo "Can not fetch title from: $1" >&2 echo "$1" >&1 exit 145 } exit 0 } main "${@}" } fetch-title "${@}" # Local Variables: # mode: Shell-script # coding: mule-utf-8 # End:
Growl
La notification utilisée par le script peut être configurée ou désactivée grâce au PrefPane de Growl dans les Préférences Système. Cette notification porte le nom du scrip et utilise l'icône de l'application Adium.
La notification, bien que ne portant qu'un seul nom, a deux rôles. Premier rôle : notifier que la récupération du contenu a commencé ; certaines fois le reste du script se déroule si vite, dépendamment de la BP et du poids du document, que Growl ne se déclenche qu'après le résultat du script. Deuxième rôle : signaler les erreurs, comme par exemple l'impossibilité de récupérer le titre d'une page, si les balises <title> et </title> sont écrites en majuscules, notamment, ce qui n'est pas conforme au standards définis par le W3C de toute façon.
Firefox 3 Current Page v1.2a
Télécharger : Firefox3CurrentPage-1.2a.zip
MD5 (Firefox3CurrentPage-1.2a.zip) = e99c5d5d6abb52cf7ce67ab7bfd1c783
Notes
[1] Bug 427448
[3] curl: (1) Protocol https not supported or disabled in libcurl
[4] Mac mini Intel Core Duo 1,66 GHz
[7] script bash inspiré et en parti réécrit de celui-ci : PulsPlayer (player radio Puls'Radio)
[8] pas d'appel au Finder, il semble que ce ne soit pas possible depuis un AdiumScript