From 797196dce97d1418e1217fbe645e7da1c94ce6c5 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Pierre=20St=C3=A5hl?= <pierre.staahl@gmail.com>
Date: Sun, 21 Jul 2019 22:31:11 +0200
Subject: [PATCH] Add add_torrent service to Transmission (#25144)

* Add add_torrent service to Transmission

* Fix services.yaml format

* Verify that torrent is whitelisted

* Add logging if adding failed

* Change warn to warning
---
 .../components/transmission/__init__.py       | 21 +++++++++++++++++++
 .../components/transmission/services.yaml     |  6 ++++++
 2 files changed, 27 insertions(+)
 create mode 100644 homeassistant/components/transmission/services.yaml

diff --git a/homeassistant/components/transmission/__init__.py b/homeassistant/components/transmission/__init__.py
index 5a2fbbff5cb..ad25b43759b 100644
--- a/homeassistant/components/transmission/__init__.py
+++ b/homeassistant/components/transmission/__init__.py
@@ -34,6 +34,14 @@ SENSOR_TYPES = {
 
 DEFAULT_SCAN_INTERVAL = timedelta(seconds=120)
 
+ATTR_TORRENT = 'torrent'
+
+SERVICE_ADD_TORRENT = 'add_torrent'
+
+SERVICE_ADD_TORRENT_SCHEMA = vol.Schema({
+    vol.Required(ATTR_TORRENT): cv.string,
+})
+
 CONFIG_SCHEMA = vol.Schema({
     DOMAIN: vol.Schema({
         vol.Required(CONF_HOST): cv.string,
@@ -82,6 +90,19 @@ def setup(hass, config):
 
     track_time_interval(hass, refresh, scan_interval)
 
+    def add_torrent(service):
+        """Add new torrent to download."""
+        torrent = service.data[ATTR_TORRENT]
+        if torrent.startswith(('http', 'ftp:', 'magnet:')) or \
+           hass.config.is_allowed_path(torrent):
+            api.add_torrent(torrent)
+        else:
+            _LOGGER.warning('Could not add torrent: '
+                            'unsupported type or no permission')
+
+    hass.services.register(DOMAIN, SERVICE_ADD_TORRENT, add_torrent,
+                           schema=SERVICE_ADD_TORRENT_SCHEMA)
+
     sensorconfig = {
         'sensors': config[DOMAIN][CONF_MONITORED_CONDITIONS],
         'client_name': config[DOMAIN][CONF_NAME]}
diff --git a/homeassistant/components/transmission/services.yaml b/homeassistant/components/transmission/services.yaml
new file mode 100644
index 00000000000..e049f89b3c6
--- /dev/null
+++ b/homeassistant/components/transmission/services.yaml
@@ -0,0 +1,6 @@
+add_torrent:
+  description: Add a new torrent to download (URL, magnet link or Base64 encoded).
+  fields:
+    torrent:
+      description: URL, magnet link or Base64 encoded file.
+      example: http://releases.ubuntu.com/19.04/ubuntu-19.04-desktop-amd64.iso.torrent}