Skip to content

Commit

Permalink
context (#12)
Browse files Browse the repository at this point in the history
  • Loading branch information
sizovilya authored Mar 3, 2021
1 parent 57a24ba commit 05d0515
Show file tree
Hide file tree
Showing 9 changed files with 38 additions and 35 deletions.
22 changes: 9 additions & 13 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -44,11 +44,6 @@ Copy this js code:
- After the login flow is completed, you should see a new log in the developer console that looks like: found npsso <64 character code>. Copy that 64 character code.
</details>

### How to get client_id and client_secret
- Go to https://account.sonyentertainmentnetwork.com/ and log in with your own credentials
- Open Chrome Dev Tools, go to Network tab and find `token` request, url - https://auth.api.sonyentertainmentnetwork.com/2.0/oauth/token
<img src="assets/screen.png" width="450">

### Functions at this moment
- You can get user profile info
- You can get trophy titles
Expand All @@ -64,8 +59,9 @@ import (
)

func main() {
lang := "ru" // full list here https://github.com/sizovilya/go-psn-api/blob/main/langs.go
region := "ru" // full list here https://github.com/sizovilya/go-psn-api/blob/main/regions.go
ctx := context.Background()
lang := "ru" // known list here https://github.com/sizovilya/go-psn-api/blob/main/langs.go, some languages are wrong and unsupported now, feel free to investigate for your own
region := "ru" // known list here https://github.com/sizovilya/go-psn-api/blob/main/regions.go, some regions are wrong and unsupported now, feel free to investigate for your own
npsso := "your npsso"
psnApi, err := psn.NewPsnApi(
lang,
Expand All @@ -76,34 +72,34 @@ func main() {
}

// This request will get access token and refresh token from Sony's servers
err = psnApi.AuthWithNPSSO(npsso)
err = psnApi.AuthWithNPSSO(ctx, npsso)
if err != nil {
panic(err)
}

// If you've obtained refresh token you may use it for next time
// If you obtain refresh token you may use it for next logins.
// Next logins should be like this:
// refreshToken, _ := psnApi.GetRefreshToken() // store refresh token somewhere for future logins by psnApi.AuthWithRefreshToken method
err = psnApi.AuthWithRefreshToken("your token") // get new access token
err = psnApi.AuthWithRefreshToken(ctx, "your token") // get new access token
if err != nil {
panic(err)
}

// How to get user's profile info
profile, err := psnApi.GetProfileRequest("geeek_52rus")
profile, err := psnApi.GetProfileRequest(ctx, "geeek_52rus")
if err != nil {
panic(err)
}
fmt.Print(profile)

// How to get trophy titles
trophyTitles, err := psnApi.GetTrophyTitles("geeek_52rus", 50, 0)
trophyTitles, err := psnApi.GetTrophyTitles(ctx, "geeek_52rus", 50, 0)
if err != nil {
panic(err)
}
fmt.Print(trophyTitles)
}

```

This project highly inspired by https://github.com/Tustin/psn-php. Some useful things like auth headers and params found in `Tustin/psn-php`.
<p align="center"> <img src="assets/gopher-dance.gif"> </p>
Binary file removed assets/screen.png
Binary file not shown.
18 changes: 9 additions & 9 deletions auth.go
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
package psn

import (
"context"
"fmt"
"net/http"
"net/url"
// "encoding/json"
// "bytes"
)

const (
Expand All @@ -20,11 +19,11 @@ type tokens struct {
}

// Method makes auth request to Sony's server and retrieves tokens
func (p *psn) AuthWithNPSSO(npsso string) error {
func (p *psn) AuthWithNPSSO(ctx context.Context, npsso string) error {
if npsso == "" {
return fmt.Errorf("npsso is empty")
}
tokens, err := p.authRequest(npsso)
tokens, err := p.authRequest(ctx, npsso)
if err != nil {
return fmt.Errorf("can't do auth request: %w", err)
}
Expand All @@ -36,7 +35,7 @@ func (p *psn) AuthWithNPSSO(npsso string) error {
}

// Method makes auth request to Sony's server and retrieves tokens
func (p *psn) AuthWithRefreshToken(refreshToken string) error {
func (p *psn) AuthWithRefreshToken(ctx context.Context, refreshToken string) error {
if refreshToken == "" {
return fmt.Errorf("refresh token is empty")
}
Expand All @@ -50,7 +49,7 @@ func (p *psn) AuthWithRefreshToken(refreshToken string) error {
postHeaders["Content-Type"] = "application/x-www-form-urlencoded"
postHeaders["Authorization"] = "Basic YWM4ZDE2MWEtZDk2Ni00NzI4LWIwZWEtZmZlYzIyZjY5ZWRjOkRFaXhFcVhYQ2RYZHdqMHY="
var tokens *tokens
err := p.post(postValues, fmt.Sprintf("%sauthz/v3/oauth/token", authUrl), postHeaders, &tokens)
err := p.post(ctx, postValues, fmt.Sprintf("%sauthz/v3/oauth/token", authUrl), postHeaders, &tokens)
if err != nil {
return fmt.Errorf("can't create new POST request %w: ", err)
}
Expand All @@ -64,7 +63,7 @@ func (p *psn) AuthWithRefreshToken(refreshToken string) error {
return nil
}

func (p *psn) authRequest(npsso string) (*tokens, error) {
func (p *psn) authRequest(ctx context.Context, npsso string) (*tokens, error) {
getValues := url.Values{}
getValues.Add("access_type", "offline")
getValues.Add("app_context", "inapp_ios")
Expand Down Expand Up @@ -98,7 +97,8 @@ func (p *psn) authRequest(npsso string) (*tokens, error) {
nextUrl := uri.String()

// not a best way to check redirect, refactor somewhere
req, err := http.NewRequest(
req, err := http.NewRequestWithContext(
ctx,
"GET",
nextUrl,
nil,
Expand Down Expand Up @@ -170,7 +170,7 @@ func (p *psn) authRequest(npsso string) (*tokens, error) {
postHeaders["Authorization"] = "Basic YWM4ZDE2MWEtZDk2Ni00NzI4LWIwZWEtZmZlYzIyZjY5ZWRjOkRFaXhFcVhYQ2RYZHdqMHY="

var tokens tokens
err = p.post(postValues, fmt.Sprintf("%sauthz/v3/oauth/token", authUrl), postHeaders, &tokens)
err = p.post(ctx, postValues, fmt.Sprintf("%sauthz/v3/oauth/token", authUrl), postHeaders, &tokens)
if err != nil {
return nil, fmt.Errorf("can't create new POST request: %w ", err)
}
Expand Down
1 change: 0 additions & 1 deletion helpers.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,3 @@ func isContain(arr []string, value string) bool {
}
return false
}

11 changes: 7 additions & 4 deletions http.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package psn

import (
"context"
"encoding/json"
"fmt"
"net/http"
Expand All @@ -10,8 +11,9 @@ import (

type headers map[string]string

func (p *psn) post(formData url.Values, url string, headers headers, value interface{}) error {
req, err := http.NewRequest(
func (p *psn) post(ctx context.Context, formData url.Values, url string, headers headers, value interface{}) error {
req, err := http.NewRequestWithContext(
ctx,
"POST",
url,
strings.NewReader(formData.Encode()),
Expand Down Expand Up @@ -45,8 +47,9 @@ func (p *psn) post(formData url.Values, url string, headers headers, value inter
return nil
}

func (p *psn) get(url string, headers headers, value interface{}) error {
req, err := http.NewRequest(
func (p *psn) get(ctx context.Context, url string, headers headers, value interface{}) error {
req, err := http.NewRequestWithContext(
ctx,
"GET",
url,
nil,
Expand Down
3 changes: 2 additions & 1 deletion langs.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ var languages = []string{
"ja",
"en",
"en-GB",
"en-US",
"fr",
"es",
"es-MX",
Expand All @@ -22,4 +23,4 @@ var languages = []string{
"ko",
"zh-CN",
"zh-TW",
}
}
9 changes: 5 additions & 4 deletions profile.go
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
package psn

import (
"context"
"fmt"
)

const usersApi = "-prof.np.community.playstation.net/userProfile/v1/users/"

const usersApi = "-prof.np.community.playstation.net/userProfile/v1/users/"

type AvatarUrls struct {
Size string `json:"size"`
Expand Down Expand Up @@ -57,12 +57,13 @@ type ProfileResponse struct {
}

// Method retrieves user profile info by PSN id
func (p *psn) GetProfileRequest(name string) (profile *Profile, err error) {
func (p *psn) GetProfileRequest(ctx context.Context, name string) (profile *Profile, err error) {
var h = headers{}
h["authorization"] = fmt.Sprintf("Bearer %s", p.accessToken)

userResponse := &ProfileResponse{}
err = p.get(
ctx,
fmt.Sprintf(
"https://%s%s%s/profile2?fields=onlineId,aboutMe,consoleAvailability,languagesUsed,avatarUrls,personalDetail,personalDetail(@default,profilePictureUrls),primaryOnlineStatus,trophySummary(level,progress,earnedTrophies),plus,isOfficiallyVerified,friendRelation,personalDetailSharing,presences(@default,platform),npId,blocking,following,currentOnlineId,displayableOldOnlineId,mutualFriendsCount,followerCount&profilePictureSizes=s,m,l&avatarSizes=s,m,l&languagesUsedLanguageSet=set4",
p.region,
Expand All @@ -75,5 +76,5 @@ func (p *psn) GetProfileRequest(name string) (profile *Profile, err error) {
if err != nil {
return nil, fmt.Errorf("can't do GET request: %w", err)
}
return &userResponse.Profile,nil
return &userResponse.Profile, nil
}
3 changes: 2 additions & 1 deletion regions.go
Original file line number Diff line number Diff line change
Expand Up @@ -61,4 +61,5 @@ var regions = []string{
"th",
"jp",
"kr",
}
"en-US",
}
6 changes: 4 additions & 2 deletions trophyTitle.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package psn

import (
"context"
"fmt"
"time"
)
Expand Down Expand Up @@ -52,15 +53,16 @@ type TrophyTitleResponse struct {
}

// Method retrieves user's trophy titles
func (p *psn) GetTrophyTitles(username string, limit, offset int32) (profile *TrophyTitleResponse, err error) {
func (p *psn) GetTrophyTitles(ctx context.Context, username string, limit, offset int32) (profile *TrophyTitleResponse, err error) {
var h = headers{}
h["authorization"] = fmt.Sprintf("Bearer %s", p.accessToken)
h["accept-language"] = "ru-RU"
//h["accept-language"] = "en-US"
h["Accept"] = "*/*"
h["Accept-Encoding"] = "gzip, deflate, br"

trophyTitleResponse := TrophyTitleResponse{}
err = p.get(
ctx,
fmt.Sprintf(
"https://%s%sfields=@default,trophyTitleSmallIconUrl&platform=PS3,PS4,PSVITA&limit=%d&offset=%d&comparedUser=%s&npLanguage=%s",
p.region,
Expand Down

0 comments on commit 05d0515

Please sign in to comment.