Skip to content

Instantly share code, notes, and snippets.

@Cellane
Last active June 22, 2018 06:10
Show Gist options
  • Save Cellane/68583196df7085390b78565793c4573e to your computer and use it in GitHub Desktop.
Save Cellane/68583196df7085390b78565793c4573e to your computer and use it in GitHub Desktop.
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: ())
}
}
}
}
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
or.filter(\Video.status == 0)
or.filter(\Video.status == 1)
}
.all()
.flatMap { videos in
let downloadTasks: [LazyFuture<Void>] = videos.map { video in
return {
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:
video.status = 2
default:
video.status = 1
}
return video.save(on: db)
}.transform(to: ())
}
}
return downloadTasks
.syncFlatten(on: ctx.container)
.transform(to: ())
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment