rp.py 15.7 KB
Newer Older
1 2 3 4 5 6
#encoding: utf-8
"""
Press review methods.
"""

import feedparser
7
import json
8
import MySQLdb
9
import requests
10 11
import sqlite3
import time
Mindiell's avatar
Mindiell committed
12
from twitter import Twitter, OAuth
13 14 15

import config
from logs import Log
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
from utils import get_url, is_moderator

def get_cursor():
    """
    This function connects to a MySQL database and returns a usable cursor.
    """
    connection = MySQLdb.connect(
        host=config.dbserver,
        user=config.dbuser,
        passwd=config.dbpassword,
        db=config.dbname
    )
    if connection:
        return connection.cursor()
    return None

def tweet(message):
    """
    Tweet message on specified account
    """
    Log.debug("tweet method")
    auth = OAuth(
        config.TOKEN,
        config.TOKENSEC,
        config.CONSKEY,
        config.CONSSEC
    )
    twitter = Twitter(auth=auth)
    try:
        Log.debug("Tweeting: %s" % message)
        twitter.statuses.update(status=message)
    except Exception as e:
        Log.error("Erreur lors du tweet : " + str(e))
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

class Rp():
    def __init__(self):
        """
        Initialisation of the press review utilities
        """
        # Date of next cleaning
        next_week = time.localtime(time.mktime(time.localtime())+(config.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")
        # default last_entry_published for tweets
        self.last_entry_published = time.strptime("2000-01-01", "%Y-%m-%d")
        # See if there is a later last_entry_published for tweets
        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"
            )
        Log.debug("Dernier tweet: %s" % self.last_entry_published)

    def tweet(self):
        """
        Tweet some RP based on french and english feeds
        """
        for feed in config.feeds:
            self.rp_to_twitter(feed)

    def rp_to_twitter(self, feed):
        """
        By parsing the RSS feed of the press-review, we know what to tweet.
        """
        Log.debug("rp_to_twitter method")
        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")
        language = "fr"
        if "/en/" in feed:
            language = "en"
        entries = feedparser.parse(feed)['entries']
        entries.reverse()
        Log.debug(self.last_entry_published)
        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:
                    # 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")
                    if len(title) + min(len(link),23) > 135:
                        # What is the number of chars we need to remove
                        excess = len(title) + min(len(link),23) - 135
                        title = ''.join([title[:-(excess + 2)], ' …'])
112 113
                    tweet("[%s] %s — %s" % (
                        language,
114
                        title,
115
                        link,
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
                    ))
                    Log.debug(entry.published_parsed)
                    Log.debug(entry.title)
                    # 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
                else:
                    Log.debug(entry.title)
                    Log.debug(entry.published_parsed)

    def count_articles(self):
        """
        Count number of articles not done in RP and returns new topic of the press review channel
        if necessary.
        """
        Log.debug("count_articles method")
143
        # TODO: Adapt this to new RP
144 145 146 147 148 149 150 151
        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])
        Log.debug("Found %s articles." % number)
152
        return "Canal de la revue de presse de La Quadrature du Net ~ %s articles en attente ~ Mode d'emploi https://wiki.laquadrature.net/Revue_de_presse ~ Une arme, le savoir est. Le diffuser, notre devoir c'est." % number
153 154 155 156 157 158 159 160 161 162 163 164

    def clean_master_rp(self):
        """
        This method cleans known users from rp_mastering each MASTER_CLEANING days
        """
        if time.localtime()>self.next_cleaning:
            # Cleaning users
            connection = sqlite3.connect(config.sqlite_db)
            connection.execute("UPDATE rpator SET score=score-1")
            connection.execute("DELETE FROM rpator WHERE score<1")
            connection.commit()
            # Date of next cleaning
165
            next_week = time.localtime(time.mktime(time.localtime())+(config.MASTER_CLEANING*86400))
166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182
            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")

    def status(self, user, msg):
        """
        Retrieving status of the article in rp database.
        """
        url = get_url(msg)
        Log.debug("url: %s" % url)
        if not url:
            return ""

        # Looking for such an article in database
183
        # TODO: Is this possible with new RP ?
