summaryrefslogtreecommitdiff
path: root/script/service/telemetry.lua
blob: 9fbbfe9efd379de4a638c6a9b1bec931ef0cd3db (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
local net      = require 'service.net'
local timer    = require 'timer'
local config   = require 'config'
local client   = require 'provider.client'
local nonil    = require 'without-check-nil'
local util     = require 'utility'
local platform = require 'bee.platform'

local tokenPath = (ROOT / 'log' / 'token'):string()
local token = util.loadFile(tokenPath)
if not token then
    token = ('%016X'):format(math.random(0, math.maxinteger))
    util.saveFile(tokenPath, token)
end

log.info('Telemetry Token:', token)

local function getClientName()
    nonil.enable()
    local clientName    = client.info.clientInfo.name
    local clientVersion = client.info.clientInfo.version
    nonil.disable()
    return table.concat({clientName, clientVersion}, ' ')
end

local function send(link, msg)
    link:write(('s4'):pack(msg))
end

local function pushClientInfo(link)
    send(link, string.pack('zzz'
        , 'pulse'
        , token
        , getClientName()
    ))
end

local function pushPlatformInfo(link)
    send(link, string.pack('zzzzz'
        , 'platform'
        , token
        , ('%s %s'):format(platform.OS, platform.Arch)
        , ('%s %s'):format(platform.CRT, platform.CRTVersion)
        , ('%s %s'):format(platform.Compiler, platform.CompilerVersion)
    ))
end

local function pushErrorLog(link)
    if not log.firstError then
        return
    end
    local err = log.firstError
    log.firstError = nil
    send(link, string.pack('zzzz'
        , 'error'
        , token
        , getClientName()
        , ('%q'):format(err)
    ))
end

timer.wait(5, function ()
    timer.loop(300, function ()
        if not config.config.telemetry.enable then
            return
        end
        local suc, link = pcall(net.connect, 'tcp', 'moe-loli.love', 11577)
        if not suc then
            suc, link = pcall(net.connect, 'tcp', '119.45.194.183', 11577)
        end
        if not suc or not link then
            return
        end
        function link:on_connect()
            pushClientInfo(link)
            pushPlatformInfo(link)
            pushErrorLog(link)
            self:close()
        end
    end)()
    timer.loop(1, function ()
        if not config.config.telemetry.enable then
            return
        end
        net.update()
    end)
end)