go-roblox/asset.go

106 lines
2.2 KiB
Go
Raw Normal View History

2020-09-08 02:45:07 +00:00
package roblox
import (
"encoding/json"
"fmt"
"io"
"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"`
}
func (s *Session) CreateAsset(options *AssetUploadOptions, f io.Reader) (AssetUploadResponse, error) {
var aresp AssetUploadResponse
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 {
return aresp, err
}
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 {
return aresp, err
}
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 {
return aresp, err
}
defer resp.Body.Close()
}
2020-09-08 02:45:07 +00:00
if resp.StatusCode != 200 {
return aresp, fmt.Errorf(resp.Status)
}
if err := json.NewDecoder(resp.Body).Decode(&aresp); err != nil {
return aresp, err
}
return aresp, nil
}
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
}