wantzel.py 31.9 KB
Newer Older
1
# encoding: utf-8
2
"""
Mindiell's avatar
Mindiell committed
3
Bot Wantzel from La Quadrature du Net.
4

Mindiell's avatar
Mindiell committed
5 6
License : AGPLv3
Doc     : https://wiki.laquadrature.net/Wantzel
7 8
"""

9
import random
10
import re
11 12
import sqlite3
import time
13 14 15 16

import feedparser
from irc import IrcClientFactory
import MySQLdb
17
from twisted.internet import reactor
18
from twitter import Twitter, OAuth
19 20 21 22

import config
from messages import messages

Mindiell's avatar
Mindiell committed
23 24 25 26 27 28 29
LOG_FILE = "wantzel.log"
DEBUG = 3
WARNING = 2
INFO = 1
ERROR = 0
LOG_LEVEL = DEBUG

30 31 32
MASTER_SCORE = 5
MASTER_CLEANING = 7  # in days

Mindiell's avatar
Mindiell committed
33 34
RP_CHANNEL = "#mytipy"

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
animals = [
    {
        "left": """><((('>""",
        "right": """<')))><""",
        "sound": "blub",
    },
    {
        "left": """=^..^=""",
        "right": """=^..^=""",
        "sound": "meow",
    },
    {
        "left": """ˁ˚ᴥ˚ˀ""",
        "right": """ˁ˚ᴥ˚ˀ""",
        "sound": "wouf",
    },
    {
        "left": """\_o<""",
        "right": """>o_/""",
        "sound": "coin",
    },
    {
        "left": """^(*(oo)*)^""",
        "right": """^(*(oo)*)^""",
        "sound": "grouïk",
    },
    {
        "left": """~~(__^·>""",
        "right": """<·^__)~~""",
        "sound": "yiik",
    },
]

Mindiell's avatar
Mindiell committed
68
class Utils(object):
69 70 71
    """
    Simple utility class to log easily.
    """
Mindiell's avatar
Mindiell committed
72 73
    @classmethod
    def log(cls, message):
74 75 76 77 78
        """
        Logging message with timestamp.
        """
        actual_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
        with open(LOG_FILE, 'a') as file_handle:
79
            try:
80
                file_handle.write("%s: %s\n" % (actual_time, message.encode("utf-8")))
81 82
            except UnicodeDecodeError:
                file_handle.write("%s: %s\n" % (actual_time, message))
Mindiell's avatar
Mindiell committed
83 84 85

    @classmethod
    def debug(cls, message):
86 87 88 89
        """
        Manage DEBUG level of logging.
        """
        if LOG_LEVEL >= DEBUG:
Mindiell's avatar
Mindiell committed
90 91 92 93
            cls.log("%s: %s" % ("DEBUG", message))

    @classmethod
    def warning(cls, message):
94 95 96 97
        """
        Manage WARNING level of logging.
        """
        if LOG_LEVEL >= WARNING:
Mindiell's avatar
Mindiell committed
98 99 100 101
            cls.log("%s: %s" % ("WARNING", message))

    @classmethod
    def info(cls, message):
102 103 104 105
        """
        Manage INFO level of logging.
        """
        if LOG_LEVEL >= INFO:
Mindiell's avatar
Mindiell committed
106 107 108 109
            cls.log("%s: %s" % ("INFO", message))

    @classmethod
    def error(cls, message):
110 111 112 113
        """
        Manage ERROR level of logging.
        """
        if LOG_LEVEL >= ERROR:
Mindiell's avatar
Mindiell committed
114 115 116 117
            cls.log("%s: %s" % ("ERROR", message))



Mindiell's avatar
Mindiell committed
118 119
def get_cursor():
    """
120
    This function connects to a MySQL database and returns a usable cursor.
Mindiell's avatar
Mindiell committed
121
    """
122
    connection = MySQLdb.connect(
Mindiell's avatar
Mindiell committed
123 124 125 126 127
        host=config.dbserver,
        user=config.dbuser,
        passwd=config.dbpassword,
        db=config.dbname
    )
128 129
    if connection:
        return connection.cursor()
Mindiell's avatar
Mindiell committed
130 131
    return None

132

133
def get_url(message):
Mindiell's avatar
Mindiell committed
134
    """
135
    Retrieve the url in the message.
Mindiell's avatar
Mindiell committed
136
    """
137 138
    # Let's get the url
    result = re.search("(https?[^ ]+)", message)
Mindiell's avatar
Mindiell committed
139
    if not result:
140
        return
141
    url = result.group(1)
