1 import { pathExists, stat, writeFile } from 'fs-extra'
2 import parseTorrent from 'parse-torrent'
3 import { join } from 'path'
4 import * as Sequelize from 'sequelize'
5 import { logger } from '@server/helpers/logger'
6 import { createTorrentPromise } from '@server/helpers/webtorrent'
7 import { CONFIG } from '@server/initializers/config'
8 import { HLS_STREAMING_PLAYLIST_DIRECTORY, STATIC_PATHS, WEBSERVER } from '@server/initializers/constants'
9 import { initDatabaseModels, sequelizeTypescript } from '../../server/initializers/database'
12 .then(() => process.exit(0))
18 async function run () {
19 logger.info('Creating torrents and updating database for HSL files.')
21 await initDatabaseModels(true)
23 const query = 'select "videoFile".id as id, "videoFile".resolution as resolution, "video".uuid as uuid from "videoFile" ' +
24 'inner join "videoStreamingPlaylist" ON "videoStreamingPlaylist".id = "videoFile"."videoStreamingPlaylistId" ' +
25 'inner join video ON video.id = "videoStreamingPlaylist"."videoId" ' +
26 'WHERE video.remote IS FALSE'
28 type: Sequelize.QueryTypes.SELECT
30 const res = await sequelizeTypescript.query(query, options)
32 for (const row of res) {
33 const videoFilename = `${row['uuid']}-${row['resolution']}-fragmented.mp4`
34 const videoFilePath = join(HLS_STREAMING_PLAYLIST_DIRECTORY, row['uuid'], videoFilename)
36 logger.info('Processing %s.', videoFilePath)
38 if (!await pathExists(videoFilePath)) {
39 console.warn('Cannot generate torrent of %s: file does not exist.', videoFilePath)
43 const createTorrentOptions = {
44 // Keep the extname, it's used by the client to stream the file inside a web browser
45 name: `video ${row['uuid']}`,
46 createdBy: 'PeerTube',
48 [ WEBSERVER.WS + '://' + WEBSERVER.HOSTNAME + ':' + WEBSERVER.PORT + '/tracker/socket' ],
49 [ WEBSERVER.URL + '/tracker/announce' ]
51 urlList: [ WEBSERVER.URL + join(STATIC_PATHS.STREAMING_PLAYLISTS.HLS, row['uuid'], videoFilename) ]
53 const torrent = await createTorrentPromise(videoFilePath, createTorrentOptions)
55 const torrentName = `${row['uuid']}-${row['resolution']}-hls.torrent`
56 const filePath = join(CONFIG.STORAGE.TORRENTS_DIR, torrentName)
58 await writeFile(filePath, torrent)
60 const parsedTorrent = parseTorrent(torrent)
61 const infoHash = parsedTorrent.infoHash
63 const stats = await stat(videoFilePath)
64 const size = stats.size
66 const queryUpdate = 'UPDATE "videoFile" SET "infoHash" = ?, "size" = ? WHERE id = ?'
69 type: Sequelize.QueryTypes.UPDATE,
70 replacements: [ infoHash, size, row['id'] ]
72 await sequelizeTypescript.query(queryUpdate, options)