Repository: pymedusa/Medusa

Issue:
uTorrent bad request
### Before submitting your issue:

Enable debug logging in Medusa settings, reproduce the error (be sure to disable after the bug is fixed)

**Branch/Commit:**
Latest stable and latest stable uTorrent
**OS:**
Windows Server 2016
**What you did:**
Added uTorrent and get bad request
**What happened:**
Can't add torrent
**What you expected:**
**Logs:**
In debug logs
```
2017-05-02 03:21:23 WARNING  SNATCHQUEUE-MANUALSNATCH-295685 :: [9c19b10] uTorrent: Unable to send Torrent
2017-05-02 03:21:23 INFO     SNATCHQUEUE-MANUALSNATCH-295685 :: [9c19b10] uTorrent: Bad Request
2017-05-02 03:21:23 INFO     SNATCHQUEUE-MANUALSNATCH-295685 :: [9c19b10] Downloading (redacted) with 10 seeders and 5 leechers and size 42.64 GB from Rarbg
2017-05-02 03:21:23 INFO     SNATCHQUEUE-MANUALSNATCH-295685 :: [9c19b10] Beginning to manual snatch release: (redacted)
```



Discussion:
Did you try with previous uTorrent versions? Seems more like a problem connecting to the client. Does the test work correctly?
Yes the test works correctly. I tried
µTorrent Stable(3.5.0 build 43580). 
I also tried uTorrent 3.4.8 build 42576 
No issues here with build 43580

```
2017-05-08 12:32:22 DEBUG    SNATCHQUEUE-MANUALSNATCH-257655 :: [b4a8a54] Calling uTorrent Client
2017-05-08 12:32:43 DEBUG    SNATCHQUEUE-MANUALSNATCH-257655 :: [b4a8a54] uTorrent: Requested a GET connection to http://localhost:9090/gui/ with params: {u'action': u'add-url', u'token': u'DCXzVnSnRsAkXRnr9_x6shcdUOXjWscpFv3jwZa4E4BW36Ym6p1IB4aPEFkAAAAA', u's': u'magnet:?xt=urn:btih:f3dc1d9fdab484587c&dn=Show.S05E20.2016.720p.BrRip.x264--.SiMPLE&tr=udp://coppersurfer.tk:6969/announce&tr=udp://open.demonii.com:1337&tr=udp://exodus.desync.com:6969&tr=udp://9.rarbg.me:2710/announce&tr=udp://glotorrents.pw:6969/announce&tr=udp://tracker.openbittorrent.com:80/announce&tr=udp://9.rarbg.to:2710/announce'} Data: None
2017-05-08 12:32:43 DEBUG    SNATCHQUEUE-MANUALSNATCH-257655 :: [b4a8a54] uTorrent: Response to GET request is {"build":43580}
```
enabled debug log and try again sending new logs
That is with debug
@Stonedestroyer no. with debug you should see:

`uTorrent: Requested a GET connection to http://localhost:9090/gui/ with params: {u'action': u'add-url'.....`
```
2017-05-09 10:06:04 WARNING  SNATCHQUEUE-MANUALSNATCH-258171 :: [8b5eb6f] uTorrent: Unable to send Torrent
2017-05-09 10:06:04 INFO     SNATCHQUEUE-MANUALSNATCH-258171 :: [8b5eb6f] uTorrent: Bad Request
2017-05-09 10:06:04 DEBUG    SNATCHQUEUE-MANUALSNATCH-258171 :: [8b5eb6f] uTorrent: Requested a GET connection to http://localhost:5003/gui/ with params: {u'action': u'add-url', u'token': u'REMOVED_TOKEN_HERE', u's': u'magnet:?xt=urn:btih:1605ca44f02a326b2d950444b2f68e8876005a62&dn=Continuum.S04.1080p.BluRay.x264-YELLOWBiRD%5Brartv%5D&tr=http%3A%2F%2Ftracker.trackerfix.com%3A80%2Fannounce&tr=udp%3A%2F%2F9.rarbg.me%3A2710&tr=udp%3A%2F%2F9.rarbg.to%3A2710&tr=udp%3A%2F%2Fopen.demonii.com%3A1337%2Fannounce&tr=udp://tracker.coppersurfer.tk:6969/announce&tr=udp://tracker.leechers-paradise.org:6969/announce&tr=udp://tracker.zer0day.to:1337/announce&tr=udp://tracker.opentrackr.org:1337/announce&tr=http://tracker.opentrackr.org:1337/announce&tr=udp://p4p.arenabg.com:1337/announce&tr=http://p4p.arenabg.com:1337/announce&tr=udp://explodie.org:6969/announce&tr=udp://9.rarbg.com:2710/announce&tr=http://explodie.org:6969/announce&tr=http://tracker.dler.org:6969/announce&tr=udp://public.popcorn-tracker.org:6969/announce&tr=udp://tracker.internetwarriors.net:1337/announce&tr=udp://ipv4.tracker.harry.lu:80/announce&tr=http://ipv4.tracker.harry.lu:80/announce&tr=udp://mgtracker.org:2710/announce&tr=http://mgtracker.org:6969/announce&tr=udp://tracker.mg64.net:6969/announce&tr=http://tracker.mg64.net:6881/announce&tr=http://torrentsmd.com:8080/announce'} Data: None
2017-05-09 10:06:04 DEBUG    SNATCHQUEUE-MANUALSNATCH-258171 :: [8b5eb6f] Calling uTorrent Client
2017-05-09 10:06:04 INFO     SNATCHQUEUE-MANUALSNATCH-258171 :: [8b5eb6f] Downloading Continuum.S04.1080p.BluRay.x264-YELLOWBiRD[rartv] with 5 seeders and 1 leechers and size 19.63 GB from Rarbg
2017-05-09 10:06:04 INFO     SNATCHQUEUE-MANUALSNATCH-258171 :: [8b5eb6f] Beginning to manual snatch release: Continuum.S04.1080p.BluRay.x264-YELLOWBiRD[rartv]
```
Test works as well, this is on latest 3.5 stable, I can try any other version numbers. I've tried most of them now except 2.2.1. 
Any progress on this issue? 
@Stonedestroyer 
I've been looking into this and found the issue(s). Will push a fix ASAP.

