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