Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import Command
- import Console
- import Crypto
- import Fluent
- import FluentSQLite
- struct DownloadVideosCommand: Command, Service {
- var arguments: [CommandArgument] { return [] }
- var options: [CommandOption] { return [] }
- var help: [String] { return [] }
- func run(using ctx: CommandContext) throws -> Future<Void> {
- return ctx.container.withPooledConnection(to: .sqlite) { db in
- return Video
- .query(on: db)
- .group(.or) { or in
- // 0 = not processed
- or.filter(\Video.status == 0)
- // 1 = processing attempted but failed
- or.filter(\Video.status == 1)
- }
- .all()
- .flatMap { videos in
- let downloadTasks = videos.map { video in
- return Process.asyncExecute(
- "youtube-dl",
- ["-x", "--audio-format", "mp3", video.url],
- on: ctx.container) { output in
- switch output {
- case .stdout(let data), .stderr(let data):
- if let string = String(data: data, encoding: .utf8) {
- print(string)
- }
- }
- }.flatMap { returnCode -> Future<Video> in
- switch returnCode {
- case 0:
- // 2 = success, never process again
- video.status = 2
- default:
- // 1 = processing attempted but failed
- video.status = 1
- }
- return video.save(on: db)
- }
- }
- return downloadTasks
- .flatten(on: ctx.container)
- .transform(to: ())
- }
- }
- }
- }
Add Comment
Please, Sign In to add comment