Skip Navigation

PieFed Plugins

Members
0
Posts
7
Created
1 yr. ago

Share Plugin snippets and discuss PieFed Plugin development.

Be warned the plugin system hooks directly into PieFed and has the potential to mess up your instance, don't copypaste scripts unless you know what you're doing.

🌉 bridged from !piefed_plugins@piefed.social by Tidepool

New Plugin Hooks in PieFed 1.6.20 - New Communities and Webhooks

There are a couple new plugin hooks that were introduced in PieFed 1.6.20 that I wanted to make a post about to help spread the knowledge. As part of this, the plugins doc page has also been updated, but feel free to ask questions here as well if any come to mind.

New Community Hooks

The first two I wanted to mention are the easy ones. They are related to new communities: 1. new_local_community 2. new_remote_community These hooks fire whenever a new local community is created, or a new remote community has been federated to your instance. The Community object is passed to the plugin directly. A potential use-case for a plugin utilizing these hooks would be some kind of integration with a community discovery service. I already made an untested proof of concept to announce new local communities to the Threadirator service that tries to auto-federate new communities across instances for discoverability.

The Webhook Hook

Broadly speaking, this hook lets you send webhooks to your PieFed instance and process that data with your plugins. As part of this, we added a new route to PieFed, POST /webhook, that fires the webhook plugin hook whenever it handles a valid request. So, here is what happens: 1. Some other service or API or whatever, sends a POST to /webhook with some kind of json payload. 2. As long as there is a valid json payload, then the webhook plugin hook will fire and that payload will be passed on to the plugin as a dict. 3. Every plugin utilizing this hook is called sequentially, so plugins utilizing this hook, should return the original, unaltered payload in case other plugins also need to utilize it, or if the payload was intended for a different plugin. 4. After firing the webhook plugin, the PieFed instance will return a 202 to the original request to /webhook to indicate that the request was properly passed to the plugin(s) on the server. There are some important notes I wanted to add about this plugin hook. As I already mentioned, because of the flexibility of this hook, it is quite possible that multiple plugins could be present on the same instance all utilizing it. So, any plugin utilizing this hook should do a couple things: 1. return the webhook payload unaltered for the next plugin to inspect 2. handle any input verification and authorization within the plugin 3. gracefully handle cases where the payload is not structured for, or intended for use with your plugin - just ignore it or log it instead of raising an exception Also of note is that there is a rate limit on the /webhook route of no more than 60 requests per minute. So, if you are trying to integrate some service that is sending more requests than that, then you should look into batching them in some way or modifying the view function for your instance to remove the rate limit.

Update: PieFed Application Actions Now Supports Sending Webhooks

In addition to the previously existing functionality of sending email(s) when an application is ready to review, now you can also (or alternatively) send a webhook. From the readme:

This feature lets you specify a webhook url and payload that is fired when an application is ready for review. The payload is a dict that is defined in the config file. You can use variable substitution in specified fields of your payload to help support properly formatting things like message bodies. The full list of variable substitutions is documented in the config file. It might not be desirable to do this substitution for all fields of the payload, so only fields that you specify will be formatted in this way. Add any fields you want to do variable substitution for to the webhook_format_fields list in the config file.

Upgrade notes

You probably want to rework your email templates if you previously set them up. Some variable names changed in the new email templates to make it easier to share variables across both the email and webhook functionality.

codeberg.org

PieFed Application Actions

This is the beginning of a plugin that performs actions when a new user application is ready for admin review. Currently, the only feature is that it can send an email address with the registration information to a list of specified email addresses. In the future, there isn't any reason this couldn't trigger other things (webhooks, other scripts, etc.) depending on demand.

codeberg.org

Plugin Experiment: Matplotlib Charts v0.0.1

Caution: This is not a working plugin. This is intended to highlight some ways the plugin system could be used in the future. But this specific code is an early attempt and not up to quality standards. Description: Experiment on plugin use-cases. Generates statistics graphs about posts, replies, users and instances over time, along with versions, languages and voting behaviour of a user. It reads from the database and writes files to the public directory served by the webserver. Images are public and can be accessed by anyone, so factor that in and don't publish somewhat personal information like the voting behavour in the last chart. This does some expensive database queries as well. It's just experimentation, not meant to be deployed yet. Additional dependencies: matplotlib charts/init.py

 python
import os, sys  
import logging  

