habraview/habraview.v

88 lines
2.0 KiB
V
Raw Permalink Normal View History

2024-11-03 14:32:04 +03:00
module main
import cli
import habr
2024-11-03 16:55:43 +03:00
import net
import net.urllib
import net.http.mime
2024-11-03 14:32:04 +03:00
import os
import veb
pub struct Context {
veb.Context
}
2024-11-03 18:00:57 +03:00
pub struct App {}
2024-11-03 14:32:04 +03:00
2024-11-03 16:55:43 +03:00
const embedded = {
'style.css': $embed_file('assets/style.css')
'highlight.min.css': $embed_file('assets/highlight.min.css')
'highlight.min.js': $embed_file('assets/highlight.min.js')
'habrfixer.js': $embed_file('assets/habrfixer.js')
'favicon.ico': $embed_file('assets/favicon.ico')
}
@['/assets/:filename']
fn (a &App) assets(mut ctx Context, filename string) veb.Result {
asset := embedded[filename] or { return ctx.not_found() }
mimetype := mime.get_mime_type(os.file_ext(filename).trim_left('.'))
ctx.set_content_type(mimetype)
return ctx.text(asset.to_string())
}
2024-11-03 14:32:04 +03:00
@[get]
fn (a &App) index(mut ctx Context) veb.Result {
article_id := ctx.query['id'] or { habr.get_id_from_url(ctx.query['url']) or { '' } }
client := habr.Habr.new()
2024-11-03 18:00:57 +03:00
raw_article := client.get_article(article_id.int()) or { return ctx.server_error(err.str()) }
2024-11-03 14:32:04 +03:00
raw_comments := client.get_article_comments(article_id.int()) or {
2024-11-03 18:00:57 +03:00
return ctx.server_error(err.str())
2024-11-03 14:32:04 +03:00
}
article := habr.Article.parse(raw_article)
comments := habr.Comments.parse(raw_comments)
return $veb.html()
}
2024-11-03 18:00:57 +03:00
fn serve(host string, port int) ! {
2024-11-03 14:32:04 +03:00
mut app := &App{}
2024-11-03 16:55:43 +03:00
mut ipversion := net.AddrFamily.ip
if host.contains(':') {
ipversion = net.AddrFamily.ip6
}
params := veb.RunParams{
host: host
port: port
family: ipversion
}
veb.run_at[App, Context](mut app, params)!
2024-11-03 14:32:04 +03:00
}
2024-11-03 18:00:57 +03:00
fn run_server(cmd cli.Command) ! {
mut host, mut port := '0.0.0.0', '8888'
if cmd.args.len == 1 {
host, port = urllib.split_host_port(cmd.args[0])
if host.is_blank() {
host = '0.0.0.0'
}
if port.is_blank() {
port = '8888'
}
}
serve(host, port.int())!
}
2024-11-03 14:32:04 +03:00
fn main() {
mut app := cli.Command{
name: 'habraview'
2024-11-03 16:55:43 +03:00
usage: '[host][:port]'
2024-11-03 14:32:04 +03:00
description: 'Habr.com posts viewer.'
version: $d('habraview_version', '0.0.0')
defaults: struct {
man: false
}
2024-11-03 18:00:57 +03:00
execute: run_server
2024-11-03 14:32:04 +03:00
}
app.setup()
app.parse(os.args)
}