repository

BlowfishCMS

A small content management system for OpenBSD

version 0.45.6 · ISC · 2026-12-03 · releases

159 lines · 11.3 KB · download this file

package BlowfishCMS::Addon::Github;
# GitHub projects: a block listing the public repositories of one GitHub
# user, with search, filters and sorting (github.js), refreshed every hour.
#
# Where each part runs:
#   admin service     the settings screen (/admin/?kind=x-github, the GitHub
#                     projects tab of Site › Add-ons): the GitHub
#                     user, and "sync now". The hourly sync (the hourly() hook,
#                     run by root's crontab as the admin account).
#   public service    the block on pages; it only reads the saved cards.
#
# Kept in the catalogue's addon_settings (no tables of its own):
#   user      the GitHub user name
#   cache     JSON {repositories, summary, synced}: markup built at sync time
#   synced_at, error   when the last sync worked, and why the last one failed
#   lock      the time a sync started (stops two running at once)
#
# Tests point the sync at a local stand-in through BLOWFISH_GITHUB_API.
use v5.36;
use utf8;
use JSON::PP ();
use HTTP::Tiny;
use POSIX qw(strftime);
use Encode qw(encode);
BEGIN {
    no strict 'refs';
    *{$_}=\&{"BlowfishCMS::$_"} for qw(h param window window_html admin_page end_page fields hidden redirect json_response
        attempt failed_action addon_setting addon_setting_save);
}
my $api=$BlowfishCMS::startup_env{BLOWFISH_GITHUB_API} // 'https://api.github.com';

sub user_ok ($u) { return ($u//'') =~ /\A[A-Za-z0-9](?:-?[A-Za-z0-9]){0,38}\z/ }
sub cache {
    my $c=attempt {JSON::PP->new->decode(addon_setting('github','cache','{}'))};
    return ref $c eq 'HASH' ? $c : {};
}

# ---- The block ----------------------------------------------------------------------
sub blocks {
    return {github_projects=>{label=>'GitHub projects',order=>5,once=>1,fields=>[[title=>'Panel title','text',120]],
        defaults=>{title=>'repository directory'},manage=>['x-github','GitHub settings'],
        about=>'Your public GitHub repositories, kept up to date.',
        note=>'Public repositories of the GitHub user set under Site › Add-ons › GitHub projects, with search and filters. Refreshed every hour.',
        render=>\&render_block}};
}
sub render_block ($b,%o) {
    my $c=cache();
    my $cards=$c->{repositories} // '<p class="panel-note">The repositories appear here after the first sync from GitHub.</p>';
    my $synced=$c->{synced} // 'not yet';
    # The cards, summary and sync time are markup built (and escaped) by sync().
    my $html=<<"HTML" =~ s/\n\z//r;
<form class="project-tools" data-directory-tools hidden role="search" aria-label="Filter repositories">
  <div class="project-field project-field--search"><label for="project-search">find a project</label><input id="project-search" data-directory-search type="search" placeholder="Search names and descriptions…" autocomplete="off"></div>
  <div class="project-field"><label for="project-language">language</label><select id="project-language" data-directory-filter="language" data-fill><option value="">All languages</option></select></div>
  <div class="project-field"><label for="project-type">show</label><select id="project-type" data-directory-filter="show" data-match="words"><option value="">All repositories</option><option value="source">Original projects</option><option value="fork">Forks</option><option value="archived">Archived</option></select></div>
  <div class="project-field"><label for="project-sort">sort by</label><select id="project-sort" data-directory-sort><option value="-updated">Recently updated</option><option value="name">Name A–Z</option><option value="-stars">Most stars</option></select></div>
</form>
<div class="directory-caption"><p data-directory-count data-noun="public repositories" role="status" aria-live="polite">All public repositories</p><button class="text-button" type="button" data-directory-reset hidden>clear filters</button></div>
<div class="project-grid" data-directory-grid>
  $cards
</div>
<p class="panel-note" data-directory-empty hidden>No projects match these filters. Try another search or <button type="button" class="text-button" data-directory-reset>clear filters</button>.</p>
<noscript><p class="panel-note">All repositories are shown above. Enable JavaScript to search, filter, and sort.</p></noscript>
<p class="project-sync">Last synced from GitHub: $synced.</p>
HTML
    return window_html($b->{data}{title},'','<div data-directory>'.$html.'</div>',%o,body_class=>'project-directory',aria=>'Public repository directory',subtitle_html=>$c->{summary}//'');
}

# ---- Fetching from GitHub -------------------------------------------------------------
# The public repositories of $user, as the block's markup.
sub fetch_parts ($user,$http=HTTP::Tiny->new(timeout=>20,verify_SSL=>1,agent=>'BlowfishCMS-github')) {
    die "That isn’t a GitHub user name.\n" unless user_ok($user);
    my %repos;
    for my $page (1..100) {
        my $res=$http->get("$api/users/$user/repos?type=owner&sort=full_name&direction=asc&per_page=100&page=$page",{headers=>{Accept=>'application/vnd.github+json'}});
        die "GitHub has no user called $user.\n" if $res->{status}==404;
        die "GitHub answered $res->{status} $res->{reason}; the repositories shown are kept as they were.\n" unless $res->{success};
        my $batch=attempt {JSON::PP->new->decode($res->{content})};
        die "GitHub’s answer couldn’t be read; the repositories shown are kept as they were.\n" unless ref $batch eq 'ARRAY';
        for my $r (@$batch) {
            next if $r->{private} || ($r->{visibility}//'public') ne 'public' || lc($r->{owner}{login}//'') ne lc $user;
            next unless ($r->{name}//'') =~ /\A[\w.-]+\z/;
            $repos{$r->{id}}=$r;
        }
        last if @$batch<100;
    }
    my @repos=sort {($b->{updated_at}//'') cmp ($a->{updated_at}//'') || $a->{name} cmp $b->{name}} values %repos;
    my @cards;
    for my $r (@repos) {
        my $name=h($r->{name});my $language=h($r->{language}||'Not specified');my $updated=h($r->{updated_at}//'');my $date=h(substr($r->{updated_at}//'',0,10));
        my $stars=int($r->{stargazers_count}||0);
        my $kind=($r->{fork}?'fork':'source').($r->{archived}?' / archived':'');my $url='https://github.com/'.h($user).'/'.$name;
        my $description=h($r->{description}||'Explore the source code and project documentation on GitHub.');
        push @cards,qq{<article class="project-card" data-card data-name="$name" data-language="$language" data-show="}.($r->{fork}?'fork':'source').($r->{archived}?' archived':'').qq{" data-updated="$updated" data-stars="$stars"><div class="project-card__top"><span class="badge">$language</span><span class="project-kind">$kind</span></div><h2><a href="$url" target="_blank" rel="noopener noreferrer">$name</a></h2><p class="project-description">$description</p><div class="project-card__bottom"><span>updated <time datetime="$date">$date</time></span><span aria-label="$stars stars">$stars stars</span></div><a class="project-open" href="$url" target="_blank" rel="noopener noreferrer">view repository <span aria-hidden="true">↗</span></a></article>};
    }
    my $stamp=strftime('%Y-%m-%dT%H:%M:%SZ',gmtime);my $label=strftime('%Y-%m-%d %H:%M UTC',gmtime);
    return {repositories=>join("\n",@cards)||'<p class="panel-note">No public repositories yet.</p>',
        summary=>scalar(@repos).' public '.(@repos==1 ? 'repository' : 'repositories'),synced=>qq{<time datetime="$stamp">$label</time>}};
}
# Fetches and saves the cards (admin service). Returns what happened.
sub sync {
    my $user=addon_setting('github','user');
    die "Set the GitHub user first.\n" unless length $user;
    my $db=$BlowfishCMS::db;my $now=time;
    # Take the lock unless another sync took it in the last five minutes.
    my $got=$db->do("INSERT INTO addon_settings(addon,key,value) VALUES ('github','lock',?) ON CONFLICT(addon,key) DO UPDATE SET value=excluded.value WHERE CAST(addon_settings.value AS INTEGER) < ?",undef,$now,$now-300);
    die "A sync is already running. Try again in a minute.\n" unless $got && $got ne '0E0';
    my $parts;
    my $ok=attempt {$parts=fetch_parts($user);1};
    my $error=$ok ? '' : BlowfishCMS::clean_error($@);
    addon_setting_save('github',lock=>'0',error=>$error,($ok ? (cache=>JSON::PP->new->canonical->encode($parts),synced_at=>$now) : ()));
    die "$error\n" unless $ok;
    return "Synced $parts->{summary} from GitHub.";
}
# Root's crontab runs this every hour (as the admin service's account).
sub hourly {
    return 'no GitHub user set' unless length addon_setting('github','user');
    return sync();
}

# ---- Settings screen (admin service, /admin/?kind=x-github) -----------------------------
sub admin {
    my $message=param('notice',2000);
    my $back='/admin/?kind=x-github';
    if ($BlowfishCMS::method eq 'POST') {
        attempt {
            my $action=param('action',30);
            if ($action eq 'github_user') {
                my $user=param('user',40);
                die "A GitHub user name is letters, numbers and single hyphens, such as octocat.\n" if length $user && !user_ok($user);
                my $changed=$user ne addon_setting('github','user');
                addon_setting_save('github',user=>$user,($changed ? (cache=>'{}',synced_at=>'',error=>'') : ()));
                my $note=!length $user ? 'Saved. The block shows no repositories until a user is set.'
                    : $changed ? ((attempt {sync()}) // 'Saved, but the first sync failed: '.BlowfishCMS::clean_error($@)) : 'Saved.';
                redirect("$back&notice=".CGI::escape(encode('UTF-8',$note)));
            }
            if ($action eq 'github_sync') {
                my $done=sync();
                redirect("$back&notice=".CGI::escape(encode('UTF-8',$done)));
            }
            die "Choose an action.\n";
        } or $message=failed_action($@);
    }
    my $user=addon_setting('github','user');my $c=cache();my $at=addon_setting('github','synced_at');my $error=addon_setting('github','error');
    admin_page('GitHub projects',section=>'x-github',notice=>$message,
        intro=>'Add the <b>GitHub projects</b> block to a page in the page builder: it lists the public repositories of the GitHub user below, which visitors can search and filter by language and kind. Private repositories are never shown.');
    my $last=length $at ? ($c->{summary} ? h($c->{summary}).', ' : '').'synced '.h(strftime('%Y-%m-%d %H:%M UTC',gmtime $at)) : 'not synced yet';
    # One box: whose repositories, and how the hourly sync is going.
    window('github','<form method="post" action="/admin/" class="admin-form" data-warn-unsaved>'.fields('github_user','x-github')
        .'<label>GitHub user<input name="user" maxlength="39" value="'.h($user).'" autocomplete="off" spellcheck="false"><span class="optional">The name in your profile’s address: github.com/<b>name</b>. Leave it empty to show no repositories.</span></label>'
        .'<button class="buttonlike is-primary" type="submit">save</button></form>'
        .'<form method="post" action="/admin/" class="admin-form box-part">'.fields('github_sync','x-github')
        .'<dl class="system-facts"><dt>Last sync</dt><dd>'.$last.'</dd>'
        .(length $error ? '<dt>Last attempt</dt><dd class="system-status--failed">failed: '.h($error).'</dd>' : '').'</dl>'
        .'<button class="buttonlike" type="submit"'.(length $user ? '' : ' disabled').'>sync now</button> <span class="optional">Repositories are fetched every hour; sync now to see a change straight away.</span></form>');
    end_page();
    return 1;
}
1;