Repository: Flexget/Flexget

Issue:
crashes with flexget 2.17 and deluge-client
<!---
Before opening an issue, verify:

- Is this a feature request? Post it on https://feathub.com/Flexget/Flexget
- Did you recently upgrade? Look at the Change Log and Upgrade Actions to make sure that you don't need to make any changes to your config https://flexget.com/ChangeLog https://flexget.com/UpgradeActions
- Are you running FlexGet as a daemon? Stop it completely and then start it again https://flexget.com/CLI/daemon
- Did you search to see if the issue already exists? https://github.com/Flexget/Flexget/issues
- Did you fill out the issue template as completely as possible?

The issue template is here because it helps to ensure you submitted all the necessary information the first time, and allows us to more quickly review issues. Please fill it out correctly and do not ignore it, no matter how irrelevant you think it may be. Thanks in advance for your help with this!
--->
### Expected behaviour:
<!---
Please don't just say "it doesn't crash" or "it works". Explain what the expected result is.
--->

add magnet link to deluge. use option to rename file

### Actual behaviour:

does download file, but it retains original file name. also crashes when unhandled error occurs

### Steps to reproduce:
- Step 1: start daemon
- Step 2: flexget downloads on scheduler
- Step 3: file is not renamed

#### Config:
```
tasks:
  shows:
    rss:
      url: '{? feed ?}'
      all_entries: no
    include: shows.yml
    deluge:
      path: '{? downloads ?}'
      content_filename: "{{series_name}} {{series_id|pad(2)}}"
      movedone: '{? downloads ?}/temp/'

  move-shows:
    filesystem:
      recursive: yes
      retrieve: files
      regexp: '.*\.(mp4|mkv)$'
      path: '{? downloads ?}/temp/'
    accept_all: yes
    disable: builtins
    move:
      to: '{? downloads ?}/series/'
      clean_source: 100

schedules:
  - tasks: shows
    schedule:
      minute: "*/30"
  - tasks: move-shows
    schedule:
      minute: "*/15"
```
  
#### Log:
<details>
 <summary>(click to expand)</summary>

```
2018-10-18 22:30 INFO     deluge_client.client showrss         Connecting to localhost:58846
2018-10-18 22:30 CRITICAL task          showrss         BUG: Unhandled error in plugin deluge: 
Traceback (most recent call last):
  File "/home/$user/.venv/flexget/lib/python3.5/site-packages/deluge_client/client.py", line 214, in call
    return self._receive_response(self.deluge_version)
  File "/home/$user/.venv/flexget/lib/python3.5/site-packages/deluge_client/client.py", line 141, in _receive_response
    d = self._socket.recv(READ_SIZE)
  File "/usr/lib/python3.5/ssl.py", line 914, in recv
    return self.read(buflen)
  File "/usr/lib/python3.5/ssl.py", line 791, in read
    return self._sslobj.read(len, buffer)
  File "/usr/lib/python3.5/ssl.py", line 577, in read
    v = self._sslobj.read(len)
socket.timeout: The read operation timed out

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/$user/.venv/flexget/lib/python3.5/site-packages/flexget/task.py", line 486, in __run_plugin
    return method(*args, **kwargs)
  File "/home/$user/.venv/flexget/lib/python3.5/site-packages/flexget/event.py", line 23, in __call__
    return self.func(*args, **kwargs)
  File "/home/$user/.venv/flexget/lib/python3.5/site-packages/flexget/plugins/clients/deluge.py", line 465, in on_task_output
    self._set_torrent_options(added_torrent, entry, modify_opts)
  File "/home/$user/.venv/flexget/lib/python3.5/site-packages/flexget/plugins/clients/deluge.py", line 585, in _set_torrent_options
    big_file_name = unused_name(big_file_name)
  File "/home/$user/.venv/flexget/lib/python3.5/site-packages/flexget/plugins/clients/deluge.py", line 541, in unused_name
    if self.client.call('is_localhost'):
  File "/home/$user/.venv/flexget/lib/python3.5/site-packages/deluge_client/client.py", line 218, in call
    raise FailedToReconnectException()
deluge_client.client.FailedToReconnectException

```
</details>

### Additional information:

- FlexGet version: 2.17
- Python version: 3.5.2
- Installation method: virtualenv pip
- Using daemon (yes/no): yes
- OS and version: Ubuntu 16.04.5 LTS

more info:
I was using 2.14.20 with python 2.7.12 and virtualenv install using --system-site-packages for deluge compatibility
when I saw that 2.17 supported deluge-client, I switched to using python 3.5.2 (newest available on 16.04 LTS in default repo). it does download the file but doesn't rename it. looks like deluge options are broken/not supported in deluge-client.
I am going to try install python 3.6.5 and creating a new virtualenv install with that version. it does restart the daemon as the service is supposed to restart on crash and the download finishes, it moved to the folder, but just keeping the original name. 
<!---
In config and debug/crash logs, remember to redact any personal or sensitive information such as passwords, API keys, private URLs and so on.

Please verify that the following data is present before submitting your issue:

- Link to a paste service or paste above the relevant config (preferably full config, including templates if present). Please make sure the paste does not expire, if possible.
- Link to a paste service or paste above debug-level logs of the relevant task/s (use `flexget -L debug execute --tasks <Task_name>`).
- FlexGet version (use `flexget -V` to get it).
- Full Python version, for example `2.7.11` (use `python -V` to get it). Note that FlexGet is not supported for use with Python v3.0, 3.1, 3.2 or 3.6.
- Installation method (pip, git install, etc).
- Whether or not you're running FlexGet as a daemon.
- OS and version.
- Attach crash log if one was generated, in addition to the debug-level log. It can be found in the directory with your config file.
--->



Discussion:

Resolving patch:
diff --git a/flexget/plugins/clients/deluge.py b/flexget/plugins/clients/deluge.py
--- a/flexget/plugins/clients/deluge.py
+++ b/flexget/plugins/clients/deluge.py
@@ -77,6 +77,8 @@ def get_localhost_auth():
             auth_file = os.path.join(os.getenv('APPDATA'), 'deluge', 'auth')
         else:
             auth_file = os.path.expanduser('~/.config/deluge/auth')
+        if not os.path.isfile(auth_file):
+            return None
 
         with open(auth_file) as auth:
             for line in auth:
@@ -462,7 +464,10 @@ def on_task_output(self, task, config):
                     except Exception as e:
                         log.info('%s was not added to deluge! %s', entry['title'], e)
                         entry.fail('Could not be added to deluge')
-                self._set_torrent_options(added_torrent, entry, modify_opts)
+                if not added_torrent:
+                    log.error('There was an error adding %s to deluge.' % entry['title'])
+                else:
+                    self._set_torrent_options(added_torrent, entry, modify_opts)
 
     def on_task_learn(self, task, config):
         """ Make sure all temp files are cleaned up when entries are learned """
@@ -538,7 +543,7 @@ def file_exists(filename):
 
             def unused_name(name):
                 # If on local computer, tries appending a (#) suffix until a unique filename is found
-                if self.client.call('is_localhost'):
+                if self.client.host in ['127.0.0.1', 'localhost']:
                     counter = 2
                     while file_exists(name):
                         name = ''.join([os.path.splitext(name)[0],


Test patch: