wantzel.py 32.1 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
Mindiell's avatar
Mindiell committed
11 12
import sqlite3
import time
13 14 15 16

import feedparser
from irc import IrcClientFactory
import MySQLdb
17
from twisted.internet import reactor
Mindiell's avatar
Mindiell committed
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
RP_CHANNEL = "#lqdn-rp"
Mindiell's avatar
Mindiell committed
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
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():
    """
Mindiell's avatar
Mindiell committed
120
    This function connects to a MySQL database and returns a usable cursor.
Mindiell's avatar
Mindiell committed
121
    """
Mindiell's avatar
Mindiell committed
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
    )
Mindiell's avatar
Mindiell committed
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

Mindiell's avatar
Mindiell committed
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:
Mindiell's avatar
Mindiell committed
159 160 161 162
        return True
    return False


163 164 165 166 167 168 169 170 171 172 173 174 175 176
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)
177 178 179
        twitter.statuses.update(status=message)
    except Exception as e:
        Utils.error("Erreur lors du tweet : " + str(e))
180 181


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
Mindiell's avatar
Mindiell committed
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
Mindiell's avatar
Mindiell committed
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)
Mindiell's avatar
Mindiell committed
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
Mindiell's avatar
Mindiell committed
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 
Mindiell's avatar
Mindiell committed
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()
Mindiell's avatar
Mindiell committed
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):
        """
Mindiell's avatar
Mindiell committed
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
Mindiell's avatar
Mindiell committed
348
        - kill (*)
Mindiell's avatar
Mindiell committed
349
            Kill an article by giving it a score of -100
350
        - admin list (*)
Mindiell's avatar
Mindiell committed
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
Christophe Le Clerc's avatar
Christophe Le Clerc committed
371
            command = re.search("[!~](rp[acpm]*|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")
Mindiell's avatar
Mindiell committed
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.

Mindiell's avatar
Mindiell committed
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
Christophe Le Clerc's avatar
Christophe Le Clerc committed
436
        is_media = 0
437
        answer = False
438
        url = get_url(msg)
Mindiell's avatar
Mindiell committed
439
        Utils.debug("url: %s" % url)
440
        if not url:
Mindiell's avatar
Mindiell committed
441
            return
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
Christophe Le Clerc's avatar
Christophe Le Clerc committed
453 454 455
        # this is media
        if "m" in command:
            is_media = 1
456

Mindiell's avatar
Mindiell committed
457 458
        # Looking for such an article in database
        cursor = get_cursor()
459 460 461 462 463 464 465 466 467 468 469 470
        # 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)
        )
471 472
        rows = cursor.fetchall()
        if not rows:
Mindiell's avatar
Mindiell committed
473
            Utils.debug("Adding an article by %s: %s" % (user, url))
474 475
            cursor.execute("""
                INSERT INTO presse SET
476
                url=%s, provenance=%s, cite=%s, note=%s, datec=NOW(), title='',
Christophe Le Clerc's avatar
Christophe Le Clerc committed
477
                lang='', published=0, nid=0, screenshot=0, fetched=0, seemscite=0, is_media=%s
478
                """,
Christophe Le Clerc's avatar
Christophe Le Clerc committed
479
                (url, user, cite, note, is_media)
480
            )
481
            answer = True
482
        else:
483
            if rows[0][2] != user:
Mindiell's avatar
Mindiell committed
484
                Utils.debug("Adding a point by %s on %s" % (user, rows[0][0]))
485
                cursor.execute(
486 487 488
                    "UPDATE presse SET note=note+1 WHERE id=%s",
                    (rows[0][0], )
                )
489 490 491
            note = rows[0][1]+1
            answer = True
            if note>=3:
Mindiell's avatar
Mindiell committed
492 493
                # Update number of articles to do
                self.count_articles()
494 495 496 497 498 499 500 501 502 503 504 505 506 507 508
        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
509
        for row in connection.execute("SELECT score FROM rpator WHERE name='%s'" % user):
510 511 512 513
            known_user = True
            score = int(row[0])
            if score>MASTER_SCORE:
                master_user = True
Mindiell's avatar
Mindiell committed
514 515
        # Channel is RP_CHANNEL, so the user is knowing the rp yet
        if channel==RP_CHANNEL:
516
            know_rp = True
Mindiell's avatar
Mindiell committed
517 518 519 520
        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
521 522 523 524 525
        # 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)
526
        connection.commit()
Mindiell's avatar
Mindiell committed
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
        # 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):
        """
