-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.rb
134 lines (118 loc) · 2.79 KB
/
app.rb
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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
require 'sinatra/base'
require 'mysql2'
require 'json'
require 'date'
require 'pp'
require 'dotenv/load'
def date2js d
return "Date(#{[d.year, d.month - 1, d.day].join(',')})"
end
class App < Sinatra::Base
get '/' do
send_file File.join(settings.public_folder, 'index.html')
end
get '/api/v1/status/room' do
content_type :json
sql =<<~SQL
SELECT
DATE_FORMAT(entry_at, "%Y-%m-%d") as `date`,
COUNT(DISTINCT user_id) as `count`
FROM YouTube_Sync_production.user_room_logs
WHERE created_at >= '2018-01-01'
GROUP BY date
ORDER BY date
SQL
data = __get_db.query(sql).map{|r| {date: Date.parse(r['date']), count: r['count']} }.sort_by{|e| e[:date]}
result = data.inject([]) do |before, v|
if before.last && (b = before.last[:date])
# if missed point found
if v[:date] - b > 1
(v[:date] - b - 1).to_i.times do |x|
before << {
date: (b + x + 1),
count: 0,
}
end
end
end
before << v
end
{
cols: [
{
label: 'Date',
type: 'date',
},
{
label: 'Users',
type: 'number',
},
],
rows: result.map{|r|
{
c: [
{ v: date2js(r[:date]) },
{ v: r[:count] },
]
}
}
}.to_json
end
get '/api/v1/status/chat' do
content_type :json
sql =<<~SQL
SELECT
DATE_FORMAT(created_at, "%Y-%m-%d") as `date`,
COUNT(DISTINCT id) as `count`
FROM YouTube_Sync_production.chats
WHERE created_at >= '2018-01-01'
AND chat_type = 'user'
GROUP BY date
ORDER BY date
SQL
data = __get_db.query(sql).map{|r| {date: Date.parse(r['date']), count: r['count']} }.sort_by{|e| e[:date]}
result = data.inject([]) do |before, v|
if before.last && (b = before.last[:date])
# if missed point found
if v[:date] - b > 1
(v[:date] - b - 1).to_i.times do |x|
before << {
date: (b + x + 1),
count: 0,
}
end
end
end
before << v
end
{
cols: [
{
label: 'Date',
type: 'date',
},
{
label: 'Messages',
type: 'number',
},
],
rows: result.map{|r|
{
c: [
{ v: date2js(r[:date]) },
{ v: r[:count] },
]
}
}
}.to_json
end
def __get_db
Mysql2::Client.new(
database: 'YouTube_Sync_production',
host: ENV['SYNCPOD_DB_HOST'],
username: ENV['SYNCPOD_DB_USERNAME'],
password: ENV['SYNCPOD_DB_PASSWORD'],
)
end
end
App.run!