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