Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# GITHUB_ID=
# GITHUB_SECRET=
# NEXTAUTH_SECRET=
# POSTGRES_URL=
# SUPABASE_KEY=
3 changes: 3 additions & 0 deletions .eslintrc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"extends": "next/core-web-vitals"
}
38 changes: 38 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.

# dependencies
/node_modules
/.pnp
.pnp.js
.yarn/install-state.gz

# testing
/coverage

# next.js
/.next/
/out/

# production
/build

# misc
.DS_Store
*.pem

# debug
npm-debug.log*
yarn-debug.log*
yarn-error.log*

# local env files
.env

# vercel
.vercel

# typescript
*.tsbuildinfo
next-env.d.ts
bun.lockb
package-lock.json
30 changes: 30 additions & 0 deletions app/api/auth/[...nextauth]/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import NextAuth, { NextAuthOptions, Session } from "next-auth"
import { JWT } from "next-auth/jwt";
import GithubProvider from "next-auth/providers/github"

const authOptions: NextAuthOptions = {
// Configure one or more authentication providers
providers: [
GithubProvider({
clientId: process.env.GITHUB_ID!,
clientSecret: process.env.GITHUB_SECRET!,
}),
],
secret: process.env.NEXTAUTH_SECRET,
callbacks: {
async session({ session, token }: { session: any; token: JWT }) {
session.accessToken = token.accessToken as string;
return session;
},
async jwt({ token, account }: { token: JWT; account: any }) {
if (account) {
token.accessToken = account.access_token as string;
}
return token;
},
},
}

const handler = NextAuth(authOptions);

export { handler as GET, handler as POST }
65 changes: 65 additions & 0 deletions app/api/contributors/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
import { fetchContributors, fetchUserData } from '../../../utils/fetchData';
import { supabase } from '@/utils/supabase';

export const GET = async (req: any, res: any) => {
try {
const data = await fetchContributions();
return Response.json(data);
} catch (error) {
console.error(error)
return Response.json({ error: 'Internal Server Error' });
}
}


async function fetchContributions() {

let { data, error } = await supabase
.from('contributions')
.select('*')

if(error){
console.error('error', error);
return [];
// throw error
}

// data should be { username: username, totalPRs: totalPrs, mergedPRs: mergedPRs, openPRs: openPRs, issues: issueCount, avatar:avatar_url };
console.log(data)
return data;
}

export const POST = async (req: any, res: any) => {
try {

//get access_token from req, validate it and add user to Users table
const json = await req.json();
let { data: { access_token: access_token } } = json

const { username: username, avatar: avatar }: { username: string; avatar: string } = await fetchUserData(access_token);

console.log("username:", username, "avatar:", avatar);

if (!(username && avatar)) {
throw Error("Invalid username or avatar");
}

// new user
// insert into Users table

const { data, error } = await supabase
.from('Users')
.insert([
{ username: username, avatar: avatar }
])
.select()

console.log("data:", data, "error:", error)
return Response.json({ data: "User added successfully" });

} catch (error) {
console.error(error);
return Response.json({ error: 'Internal Server Error' });
}

}
96 changes: 96 additions & 0 deletions app/api/refreshDB/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
import { fetchContributionData } from "@/utils/fetchData";
import { supabase } from "@/utils/supabase"

export const GET = async (req: any, res: any) => {

let contributorsData: { username: string; totalPRs: number; mergedPRs: number; openPRs: number; issues: number; avatar?: string }[] = []

// cron.schedule('* * * * *', async () => {

console.log('')
console.log('#########################################')
console.log('# #')
console.log('# Refreshing contributions every minute #')
console.log('# #')
console.log('#########################################')
console.log('')
const users = await fetchUsers();

const usernames = users?.map((user: any) => user.username) || [];

console.log("usernames:", usernames);

for (let i = 0; i < usernames.length; i++) {
const contributionData = await fetchContributionData(usernames[i]);
if(!contributionData) continue;
// Check if the username already exists in the database
const { data: existingUser, error: fetchError } = await supabase
.from('contributions')
.select('*')
.eq('username', contributionData.username)

console.log("existingUser:", existingUser, "fetchError:", fetchError);


if (fetchError) {
console.error("Fetch error:", fetchError);
continue; // Skip to the next username if there's an error
}

if (existingUser.length) {
console.log("Update existing user: ", contributionData.username);
await supabase
.from('contributions')
.update(contributionData)
.eq('username', contributionData.username);
} else {

console.log("Insert new user: ", contributionData.username);
contributorsData.push(contributionData);
}
}

console.log("contributorsData:", contributorsData);

// Upsert only new contributors
const updatedContributions = await supabase.from('contributions').upsert(contributorsData);
if (updatedContributions.error)
console.error("updatedContributions error:", updatedContributions.error)
// });
return Response.json(contributorsData);
}

