Skip to content

Commit

Permalink
Merge pull request #33 from r-anime/daily_thread_inline
Browse files Browse the repository at this point in the history
Trigger daily thread rotation from new post feed
  • Loading branch information
durinthal authored Mar 13, 2024
2 parents ab7eaa8 + d4cd11f commit 3577b83
Show file tree
Hide file tree
Showing 14 changed files with 291 additions and 233 deletions.
1 change: 0 additions & 1 deletion scripts/modapps.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
One caveat is that the username field must be sanitized (i.e. ensured valid) in the CSV prior to running this script.
"""


import argparse
import csv
from datetime import datetime, timedelta
Expand Down
10 changes: 10 additions & 0 deletions src/constants/post_constants.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
"""
Static values about posts that generally shouldn't need to change.
"""

LINK_REGEX = r"\[{name}\]\(.*?\)"
LINK_FORMAT = "[{name}]({link})"

DAILY_THREAD_NAME = "Anime Questions, Recommendations, and Discussion"
DAILY_THREAD_SHORT_NAME = "Daily Megathread"
DAILY_THREAD_AUTHOR = "AnimeMod"
11 changes: 11 additions & 0 deletions src/feeds/new_posts.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
from praw.models.reddit.submission import Submission

import config_loader
from constants import post_constants
from services import post_service, base_data_service
from utils import discord, reddit as reddit_utils
from utils.logger import logger
Expand Down Expand Up @@ -45,6 +46,16 @@ def process_post(submission: Submission):

base_data_service.update(post)

# If this is a new daily thread, do all the updating for it.
if (
author_name == post_constants.DAILY_THREAD_AUTHOR
and post_constants.DAILY_THREAD_NAME.lower() in post.title.lower()
):
try:
post_service.rotate_daily_thread(post)
except Exception:
logger.exception("Unable to process new daily thread")

logger.debug(f"Finished processing {post.id36}")


Expand Down
92 changes: 0 additions & 92 deletions src/old/daily.py

This file was deleted.

142 changes: 5 additions & 137 deletions src/old/menuupdater.py
Original file line number Diff line number Diff line change
@@ -1,17 +1,13 @@
from datetime import datetime, timezone, timedelta
import re
import time

import praw

import config_loader
from services import post_service, sidebar_service
from utils import reddit
from utils.logger import logger


SEARCH_TIMEOUT = 3600
LINK_REGEX = r"\[{name}\]\(.*?\)"
LINK_FORMAT = "[{name}]({link})"


class SubredditMenuUpdater:
Expand Down Expand Up @@ -39,8 +35,10 @@ def __init__(self, name, short_name, author, debug=False):
self.subreddit = self.reddit.subreddit(config_loader.REDDIT["subreddit"])

post = self._find_post(name, author)
self._update_menus(name, post)
self._update_redesign_menus(name, short_name, post)
db_post = post_service.get_post_by_id(post.id)
sidebar_service.replace_sidebar_link(name, reddit.make_relative_link(db_post), self.subreddit)
sidebar_service.update_redesign_menus(name, short_name, db_post, self.subreddit)

logger.info(f"Completed running subreddit menu updater for {name}")

def _find_post(self, name, author):
Expand All @@ -60,133 +58,3 @@ def _find_post(self, name, author):
if time.time() - search_start_time > SEARCH_TIMEOUT:
raise TimeoutError("Post not found")
time.sleep(15)

def _update_menus(self, name, post):
"""
Updates the sidebar text by replacing links to `name` with a permalink
to `post`. Links formatting is defined by config.
For example, the default format for links is `'[{name}](.*)'`
:param name: name of the link to format
:param post: post which should be linked to
"""
logger.debug("Updating menus on old Reddit")

pattern_match = LINK_REGEX.format(name=name)
pattern_replace = LINK_FORMAT.format(name=name, link=post.shortlink)

sidebar = self.subreddit.wiki["config/sidebar"]
sidebar_text = sidebar.content_md
sidebar_updated_text = self._replace_text(pattern_match, pattern_replace, sidebar_text)

if sidebar_updated_text is None:
logger.debug("No change necessary")
elif self.debug:
logger.debug("Running in debug mode, no change was made to sidebar")
else:
sidebar.edit(content=sidebar_updated_text, reason=f"Changed link for {name}")
logger.debug("Changes saved to sidebar")

def _update_redesign_menus(self, name, short_name, post):
"""
Updates the menu and widget text on Redesign by replacing links to
`name` with a permaling to `post`. Links formatting is identical to the
formatting used on old Reddit.
:param name: name of the link to format
:param short_name: name of the link to use in topbar menu (max 20 characters)
:param post: post which should be linked to
"""
logger.debug("Updating menus on Redesign")

assert len(short_name) <= 20

topmenu = self._get_updated_redesign_topmenu(short_name, post.shortlink)
if topmenu is None:
logger.debug("Error updating topmenu")
elif self.debug:
logger.debug("Running in debug mode, no change was made to top menu")
else:
topmenu.mod.update(data=list(topmenu))
logger.debug("Topbar menu updated")

pattern_match = LINK_REGEX.format(name=name)
pattern_replace = LINK_FORMAT.format(name=name, link=post.shortlink)

sidemenu = self._get_redesign_sidemenu(name)
sidemenu_text = sidemenu.text
sidemenu_updated_text = self._replace_text(pattern_match, pattern_replace, sidemenu_text)

if sidemenu_updated_text is None:
logger.debug("No change necessary")
elif self.debug:
logger.debug("Running in debug mode, no change was made to side menu")
else:
sidemenu.mod.update(text=sidemenu_updated_text)
logger.debug("Sidebar widget updated")

def _get_updated_redesign_topmenu(self, name, new_url):
"""
Update the menu by replacing links labeled `name` with `new_url` and
return the updated menu. Updates are *not* reflected to the subreddit
by calling this method.
:param name: text of the menulink to update
:param new_url: replacement url
"""
menu = self.subreddit.widgets.topbar[0]
assert isinstance(menu, praw.models.Menu)

for item in menu:
if isinstance(item, praw.models.MenuLink):
if item.text == name:
logger.debug(f"Found replaceable MenuLink: {item.text}")
item.url = new_url
elif isinstance(item, praw.models.Submenu):
for subitem in item:
if isinstance(subitem, praw.models.MenuLink):
if subitem.text == name:
logger.debug(f"Found replaceable MenuLink: {item.text}")
subitem.url = new_url
else:
logger.debug(f"Wrong type found searching for MenuLink: {item.__class__}")
else:
logger.debug(f"Wrong type found searching for MenuLink: {item.__class__}")

return menu

def _get_redesign_sidemenu(self, name):
"""
Return the sidebar widget containing a link to `name`.
:param name: name of the link to update
"""
sidebar = self.subreddit.widgets.sidebar

pattern_match = LINK_REGEX.format(name=name)

for widget in sidebar:
if isinstance(widget, praw.models.TextArea):
matches = re.findall(pattern_match, widget.text)
if matches:
logger.debug(f"Found matching side widget '{widget.shortName}'")
return widget

logger.debug("Found no sidebar widget with replaceable match")
return None

def _replace_text(self, pattern_match, pattern_replace, text):
matches = re.findall(pattern_match, text)
if not matches:
logger.debug("Found no replaceable match")
return None

logger.debug(
"Found replaceable matches\n"
+ f'\t\t\tOld text: {" // ".join(matches)}\n'
+ f"\t\t\tNew text: {pattern_replace}"
)

text_replaced = re.sub(pattern_match, pattern_replace, text)
return text_replaced
Loading

0 comments on commit 3577b83

Please sign in to comment.