mirror of
https://github.com/ItzCrazyKns/Perplexica.git
synced 2025-04-30 00:02:44 +00:00
Compare commits
12 Commits
6f69f6b539
...
master
Author | SHA1 | Date | |
---|---|---|---|
|
68e151b2bd | ||
|
06ff272541 | ||
|
4154d5e4b1 | ||
|
1862491496 | ||
|
073b5e897c | ||
|
9a332e79e4 | ||
|
72450b9217 | ||
|
7e1dc33a08 | ||
|
aa240009ab | ||
|
41b258e4d8 | ||
|
28b9cca413 | ||
|
8aaee2c40c |
17
README.md
17
README.md
@ -1,21 +1,5 @@
|
||||
# 🚀 Perplexica - An AI-powered search engine 🔎 <!-- omit in toc -->
|
||||
|
||||
<div align="center" markdown="1">
|
||||
<sup>Special thanks to:</sup>
|
||||
<br>
|
||||
<br>
|
||||
<a href="https://www.warp.dev/perplexica">
|
||||
<img alt="Warp sponsorship" width="400" src="https://github.com/user-attachments/assets/775dd593-9b5f-40f1-bf48-479faff4c27b">
|
||||
</a>
|
||||
|
||||
### [Warp, the AI Devtool that lives in your terminal](https://www.warp.dev/perplexica)
|
||||
|
||||
[Available for MacOS, Linux, & Windows](https://www.warp.dev/perplexica)
|
||||
|
||||
</div>
|
||||
|
||||
<hr/>
|
||||
|
||||
[](https://discord.gg/26aArMy8tT)
|
||||
|
||||

|
||||
@ -159,6 +143,7 @@ Perplexica runs on Next.js and handles all API requests. It works right away on
|
||||
|
||||
[](https://usw.sealos.io/?openapp=system-template%3FtemplateName%3Dperplexica)
|
||||
[](https://repocloud.io/details/?app_id=267)
|
||||
[](https://template.run.claw.cloud/?referralCode=U11MRQ8U9RM4&openapp=system-fastdeploy%3FtemplateName%3Dperplexica)
|
||||
|
||||
## Upcoming Features
|
||||
|
||||
|
@ -8,6 +8,7 @@ import {
|
||||
getOllamaApiEndpoint,
|
||||
getOpenaiApiKey,
|
||||
getDeepseekApiKey,
|
||||
getLMStudioApiEndpoint,
|
||||
updateConfig,
|
||||
} from '@/lib/config';
|
||||
import {
|
||||
@ -51,6 +52,7 @@ export const GET = async (req: Request) => {
|
||||
|
||||
config['openaiApiKey'] = getOpenaiApiKey();
|
||||
config['ollamaApiUrl'] = getOllamaApiEndpoint();
|
||||
config['lmStudioApiUrl'] = getLMStudioApiEndpoint();
|
||||
config['anthropicApiKey'] = getAnthropicApiKey();
|
||||
config['groqApiKey'] = getGroqApiKey();
|
||||
config['geminiApiKey'] = getGeminiApiKey();
|
||||
@ -93,6 +95,9 @@ export const POST = async (req: Request) => {
|
||||
DEEPSEEK: {
|
||||
API_KEY: config.deepseekApiKey,
|
||||
},
|
||||
LM_STUDIO: {
|
||||
API_URL: config.lmStudioApiUrl,
|
||||
},
|
||||
CUSTOM_OPENAI: {
|
||||
API_URL: config.customOpenaiApiUrl,
|
||||
API_KEY: config.customOpenaiApiKey,
|
||||
|
@ -1,124 +0,0 @@
|
||||
/**
|
||||
* Default categories and functions for generating search queries
|
||||
*/
|
||||
|
||||
import { LANGUAGE_SPECIFIC_SOURCES } from './languages';
|
||||
|
||||
/**
|
||||
* Default English categories and their sources
|
||||
*/
|
||||
export const DEFAULT_CATEGORIES: Record<string, { site: string; keyword: string }[]> = {
|
||||
'Technology': [
|
||||
{ site: 'techcrunch.com', keyword: 'tech' },
|
||||
{ site: 'wired.com', keyword: 'technology' },
|
||||
{ site: 'theverge.com', keyword: 'tech' },
|
||||
{ site: 'arstechnica.com', keyword: 'technology' },
|
||||
{ site: 'thenextweb.com', keyword: 'tech' }
|
||||
],
|
||||
'AI': [
|
||||
{ site: 'ai.googleblog.com', keyword: 'AI' },
|
||||
{ site: 'openai.com/blog', keyword: 'AI' },
|
||||
{ site: 'venturebeat.com', keyword: 'artificial intelligence' },
|
||||
{ site: 'techcrunch.com', keyword: 'artificial intelligence' },
|
||||
{ site: 'technologyreview.mit.edu', keyword: 'AI' }
|
||||
],
|
||||
'Sports': [
|
||||
{ site: 'espn.com', keyword: 'sports' },
|
||||
{ site: 'sports.yahoo.com', keyword: 'sports' },
|
||||
{ site: 'cbssports.com', keyword: 'sports' },
|
||||
{ site: 'si.com', keyword: 'sports' },
|
||||
{ site: 'bleacherreport.com', keyword: 'sports' }
|
||||
],
|
||||
'Money': [
|
||||
{ site: 'bloomberg.com', keyword: 'finance' },
|
||||
{ site: 'cnbc.com', keyword: 'money' },
|
||||
{ site: 'wsj.com', keyword: 'finance' },
|
||||
{ site: 'ft.com', keyword: 'finance' },
|
||||
{ site: 'economist.com', keyword: 'economy' }
|
||||
],
|
||||
'Gaming': [
|
||||
{ site: 'ign.com', keyword: 'games' },
|
||||
{ site: 'gamespot.com', keyword: 'gaming' },
|
||||
{ site: 'polygon.com', keyword: 'games' },
|
||||
{ site: 'kotaku.com', keyword: 'gaming' },
|
||||
{ site: 'eurogamer.net', keyword: 'games' }
|
||||
],
|
||||
'Entertainment': [
|
||||
{ site: 'variety.com', keyword: 'entertainment' },
|
||||
{ site: 'hollywoodreporter.com', keyword: 'entertainment' },
|
||||
{ site: 'ew.com', keyword: 'entertainment' },
|
||||
{ site: 'deadline.com', keyword: 'entertainment' },
|
||||
{ site: 'rollingstone.com', keyword: 'entertainment' }
|
||||
],
|
||||
'Art and Culture': [
|
||||
{ site: 'artnews.com', keyword: 'art' },
|
||||
{ site: 'artsy.net', keyword: 'art' },
|
||||
{ site: 'theartnewspaper.com', keyword: 'art' },
|
||||
{ site: 'nytimes.com/section/arts', keyword: 'culture' },
|
||||
{ site: 'culturalweekly.com', keyword: 'culture' }
|
||||
],
|
||||
'Science': [
|
||||
{ site: 'scientificamerican.com', keyword: 'science' },
|
||||
{ site: 'nature.com', keyword: 'science' },
|
||||
{ site: 'science.org', keyword: 'science' },
|
||||
{ site: 'newscientist.com', keyword: 'science' },
|
||||
{ site: 'popsci.com', keyword: 'science' }
|
||||
],
|
||||
'Health': [
|
||||
{ site: 'webmd.com', keyword: 'health' },
|
||||
{ site: 'health.harvard.edu', keyword: 'health' },
|
||||
{ site: 'mayoclinic.org', keyword: 'health' },
|
||||
{ site: 'nih.gov', keyword: 'health' },
|
||||
{ site: 'medicalnewstoday.com', keyword: 'health' }
|
||||
],
|
||||
'Travel': [
|
||||
{ site: 'travelandleisure.com', keyword: 'travel' },
|
||||
{ site: 'lonelyplanet.com', keyword: 'travel' },
|
||||
{ site: 'tripadvisor.com', keyword: 'travel' },
|
||||
{ site: 'nationalgeographic.com', keyword: 'travel' },
|
||||
{ site: 'cntraveler.com', keyword: 'travel' }
|
||||
],
|
||||
'Current News': [
|
||||
{ site: 'reuters.com', keyword: 'news' },
|
||||
{ site: 'apnews.com', keyword: 'news' },
|
||||
{ site: 'bbc.com', keyword: 'news' },
|
||||
{ site: 'npr.org', keyword: 'news' },
|
||||
{ site: 'aljazeera.com', keyword: 'news' }
|
||||
]
|
||||
};
|
||||
|
||||
/**
|
||||
* Helper function to get search queries for a category
|
||||
* Prioritizes language-specific sources if available
|
||||
*/
|
||||
export function getSearchQueriesForCategory(category: string, language?: string): { site: string; keyword: string }[] {
|
||||
// Check if we have language-specific sources for this language and category
|
||||
if (language &&
|
||||
LANGUAGE_SPECIFIC_SOURCES[language] &&
|
||||
LANGUAGE_SPECIFIC_SOURCES[language][category]) {
|
||||
return LANGUAGE_SPECIFIC_SOURCES[language][category];
|
||||
}
|
||||
|
||||
// For Chinese variants, try the general zh sources
|
||||
if (language &&
|
||||
(language.startsWith('zh') || language.includes('Hans') || language.includes('Hant')) &&
|
||||
LANGUAGE_SPECIFIC_SOURCES['zh'] &&
|
||||
LANGUAGE_SPECIFIC_SOURCES['zh'][category]) {
|
||||
return LANGUAGE_SPECIFIC_SOURCES['zh'][category];
|
||||
}
|
||||
|
||||
// If no language-specific sources, use the default English sources
|
||||
return DEFAULT_CATEGORIES[category] || DEFAULT_CATEGORIES['Technology'];
|
||||
}
|
||||
|
||||
/**
|
||||
* Default high-quality sources for the default view
|
||||
*/
|
||||
export const DEFAULT_SOURCES = [
|
||||
{ site: 'techcrunch.com', keyword: 'tech' },
|
||||
{ site: 'wired.com', keyword: 'technology' },
|
||||
{ site: 'theverge.com', keyword: 'tech' },
|
||||
{ site: 'venturebeat.com', keyword: 'artificial intelligence' },
|
||||
{ site: 'technologyreview.mit.edu', keyword: 'AI' },
|
||||
{ site: 'ai.googleblog.com', keyword: 'AI' }
|
||||
];
|
File diff suppressed because it is too large
Load Diff
@ -1,128 +0,0 @@
|
||||
import db from "@/lib/db";
|
||||
import { userPreferences } from "@/lib/db/schema";
|
||||
import { eq } from "drizzle-orm";
|
||||
|
||||
// GET handler to retrieve user preferences
|
||||
export const GET = async (req: Request) => {
|
||||
try {
|
||||
console.log('[Preferences] Retrieving user preferences');
|
||||
|
||||
// In a production app, you would get user ID from an auth session
|
||||
const url = new URL(req.url);
|
||||
const userId = url.searchParams.get('userId') || "default-user";
|
||||
|
||||
console.log(`[Preferences] Fetching preferences for user: ${userId}`);
|
||||
|
||||
const userPrefs = await db.select().from(userPreferences).where(eq(userPreferences.userId, userId));
|
||||
|
||||
if (userPrefs.length === 0) {
|
||||
console.log('[Preferences] No preferences found, returning defaults');
|
||||
// Return default preferences if none exist
|
||||
return Response.json({
|
||||
categories: ['AI', 'Technology'],
|
||||
languages: ['en'] // Default to English
|
||||
});
|
||||
}
|
||||
|
||||
// Handle backward compatibility for old schema versions
|
||||
let languages = [];
|
||||
if ('languages' in userPrefs[0] && userPrefs[0].languages) {
|
||||
languages = userPrefs[0].languages;
|
||||
} else if ('language' in userPrefs[0] && userPrefs[0].language) {
|
||||
// Convert old single language to array for backward compatibility
|
||||
languages = Array.isArray(userPrefs[0].language)
|
||||
? userPrefs[0].language
|
||||
: [userPrefs[0].language];
|
||||
} else {
|
||||
languages = ['en']; // Default to English if no language preference found
|
||||
}
|
||||
|
||||
console.log(`[Preferences] Found user preferences: categories=${JSON.stringify(userPrefs[0].categories)}, languages=${JSON.stringify(languages)}`);
|
||||
|
||||
return Response.json({
|
||||
categories: userPrefs[0].categories,
|
||||
languages: languages
|
||||
});
|
||||
} catch (err: any) {
|
||||
console.error(`[Preferences] Error getting user preferences: ${err instanceof Error ? err.message : String(err)}`);
|
||||
console.error(`[Preferences] Error stack: ${err instanceof Error ? err.stack : 'No stack trace available'}`);
|
||||
return Response.json(
|
||||
{ message: 'An error has occurred' },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
// POST handler to save user preferences
|
||||
export const POST = async (req: Request) => {
|
||||
try {
|
||||
console.log('[Preferences] Updating user preferences');
|
||||
|
||||
// In a production app, you would get user ID from an auth session
|
||||
const url = new URL(req.url);
|
||||
const userId = url.searchParams.get('userId') || "default-user";
|
||||
|
||||
const body = await req.json();
|
||||
const { categories, languages } = body;
|
||||
|
||||
console.log(`[Preferences] Received update: userId=${userId}, categories=${JSON.stringify(categories)}, languages=${JSON.stringify(languages)}`);
|
||||
|
||||
if (!categories || !Array.isArray(categories)) {
|
||||
console.error('[Preferences] Invalid categories format');
|
||||
return Response.json(
|
||||
{ message: 'Invalid categories format' },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
if (languages && !Array.isArray(languages)) {
|
||||
console.error('[Preferences] Invalid languages format');
|
||||
return Response.json(
|
||||
{ message: 'Invalid languages format' },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
const userPrefs = await db.select().from(userPreferences).where(eq(userPreferences.userId, userId));
|
||||
|
||||
try {
|
||||
if (userPrefs.length === 0) {
|
||||
// Create new preferences
|
||||
console.log(`[Preferences] Creating new preferences for user: ${userId}`);
|
||||
await db.insert(userPreferences).values({
|
||||
userId,
|
||||
categories,
|
||||
languages: languages || ['en'],
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
});
|
||||
} else {
|
||||
// Update existing preferences
|
||||
console.log(`[Preferences] Updating existing preferences for user: ${userId}`);
|
||||
await db.update(userPreferences)
|
||||
.set({
|
||||
categories,
|
||||
languages: languages || ['en'],
|
||||
updatedAt: new Date().toISOString()
|
||||
})
|
||||
.where(eq(userPreferences.userId, userId));
|
||||
}
|
||||
|
||||
console.log(`[Preferences] Successfully updated preferences for user: ${userId}`);
|
||||
} catch (error: any) {
|
||||
// If there's an error (likely due to schema mismatch), log it but don't fail
|
||||
console.warn(`[Preferences] Error updating preferences with new schema: ${error instanceof Error ? error.message : String(error)}`);
|
||||
console.warn('[Preferences] Continuing with request despite error');
|
||||
// We'll just return success anyway since we can't fix the schema issue here
|
||||
}
|
||||
|
||||
return Response.json({ message: 'Preferences updated successfully' });
|
||||
} catch (err: any) {
|
||||
console.error(`[Preferences] Error updating user preferences: ${err instanceof Error ? err.message : String(err)}`);
|
||||
console.error(`[Preferences] Error stack: ${err instanceof Error ? err.stack : 'No stack trace available'}`);
|
||||
return Response.json(
|
||||
{ message: 'An error has occurred' },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
};
|
@ -1,83 +1,54 @@
|
||||
import { getSearchQueriesForCategory, DEFAULT_SOURCES } from './categories';
|
||||
import { searchCategory, getDefaultResults, processResults } from './search';
|
||||
import { searchSearxng } from '@/lib/searxng';
|
||||
|
||||
const articleWebsites = [
|
||||
'yahoo.com',
|
||||
'www.exchangewire.com',
|
||||
'businessinsider.com',
|
||||
/* 'wired.com',
|
||||
'mashable.com',
|
||||
'theverge.com',
|
||||
'gizmodo.com',
|
||||
'cnet.com',
|
||||
'venturebeat.com', */
|
||||
];
|
||||
|
||||
const topics = ['AI', 'tech']; /* TODO: Add UI to customize this */
|
||||
|
||||
export const GET = async (req: Request) => {
|
||||
try {
|
||||
const url = new URL(req.url);
|
||||
const category = url.searchParams.get('category');
|
||||
const preferencesParam = url.searchParams.get('preferences');
|
||||
const languagesParam = url.searchParams.get('languages');
|
||||
|
||||
console.log(`[Discover] Request received: category=${category}, preferences=${preferencesParam}, languages=${languagesParam}`);
|
||||
|
||||
let data: any[] = [];
|
||||
let languages: string[] = [];
|
||||
|
||||
// Parse languages parameter
|
||||
if (languagesParam) {
|
||||
try {
|
||||
const parsedLanguages = JSON.parse(languagesParam);
|
||||
if (Array.isArray(parsedLanguages)) {
|
||||
languages = parsedLanguages;
|
||||
}
|
||||
} catch (err) {
|
||||
console.error(`[Discover] Error parsing languages: ${err instanceof Error ? err.message : String(err)}`);
|
||||
}
|
||||
}
|
||||
|
||||
console.log(`[Discover] Using languages: ${JSON.stringify(languages)}`);
|
||||
|
||||
// Handle category-specific searches
|
||||
if (category && category !== 'For You') {
|
||||
console.log(`[Discover] Searching for category: ${category}`);
|
||||
data = await searchCategory(category, languages, getSearchQueriesForCategory);
|
||||
}
|
||||
// Handle preference-based searches
|
||||
else if (preferencesParam) {
|
||||
try {
|
||||
const preferences = JSON.parse(preferencesParam);
|
||||
if (Array.isArray(preferences) && preferences.length > 0) {
|
||||
console.log(`[Discover] Searching for preferences: ${JSON.stringify(preferences)}`);
|
||||
// Get content for each preferred category
|
||||
const categoryPromises = preferences.map((pref: string) =>
|
||||
searchCategory(pref, languages, getSearchQueriesForCategory)
|
||||
);
|
||||
const results = await Promise.all(categoryPromises);
|
||||
data = results.flat();
|
||||
} else {
|
||||
console.log(`[Discover] No valid preferences found, using default search`);
|
||||
// Fallback to default behavior
|
||||
data = await getDefaultResults(languages, DEFAULT_SOURCES);
|
||||
}
|
||||
} catch (err) {
|
||||
console.error(`[Discover] Error with preferences: ${err instanceof Error ? err.message : String(err)}`);
|
||||
data = await getDefaultResults(languages, DEFAULT_SOURCES);
|
||||
}
|
||||
}
|
||||
// Default search behavior
|
||||
else {
|
||||
console.log(`[Discover] Using default search`);
|
||||
data = await getDefaultResults(languages, DEFAULT_SOURCES);
|
||||
}
|
||||
|
||||
console.log(`[Discover] Found ${data.length} results before filtering`);
|
||||
|
||||
// Process and filter results for display
|
||||
const finalData = processResults(data);
|
||||
|
||||
console.log(`[Discover] Found ${finalData.length} results after filtering`);
|
||||
const data = (
|
||||
await Promise.all([
|
||||
...new Array(articleWebsites.length * topics.length)
|
||||
.fill(0)
|
||||
.map(async (_, i) => {
|
||||
return (
|
||||
await searchSearxng(
|
||||
`site:${articleWebsites[i % articleWebsites.length]} ${
|
||||
topics[i % topics.length]
|
||||
}`,
|
||||
{
|
||||
engines: ['bing news'],
|
||||
pageno: 1,
|
||||
},
|
||||
)
|
||||
).results;
|
||||
}),
|
||||
])
|
||||
)
|
||||
.map((result) => result)
|
||||
.flat()
|
||||
.sort(() => Math.random() - 0.5);
|
||||
|
||||
return Response.json(
|
||||
{
|
||||
blogs: finalData,
|
||||
blogs: data,
|
||||
},
|
||||
{
|
||||
status: 200,
|
||||
},
|
||||
);
|
||||
} catch (err) {
|
||||
console.error(`[Discover] An error occurred in discover route: ${err instanceof Error ? err.message : String(err)}`);
|
||||
console.error(`[Discover] Error stack: ${err instanceof Error ? err.stack : 'No stack trace available'}`);
|
||||
console.error(`An error occurred in discover route: ${err}`);
|
||||
return Response.json(
|
||||
{
|
||||
message: 'An error has occurred',
|
||||
|
@ -1,173 +0,0 @@
|
||||
import { searchSearxng } from '@/lib/searxng';
|
||||
import { LANGUAGE_SPECIFIC_ENGINES } from './languages';
|
||||
|
||||
// Define the search options interface to match the one in lib/searxng.ts
|
||||
interface SearxngSearchOptions {
|
||||
categories?: string[];
|
||||
engines?: string[];
|
||||
language?: string;
|
||||
pageno?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Default search engines to use, in priority order
|
||||
*/
|
||||
export const DEFAULT_ENGINES = ['bing news', 'brave news', 'duckduckgo news'];
|
||||
|
||||
/**
|
||||
* Search with multiple engines as fallbacks
|
||||
* Tries each engine in sequence until results are found or engines exhausted
|
||||
*/
|
||||
export async function searchWithMultipleEngines(
|
||||
query: string,
|
||||
language: string,
|
||||
engines: string[] = DEFAULT_ENGINES
|
||||
): Promise<any[]> {
|
||||
let allResults: any[] = [];
|
||||
let hasResults = false;
|
||||
|
||||
// Try each engine in sequence until we get results or run out of engines
|
||||
for (const engine of engines) {
|
||||
try {
|
||||
console.log(`[Discover] Trying engine "${engine}" for query "${query}" in language "${language || 'default'}"`);
|
||||
|
||||
const searchOptions: SearxngSearchOptions = {
|
||||
engines: [engine],
|
||||
pageno: 1,
|
||||
};
|
||||
|
||||
if (language) {
|
||||
searchOptions.language = language;
|
||||
}
|
||||
|
||||
const result = await searchSearxng(query, searchOptions);
|
||||
|
||||
if (result.results && result.results.length > 0) {
|
||||
console.log(`[Discover] Found ${result.results.length} results from engine "${engine}"`);
|
||||
allResults.push(...result.results);
|
||||
hasResults = true;
|
||||
|
||||
// If we've found enough results, stop trying more engines
|
||||
if (allResults.length >= 20) {
|
||||
break;
|
||||
}
|
||||
} else {
|
||||
console.log(`[Discover] No results from engine "${engine}", trying next engine if available`);
|
||||
}
|
||||
} catch (err) {
|
||||
console.error(`[Discover] Error searching with engine "${engine}": ${err instanceof Error ? err.message : String(err)}`);
|
||||
}
|
||||
}
|
||||
|
||||
return allResults;
|
||||
}
|
||||
|
||||
/**
|
||||
* Search for a specific category across multiple languages and engines
|
||||
*/
|
||||
export async function searchCategory(
|
||||
category: string,
|
||||
languages: string[] = [],
|
||||
getQueries: (cat: string, lang?: string) => { site: string; keyword: string }[]
|
||||
): Promise<any[]> {
|
||||
console.log(`[Discover] Searching category "${category}" in languages: ${JSON.stringify(languages)}`);
|
||||
|
||||
// If no languages specified or empty array, search in English
|
||||
if (!languages || languages.length === 0) {
|
||||
const queries = getQueries(category);
|
||||
const searchPromises = queries.map(query =>
|
||||
searchWithMultipleEngines(`site:${query.site} ${query.keyword}`, '')
|
||||
);
|
||||
|
||||
const results = await Promise.all(searchPromises);
|
||||
return results.flat();
|
||||
}
|
||||
|
||||
// If languages specified, search each language and combine results
|
||||
const allResults = [];
|
||||
|
||||
for (const language of languages) {
|
||||
console.log(`[Discover] Searching in language: ${language}`);
|
||||
|
||||
// Get language-specific engines if available, otherwise use defaults
|
||||
const engines = LANGUAGE_SPECIFIC_ENGINES[language] || DEFAULT_ENGINES;
|
||||
|
||||
// Get language-specific queries
|
||||
const queries = getQueries(category, language);
|
||||
|
||||
const searchPromises = queries.map(query => {
|
||||
// For Chinese languages, don't use the site: operator
|
||||
const isChinese = language.startsWith('zh');
|
||||
const queryString = isChinese ? query.keyword : `site:${query.site} ${query.keyword}`;
|
||||
return searchWithMultipleEngines(queryString, language, engines);
|
||||
});
|
||||
|
||||
const results = await Promise.all(searchPromises);
|
||||
allResults.push(...results.flat());
|
||||
}
|
||||
|
||||
return allResults;
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper function for default search behavior that supports multiple languages
|
||||
*/
|
||||
export async function getDefaultResults(
|
||||
languages: string[] = [],
|
||||
defaultSources: { site: string; keyword: string }[]
|
||||
): Promise<any[]> {
|
||||
console.log(`[Discover] Getting default results for languages: ${JSON.stringify(languages)}`);
|
||||
|
||||
// If no languages specified, search with no language filter
|
||||
if (languages.length === 0) {
|
||||
const searchPromises = defaultSources.map(query =>
|
||||
searchWithMultipleEngines(`site:${query.site} ${query.keyword}`, '')
|
||||
);
|
||||
|
||||
const results = await Promise.all(searchPromises);
|
||||
return results.flat();
|
||||
}
|
||||
|
||||
// Otherwise, search each language separately and combine results
|
||||
let allResults: any[] = [];
|
||||
|
||||
for (const language of languages) {
|
||||
console.log(`[Discover] Default search in language: ${language}`);
|
||||
|
||||
// Get language-specific engines if available, otherwise use defaults
|
||||
const engines = LANGUAGE_SPECIFIC_ENGINES[language] || DEFAULT_ENGINES;
|
||||
|
||||
const searchPromises = defaultSources.map(query => {
|
||||
// For Chinese languages, don't use the site: operator
|
||||
const isChinese = language.startsWith('zh');
|
||||
const queryString = isChinese ? query.keyword : `site:${query.site} ${query.keyword}`;
|
||||
return searchWithMultipleEngines(queryString, language, engines);
|
||||
});
|
||||
|
||||
const results = await Promise.all(searchPromises);
|
||||
allResults.push(...results.flat());
|
||||
}
|
||||
|
||||
return allResults;
|
||||
}
|
||||
|
||||
/**
|
||||
* Process results to filter and prepare for display
|
||||
*/
|
||||
export function processResults(results: any[]): any[] {
|
||||
// Filter out items without thumbnails
|
||||
const resultsWithThumbnails = results.filter((item) => item.thumbnail);
|
||||
|
||||
// If there are no results with thumbnails but we have results without thumbnails,
|
||||
// use some of the results without thumbnails rather than showing nothing
|
||||
let finalResults = resultsWithThumbnails;
|
||||
if (resultsWithThumbnails.length === 0 && results.length > 0) {
|
||||
console.log(`[Discover] No results with thumbnails found, using up to 10 results without thumbnails`);
|
||||
finalResults = results.slice(0, 10); // Limit to 10 results without thumbnails
|
||||
} else {
|
||||
finalResults = resultsWithThumbnails;
|
||||
}
|
||||
|
||||
// Shuffle the results
|
||||
return finalResults.sort(() => Math.random() - 0.5);
|
||||
}
|
@ -1,7 +1,7 @@
|
||||
'use client';
|
||||
|
||||
import { Search, Sliders, ChevronLeft, ChevronRight } from 'lucide-react';
|
||||
import { useEffect, useState, useRef, memo, useMemo } from 'react';
|
||||
import { Search } from 'lucide-react';
|
||||
import { useEffect, useState } from 'react';
|
||||
import Link from 'next/link';
|
||||
import { toast } from 'sonner';
|
||||
|
||||
@ -12,165 +12,14 @@ interface Discover {
|
||||
thumbnail: string;
|
||||
}
|
||||
|
||||
const categories = [
|
||||
'For You', 'AI', 'Technology', 'Current News', 'Sports',
|
||||
'Money', 'Gaming', 'Entertainment', 'Art and Culture',
|
||||
'Science', 'Health', 'Travel'
|
||||
];
|
||||
|
||||
// Header component with categories
|
||||
const DiscoverHeader = memo(({
|
||||
activeCategory,
|
||||
setActiveCategory,
|
||||
setShowPreferences,
|
||||
userPreferences
|
||||
}: {
|
||||
activeCategory: string;
|
||||
setActiveCategory: (category: string) => void;
|
||||
setShowPreferences: (show: boolean) => void;
|
||||
userPreferences: string[];
|
||||
}) => {
|
||||
const categoryContainerRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
// Filter categories to show only what the user has selected in preferences
|
||||
// Always include "For You" and the currently active category if it's not in preferences
|
||||
const visibleCategories = useMemo(() => {
|
||||
// Always start with "For You"
|
||||
const filtered = ['For You'];
|
||||
|
||||
// Add user's preferred categories
|
||||
userPreferences.forEach(category => {
|
||||
if (!filtered.includes(category)) {
|
||||
filtered.push(category);
|
||||
}
|
||||
});
|
||||
|
||||
// Add active category if it's not already included
|
||||
if (activeCategory && !filtered.includes(activeCategory)) {
|
||||
filtered.push(activeCategory);
|
||||
}
|
||||
|
||||
// If user has no preferences, show a limited default set
|
||||
if (filtered.length <= 1) {
|
||||
return ['For You', 'AI', 'Technology', 'Current News'];
|
||||
}
|
||||
|
||||
return filtered;
|
||||
}, [userPreferences, activeCategory]);
|
||||
|
||||
const scrollCategories = (direction: 'left' | 'right') => {
|
||||
const container = categoryContainerRef.current;
|
||||
if (!container) return;
|
||||
|
||||
const scrollAmount = container.clientWidth * 0.8;
|
||||
const currentScroll = container.scrollLeft;
|
||||
|
||||
container.scrollTo({
|
||||
left: direction === 'left'
|
||||
? Math.max(0, currentScroll - scrollAmount)
|
||||
: currentScroll + scrollAmount,
|
||||
behavior: 'smooth'
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex flex-col pt-4">
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center">
|
||||
<Search />
|
||||
<h1 className="text-3xl font-medium p-2">Discover</h1>
|
||||
</div>
|
||||
<button
|
||||
className="p-2 rounded-full bg-light-secondary dark:bg-dark-secondary hover:bg-light-primary hover:dark:bg-dark-primary transition-colors"
|
||||
onClick={() => setShowPreferences(true)}
|
||||
aria-label="Personalize"
|
||||
>
|
||||
<Sliders size={20} />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="relative flex items-center py-4">
|
||||
<button
|
||||
className="absolute left-0 z-10 p-1 rounded-full bg-light-secondary dark:bg-dark-secondary hover:bg-light-primary/80 hover:dark:bg-dark-primary/80 transition-colors"
|
||||
onClick={() => scrollCategories('left')}
|
||||
aria-label="Scroll left"
|
||||
>
|
||||
<ChevronLeft size={20} />
|
||||
</button>
|
||||
|
||||
<div
|
||||
className="flex overflow-x-auto mx-8 no-scrollbar scroll-smooth"
|
||||
ref={categoryContainerRef}
|
||||
style={{ scrollbarWidth: 'none' }} // For Firefox
|
||||
>
|
||||
<div className="flex space-x-2">
|
||||
{visibleCategories.map((category) => (
|
||||
<button
|
||||
key={category}
|
||||
className={`px-4 py-2 rounded-full whitespace-nowrap transition-colors ${
|
||||
activeCategory === category
|
||||
? 'bg-light-primary dark:bg-dark-primary text-white'
|
||||
: 'bg-light-secondary dark:bg-dark-secondary hover:bg-light-primary/80 hover:dark:bg-dark-primary/80'
|
||||
}`}
|
||||
onClick={() => setActiveCategory(category)}
|
||||
>
|
||||
{category}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<button
|
||||
className="absolute right-0 z-10 p-1 rounded-full bg-light-secondary dark:bg-dark-secondary hover:bg-light-primary/80 hover:dark:bg-dark-primary/80 transition-colors"
|
||||
onClick={() => scrollCategories('right')}
|
||||
aria-label="Scroll right"
|
||||
>
|
||||
<ChevronRight size={20} />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<hr className="border-t border-[#2B2C2C] my-4 w-full" />
|
||||
</div>
|
||||
);
|
||||
});
|
||||
|
||||
DiscoverHeader.displayName = 'DiscoverHeader';
|
||||
|
||||
// Content component that displays articles
|
||||
const DiscoverContent = memo(({
|
||||
activeCategory,
|
||||
userPreferences,
|
||||
preferredLanguages
|
||||
}: {
|
||||
activeCategory: string;
|
||||
userPreferences: string[];
|
||||
preferredLanguages: string[];
|
||||
}) => {
|
||||
const Page = () => {
|
||||
const [discover, setDiscover] = useState<Discover[] | null>(null);
|
||||
const [contentLoading, setContentLoading] = useState(true);
|
||||
const [loading, setLoading] = useState(true);
|
||||
|
||||
useEffect(() => {
|
||||
const fetchData = async () => {
|
||||
setContentLoading(true);
|
||||
try {
|
||||
let endpoint = `/api/discover`;
|
||||
let params = [];
|
||||
|
||||
if (activeCategory !== 'For You') {
|
||||
params.push(`category=${encodeURIComponent(activeCategory)}`);
|
||||
} else if (userPreferences.length > 0) {
|
||||
params.push(`preferences=${encodeURIComponent(JSON.stringify(userPreferences))}`);
|
||||
}
|
||||
|
||||
if (preferredLanguages.length > 0) {
|
||||
params.push(`languages=${encodeURIComponent(JSON.stringify(preferredLanguages))}`);
|
||||
}
|
||||
|
||||
if (params.length > 0) {
|
||||
endpoint += `?${params.join('&')}`;
|
||||
}
|
||||
|
||||
const res = await fetch(endpoint, {
|
||||
const res = await fetch(`/api/discover`, {
|
||||
method: 'GET',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
@ -183,7 +32,6 @@ const DiscoverContent = memo(({
|
||||
throw new Error(data.message);
|
||||
}
|
||||
|
||||
// Filter out items without thumbnails (double-checking)
|
||||
data.blogs = data.blogs.filter((blog: Discover) => blog.thumbnail);
|
||||
|
||||
setDiscover(data.blogs);
|
||||
@ -191,326 +39,74 @@ const DiscoverContent = memo(({
|
||||
console.error('Error fetching data:', err.message);
|
||||
toast.error('Error fetching data');
|
||||
} finally {
|
||||
setContentLoading(false);
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
fetchData();
|
||||
}, [activeCategory, userPreferences, preferredLanguages]);
|
||||
|
||||
if (contentLoading) {
|
||||
return (
|
||||
<div className="flex flex-row items-center justify-center py-20">
|
||||
<svg
|
||||
aria-hidden="true"
|
||||
className="w-8 h-8 text-light-200 fill-light-secondary dark:text-[#202020] animate-spin dark:fill-[#ffffff3b]"
|
||||
viewBox="0 0 100 101"
|
||||
fill="none"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
>
|
||||
<path
|
||||
d="M100 50.5908C100.003 78.2051 78.1951 100.003 50.5908 100C22.9765 99.9972 0.997224 78.018 1 50.4037C1.00281 22.7993 22.8108 0.997224 50.4251 1C78.0395 1.00281 100.018 22.8108 100 50.4251ZM9.08164 50.594C9.06312 73.3997 27.7909 92.1272 50.5966 92.1457C73.4023 92.1642 92.1298 73.4365 92.1483 50.6308C92.1669 27.8251 73.4392 9.0973 50.6335 9.07878C27.8278 9.06026 9.10003 27.787 9.08164 50.594Z"
|
||||
fill="currentColor"
|
||||
/>
|
||||
<path
|
||||
d="M93.9676 39.0409C96.393 38.4037 97.8624 35.9116 96.9801 33.5533C95.1945 28.8227 92.871 24.3692 90.0681 20.348C85.6237 14.1775 79.4473 9.36872 72.0454 6.45794C64.6435 3.54717 56.3134 2.65431 48.3133 3.89319C45.869 4.27179 44.3768 6.77534 45.014 9.20079C45.6512 11.6262 48.1343 13.0956 50.5786 12.717C56.5073 11.8281 62.5542 12.5399 68.0406 14.7911C73.527 17.0422 78.2187 20.7487 81.5841 25.4923C83.7976 28.5886 85.4467 32.059 86.4416 35.7474C87.1273 38.1189 89.5423 39.6781 91.9676 39.0409Z"
|
||||
fill="currentFill"
|
||||
/>
|
||||
</svg>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (!discover || discover.length === 0) {
|
||||
return (
|
||||
<div className="flex flex-row items-center justify-center min-h-[50vh]">
|
||||
<p className="text-black/70 dark:text-white/70 text-sm">
|
||||
No content found for this category.
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="grid lg:grid-cols-3 sm:grid-cols-2 grid-cols-1 gap-4 pb-28 lg:pb-8 w-full justify-items-center lg:justify-items-start">
|
||||
{discover.map((item, i) => (
|
||||
<Link
|
||||
href={`/?q=Summary: ${item.url}`}
|
||||
key={i}
|
||||
className="max-w-sm rounded-lg overflow-hidden bg-light-secondary dark:bg-dark-secondary hover:-translate-y-[1px] transition duration-200"
|
||||
target="_blank"
|
||||
>
|
||||
{/* Using img tag with URL processing for thumbnails */}
|
||||
<img
|
||||
className="object-cover w-full aspect-video"
|
||||
src={
|
||||
new URL(item.thumbnail).origin +
|
||||
new URL(item.thumbnail).pathname +
|
||||
`?id=${new URL(item.thumbnail).searchParams.get('id')}`
|
||||
}
|
||||
alt={item.title}
|
||||
/>
|
||||
<div className="px-6 py-4">
|
||||
<div className="font-bold text-lg mb-2">
|
||||
{item.title.slice(0, 100)}...
|
||||
</div>
|
||||
<p className="text-black-70 dark:text-white/70 text-sm">
|
||||
{item.content.slice(0, 100)}...
|
||||
</p>
|
||||
</div>
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
});
|
||||
|
||||
DiscoverContent.displayName = 'DiscoverContent';
|
||||
|
||||
// Preferences modal for personalization
|
||||
const PreferencesModal = memo(({
|
||||
showPreferences,
|
||||
setShowPreferences,
|
||||
userPreferences,
|
||||
setUserPreferences,
|
||||
preferredLanguages,
|
||||
setPreferredLanguages,
|
||||
setActiveCategory
|
||||
}: {
|
||||
showPreferences: boolean;
|
||||
setShowPreferences: (show: boolean) => void;
|
||||
userPreferences: string[];
|
||||
setUserPreferences: (prefs: string[]) => void;
|
||||
preferredLanguages: string[];
|
||||
setPreferredLanguages: (langs: string[]) => void;
|
||||
setActiveCategory: (category: string) => void;
|
||||
}) => {
|
||||
const [tempPreferences, setTempPreferences] = useState<string[]>([]);
|
||||
const [tempLanguages, setTempLanguages] = useState<string[]>([]);
|
||||
|
||||
useEffect(() => {
|
||||
if (showPreferences) {
|
||||
setTempPreferences([...userPreferences]);
|
||||
setTempLanguages([...preferredLanguages]);
|
||||
}
|
||||
}, [showPreferences, userPreferences, preferredLanguages]);
|
||||
|
||||
const saveUserPreferences = async (preferences: string[], languages: string[]) => {
|
||||
try {
|
||||
const res = await fetch(`/api/discover/preferences`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
categories: preferences,
|
||||
languages
|
||||
}),
|
||||
});
|
||||
|
||||
if (res.ok) {
|
||||
toast.success('Preferences saved successfully');
|
||||
} else {
|
||||
const data = await res.json();
|
||||
throw new Error(data.message);
|
||||
}
|
||||
} catch (err: any) {
|
||||
console.error('Error saving preferences:', err.message);
|
||||
toast.error('Error saving preferences');
|
||||
}
|
||||
};
|
||||
|
||||
if (!showPreferences) return null;
|
||||
|
||||
return (
|
||||
<div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
|
||||
<div className="bg-white dark:bg-[#1E1E1E] p-6 rounded-lg w-full max-w-md">
|
||||
<h2 className="text-xl font-bold mb-4">Personalize Your Feed</h2>
|
||||
|
||||
<h3 className="font-medium mb-2">Select categories you're interested in:</h3>
|
||||
<div className="grid grid-cols-2 gap-2 mb-6">
|
||||
{categories.filter(c => c !== 'For You').map((category) => (
|
||||
<button
|
||||
key={category}
|
||||
onClick={() => {
|
||||
if (tempPreferences.includes(category)) {
|
||||
setTempPreferences(tempPreferences.filter(p => p !== category));
|
||||
} else {
|
||||
setTempPreferences([...tempPreferences, category]);
|
||||
}
|
||||
}}
|
||||
className={`px-3 py-2 rounded-md text-left transition-colors border ${
|
||||
tempPreferences.includes(category)
|
||||
? 'bg-blue-500 border-blue-500 text-white'
|
||||
: 'bg-light-secondary dark:bg-dark-secondary border-gray-400 dark:border-gray-600 hover:border-blue-400 dark:hover:border-blue-400'
|
||||
}`}
|
||||
>
|
||||
{category}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<div className="mb-6">
|
||||
<h3 className="font-medium mb-2">Preferred Languages</h3>
|
||||
<div className="grid grid-cols-2 gap-2">
|
||||
{[
|
||||
{ code: 'en', name: 'English' },
|
||||
{ code: 'ar', name: 'Arabic' },
|
||||
{ code: 'zh', name: 'Chinese' },
|
||||
{ code: 'fr', name: 'French' },
|
||||
{ code: 'de', name: 'German' },
|
||||
{ code: 'hi', name: 'Hindi' },
|
||||
{ code: 'it', name: 'Italian' },
|
||||
{ code: 'ja', name: 'Japanese' },
|
||||
{ code: 'ko', name: 'Korean' },
|
||||
{ code: 'pt', name: 'Portuguese' },
|
||||
{ code: 'ru', name: 'Russian' },
|
||||
{ code: 'es', name: 'Spanish' },
|
||||
].map((language) => (
|
||||
<button
|
||||
key={language.code}
|
||||
onClick={() => {
|
||||
if (tempLanguages.includes(language.code)) {
|
||||
setTempLanguages(tempLanguages.filter(l => l !== language.code));
|
||||
} else {
|
||||
setTempLanguages([...tempLanguages, language.code]);
|
||||
}
|
||||
}}
|
||||
className={`px-3 py-2 rounded-md text-left transition-colors border ${
|
||||
tempLanguages.includes(language.code)
|
||||
? 'bg-blue-500 border-blue-500 text-white'
|
||||
: 'bg-light-secondary dark:bg-dark-secondary border-gray-400 dark:border-gray-600 hover:border-blue-400 dark:hover:border-blue-400'
|
||||
}`}
|
||||
>
|
||||
{language.name}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<p className="text-sm text-gray-500 mt-2">
|
||||
{tempLanguages.length === 0
|
||||
? "No languages selected will show results in all languages"
|
||||
: `Selected: ${tempLanguages.length} language(s)`}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="flex justify-end space-x-2">
|
||||
<button
|
||||
className="px-4 py-2 rounded bg-gray-300 dark:bg-gray-700 hover:bg-gray-400 dark:hover:bg-gray-600 transition-colors"
|
||||
onClick={() => {
|
||||
setShowPreferences(false);
|
||||
// Reset temp preferences
|
||||
setTempPreferences([]);
|
||||
setTempLanguages([]);
|
||||
}}
|
||||
>
|
||||
Cancel
|
||||
</button>
|
||||
<button
|
||||
className="px-4 py-2 rounded bg-light-primary dark:bg-dark-primary text-white hover:bg-light-primary/80 hover:dark:bg-dark-primary/80 transition-colors"
|
||||
onClick={async () => {
|
||||
await saveUserPreferences(tempPreferences, tempLanguages);
|
||||
// Update the actual preferences after saving
|
||||
setUserPreferences(tempPreferences);
|
||||
setPreferredLanguages(tempLanguages);
|
||||
setShowPreferences(false);
|
||||
setActiveCategory('For You'); // Switch to For You view to show personalized content
|
||||
|
||||
// Reset temp preferences
|
||||
setTempPreferences([]);
|
||||
setTempLanguages([]);
|
||||
}}
|
||||
>
|
||||
Save
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
});
|
||||
|
||||
PreferencesModal.displayName = 'PreferencesModal';
|
||||
|
||||
// Main page component
|
||||
const Page = () => {
|
||||
const [activeCategory, setActiveCategory] = useState('For You');
|
||||
const [showPreferences, setShowPreferences] = useState(false);
|
||||
const [userPreferences, setUserPreferences] = useState<string[]>(['AI', 'Technology']);
|
||||
const [preferredLanguages, setPreferredLanguages] = useState<string[]>(['en']);
|
||||
const [initialLoading, setInitialLoading] = useState(true);
|
||||
|
||||
// Load user preferences on initial render
|
||||
useEffect(() => {
|
||||
const loadUserPreferences = async () => {
|
||||
try {
|
||||
const res = await fetch(`/api/discover/preferences`, {
|
||||
method: 'GET',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
});
|
||||
|
||||
if (res.ok) {
|
||||
const data = await res.json();
|
||||
setUserPreferences(data.categories || ['AI', 'Technology']);
|
||||
setPreferredLanguages(data.languages || ['en']);
|
||||
}
|
||||
} catch (err: any) {
|
||||
console.error('Error loading preferences:', err.message);
|
||||
} finally {
|
||||
setInitialLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
loadUserPreferences();
|
||||
}, []);
|
||||
|
||||
if (initialLoading) {
|
||||
return (
|
||||
<div className="flex flex-row items-center justify-center min-h-screen">
|
||||
<svg
|
||||
aria-hidden="true"
|
||||
className="w-8 h-8 text-light-200 fill-light-secondary dark:text-[#202020] animate-spin dark:fill-[#ffffff3b]"
|
||||
viewBox="0 0 100 101"
|
||||
fill="none"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
>
|
||||
<path
|
||||
d="M100 50.5908C100.003 78.2051 78.1951 100.003 50.5908 100C22.9765 99.9972 0.997224 78.018 1 50.4037C1.00281 22.7993 22.8108 0.997224 50.4251 1C78.0395 1.00281 100.018 22.8108 100 50.4251ZM9.08164 50.594C9.06312 73.3997 27.7909 92.1272 50.5966 92.1457C73.4023 92.1642 92.1298 73.4365 92.1483 50.6308C92.1669 27.8251 73.4392 9.0973 50.6335 9.07878C27.8278 9.06026 9.10003 27.787 9.08164 50.594Z"
|
||||
fill="currentColor"
|
||||
/>
|
||||
<path
|
||||
d="M93.9676 39.0409C96.393 38.4037 97.8624 35.9116 96.9801 33.5533C95.1945 28.8227 92.871 24.3692 90.0681 20.348C85.6237 14.1775 79.4473 9.36872 72.0454 6.45794C64.6435 3.54717 56.3134 2.65431 48.3133 3.89319C45.869 4.27179 44.3768 6.77534 45.014 9.20079C45.6512 11.6262 48.1343 13.0956 50.5786 12.717C56.5073 11.8281 62.5542 12.5399 68.0406 14.7911C73.527 17.0422 78.2187 20.7487 81.5841 25.4923C83.7976 28.5886 85.4467 32.059 86.4416 35.7474C87.1273 38.1189 89.5423 39.6781 91.9676 39.0409Z"
|
||||
fill="currentFill"
|
||||
/>
|
||||
</svg>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div>
|
||||
<DiscoverHeader
|
||||
activeCategory={activeCategory}
|
||||
setActiveCategory={setActiveCategory}
|
||||
setShowPreferences={setShowPreferences}
|
||||
userPreferences={userPreferences}
|
||||
/>
|
||||
|
||||
<DiscoverContent
|
||||
activeCategory={activeCategory}
|
||||
userPreferences={userPreferences}
|
||||
preferredLanguages={preferredLanguages}
|
||||
/>
|
||||
|
||||
<PreferencesModal
|
||||
showPreferences={showPreferences}
|
||||
setShowPreferences={setShowPreferences}
|
||||
userPreferences={userPreferences}
|
||||
setUserPreferences={setUserPreferences}
|
||||
preferredLanguages={preferredLanguages}
|
||||
setPreferredLanguages={setPreferredLanguages}
|
||||
setActiveCategory={setActiveCategory}
|
||||
/>
|
||||
return loading ? (
|
||||
<div className="flex flex-row items-center justify-center min-h-screen">
|
||||
<svg
|
||||
aria-hidden="true"
|
||||
className="w-8 h-8 text-light-200 fill-light-secondary dark:text-[#202020] animate-spin dark:fill-[#ffffff3b]"
|
||||
viewBox="0 0 100 101"
|
||||
fill="none"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
>
|
||||
<path
|
||||
d="M100 50.5908C100.003 78.2051 78.1951 100.003 50.5908 100C22.9765 99.9972 0.997224 78.018 1 50.4037C1.00281 22.7993 22.8108 0.997224 50.4251 1C78.0395 1.00281 100.018 22.8108 100 50.4251ZM9.08164 50.594C9.06312 73.3997 27.7909 92.1272 50.5966 92.1457C73.4023 92.1642 92.1298 73.4365 92.1483 50.6308C92.1669 27.8251 73.4392 9.0973 50.6335 9.07878C27.8278 9.06026 9.10003 27.787 9.08164 50.594Z"
|
||||
fill="currentColor"
|
||||
/>
|
||||
<path
|
||||
d="M93.9676 39.0409C96.393 38.4037 97.8624 35.9116 96.9801 33.5533C95.1945 28.8227 92.871 24.3692 90.0681 20.348C85.6237 14.1775 79.4473 9.36872 72.0454 6.45794C64.6435 3.54717 56.3134 2.65431 48.3133 3.89319C45.869 4.27179 44.3768 6.77534 45.014 9.20079C45.6512 11.6262 48.1343 13.0956 50.5786 12.717C56.5073 11.8281 62.5542 12.5399 68.0406 14.7911C73.527 17.0422 78.2187 20.7487 81.5841 25.4923C83.7976 28.5886 85.4467 32.059 86.4416 35.7474C87.1273 38.1189 89.5423 39.6781 91.9676 39.0409Z"
|
||||
fill="currentFill"
|
||||
/>
|
||||
</svg>
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<div>
|
||||
<div className="flex flex-col pt-4">
|
||||
<div className="flex items-center">
|
||||
<Search />
|
||||
<h1 className="text-3xl font-medium p-2">Discover</h1>
|
||||
</div>
|
||||
<hr className="border-t border-[#2B2C2C] my-4 w-full" />
|
||||
</div>
|
||||
|
||||
<div className="grid lg:grid-cols-3 sm:grid-cols-2 grid-cols-1 gap-4 pb-28 lg:pb-8 w-full justify-items-center lg:justify-items-start">
|
||||
{discover &&
|
||||
discover?.map((item, i) => (
|
||||
<Link
|
||||
href={`/?q=Summary: ${item.url}`}
|
||||
key={i}
|
||||
className="max-w-sm rounded-lg overflow-hidden bg-light-secondary dark:bg-dark-secondary hover:-translate-y-[1px] transition duration-200"
|
||||
target="_blank"
|
||||
>
|
||||
<img
|
||||
className="object-cover w-full aspect-video"
|
||||
src={
|
||||
new URL(item.thumbnail).origin +
|
||||
new URL(item.thumbnail).pathname +
|
||||
`?id=${new URL(item.thumbnail).searchParams.get('id')}`
|
||||
}
|
||||
alt={item.title}
|
||||
/>
|
||||
<div className="px-6 py-4">
|
||||
<div className="font-bold text-lg mb-2">
|
||||
{item.title.slice(0, 100)}...
|
||||
</div>
|
||||
<p className="text-black-70 dark:text-white/70 text-sm">
|
||||
{item.content.slice(0, 100)}...
|
||||
</p>
|
||||
</div>
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
|
@ -1,12 +1,10 @@
|
||||
'use client';
|
||||
|
||||
import DeleteChat from '@/components/DeleteChat';
|
||||
import BatchDeleteChats from '@/components/BatchDeleteChats';
|
||||
import { cn, formatTimeDifference } from '@/lib/utils';
|
||||
import { BookOpenText, Check, ClockIcon, Delete, ScanEye, Search, X } from 'lucide-react';
|
||||
import { BookOpenText, ClockIcon, Delete, ScanEye } from 'lucide-react';
|
||||
import Link from 'next/link';
|
||||
import { useEffect, useState } from 'react';
|
||||
import { toast } from 'sonner';
|
||||
|
||||
export interface Chat {
|
||||
id: string;
|
||||
@ -17,13 +15,7 @@ export interface Chat {
|
||||
|
||||
const Page = () => {
|
||||
const [chats, setChats] = useState<Chat[]>([]);
|
||||
const [filteredChats, setFilteredChats] = useState<Chat[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [searchQuery, setSearchQuery] = useState('');
|
||||
const [selectionMode, setSelectionMode] = useState(false);
|
||||
const [selectedChats, setSelectedChats] = useState<string[]>([]);
|
||||
const [hoveredChatId, setHoveredChatId] = useState<string | null>(null);
|
||||
const [isDeleteDialogOpen, setIsDeleteDialogOpen] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
const fetchChats = async () => {
|
||||
@ -39,71 +31,12 @@ const Page = () => {
|
||||
const data = await res.json();
|
||||
|
||||
setChats(data.chats);
|
||||
setFilteredChats(data.chats);
|
||||
setLoading(false);
|
||||
};
|
||||
|
||||
fetchChats();
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (searchQuery.trim() === '') {
|
||||
setFilteredChats(chats);
|
||||
} else {
|
||||
const filtered = chats.filter((chat) =>
|
||||
chat.title.toLowerCase().includes(searchQuery.toLowerCase())
|
||||
);
|
||||
setFilteredChats(filtered);
|
||||
}
|
||||
}, [searchQuery, chats]);
|
||||
|
||||
const handleSearchChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
setSearchQuery(e.target.value);
|
||||
};
|
||||
|
||||
const clearSearch = () => {
|
||||
setSearchQuery('');
|
||||
};
|
||||
|
||||
const toggleSelectionMode = () => {
|
||||
setSelectionMode(!selectionMode);
|
||||
setSelectedChats([]);
|
||||
};
|
||||
|
||||
const toggleChatSelection = (chatId: string) => {
|
||||
if (selectedChats.includes(chatId)) {
|
||||
setSelectedChats(selectedChats.filter(id => id !== chatId));
|
||||
} else {
|
||||
setSelectedChats([...selectedChats, chatId]);
|
||||
}
|
||||
};
|
||||
|
||||
const selectAllChats = () => {
|
||||
if (selectedChats.length === filteredChats.length) {
|
||||
setSelectedChats([]);
|
||||
} else {
|
||||
setSelectedChats(filteredChats.map(chat => chat.id));
|
||||
}
|
||||
};
|
||||
|
||||
const deleteSelectedChats = () => {
|
||||
if (selectedChats.length === 0) return;
|
||||
setIsDeleteDialogOpen(true);
|
||||
};
|
||||
|
||||
const handleBatchDeleteComplete = () => {
|
||||
setSelectedChats([]);
|
||||
setSelectionMode(false);
|
||||
};
|
||||
|
||||
const updateChatsAfterDelete = (newChats: Chat[]) => {
|
||||
setChats(newChats);
|
||||
setFilteredChats(newChats.filter(chat =>
|
||||
searchQuery.trim() === '' ||
|
||||
chat.title.toLowerCase().includes(searchQuery.toLowerCase())
|
||||
));
|
||||
};
|
||||
|
||||
return loading ? (
|
||||
<div className="flex flex-row items-center justify-center min-h-screen">
|
||||
<svg
|
||||
@ -131,145 +64,32 @@ const Page = () => {
|
||||
<h1 className="text-3xl font-medium p-2">Library</h1>
|
||||
</div>
|
||||
<hr className="border-t border-[#2B2C2C] my-4 w-full" />
|
||||
|
||||
{/* Search Box */}
|
||||
<div className="relative mt-6 mb-6">
|
||||
<div className="absolute inset-y-0 left-0 flex items-center pl-3 pointer-events-none">
|
||||
<Search className="w-5 h-5 text-black/50 dark:text-white/50" />
|
||||
</div>
|
||||
<input
|
||||
type="text"
|
||||
className="block w-full p-2 pl-10 pr-10 bg-light-secondary dark:bg-dark-secondary border border-light-200 dark:border-dark-200 rounded-md text-black dark:text-white focus:outline-none focus:ring-1 focus:ring-blue-500"
|
||||
placeholder="Search your threads..."
|
||||
value={searchQuery}
|
||||
onChange={handleSearchChange}
|
||||
/>
|
||||
{searchQuery && (
|
||||
<button
|
||||
onClick={clearSearch}
|
||||
className="absolute inset-y-0 right-0 flex items-center pr-3"
|
||||
>
|
||||
<X className="w-5 h-5 text-black/50 dark:text-white/50 hover:text-black dark:hover:text-white" />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Thread Count and Selection Controls */}
|
||||
<div className="mb-4">
|
||||
{!selectionMode ? (
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="text-black/70 dark:text-white/70">
|
||||
You have {chats.length} threads in Perplexica
|
||||
</div>
|
||||
<button
|
||||
onClick={toggleSelectionMode}
|
||||
className="text-black/70 dark:text-white/70 hover:text-black dark:hover:text-white text-sm transition duration-200"
|
||||
>
|
||||
Select
|
||||
</button>
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="text-black/70 dark:text-white/70">
|
||||
{selectedChats.length} selected thread{selectedChats.length !== 1 ? 's' : ''}
|
||||
</div>
|
||||
<div className="flex space-x-4">
|
||||
<button
|
||||
onClick={selectAllChats}
|
||||
className="text-black/70 dark:text-white/70 hover:text-black dark:hover:text-white text-sm transition duration-200"
|
||||
>
|
||||
{selectedChats.length === filteredChats.length ? 'Deselect all' : 'Select all'}
|
||||
</button>
|
||||
|
||||
<button
|
||||
onClick={toggleSelectionMode}
|
||||
className="text-black/70 dark:text-white/70 hover:text-black dark:hover:text-white text-sm transition duration-200"
|
||||
>
|
||||
Cancel
|
||||
</button>
|
||||
|
||||
<button
|
||||
onClick={deleteSelectedChats}
|
||||
disabled={selectedChats.length === 0}
|
||||
className={cn(
|
||||
"text-sm transition duration-200",
|
||||
selectedChats.length === 0
|
||||
? "text-red-400/50 hover:text-red-500/50 cursor-not-allowed"
|
||||
: "text-red-400 hover:text-red-500 cursor-pointer"
|
||||
)}
|
||||
>
|
||||
Delete Selected
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{filteredChats.length === 0 && (
|
||||
<div className="flex flex-row items-center justify-center min-h-[50vh]">
|
||||
{chats.length === 0 && (
|
||||
<div className="flex flex-row items-center justify-center min-h-screen">
|
||||
<p className="text-black/70 dark:text-white/70 text-sm">
|
||||
{searchQuery ? 'No threads found matching your search.' : 'No threads found.'}
|
||||
No chats found.
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{filteredChats.length > 0 && (
|
||||
{chats.length > 0 && (
|
||||
<div className="flex flex-col pb-20 lg:pb-2">
|
||||
{filteredChats.map((chat, i) => (
|
||||
{chats.map((chat, i) => (
|
||||
<div
|
||||
className={cn(
|
||||
'flex flex-col space-y-4 py-6',
|
||||
i !== filteredChats.length - 1
|
||||
i !== chats.length - 1
|
||||
? 'border-b border-white-200 dark:border-dark-200'
|
||||
: '',
|
||||
)}
|
||||
key={i}
|
||||
onMouseEnter={() => setHoveredChatId(chat.id)}
|
||||
onMouseLeave={() => setHoveredChatId(null)}
|
||||
>
|
||||
<div className="flex items-center">
|
||||
{/* Checkbox - visible when in selection mode or when hovering */}
|
||||
{(selectionMode || hoveredChatId === chat.id) && (
|
||||
<div
|
||||
className="mr-3 cursor-pointer"
|
||||
onClick={(e) => {
|
||||
e.preventDefault();
|
||||
if (!selectionMode) setSelectionMode(true);
|
||||
toggleChatSelection(chat.id);
|
||||
}}
|
||||
>
|
||||
<div className={cn(
|
||||
"w-5 h-5 border rounded flex items-center justify-center transition-colors",
|
||||
selectedChats.includes(chat.id)
|
||||
? "bg-blue-500 border-blue-500"
|
||||
: "border-gray-400 dark:border-gray-600"
|
||||
)}>
|
||||
{selectedChats.includes(chat.id) && (
|
||||
<Check className="w-4 h-4 text-white" />
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Chat Title */}
|
||||
<Link
|
||||
href={`/c/${chat.id}`}
|
||||
className={cn(
|
||||
"text-black dark:text-white lg:text-xl font-medium truncate transition duration-200 hover:text-[#24A0ED] dark:hover:text-[#24A0ED] cursor-pointer",
|
||||
selectionMode && "pointer-events-none text-black dark:text-white hover:text-black dark:hover:text-white"
|
||||
)}
|
||||
onClick={(e) => {
|
||||
if (selectionMode) {
|
||||
e.preventDefault();
|
||||
toggleChatSelection(chat.id);
|
||||
}
|
||||
}}
|
||||
>
|
||||
{chat.title}
|
||||
</Link>
|
||||
</div>
|
||||
|
||||
<Link
|
||||
href={`/c/${chat.id}`}
|
||||
className="text-black dark:text-white lg:text-xl font-medium truncate transition duration-200 hover:text-[#24A0ED] dark:hover:text-[#24A0ED] cursor-pointer"
|
||||
>
|
||||
{chat.title}
|
||||
</Link>
|
||||
<div className="flex flex-row items-center justify-between w-full">
|
||||
<div className="flex flex-row items-center space-x-1 lg:space-x-1.5 text-black/70 dark:text-white/70">
|
||||
<ClockIcon size={15} />
|
||||
@ -277,30 +97,16 @@ const Page = () => {
|
||||
{formatTimeDifference(new Date(), chat.createdAt)} Ago
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Delete button - only visible when not in selection mode */}
|
||||
{!selectionMode && (
|
||||
<DeleteChat
|
||||
chatId={chat.id}
|
||||
chats={chats}
|
||||
setChats={updateChatsAfterDelete}
|
||||
/>
|
||||
)}
|
||||
<DeleteChat
|
||||
chatId={chat.id}
|
||||
chats={chats}
|
||||
setChats={setChats}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Batch Delete Confirmation Dialog */}
|
||||
<BatchDeleteChats
|
||||
chatIds={selectedChats}
|
||||
chats={chats}
|
||||
setChats={updateChatsAfterDelete}
|
||||
onComplete={handleBatchDeleteComplete}
|
||||
isOpen={isDeleteDialogOpen}
|
||||
setIsOpen={setIsDeleteDialogOpen}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
@ -21,6 +21,7 @@ interface SettingsType {
|
||||
anthropicApiKey: string;
|
||||
geminiApiKey: string;
|
||||
ollamaApiUrl: string;
|
||||
lmStudioApiUrl: string;
|
||||
deepseekApiKey: string;
|
||||
customOpenaiApiKey: string;
|
||||
customOpenaiApiUrl: string;
|
||||
@ -548,8 +549,10 @@ const Page = () => {
|
||||
options={Object.keys(config.chatModelProviders).map(
|
||||
(provider) => ({
|
||||
value: provider,
|
||||
label: (PROVIDER_METADATA as any)[provider]?.displayName ||
|
||||
provider.charAt(0).toUpperCase() + provider.slice(1),
|
||||
label:
|
||||
(PROVIDER_METADATA as any)[provider]?.displayName ||
|
||||
provider.charAt(0).toUpperCase() +
|
||||
provider.slice(1),
|
||||
}),
|
||||
)}
|
||||
/>
|
||||
@ -689,8 +692,10 @@ const Page = () => {
|
||||
options={Object.keys(config.embeddingModelProviders).map(
|
||||
(provider) => ({
|
||||
value: provider,
|
||||
label: (PROVIDER_METADATA as any)[provider]?.displayName ||
|
||||
provider.charAt(0).toUpperCase() + provider.slice(1),
|
||||
label:
|
||||
(PROVIDER_METADATA as any)[provider]?.displayName ||
|
||||
provider.charAt(0).toUpperCase() +
|
||||
provider.slice(1),
|
||||
}),
|
||||
)}
|
||||
/>
|
||||
@ -857,6 +862,25 @@ const Page = () => {
|
||||
onSave={(value) => saveConfig('deepseekApiKey', value)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col space-y-1">
|
||||
<p className="text-black/70 dark:text-white/70 text-sm">
|
||||
LM Studio API URL
|
||||
</p>
|
||||
<Input
|
||||
type="text"
|
||||
placeholder="LM Studio API URL"
|
||||
value={config.lmStudioApiUrl}
|
||||
isSaving={savingStates['lmStudioApiUrl']}
|
||||
onChange={(e) => {
|
||||
setConfig((prev) => ({
|
||||
...prev!,
|
||||
lmStudioApiUrl: e.target.value,
|
||||
}));
|
||||
}}
|
||||
onSave={(value) => saveConfig('lmStudioApiUrl', value)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</SettingsSection>
|
||||
</div>
|
||||
|
@ -1,118 +0,0 @@
|
||||
import {
|
||||
Description,
|
||||
Dialog,
|
||||
DialogBackdrop,
|
||||
DialogPanel,
|
||||
DialogTitle,
|
||||
Transition,
|
||||
TransitionChild,
|
||||
} from '@headlessui/react';
|
||||
import { Fragment, useState } from 'react';
|
||||
import { toast } from 'sonner';
|
||||
import { Chat } from '@/app/library/page';
|
||||
|
||||
interface BatchDeleteChatsProps {
|
||||
chatIds: string[];
|
||||
chats: Chat[];
|
||||
setChats: (chats: Chat[]) => void;
|
||||
onComplete: () => void;
|
||||
isOpen: boolean;
|
||||
setIsOpen: (isOpen: boolean) => void;
|
||||
}
|
||||
|
||||
const BatchDeleteChats = ({
|
||||
chatIds,
|
||||
chats,
|
||||
setChats,
|
||||
onComplete,
|
||||
isOpen,
|
||||
setIsOpen,
|
||||
}: BatchDeleteChatsProps) => {
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
const handleDelete = async () => {
|
||||
if (chatIds.length === 0) return;
|
||||
|
||||
setLoading(true);
|
||||
try {
|
||||
for (const chatId of chatIds) {
|
||||
await fetch(`/api/chats/${chatId}`, {
|
||||
method: 'DELETE',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
const newChats = chats.filter(chat => !chatIds.includes(chat.id));
|
||||
setChats(newChats);
|
||||
|
||||
toast.success(`${chatIds.length} thread${chatIds.length > 1 ? 's' : ''} deleted`);
|
||||
onComplete();
|
||||
} catch (err: any) {
|
||||
toast.error('Failed to delete threads');
|
||||
} finally {
|
||||
setIsOpen(false);
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Transition appear show={isOpen} as={Fragment}>
|
||||
<Dialog
|
||||
as="div"
|
||||
className="relative z-50"
|
||||
onClose={() => {
|
||||
if (!loading) {
|
||||
setIsOpen(false);
|
||||
}
|
||||
}}
|
||||
>
|
||||
<DialogBackdrop className="fixed inset-0 bg-black/30" />
|
||||
<div className="fixed inset-0 overflow-y-auto">
|
||||
<div className="flex min-h-full items-center justify-center p-4 text-center">
|
||||
<TransitionChild
|
||||
as={Fragment}
|
||||
enter="ease-out duration-200"
|
||||
enterFrom="opacity-0 scale-95"
|
||||
enterTo="opacity-100 scale-100"
|
||||
leave="ease-in duration-100"
|
||||
leaveFrom="opacity-100 scale-200"
|
||||
leaveTo="opacity-0 scale-95"
|
||||
>
|
||||
<DialogPanel className="w-full max-w-md transform rounded-2xl bg-light-secondary dark:bg-dark-secondary border border-light-200 dark:border-dark-200 p-6 text-left align-middle shadow-xl transition-all">
|
||||
<DialogTitle className="text-lg font-medium leading-6 dark:text-white">
|
||||
Delete Confirmation
|
||||
</DialogTitle>
|
||||
<Description className="text-sm dark:text-white/70 text-black/70">
|
||||
Are you sure you want to delete {chatIds.length} selected thread{chatIds.length !== 1 ? 's' : ''}?
|
||||
</Description>
|
||||
<div className="flex flex-row items-end justify-end space-x-4 mt-6">
|
||||
<button
|
||||
onClick={() => {
|
||||
if (!loading) {
|
||||
setIsOpen(false);
|
||||
}
|
||||
}}
|
||||
className="text-black/50 dark:text-white/50 text-sm hover:text-black/70 hover:dark:text-white/70 transition duration-200"
|
||||
>
|
||||
Cancel
|
||||
</button>
|
||||
<button
|
||||
onClick={handleDelete}
|
||||
className="text-red-400 text-sm hover:text-red-500 transition duration-200"
|
||||
disabled={loading}
|
||||
>
|
||||
Delete
|
||||
</button>
|
||||
</div>
|
||||
</DialogPanel>
|
||||
</TransitionChild>
|
||||
</div>
|
||||
</div>
|
||||
</Dialog>
|
||||
</Transition>
|
||||
);
|
||||
};
|
||||
|
||||
export default BatchDeleteChats;
|
@ -97,6 +97,7 @@ const MessageBox = ({
|
||||
},
|
||||
),
|
||||
);
|
||||
setSpeechMessage(message.content.replace(regex, ''));
|
||||
return;
|
||||
}
|
||||
|
||||
|
@ -60,7 +60,7 @@ const loadConfig = () => {
|
||||
fs.readFileSync(path.join(process.cwd(), `${configFileName}`), 'utf-8'),
|
||||
) as any as Config;
|
||||
}
|
||||
|
||||
|
||||
// Client-side fallback - settings will be loaded via API
|
||||
return {} as Config;
|
||||
};
|
||||
@ -94,7 +94,8 @@ export const getCustomOpenaiApiUrl = () =>
|
||||
export const getCustomOpenaiModelName = () =>
|
||||
loadConfig().MODELS.CUSTOM_OPENAI.MODEL_NAME;
|
||||
|
||||
export const getLMStudioApiEndpoint = () => loadConfig().MODELS.LM_STUDIO.API_URL;
|
||||
export const getLMStudioApiEndpoint = () =>
|
||||
loadConfig().MODELS.LM_STUDIO.API_URL;
|
||||
|
||||
const mergeConfigs = (current: any, update: any): any => {
|
||||
if (update === null || update === undefined) {
|
||||
|
@ -3,42 +3,9 @@ import Database from 'better-sqlite3';
|
||||
import * as schema from './schema';
|
||||
import path from 'path';
|
||||
|
||||
// Create SQLite connection
|
||||
const sqlite = new Database(path.join(process.cwd(), 'data/db.sqlite'));
|
||||
const db = drizzle(sqlite, {
|
||||
schema: schema,
|
||||
});
|
||||
|
||||
// Initialize database schema
|
||||
(function initializeDatabase() {
|
||||
console.log('[DB] Checking database schema...');
|
||||
|
||||
try {
|
||||
// Check if userPreferences table exists
|
||||
const tableExists = sqlite.prepare(`
|
||||
SELECT name FROM sqlite_master
|
||||
WHERE type='table' AND name=?;
|
||||
`).all('userPreferences').length > 0;
|
||||
|
||||
if (!tableExists) {
|
||||
console.log('[DB] Creating userPreferences table...');
|
||||
sqlite.prepare(`
|
||||
CREATE TABLE userPreferences (
|
||||
id INTEGER PRIMARY KEY,
|
||||
userId TEXT NOT NULL UNIQUE,
|
||||
categories TEXT DEFAULT '[]' NOT NULL,
|
||||
languages TEXT DEFAULT '[]' NOT NULL,
|
||||
createdAt TEXT NOT NULL,
|
||||
updatedAt TEXT NOT NULL
|
||||
);
|
||||
`).run();
|
||||
console.log('[DB] userPreferences table created successfully.');
|
||||
} else {
|
||||
console.log('[DB] userPreferences table already exists.');
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('[DB] Error during database initialization:', error);
|
||||
}
|
||||
})();
|
||||
|
||||
export default db;
|
||||
|
@ -1,61 +0,0 @@
|
||||
import db from './index';
|
||||
import { userPreferences } from './schema';
|
||||
import { sql } from 'drizzle-orm';
|
||||
|
||||
/**
|
||||
* Run database migrations to ensure schema is up to date.
|
||||
* This is designed to run once at application startup.
|
||||
*/
|
||||
export async function runMigrations() {
|
||||
console.log('[DB Migration] Checking database schema...');
|
||||
|
||||
try {
|
||||
// Check if userPreferences table exists
|
||||
const tableExists = await checkIfTableExists('userPreferences');
|
||||
|
||||
if (!tableExists) {
|
||||
console.log('[DB Migration] Creating userPreferences table...');
|
||||
await createUserPreferencesTable();
|
||||
console.log('[DB Migration] userPreferences table created successfully.');
|
||||
} else {
|
||||
console.log('[DB Migration] userPreferences table already exists.');
|
||||
}
|
||||
|
||||
console.log('[DB Migration] Database schema is up to date.');
|
||||
} catch (error) {
|
||||
console.error('[DB Migration] Error during migration:', error);
|
||||
// Don't throw the error - we want the application to continue even if migration fails
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a table exists in the database
|
||||
*/
|
||||
async function checkIfTableExists(tableName: string): Promise<boolean> {
|
||||
const result = db.$client.prepare(`
|
||||
SELECT name FROM sqlite_master
|
||||
WHERE type='table' AND name=?;
|
||||
`).all(tableName);
|
||||
|
||||
return result.length > 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create the userPreferences table using the schema definition
|
||||
*/
|
||||
async function createUserPreferencesTable() {
|
||||
// Create the table using a raw SQL query based on our schema
|
||||
db.$client.prepare(`
|
||||
CREATE TABLE userPreferences (
|
||||
id INTEGER PRIMARY KEY,
|
||||
userId TEXT NOT NULL UNIQUE,
|
||||
categories TEXT DEFAULT '[]' NOT NULL,
|
||||
languages TEXT DEFAULT '[]' NOT NULL,
|
||||
createdAt TEXT NOT NULL,
|
||||
updatedAt TEXT NOT NULL
|
||||
);
|
||||
`).run();
|
||||
}
|
||||
|
||||
// Run migrations automatically when this module is imported
|
||||
runMigrations();
|
@ -26,17 +26,3 @@ export const chats = sqliteTable('chats', {
|
||||
.$type<File[]>()
|
||||
.default(sql`'[]'`),
|
||||
});
|
||||
|
||||
// Add user preferences table for Discover features
|
||||
export const userPreferences = sqliteTable('userPreferences', {
|
||||
id: integer('id').primaryKey(),
|
||||
userId: text('userId').notNull().unique(),
|
||||
categories: text('categories', { mode: 'json' })
|
||||
.$type<string[]>()
|
||||
.default(sql`'[]'`), // Categories will be set at the application level
|
||||
languages: text('languages', { mode: 'json' })
|
||||
.$type<string[]>()
|
||||
.default(sql`'[]'`), // Languages will be set at the application level
|
||||
createdAt: text('createdAt').notNull(),
|
||||
updatedAt: text('updatedAt').notNull(),
|
||||
});
|
||||
|
@ -4,7 +4,7 @@ import { getAnthropicApiKey } from '../config';
|
||||
|
||||
export const PROVIDER_INFO = {
|
||||
key: 'anthropic',
|
||||
displayName: 'Anthropic'
|
||||
displayName: 'Anthropic',
|
||||
};
|
||||
import { BaseChatModel } from '@langchain/core/language_models/chat_models';
|
||||
|
||||
|
@ -5,7 +5,7 @@ import { BaseChatModel } from '@langchain/core/language_models/chat_models';
|
||||
|
||||
export const PROVIDER_INFO = {
|
||||
key: 'deepseek',
|
||||
displayName: 'Deepseek AI'
|
||||
displayName: 'Deepseek AI',
|
||||
};
|
||||
|
||||
const deepseekChatModels: Record<string, string>[] = [
|
||||
|
@ -7,7 +7,7 @@ import { ChatModel, EmbeddingModel } from '.';
|
||||
|
||||
export const PROVIDER_INFO = {
|
||||
key: 'gemini',
|
||||
displayName: 'Google Gemini'
|
||||
displayName: 'Google Gemini',
|
||||
};
|
||||
import { BaseChatModel } from '@langchain/core/language_models/chat_models';
|
||||
import { Embeddings } from '@langchain/core/embeddings';
|
||||
|
@ -4,7 +4,7 @@ import { ChatModel } from '.';
|
||||
|
||||
export const PROVIDER_INFO = {
|
||||
key: 'groq',
|
||||
displayName: 'Groq'
|
||||
displayName: 'Groq',
|
||||
};
|
||||
import { BaseChatModel } from '@langchain/core/language_models/chat_models';
|
||||
|
||||
|
@ -1,19 +1,45 @@
|
||||
import { Embeddings } from '@langchain/core/embeddings';
|
||||
import { BaseChatModel } from '@langchain/core/language_models/chat_models';
|
||||
import { loadOpenAIChatModels, loadOpenAIEmbeddingModels, PROVIDER_INFO as OpenAIInfo, PROVIDER_INFO } from './openai';
|
||||
import {
|
||||
loadOpenAIChatModels,
|
||||
loadOpenAIEmbeddingModels,
|
||||
PROVIDER_INFO as OpenAIInfo,
|
||||
PROVIDER_INFO,
|
||||
} from './openai';
|
||||
import {
|
||||
getCustomOpenaiApiKey,
|
||||
getCustomOpenaiApiUrl,
|
||||
getCustomOpenaiModelName,
|
||||
} from '../config';
|
||||
import { ChatOpenAI } from '@langchain/openai';
|
||||
import { loadOllamaChatModels, loadOllamaEmbeddingModels, PROVIDER_INFO as OllamaInfo } from './ollama';
|
||||
import {
|
||||
loadOllamaChatModels,
|
||||
loadOllamaEmbeddingModels,
|
||||
PROVIDER_INFO as OllamaInfo,
|
||||
} from './ollama';
|
||||
import { loadGroqChatModels, PROVIDER_INFO as GroqInfo } from './groq';
|
||||
import { loadAnthropicChatModels, PROVIDER_INFO as AnthropicInfo } from './anthropic';
|
||||
import { loadGeminiChatModels, loadGeminiEmbeddingModels, PROVIDER_INFO as GeminiInfo } from './gemini';
|
||||
import { loadTransformersEmbeddingsModels, PROVIDER_INFO as TransformersInfo } from './transformers';
|
||||
import { loadDeepseekChatModels, PROVIDER_INFO as DeepseekInfo } from './deepseek';
|
||||
import { loadLMStudioChatModels, loadLMStudioEmbeddingsModels, PROVIDER_INFO as LMStudioInfo } from './lmstudio';
|
||||
import {
|
||||
loadAnthropicChatModels,
|
||||
PROVIDER_INFO as AnthropicInfo,
|
||||
} from './anthropic';
|
||||
import {
|
||||
loadGeminiChatModels,
|
||||
loadGeminiEmbeddingModels,
|
||||
PROVIDER_INFO as GeminiInfo,
|
||||
} from './gemini';
|
||||
import {
|
||||
loadTransformersEmbeddingsModels,
|
||||
PROVIDER_INFO as TransformersInfo,
|
||||
} from './transformers';
|
||||
import {
|
||||
loadDeepseekChatModels,
|
||||
PROVIDER_INFO as DeepseekInfo,
|
||||
} from './deepseek';
|
||||
import {
|
||||
loadLMStudioChatModels,
|
||||
loadLMStudioEmbeddingsModels,
|
||||
PROVIDER_INFO as LMStudioInfo,
|
||||
} from './lmstudio';
|
||||
|
||||
export const PROVIDER_METADATA = {
|
||||
openai: OpenAIInfo,
|
||||
@ -26,8 +52,8 @@ export const PROVIDER_METADATA = {
|
||||
lmstudio: LMStudioInfo,
|
||||
custom_openai: {
|
||||
key: 'custom_openai',
|
||||
displayName: 'Custom OpenAI'
|
||||
}
|
||||
displayName: 'Custom OpenAI',
|
||||
},
|
||||
};
|
||||
|
||||
export interface ChatModel {
|
||||
|
@ -4,7 +4,7 @@ import { ChatModel, EmbeddingModel } from '.';
|
||||
|
||||
export const PROVIDER_INFO = {
|
||||
key: 'lmstudio',
|
||||
displayName: 'LM Studio'
|
||||
displayName: 'LM Studio',
|
||||
};
|
||||
import { ChatOpenAI } from '@langchain/openai';
|
||||
import { OpenAIEmbeddings } from '@langchain/openai';
|
||||
@ -16,14 +16,12 @@ interface LMStudioModel {
|
||||
name?: string;
|
||||
}
|
||||
|
||||
const ensureV1Endpoint = (endpoint: string): string =>
|
||||
const ensureV1Endpoint = (endpoint: string): string =>
|
||||
endpoint.endsWith('/v1') ? endpoint : `${endpoint}/v1`;
|
||||
|
||||
const checkServerAvailability = async (endpoint: string): Promise<boolean> => {
|
||||
try {
|
||||
const keepAlive = getKeepAlive();
|
||||
await axios.get(`${ensureV1Endpoint(endpoint)}/models`, {
|
||||
timeout: parseInt(keepAlive) * 1000 || 5000,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
});
|
||||
return true;
|
||||
@ -34,14 +32,12 @@ const checkServerAvailability = async (endpoint: string): Promise<boolean> => {
|
||||
|
||||
export const loadLMStudioChatModels = async () => {
|
||||
const endpoint = getLMStudioApiEndpoint();
|
||||
const keepAlive = getKeepAlive();
|
||||
|
||||
|
||||
if (!endpoint) return {};
|
||||
if (!await checkServerAvailability(endpoint)) return {};
|
||||
if (!(await checkServerAvailability(endpoint))) return {};
|
||||
|
||||
try {
|
||||
const response = await axios.get(`${ensureV1Endpoint(endpoint)}/models`, {
|
||||
timeout: parseInt(keepAlive) * 1000 || 5000,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
});
|
||||
|
||||
@ -58,7 +54,7 @@ export const loadLMStudioChatModels = async () => {
|
||||
modelName: model.id,
|
||||
temperature: 0.7,
|
||||
streaming: true,
|
||||
maxRetries: 3
|
||||
maxRetries: 3,
|
||||
}) as unknown as BaseChatModel,
|
||||
};
|
||||
});
|
||||
@ -72,14 +68,12 @@ export const loadLMStudioChatModels = async () => {
|
||||
|
||||
export const loadLMStudioEmbeddingsModels = async () => {
|
||||
const endpoint = getLMStudioApiEndpoint();
|
||||
const keepAlive = getKeepAlive();
|
||||
|
||||
|
||||
if (!endpoint) return {};
|
||||
if (!await checkServerAvailability(endpoint)) return {};
|
||||
if (!(await checkServerAvailability(endpoint))) return {};
|
||||
|
||||
try {
|
||||
const response = await axios.get(`${ensureV1Endpoint(endpoint)}/models`, {
|
||||
timeout: parseInt(keepAlive) * 1000 || 5000,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
});
|
||||
|
||||
|
@ -4,7 +4,7 @@ import { ChatModel, EmbeddingModel } from '.';
|
||||
|
||||
export const PROVIDER_INFO = {
|
||||
key: 'ollama',
|
||||
displayName: 'Ollama'
|
||||
displayName: 'Ollama',
|
||||
};
|
||||
import { ChatOllama } from '@langchain/community/chat_models/ollama';
|
||||
import { OllamaEmbeddings } from '@langchain/community/embeddings/ollama';
|
||||
|
@ -4,7 +4,7 @@ import { ChatModel, EmbeddingModel } from '.';
|
||||
|
||||
export const PROVIDER_INFO = {
|
||||
key: 'openai',
|
||||
displayName: 'OpenAI'
|
||||
displayName: 'OpenAI',
|
||||
};
|
||||
import { BaseChatModel } from '@langchain/core/language_models/chat_models';
|
||||
import { Embeddings } from '@langchain/core/embeddings';
|
||||
@ -30,6 +30,18 @@ const openaiChatModels: Record<string, string>[] = [
|
||||
displayName: 'GPT-4 omni mini',
|
||||
key: 'gpt-4o-mini',
|
||||
},
|
||||
{
|
||||
displayName: 'GPT 4.1 nano',
|
||||
key: 'gpt-4.1-nano',
|
||||
},
|
||||
{
|
||||
displayName: 'GPT 4.1 mini',
|
||||
key: 'gpt-4.1-mini',
|
||||
},
|
||||
{
|
||||
displayName: 'GPT 4.1',
|
||||
key: 'gpt-4.1',
|
||||
},
|
||||
];
|
||||
|
||||
const openaiEmbeddingModels: Record<string, string>[] = [
|
||||
|
@ -2,7 +2,7 @@ import { HuggingFaceTransformersEmbeddings } from '../huggingfaceTransformer';
|
||||
|
||||
export const PROVIDER_INFO = {
|
||||
key: 'transformers',
|
||||
displayName: 'Hugging Face'
|
||||
displayName: 'Hugging Face',
|
||||
};
|
||||
|
||||
export const loadTransformersEmbeddingsModels = async () => {
|
||||
|
@ -64,7 +64,7 @@ export const getDocumentsFromLinks = async ({ links }: { links: string[] }) => {
|
||||
const splittedText = await splitter.splitText(parsedText);
|
||||
const title = res.data
|
||||
.toString('utf8')
|
||||
.match(/<title>(.*?)<\/title>/)?.[1];
|
||||
.match(/<title.*>(.*?)<\/title>/)?.[1];
|
||||
|
||||
const linkDocs = splittedText.map((text) => {
|
||||
return new Document({
|
||||
|
Reference in New Issue
Block a user