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