aboutsummaryrefslogtreecommitdiff
path: root/main.scm
blob: 320df14a14b6c5208b1f90a74c85d68f7b20a342 (plain)
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
#!/usr/bin/guile \
-q -e main -s
!#

(add-to-load-path (dirname (current-filename)))
(add-to-load-path (string-append (dirname (current-filename)) "/monad/"))
(add-to-load-path "/home/hugo/lib/guile")

(add-to-load-path "/home/hugo/code/calparse")  ; For (util), move that to a library

(setenv "LD_LIBRARY_PATH" (dirname (current-filename)))

(use-modules #; (sxml simple)
             ;; (sxml match)

             (srfi srfi-1)
             (srfi srfi-26)
             (srfi srfi-43)             ; Vector iteration

             ;; (ice-9 rdelim)
             (ice-9 regex)
             (ice-9 popen)

             (macros arrow)
             (util)

             (control monad)
             (control monad state)
             (data stack)

             (fmt-stack)
             (html)
             (json))

(define-macro (regex-case str . cases)
  `(cond
    ,@(map (lambda (case)
                (let ((pattern (car case))
                      (rest (cdr case)))
                  (if (eq? pattern 'else)
                      `(else ,@rest)
                      `((string-match ,pattern ,str) ,@rest))))
           cases)))

(define (substr-1 match)
  (match:substring match 1))

(define (class-handlers class)
  (fold (lambda (cl obj)
          (regex-case
           cl
           ("^DH$"           (set-style obj 'bold))
           ("^bg([BYC])$" => (compose (cut set-bg obj <>) string->symbol substr-1))
           ("^([BYC])$"   => (compose (cut set-fg obj <>) string->symbol substr-1))
           (else obj)))
        (empty-fmt-frame)
        (string-split class #\space)))

;;; TODO every push and pop should emit current ANSI-escape after it has run.

(use-modules (ice-9 match))

;;; TODO Every clause should return a string, in the state context of a state.

;;                  +-- State storage, "mutable"
;;                  |          +- Return value, static
;;                  V          V
;; sxml → State <fmt-stack> <string>
(define (fmt-tag tag)
  (match tag

    [('a _ body ...)
     (do fmt-before <- (get-attr)
         (push (make-fmt-frame 'underline 'B #f))
         fmt-with <- (get-attr)
         (pop)
         (return-state
          (string-append fmt-with (car body) fmt-before)))]

    [((or 'h1 'span) attrs nodes ...)
     (do let class = (hashq-ref attrs 'class)
         fmt-before <- (get-attr)
         (push (class-handlers class))
         fmt-with <- (get-attr)
         ret <- (fmap (cut string-append fmt-with <> fmt-before)
                      (fmap string-concatenate (sequence (map fmt-tag nodes))))
         (pop)
         (return-state ret))]

    ;; Default rule, since the above case requires a class list
    [(tag _ node nodes ...)
     (fmap string-concatenate (sequence (map fmt-tag (cons node nodes))))]

    ;; Just ignore tags without children
    [(tag _) (return-state "")]

    [(? string? str) (return-state str)]

    [default (return-state (format #f "[|~a|]" default))]))

(define (parse-html-string str)
  (let ((fname (tmpnam)))
    (with-output-to-file fname
      (lambda () (display str)))
    (parse-html fname)))

(define (text-for-num j int)
  (let* ((table (vector-ref j (- int 100)))
         (arr (hashq-ref table 'content))
         (text (array-ref arr 0)))
    text))

(define (max-date vect)
  (vector-fold (lambda (i accum el) (max accum (hashq-ref el 'date_updated_unix)))
               0 vect))

(define (cache-dir)
  (string-append
   (or (getenv "XDG_CACHE_HOME")
       (and=> (getenv "HOME") (cut string-append <> "/.cache"))
       "/tmp")
   "/texttv/"))

(define (cfile path)
  "Gives path to file in cache directory."
  (string-append (cache-dir) path))

(define* (display-status-bar n max #:optional (port #t))
  (let* ((progress (/ n max))
         (trnc (truncate (* 60 progress))))
    (format port
            "\rProgress [~a~a] ~3d%"
            (make-string trnc #\#)
            (make-string (- 60 trnc) #\-)
            (truncate (* 100 progress)))))

(define (main args)
  (let* (((self filename pagestr) args)
         (page (string->number pagestr)))

    (unless (file-exists? (cache-dir))
      (mkdir (cache-dir))
      (with-output-to-file (cfile "last-updated")
        (lambda () (display 0))))

    (let ((last-updated (call-with-input-file (cfile "last-updated") read)))
     (when (> (- (current-time) last-updated) 10000)
       (display "Downloading new data, please stand by...")
       (system* "curl"
                "-s" "http://api.texttv.nu/api/get/100-999?app=hugonikanor"
                "-o" (cfile filename))

       (let* ((json (get-json (cfile filename)))
              (update (max-date json)))

         (with-output-to-file (cfile "last-updated") (lambda () (display update)))

         (let ((vlen (vector-length json)))
           (format (current-error-port)
                   "~%Rendering HTML~%")
           (vector-for-each
            (lambda (i el)
              (let ((num (hashq-ref el 'num))
                    (text (vector-ref (hashq-ref el 'content) 0)))
                (with-output-to-file (cfile (format #f "~a.ansi" num))
                  (lambda ()
                    (display-status-bar i vlen (current-error-port))
                    (-> (parse-html-string text)
                        fmt-tag
                        (run-state (list (make-fmt-frame "" "" "")))
                        car display)))))
            json))
         (display-status-bar 1 1 (current-error-port))
         (newline (current-error-port))))

     (let ((p1 (cfile (format #f "~a.ansi" page)))
           (p2 (cfile (format #f "~a.ansi" (1+ page)))))
       (system* "paste" p1 p2)))))