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