summary refs log tree commit diff stats
path: root/cmd/cetus/bpod.go
diff options
context:
space:
mode:
Diffstat (limited to 'cmd/cetus/bpod.go')
-rw-r--r--cmd/cetus/bpod.go135
1 files changed, 135 insertions, 0 deletions
diff --git a/cmd/cetus/bpod.go b/cmd/cetus/bpod.go
new file mode 100644
index 0000000..f308d47
--- /dev/null
+++ b/cmd/cetus/bpod.go
@@ -0,0 +1,135 @@
+package main
+
+import (
+	"fmt"
+	"io/ioutil"
+	"os"
+	"time"
+
+	"framagit.org/andinus/cetus/pkg/background"
+	"framagit.org/andinus/cetus/pkg/bpod"
+)
+
+func execBPOD() {
+	// reqInfo holds all the parameters that needs to be sent with
+	// the request. GetJson() will pack apiKey & date in params
+	// map before sending it to another function. Adding params
+	// here will not change the behaviour of the function, changes
+	// have to be made in GetJson() too.
+	reqInfo := make(map[string]string)
+	reqInfo["api"] = string(*bpodAPI)
+
+	if *bpodRand {
+		reqInfo["random"] = "true"
+	}
+
+	cacheDir := fmt.Sprintf("%s/%s", getCacheDir(), "bpod")
+	os.MkdirAll(cacheDir, os.ModePerm)
+
+	// Check if the file is available locally, if it is then don't
+	// download it again and get it from disk.
+	//
+	// We don't know the bpod date because that will be there in
+	// response & we can't read the response without requesting
+	// it. So this will assume the bpod date to be today's date if
+	// *bpodRand is not set true. If *bpodRand is set true then we
+	// can't assume the date. Also this way too it can cause error
+	// if our assumed date doesn't matches date at the server.
+	var body string
+	var file string
+	var err error
+
+	if !*bpodRand {
+		// If not *bpodRand and the file exists then read from
+		// disk, if the file doesn't exist then get it and
+		// save it to disk.
+		file = fmt.Sprintf("%s/%s", cacheDir, time.Now().UTC().Format("2006-01-02"))
+		if _, err := os.Stat(file); err == nil {
+			data, err := ioutil.ReadFile(file)
+			chkErr(err)
+			body = string(data)
+		} else if os.IsNotExist(err) {
+			body, err = bpod.GetJson(reqInfo)
+			chkErr(err)
+
+			// Write body to the cache so that it can be
+			// read later
+			err = ioutil.WriteFile(file, []byte(body), 0644)
+			chkErr(err)
+		} else {
+			chkErr(err)
+		}
+	} else {
+		// If *bpodRand then get the file and save it to disk
+		// after unmarshal because we don't know the file name
+		// yet
+		body, err = bpod.GetJson(reqInfo)
+		chkErr(err)
+	}
+
+	// Unmarshal before dump because otherwise if we come across
+	// the date for the first time then it would just dump and
+	// exit without saving it to cache. This way we first save it
+	// to cache if *bpodRand is true.
+	res, err := bpod.UnmarshalJson(body)
+	chkErr(err)
+
+	// Correct format
+	res.Url = fmt.Sprintf("%s%s", "https://www.bing.com", res.Url)
+	dt, err := time.Parse("20060102", res.StartDate)
+	chkErr(err)
+	res.StartDate = dt.Format("2006-01-02")
+
+	file = fmt.Sprintf("%s/%s", cacheDir, res.StartDate)
+	if *bpodRand {
+		// Write body to the cache so that it can be read
+		// later
+		err = ioutil.WriteFile(file, []byte(body), 0644)
+		chkErr(err)
+	}
+
+	if *bpodDump {
+		fmt.Printf(body)
+		os.Exit(0)
+	}
+
+	// If path-only is passed then it will only print the path,
+	// even if quiet is passed. If the user wants the program to
+	// be quiet then path-only shouldn't be passed. If path-only
+	// is not passed & quiet is also not passed then print the
+	// response.
+	//
+	// Path is only printed when the media type is an image
+	// because res.HDURL is empty on non image media type.
+	if *bpodPathOnly {
+		fmt.Println(res.Url)
+	} else if !*bpodQuiet {
+		bpod.Print(res)
+	}
+
+	// Proceed only if the command was set because if it was fetch
+	// then it's already finished & should exit now.
+	if os.Args[1] == "fetch" {
+		os.Exit(0)
+	}
+
+	// Try to set background only if the media type is an image.
+	// First it downloads the image to the cache directory and
+	// then tries to set it with feh. If the download fails then
+	// it exits with a non-zero exit code.
+	imgCacheDir := fmt.Sprintf("%s/%s", cacheDir, "background")
+	os.MkdirAll(imgCacheDir, os.ModePerm)
+	imgFile := fmt.Sprintf("%s/%s", imgCacheDir, res.StartDate)
+
+	// Check if the file is available locally, if it is then don't
+	// download it again and set it from disk
+	if _, err := os.Stat(imgFile); os.IsNotExist(err) {
+		err = background.Download(imgFile, res.Url)
+		chkErr(err)
+	} else {
+		chkErr(err)
+	}
+
+	err = background.Set(imgFile)
+	chkErr(err)
+}
11-16 22:39:14 -0800 committer Kartik K. Agaram <vc@akkartik.com> 2015-11-16 22:39:14 -0800 2452' href='/akkartik/mu/commit/054dilated_reagent.cc?h=hlt&id=d18d1d3d2ac7ba0909db010649a94d01a65d98d4'>d18d1d3d ^
a796831f ^



