aboutsummaryrefslogtreecommitdiff
path: root/bom.el
blob: b97e7c1cf3ab2038a1b9dceb95b258b7b012d33e (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
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
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
;;; bom.el -- Australian weather forecast from the Bureau -*- lexical-binding: t -*-

;; Copyright (C) 2023  Free Software Foundation, Inc.

;; Author: Yuchen Pei <id@ypei.org>
;; Package-Requires: ((emacs "28.2") (web-server "0.0.2"))

;; This file is part of bom.el.

;; bom.el is free software: you can redistribute it and/or modify it
;; under the terms of the GNU Affero General Public License as
;; published by the Free Software Foundation, either version 3 of the
;; License, or (at your option) any later version.

;; bom.el is distributed in the hope that it will be useful, but WITHOUT
;; ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
;; or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero General
;; Public License for more details.

;; You should have received a copy of the GNU Affero General Public
;; License along with bom.el.  If not, see <https://www.gnu.org/licenses/>.

;;; Commentary:

;; Australian weather forecast from the Bureau. A client that
;; downloads weather forecast and serves them using emacs-web-server.

;;; Code:

(require 'hierarchy)
(require 'web-server)
(require 'ox-publish)

(defvar bom-state-files
  '((act . "IDN11060")
    (nsw . "IDN11060")
    (nt . "IDD10207")
    (qld . "IDQ11295")
    (sa . "IDS10044")
    (tas . "IDT16710")
    (vic . "IDV10753")
    (wa . "IDW14199"))
  "Alist of states and territories and their corresponding filenames on the BOM FTP server, see <http://www.bom.gov.au/catalogue/data-feeds.shtml>.")

(defun bom-api (state)
  "Get weather forecast data of STATE from the BOM FTP."
  (if-let ((filename (alist-get (intern (downcase state)) bom-state-files)))
      (let* ((buffer (find-file-noselect
                      (format
                       "/ftp:anonymous@ftp.bom.gov.au:/anon/gen/fwo/%s.xml"
                       filename)))
             (result (with-current-buffer buffer
                       (libxml-parse-xml-region (point-min) (point-max)))))
        (kill-buffer buffer)
        result)
    (user-error "State %s not found" state)))

(defun bom-get-areas (resp)
  "Given an API response RESP, get all areas."
  (dom-children (dom-by-tag resp 'forecast)))

(defvar bom-areas nil "List of areas with forecasts.")

(defvar bom-server nil "The server object.")

(defvar bom-port 9000 "The port number of the server.")

(defun bom-area-parent (area)
  "Search `bom-areas' for the parent of AREA.

Used as parentfn for hierarchy."
  (let ((parent-aac (dom-attr area 'parent-aac)))
    (cl-find-if
     (lambda (area)
       (equal (dom-attr area 'aac) parent-aac))
     bom-areas)))

(defun bom-hyphenate-downcase (name)
  "Downcase NAME and replace all space with hyphens."
  (replace-regexp-in-string " " "-" (downcase name)))

(defun bom-format-area (area level)
  "Format an AREA of LEVEL."
  (format "%s %s
:PROPERTIES:
:CUSTOM_ID: %s
:END:
%s
"
          (make-string level ?*)
          (dom-attr area 'description)
          (bom-hyphenate-downcase (dom-attr area 'description))
          (if (dom-children area)
              (concat "\n" (bom-format-forecasts (dom-children area)))
            "")))

(defun bom-area-lessp (a1 a2)
  "Compare two areas A1 and A2 based on their AAC identifier."
  (string-lessp (dom-attr a1 'aac) (dom-attr a2 'aac)))

(defun bom-format-forecasts (forecasts)
  "Format a list of FORECASTS."
  (mapconcat 'bom-format-forecast forecasts "\n"))

(defun bom-format-forecast (forecast)
  "Format a FORECAST period."
  (let ((date (substring (dom-attr forecast 'start-time-local) 5 10))
        (data (dom-children forecast))
        (min-temp) (max-temp) (precis) (prec-prob))
    (dolist (item data)
      (pcase (dom-attr item 'type)
        ("air_temperature_minimum" (setq min-temp (dom-text item)))
        ("air_temperature_maximum" (setq max-temp (dom-text item)))
        ("probability_of_precipitation" (setq prec-prob (dom-text item)))
        ("precis" (setq precis (dom-text item)))))
    (format "- %s :: %s %s %s"
            date prec-prob precis (bom-format-temp-range min-temp max-temp))))

(defun bom-format-temp-range (min-temp max-temp)
  "Format a temperature range from MIN-TEMP to MAX-TEMP."
  (if (or min-temp max-temp)
      (format "%s - %s"
              (if min-temp (concat min-temp "C") "")
              (if max-temp (concat max-temp "C") ""))
    ""))

(defun bom-format-areas-org (areas)
  "Format hierarchy of AREAS with forecasts into an org string.

We use the description of the first root as the state name.

The org string is ready to be inserted into an empty buffer for
display or export."
  (let ((state-name (dom-attr (car (hierarchy-roots areas)) 'description)))
    (format "#+title: %s weather forecast

[[elisp:(bom)][Back]]

%s"
            state-name
            (string-join
             (hierarchy-map 'bom-format-area areas 1)
             "\n"))))

(defun bom-to-path (sexp)
  "Given an SEXP, return the corresponding path.

For example, (foo \"bar\" \"baz\") is converted to /foo/bar/baz."
  (pcase-let ((`(,func . ,args) (read sexp)))
    (unless (and (symbolp func)
                 (memq func '(bom bom-state))
                 (every 'stringp args))
      (user-error "Invalid sexp: %s" sexp))
    (format "/%s"
            (string-join (cons (format "%s" func) args) "/"))))

(defun bom-elisp-link-export (link desc format)
  "An :export function for elisp: links.

Takes a LINK with description DESC, assuming FORMAT is html,
output the http path."
  (cl-assert (eq format 'html))
  (format "<a href=\"%s\">%s</a>"
          (bom-to-path link)
          (or desc link)))

(defun bom-org-to-html (s)
  "Export org string S to html and return the html string."
  (with-temp-buffer
    (insert s)
    (let ((org-html-postamble)
          (org-link-parameters
           (cons '("elisp" :export bom-elisp-link-export)
                 org-link-parameters)))
      (let ((result
             (org-export-as 'html)))
        (pop org-link-parameters)
        result))))

(defun bom-format-areas-html (areas)
  "Format hierarchy of AREAS with forecasts to an html string.

The html string can be sent as a web server response."
  (bom-org-to-html (bom-format-areas-org areas)))

(defun bom-get-forecasts (state)
  "Call BOM API and return hierarchy of STATE areas with forecasts."
  (let ((areas (hierarchy-new)))
    (hierarchy-add-trees
     areas
     (setq bom-areas (bom-get-areas (bom-api state)))
     'bom-area-parent)
    (hierarchy-sort areas 'bom-area-lessp)
    areas))

(defun bom-state-org (state)
  (bom-format-areas-org
   (bom-get-forecasts state)))

(defun bom-org ()
  "Format the \"landing page\" org string.

The string is ready for display or export."
  (format
   "#+title: Australia weather forecast

%s"
   (mapconcat
    (lambda (pair) (format "[[elisp:(bom-state \"%s\")][%s]]"
                           (car pair)
                           (upcase (format "%s" (car pair)))))
    bom-state-files
    " ")))

;;;###autoload
(defun bom-state (state)
  "Open bom forecast for STATE."
  (interactive (list (completing-read
                      "State: "
                      (mapcar (lambda (pair)
                                (upcase (format "%s" (car pair))))
                              bom-state-files))))
  (with-current-buffer (get-buffer-create "*bom*")
    (erase-buffer)
    (insert (bom-state-org state))
    (goto-char (point-min))
    (org-mode))
  (display-buffer "*bom*"))

;;;###autoload
(defun bom ()
  "Entrypoint - open bom landing page."
  (interactive)
  (with-current-buffer (get-buffer-create "*bom*")
    (erase-buffer)
    (insert (bom-org))
    (goto-char (point-min))
    (org-mode))
  (display-buffer "*bom*"))

(defun bom-from-path (path)
  "Translate a GET PATH to a pair of function and string args.

For example, if path is /foo/bar/baz, then we return
(foo . (\"bar\" \"baz\"))"
  (unless (string-prefix-p "/" path)
    (user-error "Invalid path: %s" path))
  (pcase-let ((`(,func-name . ,args) (cdr (split-string path "/"))))
    (unless (memq (intern func-name) '(bom bom-state))
      (user-error "Invalid path: %s" path))
    (cons (intern (format "%s-org" func-name)) args)))

(defun bom-serve (path)
  "Serve based on PATH."
  (bom-org-to-html (apply (bom-from-path path))))

;;;###autoload
(defun bom-start ()
  "Start serving weather forecasts."
  (when bom-server (bom-stop))
  (setq bom-server
        (ws-start
         (lambda (request)
           (with-slots (process headers) request
             (condition-case res
                 (bom-serve (alist-get :GET headers))
               (user-error (ws-send-404 process
                                        (format "%s" (cadr res))))
               (error (ws-send-500 process))
               (:success
                (ws-response-header
                 process 200 '("Content-type" . "text/html"))
                (process-send-string process res))
               )))
         bom-port)))

(defun bom-stop ()
  "Stop serving weather forecasts."
  (ws-stop bom-server))

(provide 'bom)
;;; bom.el ends here