Commit 834b86d05bf7824a2a0ce927878f17c6a28079f9

Authored by Василь Свідрик
1 parent bc80f59b26
Exists in master

add jwt decorator

Showing 2 changed files with 1 additions and 0 deletions Inline Diff

k2/__pycache__/k2rout.cpython-310.pyc
No preview for this file type
1 import zipfile 1 import zipfile
2 from flask import Flask, Blueprint, jsonify, render_template, redirect, url_for, session, jsonify 2 from flask import Flask, Blueprint, jsonify, render_template, redirect, url_for, session, jsonify
3 import os 3 import os
4 import shutil 4 import shutil
5 from flask import request 5 from flask import request
6 from .k2cfg import k2 6 from .k2cfg import k2
7 from .k2comp import Component 7 from .k2comp import Component
8 from flask_migrate import Migrate 8 from flask_migrate import Migrate
9 import requests 9 import requests
10 import subprocess 10 import subprocess
11 from flask import current_app 11 from flask import current_app
12 import yaml 12 import yaml
13 from functools import wraps 13 from functools import wraps
14 import os 14 import os
15 import sys 15 import sys
16 from .k2admmenu import K2admin_menus, K2admin_Menus_Prava 16 from .k2admmenu import K2admin_menus, K2admin_Menus_Prava
17 from sqlalchemy import text 17 from sqlalchemy import text
18 from flask_jwt_extended import get_jwt_identity, jwt_required 18 from flask_jwt_extended import get_jwt_identity, jwt_required
19 19
20 20
21 21
22 # initialize db 22 # initialize db
23 # migrate = Migrate(app, db) 23 # migrate = Migrate(app, db)
24 24
25 components_bp = Blueprint('components', __name__, template_folder='templates') 25 components_bp = Blueprint('components', __name__, template_folder='templates')
26 config = yaml.safe_load(open("db/first-login.yml")) 26 config = yaml.safe_load(open("db/first-login.yml"))
27 27
28 db = k2.db 28 db = k2.db
29 29
30 30
31 def first_login_required(view_func): 31 def first_login_required(view_func):
32 @wraps(view_func) 32 @wraps(view_func)
33 def decorated_view(*args, **kwargs): 33 def decorated_view(*args, **kwargs):
34 if 'username' not in session: 34 if 'username' not in session:
35 return redirect(url_for('components.first_login')) 35 return redirect(url_for('components.first_login'))
36 return view_func(*args, **kwargs) 36 return view_func(*args, **kwargs)
37 37
38 return decorated_view 38 return decorated_view
39 39
40 # def append_to_yaml_file(file_path, data): 40 # def append_to_yaml_file(file_path, data):
41 # with open(file_path, 'r') as f: 41 # with open(file_path, 'r') as f:
42 # existing_data = yaml.safe_load(f) or [] 42 # existing_data = yaml.safe_load(f) or []
43 # 43 #
44 # if not existing_data: 44 # if not existing_data:
45 # start_id = 1 45 # start_id = 1
46 # else: 46 # else:
47 # start_id = max(item.get('id', 0) for item in existing_data) + 1 47 # start_id = max(item.get('id', 0) for item in existing_data) + 1
48 # 48 #
49 # for i, item in enumerate(data, start=start_id): 49 # for i, item in enumerate(data, start=start_id):
50 # item['id'] = i 50 # item['id'] = i
51 # existing_data.append(item) 51 # existing_data.append(item)
52 # 52 #
53 # with open(file_path, 'w') as f: 53 # with open(file_path, 'w') as f:
54 # yaml.dump(existing_data, f, default_flow_style=False) 54 # yaml.dump(existing_data, f, default_flow_style=False)
55 55
56 def remove_from_yaml_file(file_path, component_name): 56 def remove_from_yaml_file(file_path, component_name):
57 with open(file_path, 'r') as f: 57 with open(file_path, 'r') as f:
58 existing_data = yaml.safe_load(f) or [] 58 existing_data = yaml.safe_load(f) or []
59 59
60 updated_data = [item for item in existing_data if item.get('component_name') != component_name] 60 updated_data = [item for item in existing_data if item.get('component_name') != component_name]
61 61
62 with open(file_path, 'w') as f: 62 with open(file_path, 'w') as f:
63 yaml.dump(updated_data, f, default_flow_style=False) 63 yaml.dump(updated_data, f, default_flow_style=False)
64 64
65 65
66 @components_bp.route('/api/languages', methods=['GET']) 66 @components_bp.route('/api/languages', methods=['GET'])
67 def find_language(): 67 def find_language():
68 components = Component.query.all() 68 components = Component.query.all()
69 languages_paths = [] 69 languages_paths = []
70 # Додаємо головну директорію languages 70 # Додаємо головну директорію languages
71 languages_paths.append('languages') 71 languages_paths.append('languages')
72 # Знаходимо шляхи до директорій languages всередині папки components 72 # Знаходимо шляхи до директорій languages всередині папки components
73 for component in components: 73 for component in components:
74 component_languages_directory = 'components/' + component.name + '/' + component.name + '/languages' 74 component_languages_directory = 'components/' + component.name + '/' + component.name + '/languages'
75 languages_paths.append(component_languages_directory) 75 languages_paths.append(component_languages_directory)
76 result = ';'.join(languages_paths) 76 result = ';'.join(languages_paths)
77 print(result) 77 print(result)
78 return result 78 return result
79 79
80 80
81 @components_bp.route('/home', methods=['GET', 'POST']) 81 @components_bp.route('/home', methods=['GET', 'POST'])
82 @first_login_required 82 @first_login_required
83 def home(): 83 def home():
84 return redirect('/dashboard') 84 return redirect('/dashboard')
85 85
86 86
87 @components_bp.route('/first-login', methods=['GET', 'POST']) 87 @components_bp.route('/first-login', methods=['GET', 'POST'])
88 def first_login(): 88 def first_login():
89 if request.method == "POST": 89 if request.method == "POST":
90 username = request.form.get("username") 90 username = request.form.get("username")
91 password = request.form.get("password") 91 password = request.form.get("password")
92 for user in config["users"]: 92 for user in config["users"]:
93 if user["username"] == username and user["password"] == password: 93 if user["username"] == username and user["password"] == password:
94 session['username'] = username # Збереження ім'я користувача в сесії 94 session['username'] = username # Збереження ім'я користувача в сесії
95 return redirect(url_for('components.dashboard')) 95 return redirect(url_for('components.dashboard'))
96 return "Невірне ім'я користувача або пароль." 96 return "Невірне ім'я користувача або пароль."
97 return render_template('first-login.html') 97 return render_template('first-login.html')
98 98
99 99
100 @components_bp.route('/change_language/<lang>') 100 @components_bp.route('/change_language/<lang>')
101 def change_language(lang): 101 def change_language(lang):
102 session['lang'] = lang 102 session['lang'] = lang
103 k2.current_language = lang 103 k2.current_language = lang
104 return redirect(url_for('components.dashboard')) 104 return redirect(url_for('components.dashboard'))
105 105
106 106
107 @components_bp.route('/dashboard') 107 @components_bp.route('/dashboard')
108 @first_login_required 108 @first_login_required
109 def dashboard(): 109 def dashboard():
110 # Компоненти доступні для встановлення 110 # Компоненти доступні для встановлення
111 # GET-запит до API 111 # GET-запит до API
112 try: 112 try:
113 response = requests.get(f'{k2.update_domain}api/components') 113 response = requests.get(f'{k2.update_domain}api/components')
114 json_data = response.json() 114 json_data = response.json()
115 # Перетворення JSON-об'єкту на масив 115 # Перетворення JSON-об'єкту на масив
116 component_server = [item for item in json_data] 116 component_server = [item for item in json_data]
117 except: 117 except:
118 component_server = None 118 component_server = None
119 119
120 # Встановлені компоненти 120 # Встановлені компоненти
121 components = Component.query.all() 121 components = Component.query.all()
122 components_names = [component.name for component in components] 122 components_names = [component.name for component in components]
123 # Отримання значення пошукового запиту з параметрів URL 123 # Отримання значення пошукового запиту з параметрів URL
124 search_query = request.args.get('search_query') 124 search_query = request.args.get('search_query')
125 # print(search_query) 125 # print(search_query)
126 filtered_components = [] 126 filtered_components = []
127 if search_query: 127 if search_query:
128 filtered_components = [component for component in component_server if 128 filtered_components = [component for component in component_server if
129 (search_query.lower() in component['name'].lower() if component['name'] else False) or 129 (search_query.lower() in component['name'].lower() if component['name'] else False) or
130 (search_query.lower() in component['description'].lower() if component[ 130 (search_query.lower() in component['description'].lower() if component[
131 'description'] else False)] 131 'description'] else False)]
132 else: 132 else:
133 filtered_components = component_server 133 filtered_components = component_server
134 current_language = k2.current_language 134 current_language = k2.current_language
135 135
136 return render_template('dashboard.html', components=components, 136 return render_template('dashboard.html', components=components,
137 components_names=components_names, component_server=filtered_components, 137 components_names=components_names, component_server=filtered_components,
138 search_query=search_query, language=k2.menu) 138 search_query=search_query, language=k2.menu)
139 139
140 140
141 @components_bp.route('/show_components/<string:component_id>') 141 @components_bp.route('/show_components/<string:component_id>')
142 def show_components(component_id): 142 def show_components(component_id):
143 response = requests.get(f'{k2.update_domain}api/components') 143 response = requests.get(f'{k2.update_domain}api/components')
144 json_data = response.json() 144 json_data = response.json()
145 selected_component = next((component for component in json_data if component['id'] == component_id), None) 145 selected_component = next((component for component in json_data if component['id'] == component_id), None)
146 return render_template('component-info.html', selected_component=selected_component) 146 return render_template('component-info.html', selected_component=selected_component)
147 147
148 148
149 @components_bp.route('/install_components_git/<string:component_id>') 149 @components_bp.route('/install_components_git/<string:component_id>')
150 def install_components_git(component_id): 150 def install_components_git(component_id):
151 # Шлях до головної папки проекту 151 # Шлях до головної папки проекту
152 project_folder = 'components' 152 project_folder = 'components'
153 # component = Component.get_repository_by_id(component_id) 153 # component = Component.get_repository_by_id(component_id)
154 response = requests.get(f'{k2.update_domain}api/components') 154 response = requests.get(f'{k2.update_domain}api/components')
155 json_data = response.json() 155 json_data = response.json()
156 selected_component = next((component for component in json_data if component['id'] == component_id), None) 156 selected_component = next((component for component in json_data if component['id'] == component_id), None)
157 # Назва репозиторія 157 # Назва репозиторія
158 repository_name = selected_component['name'] 158 repository_name = selected_component['name']
159 # Шлях до папки репозиторія в межах проекту 159 # Шлях до папки репозиторія в межах проекту
160 repository_folder = os.path.join(project_folder, repository_name) 160 repository_folder = os.path.join(project_folder, repository_name)
161 # URL репозиторія 161 # URL репозиторія
162 162
163 git_repo_url = selected_component['git_link'] 163 git_repo_url = selected_component['git_link']
164 try: 164 try:
165 # Перевірка наявності папки репозиторія 165 # Перевірка наявності папки репозиторія
166 if not os.path.exists(repository_folder): 166 if not os.path.exists(repository_folder):
167 # Створення папки репозиторія 167 # Створення папки репозиторія
168 os.makedirs(repository_folder) 168 os.makedirs(repository_folder)
169 # Шлях до файлу __init__.py 169 # Шлях до файлу __init__.py
170 init_file = os.path.join(repository_folder, '__init__.py') 170 init_file = os.path.join(repository_folder, '__init__.py')
171 # Перевірка наявності файлу __init__.py 171 # Перевірка наявності файлу __init__.py
172 if not os.path.exists(init_file): 172 if not os.path.exists(init_file):
173 # Створення пустого файлу __init__.py 173 # Створення пустого файлу __init__.py
174 open(init_file, 'a').close() 174 open(init_file, 'a').close()
175 # підключення до приватного репозиторію 175 # підключення до приватного репозиторію
176 # os.environ['GITLAB_PRIVATE_TOKEN'] = '8xxTpxrKVDGoXD5ynjiW' 176 # os.environ['GITLAB_PRIVATE_TOKEN'] = '8xxTpxrKVDGoXD5ynjiW'
177 # git_repo_url_with_token = git_repo_url.replace('https://', 177 # git_repo_url_with_token = git_repo_url.replace('https://',
178 # f'https://oauth2:{os.environ["GITLAB_PRIVATE_TOKEN"]}@') 178 # f'https://oauth2:{os.environ["GITLAB_PRIVATE_TOKEN"]}@')
179 179
180 # Команда для встановлення з використанням git_repo_url і повного шляху до папки репозиторія 180 # Команда для встановлення з використанням git_repo_url і повного шляху до папки репозиторія
181 command = ['venv/Scripts/python.exe', '-m', 'pip', 'install', '--use-pep517', 'git+' + git_repo_url, 181 command = ['venv/Scripts/python.exe', '-m', 'pip', 'install', '--use-pep517', 'git+' + git_repo_url,
182 '--target=' + repository_folder] 182 '--target=' + repository_folder]
183 # Виконуємо команду встановлення 183 # Виконуємо команду встановлення
184 subprocess.check_call(command) 184 subprocess.check_call(command)
185 185
186 # Шлях до файлу, до якого потрібно додати код 186 # Шлях до файлу, до якого потрібно додати код
187 file_path = 'routes.py' 187 file_path = 'routes.py'
188 # Код, який потрібно додати 188 # Код, який потрібно додати
189 code = selected_component['dependencies'] 189 code = selected_component['dependencies']
190 # Відкриття файлу у режимі дозапису 190 # Відкриття файлу у режимі дозапису
191 with open(file_path, 'a') as file: 191 with open(file_path, 'a') as file:
192 # Запис нового коду у файл 192 # Запис нового коду у файл
193 file.write('\n') 193 file.write('\n')
194 file.write(code) 194 file.write(code)
195 file.write('\n') 195 file.write('\n')
196 component = Component.query.filter_by(name=selected_component['name']).first() 196 component = Component.query.filter_by(name=selected_component['name']).first()
197 if not component: 197 if not component:
198 new_component = Component( 198 new_component = Component(
199 name=selected_component['name'], 199 name=selected_component['name'],
200 description=selected_component['description'], 200 description=selected_component['description'],
201 version=selected_component['version'], 201 version=selected_component['version'],
202 git_link=selected_component['git_link'], 202 git_link=selected_component['git_link'],
203 dependencies=selected_component['dependencies'], 203 dependencies=selected_component['dependencies'],
204 installed=True 204 installed=True
205 ) 205 )
206 # Add the new component to the database 206 # Add the new component to the database
207 db.session.add(new_component) 207 db.session.add(new_component)
208 db.session.commit() 208 db.session.commit()
209 209
210 # Повертаємо повідомлення про успішне встановлення 210 # Повертаємо повідомлення про успішне встановлення
211 return f'Installed successfully <meta http-equiv="refresh" content="1;url=/dashboard" />' 211 return f'Installed successfully <meta http-equiv="refresh" content="1;url=/dashboard" />'
212 except subprocess.CalledProcessError as e: 212 except subprocess.CalledProcessError as e:
213 return 'Error installing : ' + str(e) 213 return 'Error installing : ' + str(e)
214 214
215 215
216 @components_bp.route('/install_components/<string:component_id>') 216 @components_bp.route('/install_components/<string:component_id>')
217 def install_component_from_archive(component_id): 217 def install_component_from_archive(component_id):
218 # Шлях до головної папки проекту 218 # Шлях до головної папки проекту
219 project_folder = 'components' 219 project_folder = 'components'
220 # Отримати відповідну компоненту зі списку компонент 220 # Отримати відповідну компоненту зі списку компонент
221 response = requests.get(f'{k2.update_domain}api/components') 221 response = requests.get(f'{k2.update_domain}api/components')
222 json_data = response.json() 222 json_data = response.json()
223 selected_component = next((component for component in json_data if component['id'] == component_id), None) 223 selected_component = next((component for component in json_data if component['id'] == component_id), None)
224 if selected_component is None: 224 if selected_component is None:
225 return 'Component not found' 225 return 'Component not found'
226 # Отримати посилання на архів компоненти та версію 226 # Отримати посилання на архів компоненти та версію
227 archive_url = selected_component['latest_component_data'] 227 archive_url = selected_component['latest_component_data']
228 version = selected_component['latest_version'] 228 version = selected_component['latest_version']
229 try: 229 try:
230 # Створити шлях до папки компоненти згідно назви та версії 230 # Створити шлях до папки компоненти згідно назви та версії
231 component_folder = os.path.join(project_folder) 231 component_folder = os.path.join(project_folder)
232 os.makedirs(component_folder, exist_ok=True) 232 os.makedirs(component_folder, exist_ok=True)
233 # Завантажити архів компоненти 233 # Завантажити архів компоненти
234 response = requests.get(archive_url, stream=True) 234 response = requests.get(archive_url, stream=True)
235 response.raise_for_status() 235 response.raise_for_status()
236 # Шлях до завантаженого архіву 236 # Шлях до завантаженого архіву
237 archive_path = os.path.join(component_folder, f"{selected_component['name']}.zip") 237 archive_path = os.path.join(component_folder, f"{selected_component['name']}.zip")
238 # Зберегти архів на диск 238 # Зберегти архів на диск
239 with open(archive_path, "wb") as file: 239 with open(archive_path, "wb") as file:
240 for chunk in response.iter_content(chunk_size=8192): 240 for chunk in response.iter_content(chunk_size=8192):
241 file.write(chunk) 241 file.write(chunk)
242 # Розпакувати архів 242 # Розпакувати архів
243 with zipfile.ZipFile(archive_path, "r") as zip_ref: 243 with zipfile.ZipFile(archive_path, "r") as zip_ref:
244 zip_ref.extractall(component_folder) 244 zip_ref.extractall(component_folder)
245 # Видалити архів 245 # Видалити архів
246 os.remove(archive_path) 246 os.remove(archive_path)
247 #перейменувати якщо git 247 #перейменувати якщо git
248 component_name = selected_component['name'] 248 component_name = selected_component['name']
249 old_folder_path = os.path.join(component_folder, component_name + ".git") 249 old_folder_path = os.path.join(component_folder, component_name + ".git")
250 new_folder_path = os.path.join(component_folder, component_name) 250 new_folder_path = os.path.join(component_folder, component_name)
251 # Перевірка наявності папки зі старою назвою 251 # Перевірка наявності папки зі старою назвою
252 if os.path.exists(old_folder_path) and os.path.isdir(old_folder_path): 252 if os.path.exists(old_folder_path) and os.path.isdir(old_folder_path):
253 # Перейменування папки зі старою назвою на нову назву 253 # Перейменування папки зі старою назвою на нову назву
254 os.rename(old_folder_path, new_folder_path) 254 os.rename(old_folder_path, new_folder_path)
255 255
256 # Шлях до файлу, до якого потрібно додати роути 256 # Шлях до файлу, до якого потрібно додати роути
257 file_path = 'routes.py' 257 file_path = 'routes.py'
258 # Код, який потрібно додати 258 # Код, який потрібно додати
259 code = f'''from components.{selected_component['name']}.{selected_component['name']}.views import {selected_component['name']}\napp.register_blueprint({selected_component['name']}, url_prefix='/{selected_component['name']}')''' 259 code = f'''from components.{selected_component['name']}.{selected_component['name']}.views import {selected_component['name']}\napp.register_blueprint({selected_component['name']}, url_prefix='/{selected_component['name']}')'''
260 # selected_component['dependencies'] 260 # selected_component['dependencies']
261 261
262 # Відкриття файлу у режимі дозапису 262 # Відкриття файлу у режимі дозапису
263 with open(file_path, 'a') as file: 263 with open(file_path, 'a') as file:
264 # Запис нового коду у файл 264 # Запис нового коду у файл
265 file.write('\n') 265 file.write('\n')
266 file.write(code) 266 file.write(code)
267 file.write('\n') 267 file.write('\n')
268 268
269 # Update database with the installed component 269 # Update database with the installed component
270 component = Component.query.filter_by(name=selected_component['name']).first() 270 component = Component.query.filter_by(name=selected_component['name']).first()
271 if not component: 271 if not component:
272 component = Component( 272 component = Component(
273 name=selected_component['name'], 273 name=selected_component['name'],
274 description=selected_component['description'], 274 description=selected_component['description'],
275 version=version, 275 version=version,
276 git_link=selected_component['git_link'], 276 git_link=selected_component['git_link'],
277 dependencies=code, 277 dependencies=code,
278 installed=True 278 installed=True
279 ) 279 )
280 db.session.add(component) 280 db.session.add(component)
281 else: 281 else:
282 component.version = version 282 component.version = version
283 component.git_link = selected_component['git_link'] 283 component.git_link = selected_component['git_link']
284 component.dependencies = code 284 component.dependencies = code
285 component.installed = True 285 component.installed = True
286 286
287 db.session.commit() 287 db.session.commit()
288 288
289 # add language folders 289 # add language folders
290 290
291 k2.search_babel_translation_directories() 291 k2.search_babel_translation_directories()
292 return f'''Component installed successfully: {selected_component["name"]} v{version} {k2.babel_translation_directories}, 292 return f'''Component installed successfully: {selected_component["name"]} v{version} {k2.babel_translation_directories},
293 \n \n please wait installing requirments... 293 \n \n please wait installing requirments...
294 <meta http-equiv="refresh" content="0;url=/install-requirments/{selected_component["name"]}" />''' 294 <meta http-equiv="refresh" content="0;url=/install-requirments/{selected_component["name"]}" />'''
295 295
296 except Exception as e: 296 except Exception as e:
297 return f'Error installing component: {str(e)}' 297 return f'Error installing component: {str(e)}'
298 298
299 299
300 @components_bp.route('/install-requirments/<string:selected_component_name>', methods=['GET']) 300 @components_bp.route('/install-requirments/<string:selected_component_name>', methods=['GET'])
301 def install_requirments(selected_component_name): 301 def install_requirments(selected_component_name):
302 # menu items 302 # menu items
303 get_admin_menu() 303 get_admin_menu()
304 304
305 305
306 # install requirements 306 # install requirements
307 requirements_file = os.path.join('components', selected_component_name, "requirements.txt") 307 requirements_file = os.path.join('components', selected_component_name, "requirements.txt")
308 if os.path.isfile(requirements_file): 308 if os.path.isfile(requirements_file):
309 pip_command = f"{k2.venv_bin_path}/python -m pip install -r {requirements_file}" 309 pip_command = f"{k2.venv_bin_path}/python -m pip install -r {requirements_file}"
310 subprocess.run(pip_command, shell=True, check=True) 310 subprocess.run(pip_command, shell=True, check=True)
311 return f'''Requirements installed successfully 311 return f'''Requirements installed successfully
312 \n \n please wait installing requirments components... 312 \n \n please wait installing requirments components...
313 <meta http-equiv="refresh" content="1;url=/install-requirments-components" />''' 313 <meta http-equiv="refresh" content="1;url=/install-requirments-components" />'''
314 314
315 315
316 @components_bp.route('/install-requirments-components') 316 @components_bp.route('/install-requirments-components')
317 def install_requirements_components(): 317 def install_requirements_components():
318 # Откриття файлу requirements_components.txt 318 # Откриття файлу requirements_components.txt
319 requirements_file = 'requirements_components.txt' 319 requirements_file = 'requirements_components.txt'
320 component_ids = None 320 component_ids = None
321 if os.path.isfile(requirements_file): 321 if os.path.isfile(requirements_file):
322 with open('requirements_components.txt', 'r') as file: 322 with open('requirements_components.txt', 'r') as file:
323 component_ids = file.read().splitlines() 323 component_ids = file.read().splitlines()
324 if component_ids: 324 if component_ids:
325 for component_id in component_ids: 325 for component_id in component_ids:
326 # Виклик роуту '/install_components/<string:component_name>' для кожної назви компоненти 326 # Виклик роуту '/install_components/<string:component_name>' для кожної назви компоненти
327 response = requests.get( 327 response = requests.get(
328 f'/install_components/{component_id}') 328 f'/install_components/{component_id}')
329 return f'Requirements components installed successfully <meta http-equiv="refresh" content="1;url=/dashboard" />' 329 return f'Requirements components installed successfully <meta http-equiv="refresh" content="1;url=/dashboard" />'
330 else: 330 else:
331 return f'<meta http-equiv="refresh" content="1;url=/dashboard" />' 331 return f'<meta http-equiv="refresh" content="1;url=/dashboard" />'
332 # Опрацювання відповіді (за потреби) 332 # Опрацювання відповіді (за потреби)
333 333
334 334
335 @components_bp.route('/remove_dependencies/<string:component_id>', methods=['GET']) 335 @components_bp.route('/remove_dependencies/<string:component_id>', methods=['GET'])
336 def remove_dependencies(component_id): 336 def remove_dependencies(component_id):
337 # Знаходимо компоненту за її ID 337 # Знаходимо компоненту за її ID
338 component = Component.query.get(component_id) 338 component = Component.query.get(component_id)
339 if not component: 339 if not component:
340 return 'Component not found <meta http-equiv="refresh" content="1;url=/dashboard" />' 340 return 'Component not found <meta http-equiv="refresh" content="1;url=/dashboard" />'
341 # remove menu items 341 # remove menu items
342 component_name = component.name 342 component_name = component.name
343 # file_path = "components/menu.yml" 343 # file_path = "components/menu.yml"
344 # remove_from_yaml_file(file_path, component_name) 344 # remove_from_yaml_file(file_path, component_name)
345 requests.get(f"{k2.domain}api/add-to-menu") 345 requests.get(f"{k2.domain}api/add-to-menu")
346 # remove routes 346 # remove routes
347 file_path = 'routes.py' 347 file_path = 'routes.py'
348 with open(file_path, 'r') as file: 348 with open(file_path, 'r') as file:
349 lines = file.readlines() 349 lines = file.readlines()
350 350
351 updated_lines = [line for line in lines if line.strip() not in component.dependencies] 351 updated_lines = [line for line in lines if line.strip() not in component.dependencies]
352 with open(file_path, 'w') as file: 352 with open(file_path, 'w') as file:
353 file.writelines(updated_lines) 353 file.writelines(updated_lines)
354 354
355 component.installed = False 355 component.installed = False
356 db.session.commit() 356 db.session.commit()
357 357
358 return 'Component successfully turn off <meta http-equiv="refresh" content="1;url=/dashboard" />' 358 return 'Component successfully turn off <meta http-equiv="refresh" content="1;url=/dashboard" />'
359 359
360 360
361 @components_bp.route('/add_dependencies/<string:component_id>', methods=['GET']) 361 @components_bp.route('/add_dependencies/<string:component_id>', methods=['GET'])
362 def add_dependencies(component_id): 362 def add_dependencies(component_id):
363 # Знаходимо компоненту за її ID 363 # Знаходимо компоненту за її ID
364 component = Component.query.get(component_id) 364 component = Component.query.get(component_id)
365 if not component: 365 if not component:
366 return 'Component not found <meta http-equiv="refresh" content="1;url=/dashboard" />' 366 return 'Component not found <meta http-equiv="refresh" content="1;url=/dashboard" />'
367 367
368 file_path = 'routes.py' 368 file_path = 'routes.py'
369 code = component.dependencies 369 code = component.dependencies
370 # Відкриття файлу у режимі дозапису 370 # Відкриття файлу у режимі дозапису
371 with open(file_path, 'a') as file: 371 with open(file_path, 'a') as file:
372 # Запис нового коду у файл 372 # Запис нового коду у файл
373 file.write(code) 373 file.write(code)
374 374
375 # Оновлюємо статус компоненти 375 # Оновлюємо статус компоненти
376 component.installed = True 376 component.installed = True
377 db.session.commit() 377 db.session.commit()
378 return 'Dependencies added successfully <meta http-equiv="refresh" content="1;url=/dashboard" />' 378 return 'Dependencies added successfully <meta http-equiv="refresh" content="1;url=/dashboard" />'
379 379
380 380
381 @components_bp.route('/remove-component/<string:component_id>') 381 @components_bp.route('/remove-component/<string:component_id>')
382 def remove_component(component_id): 382 def remove_component(component_id):
383 # Шлях до головної папки проекту 383 # Шлях до головної папки проекту
384 project_folder = 'components' 384 project_folder = 'components'
385 component = Component.query.get(component_id) 385 component = Component.query.get(component_id)
386 # Назва репозиторія 386 # Назва репозиторія
387 repository_name = component.name 387 repository_name = component.name
388 # Шлях до папки репозиторія в межах проекту 388 # Шлях до папки репозиторія в межах проекту
389 repository_folder = os.path.join(project_folder, repository_name) 389 repository_folder = os.path.join(project_folder, repository_name)
390 try: 390 try:
391 # Перевірка наявності папки репозиторія 391 # Перевірка наявності папки репозиторія
392 if os.path.exists(repository_folder): 392 if os.path.exists(repository_folder):
393 # Видалення папки репозиторія 393 # Видалення папки репозиторія
394 shutil.rmtree(repository_folder) 394 shutil.rmtree(repository_folder)
395 # Видаляємо компоненту з бази 395 # Видаляємо компоненту з бази
396 if component: 396 if component:
397 db.session.delete(component) 397 db.session.delete(component)
398 db.session.commit() 398 db.session.commit()
399 399
400 # Повертаємо повідомлення про успішне видалення 400 # Повертаємо повідомлення про успішне видалення
401 return 'Component removed successfully <meta http-equiv="refresh" content="1;url=/dashboard" />' 401 return 'Component removed successfully <meta http-equiv="refresh" content="1;url=/dashboard" />'
402 except Exception as e: 402 except Exception as e:
403 # Повертаємо повідомлення про помилку видалення 403 # Повертаємо повідомлення про помилку видалення
404 return 'Error removing component: ' + str(e) 404 return 'Error removing component: ' + str(e)
405 405
406 406
407 @components_bp.route('/component/add') 407 @components_bp.route('/component/add')
408 def component_add(): 408 def component_add():
409 # components for install 409 # components for install
410 try: 410 try:
411 # GET-requests to API 411 # GET-requests to API
412 response = requests.get(f'{k2.update_domain}api/components') 412 response = requests.get(f'{k2.update_domain}api/components')
413 json_data = response.json() 413 json_data = response.json()
414 for item in json_data: 414 for item in json_data:
415 item['button'] = f"{k2.domain}/install_components/{item['id']}" 415 item['button'] = f"{k2.domain}/install_components/{item['id']}"
416 416
417 except: 417 except:
418 json_data = None 418 json_data = None
419 return jsonify(json_data) 419 return jsonify(json_data)
420 420
421 421
422 @components_bp.route('/component/list') 422 @components_bp.route('/component/list')
423 def component_list(): 423 def component_list():
424 # Встановлені компоненти 424 # Встановлені компоненти
425 component_list = [] 425 component_list = []
426 components = Component.query.all() 426 components = Component.query.all()
427 for component in components: 427 for component in components:
428 component_dict = {} 428 component_dict = {}
429 component_dict['name'] = component.name 429 component_dict['name'] = component.name
430 component_dict['id'] = component.id 430 component_dict['id'] = component.id
431 component_dict['description'] = component.description 431 component_dict['description'] = component.description
432 component_dict['version'] = component.version 432 component_dict['version'] = component.version
433 component_dict['button_off'] =f"{k2.domain}/remove_dependencies/{component.id}" 433 component_dict['button_off'] =f"{k2.domain}/remove_dependencies/{component.id}"
434 component_dict['button_on'] = f"{k2.domain}/add_dependencies/{component.id}" 434 component_dict['button_on'] = f"{k2.domain}/add_dependencies/{component.id}"
435 component_dict['button_del'] = f"{k2.domain}/remove-component/{component.id}" 435 component_dict['button_del'] = f"{k2.domain}/remove-component/{component.id}"
436 component_list.append(component_dict) 436 component_list.append(component_dict)
437 return jsonify(component_list) 437 return jsonify(component_list)
438 438
439 439
440 # menu 440 # menu
441 @components_bp.route('/api/add-to-menu', methods=['GET']) 441 @components_bp.route('/api/add-to-menu', methods=['GET'])
442 def add_to_menu(): 442 def add_to_menu():
443 data = [] 443 data = []
444 response = requests.get(f"{k2.domain}/menu-admin-items") 444 response = requests.get(f"{k2.domain}/menu-admin-items")
445 data.append(response.json()[0]) 445 data.append(response.json()[0])
446 prev_menu = response.json()[0]['title'] 446 prev_menu = response.json()[0]['title']
447 for item in response.json()[0]['children']: 447 for item in response.json()[0]['children']:
448 name_menu = item['to'] 448 name_menu = item['to']
449 caption_menu = item['title'] 449 caption_menu = item['title']
450 add_menu_with_permissions_db(name_menu, prev_menu, caption_menu) 450 add_menu_with_permissions_db(name_menu, prev_menu, caption_menu)
451 components = Component.query.all() 451 components = Component.query.all()
452 components_names = [component.name for component in components] 452 components_names = [component.name for component in components]
453 for components_names in components_names: 453 for components_names in components_names:
454 response = requests.get(f"{k2.domain}{components_names}/menu-admin-items") 454 response = requests.get(f"{k2.domain}{components_names}/menu-admin-items")
455 if response.status_code == 200: 455 if response.status_code == 200:
456 data.append(response.json()[0]) 456 data.append(response.json()[0])
457 #prev_menu = 457 #prev_menu =
458 prev_menu = response.json()[0]['title'] 458 prev_menu = response.json()[0]['title']
459 for item in response.json()[0]['children']: 459 for item in response.json()[0]['children']:
460 name_menu = item['to'] 460 name_menu = item['to']
461 caption_menu = item['title'] 461 caption_menu = item['title']
462 add_menu_with_permissions_db(name_menu, prev_menu, caption_menu) 462 add_menu_with_permissions_db(name_menu, prev_menu, caption_menu)
463 else: 463 else:
464 data 464 data
465 # add component_name key for menu items 465 # add component_name key for menu items
466 for item in data: 466 for item in data:
467 item['component_name'] = components_names 467 item['component_name'] = components_names
468 k2.menu = data 468 k2.menu = data
469 return k2.menu 469 return k2.menu
470 470
471 471
472 @components_bp.route('/api/main-menu/') 472 @components_bp.route('/api/main-menu/')
473 @jwt_required()
473 def get_admin_menu(): 474 def get_admin_menu():
474 current_user = get_jwt_identity() 475 current_user = get_jwt_identity()
475 role_id = current_user['user_role'] 476 role_id = current_user['user_role']
476 filter_menu = [] 477 filter_menu = []
477 response = requests.get(f"{k2.domain}api/add-to-menu") 478 response = requests.get(f"{k2.domain}api/add-to-menu")
478 menu_items_list = K2admin_menus.get_menu_items_by_roles(role_id) 479 menu_items_list = K2admin_menus.get_menu_items_by_roles(role_id)
479 480
480 for item in response.json(): 481 for item in response.json():
481 filtered_children = [] 482 filtered_children = []
482 for im in item['children']: 483 for im in item['children']:
483 484
484 if im['to'] in menu_items_list: 485 if im['to'] in menu_items_list:
485 filtered_children.append(im) 486 filtered_children.append(im)
486 if filtered_children: 487 if filtered_children:
487 item['children'] = filtered_children 488 item['children'] = filtered_children
488 filter_menu.append(item) 489 filter_menu.append(item)
489 filter_menu.append({"heading": 'APPS & PAGES'}) 490 filter_menu.append({"heading": 'APPS & PAGES'})
490 491
491 return jsonify(filter_menu) 492 return jsonify(filter_menu)
492 493
493 494
494 def add_menu_with_permissions_db(name_menu, prev_menu, caption_menu): 495 def add_menu_with_permissions_db(name_menu, prev_menu, caption_menu):
495 496
496 # Створення об'єкта k2admin_menus 497 # Створення об'єкта k2admin_menus
497 menu = text('SELECT COUNT(*) FROM k2admin_menus WHERE namemenu = :name_menu') 498 menu = text('SELECT COUNT(*) FROM k2admin_menus WHERE namemenu = :name_menu')
498 result = db.session.execute(menu, {'name_menu': name_menu}).fetchone() 499 result = db.session.execute(menu, {'name_menu': name_menu}).fetchone()
499 count = result[0] 500 count = result[0]
500 if count == 0: 501 if count == 0:
501 new_menu_element = K2admin_menus( 502 new_menu_element = K2admin_menus(
502 namemenu=name_menu, 503 namemenu=name_menu,
503 prevmenu=prev_menu, 504 prevmenu=prev_menu,
504 caption=caption_menu, 505 caption=caption_menu,
505 module_name=name_menu 506 module_name=name_menu
506 ) 507 )
507 # Додавання об'єкта k2admin_menus до сесії 508 # Додавання об'єкта k2admin_menus до сесії
508 db.session.add(new_menu_element) 509 db.session.add(new_menu_element)
509 db.session.commit() 510 db.session.commit()
510 # Створення об'єкта k2admin_menus_prava 511 # Створення об'єкта k2admin_menus_prava
511 new_prava = K2admin_Menus_Prava( 512 new_prava = K2admin_Menus_Prava(
512 menuid=new_menu_element.menuid, # Зв'язуємо зовнішній ключ з menuid нового меню 513 menuid=new_menu_element.menuid, # Зв'язуємо зовнішній ключ з menuid нового меню
513 username=None, 514 username=None,
514 r=0, 515 r=0,
515 w=0, 516 w=0,
516 i=0, 517 i=0,
517 d=0, 518 d=0,
518 c=0, 519 c=0,
519 exp=0, 520 exp=0,
520 imp=0, 521 imp=0,
521 settable=0, 522 settable=0,
522 cutpast=0, 523 cutpast=0,
523 enable=0, 524 enable=0,
524 roleid=-1 525 roleid=-1
525 ) 526 )
526 # Додавання об'єкта k2admin_menus_prava до сесії 527 # Додавання об'єкта k2admin_menus_prava до сесії
527 db.session.add(new_prava) 528 db.session.add(new_prava)
528 db.session.commit() 529 db.session.commit()
529 530
530 531
531 @components_bp.route('/menu-admin-items') 532 @components_bp.route('/menu-admin-items')
532 def menu_items(): 533 def menu_items():
533 menu = [ 534 menu = [
534 535
535 { 536 {
536 "title": 'Add components', 537 "title": 'Add components',
537 "icon": {"icon": 'mdi-account-circle-outline'}, 538 "icon": {"icon": 'mdi-account-circle-outline'},
538 "children": [ 539 "children": [
539 {'title': 'Install components', 'to': 'component-add'}, 540 {'title': 'Install components', 'to': 'component-add'},
540 {'title': 'Installed components', 'to': 'component-list'}, 541 {'title': 'Installed components', 'to': 'component-list'},
541 542
542 ], 543 ],
543 }] 544 }]
544 return menu 545 return menu
545 546
546 547
547 548
548 549
549 550
550 551
551 552
552 553