1 ;;; gnus-sync.el --- synchronization facility for Gnus
3 ;; Copyright (C) 2010-2012 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))
37 ;; against a LeSync server (beware the vampire LeSync, who knows your newsrc)
39 ;; (setq gnus-sync-backend '(lesync "http://lesync.info:5984/tzz")
40 ;; gnus-sync-newsrc-groups '("nntp" "nnrss"))
42 ;; What's a LeSync server?
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
48 ;; 2. run `M-: (gnus-sync-lesync-setup "http://lesync.info:5984/tzz" "tzzadmin" "mypassword" "mysalt" t t)'
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.)
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 look wrong until you do
70 ;; `g'. So it's not run automatically, you have to call it with M-x
73 ;; - use gnus-after-set-mark-hook and gnus-before-update-mark-hook to
74 ;; catch the mark updates
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.
81 ;; - installing topics and groups is inefficient and annoying, lots of
82 ;; prompts could be avoided
86 (eval-when-compile (require 'cl))
88 (or (ignore-errors (progn
90 ;; gnus-fallback-lib/ from gnus/lisp/gnus-fallback-lib
92 (let ((load-path (cons (expand-file-name
94 (file-name-directory (locate-library "gnus")))
98 "json not found in `load-path' or gnus-fallback-lib/ directory.")))
100 (require 'gnus-start)
103 (defvar gnus-topic-alist) ;; gnus-group.el
105 (autoload 'gnus-group-topic "gnus-topic")
106 (autoload 'gnus-topic-create-topic "gnus-topic" nil t)
107 (autoload 'gnus-topic-enter-dribble "gnus-topic"))
109 (defgroup gnus-sync nil
110 "The Gnus synchronization facility."
114 (defcustom gnus-sync-newsrc-groups '("nntp" "nnrss")
115 "List of groups to be synchronized in the gnus-newsrc-alist.
116 The group names are matched, they don't have to be fully
117 qualified. Typically you would choose all of these. That's the
118 default because there is no active sync backend by default, so
119 this setting is harmless until the user chooses a sync backend."
121 :type '(repeat regexp))
123 (defcustom gnus-sync-newsrc-offsets '(2 3)
124 "List of per-group data to be synchronized."
127 :type '(set (const :tag "Read ranges" 2)
128 (const :tag "Marks" 3)))
130 (defcustom gnus-sync-global-vars nil
131 "List of global variables to be synchronized.
132 You may want to sync `gnus-newsrc-last-checked-date' but pretty
133 much any symbol is fair game. You could additionally sync
134 `gnus-newsrc-alist', `gnus-server-alist', `gnus-topic-topology',
135 and `gnus-topic-alist'. Also see `gnus-variable-list'."
137 :type '(repeat (choice (variable :tag "A known variable")
138 (symbol :tag "Any symbol"))))
140 (defcustom gnus-sync-backend nil
141 "The synchronization backend."
143 :type '(radio (const :format "None" nil)
144 (list :tag "Sync server"
145 (const :format "LeSync Server API" lesync)
146 (string :tag "URL of a CouchDB database for API access"))
147 (string :tag "Sync to a file")))
149 (defvar gnus-sync-newsrc-loader nil
150 "Carrier for newsrc data")
152 (defcustom gnus-sync-lesync-name (system-name)
153 "The LeSync name for this machine."
158 (defcustom gnus-sync-lesync-install-topics 'ask
159 "Should LeSync install the recorded topics?"
162 :type '(choice (const :tag "Never Install" nil)
163 (const :tag "Always Install" t)
164 (const :tag "Ask Me Once" ask)))
166 (defvar gnus-sync-lesync-props-hash (make-hash-table :test 'equal)
167 "LeSync props, keyed by group name")
169 (defvar gnus-sync-lesync-design-prefix "/_design/lesync"
170 "The LeSync design prefix for CouchDB")
172 (defvar gnus-sync-lesync-security-object "/_security"
173 "The LeSync security object for CouchDB")
175 (defun gnus-sync-lesync-parse ()
176 "Parse the result of a LeSync request."
177 (goto-char (point-min))
179 (when (search-forward-regexp "^$" nil t)
184 "gnus-sync-lesync-parse: Could not read the LeSync response!")
187 (defun gnus-sync-lesync-call (url method headers &optional kvdata)
188 "Make an access request to URL using KVDATA and METHOD.
189 KVDATA must be an alist."
190 (let ((orig-json-alist-p (symbol-function 'json-alist-p)))
192 (lambda (list) (gnus-sync-json-alist-p list))) ; temp patch
194 (let ((url-request-method method)
195 (url-request-extra-headers headers)
196 (url-request-data (if kvdata (json-encode kvdata) nil)))
197 (with-current-buffer (url-retrieve-synchronously url)
198 (let ((data (gnus-sync-lesync-parse)))
200 12 "gnus-sync-lesync-call: %s URL %s sent %S got %S"
201 method url `((headers . ,headers) (data ,kvdata)) data)
202 (kill-buffer (current-buffer))
204 (fset 'json-alist-p orig-json-alist-p))))
206 (defun gnus-sync-lesync-PUT (url headers &optional data)
207 (gnus-sync-lesync-call url "PUT" headers data))
209 (defun gnus-sync-lesync-POST (url headers &optional data)
210 (gnus-sync-lesync-call url "POST" headers data))
212 (defun gnus-sync-lesync-GET (url headers &optional data)
213 (gnus-sync-lesync-call url "GET" headers data))
215 (defun gnus-sync-lesync-DELETE (url headers &optional data)
216 (gnus-sync-lesync-call url "DELETE" headers data))
218 ;; this is not necessary with newer versions of json.el but 1.2 or older
219 ;; (which are in Emacs 24.1 and earlier) need it
220 (defun gnus-sync-json-alist-p (list)
221 "Non-null if and only if LIST is an alist."
223 (setq list (if (consp (car list))
228 ;; this is not necessary with newer versions of json.el but 1.2 or older
229 ;; (which are in Emacs 24.1 and earlier) need it
230 (defun gnus-sync-json-plist-p (list)
231 "Non-null if and only if LIST is a plist."
233 (setq list (if (and (keywordp (car list))
239 ; (gnus-sync-lesync-setup "http://lesync.info:5984/tzz" "tzzadmin" "mypassword" "mysalt" t t)
240 ; (gnus-sync-lesync-setup "http://lesync.info:5984/tzz")
242 (defun gnus-sync-lesync-setup (url &optional user password salt reader admin)
243 (interactive "sEnter URL to set up: ")
244 "Set up the LeSync database at URL.
245 Install USER as a READER and/or an ADMIN in the security object
246 under \"_security\", and in the CouchDB \"_users\" table using
247 PASSWORD and SALT. Only one USER is thus supported for now.
248 When SALT is nil, a random one will be generated using `random'."
249 (let* ((design-url (concat url gnus-sync-lesync-design-prefix))
250 (security-object (concat url "/_security"))
251 (user-record `((names . [,user]) (roles . [])))
252 (couch-user-name (format "org.couchdb.user:%s" user))
253 (salt (or salt (sha1 (format "%s" (random)))))
255 `((_id . ,couch-user-name)
257 (name . ,(format "%s" user))
260 (password_sha . ,(when password
262 (format "%s%s" password salt))))))
264 (gnus-sync-lesync-find-prop 'rev design-url design-url)
265 (gnus-sync-lesync-get-prop 'rev design-url)))
266 (latest-func "function(head,req)
270 var ftime = (req.query['ftime'] || 0);
271 while (row = getRow())
273 if (row.value['float-time'] > ftime)
275 var s = row.value['_id'];
276 if (s) tosend.push('\"'+s.replace('\"', '\\\"')+'\"');
279 send('['+tosend.join(',') + ']');
283 ;; <key>de.alt.fan.ipod</key>
285 ;; <integer>1</integer>
286 ;; <integer>2</integer>
289 ;; <integer>100</integer>
291 ;; <integer>100</integer>
295 (xmlplistread-func "function(head, req) {
297 start({ 'headers': { 'Content-Type': 'text/xml' } });
300 send('<key>read</key>');
302 while(row = getRow())
304 var read = row.value.read;
305 if (read && read[0] && read[0] == 'invlist')
307 send('<key>'+row.key+'</key>');
308 //send('<invlist>'+read+'</invlist>');
314 for (var i = 1; i < read.length && read[i]; i++)
321 send('<integer>'+read[i]+'</integer>');
326 send('<key>start</key>');
327 send('<integer>'+from+'</integer>');
328 send('<key>end</key>');
329 send('<integer>'+(cur-1)+'</integer>');
345 (subs-func "function(doc){emit([doc._id, doc.source], doc._rev);}")
346 (revs-func "function(doc){emit(doc._id, doc._rev);}")
347 (bytimesubs-func "function(doc)
348 {emit([(doc['float-time']||0), doc._id], doc._rev);}")
349 (bytime-func "function(doc)
350 {emit([(doc['float-time']||0), doc._id], doc);}")
351 (groups-func "function(doc){emit(doc._id, doc);}"))
353 (and (assq 'ok (gnus-sync-lesync-PUT
357 (list `(readers . ,user-record)))
359 (list `(admins . ,user-record))))))
360 (assq 'ok (gnus-sync-lesync-PUT
361 (concat (file-name-directory url)
367 (assq 'ok (gnus-sync-lesync-PUT
370 `(,@(when rev (list (cons '_rev rev)))
371 (lists . ((latest . ,latest-func)
372 (xmlplistread . ,xmlplistread-func)))
373 (views . ((subs . ((map . ,subs-func)))
374 (revs . ((map . ,revs-func)))
375 (bytimesubs . ((map . ,bytimesubs-func)))
376 (bytime . ((map . ,bytime-func)))
377 (groups . ((map . ,groups-func)))))))))))
379 (defun gnus-sync-lesync-find-prop (prop url key)
380 "Retrieve a PROPerty of a document KEY at URL.
381 Calls `gnus-sync-lesync-set-prop'.
382 For the 'rev PROP, uses '_rev against the document."
383 (gnus-sync-lesync-set-prop
384 prop key (cdr (assq (if (eq prop 'rev) '_rev prop)
385 (gnus-sync-lesync-GET url nil)))))
387 (defun gnus-sync-lesync-set-prop (prop key val)
388 "Update the PROPerty of document KEY at URL to VAL.
389 Updates `gnus-sync-lesync-props-hash'."
390 (puthash (format "%s.%s" key prop) val gnus-sync-lesync-props-hash))
392 (defun gnus-sync-lesync-get-prop (prop key)
393 "Get the PROPerty of KEY from `gnus-sync-lesync-props-hash'."
394 (gethash (format "%s.%s" key prop) gnus-sync-lesync-props-hash))
396 (defun gnus-sync-deep-print (data)
397 (let* ((print-quoted t)
399 (print-escape-multibyte nil)
400 (print-escape-nonascii t)
404 (print-escape-newlines t))
407 (defun gnus-sync-newsrc-loader-builder (&optional only-modified)
408 (let* ((entries (cdr gnus-newsrc-alist))
411 (setq entry (pop entries)
413 (when (gnus-grep-in-list name gnus-sync-newsrc-groups)
415 (when (not (equal (gnus-sync-deep-print entry)
416 (gnus-sync-lesync-get-prop 'checksum name)))
417 (gnus-message 9 "%s: add %s, it's modified"
418 "gnus-sync-newsrc-loader-builder" name)
423 ; (json-encode (gnus-sync-range2invlist '((1 . 47137) (47139 . 47714) 48129 48211 49231 49281 49342 49473 49475 49502)))
424 (defun gnus-sync-range2invlist (ranges)
426 (let ((ranges (delq nil ranges))
429 (setq range (pop ranges))
433 (setq from (car range)
439 ; (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))
440 (defun gnus-sync-invlist2range (inv)
441 (setq inv (append inv nil))
442 (if (equal (format "%s" (car inv)) "invlist")
452 (push (cons start top) ret)))
453 (setq flip (not flip))
458 (defun gnus-sync-position (search list &optional test)
459 "Find the position of SEARCH in LIST using TEST, defaulting to `eq'."
461 (test (or test 'eq)))
462 (while (and list (not (funcall test (car list) search)))
465 (if (funcall test (car list) search) pos nil)))
467 (defun gnus-sync-topic-group-position (group topic-name)
469 group (cdr (assoc topic-name gnus-topic-alist)) 'equal))
471 (defun gnus-sync-fix-topic-group-position (group topic-name position)
472 (unless (equal position (gnus-sync-topic-group-position group topic-name))
473 (let* ((loc "gnus-sync-fix-topic-group-position")
474 (groups (delete group (cdr (assoc topic-name gnus-topic-alist))))
475 (position (min position (1- (length groups))))
476 (old (nth position groups)))
477 (when (and old (not (equal old group)))
478 (setf (nth position groups) group)
479 (setcdr (assoc topic-name gnus-topic-alist)
480 (append groups (list old)))
481 (gnus-message 9 "%s: %s moved to %d, swap with %s"
482 loc group position old)))))
484 (defun gnus-sync-lesync-pre-save-group-entry (url nentry &rest passed-props)
485 (let* ((loc "gnus-sync-lesync-save-group-entry")
487 (revision (gnus-sync-lesync-get-prop 'rev k))
488 (sname gnus-sync-lesync-name)
489 (topic (gnus-group-topic k))
490 (topic-offset (gnus-sync-topic-group-position k topic))
491 (sources (gnus-sync-lesync-get-prop 'source k)))
492 ;; set the revision so we don't have a conflict
494 (list (cons '_rev revision)))
498 ;; add our name to the sources list for this key
499 (source ,@(if (member gnus-sync-lesync-name sources)
501 (cons gnus-sync-lesync-name sources)))
502 ,(cons 'level (nth 1 nentry))
503 ,@(if topic (list (cons 'topic topic)) nil)
504 ,@(if topic-offset (list (cons 'topic-offset topic-offset)) nil)
506 ,(cons 'read (gnus-sync-range2invlist (nth 2 nentry)))
508 ,@(delq nil (mapcar (lambda (mark-entry)
509 (gnus-message 12 "%s: prep param %s in %s"
513 (if (listp (cdr mark-entry))
514 (cons (car mark-entry)
515 (gnus-sync-range2invlist
517 (progn ; else this is not a list
518 (gnus-message 9 "%s: non-list param %s in %s"
525 (defun gnus-sync-lesync-post-save-group-entry (url entry)
526 (let* ((loc "gnus-sync-lesync-post-save-group-entry")
527 (k (cdr (assq 'id entry))))
530 ((and (assq 'rev entry) (assq 'id entry))
532 (gnus-sync-lesync-set-prop 'rev k (cdr (assq 'rev entry)))
533 (gnus-sync-lesync-set-prop 'checksum
535 (gnus-sync-deep-print
536 (assoc k gnus-newsrc-alist)))
537 (gnus-message 9 "%s: successfully synced %s to %s"
539 ;; specifically check for document conflicts
540 ((equal "conflict" (format "%s" (cdr-safe (assq 'error entry))))
543 "%s: use `%s' to resolve the conflict synchronizing %s to %s: %s"
544 loc "gnus-sync-read" k url (cdr (assq 'reason entry))))
547 (gnus-error 1 "%s: got error while synchronizing %s to %s: %s"
548 loc k url (cdr (assq 'reason entry))))
551 (gnus-message 2 "%s: unknown sync status after %s to %s: %S"
553 (assoc 'error entry)))
555 (defun gnus-sync-lesync-groups-builder (url)
556 (let ((u (concat url gnus-sync-lesync-design-prefix "/_view/groups")))
557 (cdr (assq 'rows (gnus-sync-lesync-GET u nil)))))
559 (defun gnus-sync-subscribe-group (name)
560 "Subscribe to group NAME. Returns NAME on success, nil otherwise."
561 (gnus-subscribe-newsgroup name))
563 (defun gnus-sync-lesync-read-group-entry (url name entry &rest passed-props)
564 "Read ENTRY information for NAME. Returns NAME if successful.
565 Skips entries whose sources don't contain
566 `gnus-sync-lesync-name'. When the alist PASSED-PROPS has a
567 `subscribe-all' element that evaluates to true, we attempt to
568 subscribe to unknown groups. The user is also allowed to delete
569 unwanted groups via the LeSync URL."
570 (let* ((loc "gnus-sync-lesync-read-group-entry")
571 (entry (gnus-sync-lesync-normalize-group-entry entry passed-props))
572 (subscribe-all (cdr (assq 'subscribe-all passed-props)))
573 (sources (cdr (assq 'source entry)))
574 (rev (cdr (assq 'rev entry)))
575 (in-sources (member gnus-sync-lesync-name sources))
576 (known (assoc name gnus-newsrc-alist))
579 (if (and subscribe-all
580 (y-or-n-p (format "Subscribe to group %s?" name)))
581 (setq known (gnus-sync-subscribe-group name)
584 (when (y-or-n-p (format "Delete group %s from server?" name))
585 (if (equal name (gnus-sync-lesync-delete-group url name))
586 (gnus-message 1 "%s: removed group %s from server %s"
588 (gnus-error 1 "%s: could not remove group %s from server %s"
594 (format "Read group %s even though %s is not in sources %S?"
595 name gnus-sync-lesync-name (or sources ""))))))
597 (gnus-sync-lesync-set-prop 'rev name rev))
599 ;; if the source matches AND we have this group
600 (if (and known in-sources)
602 (gnus-message 10 "%s: reading LeSync entry %s, sources %S"
605 (setq cell (pop entry))
608 (gnus-sync-lesync-set-prop k name val)))
612 (gnus-message 5 "%s: ignoring entry %s, it wasn't subscribed. %s"
613 loc name "Call `gnus-sync-read' with C-u to force it."))
615 (gnus-message 5 "%s: ignoring entry %s, %s not in sources %S"
616 loc name gnus-sync-lesync-name (or sources "")))
619 (defun gnus-sync-lesync-install-group-entry (name)
620 (let* ((master (assoc name gnus-newsrc-alist))
621 (old-topic-name (gnus-group-topic name))
622 (old-topic (assoc old-topic-name gnus-topic-alist))
623 (target-topic-name (gnus-sync-lesync-get-prop 'topic name))
624 (target-topic-offset (gnus-sync-lesync-get-prop 'topic-offset name))
625 (target-topic (assoc target-topic-name gnus-topic-alist))
626 (loc "gnus-sync-lesync-install-group-entry"))
629 (when (eq 'ask gnus-sync-lesync-install-topics)
630 (setq gnus-sync-lesync-install-topics
631 (y-or-n-p "Install topics from LeSync?")))
632 (when (and (eq t gnus-sync-lesync-install-topics)
634 (if (equal old-topic-name target-topic-name)
635 (gnus-message 12 "%s: %s is already in topic %s"
636 loc name target-topic-name)
637 ;; see `gnus-topic-move-group'
638 (when (and old-topic target-topic)
639 (setcdr old-topic (gnus-delete-first name (cdr old-topic)))
640 (gnus-message 5 "%s: removing %s from topic %s"
641 loc name old-topic-name))
643 (when (y-or-n-p (format "Create missing topic %s?"
645 (gnus-topic-create-topic target-topic-name nil)
646 (setq target-topic (assoc target-topic-name
650 (nconc target-topic (list name))
651 (gnus-message 5 "%s: adding %s to topic %s"
652 loc name (car target-topic))
653 (gnus-topic-enter-dribble))
654 (gnus-error 2 "%s: LeSync group %s can't go in missing topic %s"
655 loc name target-topic-name)))
656 (when (and target-topic-offset target-topic)
657 (gnus-sync-fix-topic-group-position
658 name target-topic-name target-topic-offset)))
659 ;; install the subscription level
660 (when (gnus-sync-lesync-get-prop 'level name)
661 (setf (nth 1 master) (gnus-sync-lesync-get-prop 'level name)))
662 ;; install the read and other marks
663 (setf (nth 2 master) (gnus-sync-lesync-get-prop 'read name))
664 (setf (nth 3 master) (gnus-sync-lesync-get-prop 'marks name))
665 (gnus-sync-lesync-set-prop 'checksum
667 (gnus-sync-deep-print master))
669 (gnus-error 1 "%s: invalid LeSync group %s" loc name)
672 ; (gnus-sync-lesync-delete-group (cdr gnus-sync-backend) "nntp+Gmane:gwene.org.slashdot")
674 (defun gnus-sync-lesync-delete-group (url name)
675 "Returns NAME if successful deleting it from URL, an error otherwise."
676 (interactive "sEnter URL to set up: \rsEnter group name: ")
677 (let* ((u (concat (cadr gnus-sync-backend) "/" (url-hexify-string name)))
678 (del (gnus-sync-lesync-DELETE
680 `(,@(when (gnus-sync-lesync-get-prop 'rev name)
681 (list (cons "If-Match"
682 (gnus-sync-lesync-get-prop 'rev name))))))))
683 (or (cdr (assq 'id del)) del)))
685 ;;; (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)))
687 (defun gnus-sync-lesync-normalize-group-entry (entry &optional passed-props)
691 (setq entry (append passed-props entry))
692 (while (setq cell (pop entry))
697 (push (cons k (gnus-sync-invlist2range val)) ret))
698 ;; we ignore these parameters
699 ((member k '(_id subscribe-all _deleted_conflicts))
702 (push (cons 'rev val) ret))
704 (push (cons 'source (append val nil)) ret))
705 ((or (eq k 'float-time)
710 (push (cons k val) ret))
711 ;;; "How often have I said to you that when you have eliminated the
712 ;;; impossible, whatever remains, however improbable, must be the
713 ;;; truth?" --Sherlock Holmes
714 ;; everything remaining must be a mark
715 (t (push (cons k (gnus-sync-invlist2range val)) marks)))))
716 (cons (cons 'marks marks) ret)))
718 (defun gnus-sync-save (&optional force)
719 "Save the Gnus sync data to the backend.
720 With a prefix, FORCE is set and all groups will be saved."
723 ((and (listp gnus-sync-backend)
724 (eq (nth 0 gnus-sync-backend) 'lesync)
725 (stringp (nth 1 gnus-sync-backend)))
727 ;; refresh the revisions if we're forcing the save
729 (mapc (lambda (entry)
730 (when (and (assq 'key entry)
732 (gnus-sync-lesync-set-prop
734 (cdr (assq 'key entry))
735 (cdr (assq 'value entry)))))
736 ;; the revs view is key = name, value = rev
737 (cdr (assq 'rows (gnus-sync-lesync-GET
738 (concat (nth 1 gnus-sync-backend)
739 gnus-sync-lesync-design-prefix
743 (let* ((ftime (float-time))
744 (url (nth 1 gnus-sync-backend))
746 (mapcar (lambda (entry)
747 (gnus-sync-lesync-pre-save-group-entry
748 (cadr gnus-sync-backend)
750 (cons 'float-time ftime)))
751 (gnus-sync-newsrc-loader-builder (not force))))
752 ;; when there are no entries, there's nothing to save
754 (gnus-sync-lesync-POST
755 (concat url "/_bulk_docs")
756 '(("Content-Type" . "application/json"))
757 `((docs . ,(vconcat entries nil))))
759 2 "gnus-sync-save: nothing to save to the LeSync backend")
761 (mapcar (lambda (e) (gnus-sync-lesync-post-save-group-entry url e))
763 ((stringp gnus-sync-backend)
764 (gnus-message 7 "gnus-sync-save: saving to backend %s" gnus-sync-backend)
765 ;; populate gnus-sync-newsrc-loader from all but the first dummy
766 ;; entry in gnus-newsrc-alist whose group matches any of the
767 ;; gnus-sync-newsrc-groups
768 ;; TODO: keep the old contents for groups we don't have!
769 (let ((gnus-sync-newsrc-loader
770 (loop for entry in (cdr gnus-newsrc-alist)
771 when (gnus-grep-in-list
772 (car entry) ;the group name
773 gnus-sync-newsrc-groups)
774 collect (cons (car entry)
775 (mapcar (lambda (offset)
776 (cons offset (nth offset entry)))
777 gnus-sync-newsrc-offsets)))))
778 (with-temp-file gnus-sync-backend
780 (let ((coding-system-for-write gnus-ding-file-coding-system)
781 (standard-output (current-buffer)))
782 (princ (format ";; -*- mode:emacs-lisp; coding: %s; -*-\n"
783 gnus-ding-file-coding-system))
784 (princ ";; Gnus sync data v. 0.0.1\n")
785 ;; TODO: replace with `gnus-sync-deep-print'
786 (let* ((print-quoted t)
788 (print-escape-multibyte nil)
789 (print-escape-nonascii t)
793 (print-escape-newlines t)
794 (variables (cons 'gnus-sync-newsrc-loader
795 gnus-sync-global-vars))
798 (if (and (boundp (setq variable (pop variables)))
799 (symbol-value variable))
802 (princ (symbol-name variable))
804 (prin1 (symbol-value variable))
806 (princ "\n;;; skipping empty variable ")
807 (princ (symbol-name variable)))))
810 "gnus-sync-save: stored variables %s and %d groups in %s"
811 gnus-sync-global-vars
812 (length gnus-sync-newsrc-loader)
815 ;; Idea from Dan Christensen <jdc@chow.mat.jhu.edu>
816 ;; Save the .eld file with extra line breaks.
817 (gnus-message 8 "gnus-sync-save: adding whitespace to %s"
820 (goto-char (point-min))
821 (while (re-search-forward "^(\\|(\\\"" nil t)
822 (replace-match "\n\\&" t))
823 (goto-char (point-min))
824 (while (re-search-forward " $" nil t)
825 (replace-match "" t t))))))))
826 ;; the pass-through case: gnus-sync-backend is not a known choice
829 (defun gnus-sync-read (&optional subscribe-all)
830 "Load the Gnus sync data from the backend.
831 With a prefix, SUBSCRIBE-ALL is set and unknown groups will be subscribed."
833 (when gnus-sync-backend
834 (gnus-message 7 "gnus-sync-read: loading from backend %s" gnus-sync-backend)
836 ((and (listp gnus-sync-backend)
837 (eq (nth 0 gnus-sync-backend) 'lesync)
838 (stringp (nth 1 gnus-sync-backend)))
841 (mapc (lambda (entry)
842 (setq name (cdr (assq 'id entry)))
843 ;; set ftime the FIRST time through this loop, that
844 ;; way it reflects the time we FINISHED reading
845 (unless ftime (setq ftime (float-time)))
850 (gnus-sync-lesync-read-group-entry
851 (nth 1 gnus-sync-backend)
853 (cdr (assq 'value entry))
855 `(subscribe-all ,subscribe-all)))
856 (gnus-sync-lesync-install-group-entry
857 (cdr (assq 'id entry)))))))
858 (gnus-sync-lesync-groups-builder (nth 1 gnus-sync-backend)))))
860 ((stringp gnus-sync-backend)
862 (if (or debug-on-error debug-on-quit)
863 (load gnus-sync-backend nil t)
865 (load gnus-sync-backend nil t)
867 (error "Error in %s: %s" gnus-sync-backend (cadr var)))))
868 (let ((valid-count 0)
870 (dolist (node gnus-sync-newsrc-loader)
871 (if (gnus-gethash (car node) gnus-newsrc-hashtb)
874 (loop for store in (cdr node)
875 do (setf (nth (car store)
876 (assoc (car node) gnus-newsrc-alist))
878 (push (car node) invalid-groups)))
881 "gnus-sync-read: loaded %d groups (out of %d) from %s"
882 valid-count (length gnus-sync-newsrc-loader)
887 "gnus-sync-read: skipped %d groups (out of %d) from %s"
888 (length invalid-groups)
889 (length gnus-sync-newsrc-loader)
891 (gnus-message 9 "gnus-sync-read: skipped groups: %s"
892 (mapconcat 'identity invalid-groups ", ")))))
895 (gnus-message 9 "gnus-sync-read: remaking the newsrc hashtable")
896 (gnus-make-hashtable-from-newsrc-alist)))
899 (defun gnus-sync-initialize ()
900 "Initialize the Gnus sync facility."
902 (gnus-message 5 "Initializing the sync facility")
903 (gnus-sync-install-hooks))
906 (defun gnus-sync-install-hooks ()
907 "Install the sync hooks."
909 ;; (add-hook 'gnus-get-new-news-hook 'gnus-sync-read)
910 ;; (add-hook 'gnus-read-newsrc-el-hook 'gnus-sync-read)
911 (add-hook 'gnus-save-newsrc-hook 'gnus-sync-save))
913 (defun gnus-sync-unload-hook ()
914 "Uninstall the sync hooks."
916 (remove-hook 'gnus-save-newsrc-hook 'gnus-sync-save))
918 (add-hook 'gnus-sync-unload-hook 'gnus-sync-unload-hook)
920 (when gnus-sync-backend (gnus-sync-initialize))
924 ;;; gnus-sync.el ends here