556
        This method cleans known users from rp_mastering each 7 days
557 558 559
        """
        # Cleaning users
        connection = sqlite3.connect(config.sqlite_db)
560
        connection.execute("UPDATE rpator SET score=score-1")
561
        connection.execute("DELETE FROM rpator WHERE score<1")
562
        connection.commit()
563 564 565 566 567 568 569 570
        # 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")
571

572 573 574 575 576 577 578 579 580 581 582 583 584 585 586
    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()
587 588 589 590 591
        # 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:]
592
        cursor.execute("""
Christophe Le Clerc's avatar
Christophe Le Clerc committed
593
            SELECT cite, nid, note, is_media
594
            FROM presse
595 596 597 598
            WHERE url = %s
            OR url = %s""",
            (url, url2)
        )
599 600 601 602
        rows = cursor.fetchall()
        if not rows:
            self.send_message(channel, messages["status_unknown_article"] % user)
        else:
603 604 605 606 607 608 609 610 611
            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]
612
            else:
613
                message += "non publié / "
Christophe Le Clerc's avatar
Christophe Le Clerc committed
614 615
            if rows[0][3] == 1:
                message += "media / "
616
            self.send_message(channel, message[:-3])
617

618 619
    def kill(self, user, channel, msg):
        """
Mindiell's avatar
Mindiell committed
620
        Kill an article by setting its score to -100.