from app.plugins.hooks import hook  
from flask import current_app, g, Blueprint  
from app.utils import get_task_session  
from app.models import Site, Instance, Post, PostReply, User, ActivityPubLog, PostVote, PostReplyVote  
from sqlalchemy import text, func, literal_column, and_, or_  

from matplotlib.figure import Figure  
from matplotlib.colors import TABLEAU_COLORS  
import matplotlib.dates as mdates  
from datetime import datetime, timedelta  


PLUGIN_NAME = __name__.split('.')[-1]  
logger = logging.getLogger(__name__)  


def fetch_stats(session, obj, interval='day', starttime=None, endtime=None, count1=None, count2=None, sum2=None, createdcolumn=None):  
    if interval not in ['hour', 'day', 'week', 'month']:  
        interval = 'day'  
    if not starttime:  
        starttime = g.site.created_at  
    if not endtime:  
        endtime = datetime.now()  
    if not count1:  
        count1 = [obj.id != None]  
    if not createdcolumn:  
        createdcolumn = obj.created_at  

    timeseries = func.generate_series(starttime, endtime, f"1 {interval}").alias('timeseries')  
    one = literal_column("1")  

    if count2:  
        data = session.query(timeseries.column, func.count(one).filter(*count1), func.count(one).filter(*count2))  
    elif sum2:  
        data = session.query(timeseries.column, func.count(one).filter(*count1), func.sum(sum2))  
    else:  
        data = session.query(timeseries.column, func.count(one).filter(*count1))  
    data = data.select_from(timeseries).outerjoin(obj, func.date_trunc(interval, createdcolumn) == func.date_trunc(interval, timeseries.column))  
    data = data.group_by(timeseries.column).order_by(timeseries.column)  

    if interval == 'day':  
        data = data.all()[2:-2] # throw away first two days and today to remove outliers/unstable data  

    data2 = {'timestamp': [], 'count1': [], 'count2': [], 'zeros': []}  
    for row in data:  
        data2['timestamp'].append(row[0])  
        data2['count1'].append(row[1])  
        if count2:  
            data2['count2'].append(row[2])  
        data2['zeros'].append(0)  

    return data2  