Mindiell's avatar
Mindiell committed
142 143 144 145 146 147 148 149
    # Removing anchor if needed
    result = re.search("^([^#]*)", url)
    if result:
        url = result.group(1)
    # Removing trackers
    url = re.sub("[?&](utm_medium|utm_source|utm_campaign|xtor)=[^&]*", "", url)
    return url

150

151 152 153 154 155 156 157
def is_moderator(name):
    """
    This function verify if a user is a moderator.
    """
    connection = sqlite3.connect(config.sqlite_db)
    cursor = connection.cursor()
    cursor.execute("SELECT count(*) FROM moderator WHERE name=?", (name, ))
158
    if int(cursor.fetchone()[0]) == 1:
159 160 161 162
        return True
    return False


163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181
def tweet(message):
    """
    Tweet message on specified account
    """
    Utils.debug("tweet method")
    auth = OAuth(
        config.TOKEN,
        config.TOKENSEC,
        config.CONSKEY,
        config.CONSSEC
    )
    twitter = Twitter(auth=auth)
    try:
        Utils.debug("Tweeting: %s" % message)
        twitter.statuses.update(status=message)
    except Exception:
        pass


182 183 184 185 186 187 188 189
class Wantzel(object):
    """
    Wantzel bot.
    """
    def __init__(self):
        """
        Initialization of bot over IRC.
        """
190 191 192 193 194 195 196 197
        # Date of next cleaning
        next_week = time.localtime(time.mktime(time.localtime())+(MASTER_CLEANING*86400))
        self.next_cleaning = time.strptime("%s-%s-%s %s" % (
            next_week.tm_year,
            next_week.tm_mon,
            next_week.tm_mday,
            time.tzname[0]
        ), "%Y-%m-%d %Z")
Mindiell's avatar
Mindiell committed
198 199
        # Sequence for op_mode verification (fibonacci)
        self.op_sequence = [1, 2, 3, 5, 8, 13, 21, 34, 55]
200 201 202
        self.op_offset = 0
        self.op_counter = 0
        # Number of articles actually waiting
203
        self.number = None
204
        # default last_entry_published for tweets
205
        self.last_entry_published = time.strptime("2000-01-01", "%Y-%m-%d")
206
        # See if there is a later last_entry_published for tweets
207 208 209 210 211 212
        connection = sqlite3.connect(config.sqlite_db)
        for row in connection.execute("SELECT last_entry_published FROM tweets"):
            self.last_entry_published = time.strptime(
                row[0].encode("utf-8"),
                "%Y-%m-%d %H:%M:%S %Z"
            )
213
        Utils.debug("Dernier tweet: %s" % self.last_entry_published)
214 215
        # default last_entry_published for wiki
        self.last_entry_updated = time.strptime("2000-01-01", "%Y-%m-%d")
216
        # See if there is a later last_entry_published for wiki
217 218 219 220 221 222 223 224
        connection = sqlite3.connect(config.sqlite_db)
        for row in connection.execute("SELECT last_entry_updated FROM wikis"):
            self.last_entry_updated = time.strptime(
                row[0].encode("utf-8"),
                "%Y-%m-%d %H:%M:%S %Z"
            )
        Utils.debug("Dernière mise à jour du wiki: %s" % self.last_entry_updated)

225
        # Connection to IRC
226 227 228
        self.irc = IrcClientFactory(config)
        self.irc.set_privmsg = self.set_privmsg
        reactor.connectTCP(config.server, config.port, self.irc)
229 230 231 232 233 234 235
        # Prepare timer
        reactor.callLater(config.timer, self.timer)

    def timer(self):
        """
        This method launches function regularly (see config.timer).
        """
Mindiell's avatar
Mindiell committed
236
        Utils.debug("Timer called")
237
        # Tweet some RP based on french and english feeds
238 239
        self.rp_to_twitter("http://www.laquadrature.net/fr/revue-de-presse/feed")
        self.rp_to_twitter("http://www.laquadrature.net/en/press-review/feed")
240
        # Update topice based on number of articles waiting in queue 
241
        self.count_articles()
242
        # Verify op mode
243
        self.op_verification()
244
        # Tell on channel if wiki was modified since last time
245
        self.wiki_updates()
246
        # Cleaning points of mastering rp
Mindiell's avatar
Mindiell committed
247
        if time.localtime()>self.next_cleaning:
248
            self.clean_master_rp()
249 250
        # Recalling the timer
        reactor.callLater(config.timer, self.timer)
251 252 253 254 255

    def set_privmsg(self):
        """
        This method set the methods to call for each callback received from IRC.
        """
256
        # When receiving a message
257
        self.irc.client.privmsg = self.on_privmsg
258 259 260
        # When the bot discover it is no more op
        self.irc.client.irc_unknown = self.irc_unknown
        # When bot mode is changed
261 262
        self.irc.client.modeChanged = self.mode_changed

263
    def mode_changed(self, user, channel, flag_set, modes, args):
264
        """
265
        Callback called whenever bot mode is changed.
266 267
        """
        Utils.debug("Mode changed : %s %s %s %s %s" % (user, channel, flag_set, modes, args))
Mindiell's avatar
Mindiell committed
268
        if "o" in modes and self.irc.client.nickname in args:
269 270 271
            # Cleaning user name
            user = re.search("([^!]*)!", user).group(1)
            if flag_set:
272
                # thanks to user
273
                self.send_message(channel, messages["oped"] % user)
Mindiell's avatar
Mindiell committed
274 275
                # reset counter and sequence
                self.op_counter = 0
276
                self.op_offset = 0
277
            else:
278
                # bad user ;o(
279 280
                self.send_message(channel, messages["deoped"] % user)

281 282 283 284 285
    def op_verification(self):
        """
        Verify if wantzel is chan operator, if not it complains on the chan <3.
        """
        Utils.debug("op_verification method")
Mindiell's avatar
Mindiell committed
286 287
        # Bot tries to list channel users, if it can't, then it is no more an op
        self.irc.client.sendLine("NAMES %s" % RP_CHANNEL)
288 289 290 291

    def irc_unknown(self, prefix, command, params):
        """
        This Callback is called whenever the bot tries to perform the command "NAMES" on the
Mindiell's avatar
Mindiell committed
292
        RP_CHANNEL channel. If it occurs, then the bot knows that it is no more op and beg for
293 294 295 296 297 298 299
        a mode change to actual operators on the channel.
        """
        Utils.debug("UNKNOWN %s %s %s" % (prefix, command, params))
        if command=="RPL_NAMREPLY":
            # Beg for operator mode
            self.names(params)

300
    def names(self, params):
301
        """
Mindiell's avatar
Mindiell committed
302
        Send a message on channel RP_CHANNEL to beg an op mode to each actual operators.
303 304 305 306 307 308
        params is an array with :
            - params[0]:
            - params[1]:
            - params[2]: the channel
            - params[3]: the list of all users on the channel
        """
309
        Utils.debug("Names : %s" % params)
Mindiell's avatar
Mindiell committed
310
        if params[2]==RP_CHANNEL:
311 312
            ops = [user[1:] for user in params[3].split() if user[0]=="@"]
            if "@"+self.irc.client.nickname not in params[3]:
Mindiell's avatar
Mindiell committed
313 314 315 316 317 318 319 320 321 322 323 324
                # Testing based on fibonacci sequence
                self.op_counter += 1
                Utils.debug("op_counter  : %s" % self.op_counter)
                Utils.debug("op_offset   : %s" % self.op_offset)
                Utils.debug("op_sequence : %s" % self.op_sequence[self.op_offset])
                if self.op_counter>self.op_sequence[self.op_offset]:
                    self.send_message(params[2], messages["please_op"] % ", ".join(ops))
                    # Then reset op_counter
                    self.op_counter = 0
                    # And move the sequence further in order not to spam channel
                    if self.op_offset<len(self.op_sequence)-1:
                        self.op_offset += 1
325

326
    def send_message(self, channel, multiline_message):
327 328 329
        """
        Sends a message on specified channel, cutting each line in a new message
        """
330
        for message in multiline_message.splitlines():
331 332 333 334
            self.irc.client.msg(channel, message)

    def on_privmsg(self, user, channel, msg):
        """
335 336
        Wantzel can understand a lot of commands. Commands followed by a (*)
        are accessible only to moderators:
337 338 339
        - help
            Returns a message about how to use the bot.
            If a command is passed after help, the message explains how to use
340
            the command.
341
            Bot answers in private in order not to spam channel
342
        - rp(acp) <url>
343
            Add an article in the database with a specific flag
344 345
        - status <url>
            Retrieve some informations about an article in the database
346
        - stats
Mindiell's avatar
Mindiell committed
347
            Show some statistics about the RP
348
        - kill (*)
Mindiell's avatar
Mindiell committed
349
            Kill an article by giving it a score of -100
350
        - admin list (*)
351
            List rights in private
352
        - admin add (*)
353 354 355
            Add one or more new moderator to list
        - admin del (*)
            Delete one or more moderator from list
356
        - admin timer
357
            Relaunch a timer
358 359
        """
        # Cleaning user name
