Skip to content

Commit

Permalink
feat:template session store (#4526)
Browse files Browse the repository at this point in the history
* feat:template session store

Signed-off-by: jingyang <3161362058@qq.com>

* fix env

---------

Signed-off-by: jingyang <3161362058@qq.com>
  • Loading branch information
zjy365 authored Feb 19, 2024
1 parent 0180fad commit e0cc9d6
Show file tree
Hide file tree
Showing 26 changed files with 164 additions and 74 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ export default function Iframe_window({ pid }: { pid: number }) {
<iframe
className={styles.iframeContainer}
src={url}
allow="camera;microphone;clipboard-write;"
allow="camera;microphone;clipboard-write;clipboard-read;"
id={`app-window-${app?.key}`}
/>
);
Expand Down
4 changes: 1 addition & 3 deletions frontend/desktop/src/hooks/useDriver.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -73,9 +73,7 @@ export default function useDriver({ openDesktopApp }: { openDesktopApp: any }) {
const isGuidedDesktop = !!data.metadata.annotations?.[GUIDE_DESKTOP_INDEX_KEY];
!isGuidedDesktop ? setShowGuide(true) : '';
}
} catch (error) {
console.log(error);
}
} catch (error) {}
};
handleUserGuide();
// eslint-disable-next-line react-hooks/exhaustive-deps
Expand Down
4 changes: 2 additions & 2 deletions frontend/desktop/src/pages/api/price/bonus.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,8 @@ export default async function handler(req: NextApiRequest, resp: NextApiResponse
activities: result.body.data.activities
}
});
} catch (error) {
console.log(error);
} catch (error: any) {
console.log(error?.body);
jsonRes(resp, { code: 500, message: 'get price error' });
}
}
1 change: 0 additions & 1 deletion frontend/desktop/src/services/backend/db/wechatCode.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,6 @@ export async function getWeChatAccessToken() {

function isAccessTokenValid(expiresIn: number) {
const currentTime = Date.now();
console.log(expiresIn, currentTime);
return expiresIn > currentTime;
}

Expand Down
7 changes: 5 additions & 2 deletions frontend/providers/cronjob/public/locales/en/common.json
Original file line number Diff line number Diff line change
Expand Up @@ -190,5 +190,8 @@
"Basic Information": "Basic Information",
"Succeeded": "Succeeded",
"Failures": "Failures",
"Log": "Log"
}
"Log": "Log",
"Basic": "Basic",
"Username for the image registry": "Username for the image registry'",
"The password cannot be empty": "The password cannot be empty"
}
6 changes: 4 additions & 2 deletions frontend/providers/cronjob/public/locales/zh/common.json
Original file line number Diff line number Diff line change
Expand Up @@ -237,5 +237,7 @@
"Basic Information": "基础信息",
"Succeeded": "成功数",
"Failures": "失败数",
"Log": "日志"
}
"Log": "日志",
"Username for the image registry": "用户名",
"The password cannot be empty": "密码不能为空"
}
1 change: 1 addition & 0 deletions frontend/providers/cronjob/src/constants/keys.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,3 +17,4 @@ export const componentLabel = 'app.kubernetes.io/component';
// cronjob
export const cronJobTypeKey = 'cronjob-type';
export const cronJobKey = 'cloud.sealos.io/cronjob';
export const defaultDomain = 'cloud.sealos.io';
8 changes: 2 additions & 6 deletions frontend/providers/cronjob/src/pages/_app.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -46,15 +46,11 @@ function App({ Component, pageProps }: AppProps) {
content: '该应用不允许单独使用,点击确认前往 Sealos Desktop 使用。'
});

useEffect(() => {
initSystemEnv();
}, [initSystemEnv]);

