Skip to content

Commit

Permalink
Merge pull request #14 from ins0mn1a93/main
Browse files Browse the repository at this point in the history
Add StatisticsJob and modified some function
  • Loading branch information
ins0mn1a93 authored Dec 13, 2024
2 parents c6e4813 + 2236dcd commit fde9d42
Show file tree
Hide file tree
Showing 4 changed files with 208 additions and 9 deletions.
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,10 @@ In order to run the program correctly, you need to create a `config.toml` file i
capture_interval = '2s'
check_interval = '10s'

# The statistics period
# if you don't set it,the default value 60 is used
stat_period = 60

# The url of the web interface
# leave it empty if you don't want to use the web interface
web = '127.0.0.1:8080'
Expand Down
72 changes: 63 additions & 9 deletions frontend/src/pages/index.vue
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,60 @@ const pieViewOption = computed(() => {
],
}
})
const barFrequencyOption = computed(() => {
return {
dataset: {
source: stats.value,
},
color: ['#73c0de', '#fac858', '#ee6666'],
tooltip: {},
xAxis: { type: 'category' },
yAxis: { type: 'value' },
series: [
{
type: 'bar',
encode: { x: 0, y: [3, 4, 5] }, // 使用“可疑、恶意”的统计数据
},
],
}
})
const barGeoRankingOption = computed(() => {
return {
dataset: {
source: stats.value,
},
color: ['#91cc75'],
tooltip: {},
xAxis: { type: 'category' },
yAxis: { type: 'value' },
series: [
{
type: 'bar',
encode: { x: 0, y: 8 }, // 假设第 8 列是地理排名数据
},
],
}
})
const lineTrendOption = computed(() => {
return {
dataset: {
source: stats.value,
},
color: ['#5470c6'],
tooltip: {},
xAxis: { type: 'category' },
yAxis: { type: 'value' },
series: [
{
type: 'line',
encode: { x: 0, y: 8 }, // 使用趋势数据列
},
],
}
})
</script>

