Compare commits

..

15 Commits

Author SHA1 Message Date
ItzCrazyKns
a401e67d87 Merge pull request #666 from AnotiaWang/admin-password
feat: sync changes from master branch
2025-03-08 20:08:59 +05:30
AnotiaWang
d95849e538 fix: missing MODEL_NAME in config sample 2025-03-07 23:54:53 +08:00
AnotiaWang
ec5e5b3893 Merge branch 'master' into admin-password 2025-03-07 23:54:47 +08:00
ItzCrazyKns
89b5229ce9 Merge pull request #663 from ericdachen/master
Update Readme
2025-03-05 11:11:07 +05:30
ItzCrazyKns
7756340dd9 Update README.md 2025-03-05 11:09:19 +05:30
ItzCrazyKns
bbd2e9c359 feat(readme): update warp banner 2025-03-05 11:05:25 +05:30
ItzCrazyKns
a32eb1dda3 feat(readme): lint & beautify, update anchor URL 2025-03-05 10:55:02 +05:30
Eric Chen
aa834f7f04 Update README.md 2025-03-04 14:45:10 -05:00
Eric Chen
064c0fbe42 Update README.md 2025-03-04 12:16:10 -05:00
Eric Chen
bf4cf8eaeb Update README.md 2025-03-04 12:14:17 -05:00
ItzCrazyKns
639fbd7a15 feat(chat-window): lint & beautify 2024-08-02 19:37:20 +05:30
ItzCrazyKns
a88104434d feat(copilot): respect preferences 2024-08-02 19:36:50 +05:30
ItzCrazyKns
a1e0d368c6 feat(settings): add preferences 2024-08-02 19:36:39 +05:30
ItzCrazyKns
5779701b7d feat(sidebar): respect preferences 2024-08-02 19:35:57 +05:30
ItzCrazyKns
fdfe8d1f41 feat(app): add password auth for settings 2024-08-02 19:32:38 +05:30
24 changed files with 487 additions and 872 deletions

4
.gitignore vendored
View File

@@ -2,7 +2,6 @@
node_modules/ node_modules/
npm-debug.log npm-debug.log
yarn-error.log yarn-error.log
package-lock.json
# Build output # Build output
/.next/ /.next/
@@ -38,6 +37,3 @@ Thumbs.db
# Db # Db
db.sqlite db.sqlite
/searxng /searxng
# Dev
docker-compose-dev.yaml

View File

@@ -1,7 +1,22 @@
# 🚀 Perplexica - An AI-powered search engine 🔎 <!-- omit in toc --> # 🚀 Perplexica - An AI-powered search engine 🔎 <!-- omit in toc -->
[![Discord](https://dcbadge.vercel.app/api/server/26aArMy8tT?style=flat&compact=true)](https://discord.gg/26aArMy8tT) <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/>
[![Discord](https://dcbadge.vercel.app/api/server/26aArMy8tT?style=flat&compact=true)](https://discord.gg/26aArMy8tT)
![preview](.assets/perplexica-screenshot.png?) ![preview](.assets/perplexica-screenshot.png?)

View File

@@ -4,7 +4,7 @@ services:
volumes: volumes:
- ./searxng:/etc/searxng:rw - ./searxng:/etc/searxng:rw
ports: ports:
- "4000:8080" - 4000:8080
networks: networks:
- perplexica-network - perplexica-network
restart: unless-stopped restart: unless-stopped
@@ -19,7 +19,7 @@ services:
depends_on: depends_on:
- searxng - searxng
ports: ports:
- "3001:3001" - 3001:3001
volumes: volumes:
- backend-dbstore:/home/perplexica/data - backend-dbstore:/home/perplexica/data
- uploads:/home/perplexica/uploads - uploads:/home/perplexica/uploads
@@ -41,7 +41,7 @@ services:
depends_on: depends_on:
- perplexica-backend - perplexica-backend
ports: ports:
- "3000:3000" - 3000:3000
networks: networks:
- perplexica-network - perplexica-network
restart: unless-stopped restart: unless-stopped

View File

@@ -30,8 +30,8 @@
"@iarna/toml": "^2.2.5", "@iarna/toml": "^2.2.5",
"@langchain/anthropic": "^0.2.3", "@langchain/anthropic": "^0.2.3",
"@langchain/community": "^0.2.16", "@langchain/community": "^0.2.16",
"@langchain/google-genai": "^0.0.23",
"@langchain/openai": "^0.0.25", "@langchain/openai": "^0.0.25",
"@langchain/google-genai": "^0.0.23",
"@xenova/transformers": "^2.17.1", "@xenova/transformers": "^2.17.1",
"axios": "^1.6.8", "axios": "^1.6.8",
"better-sqlite3": "^11.0.0", "better-sqlite3": "^11.0.0",

View File

@@ -1,14 +1,12 @@
[GENERAL] [GENERAL]
PORT = 3001 # Port to run the server on PORT = 3001 # Port to run the server on
SIMILARITY_MEASURE = "cosine" # "cosine" or "dot" SIMILARITY_MEASURE = "cosine" # "cosine" or "dot"
CONFIG_PASSWORD = "lorem_ipsum" # Password to access config
DISCOVER_ENABLED = true
LIBRARY_ENABLED = true
COPILOT_ENABLED = true
KEEP_ALIVE = "5m" # How long to keep Ollama models loaded into memory. (Instead of using -1 use "-1m") KEEP_ALIVE = "5m" # How long to keep Ollama models loaded into memory. (Instead of using -1 use "-1m")
[SEARCH_ENGINE_BACKENDS] # "google" | "searxng" | "bing" | "brave" | "yacy"
SEARCH = "searxng"
IMAGE = "searxng"
VIDEO = "searxng"
NEWS = "searxng"
[MODELS.OPENAI] [MODELS.OPENAI]
API_KEY = "" API_KEY = ""
@@ -24,22 +22,10 @@ API_KEY = ""
[MODELS.CUSTOM_OPENAI] [MODELS.CUSTOM_OPENAI]
API_KEY = "" API_KEY = ""
API_URL = "" API_URL = ""
MODEL_NAME = ""
[MODELS.OLLAMA] [MODELS.OLLAMA]
API_URL = "" # Ollama API URL - http://host.docker.internal:11434 API_URL = "" # Ollama API URL - http://host.docker.internal:11434
[SEARCH_ENGINES.GOOGLE] [API_ENDPOINTS]
API_KEY = "" SEARXNG = "http://localhost:32768" # SearxNG API URL
CSE_ID = ""
[SEARCH_ENGINES.SEARXNG]
ENDPOINT = ""
[SEARCH_ENGINES.BING]
SUBSCRIPTION_KEY = ""
[SEARCH_ENGINES.BRAVE]
API_KEY = ""
[SEARCH_ENGINES.YACY]
ENDPOINT = ""

View File

@@ -15,5 +15,3 @@ server:
engines: engines:
- name: wolframalpha - name: wolframalpha
disabled: false disabled: false
- name: qwant
disabled: true

View File

@@ -7,12 +7,7 @@ import { PromptTemplate } from '@langchain/core/prompts';
import formatChatHistoryAsString from '../utils/formatHistory'; import formatChatHistoryAsString from '../utils/formatHistory';
import { BaseMessage } from '@langchain/core/messages'; import { BaseMessage } from '@langchain/core/messages';
import { StringOutputParser } from '@langchain/core/output_parsers'; import { StringOutputParser } from '@langchain/core/output_parsers';
import { searchSearxng } from '../lib/searchEngines/searxng'; import { searchSearxng } from '../lib/searxng';
import { searchGooglePSE } from '../lib/searchEngines/google_pse';
import { searchBraveAPI } from '../lib/searchEngines/brave';
import { searchYaCy } from '../lib/searchEngines/yacy';
import { searchBingAPI } from '../lib/searchEngines/bing';
import { getImageSearchEngineBackend } from '../config';
import type { BaseChatModel } from '@langchain/core/language_models/chat_models'; import type { BaseChatModel } from '@langchain/core/language_models/chat_models';
const imageSearchChainPrompt = ` const imageSearchChainPrompt = `
@@ -41,95 +36,6 @@ type ImageSearchChainInput = {
query: string; query: string;
}; };
async function performImageSearch(query: string) {
const searchEngine = getImageSearchEngineBackend();
let images = [];
switch (searchEngine) {
case 'google': {
const googleResult = await searchGooglePSE(query);
images = googleResult.results.map((result) => {
if (result.img_src && result.url && result.title) {
return {
img_src: result.img_src,
url: result.url,
title: result.title,
source: result.displayLink
};
}
}).filter(Boolean);
break;
}
case 'searxng': {
const searxResult = await searchSearxng(query, {
engines: ['google images', 'bing images'],
pageno: 1,
});
searxResult.results.forEach((result) => {
if (result.img_src && result.url && result.title) {
images.push({
img_src: result.img_src,
url: result.url,
title: result.title,
});
}
});
break;
}
case 'brave': {
const braveResult = await searchBraveAPI(query);
images = braveResult.results.map((result) => {
if (result.img_src && result.url && result.title) {
return {
img_src: result.img_src,
url: result.url,
title: result.title,
source: result.url
};
}
}).filter(Boolean);
break;
}
case 'yacy': {
const yacyResult = await searchYaCy(query);
images = yacyResult.results.map((result) => {
if (result.img_src && result.url && result.title) {
return {
img_src: result.img_src,
url: result.url,
title: result.title,
source: result.url
}
}
}).filter(Boolean);
break;
}
case 'bing': {
const bingResult = await searchBingAPI(query);
images = bingResult.results.map((result) => {
if (result.img_src && result.url && result.title) {
return {
img_src: result.img_src,
url: result.url,
title: result.title,
source: result.url
}
}
}).filter(Boolean);
break;
}
default:
throw new Error(`Unknown search engine ${searchEngine}`);
}
return images;
}
const strParser = new StringOutputParser(); const strParser = new StringOutputParser();
const createImageSearchChain = (llm: BaseChatModel) => { const createImageSearchChain = (llm: BaseChatModel) => {
@@ -146,7 +52,22 @@ const createImageSearchChain = (llm: BaseChatModel) => {
llm, llm,
strParser, strParser,
RunnableLambda.from(async (input: string) => { RunnableLambda.from(async (input: string) => {
const images = await performImageSearch(input); const res = await searchSearxng(input, {
engines: ['bing images', 'google images'],
});
const images = [];
res.results.forEach((result) => {
if (result.img_src && result.url && result.title) {
images.push({
img_src: result.img_src,
url: result.url,
title: result.title,
});
}
});
return images.slice(0, 10); return images.slice(0, 10);
}), }),
]); ]);

View File

@@ -7,30 +7,26 @@ import { PromptTemplate } from '@langchain/core/prompts';
import formatChatHistoryAsString from '../utils/formatHistory'; import formatChatHistoryAsString from '../utils/formatHistory';
import { BaseMessage } from '@langchain/core/messages'; import { BaseMessage } from '@langchain/core/messages';
import { StringOutputParser } from '@langchain/core/output_parsers'; import { StringOutputParser } from '@langchain/core/output_parsers';
import { searchSearxng } from '../lib/searchEngines/searxng'; import { searchSearxng } from '../lib/searxng';
import { searchGooglePSE } from '../lib/searchEngines/google_pse';
import { searchBraveAPI } from '../lib/searchEngines/brave';
import { searchBingAPI } from '../lib/searchEngines/bing';
import { getVideoSearchEngineBackend } from '../config';
import type { BaseChatModel } from '@langchain/core/language_models/chat_models'; import type { BaseChatModel } from '@langchain/core/language_models/chat_models';
const VideoSearchChainPrompt = ` const VideoSearchChainPrompt = `
You will be given a conversation below and a follow up question. You need to rephrase the follow-up question so it is a standalone question that can be used by the LLM to search Youtube for videos. You will be given a conversation below and a follow up question. You need to rephrase the follow-up question so it is a standalone question that can be used by the LLM to search Youtube for videos.
You need to make sure the rephrased question agrees with the conversation and is relevant to the conversation. You need to make sure the rephrased question agrees with the conversation and is relevant to the conversation.
Example: Example:
1. Follow up question: How does a car work? 1. Follow up question: How does a car work?
Rephrased: How does a car work? Rephrased: How does a car work?
2. Follow up question: What is the theory of relativity? 2. Follow up question: What is the theory of relativity?
Rephrased: What is theory of relativity Rephrased: What is theory of relativity
3. Follow up question: How does an AC work? 3. Follow up question: How does an AC work?
Rephrased: How does an AC work Rephrased: How does an AC work
Conversation: Conversation:
{chat_history} {chat_history}
Follow up question: {query} Follow up question: {query}
Rephrased question: Rephrased question:
`; `;
@@ -42,95 +38,6 @@ type VideoSearchChainInput = {
const strParser = new StringOutputParser(); const strParser = new StringOutputParser();
async function performVideoSearch(query: string) {
const searchEngine = getVideoSearchEngineBackend();
const youtubeQuery = `${query} site:youtube.com`;
let videos = [];
switch (searchEngine) {
case 'google': {
const googleResult = await searchGooglePSE(youtubeQuery);
googleResult.results.forEach((result) => { // Use .results instead of .originalres
if (result.img_src && result.url && result.title) {
const videoId = new URL(result.url).searchParams.get('v');
videos.push({
img_src: result.img_src,
url: result.url,
title: result.title,
iframe_src: videoId ? `https://www.youtube.com/embed/${videoId}` : null
});
}
});
break;
}
case 'searxng': {
const searxResult = await searchSearxng(query, {
engines: ['youtube'],
});
searxResult.results.forEach((result) => {
if (
result.thumbnail &&
result.url &&
result.title &&
result.iframe_src
) {
videos.push({
img_src: result.thumbnail,
url: result.url,
title: result.title,
iframe_src: result.iframe_src,
});
}
});
break;
}
case 'brave': {
const braveResult = await searchBraveAPI(youtubeQuery);
braveResult.results.forEach((result) => {
if (result.img_src && result.url && result.title) {
const videoId = new URL(result.url).searchParams.get('v');
videos.push({
img_src: result.img_src,
url: result.url,
title: result.title,
iframe_src: videoId ? `https://www.youtube.com/embed/${videoId}` : null
});
}
});
break;
}
case 'yacy': {
console.log('Not available for yacy');
videos = [];
break;
}
case 'bing': {
const bingResult = await searchBingAPI(youtubeQuery);
bingResult.results.forEach((result) => {
if (result.img_src && result.url && result.title) {
const videoId = new URL(result.url).searchParams.get('v');
videos.push({
img_src: result.img_src,
url: result.url,
title: result.title,
iframe_src: videoId ? `https://www.youtube.com/embed/${videoId}` : null
});
}
});
break;
}
default:
throw new Error(`Unknown search engine ${searchEngine}`);
}
return videos;
}
const createVideoSearchChain = (llm: BaseChatModel) => { const createVideoSearchChain = (llm: BaseChatModel) => {
return RunnableSequence.from([ return RunnableSequence.from([
RunnableMap.from({ RunnableMap.from({
@@ -145,7 +52,28 @@ const createVideoSearchChain = (llm: BaseChatModel) => {
llm, llm,
strParser, strParser,
RunnableLambda.from(async (input: string) => { RunnableLambda.from(async (input: string) => {
const videos = await performVideoSearch(input); const res = await searchSearxng(input, {
engines: ['youtube'],
});
const videos = [];
res.results.forEach((result) => {
if (
result.thumbnail &&
result.url &&
result.title &&
result.iframe_src
) {
videos.push({
img_src: result.thumbnail,
url: result.url,
title: result.title,
iframe_src: result.iframe_src,
});
}
});
return videos.slice(0, 10); return videos.slice(0, 10);
}), }),
]); ]);
@@ -159,4 +87,4 @@ const handleVideoSearch = (
return VideoSearchChain.invoke(input); return VideoSearchChain.invoke(input);
}; };
export default handleVideoSearch; export default handleVideoSearch;

View File

@@ -8,14 +8,12 @@ interface Config {
GENERAL: { GENERAL: {
PORT: number; PORT: number;
SIMILARITY_MEASURE: string; SIMILARITY_MEASURE: string;
CONFIG_PASSWORD: string;
DISCOVER_ENABLED: boolean;
LIBRARY_ENABLED: boolean;
COPILOT_ENABLED: boolean;
KEEP_ALIVE: string; KEEP_ALIVE: string;
}; };
SEARCH_ENGINE_BACKENDS: {
SEARCH: string;
IMAGE: string;
VIDEO: string;
NEWS: string;
}
MODELS: { MODELS: {
OPENAI: { OPENAI: {
API_KEY: string; API_KEY: string;
@@ -38,23 +36,8 @@ interface Config {
MODEL_NAME: string; MODEL_NAME: string;
}; };
}; };
SEARCH_ENGINES: { API_ENDPOINTS: {
GOOGLE: { SEARXNG: string;
API_KEY: string;
CSE_ID: string;
};
SEARXNG: {
ENDPOINT: string;
};
BING: {
SUBSCRIPTION_KEY: string;
};
BRAVE: {
API_KEY: string;
};
YACY: {
ENDPOINT: string;
};
}; };
} }
@@ -72,6 +55,14 @@ export const getPort = () => loadConfig().GENERAL.PORT;
export const getSimilarityMeasure = () => export const getSimilarityMeasure = () =>
loadConfig().GENERAL.SIMILARITY_MEASURE; loadConfig().GENERAL.SIMILARITY_MEASURE;
export const getConfigPassword = () => loadConfig().GENERAL.CONFIG_PASSWORD;
export const isDiscoverEnabled = () => loadConfig().GENERAL.DISCOVER_ENABLED;
export const isLibraryEnabled = () => loadConfig().GENERAL.LIBRARY_ENABLED;
export const isCopilotEnabled = () => loadConfig().GENERAL.COPILOT_ENABLED;
export const getKeepAlive = () => loadConfig().GENERAL.KEEP_ALIVE; export const getKeepAlive = () => loadConfig().GENERAL.KEEP_ALIVE;
export const getOpenaiApiKey = () => loadConfig().MODELS.OPENAI.API_KEY; export const getOpenaiApiKey = () => loadConfig().MODELS.OPENAI.API_KEY;
@@ -82,31 +73,8 @@ export const getAnthropicApiKey = () => loadConfig().MODELS.ANTHROPIC.API_KEY;
export const getGeminiApiKey = () => loadConfig().MODELS.GEMINI.API_KEY; export const getGeminiApiKey = () => loadConfig().MODELS.GEMINI.API_KEY;
export const getSearchEngineBackend = () =>
loadConfig().SEARCH_ENGINE_BACKENDS.SEARCH;
export const getImageSearchEngineBackend = () =>
loadConfig().SEARCH_ENGINE_BACKENDS.IMAGE || getSearchEngineBackend();
export const getVideoSearchEngineBackend = () =>
loadConfig().SEARCH_ENGINE_BACKENDS.VIDEO || getSearchEngineBackend();
export const getNewsSearchEngineBackend = () =>
loadConfig().SEARCH_ENGINE_BACKENDS.NEWS || getSearchEngineBackend();
export const getGoogleApiKey = () => loadConfig().SEARCH_ENGINES.GOOGLE.API_KEY;
export const getGoogleCseId = () => loadConfig().SEARCH_ENGINES.GOOGLE.CSE_ID;
export const getBraveApiKey = () => loadConfig().SEARCH_ENGINES.BRAVE.API_KEY;
export const getBingSubscriptionKey = () =>
loadConfig().SEARCH_ENGINES.BING.SUBSCRIPTION_KEY;
export const getYacyJsonEndpoint = () => loadConfig().SEARCH_ENGINES.YACY.ENDPOINT;
export const getSearxngApiEndpoint = () => export const getSearxngApiEndpoint = () =>
process.env.SEARXNG_API_URL || loadConfig().SEARCH_ENGINES.SEARXNG.ENDPOINT; process.env.SEARXNG_API_URL || loadConfig().API_ENDPOINTS.SEARXNG;
export const getOllamaApiEndpoint = () => loadConfig().MODELS.OLLAMA.API_URL; export const getOllamaApiEndpoint = () => loadConfig().MODELS.OLLAMA.API_URL;

View File

@@ -1,102 +0,0 @@
import axios from 'axios';
import { getBingSubscriptionKey } from '../../config';
interface BingAPISearchResult {
_type: string;
name: string;
url: string;
displayUrl: string;
snippet?: string;
dateLastCrawled?: string;
thumbnailUrl?: string;
contentUrl?: string;
hostPageUrl?: string;
width?: number;
height?: number;
accentColor?: string;
contentSize?: string;
datePublished?: string;
encodingFormat?: string;
hostPageDisplayUrl?: string;
id?: string;
isLicensed?: boolean;
isFamilyFriendly?: boolean;
language?: string;
mediaUrl?: string;
motionThumbnailUrl?: string;
publisher?: string;
viewCount?: number;
webSearchUrl?: string;
primaryImageOfPage?: {
thumbnailUrl?: string;
width?: number;
height?: number;
};
video?: {
allowHttpsEmbed?: boolean;
embedHtml?: string;
allowMobileEmbed?: boolean;
viewCount?: number;
duration?: string;
};
image?: {
thumbnail?: {
contentUrl?: string;
width?: number;
height?: number;
};
imageInsightsToken?: string;
imageId?: string;
};
}
export const searchBingAPI = async (query: string) => {
try {
const bingApiKey = await getBingSubscriptionKey();
const url = new URL(`https://api.cognitive.microsoft.com/bing/v7.0/search`);
url.searchParams.append('q', query);
url.searchParams.append('responseFilter', 'Webpages,Images,Videos');
const res = await axios.get(url.toString(), {
headers: {
'Ocp-Apim-Subscription-Key': bingApiKey,
'Accept': 'application/json'
}
});
if (res.data.error) {
throw new Error(`Bing API Error: ${res.data.error.message}`);
}
const originalres = res.data;
// Extract web, image, and video results
const webResults = originalres.webPages?.value || [];
const imageResults = originalres.images?.value || [];
const videoResults = originalres.videos?.value || [];
const results = webResults.map((item: BingAPISearchResult) => ({
title: item.name,
url: item.url,
content: item.snippet,
img_src: item.primaryImageOfPage?.thumbnailUrl
|| imageResults.find((img: any) => img.hostPageUrl === item.url)?.thumbnailUrl
|| videoResults.find((vid: any) => vid.hostPageUrl === item.url)?.thumbnailUrl,
...(item.video && {
videoData: {
duration: item.video.duration,
embedUrl: item.video.embedHtml?.match(/src="(.*?)"/)?.[1]
},
publisher: item.publisher,
datePublished: item.datePublished
})
}));
return { results, originalres };
} catch (error) {
const errorMessage = error.response?.data
? JSON.stringify(error.response.data, null, 2)
: error.message || 'Unknown error';
throw new Error(`Bing API Error: ${errorMessage}`);
}
};

View File

@@ -1,96 +0,0 @@
import axios from 'axios';
import { getBraveApiKey } from '../../config';
interface BraveSearchResult {
title: string;
url: string;
content?: string;
img_src?: string;
age?: string;
family_friendly?: boolean;
language?: string;
video?: {
embedUrl?: string;
duration?: string;
};
rating?: {
value: number;
scale: number;
};
products?: Array<{
name: string;
price?: string;
}>;
recipe?: {
ingredients?: string[];
cookTime?: string;
};
meta?: {
fetched?: string;
lastCrawled?: string;
};
}
export const searchBraveAPI = async (
query: string,
numResults: number = 20
): Promise<{ results: BraveSearchResult[]; originalres: any }> => {
try {
const braveApiKey = await getBraveApiKey();
const url = new URL(`https://api.search.brave.com/res/v1/web/search`);
url.searchParams.append('q', query);
url.searchParams.append('count', numResults.toString());
const res = await axios.get(url.toString(), {
headers: {
'X-Subscription-Token': braveApiKey,
'Accept': 'application/json'
}
});
if (res.data.error) {
throw new Error(`Brave API Error: ${res.data.error.message}`);
}
const originalres = res.data;
const webResults = originalres.web?.results || [];
const results: BraveSearchResult[] = webResults.map((item: any) => ({
title: item.title,
url: item.url,
content: item.description,
img_src: item.thumbnail?.src || item.deep_results?.images?.[0]?.src,
age: item.age,
family_friendly: item.family_friendly,
language: item.language,
video: item.video ? {
embedUrl: item.video.embed_url,
duration: item.video.duration
} : undefined,
rating: item.rating ? {
value: item.rating.value,
scale: item.rating.scale_max
} : undefined,
products: item.deep_results?.product_cluster?.map((p: any) => ({
name: p.name,
price: p.price
})),
recipe: item.recipe ? {
ingredients: item.recipe.ingredients,
cookTime: item.recipe.cook_time
} : undefined,
meta: {
fetched: item.meta?.fetched,
lastCrawled: item.meta?.last_crawled
}
}));
return { results, originalres };
} catch (error) {
const errorMessage = error.response?.data
? JSON.stringify(error.response.data, null, 2)
: error.message || 'Unknown error';
throw new Error(`Brave API Error: ${errorMessage}`);
}
};

View File

@@ -1,84 +0,0 @@
import axios from 'axios';
import { getGoogleApiKey, getGoogleCseId } from '../../config';
interface GooglePSESearchResult {
kind: string;
title: string;
htmlTitle: string;
link: string;
displayLink: string;
snippet?: string;
htmlSnippet?: string;
cacheId?: string;
formattedUrl: string;
htmlFormattedUrl: string;
pagemap?: {
videoobject: any;
cse_thumbnail?: Array<{
src: string;
width: string;
height: string;
}>;
metatags?: Array<{
[key: string]: string;
'author'?: string;
}>;
cse_image?: Array<{
src: string;
}>;
};
fileFormat?: string;
image?: {
contextLink: string;
thumbnailLink: string;
};
mime?: string;
labels?: Array<{
name: string;
displayName: string;
}>;
}
export const searchGooglePSE = async (query: string) => {
try {
const [googleApiKey, googleCseID] = await Promise.all([
getGoogleApiKey(),
getGoogleCseId()
]);
const url = new URL(`https://www.googleapis.com/customsearch/v1`);
url.searchParams.append('q', query);
url.searchParams.append('cx', googleCseID);
url.searchParams.append('key', googleApiKey);
const res = await axios.get(url.toString());
if (res.data.error) {
throw new Error(`Google PSE Error: ${res.data.error.message}`);
}
const originalres = res.data.items;
const results = originalres.map((item: GooglePSESearchResult) => ({
title: item.title,
url: item.link,
content: item.snippet,
img_src: item.pagemap?.cse_image?.[0]?.src
|| item.pagemap?.cse_thumbnail?.[0]?.src
|| item.image?.thumbnailLink,
...(item.pagemap?.videoobject?.[0] && {
videoData: {
duration: item.pagemap.videoobject[0].duration,
embedUrl: item.pagemap.videoobject[0].embedurl
}
})
}));
return { results, originalres };
} catch (error) {
const errorMessage = error.response?.data
? JSON.stringify(error.response.data, null, 2)
: error.message || 'Unknown error';
throw new Error(`Google PSE Error: ${errorMessage}`);
}
};

View File

@@ -1,83 +0,0 @@
import axios from 'axios';
import { getYacyJsonEndpoint } from '../../config';
interface YaCySearchResult {
channels: {
title: string;
description: string;
link: string;
image: {
url: string;
title: string;
link: string;
};
startIndex: string;
itemsPerPage: string;
searchTerms: string;
items: {
title: string;
link: string;
code: string;
description: string;
pubDate: string;
image?: string;
size: string;
sizename: string;
guid: string;
faviconUrl: string;
host: string;
path: string;
file: string;
urlhash: string;
ranking: string;
}[];
navigation: {
facetname: string;
displayname: string;
type: string;
min: string;
max: string;
mean: string;
elements: {
name: string;
count: string;
modifier: string;
url: string;
}[];
}[];
}[];
}
export const searchYaCy = async (
query: string,
numResults: number = 20
) => {
try {
const yacyBaseUrl = getYacyJsonEndpoint();
const url = new URL(`${yacyBaseUrl}/yacysearch.json`);
url.searchParams.append('query', query);
url.searchParams.append('count', numResults.toString());
const res = await axios.get(url.toString());
const originalres = res.data as YaCySearchResult;
const results = originalres.channels[0].items.map(item => ({
title: item.title,
url: item.link,
content: item.description,
img_src: item.image || null,
pubDate: item.pubDate,
host: item.host,
}));
return { results, originalres };
} catch (error) {
const errorMessage = error.response?.data
? JSON.stringify(error.response.data, null, 2)
: error.message || 'Unknown error';
throw new Error(`YaCy Error: ${errorMessage}`);
}
};

View File

@@ -1,5 +1,5 @@
import axios from 'axios'; import axios from 'axios';
import { getSearxngApiEndpoint } from '../../config'; import { getSearxngApiEndpoint } from '../config';
interface SearxngSearchOptions { interface SearxngSearchOptions {
categories?: string[]; categories?: string[];

View File

@@ -10,6 +10,10 @@ import {
getGeminiApiKey, getGeminiApiKey,
getOpenaiApiKey, getOpenaiApiKey,
updateConfig, updateConfig,
getConfigPassword,
isLibraryEnabled,
isCopilotEnabled,
isDiscoverEnabled,
getCustomOpenaiApiUrl, getCustomOpenaiApiUrl,
getCustomOpenaiApiKey, getCustomOpenaiApiKey,
getCustomOpenaiModelName, getCustomOpenaiModelName,
@@ -18,8 +22,16 @@ import logger from '../utils/logger';
const router = express.Router(); const router = express.Router();
router.get('/', async (_, res) => { router.get('/', async (req, res) => {
try { try {
const authHeader = req.headers['authorization']?.split(' ')[1];
const password = getConfigPassword();
if (authHeader !== password) {
res.status(401).json({ message: 'Unauthorized' });
return;
}
const config = {}; const config = {};
const [chatModelProviders, embeddingModelProviders] = await Promise.all([ const [chatModelProviders, embeddingModelProviders] = await Promise.all([
@@ -69,9 +81,22 @@ router.get('/', async (_, res) => {
}); });
router.post('/', async (req, res) => { router.post('/', async (req, res) => {
const authHeader = req.headers['authorization']?.split(' ')[1];
const password = getConfigPassword();
if (authHeader !== password) {
res.status(401).json({ message: 'Unauthorized' });
return;
}
const config = req.body; const config = req.body;
const updatedConfig = { const updatedConfig = {
GENERAL: {
DISCOVER_ENABLED: config.isDiscoverEnabled,
LIBRARY_ENABLED: config.isLibraryEnabled,
COPILOT_ENABLED: config.isCopilotEnabled,
},
MODELS: { MODELS: {
OPENAI: { OPENAI: {
API_KEY: config.openaiApiKey, API_KEY: config.openaiApiKey,
@@ -101,4 +126,14 @@ router.post('/', async (req, res) => {
res.status(200).json({ message: 'Config updated' }); res.status(200).json({ message: 'Config updated' });
}); });
router.get('/preferences', (_, res) => {
const preferences = {
isLibraryEnabled: isLibraryEnabled(),
isCopilotEnabled: isCopilotEnabled(),
isDiscoverEnabled: isDiscoverEnabled(),
};
res.status(200).json(preferences);
});
export default router; export default router;

View File

@@ -1,125 +1,42 @@
import express from 'express'; import express from 'express';
import { searchSearxng } from '../lib/searchEngines/searxng'; import { searchSearxng } from '../lib/searxng';
import { searchGooglePSE } from '../lib/searchEngines/google_pse';
import { searchBraveAPI } from '../lib/searchEngines/brave';
import { searchYaCy } from '../lib/searchEngines/yacy';
import { searchBingAPI } from '../lib/searchEngines/bing';
import { getNewsSearchEngineBackend } from '../config';
import logger from '../utils/logger'; import logger from '../utils/logger';
const router = express.Router(); const router = express.Router();
async function performSearch(query: string, site: string) {
const searchEngine = getNewsSearchEngineBackend();
switch (searchEngine) {
case 'google': {
const googleResult = await searchGooglePSE(query);
return googleResult.originalres.map(item => {
const imageSources = [
item.pagemap?.cse_image?.[0]?.src,
item.pagemap?.cse_thumbnail?.[0]?.src,
item.pagemap?.metatags?.[0]?.['og:image'],
item.pagemap?.metatags?.[0]?.['twitter:image'],
item.pagemap?.metatags?.[0]?.['image'],
].filter(Boolean); // Remove undefined values
return {
title: item.title,
url: item.link,
content: item.snippet,
thumbnail: imageSources[0], // First available image
img_src: imageSources[0], // Same as thumbnail for consistency
iframe_src: null,
author: item.pagemap?.metatags?.[0]?.['og:site_name'] || site,
publishedDate: item.pagemap?.metatags?.[0]?.['article:published_time']
};
});
}
case 'searxng': {
const searxResult = await searchSearxng(query, {
engines: ['bing news'],
pageno: 1,
});
return searxResult.results;
}
case 'brave': {
const braveResult = await searchBraveAPI(query);
return braveResult.results.map(item => ({
title: item.title,
url: item.url,
content: item.content,
thumbnail: item.img_src,
img_src: item.img_src,
iframe_src: null,
author: item.meta?.fetched || site,
publishedDate: item.meta?.lastCrawled
}));
}
case 'yacy': {
const yacyResult = await searchYaCy(query);
return yacyResult.results.map((item) => ({
title: item.title,
url: item.url,
content: item.content,
thumbnail: item.img_src,
img_src: item.img_src,
iframe_src: null,
author: item?.host || site,
publishedDate: item?.pubDate
}))
}
case 'bing': {
const bingResult = await searchBingAPI(query);
return bingResult.results.map(item => ({
title: item.title,
url: item.url,
content: item.content,
thumbnail: item.img_src,
img_src: item.img_src,
iframe_src: null,
author: item?.publisher || site,
publishedDate: item?.datePublished
}))
}
default:
throw new Error(`Unknown search engine ${searchEngine}`);
}
}
router.get('/', async (req, res) => { router.get('/', async (req, res) => {
try { try {
const queries = [
{ site: 'businessinsider.com', topic: 'AI' },
{ site: 'www.exchangewire.com', topic: 'AI' },
{ site: 'yahoo.com', topic: 'AI' },
{ site: 'businessinsider.com', topic: 'tech' },
{ site: 'www.exchangewire.com', topic: 'tech' },
{ site: 'yahoo.com', topic: 'tech' },
];
const data = ( const data = (
await Promise.all( await Promise.all([
queries.map(async ({ site, topic }) => { searchSearxng('site:businessinsider.com AI', {
try { engines: ['bing news'],
const query = `site:${site} ${topic}`; pageno: 1,
return await performSearch(query, site); }),
} catch (error) { searchSearxng('site:www.exchangewire.com AI', {
logger.error(`Error searching ${site}: ${error.message}`); engines: ['bing news'],
return []; pageno: 1,
} }),
}) searchSearxng('site:yahoo.com AI', {
) engines: ['bing news'],
pageno: 1,
}),
searchSearxng('site:businessinsider.com tech', {
engines: ['bing news'],
pageno: 1,
}),
searchSearxng('site:www.exchangewire.com tech', {
engines: ['bing news'],
pageno: 1,
}),
searchSearxng('site:yahoo.com tech', {
engines: ['bing news'],
pageno: 1,
}),
])
) )
.map((result) => result.results)
.flat() .flat()
.sort(() => Math.random() - 0.5) .sort(() => Math.random() - 0.5);
.filter(item => item.title && item.url && item.content);
return res.json({ blogs: data }); return res.json({ blogs: data });
} catch (err: any) { } catch (err: any) {

View File

@@ -9,10 +9,33 @@ const router = express.Router();
router.get('/', async (req, res) => { router.get('/', async (req, res) => {
try { try {
const [chatModelProviders, embeddingModelProviders] = await Promise.all([ const [chatModelProvidersRaw, embeddingModelProvidersRaw] =
getAvailableChatModelProviders(), await Promise.all([
getAvailableEmbeddingModelProviders(), getAvailableChatModelProviders(),
]); getAvailableEmbeddingModelProviders(),
]);
const chatModelProviders = {};
const chatModelProvidersKeys = Object.keys(chatModelProvidersRaw);
chatModelProvidersKeys.forEach((provider) => {
chatModelProviders[provider] = {};
const models = Object.keys(chatModelProvidersRaw[provider]);
models.forEach((model) => {
chatModelProviders[provider][model] = {};
});
});
const embeddingModelProviders = {};
const embeddingModelProvidersKeys = Object.keys(embeddingModelProvidersRaw);
embeddingModelProvidersKeys.forEach((provider) => {
embeddingModelProviders[provider] = {};
const models = Object.keys(embeddingModelProvidersRaw[provider]);
models.forEach((model) => {
embeddingModelProviders[provider][model] = {};
});
});
Object.keys(chatModelProviders).forEach((provider) => { Object.keys(chatModelProviders).forEach((provider) => {
Object.keys(chatModelProviders[provider]).forEach((model) => { Object.keys(chatModelProviders[provider]).forEach((model) => {

View File

@@ -17,12 +17,7 @@ import LineListOutputParser from '../lib/outputParsers/listLineOutputParser';
import LineOutputParser from '../lib/outputParsers/lineOutputParser'; import LineOutputParser from '../lib/outputParsers/lineOutputParser';
import { getDocumentsFromLinks } from '../utils/documents'; import { getDocumentsFromLinks } from '../utils/documents';
import { Document } from 'langchain/document'; import { Document } from 'langchain/document';
import { searchSearxng } from '../lib/searchEngines/searxng'; import { searchSearxng } from '../lib/searxng';
import { searchGooglePSE } from '../lib/searchEngines/google_pse';
import { searchBingAPI } from '../lib/searchEngines/bing';
import { searchBraveAPI } from '../lib/searchEngines/brave';
import { searchYaCy } from '../lib/searchEngines/yacy';
import { getSearchEngineBackend } from '../config';
import path from 'path'; import path from 'path';
import fs from 'fs'; import fs from 'fs';
import computeSimilarity from '../utils/computeSimilarity'; import computeSimilarity from '../utils/computeSimilarity';
@@ -137,7 +132,7 @@ class MetaSearchAgent implements MetaSearchAgentType {
You are a web search summarizer, tasked with summarizing a piece of text retrieved from a web search. Your job is to summarize the You are a web search summarizer, tasked with summarizing a piece of text retrieved from a web search. Your job is to summarize the
text into a detailed, 2-4 paragraph explanation that captures the main ideas and provides a comprehensive answer to the query. text into a detailed, 2-4 paragraph explanation that captures the main ideas and provides a comprehensive answer to the query.
If the query is \"summarize\", you should provide a detailed summary of the text. If the query is a specific question, you should answer it in the summary. If the query is \"summarize\", you should provide a detailed summary of the text. If the query is a specific question, you should answer it in the summary.
- **Journalistic tone**: The summary should sound professional and journalistic, not too casual or vague. - **Journalistic tone**: The summary should sound professional and journalistic, not too casual or vague.
- **Thorough and detailed**: Ensure that every key point from the text is captured and that the summary directly answers the query. - **Thorough and detailed**: Ensure that every key point from the text is captured and that the summary directly answers the query.
- **Not too lengthy, but detailed**: The summary should be informative but not excessively long. Focus on providing detailed information in a concise format. - **Not too lengthy, but detailed**: The summary should be informative but not excessively long. Focus on providing detailed information in a concise format.
@@ -208,36 +203,10 @@ class MetaSearchAgent implements MetaSearchAgentType {
return { query: question, docs: docs }; return { query: question, docs: docs };
} else { } else {
const res = await searchSearxng(question, {
const searchEngine = getSearchEngineBackend(); language: 'en',
engines: this.config.activeEngines,
let res; });
switch (searchEngine) {
case 'searxng':
res = await searchSearxng(question, {
language: 'en',
engines: this.config.activeEngines,
});
break;
case 'google':
res = await searchGooglePSE(question);
break;
case 'bing':
res = await searchBingAPI(question);
break;
case 'brave':
res = await searchBraveAPI(question);
break;
case 'yacy':
res = await searchYaCy(question);
break;
default:
throw new Error(`Unknown search engine ${searchEngine}`);
}
if (!res?.results) {
throw new Error(`No results found for search engine: ${searchEngine}`);
}
const documents = res.results.map( const documents = res.results.map(
(result) => (result) =>

View File

@@ -5,8 +5,9 @@ import type { Embeddings } from '@langchain/core/embeddings';
import logger from '../utils/logger'; import logger from '../utils/logger';
import db from '../db'; import db from '../db';
import { chats, messages as messagesSchema } from '../db/schema'; import { chats, messages as messagesSchema } from '../db/schema';
import { eq, asc, gt, and } from 'drizzle-orm'; import { eq, gt, and } from 'drizzle-orm';
import crypto from 'crypto'; import crypto from 'crypto';
import { isLibraryEnabled } from '../config';
import { getFileDetails } from '../utils/files'; import { getFileDetails } from '../utils/files';
import MetaSearchAgent, { import MetaSearchAgent, {
MetaSearchAgentType, MetaSearchAgentType,
@@ -94,6 +95,8 @@ const handleEmitterEvents = (
let recievedMessage = ''; let recievedMessage = '';
let sources = []; let sources = [];
const libraryEnabled = isLibraryEnabled();
emitter.on('data', (data) => { emitter.on('data', (data) => {
const parsedData = JSON.parse(data); const parsedData = JSON.parse(data);
if (parsedData.type === 'response') { if (parsedData.type === 'response') {
@@ -119,18 +122,20 @@ const handleEmitterEvents = (
emitter.on('end', () => { emitter.on('end', () => {
ws.send(JSON.stringify({ type: 'messageEnd', messageId: messageId })); ws.send(JSON.stringify({ type: 'messageEnd', messageId: messageId }));
db.insert(messagesSchema) if (libraryEnabled) {
.values({ db.insert(messagesSchema)
content: recievedMessage, .values({
chatId: chatId, content: recievedMessage,
messageId: messageId, chatId: chatId,
role: 'assistant', messageId: messageId,
metadata: JSON.stringify({ role: 'assistant',
createdAt: new Date(), metadata: JSON.stringify({
...(sources && sources.length > 0 && { sources }), createdAt: new Date(),
}), ...(sources && sources.length > 0 && { sources }),
}) }),
.execute(); })
.execute();
}
}); });
emitter.on('error', (data) => { emitter.on('error', (data) => {
const parsedData = JSON.parse(data); const parsedData = JSON.parse(data);
@@ -188,6 +193,8 @@ export const handleMessage = async (
const handler: MetaSearchAgentType = const handler: MetaSearchAgentType =
searchHandlers[parsedWSMessage.focusMode]; searchHandlers[parsedWSMessage.focusMode];
const libraryEnabled = isLibraryEnabled();
if (handler) { if (handler) {
try { try {
const emitter = await handler.searchAndAnswer( const emitter = await handler.searchAndAnswer(
@@ -201,50 +208,52 @@ export const handleMessage = async (
handleEmitterEvents(emitter, ws, aiMessageId, parsedMessage.chatId); handleEmitterEvents(emitter, ws, aiMessageId, parsedMessage.chatId);
const chat = await db.query.chats.findFirst({ if (libraryEnabled) {
where: eq(chats.id, parsedMessage.chatId), const chat = await db.query.chats.findFirst({
}); where: eq(chats.id, parsedMessage.chatId),
});
if (!chat) { if (!chat) {
await db await db
.insert(chats) .insert(chats)
.values({ .values({
id: parsedMessage.chatId, id: parsedMessage.chatId,
title: parsedMessage.content, title: parsedMessage.content,
createdAt: new Date().toString(), createdAt: new Date().toString(),
focusMode: parsedWSMessage.focusMode, focusMode: parsedWSMessage.focusMode,
files: parsedWSMessage.files.map(getFileDetails), files: parsedWSMessage.files.map(getFileDetails),
}) })
.execute(); .execute();
} }
const messageExists = await db.query.messages.findFirst({ const messageExists = await db.query.messages.findFirst({
where: eq(messagesSchema.messageId, humanMessageId), where: eq(messagesSchema.messageId, humanMessageId),
}); });
if (!messageExists) { if (!messageExists) {
await db await db
.insert(messagesSchema) .insert(messagesSchema)
.values({ .values({
content: parsedMessage.content, content: parsedMessage.content,
chatId: parsedMessage.chatId, chatId: parsedMessage.chatId,
messageId: humanMessageId, messageId: humanMessageId,
role: 'user', role: 'user',
metadata: JSON.stringify({ metadata: JSON.stringify({
createdAt: new Date(), createdAt: new Date(),
}), }),
}) })
.execute(); .execute();
} else { } else {
await db await db
.delete(messagesSchema) .delete(messagesSchema)
.where( .where(
and( and(
gt(messagesSchema.id, messageExists.id), gt(messagesSchema.id, messageExists.id),
eq(messagesSchema.chatId, parsedMessage.chatId), eq(messagesSchema.chatId, parsedMessage.chatId),
), ),
) )
.execute(); .execute();
}
} }
} catch (err) { } catch (err) {
console.log(err); console.log(err);

View File

@@ -5,7 +5,31 @@ export const metadata: Metadata = {
title: 'Library - Perplexica', title: 'Library - Perplexica',
}; };
const Layout = ({ children }: { children: React.ReactNode }) => { const Layout = async ({ children }: { children: React.ReactNode }) => {
const res = await fetch(
`${process.env.NEXT_PUBLIC_API_URL}/config/preferences`,
{
method: 'GET',
headers: {
'Content-Type': 'application/json',
},
},
);
const data = await res.json();
const { isLibraryEnabled } = data;
if (!isLibraryEnabled) {
return (
<div className="flex flex-row items-center justify-center min-h-screen w-full">
<p className="text-lg dark:text-white/70 text-black/70">
Library is disabled
</p>
</div>
);
}
return <div>{children}</div>; return <div>{children}</div>;
}; };

View File

@@ -1,8 +1,9 @@
'use client'; 'use client';
import DeleteChat from '@/components/DeleteChat'; import DeleteChat from '@/components/DeleteChat';
import { cn, formatTimeDifference } from '@/lib/utils'; import { formatTimeDifference } from '@/lib/utils';
import { BookOpenText, ClockIcon, Delete, ScanEye } from 'lucide-react'; import { cn } from '@/lib/utils';
import { BookOpenText, ClockIcon } from 'lucide-react';
import Link from 'next/link'; import Link from 'next/link';
import { useEffect, useState } from 'react'; import { useEffect, useState } from 'react';

View File

@@ -112,6 +112,83 @@ const Page = () => {
const [automaticImageSearch, setAutomaticImageSearch] = useState(false); const [automaticImageSearch, setAutomaticImageSearch] = useState(false);
const [automaticVideoSearch, setAutomaticVideoSearch] = useState(false); const [automaticVideoSearch, setAutomaticVideoSearch] = useState(false);
const [savingStates, setSavingStates] = useState<Record<string, boolean>>({}); const [savingStates, setSavingStates] = useState<Record<string, boolean>>({});
const [password, setPassword] = useState('');
const [passwordSubmitted, setPasswordSubmitted] = useState(false);
const [isPasswordValid, setIsPasswordValid] = useState(true);
const handlePasswordSubmit = async () => {
setIsLoading(true);
setPasswordSubmitted(true);
const res = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/config`, {
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${password}`,
},
});
if (res.status === 401) {
setIsPasswordValid(false);
setPasswordSubmitted(false);
setIsLoading(false);
return;
} else {
setIsPasswordValid(true);
}
const data = (await res.json()) as SettingsType;
setConfig(data);
const chatModelProvidersKeys = Object.keys(data.chatModelProviders || {});
const embeddingModelProvidersKeys = Object.keys(
data.embeddingModelProviders || {},
);
const defaultChatModelProvider =
chatModelProvidersKeys.length > 0 ? chatModelProvidersKeys[0] : '';
const defaultEmbeddingModelProvider =
embeddingModelProvidersKeys.length > 0
? embeddingModelProvidersKeys[0]
: '';
const chatModelProvider =
localStorage.getItem('chatModelProvider') ||
defaultChatModelProvider ||
'';
const chatModel =
localStorage.getItem('chatModel') ||
(data.chatModelProviders &&
data.chatModelProviders[chatModelProvider]?.length > 0
? data.chatModelProviders[chatModelProvider][0].name
: undefined) ||
'';
const embeddingModelProvider =
localStorage.getItem('embeddingModelProvider') ||
defaultEmbeddingModelProvider ||
'';
const embeddingModel =
localStorage.getItem('embeddingModel') ||
(data.embeddingModelProviders &&
data.embeddingModelProviders[embeddingModelProvider]?.[0].name) ||
'';
setSelectedChatModelProvider(chatModelProvider);
setSelectedChatModel(chatModel);
setSelectedEmbeddingModelProvider(embeddingModelProvider);
setSelectedEmbeddingModel(embeddingModel);
setChatModels(data.chatModelProviders || {});
setEmbeddingModels(data.embeddingModelProviders || {});
setAutomaticImageSearch(
localStorage.getItem('autoImageSearch') === 'true',
);
setAutomaticVideoSearch(
localStorage.getItem('autoVideoSearch') === 'true',
);
setIsLoading(false);
};
useEffect(() => { useEffect(() => {
const fetchConfig = async () => { const fetchConfig = async () => {
@@ -119,6 +196,7 @@ const Page = () => {
const res = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/config`, { const res = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/config`, {
headers: { headers: {
'Content-Type': 'application/json', 'Content-Type': 'application/json',
Authorization: `Bearer ${password}`,
}, },
}); });
@@ -193,11 +271,16 @@ const Page = () => {
method: 'POST', method: 'POST',
headers: { headers: {
'Content-Type': 'application/json', 'Content-Type': 'application/json',
Authorization: `Bearer ${password}`,
}, },
body: JSON.stringify(updatedConfig), body: JSON.stringify(updatedConfig),
}, },
); );
if (response.status === 401) {
throw new Error('Unauthorized');
}
if (!response.ok) { if (!response.ok) {
throw new Error('Failed to update config'); throw new Error('Failed to update config');
} }
@@ -211,6 +294,7 @@ const Page = () => {
const res = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/config`, { const res = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/config`, {
headers: { headers: {
'Content-Type': 'application/json', 'Content-Type': 'application/json',
Authorization: `Bearer ${password}`,
}, },
}); });
@@ -376,6 +460,33 @@ const Page = () => {
/> />
</svg> </svg>
</div> </div>
) : !passwordSubmitted ? (
<div className="flex flex-col max-w-md mx-auto mt-10 p-6 bg-light-secondary dark:bg-dark-secondary border border-light-200 dark:border-dark-200 rounded-2xl">
<h2 className="text-sm text-black/80 dark:text-white/80">
Enter the password to access the settings
</h2>
<div className="flex flex-col">
<Input
type="password"
placeholder="Password"
className="mt-4"
disabled={isLoading}
onChange={(e) => setPassword(e.target.value)}
/>
</div>
{!isPasswordValid && (
<p className="text-xs text-red-500 mt-2">
Password is incorrect
</p>
)}
<button
onClick={handlePasswordSubmit}
disabled={isLoading}
className="bg-[#24A0ED] flex flex-row items-center text-xs mt-4 text-white disabled:text-white/50 hover:bg-opacity-85 transition duration-100 disabled:bg-[#ececec21] rounded-full px-4 py-2"
>
Submit
</button>
</div>
) : ( ) : (
config && ( config && (
<div className="flex flex-col space-y-6 pb-28 lg:pb-8"> <div className="flex flex-col space-y-6 pb-28 lg:pb-8">

View File

@@ -1,5 +1,6 @@
import { cn } from '@/lib/utils'; import { cn } from '@/lib/utils';
import { Switch } from '@headlessui/react'; import { Switch } from '@headlessui/react';
import { useEffect } from 'react';
const CopilotToggle = ({ const CopilotToggle = ({
copilotEnabled, copilotEnabled,
@@ -8,11 +9,33 @@ const CopilotToggle = ({
copilotEnabled: boolean; copilotEnabled: boolean;
setCopilotEnabled: (enabled: boolean) => void; setCopilotEnabled: (enabled: boolean) => void;
}) => { }) => {
const fetchAndSetCopilotEnabled = async () => {
const res = await fetch(
`${process.env.NEXT_PUBLIC_API_URL}/config/preferences`,
{
method: 'GET',
headers: {
'Content-Type': 'application/json',
},
},
);
const preferences = await res.json();
setCopilotEnabled(preferences.isCopilotEnabled);
};
useEffect(() => {
fetchAndSetCopilotEnabled();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
return ( return (
<div className="group flex flex-row items-center space-x-1 active:scale-95 duration-200 transition cursor-pointer"> <div className="group flex flex-row items-center space-x-1 active:scale-95 duration-200 transition cursor-pointer">
<Switch <Switch
checked={copilotEnabled} checked={copilotEnabled}
onChange={setCopilotEnabled} onChange={setCopilotEnabled}
disabled={true}
className="bg-light-secondary dark:bg-dark-secondary border border-light-200/70 dark:border-dark-200 relative inline-flex h-5 w-10 sm:h-6 sm:w-11 items-center rounded-full" className="bg-light-secondary dark:bg-dark-secondary border border-light-200/70 dark:border-dark-200 relative inline-flex h-5 w-10 sm:h-6 sm:w-11 items-center rounded-full"
> >
<span className="sr-only">Copilot</span> <span className="sr-only">Copilot</span>

View File

@@ -4,9 +4,15 @@ import { cn } from '@/lib/utils';
import { BookOpenText, Home, Search, SquarePen, Settings } from 'lucide-react'; import { BookOpenText, Home, Search, SquarePen, Settings } from 'lucide-react';
import Link from 'next/link'; import Link from 'next/link';
import { useSelectedLayoutSegments } from 'next/navigation'; import { useSelectedLayoutSegments } from 'next/navigation';
import React, { useState, type ReactNode } from 'react'; import React, { useEffect, useMemo, useState, type ReactNode } from 'react';
import Layout from './Layout'; import Layout from './Layout';
export type Preferences = {
isLibraryEnabled: boolean;
isDiscoverEnabled: boolean;
isCopilotEnabled: boolean;
};
const VerticalIconContainer = ({ children }: { children: ReactNode }) => { const VerticalIconContainer = ({ children }: { children: ReactNode }) => {
return ( return (
<div className="flex flex-col items-center gap-y-3 w-full">{children}</div> <div className="flex flex-col items-center gap-y-3 w-full">{children}</div>
@@ -17,6 +23,31 @@ const Sidebar = ({ children }: { children: React.ReactNode }) => {
const segments = useSelectedLayoutSegments(); const segments = useSelectedLayoutSegments();
const [isSettingsOpen, setIsSettingsOpen] = useState(false); const [isSettingsOpen, setIsSettingsOpen] = useState(false);
const [preferences, setPreferences] = useState<Preferences | null>(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
const fetchPreferences = async () => {
setLoading(true);
const res = await fetch(
`${process.env.NEXT_PUBLIC_API_URL}/config/preferences`,
{
method: 'GET',
headers: {
'Content-Type': 'application/json',
},
},
);
const data = await res.json();
setPreferences(data);
setLoading(false);
};
fetchPreferences();
}, []);
const navLinks = [ const navLinks = [
{ {
@@ -24,22 +55,44 @@ const Sidebar = ({ children }: { children: React.ReactNode }) => {
href: '/', href: '/',
active: segments.length === 0 || segments.includes('c'), active: segments.length === 0 || segments.includes('c'),
label: 'Home', label: 'Home',
show: true,
}, },
{ {
icon: Search, icon: Search,
href: '/discover', href: '/discover',
active: segments.includes('discover'), active: segments.includes('discover'),
label: 'Discover', label: 'Discover',
show: preferences?.isDiscoverEnabled,
}, },
{ {
icon: BookOpenText, icon: BookOpenText,
href: '/library', href: '/library',
active: segments.includes('library'), active: segments.includes('library'),
label: 'Library', label: 'Library',
show: preferences?.isLibraryEnabled,
}, },
]; ];
return ( return loading ? (
<div className="flex flex-row items-center justify-center h-full">
<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>
<div className="hidden lg:fixed lg:inset-y-0 lg:z-50 lg:flex lg:w-20 lg:flex-col"> <div className="hidden lg:fixed lg:inset-y-0 lg:z-50 lg:flex lg:w-20 lg:flex-col">
<div className="flex grow flex-col items-center justify-between gap-y-5 overflow-y-auto bg-light-secondary dark:bg-dark-secondary px-2 py-8"> <div className="flex grow flex-col items-center justify-between gap-y-5 overflow-y-auto bg-light-secondary dark:bg-dark-secondary px-2 py-8">
@@ -47,23 +100,26 @@ const Sidebar = ({ children }: { children: React.ReactNode }) => {
<SquarePen className="cursor-pointer" /> <SquarePen className="cursor-pointer" />
</a> </a>
<VerticalIconContainer> <VerticalIconContainer>
{navLinks.map((link, i) => ( {navLinks.map(
<Link (link, i) =>
key={i} link.show === true && (
href={link.href} <Link
className={cn( key={i}
'relative flex flex-row items-center justify-center cursor-pointer hover:bg-black/10 dark:hover:bg-white/10 duration-150 transition w-full py-2 rounded-lg', href={link.href}
link.active className={cn(
? 'text-black dark:text-white' 'relative flex flex-row items-center justify-center cursor-pointer hover:bg-black/10 dark:hover:bg-white/10 duration-150 transition w-full py-2 rounded-lg',
: 'text-black/70 dark:text-white/70', link.active
)} ? 'text-black dark:text-white'
> : 'text-black/70 dark:text-white/70',
<link.icon /> )}
{link.active && ( >
<div className="absolute right-0 -mr-2 h-full w-1 rounded-l-lg bg-black dark:bg-white" /> <link.icon />
)} {link.active && (
</Link> <div className="absolute right-0 -mr-2 h-full w-1 rounded-l-lg bg-black dark:bg-white" />
))} )}
</Link>
),
)}
</VerticalIconContainer> </VerticalIconContainer>
<Link href="/settings"> <Link href="/settings">