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