-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtemp_homeController.js
More file actions
293 lines (268 loc) · 10.3 KB
/
Copy pathtemp_homeController.js
File metadata and controls
293 lines (268 loc) · 10.3 KB
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
const db = require('../config/db');
const { success, error } = require('../utils/response');
// PLAYABLE health statuses GÇö must match channelController.js
const WORKING_STATUSES = ['online', 'playable', 'stable', 'unstable', 'unknown'];
const ALLOW_UNKNOWN = process.env.ALLOW_UNKNOWN_STREAMS === 'true';
const formatChannelRow = (req, row) => {
if (!row) return row;
const protocol = req.headers['x-forwarded-proto'] || req.protocol;
const baseUrl = `${protocol}://${req.get('host')}`;
const localUrl = row.local_logo_url ? `${baseUrl}${row.local_logo_url}` : null;
return {
...row,
logo_url: localUrl || row.logo_url,
local_logo_url: localUrl,
logo_status: row.logo_status || 'unknown',
};
};
// Fix #26: Cache schema introspection results at module level to avoid per-request queries
let mergedIntoColumnExists = null;
let healthStatusColumnExists = null;
async function checkMergedIntoColumn() {
if (mergedIntoColumnExists !== null) return mergedIntoColumnExists;
try {
const result = await db.query(
`SELECT 1 FROM information_schema.columns WHERE table_name='channels' AND column_name='merged_into_channel_id'`
);
mergedIntoColumnExists = result.rows.length > 0;
} catch (_) {
mergedIntoColumnExists = false;
}
return mergedIntoColumnExists;
}
async function checkHealthStatusColumn() {
if (healthStatusColumnExists !== null) return healthStatusColumnExists;
try {
const result = await db.query(
`SELECT 1 FROM information_schema.columns WHERE table_name='channels' AND column_name='health_status'`
);
healthStatusColumnExists = result.rows.length > 0;
} catch (_) {
healthStatusColumnExists = false;
}
return healthStatusColumnExists;
}
/**
* Build a health fragment and param list for playable channels.
* Returns { fragment, params, nextIndex }
*/
function buildHealthFilter(paramIndex) {
const statusList = WORKING_STATUSES.map((_, i) => `$${paramIndex + i}`).join(', ');
// Always allow NULL (unscanned) and 'unknown'; ALLOW_UNKNOWN kept for backwards compat
let fragment = `(c.health_status IS NULL OR c.health_status IN (${statusList}))`;
return { fragment, params: [...WORKING_STATUSES], nextIndex: paramIndex + WORKING_STATUSES.length };
}
/**
* Base WHERE conditions for home/playable channels.
* Returns { conditions, params, paramIndex }
*/
async function buildBaseConditions() {
const conditions = [
`c.status = 'active'`,
`c.is_hidden IS NOT TRUE`,
`c.is_removed IS NOT TRUE`,
`c.stream_url IS NOT NULL`,
`c.stream_url != ''`,
];
const params = [];
let paramIndex = 1;
// merged_into guard (migration 012) - cached check
if (await checkMergedIntoColumn()) {
conditions.unshift(`c.merged_into_channel_id IS NULL`);
}
// health filter - cached check
if (await checkHealthStatusColumn()) {
const { fragment, params: hp, nextIndex } = buildHealthFilter(paramIndex);
conditions.push(`(${fragment})`);
params.push(...hp);
paramIndex = nextIndex;
}
return { conditions, params, paramIndex };
}
/**
* Fetch N channels for a section, applying extra conditions/ordering.
*/
async function fetchSection(req, extraConditions, extraParams, orderSQL, limit, baseConditions, baseParams, baseParamIndex) {
const allConditions = [...baseConditions, ...extraConditions];
const allParams = [...baseParams, ...extraParams];
const sql = `
SELECT c.*, cat.name AS category_name
FROM channels c
LEFT JOIN categories cat ON c.category_id = cat.id
WHERE ${allConditions.join(' AND ')}
${orderSQL}
LIMIT $${allParams.length + 1}
`;
const result = await db.query(sql, [...allParams, limit]);
return result.rows.map(row => formatChannelRow(req, row));
}
/**
* GET /api/home
* Returns structured DTH-style home sections:
* - continue_watching (last 5 recently watched by the user, if auth)
* - premium_channels
* - popular_channels
* - featured_channels
* - categories: ordered list of category sections each with up to 15 channels
*/
exports.getHome = async (req, res) => {
try {
const userId = req.user?.id || null;
const { conditions: bc, params: bp } = await buildBaseConditions();
const JOIN = `LEFT JOIN categories cat ON c.category_id = cat.id`;
const BASE_WHERE = `WHERE ${bc.join(' AND ')}`;
// GöÇGöÇ 1. Continue Watching GöÇGöÇGöÇGöÇGöÇGöÇGöÇGöÇGöÇGöÇGöÇGöÇGöÇGöÇGöÇGöÇGöÇGöÇGöÇGöÇGöÇGöÇGöÇGöÇGöÇGöÇGöÇGöÇGöÇGöÇGöÇGöÇGöÇGöÇGöÇGöÇGöÇGöÇGöÇGöÇGöÇGöÇGöÇGöÇGöÇGöÇ
let continueWatching = [];
if (userId) {
try {
const cwRes = await db.query(
`SELECT DISTINCT ON (wh.channel_id)
c.*, cat.name AS category_name,
wh.watched_at
FROM watch_history wh
JOIN channels c ON c.id = wh.channel_id
LEFT JOIN categories cat ON c.category_id = cat.id
WHERE wh.user_id = $1
AND c.status = 'active'
AND c.stream_url IS NOT NULL AND c.stream_url != ''
ORDER BY wh.channel_id, wh.watched_at DESC
LIMIT 10`,
[userId]
);
const sorted = cwRes.rows.sort((a, b) => new Date(b.watched_at) - new Date(a.watched_at));
continueWatching = sorted.slice(0, 5).map(row => formatChannelRow(req, row));
} catch (e) {
console.error('[home] continue_watching error:', e.message);
}
}
// GöÇGöÇ 2-5. Run all four sections in parallel for faster response GöÇGöÇGöÇGöÇGöÇGöÇGöÇGöÇGöÇ
const [premiumResult, popularResult, featuredResult, catChannelsRes] = await Promise.all([
// 2. Premium Channels
db.query(
`SELECT c.*, cat.name AS category_name
FROM channels c ${JOIN}
${BASE_WHERE}
AND c.is_premium = true
ORDER BY
CASE WHEN c.is_featured = true THEN 0 ELSE 1 END,
COALESCE(c.popularity_score, 0) DESC,
COALESCE(c.sort_order, 999) ASC,
c.name ASC
LIMIT 20`,
bp
).catch(e => { console.error('[home] premium_channels error:', e.message); return { rows: [] }; }),
// 3. Popular Channels
db.query(
`SELECT c.*, cat.name AS category_name
FROM channels c ${JOIN}
${BASE_WHERE}
ORDER BY
CASE WHEN c.is_featured = true THEN 0 ELSE 1 END,
CASE WHEN c.is_popular = true THEN 0 ELSE 1 END,
COALESCE(c.popularity_score, 0) DESC,
COALESCE(c.watch_count, 0) DESC,
COALESCE(c.sort_order, 999) ASC,
c.name ASC
LIMIT 20`,
bp
).catch(e => { console.error('[home] popular_channels error:', e.message); return { rows: [] }; }),
// 4. Featured Channels
db.query(
`SELECT c.*, cat.name AS category_name
FROM channels c ${JOIN}
${BASE_WHERE}
AND c.is_featured = true
ORDER BY
COALESCE(c.popularity_score, 0) DESC,
COALESCE(c.sort_order, 999) ASC,
c.name ASC
LIMIT 15`,
bp
).catch(e => { console.error('[home] featured_channels error:', e.message); return { rows: [] }; }),
// 5. Category Sections GÇö single CTE query with all required fields for logo formatting
db.query(
`WITH ranked_channels AS (
SELECT
c.*,
cat.name AS category_name,
cat.icon_url,
cat.sort_order AS cat_sort_order,
ROW_NUMBER() OVER (
PARTITION BY c.category_id
ORDER BY
CASE WHEN c.is_featured = true THEN 0 ELSE 1 END,
COALESCE(c.popularity_score, 0) DESC,
COALESCE(c.watch_count, 0) DESC,
COALESCE(c.sort_order, 999) ASC,
c.name ASC
) AS rn
FROM channels c
LEFT JOIN categories cat ON c.category_id = cat.id
${BASE_WHERE}
AND cat.status = 'active'
AND c.category_id IS NOT NULL
)
SELECT
cat.id,
cat.name,
cat.icon_url,
cat.sort_order AS cat_sort_order,
JSON_AGG(
JSON_BUILD_OBJECT(
'id', rc.id,
'name', rc.name,
'logo_url', rc.logo_url,
'local_logo_url', rc.local_logo_url,
'logo_status', rc.logo_status,
'stream_url', rc.stream_url,
'backup_stream_url', rc.backup_stream_url,
'health_status', rc.health_status,
'category_id', rc.category_id,
'category_name', rc.category_name,
'language', rc.language,
'quality', rc.quality,
'is_premium', rc.is_premium,
'is_featured', rc.is_featured,
'is_popular', rc.is_popular,
'popularity_score', rc.popularity_score,
'watch_count', rc.watch_count,
'sort_order', rc.sort_order,
'referrer', rc.referrer,
'user_agent', rc.user_agent
) ORDER BY rc.rn
) AS channels
FROM categories cat
LEFT JOIN ranked_channels rc ON cat.id = rc.category_id AND rc.rn <= 15
WHERE cat.status = 'active'
GROUP BY cat.id
HAVING COUNT(rc.id) > 0
ORDER BY cat.sort_order ASC, cat.name ASC`,
bp
).catch(e => { console.error('[home] categories error:', e.message); return { rows: [] }; }),
]);
const premiumChannels = premiumResult.rows.map(row => formatChannelRow(req, row));
const popularChannels = popularResult.rows.map(row => formatChannelRow(req, row));
const featuredChannels = featuredResult.rows.map(row => formatChannelRow(req, row));
const categories = catChannelsRes.rows.map(row => ({
id: row.id,
name: row.name,
icon_url: row.icon_url,
sort_order: row.cat_sort_order,
channel_count: row.channels?.length || 0,
channels: (row.channels || []).map(ch => formatChannelRow(req, ch)),
}));
return res.json({
success: true,
data: {
continue_watching: continueWatching,
premium_channels: premiumChannels,
popular_channels: popularChannels,
featured_channels: featuredChannels,
categories,
},
});
} catch (err) {
console.error('[home] getHome error:', err);
return error(res, 'Failed to load home data', 500);
}
};