Skip Navigation

hendrik

@hendrik.palaver.p3x.de.ap.tdpl.io

7 Posts296 Comments0 Memberships

Joined October 2026

A software developer and Linux nerd, living in Germany. I'm usually a chill dude but my online persona doesn't always reflect my true personality. Take what I say with a grain of salt, I usually try to b…

🌉 bridged from @hendrik@palaver.p3x.de by Tidepool

  • Mod Log

    Should I be more civil here? I must admit I lost some of my cool regarding all the slop we get in the selfhosted community.

    Nothing fancy though, nobody got banned or anything. I'm just curious.

  • What's the latest and greatest AI in image editing and image2image?

    I would like to experiment with image editing. Idk, brush up my vacation photos, remove some of the other tourists, make it look like I've been somewhere I haven't... Swap my face onto someone or change my clothes, change the weather/sky... Draw me as a character in some artist's style... If it works well enough, take some of the blurry images from my potato phone camera from 15 years ago and clean them up... The stuff I've seen people on YouTube do with AI.

    What's a good and recent model or "editor" to do that? Open-weights please and preferably something I can just use straight away without fiddling 3 hours with some ComfyUI nodes. Bonus points for being efficient and running on my laptop 😅

    And is there some Free Software UI / software to make it easy? I mean I'm perfectly able to learn how to provide it with stencils(maybe they don't need that anymore in 2026?) and whatever stuff it needs as input, run it on the commandline... But maybe there's a nice interface like an image editor?

    Edit: I forgot: I mentioned different use-cases... Seems to me there are different models for like regular image editing (which gets one image and a prompt as input) and models which get two images as input? Like a picture, and another picture and the instruction to draw this person onto that picture?

  • AI scrapers everywhere

    There's a nice article: The Day I Logged 1 In Every 2000 Public IPv4: Visualizing The AI Scraper DDoS which someone kindly dropped in the fuck_ai community. It's worth reading. After reading it, I decided to have another look at my logfiles and I'm pretty sure I see the same thing. A good while back I had my small 1-3 people instance nearly melt because of Tencent and Alibaba. I managed to address that by blocking some of their IP ranges. Proceedingly rimu implemented a Honeypot, which currently has 14.272 IPs blocked on my instance. And a few database requests got more efficient. But I think the overall situation deteriorated. These days the AI scrapers seem to come from everywhere on the internet. My logfiles just scroll by again. It's not as bad as when I was hit by the really nasty crawlers. The server keeps up with it, I'm just constantly sending out loads of data. There's a crawler getting caught up in the honeypot almost every minute. But there's also still a near infinite amount of addresses left, querying all kinds of posts, communities and user profiles. And I notice since it's a dysproportionate amount of traffic for a small instance. I think the honeypot is great. But the AI scrapers have way to many addresses. And in the mid-term we probably need to come up with some more mitigations. At least to cater to smaller servers. Just wanted to draw some attention to how things change. I've switched my instance to "private" for now, but I'll continue to investigate. I've made two images myself (for palaver.p3x.de). First is all IPv4 addresses in my nginx log. That includes all Fedi instances and users. But I'm just a small instance and I guess most of the reddish areas are caused by crawlers. AJvKYRbM1j1amZm.png Second image is what's in my honeypot, (dots visible after zooming in): 1y7biwvTHxw9Q8q.png

  • Sendspin multi-room audio coming along

    This is a bit smart-home specific... I've long wanted to build some smart speakers with Home Assistant's voice assistant and a multi-room music solution. Sadly I could never get Snapcast work to an acceptable level, but seems there is a new kid in the block now. Sendspin (formerly Resonate) is an open synchronized music protocol. Currently being implemented within ESPHome. A few days ago they fixed some more memory issues and seems it's getting along. Maybe we'll get an open and working multi-room audio solution added to ESPHome soon. I got it working on both an ESP32-S3 and an old ESP32 (with PSRAM). It's got nice features like the title, artist, album and cover art being transferred so we can just display that on a small TFT. And it's just about starting to work well enough. Now they need to finalize it, get some more things changed around in ESPHome and I can finally assemble some synced speakers for the kitchen and livingroom. Yay! Seems it's early days for the server-side of it as well. We got support by Music Assistant. Other than that the (few) libraries warn they're still more or less just a tech demo. So as of now this is somewhat limited to tinkerers, but IMO looking really promising. • https://esphome.io/ • https://www.music-assistant.io/ • https://www.sendspin-audio.com/ • https://github.com/esphome/esphome/pull/12284 (plus a bunch of related PRs)

    github.com
  • 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.