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