Skip to content

Commit

Permalink
chore: Merge branch 'v0.5.4'
Browse files Browse the repository at this point in the history
  • Loading branch information
milouse committed Jun 1, 2020
2 parents 7575637 + 5c9cfdf commit 44bb1f4
Show file tree
Hide file tree
Showing 10 changed files with 465 additions and 246 deletions.
2 changes: 1 addition & 1 deletion chwall/__init__.py
Original file line number Diff line number Diff line change
@@ -1 +1 @@
__version__ = "0.5.3"
__version__ = "0.5.4"
30 changes: 13 additions & 17 deletions chwall/daemon.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import subprocess

# chwall imports
from chwall import __version__
from chwall.utils import BASE_CACHE_PATH, read_config, cleanup_cache, \
get_logger
from chwall.wallpaper import pick_wallpaper, ChwallWallpaperSetError, \
Expand Down Expand Up @@ -62,28 +63,22 @@ def daemon_change_label(last_change, next_change):
if last_change > 60:
last_change_m = int(last_change / 60)
last_change_s = last_change % 60
if last_change_m < 2:
last_change_label = (
_("Last change was 1 minute and {seconds}s ago")
.format(seconds=last_change_s))
else:
last_change_label = (
_("Last change was {minutes} minutes and {seconds}s ago")
.format(minutes=last_change_m, seconds=last_change_s))
last_change_label = gettext.ngettext(
"Last change was {minutes} minute and {seconds}s ago",
"Last change was {minutes} minutes and {seconds}s ago",
last_change_m
).format(minutes=last_change_m, seconds=last_change_s)
else:
last_change_label = (_("Last change was {seconds}s ago")
.format(seconds=last_change))
if next_change > 60:
next_change_m = int(next_change / 60)
next_change_s = next_change % 60
if next_change_m < 2:
next_change_label = (
_("Next change in 1 minute and {seconds}s")
.format(seconds=next_change_s))
else:
next_change_label = (
_("Next change in {minutes} minutes and {seconds}s")
.format(minutes=next_change_m, seconds=next_change_s))
next_change_label = gettext.ngettext(
"Next change in {minutes} minute and {seconds}s",
"Next change in {minutes} minutes and {seconds}s",
next_change_m
).format(minutes=next_change_m, seconds=next_change_s)
else:
next_change_label = (_("Next change in {seconds}s")
.format(seconds=next_change))
Expand Down Expand Up @@ -240,7 +235,8 @@ def start_daemon():
daemonize()
with open("{}/chwall_pid".format(BASE_CACHE_PATH), "w") as f:
f.write(str(os.getpid()))
logger.info(_("Start loop"))
logger.info(_("Starting Chwall Daemon v{version}…")
.format(version=__version__))
sys.exit(daemon_loop())


Expand Down
8 changes: 4 additions & 4 deletions chwall/fetcher/bing.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,11 @@ def fetch_pictures(config):
pictures = {}
already_done = []
url = "https://www.bing.com/HPImageArchive.aspx?format=js&n=8&mkt={}"
for l in i18n_src:
lu = "{}[0-9]{{10}}".format(l.upper())
data = requests.get(url.format(l)).json()
for lang in i18n_src:
lang_url = "{}[0-9]{{10}}".format(lang.upper())
data = requests.get(url.format(lang)).json()
for p in data["images"]:
ad = re.sub(lu, "", p["url"])
ad = re.sub(lang_url, "", p["url"])
if ad in already_done:
continue
already_done.append(ad)
Expand Down
69 changes: 69 additions & 0 deletions chwall/fetcher/pexels.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
import requests

from chwall.utils import get_logger

import gettext
# Uncomment the following line during development.
# Please, be cautious to NOT commit the following line uncommented.
# gettext.bindtextdomain("chwall", "./locale")
gettext.textdomain("chwall")
_ = gettext.gettext

logger = get_logger(__name__)


def fetch_pictures(config):
px_conf = config.get("pexels", {})
client_id = px_conf.get("access_key")
if client_id is None:
logger.error(
_("An `access_key' param is required to fetch pictures "
"from Pexels.")
)
return {}
width = px_conf.get("width", 1600)
params = {"per_page": px_conf.get("count", 10)}
if "query" in px_conf:
params["query"] = px_conf["query"]
url = "https://api.pexels.com/v1/search"
else:
url = "https://api.pexels.com/v1/curated"
pictures = {}
data = requests.get(
url,
params=params,
headers={"Authorization": client_id}
).json()
for p in data["photos"]:
px = p["src"]["original"] + "?auto=compress&width={}".format(width)
pictures[px] = {
"image": px,
"author": p["photographer"],
"url": p["url"],
"type": "Pexels"
}
return pictures


