Skip to content

Commit

Permalink
Merge pull request #23 from sjdonado/feat/17-select-default-adapter
Browse files Browse the repository at this point in the history
Feat/17 select default adapter
  • Loading branch information
sjdonado authored Jul 15, 2024
2 parents cf14ba9 + 721aea9 commit a7ad3fc
Show file tree
Hide file tree
Showing 22 changed files with 161 additions and 93 deletions.
6 changes: 3 additions & 3 deletions src/adapters/apple-music.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { ENV } from '~/config/env';
import { MetadataType, ServiceType } from '~/config/enum';
import { MetadataType, Adapter } from '~/config/enum';
import { RESPONSE_COMPARE_MIN_SCORE } from '~/config/constants';

import HttpClient from '~/utils/http-client';
Expand Down Expand Up @@ -31,7 +31,7 @@ export async function getAppleMusicLink(query: string, metadata: SearchMetadata)
// apple music does not support x-www-form-urlencoded encoding
const params = `term=${encodeURIComponent(query)}`;

const url = new URL(`${ENV.services.appleMusic.apiUrl}/search?${params}`);
const url = new URL(`${ENV.adapters.appleMusic.apiUrl}/search?${params}`);

const cache = await getCachedSearchResultLink(url);
if (cache) {
Expand All @@ -50,7 +50,7 @@ export async function getAppleMusicLink(query: string, metadata: SearchMetadata)
const { href, score } = getResultWithBestScore(doc, listElements, query);

const searchResultLink = {
type: ServiceType.AppleMusic,
type: Adapter.AppleMusic,
url: href,
isVerified: score > RESPONSE_COMPARE_MIN_SCORE,
} as SearchResultLink;
Expand Down
6 changes: 3 additions & 3 deletions src/adapters/deezer.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { ENV } from '~/config/env';
import { MetadataType, ServiceType } from '~/config/enum';
import { MetadataType, Adapter } from '~/config/enum';
import { ADAPTERS_QUERY_LIMIT } from '~/config/constants';

import HttpClient from '~/utils/http-client';
Expand Down Expand Up @@ -41,7 +41,7 @@ export async function getDeezerLink(query: string, metadata: SearchMetadata) {
limit: String(ADAPTERS_QUERY_LIMIT),
});

const url = new URL(`${ENV.services.deezer.apiUrl}/${searchType}`);
const url = new URL(`${ENV.adapters.deezer.apiUrl}/${searchType}`);
url.search = params.toString();

const cache = await getCachedSearchResultLink(url);
Expand All @@ -60,7 +60,7 @@ export async function getDeezerLink(query: string, metadata: SearchMetadata) {
const [{ title, name, link }] = response.data;

const searchResultLink = {
type: ServiceType.Deezer,
type: Adapter.Deezer,
url: link,
isVerified: responseMatchesQuery(title ?? name ?? '', query),
} as SearchResultLink;
Expand Down
8 changes: 4 additions & 4 deletions src/adapters/soundcloud.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { ENV } from '~/config/env';
import { MetadataType, ServiceType } from '~/config/enum';
import { MetadataType, Adapter } from '~/config/enum';
import { RESPONSE_COMPARE_MIN_SCORE } from '~/config/constants';

import HttpClient from '~/utils/http-client';
Expand All @@ -19,7 +19,7 @@ export async function getSoundCloudLink(query: string, metadata: SearchMetadata)
q: query,
});

const url = new URL(`${ENV.services.soundCloud.baseUrl}/search`);
const url = new URL(`${ENV.adapters.soundCloud.baseUrl}/search`);
url.search = params.toString();

const cache = await getCachedSearchResultLink(url);
Expand All @@ -45,8 +45,8 @@ export async function getSoundCloudLink(query: string, metadata: SearchMetadata)
}

const searchResultLink = {
type: ServiceType.SoundCloud,
url: `${ENV.services.soundCloud.baseUrl}${href}`,
type: Adapter.SoundCloud,
url: `${ENV.adapters.soundCloud.baseUrl}${href}`,
isVerified: true,
} as SearchResultLink;