@hook("cron_daily")  
def generate_charts_loop(data):  
    """Hook that runs on a periodic interval"""  
    from app import redis_client  
    with current_app.app_context(), get_task_session() as session:  
        g.site = session.query(Site).get(1)  

        languages = session.execute(text('SELECT language.name, COUNT(*) FROM post LEFT JOIN language ON post.language_id = language.id AND post.deleted = False GROUP BY name ORDER BY count DESC LIMIT 10')).all()  
        colors = list( TABLEAU_COLORS.keys() )  
        colors.insert(1, 'lightgray')  
        fig = Figure()  
        ax = fig.add_subplot()  
        labels = [r.name if r.name else 'Unknown' for r in languages]  
        hbars = ax.barh(labels, [r.count for r in languages], align='center', label=labels, color=colors)  
        ax.invert_yaxis()  
        ax.xaxis.set_visible(False)  
        ax.set_title('Top 10 post languages', y=0.0)  
        ax.text(0.99, -0.01, datetime.now().strftime('%Y-%m-%d %H:%M:%S') + '  on ' + g.site.name, verticalalignment='top', horizontalalignment='right', transform=ax.transAxes, color='darkgrey') #, fontsize=15  
        fig.tight_layout()  
        filename = "/var/lib/piefed/app/static/tmp/languages.svg"  
        fig.savefig(filename, format="svg")  

        software = session.execute(text('SELECT software, COUNT(*) FROM instance WHERE "gone_forever" IS False GROUP BY software ORDER BY count DESC LIMIT 15')).all()  
        myexplode = [0.2 if r.software == 'piefed' else 0 for r in software]  
        fig = Figure()  
        ax = fig.add_subplot()  
        colors = list( TABLEAU_COLORS.keys() )  
        hbars = ax.barh([r.software for r in software], [r.count for r in software], align='center', color=colors)  
        ax.bar_label(hbars, fmt='%d')  
        ax.invert_yaxis()  
        ax.set_title('Instances by Software', y=0.0)  
        ax.text(0.99, -0.01, datetime.now().strftime('%Y-%m-%d %H:%M:%S') + '  on ' + g.site.name, verticalalignment='top', horizontalalignment='right', transform=ax.transAxes, color='darkgrey') #, fontsize=15  
        fig.tight_layout()  
        fig.savefig("/var/lib/piefed/app/static/tmp/software.svg", format="svg") # , transparent=True  

        for software in ["mastodon", "lemmy", "peertube", "friendica", "piefed", "sharkey", "mbin"]:  
            version = session.execute(text('SELECT version, COUNT(*) FROM instance WHERE "software" = :software AND "gone_forever" IS False GROUP BY version ORDER BY count DESC'), {'software': software}).all()  
            fig = Figure()  
            ax = fig.add_subplot()  
            ax.pie([r.count for r in version], labels=[r.version for r in version])  
            ax.set_title(f"{software} versions", y=0.0)  
            ax.text(0.99, -0.01, datetime.now().strftime('%Y-%m-%d %H:%M:%S') + '  on ' + g.site.name, verticalalignment='top', horizontalalignment='right', transform=ax.transAxes, color='darkgrey') #, fontsize=15  
            fig.tight_layout()  
            fig.savefig(f"/var/lib/piefed/app/static/tmp/version_{software}.svg", format="svg")  

        for interval in ['day', 'week', 'month']: # hour  
            data = fetch_stats(session, Instance, interval)  
            data_gone = fetch_stats(session, Instance, interval, createdcolumn=Instance.last_seen, count1=[Instance.gone_forever == True])  
            fig = Figure()  
            ax = fig.subplots()  
            ax.fill_between(data['timestamp'], data['zeros'], data['count1'], step='pre', alpha=0.4)  
            ax.step(data['timestamp'], data['count1'], label="Instances discovered")  
            ax.fill_between(data_gone['timestamp'], data_gone['zeros'], [-x for x in data_gone['count1']], step='pre', alpha=0.4)  
            ax.step(data_gone['timestamp'], [-x for x in data_gone['count1']], label="Instances gone")  
            ax.plot([], [], ' ', label=f"(per {interval})")  
            ax.legend(loc="upper right")  
            fig.tight_layout()  
            fig.savefig(f"/var/lib/piefed/app/static/tmp/instances_{interval}.svg", format="svg")  

            data_posts = fetch_stats(session, Post, interval, count1=[and_(Post.deleted == False, Post.up_votes > 0)], count2=[Post.deleted == True])  
            data_replies = fetch_stats(session, PostReply, interval, count1=[and_(PostReply.deleted == False, PostReply.up_votes > 1)], count2=[PostReply.deleted == True])  
            posts_byvote = fetch_stats(session, Post, interval, count1=[and_(Post.deleted == False, Post.up_votes > 30)], count2=[and_(Post.deleted == False, Post.up_votes == 0)])  
            replies_byvote = fetch_stats(session, PostReply, interval, count1=[and_(PostReply.deleted == False, PostReply.up_votes > 10)], count2=[and_(PostReply.deleted == False, PostReply.up_votes <= 1)])  
            fig = Figure()  
            axs = fig.subplots(2)  
            axs[0].fill_between(data_posts['timestamp'], data_posts['zeros'], data_posts['count1'], step='pre', alpha=0.4)  
            axs[0].step(data_posts['timestamp'], data_posts['count1'], label = f"Posts (per {interval})")  
            axs[0].fill_between(data_posts['timestamp'], data_posts['zeros'], [-x for x in data_posts['count2']], step='pre', alpha=0.4)  
            axs[0].step(data_posts['timestamp'], [-x for x in data_posts['count2']], label="Posts removed")  
            axs[0].fill_between(posts_byvote['timestamp'], posts_byvote['zeros'], posts_byvote['count1'], step='pre', alpha=0.4)  
            axs[0].plot([], [], label=">30 upvotes")  
            axs[0].fill_between(posts_byvote['timestamp'], data_posts['count1'], [x + y for x, y in zip(data_posts['count1'], posts_byvote['count2'])], step='pre', alpha=0.4)  
            axs[0].plot([], [], label="0 upvotes")  
            axs[1].fill_between(data_replies['timestamp'], data_replies['zeros'], data_replies['count1'], step='pre', alpha=0.4)  
            axs[1].step(data_replies['timestamp'], data_replies['count1'], label = f"Comments (per {interval})")  
            axs[1].fill_between(data_replies['timestamp'], data_replies['zeros'], [-x for x in data_replies['count2']], step='pre', alpha=0.4)  
            axs[1].step(data_replies['timestamp'], [-x for x in data_replies['count2']], label= "Comments removed")  
            axs[1].fill_between(replies_byvote['timestamp'], replies_byvote['zeros'], replies_byvote['count1'], step='pre', alpha=0.4)  
            axs[1].plot([], [], label=">10 upvotes")  
            axs[1].fill_between(replies_byvote['timestamp'], data_replies['count1'], [x + y for x, y in zip(data_replies['count1'], replies_byvote['count2'])], step='pre', alpha=0.4)  
            axs[1].plot([], [], label="<=1 upvote")  
            axs[0].legend(loc="upper left")  
            axs[1].legend(loc="upper left")  
            fig.tight_layout()  
            fig.savefig(f"/var/lib/piefed/app/static/tmp/posts_{interval}.svg", format="svg")  

            data = fetch_stats(session, User, interval, createdcolumn=User.created, count1=[User.bot == False], count2=[and_(User.bot == False, User.deleted == False, User.banned == False, User.last_seen - User.created < timedelta(days=3), User.created < datetime.now() - timedelta(days=5))])  
            users_removed = fetch_stats(session, User, interval, createdcolumn=User.last_seen, count1=[or_(User.deleted == True, User.banned == True)])  
            fig = Figure()  
            ax = fig.subplots()  
            ax.fill_between(data['timestamp'], data['zeros'], data['count1'], step='pre', alpha=0.4)  
            ax.step(data['timestamp'], data['count1'], label="Users discovered")  
            ax.fill_between(users_removed['timestamp'], users_removed['zeros'], [-x for x in users_removed['count1']], step='pre', alpha=0.4)  
            ax.step(users_removed['timestamp'], [-x for x in users_removed['count1']], label="Users removed")  
            ax.fill_between(data['timestamp'], data['count1'], [x - y for x, y in zip(data['count1'], data['count2'])], step='pre', alpha=0.4)  
            ax.plot([], [], label="non-returning")  
            ax.plot([], [], ' ', label=f"(per {interval})")  
            # ToDo: show inactive  
            ax.legend(loc="upper right")  
            fig.tight_layout()  
            fig.savefig(f"/var/lib/piefed/app/static/tmp/users_{interval}.svg", format="svg")  

        starttime = datetime.now() - timedelta(days=3)  
        endtime = datetime.now()  
        interval = 'hour'  
        timeseries = func.generate_series(starttime, endtime, f"1 {interval}").alias('timeseries')  
        one = literal_column("1")  
        data = session.query(timeseries.column, func.count(one).filter(ActivityPubLog.id != None), ActivityPubLog.activity_type, ActivityPubLog.direction).select_from(timeseries).outerjoin(ActivityPubLog, func.date_trunc(interval, ActivityPubLog.created_at) == func.date_trunc(interval, timeseries.column)).group_by(timeseries.column, ActivityPubLog.activity_type, ActivityPubLog.direction).order_by(timeseries.column).all()[:-2]  
        timestamps = []  
        activity_types = []  
        values = dict()  
        values['in'] = dict()  
        values['out'] = dict()  
        for r in data:  
            timestamp_ = r[0]  
            value_ = r[1]  
            type_ = r[2]  
            direction_ = r[3]  
            if direction_ not in ['in', 'out']:  
                continue  
            if type_ not in values[direction_]:  
                values[direction_][type_] = dict()  
            values[direction_][type_][timestamp_] = value_  
            if timestamp_ not in timestamps:  
                timestamps.append(timestamp_)  
            if type_ not in activity_types:  
                activity_types.append(type_)  
        val2 = dict()  
        for direction in ['in', 'out']:  
            val2[direction] = dict()  
            for type_ in activity_types:  
                val2[direction][type_] = []  
                for i, ts in enumerate(timestamps):  
                    if (type_ in values[direction]) and (ts in values[direction][type_]):  
                        val2[direction][type_].append(values[direction][type_][ts])  
                    else:  
                        val2[direction][type_].append(0)  
        fig = Figure()  
        ax = fig.subplots()  
        defaultColors = [  
            "#3366CC", "#DC3912", "#FF9900", "#109618", "#990099", "#3B3EAC", "#0099C6",  
            "#DD4477", "#66AA00", "#B82E2E", "#316395", "#994499", "#22AA99", "#AAAA11",  
            "#6633CC", "#E67300", "#8B0707", "#329262", "#5574A6", "#651067"  
        ]  
        bottom = [0 for r in timestamps]  
        shownTypes = ['Announce', 'Create', 'Update', 'Delete', 'Undo Vote', 'Dislike', 'Like'] # , 'PeerTube View', 'Duplicate', 'User Ban', 'Add Mod/Sticky', 'Remove Mod/Sticky', 'Undo Delete', 'Post Lock', 'Accept', 'Follow', 'Flag', 'Unknown', 'Undo'  
        for type_, color in zip(shownTypes, defaultColors):  
            y2 = [x + y for x, y in zip(val2['in'][type_], bottom)]  
            ax.vlines(timestamps, bottom, y2, colors=color, linewidth=3, label=type_)  
            bottom = y2  
        ax.xaxis.set_major_formatter(mdates.DateFormatter('%H:%M'))  
        ax.legend(loc='center left')  
        fig.tight_layout()  
        fig.savefig(f"/var/lib/piefed/app/static/tmp/activity.svg", format="svg")  

        user = session.query(User).filter(User.id == 145).one()  
        interval = 'day'  
        starttime = max( datetime.now() - timedelta(days=180), user.created )  
        endtime = datetime.now()  
        data_posts = fetch_stats(session, Post, interval, starttime, endtime, count1=[Post.user_id == user.id])  # , sum2=Post.up_votes  
        data_replies = fetch_stats(session, PostReply, interval, starttime, endtime, count1=[PostReply.user_id == user.id])  
        data_post_votes = fetch_stats(session, PostVote, interval, starttime, endtime, count1=[and_(PostVote.user_id == user.id, PostVote.effect > 0)], count2=[and_(PostVote.user_id == user.id, PostVote.effect < 0)])  
        data_reply_votes = fetch_stats(session, PostReplyVote, interval, starttime, endtime, count1=[and_(PostReplyVote.user_id == user.id, PostReplyVote.effect > 0)], count2=[and_(PostReplyVote.user_id == user.id, PostReplyVote.effect < 0)])  
        data_votes = {'timestamp': [x for x, y in zip(data_post_votes['timestamp'], data_reply_votes['timestamp'])],  
                      'count1': [x + y for x, y in zip(data_post_votes['count1'], data_reply_votes['count1'])],  
                      'count2': [x + y for x, y in zip(data_post_votes['count2'], data_reply_votes['count2'])] }  
        data_post_votes_in = fetch_stats(session, PostVote, interval, starttime, endtime, count1=[and_(PostVote.author_id == user.id, PostVote.effect > 0)], count2=[and_(PostVote.author_id == user.id, PostVote.effect < 0)])  
        data_reply_votes_in = fetch_stats(session, PostReplyVote, interval, starttime, endtime, count1=[and_(PostReplyVote.author_id == user.id, PostReplyVote.effect > 0)], count2=[and_(PostReplyVote.author_id == user.id, PostReplyVote.effect < 0)])  
        data_votes_in = {'timestamp': [x for x, y in zip(data_post_votes_in['timestamp'], data_reply_votes_in['timestamp'])],  
                         'count1': [x + y for x, y in zip(data_post_votes_in['count1'], data_reply_votes_in['count1'])],  
                         'count2': [x + y for x, y in zip(data_post_votes_in['count2'], data_reply_votes_in['count2'])] }  
        fig = Figure()  
        axs = fig.subplots(3)  
        axs[0].set_title(f"{user.user_name}")  
        bottom = data_posts['zeros']  
        axs[0].vlines(data_posts['timestamp'], bottom, data_posts['count1'], colors="#3366CC", linewidth=2, label="Posts")  
        bottom = data_posts['count1']  
        axs[0].vlines(data_replies['timestamp'], bottom, [x+y for x, y in zip(data_posts['count1'], data_replies['count1'])], colors="#FF9900", linewidth=2, label="Comments")  
        axs[0].legend(loc="upper left")  
        bottom = [0 for r in data_votes['timestamp']]  
        axs[1].vlines(data_votes['timestamp'], bottom, data_votes['count1'], colors="#22AA99", linewidth=2, label="Upvotes")  
        axs[1].vlines(data_votes['timestamp'], bottom, [-x for x in data_votes['count2']], colors="#DD4477", linewidth=2, label="Downvotes")  
        axs[1].legend(loc="upper left")  
        bottom = [0 for r in data_votes_in['timestamp']]  
        axs[2].vlines(data_votes_in['timestamp'], bottom, data_votes_in['count1'], colors="#66AA00", linewidth=2, label="Upvotes")  
        axs[2].vlines(data_votes_in['timestamp'], bottom, [-x for x in data_votes_in['count2']], colors="#DC3912", linewidth=2, label="Downvotes")  
        fig.tight_layout()  
        fig.savefig(f"/var/lib/piefed/app/static/tmp/user_145.svg", format="svg")  


