Exemplo n.º 1
0
 def callTFTU(self, **kwargs):
     kwargs = dict(dict(sizeWhenDone=200, leftUntilDone=100), **kwargs)
     if 'name' not in kwargs:
         kwargs['name'] = 'awesome torrent {id}'.format(**kwargs)
     if kwargs['leftUntilDone'] != 0:
         kwargs['status'] = 4
     else:
         kwargs['status'] = 6
     cli = MagicMock()
     cli.rpc_version = 15
     return Torrent(cli, kwargs)
Exemplo n.º 2
0
    def _request(self,
                 method,
                 arguments=None,
                 ids=None,
                 require_ids=False,
                 timeout=None):
        """
        Send json-rpc request to Transmission using http POST
        """
        if not isinstance(method, string_types):
            raise ValueError('request takes method as string')
        if arguments is None:
            arguments = {}
        if not isinstance(arguments, dict):
            raise ValueError('request takes arguments as dict')
        ids = parse_torrent_ids(ids)
        if len(ids) > 0:
            arguments['ids'] = ids
        elif require_ids:
            raise ValueError('request require ids')

        query = json.dumps({
            'tag': self._sequence,
            'method': method,
            'arguments': arguments
        })
        self._sequence += 1
        start = time.time()
        http_data = self._http_query(query, timeout)
        elapsed = time.time() - start
        LOGGER.info('http request took %.3f s' % (elapsed))

        try:
            data = json.loads(http_data)
        except ValueError as error:
            LOGGER.error('Error: ' + str(error))
            LOGGER.error('Request: \"%s\"' % (query))
            LOGGER.error('HTTP data: \"%s\"' % (http_data))
            raise

        LOGGER.debug(json.dumps(data, indent=2))
        if 'result' in data:
            if data['result'] != 'success':
                raise TransmissionError('Query failed with result \"%s\".' %
                                        (data['result']))
        else:
            raise TransmissionError('Query failed without result.')

        results = {}
        if method == 'torrent-get':
            for item in data['arguments']['torrents']:
                results[item['id']] = Torrent(self, item)
                if self.protocol_version == 2 and 'peers' not in item:
                    self.protocol_version = 1
        elif method == 'torrent-add':
            item = None
            if 'torrent-added' in data['arguments']:
                item = data['arguments']['torrent-added']
            elif 'torrent-duplicate' in data['arguments']:
                item = data['arguments']['torrent-duplicate']
            if item:
                results[item['id']] = Torrent(self, item)
            else:
                raise TransmissionError('Invalid torrent-add response.')
        elif method == 'session-get':
            self._update_session(data['arguments'])
        elif method == 'session-stats':
            # older versions of T has the return data in "session-stats"
            if 'session-stats' in data['arguments']:
                self._update_session(data['arguments']['session-stats'])
            else:
                self._update_session(data['arguments'])
        elif method in ('port-test', 'blocklist-update', 'free-space',
                        'torrent-rename-path'):
            results = data['arguments']
        else:
            return None

        return results
Exemplo n.º 3
0
    def testAttributes(self):
        torrent = Torrent(None, {"id": 42})
        self.assertTrue(hasattr(torrent, "id"))
        self.assertEqual(torrent.id, 42)
        self.assertPropertyException(KeyError, torrent, "status")
        self.assertPropertyException(KeyError, torrent, "progress")
        self.assertPropertyException(KeyError, torrent, "ratio")
        self.assertPropertyException(KeyError, torrent, "eta")
        self.assertPropertyException(KeyError, torrent, "date_active")
        self.assertPropertyException(KeyError, torrent, "date_added")
        self.assertPropertyException(KeyError, torrent, "date_started")
        self.assertPropertyException(KeyError, torrent, "date_done")

        self.assertRaises(KeyError, torrent.format_eta)
        self.assertEqual(torrent.files(), {})

        data = {
            "id": 1,
            "status": 4,
            "sizeWhenDone": 1000,
            "leftUntilDone": 500,
            "uploadedEver": 1000,
            "downloadedEver": 2000,
            "uploadRatio": 0.5,
            "eta": 3600,
            "activityDate": time.mktime((2008, 12, 11, 11, 15, 30, 0, 0, -1)),
            "addedDate": time.mktime((2008, 12, 11, 8, 5, 10, 0, 0, -1)),
            "startDate": time.mktime((2008, 12, 11, 9, 10, 5, 0, 0, -1)),
            "doneDate": time.mktime((2008, 12, 11, 10, 0, 15, 0, 0, -1)),
        }

        torrent = Torrent(None, data)
        self.assertEqual(torrent.id, 1)
        self.assertEqual(torrent.leftUntilDone, 500)
        self.assertEqual(torrent.status, "downloading")
        self.assertEqual(torrent.progress, 50.0)
        self.assertEqual(torrent.ratio, 0.5)
        self.assertEqual(torrent.eta, datetime.timedelta(seconds=3600))
        self.assertEqual(
            torrent.date_active, datetime.datetime(2008, 12, 11, 11, 15, 30)
        )
        self.assertEqual(torrent.date_added, datetime.datetime(2008, 12, 11, 8, 5, 10))
        self.assertEqual(
            torrent.date_started, datetime.datetime(2008, 12, 11, 9, 10, 5)
        )
        self.assertEqual(torrent.date_done, datetime.datetime(2008, 12, 11, 10, 0, 15))

        self.assertEqual(
            torrent.format_eta(), transmissionrpc.utils.format_timedelta(torrent.eta)
        )

        torrent = Torrent(None, {"id": 42, "eta": -1})
        self.assertPropertyException(ValueError, torrent, "eta")

        data = {
            "id": 1,
            "status": 4,
            "sizeWhenDone": 1000,
            "leftUntilDone": 500,
            "uploadedEver": 1000,
            "downloadedEver": 2000,
            "uploadRatio": 0.5,
            "eta": 3600,
            "activityDate": time.mktime((2008, 12, 11, 11, 15, 30, 0, 0, -1)),
            "addedDate": time.mktime((2008, 12, 11, 8, 5, 10, 0, 0, -1)),
            "startDate": time.mktime((2008, 12, 11, 9, 10, 5, 0, 0, -1)),
            "doneDate": 0,
        }

        torrent = Torrent(None, data)
        self.assertEqual(torrent.date_done, None)
