RemoteWebDavStorage.js 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. const fs = require('fs-extra');
  2. const path = require('path');
  3. const { createClient } = require('webdav');
  4. class RemoteWebDavStorage {
  5. constructor(config) {
  6. this.config = Object.assign({}, config);
  7. this.config.maxContentLength = this.config.maxContentLength || 10*1024*1024;
  8. this.config.maxBodyLength = this.config.maxContentLength;
  9. this.wdc = createClient(config.url, this.config);
  10. }
  11. _convertStat(data) {
  12. return {
  13. isDirectory: function() {
  14. return data.type === "directory";
  15. },
  16. isFile: function() {
  17. return data.type === "file";
  18. },
  19. mtime: (new Date(data.lastmod)).getTime(),
  20. name: data.basename,
  21. size: data.size || 0
  22. };
  23. }
  24. async stat(filename) {
  25. const stat = await this.wdc.stat(filename);
  26. return this._convertStat(stat);
  27. }
  28. async writeFile(filename, data) {
  29. return await this.wdc.putFileContents(filename, data)
  30. }
  31. async unlink(filename) {
  32. return await this.wdc.deleteFile(filename);
  33. }
  34. async readFile(filename) {
  35. return await this.wdc.getFileContents(filename)
  36. }
  37. async mkdir(dirname) {
  38. return await this.wdc.createDirectory(dirname);
  39. }
  40. async putFile(filename) {
  41. if (!await fs.pathExists(filename)) {
  42. throw new Error(`File not found: ${filename}`);
  43. }
  44. const base = path.basename(filename);
  45. let remoteFilename = `/${base}`;
  46. if (base.length > 3) {
  47. const remoteDir = `/${base.substr(0, 3)}`;
  48. try {
  49. await this.mkdir(remoteDir);
  50. } catch (e) {
  51. //
  52. }
  53. remoteFilename = `${remoteDir}/${base}`;
  54. }
  55. try {
  56. const localStat = await fs.stat(filename);
  57. const remoteStat = await this.stat(remoteFilename);
  58. if (remoteStat.isFile && localStat.size == remoteStat.size) {
  59. return;
  60. }
  61. await this.unlink(remoteFilename);
  62. } catch (e) {
  63. //
  64. }
  65. const data = await fs.readFile(filename);
  66. await this.writeFile(remoteFilename, data);
  67. }
  68. async getFile(filename) {
  69. if (await fs.pathExists(filename)) {
  70. return;
  71. }
  72. const base = path.basename(filename);
  73. let remoteFilename = `/${base}`;
  74. if (base.length > 3) {
  75. remoteFilename = `/${base.substr(0, 3)}/${base}`;
  76. }
  77. const data = await this.readFile(remoteFilename);
  78. await fs.writeFile(filename, data);
  79. }
  80. async getFileSuccess(filename) {
  81. try {
  82. await this.getFile(filename);
  83. return true;
  84. } catch (e) {
  85. //
  86. }
  87. return false;
  88. }
  89. }
  90. module.exports = RemoteWebDavStorage;