+
+// ---------------------------------------------------------------------------
+
+function safeWebtorrentDestroy (
+ webtorrent: WebTorrent.Instance,
+ torrentId: string,
+ downloadedFile?: { directoryPath: string, filepath: string },
+ torrentName?: string
+) {
+ return new Promise(res => {
+ webtorrent.destroy(err => {
+ // Delete torrent file
+ if (torrentName) {
+ logger.debug('Removing %s torrent after webtorrent download.', torrentId)
+ remove(torrentId)
+ .catch(err => logger.error('Cannot remove torrent %s in webtorrent download.', torrentId, { err }))
+ }
+
+ // Delete downloaded file
+ if (downloadedFile) deleteDownloadedFile(downloadedFile)
+
+ if (err) logger.warn('Cannot destroy webtorrent in timeout.', { err })
+
+ return res()
+ })
+ })
+}
+
+function deleteDownloadedFile (downloadedFile: { directoryPath: string, filepath: string }) {
+ // We want to delete the base directory
+ let pathToDelete = dirname(downloadedFile.filepath)
+ if (pathToDelete === '.') pathToDelete = downloadedFile.filepath
+
+ const toRemovePath = join(downloadedFile.directoryPath, pathToDelete)
+
+ logger.debug('Removing %s after webtorrent download.', toRemovePath)
+ remove(toRemovePath)
+ .catch(err => logger.error('Cannot remove torrent file %s in webtorrent download.', toRemovePath, { err }))
+}