-
Notifications
You must be signed in to change notification settings - Fork 0
/
nnhackernews.el
2054 lines (1862 loc) · 87.3 KB
/
nnhackernews.el
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
;;; nnhackernews.el --- Gnus backend for Hacker News -*- lexical-binding: t; coding: utf-8 -*-
;; Copyright (C) 2019 The Authors of nnhackernews.el
;; Authors: dickmao <github id: dickmao>
;; Version: 0.1.0
;; Keywords: news
;; URL: https://github.com/dickmao/nnhackernews
;; Package-Requires: ((emacs "25.2") (request "0.3.3") (dash "2.18.1") (anaphora "1.0.4"))
;; This file is NOT part of GNU Emacs.
;; This program is free software: you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation, either version 3 of the License, or
;; (at your option) any later version.
;; This program is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;; GNU General Public License for more details.
;; You should have received a copy of the GNU General Public License
;; along with nnhackernews.el. If not, see <https://www.gnu.org/licenses/>.
;;; Commentary:
;; A Gnus backend for Hacker News.
;;; Code:
(eval-when-compile (require 'cl-lib)
(cl-assert (fboundp 'libxml-parse-html-region) nil
"nnhackernews requires emacs built with libxml support"))
(require 'nnoo)
(require 'gnus)
(require 'gnus-start)
(require 'gnus-art)
(require 'gnus-sum)
(require 'gnus-msg)
(require 'gnus-cite)
(require 'gnus-srvr)
(require 'gnus-cache)
(require 'gnus-bcklg)
(require 'gnus-score)
(require 'mm-url)
(require 'cl-lib)
(require 'json)
(require 'subr-x)
(require 'request)
(require 'dash)
(require 'anaphora)
(require 'url-http)
(nnoo-declare nnhackernews)
(defconst nnhackernews-hacker-news-url "https://news.ycombinator.com")
(defconst nnhackernews--group-ask "ask")
(defconst nnhackernews--group-show "show")
(defconst nnhackernews--group-job "job")
(defconst nnhackernews--group-stories "news")
(defgroup nnhackernews nil "A Gnus backend for Hacker News."
:group 'gnus)
(defcustom nnhackernews-render-story t
"If non-nil, follow link upon `gnus-summary-select-article'.
Otherwise, just display link."
:type 'boolean
:group 'nnhackernews)
(defcustom nnhackernews-localhost "127.0.0.1"
"Some users keep their browser in a separate domain.
Do not set this to \"localhost\" as a numeric IP is required for the oauth
handshake."
:type 'string
:group 'nnhackernews)
(defcustom nnhackernews-purge-threshold 30000
"When number of headers exceeds this, call `nnhackernews-purge'."
:type 'integer
:group 'nnhackernews)
(defcustom nnhackernews-max-items-per-scan 100
"Maximum items to fetch from firebase each refresh cycle."
:type 'integer
:group 'nnhackernews)
(defcustom nnhackernews-refractory-ms 2200
"In June 2021, hackernews started throttling responses."
:type 'integer
:group 'nnhackernews)
(defcustom nnhackernews-max-render-bytes 300e3
"`quoted-printable-encode-region' bogs when javascript spyware overdoes it."
:type 'integer
:group 'nnhackernews)
(defvoo nnhackernews-status-string "")
(defvar nnhackernews-avoid-rescoring nil
"This semaphore avoids unnecessary scoring.
The unnecessary run results from `nndraft-update-unread-articles'
calling `gnus-group-get-new-news-this-group'.")
(defvar nnhackernews--mutex-display-article
(when (fboundp 'make-mutex)
(make-mutex "nnhackernews--mutex-display-article"))
"Scoring in `gnus-after-getting-new-news-hook' emits 'Selecting deleted buffer'.")
(defvar nnhackernews--last-item nil "Keep track of where we are.")
(defvar nnhackernews--debug-request-items nil "Keep track of ids to re-request for testing.")
(defvar nnhackernews--last-scan-time (- (truncate (float-time)) 100)
"Don't scan more than once every few seconds.")
(defmacro nnhackernews--callback (result &optional callback)
"Set RESULT to return value of CALLBACK."
`(cl-function (lambda (&rest args &key data &allow-other-keys)
(setq ,result (if ,callback
(apply ,callback args)
data)))))
(defun nnhackernews-alist-get (key alist &optional default remove testfn)
"Replicated library function for emacs-25.
Same argument meanings for KEY ALIST DEFAULT REMOVE and TESTFN."
(ignore remove)
(let ((x (if (not testfn)
(assq key alist)
(assoc key alist))))
(if x (cdr x) default)))
(gv-define-expander nnhackernews-alist-get
(lambda (do key alist &optional default remove testfn)
(macroexp-let2 macroexp-copyable-p k key
(gv-letplace (getter setter) alist
(macroexp-let2 nil p `(if (and ,testfn (not (eq ,testfn 'eq)))
(assoc ,k ,getter)
(assq ,k ,getter))
(funcall do (if (null default) `(cdr ,p)
`(if ,p (cdr ,p) ,default))
(lambda (v)
(macroexp-let2 nil v v
(let ((set-exp
`(if ,p (setcdr ,p ,v)
,(funcall setter
`(cons (setq ,p (cons ,k ,v))
,getter)))))
`(progn
,(cond
((null remove) set-exp)
((or (eql v default)
(and (eq (car-safe v) 'quote)
(eq (car-safe default) 'quote)
(eql (cadr v) (cadr default))))
`(if ,p ,(funcall setter `(delq ,p ,getter))))
(t
`(cond
((not (eql ,default ,v)) ,set-exp)
(,p ,(funcall setter
`(delq ,p ,getter))))))
,v))))))))))
(defsubst nnhackernews--gethash (string hashtable &optional dflt)
"Get corresponding value of STRING from HASHTABLE, or DFLT if undefined.
Starting in emacs-src commit c1b63af, Gnus moved from obarrays to
normal hashtables."
(if (fboundp 'gnus-gethash)
(let ((sym (intern-soft string hashtable)))
(if (or (null sym) (not (boundp sym))) dflt (symbol-value sym)))
(gethash string hashtable dflt)))
(defsubst nnhackernews--replace-hash (string func hashtable)
"Set value of STRING to FUNC applied to existing STRING value in HASHTABLE.
Starting in emacs-src commit c1b63af, Gnus moved from obarrays to
normal hashtables."
(let* ((capture (nnhackernews--gethash string hashtable))
(replace-with (funcall func capture)))
(if (fboundp 'gnus-sethash)
(set (intern string hashtable) replace-with)
(puthash string replace-with hashtable))))
(defmacro nnhackernews--remhash (string hashtable)
"Remove STRING from HASHTABLE.
Starting in emacs-src commit c1b63af, Gnus moved from obarrays to
normal hashtables."
`(,(if (fboundp 'gnus-sethash)
'unintern
'remhash)
,(if (fboundp 'gnus-sethash)
(cons 'intern (list string hashtable))
string)
,hashtable))
(defmacro nnhackernews--sethash (string value hashtable)
"Set corresponding value of STRING to VALUE in HASHTABLE.
Starting in emacs-src commit c1b63af, Gnus moved from obarrays to
normal hashtables."
`(,(if (fboundp 'gnus-sethash)
'gnus-sethash
'puthash)
,string ,value ,hashtable))
(defmacro nnhackernews--maphash (func table)
"Map FUNC taking key and value over TABLE, return nil.
Starting in emacs-src commit c1b63af, Gnus moved from obarrays to
normal hashtables."
(declare (indent nil))
`(,(if (fboundp 'gnus-gethash-safe)
'mapatoms
'maphash)
,(if (fboundp 'gnus-gethash-safe)
`(lambda (k) (funcall
(apply-partially
,func
(symbol-name k) (funcall (function gnus-gethash-safe) k ,table))))
func)
,table))
(defvar nnhackernews-summary-voting-map
(let ((map (make-sparse-keymap)))
map)
"Voting map.")
(defvar nnhackernews-summary-mode-map
(let ((map (make-sparse-keymap)))
(define-key map "r" #'gnus-summary-followup)
(define-prefix-command 'nnhackernews-summary-voting-map)
(define-key map "R" 'nnhackernews-summary-voting-map)
(define-key nnhackernews-summary-voting-map "0" #'nnhackernews-novote)
(define-key nnhackernews-summary-voting-map "-" #'nnhackernews-downvote)
(define-key nnhackernews-summary-voting-map "=" #'nnhackernews-upvote)
(define-key nnhackernews-summary-voting-map "+" #'nnhackernews-upvote)
map))
(defvar nnhackernews-article-mode-map
(copy-keymap nnhackernews-summary-mode-map)) ;; how does Gnus do this?
(define-minor-mode nnhackernews-article-mode
"Disallow `gnus-article-reply-with-original'.
\\{gnus-article-mode-map}"
:lighter " HN"
:keymap nnhackernews-article-mode-map)
(define-minor-mode nnhackernews-summary-mode
"Disallow \"reply\" commands in `gnus-summary-mode-map'.
\\{nnhackernews-summary-mode-map}"
:lighter " HN"
:keymap nnhackernews-summary-mode-map)
(defsubst nnhackernews-novote ()
"Retract vote."
(interactive)
(nnhackernews-vote-current-article 0))
(defsubst nnhackernews-downvote ()
"Downvote the article in current buffer."
(interactive)
(nnhackernews-vote-current-article -1))
(defsubst nnhackernews-upvote ()
"Upvote the article in current buffer."
(interactive)
(nnhackernews-vote-current-article 1))
(defvar nnhackernews--seq-map-indexed
(if (fboundp 'seq-map-indexed)
#'seq-map-indexed
(lambda (function sequence)
(let ((index 0))
(seq-map (lambda (elt)
(prog1
(funcall function elt index)
(setq index (1+ index))))
sequence)))))
(defmacro nnhackernews--normalize-server ()
"Disallow \"server\" from being empty string, which is unsettling.
Normalize it to \"nnhackernews-default\"."
`(let ((canonical "nnhackernews-default"))
(when (equal server "")
(setq server nil))
(unless server
(setq server canonical))
(unless (string= server canonical)
(error "`nnhackernews--normalize-server': multiple servers unsupported!"))))
(defvar nnhackernews-score-files nil "For `nnhackernews--ensure-score-file'.")
(defvar nnhackernews-location-hashtb (gnus-make-hashtable)
"Id -> ( group . index ).")
(defvar nnhackernews-root-hashtb (gnus-make-hashtable)
"Id -> possibly ancient header.")
(defvar nnhackernews-headers-alist nil
"Group -> headers. This is an alist. Hashtable mysteriously slow.")
(defvar nnhackernews-refs-hashtb (gnus-make-hashtable)
"Who replied to whom (global over all entries).")
(defvar nnhackernews-authors-hashtb (gnus-make-hashtable)
"For fast lookup of parent-author (global over all entries).")
(defun nnhackernews-get-headers (group)
"List headers from GROUP."
(cl-second (assoc group nnhackernews-headers-alist)))
(defun nnhackernews-find-header (id &optional noquery)
"Retrieve property list of ID.
If NOQUERY, return nil and avoid querying if not extant."
(if-let ((location (nnhackernews--gethash id nnhackernews-location-hashtb)))
(cl-destructuring-bind (group . index) location
(nnhackernews--get-header (1+ index) group))
(unless noquery
(nnhackernews--request-item id))))
(defun nnhackernews-refs-for (id)
"Return ancestors sorted oldest to youngest as list for ID."
(cl-loop with get-root-plst = #'ignore
for prev-id = id then cur-id
for cur-id =
(let ((cached (nnhackernews--gethash prev-id
nnhackernews-refs-hashtb
'NULL)))
(if (eq cached 'NULL)
(let ((plst (nnhackernews--request-item prev-id)))
(nnhackernews-add-entry nnhackernews-refs-hashtb
plst :parent)
(setq get-root-plst (lambda () plst))
(plist-get plst :parent))
(setq get-root-plst (apply-partially #'nnhackernews-find-header prev-id t))
cached))
until (null cur-id)
collect cur-id into rresult
finally return
(let ((result (nreverse rresult))
(root-plst (funcall get-root-plst)))
(when (and result
(string= (plist-get root-plst :id) (car result)))
(nnhackernews--sethash (car result) root-plst
nnhackernews-root-hashtb))
result)))
(defun nnhackernews--retrieve-root (header)
"Retrieve and cache property list HEADER root."
(if-let ((root-id (car (nnhackernews-refs-for (plist-get header :id)))))
(nnhackernews--gethash root-id nnhackernews-root-hashtb)
header))
(defun nnhackernews--group-for (header)
"Classify HEADER as one of ask, show, or news based on title."
(let* ((root-plst (nnhackernews--retrieve-root header))
(title (or (plist-get header :link_title) ""))
(type (or (plist-get root-plst :type) "")))
;; string-match-p like all elisp searching is case-insensitive
(cond ((string= type "job") nnhackernews--group-job)
((string-match-p "^\\(Launch\\|Show\\) HN" title) nnhackernews--group-show)
((string-match-p "^\\(Ask\\|Tell\\) HN" title) nnhackernews--group-ask)
(t nnhackernews--group-stories))))
(defsubst nnhackernews--get-user-cookie ()
"Extract Hacker News login from cookies."
(let* ((site (url-host (url-generic-parse-url nnhackernews-hacker-news-url))))
(cdr (assoc-string
"user"
(cl-loop with result
for securep in '(t nil)
do (setq result
(request-cookie-alist site "/" securep))
until result
finally return result)))))
(defun nnhackernews--domify (html)
"Parse HTML into dom."
(with-temp-buffer
(insert html)
(if (fboundp 'libxml-parse-html-region)
(libxml-parse-html-region (point-min) (point-max))
(error "`nnhackernews--domify': need libxml-parse-html-region"))))
(cl-defun nnhackernews--request-login-success (&key data &allow-other-keys)
"Validate login depending on what DATA say.
After some time, logging in via browser recaptcha might be
necessary. Remember `string-match-p' is always case-insensitive
as is all elisp pattern matching."
(when (and (stringp data)
(string-match-p (regexp-quote "validation required") data))
(display-warning
'nnhackernews
(concat "Recaptcha required. Please login via browser and try again."))
(error "Recaptcha required"))
data)
(defun nnhackernews--request-login (url &optional hidden)
"Store a cookie from URL with HIDDEN plist."
(let* (result
(auth-source-do-cache nil)
(auth-source-save-behavior 'ask)
(auth-source-creation-prompts '((user . "news.ycombinator.com user: ")
(secret . "Password for %u: ")))
(found (car (auth-source-search :max 1 :host "news.ycombinator.com" :require
'(:user :secret) :create t))))
(nnhackernews--request
"nnhackernews--request-login"
url
:backend 'curl
:data (append
(cl-loop for (k v) on hidden by (function cddr)
collect (cons (cl-subseq (symbol-name k) 1) v))
`(("acct" . ,(plist-get found :user))
("pw" . ,(let ((secret (plist-get found :secret)))
(if (functionp secret)
(funcall secret)
secret)))))
:success (nnhackernews--callback result #'nnhackernews--request-login-success))
result))
(defmacro nnhackernews--extract-hidden (dom hidden)
"Extract hidden tag-value pairs from DOM into plist HIDDEN."
`(-tree-map-nodes
(lambda (x)
(and (listp x)
(eq (car x) 'input)
(string= "hidden" (alist-get 'type (cl-second x)))
(not (string= "creating" (alist-get 'name (cl-second x))))))
(lambda (x)
(let ((keyname (intern (concat ":" (alist-get 'name (cl-second x))))))
(unless (plist-get ,hidden keyname)
(!cons (alist-get 'value (cl-second x)) ,hidden)
(!cons keyname ,hidden))))
,dom))
(cl-defun nnhackernews--request-hidden-success (&key data response &allow-other-keys)
"Based on DATA and RESPONSE, we may need to login first. Return :fnid and :fnop."
(let* ((dom (nnhackernews--domify data))
(form (car (alist-get 'form (alist-get 'body dom))))
(url (request-response-url response))
(path (car (url-path-and-query (url-generic-parse-url url))))
(login-p (aif (alist-get 'action form) (cl-search it path)))
hidden)
(nnhackernews--extract-hidden dom hidden)
(when login-p
(setq dom (nnhackernews--domify (nnhackernews--request-login url hidden)))
(nnhackernews--extract-hidden dom hidden))
hidden))
(defun nnhackernews--request-hidden (url)
"Get the hidden fields (e.g., FNID, FNOP, HMAC) from URL."
(let (result)
(nnhackernews--request
"nnhackernews--request-hidden"
url
:backend 'curl
:success (nnhackernews--callback result #'nnhackernews--request-hidden-success))
result))
(defsubst nnhackernews--who-am-i ()
"Get my Hacker News username."
(let ((user-cookie (nnhackernews--get-user-cookie)))
(unless user-cookie
(nnhackernews--request-login (format "%s/login" nnhackernews-hacker-news-url))
(setq user-cookie (nnhackernews--get-user-cookie)))
(if (stringp user-cookie)
(car (split-string user-cookie "&"))
(gnus-message 3 "nnhackernews--who-am-i: failed to get user-cookie")
"error")))
(defsubst nnhackernews--append-header (plst &optional group)
"Update data structures for PLST \"header\".
If GROUP classification omitted, figure it out."
(let ((id (plist-get plst :id))
(group (or group (nnhackernews--group-for plst))))
(nnhackernews--sethash id
(cons group (length (nnhackernews-get-headers group)))
nnhackernews-location-hashtb)
(setf (nnhackernews-alist-get group nnhackernews-headers-alist nil nil #'equal)
(list (nconc (nnhackernews-get-headers group) (list plst))))
plst))
(nnoo-define-basics nnhackernews)
(defun nnhackernews-vote-current-article (vote)
"VOTE is +1, -1, 0."
(unless gnus-newsgroup-name (error "No current newgroup"))
(if-let ((article-number (or (with-current-buffer gnus-article-buffer
(cdr gnus-article-current))
(with-current-buffer gnus-summary-buffer
(gnus-summary-article-number)))))
(let* ((header (nnhackernews--get-header
article-number
(gnus-group-real-name gnus-newsgroup-name)))
(orig-score (format "%s" (plist-get header :score)))
(new-score (if (zerop vote) orig-score
(concat orig-score " "
(if (> vote 0) "+" "")
(format "%s" vote)))))
(save-excursion
(save-window-excursion
(with-current-buffer gnus-summary-buffer
(if (eq (gnus-summary-article-number) (cdr gnus-article-current))
(if (nnhackernews--request-vote (plist-get header :id) vote)
(with-current-buffer gnus-article-buffer
(let ((inhibit-read-only t))
(nnheader-replace-header "Score" new-score)))
(gnus-message 5 "nnhackernews-vote-current-article: failed for %s"
(plist-get header :id)))
(message "Open the article before voting."))))))
(error "No current article")))
(defsubst nnhackernews--gate (&optional group)
"Apply our minor modes only when the following conditions hold for GROUP."
(unless group
(setq group gnus-newsgroup-name))
(and (stringp group)
(listp (gnus-group-method group))
(eq 'nnhackernews (car (gnus-group-method group)))))
(defsubst nnhackernews--message-gate ()
"In `message-mode', `gnus-newsgroup-name' could be anything."
(nnhackernews--gate (car-safe gnus-message-group-art)))
(deffoo nnhackernews-request-close ()
(nnhackernews-close-server)
t)
(deffoo nnhackernews-request-type (_group &optional _article)
'news)
(deffoo nnhackernews-server-opened (&optional server)
(nnhackernews--normalize-server)
nnhackernews--last-item)
(deffoo nnhackernews-status-message (&optional server)
(nnhackernews--normalize-server)
"")
(deffoo nnhackernews-open-server (_server &optional _defs)
t)
(deffoo nnhackernews-close-group (_group &optional server)
(nnhackernews--normalize-server)
t)
(defmacro nnhackernews--with-group (group &rest body)
"Disambiguate GROUP if it's empty and execute BODY."
(declare (debug (form &rest form))
(indent defun))
`(let* ((group (or ,group (gnus-group-real-name gnus-newsgroup-name)))
(gnus-newsgroup-name (gnus-group-full-name group "nnhackernews:")))
,@body))
(defun nnhackernews--get-header (article-number &optional group)
"Get header indexed ARTICLE-NUMBER for GROUP."
(nnhackernews--with-group group
(elt (nnhackernews-get-headers group) (1- article-number))))
(defun nnhackernews--get-body (header &optional server)
"Get full text of submission or comment HEADER at SERVER."
(nnhackernews--normalize-server)
(if-let ((url (plist-get header :url)))
(format "<div><p><a href=\"%s\">%s</a></div>" url url)
(or (plist-get header :text)
(plist-get (nnhackernews--request-item (plist-get header :id)) :text)
"")))
(defun nnhackernews--massage (body)
"Precede each quoted line of BODY broken by `shr-fill-line' with '>'."
(with-temp-buffer
(insert body)
(mm-url-decode-entities)
(cl-loop initially (goto-char (point-min))
until (and (null (re-search-forward "\\(^>\\( .*?\\)\\)<p>" nil t))
(null (re-search-forward "\\(<p>\\s-*>\\( .*?\\)\\)<p>" nil t)))
do (let* ((start (match-beginning 1))
(end (match-end 1))
(matched (match-string 2)))
(perform-replace
".*"
(concat "<p>\n"
(with-temp-buffer
(insert matched)
(fill-region (point-min) (point-max))
(insert
(prog1
(cl-subseq (replace-regexp-in-string
"\n" "<br>\n> " (concat "\n" (buffer-string)))
5)
(erase-buffer)))
(buffer-string))
"\n")
nil t nil nil nil start end)))
(buffer-string)))
(defsubst nnhackernews--citation-wrap (author body)
"Cite AUTHOR using `gnus-message-cite-prefix-regexp' before displaying BODY.
Originally written by Paul Issartel."
(with-temp-buffer
(insert body)
(mm-url-remove-markup)
(mm-url-decode-entities)
(fill-region (point-min) (point-max))
(let* ((trimmed-1 (replace-regexp-in-string "\\(\\s-\\|\n\\)+$" "" (buffer-string)))
(trimmed (replace-regexp-in-string "^\\(\\s-\\|\n\\)+" "" trimmed-1)))
(concat author " wrote:<p>\n"
"<pre>\n"
(cl-subseq (replace-regexp-in-string "\n" "\n> " (concat "\n" trimmed)) 1)
"\n</pre><p>"))))
(defun nnhackernews-add-entry (hashtb e field)
"Add to HASHTB the pair consisting of entry E's name to its FIELD."
(nnhackernews--sethash (plist-get e :id) (plist-get e field) hashtb))
(defun nnhackernews--summary-exit (group)
"Call `gnus-summary-exit' for GROUP without the rescoring mess."
(remove-function (symbol-function 'gnus-summary-exit)
(symbol-function 'nnhackernews--score-pending))
(unwind-protect
(let ((summary-buffer-name (gnus-summary-buffer-name group)))
(with-current-buffer summary-buffer-name
(gnus-summary-exit t t)
(gnus-kill-buffer gnus-article-buffer)
(gnus-kill-buffer gnus-original-article-buffer))
(gnus-kill-buffer (get-buffer summary-buffer-name)))
(add-function :after (symbol-function 'gnus-summary-exit)
(symbol-function 'nnhackernews--score-pending))))
(defsubst nnhackernews--ensure-score-files (group)
"File I/O remains a perennial problem for score files for GROUP."
(if-let ((files (alist-get (intern group) nnhackernews-score-files)))
(condition-case nil
(progn
(dolist (file files t)
(gnus-score-load-score-alist file)))
(error nil))
t))
(defmacro nnhackernews--with-mutex (mtx &rest body)
"If capable of threading, lock with MTX and execute BODY."
(declare (indent 1))
(if (fboundp 'with-mutex)
`(with-mutex ,mtx ,@body)
`(progn ,@body)))
(defun nnhackernews--daring-scoring (group)
"Dare to score GROUP without the benefit of `gnus-summary-read-group'."
(with-temp-buffer
;; Withhold judgment of setqs, mimicking `gnus-summary-setup-buffer'
(setq gnus-newsgroup-name group) ;; now defvar-local, right?
(set-default 'gnus-newsgroup-name gnus-newsgroup-name)
(gnus-summary-mode)
(gnus-update-format-specifications 'summary 'summary-mode 'summary-dummy)
(gnus-update-summary-mark-positions)
(gnus-summary-set-local-parameters gnus-newsgroup-name)
(let ((gnus-single-article-buffer t))
;; employ a hack that messes with *Article*, not an article I'm reading
(gnus-select-newsgroup group nil nil))
;; Save the active value in effect when the group was entered.
(setq gnus-newsgroup-active
(copy-tree (gnus-active gnus-newsgroup-name)))
(setq gnus-newsgroup-highest (cdr gnus-newsgroup-active))
(gnus-run-hooks 'gnus-select-group-hook)
(gnus-possibly-score-headers)
(gnus-summary-prepare) ;; this actually updates unreads... can't blame a 20yo
(gnus-run-hooks 'gnus-apply-kill-hook)
(setq gnus-newsgroup-prepared t)
(gnus-run-hooks 'gnus-summary-prepared-hook)
(gnus-group-update-group group nil t)
(gnus-score-adaptive)
(gnus-score-save)
(gnus-run-hooks 'gnus-exit-group-hook)
(gnus-summary-update-info)
(gnus-run-hooks 'gnus-summary-prepare-exit-hook)
(gnus-close-group group)
(gnus-run-hooks 'gnus-summary-exit-hook)
(when (equal gnus-article-buffer (default-value 'gnus-article-buffer))
;; can't be killing an article I was reading!
(gnus-kill-buffer gnus-article-buffer)
(gnus-kill-buffer gnus-original-article-buffer))))
(defun nnhackernews--rescore (group force)
"Unforced rescore of GROUP when merely `gnus-summary-exit'.
FORCE in wake of `gnus-after-getting-new-news-hook'."
(when (nnhackernews--gate group)
(cl-loop repeat 5
for ensured = (nnhackernews--ensure-score-files group)
until ensured
do (sleep-for 0 300)
finally (unless ensured
(gnus-message 2 "nnhackernews--rescore: Bad score files %s!"
(alist-get (intern group)
nnhackernews-score-files))))
(let* ((num-headers (length (nnhackernews-get-headers
(gnus-group-real-name group))))
(marks (gnus-info-marks (gnus-get-info group)))
(seen (or (cdr-safe (--max-by (> (or (cdr-safe it) 0) (or (cdr-safe other) 0))
(alist-get 'seen marks)))
0)))
(unless (zerop seen)
(when (or force (> num-headers seen))
(save-window-excursion
(let (gnus-auto-select-subject
gnus-summary-next-group-on-exit
(unread (length (gnus-list-of-unread-articles group)))
(gnus-large-newsgroup 10000))
(if (zerop unread)
(gnus-message 7 "nnhackernews--rescore: skipping %s no unread"
group)
;; Q: Why `gnus-summary-read-group'?
;; A: `gnus-score-headers' message-clone-locals `gnus-summary-buffer'
;; Problem: Fights with main thread UI since it calls
;; `gnus-configure-windows',
(nnhackernews--with-mutex nnhackernews--mutex-display-article
(if (> (gnus-continuum-version) 5.13)
(nnhackernews--daring-scoring group)
(gnus-summary-read-group group nil t)
(nnhackernews--summary-exit group)))))))))))
(defalias 'nnhackernews--score-pending
(lambda (&rest _args)
(awhen (gnus-group-name-at-point)
(nnhackernews--rescore it nil))))
(defun nnhackernews-extant-summary-buffer (group)
"Return main thread's summary buffer for GROUP if extant."
(let* ((args (when (and (boundp 'gnus-threaded-get-unread-articles)
gnus-threaded-get-unread-articles)
'(t)))
(name (apply #'gnus-summary-buffer-name group args)))
(gnus-buffer-live-p name)))
(defun nnhackernews--score-unread (group)
"Filter unread messages for GROUP now.
Otherwise *Group* buffer annoyingly overrepresents unread."
(when (or (gnus-native-method-p '(nnhackernews ""))
(gnus-secondary-method-p '(nnhackernews "")))
(nnhackernews--with-group group
(when (and (not (nnhackernews-extant-summary-buffer gnus-newsgroup-name))
(not nnhackernews-avoid-rescoring))
(nnhackernews--rescore gnus-newsgroup-name t)))))
(defun nnhackernews--mark-scored-as-read (group)
"Reflect the scoring results now.
If root article (story) is scored in GROUP, that means we've already
read it. This function seems redundant with `nnhackernews--score-unread'
but might be faster on startup? See 15195cc."
(nnhackernews--with-group group
(let ((preface (format "nnhackernews--mark-scored-as-read: %s not rescoring " group))
(extant (nnhackernews-extant-summary-buffer gnus-newsgroup-name))
(unread (gnus-group-unread gnus-newsgroup-name)))
(cond ((or (not (numberp unread)) (<= unread 0))
(gnus-message 7 (concat preface "(unread %s)") unread))
((and extant (buffer-local-value 'gnus-newsgroup-prepared extant))
;; reflect the extant logic in `gnus-summary-setup-buffer'
(gnus-message 7 (concat preface "(extant %s)") (buffer-name extant)))
(t
(save-excursion
(let (gnus-auto-select-subject
(gnus-large-newsgroup 10000))
(gnus-summary-read-group gnus-newsgroup-name nil t)
(with-current-buffer (gnus-summary-buffer-name gnus-newsgroup-name)
(dolist (datum gnus-newsgroup-data)
(-when-let* ((article (gnus-data-number datum))
(plst (nnhackernews--get-header article))
(scored-story-p (and (plist-get plst :title)
(> (gnus-summary-article-score article) 0))))
(gnus-message 7 "nnhackernews--mark-scored-as-read: %s (%s %s)"
(plist-get plst :title) group article)
(gnus-summary-mark-as-read article))))
(nnhackernews--summary-exit gnus-newsgroup-name))))))))
(deffoo nnhackernews-request-group-scan (group &optional server info)
"\\[gnus-group-get-new-news-this-group] calls this."
(nnhackernews--normalize-server)
(nnhackernews--with-group group
(gnus-message 5 "nnhackernews-request-group-scan: scanning %s..." group)
(gnus-activate-group gnus-newsgroup-name t)
(gnus-get-unread-articles-in-group
(or info (gnus-get-info gnus-newsgroup-name))
(gnus-active (gnus-info-group info)))
(gnus-message 5 "nnhackernews-request-group-scan: scanning %s...done" group)
(nnhackernews--score-unread group))
t)
(defun nnhackernews--checksum ()
"Ensure header tallies agree.
The two hashtables being reconciled are `nnhackernews-location-hashtb' and
`nnhackernews-headers-alist'."
(let ((counts (gnus-make-hashtable)))
(nnhackernews--maphash
(lambda (_id group-index)
(nnhackernews--replace-hash (car group-index) (lambda (v) (1+ (or v 0)))
counts))
nnhackernews-location-hashtb)
(mapc
(lambda (pair)
(cl-destructuring-bind (group headers) pair
(cl-assert (= (nnhackernews--gethash group counts 0)
(length headers))
nil
"nnhackernews--checksum: %s, %s != %s"
group (nnhackernews--gethash group counts 0)
(length headers))))
nnhackernews-headers-alist)
(let (result)
(nnhackernews--maphash
(lambda (group count)
(push (cons group count) result))
counts)
result)))
;; gnus-group-select-group
;; gnus-group-read-group
;; gnus-summary-read-group
;; gnus-summary-read-group-1
;; gnus-summary-setup-buffer
;; sets gnus-newsgroup-name
;; gnus-select-newsgroup
;; gnus-request-group
;; nnhackernews-request-group
(deffoo nnhackernews-request-group (group &optional server _fast info)
(nnhackernews--normalize-server)
(nnhackernews--with-group group
(let* ((info (or info (gnus-get-info gnus-newsgroup-name)))
(headers (nnhackernews-get-headers group))
(first-header (1+ (or (-find-index #'identity headers) 0)))
(last-header (length headers))
(num-headers (if (> first-header last-header) 0
(1+ (- last-header first-header))))
(status (format "211 %d %d %d %s"
num-headers first-header last-header group)))
(gnus-message 7 "nnhackernews-request-group: %s" status)
(nnheader-insert "%s\n" status)
(when info
(gnus-info-set-marks
info
(append (assq-delete-all 'seen (gnus-info-marks info))
(list `(seen (1 . ,num-headers))))
t)
(gnus-info-set-method info (gnus-group-method gnus-newsgroup-name) t)
(gnus-set-info gnus-newsgroup-name info)))
t))
(defsubst nnhackernews--json-read ()
"Copied from ein:json-read() by tkf."
(goto-char (point-max))
(backward-sexp)
(let ((json-object-type 'plist)
(json-array-type 'list))
(json-read)))
(defun nnhackernews--request-max-item ()
"Retrieve the max-item from which all read-unread accounting stems."
(let (max-item)
(nnhackernews--request
"nnhackernews--request-max-item"
"https://hacker-news.firebaseio.com/v0/maxitem.json"
:parser 'nnhackernews--json-read
:success (nnhackernews--callback max-item))
max-item))
(defun nnhackernews--request-newstories ()
"Return list of id's which we know to be stories (as opposed to comments)."
(let (stories)
(nnhackernews--request
"nnhackernews--request-newstories"
"https://hacker-news.firebaseio.com/v0/newstories.json"
:success (nnhackernews--callback
stories
(cl-function
(lambda (&key data &allow-other-keys)
;; manual recommended listify appends nil
(append
(eval (car (read-from-string (subst-char-in-string ?, ?\ data))))
nil)))))
stories))
(cl-defun nnhackernews--request (caller url
&rest attributes
&key parser (backend 'url-retrieve) (timeout 10)
&allow-other-keys)
"Prefix errors with CALLER executing synchronous request to URL.
Request shall contain ATTRIBUTES, one of which is PARSER of the
response, if provided (shall default to verbatim dump of
response, if not). BACKEND can be curl (defaults to
`url-retrieve'). TIMEOUT is seconds, default 10."
(unless parser
(setq attributes (append attributes (list :parser #'buffer-string))))
(setq attributes
(cl-loop for (k v) on attributes by (function cddr)
unless (eq k :backend)
collect k and collect v))
(let ((request-backend backend))
(apply #'request url
:sync t
:timeout timeout
:error (apply-partially #'nnhackernews--request-error caller)
attributes)))
(cl-defun nnhackernews--request-vote-success (item vote &key data &allow-other-keys)
"If necessary, login first.
Then locate ITEM VOTE link in DATA (will depend on VOTE sign)."
(let* ((dom (nnhackernews--domify data))
(before (format "%s_%s" (if (> vote 0) "up" "un") item))
(after (format "%s_%s" (if (<= vote 0) "up" "un") item))
before-found result)
(-tree-map-nodes
(lambda (x)
(and (listp x)
(eq (car x) 'a)
(let ((id (alist-get 'id (cl-second x))))
(or (string= before id) (string= after id)))))
(lambda (x)
(let ((id (alist-get 'id (cl-second x)))
(href (alist-get 'href (cl-second x))))
(cond ((string= before id)
(setq before-found (concat (file-name-as-directory nnhackernews-hacker-news-url) href)))
((string= after id) (setq result t)))))
dom)
(when before-found
(nnhackernews--request
"nnhackernews--request-vote-success"
before-found
:backend 'curl
:success (nnhackernews--callback
result
(cl-function
(lambda (&key data response &allow-other-keys)
(let* ((dom (nnhackernews--domify data))
(form (alist-get 'form (alist-get 'body dom)))
(url (request-response-url response))
hidden)
(nnhackernews--extract-hidden dom hidden)
(when (string= "vote" (alist-get 'action (car form)))
(setq dom (nnhackernews--domify
(nnhackernews--request-login url hidden))))
(let (result0)
(-tree-map-nodes
(lambda (x)
(and (listp x)
(eq (car x) 'a)
(string= after (alist-get 'id (cl-second x)))))
(lambda (_x) (setq result0 t))
dom)
result0)))))))
result))
(defun nnhackernews--request-vote (item vote)
"Tally for ITEM the VOTE."
(let (result)
(nnhackernews--request
"nnhackernews--request-vote"
(format "%s/item?id=%s" nnhackernews-hacker-news-url item)
:backend 'curl
:success (nnhackernews--callback
result
(apply-partially #'nnhackernews--request-vote-success item vote)))
result))
(defsubst nnhackernews--enforce-curl ()
"Curl must exist."
(unless (executable-find "curl")
(error "`nnhackernews--enforce-curl': the 'curl' program was not found")))
(defun nnhackernews--request-reply (url text hidden)
"Reply URL with TEXT using HIDDEN credentials."
(nnhackernews--enforce-curl)
(let (result)
(nnhackernews--request
"nnhackernews--request-reply"
url
:backend 'curl
:data (append (cl-loop for (k v) on hidden by (function cddr)
collect (cons (cl-subseq (symbol-name k) 1) v))
`(("text" . ,text)))
:success (nnhackernews--callback result))
result))