Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

146 řádky
4.5KB

  1. import os
  2. import re
  3. import time
  4. import datetime
  5. from flask import json, request, send_from_directory
  6. from flask_classy import route, FlaskView
  7. from modules.core.db import DBModel
  8. from modules.core.baseview import BaseView
  9. from modules.core.core import cbpi
  10. from modules.database.dbmodel import Step
  11. from yaml import Loader, Dumper
  12. from yaml import load, dump
  13. from modules.step import StepView
  14. class RecipeBook(FlaskView):
  15. @route('/load', methods=["POST"])
  16. def load(self):
  17. data = request.json
  18. recipe_name = data.get("name")
  19. if re.match("^[A-Za-z0-9_-]*$", recipe_name) is None:
  20. return ('Recipie Name contains not allowed characters', 500)
  21. with open("./recipes/%s.json" % recipe_name) as json_data:
  22. d = json.load(json_data)
  23. Step.delete_all()
  24. StepView().reset()
  25. for s in d["steps"]:
  26. Step.insert(**{"name": s.get("name"), "type": s.get("type"), "config": s.get("config")})
  27. self.api.ws_emit("UPDATE_ALL_STEPS", Step.get_all())
  28. self.api.notify(headline="Recipe %s loaded successfully" % recipe_name, message="")
  29. return ('', 204)
  30. @route('/download/<name>', methods=["GET"])
  31. def download(self, name):
  32. """
  33. Download a log file by name
  34. ---
  35. tags:
  36. - logs
  37. parameters:
  38. - in: path
  39. name: file
  40. schema:
  41. type: string
  42. required: true
  43. description: filename
  44. responses:
  45. 200:
  46. description: Log file downloaded
  47. """
  48. file = "%s.json" % name
  49. print file
  50. if not self.check_filename(file):
  51. return ('File Not Found111', 404)
  52. return send_from_directory('../../recipes', file, as_attachment=True, attachment_filename=file)
  53. def check_filename(self, name):
  54. import re
  55. print "CHECK"
  56. pattern = re.compile('^([A-Za-z0-9-_])+.json$')
  57. return True if pattern.match(name) else False
  58. @route('/<name>', methods=["DELETE"])
  59. def remove(self, name):
  60. recipe_name = name
  61. if re.match("^[A-Za-z0-9_-]*$", recipe_name) is None:
  62. return ('Recipie Name contains not allowed characters', 500)
  63. filename = "./recipes/%s.json" % recipe_name
  64. if os.path.isfile(filename) == True:
  65. os.remove(filename)
  66. self.api.notify(headline="Recipe %s deleted successfully" % recipe_name, message="")
  67. return ('', 204)
  68. else:
  69. self.api.notify(headline="Faild to delete Recipe %s deleted" % recipe_name, message="")
  70. return ('', 404)
  71. return ('', 204)
  72. @route('/', methods=["GET"])
  73. def get_all(self):
  74. result = []
  75. for filename in os.listdir("./recipes"):
  76. if filename.endswith(".json"):
  77. result.append({"id":filename.split(".")[0], "name": filename.split(".")[0], "change_date": self._modification_date('./recipes/%s' % filename)})
  78. return json.dumps(result)
  79. def _modification_date(self, filename):
  80. t = os.path.getmtime(filename)
  81. return datetime.datetime.fromtimestamp(t).strftime('%Y-%m-%d %H:%M:%S')
  82. @route('/save', methods=["POST"])
  83. def save(self):
  84. """
  85. Save Recepie
  86. ---
  87. tags:
  88. - steps
  89. responses:
  90. 204:
  91. description: Recipe saved
  92. """
  93. recipe_name = self.api.get_config_parameter("brew_name")
  94. if recipe_name is None or len(recipe_name) <= 0:
  95. self.api.notify(headline="Please set brew name", message="Recipe not saved!", type="danger")
  96. return ('Recipie Name contains not allowed characters', 500)
  97. if re.match("^[\sA-Za-z0-9_-]*$", recipe_name) is None:
  98. self.api.notify(headline="Only alphanummeric charaters are allowd for recipe name", message="", type="danger")
  99. return ('Recipie Name contains not allowed characters', 500)
  100. recipe_data = {"name": recipe_name, "steps": Step.get_all()}
  101. file_name = recipe_name.replace(" ", "_")
  102. with open('./recipes/%s.json' % file_name, 'w') as outfile:
  103. json.dump(recipe_data, outfile, indent=4)
  104. self.api.notify(headline="Recipe %s saved successfully" % recipe_name, message="")
  105. return ('', 204)
  106. @cbpi.addon.core.initializer(order=2000)
  107. def init(cbpi):
  108. RecipeBook.api = cbpi
  109. RecipeBook.register(cbpi._app, route_base='/api/recipebook')