From 96e1c4b42454c030abf81dfe4c14de7605bfbae6 Mon Sep 17 00:00:00 2001 From: Skeris Date: Thu, 14 Apr 2022 20:43:13 +0300 Subject: [PATCH] -- --- Dockerfile | 2 +- DockerfileStaging | 10 ++++++ app/app.go | 18 +++++++++- dal/mongo/dal.go | 56 ++++++++++++++++++++++++++--- go.mod | 1 + ops/deployStaging | 33 +++++++++++++++++ service/service.go | 89 +++++++++++++++++++++++++++++++++++++++------- 7 files changed, 190 insertions(+), 19 deletions(-) create mode 100644 DockerfileStaging create mode 100755 ops/deployStaging diff --git a/Dockerfile b/Dockerfile index 5c6741f..10bd31c 100644 --- a/Dockerfile +++ b/Dockerfile @@ -4,7 +4,7 @@ COPY prod.crt / COPY prod.key / ENV APP_ADDR=:1488 ENV BB_IS_PROD=true -ENV BB_MONGO_URI=mongodb://mongodb +ENV BB_MONGO_URI=mongodb://mongodb,mongodb2 ENV MINIO_ENDPOINT=minio:9001 RUN apk add --no-cache ca-certificates CMD ["/heruvym"] diff --git a/DockerfileStaging b/DockerfileStaging new file mode 100644 index 0000000..5c6741f --- /dev/null +++ b/DockerfileStaging @@ -0,0 +1,10 @@ +FROM alpine +ADD heruvym / +COPY prod.crt / +COPY prod.key / +ENV APP_ADDR=:1488 +ENV BB_IS_PROD=true +ENV BB_MONGO_URI=mongodb://mongodb +ENV MINIO_ENDPOINT=minio:9001 +RUN apk add --no-cache ca-certificates +CMD ["/heruvym"] diff --git a/app/app.go b/app/app.go index a554d13..6c82921 100644 --- a/app/app.go +++ b/app/app.go @@ -3,11 +3,13 @@ package app import ( rAL "bitbucket.org/skeris/profile/dal" "context" + "encoding/json" "errors" "fmt" "github.com/BlackBroker/trashlog/wrappers/zaptg" "github.com/skeris/appInit" "go.uber.org/zap/zapcore" + tb "gopkg.in/tucnak/telebot.v2" "heruvym/dal/minio" "heruvym/dal/mongo" "heruvym/middleware" @@ -19,6 +21,7 @@ import ( "os" "os/signal" "syscall" + "time" "github.com/themakers/hlog" "go.uber.org/zap" @@ -152,7 +155,20 @@ func New(ctx context.Context, opts interface{}) (appInit.CommonApp, error) { return nil, err } - heruvym := service.New(blobStore, database, connRoles, logger) + newBot, err := tb.NewBot(tb.Settings{ + Token: "5240336345:AAG6ZXm6IYqsIZn7SoJTltJWviOXhVa4D0c", + Verbose: false, + ParseMode: tb.ModeHTML, + Poller: &tb.LongPoller{ + Timeout: time.Second, + }, + }) + if err != nil { + logger.Emit(json.Token(err)) + return nil, err + } + + heruvym := service.New(blobStore, database, connRoles, logger, newBot) interrupt := make(chan os.Signal, 1) signal.Notify(interrupt, os.Interrupt, syscall.SIGTERM) diff --git a/dal/mongo/dal.go b/dal/mongo/dal.go index 502c63a..2e12011 100644 --- a/dal/mongo/dal.go +++ b/dal/mongo/dal.go @@ -235,6 +235,7 @@ func (d *DAL) CreateTicket( Title: title, State: model.StateOpen, CreatedAt: time.Now(), + UpdatedAt: time.Now(), Rate: -1, TopMessage: model.Message{ ID: xid.New().String(), @@ -387,7 +388,7 @@ func (d *DAL) YieldActiveTickets( } func (d *DAL) YieldTickets(ctx context.Context, limit int64) ([]model.Ticket, int64, error) { - sort := bson.M{"State": -1, "UpdatedAt": 1} + sort := bson.D{{"State", -1}, {"UpdatedAt", 1}} cursor, err := d.colTck.Find(ctx, bson.M{}, options.Find().SetLimit(limit).SetSort(sort)) if err != nil { @@ -415,7 +416,7 @@ func (d *DAL) YieldUserTickets(ctx context.Context, userID string, limit int64) "UserID": userID, } - sort := bson.M{"State": -1, "UpdatedAt": 1} + sort := bson.D{{"State", -1}, {"UpdatedAt", 1}} cursor, err := d.colTck.Find(ctx, query, options.Find().SetSort(sort).SetLimit(limit)) if err != nil { @@ -638,9 +639,9 @@ func (d *DAL) GetTicketPage( } } - sort := bson.M{"State": -1, "UpdatedAt": 1} + sort := bson.D{{"State", -1}, {"UpdatedAt", -1}} - cur, err := d.colTck.Find(ctx, query, options.Find().SetLimit(limit).SetSkip(skip*limit).SetSort(sort)) + cur, err := d.colTck.Find(ctx, query, options.Find().SetSort(sort).SetLimit(limit).SetSkip(skip*limit)) if err != nil { return nil, 0, err } @@ -683,7 +684,7 @@ func (d *DAL) GetMessagesPage(ctx context.Context, } } - sort := bson.M{"UpdatedAt": 1} + sort := bson.D{{"UpdatedAt", 1}} cur, err := d.colMsg.Find(ctx, query, options.Find().SetLimit(limit).SetSkip(limit*offset).SetSort(sort)) if err != nil { @@ -732,3 +733,48 @@ func (d *DAL) SetAnswerer(ctx context.Context, ticket, answerer string) error { return nil } +type Additional struct { + Email string + Uid int64 +} +type Identites struct { + ID string `bson:"_id"` + Identites []Identity `bson:"Identities"` +} +type Identity struct { + Name string `bson:"Name"` + Identity string `bson:"Identity"` +} +type UidTechs struct { + DisplayID int64 `bson:"display_id"` + ID string `bson:"_id"` +} +func (d *DAL) GetAdditionalData(ctx context.Context, id string) (*Additional, error) { + result := Additional{} + idens := Identites{} + if err := d.client.Database("bb-identity").Collection("tp-users").FindOne(ctx, bson.M{ + "_id": id, + }, options.FindOne().SetProjection(bson.D{{ + "Identities",1, + }})).Decode(&idens); err != nil { + return nil, err + } + + for _, iden := range idens.Identites { + fmt.Println(iden.Name,iden) + if iden.Name == "email" { + result.Email = iden.Identity + } + } + + u := UidTechs{} + if err := d.client.Database("profile").Collection("profile").FindOne(ctx, bson.M{ + "_id": id, + }, options.FindOne().SetProjection( bson.D{{ + "display_id",1, + }})).Decode(&u); err != nil { + return nil, err + } + result.Uid = u.DisplayID + return &result, nil +} diff --git a/go.mod b/go.mod index 7fa70a9..09256a9 100644 --- a/go.mod +++ b/go.mod @@ -16,4 +16,5 @@ require ( github.com/themakers/hlog v0.0.0-20191205140925-235e0e4baddf go.mongodb.org/mongo-driver v1.5.3 go.uber.org/zap v1.17.0 + gopkg.in/tucnak/telebot.v2 v2.3.5 // indirect ) diff --git a/ops/deployStaging b/ops/deployStaging new file mode 100755 index 0000000..5f8a030 --- /dev/null +++ b/ops/deployStaging @@ -0,0 +1,33 @@ +#!/bin/sh -e + +cd .. + +echo "" +echo "" +echo "################################################################" +echo "#### BUILDING APP" +echo "################################################################" +echo "" +echo "" + +make build + +echo "" +echo "" +echo "################################################################" +echo "#### BUILDING DOCKER IMAGE" +echo "################################################################" +echo "" +echo "" + +sudo docker build -t 192.168.193.154:31320/heruvym:latest . -f DockerfileStaging + +echo "" +echo "" +echo "################################################################" +echo "#### BUILDING PUSH IMAGE" +echo "################################################################" +echo "" +echo "" + +sudo docker push 192.168.193.154:31320/heruvym \ No newline at end of file diff --git a/service/service.go b/service/service.go index ac61ee8..6eed544 100644 --- a/service/service.go +++ b/service/service.go @@ -8,6 +8,7 @@ import ( "fmt" "github.com/rs/xid" "github.com/themakers/hlog" + tb "gopkg.in/tucnak/telebot.v2" "heruvym/dal/minio" "heruvym/dal/mongo" "heruvym/jwt_adapter" @@ -23,14 +24,17 @@ type Heruvym struct { dal *mongo.DAL ral rAL.LayerMongoDb bs *minio.BlobStore + + notifier *tb.Bot } -func New(blobs *minio.BlobStore, dataAccessLayer *mongo.DAL, ral rAL.LayerMongoDb, log hlog.Logger) *Heruvym { +func New(blobs *minio.BlobStore, dataAccessLayer *mongo.DAL, ral rAL.LayerMongoDb, log hlog.Logger, notifier *tb.Bot) *Heruvym { return &Heruvym{ logger: log.Module("Service"), dal: dataAccessLayer, ral: ral, bs: blobs, + notifier:notifier, } } @@ -106,6 +110,7 @@ func (h *Heruvym) CreateTicket(w http.ResponseWriter, r *http.Request) { } if err != nil || len(tickets) == 0 { + ticketID, err = h.dal.CreateTicket( ctx, session.User, @@ -129,6 +134,31 @@ func (h *Heruvym) CreateTicket(w http.ResponseWriter, r *http.Request) { http.Error(w, "CannotCreateMessage", http.StatusInternalServerError) return } + + go func() { + role, _ := h.ral.GetProfileRole(context.TODO(), session.User) + if role != "user" && role != ""{ + return + } + if session.User != "" { + additional, err := h.dal.GetAdditionalData(context.TODO(), session.User) + fmt.Println("CAN NOT NOTIFY", err) + + if err == nil { + if _, err := h.notifier.Send(tb.ChatID(-1001344671794), + fmt.Sprintf("Поступило новое сообщение от пользователя %d с почтой %s", + additional.Uid, additional.Email)); err != nil { + fmt.Println("CAN NOT NOTIFY", err) + } + return + } + } + if _, err := h.notifier.Send(tb.ChatID(-1001344671794), + fmt.Sprintf("Поступило новое сообщение от незарегистриованного пользователя")); err != nil { + fmt.Println("CAN NOT NOTIFY", err) + } + }() + } else { ticketID = tickets[0].ID } @@ -193,16 +223,16 @@ func (h *Heruvym) allTickets(ctx context.Context, output chan interface{}) { } }() - data, count, err := h.dal.YieldTickets(ctx, 20) - - if err != nil { - output <- errors.New("cannot get tickets:" + err.Error()) - return - } - - if data != nil { - output <- GetTicketsResp{data, count} - } + //data, count, err := h.dal.YieldTickets(ctx, 20) + // + //if err != nil { + // output <- errors.New("cannot get tickets:" + err.Error()) + // return + //} + // + //if data != nil { + // output <- GetTicketsResp{data, count} + //} if err := h.dal.WatchAllTickets(ctx, func(ticket model.Ticket) error { output <- ticket @@ -220,7 +250,7 @@ func (h *Heruvym) userTickets(ctx context.Context, userID string, output chan in } }() - data, count, err := h.dal.YieldTickets(ctx, 20) + data, count, err := h.dal.YieldUserTickets(ctx,userID, 20) if err != nil { output <- errors.New("cannot get tickets:" + err.Error()) @@ -286,6 +316,32 @@ func (h *Heruvym) PutMessage( return errors.New("can not put message"), http.StatusInternalServerError } + + go func() { + role, _ := h.ral.GetProfileRole(context.TODO(), sess.User) + if role != "user" && role != ""{ + return + } + if sess.User != "" { + additional, err := h.dal.GetAdditionalData(context.TODO(), sess.User) + fmt.Println("CAN NOT NOTIFY", err) + + if err == nil { + if _, err := h.notifier.Send(tb.ChatID(-1001344671794), + fmt.Sprintf("Поступило новое сообщение от пользователя %d с почтой %s", + additional.Uid, additional.Email)); err != nil { + fmt.Println("CAN NOT NOTIFY", err) + } + return + } + } + if _, err := h.notifier.Send(tb.ChatID(-1001344671794), + fmt.Sprintf( + "Поступило новое сообщение от незарегистриованного пользователя")); err != nil { + fmt.Println("CAN NOT NOTIFY", err) + } + }() + if err := h.dal.UpdateTopMessage(ctx, request.TicketID, message); err != nil { return errors.New("can not update ticket"), http.StatusInternalServerError } @@ -407,6 +463,11 @@ func (h *Heruvym) Subscribe(ctx context.Context) chan interface{} { }() } else { go func() { + defer func() { + if v := recover(); v != nil { + fmt.Println("heryvym panic", v) + } + }() ticket, err := h.dal.GetTicket4User(ctx, ticketID, sess.User) if err != nil || ticket == nil { output <- errors.New("no tickets 4 user") @@ -519,6 +580,10 @@ func (h *Heruvym) CloseTicket(ctx context.Context, req CloseTicketReq) (*CloseTi return nil, http.StatusBadRequest } + if _, err := h.dal.PutMessage(ctx, "close", "close", "close", req.TicketID, []string{}); err != nil { + return nil, http.StatusBadRequest + } + return &CloseTicketResp{ TicketID: req.TicketID, }, http.StatusOK