def plugin_info():  
    """Plugin metadata"""  
    return {  
        "name": "Matplotlib Charts",  
        "version": "0.0.1",  
        "description": "An experimental plugin that generates statistics charts",  
        "license": "AGPL-3.0",                                   # Must be AGPL-compatible  
        "source_url": "https://piefed.social/post/1308113",  # Required  
        "author": "hendrik"  
    }  

——— Optional: Create a CMS page (Admin -> Pages) called something like /statistics with the following content:

 markdown
![](/static/tmp/activity.svg)  
![](/static/tmp/posts_week.svg)  
![](/static/tmp/users_week.svg)  
![](/static/tmp/instances_day.svg)  

![](/static/tmp/software.svg)  
![](/static/tmp/version_piefed.svg)  
![](/static/tmp/version_lemmy.svg)  
![](/static/tmp/languages.svg)  
![](/static/tmp/user_145.svg)  

Plugin Experiment: Codeberg Crossposter v0.0.1

Caution: This is not a working plugin. Just some code for further discussion within the developer community. Main issue is that we don't (yet) have much of a proper interface to hook into, so this code pokes around in the database and misuses various functions to accomplish the task of posting and replying. Probably circumventing some other code which encompasses these things in regular PieFed for good reasons. And then I hardcoded several magic numbers so it won't work unless those are replaced with correct instance-specific values. And no guarantee this will not end up in a some loop and post endlessly. Anyway: use a dedicated user for bots, set the "bot account" flag and consider using a seperate community (preferrably local-only) for testing. And make sure you have database backups. So: you've been warned not to deploy this "plugin". Description: Experimenting with the plugin interface Additional dependencies: None codeberg_crossposter/init.py

 python
