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
| const axios = require('axios'); const express = require('express'); const { startOfWeek, startOfMonth, startOfYear, differenceInDays, format, } = require('date-fns'); const path = require('path'); const app = express(); app.use(function(req, res, next) { res.setHeader('Access-Control-Allow-Origin', '*'); res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE'); res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization'); next(); });
app.use(express.json());
const { createClient } = require('@supabase/supabase-js'); const supabaseUrl = '你的数据库地址'; const supabaseKey = process.env.SUPABASE_KEY; const supabase = createClient(supabaseUrl, supabaseKey);
const apiKey = process.env.API_KEY || ''; const secretKey = process.env.SECRET_KEY || ''; const siteId = process.env.SITE_ID || ''; let access_token = null; let refresh_token = null;
app.get('/baidupv', async (req, res) => { const { data: tokenData, error } = await supabase .from('PVTokens') .select() .eq('name', 'baidu') if (error) { console.error('Database Error:', error); res.json({ error: 'database error' }) } else { const today = new Date(); const todayFormat = format(today, 'yyyyMMdd'); let latestTime = tokenData[0].time; let passTime = differenceInDays(today, latestTime); let data = { today_uv: null, today_pv: null, yesterday_uv: null, yesterday_pv: null, last_week_uv: null, last_week_pv: null, last_month_uv: null, last_month_pv: null, last_year_uv: null, last_year_pv: null, total_uv: null, total_pv: null }; if (passTime < 20) { access_token = tokenData[0].tokens.access_token; } else { refresh_token = tokenData[0].tokens.refresh_token; const newTokens = await refreshAccessToken(apiKey, secretKey, refresh_token); access_token = newTokens.access_token; refresh_token = newTokens.refresh_token; const { data, error } = await supabase .from('PVTokens') .update({ tokens: {"access_token": access_token, "refresh_token": refresh_token}, time: today }) .eq('name', 'baidu') .select() } const totalData = await getData('20250403', todayFormat, 'pv_count,visitor_count', access_token, siteId); if (totalData && totalData.result && totalData.result.items && totalData.result.items[1]) { const dataPoints = totalData.result.items[1]; data.today_pv = dataPoints.slice(-2)[1][0]; data.today_uv = dataPoints.slice(-2)[1][1]; data.yesterday_pv = dataPoints.slice(-2)[0][0]; data.yesterday_uv = dataPoints.slice(-2)[0][1]; const daysPassedInWeek = differenceInDays(today, startOfWeek(today, { weekStartsOn: 1 })); const daysPassedInMonth = differenceInDays(today, startOfMonth(today)); const daysPassedInYear = differenceInDays(today, startOfYear(today)); dataPoints.slice().reverse().forEach((point, index) => { var pv = point[0] == "--" ? 0 : point[0]; var uv = point[1] == "--" ? 0 : point[1]; data.total_pv += pv; data.total_uv += uv; if(index < daysPassedInWeek) { data.last_week_pv += pv; data.last_week_uv += uv; } if(index < daysPassedInMonth) { data.last_month_pv += pv; data.last_month_uv += uv; } if(index < daysPassedInYear) { data.last_year_pv += pv; data.last_year_uv += uv; } }); } res.json(data) } })
async function getData(startDate, endDate, metrics, accessToken, siteId) { const url = "https://openapi.baidu.com/rest/2.0/tongji/report/getData"; const params = new URLSearchParams({ access_token: accessToken, site_id: siteId, method: 'overview/getTimeTrendRpt', start_date: startDate, end_date: endDate, metrics: metrics }); try { const response = await axios.get(url, { params }); return response.data; } catch (error) { console.error('Error fetching PV data:', error); throw new Error('Error fetching PV data.'); } }
async function refreshAccessToken(apiKey, secretKey, refreshToken) { const url = "https://openapi.baidu.com/oauth/2.0/token"; const params = new URLSearchParams({ grant_type: 'refresh_token', refresh_token: refreshToken, client_id: apiKey, client_secret: secretKey }); try { const response = await axios.get(url, { params }); return response.data; } catch (error) { console.error('Error refreshing access token:', error); throw new Error('Error refreshing access token.'); } }
const server = app.listen(process.env.PORT || 3000, () => { const port = server.address().port; console.log(`Server is running on port ${port}`); });
|