Skip to content

Commit

Permalink
fixed uploading files functionality and finding files
Browse files Browse the repository at this point in the history
  • Loading branch information
danilojezernik committed Oct 12, 2024
1 parent 2e886ce commit 62aa7a1
Show file tree
Hide file tree
Showing 21 changed files with 488 additions and 182 deletions.
25 changes: 25 additions & 0 deletions .idea/developer-tools.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 6 additions & 0 deletions .idea/httpClient.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

9 changes: 9 additions & 0 deletions .idea/inspectionProfiles/Project_Default.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 0 additions & 3 deletions .idea/misc.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -22,4 +22,5 @@ openai~=1.44.0
pip~=24.0
distro~=1.9.0
APScheduler~=3.10.4
attrs~=24.2.0
attrs~=24.2.0
nltk~=3.9.1
4 changes: 3 additions & 1 deletion src/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@
# Imported routes
from src.routes import index, blog, login, user, experiences, links, register, contact, projects, newsletter, \
subscriber, comments, github, book, media, angular, vue, typescript, javascript, mongodb, python, language, chatgpt, \
chat, dev_to_api
chat, dev_to_api, send_sms, screenshot
from src.services import db
from src.tags_metadata import tags_metadata
from src.utils.domain_to_txt import write_fields_to_txt
Expand All @@ -44,8 +44,10 @@

app.include_router(index.router, prefix='/index', tags=['Index'])
app.include_router(blog.router, prefix='/blog', tags=['Blog'])
app.include_router(send_sms.router, prefix='/sms', tags=['SMS'])
app.include_router(dev_to_api.router, prefix='/dev', tags=['Dev'])
app.include_router(media.router, prefix='/media', tags=['Media'])
app.include_router(screenshot.router, prefix='/screenshot', tags=['Media'])
app.include_router(github.router, prefix='/github', tags=['Github'])
app.include_router(book.router, prefix='/book', tags=['Book'])

Expand Down
8 changes: 8 additions & 0 deletions src/env.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,3 +33,11 @@
# TESTING
EMAIL_1 = str(os.getenv('EMAIL_1'))
EMAIL_2 = str(os.getenv('EMAIL_2'))

# TWILIO
ACCOUNT_SID = str(os.getenv('ACCOUNT_SID'))
AUTH_TOKEN = str(os.getenv('AUTH_TOKEN'))
PHONE_NUMBER_TWILIO = str(os.getenv('PHONE_NUMBER_TWILIO'))
PHONE_NUMBER_MY = str(os.getenv('PHONE_NUMBER_MY'))

NGROK = str(os.getenv('NGROK'))
34 changes: 18 additions & 16 deletions src/routes/angular.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@

# Define the root media directory and the subdirectory for media files
angular_root_directory = 'media' # The root directory where all media files are stored
angular_media_directory = os.path.join(angular_root_directory, 'angular_media') # Subdirectory for specific media files
media_directory = os.path.join(angular_root_directory, 'angular_media') # Subdirectory for specific media files

router = APIRouter()

Expand Down Expand Up @@ -246,19 +246,19 @@ async def get_angular_image(filename: str):
:param filename: The name of the file to be retrieved.
:return: The file if found; otherwise, raises a 404 error.
"""
file_path = os.path.join(angular_media_directory, filename)
file_path = os.path.join(media_directory, filename)

# Check if the file exists
if not os.path.exists(file_path):
# Raise a 404 error if the file is not found
raise HTTPException(status_code=404, detail='Image not found!')
return {"message": f"Image '{filename}' not found in the directory."}

try:
# Return the file as a response
return FileResponse(file_path)
except Exception as e:
# Raise an HTTP 500 error if there was an issue serving the file
raise HTTPException(status_code=500, detail=f'Error serving file: {str(e)}')
return {"message": f"Error serving file: {str(e)}"}


# PRIVATE
Expand All @@ -275,18 +275,17 @@ async def upload_angular_file(file: UploadFile = File(...), current_user: User =
:return: A success message indicating the file was uploaded.
"""
try:
upload_directory = angular_media_directory
os.makedirs(upload_directory, exist_ok=True)
os.makedirs(media_directory, exist_ok=True)
contents = await file.read()
file_name = file.filename if file.filename else 'uploaded_file'
file_path = os.path.join(upload_directory, file_name)
file_path = os.path.join(media_directory, file_name)
with open(file_path, 'wb') as f:
f.write(contents)
except Exception as e:
raise HTTPException(status_code=500, detail=f'There was an error uploading the file: {str(e)}')
finally:
await file.close()
return {"message": f"Successfully uploaded {file_name} to {upload_directory}"}
return {"message": f"Successfully uploaded {file_name} to {media_directory}"}



