Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
__pycache__/
eco_project/backend/gcloud-credentials.json
server.log
eco_project/backend/videos.json
eco_project/backend/videos.json.lock
59 changes: 52 additions & 7 deletions eco_project/backend/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -465,14 +465,59 @@ def livestock():
]
return jsonify(mock_data)

@app.route('/api/videos')
import json
import bleach
from filelock import FileLock

# Path for the videos JSON file and its lock file
VIDEOS_FILE = os.path.join(app.root_path, 'videos.json')
LOCK_FILE = os.path.join(app.root_path, 'videos.json.lock')

@app.route('/api/videos', methods=['GET', 'POST'])
def videos():
mock_videos = [
{"title": "The Problem with Traditional Agriculture", "url": "https://www.youtube.com/embed/Yp7XFAE8kr4"},
{"title": "Agroecology for Sustainable Food Systems", "url": "https://www.youtube.com/embed/6OyGlwYUS5w"},
{"title": "How does an organic farmer conserve water?", "url": "https://www.youtube.com/embed/32ZMYDbItQ8"}
]
return jsonify(mock_videos)
if request.method == 'POST':
# Handle video submission
data = request.get_json()
title = data.get('title')
url = data.get('url')

if not title or not url:
return jsonify({"error": "Title and URL are required."}), 400

# Sanitize user input
sanitized_title = bleach.clean(title)
sanitized_url = bleach.clean(url)

# A simple check to ensure the URL is a YouTube embed URL
if not sanitized_url.startswith("https://www.youtube.com/embed/"):
return jsonify({"error": "Invalid YouTube URL."}), 400

with FileLock(LOCK_FILE):
# Read existing videos
try:
with open(VIDEOS_FILE, 'r') as f:
videos = json.load(f)
except (FileNotFoundError, json.JSONDecodeError):
videos = []

# Add new video
videos.append({"title": sanitized_title, "url": sanitized_url})

# Write updated videos list back to the file
with open(VIDEOS_FILE, 'w') as f:
json.dump(videos, f, indent=4)

return jsonify({"message": "Video added successfully!"}), 201

else: # GET request
# Return the list of videos
with FileLock(LOCK_FILE):
try:
with open(VIDEOS_FILE, 'r') as f:
videos = json.load(f)
return jsonify(videos)
except (FileNotFoundError, json.JSONDecodeError):
return jsonify([])

@app.route('/api/chat', methods=['POST'])
def chat():
Expand Down
9 changes: 9 additions & 0 deletions eco_project/backend/static/videos.html
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,15 @@ <h1>Video Gallery</h1>
</nav>
</header>
<main>
<section id="video-submission">
<h2>Share a Video</h2>
<form id="video-form">
<input type="text" id="video-title" placeholder="Video Title" required>
<input type="url" id="video-url" placeholder="Video URL" required>
<button type="submit">Share Video</button>
</form>
<div id="error-message" class="error"></div>
</section>
<section id="videos">
<h2>Featured Videos</h2>
<div class="video-container">
Expand Down
56 changes: 54 additions & 2 deletions eco_project/backend/static/videos.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
document.addEventListener('DOMContentLoaded', () => {
const videoContainer = document.querySelector('.video-container');
const videoForm = document.getElementById('video-form');

async function fetchVideos() {
try {
Expand All @@ -15,17 +16,68 @@ document.addEventListener('DOMContentLoaded', () => {
}

function displayVideos(videos) {
if (videos.length === 0) {
videoContainer.innerHTML = '<p>No videos to display.</p>';
return;
}
let html = '';
videos.forEach(video => {
const embedUrl = video.url.includes('youtube.com/watch?v=')
? video.url.replace('watch?v=', 'embed/')
: video.url;

html += `
<div class="video-item">
<iframe src="${video.url}" frameborder="0" allowfullscreen></iframe>
<iframe src="${embedUrl}" frameborder="0" allowfullscreen></iframe>
<div class="video-item-title">${video.title}</div>
</div>
`;
});
videoContainer.innerHTML = html;
}

videoForm.addEventListener('submit', async (event) => {
event.preventDefault();

const titleInput = document.getElementById('video-title');
const urlInput = document.getElementById('video-url');
const errorMessage = document.getElementById('error-message');

errorMessage.textContent = '';

let videoUrl = urlInput.value;
if (videoUrl.includes('youtube.com/watch?v=')) {
videoUrl = videoUrl.replace('watch?v=', 'embed/');
}

const newVideo = {
title: titleInput.value,
url: videoUrl,
};

try {
const response = await fetch('/api/videos', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(newVideo),
});

if (!response.ok) {
const errorData = await response.json();
throw new Error(errorData.error || `HTTP error! status: ${response.status}`);
}

titleInput.value = '';
urlInput.value = '';

fetchVideos(); // Refresh the list of videos
} catch (error) {
console.error('Failed to submit video:', error);
errorMessage.textContent = `Error: ${error.message}`;
}
});

fetchVideos();
});
});
14 changes: 14 additions & 0 deletions eco_project/backend/videos.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
[
{
"title": "The Problem with Traditional Agriculture",
"url": "https://www.youtube.com/embed/Yp7XFAE8kr4"
},
{
"title": "Agroecology for Sustainable Food Systems",
"url": "https://www.youtube.com/embed/6OyGlwYUS5w"
},
{
"title": "How does an organic farmer conserve water?",
"url": "https://www.youtube.com/embed/32ZMYDbItQ8"
}
]
Empty file.
Loading