@@ -2,10 +2,100 @@ package pg
22
33import (
44 "context"
5+ "time"
56
7+ "github.com/shellhub-io/shellhub/api/pkg/gateway"
8+ "github.com/shellhub-io/shellhub/api/store/pg/internal/entity"
69 "github.com/shellhub-io/shellhub/pkg/models"
710)
811
912func (pg * pg ) GetStats (ctx context.Context ) (* models.Stats , error ) {
10- return nil , nil
13+ var tenantID string
14+ if tenant := gateway .TenantFromContext (ctx ); tenant != nil {
15+ tenantID = tenant .ID
16+ }
17+
18+ onlineDevices := 0
19+ query := pg .driver .NewSelect ().
20+ Model ((* entity .Device )(nil )).
21+ Where ("disconnected_at IS NULL" ).
22+ Where ("seen_at > ?" , time .Now ().Add (- 2 * time .Minute )).
23+ Where ("status = ?" , "accepted" )
24+
25+ if tenantID != "" {
26+ query = query .Where ("namespace_id = (SELECT id FROM namespaces WHERE id = ?)" , tenantID )
27+ }
28+
29+ count , err := query .Count (ctx )
30+ if err != nil {
31+ return nil , fromSqlError (err )
32+ }
33+ onlineDevices = count
34+
35+ registeredDevices := 0
36+ query = pg .driver .NewSelect ().
37+ Model ((* entity .Device )(nil )).
38+ Where ("status = ?" , "accepted" )
39+
40+ if tenantID != "" {
41+ query = query .Where ("namespace_id = (SELECT id FROM namespaces WHERE id = ?)" , tenantID )
42+ }
43+
44+ count , err = query .Count (ctx )
45+ if err != nil {
46+ return nil , fromSqlError (err )
47+ }
48+ registeredDevices = count
49+
50+ pendingDevices := 0
51+ query = pg .driver .NewSelect ().
52+ Model ((* entity .Device )(nil )).
53+ Where ("status = ?" , "pending" )
54+
55+ if tenantID != "" {
56+ query = query .Where ("namespace_id = (SELECT id FROM namespaces WHERE id = ?)" , tenantID )
57+ }
58+
59+ count , err = query .Count (ctx )
60+ if err != nil {
61+ return nil , fromSqlError (err )
62+ }
63+ pendingDevices = count
64+
65+ rejectedDevices := 0
66+ query = pg .driver .NewSelect ().
67+ Model ((* entity .Device )(nil )).
68+ Where ("status = ?" , "rejected" )
69+
70+ if tenantID != "" {
71+ query = query .Where ("namespace_id = (SELECT id FROM namespaces WHERE id = ?)" , tenantID )
72+ }
73+
74+ count , err = query .Count (ctx )
75+ if err != nil {
76+ return nil , fromSqlError (err )
77+ }
78+ rejectedDevices = count
79+
80+ // activeSessions := 0
81+ // query = pg.driver.NewSelect().
82+ // Model((*entity.ActiveSession)(nil))
83+ //
84+ // if tenantID != "" {
85+ // query = query.Where("tenant_id = ?", tenantID)
86+ // }
87+ //
88+ // count, err = query.Count(ctx)
89+ // if err != nil {
90+ // return nil, fromSqlError(err)
91+ // }
92+ // activeSessions = count
93+
94+ return & models.Stats {
95+ RegisteredDevices : registeredDevices ,
96+ OnlineDevices : onlineDevices ,
97+ PendingDevices : pendingDevices ,
98+ RejectedDevices : rejectedDevices ,
99+ ActiveSessions : 0 ,
100+ }, nil
11101}
0 commit comments