diff options
Diffstat (limited to 'cgi/post.py')
| -rw-r--r-- | cgi/post.py | 88 | 
1 files changed, 55 insertions, 33 deletions
| diff --git a/cgi/post.py b/cgi/post.py index 89c2a19..07b05bc 100644 --- a/cgi/post.py +++ b/cgi/post.py @@ -7,6 +7,7 @@ import threading  import queue  import formatting  import logging +import html  from database import *  from template import * @@ -193,7 +194,7 @@ def shortenMsg(message, elid='0', elboard='0'):      if len(message_shortened) > limit:          message_shortened = message_shortened[:limit] -    #message_shortened = formatting.close_html(message_shortened) +    message_shortened = formatting.close_html(message_shortened)      return True, message_shortened    else: @@ -722,12 +723,14 @@ def deletePost(postid, password, deltype=0, imageonly=False, quick=False):      if not post["parentid"]:        deleteReplies(post) -    logging.info("Deleting post " + str(postid)) +    logging.info("Deleting post %d - parentid: %d" % (post["id"], post["parentid"]))      if deltype != 0 and post["parentid"]:        # Soft delete (recycle bin) +      logging.info("Soft delete")        UpdateDb("UPDATE `posts` SET `IS_DELETED` = %s WHERE `boardid` = %s AND `id` = %s LIMIT 1", (deltype, board["id"], post["id"]))      else:        # Hard delete +      logging.info("Hard delete")        if post["file"]:          deleteFile(post) @@ -745,10 +748,16 @@ def deletePost(postid, password, deltype=0, imageonly=False, quick=False):                  (newlast["timestamp"], threadNumReplies(post["parentid"]), post["parentid"], board["id"]))      if not post['parentid']: +      logging.info("Unlinking html")        if board['board_type'] == 1: -        os.unlink(Settings.ROOT_DIR + str(board["dir"]) + "/res/" + str(post["timestamp"]) + ".html") +        fname = Settings.ROOT_DIR + str(board["dir"]) + "/res/" + str(post["timestamp"]) + ".html"        else: -        os.unlink(Settings.ROOT_DIR + str(board["dir"]) + "/res/" + str(post["id"]) + ".html") +        fname = Settings.ROOT_DIR + str(board["dir"]) + "/res/" + str(post["id"]) + ".html" + +      try: +        os.unlink(fname) +      except FileNotFoundError: +        logging.warn("Thread HTML (%s) didn't exist! Continuing..." % fname)      regenerateHome() @@ -907,7 +916,7 @@ def autoclose_thread(parentid, t, replies):      notice_post["bumped"] = get_parent_post(parentid, board["id"])["bumped"]      notice_post["timestamp_formatted"] = str(replylimit) + " mensajes"      notice_post.insert() -    UpdateDb("UPDATE `posts` SET `locked` = 1 WHERE `boardid` = '%s' AND `id` = '%s' LIMIT 1" % (board["id"], _mysql.escape_string(parentid))) +    UpdateDb("UPDATE `posts` SET `locked` = 1 WHERE `boardid` = %s AND `id` = %s LIMIT 1", (board["id"], parentid))  def pageNavigator(page_num, page_count, is_omitted=False):    """ @@ -972,10 +981,12 @@ def flood_check(t,post,boardid):    if not post["parentid"]:      maxtime = round(t - int(board['threadsecs'])) -    #lastpost = FetchOne("SELECT COUNT(*) FROM `posts` WHERE `ip` = INET6_ATON('%s') and `parentid` = 0 and `boardid` = '%s' and IS_DELETED = 0 AND timestamp > %d" % (str(post["ip"]), boardid, int(maxtime)), 0) +    lastpost = FetchOne("SELECT `timestamp` FROM `posts` WHERE `ip` = INET6_ATON(%s) and `parentid` = 0 and `boardid` = %s and IS_DELETED = 0 AND timestamp > %s", +        (post["ip"], boardid, maxtime))      # NO MATTER THE IP -    lastpost = FetchOne("SELECT `timestamp` FROM `posts` WHERE `parentid` = 0 and `boardid` = %s and IS_DELETED = 0 AND timestamp > %s", +    if not lastpost: +        lastpost = FetchOne("SELECT `timestamp` FROM `posts` WHERE `parentid` = 0 and `boardid` = %s and IS_DELETED = 0 AND timestamp > %s",                         (boardid, maxtime))    else:      maxtime = round(t - int(board['postsecs'])) @@ -990,11 +1001,10 @@ def flood_check(t,post,boardid):        wait = int(int(board['threadsecs']) - (t - int(lastpost["timestamp"])))        raise UserError("Espera " + str(wait) + " segundos antes de crear otro hilo.") -def cut_home_msg(message, boardlength=0): +def cut_msg(message, limit):    short_message = message.replace("<br />", " ")    short_message = short_message.split("<hr />")[0]    short_message = re.compile(r"<[^>]*?>", re.DOTALL | re.IGNORECASE).sub("", short_message) # Removes HTML tags -  limit = Settings.HOME_LASTPOSTS_LENGTH - boardlength    if len(short_message) > limit:      if isinstance(short_message, str): @@ -1002,6 +1012,9 @@ def cut_home_msg(message, boardlength=0):      short_message = re.compile(r"&(.(?!;))*$", re.DOTALL | re.IGNORECASE).sub("", short_message) # Removes incomplete HTML    return short_message +def cut_home_msg(message, boardlength=0): +  return cut_msg(message, Settings.HOME_LASTPOSTS_LENGTH - boardlength) +  def getLastAge(board_type, limit):    threads = []    sql = "SELECT posts.id, boards.name AS board_fulln, boards.subname AS board_name, board_type, boards.dir, timestamp, bumped, last, length, thumb, CASE WHEN posts.subject = boards.subject THEN posts.message ELSE posts.subject END AS content FROM posts INNER JOIN boards ON boardid = boards.id WHERE parentid = 0 AND IS_DELETED = 0 AND boards.secret = 0 AND posts.locked < 3 AND boards.board_type = %s ORDER BY bumped DESC LIMIT %s" @@ -1209,12 +1222,13 @@ def latestAdd(post, postnum, postid, parent_post):    else:      url = '/%s/res/%s.html#%s' % (board['dir'], parentid, postid) -  sql = "INSERT INTO last (id, boardid, board_name, timestamp, timestamp_formatted, content, url) VALUES ('%s', '%s', '%s', '%s', '%s', '%s', '%s')" % (str(postid), board['id'], _mysql.escape_string(board['name']), post['timestamp'], _mysql.escape_string(timestamp_formatted), _mysql.escape_string(content), _mysql.escape_string(url)) -  UpdateDb(sql) +  sql = "INSERT INTO last (id, boardid, board_name, timestamp, timestamp_formatted, content, url) VALUES (%s, %s, %s, %s, %s, %s, %s)" +  params = (postid, board['id'], board['name'], post['timestamp'], timestamp_formatted, content, url) +  UpdateDb(sql, params)  def latestRemove(postid):    board = Settings._.BOARD -  UpdateDb("DELETE FROM last WHERE id = %s AND boardid = %s" % (str(postid), board['id'])) +  UpdateDb("DELETE FROM last WHERE id = %s AND boardid = %s", (postid, board['id']))  def archiveThread(postid):    import json @@ -1271,7 +1285,7 @@ def magic_ball():    return string -def discord_hook(post, url): +def discord_hook(post, parent_post, url):    if not Settings.DISCORD_HOOK_URL:      return @@ -1280,23 +1294,31 @@ def discord_hook(post, url):    board = Settings._.BOARD -  #data = {"embeds": [{ -  #    "title": post['subject'], -  #    "description": cut_home_msg(post['message'], 30), -  #    "url": "https://bienvenidoainternet.org" + url, # TODO: Parametrizar. -  #    "color": 11910504, -  #    "timestamp": datetime.datetime.utcfromtimestamp(post['timestamp']).isoformat(), -  #    "footer": { "text": board['name'] }, -  #    "thumbnail": { "url": "%s%s/thumb/%s" % (Settings.HOME_URL, board['dir'], post['thumb']) }, -  #    "author": { -  #      "name": "Nuevo hilo", -  #      "icon_url": "%s0/junk/w/shobon.gif" % Settings.HOME_URL -  #    }}] -  #} -  data = {"content": "test"} -  jsondata = json.dumps(data, separators=(',',':')) - -  opener = urllib.request.build_opener() -  #opener.addheaders = [('User-Agent', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:59.0) Gecko/20100101 Firefox/59.0')] -  response = opener.open(Settings.DISCORD_HOOK_URL, jsondata, 6) -  the_page = response.read() +  if parent_post: +    ptitle = "Nueva respuesta en {} ({})".format(html.unescape(parent_post["subject"]), parent_post["length"]+1) +  else: +    ptitle = "Nuevo hilo: {}".format(html.unescape(post['subject'])) + +  data = {"embeds": [{ +      "type": "rich", +      "title": ptitle, +      "description": html.unescape(cut_msg(post['message'], 200)), +      "color": 11910504, +      "url": "https://bienvenidoainternet.org" + url, # TODO: Parametrizar. +      "timestamp": datetime.datetime.utcfromtimestamp(post['timestamp']).isoformat(), +      "footer": { "text": board['name'] }, +      }] +  } +  if post['thumb']: +    data["embeds"][0]["thumbnail"] = {"url": "%s%s/thumb/%s" % (Settings.HOME_URL, board['dir'], post['thumb'])} +  jsondata = json.dumps(data, separators=(',',':')).encode('utf-8') + +  try: +    req = urllib.request.Request(Settings.DISCORD_HOOK_URL) +    req.add_header('Content-Type', 'application/json') +    req.add_header('Content-Length', len(jsondata)) +    req.add_header('User-Agent', "weabot/0.1") +    response = urllib.request.urlopen(req, jsondata) +  except urllib.error.HTTPError as e: +    raise Exception(e.read()) +   | 