useEffect(() => {
NProgress.start();
const response = createSealosApp();

(async () => {
const SystemEnv = await initSystemEnv();
try {
const res = await sealosApp.getSession();
localStorage.setItem('session', JSON.stringify(res));
Expand All @@ -72,7 +68,7 @@ function App({ Component, pageProps }: AppProps) {
NProgress.done();

return response;
}, [SystemEnv.domain, openConfirm]);
}, [openConfirm]);

// add resize event
useEffect(() => {
Expand Down
3 changes: 2 additions & 1 deletion frontend/providers/cronjob/src/pages/api/platform/getEnv.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { defaultDomain } from '@/constants/keys';
import { jsonRes } from '@/services/backend/response';
import { ApiResp } from '@/services/kubernet';
import type { NextApiRequest, NextApiResponse } from 'next';
Expand All @@ -9,7 +10,7 @@ export type EnvResponse = {
export default async function handler(req: NextApiRequest, res: NextApiResponse<ApiResp>) {
jsonRes<EnvResponse>(res, {
data: {
domain: process.env.SEALOS_DOMAIN || 'cloud.sealos.io'
domain: process.env.SEALOS_DOMAIN || defaultDomain
}
});
}
9 changes: 6 additions & 3 deletions frontend/providers/cronjob/src/store/env.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
import { getPlatformEnv } from '@/api/platform';
import { defaultDomain } from '@/constants/keys';
import { EnvResponse } from '@/pages/api/platform/getEnv';
import { create } from 'zustand';
import { immer } from 'zustand/middleware/immer';

type EnvState = {
SystemEnv: EnvResponse;
initSystemEnv: () => void;
initSystemEnv: () => Promise<EnvResponse>;
};

const useEnvStore = create<EnvState>()(
Expand All @@ -16,12 +17,14 @@ const useEnvStore = create<EnvState>()(
initSystemEnv: async () => {
try {
const data = await getPlatformEnv();

set((state) => {
state.SystemEnv = data;
});
return data;
} catch (error) {
console.log(error, 'get system env');
return {
domain: defaultDomain
};
}
}
}))
Expand Down
2 changes: 1 addition & 1 deletion frontend/providers/cronjob/src/utils/adapt.ts
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,7 @@ export const adaptAppListItem = (app: V1Deployment): AppListItemType => {
memory: memoryFormatToMi(
app.spec?.template?.spec?.containers?.[0]?.resources?.limits?.memory || '0'
),
replicas: app.spec?.replicas || 1
replicas: app.spec?.replicas || 0
};
};

Expand Down
2 changes: 1 addition & 1 deletion frontend/providers/cronjob/src/utils/user.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,5 +41,5 @@ export const getUserNamespace = () => {
export const getUserServiceAccount = () => {
const kubeConfig = getUserKubeConfig();
const json = yaml.load(kubeConfig) as KC;
return json?.contexts[0]?.context?.user || json?.users[0]?.name;
return json?.contexts[0]?.context?.namespace?.replace('ns-', '') || json?.users[0]?.name;
};
17 changes: 14 additions & 3 deletions frontend/providers/template/src/hooks/useConfirm.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { useCallback, useRef } from 'react';
import React, { ReactNode, useCallback, useRef } from 'react';
import {
AlertDialog,
AlertDialogBody,
Expand All @@ -11,7 +11,15 @@ import {
} from '@chakra-ui/react';
import { useTranslation } from 'next-i18next';

export const useConfirm = ({ title = 'Prompt', content }: { title?: string; content: string }) => {
export const useConfirm = ({
title = 'Prompt',
content,
otherContent
}: {
title?: string;
content: string;
otherContent?: ReactNode;
}) => {
const { t } = useTranslation();
const { isOpen, onOpen, onClose } = useDisclosure();
const cancelRef = useRef(null);
Expand All @@ -38,7 +46,10 @@ export const useConfirm = ({ title = 'Prompt', content }: { title?: string; cont
{t(title)}
</AlertDialogHeader>

<AlertDialogBody>{t(content)}</AlertDialogBody>
<AlertDialogBody>
{otherContent}
{t(content)}
</AlertDialogBody>

<AlertDialogFooter>
<Button
Expand Down
7 changes: 4 additions & 3 deletions frontend/providers/template/src/pages/_app.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import Layout from '@/components/layout';

import '@/styles/reset.scss';
import 'nprogress/nprogress.css';
import useSessionStore from '@/store/session';

//Binding events.
Router.events.on('routeChangeStart', () => NProgress.start());
Expand All @@ -37,6 +38,7 @@ const queryClient = new QueryClient({

const App = ({ Component, pageProps, domain }: AppProps & { domain: string }) => {
const router = useRouter();
const { setSession } = useSessionStore();
const { i18n } = useTranslation();
const { setScreenWidth, loading, setLastRoute } = useGlobalStore();
const { Loading } = useLoading();
Expand All @@ -52,10 +54,9 @@ const App = ({ Component, pageProps, domain }: AppProps & { domain: string }) =>
(async () => {
try {
const res = await sealosApp.getSession();
localStorage.setItem('session', JSON.stringify(res));
console.log('app init success');
setSession(res);
} catch (err) {
console.log(err, 'App is not running in desktop');
console.warn('App is not running in desktop');
}
})();
NProgress.done();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import yaml from 'js-yaml';
import type { NextApiRequest, NextApiResponse } from 'next';
import path from 'path';
import { replaceRawWithCDN } from './listTemplate';
import { EnvResponse } from '@/types';

export default async function handler(req: NextApiRequest, res: NextApiResponse<ApiResp>) {
try {
Expand Down Expand Up @@ -65,12 +66,13 @@ export async function GetTemplateByName({
const cdnUrl = process.env.CDN_URL;
const targetFolder = process.env.TEMPLATE_REPO_FOLDER || 'template';

const TemplateEnvs = {
const TemplateEnvs: EnvResponse = {
SEALOS_CLOUD_DOMAIN: process.env.SEALOS_CLOUD_DOMAIN || 'cloud.sealos.io',
SEALOS_CERT_SECRET_NAME: process.env.SEALOS_CERT_SECRET_NAME || 'wildcard-cert',
TEMPLATE_REPO_URL:
process.env.TEMPLATE_REPO_URL || 'https://github.com/labring-actions/templates',
SEALOS_NAMESPACE: namespace || ''
SEALOS_NAMESPACE: namespace || '',
SEALOS_SERVICE_ACCOUNT: namespace.replace('ns-', '')
};

const originalPath = process.cwd();
Expand Down
3 changes: 2 additions & 1 deletion frontend/providers/template/src/pages/api/platform/getEnv.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,8 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse<
SEALOS_CERT_SECRET_NAME: process.env.SEALOS_CERT_SECRET_NAME || 'wildcard-cert',
TEMPLATE_REPO_URL:
process.env.TEMPLATE_REPO_URL || 'https://github.com/labring-actions/templates',
SEALOS_NAMESPACE: user_namespace || ''
SEALOS_NAMESPACE: user_namespace || '',
SEALOS_SERVICE_ACCOUNT: user_namespace.replace('ns-', '')
}
});
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import { CopyLinkIcon, HomePageIcon, HtmlIcon, MdIcon, ShareIcon } from '@/components/icons';
import { useCachedStore } from '@/store/cached';
import useSessionStore from '@/store/session';
import { TemplateType } from '@/types/app';
import type { YamlItemType } from '@/types/index';
import { downLoadBold, formatStarNumber, useCopyData } from '@/utils/tools';
Expand Down Expand Up @@ -42,7 +44,8 @@ const Header = ({
cloudDomain: string;
}) => {
console.log(templateDetail, 'templateDetail');

const { insideCloud } = useCachedStore();
const { session } = useSessionStore();
const { t } = useTranslation();
const { copyData } = useCopyData();
const handleExportYaml = useCallback(async () => {
Expand Down Expand Up @@ -70,10 +73,10 @@ const Header = ({
cursor: 'pointer'
};

const copyTemplateLink = () => {
const copyTemplateLink = useCallback(() => {
const str = `https://${cloudDomain}/?openapp=system-template%3FtemplateName%3D${appName}`;
copyData(str);
};
}, [appName, cloudDomain, copyData]);

const MdPart = `[![](https://raw.githubusercontent.com/labring-actions/templates/main/Deploy-on-Sealos.svg)](https://${cloudDomain}/?openapp=system-template%3FtemplateName%3D${appName})`;

Expand Down Expand Up @@ -161,10 +164,9 @@ const Header = ({
<PopoverBody p={'20px'}>
<Flex
onClick={copyTemplateLink}
w="60px"
flexDirection={'column'}
justifyContent={'center'}
alignItems={'center'}
alignItems={'start'}
>
<Flex {...IconBox}>
<CopyLinkIcon />
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,11 +56,10 @@ export default function OtherList({ instanceName }: { instanceName: string }) {
title: 'Description',
key: 'service ports',
render: (item: ResourceListItemType) => {
const text = item?.servicePorts
? item?.servicePorts
?.map((item) => `${item?.port}:${item?.nodePort}/${item?.protocol}`)
.join(', ')
: '';
const text =
item?.servicePorts && item.serviceType === 'NodePort'
? item?.servicePorts?.map((i) => `${i.port}:${i.nodePort}/${i.protocol}`).join(', ')
: '';
return <Text>{text}</Text>;
}
}
Expand Down
13 changes: 6 additions & 7 deletions frontend/providers/template/src/services/backend/kubernetes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -79,18 +79,17 @@ export async function CreateYaml(
created.push(response.body);
}
} catch (error: any) {
console.log('create error');
console.log('create yaml error');
/* delete success specs */
for (const spec of created) {
try {
console.log('delete:', spec.kind);
client.delete(spec);
} catch (error) {
error;
await client.delete(spec);
} catch (error: any) {
console.log('delete error:', spec.kind, error.body);
}
}
// console.error(error, '<=create error')
return Promise.reject(error);
return Promise.reject(error.body || 'CreateYaml Error');
}
return created;
}
Expand Down Expand Up @@ -189,7 +188,7 @@ export async function delYaml(kc: k8s.KubeConfig, specs: k8s.KubernetesObject[])
try {
for (const spec of validSpecs) {
console.log('delete:', spec.kind);
client.delete(spec);
await client.delete(spec);
}
} catch (error: any) {
// console.error(error, '<=create error')
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ export const jsonRes = <T = any>(
} else if (error?.code && error.code in ERROR_TEXT) {
msg = ERROR_TEXT[error.code];
}
console.error('===jsonRes error===\n ', error);
console.log('===jsonRes error===\n ', error);
}

res.json({
Expand Down
Loading

0 comments on commit e0cc9d6

Please sign in to comment.