a796831f ^

b24eb476 ^
a796831f ^
1f7e3c05 ^
79eef536 ^
21c27706 ^
79eef536 ^
a796831f ^



780b2ce1 ^
a796831f ^




a796831f ^

2d713167 ^



a796831f ^




2d713167 ^



a796831f ^



2d713167 ^



a796831f ^




d5f89e0f ^
a796831f ^



555d95c1 ^
4ad0f652 ^
a796831f ^


c4e143d6 ^

9dcbec39 ^
c4e143d6 ^


9dcbec39 ^
c4e143d6 ^


66abe7c1 ^






ce2e604e ^


c4e143d6 ^
08cf048f ^
79eef536 ^
b74443e5 ^
eb4eecea ^
66abe7c1 ^






ce2e604e ^
a17f9186 ^
a796831f ^
a796831f ^



79eef536 ^
a796831f ^
66abe7c1 ^




a072f674 ^
eb4eecea ^
a072f674 ^

a796831f ^

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
                                                                             

                                                                          


                           
          

                                  
                                              
 
                                                   
          




                                     
                                        
          

                                                  
                                              


                                                              
          



                                                

                                                                
                                       




                                                             



                                                                          

                                            
                       
                         
                                      
                        
                
                      



                                                                            
                           




                                            

                                             



                                                                 




                                             



                                                                 



                                             



                                                                 




                                     
                                                   



                                    
                          
                             


                        

                       
                                                                       


                    
                                                              


           






                                                                          


                                                            
   
                        
                               
                              
                             






                                                                          
                                                  
                                                                 
   



         
                               
                                




                                                                        
                                                    
                       

                                                

                
//: An alternative syntax for reagents that permits whitespace in properties,
//: grouped by brackets. We'll use this ability in the next layer, when we
//: generalize types from lists to trees of properties.

:(scenarios load)
:(scenario dilated_reagent)
def main [
  {1: number, foo: bar} <- copy 34
]
+parse:   product: {1: "number", "foo": "bar"}

