0
v-firecrawl/apps/api/src/controllers/search.ts

166 lines
4.5 KiB
TypeScript
Raw Normal View History

2024-04-23 18:28:32 -04:00
import { Request, Response } from "express";
import { WebScraperDataProvider } from "../scraper/WebScraper";
import { billTeam, checkTeamCredits } from "../services/billing/credit_billing";
import { authenticateUser } from "./auth";
import { RateLimiterMode } from "../types";
import { logJob } from "../services/logging/log_job";
2024-04-23 18:44:11 -04:00
import { PageOptions, SearchOptions } from "../lib/entities";
2024-04-23 19:45:06 -04:00
import { search } from "../search";
2024-04-23 20:05:58 -04:00
import { isUrlBlocked } from "../scraper/WebScraper/utils/blocklist";
2024-04-23 18:28:32 -04:00
export async function searchHelper(
req: Request,
team_id: string,
crawlerOptions: any,
2024-04-23 18:44:11 -04:00
pageOptions: PageOptions,
searchOptions: SearchOptions
2024-04-23 18:28:32 -04:00
): Promise<{
success: boolean;
error?: string;
data?: any;
returnCode: number;
}> {
const query = req.body.query;
2024-04-23 18:44:11 -04:00
const advanced = false;
2024-04-23 18:28:32 -04:00
if (!query) {
return { success: false, error: "Query is required", returnCode: 400 };
}
2024-04-23 19:45:06 -04:00
const tbs = searchOptions.tbs ?? null;
const filter = searchOptions.filter ?? null;
let res = await search({
query: query,
advanced: advanced,
num_results: searchOptions.limit ?? 7,
tbs: tbs,
filter: filter,
lang: searchOptions.lang ?? "en",
country: searchOptions.country ?? "us",
location: searchOptions.location,
});
2024-04-23 18:28:32 -04:00
let justSearch = pageOptions.fetchPageContent === false;
2024-04-23 18:44:11 -04:00
if (justSearch) {
2024-04-23 18:28:32 -04:00
return { success: true, data: res, returnCode: 200 };
}
2024-04-24 13:11:01 -04:00
res = res.filter((r) => !isUrlBlocked(r.url));
2024-04-23 20:06:48 -04:00
2024-04-23 19:45:06 -04:00
if (res.length === 0) {
2024-04-23 18:28:32 -04:00
return { success: true, error: "No search results found", returnCode: 200 };
}
2024-04-23 20:05:58 -04:00
// filter out social media links
2024-04-23 18:28:32 -04:00
const a = new WebScraperDataProvider();
await a.setOptions({
mode: "single_urls",
2024-04-24 13:11:01 -04:00
urls: res.map((r) => r.url),
2024-04-23 18:28:32 -04:00
crawlerOptions: {
...crawlerOptions,
},
2024-04-23 18:44:11 -04:00
pageOptions: {
...pageOptions,
onlyMainContent: pageOptions?.onlyMainContent ?? true,
fetchPageContent: pageOptions?.fetchPageContent ?? true,
fallback: false,
},
2024-04-23 18:28:32 -04:00
});
const docs = await a.getDocuments(true);
2024-04-23 18:44:11 -04:00
if (docs.length === 0) {
2024-04-23 18:28:32 -04:00
return { success: true, error: "No search results found", returnCode: 200 };
}
// make sure doc.content is not empty
const filteredDocs = docs.filter(
(doc: { content?: string }) => doc.content && doc.content.trim().length > 0
);
if (filteredDocs.length === 0) {
return { success: true, error: "No page found", returnCode: 200 };
}
2024-04-23 18:44:11 -04:00
const { success, credit_usage } = await billTeam(
team_id,
filteredDocs.length
);
if (!success) {
return {
success: false,
error:
"Failed to bill team. Insufficient credits or subscription not found.",
returnCode: 402,
};
}
2024-04-23 18:28:32 -04:00
return {
success: true,
data: filteredDocs,
returnCode: 200,
};
}
export async function searchController(req: Request, res: Response) {
try {
// make sure to authenticate user first, Bearer <token>
const { success, team_id, error, status } = await authenticateUser(
req,
res,
RateLimiterMode.Search
);
if (!success) {
return res.status(status).json({ error });
}
const crawlerOptions = req.body.crawlerOptions ?? {};
2024-04-23 18:44:11 -04:00
const pageOptions = req.body.pageOptions ?? {
onlyMainContent: true,
fetchPageContent: true,
fallback: false,
};
2024-04-23 18:28:32 -04:00
const origin = req.body.origin ?? "api";
2024-04-23 18:44:11 -04:00
const searchOptions = req.body.searchOptions ?? { limit: 7 };
2024-04-23 18:28:32 -04:00
try {
const { success: creditsCheckSuccess, message: creditsCheckMessage } =
await checkTeamCredits(team_id, 1);
if (!creditsCheckSuccess) {
return res.status(402).json({ error: "Insufficient credits" });
}
} catch (error) {
console.error(error);
return res.status(500).json({ error: "Internal server error" });
}
const startTime = new Date().getTime();
const result = await searchHelper(
req,
team_id,
crawlerOptions,
2024-04-23 18:44:11 -04:00
pageOptions,
searchOptions
2024-04-23 18:28:32 -04:00
);
const endTime = new Date().getTime();
const timeTakenInSeconds = (endTime - startTime) / 1000;
logJob({
success: result.success,
message: result.error,
2024-04-24 13:23:26 -04:00
num_docs: result.data.length,
docs: result.data,
2024-04-23 18:28:32 -04:00
time_taken: timeTakenInSeconds,
team_id: team_id,
mode: "search",
2024-04-24 13:23:26 -04:00
url: req.body.query,
2024-04-23 18:28:32 -04:00
crawlerOptions: crawlerOptions,
pageOptions: pageOptions,
origin: origin,
});
return res.status(result.returnCode).json(result);
} catch (error) {
console.error(error);
return res.status(500).json({ error: error.message });
}
}