Mindiell's avatar
Mindiell committed
360
        user = re.search("([^!]*)!", user).group(1)
Mindiell's avatar
Mindiell committed
361
        Utils.debug("Message received: %s %s %s" % (user, channel, msg))
Mindiell's avatar
Mindiell committed
362
        # Never answer to botself
363
        if user!=config.nickname:
Mindiell's avatar
Mindiell committed
364 365 366 367 368
            # If it's a query, bot should answer to the user as the channel
            if "#" not in channel:
                channel = user
            # Help command, specific
            if "wantzel" in msg and ("help" in msg or "aide" in msg):
369
                self.help(user, channel, msg)
Mindiell's avatar
Mindiell committed
370
            # Find known command
371
            command = re.search("[!~](rp[acp]*|status|kill|help|stats|admin)", msg)
Mindiell's avatar
Mindiell committed
372
            Utils.debug("Command: %s" % command)
Mindiell's avatar
Mindiell committed
373
            if command:
Mindiell's avatar
Mindiell committed
374
                Utils.debug("group(0): %s" % command.group(0))
Mindiell's avatar
Mindiell committed
375
                command = command.group(1)
Mindiell's avatar
Mindiell committed
376
                Utils.debug("Command: %s" % command)
Mindiell's avatar
Mindiell committed
377
                if command.startswith("rp"):
Mindiell's avatar
Mindiell committed
378
                    Utils.debug("Calling self.rp")
379
                    self.rp(command, user, channel, msg)
380 381 382
                if command.startswith("status"):
                    Utils.debug("Calling self.status")
                    self.status(command, user, channel, msg)
383
                elif command == "help":
Mindiell's avatar
Mindiell committed
384
                    Utils.debug("Calling self.help")
385
                    self.help(user, channel, msg)
386
                elif command == "kill":
Mindiell's avatar
Mindiell committed
387
                    Utils.debug("Calling self.kill")
Mindiell's avatar
Mindiell committed
388
                    self.kill(user, channel, msg)
389
                elif command == "stats":
Mindiell's avatar
Mindiell committed
390
                    Utils.debug("Calling self.stats")
391 392
                    self.stats(channel)
                elif command == "admin":
Mindiell's avatar
Mindiell committed
393
                    Utils.debug("Calling self.admin")
394
                    self.admin(user, channel, msg)
395 396
            # Very specific command for fun only. You can easily garbage or
            # comment the next few lines
397
            if user.lower()=="deltree" and msg=="\_o< ~ Coin ~ >o_/":
398 399 400 401 402 403 404
                animal = random.choice(animals)
                self.send_message(channel, messages["coin_deltree"] % (
                    animal["left"],
                    animal["sound"],
                    animal["sound"],
                    animal["right"],
                ))
405 406
            # End of fun command.

407 408 409
        # No more giving the title of an url
        #if title and website:
        #    self.send_message(channel, messages["title"] % (title, website))
410

411
    def help(self, user, channel, msg):
412 413
        """
        Show global help.
414
        If a known command is behind the ~!help command, an adequate message is
415 416
        returned.
        """
Mindiell's avatar
Mindiell committed
417
        Utils.debug("help command")
Mindiell's avatar
Mindiell committed
418
        # Searching for a command after help keyword
419
        command = re.search("[!~]help (help|rp|status|stats|kill|admin)", msg)
Mindiell's avatar
Mindiell committed
420 421
        if command:
            command = command.group(1)
422
            self.send_message(user, messages["help_"+command])
Mindiell's avatar
Mindiell committed
423
        else:
424
            self.send_message(user, messages["help"])
425

426
    def rp(self, command, user, channel, msg):
427 428 429
        """
        Adding the article in rp database.
        """
Mindiell's avatar
Mindiell committed
430
        Utils.debug("rp command : %s" % command)
Mindiell's avatar
Mindiell committed
431
        Utils.debug("rp user    : %s" % user)
Mindiell's avatar
Mindiell committed
432
        Utils.debug("rp channel : %s" % channel)
Mindiell's avatar
Mindiell committed
433
        Utils.debug("rp msg     : %s" % msg)
434
        cite = 0
435
        note = 1
436
        answer = False
437
        url = get_url(msg)
Mindiell's avatar
Mindiell committed
438
        Utils.debug("url: %s" % url)
439
        if not url:
Mindiell's avatar
Mindiell committed
440
            return
441

