webtorrent.ts 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181
  1. import { logger } from './logger'
  2. import { generateVideoImportTmpPath } from './utils'
  3. import * as WebTorrent from 'webtorrent'
  4. import { createWriteStream, ensureDir, remove, writeFile } from 'fs-extra'
  5. import { CONFIG } from '../initializers/config'
  6. import { dirname, join } from 'path'
  7. import * as createTorrent from 'create-torrent'
  8. import { promisify2 } from './core-utils'
  9. import { MVideo } from '@server/types/models/video/video'
  10. import { MVideoFile, MVideoFileRedundanciesOpt } from '@server/types/models/video/video-file'
  11. import { isStreamingPlaylist, MStreamingPlaylistVideo } from '@server/types/models/video/video-streaming-playlist'
  12. import { WEBSERVER } from '@server/initializers/constants'
  13. import * as parseTorrent from 'parse-torrent'
  14. import * as magnetUtil from 'magnet-uri'
  15. import { isArray } from '@server/helpers/custom-validators/misc'
  16. import { getTorrentFileName, getVideoFilePath } from '@server/lib/video-paths'
  17. import { extractVideo } from '@server/helpers/video'
  18. const createTorrentPromise = promisify2<string, any, any>(createTorrent)
  19. async function downloadWebTorrentVideo (target: { magnetUri: string, torrentName?: string }, timeout: number) {
  20. const id = target.magnetUri || target.torrentName
  21. let timer
  22. const path = generateVideoImportTmpPath(id)
  23. logger.info('Importing torrent video %s', id)
  24. const directoryPath = join(CONFIG.STORAGE.TMP_DIR, 'webtorrent')
  25. await ensureDir(directoryPath)
  26. return new Promise<string>((res, rej) => {
  27. const webtorrent = new WebTorrent()
  28. let file: WebTorrent.TorrentFile
  29. const torrentId = target.magnetUri || join(CONFIG.STORAGE.TORRENTS_DIR, target.torrentName)
  30. const options = { path: directoryPath }
  31. const torrent = webtorrent.add(torrentId, options, torrent => {
  32. if (torrent.files.length !== 1) {
  33. if (timer) clearTimeout(timer)
  34. for (const file of torrent.files) {
  35. deleteDownloadedFile({ directoryPath, filepath: file.path })
  36. }
  37. return safeWebtorrentDestroy(webtorrent, torrentId, undefined, target.torrentName)
  38. .then(() => rej(new Error('Cannot import torrent ' + torrentId + ': there are multiple files in it')))
  39. }
  40. file = torrent.files[0]
  41. // FIXME: avoid creating another stream when https://github.com/webtorrent/webtorrent/issues/1517 is fixed
  42. const writeStream = createWriteStream(path)
  43. writeStream.on('finish', () => {
  44. if (timer) clearTimeout(timer)
  45. safeWebtorrentDestroy(webtorrent, torrentId, { directoryPath, filepath: file.path }, target.torrentName)
  46. .then(() => res(path))
  47. .catch(err => logger.error('Cannot destroy webtorrent.', { err }))
  48. })
  49. file.createReadStream().pipe(writeStream)
  50. })
  51. torrent.on('error', err => rej(err))
  52. timer = setTimeout(() => {
  53. const err = new Error('Webtorrent download timeout.')
  54. safeWebtorrentDestroy(webtorrent, torrentId, file ? { directoryPath, filepath: file.path } : undefined, target.torrentName)
  55. .then(() => rej(err))
  56. .catch(destroyErr => {
  57. logger.error('Cannot destroy webtorrent.', { err: destroyErr })
  58. rej(err)
  59. })
  60. }, timeout)
  61. })
  62. }
  63. async function createTorrentAndSetInfoHash (videoOrPlaylist: MVideo | MStreamingPlaylistVideo, videoFile: MVideoFile) {
  64. const video = extractVideo(videoOrPlaylist)
  65. const { baseUrlHttp } = video.getBaseUrls()
  66. const options = {
  67. // Keep the extname, it's used by the client to stream the file inside a web browser
  68. name: `${video.name} ${videoFile.resolution}p${videoFile.extname}`,
  69. createdBy: 'PeerTube',
  70. announceList: [
  71. [ WEBSERVER.WS + '://' + WEBSERVER.HOSTNAME + ':' + WEBSERVER.PORT + '/tracker/socket' ],
  72. [ WEBSERVER.URL + '/tracker/announce' ]
  73. ],
  74. urlList: [ videoOrPlaylist.getVideoFileUrl(videoFile, baseUrlHttp) ]
  75. }
  76. const torrent = await createTorrentPromise(getVideoFilePath(videoOrPlaylist, videoFile), options)
  77. const filePath = join(CONFIG.STORAGE.TORRENTS_DIR, getTorrentFileName(videoOrPlaylist, videoFile))
  78. logger.info('Creating torrent %s.', filePath)
  79. await writeFile(filePath, torrent)
  80. const parsedTorrent = parseTorrent(torrent)
  81. videoFile.infoHash = parsedTorrent.infoHash
  82. }
  83. function generateMagnetUri (
  84. videoOrPlaylist: MVideo | MStreamingPlaylistVideo,
  85. videoFile: MVideoFileRedundanciesOpt,
  86. baseUrlHttp: string,
  87. baseUrlWs: string
  88. ) {
  89. const video = isStreamingPlaylist(videoOrPlaylist)
  90. ? videoOrPlaylist.Video
  91. : videoOrPlaylist
  92. const xs = videoOrPlaylist.getTorrentUrl(videoFile, baseUrlHttp)
  93. const announce = videoOrPlaylist.getTrackerUrls(baseUrlHttp, baseUrlWs)
  94. let urlList = [ videoOrPlaylist.getVideoFileUrl(videoFile, baseUrlHttp) ]
  95. const redundancies = videoFile.RedundancyVideos
  96. if (isArray(redundancies)) urlList = urlList.concat(redundancies.map(r => r.fileUrl))
  97. const magnetHash = {
  98. xs,
  99. announce,
  100. urlList,
  101. infoHash: videoFile.infoHash,
  102. name: video.name
  103. }
  104. return magnetUtil.encode(magnetHash)
  105. }
  106. // ---------------------------------------------------------------------------
  107. export {
  108. createTorrentPromise,
  109. createTorrentAndSetInfoHash,
  110. generateMagnetUri,
  111. downloadWebTorrentVideo
  112. }
  113. // ---------------------------------------------------------------------------
  114. function safeWebtorrentDestroy (
  115. webtorrent: WebTorrent.Instance,
  116. torrentId: string,
  117. downloadedFile?: { directoryPath: string, filepath: string },
  118. torrentName?: string
  119. ) {
  120. return new Promise(res => {
  121. webtorrent.destroy(err => {
  122. // Delete torrent file
  123. if (torrentName) {
  124. logger.debug('Removing %s torrent after webtorrent download.', torrentId)
  125. remove(torrentId)
  126. .catch(err => logger.error('Cannot remove torrent %s in webtorrent download.', torrentId, { err }))
  127. }
  128. // Delete downloaded file
  129. if (downloadedFile) deleteDownloadedFile(downloadedFile)
  130. if (err) logger.warn('Cannot destroy webtorrent in timeout.', { err })
  131. return res()
  132. })
  133. })
  134. }
  135. function deleteDownloadedFile (downloadedFile: { directoryPath: string, filepath: string }) {
  136. // We want to delete the base directory
  137. let pathToDelete = dirname(downloadedFile.filepath)
  138. if (pathToDelete === '.') pathToDelete = downloadedFile.filepath
  139. const toRemovePath = join(downloadedFile.directoryPath, pathToDelete)
  140. logger.debug('Removing %s after webtorrent download.', toRemovePath)
  141. remove(toRemovePath)
  142. .catch(err => logger.error('Cannot remove torrent file %s in webtorrent download.', toRemovePath, { err }))
  143. }