-
Notifications
You must be signed in to change notification settings - Fork 57
/
Copy pathmain.cpp
669 lines (592 loc) · 17.1 KB
/
main.cpp
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
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
// main.cpp
//
// Copyright (c) 2019-2025 Kristofer Berggren
// All rights reserved.
//
// nchat is distributed under the MIT license, see LICENSE for details.
#include <iostream>
#include <map>
#include <regex>
#include <set>
#include <string>
#include <cassert>
#include <dlfcn.h>
#include <path.hpp>
#include "appconfig.h"
#include "apputil.h"
#include "fileutil.h"
#include "log.h"
#include "messagecache.h"
#include "profiles.h"
#include "scopeddirlock.h"
#include "status.h"
#include "sysutil.h"
#include "ui.h"
#ifdef HAS_DUMMY
#include "duchat.h"
#endif
#ifdef HAS_TELEGRAM
#include "tgchat.h"
#endif
#ifdef HAS_WHATSAPP
#include "wmchat.h"
#endif
static std::string GetFeatures();
static void RemoveProfile();
static std::shared_ptr<Protocol> SetupProfile();
static void ShowHelp();
static void ShowVersion();
class ProtocolBaseFactory
{
public:
ProtocolBaseFactory() { }
virtual ~ProtocolBaseFactory() { }
virtual std::string GetName() const = 0;
virtual std::string GetSetupMessage() const = 0;
virtual std::shared_ptr<Protocol> Create() const = 0;
};
template<typename T>
class ProtocolFactory : public ProtocolBaseFactory
{
public:
virtual std::string GetName() const
{
return T::GetName();
}
virtual std::string GetSetupMessage() const
{
return T::GetSetupMessage();
}
virtual std::shared_ptr<Protocol> Create() const
{
std::shared_ptr<T> protocol;
#ifdef HAS_DYNAMICLOAD
std::string libPath =
FileUtil::DirName(FileUtil::GetSelfPath()) + "/../" CMAKE_INSTALL_LIBDIR "/" + T::GetLibName() +
FileUtil::GetLibSuffix();
std::string createFunc = T::GetCreateFunc();
void* handle = dlopen(libPath.c_str(), RTLD_LAZY);
if (handle == nullptr)
{
LOG_ERROR("failed dlopen %s", libPath.c_str());
const char* dlerr = dlerror();
if (dlerr != nullptr)
{
LOG_ERROR("dlerror %s", dlerr);
}
std::cout << "Failed to load " << libPath << ", skipping profile.\n";
return protocol;
}
// intentionally leak 'handle' as dlclose may cause exit crash as go routines are not explicitly managed
T* (* CreateFunc)() = (T * (*)())dlsym(handle, createFunc.c_str());
if (CreateFunc == nullptr)
{
LOG_ERROR("failed dlsym %s", createFunc.c_str());
return protocol;
}
protocol.reset(CreateFunc());
#else
protocol = std::make_shared<T>();
#endif
return protocol;
}
};
static std::vector<std::shared_ptr<ProtocolBaseFactory>> GetProtocolFactorys()
{
std::vector<std::shared_ptr<ProtocolBaseFactory>> protocolFactorys =
{
#ifdef HAS_DUMMY
std::shared_ptr<ProtocolBaseFactory>(new ProtocolFactory<DuChat>()),
#endif
#ifdef HAS_TELEGRAM
std::shared_ptr<ProtocolBaseFactory>(new ProtocolFactory<TgChat>()),
#endif
#ifdef HAS_WHATSAPP
std::shared_ptr<ProtocolBaseFactory>(new ProtocolFactory<WmChat>()),
#endif
};
return protocolFactorys;
}
int main(int argc, char* argv[])
{
// Defaults
umask(S_IRWXG | S_IRWXO);
FileUtil::SetApplicationDir(FileUtil::GetDefaultApplicationDir());
Log::SetVerboseLevel(Log::INFO_LEVEL);
// Argument handling
std::string exportDir;
bool isKeyDump = false;
bool isRemove = false;
bool isSetup = false;
std::vector<std::string> args(argv + 1, argv + argc);
for (auto it = args.begin(); it != args.end(); ++it)
{
if (((*it == "-d") || (*it == "--confdir")) && (std::distance(it + 1, args.end()) > 0))
{
++it;
FileUtil::SetApplicationDir(*it);
}
else if ((*it == "-e") || (*it == "--verbose"))
{
Log::SetVerboseLevel(Log::DEBUG_LEVEL);
}
else if ((*it == "-ee") || (*it == "--extra-verbose"))
{
Log::SetVerboseLevel(Log::TRACE_LEVEL);
}
else if ((*it == "-h") || (*it == "--help"))
{
ShowHelp();
return 0;
}
else if ((*it == "-k") || (*it == "--keydump"))
{
isKeyDump = true;
}
else if ((*it == "-m") || (*it == "--devmode"))
{
AppUtil::SetDeveloperMode(true);
}
else if ((*it == "-mm") || (*it == "--extra-devmode"))
{
std::cout << "dev mode starting in 5 sec\n";
sleep(5);
AppUtil::SetDeveloperMode(true);
}
else if ((*it == "-r") || (*it == "--remove"))
{
isRemove = true;
}
else if ((*it == "-s") || (*it == "--setup"))
{
isSetup = true;
}
else if ((*it == "-v") || (*it == "--version"))
{
ShowVersion();
return 0;
}
else if (((*it == "-x") || (*it == "--export")) && (std::distance(it + 1, args.end()) > 0))
{
++it;
exportDir = *it;
}
else
{
ShowHelp();
return 1;
}
}
bool isDirInited = false;
static const int dirVersion = 1;
if (!apathy::Path(FileUtil::GetApplicationDir()).exists())
{
FileUtil::InitDirVersion(FileUtil::GetApplicationDir(), dirVersion);
isDirInited = true;
}
ScopedDirLock dirLock(FileUtil::GetApplicationDir());
if (!dirLock.IsLocked())
{
std::cerr <<
"error: unable to acquire lock for " << FileUtil::GetApplicationDir() << "\n" <<
" only one nchat session per account/confdir is supported.\n";
return 1;
}
if (!isDirInited)
{
int storedVersion = FileUtil::GetDirVersion(FileUtil::GetApplicationDir());
if (storedVersion != dirVersion)
{
if (isSetup)
{
FileUtil::InitDirVersion(FileUtil::GetApplicationDir(), dirVersion);
}
else
{
std::cerr << "error: invalid config dir content, exiting. use -s to setup nchat.\n";
return 1;
}
}
}
// Remove profile
if (isRemove)
{
RemoveProfile();
return 0;
}
// Init profiles dir
Profiles::Init();
// Init logging
const std::string& logPath = FileUtil::GetApplicationDir() + std::string("/log.txt");
Log::Init(logPath);
std::string appNameVersion = AppUtil::GetAppName(true /*p_WithVersion*/);
LOG_INFO("%s", appNameVersion.c_str());
std::string osArch = SysUtil::GetOsArch();
LOG_INFO("%s", osArch.c_str());
std::string compiler = SysUtil::GetCompiler();
LOG_INFO("%s", compiler.c_str());
std::string go = SysUtil::GetGo(GO_VERSION);
LOG_INFO("%s", go.c_str());
std::string features = GetFeatures();
LOG_INFO("%s", features.c_str());
// Init signal handler
AppUtil::InitSignalHandler();
// Run keydump if required
if (isKeyDump)
{
Ui::RunKeyDump();
return 0;
}
// Init app config
AppConfig::Init();
FileUtil::SetDownloadsDir(AppConfig::GetStr("downloads_dir"));
static const bool isLogdumpEnabled = AppConfig::GetBool("logdump_enabled");
// Init core dump
static const bool isCoredumpEnabled = AppConfig::GetBool("coredump_enabled");
if (isCoredumpEnabled)
{
#ifndef HAS_COREDUMP
LOG_WARNING("core dump not supported");
#else
AppUtil::InitCoredump();
#endif
}
// Init message cache
MessageCache::Init();
// Run setup if required
std::shared_ptr<Protocol> setupProtocol;
if (isSetup)
{
setupProtocol = SetupProfile();
if (!setupProtocol)
{
MessageCache::Cleanup();
AppConfig::Cleanup();
return 1;
}
}
// Init ui
std::shared_ptr<Ui> ui = std::make_shared<Ui>();
// Set message cache message handler
std::function<void(std::shared_ptr<ServiceMessage>)> messageHandler =
std::bind(&Ui::MessageHandler, std::ref(*ui), std::placeholders::_1);
MessageCache::SetMessageHandler(messageHandler);
// Load profile(s)
std::string profilesDir = FileUtil::GetApplicationDir() + "/profiles";
const std::vector<apathy::Path>& profilePaths = apathy::Path::listdir(profilesDir);
for (auto& profilePath : profilePaths)
{
std::string profileId = profilePath.filename();
if (profileId == "version") continue;
std::stringstream ss(profileId);
std::string protocolName;
if ((profileId.find("_") == std::string::npos) || !std::getline(ss, protocolName, '_'))
{
LOG_WARNING("invalid profile name, skipping %s", profileId.c_str());
continue;
}
#ifndef HAS_MULTIPROTOCOL
if (!ui->GetProtocols().empty())
{
LOG_WARNING("multiple profile support not enabled, skipping %s", profileId.c_str());
continue;
}
#endif
if (setupProtocol && (setupProtocol->GetProfileId() == profileId))
{
LOG_DEBUG("adding new profile %s", profileId.c_str());
ui->AddProtocol(setupProtocol);
setupProtocol.reset();
}
else
{
bool found = false;
std::vector<std::shared_ptr<ProtocolBaseFactory>> allProtocolFactorys = GetProtocolFactorys();
for (auto& protocolFactory : allProtocolFactorys)
{
if (protocolFactory->GetName() == protocolName)
{
LOG_DEBUG("loading existing profile %s", profileId.c_str());
std::shared_ptr<Protocol> protocol = protocolFactory->Create();
if (protocol)
{
protocol->LoadProfile(profilesDir, profileId);
ui->AddProtocol(protocol);
found = true;
}
}
}
if (!found)
{
std::string msg = "Protocol " + protocolName + " not supported";
if (protocolName == "WhatsAppMd")
{
// Special logging for WhatsApp which may be auto-disabled from build if go dependency not met
msg += " (requires Go >= " + std::string(GO_VERSION_MIN) + ")";
}
LOG_WARNING("%s", msg.c_str());
std::cout << msg << "\n";
}
}
}
// Start protocol(s) and ui
ui->Init();
std::unordered_map<std::string, std::shared_ptr<Protocol>>& protocols = ui->GetProtocols();
bool hasProtocols = !protocols.empty();
if (hasProtocols && exportDir.empty())
{
// Sort protocols
std::map<std::string, std::shared_ptr<Protocol>> protocolsSorted(protocols.begin(), protocols.end());
// Login
Status::Set(Status::FlagConnecting);
std::thread loginThread([&]
{
for (auto& protocol : protocolsSorted)
{
protocol.second->SetMessageHandler(messageHandler);
protocol.second->Login();
}
});
// Ui main loop
ui->Run();
// Cleanup login thread
if (loginThread.joinable())
{
loginThread.join();
}
// Logout
for (auto& protocol : protocolsSorted)
{
protocol.second->Logout();
protocol.second->CloseProfile();
}
}
// Cleanup ui
ui.reset();
// Perform export if requested
if (!exportDir.empty())
{
MessageCache::Export(exportDir);
}
// Cleanup
MessageCache::Cleanup();
AppConfig::Cleanup();
Profiles::Cleanup();
// Exit code
int rv = 0;
if (!hasProtocols)
{
std::cout << "No profiles setup, exiting.\n";
rv = 1;
}
LOG_INFO("exit");
Log::Cleanup(isLogdumpEnabled);
return rv;
}
std::string GetFeatures()
{
std::string features =
#if defined(HAS_TELEGRAM)
"Telegram ON, "
#else
"Telegram OFF, "
#endif
#if defined(HAS_WHATSAPP)
"WhatsApp ON"
#else
"WhatsApp OFF"
#endif
;
return features;
}
void RemoveProfile()
{
// Show profiles
std::string profilesDir = FileUtil::GetApplicationDir() + "/profiles";
const std::vector<apathy::Path>& profilePaths = apathy::Path::listdir(profilesDir);
int id = 0;
std::map<int, std::string> idPath;
std::cout << "Remove profile:\n";
for (auto& profilePath : profilePaths)
{
std::string profileId = profilePath.filename();
if (profileId == "version") continue;
std::stringstream ss(profileId);
std::string protocolName;
if ((profileId.find("_") == std::string::npos) || !std::getline(ss, protocolName, '_'))
{
LOG_WARNING("invalid profile name, skipping %s", profileId.c_str());
continue;
}
std::cout << id << ". " << profileId << "\n";
idPath[id++] = profilePath.string();
}
std::cout << id << ". Cancel removal\n";
size_t selectid = id;
std::cout << "Remove profile (" << selectid << "): ";
std::string line;
std::getline(std::cin, line);
if (!line.empty())
{
try
{
selectid = stoi(line);
}
catch (...)
{
}
}
if (!idPath.count(selectid))
{
std::cout << "Removal aborted, exiting." << std::endl;
return;
}
std::string profilePath = idPath.at(selectid);
LOG_TRACE("deleting %s", profilePath.c_str());
FileUtil::RmDir(profilePath);
}
std::shared_ptr<Protocol> SetupProfile()
{
std::shared_ptr<Protocol> rv;
std::vector<std::shared_ptr<ProtocolBaseFactory>> protocolFactorys = GetProtocolFactorys();
std::cout << "Protocols:" << std::endl;
size_t idx = 0;
for (auto it = protocolFactorys.begin(); it != protocolFactorys.end(); ++it, ++idx)
{
std::cout << idx << ". " << (*it)->GetName() << std::endl;
}
std::cout << idx << ". Exit setup" << std::endl;
size_t selectidx = idx;
std::cout << "Select protocol (" << selectidx << "): ";
std::string line;
std::getline(std::cin, line);
if (!line.empty())
{
try
{
selectidx = stoi(line);
}
catch (...)
{
}
}
if (selectidx >= protocolFactorys.size())
{
std::cout << "Setup aborted, exiting." << std::endl;
return rv;
}
std::string profileId;
std::string profilesDir = FileUtil::GetApplicationDir() + std::string("/profiles");
#ifndef HAS_MULTIPROTOCOL
FileUtil::RmDir(profilesDir);
FileUtil::MkDir(profilesDir);
Profiles::Init();
#endif
std::string setupMessage = protocolFactorys.at(selectidx)->GetSetupMessage();
if (!setupMessage.empty())
{
LOG_WARNING("%s", setupMessage.c_str());
std::cout << setupMessage;
sleep(3);
}
std::shared_ptr<Protocol> protocol = protocolFactorys.at(selectidx)->Create();
bool setupResult = protocol && protocol->SetupProfile(profilesDir, profileId);
if (setupResult)
{
std::cout << "Succesfully set up profile " << profileId << "\n";
rv = protocol;
}
else
{
std::cout << "Setup failed\n";
protocol->Logout();
protocol->CloseProfile();
}
return rv;
}
void ShowHelp()
{
std::cout <<
"nchat is a terminal-based telegram / whatsapp client.\n"
"\n"
"Usage: nchat [OPTION]\n"
"\n"
"Command-line Options:\n"
" -d, --confdir <DIR> use a different directory than ~/.config/nchat\n"
" -e, --verbose enable verbose logging\n"
" -ee, --extra-verbose enable extra verbose logging\n"
" -h, --help display this help and exit\n"
" -k, --keydump key code dump mode\n"
" -m, --devmode developer mode\n"
" -r, --remove remove chat protocol account\n"
" -s, --setup set up chat protocol account\n"
" -v, --version output version information and exit\n"
" -x, --export <DIR> export message cache to specified dir\n"
"\n"
"Interactive Commands:\n"
" PageDn history next page\n"
" PageUp history previous page\n"
" Tab next chat\n"
" Sh-Tab previous chat\n"
" Ctrl-f jump to unread chat\n"
" Ctrl-g toggle show help bar\n"
" Ctrl-l toggle show contact list\n"
" Ctrl-n goto chat\n"
" Ctrl-p toggle show top bar\n"
" Ctrl-q quit\n"
" Ctrl-s insert emoji\n"
" Ctrl-t send file\n"
" Ctrl-x send message\n"
" Ctrl-y toggle show emojis\n"
" KeyUp select message\n"
" Alt-d delete/leave current chat\n"
" Alt-e external editor compose\n"
" Alt-n search contacts\n"
" Alt-t external telephone call\n"
" Alt-/ find in chat\n"
" Alt-? find next in chat\n"
" Alt-$ external spell check\n"
" Alt-, decrease contact list width\n"
" Alt-. increase contact list width\n"
"\n"
"Interactive Commands for Selected Message:\n"
" Ctrl-d delete selected message\n"
" Ctrl-r download attached file\n"
" Ctrl-v open/view attached file\n"
" Ctrl-w open link\n"
" Ctrl-x send reply to selected message\n"
" Ctrl-z edit selected message\n"
" Alt-c copy selected message to clipboard\n"
" Alt-q jump to quoted/replied message\n"
" Alt-r forward selected message\n"
" Alt-s add/remove reaction on selected message\n"
" Alt-w external message viewer\n"
"\n"
"Interactive Commands for Text Input:\n"
" Ctrl-a move cursor to start of line\n"
" Ctrl-c clear input buffer\n"
" Ctrl-e move cursor to end of line\n"
" Ctrl-k delete from cursor to end of line\n"
" Ctrl-u delete from cursor to start of line\n"
" Alt-Left move cursor backward one word\n"
" Alt-Right move cursor forward one word\n"
" Alt-Backsp delete previous word\n"
" Alt-Delete delete next word\n"
" Alt-c copy input buffer to clipboard (if no message selected)\n"
" Alt-v paste into input buffer from clipboard\n"
" Alt-x cut input buffer to clipboard\n"
"\n"
"Report bugs at https://github.com/d99kris/nchat\n"
"\n";
}
void ShowVersion()
{
std::cout <<
AppUtil::GetAppName(true /*p_WithVersion*/) << "\n"
"\n"
"Copyright (c) 2019-2025 Kristofer Berggren\n"
"\n"
"nchat is distributed under the MIT license.\n"
"\n"
"Written by Kristofer Berggren.\n";
}