diff --git a/deluge/core/core.py b/deluge/core/core.py index c7428baa2d..fc12f7bc56 100644 --- a/deluge/core/core.py +++ b/deluge/core/core.py @@ -12,7 +12,6 @@ import os import shutil import tempfile -import threading from base64 import b64decode, b64encode from typing import Any, Dict, List, Optional, Tuple, Union from urllib.request import URLError, urlopen @@ -1001,21 +1000,19 @@ def create_torrent( add_to_session=False, ): log.debug('creating torrent..') - threading.Thread( - target=self._create_torrent_thread, - args=( - path, - tracker, - piece_length, - comment, - target, - webseeds, - private, - created_by, - trackers, - add_to_session, - ), - ).start() + return threads.deferToThread( + self._create_torrent_thread, + path, + tracker, + piece_length, + comment=comment, + target=target, + webseeds=webseeds, + private=private, + created_by=created_by, + trackers=trackers, + add_to_session=add_to_session, + ) def _create_torrent_thread( self, @@ -1055,12 +1052,13 @@ def _create_torrent_thread( with open(target, 'wb') as _file: _file.write(filecontent) + filedump = b64encode(filecontent) log.debug('torrent created!') if add_to_session: options = {} options['download_location'] = os.path.split(path)[0] - filedump = b64encode(filecontent) self.add_torrent_file(filename, filedump, options) + return filename, filedump @export def upload_plugin(self, filename: str, filedump: Union[str, bytes]) -> None: diff --git a/deluge/tests/test_core.py b/deluge/tests/test_core.py index c2f6333ab2..8f6997f60f 100644 --- a/deluge/tests/test_core.py +++ b/deluge/tests/test_core.py @@ -3,11 +3,12 @@ # the additional special exception to link portions of this program with the OpenSSL library. # See LICENSE for more details. # - +import base64 import os from base64 import b64encode from hashlib import sha1 as sha +import libtorrent import pytest import pytest_twisted from twisted.internet import defer, reactor, task @@ -483,3 +484,32 @@ def test__create_peer_id(self): assert self.core._create_peer_id('2.0.1rc1') == '-DE201r-' assert self.core._create_peer_id('2.11.0b2') == '-DE2B0b-' assert self.core._create_peer_id('2.4.12b2.dev3') == '-DE24CD-' + + @pytest.mark.parametrize( + 'path', + [ + common.get_test_data_file('deluge.png'), + os.path.dirname(common.get_test_data_file('deluge.png')), + ], + ) + @pytest.mark.parametrize('piece_length', [2**14, 2**16]) + def test_create_torrent(self, path, tmp_path, piece_length): + target = tmp_path / 'test.torrent' + + def check_torrent_ok(result): + filename, filedump = result + filecontent = base64.b64decode(filedump) + + with open(target, 'rb') as f: + assert f.read() == filecontent + + libtorrent.torrent_info(filecontent) + + d = self.core.create_torrent( + path=path, + tracker=None, + piece_length=piece_length, + target=target, + add_to_session=False, + ) + return d.addCallback(check_torrent_ok)