Skip to content

Commit

Permalink
fix: inplayer in service
Browse files Browse the repository at this point in the history
  • Loading branch information
dbudzins committed Nov 30, 2022
1 parent b2cf9cb commit 57757e9
Show file tree
Hide file tree
Showing 6 changed files with 107 additions and 29 deletions.
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import jwtDecode from 'jwt-decode';

import { post, put, patch, get } from './cleeng.service';

import { getOverrideIP } from '#src/utils/common';
Expand All @@ -15,13 +17,40 @@ import type {
GetLocales,
GetCaptureStatus,
UpdateCaptureAnswers,
LoginPayload,
AuthData,
JwtDetails,
} from '#types/account';
import type { Config } from '#types/Config';

export const login: Login = async (payload, sandbox) => {
payload.customerIP = getOverrideIP();
return post(sandbox, '/auths', JSON.stringify(payload));
export const login: Login = async ({ config, email, password }) => {
const payload: LoginPayload = {
email,
password,
publisherId: config.integrations.cleeng?.id || '',
customerIP: getOverrideIP(),
};

const { responseData: auth, errors }: ServiceResponse<AuthData> = await post(!!config.integrations.cleeng?.useSandbox, '/auths', JSON.stringify(payload));

if (errors.length > 0) throw new Error(errors[0]);

return {
auth,
user: await getUser({ config, auth }),
};
};

async function getUser({ config, auth }: { config: Config; auth: AuthData }) {
const decodedToken: JwtDetails = jwtDecode(auth.jwt);
const customerId = decodedToken.customerId;
const { responseData: user, errors } = await getCustomer({ customerId }, !!config.integrations.cleeng?.useSandbox, auth.jwt);

if (errors.length > 0) throw new Error(errors[0]);

return user;
}

export const register: Register = async (payload, sandbox) => {
payload.customerIP = getOverrideIP();
return post(sandbox, '/customers', JSON.stringify(payload));
Expand Down
18 changes: 18 additions & 0 deletions src/services/inplayer.account.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import InPlayer from '@inplayer-org/inplayer.js';

import type { Login } from '#types/account';
import { processInplayerAccount, processInPlayerAuth } from '#src/utils/common';

export const login: Login = async ({ config, email, password }) => {
const { data } = await InPlayer.Account.signInV2({
email,
password,
clientId: config.integrations.inplayer?.clientId || '',
referrer: window.location.href,
});

return {
auth: processInPlayerAuth(data),
user: processInplayerAccount(data.account),
};
};
60 changes: 41 additions & 19 deletions src/stores/AccountController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@ import jwtDecode from 'jwt-decode';

import * as subscriptionService from '#src/services/subscription.service';
import { getPaymentDetails, getTransactions } from '#src/services/subscription.service';
import * as accountService from '#src/services/account.service';
import { fetchCustomerConsents, fetchPublisherConsents, updateCustomer } from '#src/services/account.service';
import * as cleengAccountService from '#src/services/cleeng.account.service';
import * as inplayerAccountService from '#src/services/inplayer.account.service';
import { useFavoritesStore } from '#src/stores/FavoritesStore';
import { useWatchHistoryStore } from '#src/stores/WatchHistoryStore';
import type { AuthData, Capture, CustomerConsent, JwtDetails } from '#types/account';
Expand All @@ -14,6 +14,7 @@ import { restoreWatchHistory, serializeWatchHistory } from '#src/stores/WatchHis
import { restoreFavorites, serializeFavorites } from '#src/stores/FavoritesController';
import { getMediaByWatchlist } from '#src/services/api.service';
import { queryClient } from '#src/providers/QueryProvider';
import type { AccessModel, Config } from '#types/Config';

const PERSIST_KEY_ACCOUNT = 'auth';

Expand Down Expand Up @@ -107,7 +108,7 @@ export async function updateUser(values: { firstName: string; lastName: string }

const { cleengSandbox } = useConfigStore.getState().getCleengData();

const response = await updateCustomer({ ...values, id: user.id.toString() }, cleengSandbox, auth.jwt);
const response = await cleengAccountService.updateCustomer({ ...values, id: user.id.toString() }, cleengSandbox, auth.jwt);

if (!response) {
return { errors: Array.of('Unknown error') };
Expand All @@ -121,7 +122,7 @@ export async function updateUser(values: { firstName: string; lastName: string }
}

const getFreshJwtToken = async (sandbox: boolean, auth: AuthData) => {
const result = await accountService.refreshToken({ refreshToken: auth.refreshToken }, sandbox);
const result = await cleengAccountService.refreshToken({ refreshToken: auth.refreshToken }, sandbox);

if (result.errors.length) throw new Error(result.errors[0]);

Expand All @@ -145,7 +146,7 @@ export const afterLogin = async (sandbox: boolean, auth: AuthData) => {
const { accessModel } = useConfigStore.getState();
const decodedToken: JwtDetails = jwtDecode(auth.jwt);
const customerId = decodedToken.customerId;
const response = await accountService.getCustomer({ customerId }, sandbox, auth.jwt);
const response = await cleengAccountService.getCustomer({ customerId }, sandbox, auth.jwt);

if (response.errors.length) throw new Error(response.errors[0]);

Expand All @@ -160,14 +161,19 @@ export const afterLogin = async (sandbox: boolean, auth: AuthData) => {
};

export const login = async (email: string, password: string) => {
await useConfig(async ({ cleengId, cleengSandbox }) => {
await withAccountService(async ({ accountService, config, accessModel }) => {
useAccountStore.setState({ loading: true });

const response = await accountService.login({ email, password, publisherId: cleengId }, cleengSandbox);
const response = await accountService.login({ config, email, password });

if (response.errors.length > 0) throw new Error(response.errors[0]);
useAccountStore.setState({
auth: response.auth,
user: response.user,
});

await Promise.allSettled([accessModel === 'SVOD' ? reloadActiveSubscription() : Promise.resolve(), getCustomerConsents(), getPublisherConsents()]);

await afterLogin(cleengSandbox, response.responseData);
useAccountStore.setState({ loading: false });

await restoreFavorites();
await restoreWatchHistory();
Expand Down Expand Up @@ -196,11 +202,11 @@ export const logout = async () => {

export const register = async (email: string, password: string) => {
await useConfig(async ({ cleengId, cleengSandbox }) => {
const localesResponse = await accountService.getLocales(cleengSandbox);
const localesResponse = await cleengAccountService.getLocales(cleengSandbox);

if (localesResponse.errors.length > 0) throw new Error(localesResponse.errors[0]);

const responseRegister = await accountService.register(
const responseRegister = await cleengAccountService.register(
{
email: email,
password: password,
Expand Down Expand Up @@ -232,7 +238,7 @@ export const updatePersonalShelves = async () => {
favorites: serializeFavorites(favorites),
};

return await accountService.updateCustomer(
return await cleengAccountService.updateCustomer(
{
id: customerId,
externalData: personalShelfData,
Expand All @@ -245,7 +251,7 @@ export const updatePersonalShelves = async () => {

export const updateConsents = async (customerConsents: CustomerConsent[]) => {
return await useLoginContext(async ({ cleengSandbox, customerId, auth: { jwt } }) => {
const response = await accountService.updateCustomerConsents(
const response = await cleengAccountService.updateCustomerConsents(
{
id: customerId,
consents: customerConsents,
Expand All @@ -262,7 +268,7 @@ export const updateConsents = async (customerConsents: CustomerConsent[]) => {

export async function getCustomerConsents() {
return await useLoginContext(async ({ cleengSandbox, customerId, auth: { jwt } }) => {
const response = await fetchCustomerConsents({ customerId }, cleengSandbox, jwt);
const response = await cleengAccountService.fetchCustomerConsents({ customerId }, cleengSandbox, jwt);

if (response && !response.errors?.length) {
useAccountStore.setState({ customerConsents: response.responseData.consents });
Expand All @@ -274,7 +280,7 @@ export async function getCustomerConsents() {

export async function getPublisherConsents() {
return await useConfig(async ({ cleengId, cleengSandbox }) => {
const response = await fetchPublisherConsents({ publisherId: cleengId }, cleengSandbox);
const response = await cleengAccountService.fetchPublisherConsents({ publisherId: cleengId }, cleengSandbox);

if (response && !response.errors?.length) {
useAccountStore.setState({ publisherConsents: response.responseData.consents });
Expand All @@ -286,7 +292,7 @@ export async function getPublisherConsents() {

export const getCaptureStatus = async () => {
return await useLoginContext(async ({ cleengSandbox, customerId, auth: { jwt } }) => {
const response = await accountService.getCaptureStatus({ customerId }, cleengSandbox, jwt);
const response = await cleengAccountService.getCaptureStatus({ customerId }, cleengSandbox, jwt);

if (response.errors.length > 0) throw new Error(response.errors[0]);

Expand All @@ -296,7 +302,7 @@ export const getCaptureStatus = async () => {

export const updateCaptureAnswers = async (capture: Capture) => {
return await useLoginContext(async ({ cleengSandbox, customerId, auth }) => {
const response = await accountService.updateCaptureAnswers({ customerId, ...capture }, cleengSandbox, auth.jwt);
const response = await cleengAccountService.updateCaptureAnswers({ customerId, ...capture }, cleengSandbox, auth.jwt);

if (response.errors.length > 0) throw new Error(response.errors[0]);

Expand All @@ -309,7 +315,7 @@ export const updateCaptureAnswers = async (capture: Capture) => {

export const resetPassword = async (email: string, resetUrl: string) => {
return await useConfig(async ({ cleengId, cleengSandbox }) => {
const response = await accountService.resetPassword(
const response = await cleengAccountService.resetPassword(
{
customerEmail: email,
publisherId: cleengId,
Expand All @@ -326,7 +332,7 @@ export const resetPassword = async (email: string, resetUrl: string) => {

export const changePassword = async (customerEmail: string, newPassword: string, resetPasswordToken: string) => {
return await useConfig(async ({ cleengId, cleengSandbox }) => {
const response = await accountService.changePassword(
const response = await cleengAccountService.changePassword(
{
publisherId: cleengId,
customerEmail,
Expand Down Expand Up @@ -450,3 +456,19 @@ function useLoginContext<T>(callback: (args: { cleengId: string; cleengSandbox:

return useConfig((config) => callback({ ...config, customerId: user.id, auth }));
}

function withAccountService<T>(
callback: (args: { accountService: typeof inplayerAccountService | typeof cleengAccountService; config: Config; accessModel: AccessModel }) => T,
): T {
const { config, accessModel } = useConfigStore.getState();

const { cleeng, inplayer } = config.integrations;

if (inplayer?.clientId) {
return callback({ accountService: inplayerAccountService, config, accessModel });
} else if (cleeng?.id) {
return callback({ accountService: cleengAccountService, config, accessModel });
}

throw new Error('No account service available');
}
2 changes: 1 addition & 1 deletion src/stores/CheckoutController.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import type { CreateOrderPayload, UpdateOrderPayload } from '#types/checkout';
import { getLocales } from '#src/services/account.service';
import { getLocales } from '#src/services/cleeng.account.service';
import * as checkoutService from '#src/services/checkout.service';
import { useConfigStore } from '#src/stores/ConfigStore';
import { useAccountStore } from '#src/stores/AccountStore';
Expand Down
11 changes: 10 additions & 1 deletion types/account.d.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import type { SerializedWatchHistoryItem } from './watchHistory';
import type { SerializedFavorite } from './favorite';

import type { Config } from '#types/Config';

export type AuthData = {
jwt: string;
customerToken: string;
Expand All @@ -22,6 +24,12 @@ export type PayloadWithIPOverride = {
customerIP?: string;
};

export type LoginArgs = {
config: Config;
email: string;
password: string;
};

export type LoginPayload = PayloadWithIPOverride & {
email: string;
password: string;
Expand Down Expand Up @@ -243,7 +251,8 @@ export type UpdateCaptureAnswersPayload = {
customerId: string;
} & Capture;

type Login = CleengRequest<LoginPayload, AuthData>;
// TODO: Convert these all to generic non-cleeng calls
type Login = (args: LoginArgs) => Promise<{ auth: AuthData; user: Customer }>;
type Register = CleengRequest<RegisterPayload, AuthData>;
type GetPublisherConsents = CleengRequest<GetPublisherConsentsPayload, GetPublisherConsentsResponse>;
type GetCustomerConsents = CleengAuthRequest<GetCustomerConsentsPayload, GetCustomerConsentsResponse>;
Expand Down
10 changes: 5 additions & 5 deletions types/cleeng.d.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
interface ApiResponse {
errors: string[];
}
type CleengResponse<R> = { responseData: R } & ApiResponse;
type CleengEmptyRequest<R> = (sandbox: boolean) => Promise<CleengResponse<R>>;
type CleengEmptyAuthRequest<R> = (sandbox: boolean, jwt: string) => Promise<CleengResponse<R>>;
type CleengRequest<P, R> = (payload: P, sandbox: boolean) => Promise<CleengResponse<R>>;
type CleengAuthRequest<P, R> = (payload: P, sandbox: boolean, jwt: string) => Promise<CleengResponse<R>>;
type ServiceResponse<R> = { responseData: R } & ApiResponse;
type CleengEmptyRequest<R> = (sandbox: boolean) => Promise<ServiceResponse<R>>;
type CleengEmptyAuthRequest<R> = (sandbox: boolean, jwt: string) => Promise<ServiceResponse<R>>;
type CleengRequest<P, R> = (payload: P, sandbox: boolean) => Promise<ServiceResponse<R>>;
type CleengAuthRequest<P, R> = (payload: P, sandbox: boolean, jwt: string) => Promise<ServiceResponse<R>>;

0 comments on commit 57757e9

Please sign in to comment.