go-roblox/asset.go

105 lines
2.1 KiB
Go
Raw Normal View History

2020-09-08 02:45:07 +00:00
package roblox
import (
"fmt"
"io"
2021-12-31 22:36:54 +00:00
"io/ioutil"
2020-09-08 02:45:07 +00:00
"net/http"
"net/url"
"strconv"
2021-03-17 12:46:02 +00:00
"strings"
2020-09-08 02:45:07 +00:00
)
type AssetUploadOptions struct {
Name string
2020-09-22 16:30:25 +00:00
AssetID int
2020-09-08 02:45:07 +00:00
Description string
Public bool
Comments bool
Group int
}
type AssetUploadResponse struct {
AssetID int64 `json:"AssetId"`
AssetVersionID int64 `json:"AssetVersionId"`
}
2021-12-31 22:36:54 +00:00
func (s *Session) CreateAsset(options *AssetUploadOptions, f io.Reader) (int, error) {
2020-09-22 16:30:25 +00:00
endpoint, err := url.Parse("https://data.roblox.com/Data/Upload.ashx?json=1&type=Model&genreTypeId=1")
2020-09-08 02:45:07 +00:00
if err != nil {
2021-12-31 22:36:54 +00:00
return -1, err
2020-09-08 02:45:07 +00:00
}
query := endpoint.Query()
query.Set("name", options.Name)
query.Set("description", options.Description)
2020-09-22 16:30:25 +00:00
query.Set("assetid", strconv.Itoa(options.AssetID))
2020-09-08 02:45:07 +00:00
// 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()
2021-03-17 12:46:02 +00:00
req, err := http.NewRequest("POST", endpoint.String(), nil)
req.Header.Set("user-agent", "Roblox")
2020-09-08 02:45:07 +00:00
// Perform request
resp, err := s.client.Do(req)
if err != nil {
2021-12-31 22:36:54 +00:00
return -1, err
2020-09-08 02:45:07 +00:00
}
defer resp.Body.Close()
2021-03-17 12:46:02 +00:00
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 {
2021-12-31 22:36:54 +00:00
return -1, err
2021-03-17 12:46:02 +00:00
}
defer resp.Body.Close()
}
2020-09-08 02:45:07 +00:00
if resp.StatusCode != 200 {
2021-12-31 22:36:54 +00:00
return -1, fmt.Errorf(resp.Status)
2020-09-08 02:45:07 +00:00
}
2021-12-31 22:36:54 +00:00
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return -1, err
2020-09-08 02:45:07 +00:00
}
2021-12-31 22:36:54 +00:00
return strconv.Atoi(string(body))
2020-09-08 02:45:07 +00:00
}
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
}