ALR/internal/dlcache/dlcache.go

95 lines
2.4 KiB
Go
Raw Normal View History

2025-01-18 16:30:02 +00:00
// This file was originally part of the project "LURE - Linux User REpository", created by Elara Musayelyan.
// It has been modified as part of "ALR - Any Linux Repository" by Евгений Храмов.
//
// ALR - Any Linux Repository
// Copyright (C) 2025 Евгений Храмов
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
2024-01-22 10:36:06 +00:00
package dlcache
import (
"context"
"os"
"path/filepath"
"gitea.plemya-x.ru/Plemya-x/ALR/internal/config"
2024-01-22 10:36:06 +00:00
)
2025-01-14 09:59:00 +00:00
type Config interface {
GetPaths(ctx context.Context) *config.Paths
}
type DownloadCache struct {
cfg Config
}
func New(cfg Config) *DownloadCache {
return &DownloadCache{
cfg,
}
}
func (dc *DownloadCache) BasePath(ctx context.Context) string {
return filepath.Join(
dc.cfg.GetPaths(ctx).CacheDir, "dl",
)
2024-01-22 10:36:06 +00:00
}
// New creates a new directory with the given ID in the cache.
// If a directory with the same ID already exists,
// it will be deleted before creating a new one.
2025-01-14 09:59:00 +00:00
func (dc *DownloadCache) New(ctx context.Context, id string) (string, error) {
2024-01-22 10:36:06 +00:00
h, err := hashID(id)
if err != nil {
return "", err
}
2025-01-14 09:59:00 +00:00
itemPath := filepath.Join(dc.BasePath(ctx), h)
2024-01-22 10:36:06 +00:00
fi, err := os.Stat(itemPath)
if err == nil || (fi != nil && !fi.IsDir()) {
err = os.RemoveAll(itemPath)
if err != nil {
return "", err
}
}
err = os.MkdirAll(itemPath, 0o755)
if err != nil {
return "", err
}
return itemPath, nil
}
// Get checks if an entry with the given ID
// already exists in the cache, and if so,
// returns the directory and true. If it
// does not exist, it returns an empty string
// and false.
2025-01-14 09:59:00 +00:00
func (dc *DownloadCache) Get(ctx context.Context, id string) (string, bool) {
2024-01-22 10:36:06 +00:00
h, err := hashID(id)
if err != nil {
return "", false
}
2025-01-14 09:59:00 +00:00
itemPath := filepath.Join(dc.BasePath(ctx), h)
2024-01-22 10:36:06 +00:00
_, err = os.Stat(itemPath)
if err != nil {
return "", false
}
return itemPath, true
}