-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcontroller.js
244 lines (205 loc) · 8.13 KB
/
controller.js
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
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
const { createClient } = require('@supabase/supabase-js');
const supabaseUrl = process.env.SUPABASE_URL;
const supabaseKey = process.env.SUPABASE_KEY;
const supabase = createClient(supabaseUrl, supabaseKey);
// Save user without last_message column
async function saveUser(chatId, username) {
try {
const { data, error: selectError } = await supabase
.from('users')
.select('user_id')
.eq('user_id', chatId)
.single();
if (selectError && selectError.code !== 'PGRST116') { // Allow "No Rows Found" error
console.error('Error fetching user:', selectError.message);
return;
}
if (data) {
console.log('User already exists:', data.user_id);
// update username if it's different
if (data.username !== username) {
const { error: updateError } = await supabase.from('users')
.update({ username: username })
.eq('user_id', chatId);
if (updateError) {
console.error('Error updating username:', updateError.message);
} else {
// console.log('Username updated:', chatId);
}
}
return;
}
const { error: insertError } = await supabase.from('users').insert([{
user_id: chatId,
username: username,
start_date: new Date(),
total_messages: 0,
// last message as yesterday to allow for first message
last_message_date: new Date(new Date().setDate(new Date().getDate() - 1)).toISOString().split('T')[0]
}]);
if (insertError) {
console.error('Error inserting user:', insertError.message);
} else {
// console.log('User successfully saved:', chatId);
}
} catch (error) {
console.error('Unexpected error while saving user:', error.message);
}
}
// Increment message count
async function incrementMessageCount(chatId) {
const { data, error } = await supabase
.from('users')
.select('total_messages, last_message_date')
.eq('user_id', chatId)
.single();
const today = new Date().toISOString().split('T')[0];
if (!data) {
// If no data is found, return default (user doesn't exist yet).
return { canSend: false, totalMessages: 0 };
}
let newMessageCount = data.total_messages;
// Handle case where last_message_date is null or it's not today
if (!data.last_message_date || data.last_message_date.split('T')[0] !== today) {
// Update the message count to 1 if it's a new day
await supabase.from('users')
.update({ total_messages: 1, last_message_date: today })
.eq('user_id', chatId);
newMessageCount = 1;
} else if (data.total_messages < 10) {
// If the user has sent less than 10 messages, increment the count
await supabase.from('users')
.update({ total_messages: data.total_messages + 1 })
.eq('user_id', chatId);
newMessageCount = data.total_messages + 1;
} else {
// If the user has reached the daily message limit, return false
return { canSend: false, totalMessages: 10 };
}
return { canSend: true, totalMessages: newMessageCount };
}
// Increment message count
async function checkMessageCount(chatId) {
const { data, error } = await supabase
.from('users')
.select('total_messages, last_message_date')
.eq('user_id', chatId)
.single();
const today = new Date().toISOString().split('T')[0];
if (!data) {
// If no data is found, return default (user doesn't exist yet).
return { canSend: false, totalMessages: 0 };
}
// Handle case where last_message_date is null or it's not today
if (!data.last_message_date || data.last_message_date.split('T')[0] !== today) {
// Update the message count to 1 if it's a new day
return { canSend: true };
} else if (data.total_messages < 10) {
return { canSend: true };
} else {
// If the user has reached the daily message limit, return false
return { canSend: false };
}
}
async function getMessageCount(chatId) {
const { data } = await supabase
.from('users')
.select('total_messages')
.eq('user_id', chatId)
.single();
return data ? data.total_messages : 0;
}
async function getUserSettings(chatId) {
try {
const { data, error } = await supabase
.from('users')
.select('username, is_premium, subscription_date, total_messages, default_language')
.eq('user_id', chatId)
.single();
if (error) {
console.error('Error fetching user settings:', error.message);
return null;
}
return data;
} catch (error) {
console.error('Unexpected error while fetching user settings:', error.message);
return null;
}
}
async function updateUserLanguage(chatId, language) {
try {
const { error } = await supabase
.from('users')
.update({ default_language: language })
.eq('user_id', chatId);
if (error) {
console.error('Error updating user language:', error.message);
return false;
}
return true;
} catch (error) {
console.error('Unexpected error while updating user language:', error.message);
return false;
}
}
async function getUserDefaultLanguage(chatId) {
try {
const { data, error } = await supabase
.from('users')
.select('default_language')
.eq('user_id', chatId)
.single();
if (error) {
console.error('Error fetching user default language:', error.message);
return 'en'; // Return 'en' as a fallback default language
}
return data?.default_language || 'en'; // If the user doesn’t have a default language, fallback to 'en'
} catch (error) {
console.error('Unexpected error while fetching default language:', error.message);
return 'en'; // Return 'en' as a fallback default language
}
}
async function getTotalUsers() {
try {
const { count, error } = await supabase
.from('users')
.select('*', { count: 'exact', head: true }); // Count rows without fetching data
if (error) {
console.error('Error getting total users:', error.message);
return 0; // Return 0 if there is an error
}
return count || 0; // Return count or fallback to 0
} catch (error) {
console.error('Unexpected error while getting total users:', error.message);
return 0; // Return 0 if there is an exception
}
}
async function isUserMemberOrSubscribed(bot, chatId) {
try {
// Check if the user is a member of the channel
const channelUsername = "@horansoftware";
const memberStatus = await bot.getChatMember(channelUsername, chatId);
if (
memberStatus.status === "member" ||
memberStatus.status === "administrator" ||
memberStatus.status === "creator"
) {
return true; // User is a member
}
// Check if the user is a premium subscriber
const { data, error } = await supabase
.from("users")
.select("is_premium")
.eq("user_id", chatId)
.single();
if (error) {
console.error("Error fetching user subscription status:", error.message);
return false; // Assume not subscribed on error
}
return data?.is_premium || false; // Return true if the user is premium, false otherwise
} catch (error) {
console.error("Error checking membership or subscription:", error.message);
return false; // Default to not a member or subscribed
}
}
module.exports = { saveUser, incrementMessageCount, getMessageCount, getUserSettings, updateUserLanguage, getUserDefaultLanguage, checkMessageCount, getTotalUsers, isUserMemberOrSubscribed };