using System.Collections.Specialized;
using System.Net.Http;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace Dpz.Core.Service;
public interface IBingWallpaper
{
/// <summary>
/// 随机获取一张壁纸
/// </summary>
/// <returns></returns>
Task<Wallpaper> GetRandomWallpaperAsync();
/// <summary>
/// 获取今日的所有壁纸
/// </summary>
/// <returns></returns>
Task<List<Wallpaper>> GetTodayWallpapersAsync();
/// <summary>
/// 清除缓存
/// </summary>
/// <returns></returns>
Task ClearCacheAsync();
}
public class Wallpaper
{
private const string Host = "https://cn.bing.com";
private string _url = "";
[JsonProperty("url")]
public string Url
{
get => _url.StartsWith("http", StringComparison.OrdinalIgnoreCase) ? _url : Host + _url;
set => _url = value;
}
[JsonProperty("copyright")]
public string? CopyRight { get; set; }
[JsonProperty("copyrightlink")]
public string? CopyRightLink { get; set; }
}
public class BingWallpaper(
ILogger<BingWallpaper> logger,
IHttpClientFactory httpClientFactory,
IHybridCachingProvider cachingProvider
) : IBingWallpaper
{
private const string BingWallpaperKey = "bing-wallpaper-8";
private const string BingWallpaperRandomKey = "bing-wallpaper-random:first";
private async Task<List<Wallpaper>> FetchWallpaperAsync()
{
try
{
//var request = new RestRequest("/HPImageArchive.aspx", Method.GET);
var parameters = new NameValueCollection
{
{ "format", "js" },
//请求图片截止天数 0 今天 -1 截止中明天 (预准备的) 1 截止至昨天,类推(目前最多获取到7天前的图片)
{ "idx", "0" },
//1-8 返回请求数量,目前最多一次获取8张
{ "n", "8" },
//地区
{ "mkt", "zh-CN" }
};
var httpClient = httpClientFactory.CreateClient("edge");
var request = new HttpRequestMessage(
HttpMethod.Get,
$"https://cn.bing.com/HPImageArchive.aspx?{parameters.ToQueryString()}"
);
var response = await httpClient.SendAsync(request);
var content = await response.Content.ReadAsStringAsync();
var result = JObject.Parse(content)["images"]?.ToObject<List<Wallpaper>>() ?? [];
await cachingProvider.SetAsync(BingWallpaperKey, result, TimeSpan.FromDays(1));
await cachingProvider.RemoveAsync(BingWallpaperRandomKey);
return result;
}
catch (Exception e)
{
logger.LogError(e, "获取bing壁纸失败");
var result = new List<Wallpaper>
{
new()
{
Url =
"/th?id=OHR.RedAlley_ZH-CN2795378972_1920x1080.jpg&rf=LaDigue_1920x1080.jpg&pid=hp",
CopyRight = "武侯祠内红墙和竹林掩映下的小巷,中国成都 (© Eastimages/Getty Images)",
CopyRightLink =
"https://www.bing.com/search?q=%E6%AD%A6%E4%BE%AF%E7%A5%A0&form=hpcapt&mkt=zh-cn"
}
};
await cachingProvider.SetAsync(BingWallpaperKey, result, TimeSpan.FromDays(1));
return result;
}
}
public async Task<Wallpaper> GetRandomWallpaperAsync()
{
var cache = await cachingProvider.GetAsync<Wallpaper>(BingWallpaperRandomKey);
if (!cache.IsNull && cache.HasValue)
{
return cache.Value;
}
List<Wallpaper> list;
var listCache = await cachingProvider.GetAsync<List<Wallpaper>>(BingWallpaperKey);
if (!listCache.IsNull && listCache.HasValue)
{
list = listCache.Value;
}
else
{
list = await FetchWallpaperAsync();
}
var result = list.OrderBy(_ => Guid.NewGuid()).First();
await cachingProvider.SetAsync(BingWallpaperRandomKey, result, TimeSpan.FromDays(1));
return result;
}
public async Task<List<Wallpaper>> GetTodayWallpapersAsync()
{
var cache = await cachingProvider.GetAsync<List<Wallpaper>>(BingWallpaperKey);
if (!cache.IsNull && cache.HasValue)
{
return cache.Value;
}
return await FetchWallpaperAsync();
}
public async Task ClearCacheAsync()
{
await FetchWallpaperAsync();
}
}