go-roblox/asset.go

105 lines
2.1 KiB
Go

package roblox
import (
"fmt"
"io"
"io/ioutil"
"net/http"
"net/url"
"strconv"
"strings"
)
type AssetUploadOptions struct {
Name string
AssetID int
Description string
Public bool
Comments bool
Group int
}
type AssetUploadResponse struct {
AssetID int64 `json:"AssetId"`
AssetVersionID int64 `json:"AssetVersionId"`
}
func (s *Session) CreateAsset(options *AssetUploadOptions, f io.Reader) (int, error) {
endpoint, err := url.Parse("https://data.roblox.com/Data/Upload.ashx?json=1&type=Model&genreTypeId=1")
if err != nil {
return -1, err
}
query := endpoint.Query()
query.Set("name", options.Name)
query.Set("description", options.Description)
query.Set("assetid", strconv.Itoa(options.AssetID))
// Comments
if options.Comments {
query.Set("allowComments", "true")
} else {
query.Set("allowComments", "false")
}
// Public
if options.Public {
query.Set("ispublic", "true")
} else {
query.Set("ispublic", "false")
}
// Group
if options.Group > 0 {
query.Set("groupId", strconv.Itoa(options.Group))
}
endpoint.RawQuery = query.Encode()
req, err := http.NewRequest("POST", endpoint.String(), nil)
req.Header.Set("user-agent", "Roblox")
// Perform request
resp, err := s.client.Do(req)
if err != nil {
return -1, err
}
defer resp.Body.Close()
if resp.StatusCode == 403 && resp.Header.Get("X-Csrf-Token") != "" {
req, err := http.NewRequest("POST", endpoint.String(), f)
req.Header.Set("user-agent", "Roblox")
req.Header.Set("x-csrf-token", strings.Trim(resp.Header["X-Csrf-Token"][0], " "))
// Perform request
resp, err = s.client.Do(req)
if err != nil {
return -1, err
}
defer resp.Body.Close()
}
if resp.StatusCode != 200 {
return -1, fmt.Errorf(resp.Status)
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return -1, err
}
return strconv.Atoi(string(body))
}
func (s *Session) Download(id int) (io.Reader, error) {
resp, err := s.client.Get("https://assetgame.roblox.com/Asset/?id=" + strconv.Itoa(id))
if err != nil {
return nil, err
}
if resp.StatusCode != 200 {
return nil, fmt.Errorf(resp.Status)
}
return resp.Body, nil
}