def preferences():
return {
"name": "Pexels",
"options": {
"width": {
"widget": "number",
"default": 1600
},
"count": {
"widget": "number",
"default": 10
},
"access_key": {
"widget": "text",
"label": _("API access key")
},
"query": {
"widget": "text",
"label": _("Search query")
}
}
}
4 changes: 2 additions & 2 deletions chwall/fetcher/unsplash.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ def fetch_pictures(config):
if len(label) > 200:
label = label[0:200] + "…"
location = p.get("location", {}).get("title", "")
if location != "":
if location is not None and location != "":
label = (_("{desc}, taken in {location}")
.format(desc=label, location=location))
pictures[px] = {
Expand All @@ -71,7 +71,7 @@ def preferences():
},
"access_key": {
"widget": "text",
"label": _("API access_key")
"label": _("API access key")
},
"query": {
"widget": "text",
Expand Down
31 changes: 19 additions & 12 deletions chwall/gui/preferences.py
Original file line number Diff line number Diff line change
Expand Up @@ -605,10 +605,12 @@ def on_cleanup_cache(widget, update_label, clear_all=False):
deleted = cleanup_cache(clear_all)
if deleted == 0:
return
if deleted < 2:
message = _("{number} cache entry has been removed.")
else:
message = _("{number} cache entries have been removed.")

message = gettext.ngettext(
"{number} cache entry has been removed.",
"{number} cache entries have been removed.",
deleted
).format(number=deleted)

widget.get_parent().foreach(update_label)

Expand All @@ -618,7 +620,7 @@ def on_cleanup_cache(widget, update_label, clear_all=False):
_("Cache cleanup")
)
dialog.set_icon_name("chwall")
dialog.format_secondary_text(message.format(number=deleted))
dialog.format_secondary_text(message)
dialog.run()
dialog.destroy()

Expand All @@ -628,20 +630,25 @@ def on_cleanup_cache(widget, update_label, clear_all=False):
for pic in os.scandir(pic_cache):
if pic.stat().st_size == 0:
broken_files += 1
if broken_files < 2:
label = _("{number} broken picture currently in cache")
else:
label = _("{number} broken pictures currently in cache")

label = gettext.ngettext(
"{number} broken picture currently in cache",
"{number} broken pictures currently in cache",
broken_files
).format(number=broken_files)

def _update_broken_label(sibling):
if isinstance(sibling, Gtk.Label):
sibling.set_label(
_("{number} broken picture currently in cache")
.format(number="0")
gettext.ngettext(
"{number} broken picture currently in cache",
"{number} broken pictures currently in cache",
0
).format(number=0)
)

