-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathreplaybuffer.cpp
More file actions
572 lines (494 loc) · 14 KB
/
Copy pathreplaybuffer.cpp
File metadata and controls
572 lines (494 loc) · 14 KB
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
/*
* Copyright (C) 2004-2012 See the AUTHORS file for details.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 as published
* by the Free Software Foundation.
*
* Saves buffers on disk
* Author: crocket <crockabiscuit@gmail.com>
*/
#include <znc/Chan.h>
#include <znc/User.h>
#include <znc/Buffer.h>
#include <znc/Server.h>
#include <znc/IRCNetwork.h>
#include <znc/FileUtils.h>
#include <time.h> /* localtime_r, strftime */
class CReplayBuffer;
class CReplayBufferJob : public CTimer
{
public:
CReplayBufferJob(CModule* pModule, unsigned int uInterval, unsigned int uCycles, const CString& sLabel, const CString& sDescription)
: CTimer(pModule, uInterval, uCycles, sLabel, sDescription) {}
virtual ~CReplayBufferJob() {}
protected:
virtual void RunJob();
};
class CReplayBuffer : public CModule
{
public:
MODCONSTRUCTOR(CReplayBuffer)
{
m_bSeenJoin=false;
m_pTimer = NULL;
AddHelpCommand();
AddCommand("dump", static_cast<CModCommand::ModCmdFunc>(&CReplayBuffer::Dump),
"<channel>", "Dump a stored channel buffer.");
AddCommand("del", static_cast<CModCommand::ModCmdFunc>(&CReplayBuffer::Del),
"<channel>", "Delete channel buffer(s). Supported wildcards : * and ?");
AddCommand("count", static_cast<CModCommand::ModCmdFunc>(&CReplayBuffer::Count),
"<channel>", "Count lines in channel buffers. Wildcards * and ? supported");
AddCommand("save", static_cast<CModCommand::ModCmdFunc>(&CReplayBuffer::Save),
"", "Save all channel buffers.");
AddCommand("list", static_cast<CModCommand::ModCmdFunc>(&CReplayBuffer::List),
"", "List all of saved channel buffers.");
AddCommand("timers", static_cast<CModCommand::ModCmdFunc>(&CReplayBuffer::Timers),
"", "List the timers associated with " + GetModName());
}
virtual ~CReplayBuffer()
{
SaveBuffer();
}
virtual bool OnLoad(const CString& sArgs, CString& sMessage)
{
// If the module has been loaded with ZNC connected to a network,
// add a timer that saves channel buffers every minute.
if(GetNetwork()->IsIRCConnected())
{
if(!StartTimer())
{
sMessage=GetModName()+" failed to start a timer in OnLoad.";
return false;
}
}
return true;
}
virtual void OnIRCConnected()
{
StartTimer();
}
virtual void OnIRCDisconnected()
{
StopTimer();
SaveBuffer();
}
// It outputs the refilled channel buffer
// after znc joins a channel and
// after the IRC client becomes ready to accept the backlog data.
virtual EModRet OnRaw(CString &sLine)
{
CString sCmd=sLine.Token(1);
// parse JOIN messages.
if(sCmd.Equals("JOIN"))
{
// JOIN message format
// ':nick!user@host JOIN [:]channel'
CString sChan=sLine.Token(2);
// If it contains the optional ":", remove it
if(sChan.Left(1) == ":")
sChan.LeftChomp();
CString sNick=sLine.Token(0, false, "!");
sNick.LeftChomp();
if(sNick.Equals(GetNetwork()->GetCurNick()))
{
m_bSeenJoin=true;
m_sSavedChannel=sChan;
}
}
else if(m_bSeenJoin && sCmd.Equals("366"))
{
// 366 denotes the end of /NAMES list after which IRC clients can receive
// chat data. 366 also means 'the end of JOIN'.
// 366 should match right after JOIN is seen since /NAMES can be invoked
// directly by users.
CChan *pChan = GetNetwork()->FindChan(m_sSavedChannel);
if(pChan == NULL)
{
CUtils::PrintError("["+GetModName()+".so] failed to gain access to the channel ["
+m_sSavedChannel+"]");
m_bSeenJoin=false;
return CONTINUE;
}
// 366 message format :
// prefix 366 nick channel :End of /NAMES list.
CString sChan=sLine.Token(3);
if(sChan != m_sSavedChannel)
{
CUtils::PrintMessage("["+GetModName()+".so] 366 was received for ["
+sChan+"] while "+GetModName()+" was expecting it from ["
+ m_sSavedChannel+"]");
return CONTINUE;
}
if(!pChan->GetBuffer().IsEmpty())
ReplayChannel(pChan);
m_bSeenJoin=false;
}
return CONTINUE;
}
virtual void OnJoin(const CNick &cNick, CChan& cChan)
{
if(cNick.GetNick().Equals(GetNetwork()->GetCurNick()) && cChan.GetBuffer().IsEmpty())
if(!BootStrap(cChan))
DEBUG("["+GetModName()+".so] BootStrap not successfull in OnJoin.");
}
virtual void OnPart(const CNick& cNick, CChan &cChan, const CString &sMsg)
{
if(cNick.GetNick().Equals(GetNetwork()->GetCurNick())) {
if(!SaveChannel(cChan))
CUtils::PrintError("["+GetModName()+".so] failed to save the channel buffer for ["
+cChan.GetName()+"]");
}
}
unsigned int SaveBuffer()
{
unsigned int count=0;
CIRCNetwork* pNetwork=GetNetwork();
if(pNetwork == NULL)
{
CUtils::PrintError("["+GetModName()+".so] not associated with any IRC network, "+
"and it can't save any channel buffer.");
return 0;
}
// Save each channel buffer to disk
const std::vector<CChan *>& vChans = pNetwork->GetChans();
std::vector<CChan*>::const_iterator it;
for (it=vChans.begin(); it != vChans.end(); ++it)
{
CChan &cChan=**it;
if(!SaveChannel(cChan))
CUtils::PrintError("["+GetModName()+".so] failed to save the channel buffer for ["
+cChan.GetName()+"]");
else
count+=1;
}
return count;
}
protected:
private:
bool m_bSeenJoin;
CString m_sSavedChannel;
CTimer *m_pTimer;
// Start of command functions.
void Save(const CString &sArgs)
{
unsigned int count=SaveBuffer();
PutModule(CString(count)+" channel buffer(s) saved.");
}
void Timers(const CString &sArgs)
{
ListTimers();
}
void List(const CString &sArgs)
{
MCString mcString;
MCString::iterator it;
// Fill the map with channel buffers.
GetBufferList("*", mcString);
if(mcString.empty())
{
PutModule("No channel buffer is saved yet...");
return;
}
CTable table;
table.AddColumn("Channel");
table.AddColumn("Size in bytes");
// Fill the table using the map.
for(it=mcString.begin(); it!=mcString.end(); ++it)
{
CFile File(it->second);
table.AddRow();
table.SetCell("Channel", "'"+it->first+"'");
table.SetCell("Size in bytes", CString(File.GetSize()) );
}
PutModule(table);
}
void Del(const CString &sLine)
{
CString sArgs=sLine.Token(1, true);
MCString mcChans;
MCString::iterator it;
if(sArgs.empty() || sArgs.find(" ") != CString::npos)
{
HandleHelpCommand("help del");
return;
}
// Fill the map with channel buffers
GetBufferList(sArgs, mcChans);
// Delete channel buffers.
unsigned int count=0;
for(it=mcChans.begin(); it != mcChans.end(); ++it)
{
const CString &ePath=it->second;
if(!CFile::Delete(ePath))
CUtils::PrintError("["+GetModName()+".so] failed to delete "+ePath);
else
count+=1;
}
PutModule(CString(count)+" channel buffers deleted.");
}
// Count the number of lines in channel buffers.
void Count(const CString &sLine)
{
CString sBuf;
MCString msChan;
MCString::iterator it;
CString sCmd=sLine.Token(0);
CString sArgs=sLine.Token(1, true);
if(sArgs.empty() || sArgs.find(" ") != CString::npos)
{
HandleHelpCommand("help count");
return;
}
CTable table;
table.AddColumn("Channel");
table.AddColumn("Lines");
GetBufferList(sArgs, msChan);
// Fill the table using the map entries.
for(it=msChan.begin(); it != msChan.end(); ++it)
{
const CString &sChan=it->first;
const CString &sChanPath=it->second;
if(!ReadChanFile(sChanPath, sBuf))
{
CUtils::PrintError("["+GetModName()+".so] "
+"failed to read the channel buffer for ["+sChan+"]");
continue;
}
// Count the number of lines in a channel buffer.
const char* pBuf=sBuf.c_str();
size_t size=sBuf.size();
unsigned int count=0;
for(size_t i=0; i<size; ++i)
{
if(pBuf[i] == '\n')
count+=1;
}
table.AddRow();
table.SetCell("Channel", sChan);
table.SetCell("Lines", CString(count/2)); // each line consumes two lines in a saved buffer.
}
PutModule(table);
}
void Dump(const CString& sLine)
{
// Channel names are case-insensitive.
CString sChan=sLine.Token(1, true);
if(sChan.empty() || sChan.find(" ") != CString::npos)
{
HandleHelpCommand("help dump");
return;
}
CString sFile;
if (ReadChan(sChan, sFile))
{
VCString vsLines;
VCString::iterator it;
sFile.Split("\n", vsLines);
for (it = vsLines.begin(); it != vsLines.end(); ++it) {
CString line(*it);
line.Trim();
PutModule("["+line+"]");
}
}
else
{
DEBUG("["+GetModName()+".so] failed to read a channel buffer for ["
+sChan+"]");
}
PutModule("//!-- EOF "+sChan);
}
// End of command functions.
CString GetPath(const CString & sFile)
{
return GetSavePath()+"/"+sFile;
}
// Fills a map with channel buffers matching sWild.
// key : decoded filename
// value : URL-encoded filepath
void GetBufferList(const CString &sWild, MCString &mcString)
{
CDir dir(GetSavePath());
CDir::iterator dit;
CString eFile;
CString ePath;
CString sFile;
CString slWild=sWild.AsLower(); // channel names are case-insensitive.
// Iterate through all of channel buffers.
for(dit=dir.begin(); dit != dir.end(); ++dit)
{
eFile=(**dit).GetShortName();
ePath=(**dit).GetLongName();
// Decode URL encoded file names
sFile=eFile.Escape_n(CString::EURL,CString::EASCII);
if(sFile.WildCmp(slWild))
mcString.insert(std::pair<CString,CString>(sFile, ePath));
}
}
bool ReadChan(const CString & sChan, CString & sBuffer)
{
// Use URL encoding.
// Channel names are case-insensitive.
CString eChan=sChan.AsLower().Escape_n(CString::EURL);
return ReadChanFile(GetPath(eChan), sBuffer);
}
bool ReadChanFile(const CString & sPath, CString & sBuffer)
{
sBuffer = "";
CFile File(sPath);
CString sFile;
if (sPath.empty() || !File.Open() || !File.ReadFile(sFile))
{
DEBUG("["+GetModName()+".so] failed to read "
+sPath+" in ReadChanFile.");
File.Close();
return false;
}
File.Close();
sBuffer=sFile;
return true;
}
// Fill the channel buffer with the saved buffer.
bool BootStrap(CChan &cChan)
{
CString sFile;
// Read the backlog stored in disk.
if (ReadChan(cChan.GetName(), sFile))
{
VCString vsLines;
VCString::iterator it;
sFile.Split("\n", vsLines);
timeval tv={0, 0};
for (it = vsLines.begin(); it != vsLines.end(); ++it)
{
CString sLine(*it);
sLine.Trim();
// Each line is saved in two line format.
// @timestamp IRCmessage :{text}
// The content of {text}
if(sLine[0] == '@' && it+1 != vsLines.end())
{
// timestamp
CString sTimestamp = sLine.Token(0);
sTimestamp.TrimLeft("@");
tv.tv_sec = sTimestamp.ToLongLong();
// IRC message
CString sFormat = sLine.Token(1, true);
// The content of {text}
CString sText(*++it);
sText.Trim();
// Add them to the channel buffer.
cChan.AddBuffer(sFormat, sText, &tv);
}
}
}
else
{
DEBUG("["+GetModName()+".so] failed to read a channel buffer for ["
+cChan.GetName()+"]");
return false;
}
return true;
}
void ReplayChannel(CChan *pChan)
{
if(pChan == NULL)
{
CUtils::PrintError("["+GetModName()+".so] pChan was given NULL in ReplayChannel");
return;
}
const CBuffer &Buffer=pChan->GetBuffer();
unsigned int size=Buffer.Size();
time_t logtime=0;
struct tm t;
char timeStr[1024];
PutUser(":***!znc@znc.in PRIVMSG "+pChan->GetName()+" :"+GetModName()+" Buffer Playback...");
for(unsigned int i=0; i<size; ++i)
{
const CBufLine &bufLine = Buffer.GetBufLine(i);
// Format time.
logtime=bufLine.GetTime().tv_sec;
localtime_r(&logtime, &t);
// Time formatted as Year/Month/Date [hour:minute:second am/pm]
if(!strftime(timeStr, sizeof(timeStr), "%Y/%b/%d [%I:%M:%S %P] ", &t))
{
CUtils::PrintError("["+GetModName()+".so] couldn't format a time log with strftime.]");
break;
}
// Replace {text} with the real text.
CString chanBuf=bufLine.GetFormat().Replace_n("{text}", timeStr+bufLine.GetText());
PutUser(chanBuf);
}
PutUser(":***!znc@znc.in PRIVMSG "+pChan->GetName()+" :"+GetModName()+" Playback Complete.");
}
bool StartTimer()
{
if(m_pTimer)
{
CUtils::PrintMessage("["+GetModName()+".so] timer is already in action.]");
return true;
}
m_pTimer=new CReplayBufferJob(this, 60, 0, "SaveBuffer", "Saves the current buffer to disk every 1 minute");
if(!AddTimer(m_pTimer))
{
CUtils::PrintError("["+GetModName()+".so] failed to start timer.");
delete m_pTimer;
m_pTimer=NULL;
return false;
}
return true;
}
bool StopTimer()
{
bool bRet=true;
if(m_pTimer == NULL)
{
CUtils::PrintError("["+GetModName()+".so] timer is not existent.]");
return false;
}
bRet=RemTimer(m_pTimer);
m_pTimer = NULL;
if(!bRet)
CUtils::PrintError("["+GetModName()+".so] there was a problem deleting a timer.");
return bRet;
}
bool SaveChannel(CChan& cChan)
{
CString sBuf;
// Set filenames to lower-case channel names in URL encoding to avoid "/"
// Since channel names are case-insensitive, lower-case names are used in filenames.
CString sPath = GetPath(cChan.GetName().AsLower().Escape_n(CString::EURL));
// Rearrange the channel buffer so as to save it.
const CBuffer &Buffer = cChan.GetBuffer();
unsigned int bufSize=Buffer.Size();
// If bufSize is 0, don't save the buffer.
if(bufSize == 0)
return true;
for (unsigned int i=0; i<bufSize ; ++i)
{
const CBufLine &Line = Buffer.GetBufLine(i);
sBuf+= "@"+CString(Line.GetTime().tv_sec)+" "+Line.GetFormat()+"\n"+Line.GetText()+"\n";
}
CFile File(sPath);
if (File.Open(O_WRONLY | O_CREAT | O_TRUNC, 0600)) {
File.Chmod(0600);
File.Write(sBuf);
}
else
{
CUtils::PrintError("["+GetModName()+".so] failed to open file ["+sPath+"]");
return false;
}
File.Close();
return true;
}
};
void CReplayBufferJob::RunJob()
{
CReplayBuffer *p = (CReplayBuffer *)m_pModule;
p->SaveBuffer();
}
template<> void TModInfo<CReplayBuffer>(CModInfo& Info) {
Info.SetWikiPage("replaybuffer");
}
NETWORKMODULEDEFS(CReplayBuffer, "Stores channel buffers on disks, and restores them when you join those channels again.")