-
Notifications
You must be signed in to change notification settings - Fork 0
/
Program.cs
220 lines (191 loc) · 5.34 KB
/
Program.cs
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
using System;
using System.Collections.Generic;
using System.CommandLine;
using System.CommandLine.Invocation;
using System.CommandLine.NamingConventionBinder;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Reflection;
using System.Text.Json;
using System.Threading.Tasks;
using System.Web;
namespace BingDailyImagesDl
{
public static class Program
{
private const string BaseUrl = "https://www.bing.com";
private const string ImageMetadataUrl = "HPImageArchive.aspx?format=js&idx=0&n=8&mkt=en-CA"; // n indicates how many image metadatas to fetch. 8 is max.
private static readonly string[] ImgMimes = {
"image/apng",
"image/bmp",
"image/gif",
"image/x-icon",
"image/jpeg",
"image/png",
"image/svg+xml",
"image/tiff",
"image/webp",
};
private static string CurrentExeDirectory => Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
public static async Task Main(string[] args)
{
var option = new Option<string>("--savedir", "The directory to save downloaded images to.")
{
Name = "savedir",
IsRequired = true
};
option.AddAlias("-s");
var cmd = new RootCommand
{
option
};
cmd.Description = "Download the Bing daily image.";
try
{
cmd.Handler = CommandHandler.Create<string>(DownloadBingDailyImage);
await cmd.InvokeAsync(args);
}
catch (Exception ex)
{
LogException(ex);
}
}
private static async Task DownloadBingDailyImage(string saveDir)
{
var jsonHttpClient = BuildJsonHttpClient();
var metadataTask = jsonHttpClient.GetStringAsync($"{BaseUrl}/{ImageMetadataUrl}");
var metadataStr = await metadataTask;
var metadata = JsonSerializer.Deserialize<RootObject>(metadataStr, new JsonSerializerOptions {PropertyNameCaseInsensitive = true});
var imageHttpClient = BuildImageHttpClient();
if (metadata.Images.Length == 0)
{
return;
}
var cache = new StringCache(Path.Combine(CurrentExeDirectory, "cache.txt"));
cache.Load();
try
{
foreach (var metadataImage in metadata.Images)
{
var uri = new Uri(BaseUrl + metadataImage.Url);
var queryDictionary = HttpUtility.ParseQueryString(uri.Query);
var id = queryDictionary["id"];
if (cache.Contains(id))
{
continue;
}
var imgStream = await imageHttpClient.GetStreamAsync(uri);
var directoryInfo = Directory.CreateDirectory(saveDir);
await using var fileStream = File.Create(Path.Combine(directoryInfo.FullName, id));
await imgStream.CopyToAsync(fileStream);
cache.Add(id);
}
}
catch (Exception ex)
{
LogException(ex);
}
finally
{
cache.Flush();
}
}
private static HttpClient BuildImageHttpClient()
{
var client = new HttpClient();
client.DefaultRequestHeaders.Accept.Clear();
foreach (var mime in ImgMimes)
{
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(mime));
}
return client;
}
private static HttpClient BuildJsonHttpClient()
{
var client = new HttpClient();
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
return client;
}
private static void LogException(Exception ex)
{
File.WriteAllText(
Path.Combine(
Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), $"err-{DateTime.UtcNow.Ticks}.txt"),
ex.ToString());
}
public class RootObject
{
public Image[] Images { get; set; }
public ToolTips ToolTips { get; set; }
}
public class ToolTips
{
public string Loading { get; set; }
public string Previous { get; set; }
public string Next { get; set; }
public string WallE { get; set; }
public string WallS { get; set; }
}
public class Image
{
public string StartDate { get; set; }
public string FullStartDate { get; set; }
public string EndDate { get; set; }
public string Url { get; set; }
public string UrlBase { get; set; }
public string Copyright { get; set; }
public string CopyrightLink { get; set; }
public string Title { get; set; }
public string Quiz { get; set; }
public bool Wp { get; set; }
public string Hsh { get; set; }
public int Drk { get; set; }
public int Top { get; set; }
public int Bot { get; set; }
public object[] Hs { get; set; }
}
public class StringCache
{
private readonly IList<string> _added = new List<string>();
private string[] _cache;
public StringCache(string filePath)
{
FilePath = filePath;
}
public string FilePath { get; }
public void Load()
{
try
{
_cache = File.ReadAllLines(FilePath);
}
catch
{
var s = File.CreateText(FilePath);
s.Close();
_cache = File.ReadAllLines(FilePath);
}
}
public bool Contains(string str)
{
return _cache.Contains(str);
}
public void Add(string str)
{
_added.Add(str);
}
public void Flush()
{
if (_added.Count > 0)
{
File.AppendAllLines(FilePath, _added);
_added.Clear();
}
Load();
}
}
}
}