AdaCode / newsdb.xml

  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
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE muclient>
<!-- Saved on Monday, December 03, 2012, 12:00 PM -->
<!-- MuClient version 4.77 -->

<!-- Plugin "NewsDB" generated by Plugin Wizard -->

<muclient>
<plugin
   name="NewsDB"
   author="Ada"
   id="04e2d2848d88a45b775ebfd6"
   language="Python"
   purpose="News Database"
   date_written="2012-12-06 12:00:00"
   requires="4.62"
   version="1.6"
   >
<description trim="y">
<![CDATA[
Organizations in Achaea tend to poof lately and along with them go the precious news-boards! This plugin reads and maintains a database of this news on your computer so they stay with you as long as you want. Oh, you can also search through the db using keywords and complex search expressions. Have a look at the available aliases to interact with it. I'll add the ability to paginate search results, search through date ranges and the ability to search by author, recipient, subject, etc. in later versions.

This plugin is written in Python, please see this page to setup Python on your computer: http://adayoung.bitbucket.org/pythonsqlite.html

The following aliases are available:

    NewsDB:addnews <org> <post number> [<post number>]
    NewsDB:readnews <org> <post number>
    NewsDB:search <org> <search expression>
    NewsDB:readnext
    NewsDB:readprev
    NewsDB:nstat
    NewsDB:nsum <org> <post number>
    NewsDB:export <org> [from:<post number> to:<post number>]
    NewsDB:import

The plugin will ask you for a file location on first load, just point it wherever you want your database file to be created. If you get "OperationalError: database is locked" error while trying to add an entry, please delete the .journal file wherever you have your database file to resolve the issue.
]]>
</description>

</plugin>

<!--  Get our standard constants -->

<include name="constants.pys"/>

<!--  Triggers  -->

<triggers>
  <trigger
   group="NewsDB"
   enabled="y"
   keep_evaluating="y"
   match="^You leave the news room and reside in Achaea proper once more\.$"
   name="NewsExit"
   regexp="y"
   send_to="12"
   sequence="100"
  >
  <send>
world.EnableTrigger("PromptCaptureNewsDB", True)
  </send>
  </trigger>
  <trigger
   group="NewsDB"
   enabled="n"
   keep_evaluating="y"
   match="^.+? SECTION \d+/\d+$"
   name="NewsSection"
   regexp="y"
   send_to="12"
   sequence="100"
  >
  <send>
world.EnableTrigger("PromptCaptureNewsDB", False)
  </send>
  </trigger>
  <trigger
   group="NewsDB"
   enabled="n"
   keep_evaluating="y"
   match="^(.+?) NEWS \#(\d+)$"
   name="NewsPreamble"
   regexp="y"
   send_to="12"
   sequence="100"
  >
  <send>
orgname = u"%1"
newsid = int("%2")
world.EnableTrigger("NewsSection", False)
world.EnableTrigger("NewsDate", True)
world.EnableTrigger("NewsFrom", True)
world.EnableTrigger("NewsTo", True)
world.EnableTrigger("NewsSubject", True)
world.EnableTrigger("NewsPreamble", False)
  </send>
  </trigger>
  <trigger
   group="NewsDB"
   enabled="n"
   keep_evaluating="y"
   match="^Date\: (\d+)/(\d+)/(\d+) at (\d+)\:(\d+)$"
   name="NewsDate"
   regexp="y"
   send_to="12"
   sequence="100"
  >
  <send>
(month, day, year, hour, minutes) = (int("%1"), int("%2"), int("%3"), int("%4"), int("%5"))
timestamp = unicode(datetime(year, month, day,  hour, minutes).strftime("%Y-%m-%d %H:%M:%S"))
world.EnableTrigger("NewsDate", False)
  </send>
  </trigger>
  <trigger
   group="NewsDB"
   enabled="n"
   keep_evaluating="y"
   match="^From\: (.+)$"
   name="NewsFrom"
   regexp="y"
   send_to="12"
   sequence="100"
  >
  <send>
