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