add blink to creator app

This commit is contained in:
kulikov0 committed 2026-10-25 12:13:04 +01:00
1 parent 38fff05bb3
commit e0e82f5212
25 files changed
+317 -111

No files matched your search

+43
View File
@@ -8,6 +8,7 @@ import (
"io"
"net/http"
"net/url"
"path"
"strconv"
"strings"
@@ -22,6 +23,7 @@ const (
ClientUserAgent = "web_client (client 0.1.85)"
LoginLinkBase = "https://blinkmap.com/deeplink/webapp/login"
JoinLinkScheme = "blink://"
InviteLinkHost = "blinkmap.com"
)
var ErrLoginPending = errors.New("blink login is not approved yet")
@@ -65,6 +67,23 @@ func ParseChatID(input string) (int64, error) {
return chatID, nil
}
func ParseInviteKey(input string) (string, bool) {
trimmed := strings.TrimSpace(input)
if !strings.Contains(trimmed, "://") {
trimmed = "https://" + trimmed
}
parsed, err := url.Parse(trimmed)
if err != nil {
return "", false
}
host := parsed.Hostname()
invitePath := strings.TrimRight(parsed.Path, "/")
if (host != InviteLinkHost && host != "web."+InviteLinkHost) || !strings.Contains(invitePath, "/join/") {
return "", false
}
return path.Base(invitePath), true
}
func JoinLink(chatID int64) string {
return JoinLinkScheme + strconv.FormatInt(chatID, 10)
}
@@ -205,6 +224,30 @@ func CreateGroupChat(client *http.Client, accessToken string, accountID int64, n
return result.Data.ChatID, nil
}
func FetchInviteChatID(client *http.Client, accessToken, inviteKey string) (int64, error) {
var result struct {
ChatID int64 `json:"chat_id"`
AlreadyMember bool `json:"already_member"`
}
raw, status, err := apiDo(client, http.MethodGet, "/messenger/v2/chats/invite/"+url.PathEscape(inviteKey)+"/preview", accessToken, nil)
if err != nil {
return 0, fmt.Errorf("invite preview: %w", err)
}
if status != http.StatusOK {
return 0, &StatusError{Operation: "invite preview", Status: status, Body: common.BodySnippet(raw)}
}
if err := json.Unmarshal(raw, &result); err != nil {
return 0, fmt.Errorf("invite preview decode: %w", err)
}
if result.ChatID <= 0 {
return 0, fmt.Errorf("invite preview: no chat_id in %s", common.BodySnippet(raw))
}
if !result.AlreadyMember {
return 0, fmt.Errorf("invite preview: the account is not a member of chat %d, join it in the Blink app first", result.ChatID)
}
return result.ChatID, nil
}
func apiDo(client *http.Client, method, path, bearer string, body any) ([]byte, int, error) {
var reader io.Reader
if body != nil {
+53
View File
@@ -18,6 +18,9 @@ const (
RefreshTokenEntry = "blink_refresh_token"
accessTokenRefreshMargin = time.Hour
loginPollInterval = 5 * time.Second
loginDefaultTTL = 600
loginRenewFraction = 0.8
)
type Credentials struct {
@@ -51,6 +54,18 @@ func SaveTokens(path string, tokens TokenPair) error {
})
}
func LoginToFile(path string, client *http.Client, statusFn func(string), logFn func(string, ...any)) error {
tokens, err := waitForLogin(client, statusFn, logFn)
if err != nil {
return err
}
if err := SaveTokens(path, tokens); err != nil {
return fmt.Errorf("save tokens to %s: %w", path, err)
}
logFn("[login] approved, tokens saved to %s", path)
return nil
}
func (c *Credentials) AccessToken() (string, error) {
if accessTokenFresh(c.tokens) {
return c.tokens.Token, nil
@@ -67,6 +82,16 @@ func (c *Credentials) ConnectCall(chatID int64) (CallConnection, error) {
})
}
func (c *Credentials) ResolveChatID(room string) (int64, error) {
inviteKey, isInvite := ParseInviteKey(room)
if !isInvite {
return ParseChatID(room)
}
return withAccessToken(c, "invite preview", func(accessToken string) (int64, error) {
return FetchInviteChatID(c.client, accessToken, inviteKey)
})
}
func (c *Credentials) CreateChat(name string) (int64, error) {
return withAccessToken(c, "group chat create", func(accessToken string) (int64, error) {
accountID, err := FetchAccountID(c.client, accessToken)
@@ -149,3 +174,31 @@ func accessTokenFresh(tokens TokenPair) bool {
expiresIn := time.Until(time.Unix(tokens.TokenExpiresAt, 0))
return tokens.Token != "" && expiresIn > accessTokenRefreshMargin
}
func waitForLogin(client *http.Client, statusFn func(string), logFn func(string, ...any)) (TokenPair, error) {
for {
request, err := RequestLogin(client)
if err != nil {
return TokenPair{}, err
}
link := LoginLink(request.WAT)
logFn("[login] open this link on the phone with the Blink app: %s", link)
statusFn(common.StatusLoginLink + ":" + link)
ttl := request.TTL
if ttl <= 0 {
ttl = loginDefaultTTL
}
renewAt := time.Now().Add(time.Duration(float64(ttl)*loginRenewFraction) * time.Second)
for time.Now().Before(renewAt) {
time.Sleep(loginPollInterval)
tokens, err := PollLogin(client, request.WAT)
if err == nil {
return tokens, nil
}
if !errors.Is(err, ErrLoginPending) {
logFn("[login] poll: %v", err)
}
}
logFn("[login] login link expired, requesting a new one")
}
}
-83
View File
@@ -1,83 +0,0 @@
package blink
import (
"errors"
"fmt"
"io"
"net/http"
"strings"
"time"
"rsc.io/qr"
)
const (
loginPollInterval = 5 * time.Second
loginDefaultTTL = 600
loginRenewFraction = 0.8
qrQuietZone = 2
qrDarkCell = "\x1b[40m \x1b[0m"
qrLightCell = "\x1b[47m \x1b[0m"
)
func LoginToFile(path string, client *http.Client, out io.Writer, logFn func(string, ...any)) error {
tokens, err := LoginWithQR(client, out, logFn)
if err != nil {
return err
}
if err := SaveTokens(path, tokens); err != nil {
return fmt.Errorf("save tokens to %s: %w", path, err)
}
logFn("[login] approved, tokens saved to %s", path)
return nil
}
func LoginWithQR(client *http.Client, out io.Writer, logFn func(string, ...any)) (TokenPair, error) {
for {
request, err := RequestLogin(client)
if err != nil {
return TokenPair{}, err
}
link := LoginLink(request.WAT)
if err := WriteQR(out, link); err != nil {
return TokenPair{}, err
}
fmt.Fprintf(out, "\n Scan the QR with the Blink app, or open this link on the phone:\n %s\n\n", link)
ttl := request.TTL
if ttl <= 0 {
ttl = loginDefaultTTL
}
renewAt := time.Now().Add(time.Duration(float64(ttl)*loginRenewFraction) * time.Second)
for time.Now().Before(renewAt) {
time.Sleep(loginPollInterval)
tokens, err := PollLogin(client, request.WAT)
if err == nil {
return tokens, nil
}
if !errors.Is(err, ErrLoginPending) {
logFn("[login] poll: %v", err)
}
}
logFn("[login] QR expired, requesting a new one")
}
}
func WriteQR(out io.Writer, text string) error {
code, err := qr.Encode(text, qr.M)
if err != nil {
return err
}
var builder strings.Builder
for y := -qrQuietZone; y < code.Size+qrQuietZone; y++ {
for x := -qrQuietZone; x < code.Size+qrQuietZone; x++ {
if code.Black(x, y) {
builder.WriteString(qrDarkCell)
} else {
builder.WriteString(qrLightCell)
}
}
builder.WriteString("\n")
}
_, err = io.WriteString(out, builder.String())
return err
}