442 443 444 445 446 447 448 449 450 451 452
        # Managing flags
        # LQdN is quoted
        if "c" in command:
            cite += 1
        # the article speak about LQdN
        if command.count("p") > 1:
            cite += 2
        # Archive this article
        if "a" in command:
            cite += 4

Mindiell's avatar
Mindiell committed
453 454
        # Looking for such an article in database
        cursor = get_cursor()
455 456 457 458 459 460 461 462 463 464 465 466
        # We need to be able to retrieve an url with "http" or "https"
        if url.startswith("https"):
            url2 = "http" + url[5:]
        else:
            url2 = "https" + url[4:]
        cursor.execute("""
            SELECT id, note, provenance
            FROM presse
            WHERE url = %s
            OR url = %s""",
            (url, url2)
        )
467 468
        rows = cursor.fetchall()
        if not rows:
Mindiell's avatar
Mindiell committed
469
            Utils.debug("Adding an article by %s: %s" % (user, url))
470 471
            cursor.execute("""
                INSERT INTO presse SET
472
                url=%s, provenance=%s, cite=%s, note=%s, datec=NOW(), title='',
473 474
                lang='', published=0, nid=0, screenshot=0, fetched=0, seemscite=0
                """,
475
                (url, user, cite, note)
476
            )
477
            answer = True
478
        else:
479
            if rows[0][2] != user:
Mindiell's avatar
Mindiell committed
480
                Utils.debug("Adding a point by %s on %s" % (user, rows[0][0]))
481
                cursor.execute(
482 483 484
                    "UPDATE presse SET note=note+1 WHERE id=%s",
                    (rows[0][0], )
                )
485 486 487
            note = rows[0][1]+1
            answer = True
            if note>=3:
488 489
                # Update number of articles to do
                self.count_articles()
490 491 492 493 494 495 496 497 498 499 500 501 502 503 504
        if answer:
            # Answer is now based on where, who, note, and a little magic
            self.did_rp(channel, user, note)

    def did_rp(self, channel, user, note):
        """
        Answers after a "rp" command has been submitted. The answer is based on the channel, the
        user and the note of the article.
        """
        know_rp = False
        known_user = False
        master_user = False
        # Retrieve user's score in database
        connection = sqlite3.connect(config.sqlite_db)
        score = 0
Mindiell's avatar
Mindiell committed
505
        for row in connection.execute("SELECT score FROM rpator WHERE name='%s'" % user):
506 507 508 509
            known_user = True
            score = int(row[0])
            if score>MASTER_SCORE:
                master_user = True
Mindiell's avatar
Mindiell committed
510 511
        # Channel is RP_CHANNEL, so the user is knowing the rp yet
        if channel==RP_CHANNEL:
512
            know_rp = True
Mindiell's avatar
Mindiell committed
513 514 515 516
        Utils.debug("know_rp     : %s" % know_rp)
        Utils.debug("known_user  : %s" % known_user)
        Utils.debug("score       : %s" % score)
        Utils.debug("master_user : %s" % master_user)
Mindiell's avatar
Mindiell committed
517 518 519 520 521
        # Store new score for this user
        if known_user:
            connection.execute("UPDATE rpator SET score=score+1 WHERE name='%s';" % user)
        else:
            connection.execute("INSERT INTO rpator (name, score) VALUES ('%s', 1);" % user)
522
        connection.commit()
Mindiell's avatar
Mindiell committed
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
        # Ok, we got all information we need, let's answer now !
        if master_user:
            # user is a rp master
            if note==1:
                self.send_message(channel, messages["master_rp_new_article"] % user)
            elif note<3:
                self.send_message(channel, messages["master_rp_known_article"] % user)
            else:
                self.send_message(channel, messages["master_rp_taken_article"] % user)
        elif known_user or know_rp:
            # user is known but not a master and/or he knows the rp channel
            if note==1:
                self.send_message(channel, messages["known_rp_new_article"] % user)
            elif note<3:
                self.send_message(channel, messages["known_rp_known_article"] % user)
            else:
                self.send_message(channel, messages["known_rp_taken_article"] % user)
        else:
            # user is unknown, and he does'nt seems to know the rp channel
            if note==1:
                self.send_message(channel, messages["new_rp_new_article"] % user)
            elif note<3:
                self.send_message(channel, messages["new_rp_known_article"] % user)
            else:
                self.send_message(channel, messages["new_rp_taken_article"] % user)

    def clean_master_rp(self):
        """
        This method cleans the known user from rp_mastering each 7 days
        """
        # Cleaning users
        connection = sqlite3.connect(config.sqlite_db)
        connection.execute("UPDATE rpator SET score=score-1 WHERE user='%s'" % user)
        connection.execute("DELETE FROM rpator WHERE score<1")
