summaryrefslogtreecommitdiffstats
path: root/quicknote.go
blob: df70d9777cd2534b65d57f5751c45d7cfdaf7bee (plain) (blame)
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
package main

import (
	"bufio"
	"fmt"
	"io/ioutil"
	"net/http"
	"os"
	"os/user"
	"path/filepath"
	"regexp"
	"strings"

	"github.com/atotto/clipboard"
)

func main() {
	if len(os.Args) < 2 {
		fmt.Println("Usage: quicknote [-c] <url> [markdown-file]")
		os.Exit(1)
	}

	url := ""
	markdownFile := ""

	if os.Args[1] == "-c" {
		urlFromClipboard, err := clipboard.ReadAll()
		if err != nil {
			fmt.Printf("Error getting URL from clipboard: %v\n", err)
			os.Exit(1)
		}
		url = strings.TrimSpace(urlFromClipboard)
	} else {
		url = os.Args[1]
	}

	if len(os.Args) == 2 || (len(os.Args) == 3 && os.Args[1] == "-c") {
		usr, err := user.Current()
		if err != nil {
			fmt.Printf("Error getting user home directory: %v\n", err)
			os.Exit(1)
		}
		markdownFile = filepath.Join(usr.HomeDir, "Documents", "Notes", "quicknote.md")
	} else {
		markdownFile = os.Args[2]
	}

	resp, err := http.Get(url)
	if err != nil {
		fmt.Printf("Error fetching URL: %v\n", err)
		os.Exit(1)
	}
	defer resp.Body.Close()

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		fmt.Printf("Error reading response body: %v\n", err)
		os.Exit(1)
	}

	htmlContent := string(body)
	title, err := extractTitle(htmlContent)

	if err != nil {
		fmt.Printf("Error: %v\n", err)
		title = promptForTitle()
	}

	markdownLink := fmt.Sprintf("- [%s](%s)\n", title, url)
	err = appendToFile(markdownFile, markdownLink)
	if err != nil {
		fmt.Printf("Error appending to file: %v\n", err)
		os.Exit(1)
	}
}

func extractTitle(html string) (string, error) {
	re := regexp.MustCompile(`(?i)<\s*title\s*>(.*?)<\s*/\s*title\s*>`)
	match := re.FindStringSubmatch(html)
	if len(match) > 0 {
		title := strings.TrimSpace(match[1])
		if title != "" {
			return title, nil
		}
		return "", fmt.Errorf("title tag is empty")
	}
	return "", fmt.Errorf("title tag is not present")
}

func promptForTitle() string {
	reader := bufio.NewReader(os.Stdin)
	fmt.Print("Please enter a title for the URL: ")
	title, _ := reader.ReadString('\n')
	return strings.TrimSpace(title)
}

func appendToFile(filename, content string) error {
	f, err := os.OpenFile(filename, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
	if err != nil {
		return err
	}
	defer f.Close()

	if _, err := f.WriteString(content); err != nil {
		return err
	}
	return nil
}