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