|
| 1 | +try: |
| 2 | + from methods.regular.regular_api import * |
| 3 | +except: |
| 4 | + from default.methods.regular.regular_api import * |
| 5 | +from shared.permissions.super_admin_only import Super_Admin |
| 6 | +from shared.data_tools_core import Data_tools |
| 7 | +import uuid |
| 8 | +import tempfile |
| 9 | +from shared.database.image import Image |
| 10 | +from shared.database.system_configs.system_configs import SystemConfigs |
| 11 | +import mimetypes |
| 12 | +data_tools = Data_tools().data_tools |
| 13 | + |
| 14 | +@routes.route('/api/v1/admin/set-logo', |
| 15 | + methods = ['POST']) |
| 16 | +@Super_Admin.is_super() |
| 17 | +def api_admin_set_logo(): |
| 18 | + log = regular_log.default() |
| 19 | + with sessionMaker.session_scope() as session: |
| 20 | + binary_file = request.files.get('file') |
| 21 | + if not binary_file: |
| 22 | + log['error']['file'] = 'No file provided' |
| 23 | + return jsonify(log = log), 400 |
| 24 | + |
| 25 | + system_configs, log = admin_set_logo_core(session = session, file_binary = binary_file, log = log) |
| 26 | + if regular_log.log_has_error(log): |
| 27 | + return jsonify(log = log), 400 |
| 28 | + |
| 29 | + return jsonify(sytem_configs = system_configs) |
| 30 | +def admin_set_logo_core(session, file_binary, log = regular_log.default()): |
| 31 | + # Upload to temp dir |
| 32 | + temp_dir = tempfile.gettempdir() |
| 33 | + extension = file_binary.filename.split('.')[len(file_binary.filename.split('.')) - 1] |
| 34 | + allowed_formats = ['jpg', 'png', 'webp', 'jpeg'] |
| 35 | + if extension not in allowed_formats: |
| 36 | + log['error']['image'] = f'Invalid image format only support {allowed_formats}.' |
| 37 | + return None, log |
| 38 | + file_path = f"{temp_dir}/{uuid.uuid4()}.{extension}" |
| 39 | + file_binary.save(file_path) |
| 40 | + blob_path = f'{settings.SYSTEM_DATA_BASE_DIR}{file_binary.filename}' |
| 41 | + # Upload to Cloud Storage |
| 42 | + |
| 43 | + content_type = mimetypes.guess_type(file_binary.filename) |
| 44 | + print('FILE PATH', file_path, content_type) |
| 45 | + data_tools.upload_to_cloud_storage( |
| 46 | + temp_local_path = file_path, |
| 47 | + blob_path = blob_path, |
| 48 | + content_type = content_type[0] |
| 49 | + ) |
| 50 | + # Save new image Object |
| 51 | + new_image = Image(original_filename = file_binary.filename, url_signed_blob_path = blob_path) |
| 52 | + session.add(new_image) |
| 53 | + session.flush() |
| 54 | + # Save System Config |
| 55 | + config = SystemConfigs.set_logo(session = session, image_id = new_image.id) |
| 56 | + config_data = config.serialize(session = session) |
| 57 | + return config_data, log |
0 commit comments