Commit 631cba615723ea77d9926903a2a1d980e7f0decd

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

fix folder name from git bug

Showing 1 changed file with 140 additions and 79 deletions Inline Diff

1 import zipfile 1 import zipfile
2 from flask import Flask, Blueprint, jsonify, render_template, redirect, url_for, session, g 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 16
17 # initialize db 17 # initialize db
18 #migrate = Migrate(app, db) 18 # migrate = Migrate(app, db)
19 19
20 components_bp = Blueprint('components', __name__, template_folder='templates') 20 components_bp = Blueprint('components', __name__, template_folder='templates')
21 config = yaml.safe_load(open("db/first-login.yml")) 21 config = yaml.safe_load(open("db/first-login.yml"))
22 22
23
24 db = k2.db 23 db = k2.db
25 24
26 25
27 def first_login_required(view_func): 26 def first_login_required(view_func):
28 @wraps(view_func) 27 @wraps(view_func)
29 def decorated_view(*args, **kwargs): 28 def decorated_view(*args, **kwargs):
30 if 'username' not in session: 29 if 'username' not in session:
31 return redirect(url_for('components.first_login')) 30 return redirect(url_for('components.first_login'))
32 return view_func(*args, **kwargs) 31 return view_func(*args, **kwargs)
32
33 return decorated_view 33 return decorated_view
34 34
35 def append_to_yaml_file(file_path, data):
36 with open(file_path, 'r') as f:
37 existing_data = yaml.safe_load(f) or []
38 35
39 if not existing_data: 36 # def append_to_yaml_file(file_path, data):
40 start_id = 1 37 # with open(file_path, 'r') as f:
41 else: 38 # existing_data = yaml.safe_load(f) or []
42 start_id = max(item.get('id', 0) for item in existing_data) + 1 39 #
40 # if not existing_data:
41 # start_id = 1
42 # else:
43 # start_id = max(item.get('id', 0) for item in existing_data) + 1
44 #
45 # for i, item in enumerate(data, start=start_id):
46 # item['id'] = i
47 # existing_data.append(item)
48 #
49 # with open(file_path, 'w') as f:
50 # yaml.dump(existing_data, f, default_flow_style=False)
43 51
44 for i, item in enumerate(data, start=start_id):
45 item['id'] = i
46 existing_data.append(item)
47 52
48 with open(file_path, 'w') as f:
49 yaml.dump(existing_data, f, default_flow_style=False)
50
51
52 def remove_from_yaml_file(file_path, component_name): 53 def remove_from_yaml_file(file_path, component_name):
53 with open(file_path, 'r') as f: 54 with open(file_path, 'r') as f:
54 existing_data = yaml.safe_load(f) or [] 55 existing_data = yaml.safe_load(f) or []
55 56
56 updated_data = [item for item in existing_data if item.get('component_name') != component_name] 57 updated_data = [item for item in existing_data if item.get('component_name') != component_name]
57 58
58 with open(file_path, 'w') as f: 59 with open(file_path, 'w') as f:
59 yaml.dump(updated_data, f, default_flow_style=False) 60 yaml.dump(updated_data, f, default_flow_style=False)
60 61
62
61 @components_bp.route('/api/languages', methods=['GET']) 63 @components_bp.route('/api/languages', methods=['GET'])
62 def find_language(): 64 def find_language():
63 components = Component.query.all() 65 components = Component.query.all()
64 languages_paths = [] 66 languages_paths = []
65 # Додаємо головну директорію languages 67 # Додаємо головну директорію languages
66 languages_paths.append('languages') 68 languages_paths.append('languages')
67 # Знаходимо шляхи до директорій languages всередині папки components 69 # Знаходимо шляхи до директорій languages всередині папки components
68 for component in components: 70 for component in components:
69 component_languages_directory = 'components/' + component.name + '/' + component.name + '/languages' 71 component_languages_directory = 'components/' + component.name + '/' + component.name + '/languages'
70 languages_paths.append(component_languages_directory) 72 languages_paths.append(component_languages_directory)
71 result = ';'.join(languages_paths) 73 result = ';'.join(languages_paths)
72 print(result) 74 print(result)
73 return result 75 return result
74 76
75 @components_bp.route('/api/add-to-menu', methods=['GET'])
76 def add_to_menu():
77 data = []
78 components = Component.query.all()
79 components_names = [component.name for component in components]
80 for components_names in components_names:
81 response = requests.get(f"{k2.domain}{components_names}/menu-admin-items")
82 print(response)
83 if response.status_code == 200:
84 data.append(response.json()[0])
85 else:
86 data
87 # add component_name key for menu items
88 for item in data:
89 item['component_name'] = components_names
90 k2.menu = data
91 return k2.menu
92 77
93 @components_bp.route('/home', methods=['GET', 'POST']) 78 @components_bp.route('/home', methods=['GET', 'POST'])
94 @first_login_required 79 @first_login_required
95 def home(): 80 def home():
96 return redirect('/dashboard') 81 return redirect('/dashboard')
97 82
83
98 @components_bp.route('/first-login', methods=['GET', 'POST']) 84 @components_bp.route('/first-login', methods=['GET', 'POST'])
99 def first_login(): 85 def first_login():
100 if request.method == "POST": 86 if request.method == "POST":
101 username = request.form.get("username") 87 username = request.form.get("username")
102 password = request.form.get("password") 88 password = request.form.get("password")
103 for user in config["users"]: 89 for user in config["users"]:
104 if user["username"] == username and user["password"] == password: 90 if user["username"] == username and user["password"] == password:
105 session['username'] = username # Збереження ім'я користувача в сесії 91 session['username'] = username # Збереження ім'я користувача в сесії
106 return redirect(url_for('components.dashboard')) 92 return redirect(url_for('components.dashboard'))
107 return "Невірне ім'я користувача або пароль." 93 return "Невірне ім'я користувача або пароль."
108 return render_template('first-login.html') 94 return render_template('first-login.html')
109 95
110 96
111 @components_bp.route('/change_language/<lang>') 97 @components_bp.route('/change_language/<lang>')
112 def change_language(lang): 98 def change_language(lang):
113 session['lang'] = lang 99 session['lang'] = lang
114 k2.current_language = lang 100 k2.current_language = lang
115 return redirect(url_for('components.dashboard')) 101 return redirect(url_for('components.dashboard'))
116 102
103
117 @components_bp.route('/dashboard') 104 @components_bp.route('/dashboard')
118 @first_login_required 105 @first_login_required
119 def dashboard(): 106 def dashboard():
120 # Компоненти доступні для встановлення 107 # Компоненти доступні для встановлення
121 try: 108 try:
122 # GET-запит до API 109 # GET-запит до API
123 response = requests.get(f'{k2.update_domain}api/components') 110 response = requests.get(f'{k2.update_domain}api/components')
124 json_data = response.json() 111 json_data = response.json()
125 # Перетворення JSON-об'єкту на масив 112 # Перетворення JSON-об'єкту на масив
126 component_server = [item for item in json_data] 113 component_server = [item for item in json_data]
127 except: 114 except:
128 component_server = None 115 component_server = None
129 116
130 # Встановлені компоненти 117 # Встановлені компоненти
131 components = Component.query.all() 118 components = Component.query.all()
132 components_names = [component.name for component in components] 119 components_names = [component.name for component in components]
133 # Отримання значення пошукового запиту з параметрів URL 120 # Отримання значення пошукового запиту з параметрів URL
134 search_query = request.args.get('search_query') 121 search_query = request.args.get('search_query')
135 #print(search_query) 122 # print(search_query)
136 filtered_components = [] 123 filtered_components = []
137 if search_query: 124 if search_query:
138 filtered_components = [component for component in component_server if 125 filtered_components = [component for component in component_server if
139 (search_query.lower() in component['name'].lower() if component['name'] else False) or 126 (search_query.lower() in component['name'].lower() if component['name'] else False) or
140 (search_query.lower() in component['description'].lower() if component[ 127 (search_query.lower() in component['description'].lower() if component[
141 'description'] else False)] 128 'description'] else False)]
142 else: 129 else:
143 filtered_components = component_server 130 filtered_components = component_server
144 current_language = k2.current_language 131 current_language = k2.current_language
145 132
146 return render_template('dashboard.html', components=components, 133 return render_template('dashboard.html', components=components,
147 components_names=components_names, component_server=filtered_components, 134 components_names=components_names, component_server=filtered_components,
148 search_query=search_query, language=k2.menu ) 135 search_query=search_query, language=k2.menu)
149 136
137
150 @components_bp.route('/show_components/<string:component_id>') 138 @components_bp.route('/show_components/<string:component_id>')
151 def show_components(component_id): 139 def show_components(component_id):
152 response = requests.get(f'{k2.update_domain}api/components') 140 response = requests.get(f'{k2.update_domain}api/components')
153 json_data = response.json() 141 json_data = response.json()
154 selected_component = next((component for component in json_data if component['id'] == component_id), None) 142 selected_component = next((component for component in json_data if component['id'] == component_id), None)
155 return render_template('component-info.html', selected_component=selected_component) 143 return render_template('component-info.html', selected_component=selected_component)
156 144
145
157 @components_bp.route('/install_components_git/<string:component_id>') 146 @components_bp.route('/install_components_git/<string:component_id>')
158 def install_components_git(component_id): 147 def install_components_git(component_id):
159 # Шлях до головної папки проекту 148 # Шлях до головної папки проекту
160 project_folder = 'components' 149 project_folder = 'components'
161 #component = Component.get_repository_by_id(component_id) 150 # component = Component.get_repository_by_id(component_id)
162 response = requests.get(f'{k2.update_domain}api/components') 151 response = requests.get(f'{k2.update_domain}api/components')
163 json_data = response.json() 152 json_data = response.json()
164 selected_component = next((component for component in json_data if component['id'] == component_id), None) 153 selected_component = next((component for component in json_data if component['id'] == component_id), None)
165 # Назва репозиторія 154 # Назва репозиторія
166 repository_name = selected_component['name'] 155 repository_name = selected_component['name']
167 # Шлях до папки репозиторія в межах проекту 156 # Шлях до папки репозиторія в межах проекту
168 repository_folder = os.path.join(project_folder, repository_name) 157 repository_folder = os.path.join(project_folder, repository_name)
169 # URL репозиторія 158 # URL репозиторія
170 159
171 git_repo_url = selected_component['git_link'] 160 git_repo_url = selected_component['git_link']
172 try: 161 try:
173 # Перевірка наявності папки репозиторія 162 # Перевірка наявності папки репозиторія
174 if not os.path.exists(repository_folder): 163 if not os.path.exists(repository_folder):
175 # Створення папки репозиторія 164 # Створення папки репозиторія
176 os.makedirs(repository_folder) 165 os.makedirs(repository_folder)
177 # Шлях до файлу __init__.py 166 # Шлях до файлу __init__.py
178 init_file = os.path.join(repository_folder, '__init__.py') 167 init_file = os.path.join(repository_folder, '__init__.py')
179 # Перевірка наявності файлу __init__.py 168 # Перевірка наявності файлу __init__.py
180 if not os.path.exists(init_file): 169 if not os.path.exists(init_file):
181 # Створення пустого файлу __init__.py 170 # Створення пустого файлу __init__.py
182 open(init_file, 'a').close() 171 open(init_file, 'a').close()
183 #підключення до приватного репозиторію 172 # підключення до приватного репозиторію
184 #os.environ['GITLAB_PRIVATE_TOKEN'] = '8xxTpxrKVDGoXD5ynjiW' 173 # os.environ['GITLAB_PRIVATE_TOKEN'] = '8xxTpxrKVDGoXD5ynjiW'
185 #git_repo_url_with_token = git_repo_url.replace('https://', 174 # git_repo_url_with_token = git_repo_url.replace('https://',
186 # f'https://oauth2:{os.environ["GITLAB_PRIVATE_TOKEN"]}@') 175 # f'https://oauth2:{os.environ["GITLAB_PRIVATE_TOKEN"]}@')
187 176
188 # Команда для встановлення з використанням git_repo_url і повного шляху до папки репозиторія 177 # Команда для встановлення з використанням git_repo_url і повного шляху до папки репозиторія
189 command = ['venv/Scripts/python.exe', '-m', 'pip', 'install', '--use-pep517', 'git+' + git_repo_url, '--target=' + repository_folder] 178 command = ['venv/Scripts/python.exe', '-m', 'pip', 'install', '--use-pep517', 'git+' + git_repo_url,
179 '--target=' + repository_folder]
190 # Виконуємо команду встановлення 180 # Виконуємо команду встановлення
191 subprocess.check_call(command) 181 subprocess.check_call(command)
192 182
193 # Шлях до файлу, до якого потрібно додати код 183 # Шлях до файлу, до якого потрібно додати код
194 file_path = 'routes.py' 184 file_path = 'routes.py'
195 # Код, який потрібно додати 185 # Код, який потрібно додати
196 code = selected_component['dependencies'] 186 code = selected_component['dependencies']
197 # Відкриття файлу у режимі дозапису 187 # Відкриття файлу у режимі дозапису
198 with open(file_path, 'a') as file: 188 with open(file_path, 'a') as file:
199 # Запис нового коду у файл 189 # Запис нового коду у файл
200 file.write('\n') 190 file.write('\n')
201 file.write(code) 191 file.write(code)
202 file.write('\n') 192 file.write('\n')
203 component = Component.query.filter_by(name=selected_component['name']).first() 193 component = Component.query.filter_by(name=selected_component['name']).first()
204 if not component: 194 if not component:
205 new_component = Component( 195 new_component = Component(
206 name=selected_component['name'], 196 name=selected_component['name'],
207 description=selected_component['description'], 197 description=selected_component['description'],
208 version=selected_component['version'], 198 version=selected_component['version'],
209 git_link=selected_component['git_link'], 199 git_link=selected_component['git_link'],
210 dependencies=selected_component['dependencies'], 200 dependencies=selected_component['dependencies'],
211 installed=True 201 installed=True
212 ) 202 )
213 # Add the new component to the database 203 # Add the new component to the database
214 db.session.add(new_component) 204 db.session.add(new_component)
215 db.session.commit() 205 db.session.commit()
216 206
217 # Повертаємо повідомлення про успішне встановлення 207 # Повертаємо повідомлення про успішне встановлення
218 return f'Installed successfully <meta http-equiv="refresh" content="1;url=/dashboard" />' 208 return f'Installed successfully <meta http-equiv="refresh" content="1;url=/dashboard" />'
219 except subprocess.CalledProcessError as e: 209 except subprocess.CalledProcessError as e:
220 return 'Error installing : ' + str(e) 210 return 'Error installing : ' + str(e)
221 211
212
222 @components_bp.route('/install_components/<string:component_id>') 213 @components_bp.route('/install_components/<string:component_id>')
223 def install_component_from_archive(component_id): 214 def install_component_from_archive(component_id):
224 # Шлях до головної папки проекту 215 # Шлях до головної папки проекту
225 project_folder = 'components' 216 project_folder = 'components'
226 # Отримати відповідну компоненту зі списку компонент 217 # Отримати відповідну компоненту зі списку компонент
227 response = requests.get(f'{k2.update_domain}api/components') 218 response = requests.get(f'{k2.update_domain}api/components')
228 json_data = response.json() 219 json_data = response.json()
229 selected_component = next((component for component in json_data if component['id'] == component_id), None) 220 selected_component = next((component for component in json_data if component['id'] == component_id), None)
230 if selected_component is None: 221 if selected_component is None:
231 return 'Component not found' 222 return 'Component not found'
232 # Отримати посилання на архів компоненти та версію 223 # Отримати посилання на архів компоненти та версію
233 archive_url = selected_component['latest_component_data'] 224 archive_url = selected_component['latest_component_data']
234 version = selected_component['latest_version'] 225 version = selected_component['latest_version']
235 try: 226 try:
236 # Створити шлях до папки компоненти згідно назви та версії 227 # Створити шлях до папки компоненти згідно назви та версії
237 component_folder = os.path.join(project_folder) 228 component_folder = os.path.join(project_folder)
238 os.makedirs(component_folder, exist_ok=True) 229 os.makedirs(component_folder, exist_ok=True)
239 # Завантажити архів компоненти 230 # Завантажити архів компоненти
240 response = requests.get(archive_url, stream=True) 231 response = requests.get(archive_url, stream=True)
241 response.raise_for_status() 232 response.raise_for_status()
242 # Шлях до завантаженого архіву 233 # Шлях до завантаженого архіву
243 archive_path = os.path.join(component_folder, f"{selected_component['name']}.zip") 234 archive_path = os.path.join(component_folder, f"{selected_component['name']}.zip")
244 # Встановити залежності з файлу requirements.txt
245
246 # Зберегти архів на диск 235 # Зберегти архів на диск
247 with open(archive_path, "wb") as file: 236 with open(archive_path, "wb") as file:
248 for chunk in response.iter_content(chunk_size=8192): 237 for chunk in response.iter_content(chunk_size=8192):
249 file.write(chunk) 238 file.write(chunk)
250 # Розпакувати архів 239 # Розпакувати архів
251 with zipfile.ZipFile(archive_path, "r") as zip_ref: 240 with zipfile.ZipFile(archive_path, "r") as zip_ref:
252 zip_ref.extractall(component_folder) 241 zip_ref.extractall(component_folder)
253
254 # Видалити архів 242 # Видалити архів
255 os.remove(archive_path) 243 os.remove(archive_path)
244 #перейменувати якщо git
245 component_name = selected_component['name']
246 old_folder_path = os.path.join(component_folder, component_name + ".git")
247 new_folder_path = os.path.join(component_folder, component_name)
248 # Перевірка наявності папки зі старою назвою
249 if os.path.exists(old_folder_path) and os.path.isdir(old_folder_path):
250 # Перейменування папки зі старою назвою на нову назву
251 os.rename(old_folder_path, new_folder_path)
256 252
257 # Шлях до файлу, до якого потрібно додати код 253 # Шлях до файлу, до якого потрібно додати роути
258 file_path = 'routes.py' 254 file_path = 'routes.py'
259 # Код, який потрібно додати 255 # Код, який потрібно додати
260 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']}')''' 256 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']}')'''
261 #selected_component['dependencies'] 257 # selected_component['dependencies']
262 258
263 # Відкриття файлу у режимі дозапису 259 # Відкриття файлу у режимі дозапису
264 with open(file_path, 'a') as file: 260 with open(file_path, 'a') as file:
265 # Запис нового коду у файл 261 # Запис нового коду у файл
266 file.write('\n') 262 file.write('\n')
267 file.write(code) 263 file.write(code)
268 file.write('\n') 264 file.write('\n')
269 265
270 #Update database with the installed component 266 # Update database with the installed component
271 component = Component.query.filter_by(name=selected_component['name']).first() 267 component = Component.query.filter_by(name=selected_component['name']).first()
272 if not component: 268 if not component:
273 component = Component( 269 component = Component(
274 name=selected_component['name'], 270 name=selected_component['name'],
275 description=selected_component['description'], 271 description=selected_component['description'],
276 version=version, 272 version=version,
277 git_link=selected_component['git_link'], 273 git_link=selected_component['git_link'],
278 dependencies=code, 274 dependencies=code,
279 installed=True 275 installed=True
280 ) 276 )
281 db.session.add(component) 277 db.session.add(component)
282 else: 278 else:
283 component.version = version 279 component.version = version
284 component.git_link = selected_component['git_link'] 280 component.git_link = selected_component['git_link']
285 component.dependencies = code 281 component.dependencies = code
286 component.installed = True 282 component.installed = True
287 283
288 db.session.commit() 284 db.session.commit()
289 285
290 #add language folders 286 # add language folders
291 k2.search_babel_translation_directories() 287 k2.search_babel_translation_directories()
292 return f'''Component installed successfully: {selected_component["name"]} v{version} {k2.babel_translation_directories}, 288 return f'''Component installed successfully: {selected_component["name"]} v{version} {k2.babel_translation_directories},
293 \n \n please wait installing requirments... 289 \n \n please wait installing requirments...
294 <meta http-equiv="refresh" content="0;url=/install-requirments/{selected_component["name"]}" />''' 290 <meta http-equiv="refresh" content="0;url=/install-requirments/{selected_component["name"]}" />'''
295 291
296 except Exception as e: 292 except Exception as e:
297 return f'Error installing component: {str(e)}' 293 return f'Error installing component: {str(e)}'
298 294
295
299 @components_bp.route('/install-requirments/<string:selected_component_name>', methods=['GET']) 296 @components_bp.route('/install-requirments/<string:selected_component_name>', methods=['GET'])
300 def install_requirments(selected_component_name): 297 def install_requirments(selected_component_name):
301 #menu items api 298 # menu items
302 response = requests.get(f"{k2.domain}{selected_component_name}/menu-items")
303 if response.status_code == 200:
304 data = response.json()
305
306 else:
307 data = []
308 # add component_name key for menu items
309 for item in data:
310 item['component_name'] = selected_component_name
311 file_path = 'components/menu.yml'
312 append_to_yaml_file(file_path, data)
313 get_admin_menu() 299 get_admin_menu()
314 300
315 #install requirements 301 # install requirements
316 requirements_file = os.path.join('components', selected_component_name, "requirements.txt") 302 requirements_file = os.path.join('components', selected_component_name, "requirements.txt")
317 if os.path.isfile(requirements_file): 303 if os.path.isfile(requirements_file):
318 pip_command = f"{k2.venv_bin_path}/python -m pip install -r {requirements_file}" 304 pip_command = f"{k2.venv_bin_path}/python -m pip install -r {requirements_file}"
319 subprocess.run(pip_command, shell=True, check=True) 305 subprocess.run(pip_command, shell=True, check=True)
320 return f'''Requirements installed successfully 306 return f'''Requirements installed successfully
321 \n \n please wait installing requirments components... 307 \n \n please wait installing requirments components...
322 <meta http-equiv="refresh" content="1;url=/install-requirments-components" />''' 308 <meta http-equiv="refresh" content="1;url=/install-requirments-components" />'''
323 309
310
324 @components_bp.route('/install-requirments-components') 311 @components_bp.route('/install-requirments-components')
325 def install_requirements_components(): 312 def install_requirements_components():
326 # Откриття файлу requirements_components.txt 313 # Откриття файлу requirements_components.txt
327 requirements_file = 'requirements_components.txt' 314 requirements_file = 'requirements_components.txt'
328 component_ids = None 315 component_ids = None
329 if os.path.isfile(requirements_file): 316 if os.path.isfile(requirements_file):
330 with open('requirements_components.txt', 'r') as file: 317 with open('requirements_components.txt', 'r') as file:
331 component_ids = file.read().splitlines() 318 component_ids = file.read().splitlines()
332 if component_ids: 319 if component_ids:
333 for component_id in component_ids: 320 for component_id in component_ids:
334 # Виклик роуту '/install_components/<string:component_name>' для кожної назви компоненти 321 # Виклик роуту '/install_components/<string:component_name>' для кожної назви компоненти
335 response = requests.get( 322 response = requests.get(
336 f'/install_components/{component_id}') 323 f'/install_components/{component_id}')
337 return f'Requirements components installed successfully <meta http-equiv="refresh" content="1;url=/dashboard" />' 324 return f'Requirements components installed successfully <meta http-equiv="refresh" content="1;url=/dashboard" />'
338 else: 325 else:
339 return f'<meta http-equiv="refresh" content="1;url=/dashboard" />' 326 return f'<meta http-equiv="refresh" content="1;url=/dashboard" />'
340 # Опрацювання відповіді (за потреби) 327 # Опрацювання відповіді (за потреби)
341 328
329
342 @components_bp.route('/remove_dependencies/<string:component_id>', methods=['GET']) 330 @components_bp.route('/remove_dependencies/<string:component_id>', methods=['GET'])
343 def remove_dependencies(component_id): 331 def remove_dependencies(component_id):
344 # Знаходимо компоненту за її ID 332 # Знаходимо компоненту за її ID
345 component = Component.query.get(component_id) 333 component = Component.query.get(component_id)
346 if not component: 334 if not component:
347 return 'Component not found <meta http-equiv="refresh" content="1;url=/dashboard" />' 335 return 'Component not found <meta http-equiv="refresh" content="1;url=/dashboard" />'
348 #remove menu items 336 # remove menu items
349 component_name = component.name 337 component_name = component.name
350 file_path = "components/menu.yml" 338 # file_path = "components/menu.yml"
351 remove_from_yaml_file(file_path, component_name) 339 # remove_from_yaml_file(file_path, component_name)
352 340 requests.get(f"{k2.domain}api/add-to-menu")
353 # remove routes 341 # remove routes
354 file_path = 'routes.py' 342 file_path = 'routes.py'
355 with open(file_path, 'r') as file: 343 with open(file_path, 'r') as file:
356 lines = file.readlines() 344 lines = file.readlines()
357 345
358 updated_lines = [line for line in lines if line.strip() not in component.dependencies] 346 updated_lines = [line for line in lines if line.strip() not in component.dependencies]
359 with open(file_path, 'w') as file: 347 with open(file_path, 'w') as file:
360 file.writelines(updated_lines) 348 file.writelines(updated_lines)
361 349
362 component.installed = False 350 component.installed = False
363 db.session.commit() 351 db.session.commit()
364 352
365 return 'Component successfully turn off <meta http-equiv="refresh" content="1;url=/dashboard" />' 353 return 'Component successfully turn off <meta http-equiv="refresh" content="1;url=/dashboard" />'
366 354
355
367 @components_bp.route('/add_dependencies/<string:component_id>', methods=['GET']) 356 @components_bp.route('/add_dependencies/<string:component_id>', methods=['GET'])
368 def add_dependencies(component_id): 357 def add_dependencies(component_id):
369
370 # Знаходимо компоненту за її ID 358 # Знаходимо компоненту за її ID
371 component = Component.query.get(component_id) 359 component = Component.query.get(component_id)
372 if not component: 360 if not component:
373 return 'Component not found <meta http-equiv="refresh" content="1;url=/dashboard" />' 361 return 'Component not found <meta http-equiv="refresh" content="1;url=/dashboard" />'
374 362
375 # Шлях до файлу, з якого потрібно видалити залежності
376 file_path = 'routes.py' 363 file_path = 'routes.py'
377 code = component.dependencies 364 code = component.dependencies
378 # Відкриття файлу у режимі дозапису 365 # Відкриття файлу у режимі дозапису
379 with open(file_path, 'a') as file: 366 with open(file_path, 'a') as file:
380 # Запис нового коду у файл 367 # Запис нового коду у файл
381 file.write(code) 368 file.write(code)
382 369
383 # Оновлюємо статус компоненти 370 # Оновлюємо статус компоненти
384 component.installed = True 371 component.installed = True
385 db.session.commit() 372 db.session.commit()
386 return 'Dependencies added successfully <meta http-equiv="refresh" content="1;url=/dashboard" />' 373 return 'Dependencies added successfully <meta http-equiv="refresh" content="1;url=/dashboard" />'
387 374
375
388 @components_bp.route('/remove-component/<string:component_id>') 376 @components_bp.route('/remove-component/<string:component_id>')
389 def remove_component(component_id): 377 def remove_component(component_id):
390 # Шлях до головної папки проекту 378 # Шлях до головної папки проекту
391 project_folder = 'components' 379 project_folder = 'components'
392 component = Component.query.get(component_id) 380 component = Component.query.get(component_id)
393 # Назва репозиторія 381 # Назва репозиторія
394 repository_name = component.name 382 repository_name = component.name
395 # Шлях до папки репозиторія в межах проекту 383 # Шлях до папки репозиторія в межах проекту
396 repository_folder = os.path.join(project_folder, repository_name) 384 repository_folder = os.path.join(project_folder, repository_name)
397 try: 385 try:
398 # Перевірка наявності папки репозиторія 386 # Перевірка наявності папки репозиторія
399 if os.path.exists(repository_folder): 387 if os.path.exists(repository_folder):
400 # Видалення папки репозиторія 388 # Видалення папки репозиторія
401 shutil.rmtree(repository_folder) 389 shutil.rmtree(repository_folder)
402 # Видаляємо компоненту з бази 390 # Видаляємо компоненту з бази
403 if component: 391 if component:
404 db.session.delete(component) 392 db.session.delete(component)
405 db.session.commit() 393 db.session.commit()
406 394
407 # Повертаємо повідомлення про успішне видалення 395 # Повертаємо повідомлення про успішне видалення
408 return 'Component removed successfully <meta http-equiv="refresh" content="1;url=/dashboard" />' 396 return 'Component removed successfully <meta http-equiv="refresh" content="1;url=/dashboard" />'
409 except Exception as e: 397 except Exception as e:
410 # Повертаємо повідомлення про помилку видалення 398 # Повертаємо повідомлення про помилку видалення
411 return 'Error removing component: ' + str(e) 399 return 'Error removing component: ' + str(e)
412 400
401
402
403
404 @components_bp.route('/component/add')
405 def component_add():
406 # components for install
407 try:
408 # GET-requests to API
409 response = requests.get(f'{k2.update_domain}api/components')
410 json_data = response.json()
411 for item in json_data:
412 item['button'] = f"{k2.domain}/install_components/{item['id']}"
413
414 except:
415 json_data = None
416 return jsonify(json_data)
417
418
419 @components_bp.route('/component/list')
420 def component_list():
421 # Встановлені компоненти
422 component_list = []
423 components = Component.query.all()
424 for component in components:
425 component_dict = {}
426 component_dict['name'] = component.name
427 component_dict['id'] = component.id
428 component_dict['description'] = component.description
429 component_dict['version'] = component.version
430 component_dict['button_off'] =f"{k2.domain}/remove_dependencies/{component.id}"
431 component_dict['button_on'] = f"{k2.domain}/add_dependencies/{component.id}"
432 component_dict['button_del'] = f"{k2.domain}/remove-component/{component.id}"
433 component_list.append(component_dict)
434 return jsonify(component_list)