aboutsummaryrefslogtreecommitdiff
path: root/src/main.cpp
blob: dff2328c214528a389df3d33d7d3952a72c6bb89 (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
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
#include "../include/Channel.hpp"
#include "../include/ChannelSidePanel.hpp"
#include "../include/UsersSidePanel.hpp"
#include "../include/ChannelTopPanel.hpp"
#include "../include/Cache.hpp"
#include "../include/ResourceCache.hpp"
#include "../include/Video.hpp"
#include "../include/Command.hpp"
#include "../include/Settings.hpp"
#include "../include/ColorScheme.hpp"
#include <string>
#include <SFML/Graphics.hpp>
#include <cstring>
#include <boost/filesystem/path.hpp>
#include <odhtdb/Database.hpp>
#include <odhtdb/Signature.hpp>
#include <odhtdb/bin2hex.hpp>
#include <odhtdb/hex2bin.hpp>
#include <X11/Xlib.h>

using namespace std;
using namespace dchat;
using namespace TinyProcessLib;

string createChannelJoinKey(const unique_ptr<odhtdb::DatabaseCreateResponse> &databaseCreateResponse)
{
    string result;
    result += databaseCreateResponse->getRequestHash()->toString();
    result += "&";
    result += odhtdb::bin2hex((const char*)databaseCreateResponse->getNodeEncryptionKey()->data, databaseCreateResponse->getNodeEncryptionKey()->size);
    return result;
}

odhtdb::DatabaseNode createDatabaseNodeFromJoinKey(const string &joinKey)
{
    odhtdb::DatabaseNode result;
    
    string nodeHashStr = odhtdb::hex2bin(joinKey.c_str(), 64);
    memcpy(result.getRequestHash()->getData(), nodeHashStr.data(), nodeHashStr.size());
    
    string nodeEncryptionKeyStr = odhtdb::hex2bin(joinKey.c_str() + 65, 64);
    char *nodeEncryptionKeyRaw = new char[nodeEncryptionKeyStr.size()];
    result.getNodeEncryptionKey()->data = nodeEncryptionKeyRaw;
    result.getNodeEncryptionKey()->size = nodeEncryptionKeyStr.size();
    
    return result;
}

void channelAddStoredMessages(Channel *channel, const odhtdb::DatabaseStorageObjectList *nodeStorage)
{
    for(auto nodeStorageAddedObject : nodeStorage->objects)
    {
        if(nodeStorageAddedObject->decryptedObject.operation == odhtdb::DatabaseOperation::ADD_DATA)
        {
            User *user = channel->getUserByPublicKey(nodeStorageAddedObject->creatorPublicKey);
            if(!user)
            {
                fprintf(stderr, "Missing user? %s\n", nodeStorageAddedObject->creatorPublicKey.toString().c_str());
                continue;
            }
            string msg((const char*)nodeStorageAddedObject->decryptedObject.data.data, nodeStorageAddedObject->decryptedObject.data.size);
            channel->addLocalMessage(msg, user);
        }
    }
}

int main(int argc, char **argv)
{
    /*
    boost::filesystem::path programPath(argv[0]);
    auto parentPath = programPath.parent_path();
    printf("parent path: %s\n", parentPath.string().c_str());
    boost::filesystem::current_path(parentPath); // Ensures loading of resources works no matter which path we run this executable from
    */
    
    XInitThreads();
    sf::RenderWindow window(sf::VideoMode(1920, 1080), "dchat");
    window.setVerticalSyncEnabled(false);
    window.setFramerateLimit(60);
    
    odhtdb::Database database("bootstrap.ring.cx", 4222, Cache::getDchatDir());
    
    database.setOnCreateNodeCallback([](const odhtdb::DatabaseCreateNodeRequest &request)
    {
        
    });
    
    database.setOnAddNodeCallback([](const odhtdb::DatabaseAddNodeRequest &request)
    {
        
    });
    
    database.setOnAddUserCallback([](const odhtdb::DatabaseAddUserRequest &request)
    {
        
    });
    //Video video(500, 500, "https://www.youtube.com/watch?v=bs0-EX9mJmg");
    
    Cache cache;
    
    Channel offlineChannel("Offline");
    ChannelSidePanel::addChannel(&offlineChannel);
    Channel::setCurrent(&offlineChannel);
    
    vector<Channel*> channels;
    
    odhtdb::Signature::KeyPair *currentUserKeyPair = nullptr;
    vector<odhtdb::NodeLocalUser> localNodeUsers;
    string currentUserName;
    string currentUserPassword;
    
    Command::add("login", [&currentUserKeyPair, &currentUserName, &currentUserPassword, &localNodeUsers, &database, &channels](const vector<string> &args)
    {
        if(args.size() != 2)
        {
            fprintf(stderr, "Expected 2 arguments for command login (username and password), got %u argument(s)\n", args.size());
            return;
        }
        
        try
        {
            odhtdb::Signature::KeyPair keyPair = database.getStorage().decryptLocalEncryptedUser(args[0], args[1]);
            localNodeUsers = database.getStorage().getLocalNodeUsers(keyPair);
            
            ChannelSidePanel::removeAllChannels();
            for(Channel *channel : channels)
            {
                delete channel;
            }
            channels.clear();
            
            for(auto localNodeUser : localNodeUsers)
            {
                auto nodeStorage = database.getStorage().getStorage(localNodeUser.nodeHash);
                if(!nodeStorage) continue;
                
                auto nodeDecryptionKeyResult = database.getStorage().getNodeDecryptionKey(localNodeUser.nodeHash);
                if(!nodeDecryptionKeyResult.first) continue;
                
                User *newLocalUser = new OnlineUser(localNodeUser.localUser);
                odhtdb::DatabaseNode databaseNode(nodeDecryptionKeyResult.second, make_shared<odhtdb::Hash>(localNodeUser.nodeHash));
                Channel *channel = new Channel(nodeStorage->nodeName, databaseNode, newLocalUser, &database);
                
                auto nodeUserMapByPublicKey = database.getStorage().getNodeUsers(localNodeUser.nodeHash);
                for(auto nodeUserIt : *nodeUserMapByPublicKey)
                {
                    if(nodeUserIt.second != localNodeUser.localUser)
                    {
                        User *newRemoteUser = new OnlineUser(nodeUserIt.second);
                        channel->addUser(newRemoteUser);
                    }
                }
                
                ChannelSidePanel::addChannel(channel);
                channels.push_back(channel);
                Channel::setCurrent(channel);
                channelAddStoredMessages(channel, nodeStorage);
            }
            
            printf("Successfully logged into user %s\n", args[0].c_str());
            if(currentUserKeyPair)
                delete currentUserKeyPair;
            currentUserKeyPair = new odhtdb::Signature::KeyPair(keyPair);
            
            currentUserName = args[0];
            currentUserPassword = args[1];
        }
        catch(odhtdb::DatabaseStorageException &e)
        {
            fprintf(stderr, "Failed to login, reason: %s\n", e.what());
        }
    });
    
    Command::add("register", [&currentUserKeyPair, &currentUserName, &currentUserPassword, &localNodeUsers, &database](const vector<string> &args)
    {
        if(args.size() != 2)
        {
            fprintf(stderr, "Expected 2 arguments for command register (username and password), got %u argument(s)\n", args.size());
            return;
        }
        
        if(currentUserKeyPair)
        {
            fprintf(stderr, "You can't register a new account when you are logged in, please logout first\n");
            return;
        }
        
        odhtdb::Signature::KeyPair keyPair;
        if(!database.getStorage().storeLocalUser(args[0], keyPair, args[1]))
        {
            fprintf(stderr, "User with name %s already exists in storage\n", args[0].c_str());
            return;
        }
        
        printf("Registered user %s, public key: %s, private key: %s\n", args[0].c_str(), keyPair.getPublicKey().toString().c_str(), keyPair.getPrivateKey().toString().c_str());
        printf("Successfully logged into user %s\n", args[0].c_str());
        
        if(currentUserKeyPair)
            delete currentUserKeyPair;
        currentUserKeyPair = new odhtdb::Signature::KeyPair(keyPair);
        localNodeUsers.clear();
        
        currentUserName = args[0];
        currentUserPassword = args[1];
    });
    
    Command::add("cc", [&currentUserKeyPair, &currentUserName, &database, &channels](const vector<string> &args)
    {
        if(args.size() != 1)
        {
            fprintf(stderr, "Expected 1 argument for command cc (channel name), got %u argument(s)\n", args.size());
            return;
        }
        
        if(!currentUserKeyPair)
        {
            fprintf(stderr, "You are not logged in. Please login before creating a channel\n");
            return;
        }
        
        auto createResponse = database.create(currentUserName, *currentUserKeyPair, args[0]);
        database.commit();
        printf("Created database '%s', join key: '%s'\n", args[0].c_str(), createChannelJoinKey(createResponse).c_str());
        
        User *newLocalUser = new OnlineUser(createResponse->getNodeAdminUser());
        odhtdb::DatabaseNode databaseNode(createResponse->getNodeEncryptionKey(), createResponse->getRequestHash());
        Channel *channel = new Channel(args[0], databaseNode, newLocalUser, &database);
        ChannelSidePanel::addChannel(channel);
        channels.push_back(channel);
        Channel::setCurrent(channel);
    });
    
    Command::add("jc", [&currentUserKeyPair, &database, &localNodeUsers](const vector<string> &args)
    {
        if(args.size() != 1)
        {
            fprintf(stderr, "Expected 1 argument for command jc (channel join key), got %u argument(s)\n", args.size());
            return;
        }
        
        if(args[0].size() != 129)
        {
            fprintf(stderr, "Expected join key to be 129 characters, was %u character(s)\n", args[0].size());
            return;
        }
        
        if(!currentUserKeyPair)
        {
            fprintf(stderr, "You are not logged in. Please login before joining a channel\n");
            return;
        }
        
        odhtdb::DatabaseNode databaseNode = createDatabaseNodeFromJoinKey(args[0]);
        for(auto localNodeUser : localNodeUsers)
        {
            if(*databaseNode.getRequestHash() == localNodeUser.nodeHash)
            {
                fprintf(stderr, "You have already joined the channel %s\n", databaseNode.getRequestHash()->toString().c_str());
                return;
            }
        }
#if 0
        User *newLocalUser = new OnlineUser(localNodeUser.localUser);
        odhtdb::DatabaseNode databaseNode(nodeDecryptionKeyResult.second, make_shared<odhtdb::Hash>(localNodeUser.nodeHash));
        Channel *channel = new Channel(nodeStorage->nodeName, databaseNode, newLocalUser, &database);
        
        auto nodeUserMapByPublicKey = database.getStorage().getNodeUsers(localNodeUser.nodeHash);
        for(auto nodeUserIt : *nodeUserMapByPublicKey)
        {
            if(nodeUserIt.second != localNodeUser.localUser)
            {
                User *newRemoteUser = new OnlineUser(nodeUserIt.second);
                channel->addUser(newRemoteUser);
            }
        }
        
        ChannelSidePanel::addChannel(channel);
        channels.push_back(channel);
        Channel::setCurrent(channel);
        channelAddStoredMessages(channel, nodeStorage);
#endif
    });
    
    Command::add("scale", [](const vector<string> &args)
    {
        if(args.size() != 1)
        {
            fprintf(stderr, "Expected 1 argument for command scale, got %u argument(s)\n", args.size());
            return;
        }
        
        float scaling = stof(args[0]);
        Settings::setScaling(scaling);
        printf("UI scaling set to %f\n", scaling);
    });
    
    sf::Event event;
    while (window.isOpen())
    {
        while (window.pollEvent(event))
        {
            if (event.type == sf::Event::Closed)
                window.close();
            else if(event.type == sf::Event::Resized)
            {
                sf::FloatRect viewRect(0.0f, 0.0f, event.size.width, event.size.height);
                const int minWidth = 800;
                if(event.size.width < minWidth)
                {
                    viewRect.width = minWidth;
                    window.setSize(sf::Vector2u(minWidth, event.size.height));
                }
                
                sf::View view(viewRect);
                window.setView(view);
            }
            Channel::getCurrent()->processEvent(event);
        }

        window.clear(ColorScheme::getBackgroundColor());
        ChannelSidePanel::draw(window);
        Channel::getCurrent()->draw(window, cache);
        UsersSidePanel::draw(window);
        ChannelTopPanel::draw(window);
        //video.draw(window);
        window.display();
    }

    return 0;
}