621
        """
Mindiell's avatar
Mindiell committed
622
        Utils.debug("kill command")
Mindiell's avatar
Mindiell committed
623 624
        if is_moderator(user):
            url = get_url(msg)
Mindiell's avatar
Mindiell committed
625
            Utils.debug("url: %s" % url)
626
            if url == "":
Mindiell's avatar
Mindiell committed
627
                return
628
            elif url == "http":
Mindiell's avatar
Mindiell committed
629 630 631 632
                self.send_message(channel, messages["rp_http"] % user)
                return
            # Looking for such an article in database
            cursor = get_cursor()
633 634 635 636 637 638 639 640 641 642 643 644
            # 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)
            )
Mindiell's avatar
Mindiell committed
645 646 647 648 649 650
            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
651
        else:
Mindiell's avatar
Mindiell committed
652
            self.send_message(channel, messages["not_moderator"])
653

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

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

705
    def admin_list(self, user, channel):
Mindiell's avatar
Mindiell committed
706 707 708
        """
        List actual moderators.
        """
Mindiell's avatar
Mindiell committed
709
        Utils.debug("admin_list command")
Mindiell's avatar
Mindiell committed
710 711 712 713 714
        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"))
715
            self.send_message(channel, messages["admin_list"] % ", ".join(sorted(names)))
Mindiell's avatar
Mindiell committed
716 717 718 719 720 721 722
        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
723
        Utils.debug("admin_add command")
Mindiell's avatar
Mindiell committed
724 725 726 727
        if is_moderator(user):
            try:
                names = []
                connection = sqlite3.connect(config.sqlite_db)
728
                result = re.search("[!~]admin add (([^,]+, ?)+)?(.*)", msg)
Mindiell's avatar
Mindiell committed
729
                if result.group(1):
730
                    names = [name.strip() for name in result.group(1).split(",") if name.strip() != ""]
Mindiell's avatar
Mindiell committed
731 732 733 734 735
                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"))
736
                names = list(set([name for name in names if name not in moderators]))
Mindiell's avatar
Mindiell committed
737 738 739 740 741 742 743 744
                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"])
745
            except Exception:
Mindiell's avatar
Mindiell committed
746 747 748 749 750 751 752 753
                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
754
        Utils.debug("admin_del command")
Mindiell's avatar
Mindiell committed
755 756 757
        if is_moderator(user):
            try:
                names = []
758
                result = re.search("[!~]admin del (([^,]+, ?)+)?(.*)", msg)
Mindiell's avatar
Mindiell committed
759
                if result.group(1):
760
                    names = [name.strip() for name in result.group(1).split(",") if name.strip() != ""]
Mindiell's avatar
Mindiell committed
761
                names.append(result.group(3))
762
                names = list(set(names))
Mindiell's avatar
Mindiell committed
763
                Utils.debug(names)
Mindiell's avatar
Mindiell committed
764 765 766 767 768
                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))
769
            except Exception:
Mindiell's avatar
Mindiell committed
770 771 772 773
                pass
        else:
            self.send_message(channel, messages["not_moderator"])

774
    def admin_timer(self, user, channel):
775 776 777 778 779 780 781 782
        """
        Relaunch a timer.
        """
        Utils.debug("admin_timer command")
        if is_moderator(user):
            try:
                # Recalling the timer
                reactor.callLater(config.timer, self.timer)
783
            except Exception:
784 785 786 787
                pass
        else:
            self.send_message(channel, messages["not_moderator"])

Mindiell's avatar
Mindiell committed
788 789 790 791 792
    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
793
        Utils.debug("count_articles method")
Mindiell's avatar
Mindiell committed
794 795 796 797 798 799 800
        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])
801
        Utils.debug("Found %s articles." % number)
802
        if self.number != number:
Mindiell's avatar
Mindiell committed
803
            self.irc.client.topic(RP_CHANNEL, messages["topic"] % number)
Mindiell's avatar
Mindiell committed
804 805 806 807 808 809
        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
810
        Utils.debug("rp_to_twitter method")
Mindiell's avatar
Mindiell committed
811 812
        now = time.localtime()
        today = time.strptime("%s-%s-%s %s" % (
813 814 815 816 817
            now.tm_year,
            now.tm_mon,
            now.tm_mday,
            time.tzname[0]
            ), "%Y-%m-%d %Z")
Mindiell's avatar
Mindiell committed
818 819 820
        language = "fr"
        if "/en/" in rss:
            language = "en"
Mindiell's avatar
Mindiell committed
821 822
        entries = feedparser.parse(rss)['entries']
        entries.reverse()
823
        Utils.debug(self.last_entry_published)
Mindiell's avatar
Mindiell committed
824 825 826 827 828
        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
829 830 831 832
                    # 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")
833
                    if len(title) + min(len(link),23) > 135:
okhin's avatar
okhin committed
834
                        # What is the number of chars we need to remove
835
                        excess = len(title) + min(len(link),23) - 135
836
                        title = ''.join([title[:-(excess + 2)], ' …'])
837
                    tweet(messages["tweet_rp_%s" % language] % (
okhin's avatar
okhin committed
838 839
                        title,
                        link
Mindiell's avatar
Mindiell committed
840
                    ))
Mindiell's avatar
Mindiell committed
841
                    Utils.debug(entry.published_parsed)
Mindiell's avatar
Mindiell committed
842
                    Utils.debug(entry.title)
Mindiell's avatar
Mindiell committed
843 844 845 846 847 848 849 850 851 852 853 854 855 856
                    # 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
857 858 859
                else:
                    Utils.debug(entry.title)
                    Utils.debug(entry.published_parsed)
Mindiell's avatar
Mindiell committed
860

861 862 863 864 865 866 867 868 869 870 871 872 873 874 875
    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
876
                    self.send_message("#lqdn-travail", messages["wiki_update"] % (
877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893
                        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()

894 895

if __name__ == '__main__':
896
    Wantzel()
897
    reactor.run()