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