summaryrefslogtreecommitdiff
path: root/front-end/src/App.jsx
blob: 104b561677fedd2479468919472429290d118532 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
// src/App.js
import React, { useState, useEffect } from 'react';
import axios from 'axios';
import './App.css';

const API_BASE_URL = import.meta.env.VITE_API_BASE_URL || 'http://127.0.0.1:4000';

function App() {
  const [videos, setVideos] = useState([]);
  const [channels, setChannels] = useState([]);
  const [loading, setLoading] = useState(true);
  const [channelsLoading, setChannelsLoading] = useState(true);
  const [error, setError] = useState(null);
  const [selectedChannelId, setSelectedChannelId] = useState('');
  const [expandedDescriptions, setExpandedDescriptions] = useState({});
  const [showAddSubscription, setShowAddSubscription] = useState(false);
  const [subscriptionUrl, setSubscriptionUrl] = useState('');
  const [timeBetweenFetches, setTimeBetweenFetches] = useState(300); // Default 5 minutes
  const [addingSubscription, setAddingSubscription] = useState(false);
  const [subscriptionError, setSubscriptionError] = useState(null);
  const [subscriptionSuccess, setSubscriptionSuccess] = useState(null);

  const fetchChannels = async () => {
    try {
      setChannelsLoading(true);
      const response = await axios.get(`${API_BASE_URL}/subs-info`);

      if (response.data && Array.isArray(response.data)) {
        const formattedChannels = response.data.map(subscription => {
          // Extract the ID and type from the _id field
          const isPlaylist = subscription._id.startsWith('yt:playlist:');
          const id = subscription._id.replace('yt:channel:', '').replace('yt:playlist:', '');
          const type = isPlaylist ? 'playlist' : 'channel';

          return {
            id: id,
            _id: subscription._id,
            type: type,
            title: subscription.title || id, // Use title if available, fallback to ID
            last_fetch: subscription.last_fetch,
            last_video_update: subscription.last_video_update,
            new_vids: subscription.new_vids,
            time_between_fetches: subscription.time_between_fetches,
            videos: subscription.videos
          };
        });
        setChannels(formattedChannels);
      }
    } catch (err) {
      console.error('Error fetching channels:', err);
      setError('Failed to fetch available subscriptions.');
    } finally {
      setChannelsLoading(false);
    }
  };

  const fetchVideos = async (channelId) => {
    try {
      setLoading(true);
      setError(null);
      setExpandedDescriptions({}); // Reset expanded states when fetching new videos

      // Find the full _id for the API call
      const subscription = channels.find(ch => ch.id === channelId);
      if (!subscription) return;

      const apiUrl = `${API_BASE_URL}/vid-from-link/${subscription._id}`;
      const response = await axios.get(apiUrl);

      if (response.data && Array.isArray(response.data)) {
        setVideos(response.data);
      } else {
        throw new Error('Invalid response format');
      }
    } catch (err) {
      setError('Failed to fetch videos. Please check the subscription and ensure the API is running.');
      console.error('Error fetching videos:', err);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchChannels();
  }, []);

  useEffect(() => {
    if (selectedChannelId) {
      fetchVideos(selectedChannelId);
    }
  }, [selectedChannelId]);

  const handleChannelChange = (e) => {
    setSelectedChannelId(e.target.value);
  };

  const handleRefreshChannels = () => {
    fetchChannels();
  };

  const toggleDescription = (videoId) => {
    setExpandedDescriptions(prev => ({
      ...prev,
      [videoId]: !prev[videoId]
    }));
  };

  const formatDate = (dateString) => {
    try {
      return new Date(dateString).toLocaleDateString('en-US', {
        year: 'numeric',
        month: 'short',
        day: 'numeric',
        hour: '2-digit',
        minute: '2-digit'
      });
    } catch {
      return dateString;
    }
  };

  const formatRelativeTime = (dateString) => {
    try {
      const date = new Date(dateString);
      const now = new Date();
      const diffInHours = Math.floor((now - date) / (1000 * 60 * 60));

      if (diffInHours < 1) {
        return 'Just now';
      } else if (diffInHours < 24) {
        return `${diffInHours}h ago`;
      } else {
        const diffInDays = Math.floor(diffInHours / 24);
        return `${diffInDays}d ago`;
      }
    } catch {
      return dateString;
    }
  };

  const formatDuration = (seconds) => {
    if (seconds < 0) {
      return '?:??';
    }

    const hours = Math.floor(seconds / 3600);
    const minutes = Math.floor((seconds % 3600) / 60);
    const remainingSeconds = seconds % 60;

    if (hours > 0) {
      return `${hours}:${minutes.toString().padStart(2, '0')}:${remainingSeconds.toString().padStart(2, '0')}`;
    } else {
      return `${minutes}:${remainingSeconds.toString().padStart(2, '0')}`;
    }
  };

  const handleAddSubscription = async (e) => {
    e.preventDefault();

    if (!subscriptionUrl.trim()) {
      setSubscriptionError('Please enter a YouTube channel/playlist URL');
      return;
    }

    try {
      setAddingSubscription(true);
      setSubscriptionError(null);
      setSubscriptionSuccess(null);

      const formData = new FormData();
      formData.append('url', subscriptionUrl.trim());
      formData.append('time_between_fetches', timeBetweenFetches.toString());

      const response = await axios.post(`${API_BASE_URL}/add-sub/`, formData, {
        headers: {
          'Content-Type': 'multipart/form-data',
        },
      });

      if (response.data) {
        setSubscriptionSuccess('Subscription added successfully!');
        setSubscriptionUrl('');
        setTimeBetweenFetches(300);
        setShowAddSubscription(false);

        // Refresh the subs list to include the new subscription
        fetchChannels();
      } else {
        throw new Error(response.data.error || 'Failed to add subscription');
      }
    } catch (err) {
      console.error('Error adding subscription:', err);
      setSubscriptionError(
        err.response?.data?.error ||
        err.message ||
        'Failed to add subscription. Please check the URL and try again.'
      );
    } finally {
      setAddingSubscription(false);
    }
  };

  const resetSubscriptionForm = () => {
    setSubscriptionUrl('');
    setTimeBetweenFetches(300);
    setSubscriptionError(null);
    setSubscriptionSuccess(null);
  };

  return (
    <div className="App">
      <header className="App-header">
        <h1>YouTube Subscriptions</h1>

        <div className="channel-selector">
          <div className="selector-header">
            <label htmlFor="channel-select">Select Subscription:</label>
            <button
              onClick={handleRefreshChannels}
              className="refresh-button"
              disabled={channelsLoading}
            >
              {channelsLoading ? 'Refreshing...' : '↻ Refresh'}
            </button>
          </div>

          <select
            id="channel-select"
            value={selectedChannelId}
            onChange={handleChannelChange}
            className="channel-select"
            disabled={channelsLoading || channels.length === 0}
          >
            {channelsLoading ? (
              <option value="">Loading subscriptions...</option>
            ) : channels.length === 0 ? (
              <option value="">No subscriptions available</option>
            ) : (
              <>
                <option value="">Choose a subscription...</option>
                {channels.map((channel) => (
                  <option key={channel.id} value={channel.id}>
                    {channel.type === 'playlist' ? '📋' : '📺'} {channel.title} - {channel.id} ({channel.videos} videos, {channel.new_vids} new)
                  </option>
                ))}
              </>
            )}
          </select>

          {selectedChannelId && channels.length > 0 && (
            <div className="channel-info">
              <p className="subscription-main">
                <strong>{channels.find(ch => ch.id === selectedChannelId)?.title} - {selectedChannelId}</strong>
                <span className="subscription-type">
                  ({channels.find(ch => ch.id === selectedChannelId)?.type})
                </span>
              </p>
              {(channels.find(ch => ch.id === selectedChannelId)?.last_video_update || channels.find(ch => ch.id === selectedChannelId)?.last_fetch) && (
                <p className="last-dates">
                  {channels.find(ch => ch.id === selectedChannelId)?.last_video_update && (
                    <span className="last-updated">Last updated: {formatRelativeTime(channels.find(ch => ch.id === selectedChannelId).last_video_update)}</span>
                  )}
                  {channels.find(ch => ch.id === selectedChannelId)?.last_fetch && (
                    <span className="last-fetched">Last fetched: {formatRelativeTime(channels.find(ch => ch.id === selectedChannelId).last_fetch)}</span>
                  )}
                </p>
              )}
            </div>
          )}
        </div>
        <div className="subscription-section">
          <button
            onClick={() => {
              setShowAddSubscription(!showAddSubscription);
              resetSubscriptionForm();
            }}
            className="add-subscription-toggle"
          >
            {showAddSubscription ? '✕ Cancel' : '+ Add Subscription'}
          </button>

          {showAddSubscription && (
            <div className="subscription-form-container">
              <form onSubmit={handleAddSubscription} className="subscription-form">
                <h3>Add New Subscription</h3>

                <div className="form-group">
                  <label htmlFor="subscription-url">YouTube Channel or Playlist URL:</label>
                  <input
                    id="subscription-url"
                    type="url"
                    value={subscriptionUrl}
                    onChange={(e) => setSubscriptionUrl(e.target.value)}
                    placeholder="https://www.youtube.com/channel/UCxxx... or https://www.youtube.com/playlist?list=PLxxx..."
                    className="subscription-input"
                    disabled={addingSubscription}
                  />
                </div>

                <div className="form-group">
                  <label htmlFor="time-between-fetches">
                    Fetch Interval (seconds):
                  </label>
                  <input
                    id="time-between-fetches"
                    type="number"
                    value={timeBetweenFetches}
                    onChange={(e) => setTimeBetweenFetches(parseInt(e.target.value) || 300)}
                    min="60"
                    max="86400"
                    className="subscription-input"
                    disabled={addingSubscription}
                  />
                  <small className="interval-help">
                    How often to check for new videos (default: 300s = 5 minutes)
                  </small>
                </div>

                {subscriptionError && (
                  <div className="subscription-error">{subscriptionError}</div>
                )}

                {subscriptionSuccess && (
                  <div className="subscription-success">{subscriptionSuccess}</div>
                )}

                <div className="form-actions">
                  <button
                    type="submit"
                    className="submit-subscription"
                    disabled={addingSubscription || !subscriptionUrl.trim()}
                  >
                    {addingSubscription ? 'Adding...' : 'Add Subscription'}
                  </button>
                </div>
              </form>
            </div>
          )}
        </div>
      </header>

      <main className="main-content">
        {channelsLoading && <div className="loading">Loading subscriptions...</div>}

        {error && (
          <div className="error">
            {error}
            <button onClick={() => selectedChannelId && fetchVideos(selectedChannelId)} className="retry-button">
              Try Again
            </button>
          </div>
        )}

        {!channelsLoading && channels.length === 0 && !error && (
          <div className="no-channels">
            <h3>No subscriptions available</h3>
            <p>No YouTube channels or playlists found in the subscription list.</p>
            <button onClick={handleRefreshChannels} className="retry-button">
              Refresh Subscriptions
            </button>
          </div>
        )}

        {loading && selectedChannelId && (
          <div className="loading">Loading videos for {channels.find(ch => ch.id === selectedChannelId)?.title}...</div>
        )}

        {!loading && !error && selectedChannelId && (
          <div className="videos-container">
            <h2>
              Latest Videos from {channels.find(ch => ch.id === selectedChannelId)?.title}
              <span className="subscription-id"> - {selectedChannelId}</span>
              {videos.length > 0 && ` (${videos.length})`}
            </h2>
            <div className="videos-grid">
              {videos.sort((a, b) => new Date(b.published) - new Date(a.published)).map((video) => (
                <div key={video.id} className="video-card">
                  <div className="video-thumbnail">
                    <img
                      src={video.thumbnail}
                      alt={video.title}
                      className="thumbnail-image"
                      onError={(e) => {
                        e.target.src = 'https://via.placeholder.com/300x180/333/fff?text=No+Thumbnail';
                      }}
                    />
                    <div className="duration-overlay">
                      {formatDuration(video.duration)}
                    </div>
                    <div className="play-button"></div>
                  </div>

                  <div className="video-info">
                    <h3
                      className="video-title"
                      title={video.title}
                    >
                      {video.title}
                    </h3>
                    <p className="video-author">
                      By: <a
                        href={video.author_channel}
                        target="_blank"
                        rel="noopener noreferrer"
                        className="channel-link"
                      >
                        {video.author}
                      </a>
                    </p>
                    <p className="video-date">Published: {formatDate(video.published)}</p>
                    {video.updated && (
                      <p className="video-date">Updated: {formatDate(video.updated)}</p>
                    )}

                    {video.summary && (
                      <div className="video-summary">
                        <p className={expandedDescriptions[video.id] ? 'expanded' : 'collapsed'}>
                          {video.summary}
                        </p>
                        {video.summary.length > 100 && (
                          <button
                            className="expand-button"
                            onClick={() => toggleDescription(video.id)}
                          >
                            {expandedDescriptions[video.id] ? 'Show Less' : 'Show More'}
                          </button>
                        )}
                      </div>
                    )}

                    <div className="video-actions">
                      <a
                        href={video.link}
                        target="_blank"
                        rel="noopener noreferrer"
                        className="watch-button"
                      >
                        Watch on YouTube
                      </a>
                    </div>
                  </div>
                </div>
              ))}
            </div>
          </div>
        )}

        {!loading && !error && selectedChannelId && videos.length === 0 && (
          <div className="no-videos">
            <h3>No videos found for this subscription</h3>
            <p>The channel or playlist might not have any videos or there was an issue loading them.</p>
          </div>
        )}

        {!channelsLoading && !selectedChannelId && channels.length > 0 && (
          <div className="no-selection">
            <h3>Please select a subscription to view videos</h3>
            <p>Choose a channel or playlist from the dropdown above to see its latest videos.</p>
          </div>
        )}
      </main>
    </div>
  );
}

export default App;