Resolving patch:
diff --git a/medusa/clients/torrent/generic.py b/medusa/clients/torrent/generic.py
--- a/medusa/clients/torrent/generic.py
+++ b/medusa/clients/torrent/generic.py
@@ -19,8 +19,6 @@
 from medusa.logger.adapters.style import BraceAdapter
 
 import requests
-from six.moves.http_cookiejar import CookieJar
-
 
 log = BraceAdapter(logging.getLogger(__name__))
 log.logger.addHandler(logging.NullHandler())
@@ -52,7 +50,6 @@ def __init__(self, name, host=None, username=None, password=None):
         self.last_time = time.time()
         self.session = helpers.make_session()
         self.session.auth = (self.username, self.password)
-        self.session.cookies = CookieJar()
 
     def _request(self, method='get', params=None, data=None, files=None, cookies=None):
 
@@ -321,5 +318,5 @@ def test_authentication(self):
                 return True, 'Success: Connected and Authenticated'
             else:
                 return False, 'Error: Unable to get {name} Authentication, check your config!'.format(name=self.name)
-        except Exception:
-            return False, 'Error: Unable to connect to {name}'.format(name=self.name)
+        except Exception as error:
+            return False, 'Unable to connect to {name}. Error: {msg}'.format(name=self.name, msg=error)
diff --git a/medusa/clients/torrent/utorrent_client.py b/medusa/clients/torrent/utorrent_client.py
--- a/medusa/clients/torrent/utorrent_client.py
+++ b/medusa/clients/torrent/utorrent_client.py
@@ -6,6 +6,7 @@
 
 import logging
 import re
+from collections import OrderedDict
 
 from medusa import app
 from medusa.clients.torrent.generic import GenericClient
@@ -13,9 +14,6 @@
 
 from requests.compat import urljoin
 
-from six import iteritems
-
-
 log = BraceAdapter(logging.getLogger(__name__))
 log.logger.addHandler(logging.NullHandler())
 
@@ -37,39 +35,29 @@ def __init__(self, host=None, username=None, password=None):
         self.url = urljoin(self.host, 'gui/')
 
     def _request(self, method='get', params=None, data=None, files=None, cookies=None):
-
         if cookies:
             log.debug('{name}: Received unused argument: cookies={value!r}',
                       {'name': self.name, 'value': cookies})
 
-        # Workaround for uTorrent 2.2.1
-        # Need an OrderedDict but only supported in 2.7+
-        # Medusa is no longer 2.6+
-
-        # TOD0: Replace this with an OrderedDict
-        ordered_params = {
+        # "token" must be the first parameter: https://goo.gl/qTxf9x
+        ordered_params = OrderedDict({
             'token': self.auth,
-        }
-
-        for k, v in iteritems(params) or {}:
-            ordered_params.update({k: v})
+        })
+        ordered_params.update(params)
 
         return super(UTorrentAPI, self)._request(method=method, params=ordered_params, data=data, files=files)
 
     def _get_auth(self):
-
-        try:
-            self.response = self.session.get(urljoin(self.url, 'token.html'), verify=False)
+        self.response = self.session.get(urljoin(self.url, 'token.html'), verify=False)
+        if not self.response.status_code == 404:
             self.auth = re.findall('<div.*?>(.*?)</', self.response.text)[0]
-        except Exception:
-            return None
-
-        return self.auth if not self.response.status_code == 404 else None
+            return self.auth
 
     def _add_torrent_uri(self, result):
         return self._request(params={
             'action': 'add-url',
-            's': result.url,
+            # limit the param length to 1024 chars (uTorrent bug)
+            's': result.url[:1024],
         })
 
     def _add_torrent_file(self, result):
@@ -87,7 +75,6 @@ def _add_torrent_file(self, result):
         )
 
     def _set_torrent_label(self, result):
-
         if result.show.is_anime and app.TORRENT_LABEL_ANIME:
             label = app.TORRENT_LABEL_ANIME
         else:
@@ -101,7 +88,6 @@ def _set_torrent_label(self, result):
         })
 
     def _set_torrent_ratio(self, result):
-
         ratio = result.ratio or None
 
         if ratio:
@@ -123,7 +109,6 @@ def _set_torrent_ratio(self, result):
         return True
 
     def _set_torrent_seed_time(self, result):
-
         if app.TORRENT_SEED_TIME:
             if self._request(params={
                 'action': 'setprops',


Test patch: