'Called by any thread'

def add(self, tdef, dscfg, pstate=None, setupDelay=0, hidden=False, share_mode=False, checkpoint_disabled=False):

    d = None
    with self.session_lock:
        if ((not isinstance(tdef, TorrentDefNoMetainfo)) and (not tdef.is_finalized())):
            raise ValueError('TorrentDef    not    finalized')
        infohash = tdef.get_infohash()
        try:
            if (not os.path.isdir(dscfg.get_dest_dir())):
                os.makedirs(dscfg.get_dest_dir())
        except OSError:
            self._logger.error('Unable    to    create    the    download    destination    directory.')
        if (dscfg.get_time_added() == 0):
            dscfg.set_time_added(int(timemod.time()))
        if (infohash in self.downloads):
            raise DuplicateDownloadException('This    download    already    exists.')
        from Tribler.Core.Libtorrent.LibtorrentDownloadImpl import LibtorrentDownloadImpl
        d = LibtorrentDownloadImpl(self.session, tdef)
        if (pstate is None):
            pstate = self.load_download_pstate_noexc(infohash)
            if (pstate is not None):
                self._logger.debug('tlm:    add:    pstate    is    %s    %s', pstate.get('dlstate', 'status'), pstate.get('dlstate', 'progress'))
        self.downloads[infohash] = d
        setup_deferred = d.setup(dscfg, pstate, wrapperDelay=setupDelay, share_mode=share_mode, checkpoint_disabled=checkpoint_disabled)
        setup_deferred.addCallback(self.on_download_handle_created)
    if (d and (not hidden) and self.session.config.get_megacache_enabled()):
        @forceDBThread
        def write_my_pref():
            torrent_id = self.torrent_db.getTorrentID(infohash)
            data = {'destination_path': d.get_dest_dir()}
            self.mypref_db.addMyPreference(torrent_id, data)
        if isinstance(tdef, TorrentDefNoMetainfo):
            self.torrent_db.addOrGetTorrentID(tdef.get_infohash())
            self.torrent_db.updateTorrent(tdef.get_infohash(), name=tdef.get_name_as_unicode())
            write_my_pref()
        elif self.rtorrent_handler:
            self.rtorrent_handler.save_torrent(tdef, write_my_pref)
        else:
            self.torrent_db.addExternalTorrent(tdef, extra_info={'status': 'good'})
            write_my_pref()
    return d