558
        connection.commit()
559 560 561 562 563 564 565 566
        # Date of next cleaning
        next_week = time.localtime(time.mktime(time.localtime())+(MASTER_CLEANING*86400))
        self.next_cleaning = time.strptime("%s-%s-%s %s" % (
            next_week.tm_year,
            next_week.tm_mon,
            next_week.tm_mday,
            time.tzname[0]
        ), "%Y-%m-%d %Z")
567

568 569 570 571 572 573 574 575 576 577 578 579 580 581 582
    def status(self, command, user, channel, msg):
        """
        Retrieving status of the article in rp database.
        """
        Utils.debug("rp command : %s" % command)
        Utils.debug("rp user : %s" % user)
        Utils.debug("rp channel : %s" % channel)
        Utils.debug("rp msg : %s" % msg)
        url = get_url(msg)
        Utils.debug("url: %s" % url)
        if not url:
            return

        # Looking for such an article in database
        cursor = get_cursor()
583 584 585 586 587
        # We need to be able to retrieve an url with "http" or "https"
        if url.startswith("https"):
            url2 = "http" + url[5:]
        else:
            url2 = "https" + url[4:]
588
        cursor.execute("""
589
            SELECT cite, nid, note
590
            FROM presse
591 592 593 594
            WHERE url = %s
            OR url = %s""",
            (url, url2)
        )
595 596 597 598
        rows = cursor.fetchall()
        if not rows:
            self.send_message(channel, messages["status_unknown_article"] % user)
        else:
599 600 601 602 603 604 605 606 607
            message = "%s: note %s / " % (user, rows[0][2])
            if rows[0][0] & 1:
                message += "cite LQdN / "
            if rows[0][0] & 2:
                message += "parle de LQdN / "
            if rows[0][0] & 4:
                message += "archivé / "
            if rows[0][1] > 0:
                message += "publié (https://laquadrature.net/node/%s) / " % rows[0][1]
608
            else:
609 610
                message += "non publié / "
            self.send_message(channel, message[:-3])
611

612 613
    def kill(self, user, channel, msg):
        """
Mindiell's avatar
Mindiell committed
614
        Kill an article by setting its score to -100.
615
        """
Mindiell's avatar
Mindiell committed
616
        Utils.debug("kill command")
617 618
        if is_moderator(user):
            url = get_url(msg)
Mindiell's avatar
Mindiell committed
619
            Utils.debug("url: %s" % url)
620
            if url == "":
621
                return
622
            elif url == "http":
623 624 625 626
                self.send_message(channel, messages["rp_http"] % user)
                return
            # Looking for such an article in database
            cursor = get_cursor()
627 628 629 630 631 632 633 634 635 636 637 638
            # We need to be able to retrieve an url with "http" or "https"
            if url.startswith("https"):
                url2 = "http" + url[5:]
            else:
                url2 = "https" + url[4:]
            cursor.execute("""
                SELECT id, note
                FROM presse
                WHERE url = %s
                OR url = %s""",
                (url, url2)
            )
639 640 641 642 643 644
            rows = cursor.fetchall()
            if not rows:
                self.send_message(channel, messages["kill_none"] % url)
            else:
                cursor.execute("UPDATE presse SET note=-100 WHERE id=%s", (rows[0][0], ))
                self.send_message(channel, messages["kill_done"] % url)
Mindiell's avatar
Mindiell committed
645
        else:
646
            self.send_message(channel, messages["not_moderator"])
647

648
    def stats(self, channel):
649 650 651
        """
        Returns stats on articles in press review.
        """
Mindiell's avatar
Mindiell committed
652
        Utils.debug("stats command")
653
        cursor = get_cursor()
654
        periods = [1, 3, 7, 15]
655
        notes = [0, 3, 4]
656 657 658 659
        notnull = 0
        somethingatall = 0
        for note in notes:
            notnull = 0
660
            period_result = ""
661
            for period in periods:
662 663 664
                cursor.execute("""
                    SELECT COUNT(id) AS cid
                    FROM presse
665 666 667 668 669 670
                    WHERE nid=0
                    AND datec>(NOW()-INTERVAL %s DAY)
                    AND note>=%s""",
                    (period, note)
                )
                rows = cursor.fetchall()
671
                if rows[0][0] > 0:
672
                    period_result = period_result + "%sj:%s, " % (period, rows[0][0])
673
                    notnull = 1
