summary refs log tree commit diff stats
path: root/main.go
blob: 9f506f4faf904fbe8cf2d1a1f74e61a7410cc47d (plain) (blame)
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
// Copyright (c) 2020, Andinus <andinus@inventati.org>

// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.

// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

package main

import (
	"encoding/json"
	"flag"
	"fmt"
	"io/ioutil"
	"log"
	"net/http"
	"os/exec"
	"time"
)

var (
	err     error
	timeout time.Duration
)

func main() {
	var (
		imgPath string

		apod       bool
		apodAPI    string
		apodAPIKey string
	)

	// Parse flags passed to program
	flag.StringVar(&imgPath, "img-path", "", "Image to set as wallpaper")

	flag.BoolVar(&apod, "apod", false, "Set Astronomy Picture of the Day as wallpaper")
	flag.StringVar(&apodAPI, "apod-api", "https://api.nasa.gov/planetary/apod", "APOD API URL")
	flag.StringVar(&apodAPIKey, "apod-api-key", "DEMO_KEY", "APOD API Key")

	flag.DurationVar(&timeout, "timeout", 16, "Timeout for http client")

	flag.Parse()

	if len(imgPath) > 0 {
		err = setWall(imgPath)
		errChk(err)
		return
	}

	if apod != false {
		apodI := make(map[string]string)
		apodI["api"] = apodAPI
		apodI["apiKey"] = apodAPIKey

		err = setWallFromAPOD(apodI)
		errChk(err)
		return
	}
}

// Calls feh to set the wallpaper
func setWall(imgPath string) error {
	feh, err := exec.LookPath("feh")
	if err != nil {
		fmt.Println("Error: feh is not in $PATH")
		return err
	}

	fmt.Printf("Path to set as Wallpaper: %s\n", imgPath)

	err = exec.Command(feh, "--bg-fill", imgPath).Run()
	return err
}

// Get url of Astronomy Picture of the Day & pass it to setWall()
func setWallFromAPOD(apodI map[string]string) error {
	type apodRes struct {
		Copyright      string `json:"copyright"`
		Date           string `json:"string"`
		Explanation    string `json:"explanation"`
		HDURL          string `json:"hdurl"`
		MediaType      string `json:"media_type"`
		ServiceVersion string `json:"service_version"`
		Title          string `json:"title"`
		URL            string `json:"url"`
	}

	apodNow := apodRes{}

	req, err := http.NewRequest(http.MethodGet, apodI["api"], nil)
	if err != nil {
		return err
	}
	q := req.URL.Query()
	q.Add("api_key", apodI["apiKey"])
	req.URL.RawQuery = q.Encode()

	res, err := getRes(req)
	if err != nil {
		fmt.Printf("Error: GET %s\n", apodI["api"])
		return err
	}
	defer res.Body.Close()

	apiBody, err := ioutil.ReadAll(res.Body)
	if err != nil {
		return err
	}

	err = json.Unmarshal([]byte(apiBody), &apodNow)
	if err != nil {
		return err
	}

	// Set Astronomy Picture of the Day as wallpaper
	err = setWall(apodNow.HDURL)
	return err
}

func getRes(req *http.Request) (*http.Response, error) {
	client := http.Client{
		Timeout: time.Second * timeout,
	}
	res, err := client.Do(req)

	return res, err
}

func errChk(err error) {
	if err != nil {
		log.Fatal(err)
	}
}
stom_conf = fm.confpath('rc.conf') default_conf = fm.relpath('defaults', 'rc.conf') load_default_rc = fm.settings.load_default_rc # If load_default_rc is None, think hard: If the users rc.conf is # about as large as the default rc.conf, he probably copied it as a whole # and doesn't want to load the default rc.conf anymore. if load_default_rc is None: try: custom_conf_size = os.stat(custom_conf).st_size except: load_default_rc = True else: default_conf_size = os.stat(default_conf).st_size load_default_rc = custom_conf_size < default_conf_size - 2048 if load_default_rc: fm.source_cmdlist(default_conf) if os.access(custom_conf, os.R_OK): fm.source_cmdlist(custom_conf) # Load plugins try: plugindir = fm.confpath('plugins') plugins = [p[:-3] for p in os.listdir(plugindir) \ if p.endswith('.py') and not p.startswith('_')] except: pass else: if not os.path.exists(fm.confpath('plugins', '__init__.py')): f = open(fm.confpath('plugins', '__init__.py'), 'w') f.close() import types ranger.fm = fm for plugin in sorted(plugins): try: mod = __import__('plugins', fromlist=[plugin]) fm.log.append("Loaded plugin '%s'." % module) except Exception as e: fm.log.append("Error in plugin '%s'" % plugin) import traceback for line in traceback.format_exception_only(type(e), e): fm.log.append(line) ranger.fm = None allow_access_to_confdir(ranger.arg.confdir, False) else: comcont = ranger.api.commands.CommandContainer() ranger.api.commands.alias = comcont.alias from ranger.defaults import commands, keys, apps comcont.load_commands_from_object(fm, dir(Actions)) comcont.load_commands_from_module(commands) fm.commands = comcont fm.source_cmdlist(fm.relpath('defaults', 'rc.conf')) fm.apps = apps.CustomApplications() def load_apps(fm, clean): import ranger if not clean: allow_access_to_confdir(ranger.arg.confdir, True) try: import apps except ImportError: from ranger.defaults import apps allow_access_to_confdir(ranger.arg.confdir, False) else: from ranger.defaults import apps fm.apps = apps.CustomApplications() def allow_access_to_confdir(confdir, allow): if allow: try: os.makedirs(confdir) except OSError as err: if err.errno != EEXIST: # EEXIST means it already exists print("This configuration directory could not be created:") print(confdir) print("To run ranger without the need for configuration") print("files, use the --clean option.") raise SystemExit() if not confdir in sys.path: sys.path[0:0] = [confdir] else: if sys.path[0] == confdir: del sys.path[0] # Debugging functions. These will be activated when run with --debug. # Example usage in the code: # import ranger; ranger.log("hello world") def log(*objects, **keywords): """ Writes objects to a logfile (for the purpose of debugging only.) Has the same arguments as print() in python3. """ from ranger import arg if LOGFILE is None or not arg.debug or arg.clean: return start = 'start' in keywords and keywords['start'] or 'ranger:' sep = 'sep' in keywords and keywords['sep'] or ' ' _file = 'file' in keywords and keywords['file'] or open(LOGFILE, 'a') end = 'end' in keywords and keywords['end'] or '\n' _file.write(sep.join(map(str, (start, ) + objects)) + end) def log_traceback(): from ranger import arg if LOGFILE is None or not arg.debug or arg.clean: return import traceback traceback.print_stack(file=open(LOGFILE, 'a'))