webtorrent.ts 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171
  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/typings/models/video/video'
  10. import { MVideoFile, MVideoFileRedundanciesOpt } from '@server/typings/models/video/video-file'
  11. import { isStreamingPlaylist, MStreamingPlaylistVideo } from '@server/typings/models/video/video-streaming-playlist'
  12. import { STATIC_PATHS, 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 { extractVideo } from '@server/lib/videos'
  17. import { getTorrentFileName, getVideoFilename, getVideoFilePath } from '@server/lib/video-paths'
  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 (let 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. return safeWebtorrentDestroy(webtorrent, torrentId, { directoryPath, filepath: file.path }, target.torrentName)
  46. .then(() => res(path))
  47. })
  48. file.createReadStream().pipe(writeStream)
  49. })
  50. torrent.on('error', err => rej(err))
  51. timer = setTimeout(async () => {
  52. return safeWebtorrentDestroy(webtorrent, torrentId, file ? { directoryPath, filepath: file.path } : undefined, target.torrentName)
  53. .then(() => rej(new Error('Webtorrent download timeout.')))
  54. }, timeout)
  55. })
  56. }
  57. async function createTorrentAndSetInfoHash (videoOrPlaylist: MVideo | MStreamingPlaylistVideo, videoFile: MVideoFile) {
  58. const video = extractVideo(videoOrPlaylist)
  59. const options = {
  60. // Keep the extname, it's used by the client to stream the file inside a web browser
  61. name: `${video.name} ${videoFile.resolution}p${videoFile.extname}`,
  62. createdBy: 'PeerTube',
  63. announceList: [
  64. [ WEBSERVER.WS + '://' + WEBSERVER.HOSTNAME + ':' + WEBSERVER.PORT + '/tracker/socket' ],
  65. [ WEBSERVER.URL + '/tracker/announce' ]
  66. ],
  67. urlList: [ WEBSERVER.URL + STATIC_PATHS.WEBSEED + getVideoFilename(videoOrPlaylist, videoFile) ]
  68. }
  69. const torrent = await createTorrentPromise(getVideoFilePath(videoOrPlaylist, videoFile), options)
  70. const filePath = join(CONFIG.STORAGE.TORRENTS_DIR, getTorrentFileName(videoOrPlaylist, videoFile))
  71. logger.info('Creating torrent %s.', filePath)
  72. await writeFile(filePath, torrent)
  73. const parsedTorrent = parseTorrent(torrent)
  74. videoFile.infoHash = parsedTorrent.infoHash
  75. }
  76. function generateMagnetUri (
  77. videoOrPlaylist: MVideo | MStreamingPlaylistVideo,
  78. videoFile: MVideoFileRedundanciesOpt,
  79. baseUrlHttp: string,
  80. baseUrlWs: string
  81. ) {
  82. const video = isStreamingPlaylist(videoOrPlaylist)
  83. ? videoOrPlaylist.Video
  84. : videoOrPlaylist
  85. const xs = videoOrPlaylist.getTorrentUrl(videoFile, baseUrlHttp)
  86. const announce = videoOrPlaylist.getTrackerUrls(baseUrlHttp, baseUrlWs)
  87. let urlList = [ videoOrPlaylist.getVideoFileUrl(videoFile, baseUrlHttp) ]
  88. const redundancies = videoFile.RedundancyVideos
  89. if (isArray(redundancies)) urlList = urlList.concat(redundancies.map(r => r.fileUrl))
  90. const magnetHash = {
  91. xs,
  92. announce,
  93. urlList,
  94. infoHash: videoFile.infoHash,
  95. name: video.name
  96. }
  97. return magnetUtil.encode(magnetHash)
  98. }
  99. // ---------------------------------------------------------------------------
  100. export {
  101. createTorrentAndSetInfoHash,
  102. generateMagnetUri,
  103. downloadWebTorrentVideo
  104. }
  105. // ---------------------------------------------------------------------------
  106. function safeWebtorrentDestroy (
  107. webtorrent: WebTorrent.Instance,
  108. torrentId: string,
  109. downloadedFile?: { directoryPath: string, filepath: string },
  110. torrentName?: string
  111. ) {
  112. return new Promise(res => {
  113. webtorrent.destroy(err => {
  114. // Delete torrent file
  115. if (torrentName) {
  116. logger.debug('Removing %s torrent after webtorrent download.', torrentId)
  117. remove(torrentId)
  118. .catch(err => logger.error('Cannot remove torrent %s in webtorrent download.', torrentId, { err }))
  119. }
  120. // Delete downloaded file
  121. if (downloadedFile) deleteDownloadedFile(downloadedFile)
  122. if (err) logger.warn('Cannot destroy webtorrent in timeout.', { err })
  123. return res()
  124. })
  125. })
  126. }
  127. function deleteDownloadedFile (downloadedFile: { directoryPath: string, filepath: string }) {
  128. // We want to delete the base directory
  129. let pathToDelete = dirname(downloadedFile.filepath)
  130. if (pathToDelete === '.') pathToDelete = downloadedFile.filepath
  131. const toRemovePath = join(downloadedFile.directoryPath, pathToDelete)
  132. logger.debug('Removing %s after webtorrent download.', toRemovePath)
  133. remove(toRemovePath)
  134. .catch(err => logger.error('Cannot remove torrent file %s in webtorrent download.', toRemovePath, { err }))
  135. }