Порядок с контактами в Адресной книге на MacOSX c помощью Apple script.

топ 100 блогов apple_russia23.10.2010 Из Порядок с контактами в Адресной книге на MacOSX c помощью Apple script. [info]ru_mac  отправили сюда, чтобы добро не пропадало. Может кто возьмется доработать...

Обычная ситуация - бардак в записной книге контактов. За годы скопились контакты со всевозможными вариациями написания номера. Основная проблема это +7 и 8 в начале номера.

Порядок с контактами в Адресной книге на MacOSX c помощью Apple script.

Очень неудобно за границей, да и при синхронизации контактов с другими системами постоянно появляются несостыковки. Перебивать номера вручную невеселая работа, на помощь приходит AppleScript.


Вот что нужно для работы этого скрипта:
- MacOSX 10.5 и старше
- 5 минут.

Предупреждение:
Вы используете этот скрипт на свой страх и риск! Сохраните все свои контакты в архив!

Есть вероятность что скрипт может некорректно обработать международные номера (номера Испании, Франции и Великобритании игнорируются и остаются как и должны быть).

Поехали?

Шаги:

1) Сохраняем все контакты в архив File > Export > Adress Book Archive
2) Проверить точно ли сохранили архив.
3) Скачаиваем скрипт www.skorenev.ru/blogs/FixCRPhoneNumbers1.1.zip
4) Сделать еще одну копию архива Адресной книги, на всякий случай. 8)
5) Открываем скрипт (двойной клик или Utilities > AppleScript Editor > Open File)
6) Активируем кнопку Run (верхний левый угол в AppleScript Editor)

PS
Объязательно проверьте, правильно ли телефоны обработались. ;)

PSS

Сам скрипт ниже

#------------------------------------#
(*script done with content from

http://www.mactech.com/articles/mactech/Vol.21/21.10/ScriptingAddressBook/index.html
http://vocaro.com/trevor/software/applescript/Remove%20Duplicate%20Phone%20Numbers.zip
http://www.apple.com/applescript/sbrt/sbrt-06.html
http://www.grupoice.com/esp/temas/camp/2_8_dig/index.htm

Script Based on script by Christian Saborío
[email protected]
http://www.grumpytico.com

Remake for Russian phone numbers by Korenev Sergey
[email protected]
http://www.skorenev.ru

*)

display dialog "Warning: Be sure to back up your Address Book database first!" & return & return & "Do you still want to continue?"


property prependCRAreaCode : "+7"

tell application "Address Book"
set contactlist to selection
repeat with i from 1 to the count of contactlist
set currentPerson to item i of contactlist
set phonePropertes to properties of phones of currentPerson
repeat with i from 1 to the count of phonePropertes
set currentItem to item i of phonePropertes
set oldLabel to label of currentItem
set oldPhone to value of currentItem
set newPhone to my checkNumber(oldPhone, oldLabel)
set names to (first name of currentPerson) & " " & (last name of currentPerson)

-- если федеральный номер сотового или полный номер с кодом
if (length of newPhone = 12) then
delete (phones of currentPerson whose id is id of currentItem)

-- формируем формат +7 (###) ### ## ##
set formatedPhone to newPhone
set countryCode to ((characters 1 thru 2 of newPhone) as string)
set operatorCode to " (" & ((characters 3 thru 5 of newPhone) as string) & ") "
set part01 to ((characters 6 thru 8 of newPhone) as string) & " "
set part02 to ((characters 9 thru 10 of newPhone) as string) & " "
set part03 to ((characters 11 thru 12 of newPhone) as string) & " "
set formatedPhone to countryCode & operatorCode & part01 & part02 & part03
make new phone at end of phones of currentPerson with properties {label:oldLabel, value:formatedPhone}

-- часть сохранения, без этого у меня не заработало 8)
make new url at end of urls of currentPerson with properties {label:"Work", value:"http://www.needtowork.com"}
delete (urls of currentPerson whose value is "http://www.needtowork.com")
save
end if