:(scenario load_trailing_space_after_curly_bracket)
def main [
  # line below has a space at the end
  { 
]
# successfully parsed

:(scenario dilated_reagent_with_comment)
def main [
  {1: number, foo: bar} <- copy 34  # test comment
]
+parse:   product: {1: "number", "foo": "bar"}
$error: 0

:(scenario dilated_reagent_with_comment_immediately_following)
def main [
  1:number <- copy {34: literal}  # test comment
]
$error: 0

//: First augment next_word to group balanced brackets together.

:(before "End next_word Special-cases")
if (in.peek() == '(')
  return slurp_balanced_bracket(in);
// treat curlies mostly like parens, but don't mess up labels
if (start_of_dilated_reagent(in))
  return slurp_balanced_bracket(in);

:(code)
// A curly is considered a label if it's the last thing on a line. Dilated
// reagents should remain all on one line.
bool start_of_dilated_reagent(istream& in) {
  if (in.peek() != '{') return false;
  int pos = in.tellg();
  in.get();  // slurp '{'
  skip_whitespace_but_not_newline(in);
  char next = in.peek();
  in.seekg(pos);
  return next != '\n';
}

// Assume the first letter is an open bracket, and read everything until the
// matching close bracket.
// We balance {} () and [].
string slurp_balanced_bracket(istream& in) {
  ostringstream result;
  char c;
  list<char> open_brackets;
  while (in >> c) {
    if (c == '(') open_brackets.push_back(c);
    if (c == ')') {
      if (open_brackets.empty() || open_brackets.back() != '(') {
        raise << "unbalanced ')'\n" << end();
        continue;
      }
      assert(open_brackets.back() == '(');
      open_brackets.pop_back();
    }
    if (c == '[') open_brackets.push_back(c);
    if (c == ']') {
      if (open_brackets.empty() || open_brackets.back() != '[') {
        raise << "unbalanced ']'\n" << end();
        continue;
      }
      open_brackets.pop_back();
    }
    if (c == '{') open_brackets.push_back(c);
    if (c == '}') {
      if (open_brackets.empty() || open_brackets.back() != '{') {
        raise << "unbalanced '}'\n" << end();
        continue;
      }
      open_brackets.pop_back();
    }
    result << c;
    if (open_brackets.empty()) break;
  }
  skip_whitespace_and_comments_but_not_newline(in);
  return result.str();
}

:(after "Parsing reagent(string s)")
if (starts_with(s, "{")) {
  assert(properties.empty());
  istringstream in(s);
  in >> std::noskipws;
  in.get();  // skip '{'
  name = slurp_key(in);
  if (name.empty()) {
    raise << "invalid reagent '" << s << "' without a name\n" << end();
    return;
  }
  if (name == "}") {
    raise << "invalid empty reagent '" << s << "'\n" << end();
    return;
  }
  {
    string s = next_word(in);
    if (s.empty()) {
      assert(!has_data(in));
      raise << "incomplete dilated reagent at end of file (0)\n" << end();
      return;
    }
    string_tree* type_names = new string_tree(s);
    // End Parsing Dilated Reagent Type Property(type_names)
    type = new_type_tree(type_names);
    delete type_names;
  }
  while (has_data(in)) {
    string key = slurp_key(in);
    if (key.empty()) continue;
    if (key == "}") continue;
    string s = next_word(in);
    if (s.empty()) {
      assert(!has_data(in));
      raise << "incomplete dilated reagent at end of file (1)\n" << end();
      return;
    }
    string_tree* value = new string_tree(s);
    // End Parsing Dilated Reagent Property(value)
    properties.push_back(pair<string, string_tree*>(key, value));
  }
  return;
}

:(code)
string slurp_key(istream& in) {
  string result = next_word(in);
  if (result.empty()) {
    assert(!has_data(in));
    raise << "incomplete dilated reagent at end of file (2)\n" << end();
    return result;
  }
  while (!result.empty() && *result.rbegin() == ':')
    strip_last(result);
  while (isspace(in.peek()) || in.peek() == ':')
    in.get();
  return result;
}