-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcloudflare-worker.js
More file actions
435 lines (387 loc) · 13.5 KB
/
Copy pathcloudflare-worker.js
File metadata and controls
435 lines (387 loc) · 13.5 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
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
const DEBUG = false;
const REPO_OWNER = 'D3rhami';
const REPO_NAME = 'milli-gold-capture';
const DATABASE_PATH = 'database';
function gregorianToSolar(year, month, day, formatType) {
if (formatType === undefined) {
formatType = "array";
}
if (year < 1 || month < 1 || month > 12 || day < 1 || day > 31) {
return "Invalid Input";
}
let persianYear = year - 621;
let persianMonth, persianDay;
if (month < 3 || (month === 3 && day < 21)) {
persianYear--;
}
if (month === 1) {
if (day <= 20) {
persianMonth = 10;
persianDay = day + 10;
} else {
persianMonth = 11;
persianDay = day - 20;
}
} else if (month === 2) {
if (day <= 19) {
persianMonth = 11;
persianDay = day + 11;
} else {
persianMonth = 12;
persianDay = day - 19;
}
} else if (month === 3) {
if (day <= 20) {
persianMonth = 12;
persianDay = day + 9;
} else {
persianMonth = 1;
persianDay = day - 20;
}
} else if (month === 4) {
if (day <= 20) {
persianMonth = 1;
persianDay = day + 11;
} else {
persianMonth = 2;
persianDay = day - 20;
}
} else if (month === 5) {
if (day <= 21) {
persianMonth = 2;
persianDay = day + 10;
} else {
persianMonth = 3;
persianDay = day - 21;
}
} else if (month === 6) {
if (day <= 21) {
persianMonth = 3;
persianDay = day + 10;
} else {
persianMonth = 4;
persianDay = day - 21;
}
} else if (month === 7) {
if (day <= 22) {
persianMonth = 4;
persianDay = day + 9;
} else {
persianMonth = 5;
persianDay = day - 22;
}
} else if (month === 8) {
if (day <= 22) {
persianMonth = 5;
persianDay = day + 9;
} else {
persianMonth = 6;
persianDay = day - 22;
}
} else if (month === 9) {
if (day <= 22) {
persianMonth = 6;
persianDay = day + 9;
} else {
persianMonth = 7;
persianDay = day - 22;
}
} else if (month === 10) {
if (day <= 22) {
persianMonth = 7;
persianDay = day + 8;
} else {
persianMonth = 8;
persianDay = day - 22;
}
} else if (month === 11) {
if (day <= 21) {
persianMonth = 8;
persianDay = day + 9;
} else {
persianMonth = 9;
persianDay = day - 21;
}
} else if (month === 12) {
if (day <= 21) {
persianMonth = 9;
persianDay = day + 9;
} else {
persianMonth = 10;
persianDay = day - 21;
}
}
if (formatType === "array") {
return [persianYear, persianMonth, persianDay];
} else if (formatType === "string") {
return persianYear + "-" +
(persianMonth <= 9 ? "0" + persianMonth : persianMonth) + "-" +
(persianDay <= 9 ? "0" + persianDay : persianDay);
} else if (formatType === "object") {
return {
year: persianYear,
month: persianMonth,
day: persianDay
};
} else if (formatType === "json") {
return JSON.stringify({
year: persianYear,
month: persianMonth,
day: persianDay
});
} else {
throw "Invalid Type";
}
}
function _log(msg) {
if (DEBUG) {
console.log(msg);
}
}
function getTehranDateTime() {
// Get current time in Tehran timezone
const now = new Date();
const tehranTime = new Date(now.toLocaleString("en-US", {timeZone: "Asia/Tehran"}));
return tehranTime;
}
function formatTehranTime(date, format = 'full') {
const year = date.getFullYear();
const month = String(date.getMonth() + 1).padStart(2, '0');
const day = String(date.getDate()).padStart(2, '0');
const hours = String(date.getHours()).padStart(2, '0');
const minutes = String(date.getMinutes()).padStart(2, '0');
const seconds = String(date.getSeconds()).padStart(2, '0');
if (format === 'date') {
return `${year}-${month}-${day}`;
}
return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}
async function logError(errorMsg, env) {
try {
const tehranTime = getTehranDateTime();
const today = formatTehranTime(tehranTime, 'date');
const timestamp = formatTehranTime(tehranTime);
const logContent = `[${timestamp}] ${errorMsg}\n`;
_log(`Logging error: ${logContent.trim()}`);
const url = `https://api.github.com/repos/${REPO_OWNER}/${REPO_NAME}/contents/${DATABASE_PATH}/server.log`;
const headers = {
'Authorization': `token ${env.GITHUB_TOKEN}`,
'Accept': 'application/vnd.github.v3+json',
'User-Agent': 'Cloudflare-Worker'
};
let newContent = logContent;
let sha = null;
try {
const response = await fetch(url, { headers });
if (response.ok) {
const data = await response.json();
const existingContent = atob(data.content);
newContent = existingContent + logContent;
sha = data.sha;
}
} catch (e) {
_log(`Error getting existing log: ${e}`);
}
const encodedContent = btoa(newContent);
const requestData = {
message: `Update server.log - ${today}`,
content: encodedContent
};
if (sha) {
requestData.sha = sha;
}
const logResponse = await fetch(url, {
method: 'PUT',
headers: {
...headers,
'Content-Type': 'application/json'
},
body: JSON.stringify(requestData)
});
if (!logResponse.ok) {
_log(`Failed to log error to GitHub: ${logResponse.status} - ${await logResponse.text()}`);
}
} catch (e) {
_log(`Failed to log error: ${e}`);
_log(`Original error was: ${errorMsg}`);
}
}
async function getGoldPrice() {
const url = "https://milli.gold/api/v1/public/milli-price/external";
const headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/136.0.0.0 Safari/537.36",
"Accept": "application/json",
};
try {
const response = await fetch(url, { headers });
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
const data = await response.json();
return data;
} catch (e) {
return `error was ${e}`;
}
}
async function getCsvFromGithub(filename, env) {
const url = `https://api.github.com/repos/${REPO_OWNER}/${REPO_NAME}/contents/${DATABASE_PATH}/${filename}`;
const headers = {
'Authorization': `token ${env.GITHUB_TOKEN}`,
'Accept': 'application/vnd.github.v3+json',
'User-Agent': 'Cloudflare-Worker'
};
try {
_log(`Fetching CSV from GitHub: ${filename}`);
const response = await fetch(url, { headers });
_log(`GitHub GET response: ${response.status}`);
if (response.ok) {
const data = await response.json();
const content = atob(data.content);
const sha = data.sha;
_log(`Successfully fetched existing CSV with ${content.length} characters`);
return { content, sha };
} else if (response.status === 404) {
_log(`CSV file ${filename} doesn't exist yet, will create new one`);
return { content: null, sha: null };
} else {
const errorText = await response.text();
_log(`Unexpected response from GitHub: ${response.status} - ${errorText}`);
await logError(`Error fetching CSV from GitHub: ${response.status} - ${errorText}`, env);
return { content: null, sha: null };
}
} catch (e) {
_log(`Exception while fetching CSV: ${e}`);
await logError(`Error fetching CSV from GitHub: ${e}`, env);
return { content: null, sha: null };
}
}
async function pushCsvToGithub(filename, content, sha, env) {
const url = `https://api.github.com/repos/${REPO_OWNER}/${REPO_NAME}/contents/${DATABASE_PATH}/${filename}`;
const headers = {
'Authorization': `token ${env.GITHUB_TOKEN}`,
'Accept': 'application/vnd.github.v3+json',
'User-Agent': 'Cloudflare-Worker',
'Content-Type': 'application/json'
};
const encodedContent = btoa(content);
const price = content.trim().split('\n').pop().split(',')[0];
const requestData = {
message: jaliMsg(price),
content: encodedContent
};
if (sha) {
requestData.sha = sha;
_log(`Updating existing file ${filename} with SHA: ${sha}`);
} else {
_log(`Creating new file ${filename}`);
}
try {
_log(`Pushing CSV to GitHub: ${filename}`);
const response = await fetch(url, {
method: 'PUT',
headers,
body: JSON.stringify(requestData)
});
_log(`GitHub PUT response: ${response.status}`);
if (response.ok) {
_log(`Successfully pushed ${filename} to GitHub`);
return true;
} else {
const errorText = await response.text();
const errorMsg = `Failed to push ${filename}: ${response.status} - ${errorText}`;
_log(errorMsg);
await logError(errorMsg, env);
return false;
}
} catch (e) {
const errorMsg = `Exception pushing CSV to GitHub: ${e}`;
_log(errorMsg);
await logError(errorMsg, env);
return false;
}
}
function jaliMsg(price) {
const tehranTime = getTehranDateTime();
const gregorianDate = formatTehranTime(tehranTime, 'date');
const timeStr = formatTehranTime(tehranTime).split(' ')[1];
const [year, month, day] = gregorianDate.split('-').map(Number);
const persianMonthNames = [
'Farvardin', 'Ordibehesht', 'Khordad', 'Tir', 'Mordad', 'Shahrivar',
'Mehr', 'Aban', 'Azar', 'Dey', 'Bahman', 'Esfand'
];
const solarDate = gregorianToSolar(year, month, day, 'array');
const [solarYear, solarMonth, solarDay] = solarDate;
const monthName = persianMonthNames[solarMonth - 1];
return `📆 ${solarDay}-${monthName}-${solarYear}|${timeStr}🪙${price} . add by cloudflare worker`;
}
async function processGoldData(env) {
_log("Starting gold data processing");
if (!env.GITHUB_TOKEN) {
const errorMsg = "GITHUB_TOKEN not found in environment variables";
_log(errorMsg);
await logError(errorMsg, env);
return { success: false, error: errorMsg };
}
const goldData = await getGoldPrice();
if (typeof goldData === 'string') {
const errorMsg = `Failed to get gold price: ${goldData}`;
_log(errorMsg);
await logError(errorMsg, env);
return { success: false, error: errorMsg };
}
_log(`Retrieved gold data: ${JSON.stringify(goldData)}`);
const dateFromApi = goldData.date;
const today = dateFromApi.split('T')[0];
const filename = `${today}.csv`;
const { content: existingContent, sha } = await getCsvFromGithub(filename, env);
let csvContent;
if (existingContent === null) {
_log("Creating new CSV file with headers");
csvContent = "price18,date\n";
} else {
csvContent = existingContent;
}
const newRow = `${goldData.price18},${goldData.date}\n`;
csvContent += newRow;
_log(`Adding new row: ${newRow.trim()}`);
const success = await pushCsvToGithub(filename, csvContent, sha, env);
if (success) {
_log(`Successfully processed and pushed data for ${today}`);
return { success: true, message: `Data processed for ${today}` };
} else {
const errorMsg = `Failed to push data to GitHub for ${today}`;
_log(errorMsg);
await logError(errorMsg, env);
return { success: false, error: errorMsg };
}
}
// Cloudflare Worker event handlers
export default {
async fetch(request, env, ctx) {
// Handle HTTP requests (for manual triggers)
try {
const result = await processGoldData(env);
return new Response(JSON.stringify(result), {
headers: { 'Content-Type': 'application/json' }
});
} catch (error) {
return new Response(JSON.stringify({
success: false,
error: error.message
}), {
status: 500,
headers: { 'Content-Type': 'application/json' }
});
}
},
async scheduled(event, env, ctx) {
// Handle cron triggers (automatic execution)
try {
const result = await processGoldData(env);
console.log('Scheduled execution result:', result);
} catch (error) {
console.error('Scheduled execution error:', error);
await logError(`Scheduled execution error: ${error.message}`, env);
}
}
};