2022-11-10 16:36:24 +00:00
|
|
|
import { useState, useEffect, useRef } from 'react';
|
2022-06-13 20:36:54 +00:00
|
|
|
import { dequal } from 'dequal';
|
|
|
|
import { Subscription } from 'rxjs';
|
|
|
|
import { createSelector } from 'reselect';
|
|
|
|
import { shallowEqual } from 'react-redux';
|
2022-11-10 16:36:24 +00:00
|
|
|
import { orderBy } from 'lodash';
|
2022-06-13 20:36:54 +00:00
|
|
|
|
|
|
|
import { TSupportedPermissions } from '../../reducers/permissions';
|
|
|
|
import { IApplicationState, TSubscriptionModel } from '../../definitions';
|
|
|
|
import { getUserSelector } from '../../selectors/login';
|
|
|
|
import { useAppSelector } from './useAppSelector';
|
|
|
|
import { getSubscriptionByRoomId } from '../database/services/Subscription';
|
|
|
|
|
|
|
|
const getPermissionsSelector = createSelector(
|
|
|
|
[(state: IApplicationState) => state.permissions, (_state: any, permissionsArray: TSupportedPermissions[]) => permissionsArray],
|
|
|
|
(permissions, permissionsArray) => permissionsArray.map(p => permissions[p])
|
|
|
|
);
|
|
|
|
|
|
|
|
const useSubscriptionRoles = (rid?: string): TSubscriptionModel['roles'] => {
|
|
|
|
const [subscriptionRoles, setSubscriptionRoles] = useState<TSubscriptionModel['roles']>([]);
|
2022-11-10 16:36:24 +00:00
|
|
|
const subscriptionRoleRef = useRef<TSubscriptionModel['roles']>([]);
|
2022-06-13 20:36:54 +00:00
|
|
|
|
|
|
|
useEffect(() => {
|
|
|
|
if (!rid) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
let subSubscription: Subscription;
|
|
|
|
getSubscriptionByRoomId(rid).then(sub => {
|
|
|
|
if (!sub) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
const observable = sub.observe();
|
|
|
|
subSubscription = observable.subscribe(s => {
|
2022-11-10 16:36:24 +00:00
|
|
|
const newRoles = orderBy(s.roles);
|
|
|
|
if (!dequal(subscriptionRoleRef.current, newRoles)) {
|
|
|
|
subscriptionRoleRef.current = newRoles;
|
|
|
|
setSubscriptionRoles(newRoles);
|
2022-06-13 20:36:54 +00:00
|
|
|
}
|
|
|
|
});
|
|
|
|
});
|
|
|
|
|
|
|
|
return () => {
|
2022-11-10 16:36:24 +00:00
|
|
|
if (subSubscription && subSubscription?.unsubscribe) {
|
|
|
|
subSubscription.unsubscribe();
|
|
|
|
}
|
2022-06-13 20:36:54 +00:00
|
|
|
};
|
2022-11-10 16:36:24 +00:00
|
|
|
}, []);
|
2022-06-13 20:36:54 +00:00
|
|
|
|
|
|
|
return subscriptionRoles;
|
|
|
|
};
|
|
|
|
|
|
|
|
export function usePermissions(permissions: TSupportedPermissions[], rid?: string): boolean[] {
|
|
|
|
const userRoles = useAppSelector(state => getUserSelector(state).roles || [], shallowEqual);
|
|
|
|
const permissionsRedux = useAppSelector(state => getPermissionsSelector(state, permissions), shallowEqual);
|
|
|
|
const subscriptionRoles = useSubscriptionRoles(rid);
|
|
|
|
|
|
|
|
const mergedRoles = [...new Set([...(subscriptionRoles || []), ...userRoles])];
|
|
|
|
return permissionsRedux.map(permission => (permission ?? []).some(r => mergedRoles.includes(r)));
|
|
|
|
}
|