Mindiell's avatar
Mindiell committed
674
                    somethingatall = 1
675
            if notnull:
676
                self.send_message(channel, "note>=%s: " % note + period_result[:-2])
677
        if somethingatall == 0:
678
            self.send_message(channel, messages["stats_bravo"] % periods[-1])
679

680 681 682
    def admin(self, user, channel, msg):
        """
        Manage moderation.
683
        A sub-command should be behind the !~admin command.
684
        """
Mindiell's avatar
Mindiell committed
685
        Utils.debug("admin command")
686
        # Searching for a command after admin keyword
687
        command = re.search("[~!]admin (list|add|del|timer)", msg)
688 689
        if command:
            command = command.group(1)
690 691 692
            if command == "list":
                self.admin_list(user, channel)
            elif command == "add":
693
                self.admin_add(user, channel, msg)
694
            elif command == "del":
695
                self.admin_del(user, channel, msg)
696 697
            elif command == "timer":
                self.admin_timer(user, channel)
698

699
    def admin_list(self, user, channel):
700 701 702
        """
        List actual moderators.
        """
Mindiell's avatar
Mindiell committed
703
        Utils.debug("admin_list command")
704 705 706 707 708
        if is_moderator(user):
            connection = sqlite3.connect(config.sqlite_db)
            names = []
            for row in connection.execute("SELECT name FROM moderator"):
                names.append(row[0].encode("utf-8"))
709
            self.send_message(channel, messages["admin_list"] % ", ".join(sorted(names)))
710 711 712 713 714 715 716
        else:
            self.send_message(channel, messages["not_moderator"])

    def admin_add(self, user, channel, msg):
        """
        Add some new moderators if not existing yet.
        """
Mindiell's avatar
Mindiell committed
717
        Utils.debug("admin_add command")
718 719 720 721
        if is_moderator(user):
            try:
                names = []
                connection = sqlite3.connect(config.sqlite_db)
722
                result = re.search("[!~]admin add (([^,]+, ?)+)?(.*)", msg)
723
                if result.group(1):
724
                    names = [name.strip() for name in result.group(1).split(",") if name.strip() != ""]
725 726 727 728 729
                names.append(result.group(3))
                # Do not add actual moderators
                moderators = []
                for row in connection.execute("SELECT name FROM moderator"):
                    moderators.append(row[0].encode("utf-8"))
730
                names = list(set([name for name in names if name not in moderators]))
731 732 733 734 735 736 737 738
                if names:
                    # Converting set in list of tuples
                    values = [(name,) for name in names]
                    connection.executemany("INSERT INTO moderator (name) VALUES (?)", values)
                    connection.commit()
                    self.send_message(channel, messages["admin_add"] % ", ".join(names))
                else:
                    self.send_message(channel, messages["admin_add_empty"])
739
            except Exception:
740 741 742 743 744 745 746 747
                pass
        else:
            self.send_message(channel, messages["not_moderator"])

    def admin_del(self, user, channel, msg):
        """
        Delete a moderator from list.
        """
Mindiell's avatar
Mindiell committed
748
        Utils.debug("admin_del command")
749 750 751
        if is_moderator(user):
            try:
                names = []
752
                result = re.search("[!~]admin del (([^,]+, ?)+)?(.*)", msg)
753
                if result.group(1):
754
                    names = [name.strip() for name in result.group(1).split(",") if name.strip() != ""]
755
                names.append(result.group(3))
756
                names = list(set(names))
Mindiell's avatar
Mindiell committed
757
                Utils.debug(names)
758 759 760 761 762
                connection = sqlite3.connect(config.sqlite_db)
                for name in names:
                    connection.execute("DELETE FROM moderator WHERE name=?", (name, ))
                connection.commit()
                self.send_message(channel, messages["admin_del"] % ", ".join(names))
763
            except Exception:
764 765 766 767
                pass
        else:
            self.send_message(channel, messages["not_moderator"])

768
    def admin_timer(self, user, channel):
769 770 771 772 773 774 775 776
        """
        Relaunch a timer.
        """
        Utils.debug("admin_timer command")
        if is_moderator(user):
            try:
                # Recalling the timer
                reactor.callLater(config.timer, self.timer)
777
            except Exception:
778 779 780 781
                pass
        else:
            self.send_message(channel, messages["not_moderator"])

782 783 784 785 786
    def count_articles(self):
        """
        Count number of articles not done in RP and updates the topic of the
        press review channel if needed.
        """
Mindiell's avatar
Mindiell committed
787
        Utils.debug("count_articles method")
