Skip to content

Commit

Permalink
improve handling of china market #20, add italian translation #14, im…
Browse files Browse the repository at this point in the history
…prove notification #19
  • Loading branch information
neffo committed Oct 2, 2017
1 parent a51cb95 commit dc3e6c7
Show file tree
Hide file tree
Showing 8 changed files with 371 additions and 98 deletions.
5 changes: 4 additions & 1 deletion buildzip.sh
@@ -1,8 +1,11 @@
#!/bin/bash

glib-compile-schemas schemas/
intltool-extract --type=gettext/glade Settings.ui
xgettext -k -k_ -kN_ -o locale/BingWallpaper.pot Settings.ui.h extension.js prefs.js --from-code=UTF-8

rm BingWallpaper@ineffable-gmail.com.zip

zip -r BingWallpaper@ineffable-gmail.com.zip *

zip -d BingWallpaper@ineffable-gmail.com.zip screenshot/* screenshot buildzip.sh

130 changes: 89 additions & 41 deletions extension.js
Expand Up @@ -10,6 +10,8 @@ const GLib = imports.gi.GLib;
const Util = imports.misc.util;
const PanelMenu = imports.ui.panelMenu;
const PopupMenu = imports.ui.popupMenu;
const Clipboard = St.Clipboard.get_default();
const CLIPBOARD_TYPE = St.ClipboardType.CLIPBOARD;

const ExtensionUtils = imports.misc.extensionUtils;
const Me = ExtensionUtils.getCurrentExtension();
Expand All @@ -19,12 +21,12 @@ const Convenience = Me.imports.convenience;
const Gettext = imports.gettext.domain('BingWallpaper');
const _ = Gettext.gettext;

const BingImageURL = "https://www.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1&mkt=";
const BingImageURL = "https://www.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1&mbl=1&mkt=";
const BingURL = "https://bing.com";
const IndicatorName = "BingWallpaperIndicator";
const TIMEOUT_SECONDS = 24 * 3600; // FIXME: this should use the end data from the json data
const TIMEOUT_SECONDS_ON_HTTP_ERROR = 1 * 3600; // retry in on-hour if there is a http error
const ICON = "bing"
const ICON = "bing";

let monitors;
let validresolutions = [ '800x600' , '1024x768', '1280x720', '1280x768', '1366x768', '1920x1080', '1920x1200'];
Expand All @@ -36,7 +38,6 @@ let autores; // automatically selected resolution

let bingWallpaperIndicator=null;


function log(msg) {
if (bingWallpaperIndicator==null || bingWallpaperIndicator._settings.get_boolean('debug-logging'))
print("BingWallpaper extension: " + msg); // disable to keep the noise down in journal
Expand All @@ -63,37 +64,19 @@ const LongNotification = new Lang.Class({
}
});

function notify(msg, details, transient) {
// set notifications icon
let source = new MessageTray.Source("BingWallpaper", ICON);
// force expanded notification
source.policy = new MessageTray.NotificationPolicy({ enable: true,
enableSound: false,
showBanners: true,
forceExpanded: true,
showInLockScreen: true,
detailsInLockScreen: true
});
Main.messageTray.add(source);
let notification = new LongNotification(source, msg, details);
notification.setTransient(transient);
// Add action to open Bing website with default browser
notification.addAction(_("Bing website"), Lang.bind(this, function() {
Util.spawn(["xdg-open", BingURL]);
}));
source.notify(notification);
}

function notifyError(msg) {
Main.notifyError("BingWallpaper extension error", msg);
}

function doSetBackground(uri, schema) {
let gsettings = new Gio.Settings({schema: schema});
gsettings.set_string('picture-uri', 'file://' + uri);
let prev = gsettings.get_string('picture-uri');
uri = 'file://'+ uri;
gsettings.set_string('picture-uri', uri);
gsettings.set_string('picture-options', 'zoom');
Gio.Settings.sync();
gsettings.apply();
return (prev != uri); // return true if background uri has changed
}

let httpSession = new Soup.SessionAsync();
Expand All @@ -117,6 +100,8 @@ const BingWallpaperIndicator = new Lang.Class({
this._updatePending = false;
this._timeout = null;
this.longstartdate = null;
this.imagelink = "";
this.imageURL= "";

this._settings = Utils.getSettings();
this._settings.connect('changed::hide', Lang.bind(this, function() {
Expand All @@ -127,16 +112,19 @@ const BingWallpaperIndicator = new Lang.Class({

this.refreshDueItem = new PopupMenu.PopupMenuItem(_("<No refresh scheduled>"));
this.showItem = new PopupMenu.PopupMenuItem(_("Show description"));
this.clipboardItem = new PopupMenu.PopupMenuItem(_("Copy image URL to clipboard"));
this.wallpaperItem = new PopupMenu.PopupMenuItem(_("Set wallpaper"));
this.refreshItem = new PopupMenu.PopupMenuItem(_("Refresh Now"));
this.settingsItem = new PopupMenu.PopupMenuItem(_("Settings"));
this.menu.addMenuItem(this.refreshDueItem);
this.menu.addMenuItem(this.showItem);
this.menu.addMenuItem(this.clipboardItem);
this.menu.addMenuItem(this.wallpaperItem);
this.menu.addMenuItem(this.refreshItem);
this.menu.addMenuItem(this.settingsItem);
this.refreshDueItem.setSensitive(false);
this.showItem.connect('activate', Lang.bind(this, this._showDescription));
this.clipboardItem.connect('activate', Lang.bind(this, this._copyURLToClipboard));
this.wallpaperItem.connect('activate', Lang.bind(this, this._setBackground));
this.refreshItem.connect('activate', Lang.bind(this, this._refresh));
this.settingsItem.connect('activate', function() {
Expand All @@ -146,21 +134,56 @@ const BingWallpaperIndicator = new Lang.Class({
this.actor.connect('button-press-event', Lang.bind(this, function () {
// Grey out menu items if an update is pending
this.refreshItem.setSensitive(!this._updatePending);
this.clipboardItem.setSensitive(!this._updatePending && this.imageURL != "");
this.showItem.setSensitive(!this._updatePending && this.title != "" && this.explanation != "");
this.wallpaperItem.setSensitive(!this._updatePending && this.filename != "");
}));
this._restartTimeout(60); // wait 60 seconds before performing refresh
},

_notify: function(msg, details, transient, show_prefs) {
// set notifications icon
let source = new MessageTray.Source("BingWallpaper", ICON);
// force expanded notification
source.policy = new MessageTray.NotificationPolicy({ enable: true,
enableSound: false,
showBanners: true,
forceExpanded: true,
showInLockScreen: true,
detailsInLockScreen: true
});
Main.messageTray.add(source);
let notification = new LongNotification(source, msg, details);
notification.setTransient(transient);
// Add action to open Bing website with default browser
if (show_prefs !== false) {
notification.addAction(_("Open extension settings"), Lang.bind(this, function() {
Util.spawn(["gnome-shell-extension-prefs", Me.metadata.uuid]);
}));
}
else {
notification.addAction(_("Bing website"), Lang.bind(this, function() {
Util.spawn(["xdg-open", this.imagelink ? this.imagelink : BingURL]);
}));
}
source.notify(notification);
},

_setBackground: function() {
let changed = false;
if (this.filename == "")
return;
if (this._settings.get_boolean('set-background')) {
doSetBackground(this.filename, 'org.gnome.desktop.background');
changed = doSetBackground(this.filename, 'org.gnome.desktop.background');
}
if (this._settings.get_boolean('set-lock-screen')) {
doSetBackground(this.filename, 'org.gnome.desktop.screensaver');
changed = changed || doSetBackground(this.filename, 'org.gnome.desktop.screensaver');
}
return changed;
},

_copyURLToClipboard: function() {
Clipboard.set_text(CLIPBOARD_TYPE, this.imageURL);
},

_restartTimeout: function(seconds = null) {
Expand All @@ -180,13 +203,13 @@ const BingWallpaperIndicator = new Lang.Class({
// 201708041400 YYYYMMDDHHMM
// 012345678901
let timezone = GLib.TimeZone.new_utc();
let refreshDue = GLib.DateTime.new(timezone,
let refreshDue = GLib.DateTime.new(timezone,
parseInt(longdate.substr(0,4)), // year
parseInt(longdate.substr(4,2)), // month
parseInt(longdate.substr(6,2)), // day
parseInt(longdate.substr(8,2)), // hour
parseInt(longdate.substr(10,2)), // mins
0 ).add_seconds(86400); // seconds
0 ).add_seconds(86400); // seconds

let now = GLib.DateTime.new_now(timezone);
let difference = refreshDue.difference(now)/1000000;
Expand All @@ -200,14 +223,25 @@ const BingWallpaperIndicator = new Lang.Class({
this._restartTimeout(difference);
},

// convert shortdate format into human friendly format
_localeDate: function (shortdate) {
let timezone = GLib.TimeZone.new_local(); // TZ doesn't really matter for this
let date = GLib.DateTime.new(timezone,
parseInt(shortdate.substr(0,4)), // year
parseInt(shortdate.substr(4,2)), // month
parseInt(shortdate.substr(6,2)), // day
0, 0, 0 );
return date.format('%Y-%m-%d'); // ISO 8601 - https://xkcd.com/1179/
},

_showDescription: function() {
if (this.title == "" && this.explanation == "") {
this._refresh();
} else {
let message = this.explanation;
if (this.copyright != "")
message += "\n" + this.copyright + ""
notify(this.title, message, this._settings.get_boolean('transient'));
message += "\n" + this.copyright;
this._notify(this.title, message, this._settings.get_boolean('transient'), false);
}
},

Expand Down Expand Up @@ -246,26 +280,38 @@ const BingWallpaperIndicator = new Lang.Class({
_parseData: function(data) {
let parsed = JSON.parse(data);
let imagejson = parsed['images'][0];
let datamarket = parsed['market']['mkt'];
let prefmarket = this._settings.get_string('market');

if (datamarket != prefmarket) {
this._notify(
_("Market not available in your region"),_("The selected market is not available in your country or geographic region.\n")
+ '(Mismatch Req: '+prefmarket +' != Recv: ' + datamarket +')',
false, true
);
log('Mismatched market data, Req: '+prefmarket +' != Recv: ' + datamarket +')');
}

if (imagejson['url'] != '') {
this.title = imagejson['copyright'].replace(/\s*\(.*?\)\s*/g, "");
this.explanation = _("Bing Wallpaper of the Day for")+" "+imagejson['startdate']+"";
this.explanation = _("Bing Wallpaper of the Day for")+' '+this._localeDate(imagejson['startdate'])+' ('+datamarket+')';
this.copyright = imagejson['copyright'].match(/\(([^)]+)\)/)[1].replace('\*\*','');;
this.longstartdate = imagejson['fullstartdate'];
this.imagelink = BingURL+imagejson['quiz'];
let resolution = this._settings.get_string('resolution');

