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