import os  
from datetime import datetime, timedelta, timezone  
import logging  

from app.plugins.hooks import hook  
from flask import current_app, g  
from app.utils import get_task_session, html_to_text  
from app.models import User, Community, Post, Site, PostReply, Notification, CommunityFlair  
from app.shared.post import make_post, edit_post  
from app.shared.reply import make_reply, edit_reply  
from app.shared.tasks import task_selector  
from app.constants import POST_TYPE_ARTICLE, POST_TYPE_LINK, SRC_API  
from sqlalchemy import or_  

import httpx  
from bs4 import BeautifulSoup  
import re  

PLUGIN_NAME = __name__.split('.')[-1]  
logger = logging.getLogger(__name__)  


@hook("cron_often")  
def codeberg_import_loop(data):  
    """Hook that runs on a periodic interval"""  
    from app import redis_client  
    with current_app.app_context(), get_task_session() as session:  
        g.site = session.query(Site).get(1)  
        user = session.query(User).filter_by(user_name="rss_bot", id=999122630, banned=False, deleted=False).one()  
        res = redis_client.get(f"plugins:{PLUGIN_NAME}:previous_time")  
        if res is not None:  
            previous_time = datetime.fromtimestamp(float(res))  
        else:  
            logger.warning("Couldn't determine last run")  
            previous_time = datetime(year=1970, month=1, day=1)  
        if datetime.now() - previous_time >= timedelta(minutes=15):  
            #         Name,            RSS Feed,                                       post to community_id  
            urls = [("PieFed",        "https://codeberg.org/rimu/pyfedi.rss",          999846),  
                    ("PieFed-Notifs", "https://codeberg.org/PieFed/piefed-notifs.rss", 999846)]  
            for feedname, url, community_id in urls:  
                logger.info(f"[{PLUGIN_NAME}] Fetching Codeberg RSS feed {url}")  
                community = session.query(Community).filter_by(id=community_id, banned=False).one()  
                response = httpx.get(url, timeout=5.0)  
                response.raise_for_status()  
                soup = BeautifulSoup(response.content, 'xml')  
                items = soup.find_all(['item','entry'])  
                for item in items[:30]:  
                    title = item.find('title').text  
                    link = item.find('link').get('href') or item.find('link').text  
                    description = item.find('description').text  
                    content = item.find(['content', 'content:encoded'])  
                    content = content.text if content else None  
                    author = item.find('author').text  
                    published = item.find('pubDate').text  
                    #pub_timestamp = datetime.strptime(published, "%a, %d %b %Y %H:%M:%S %z")  
                    if user and community and title and description and content:  
                        x_push = re.match(r"^(?P<author>\S+) pushed to (?P<branch>\S+) at (?P<repo>\S+)$", title)  
                        x_issue = re.match(r"^(?P<author>\S+) (?P<action>created|opened|closed|merged|reopened|commented on) (?P<category>issue|pull request) (?P<repo>\S+)#(?P<issue>\d+)$", title)  
                        if x_push:  
                            pass  
                        elif x_issue:  
                            author = x_issue.group('author')  
                            action = x_issue.group('action')  
                            category = x_issue.group('category')  
                            if category == "issue":  
                                category = "Issue"  
                            elif category == "pull request":  
                                category = "PR"  
                            repo = x_issue.group('repo')  
                            issue = x_issue.group('issue')  

                            if action == "created" or action == "opened":  
                                y = re.match(r"^(?P<num>\d+)#(?P<title>.+)#$", description)  
                                num = y.group('num')  
                                title = y.group('title')  
                                title = (feedname + " " + category + " #" + issue + ": " + title)[:220]  
                                body = f"{action} {published} by {author}\n\n" + html_to_text(content) + f"\n\n(imported from [{feedname} Feed]({url}) by [rss_bot](user.public_url()))"  
                                previous_posts = session.query(Post).filter(or_(Post.title.startswith(title), Post.url == link), Post.community_id == community.id).all()  
                                if not previous_posts:  
                                    post_data = {  
                                        'title': title,  
                                        'body': body,  
                                        'url': link,  
                                        'nsfw': False,  
                                        'notify_author': True,  
                                        'language_id': 2,  
                                        'timezone': "Europe/Berlin",  
                                    }  
                                    uploaded_file = None  
                                    user_id, post = make_post(post_data, community, POST_TYPE_LINK if link else POST_TYPE_ARTICLE, SRC_API, auth="Bearer "+user.encode_jwt_token(), uploaded_file=uploaded_file)  
                                    session.commit()  
                                    logger.info(f"Posted {post.public_url()} {post.title}\n")  
                                else:  
                                    for post in previous_posts:  
                                        if post.user_id == user.id:  
                                            post_data = {  
                                                'title': post.title,  
                                                'body': post.body,  
                                                'url': post.url,  
                                                'nsfw': post.nsfw,  
                                                'notify_author': post.notify_author,  
                                                'language_id': post.language_id,  
                                                'timezone': post.timezone,  
                                            }  
                                            modified = False  
                                            z = re.match(r"^" + re.escape(title) + r"( (\[merged\]|\[closed\]|\[reopened\]))*$", post.title)  
                                            if not z:  
                                                post_data['title'] = title  
                                                modified = True  
                                                logger.info(f"Post title edited: {post.public_url()} {title}")  
                                            if post.body != body:  
                                                post_data['body'] = body  
                                                modified = True  
                                                logger.info(f"Post body edited: {post.public_url()} {title}")  
                                            if modified:  
                                                user_id, post = edit_post(post_data, post, post.type, SRC_API, user, uploaded_file=None)  
                                                session.commit()  

                            elif action == "merged" or action == "closed" or action == "reopened":  
                                title = (feedname + " " + category + " #" + issue + ": " + description)[:220]  
                                previous_posts = session.query(Post).filter(or_(Post.title.startswith(title), Post.url == link), Post.community_id == community.id, Post.user_id == user.id, Post.deleted == False)>  
                                for post in previous_posts:  
                                    reply_data = {  
                                        'body': f"{action} {published} by {author}",  
                                        'notify_author': True,  
                                        'language_id': 2,  
                                        'distinguished': False,  
                                    }  
                                    previous_replies = post.replies.filter(PostReply.body == reply_data['body'], PostReply.user_id == user.id, PostReply.deleted == False).all()  
                                    if not previous_replies:  
                                        user_id, reply = make_reply(reply_data, post, None, SRC_API, auth="Bearer "+user.encode_jwt_token())  
                                        post.title = post.title + f" [{action}]";  
                                        flair = session.query(CommunityFlair).filter(CommunityFlair.flair == action, CommunityFlair.community_id == post.community_id).one_or_none()  
                                        if action == "merged" or action == "closed":  
                                            post.flair = list(filter(lambda f: f.flair != "open", post.flair))  
                                        elif action == "reopened":  
                                            post.flair = list(filter(lambda f: f.flair != "closed", post.flair))  
                                            post.title.removesuffix(' [closed] [reopened]')  
                                            flair = session.query(CommunityFlair).filter(CommunityFlair.flair == "open", CommunityFlair.community_id == post.community_id).one_or_none()  
                                        if flair:  
                                            post.flair.append(flair)  
                                            logger.info(f"flair {flair.flair} appended")  
                                        session.commit()  
                                        task_selector('edit_post', post_id=post.id)  
                                        logger.info(f"Post edited ({action}): {post.public_url()} {post.title}\n")  
                            elif action == "commented on":  
                                x_link = re.match(r"^(?P<parentlink>\S+)(?P<commentid>#.+)$", link)  
                                parent_link = x_link.group('parentlink')  
                                parent_post = session.query(Post).filter(Post.url == parent_link, Post.community_id == community.id, Post.user_id == user.id, Post.deleted == False).first()  
                                #content.removeprefix("prefix")  
                                content = f"{link}\n{published} by {author}\n\n" + content.split("\n",2)[2]  
                                if parent_post:  
                                    reply_data = {  
                                        'body': content,  
                                        'notify_author': True,  
                                        'language_id': 2,  
                                        'distinguished': False,  
                                    }  
                                    previous_reply = parent_post.replies.filter(or_(PostReply.body == reply_data['body'], PostReply.body.startswith(link)), PostReply.user_id == user.id, PostReply.deleted == Fals>  
                                    if not previous_reply:  
                                        user_id, reply = make_reply(reply_data, parent_post, None, SRC_API, auth="Bearer "+user.encode_jwt_token())  
                                        session.commit()  
                                        logger.info(f"Reply {reply.public_url()} {reply.body[:50]}\n")  
                                    else:  
                                        if previous_reply.user_id == user.id:  
                                            if previous_reply.body != reply_data['body']:  
                                                user_id, reply = edit_reply(reply_data, previous_reply, parent_post, SRC_API, auth="Bearer "+user.encode_jwt_token())  
                                                session.commit()  
                                                logger.info(f"Comment edited: {previous_reply.public_url()} {previous_reply.body[:50]}\n")  

                            else:  
                                logger.warning(f"Unknown action \"{action}\"")  
                        else:  
                            logger.warning(f"Unknown feed item \"{title}\"")  

            redis_client.set(f"plugins:{PLUGIN_NAME}:previous_time", datetime.now().timestamp())  

        notifications = session.query(Notification).filter(Notification.user_id == user.id, Notification.read == False).all()  
        for notification in notifications:  
            if notification.targets:  
                post_id = notification.targets.get('post_id', 0)  
                comment_id = notification.targets.get('comment_id', 0)  
                if post_id and comment_id:  
                    print(f"Notification: {post_id} {comment_id}")  
                    post = session.query(Post).filter(Post.id == post_id, Post.deleted == False).one()  
                    if post.user_id == user.id and post.community_id in [999846]:  
                        parent_reply = post.replies.filter(PostReply.id == comment_id, PostReply.deleted == False).one()  
                        if parent_reply:  
                            reply_data = {  
                                'body': "I'm a one-directional bot. Your replies will not be forwarded to Codeberg!",  
                                'notify_author': True,  
                                'language_id': 2,  
                                'distinguished': False,  
                            }  
                            user_id, reply = make_reply(reply_data, post, parent_reply.id, SRC_API, auth="Bearer "+user.encode_jwt_token())  
                            session.commit()  
                            user.unread_notifications -= 1  
                            notification.read = True  
                            session.commit()  
                            logger.info(f"Reply {reply.public_url()} {reply.body[:50]}\n")  

    return None  


def plugin_info():  
    """Plugin metadata"""  
    return {  
        "name": "Codeberg Crossposter",  
        "version": "0.0.1",  
        "description": "Experimenting with the plugin interface",  
        "license": "AGPL-3.0",                             # Must be AGPL-compatible  
        "source_url": "https://piefed.social/post/1306500",  # Required  
        "author": "hendrik"  
    }  

How to use Plugins from this community

Share Plugin snippets and discuss PieFed Plugin development in this community. First of all: Plugins are an admin-only thing. They hook into PieFed's internals and have access to the entire instance and its database. So: • This feature is not intended for moderators and users. You have to be an instance owner to be able to install Plugins. • Caution is advised, don't blindly copy-paste executable code from the internet. • Plugins are still in an early stage. Documentation is at: https://codeberg.org/rimu/pyfedi/src/branch/main/docs/PLUGINS.md To install a plugin, copy the code to piefed/app/plugins/<plugin_name>/__init__.py As there's currenty no admin interface, deactivate plugins by renaming them. For example __init__.py --> __init__.py.disabled You will find log output in your send_queue's output. If you set it up in a crontab as per the INSTALL.md, that's likely journalctl -u cron.service -f Make sure to mention additional library requirements and install them in PieFed's environment.