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