reprogl
113 строк · 2.2 Кб
1package repositories2
3import (4"database/sql"5"errors"6
7"github.com/doug-martin/goqu/v9"8"xelbot.com/reprogl/container"9"xelbot.com/reprogl/models"10"xelbot.com/reprogl/utils"11trackmodels "xelbot.com/reprogl/utils/tracking/models"12)
13
14type TrackingRepository struct {15DB *sql.DB16}
17
18func (tr *TrackingRepository) GetAgentByHash(hash string) (*models.TrackingAgent, error) {19query := `20SELECT
21ta.id,
22ta.user_agent,
23ta.hash,
24ta.is_bot,
25ta.created_at
26FROM tracking_agent AS ta
27WHERE (ta.hash = ?)`
28
29agent := &models.TrackingAgent{}30
31err := tr.DB.QueryRow(query, hash).Scan(32&agent.ID,33&agent.UserAgent,34&agent.Hash,35&agent.IsBot,36&agent.CreatedAt)37
38if err != nil {39if errors.Is(err, sql.ErrNoRows) {40return nil, models.RecordNotFound41} else {42return nil, err43}44}45
46return agent, nil47}
48
49func (tr *TrackingRepository) SaveTrackingAgent(activity *trackmodels.Activity) (int, error) {50query := `INSERT INTO tracking_agent51(user_agent, hash, is_bot, created_at)
52VALUES(?, ?, ?, ?)`
53
54result, err := tr.DB.Exec(55query,56activity.UserAgent,57container.MD5(activity.UserAgent),58activity.IsBot(),59activity.Time,60)61if err != nil {62return 0, err63}64
65id, err := result.LastInsertId()66if err != nil {67return 0, err68}69
70return int(id), nil71}
72
73func (tr *TrackingRepository) SaveTracking(activity *trackmodels.Activity, agentId, articleId int) error {74data := goqu.Record{75"ip_addr": activity.Addr.String(),76"is_cdn": activity.IsCDN,77"status_code": activity.Status,78"duration": activity.Duration.Microseconds(),79
80"time_created": activity.Time.Format("2006-01-02 15:04:05.000"),81}82
83if agentId > 0 {84data["user_agent_id"] = agentId85}86if articleId > 0 {87data["post_id"] = articleId88} else {89data["request_uri"] = utils.EllipticalTruncate(activity.RequestedURI, 128)90}91
92if activity.LocationID > 0 {93data["ip_long"] = activity.LocationID94}95
96if activity.Method != "GET" {97data["method"] = activity.Method98}99
100ds := goqu.Dialect("mysql8").Insert("tracking").Rows(data)101
102query, _, err := ds.ToSQL()103if err != nil {104return err105}106
107_, err = tr.DB.Exec(query)108if err != nil {109return err110}111
112return nil113}
114