Downloader.qml 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. import QtQuick 2.0
  2. import Process 1.0
  3. import FileIO 1.0
  4. Item {
  5. id: downloader
  6. // in
  7. property string downloadDir
  8. property bool multiConnections: false
  9. property bool limitDownload: false
  10. property string limitDownloadValue: "1M"
  11. // out
  12. readonly property alias isRunning: process.isRunning
  13. property var progress
  14. property bool canceled: false
  15. property string archiveCompletedPath
  16. signal finished()
  17. signal error(string errors)
  18. Process {
  19. id: process
  20. property string errors: ""
  21. onFinished: {
  22. console.log("Download exit code: " + code)
  23. if (code === 0) {
  24. FileIO.writeTextFile(archiveCompletedPath, "")
  25. downloader.finished()
  26. } else {
  27. downloader.error(errors)
  28. }
  29. }
  30. onOutputRead: {
  31. let lines = output.split("\n")
  32. for (let line of lines) {
  33. // "[#6b754a 249MiB/5.4GiB(4%) CN:1 DL:6.4MiB ETA:13m46s]\n"
  34. let groups = line.match(/\s([^\/]+)\/([^\/]+)\((\d+)%?\).*DL:([^\s]+).*ETA:([^\s\]]+)/)
  35. // 0: " 249MiB/5.4GiB(4%) CN:1 DL:6.4MiB ETA:13m46s"
  36. // 1: "249MiB"
  37. // 2: "5.4GiB"
  38. // 3: "4%"
  39. // 4: "6.4MiB"
  40. // 5: "13m46s"
  41. if (groups) {
  42. progress = {
  43. downloaded: groups[1],
  44. total: groups[2],
  45. percent: Number(groups[3]),
  46. speed: groups[4],
  47. estimated: groups[5]
  48. }
  49. }
  50. if (line.match(/ERROR/i)) {
  51. errors += "\n" + line
  52. }
  53. }
  54. }
  55. }
  56. function download(url, fileName, md5) {
  57. canceled = false
  58. let filePath = downloadDir + fileName
  59. archiveCompletedPath = filePath + ".completed"
  60. process.errors = ""
  61. if (FileIO.isFileExists(archiveCompletedPath)) {
  62. // patch archive was already downloaded but something went wrong when applying it
  63. ui.log(fileName + " " + qsTr("is already downloaded"))
  64. finished()
  65. return
  66. } else {
  67. ui.log(qsTr("Starting downloading: ") + fileName)
  68. FileIO.createDirectory(downloadDir)
  69. process.workingDirectory = downloadDir
  70. var args = ["-oL", "aria2c", "-c", url, "--enable-color=false", `--dir=${downloadDir}`, `--out=${fileName}`]
  71. if (md5) {
  72. args.push(`--checksum=md5=${md5}`)
  73. }
  74. if (multiConnections) {
  75. args.push("-x4")
  76. }
  77. if (limitDownload) {
  78. args.push("--max-download-limit=" + limitDownloadValue)
  79. }
  80. process.start("stdbuf", args)
  81. }
  82. progress = {
  83. downloaded: "",
  84. total: "",
  85. percent: 0,
  86. speed: "",
  87. estimated: ""
  88. }
  89. }
  90. function cancel() {
  91. canceled = true
  92. process.terminate()
  93. }
  94. }