===== Автоматизация скачивания torrent в macOS ===== {{:apple-mac-os:macos-monterey:pasted:20220203-103711.png }} Рассмотрим пример использования "Действия папки" для автоматизации отправки **.torrent** файлов на удалённый сервер **transmission**. В рассматриваемом примере **transmission** установлен на роутере **ASUS** с кастомной прошивкой от **Merlin**. Подсмотрев пример в [[https://blog.flo.cx/2011/02/how-to-open-magnet-links-on-a-remote-transmission-daemon-with-one-click/|этом блоге]], создал автоматизацию действия папки по старинке в **Automator.app** и используя shell-script. {{ :apple-mac-os:macos-monterey:pasted:20220203-104925.png }} Текст скрипта: #!/bin/zsh for file in "$@" do if [[ "$(basename ${file##*.})" == "torrent" ]] then #Authentication HOST=My-Router.local PORT=9092 USER=torruser PASS=torrpassword #Encoding torrent file METAINFO=$(base64 -i $file) # set true if you want every torrent to be paused initially #PAUSED="true" PAUSED="false" #Push SESSID=$(curl --silent --anyauth --user $USER:$PASS "http://$HOST:$PORT/transmission/rpc" | sed 's/.*//g;s/<\/code>.*//g') curl --silent --anyauth --user $USER:$PASS --header "$SESSID" "http://$HOST:$PORT/transmission/rpc" -d "{\"method\":\"torrent-add\",\"arguments\":{\"paused\":${PAUSED},\"metainfo\":\"${METAINFO}\"}}" # Remove .torrent file rm $file -f fi done Однако день спустя, наткнулся на [[https://forum.transmissionbt.com/viewtopic.php?t=7786|реализацию]] на **AppleScript**, которая мне показалась интереснее, поэтому начал изучение вопроса с начала. В итоге получился рабочий вариант, который не зависит от устаревающего **Automator**, также добавлена обработка ошибок и уведомления. Сохраняем скрипт в каталоге ''~/Library/Scripts/Folder Action Scripts'' --Глобальная переменная, передаём расширение файла property FileExt : "torrent" --Выполняется при любом добавлении файла в каталог on adding folder items to this_folder after receiving added_items repeat with torrentFile in added_items tell application "System Events" --если добавленный файл имеет расширение torrent, процесс запускается if the name extension of the torrentFile is equal to FileExt then --Параметры переменных подключения к серверу --Пользователь, пароль, порт настраиваются в /opt/etc/transmission/settings.json на стороне сервера set transmissionuser to "torruser" set transmissionpass to "torrpassword" set transmissionhost to "My-Router.local" set transmissionport to "9092" set transmissionauth to transmissionuser & ":" & transmissionpass set transmissionurl to "http://" & transmissionhost & ":" & transmissionport set rpcurl to transmissionurl & "/transmission/rpc" --Если сервер доступен, отправляем файл if (my CheckServer(transmissionhost, transmissionport)) is true ¬ then my SendTorrent(torrentFile, rpcurl, transmissionauth) end if end tell end repeat end adding folder items to --Проверка доступности сервера on CheckServer(thost, tport) try do shell script "nc -z" & space & thost & space & tport return true on error display dialog "Сервер transmission" & space & thost & space & "недоступен." with title ¬ "Transmission-RPC" buttons {"OK"} default button 1 with icon stop giving up after 10 end try end CheckServer --Отправка torrent файла в формате base64 on SendTorrent(torrentFile, rpcurl, transmissionauth) set metainfo to do shell script "base64 -i " & quoted form of (POSIX path of (torrentFile)) set sessionid to do shell script "curl --silent " & rpcurl & " --anyauth --user " & transmissionauth & ¬ " | sed 's/.*//g;s/<\\/code>.*//g'" set json to "{\"method\": \"torrent-add\", \"arguments\":{\"metainfo\":\"" & metainfo & "\" }}" set answer to do shell script "curl --silent --anyauth --user " & transmissionauth & space & rpcurl & " --header " & ¬ quoted form of (sessionid) & " -d " & quoted form of (json) & " | sed 's/.*result\\\":\\\"//g;s/\\\"}//g'" if answer is equal to "success" then my SuccessAction(torrentFile) else my ErrorAction(answer, torrentFile) end if end SendTorrent --В случае успеха отправки on SuccessAction(torrentFile) -- Показ уведомления об успешной отправке display notification name of (info for (torrentFile as alias)) with title "Transmission-RPC" subtitle "Успешно отправлен на закачку" --Удаление обработанного .torrent файла --delete torrentFile -- удаление в корзину do shell script "rm -f " & quoted form of (POSIX path of (torrentFile)) end SuccessAction --В случае неудачи отправки on ErrorAction(answer, torrentFile) -- Сообщение об ошибке отправки .torrent файла, исчезает через 10 сек set errMsg to do shell script "echo " & quoted form of (answer) & " | sed 's/.*

//g;s/<\\/p>.*//g'" display dialog "Ошибка отправки файла: " & quoted form of (name of (info for (torrentFile as alias))) & "." & return & "Ответ сервера:" & space & ¬ errMsg with title "Transmission-RPC" buttons {"OK"} default button 1 with icon stop giving up after 10 end ErrorAction Для установки скрипта вызываем контекстное меню на каталоге: {{ :apple-mac-os:macos-monterey:pasted:20220203-110900.png }} Так же "Настройка действий папки" можно вызвать через spotlight. {{ :apple-mac-os:macos-monterey:pasted:20220203-111048.png }} В обработку скрипта попадают все файлы и каталоги, которые будут добавляться в настроенный каталог, если расширение файла или файлов **.torrent**, то они будут отправлены в **transmission** для последующей загрузки. Также существует [[https://www.reddit.com/r/shortcuts/comments/9wo3c6/add_torrent_file_to_transmission/|решение]], реализованное с помощью "Быстрые Команды", которое позволяет вручную отправлять **.torrent** файлы на удалённый сервер на **iOS** и **iPadOS**. ---- Проверено на следующих конфигурациях: ^ Версия ОС ^ | Apple macOS Monterey (12.0) | | Apple macOS Ventura (13.0) | | Apple macOS Sonoma (14.0) | ---- {{:user:vyakob.png?50&nolink |}} Автор первичной редакции:\\ [[user:vyakob|Виталий Якоб]] \\ Время публикации: 03.02.2022 10:39 {{tag>Apple "Mac OS" macOS "macOS Monterey" Automator torrent transmission AppleScript Script}} ~~DISCUSSION~~