We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
PyLoad plugin fails with Internal API Error
I'm using pyload as packaged by http://spk.unzureichende.info/ for Synology, using 0.4.9-4, and the latest flexget.

The problem seems to be the way urllib does the request:

```
>>> from urllib import urlencode; from urllib2 import urlopen; urlopen('http://localhost:8000/api/login', urlencode({'a': 1}))
urllib2.HTTPError: HTTP Error 500: Internal Server Error
```

Strangly, it works using requests:

```
>>> import requests; requests.post('http://dollhouse:8000/api/login')
<Response [200]>
```

It turns out that this is because urllib2 only sets this Accpet-Encoding header:

```
Accept-Encoding: identity
```

Things look better when I add gzip manually:

```
>>> import urllib2; headers = { 'Accept' : '*/*', 'Accept-Encoding': 'identity, gzip'}; re = urllib2.Request('http://localhost:8000/api/login', "", headers); urllib2.urlopen(re)
<addinfourl at 41238752 whose fp = <socket._fileobject object at 0x27466d0>>
```

I should say that I am using pyload as packaged by http://spk.unzureichende.info/ for Synology, using 0.4.9-4.

I've also described the issue here:

https://github.com/pyload/pyload/issues/297


--- 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/output/pyload.py`
Content:
```
1 # -*- coding: utf-8 -*-
2 
3 from __future__ import unicode_literals, division, absolute_import
4 from urllib import urlencode, quote
5 from urllib2 import urlopen, URLError, HTTPError
6 from logging import getLogger
7 from flexget.utils import json
8 from flexget.plugin import register_plugin, PluginError
9 from flexget import validator
10 
11 log = getLogger('pyload')
12 
13 
14 class PluginPyLoad(object):
15     """
16     Parse task content or url for hoster links and adds them to pyLoad.
17 
18     Example::
19 
20       pyload:
21         api: http://localhost:8000/api
22         queue: yes
23         username: my_username
24         password: my_password
25         folder: desired_folder
26         hoster:
27           - YoutubeCom
28         parse_url: no
29         multiple_hoster: yes
30         enabled: yes
31 
32     Default values for the config elements::
33 
34       pyload:
35           api: http://localhost:8000/api
36           queue: no
37           hoster: ALL
38           parse_url: no
39           multiple_hoster: yes
40           enabled: yes
41     """
42 
43     __author__ = 'http://pyload.org'
44     __version__ = '0.4'
45 
46     DEFAULT_API = 'http://localhost:8000/api'
47     DEFAULT_QUEUE = False
48     DEFAULT_FOLDER = ''
49     DEFAULT_HOSTER = []
50     DEFAULT_PARSE_URL = False
51     DEFAULT_MULTIPLE_HOSTER = True
52     DEFAULT_PREFERRED_HOSTER_ONLY = False
53     DEFAULT_HANDLE_NO_URL_AS_FAILURE = False
54 
55     def __init__(self):
56         self.session = None
57 
58     def validator(self):
59         """Return config validator"""
60         root = validator.factory()
61         root.accept('boolean')
62         advanced = root.accept('dict')
63         advanced.accept('text', key='api')
64         advanced.accept('text', key='username')
65         advanced.accept('text', key='password')
66         advanced.accept('text', key='folder')
67         advanced.accept('boolean', key='queue')
68         advanced.accept('boolean', key='parse_url')
69         advanced.accept('boolean', key='multiple_hoster')
70         advanced.accept('list', key='hoster').accept('text')
71         advanced.accept('boolean', key='preferred_hoster_only')
72         advanced.accept('boolean', key='handle_no_url_as_failure')
73         return root
74 
75     def on_process_start(self, task, config):
76         self.session = None
77 
78     def on_task_output(self, task, config):
79         if not config.get('enabled', True):
80             return
81         if not task.accepted:
82             return
83 
84         self.add_entries(task, config)
85 
86     def add_entries(self, task, config):
87         """Adds accepted entries"""
88 
89         try:
90             self.check_login(task, config)
91         except URLError:
92             raise PluginError('pyLoad not reachable', log)
93         except PluginError:
94             raise
95         except Exception as e:
96             raise PluginError('Unknown error: %s' % str(e), log)
97 
98         api = config.get('api', self.DEFAULT_API)
99         hoster = config.get('hoster', self.DEFAULT_HOSTER)
100         folder = config.get('folder', self.DEFAULT_FOLDER)
101 
102         for entry in task.accepted:
103             # bunch of urls now going to check
104             content = entry.get('description', '') + ' ' + quote(entry['url'])
105             content = json.dumps(content.encode("utf8"))
106 
107             url = json.dumps(entry['url']) if config.get('parse_url', self.DEFAULT_PARSE_URL) else "''"
108 
109             log.debug("Parsing url %s" % url)
110 
111             result = query_api(api, "parseURLs", {"html": content, "url": url, "session": self.session})
112 
113             # parsed { plugins: [urls] }
114             parsed = json.loads(result.read())
115 
116             urls = []
117 
118             # check for preferred hoster
119             for name in hoster:
120                 if name in parsed:
121                     urls.extend(parsed[name])
122                     if not config.get('multiple_hoster', self.DEFAULT_MULTIPLE_HOSTER):
123                         break
124 
125             # no preferred hoster and not preferred hoster only - add all recognized plugins
126             if not urls and not config.get('preferred_hoster_only', self.DEFAULT_PREFERRED_HOSTER_ONLY):
127                 for name, purls in parsed.iteritems():
128                     if name != "BasePlugin":
129                         urls.extend(purls)
130 
131             if task.manager.options.test:
132                 log.info('Would add `%s` to pyload' % urls)
133                 continue
134 
135             # no urls found
136             if not urls:
137                 if config.get('handle_no_url_as_failure', self.DEFAULT_HANDLE_NO_URL_AS_FAILURE):
138                     entry.fail("No suited urls in entry %s" % entry['title'])
139                 else:
140                     log.info("No suited urls in entry %s" % entry['title'])
141                 continue
142 
143             log.debug("Add %d urls to pyLoad" % len(urls))
144 
145             try:
146                 dest = 1 if config.get('queue', self.DEFAULT_QUEUE) else 0  # Destination.Queue = 1
147                 post = {'name': "'%s'" % entry['title'].encode("ascii", "ignore"),
148                         'links': str(urls),
149                         'dest': dest,
150                         'session': self.session}
151 
152                 pid = query_api(api, "addPackage", post).read()
153                 log.debug('added package pid: %s' % pid)
154 
155                 if folder:
156                     # set folder with api
157                     data = {'folder': folder}
158                     query_api(api, "setPackageData", {'pid': pid, 'data': data, 'session': self.session})
159 
160             except Exception as e:
161                 entry.fail(str(e))
162 
163     def check_login(self, task, config):
164         url = config.get('api', self.DEFAULT_API)
165 
166         if not self.session:
167             # Login
168             post = {'username': config['username'], 'password': config['password']}
169             result = query_api(url, "login", post)
170             response = json.loads(result.read())
171             if not response:
172                 raise PluginError('Login failed', log)
173             self.session = response.replace('"', '')
174         else:
175             try:
176                 query_api(url, 'getServerVersion', {'session': self.session})
177             except HTTPError as e:
178                 if e.code == 403:  # Forbidden
179                     self.session = None
180                     return self.check_login(task, config)
181                 else:
182                     raise PluginError('HTTP Error %s' % e, log)
183 
184 
185 def query_api(url, method, post=None):
186     try:
187         return urlopen(url.rstrip("/") + "/" + method.strip("/"), urlencode(post) if post else None)
188     except HTTPError as e:
189         if e.code == 500:
190             raise PluginError('Internal API Error', log)
191         raise
192 
193 register_plugin(PluginPyLoad, 'pyload', api_ver=2)
194
```
--- 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/output/pyload.py b/flexget/plugins/output/pyload.py
--- a/flexget/plugins/output/pyload.py
+++ b/flexget/plugins/output/pyload.py
@@ -1,10 +1,10 @@
 # -*- coding: utf-8 -*-
 
 from __future__ import unicode_literals, division, absolute_import
-from urllib import urlencode, quote
-from urllib2 import urlopen, URLError, HTTPError
+from urllib import quote
+from requests.exceptions import RequestException
 from logging import getLogger
-from flexget.utils import json
+from flexget.utils import json, requests
 from flexget.plugin import register_plugin, PluginError
 from flexget import validator
 
@@ -88,7 +88,7 @@
 
         try:
             self.check_login(task, config)
-        except URLError:
+        except IOError:
             raise PluginError('pyLoad not reachable', log)
         except PluginError:
             raise
@@ -111,7 +111,7 @@
             result = query_api(api, "parseURLs", {"html": content, "url": url, "session": self.session})
 
             # parsed { plugins: [urls] }
-            parsed = json.loads(result.read())
+            parsed = result.json()
 
             urls = []
 
@@ -149,7 +149,7 @@
                         'dest': dest,
                         'session': self.session}
 
-                pid = query_api(api, "addPackage", post).read()
+                pid = query_api(api, "addPackage", post).text
                 log.debug('added package pid: %s' % pid)
 
                 if folder:
@@ -167,7 +167,7 @@
             # Login
             post = {'username': config['username'], 'password': config['password']}
             result = query_api(url, "login", post)
-            response = json.loads(result.read())
+            response = result.json()
             if not response:
                 raise PluginError('Login failed', log)
             self.session = response.replace('"', '')
@@ -175,7 +175,7 @@
             try:
                 query_api(url, 'getServerVersion', {'session': self.session})
             except HTTPError as e:
-                if e.code == 403:  # Forbidden
+                if e.response.status_code == 403:  # Forbidden
                     self.session = None
                     return self.check_login(task, config)
                 else:
@@ -184,10 +184,15 @@
 
 def query_api(url, method, post=None):
     try:
-        return urlopen(url.rstrip("/") + "/" + method.strip("/"), urlencode(post) if post else None)
-    except HTTPError as e:
-        if e.code == 500:
-            raise PluginError('Internal API Error', log)
+        response = requests.request(
+            'post' if post is not None else 'get',
+            url.rstrip("/") + "/" + method.strip("/"),
+            data=post)
+        response.raise_for_status()
+        return response
+    except RequestException as e:
+        if e.response.status_code == 500:
+            raise PluginError('Internal API Error: <%s> <%s> <%s>' % (method, url, post), log)
         raise
 
 register_plugin(PluginPyLoad, 'pyload', api_ver=2)

{"golden_diff": "diff --git a/flexget/plugins/output/pyload.py b/flexget/plugins/output/pyload.py\n--- a/flexget/plugins/output/pyload.py\n+++ b/flexget/plugins/output/pyload.py\n@@ -1,10 +1,10 @@\n # -*- coding: utf-8 -*-\n \n from __future__ import unicode_literals, division, absolute_import\n-from urllib import urlencode, quote\n-from urllib2 import urlopen, URLError, HTTPError\n+from urllib import quote\n+from requests.exceptions import RequestException\n from logging import getLogger\n-from flexget.utils import json\n+from flexget.utils import json, requests\n from flexget.plugin import register_plugin, PluginError\n from flexget import validator\n \n@@ -88,7 +88,7 @@\n \n         try:\n             self.check_login(task, config)\n-        except URLError:\n+        except IOError:\n             raise PluginError('pyLoad not reachable', log)\n         except PluginError:\n             raise\n@@ -111,7 +111,7 @@\n             result = query_api(api, \"parseURLs\", {\"html\": content, \"url\": url, \"session\": self.session})\n \n             # parsed { plugins: [urls] }\n-            parsed = json.loads(result.read())\n+            parsed = result.json()\n \n             urls = []\n \n@@ -149,7 +149,7 @@\n                         'dest': dest,\n                         'session': self.session}\n \n-                pid = query_api(api, \"addPackage\", post).read()\n+                pid = query_api(api, \"addPackage\", post).text\n                 log.debug('added package pid: %s' % pid)\n \n                 if folder:\n@@ -167,7 +167,7 @@\n             # Login\n             post = {'username': config['username'], 'password': config['password']}\n             result = query_api(url, \"login\", post)\n-            response = json.loads(result.read())\n+            response = result.json()\n             if not response:\n                 raise PluginError('Login failed', log)\n             self.session = response.replace('\"', '')\n@@ -175,7 +175,7 @@\n             try:\n                 query_api(url, 'getServerVersion', {'session': self.session})\n             except HTTPError as e:\n-                if e.code == 403:  # Forbidden\n+                if e.response.status_code == 403:  # Forbidden\n                     self.session = None\n                     return self.check_login(task, config)\n                 else:\n@@ -184,10 +184,15 @@\n \n def query_api(url, method, post=None):\n     try:\n-        return urlopen(url.rstrip(\"/\") + \"/\" + method.strip(\"/\"), urlencode(post) if post else None)\n-    except HTTPError as e:\n-        if e.code == 500:\n-            raise PluginError('Internal API Error', log)\n+        response = requests.request(\n+            'post' if post is not None else 'get',\n+            url.rstrip(\"/\") + \"/\" + method.strip(\"/\"),\n+            data=post)\n+        response.raise_for_status()\n+        return response\n+    except RequestException as e:\n+        if e.response.status_code == 500:\n+            raise PluginError('Internal API Error: <%s> <%s> <%s>' % (method, url, post), log)\n         raise\n \n register_plugin(PluginPyLoad, 'pyload', api_ver=2)\n", "issue": "PyLoad plugin fails with Internal API Error\nI'm using pyload as packaged by http://spk.unzureichende.info/ for Synology, using 0.4.9-4, and the latest flexget.\n\nThe problem seems to be the way urllib does the request:\n\n```\n>>> from urllib import urlencode; from urllib2 import urlopen; urlopen('http://localhost:8000/api/login', urlencode({'a': 1}))\nurllib2.HTTPError: HTTP Error 500: Internal Server Error\n```\n\nStrangly, it works using requests:\n\n```\n>>> import requests; requests.post('http://dollhouse:8000/api/login')\n<Response [200]>\n```\n\nIt turns out that this is because urllib2 only sets this Accpet-Encoding header:\n\n```\nAccept-Encoding: identity\n```\n\nThings look better when I add gzip manually:\n\n```\n>>> import urllib2; headers = { 'Accept' : '*/*', 'Accept-Encoding': 'identity, gzip'}; re = urllib2.Request('http://localhost:8000/api/login', \"\", headers); urllib2.urlopen(re)\n<addinfourl at 41238752 whose fp = <socket._fileobject object at 0x27466d0>>\n```\n\nI should say that I am using pyload as packaged by http://spk.unzureichende.info/ for Synology, using 0.4.9-4.\n\nI've also described the issue here:\n\nhttps://github.com/pyload/pyload/issues/297\n\n", "before_files": [{"content": "# -*- coding: utf-8 -*-\n\nfrom __future__ import unicode_literals, division, absolute_import\nfrom urllib import urlencode, quote\nfrom urllib2 import urlopen, URLError, HTTPError\nfrom logging import getLogger\nfrom flexget.utils import json\nfrom flexget.plugin import register_plugin, PluginError\nfrom flexget import validator\n\nlog = getLogger('pyload')\n\n\nclass PluginPyLoad(object):\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        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.4'\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    def __init__(self):\n        self.session = None\n\n    def validator(self):\n        \"\"\"Return config validator\"\"\"\n        root = validator.factory()\n        root.accept('boolean')\n        advanced = root.accept('dict')\n        advanced.accept('text', key='api')\n        advanced.accept('text', key='username')\n        advanced.accept('text', key='password')\n        advanced.accept('text', key='folder')\n        advanced.accept('boolean', key='queue')\n        advanced.accept('boolean', key='parse_url')\n        advanced.accept('boolean', key='multiple_hoster')\n        advanced.accept('list', key='hoster').accept('text')\n        advanced.accept('boolean', key='preferred_hoster_only')\n        advanced.accept('boolean', key='handle_no_url_as_failure')\n        return root\n\n    def on_process_start(self, task, config):\n        self.session = None\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        try:\n            self.check_login(task, config)\n        except URLError:\n            raise PluginError('pyLoad not reachable', log)\n        except PluginError:\n            raise\n        except Exception as e:\n            raise PluginError('Unknown error: %s' % str(e), log)\n\n        api = config.get('api', self.DEFAULT_API)\n        hoster = config.get('hoster', self.DEFAULT_HOSTER)\n        folder = config.get('folder', self.DEFAULT_FOLDER)\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.encode(\"utf8\"))\n\n            url = json.dumps(entry['url']) if config.get('parse_url', self.DEFAULT_PARSE_URL) else \"''\"\n\n            log.debug(\"Parsing url %s\" % url)\n\n            result = query_api(api, \"parseURLs\", {\"html\": content, \"url\": url, \"session\": self.session})\n\n            # parsed { plugins: [urls] }\n            parsed = json.loads(result.read())\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('preferred_hoster_only', self.DEFAULT_PREFERRED_HOSTER_ONLY):\n                for name, purls in parsed.iteritems():\n                    if name != \"BasePlugin\":\n                        urls.extend(purls)\n\n            if task.manager.options.test:\n                log.info('Would add `%s` 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                    log.info(\"No suited urls in entry %s\" % entry['title'])\n                continue\n\n            log.debug(\"Add %d urls to pyLoad\" % len(urls))\n\n            try:\n                dest = 1 if config.get('queue', self.DEFAULT_QUEUE) else 0  # Destination.Queue = 1\n                post = {'name': \"'%s'\" % entry['title'].encode(\"ascii\", \"ignore\"),\n                        'links': str(urls),\n                        'dest': dest,\n                        'session': self.session}\n\n                pid = query_api(api, \"addPackage\", post).read()\n                log.debug('added package pid: %s' % pid)\n\n                if folder:\n                    # set folder with api\n                    data = {'folder': folder}\n                    query_api(api, \"setPackageData\", {'pid': pid, 'data': data, 'session': self.session})\n\n            except Exception as e:\n                entry.fail(str(e))\n\n    def check_login(self, task, config):\n        url = config.get('api', self.DEFAULT_API)\n\n        if not self.session:\n            # Login\n            post = {'username': config['username'], 'password': config['password']}\n            result = query_api(url, \"login\", post)\n            response = json.loads(result.read())\n            if not response:\n                raise PluginError('Login failed', log)\n            self.session = response.replace('\"', '')\n        else:\n            try:\n                query_api(url, 'getServerVersion', {'session': self.session})\n            except HTTPError as e:\n                if e.code == 403:  # Forbidden\n                    self.session = None\n                    return self.check_login(task, config)\n                else:\n                    raise PluginError('HTTP Error %s' % e, log)\n\n\ndef query_api(url, method, post=None):\n    try:\n        return urlopen(url.rstrip(\"/\") + \"/\" + method.strip(\"/\"), urlencode(post) if post else None)\n    except HTTPError as e:\n        if e.code == 500:\n            raise PluginError('Internal API Error', log)\n        raise\n\nregister_plugin(PluginPyLoad, 'pyload', api_ver=2)\n", "path": "flexget/plugins/output/pyload.py"}], "after_files": [{"content": "# -*- coding: utf-8 -*-\n\nfrom __future__ import unicode_literals, division, absolute_import\nfrom urllib import quote\nfrom requests.exceptions import RequestException\nfrom logging import getLogger\nfrom flexget.utils import json, requests\nfrom flexget.plugin import register_plugin, PluginError\nfrom flexget import validator\n\nlog = getLogger('pyload')\n\n\nclass PluginPyLoad(object):\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        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.4'\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    def __init__(self):\n        self.session = None\n\n    def validator(self):\n        \"\"\"Return config validator\"\"\"\n        root = validator.factory()\n        root.accept('boolean')\n        advanced = root.accept('dict')\n        advanced.accept('text', key='api')\n        advanced.accept('text', key='username')\n        advanced.accept('text', key='password')\n        advanced.accept('text', key='folder')\n        advanced.accept('boolean', key='queue')\n        advanced.accept('boolean', key='parse_url')\n        advanced.accept('boolean', key='multiple_hoster')\n        advanced.accept('list', key='hoster').accept('text')\n        advanced.accept('boolean', key='preferred_hoster_only')\n        advanced.accept('boolean', key='handle_no_url_as_failure')\n        return root\n\n    def on_process_start(self, task, config):\n        self.session = None\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        try:\n            self.check_login(task, config)\n        except IOError:\n            raise PluginError('pyLoad not reachable', log)\n        except PluginError:\n            raise\n        except Exception as e:\n            raise PluginError('Unknown error: %s' % str(e), log)\n\n        api = config.get('api', self.DEFAULT_API)\n        hoster = config.get('hoster', self.DEFAULT_HOSTER)\n        folder = config.get('folder', self.DEFAULT_FOLDER)\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.encode(\"utf8\"))\n\n            url = json.dumps(entry['url']) if config.get('parse_url', self.DEFAULT_PARSE_URL) else \"''\"\n\n            log.debug(\"Parsing url %s\" % url)\n\n            result = query_api(api, \"parseURLs\", {\"html\": content, \"url\": url, \"session\": self.session})\n\n            # parsed { plugins: [urls] }\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('preferred_hoster_only', self.DEFAULT_PREFERRED_HOSTER_ONLY):\n                for name, purls in parsed.iteritems():\n                    if name != \"BasePlugin\":\n                        urls.extend(purls)\n\n            if task.manager.options.test:\n                log.info('Would add `%s` 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                    log.info(\"No suited urls in entry %s\" % entry['title'])\n                continue\n\n            log.debug(\"Add %d urls to pyLoad\" % len(urls))\n\n            try:\n                dest = 1 if config.get('queue', self.DEFAULT_QUEUE) else 0  # Destination.Queue = 1\n                post = {'name': \"'%s'\" % entry['title'].encode(\"ascii\", \"ignore\"),\n                        'links': str(urls),\n                        'dest': dest,\n                        'session': self.session}\n\n                pid = query_api(api, \"addPackage\", post).text\n                log.debug('added package pid: %s' % pid)\n\n                if folder:\n                    # set folder with api\n                    data = {'folder': folder}\n                    query_api(api, \"setPackageData\", {'pid': pid, 'data': data, 'session': self.session})\n\n            except Exception as e:\n                entry.fail(str(e))\n\n    def check_login(self, task, config):\n        url = config.get('api', self.DEFAULT_API)\n\n        if not self.session:\n            # Login\n            post = {'username': config['username'], 'password': config['password']}\n            result = query_api(url, \"login\", post)\n            response = result.json()\n            if not response:\n                raise PluginError('Login failed', log)\n            self.session = response.replace('\"', '')\n        else:\n            try:\n                query_api(url, 'getServerVersion', {'session': self.session})\n            except HTTPError as e:\n                if e.response.status_code == 403:  # Forbidden\n                    self.session = None\n                    return self.check_login(task, config)\n                else:\n                    raise PluginError('HTTP Error %s' % e, log)\n\n\ndef query_api(url, method, post=None):\n    try:\n        response = requests.request(\n            'post' if post is not None else 'get',\n            url.rstrip(\"/\") + \"/\" + method.strip(\"/\"),\n            data=post)\n        response.raise_for_status()\n        return response\n    except RequestException as e:\n        if e.response.status_code == 500:\n            raise PluginError('Internal API Error: <%s> <%s> <%s>' % (method, url, post), log)\n        raise\n\nregister_plugin(PluginPyLoad, 'pyload', api_ver=2)\n", "path": "flexget/plugins/output/pyload.py"}]}