file_io.py 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163
  1. import os
  2. from pathlib import Path
  3. from flask import Blueprint, Response, request
  4. from flask_cors import CORS
  5. from datetime import datetime
  6. import json
  7. import hashlib
  8. import time
  9. from webservice.auth import Auth
  10. from webservice.planner_load import PlannerLoad
  11. from webservice.config_load import ConfigLoad
  12. bp = Blueprint('file_io', __name__)
  13. # cors = CORS(app, resources={r"/*": {"origins": "http://localhost:4200/"}})
  14. CORS(bp)
  15. script_dir = Path(__file__).parent
  16. save_dir = script_dir.parent.joinpath('save')
  17. planner_dir = script_dir.parent.joinpath('export')
  18. config_dir = script_dir.parent.joinpath('config')
  19. # save_dir = Path('C:\\Projekte\\Python\\Planung\\save')
  20. user_info = None
  21. @bp.route('/login/', methods=['POST'])
  22. def login():
  23. user = request.get_json()['data']['user']
  24. password = request.get_json()['data']['password']
  25. user_info = Auth().get_user(user, password)
  26. return Response(
  27. response=json.dumps(user_info),
  28. mimetype='application/json'
  29. )
  30. @bp.route('/list', methods=['GET'])
  31. def list_json():
  32. return json.dumps(list_dict(), indent=2)
  33. def list_dict():
  34. result = {'list': [], 'tree': {}}
  35. for currentFile in save_dir.iterdir():
  36. if currentFile.is_file() and currentFile.name[-5:] == '.json':
  37. year, version, timestamp = currentFile.name[:-5].split("_")
  38. if year not in result['tree']:
  39. result['tree'][year] = {}
  40. if version not in result['tree'][year]:
  41. result['tree'][year][version] = []
  42. result['tree'][year][version].append(timestamp)
  43. result['list'].append({'year': year, 'version': version, 'timestamp': timestamp})
  44. result['list'].sort(key=lambda x: x['timestamp'])
  45. return result
  46. @bp.route('/load/<year>/<version>/<timestamp>', methods=['GET'])
  47. def load(year, version, timestamp):
  48. file = full_filename(year, version, timestamp)
  49. if timestamp == 'new':
  50. return Response(
  51. response=new_file(year),
  52. mimetype='application/json'
  53. )
  54. if timestamp == 'current' or not Path(file).exists():
  55. file_list = list_dict()
  56. timestamp = file_list['tree'][year][version][-1]
  57. file = full_filename(year, version, timestamp)
  58. print(file)
  59. time.sleep(2)
  60. with open(file, 'r') as frh:
  61. structure = json.loads(frh.read())
  62. if 'options' not in structure[0]:
  63. p_load = PlannerLoad(planner_dir)
  64. structure = p_load.convert_file(structure)
  65. return Response(
  66. response=json.dumps(structure),
  67. mimetype='application/json'
  68. )
  69. def full_filename(year, version, timestamp):
  70. return f'{str(save_dir)}/{year}_{version}_{timestamp}.json'
  71. @bp.route('/new/<year>', methods=['GET'])
  72. def new_file(year):
  73. p_load = PlannerLoad(planner_dir)
  74. structure = p_load.new_file(year)
  75. return json.dumps(structure)
  76. @bp.route('/load/<filename>', methods=['GET'])
  77. def load_file(filename):
  78. full_filename = f'{str(save_dir)}/{filename}.json'
  79. if not Path(full_filename).exists():
  80. file_list = list_dict()
  81. timestamp = file_list[filename][-1]
  82. full_filename = f'{full_filename[:-5]}_{timestamp}.json'
  83. print(full_filename)
  84. with open(full_filename, 'r') as frh:
  85. return frh.read()
  86. @bp.route('/save/<year>/<version>', methods=['POST'])
  87. def save_version(year, version):
  88. return save(year + '_' + version)
  89. @bp.route('/save/<filename>', methods=['POST'])
  90. def save(filename):
  91. if request.method != 'POST':
  92. return 'File is missing!'
  93. new_filename = str(save_dir) + '/' + filename + '_' + datetime.now().strftime('%Y%m%d%H%M%S') + '.json'
  94. data = request.get_json()['data']
  95. with open(new_filename, 'w') as fwh:
  96. json.dump(data, fwh, indent=2)
  97. print(new_filename)
  98. try:
  99. file_list = list_dict()
  100. timestamp = file_list[filename][-2]
  101. old_filename = str(save_dir) + '/' + filename + "_" + timestamp + '.json'
  102. if old_filename != new_filename and hash(old_filename) == hash(new_filename):
  103. Path(old_filename).unlink()
  104. return 'File saved with no changes!'
  105. except KeyError:
  106. pass
  107. return 'File saved with new data!'
  108. @bp.route('/config', methods=['GET'])
  109. def config():
  110. cfg = ConfigLoad(str(config_dir))
  111. return Response(
  112. response=json.dumps(cfg.load_file('reisacher', '2023')),
  113. mimetype='application/json'
  114. )
  115. @bp.route('/accounts/<period>', methods=['GET'])
  116. def accounts(period):
  117. with open(planner_dir.joinpath(f'accounts_{period}.json'), 'r') as frh:
  118. return frh.read()
  119. def hash(filename):
  120. BUF_SIZE = 65536
  121. sha1 = hashlib.sha1()
  122. with open(filename, 'rb') as g:
  123. while True:
  124. hashdata = g.read(BUF_SIZE)
  125. if not hashdata:
  126. break
  127. sha1.update(hashdata)
  128. return sha1.hexdigest()