forked from CyberShadow/DFeed
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsubscriptions.d
More file actions
984 lines (827 loc) · 27.7 KB
/
subscriptions.d
File metadata and controls
984 lines (827 loc) · 27.7 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
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
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
/* Copyright (C) 2015, 2016, 2017 Vladimir Panteleev <vladimir@thecybershadow.net>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
module subscriptions;
import std.algorithm;
import std.ascii;
import std.exception;
import std.format;
import std.process;
import std.regex;
import std.string;
import std.typecons;
import std.typetuple;
import ae.net.ietf.url : UrlParameters;
import ae.sys.log;
import ae.sys.timing;
import ae.utils.array;
import ae.utils.json;
import ae.utils.meta;
import ae.utils.text;
import ae.utils.textout;
import ae.utils.time;
import ae.utils.xmllite : putEncodedEntities;
import common;
import database;
import groups;
import ircsink;
import message;
import messagedb : threadID;
import user;
import web : getPost, site;
void log(string s)
{
static Logger log;
(log ? log : (log=createLogger("Subscription")))(s);
}
struct Subscription
{
string userName, id;
Trigger trigger;
Action[] actions;
this(string userName, UrlParameters data)
{
this.userName = userName;
this.id = data.get("id", null);
this.trigger = getTrigger(userName, data);
this.actions = getActions(userName, data);
}
@property FormSection[] sections() { return cast(FormSection[])[trigger] ~ cast(FormSection[])actions; }
void save()
{
assert(id, "No subscription ID");
assert(userName, "No subscription username");
foreach (section; sections)
section.validate();
UrlParameters data;
data["id"] = id;
data["trigger-type"] = trigger.type;
foreach (section; sections)
section.serialize(data);
{
mixin(DB_TRANSACTION);
query!"INSERT OR REPLACE INTO [Subscriptions] ([ID], [Username], [Data]) VALUES (?, ?, ?)"
.exec(id, userName, SubscriptionData(data).toJson());
foreach (section; sections)
section.save();
}
}
void remove()
{
mixin(DB_TRANSACTION);
foreach (section; sections)
section.cleanup();
query!`DELETE FROM [Subscriptions] WHERE [ID] = ?`.exec(id);
}
void unsubscribe()
{
foreach (action; actions)
action.unsubscribe();
save();
}
void runActions(Rfc850Post post)
{
log("Running subscription %s (%s trigger) actions for post %s".format(id, trigger.type, post.id));
string name = getUserSetting(userName, "name");
string email = getUserSetting(userName, "email");
if ((name && !icmp(name, post.author))
|| (email && !icmp(email, post.authorEmail)))
{
log("Post created by author, ignoring");
return;
}
foreach (action; actions)
action.run(this, post);
}
int getUnreadCount()
{
auto user = new RegisteredUser(userName);
int count = 0;
foreach (int rowid; query!"SELECT [MessageRowID] FROM [SubscriptionPosts] WHERE [SubscriptionID] = ?".iterate(id))
if (!user.isRead(rowid))
count++;
return count;
}
}
/// POD serialization type to avoid depending on UrlParameters internals
struct SubscriptionData
{
string[][string] items;
this(UrlParameters parameters) { items = parameters.items; }
@property UrlParameters data() { UrlParameters result; result.items = items; return result; }
}
bool subscriptionExists(string subscriptionID)
{
return query!`SELECT COUNT(*) FROM [Subscriptions] WHERE [ID]=?`.iterate(subscriptionID).selectValue!int > 0;
}
Subscription getSubscription(string subscriptionID)
out(result) { assert(result.id == subscriptionID); }
body
{
foreach (string userName, string data; query!`SELECT [Username], [Data] FROM [Subscriptions] WHERE [ID] = ?`.iterate(subscriptionID))
return Subscription(userName, data.jsonParse!SubscriptionData.data);
throw new Exception("No such subscription");
}
Subscription getUserSubscription(string userName, string subscriptionID)
out(result) { assert(result.id == subscriptionID && result.userName == userName); }
body
{
enforce(userName.length, "Not logged in");
foreach (string data; query!`SELECT [Data] FROM [Subscriptions] WHERE [Username] = ? AND [ID] = ?`.iterate(userName, subscriptionID))
return Subscription(userName, data.jsonParse!SubscriptionData.data);
throw new Exception("No such user subscription");
}
Subscription[] getUserSubscriptions(string userName)
{
assert(userName);
Subscription[] results;
foreach (string data; query!`SELECT [Data] FROM [Subscriptions] WHERE [Username] = ?`.iterate(userName))
results ~= Subscription(userName, data.jsonParse!SubscriptionData.data);
return results;
}
void createReplySubscription(string userName)
{
auto replySubscriptions = getUserSubscriptions(userName)
.filter!(result => result.trigger.type == "reply");
auto subscription = replySubscriptions.empty
? createSubscription(userName, "reply")
: replySubscriptions.front
;
subscription.save();
}
Subscription createSubscription(string userName, string triggerType, string[string] extraData = null)
{
UrlParameters data = extraData;
data["trigger-type"] = triggerType;
Subscription subscription;
subscription.userName = userName;
subscription.id = data["id"] = randomString();
subscription.trigger = getTrigger(userName, data);
subscription.actions = getActions(userName, data);
return subscription;
}
abstract class FormSection
{
string userName, subscriptionID;
this(string userName, UrlParameters data) { list(this.userName, this.subscriptionID) = tuple(userName, data.get("id", null)); }
/// Output the form HTML to edit this trigger.
abstract void putEditHTML(ref StringBuffer html);
/// Serialize state to a key-value AA,
/// with the same keys as form input names.
abstract void serialize(ref UrlParameters data);
/// Verify that the settings are valid.
/// Throw an exception otherwise.
abstract void validate();
/// Create or update any persistent state
/// (outside the [Subscriptions] table).
abstract void save();
/// Clean up any persistent state after deletion
/// (outside the [Subscriptions] table).
abstract void cleanup();
}
// ***********************************************************************
class Trigger : FormSection
{
mixin GenerateConstructorProxies;
/// TriggerType
abstract @property string type() const;
/// HTML description shown in the subscription list.
abstract void putDescription(ref StringBuffer html);
final string getDescription()
{
StringBuffer description;
putDescription(description);
return description.get().assumeUnique();
}
/// Text description shown in emails and feed titles.
abstract string getTextDescription();
/// Short description for IRC and email subjects.
abstract string getShortPostDescription(Rfc850Post post);
/// Longer description emails.
abstract string getLongPostDescription(Rfc850Post post);
}
final class ReplyTrigger : Trigger
{
mixin GenerateConstructorProxies;
override @property string type() const { return "reply"; }
override void putDescription(ref StringBuffer html) { html.put(getTextDescription()); }
override string getTextDescription() { return "Replies to your posts"; }
override string getShortPostDescription(Rfc850Post post)
{
return "%s replied to your post in the thread \"%s\"".format(post.author, post.subject);
}
override string getLongPostDescription(Rfc850Post post)
{
return "%s has just replied to your %s post in the thread titled \"%s\" in the %s group of %s.".format(
post.author,
post.time.formatTime!`F j`,
post.subject,
post.xref[0].group,
site.config.host,
);
}
override void putEditHTML(ref StringBuffer html)
{
html.put("When someone replies to your posts:");
}
override void serialize(ref UrlParameters data) {}
override void validate() {}
override void save()
{
string email = getUserSetting(userName, "email");
if (email)
query!`INSERT OR REPLACE INTO [ReplyTriggers] ([SubscriptionID], [Email]) VALUES (?, ?)`.exec(subscriptionID, email);
}
override void cleanup()
{
query!`DELETE FROM [ReplyTriggers] WHERE [SubscriptionID] = ?`.exec(subscriptionID);
}
}
final class ThreadTrigger : Trigger
{
string threadID;
this(string userName, UrlParameters data)
{
super(userName, data);
this.threadID = data.get("trigger-thread-id", null);
}
override @property string type() const { return "thread"; }
final void putThreadName(ref StringBuffer html)
{
auto post = getPost(threadID);
html.put(`<a href="`), html.putEncodedEntities(idToUrl(threadID)), html.put(`"><b>`),
html.putEncodedEntities(post ? post.subject : threadID),
html.put(`</b></a>`);
}
override void putDescription(ref StringBuffer html)
{
html.put(`Replies to the thread `), putThreadName(html);
}
override string getTextDescription()
{
auto post = getPost(threadID);
return "Replies to the thread " ~ (post ? `"` ~ post.subject ~ `"` : threadID);
}
override string getShortPostDescription(Rfc850Post post)
{
return "%s replied to the thread \"%s\"".format(post.author, post.subject);
}
override string getLongPostDescription(Rfc850Post post)
{
return "%s has just replied to a thread you have subscribed to titled \"%s\" in the %s group of %s.".format(
post.author,
post.subject,
post.xref[0].group,
site.config.host,
);
}
override void putEditHTML(ref StringBuffer html)
{
auto post = getPost(threadID);
html.put(
`<input type="hidden" name="trigger-thread-id" value="`), html.putEncodedEntities(threadID), html.put(`">` ~
`When someone posts a reply to the thread `), putThreadName(html), html.put(`:`
);
}
override void serialize(ref UrlParameters data)
{
data["trigger-thread-id"] = threadID;
}
override void validate()
{
enforce(getPost(threadID), "No such post");
}
override void save()
{
query!`INSERT OR REPLACE INTO [ThreadTriggers] ([SubscriptionID], [ThreadID]) VALUES (?, ?)`.exec(subscriptionID, threadID);
}
override void cleanup()
{
query!`DELETE FROM [ThreadTriggers] WHERE [SubscriptionID] = ?`.exec(subscriptionID);
}
}
final class ContentTrigger : Trigger
{
struct StringFilter
{
bool enabled;
bool isRegex;
bool caseSensitive;
string str;
}
bool onlyNewThreads;
bool onlyInGroups; string[] groups;
StringFilter authorNameFilter, authorEmailFilter, subjectFilter, messageFilter;
this(string userName, UrlParameters data)
{
super(userName, data);
this.onlyNewThreads = data.get("trigger-content-message-type", null) == "threads";
this.onlyInGroups = !!("trigger-content-only-in-groups" in data);
this.groups = data.getAll("trigger-content-groups");
void readStringFilter(string id, out StringFilter filter)
{
auto prefix = "trigger-content-" ~ id ~ "-";
filter.enabled = !!((prefix ~ "enabled") in data);
filter.isRegex = data.get(prefix ~ "match-type", null) == "regex";
filter.caseSensitive = !!((prefix ~ "case-sensitive") in data);
filter.str = data.get(prefix ~ "str", null);
}
readStringFilter("author-name", authorNameFilter);
readStringFilter("author-email", authorEmailFilter);
readStringFilter("subject", subjectFilter);
readStringFilter("message", messageFilter);
}
override @property string type() const { return "content"; }
override void putDescription(ref StringBuffer html)
{
html.put(onlyNewThreads ? `New threads` : `New posts`);
if (onlyInGroups)
{
html.put(` in `);
void putGroup(string group)
{
auto gi = getGroupInfo(group);
html.put(`<b>`), html.putEncodedEntities(gi ? gi.publicName : group), html.put(`</b>`);
}
putGroup(groups[0]);
if (groups.length==1)
{}
else
if (groups.length==2)
html.put(` and `), putGroup(groups[1]);
else
if (groups.length==3)
html.put(`, `), putGroup(groups[1]), html.put(` and `), putGroup(groups[2]);
else
html.put(`, `), putGroup(groups[1]), html.put(`, (<b>%d</b> more)`.format(groups.length-2));
}
void putStringFilter(string preface, ref StringFilter filter)
{
if (filter.enabled)
html.put(
` `, preface, ` `,
filter.isRegex ? `/` : ``,
`<b>`), html.putEncodedEntities(filter.str), html.put(`</b>`,
filter.isRegex ? `/` : ``,
filter.isRegex && !filter.caseSensitive ? `i` : ``,
);
}
putStringFilter("from", authorNameFilter);
putStringFilter("from email", authorEmailFilter);
putStringFilter("titled", subjectFilter);
putStringFilter("containing", messageFilter);
}
override string getTextDescription() { return getDescription().replace(`<b>`, "\“").replace(`</b>`, "\”"); }
override string getShortPostDescription(Rfc850Post post)
{
auto s = "%s %s thread \"%s\" in %s".format(
post.author,
post.references.length ? "replied to the" : "created",
post.subject,
post.xref[0].group,
);
string matchStr =
authorNameFilter .enabled && authorNameFilter .str ? authorNameFilter .str :
authorEmailFilter.enabled && authorEmailFilter.str ? authorEmailFilter.str :
subjectFilter .enabled && subjectFilter .str ? subjectFilter .str :
messageFilter .enabled && messageFilter .str ? messageFilter .str :
null;
if (matchStr)
s = "%s matching %s".format(s, matchStr);
return s;
}
override string getLongPostDescription(Rfc850Post post)
{
return "%s has just %s a thread titled \"%s\" in the %s group of %s.\n\nThis %s matches a content alert subscription you have created (%s).".format(
post.author,
post.references.length ? "replied to" : "created",
post.subject,
post.xref[0].group,
site.config.host,
post.references.length ? "post" : "thread",
getTextDescription(),
);
}
override void putEditHTML(ref StringBuffer html)
{
html.put(
`<div id="trigger-content">` ~
`When someone ` ~
`<select name="trigger-content-message-type">` ~
`<option value="posts"` , onlyNewThreads ? `` : ` selected`, `>posts or replies to a thread</option>` ~
`<option value="threads"`, onlyNewThreads ? ` selected` : ``, `>posts a new thread</option>` ~
`</select>` ~
`<table>` ~
`<tr><td>` ~
`<input type="checkbox" name="trigger-content-only-in-groups"`, onlyInGroups ? ` checked` : ``, `> only in the groups:` ~
`</td><td>` ~
`<select name="trigger-content-groups" multiple size="10">`
);
foreach (set; groupHierarchy)
{
if (!set.visible)
continue;
html.put(
`<option disabled>`), html.putEncodedEntities(set.shortName), html.put(`</option>`
);
foreach (group; set.groups)
html.put(
`<option value="`), html.putEncodedEntities(group.internalName), html.put(`"`, groups.canFind(group.internalName) ? ` selected` : ``, `>` ~
` `), html.putEncodedEntities(group.publicName), html.put(`</option>`
);
}
html.put(
`</select>` ~
`</td></tr>`
);
void putStringFilter(string name, string id, ref StringFilter filter)
{
html.put(
`<tr><td>` ~
`<input type="checkbox" name="trigger-content-`, id, `-enabled"`, filter.enabled ? ` checked` : ``, `> ` ~
`and when the `, name, ` ` ~
`</td><td>` ~
`<select name="trigger-content-`, id, `-match-type">` ~
`<option value="substring"`, filter.isRegex ? `` : ` selected`, `>contains the string</option>` ~
`<option value="regex"` , filter.isRegex ? ` selected` : ``, `>matches the regular expression</option>` ~
`</select> ` ~
`<input name="trigger-content-`, id, `-str" value="`), html.putEncodedEntities(filter.str), html.put(`"> ` ~
`(` ~
`<input type="checkbox" name="trigger-content-`, id, `-case-sensitive"`, filter.caseSensitive ? ` checked` : ``, `>` ~
` case sensitive )` ~
`</td></tr>`
);
}
putStringFilter("author name", "author-name", authorNameFilter);
putStringFilter("author email", "author-email", authorEmailFilter);
putStringFilter("subject", "subject", subjectFilter);
putStringFilter("message", "message", messageFilter);
html.put(`</table></div>`);
}
override void serialize(ref UrlParameters data) const
{
data["trigger-content-message-type"] = onlyNewThreads ? "threads" : "posts";
if (onlyInGroups) data["trigger-content-only-in-groups"] = "on";
foreach (group; groups)
data.add("trigger-content-groups", group);
void serializeStringFilter(string id, ref in StringFilter filter)
{
auto prefix = "trigger-content-" ~ id ~ "-";
if (filter.enabled) data[prefix ~ "enabled"] = "on";
data[prefix ~ "match-type"] = filter.isRegex ? "regex" : "substring";
if (filter.caseSensitive) data[prefix ~ "case-sensitive"] = "on";
data[prefix ~ "str"] = filter.str;
}
serializeStringFilter("author-name", authorNameFilter);
serializeStringFilter("author-email", authorEmailFilter);
serializeStringFilter("subject", subjectFilter);
serializeStringFilter("message", messageFilter);
}
override void validate()
{
void validateFilter(string name, ref StringFilter filter)
{
if (filter.enabled)
{
enforce(filter.str.length, "No %s search term specified".format(name));
try
auto re = regex(filter.str);
catch (Exception e)
throw new Exception("Invalid %s regex `%s`: %s".format(name, filter.str, e.msg));
}
}
validateFilter("author name", authorNameFilter);
validateFilter("author email", authorEmailFilter);
validateFilter("subject", subjectFilter);
validateFilter("message", messageFilter);
if (onlyInGroups)
enforce(groups.length, "No groups selected");
}
override void save()
{
query!`INSERT OR REPLACE INTO [ContentTriggers] ([SubscriptionID]) VALUES (?)`.exec(subscriptionID);
}
override void cleanup()
{
query!`DELETE FROM [ContentTriggers] WHERE [SubscriptionID] = ?`.exec(subscriptionID);
}
bool checkPost(Rfc850Post post)
{
if (onlyNewThreads && post.references.length)
return false;
if (onlyInGroups && post.xref.all!(xref => !groups.canFind(xref.group)))
return false;
bool checkFilter(ref StringFilter filter, string field)
{
if (!filter.enabled)
return true;
if (filter.isRegex)
return !!field.match(regex(filter.str, filter.caseSensitive ? "" : "i"));
else
return field.indexOf(filter.str, filter.caseSensitive ? CaseSensitive.yes : CaseSensitive.no) >= 0;
}
if (!checkFilter(authorNameFilter , post.author )) return false;
if (!checkFilter(authorEmailFilter, post.authorEmail)) return false;
if (!checkFilter(subjectFilter , post.subject )) return false;
if (!checkFilter(messageFilter , post.newContent )) return false;
return true;
}
}
Trigger getTrigger(string userName, UrlParameters data)
out(result) { assert(result.type == data.get("trigger-type", null)); }
body
{
auto triggerType = data.get("trigger-type", null);
switch (triggerType)
{
case "reply":
return new ReplyTrigger(userName, data);
case "thread":
return new ThreadTrigger(userName, data);
case "content":
return new ContentTrigger(userName, data);
default:
throw new Exception("Unknown subscription trigger type: " ~ triggerType);
}
}
// ***********************************************************************
void checkPost(Rfc850Post post)
{
// ReplyTrigger
if (auto parentID = post.parentID())
if (auto parent = getPost(parentID))
foreach (string subscriptionID; query!"SELECT [SubscriptionID] FROM [ReplyTriggers] WHERE [Email] = ?".iterate(parent.authorEmail))
getSubscription(subscriptionID).runActions(post);
// ThreadTrigger
foreach (string subscriptionID; query!"SELECT [SubscriptionID] FROM [ThreadTriggers] WHERE [ThreadID] = ?".iterate(post.threadID))
getSubscription(subscriptionID).runActions(post);
// ContentTrigger
foreach (string subscriptionID; query!"SELECT [SubscriptionID] FROM [ContentTriggers]".iterate())
{
auto subscription = getSubscription(subscriptionID);
if ((cast(ContentTrigger)subscription.trigger).checkPost(post))
subscription.runActions(post);
}
}
final class SubscriptionSink : NewsSink
{
protected:
override void handlePost(Post post, Fresh fresh)
{
if (!fresh)
return;
auto message = cast(Rfc850Post)post;
if (!message)
return;
log("Checking post " ~ message.id);
try
checkPost(message);
catch (Exception e)
foreach (line; e.toString().splitLines())
log("* " ~ line);
}
}
// ***********************************************************************
class Action : FormSection
{
mixin GenerateConstructorProxies;
/// Execute this action, if it is enabled.
abstract void run(ref Subscription subscription, Rfc850Post post);
/// Disable this action (used for one-click-unsubscribe in emails)
abstract void unsubscribe();
}
final class IrcAction : Action
{
bool enabled;
string nick;
string network;
this(string userName, UrlParameters data)
{
super(userName, data);
enabled = !!("saction-irc-enabled" in data);
nick = data.get("saction-irc-nick", null);
network = data.get("saction-irc-network", null);
}
override void putEditHTML(ref StringBuffer html)
{
html.put(
`<p>` ~
`<input type="checkbox" name="saction-irc-enabled"`, enabled ? ` checked` : ``, `> ` ~
`Send a private message to <input name="saction-irc-nick" value="`), html.putEncodedEntities(nick), html.put(`"> on the ` ~
`<select name="saction-irc-network">`);
foreach (irc; services!IrcSink)
{
html.put(
`<option value="`), html.putEncodedEntities(irc.network), html.put(`"`, network == irc.network ? ` selected` : ``, `>`),
html.putEncodedEntities(irc.network),
html.put(`</option>`);
}
html.put(
`</select> IRC network` ~
`</p>`
);
}
override void serialize(ref UrlParameters data)
{
if (enabled) data["saction-irc-enabled"] = "on";
data["saction-irc-nick"] = nick;
data["saction-irc-network"] = network;
}
override void run(ref Subscription subscription, Rfc850Post post)
{
if (!enabled)
return;
// Queue messages to avoid sending more than 1 PM per message.
static string[string][string] queue;
static TimerTask queueTask;
queue[network][nick] = subscription.trigger.getShortPostDescription(post) ~ ": " ~ post.url;
if (!queueTask)
queueTask = setTimeout({
queueTask = null;
scope(exit) queue = null;
foreach (irc; services!IrcSink)
foreach (nick, message; queue.get(irc.network, null))
irc.sendMessage(nick, message);
}, 1.msecs);
}
override void validate()
{
if (!enabled)
return;
enforce(nick.length, "No nickname indicated");
foreach (c; nick)
if (!(isAlphaNum(c) || c.isOneOf(r"-_|\[]{}`")))
throw new Exception("Invalid character in nickname.");
}
override void save() {}
override void cleanup() {}
override void unsubscribe() { enabled = false; }
}
final class EmailAction : Action
{
bool enabled;
string address;
this(string userName, UrlParameters data)
{
super(userName, data);
enabled = !!("saction-email-enabled" in data);
address = data.get("saction-email-address", getUserSetting(userName, "email"));
}
override void putEditHTML(ref StringBuffer html)
{
html.put(
`<p>` ~
`<input type="checkbox" name="saction-email-enabled"`, enabled ? ` checked` : ``, `> ` ~
`Send an email to <input type="email" size="30" name="saction-email-address" value="`), html.putEncodedEntities(address), html.put(`">` ~
`</p>`
);
}
override void serialize(ref UrlParameters data)
{
if (enabled) data["saction-email-enabled"] = "on";
data["saction-email-address"] = address;
}
string getUserRealName(string userName)
{
auto name = getUserSetting(userName, "name");
if (!name)
// name = address.split("@")[0].capitalize();
name = userName;
return name;
}
override void run(ref Subscription subscription, Rfc850Post post)
{
if (!enabled)
return;
auto unreadCount = subscription.getUnreadCount();
if (unreadCount)
{
log("User %s has %d unread messages in subscription %s - not emailing"
.format(subscription.userName, unreadCount, subscription.id));
return;
}
// Queue messages to avoid sending more than 1 email per message.
static struct Email { string[] args; string content; }
static Email[string] queue;
static TimerTask queueTask;
if (address in queue)
{
// TODO: Maybe add something to the content, to indicate that
// a second subscription was triggered by the same message.
return;
}
queue[address] = Email([
"-s", subscription.trigger.getShortPostDescription(post),
"-r", "%s <no-reply@%s>".format(site.config.host, site.config.host),
address], formatMessage(subscription, post));
if (!queueTask)
queueTask = setTimeout({
queueTask = null;
scope(exit) queue = null;
foreach (address, email; queue)
{
auto pipes = pipeProcess(["mail"] ~ email.args, Redirect.stdin);
pipes.stdin.rawWrite(email.content);
pipes.stdin.close();
enforce(wait(pipes.pid) == 0, "mail program failed");
}
}, 1.msecs);
}
string formatMessage(ref Subscription subscription, Rfc850Post post)
{
return q"EOF
Howdy %s,
%s
This %s is located at:
%s
Here is the message that has just been posted:
----------------------------------------------
%-(%s
%)
----------------------------------------------
To reply to this message, please visit this page:
http://%s%s
There may also be other messages matching your subscription, but you will not receive any more notifications for this subscription until you've read all messages matching this subscription:
http://%s/subscription-posts/%s
All the best,
%s
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Unsubscription information:
To stop receiving emails for this subscription, please visit this page:
http://%s/subscription-unsubscribe/%s
Or, visit your settings page to edit your subscriptions:
http://%s/settings
.
EOF"
.format(
getUserRealName(userName).split(" ")[0],
subscription.trigger.getLongPostDescription(post),
post.references.length ? "post" : "thread",
post.url,
post.content.strip.splitAsciiLines.map!(line => line.startsWith('.') ? '.' ~ line : line),
site.config.host, idToUrl(post.id, "reply"),
site.config.host, subscription.id,
site.config.name.length ? site.config.name : site.config.host,
site.config.host, subscription.id,
site.config.host,
);
}
override void validate()
{
if (!enabled)
return;
enforce(address.match(re!(`^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$`, "i")), "Invalid email address");
}
override void save() {}
override void cleanup() {}
override void unsubscribe() { enabled = false; }
}
final class DatabaseAction : Action
{
mixin GenerateConstructorProxies;
override void putEditHTML(ref StringBuffer html)
{
html.put(
`<p>Additionally, you can <a href="/subscription-feed/`, subscriptionID, `">subscribe to an ATOM feed of matched posts</a>, ` ~
`or <a href="/subscription-posts/`, subscriptionID, `">read them online</a>.</p>`
);
}
override void serialize(ref UrlParameters data) {}
override void run(ref Subscription subscription, Rfc850Post post)
{
assert(post.rowid, "No row ID for message " ~ post.id);
query!"INSERT INTO [SubscriptionPosts] ([SubscriptionID], [MessageID], [MessageRowID], [Time]) VALUES (?, ?, ?, ?)"
.exec(subscriptionID, post.id, post.rowid, post.time.stdTime);
// TODO: trim old posts?
}
override void validate() {}
override void save() {}
override void cleanup() {} // Just leave the SubscriptionPosts alone, e.g. in case the user clicks undo
override void unsubscribe() {}
}
Action[] getActions(string userName, UrlParameters data)
{
Action[] result;
foreach (ActionType; TypeTuple!(EmailAction, IrcAction, DatabaseAction))
result ~= new ActionType(userName, data);
return result;
}
// ***********************************************************************
private string getUserSetting(string userName, string setting)
{
foreach (string value; query!`SELECT [Value] FROM [UserSettings] WHERE [User] = ? AND [Name] = ?`.iterate(userName, setting))
return value;
return null;
}