Skip to content

Commit

Permalink
Move get new postID from /share/ to embed endpoint
Browse files Browse the repository at this point in the history
  • Loading branch information
Wikidepia committed Jan 12, 2025
1 parent 2627731 commit cd00984
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 19 deletions.
28 changes: 28 additions & 0 deletions handlers/embed.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,10 @@ import (
"instafix/utils"
"instafix/views"
"instafix/views/model"
"log/slog"
"net/http"
"net/url"
"path"
"strconv"
"strings"

Expand All @@ -26,6 +28,24 @@ func mediaidToCode(mediaID int) string {
return shortCode
}

func getSharePostID(postID string) (string, error) {
req, err := http.NewRequest("HEAD", "https://www.instagram.com/share/reel/"+postID+"/", nil)
if err != nil {
return "", err
}
resp, err := http.DefaultTransport.RoundTrip(req)
if err != nil {
return "", err
}
defer resp.Body.Close()
redirURL, err := url.Parse(resp.Header.Get("Location"))
if err != nil {
return "", err
}
postID = path.Base(redirURL.Path)
return postID, nil
}

func Embed(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
viewsData := &model.ViewsData{}
Expand Down Expand Up @@ -72,6 +92,14 @@ func Embed(w http.ResponseWriter, r *http.Request) {
return
}
postID = mediaidToCode(mediaID)
} else if strings.Contains(r.URL.Path, "/share/") {
postID, err = getSharePostID(postID)
if err != nil {
slog.Error("Failed to get new postID from share URL", "postID", postID, "err", err)
viewsData.Description = "Failed to get new postID from share URL"
views.Embed(viewsData, w)
return
}
}

// If User-Agent is not bot, redirect to Instagram
Expand Down
19 changes: 0 additions & 19 deletions handlers/scraper/data.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ import (
"log/slog"
"net/http"
"net/url"
"path"
"strconv"
"strings"
"time"
Expand Down Expand Up @@ -68,24 +67,6 @@ func GetData(postID string) (*InstaData, error) {
return nil, errors.New("postID is not a valid Instagram post ID")
}

// Shortened postID
if postID[0] == 'B' {
req, err := http.NewRequest("HEAD", "https://www.instagram.com/share/reel/"+postID+"/", nil)
if err != nil {
return nil, err
}
resp, err := http.DefaultTransport.RoundTrip(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
redirURL, err := url.Parse(resp.Header.Get("Location"))
if err != nil {
return nil, err
}
postID = path.Base(redirURL.Path)
}

i := &InstaData{PostID: postID}
err := DB.View(func(tx *bolt.Tx) error {
b := tx.Bucket([]byte("data"))
Expand Down

0 comments on commit cd00984

Please sign in to comment.