184 185 186 187 188 189 190 191 192 193 194 195 196 197 198
        cursor = get_cursor()
        # 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 cite, nid, note
            FROM presse
            WHERE url = %s
            OR url = %s""",
            (url, url2)
        )
        rows = cursor.fetchall()
        if not rows:
199
            return "Désolé %s, l'url donnée n'existe pas dans la base de données." % user
200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223
        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]
        else:
            message += "non publié / "
        return message[:-3]

    def kill(self, user, msg):
        """
        Kill an article by setting its score to -100.
        """
        Log.debug("kill command")
        if is_moderator(user):
            url = get_url(msg)
            Log.debug("url: %s" % url)
            if url == "":
                return message
            elif url == "http":
224
                return "Merci %s, mais je prends en compte uniquement les adresses internet qui commencent par http ou https" % user
225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240
            # Looking for such an article in database
            cursor = get_cursor()
            # 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)
            )
            rows = cursor.fetchall()
            if not rows:
241
                return "%s n'existe pas dans la base de données." % url
242 243
            else:
                cursor.execute("UPDATE presse SET note=-100 WHERE id=%s", (rows[0][0], ))
244 245
                return "%s mis à -100" % url
        return "Désolé, il ne semble pas que vous ayez les droits pour cette commande."
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

    def stats(self):
        """
        Returns stats on articles in press review.
        """
        Log.debug("stats command")
        cursor = get_cursor()
        periods = [1, 3, 7, 15]
        notes = [0, 3, 4]
        notnull = 0
        somethingatall = 0
        for note in notes:
            notnull = 0
            period_result = ""
            for period in periods:
                cursor.execute("""
                    SELECT COUNT(id) AS cid
                    FROM presse
                    WHERE nid=0
                    AND datec>(NOW()-INTERVAL %s DAY)
                    AND note>=%s""",
                    (period, note)
                )
                rows = cursor.fetchall()
                if rows[0][0] > 0:
                    period_result = period_result + "%sj:%s, " % (period, rows[0][0])
                    notnull = 1
                    somethingatall = 1
            if notnull:
                return "note>=%s: " % note + period_result[:-2]
        if somethingatall == 0:
277
            return "Bravo les neurones, rien en retard depuis ces %s derniers jours!" % periods[-1]
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

    def rp(self, command, user, channel, msg):
        """
        Adding the article in rp database.
        """
        cite = 0
        note = 1
        answer = False
        url = get_url(msg)
        Log.debug("url: %s" % url)
        if not url:
            return ""

        # 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

        # Looking for such an article in database
        cursor = get_cursor()
        # 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)
        )
        rows = cursor.fetchall()
        if not rows:
            Log.debug("Adding an article by %s: %s" % (user, url))
            cursor.execute("""
                INSERT INTO presse SET
                url=%s, provenance=%s, cite=%s, note=%s, datec=NOW(), title='',
                lang='', published=0, nid=0, screenshot=0, fetched=0, seemscite=0
                """,
                (url, user, cite, note)
            )
            answer = True
        else:
            if rows[0][2] != user:
                Log.debug("Adding a point by %s on %s" % (user, rows[0][0]))
                cursor.execute(
                    "UPDATE presse SET note=note+1 WHERE id=%s",
                    (rows[0][0], )
                )
            note = rows[0][1]+1
            answer = True
            if note>=3:
                # Update number of articles to do
                self.count_articles()
339 340

        # Do the same for new RP
341
        Log.debug("Adding article to new RP")
342 343 344 345 346 347
        data = {
            "url": url,
            "speak": True if "c" in command else False,
            "archive": True if "a" in command else False,
            "quote": True if command.count("p") > 1 else False,
        }
348
        Log.debug(data)
349 350 351 352 353 354 355 356 357
        try:
            result = requests.post(
                "%s/articles/" % config.api,
                data=data,
                headers={"Authorization": config.token},
            )
        except Exception as e:
            Log.error("Erreur lors de l'appel à l'API : " + str(e))
        Log.debug(result.status_code)
358
        if result.status_code>=200 and result.status_code<300:
359 360 361 362 363 364
            try:
                article = json.loads(result.text)
                note = article["score"]
                answer = True
            except Exception as e:
                Log.error("Erreur lors de la récupération de l'article : " + str(e))
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
        if answer:
            # Answer is now based on where, who, note, and a little magic
            return 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
        for row in connection.execute("SELECT score FROM rpator WHERE name='%s'" % user):
            known_user = True
            score = int(row[0])
            if score>config.MASTER_SCORE:
                master_user = True
        # Channel is RP_CHANNEL, so the user is knowing the rp yet
        if channel==config.RP_CHANNEL:
            know_rp = True
        Log.debug("know_rp     : %s" % know_rp)
        Log.debug("known_user  : %s" % known_user)
        Log.debug("score       : %s" % score)
        Log.debug("master_user : %s" % master_user)
        # 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)
        connection.commit()

        # Ok, we got all information we need, let's answer now !
        if master_user:
            # user is a rp master
            if note==1:
403
                return "Merci pour l'info %s !" % user
404
            elif note<3:
405
                return "Merci %s !" % user
406
            else:
407
                return "Merci %s ! L'article est prêt pour la revue de presse !" % user
408 409 410
        elif known_user or know_rp:
            # user is known but not a master and/or he knows the rp channel
            if note==1:
411
                return "Merci %s, cette url a été ajoutée à la revue de presse !" % user
412
            elif note<3:
413
                return "Merci %s ! Un point a été ajouté à cet article : à partir de 3, il pourra être repris dans la revue de presse." % user
414
            else:
415
                return "Merci %s ! Un point a été ajouté à cet article : il va être repris dans la revue de presse." % user
416 417 418
        else:
            # user is unknown, and he does'nt seems to know the rp channel
            if note==1:
419
                return "Merci %s, cette url a été ajoutée à la revue de presse ! À présent, que dirais-tu d'aider à choisir les extraits de l'article à publier sur #lqdn-rp ? <3" % user
420
            elif note<3:
421
                return "Merci %s ! Un point a été ajouté à cet article : à partir de 3, il pourra être repris dans la revue de presse. D'ailleurs, que dirais-tu d'aider à choisir les extraits à publier sur #lqdn-rp ? <3" % user
422
            else:
423
                return "Merci %s ! Un point a été ajouté à cet article : il va être repris dans la revue de presse. D'ailleurs, que dirais-tu d'aider à choisir les extraits à publier sur #lqdn-rp ? <3" % user