const fetchUsers = async () => {

let { data: Users, error } = await supabase
.from('Users')
.select('*')

// console.log("Users:", Users)

if (error) { console.log('error', error); return [] }
return Users;
}

import { NextResponse } from "next/server";

import cron from 'node-cron';

export async function POST(req: any, res: any) {

try {



await fetch('/api/refreshDB', { method: "GET" });



return NextResponse.json({ data: 'Success', status: 200 });

} catch (error) {
console.log(error)
return NextResponse.json({ error: error }, { status: 500 })
}

}
18 changes: 18 additions & 0 deletions app/components/Footer.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import Link from "next/link";

export default function Footer() {
return (

<footer className="flex flex-col gap-2 sm:flex-row py-6 w-full shrink-0 items-center px-4 md:px-6 border-t">
<p className="text-xs text-muted-foreground">&copy; 2024 100xLeaderboard. All rights reserved.</p>
<nav className="sm:ml-auto flex gap-4 sm:gap-6">
<Link href="#" className="text-xs hover:underline underline-offset-4" prefetch={false}>
Terms of Service
</Link>
<Link href="#" className="text-xs hover:underline underline-offset-4" prefetch={false}>
Privacy
</Link>
</nav>
</footer>
)
}
32 changes: 32 additions & 0 deletions app/components/Hero.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
'use client'

import Link from "next/link"


export default function Hero() {
return (
<>
<div className="flex flex-col">
<header className="px-4 lg:px-6 h-14 flex items-center justify-between">
<Link href="#" className="flex items-center justify-center" prefetch={false}>
<span className="sr-only">100xLeaderboard</span>
</Link>

</header>
<main className="flex-1">
<section className="w-full py-2 lg:py-2">
<div className="container grid items-center justify-center gap-4 px-4 md:px-6 lg:gap-10">
<div className="space-y-2">
<h2 className="text-3xl font-bold tracking-tighter md:text-4xl/tight">
100xLeaderboard
</h2>
<p className="max-w-[600px] text-muted-foreground md:text-xl/relaxed lg:text-base/relaxed xl:text-xl/relaxed">
The Ultimate Showcase of Top Contributors </p>
</div>
</div>
</section>
</main>
</div>
</>
)
}
85 changes: 85 additions & 0 deletions app/components/Home.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
'use client'
import { Page, Box } from "grommet"
import { getSession, signIn, signOut, useSession } from "next-auth/react";

import { Component } from "./component";
import { useState, useEffect } from "react";
import Footer from "./Footer";
import Hero from "./Hero";

import { Button } from "./ui/button";
import { FaGithub } from "react-icons/fa";


export default function Home() {

const { data: session } = useSession();
const [contributorData, setContributorData] = useState([]);

useEffect(() => {
const fetchData = async () => {
const data = await fetch('/api/contributors?', { headers: { 'Cache-Control': 'no-cache' } }).then((res) => res.json());
if (data.error) { setContributorData([]) }
else {
setContributorData(data);
}
};
fetchData();

// const intervalId = setInterval(fetchData, 10000); // load every 10 seconds

// return () => clearInterval(intervalId); // Cleanup on unmount
}, []);

useEffect(() => {
if (session) {
//@ts-ignore
const access_token = session.accessToken || "test";

fetch('/api/contributors', {method:"POST", headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ data: { access_token: access_token } })}).then((res) => res.json());
}
}
, [])


return (
<>
<Page>


<Box>
<Hero />
{!session &&
<div className="flex justify-center mt-4">
<Button
onClick={() => signIn()}
className="inline-flex w-50 h-10 items-center justify-center rounded-md text-sm font-medium text-primary-foreground shadow transition-colors hover:bg-primary/90 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50"
>
<FaGithub className="mr-1" size="small" />
Connect Github
</Button>
</div>

}

{/* {session && */}
{/* <div className="flex justify-center mt-4">
<Button
onClick={() => signOut()}
className="inline-flex w-50 h-10 items-center justify-center rounded-md text-sm font-medium text-primary-foreground shadow transition-colors hover:bg-primary/90 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50"
>
<FaGithub className="mr-1" size="small" />
Signout
</Button>
</div> */}

<Component contributors={contributorData} />
{/* {session ? <Component contributors={contributorData} /> : <Login />} */}
<Footer />
</Box>
</Page >


</>
);
}
Loading