Compare commits

...

7 Commits

Author SHA1 Message Date
634d5a348a fix testFileUrl 2025-08-28 16:35:56 +08:00
488a91e651 show ramdom background image 2025-08-28 15:23:01 +08:00
3dd042a752 fix code style 2025-08-28 14:06:28 +08:00
43af0412ef fix layout 2025-08-28 11:37:55 +08:00
b17fa45d79 frontend for pinned resources 2025-08-28 11:28:59 +08:00
1925cf404e fix route 2025-08-28 10:58:57 +08:00
77ad261670 Add api for pinned resources 2025-08-28 10:38:55 +08:00
15 changed files with 279 additions and 44 deletions

View File

@@ -115,7 +115,7 @@ article {
ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, system-ui;
}
code {
pre code {
width: 100%;
display: block;
overflow-x: auto;

View File

@@ -162,6 +162,7 @@ export interface ServerConfig {
allow_normal_user_upload: boolean;
max_normal_user_upload_size_in_mb: number;
upload_prompt: string;
pinned_resources: number[];
}
export enum RSort {

View File

@@ -415,6 +415,10 @@ class Network {
);
}
async getPinnedResources(): Promise<Response<Resource[]>> {
return this._callApi(() => axios.get(`${this.apiBaseUrl}/resource/pinned`));
}
async createS3Storage(
name: string,
endPoint: string,

View File

@@ -95,7 +95,9 @@ function ActivityCard({ activity }: { activity: Activity }) {
) {
content = (
<div className={"mx-1"}>
<div className={"font-bold my-4 break-all"}>{activity.resource?.title}</div>
<div className={"font-bold my-4 break-all"}>
{activity.resource?.title}
</div>
{activity.resource?.image && (
<div>
<img
@@ -116,7 +118,9 @@ function ActivityCard({ activity }: { activity: Activity }) {
} else if (activity.type === ActivityType.NewFile) {
content = (
<div>
<h4 className={"font-bold py-2 break-all"}>{activity.file!.filename}</h4>
<h4 className={"font-bold py-2 break-all"}>
{activity.file!.filename}
</h4>
<div className={"text-sm my-1 comment_tile"}>
<Markdown>
{activity.file!.description.replaceAll("\n", " \n")}
@@ -170,8 +174,12 @@ function ActivityCard({ activity }: { activity: Activity }) {
src={network.getUserAvatar(activity.user!)}
/>
</div>
<span className={"mx-2 font-bold text-sm"}>{activity.user?.username}</span>
<span className={"ml-2 badge-sm sm:badge-md badge badge-primary badge-soft"}>
<span className={"mx-2 font-bold text-sm"}>
{activity.user?.username}
</span>
<span
className={"ml-2 badge-sm sm:badge-md badge badge-primary badge-soft"}
>
{messages[activity.type]}
</span>
</div>

View File

@@ -164,7 +164,8 @@ export default function CollectionPage() {
<span className="flex-1" />
{!collection.isPublic && (
<Badge className="badge-soft badge-error text-xs mr-2 shadow-xs">
<MdOutlineLock size={16} className="inline-block" /> {t("Private")}
<MdOutlineLock size={16} className="inline-block" />{" "}
{t("Private")}
</Badge>
)}
</div>

View File

@@ -2,10 +2,12 @@ import { useEffect, useState } from "react";
import ResourcesView from "../components/resources_view.tsx";
import { network } from "../network/network.ts";
import { app } from "../app.ts";
import { RSort } from "../network/models.ts";
import { Resource, RSort } from "../network/models.ts";
import { useTranslation } from "../utils/i18n";
import { useAppContext } from "../components/AppContext.tsx";
import Select from "../components/select.tsx";
import { useNavigate } from "react-router";
import { useNavigator } from "../components/navigator.tsx";
export default function HomePage() {
useEffect(() => {
@@ -31,6 +33,7 @@ export default function HomePage() {
return (
<>
<PinnedResources />
<div className={"flex pt-4 px-4 items-center"}>
<Select
values={[
@@ -58,3 +61,80 @@ export default function HomePage() {
</>
);
}
let cachedPinnedResources: Resource[] | null = null;
function PinnedResources() {
const [pinnedResources, setPinnedResources] = useState<Resource[]>([]);
const navigator = useNavigator();
useEffect(() => {
if (cachedPinnedResources != null) {
setPinnedResources(cachedPinnedResources);
return;
}
const prefetchData = app.getPreFetchData();
if (prefetchData && prefetchData.background) {
navigator.setBackground(network.getResampledImageUrl(prefetchData.background));
}
if (prefetchData && prefetchData.pinned) {
cachedPinnedResources = prefetchData.pinned;
setPinnedResources(cachedPinnedResources!);
return;
}
const fetchPinnedResources = async () => {
const res = await network.getPinnedResources();
if (res.success) {
cachedPinnedResources = res.data ?? [];
setPinnedResources(res.data ?? []);
}
};
fetchPinnedResources();
}, []);
if (pinnedResources.length == 0) {
return <></>;
}
return (
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4 p-4">
{pinnedResources.map((resource) => (
<PinnedResourceItem key={resource.id} resource={resource} />
))}
</div>
);
}
function PinnedResourceItem({ resource }: { resource: Resource }) {
const navigate = useNavigate();
return (
<a
href={`/resources/${resource.id}`}
className={"p-2 cursor-pointer block"}
onClick={(e) => {
e.preventDefault();
navigate(`/resources/${resource.id}`);
}}
>
<div
className={
"card shadow hover:shadow-md transition-shadow bg-base-100-tr82"
}
>
{resource.image != null && (
<figure>
<img
src={network.getResampledImageUrl(resource.image.id)}
alt="cover"
className="w-full aspect-[5/2] object-cover"
/>
</figure>
)}
<div className="p-4">
<h2 className="card-title break-all">{resource.title}</h2>
</div>
</div>
</a>
);
}

View File

@@ -14,12 +14,15 @@ export default function ManageServerConfigPage() {
const [config, setConfig] = useState<ServerConfig | null>(null);
const [pinnedResources, setPinnedResources] = useState("");
const [isLoading, setIsLoading] = useState(false);
useEffect(() => {
network.getServerConfig().then((res) => {
if (res.success) {
setConfig(res.data!);
setPinnedResources(res.data!.pinned_resources.join(","));
} else {
showToast({
message: res.message,
@@ -56,8 +59,25 @@ export default function ManageServerConfigPage() {
if (isLoading) {
return;
}
function isPositiveInteger(str: string) {
return /^[1-9]\d*$/.test(str);
}
for (const e of pinnedResources.split(",")) {
if (!isPositiveInteger(e)) {
showToast({
message: "Pinned resources must be a comma separated list of numbers",
type: "error",
});
return;
}
}
let pinned = pinnedResources.split(",").map((id) => parseInt(id));
setConfig({ ...config, pinned_resources: pinned });
setIsLoading(true);
const res = await network.setServerConfig(config);
const res = await network.setServerConfig({
...config,
pinned_resources: pinned,
});
if (res.success) {
showToast({
message: t("Update server config successfully"),
@@ -197,6 +217,14 @@ export default function ManageServerConfigPage() {
setConfig({ ...config, upload_prompt: e.target.value });
}}
></Input>
<Input
type="text"
value={pinnedResources}
label="Pinned resources"
onChange={(e) => {
setPinnedResources(e.target.value);
}}
></Input>
<InfoAlert
className="my-2"
message="If the cloudflare turnstile keys are not empty, the turnstile will be used for register and download."

View File

@@ -217,7 +217,8 @@ export default function ResourcePage() {
</div>
</button>
<Tags tags={resource.tags} />
<p className={"px-3 mt-2"}>
<div className={"px-3 mt-2 flex flex-wrap"}>
{resource.links &&
resource.links.map((l) => {
return (
@@ -238,7 +239,7 @@ export default function ResourcePage() {
);
})}
<CollectionDialog rid={resource.id} />
</p>
</div>
<div
className="tabs tabs-box my-4 mx-2 p-4 shadow"

View File

@@ -48,7 +48,13 @@ func setServerConfig(c fiber.Ctx) error {
return model.NewRequestError("Invalid request parameters")
}
config.SetConfig(sc)
if err := config.SetConfig(sc); err != nil {
return model.NewInternalServerError("Failed to save configuration")
}
if err := sc.Validate(); err != nil {
return model.NewRequestError(err.Error())
}
return c.JSON(model.Response[any]{
Success: true,

View File

@@ -267,6 +267,21 @@ func handleGetRandomResource(c fiber.Ctx) error {
})
}
func handleGetPinnedResources(c fiber.Ctx) error {
views, err := service.GetPinnedResources()
if err != nil {
return err
}
if views == nil {
views = []model.ResourceView{}
}
return c.Status(fiber.StatusOK).JSON(model.Response[[]model.ResourceView]{
Success: true,
Data: views,
Message: "Pinned resources retrieved successfully",
})
}
func AddResourceRoutes(api fiber.Router) {
resource := api.Group("/resource")
{
@@ -274,6 +289,7 @@ func AddResourceRoutes(api fiber.Router) {
resource.Get("/search", handleSearchResources)
resource.Get("/", handleListResources)
resource.Get("/random", handleGetRandomResource)
resource.Get("/pinned", handleGetPinnedResources)
resource.Get("/:id", handleGetResource)
resource.Delete("/:id", handleDeleteResource)
resource.Get("/tag/:tag", handleListResourcesWithTag)

View File

@@ -2,6 +2,7 @@ package config
import (
"encoding/json"
"errors"
"nysoure/server/utils"
"os"
"path/filepath"
@@ -34,6 +35,30 @@ type ServerConfig struct {
MaxNormalUserUploadSizeInMB int `json:"max_normal_user_upload_size_in_mb"`
// Prompt for upload page
UploadPrompt string `json:"upload_prompt"`
// PinnedResources is a list of resource IDs that are pinned to the top of the page.
PinnedResources []uint `json:"pinned_resources"`
}
func (c *ServerConfig) Validate() error {
if c.MaxUploadingSizeInMB <= 0 {
return errors.New("MaxUploadingSizeInMB must be positive")
}
if c.MaxFileSizeInMB <= 0 {
return errors.New("MaxFileSizeInMB must be positive")
}
if c.MaxDownloadsPerDayForSingleIP <= 0 {
return errors.New("MaxDownloadsPerDayForSingleIP must be positive")
}
if c.ServerName == "" {
return errors.New("ServerName must not be empty")
}
if c.ServerDescription == "" {
return errors.New("ServerDescription must not be empty")
}
if len(c.PinnedResources) > 8 {
return errors.New("PinnedResources must not exceed 8 items")
}
return nil
}
func init() {
@@ -51,6 +76,7 @@ func init() {
AllowNormalUserUpload: true,
MaxNormalUserUploadSizeInMB: 16,
UploadPrompt: "You can upload your files here.",
PinnedResources: []uint{},
}
} else {
data, err := os.ReadFile(p)
@@ -68,16 +94,17 @@ func GetConfig() ServerConfig {
return *config
}
func SetConfig(newConfig ServerConfig) {
func SetConfig(newConfig ServerConfig) error {
config = &newConfig
data, err := json.MarshalIndent(config, "", " ")
if err != nil {
panic(err)
return err
}
p := filepath.Join(utils.GetStoragePath(), "config.json")
if err := os.WriteFile(p, data, 0644); err != nil {
panic(err)
return err
}
return nil
}
func MaxUploadingSize() int64 {
@@ -127,3 +154,7 @@ func MaxNormalUserUploadSize() int64 {
func UploadPrompt() string {
return config.UploadPrompt
}
func PinnedResources() []uint {
return config.PinnedResources
}

View File

@@ -155,6 +155,16 @@ func serveIndexHtml(c fiber.Ctx) error {
preFetchData = url.PathEscape(string(preFetchDataJson))
}
}
} else if path == "/" || path == "" {
pinned, err := service.GetPinnedResources()
random, err1 := service.RandomCover()
if err == nil && err1 == nil {
preFetchDataJson, _ := json.Marshal(map[string]interface{}{
"pinned": pinned,
"background": random,
})
preFetchData = url.PathEscape(string(preFetchDataJson))
}
}
content = strings.ReplaceAll(content, "{{SiteName}}", siteName)

View File

@@ -445,32 +445,51 @@ func DownloadFile(fid, cfToken string) (string, string, error) {
}
func testFileUrl(url string) (int64, error) {
client := http.Client{
Timeout: 10 * time.Second,
}
req, err := http.NewRequest("HEAD", url, nil)
client := http.Client{Timeout: 10 * time.Second}
// Try HEAD request first, fallback to GET
for _, method := range []string{"HEAD", "GET"} {
req, err := http.NewRequest(method, url, nil)
if err != nil {
return 0, model.NewRequestError("failed to create HTTP request")
}
resp, err := client.Do(req)
if err != nil {
if method == "GET" {
return 0, model.NewRequestError("failed to send HTTP request")
}
continue // Try GET if HEAD fails
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
if method == "GET" {
return 0, model.NewRequestError("URL is not accessible, status code: " + resp.Status)
}
if resp.Header.Get("Content-Length") == "" {
continue // Try GET if HEAD fails
}
contentLengthStr := resp.Header.Get("Content-Length")
if contentLengthStr == "" {
if method == "GET" {
return 0, model.NewRequestError("URL does not provide content length")
}
contentLength, err := strconv.ParseInt(resp.Header.Get("Content-Length"), 10, 64)
if err != nil {
return 0, model.NewRequestError("failed to parse Content-Length header")
continue // Try GET if HEAD doesn't provide Content-Length
}
if contentLength <= 0 {
contentLength, err := strconv.ParseInt(contentLengthStr, 10, 64)
if err != nil || contentLength <= 0 {
if method == "GET" {
return 0, model.NewRequestError("Content-Length is not valid")
}
continue // Try GET if HEAD has invalid Content-Length
}
return contentLength, nil
}
return 0, model.NewRequestError("failed to get valid content length")
}
// downloadFile return nil if the download is successful or the context is cancelled

View File

@@ -2,6 +2,7 @@ package service
import (
"net/url"
"nysoure/server/config"
"nysoure/server/dao"
"nysoure/server/model"
"strconv"
@@ -286,3 +287,32 @@ func RandomResource(host string) (*model.ResourceDetailView, error) {
}
return &v, nil
}
var lastSuccessCover uint
func RandomCover() (uint, error) {
for retries := 0; retries < 5; retries++ {
v, err := dao.RandomResource()
if err != nil {
return 0, err
}
if len(v.Images) > 0 {
lastSuccessCover = v.Images[0].ID
return v.Images[0].ID, nil
}
}
return lastSuccessCover, nil
}
func GetPinnedResources() ([]model.ResourceView, error) {
ids := config.PinnedResources()
var views []model.ResourceView
for _, id := range ids {
r, err := dao.GetResourceByID(id)
if err != nil {
continue
}
views = append(views, r.ToView())
}
return views, nil
}