Skip to content

Commit

Permalink
Add Youtube tabs with filters
Browse files Browse the repository at this point in the history
  • Loading branch information
anoopkarnik committed Jul 30, 2024
1 parent ef7117f commit 27991f7
Show file tree
Hide file tree
Showing 23 changed files with 1,638 additions and 116 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,10 @@ export const onNotionConnection = async ({access_token, workspace_id, workspace_
if(notion_connected) return {success: "Notion Connection already exists"}
const notion = await createConnection({type: 'Notion', userId, accessToken: access_token, workspaceName: workspace_name, workspaceIcon: workspace_icon, workspaceId: workspace_id})
if(!notion) return {error: "Notion Connection not created successfully"}
return notion
return {
success: "Notion Connection created successfully",
result: notion
}
}

export const getNotionConnection = async (userId: string) => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,10 @@ export const onOpenAIConnection = async ({apiKey,userId}:any) => {
if (openai_connected) return {success: "OpenAI Connection already exists"}
const openai = await createConnection({apiKey,type:'OpenAI', userId})
if(!openai) return {error: "OpenAI Connection not created successfully"}
return openai;
return {
success: "OpenAI Connection created successfully",
result: openai
}

}

Expand Down
12 changes: 10 additions & 2 deletions apps/dashboard-app/actions/connections/user-connections.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,16 @@ export const getUserInfo = async (userId: string) => {
}

export const updateConnectionById = async (id: string, name: string) => {
const conn = await updateConnection(id,name);
return conn;
try{
const conn = await updateConnection(id,name);
return {
success: `Notion Connection Name successfully updated to ${name}`,
result: conn
}
}
catch (error) {
return {error: "Notion Connection Not not updated successfully"}
}
}

export const deleteConnectionById = async (id: string) => {
Expand Down
97 changes: 76 additions & 21 deletions apps/dashboard-app/actions/connections/youtube-connections.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
'use server'

import { createConnection, getConnectionByAccessToken, getConnectionsByUserAndType } from '@repo/prisma-db/repo/connection'
import { createConnection, getConnectionByAccessToken, getConnectionByUserIdAndTypeAndName, getConnectionsByUserAndType } from '@repo/prisma-db/repo/connection'
import axios from 'axios'
import { getNotionConnection } from './notion-connections'
import { createNotionPageAction } from '../notion/notion'
import { createNotionPageAction, queryAllNotionDatabaseAction } from '../notion/notion'
import { delay } from '../../lib/utils'
import { modifyNotionPage } from '@repo/notion/notion-client'

const MAX_RETRIES = 3;
const RETRY_DELAY = 1000;
Expand All @@ -13,28 +14,17 @@ export const onYoutubeConnection = async ({access_token, refresh_token, scopes,
if(access_token && userId){
console.log('Access Token', access_token)
const connected = await getConnectionByAccessToken(access_token)
if (!connected){
const notions:any = await getNotionConnection(userId)
const notion = notions[0]
if (!notion) return null
if (!notion.notionDb.channelsDb) return null
if (!notion.notionDb.videosDb) return null
let channelsDbId = notion.notionDb.channelsDb.id
let videosDbId = notion.notionDb.videosDb.id
const youtube:any = await createConnection({type:'Youtube', accessToken: access_token, refreshToken:refresh_token, scopes, userId})
const youtubeChannels = await getChannels(access_token)
const youtubeChannelsDb = await createYoutubeChannnels({apiToken: notion.accessToken, dbId: channelsDbId, channels: youtubeChannels, youtube})
for ( let channel of youtubeChannelsDb){
const youtubeVideos = await getVideos(access_token, channel.uploadId)
const youtubeVideosDb = await createVideos({apiToken: notion.accessToken, dbId: videosDbId, videos: youtubeVideos,channelId:channel.id})
}
return youtube;
}
if (connected) return {success: "Youtube Connection already exists"}
const youtube:any = await createConnection({type:'Youtube', accessToken: access_token, refreshToken:refresh_token, scopes, userId})
if(!youtube) return {error: "Youtube Connection not created successfully"}
return {success: "Youtube Connection created successfully", result: youtube}

}
return null
}

export const getYoutubeConnection = async (userId: string) => {
console.log('User Id', userId)
const connections = await getConnectionsByUserAndType(userId, 'Youtube')
let result:any = []
connections?.forEach((conn: any) => {
Expand All @@ -43,6 +33,48 @@ export const getYoutubeConnection = async (userId: string) => {
return result
}

export const getAndUpdateChannels = async (userId:string,name:string) =>{
const connection = await getConnectionByUserIdAndTypeAndName(userId, 'Youtube', name)
if (!connection) return {error: "Youtube Connection not found"}
const refreshToken = connection.refreshToken
if (!refreshToken) return {error: "Refresh Token not found for this Youtube Connection"}
const accessToken = await getAccessTokenByRefreshToken(refreshToken)
if (!accessToken) return {error: "Access Token not refreshed from Refresh Token of this Youtube Connection"}
const notions:any = await getNotionConnection(userId)
const notion = notions[0]
if (!notion) return {error: "Notion Connection not found"}
if (!notion.notionDb.channelsDb) return {error: "Channels Database not updated in Notion Connection"}
let channelsDbId = notion.notionDb.channelsDb.id
const youtubeChannels = await getChannels(accessToken)
if (!youtubeChannels) return {error: "Youtube Channels not fetched via Youtube data API"}
const youtubeChannelsDb = await createYoutubeChannnels({apiToken: notion.accessToken, dbId: channelsDbId, channels: youtubeChannels, youtubeAccountName:name})
return {success: "Youtube Channels updated in Notion Database", result: youtubeChannelsDb}
}

export const getAndUpdateVideos = async (userId:string,name:string) =>{
const connection = await getConnectionByUserIdAndTypeAndName(userId, 'Youtube', name)
if (!connection) return {error: "Youtube Connection not found"}
const refreshToken = connection.refreshToken
if (!refreshToken) return {error: "Refresh Token not found for this Youtube Connection"}
const accessToken = await getAccessTokenByRefreshToken(refreshToken)
if (!accessToken) return {error: "Access Token not refreshed from Refresh Token of this Youtube Connection"}
const notions:any = await getNotionConnection(userId)
const notion = notions[0]
if (!notion) return {error: "Notion Connection not found"}
if (!notion.notionDb.videosDb) return {error: "Videos Database not updated in Notion Connection"}
let videosDbId = notion.notionDb.videosDb.id
if (!notion.notionDb.channelsDb) return {error: "Channels Database not updated in Notion Connection"}
let channelsDbId = notion.notionDb.channelsDb.id
const channelsDb = await queryAllNotionDatabaseAction({apiToken: notion.accessToken, database_id: channelsDbId})
if (!channelsDb) return {error: "Channels Database not fetched from Notion Connection"}
for (let channel of channelsDb.results){
const youtubeVideos = await getVideos(accessToken, channel.uploadId)
const youtubeVideosDb = await createVideos({apiToken: notion.accessToken, dbId: videosDbId, videos: youtubeVideos,channelId:channel.id})
break
}
return {success: "Youtube Channel Videos updated in Notion Database"}
}

export const getChannels = async (access_token: string): Promise<any[]> => {
const results: any[] = [];
const baseUrl = 'https://www.googleapis.com/youtube/v3';
Expand Down Expand Up @@ -93,7 +125,7 @@ export const getChannels = async (access_token: string): Promise<any[]> => {
}
};

export const createYoutubeChannnels = async ({apiToken, dbId, channels,youtube}:any) => {
export const createYoutubeChannnels = async ({apiToken, dbId, channels,youtubeAccountName}:any) => {
let results:any = []
for (let channel of channels){
let properties:any = [
Expand All @@ -107,7 +139,7 @@ export const createYoutubeChannnels = async ({apiToken, dbId, channels,youtube}:
{name: 'Views', type: 'number', value: Number(channel.totalViews)},
{name: 'uploadId', type: 'text', value: channel.uploadId},
{name: 'Author', type: 'text', value: channel.name},
{name: 'Account', type: 'text', value: youtube.name}
{name: 'Account', type: 'text', value: youtubeAccountName}
]
let result = await createNotionPageAction({apiToken, dbId, properties})
results.push(result)
Expand Down Expand Up @@ -169,11 +201,34 @@ export const createVideos = async ({apiToken, dbId, videos,channelId}:any) => {
{name: 'Platform', type: 'select', value: 'Youtube'},
{name: 'Status', type: 'status', value: 'Not started'},
{name: 'URL', type: 'url', value: `https://www.youtube.com/watch?v=${video.videoId}`},
{name: 'videoId', type: 'text', value: video.videoId},
{name: 'Channel', type: 'text', value: video.channelTitle},
{name: 'Youtube Channels', type: 'relation', value: [channelId]}
]
let result = await createNotionPageAction({apiToken, dbId, properties})
results.push(result)
}
return results
}

const getAccessTokenByRefreshToken = async (refresh_token: string) => {
try{
const url = 'https://oauth2.googleapis.com/token'
const data = {
client_id: process.env.NEXT_PUBLIC_YOUTUBE_CLIENT_ID,
client_secret: process.env.NEXT_PUBLIC_YOUTUBE_CLIENT_SECRET,
refresh_token,
grant_type: 'refresh_token'
}
const response = await axios.post(url, data)
return response.data.access_token
}catch(err){
return null
}
}

export const modifyNotionPageAction = async ({apiToken,page_id,properties}:any) => {
const response = await modifyNotionPage({apiToken,page_id,properties})
console.log('Modify Notion Page Response', response)
return response;
}
4 changes: 2 additions & 2 deletions apps/dashboard-app/actions/notion/notion.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,8 +43,8 @@ export const updateNotionDatabase = async (notionId: string, field:string, value
return notionDb;
}

export const queryNotionDatabaseAction = async ({apiToken,database_id}:any) => {
const response = await queryNotionDatabase({apiToken,database_id, filters: [] })
export const queryNotionDatabaseAction = async ({apiToken,database_id,filters,sorts,cursor}:any) => {
const response = await queryNotionDatabase({apiToken,database_id, filters, sorts,cursor })
return response;
}

Expand Down
31 changes: 25 additions & 6 deletions apps/dashboard-app/app/(dashboard)/connections/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import { getUserInfo } from '../../../actions/connections/user-connections';
import { onNotionConnection } from '../../../actions/connections/notion-connections';
import { onOpenAIConnection } from '../../../actions/connections/openai-connections';
import { onYoutubeConnection } from '../../../actions/connections/youtube-connections';
import { useToast } from '../../../hooks/useToast';

const PlannerPage = () => {
const isMobile = useMedia("(max-width: 1324px)", false);
Expand All @@ -31,6 +32,7 @@ const PlannerPage = () => {
const user = session?.data?.user
const userId = user?.id
const connectionsContext = useContext(ConnectionsContext)
const {toast} = useToast();


const handleSelect = (value:any) => {
Expand All @@ -41,17 +43,34 @@ const PlannerPage = () => {

useEffect(() =>{
const onUserConnection = async () =>{
if (user && access_token){
if (user){
let response;
if (type === 'Notion'){
const notion = await onNotionConnection({access_token,workspace_id,workspace_icon,workspace_name,database_id,userId})
connectionsContext.setNotionNode(notion)
response = await onNotionConnection({access_token,workspace_id,workspace_icon,workspace_name,database_id,userId})
connectionsContext.setNotionNode(response.result)
}
if (type === 'OpenAI'){
const openAI = await onOpenAIConnection({apiKey,userId})
connectionsContext.setOpenAINode(openAI)
response = await onOpenAIConnection({apiKey,userId})
connectionsContext.setOpenAINode(response.result)
}
if (type === 'Youtube'){
const youtube = await onYoutubeConnection({access_token,refresh_token,scopes,userId})
response = await onYoutubeConnection({access_token,refresh_token,scopes,userId})
}
console.log( 'Whait is adfadtafasdfa')
console.log(response)
if (response?.success){
toast({
title: "Success",
description: response?.success,
variant: "default"
})
}
else if (response?.error){
toast({
title: "Error",
description: response?.error,
variant: "destructive"
})
}
const user_info = await getUserInfo(userId || '')

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,6 @@ const Settings = () => {
<DbSelection title='Archive Notion Db' name='Archive' fieldName="archiveDb"/>
<DbSelection title='Interesting Notion Db' name='Interesting' fieldName="interestingDb"/>
<DbSelection title='Podcasts Notion Db' name='Podcasts' fieldName="podcastsDb"/>
<DbSelection title='Channels Notion Db' name='Channels' fieldName="channelsDb"/>
<DbSelection title='Videos Notion Db' name='Videos' fieldName="videosDb"/>
<DbSelection title='Skill Treees Notion Db' name='Skill Trees' fieldName="skillTreesDb"/>
</div>
</div>
Expand Down
20 changes: 20 additions & 0 deletions apps/dashboard-app/app/(dashboard)/youtube/_components/Modal.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import React from 'react';

const Modal = ({ show, onClose, children }:any) => {
if (!show) {
return null;
}

return (
<div className="fixed inset-0 bg-black bg-opacity-80 flex items-center justify-center">
<div className="bg-background rounded-lg p-4 relative">
<button className="absolute top-1 right-1" onClick={onClose}>
X
</button>
{children}
</div>
</div>
);
};

export default Modal;
Loading

0 comments on commit 27991f7

Please sign in to comment.