-
Notifications
You must be signed in to change notification settings - Fork 0
/
applet.js
231 lines (189 loc) · 7.33 KB
/
applet.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
const Applet = imports.ui.applet;
const Soup = imports.gi.Soup;
const Gio = imports.gi.Gio;
const GLib = imports.gi.GLib;
const Mainloop = imports.mainloop;
const Lang = imports.lang;
const logging = false;
const _httpSession = new Soup.SessionAsync();
Soup.Session.prototype.add_feature.call(_httpSession, new Soup.ProxyResolverDefault());
const bingHost = 'https://www.bing.com';
const bingRequestPath = '/HPImageArchive.aspx?format=js&idx=0&n=1&mbl=1&mkt=en-US';
function log(message) {
if (logging) global.log(`[bing-wallpaper@starcross.dev]: ${message}`);
}
function BingWallpaperApplet(orientation, panel_height, instance_id) {
this._init(orientation, panel_height, instance_id);
}
BingWallpaperApplet.prototype = {
__proto__: Applet.IconApplet.prototype,
_init: function (orientation, panel_height, instance_id) {
// Generic Setup
Applet.IconApplet.prototype._init.call(this, orientation, panel_height, instance_id);
this.set_applet_icon_name("bing-wallpaper-symbolic");
this.set_applet_tooltip('Bing Desktop Wallpaper');
// Path to store data in
this.wallpaperDir = `${GLib.get_user_config_dir()}/bingwallpaper`;
let dir = Gio.file_new_for_path(this.wallpaperDir);
if (!dir.query_exists(null))
dir.make_directory(null);
this.wallpaperPath = `${this.wallpaperDir}/BingWallpaper.jpg`;
this.metaDataPath = `${this.wallpaperDir}/meta.json`;
// Begin refresh loop
this._refresh();
},
_refresh: function () {
log(`Beginning refresh`);
// const now = GLib.DateTime.new_now_utc();
// const today = GLib.DateTime.new_utc(now.get_year(), now.get_month(), now.get_day_of_month(), 0, 0, 0);
//
// let file = Gio.file_new_for_path(this.wallpaperPath);
// let file_exists = file.query_exists(null);
//
// if (file_exists) {
// let file_info = file.query_info('*', Gio.FileQueryInfoFlags.NONE, null);
// let file_size = file_info.get_size();
// let file_mod_secs = file_info.get_modification_time().tv_sec;
//
// if ((file_mod_secs < today.to_unix()) || !file_size) { // Is the image old, or empty?
// log("Calling getMetaData");
// this._getMetaData();
// } else {
// log("Skipping, image appears up to date");
//
// }
// } else { // Image does not exist yet
// this._getMetaData()
// }
this._getMetaData();
this._setTimeout(300);
},
_removeTimeout: function () {
if (this._timeout) {
Mainloop.source_remove(this._timeout);
this._timeout = null;
}
},
_setTimeout: function (seconds) {
/** Cancel current timeout in event of an error and try again shortly */
this._removeTimeout();
log(`Setting timeout (${seconds}s)`);
this._timeout = Mainloop.timeout_add_seconds(seconds, Lang.bind(this, this._refresh));
},
destroy: function () {
this._removeTimeout();
},
on_applet_removed_from_panel() {
this._removeTimeout();
},
_getMetaData: function () {
/** Check for local metadata */
try {
const jsonString = GLib.file_get_contents(this.metaDataPath)[1];
const json = JSON.parse(jsonString);
this.imageData = json.images[0];
this.set_applet_tooltip(this.imageData.copyright);
log(`Got image url from local file : ${this.imageData.url}`);
/** See if this data is current */
const start_date = GLib.DateTime.new(
GLib.TimeZone.new_utc(),
this.imageData.fullstartdate.substring(0,4),
this.imageData.fullstartdate.substring(4,6),
this.imageData.fullstartdate.substring(6,8),
this.imageData.fullstartdate.substring(8,10),
this.imageData.fullstartdate.substring(10,12),
0
);
const end_date = start_date.add_days(1);
const now = GLib.DateTime.new_now_utc();
if (now.to_unix() < end_date.to_unix()) {
log('metadata up to date');
// Look for image file, check this is up to date
let image_file = Gio.file_new_for_path(this.wallpaperPath);
if (image_file.query_exists(null)) {
let image_file_info = image_file.query_info('*', Gio.FileQueryInfoFlags.NONE, null);
let image_file_size = image_file_info.get_size();
let image_file_mod_secs = image_file_info.get_modification_time().tv_sec;
if ((image_file_mod_secs > end_date.to_unix()) || !image_file_size) { // Is the image old, or empty?
this._downloadImage();
} else {
log("image appears up to date");
}
} else {
log("No image file found");
this._downloadImage();
}
}
else {
log('metadata is old, requesting new...');
this._downloadMetaData();
}
} catch (err) {
log(`Unable to get local metadata ${err}`);
/** File does not exist or there was an error processing it */
this._downloadMetaData();
}
},
_downloadMetaData: function () {
// Retrieve json metadata, either from local file or remote
let request = Soup.Message.new('GET', `${bingHost}${bingRequestPath}`);
_httpSession.queue_message(request, (_httpSession, message) => {
if (message.status_code === 200) {
// Write to meta data file
let gFile = Gio.file_new_for_path(this.metaDataPath);
let fStream = gFile.replace(null, false, Gio.FileCreateFlags.NONE, null);
let toWrite = message.response_body.data.length;
while (toWrite > 0)
toWrite -= fStream.write(message.response_body.data, null);
fStream.close(null);
const json = JSON.parse(message.response_body.data);
this.imageData = json.images[0];
this.set_applet_tooltip(this.imageData.copyright);
log(`Got image url from download: ${this.imageData.url}`);
this._downloadImage();
} else {
log(`Failed to acquire image metadata (${message.status_code})`);
this._setTimeout(60) // Try again
}
});
},
_downloadImage: function () {
log('downloading new image');
const url = `${bingHost}${this.imageData.url}`;
let gFile = Gio.file_new_for_path(this.wallpaperPath);
// open the file
let fStream = gFile.replace(null, false, Gio.FileCreateFlags.NONE, null);
// create an http message
let request = Soup.Message.new('GET', url);
// got_chunk event
request.connect('got_chunk', function (message, chunk) {
if (message.status_code === 200) { // only save the data we want, not content of 301 redirect page
fStream.write(chunk.get_data(), null);
}
});
// queue the http request
_httpSession.queue_message(request, (httpSession, message) => {
// request completed
fStream.close(null);
if (message.status_code === 200) {
log('Download successful');
this._setBackground();
} else {
log("Couldn't fetch image from " + url);
this._setTimeout(60) // Try again
}
});
},
_setBackground: function () {
let gSetting = new Gio.Settings({schema: 'org.cinnamon.desktop.background'});
const uri = 'file://' + this.wallpaperPath;
gSetting.set_string('picture-uri', uri);
gSetting.set_string('picture-options', 'zoom');
Gio.Settings.sync();
gSetting.apply();
}
};
function main(metadata, orientation, panelHeight, instanceId) {
let bingApplet = new BingWallpaperApplet(orientation, panelHeight, instanceId);
return bingApplet;
}