-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy patheconomistdownload.js
338 lines (303 loc) · 10.1 KB
/
economistdownload.js
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
/*
Created by Jing on Apr 19, 2021
Last updated on Feb 12, 2025
Retrive the audio file archive from The Economist CDN server.
*/
const cdnurl = "https://audiocdn.economist.com/sites/default/files/AudioArchive/";
const cdnurl_2025 = "https://economist.com/mobile-assets/{0}-audio.zip"
const jsonUrl = "https://jingking.github.io/The-Economist-Audio-List/EditionsQuery.json";
var urlstr_2012 = cdnurl + "{0}/{1}/{1}_TheEconomist_Full_Edition.{2}";
var urlstr_2019 = cdnurl + "{0}/{1}/Issue_{2}_{1}_The_Economist_Full_Edition.{3}";
var urlstr = cdnurl + "{0}/{1}/Issue_{2}_{1}_The_Economist_Full_edition.{3}";
//file extension
let extension = {
download: "zip",
online: "m4a"
};
const InitiaYear = 2021;
const InitialDate = new Date(InitiaYear,0,2);
const InitiaIssue = 9226;
//cover image config
var imgurlconfig = [
{
date:new Date(2000,0,1),//2000-01-01,//
urlconfig:{
imgurl: "https://www.economist.com/img/b/400/526/90/sites/default/files/{0}issuecov{1}.jpg",
file:['US400','UK400']
}
},
{
date:new Date(2010,8,5),//2010-09-05,//>= 2010-09-11
urlconfig:{
imgurl: "https://www.economist.com/img/b/400/526/90/sites/default/files/{0}_{1}.jpg",
file:['cna400','cuk400','cuk400hires','cna400hires','CNA400']
}
},
{
date:new Date(2012,8,16),//2012-09-16,//>= 2012-09-22
urlconfig:{
imgurl: "https://www.economist.com/img/b/400/526/90/sites/default/files/print-covers/{0}_{1}.jpg",
file:['cna1280','cuk1280','de_us','de_uk','cna400','cuk400','cna400hires', 'cna1248', 'cna1280_0']
}
},
{
date:new Date(2022,4,15),//2022-05-15,//>= 2022-05-21
urlconfig:{
imgurl: "https://www.economist.com/img/b/400/526/90/media-assets/image/{0}_{1}.jpg",
file:['DE_US','DE_EU']
}
}
];
//content ref
var imghref = "https://www.economist.com/printedition/{0}";
let MyEdition = {
Date: "", //Weekly Edition Date
Issue: "", //Weekly Edition Issue
Title: "", //Title text
Image: "",//Cover image HTML
AudioURL: "", //Audio URL
DownloadURL: "",//Mp3 zip file URL
ContentIndex: "" //content index
};
function getEditionByDate(){
var year = document.getElementById("year").value;
var month = document.getElementById("month").value;
var day = document.getElementById("day").selectedIndex+1;
var d = getEditionDate(year,month,day);
if (d != null){
this.document.getElementById("edition_content").style.display = 'block';
getEdition(d)
.then(function(MyEdition){
if (MyEdition != null){
this.document.getElementById("edition_title").innerHTML = MyEdition.Title;
this.document.getElementById("edition_img").innerHTML = MyEdition.Image;
this.document.getElementById("edition_url").innerHTML = MyEdition.Title.link(MyEdition.DownloadURL);
if (MyEdition.AudioURL != "")
{
this.document.getElementById("edition_audiosource").src = MyEdition.AudioURL;
audio = this.document.getElementById("edition_audio");
audio.preload = "metadata";
audio.load();
}
else{
this.document.getElementById("edition_audio").style.display = 'none';
}
}
})
}
else
this.document.getElementById("edition_title").innerHTML = "Error!";
}
//input any date, return valid weekly edition date
function getEditionDate(year,month,day){
var d = new Date(year, month, day);
dayofweek = d.getDay();
//console.log(dayofweek);
if (dayofweek<6)
d = new Date(year, month, day-1-dayofweek);
//special case
if (d.getFullYear() ==2011 && d.getMonth() == 11 && d.getDate() >=24)
return new Date(2011, 11, 31);
//2022 summer double issue
if (d.getFullYear() ==2022 && d.getMonth() == 7 && d.getDate() < 13)
return getEditionDate(year, month, day-7);
//2023 summer double issue
if (d.getFullYear() ==2023 && d.getMonth() == 7 && d.getDate() < 12)
return getEditionDate(year, month, day-7);
if (d.getMonth() == 11 && d.getDate() >24 ){
return getEditionDate(year, month, day-7);
} //Christmas
else
return d;
}
//assemble myedition
async function getEdition(d){
if (d != null){
let edition = new Object();
edition.Date = d.toISOString().slice(0, 10);
edition.Issue = getEditionIssue(d);
edition.Title = getEditionTitle(d);
edition.Image = getEditionImg(d);
const URLs = await getEditionURL(d);
edition.AudioURL = URLs.audio;
edition.DownloadURL = URLs.download;
return edition;
}
else
return null;
}
function getEditionTitle(d){
//need to retrive title from official website
//use Date as a placeholder for now.
return "Weekly Edition "+d.toISOString().slice(0, 10);
}
//get cover image and asseble HTML output
function getEditionImg(d){
var imageresults = document.createElement("a");
var datestr=d.toISOString().slice(0, 10);
var i=0;
while((i < imgurlconfig.length) && (d > imgurlconfig[i].date)){
i++;
}
var url = imgurlconfig[i-1].urlconfig.imgurl;
var files = imgurlconfig[i-1].urlconfig.file;
for(i=0; i < files.length; i++){
var img = document.createElement('img');
img.src=url.format(datestr.replace(/-/g, ''),files[i]);
img.alt = "";
imageresults.appendChild(img);
}
imageresults.href = imghref.format(datestr);
imageresults.target = "_blank";
return imageresults.outerHTML;
}
//input the weekly edition date, return date, m4a download url and zip file download url
async function getEditionURL(d){
if (d.getMonth() == 11 && d.getDate() >24 && d.getDate() <31) return null;
datestr=d.toISOString().slice(0, 10).replace(/-/g, '');
year=datestr.slice(0,4);
var URLs = {
date:"",
audio:"",
download:""
}
if (d > new Date(2024,11,1)){// Old CDN URL stopped working since Dec 2024
datestr = d.toISOString().split('T')[0];
fetchIdByDate(datestr)
const tagid = await fetchIdByDate(datestr);
URLs.download = cdnurl_2025.format(tagid);
return URLs;
}else{
issuestr=getEditionIssue(d);
URLs.date = datestr;
if (issuestr== 9136){
URLs.audio = urlstr.format(year,datestr,issuestr,extension.online);
URLs.download = urlstr_2019.format(year,datestr,issuestr,extension.download);
}else if (issuestr> 8796){
URLs.audio = urlstr.format(year,datestr,issuestr,extension.online);
URLs.download = urlstr.format(year,datestr,issuestr,extension.download);
}else {
URLs.audio = urlstr_2012.format(year,datestr,extension.online);
URLs.download = urlstr_2012.format(year,datestr,extension.download);
}
return URLs;
}
}
function getEditionIssue(d){
//2022 summer double issue - 9307
//2023 summer double issue - 9357
var i = InitiaIssue;
if (d > new Date(2022,7,12))
i = i-1;
if (d > new Date(2023,7,11))
i = i-1;
return Math.round(i - (year-InitiaYear) + (d-InitialDate)/(1000*60*60*24*7));
}
//get annual download list
async function getDownloadList(){
this.document.getElementById("list").innerHTML = "";
year=document.getElementById("year_d").value;
if (year > 2024)
{
fetchIdList()
.then(function(parts){
for (var i = 0; i < parts.length; i++){
var date = parts[i].datePublished;
var id = parts[i].id.split('/content/')[1];
var datestr = date.split('T')[0];
this.document.getElementById("list").innerHTML += datestr.link(cdnurl_2025.format(id)) + "<br />";
}
})
}
else{
var d = getEditionDate(year,0,7);
var day = d.getDate();
for(var i = day; i < 360; i=i+7){
if (year == 2011 && i==358){
i=365;
}
getEditionURL(new Date(year,0,i))
.then(function(URLs){
if (URLs != null)
this.document.getElementById("list").innerHTML += URLs.date.link(URLs.download) + "<br />";
})
}
}
}
//string format function
String.prototype.format = function(){
var content = this;
for (var i=0; i < arguments.length; i++)
{
var replacement = '{' + i + '}';
content = content.replaceAll(replacement, arguments[i]);
}
return content;
};
String.prototype.replaceAll = function(target, replacement) {
return this.split(target).join(replacement);
};
//hide invalid images
document.addEventListener('error', function (event) {
if (event.target.tagName.toLowerCase() !== 'img') return;
event.target.style.display = 'none';
}, true);
async function fetchIdByDate(date) {
try {
const response = await fetch(jsonUrl);
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
const data = await response.json();
// Loop through the JSON array
const parts = data?.data?.section?.hasPart?.parts || [];
const match = parts.find(part => part.datePublished.startsWith(date));
if (match) {
id = match.id.split('/content/')[1];
return id;
} else {
console.log("No matching ID found for selecte issue.");
return null;
}
} catch (error) {
console.error("Error fetching JSON:", error);
}
}
async function fetchIdByDate(date) {
try {
const response = await fetch(jsonUrl);
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
const data = await response.json();
// Loop through the JSON array
const parts = data?.data?.section?.hasPart?.parts || [];
const match = parts.find(part => part.datePublished.startsWith(date));
if (match) {
id = match.id.split('/content/')[1];
return id;
} else {
console.log("No matching ID found for selecte issue.");
return null;
}
} catch (error) {
console.error("Error fetching JSON:", error);
}
}
async function fetchIdList() {
try {
const response = await fetch(jsonUrl);
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
const data = await response.json();
const parts = data?.data?.section?.hasPart?.parts || [];
if (parts != null) {
return parts;
} else {
return null;
}
} catch (error) {
console.error("Error fetching JSON:", error);
}
}