rssparser.lisp

Check-in [f06c0d41c4]
Login

Check-in [f06c0d41c4]

Many hyperlinks are disabled.
Use anonymous login to enable hyperlinks.

Overview
Comment:Transferred from Bitbucket
Downloads: Tarball | ZIP archive | SQL archive
Timelines: family | ancestors | descendants | both | trunk
Files: files | file ages | folders
SHA3-256: f06c0d41c45e79499bfaa4d009fa3377164c7ebde64c0a034540fdc52a7b32f5
User & Date: Cthulhux 2019-11-17 00:42:03
Context
2020-04-22
07:55
Fixed README check-in: 1b6f35c75a user: Cthulhux tags: trunk
2019-11-17
00:42
Transferred from Bitbucket check-in: f06c0d41c4 user: Cthulhux tags: trunk
00:39
initial empty check-in check-in: 9895f32525 user: Cthulhux tags: trunk
Changes
Hide Diffs Unified Diffs Ignore Whitespace Patch

Added README.md.































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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
# rssparser.lisp

A Web-to-RSS parser in Common Lisp.

## What does it do?

This software was written because a disappointing number of websites still does not have an RSS or Atom feed so I could subscribe to their updates, e.g. the [KiTTY website](https://www.9bis.net/kitty/?action=news&zone=en). The script tries to find new *articles* on any website according to given criteria (CSS selectors) and parse them into a valid RSS feed so I can subscribe to them in my usual RSS feed reader.

## Screenshot

![Screenshot](http://i.imgur.com/fzkvW9H.png)

## Syntax

* *chmod +x rssparser.lisp*, then:
  * ./rssparser.lisp add *<Title> <URL> <EntrySelector> <TitleSelector> [<ContentSelector>]*
  * ./rssparser.lisp delete *<ID>*
  * ./rssparser.lisp list
  * ./rssparser.lisp export *<ID>*

***Run a simple web interface on port 5000:***

* ./rssparser.lisp webserver

***Cronjob or manual feed creation command:***

* ./rssparser.lisp parse

Supported *selectors* are all valid [CSS selectors](http://www.w3schools.com/cssref/css_selectors.asp). If you don't specify a `ContentSelector` when adding a new feed, `rssparser.lisp` will use an empty item body.

### Example

If you want to subscribe to the KiTTY website, you can either use the web interface or perform the following commands:

    % ./rssparser.lisp add "KiTTY" "https://www.9bis.net/kitty/?action=news&zone=en" ".news" "h1" ""
    Success!

    % ./rssparser.lisp parse

    % ./rssparser.lisp list
    1 feed is set up:

    ID: 23  Title:        KiTTY
            URL:          https://www.9bis.net/kitty/?action=news&zone=en
            Last success: Sun, 27 Mar 2016 17:54:18 +0200

By default, the KiTTY website feed will be stored as `feeds/feed23.xml` then.

## Requirements

You'll need the files from this repository and [SBCL](http://www.sbcl.org) with [Quicklisp](http://www.quicklisp.org) set up. [SQLite3](https://sqlite3.org) should be available. Also, you should create a folder where your feed files should be created (`./feeds` by default). Hard links are allowed.

### Packages

Usually, Quicklisp should install the required packages for you. If you want to install them manually, `rssparser.lisp` currently requires these:

* `datafly`
* `hunchentoot`
* `cl-who`
* `parenscript`
* `smackjack`
* `lass`
* `cl-ppcre`
* `dexador`
* `clss`
* `plump`
* `plump-sexp`
* `local-time`
* `xml-emitter`

### SQLite schema

The `feeds.db` file has the following schema:

    CREATE TABLE feeds (
      id integer primary key autoincrement,
      feedtitle text not null,
      url text not null,
      entryselector text not null,
      titleselector text not null,
      contentselector text not null,
      lastsuccess integer
    );

    CREATE TABLE entries (
      id integer primary key autoincrement,
      feedid integer,
      title text not null,
      contents blob,
      url text not null,
      timestamp integer
    );

### Exporting feeds into a new database

If you want to transfer one or more of your stored feeds into a new database, that's what the `export` command is for:

    % ./rssparser.lisp export 23
    Execute this SQL command to add this feed to a new database:
      INSERT INTO feeds ('feedtitle', 'url', 'entryselector', 'titleselector', 'contentselector') VALUES ('KiTTy', 'https://www.9bis.net/kitty/?action=news&zone=en', '.news', 'h1', '');

## Configuration

You can set a couple of parameters in the `config.lisp` file:

* `+database-file+`: The SQLite database file. (Default: `feeds.db`.) Note that this file *needs* to be accessible for the RSS parser to work!
* `+feed-folder+`: The folder where the feed files should be created. (Default: `feeds/`.) The script *needs* to be able to create files there; it checks its permissions automatically and informs you if it needs some help.
* `+max-items-per-feed+`: The maximum number of items per feed. (Default: `50`.)
* `+feed-cleanup+`: If set to `t` (which is the default value), the `entries` table will automatically be purged from old entries (only *2 * `+max-items-per-feed+`* are kept). Set this to `nil` if you want to bloat your database.
* `+remove-dead-feeds+`: If set to `t`, a website which is not reachable anymore will automatically be removed from your feed list. The parser will inform you of that so if you run `rssparser.lisp` as a cronjob, you'll see what happened in your logfiles.
* `+webserver-port+`: The port to run the webserver on when `rssparser.lisp webserver` is executed. It should be available through your firewall. (Default: `5000`.)

Added config.lisp.









































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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
;;; Web to RSS Parser
;;; by tux. [ http://tuxproject.de ]
;;;
;;; Licensed under the terms of the WTFPL.
;;; http://wtfpl.net/txt/copying/


(in-package #:rssparser)


(defun get-args ()
  "Returns the list of command-line parameters. Don't touch this."
  (or
   #+sbcl sb-ext:*posix-argv*
   #+ccl *command-line-argument-list*
   nil))


;;; -------- SET YOUR OPTIONS BELOW --------


;;; Store the script's command mode in a parameter
;;; so we won't have to fetch it again and again.
;;; Also store the arguments.
(defparameter *script-mode* (cadr (get-args)))
(defparameter *script-arguments* (cddr (get-args)))


;;; Store the database file name and the folder
;;; for our feed files so we can easily change
;;; them later if we want to ...
(defconstant +database-file+ "/home/tux/hg/rssparser.lisp/feeds.db")
(defconstant +feed-folder+ "/home/tux/hg/rssparser.lisp/feeds/")


;;; Store the maximum number of entries per feed.
(defconstant +max-items-per-feed+ 50)


;;; Set up a feed cleaner: If this constant is not NIL,
;;; the feed parser will remove old entries from the
;;; database automatically.
(defconstant +feed-cleanup+ t)


;;; If a website is dead, it could automatically be
;;; removed from the feed list.
(defconstant +remove-dead-feeds+ t)


;; By default, the webserver listens on this port.
(defconstant +webserver-port+ 5000)

Added feeds.db.dist.

cannot compute difference between binary files

Added package.lisp.































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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
;;; Web to RSS Parser
;;; by tux. [ http://tuxproject.de ]
;;;
;;; Licensed under the terms of the WTFPL.
;;; http://wtfpl.net/txt/copying/


(load "~/quicklisp/setup.lisp")

(ql:quickload '(:datafly        ;; for database access

                ;; WEB SERVER:
                :hunchentoot    ;; for providing a web server
                :cl-who         ;; for building the HTML output
                :parenscript    ;; for the avoiding of the horrible JS syntax
                :smackjack      ;; for AJAX requests
                :lass           ;; for building the (S)CSS styles

                ;; WEB/RSS CLIENT:
                :cl-ppcre       ;; for regex
                :dexador        ;; for using the web
                :clss           ;; for CSS selecting
                :plump          ;; for parsing XML/DOM
                :plump-sexp     ;; for converting DOM to S-exps
                :local-time     ;; for time conversion
                :xml-emitter)   ;; for creating the RSS files
              :silent t)

(defpackage #:rssparser
  (:use :cl :sxql :datafly :xml-emitter :local-time :hunchentoot :cl-who :lass :smackjack :sb-int)
  (:import-from :parenscript :ps :chain))

Added rssparser.lisp.































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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
#!/opt/local/bin/sbcl --script

;;; Web to RSS Parser
;;; by tux. [ https://tuxproject.de ]
;;;
;;; Licensed under the terms of the WTFPL.
;;; http://wtfpl.net/txt/copying/


;;; valid syntax:
;;;  * ./rssparser add <Title> <URL> <EntrySelector> <TitleSelector> [<ContentSelector>]
;;;  * ./rssparser.lisp del(ete) <ID>
;;;  * ./rssparser.lisp list
;;;  * ./rssparser.lisp export <ID>
;;;  * ./rssparser.lisp webserver
;;;  * ./rssparser.lisp parse


;;; SETUP

(load (merge-pathnames "package.lisp" *load-truename*))
(load (merge-pathnames "config.lisp" *load-truename*))

(in-package #:rssparser)



;;; HELPER FUNCTIONS


(defun show-syntax ()
  "Prints the command-line syntax for the RSS parser."
  (format t "Syntax:~% * rssparser.lisp add <Title> <URL> <EntrySelector> <TitleSelector> [<ContentSelector>]~% * rssparser.lisp delete <ID>~% * rssparser.lisp list~% * rssparser.lisp export <ID>~% * rssparser.lisp webserver~%~%If you're a bot:~% * rssparser.lisp parse"))


(defun print-feed-list (list)
  "Makes the feed list look nicer."
  (loop for feed in list do
       (let ((id-pair (first feed))
             (title-pair (second feed))
             (url-pair (third feed))
             (lastsuccess-pair (fourth feed)))

         (format t "~%ID: ~a  Title:        ~a~%        URL:          ~a~%        Last success: ~a~%"
                 (cdr id-pair)
                 (cdr title-pair)
                 (cdr url-pair)
                 (if (cdr lastsuccess-pair)
                     (timestamp-to-rssdate (cdr lastsuccess-pair))
                     ;; New feeds don't have a "last success" yet:
                     "-")))))


(clss:define-pseudo-selector external-link (node)
  "CLSS pseudo-selector for external links, shamelessly borrowed from the CLSS manual."
  (let ((href (plump:attribute node "href")))
    (and href (cl-ppcre:scan "^(http|https)://" href))))


(defun extract-urls (node)
  "Tries to find an external href in <node>. Returns a list of all found URLs."
  (let ((link-list (clss:select "a:external-link" node)))
    (loop for found-link being the elements of link-list
       collect (list (plump:attribute found-link "href")))))


(defun timestamp-to-rssdate (timestamp)
  "Returns a readable date from a given timestamp."
  (format-timestring nil
                     (unix-to-timestamp timestamp)
                     :format +rfc-1123-format+))



;;; WEB SERVER


;; Define a parameter to determine if a method has been called via web interface.
(defparameter *is-web* nil)

;; Make Parenscript coexist with CL-WHO
(setf parenscript:*js-string-delimiter* #\")

;; Set the output doctype
(setf (html-mode) :html5)

;; Instantiate an AJAX listener for Smackjack
(defparameter *ajax-processor*
  (make-instance 'ajax-processor :server-uri "/ajax"))

;; Define the routes for Hunchentoot
(setq *dispatch-table*
      (list 'dispatch-easy-handlers
            (create-ajax-dispatcher *ajax-processor*)))


;; Define the HTML output when accessing the web UI
(define-easy-handler (rssweb :uri "/" :default-request-type :get)
    ((state-variable :parameter-type 'string))
  (with-html-output-to-string
      (s nil :indent t)

    (:html
     (:head
      (:title "RSSParser Web Control Center")
      (str (generate-prologue *ajax-processor*))
      (:style :type "text/css"
              (str (compile-and-write
                    '(body
                      :margin 0
                      :padding 0
                      :font-family monospace
                      :font-size 12px)
                    '(h1
                      :margin 5px)
                    '(input
                      :width 335px)
                    '(div#controls
                      :display block
                      :width "calc (100% - 20px)"
                      :padding 10px
                      :background-color lightgrey)
                    '(div#addfeed
                      :display none
                      :position absolute
                      :font-family sans-serif
                      :top 5px
                      :right 5px
                      :border 1px solid darkgray
                      :padding 8px
                      :background-color white
                      (b
                       :margin-bottom 6px)
                      (div
                       :display inline-block)
                      (div.label
                       :width 100px)
                      (div.explanation
                       :width 440px
                       :margin-bottom 4px
                       :font-size 11px))
                    '(table
                      :margin 10px
                      :border-collapse collapse
                      (tr
                       (td
                        :border 1px solid darkgray
                        :padding 4px)
                       (td.centered
                        :text-align center)))
                    '(div#footer
                      :position fixed
                      :width 100%
                      :padding 5px
                      :display block
                      :bottom 0px
                      :left 0px))))
      (:script :type "text/javascript"
               (str (ps
                     (defun print-response-callback (response)
                       (alert response))

                     (defun add-feed ()
                       (setf (chain document (get-element-by-id "addfeed") style display) "inline-block"))

                     (defun add-this-feed ()
                       (let ((title (chain document (get-element-by-id "TitleToAdd") value))
                             (url (chain document (get-element-by-id "URLToAdd") value))
                             (entry-selector (chain document (get-element-by-id "EntrySelectorToAdd") value))
                             (title-selector (chain document (get-element-by-id "TitleSelectorToAdd") value))
                             (content-selector (chain document (get-element-by-id "ContentSelectorToAdd") value)))
                         (if (or (not title) (not url) (not entry-selector) (not title-selector))
                             (alert "You should enter valid feed data before we can process your request.")
                             (progn
                               (chain smackjack (ajax-add-feed (list title url entry-selector title-selector content-selector) print-response-callback))
                               (close-add-feed-dlg)
                               (request-table)))))

                     (defun close-add-feed-dlg ()
                       (loop for inputid in (list "TitleToAdd" "URLToAdd" "EntrySelectorToAdd" "TitleSelectorToAdd" "ContentSelectorToAdd") do
                            (setf (chain document (get-element-by-id inputid) value) nil))
                       (setf (chain document (get-element-by-id "addfeed") style display) "none"))

                     (defun parse-all ()
                       (chain smackjack (ajax-parse-feeds print-response-callback))
                       (request-table))

                     (defun update-table (htmltext)
                       (setf (chain document (get-element-by-id "ajaxtable") inner-h-t-m-l) htmltext))

                     (defun request-table ()
                       (chain smackjack (htmltable update-table))
                       nil)

                     (defun zap-feed (feedid)
                       (chain smackjack (ajax-delete-feed feedid))
                       (request-table)
                       nil)))))
     (:body
      (:h1 "RSSParser Web Control Center")
      (:div :id "controls"
            (:button :type "button"
                     :onclick (ps (parse-all))
                     "Parse All Feeds")
            (:button :type "button"
                     :onclick (ps (add-feed))
                     "Add a Feed"))
      (:div :id "addfeed"
            (:div :class "explanation" "Please type the title of the feed you'd like to add.") (:br)
            (:div :class "label" "Title:") (:input :type "text" :id "TitleToAdd" :placeholder "e.g. KiTTY") (:br) (:br)
            (:div :class "explanation" "Please type the URL of the website you want to make an RSS feed of.") (:br)
            (:div :class "label" "URL:") (:input :type "text" :id "URLToAdd" :placeholder "e.g. http://www.9bis.net/kitty/?action=news&zone=en") (:br) (:br)
            (:b "CSS Selectors:") (:a :href "http://www.w3schools.com/cssref/trysel.asp" :target "_blank" "[?]") (:br)
            (:div :class "explanation" (str (concatenate 'string "Please type the single entry selector of the feed. For a blog, this is usually a DIV named \"article\" or similar. RSSParser.lisp will use this selector as the container selector for the following elements."))) (:br)
            (:div :class "label" "Selector:") (:input :type "text" :id "EntrySelectorToAdd" :placeholder "e.g. .news") (:br) (:br)
            (:div :class "explanation" "Please type the title selector of the feed. This is usually the headline inside the entry selector.") (:br)
            (:div :class "label" "Selector:") (:input :type "text" :id "TitleSelectorToAdd" :placeholder "e.g. h1") (:br) (:br)
            (:div :class "explanation" (str (concatenate 'string (htm (:em "(Optional)")) " Please type the content selector of the feed. This is usually the text part of the entry selector. If this is left blank, RSSParser.lisp will use the complete entry selector for the contents of your feed items."))) (:br)
            (:div :class "label" "Selector:") (:input :type "text" :id "ContentSelectorToAdd" :placeholder "e.g. \"\"") (:br) (:br)
            (:button :type "button"
                     :onclick (ps (add-this-feed))
                     "Add this feed")
            (:button :type "button"
                     :onclick (ps (close-add-feed-dlg))
                     "Cancel"))
      (:div :id "ajaxtable")
      (:div :id "footer"
            (:a :href "http://bitbucket.org/tux_/rssparser.lisp" :target "_blank" "Powered by RSSParser.lisp"))
      (:script :type "text/javascript"
               (str (ps (request-table))))))))


;; Define an AJAX handler which returns the updated feeds list (as a table)
(defun-ajax htmltable ()
  (*ajax-processor* :callback-data :response-text)
  (with-html-output-to-string
      (s nil :indent t)
    (:table
     (:tr
      (:th "ID")
      (:th "Title")
      (:th "Original URL")
      (:th "Last success")
      (:th "Delete"))
     (loop for feed in (list-all-feeds) do
          (let ((id-pair (first feed))
                (title-pair (second feed))
                (url-pair (third feed))
                (lastsuccess-pair (fourth feed)))
            (htm (:tr
                  (:td (str (cdr id-pair)))
                  (:td (str (cdr title-pair)))
                  (:td
                   (:a :href (cdr url-pair) :target "_blank" (str (cdr url-pair))))
                  (:td (if (cdr lastsuccess-pair)
                           (str (timestamp-to-rssdate (cdr lastsuccess-pair)))
                           "-"))
                  (:td :class "centered"
                       (:button :type "button"
                                :title (concatenate 'string "Delete the " (write-to-string (cdr title-pair)) " feed")
                                :onclick (concatenate 'string "javascript:zapFeed(\"" (write-to-string (cdr id-pair)) "\")")
                                "x")))))))))


;;; MAIN APPLICATION


;; Force the charset to be Unicode
(setf sb-impl::*default-external-format* :UTF-8)

(connect-toplevel :sqlite3 :database-name +database-file+)

(defun add-new-feed (params)
  "Adds a new feed to the database."
  ;; Params: Feed title, URL, entry selector, title sel., [ content sel. ]
  (if
   (and
    ;; URL given?
    (cl-ppcre:scan "^https?://" (second params))
    ;; Are the necessary params given at all?
    (>= (list-length params) 4)
    (<= (list-length params) 5))
   (progn
     (if
      (and
       ;; Everything but the title must not be a number.
       (not (numberp (parse-integer (second params) :junk-allowed t)))
       (not (numberp (parse-integer (third params) :junk-allowed t)))
       (not (numberp (parse-integer (fourth params) :junk-allowed t))))
      (progn
        (let ((content
               (if (fifth params)
                   (princ-to-string (fifth params))
                   "")))
          (execute
           ;; all arguments are set (probably even correctly).
           (insert-into :feeds
                        (set= :feedtitle (princ-to-string (first params))
                              :url (princ-to-string (second params))
                              :entryselector (princ-to-string (third params))
                              :titleselector (princ-to-string (fourth params))
                              :contentselector content))))
        t)
      nil))
   (progn
     ;; invalid number of arguments
     (show-syntax)
     nil)))


;; AJAX handler for feed addition:
(defun-ajax ajax-add-feed (params)
  (*ajax-processor* :callback-data :response-text)
  (setf *is-web* t)
  (if
   (add-new-feed params)
   "We successfully added your feed. :-)"
   "Sorry, something went wrong. :-(")
  (setf *is-web* nil))


(defun delete-feed (id)
  "Deletes a feed and all of its references."
  (if
   (and
    (eql 1 (list-length id))
    (numberp (parse-integer (car id) :junk-allowed t)))
   (let ((id-to-delete (car id)))
     ;; The <id-to-delete> is the number of the feed to delete.
     (if
      (retrieve-one (select :id (from :feeds) (where (:= :id id-to-delete))))
      (progn
        ;; This feed exists. Remove it.
        (execute (delete-from :feeds
                              (where (:= :id id-to-delete))))
        (execute (delete-from :entries
                              (where (:= :feedid id-to-delete))))
        ;; Now that the database entry is gone, we don't
        ;; need the XML file anymore.
        (let
            ;; The file is probably "feeds/feed<ID>.xml".
            ((feed-file (probe-file (concatenate 'string +feed-folder+ "feed" id-to-delete ".xml"))))
          (if feed-file
              ;; We have an XML file. Yet.
              (delete-file feed-file)))
        t)
      ;; No such feed in the database
      nil))
   (progn
     ;; invalid number of arguments or ID is NaN
     (show-syntax)
     nil)))


(defun export-feed (id)
  "Exports a feed's INSERT command for transferring it into another database."
  (if
   (and
    (eql 1 (list-length id))
    (numberp (parse-integer (car id) :junk-allowed t)))
   (progn
     (let* ((id-to-export (car id))
            (feed (retrieve-one (select
                                 (:feedtitle :url :entryselector :titleselector :contentselector)
                                 (from :feeds)
                                 (where (:= :id id-to-export))))))

       ;; The <id-to-export> is the number of the feed to export.
       (if feed
           (progn
             ;; This feed exists. Export it.
             (let
                 ((feed-title (second feed))
                  (feed-url (fourth feed))
                  (feed-entries (sixth feed))
                  (feed-entry-titles (eighth feed))
                  (feed-entry-contents (tenth feed)))
               (concatenate 'string
			    "INSERT INTO feeds ('feedtitle', 'url', 'entryselector', 'titleselector', 'contentselector') "
			    "VALUES ('" feed-title "', '" feed-url "', '" feed-entries "', '" feed-entry-titles "', '" feed-entry-contents "');")))
           ;; No such feed in the database
           nil)))
   (progn
     ;; invalid number of arguments or ID is NaN
     (show-syntax)
     nil)))


;; AJAX handler for feed deletion:
(defun-ajax ajax-delete-feed (feed-id)
  (*ajax-processor* :callback-data :response-text)
  (if
   (delete-feed (list feed-id))
   (concatenate 'string "Deleted feed " feed-id)
   "Failed to delete the feed, sorry."))


(defun list-all-feeds ()
  "Lists all known feeds."
  (retrieve-all
   (select (:id :feedtitle :url :lastsuccess)
           (from :feeds))
   :as 'trivial-types:association-list))


(defun parse-all-feeds ()
  "Loops over the known feeds and generates the XML files."
  (loop for feed in
       (retrieve-all
        (select (:feedtitle :url :entryselector :titleselector :contentselector :id)
                (from :feeds)))
     do
       (let
           ((feed-title (second feed))
            (feed-url (fourth feed))
            (feed-entries (sixth feed))
            (feed-entry-titles (eighth feed))
            (feed-entry-contents (tenth feed))
            (feed-id (last feed)))
         (handler-case
             (let ((the-dom (plump:parse (dex:get feed-url))))
               ;; the-dom is the DOM of our feed URL now.
               ;; We can process it normally.
               (let ((box-elements (clss:select feed-entries the-dom))
                     (feed-file (concatenate 'string +feed-folder+ "feed" (princ-to-string (car feed-id)) ".xml")))
                 (with-open-file (stream feed-file
                                         :direction :output
                                         :if-exists :overwrite
                                         :if-does-not-exist :create)
                   (with-rss2 (stream :encoding "utf-8")
                     (rss-channel-header feed-title feed-url)
                     (loop for feed-entry being the elements of box-elements do
                          (let
                              ((contents
                                ;; If the feed has an "empty" contents selector, take the
                                ;; whole box element's content as the entry contents
                                (if (string= feed-entry-contents "")
                                    (list feed-entry)
                                    (clss:select feed-entry-contents feed-entry)))

                               ;; The title elements are always stored with the feed.
                               (titles (clss:select feed-entry-titles feed-entry)))

                            ;; Loop over all titles/contents and add an RSS item for each of them
                            (loop for single-title being the elements of titles
                               for single-contents being the elements of contents
                               do
                                 (let
                                     ;; Grab the plain text from the title:
                                     ((our-title (plump:text single-title))
                                      ;; Try to find the entry URL:
                                      (our-url (extract-urls single-title))
                                      ;; Serialize the contents to NIL (return a string):
                                      (our-contents (plump:serialize (plump-sexp:parse (plump-sexp:serialize single-contents)) nil)))
                                   ;; Write the data to the database:
                                   (when
                                       (and
                                        our-title
                                        our-contents

                                        ;; Only do it if we don't have this item yet :-)
                                        (not (retrieve-all
                                              (select :*
                                                      (from :entries)
                                                      (where (:and
                                                              (:= :feedid (car feed-id))
                                                              (:= :title our-title)))))))

                                     (execute
                                      (insert-into :entries
                                                   (set= :feedid (princ-to-string (car feed-id))
                                                         :title (princ-to-string our-title)
                                                         :contents (princ-to-string our-contents)
                                                         :url (if our-url (princ-to-string (caar our-url)) feed-url)
                                                         :timestamp (timestamp-to-unix (now)))))))

                               ;; Update the success timestamp in the database.
                                 (execute
                                  (update :feeds
                                          (set= :lastsuccess (timestamp-to-unix (now)))
                                          (where (:= :id (car feed-id))))))))

                     ;; Clean up if requested.
                     (when +feed-cleanup+
                       (execute
                        (delete-from :entries
                                     (where (:in :id
                                                 (select :id
                                                         (from :entries)
                                                         (where (:= :feedid (car feed-id)))
                                                         (order-by (:desc :timestamp))
                                                         (limit -1)
                                                         (offset (* 2 +max-items-per-feed+))))))))

                     ;; We have a nicely filled database now.
                     ;; Grab the newest entries and put them into our feed.
                     (loop for item-list in
                          (retrieve-all
                           (select (:title :contents :url :timestamp)
                                   (from :entries)
                                   (where (:= :feedid (car feed-id)))
                                   (order-by (:asc :timestamp))
                                   (limit +max-items-per-feed+))
                           :as 'trivial-types:association-list)
                        do
                        ;; Our list should look as follows now:
                        ;; ((TITLE) (CONTENTS) (URL) (TIMESTAMP))
                          (let ((this-title (cdr (first item-list)))
                                (this-contents (cdr (second item-list)))
                                (this-url (cdr (third item-list)))
                                (this-timestamp (cdr (fourth item-list))))

                            ;; Write each fetched item to the RSS file.
                            (rss-item (princ-to-string this-title)
                                      :link this-url
                                      :description (princ-to-string this-contents)
                                      :pubDate (princ-to-string (timestamp-to-rssdate this-timestamp)))))))))

           (simple-file-error ()
             ;; The feed folder is not writeable.
             (unless *is-web*
               (format t "Please fix the access rights for ~a for this script to work.~%" +feed-folder+))
             (return nil))

           (simple-stream-error ()
             ;; Connection reset by peer.
             (format t (concatenate 'string "~%Feed " (prin1-to-string (car feed-id)) " has a website which is "
                                   "temporarily unavailable. We'll try later.")))

           (sb-bsd-sockets:connection-refused-error ()
             ;; Connection refused.
             (format t (concatenate 'string "~%Feed " (prin1-to-string (car feed-id)) " has a website which is "
                                   "temporarily unavailable. We'll try later.")))

           (sb-bsd-sockets:interrupted-error ()
             ;; Connection interrupted.
             (format t (concatenate 'string "~%Feed " (prin1-to-string (car feed-id)) " has a website which is "
                                   "temporarily unavailable. We'll try later.")))

           (dex:http-request-service-unavailable ()
             ;; Temporary website error. Retry later.
             (format t (concatenate 'string "~%Feed " (prin1-to-string (car feed-id)) " has a website which is "
                                   "temporarily unavailable. We'll try later.")))

           (dex:http-request-forbidden ()
             ;; Probably also temporary website error. Retry later.
             (format t (concatenate 'string "~%Feed " (prin1-to-string (car feed-id)) " has a website which is "
                                   "temporarily unavailable. We'll try later.")))

           (dex:http-request-failed (e)
             ;; Page not found. Assume it is gone.
             (if +remove-dead-feeds+
                 (progn
                   ;; Remove the page from the feeds.
                   (unless *is-web*
                     (format t (concatenate 'string
                                            "~%Feed " (prin1-to-string (car feed-id)) " seems to have a broken website: "
                                            feed-url " could not be reached (" e "). We'll better remove it.")))
                   (force-output nil)
                   (delete-feed (list (write-to-string (car feed-id)))))
                 (progn
                   ;; Display a warning.
                   (unless *is-web*
                     (format t (concatenate 'string
                                            "~%Feed " (prin1-to-string (car feed-id)) " seems to have a broken website: "
                                            feed-url " could not be reached (" e ").")))
                   (force-output nil)))))))

  (setf *is-web* nil))


;; AJAX handler for feed parsing:
(defun-ajax ajax-parse-feeds ()
  (*ajax-processor* :callback-data :response-text)
  (setf *is-web* t)
  (parse-all-feeds)
  "Good news: We just refreshed all of your generated RSS feeds. :-)")


(defun start-webserver ()
  "Runs the RSS parser's built-in web server."
  (format t "Starting the web server on port ~d. Press Ctrl+C to quit.~%~%" +webserver-port+)
  (force-output nil)
  (defparameter *server*
    (start (make-instance 'easy-acceptor :port +webserver-port+))))


(defun rssparser ()
  "The main function, evaluating the command-line parameters."
  (cond
    ((string= *script-mode* "add")
     ;; add an entry
     (when
         (add-new-feed *script-arguments*)
       (format t "Success!~%")))
    ((or
      (string= *script-mode* "delete")
      (string= *script-mode* "del"))
     ;; remove an entry
     (if
      (delete-feed *script-arguments*)
      (format t "Deletion successful!~%")
      (format t "This feed could not be deleted.~%")))
    ((string= *script-mode* "list")
     ;; list all entries
     (let ((feedlist (list-all-feeds)))
       (if feedlist
           (progn
             ;; print a list of feeds
             (format t (concatenate 'string
                                    (prin1-to-string (list-length feedlist))
                                    (if (eql 1 (list-length feedlist))
                                        " feed is set up:~%"
                                        " feeds are set up:~%")))
             (force-output nil)
             (print-feed-list feedlist))
           (format t "You don't have any feeds yet."))))
    ((string= *script-mode* "export")
     ;; show an SQLite command to transfer this feed elsewhere
     (let ((result (export-feed *script-arguments*)))
      (if result
       (format t "Execute this SQL command to add this feed to a new database:~%  ~A~%~%" result)
       (format t "This feed could not be exported.~%"))))
    ((string= *script-mode* "parse")
     ;; the parser for existing sites
     (parse-all-feeds))
    ((string= *script-mode* "webserver")
     ;; start the web server
     (handler-case
         (start-webserver)
       (sb-sys:interactive-interrupt ()
         (format t "~%~%Quitting the web server. Goodbye.~%~%"))))
    (t
     ;; else ...
     (show-syntax))))



(rssparser)