Skip to content
This repository was archived by the owner on Aug 24, 2020. It is now read-only.

Commit

Permalink
adicionado ranking
Browse files Browse the repository at this point in the history
  • Loading branch information
jhonata-menezes committed May 31, 2017
1 parent 880b0fd commit 8f2c587
Show file tree
Hide file tree
Showing 15 changed files with 263 additions and 2,260 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
.idea/
config.json
1 change: 0 additions & 1 deletion api/partidas.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,6 @@ func (p *Partidas) Get(rodada int) {
res, err = request.Get(URL_PARTIDAS, 10)
}
if err != nil || res.StatusCode() != 200 {
log.Println("nao foi possivel obter a rodada", rodada, err)
return
}
if err = json.Unmarshal(res.Body(), &p); err != nil {
Expand Down
86 changes: 86 additions & 0 deletions bot/bot_kartolafc.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
package bot

import (
"gopkg.in/telegram-bot-api.v4"
"log"
"github.com/jhonata-menezes/kartolafc-backend/cmd"
"regexp"
"github.com/jhonata-menezes/kartolafc-backend/notification"
"errors"
)

func Run(channelNotification chan *notification.MessageNotification) {
// se nao tiver configurado nenhuma chave, bot nao e iniciado.
if cmd.Config.BotKey == "" {
log.Println("bot desabilitado")
return
}
bot, err := tgbotapi.NewBotAPI(cmd.Config.BotKey)
if err != nil {
log.Panic(err)
}
//bot.Debug = true
log.Printf("Authorized on account %s", bot.Self.UserName)

u := tgbotapi.NewUpdate(0)
u.Timeout = 60

updates, err := bot.GetUpdatesChan(u)

for update := range updates {
if update.Message == nil {
continue
}
if update.Message.From.ID != cmd.Config.BotIdClient {
continue
}
log.Printf("[ %s %s ] %s \n", update.Message.From.UserName, update.Message.From.ID, update.Message.Text)

msg := tgbotapi.NewMessage(update.Message.Chat.ID, "comando não encontrado")
msg.ReplyToMessageID = update.Message.MessageID
command := TelegramGetCommand(update.Message.Text)

switch command {
case "/n":
notify, err := getNotificacao(update.Message.Text)
if err == nil {
channelNotification <- &notify
msg.Text = "Notificaçao enviada"
} else {
msg.Text = "padrao incorreto"
}
break
}

bot.Send(msg)
}
}


func TelegramGetCommand(s string) string {
regComando, _ := regexp.Compile("(/[\\w-_]+) ?")
if regComando.MatchString(s) {
match := regComando.FindStringSubmatch(s)
return match[1]
}
return ""
}

func getNotificacao(s string) (notification.MessageNotification, error) {
regComando, _ := regexp.Compile("(/[\\w-_]+) ?\n(.*?)\n(.*?)\n(.*?)\n(.*?)$")
if regComando.MatchString(s) {
match := regComando.FindStringSubmatch(s)
return notification.MessageNotification{match[2], match[3], match[4], "", nil, match[5]}, nil
}
log.Println("errou")
return notification.MessageNotification{}, errors.New("nao foi possivel parsear")
}

func TelegramCommandGetMessage(s string) string {
regMensagem, _ := regexp.Compile("(/[\\w-_]+) (.*?)$")
if regMensagem.MatchString(s) {
match := regMensagem.FindStringSubmatch(s)
return match[2]
}
return ""
}
6 changes: 5 additions & 1 deletion cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,6 @@ func UpdateDestaques() {
destaques := api.Destaques{}
destaques.GetDestaques()
if len(destaques) > 0 {
//log.Printf("%#v", destaques)
CacheDestaques = destaques
}

Expand All @@ -49,6 +48,11 @@ func UpdateMercado() {
}

func UpdatePontuados() {
// para nao ficar enviando muitas requisicoes, ira apenas atualizar quando o mercado estiver fechado
for (CacheStatus.StatusMercado != 2) {
SleepCacheSecond(60)
}

pontuados := api.Pontuados{}
pontuados.GetPontuados()

Expand Down
28 changes: 19 additions & 9 deletions cmd/cmd.go
Original file line number Diff line number Diff line change
@@ -1,21 +1,31 @@
package cmd

import (
"github.com/spf13/cobra"
"os"
"io/ioutil"
"log"
"encoding/json"
)

var ServerBind string
var MongoDBIpPort string
type configTemplate struct {
ServerBind string `json:"bind"`
MongoDB string `json:"mongodb"`
VapidPrivate string `json:"vapidPrivate"`
BotKey string `json:"botKey"`
BotIdClient int `json:"botClientId"`
}

var Config configTemplate

func init() {
cmd := cobra.Command{}
cmd.Flags().StringVarP(&ServerBind, "bind", "b", "0.0.0.0:5015", "bind de interface ip:porta")
cmd.Flags().StringVarP(&MongoDBIpPort, "mongodb", "m", "127.0.0.1:27017", "conexao mongo")
//"Kartola FC é um wrapper da API do cartolafc"
c, err := ioutil.ReadFile("./config.json")
if err != nil {
log.Println("arquivo de configuraçao nao existe")
}

if err := cmd.Execute(); err != nil {
os.Exit(1)
err = json.Unmarshal(c, &Config)
if err != nil {
panic(err)
}
}

7 changes: 7 additions & 0 deletions config.json.dist
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"bind": "0.0.0.0:5015",
"mongodb": "127.0.0.1:27017",
"vapidPrivate": "",
"botKey": "",
"botClientId": 0
}
22 changes: 21 additions & 1 deletion controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ func GetTimes(response http.ResponseWriter, request *http.Request) {
times.Pesquisa = timePesquisado
times.GetTimes()

response.Write(JsonBuild(times))
render.JSON(response, request, times)
}

func GetTime(response http.ResponseWriter, request *http.Request) {
Expand Down Expand Up @@ -114,6 +114,26 @@ func AddNotificacao(response http.ResponseWriter, request *http.Request) {
render.JSON(response, request, DefaultMessage{"ok", "Inscrito com sucesso"})
}

func GetMelhoresRanking(response http.ResponseWriter, request *http.Request) {
responseDefault(response)
render.JSON(response, request, CacheRankingPontuadosMelhores)
}

func GetRankingTimeId(response http.ResponseWriter, request *http.Request) {
responseDefault(response)
timeId, err := strconv.Atoi(chi.URLParam(request, "id"))

if err != nil ||
timeId < 1 ||
timeId >= 15000000 ||
CacheRankingTimeIdPontuados[timeId].TimeId == 0{

render.JSON(response, request, DefaultMessage{"error", "id informado nao existe"})
}else{
render.JSON(response, request, CacheRankingTimeIdPontuados[timeId])
}
}

func responseDefault(w http.ResponseWriter) {
w.Header().Set("Access-Control-Allow-Origin", "*")
}
16 changes: 0 additions & 16 deletions json_build.go

This file was deleted.

2 changes: 1 addition & 1 deletion main/get_times.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ func main() {
idInicial, _:= strconv.Atoi(os.Args[1])
idFinal, _ := strconv.Atoi(os.Args[2])
jobs, _ := strconv.Atoi(os.Args[3])
session, err := mgo.Dial(cmd.MongoDBIpPort)
session, err := mgo.Dial(cmd.Config.MongoDB)
session.SetSocketTimeout(3 * time.Hour)
session.SetMode(mgo.Monotonic, true)
if err != nil {
Expand Down
88 changes: 58 additions & 30 deletions main/kartola.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,47 +8,38 @@ import (
"github.com/pressly/chi/render"
"github.com/jhonata-menezes/kartolafc-backend/cmd"
"log"
"io/ioutil"
"encoding/json"
"github.com/jhonata-menezes/kartolafc-backend/api"
"github.com/jhonata-menezes/kartolafc-backend/notification"
"time"
"github.com/goware/cors"
"github.com/jhonata-menezes/kartolafc-backend/bot"
"gopkg.in/mgo.v2"
"time"
"gopkg.in/mgo.v2/bson"
"encoding/json"
)

func main() {

go kartolafc.UpdateCache()

// temporario, para criar pontuados mesmo com mercado aberto
fileByte, err := ioutil.ReadFile("./pontuados.json")
if err == nil {
p := api.Pontuados{}
json.Unmarshal(fileByte, &p)
kartolafc.CachePontuados = p
// mongodb
session, err := mgo.Dial(cmd.Config.MongoDB)
if err != nil {
panic(err)
}
session.SetMode(mgo.Monotonic, true)
session.SetSocketTimeout(3 * time.Hour)
ranking(session.Copy())
//-------------------------------------------------------------------------------------

// temporario para teste com web push
// web push
go notification.AddSubscribe(&notification.ChannelSubscribe)
channelMessageNotification := make(chan notification.MessageNotification, 1000)
go notification.Notify(&channelMessageNotification)
go func (){
for {
m := notification.MessageNotification{}
m.Body = "teste 001"
m.Badge = "http://images.terra.com/2015/05/20/corinthians.png"
m.Icon = "http://images.terra.com/2015/05/20/corinthians.png"
m.Link = "http://kartolafc.com.br/#/ligas"
m.Title = "Title Teste"
m.Vibrate = []int{200, 100, 200}
channelMessageNotification <- m

log.Println("Enviando notificacao")
time.Sleep(30 * time.Second)
}
}()
// ----------------------------------
channelMessageNotification := make(chan *notification.MessageNotification, 1000)
go bot.Run(channelMessageNotification)
go notification.Notify(channelMessageNotification)

// pontuados
go getPontuados(session.Copy())

router := chi.NewRouter()
router.Use(middleware.DefaultCompress)
Expand All @@ -71,9 +62,46 @@ func main() {

kartolafc.BuildRoutes(router)
log.Println("Bora Cumpade.")
log.Println("listen", cmd.ServerBind)
err = http.ListenAndServe(cmd.ServerBind, router)
log.Println("listen", cmd.Config.ServerBind)
err = http.ListenAndServe(cmd.Config.ServerBind, router)
if err != nil {
panic(err)
}
}

func ranking(session *mgo.Session) {
colllection := session.DB("kartolafc").C("times")
go kartolafc.LoadInMemory(colllection)
}

func getPontuados(session *mgo.Session) {
// aguarda alguns segundos para o status estar disponivel
time.Sleep(3 * time.Second)
// se o mercado estiver fechado nao e preciso
if kartolafc.CacheStatus.StatusMercado == 2 {
return
}
// temporario, para criar pontuados mesmo com mercado aberto
collection := session.DB("kartolafc").C("pontuados")

var pontuadosResult interface{}
err := collection.Find(bson.M{"rodada": (kartolafc.CacheStatus.RodadaAtual - 1)}).One(&pontuadosResult)
if err != nil {
log.Println("erro na consulta dos pontuados", err)
return
}

pontuadosByte, err := json.Marshal(pontuadosResult)
if err != nil {
log.Println("nao foi possivel mapear os pontuados na interface")
}

pontuados := api.Pontuados{}
json.Unmarshal(pontuadosByte, &pontuados)

if pontuados.Rodada == 0 {
log.Println("quantidade de pontuados retornado da collection igual a zero")
return
}
kartolafc.CachePontuados = pontuados
}
Loading

0 comments on commit 8f2c587

Please sign in to comment.