2022-12-27 23:53:28 -05:00
|
|
|
package routes
|
|
|
|
|
|
|
|
import (
|
2022-12-28 11:33:26 -05:00
|
|
|
"anonymousoverflow/config"
|
2022-12-27 23:53:28 -05:00
|
|
|
"fmt"
|
2023-02-20 14:17:24 -05:00
|
|
|
"regexp"
|
2022-12-27 23:53:28 -05:00
|
|
|
"strings"
|
|
|
|
|
|
|
|
"github.com/gin-gonic/gin"
|
|
|
|
)
|
|
|
|
|
|
|
|
func GetHome(c *gin.Context) {
|
2022-12-28 11:33:26 -05:00
|
|
|
c.HTML(200, "home.html", gin.H{
|
|
|
|
"version": config.Version,
|
|
|
|
})
|
2022-12-27 23:53:28 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
type urlConversionRequest struct {
|
|
|
|
URL string `form:"url" binding:"required"`
|
|
|
|
}
|
|
|
|
|
2024-03-25 10:05:24 -07:00
|
|
|
var coreRegex = regexp.MustCompile(`(?:https?://)?(?:www\.)?([^/]+)(/(?:questions|q|a)/.+)`)
|
|
|
|
|
|
|
|
// Will return `nil` if `rawUrl` is invalid.
|
|
|
|
func translateUrl(rawUrl string) string {
|
|
|
|
coreMatches := coreRegex.FindStringSubmatch(rawUrl)
|
|
|
|
if coreMatches == nil {
|
|
|
|
return ""
|
|
|
|
}
|
|
|
|
|
|
|
|
domain := coreMatches[1]
|
|
|
|
rest := coreMatches[2]
|
|
|
|
|
|
|
|
exchange := ""
|
|
|
|
if domain == "stackoverflow.com" {
|
|
|
|
// No exchange parameter needed.
|
|
|
|
} else if sub, found := strings.CutSuffix(domain, ".stackexchange.com"); found {
|
|
|
|
if sub == "" {
|
|
|
|
return ""
|
|
|
|
} else if strings.Contains(sub, ".") {
|
|
|
|
// Anything containing dots is interpreted as a full domain, so we use the correct full domain.
|
|
|
|
exchange = domain
|
|
|
|
} else {
|
|
|
|
exchange = sub
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
exchange = domain
|
|
|
|
}
|
|
|
|
|
|
|
|
// Ensure we properly format the return string to avoid double slashes
|
|
|
|
if exchange == "" {
|
|
|
|
return rest
|
|
|
|
} else {
|
|
|
|
return fmt.Sprintf("/exchange/%s%s", exchange, rest)
|
|
|
|
}
|
|
|
|
}
|
2023-02-20 14:17:24 -05:00
|
|
|
|
2022-12-27 23:53:28 -05:00
|
|
|
func PostHome(c *gin.Context) {
|
|
|
|
body := urlConversionRequest{}
|
|
|
|
|
|
|
|
if err := c.ShouldBind(&body); err != nil {
|
|
|
|
c.HTML(400, "home.html", gin.H{
|
|
|
|
"errorMessage": "Invalid request body",
|
|
|
|
})
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2024-03-25 10:05:24 -07:00
|
|
|
translated := translateUrl(body.URL)
|
2023-08-21 02:01:56 -04:00
|
|
|
|
2024-03-25 10:05:24 -07:00
|
|
|
if translated == "" {
|
2022-12-27 23:53:28 -05:00
|
|
|
c.HTML(400, "home.html", gin.H{
|
2023-02-20 14:17:24 -05:00
|
|
|
"errorMessage": "Invalid stack overflow/exchange URL",
|
2022-12-27 23:53:28 -05:00
|
|
|
})
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2024-03-25 10:05:24 -07:00
|
|
|
c.Redirect(302, translated)
|
2022-12-27 23:53:28 -05:00
|
|
|
}
|