-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfavicon_handler.go
More file actions
197 lines (160 loc) · 5.37 KB
/
favicon_handler.go
File metadata and controls
197 lines (160 loc) · 5.37 KB
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
package main
import (
"crypto/tls"
"errors"
"fmt"
"io"
"net/http"
"os"
"path/filepath"
"regexp"
"strings"
"time"
)
// FaviconHandler manages favicon operations for projects
type FaviconHandler struct {
BaseDirectory string // Base directory for storing favicons
}
// NewFaviconHandler creates a new FaviconHandler with the specified base directory
func NewFaviconHandler(baseDir string) *FaviconHandler {
return &FaviconHandler{
BaseDirectory: baseDir,
}
}
// FetchFavicon gets a favicon from a website URL
func (fh *FaviconHandler) FetchFavicon(url string) ([]byte, error) {
if url == "" {
return nil, errors.New("URL cannot be empty")
}
// Ensure URL has a scheme
if !strings.HasPrefix(url, "http://") && !strings.HasPrefix(url, "https://") {
url = "https://" + url
}
// Create a custom HTTP client with relaxed TLS settings for testing
tr := &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}
client := &http.Client{
Transport: tr,
Timeout: time.Second * 10,
}
// Try direct favicon.ico path first
parsedURL := strings.TrimSuffix(url, "/")
faviconURL := fmt.Sprintf("%s/favicon.ico", parsedURL)
resp, err := client.Get(faviconURL)
if err == nil && resp.StatusCode == http.StatusOK {
defer resp.Body.Close()
return io.ReadAll(resp.Body)
}
// If direct path fails, try to get the web page and parse for favicon
resp, err = client.Get(url)
if err != nil {
return nil, fmt.Errorf("failed to fetch website: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("failed to fetch website, status code: %d", resp.StatusCode)
}
// Read the body content
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("failed to read response body: %v", err)
}
// Extract favicon link from HTML
bodyStr := string(body)
re := regexp.MustCompile(`<link[^>]*rel=["'](?:shortcut )?icon["'][^>]*href=["']([^"']+)["'][^>]*>`)
matches := re.FindStringSubmatch(bodyStr)
if len(matches) < 2 {
return nil, fmt.Errorf("no favicon found in the HTML")
}
faviconURL = matches[1]
if !strings.HasPrefix(faviconURL, "http") {
// Handle relative URLs
if strings.HasPrefix(faviconURL, "//") {
faviconURL = "https:" + faviconURL
} else if strings.HasPrefix(faviconURL, "/") {
faviconURL = fmt.Sprintf("%s%s", parsedURL, faviconURL)
} else {
faviconURL = fmt.Sprintf("%s/%s", parsedURL, faviconURL)
}
}
// Fetch the favicon
resp, err = client.Get(faviconURL)
if err != nil {
return nil, fmt.Errorf("failed to fetch favicon: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("failed to fetch favicon, status code: %d", resp.StatusCode)
}
return io.ReadAll(resp.Body)
}
// GenerateSlug creates a URL-friendly slug from a project name
func GenerateSlug(projectName string) string {
// Convert to lowercase
slug := strings.ToLower(projectName)
// Replace spaces with hyphens
slug = strings.ReplaceAll(slug, " ", "-")
// Remove special characters
reg := regexp.MustCompile(`[^a-z0-9-]`)
slug = reg.ReplaceAllString(slug, "")
// Remove consecutive hyphens
for strings.Contains(slug, "--") {
slug = strings.ReplaceAll(slug, "--", "-")
}
// Trim leading and trailing hyphens
slug = strings.Trim(slug, "-")
return slug
}
// GetFaviconPath generates the proper file path for a project favicon
func (fh *FaviconHandler) GetFaviconPath(projectName string) string {
slug := GenerateSlug(projectName)
logosDir := filepath.Join(fh.BaseDirectory, "data", "logos", slug)
return filepath.Join(logosDir, "favicon.png")
}
// SaveFavicon saves favicon data to the filesystem
func (fh *FaviconHandler) SaveFavicon(projectName string, faviconData []byte) (string, error) {
if len(faviconData) == 0 {
return "", errors.New("favicon data cannot be empty")
}
slug := GenerateSlug(projectName)
logosDir := filepath.Join(fh.BaseDirectory, "data", "logos", slug)
// Create the logos directory if it doesn't exist
if err := os.MkdirAll(logosDir, 0755); err != nil {
return "", fmt.Errorf("failed to create directory: %v", err)
}
faviconPath := filepath.Join(logosDir, "favicon.png")
// Write the favicon file
if err := os.WriteFile(faviconPath, faviconData, 0644); err != nil {
return "", fmt.Errorf("failed to write favicon file: %v", err)
}
// Return the relative path to the favicon
relPath, err := filepath.Rel(fh.BaseDirectory, faviconPath)
if err != nil {
return faviconPath, nil // Fall back to absolute path if relative path can't be determined
}
return relPath, nil
}
// RemoveFavicon deletes a project's favicon
func (fh *FaviconHandler) RemoveFavicon(projectName string) error {
faviconPath := fh.GetFaviconPath(projectName)
if _, err := os.Stat(faviconPath); os.IsNotExist(err) {
return nil // File doesn't exist, so nothing to remove
}
if err := os.Remove(faviconPath); err != nil {
return fmt.Errorf("failed to remove favicon: %v", err)
}
// Try to remove the directory if it's empty
slug := GenerateSlug(projectName)
logosDir := filepath.Join(fh.BaseDirectory, "data", "logos", slug)
// Check if directory is empty
entries, err := os.ReadDir(logosDir)
if err == nil && len(entries) == 0 {
// Directory is empty, try to remove it
if err := os.Remove(logosDir); err != nil {
// Non-critical error, just log it
fmt.Printf("Warning: could not remove empty directory %s: %v\n", logosDir, err)
}
}
return nil
}