### Start Stream Function
Source: https://github.com/ammarbasha2011/my-restreamer/blob/main/public/index.html
Initiates a stream for a given destination ID by sending a POST request to the start stream API endpoint. Shows a toast message with the result and refreshes the destination list after a short delay if the stream starts successfully.
```javascript
window.startStream = async (id) => {
const response = await api.post(`/api/stream/start/${id}`, {});
showToast(await response.text(), !response.ok);
if (response.ok) setTimeout(refreshDestinations, 1000);
};
```
--------------------------------
### API Client for Restreamer
Source: https://github.com/ammarbasha2011/my-restreamer/blob/main/public/index.html
Defines an API client object with methods for GET, POST, and DELETE requests to interact with the backend. Handles basic response checking for success or failure.
```javascript
const grid = document.getElementById('destinations-grid');
const addDestBtn = document.getElementById('add-dest-btn');
const toast = document.getElementById('toast');
const api = {
get: (endpoint) => fetch(endpoint).then(res => res.ok ? res.json() : Promise.reject(res)),
post: (endpoint, body) => fetch(endpoint, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(body)
}),
delete: (endpoint) => fetch(endpoint, {
method: 'DELETE'
})
};
```
--------------------------------
### Initialize and Refresh Status
Source: https://github.com/ammarbasha2011/my-restreamer/blob/main/public/index.html
Sets up the initial loading of streaming destinations and schedules periodic updates. This code runs when the DOM is fully loaded.
```javascript
document.addEventListener('DOMContentLoaded', () => { refreshDestinations(); setInterval(refreshDestinations, 7000); });
```
--------------------------------
### Create Channel Card HTML
Source: https://github.com/ammarbasha2011/my-restreamer/blob/main/public/index.html
Generates the HTML structure for a single destination channel card, including status indicators, buttons, playlist display, and forms for uploading videos or adding YouTube URLs. It dynamically sets button states based on the streaming status.
```javascript
function createChannelCard(dest) {
const card = document.createElement('div');
card.className = 'card';
card.id = `dest-${dest.id}`;
card.innerHTML = `
Playlist
${dest.playlist.length > 0 ? dest.playlist.map(f => `- ${f}
`).join('') : '- Empty
'}
`;
return card;
}
```
--------------------------------
### Add New Destination
Source: https://github.com/ammarbasha2011/my-restreamer/blob/main/public/index.html
Handles the click event for the 'Add Destination' button. Prompts the user for a name and stream key, then sends a POST request to create a new destination. Refreshes the destination list upon successful creation.
```javascript
addDestBtn.addEventListener('click', async () => {
const name = prompt('Enter a name for the new stream channel:');
if (!name) return;
const key = prompt(`Enter the stream key for "${name}":`);
if (!key) return;
const response = await api.post('/api/destinations', {
name,
key
});
showToast(await response.text(), !response.ok);
if (response.ok) refreshDestinations();
});
```
--------------------------------
### Attach Video Upload Handlers
Source: https://github.com/ammarbasha2011/my-restreamer/blob/main/public/index.html
Attaches submit event listeners to all elements with the class 'upload-form'. When a form is submitted, it prevents the default action, extracts the destination ID, and sends the video file to the server. Provides user feedback via toast messages and updates the UI on success.
```javascript
function attachUploadHandlers() {
document.querySelectorAll('.upload-form').forEach(form => {
form.addEventListener('submit', async (e) => {
e.preventDefault();
const id = form.dataset.id;
const formData = new FormData(form);
const btn = form.querySelector('button');
btn.textContent = 'Uploading...';
btn.disabled = true;
const response = await fetch(`/api/upload/${id}`, {
method: 'POST',
body: formData
});
showToast(await response.text(), !response.ok);
btn.textContent = 'Upload Video';
btn.disabled = false;
if (response.ok) {
form.reset();
refreshDestinations();
}
});
});
}
```
--------------------------------
### Refresh Destinations List
Source: https://github.com/ammarbasha2011/my-restreamer/blob/main/public/index.html
Fetches the list of destinations from the API and updates the UI by clearing the existing grid and appending new channel cards. It also attaches event handlers for upload and YouTube forms after refreshing.
```javascript
async function refreshDestinations() {
try {
const destinations = await api.get('/api/destinations');
grid.innerHTML = ''; // Clear grid
destinations.forEach(dest => grid.appendChild(createChannelCard(dest)));
attachUploadHandlers();
attachYoutubeHandlers();
} catch (err) {
showToast('Error fetching data.', true);
}
}
```
--------------------------------
### Attach YouTube URL Handlers
Source: https://github.com/ammarbasha2011/my-restreamer/blob/main/public/index.html
Attaches submit event listeners to all elements with the class 'youtube-form'. When a form is submitted, it prevents the default action, extracts the destination ID and YouTube URL, and sends a POST request to add the video to the playlist. Provides user feedback and resets the form on success.
```javascript
function attachYoutubeHandlers() {
document.querySelectorAll('.youtube-form').forEach(form => {
form.addEventListener('submit', async (e) => {
e.preventDefault();
const id = form.dataset.id;
const url = form.querySelector('input[name="url"]')?.value;
const btn = form.querySelector('button');
btn.textContent = 'Downloading...';
btn.disabled = true;
const response = await api.post(`/api/youtube/add/${id}`, {
url
});
showToast(await response.text(), !response.ok);
btn.textContent = 'Add From URL';
btn.disabled = false;
if (response.ok) {
form.reset(); // No need to refresh here, the periodic refresh will catch it
}
});
});
}
```
--------------------------------
### Display Toast Notifications
Source: https://github.com/ammarbasha2011/my-restreamer/blob/main/public/index.html
Shows a temporary message to the user, either as an error or a standard notification. The toast is automatically hidden after 3 seconds.
```javascript
function showToast(message, isError = false) { const toast = document.getElementById('toast'); toast.textContent = message; toast.style.backgroundColor = isError ? 'var(--danger-color)' : '#333'; toast.classList.add('show'); setTimeout(() => toast.classList.remove('show'), 3000); }
```
--------------------------------
### Refresh Streaming Destinations
Source: https://github.com/ammarbasha2011/my-restreamer/blob/main/public/index.html
Fetches the current status of streaming destinations and updates the UI. This function is called on initial load and periodically.
```javascript
function refreshDestinations() { fetch('/api/destinations').then(response => response.json()).then(data => { const destinationsList = document.getElementById('destinations'); destinationsList.innerHTML = ''; data.forEach(dest => { const li = document.createElement('li'); li.textContent = `${dest.name}: ${dest.status}`; destinationsList.appendChild(li); }); }).catch(error => { console.error('Error fetching destinations:', error); showToast('Failed to load destinations', true); }); }
```
--------------------------------
### Clear Playlist Function
Source: https://github.com/ammarbasha2011/my-restreamer/blob/main/public/index.html
Provides a function to clear the playlist for a specific destination. It prompts the user for confirmation before sending a POST request to the clear playlist API endpoint. Refreshes the destination list upon successful clearing.
```javascript
window.clearPlaylist = async (id) => {
if (confirm('Are you sure you want to clear this playlist?')) {
const response = await api.post(`/api/playlist/clear/${id}`, {});
showToast(await response.text(), !respon
```
--------------------------------
### Delete Destination Function
Source: https://github.com/ammarbasha2011/my-restreamer/blob/main/public/index.html
Provides a function to delete a destination channel. It prompts for confirmation before sending a DELETE request to the API. Refreshes the destination list if the deletion is successful.
```javascript
window.deleteDestination = async (id) => {
if (confirm('Are you sure you want to delete this channel and all its videos?')) {
const response = await api.delete(`/api/destinations/${id}`);
showToast(await response.text(), !response.ok);
if (response.ok) refreshDestinations();
}
};
```
--------------------------------
### Stop Stream Function
Source: https://github.com/ammarbasha2011/my-restreamer/blob/main/public/index.html
Stops an ongoing stream for a given destination ID by sending a POST request to the stop stream API endpoint. Displays a toast message with the outcome and refreshes the destination list after a delay if the stream stops successfully.
```javascript
window.stopStream = async (id) => {
const response = await api.post(`/api/stream/stop/${id}`, {});
showToast(await response.text(), !response.ok);
if (response.ok) setTimeout(refreshDestinations, 1000);
};
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.