99 lines
2.5 KiB
Go
99 lines
2.5 KiB
Go
package main
|
||
|
||
import (
|
||
"bytes"
|
||
"fmt"
|
||
"net/http"
|
||
"time"
|
||
|
||
"github.com/chromedp/chromedp"
|
||
"github.com/labstack/echo/v4"
|
||
qrcode "github.com/skip2/go-qrcode"
|
||
)
|
||
|
||
type advancedParameters struct {
|
||
URL string `json:"url"`
|
||
Resolution [2]int64 `json:"screen"` // width;height
|
||
СustomDelay *int `json:"delay"` // custom screenshot delay (in seconds). Defaults to a global delay
|
||
}
|
||
|
||
// Basic screenshot implementation
|
||
func screenshot(c echo.Context) error {
|
||
url := c.QueryParam("url")
|
||
if url == "" {
|
||
return c.String(http.StatusNotAcceptable, `Required parameter "url" is empty.`)
|
||
}
|
||
|
||
var buf []byte
|
||
err := readFromCache("screenshot_"+url, &buf)
|
||
|
||
if err != nil {
|
||
if err := chromedp.Run(ctx, fullScreenshot(url, [2]int64{1366, 768}, 90, time.Duration(screenshotDelay)*time.Second, &buf)); err != nil {
|
||
return err
|
||
}
|
||
if err := cache(buf, "screenshot_"+url); err != nil {
|
||
return err
|
||
}
|
||
}
|
||
|
||
reader := bytes.NewReader(buf)
|
||
return c.Stream(http.StatusOK, "image/png", reader)
|
||
}
|
||
|
||
// Advanced screenshot implementation
|
||
func advancedScreenshot(c echo.Context) error {
|
||
params := new(advancedParameters)
|
||
if err := c.Bind(¶ms); err != nil {
|
||
return err
|
||
}
|
||
|
||
if params.URL == "" {
|
||
return c.String(http.StatusNotAcceptable, `Required parameter "url" is empty.`)
|
||
}
|
||
|
||
if params.Resolution[0]+params.Resolution[1] < 10 {
|
||
return c.String(http.StatusBadRequest, `Resolution is too low.`)
|
||
}
|
||
|
||
if params.Resolution[0]+params.Resolution[1] > 32768 {
|
||
return c.String(http.StatusBadRequest, `Resolution is too big.`)
|
||
}
|
||
|
||
if params.СustomDelay == nil {
|
||
params.СustomDelay = &screenshotDelay
|
||
}
|
||
|
||
var buf []byte
|
||
filename := fmt.Sprintf("screenshot_%dx%d_%s_%ds", params.Resolution[0], params.Resolution[1], params.URL, *params.СustomDelay)
|
||
err := readFromCache(filename, &buf)
|
||
|
||
if err != nil {
|
||
if err := chromedp.Run(ctx, fullScreenshot(params.URL, params.Resolution, 90, time.Duration(*params.СustomDelay)*time.Second, &buf)); err != nil {
|
||
return err
|
||
}
|
||
if err := cache(buf, filename); err != nil {
|
||
return err
|
||
}
|
||
}
|
||
|
||
reader := bytes.NewReader(buf)
|
||
return c.Stream(http.StatusOK, "image/png", reader)
|
||
}
|
||
|
||
func qrCode(c echo.Context) error {
|
||
text := c.QueryParam("text")
|
||
if text == "" {
|
||
return c.String(http.StatusNotAcceptable, `Required parameter "text" is empty.`)
|
||
}
|
||
|
||
code, err := qrcode.Encode(text, qrcode.Medium, 100+len(text)*3)
|
||
if err != nil {
|
||
fmt.Printf("[WARNING] An error occurred while trying to generate QR-code:\n%s", err.Error())
|
||
return err
|
||
}
|
||
|
||
reader := bytes.NewReader(code)
|
||
|
||
return c.Stream(http.StatusOK, "image/png", reader)
|
||
}
|