summaryrefslogtreecommitdiff
path: root/chatroom.c
blob: e2a6b1aaa531448c90028c2706b3e41a520e0fa9 (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
#include "client.h"
#include "chatroom.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

chatroom_t chatrooms[MAX_CHATROOMS];
int chatroom_count = 0;

void load_chatrooms(const char *filename) {
    FILE *fp = fopen(filename, "r");
    if (!fp) {
        perror("chatroom file");
        exit(1);
    }

    while (fscanf(fp, "%s %d %s %s %[^\n]",
                  chatrooms[chatroom_count].name,
                  &chatrooms[chatroom_count].users,
                  chatrooms[chatroom_count].created,
                  chatrooms[chatroom_count].time,
                  chatrooms[chatroom_count].topic) == 5) {
        chatroom_count++;
    }

    fclose(fp);
}

void print_chatroom_list(int sock) {
    send_to_client(sock, "room-name   #    created      time     topic\n");
    send_to_client(sock, "--------------------------------------------------------\n");
    for (int i = 0; i < chatroom_count; i++) {
        char line[BUFFER_SIZE];
        snprintf(line, sizeof(line), "%-10s %-4d %-12s %-8s %s\n",
                 chatrooms[i].name,
                 chatrooms[i].users,
                 chatrooms[i].created,
                 chatrooms[i].time,
                 chatrooms[i].topic);
        send_to_client(sock, line);
    }
    send_to_client(sock, "--------------------------------------------------------\n");
}

int join_chatroom(const char *name, client_t *cli) {
    for (int i = 0; i < chatroom_count; i++) {
        if (strcmp(chatrooms[i].name, name) == 0) {
            leave_chatroom(cli);
            strncpy(cli->room, name, sizeof(cli->room) - 1);
            chatrooms[i].users++;
            return 1;
        }
    }
    return 0;
}

void leave_chatroom(client_t *cli) {
    for (int i = 0; i < chatroom_count; i++) {
        if (strcmp(chatrooms[i].name, cli->room) == 0) {
            chatrooms[i].users--;
            break;
        }
    }
    strcpy(cli->room, "");
}