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