]> gitweb.fperrin.net Git - atom.git/blob - atom.el
Documentation.
[atom.git] / atom.el
1 ;;; atom.el --- Create an Atom feed
2
3 ;; Copyright (C) 2011  Frédéric Perrin
4
5 ;; Author: Frédéric Perrin <frederic.perrin@resel.fr>
6 ;; Keywords: www, hypermedia, atom, rss
7
8 ;; This program is free software; you can redistribute it and/or modify
9 ;; it under the terms of the GNU General Public License as published by
10 ;; the Free Software Foundation, either version 3 of the License, or
11 ;; (at your option) any later version.
12
13 ;; This program is distributed in the hope that it will be useful,
14 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
15 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 ;; GNU General Public License for more details.
17
18 ;; You should have received a copy of the GNU General Public License
19 ;; along with this program.  If not, see <http://www.gnu.org/licenses/>.
20
21 ;;; Commentary:
22
23 ;; This is a library for creating an Atom feed from a Lisp program.
24 ;; The normal usage is to create a feed with `atom-create', giving it
25 ;; a title and a Web address. Once the feed has been created, entries
26 ;; may be added to the feed, by specifying (at the minimum) a title, a
27 ;; permanent link and the content of the entry. Text-only, HTML and
28 ;; XHTML entries are supported.
29
30 ;; It is possible to produce both Atom and RSS feeds.
31
32 ;; A typical usage would look like this:
33
34 ;; (let ((my-atom-feed (atom-create "My feed" "http://example.org")))
35 ;;   ; A simple, text-only entry
36 ;;   (atom-add-text-entry
37 ;;    my-atom-feed
38 ;;    "Hello world"
39 ;;    "http://example.org/hello"
40 ;;    "Hello the world!")
41 ;;
42 ;;   (atom-add-xhtml-entry
43 ;;    my-atom-feed
44 ;;    "An XHTML example"
45 ;;    "http://example.org/html-example"
46 ;;    "<p>One can also use <acronym>XHTML</acronym> in the entries.</p>")
47 ;;
48 ;;   (atom-print my-atom-feed)
49 ;;   ;; If you prefer RSS feeds:
50 ;;   (atom-to-rss-print my-atom-feed))
51
52 ;; Full documentation is available at <http://tar-jx.bz/code/atom.html>.
53
54 ;;; Code:
55
56 (require 'xml)
57 (require 'url-parse)
58 (require 'cl) ; for setf in url-canonalize
59
60 (defun atom-create (title link &optional subtitle self id author updated)
61   "Create a new atom structure.
62
63 TITLE is the title for the feed, a short, text-only, human
64 readable string.
65
66 LINK is the URL of a page responible for the content of this
67 feed.
68
69 SUBTITLE is a subtitle for the feed; it can be a bit longer than
70 TITLE, maybe a paragraph long.
71
72 SELF is the canonical URL to this feed.
73
74 ID is a unique identifier for this feed. If not given, it
75 defaults to SELF.
76
77 AUTHOR is the author of the feed. See `atom-massage-author' for
78 the possible ways to specify it. In particular, `nil' uses
79 `user-full-name' and `user-mail-address'.
80
81 UPDATED is the date the feed was last updated. If not given,
82 `(current-time)' is used."
83   (let ((atom-feed (list (list 'title nil title))))
84     (atom-modify-entry atom-feed 'link `(((href . ,link))))
85     (atom-modify-entry atom-feed 'author (atom-massage-author author))
86     (if subtitle (atom-modify-entry atom-feed 'subtitle subtitle))
87     (if self (atom-modify-entry atom-feed 'link
88                                 `(((href . ,self) (rel . "self")
89                                    (type . "application/atom+xml")))))
90     (atom-modify-entry atom-feed 'updated (atom-format-time updated))
91     (atom-modify-entry atom-feed 'id (or id self link))
92     atom-feed))
93
94 (defun atom-push-entry (atom entry)
95   "Add the entry ENTRY to the feed ATOM."
96   (nconc atom (list `(entry nil ,@entry))))
97
98 (defun atom-modify-entry (entry name val)
99   "Set the NAME element of ENTRY to VAL."
100   (let ((elem (if (stringp val)
101                   (list name nil val)
102                 (cons name val))))
103     (nconc entry (list elem))))
104
105 (defun atom-add-entry (atom title link content
106                             &optional updated id summary)
107   "Add an entry to the atom flux ATOM. Return the newly added
108 entry.
109
110 TITLE is a short, text-only, human readable string.
111
112 LINK is a permanent link for this entry. For a given entry, LINK
113 may change between successive generations of the atom feed.
114
115 CONTENT is the content of the entry; use `atom-add-html-entry'
116 or `atom-add-xhtml-entry' when CONTENT is not text-only.
117
118 If SUMMARY is not given, the entry will not contain any summary.
119
120 UPDATED defaults to `(current-time)' if omitted, which is
121 probably not a very good default.
122
123 ID defaults to LINK, which is not optimal; see `atom-generate-id'
124 for a way to create good identifiers. For a given entry, it must
125 not change between successive generations of the atom feed, even
126 when the content of the entry ."
127   (let ((entry (list (list 'title nil title))))
128     (atom-modify-entry entry 'link  (list (list (cons 'href link))))
129     (atom-modify-entry entry 'id (or id link))
130     (atom-modify-entry entry 'updated (atom-format-time updated))
131     (if summary (atom-modify-entry entry 'summary summary))
132     (atom-modify-entry entry 'content content)
133     (atom-push-entry atom entry)
134     entry))
135
136 (defalias 'atom-add-text-entry 'atom-add-entry
137   "Add an entry to ATOM, with a textual content. See
138 `atom-add-entry' for details.")
139
140 (defun atom-add-html-entry (atom title link content
141                                   &optional updated id summary)
142   "Add an entry to ATOM, with some HTML content. CONTENT should
143 be a string enconding a valid HTML fragment. See `atom-add-entry'
144 for additional details."
145   (atom-add-entry atom
146    title link (atom-massage-html content)
147    updated id (and summary (atom-massage-html summary))))
148
149 (defun atom-add-xhtml-entry (atom title link content
150                                   &optional updated id summary noconvert)
151   "Add an entry to ATOM, with some XHTML content. CONTENT may be
152 given either as a string, or as an XML tree, of a valid XHTML
153 fragment. See `atom-add-entry' for additional details.
154
155 If CONVERT, translate all links in CONTENT so that they are no
156 longer relative to LINK."
157   (let ((xhtml-content (atom-massage-xhtml content)))
158     (unless noconvert
159       (atom-xhtml-convert-links (cadr xhtml-content) link))
160     (atom-add-entry atom
161                     title link xhtml-content
162                     updated id (and summary (atom-massage-xhtml summary)))))
163
164 (defun atom-print (atom)
165   "Print the Atom feed ATOM in the current buffer."
166   (insert "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n")
167   (insert "<feed xmlns=\"http://www.w3.org/2005/Atom\">\n")
168   (xml-print atom)
169   (insert "\n</feed>"))
170
171 (defun atom-write-file (atom filename)
172   "Writes the feed ATOM to FILENAME."
173   (with-temp-buffer
174     (atom-print atom)
175     (write-region (point-min) (point-max) filename)))
176
177 \f
178 (defun atom-to-rss (atom)
179   "Translate an Atom feed into an RSS one, returning the translation.
180
181 Some information may be lost or approximated."
182   (let ((rss (list (assoc 'title atom))))
183     (atom-to-rss-translator atom rss '((subtitle . description)
184                                        (updated . pubDate)
185                                        (link . link)))
186     (atom-to-rss-modify-time rss)
187     (atom-to-rss-modify-link rss)
188     (dolist (entry (xml-get-children atom 'entry))
189       (push (atom-to-rss-item entry) rss))
190     (reverse rss)))
191
192 (defun atom-to-rss-item (entry)
193   "Translates an Atom entry into an RSS item."
194   (let ((item (list (assoc 'title entry))))
195     (atom-to-rss-translator
196      (xml-node-children entry) item
197      '((id . guid) (content . description) (updated . pubDate) (link . link)))
198     (atom-to-rss-modify-time item)
199     (atom-to-rss-modify-link item)
200     (let ((guid (assoc 'guid item))
201           (descr (assoc 'description item)))
202       (if guid
203           (setcar (cdr guid) (list (cons 'isPermaLink "false"))))
204       (if (and descr
205                (equal (xml-get-attribute descr 'type) "xhtml"))
206           (setcar (cddr descr) (xml-node-as-text descr))))
207     `(item nil ,@item)))
208
209 (defun atom-to-rss-translator (source target translations)
210   (dolist (translation translations)
211     (let* ((from (car translation))
212            (to (cdr translation))
213            (data (copy-tree (cdr (assoc from source)))))
214       (when data
215         (atom-modify-entry target to data)))))
216
217 (defun atom-to-rss-modify-link (entry)
218   (let* ((link (assoc 'link entry))
219          (link-addr (xml-get-attribute-or-nil link 'href)))
220     (when link
221       (setcar (cdr link) nil)
222       (setcdr (cdr link) (cons link-addr nil)))))
223
224 (defun atom-print-as-rss (atom)
225   (let ((rss (atom-to-rss atom)))
226     (insert "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n")
227     (insert "<rss version=\"2.0\">\n")
228     (insert "  <channel>\n")
229     (xml-print rss "    ")
230     (insert "\n  </channel>\n")
231     (insert "</rss>")))
232
233 (defun atom-to-rss-time (time)
234   "Translates a string from the format used by Atom into the
235 format used by RSS."
236   ;; Same remark as in `atom-format-time'
237   (let ((system-time-locale "C"))
238     (format-time-string "%a, %d %b %Y %T %z" (atom-parse-time time))))
239
240 (defun atom-to-rss-modify-time (entry)
241   "Modify ENTRY, changing the format of the `pubDate' in it."
242   (let ((pubDate (assoc 'pubDate entry)))
243     (setcar (cddr pubDate)
244             (atom-to-rss-time (car (xml-node-children pubDate))))))
245
246 (defun atom-to-rss-write-file (atom filename)
247   "Saves ATOM as a RSS feed into FILENAME."
248   (with-temp-buffer
249     (atom-print-as-rss atom)
250     (write-region nil nil filename)))
251
252 \f
253 (defvar atom-time-format-string "%Y-%m-%dT%T%z"
254   "The format for string representation of dates.")
255
256 (defun atom-format-time (&optional time)
257   "Format a time according to RFC3339."
258   ;; The time zone must be specified in numeric form, but with a colon between
259   ;; the hour and minute parts.
260   (replace-regexp-in-string
261    "\\(..\\)$" ":\\1"
262    (format-time-string atom-time-format-string time)))
263
264 (defun atom-parse-time (&optional time)
265   "Parse a time as specified in RFC3339 into Emacs's native format."
266   (date-to-time (replace-regexp-in-string ":\\(..\\)$" "\\1" time)))
267
268 (defun atom-massage-html (content)
269   "Massage CONTENT so it can be used as an HTML fragment in an
270 Atom feed. CONTENT must be a string."
271   (list '((type . "html")) content))
272
273 (defun atom-string-to-xml (string)
274   "Convert STRING into a Lisp structure as used by `xml.el'."
275   (with-temp-buffer
276     (insert "<div xmlns=\"http://www.w3.org/1999/xhtml\">")
277     (insert string)
278     (insert "</div>")
279     (xml-parse-region (point-min) (point-max))))
280
281 (defun atom-massage-xhtml (content)
282   "Massage CONTENT so it can be used as an XHTML fragment in an
283 Atom feed."
284   `(((type . "xhtml"))
285     ,@(or (and (stringp content)
286                (atom-string-to-xml content))
287           content)))
288
289 (defun atom-massage-author (author)
290   "Return an XML node representing the author. AUTHOR can be:
291 - nil, in which case `user-full-name' and `user-mail-address' are
292   used;
293 - a single string, the full name of the author; no email address
294   will be included;
295 - a list with two elements, the full name and the email address
296   of the author;
297 - something else, assumed to be a complete `atomPersonConstruct'."
298   `(nil ,@(cond
299            ((null author) `((name nil ,user-full-name)
300                             (email nil ,user-mail-address)))
301            ((stringp author) `((name nil ,author)))
302            ((= 2 (length author)) `((name nil ,(car author))
303                                     (email nil ,(cadr author))))
304            (t `(author nil ,author)))))
305
306 (defun atom-xhtml-convert-links (node base)
307   "Make all links in NODE (a fragment of an XHTML document)
308 absolute, in the context of BASE, an URL."
309   (dolist (attr-name (list 'href 'src))
310     (let ((attr (assoc attr-name (xml-node-attributes node))))
311       (when attr (setcdr attr (url-canonalize (cdr attr) base)))))
312   (dolist (child (xml-node-children node))
313     (when (listp child) (atom-xhtml-convert-links child base))))
314
315 (defun atom-generate-id (link creation-date)
316   "Generate a string suitable for use as an atom:id element. This
317 implements Mark Pilgrom's tag: URI method, using the
318 CREATION-DATE of the entry, and the domain part of LINK."
319     (format "tag:%s,%s:/%s"
320             (url-host (url-generic-parse-url link))
321             (format-time-string "%Y-%m-%d" creation-date)
322             (format-time-string "%Y%m%d%H%M%S" creation-date)))
323
324 \f
325 ;;; Functions that should probably not be there
326
327 (defun url-canonalize (address base)
328   "Make ADRESS an absolute URL, taking it in the BASE context."
329   ;; I feel such a function should exist in `url-parse'. Did I miss it?
330   (let ((url-base (url-generic-parse-url base))
331         (url-address (url-generic-parse-url address)))
332     (if (url-host url-address)
333         address
334       (setf (url-filename url-base)
335             (expand-file-name address
336                               (file-name-directory (url-filename url-base))))
337       (url-recreate-url url-base))))
338
339 (defun xml-node-as-text (node)
340   "Return a string representing NODEn, an XML structure."
341   (with-temp-buffer
342     (xml-print (xml-node-children node))
343     (buffer-string)))
344
345 (provide 'atom)
346 ;;; atom.el ends here