1 ;;; gnus-sync.el --- synchronization facility for Gnus
3 ;; Copyright (C) 2010-2011 Free Software Foundation, Inc.
5 ;; Author: Ted Zlatanov <tzz@lifelogs.com>
6 ;; Keywords: news synchronization nntp nnrss
8 ;; This file is part of GNU Emacs.
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.
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.
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/>.
25 ;; This is the gnus-sync.el package.
27 ;; Put this in your startup file (~/.gnus.el for instance)
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...
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))
38 ;; against a LeSync server (beware the vampire LeSync, who knows your newsrc)
40 ;; (setq gnus-sync-backend '(lesync "http://lesync.info/sync.php")
41 ;; gnus-sync-global-vars `(gnus-newsrc-last-checked-date)
42 ;; gnus-sync-newsrc-groups `("nntp" "nnrss")
43 ;; gnus-sync-newsrc-offsets `(2 3))
45 ;; What's a LeSync server?
47 ;; 1. install CouchDB, set up a real admin user, and create a
48 ;; database, e.g. "tzz" and save the URL,
49 ;; e.g. http://lesync.info:5984/tzz
51 ;; 2. run `M-: (gnus-sync-lesync-setup "http://lesync.info:5984/tzz" "tzzadmin" "mypassword" "mysalt" t t)'
52 ;; (If you run it more than once, you have to remove the entry from
53 ;; _users yourself. This is intentional.)
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.
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
64 ;; If you want to try it out, I will create a test DB for you under
65 ;; http://lesync.info:5984/yourfavoritedbname
69 ;; - after gnus-sync-read, the message counts are wrong. So it's not
70 ;; run automatically, you have to call it with M-x gnus-sync-read
72 ;; - use gnus-after-set-mark-hook and gnus-before-update-mark-hook to
73 ;; catch the mark updates
75 ;; - repositioning of groups within topic after a LeSync sync is a
76 ;; weird sort of bubble sort ("buttle" sort: the old entry ends up
77 ;; at the rear of the list); you will eventually end up with the
78 ;; right order after calling `gnus-sync-read' a bunch of times.
80 ;; - installing topics and groups is inefficient and annoying, lots of
81 ;; prompts could be avoided
85 (eval-when-compile (require 'cl))
87 (or (ignore-errors (progn
89 ;; gnus-fallback-lib/ from gnus/lisp/gnus-fallback-lib
91 (let ((load-path (cons (expand-file-name
93 (file-name-directory (locate-library "gnus")))
97 "json not found in `load-path' or gnus-fallback-lib/ directory.")))
102 (defgroup gnus-sync nil
103 "The Gnus synchronization facility."
107 (defcustom gnus-sync-newsrc-groups `("nntp" "nnrss")
108 "List of groups to be synchronized in the gnus-newsrc-alist.
109 The group names are matched, they don't have to be fully
110 qualified. Typically you would choose all of these. That's the
111 default because there is no active sync backend by default, so
112 this setting is harmless until the user chooses a sync backend."
114 :type '(repeat regexp))
116 (defcustom gnus-sync-global-vars nil
117 "List of global variables to be synchronized.
118 You may want to sync `gnus-newsrc-last-checked-date' but pretty
119 much any symbol is fair game. You could additionally sync
120 `gnus-newsrc-alist', `gnus-server-alist', `gnus-topic-topology',
121 and `gnus-topic-alist'. Also see `gnus-variable-list'."
123 :type '(repeat (choice (variable :tag "A known variable")
124 (symbol :tag "Any symbol"))))
126 (defcustom gnus-sync-backend nil
127 "The synchronization backend."
129 :type '(radio (const :format "None" nil)
130 (list :tag "Sync server"
131 (const :format "LeSync Server API" lesync)
132 (string :tag "URL of a CouchDB database for API access"))
133 (string :tag "Sync to a file")))
135 (defvar gnus-sync-newsrc-loader nil
136 "Carrier for newsrc data")
138 (defcustom gnus-sync-lesync-name (system-name)
139 "The LeSync name for this machine."
143 (defcustom gnus-sync-lesync-install-topics 'ask
144 "Should LeSync install the recorded topics?"
146 :type '(choice (const :tag "Never Install" nil)
147 (const :tag "Always Install" t)
148 (const :tag "Ask Me Once" ask)))
150 (defvar gnus-sync-lesync-props-hash (make-hash-table :test 'equal)
151 "LeSync props, keyed by group name")
153 (defvar gnus-sync-lesync-design-prefix "/_design/lesync"
154 "The LeSync design prefix for CouchDB")
156 (defvar gnus-sync-lesync-security-object "/_security"
157 "The LeSync security object for CouchDB")
159 (defun gnus-sync-lesync-parse ()
160 "Parse the result of a LeSync request."
161 (goto-char (point-min))
163 (when (search-forward-regexp "^$" nil t)
168 "gnus-sync-lesync-parse: Could not read the LeSync response!")
171 (defun gnus-sync-lesync-call (url method headers &optional kvdata)
172 "Make an access request to URL using KVDATA and METHOD.
173 KVDATA must be an alist."
174 ;;(debug (json-encode kvdata))
175 ;; (when (string-match-p "gmane.emacs.devel" url) (debug kvdata))
176 (flet ((json-alist-p (list) (gnus-sync-json-alist-p list))) ; temp patch
177 (let ((url-request-method method)
178 (url-request-extra-headers headers)
179 (url-request-data (if kvdata (json-encode kvdata) nil)))
180 (with-current-buffer (url-retrieve-synchronously url)
181 ;;(debug (buffer-string))
182 (let ((data (gnus-sync-lesync-parse)))
183 (gnus-message 12 "gnus-sync-lesync-call: %s URL %s sent %S got %S"
184 method url `((headers . ,headers) (data ,kvdata)) data)
185 (kill-buffer (current-buffer))
188 (defun gnus-sync-lesync-PUT (url headers &optional data)
189 (gnus-sync-lesync-call url "PUT" headers data))
191 (defun gnus-sync-lesync-POST (url headers &optional data)
192 (gnus-sync-lesync-call url "POST" headers data))
194 (defun gnus-sync-lesync-GET (url headers &optional data)
195 (gnus-sync-lesync-call url "GET" headers data))
197 (defun gnus-sync-lesync-DELETE (url headers &optional data)
198 (gnus-sync-lesync-call url "DELETE" headers data))
200 ;; this is not necessary with newer versions of json.el but 1.2 or older
201 ;; (which are in Emacs 24.1 and earlier) need it
202 (defun gnus-sync-json-alist-p (list)
203 "Non-null if and only if LIST is an alist."
205 (setq list (if (consp (car list))
210 ;; this is not necessary with newer versions of json.el but 1.2 or older
211 ;; (which are in Emacs 24.1 and earlier) need it
212 (defun gnus-sync-json-plist-p (list)
213 "Non-null if and only if LIST is a plist."
215 (setq list (if (and (keywordp (car list))
221 ; (gnus-sync-lesync-setup "http://lesync.info:5984/tzz" "tzzadmin" "mypassword" "mysalt" t t)
223 (defun gnus-sync-lesync-setup (url &optional user password salt reader admin)
224 (interactive "sEnter URL to set up: ")
225 "Set up the LeSync database at URL.
226 Install USER as a READER and/or an ADMIN in the security object
227 under \"_security\", and in the CouchDB \"_users\" table using
228 PASSWORD and SALT. Only one USER is thus supported for now.
229 When SALT is nil, a random one will be generated using `random'."
230 (let* ((design-url (concat url gnus-sync-lesync-design-prefix))
231 (security-object (concat url "/_security"))
232 (user-record `((names . [,user]) (roles . [])))
233 (couch-user-name (format "org.couchdb.user:%s" user))
234 (salt (or salt (sha1 (random t))))
235 (couch-user-record `((_id . ,couch-user-name)
237 (name . ,(format "%s" user))
239 (password_sha . ,(sha1
240 (format "%s%s" password salt)))
241 (salt . ,(format "%s" salt))))
243 (gnus-sync-lesync-find-prop 'rev design-url design-url)
244 (gnus-sync-lesync-get-prop 'rev design-url)))
245 (latest-func "function(head,req)
249 var ftime = (req.query['ftime'] || 0);
250 while (row = getRow())
252 if (row.value['float-time'] > ftime)
254 var s = row.value['_id'];
255 if (s) tosend.push('\"'+s.replace('\"', '\\\"')+'\"');
258 send('['+tosend.join(',') + ']');
260 (subs-func "function(doc){emit([doc._id, doc.source], doc._rev);}")
261 (revs-func "function(doc){emit(doc._id, doc._rev);}")
262 (bytimesubs-func "function(doc)
263 {emit([(doc['float-time']||0), doc._id], doc._rev);}")
264 (bytime-func "function(doc)
265 {emit([(doc['float-time']||0), doc._id], doc);}")
266 (groups-func "function(doc){emit(doc._id, doc);}"))
268 (and (assq 'ok (gnus-sync-lesync-PUT
272 (list `(readers . ,user-record)))
274 (list `(admins . ,user-record))))))
275 (assq 'ok (gnus-sync-lesync-PUT
276 (concat (file-name-directory url)
282 (assq 'ok (gnus-sync-lesync-PUT
285 `(,@(when rev (list (cons '_rev rev)))
286 (lists . ((latest . ,latest-func)))
287 (views . ((subs . ((map . ,subs-func)))
288 (revs . ((map . ,revs-func)))
289 (bytimesubs . ((map . ,bytimesubs-func)))
290 (bytime . ((map . ,bytime-func)))
291 (groups . ((map . ,groups-func)))))))))))
293 (defun gnus-sync-lesync-find-prop (prop url key)
294 "Retrieve a PROPerty of a document KEY at URL.
295 Calls `gnus-sync-lesync-set-prop'.
296 For the 'rev PROP, uses '_rev against the document."
297 (gnus-sync-lesync-set-prop
298 prop key (cdr (assq (if (eq prop 'rev) '_rev prop)
299 (gnus-sync-lesync-GET url nil)))))
301 (defun gnus-sync-lesync-set-prop (prop key val)
302 "Update the PROPerty of document KEY at URL to VAL.
303 Updates `gnus-sync-lesync-props-hash'."
304 (puthash (format "%s.%s" key prop) val gnus-sync-lesync-props-hash))
306 (defun gnus-sync-lesync-get-prop (prop key)
307 "Get the PROPerty of KEY from `gnus-sync-lesync-props-hash'."
308 (gethash (format "%s.%s" key prop) gnus-sync-lesync-props-hash))
310 (defun gnus-sync-deep-print (data)
311 (let* ((print-quoted t)
313 (print-escape-multibyte nil)
314 (print-escape-nonascii t)
318 (print-escape-newlines t))
321 (defun gnus-sync-newsrc-loader-builder (&optional only-modified)
322 (let* ((entries (cdr gnus-newsrc-alist))
325 (setq entry (pop entries)
327 (when (gnus-grep-in-list name gnus-sync-newsrc-groups)
329 (when (not (equal (gnus-sync-deep-print entry)
330 (gnus-sync-lesync-get-prop 'checksum name)))
331 (gnus-message 9 "%s: add %s, it's modified"
332 "gnus-sync-newsrc-loader-builder" name)
337 ; (json-encode (gnus-sync-range2invlist '((1 . 47137) (47139 . 47714) 48129 48211 49231 49281 49342 49473 49475 49502)))
338 (defun gnus-sync-range2invlist (ranges)
340 (let ((ranges (delq nil ranges))
343 (setq range (pop ranges))
347 (setq from (car range)
353 ; (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))
354 (defun gnus-sync-invlist2range (inv)
355 (setq inv (append inv nil))
356 (if (equal (format "%s" (car inv)) "invlist")
366 (push (cons start top) ret)))
367 (setq flip (not flip))
372 (defun gnus-sync-position (search list &optional test)
373 "Find the position of SEARCH in LIST using TEST, defaulting to `eq'."
375 (test (or test 'eq)))
376 (while (and list (not (funcall test (car list) search)))
379 (if (funcall test (car list) search) pos nil)))
381 (defun gnus-sync-topic-group-position (group topic-name)
383 group (cdr (assoc topic-name gnus-topic-alist)) 'equal))
385 (defun gnus-sync-fix-topic-group-position (group topic-name position)
386 (unless (equal position (gnus-sync-topic-group-position group topic-name))
387 (let* ((loc "gnus-sync-fix-topic-group-position")
388 (groups (delete group (cdr (assoc topic-name gnus-topic-alist))))
389 (position (min position (1- (length groups))))
390 (old (nth position groups)))
391 (when (and old (not (equal old group)))
392 (setf (nth position groups) group)
393 (setcdr (assoc topic-name gnus-topic-alist)
394 (append groups (list old)))
395 (gnus-message 9 "%s: %s moved to %d, swap with %s"
396 loc group position old)))))
398 (defun gnus-sync-lesync-pre-save-group-entry (url nentry &rest passed-props)
399 (let* ((loc "gnus-sync-lesync-save-group-entry")
401 (revision (gnus-sync-lesync-get-prop 'rev k))
402 (sname gnus-sync-lesync-name)
403 (topic (gnus-group-topic k))
404 (topic-offset (gnus-sync-topic-group-position k topic))
405 (sources (gnus-sync-lesync-get-prop 'source k)))
406 ;; set the revision so we don't have a conflict
408 (list (cons '_rev revision)))
412 ;; add our name to the sources list for this key
413 (source ,@(if (member gnus-sync-lesync-name sources)
415 (cons gnus-sync-lesync-name sources)))
416 ,(cons 'level (nth 1 nentry))
417 ,@(if topic (list (cons 'topic topic)) nil)
418 ,@(if topic-offset (list (cons 'topic-offset topic-offset)) nil)
420 ,(cons 'read (gnus-sync-range2invlist (nth 2 nentry)))
422 ,@(mapcar (lambda (mark-entry)
423 (cons (car mark-entry)
424 (gnus-sync-range2invlist (cdr mark-entry))))
427 (defun gnus-sync-lesync-post-save-group-entry (url entry)
428 (let* ((loc "gnus-sync-lesync-post-save-group-entry")
429 (k (cdr (assq 'id entry))))
432 ((and (assq 'rev entry) (assq 'id entry))
434 (gnus-sync-lesync-set-prop 'rev k (cdr (assq 'rev entry)))
435 (gnus-sync-lesync-set-prop 'checksum
437 (gnus-sync-deep-print
438 (assoc k gnus-newsrc-alist)))
439 (gnus-message 9 "%s: successfully synced %s to %s"
441 ;; specifically check for document conflicts
442 ((equal "conflict" (format "%s" (cdr-safe (assq 'error entry))))
445 "%s: use `%s' to resolve the conflict synchronizing %s to %s: %s"
446 loc "gnus-sync-read" k url (cdr (assq 'reason entry))))
449 (gnus-error 1 "%s: got error while synchronizing %s to %s: %s"
450 loc k url (cdr (assq 'reason entry))))
453 (gnus-message 2 "%s: unknown sync status after %s to %s: %S"
455 (assoc 'error entry)))
457 (defun gnus-sync-lesync-groups-builder (url)
458 (let ((u (concat url gnus-sync-lesync-design-prefix "/_view/groups")))
459 (cdr (assq 'rows (gnus-sync-lesync-GET u nil)))))
461 (defun gnus-sync-subscribe-group (name)
462 "Subscribe to group NAME. Returns NAME on success, nil otherwise."
463 (gnus-subscribe-newsgroup name))
465 (defun gnus-sync-lesync-read-group-entry (url name entry &rest passed-props)
466 "Read ENTRY information for NAME. Returns NAME if successful.
467 Skips entries whose sources don't contain
468 `gnus-sync-lesync-name'. When the alist PASSED-PROPS has a
469 `subscribe-all' element that evaluates to true, we attempt to
470 subscribe to unknown groups. The user is also allowed to delete
471 unwanted groups via the LeSync URL."
472 (let* ((loc "gnus-sync-lesync-read-group-entry")
473 (entry (gnus-sync-lesync-normalize-group-entry entry passed-props))
474 (subscribe-all (cdr (assq 'subscribe-all passed-props)))
475 (sources (cdr (assq 'source entry)))
476 (rev (cdr (assq 'rev entry)))
477 (in-sources (member gnus-sync-lesync-name sources))
478 (known (assoc name gnus-newsrc-alist))
481 (if (and subscribe-all
482 (y-or-n-p (format "Subscribe to group %s?" name)))
483 (setq known (gnus-sync-subscribe-group name)
486 (when (y-or-n-p (format "Delete group %s from server?" name))
487 (if (equal name (gnus-sync-lesync-delete-group url name))
488 (gnus-message 1 "%s: removed group %s from server %s"
490 (gnus-error 1 "%s: could not remove group %s from server %s"
496 (format "Read group %s even though %s is not in sources %S?"
497 name gnus-sync-lesync-name (or sources ""))))))
499 (gnus-sync-lesync-set-prop 'rev name rev))
501 ;; if the source matches AND we have this group
502 (if (and known in-sources)
504 (gnus-message 10 "%s: reading LeSync entry %s, sources %S"
507 (setq cell (pop entry))
510 (gnus-sync-lesync-set-prop k name val)))
514 (gnus-message 5 "%s: ignoring entry %s, it wasn't subscribed. %s"
515 loc name "Call `gnus-sync-read' with C-u to force it."))
517 (gnus-message 5 "%s: ignoring entry %s, %s not in sources %S"
518 loc name gnus-sync-lesync-name (or sources "")))
521 (defun gnus-sync-lesync-install-group-entry (name)
522 (let* ((master (assoc name gnus-newsrc-alist))
523 (old-topic-name (gnus-group-topic name))
524 (old-topic (assoc old-topic-name gnus-topic-alist))
525 (target-topic-name (gnus-sync-lesync-get-prop 'topic name))
526 (target-topic-offset (gnus-sync-lesync-get-prop 'topic-offset name))
527 (target-topic (assoc target-topic-name gnus-topic-alist))
528 (loc "gnus-sync-lesync-install-group-entry"))
531 (when (eq 'ask gnus-sync-lesync-install-topics)
532 (setq gnus-sync-lesync-install-topics
533 (y-or-n-p "Install topics from LeSync?")))
534 (when (and (eq t gnus-sync-lesync-install-topics)
536 (if (equal old-topic-name target-topic-name)
537 (gnus-message 12 "%s: %s is already in topic %s"
538 loc name target-topic-name)
539 ;; see `gnus-topic-move-group'
540 (when (and old-topic target-topic)
541 (setcdr old-topic (gnus-delete-first name (cdr old-topic)))
542 (gnus-message 5 "%s: removing %s from topic %s"
543 loc name old-topic-name))
545 (when (y-or-n-p (format "Create missing topic %s?"
547 (gnus-topic-create-topic target-topic-name nil)
548 (setq target-topic (assoc target-topic-name
552 (nconc target-topic (list name))
553 (gnus-message 5 "%s: adding %s to topic %s"
554 loc name (car target-topic))
555 (gnus-topic-enter-dribble))
556 (gnus-error 2 "%s: LeSync group %s can't go in missing topic %s"
557 loc name target-topic-name)))
558 (when (and target-topic-offset target-topic)
559 (gnus-sync-fix-topic-group-position
560 name target-topic-name target-topic-offset)))
561 ;; install the subscription level
562 (when (gnus-sync-lesync-get-prop 'level name)
563 (setf (nth 1 master) (gnus-sync-lesync-get-prop 'level name)))
564 ;; install the read and other marks
565 (setf (nth 2 master) (gnus-sync-lesync-get-prop 'read name))
566 (setf (nth 3 master) (gnus-sync-lesync-get-prop 'marks name))
567 (gnus-sync-lesync-set-prop 'checksum
569 (gnus-sync-deep-print master))
571 (gnus-error 1 "%s: invalid LeSync group %s" loc name)
574 ; (gnus-sync-lesync-delete-group (cdr gnus-sync-backend) "nntp+Gmane:gwene.org.slashdot")
576 (defun gnus-sync-lesync-delete-group (url name)
577 "Returns NAME if successful deleting it from URL, an error otherwise."
578 (interactive "sEnter URL to set up: \rsEnter group name: ")
579 (let* ((u (concat (cadr gnus-sync-backend) "/" (url-hexify-string name)))
580 (del (gnus-sync-lesync-DELETE
582 `(,@(when (gnus-sync-lesync-get-prop 'rev name)
583 (list (cons "If-Match"
584 (gnus-sync-lesync-get-prop 'rev name))))))))
585 (or (cdr (assq 'id del)) del)))
587 ;;; (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)))
589 (defun gnus-sync-lesync-normalize-group-entry (entry &optional passed-props)
593 (setq entry (append passed-props entry))
594 (while (setq cell (pop entry))
599 (push (cons k (gnus-sync-invlist2range val)) ret))
600 ;; we already know the name
604 (push (cons 'rev val) ret))
606 (push (cons 'source (append val nil)) ret))
607 ((or (eq k 'float-time)
612 (push (cons k val) ret))
613 ;;; "How often have I said to you that when you have eliminated the
614 ;;; impossible, whatever remains, however improbable, must be the
615 ;;; truth?" --Sherlock Holmes
616 ;; everything remaining must be a mark
617 (t (push (cons k (gnus-sync-invlist2range val)) marks)))))
618 (cons (cons 'marks marks) ret)))
620 (defun gnus-sync-save (&optional force)
621 "Save the Gnus sync data to the backend.
622 With a prefix, FORCE is set and all groups will be saved."
625 ((and (listp gnus-sync-backend)
626 (eq (nth 0 gnus-sync-backend) 'lesync)
627 (stringp (nth 1 gnus-sync-backend)))
629 ;; refresh the revisions if we're forcing the save
631 (mapc (lambda (entry)
632 (when (and (assq 'key entry)
634 (gnus-sync-lesync-set-prop
636 (cdr (assq 'key entry))
637 (cdr (assq 'value entry)))))
638 ;; the revs view is key = name, value = rev
639 (cdr (assq 'rows (gnus-sync-lesync-GET
640 (concat (nth 1 gnus-sync-backend)
641 gnus-sync-lesync-design-prefix
645 (let* ((ftime (float-time))
646 (url (nth 1 gnus-sync-backend))
648 (mapcar (lambda (entry)
649 (gnus-sync-lesync-pre-save-group-entry
650 (cadr gnus-sync-backend)
652 (cons 'float-time ftime)))
653 (gnus-sync-newsrc-loader-builder (not force))))
654 ;; when there are no entries, there's nothing to save
656 (gnus-sync-lesync-POST
657 (concat url "/_bulk_docs")
658 '(("Content-Type" . "application/json"))
659 `((docs . ,(vconcat entries nil))))
661 2 "gnus-sync-save: nothing to save to the LeSync backend")
663 (mapcar (apply-partially 'gnus-sync-lesync-post-save-group-entry url)
665 ((stringp gnus-sync-backend)
666 (gnus-message 7 "gnus-sync-save: saving to backend %s" gnus-sync-backend)
667 ;; populate gnus-sync-newsrc-loader from all but the first dummy
668 ;; entry in gnus-newsrc-alist whose group matches any of the
669 ;; gnus-sync-newsrc-groups
670 ;; TODO: keep the old contents for groups we don't have!
671 (let ((gnus-sync-newsrc-loader (gnus-sync-newsrc-loader-builder)))
672 (with-temp-file gnus-sync-backend
674 (let ((coding-system-for-write gnus-ding-file-coding-system)
675 (standard-output (current-buffer)))
676 (princ (format ";; -*- mode:emacs-lisp; coding: %s; -*-\n"
677 gnus-ding-file-coding-system))
678 (princ ";; Gnus sync data v. 0.0.1\n")
679 ;; TODO: replace with `gnus-sync-deep-print'
680 (let* ((print-quoted t)
682 (print-escape-multibyte nil)
683 (print-escape-nonascii t)
687 (print-escape-newlines t)
688 (variables (cons 'gnus-sync-newsrc-loader
689 gnus-sync-global-vars))
692 (if (and (boundp (setq variable (pop variables)))
693 (symbol-value variable))
696 (princ (symbol-name variable))
698 (prin1 (symbol-value variable))
700 (princ "\n;;; skipping empty variable ")
701 (princ (symbol-name variable)))))
704 "gnus-sync-save: stored variables %s and %d groups in %s"
705 gnus-sync-global-vars
706 (length gnus-sync-newsrc-loader)
709 ;; Idea from Dan Christensen <jdc@chow.mat.jhu.edu>
710 ;; Save the .eld file with extra line breaks.
711 (gnus-message 8 "gnus-sync-save: adding whitespace to %s"
714 (goto-char (point-min))
715 (while (re-search-forward "^(\\|(\\\"" nil t)
716 (replace-match "\n\\&" t))
717 (goto-char (point-min))
718 (while (re-search-forward " $" nil t)
719 (replace-match "" t t))))))))
720 ;; the pass-through case: gnus-sync-backend is not a known choice
723 (defun gnus-sync-read (&optional subscribe-all)
724 "Load the Gnus sync data from the backend.
725 With a prefix, SUBSCRIBE-ALL is set and unknown groups will be subscribed."
727 (when gnus-sync-backend
728 (gnus-message 7 "gnus-sync-read: loading from backend %s" gnus-sync-backend)
730 ((and (listp gnus-sync-backend)
731 (eq (nth 0 gnus-sync-backend) 'lesync)
732 (stringp (nth 1 gnus-sync-backend)))
735 (mapcar (lambda (entry)
736 (setq name (cdr (assq 'id entry)))
737 ;; set ftime the FIRST time through this loop, that
738 ;; way it reflects the time we FINISHED reading
739 (unless ftime (setq ftime (float-time)))
744 (gnus-sync-lesync-read-group-entry
745 (nth 1 gnus-sync-backend)
747 (cdr (assq 'value entry))
749 `(subscribe-all ,subscribe-all)))
750 (gnus-sync-lesync-install-group-entry
751 (cdr (assq 'id entry)))))))
752 (gnus-sync-lesync-groups-builder (nth 1 gnus-sync-backend)))))
754 ((stringp gnus-sync-backend)
756 (if (or debug-on-error debug-on-quit)
757 (load gnus-sync-backend nil t)
759 (load gnus-sync-backend nil t)
761 (error "Error in %s: %s" gnus-sync-backend (cadr var)))))
762 (let ((valid-count 0)
764 (dolist (node gnus-sync-newsrc-loader)
765 (if (gnus-gethash (car node) gnus-newsrc-hashtb)
768 (loop for store in (cdr node)
769 do (setf (nth (car store)
770 (assoc (car node) gnus-newsrc-alist))
772 (push (car node) invalid-groups)))
775 "gnus-sync-read: loaded %d groups (out of %d) from %s"
776 valid-count (length gnus-sync-newsrc-loader)
781 "gnus-sync-read: skipped %d groups (out of %d) from %s"
782 (length invalid-groups)
783 (length gnus-sync-newsrc-loader)
785 (gnus-message 9 "gnus-sync-read: skipped groups: %s"
786 (mapconcat 'identity invalid-groups ", ")))))
789 (gnus-message 9 "gnus-sync-read: remaking the newsrc hashtable")
790 (gnus-make-hashtable-from-newsrc-alist)))
793 (defun gnus-sync-initialize ()
794 "Initialize the Gnus sync facility."
796 (gnus-message 5 "Initializing the sync facility")
797 (gnus-sync-install-hooks))
800 (defun gnus-sync-install-hooks ()
801 "Install the sync hooks."
803 ;; (add-hook 'gnus-get-new-news-hook 'gnus-sync-read)
804 ;; (add-hook 'gnus-read-newsrc-el-hook 'gnus-sync-read)
805 (add-hook 'gnus-save-newsrc-hook 'gnus-sync-save))
807 (defun gnus-sync-unload-hook ()
808 "Uninstall the sync hooks."
810 (remove-hook 'gnus-save-newsrc-hook 'gnus-sync-save))
812 (add-hook 'gnus-sync-unload-hook 'gnus-sync-unload-hook)
814 (when gnus-sync-backend (gnus-sync-initialize))
818 ;;; gnus-sync.el ends here