Exemplo n.º 4
0
 def testConstruction(self):
     self.assertRaises(ValueError, Torrent, None, {})
     Torrent(None, {"id": 42})
Exemplo n.º 5
0
 def testUnicode(self):
     torrent = Torrent(None, {"id": 42, "name": "あみ"})
     self.assertEqual(torrent.id, 42)
     repr(torrent)
     str(torrent)
Exemplo n.º 6
0
            LOGGER.error('Request: \"%s\"' % (query))
            LOGGER.error('HTTP data: \"%s\"' % (http_data))
            raise

        LOGGER.debug(json.dumps(data, indent=2))
        if 'result' in data:
            if data['result'] != 'success':
                raise TransmissionError('Query failed with result \"%s\".' %
                                        (data['result']))
        else:
            raise TransmissionError('Query failed without result.')

        results = {}
        if method == 'torrent-get':
            for item in data['arguments']['torrents']:
                results[item['id']] = Torrent(self, item)
                if self.protocol_version == 2 and 'peers' not in item:
                    self.protocol_version = 1
        elif method == 'torrent-add':
            item = data['arguments']['torrent-added']
            results[item['id']] = Torrent(self, item)
        elif method == 'session-get':
            self._update_session(data['arguments'])
        elif method == 'session-stats':
            # older versions of T has the return data in "session-stats"
            if 'session-stats' in data['arguments']:
                self._update_session(data['arguments']['session-stats'])
            else:
                self._update_session(data['arguments'])
        elif method in ('port-test', 'blocklist-update'):
            results = data['arguments']
Exemplo n.º 7
0
    def _request(self,
                 method,
                 arguments=None,
                 ids=None,
                 require_ids=False,
                 timeout=None):
        """
        Send json-rpc request to Transmission using http POST
        """
        if not isinstance(method, str):
            raise ValueError("request takes method as string")
        if arguments is None:
            arguments = {}
        if not isinstance(arguments, dict):
            raise ValueError("request takes arguments as dict")
        ids = parse_torrent_ids(ids)
        if ids:
            arguments["ids"] = ids
        elif require_ids:
            raise ValueError("request require ids")
        use_logger = is_logger_configured()

        query = json.dumps({
            "tag": self._sequence,
            "method": method,
            "arguments": arguments
        })
        self._sequence += 1
        start = time.time()
        http_data = self._http_query(query, timeout)
        if isinstance(http_data, bytes):
            http_data = str(http_data, encoding="utf-8", errors="replace")
        http_data = "".join(
            list(filter(lambda c: unicodedata.category(c)[0] != "C",
                        http_data)))
        elapsed = time.time() - start
        if use_logger:
            LOGGER.info("http request took %.3f s", elapsed)

        try:
            data = json.loads(http_data)
        except ValueError as error:
            if use_logger:
                LOGGER.error("Error: %s", str(error))
                LOGGER.error('Request: "%s"', query)
                LOGGER.error('HTTP data: "%s"', http_data)
            raise

        if use_logger:
            LOGGER.debug(json.dumps(data, indent=2))
        if "result" in data:
            if data["result"] != "success":
                raise TransmissionError('Query failed with result "%s".' %
                                        (data["result"]))
        else:
            raise TransmissionError("Query failed without result.")

        results = {}
        if method == "torrent-get":
            for item in data["arguments"]["torrents"]:
                results[item["id"]] = Torrent(self, item)
                if self.protocol_version == 2 and "peers" not in item:
                    self.protocol_version = 1
        elif method == "torrent-add":
            item = None
            if "torrent-added" in data["arguments"]:
                item = data["arguments"]["torrent-added"]
            elif "torrent-duplicate" in data["arguments"]:
                item = data["arguments"]["torrent-duplicate"]
            if item:
                results[item["id"]] = Torrent(self, item)
            else:
                raise TransmissionError("Invalid torrent-add response.")
        elif method == "session-get":
            self._update_session(data["arguments"])
        elif method == "session-stats":
            # older versions of T has the return data in "session-stats"
            if "session-stats" in data["arguments"]:
                self._update_session(data["arguments"]["session-stats"])
            else:
                self._update_session(data["arguments"])
        elif method in (
                "port-test",
                "blocklist-update",
                "free-space",
                "torrent-rename-path",
        ):
            results = data["arguments"]
        else:
            return None

        return results