-- если городской номер
if (length of newPhone = 7) then
delete (phones of currentPerson whose id is id of currentItem)

-- формируем формат +7 (495) ### ## ##
set formatedPhone to newPhone
set countryCode to "+7"
set operatorCode to " (495) "
set part01 to ((characters 1 thru 3 of newPhone) as string) & " "
set part02 to ((characters 4 thru 5 of newPhone) as string) & " "
set part03 to ((characters 6 thru 7 of newPhone) as string) & " "
set formatedPhone to countryCode & operatorCode & part01 & part02 & part03

-- часть сохранения, не спрашивайте зачем 8)
make new phone at end of phones of currentPerson with properties {label:oldLabel, value:formatedPhone}
make new url at end of urls of currentPerson with properties {label:"Work", value:"http://www.needtowork.com"}
delete (urls of currentPerson whose value is "http://www.needtowork.com")
save
end if
end repeat
end repeat
end tell


on checkNumber(phoneNumber, phoneLabel)

set trimmedPhone to replace_chars(phoneNumber, "+", "")
set trimmedPhone to replace_chars(trimmedPhone, " ", "")
set trimmedPhone to replace_chars(trimmedPhone, "(", "")
set trimmedPhone to replace_chars(trimmedPhone, ")", "")
set trimmedPhone to replace_chars(trimmedPhone, "-", "")


-- очищенный городской
if (length of trimmedPhone = 7) then
if phoneLabel = "mobile" or trimmedPhone begins with trimmedPhone then
set phoneNumber to trimmedPhone
end if
end if

if (length of trimmedPhone = 11) then
-- режем сотовый числовую форму из 8 (###) ### ## ##
if trimmedPhone begins with "8" then
set trimmedPhone to ((characters 2 thru 11 of trimmedPhone) as string)
end if

-- режем сотовый числовую форму из +7 (###) ### ## ##
if trimmedPhone begins with "7" then
set trimmedPhone to ((characters 2 thru 11 of trimmedPhone) as string)
end if
if phoneLabel = "mobile" or trimmedPhone begins with trimmedPhone then
set phoneNumber to prependCRAreaCode & "" & trimmedPhone
--display dialog phoneNumber
end if
end if
return phoneNumber
end checkNumber

on replace_chars(this_text, search_string, replacement_string)
set AppleScript's text item delimiters to the search_string
set the item_list to every text item of this_text
set AppleScript's text item delimiters to the replacement_string
set this_text to the item_list as string
set AppleScript's text item delimiters to ""
return this_text
end replace_chars

#------------------------------------#

Оставить комментарий

Архив записей в блогах:
Новые репрессивные законы в России - не из-за Майдана. Сегодня именно внутренние проблемы России обуславливают принятие новых репрессивных законов. В этом уверен руководитель Центра экономических исследований Института глобализации и социальных движений Василий Колташов. Почитайте его ...
После того, как пыль от саморазрушения "Правого дела" улеглась, можно окинуть взглядом весь получившийся ландшафт перед выборами. Что мы теперь там видим? А видим мы то, что стратегически теперь воплощается худший для Кремля (при имеющихся ...
Фото: Присланные из Суксуна фото стационарный пост ДПС «Ирень», расположенный в 30 километрах от поселка-райцентра Суксун Пермского края после ночного бояРано утром 12 июня, ближе к трем часам утра 12 июня на стационарный пост ДПС «Ирень», ...
Сеть фастфуда "Вкусно и точка" закончила 2022 год с убытками в размере 11,3 миллиарда рублей. Это всё, что вам нужно знать о русском ребрендинге - бессмысленном и беспощадном. ...
Если в начале российской мелодрамы показана счастливая хихикающая и сюсюкающая семья, значит через 15 минут половина ее членов будет уничтожена насмерть волею российских сценаристов. Вот счас фоном, нопремер, идет типичне случай. Посюсюкали первые пять минут и будя, уже труп одного ...