ニジカ投稿局 https://tv.nizika.tv
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

webtorrent.ts 9.3 KiB

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