Initial commit

Includes:
SCG parser
MTG cards search
This commit is contained in:
Artyom Belousov 2019-05-10 14:59:37 +03:00
commit 1af9226764
8 changed files with 181 additions and 0 deletions

View file

@ -0,0 +1,21 @@
package cardsinfo
import (
"github.com/stretchr/testify/assert"
"testing"
)
func TestFetchPriceOne(t *testing.T) {
price, _ := fetchPrice("$2.28")
assert.Equal(t, 2.28, price)
}
func TestFetchPriceTwo(t *testing.T) {
price, _ := fetchPrice("$2.28$1.14")
assert.Equal(t, 2.28, price)
}
func TestFetchPriceNo(t *testing.T) {
_, err := fetchPrice("")
assert.NotNil(t, err)
}

42
cardsinfo/names.go Normal file
View file

@ -0,0 +1,42 @@
package cardsinfo
import (
mtg "github.com/MagicTheGathering/mtg-sdk-go"
"strings"
)
func getCardName(card *mtg.Card) string {
switch card.Layout {
case "split":
return strings.Join(card.Names, " // ")
case "transform":
return strings.Join(card.Names, " | ")
default:
return card.Name
}
}
func getOriginalNameFromLang(name, lang string, channel chan string) {
cards, _, _ := mtg.NewQuery().Where(mtg.CardLanguage, lang).Where(mtg.CardName, name).PageS(1, 1)
if len(cards) > 0 {
name := getCardName(cards[0])
channel <- name
} else {
channel <- ""
}
}
func GetOriginalName(name string) string {
langs := []string{"Russian", ""}
channel := make(chan string)
for i := range langs {
go getOriginalNameFromLang(name, langs[i], channel)
}
for i := 0; i < len(langs); i++ {
name := <-channel
if name != "" {
return name
}
}
return ""
}

56
cardsinfo/scgprices.go Normal file
View file

@ -0,0 +1,56 @@
package cardsinfo
import (
"errors"
"github.com/antchfx/htmlquery"
"strconv"
"strings"
)
const SCGURL = "http://www.starcitygames.com/results?name="
func GetSCGPrices(name string) ([]CardPrice, error) {
splitted := strings.Split(name, " ")
scgName := strings.Join(splitted, "+")
url := SCGURL + scgName
doc, err := htmlquery.LoadURL(url)
if err != nil {
return nil, err
}
nodesOdd := htmlquery.Find(doc, "//tr[contains(@class, 'deckdbbody_row')]")
nodesEven := htmlquery.Find(doc, "//tr[contains(@class, 'deckdbbody2_row')]")
nodes := append(nodesOdd, nodesEven...)
prices := make([]CardPrice, 0)
for _, node := range nodes {
nameNode := htmlquery.FindOne(node, "//td[contains(@class, 'search_results_1')]")
if nameNode == nil {
continue
}
name := htmlquery.InnerText(nameNode)
priceNode := htmlquery.FindOne(node, "//td[contains(@class, 'search_results_9')]")
if priceNode == nil {
continue
}
priceS := htmlquery.InnerText(priceNode)
price, err := fetchPrice(priceS)
if err != nil {
continue
}
obj := CardPrice{
Name: name,
Price: price,
}
prices = append(prices, obj)
}
return prices, nil
}
func fetchPrice(price string) (float64, error) {
split := strings.Split(price, "$")
if len(split) < 2 {
return 0, errors.New("Not enough values")
}
p := split[1]
v, err := strconv.ParseFloat(p, 64)
return v, err
}

6
cardsinfo/structs.go Normal file
View file

@ -0,0 +1,6 @@
package cardsinfo
type CardPrice struct {
Name string
Price float64
}