converter/app/backend/binary.go
2025-06-22 23:12:02 -04:00

116 lines
2.7 KiB
Go

package backend
import (
"binaryserver/app/db"
"fmt"
"net/http"
"strconv"
"strings"
"github.com/go-rod/rod"
"github.com/go-rod/rod/lib/launcher"
)
var browser *rod.Browser
func asciiToBinary(text string) string {
var result []string
for _, char := range text {
binary := fmt.Sprintf("%08b", char) // 8-bit binary format
result = append(result, binary)
}
return strings.Join(result, " ")
}
func binaryToASCII(binary string) (string, error) {
// Ensure the length of the binary string is a multiple of 8
if len(binary)%8 != 0 {
return "", fmt.Errorf("binary string length must be a multiple of 8")
}
var sb strings.Builder
for i := 0; i < len(binary); i += 8 {
byteStr := binary[i : i+8]
b, err := strconv.ParseUint(byteStr, 2, 8)
if err != nil {
return "", fmt.Errorf("invalid binary sequence at position %d: %v", i, err)
}
sb.WriteByte(byte(b))
}
return sb.String(), nil
}
func instagramHandleExists(username string, bypass ...bool) string {
records, _ := db.GetRecords(db.QueryOptions{Where: fmt.Sprintf(`handle='%v'`, username)})
if len(records) > 0 && len(bypass) == 0 {
return records[0].URL
}
url := fmt.Sprintf("https://www.instagram.com/%s/", username)
page := browser.MustPage(url)
// Wait until body is loaded
page.MustWaitLoad().MustWaitIdle()
body := page.MustElement("body").MustText()
record := db.NewRecord(username, url)
// Instagram shows this for non-existent users
if strings.Contains(body, "Sorry, this page isn't available") {
record.URL = ""
db.SaveRecord(record)
return ""
}
db.SaveRecord(record)
return url
}
func BinaryHandler(w http.ResponseWriter, req *http.Request) {
binaryInput := strings.ReplaceAll(req.URL.Query().Get("binary"), " ", "")
var text string
var handle string
var err error
if binaryInput == "" {
asciiInput := req.URL.Query().Get("text")
if asciiInput == "" {
fmt.Fprintf(w, "Could not encode or decode!\n")
return
}
text = asciiToBinary(asciiInput)
fmt.Fprintf(w, "%v\n", GetFancyResponse(`<center><p>`+text+`</p></center>`, ""))
return
} else {
text, err = binaryToASCII(binaryInput)
text = strings.ReplaceAll(text, "@", "")
handle = text
}
if err != nil {
fmt.Fprintf(w, "Could not decode!\n")
return
}
var url string
if url = instagramHandleExists(text); url != "" {
text = `<center><a href="` + url + `">` + text + `</a></center>`
} else {
text = `<center><p>` + text + `</p></center>`
}
if url == "" {
handle = ""
}
fmt.Fprintf(w, "%v\n", GetFancyResponse(text, handle))
}
func init() {
path, _ := launcher.New().
Headless(true).
NoSandbox(true).
// Uncomment below to see browser
// Set("headless", "false").
Launch()
browser = rod.New().ControlURL(path).MustConnect()
}