Expand All @@ -298,12 +297,16 @@ async def list_angular_images(current_user: User = Depends(require_role('admin')
:return: A list of filenames in the upload directory.
"""
upload_directory = angular_media_directory
if not os.path.exists(upload_directory):
raise HTTPException(status_code=404, detail='Upload directory not found!')
image_names = [f for f in os.listdir(upload_directory) if os.path.isfile(os.path.join(upload_directory, f))]
return {"images": image_names}
if not os.path.exists(media_directory):
return {"images": [], "message": "No images found. Directory does not exist."}

image_names = [f for f in os.listdir(media_directory) if os.path.isfile(os.path.join(media_directory, f))]
# If no images are found, return an empty list with a message
if not image_names:
return {"images": [], "message": "No images found in the directory."}

# Return the list of filenames
return {"images": image_names}

# Delete a media file by filename
@router.delete("/media/{filename}")
Expand All @@ -315,12 +318,11 @@ async def delete_angular_image(filename: str, current_user: User = Depends(requi
:param filename: The name of the file to be deleted.
:return: A success message if the file is deleted; otherwise, raises a 404 error.
"""
upload_directory = angular_media_directory
file_path = os.path.join(upload_directory, filename)
file_path = os.path.join(media_directory, filename)
if not os.path.exists(file_path):
raise HTTPException(status_code=404, detail="Image not found")
try:
os.remove(file_path)
except Exception as e:
raise HTTPException(status_code=500, detail=f"There was an error deleting the file: {str(e)}")
return {"message": f"Successfully deleted {filename} from {upload_directory}"}
return {"message": f"Successfully deleted {filename} from {media_directory}"}
35 changes: 19 additions & 16 deletions src/routes/blog.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,8 @@
from src.template import blog_notifications

# Define the root media directory and the subdirectory for media files
blogs_root_directory = 'media' # The root directory where all media files are stored
blogs_media_directory = os.path.join(blogs_root_directory, 'blogs_media') # Subdirectory for specific media files
root_directory = 'media' # The root directory where all media files are stored
media_directory = os.path.join(root_directory, 'blogs_media') # Subdirectory for specific media files

router = APIRouter()

Expand Down Expand Up @@ -254,18 +254,17 @@ async def upload_blog_file(file: UploadFile = File(...), current_user: User = D
:return: A success message indicating the file was uploaded.
"""
try:
upload_directory = blogs_media_directory
os.makedirs(upload_directory, exist_ok=True)
os.makedirs(media_directory, exist_ok=True)
contents = await file.read()
file_name = file.filename if file.filename else 'uploaded_file'
file_path = os.path.join(upload_directory, file_name)
file_path = os.path.join(media_directory, file_name)
with open(file_path, 'wb') as f:
f.write(contents)
except Exception as e:
raise HTTPException(status_code=500, detail=f'There was an error uploading the file: {str(e)}')
finally:
await file.close()
return {"message": f"Successfully uploaded {file_name} to {upload_directory}"}
return {"message": f"Successfully uploaded {file_name} to {media_directory}"}


# Retrieve a media file by filename
Expand All @@ -277,19 +276,19 @@ async def get_blog_image(filename: str):
:param filename: The name of the file to be retrieved.
:return: The file if found; otherwise, raises a 404 error.
"""
file_path = os.path.join(blogs_media_directory, filename)
file_path = os.path.join(media_directory, filename)

# Check if the file exists
if not os.path.exists(file_path):
# Raise a 404 error if the file is not found
raise HTTPException(status_code=404, detail='Image not found!')
return {"message": f"Image '{filename}' not found in the directory."}

try:
# Return the file as a response
return FileResponse(file_path)
except Exception as e:
# Raise an HTTP 500 error if there was an issue serving the file
raise HTTPException(status_code=500, detail=f'Error serving file: {str(e)}')
return {"message": f"Error serving file: {str(e)}"}


# List all media files
Expand All @@ -300,10 +299,15 @@ async def list_blog_images(current_user: User = Depends(require_role('admin'))):
:return: A list of filenames in the upload directory.
"""
upload_directory = blogs_media_directory
if not os.path.exists(upload_directory):
raise HTTPException(status_code=404, detail='Upload directory not found!')
image_names = [f for f in os.listdir(upload_directory) if os.path.isfile(os.path.join(upload_directory, f))]
if not os.path.exists(media_directory):
return {"images": [], "message": "No images found. Directory does not exist."}

image_names = [f for f in os.listdir(media_directory) if os.path.isfile(os.path.join(media_directory, f))]
# If no images are found, return an empty list with a message
if not image_names:
return {"images": [], "message": "No images found in the directory."}

# Return the list of filenames
return {"images": image_names}


Expand All @@ -317,12 +321,11 @@ async def delete_blog_image(filename: str, current_user: User = Depends(require
:param filename: The name of the file to be deleted.
:return: A success message if the file is deleted; otherwise, raises a 404 error.
"""
upload_directory = blogs_media_directory
file_path = os.path.join(upload_directory, filename)
file_path = os.path.join(media_directory, filename)
if not os.path.exists(file_path):
raise HTTPException(status_code=404, detail="Image not found")
try:
os.remove(file_path)
except Exception as e:
raise HTTPException(status_code=500, detail=f"There was an error deleting the file: {str(e)}")
return {"message": f"Successfully deleted {filename} from {upload_directory}"}
return {"message": f"Successfully deleted {filename} from {media_directory}"}
33 changes: 18 additions & 15 deletions src/routes/book.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@

# Define the root media directory and the subdirectory for media files
media_root_directory = 'media' # The root directory where all media files are stored
book_media_directory = os.path.join(media_root_directory, 'books_media') # Subdirectory for specific media files
media_directory = os.path.join(media_root_directory, 'books_media') # Subdirectory for specific media files

router = APIRouter()

Expand Down Expand Up @@ -163,18 +163,17 @@ async def upload_book_file(file: UploadFile = File(...), current_user: User = De
:return: A success message indicating the file was uploaded.
"""
try:
upload_directory = book_media_directory
os.makedirs(upload_directory, exist_ok=True)
os.makedirs(media_directory, exist_ok=True)
contents = await file.read()
file_name = file.filename if file.filename else 'uploaded_file'
file_path = os.path.join(upload_directory, file_name)
file_path = os.path.join(media_directory, file_name)
with open(file_path, 'wb') as f:
f.write(contents)
except Exception as e:
raise HTTPException(status_code=500, detail=f'There was an error uploading the file: {str(e)}')
finally:
await file.close()
return {"message": f"Successfully uploaded {file_name} to {upload_directory}"}
return {"message": f"Successfully uploaded {file_name} to {media_directory}"}


# Retrieve a media file by filename
Expand All @@ -186,19 +185,19 @@ async def get_book_image(filename: str):
:param filename: The name of the file to be retrieved.
:return: The file if found; otherwise, raises a 404 error.
"""
file_path = os.path.join(book_media_directory, filename)
file_path = os.path.join(media_directory, filename)

# Check if the file exists
if not os.path.exists(file_path):
# Raise a 404 error if the file is not found
raise HTTPException(status_code=404, detail='Image not found!')
return {"message": f"Image '{filename}' not found in the directory."}

try:
# Return the file as a response
return FileResponse(file_path)
except Exception as e:
# Raise an HTTP 500 error if there was an issue serving the file
raise HTTPException(status_code=500, detail=f'Error serving file: {str(e)}')
return {"message": f"Error serving file: {str(e)}"}


# List all media files
Expand All @@ -209,10 +208,15 @@ async def list_book_images(current_user: User = Depends(require_role('admin'))):
:return: A list of filenames in the upload directory.
"""
upload_directory = book_media_directory
if not os.path.exists(upload_directory):
raise HTTPException(status_code=404, detail='Upload directory not found!')
image_names = [f for f in os.listdir(upload_directory) if os.path.isfile(os.path.join(upload_directory, f))]
if not os.path.exists(media_directory):
return {"images": [], "message": "No images found. Directory does not exist."}

image_names = [f for f in os.listdir(media_directory) if os.path.isfile(os.path.join(media_directory, f))]
# If no images are found, return an empty list with a message
if not image_names:
return {"images": [], "message": "No images found in the directory."}

# Return the list of filenames
return {"images": image_names}


Expand All @@ -226,12 +230,11 @@ async def delete_book_image(filename: str, current_user: User = Depends(require_
:param filename: The name of the file to be deleted.
:return: A success message if the file is deleted; otherwise, raises a 404 error.
"""
upload_directory = book_media_directory
file_path = os.path.join(upload_directory, filename)
file_path = os.path.join(media_directory, filename)
if not os.path.exists(file_path):
raise HTTPException(status_code=404, detail="Image not found")
try:
os.remove(file_path)
except Exception as e:
raise HTTPException(status_code=500, detail=f"There was an error deleting the file: {str(e)}")
return {"message": f"Successfully deleted {filename} from {upload_directory}"}
return {"message": f"Successfully deleted {filename} from {media_directory}"}
Loading

0 comments on commit 62aa7a1

Please sign in to comment.