-
Notifications
You must be signed in to change notification settings - Fork 0
/
meower.ino
424 lines (356 loc) · 12.9 KB
/
meower.ino
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
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
#include <ArduinoJson.h>
#include <HTTPClient.h>
#include <Preferences.h>
#include <WiFi.h>
#include <WebServer.h>
#include <ctime>
#include <Arduino.h>
Preferences preferences;
WebServer server(80);
const char* meowerAPI = "https://api.meower.org/home?autoget=1&page=1";
const char* version = "1.1.0";
unsigned long lastTimestamp = 0;
bool firstRun = true;
char base64_table[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
char decodedToken[44]; // Global variable to store the decoded token
char base64_decode_char(char c) {
if (c >= 'A' && c <= 'Z') {
return c - 'A';
} else if (c >= 'a' && c <= 'z') {
return c - 'a' + 26;
} else if (c >= '0' && c <= '9') {
return c - '0' + 52;
} else if (c == '+') {
return 62;
} else if (c == '/') {
return 63;
} else {
return 0;
}
}
void base64_decode(const char* input, char* output) {
int len = strlen(input);
int i = 0;
int j = 0;
while (i < len) {
char a = base64_decode_char(input[i++]);
char b = base64_decode_char(input[i++]);
char c = base64_decode_char(input[i++]);
char d = base64_decode_char(input[i++]);
output[j++] = (a << 2) | (b >> 4);
output[j++] = (b << 4) | (c >> 2);
output[j++] = (c << 6) | d;
}
output[j] = '\0';
}
void setup() {
Serial.begin(115200);
while (!Serial) continue; // Wait for Serial to be ready
Serial.println("---------------- Meower for ESP32 ----------------");
Serial.print("Created with ❤️ by JoshAtticus | Version ");
Serial.println(version);
Serial.println("--------------------------------------------------");
initializeWiFi(); // Initialize WiFi connection
const char* encodedToken = "cDNxUEVBRE5JRzJoUjMweHdtU0EtY1hLRzJKdjFNTHJjTWhwbXhxakd5VQ==";
base64_decode(encodedToken, decodedToken);
server.on("/", HTTP_GET, handleRoot);
server.on("/posts", HTTP_GET, handlePosts);
server.on("/post", HTTP_POST, handlePost);
server.begin();
}
void loop() {
server.handleClient();
// Fetch new posts every second, if connected
if (WiFi.status() == WL_CONNECTED) {
fetchPosts();
} else {
Serial.println("WiFi not connected. Attempting to reconnect...");
reconnectWiFi();
}
// Check for serial input to handle "wifi", "post: ", or "username: " commands
if (Serial.available()) {
String input = Serial.readStringUntil('\n');
input.trim();
if (input == "wifi") {
// Clear existing credentials and restart WiFi setup
preferences.begin("wifi", false);
preferences.clear();
preferences.putString("configured", "false"); // Add this line to indicate that WiFi setup is needed
preferences.end();
initializeWiFi();
} else if (input.startsWith("post: ")) {
String content = input.substring(6); // Extract content after "post: "
sendPost(content);
} else if (input.startsWith("username: ")) {
String newUsername = input.substring(10); // Extract username after "username: "
setUsername(newUsername);
}
}
delay(1000);
}
void setUsername(const String& newUsername) {
if (newUsername.length() > 0) {
// Save the new username to preferences
preferences.begin("meower", false);
preferences.putString("username", newUsername);
preferences.end(); // Data is saved, close the preferences
// Print a confirmation message
Serial.print("Username set to: ");
Serial.println(newUsername);
} else {
Serial.println("Username cannot be blank.");
}
}
void initializeWiFi() {
preferences.begin("wifi", false);
bool isConfigured = preferences.getBool("configured", false);
if (!isConfigured) {
askForWiFiCredentials();
} else {
String ssid = preferences.getString("ssid", "");
String password = preferences.getString("password", "");
preferences.end(); // Close the Preferences before connecting
connectToWiFi(ssid, password);
}
preferences.begin("meower", false); // Use a separate namespace for the username
String username = preferences.getString("username", "");
preferences.end();
if (username == "") {
askForUsername();
}
}
void askForUsername() {
Serial.println("Enter Username (must not be blank!):");
while (!Serial.available()) { delay(100); } // Wait for input
String username = Serial.readStringUntil('\n');
username.trim(); // Remove any newline or whitespace
if (username.length() > 0) {
// Save Username to preferences under "meower" namespace
preferences.begin("meower", false);
preferences.putString("username", username);
preferences.end(); // Data is saved, close the preferences
Serial.print("Username set to: ");
Serial.println(username);
} else {
Serial.println("Username cannot be blank.");
}
}
void askForWiFiCredentials() {
// Clear any existing credentials
preferences.clear();
// Clear the serial buffer to ensure there's no leftover input
while (Serial.available() > 0) {
Serial.read();
}
Serial.println("Enter SSID:");
while (!Serial.available()) { delay(100); } // Wait for input
String ssid = Serial.readStringUntil('\n');
ssid.trim(); // Remove any newline or whitespace
Serial.println("Enter Password:");
while (!Serial.available()) { delay(100); } // Wait for input
String password = Serial.readStringUntil('\n');
password.trim(); // Remove any newline or whitespace
// Save SSID and Password to preferences
preferences.begin("wifi", false);
preferences.putString("ssid", ssid);
preferences.putString("password", password);
preferences.putBool("configured", true);
preferences.end();
Serial.println("WiFi credentials saved.");
// Attempt to connect with the new credentials
connectToWiFi(ssid, password);
}
void connectToWiFi(const String& ssid, const String& password) {
WiFi.begin(ssid.c_str(), password.c_str());
Serial.print("Connecting to WiFi");
unsigned long startAttemptTime = millis();
// Set a timeout period for the connection attempt (e.g., 15 seconds)
unsigned long connectionTimeout = 15 * 1000; // 15,000 milliseconds
// Attempt to connect until the timeout is reached
while (WiFi.status() != WL_CONNECTED &&
millis() - startAttemptTime < connectionTimeout) {
delay(500);
Serial.print(".");
}
if (WiFi.status() == WL_CONNECTED) {
Serial.println(" connected!");
Serial.print("Connected to ");
Serial.println(ssid);
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
Serial.print("API Address: ");
Serial.print(WiFi.localIP());
Serial.println("/");
Serial.println("--------------------------------------------------");
} else {
Serial.println(" connection failed!");
WiFi.disconnect(); // Disconnect from the WiFi network
askForWiFiCredentials(); // Ask for credentials again
}
}
void sendPost(const String& content) {
preferences.begin("meower", true); // Open "meower" namespace to retrieve the username
String username = preferences.getString("username", "");
preferences.end(); // Close the preferences after retrieving the username
if (username != "" && content != "") {
DynamicJsonDocument doc(1024);
doc["message"] = content;
doc["name"] = username;
String requestBody;
serializeJson(doc, requestBody);
HTTPClient http;
String webhookUrl = "https://webhooks.meower.org/webhook/";
String id = "1fc2e472-0a27-42d7-a2cd-f2c00e79424e";
String chatId = "home";
String postUrl = webhookUrl + id + "/" + decodedToken + "/" + chatId + "/post";
http.begin(postUrl);
http.addHeader("Content-Type", "application/json");
int httpResponseCode = http.POST(requestBody);
if (httpResponseCode == 200) { // Check specifically for 200 status code
Serial.println("Post sent successfully!");
} else {
Serial.println("--------------------Error!--------------------");
Serial.print("Failed to send post! Error code was ");
Serial.println(httpResponseCode);
Serial.print("HTTP response: ");
Serial.println(http.getString()); // Print the full HTTP response
Serial.println("----------------------------------------------");
}
http.end();
} else {
Serial.println("Username or content missing.");
}
}
void fetchPosts() {
if (WiFi.status() == WL_CONNECTED) {
HTTPClient http;
http.begin(meowerAPI);
int httpCode = http.GET();
if (httpCode > 0) {
String payload = http.getString();
// Parse JSON
DynamicJsonDocument doc(8192); // Adjust size for your needs
deserializeJson(doc, payload);
JsonArray posts = doc["autoget"].as<JsonArray>();
// Assume the first post is the latest; adjust if a newer one is found
JsonObject latestPost = posts[0];
unsigned long latestTimestamp = latestPost["t"]["e"].as<unsigned long>();
// Find the latest post in the current fetched posts
for (JsonObject post : posts) {
unsigned long postTimestamp = post["t"]["e"].as<unsigned long>();
if (postTimestamp > latestTimestamp) {
latestTimestamp = postTimestamp;
latestPost = post; // Update the latest post
}
}
// Check if the latest post is newer than the last one we've seen
if (latestTimestamp > lastTimestamp) {
String username = latestPost["u"].as<String>();
String message = latestPost["p"].as<String>();
// Check if the username is "Discord", "Revower", or "Webhooks"
bool isBridgedUser = username == "Discord" || username == "Revower";
bool isWebhookUser = username == "Webhooks";
bool isESP32User = username == "ESP32Meower";
if (isBridgedUser) {
username = "(BRIDGED)"; // Replace with "(BRIDGED)"
} else if (isWebhookUser) {
username = "(WEBHOOK)"; // Replace with "(WEBHOOK)"
}
// Print the latest post
Serial.print(username);
// Only print the colon if it's not a special user
if (!isBridgedUser && !isWebhookUser) {
Serial.print(": ");
} else {
Serial.print(" "); // Print a space after the special tag
}
Serial.println(message);
// Update lastTimestamp with the latest post's timestamp
lastTimestamp = latestTimestamp;
}
} else {
Serial.println("Error on HTTP request");
}
http.end();
} else {
Serial.println("WiFi not connected. Reconnecting...");
reconnectWiFi();
}
}
void reconnectWiFi() {
// Retrieve credentials from preferences
preferences.begin("wifi", true);
String ssid = preferences.getString("ssid");
String password = preferences.getString("password");
preferences.end();
// Reconnect to WiFi
WiFi.begin(ssid.c_str(), password.c_str());
}
void handleRoot() {
server.send(200, "application/json", getPostsJson());
}
void handlePosts() {
server.send(200, "application/json", getPostsJson());
}
void handlePost() {
if (server.hasArg("plain")) {
String content = server.arg("plain");
DynamicJsonDocument json(1024);
deserializeJson(json, content);
String message = json["message"].as<String>();
sendPost(message);
server.send(200, "application/json", "{\"success\": true}");
} else {
server.send(400, "application/json", "{\"error\": \"Message missing in request body\"}");
}
}
String getFormattedDateTime(unsigned long timestamp) {
time_t time = (time_t)timestamp;
struct tm* timeinfo;
char buffer[80];
timeinfo = localtime(&time);
strftime(buffer, sizeof(buffer), "%d/%m/%Y at %I:%M:%S %p", timeinfo);
return String(buffer);
}
String getPostsJson() {
DynamicJsonDocument doc(8192); // Adjust size for your needs
JsonArray postsArray = doc.createNestedArray("posts");
if (WiFi.status() == WL_CONNECTED) {
HTTPClient http;
http.begin(meowerAPI);
int httpCode = http.GET();
if (httpCode > 0) {
String payload = http.getString();
// Parse JSON
DynamicJsonDocument doc(8192); // Adjust size for your needs
deserializeJson(doc, payload);
JsonArray posts = doc["autoget"].as<JsonArray>();
// Add posts to the response JSON
for (JsonObject post : posts) {
String postId = post["_id"].as<String>();
bool isDeleted = post["isDeleted"].as<bool>();
String username = post["u"].as<String>();
String message = post["p"].as<String>();
unsigned long timestamp = post["t"]["e"].as<unsigned long>();
// Create a JSON object for each post
JsonObject postObject = postsArray.createNestedObject();
postObject["username"] = username;
postObject["message"] = message;
postObject["post_id"] = postId;
postObject["is_deleted"] = isDeleted;
postObject["timestamp"] = timestamp;
postObject["formatted_datetime"] = getFormattedDateTime(timestamp);
}
} else {
Serial.println("Error on HTTP request");
}
http.end();
} else {
Serial.println("WiFi not connected. Reconnecting...");
reconnectWiFi();
}
// Serialize the JSON document to a string
String response;
serializeJson(doc, response);
return response;
}