# Buggy code
def render_PUT(self, request):
    """
    .. http:put:: /channels/discovered/(string: channelid)/torrents/http%3A%2F%2Ftest.com%2Ftest.torrent

    Add a torrent by magnet or url to your channel. Returns error 500 if something is wrong with the torrent file
    and DuplicateTorrentFileError if already added to your channel (except with magnet links).

        **Example request**:

        .. sourcecode:: none

            curl -X PUT http://localhost:8085/channels/discovered/abcdefg/torrents/
            http%3A%2F%2Ftest.com%2Ftest.torrent --data "description=nice video"

        **Example response**:

        .. sourcecode:: javascript

            {
                "added": "http://test.com/test.torrent"
            }

        :statuscode 404: if your channel does not exist.
        :statuscode 500: if the specified torrent is already in your channel.
    """
    channel = self.get_channel_from_db(self.cid)
    if channel is None:
        return BaseChannelsEndpoint.return_404(request)

    parameters = http.parse_qs(request.content.read(), 1)

    if "description" not in parameters or len(parameters["description"]) == 0:
        extra_info = {}
    else:
        extra_info = {"description": parameters["description"][0]}

    try:
        if self.infohash.startswith("http:") or self.infohash.startswith("https:"):
            torrent_def = TorrentDef.load_from_url(self.infohash)
            self.session.add_torrent_def_to_channel(
                channel[0], torrent_def, extra_info, forward=True
            )
        if self.infohash.startswith("magnet:"):

            def on_receive_magnet_meta_info(meta_info):
                torrent_def = TorrentDef.load_from_dict(meta_info)
                self.session.add_torrent_def_to_channel(
                    channel[0], torrent_def, extra_info, forward=True
                )

            infohash_or_magnet = self.infohash
            callback = on_receive_magnet_meta_info
            self.session.lm.ltmgr.get_metainfo(infohash_or_magnet, callback)

    except (DuplicateTorrentFileError, ValueError) as ex:
        return BaseChannelsEndpoint.return_500(self, request, ex)

    return json.dumps({"added": self.infohash})


# Traceback (AssertionError)
I: test_add_torrent_from_magnet_to_channel_without_description (Tribler.Test.Core.Modules.RestApi.Channels.test_channels_torrents_endpoint.TestModifyChannelTorrentEndpoint) ... ok
I: test_add_torrent_from_url_to_channel_with_description (Tribler.Test.Core.Modules.RestApi.Channels.test_channels_torrents_endpoint.TestModifyChannelTorrentEndpoint) ... 2016-07-04 16:21:10,891 [ERROR] The reactor was dirty:
I: 2016-07-04 16:21:10,894 [ERROR] >     <DelayedCall 0x9792a968 [0.772477149963s] called=0 cancelled=0 LoopingCall<5>(ChannelCommunity.take_step, *(), **{})()>
I: 2016-07-04 16:21:10,897 [ERROR] >     <DelayedCall 0x978549e0 [4.73240303993s] called=0 cancelled=0 LoopingCall<5.0>(ChannelCommunity._periodically_clean_delayed, *(), **{})()>
I: ERROR
I: ======================================================================
I: ERROR: test_add_torrent_from_url_to_channel_with_description (Tribler.Test.Core.Modules.RestApi.Channels.test_channels_torrents_endpoint.TestModifyChannelTorrentEndpoint)
I: ----------------------------------------------------------------------
I: Traceback (most recent call last):
I:   File "/data/data/org.tribler.android/files/lib/python2.7/site-packages/Tribler/Test/test_as_server.py", line 274, in tearDown
I:     super(TestAsServer, self).tearDown(annotate=False)
I:   File "/data/data/org.tribler.android/files/lib/python2.7/site-packages/Tribler/Core/Utilities/twisted_thread.py", line 151, in errback
I:     failure.raiseException()
I:   File "/data/data/org.tribler.android/files/lib/python2.7/site-packages/twisted/internet/defer.py", line 588, in _runCallbacks
I:     current.result = callback(current.result, *args, **kw)
I:   File "/data/data/org.tribler.android/files/lib/python2.7/site-packages/Tribler/Test/test_as_server.py", line 143, in checkReactor
I:     self.assertFalse(delayed_calls, "The reactor was dirty when tearing down the test")
I: AssertionError: The reactor was dirty when tearing down the test
I: ----------------------------------------------------------------------

# Fixed code
def render_PUT(self, request):
    """
    .. http:put:: /channels/discovered/(string: channelid)/torrents/http%3A%2F%2Ftest.com%2Ftest.torrent

    Add a torrent by magnet or url to your channel. Returns error 500 if something is wrong with the torrent file
    and DuplicateTorrentFileError if already added to your channel (except with magnet links).

        **Example request**:

        .. sourcecode:: none

            curl -X PUT http://localhost:8085/channels/discovered/abcdefg/torrents/
            http%3A%2F%2Ftest.com%2Ftest.torrent --data "description=nice video"

        **Example response**:

        .. sourcecode:: javascript

            {
                "added": "http://test.com/test.torrent"
            }

        :statuscode 404: if your channel does not exist.
        :statuscode 500: if the specified torrent is already in your channel.
    """
    channel = self.get_channel_from_db(self.cid)
    if channel is None:
        return BaseChannelsEndpoint.return_404(request)

    parameters = http.parse_qs(request.content.read(), 1)

    if "description" not in parameters or len(parameters["description"]) == 0:
        extra_info = {}
    else:
        extra_info = {"description": parameters["description"][0]}

    def _on_url_fetched(data):
        return TorrentDef.load_from_memory(data)

    def _on_magnet_fetched(meta_info):
        return TorrentDef.load_from_dict(meta_info)

    def _on_torrent_def_loaded(torrent_def):
        self.session.add_torrent_def_to_channel(
            channel[0], torrent_def, extra_info, forward=True
        )
        return self.path

    def _on_added(added):
        request.write(json.dumps({"added": added}))
        request.finish()

    def _on_add_failed(failure):
        failure.trap(ValueError, DuplicateTorrentFileError)
        self._logger.exception(failure.value)
        request.write(BaseChannelsEndpoint.return_500(self, request, failure.value))
        request.finish()

    if self.path.startswith("http:") or self.path.startswith("https:"):
        self.deferred = http_get(self.path)
        self.deferred.addCallback(_on_url_fetched)

    if self.path.startswith("magnet:"):
        try:
            self.session.lm.ltmgr.get_metainfo(
                self.path,
                callback=self.deferred.callback,
                timeout=30,
                timeout_callback=self.deferred.errback,
                notify=True,
            )
        except Exception as ex:
            self.deferred.errback(ex)

        self.deferred.addCallback(_on_magnet_fetched)

    self.deferred.addCallback(_on_torrent_def_loaded)
    self.deferred.addCallback(_on_added)
    self.deferred.addErrback(_on_add_failed)
    return NOT_DONE_YET