aboutsummaryrefslogtreecommitdiffhomepage
path: root/backend/account/icon.go
blob: 8f7652742d6f9ddddf608cbc63cab1c1131b65e4 (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
package account

import (
	"context"
	"fmt"
	"io"
	"net/http"
	"net/url"
	"os"
	"path"
	"path/filepath"
	"time"

	"github.com/nsfisis/iosdc-japan-2024-albatross/backend/db"
	"github.com/nsfisis/iosdc-japan-2024-albatross/backend/fortee"
)

func FetchIcon(
	ctx context.Context,
	q *db.Queries,
	userID int,
) error {
	ctx, cancel := context.WithTimeout(ctx, 15*time.Second)
	defer cancel()

	// Fetch user.
	user, err := q.GetUserByID(ctx, int32(userID))
	if err != nil {
		return fmt.Errorf("failed to fetch user icon (uid=%d): %w", userID, err)
	}
	// Fetch user icon URL.
	avatarURL, err := fortee.GetUserAvatarURL(ctx, user.Username)
	if err != nil {
		return fmt.Errorf("failed to fetch user icon (uid=%d): %w", userID, err)
	}
	// Download user icon file.
	filePath := fmt.Sprintf("/files/img/%s/icon%s", url.PathEscape(user.Username), path.Ext(avatarURL))
	if err := downloadFile(ctx, fortee.Endpoint+avatarURL, "/data"+filePath); err != nil {
		return fmt.Errorf("failed to fetch user icon (uid=%d): %w", userID, err)
	}
	// Save user icon path.
	if err := q.UpdateUserIconPath(ctx, db.UpdateUserIconPathParams{
		UserID:   int32(userID),
		IconPath: &filePath,
	}); err != nil {
		return fmt.Errorf("failed to fetch user icon (uid=%d): %w", userID, err)
	}
	return nil
}

func downloadFile(ctx context.Context, url string, filePath string) error {
	req, err := http.NewRequestWithContext(ctx, "GET", url, nil)
	if err != nil {
		return fmt.Errorf("failed to download file (%s): %w", url, err)
	}

	client := &http.Client{}
	res, err := client.Do(req)
	if err != nil {
		return fmt.Errorf("failed to download file (%s): %w", url, err)
	}
	defer res.Body.Close()

	if res.StatusCode != http.StatusOK {
		return fmt.Errorf("failed to download file (%s): status %d", url, res.StatusCode)
	}

	fileDir := filepath.Dir(filePath)
	if err := os.MkdirAll(fileDir, 0755); err != nil {
		return fmt.Errorf("failed to create directory (%s): %w", fileDir, err)
	}

	file, err := os.Create(filePath)
	if err != nil {
		return fmt.Errorf("failed to open file (%s): %w", filePath, err)
	}
	defer file.Close()

	_, err = io.Copy(file, res.Body)
	if err != nil {
		return fmt.Errorf("failed to save file (%s): %w", filePath, err)
	}

	return nil
}