Expand Down
12 changes: 6 additions & 6 deletions src/adapters/spotify.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import {
SPOTIFY_LINK_DESKTOP_REGEX,
SPOTIFY_LINK_MOBILE_REGEX,
} from '~/config/constants';
import { MetadataType, ServiceType } from '~/config/enum';
import { MetadataType, Adapter } from '~/config/enum';

import HttpClient from '~/utils/http-client';
import { logger } from '~/utils/logger';
Expand Down Expand Up @@ -61,7 +61,7 @@ export async function getSpotifyLink(query: string, metadata: SearchMetadata) {
limit: String(ADAPTERS_QUERY_LIMIT),
});

const url = new URL(ENV.services.spotify.apiUrl);
const url = new URL(ENV.adapters.spotify.apiUrl);
url.search = params.toString();

const cache = await getCachedSearchResultLink(url);
Expand All @@ -86,7 +86,7 @@ export async function getSpotifyLink(query: string, metadata: SearchMetadata) {
const { name, external_urls } = data.items[0];

const searchResultLink = {
type: ServiceType.Spotify,
type: Adapter.Spotify,
url: external_urls.spotify,
isVerified: responseMatchesQuery(name ?? '', query),
} as SearchResultLink;
Expand All @@ -103,7 +103,7 @@ export async function fetchSpotifyMetadata(spotifyLink: string) {
let url = spotifyLink;

const spotifyHeaders = {
'User-Agent': `${ENV.services.spotify.clientVersion} (Macintosh; Apple Silicon)`,
'User-Agent': `${ENV.adapters.spotify.clientVersion} (Macintosh; Apple Silicon)`,
};

let html = await HttpClient.get<string>(url, {
Expand Down Expand Up @@ -145,7 +145,7 @@ export async function getOrUpdateSpotifyAccessToken() {
});

const response = await HttpClient.post<SpotifyAuthResponse>(
ENV.services.spotify.authUrl,
ENV.adapters.spotify.authUrl,
data,
{
headers: {
Expand All @@ -154,7 +154,7 @@ export async function getOrUpdateSpotifyAccessToken() {
Authorization:
'Basic ' +
Buffer.from(
ENV.services.spotify.clientId + ':' + ENV.services.spotify.clientSecret
ENV.adapters.spotify.clientId + ':' + ENV.adapters.spotify.clientSecret
).toString('base64'),
},
}
Expand Down
6 changes: 3 additions & 3 deletions src/adapters/tidal.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { ENV } from '~/config/env';
import { ServiceType } from '~/config/enum';
import { Adapter } from '~/config/enum';

import { SearchResultLink } from '~/services/search';

Expand All @@ -8,11 +8,11 @@ export function getTidalLink(query: string) {
q: query,
});

const url = new URL(`${ENV.services.tidal.baseUrl}/search`);
const url = new URL(`${ENV.adapters.tidal.baseUrl}/search`);
url.search = params.toString();

return {
type: ServiceType.Tidal,
type: Adapter.Tidal,
url: url.toString(),
} as SearchResultLink;
}
10 changes: 5 additions & 5 deletions src/adapters/youtube.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { ENV } from '~/config/env';
import { MetadataType, ServiceType } from '~/config/enum';
import { MetadataType, Adapter } from '~/config/enum';

import { logger } from '~/utils/logger';

Expand All @@ -23,7 +23,7 @@ export async function getYouTubeLink(query: string, metadata: SearchMetadata) {
q: `${query} ${YOUTUBE_SEARCH_TYPES[metadata.type]}`,
});

const url = new URL(ENV.services.youTube.musicUrl);
const url = new URL(ENV.adapters.youTube.musicUrl);
url.search = params.toString();

const cache = await getCachedSearchResultLink(url);
Expand All @@ -40,7 +40,7 @@ export async function getYouTubeLink(query: string, metadata: SearchMetadata) {
secure: true,
};

const cookies = ENV.services.youTube.cookies.split(';').map(cookie => {
const cookies = ENV.adapters.youTube.cookies.split(';').map(cookie => {
const [name, value] = cookie.split('=');
return {
...youtubeCookie,
Expand All @@ -60,7 +60,7 @@ export async function getYouTubeLink(query: string, metadata: SearchMetadata) {
}

const searchResultLink = {
type: ServiceType.YouTube,
type: Adapter.YouTube,
url: link,
isVerified: true,
} as SearchResultLink;
Expand All @@ -78,7 +78,7 @@ export async function fetchYoutubeMetadata(youtubeLink: string) {

const html = await HttpClient.get<string>(youtubeLink, {
headers: {
Cookie: ENV.services.youTube.cookies,
Cookie: ENV.adapters.youTube.cookies,
},
});

Expand Down
2 changes: 1 addition & 1 deletion src/config/enum.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
export enum ServiceType {
export enum Adapter {
Spotify = 'spotify',
YouTube = 'youTube',
AppleMusic = 'appleMusic',
Expand Down
2 changes: 1 addition & 1 deletion src/config/env.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { version } from '../../package.json';

export const ENV = {
services: {
adapters: {
spotify: {
authUrl: Bun.env.SPOTIFY_AUTH_URL!,
clientId: Bun.env.SPOTIFY_CLIENT_ID!,
Expand Down
18 changes: 9 additions & 9 deletions src/parsers/link.ts
Original file line number Diff line number Diff line change
@@ -1,25 +1,25 @@
import { ParseError } from 'elysia';

import { SPOTIFY_LINK_REGEX, YOUTUBE_LINK_REGEX } from '~/config/constants';
import { ServiceType } from '~/config/enum';
import { Adapter } from '~/config/enum';
import { getSourceFromId } from '~/utils/encoding';

import { logger } from '~/utils/logger';

export type SearchService = {
export type SearchParser = {
id: string;
type: string;
source: string;
};

export const getSearchService = async (link?: string, searchId?: string) => {
export const getSearchParser = async (link?: string, searchId?: string) => {
const decodedSource = searchId ? getSourceFromId(searchId) : undefined;

let source = link;

if (searchId && decodedSource) {
logger.info(
`[${getSearchService.name}] (${searchId}) source decoded: ${decodedSource}`
`[${getSearchParser.name}] (${searchId}) source decoded: ${decodedSource}`
);
source = decodedSource;
}
Expand All @@ -29,24 +29,24 @@ export const getSearchService = async (link?: string, searchId?: string) => {
const spotifyId = source!.match(SPOTIFY_LINK_REGEX)?.[3];
if (spotifyId) {
id = spotifyId;
type = ServiceType.Spotify;
type = Adapter.Spotify;
}

const youtubeId = source!.match(YOUTUBE_LINK_REGEX)?.[1];
if (youtubeId) {
id = youtubeId;
type = ServiceType.YouTube;
type = Adapter.YouTube;
}

if (!id || !type) {
throw new ParseError('Service id could not be extracted from source.');
}

const searchService = {
const searchParser = {
id,
type,
source,
} as SearchService;
} as SearchParser;

return searchService;
return searchParser;
};
5 changes: 3 additions & 2 deletions src/routes/api.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { Elysia } from 'elysia';

import { logger } from '~/utils/logger';
import { Adapter } from '~/config/enum';

import { apiVersionValidator, searchPayloadValidator } from '~/validations/search';

Expand All @@ -18,8 +19,8 @@ export const apiRouter = new Elysia().group('/api', app =>
})
.post(
'/search',
async ({ body: { link } }) => {
const searchResult = await search(link);
async ({ body: { link, adapters } }) => {
const searchResult = await search({ link, adapters: adapters as Adapter[] });

return searchResult;
},
Expand Down
4 changes: 2 additions & 2 deletions src/routes/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ export const pageRouter = new Elysia()
'/',
async ({ query: { id }, redirect }) => {
try {
const searchResult = id ? await search(undefined, id) : undefined;
const searchResult = id ? await search({ searchId: id }) : undefined;

return (
<MainLayout
Expand All @@ -61,7 +61,7 @@ export const pageRouter = new Elysia()
.post(
'/search',
async ({ body: { link } }) => {
const searchResult = await search(link);
const searchResult = await search({ link });
return <SearchCard searchResult={searchResult} />;
},
{
Expand Down
Loading

0 comments on commit a7ad3fc

Please sign in to comment.