Skip to content

Commit

Permalink
feat: v4.40.0
Browse files Browse the repository at this point in the history
  • Loading branch information
surmon-china committed Aug 17, 2024
1 parent 6556c66 commit 0343e0c
Show file tree
Hide file tree
Showing 17 changed files with 157 additions and 276 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "surmon.me",
"version": "4.39.0",
"version": "4.40.0",
"description": "Surmon.me blog",
"author": "Surmon",
"license": "MIT",
Expand Down
48 changes: 20 additions & 28 deletions src/bff.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,10 @@ import { getGTagScript } from './server/getters/gtag'
import { getAllWallpapers } from './server/getters/wallpaper'
import { getMyGoogleMap } from './server/getters/my-google-map'
import { getTwitterProfile, getTwitterTweets } from './server/getters/twitter'
import { getGitHubSponsors, getGitHubContributions } from './server/getters/github'
import { getInstagramMedias, getInstagramMediaChildren, getInstagramCalendar } from './server/getters/instagram'
import { getYouTubeChannelPlayLists, getYouTubeVideoListByPlayerlistId } from './server/getters/youtube'
import { getGitHubStatistic, getNPMStatistic } from './server/getters/open-srouce'
import { getGitHubStatistic, getGitHubSponsors, getGitHubContributions } from './server/getters/github'
import { getNPMStatistic } from './server/getters/npm'
import { getDoubanMovies } from './server/getters/douban'
import { getSongList } from './server/getters/netease-music'
import { getWebFont, WebFontContentType } from './server/getters/webfont'
Expand Down Expand Up @@ -122,20 +122,6 @@ createExpressApp().then(async ({ app, server, cache }) => {
responser(() => getWallpaperCache())
)

// GitHub sponsors
const getSponsorsCache = cacher.interval(cache, {
key: TunnelModule.GitHubSponsors,
ttl: days(3),
interval: hours(18),
retry: minutes(10),
getter: getGitHubSponsors
})

app.get(
`${TUN}/${TunnelModule.GitHubSponsors}`,
responser(() => getSponsorsCache())
)

// 163 music BGM list
const get163MusicCache = cacher.interval(cache, {
key: TunnelModule.NetEaseMusic,
Expand Down Expand Up @@ -240,30 +226,36 @@ createExpressApp().then(async ({ app, server, cache }) => {
})(request, response, next)
})

// GitHub sponsors
app.get(
`${TUN}/${TunnelModule.GitHubSponsors}`,
responser(() => {
return cacher.passive(cache, {
key: TunnelModule.GitHubSponsors,
ttl: hours(4),
getter: getGitHubSponsors
})
})
)

// GitHub contributions
app.get(
`${TUN}/${TunnelModule.GitHubContributions}`,
responser(() => {
return cacher.passive(cache, {
key: TunnelModule.GitHubContributions,
ttl: hours(8),
getter: () => {
const now = new Date()
const end = now.toISOString()
now.setFullYear(now.getFullYear() - 1)
const start = now.toISOString()
return getGitHubContributions(start, end)
}
ttl: hours(4),
getter: getGitHubContributions
})
})
)

// GitHub statistic
app.get(
`${TUN}/${TunnelModule.OpenSourceGitHubStatistic}`,
`${TUN}/${TunnelModule.StatisticGitHubJson}`,
responser(() => {
return cacher.passive(cache, {
key: TunnelModule.OpenSourceGitHubStatistic,
key: TunnelModule.StatisticGitHubJson,
ttl: hours(8),
getter: getGitHubStatistic
})
Expand All @@ -272,10 +264,10 @@ createExpressApp().then(async ({ app, server, cache }) => {

// NPM statistic
app.get(
`${TUN}/${TunnelModule.OpenSourceNPMStatistic}`,
`${TUN}/${TunnelModule.StatisticNpmJson}`,
responser(() => {
return cacher.passive(cache, {
key: TunnelModule.OpenSourceNPMStatistic,
key: TunnelModule.StatisticNpmJson,
ttl: hours(8),
getter: getNPMStatistic
})
Expand Down
15 changes: 9 additions & 6 deletions src/components/widget/sponsor/provider.vue
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,15 @@
const { isZhLang } = useEnhancer()
const activeProvider = computed(() => props.state.activeProvider.value)
const allGitHubSponsors = computed(() => {
if (!props.state.githubSponsors.data) {
return []
}
return [
...props.state.githubSponsor.activeSponsors.map((sponsor) => ({
...props.state.githubSponsors.data.currentSponsors.map((sponsor) => ({
active: true,
_: sponsor
})),
...props.state.githubSponsor.inactiveSponsors.map((sponsor) => ({
...props.state.githubSponsors.data.pastSponsors.map((sponsor) => ({
active: false,
_: sponsor
}))
Expand Down Expand Up @@ -70,13 +73,13 @@
<i18n>
<template #zh>
我在 GitHub Sponsors 累计已得到
<span class="active-total"> {{ state.githubSponsor.activeSponsors.length }} </span>
+ {{ state.githubSponsor.inactiveSponsors.length }} 位赞助者的支持
<span class="active-total"> {{ state.githubSponsors.data?.currentSponsors.length }} </span>
+ {{ state.githubSponsors.data?.pastSponsors.length }} 位赞助者的支持
</template>
<template #en>
I have accumulated
<span class="active-total">{{ state.githubSponsor.activeSponsors.length }}</span>
+ {{ state.githubSponsor.inactiveSponsors.length }} backers on GitHub Sponsors
<span class="active-total">{{ state.githubSponsors.data?.currentSponsors.length }}</span>
+ {{ state.githubSponsors.data?.pastSponsors.length }} backers on GitHub Sponsors
</template>
</i18n>
</p>
Expand Down
6 changes: 3 additions & 3 deletions src/components/widget/sponsor/state.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { ref, computed } from 'vue'
import { useEnhancer } from '/@/app/enhancer'
import { GAEventCategories } from '/@/constants/gtag'
import { useSponsorStore } from '/@/stores/sponsor'
import { useGitHubSponsorsStore } from '/@/stores/sponsors'
import { IDENTITIES, VALUABLE_LINKS } from '/@/config/app.config'

export enum ProviderId {
Expand Down Expand Up @@ -60,7 +60,7 @@ export const PROVIDERS = [
export type SponsorState = ReturnType<typeof useSponsorState>
export const useSponsorState = (initId?: ProviderId) => {
const { gtag } = useEnhancer()
const githubSponsor = useSponsorStore()
const githubSponsors = useGitHubSponsorsStore()
const activeId = ref(initId && PROVIDER_IDS.includes(initId) ? initId : PROVIDERS[0].id)
const activeProvider = computed(() => PROVIDERS.find((t) => t.id === activeId.value)!)

Expand All @@ -77,6 +77,6 @@ export const useSponsorState = (initId?: ProviderId) => {
activeId,
activeProvider,
setProviderId,
githubSponsor
githubSponsors
}
}
1 change: 0 additions & 1 deletion src/config/bff.yargs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
import yargs from 'yargs'
const argv = yargs(process.argv.slice(2)).argv

export const GITHUB_BEARER_TOKEN = argv.github_token
export const INSTAGRAM_TOKEN = argv.instagram_token
export const YOUTUBE_API_KEY = argv.youtube_token
export const TWITTER_COOKIE = argv.twitter_cookie
Expand Down
8 changes: 4 additions & 4 deletions src/constants/tunnel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,10 @@ export enum TunnelModule {
InstagramMediaChildren = 'instagram_media_children',
InstagramCalendar = 'instagram_calendar',
BingWallpaper = 'bing_wallpaper',
GitHubSponsors = 'github_sponsors',
GitHubContributions = 'github_contributions',
NetEaseMusic = 'netease_music',
DoubanMovies = 'douban_movies',
OpenSourceGitHubStatistic = 'open_source_github_statistic',
OpenSourceNPMStatistic = 'open_source_npm_statistic'
GitHubSponsors = 'github_sponsors',
GitHubContributions = 'github_contributions',
StatisticGitHubJson = 'statistic_github_json',
StatisticNpmJson = 'statistic_npm_json'
}
4 changes: 2 additions & 2 deletions src/pages/about/desktop.vue
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
import { useAboutPageMeta, useAdminAvatar, i18ns, SPECIAL_LINKS } from './shared'
const { gtag, gState, isZhLang, cdnDomain } = useEnhancer()
const { adminInfo, appOption, sponsor } = useStores()
const { adminInfo, appOption, githubSponsors } = useStores()
const handleGTagEvent = (event: string) => {
gtag?.event(event, {
Expand All @@ -43,7 +43,7 @@
}
const handleSponsor = () => {
sponsor.fetch()
githubSponsors.fetch()
gState.toggleSwitcher('sponsor', true)
handleGTagEvent('sponsor_modal')
}
Expand Down
4 changes: 2 additions & 2 deletions src/pages/article/index.vue
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@
}>()
const { i18n: _i18n, head, seoMeta, route, gtag, gState } = useEnhancer()
const { identity, sponsor, comment: commentStore, articleDetail: articleDetailStore } = useStores()
const { identity, githubSponsors, comment: commentStore, articleDetail: articleDetailStore } = useStores()
const { article, fetching, prevArticle, nextArticle, relatedArticles } = storeToRefs(articleDetailStore)
const isLiked = computed(() => Boolean(article.value && identity.isLikedPage(article.value.id)))
const articleExtends = computed(() => article.value?.extends || [])
Expand All @@ -54,7 +54,7 @@
}
const handleSponsor = () => {
sponsor.fetch()
githubSponsors.fetch()
gState.toggleSwitcher('sponsor', true)
gtag?.event('article_sponsor', {
event_category: GAEventCategories.Article
Expand Down
2 changes: 1 addition & 1 deletion src/pages/sponsor.vue
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
})
onBeforeMount(() => {
sponsorState.githubSponsor.fetch()
sponsorState.githubSponsors.fetch()
})
onMounted(() => {
Expand Down
146 changes: 43 additions & 103 deletions src/server/getters/github.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,28 +6,33 @@

import axios from '@/server/services/axios'
import { IDENTITIES } from '@/config/app.config'
import { GITHUB_BEARER_TOKEN } from '@/config/bff.yargs'

const graphqlGitHub = <T = any>(query: string): Promise<T> => {
return axios
.request<any>({
// https://github.com/settings/tokens
headers: { Authorization: `bearer ${GITHUB_BEARER_TOKEN}` },
url: `https://api.github.com/graphql`,
method: 'POST',
data: JSON.stringify({
query: `query {
user(login: "${IDENTITIES.GITHUB_USER_NAME}") {
${query}
}
}`
})
})
.then((response) => {
return response.data.errors
? Promise.reject(response.data.errors.map((error) => error.message).join('; '))
: Promise.resolve(response.data.data.user)
})
export const fetchGitHubStatisticJSON = async <T = any>(fileName: string): Promise<T> => {
const url = `https://raw.githubusercontent.com/${IDENTITIES.GITHUB_USER_NAME}/${IDENTITIES.GITHUB_USER_NAME}/release/${fileName}`
const response = await axios.get<T>(url, { timeout: 6000 })
return response.data
}

export interface GitHubStatistic {
followerCount: number
followingCount: number
gistCount: number
repositoryCount: number
organizationCount: number
totalStarCount: number
totalCodeSize: number
}

export const getGitHubStatistic = () => {
return fetchGitHubStatisticJSON<any>('github.json').then((data) => ({
followerCount: data.userinfo.followers,
followingCount: data.userinfo.following,
gistCount: data.userinfo.public_gists,
repositoryCount: data.userinfo.public_repos,
organizationCount: data.organizations.length,
totalStarCount: data.statistics.stars,
totalCodeSize: data.statistics.size
}))
}

export interface GitHubSponsorUser {
Expand All @@ -39,94 +44,29 @@ export interface GitHubSponsorUser {
}

export interface GitHubSponsorsResponse {
sponsorsActivities: {
nodes: Array<null | {
action: string
sponsorsTier: {
isOneTime: boolean
}
sponsor: GitHubSponsorUser
}>
}
sponsors: {
totalCount: number
edges: Array<{
node: GitHubSponsorUser
}>
}
totalCount: number
currentSponsors: GitHubSponsorUser[]
pastSponsors: GitHubSponsorUser[]
}

export const getGitHubSponsors = () => {
const SPONSOR_NODE_QUERY = `
... on User {
login
name
url
avatarUrl
websiteUrl
}
... on Organization {
login
name
url
avatarUrl
websiteUrl
}
`

// https://github.com/orgs/community/discussions/37234#discussioncomment-4047906
// https://github.com/dohooo/get-past-sponsors
// https://github.com/community/community/discussions/3818#discussioncomment-2155340
// https://docs.github.com/en/graphql/reference/objects#sponsorsactivity
// https://docs.github.com/en/graphql/reference/enums#sponsorsactivityaction
return graphqlGitHub(`
sponsorsActivities(first:100, period: ALL, orderBy: { direction: DESC, field: TIMESTAMP }, actions: [NEW_SPONSORSHIP, CANCELLED_SPONSORSHIP]) {
nodes {
action,
sponsorsTier {
isOneTime
},
sponsor {
${SPONSOR_NODE_QUERY}
}
}
},
sponsors(first: 100) {
totalCount
edges {
node {
${SPONSOR_NODE_QUERY}
}
}
}
`)
return fetchGitHubStatisticJSON<GitHubSponsorsResponse>('github.sponsors.json')
}

const isISODateString = (dateString: string) => {
if (!/\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}.\d{3}Z/.test(dateString)) return false
return new Date(dateString).toISOString() === dateString
export interface GitHubContributionDay {
weekday: number
date: string // YYYY-MM-DD
contributionCount: number
color: string
}

export const getGitHubContributions = async (from: string, to: string): Promise<any> => {
if (!isISODateString(from) || !isISODateString(to)) {
return Promise.reject('Invalid date string!')
}

const result = await graphqlGitHub(`
contributionsCollection(from: "${from}", to: "${to}") {
contributionCalendar {
totalContributions
weeks {
contributionDays {
weekday
date
contributionCount
color
}
}
}
}
`)
export interface GitHubContributionsResponse {
totalContributions: number
weeks: Array<{
contributionDays: Array<GitHubContributionDay>
}>
}

return result.contributionsCollection.contributionCalendar
export const getGitHubContributions = () => {
return fetchGitHubStatisticJSON<GitHubContributionsResponse>('github.contributions.json')
}
Loading

0 comments on commit 0343e0c

Please sign in to comment.