Add the LeSync gnus-sync backend.
[gnus] / lisp / gnus-sync.el
1 ;;; gnus-sync.el --- synchronization facility for Gnus
2
3 ;; Copyright (C) 2010-2011  Free Software Foundation, Inc.
4
5 ;; Author: Ted Zlatanov <tzz@lifelogs.com>
6 ;; Keywords: news synchronization nntp nnrss
7
8 ;; This file is part of GNU Emacs.
9
10 ;; GNU Emacs is free software: you can redistribute it and/or modify
11 ;; it under the terms of the GNU General Public License as published by
12 ;; the Free Software Foundation, either version 3 of the License, or
13 ;; (at your option) any later version.
14
15 ;; GNU Emacs is distributed in the hope that it will be useful,
16 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18 ;; GNU General Public License for more details.
19
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with GNU Emacs.  If not, see <http://www.gnu.org/licenses/>.
22
23 ;;; Commentary:
24
25 ;; This is the gnus-sync.el package.
26
27 ;; Put this in your startup file (~/.gnus.el for instance)
28
29 ;; possibilities for gnus-sync-backend:
30 ;; Tramp over SSH: /ssh:user@host:/path/to/filename
31 ;; ...or any other file Tramp and Emacs can handle...
32
33 ;; (setq gnus-sync-backend "/remote:/path.gpg" ; will use Tramp+EPA if loaded
34 ;;       gnus-sync-global-vars `(gnus-newsrc-last-checked-date)
35 ;;       gnus-sync-newsrc-groups `("nntp" "nnrss")
36 ;;       gnus-sync-newsrc-offsets `(2 3))
37
38 ;; against a LeSync server (beware the vampire LeSync, who knows your newsrc)
39
40 ;; (setq gnus-sync-backend '(lesync "http://lesync.info/sync.php")
41 ;;       gnus-sync-global-vars `(gnus-newsrc-last-checked-date)
42 ;;       gnus-sync-newsrc-groups `("nntp" "nnrss")
43 ;;       gnus-sync-newsrc-offsets `(2 3))
44
45 ;; What's a LeSync server?
46
47 ;; 1. install CouchDB, set up a real admin user, and create a
48 ;; database, e.g. "tzz" and save the URL,
49 ;; e.g. http://lesync.info:5984/tzz
50
51 ;; 2. run `M-: (gnus-sync-lesync-setup "http://lesync.info:5984/tzz" "tzzadmin" "mypassword" "mysalt" t t)'
52 ;;    (If you run it more than once, you have to remove the entry from
53 ;;    _users yourself.  This is intentional.)
54
55 ;; That's it, you can start using http://lesync.info:5984/tzz in your
56 ;; gnus-sync-backend as a LeSync backend.  Fan fiction about the
57 ;; vampire LeSync is welcome.
58
59 ;; You may not want to expose a CouchDB install to the Big Bad
60 ;; Internet, especially if your love of all things furry would be thus
61 ;; revealed.  Make sure it's not accessible by unauthorized users and
62 ;; guests, at least.
63
64 ;; If you want to try it out, I will create a test DB for you under
65 ;; http://lesync.info:5984/yourfavoritedbname
66
67 ;; TODO:
68
69 ;; - after gnus-sync-read, the message counts are wrong.  So it's not
70 ;;   run automatically, you have to call it with M-x gnus-sync-read
71
72 ;; - use gnus-after-set-mark-hook and gnus-before-update-mark-hook to
73 ;;   catch the mark updates
74
75 ;; - repositioning of groups within topic after a LeSync sync is a
76 ;;   weird sort of bubble sort ("buttle" sort: the old entry ends up
77 ;;   at the rear of the list); you will eventually end up with the
78 ;;   right order after calling `gnus-sync-read' a bunch of times.
79
80 ;; - installing topics and groups is inefficient and annoying, lots of
81 ;;   prompts could be avoided
82
83 ;;; Code:
84
85 (eval-when-compile (require 'cl))
86 (require 'json)
87 (require 'gnus)
88 (require 'gnus-start)
89 (require 'gnus-util)
90
91 (defgroup gnus-sync nil
92   "The Gnus synchronization facility."
93   :version "24.1"
94   :group 'gnus)
95
96 (defcustom gnus-sync-newsrc-groups `("nntp" "nnrss")
97   "List of groups to be synchronized in the gnus-newsrc-alist.
98 The group names are matched, they don't have to be fully
99 qualified.  Typically you would choose all of these.  That's the
100 default because there is no active sync backend by default, so
101 this setting is harmless until the user chooses a sync backend."
102   :group 'gnus-sync
103   :type '(repeat regexp))
104
105 (defcustom gnus-sync-global-vars nil
106   "List of global variables to be synchronized.
107 You may want to sync `gnus-newsrc-last-checked-date' but pretty
108 much any symbol is fair game.  You could additionally sync
109 `gnus-newsrc-alist', `gnus-server-alist', `gnus-topic-topology',
110 and `gnus-topic-alist'.  Also see `gnus-variable-list'."
111   :group 'gnus-sync
112   :type '(repeat (choice (variable :tag "A known variable")
113                          (symbol :tag "Any symbol"))))
114
115 (defcustom gnus-sync-backend nil
116   "The synchronization backend."
117   :group 'gnus-sync
118   :type '(radio (const :format "None" nil)
119                 (list :tag "Sync server"
120                       (const :format "LeSync Server API" lesync)
121                       (string :tag "URL of a CouchDB database for API access"))
122                 (string :tag "Sync to a file")))
123
124 (defvar gnus-sync-newsrc-loader nil
125   "Carrier for newsrc data")
126
127 (defcustom gnus-sync-lesync-name (system-name)
128   "The LeSync name for this machine."
129   :group 'gnus-sync
130   :type 'string)
131
132 (defcustom  gnus-sync-lesync-install-topics 'ask
133   "Should LeSync install the recorded topics?"
134   :group 'gnus-sync
135   :type '(choice (const :tag "Never Install" nil)
136                  (const :tag "Always Install" t)
137                  (const :tag "Ask Me Once" ask)))
138
139 (defvar gnus-sync-lesync-props-hash (make-hash-table :test 'equal)
140   "LeSync props, keyed by group name")
141
142 (defvar gnus-sync-lesync-design-prefix "/_design/lesync"
143   "The LeSync design prefix for CouchDB")
144
145 (defvar gnus-sync-lesync-security-object "/_security"
146   "The LeSync security object for CouchDB")
147
148 (defun gnus-sync-lesync-parse ()
149   "Parse the result of a LeSync request."
150   (goto-char (point-min))
151   (condition-case nil
152       (when (search-forward-regexp "^$" nil t)
153         (json-read))
154     (error
155      (gnus-message
156       1
157       "gnus-sync-lesync-parse: Could not read the LeSync response!")
158      nil)))
159
160 (defun gnus-sync-lesync-call (url method headers &optional kvdata)
161   "Make an access request to URL using KVDATA and METHOD.
162 KVDATA must be an alist."
163   ;;(debug (json-encode kvdata))
164   ;; (when (string-match-p "gmane.emacs.devel" url) (debug kvdata))
165   (flet ((json-alist-p (list) (gnus-sync-json-alist-p list))) ; temp patch
166     (let ((url-request-method method)
167           (url-request-extra-headers headers)
168           (url-request-data (if kvdata (json-encode kvdata) nil)))
169       (with-current-buffer (url-retrieve-synchronously url)
170         ;;(debug (buffer-string))
171         (let ((data (gnus-sync-lesync-parse)))
172           (gnus-message 12 "gnus-sync-lesync-call: %s URL %s sent %S got %S"
173                         method url `((headers . ,headers) (data ,kvdata)) data)
174           (kill-buffer (current-buffer))
175           data)))))
176
177 (defun gnus-sync-lesync-PUT (url headers &optional data)
178   (gnus-sync-lesync-call url "PUT" headers data))
179
180 (defun gnus-sync-lesync-POST (url headers &optional data)
181   (gnus-sync-lesync-call url "POST" headers data))
182
183 (defun gnus-sync-lesync-GET (url headers &optional data)
184   (gnus-sync-lesync-call url "GET" headers data))
185
186 (defun gnus-sync-lesync-DELETE (url headers &optional data)
187   (gnus-sync-lesync-call url "DELETE" headers data))
188
189 ;; this is not necessary with newer versions of json.el but 1.2 or older
190 ;; (which are in Emacs 24.1 and earlier) need it
191 (defun gnus-sync-json-alist-p (list)
192   "Non-null if and only if LIST is an alist."
193   (while (consp list)
194     (setq list (if (consp (car list))
195                    (cdr list)
196                  'not-alist)))
197   (null list))
198
199 ;; this is not necessary with newer versions of json.el but 1.2 or older
200 ;; (which are in Emacs 24.1 and earlier) need it
201 (defun gnus-sync-json-plist-p (list)
202   "Non-null if and only if LIST is a plist."
203   (while (consp list)
204     (setq list (if (and (keywordp (car list))
205                         (consp (cdr list)))
206                    (cddr list)
207                  'not-plist)))
208   (null list))
209
210 ; (gnus-sync-lesync-setup "http://lesync.info:5984/tzz" "tzzadmin" "mypassword" "mysalt" t t)
211
212 (defun gnus-sync-lesync-setup (url &optional user password salt reader admin)
213   (interactive "sEnter URL to set up: ")
214   "Set up the LeSync database at URL.
215 Install USER as a READER and/or an ADMIN in the security object
216 under \"_security\", and in the CouchDB \"_users\" table using
217 PASSWORD and SALT.  Only one USER is thus supported for now.
218 When SALT is nil, a random one will be generated using `random'."
219   (let* ((design-url (concat url gnus-sync-lesync-design-prefix))
220          (security-object (concat url "/_security"))
221          (user-record `((names . [,user]) (roles . [])))
222          (couch-user-name (format "org.couchdb.user:%s" user))
223          (salt (or salt (sha1 (random t))))
224          (couch-user-record `((_id . ,couch-user-name)
225                               (type . user)
226                               (name . ,(format "%s" user))
227                               (roles . [])
228                               (password_sha . ,(sha1
229                                                 (format "%s%s" password salt)))
230                               (salt . ,(format "%s" salt))))
231          (rev (progn
232                 (gnus-sync-lesync-find-prop 'rev design-url design-url)
233                 (gnus-sync-lesync-get-prop 'rev design-url)))
234          (latest-func "function(head,req)
235 {
236   var tosend = [];
237   var row;
238   var ftime = (req.query['ftime'] || 0);
239   while (row = getRow())
240   {
241     if (row.value['float-time'] > ftime)
242     {
243       var s = row.value['_id'];
244       if (s) tosend.push('\"'+s.replace('\"', '\\\"')+'\"');
245     }
246   }
247   send('['+tosend.join(',') + ']');
248 }")
249          (subs-func "function(doc){emit([doc._id, doc.source], doc._rev);}")
250          (revs-func "function(doc){emit(doc._id, doc._rev);}")
251          (bytimesubs-func "function(doc)
252 {emit([(doc['float-time']||0), doc._id], doc._rev);}")
253          (bytime-func "function(doc)
254 {emit([(doc['float-time']||0), doc._id], doc);}")
255          (groups-func "function(doc){emit(doc._id, doc);}"))
256     (and (if user
257              (and (assq 'ok (gnus-sync-lesync-PUT
258                              security-object
259                              nil
260                              (append (and reader
261                                           (list `(readers . ,user-record)))
262                                      (and admin
263                                           (list `(admins . ,user-record))))))
264                   (assq 'ok (gnus-sync-lesync-PUT
265                              (concat (file-name-directory url)
266                                      "_users/"
267                                      couch-user-name)
268                              nil
269                              couch-user-record)))
270            t)
271          (assq 'ok (gnus-sync-lesync-PUT
272                     design-url
273                     nil
274                     `(,@(when rev (list (cons '_rev rev)))
275                       (lists . ((latest . ,latest-func)))
276                       (views . ((subs . ((map . ,subs-func)))
277                                 (revs . ((map . ,revs-func)))
278                                 (bytimesubs . ((map . ,bytimesubs-func)))
279                                 (bytime . ((map . ,bytime-func)))
280                                 (groups . ((map . ,groups-func)))))))))))
281
282 (defun gnus-sync-lesync-find-prop (prop url key)
283   "Retrieve a PROPerty of a document KEY at URL.
284 Calls `gnus-sync-lesync-set-prop'.
285 For the 'rev PROP, uses '_rev against the document."
286   (gnus-sync-lesync-set-prop
287    prop key (cdr (assq (if (eq prop 'rev) '_rev prop)
288                        (gnus-sync-lesync-GET url nil)))))
289
290 (defun gnus-sync-lesync-set-prop (prop key val)
291   "Update the PROPerty of document KEY at URL to VAL.
292 Updates `gnus-sync-lesync-props-hash'."
293     (puthash (format "%s.%s" key prop) val gnus-sync-lesync-props-hash))
294
295 (defun gnus-sync-lesync-get-prop (prop key)
296   "Get the PROPerty of KEY from `gnus-sync-lesync-props-hash'."
297     (gethash (format "%s.%s" key prop) gnus-sync-lesync-props-hash))
298
299 (defun gnus-sync-deep-print (data)
300   (let* ((print-quoted t)
301          (print-readably t)
302          (print-escape-multibyte nil)
303          (print-escape-nonascii t)
304          (print-length nil)
305          (print-level nil)
306          (print-circle nil)
307          (print-escape-newlines t))
308     (format "%S" data)))
309
310 (defun gnus-sync-newsrc-loader-builder (&optional only-modified)
311   (let* ((entries (cdr gnus-newsrc-alist))
312          entry name ret)
313     (while entries
314       (setq entry (pop entries)
315             name (car entry))
316       (when (gnus-grep-in-list name gnus-sync-newsrc-groups)
317         (if only-modified
318             (when (not (equal (gnus-sync-deep-print entry)
319                               (gnus-sync-lesync-get-prop 'checksum name)))
320               (gnus-message 9 "%s: add %s, it's modified"
321                             "gnus-sync-newsrc-loader-builder" name)
322               (push entry ret))
323           (push entry ret))))
324     ret))
325
326 ; (json-encode (gnus-sync-range2invlist '((1 . 47137) (47139 . 47714) 48129 48211 49231 49281 49342 49473 49475 49502)))
327 (defun gnus-sync-range2invlist (ranges)
328   (append '(invlist)
329           (let ((ranges (delq nil ranges))
330                 ret range from to)
331             (while ranges
332               (setq range (pop ranges))
333               (if (atom range)
334                   (setq from range
335                         to range)
336                 (setq from (car range)
337                       to (cdr range)))
338               (push from ret)
339               (push (1+ to) ret))
340             (reverse ret))))
341
342 ; (let* ((d '((1 . 47137) (47139 . 47714) 48129 48211 49231 49281 49342 49473 49475 49502)) (j (format "%S" (gnus-sync-invlist2range (gnus-sync-range2invlist d))))) (or (equal (format "%S" d) j) j))
343 (defun gnus-sync-invlist2range (inv)
344   (setq inv (append inv nil))
345   (if (equal (format "%s" (car inv)) "invlist")
346       (let ((i (cdr inv))
347             (start 0)
348             ret cur top flip)
349         (while i
350           (setq cur (pop i))
351           (when flip
352             (setq top (1- cur))
353             (if (= start top)
354                 (push start ret)
355               (push (cons start top) ret)))
356           (setq flip (not flip))
357           (setq start cur))
358         (reverse ret))
359     inv))
360
361 (defun gnus-sync-position (search list &optional test)
362   "Find the position of SEARCH in LIST using TEST, defaulting to `eq'."
363   (let ((pos 0)
364         (test (or test 'eq)))
365     (while (and list (not (funcall test (car list) search)))
366       (pop list)
367       (incf pos))
368     (if (funcall test (car list) search) pos nil)))
369
370 (defun gnus-sync-topic-group-position (group topic-name)
371   (gnus-sync-position
372    group (cdr (assoc topic-name gnus-topic-alist)) 'equal))
373
374 (defun gnus-sync-fix-topic-group-position (group topic-name position)
375   (unless (equal position (gnus-sync-topic-group-position group topic-name))
376     (let* ((loc "gnus-sync-fix-topic-group-position")
377            (groups (delete group (cdr (assoc topic-name gnus-topic-alist))))
378            (position (min position (1- (length groups))))
379            (old (nth position groups)))
380       (when (and old (not (equal old group)))
381         (setf (nth position groups) group)
382         (setcdr (assoc topic-name gnus-topic-alist)
383                 (append groups (list old)))
384         (gnus-message 9 "%s: %s moved to %d, swap with %s"
385                       loc group position old)))))
386
387 (defun gnus-sync-lesync-pre-save-group-entry (url nentry &rest passed-props)
388   (let* ((loc "gnus-sync-lesync-save-group-entry")
389          (k (car nentry))
390          (revision (gnus-sync-lesync-get-prop 'rev k))
391          (sname gnus-sync-lesync-name)
392          (topic (gnus-group-topic k))
393          (topic-offset (gnus-sync-topic-group-position k topic))
394          (sources (gnus-sync-lesync-get-prop 'source k)))
395     ;; set the revision so we don't have a conflict
396     `(,@(when revision
397           (list (cons '_rev revision)))
398       (_id . ,k)
399       ;; the time we saved
400       ,@passed-props
401       ;; add our name to the sources list for this key
402       (source ,@(if (member gnus-sync-lesync-name sources)
403                     sources
404                   (cons gnus-sync-lesync-name sources)))
405       ,(cons 'level (nth 1 nentry))
406       ,@(if topic (list (cons 'topic topic)) nil)
407       ,@(if topic-offset (list (cons 'topic-offset topic-offset)) nil)
408       ;; the read marks
409       ,(cons 'read (gnus-sync-range2invlist (nth 2 nentry)))
410       ;; the other marks
411       ,@(mapcar (lambda (mark-entry)
412                   (cons (car mark-entry)
413                         (gnus-sync-range2invlist (cdr mark-entry))))
414                 (nth 3 nentry)))))
415
416 (defun gnus-sync-lesync-post-save-group-entry (url entry)
417   (let* ((loc "gnus-sync-lesync-post-save-group-entry")
418          (k (cdr (assq 'id entry))))
419     (cond
420      ;; success!
421      ((and (assq 'rev entry) (assq 'id entry))
422       (progn
423         (gnus-sync-lesync-set-prop 'rev k (cdr (assq 'rev entry)))
424         (gnus-sync-lesync-set-prop 'checksum
425                                    k
426                                    (gnus-sync-deep-print
427                                     (assoc k gnus-newsrc-alist)))
428         (gnus-message 9 "%s: successfully synced %s to %s"
429                       loc k url)))
430      ;; specifically check for document conflicts
431      ((equal "conflict" (format "%s" (cdr-safe (assq 'error entry))))
432       (gnus-error
433        1
434        "%s: use `%s' to resolve the conflict synchronizing %s to %s: %s"
435        loc "gnus-sync-read" k url (cdr (assq 'reason entry))))
436      ;; generic errors
437      ((assq 'error entry)
438       (gnus-error 1 "%s: got error while synchronizing %s to %s: %s"
439                   loc k url (cdr (assq 'reason entry))))
440
441      (t
442       (gnus-message 2 "%s: unknown sync status after %s to %s: %S"
443                     loc k url entry)))
444     (assoc 'error entry)))
445
446 (defun gnus-sync-lesync-groups-builder (url)
447   (let ((u (concat url gnus-sync-lesync-design-prefix "/_view/groups")))
448     (cdr (assq 'rows (gnus-sync-lesync-GET u nil)))))
449
450 (defun gnus-sync-subscribe-group (name)
451   "Subscribe to group NAME.  Returns NAME on success, nil otherwise."
452   (gnus-subscribe-newsgroup name))
453
454 (defun gnus-sync-lesync-read-group-entry (url name entry &rest passed-props)
455   "Read ENTRY information for NAME.  Returns NAME if successful.
456 Skips entries whose sources don't contain
457 `gnus-sync-lesync-name'.  When the alist PASSED-PROPS has a
458 `subscribe-all' element that evaluates to true, we attempt to
459 subscribe to unknown groups.  The user is also allowed to delete
460 unwanted groups via the LeSync URL."
461   (let* ((loc "gnus-sync-lesync-read-group-entry")
462          (entry (gnus-sync-lesync-normalize-group-entry entry passed-props))
463          (subscribe-all (cdr (assq 'subscribe-all passed-props)))
464          (sources (cdr (assq 'source entry)))
465          (rev (cdr (assq 'rev entry)))
466          (in-sources (member gnus-sync-lesync-name sources))
467          (known (assoc name gnus-newsrc-alist))
468          cell)
469     (unless known
470       (if (and subscribe-all
471                (y-or-n-p (format "Subscribe to group %s?" name)))
472           (setq known (gnus-sync-subscribe-group name)
473                 in-sources t)
474         ;; else...
475         (when (y-or-n-p (format "Delete group %s from server?" name))
476           (if (equal name (gnus-sync-lesync-delete-group url name))
477               (gnus-message 1 "%s: removed group %s from server %s"
478                             loc name url)
479             (gnus-error 1 "%s: could not remove group %s from server %s"
480                         loc name url)))))
481     (when known
482       (unless in-sources
483         (setq in-sources
484               (y-or-n-p
485                (format "Read group %s even though %s is not in sources %S?"
486                        name gnus-sync-lesync-name (or sources ""))))))
487     (when rev
488       (gnus-sync-lesync-set-prop 'rev name rev))
489
490     ;; if the source matches AND we have this group
491     (if (and known in-sources)
492         (progn
493           (gnus-message 10 "%s: reading LeSync entry %s, sources %S"
494                         loc name sources)
495           (while entry
496             (setq cell (pop entry))
497             (let ((k (car cell))
498                   (val (cdr cell)))
499               (gnus-sync-lesync-set-prop k name val)))
500           name)
501       ;; else...
502       (unless known
503         (gnus-message 5 "%s: ignoring entry %s, it wasn't subscribed.  %s"
504                         loc name "Call `gnus-sync-read' with C-u to force it."))
505       (unless in-sources
506         (gnus-message 5 "%s: ignoring entry %s, %s not in sources %S"
507                       loc name gnus-sync-lesync-name (or sources "")))
508       nil)))
509
510 (defun gnus-sync-lesync-install-group-entry (name)
511   (let* ((master (assoc name gnus-newsrc-alist))
512          (old-topic-name (gnus-group-topic name))
513          (old-topic (assoc old-topic-name gnus-topic-alist))
514          (target-topic-name (gnus-sync-lesync-get-prop 'topic name))
515          (target-topic-offset (gnus-sync-lesync-get-prop 'topic-offset name))
516          (target-topic (assoc target-topic-name gnus-topic-alist))
517          (loc "gnus-sync-lesync-install-group-entry"))
518     (if master
519         (progn
520           (when (eq 'ask gnus-sync-lesync-install-topics)
521             (setq gnus-sync-lesync-install-topics
522                   (y-or-n-p "Install topics from LeSync?")))
523           (when (and (eq t gnus-sync-lesync-install-topics)
524                      target-topic-name)
525             (if (equal old-topic-name target-topic-name)
526                 (gnus-message 12 "%s: %s is already in topic %s"
527                               loc name target-topic-name)
528               ;; see `gnus-topic-move-group'
529               (when (and old-topic target-topic)
530                 (setcdr old-topic (gnus-delete-first name (cdr old-topic)))
531                 (gnus-message 5 "%s: removing %s from topic %s"
532                               loc name old-topic-name))
533               (unless target-topic
534                 (when (y-or-n-p (format "Create missing topic %s?"
535                                         target-topic-name))
536                   (gnus-topic-create-topic target-topic-name nil)
537                   (setq target-topic (assoc target-topic-name
538                                             gnus-topic-alist))))
539               (if target-topic
540                   (prog1
541                       (nconc target-topic (list name))
542                     (gnus-message 5 "%s: adding %s to topic %s"
543                                   loc name (car target-topic))
544                     (gnus-topic-enter-dribble))
545                 (gnus-error 2 "%s: LeSync group %s can't go in missing topic %s"
546                             loc name target-topic-name)))
547             (when (and target-topic-offset target-topic)
548               (gnus-sync-fix-topic-group-position
549                name target-topic-name target-topic-offset)))
550           ;; install the subscription level
551           (when (gnus-sync-lesync-get-prop 'level name)
552             (setf (nth 1 master) (gnus-sync-lesync-get-prop 'level name)))
553           ;; install the read and other marks
554           (setf (nth 2 master) (gnus-sync-lesync-get-prop 'read name))
555           (setf (nth 3 master) (gnus-sync-lesync-get-prop 'marks name))
556           (gnus-sync-lesync-set-prop 'checksum
557                                      name
558                                      (gnus-sync-deep-print master))
559           nil)
560       (gnus-error 1 "%s: invalid LeSync group %s" loc name)
561       'invalid-name)))
562
563 ; (gnus-sync-lesync-delete-group (cdr gnus-sync-backend) "nntp+Gmane:gwene.org.slashdot")
564
565 (defun gnus-sync-lesync-delete-group (url name)
566   "Returns NAME if successful deleting it from URL, an error otherwise."
567   (interactive "sEnter URL to set up: \rsEnter group name: ")
568   (let* ((u (concat (cadr gnus-sync-backend) "/" (url-hexify-string name)))
569          (del (gnus-sync-lesync-DELETE
570                u
571                `(,@(when (gnus-sync-lesync-get-prop 'rev name)
572                      (list (cons "If-Match"
573                                  (gnus-sync-lesync-get-prop 'rev name))))))))
574     (or (cdr (assq 'id del)) del)))
575
576 ;;; (gnus-sync-lesync-normalize-group-entry '((subscribe . ["invlist"]) (read . ["invlist"]) (topic-offset . 20) (topic . "news") (level . 6) (source . ["a" "b"]) (float-time . 1319671237.099285) (_rev . "10-edf5107f41e5e6f7f6629d1c0ee172f7") (_id . "nntp+news.net:alt.movies")) '((read-time 1319672156.486414) (subscribe-all nil)))
577
578 (defun gnus-sync-lesync-normalize-group-entry (entry &optional passed-props)
579   (let (ret
580         marks
581         cell)
582     (setq entry (append passed-props entry))
583     (while (setq cell (pop entry))
584       (let ((k (car cell))
585             (val (cdr cell)))
586         (cond
587          ((eq k 'read)
588           (push (cons k (gnus-sync-invlist2range val)) ret))
589          ;; we already know the name
590          ((eq k '_id)
591           nil)
592          ((eq k '_rev)
593           (push (cons 'rev val) ret))
594          ((eq k 'source)
595           (push (cons 'source (append val nil)) ret))
596          ((or (eq k 'float-time)
597               (eq k 'level)
598               (eq k 'topic)
599               (eq k 'topic-offset)
600               (eq k 'read-time))
601           (push (cons k val) ret))
602 ;;; "How often have I said to you that when you have eliminated the
603 ;;; impossible, whatever remains, however improbable, must be the
604 ;;; truth?" --Sherlock Holmes
605           ;; everything remaining must be a mark
606           (t (push (cons k (gnus-sync-invlist2range val)) marks)))))
607     (cons (cons 'marks marks) ret)))
608
609 (defun gnus-sync-save (&optional force)
610 "Save the Gnus sync data to the backend.
611 With a prefix, FORCE is set and all groups will be saved."
612   (interactive "P")
613   (cond
614    ((and (listp gnus-sync-backend)
615          (eq (nth 0 gnus-sync-backend) 'lesync)
616          (stringp (nth 1 gnus-sync-backend)))
617
618     ;; refresh the revisions if we're forcing the save
619     (when force
620       (mapc (lambda (entry)
621               (when (and (assq 'key entry)
622                          (assq 'value entry))
623                 (gnus-sync-lesync-set-prop
624                  'rev
625                  (cdr (assq 'key entry))
626                  (cdr (assq 'value entry)))))
627             ;; the revs view is key = name, value = rev
628             (cdr (assq 'rows (gnus-sync-lesync-GET
629                               (concat (nth 1 gnus-sync-backend)
630                                       gnus-sync-lesync-design-prefix
631                                       "/_view/revs")
632                               nil)))))
633
634     (let* ((ftime (float-time))
635            (url (nth 1 gnus-sync-backend))
636            (entries
637             (mapcar (lambda (entry)
638                       (gnus-sync-lesync-pre-save-group-entry
639                        (cadr gnus-sync-backend)
640                        entry
641                        (cons 'float-time ftime)))
642                     (gnus-sync-newsrc-loader-builder (not force))))
643            ;; when there are no entries, there's nothing to save
644            (sync (if entries
645                      (gnus-sync-lesync-POST
646                       (concat url "/_bulk_docs")
647                       '(("Content-Type" . "application/json"))
648                       `((docs . ,(vconcat entries nil))))
649                    (gnus-message
650                     2 "gnus-sync-save: nothing to save to the LeSync backend")
651                    nil)))
652       (mapcar (apply-partially 'gnus-sync-lesync-post-save-group-entry url)
653               sync)))
654    ((stringp gnus-sync-backend)
655     (gnus-message 7 "gnus-sync-save: saving to backend %s" gnus-sync-backend)
656     ;; populate gnus-sync-newsrc-loader from all but the first dummy
657     ;; entry in gnus-newsrc-alist whose group matches any of the
658     ;; gnus-sync-newsrc-groups
659     ;; TODO: keep the old contents for groups we don't have!
660     (let ((gnus-sync-newsrc-loader (gnus-sync-newsrc-loader-builder)))
661       (with-temp-file gnus-sync-backend
662         (progn
663           (let ((coding-system-for-write gnus-ding-file-coding-system)
664                 (standard-output (current-buffer)))
665             (princ (format ";; -*- mode:emacs-lisp; coding: %s; -*-\n"
666                            gnus-ding-file-coding-system))
667             (princ ";; Gnus sync data v. 0.0.1\n")
668             ;; TODO: replace with `gnus-sync-deep-print'
669             (let* ((print-quoted t)
670                    (print-readably t)
671                    (print-escape-multibyte nil)
672                    (print-escape-nonascii t)
673                    (print-length nil)
674                    (print-level nil)
675                    (print-circle nil)
676                    (print-escape-newlines t)
677                    (variables (cons 'gnus-sync-newsrc-loader
678                                     gnus-sync-global-vars))
679                    variable)
680               (while variables
681                 (if (and (boundp (setq variable (pop variables)))
682                            (symbol-value variable))
683                     (progn
684                       (princ "\n(setq ")
685                       (princ (symbol-name variable))
686                       (princ " '")
687                       (prin1 (symbol-value variable))
688                       (princ ")\n"))
689                   (princ "\n;;; skipping empty variable ")
690                   (princ (symbol-name variable)))))
691             (gnus-message
692              7
693              "gnus-sync-save: stored variables %s and %d groups in %s"
694              gnus-sync-global-vars
695              (length gnus-sync-newsrc-loader)
696              gnus-sync-backend)
697
698             ;; Idea from Dan Christensen <jdc@chow.mat.jhu.edu>
699             ;; Save the .eld file with extra line breaks.
700             (gnus-message 8 "gnus-sync-save: adding whitespace to %s"
701                           gnus-sync-backend)
702             (save-excursion
703               (goto-char (point-min))
704               (while (re-search-forward "^(\\|(\\\"" nil t)
705                 (replace-match "\n\\&" t))
706               (goto-char (point-min))
707               (while (re-search-forward " $" nil t)
708                 (replace-match "" t t))))))))
709     ;; the pass-through case: gnus-sync-backend is not a known choice
710     (nil)))
711
712 (defun gnus-sync-read (&optional subscribe-all)
713   "Load the Gnus sync data from the backend.
714 With a prefix, SUBSCRIBE-ALL is set and unknown groups will be subscribed."
715   (interactive "P")
716   (when gnus-sync-backend
717     (gnus-message 7 "gnus-sync-read: loading from backend %s" gnus-sync-backend)
718     (cond
719      ((and (listp gnus-sync-backend)
720            (eq (nth 0 gnus-sync-backend) 'lesync)
721            (stringp (nth 1 gnus-sync-backend)))
722       (let ((errored nil)
723             name ftime)
724         (mapcar (lambda (entry)
725                   (setq name (cdr (assq 'id entry)))
726                   ;; set ftime the FIRST time through this loop, that
727                   ;; way it reflects the time we FINISHED reading
728                   (unless ftime (setq ftime (float-time)))
729
730                   (unless errored
731                     (setq errored
732                           (when (equal name
733                                        (gnus-sync-lesync-read-group-entry
734                                         (nth 1 gnus-sync-backend)
735                                         name
736                                         (cdr (assq 'value entry))
737                                         `(read-time ,ftime)
738                                         `(subscribe-all ,subscribe-all)))
739                             (gnus-sync-lesync-install-group-entry
740                              (cdr (assq 'id entry)))))))
741                 (gnus-sync-lesync-groups-builder (nth 1 gnus-sync-backend)))))
742
743      ((stringp gnus-sync-backend)
744       ;; read data here...
745       (if (or debug-on-error debug-on-quit)
746           (load gnus-sync-backend nil t)
747         (condition-case var
748             (load gnus-sync-backend nil t)
749           (error
750            (error "Error in %s: %s" gnus-sync-backend (cadr var)))))
751       (let ((valid-count 0)
752             invalid-groups)
753         (dolist (node gnus-sync-newsrc-loader)
754           (if (gnus-gethash (car node) gnus-newsrc-hashtb)
755               (progn
756                 (incf valid-count)
757                 (loop for store in (cdr node)
758                       do (setf (nth (car store)
759                                     (assoc (car node) gnus-newsrc-alist))
760                                (cdr store))))
761             (push (car node) invalid-groups)))
762         (gnus-message
763          7
764          "gnus-sync-read: loaded %d groups (out of %d) from %s"
765          valid-count (length gnus-sync-newsrc-loader)
766          gnus-sync-backend)
767         (when invalid-groups
768           (gnus-message
769            7
770            "gnus-sync-read: skipped %d groups (out of %d) from %s"
771            (length invalid-groups)
772            (length gnus-sync-newsrc-loader)
773            gnus-sync-backend)
774           (gnus-message 9 "gnus-sync-read: skipped groups: %s"
775                         (mapconcat 'identity invalid-groups ", ")))))
776      (nil))
777
778     (gnus-message 9 "gnus-sync-read: remaking the newsrc hashtable")
779     (gnus-make-hashtable-from-newsrc-alist)))
780
781 ;;;###autoload
782 (defun gnus-sync-initialize ()
783 "Initialize the Gnus sync facility."
784   (interactive)
785   (gnus-message 5 "Initializing the sync facility")
786   (gnus-sync-install-hooks))
787
788 ;;;###autoload
789 (defun gnus-sync-install-hooks ()
790   "Install the sync hooks."
791   (interactive)
792   ;; (add-hook 'gnus-get-new-news-hook 'gnus-sync-read)
793   ;; (add-hook 'gnus-read-newsrc-el-hook 'gnus-sync-read)
794   (add-hook 'gnus-save-newsrc-hook 'gnus-sync-save))
795
796 (defun gnus-sync-unload-hook ()
797   "Uninstall the sync hooks."
798   (interactive)
799   (remove-hook 'gnus-save-newsrc-hook 'gnus-sync-save))
800
801 (add-hook 'gnus-sync-unload-hook 'gnus-sync-unload-hook)
802
803 (when gnus-sync-backend (gnus-sync-initialize))
804
805 (provide 'gnus-sync)
806
807 ;;; gnus-sync.el ends here