1 ;;; gnus-sync.el --- synchronization facility for Gnus
3 ;; Copyright (C) 2010-2016 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)
104 (defvar gnus-topic-alist) ;; gnus-group.el
105 (autoload 'gnus-group-topic "gnus-topic")
107 (defgroup gnus-sync nil
108 "The Gnus synchronization facility."
112 (defcustom gnus-sync-newsrc-groups '("nntp" "nnrss")
113 "List of groups to be synchronized in the gnus-newsrc-alist.
114 The group names are matched, they don't have to be fully
115 qualified. Typically you would choose all of these. That's the
116 default because there is no active sync backend by default, so
117 this setting is harmless until the user chooses a sync backend."
119 :type '(repeat regexp))
121 (defcustom gnus-sync-newsrc-offsets '(2 3)
122 "List of per-group data to be synchronized."
125 :type '(set (const :tag "Read ranges" 2)
126 (const :tag "Marks" 3)))
128 (defcustom gnus-sync-global-vars nil
129 "List of global variables to be synchronized.
130 You may want to sync `gnus-newsrc-last-checked-date' but pretty
131 much any symbol is fair game. You could additionally sync
132 `gnus-newsrc-alist', `gnus-server-alist', `gnus-topic-topology',
133 and `gnus-topic-alist'. Also see `gnus-variable-list'."
135 :type '(repeat (choice (variable :tag "A known variable")
136 (symbol :tag "Any symbol"))))
138 (defcustom gnus-sync-backend nil
139 "The synchronization backend."
141 :type '(radio (const :format "None" nil)
142 (list :tag "Sync server"
143 (const :format "LeSync Server API" lesync)
144 (string :tag "URL of a CouchDB database for API access"))
145 (string :tag "Sync to a file")))
147 (defvar gnus-sync-newsrc-loader nil
148 "Carrier for newsrc data")
150 (defcustom gnus-sync-file-encrypt-to nil
151 "If non-nil, set `epa-file-encrypt-to' from this for encrypting the Sync file."
153 :type '(choice string (repeat string))
156 (defcustom gnus-sync-lesync-name (system-name)
157 "The LeSync name for this machine."
162 (defcustom gnus-sync-lesync-install-topics 'ask
163 "Should LeSync install the recorded topics?"
166 :type '(choice (const :tag "Never Install" nil)
167 (const :tag "Always Install" t)
168 (const :tag "Ask Me Once" ask)))
170 (defvar gnus-sync-lesync-props-hash (make-hash-table :test 'equal)
171 "LeSync props, keyed by group name")
173 (defvar gnus-sync-lesync-design-prefix "/_design/lesync"
174 "The LeSync design prefix for CouchDB")
176 (defvar gnus-sync-lesync-security-object "/_security"
177 "The LeSync security object for CouchDB")
179 (defun gnus-sync-lesync-parse ()
180 "Parse the result of a LeSync request."
181 (goto-char (point-min))
183 (when (search-forward-regexp "^$" nil t)
188 "gnus-sync-lesync-parse: Could not read the LeSync response!")
191 (defun gnus-sync-lesync-call (url method headers &optional kvdata)
192 "Make an access request to URL using KVDATA and METHOD.
193 KVDATA must be an alist."
194 (gmm-flet ((json-alist-p (list) (gnus-sync-json-alist-p list))) ; temp patch
195 (let ((url-request-method method)
196 (url-request-extra-headers headers)
197 (url-request-data (if kvdata (json-encode kvdata) nil)))
198 (with-current-buffer (url-retrieve-synchronously url)
199 (let ((data (gnus-sync-lesync-parse)))
200 (gnus-message 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))
205 (defun gnus-sync-lesync-PUT (url headers &optional data)
206 (gnus-sync-lesync-call url "PUT" headers data))
208 (defun gnus-sync-lesync-POST (url headers &optional data)
209 (gnus-sync-lesync-call url "POST" headers data))
211 (defun gnus-sync-lesync-GET (url headers &optional data)
212 (gnus-sync-lesync-call url "GET" headers data))
214 (defun gnus-sync-lesync-DELETE (url headers &optional data)
215 (gnus-sync-lesync-call url "DELETE" headers data))
217 ;; this is not necessary with newer versions of json.el but 1.2 or older
218 ;; (which are in Emacs 24.1 and earlier) need it
219 (defun gnus-sync-json-alist-p (list)
220 "Non-null if and only if LIST is an alist."
222 (setq list (if (consp (car list))
227 ;; this is not necessary with newer versions of json.el but 1.2 or older
228 ;; (which are in Emacs 24.1 and earlier) need it
229 (defun gnus-sync-json-plist-p (list)
230 "Non-null if and only if LIST is a plist."
232 (setq list (if (and (keywordp (car list))
238 ; (gnus-sync-lesync-setup "http://lesync.info:5984/tzz" "tzzadmin" "mypassword" "mysalt" t t)
239 ; (gnus-sync-lesync-setup "http://lesync.info:5984/tzz")
241 (defun gnus-sync-lesync-setup (url &optional user password salt reader admin)
242 (interactive "sEnter URL to set up: ")
243 "Set up the LeSync database at URL.
244 Install USER as a READER and/or an ADMIN in the security object
245 under \"_security\", and in the CouchDB \"_users\" table using
246 PASSWORD and SALT. Only one USER is thus supported for now.
247 When SALT is nil, a random one will be generated using `random'."
248 (let* ((design-url (concat url gnus-sync-lesync-design-prefix))
249 (security-object (concat url "/_security"))
250 (user-record `((names . [,user]) (roles . [])))
251 (couch-user-name (format "org.couchdb.user:%s" user))
252 (salt (or salt (sha1 (format "%s" (random)))))
254 `((_id . ,couch-user-name)
256 (name . ,(format "%s" user))
259 (password_sha . ,(when password
261 (format "%s%s" password salt))))))
263 (gnus-sync-lesync-find-prop 'rev design-url design-url)
264 (gnus-sync-lesync-get-prop 'rev design-url)))
265 (latest-func "function(head,req)
269 var ftime = (req.query['ftime'] || 0);
270 while (row = getRow())
272 if (row.value['float-time'] > ftime)
274 var s = row.value['_id'];
275 if (s) tosend.push('\"'+s.replace('\"', '\\\"')+'\"');
278 send('['+tosend.join(',') + ']');
282 ;; <key>de.alt.fan.ipod</key>
284 ;; <integer>1</integer>
285 ;; <integer>2</integer>
288 ;; <integer>100</integer>
290 ;; <integer>100</integer>
294 (xmlplistread-func "function(head, req) {
296 start({ 'headers': { 'Content-Type': 'text/xml' } });
299 send('<key>read</key>');
301 while(row = getRow())
303 var read = row.value.read;
304 if (read && read[0] && read[0] == 'invlist')
306 send('<key>'+row.key+'</key>');
307 //send('<invlist>'+read+'</invlist>');
313 for (var i = 1; i < read.length && read[i]; i++)
320 send('<integer>'+read[i]+'</integer>');
325 send('<key>start</key>');
326 send('<integer>'+from+'</integer>');
327 send('<key>end</key>');
328 send('<integer>'+(cur-1)+'</integer>');
344 (subs-func "function(doc){emit([doc._id, doc.source], doc._rev);}")
345 (revs-func "function(doc){emit(doc._id, doc._rev);}")
346 (bytimesubs-func "function(doc)
347 {emit([(doc['float-time']||0), doc._id], doc._rev);}")
348 (bytime-func "function(doc)
349 {emit([(doc['float-time']||0), doc._id], doc);}")
350 (groups-func "function(doc){emit(doc._id, doc);}"))
352 (and (assq 'ok (gnus-sync-lesync-PUT
356 (list `(readers . ,user-record)))
358 (list `(admins . ,user-record))))))
359 (assq 'ok (gnus-sync-lesync-PUT
360 (concat (file-name-directory url)
366 (assq 'ok (gnus-sync-lesync-PUT
369 `(,@(when rev (list (cons '_rev rev)))
370 (lists . ((latest . ,latest-func)
371 (xmlplistread . ,xmlplistread-func)))
372 (views . ((subs . ((map . ,subs-func)))
373 (revs . ((map . ,revs-func)))
374 (bytimesubs . ((map . ,bytimesubs-func)))
375 (bytime . ((map . ,bytime-func)))
376 (groups . ((map . ,groups-func)))))))))))
378 (defun gnus-sync-lesync-find-prop (prop url key)
379 "Retrieve a PROPerty of a document KEY at URL.
380 Calls `gnus-sync-lesync-set-prop'.
381 For the 'rev PROP, uses '_rev against the document."
382 (gnus-sync-lesync-set-prop
383 prop key (cdr (assq (if (eq prop 'rev) '_rev prop)
384 (gnus-sync-lesync-GET url nil)))))
386 (defun gnus-sync-lesync-set-prop (prop key val)
387 "Update the PROPerty of document KEY at URL to VAL.
388 Updates `gnus-sync-lesync-props-hash'."
389 (puthash (format "%s.%s" key prop) val gnus-sync-lesync-props-hash))
391 (defun gnus-sync-lesync-get-prop (prop key)
392 "Get the PROPerty of KEY from `gnus-sync-lesync-props-hash'."
393 (gethash (format "%s.%s" key prop) gnus-sync-lesync-props-hash))
395 (defun gnus-sync-deep-print (data)
396 (let* ((print-quoted t)
398 (print-escape-multibyte nil)
399 (print-escape-nonascii t)
403 (print-escape-newlines t))
406 (defun gnus-sync-newsrc-loader-builder (&optional only-modified)
407 (let* ((entries (cdr gnus-newsrc-alist))
410 (setq entry (pop entries)
412 (when (gnus-grep-in-list name gnus-sync-newsrc-groups)
414 (when (not (equal (gnus-sync-deep-print entry)
415 (gnus-sync-lesync-get-prop 'checksum name)))
416 (gnus-message 9 "%s: add %s, it's modified"
417 "gnus-sync-newsrc-loader-builder" name)
422 ; (json-encode (gnus-sync-range2invlist '((1 . 47137) (47139 . 47714) 48129 48211 49231 49281 49342 49473 49475 49502)))
423 (defun gnus-sync-range2invlist (ranges)
425 (let ((ranges (delq nil ranges))
428 (setq range (pop ranges))
432 (setq from (car range)
438 ; (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))
439 (defun gnus-sync-invlist2range (inv)
440 (setq inv (append inv nil))
441 (if (equal (format "%s" (car inv)) "invlist")
451 (push (cons start top) ret)))
452 (setq flip (not flip))
457 (defun gnus-sync-position (search list &optional test)
458 "Find the position of SEARCH in LIST using TEST, defaulting to `eq'."
460 (test (or test 'eq)))
461 (while (and list (not (funcall test (car list) search)))
464 (if (funcall test (car list) search) pos nil)))
466 (defun gnus-sync-topic-group-position (group topic-name)
468 group (cdr (assoc topic-name gnus-topic-alist)) 'equal))
470 (defun gnus-sync-fix-topic-group-position (group topic-name position)
471 (unless (equal position (gnus-sync-topic-group-position group topic-name))
472 (let* ((loc "gnus-sync-fix-topic-group-position")
473 (groups (delete group (cdr (assoc topic-name gnus-topic-alist))))
474 (position (min position (1- (length groups))))
475 (old (nth position groups)))
476 (when (and old (not (equal old group)))
477 (setf (nth position groups) group)
478 (setcdr (assoc topic-name gnus-topic-alist)
479 (append groups (list old)))
480 (gnus-message 9 "%s: %s moved to %d, swap with %s"
481 loc group position old)))))
483 (defun gnus-sync-lesync-pre-save-group-entry (url nentry &rest passed-props)
484 (let* ((loc "gnus-sync-lesync-save-group-entry")
486 (revision (gnus-sync-lesync-get-prop 'rev k))
487 (sname gnus-sync-lesync-name)
488 (topic (gnus-group-topic k))
489 (topic-offset (gnus-sync-topic-group-position k topic))
490 (sources (gnus-sync-lesync-get-prop 'source k)))
491 ;; set the revision so we don't have a conflict
493 (list (cons '_rev revision)))
497 ;; add our name to the sources list for this key
498 (source ,@(if (member gnus-sync-lesync-name sources)
500 (cons gnus-sync-lesync-name sources)))
501 ,(cons 'level (nth 1 nentry))
502 ,@(if topic (list (cons 'topic topic)) nil)
503 ,@(if topic-offset (list (cons 'topic-offset topic-offset)) nil)
505 ,(cons 'read (gnus-sync-range2invlist (nth 2 nentry)))
507 ,@(delq nil (mapcar (lambda (mark-entry)
508 (gnus-message 12 "%s: prep param %s in %s"
512 (if (listp (cdr mark-entry))
513 (cons (car mark-entry)
514 (gnus-sync-range2invlist
516 (progn ; else this is not a list
517 (gnus-message 9 "%s: non-list param %s in %s"
524 (defun gnus-sync-lesync-post-save-group-entry (url entry)
525 (let* ((loc "gnus-sync-lesync-post-save-group-entry")
526 (k (cdr (assq 'id entry))))
529 ((and (assq 'rev entry) (assq 'id entry))
531 (gnus-sync-lesync-set-prop 'rev k (cdr (assq 'rev entry)))
532 (gnus-sync-lesync-set-prop 'checksum
534 (gnus-sync-deep-print
535 (assoc k gnus-newsrc-alist)))
536 (gnus-message 9 "%s: successfully synced %s to %s"
538 ;; specifically check for document conflicts
539 ((equal "conflict" (format "%s" (cdr-safe (assq 'error entry))))
542 "%s: use `%s' to resolve the conflict synchronizing %s to %s: %s"
543 loc "gnus-sync-read" k url (cdr (assq 'reason entry))))
546 (gnus-error 1 "%s: got error while synchronizing %s to %s: %s"
547 loc k url (cdr (assq 'reason entry))))
550 (gnus-message 2 "%s: unknown sync status after %s to %s: %S"
552 (assoc 'error entry)))
554 (defun gnus-sync-lesync-groups-builder (url)
555 (let ((u (concat url gnus-sync-lesync-design-prefix "/_view/groups")))
556 (cdr (assq 'rows (gnus-sync-lesync-GET u nil)))))
558 (defun gnus-sync-subscribe-group (name)
559 "Subscribe to group NAME. Returns NAME on success, nil otherwise."
560 (gnus-subscribe-newsgroup name))
562 (defun gnus-sync-lesync-read-group-entry (url name entry &rest passed-props)
563 "Read ENTRY information for NAME. Returns NAME if successful.
564 Skips entries whose sources don't contain
565 `gnus-sync-lesync-name'. When the alist PASSED-PROPS has a
566 `subscribe-all' element that evaluates to true, we attempt to
567 subscribe to unknown groups. The user is also allowed to delete
568 unwanted groups via the LeSync URL."
569 (let* ((loc "gnus-sync-lesync-read-group-entry")
570 (entry (gnus-sync-lesync-normalize-group-entry entry passed-props))
571 (subscribe-all (cdr (assq 'subscribe-all passed-props)))
572 (sources (cdr (assq 'source entry)))
573 (rev (cdr (assq 'rev entry)))
574 (in-sources (member gnus-sync-lesync-name sources))
575 (known (assoc name gnus-newsrc-alist))
578 (if (and subscribe-all
579 (y-or-n-p (format "Subscribe to group %s?" name)))
580 (setq known (gnus-sync-subscribe-group name)
583 (when (y-or-n-p (format "Delete group %s from server?" name))
584 (if (equal name (gnus-sync-lesync-delete-group url name))
585 (gnus-message 1 "%s: removed group %s from server %s"
587 (gnus-error 1 "%s: could not remove group %s from server %s"
593 (format "Read group %s even though %s is not in sources %S?"
594 name gnus-sync-lesync-name (or sources ""))))))
596 (gnus-sync-lesync-set-prop 'rev name rev))
598 ;; if the source matches AND we have this group
599 (if (and known in-sources)
601 (gnus-message 10 "%s: reading LeSync entry %s, sources %S"
604 (setq cell (pop entry))
607 (gnus-sync-lesync-set-prop k name val)))
611 (gnus-message 5 "%s: ignoring entry %s, it wasn't subscribed. %s"
612 loc name "Call `gnus-sync-read' with C-u to force it."))
614 (gnus-message 5 "%s: ignoring entry %s, %s not in sources %S"
615 loc name gnus-sync-lesync-name (or sources "")))
618 (declare-function gnus-topic-create-topic "gnus-topic"
619 (topic parent &optional previous full-topic))
620 (declare-function gnus-topic-enter-dribble "gnus-topic" ())
622 (defun gnus-sync-lesync-install-group-entry (name)
623 (let* ((master (assoc name gnus-newsrc-alist))
624 (old-topic-name (gnus-group-topic name))
625 (old-topic (assoc old-topic-name gnus-topic-alist))
626 (target-topic-name (gnus-sync-lesync-get-prop 'topic name))
627 (target-topic-offset (gnus-sync-lesync-get-prop 'topic-offset name))
628 (target-topic (assoc target-topic-name gnus-topic-alist))
629 (loc "gnus-sync-lesync-install-group-entry"))
632 (when (eq 'ask gnus-sync-lesync-install-topics)
633 (setq gnus-sync-lesync-install-topics
634 (y-or-n-p "Install topics from LeSync?")))
635 (when (and (eq t gnus-sync-lesync-install-topics)
637 (if (equal old-topic-name target-topic-name)
638 (gnus-message 12 "%s: %s is already in topic %s"
639 loc name target-topic-name)
640 ;; see `gnus-topic-move-group'
641 (when (and old-topic target-topic)
642 (setcdr old-topic (gnus-delete-first name (cdr old-topic)))
643 (gnus-message 5 "%s: removing %s from topic %s"
644 loc name old-topic-name))
646 (when (y-or-n-p (format "Create missing topic %s?"
648 (gnus-topic-create-topic target-topic-name nil)
649 (setq target-topic (assoc target-topic-name
653 (nconc target-topic (list name))
654 (gnus-message 5 "%s: adding %s to topic %s"
655 loc name (car target-topic))
656 (gnus-topic-enter-dribble))
657 (gnus-error 2 "%s: LeSync group %s can't go in missing topic %s"
658 loc name target-topic-name)))
659 (when (and target-topic-offset target-topic)
660 (gnus-sync-fix-topic-group-position
661 name target-topic-name target-topic-offset)))
662 ;; install the subscription level
663 (when (gnus-sync-lesync-get-prop 'level name)
664 (setf (nth 1 master) (gnus-sync-lesync-get-prop 'level name)))
665 ;; install the read and other marks
666 (setf (nth 2 master) (gnus-sync-lesync-get-prop 'read name))
667 (setf (nth 3 master) (gnus-sync-lesync-get-prop 'marks name))
668 (gnus-sync-lesync-set-prop 'checksum
670 (gnus-sync-deep-print master))
672 (gnus-error 1 "%s: invalid LeSync group %s" loc name)
675 ; (gnus-sync-lesync-delete-group (cdr gnus-sync-backend) "nntp+Gmane:gwene.org.slashdot")
677 (defun gnus-sync-lesync-delete-group (url name)
678 "Returns NAME if successful deleting it from URL, an error otherwise."
679 (interactive "sEnter URL to set up: \rsEnter group name: ")
680 (let* ((u (concat (cadr gnus-sync-backend) "/" (url-hexify-string name)))
681 (del (gnus-sync-lesync-DELETE
683 `(,@(when (gnus-sync-lesync-get-prop 'rev name)
684 (list (cons "If-Match"
685 (gnus-sync-lesync-get-prop 'rev name))))))))
686 (or (cdr (assq 'id del)) del)))
688 ;;; (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)))
690 (defun gnus-sync-lesync-normalize-group-entry (entry &optional passed-props)
694 (setq entry (append passed-props entry))
695 (while (setq cell (pop entry))
700 (push (cons k (gnus-sync-invlist2range val)) ret))
701 ;; we ignore these parameters
702 ((member k '(_id subscribe-all _deleted_conflicts))
705 (push (cons 'rev val) ret))
707 (push (cons 'source (append val nil)) ret))
708 ((or (eq k 'float-time)
713 (push (cons k val) ret))
714 ;;; "How often have I said to you that when you have eliminated the
715 ;;; impossible, whatever remains, however improbable, must be the
716 ;;; truth?" --Sherlock Holmes
717 ;; everything remaining must be a mark
718 (t (push (cons k (gnus-sync-invlist2range val)) marks)))))
719 (cons (cons 'marks marks) ret)))
721 (defun gnus-sync-save (&optional force)
722 "Save the Gnus sync data to the backend.
723 With a prefix, FORCE is set and all groups will be saved."
726 ((and (listp gnus-sync-backend)
727 (eq (nth 0 gnus-sync-backend) 'lesync)
728 (stringp (nth 1 gnus-sync-backend)))
730 ;; refresh the revisions if we're forcing the save
732 (mapc (lambda (entry)
733 (when (and (assq 'key entry)
735 (gnus-sync-lesync-set-prop
737 (cdr (assq 'key entry))
738 (cdr (assq 'value entry)))))
739 ;; the revs view is key = name, value = rev
740 (cdr (assq 'rows (gnus-sync-lesync-GET
741 (concat (nth 1 gnus-sync-backend)
742 gnus-sync-lesync-design-prefix
746 (let* ((ftime (float-time))
747 (url (nth 1 gnus-sync-backend))
749 (mapcar (lambda (entry)
750 (gnus-sync-lesync-pre-save-group-entry
751 (cadr gnus-sync-backend)
753 (cons 'float-time ftime)))
754 (gnus-sync-newsrc-loader-builder (not force))))
755 ;; when there are no entries, there's nothing to save
757 (gnus-sync-lesync-POST
758 (concat url "/_bulk_docs")
759 '(("Content-Type" . "application/json"))
760 `((docs . ,(vconcat entries nil))))
762 2 "gnus-sync-save: nothing to save to the LeSync backend")
764 (mapcar (lambda (e) (gnus-sync-lesync-post-save-group-entry url e))
766 ((stringp gnus-sync-backend)
767 (gnus-message 7 "gnus-sync-save: saving to backend %s" gnus-sync-backend)
768 ;; populate gnus-sync-newsrc-loader from all but the first dummy
769 ;; entry in gnus-newsrc-alist whose group matches any of the
770 ;; gnus-sync-newsrc-groups
771 ;; TODO: keep the old contents for groups we don't have!
772 (let ((gnus-sync-newsrc-loader
773 (loop for entry in (cdr gnus-newsrc-alist)
774 when (gnus-grep-in-list
775 (car entry) ;the group name
776 gnus-sync-newsrc-groups)
777 collect (cons (car entry)
778 (mapcar (lambda (offset)
779 (cons offset (nth offset entry)))
780 gnus-sync-newsrc-offsets)))))
781 (with-temp-file gnus-sync-backend
783 (let ((coding-system-for-write gnus-ding-file-coding-system)
784 (standard-output (current-buffer)))
785 (when gnus-sync-file-encrypt-to
786 (set (make-local-variable 'epa-file-encrypt-to)
787 gnus-sync-file-encrypt-to))
788 (princ (format ";; -*- mode:emacs-lisp; coding: %s; -*-\n"
789 gnus-ding-file-coding-system))
790 (princ ";; Gnus sync data v. 0.0.1\n")
791 ;; TODO: replace with `gnus-sync-deep-print'
792 (let* ((print-quoted t)
794 (print-escape-multibyte nil)
795 (print-escape-nonascii t)
799 (print-escape-newlines t)
800 (variables (cons 'gnus-sync-newsrc-loader
801 gnus-sync-global-vars))
804 (if (and (boundp (setq variable (pop variables)))
805 (symbol-value variable))
808 (princ (symbol-name variable))
810 (prin1 (symbol-value variable))
812 (princ "\n;;; skipping empty variable ")
813 (princ (symbol-name variable)))))
816 "gnus-sync-save: stored variables %s and %d groups in %s"
817 gnus-sync-global-vars
818 (length gnus-sync-newsrc-loader)
821 ;; Idea from Dan Christensen <jdc@chow.mat.jhu.edu>
822 ;; Save the .eld file with extra line breaks.
823 (gnus-message 8 "gnus-sync-save: adding whitespace to %s"
826 (goto-char (point-min))
827 (while (re-search-forward "^(\\|(\\\"" nil t)
828 (replace-match "\n\\&" t))
829 (goto-char (point-min))
830 (while (re-search-forward " $" nil t)
831 (replace-match "" t t))))))))
832 ;; the pass-through case: gnus-sync-backend is not a known choice
835 (defun gnus-sync-read (&optional subscribe-all)
836 "Load the Gnus sync data from the backend.
837 With a prefix, SUBSCRIBE-ALL is set and unknown groups will be subscribed."
839 (when gnus-sync-backend
840 (gnus-message 7 "gnus-sync-read: loading from backend %s" gnus-sync-backend)
842 ((and (listp gnus-sync-backend)
843 (eq (nth 0 gnus-sync-backend) 'lesync)
844 (stringp (nth 1 gnus-sync-backend)))
847 (mapc (lambda (entry)
848 (setq name (cdr (assq 'id entry)))
849 ;; set ftime the FIRST time through this loop, that
850 ;; way it reflects the time we FINISHED reading
851 (unless ftime (setq ftime (float-time)))
856 (gnus-sync-lesync-read-group-entry
857 (nth 1 gnus-sync-backend)
859 (cdr (assq 'value entry))
861 `(subscribe-all ,subscribe-all)))
862 (gnus-sync-lesync-install-group-entry
863 (cdr (assq 'id entry)))))))
864 (gnus-sync-lesync-groups-builder (nth 1 gnus-sync-backend)))))
866 ((stringp gnus-sync-backend)
868 (if (or debug-on-error debug-on-quit)
869 (load gnus-sync-backend nil t)
871 (load gnus-sync-backend nil t)
873 (error "Error in %s: %s" gnus-sync-backend (cadr var)))))
874 (let ((valid-count 0)
876 (dolist (node gnus-sync-newsrc-loader)
877 (if (gnus-gethash (car node) gnus-newsrc-hashtb)
880 (loop for store in (cdr node)
881 do (setf (nth (car store)
882 (assoc (car node) gnus-newsrc-alist))
884 (push (car node) invalid-groups)))
887 "gnus-sync-read: loaded %d groups (out of %d) from %s"
888 valid-count (length gnus-sync-newsrc-loader)
893 "gnus-sync-read: skipped %d groups (out of %d) from %s"
894 (length invalid-groups)
895 (length gnus-sync-newsrc-loader)
897 (gnus-message 9 "gnus-sync-read: skipped groups: %s"
898 (mapconcat 'identity invalid-groups ", ")))))
901 (gnus-message 9 "gnus-sync-read: remaking the newsrc hashtable")
902 (gnus-make-hashtable-from-newsrc-alist)))
905 (defun gnus-sync-initialize ()
906 "Initialize the Gnus sync facility."
908 (gnus-message 5 "Initializing the sync facility")
909 (gnus-sync-install-hooks))
912 (defun gnus-sync-install-hooks ()
913 "Install the sync hooks."
915 ;; (add-hook 'gnus-get-new-news-hook 'gnus-sync-read)
916 ;; (add-hook 'gnus-read-newsrc-el-hook 'gnus-sync-read)
917 (add-hook 'gnus-save-newsrc-hook 'gnus-sync-save))
919 (defun gnus-sync-unload-hook ()
920 "Uninstall the sync hooks."
922 (remove-hook 'gnus-save-newsrc-hook 'gnus-sync-save))
924 (add-hook 'gnus-sync-unload-hook 'gnus-sync-unload-hook)
926 (when gnus-sync-backend (gnus-sync-initialize))
930 ;;; gnus-sync.el ends here