Skip to content

Commit

Permalink
added youtube channels
Browse files Browse the repository at this point in the history
  • Loading branch information
anoopkarnik committed Jul 22, 2024
1 parent 22825d0 commit f60c008
Show file tree
Hide file tree
Showing 37 changed files with 856 additions and 351 deletions.
18 changes: 8 additions & 10 deletions apps/dashboard-app/actions/connections/notion-connections.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
'use server'

import { createNotion, createNotionDb, getNotionByAccessToken, getNotionByUserId } from '@repo/prisma-db/repo/notion'

import { createConnection, getConnectionByAccessToken, getConnectionsByUser, getConnectionsByUserAndType } from '@repo/prisma-db/repo/connection'
interface notionProps {
access_token: string,
notion_connected: any,
Expand All @@ -11,19 +10,18 @@ interface notionProps {
userId: any
}

export const onNotionConnection = async ({access_token, notion_connected, workspace_id, workspace_icon, workspace_name,
userId}: any) => {
export const onNotionConnection = async ({access_token, workspace_id, workspace_icon, workspace_name, userId}: any) => {
if(access_token){
const notion_connected = await getNotionByAccessToken(access_token)
if (!notion_connected){
const notion = await createNotion({access_token, notion_connected, workspace_id, workspace_icon, workspace_name, userId})
await createNotionDb({notionId: notion.id})
const notion_connected = await getConnectionByAccessToken(access_token)
if (!notion_connected){
const notion = await createConnection({type: 'Notion', userId, accessToken: access_token, workspaceName: workspace_name, workspaceIcon: workspace_icon, workspaceId: workspace_id})
return notion;
}
}

return null
}

export const getNotionConnection = async (userId: string) => {
const connection = await getNotionByUserId(userId)
const connection = await getConnectionsByUserAndType(userId, 'Notion')
return connection
}
13 changes: 5 additions & 8 deletions apps/dashboard-app/actions/connections/openai-connections.tsx
Original file line number Diff line number Diff line change
@@ -1,23 +1,20 @@
'use server'

import { createOpenAI,getOpenAIByAPIKey,getOpenAIByUserId } from '@repo/prisma-db/repo/openAi'
import { createConnection, getConnectionByAPIKey, getConnectionsByUserAndType } from '@repo/prisma-db/repo/connection'

interface Props {
apiKey: string,
userId: string
}

export const onOpenAIConnection = async ({apiKey,userId}:any) => {
if(apiKey){
const openai_connected = await getOpenAIByAPIKey(apiKey)
const openai_connected = await getConnectionByAPIKey(apiKey)
if (!openai_connected){
await createOpenAI({name: 'My OpenAI Key',apiKey,openai_connected, userId})
const openai = await createConnection({apiKey,type:'OpenAI', userId})
return openai;
}
}

}

export const getOpenAIConnection = async (userId: string) => {
const connection = await getOpenAIByUserId(userId)
const connection = await getConnectionsByUserAndType(userId, 'OpenAI')
return connection
}
12 changes: 3 additions & 9 deletions apps/dashboard-app/actions/connections/user-connections.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
'use server'
import { getConnectionByUser} from '@repo/prisma-db/repo/user'

import { updateConnection,deleteConnection, deleteYoutubeConnection, deleteNotionConnection, deleteOpenAIConnection } from '@repo/prisma-db/repo/connection'
import { updateConnection,deleteConnection, deleteNotionDb } from '@repo/prisma-db/repo/connection'
export const getUserInfo = async (userId: string) => {
const user_info:any = await getConnectionByUser(userId);
return user_info;
Expand All @@ -14,14 +14,8 @@ export const updateConnectionById = async (id: string, name: string) => {

export const deleteConnectionById = async (id: string) => {
const conn = await deleteConnection(id);
if (conn.type === 'Youtube') {
await deleteYoutubeConnection(conn.youtubeId as string);
}
else if (conn.type === 'OpenAI') {
await deleteOpenAIConnection(conn.openaiId as string);
}
else if (conn.type === 'Notion') {
await deleteNotionConnection(conn.notionId as string);
if (conn.type === 'Notion') {
await deleteNotionDb(id);
}
return conn;
}
184 changes: 179 additions & 5 deletions apps/dashboard-app/actions/connections/youtube-connections.tsx
Original file line number Diff line number Diff line change
@@ -1,19 +1,193 @@
'use server'

import { createYoutube, getYoutubeByAccessToken, getYoutubeByUserId } from '@repo/prisma-db/repo/youtube'
import { createConnection, getConnectionByAccessToken, getConnectionsByUserAndType } from '@repo/prisma-db/repo/connection'
import axios from 'axios'
import { access } from 'fs'


export const onYoutubeConnection = async ({access_token, refresh_token, scopes, userId}: any) => {
if(access_token){
const connected = await getYoutubeByAccessToken(access_token)
const connected = await getConnectionByAccessToken(access_token)
if (!connected){
const youtube = await createYoutube({name:'My Youtube Account', access_token, refresh_token, scopes, userId})
const results = await GetChannelAndVideoIds(access_token)
const youtube = await createConnection({type:'Youtube', accessToken: access_token, refreshToken:refresh_token, scopes, userId, results})
return youtube;
}
}
return null
}

export const GetChannelAndVideoIds = async (accessToken: string) => {
let nextPageChannelToken = true
let results:any = []
while (nextPageChannelToken){
let channels;
if (nextPageChannelToken === true){
channels = await fetch(`https://www.googleapis.com/youtube/v3/subscriptions?part=snippet&mine=true&maxResults=50`, {
headers: {
Authorization: `Bearer ${accessToken}`
}
})
}
else{
channels = await fetch(`https://www.googleapis.com/youtube/v3/subscriptions?part=snippet&mine=true&maxResults=50&pageToken=${nextPageChannelToken}`, {
headers: {
Authorization: `Bearer ${accessToken}`
}
})
}
const channelsJson = await channels.json()
console.log(channelsJson)
for (let channel of channelsJson.items){
let nextPageToken = true
let channelId = channel.snippet.channelId
while (nextPageToken){
let videos;
if (nextPageToken === true){
videos = await fetch(`https://www.googleapis.com/youtube/v3/search?mine=true&maxResults=50&channelId=${channelId}`, {
headers: {
Authorization: `Bearer ${accessToken}`
}
})
}
else{
videos = await fetch(`https://www.googleapis.com/youtube/v3/searchh?channelId=${channelId}&mine=true&maxResults=50&pageToken=${nextPageToken}`, {
headers: {
Authorization: `Bearer ${accessToken}`
}
})
}
const videosJson = await videos.json()
console.log(videosJson)
for (let video of videosJson.items){
await results.push({channelId: channelId, videoId: video.id})
}
if (videosJson.nextPageToken){
nextPageToken = videosJson.nextPageToken
}
else{
break
}
}
}


if (channelsJson.nextPageToken){
nextPageChannelToken = channelsJson.nextPageToken
}
else{
break
}
}
return results;
}


export const getYoutubeConnection = async (userId: string) => {
const connection = await getYoutubeByUserId(userId)
return connection
const connections = await getConnectionsByUserAndType(userId, 'Youtube')
let result:any = []
connections?.forEach((conn: any) => {
result.push({id: conn.id, name: conn.name, icon: '',access_token: conn.accessToken, refresh_token: conn.refreshToken, scopes: conn.scopes})
})
return result
}

export const getChannels = async (userId: string, selectedAccount: string) => {
const connections = await getConnectionsByUserAndType(userId, 'Youtube')
const clientId = process.env.NEXT_PUBLIC_YOUTUBE_CLIENT_ID
const clientSecret = process.env.NEXT_PUBLIC_YOUTUBE_CLIENT_SECRET
if (!connections || connections.length === 0) return []
let account = connections.find((conn: any) => conn.name === selectedAccount)
const refreshToken = account?.refreshToken
const response = await axios.post(`https://oauth2.googleapis.com/token`,null, {
params:{
client_id: clientId,
client_secret: clientSecret,
refresh_token: refreshToken,
grant_type: 'refresh_token'
}
})
console.log(response.data)
let accessToken = response.data.access_token
let nextPageToken = true
let results:any = []
while (nextPageToken){
let channels;
if (nextPageToken === true){
channels = await fetch(`https://www.googleapis.com/youtube/v3/subscriptions?part=snippet&mine=true&maxResults=50`, {
headers: {
Authorization: `Bearer ${accessToken}`
}
})
}
else{
channels = await fetch(`https://www.googleapis.com/youtube/v3/subscriptions?part=snippet&mine=true&maxResults=50&pageToken=${nextPageToken}`, {
headers: {
Authorization: `Bearer ${accessToken}`
}
})
}
const channelsJson = await channels.json()
for (let channel of channelsJson.items){
await results.push({id: channel.id, name: channel.snippet.title, description: channel.snippet.description,
imageId: channel.snippet.thumbnails.high.url, channelId: channel.snippet.channelId})
}
if (channelsJson.nextPageToken){
nextPageToken = channelsJson.nextPageToken
}
else{
break
}
}
return results
}

export const getVideosByChannel = async (userId: string, channelId: string) => {
const connections = await getConnectionsByUserAndType(userId, 'Youtube')
const clientId = process.env.NEXT_PUBLIC_YOUTUBE_CLIENT_ID
const clientSecret = process.env.NEXT_PUBLIC_YOUTUBE_CLIENT_SECRET
if (!connections || connections.length === 0) return []
let account = connections[0]
const refreshToken = account?.refreshToken
const response = await axios.post(`https://oauth2.googleapis.com/token`,null, {
params:{
client_id: clientId,
client_secret: clientSecret,
refresh_token: refreshToken,
grant_type: 'refresh_token'
}
})
console.log(response.data)
let accessToken = response.data.access_token
let nextPageToken = true
let results:any = []
while (nextPageToken){
let videos;
if (nextPageToken === true){
videos = await fetch(`https://www.googleapis.com/youtube/v3/search?part=snippet&channelId=${channelId}&type=video&maxResults=50`, {
headers: {
Authorization: `Bearer ${accessToken}`
}
})
}
else{
videos = await fetch(`https://www.googleapis.com/youtube/v3/search?part=snippet&channelId=${channelId}&type=video&maxResults=50&pageToken=${nextPageToken}`, {
headers: {
Authorization: `Bearer ${accessToken}`
}
})
}
const videosJson = await videos.json()
for (let video of videosJson.items){
await results.push({id: video.id.videoId, title: video.snippet.title, description: video.snippet.description,
imageId: video.snippet.thumbnails.high.url})
}
if (videosJson.nextPageToken){
nextPageToken = videosJson.nextPageToken
}
else{
break
}
}
return results
}
48 changes: 30 additions & 18 deletions apps/dashboard-app/actions/notion/notion.ts
Original file line number Diff line number Diff line change
@@ -1,33 +1,45 @@
'use server'
import { getNotionByUserId, updateNotionDb} from "@repo/prisma-db/repo/notion";
import { getConnectionsByUserAndType, updateNotionDb} from "@repo/prisma-db/repo/connection";
import { getNotionDatabaseProperties, queryAllNotionDatabase, queryNotionDatabase } from '@repo/notion/notion-client'
import { format } from "date-fns";

export const getDatabases = async (token: string) => {
const response = await fetch('https://api.notion.com/v1/search', {
method: 'POST',
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json',
'Notion-Version': '2022-02-22'
},
body: JSON.stringify({
filter: {
value: 'database',
property: 'object'
}
try{
const response = await fetch('https://api.notion.com/v1/search', {
method: 'POST',
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json',
'Notion-Version': '2022-02-22'
},
body: JSON.stringify({
filter: {
value: 'database',
property: 'object'
}
})
});
const data = await response.json();
const results:any = [];
data?.results.forEach((conn: any) => {
results.push({id: conn.id, name: conn?.title?.[0]?.text?.content, icon: conn?.icon?.emoji})
})
});
const data = await response.json();
return data.results;
return results
}
catch(err){
console.log(err)
}

}

export const getNotionInfo = async (userId: string) => {
const notion_info = await getNotionByUserId(userId)
return notion_info;
const notion_info = await getConnectionsByUserAndType(userId, 'Notion');
return notion_info?.[0];
}

export const updateNotionDatabase = async (notionId: string, field:string, value: any) => {

console.log('Update Notion Database', notionId, field, value)
const notionDb = await updateNotionDb({id:notionId, field, value} );
return notionDb;
}
Expand Down
2 changes: 1 addition & 1 deletion apps/dashboard-app/actions/workflows/workflow.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ export const getNodes = async (workflowId:string) => {
}

export const addNodeToWorkflow = async ({name,description,workflowId,type,userId,actionType,subActionType,actionData}:any) => {
console.log('Adding node to workflow',name,description,workflowId,type,userId,actionType,subActionType,actionData);
logger.info('Adding node to workflow',name,description,workflowId,type,userId,actionType,subActionType,actionData);
const node:any = await createNode({name,description,workflowId,type,userId,actionType,subActionType,actionData});
return node;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,13 @@ const Connected = () => {
if (session?.data?.user?.id) {
const userInfo = await getUserInfo(session.data.user.id);
const newConnections: any = [];
if (!userInfo) {
return;
}
for (let connection of userInfo?.connections) {
const cons = CONNECTIONS.find((con) => con.title === connection.type);
if (cons) {
const newConnection = { ...cons, ...connection };
console.log()
if (!connections.some((conn:any) => conn.id === newConnection.id)) {
newConnections.push(newConnection);
}
Expand Down
Loading

0 comments on commit f60c008

Please sign in to comment.