| 1 | module main |
| 2 | |
| 3 | import os |
| 4 | |
| 5 | const default_avatar_name = 'default_avatar.png' |
| 6 | const assets_path = 'assets' |
| 7 | const avatar_max_file_size = 1 * 1024 * 1024 // 1 megabyte |
| 8 | |
| 9 | const supported_mime_types = [ |
| 10 | 'image/jpeg', |
| 11 | 'image/png', |
| 12 | 'image/webp', |
| 13 | ] |
| 14 | |
| 15 | fn validate_avatar_content_type(content_type string) bool { |
| 16 | return supported_mime_types.contains(content_type) |
| 17 | } |
| 18 | |
| 19 | fn extract_file_extension_from_mime_type(mime_type string) !string { |
| 20 | is_valid_mime_type := validate_avatar_content_type(mime_type) |
| 21 | |
| 22 | if !is_valid_mime_type { |
| 23 | return error('MIME type is not supported') |
| 24 | } |
| 25 | |
| 26 | mime_parts := mime_type.split('/') |
| 27 | |
| 28 | return mime_parts[1] |
| 29 | } |
| 30 | |
| 31 | fn validate_avatar_file_size(content string) bool { |
| 32 | return content.len <= avatar_max_file_size |
| 33 | } |
| 34 | |
| 35 | fn (app App) build_avatar_file_path(avatar_filename string) string { |
| 36 | relative_path := os.join_path(app.config.avatars_path, avatar_filename) |
| 37 | |
| 38 | return os.abs_path(relative_path) |
| 39 | } |
| 40 | |
| 41 | fn (app App) build_avatar_file_url(avatar_filename string) string { |
| 42 | clean_path := app.config.avatars_path.trim_string_left('./') |
| 43 | return os.join_path('/', clean_path, avatar_filename) |
| 44 | } |
| 45 | |
| 46 | fn (app App) write_user_avatar(avatar_filename string, file_content string) bool { |
| 47 | path := os.join_path(app.config.avatars_path, avatar_filename) |
| 48 | |
| 49 | os.write_file(path, file_content) or { return false } |
| 50 | |
| 51 | return true |
| 52 | } |
| 53 | |
| 54 | fn (app App) prepare_user_avatar_url(avatar_filename_or_url string) string { |
| 55 | is_url := avatar_filename_or_url.starts_with('http') |
| 56 | is_default_avatar := avatar_filename_or_url == default_avatar_name |
| 57 | if is_url { |
| 58 | return avatar_filename_or_url |
| 59 | } |
| 60 | if is_default_avatar { |
| 61 | return os.join_path('/', assets_path, avatar_filename_or_url) |
| 62 | } |
| 63 | return app.build_avatar_file_url(avatar_filename_or_url) |
| 64 | } |
| 65 | |