author = u"%1"
world.EnableTrigger("NewsFrom", False)
  </send>
  </trigger>
  <trigger
   group="NewsDB"
   enabled="n"
   keep_evaluating="y"
   match="^To\s+\: (.+)$"
   name="NewsTo"
   regexp="y"
   send_to="12"
   sequence="100"
  >
  <send>
recipient = u"%1"
world.EnableTrigger("NewsTo", False)
  </send>
  </trigger>
  <trigger
   group="NewsDB"
   enabled="n"
   keep_evaluating="y"
   match="^Subj\: (.+)$"
   name="NewsSubject"
   regexp="y"
   send_to="12"
   sequence="100"
  >
  <send>
subject = u"%1"
content = []
world.EnableTrigger("NewsSubject", False)
world.EnableTrigger("NewsContent", True)
world.EnableTrigger("NewsContentBlanks", True)
world.EnableTrigger("NewsMore", True)
world.EnableTrigger("NewsPostamble", True)
world.EnableTrigger("NewsPostambleLost", True)
world.EnableTrigger("PromptCaptureNewsRoom", True)
  </send>
  </trigger>
  <trigger
   group="NewsDB"
   enabled="n"
   keep_evaluating="y"
   match="^(.+)$"
   name="NewsContent"
   regexp="y"
   send_to="12"
   sequence="100"
  >
  <send>
content.append(u"%0")
  </send>
  </trigger>
  <trigger
   group="NewsDB"
   enabled="n"
   keep_evaluating="y"
   match="^$"
   name="NewsContentBlanks"
   regexp="y"
   send_to="12"
   sequence="100"
  >
  <send>
content.append(u"%0")
  </send>
  </trigger>
  <trigger
   group="NewsDB"
   enabled="n"
   keep_evaluating="y"
   match="^\[Type MORE if you wish to continue reading\. \(\d+\% shown\)\]$"
   name="NewsMore"
   regexp="y"
   send_to="12"
   sequence="100"
  >
  <send>
content.pop()
world.EnableTrigger("NewsContinue", True)
world.EnableTrigger("NewsContent", False)
world.EnableTrigger("NewsContentBlanks", False)
world.EnableTrigger("NewsPostamble", False)
world.EnableTrigger("NewsPostambleLost", False)
world.EnableTrigger("PromptCaptureNewsRoom", False)
world.EnableTrigger("NewsMore", False)
world.Note("NewsDB: Requesting MORE...")
world.Send("MORE")
  </send>
  </trigger>
  <trigger
   group="NewsDB"
   enabled="n"
   keep_evaluating="y"
   match="^\[File continued via MORE\]$"
   name="NewsContinue"
   regexp="y"
   send_to="12"
   sequence="100"
  >
  <send>
world.EnableTrigger("NewsContent", True)
world.EnableTrigger("NewsContentBlanks", True)
world.EnableTrigger("NewsMore", True)
world.EnableTrigger("NewsPostamble", True)
world.EnableTrigger("NewsPostambleLost", True)
world.EnableTrigger("NewsContinue", False)
  </send>
  </trigger>
  <trigger
   group="NewsDB"
   enabled="n"
   keep_evaluating="y"
   match="^Penned by (M|m)y hand on the"
   name="NewsPostamble"
   regexp="y"
   send_to="12"
   sequence="100"
  >
  <send>
world.EnableTrigger("NewsContent", False)
world.EnableTrigger("NewsContentBlanks", False)
world.EnableTrigger("NewsMore", False)
world.EnableTrigger("PromptCaptureNewsDB", True)
world.EnableTrigger("PromptCaptureNewsRoom", True)
world.EnableTrigger("NewsPostamble", False)
world.EnableTrigger("NewsPostambleLost", False)
  </send>
  </trigger>
  <trigger
   group="NewsDB"
   enabled="n"
   keep_evaluating="y"
   match="^That article doesn\'t exist or has been lost\.$"
   name="NewsPostambleLost"
   regexp="y"
   send_to="12"
   sequence="100"
  >
  <send>