788 789 790 791 792 793 794
        cursor = get_cursor()
        cursor.execute("""SELECT COUNT(*) FROM presse
            WHERE DATE_SUB(NOW(), INTERVAL 2 MONTH)<datec
            AND note > 2
            AND nid = 0""")
        rows = cursor.fetchall()
        number = int(rows[0][0])
795
        Utils.debug("Found %s articles." % number)
796
        if self.number != number:
Mindiell's avatar
Mindiell committed
797
            self.irc.client.topic(RP_CHANNEL, messages["topic"] % number)
798 799 800 801 802 803
        self.number = number

    def rp_to_twitter(self, rss):
        """
        By parsing the RSS feed of the press-review, we know what to tweet.
        """
Mindiell's avatar
Mindiell committed
804
        Utils.debug("rp_to_twitter method")
805 806
        now = time.localtime()
        today = time.strptime("%s-%s-%s %s" % (
807 808 809 810 811
            now.tm_year,
            now.tm_mon,
            now.tm_mday,
            time.tzname[0]
            ), "%Y-%m-%d %Z")
Mindiell's avatar
Mindiell committed
812 813 814
        language = "fr"
        if "/en/" in rss:
            language = "en"
815 816
        entries = feedparser.parse(rss)['entries']
        entries.reverse()
817
        Utils.debug(self.last_entry_published)
818 819 820 821 822
        for entry in entries:
            # if date of publication is greater than today, midnight, and
            # lesser than future
            if today < entry.published_parsed < now:
                if self.last_entry_published < entry.published_parsed:
okhin's avatar
okhin committed
823 824 825 826
                    # Let's see if we can truncate the lenght of the tweet
                    # We have 5 chars for the language, so max-length is 135
                    title = entry.title.encode("utf-8")
                    link = entry.link.encode("utf-8")
827
                    if len(title) + min(len(link),23) > 135:
okhin's avatar
okhin committed
828
                        # What is the number of chars we need to remove
829 830
                        excess = len(title) + min(len(link),23) - 135
                        title = ''.join([title[:-(excess + 4)], ' ...'])
831
                    tweet(messages["tweet_rp_%s" % language] % (
okhin's avatar
okhin committed
832 833
                        title,
                        link
834
                    ))
Mindiell's avatar
Mindiell committed
835
                    Utils.debug(entry.published_parsed)
Mindiell's avatar
Mindiell committed
836
                    Utils.debug(entry.title)
837 838 839 840 841 842 843 844 845 846 847 848 849 850
                    # Save last_entry_published
                    self.last_entry_published = entry.published_parsed
                    last_entry_published = time.strftime(
                        "%Y-%m-%d %H:%M:%S %Z",
                        self.last_entry_published
                    )
                    connection = sqlite3.connect(config.sqlite_db)
                    connection.execute(
                        "UPDATE tweets SET last_entry_published=?",
                        (last_entry_published,)
                    )
                    connection.commit()
                    # Tweet only one message in order not to spam
                    return
851 852 853
                else:
                    Utils.debug(entry.title)
                    Utils.debug(entry.published_parsed)
854

855 856 857 858 859 860 861 862 863 864 865 866 867 868 869
    def wiki_updates(self):
        url = "https://wiki.laquadrature.net/api.php?days=1&limit=50&translations=filter&action=feedrecentchanges&feedformat=atom"
        now = time.localtime()
        today = time.strptime("%s-%s-%s %s" % (
            now.tm_year,
            now.tm_mon,
            now.tm_mday,
            time.tzname[0]
            ), "%Y-%m-%d %Z")
        entries = feedparser.parse(url)['entries']
        for entry in entries:
            # if date of update is greater than today midnight
            if today < entry.updated_parsed:
                if self.last_entry_updated < entry.updated_parsed:
                    # Ecriture de la mise à jour sur le canal de travail
870
                    self.send_message("#lqdn-travail", messages["wiki_update"] % (
871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887
                        entry.author.encode("utf-8"),
                        entry.title.encode("utf-8"),
                        entry.link.encode("utf-8"),
                    ))
                    # Save last_entry_published
                    self.last_entry_updated = entry.updated_parsed
                    last_entry_updated = time.strftime(
                        "%Y-%m-%d %H:%M:%S %Z",
                        self.last_entry_updated
                    )
                    connection = sqlite3.connect(config.sqlite_db)
                    connection.execute(
                        "UPDATE wikis SET last_entry_updated=?",
                        (last_entry_updated,)
                    )
                    connection.commit()

888 889

if __name__ == '__main__':
890
    Wantzel()
891
    reactor.run()