webtorrent.ts 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  1. import { decode, encode } from 'bencode'
  2. import createTorrent from 'create-torrent'
  3. import { createWriteStream, ensureDir, readFile, remove, writeFile } from 'fs-extra'
  4. import magnetUtil from 'magnet-uri'
  5. import parseTorrent from 'parse-torrent'
  6. import { dirname, join } from 'path'
  7. import { pipeline } from 'stream'
  8. import WebTorrent, { Instance, TorrentFile } from 'webtorrent'
  9. import { isArray } from '@server/helpers/custom-validators/misc'
  10. import { WEBSERVER } from '@server/initializers/constants'
  11. import { generateTorrentFileName } from '@server/lib/paths'
  12. import { VideoPathManager } from '@server/lib/video-path-manager'
  13. import { MVideo } from '@server/types/models/video/video'
  14. import { MVideoFile, MVideoFileRedundanciesOpt } from '@server/types/models/video/video-file'
  15. import { MStreamingPlaylistVideo } from '@server/types/models/video/video-streaming-playlist'
  16. import { sha1 } from '@shared/extra-utils'
  17. import { CONFIG } from '../initializers/config'
  18. import { promisify2 } from './core-utils'
  19. import { logger } from './logger'
  20. import { generateVideoImportTmpPath } from './utils'
  21. import { extractVideo } from './video'
  22. const createTorrentPromise = promisify2<string, any, any>(createTorrent)
  23. async function downloadWebTorrentVideo (target: { uri: string, torrentName?: string }, timeout: number) {
  24. const id = target.uri || target.torrentName
  25. let timer
  26. const path = generateVideoImportTmpPath(id)
  27. logger.info('Importing torrent video %s', id)
  28. const directoryPath = join(CONFIG.STORAGE.TMP_DIR, 'webtorrent')
  29. await ensureDir(directoryPath)
  30. return new Promise<string>((res, rej) => {
  31. const webtorrent = new WebTorrent()
  32. let file: TorrentFile
  33. const torrentId = target.uri || join(CONFIG.STORAGE.TORRENTS_DIR, target.torrentName)
  34. const options = { path: directoryPath }
  35. const torrent = webtorrent.add(torrentId, options, torrent => {
  36. if (torrent.files.length !== 1) {
  37. if (timer) clearTimeout(timer)
  38. for (const file of torrent.files) {
  39. deleteDownloadedFile({ directoryPath, filepath: file.path })
  40. }
  41. return safeWebtorrentDestroy(webtorrent, torrentId, undefined, target.torrentName)
  42. .then(() => rej(new Error('Cannot import torrent ' + torrentId + ': there are multiple files in it')))
  43. }
  44. logger.debug('Got torrent from webtorrent %s.', id, { infoHash: torrent.infoHash })
  45. file = torrent.files[0]
  46. // FIXME: avoid creating another stream when https://github.com/webtorrent/webtorrent/issues/1517 is fixed
  47. const writeStream = createWriteStream(path)
  48. writeStream.on('finish', () => {
  49. if (timer) clearTimeout(timer)
  50. safeWebtorrentDestroy(webtorrent, torrentId, { directoryPath, filepath: file.path }, target.torrentName)
  51. .then(() => res(path))
  52. .catch(err => logger.error('Cannot destroy webtorrent.', { err }))
  53. })
  54. pipeline(
  55. file.createReadStream(),
  56. writeStream,
  57. err => {
  58. if (err) rej(err)
  59. }
  60. )
  61. })
  62. torrent.on('error', err => rej(err))
  63. timer = setTimeout(() => {
  64. const err = new Error('Webtorrent download timeout.')
  65. safeWebtorrentDestroy(webtorrent, torrentId, file ? { directoryPath, filepath: file.path } : undefined, target.torrentName)
  66. .then(() => rej(err))
  67. .catch(destroyErr => {
  68. logger.error('Cannot destroy webtorrent.', { err: destroyErr })
  69. rej(err)
  70. })
  71. }, timeout)
  72. })
  73. }
  74. function createTorrentAndSetInfoHash (videoOrPlaylist: MVideo | MStreamingPlaylistVideo, videoFile: MVideoFile) {
  75. return VideoPathManager.Instance.makeAvailableVideoFile(videoFile.withVideoOrPlaylist(videoOrPlaylist), videoPath => {
  76. return createTorrentAndSetInfoHashFromPath(videoOrPlaylist, videoFile, videoPath)
  77. })
  78. }
  79. async function createTorrentAndSetInfoHashFromPath (
  80. videoOrPlaylist: MVideo | MStreamingPlaylistVideo,
  81. videoFile: MVideoFile,
  82. filePath: string
  83. ) {
  84. const video = extractVideo(videoOrPlaylist)
  85. const options = {
  86. // Keep the extname, it's used by the client to stream the file inside a web browser
  87. name: buildInfoName(video, videoFile),
  88. createdBy: 'PeerTube',
  89. announceList: buildAnnounceList(),
  90. urlList: buildUrlList(video, videoFile)
  91. }
  92. const torrentContent = await createTorrentPromise(filePath, options)
  93. const torrentFilename = generateTorrentFileName(videoOrPlaylist, videoFile.resolution)
  94. const torrentPath = join(CONFIG.STORAGE.TORRENTS_DIR, torrentFilename)
  95. logger.info('Creating torrent %s.', torrentPath)
  96. await writeFile(torrentPath, torrentContent)
  97. // Remove old torrent file if it existed
  98. if (videoFile.hasTorrent()) {
  99. await remove(join(CONFIG.STORAGE.TORRENTS_DIR, videoFile.torrentFilename))
  100. }
  101. const parsedTorrent = parseTorrent(torrentContent)
  102. videoFile.infoHash = parsedTorrent.infoHash
  103. videoFile.torrentFilename = torrentFilename
  104. }
  105. async function updateTorrentMetadata (videoOrPlaylist: MVideo | MStreamingPlaylistVideo, videoFile: MVideoFile) {
  106. const video = extractVideo(videoOrPlaylist)
  107. const oldTorrentPath = join(CONFIG.STORAGE.TORRENTS_DIR, videoFile.torrentFilename)
  108. const torrentContent = await readFile(oldTorrentPath)
  109. const decoded = decode(torrentContent)
  110. decoded['announce-list'] = buildAnnounceList()
  111. decoded.announce = decoded['announce-list'][0][0]
  112. decoded['url-list'] = buildUrlList(video, videoFile)
  113. decoded.info.name = buildInfoName(video, videoFile)
  114. decoded['creation date'] = Math.ceil(Date.now() / 1000)
  115. const newTorrentFilename = generateTorrentFileName(videoOrPlaylist, videoFile.resolution)
  116. const newTorrentPath = join(CONFIG.STORAGE.TORRENTS_DIR, newTorrentFilename)
  117. logger.info('Updating torrent metadata %s -> %s.', oldTorrentPath, newTorrentPath)
  118. await writeFile(newTorrentPath, encode(decoded))
  119. await remove(join(CONFIG.STORAGE.TORRENTS_DIR, videoFile.torrentFilename))
  120. videoFile.torrentFilename = newTorrentFilename
  121. videoFile.infoHash = sha1(encode(decoded.info))
  122. }
  123. function generateMagnetUri (
  124. video: MVideo,
  125. videoFile: MVideoFileRedundanciesOpt,
  126. trackerUrls: string[]
  127. ) {
  128. const xs = videoFile.getTorrentUrl()
  129. const announce = trackerUrls
  130. let urlList = [ videoFile.getFileUrl(video) ]
  131. const redundancies = videoFile.RedundancyVideos
  132. if (isArray(redundancies)) urlList = urlList.concat(redundancies.map(r => r.fileUrl))
  133. const magnetHash = {
  134. xs,
  135. announce,
  136. urlList,
  137. infoHash: videoFile.infoHash,
  138. name: video.name
  139. }
  140. return magnetUtil.encode(magnetHash)
  141. }
  142. // ---------------------------------------------------------------------------
  143. export {
  144. createTorrentPromise,
  145. updateTorrentMetadata,
  146. createTorrentAndSetInfoHash,
  147. createTorrentAndSetInfoHashFromPath,
  148. generateMagnetUri,
  149. downloadWebTorrentVideo
  150. }
  151. // ---------------------------------------------------------------------------
  152. function safeWebtorrentDestroy (
  153. webtorrent: Instance,
  154. torrentId: string,
  155. downloadedFile?: { directoryPath: string, filepath: string },
  156. torrentName?: string
  157. ) {
  158. return new Promise<void>(res => {
  159. webtorrent.destroy(err => {
  160. // Delete torrent file
  161. if (torrentName) {
  162. logger.debug('Removing %s torrent after webtorrent download.', torrentId)
  163. remove(torrentId)
  164. .catch(err => logger.error('Cannot remove torrent %s in webtorrent download.', torrentId, { err }))
  165. }
  166. // Delete downloaded file
  167. if (downloadedFile) deleteDownloadedFile(downloadedFile)
  168. if (err) logger.warn('Cannot destroy webtorrent in timeout.', { err })
  169. return res()
  170. })
  171. })
  172. }
  173. function deleteDownloadedFile (downloadedFile: { directoryPath: string, filepath: string }) {
  174. // We want to delete the base directory
  175. let pathToDelete = dirname(downloadedFile.filepath)
  176. if (pathToDelete === '.') pathToDelete = downloadedFile.filepath
  177. const toRemovePath = join(downloadedFile.directoryPath, pathToDelete)
  178. logger.debug('Removing %s after webtorrent download.', toRemovePath)
  179. remove(toRemovePath)
  180. .catch(err => logger.error('Cannot remove torrent file %s in webtorrent download.', toRemovePath, { err }))
  181. }
  182. function buildAnnounceList () {
  183. return [
  184. [ WEBSERVER.WS + '://' + WEBSERVER.HOSTNAME + ':' + WEBSERVER.PORT + '/tracker/socket' ],
  185. [ WEBSERVER.URL + '/tracker/announce' ]
  186. ]
  187. }
  188. function buildUrlList (video: MVideo, videoFile: MVideoFile) {
  189. return [ videoFile.getFileUrl(video) ]
  190. }
  191. function buildInfoName (video: MVideo, videoFile: MVideoFile) {
  192. return `${video.name} ${videoFile.resolution}p${videoFile.extname}`
  193. }