Blame


1 cfb62e6e 2022-01-08 op package main
2 cfb62e6e 2022-01-08 op
3 cfb62e6e 2022-01-08 op import (
4 cfb62e6e 2022-01-08 op "bufio"
5 cfb62e6e 2022-01-08 op "context"
6 cfb62e6e 2022-01-08 op "errors"
7 cfb62e6e 2022-01-08 op "regexp"
8 cfb62e6e 2022-01-08 op "strings"
9 cfb62e6e 2022-01-08 op
10 cfb62e6e 2022-01-08 op gemini "git.sr.ht/~adnano/go-gemini"
11 cfb62e6e 2022-01-08 op )
12 cfb62e6e 2022-01-08 op
13 cfb62e6e 2022-01-08 op var (
14 cfb62e6e 2022-01-08 op ErrNoTitle = errors.New(`no title found`)
15 cfb62e6e 2022-01-08 op
16 cfb62e6e 2022-01-08 op title1 = regexp.MustCompile(`^#[^#]`)
17 cfb62e6e 2022-01-08 op title2 = regexp.MustCompile(`^##[^#]`)
18 cfb62e6e 2022-01-08 op title3 = regexp.MustCompile(`^###`)
19 cfb62e6e 2022-01-08 op )
20 cfb62e6e 2022-01-08 op
21 cfb62e6e 2022-01-08 op func geminiTitle(url string) (string, error) {
22 cfb62e6e 2022-01-08 op client := gemini.Client{}
23 cfb62e6e 2022-01-08 op ctx := context.Background()
24 cfb62e6e 2022-01-08 op resp, err := client.Get(ctx, url)
25 cfb62e6e 2022-01-08 op if err != nil {
26 cfb62e6e 2022-01-08 op return "", err
27 cfb62e6e 2022-01-08 op }
28 cfb62e6e 2022-01-08 op defer resp.Body.Close()
29 cfb62e6e 2022-01-08 op
30 cfb62e6e 2022-01-08 op if resp.Status != 20 || !strings.HasPrefix(resp.Meta, "text/gemini") {
31 cfb62e6e 2022-01-08 op return "", ErrNoTitle
32 cfb62e6e 2022-01-08 op }
33 cfb62e6e 2022-01-08 op
34 cfb62e6e 2022-01-08 op var t2, t3 string
35 cfb62e6e 2022-01-08 op
36 cfb62e6e 2022-01-08 op scanner := bufio.NewScanner(resp.Body)
37 cfb62e6e 2022-01-08 op for scanner.Scan() {
38 cfb62e6e 2022-01-08 op line := scanner.Text()
39 cfb62e6e 2022-01-08 op
40 cfb62e6e 2022-01-08 op switch {
41 cfb62e6e 2022-01-08 op case title1.MatchString(line):
42 cfb62e6e 2022-01-08 op return line, nil
43 cfb62e6e 2022-01-08 op case title2.MatchString(line) && t2 == "":
44 cfb62e6e 2022-01-08 op t2 = line
45 cfb62e6e 2022-01-08 op case title3.MatchString(line) && t3 == "":
46 cfb62e6e 2022-01-08 op t3 = line
47 cfb62e6e 2022-01-08 op }
48 cfb62e6e 2022-01-08 op }
49 cfb62e6e 2022-01-08 op
50 cfb62e6e 2022-01-08 op if t2 != "" {
51 cfb62e6e 2022-01-08 op return t2, nil
52 cfb62e6e 2022-01-08 op }
53 cfb62e6e 2022-01-08 op
54 cfb62e6e 2022-01-08 op if t3 != "" {
55 cfb62e6e 2022-01-08 op return t3, nil
56 cfb62e6e 2022-01-08 op }
57 cfb62e6e 2022-01-08 op
58 cfb62e6e 2022-01-08 op return "", ErrNoTitle
59 cfb62e6e 2022-01-08 op }