world.EnableTrigger("NewsPreamble", False)
world.EnableTrigger("NewsDate", False)
world.EnableTrigger("NewsFrom", False)
world.EnableTrigger("NewsTo", False)
world.EnableTrigger("NewsSubject", False)
world.EnableTrigger("NewsContent", False)
world.EnableTrigger("NewsContentBlanks", False)
world.EnableTrigger("NewsMore", False)
world.EnableTrigger("NewsPostamble", False)
world.EnableTrigger("NewsPostambleLost", False)
world.EnableTrigger("PromptCaptureNewsDB", True)
world.EnableTrigger("PromptCaptureNewsRoom", True)
  </send>
  </trigger>
  <trigger
   group="NewsDB"
   enabled="n"
   keep_evaluating="y"
   match="^\d+h(, \d+m)?(, \d+e)?(, \d+w)? [@cexkdb]*(?: Vote)?-"
   name="PromptCaptureNewsDB"
   regexp="y"
   send_to="12"
   sequence="900"
  >
  <send>
world.Note("NewsDB: I won't work outside the News room!")
newslist = []
world.EnableTrigger("NewsSection", False)
world.EnableTrigger("NewsPreamble", False)
world.EnableTrigger("NewsDate", False)
world.EnableTrigger("NewsFrom", False)
world.EnableTrigger("NewsTo", False)
world.EnableTrigger("NewsSubject", False)
world.EnableTrigger("NewsContent", False)
world.EnableTrigger("NewsContentBlanks", False)
world.EnableTrigger("NewsMore", False)
world.EnableTrigger("NewsContinue", False)
world.EnableTrigger("NewsPostamble", False)
world.EnableTrigger("NewsPostambleLost", False)
world.EnableTrigger("PromptCaptureNewsDB", False)
world.EnableTrigger("PromptCaptureNewsRoom", False)
  </send>
  </trigger>
  <trigger
   group="NewsDB"
   enabled="n"
   keep_evaluating="y"
   match="^News\> $"
   name="PromptCaptureNewsRoom"
   regexp="y"
   send_to="12"
   sequence="900"
  >
  <send>
world.EnableTrigger("NewsSection", False)
world.EnableTrigger("NewsContent", False)
world.EnableTrigger("NewsContentBlanks", False)
world.EnableTrigger("NewsMore", False)
world.EnableTrigger("NewsPostable", False)
world.EnableTrigger("NewsPostambleLost", False)
world.EnableTrigger("PromptCaptureNewsDB", False)
world.EnableTrigger("PromptCaptureNewsRoom", False)
if len(newslist) > 0:
    Note("NewsDB: Reading specified news, items left: %d" % len(newslist))
ProcessNews(orgname, newsid, timestamp, author, recipient, subject, content)
ProcessNewsList()
  </send>
  </trigger>
</triggers>

<!--  Aliases  -->

<aliases>
  <alias
   match="^NewsDB:addnews (\w+) (\d+)( \d+)?$"
   enabled="y"
   regexp="y"
   send_to="12"
   ignore_case="y"
   sequence="100"
  >
  <send>
if len(newslist) > 0:
    Note("NewsDB: I'm currently reading the last order of which %d items are left." % len(newslist))
elif len("%3") > 0:
    newslist = range(int("%2"), int("%3") + 1)
    newslist.sort(reverse=True)
    world.Send("SECTION %1")
    ProcessNewsList()
else:
    newslist = [int("%2")]
    world.EnableTrigger("NewsSection", True)
    world.EnableTrigger("PromptCaptureNewsDB", True)
    world.Send("SECTION %1")
    ProcessNewsList()
  </send>
  </alias>
  <alias
   match="^NewsDB:readnews (\w+) (\d+)$"
   enabled="y"
   regexp="y"
   send_to="12"
   ignore_case="y"
   sequence="100"
  >
  <send>
