We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Pyload, error when checking version.

<!---
Before opening an issue, verify:

- Is this a feature request? Post it on https://feathub.com/Flexget/Flexget
No.
- Is this an issue with webui? Make an issue over on https://github.com/Flexget/webui
No.
- 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
No.
- Are you running FlexGet as a daemon? Stop it completely and then start it again https://flexget.com/CLI/daemon
Yes.
- Did you search to see if the issue already exists? https://github.com/Flexget/Flexget/issues
Yes.
- Did you fill out the issue template as completely as possible?
Yes!?

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!
--->
When there are accepted entries and the version check, an error occurs, I put it in the pastbin, the error aparently is related with this PR  #2642

### Expected behaviour:
Add entries and download.

<!---
Please don't just say "it doesn't crash" or "it works". Explain what the expected result is.
--->

### Actual behaviour:
PASTBIN: https://pastebin.com/R3Hk3zSh

### Steps to reproduce:
- Step 1: ...
When I run a task with the pyload plugin and there are accepted entries.

#### Config:
```yaml--- config from task: pyload
accept_all: true
metainfo_series: true
pyload:
  api: http://localhost:8000/api
  enabled: true
  folder: /media/luiz/HD/Downloads
  hoster:
    - MegauploadComFolder
    - MegauploadCom
    - ZippyshareCom
  package: '{{series_name}} - {{tvdb_series_name}}'
  parse_url: true
  password: admin
  queue: true
  username: luiz
rss:
  all_entries: true
  ascii: false
  escape: false
  group_links: false
  silent: false
  url: /home/luiz/.flexget/rss.xml
thetvdb_lookup: true
trakt_lookup: true

---

```
  
#### Log:
<details>
 <summary>https://pastebin.com/R3Hk3zSh</summary>

```
paste log output here
```
</details>

### Additional information:

- FlexGet version: 3.1.67.dev
- Python version: Python 3.8.2
- Installation method: git venv
- Using daemon (yes/no): yes
- OS and version: Linux HP 5.4.0-42-generic #46-Ubuntu SMP Fri Jul 10 00:24:02 UTC 2020 x86_64 x86_64 x86_64 GNU/Linux
- Link to crash log: https://pastebin.com/R3Hk3zSh

<!---
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). 
- 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.
--->


