File size: 10,607 Bytes
1ae753d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
const axios = require('axios');
const crypto = require('./crypto');

let GIST_ID = process.env.GIST_ID;
const GITHUB_TOKEN = process.env.GITHUB_TOKEN;

if (!GITHUB_TOKEN) {
    console.error('❌ GITHUB_TOKEN not set!');
}

let GIST_API = GIST_ID ? `https://api.github.com/gists/${GIST_ID}` : null;

// Cache
let usersCache = null;
let scheduleCache = null;
let cacheTime = 0;
const CACHE_DURATION = 60000; // 1 minute
let gistInitialized = false;

// Создание нового Gist с дефолтными данными
async function createDefaultGist() {
    if (!GITHUB_TOKEN) {
        console.error('Cannot create Gist without GITHUB_TOKEN');
        return null;
    }

    try {
        console.log('📝 Creating new Gist with default data...');
        
        const defaultData = {
            users: [],
            schedule: [
                {
                    channelId: 'TV-1',
                    channelName: 'TV-1',
                    programs: [
                        {
                            time: '08:00', // Время в МСК (UTC+3)
                            name: 'Ну, погоди! — Выпуск 1-4',
                            file: 'nu-pogodi-1-4.mp4',
                            description: 'Классика советской анимации'
                        },
                        {
                            time: '10:00', // Время в МСК (UTC+3)
                            name: 'Ну, погоди! — Выпуск 5-8',
                            file: 'nu-pogodi-5-8.mp4',
                            description: 'Продолжение приключений'
                        },
                        {
                            time: '12:00', // Время в МСК (UTC+3)
                            name: 'Ну, погоди! — Выпуск 9-12',
                            file: 'nu-pogodi-9-12.mp4',
                            description: 'Новые серии'
                        },
                        {
                            time: '14:00', // Время в МСК (UTC+3)
                            name: 'Ну, погоди! — Выпуск 13-16',
                            file: 'nu-pogodi-13-16.mp4',
                            description: 'Финальные серии'
                        },
                        {
                            time: '16:00', // Время в МСК (UTC+3)
                            name: 'Ну, погоди! — Выпуск 1-4 (повтор)',
                            file: 'nu-pogodi-1-4.mp4',
                            description: 'Повтор'
                        }
                    ]
                }
            ]
        };

        const response = await axios.post('https://api.github.com/gists', {
            description: 'V-OTV Database (users + schedule)',
            public: false,
            files: {
                'users.json': {
                    content: JSON.stringify(defaultData.users, null, 2)
                },
                'schedule.json': {
                    content: JSON.stringify(defaultData.schedule, null, 2)
                }
            }
        }, {
            headers: {
                'Authorization': `token ${GITHUB_TOKEN}`,
                'Accept': 'application/vnd.github.v3+json'
            }
        });

        GIST_ID = response.data.id;
        GIST_API = `https://api.github.com/gists/${GIST_ID}`;
        
        console.log(`✅ Gist created successfully! ID: ${GIST_ID}`);
        console.log(`⚠️  Add this to your HF Secrets: GIST_ID=${GIST_ID}`);
        
        return defaultData;
    } catch (error) {
        console.error('Failed to create Gist:', error.message);
        return null;
    }
}

// Инициализация Gist (создание если не существует)
async function initializeGist() {
    if (gistInitialized) return true;

    if (!GIST_ID && GITHUB_TOKEN) {
        console.log('📋 No GIST_ID provided, creating new Gist...');
        const data = await createDefaultGist();
        if (data) {
            usersCache = data.users;
            scheduleCache = data.schedule;
            cacheTime = Date.now();
            gistInitialized = true;
            return true;
        }
        return false;
    }

    if (!GIST_ID || !GITHUB_TOKEN) {
        console.warn('⚠️  GIST_ID or GITHUB_TOKEN not set. Using local fallback.');
        gistInitialized = true;
        return false;
    }

    // Проверка существования Gist
    try {
        await axios.get(GIST_API, {
            headers: {
                'Authorization': `token ${GITHUB_TOKEN}`,
                'Accept': 'application/vnd.github.v3+json'
            }
        });
        gistInitialized = true;
        return true;
    } catch (error) {
        if (error.response && error.response.status === 404) {
            console.log('📋 Gist not found, creating new one...');
            const data = await createDefaultGist();
            if (data) {
                usersCache = data.users;
                scheduleCache = data.schedule;
                cacheTime = Date.now();
                gistInitialized = true;
                return true;
            }
        }
        console.error('Gist initialization error:', error.message);
        return false;
    }
}

