gnus-sync.el 35 KB

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