feat: rename routes dir - 2/2

This commit is contained in:
DIYgod
2024-03-01 01:24:49 +08:00
parent 398be0f592
commit 6f57c02538
6463 changed files with 153 additions and 153 deletions
+31
View File
@@ -0,0 +1,31 @@
import got from '@/utils/got';
import { config } from '@/config';
module.exports = async (ctx) => {
const user = ctx.req.param('user');
const repo = ctx.req.param('repo');
const host = `https://github.com/${user}/${repo}`;
const url = `https://api.github.com/repos/${user}/${repo}/branches`;
const headers = {};
if (config.github && config.github.access_token) {
headers.Authorization = `token ${config.github.access_token}`;
}
const response = await got({
method: 'get',
url,
headers,
});
const data = response.data;
ctx.set('data', {
title: `${user}/${repo} Branches`,
link: `${host}/branches/all`,
item: data.map((item) => ({
title: item.name,
description: item.name,
link: `${host}/commits/${item.name}`,
})),
});
};
+185
View File
@@ -0,0 +1,185 @@
import got from '@/utils/got';
import { parseDate } from '@/utils/parse-date';
const md = require('markdown-it')({
html: true,
});
const rootUrl = 'https://github.com';
const apiUrl = 'https://api.github.com';
import { config } from '@/config';
const typeDict = {
issue: {
title: 'Issue',
},
issues: {
title: 'Issue',
},
pull: {
title: 'Pull request',
},
};
module.exports = async (ctx) => {
const user = ctx.req.param('user');
const repo = ctx.req.param('repo');
const number = ctx.req.param('number') && isNaN(Number.parseInt(ctx.req.param('number'))) ? 1 : Number.parseInt(ctx.req.param('number'));
const limit = ctx.req.query('limit') ? Number.parseInt(ctx.req.query('limit')) : 100;
const headers =
config.github && config.github.access_token
? {
Accept: 'application/vnd.github.v3+json',
Authorization: `token ${config.github.access_token}`,
}
: {
Accept: 'application/vnd.github.v3+json',
};
await (isNaN(number) ? allIssues(ctx, user, repo, limit, headers) : singleIssue(ctx, user, repo, number, limit, headers));
};
async function allIssues(ctx, user, repo, limit, headers) {
const response = await got(`${apiUrl}/repos/${user}/${repo}/issues/comments`, {
headers,
searchParams: {
sort: 'updated',
direction: 'desc',
per_page: limit,
},
});
const timeline = response.data;
const items = timeline.map((item) => {
const actor = item.actor?.login ?? item.user?.login ?? 'ghost';
const issueUrlParts = item.issue_url.split('/');
const issue = issueUrlParts.at(-1);
const urlParts = item.html_url.split('/');
const issueType = typeDict[urlParts.at(-2)].title;
return {
title: `${actor} commented on ${user}/${repo}: ${issueType} #${issue}`,
author: actor,
pubDate: parseDate(item.created_at),
link: item.html_url,
description: item.body ? md.render(item.body) : null,
};
});
const rateLimit = {
limit: Number.parseInt(response.headers['x-ratelimit-limit']),
remaining: Number.parseInt(response.headers['x-ratelimit-remaining']),
reset: parseDate(Number.parseInt(response.headers['x-ratelimit-reset']) * 1000),
resoure: response.headers['x-ratelimit-resource'],
used: Number.parseInt(response.headers['x-ratelimit-used']),
};
ctx.set('data', {
title: `${user}/${repo}: Issue & Pull request comments`,
link: `${rootUrl}/${user}/${repo}`,
item: items,
});
ctx.set('json', {
title: `${user}/${repo}: Issue & Pull request comments`,
link: `${rootUrl}/${user}/${repo}`,
item: items,
rateLimit,
});
}
async function singleIssue(ctx, user, repo, number, limit, headers) {
const response = await got(`${apiUrl}/repos/${user}/${repo}/issues/${number}`, {
headers,
});
const issue = response.data;
const type = issue.pull_request ? 'pull' : 'issue';
const timelineResponse = await got(issue.timeline_url, {
headers,
searchParams: {
per_page: limit,
},
});
const timeline = timelineResponse.data;
const items = [
{
title: `${issue.user.login} created ${user}/${repo}: ${typeDict[type].title} #${issue.number}`,
description: issue.body ? md.render(issue.body) : null,
author: issue.user.login,
pubDate: parseDate(issue.created_at),
link: `${issue.html_url}#issue-${issue.id}`,
},
];
for (const item of timeline) {
const actor = item.actor?.login ?? item.user?.login ?? 'ghost';
switch (item.event) {
case 'closed':
items.push({
title: `${actor} ${item.event} ${user}/${repo}: ${typeDict[type].title} #${issue.number}`,
author: actor,
pubDate: parseDate(item.created_at),
link: item.url,
});
break;
case 'commented':
items.push({
title: `${actor} ${item.event} on ${user}/${repo}: ${typeDict[type].title} #${issue.number}`,
description: md.render(item.body),
author: actor,
pubDate: parseDate(item.created_at),
link: item.html_url,
});
break;
case 'cross-referenced':
items.push({
title: `${actor} ${item.event} on ${user}/${repo}: ${typeDict[type].title} #${issue.number}`,
description: `${actor} mentioned this issue in <a href='${item.source.issue.html_url}'><b>${item.source.issue.title}</b> #${item.source.issue.number}</a>`,
author: actor,
pubDate: parseDate(item.created_at),
guid: `${actor} ${item.event} on ${user}/${repo}: ${typeDict[type].title} #${issue.number} on ${item.created_at}`,
link: `${actor} ${item.event} on ${user}/${repo}: ${typeDict[type].title} #${issue.number} on ${item.created_at}`,
});
break;
case 'renamed':
items.push({
title: `${actor} ${item.event} on ${user}/${repo}: ${typeDict[type].title} #${issue.number}`,
description: `${actor} changed the title <del>${item.rename.from}</del> ${item.rename.to}`,
author: actor,
pubDate: parseDate(item.created_at),
link: item.url,
});
break;
case 'reviewed':
items.push({
title: `${item.user.login} ${item.event} on ${user}/${repo}: ${typeDict[type].title} #${issue.number}`,
description: item.body ? md.render(item.body) : item.state.replace('_', ' '),
author: item.user.login,
pubDate: parseDate(item.submitted_at),
link: item.html_url,
});
break;
default:
break;
}
}
ctx.set('data', {
title: `${user}/${repo}: ${typeDict[type].title} #${number} - ${issue.title}`,
link: issue.html_url,
item: items,
});
ctx.set('json', {
title: `${user}/${repo}: ${typeDict[type].title} #${number} - ${issue.title}`,
link: issue.html_url,
item: items,
rateLimit: {
limit: Number.parseInt(response.headers['x-ratelimit-limit']),
remaining: Number.parseInt(response.headers['x-ratelimit-remaining']),
reset: parseDate(Number.parseInt(response.headers['x-ratelimit-reset']) * 1000),
resoure: response.headers['x-ratelimit-resource'],
used: Number.parseInt(response.headers['x-ratelimit-used']),
},
});
}
+79
View File
@@ -0,0 +1,79 @@
import got from '@/utils/got';
import { config } from '@/config';
module.exports = async (ctx) => {
const { user, repo, order, anon } = ctx.req.param();
const host = `https://github.com/${user}/${repo}`;
const url = `https://api.github.com/repos/${user}/${repo}/contributors?` + (anon ? 'anon=1' : '');
// Use token if available
const headers = {};
if (config.github && config.github.access_token) {
headers.Authorization = `token ${config.github.access_token}`;
}
// First page
const response = await got({
method: 'get',
url,
headers,
});
let data = response.data;
try {
// Get total page number
const last_page_link = response.headers.link.split(',').find((elem) => elem.includes('"last"'));
const url_base = last_page_link.match(/<(.*)page=\d*/)[1];
const page_count = Number(last_page_link.match(/page=(\d*)/)[1]);
const generate_array = (n) => [...Array(n - 1)].map((_, index) => index + 2);
const page_array = generate_array(page_count);
// Get everypage
const tasks = page_array.map(async (page) => {
const response = await got({
method: 'get',
url: `${url_base}page=${page}`,
headers,
});
data = [...data, ...response.data];
});
await Promise.all(tasks);
} catch (error) {
// If only one page
// Other errors
if (!(error instanceof TypeError)) {
throw error;
}
}
// Sort by commits
data.sort((a, b) => a.contributions - b.contributions);
if (order !== 'asc') {
data.reverse();
}
const items = data.map((item) =>
item.type === 'Anonymous'
? {
title: `Contributor: ${item.name}`,
description: `<p>Anonymous contributor</p><p>Name: ${item.name}</p><p>E-mail: ${item.email}</p><p>Contributions: ${item.contributions}</p>`,
guid: `anon-${item.name}`,
}
: {
title: `Contributor: ${item.login}`,
description: `<img src="${item.avatar_url}"></img><p><a href="${item.html_url}">${item.login}</a></p><p>Contributions: ${item.contributions}</p>`,
link: item.html_url,
guid: item.id,
}
);
ctx.set('data', {
title: `${user}/${repo} Contributors`,
link: `${host}/graphs/contributors`,
description: `New contributors for ${user}/${repo}`,
item: items,
});
};
+45
View File
@@ -0,0 +1,45 @@
import got from '@/utils/got';
import { config } from '@/config';
const queryString = require('query-string');
module.exports = async (ctx) => {
const user = ctx.req.param('user');
const repo = ctx.req.param('repo');
const branch = ctx.req.param('branch');
const filepath = ctx.req.param('filepath');
const fileUrl = `https://github.com/${user}/${repo}/commits/${branch}/${filepath}`;
const headers = {};
if (config.github && config.github.access_token) {
headers.Authorization = `token ${config.github.access_token}`;
}
const res = await got.get(`https://api.github.com/repos/${user}/${repo}/commits`, {
searchParams: queryString.stringify({
sha: branch,
path: filepath,
}),
headers,
});
const list = res.data;
const count = [];
for (let i = 0; i < Math.min(list.length, 10); i++) {
count.push(i);
}
const resultItems = count.map((i) => {
const each = list[i];
return {
title: each.commit.message.split('\n')[0],
description: `<pre>${each.commit.message}</pre>`,
link: each.html_url,
author: each.commit.author.name,
pubDate: new Date(each.commit.committer.date).toUTCString(),
};
});
ctx.set('data', {
title: `GitHub File - ${user}/${repo}/${branch}/${filepath}`,
link: fileUrl,
item: resultItems,
});
};
+50
View File
@@ -0,0 +1,50 @@
import got from '@/utils/got';
import { config } from '@/config';
module.exports = async (ctx) => {
if (!config.github || !config.github.access_token) {
throw new Error('GitHub follower RSS is disabled due to the lack of <a href="https://docs.rsshub.app/install/#pei-zhi-bu-fen-rss-mo-kuai-pei-zhi">relevant config</a>');
}
const user = ctx.req.param('user');
const host = `https://github.com/${user}`;
const url = 'https://api.github.com/graphql';
const response = await got({
method: 'post',
url,
headers: {
Authorization: `bearer ${config.github.access_token}`,
},
json: {
query: `
{
user(login: "${user}") {
followers(first: 10) {
edges {
node {
login
avatarUrl
}
}
}
}
}
`,
},
});
const data = response.data.data.user.followers.edges;
ctx.set('data', {
allowEmpty: true,
title: `${user}'s followers`,
link: host,
item: data.map((follower) => ({
title: `${follower.node.login} started following ${user}`,
author: follower.node.login,
description: `<a href="https://github.com/${follower.node.login}">${follower.node.login}</a> <br> <img sytle="width:50px;" src='${follower.node.avatarUrl}'>`,
link: `https://github.com/${follower.node.login}`,
})),
});
};
+35
View File
@@ -0,0 +1,35 @@
import got from '@/utils/got';
import { config } from '@/config';
import { parseDate } from '@/utils/parse-date';
module.exports = async (ctx) => {
const gistId = ctx.req.param('gistId');
const headers = { Accept: 'application/vnd.github.v3+json' };
if (config.github && config.github.access_token) {
headers.Authorization = `Bearer ${config.github.access_token}`;
}
const host = 'https://gist.github.com';
const apiUrl = `https://api.github.com/gists/${gistId}`;
const { data: response } = await got(apiUrl, {
headers,
});
const items = response.history.map((item, index) => ({
title: `${item.user.login} ${index === response.history.length - 1 ? 'created' : 'revised'} this gist`,
description: item.change_status.total ? `${item.change_status.additions} additions and ${item.change_status.deletions} deletions` : null,
link: `${host}/${gistId}/${item.version}`,
pubDate: parseDate(item.committed_at), // e.g. 2022-09-02T11:09:56Z
}));
ctx.set('data', {
allowEmpty: true,
title: `${response.owner.login} / ${Object.values(response.files)[0].filename}`,
description: response.description,
image: response.owner.avatar_url,
link: `${response.html_url}/revisions`,
item: items,
});
};
+52
View File
@@ -0,0 +1,52 @@
import got from '@/utils/got';
import { config } from '@/config';
const md = require('markdown-it')({
html: true,
linkify: true,
});
const queryString = require('query-string');
import { parseDate } from '@/utils/parse-date';
module.exports = async (ctx) => {
const user = ctx.req.param('user');
const repo = ctx.req.param('repo');
const state = ctx.req.param('state');
const labels = ctx.req.param('labels');
const limit = ctx.req.query('limit') ? (Number.parseInt(ctx.req.query('limit')) > 100 ? 100 : Number.parseInt(ctx.req.query('limit'))) : 100;
const host = `https://github.com/${user}/${repo}/issues`;
const url = `https://api.github.com/repos/${user}/${repo}/issues`;
const headers = { Accept: 'application/vnd.github.v3+json' };
if (config.github && config.github.access_token) {
headers.Authorization = `token ${config.github.access_token}`;
}
const response = await got({
method: 'get',
url,
searchParams: queryString.stringify({
state,
labels,
sort: 'created',
direction: 'desc',
per_page: limit,
}),
headers,
});
const data = response.data;
ctx.set('data', {
allowEmpty: true,
title: `${user}/${repo}${state ? ' ' + state.replace(/^\S/, (s) => s.toUpperCase()) : ''} Issues${labels ? ' - ' + labels : ''}`,
link: host,
item: data
.filter((item) => item.pull_request === undefined)
.map((item) => ({
title: item.title,
description: item.body ? md.render(item.body) : 'No description',
pubDate: parseDate(item.created_at),
author: item.user.login,
link: `${host}/${item.number}`,
})),
});
};
+19
View File
@@ -0,0 +1,19 @@
module.exports = {
'/branches/:user/:repo': ['max-arnold'],
'/comments/:user/:repo/:number?': ['TonyRL', 'FliegendeWurst'],
'/contributors/:user/:repo/:order?/:anon?': ['zoenglinghou'],
'/file/:user/:repo/:branch/:filepath+': ['zengxs'],
'/gist/:gistId': ['TonyRL'],
'/issue/:user/:repo/:state?/:labels?': ['HenryQW', 'AndreyMZ'],
'/notifications': ['zhzy0077'],
'/pull/:user/:repo/:state?': ['hashman', 'TonyRL'],
'/pulse/:user/:repo/:period?': ['jameschensmith'],
'/repos/:user': ['DIYgod'],
'/search/:query/:sort?/:order?': ['LogicJake'],
'/starred_repos/:user': ['LanceZhu'],
'/stars/:user/:repo': ['HenryQW'],
'/topics/:name/:qs?': ['queensferryme'],
'/trending/:since/:language/:spoken_language?': ['DIYgod', 'jameschensmith'],
'/user/followers/:user': ['HenryQW'],
'/wiki/:user/:repo/:page?': ['TonyRL'],
};
+47
View File
@@ -0,0 +1,47 @@
import got from '@/utils/got';
import { parseDate } from '@/utils/parse-date';
const apiUrl = 'https://api.github.com';
import { config } from '@/config';
module.exports = async (ctx) => {
if (!config.github || !config.github.access_token) {
throw new Error('GitHub trending RSS is disabled due to the lack of <a href="https://docs.rsshub.app/install/#pei-zhi-bu-fen-rss-mo-kuai-pei-zhi">relevant config</a>');
}
const headers = {
Accept: 'application/vnd.github.v3+json',
Authorization: `Bearer ${config.github.access_token}`,
'X-GitHub-Api-Version': '2022-11-28',
};
const response = await got(`${apiUrl}/notifications`, {
headers,
});
const notifications = response.data;
const items = notifications.map((item) => ({
title: item.subject.title,
description: item.subject.title,
pubDate: parseDate(item.updated_at), // item.updated_at follows ISO 8601.
guid: item.id,
link: item.subject.url,
}));
ctx.set('data', {
title: 'Github Notifications',
link: 'https://github.com/notifications',
item: items,
});
ctx.set('json', {
title: 'Github Notifications',
item: notifications,
rateLimit: {
limit: Number.parseInt(response.headers['X-RateLimit-Limit']),
remaining: Number.parseInt(response.headers['X-RateLimit-Remaining']),
reset: parseDate(Number.parseInt(response.headers['X-RateLimit-Reset']) * 1000),
resoure: response.headers['X-RateLimit-Resource'],
used: Number.parseInt(response.headers['X-RateLimit-Used']),
},
});
};
+46
View File
@@ -0,0 +1,46 @@
import got from '@/utils/got';
import { config } from '@/config';
const md = require('markdown-it')({
html: true,
linkify: true,
});
import { parseDate } from '@/utils/parse-date';
module.exports = async (ctx) => {
const user = ctx.req.param('user');
const repo = ctx.req.param('repo');
const state = ctx.req.param('state') ?? 'open';
const labels = ctx.req.param('labels');
const host = `https://github.com/${user}/${repo}/pulls`;
const url = `https://api.github.com/repos/${user}/${repo}/issues`; // every PR is also an issue
const headers = { Accept: 'application/vnd.github.v3+json' };
if (config.github && config.github.access_token) {
headers.Authorization = `token ${config.github.access_token}`;
}
const response = await got(url, {
searchParams: {
state,
labels,
sort: 'created',
direction: 'desc',
per_page: ctx.req.query('limit') ? (Number.parseInt(ctx.req.query('limit')) <= 100 ? Number.parseInt(ctx.req.query('limit')) : 100) : 100,
},
headers,
});
const data = response.data.filter((item) => item.pull_request);
ctx.set('data', {
allowEmpty: true,
title: `${user}/${repo} Pull requests`,
link: host,
item: data.map((item) => ({
title: item.title,
author: item.user.login,
description: item.body ? md.render(item.body) : 'No description',
pubDate: parseDate(item.created_at),
link: item.html_url,
})),
});
};
+87
View File
@@ -0,0 +1,87 @@
import { load } from 'cheerio';
import * as path from 'node:path';
import got from '@/utils/got';
import md5 from '@/utils/md5';
import { parseDate } from '@/utils/parse-date';
import { art } from '@/utils/render';
module.exports = async (ctx) => {
const { user, repo, period } = ctx.req.param();
const periods = ['daily', 'halfweekly', 'weekly', 'monthly'];
const pulsePeriod = periods.includes(period) ? period : periods[2];
const link = `https://github.com/${user}/${repo}/pulse/${pulsePeriod}`;
const { data: pulsePage } = await got(link);
const $ = load(pulsePage);
const $mainSections = $('main .Layout-main').children();
const $subheading = $mainSections.eq(0);
const [periodFrom, periodTo] = $subheading.find('h2').text().split('–');
const $overview = $mainSections.eq(1);
const overviewItems = $overview
.find('ul ul li')
.map((_, el) => $(el).text())
.toArray();
const $commitActivity = $mainSections.eq(2);
let commitActivity;
const $contributionData = $commitActivity.find('.js-pulse-contribution-data');
if ($contributionData.length) {
const summaryUrl = $contributionData.attr('data-pulse-diffstat-summary-url');
commitActivity = (await got(`https://github.com${summaryUrl}`)).data;
} else {
commitActivity = $commitActivity.text();
}
const $githubActivity = $mainSections.eq(3);
let githubActivity;
const $sections = $githubActivity.find('h3');
if ($sections.length) {
githubActivity = $sections
.map((_, section) => {
const $section = $(section);
const $sectionSiblings = $section.nextUntil('h3');
const $paragraph = $section.nextUntil('ul');
const $list = $sectionSiblings.last();
return {
heading: $section.text(),
paragraph: $paragraph.length > 0 ? $paragraph.text() : undefined,
items: $list
.children()
.map((_, item) => {
const $item = $(item);
const $link = $item.find('a');
const $details = $item.find('p');
const $relativeTime = $details.find('relative-time');
$relativeTime.replaceWith($relativeTime.attr('datetime'));
return {
link: { text: $link.text(), url: $link.attr('href') },
details: $details.text(),
};
})
.toArray(),
};
})
.toArray();
}
ctx.set('data', {
title: `${user}/${repo} ${pulsePeriod} Pulse`,
link,
item: [
{
guid: md5(`${user}${repo}${period}${periodFrom}${periodTo}`),
title: `${periodFrom} - ${periodTo}`,
description: art(path.join(__dirname, 'templates/pulse-description.art'), {
overviewItems,
commitActivity,
githubActivity,
}),
pubDate: parseDate(periodTo),
},
],
});
};
+111
View File
@@ -0,0 +1,111 @@
module.exports = {
'github.com': {
_name: 'GitHub',
'.': [
{
title: 'Repo branches',
docs: 'https://docs.rsshub.app/routes/programming#github',
source: ['/:user/:repo/branches', '/:user/:repo'],
target: '/github/branches/:user/:repo',
},
{
title: 'Issues / Pull Requests comments',
docs: 'https://docs.rsshub.app/routes/programming#github',
source: ['/:user/:repo/:type/:number'],
target: '/github/comments/:user/:repo/:number',
},
{
title: 'Issue & Pull Request comments',
docs: 'https://docs.rsshub.app/routes/programming#github',
source: ['/:user/:repo/:type'],
target: '/github/comments/:user/:repo',
},
{
title: 'Repo contributors',
docs: 'https://docs.rsshub.app/routes/programming#github',
source: ['/:user/:repo/graphs/contributors', '/:user/:repo'],
target: '/github/contributors/:user/:repo',
},
{
title: 'File commits',
docs: 'https://docs.rsshub.app/routes/programming#github',
source: '/:user/:repo/blob/:branch/*filepath',
target: '/github/file/:user/:repo/:branch/:filepath',
},
{
title: 'Repo issues',
docs: 'https://docs.rsshub.app/routes/programming#github',
source: ['/:user/:repo/issues', '/:user/:repo/issues/:id', '/:user/:repo'],
target: '/github/issue/:user/:repo',
},
{
title: 'Repo Pull Requests',
docs: 'https://docs.rsshub.app/routes/programming#github',
source: ['/:user/:repo/pulls', '/:user/:repo/pulls/:id', '/:user/:repo'],
target: '/github/pull/:user/:repo',
},
{
title: 'Pulse',
docs: 'https://docs.rsshub.app/routes/programming#github',
source: ['/:user/:repo/pulse', '/:user/:repo/pulse/:period'],
target: '/github/pulse/:user/:repo/:period?',
},
{
title: 'User repos',
docs: 'https://docs.rsshub.app/routes/programming#github',
source: '/:user',
target: '/github/repos/:user',
},
{
title: 'Repo stars',
docs: 'https://docs.rsshub.app/routes/programming#github',
source: ['/:user/:repo/stargazers', '/:user/:repo'],
target: '/github/stars/:user/:repo',
},
{
title: 'User starred repositories',
docs: 'https://docs.rsshub.app/routes/programming#github',
source: '/:user',
target: '/github/starred_repos/:user',
},
{
title: 'Topics',
docs: 'https://docs.rsshub.app/routes/programming#github',
source: '/topics',
target: '/github/topics/:name/:qs?',
},
{
title: 'Trending',
docs: 'https://docs.rsshub.app/routes/programming#github',
source: '/trending',
target: '/github/trending/:since',
},
{
title: 'User followers',
docs: 'https://docs.rsshub.app/routes/programming#github',
source: '/:user',
target: '/github/user/followers/:user',
},
{
title: 'Wiki history',
docs: 'https://docs.rsshub.app/routes/programming#github',
source: ['/:user/:repo/wiki/:page/_history', '/:user/:repo/wiki/:page', '/:user/:repo/wiki/_history', '/:user/:repo/wiki'],
target: '/github/wiki/:user/:repo/:page',
},
{
title: 'Notifications',
docs: 'https://docs.rsshub.app/routes/programming#github',
source: ['/notifications'],
target: '/github/notifications',
},
],
gist: [
{
title: 'Gist Commits',
docs: 'https://docs.rsshub.app/routes/programming#github',
source: ['/:owner/:gistId/revisions', '/:owner/:gistId/stargazers', '/:owner/:gistId/forks', '/:owner/:gistId'],
target: '/github/gist/:gistId',
},
],
},
};
+34
View File
@@ -0,0 +1,34 @@
import got from '@/utils/got';
import { config } from '@/config';
const queryString = require('query-string');
module.exports = async (ctx) => {
const user = ctx.req.param('user');
const headers = {};
if (config.github && config.github.access_token) {
headers.Authorization = `token ${config.github.access_token}`;
}
const response = await got({
method: 'get',
url: `https://api.github.com/users/${user}/repos`,
searchParams: queryString.stringify({
sort: 'created',
}),
headers,
});
const data = response.data;
ctx.set('data', {
allowEmpty: true,
title: `${user}'s GitHub repositories`,
link: `https://github.com/${user}`,
item:
data &&
data.map((item) => ({
title: item.name,
description: item.description || 'No description',
pubDate: new Date(item.created_at).toUTCString(),
link: item.html_url,
})),
});
};
+20
View File
@@ -0,0 +1,20 @@
module.exports = function (router) {
router.get('/branches/:user/:repo', './branches');
router.get('/comments/:user/:repo/:type/:number', './comments'); // deprecated
router.get('/comments/:user/:repo/:number?', './comments');
router.get('/contributors/:user/:repo/:order?/:anon?', './contributors');
router.get('/file/:user/:repo/:branch/:filepath+', './file');
router.get('/gist/:gistId', './gist');
router.get('/issue/:user/:repo/:state?/:labels?', './issue');
router.get('/notifications', './notifications');
router.get('/pull/:user/:repo/:state?/:labels?', './pulls');
router.get('/pulse/:user/:repo/:period?', './pulse');
router.get('/repos/:user', './repos');
router.get('/search/:query/:sort?/:order?', './search');
router.get('/starred_repos/:user', './starred-repos');
router.get('/stars/:user/:repo', './star');
router.get('/topics/:name/:qs?', './topic');
router.get('/trending/:since/:language/:spoken_language?', './trending');
router.get('/user/followers/:user', './follower');
router.get('/wiki/:user/:repo/:page?', './wiki');
};
+41
View File
@@ -0,0 +1,41 @@
import got from '@/utils/got';
import { load } from 'cheerio';
const url = require('url');
const host = 'https://github.com';
module.exports = async (ctx) => {
const query = ctx.req.param('query');
let sort = ctx.req.param('sort') || 'bestmatch';
const order = ctx.req.param('order') || 'desc';
if (sort === 'bestmatch') {
sort = '';
}
const suffix = 'search?o='.concat(order, '&q=', encodeURIComponent(query), '&s=', sort, '&type=Repositories');
const link = url.resolve(host, suffix);
const response = await got.get(link);
const $ = load(response.data);
const out = $('.repo-list li')
.slice(0, 10)
.map(function () {
const a = $(this).find('.f4.text-normal > a');
const single = {
title: a.text(),
author: a.text().split('/')[0].trim(),
link: host.concat(a.attr('href')),
description: $(this).find('div p').text().trim(),
};
return single;
})
.get();
ctx.set('data', {
allowEmpty: true,
title: `${query}的搜索结果`,
link,
item: out,
});
};
+51
View File
@@ -0,0 +1,51 @@
import got from '@/utils/got';
import { config } from '@/config';
module.exports = async (ctx) => {
if (!config.github || !config.github.access_token) {
throw new Error('GitHub star RSS is disabled due to the lack of <a href="https://docs.rsshub.app/install/#pei-zhi-bu-fen-rss-mo-kuai-pei-zhi">relevant config</a>');
}
const user = ctx.req.param('user');
const repo = ctx.req.param('repo');
const host = `https://github.com/${user}/${repo}/stargazers`;
const url = 'https://api.github.com/graphql';
const response = await got({
method: 'post',
url,
headers: {
Authorization: `bearer ${config.github.access_token}`,
},
json: {
query: `
{
repository(owner: "${user}", name: "${repo}") {
stargazers(last: 10) {
edges {
node {
login
avatarUrl
}
}
}
}
}
`,
},
});
const data = response.data.data.repository.stargazers.edges.reverse();
ctx.set('data', {
allowEmpty: true,
title: `${user}/${repo}’s stargazers`,
link: host,
item: data.map((follower) => ({
title: `${follower.node.login} starred ${user}/${repo}`,
author: follower.node.login,
description: `<a href="https://github.com/${follower.node.login}">${follower.node.login}</a> <br> <img sytle="width:50px;" src='${follower.node.avatarUrl}'>`,
link: `https://github.com/${follower.node.login}`,
})),
});
};
+63
View File
@@ -0,0 +1,63 @@
import got from '@/utils/got';
import { config } from '@/config';
module.exports = async (ctx) => {
if (!config.github || !config.github.access_token) {
throw new Error('GitHub star RSS is disabled due to the lack of <a href="https://docs.rsshub.app/install/#pei-zhi-bu-fen-rss-mo-kuai-pei-zhi">relevant config</a>');
}
const user = ctx.req.param('user');
const host = `https://github.com/${user}?tab=stars`;
const url = 'https://api.github.com/graphql';
const response = await got({
method: 'post',
url,
headers: {
Authorization: `bearer ${config.github.access_token}`,
},
json: {
query: `
{
user(login: "${user}") {
starredRepositories(first: 10, orderBy: {direction: DESC, field: STARRED_AT}) {
edges {
starredAt
node {
name
description
url
openGraphImageUrl
primaryLanguage {
name
}
stargazers {
totalCount
}
}
}
}
}
}
`,
},
});
const data = response.data.data.user.starredRepositories.edges;
ctx.set('data', {
allowEmpty: true,
title: `${user}’s starred repositories`,
link: host,
description: `${user}’s starred repositories`,
item: data.map((repo) => ({
title: `${user} starred ${repo.node.name}`,
author: user,
description: `${repo.node.description === null ? 'no description' : repo.node.description} <br> primary language: ${
repo.node.primaryLanguage === null ? 'no primary language' : repo.node.primaryLanguage.name
} <br> stargazers: ${repo.node.stargazers.totalCount} <br> <img sytle="width:50px;" src='${repo.node.openGraphImageUrl}'>`,
pubDate: new Date(repo.starredAt),
link: repo.node.url,
})),
});
};
@@ -0,0 +1 @@
{{@ desc }}
@@ -0,0 +1,24 @@
<h2>Overview</h2>
<ul>
{{each overviewItems item}}
<li>{{item}}</li>
{{/each}}
</ul>
{{@ commitActivity}}
{{each githubActivity activity}}
<h2>{{activity.heading}}</h2>
{{if activity.paragraph}}
<p>{{activity.paragraph}}</p>
{{/if}}
<ul>
{{each activity.items item}}
<li>
<a href="{{item.link.url}}">{{item.link.text}}</a>
<p>{{item.details}}</p>
</li>
{{/each}}
</ul>
{{/each}}
@@ -0,0 +1,5 @@
<img src="{{@ cover }}">
<br>{{@ desc }}
<br><br>Language: {{@ lang }}
<br>Stars: {{@ stars }}
<br>Forks: {{@ forks }}
+41
View File
@@ -0,0 +1,41 @@
import { load } from 'cheerio';
import got from '@/utils/got';
import { parseDate } from '@/utils/parse-date';
module.exports = async (ctx) => {
const link = `https://github.com/topics/${ctx.req.param('name')}`;
const { data, url } = await got(link, {
searchParams: new URLSearchParams(ctx.req.param('qs')),
});
const $ = load(data);
ctx.set('data', {
title: $('title').text(),
description: $('.markdown-body').text().trim(),
link: url,
item: $('article.my-4')
.toArray()
.map((item) => {
item = $(item);
const title = item.find('h3').text().trim();
const author = title.split('/')[0];
const description = (item.find('a img').prop('outerHTML') ?? '') + item.find('div > div > p').text();
const link = `https://github.com${item.find('h3 a').last().attr('href')}`;
const category = item
.find('.topic-tag')
.toArray()
.map((item) => $(item).text().trim());
const pubDate = parseDate(item.find('relative-time').attr('datetime'));
return {
title,
author,
description,
link,
category,
pubDate,
};
}),
});
};
+89
View File
@@ -0,0 +1,89 @@
import { config } from '@/config';
import got from '@/utils/got';
import { art } from '@/utils/render';
import { load } from 'cheerio';
import * as path from 'node:path';
module.exports = async (ctx) => {
if (!config.github || !config.github.access_token) {
throw new Error('GitHub trending RSS is disabled due to the lack of <a href="https://docs.rsshub.app/install/#pei-zhi-bu-fen-rss-mo-kuai-pei-zhi">relevant config</a>');
}
const since = ctx.req.param('since');
const language = ctx.req.param('language') === 'any' ? '' : ctx.req.param('language');
const spoken_language = ctx.req.param('spoken_language') ?? '';
const trendingUrl = `https://github.com/trending/${encodeURIComponent(language)}?since=${since}&spoken_language_code=${spoken_language}`;
const { data: trendingPage } = await got({
method: 'get',
url: trendingUrl,
headers: {
Referer: trendingUrl,
},
});
const $ = load(trendingPage);
const articles = $('article');
const trendingRepos = articles.toArray().map((item) => {
const [owner, name] = $(item).find('h2').text().split('/');
return {
name: name.trim(),
owner: owner.trim(),
};
});
const { data: repoData } = await got({
method: 'post',
url: 'https://api.github.com/graphql',
headers: {
Authorization: `bearer ${config.github.access_token}`,
},
json: {
query: `
query {
${trendingRepos
.map(
(repo, index) => `
_${index}: repository(owner: "${repo.owner}", name: "${repo.name}") {
...RepositoryFragment
}
`
)
.join('\n')}
}
fragment RepositoryFragment on Repository {
description
forkCount
nameWithOwner
openGraphImageUrl
primaryLanguage {
name
}
stargazerCount
}
`,
},
});
const repos = Object.values(repoData.data).map((repo) => {
const found = trendingRepos.find((r) => `${r.owner}/${r.name}` === repo.nameWithOwner);
return { ...found, ...repo };
});
ctx.set('data', {
title: $('title').text(),
link: trendingUrl,
item: repos.map((r) => ({
title: r.nameWithOwner,
author: r.owner,
description: art(path.join(__dirname, 'templates/trending-description.art'), {
cover: r.openGraphImageUrl,
desc: r.description,
forks: r.forkCount,
lang: r.primaryLanguage?.name || 'Unknown',
stars: r.stargazerCount,
}),
link: `https://github.com/${r.nameWithOwner}`,
})),
});
};
+32
View File
@@ -0,0 +1,32 @@
import got from '@/utils/got';
import { load } from 'cheerio';
import { parseDate } from '@/utils/parse-date';
const baseUrl = 'https://github.com';
module.exports = async (ctx) => {
const { user, repo, page } = ctx.req.param();
const url = `${baseUrl}/${user}/${repo}/wiki${page ? `/${page}` : ''}/_history`;
const { data } = await got(url);
const $ = load(data);
const items = $('.js-wiki-history-revision')
.toArray()
.map((item) => {
item = $(item);
return {
title: item.find('.h5').text(),
author: item.find('.mt-1 a').text(),
pubDate: parseDate(item.find('relative-time').attr('datetime')),
link: `${baseUrl}${item.find('.text-mono a').attr('href')}`,
};
});
ctx.set('data', {
title: `${$('.gh-header-title').text()} - ${user}/${repo}`,
link: url,
item: items,
});
};