history/main.c

94 lines
1.9 KiB
C

#include "irc.h"
#include "cfg.h"
#include <time.h>
IRCC_client client;
void die(char *msg) {
puts(msg);
IRCC_close(&client);
exit(1);
}
struct tm GetTime(void) {
time_t t = time(NULL);
return *localtime(&t);
}
char *GetFilename(void) {
//Get filename + date
struct tm tm = GetTime();
size_t filename_size = strlen(client.channel + 1) + (sizeof(tm.tm_year) * 3) + strlen(EXT) + 3;
char *filename = malloc(filename_size + 1);
if (filename == NULL)
die("malloc returned NULL");
snprintf(filename, filename_size, "%s-%d-%d-%d%s", client.channel + 1, tm.tm_year + 1900, tm.tm_mon, tm.tm_mday, EXT);
return filename;
}
void WriteToFile(void) {
if (client.msg[1] == '.' || client.channel[0] != '#')
return;
char *filename = GetFilename();
FILE *fp = fopen(filename, "a");
free(filename);
if (fp == NULL) {
printf("Cant open file %s\n", client.channel);
return;
}
fprintf(fp, FORMAT, client.nick, client.msg + 1);
fclose(fp);
}
void recvinfo(void) {
while (1) {
unsigned int irc_status = IRCC_recv(&client);
if (irc_status == IRCC_DISCONNECTED)
die("Disconnected");
else if (client.nick != NULL && client.channel != NULL && client.msg != NULL && irc_status == IRCC_PRIVMSG)
WriteToFile();
else if (irc_status == IRCC_CONNECTED)
return;
}
}
int main(void) {
if (chdir(DIR))
die("Cant chdir");
//512 - size of raw buffer (max irc)
IRCC_init(&client);
int status = IRCC_connect(&client, HOST, PORT);
if (status == IRCC_ERROR)
die("Conn refused");
//Register
IRCC_register(&client, NICK);
//Recv motd and join in channel
recvinfo();
sleep(5);
for (size_t i = 0; i < sizeof(channels) / sizeof(char *); i++) {
if (channels[i] == NULL)
break;
size_t join_size = strlen("JOIN \r\n") + strlen(channels[i]) + 1;
char *tmp = malloc(join_size);
if (tmp == NULL)
die("malloc retured NULL");
snprintf(tmp, join_size, "JOIN %s\r\n", channels[i]);
send(client.socket, tmp, join_size, 0);
free(tmp);
}
recvinfo();
}