ShowNews(u"%1", int("%2"))
  </send>
  </alias>
  <alias
   match="^NewsDB:search (\w+) (.+)$"
   enabled="y"
   regexp="y"
   send_to="12"
   ignore_case="y"
   sequence="100"
  >
  <send>
SearchNews(orgname=u"%1", content=u"%2")
  </send>
  </alias>
  <alias
   match="^NewsDB:readnext$"
   enabled="y"
   regexp="y"
   send_to="12"
   ignore_case="y"
   sequence="100"
  >
  <send>
ReadNext()
  </send>
  </alias>
  <alias
   match="^NewsDB:readprev$"
   enabled="y"
   regexp="y"
   send_to="12"
   ignore_case="y"
   sequence="100"
  >
  <send>
ReadPrev()
  </send>
  </alias>
  <alias
   match="^NewsDB:nstat$"
   enabled="y"
   regexp="y"
   send_to="12"
   ignore_case="y"
   sequence="100"
  >
  <send>NStat()</send>
  </alias>
  <alias
   match="^NewsDB:nsum (\w+) (\d+)$"
   enabled="y"
   regexp="y"
   send_to="12"
   ignore_case="y"
   sequence="100"
  >
  <send>NSum(u"%1", int("%2"))</send>
  </alias>
  <alias
   match="^NewsDB:export (\w+)$"
   enabled="y"
   regexp="y"
   send_to="12"
   ignore_case="y"
   sequence="100"
  >
  <send>DumpData(u"%1")</send>
  </alias>
  <alias
   match="^NewsDB:export (\w+) from\:(\d+) to\:(\d+)$"
   enabled="y"
   regexp="y"
   send_to="12"
   ignore_case="y"
   sequence="100"
  >
  <send>DumpData(u"%1", int("%2"), int("%3"))</send>
  </alias>
  <alias
   match="^NewsDB:import$"
   enabled="y"
   regexp="y"
   send_to="12"
   ignore_case="y"
   sequence="100"
  >
  <send>LoadData()</send>
  </alias>
  <alias
   match="^NewsDB:test (.*?)$"
   enabled="y"
   regexp="y"
   send_to="12"
   ignore_case="y"
   sequence="100"
  >
  <send>exec(u"%1")</send>
  </alias>
</aliases>

<!--  Script  -->