--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `flexget/plugins/clients/pyload.py`
Content:
```
1 from urllib.parse import quote
2 
3 from loguru import logger
4 from requests.exceptions import RequestException
5 
6 from flexget import plugin
7 from flexget.config_schema import one_or_more
8 from flexget.event import event
9 from flexget.utils import json
10 from flexget.utils.template import RenderError
11 
12 logger = logger.bind(name='pyload')
13 
14 
15 class PyloadApi:
16     def __init__(self, requests, url):
17         self.requests = requests
18         self.url = url
19 
20     def get_session(self, config):
21         # Login
22         data = {'username': config['username'], 'password': config['password']}
23         result = self.post('login', data=data)
24         response = result.json()
25         if not response:
26             raise plugin.PluginError('Login failed', logger)
27 
28         if isinstance(response, str):
29             return response.replace('"', '')
30         else:
31             return response
32 
33     def get(self, method):
34         try:
35             return self.requests.get(self.url.rstrip("/") + "/" + method.strip("/"))
36         except RequestException as e:
37             if e.response and e.response.status_code == 500:
38                 raise plugin.PluginError(
39                     'Internal API Error: <%s> <%s>' % (method, self.url), logger
40                 )
41             raise
42 
43     def post(self, method, data):
44         try:
45             return self.requests.post(self.url.rstrip("/") + "/" + method.strip("/"), data=data)
46         except RequestException as e:
47             if e.response and e.response.status_code == 500:
48                 raise plugin.PluginError(
49                     'Internal API Error: <%s> <%s> <%s>' % (method, self.url, data), logger
50                 )
51             raise
52 
53 
54 class PluginPyLoad:
55     """
56     Parse task content or url for hoster links and adds them to pyLoad.
57 
58     Example::
59 
60       pyload:
61         api: http://localhost:8000/api
62         queue: yes
63         username: my_username
64         password: my_password
65         folder: desired_folder
66         package: desired_package_name (jinja2 supported)
67         package_password: desired_package_password
68         hoster:
69           - YoutubeCom
70         parse_url: no
71         multiple_hoster: yes
72         enabled: yes
73 
74     Default values for the config elements::
75 
76       pyload:
77           api: http://localhost:8000/api
78           queue: no
79           hoster: ALL
80           parse_url: no
81           multiple_hoster: yes
82           enabled: yes
83     """
84 
85     __author__ = 'http://pyload.org'
86     __version__ = '0.5'
87 
88     DEFAULT_API = 'http://localhost:8000/api'
89     DEFAULT_QUEUE = False
90     DEFAULT_FOLDER = ''
91     DEFAULT_HOSTER = []
92     DEFAULT_PARSE_URL = False
93     DEFAULT_MULTIPLE_HOSTER = True
94     DEFAULT_PREFERRED_HOSTER_ONLY = False
95     DEFAULT_HANDLE_NO_URL_AS_FAILURE = False
96 
97     schema = {
98         'type': 'object',
99         'properties': {
100             'api': {'type': 'string'},
101             'username': {'type': 'string'},
102             'password': {'type': 'string'},
103             'folder': {'type': 'string'},
104             'package': {'type': 'string'},
105             'package_password': {'type': 'string'},
106             'queue': {'type': 'boolean'},
107             'parse_url': {'type': 'boolean'},
108             'multiple_hoster': {'type': 'boolean'},
109             'hoster': one_or_more({'type': 'string'}),
110             'preferred_hoster_only': {'type': 'boolean'},
111             'handle_no_url_as_failure': {'type': 'boolean'},
112             'enabled': {'type': 'boolean'},
113         },
114         'required': ['username', 'password'],
115         'additionalProperties': False,
116     }
117 
118     def on_task_output(self, task, config):
119         if not config.get('enabled', True):
120             return
121         if not task.accepted:
122             return
123 
124         self.add_entries(task, config)
125 
126     @staticmethod
127     def get_version_from_packaging():
128         version = None
129         try:
130             from packaging import version
131         except ModuleNotFoundError:
132             logger.warning('packaging is not installed')
133         return version
134 
135     def add_entries(self, task, config):
136         """Adds accepted entries"""
137 
138         apiurl = config.get('api', self.DEFAULT_API)
139         api = PyloadApi(task.requests, apiurl)
140 
141         try:
142             session = api.get_session(config)
143         except OSError:
144             raise plugin.PluginError('pyLoad not reachable', logger)
145         except plugin.PluginError:
146             raise
147         except Exception as e:
148             raise plugin.PluginError('Unknown error: %s' % str(e), logger)
149 
150         remote_version = None
151         try:
152             remote_version = api.get('getServerVersion')
153         except RequestException as e:
154             if e.response is not None and e.response.status_code == 404:
155                 remote_version = json.loads(api.get('get_server_version').content)
156             else:
157                 raise e
158 
159         parse_urls_command = 'parseURLs'
160         add_package_command = 'addPackage'
161         set_package_data_command = 'setPackageData'
162 
163         is_pyload_ng = False
164         version = self.get_version_from_packaging()
165         if version and version.parse(remote_version) >= version.parse('0.5'):
166             parse_urls_command = 'parse_urls'
167             add_package_command = 'add_package'
168             set_package_data_command = 'set_package_date'
169             is_pyload_ng = True
170 
171         hoster = config.get('hoster', self.DEFAULT_HOSTER)
172 
173         for entry in task.accepted:
174             # bunch of urls now going to check
175             content = entry.get('description', '') + ' ' + quote(entry['url'])
176             content = json.dumps(content)
177 
178             if is_pyload_ng:
179                 url = entry['url'] if config.get('parse_url', self.DEFAULT_PARSE_URL) else ''
180             else:
181                 url = (
182                     json.dumps(entry['url'])
183                     if config.get('parse_url', self.DEFAULT_PARSE_URL)
184                     else "''"
185                 )
186 
187             logger.debug('Parsing url {}', url)
188 
189             data = {'html': content, 'url': url}
190             if not is_pyload_ng:
191                 data['session'] = session
192             result = api.post(parse_urls_command, data=data)
193 
194             parsed = result.json()
195 
196             urls = []
197 
198             # check for preferred hoster
199             for name in hoster:
200                 if name in parsed:
201                     urls.extend(parsed[name])
202                     if not config.get('multiple_hoster', self.DEFAULT_MULTIPLE_HOSTER):
203                         break
204 
205             # no preferred hoster and not preferred hoster only - add all recognized plugins
206             if not urls and not config.get(
207                 'preferred_hoster_only', self.DEFAULT_PREFERRED_HOSTER_ONLY
208             ):
209                 for name, purls in parsed.items():
210                     if name != 'BasePlugin':
211                         urls.extend(purls)
212 
213             if task.options.test:
214                 logger.info('Would add `{}` to pyload', urls)
215                 continue
216 
217             # no urls found
218             if not urls:
219                 if config.get('handle_no_url_as_failure', self.DEFAULT_HANDLE_NO_URL_AS_FAILURE):
220                     entry.fail('No suited urls in entry %s' % entry['title'])
221                 else:
222                     logger.info('No suited urls in entry {}', entry['title'])
223                 continue
224 
225             logger.debug('Add {} urls to pyLoad', len(urls))
226 
227             try:
228                 dest = 1 if config.get('queue', self.DEFAULT_QUEUE) else 0  # Destination.Queue = 1
229 
230                 # Use the title of the entry, if no naming schema for the package is defined.
231                 name = config.get('package', entry['title'])
232 
233                 # If name has jinja template, render it
234                 try:
235                     name = entry.render(name)
236                 except RenderError as e:
237                     name = entry['title']
238                     logger.error('Error rendering jinja event: {}', e)
239 
240                 if is_pyload_ng:
241                     data = {
242                         'name': name.encode('ascii', 'ignore').decode(),
243                         'links': urls,
244                         'dest': dest,
245                     }
246                 else:
247                     data = {
248                         'name': json.dumps(name.encode('ascii', 'ignore').decode()),
249                         'links': json.dumps(urls),
250                         'dest': json.dumps(dest),
251                         'session': session,
252                     }
253 
254                 pid = api.post(add_package_command, data=data).text
255                 logger.debug('added package pid: {}', pid)
256 
257                 # Set Folder
258                 folder = config.get('folder', self.DEFAULT_FOLDER)
259                 folder = entry.get('path', folder)
260                 if folder:
261                     # If folder has jinja template, render it
262                     try:
263                         folder = entry.render(folder)
264                     except RenderError as e:
265                         folder = self.DEFAULT_FOLDER
266                         logger.error('Error rendering jinja event: {}', e)
267                     # set folder with api
268                     data = json.dumps({'folder': folder})
269                     post_data = {'pid': pid, 'data': data}
270                     if not is_pyload_ng:
271                         post_data['session'] = session
272                     api.post(set_package_data_command, data=post_data)
273 
274                 # Set Package Password
275                 package_password = config.get('package_password')
276                 if package_password:
277                     data = json.dumps({'password': package_password})
278                     post_data = {'pid': pid, 'data': data}
279                     if not is_pyload_ng:
280                         post_data['session'] = session
281                     api.post(set_package_data_command, data=post_data)
282 
283             except Exception as e:
284                 entry.fail(str(e))
285 
286 
287 @event('plugin.register')
288 def register_plugin():
289     plugin.register(PluginPyLoad, 'pyload', api_ver=2)
290
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/flexget/plugins/clients/pyload.py b/flexget/plugins/clients/pyload.py
--- a/flexget/plugins/clients/pyload.py
+++ b/flexget/plugins/clients/pyload.py
@@ -123,15 +123,6 @@
 
         self.add_entries(task, config)
 
-    @staticmethod
-    def get_version_from_packaging():
-        version = None
-        try:
-            from packaging import version
-        except ModuleNotFoundError:
-            logger.warning('packaging is not installed')
-        return version
-
     def add_entries(self, task, config):
         """Adds accepted entries"""
 
@@ -147,26 +138,18 @@
         except Exception as e:
             raise plugin.PluginError('Unknown error: %s' % str(e), logger)
 
-        remote_version = None
-        try:
-            remote_version = api.get('getServerVersion')
-        except RequestException as e:
-            if e.response is not None and e.response.status_code == 404:
-                remote_version = json.loads(api.get('get_server_version').content)
-            else:
-                raise e
-
+        # old pyload (stable)
+        is_pyload_ng = False
         parse_urls_command = 'parseURLs'
         add_package_command = 'addPackage'
         set_package_data_command = 'setPackageData'
 
-        is_pyload_ng = False
-        version = self.get_version_from_packaging()
-        if version and version.parse(remote_version) >= version.parse('0.5'):
+        # pyload-ng is returning dict instead of session string on login
+        if isinstance(session, dict):
+            is_pyload_ng = True
             parse_urls_command = 'parse_urls'
             add_package_command = 'add_package'
             set_package_data_command = 'set_package_date'
-            is_pyload_ng = True
 
         hoster = config.get('hoster', self.DEFAULT_HOSTER)

{"golden_diff": "diff --git a/flexget/plugins/clients/pyload.py b/flexget/plugins/clients/pyload.py\n--- a/flexget/plugins/clients/pyload.py\n+++ b/flexget/plugins/clients/pyload.py\n@@ -123,15 +123,6 @@\n \n         self.add_entries(task, config)\n \n-    @staticmethod\n-    def get_version_from_packaging():\n-        version = None\n-        try:\n-            from packaging import version\n-        except ModuleNotFoundError:\n-            logger.warning('packaging is not installed')\n-        return version\n-\n     def add_entries(self, task, config):\n         \"\"\"Adds accepted entries\"\"\"\n \n@@ -147,26 +138,18 @@\n         except Exception as e:\n             raise plugin.PluginError('Unknown error: %s' % str(e), logger)\n \n-        remote_version = None\n-        try:\n-            remote_version = api.get('getServerVersion')\n-        except RequestException as e:\n-            if e.response is not None and e.response.status_code == 404:\n-                remote_version = json.loads(api.get('get_server_version').content)\n-            else:\n-                raise e\n-\n+        # old pyload (stable)\n+        is_pyload_ng = False\n         parse_urls_command = 'parseURLs'\n         add_package_command = 'addPackage'\n         set_package_data_command = 'setPackageData'\n \n-        is_pyload_ng = False\n-        version = self.get_version_from_packaging()\n-        if version and version.parse(remote_version) >= version.parse('0.5'):\n+        # pyload-ng is returning dict instead of session string on login\n+        if isinstance(session, dict):\n+            is_pyload_ng = True\n             parse_urls_command = 'parse_urls'\n             add_package_command = 'add_package'\n             set_package_data_command = 'set_package_date'\n-            is_pyload_ng = True\n \n         hoster = config.get('hoster', self.DEFAULT_HOSTER)\n", "issue": "Pyload, error when checking version.\n\r\n<!---\r\nBefore opening an issue, verify:\r\n\r\n- Is this a feature request? Post it on https://feathub.com/Flexget/Flexget\r\nNo.\r\n- Is this an issue with webui? Make an issue over on https://github.com/Flexget/webui\r\nNo.\r\n- Did you recently upgrade? Look at the Change Log and Upgrade Actions to make sure that you don't need to make any \r\nchanges to your config https://flexget.com/ChangeLog https://flexget.com/UpgradeActions\r\nNo.\r\n- Are you running FlexGet as a daemon? Stop it completely and then start it again https://flexget.com/CLI/daemon\r\nYes.\r\n- Did you search to see if the issue already exists? https://github.com/Flexget/Flexget/issues\r\nYes.\r\n- Did you fill out the issue template as completely as possible?\r\nYes!?\r\n\r\nThe 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!\r\n--->\r\nWhen there are accepted entries and the version check, an error occurs, I put it in the pastbin, the error aparently is related with this PR  #2642\r\n\r\n### Expected behaviour:\r\nAdd entries and download.\r\n\r\n<!---\r\nPlease don't just say \"it doesn't crash\" or \"it works\". Explain what the expected result is.\r\n--->\r\n\r\n### Actual behaviour:\r\nPASTBIN: https://pastebin.com/R3Hk3zSh\r\n\r\n### Steps to reproduce:\r\n- Step 1: ...\r\nWhen I run a task with the pyload plugin and there are accepted entries.\r\n\r\n#### Config:\r\n```yaml--- config from task: pyload\r\naccept_all: true\r\nmetainfo_series: true\r\npyload:\r\n  api: http://localhost:8000/api\r\n  enabled: true\r\n  folder: /media/luiz/HD/Downloads\r\n  hoster:\r\n    - MegauploadComFolder\r\n    - MegauploadCom\r\n    - ZippyshareCom\r\n  package: '{{series_name}} - {{tvdb_series_name}}'\r\n  parse_url: true\r\n  password: admin\r\n  queue: true\r\n  username: luiz\r\nrss:\r\n  all_entries: true\r\n  ascii: false\r\n  escape: false\r\n  group_links: false\r\n  silent: false\r\n  url: /home/luiz/.flexget/rss.xml\r\nthetvdb_lookup: true\r\ntrakt_lookup: true\r\n\r\n---\r\n\r\n```\r\n  \r\n#### Log:\r\n<details>\r\n <summary>https://pastebin.com/R3Hk3zSh</summary>\r\n\r\n```\r\npaste log output here\r\n```\r\n</details>\r\n\r\n### Additional information:\r\n\r\n- FlexGet version: 3.1.67.dev\r\n- Python version: Python 3.8.2\r\n- Installation method: git venv\r\n- Using daemon (yes/no): yes\r\n- OS and version: Linux HP 5.4.0-42-generic #46-Ubuntu SMP Fri Jul 10 00:24:02 UTC 2020 x86_64 x86_64 x86_64 GNU/Linux\r\n- Link to crash log: https://pastebin.com/R3Hk3zSh\r\n\r\n<!---\r\nIn config and debug/crash logs, remember to redact any personal or sensitive information such as passwords, API keys, private URLs and so on.\r\n\r\nPlease verify that the following data is present before submitting your issue:\r\n\r\n- 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.\r\n- Link to a paste service or paste above debug-level logs of the relevant task/s (use `flexget -L debug execute --tasks <Task_name>`).\r\n- FlexGet version (use `flexget -V` to get it).\r\n- Full Python version, for example `2.7.11` (use `python -V` to get it). \r\n- Installation method (pip, git install, etc).\r\n- Whether or not you're running FlexGet as a daemon.\r\n- OS and version.\r\n\r\n- 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.\r\n--->\r\n\n", "before_files": [{"content": "from urllib.parse import quote\n\nfrom loguru import logger\nfrom requests.exceptions import RequestException\n\nfrom flexget import plugin\nfrom flexget.config_schema import one_or_more\nfrom flexget.event import event\nfrom flexget.utils import json\nfrom flexget.utils.template import RenderError\n\nlogger = logger.bind(name='pyload')\n\n\nclass PyloadApi:\n    def __init__(self, requests, url):\n        self.requests = requests\n        self.url = url\n\n    def get_session(self, config):\n        # Login\n        data = {'username': config['username'], 'password': config['password']}\n        result = self.post('login', data=data)\n        response = result.json()\n        if not response:\n            raise plugin.PluginError('Login failed', logger)\n\n        if isinstance(response, str):\n            return response.replace('\"', '')\n        else:\n            return response\n\n    def get(self, method):\n        try:\n            return self.requests.get(self.url.rstrip(\"/\") + \"/\" + method.strip(\"/\"))\n        except RequestException as e:\n            if e.response and e.response.status_code == 500:\n                raise plugin.PluginError(\n                    'Internal API Error: <%s> <%s>' % (method, self.url), logger\n                )\n            raise\n\n    def post(self, method, data):\n        try:\n            return self.requests.post(self.url.rstrip(\"/\") + \"/\" + method.strip(\"/\"), data=data)\n        except RequestException as e:\n            if e.response and e.response.status_code == 500:\n                raise plugin.PluginError(\n                    'Internal API Error: <%s> <%s> <%s>' % (method, self.url, data), logger\n                )\n            raise\n\n\nclass PluginPyLoad:\n    \"\"\"\n    Parse task content or url for hoster links and adds them to pyLoad.\n\n    Example::\n\n      pyload:\n        api: http://localhost:8000/api\n        queue: yes\n        username: my_username\n        password: my_password\n        folder: desired_folder\n        package: desired_package_name (jinja2 supported)\n        package_password: desired_package_password\n        hoster:\n          - YoutubeCom\n        parse_url: no\n        multiple_hoster: yes\n        enabled: yes\n\n    Default values for the config elements::\n\n      pyload:\n          api: http://localhost:8000/api\n          queue: no\n          hoster: ALL\n          parse_url: no\n          multiple_hoster: yes\n          enabled: yes\n    \"\"\"\n\n    __author__ = 'http://pyload.org'\n    __version__ = '0.5'\n\n    DEFAULT_API = 'http://localhost:8000/api'\n    DEFAULT_QUEUE = False\n    DEFAULT_FOLDER = ''\n    DEFAULT_HOSTER = []\n    DEFAULT_PARSE_URL = False\n    DEFAULT_MULTIPLE_HOSTER = True\n    DEFAULT_PREFERRED_HOSTER_ONLY = False\n    DEFAULT_HANDLE_NO_URL_AS_FAILURE = False\n\n    schema = {\n        'type': 'object',\n        'properties': {\n            'api': {'type': 'string'},\n            'username': {'type': 'string'},\n            'password': {'type': 'string'},\n            'folder': {'type': 'string'},\n            'package': {'type': 'string'},\n            'package_password': {'type': 'string'},\n            'queue': {'type': 'boolean'},\n            'parse_url': {'type': 'boolean'},\n            'multiple_hoster': {'type': 'boolean'},\n            'hoster': one_or_more({'type': 'string'}),\n            'preferred_hoster_only': {'type': 'boolean'},\n            'handle_no_url_as_failure': {'type': 'boolean'},\n            'enabled': {'type': 'boolean'},\n        },\n        'required': ['username', 'password'],\n        'additionalProperties': False,\n    }\n\n    def on_task_output(self, task, config):\n        if not config.get('enabled', True):\n            return\n        if not task.accepted:\n            return\n\n        self.add_entries(task, config)\n\n    @staticmethod\n    def get_version_from_packaging():\n        version = None\n        try:\n            from packaging import version\n        except ModuleNotFoundError:\n            logger.warning('packaging is not installed')\n        return version\n\n    def add_entries(self, task, config):\n        \"\"\"Adds accepted entries\"\"\"\n\n        apiurl = config.get('api', self.DEFAULT_API)\n        api = PyloadApi(task.requests, apiurl)\n\n        try:\n            session = api.get_session(config)\n        except OSError:\n            raise plugin.PluginError('pyLoad not reachable', logger)\n        except plugin.PluginError:\n            raise\n        except Exception as e:\n            raise plugin.PluginError('Unknown error: %s' % str(e), logger)\n\n        remote_version = None\n        try:\n            remote_version = api.get('getServerVersion')\n        except RequestException as e:\n            if e.response is not None and e.response.status_code == 404:\n                remote_version = json.loads(api.get('get_server_version').content)\n            else:\n                raise e\n\n        parse_urls_command = 'parseURLs'\n        add_package_command = 'addPackage'\n        set_package_data_command = 'setPackageData'\n\n        is_pyload_ng = False\n        version = self.get_version_from_packaging()\n        if version and version.parse(remote_version) >= version.parse('0.5'):\n            parse_urls_command = 'parse_urls'\n            add_package_command = 'add_package'\n            set_package_data_command = 'set_package_date'\n            is_pyload_ng = True\n\n        hoster = config.get('hoster', self.DEFAULT_HOSTER)\n\n        for entry in task.accepted:\n            # bunch of urls now going to check\n            content = entry.get('description', '') + ' ' + quote(entry['url'])\n            content = json.dumps(content)\n\n            if is_pyload_ng:\n                url = entry['url'] if config.get('parse_url', self.DEFAULT_PARSE_URL) else ''\n            else:\n                url = (\n                    json.dumps(entry['url'])\n                    if config.get('parse_url', self.DEFAULT_PARSE_URL)\n                    else \"''\"\n                )\n\n            logger.debug('Parsing url {}', url)\n\n            data = {'html': content, 'url': url}\n            if not is_pyload_ng:\n                data['session'] = session\n            result = api.post(parse_urls_command, data=data)\n\n            parsed = result.json()\n\n            urls = []\n\n            # check for preferred hoster\n            for name in hoster:\n                if name in parsed:\n                    urls.extend(parsed[name])\n                    if not config.get('multiple_hoster', self.DEFAULT_MULTIPLE_HOSTER):\n                        break\n\n            # no preferred hoster and not preferred hoster only - add all recognized plugins\n            if not urls and not config.get(\n                'preferred_hoster_only', self.DEFAULT_PREFERRED_HOSTER_ONLY\n            ):\n                for name, purls in parsed.items():\n                    if name != 'BasePlugin':\n                        urls.extend(purls)\n\n            if task.options.test:\n                logger.info('Would add `{}` to pyload', urls)\n                continue\n\n            # no urls found\n            if not urls:\n                if config.get('handle_no_url_as_failure', self.DEFAULT_HANDLE_NO_URL_AS_FAILURE):\n                    entry.fail('No suited urls in entry %s' % entry['title'])\n                else:\n                    logger.info('No suited urls in entry {}', entry['title'])\n                continue\n\n            logger.debug('Add {} urls to pyLoad', len(urls))\n\n            try:\n                dest = 1 if config.get('queue', self.DEFAULT_QUEUE) else 0  # Destination.Queue = 1\n\n                # Use the title of the entry, if no naming schema for the package is defined.\n                name = config.get('package', entry['title'])\n\n                # If name has jinja template, render it\n                try:\n                    name = entry.render(name)\n                except RenderError as e:\n                    name = entry['title']\n                    logger.error('Error rendering jinja event: {}', e)\n\n                if is_pyload_ng:\n                    data = {\n                        'name': name.encode('ascii', 'ignore').decode(),\n                        'links': urls,\n                        'dest': dest,\n                    }\n                else:\n                    data = {\n                        'name': json.dumps(name.encode('ascii', 'ignore').decode()),\n                        'links': json.dumps(urls),\n                        'dest': json.dumps(dest),\n                        'session': session,\n                    }\n\n                pid = api.post(add_package_command, data=data).text\n                logger.debug('added package pid: {}', pid)\n\n                # Set Folder\n                folder = config.get('folder', self.DEFAULT_FOLDER)\n                folder = entry.get('path', folder)\n                if folder:\n                    # If folder has jinja template, render it\n                    try:\n                        folder = entry.render(folder)\n                    except RenderError as e:\n                        folder = self.DEFAULT_FOLDER\n                        logger.error('Error rendering jinja event: {}', e)\n                    # set folder with api\n                    data = json.dumps({'folder': folder})\n                    post_data = {'pid': pid, 'data': data}\n                    if not is_pyload_ng:\n                        post_data['session'] = session\n                    api.post(set_package_data_command, data=post_data)\n\n                # Set Package Password\n                package_password = config.get('package_password')\n                if package_password:\n                    data = json.dumps({'password': package_password})\n                    post_data = {'pid': pid, 'data': data}\n                    if not is_pyload_ng:\n                        post_data['session'] = session\n                    api.post(set_package_data_command, data=post_data)\n\n            except Exception as e:\n                entry.fail(str(e))\n\n\n@event('plugin.register')\ndef register_plugin():\n    plugin.register(PluginPyLoad, 'pyload', api_ver=2)\n", "path": "flexget/plugins/clients/pyload.py"}], "after_files": [{"content": "from urllib.parse import quote\n\nfrom loguru import logger\nfrom requests.exceptions import RequestException\n\nfrom flexget import plugin\nfrom flexget.config_schema import one_or_more\nfrom flexget.event import event\nfrom flexget.utils import json\nfrom flexget.utils.template import RenderError\n\nlogger = logger.bind(name='pyload')\n\n\nclass PyloadApi:\n    def __init__(self, requests, url):\n        self.requests = requests\n        self.url = url\n\n    def get_session(self, config):\n        # Login\n        data = {'username': config['username'], 'password': config['password']}\n        result = self.post('login', data=data)\n        response = result.json()\n        if not response:\n            raise plugin.PluginError('Login failed', logger)\n\n        if isinstance(response, str):\n            return response.replace('\"', '')\n        else:\n            return response\n\n    def get(self, method):\n        try:\n            return self.requests.get(self.url.rstrip(\"/\") + \"/\" + method.strip(\"/\"))\n        except RequestException as e:\n            if e.response and e.response.status_code == 500:\n                raise plugin.PluginError(\n                    'Internal API Error: <%s> <%s>' % (method, self.url), logger\n                )\n            raise\n\n    def post(self, method, data):\n        try:\n            return self.requests.post(self.url.rstrip(\"/\") + \"/\" + method.strip(\"/\"), data=data)\n        except RequestException as e:\n            if e.response and e.response.status_code == 500:\n                raise plugin.PluginError(\n                    'Internal API Error: <%s> <%s> <%s>' % (method, self.url, data), logger\n                )\n            raise\n\n\nclass PluginPyLoad:\n    \"\"\"\n    Parse task content or url for hoster links and adds them to pyLoad.\n\n    Example::\n\n      pyload:\n        api: http://localhost:8000/api\n        queue: yes\n        username: my_username\n        password: my_password\n        folder: desired_folder\n        package: desired_package_name (jinja2 supported)\n        package_password: desired_package_password\n        hoster:\n          - YoutubeCom\n        parse_url: no\n        multiple_hoster: yes\n        enabled: yes\n\n    Default values for the config elements::\n\n      pyload:\n          api: http://localhost:8000/api\n          queue: no\n          hoster: ALL\n          parse_url: no\n          multiple_hoster: yes\n          enabled: yes\n    \"\"\"\n\n    __author__ = 'http://pyload.org'\n    __version__ = '0.5'\n\n    DEFAULT_API = 'http://localhost:8000/api'\n    DEFAULT_QUEUE = False\n    DEFAULT_FOLDER = ''\n    DEFAULT_HOSTER = []\n    DEFAULT_PARSE_URL = False\n    DEFAULT_MULTIPLE_HOSTER = True\n    DEFAULT_PREFERRED_HOSTER_ONLY = False\n    DEFAULT_HANDLE_NO_URL_AS_FAILURE = False\n\n    schema = {\n        'type': 'object',\n        'properties': {\n            'api': {'type': 'string'},\n            'username': {'type': 'string'},\n            'password': {'type': 'string'},\n            'folder': {'type': 'string'},\n            'package': {'type': 'string'},\n            'package_password': {'type': 'string'},\n            'queue': {'type': 'boolean'},\n            'parse_url': {'type': 'boolean'},\n            'multiple_hoster': {'type': 'boolean'},\n            'hoster': one_or_more({'type': 'string'}),\n            'preferred_hoster_only': {'type': 'boolean'},\n            'handle_no_url_as_failure': {'type': 'boolean'},\n            'enabled': {'type': 'boolean'},\n        },\n        'required': ['username', 'password'],\n        'additionalProperties': False,\n    }\n\n    def on_task_output(self, task, config):\n        if not config.get('enabled', True):\n            return\n        if not task.accepted:\n            return\n\n        self.add_entries(task, config)\n\n    def add_entries(self, task, config):\n        \"\"\"Adds accepted entries\"\"\"\n\n        apiurl = config.get('api', self.DEFAULT_API)\n        api = PyloadApi(task.requests, apiurl)\n\n        try:\n            session = api.get_session(config)\n        except OSError:\n            raise plugin.PluginError('pyLoad not reachable', logger)\n        except plugin.PluginError:\n            raise\n        except Exception as e:\n            raise plugin.PluginError('Unknown error: %s' % str(e), logger)\n\n        # old pyload (stable)\n        is_pyload_ng = False\n        parse_urls_command = 'parseURLs'\n        add_package_command = 'addPackage'\n        set_package_data_command = 'setPackageData'\n\n        # pyload-ng is returning dict instead of session string on login\n        if isinstance(session, dict):\n            is_pyload_ng = True\n            parse_urls_command = 'parse_urls'\n            add_package_command = 'add_package'\n            set_package_data_command = 'set_package_date'\n\n        hoster = config.get('hoster', self.DEFAULT_HOSTER)\n\n        for entry in task.accepted:\n            # bunch of urls now going to check\n            content = entry.get('description', '') + ' ' + quote(entry['url'])\n            content = json.dumps(content)\n\n            if is_pyload_ng:\n                url = entry['url'] if config.get('parse_url', self.DEFAULT_PARSE_URL) else ''\n            else:\n                url = (\n                    json.dumps(entry['url'])\n                    if config.get('parse_url', self.DEFAULT_PARSE_URL)\n                    else \"''\"\n                )\n\n            logger.debug('Parsing url {}', url)\n\n            data = {'html': content, 'url': url}\n            if not is_pyload_ng:\n                data['session'] = session\n            result = api.post(parse_urls_command, data=data)\n\n            parsed = result.json()\n\n            urls = []\n\n            # check for preferred hoster\n            for name in hoster:\n                if name in parsed:\n                    urls.extend(parsed[name])\n                    if not config.get('multiple_hoster', self.DEFAULT_MULTIPLE_HOSTER):\n                        break\n\n            # no preferred hoster and not preferred hoster only - add all recognized plugins\n            if not urls and not config.get(\n                'preferred_hoster_only', self.DEFAULT_PREFERRED_HOSTER_ONLY\n            ):\n                for name, purls in parsed.items():\n                    if name != 'BasePlugin':\n                        urls.extend(purls)\n\n            if task.options.test:\n                logger.info('Would add `{}` to pyload', urls)\n                continue\n\n            # no urls found\n            if not urls:\n                if config.get('handle_no_url_as_failure', self.DEFAULT_HANDLE_NO_URL_AS_FAILURE):\n                    entry.fail('No suited urls in entry %s' % entry['title'])\n                else:\n                    logger.info('No suited urls in entry {}', entry['title'])\n                continue\n\n            logger.debug('Add {} urls to pyLoad', len(urls))\n\n            try:\n                dest = 1 if config.get('queue', self.DEFAULT_QUEUE) else 0  # Destination.Queue = 1\n\n                # Use the title of the entry, if no naming schema for the package is defined.\n                name = config.get('package', entry['title'])\n\n                # If name has jinja template, render it\n                try:\n                    name = entry.render(name)\n                except RenderError as e:\n                    name = entry['title']\n                    logger.error('Error rendering jinja event: {}', e)\n\n                if is_pyload_ng:\n                    data = {\n                        'name': name.encode('ascii', 'ignore').decode(),\n                        'links': urls,\n                        'dest': dest,\n                    }\n                else:\n                    data = {\n                        'name': json.dumps(name.encode('ascii', 'ignore').decode()),\n                        'links': json.dumps(urls),\n                        'dest': json.dumps(dest),\n                        'session': session,\n                    }\n\n                pid = api.post(add_package_command, data=data).text\n                logger.debug('added package pid: {}', pid)\n\n                # Set Folder\n                folder = config.get('folder', self.DEFAULT_FOLDER)\n                folder = entry.get('path', folder)\n                if folder:\n                    # If folder has jinja template, render it\n                    try:\n                        folder = entry.render(folder)\n                    except RenderError as e:\n                        folder = self.DEFAULT_FOLDER\n                        logger.error('Error rendering jinja event: {}', e)\n                    # set folder with api\n                    data = json.dumps({'folder': folder})\n                    post_data = {'pid': pid, 'data': data}\n                    if not is_pyload_ng:\n                        post_data['session'] = session\n                    api.post(set_package_data_command, data=post_data)\n\n                # Set Package Password\n                package_password = config.get('package_password')\n                if package_password:\n                    data = json.dumps({'password': package_password})\n                    post_data = {'pid': pid, 'data': data}\n                    if not is_pyload_ng:\n                        post_data['session'] = session\n                    api.post(set_package_data_command, data=post_data)\n\n            except Exception as e:\n                entry.fail(str(e))\n\n\n@event('plugin.register')\ndef register_plugin():\n    plugin.register(PluginPyLoad, 'pyload', api_ver=2)\n", "path": "flexget/plugins/clients/pyload.py"}]}