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