prefbox = self.make_button_row(
label.format(number=broken_files),
label,
_("Clear broken pictures"),
on_cleanup_cache,
"destructive-action",
Expand Down
96 changes: 72 additions & 24 deletions chwall/wallpaper.py
Original file line number Diff line number Diff line change
Expand Up @@ -155,11 +155,11 @@ def set_nitrogen_wallpaper(path):
cmd = ["nitrogen", "--set-zoom-fill", "--set-color=#000000", "--save"]
# screen_info = (scr_number, scr_width, scr_height, scr_ratio, display)
screen_info = get_screen_config()
# wall_info = (wall_width, wall_height, wall_ratio)
wall_info = get_wall_config(path)
if wall_info is None:
wall_info = (0, 0, 1)
ratio_cmp = int(screen_info[3]) - int(wall_info[2])
# wall_spec = (wall_width, wall_height, wall_ratio)
wall_spec = get_wall_config(path)
if wall_spec is None:
wall_spec = (0, 0, 1)
ratio_cmp = int(screen_info[3]) - int(wall_spec[2])
if screen_info[0] > 1 and ratio_cmp != 0:
err = 0
for screen_index in range(screen_info[0]):
Expand Down Expand Up @@ -216,23 +216,54 @@ def set_wallpaper(path, config):
return path


def fetch_wallpaper(collecs):
wp = collecs["data"][collecs["pictures"][0]]
current_wall = clean_wallpaper_info(wp)
with open("{}/current_wallpaper".format(BASE_CACHE_PATH), "w") as f:
for line in current_wall:
f.write(line + "\n")
pic_file = current_wall[-1]
def fetch_wallpaper(wp_data):
current_wall = clean_wallpaper_info(wp_data)
pic_file = current_wall[4]

def _write_current_wallpaper_info(current_wall):
with open("{}/current_wallpaper".format(BASE_CACHE_PATH), "w") as f:
for line in current_wall:
f.write(line + "\n")

if os.path.exists(pic_file):
return pic_file, wp["image"]
with open(pic_file, "wb") as f:
f.write(requests.get(wp["image"]).content)
_write_current_wallpaper_info(current_wall)
return pic_file, current_wall[0]

try_again = 5
while try_again > 0:
try:
pic_data = requests.get(current_wall[0]).content
with open(pic_file, "wb") as f:
f.write(pic_data)
break
except (requests.exceptions.ConnectionError,
requests.exceptions.HTTPError,
requests.exceptions.Timeout) as e:
logger.error(
_("Catch {error} exception while downloading {picture}. "
"Wait {time} seconds before retrying.")
.format(error=type(e).__name__, picture=current_wall[0],
time=WAIT_ERROR)
)
try_again -= 1
try:
time.sleep(WAIT_ERROR)
except KeyboardInterrupt:
logger.warning(_("Retry NOW to download {picture}")
.format(picture=current_wall[0]))

if not os.path.exists(pic_file):
# We probably went here because of a network error. Thus do nothing yet
# and move back without anything.
return None, None
if os.path.getsize(pic_file) == 0:
# Do not keep empty files. It may be caused by a network error or
# something else, which may be resolved later.
os.unlink(pic_file)
return None, None
return pic_file, wp["image"]

_write_current_wallpaper_info(current_wall)
return pic_file, current_wall[0]


def pick_wallpaper(config, backward=False, guard=False):
Expand All @@ -241,13 +272,18 @@ def pick_wallpaper(config, backward=False, guard=False):
build_roadmap(config)
with open(road_map, "r") as f:
data = yaml.safe_load(f)
must_advance = len(data.get("pictures", [])) == 0 and backward is False
if must_advance or data is None:
no_pic_left = len(data.get("pictures", [])) == 0 and backward is False
if no_pic_left or data is None:
# Woops, no picture left. Removing current roadmap.
os.unlink(road_map)
if guard is True:
# Wow, we already try to reload once, it's very bad to be
# there. Maybe a little network error. Be patient
logger.error(
_("Impossible to build a new road map. It may be "
"caused by a temporarily network error. Please "
"try again later.")
)
return None
# List is empty. Maybe it was the last picture of the current list?
# Thus, try again now. Backward is always false because at this point,
Expand All @@ -262,20 +298,29 @@ def pick_wallpaper(config, backward=False, guard=False):
# Previous one
data["pictures"].insert(0, data["history"].pop())
# Now we are good to do a fake "forward" move
lp, wp = fetch_wallpaper(data)
lp, wp = fetch_wallpaper(data["data"][data["pictures"][0]])
if lp is None:
# Something goes wrong, thus do nothing. It may be because of a
# networking error or something else.
# In any case, we remove the current roadmap file to force its
# recomputing the next time pick_wallpaper is called.
os.unlink(road_map)
logger.error(
_("Impossible to get any picture at this time. It may be "
"caused by a temporarily network error. Please try again "
"later.")
)
return None
data["pictures"].remove(wp)
data["history"].append(wp)
with open(road_map, "w") as f:
yaml.dump(data, f, explicit_start=True,
default_flow_style=False)
return set_wallpaper(lp, config)
try:
lp = set_wallpaper(lp, config)
except OSError as e:
logger.error("{}: {}".format(type(e).__name__, e))
remove_wallpaper_from_roadmap(wp)
# Try again for next wallpaper
return pick_wallpaper(config, backward)
return lp


def remove_wallpaper_from_roadmap(wp):
Expand All @@ -287,6 +332,9 @@ def remove_wallpaper_from_roadmap(wp):
if wp in data.get("history", []):
data["history"].remove(wp)
if wp in data.get("data", {}):
wallinfo = clean_wallpaper_info(data["data"][wp])
if wallinfo[3] != "local" and os.path.exists(wallinfo[4]):
os.unlink(wallinfo[4])
del data["data"][wp]
with open(road_map, "w") as f:
yaml.dump(data, f, explicit_start=True,
Expand Down Expand Up @@ -326,7 +374,7 @@ def clean_wallpaper_info(data):
rights = data.get("copyright")
if rights is None or rights == "":
rights = _("{title} by {author}").format(
title=data.get("description", "Picture"),
title=data.get("description", _("Picture")),
author=data.get("author", "unknown"))
description = _("{title} (on {source})").format(
title=rights.replace("\n", " "),
Expand Down
Loading

0 comments on commit 44bb1f4

Please sign in to comment.