Guest User

Untitled

a guest
Jun 23rd, 2018
118
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.12 KB | None | 0 0
  1. import Command
  2. import Console
  3. import Crypto
  4. import Fluent
  5. import FluentSQLite
  6.  
  7. struct DownloadVideosCommand: Command, Service {
  8. var arguments: [CommandArgument] { return [] }
  9. var options: [CommandOption] { return [] }
  10. var help: [String] { return [] }
  11.  
  12. func run(using ctx: CommandContext) throws -> Future<Void> {
  13. return ctx.container.withPooledConnection(to: .sqlite) { db in
  14. return Video
  15. .query(on: db)
  16. .group(.or) { or in
  17. // 0 = not processed
  18. or.filter(\Video.status == 0)
  19. // 1 = processing attempted but failed
  20. or.filter(\Video.status == 1)
  21. }
  22. .all()
  23. .flatMap { videos in
  24. let downloadTasks = videos.map { video in
  25. return Process.asyncExecute(
  26. "youtube-dl",
  27. ["-x", "--audio-format", "mp3", video.url],
  28. on: ctx.container) { output in
  29. switch output {
  30. case .stdout(let data), .stderr(let data):
  31. if let string = String(data: data, encoding: .utf8) {
  32. print(string)
  33. }
  34. }
  35. }.flatMap { returnCode -> Future<Video> in
  36. switch returnCode {
  37. case 0:
  38. // 2 = success, never process again
  39. video.status = 2
  40. default:
  41. // 1 = processing attempted but failed
  42. video.status = 1
  43. }
  44.  
  45. return video.save(on: db)
  46. }
  47. }
  48.  
  49. return downloadTasks
  50. .flatten(on: ctx.container)
  51. .transform(to: ())
  52. }
  53. }
  54. }
  55. }
Add Comment
Please, Sign In to add comment