serveur de hook HTTP
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

restore 2.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. #!/usr/bin/env node
  2. var fs = require('fs');
  3. var path = require('path');
  4. var http = require('http');
  5. var config = require('../lib/config');
  6. var backupFile = process.env.MARANG_BACKUP_FILE;
  7. if (!backupFile) {
  8. console.error('You must provide the path of a backup file via the "MARANG_BACKUP_FILE" environment variable.');
  9. process.exit(1);
  10. }
  11. if (!fs.existsSync(backupFile)) {
  12. console.error('Backup file "%s" does not exist.', backupFile);
  13. process.exit(1);
  14. }
  15. var fileContent = fs.readFileSync(backupFile, 'utf8');
  16. var backup;
  17. try {
  18. backup = JSON.parse(fileContent);
  19. } catch(err) {
  20. console.error('The backup "%s" is not a valid JSON file.', backupFile);
  21. process.exit(1);
  22. }
  23. console.log("Restoring slots...")
  24. Object.keys(backup.slots).forEach(slotKey => {
  25. var slot = backup.slots[slotKey];
  26. postAPI('/api/slots/'+slotKey, slot, err => {
  27. if (err) {
  28. console.error(err.message);
  29. process.exit(1);
  30. }
  31. console.log("Restored slot '%s'.", slotKey);
  32. });
  33. });
  34. function postAPI(path, data, cb) {
  35. var postData
  36. try {
  37. postData = JSON.stringify(data);
  38. } catch(err) {
  39. return cb(err);
  40. }
  41. var credentials = config.webApp.credentials.username +
  42. ':' +
  43. process.env.MARANG_PASSWORD
  44. ;
  45. var opts = {
  46. host: config.webApp.host,
  47. port: config.webApp.port,
  48. path: path,
  49. auth: credentials,
  50. headers: {
  51. "Content-Type": "application/json",
  52. "Content-Length": Buffer.byteLength(postData)
  53. },
  54. method: "POST"
  55. }
  56. var req = http.request(opts, res => {
  57. if(res.statusCode < 200 || res.statusCode >= 400) {
  58. return cb(new Error('Unexpected HTTP response: ' + res.statusCode + ' ' + res.statusMessage));
  59. }
  60. res.setEncoding('utf8');
  61. var data = '';
  62. res.on('data', chunk => {
  63. data += chunk;
  64. });
  65. res.once('end', () => {
  66. var json;
  67. try {
  68. json = JSON.parse(data);
  69. } catch(err) {
  70. return cb(err);
  71. }
  72. cb(null, json);
  73. });
  74. res.once('error', (err) => {
  75. res.removeAllListeners();
  76. cb(err);
  77. });
  78. });
  79. req.write(postData);
  80. req.end();
  81. }