-
Notifications
You must be signed in to change notification settings - Fork 68
Expand file tree
/
Copy pathHome Weather Script.js
More file actions
369 lines (318 loc) · 10.7 KB
/
Home Weather Script.js
File metadata and controls
369 lines (318 loc) · 10.7 KB
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
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
// Variables used by Scriptable.
// These must be at the very top of the file. Do not edit.
// icon-color: deep-green; icon-glyph: magic;
// Variables used by Scriptable.
// These must be at the very top of the file. Do not edit.
// icon-color: red; icon-glyph: magic;
// Variables used by Scriptable.
// These must be at the very top of the file. Do not edit.
// icon-color: deep-purple; icon-glyph: magic;
// Variables used by Scriptable.
// These must be at the very top of the file. Do not edit.
// icon-color: light-gray; icon-glyph: magic;
// To use, add a parameter to the widget with a format of: image.png|padding-top|text-color
// The image should be placed in the iCloud Scriptable folder (case-sensitive).
// The padding-top spacing parameter moves the text down by a set amount.
// The text color parameter should be a hex value.
// For example, to use the image bkg_fall.PNG with a padding of 40 and a text color of red,
// the parameter should be typed as: bkg_fall.png|40|#ff0000
// All parameters are required and separated with "|"
// Parameters allow different settings for multiple widget instances.
let widgetHello = new ListWidget();
var today = new Date();
var widgetInputRAW = args.widgetParameter;
try {
widgetInputRAW.toString();
} catch(e) {
throw new Error("Please long press the widget and add a parameter.");
}
var widgetInput = widgetInputRAW.toString();
var inputArr = widgetInput.split("|");
// iCloud file path
var scriptableFilePath = "/var/mobile/Library/Mobile Documents/iCloud~dk~simonbs~Scriptable/Documents/";
var removeSpaces1 = inputArr[0].split(" "); // Remove spaces from file name
var removeSpaces2 = removeSpaces1.join('');
var tempPath = removeSpaces2.split(".");
var backgroundImageURLRAW = scriptableFilePath + tempPath[0];
var fm = FileManager.iCloud();
var backgroundImageURL = scriptableFilePath + tempPath[0] + ".";
var backgroundImageURLInput = scriptableFilePath + removeSpaces2;
// For users having trouble with extensions
// Uses user-input file path is the file is found
// Checks for common file format extensions if the file is not found
if (fm.fileExists(backgroundImageURLInput) == false) {
var fileTypes = ['png', 'jpg', 'jpeg', 'tiff', 'webp', 'gif'];
fileTypes.forEach(function(item) {
if (fm.fileExists((backgroundImageURL + item.toLowerCase())) == true) {
backgroundImageURL = backgroundImageURLRAW + "." + item.toLowerCase();
} else if (fm.fileExists((backgroundImageURL + item.toUpperCase())) == true) {
backgroundImageURL = backgroundImageURLRAW + "." + item.toUpperCase();
}
});
} else {
backgroundImageURL = scriptableFilePath + removeSpaces2;
}
var spacing = parseInt(inputArr[1]);
//API_KEY
let API_WEATHER = "XXXXXXXXXXXXXXXXXXXXXX";//Load Your api here
let CITY_WEATHER = "XXXXXXXXXX";//add your city ID
//Get storage
var base_path = "/var/mobile/Library/Mobile Documents/iCloud~dk~simonbs~Scriptable/Documents/weather/";
var fm = FileManager.iCloud();
// Fetch Image from Url
async function fetchimageurl(url) {
const request = new Request(url)
var res = await request.loadImage();
return res;
}
// Get formatted Date
function getformatteddate(){
var months = ['January','February','March','April','May','June','July','August','September','October','November','December'];
return months[today.getMonth()] + " " + today.getDate()
}
// Long-form days and months
var days = ['周日','周一','周二','周三','周四','周五','周六'];
var months = ['1月','2月','3月','4月','5月','6月','7月','8月','9月','10月','11月','12月'];
// Load image from local drive
async function fetchimagelocal(path){
var finalPath = base_path + path + ".png";
if(fm.fileExists(finalPath)==true){
console.log("file exists: " + finalPath);
return finalPath;
}else{
//throw new Error("Error file not found: " + path);
if(fm.fileExists(base_path)==false){
console.log("Directry not exist creating one.");
fm.createDirectory(base_path);
}
console.log("Downloading file: " + finalPath);
await downloadimg(path);
if(fm.fileExists(finalPath)==true){
console.log("file exists after download: " + finalPath);
return finalPath;
}else{
throw new Error("Error file not found: " + path);
}
}
}
async function downloadimg(path){
const url = "http://a.animedlweb.ga/weather/weathers25_2.json";
const data = await fetchWeatherData(url);
var dataimg = null;
var name = null;
if(path.includes("bg")){
dataimg = data.background;
name = path.replace("_bg","");
}else{
dataimg = data.icon;
name = path.replace("_ico","");
}
var imgurl=null;
switch (name){
case "01d":
imgurl = dataimg._01d;
break;
case "01n":
imgurl = dataimg._01n;
break;
case "02d":
imgurl = dataimg._02d;
break;
case "02n":
imgurl = dataimg._02n;
break;
case "03d":
imgurl = dataimg._03d;
break;
case "03n":
imgurl = dataimg._03n;
break;
case "04d":
imgurl = dataimg._04d;
break;
case "04n":
imgurl = dataimg._04n;
break;
case "09d":
imgurl = dataimg._09d;
break;
case "09n":
imgurl = dataimg._09n;
break;
case "10d":
imgurl = dataimg._10d;
break;
case "10n":
imgurl = dataimg._10n;
break;
case "11d":
imgurl = dataimg._11d;
break;
case "11n":
imgurl = dataimg._11n;
break;
case "13d":
imgurl = dataimg._13d;
break;
case "13n":
imgurl = dataimg._13n;
break;
case "50d":
imgurl = dataimg._50d;
break;
case "50n":
imgurl = dataimg._50n;
break;
}
const image = await fetchimageurl(imgurl);
console.log("Downloaded Image");
fm.writeImage(base_path+path+".png",image);
}
//get Json weather
async function fetchWeatherData(url) {
const request = new Request(url);
const res = await request.loadJSON();
return res;
}
// Get Location
/*Location.setAccuracyToBest();
let curLocation = await Location.current();
console.log(curLocation.latitude);
console.log(curLocation.longitude);*/
let wetherurl = "http://api.openweathermap.org/data/2.5/weather?id=" + CITY_WEATHER + "&APPID=" + API_WEATHER + "&units=metric";
//"http://api.openweathermap.org/data/2.5/weather?lat=" + curLocation.latitude + "&lon=" + curLocation.longitude + "&appid=" + API_WEATHER + "&units=metric";
//"http://api.openweathermap.org/data/2.5/weather?id=" + CITY_WEATHER + "&APPID=" + API_WEATHER + "&units=metric"
const weatherJSON = await fetchWeatherData(wetherurl);
const cityName = weatherJSON.name;
const weatherarry = weatherJSON.weather;
const iconData = weatherarry[0].icon;
const weathername = weatherarry[0].main;
const curTempObj = weatherJSON.main;
const curTemp = curTempObj.temp;
const highTemp = curTempObj.temp_max;
const lowTemp = curTempObj.temp_min;
const feel_like = curTempObj.feels_like;
//Completed loading weather data
// Greetings arrays per time period.
var greetingsMorning = [
'早上好.靓仔'
];
var greetingsNoon = [
'中午好.靓仔'
];
var greetingsAfternoon = [
'下午好.靓仔'
];
var greetingsEvening = [
'晚上好.靓仔'
];
var greetingsNight = [
'睡觉时间.靓仔'
];
var greetingsLateNight = [
'赶紧睡觉!!!'
];
// Holiday customization
var holidaysByKey = {
// month,week,day: datetext
"11,4,4": "Happy Thanksgiving!"
}
var holidaysByDate = {
// month,date: greeting
"1,1": "Happy " + (today.getFullYear()).toString() + "!",
"10,31": "Happy Halloween!",
"12,25": "Merry Christmas!"
}
var holidayKey = (today.getMonth() + 1).toString() + "," + (Math.ceil(today.getDate() / 7)).toString() + "," + (today.getDay()).toString();
var holidayKeyDate = (today.getMonth() + 1).toString() + "," + (today.getDate()).toString();
// Date Calculations
var weekday = days[ today.getDay() ];
var month = months[ today.getMonth() ];
var date = today.getDate();
var hour = today.getHours();
// Append ordinal suffix to date
function ordinalSuffix(input) {
if (input % 10 == 1 && date != 11) {
return input.toString() + "日";
} else if (input % 10 == 2 && date != 12) {
return input.toString() + "日";
} else if (input % 10 == 3 && date != 13) {
return input.toString() + "日";
} else {
return input.toString() + "日";
}
}
// Generate date string
var datefull = month + " " + ordinalSuffix(date) +", " + weekday;
// Support for multiple greetings per time period
function randomGreeting(greetingArray) {
return Math.floor(Math.random() * greetingArray.length);
}
var greeting = new String("Howdy.")
if (hour < 5 && hour >= 1) { // 1am - 5am
greeting = greetingsLateNight[randomGreeting(greetingsLateNight)];
} else if (hour >= 23 || hour < 1) { // 11pm - 1am
greeting = greetingsNight[randomGreeting(greetingsNight)];
} else if (hour < 11) { // Before noon (5am - 12pm)
greeting = greetingsMorning[randomGreeting(greetingsMorning)];
} else if (hour >=11 && hour <= 13) { // 11am - 1pm
greeting = greetingsNoon[randomGreeting(greetingsNoon)];
} else if (hour > 13 && hour <= 17) { // 1pm - 5pm
greeting = greetingsAfternoon[randomGreeting(greetingsAfternoon)];
} else if (hour > 17 && hour < 23) { // 5pm - 11pm
greeting = greetingsEvening[randomGreeting(greetingsEvening)];
}
// Overwrite greeting if calculated holiday
if (holidaysByKey[holidayKey]) {
greeting = holidaysByKey[holidayKey];
}
// Overwrite all greetings if specific holiday
if (holidaysByDate[holidayKeyDate]) {
greeting = holidaysByDate[holidayKeyDate];
}
// Try/catch for color input parameter
try {
inputArr[2].toString();
} catch(e) {
throw new Error("Please long press the widget and add a parameter.");
}
let themeColor = new Color(inputArr[2].toString());
/* --------------- */
/* Assemble Widget */
/* --------------- */
//Top spacing
widgetHello.addSpacer(45);
// Greeting label
let hello = widgetHello.addText(greeting);
hello.font = Font.boldSystemFont(35);
hello.textColor = themeColor;
hello.centerAlignText();
widgetHello.addSpacer(10);
let hStack = widgetHello.addStack();
hStack.layoutHorizontally();
// Centers weather line
hStack.addSpacer(45);
// Date label in stack
let datetext = hStack.addText('\xa0\xa0\xa0\xa0' + datefull + '\xa0\xa0\xa0\xa0\xa0\xa0\xa0\xa0');
datetext.font = Font.regularSystemFont(18);
datetext.textColor = themeColor;
datetext.textOpacity = (0.7);
datetext.centerAlignText();
//image
var img = Image.fromFile(await fetchimagelocal(iconData + "_ico"));
//image in stack
let widgetimg = hStack.addImage(img);
widgetimg.imageSize = new Size(20, 20);
//tempeture label in stack
let temptext = hStack.addText('\xa0\xa0'+ Math.round(curTemp).toString()+"\u2103");
temptext.font = Font.regularSystemFont(18);
temptext.textColor = themeColor;
temptext.textOpacity = (0.7);
temptext.centerAlignText();
// Bottom Spacer
widgetHello.addSpacer();
widgetHello.setPadding(0, 0, 0, 0);
// Background image
widgetHello.backgroundImage = Image.fromFile(backgroundImageURL);
// Set widget
Script.setWidget(widgetHello);