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