Exemplo n.º 8
0
 def testUnicode(self):
     torrent = Torrent(None, {'id': 42, 'name': 'あみ'})
     self.assertEqual(torrent.id, 42)
     repr(torrent)
     str(torrent)
Exemplo n.º 9
0
    def testAttributes(self):
        torrent = Torrent(None, {'id': 42})
        self.assertTrue(hasattr(torrent, 'id'))
        self.assertEqual(torrent.id, 42)
        self.assertPropertyException(KeyError, torrent, 'status')
        self.assertPropertyException(KeyError, torrent, 'progress')
        self.assertPropertyException(KeyError, torrent, 'ratio')
        self.assertPropertyException(KeyError, torrent, 'eta')
        self.assertPropertyException(KeyError, torrent, 'date_active')
        self.assertPropertyException(KeyError, torrent, 'date_added')
        self.assertPropertyException(KeyError, torrent, 'date_started')
        self.assertPropertyException(KeyError, torrent, 'date_done')

        self.assertRaises(KeyError, torrent.format_eta)
        self.assertEqual(torrent.files(), {})

        data = {
            'id': 1,
            'status': 4,
            'sizeWhenDone': 1000,
            'leftUntilDone': 500,
            'uploadedEver': 1000,
            'downloadedEver': 2000,
            'uploadRatio': 0.5,
            'eta': 3600,
            'activityDate': time.mktime((2008, 12, 11, 11, 15, 30, 0, 0, -1)),
            'addedDate': time.mktime((2008, 12, 11, 8, 5, 10, 0, 0, -1)),
            'startDate': time.mktime((2008, 12, 11, 9, 10, 5, 0, 0, -1)),
            'doneDate': time.mktime((2008, 12, 11, 10, 0, 15, 0, 0, -1)),
        }

        torrent = Torrent(None, data)
        self.assertEqual(torrent.id, 1)
        self.assertEqual(torrent.leftUntilDone, 500)
        self.assertEqual(torrent.status, 'downloading')
        self.assertEqual(torrent.progress, 50.0)
        self.assertEqual(torrent.ratio, 0.5)
        self.assertEqual(torrent.eta, datetime.timedelta(seconds=3600))
        self.assertEqual(torrent.date_active, datetime.datetime(2008, 12, 11, 11, 15, 30))
        self.assertEqual(torrent.date_added, datetime.datetime(2008, 12, 11, 8, 5, 10))
        self.assertEqual(torrent.date_started, datetime.datetime(2008, 12, 11, 9, 10, 5))
        self.assertEqual(torrent.date_done, datetime.datetime(2008, 12, 11, 10, 0, 15))

        self.assertEqual(torrent.format_eta(), transmissionrpc.utils.format_timedelta(torrent.eta))

        torrent = Torrent(None, {'id': 42, 'eta': -1})
        self.assertPropertyException(ValueError, torrent, 'eta')

        data = {
            'id': 1,
            'status': 4,
            'sizeWhenDone': 1000,
            'leftUntilDone': 500,
            'uploadedEver': 1000,
            'downloadedEver': 2000,
            'uploadRatio': 0.5,
            'eta': 3600,
            'activityDate': time.mktime((2008, 12, 11, 11, 15, 30, 0, 0, -1)),
            'addedDate': time.mktime((2008, 12, 11, 8, 5, 10, 0, 0, -1)),
            'startDate': time.mktime((2008, 12, 11, 9, 10, 5, 0, 0, -1)),
            'doneDate': 0,
        }

        torrent = Torrent(None, data)
        self.assertEqual(torrent.date_done, None)