<template>
Expand All @@ -74,23 +128,23 @@ const pieViewOption = computed(() => {
<VChart :option="pieViewOption" theme="dark" autoresize />
</div>
<div class="subview-chart">
<h3>近七日威胁度</h3>
<VChart :option="pieViewOption" theme="dark" autoresize />
<h3>可疑及以上威胁度的频率</h3>
<VChart :option="barFrequencyOption" theme="dark" autoresize />
</div>
<div class="subview-chart">
<h3>近七日威胁度</h3>
<VChart :option="pieViewOption" theme="dark" autoresize />
<h3>地理位置排名</h3>
<VChart :option="barGeoRankingOption" theme="dark" autoresize />
</div>
<div class="subview-chart">
<h3>近七日威胁度</h3>
<VChart :option="pieViewOption" theme="dark" autoresize />
<h3>威胁度走势</h3>
<VChart :option="lineTrendOption" theme="dark" autoresize />
</div>
<div class="subview-chart">
<h3>近七日威胁度</h3>
<VChart :option="pieViewOption" theme="dark" autoresize />
<h3>情报来源占比</h3>
<VChart :option="pieViewOption" theme="dark" autoresize />
</div>
<div class="subview-chart">
<h3>近七日威胁度</h3>
<h3>To be continue</h3>
<VChart :option="pieViewOption" theme="dark" autoresize />
</div>
</div>
Expand Down
1 change: 1 addition & 0 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ func main() {
func init() {
if viper.GetDuration("check_interval") > 0 {
go func() {
util.StartStatisticsJob()
for {
tic.Check()
time.Sleep(viper.GetDuration("check_interval"))
Expand Down
140 changes: 140 additions & 0 deletions util/statistics.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,140 @@
package util

import (
"database/sql"
"fmt"
"log"
"time"

_ "github.com/mattn/go-sqlite3"
"github.com/spf13/viper"
)

type Statistics struct {
ID int64 `json:"id"`
Time int64 `json:"time"` // Calculated based on timestamp / stat_period
Risk_unknown_count int64 `json:"risk_unknown_count"`
Risk_safe_count int64 `json:"risk_safe_count"`
Risk_normal_count int64 `json:"risk_normal_count"`
Risk_suspicious_count int64 `json:"risk_suspicious_count"`
Risk_Malicious_count int64 `json:"risk_Malicious_count"`
Credibility_low_count int64 `json:"credibility_low_count"`
// To Add
}

var (
StatPeriod int
StatDB *sql.DB
)

func init() {
var err error
StatDB, err = sql.Open("sqlite3", "file:statistics.db")
if err != nil {
log.Panicln("Failed to open statistics database:", err)
}

_, err = StatDB.Exec(`
CREATE TABLE IF NOT EXISTS statistics (
id INTEGER,
time INTEGER,
risk_unknown_count INTEGER,
risk_safe_count INTEGER,
risk_normal_count INTEGER,
risk_suspicious_count INTEGER,
risk_Malicious_count INTEGER,
credibility_low_count INTEGER
-- To Add
)
`)
if err != nil {
log.Println("Failed to create table:", err)
}
StatDB.Exec("CREATE INDEX IF NOT EXISTS idx_time ON statistics (time)")
}

func (s *Statistics) Save() error {
_, err := StatDB.Exec(`
INSERT INTO statistics (id, time, risk_unknown_count, risk_safe_count, risk_normal_count,risk_suspicious_count, risk_Malicious_count, credibility_low_count)
VALUES(?, ?, ?, ?, ?, ?, ?, ?)
`,
s.ID,
s.Time,
s.Risk_unknown_count,
s.Risk_safe_count,
s.Risk_normal_count,
s.Risk_suspicious_count,
s.Risk_Malicious_count,
s.Credibility_low_count)
return err
}

// 定期更新统计数据
func StartStatisticsJob() {
go func() {
statPeriod := viper.GetInt("stat_period")
if statPeriod <= 0 {
statPeriod = 60
fmt.Println("The stat_period has been set as 60 seconds")
}

for {
time.Sleep(time.Duration(statPeriod) * time.Second)

timestamp := time.Now().Unix()
timeSlot := timestamp / int64(statPeriod)

stat := &Statistics{
Time: timeSlot,
Risk_unknown_count: calculateRiskUnknownCount(),
Risk_safe_count: calculateRiskSafeCount(),
Risk_normal_count: calculateRiskNormalCount(),
Risk_suspicious_count: calculateRiskSuspiciousCount(),
Risk_Malicious_count: calculateRiskMaliciousCount(),
Credibility_low_count: calculateCredibilityLowCount(),
}

if err := stat.Save(); err != nil {
log.Println("Error saving statistics:", err)
} else {
log.Printf("Statistics for time %d saved successfully\n", timeSlot)
}
}
}()
}

func calculateRiskUnknownCount() int64 {
var count int64
DB.QueryRow(`SELECT COUNT(*) FROM threats WHERE risk_level = ?`, "Unknown").Scan(&count)
return count
}

func calculateRiskSafeCount() int64 {
var count int64
DB.QueryRow(`SELECT COUNT(*) FROM threats WHERE risk_level = ?`, "Safe").Scan(&count)
return count
}

func calculateRiskNormalCount() int64 {
var count int64
DB.QueryRow(`SELECT COUNT(*) FROM threats WHERE risk_level = ?`, "Normal").Scan(&count)
return count
}

func calculateRiskSuspiciousCount() int64 {
var count int64
DB.QueryRow(`SELECT COUNT(*) FROM threats WHERE risk_level = ?`, "Suspicious").Scan(&count)
return count
}

func calculateRiskMaliciousCount() int64 {
var count int64
DB.QueryRow(`SELECT COUNT(*) FROM threats WHERE risk_level = ?`, "Malicious").Scan(&count)
return count
}

func calculateCredibilityLowCount() int64 {
var count int64
DB.QueryRow(`SELECT COUNT(*) FROM threats WHERE credibility_level = ?`, "Low").Scan(&count)
return count
}

0 comments on commit fde9d42

Please sign in to comment.