// Get Gist data
async function getGistData() {
    await initializeGist();

    if (!GIST_ID || !GITHUB_TOKEN) {
        return getLocalData();
    }

    try {
        const response = await axios.get(GIST_API, {
            headers: {
                'Authorization': `token ${GITHUB_TOKEN}`,
                'Accept': 'application/vnd.github.v3+json'
            }
        });

        const files = response.data.files;
        
        let users = [];
        let schedule = [];

        // Загрузка и расшифровка пользователей
        if (files['users.json']) {
            const encryptedUsers = JSON.parse(files['users.json'].content);
            users = crypto.decryptUsers(encryptedUsers);
        }

        // Загрузка расписания (не шифруется)
        if (files['schedule.json']) {
            schedule = JSON.parse(files['schedule.json'].content);
        }

        return { users, schedule };
    } catch (error) {
        console.error('Gist fetch error:', error.message);
        return getLocalData();
    }
}

// Update Gist data
async function updateGistData(data) {
    await initializeGist();

    if (!GIST_ID || !GITHUB_TOKEN) {
        return saveLocalData(data);
    }

    try {
        const files = {};
        
        if (data.users) {
            // Шифрование пользователей перед сохранением
            const encryptedUsers = crypto.encryptUsers(data.users);
            files['users.json'] = {
                content: JSON.stringify(encryptedUsers, null, 2)
            };
        }
        
        if (data.schedule) {
            // Расписание не шифруется
            files['schedule.json'] = {
                content: JSON.stringify(data.schedule, null, 2)
            };
        }

        await axios.patch(GIST_API, { files }, {
            headers: {
                'Authorization': `token ${GITHUB_TOKEN}`,
                'Accept': 'application/vnd.github.v3+json'
            }
        });

        // Clear cache
        usersCache = null;
        scheduleCache = null;
        cacheTime = 0;

        return true;
    } catch (error) {
        console.error('Gist update error:', error.message);
        return false;
    }
}

// Local fallback
function getLocalData() {
    return {
        users: [],
        schedule: [
            {
                channelId: 'TV-1',
                channelName: 'TV-1',
                programs: [
                    {
                        time: '08:00', // Время в МСК (UTC+3)
                        name: 'Ну, погоди! — Выпуск 1-4',
                        file: 'nu-pogodi-1-4.mp4',
                        description: 'Классика советской анимации'
                    },
                    {
                        time: '10:00', // Время в МСК (UTC+3)
                        name: 'Ну, погоди! — Выпуск 5-8',
                        file: 'nu-pogodi-5-8.mp4',
                        description: 'Продолжение приключений'
                    },
                    {
                        time: '12:00', // Время в МСК (UTC+3)
                        name: 'Ну, погоди! — Выпуск 9-12',
                        file: 'nu-pogodi-9-12.mp4',
                        description: 'Новые серии'
                    },
                    {
                        time: '14:00', // Время в МСК (UTC+3)
                        name: 'Ну, погоди! — Выпуск 13-16',
                        file: 'nu-pogodi-13-16.mp4',
                        description: 'Финальные серии'
                    }
                ]
            }
        ]
    };
}

function saveLocalData(data) {
    // In production with Gist, this won't be used
    console.log('Local save (no-op in production)');
    return true;
}

// Public API
async function getUsers() {
    const now = Date.now();
    if (usersCache && (now - cacheTime) < CACHE_DURATION) {
        return usersCache;
    }

    const data = await getGistData();
    usersCache = data.users;
    cacheTime = now;
    return usersCache;
}

async function saveUsers(users) {
    usersCache = users;
    return await updateGistData({ users });
}

async function getSchedule() {
    const now = Date.now();
    if (scheduleCache && (now - cacheTime) < CACHE_DURATION) {
        return scheduleCache;
    }

    const data = await getGistData();
    scheduleCache = data.schedule;
    cacheTime = now;
    return scheduleCache;
}

async function saveSchedule(schedule) {
    scheduleCache = schedule;
    return await updateGistData({ schedule });
}

module.exports = {
    getUsers,
    saveUsers,
    getSchedule,
    saveSchedule,
    initializeGist
};