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