package v1 import ( "encoding/json" "fmt" "html" "net/http" "net/url" "strings" "github.com/boojack/slash/api/auth" "github.com/boojack/slash/store" "github.com/labstack/echo/v4" "github.com/pkg/errors" ) func (s *APIV1Service) registerRedirectorRoutes(g *echo.Group) { g.GET("/*", func(c echo.Context) error { ctx := c.Request().Context() if len(c.ParamValues()) == 0 { return echo.NewHTTPError(http.StatusBadRequest, "invalid shortcut name") } shortcutName := c.ParamValues()[0] shortcut, err := s.Store.GetShortcut(ctx, &store.FindShortcut{ Name: &shortcutName, }) if err != nil { return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("failed to get shortcut, err: %s", err)).SetInternal(err) } if shortcut == nil { return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("not found shortcut with name: %s", shortcutName)) } if shortcut.Visibility != store.VisibilityPublic { userID, ok := c.Get(auth.UserIDContextKey).(int) if !ok { return echo.NewHTTPError(http.StatusUnauthorized, "Unauthorized") } if shortcut.Visibility == store.VisibilityPrivate && shortcut.CreatorID != userID { return echo.NewHTTPError(http.StatusUnauthorized, "Unauthorized") } } if err := s.createShortcutViewActivity(c, shortcut); err != nil { return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("failed to create activity, err: %s", err)).SetInternal(err) } return redirectToShortcut(c, shortcut) }) } func redirectToShortcut(c echo.Context, shortcut *store.Shortcut) error { isValidURL := isValidURLString(shortcut.Link) if shortcut.OpenGraphMetadata == nil || (shortcut.OpenGraphMetadata.Title == "" && shortcut.OpenGraphMetadata.Description == "" && shortcut.OpenGraphMetadata.Image == "") { if isValidURL { return c.Redirect(http.StatusSeeOther, shortcut.Link) } return c.String(http.StatusOK, shortcut.Link) } htmlTemplate := `
%s%s` metadataList := []string{ fmt.Sprintf(`