<script>
<![CDATA[
import sqlite3
import cPickle
from random import uniform
from datetime import datetime

import Tkinter
root = Tkinter.Tk()
root.withdraw() # to hide the Tk GUI window as per http://stackoverflow.com/a/1796726

from tkFileDialog import asksaveasfilename, askopenfilename

def Note(message): # not writing world.Note everywhere ^_^
    world.Note(message)

DBFile = world.GetVariable("dbpath")
if not DBFile:
    while not (DBFile and len(DBFile) > 0):
        DBFile = asksaveasfilename(defaultextension=".db", filetypes=[("SQLite3 database file", "*.db")], title="Select a new file to save your database into.")
    world.SetVariable("dbpath", DBFile)
    world.SaveState

db = sqlite3.connect(DBFile)
cursor = db.cursor()

def createdb():
    cursor.execute("PRAGMA foreign_keys=ON")
    cursor.execute("""
    CREATE TABLE IF NOT EXISTS orgs (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        orgname TEXT UNIQUE
    )""")
    cursor.execute("""
    CREATE TABLE IF NOT EXISTS org_news (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        newsid INTEGER,
        author TEXT,
        recipient TEXT,
        subject TEXT,
        timestamp TEXT,
        f_content TEXT,
        orgid INTEGER REFERENCES orgs(id) ON DELETE CASCADE
    )""")
    cursor.execute("""
    CREATE INDEX IF NOT EXISTS org_news_index ON org_news (newsid, author, recipient, subject, timestamp, orgid)
    """)
    cursor.execute("""
    CREATE VIRTUAL TABLE IF NOT EXISTS org_news_fts USING fts4(content="org_news", f_content)
    """)
    cursor.execute("""
    CREATE TRIGGER IF NOT EXISTS org_news_ai AFTER INSERT ON org_news BEGIN
        INSERT INTO org_news_fts(docid, f_content) VALUES(new.rowid, new.f_content);
    END;
    """)
    cursor.execute("""
    CREATE TRIGGER IF NOT EXISTS org_news_bd BEFORE DELETE ON org_news BEGIN
        DELETE FROM org_news_fts WHERE docid=old.rowid;
    END;
    """)
    db.commit()

createdb()
newslist = []
resultset = []
resultindex = 0
flipflop = False

def ProcessNewsList():
    sleeptime = uniform(1, 3)
    global flipflop
    if flipflop:
        world.DoAfterSpecial(sleeptime, "ProcessNewsList()", 12)
        flipflop = False
        return
    else:
        flipflop = True
    if len(newslist) > 0:
        world.EnableTrigger("NewsPreamble", True)
        world.EnableTrigger("NewsPostambleLost", True)
        newspost = newslist.pop()
        world.Send("READ %d" % newspost)
    else:
        Note("NewsDB: Finished reading the specified news into database ^_^")

def ProcessOrg(orgname):
    cursor.execute("SELECT id FROM orgs WHERE orgname=?", (orgname, ))
    results = cursor.fetchall()
    if not len(results) > 0:
        cursor.execute("INSERT INTO orgs (orgname) VALUES (?)", (orgname, ))
        cursor.execute("SELECT last_insert_rowid()")
        results = cursor.fetchone()
        return results[0]
    else:
        return results[0][0]

def ProcessNews(orgname, newsid, timestamp, author, recipient, subject, content):
    content = "\n".join(content)
    orgid = ProcessOrg(orgname)
    cursor.execute("SELECT newsid FROM org_news n JOIN orgs o ON n.orgid=o.id WHERE o.orgname=? AND n.newsid=?", (orgname, newsid))
    results = cursor.fetchall()
    if not len(results) > 0:
        cursor.execute("INSERT INTO org_news (newsid, author, recipient, subject, timestamp, f_content, orgid) VALUES (?, ?, ?, ?, datetime(?), ?, ?)", (newsid, author, recipient, subject, timestamp, content, orgid))
    db.commit()

def ValidateOrgname(orgname):
    cursor.execute("SELECT orgname FROM orgs WHERE orgname LIKE ?", ("%" + orgname + "%", ))
    orgnames = cursor.fetchall()
    if len(orgnames) > 1:
        Note("Oops, multiple organisations match the supplied input:")
        for i in orgnames:
            Note(i[0])
        for i in orgnames:
          if i[0] == orgname:
            Note("Results for exact match [%s]" % i[0])
            return i[0]
    elif len(orgnames) < 1:
        Note("No matching organisations found :(")
    else:
        orgname = orgnames[0][0]
        return orgname
    return None

def ShowNews(orgname, newsid):
    orgname = ValidateOrgname(orgname)
    if orgname is None: # bail out
        return

    cursor.execute("SELECT orgname, newsid, timestamp, author, recipient, subject, f_content FROM org_news n JOIN orgs o ON n.orgid=o.id WHERE o.orgname=? AND n.newsid=? LIMIT 1", (orgname, newsid))
    results = cursor.fetchall()
    if len(results) > 0:
        (orgname, newsid, timestamp, author, recipient, subject, content) = results[0]
        Note("""
%s NEWS #%d
Date: %s
From: %s
To  : %s
Subj: %s
%s""" % (orgname, newsid, timestamp, author, recipient, subject, content))
    else:
        Note("NewsDB: No item with the given id was found in %s's news database." % orgname)

def SearchNews(orgname, content):
    orgname = ValidateOrgname(orgname)
    if orgname is None: # bail out
        return

    cursor.execute("SELECT id FROM orgs WHERE orgname=?", (orgname, ))
    orgid = cursor.fetchone()[0]

    cursor.execute("SELECT newsid, author, subject, snippet(org_news_fts, '[', ']', '...') FROM org_news_fts fts JOIN org_news n ON fts.docid=n.id WHERE fts.f_content MATCH ? AND orgid=? ORDER BY n.timestamp", (content, orgid))
    results = cursor.fetchall()

    if len(results) > 0:
        global resultset
        global resultindex
        resultset = [orgname]
        resultindex = 0
        Note("-"*80)
        Note("[News #] [From]          [Subject]            [Snippet]")
        Note("-"*80)
        for i in results:
            (newsid, author, subject, snippet) = i
            resultset.append(newsid)
            newsid = str(newsid)

            # center the search terms in the snippet before it is snipped
            snippet_index = snippet.find('[') - 10
            snippet = "..." + snippet[snippet_index:][3:]

            if len(newsid) > 8:
                newsid = newsid[:8]
            else:
                newsid = newsid + " "*(8-len(newsid))
            if len(author) > 15:
                author = author[:14] + " "
            else:
                author = author + " "*(15-len(author))
            if len(subject) > 20:
                subject = subject[:17] + ".. "
            else:
                subject = subject + " "*(20-len(subject))
            snippet = snippet.replace("\n", " ")
            if len(snippet) > 33:
                snippet = snippet[:31] + "..."
            Note("%s %s %s %s" % (newsid, author, subject, snippet))
        Note("-"*80)
        Note("Total results: %d" % len(results))
    else:
        Note("NewsDB: The specified query did not return any results.")

def ReadNext():
    global resultset
    global resultindex
    if len(resultset) > 1:
        (orgname, newsids) = (resultset[0], resultset[1:])
        if resultindex < len(newsids):
            ShowNews(orgname, newsids[resultindex])
            resultindex += 1
        else:
            Note("NewsDB: Already at the last search result.")
    else:
        Note("NewDB: There are no results in the buffer, try searching for something first with newsdb:search <org> <search expression>")

def ReadPrev():
    global resultset
    global resultindex
    if len(resultset) > 1:
        (orgname, newsids) = (resultset[0], resultset[1:])
        if resultindex > 0:
            resultindex -= 1
            ShowNews(orgname, newsids[resultindex])
        else:
            Note("NewsDB: Already at the first search result.")
    else:
        Note("NewDB: There are no results in the buffer, try searching for something first with newsdb:search <org> <search expression>")

def NStat():
    cursor.execute("SELECT orgname, COUNT(newsid) FROM org_news n JOIN orgs o ON n.orgid = o.id GROUP BY orgname")
    results = cursor.fetchall()
    if len(results) > 0:
        orgnames = {}
        for i in results:
            orgnames[i[0]] = i[1]
        for i in orgnames.keys():
            if len(i) > 30:
                o_name = i[30:]
            else:
                o_name = i + " "*(30-len(i)) + ":"
            Note("%s\t%d articles in database." % (o_name.title(), orgnames[i]))
    else:
        Note("NewDB: We got nothing indexed so far, make your way to a News Room and try newsdb:addnews <org> <from post number> <to post number>")

def NSum(orgname, newspost):
    orgname = ValidateOrgname(orgname)
    if orgname is None: # bail out
        return

    cursor.execute("SELECT newsid, author, subject FROM org_news n JOIN orgs o ON n.orgid=o.id WHERE orgname=? AND n.newsid>=?", (orgname, newspost))
    results = cursor.fetchall()
    if len(results) > 0:
        Note("""
****************************[ PUBLIC NEWS SUMMARY ]****************************
ID      Author                     Title
-------------------------------------------------------------------------------""")
        for i in results[:20]:
            (newsid, author, subject) = i
            n_id = str(newsid)
            if len(n_id) > 7:
                n_id = n_id[:7]
            else:
                n_id = n_id + " "*(7-len(n_id))
            if len(author) > 26:
                author = author[:26]
            else:
                author = author + " "*(26-len(author))
            if len(subject) > 39:
                subject = subject[:39]
            else:
                subject = subject + " "*(39-len(subject))
            Note("%s %s %s" % (n_id, author, subject))
        Note("*******************************************************************************")
        if len(results) > 20:
            Note("NewsDB: Enter newsdb:nsum %s %d to continue." % (orgname, newsid+1))
    else:
        Note("NewsDB: Not a valid post number to begin with. Perhaps that post is not in the database yet?")

def DumpData(orgname, fromid=None, toid=None):
    orgname = ValidateOrgname(orgname)
    if orgname is None: # bail out
        return

    filename = asksaveasfilename(defaultextension=".pickle", filetypes=[("NewsDB Pickle", "*.pickle")])
    if filename is '': # bail out
        Note("NewsDB: Export cancelled by user.")
        return

    if fromid is None:
        fromid = 1
    if toid is None:
        cursor.execute("SELECT newsid FROM org_news n JOIN orgs o ON n.orgid=o.id WHERE o.orgname=? ORDER BY newsid DESC LIMIT 1", (orgname, ))
        results = cursor.fetchall()
        toid = results[0][0]

    cursor.execute("SELECT orgname, newsid, timestamp, author, recipient, subject, f_content FROM org_news n JOIN orgs o ON n.orgid=o.id WHERE o.orgname=? AND n.newsid>=? AND n.newsid<=?", (orgname, fromid, toid))
    results = cursor.fetchall()

    with open(filename, 'w') as dump_file:
        cPickle.dump(results, dump_file)
    Note("Exported a total of %d objects." % len(results))

def LoadData():
    filename = askopenfilename(defaultextension=".pickle", filetypes=[("NewsDB Pickle", "*.pickle")])
    if filename is '': # bail out
        Note("NewsDB: Import cancelled by user.")
        return

    with open(filename, 'r') as load_file:
        try:
            results = cPickle.load(load_file)
        except:
            Note("NewsDB: Invalid file or the file does not contain a NewsDB pickle object.")
            return

    try:
        total_objects = len(results)
        orgname = results[0][0]
        orgid = ProcessOrg(orgname)
        import_set = []
        for i in range(len(results)):
            (orgname, newsid, timestamp, author, recipient, subject, f_content) = results[i]
            cursor.execute("SELECT newsid FROM org_news WHERE orgid=? AND newsid=?", (orgid, newsid))
            n_results = cursor.fetchall()
            if not len(n_results) > 0: # here we prune results to avoid duplicates
                import_set.append((newsid, author, recipient, subject, timestamp, f_content, orgid))

        cursor.executemany("""
        INSERT INTO org_news (newsid, author, recipient, subject, timestamp, f_content, orgid) VALUES (?, ?, ?, ?, datetime(?), ?, ?)
        """, import_set) # this line makes the inserts go super fast
        db.commit()
        Note("NewsDB: Imported a total of %d new objects." % len(import_set))
    except sqlite3.Error as e:
        Note("SQLite error: {0}".format(e.message))
    except:
        Note("NewsDB: Invalid file or the file does not contain a NewsDB pickle object.")

]]>
</script>

<!--  Plugin help  -->

<aliases>
  <alias
   script="OnHelp"
   match="NewsDB:help"
   ignore_case="y"
   enabled="y"
  >
  </alias>
</aliases>

<script>
<![CDATA[
def OnHelp (a, b, c):
    world.note (world.GetPluginInfo (world.GetPluginID, 3))
]]>
</script>

</muclient>
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.