import https from 'https';
import { WallpaperInfo } from '../models/Project';
export class WallpaperService {
async getRandomWallpaper(resolution: string = '1920x1080', market: string = 'zh-CN'): Promise<WallpaperInfo> {
const apiUrl = `https://www.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1&mkt=${market}&uhd=1&uhdwidth=${resolution.split('x')[0]}&uhdheight=${resolution.split('x')[1]}`;
const wallpaperData = await this.makeHttpRequest(apiUrl);
if (!wallpaperData.images || wallpaperData.images.length === 0) {
throw new Error('未找到可用的壁纸');
}
const wallpaper = wallpaperData.images[0];
const baseUrl = 'https://www.bing.com';
const imageUrl = baseUrl + wallpaper.url;
return {
title: wallpaper.title,
description: wallpaper.copyright,
imageUrl: imageUrl,
resolution: resolution,
date: wallpaper.startdate,
market: market,
fullUrl: imageUrl
};
}
private makeHttpRequest(url: string): Promise<any> {
return new Promise((resolve, reject) => {
https.get(url, (res) => {
let data = '';
res.on('data', (chunk) => {
data += chunk;
});
res.on('end', () => {
try {
const jsonData = JSON.parse(data);
resolve(jsonData);
} catch (error) {
reject(new Error('解析壁纸数据失败'));
}
});
}).on('error', (error) => {
reject(new Error(`获取壁纸失败: ${error.message}`));
});
});
}
}