if (resolution == "auto") {
log("auto resolution selected ("+autores+")");
resolution = autores;
}
if (validresolutions.indexOf(resolution) == -1 || imagejson['wp'] == false ||

if (validresolutions.indexOf(resolution) == -1 || imagejson['wp'] == false ||
(this._settings.get_string('resolution') == "auto" && autores == "1920x1200") ) {
// resolution invalid, animated background, or override auto selected 1920x1200 to avoid bing logo unless user wants it
resolution = "1920x1080";
resolution = "1920x1080";
}

let url = BingURL+imagejson['url'].replace('1920x1080',resolution); // mangle url to user's resolution
this.imageURL = BingURL+imagejson['url'].replace('1920x1080',resolution); // mangle url to user's resolution

let BingWallpaperDir = this._settings.get_string('download-folder');
let userHomeDir = GLib.get_home_dir();
Expand All @@ -277,8 +323,8 @@ const BingWallpaperIndicator = new Lang.Class({
BingWallpaperDir = userHomeDir + "/Pictures/BingWallpaper/";
else if (!BingWallpaperDir.endsWith('/'))
BingWallpaperDir += '/';
this.filename = BingWallpaperDir+imagejson['startdate']+'-'+url.replace(/^.*[\\\/]/, '');

this.filename = BingWallpaperDir+imagejson['startdate']+'-'+this.imageURL.replace(/^.*[\\\/]/, '');
let file = Gio.file_new_for_path(this.filename);
let file_exists = file.query_exists(null);
let file_info = file_exists ? file.query_info ('*',Gio.FileQueryInfoFlags.NONE,null): 0;
Expand All @@ -288,10 +334,12 @@ const BingWallpaperIndicator = new Lang.Class({
if (!dir.query_exists(null)) {
dir.make_directory_with_parents(null);
}
this._download_image(url, file);
this._download_image(this.imageURL, file);
} else {
log("Image already downloaded");
this._setBackground();
let changed = this._setBackground();
if (changed === true)
this._showDescription(); // notify only if the background was changed
this._updatePending = false;
}
} else {
Expand Down Expand Up @@ -356,7 +404,7 @@ const BingWallpaperIndicator = new Lang.Class({
while(imagelist.length > maxpictures+1) {
var to_delete = imagelist.shift(); // get the first (oldest item from the list)
log("image: "+to_delete);
if (deletepictures) {
if (deletepictures && to_delete != '') {
var file = Gio.file_new_for_path(to_delete);
if (file.query_exists(null)) {
file.delete(null);
Expand Down
43 changes: 23 additions & 20 deletions icons/bing.svg
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.

1 comment on commit dc3e6c7

@neffo
Copy link
Owner Author

@neffo neffo commented on dc3e6c7 Oct 2, 2017

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

fixes #18, though i think the icon should be reactive to current theme for taskbar (not sure how to do this well)

Please sign in to comment.