mirror of
https://github.com/apricote/Listory.git
synced 2026-01-13 13:11:02 +00:00
chore(deps): bump all (#294)
This commit is contained in:
parent
1979d924c9
commit
38cf2ff549
69 changed files with 4681 additions and 3804 deletions
20
.github/workflows/ci.yaml
vendored
20
.github/workflows/ci.yaml
vendored
|
|
@ -9,15 +9,7 @@ jobs:
|
|||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v3
|
||||
|
||||
- name: npm Cache
|
||||
uses: actions/cache@v3
|
||||
with:
|
||||
path: ~/.npm
|
||||
key: ${{ runner.os }}-node-${{ hashFiles('**/package-lock.json') }}
|
||||
restore-keys: |
|
||||
${{ runner.os }}-node-
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v3
|
||||
|
|
@ -38,15 +30,7 @@ jobs:
|
|||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v3
|
||||
|
||||
- name: npm Cache
|
||||
uses: actions/cache@v3
|
||||
with:
|
||||
path: ~/.npm
|
||||
key: ${{ runner.os }}-node-${{ hashFiles('**/package-lock.json') }}
|
||||
restore-keys: |
|
||||
${{ runner.os }}-node-
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v3
|
||||
|
|
|
|||
8
.github/workflows/release.yaml
vendored
8
.github/workflows/release.yaml
vendored
|
|
@ -20,9 +20,9 @@ jobs:
|
|||
persist-credentials: false
|
||||
|
||||
- name: Setup Docker Buildx
|
||||
uses: docker/setup-buildx-action@v2
|
||||
uses: docker/setup-buildx-action@v3
|
||||
with:
|
||||
version: "v0.10.4"
|
||||
version: "v0.11.2"
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v3
|
||||
|
|
@ -32,10 +32,10 @@ jobs:
|
|||
- name: Install Helm
|
||||
uses: azure/setup-helm@v3
|
||||
with:
|
||||
version: "v3.9.0"
|
||||
version: "v3.11.1"
|
||||
|
||||
- name: Login to Docker Hub
|
||||
uses: docker/login-action@v2
|
||||
uses: docker/login-action@v3
|
||||
with:
|
||||
username: ${{ secrets.DOCKER_USERNAME }}
|
||||
password: ${{ secrets.DOCKER_PASSWORD }}
|
||||
|
|
|
|||
|
|
@ -6,7 +6,7 @@ services:
|
|||
#####
|
||||
|
||||
db:
|
||||
image: postgres:15.3
|
||||
image: postgres:15.4
|
||||
restart: unless-stopped
|
||||
environment:
|
||||
POSTGRES_PASSWORD: listory
|
||||
|
|
@ -32,7 +32,7 @@ services:
|
|||
# make sure to restart the container if you made any changes.
|
||||
env_file: .env
|
||||
ports:
|
||||
- 3000:3000 # API
|
||||
- "3000:3000" # API
|
||||
networks:
|
||||
- web
|
||||
- db
|
||||
|
|
|
|||
|
|
@ -12,7 +12,7 @@ services:
|
|||
#####
|
||||
|
||||
db:
|
||||
image: postgres:15.3
|
||||
image: postgres:16.0
|
||||
environment:
|
||||
POSTGRES_PASSWORD: listory
|
||||
POSTGRES_USER: listory
|
||||
|
|
@ -72,7 +72,7 @@ services:
|
|||
- web
|
||||
|
||||
proxy:
|
||||
image: traefik:v2.10.3
|
||||
image: traefik:v2.10.4
|
||||
command:
|
||||
#- --log.level=debug
|
||||
#- --accesslog=true
|
||||
|
|
@ -129,7 +129,7 @@ services:
|
|||
|
||||
prometheus:
|
||||
profiles: ["observability"]
|
||||
image: prom/prometheus:v2.45.0
|
||||
image: prom/prometheus:v2.47.0
|
||||
volumes:
|
||||
- ./observability/prometheus:/etc/prometheus
|
||||
- prometheus_data:/prometheus
|
||||
|
|
@ -139,14 +139,14 @@ services:
|
|||
- "--storage.tsdb.retention.time=200h"
|
||||
- "--web.enable-lifecycle"
|
||||
ports:
|
||||
- 9090:9090
|
||||
- "9090:9090"
|
||||
networks:
|
||||
- observability
|
||||
- web
|
||||
|
||||
loki:
|
||||
profiles: ["observability"]
|
||||
image: grafana/loki:2.8.2
|
||||
image: grafana/loki:2.8.5
|
||||
command: ["-config.file=/etc/loki/loki.yaml"]
|
||||
ports:
|
||||
- "3100" # loki needs to be exposed so it receives logs
|
||||
|
|
@ -157,7 +157,7 @@ services:
|
|||
|
||||
promtail:
|
||||
profiles: ["observability"]
|
||||
image: grafana/promtail:2.8.2
|
||||
image: grafana/promtail:2.8.5
|
||||
command: ["-config.file=/etc/promtail.yaml"]
|
||||
volumes:
|
||||
- ./observability/promtail/promtail.yaml:/etc/promtail.yaml
|
||||
|
|
@ -175,7 +175,7 @@ services:
|
|||
|
||||
tempo:
|
||||
profiles: ["observability"]
|
||||
image: grafana/tempo:2.1.1
|
||||
image: grafana/tempo:2.2.3
|
||||
command: ["-config.file=/etc/tempo.yaml"]
|
||||
volumes:
|
||||
- ./observability/tempo/tempo.yaml:/etc/tempo.yaml
|
||||
|
|
@ -189,7 +189,7 @@ services:
|
|||
|
||||
grafana:
|
||||
profiles: ["observability"]
|
||||
image: grafana/grafana-oss:9.5.5
|
||||
image: grafana/grafana-oss:9.5.9
|
||||
volumes:
|
||||
- ./observability/grafana/provisioning:/etc/grafana/provisioning
|
||||
environment:
|
||||
|
|
@ -200,7 +200,7 @@ services:
|
|||
- GF_USERS_ALLOW_SIGN_UP=false
|
||||
- GF_SERVER_HTTP_PORT=2345
|
||||
ports:
|
||||
- 2345:2345
|
||||
- "2345:2345"
|
||||
networks:
|
||||
- observability
|
||||
|
||||
|
|
|
|||
|
|
@ -1,44 +0,0 @@
|
|||
This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).
|
||||
|
||||
## Available Scripts
|
||||
|
||||
In the project directory, you can run:
|
||||
|
||||
### `npm start`
|
||||
|
||||
Runs the app in the development mode.<br />
|
||||
Open [http://localhost:3000](http://localhost:3000) to view it in the browser.
|
||||
|
||||
The page will reload if you make edits.<br />
|
||||
You will also see any lint errors in the console.
|
||||
|
||||
### `npm test`
|
||||
|
||||
Launches the test runner in the interactive watch mode.<br />
|
||||
See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information.
|
||||
|
||||
### `npm run build`
|
||||
|
||||
Builds the app for production to the `build` folder.<br />
|
||||
It correctly bundles React in production mode and optimizes the build for the best performance.
|
||||
|
||||
The build is minified and the filenames include the hashes.<br />
|
||||
Your app is ready to be deployed!
|
||||
|
||||
See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information.
|
||||
|
||||
### `npm run eject`
|
||||
|
||||
**Note: this is a one-way operation. Once you `eject`, you can’t go back!**
|
||||
|
||||
If you aren’t satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project.
|
||||
|
||||
Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you’re on your own.
|
||||
|
||||
You don’t have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn’t feel obligated to use this feature. However we understand that this tool wouldn’t be useful if you couldn’t customize it when you are ready for it.
|
||||
|
||||
## Learn More
|
||||
|
||||
You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started).
|
||||
|
||||
To learn React, check out the [React documentation](https://reactjs.org/).
|
||||
2483
frontend/package-lock.json
generated
2483
frontend/package-lock.json
generated
File diff suppressed because it is too large
Load diff
|
|
@ -8,32 +8,32 @@
|
|||
},
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@testing-library/jest-dom": "5.16.5",
|
||||
"@testing-library/jest-dom": "6.1.3",
|
||||
"@testing-library/react": "14.0.0",
|
||||
"@testing-library/user-event": "14.4.3",
|
||||
"@types/jest": "29.5.2",
|
||||
"@types/node": "18.16.19",
|
||||
"@types/react": "18.2.14",
|
||||
"@types/react-dom": "18.2.6",
|
||||
"@testing-library/user-event": "14.5.1",
|
||||
"@types/jest": "29.5.5",
|
||||
"@types/node": "20.6.2",
|
||||
"@types/react": "18.2.21",
|
||||
"@types/react-dom": "18.2.7",
|
||||
"@types/react-router-dom": "5.3.3",
|
||||
"@types/recharts": "1.8.24",
|
||||
"@vitejs/plugin-react": "4.0.1",
|
||||
"autoprefixer": "10.4.14",
|
||||
"axios": "0.27.2",
|
||||
"@vitejs/plugin-react": "4.0.4",
|
||||
"autoprefixer": "10.4.15",
|
||||
"axios": "1.5.0",
|
||||
"date-fns": "2.30.0",
|
||||
"eslint-config-react-app": "7.0.1",
|
||||
"jsdom": "22.1.0",
|
||||
"npm-run-all": "4.1.5",
|
||||
"postcss": "8.4.24",
|
||||
"prettier": "2.8.8",
|
||||
"postcss": "8.4.29",
|
||||
"prettier": "3.0.3",
|
||||
"react": "18.2.0",
|
||||
"react-dom": "18.2.0",
|
||||
"react-router-dom": "6.14.1",
|
||||
"recharts": "2.7.2",
|
||||
"tailwindcss": "3.3.2",
|
||||
"typescript": "5.1.6",
|
||||
"vite": "4.3.9",
|
||||
"vitest": "0.32.2"
|
||||
"react-router-dom": "6.16.0",
|
||||
"recharts": "2.8.0",
|
||||
"tailwindcss": "3.3.3",
|
||||
"typescript": "5.2.2",
|
||||
"vite": "4.4.9",
|
||||
"vitest": "0.34.4"
|
||||
},
|
||||
"scripts": {
|
||||
"format": "prettier --write \"./*.js\" \"src/**/*.(tsx|ts|css)\"",
|
||||
|
|
|
|||
|
|
@ -3,4 +3,4 @@ module.exports = {
|
|||
tailwindcss: {},
|
||||
autoprefixer: {},
|
||||
},
|
||||
}
|
||||
};
|
||||
|
|
|
|||
|
|
@ -19,7 +19,7 @@ export class UnauthenticatedError extends Error {}
|
|||
|
||||
export const getRecentListens = async (
|
||||
options: PaginationOptions = { page: 1, limit: 10 },
|
||||
client: AxiosInstance
|
||||
client: AxiosInstance,
|
||||
): Promise<Pagination<Listen>> => {
|
||||
const { page, limit } = options;
|
||||
|
||||
|
|
@ -44,7 +44,7 @@ export const getRecentListens = async (
|
|||
|
||||
export const getListensReport = async (
|
||||
options: ListenReportOptions,
|
||||
client: AxiosInstance
|
||||
client: AxiosInstance,
|
||||
): Promise<ListenReportItem[]> => {
|
||||
const {
|
||||
timeFrame,
|
||||
|
|
@ -60,7 +60,7 @@ export const getListensReport = async (
|
|||
customTimeStart: formatISO(customTimeStart),
|
||||
customTimeEnd: formatISO(customTimeEnd),
|
||||
},
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
switch (res.status) {
|
||||
|
|
@ -83,7 +83,7 @@ export const getListensReport = async (
|
|||
|
||||
export const getTopArtists = async (
|
||||
options: TopArtistsOptions,
|
||||
client: AxiosInstance
|
||||
client: AxiosInstance,
|
||||
): Promise<TopArtistsItem[]> => {
|
||||
const {
|
||||
time: { timePreset, customTimeStart, customTimeEnd },
|
||||
|
|
@ -97,7 +97,7 @@ export const getTopArtists = async (
|
|||
customTimeStart: formatISO(customTimeStart),
|
||||
customTimeEnd: formatISO(customTimeEnd),
|
||||
},
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
switch (res.status) {
|
||||
|
|
@ -120,7 +120,7 @@ export const getTopArtists = async (
|
|||
|
||||
export const getTopAlbums = async (
|
||||
options: TopAlbumsOptions,
|
||||
client: AxiosInstance
|
||||
client: AxiosInstance,
|
||||
): Promise<TopAlbumsItem[]> => {
|
||||
const {
|
||||
time: { timePreset, customTimeStart, customTimeEnd },
|
||||
|
|
@ -134,7 +134,7 @@ export const getTopAlbums = async (
|
|||
customTimeStart: formatISO(customTimeStart),
|
||||
customTimeEnd: formatISO(customTimeEnd),
|
||||
},
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
switch (res.status) {
|
||||
|
|
@ -157,7 +157,7 @@ export const getTopAlbums = async (
|
|||
|
||||
export const getTopTracks = async (
|
||||
options: TopTracksOptions,
|
||||
client: AxiosInstance
|
||||
client: AxiosInstance,
|
||||
): Promise<TopTracksItem[]> => {
|
||||
const {
|
||||
time: { timePreset, customTimeStart, customTimeEnd },
|
||||
|
|
@ -171,7 +171,7 @@ export const getTopTracks = async (
|
|||
customTimeStart: formatISO(customTimeStart),
|
||||
customTimeEnd: formatISO(customTimeEnd),
|
||||
},
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
switch (res.status) {
|
||||
|
|
@ -194,7 +194,7 @@ export const getTopTracks = async (
|
|||
|
||||
export const getTopGenres = async (
|
||||
options: TopGenresOptions,
|
||||
client: AxiosInstance
|
||||
client: AxiosInstance,
|
||||
): Promise<TopGenresItem[]> => {
|
||||
const {
|
||||
time: { timePreset, customTimeStart, customTimeEnd },
|
||||
|
|
@ -208,7 +208,7 @@ export const getTopGenres = async (
|
|||
customTimeStart: formatISO(customTimeStart),
|
||||
customTimeEnd: formatISO(customTimeEnd),
|
||||
},
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
switch (res.status) {
|
||||
|
|
@ -230,7 +230,7 @@ export const getTopGenres = async (
|
|||
};
|
||||
|
||||
export const getApiTokens = async (
|
||||
client: AxiosInstance
|
||||
client: AxiosInstance,
|
||||
): Promise<ApiToken[]> => {
|
||||
const res = await client.get<ApiToken[]>(`/api/v1/auth/api-tokens`);
|
||||
|
||||
|
|
@ -251,7 +251,7 @@ export const getApiTokens = async (
|
|||
|
||||
export const createApiToken = async (
|
||||
description: string,
|
||||
client: AxiosInstance
|
||||
client: AxiosInstance,
|
||||
): Promise<NewApiToken> => {
|
||||
const res = await client.post<NewApiToken>(`/api/v1/auth/api-tokens`, {
|
||||
description,
|
||||
|
|
@ -274,7 +274,7 @@ export const createApiToken = async (
|
|||
|
||||
export const revokeApiToken = async (
|
||||
id: string,
|
||||
client: AxiosInstance
|
||||
client: AxiosInstance,
|
||||
): Promise<void> => {
|
||||
const res = await client.delete<NewApiToken>(`/api/v1/auth/api-tokens/${id}`);
|
||||
|
||||
|
|
|
|||
|
|
@ -13,7 +13,7 @@ export const AuthApiTokens: React.FC = () => {
|
|||
const { apiTokens, isLoading, createToken, revokeToken } = useApiTokens();
|
||||
const sortedTokens = useMemo(
|
||||
() => apiTokens.sort((a, b) => (a.createdAt > b.createdAt ? -1 : 1)),
|
||||
[apiTokens]
|
||||
[apiTokens],
|
||||
);
|
||||
|
||||
requireUser();
|
||||
|
|
@ -97,7 +97,7 @@ const NewTokenForm: React.FC<{
|
|||
createToken,
|
||||
setNewToken,
|
||||
setNewTokenDescription,
|
||||
]
|
||||
],
|
||||
);
|
||||
|
||||
return (
|
||||
|
|
|
|||
|
|
@ -111,7 +111,7 @@ const Pagination: React.FC<{
|
|||
>
|
||||
...
|
||||
</div>
|
||||
)
|
||||
),
|
||||
)}
|
||||
<button
|
||||
className={`${
|
||||
|
|
|
|||
|
|
@ -23,7 +23,7 @@ export const ReportListens: React.FC = () => {
|
|||
const { requireUser } = useAuthProtection();
|
||||
|
||||
const [timeFrame, setTimeFrame] = useState<"day" | "week" | "month" | "year">(
|
||||
"day"
|
||||
"day",
|
||||
);
|
||||
|
||||
const [timeOptions, setTimeOptions] = useState<TimeOptions>({
|
||||
|
|
@ -34,7 +34,7 @@ export const ReportListens: React.FC = () => {
|
|||
|
||||
const reportOptions = useMemo(
|
||||
() => ({ timeFrame, time: timeOptions }),
|
||||
[timeFrame, timeOptions]
|
||||
[timeFrame, timeOptions],
|
||||
);
|
||||
|
||||
const { report, isLoading } = useListensReport(reportOptions);
|
||||
|
|
@ -59,7 +59,7 @@ export const ReportListens: React.FC = () => {
|
|||
className="block appearance-none min-w-full md:win-w-0 md:w-1/4 bg-white dark:bg-gray-700 border border-gray-400 hover:border-gray-500 dark:border-gray-600 dark:hover:border-gray-500 dark:hover:text-gray-200 p-2 rounded shadow leading-tight focus:outline-none focus:ring"
|
||||
onChange={(e) =>
|
||||
setTimeFrame(
|
||||
e.target.value as "day" | "week" | "month" | "year"
|
||||
e.target.value as "day" | "week" | "month" | "year",
|
||||
)
|
||||
}
|
||||
>
|
||||
|
|
@ -163,7 +163,7 @@ const ReportGraph: React.FC<{
|
|||
};
|
||||
|
||||
const shortDateFormatFromTimeFrame = (
|
||||
timeFrame: "day" | "week" | "month" | "year"
|
||||
timeFrame: "day" | "week" | "month" | "year",
|
||||
): string => {
|
||||
const FORMAT_DAY = "P";
|
||||
const FORMAT_WEEK = "'Week' w yyyy";
|
||||
|
|
@ -186,7 +186,7 @@ const shortDateFormatFromTimeFrame = (
|
|||
};
|
||||
|
||||
const dateFormatFromTimeFrame = (
|
||||
timeFrame: "day" | "week" | "month" | "year"
|
||||
timeFrame: "day" | "week" | "month" | "year",
|
||||
): string => {
|
||||
const FORMAT_DAY = "PPPP";
|
||||
const FORMAT_WEEK = "'Week starting on' PPPP";
|
||||
|
|
|
|||
|
|
@ -22,7 +22,7 @@ export const ReportTopAlbums: React.FC = () => {
|
|||
() => ({
|
||||
time: timeOptions,
|
||||
}),
|
||||
[timeOptions]
|
||||
[timeOptions],
|
||||
);
|
||||
|
||||
const { topAlbums, isLoading } = useTopAlbums(options);
|
||||
|
|
|
|||
|
|
@ -21,7 +21,7 @@ export const ReportTopArtists: React.FC = () => {
|
|||
() => ({
|
||||
time: timeOptions,
|
||||
}),
|
||||
[timeOptions]
|
||||
[timeOptions],
|
||||
);
|
||||
|
||||
const { topArtists, isLoading } = useTopArtists(options);
|
||||
|
|
|
|||
|
|
@ -25,7 +25,7 @@ export const ReportTopGenres: React.FC = () => {
|
|||
() => ({
|
||||
time: timeOptions,
|
||||
}),
|
||||
[timeOptions]
|
||||
[timeOptions],
|
||||
);
|
||||
|
||||
const { topGenres, isLoading } = useTopGenres(options);
|
||||
|
|
|
|||
|
|
@ -22,7 +22,7 @@ export const ReportTopTracks: React.FC = () => {
|
|||
() => ({
|
||||
time: timeOptions,
|
||||
}),
|
||||
[timeOptions]
|
||||
[timeOptions],
|
||||
);
|
||||
|
||||
const { topTracks, isLoading } = useTopTracks(options);
|
||||
|
|
|
|||
|
|
@ -1,4 +1,8 @@
|
|||
import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } from "axios";
|
||||
import axios, {
|
||||
AxiosInstance,
|
||||
InternalAxiosRequestConfig,
|
||||
AxiosResponse,
|
||||
} from "axios";
|
||||
import React, {
|
||||
createContext,
|
||||
useContext,
|
||||
|
|
@ -13,7 +17,7 @@ interface ApiClientContext {
|
|||
}
|
||||
|
||||
const apiClientContext = createContext<ApiClientContext>(
|
||||
undefined as any as ApiClientContext
|
||||
undefined as any as ApiClientContext,
|
||||
);
|
||||
|
||||
export const ProvideApiClient: React.FC<{ children: React.ReactNode }> = ({
|
||||
|
|
@ -35,13 +39,13 @@ export function useApiClient() {
|
|||
function useProvideApiClient(): ApiClientContext {
|
||||
const { accessToken, refreshAccessToken } = useAuth();
|
||||
|
||||
// Wrap value to immediatly update when refreshing access token
|
||||
// Wrap value to immediately update when refreshing access token
|
||||
// and always having access to newest access token in interceptor
|
||||
const localAccessToken = useRef(accessToken);
|
||||
|
||||
// initialState must be passed as function as return value of axios.create()
|
||||
// is also callable and react will call it and then use that result (promise)
|
||||
// as the initial state instead of the axios instace.
|
||||
// as the initial state instead of the axios instance.
|
||||
const [client] = useState<AxiosInstance>(() => axios.create());
|
||||
|
||||
useEffect(() => {
|
||||
|
|
@ -54,15 +58,11 @@ function useProvideApiClient(): ApiClientContext {
|
|||
// Setup Axios Interceptors
|
||||
const requestInterceptor = client.interceptors.request.use(
|
||||
(config) => {
|
||||
if (!config.headers) {
|
||||
config.headers = {};
|
||||
}
|
||||
|
||||
config.headers.Authorization = `Bearer ${localAccessToken.current}`;
|
||||
|
||||
return config;
|
||||
},
|
||||
(err) => Promise.reject(err)
|
||||
(err) => Promise.reject(err),
|
||||
);
|
||||
const responseInterceptor = client.interceptors.response.use(
|
||||
(data) => data,
|
||||
|
|
@ -73,7 +73,7 @@ function useProvideApiClient(): ApiClientContext {
|
|||
|
||||
const { response, config } = err as {
|
||||
response: AxiosResponse;
|
||||
config: AxiosRequestConfig;
|
||||
config: InternalAxiosRequestConfig;
|
||||
};
|
||||
|
||||
if (response && response.status !== 401) {
|
||||
|
|
@ -84,7 +84,7 @@ function useProvideApiClient(): ApiClientContext {
|
|||
localAccessToken.current = await refreshAccessToken();
|
||||
|
||||
return client.request(config);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
return () => {
|
||||
|
|
|
|||
|
|
@ -27,7 +27,7 @@ export const useRecentListens = (options: PaginationOptions) => {
|
|||
|
||||
const fetchData = useMemo(
|
||||
() => () => getRecentListens(options, client),
|
||||
[options, client]
|
||||
[options, client],
|
||||
);
|
||||
|
||||
const {
|
||||
|
|
@ -48,7 +48,7 @@ export const useListensReport = (options: ListenReportOptions) => {
|
|||
|
||||
const fetchData = useMemo(
|
||||
() => () => getListensReport(options, client),
|
||||
[options, client]
|
||||
[options, client],
|
||||
);
|
||||
|
||||
const {
|
||||
|
|
@ -65,7 +65,7 @@ export const useTopArtists = (options: TopArtistsOptions) => {
|
|||
|
||||
const fetchData = useMemo(
|
||||
() => () => getTopArtists(options, client),
|
||||
[options, client]
|
||||
[options, client],
|
||||
);
|
||||
|
||||
const {
|
||||
|
|
@ -82,7 +82,7 @@ export const useTopAlbums = (options: TopAlbumsOptions) => {
|
|||
|
||||
const fetchData = useMemo(
|
||||
() => () => getTopAlbums(options, client),
|
||||
[options, client]
|
||||
[options, client],
|
||||
);
|
||||
|
||||
const {
|
||||
|
|
@ -99,7 +99,7 @@ export const useTopTracks = (options: TopTracksOptions) => {
|
|||
|
||||
const fetchData = useMemo(
|
||||
() => () => getTopTracks(options, client),
|
||||
[options, client]
|
||||
[options, client],
|
||||
);
|
||||
|
||||
const {
|
||||
|
|
@ -116,7 +116,7 @@ export const useTopGenres = (options: TopGenresOptions) => {
|
|||
|
||||
const fetchData = useMemo(
|
||||
() => () => getTopGenres(options, client),
|
||||
[options, client]
|
||||
[options, client],
|
||||
);
|
||||
|
||||
const {
|
||||
|
|
@ -149,7 +149,7 @@ export const useApiTokens = () => {
|
|||
|
||||
return apiToken;
|
||||
},
|
||||
[client, reload]
|
||||
[client, reload],
|
||||
);
|
||||
|
||||
const revokeToken = useCallback(
|
||||
|
|
@ -157,7 +157,7 @@ export const useApiTokens = () => {
|
|||
await revokeApiToken(id, client);
|
||||
await reload();
|
||||
},
|
||||
[client, reload]
|
||||
[client, reload],
|
||||
);
|
||||
|
||||
return { apiTokens, isLoading, error, createToken, revokeToken };
|
||||
|
|
|
|||
|
|
@ -2,7 +2,7 @@ import { useCallback, useEffect, useState, useTransition } from "react";
|
|||
|
||||
type UseAsync = <T>(
|
||||
asyncFunction: () => Promise<T>,
|
||||
initialValue: T
|
||||
initialValue: T,
|
||||
) => {
|
||||
pending: boolean;
|
||||
value: T;
|
||||
|
|
@ -12,7 +12,7 @@ type UseAsync = <T>(
|
|||
|
||||
export const useAsync: UseAsync = <T extends any>(
|
||||
asyncFunction: () => Promise<T>,
|
||||
initialValue: T
|
||||
initialValue: T,
|
||||
) => {
|
||||
const [pending, setPending] = useState(false);
|
||||
const [value, setValue] = useState<T>(initialValue);
|
||||
|
|
|
|||
|
|
@ -5,7 +5,7 @@ import React, { useEffect } from "react";
|
|||
*/
|
||||
export const useOutsideClick = (
|
||||
ref: React.MutableRefObject<any>,
|
||||
callback: () => void
|
||||
callback: () => void,
|
||||
) => {
|
||||
useEffect(() => {
|
||||
/**
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
import React from "react";
|
||||
|
||||
export const CogwheelIcon: React.FC<React.SVGProps<SVGSVGElement>> = (
|
||||
props
|
||||
props,
|
||||
) => {
|
||||
return (
|
||||
<svg
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
import React from "react";
|
||||
|
||||
export const TrashcanIcon: React.FC<React.SVGProps<SVGSVGElement>> = (
|
||||
props
|
||||
props,
|
||||
) => {
|
||||
return (
|
||||
<svg
|
||||
|
|
|
|||
|
|
@ -17,5 +17,5 @@ root.render(
|
|||
</BrowserRouter>
|
||||
</ProvideApiClient>
|
||||
</ProvideAuth>
|
||||
</React.StrictMode>
|
||||
</React.StrictMode>,
|
||||
);
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
export const getPaginationItems = (
|
||||
currentPage: number,
|
||||
totalPages: number,
|
||||
delta: number = 1
|
||||
delta: number = 1,
|
||||
): (number | null)[] => {
|
||||
const left = currentPage - delta;
|
||||
const right = currentPage + delta;
|
||||
|
|
|
|||
|
|
@ -5,7 +5,7 @@ export const qs = (parameters: QueryParameters): string => {
|
|||
const queryParams = new URLSearchParams();
|
||||
|
||||
Object.entries(parameters).forEach(([key, value]) =>
|
||||
queryParams.append(key, value)
|
||||
queryParams.append(key, value),
|
||||
);
|
||||
|
||||
return queryParams.toString();
|
||||
|
|
|
|||
5281
package-lock.json
generated
5281
package-lock.json
generated
File diff suppressed because it is too large
Load diff
97
package.json
97
package.json
|
|
@ -26,94 +26,93 @@
|
|||
"test:e2e": "jest --config ./apps/listory/test/jest-e2e.json"
|
||||
},
|
||||
"dependencies": {
|
||||
"@apricote/nest-pg-boss": "2.0.0",
|
||||
"@narando/nest-axios-interceptor": "2.2.0",
|
||||
"@nestjs/axios": "0.1.0",
|
||||
"@nestjs/common": "9.4.3",
|
||||
"@nestjs/config": "2.3.4",
|
||||
"@nestjs/core": "9.4.3",
|
||||
"@apricote/nest-pg-boss": "2.1.0",
|
||||
"@narando/nest-axios-interceptor": "3.0.0",
|
||||
"@nestjs/axios": "3.0.0",
|
||||
"@nestjs/common": "10.2.5",
|
||||
"@nestjs/config": "3.1.1",
|
||||
"@nestjs/core": "10.2.5",
|
||||
"@nestjs/jwt": "10.1.1",
|
||||
"@nestjs/passport": "9.0.3",
|
||||
"@nestjs/platform-express": "9.4.3",
|
||||
"@nestjs/serve-static": "3.0.1",
|
||||
"@nestjs/swagger": "6.3.0",
|
||||
"@nestjs/terminus": "9.2.2",
|
||||
"@nestjs/typeorm": "9.0.1",
|
||||
"@nestjs/passport": "10.0.2",
|
||||
"@nestjs/platform-express": "10.2.5",
|
||||
"@nestjs/serve-static": "4.0.0",
|
||||
"@nestjs/swagger": "7.1.11",
|
||||
"@nestjs/terminus": "10.1.1",
|
||||
"@nestjs/typeorm": "10.0.0",
|
||||
"@opentelemetry/api": "1.6.0",
|
||||
"@opentelemetry/api-metrics": "0.33.0",
|
||||
"@opentelemetry/context-async-hooks": "1.17.0",
|
||||
"@opentelemetry/exporter-prometheus": "0.43.0",
|
||||
"@opentelemetry/exporter-trace-otlp-http": "0.43.0",
|
||||
"@opentelemetry/instrumentation": "0.43.0",
|
||||
"@opentelemetry/instrumentation-dns": "0.31.5",
|
||||
"@opentelemetry/instrumentation-express": "0.32.4",
|
||||
"@opentelemetry/instrumentation-dns": "0.32.2",
|
||||
"@opentelemetry/instrumentation-express": "0.33.1",
|
||||
"@opentelemetry/instrumentation-http": "0.43.0",
|
||||
"@opentelemetry/instrumentation-nestjs-core": "0.32.5",
|
||||
"@opentelemetry/instrumentation-pg": "0.35.3",
|
||||
"@opentelemetry/instrumentation-pino": "0.33.4",
|
||||
"@opentelemetry/instrumentation-nestjs-core": "0.33.1",
|
||||
"@opentelemetry/instrumentation-pg": "0.36.1",
|
||||
"@opentelemetry/instrumentation-pino": "0.34.1",
|
||||
"@opentelemetry/resources": "1.17.0",
|
||||
"@opentelemetry/sdk-metrics": "1.17.0",
|
||||
"@opentelemetry/sdk-node": "0.43.0",
|
||||
"@opentelemetry/sdk-trace-base": "1.17.0",
|
||||
"@opentelemetry/semantic-conventions": "1.17.0",
|
||||
"@sentry/node": "7.57.0",
|
||||
"@sentry/node": "7.69.0",
|
||||
"class-transformer": "0.5.1",
|
||||
"class-validator": "0.14.0",
|
||||
"cookie-parser": "1.4.6",
|
||||
"date-fns": "2.30.0",
|
||||
"joi": "17.9.2",
|
||||
"lodash": "^4.17.21",
|
||||
"nest-raven": "9.2.0",
|
||||
"nestjs-otel": "5.1.4",
|
||||
"nestjs-pino": "3.3.0",
|
||||
"joi": "17.10.1",
|
||||
"lodash": "4.17.21",
|
||||
"nest-raven": "10.0.0",
|
||||
"nestjs-otel": "5.1.5",
|
||||
"nestjs-pino": "3.4.0",
|
||||
"nestjs-typeorm-paginate": "4.0.4",
|
||||
"passport": "0.6.0",
|
||||
"passport-http-bearer": "^1.0.1",
|
||||
"passport-http-bearer": "1.0.1",
|
||||
"passport-jwt": "4.0.1",
|
||||
"passport-spotify": "2.0.0",
|
||||
"pg": "8.11.1",
|
||||
"pg-boss": "^9.0.0",
|
||||
"pino": "8.14.1",
|
||||
"pino-http": "8.3.3",
|
||||
"pg": "8.11.3",
|
||||
"pg-boss": "9.0.3",
|
||||
"pino": "8.15.1",
|
||||
"pino-http": "8.5.0",
|
||||
"reflect-metadata": "0.1.13",
|
||||
"rimraf": "5.0.1",
|
||||
"rxjs": "7.8.1",
|
||||
"typeorm": "0.3.17"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@nestjs/cli": "9.5.0",
|
||||
"@nestjs/schematics": "9.2.0",
|
||||
"@nestjs/testing": "9.4.3",
|
||||
"@nestjs/cli": "10.1.17",
|
||||
"@nestjs/schematics": "10.0.2",
|
||||
"@nestjs/testing": "10.2.5",
|
||||
"@types/cookie-parser": "1.4.4",
|
||||
"@types/express": "4.17.17",
|
||||
"@types/jest": "29.5.2",
|
||||
"@types/lodash": "^4.14.194",
|
||||
"@types/long": "4.0.2",
|
||||
"@types/node": "18.16.19",
|
||||
"@types/passport-http-bearer": "^1.0.37",
|
||||
"@types/passport-jwt": "3.0.8",
|
||||
"@types/jest": "29.5.5",
|
||||
"@types/lodash": "4.14.198",
|
||||
"@types/node": "20.6.2",
|
||||
"@types/passport-http-bearer": "1.0.37",
|
||||
"@types/passport-jwt": "3.0.9",
|
||||
"@types/supertest": "2.0.12",
|
||||
"@typescript-eslint/eslint-plugin": "5.60.1",
|
||||
"@typescript-eslint/parser": "5.60.1",
|
||||
"eslint": "8.44.0",
|
||||
"@typescript-eslint/eslint-plugin": "6.7.0",
|
||||
"@typescript-eslint/parser": "6.7.0",
|
||||
"eslint": "8.49.0",
|
||||
"eslint-config-airbnb-base": "15.0.0",
|
||||
"eslint-config-airbnb-typescript": "17.0.0",
|
||||
"eslint-config-prettier": "8.8.0",
|
||||
"eslint-plugin-import": "2.27.5",
|
||||
"eslint-plugin-jsdoc": "46.4.3",
|
||||
"eslint-config-airbnb-typescript": "17.1.0",
|
||||
"eslint-config-prettier": "9.0.0",
|
||||
"eslint-plugin-import": "2.28.1",
|
||||
"eslint-plugin-jsdoc": "46.8.1",
|
||||
"eslint-plugin-jsx-a11y": "6.7.1",
|
||||
"eslint-plugin-prefer-arrow": "1.2.3",
|
||||
"eslint-plugin-react": "7.32.2",
|
||||
"eslint-plugin-react": "7.33.2",
|
||||
"eslint-plugin-react-hooks": "4.6.0",
|
||||
"jest": "29.5.0",
|
||||
"pino-pretty": "10.0.0",
|
||||
"prettier": "2.8.8",
|
||||
"jest": "29.7.0",
|
||||
"pino-pretty": "10.2.0",
|
||||
"prettier": "3.0.3",
|
||||
"supertest": "6.3.3",
|
||||
"ts-jest": "29.1.1",
|
||||
"ts-loader": "9.4.4",
|
||||
"ts-node": "10.9.1",
|
||||
"tsconfig-paths": "4.2.0",
|
||||
"typescript": "5.1.6"
|
||||
"typescript": "5.2.2"
|
||||
},
|
||||
"jest": {
|
||||
"moduleFileExtensions": [
|
||||
|
|
|
|||
|
|
@ -56,7 +56,7 @@ describe("AuthController", () => {
|
|||
expect(res.cookie).toHaveBeenCalledWith(
|
||||
COOKIE_REFRESH_TOKEN,
|
||||
refreshToken,
|
||||
{ httpOnly: true }
|
||||
{ httpOnly: true },
|
||||
);
|
||||
});
|
||||
|
||||
|
|
@ -65,7 +65,7 @@ describe("AuthController", () => {
|
|||
|
||||
expect(res.redirect).toHaveBeenCalledTimes(1);
|
||||
expect(res.redirect).toHaveBeenCalledWith(
|
||||
"/login/success?source=spotify"
|
||||
"/login/success?source=spotify",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -57,7 +57,7 @@ export class AuthController {
|
|||
@UseGuards(RefreshTokenAuthGuard)
|
||||
async refreshAccessToken(
|
||||
// With RefreshTokenAuthGuard the session is available instead of user
|
||||
@ReqUser() session: AuthSession
|
||||
@ReqUser() session: AuthSession,
|
||||
): Promise<RefreshAccessTokenResponseDto> {
|
||||
const { accessToken } = await this.authService.createAccessToken(session);
|
||||
|
||||
|
|
@ -69,7 +69,7 @@ export class AuthController {
|
|||
@AuthAccessToken()
|
||||
async createApiToken(
|
||||
@ReqUser() user: User,
|
||||
@Body("description") description: string
|
||||
@Body("description") description: string,
|
||||
): Promise<NewApiTokenDto> {
|
||||
const apiToken = await this.authService.createApiToken(user, description);
|
||||
|
||||
|
|
@ -100,7 +100,7 @@ export class AuthController {
|
|||
@AuthAccessToken()
|
||||
async revokeApiToken(
|
||||
@ReqUser() user: User,
|
||||
@Param("id") id: string
|
||||
@Param("id") id: string,
|
||||
): Promise<void> {
|
||||
return this.authService.revokeApiToken(user, id);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -38,7 +38,7 @@ describe("AuthService", () => {
|
|||
usersService = module.get<UsersService>(UsersService);
|
||||
jwtService = module.get<JwtService>(JwtService);
|
||||
authSessionRepository = module.get<AuthSessionRepository>(
|
||||
AuthSessionRepository
|
||||
AuthSessionRepository,
|
||||
);
|
||||
apiTokenRepository = module.get<ApiTokenRepository>(ApiTokenRepository);
|
||||
});
|
||||
|
|
@ -84,7 +84,7 @@ describe("AuthService", () => {
|
|||
|
||||
expect(service.allowedByUserFilter).toHaveBeenCalledTimes(1);
|
||||
expect(service.allowedByUserFilter).toHaveBeenCalledWith(
|
||||
loginDto.profile.id
|
||||
loginDto.profile.id,
|
||||
);
|
||||
});
|
||||
|
||||
|
|
@ -92,7 +92,7 @@ describe("AuthService", () => {
|
|||
service.allowedByUserFilter = jest.fn().mockReturnValue(false);
|
||||
|
||||
await expect(service.spotifyLogin(loginDto)).rejects.toThrow(
|
||||
ForbiddenException
|
||||
ForbiddenException,
|
||||
);
|
||||
});
|
||||
|
||||
|
|
@ -197,7 +197,7 @@ describe("AuthService", () => {
|
|||
{
|
||||
jwtid: session.id,
|
||||
expiresIn: "EXPIRATION_TIME",
|
||||
}
|
||||
},
|
||||
);
|
||||
});
|
||||
});
|
||||
|
|
@ -231,7 +231,7 @@ describe("AuthService", () => {
|
|||
session.revokedAt = new Date("2020-01-01T00:00:00Z");
|
||||
|
||||
await expect(service.createAccessToken(session)).rejects.toThrow(
|
||||
ForbiddenException
|
||||
ForbiddenException,
|
||||
);
|
||||
});
|
||||
|
||||
|
|
@ -258,7 +258,7 @@ describe("AuthService", () => {
|
|||
|
||||
it("returns the session", async () => {
|
||||
await expect(service.findSession("AUTH_SESSION")).resolves.toEqual(
|
||||
session
|
||||
session,
|
||||
);
|
||||
|
||||
expect(authSessionRepository.findOneBy).toHaveBeenCalledTimes(1);
|
||||
|
|
|
|||
|
|
@ -20,11 +20,11 @@ export class AuthService {
|
|||
private readonly usersService: UsersService,
|
||||
private readonly jwtService: JwtService,
|
||||
private readonly authSessionRepository: AuthSessionRepository,
|
||||
private readonly apiTokenRepository: ApiTokenRepository
|
||||
private readonly apiTokenRepository: ApiTokenRepository,
|
||||
) {
|
||||
this.userFilter = this.config.get<string>("SPOTIFY_USER_FILTER");
|
||||
this.sessionExpirationTime = this.config.get<string>(
|
||||
"SESSION_EXPIRATION_TIME"
|
||||
"SESSION_EXPIRATION_TIME",
|
||||
);
|
||||
}
|
||||
|
||||
|
|
@ -69,7 +69,7 @@ export class AuthService {
|
|||
* @param session
|
||||
*/
|
||||
private async createRefreshToken(
|
||||
session: AuthSession
|
||||
session: AuthSession,
|
||||
): Promise<{ refreshToken: string }> {
|
||||
const payload = {
|
||||
sub: session.user.id,
|
||||
|
|
@ -86,7 +86,7 @@ export class AuthService {
|
|||
}
|
||||
|
||||
async createAccessToken(
|
||||
session: AuthSession
|
||||
session: AuthSession,
|
||||
): Promise<{ accessToken: string }> {
|
||||
if (session.revokedAt) {
|
||||
throw new ForbiddenException("SessionIsRevoked");
|
||||
|
|
@ -115,7 +115,7 @@ export class AuthService {
|
|||
|
||||
// TODO demagic 20
|
||||
const tokenBuffer = await new Promise<Buffer>((resolve, reject) =>
|
||||
randomBytes(20, (err, buf) => (err ? reject(err) : resolve(buf)))
|
||||
randomBytes(20, (err, buf) => (err ? reject(err) : resolve(buf))),
|
||||
);
|
||||
apiToken.token = `lis${tokenBuffer.toString("hex")}`;
|
||||
|
||||
|
|
|
|||
|
|
@ -6,6 +6,6 @@ export function AuthAccessToken() {
|
|||
return applyDecorators(
|
||||
UseGuards(ApiAuthGuard),
|
||||
ApiBearerAuth(),
|
||||
ApiUnauthorizedResponse({ description: "Unauthorized" })
|
||||
ApiUnauthorizedResponse({ description: "Unauthorized" }),
|
||||
);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -4,5 +4,5 @@ export const ReqUser = createParamDecorator<void>(
|
|||
(_: void, ctx: ExecutionContext) => {
|
||||
const request = ctx.switchToHttp().getRequest();
|
||||
return request.user;
|
||||
}
|
||||
},
|
||||
);
|
||||
|
|
|
|||
|
|
@ -29,7 +29,7 @@ export class SpotifyAuthFilter implements ExceptionFilter {
|
|||
|
||||
this.logger.error(
|
||||
`Login with Spotify failed: ${exception}`,
|
||||
exception.stack
|
||||
exception.stack,
|
||||
);
|
||||
|
||||
response.redirect(`/login/failure?reason=${reason}&source=spotify`);
|
||||
|
|
|
|||
|
|
@ -8,11 +8,11 @@ import { AuthStrategy } from "./strategies.enum";
|
|||
@Injectable()
|
||||
export class AccessTokenStrategy extends PassportStrategy(
|
||||
Strategy,
|
||||
AuthStrategy.AccessToken
|
||||
AuthStrategy.AccessToken,
|
||||
) {
|
||||
constructor(
|
||||
private readonly authService: AuthService,
|
||||
config: ConfigService
|
||||
config: ConfigService,
|
||||
) {
|
||||
super({
|
||||
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
|
||||
|
|
|
|||
|
|
@ -12,7 +12,7 @@ import { AuthStrategy } from "./strategies.enum";
|
|||
@Injectable()
|
||||
export class ApiTokenStrategy extends PassportStrategy(
|
||||
Strategy,
|
||||
AuthStrategy.ApiToken
|
||||
AuthStrategy.ApiToken,
|
||||
) {
|
||||
constructor(private readonly authService: AuthService) {
|
||||
super();
|
||||
|
|
|
|||
|
|
@ -54,7 +54,7 @@ describe("RefreshTokenStrategy", () => {
|
|||
authService.findSession = jest.fn().mockResolvedValue(undefined);
|
||||
|
||||
await expect(strategy.validate(payload)).rejects.toThrow(
|
||||
UnauthorizedException
|
||||
UnauthorizedException,
|
||||
);
|
||||
});
|
||||
|
||||
|
|
@ -62,7 +62,7 @@ describe("RefreshTokenStrategy", () => {
|
|||
session.revokedAt = "2021-01-01";
|
||||
|
||||
await expect(strategy.validate(payload)).rejects.toThrow(
|
||||
ForbiddenException
|
||||
ForbiddenException,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -19,11 +19,11 @@ const extractJwtFromCookie: JwtFromRequestFunction = (req) => {
|
|||
@Injectable()
|
||||
export class RefreshTokenStrategy extends PassportStrategy(
|
||||
Strategy,
|
||||
AuthStrategy.RefreshToken
|
||||
AuthStrategy.RefreshToken,
|
||||
) {
|
||||
constructor(
|
||||
private readonly authService: AuthService,
|
||||
config: ConfigService
|
||||
config: ConfigService,
|
||||
) {
|
||||
super({
|
||||
jwtFromRequest: extractJwtFromCookie,
|
||||
|
|
|
|||
|
|
@ -8,17 +8,17 @@ import { AuthStrategy } from "./strategies.enum";
|
|||
@Injectable()
|
||||
export class SpotifyStrategy extends PassportStrategy(
|
||||
Strategy,
|
||||
AuthStrategy.Spotify
|
||||
AuthStrategy.Spotify,
|
||||
) {
|
||||
constructor(
|
||||
private readonly authService: AuthService,
|
||||
config: ConfigService
|
||||
config: ConfigService,
|
||||
) {
|
||||
super({
|
||||
clientID: config.get<string>("SPOTIFY_CLIENT_ID"),
|
||||
clientSecret: config.get<string>("SPOTIFY_CLIENT_SECRET"),
|
||||
callbackURL: `${config.get<string>(
|
||||
"APP_URL"
|
||||
"APP_URL",
|
||||
)}/api/v1/auth/spotify/callback`,
|
||||
scope: [
|
||||
"user-read-private",
|
||||
|
|
|
|||
|
|
@ -27,7 +27,7 @@ import * as Joi from "joi";
|
|||
SPOTIFY_UPDATE_INTERVAL_SEC: Joi.number().default(60),
|
||||
SPOTIFY_WEB_API_URL: Joi.string().default("https://api.spotify.com/"),
|
||||
SPOTIFY_AUTH_API_URL: Joi.string().default(
|
||||
"https://accounts.spotify.com/"
|
||||
"https://accounts.spotify.com/",
|
||||
),
|
||||
SPOTIFY_USER_FILTER: Joi.string(),
|
||||
|
||||
|
|
@ -53,14 +53,14 @@ import * as Joi from "joi";
|
|||
{
|
||||
is: Joi.valid(true),
|
||||
then: Joi.required(),
|
||||
}
|
||||
},
|
||||
),
|
||||
PROMETHEUS_BASIC_AUTH_PASSWORD: Joi.string().when(
|
||||
"PROMETHEUS_BASIC_AUTH",
|
||||
{
|
||||
is: Joi.valid(true),
|
||||
then: Joi.required(),
|
||||
}
|
||||
},
|
||||
),
|
||||
}),
|
||||
}),
|
||||
|
|
|
|||
|
|
@ -5,7 +5,7 @@ import { TYPEORM_ENTITY_REPOSITORY } from "./entity-repository.decorator";
|
|||
|
||||
export class TypeOrmRepositoryModule {
|
||||
public static for<T extends new (...args: any[]) => any>(
|
||||
repositories: T[]
|
||||
repositories: T[],
|
||||
): DynamicModule {
|
||||
const providers: Provider[] = [];
|
||||
|
||||
|
|
@ -24,7 +24,7 @@ export class TypeOrmRepositoryModule {
|
|||
return new repository(
|
||||
baseRepository.target,
|
||||
baseRepository.manager,
|
||||
baseRepository.queryRunner
|
||||
baseRepository.queryRunner,
|
||||
);
|
||||
},
|
||||
});
|
||||
|
|
|
|||
|
|
@ -39,7 +39,7 @@ export class CreateUsersTable0000000000001 implements MigrationInterface {
|
|||
}),
|
||||
],
|
||||
}),
|
||||
true
|
||||
true,
|
||||
);
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -43,7 +43,7 @@ export class CreateLibraryTables0000000000002 implements MigrationInterface {
|
|||
}),
|
||||
],
|
||||
}),
|
||||
true
|
||||
true,
|
||||
);
|
||||
|
||||
await queryRunner.createTable(
|
||||
|
|
@ -64,7 +64,7 @@ export class CreateLibraryTables0000000000002 implements MigrationInterface {
|
|||
isUnique: true,
|
||||
}),
|
||||
],
|
||||
})
|
||||
}),
|
||||
);
|
||||
|
||||
await queryRunner.createTable(
|
||||
|
|
@ -94,7 +94,7 @@ export class CreateLibraryTables0000000000002 implements MigrationInterface {
|
|||
referencedTableName: "album",
|
||||
}),
|
||||
],
|
||||
})
|
||||
}),
|
||||
);
|
||||
|
||||
await queryRunner.createTable(
|
||||
|
|
@ -137,7 +137,7 @@ export class CreateLibraryTables0000000000002 implements MigrationInterface {
|
|||
}),
|
||||
],
|
||||
}),
|
||||
true
|
||||
true,
|
||||
);
|
||||
|
||||
await queryRunner.createTable(
|
||||
|
|
@ -180,7 +180,7 @@ export class CreateLibraryTables0000000000002 implements MigrationInterface {
|
|||
}),
|
||||
],
|
||||
}),
|
||||
true
|
||||
true,
|
||||
);
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -65,7 +65,7 @@ export class CreateListensTable0000000000003 implements MigrationInterface {
|
|||
}),
|
||||
],
|
||||
}),
|
||||
true
|
||||
true,
|
||||
);
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -60,7 +60,7 @@ export class CreateAuthSessionsTable0000000000004
|
|||
}),
|
||||
],
|
||||
}),
|
||||
true
|
||||
true,
|
||||
);
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -34,7 +34,7 @@ export class CreateGenreTables0000000000005 implements MigrationInterface {
|
|||
}),
|
||||
],
|
||||
}),
|
||||
true
|
||||
true,
|
||||
);
|
||||
|
||||
await queryRunner.createTable(
|
||||
|
|
@ -77,7 +77,7 @@ export class CreateGenreTables0000000000005 implements MigrationInterface {
|
|||
}),
|
||||
],
|
||||
}),
|
||||
true
|
||||
true,
|
||||
);
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -8,7 +8,7 @@ export class AddUpdatedAtColumnes0000000000006 implements MigrationInterface {
|
|||
name: "updatedAt",
|
||||
type: "timestamp",
|
||||
default: "NOW()",
|
||||
})
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -67,7 +67,7 @@ export class CreateApiTokensTable0000000000007 implements MigrationInterface {
|
|||
}),
|
||||
],
|
||||
}),
|
||||
true
|
||||
true,
|
||||
);
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -17,7 +17,7 @@ export class HealthCheckController {
|
|||
private readonly health: HealthCheckService,
|
||||
private readonly http: HttpHealthIndicator,
|
||||
private readonly typeorm: TypeOrmHealthIndicator,
|
||||
private readonly config: ConfigService
|
||||
private readonly config: ConfigService,
|
||||
) {}
|
||||
|
||||
@Get()
|
||||
|
|
@ -30,7 +30,7 @@ export class HealthCheckController {
|
|||
this.config.get<string>("SPOTIFY_WEB_API_URL"),
|
||||
{
|
||||
validateStatus: () => true,
|
||||
} // Successful as long as we get a valid HTTP response back }
|
||||
}, // Successful as long as we get a valid HTTP response back }
|
||||
),
|
||||
() => this.typeorm.pingCheck("db"),
|
||||
]);
|
||||
|
|
|
|||
|
|
@ -82,7 +82,7 @@ export class ListenRepository extends Repository<Listen> {
|
|||
.execute();
|
||||
|
||||
return this.findBy(
|
||||
result.identifiers.filter(Boolean).map(({ id }) => ({ id }))
|
||||
result.identifiers.filter(Boolean).map(({ id }) => ({ id })),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -41,7 +41,7 @@ describe("Listens Controller", () => {
|
|||
|
||||
it("returns the listens", async () => {
|
||||
await expect(
|
||||
controller.getRecentlyPlayed(filter, user, 1, 10)
|
||||
controller.getRecentlyPlayed(filter, user, 1, 10),
|
||||
).resolves.toEqual(listens);
|
||||
|
||||
expect(listensService.getListens).toHaveBeenCalledTimes(1);
|
||||
|
|
@ -57,7 +57,7 @@ describe("Listens Controller", () => {
|
|||
await controller.getRecentlyPlayed(filter, user, 1, 1000);
|
||||
|
||||
expect(listensService.getListens).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ limit: 100 })
|
||||
expect.objectContaining({ limit: 100 }),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -19,7 +19,7 @@ export class ListensController {
|
|||
@Query("filter") filter: GetListensFilterDto,
|
||||
@ReqUser() user: User,
|
||||
@Query("page") page: number = 1,
|
||||
@Query("limit") limit: number = 10
|
||||
@Query("limit") limit: number = 10,
|
||||
): Promise<Pagination<Listen>> {
|
||||
const clampedLimit = limit > 100 ? 100 : limit;
|
||||
|
||||
|
|
|
|||
|
|
@ -56,7 +56,7 @@ describe("ListensService", () => {
|
|||
|
||||
it("creates the listen", async () => {
|
||||
await expect(
|
||||
service.createListen({ user, track, playedAt })
|
||||
service.createListen({ user, track, playedAt }),
|
||||
).resolves.toEqual(response);
|
||||
|
||||
expect(listenRepository.insertNoConflict).toHaveBeenCalledTimes(1);
|
||||
|
|
|
|||
|
|
@ -32,7 +32,7 @@ export class ListensService {
|
|||
}
|
||||
|
||||
async createListens(
|
||||
listensData: CreateListenRequestDto[]
|
||||
listensData: CreateListenRequestDto[],
|
||||
): Promise<Listen[]> {
|
||||
const existingListens = await this.listenRepository.findBy(listensData);
|
||||
|
||||
|
|
@ -42,17 +42,17 @@ export class ListensService {
|
|||
(existingListen) =>
|
||||
newListen.user.id === existingListen.user.id &&
|
||||
newListen.track.id === existingListen.track.id &&
|
||||
newListen.playedAt.getTime() === existingListen.playedAt.getTime()
|
||||
)
|
||||
newListen.playedAt.getTime() === existingListen.playedAt.getTime(),
|
||||
),
|
||||
);
|
||||
|
||||
return this.listenRepository.save(
|
||||
missingListens.map((entry) => this.listenRepository.create(entry))
|
||||
missingListens.map((entry) => this.listenRepository.create(entry)),
|
||||
);
|
||||
}
|
||||
|
||||
async getListens(
|
||||
options: GetListensDto & IPaginationOptions
|
||||
options: GetListensDto & IPaginationOptions,
|
||||
): Promise<Pagination<Listen>> {
|
||||
const { page, limit, user, filter } = options;
|
||||
|
||||
|
|
|
|||
|
|
@ -13,7 +13,7 @@ import { Scope } from "@sentry/node";
|
|||
|
||||
function setupSentry(
|
||||
app: NestExpressApplication,
|
||||
configService: ConfigService
|
||||
configService: ConfigService,
|
||||
) {
|
||||
Sentry.init({
|
||||
dsn: configService.get<string>("SENTRY_DSN"),
|
||||
|
|
@ -34,7 +34,7 @@ function setupSentry(
|
|||
}
|
||||
},
|
||||
],
|
||||
})
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
|
|
@ -49,7 +49,7 @@ async function bootstrap() {
|
|||
new ValidationPipe({
|
||||
transform: true,
|
||||
transformOptions: { enableImplicitConversion: true },
|
||||
})
|
||||
}),
|
||||
);
|
||||
app.enableShutdownHooks();
|
||||
|
||||
|
|
|
|||
|
|
@ -57,7 +57,7 @@ describe("MusicLibraryService", () => {
|
|||
artistRepository.findOneBy = jest.fn().mockResolvedValue(artist);
|
||||
|
||||
await expect(
|
||||
service.findArtist({ spotify: { id: "spotify_artist" } })
|
||||
service.findArtist({ spotify: { id: "spotify_artist" } }),
|
||||
).resolves.toEqual(artist);
|
||||
|
||||
expect(artistRepository.findOneBy).toHaveBeenCalledTimes(1);
|
||||
|
|
@ -90,7 +90,7 @@ describe("MusicLibraryService", () => {
|
|||
|
||||
it("creates the entity", async () => {
|
||||
await expect(service.createArtist(createArtistDto)).resolves.toEqual(
|
||||
artist
|
||||
artist,
|
||||
);
|
||||
|
||||
expect(artistRepository.create).toHaveBeenCalledTimes(1);
|
||||
|
|
@ -115,7 +115,7 @@ describe("MusicLibraryService", () => {
|
|||
.mockRejectedValue(uniqueViolationError);
|
||||
|
||||
await expect(service.createArtist(createArtistDto)).resolves.toEqual(
|
||||
artist
|
||||
artist,
|
||||
);
|
||||
|
||||
expect(service.findArtist).toHaveBeenCalledTimes(1);
|
||||
|
|
@ -130,7 +130,7 @@ describe("MusicLibraryService", () => {
|
|||
.mockRejectedValue(new Error("Generic Error"));
|
||||
|
||||
await expect(service.createArtist(createArtistDto)).rejects.toThrow(
|
||||
"Generic Error"
|
||||
"Generic Error",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
|
@ -167,7 +167,7 @@ describe("MusicLibraryService", () => {
|
|||
|
||||
it("updates the entity", async () => {
|
||||
await expect(service.updateArtist(updateArtistDto)).resolves.toEqual(
|
||||
artist
|
||||
artist,
|
||||
);
|
||||
|
||||
expect(artistRepository.save).toHaveBeenCalledTimes(1);
|
||||
|
|
@ -183,7 +183,7 @@ describe("MusicLibraryService", () => {
|
|||
.mockRejectedValue(new Error("Generic Error"));
|
||||
|
||||
await expect(service.updateArtist(updateArtistDto)).rejects.toThrow(
|
||||
"Generic Error"
|
||||
"Generic Error",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
|
@ -198,7 +198,7 @@ describe("MusicLibraryService", () => {
|
|||
albumRepository.findOneBy = jest.fn().mockResolvedValue(album);
|
||||
|
||||
await expect(
|
||||
service.findAlbum({ spotify: { id: "spotify_album" } })
|
||||
service.findAlbum({ spotify: { id: "spotify_album" } }),
|
||||
).resolves.toEqual(album);
|
||||
|
||||
expect(albumRepository.findOneBy).toHaveBeenCalledTimes(1);
|
||||
|
|
@ -231,7 +231,7 @@ describe("MusicLibraryService", () => {
|
|||
|
||||
it("creates the entity", async () => {
|
||||
await expect(service.createAlbum(createAlbumDto)).resolves.toEqual(
|
||||
album
|
||||
album,
|
||||
);
|
||||
|
||||
expect(albumRepository.create).toHaveBeenCalledTimes(1);
|
||||
|
|
@ -256,7 +256,7 @@ describe("MusicLibraryService", () => {
|
|||
.mockRejectedValue(uniqueViolationError);
|
||||
|
||||
await expect(service.createAlbum(createAlbumDto)).resolves.toEqual(
|
||||
album
|
||||
album,
|
||||
);
|
||||
|
||||
expect(service.findAlbum).toHaveBeenCalledTimes(1);
|
||||
|
|
@ -271,7 +271,7 @@ describe("MusicLibraryService", () => {
|
|||
.mockRejectedValue(new Error("Generic Error"));
|
||||
|
||||
await expect(service.createAlbum(createAlbumDto)).rejects.toThrow(
|
||||
"Generic Error"
|
||||
"Generic Error",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
|
@ -287,7 +287,7 @@ describe("MusicLibraryService", () => {
|
|||
genreRepository.findOneBy = jest.fn().mockResolvedValue(genre);
|
||||
|
||||
await expect(service.findGenre({ name: "Foo" })).resolves.toEqual(
|
||||
genre
|
||||
genre,
|
||||
);
|
||||
|
||||
expect(genreRepository.findOneBy).toHaveBeenCalledTimes(1);
|
||||
|
|
@ -317,7 +317,7 @@ describe("MusicLibraryService", () => {
|
|||
|
||||
it("creates the entity", async () => {
|
||||
await expect(service.createGenre(createGenreDto)).resolves.toEqual(
|
||||
genre
|
||||
genre,
|
||||
);
|
||||
|
||||
expect(genreRepository.create).toHaveBeenCalledTimes(1);
|
||||
|
|
@ -342,7 +342,7 @@ describe("MusicLibraryService", () => {
|
|||
.mockRejectedValue(uniqueViolationError);
|
||||
|
||||
await expect(service.createGenre(createGenreDto)).resolves.toEqual(
|
||||
genre
|
||||
genre,
|
||||
);
|
||||
|
||||
expect(service.findGenre).toHaveBeenCalledTimes(1);
|
||||
|
|
@ -357,7 +357,7 @@ describe("MusicLibraryService", () => {
|
|||
.mockRejectedValue(new Error("Generic Error"));
|
||||
|
||||
await expect(service.createGenre(createGenreDto)).rejects.toThrow(
|
||||
"Generic Error"
|
||||
"Generic Error",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
|
@ -372,7 +372,7 @@ describe("MusicLibraryService", () => {
|
|||
trackRepository.findOneBy = jest.fn().mockResolvedValue(track);
|
||||
|
||||
await expect(
|
||||
service.findTrack({ spotify: { id: "spotify_track" } })
|
||||
service.findTrack({ spotify: { id: "spotify_track" } }),
|
||||
).resolves.toEqual(track);
|
||||
|
||||
expect(trackRepository.findOneBy).toHaveBeenCalledTimes(1);
|
||||
|
|
@ -405,7 +405,7 @@ describe("MusicLibraryService", () => {
|
|||
|
||||
it("creates the entity", async () => {
|
||||
await expect(service.createTrack(createTrackDto)).resolves.toEqual(
|
||||
track
|
||||
track,
|
||||
);
|
||||
|
||||
expect(trackRepository.create).toHaveBeenCalledTimes(1);
|
||||
|
|
@ -430,7 +430,7 @@ describe("MusicLibraryService", () => {
|
|||
.mockRejectedValue(uniqueViolationError);
|
||||
|
||||
await expect(service.createTrack(createTrackDto)).resolves.toEqual(
|
||||
track
|
||||
track,
|
||||
);
|
||||
|
||||
expect(service.findTrack).toHaveBeenCalledTimes(1);
|
||||
|
|
@ -445,7 +445,7 @@ describe("MusicLibraryService", () => {
|
|||
.mockRejectedValue(new Error("Generic Error"));
|
||||
|
||||
await expect(service.createTrack(createTrackDto)).rejects.toThrow(
|
||||
"Generic Error"
|
||||
"Generic Error",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -24,7 +24,7 @@ export class MusicLibraryService {
|
|||
private readonly albumRepository: AlbumRepository,
|
||||
private readonly artistRepository: ArtistRepository,
|
||||
private readonly genreRepository: GenreRepository,
|
||||
private readonly trackRepository: TrackRepository
|
||||
private readonly trackRepository: TrackRepository,
|
||||
) {}
|
||||
|
||||
async findArtist(query: FindArtistDto): Promise<Artist | undefined> {
|
||||
|
|
@ -77,7 +77,7 @@ export class MusicLibraryService {
|
|||
|
||||
async createArtists(data: CreateArtistDto[]): Promise<Artist[]> {
|
||||
return this.artistRepository.save(
|
||||
data.map((entry) => this.artistRepository.create(entry))
|
||||
data.map((entry) => this.artistRepository.create(entry)),
|
||||
);
|
||||
}
|
||||
|
||||
|
|
@ -129,7 +129,7 @@ export class MusicLibraryService {
|
|||
|
||||
async createAlbums(data: CreateAlbumDto[]): Promise<Album[]> {
|
||||
return this.albumRepository.save(
|
||||
data.map((entry) => this.albumRepository.create(entry))
|
||||
data.map((entry) => this.albumRepository.create(entry)),
|
||||
);
|
||||
}
|
||||
|
||||
|
|
@ -170,7 +170,7 @@ export class MusicLibraryService {
|
|||
|
||||
async createGenres(data: CreateGenreDto[]): Promise<Genre[]> {
|
||||
return this.genreRepository.save(
|
||||
data.map((entry) => this.genreRepository.create(entry))
|
||||
data.map((entry) => this.genreRepository.create(entry)),
|
||||
);
|
||||
}
|
||||
|
||||
|
|
@ -212,7 +212,7 @@ export class MusicLibraryService {
|
|||
|
||||
async createTracks(data: CreateTrackDto[]): Promise<Track[]> {
|
||||
return this.trackRepository.save(
|
||||
data.map((entry) => this.trackRepository.create(entry))
|
||||
data.map((entry) => this.trackRepository.create(entry)),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -19,7 +19,7 @@ describe("UrlValueParserService", () => {
|
|||
describe("replacePathValues", () => {
|
||||
it("works with default replacement", () => {
|
||||
const replaced = service.replacePathValues(
|
||||
"/in/world/14/userId/abca12d231"
|
||||
"/in/world/14/userId/abca12d231",
|
||||
);
|
||||
expect(replaced).toBe("/in/world/#val/userId/#val");
|
||||
});
|
||||
|
|
@ -27,21 +27,21 @@ describe("UrlValueParserService", () => {
|
|||
it("works with custom replacement", () => {
|
||||
const replaced = service.replacePathValues(
|
||||
"/in/world/14/userId/abca12d231",
|
||||
"<id>"
|
||||
"<id>",
|
||||
);
|
||||
expect(replaced).toBe("/in/world/<id>/userId/<id>");
|
||||
});
|
||||
|
||||
it("works with negative decimal numbers", () => {
|
||||
const replaced = service.replacePathValues(
|
||||
"/some/path/-154/userId/-ABC363AFE2"
|
||||
"/some/path/-154/userId/-ABC363AFE2",
|
||||
);
|
||||
expect(replaced).toBe("/some/path/#val/userId/-ABC363AFE2");
|
||||
});
|
||||
|
||||
it("works with spotify ids", () => {
|
||||
const replaced = service.replacePathValues(
|
||||
"/v1/albums/2PzfMWIpq6JKucGhkS1X5M"
|
||||
"/v1/albums/2PzfMWIpq6JKucGhkS1X5M",
|
||||
);
|
||||
expect(replaced).toBe("/v1/albums/#val");
|
||||
});
|
||||
|
|
|
|||
|
|
@ -32,7 +32,7 @@ export class UrlValueParserService {
|
|||
"/" +
|
||||
parseResult.chunks
|
||||
.map((chunk, i) =>
|
||||
parseResult.valueIndexes.includes(i) ? replacement : chunk
|
||||
parseResult.valueIndexes.includes(i) ? replacement : chunk,
|
||||
)
|
||||
.join("/")
|
||||
);
|
||||
|
|
|
|||
|
|
@ -22,7 +22,7 @@ export class ReportsController {
|
|||
async getListens(
|
||||
@Query() time: ReportTimeDto,
|
||||
@Query("timeFrame") timeFrame: Timeframe,
|
||||
@ReqUser() user: User
|
||||
@ReqUser() user: User,
|
||||
): Promise<ListenReportDto> {
|
||||
return this.reportsService.getListens({ user, timeFrame, time });
|
||||
}
|
||||
|
|
@ -31,7 +31,7 @@ export class ReportsController {
|
|||
@AuthAccessToken()
|
||||
async getTopArtists(
|
||||
@Query() time: ReportTimeDto,
|
||||
@ReqUser() user: User
|
||||
@ReqUser() user: User,
|
||||
): Promise<TopArtistsReportDto> {
|
||||
return this.reportsService.getTopArtists({ user, time });
|
||||
}
|
||||
|
|
@ -40,7 +40,7 @@ export class ReportsController {
|
|||
@AuthAccessToken()
|
||||
async getTopAlbums(
|
||||
@Query() time: ReportTimeDto,
|
||||
@ReqUser() user: User
|
||||
@ReqUser() user: User,
|
||||
): Promise<TopAlbumsReportDto> {
|
||||
return this.reportsService.getTopAlbums({ user, time });
|
||||
}
|
||||
|
|
@ -49,7 +49,7 @@ export class ReportsController {
|
|||
@AuthAccessToken()
|
||||
async getTopTracks(
|
||||
@Query() time: ReportTimeDto,
|
||||
@ReqUser() user: User
|
||||
@ReqUser() user: User,
|
||||
): Promise<TopTracksReportDto> {
|
||||
return this.reportsService.getTopTracks({ user, time });
|
||||
}
|
||||
|
|
@ -58,7 +58,7 @@ export class ReportsController {
|
|||
@AuthAccessToken()
|
||||
async getTopGenres(
|
||||
@Query() time: ReportTimeDto,
|
||||
@ReqUser() user: User
|
||||
@ReqUser() user: User,
|
||||
): Promise<TopGenresReportDto> {
|
||||
return this.reportsService.getTopGenres({ user, time });
|
||||
}
|
||||
|
|
|
|||
|
|
@ -90,7 +90,7 @@ export class ReportsService {
|
|||
// efficient or make pauses for event loop.
|
||||
const reportItems = eachOfInterval(interval).map((date) => {
|
||||
const count = listens.filter((listen) =>
|
||||
isSame(date, listen.playedAt)
|
||||
isSame(date, listen.playedAt),
|
||||
).length;
|
||||
return { date: formatISO(date), count };
|
||||
});
|
||||
|
|
@ -99,7 +99,7 @@ export class ReportsService {
|
|||
}
|
||||
|
||||
async getTopArtists(
|
||||
options: GetTopArtistsReportDto
|
||||
options: GetTopArtistsReportDto,
|
||||
): Promise<TopArtistsReportDto> {
|
||||
const getArtistsWithCountQB = this.getListensQueryFromOptions(options)
|
||||
.leftJoin("listen.track", "track")
|
||||
|
|
@ -125,7 +125,7 @@ export class ReportsService {
|
|||
href: data.spotifyHref,
|
||||
},
|
||||
},
|
||||
})
|
||||
}),
|
||||
);
|
||||
|
||||
return {
|
||||
|
|
@ -134,7 +134,7 @@ export class ReportsService {
|
|||
}
|
||||
|
||||
async getTopAlbums(
|
||||
options: GetTopAlbumsReportDto
|
||||
options: GetTopAlbumsReportDto,
|
||||
): Promise<TopAlbumsReportDto> {
|
||||
const [rawAlbumsWithCount, rawAlbumDetails] = await Promise.all([
|
||||
this.getListensQueryFromOptions(options)
|
||||
|
|
@ -164,7 +164,7 @@ export class ReportsService {
|
|||
(data) => ({
|
||||
count: Number.parseInt(data.listens, 10),
|
||||
album: albumDetails.find((album) => album.id === data.album_id),
|
||||
})
|
||||
}),
|
||||
);
|
||||
|
||||
return {
|
||||
|
|
@ -173,7 +173,7 @@ export class ReportsService {
|
|||
}
|
||||
|
||||
async getTopTracks(
|
||||
options: GetTopTracksReportDto
|
||||
options: GetTopTracksReportDto,
|
||||
): Promise<TopTracksReportDto> {
|
||||
const [rawTracksWithCount, rawTrackDetails] = await Promise.all([
|
||||
this.getListensQueryFromOptions(options)
|
||||
|
|
@ -201,7 +201,7 @@ export class ReportsService {
|
|||
(data) => ({
|
||||
count: Number.parseInt(data.listens, 10),
|
||||
track: trackDetails.find((track) => track.id === data.id),
|
||||
})
|
||||
}),
|
||||
);
|
||||
|
||||
return {
|
||||
|
|
@ -210,7 +210,7 @@ export class ReportsService {
|
|||
}
|
||||
|
||||
async getTopGenres(
|
||||
options: GetTopGenresReportDto
|
||||
options: GetTopGenresReportDto,
|
||||
): Promise<TopGenresReportDto> {
|
||||
const [rawGenresWithCount, rawGenresWithArtistsCount] = await Promise.all([
|
||||
this.getListensQueryFromOptions(options)
|
||||
|
|
@ -298,7 +298,7 @@ export class ReportsService {
|
|||
case TimePreset.LAST_180_DAYS:
|
||||
case TimePreset.LAST_365_DAYS: {
|
||||
interval.start = startOfDay(
|
||||
sub(interval.start, { days: timePresetToDays[options.timePreset] })
|
||||
sub(interval.start, { days: timePresetToDays[options.timePreset] }),
|
||||
);
|
||||
break;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -2,12 +2,12 @@ import { createJob } from "@apricote/nest-pg-boss";
|
|||
|
||||
export type ICrawlerSupervisorJob = {};
|
||||
export const CrawlerSupervisorJob = createJob<ICrawlerSupervisorJob>(
|
||||
"spotify-crawler-supervisor"
|
||||
"spotify-crawler-supervisor",
|
||||
);
|
||||
|
||||
export type IUpdateSpotifyLibraryJob = {};
|
||||
export const UpdateSpotifyLibraryJob = createJob<IUpdateSpotifyLibraryJob>(
|
||||
"update-spotify-library"
|
||||
"update-spotify-library",
|
||||
);
|
||||
|
||||
export type IImportSpotifyJob = { userID: string };
|
||||
|
|
|
|||
|
|
@ -24,7 +24,7 @@ export class SchedulerService implements OnApplicationBootstrap {
|
|||
@ImportSpotifyJob.Inject()
|
||||
private readonly importSpotifyJobService: JobService<IImportSpotifyJob>,
|
||||
@UpdateSpotifyLibraryJob.Inject()
|
||||
private readonly updateSpotifyLibraryJobService: JobService<IUpdateSpotifyLibraryJob>
|
||||
private readonly updateSpotifyLibraryJobService: JobService<IUpdateSpotifyLibraryJob>,
|
||||
) {}
|
||||
|
||||
async onApplicationBootstrap() {
|
||||
|
|
@ -65,9 +65,9 @@ export class SchedulerService implements OnApplicationBootstrap {
|
|||
{ userID: user.id },
|
||||
{},
|
||||
pollRate,
|
||||
user.id
|
||||
user.id,
|
||||
);
|
||||
})
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -6,14 +6,14 @@ import {
|
|||
import { HttpService } from "@nestjs/axios";
|
||||
import { Injectable, Logger } from "@nestjs/common";
|
||||
import { Counter, Histogram } from "@opentelemetry/api-metrics";
|
||||
import type { AxiosRequestConfig } from "axios";
|
||||
import type { InternalAxiosRequestConfig } from "axios";
|
||||
import { MetricService } from "nestjs-otel";
|
||||
import { UrlValueParserService } from "../../../open-telemetry/url-value-parser.service";
|
||||
|
||||
const SPOTIFY_API_METRICS_CONFIG_KEY = Symbol("kSpotifyApiMetricsInterceptor");
|
||||
|
||||
// Merging our custom properties with the base config
|
||||
interface SpotifyApiMetricsConfig extends AxiosRequestConfig {
|
||||
interface SpotifyApiMetricsConfig extends InternalAxiosRequestConfig {
|
||||
[SPOTIFY_API_METRICS_CONFIG_KEY]: {
|
||||
startTime: number;
|
||||
};
|
||||
|
|
@ -28,13 +28,13 @@ export class MetricsInterceptor extends AxiosInterceptor<SpotifyApiMetricsConfig
|
|||
constructor(
|
||||
httpService: HttpService,
|
||||
metricService: MetricService,
|
||||
private readonly urlValueParserService: UrlValueParserService
|
||||
private readonly urlValueParserService: UrlValueParserService,
|
||||
) {
|
||||
super(httpService);
|
||||
|
||||
this.responseCounter = metricService.getCounter(
|
||||
"listory_spotify_api_http_response",
|
||||
{ description: "Total number of HTTP responses from Spotify API" }
|
||||
{ description: "Total number of HTTP responses from Spotify API" },
|
||||
);
|
||||
|
||||
this.requestHistogram = metricService.getHistogram(
|
||||
|
|
@ -43,7 +43,7 @@ export class MetricsInterceptor extends AxiosInterceptor<SpotifyApiMetricsConfig
|
|||
description:
|
||||
"HTTP latency value recorder in seconds for requests made to Spotify API",
|
||||
unit: "seconds",
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
|
|
@ -71,7 +71,7 @@ export class MetricsInterceptor extends AxiosInterceptor<SpotifyApiMetricsConfig
|
|||
status: response.status.toString(),
|
||||
path: this.urlValueParserService.replacePathValues(
|
||||
response.config.url,
|
||||
"<id>"
|
||||
"<id>",
|
||||
),
|
||||
};
|
||||
|
||||
|
|
|
|||
|
|
@ -25,8 +25,8 @@ export class SpotifyApiService {
|
|||
{
|
||||
headers: { Authorization: `Bearer ${accessToken}` },
|
||||
params: parameters,
|
||||
}
|
||||
)
|
||||
},
|
||||
),
|
||||
);
|
||||
|
||||
return history.data.items;
|
||||
|
|
@ -34,12 +34,12 @@ export class SpotifyApiService {
|
|||
|
||||
async getArtist(
|
||||
accessToken: string,
|
||||
spotifyID: string
|
||||
spotifyID: string,
|
||||
): Promise<ArtistObject> {
|
||||
const artist = await firstValueFrom(
|
||||
this.httpService.get<ArtistObject>(`v1/artists/${spotifyID}`, {
|
||||
headers: { Authorization: `Bearer ${accessToken}` },
|
||||
})
|
||||
}),
|
||||
);
|
||||
|
||||
return artist.data;
|
||||
|
|
@ -47,7 +47,7 @@ export class SpotifyApiService {
|
|||
|
||||
async getArtists(
|
||||
accessToken: string,
|
||||
spotifyIDs: string[]
|
||||
spotifyIDs: string[],
|
||||
): Promise<ArtistObject[]> {
|
||||
const artist = await firstValueFrom(
|
||||
this.httpService.get<{ artists: ArtistObject[] }>(`v1/artists`, {
|
||||
|
|
@ -55,7 +55,7 @@ export class SpotifyApiService {
|
|||
params: {
|
||||
ids: spotifyIDs.join(","),
|
||||
},
|
||||
})
|
||||
}),
|
||||
);
|
||||
|
||||
return artist.data.artists;
|
||||
|
|
@ -65,14 +65,14 @@ export class SpotifyApiService {
|
|||
const album = await firstValueFrom(
|
||||
this.httpService.get<AlbumObject>(`v1/albums/${spotifyID}`, {
|
||||
headers: { Authorization: `Bearer ${accessToken}` },
|
||||
})
|
||||
}),
|
||||
);
|
||||
return album.data;
|
||||
}
|
||||
|
||||
async getAlbums(
|
||||
accessToken: string,
|
||||
spotifyIDs: string[]
|
||||
spotifyIDs: string[],
|
||||
): Promise<AlbumObject[]> {
|
||||
const album = await firstValueFrom(
|
||||
this.httpService.get<{ albums: AlbumObject[] }>(`v1/albums`, {
|
||||
|
|
@ -80,7 +80,7 @@ export class SpotifyApiService {
|
|||
params: {
|
||||
ids: spotifyIDs.join(","),
|
||||
},
|
||||
})
|
||||
}),
|
||||
);
|
||||
return album.data.albums;
|
||||
}
|
||||
|
|
@ -89,7 +89,7 @@ export class SpotifyApiService {
|
|||
const track = await firstValueFrom(
|
||||
this.httpService.get<TrackObject>(`v1/tracks/${spotifyID}`, {
|
||||
headers: { Authorization: `Bearer ${accessToken}` },
|
||||
})
|
||||
}),
|
||||
);
|
||||
|
||||
return track.data;
|
||||
|
|
@ -97,7 +97,7 @@ export class SpotifyApiService {
|
|||
|
||||
async getTracks(
|
||||
accessToken: string,
|
||||
spotifyIDs: string[]
|
||||
spotifyIDs: string[],
|
||||
): Promise<TrackObject[]> {
|
||||
const track = await firstValueFrom(
|
||||
this.httpService.get<{ tracks: TrackObject[] }>(`v1/tracks`, {
|
||||
|
|
@ -105,7 +105,7 @@ export class SpotifyApiService {
|
|||
params: {
|
||||
ids: spotifyIDs.join(","),
|
||||
},
|
||||
})
|
||||
}),
|
||||
);
|
||||
|
||||
return track.data.tracks;
|
||||
|
|
|
|||
|
|
@ -11,7 +11,7 @@ export class SpotifyAuthService {
|
|||
|
||||
constructor(
|
||||
private readonly httpService: HttpService,
|
||||
config: ConfigService
|
||||
config: ConfigService,
|
||||
) {
|
||||
this.clientID = config.get<string>("SPOTIFY_CLIENT_ID");
|
||||
this.clientSecret = config.get<string>("SPOTIFY_CLIENT_SECRET");
|
||||
|
|
@ -27,8 +27,8 @@ export class SpotifyAuthService {
|
|||
username: this.clientID,
|
||||
password: this.clientSecret,
|
||||
},
|
||||
}
|
||||
)
|
||||
},
|
||||
),
|
||||
);
|
||||
|
||||
return response.data.access_token;
|
||||
|
|
@ -44,8 +44,8 @@ export class SpotifyAuthService {
|
|||
username: this.clientID,
|
||||
password: this.clientSecret,
|
||||
},
|
||||
}
|
||||
)
|
||||
},
|
||||
),
|
||||
);
|
||||
|
||||
return response.data.access_token;
|
||||
|
|
|
|||
|
|
@ -39,7 +39,7 @@ export class SpotifyService {
|
|||
private readonly listensService: ListensService,
|
||||
private readonly musicLibraryService: MusicLibraryService,
|
||||
private readonly spotifyApi: SpotifyApiService,
|
||||
private readonly spotifyAuth: SpotifyAuthService
|
||||
private readonly spotifyAuth: SpotifyAuthService,
|
||||
) {}
|
||||
|
||||
@Span()
|
||||
|
|
@ -82,7 +82,7 @@ export class SpotifyService {
|
|||
@Span()
|
||||
async crawlListensForUser(
|
||||
user: User,
|
||||
retryOnExpiredToken: boolean = true
|
||||
retryOnExpiredToken: boolean = true,
|
||||
): Promise<void> {
|
||||
this.logger.debug({ userId: user.id }, `Crawling recently played tracks`);
|
||||
|
||||
|
|
@ -93,7 +93,7 @@ export class SpotifyService {
|
|||
if (err.response && err.response.status === 401 && retryOnExpiredToken) {
|
||||
try {
|
||||
const accessToken = await this.spotifyAuth.refreshAccessToken(
|
||||
user.spotify
|
||||
user.spotify,
|
||||
);
|
||||
await this.usersService.updateSpotifyConnection(user, {
|
||||
...user.spotify,
|
||||
|
|
@ -103,7 +103,7 @@ export class SpotifyService {
|
|||
} catch (errFromAuth) {
|
||||
this.logger.error(
|
||||
{ userId: user.id },
|
||||
`Refreshing access token failed for user "${user.id}": ${errFromAuth}`
|
||||
`Refreshing access token failed for user "${user.id}": ${errFromAuth}`,
|
||||
);
|
||||
throw errFromAuth;
|
||||
}
|
||||
|
|
@ -112,7 +112,7 @@ export class SpotifyService {
|
|||
}
|
||||
|
||||
this.logger.error(
|
||||
`Unexpected error while fetching recently played tracks: ${err}`
|
||||
`Unexpected error while fetching recently played tracks: ${err}`,
|
||||
);
|
||||
throw err;
|
||||
}
|
||||
|
|
@ -122,7 +122,7 @@ export class SpotifyService {
|
|||
}
|
||||
|
||||
const tracks = await this.importTracks(
|
||||
uniq(playHistory.map((history) => history.track.id))
|
||||
uniq(playHistory.map((history) => history.track.id)),
|
||||
);
|
||||
|
||||
const listenData = playHistory.map((history) => ({
|
||||
|
|
@ -140,15 +140,15 @@ export class SpotifyService {
|
|||
listen.track.name
|
||||
}" by ${listen.track.artists
|
||||
?.map((artist) => `"${artist.name}"`)
|
||||
.join(", ")}`
|
||||
)
|
||||
.join(", ")}`,
|
||||
),
|
||||
);
|
||||
|
||||
const newestPlayTime = new Date(
|
||||
playHistory
|
||||
.map((history) => history.played_at)
|
||||
.sort()
|
||||
.pop()
|
||||
.pop(),
|
||||
);
|
||||
|
||||
/**
|
||||
|
|
@ -181,7 +181,7 @@ export class SpotifyService {
|
|||
@Span()
|
||||
async importTrack(
|
||||
spotifyID: string,
|
||||
retryOnExpiredToken: boolean = true
|
||||
retryOnExpiredToken: boolean = true,
|
||||
): Promise<Track> {
|
||||
const track = await this.musicLibraryService.findTrack({
|
||||
spotify: { id: spotifyID },
|
||||
|
|
@ -195,7 +195,7 @@ export class SpotifyService {
|
|||
try {
|
||||
spotifyTrack = await this.spotifyApi.getTrack(
|
||||
this.appAccessToken,
|
||||
spotifyID
|
||||
spotifyID,
|
||||
);
|
||||
} catch (err) {
|
||||
if (err.response && err.response.status === 401 && retryOnExpiredToken) {
|
||||
|
|
@ -211,8 +211,8 @@ export class SpotifyService {
|
|||
this.importAlbum(spotifyTrack.album.id),
|
||||
Promise.all(
|
||||
spotifyTrack.artists.map(({ id: artistID }) =>
|
||||
this.importArtist(artistID)
|
||||
)
|
||||
this.importArtist(artistID),
|
||||
),
|
||||
),
|
||||
]);
|
||||
|
||||
|
|
@ -232,15 +232,15 @@ export class SpotifyService {
|
|||
@Span()
|
||||
async importTracks(
|
||||
spotifyIDs: string[],
|
||||
retryOnExpiredToken: boolean = true
|
||||
retryOnExpiredToken: boolean = true,
|
||||
): Promise<Track[]> {
|
||||
const tracks = await this.musicLibraryService.findTracks(
|
||||
spotifyIDs.map((id) => ({ spotify: { id } }))
|
||||
spotifyIDs.map((id) => ({ spotify: { id } })),
|
||||
);
|
||||
|
||||
// Get missing ids
|
||||
const missingIDs = spotifyIDs.filter(
|
||||
(id) => !tracks.some((track) => track.spotify.id === id)
|
||||
(id) => !tracks.some((track) => track.spotify.id === id),
|
||||
);
|
||||
|
||||
// No need to make spotify api request if all data is available locally
|
||||
|
|
@ -256,11 +256,11 @@ export class SpotifyService {
|
|||
chunk(missingIDs, SPOTIFY_BULK_MAX_IDS).map(async (ids) => {
|
||||
const batchTracks = await this.spotifyApi.getTracks(
|
||||
this.appAccessToken,
|
||||
ids
|
||||
ids,
|
||||
);
|
||||
|
||||
spotifyTracks.push(...batchTracks);
|
||||
})
|
||||
}),
|
||||
);
|
||||
} catch (err) {
|
||||
if (err.response && err.response.status === 401 && retryOnExpiredToken) {
|
||||
|
|
@ -279,24 +279,24 @@ export class SpotifyService {
|
|||
const artists = await this.importArtists(
|
||||
uniq(
|
||||
spotifyTracks.flatMap((track) =>
|
||||
track.artists.map((artist) => artist.id)
|
||||
)
|
||||
)
|
||||
track.artists.map((artist) => artist.id),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const albums = await this.importAlbums(
|
||||
uniq(spotifyTracks.map((track) => track.album.id))
|
||||
uniq(spotifyTracks.map((track) => track.album.id)),
|
||||
);
|
||||
|
||||
// Find the right albums & artists for each spotify track & create db entry
|
||||
const newTracks = await this.musicLibraryService.createTracks(
|
||||
spotifyTracks.map((spotifyTrack) => {
|
||||
const trackAlbum = albums.find(
|
||||
(album) => spotifyTrack.album.id === album.spotify.id
|
||||
(album) => spotifyTrack.album.id === album.spotify.id,
|
||||
);
|
||||
|
||||
const trackArtists = spotifyTrack.artists.map((trackArtist) =>
|
||||
artists.find((artist) => trackArtist.id == artist.spotify.id)
|
||||
artists.find((artist) => trackArtist.id == artist.spotify.id),
|
||||
);
|
||||
|
||||
return {
|
||||
|
|
@ -310,7 +310,7 @@ export class SpotifyService {
|
|||
href: spotifyTrack.href,
|
||||
},
|
||||
};
|
||||
})
|
||||
}),
|
||||
);
|
||||
|
||||
// Return new & existing tracks
|
||||
|
|
@ -320,7 +320,7 @@ export class SpotifyService {
|
|||
@Span()
|
||||
async importAlbum(
|
||||
spotifyID: string,
|
||||
retryOnExpiredToken: boolean = true
|
||||
retryOnExpiredToken: boolean = true,
|
||||
): Promise<Album> {
|
||||
const album = await this.musicLibraryService.findAlbum({
|
||||
spotify: { id: spotifyID },
|
||||
|
|
@ -334,7 +334,7 @@ export class SpotifyService {
|
|||
try {
|
||||
spotifyAlbum = await this.spotifyApi.getAlbum(
|
||||
this.appAccessToken,
|
||||
spotifyID
|
||||
spotifyID,
|
||||
);
|
||||
} catch (err) {
|
||||
if (err.response && err.response.status === 401 && retryOnExpiredToken) {
|
||||
|
|
@ -348,8 +348,8 @@ export class SpotifyService {
|
|||
|
||||
const artists = await Promise.all(
|
||||
spotifyAlbum.artists.map(({ id: artistID }) =>
|
||||
this.importArtist(artistID)
|
||||
)
|
||||
this.importArtist(artistID),
|
||||
),
|
||||
);
|
||||
|
||||
return this.musicLibraryService.createAlbum({
|
||||
|
|
@ -367,15 +367,15 @@ export class SpotifyService {
|
|||
@Span()
|
||||
async importAlbums(
|
||||
spotifyIDs: string[],
|
||||
retryOnExpiredToken: boolean = true
|
||||
retryOnExpiredToken: boolean = true,
|
||||
): Promise<Album[]> {
|
||||
const albums = await this.musicLibraryService.findAlbums(
|
||||
spotifyIDs.map((id) => ({ spotify: { id } }))
|
||||
spotifyIDs.map((id) => ({ spotify: { id } })),
|
||||
);
|
||||
|
||||
// Get missing ids
|
||||
const missingIDs = spotifyIDs.filter(
|
||||
(id) => !albums.some((album) => album.spotify.id === id)
|
||||
(id) => !albums.some((album) => album.spotify.id === id),
|
||||
);
|
||||
|
||||
// No need to make spotify api request if all data is available locally
|
||||
|
|
@ -391,11 +391,11 @@ export class SpotifyService {
|
|||
chunk(missingIDs, SPOTIFY_BULK_ALBUMS_MAX_IDS).map(async (ids) => {
|
||||
const batchAlbums = await this.spotifyApi.getAlbums(
|
||||
this.appAccessToken,
|
||||
ids
|
||||
ids,
|
||||
);
|
||||
|
||||
spotifyAlbums.push(...batchAlbums);
|
||||
})
|
||||
}),
|
||||
);
|
||||
} catch (err) {
|
||||
if (err.response && err.response.status === 401 && retryOnExpiredToken) {
|
||||
|
|
@ -410,16 +410,16 @@ export class SpotifyService {
|
|||
const artists = await this.importArtists(
|
||||
uniq(
|
||||
spotifyAlbums.flatMap((album) =>
|
||||
album.artists.map((artist) => artist.id)
|
||||
)
|
||||
)
|
||||
album.artists.map((artist) => artist.id),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
// Find the right albums & artists for each spotify track & create db entry
|
||||
const newAlbums = await this.musicLibraryService.createAlbums(
|
||||
spotifyAlbums.map((spotifyAlbum) => {
|
||||
const albumArtists = spotifyAlbum.artists.map((albumArtist) =>
|
||||
artists.find((artist) => albumArtist.id == artist.spotify.id)
|
||||
artists.find((artist) => albumArtist.id == artist.spotify.id),
|
||||
);
|
||||
|
||||
return {
|
||||
|
|
@ -432,7 +432,7 @@ export class SpotifyService {
|
|||
href: spotifyAlbum.href,
|
||||
},
|
||||
};
|
||||
})
|
||||
}),
|
||||
);
|
||||
|
||||
return [...albums, ...newAlbums];
|
||||
|
|
@ -441,7 +441,7 @@ export class SpotifyService {
|
|||
@Span()
|
||||
async importArtist(
|
||||
spotifyID: string,
|
||||
retryOnExpiredToken: boolean = true
|
||||
retryOnExpiredToken: boolean = true,
|
||||
): Promise<Artist> {
|
||||
const artist = await this.musicLibraryService.findArtist({
|
||||
spotify: { id: spotifyID },
|
||||
|
|
@ -455,7 +455,7 @@ export class SpotifyService {
|
|||
try {
|
||||
spotifyArtist = await this.spotifyApi.getArtist(
|
||||
this.appAccessToken,
|
||||
spotifyID
|
||||
spotifyID,
|
||||
);
|
||||
} catch (err) {
|
||||
if (err.response && err.response.status === 401 && retryOnExpiredToken) {
|
||||
|
|
@ -468,7 +468,7 @@ export class SpotifyService {
|
|||
}
|
||||
|
||||
const genres = await Promise.all(
|
||||
spotifyArtist.genres.map((genreName) => this.importGenre(genreName))
|
||||
spotifyArtist.genres.map((genreName) => this.importGenre(genreName)),
|
||||
);
|
||||
|
||||
return this.musicLibraryService.createArtist({
|
||||
|
|
@ -486,15 +486,15 @@ export class SpotifyService {
|
|||
@Span()
|
||||
async importArtists(
|
||||
spotifyIDs: string[],
|
||||
retryOnExpiredToken: boolean = true
|
||||
retryOnExpiredToken: boolean = true,
|
||||
): Promise<Artist[]> {
|
||||
const artists = await this.musicLibraryService.findArtists(
|
||||
spotifyIDs.map((id) => ({ spotify: { id } }))
|
||||
spotifyIDs.map((id) => ({ spotify: { id } })),
|
||||
);
|
||||
|
||||
// Get missing ids
|
||||
const missingIDs = spotifyIDs.filter(
|
||||
(id) => !artists.some((artist) => artist.spotify.id === id)
|
||||
(id) => !artists.some((artist) => artist.spotify.id === id),
|
||||
);
|
||||
|
||||
// No need to make spotify api request if all data is available locally
|
||||
|
|
@ -510,11 +510,11 @@ export class SpotifyService {
|
|||
chunk(missingIDs, SPOTIFY_BULK_MAX_IDS).map(async (ids) => {
|
||||
const batchArtists = await this.spotifyApi.getArtists(
|
||||
this.appAccessToken,
|
||||
ids
|
||||
ids,
|
||||
);
|
||||
|
||||
spotifyArtists.push(...batchArtists);
|
||||
})
|
||||
}),
|
||||
);
|
||||
} catch (err) {
|
||||
if (err.response && err.response.status === 401 && retryOnExpiredToken) {
|
||||
|
|
@ -527,14 +527,14 @@ export class SpotifyService {
|
|||
}
|
||||
|
||||
const genres = await this.importGenres(
|
||||
uniq(spotifyArtists.flatMap((artist) => artist.genres))
|
||||
uniq(spotifyArtists.flatMap((artist) => artist.genres)),
|
||||
);
|
||||
|
||||
// Find the right genres for each spotify artist & create db entry
|
||||
const newArtists = await this.musicLibraryService.createArtists(
|
||||
spotifyArtists.map((spotifyArtist) => {
|
||||
const artistGenres = spotifyArtist.genres.map((artistGenre) =>
|
||||
genres.find((genre) => artistGenre == genre.name)
|
||||
genres.find((genre) => artistGenre == genre.name),
|
||||
);
|
||||
|
||||
return {
|
||||
|
|
@ -547,7 +547,7 @@ export class SpotifyService {
|
|||
href: spotifyArtist.href,
|
||||
},
|
||||
};
|
||||
})
|
||||
}),
|
||||
);
|
||||
|
||||
return [...artists, ...newArtists];
|
||||
|
|
@ -556,7 +556,7 @@ export class SpotifyService {
|
|||
@Span()
|
||||
async updateArtist(
|
||||
spotifyID: string,
|
||||
retryOnExpiredToken: boolean = true
|
||||
retryOnExpiredToken: boolean = true,
|
||||
): Promise<Artist> {
|
||||
const artist = await this.importArtist(spotifyID, retryOnExpiredToken);
|
||||
|
||||
|
|
@ -565,7 +565,7 @@ export class SpotifyService {
|
|||
try {
|
||||
spotifyArtist = await this.spotifyApi.getArtist(
|
||||
this.appAccessToken,
|
||||
spotifyID
|
||||
spotifyID,
|
||||
);
|
||||
} catch (err) {
|
||||
if (err.response && err.response.status === 401 && retryOnExpiredToken) {
|
||||
|
|
@ -578,7 +578,7 @@ export class SpotifyService {
|
|||
}
|
||||
|
||||
const genres = await Promise.all(
|
||||
spotifyArtist.genres.map((genreName) => this.importGenre(genreName))
|
||||
spotifyArtist.genres.map((genreName) => this.importGenre(genreName)),
|
||||
);
|
||||
|
||||
await this.musicLibraryService.updateArtist({
|
||||
|
|
@ -609,12 +609,12 @@ export class SpotifyService {
|
|||
@Span()
|
||||
async importGenres(names: string[]): Promise<Genre[]> {
|
||||
const genres = await this.musicLibraryService.findGenres(
|
||||
names.map((name) => ({ name }))
|
||||
names.map((name) => ({ name })),
|
||||
);
|
||||
|
||||
// Get missing genres
|
||||
const missingGenres = names.filter(
|
||||
(name) => !genres.some((genre) => genre.name === name)
|
||||
(name) => !genres.some((genre) => genre.name === name),
|
||||
);
|
||||
|
||||
// No need to create genres if all data is available locally
|
||||
|
|
@ -623,7 +623,7 @@ export class SpotifyService {
|
|||
}
|
||||
|
||||
const newGenres = await this.musicLibraryService.createGenres(
|
||||
missingGenres.map((name) => ({ name }))
|
||||
missingGenres.map((name) => ({ name })),
|
||||
);
|
||||
|
||||
return [...genres, ...newGenres];
|
||||
|
|
@ -646,7 +646,7 @@ export class SpotifyService {
|
|||
resolve();
|
||||
} catch (err) {
|
||||
this.logger.warn(
|
||||
`Error while refreshing spotify app access token ${err}`
|
||||
`Error while refreshing spotify app access token ${err}`,
|
||||
);
|
||||
|
||||
reject(err);
|
||||
|
|
|
|||
|
|
@ -24,7 +24,7 @@ describe("UsersService", () => {
|
|||
service = module.get<UsersService>(UsersService);
|
||||
userRepository = module.get<UserRepository>(UserRepository);
|
||||
importSpotifyJobService = module.get<JobService<IImportSpotifyJob>>(
|
||||
ImportSpotifyJob.ServiceProvider.provide
|
||||
ImportSpotifyJob.ServiceProvider.provide,
|
||||
);
|
||||
});
|
||||
|
||||
|
|
|
|||
|
|
@ -11,7 +11,7 @@ export class UsersService {
|
|||
constructor(
|
||||
private readonly userRepository: UserRepository,
|
||||
@ImportSpotifyJob.Inject()
|
||||
private readonly importSpotifyJobService: JobService<IImportSpotifyJob>
|
||||
private readonly importSpotifyJobService: JobService<IImportSpotifyJob>,
|
||||
) {}
|
||||
|
||||
async findById(id: string): Promise<User> {
|
||||
|
|
@ -59,7 +59,7 @@ export class UsersService {
|
|||
|
||||
async updateSpotifyConnection(
|
||||
user: User,
|
||||
spotify: SpotifyConnection
|
||||
spotify: SpotifyConnection,
|
||||
): Promise<void> {
|
||||
// eslint-disable-next-line no-param-reassign
|
||||
user.spotify = spotify;
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue