diff --git a/README.md b/README.md index f360f5c41..642a10583 100644 --- a/README.md +++ b/README.md @@ -34,9 +34,9 @@ RAIR deploys each its services in a self-contained Docker image: It's the moment of truth. From the repository root, run: - docker-compose -f {dockerfile.yml} up + docker-compose -f docker-compose.local-new.yml up -d -`{dockerfile.yml}` will be the file configured for your specific deployment. Wait for the app to build. Keep an eye on the terminal for any errors. +Wait for the app to build. Keep an eye on the terminal for any errors. ## Launch the App diff --git a/docker-compose-prod.yaml b/docker-compose-prod.yaml index ec280b3ce..73e2eedf2 100644 --- a/docker-compose-prod.yaml +++ b/docker-compose-prod.yaml @@ -67,6 +67,7 @@ services: AWS_SECRET_ACCESS_KEY: ${filebase_secret_access_key} FILEBASE_BUCKET: ${filebase_bucket} YOTI_CLIENT_ID: ${yoti_client_id} + RATE_LIMIT_MINUTE: ${rate_limit_minute} ports: - 3000:3000 - 5000:5000 diff --git a/docker-compose-web.yml b/docker-compose-web.yml index 8c886be28..b55244dfd 100644 --- a/docker-compose-web.yml +++ b/docker-compose-web.yml @@ -64,6 +64,7 @@ services: AWS_SECRET_ACCESS_KEY: ${filebase_secret_access_key} FILEBASE_BUCKET: ${filebase_bucket} YOTI_CLIENT_ID: ${yoti_client_id} + RATE_LIMIT_MINUTE: ${rate_limit_minute} ports: - 3000:3000 - 5000:5000 diff --git a/docker-compose.local-new.yml b/docker-compose.local-new.yml index 6008aabb2..c1459c5e9 100644 --- a/docker-compose.local-new.yml +++ b/docker-compose.local-new.yml @@ -53,6 +53,7 @@ services: AWS_SECRET_ACCESS_KEY: ${filebase_secret_access_key} FILEBASE_BUCKET: ${filebase_bucket} YOTI_CLIENT_ID: ${yoti_client_id} + RATE_LIMIT_MINUTE: ${rate_limit_minute} ports: - 3000:3000 - 5000:5000 diff --git a/docker-compose.local-ssl-with_certbot.yml b/docker-compose.local-ssl-with_certbot.yml index 089089e4f..1fbb09c5d 100644 --- a/docker-compose.local-ssl-with_certbot.yml +++ b/docker-compose.local-ssl-with_certbot.yml @@ -75,6 +75,7 @@ services: AWS_SECRET_ACCESS_KEY: ${filebase_secret_access_key} FILEBASE_BUCKET: ${filebase_bucket} YOTI_CLIENT_ID: ${yoti_client_id} + RATE_LIMIT_MINUTE: ${rate_limit_minute} ports: - 3000:3000 - 5000:5000 diff --git a/docker-compose.local-ssl-without_certbot.yml b/docker-compose.local-ssl-without_certbot.yml index a79bccf4c..538d4acc2 100644 --- a/docker-compose.local-ssl-without_certbot.yml +++ b/docker-compose.local-ssl-without_certbot.yml @@ -66,6 +66,7 @@ services: AWS_SECRET_ACCESS_KEY: ${filebase_secret_access_key} FILEBASE_BUCKET: ${filebase_bucket} YOTI_CLIENT_ID: ${yoti_client_id} + RATE_LIMIT_MINUTE: ${rate_limit_minute} ports: - 3000:3000 - 5000:5000 diff --git a/docker-compose.yml b/docker-compose.yml index 67d82bddb..e9b839a69 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -66,6 +66,7 @@ services: AWS_SECRET_ACCESS_KEY: ${filebase_secret_access_key} FILEBASE_BUCKET: ${filebase_bucket} YOTI_CLIENT_ID: ${yoti_client_id} + RATE_LIMIT_MINUTE: ${rate_limit_minute} ports: - 3000:3000 - 5000:5000 diff --git a/rair-front/package.json b/rair-front/package.json index 04b688685..8966c5001 100644 --- a/rair-front/package.json +++ b/rair-front/package.json @@ -24,6 +24,7 @@ "@emotion/styled": "^11.13.0", "@fortawesome/fontawesome-svg-core": "^6.6.0", "@fortawesome/free-brands-svg-icons": "^6.6.0", + "@fortawesome/free-regular-svg-icons": "^6.6.0", "@fortawesome/free-solid-svg-icons": "^6.6.0", "@fortawesome/react-fontawesome": "^0.2.2", "@getyoti/react-face-capture": "^2.3.1", diff --git a/rair-front/src/App.tsx b/rair-front/src/App.tsx index 74aff8ccb..517b581a7 100644 --- a/rair-front/src/App.tsx +++ b/rair-front/src/App.tsx @@ -70,7 +70,6 @@ import { import { detectBlockchain } from './utils/blockchainData'; // import getInformationGoogleAnalytics from './utils/googleAnalytics'; import gtag from './utils/gtag'; -import { rFetch } from './utils/rFetch'; // views import ErrorFallback from './views/ErrorFallback/ErrorFallback'; @@ -105,7 +104,6 @@ function App() { const [tabIndexItems, setTabIndexItems] = useState(0); const [tokenNumber, setTokenNumber] = useState(undefined); const navigate = useNavigate(); - const [notificationCount, setNotificationCount] = useState(0); // Redux const { @@ -171,21 +169,6 @@ function App() { } }, [dispatch, logoutUser, blockchainSettings]); - const getNotificationsCount = useCallback(async () => { - if (isLoggedIn && currentUserAddress) { - const result = await rFetch(`/api/notifications?onlyUnread=true`); - if (result.success && result.totalCount >= 0) { - setNotificationCount(result.totalCount); - } - } else { - setNotificationCount(0); - } - }, [isLoggedIn, currentUserAddress]); - - useEffect(() => { - getNotificationsCount(); - }, [getNotificationsCount]); - // gtag useEffect(() => { @@ -306,8 +289,6 @@ function App() { showAlert={showAlert} setTabIndexItems={setTabIndexItems} isAboutPage={isAboutPage} - notificationCount={notificationCount} - getNotificationsCount={getNotificationsCount} /> ) )} diff --git a/rair-front/src/components/DemoMediaUpload/MediaItemChange/MediaItemChange.tsx b/rair-front/src/components/DemoMediaUpload/MediaItemChange/MediaItemChange.tsx index c08298745..7361db549 100644 --- a/rair-front/src/components/DemoMediaUpload/MediaItemChange/MediaItemChange.tsx +++ b/rair-front/src/components/DemoMediaUpload/MediaItemChange/MediaItemChange.tsx @@ -1,3 +1,4 @@ +//@ts-nocheck import React, { useCallback, useState } from 'react'; import { faCheck, @@ -40,7 +41,8 @@ const MediaItemChange: React.FC = ({ const closeModal = useCallback(() => { setModalIsOpen(false); - }, [setModalIsOpen]); + getMediaList(); + }, [setModalIsOpen, getMediaList]); const [titleValue, setTitleValue] = useState(item.title); const [disabledBtn, setDisabledBtn] = useState(false); @@ -103,25 +105,13 @@ const MediaItemChange: React.FC = ({ className="media-item-title"> {textFlag ? (
-

- {item.title.length > 15 - ? item.title.slice(0, 6) + - '...' + - item.title.slice(item.title.length - 10, 10) - : item.title} -

+

{item.title}

) : (
{!editTitleVideo ? ( <> -

- {item.title.length > 15 - ? item.title.slice(0, 6) + - '...' + - item.title.slice(item.title.length - 10, 10) - : item.title} -

+

{item.title}

{newUserStatus ? ( diff --git a/rair-front/src/components/DemoMediaUpload/PopUpChangeVideo/PopUpChangeVideo.tsx b/rair-front/src/components/DemoMediaUpload/PopUpChangeVideo/PopUpChangeVideo.tsx index 28567595d..8bb1b36c7 100644 --- a/rair-front/src/components/DemoMediaUpload/PopUpChangeVideo/PopUpChangeVideo.tsx +++ b/rair-front/src/components/DemoMediaUpload/PopUpChangeVideo/PopUpChangeVideo.tsx @@ -1,3 +1,4 @@ +//@ts-nocheck import React, { useCallback, useEffect, useState } from 'react'; import Modal from 'react-modal'; @@ -22,9 +23,8 @@ const PopUpChangeVideo: React.FC = ({ mediaList, index }) => { - const { primaryColor, textColor, primaryButtonColor } = useAppSelector( - (store) => store.colors - ); + const { primaryColor, textColor, primaryButtonColor, isDarkMode } = + useAppSelector((store) => store.colors); const { categories } = useAppSelector((store) => store.settings); const rSwal = useSwal(); @@ -33,7 +33,7 @@ const PopUpChangeVideo: React.FC = ({ const [categoryList, setCategoryList] = useState( undefined ); - const [itemCategory, setItemCategory] = useState(item.category); + const [itemCategory, setItemCategory] = useState(item.category._id); const getCategory = useCallback(async () => { if (categories) { @@ -42,7 +42,7 @@ const PopUpChangeVideo: React.FC = ({ return { id: item._id, label: item.name, - value: item.name, + value: item._id, disabled: false }; }) @@ -69,16 +69,12 @@ const PopUpChangeVideo: React.FC = ({ setMediaList(newMediaList); closeModal(); } else { - const choiceCategory: any = - categoryList && - categoryList.find((item: any) => item.value === itemCategory); - setUploadSuccess(true); const updatedVideo = { description: desc, title: title, - category: choiceCategory.id + category: itemCategory }; try { const request = await rFetch(`/api/files/update/${item._id}`, { @@ -99,14 +95,14 @@ const PopUpChangeVideo: React.FC = ({ closeModal(); setDesc(item.description); setTitle(item.title); - setItemCategory(item.category); + setItemCategory(item.category._id); setUploadSuccess(null); } } catch (e) { closeModal(); setDesc(item.description); setTitle(item.title); - setItemCategory(item.category); + setItemCategory(item.category._id); setUploadSuccess(null); } } @@ -122,7 +118,7 @@ const PopUpChangeVideo: React.FC = ({ color: textColor }, labelCSS: { - color: `${primaryColor === 'rhyno' ? 'rgb(41, 41, 41)' : '#fff'}`, + color: textColor, marginTop: 5, marginBottom: 5 } @@ -133,7 +129,9 @@ const PopUpChangeVideo: React.FC = ({ zIndex: '1' }, content: { - background: primaryColor === 'rhyno' ? '#F2F2F2' : '#383637', + background: isDarkMode + ? `color-mix(in srgb, ${primaryColor}, #2D2D2D)` + : 'var(--rhyno)', top: '50%', left: '50%', right: 'auto', @@ -171,7 +169,7 @@ const PopUpChangeVideo: React.FC = ({ if (defaultCategory) { setItemCategory(defaultCategory.value); } else { - setItemCategory(item.category); + setItemCategory(item.category._id); } } } @@ -191,7 +189,7 @@ const PopUpChangeVideo: React.FC = ({ label="Title" customClass="form-control input-select-custom-style" placeholder="Select a description" - // {...selectCommonInfoNFT} + {...selectCommonInfoNFT} /> = ({ label="Description" customClass="form-control input-select-custom-style" placeholder="Select a description" - // {...selectCommonInfoNFT} + {...selectCommonInfoNFT} /> = ({ {...selectCommonInfoNFT} />
diff --git a/rair-front/src/components/MockUpPage/NftList/NftData/NftCollectionPage.tsx b/rair-front/src/components/MockUpPage/NftList/NftData/NftCollectionPage.tsx index 3f5275fd4..6a48014c6 100644 --- a/rair-front/src/components/MockUpPage/NftList/NftData/NftCollectionPage.tsx +++ b/rair-front/src/components/MockUpPage/NftList/NftData/NftCollectionPage.tsx @@ -70,7 +70,8 @@ const NftCollectionPageComponent: FC = ({ currentCollection, currentCollectionTotal, currentCollectionStatus, - currentCollectionMetadata + currentCollectionMetadata, + currentCollectionNextPageStatus } = useAppSelector((store) => store.tokens); const { width } = useWindowDimensions(); @@ -272,9 +273,9 @@ const NftCollectionPageComponent: FC = ({ useEffect(() => { if ( + !metadataFilter && currentCollectionStatus !== dataStatuses.Loading && - currentCollectionMetadata?.product?.firstTokenIndex && - !currentCollection[currentCollectionMetadata?.product?.firstTokenIndex] + Object.keys(currentCollection).length === 1 ) { getResetTokens(); } @@ -282,7 +283,9 @@ const NftCollectionPageComponent: FC = ({ currentCollectionMetadata, currentCollection, getResetTokens, - currentCollectionStatus + currentCollectionStatus, + metadataFilter, + selectedAttributeValues ]); useEffect(() => { @@ -338,11 +341,11 @@ const NftCollectionPageComponent: FC = ({ // eslint-disable-next-line react-hooks/exhaustive-deps }, []); - useEffect(() => { - if (!metadataFilter) { - setSelectedAttributeValues(undefined); - } - }, [metadataFilter, setSelectedAttributeValues]); + // useEffect(() => { + // if (!metadataFilter) { + // setSelectedAttributeValues(undefined); + // } + // }, [metadataFilter, setSelectedAttributeValues]); const selectedAttributeValuesFunction = (selectedAttributeValues) => { if (selectedAttributeValues) { @@ -378,7 +381,7 @@ const NftCollectionPageComponent: FC = ({ return ; } - if (currentCollectionTotal === 0) { + if (currentCollectionTotal === 0 && !metadataFilter) { return (
{!!embeddedParams || ( @@ -488,59 +491,37 @@ const NftCollectionPageComponent: FC = ({ aria-hidden="true" /> - {isMobileDesign ? ( - - ) : ( - - )} +
{tokenDataFiltered.length > 0 ? (
@@ -565,94 +546,82 @@ const NftCollectionPageComponent: FC = ({ className={`list-button-wrapper-grid-template ${ metadataFilter && 'with-modal' }`}> - {tokenDataFiltered.length > 0 - ? tokenDataFiltered.map((token, index) => { - if ( - token.metadata.image && - token.metadata.image !== 'undefined' - ) { - return ( - - ); - } else { - return null; - } - }) - : filteredData && filteredData.length > 0 - ? filteredData.map((item, index) => { - if ( - item.metadata.image && - item.metadata.image !== 'undefined' - ) { - return ( - - ); - } else { - return null; - } - }) - : Array.from(new Array(10)).map((item, index) => { - return ( - - ); - })} + {tokenDataFiltered.length > 0 ? ( + tokenDataFiltered.map((token, index) => { + if ( + token.metadata.image && + token.metadata.image !== 'undefined' + ) { + return ( + + ); + } else { + return null; + } + }) + ) : filteredData && filteredData.length > 0 ? ( + filteredData.map((item, index) => { + if (item.metadata.image && item.metadata.image !== 'undefined') { + return ( + + ); + } else { + return null; + } + }) + ) : ( +

No tokens found

+ )}
{metadataFilter && (
@@ -780,7 +749,7 @@ const NftCollectionPageComponent: FC = ({
)} - {isLoading && ( + {currentCollectionNextPageStatus && (
{ + const { width } = useWindowDimensions(); + const isMobileDesign = width < 820; + return (
{filteredDataAttributes && filteredDataAttributes.length > 0 && @@ -36,6 +44,20 @@ const ClearMetadataBox = ({ return newItem; }); setSelectedAttributeValues(result); + + getAllProduct( + '0', + showTokenRef.current.toString(), + selectedAttributeValues && + selectedAttributeValues.length && + selectedAttributeValues?.reduce((acc, item) => { + const { name, values } = item; + const newValue = values.filter((el) => el.active); + + acc[name] = newValue.map((el) => el.value); + return acc; + }, {}) + ); }; if (val.active) { diff --git a/rair-front/src/components/MockUpPage/NftList/NftData/TitleCollection/FilterMetadataTokens/MetadataAttrPropertyItems/MetadataAttributesPropertyItem.tsx b/rair-front/src/components/MockUpPage/NftList/NftData/TitleCollection/FilterMetadataTokens/MetadataAttrPropertyItems/MetadataAttributesPropertyItem.tsx index a51e2b9c0..9695906dd 100644 --- a/rair-front/src/components/MockUpPage/NftList/NftData/TitleCollection/FilterMetadataTokens/MetadataAttrPropertyItems/MetadataAttributesPropertyItem.tsx +++ b/rair-front/src/components/MockUpPage/NftList/NftData/TitleCollection/FilterMetadataTokens/MetadataAttrPropertyItems/MetadataAttributesPropertyItem.tsx @@ -46,7 +46,7 @@ const MetadataAttributesPropertyItem = ({ {item.value.length > 7 && !isMobileDesign ? ( <> - {`${item.value.slice(0, 4)}... (${quantity})`} + <>{`${item.value.slice(0, 4)}... (${quantity})`} ) : ( diff --git a/rair-front/src/components/MockUpPage/NftList/NftData/TitleCollection/FilterMetadataTokens/MetadataItem.tsx b/rair-front/src/components/MockUpPage/NftList/NftData/TitleCollection/FilterMetadataTokens/MetadataItem.tsx index 1d3314597..ae32b0bfd 100644 --- a/rair-front/src/components/MockUpPage/NftList/NftData/TitleCollection/FilterMetadataTokens/MetadataItem.tsx +++ b/rair-front/src/components/MockUpPage/NftList/NftData/TitleCollection/FilterMetadataTokens/MetadataItem.tsx @@ -68,7 +68,7 @@ const MetadataItem = ({ {item.name.length > 8 && !isMobileDesign ? ( <> - {`${item.name.slice(0, 6)}...`} + <>{`${item.name.slice(0, 6)}...`} ) : ( diff --git a/rair-front/src/components/MockUpPage/NftList/NftList.tsx b/rair-front/src/components/MockUpPage/NftList/NftList.tsx index a9617881c..8ff356723 100644 --- a/rair-front/src/components/MockUpPage/NftList/NftList.tsx +++ b/rair-front/src/components/MockUpPage/NftList/NftList.tsx @@ -28,12 +28,28 @@ const NftListComponent: FC = ({ titleSearch, sortItem }) => { return ; } - const filteredData = catalog.filter((item) => { - return ( - item.product.cover !== 'none' && - item.product.name.toLowerCase().includes(titleSearch.toLowerCase()) - ); - }); + const filteredData = catalog + .filter((item) => { + return ( + item.product.cover !== 'none' && + item.product.name.toLowerCase().includes(titleSearch.toLowerCase()) + ); + }) + .sort((a, b) => { + if (sortItem === 'up') { + if (a.product.name < b.product.name) { + return 1; + } + } + + if (sortItem === 'down') { + if (a.product.name > b.product.name) { + return -1; + } + } + + return 0; + }); if (catalogStatus !== dataStatuses.Complete) { return ; diff --git a/rair-front/src/components/MockUpPage/PaginationBox/PaginationBox.tsx b/rair-front/src/components/MockUpPage/PaginationBox/PaginationBox.tsx index 44b992283..c383d868f 100644 --- a/rair-front/src/components/MockUpPage/PaginationBox/PaginationBox.tsx +++ b/rair-front/src/components/MockUpPage/PaginationBox/PaginationBox.tsx @@ -7,20 +7,34 @@ import { IPaginationBox } from '../mockupPage.types'; const PaginationBox: React.FC = ({ changePage, + currentPage, totalPageForPagination, whatPage, itemsPerPageNotifications }) => { - const { itemsPerPage, currentPage } = useAppSelector((store) => store.tokens); - + const { itemsPerPage } = useAppSelector((store) => store.tokens); const { isDarkMode, primaryButtonColor } = useAppSelector( (store) => store.colors ); const [page, setPage] = useState(currentPage); - const [pagesArray, setPagesArray] = useState>([]); + const [totalPage, setTotalPages] = useState(); + const [totalPageVideo, setTotalPagesVideo] = useState(); - // const hotdropsVar = import.meta.env.VITE_TESTNET; + const pagesArray: number[] = []; + if (whatPage && whatPage === 'nft' && totalPage) { + for (let i = 0; i < totalPage; i++) { + pagesArray.push(i + 1); + } + } else if (whatPage && whatPage === 'video' && totalPageVideo) { + for (let i = 0; i < totalPageVideo; i++) { + pagesArray.push(i + 1); + } + } else if (whatPage && whatPage === 'notifications' && totalPage) { + for (let i = 0; i < totalPage; i++) { + pagesArray.push(i + 1); + } + } const getPagesCount = (totalCount: number, itemsPerPage: number) => { return Math.ceil(totalCount / itemsPerPage); @@ -34,30 +48,21 @@ const PaginationBox: React.FC = ({ }; useEffect(() => { - if (!totalPageForPagination) { - return; - } - let totalPages = 0; - switch (whatPage) { - case 'nft': - totalPages = getPagesCount(totalPageForPagination, itemsPerPage); - break; - case 'video': - totalPages = getPagesCount(totalPageForPagination, itemsPerPage); - break; - case 'notifications': - totalPages = getPagesCount( - totalPageForPagination, - itemsPerPageNotifications || 0 - ); - break; - } - const pageArray: Array = []; - for (let i = 0; i < totalPages; i++) { - pageArray.push(i + 1); + if (totalPageForPagination && whatPage === 'nft') { + setTotalPages(getPagesCount(totalPageForPagination, itemsPerPage)); + } else if (totalPageForPagination && whatPage === 'video') { + setTotalPagesVideo(getPagesCount(totalPageForPagination, itemsPerPage)); + } else if ( + totalPageForPagination && + whatPage === 'notifications' && + itemsPerPageNotifications + ) { + setTotalPages( + getPagesCount(totalPageForPagination, itemsPerPageNotifications) + ); } - setPagesArray(pageArray); }, [ + setTotalPages, totalPageForPagination, itemsPerPage, whatPage, @@ -79,8 +84,9 @@ const PaginationBox: React.FC = ({ primaryButtonColor={primaryButtonColor} count={pagesArray.length} page={page} - showFirstButton={false} onChange={handlePage} + // hideNextButton={true} + // hidePrevButton={true} shape="rounded" /> )} diff --git a/rair-front/src/components/MockUpPage/PaginationBox/PaginationBoxStyled.tsx b/rair-front/src/components/MockUpPage/PaginationBox/PaginationBoxStyled.tsx index b36e15a1a..042c55b34 100644 --- a/rair-front/src/components/MockUpPage/PaginationBox/PaginationBoxStyled.tsx +++ b/rair-front/src/components/MockUpPage/PaginationBox/PaginationBoxStyled.tsx @@ -6,9 +6,7 @@ interface IPaginationBoxStyled { isDarkMode?: boolean; } -export const PaginationBoxStyled = styled(Pagination).withConfig({ - shouldForwardProp: () => true -})` +export const PaginationBoxStyled = styled(Pagination)` ul { li { button { @@ -20,12 +18,7 @@ export const PaginationBoxStyled = styled(Pagination).withConfig({ ${({ isDarkMode }) => (!isDarkMode ? '#2d2d2d' : '#fff')}; &.Mui-selected { - background: ${({ primaryButtonColor }) => - `${ - import.meta.env.VITE_TESTNET - ? 'var(--hot-drops)' - : primaryButtonColor - }`}; + background: ${({ primaryButtonColor }) => `${primaryButtonColor}`}; color: #fff; border: none; -webkit-box-shadow: 0px 0px 7px 0.4px #b278a7; @@ -33,12 +26,7 @@ export const PaginationBoxStyled = styled(Pagination).withConfig({ box-shadow: 0px 0px 7px 0.4px #b278a7; } &:hover { - background: ${({ primaryButtonColor }) => - `${ - import.meta.env.VITE_TESTNET === 'true' - ? 'var(--hot-drops)' - : primaryButtonColor - }`}; + background: ${({ primaryButtonColor }) => `${primaryButtonColor}`}; color: #fff; } } diff --git a/rair-front/src/components/MockUpPage/SearchPanel.tsx b/rair-front/src/components/MockUpPage/SearchPanel.tsx index 8bdfe5b74..12c228cd7 100644 --- a/rair-front/src/components/MockUpPage/SearchPanel.tsx +++ b/rair-front/src/components/MockUpPage/SearchPanel.tsx @@ -361,6 +361,7 @@ const SearchPanel: FC = ({ tabIndex, setTabIndex }) => { })}
diff --git a/rair-front/src/components/MockUpPage/SelectBox/SelectNumber/SelectNumber.tsx b/rair-front/src/components/MockUpPage/SelectBox/SelectNumber/SelectNumber.tsx index 4b9d03338..550563546 100644 --- a/rair-front/src/components/MockUpPage/SelectBox/SelectNumber/SelectNumber.tsx +++ b/rair-front/src/components/MockUpPage/SelectBox/SelectNumber/SelectNumber.tsx @@ -135,10 +135,12 @@ const SelectNumber: React.FC = ({
{ranges.map((range, index) => { return ( diff --git a/rair-front/src/components/Navigation/Menu.tsx b/rair-front/src/components/Navigation/Menu.tsx index d3dee6cb4..75a0f9e15 100644 --- a/rair-front/src/components/Navigation/Menu.tsx +++ b/rair-front/src/components/Navigation/Menu.tsx @@ -8,7 +8,7 @@ import { formatEther, isAddress, ZeroAddress } from 'ethers'; import { TUserResponse } from '../../axios.responseTypes'; import useConnectUser from '../../hooks/useConnectUser'; import useContracts from '../../hooks/useContracts'; -import { useAppSelector } from '../../hooks/useReduxHooks'; +import { useAppDispatch, useAppSelector } from '../../hooks/useReduxHooks'; import useServerSettings from '../../hooks/useServerSettings'; import { BellIcon, @@ -39,6 +39,7 @@ import { } from './NavigationItems/NavigationItems'; import './Menu.css'; +import { fetchNotifications } from '../../redux/notificationsSlice'; interface IMenuNavigation { renderBtnConnect: boolean; @@ -48,8 +49,6 @@ interface IMenuNavigation { isSplashPage: boolean; isAboutPage: boolean; realChainId: string | undefined; - notificationCount?: number; - getNotificationsCount?: any; } const MenuNavigation: React.FC = ({ @@ -57,9 +56,7 @@ const MenuNavigation: React.FC = ({ setTabIndexItems, isSplashPage, isAboutPage, - realChainId, - notificationCount, - getNotificationsCount + realChainId }) => { const [click, setClick] = useState(false); const [userData, setUserData] = useState(null); @@ -70,22 +67,24 @@ const MenuNavigation: React.FC = ({ const [userBalance, setUserBalance] = useState(''); const [activeSearch, setActiveSearch] = useState(false); const [isLoadingBalance, setIsLoadingBalance] = useState(false); + const dispatch = useAppDispatch(); const [messageAlert, setMessageAlert] = useState(null); const { isLoggedIn, loginStatus, ageVerified } = useAppSelector( (store) => store.user ); - const [realDataNotification, setRealDataNotification] = useState([]); const { mainTokenInstance } = useContracts(); const { currentUserAddress, connectedChain } = useAppSelector( (state) => state.web3 ); + const { totalUnreadCount } = useAppSelector((store) => store.notifications); const { primaryButtonColor, textColor, iconColor, secondaryColor, - primaryColor + primaryColor, + isDarkMode } = useAppSelector((store) => store.colors); const hotdropsVar = import.meta.env.VITE_TESTNET; @@ -98,25 +97,6 @@ const MenuNavigation: React.FC = ({ setActiveSearch((prev) => !prev); }; - const getNotifications = useCallback(async () => { - if (currentUserAddress && isLoggedIn) { - const result = await rFetch(`/api/notifications`); - if (result.success) { - setRealDataNotification(result.notifications); - } - } else { - setRealDataNotification([]); - } - }, [currentUserAddress, isLoggedIn]); - - useEffect(() => { - getNotificationsCount(); - }, [click]); - - useEffect(() => { - getNotifications(); - }, []); - const toggleMenu = (otherPage?: string | undefined) => { if (otherPage === 'nav') { setClick(true); @@ -201,6 +181,12 @@ const MenuNavigation: React.FC = ({ getBalance(); }, [getBalance]); + useEffect(() => { + if (currentUserAddress && isLoggedIn) { + dispatch(fetchNotifications()); + } + }, [currentUserAddress, isLoggedIn]); + return ( = ({ height="40px" marginLeft={'17px'}> - {notificationCount && notificationCount > 0 ? ( + {totalUnreadCount > 0 ? (
= ({ fontWeight: 'bold', color: '#fff' }}> - {notificationCount > 9 ? '9+' : notificationCount} + {totalUnreadCount > 9 ? '9+' : totalUnreadCount}
) : ( '' @@ -366,10 +352,9 @@ const MenuNavigation: React.FC = ({ }} className="mobileAikonWidget" style={{ - backgroundColor: - primaryColor === 'rhyno' - ? 'var(--rhyno-20)' - : 'var(--charcoal-80)' + backgroundColor: !isDarkMode + ? 'var(--rhyno-20)' + : 'var(--charcoal-80)' }}>
= ({ const { nickName, isLoggedIn, avatar } = useAppSelector( (state) => state.user ); - const [notificationCount, setNotificationCount] = useState(0); - const getNotificationsCount = useCallback(async () => { - if (currentUserAddress && isLoggedIn) { - const result = await rFetch(`/api/notifications?onlyUnread=true`); - if (result.success && result.totalCount >= 0) { - setNotificationCount(result.totalCount); - } - } else { - setNotificationCount(0); - } - }, [currentUserAddress, isLoggedIn]); - - useEffect(() => { - getNotificationsCount(); - }, [getNotificationsCount]); + const {totalUnreadCount} = useAppSelector(store => store.notifications); return (
@@ -88,7 +74,7 @@ const MobileChoiseNav: React.FC = ({ height="40px" marginLeft={'17px'}> - {notificationCount > 0 && ( + {totalUnreadCount > 0 && (
= ({ color: '#fff' }} className="red-circle-notifications"> - {notificationCount > 9 ? '9+' : notificationCount} + {totalUnreadCount > 9 ? '9+' : totalUnreadCount}
)} diff --git a/rair-front/src/components/Navigation/MenuComponents/MobileListMenu.tsx b/rair-front/src/components/Navigation/MenuComponents/MobileListMenu.tsx index 2a9ccd8da..e14a116cf 100644 --- a/rair-front/src/components/Navigation/MenuComponents/MobileListMenu.tsx +++ b/rair-front/src/components/Navigation/MenuComponents/MobileListMenu.tsx @@ -39,7 +39,7 @@ const MobileListMenu: React.FC = ({ const { searchResults } = useAppSelector((store) => store.searchbar); const hotdropsVar = import.meta.env.VITE_TESTNET; - const { iconColor, primaryColor, secondaryColor } = useAppSelector( + const { iconColor, primaryColor, secondaryColor, isDarkMode } = useAppSelector( (store) => store.colors ); @@ -142,7 +142,9 @@ const MobileListMenu: React.FC = ({ secondaryColor={secondaryColor} hotdrops={hotdropsVar} primaryColor={primaryColor} - click={click}> + click={click} + isDarkMode={isDarkMode} + >
{activeSearch && ( <> diff --git a/rair-front/src/components/Navigation/MenuComponents/MobileNavigationList.tsx b/rair-front/src/components/Navigation/MenuComponents/MobileNavigationList.tsx index 8c7fd3977..f06524293 100644 --- a/rair-front/src/components/Navigation/MenuComponents/MobileNavigationList.tsx +++ b/rair-front/src/components/Navigation/MenuComponents/MobileNavigationList.tsx @@ -6,7 +6,7 @@ import { formatEther } from 'ethers'; import useConnectUser from '../../../hooks/useConnectUser'; import useContracts from '../../../hooks/useContracts'; -import { useAppSelector } from '../../../hooks/useReduxHooks'; +import { useAppDispatch, useAppSelector } from '../../../hooks/useReduxHooks'; import useServerSettings from '../../../hooks/useServerSettings'; import useSwal from '../../../hooks/useSwal'; import useWeb3Tx from '../../../hooks/useWeb3Tx'; @@ -18,6 +18,7 @@ import { NavFooter, NavFooterBox } from '../../Footer/FooterItems/FooterItems'; import PaginationBox from '../../MockUpPage/PaginationBox/PaginationBox'; import NotificationBox from '../../UserProfileSettings/PopUpNotification/NotificationBox/NotificationBox'; import { BackBtnMobileNav } from '../NavigationItems/NavigationItems'; +import { fetchNotifications } from '../../../redux/notificationsSlice'; interface IMobileNavigationList { messageAlert: string | null; @@ -34,6 +35,7 @@ const MobileNavigationList: React.FC = ({ toggleMenu, click }) => { + const dispatch = useAppDispatch(); const [userBalance, setUserBalance] = useState(''); const [userRairBalance, setUserRairBalance] = useState(BigInt(0)); const { primaryColor, primaryButtonColor, textColor, isDarkMode } = @@ -87,58 +89,20 @@ const MobileNavigationList: React.FC = ({ ]); const [copyEth, setCopyEth] = useState(false); - const [notificationArray, setNotificationArray] = useState(); - const [notificationCount, setNotificationCount] = useState(0); const [flagLoading, setFlagLoading] = useState(false); + const { notifications, totalCount } = useAppSelector( + (store) => store.notifications + ); const [currentPageNotification, setCurrentPageNotification] = useState(1); const reactSwal = useSwal(); const { logoutUser } = useConnectUser(); - const getNotifications = useCallback( - async (pageNum?: number) => { - if (isLoggedIn && messageAlert && currentUserAddress) { - setFlagLoading(true); - const result = await rFetch( - `/api/notifications${pageNum ? `?pageNum=${Number(pageNum)}` : ''}` - ); - if (result.success) { - const sortedNotifications = result.notifications.sort((a, b) => { - if (!a.read && b.read) return -1; - if (a.read && !b.read) return 1; - - const dateA = new Date(a.createdAt).getTime(); - const dateB = new Date(b.createdAt).getTime(); - - return dateB - dateA; - }); - setNotificationArray(sortedNotifications); - } - } else { - setNotificationArray([]); - } - }, - [messageAlert, currentUserAddress, isLoggedIn] - ); - - const getNotificationsCount = useCallback(async () => { - if (isLoggedIn && currentUserAddress) { - setFlagLoading(true); - const result = await rFetch(`/api/notifications`); - if (result.success && result.totalCount >= 0) { - setNotificationCount(result.totalCount); - } - setFlagLoading(false); - } else { - setNotificationCount(0); - } - }, [currentUserAddress, isLoggedIn]); - const changePageForVideo = (currentPage: number) => { setCurrentPageNotification(currentPage); const currentPageNumber = currentPage === 0 ? currentPage : currentPage - 1; - getNotifications(Number(currentPageNumber)); + dispatch(fetchNotifications(Number(currentPageNumber))); }; const deleteAllNotificaiton = useCallback(async () => { @@ -150,8 +114,7 @@ const MobileNavigationList: React.FC = ({ }); if (result.success) { - getNotifications(); - getNotificationsCount(); + dispatch(fetchNotifications()); reactSwal.fire({ title: 'Success', icon: 'success' @@ -160,15 +123,13 @@ const MobileNavigationList: React.FC = ({ } setFlagLoading(false); } - }, [currentUserAddress, getNotifications, getNotificationsCount, reactSwal]); - - useEffect(() => { - getNotificationsCount(); - }, [getNotificationsCount]); + }, [currentUserAddress, dispatch, reactSwal]); useEffect(() => { - getNotifications(0); - }, [getNotifications]); + if (currentUserAddress && isLoggedIn) { + dispatch(fetchNotifications(0)); + } + }, [currentUserAddress, isLoggedIn]); useEffect(() => { getBalance(); @@ -205,19 +166,22 @@ const MobileNavigationList: React.FC = ({
{flagLoading ? ( - ) : notificationArray && notificationArray.length > 0 ? ( - notificationArray.map((el) => { + ) : notifications && notifications.length > 0 ? ( + notifications.map((el) => { return ( - + ); }) ) : ( @@ -246,9 +204,9 @@ const MobileNavigationList: React.FC = ({
)}
- {notificationCount > 0 && ( + {totalCount > 0 && ( = ({
- {currentUserAddress && ( + {currentUserAddress && isLoggedIn && (
  • Logout @@ -401,8 +359,13 @@ const MobileNavigationList: React.FC = ({ ) : ( - {currentUserAddress && ( -
  • + {currentUserAddress && isLoggedIn && ( +
  • Logout
  • diff --git a/rair-front/src/components/Navigation/NavigationItems/NavigationItems.tsx b/rair-front/src/components/Navigation/NavigationItems/NavigationItems.tsx index 794ab3b33..b4b4ba192 100644 --- a/rair-front/src/components/Navigation/NavigationItems/NavigationItems.tsx +++ b/rair-front/src/components/Navigation/NavigationItems/NavigationItems.tsx @@ -87,8 +87,9 @@ export const TitleEditProfile = styled.h4` export const List = styled.ul.withConfig({ shouldForwardProp: (prop) => emotionIsPropValid(prop) })` - background: ${({ secondaryColor }) => - `color-mix(in srgb, ${secondaryColor}, #888888)`}; +background: ${({ isDarkMode, secondaryColor }) => +!isDarkMode ? '#fff' : `color-mix(in srgb, ${secondaryColor}, #888888)`}; + overflow: ${(props) => props.click && 'hidden'}; border-bottom-right-radius: 16px; border-bottom-left-radius: 16px; diff --git a/rair-front/src/components/UserProfileSettings/PopUpNotification/NotificationBox/NotificationBox.tsx b/rair-front/src/components/UserProfileSettings/PopUpNotification/NotificationBox/NotificationBox.tsx index 0c8e9fd34..d2aeaf542 100644 --- a/rair-front/src/components/UserProfileSettings/PopUpNotification/NotificationBox/NotificationBox.tsx +++ b/rair-front/src/components/UserProfileSettings/PopUpNotification/NotificationBox/NotificationBox.tsx @@ -1,9 +1,11 @@ import { useCallback } from 'react'; import { Provider, useStore } from 'react-redux'; -import { useAppSelector } from '../../../../hooks/useReduxHooks'; +import { useAppDispatch, useAppSelector } from '../../../../hooks/useReduxHooks'; import useSwal from '../../../../hooks/useSwal'; +import useWindowDimensions from '../../../../hooks/useWindowDimensions'; import { CloseIconMobile } from '../../../../images'; +import { fetchNotifications } from '../../../../redux/notificationsSlice'; import { SocialMenuMobile } from '../../../../styled-components/SocialLinkIcons/SocialLinkIcons'; import { rFetch } from '../../../../utils/rFetch'; import NotificationPage from '../../NotificationPage/NotificationPage'; @@ -13,14 +15,16 @@ import './NotificationBox.css'; const NotificationBox = ({ title, el, - getNotifications, - getNotificationsCount }) => { - const { headerLogoMobile, primaryColor } = useAppSelector( + const { headerLogoMobile, primaryColor, isDarkMode } = useAppSelector( (store) => store.colors ); const { currentUserAddress } = useAppSelector((store) => store.web3); + const { width } = useWindowDimensions(); + + const dispatch = useAppDispatch(); + const reactSwal = useSwal(); const store = useStore(); @@ -37,30 +41,30 @@ const NotificationBox = ({ }); if (result.success) { - getNotifications(); - getNotificationsCount(); + dispatch(fetchNotifications(0)); } } - }, [currentUserAddress, el._id, getNotifications, getNotificationsCount]); + }, [currentUserAddress, el._id]); const readNotification = useCallback(async () => { if (currentUserAddress) { - const result = await rFetch(`/api/notifications`, { - method: 'PUT', - body: JSON.stringify({ - ids: [el._id] - }), - headers: { - 'Content-Type': 'application/json' - } - }); + if(!el.read) { + const result = await rFetch(`/api/notifications`, { + method: 'PUT', + body: JSON.stringify({ + ids: [el._id] + }), + headers: { + 'Content-Type': 'application/json' + } + }); - if (result.success) { - getNotifications(); - getNotificationsCount(); + if (result.success) { + dispatch(fetchNotifications(0)); + } } } - }, [currentUserAddress, el._id, getNotifications, getNotificationsCount]); + }, [currentUserAddress, el._id]); const showMoreDetails = () => { reactSwal.fire({ @@ -75,15 +79,14 @@ const NotificationBox = ({ }, showConfirmButton: false, showCloseButton: true - // cancelButtonText: - // '', - // cancelButtonAriaLabel: 'Thumbs down' }); }; return (
    -
    +
    {!el.read &&
    }
    @@ -93,7 +96,6 @@ const NotificationBox = ({
    { - // readNotification(); showMoreDetails(); readNotification(); }} diff --git a/rair-front/src/components/UserProfileSettings/PopUpNotification/PopUpNotification.tsx b/rair-front/src/components/UserProfileSettings/PopUpNotification/PopUpNotification.tsx index cf5e4ab81..d30a3cee5 100644 --- a/rair-front/src/components/UserProfileSettings/PopUpNotification/PopUpNotification.tsx +++ b/rair-front/src/components/UserProfileSettings/PopUpNotification/PopUpNotification.tsx @@ -1,102 +1,87 @@ import { useCallback, useEffect, useState } from 'react'; import { Popup } from 'reactjs-popup'; -import { useAppSelector } from '../../../hooks/useReduxHooks'; +import { useAppDispatch, useAppSelector } from '../../../hooks/useReduxHooks'; import useSwal from '../../../hooks/useSwal'; import { BellIcon } from '../../../images'; +import { fetchNotifications } from '../../../redux/notificationsSlice'; import { SocialBox } from '../../../styled-components/SocialLinkIcons/SocialLinkIcons'; import { rFetch } from '../../../utils/rFetch'; import PaginationBox from '../../MockUpPage/PaginationBox/PaginationBox'; import NotificationBox from './NotificationBox/NotificationBox'; -const PopUpNotification = ({ - getNotifications, - realDataNotification, - notificationCount, - getNotificationsCount -}) => - // props was - isNotification - { - const [openModal, setOpenModal] = useState(false); - const reactSwal = useSwal(); - const { currentUserAddress } = useAppSelector((state) => state.web3); - const [totalPageForPagination, setTotalPageForPagination] = useState(0); - const [currentPageForNotification, setCurrentPageNotification] = - useState(1); - const { primaryColor, primaryButtonColor, textColor } = useAppSelector( - (store) => store.colors - ); - const { email, isLoggedIn } = useAppSelector((store) => store.user); +const PopUpNotification = ({ realDataNotification, notificationCount }) => { + const [openModal, setOpenModal] = useState(false); + const dispatch = useAppDispatch(); + const reactSwal = useSwal(); + const { currentUserAddress } = useAppSelector((state) => state.web3); + const { isLoggedIn } = useAppSelector((store) => store.user); + const { totalUnreadCount, totalCount } = useAppSelector( + (store) => store.notifications + ); + const [totalPageForPagination, setTotalPageForPagination] = useState(0); + const [currentPageForNotification, setCurrentPageNotification] = + useState(1); + const { primaryColor, primaryButtonColor, textColor } = useAppSelector( + (store) => store.colors + ); + const { email } = useAppSelector((store) => store.user); - const changePageForVideo = (currentPage: number) => { - setCurrentPageNotification(currentPage); - const currentPageNumber = - currentPage === 0 ? currentPage : currentPage - 1; - getNotifications(Number(currentPageNumber)); - }; + const changePageForNotification = (currentPage: number) => { + setCurrentPageNotification(currentPage); + const currentPageNumber = currentPage === 0 ? currentPage : currentPage - 1; + dispatch(fetchNotifications(Number(currentPageNumber))); + }; - const getNotificationsCountPagitation = useCallback(async () => { - if (currentUserAddress && isLoggedIn) { - const result = await rFetch(`/api/notifications`); - if (result.success && result.totalCount > 0) { - setTotalPageForPagination(result.totalCount); - } - } else { - setTotalPageForPagination(0); - } - }, [currentUserAddress, isLoggedIn]); + const getNotificationsCountPagitation = useCallback(async () => { + if (currentUserAddress && isLoggedIn) { + setTotalPageForPagination(notificationCount); + } else { + setTotalPageForPagination(0); + } + }, [currentUserAddress, isLoggedIn, notificationCount]); - const deleteAllNotificaiton = useCallback(async () => { - if (currentUserAddress) { - const result = await rFetch(`/api/notifications`, { - method: 'DELETE', - body: JSON.stringify([]) - }); + const deleteAllNotificaiton = useCallback(async () => { + if (currentUserAddress) { + const result = await rFetch(`/api/notifications`, { + method: 'DELETE', + body: JSON.stringify([]) + }); - if (result.success) { - getNotifications(); - getNotificationsCount(); - reactSwal.fire({ - title: 'Success', - icon: 'success' - }); - } - } - }, [ - currentUserAddress, - getNotifications, - getNotificationsCount, - reactSwal - ]); - - useEffect(() => { - if (openModal) { - getNotifications(0); - getNotificationsCount(); + if (result.success) { + dispatch(fetchNotifications(0)); + reactSwal.fire({ + title: 'Success', + icon: 'success' + }); } - }, [getNotifications, getNotificationsCount, openModal]); + } + }, [currentUserAddress, reactSwal]); - useEffect(() => { - getNotificationsCount(); - }, [getNotificationsCount]); + useEffect(() => { + if (openModal) { + dispatch(fetchNotifications(0)); + } + }, [dispatch, openModal]); - useEffect(() => { - getNotificationsCountPagitation(); - }, [getNotificationsCountPagitation]); + useEffect(() => { + getNotificationsCountPagitation(); + }, [getNotificationsCountPagitation]); - const onCloseNext = useCallback(() => { - if (!openModal) { - setOpenModal(false); - } - }, [openModal]); + const onCloseNext = useCallback(() => { + if (!openModal) { + setOpenModal(false); + } + }, [openModal]); - useEffect(() => { - onCloseNext(); - }, [onCloseNext]); + useEffect(() => { + onCloseNext(); + }, [onCloseNext]); - return ( - <> + return ( + <> + {currentUserAddress && isLoggedIn && ( setOpenModal((prev) => !prev)} className="social-bell-icon notifications" @@ -104,7 +89,7 @@ const PopUpNotification = ({ notification={true}> {email && } - {notificationCount > 0 && ( + {totalUnreadCount > 0 && (
    - {notificationCount > 9 ? '9+' : notificationCount} + {totalUnreadCount > 9 ? '9+' : totalUnreadCount}
    )}
    - { - setOpenModal(false); - }}> - {openModal && ( -
    -
    -
    Notifications
    - -
    -
    - {realDataNotification && realDataNotification.length > 0 ? ( - realDataNotification.map((el) => { - return ( - - ); - }) - ) : ( -
    - {"You don't have any notifications now"} -
    - )} -
    - {notificationCount > 0 && totalPageForPagination && ( - - )} + Clear all + +
    +
    + {realDataNotification && realDataNotification.length > 0 ? ( + realDataNotification.map((el) => { + return ( + + ); + }) + ) : ( +
    + {"You don't have any notifications now"}
    + )} +
    + {notificationCount > 0 && totalPageForPagination && ( + + )}
    - )} - - - ); - }; +
    + )} + + + ); +}; export default PopUpNotification; diff --git a/rair-front/src/components/common/PurchaseToken.tsx b/rair-front/src/components/common/PurchaseToken.tsx index e63cc64dd..de2a27773 100644 --- a/rair-front/src/components/common/PurchaseToken.tsx +++ b/rair-front/src/components/common/PurchaseToken.tsx @@ -104,6 +104,7 @@ const Agreements: React.FC = ({ useContracts(); const { currentUserAddress } = useAppSelector((store) => store.web3); + const { isLoggedIn } = useAppSelector((store) => store.user); const { textColor, primaryButtonColor } = useAppSelector( (store) => store.colors ); @@ -266,6 +267,10 @@ const Agreements: React.FC = ({ }); }; + if (!isLoggedIn) { + reactSwal.fire('Please login', '', 'info'); + } + if (!diamondMarketplaceInstance) { return ; } diff --git a/rair-front/src/components/nft/PersonalProfile/PersonalProfileFavoritesTab/MyfavoriteItem/MyfavoriteItem.tsx b/rair-front/src/components/nft/PersonalProfile/PersonalProfileFavoritesTab/MyfavoriteItem/MyfavoriteItem.tsx index f05252de8..e946e0e88 100644 --- a/rair-front/src/components/nft/PersonalProfile/PersonalProfileFavoritesTab/MyfavoriteItem/MyfavoriteItem.tsx +++ b/rair-front/src/components/nft/PersonalProfile/PersonalProfileFavoritesTab/MyfavoriteItem/MyfavoriteItem.tsx @@ -1,9 +1,10 @@ +//@ts-nocheck import React, { useCallback, useEffect, useState } from 'react'; import { useLocation, useNavigate } from 'react-router-dom'; import axios from 'axios'; import { isAddress, ZeroAddress } from 'ethers'; -import { FavoriteItem, UserFavoriteItemInfo } from './MyFavoriteStyledItems'; +import { FavoriteItem } from './MyFavoriteStyledItems'; import { TUserResponse } from '../../../../../axios.responseTypes'; import { useAppSelector } from '../../../../../hooks/useReduxHooks'; @@ -14,6 +15,7 @@ import BtnMyFavorite from '../BtnMyFavorite/BtnMyFavorite'; import { IMyfavoriteItem } from '../myFavorites.types'; import defaultAvatar from './../../../../UserProfileSettings/images/defaultUserPictures.png'; +import useWindowDimensions from '../../../../../hooks/useWindowDimensions'; const MyfavoriteItem: React.FC = ({ item, @@ -22,6 +24,8 @@ const MyfavoriteItem: React.FC = ({ }) => { const [profileData, setprofileData] = useState(undefined); const { isLoggedIn, publicAddress } = useAppSelector((store) => store.user); + const { width } = useWindowDimensions(); + const isMobileDesign = width < 600; const navigate = useNavigate(); @@ -82,69 +86,91 @@ const MyfavoriteItem: React.FC = ({ image={item.token.metadata.image}>
    + cursor: 'pointer', + zIndex: '5', + height: '100%' + }}> -
    +
    {isCurrentUser && ( removeFavotite && removeFavotite(item._id)} /> )} -
    -
    - - {item.token.metadata ? ( - <> - {item.token.metadata.name} - - ) : ( - No metadata available - )} -
    -
    -
    - - {profileData && ( - user - )} - {profileData && ( - - {profileData.nickName - ? profileData.nickName.length > 16 - ? profileData.nickName.slice(0, 5) + - '...' + - profileData.nickName.slice( - profileData.nickName.length - 4 - ) - : profileData.nickName - : profileData?.publicAddress?.slice(0, 5) + - '...' + - profileData?.publicAddress?.slice( - profileData.publicAddress.length - 4 +
    +
    +
    + {item.token.metadata?.name !== 'none' && + isMobileDesign && + item.token.metadata?.name.length > 16 + ? item.token.metadata?.name.slice(0, 16) + '...' + : item.token.metadata?.name.length > 22 + ? item.token.metadata?.name.slice(0, 22) + '...' + : item.token.metadata?.name} +
    +
    + {item?.token.isMinted && item?.token?.ownerAddress && ( +
    + User Avatar +
    + {profileData && ( + <> + {profileData.nickName + ? profileData.nickName.length > 16 + ? profileData.nickName.slice(0, 5) + + '...' + + profileData.nickName.slice( + profileData.nickName.length - 4 + ) + : profileData.nickName + : profileData?.publicAddress?.slice(0, 5) + + '...' + + profileData?.publicAddress?.slice( + profileData.publicAddress.length - 4 + )} + )} - - )} - +
    +
    + )} +
    +
    +
    + View item +
    diff --git a/rair-front/src/components/nft/PersonalProfile/PersonalProfileMyNftTab/ResaleModal/ResaleModal.tsx b/rair-front/src/components/nft/PersonalProfile/PersonalProfileMyNftTab/ResaleModal/ResaleModal.tsx index 570bdd3e6..1c4a8c393 100644 --- a/rair-front/src/components/nft/PersonalProfile/PersonalProfileMyNftTab/ResaleModal/ResaleModal.tsx +++ b/rair-front/src/components/nft/PersonalProfile/PersonalProfileMyNftTab/ResaleModal/ResaleModal.tsx @@ -305,10 +305,18 @@ const ResaleModal: React.FC = ({
    {item && item.metadata && item.metadata.name}
    -
    +
    {chainData && ( <> -
    {chainData.symbol}
    +
    {chainData?.viem?.nativeCurrency?.symbol}
    blockchain )} diff --git a/rair-front/src/components/video/video.types.ts b/rair-front/src/components/video/video.types.ts index 28c33738e..1a944146c 100644 --- a/rair-front/src/components/video/video.types.ts +++ b/rair-front/src/components/video/video.types.ts @@ -1,5 +1,6 @@ import { TTokenData } from '../../axios.responseTypes'; import { CatalogVideoItem } from '../../types/commonTypes'; +import { TSortChoice } from '../ResalePage/listOffers.types'; import { ContractType } from './../adminViews/adminView.types'; export interface IVideoPlayer { @@ -23,6 +24,7 @@ export interface IVideoList { responseLabel?: string; endpoint?: string; handleVideoIsUnlocked?: () => void; + sortItem: TSortChoice | undefined; } export type MediaListResponseType = { diff --git a/rair-front/src/components/video/videoItem.tsx b/rair-front/src/components/video/videoItem.tsx index e9801922b..eb010694d 100644 --- a/rair-front/src/components/video/videoItem.tsx +++ b/rair-front/src/components/video/videoItem.tsx @@ -15,11 +15,10 @@ import { useAppSelector } from '../../hooks/useReduxHooks'; import useSwal from '../../hooks/useSwal'; import useWindowDimensions from '../../hooks/useWindowDimensions'; import { CustomModalStyle } from '../../types/commonTypes'; -import { User } from '../../types/databaseTypes'; +import { Offer, User } from '../../types/databaseTypes'; import formatDuration from '../../utils/durationUtils'; import { rFetch } from '../../utils/rFetch'; import { TooltipBox } from '../common/Tooltip/TooltipBox'; -import { TOfferType } from '../marketplace/marketplace.types'; import NftVideoplayer from '../MockUpPage/NftList/NftData/NftVideoplayer/NftVideoplayer'; import { SvgLock } from '../MockUpPage/NftList/SvgLock'; import CustomButton from '../MockUpPage/utils/button/CustomButton'; @@ -31,7 +30,7 @@ import YotiPage from '../YotiPage/YotiPage'; Modal.setAppElement('#root'); const VideoItem: React.FC = ({ item }) => { - const [offersArray, setOffersArray] = useState([]); + const [offersArray, setOffersArray] = useState([]); const { ageVerified } = useAppSelector((store) => store.user); @@ -136,20 +135,14 @@ const VideoItem: React.FC = ({ item }) => { }; const getInfo = useCallback(async () => { - if (item) { - const { data } = await rFetch(`/api/files/${item._id}/unlocks`); - - if (data?.offers && data.offers.length > 0) { - const firstOffer = data.offers[0]; - - if (firstOffer.contract?._id) { - const { contract } = await rFetch( - `/api/contracts/${firstOffer.contract._id}` - ); - setOffersArray(data.offers); - - setContractData(contract); - } + if (item.unlockData?.offers && item.unlockData?.offers.length > 0) { + const firstOffer = item.unlockData.offers[0]; + setOffersArray(item.unlockData.offers); + if (firstOffer.contract) { + const { contract } = await rFetch( + `/api/contracts/${firstOffer.contract}` + ); + setContractData(contract); } } }, [item, setContractData]); diff --git a/rair-front/src/components/video/videoList.tsx b/rair-front/src/components/video/videoList.tsx index b927aa786..b47b1eea5 100644 --- a/rair-front/src/components/video/videoList.tsx +++ b/rair-front/src/components/video/videoList.tsx @@ -14,7 +14,7 @@ import LoadingComponent from '../common/LoadingComponent'; import HomePageFilterModal from '../GlobalModal/FilterModal/FilterModal'; import GlobalModal from '../GlobalModal/GlobalModal'; -const VideoList: React.FC = ({ titleSearch }) => { +const VideoList: React.FC = ({ titleSearch, sortItem }) => { const { videoListStatus, totalVideos, videos } = useAppSelector( (state) => state.videos ); @@ -50,6 +50,21 @@ const VideoList: React.FC = ({ titleSearch }) => { .filter((video) => video.title.toLowerCase().includes(titleSearch.toLowerCase()) ) + .sort((a, b) => { + if (sortItem === 'up') { + if (a.title < b.title) { + return 1; + } + } + + if (sortItem === 'down') { + if (a.title > b.title) { + return -1; + } + } + + return 0; + }) .map((video, index) => { return ; }) diff --git a/rair-front/src/components/videoManager/VideoManager.tsx b/rair-front/src/components/videoManager/VideoManager.tsx index 80e376fff..2dba0e59b 100644 --- a/rair-front/src/components/videoManager/VideoManager.tsx +++ b/rair-front/src/components/videoManager/VideoManager.tsx @@ -2,6 +2,7 @@ import { useCallback, useEffect, useState } from 'react'; import { Provider, useStore } from 'react-redux'; import { faTrash } from '@fortawesome/free-solid-svg-icons'; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; +import { formatEther } from 'ethers'; import OfferSelector from './OfferSelector'; @@ -9,26 +10,48 @@ import { useAppSelector } from '../../hooks/useReduxHooks'; import useServerSettings from '../../hooks/useServerSettings'; import useSwal from '../../hooks/useSwal'; import { rFetch } from '../../utils/rFetch'; +import { OptionsType } from '../common/commonTypes/InputSelectTypes.types'; import InputField from '../common/InputField'; +import InputSelect from '../common/InputSelect'; import AnalyticsPopUp from '../DemoMediaUpload/UploadedListBox/AnalyticsPopUp/AnalyticsPopUp'; -import { formatEther } from 'ethers'; const VideoManager = () => { const [uploads, setUploads] = useState([]); const [unlockData, setUnlockData] = useState([]); const [refresh, setRefresh] = useState(false); const [hiddenFlag, setHiddenFlag] = useState(false); + const [categoryOptions, setCategoryOptions] = useState>( + [] + ); const [filter, setFilter] = useState(''); const [selectedFile, setSelectedFile] = useState({}); const { currentUserAddress } = useAppSelector((store) => store.web3); - const { textColor, primaryButtonColor, secondaryButtonColor } = + const { primaryColor, textColor, primaryButtonColor, secondaryButtonColor } = useAppSelector((store) => store.colors); const { getBlockchainData } = useServerSettings(); const reactSwal = useSwal(); + const loadCategories = useCallback(async () => { + const { success, result } = await rFetch('/api/categories'); + if (success) { + setCategoryOptions( + result.map((item) => { + return { + label: item.name, + value: item._id + }; + }) + ); + } + }, []); + + useEffect(() => { + loadCategories(); + }, [loadCategories]); + useEffect(() => { setUnlockData([]); if (!selectedFile._id) { @@ -120,6 +143,15 @@ const VideoManager = () => { }); }, [selectedFile, refreshFileList, reactSwal]); + const updateCategory = useCallback( + async (categoryId) => { + await updateFile({ + category: categoryId + }); + }, + [updateFile] + ); + const updateDemoStatus = useCallback(async () => { await updateFile({ demo: !selectedFile.demo @@ -219,53 +251,106 @@ const VideoManager = () => { } />
    -
    - {selectedFile.type} -

    {selectedFile.title}

    -
    - -
    - {selectedFile?.category?.name} -
    - - - -
    - {selectedFile.duration} -
    - {selectedFile.description} -
    -
    +
    + + + {[ + { + label: 'Type', + value: selectedFile.type + }, + { + label: 'Title', + value: selectedFile.title + }, + { + label: 'Category', + value: ( + + ) + }, + { + label: 'Views', + value: + }, + { + label: 'Unlockable', + value: ( + + ) + }, + { + label: 'Age Restriction', + value: ( + + ) + }, + { + label: 'Visibility', + value: ( + + ) + }, + { + label: 'Duration', + value: selectedFile.duration + }, + { + label: 'Description', + value: selectedFile.description + } + ].map((item, index) => { + return ( + + + + + ); + })} + +
    {item.label}{item.value}
    diff --git a/rair-front/src/hooks/useConnectUser.tsx b/rair-front/src/hooks/useConnectUser.tsx index f7e50cc3c..12a6b76cb 100644 --- a/rair-front/src/hooks/useConnectUser.tsx +++ b/rair-front/src/hooks/useConnectUser.tsx @@ -253,7 +253,7 @@ const useConnectUser = () => { dispatchStack.push(setExchangeRates(await getCoingeckoRates())); dispatchStack.push(setConnectedChain(loginData.blockchain)); - let firstTimeLogin = false; + let willUpdateUserData = false; try { // Check if user exists in DB @@ -263,10 +263,14 @@ const useConnectUser = () => { let user = userDataResponse.data.user; if (!userDataResponse.data.success || !user) { // If the user doesn't exist, send a request to register him using a TEMP adminNFT - firstTimeLogin = true; + willUpdateUserData = true; + const relevantUserData = { publicAddress: loginData.userAddress }; + if (loginData?.userDetails?.email) { + relevantUserData['email'] = loginData.userDetails.email; + } const userCreation = await axios.post( '/api/users', - JSON.stringify({ publicAddress: loginData.userAddress }), + JSON.stringify(relevantUserData), { headers: { Accept: 'application/json', @@ -275,6 +279,11 @@ const useConnectUser = () => { } ); user = userCreation.data.user; + } else if ( + !userDataResponse?.data?.user?.email && + loginData?.userDetails?.email + ) { + willUpdateUserData = true; } // Authorize user @@ -298,11 +307,13 @@ const useConnectUser = () => { loginData.userAddress ); reactSwal.close(); - if (firstTimeLogin) { + if (willUpdateUserData) { const userData = await loginData.userDetails; const availableData: Partial = {}; - if (userData.email) { + if (userData?.email && !loginResponse.user.email) { availableData.email = userData.email; + } + if (userData?.email && !loginResponse.user.nickName) { availableData.nickName = userData.email?.split('@')?.[0]; } if (userData.name && !userData.name.includes('@')) { diff --git a/rair-front/src/images/index.tsx b/rair-front/src/images/index.tsx index 6135fc8ef..ced95ee51 100644 --- a/rair-front/src/images/index.tsx +++ b/rair-front/src/images/index.tsx @@ -321,7 +321,6 @@ export const MenuIcon = ({ primaryColor }) => { }; export const CloseIconMobile = ({ primaryColor }) => { - console.info(primaryColor, 'primaryColor') return ( ; + totalCount: number; + totalUnreadCount: number; + notificationsStatus: dataStatuses; +} + +interface NotificaitonItem { + createdAt: string; + data: Array; + read: boolean; + tokenData: Array; + type: string; + updatedAt: string; + user: string; + _id: string; +} + +const initialState: NotificationState = { + notifications: [], + totalCount: 0, + totalUnreadCount: 0, + notificationsStatus: dataStatuses.Uninitialized +}; + +export const fetchNotifications = createAsyncThunk( + 'notifications/fetchData', + async (pageNum?: number) => { + const responseData = await axios.get( + `/api/notifications${pageNum ? `?pageNum=${Number(pageNum)}` : ''}` + ); + + const responseUnreadData = await axios.get( + `/api/notifications?onlyUnread=true` + ); + + return { + data: responseData, + unreadData: responseUnreadData + }; + } +); + +export const notificationsSlice = createSlice({ + name: 'notifications', + initialState, + reducers: { + clearResults: (state) => { + state.notificationsStatus = {}; + } + }, + extraReducers: (builder) => { + builder + .addCase(fetchNotifications.pending, (state) => { + state.notificationsStatus = dataStatuses.Loading; + }) + .addCase(fetchNotifications.fulfilled, (state, action: PayloadAction) => { + state.notificationsStatus = dataStatuses.Complete; + const sortedNotifications = action.payload.data.data.notifications.sort( + (a, b) => { + if (!a.read && b.read) return -1; + if (a.read && !b.read) return 1; + + const dateA = new Date(a.createdAt).getTime(); + const dateB = new Date(b.createdAt).getTime(); + + return dateB - dateA; + } + ); + + state.notifications = sortedNotifications; + state.totalCount = action.payload.data.data.totalCount; + state.totalUnreadCount = action.payload.unreadData.data.totalCount; + }) + .addCase(fetchNotifications.rejected, (state) => { + state.notificationsStatus = dataStatuses.Failed; + }); + } +}); + +export const { clearResults } = notificationsSlice.actions; +export default notificationsSlice.reducer; diff --git a/rair-front/src/redux/store.ts b/rair-front/src/redux/store.ts index b42ca091b..02ffda718 100644 --- a/rair-front/src/redux/store.ts +++ b/rair-front/src/redux/store.ts @@ -2,6 +2,7 @@ import type { Action, ThunkAction } from '@reduxjs/toolkit'; import { configureStore } from '@reduxjs/toolkit'; import colorSlice from './colorSlice'; +import notificationsSlice from './notificationsSlice'; import searchbarSlice from './searchbarSlice'; import seoSlice from './seoSlice'; import settingsSlice from './settingsSlice'; @@ -19,7 +20,8 @@ export const store = configureStore({ seo: seoSlice, user: userSlice, videos: videoSlice, - searchbar: searchbarSlice + searchbar: searchbarSlice, + notifications: notificationsSlice } }); diff --git a/rair-front/src/redux/tokenSlice.ts b/rair-front/src/redux/tokenSlice.ts index eba57a752..7b553caaa 100644 --- a/rair-front/src/redux/tokenSlice.ts +++ b/rair-front/src/redux/tokenSlice.ts @@ -94,6 +94,7 @@ export interface TokensState { currentCollectionStatus: dataStatuses; currentCollectionTotal: number; currentCollection: { [index: string]: CollectionTokens }; + currentCollectionNextPageStatus: boolean; currentCollectionMetadata: MetadataForCollection; currentCollectionMetadataStatus: dataStatuses; itemsPerPage: number; @@ -110,6 +111,7 @@ const initialState: TokensState = { currentCollectionStatus: dataStatuses.Uninitialized, currentCollectionTotal: 0, currentCollection: {}, + currentCollectionNextPageStatus: false, currentCollectionParams: undefined, // Collection contract data currentCollectionMetadataStatus: dataStatuses.Uninitialized, @@ -272,9 +274,10 @@ export const loadNextCollectionPage = createAsyncThunk( if (!tokens.currentCollectionParams) { return; } + const lastTokenLoaded = Object.keys(tokens.currentCollection).at(-1); const { blockchain, contract, product, fromToken, toToken, attributes } = tokens.currentCollectionParams; - const startingToken = BigInt(toToken) + BigInt(1); + const startingToken = BigInt(lastTokenLoaded || toToken) + BigInt(1); const queryParams = new URLSearchParams({ fromToken: startingToken.toString(), toToken: (startingToken + BigInt(20)).toString() @@ -313,6 +316,7 @@ export const tokenSlice = createSlice({ state.currentCollectionStatus = dataStatuses.Uninitialized; state.currentCollectionTotal = 0; state.currentCollection = {}; + state.currentCollectionNextPageStatus = false; state.currentCollectionMetadataStatus = dataStatuses.Uninitialized; state.currentCollectionMetadata = {}; state.currentCollectionParams = undefined; @@ -359,6 +363,10 @@ export const tokenSlice = createSlice({ }) // Reuse collection data for next page + .addCase(loadNextCollectionPage.pending, (state) => { + state.currentCollectionNextPageStatus = true; + }) + .addCase( loadNextCollectionPage.fulfilled, (state, action: PayloadAction) => { @@ -367,10 +375,15 @@ export const tokenSlice = createSlice({ state.currentCollection[token.uniqueIndexInContract.toString()] = token; }); + state.currentCollectionNextPageStatus = false; } } ) + .addCase(loadNextCollectionPage.rejected, (state) => { + state.currentCollectionNextPageStatus = false; + }) + // Load metadata for collection .addCase(loadCollectionMetadata.pending, (state) => { state.currentCollectionMetadataStatus = dataStatuses.Loading; diff --git a/rair-front/src/styled-components/SocialLinkIcons/SocialLinkIcons.tsx b/rair-front/src/styled-components/SocialLinkIcons/SocialLinkIcons.tsx index 30e918b46..4178feb7c 100644 --- a/rair-front/src/styled-components/SocialLinkIcons/SocialLinkIcons.tsx +++ b/rair-front/src/styled-components/SocialLinkIcons/SocialLinkIcons.tsx @@ -36,12 +36,12 @@ export const SocialBox = styled.div.withConfig({ span { width: 7px; height: 7px; - background: red; + // background: red; position: absolute; top: 0px; right: 0; border-radius: 50%; - background: #f63419; + // background: #f63419; } &.social-sun-icon { diff --git a/rair-front/yarn.lock b/rair-front/yarn.lock index 4b8011283..a640b0b09 100644 --- a/rair-front/yarn.lock +++ b/rair-front/yarn.lock @@ -2335,12 +2335,12 @@ "@ethereumjs/util" "^8.1.0" crc-32 "^1.2.0" -"@ethereumjs/common@^4.1.0", "@ethereumjs/common@^4.2.0": - version "4.2.0" - resolved "https://registry.npmjs.org/@ethereumjs/common/-/common-4.2.0.tgz" - integrity sha512-UWqovZQksxEY9cU+s1cF3JwFyJdKrJsURM+ORHpZZLQfsqQf+1uGbD3N0AvQ7M+Jz/LxkiVY98+Cd3OMzsrOcA== +"@ethereumjs/common@^4.1.0", "@ethereumjs/common@^4.4.0": + version "4.4.0" + resolved "https://registry.npmjs.org/@ethereumjs/common/-/common-4.4.0.tgz" + integrity sha512-Fy5hMqF6GsE6DpYTyqdDIJPJgUtDn4dL120zKw+Pswuo+iLyBsEYuSyzMw6NVzD2vDzcBG9fE4+qX4X2bPc97w== dependencies: - "@ethereumjs/util" "^9.0.2" + "@ethereumjs/util" "^9.1.0" "@ethereumjs/rlp@^4.0.1": version "4.0.1" @@ -2363,14 +2363,14 @@ ethereum-cryptography "^2.0.0" "@ethereumjs/tx@^5.1.0": - version "5.2.1" - resolved "https://registry.npmjs.org/@ethereumjs/tx/-/tx-5.2.1.tgz" - integrity sha512-BzdtUaa7KtP8T5NxJWRxo/RBoJzxYeCdx2n2C4zZLuWJBYVccfcyMiyDgr6W78Utmu/jIfGXknfh2t06+rTkiw== + version "5.4.0" + resolved "https://registry.npmjs.org/@ethereumjs/tx/-/tx-5.4.0.tgz" + integrity sha512-SCHnK7m/AouZ7nyoR0MEXw1OO/tQojSbp88t8oxhwes5iZkZCtfFdUrJaiIb72qIpH2FVw6s1k1uP7LXuH7PsA== dependencies: - "@ethereumjs/common" "^4.2.0" + "@ethereumjs/common" "^4.4.0" "@ethereumjs/rlp" "^5.0.2" - "@ethereumjs/util" "^9.0.2" - ethereum-cryptography "^2.1.3" + "@ethereumjs/util" "^9.1.0" + ethereum-cryptography "^2.2.1" "@ethereumjs/util@^8.0.0", "@ethereumjs/util@^8.1.0": version "8.1.0" @@ -2381,7 +2381,7 @@ ethereum-cryptography "^2.0.0" micro-ftch "^0.3.1" -"@ethereumjs/util@^9.0.1", "@ethereumjs/util@^9.0.2": +"@ethereumjs/util@^9.0.1": version "9.0.2" resolved "https://registry.npmjs.org/@ethereumjs/util/-/util-9.0.2.tgz" integrity sha512-dasKCj6Vb5spVPnNmRDFHmbfBySvokE440F0RDroPLzO4Mb4hyDqeoOMUxlbLz/BscK2pOpWUendGA+AOvGpNQ== @@ -2397,6 +2397,14 @@ "@ethereumjs/rlp" "^5.0.2" ethereum-cryptography "^2.2.1" +"@ethereumjs/util@^9.1.0": + version "9.1.0" + resolved "https://registry.npmjs.org/@ethereumjs/util/-/util-9.1.0.tgz" + integrity sha512-XBEKsYqLGXLah9PNJbgdkigthkG7TAGvlD/sH12beMXEyHDyigfcbdvHhmLyDWgDyOJn4QwiQUaF7yeuhnjdog== + dependencies: + "@ethereumjs/rlp" "^5.0.2" + ethereum-cryptography "^2.2.1" + "@ethersproject/abi@^5.7.0", "@ethersproject/abi@5.7.0": version "5.7.0" resolved "https://registry.npmjs.org/@ethersproject/abi/-/abi-5.7.0.tgz" @@ -2793,6 +2801,13 @@ dependencies: "@fortawesome/fontawesome-common-types" "6.6.0" +"@fortawesome/free-regular-svg-icons@^6.6.0": + version "6.6.0" + resolved "https://registry.npmjs.org/@fortawesome/free-regular-svg-icons/-/free-regular-svg-icons-6.6.0.tgz" + integrity sha512-Yv9hDzL4aI73BEwSEh20clrY8q/uLxawaQ98lekBx6t9dQKDHcDzzV1p2YtBGTtolYtNqcWdniOnhzB+JPnQEQ== + dependencies: + "@fortawesome/fontawesome-common-types" "6.6.0" + "@fortawesome/free-solid-svg-icons@^6.6.0": version "6.6.0" resolved "https://registry.npmjs.org/@fortawesome/free-solid-svg-icons/-/free-solid-svg-icons-6.6.0.tgz" @@ -3446,13 +3461,13 @@ dependencies: moo "^0.5.1" -"@metamask/abi-utils@^2.0.2": - version "2.0.2" - resolved "https://registry.npmjs.org/@metamask/abi-utils/-/abi-utils-2.0.2.tgz" - integrity sha512-B/A1dY/w4F/t6cDHUscklO6ovb/ztFsrsTXFd8QlqSByk/vyy+QbPE3VVpmmyI/7RX+PA1AJcvBdzCIz+r9dVQ== +"@metamask/abi-utils@^2.0.4": + version "2.0.4" + resolved "https://registry.npmjs.org/@metamask/abi-utils/-/abi-utils-2.0.4.tgz" + integrity sha512-StnIgUB75x7a7AgUhiaUZDpCsqGp7VkNnZh2XivXkJ6mPkE83U8ARGQj5MbRis7VJY8BC5V1AbB1fjdh0hupPQ== dependencies: - "@metamask/utils" "^8.0.0" - superstruct "^1.0.3" + "@metamask/superstruct" "^3.1.0" + "@metamask/utils" "^9.0.0" "@metamask/detect-provider@^2.0.0": version "2.0.0" @@ -3469,16 +3484,16 @@ "@metamask/utils" "^5.0.1" "@metamask/eth-sig-util@^7.0.1": - version "7.0.1" - resolved "https://registry.npmjs.org/@metamask/eth-sig-util/-/eth-sig-util-7.0.1.tgz" - integrity sha512-59GSrMyFH2fPfu7nKeIQdZ150zxXNNhAQIUaFRUW+MGtVA4w/ONbiQobcRBLi+jQProfIyss51G8pfLPcQ0ylg== + version "7.0.3" + resolved "https://registry.npmjs.org/@metamask/eth-sig-util/-/eth-sig-util-7.0.3.tgz" + integrity sha512-PAtGnOkYvh90k2lEZldq/FK7GTLF6WxE+2bV85PoA3pqlJnmJCAY62tuvxHSwnVngSKlc4mcNvjnUg2eYO6JGg== dependencies: "@ethereumjs/util" "^8.1.0" - "@metamask/abi-utils" "^2.0.2" - "@metamask/utils" "^8.1.0" + "@metamask/abi-utils" "^2.0.4" + "@metamask/utils" "^9.0.0" + "@scure/base" "~1.1.3" ethereum-cryptography "^2.1.2" tweetnacl "^1.0.3" - tweetnacl-util "^0.15.1" "@metamask/eth-sig-util@5.0.2": version "5.0.2" @@ -3672,6 +3687,11 @@ util "^0.12.4" uuid "^8.3.2" +"@metamask/superstruct@^3.1.0": + version "3.1.0" + resolved "https://registry.npmjs.org/@metamask/superstruct/-/superstruct-3.1.0.tgz" + integrity sha512-N08M56HdOgBfRKkrgCMZvQppkZGcArEop3kixNEtVbJKm6P9Cfg0YkI6X0s1g78sNrj2fWUwvJADdZuzJgFttA== + "@metamask/utils@^5.0.1": version "5.0.2" resolved "https://registry.npmjs.org/@metamask/utils/-/utils-5.0.2.tgz" @@ -3683,7 +3703,7 @@ semver "^7.3.8" superstruct "^1.0.3" -"@metamask/utils@^8.0.0", "@metamask/utils@^8.1.0", "@metamask/utils@^8.3.0": +"@metamask/utils@^8.1.0", "@metamask/utils@^8.3.0": version "8.4.0" resolved "https://registry.npmjs.org/@metamask/utils/-/utils-8.4.0.tgz" integrity sha512-dbIc3C7alOe0agCuBHM1h71UaEaEqOk2W8rAtEn8QGz4haH2Qq7MoK6i7v2guzvkJVVh79c+QCzIqphC3KvrJg== @@ -3698,6 +3718,21 @@ superstruct "^1.0.3" uuid "^9.0.1" +"@metamask/utils@^9.0.0": + version "9.3.0" + resolved "https://registry.npmjs.org/@metamask/utils/-/utils-9.3.0.tgz" + integrity sha512-w8CVbdkDrVXFJbfBSlDfafDR6BAkpDmv1bC1UJVCoVny5tW2RKAdn9i68Xf7asYT4TnUhl/hN4zfUiKQq9II4g== + dependencies: + "@ethereumjs/tx" "^4.2.0" + "@metamask/superstruct" "^3.1.0" + "@noble/hashes" "^1.3.1" + "@scure/base" "^1.1.3" + "@types/debug" "^4.1.7" + debug "^4.3.4" + pony-cause "^2.1.10" + semver "^7.5.4" + uuid "^9.0.1" + "@motionone/animation@^10.15.1", "@motionone/animation@^10.16.3": version "10.16.3" resolved "https://registry.npmjs.org/@motionone/animation/-/animation-10.16.3.tgz" @@ -4518,7 +4553,7 @@ resolved "https://registry.npmjs.org/@safe-global/safe-gateway-typescript-sdk/-/safe-gateway-typescript-sdk-3.13.3.tgz" integrity sha512-qBDM469cVCedpBpeTSn+k5FUr9+rq5bMTflp/mKd7h35uafcexvOR/PHZn2qftqV8b1kc9b8t22cPRJ2365jew== -"@scure/base@^1.1.3", "@scure/base@~1.1.0", "@scure/base@~1.1.2", "@scure/base@~1.1.4", "@scure/base@~1.1.6": +"@scure/base@^1.1.3", "@scure/base@~1.1.0", "@scure/base@~1.1.2", "@scure/base@~1.1.3", "@scure/base@~1.1.4", "@scure/base@~1.1.6": version "1.1.7" resolved "https://registry.npmjs.org/@scure/base/-/base-1.1.7.tgz" integrity sha512-PPNYBslrLNNUQ/Yad37MHYsNQtK67EhWb6WtSvNLLPo7SdVZgkUjD6Dg+5On7zNwmskf8OX7I7Nx5oN+MIWE0g== @@ -5571,12 +5606,12 @@ dependencies: "@types/node" "*" -"@types/node@*", "@types/node@^18.0.0 || >=20.0.0", "@types/node@>=13.7.0": - version "20.10.6" - resolved "https://registry.npmjs.org/@types/node/-/node-20.10.6.tgz" - integrity sha512-Vac8H+NlRNNlAmDfGUP7b5h/KA+AtWIzuXy0E6OyP8f1tCLYAtPvKRRDJjAPqhpCb0t6U2j7/xqAuLEebW2kiw== +"@types/node@*", "@types/node@^18.0.0 || >=20.0.0", "@types/node@>=13.7.0", "@types/node@22.7.5": + version "22.7.5" + resolved "https://registry.npmjs.org/@types/node/-/node-22.7.5.tgz" + integrity sha512-jML7s2NAzMWc//QSJ1a3prpk78cOPchGvXJsC3C6R6PSMoooztvRVQEz89gmBTBY1SPMaqo5teB4uNHPdetShQ== dependencies: - undici-types "~5.26.4" + undici-types "~6.19.2" "@types/node@^10.12.18": version "10.17.60" @@ -9518,17 +9553,7 @@ ethereum-cryptography@^1.1.2: "@scure/bip32" "1.1.5" "@scure/bip39" "1.1.1" -ethereum-cryptography@^2.0.0, ethereum-cryptography@^2.1.2, ethereum-cryptography@^2.1.3: - version "2.1.3" - resolved "https://registry.npmjs.org/ethereum-cryptography/-/ethereum-cryptography-2.1.3.tgz" - integrity sha512-BlwbIL7/P45W8FGW2r7LGuvoEZ+7PWsniMvQ4p5s2xCyw9tmaDlpfsN9HjAucbF+t/qpVHwZUisgfK24TCW8aA== - dependencies: - "@noble/curves" "1.3.0" - "@noble/hashes" "1.3.3" - "@scure/bip32" "1.3.3" - "@scure/bip39" "1.2.2" - -ethereum-cryptography@^2.2.1: +ethereum-cryptography@^2.0.0, ethereum-cryptography@^2.1.2, ethereum-cryptography@^2.1.3, ethereum-cryptography@^2.2.1: version "2.2.1" resolved "https://registry.npmjs.org/ethereum-cryptography/-/ethereum-cryptography-2.2.1.tgz" integrity sha512-r/W8lkHSiTLxUxW8Rf3u4HGB0xQweG2RyETjywylKZSzLWoWAijRz8WCuOtJ6wah+avllXBqZuk29HCCvhEIRg== @@ -9599,16 +9624,16 @@ ethers@^5.5.1, ethers@^5.7.1: "@ethersproject/wordlists" "5.7.0" "ethers@^5.6.8 || ^6.0.8", ethers@^6.13.2: - version "6.13.2" - resolved "https://registry.npmjs.org/ethers/-/ethers-6.13.2.tgz" - integrity sha512-9VkriTTed+/27BGuY1s0hf441kqwHJ1wtN2edksEtiRvXx+soxRX3iSXTfFqq2+YwrOqbDoTHjIhQnjJRlzKmg== + version "6.13.4" + resolved "https://registry.npmjs.org/ethers/-/ethers-6.13.4.tgz" + integrity sha512-21YtnZVg4/zKkCQPjrDj38B1r4nQvTZLopUGMLQ1ePU2zV/joCfDC3t3iKQjWRzjjjbzR+mdAIoikeBRNkdllA== dependencies: "@adraffy/ens-normalize" "1.10.1" "@noble/curves" "1.2.0" "@noble/hashes" "1.3.2" - "@types/node" "18.15.13" + "@types/node" "22.7.5" aes-js "4.0.0-beta.5" - tslib "2.4.0" + tslib "2.7.0" ws "8.17.1" ethers@^5.7.2: @@ -10470,9 +10495,9 @@ i18next-browser-languagedetector@7.1.0: "@babel/runtime" "^7.19.4" i18next@^23.12.2, i18next@^23.7.16, "i18next@>= 23.2.3": - version "23.14.0" - resolved "https://registry.npmjs.org/i18next/-/i18next-23.14.0.tgz" - integrity sha512-Y5GL4OdA8IU2geRrt2+Uc1iIhsjICdHZzT9tNwQ3TVqdNzgxHToGCKf/TPRP80vTCAP6svg2WbbJL+Gx5MFQVA== + version "23.16.2" + resolved "https://registry.npmjs.org/i18next/-/i18next-23.16.2.tgz" + integrity sha512-dFyxwLXxEQK32f6tITBMaRht25mZPJhQ0WbC0p3bO2mWBal9lABTMqSka5k+GLSRWLzeJBKDpH7BeIA9TZI7Jg== dependencies: "@babel/runtime" "^7.23.2" @@ -11860,9 +11885,9 @@ logkitty@^0.7.1: yargs "^15.1.0" loglevel@^1.8.1, loglevel@^1.9.1: - version "1.9.1" - resolved "https://registry.npmjs.org/loglevel/-/loglevel-1.9.1.tgz" - integrity sha512-hP3I3kCrDIMuRwAwHltphhDM1r8i55H33GgqjXbrisuJhF4kRhW1dNuxsRklp4bXl8DSdLaNLuiL4A/LWRfxvg== + version "1.9.2" + resolved "https://registry.npmjs.org/loglevel/-/loglevel-1.9.2.tgz" + integrity sha512-HgMmCqIJSAKqo68l0rS2AanEWfkxaZ5wNiEFb5ggm08lDs9Xl2KxBlX3PTcaD2chBM1gXAYf491/M2Rv8Jwayg== long@^4.0.0: version "4.0.0" @@ -15338,6 +15363,11 @@ tslib@2.6.2: resolved "https://registry.npmjs.org/tslib/-/tslib-2.6.2.tgz" integrity sha512-AEYxH93jGFPn/a2iVAwW87VuUIkR1FVUKB77NwMF7nBTDkDrrT/Hpt/IrCJ0QXhW27jTBDcf5ZY7w6RiqTMw2Q== +tslib@2.7.0: + version "2.7.0" + resolved "https://registry.npmjs.org/tslib/-/tslib-2.7.0.tgz" + integrity sha512-gLXCKdN1/j47AiHiOkJN69hJmcbGTHI0ImLmbYLHykhgeN0jVGola9yVjFgzCUklsZQMW55o+dW7IXv3RCXDzA== + tty-browserify@0.0.1: version "0.0.1" resolved "https://registry.npmjs.org/tty-browserify/-/tty-browserify-0.0.1.tgz" @@ -15518,6 +15548,11 @@ undici-types@~5.26.4: resolved "https://registry.npmjs.org/undici-types/-/undici-types-5.26.5.tgz" integrity sha512-JlCMO+ehdEIKqlFxk6IfVoAUVmgz7cU7zD/h9XZ0qzeosSHmUJVOzSQvvYSYWXkFXC+IfLKSIffhv0sVZup6pA== +undici-types@~6.19.2: + version "6.19.8" + resolved "https://registry.npmjs.org/undici-types/-/undici-types-6.19.8.tgz" + integrity sha512-ve2KP6f/JnbPBFyobGHuerC9g1FYGn/F8n1LWTwNxCEzd6IfqTwUQcNXgEtmmQ6DlRrC1hrSrBnCZPokRrDHjw== + unenv@^1.8.0: version "1.9.0" resolved "https://registry.npmjs.org/unenv/-/unenv-1.9.0.tgz" diff --git a/rair-infra/assets/Performance-Testing/locust/BatchUsersCreate.py b/rair-infra/assets/Performance-Testing/locust/BatchUsersCreate.py new file mode 100644 index 000000000..95045a2bc --- /dev/null +++ b/rair-infra/assets/Performance-Testing/locust/BatchUsersCreate.py @@ -0,0 +1,10 @@ +from locust import HttpUser, task, between +import random + +class BatchUsers(HttpUser): + wait_time = between(3, 8) + @task + def createUser(self): + random_number = hex(random.getrandbits(160)) + request_body = {'publicAddress': random_number} + self.client.post('/api/users', json=request_body) diff --git a/rair-infra/assets/akash/deploy.yml b/rair-infra/assets/akash/deploy.yml new file mode 100644 index 000000000..4d355e835 --- /dev/null +++ b/rair-infra/assets/akash/deploy.yml @@ -0,0 +1,224 @@ +--- +version: "2.0" +services: + mongo: + image: mongo:latest + expose: + - port: 27017 + as: 27017 + proto: tcp + to: + - global: false + - service: rair-front + - service: rair-node + - service: rair-stream + - service: rair-sync + - service: redis + env: + - MONGO_INITDB_ROOT_USERNAME=admin + - MONGO_INITDB_ROOT_PASSWORD=admin + - MONGO_INITDB_DATABASE=rair-db + rair-front: + image: rairprotocol/rair-front:b51c7a7053dd639b204f6ca7f3784246be7031dd + expose: + - port: 80 + as: 80 + to: + - global: true + # uncomment below to have a custom URL for your web page + #accept: + # - xxx.yourdomain.com + http_options: + max_body_size: 4294967295 + read_timeout: 60000 + send_timeout: 60000 + next_cases: + - error + - timeout + next_tries: 3 + next_timeout: 60000 + env: + - Environment=Variables + rair-node: + image: rairprotocol/rair-node:b51c7a7053dd639b204f6ca7f3784246be7031dd + expose: + - port: 3000 + as: 3000 + proto: tcp + to: + - global: false + - service: rair-front + - service: rair-stream + - service: rair-sync + - service: redis + - service: mongo + - port: 5000 + as: 5000 + proto: tcp + to: + - global: false + - service: rair-front + - service: rair-stream + - service: rair-sync + env: + - MONGO_URI_LOCAL=mongodb://admin:admin@mongo:27017/rair-db?authSource=admin + - ADMIN_NETWORK=0x2105 + - APP_NAME=Test_Deployment + - ADMIN_CONTRACT=0xfc3666266d129504dd6c713f9bce107747ae4aee + - REDIS_HOST=redis + - REDIS_PORT=6379 + - SESSION_SECRET=testing + - BASE_BCN_URL=http://rair-sync:5001 + rair-stream: + image: rairprotocol/rair-stream:b51c7a7053dd639b204f6ca7f3784246be7031dd + expose: + - port: 5002 + as: 5002 + proto: tcp + to: + - global: false + - service: rair-front + - service: rair-node + - service: rair-sync + - service: redis + - service: mongo + env: + - REDIS_HOST=redis + - REDIS_PORT=6379 + - BASE_RAIRNODE_URL=http://rair-node:5000 + rair-sync: + image: rairprotocol/rair-sync:b51c7a7053dd639b204f6ca7f3784246be7031dd + expose: + - port: 5001 + as: 5001 + proto: tcp + to: + - global: false + - service: rair-front + - service: rair-node + - service: rair-stream + - service: redis + - service: mongo + env: + - MONGO_URI_LOCAL=mongodb://admin:admin@mongo:27017/rair-db?authSource=admin + - DEFAULT_PRODUCT_COVER=https://rair.myfilebase.com/ipfs/QmcV94NurwfWVGpXTST1we8uDbYiVQamKe87WEHK6DRzqa + - BASE_RAIRNODE_URL=http://rair-node:5000 + - REDIS_HOST=redis + - REDIS_PORT=6379 + - SYNC_CONTRACT_REPEAT_EVERY=30 + - SYNC_CONTRACT_TASK_INTERVAL=5 + redis: + image: redis:6.2.3-alpine + expose: + - port: 6379 + as: 6379 + proto: tcp + to: + - global: false + - service: rair-front + - service: rair-node + - service: rair-stream + - service: rair-sync + - service: mongo + command: + - redis-server + args: + - "--protected-mode no" + env: + - Environment=Variables +profiles: + compute: + mongo: + resources: + cpu: + units: 1 + memory: + size: 2Gi + storage: + - size: 5Gi + rair-front: + resources: + cpu: + units: 1 + memory: + size: 2Gi + storage: + - size: 5Gi + rair-node: + resources: + cpu: + units: 1 + memory: + size: 2Gi + storage: + - size: 5Gi + rair-stream: + resources: + cpu: + units: 1 + memory: + size: 2Gi + storage: + - size: 5Gi + rair-sync: + resources: + cpu: + units: 1 + memory: + size: 2Gi + storage: + - size: 5Gi + redis: + resources: + cpu: + units: 1 + memory: + size: 2Gi + storage: + - size: 5Gi + placement: + dcloud: + pricing: + mongo: + denom: uakt + amount: 1000 + rair-front: + denom: uakt + amount: 1000 + rair-node: + denom: uakt + amount: 1000 + rair-stream: + denom: uakt + amount: 1000 + rair-sync: + denom: uakt + amount: 1000 + redis: + denom: uakt + amount: 1000 +deployment: + mongo: + dcloud: + profile: mongo + count: 1 + rair-front: + dcloud: + profile: rair-front + count: 1 + rair-node: + dcloud: + profile: rair-node + count: 1 + rair-stream: + dcloud: + profile: rair-stream + count: 1 + rair-sync: + dcloud: + profile: rair-sync + count: 1 + redis: + dcloud: + profile: redis + count: 1 diff --git a/rair-infra/assets/selenium/HealthCheck.py b/rair-infra/assets/selenium/HealthCheck.py new file mode 100644 index 000000000..b52c395a5 --- /dev/null +++ b/rair-infra/assets/selenium/HealthCheck.py @@ -0,0 +1,3250 @@ +import unittest +from selenium import webdriver + +# -*- coding: utf-8 -*- +from selenium import webdriver +from selenium.webdriver import ActionChains +from selenium.webdriver.common.by import By +from selenium.webdriver.common.keys import Keys +from selenium.webdriver.support.ui import Select +from selenium.common.exceptions import NoSuchElementException, ElementClickInterceptedException, NoSuchWindowException, \ + ElementNotInteractableException, WebDriverException +from selenium.common.exceptions import NoAlertPresentException +from selenium.webdriver.chrome.options import Options +from selenium.webdriver.common.proxy import Proxy, ProxyType +import unittest, time, re +from bs4 import BeautifulSoup +import pickle +import random +import csv +import traceback +import Automation.WebAutomation.alog +from selenium.webdriver.support.wait import WebDriverWait +from selenium.webdriver.support import expected_conditions as EC +#import WebAutomation.alog +import xml.parsers.expat as xmlerr +import shutil,os,zipfile,socket,time +import json +import sys +import csv +import xml.etree.cElementTree as ET +import pprint +import requests +from collections import defaultdict +from datetime import datetime +import math +from decimal import Decimal +import os +import platform +import zipfile +import mmap +import uuid +import os +import traceback +from threading import Thread +from time import sleep +import subprocess +from subprocess import call +from subprocess import Popen, PIPE +import threading +import glob +from threading import Lock +lock = Lock() +import multiprocessing +import time +import mmap +import pprint +import pytest +from selenium import webdriver +from selenium.common.exceptions import TimeoutException +from selenium.webdriver.chrome.options import Options +from selenium.webdriver.firefox.options import Options as options +from selenium.webdriver.firefox.service import Service +#from selenium.webdriver.opera.options import Options +from selenium.webdriver.common.keys import Keys +from selenium.webdriver.common.desired_capabilities import DesiredCapabilities +from selenium.webdriver.support.ui import Select +from time import sleep +import Automation.WebAutomation.charlesProxyService as c +#import WebAutomation.charlesProxyService as c +from Automation.WebAutomation.utilities import createFolder +#from WebAutomation.utilities import createFolder +import Automation.WebAutomation.webconfig as wc +#import WebAutomation.webconfig as wc +from Automation.WebAutomation.HealthCheckTestRunner import _data +#from WebAutomation.RAIRHomePageTestRunner import _data +from sys import platform +from Locators import Locator +from PIL import Image +from pytesseract import pytesseract +import re + +pp = pprint.PrettyPrinter(indent=4) + +BASE_DIR = os.getcwd() +print("The current directory is") +print(BASE_DIR) + +#os.path.join(BASE_DIR, +base_path = BASE_DIR + +BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +print("The current directory is") +print(BASE_DIR) + +ABOUT_PAGE_URL = wc.ABOUT_PAGE_URL +BETA_URL = wc.BETA_URL +RAIRLICENSE = wc.RAIRLICENSE +GREYMAN_URL = wc.GREYMAN_URL +QA1_URL = wc.QA1_URL +QA2_URL = wc.QA2_URL +QA3_URL = wc.QA3_URL +RAIRPROTOCOL = wc.RAIRPROTOCOL +RAIR_MARKET = wc.RAIR_MARKET +OPENCARBON_MARKET = wc.OPENCARBON_MARKET +HOTDROPS_URL = wc.HOTDROPS_URL +HOTDROPS_PROD_URL = wc.HOTDROPS_PROD_URL +PROD_URL = wc.PROD_URL +SECRET_RECOVERY_PHRASE = wc.SECRET_RECOVERY_PHRASE +SECRET_RECOVERY_PHRASE_QA = wc.SECRET_RECOVERY_PHRASE_QA +NEW_PASSWORD = wc.NEW_PASSWORD +NEW_PASSWORD_QA = wc.NEW_PASSWORD_QA +ChromeExtension_Url = wc.ChromeExtension_Url +Expected_Filter_Labels = wc.Expected_Filter_Labels + +WEBDRIVERDIRECTORY = os.path.join(BASE_DIR, 'WebAutomation/Drivers', 'webdrivers') +SCREENSHOT_DIRECTORY = os.path.join(BASE_DIR, 'WebAutomation/screenshots', '') +VIDEO_UPLOAD_FILE = os.path.join(BASE_DIR, 'WebAutomation', '202307_video.mp4') +#VIDEO_UPLOAD_FILE = os.path.join(BASE_DIR, 'WebAutomation', '500MB.mp4') +METADATA_CSV_FILE = os.path.join(BASE_DIR, 'WebAutomation', 'Metadata_5k.csv') + +conversationBuilderBot = {} +conversationBuilderBot = {} + +############################################################ +global test_results_dir_json_wire +global test_results_dir_csv +global test_results_dir_excel +global test_results_dir_html +global test_results_dir_json_reports + +############################# ############################# +print("Getting the values for the Directories") +test_results_dir_json_wire = _data['test_results_dir_json_wire'] +print(test_results_dir_json_wire) +test_results_dir_csv = _data['test_results_dir_csv'] +print(test_results_dir_csv) +test_results_dir_excel = _data['test_results_dir_excel'] +print(test_results_dir_excel) +test_results_dir_html = _data['test_results_dir_html'] +print(test_results_dir_html) +test_results_dir_json_reports = _data['test_results_dir_json_reports'] +print(test_results_dir_json_reports) + +########################################################### + +if platform == "linux" or platform == "linux2": + print("Linux") + platform = 'Linux' + WEBDRIVERDIRECTORY_CHROMEDRIVER = os.path.join(WEBDRIVERDIRECTORY,'chromedriver','chromedriver_linux64') + WEBDRIVERDIRECTORY_FIREFOXDRIVER = os.path.join(WEBDRIVERDIRECTORY, 'firefoxdriver','geckodriver-linux64') + #EXTENSION_PATH_FIREFOX = '/home/xxxxxx/snap/firefox/common/.mozilla/firefox/3ct2n3rf.default/extensions/webextension@metamask.io.xpi' + EXTENSION_PATH_FIREFOX = '/home/xxxx/.mozilla/firefox/extensions/webextension@metamask.io.xpi' + EXTENSION_PATH_CHROME = '/home/xxxxxx/.config/google-chrome/Default/Extensions/nkbihfbeogaeaoehlefnkodbefgpgknn/10.3.0_0.crx' + +if platform == "darwin": + print("Darwin") + platform = 'Darwin' + WEBDRIVERDIRECTORY_CHROMEDRIVER = os.path.join(WEBDRIVERDIRECTORY, 'chromedriver', 'chromedriver_mac64') + WEBDRIVERDIRECTORY_FIREFOXDRIVER = os.path.join(WEBDRIVERDIRECTORY, 'firefoxdriver', 'geckodriver-macos') + WEBDRIVERDIRECTORY_SAFARIDRIVER = os.path.join(WEBDRIVERDIRECTORY, '', '') + + +if platform == "win32": + print("Win32") + platform = 'Win32' + WEBDRIVERDIRECTORY_CHROMEDRIVER = os.path.join(WEBDRIVERDIRECTORY, 'chromedriver', 'chromedriver_win32') + WEBDRIVERDIRECTORY_FIREFOXDRIVER = os.path.join(WEBDRIVERDIRECTORY, 'firefoxdriver', 'geckodriver-win64') + +if platform == "win64": + print("Win64") + platform = 'Win64' + WEBDRIVERDIRECTORY_CHROMEDRIVER = os.path.join(WEBDRIVERDIRECTORY, 'chromedriver', 'chromedriver_win32') + WEBDRIVERDIRECTORY_FIREFOXDRIVER = os.path.join(WEBDRIVERDIRECTORY, 'firefoxdriver', 'geckodriver-win64') + +#@pytest.fixture(params=["chrome"],scope="class") +@pytest.fixture(params=["firefox"],scope="class") + +def driver_init(request): + if request.param == "chrome": + # Local webdriver implementation + print("Starting Chrome test") + if _data['MITM'] == 'True': + print("Since the MITM Proxy is TRUE we will Set the Proxy option") + myProxy = wc.MITMHOST + ':' + wc.MITMPORT + chrome_options = webdriver.ChromeOptions() + chrome_options.add_argument('--proxy-server=%s' % myProxy) + chrome_options.add_argument('ignore-certificate-errors') + if _data['HEADLESS'] == 'True': + print("Setting the Headless option for Chrome") + chrome_options.add_argument("--headless") + chrome_options.add_argument('--no-sandbox') + chrome_options.add_argument('--disable-dev-shm-usage') + print("Chromedriver Location") + print(WEBDRIVERDIRECTORY_CHROMEDRIVER + '/chromedriver') + web_driver = webdriver.Chrome(executable_path=WEBDRIVERDIRECTORY_CHROMEDRIVER + '/chromedriver',options=chrome_options) + else: + print("Since the MITM Proxy is FALSE we will NOT Set the Proxy option") + print("Chromedriver Location") + print(WEBDRIVERDIRECTORY_CHROMEDRIVER + '/chromedriver') + chrome_options = webdriver.ChromeOptions() + chrome_options.add_extension(EXTENSION_PATH_CHROME) + if _data['HEADLESS'] == 'True': + print("Setting the Headless option for Chrome") + chrome_options.add_argument("--headless") + chrome_options.add_argument('--no-sandbox') + chrome_options.add_argument('--disable-dev-shm-usage') + web_driver = webdriver.Chrome(executable_path=WEBDRIVERDIRECTORY_CHROMEDRIVER + '/chromedriver',options=chrome_options) + + if request.param == "firefox": + print("Starting Firefox test") + if _data['MITM'] == 'True': + print("Since the MITM Proxy is TRUE we will Set the Proxy option") + # Local webdriver implementation + myProxy = wc.MITMHOST + ':' + wc.MITMPORT + proxy = Proxy({ + 'proxyType': ProxyType.MANUAL, + 'httpProxy': myProxy, + 'ftpProxy': myProxy, + 'sslProxy': myProxy, + 'noProxy': '' # set this value as desired + }) + + fireFoxOptions = webdriver.FirefoxOptions() + if _data['HEADLESS'] == 'True': + print("Setting the Headless option for Firefox") + fireFoxOptions.set_headless() + fireFoxOptions.set_preference('network.http.phishy-userpass-length', 255) + fireFoxOptions.set_preference("network.automatic-ntlm-auth.trusted-uris", BETA_URL) + fireFoxOptions.set_preference("network.proxy.type", 1) + fireFoxOptions.set_preference("network.proxy.http", wc.MITMHOST) + fireFoxOptions.set_preference("network.proxy.http_port", wc.MITMPORT) + ############################### + # fireFoxOptions.set_preference('network.proxy.type', 1) + # # Set the host/port. + # fireFoxOptions.set_preference('network.proxy.http', proxy_host) + fireFoxOptions.set_preference('network.proxy.https_port', wc.MITMPORT) + fireFoxOptions.set_preference("network.proxy.ssl", wc.MITMHOST) + fireFoxOptions.set_preference("network.proxy.ssl_port", int(wc.MITMPORT)) + print("Gecko Location") + print(WEBDRIVERDIRECTORY_FIREFOXDRIVER + '/geckodriver') + web_driver = webdriver.Firefox(executable_path=WEBDRIVERDIRECTORY_FIREFOXDRIVER + '/geckodriver', firefox_options=fireFoxOptions) + web_driver.implicitly_wait(1) + else: + print("Since the MITM Proxy is FALSE we will NOT Set the Proxy option") + print("Gecko Location") + print(WEBDRIVERDIRECTORY_FIREFOXDRIVER + '/geckodriver') + fireFoxOptions = webdriver.FirefoxOptions() + if _data['HEADLESS'] == 'True': + print("Setting the Headless option for Firefox") + fireFoxOptions.add_argument("--headless") + #fireFoxOptions.set_headless() + + #Do not wait for page to download completely + options = Options() + options.add_argument("-profile") + options.add_argument("/home/xxxxxx/.mozilla/firefox") + #options.add_argument("/home/opendatalabs/snap/firefox/common/.mozilla/firefox/3ct2n3rf.default") + caps = DesiredCapabilities().FIREFOX + caps["pageLoadStrategy"] = "eager" + new_driver_path = WEBDRIVERDIRECTORY_FIREFOXDRIVER + '/geckodriver' + serv = Service(new_driver_path) + web_driver = webdriver.Firefox(service=serv, options=fireFoxOptions) + web_driver.implicitly_wait(1) + + # if request.param == "safari": + # # Local webdriver implementation + # options = Options() + + request.cls.driver = web_driver + yield + #web_driver.close() + + web_driver.quit() + +def metamask_user_login(self, xxxx, pwd): + driver = self.driver + sleep(5) + driver.find_element("xpath", '//*[@id="onboarding__terms-checkbox"]').click() + #driver.find_element("xpath", '//button[text()="Get started"]').click() + #sleep(5) + #driver.find_element("xpath",'//button[text()="No thanks"]').click() + sleep(2) + driver.find_element("xpath",'//button[text()="Import an existing wallet"]').click() + sleep(5) + driver.find_element("xpath", '//button[text()="I agree"]').click() + sleep(5) + #driver.find_element("xpath",'//button[text()="No Thanks"]').click() + #sleep(5) + # After this you will need to enter you wallet details + inputs = driver.find_elements("xpath",'//input') + + SECRET_RECOVERY_PHRASE = xxxx + NEW_PASSWORD = pwd + + SEED_PHRASE = list(SECRET_RECOVERY_PHRASE.split(" ")) + print(SEED_PHRASE) + i = 0 + j = 0 + while j <= 11: + print(SEED_PHRASE[j]) + inputs[i].send_keys(SEED_PHRASE[j]) + i = i + 2 + j = j + 1 + + sleep(5) + driver.find_element("xpath",'//button[text()="Confirm Secret Recovery Phrase"]').click() + sleep(10) + inputs2 = driver.find_elements("xpath", '//input') + inputs2[0].send_keys(NEW_PASSWORD) + sleep(5) + # driver.find_element('//*[@id="confirm-password"]').send_keys(NEW_PASSWORD) + inputs2[1].send_keys(NEW_PASSWORD) + sleep(5) + driver.find_element("xpath", '//*[@class="create-password__form__terms-label"]').click() + #driver.find_element("xpath",'//*[@id="create-new-vault__terms-checkbox"]').click() + # driver.find_element_by_css_selector('.first-time-flow__terms').click() + sleep(5) + driver.find_element("xpath",'//button[text()="Import my wallet"]').click() + sleep(20) + driver.find_element("xpath", '//button[text()="Got it"]').click() + sleep(5) + driver.find_element("xpath", '//button[text()="Next"]').click() + sleep(5) + driver.find_element("xpath",'//button[text()="Done"]').click() + sleep(10) + +def Switch_Blockchain(self): + driver = self.driver + print("driver.window_handles : " + str(self.driver.window_handles)) + driver.switch_to.window(driver.window_handles[-1]) + time.sleep(10) + driver.find_element("xpath","//button[contains(.,'Approve')]").click() + time.sleep(10) + print("driver.window_handles_network : " + str(self.driver.window_handles)) + driver.switch_to.window(driver.window_handles[-1]) + time.sleep(5) + driver.find_element("xpath","//button[contains(.,'Switch network')]").click() + time.sleep(5) + driver.switch_to.window(driver.window_handles[-1]) + time.sleep(5) + +def ConnectWallet_metamask(self,server): + + self.driver.get(server) + self.driver.find_element(By.TAG_NAME, 'body').send_keys(Keys.CONTROL + "R") + print(self.driver.title) + driver = self.driver + ###########Added because of Bug######### + try: + time.sleep(5) + driver.switch_to.window(driver.window_handles[-1]) + time.sleep(10) + driver.find_element("xpath", Locator.connect_wallet).click() + time.sleep(2) + print("No errors") + except: + + print("An exception occurred") + driver.switch_to.window(driver.window_handles[-1]) + time.sleep(5) + driver.find_element("xpath","//button[contains(.,'Cancel')]").click() + #webdriver.ActionChains(driver).send_keys(Keys.TAB,Keys.TAB,Keys.ENTER).perform() + time.sleep(5) + driver.switch_to.window(driver.window_handles[-1]) + time.sleep(5) + webdriver.ActionChains(driver).send_keys(Keys.ESCAPE).perform() + driver.switch_to.window(driver.window_handles[-1]) + driver.implicitly_wait(10) + driver.find_element("xpath", Locator.connect_wallet).click() + ##################### + + finally: + + time.sleep(10) + driver.switch_to.window(driver.window_handles[-1]) + driver.find_element("xpath", "//button[contains(.,'Web3')]").click() + time.sleep(5) + driver.switch_to.window(driver.window_handles[-1]) + print("driver.window_handles : " + str(self.driver.window_handles)) + driver.find_element("xpath", "//button[contains(.,'Next')]").click() + time.sleep(10) + driver.find_element("xpath", "//button[contains(.,'Confirm')]").click() + time.sleep(20) + print("driver.window_handles_updated : " + str(self.driver.window_handles)) + print("Metamask_window_handle : " + str(self.driver.window_handles[2])) + time.sleep(5) + driver.switch_to.window(driver.window_handles[-1]) + time.sleep(5) + + # Challenge Block + # driver.find_element("xpath","//div[1]/div/div[2]/div/div[3]/div[1]/i").click() + try: + driver.find_element("xpath", '//*[@class="fa fa-arrow-down"]').click() + except: + print("An exception occurred") + finally: + time.sleep(5) + driver.find_element("xpath", "//button[contains(.,'Sign')]").click() + time.sleep(15) + print("driver.window_handles_updated : " + str(self.driver.window_handles)) + # driver.switch_to.window(driver.window_handles[2]) + time.sleep(5) + driver.switch_to.window(driver.window_handles[-1]) + print("Sign-in completed") + #Saving the Screenshot + driver.save_screenshot(SCREENSHOT_DIRECTORY + "ConnectWallet.png") + + # Nonce Block + # driver.find_element_by_xpath("//button[contains(.,'Sign')]").click() + # time.sleep(5) + # driver.switch_to.window(driver.window_handles[-1]) + # time.sleep(5) + # driver.find_element_by_class_name(Locator.menu_admin).click() + # time.sleep(5) + ######################################################### + +def Logout(self): + driver = self.driver + time.sleep(10) + + # driver.find_element_by_xpath("//a[contains(@href, '/all')]").click() + try: + driver.find_element(By.XPATH, Locator.profile_dropdown).click() + except: + print("### Exception ###") + driver.find_element(By.XPATH, Locator.profile_dropdown_beta).click() + else: + print("Nothing went wrong") + + sleep(5) + driver.find_element(By.XPATH, "//li[contains(.,'Logout')]").click() + time.sleep(5) + webdriver.ActionChains(driver).send_keys(Keys.ESCAPE).perform() + + driver.delete_all_cookies() + + # Saving the Screenshot + driver.save_screenshot(SCREENSHOT_DIRECTORY + "Contract_ConfirmReject.png") + time.sleep(10) + + # Opening the image & storing it in an image object + img = Image.open(SCREENSHOT_DIRECTORY + "Contract_ConfirmReject.png") + time.sleep(5) + + # Size of the image in pixels (size of original image) + # (This is not mandatory) + width, height = img.size + + # Setting the points for cropped image + left = 400 + top = height / 8 + right = 1200 + bottom = 7 * height / 8 + + # Cropped image of above dimension + # (It will not change original image) + im1 = img.crop((left, top, right, bottom)) + # Shows the image in image viewer + # im1.show() + + # Passing the image object to image_to_string() function + # This function will extract the text from the image + text = pytesseract.image_to_string(im1) + + # Modifying text + mod_text = text.rstrip() + without_line_breaks = mod_text.replace("\n", " ") + + # Appending text to log file + test_logs = open(SCREENSHOT_DIRECTORY + "TestExecutionLogs.txt", "a") + test_case_name = os.environ.get('PYTEST_CURRENT_TEST').split(':')[-1].split(' ')[0] + test_logs.write( + Test_HealthCheck.dt_string + "," + test_case_name + "," + without_line_breaks + "\n") + test_logs.close() + # print(text[:-1]) + time.sleep(5) + +def Logout_hotdrops(self): + driver = self.driver + time.sleep(10) + + webdriver.ActionChains(driver).send_keys(Keys.ESCAPE).perform() + # driver.find_element_by_xpath("//a[contains(@href, '/all')]").click() + try: + driver.find_element(By.XPATH, Locator.profile_dropdown_hotdrops).click() + except: + print("### Exception ###") + driver.find_element(By.XPATH, Locator.profile_dropdown).click() + else: + print("Nothing went wrong") + + sleep(5) + driver.find_element(By.XPATH, "//li[contains(.,'Logout')]").click() + time.sleep(5) + webdriver.ActionChains(driver).send_keys(Keys.ESCAPE).perform() + + driver.delete_all_cookies() + +def delete_cookies(self): + driver = self.driver + driver.get('about:preferences#privacy') + clear_button = driver.find_element(By.XPATH, '//*[@id="clearSiteDataButton"]') + time.sleep(2) + driver.execute_script("arguments[0].scrollIntoView();", clear_button) + time.sleep(5) + ActionChains(driver).move_to_element(clear_button).click().perform() + time.sleep(5) + driver.switch_to.window(driver.window_handles[-1]) + time.sleep(2) + webdriver.ActionChains(driver).send_keys(Keys.TAB).perform() + time.sleep(2) + webdriver.ActionChains(driver).send_keys(Keys.TAB).perform() + time.sleep(2) + webdriver.ActionChains(driver).send_keys(Keys.TAB).perform() + time.sleep(2) + webdriver.ActionChains(driver).send_keys(Keys.ENTER).perform() + time.sleep(5) + cookie_alert = driver.switch_to.alert + cookie_alert.accept() + time.sleep(2) + #driver.find_element(By.TAG_NAME, 'body').send_keys(Keys.CONTROL + "w") + # driver.execute_script("arguments[0].click();", clear_button) + #checkboxes = driver.find_elements(By.XPATH, "//input[@type='checkbox']") + #for checkbox in checkboxes: + # if not checkbox.is_selected(): + # checkbox.click() + #clear_button = driver.find_element(By.XPATH, "//button[@data-testid='clear-private-data-button']") + #ActionChains(driver).move_to_element(clear_button).click().perform() + + +@pytest.mark.usefixtures("driver_init") +class BasicTest: + print("Initializing Basic Test") + pass +class Test_HealthCheck(BasicTest): + print("Initializing URL Open Test") + + now = datetime.now() + dt_string = now.strftime("%d%m%Y_%H%M%S") + addon_id = "null" + SUT = OPENCARBON_MARKET + SEARCH_CONTRACT = "2106" + + @pytest.mark.run(order=1) + #@pytest.mark.skip + def test_metamask_login_publicKey(self): + try: + + _t = None + print("Running the Test Open Url") + if _data['MITM'] == 'True': + print("Clearing Cache as flag is True") + c.clearCache() + time.sleep(2) + ######################### Using Proxy Service ########################################## + + Test_HealthCheck.addon_id = self.driver.install_addon(EXTENSION_PATH_FIREFOX, temporary=True) + print(Test_HealthCheck.addon_id) + time.sleep(10) + #self.driver.get(ChromeExtension_Url) + #self.driver.get("about:support") + sleep(10) + print("driver.window_handles : " + str(self.driver.window_handles)) + print("current window handle : " + str(self.driver.current_window_handle)) + self.driver.switch_to.window(window_name=self.driver.window_handles[-1]) + metamask_user_login(self, SECRET_RECOVERY_PHRASE_QA,NEW_PASSWORD_QA) + sleep(10) + + + except AssertionError: + pytest.fail("Test case failed") + except NoSuchElementException: + pytest.fail("Test case failed") + except ElementClickInterceptedException: + pytest.fail("Test case failed") + except IndexError: + pytest.fail("Test case failed") + except NoSuchWindowException: + pytest.fail("Test case failed") + except: + print(traceback.format_exc()) + + @pytest.mark.run(order=2) + #@pytest.mark.skip + def test_connectWallet_metamask_OpenCarbon(self): + try: + + _t = None + print("Running the Test Open Url") + if _data['MITM'] == 'True': + print("Clearing Cache as flag is True") + c.clearCache() + time.sleep(2) + ### + + driver = self.driver + + ##################### + ConnectWallet_metamask(self,Test_HealthCheck.SUT) + # refresh page + driver.refresh() + time.sleep(25) + + except AssertionError: + pytest.fail("Test case failed") + except NoSuchElementException: + pytest.fail("Test case failed") + except IndexError: + pytest.fail("Test case failed") + except NoSuchWindowException: + pytest.fail("Test case failed") + except: + print(traceback.format_exc()) + + + @pytest.mark.skip + def test_Upload_DemoVideo_MVP(self): + try: + + _t = None + print("Running the Test Open Url") + if _data['MITM'] == 'True': + print("Clearing Cache as flag is True") + c.clearCache() + time.sleep(2) + ######################### Using Proxy Service ########################################## + + driver = self.driver + time.sleep(10) + + # driver.find_element_by_xpath("//a[contains(@href, '/all')]").click() + driver.find_element(By.XPATH, '//body').send_keys(Keys.CONTROL + Keys.HOME) + time.sleep(10) + # Saving the Screenshot + driver.save_screenshot(SCREENSHOT_DIRECTORY + "DemoVideoUpload.png") + #driver.find_element_by_xpath("//div[@id='root']/div/div/div/div[3]/div/div[2]/div/div/button[2]").click() + #driver.find_element(By.XPATH,Locator.profile_dropdown_hotdrops).click() + try: + driver.find_element(By.XPATH, Locator.profile_dropdown).click() + except: + print("### Exception ###") + driver.find_element(By.XPATH, Locator.profile_dropdown_hotdrops).click() + else: + print("Nothing went wrong") + #driver.find_element_by_xpath("//span[contains(.,'@suresh111')]").click() + sleep(5) + driver.find_element(By.XPATH,"//li[contains(.,'Upload')]").click() + time.sleep(5) + webdriver.ActionChains(driver).send_keys(Keys.ESCAPE).perform() + #Upload video + time.sleep(5) + driver.find_element("xpath", "//input[@type='file']").send_keys(VIDEO_UPLOAD_FILE) + time.sleep(10) + print("driver.window_handles : " + str(self.driver.window_handles)) + #driver.find_element("xpath", "//button[contains(.,'Select offer')]").click() + offer = driver.find_element("xpath", "//button[contains(.,'Select offer')]") + time.sleep(5) + driver.execute_script("arguments[0].scrollIntoView();", offer) + driver.execute_script("arguments[0].click();", offer) + #driver.find_element("xpath", "//div[1]/div/div/div[3]/div[2]/div/div/div[2]/div/div[2]/div/div").click() + time.sleep(10) + webdriver.ActionChains(driver).send_keys(Keys.TAB).perform() + time.sleep(5) + webdriver.ActionChains(driver).send_keys(Keys.ARROW_DOWN).perform() + time.sleep(5) + #webdriver.ActionChains(driver).send_keys(Keys.ARROW_RIGHT).perform() + #time.sleep(5) + #webdriver.ActionChains(driver).send_keys(Keys.ARROW_RIGHT).perform() + #time.sleep(5) + #webdriver.ActionChains(driver).send_keys(Keys.ARROW_RIGHT).perform() + #time.sleep(5) + webdriver.ActionChains(driver).send_keys(Keys.TAB).perform() + time.sleep(5) + webdriver.ActionChains(driver).send_keys(Keys.ARROW_DOWN).perform() + time.sleep(5) + webdriver.ActionChains(driver).send_keys(Keys.ARROW_DOWN).perform() + time.sleep(5) + webdriver.ActionChains(driver).send_keys(Keys.TAB).perform() + time.sleep(5) + webdriver.ActionChains(driver).send_keys(Keys.ARROW_DOWN).perform() + time.sleep(5) + driver.find_element("xpath", "//button[contains(.,'Unlockable')]").click() + time.sleep(5) + driver.find_element("xpath", "//button[contains(.,'Save')]").click() + time.sleep(5) + driver.switch_to.window(driver.window_handles[-1]) + time.sleep(5) + driver.find_element(By.XPATH, '//body').send_keys(Keys.CONTROL + Keys.HOME) + time.sleep(5) + driver.find_element("xpath", "//button[contains(.,'Upload')]").click() + time.sleep(5) + driver.switch_to.window(driver.window_handles[-1]) + time.sleep(5) + driver.find_element("xpath", "//button[contains(.,'Cloud')]").click() + time.sleep(120) + # refresh page + driver.refresh() + # Saving the Screenshot + driver.save_screenshot(SCREENSHOT_DIRECTORY + "Contract_ConfirmReject.png") + time.sleep(10) + + # Opening the image & storing it in an image object + img = Image.open(SCREENSHOT_DIRECTORY + "Contract_ConfirmReject.png") + time.sleep(5) + + # Size of the image in pixels (size of original image) + # (This is not mandatory) + width, height = img.size + + # Setting the points for cropped image + left = 400 + top = height / 8 + right = 1200 + bottom = 7 * height / 8 + + # Cropped image of above dimension + # (It will not change original image) + im1 = img.crop((left, top, right, bottom)) + # Shows the image in image viewer + # im1.show() + + # Passing the image object to image_to_string() function + # This function will extract the text from the image + text = pytesseract.image_to_string(im1) + + # Modifying text + mod_text = text.rstrip() + without_line_breaks = mod_text.replace("\n", " ") + + # Appending text to log file + test_logs = open(SCREENSHOT_DIRECTORY + "TestExecutionLogs.txt", "a") + test_case_name = os.environ.get('PYTEST_CURRENT_TEST').split(':')[-1].split(' ')[0] + test_logs.write( + Test_HealthCheck.dt_string + "," + test_case_name + "," + without_line_breaks + "\n") + test_logs.close() + # print(text[:-1]) + time.sleep(5) + + # driver.find_element_by_xpath('//button[text()="OK"]').click() + # print("driver.window_handles_final : " + str(self.driver.window_handles)) + # time.sleep(5) + # driver.switch_to.window(driver.window_handles[-1]) + # assert CREATOR_URL == self.driver.current_url + assert (Test_HealthCheck.SUT + "demo") in self.driver.current_url + + + except AssertionError: + pytest.fail("Test case failed") + except NoSuchElementException: + pytest.fail("Test case failed") + except IndexError: + pytest.fail("Test case failed") + except NoSuchWindowException: + pytest.fail("Test case failed") + except ElementNotInteractableException: + pytest.fail("Test case failed") + except ElementClickInterceptedException: + pytest.fail("Test case failed") + except: + print(traceback.format_exc()) + + + @pytest.mark.skip + def test_ModifyTitle_UploadedDemoVideo(self): + try: + + _t = None + print("Running the Test Open Url") + if _data['MITM'] == 'True': + print("Clearing Cache as flag is True") + c.clearCache() + time.sleep(2) + ######################### Using Proxy Service ########################################## + + driver = self.driver + time.sleep(10) + + webdriver.ActionChains(driver).send_keys(Keys.ESCAPE).perform() + try: + driver.find_element(By.XPATH, Locator.profile_dropdown).click() + except: + print("### Exception ###") + driver.find_element(By.XPATH, Locator.profile_dropdown_hotdrops).click() + else: + print("Nothing went wrong") + + # driver.find_element_by_xpath("//span[contains(.,'@suresh111')]").click() + sleep(5) + driver.find_element(By.XPATH, "//li[contains(.,'Upload')]").click() + time.sleep(5) + webdriver.ActionChains(driver).send_keys(Keys.ESCAPE).perform() + time.sleep(5) + + # Changing title of video + # driver.find_element(By.XPATH, "//div[1]/div/div/div[3]/div[2]/div/div/div[2]/div/button[2]/i").click() + + pencil_icon = driver.find_element(By.CSS_SELECTOR, ".fa-pencil") + #pencil_icon = driver.find_element("xpath", '//*[@class="svg-inline--fa fa-pencil "]') + #pencil_icon = driver.find_element("xpath", '//*[@class="fas fa-pencil-alt"]') + time.sleep(2) + driver.execute_script("arguments[0].scrollIntoView();", pencil_icon) + driver.execute_script("arguments[0].click();", pencil_icon) + time.sleep(5) + webdriver.ActionChains(driver).send_keys(Keys.TAB).perform() + time.sleep(2) + webdriver.ActionChains(driver).send_keys(Keys.BACKSPACE).perform() + time.sleep(5) + driver.find_element("xpath", "//input[@placeholder='Select a description']").send_keys("chg-title") + #WebDriverWait(driver, 20).until( + # EC.element_to_be_clickable((By.XPATH, '//*[@class="form-control input-select-custom-style"]'))).send_keys( + # 'chg_title') + #driver.find_element("xpath", '//*[@class="form-control input-select-custom-style"]').send_keys("chg_title") + time.sleep(2) + driver.find_element("xpath", "//button[contains(.,'Update')]").click() + + # driver.find_element("xpath", '//*[@class="fas fa-trash"]').click() + time.sleep(5) + driver.switch_to.window(driver.window_handles[1]) + driver.find_element("xpath", "//button[contains(.,'OK')]").click() + # driver.find_element(By.XPATH, "//div[5]/div/div[6]/button[1]").click() + time.sleep(5) + #webdriver.ActionChains(driver).send_keys(Keys.ESCAPE).perform() + #time.sleep(5) + driver.switch_to.window(driver.window_handles[-1]) + time.sleep(5) + + + + except AssertionError: + pytest.fail("Test case failed") + except NoSuchElementException: + pytest.fail("Test case failed") + except NoSuchWindowException: + pytest.fail("Test case failed") + except ElementNotInteractableException: + pytest.fail("Test case failed") + except: + print(traceback.format_exc()) + + @pytest.mark.skip + def test_StreamDemoVideo_MVP(self): + try: + + _t = None + print("Running the Test Open Url") + if _data['MITM'] == 'True': + print("Clearing Cache as flag is True") + c.clearCache() + time.sleep(2) + ######################### Using Proxy Service ########################################## + + driver = self.driver + time.sleep(10) + + FirstVideo = driver.find_element("xpath", '//img[@class="modal-content-play-image"]') + #FirstVideo = driver.find_element("xpath", + # '//div[1]/div/div/div[3]/div[2]/div/div/div[2]/div/div[1]/img[1]') + driver.execute_script("arguments[0].scrollIntoView();", FirstVideo) + driver.execute_script("arguments[0].click();", FirstVideo) + time.sleep(5) + # driver.find_element("xpath", "//div/div/div/div[3]/div[2]/div/div/div[4]/div[2]/div").click() + # time.sleep(5) + driver.switch_to.window(driver.window_handles[-1]) + time.sleep(5) + + FirstVideo_popup = driver.find_element("xpath", + '//div[5]/div/div/div/div[1]/img[1]') + driver.execute_script("arguments[0].scrollIntoView();", FirstVideo_popup) + driver.execute_script("arguments[0].click();", FirstVideo_popup) + #webdriver.ActionChains(driver).send_keys(Keys.ESCAPE).perform() + #time.sleep(5) + #driver.switch_to.window(driver.window_handles[-1]) + time.sleep(120) + + substring = "0.ts" + # JavaScript command to traffic + r = driver.execute_script("return window.performance.getEntries();") + result = 0 + for res in r: + if result != 1: + # print(res['name']) + fullstring = res['name'] + print("%%%%%%%%%%%%%") + print(fullstring) + if fullstring != None and substring in fullstring: + result = 1 + assert result == 1 + print("Found!") + # Appending text to log file + test_logs = open(SCREENSHOT_DIRECTORY + "TestExecutionLogs.txt", "w") + test_case_name = os.environ.get('PYTEST_CURRENT_TEST').split(':')[-1].split(' ')[0] + test_logs.write( + Test_HealthCheck.dt_string + "," + test_case_name + "," + "Test case Passed" + "," + fullstring + "\n") + test_logs.close() + else: + result = 0 + print("Not found!") + # Appending text to log file + test_logs = open(SCREENSHOT_DIRECTORY + "TestExecutionLogs.txt", "w") + test_case_name = os.environ.get('PYTEST_CURRENT_TEST').split(':')[-1].split(' ')[0] + test_logs.write( + Test_HealthCheck.dt_string + "," + test_case_name + "," + "Test case Failed" + "," + fullstring + "\n") + test_logs.close() + + # assert GREYMAN_URL == self.driver.current_url + webdriver.ActionChains(driver).send_keys(Keys.ESCAPE).perform() + time.sleep(5) + driver.switch_to.window(driver.window_handles[-1]) + assert result == 1 + + except AssertionError: + pytest.fail("Test case failed") + except NoSuchElementException: + pytest.fail("Test case failed") + except NoSuchWindowException: + pytest.fail("Test case failed") + except ElementNotInteractableException: + pytest.fail("Test case failed") + except: + print(traceback.format_exc()) + + + @pytest.mark.skip + def test_Delete_DemoVideo_MVP(self): + try: + + _t = None + print("Running the Test Open Url") + if _data['MITM'] == 'True': + print("Clearing Cache as flag is True") + c.clearCache() + time.sleep(2) + ######################### Using Proxy Service ########################################## + + driver = self.driver + time.sleep(10) + webdriver.ActionChains(driver).send_keys(Keys.ESCAPE).perform() + time.sleep(5) + driver.switch_to.window(driver.window_handles[-1]) + + try: + driver.find_element(By.XPATH, Locator.profile_dropdown).click() + except: + print("### Exception ###") + driver.find_element(By.XPATH, Locator.profile_dropdown_hotdrops).click() + else: + print("Nothing went wrong") + #driver.find_element(By.XPATH, Locator.profile_dropdown_hotdrops).click() + # driver.find_element_by_xpath("//span[contains(.,'@suresh111')]").click() + sleep(5) + driver.find_element(By.XPATH, "//li[contains(.,'Upload')]").click() + time.sleep(5) + webdriver.ActionChains(driver).send_keys(Keys.ESCAPE).perform() + time.sleep(5) + driver.switch_to.window(driver.window_handles[-1]) + time.sleep(5) + #Deletig video + #driver.find_element(By.XPATH, "//div[1]/div/div/div[3]/div[2]/div/div/div[2]/div/button[2]/i").click() + driver.find_element(By.XPATH, '//body').send_keys(Keys.CONTROL + Keys.HOME) + time.sleep(5) + trash_icon = driver.find_element(By.XPATH, '//*[@class="btn btn-danger rounded-rairo "]') + #trash_icon = driver.find_element(By.XPATH, '//*[@class="svg-inline--fa fa-trash "]') + #trash_icon = driver.find_element(By.XPATH, '//*[@id="App"]/div/div[3]/div[2]/div/div/div[2]/div/button[2]/svg/path') + time.sleep(2) + driver.execute_script("arguments[0].scrollIntoView();", trash_icon) + driver.execute_script("arguments[0].click();", trash_icon) + + #driver.find_element("xpath", '//*[@class="fas fa-trash"]').click() + time.sleep(5) + driver.switch_to.window(driver.window_handles[1]) + driver.find_element("xpath", "//button[contains(.,'Yes')]").click() + #driver.find_element(By.XPATH, "//div[5]/div/div[6]/button[1]").click() + time.sleep(5) + webdriver.ActionChains(driver).send_keys(Keys.ESCAPE).perform() + time.sleep(5) + driver.switch_to.window(driver.window_handles[-1]) + time.sleep(5) + # Saving the Screenshot + driver.save_screenshot(SCREENSHOT_DIRECTORY + "Contract_ConfirmReject.png") + time.sleep(10) + + # Opening the image & storing it in an image object + img = Image.open(SCREENSHOT_DIRECTORY + "Contract_ConfirmReject.png") + time.sleep(5) + + # Size of the image in pixels (size of original image) + # (This is not mandatory) + width, height = img.size + + # Setting the points for cropped image + left = 400 + top = height / 8 + right = 1200 + bottom = 7 * height / 8 + + # Cropped image of above dimension + # (It will not change original image) + im1 = img.crop((left, top, right, bottom)) + # Shows the image in image viewer + # im1.show() + + # Passing the image object to image_to_string() function + # This function will extract the text from the image + text = pytesseract.image_to_string(im1) + + # Modifying text + mod_text = text.rstrip() + without_line_breaks = mod_text.replace("\n", " ") + + # Appending text to log file + test_logs = open(SCREENSHOT_DIRECTORY + "TestExecutionLogs.txt", "a") + test_case_name = os.environ.get('PYTEST_CURRENT_TEST').split(':')[-1].split(' ')[0] + test_logs.write( + Test_HealthCheck.dt_string + "," + test_case_name + "," + without_line_breaks + "\n") + test_logs.close() + # print(text[:-1]) + time.sleep(5) + + # driver.find_element_by_xpath('//button[text()="OK"]').click() + # print("driver.window_handles_final : " + str(self.driver.window_handles)) + # time.sleep(5) + # driver.switch_to.window(driver.window_handles[-1]) + # assert CREATOR_URL == self.driver.current_url + assert (Test_HealthCheck.SUT + "demo") in self.driver.current_url + + + except AssertionError: + pytest.fail("Test case failed") + except NoSuchElementException: + pytest.fail("Test case failed") + except ElementNotInteractableException: + pytest.fail("Test case failed") + except NoSuchWindowException: + pytest.fail("Test case failed") + except: + print(traceback.format_exc()) + + @pytest.mark.skip + def test_Upload_Video_MVP(self): + try: + + _t = None + print("Running the Test Open Url") + if _data['MITM'] == 'True': + print("Clearing Cache as flag is True") + c.clearCache() + time.sleep(2) + ######################### Using Proxy Service ########################################## + + driver = self.driver + time.sleep(10) + + # driver.find_element_by_xpath("//a[contains(@href, '/all')]").click() + sleep(10) + driver.find_element(By.XPATH, '//body').send_keys(Keys.CONTROL + Keys.HOME) + #driver.find_element_by_xpath("//div[@id='root']/div/div/div/div[3]/div/div[2]/div/div/button[2]").click() + try: + driver.find_element(By.XPATH, Locator.profile_dropdown_hotdrops).click() + except: + print("### Exception ###") + driver.find_element(By.XPATH, Locator.profile_dropdown).click() + else: + print("Nothing went wrong") + #driver.find_element(By.XPATH,Locator.profile_dropdown_hotdrops).click() + #driver.find_element_by_xpath("//span[contains(.,'@suresh111')]").click() + sleep(5) + driver.find_element(By.XPATH,"//li[contains(.,'Upload')]").click() + time.sleep(5) + webdriver.ActionChains(driver).send_keys(Keys.ESCAPE).perform() + # refresh page + driver.refresh() + time.sleep(25) + #Upload video + time.sleep(5) + driver.find_element("xpath", "//input[@type='file']").send_keys(VIDEO_UPLOAD_FILE) + time.sleep(5) + print("driver.window_handles : " + str(self.driver.window_handles)) + driver.find_element("xpath", "//button[contains(.,'Select offer')]").click() + #driver.find_element("xpath", "//div[1]/div/div/div[3]/div[2]/div/div/div[2]/div/div[2]/div/div").click() + time.sleep(10) + webdriver.ActionChains(driver).send_keys(Keys.TAB).perform() + time.sleep(5) + webdriver.ActionChains(driver).send_keys(Keys.ARROW_DOWN).perform() + time.sleep(5) + webdriver.ActionChains(driver).send_keys(Keys.ARROW_RIGHT).perform() + time.sleep(5) + webdriver.ActionChains(driver).send_keys(Keys.ARROW_RIGHT).perform() + time.sleep(5) + webdriver.ActionChains(driver).send_keys(Keys.ARROW_RIGHT).perform() + time.sleep(5) + webdriver.ActionChains(driver).send_keys(Keys.TAB).perform() + time.sleep(5) + webdriver.ActionChains(driver).send_keys(Keys.ARROW_DOWN).perform() + time.sleep(5) + webdriver.ActionChains(driver).send_keys(Keys.ARROW_DOWN).perform() + time.sleep(5) + webdriver.ActionChains(driver).send_keys(Keys.TAB).perform() + time.sleep(5) + webdriver.ActionChains(driver).send_keys(Keys.ARROW_DOWN).perform() + time.sleep(5) + webdriver.ActionChains(driver).send_keys(Keys.ARROW_DOWN).perform() + time.sleep(5) + driver.find_element("xpath", "//button[contains(.,'Save')]").click() + time.sleep(5) + driver.find_element("xpath", "//button[contains(.,'Upload')]").click() + time.sleep(5) + driver.switch_to.window(driver.window_handles[-1]) + time.sleep(5) + driver.find_element("xpath", "//button[contains(.,'Cloud')]").click() + time.sleep(120) + # refresh page + driver.refresh() + time.sleep(5) + # Saving the Screenshot + driver.save_screenshot(SCREENSHOT_DIRECTORY + "UploadVideo_MVP.png") + time.sleep(10) + + # driver.find_element_by_xpath('//button[text()="OK"]').click() + # print("driver.window_handles_final : " + str(self.driver.window_handles)) + # time.sleep(5) + # driver.switch_to.window(driver.window_handles[-1]) + # assert CREATOR_URL == self.driver.current_url + assert (Test_HealthCheck.SUT + "demo") in self.driver.current_url + + + except AssertionError: + pytest.fail("Test case failed") + except NoSuchElementException: + pytest.fail("Test case failed") + except IndexError: + pytest.fail("Test case failed") + except NoSuchWindowException: + pytest.fail("Test case failed") + except ElementNotInteractableException: + pytest.fail("Test case failed") + except ElementClickInterceptedException: + pytest.fail("Test case failed") + except: + print(traceback.format_exc()) + + + @pytest.mark.skip + def test_StreamVideo_Unlockables(self): + try: + + _t = None + print("Running the Test Open Url") + if _data['MITM'] == 'True': + print("Clearing Cache as flag is True") + c.clearCache() + time.sleep(2) + ######################### Using Proxy Service ########################################## + + driver = self.driver + time.sleep(10) + #driver.find_element("xpath", "//div[1]/div/div/div[1]/div[1]/div/img").click() + driver.find_element(By.XPATH, '//body').send_keys(Keys.CONTROL + Keys.HOME) + #driver.find_element("xpath", "//img[@alt='Rair Tech']").click() + driver.find_element(By.XPATH, "//img[@alt='Rair Tech']").click() + time.sleep(5) + driver.find_element("xpath", "//li[contains(.,'Videos')]").click() + time.sleep(5) + #driver.find_element("xpath", "//div[2]/div/div/div/div/input").send_keys("Fire") + #driver.find_element("xpath", '//*[@class="container-search"]/input').send_keys("1-automation") + driver.find_element("xpath", "//input[@placeholder='Search videos']").send_keys("george") + time.sleep(10) + #FirstVideo = driver.find_element("xpath",'//div[1]/div/div/div[3]/div[2]/div/div[2]/div/div/div/div[3]/div[2]/div[1]/button/div[1]/img[2]') + FirstVideo = driver.find_element("xpath", "//img[@alt='Animated video thumbnail']") + driver.execute_script("arguments[0].scrollIntoView();", FirstVideo) + driver.execute_script("arguments[0].click();", FirstVideo) + time.sleep(10) + # driver.find_element("xpath", "//div/div/div/div[3]/div[2]/div/div/div[4]/div[2]/div").click() + # time.sleep(5) + driver.switch_to.window(driver.window_handles[-1]) + + FirstVideo_popup = driver.find_element("xpath", "//img[@alt='Button play video']") + #FirstVideo_popup = driver.find_element("xpath",'//div[6]/div/div/div[2]/div[1]/img[1]') + driver.execute_script("arguments[0].scrollIntoView();", FirstVideo_popup) + driver.execute_script("arguments[0].click();", FirstVideo_popup) + #webdriver.ActionChains(driver).send_keys(Keys.ESCAPE).perform() + #time.sleep(5) + #driver.switch_to.window(driver.window_handles[-1]) + time.sleep(100) + + substring = "0.ts" + # JavaScript command to traffic + r = driver.execute_script("return window.performance.getEntries();") + result = 0 + for res in r: + if result != 1: + # print(res['name']) + fullstring = res['name'] + print("%%%%%%%%%%%%%") + print(fullstring) + if fullstring != None and substring in fullstring: + result = 1 + assert result == 1 + print("Found!") + # Appending text to log file + test_logs = open(SCREENSHOT_DIRECTORY + "TestExecutionLogs.txt", "w") + test_case_name = os.environ.get('PYTEST_CURRENT_TEST').split(':')[-1].split(' ')[0] + test_logs.write( + Test_HealthCheck.dt_string + "," + test_case_name + "," + "Test case Passed" + "," + fullstring + "\n") + test_logs.close() + else: + result = 0 + print("Not found!") + # Appending text to log file + test_logs = open(SCREENSHOT_DIRECTORY + "TestExecutionLogs.txt", "w") + test_case_name = os.environ.get('PYTEST_CURRENT_TEST').split(':')[-1].split(' ')[0] + test_logs.write( + Test_HealthCheck.dt_string + "," + test_case_name + "," + "Test case Failed" + "," + fullstring + "\n") + test_logs.close() + + # assert GREYMAN_URL == self.driver.current_url + #webdriver.ActionChains(driver).send_keys(Keys.ESCAPE).perform() + #time.sleep(5) + #driver.switch_to.window(driver.window_handles[-1]) + assert result == 1 + + + except AssertionError: + pytest.fail("Test case failed") + except NoSuchElementException: + pytest.fail("Test case failed") + except NoSuchWindowException: + pytest.fail("Test case failed") + except ElementNotInteractableException: + pytest.fail("Test case failed") + except ElementClickInterceptedException: + pytest.fail("Test case failed") + except: + print(traceback.format_exc()) + + + @pytest.mark.skip + def test_StreamVideo_SingleTokenView(self): + try: + + _t = None + print("Running the Test Open Url") + if _data['MITM'] == 'True': + print("Clearing Cache as flag is True") + c.clearCache() + time.sleep(2) + ######################### Using Proxy Service ########################################## + + driver = self.driver + time.sleep(10) + driver.find_element("xpath", "//span[contains(.,'View Collection')]").click() + #driver.find_element("xpath", "//div[6]/div/div/div[2]/div[2]/div[2]/div/div/span").click() + #driver.find_element("xpath", "sc-ftvSup lkCoVD CustomButton_nftDataPageShowMoreText__3S0Ai").click() + time.sleep(5) + driver.switch_to.window(driver.window_handles[-1]) + time.sleep(10) + #driver.find_element("xpath", "//div[1]/div/div/div[3]/div[2]/div/div[3]/div/div[1]/div/div[2]/div[2]/span[2]").click() + #time.sleep(5) + #FirstNFT = driver.find_element("xpath", '//div[1]/div[2]/div/div[3]/div[2]/div/div[4]/div/div[1]/div/div[2]/div[2]/span[2]') + #FirstNFT = driver.find_element("xpath",'//img[@alt="NFT token"]') + #FirstNFT = driver.find_element("xpath", '//img[@alt="NFT token"]') + FirstNFT = driver.find_element("xpath", '//div[@id="App"]/div/div[3]/div[2]/div/div[4]/div/div/div/img') + driver.execute_script("arguments[0].scrollIntoView();", FirstNFT) + time.sleep(5) + ## + a = ActionChains(driver) + m = driver.find_element("xpath", '//div[1]/div[2]/div/div[3]/div[2]/div/div[4]/div/div[1]/div/div/div[1]') + # hover over element + a.move_to_element(m).perform() + time.sleep(10) + # identify sub menu element + SubMenu = driver.find_element("xpath", '//div[1]/div[2]/div/div[3]/div[2]/div/div[4]/div/div[1]/div/div/div[2]/span[2]') + # hover over element and click + time.sleep(10) + a.move_to_element(SubMenu).click().perform() + time.sleep(5) + ### + + #driver.execute_script("arguments[0].click();", FirstNFT) + time.sleep(10) + # driver.find_element("xpath", "//div/div/div/div[3]/div[2]/div/div/div[4]/div[2]/div").click() + # time.sleep(5) + #driver.switch_to.window(driver.window_handles[-1]) + + #FirstVideo_popup = driver.find_element("xpath", '//div[1]/div/div/div[3]/div[2]/main/div[2]/div[4]/div/div[1]/img') + FirstVideo_popup = driver.find_element("xpath", '//div[5]/div/div/img') + driver.execute_script("arguments[0].scrollIntoView();", FirstVideo_popup) + driver.execute_script("arguments[0].click();", FirstVideo_popup) + # webdriver.ActionChains(driver).send_keys(Keys.ESCAPE).perform() + # time.sleep(5) + # driver.switch_to.window(driver.window_handles[-1]) + time.sleep(30) + + substring = "0.ts" + # JavaScript command to traffic + r = driver.execute_script("return window.performance.getEntries();") + result = 0 + for res in r: + if result != 1: + # print(res['name']) + fullstring = res['name'] + print("%%%%%%%%%%%%%") + print(fullstring) + if fullstring != None and substring in fullstring: + result = 1 + assert result == 1 + print("Found!") + # Appending text to log file + test_logs = open(SCREENSHOT_DIRECTORY + "TestExecutionLogs.txt", "w") + test_case_name = os.environ.get('PYTEST_CURRENT_TEST').split(':')[-1].split(' ')[0] + test_logs.write( + Test_HealthCheck.dt_string + "," + test_case_name + "," + "Test case Passed" + "," + fullstring + "\n") + test_logs.close() + else: + result = 0 + print("Not found!") + # Appending text to log file + test_logs = open(SCREENSHOT_DIRECTORY + "TestExecutionLogs.txt", "w") + test_case_name = os.environ.get('PYTEST_CURRENT_TEST').split(':')[-1].split(' ')[0] + test_logs.write( + Test_HealthCheck.dt_string + "," + test_case_name + "," + "Test case Failed" + "," + fullstring + "\n") + test_logs.close() + + # assert GREYMAN_URL == self.driver.current_url + + webdriver.ActionChains(driver).send_keys(Keys.ESCAPE).perform() + time.sleep(5) + driver.switch_to.window(driver.window_handles[-1]) + time.sleep(5) + assert result == 1 + + + except AssertionError: + pytest.fail("Test case failed") + except NoSuchElementException: + pytest.fail("Test case failed") + except NoSuchWindowException: + pytest.fail("Test case failed") + except ElementNotInteractableException: + pytest.fail("Test case failed") + except IndexError: + pytest.fail("Test case failed") + except: + print(traceback.format_exc()) + + @pytest.mark.skip + def test_Delete_Video_MVP(self): + try: + + _t = None + print("Running the Test Open Url") + if _data['MITM'] == 'True': + print("Clearing Cache as flag is True") + c.clearCache() + time.sleep(2) + ######################### Using Proxy Service ########################################## + + driver = self.driver + time.sleep(10) + + #driver.find_element(By.XPATH, Locator.profile_dropdown_hotdrops).click() + try: + driver.find_element(By.XPATH, Locator.profile_dropdown_hotdrops).click() + except: + print("### Exception ###") + driver.find_element(By.XPATH, Locator.profile_dropdown).click() + else: + print("Nothing went wrong") + # driver.find_element_by_xpath("//span[contains(.,'@suresh111')]").click() + sleep(5) + driver.find_element(By.XPATH, "//li[contains(.,'Upload')]").click() + time.sleep(5) + webdriver.ActionChains(driver).send_keys(Keys.ESCAPE).perform() + time.sleep(5) + #Deletig video + #driver.find_element(By.XPATH, "//div[1]/div/div/div[3]/div[2]/div/div/div[2]/div/button[2]/i").click() + + trash_icon = driver.find_element("xpath", '//*[@class="fas fa-trash"]') + time.sleep(2) + driver.execute_script("arguments[0].scrollIntoView();", trash_icon) + driver.execute_script("arguments[0].click();", trash_icon) + + #driver.find_element("xpath", '//*[@class="fas fa-trash"]').click() + time.sleep(5) + driver.switch_to.window(driver.window_handles[1]) + driver.find_element("xpath", "//button[contains(.,'Yes')]").click() + #driver.find_element(By.XPATH, "//div[5]/div/div[6]/button[1]").click() + time.sleep(5) + webdriver.ActionChains(driver).send_keys(Keys.ESCAPE).perform() + time.sleep(5) + driver.switch_to.window(driver.window_handles[-1]) + time.sleep(5) + # Saving the Screenshot + driver.save_screenshot(SCREENSHOT_DIRECTORY + "Contract_ConfirmReject.png") + time.sleep(10) + + # Opening the image & storing it in an image object + img = Image.open(SCREENSHOT_DIRECTORY + "Contract_ConfirmReject.png") + time.sleep(5) + + # Size of the image in pixels (size of original image) + # (This is not mandatory) + width, height = img.size + + # Setting the points for cropped image + left = 400 + top = height / 8 + right = 1200 + bottom = 7 * height / 8 + + # Cropped image of above dimension + # (It will not change original image) + im1 = img.crop((left, top, right, bottom)) + # Shows the image in image viewer + # im1.show() + + # Passing the image object to image_to_string() function + # This function will extract the text from the image + text = pytesseract.image_to_string(im1) + + # Modifying text + mod_text = text.rstrip() + without_line_breaks = mod_text.replace("\n", " ") + + # Appending text to log file + test_logs = open(SCREENSHOT_DIRECTORY + "TestExecutionLogs.txt", "a") + test_case_name = os.environ.get('PYTEST_CURRENT_TEST').split(':')[-1].split(' ')[0] + test_logs.write( + Test_HealthCheck.dt_string + "," + test_case_name + "," + without_line_breaks + "\n") + test_logs.close() + # print(text[:-1]) + time.sleep(5) + + # driver.find_element_by_xpath('//button[text()="OK"]').click() + # print("driver.window_handles_final : " + str(self.driver.window_handles)) + # time.sleep(5) + # driver.switch_to.window(driver.window_handles[-1]) + # assert CREATOR_URL == self.driver.current_url + assert (Test_HealthCheck.SUT + "demo") in self.driver.current_url + + + except AssertionError: + pytest.fail("Test case failed") + except NoSuchElementException: + pytest.fail("Test case failed") + except ElementNotInteractableException: + pytest.fail("Test case failed") + except ElementClickInterceptedException: + pytest.fail("Test case failed") + except NoSuchWindowException: + pytest.fail("Test case failed") + except: + print(traceback.format_exc()) + + + @pytest.mark.skip + def test_MintToken_EasyMint(self): + try: + + _t = None + print("Running the Test Open Url") + if _data['MITM'] == 'True': + print("Clearing Cache as flag is True") + c.clearCache() + time.sleep(2) + ######################### Using Proxy Service ########################################## + + driver = self.driver + time.sleep(10) + #driver.find_element("xpath", "//div[1]/div/div/div[1]/div[1]/div/img").click() + driver.find_element("xpath", "//img[@alt='Rair Tech']").click() + time.sleep(5) + #driver.find_element("xpath", "//li[contains(.,'NFT')]").click() + time.sleep(10) + # refresh page + driver.refresh() + time.sleep(25) + try: + driver.find_element("xpath", "//input[@placeholder='Search']").send_keys(Keys.RETURN) + except: + print("### Exception ###") + driver.find_element("xpath", "//input[@placeholder='Search the rairverse...']").send_keys(Keys.RETURN) + time.sleep(5) + driver.find_element("xpath", "//input[@placeholder='Search the rairverse...']").send_keys(Test_HealthCheck.SEARCH_CONTRACT) + else: + time.sleep(5) + time.sleep(5) + driver.find_element("xpath", "//input[@placeholder='Search']").send_keys(Test_HealthCheck.SEARCH_CONTRACT) + print("Nothing went wrong") + + time.sleep(20) + driver.find_element("xpath", "//div[1]/div/div/div[1]/div[2]/div/div/div/div[1]/div/p").click() + time.sleep(10) + driver.switch_to.window(driver.window_handles[-1]) + time.sleep(5) + #EasyMint = driver.find_element("xpath", "//button[contains(.,'Mint')]") + EasyMint = driver.find_element("xpath", "//div[1]/div/div/div[3]/div[2]/div/div[3]/div/div[2]/div[1]/div/span") + time.sleep(5) + driver.execute_script("arguments[0].scrollIntoView();", EasyMint) + driver.execute_script("arguments[0].click();", EasyMint) + time.sleep(5) + driver.find_element("xpath", "//button[contains(.,'Buy')]").click() + time.sleep(5) + driver.find_element("xpath", "//button[contains(.,'Switch')]").click() + #driver.find_element("xpath", '//button[text()="Switch to Matic(Polygon) Testnet"]').click() + time.sleep(10) + # Switch network + driver.switch_to.window(driver.window_handles[-1]) + time.sleep(15) + try: + driver.find_element("xpath", "//button[contains(.,'Approve')]").click() + except: + print("### Exception ###") + else: + print("Nothing went wrong") + time.sleep(10) + print("driver.window_handles_network : " + str(self.driver.window_handles)) + driver.switch_to.window(driver.window_handles[-1]) + time.sleep(10) + driver.find_element("xpath", "//button[contains(.,'Switch network')]").click() + time.sleep(10) + driver.switch_to.window(driver.window_handles[-1]) + #driver.execute_script("arguments[0].scrollIntoView();", EasyMint) + #driver.execute_script("arguments[0].click();", EasyMint) + #time.sleep(5) + #driver.find_element("xpath", "//button[contains(.,'Buy')]").click() + #time.sleep(5) + driver.find_element("xpath", "//button[contains(.,'Purchase')]").click() + print("Purchase Button clicked") + #driver.find_element("xpath", '//button[text()="Purchase"]').click() + time.sleep(25) + + # Saving the Screenshot + #saveScreenshot(self, "EasyMint_clickPurchase.png") + driver.save_screenshot(SCREENSHOT_DIRECTORY + "EasyMint_clickPurchase.png") + #time.sleep(5) + driver.switch_to.window(driver.window_handles[-1]) + #time.sleep(10) + + + try: + print("driver.window_handles_Purchase_clicked : " + str(self.driver.window_handles)) + time.sleep(10) + token_confirm = driver.find_element("xpath","//button[contains(.,'Reject')]") + driver.execute_script("arguments[0].scrollIntoView();", token_confirm) + time.sleep(10) + token_confirm_enabled = WebDriverWait(driver, 20).until( + EC.element_to_be_clickable((By.XPATH, "//button[contains(.,'Confirm')]"))) + driver.execute_script("arguments[0].click();", token_confirm_enabled) + time.sleep(100) + print("driver.window_handles_token_minted : " + str(self.driver.window_handles)) + driver.switch_to.window(driver.window_handles[-1]) + time.sleep(5) + + mint_status = driver.find_element("xpath", '//*[@id="swal2-title"]').text + print(mint_status) + + # Extracting next token number + mint_message = driver.find_element("xpath", '//*[@id="swal2-html-container"]').text + print(mint_message) + + driver.find_element("xpath", '//button[text()="OK"]').click() + print("driver.window_handles_updated_final : " + str(self.driver.window_handles)) + time.sleep(10) + webdriver.ActionChains(driver).send_keys(Keys.ESCAPE).perform() + # driver.find_element_by_tag_name('body').send_keys(Keys.ESCAPE) + + Test_HealthCheck.redirected_url = self.driver.current_url + redirected_url_split = Test_HealthCheck.redirected_url.split("/") + + if "token" in mint_message: + _token = re.findall(r'\b\d+\b', mint_message) + __token = _token[0] + token = int(__token) + Test_HealthCheck.next_token = token + 1 + Test_HealthCheck.next_token_index = Test_HealthCheck.next_token + 1 + print(Test_HealthCheck.next_token_index) + else: + __token = redirected_url_split[7] + Test_HealthCheck_token = int(__token) + print(Test_HealthCheck_token) + Test_HealthCheck.next_token = Test_HealthCheck_token + 1 + Test_HealthCheck.next_token_index = Test_HealthCheck.next_token + 1 + print(Test_HealthCheck.next_token_index) + print("token# missing in message") + ### + + except NoSuchElementException: + time.sleep(5) + webdriver.ActionChains(driver).send_keys(Keys.ESCAPE).perform() + time.sleep(5) + webdriver.ActionChains(driver).send_keys(Keys.ESCAPE).perform() + except ElementNotInteractableException: + pytest.fail("Test case failed") + except: + print(traceback.format_exc()) + + assert mint_status == "Success" + #webdriver.ActionChains(driver).send_keys(Keys.ESCAPE).perform() + #time.sleep(5) + #driver.switch_to.window(driver.window_handles[-1]) + #assert result == 1 + + + except AssertionError: + pytest.fail("Test case failed") + except NoSuchElementException: + pytest.fail("Test case failed") + except NoSuchWindowException: + pytest.fail("Test case failed") + except ElementNotInteractableException: + pytest.fail("Test case failed") + except IndexError: + pytest.fail("Test case failed") + except UnboundLocalError: + pytest.fail("Test case failed") + except TimeoutException: + pytest.fail("Test case failed") + except ElementClickInterceptedException: + pytest.fail("Test case failed") + except: + print(traceback.format_exc()) + + + @pytest.mark.skip + def test_CreateResaleOffer_SingleTokenView(self): + try: + + _t = None + print("Running the Test Open Url") + if _data['MITM'] == 'True': + print("Clearing Cache as flag is True") + c.clearCache() + time.sleep(2) + ######################### Using Proxy Service ########################################## + + + driver = self.driver + time.sleep(2) + driver.switch_to.window(driver.window_handles[-1]) + time.sleep(2) + resaleOffer_button = driver.find_element("xpath", "//div[1]/div/div/div[3]/div[2]/main/div[3]/div[3]/div[2]/button") + driver.execute_script("arguments[0].scrollIntoView();", resaleOffer_button) + time.sleep(2) + driver.execute_script("arguments[0].click();", resaleOffer_button) + #driver.find_element("xpath", "//div[1]/div/div/div[3]/div[2]/main/div[3]/div[3]/div[2]/button").click() + time.sleep(5) + driver.switch_to.window(driver.window_handles[-1]) + time.sleep(5) + driver.find_element("xpath", "//input[@placeholder='Your price']").send_keys(Keys.RETURN) + time.sleep(2) + driver.find_element("xpath", "//input[@placeholder='Your price']").send_keys("0.002") + time.sleep(2) + driver.find_element("xpath", "//div[@id='swal2-html-container']/div/div[3]/button/span").click() + #driver.find_element("xpath", '//*[@class="nft-item-sell-buton"]').click() + #driver.find_element("xpath", '//button[text()="Sell"]').click() + time.sleep(2) + #driver.find_element("xpath", "//button[contains(.,'Sell')]").click() + #driver.find_element("xpath", "//div[@id='swal2-html-container']/div/div[3]/button/span").click() + time.sleep(4) + driver.switch_to.window(driver.window_handles[-1]) + driver.find_element("xpath", "//button[contains(.,'OK')]").click() + time.sleep(2) + driver.switch_to.window(driver.window_handles[-1]) + time.sleep(2) + #assert result == 1 + + + except AssertionError: + pytest.fail("Test case failed") + except NoSuchElementException: + pytest.fail("Test case failed") + except NoSuchWindowException: + pytest.fail("Test case failed") + except ElementNotInteractableException: + pytest.fail("Test case failed") + except ElementClickInterceptedException: + pytest.fail("Test case failed") + except IndexError: + pytest.fail("Test case failed") + except: + print(traceback.format_exc()) + + + @pytest.mark.skip + def test_AddFavorite(self): + try: + + _t = None + print("Running the Test Open Url") + if _data['MITM'] == 'True': + print("Clearing Cache as flag is True") + c.clearCache() + time.sleep(2) + ######################### Using Proxy Service ########################################## + + driver = self.driver + time.sleep(10) + # driver.find_element("xpath", "//div[1]/div/div/div[1]/div[1]/div/img").click() + driver.find_element("xpath", "//img[@alt='Rair Tech']").click() + time.sleep(5) + # driver.find_element("xpath", "//li[contains(.,'NFT')]").click() + # time.sleep(10) + # refresh page + driver.refresh() + time.sleep(5) + try: + driver.find_element("xpath", "//input[@placeholder='Search']").send_keys(Keys.RETURN) + except: + print("### Exception ###") + driver.find_element("xpath", "//input[@placeholder='Search the rairverse...']").send_keys( + Keys.RETURN) + time.sleep(5) + driver.find_element("xpath", "//input[@placeholder='Search the rairverse...']").send_keys( + Test_HealthCheck.SEARCH_CONTRACT) + else: + time.sleep(5) + time.sleep(5) + driver.find_element("xpath", "//input[@placeholder='Search']").send_keys(Test_HealthCheck.SEARCH_CONTRACT) + print("Nothing went wrong") + + time.sleep(20) + driver.find_element("xpath", "//div[1]/div/div/div[1]/div[2]/div/div/div/div[1]/div/p").click() + time.sleep(10) + driver.switch_to.window(driver.window_handles[-1]) + time.sleep(5) + #print(Test_HealthCheck.next_token_index) + #i = Test_HealthCheck.next_token_index + i = 1 + #driver.execute_script("window.scrollTo(0, document.body.scrollHeight);") + #time.sleep(30) + tile_iterator = "//div[@id='App']/div/div[3]/div[2]/div/div[4]/div/div[" + str(i) + "]/div/img" + # tile_iterator = "//div/div/div/div[3]/div[2]/div/div[3]/div/div[" + str(i) + "]/div/div[2]/div[2]/span[2]" + tile = driver.find_element("xpath", tile_iterator) + time.sleep(5) + driver.execute_script("arguments[0].scrollIntoView();", tile) + time.sleep(5) + + a = ActionChains(driver) + m = driver.find_element("xpath", '//div[1]/div[2]/div/div[3]/div[2]/div/div[4]/div/div[2]/div/div') + # hover over element + a.move_to_element(m).perform() + time.sleep(10) + # identify sub menu element + FirstNFT = driver.find_element("xpath", '//div[1]/div[2]/div/div[3]/div[2]/div/div[4]/div/div[2]/div/div/div[2]/span[2]') + # hover over element and click + time.sleep(10) + a.move_to_element(FirstNFT).click().perform() + time.sleep(5) + ### + time.sleep(5) + favorite_icon = driver.find_element("xpath", "//*[@class='nft-collection-icons-icon']/i") + driver.execute_script("arguments[0].scrollIntoView();", favorite_icon) + driver.execute_script("arguments[0].click();", favorite_icon) + time.sleep(5) + + #assert mint_status == "Success" + # webdriver.ActionChains(driver).send_keys(Keys.ESCAPE).perform() + # time.sleep(5) + # driver.switch_to.window(driver.window_handles[-1]) + # assert result == 1 + + + except AssertionError: + pytest.fail("Test case failed") + except NoSuchElementException: + pytest.fail("Test case failed") + except NoSuchWindowException: + pytest.fail("Test case failed") + except ElementNotInteractableException: + pytest.fail("Test case failed") + except ElementClickInterceptedException: + pytest.fail("Test case failed") + except IndexError: + pytest.fail("Test case failed") + except: + print(traceback.format_exc()) + + @pytest.mark.skip + def test_RemoveFavorite(self): + try: + + _t = None + print("Running the Test Open Url") + if _data['MITM'] == 'True': + print("Clearing Cache as flag is True") + c.clearCache() + time.sleep(2) + ######################### Using Proxy Service ########################################## + + driver = self.driver + time.sleep(10) + + # driver.find_element_by_xpath("//a[contains(@href, '/all')]").click() + sleep(10) + #driver.find_element(By.XPATH, Locator.profile_dropdown_hotdrops).click() + try: + driver.find_element(By.XPATH, Locator.profile_dropdown_hotdrops).click() + except: + print("### Exception ###") + driver.find_element(By.XPATH, Locator.profile_dropdown).click() + else: + print("Nothing went wrong") + sleep(5) + driver.find_element(By.XPATH, "//li[contains(.,'Profile settings')]").click() + time.sleep(5) + driver.switch_to.window(driver.window_handles[-1]) + time.sleep(5) + #driver.find_element("xpath", '//*[@class="profile-input-edit btn"]').click() + #time.sleep(10) + #webdriver.ActionChains(driver).send_keys(Keys.ESCAPE).perform() + time.sleep(2) + driver.find_element("xpath", "//li[contains(.,'Favorited')]").click() + time.sleep(5) + heart = driver.find_element("xpath", '//*[@class="fas fa-heart like-button"]') + #driver.find_element("xpath", "//div[@id='App']/div/div[3]/div[2]/div/div[5]/div/div[2]/div[3]/div/div/div[1]/div/button/i").click() + driver.execute_script("arguments[0].scrollIntoView();", heart) + driver.execute_script("arguments[0].click();", heart) + time.sleep(2) + driver.switch_to.window(driver.window_handles[-1]) + time.sleep(2) + driver.find_element("xpath", "//button[contains(.,'Remove')]").click() + time.sleep(2) + + + + # driver.find_element_by_xpath('//button[text()="OK"]').click() + # print("driver.window_handles_final : " + str(self.driver.window_handles)) + # time.sleep(5) + # driver.switch_to.window(driver.window_handles[-1]) + #assert NEW_DEV_URL + Locator.public_key == self.driver.current_url + # assert (NEW_DEV_URL) in self.driver.current_url + + + except AssertionError: + pytest.fail("Test case failed") + except NoSuchElementException: + pytest.fail("Test case failed") + except NoSuchWindowException: + pytest.fail("Test case failed") + except ElementNotInteractableException: + pytest.fail("Test case failed") + except ElementClickInterceptedException: + pytest.fail("Test case failed") + except: + print(traceback.format_exc()) + + @pytest.mark.skip + def test_MintToken_SingleTokenView(self): + try: + + _t = None + print("Running the Test Open Url") + if _data['MITM'] == 'True': + print("Clearing Cache as flag is True") + c.clearCache() + time.sleep(2) + ######################### Using Proxy Service ########################################## + + + driver = self.driver + time.sleep(10) + #Test_HealthCheck.next_token_index = 111 + #driver.find_element("xpath", "//div[1]/div/div/div[1]/div[1]/div/img").click() + driver.find_element("xpath", "//img[@alt='Rair Tech']").click() + time.sleep(5) + #driver.find_element("xpath", "//li[contains(.,'NFT')]").click() + #time.sleep(10) + # refresh page + driver.refresh() + time.sleep(5) + + try: + driver.find_element("xpath", "//input[@placeholder='Search']").send_keys(Keys.RETURN) + except: + print("### Exception ###") + driver.find_element("xpath", "//input[@placeholder='Search the rairverse...']").send_keys(Keys.RETURN) + time.sleep(5) + driver.find_element("xpath", "//input[@placeholder='Search the rairverse...']").send_keys("10012024") + else: + time.sleep(5) + time.sleep(5) + driver.find_element("xpath", "//input[@placeholder='Search']").send_keys("10012024") + print("Nothing went wrong") + print("#### Because of Bug in Application ####") + time.sleep(15) + driver.find_element("xpath", + "//div[1]/div/div/div[1]/div[2]/div/div/div/div[1]/div/p").click() + time.sleep(5) + driver.switch_to.window(driver.window_handles[-1]) + time.sleep(5) + tile_iterator = "//div[@id='App']/div/div[3]/div[2]/div/div[4]/div/div[1]/div/img" + # tile_iterator = "//div/div/div/div[3]/div[2]/div/div[3]/div/div[" + str(i) + "]/div/div[2]/div[2]/span[2]" + tile = driver.find_element("xpath", tile_iterator) + time.sleep(5) + driver.execute_script("arguments[0].scrollIntoView();", tile) + driver.execute_script("arguments[0].click();", tile) + time.sleep(5) + driver.find_element("xpath", "//img[@alt='Rair Tech']").click() + time.sleep(2) + driver.refresh() + time.sleep(2) + driver.find_element("xpath", "//input[@placeholder='Search']").send_keys(Keys.RETURN) + time.sleep(2) + driver.find_element("xpath", "//input[@placeholder='Search']").send_keys("10012024") + + + time.sleep(20) + driver.find_element("xpath", "//div[1]/div/div/div[1]/div[2]/div/div/div/div[1]/div/p").click() + time.sleep(10) + driver.switch_to.window(driver.window_handles[-1]) + time.sleep(5) + + print(Test_HealthCheck.next_token_index) + i = Test_HealthCheck.next_token_index + driver.execute_script("window.scrollTo(0, document.body.scrollHeight);") + time.sleep(10) + tile_iterator = "//div[@id='App']/div/div[3]/div[2]/div/div[4]/div/div[" + str(i) + "]/div/img" + #tile_iterator = "//div/div/div/div[3]/div[2]/div/div[3]/div/div[" + str(i) + "]/div/div[2]/div[2]/span[2]" + tile = driver.find_element("xpath", tile_iterator) + time.sleep(5) + driver.execute_script("arguments[0].scrollIntoView();", tile) + driver.execute_script("arguments[0].click();", tile) + time.sleep(10) + mint_button = driver.find_element("xpath", "//div[1]/div/div/div[3]/div[2]/main/div[3]/div[2]/div[2]/div[2]/button/span") + mint_button_text = (mint_button).text + #mint_button_text = driver.find_element("xpath", "//div[1]/div/div/div[3]/div[2]/main/div[2]/div[2]/div[2]/div[2]/button/span").text + if "Switch" in mint_button_text: + driver.execute_script("arguments[0].scrollIntoView();", mint_button) + driver.execute_script("arguments[0].click();", mint_button) + #driver.find_element("xpath", "//div[1]/div/div/div[3]/div[2]/main/div[2]/div[2]/div[2]/div[2]/button/span").click() + time.sleep(10) + # Switch network + driver.switch_to.window(driver.window_handles[-1]) + time.sleep(15) + #driver.find_element("xpath", "//button[contains(.,'Approve')]").click() + #time.sleep(10) + #print("driver.window_handles_network : " + str(self.driver.window_handles)) + #driver.switch_to.window(driver.window_handles[-1]) + #time.sleep(10) + driver.find_element("xpath", "//button[contains(.,'Switch network')]").click() + time.sleep(5) + driver.switch_to.window(driver.window_handles[-1]) + #driver.refresh() + else: + print("already on correct network") + time.sleep(5) + driver.execute_script("arguments[0].scrollIntoView();", mint_button) + driver.execute_script("arguments[0].click();", mint_button) + time.sleep(20) + + # Saving the Screenshot + #saveScreenshot(self, "Greyman_clickPurchase.png") + #time.sleep(5) + driver.switch_to.window(driver.window_handles[-1]) + #time.sleep(10) + + + try: + print("driver.window_handles_before_minted_1 : " + str(self.driver.window_handles)) + token_confirm = driver.find_element("xpath","//button[contains(.,'Reject')]") + driver.execute_script("arguments[0].scrollIntoView();", token_confirm) + time.sleep(10) + token_confirm_enabled = WebDriverWait(driver, 30).until( + EC.element_to_be_clickable((By.XPATH, "//button[contains(.,'Confirm')]"))) + driver.execute_script("arguments[0].click();", token_confirm_enabled) + time.sleep(60) + print("driver.window_handles_token_minted : " + str(self.driver.window_handles)) + driver.switch_to.window(driver.window_handles[-1]) + time.sleep(5) + + mint_status = driver.find_element("xpath", '//*[@id="swal2-title"]').text + print(mint_status) + + driver.find_element("xpath", '//button[text()="OK"]').click() + print("driver.window_handles_updated_final : " + str(self.driver.window_handles)) + time.sleep(10) + webdriver.ActionChains(driver).send_keys(Keys.ESCAPE).perform() + # driver.find_element_by_tag_name('body').send_keys(Keys.ESCAPE) + + except NoSuchElementException: + time.sleep(5) + webdriver.ActionChains(driver).send_keys(Keys.ESCAPE).perform() + time.sleep(5) + webdriver.ActionChains(driver).send_keys(Keys.ESCAPE).perform() + except ElementNotInteractableException: + pytest.fail("Test case failed") + except: + print(traceback.format_exc()) + + assert mint_status == "Success" + #webdriver.ActionChains(driver).send_keys(Keys.ESCAPE).perform() + #time.sleep(5) + #driver.switch_to.window(driver.window_handles[-1]) + #assert result == 1 + + + except AssertionError: + pytest.fail("Test case failed") + except NoSuchElementException: + pytest.fail("Test case failed") + except NoSuchWindowException: + pytest.fail("Test case failed") + except ElementNotInteractableException: + pytest.fail("Test case failed") + except ElementClickInterceptedException: + pytest.fail("Test case failed") + except IndexError: + pytest.fail("Test case failed") + except: + print(traceback.format_exc()) + + + @pytest.mark.skip + def test_FilterLabels(self): + try: + + _t = None + print("Running the Test Open Url") + if _data['MITM'] == 'True': + print("Clearing Cache as flag is True") + c.clearCache() + time.sleep(2) + ######################### Using Proxy Service ########################################## + + driver = self.driver + time.sleep(10) + + #driver.find_element("xpath", "//div[1]/div/div/div[1]/div[1]/div/img").click() + driver.find_element("xpath", "//img[@alt='Rair Tech']").click() + time.sleep(5) + + # refresh page + driver.refresh() + time.sleep(10) + + driver.find_element("xpath", '//div[@id="home-page-modal-filter"]/div/div[2]/div/div[2]').click() + driver.find_element("xpath", '//div[@id="home-page-modal-filter"]/div/div/div/div[2]').click() + #filter_labels = driver.find_elements(By.XPATH, "//input") + filter_labels = driver.find_elements(By.XPATH, '//span[@class="dropdown-option-text"]') + print(len(filter_labels)) + result = 1 + k = 0 + for ff in range(len(filter_labels)): + if result == 1: + print(filter_labels[ff].text) + print(Expected_Filter_Labels[k]) + #label = f'Filter_Label_{k}' + if ((filter_labels[ff].text) == Expected_Filter_Labels[k]): + result = 1 + k = k + 1 + else: + result = 0 + assert result == 1 + #pytest.fail("Test case failed") + else: + print("Test case Failed") + + + # Saving the Screenshot + driver.save_screenshot(SCREENSHOT_DIRECTORY + "Filter_Block.png") + time.sleep(5) + + # driver.find_element_by_xpath('//button[text()="OK"]').click() + # print("driver.window_handles_final : " + str(self.driver.window_handles)) + # time.sleep(5) + # driver.switch_to.window(driver.window_handles[-1]) + #assert (NEW_DEV_URL) in self.driver.current_url + + + except AssertionError: + pytest.fail("Test case failed") + except NoSuchElementException: + pytest.fail("Test case failed") + except NoSuchWindowException: + pytest.fail("Test case failed") + except ElementNotInteractableException: + pytest.fail("Test case failed") + except ElementClickInterceptedException: + pytest.fail("Test case failed") + except: + print(traceback.format_exc()) + + + @pytest.mark.skip + def test_Profile(self): + try: + + _t = None + print("Running the Test Open Url") + if _data['MITM'] == 'True': + print("Clearing Cache as flag is True") + c.clearCache() + time.sleep(2) + ######################### Using Proxy Service ########################################## + + driver = self.driver + time.sleep(10) + + # driver.find_element_by_xpath("//a[contains(@href, '/all')]").click() + sleep(10) + driver.find_element(By.XPATH, Locator.profile_dropdown_hotdrops).click() + sleep(5) + driver.find_element(By.XPATH, "//li[contains(.,'Profile settings')]").click() + time.sleep(5) + driver.switch_to.window(driver.window_handles[-1]) + time.sleep(5) + #driver.find_element("xpath", '//*[@class="profile-input-edit btn"]').click() + #driver.find_element("xpath", '//*[@class="profile-input-edit btn hotdrops-bg"]').click() + time.sleep(10) + webdriver.ActionChains(driver).send_keys(Keys.ESCAPE).perform() + + # Saving the Screenshot + driver.save_screenshot(SCREENSHOT_DIRECTORY + "Contract_ConfirmReject.png") + time.sleep(10) + + # driver.find_element_by_xpath('//button[text()="OK"]').click() + # print("driver.window_handles_final : " + str(self.driver.window_handles)) + # time.sleep(5) + # driver.switch_to.window(driver.window_handles[-1]) + assert Test_HealthCheck.SUT + Locator.public_key == self.driver.current_url + #assert (NEW_DEV_URL) in self.driver.current_url + + + except AssertionError: + pytest.fail("Test case failed") + except NoSuchElementException: + pytest.fail("Test case failed") + except NoSuchWindowException: + pytest.fail("Test case failed") + except ElementNotInteractableException: + pytest.fail("Test case failed") + except ElementClickInterceptedException: + pytest.fail("Test case failed") + except: + print(traceback.format_exc()) + + @pytest.mark.skip + def test_Upload_Metadata_csv(self): + try: + + _t = None + print("Running the Test Open Url") + if _data['MITM'] == 'True': + print("Clearing Cache as flag is True") + c.clearCache() + time.sleep(2) + ######################### Using Proxy Service ########################################## + + driver = self.driver + time.sleep(10) + + # driver.find_element_by_xpath("//a[contains(@href, '/all')]").click() + # sleep(10) + # driver.find_element_by_xpath("//div[@id='root']/div/div/div/div[3]/div/div[2]/div/div/button[2]").click() + driver.find_element(By.XPATH, Locator.profile_dropdown).click() + # driver.find_element_by_xpath("//span[contains(.,'@suresh111')]").click() + sleep(5) + driver.find_element(By.XPATH, "//li[contains(.,'Factory')]").click() + time.sleep(2) + webdriver.ActionChains(driver).send_keys(Keys.ESCAPE).perform() + + Contract_list_tab = driver.find_element(By.XPATH, '//a[contains(text(),"My Contracts")]') + driver.execute_script("arguments[0].scrollIntoView();", Contract_list_tab) + driver.execute_script("arguments[0].click();", Contract_list_tab) + # driver.find_element(By.XPATH,'//a[contains(text(),"My Contracts")]').click() + time.sleep(15) + driver.find_element(By.XPATH, '//body').send_keys(Keys.CONTROL + Keys.HOME) + time.sleep(5) + search_contract_box = driver.find_element("xpath", "//input[@placeholder='Search Contracts']") + driver.find_element("xpath", "//input[@placeholder='Search Contracts']").send_keys(Keys.RETURN) + time.sleep(5) + driver.find_element("xpath", "//input[@placeholder='Search Contracts']").send_keys("270420") + time.sleep(10) + webdriver.ActionChains(driver).send_keys(Keys.TAB).perform() + time.sleep(2) + webdriver.ActionChains(driver).send_keys(Keys.ENTER).perform() + # driver.find_element("xpath", "//div[1]/div/div/div[1]/div[2]/div/div/div/div[1]/div/p").click() + time.sleep(10) + driver.find_element(By.XPATH, '//a[contains(text(),"Existing Collections")]').click() + time.sleep(5) + driver.find_element(By.XPATH, '//div[1]/div/div/div[3]/div[2]/div/div[1]/div[2]/div[2]/div/a').click() + time.sleep(5) + driver.find_element(By.XPATH, '//*[@id="Batch Metadata"]').click() + time.sleep(5) + driver.find_element("xpath", "//button[contains(.,'Advanced')]").click() + + # Upload csv + inputs_csv = driver.find_elements("xpath", "//input[@type='file']") + time.sleep(5) + upload_csv_element = driver.find_element("xpath", "//div[@id='App']/div/div[3]/div[2]/div[5]/section/div/img") + driver.execute_script("arguments[0].scrollIntoView();", upload_csv_element) + #driver.execute_script("arguments[0].send_keys(METADATA_CSV_FILE);", upload_csv_element) + #driver.find_element("xpath", "//input[@type='file']").send_keys(METADATA_CSV_FILE) + time.sleep(5) + #print(inputs_csv) + inputs_csv[1].send_keys(METADATA_CSV_FILE) + #driver.find_element("xpath", "//div[@id='App']/div/div[3]/div[2]/div[5]/section/div/img").send_keys(METADATA_CSV_FILE) + time.sleep(30) + #driver.find_element("xpath", "//button[contains(.,'Advanced')]").click() + time.sleep(10) + driver.execute_script("window.scrollTo(0,document.body.scrollHeight)") + print("driver.window_handles : " + str(self.driver.window_handles)) + time.sleep(5) + + assert (NEW_DEV_URL + "creator/contract") in self.driver.current_url + + + except AssertionError: + pytest.fail("Test case failed") + except NoSuchElementException: + pytest.fail("Test case failed") + except ElementNotInteractableException: + pytest.fail("Test case failed") + except ElementClickInterceptedException: + pytest.fail("Test case failed") + except NoSuchWindowException: + pytest.fail("Test case failed") + except IndexError: + pytest.fail("Test case failed") + except: + print(traceback.format_exc()) + + + @pytest.mark.skip + def test_Upload_Video_Factory(self): + try: + + _t = None + print("Running the Test Open Url") + if _data['MITM'] == 'True': + print("Clearing Cache as flag is True") + c.clearCache() + time.sleep(2) + ######################### Using Proxy Service ########################################## + + driver = self.driver + time.sleep(10) + + # driver.find_element_by_xpath("//a[contains(@href, '/all')]").click() + #sleep(10) + # driver.find_element_by_xpath("//div[@id='root']/div/div/div/div[3]/div/div[2]/div/div/button[2]").click() + #driver.find_element(By.XPATH, Locator.profile_dropdown_hotdrops).click() + try: + driver.find_element(By.XPATH, Locator.profile_dropdown_hotdrops).click() + except: + print("### Exception ###") + driver.find_element(By.XPATH, Locator.profile_dropdown).click() + else: + print("Nothing went wrong") + # driver.find_element_by_xpath("//span[contains(.,'@suresh111')]").click() + sleep(5) + driver.find_element(By.XPATH, "//li[contains(.,'Factory')]").click() + time.sleep(2) + webdriver.ActionChains(driver).send_keys(Keys.ESCAPE).perform() + + Contract_list_tab = driver.find_element(By.XPATH, '//a[contains(text(),"My Contracts")]') + driver.execute_script("arguments[0].scrollIntoView();", Contract_list_tab) + driver.execute_script("arguments[0].click();", Contract_list_tab) + #driver.find_element(By.XPATH,'//a[contains(text(),"My Contracts")]').click() + time.sleep(15) + driver.find_element(By.XPATH, '//body').send_keys(Keys.CONTROL + Keys.HOME) + time.sleep(5) + search_contract_box = driver.find_element("xpath", "//input[@placeholder='Contract filter']") + driver.find_element("xpath", "//input[@placeholder='Contract filter']").send_keys(Keys.RETURN) + time.sleep(5) + driver.find_element("xpath", "//input[@placeholder='Contract filter']").send_keys(Test_HealthCheck.SEARCH_CONTRACT) + time.sleep(10) + webdriver.ActionChains(driver).send_keys(Keys.TAB, Keys.TAB, Keys.TAB, Keys.TAB, Keys.TAB, Keys.TAB, Keys.TAB, Keys.TAB, Keys.TAB).perform() + time.sleep(2) + webdriver.ActionChains(driver).send_keys(Keys.ENTER).perform() + #driver.find_element("xpath", "//div[1]/div/div/div[1]/div[2]/div/div/div/div[1]/div/p").click() + time.sleep(10) + driver.find_element(By.XPATH,'//a[contains(text(),"Existing Collections")]').click() + time.sleep(5) + driver.find_element(By.XPATH,'//div[1]/div/div/div[3]/div[2]/div/div[1]/div[2]/div[2]/div/a').click() + time.sleep(8) + driver.find_element(By.XPATH,'//*[@id="Media Files"]').click() + + # Upload video + time.sleep(5) + driver.find_element("xpath", "//input[@type='file']").send_keys(VIDEO_UPLOAD_FILE) + time.sleep(10) + driver.execute_script("window.scrollTo(0,document.body.scrollHeight)") + print("driver.window_handles : " + str(self.driver.window_handles)) + time.sleep(5) + select_contract = driver.find_element("xpath", "//button[contains(.,'Select offer')]") + #select_contract = driver.find_element("xpath", '//*[@class="form-control input-select-custom-style"]') + driver.execute_script("arguments[0].scrollIntoView();", select_contract) + driver.execute_script("arguments[0].click();", select_contract) + #driver.find_element("xpath", "//*[contains(.,'Select a Contract')]").click() + #driver.find_element("xpath", "//div[1]/div/div/div[3]/div[2]/div[2]/div[2]/div/div[2]/div/div").click() + time.sleep(15) + webdriver.ActionChains(driver).send_keys(Keys.TAB).perform() + time.sleep(5) + webdriver.ActionChains(driver).send_keys(Keys.TAB).perform() + time.sleep(5) + webdriver.ActionChains(driver).send_keys(Keys.ARROW_RIGHT).perform() + time.sleep(2) + webdriver.ActionChains(driver).send_keys(Keys.TAB).perform() + time.sleep(5) + webdriver.ActionChains(driver).send_keys(Keys.ARROW_RIGHT).perform() + time.sleep(5) + driver.find_element("xpath", "//button[contains(.,'Save')]").click() + time.sleep(5) + #driver.find_element("xpath", "//div[1]/div/div/div[3]/div[2]/div[2]/div[2]/div/div[1]/div[1]/span/button/i").click() + #webdriver.ActionChains(driver).send_keys(Keys.TAB).perform() + #webdriver.ActionChains(driver).send_keys(Keys.TAB).perform() + #driver.find_element("xpath", "//input[2]").send_keys("Automation") + #webdriver.ActionChains(driver).send_keys(Keys.TAB).perform() + #time.sleep(2) + #webdriver.ActionChains(driver).send_keys(Keys.ARROW_RIGHT).perform() + #time.sleep(2) + #driver.find_element("xpath", "//button[contains(.,'Update')]").click() + driver.execute_script("window.scrollTo(0, document.body.scrollHeight);") + time.sleep(5) + driver.find_element("xpath", "//button[contains(.,'Upload')]").click() + time.sleep(5) + driver.switch_to.window(driver.window_handles[-1]) + time.sleep(5) + driver.find_element("xpath", "//button[contains(.,'Cloud')]").click() + time.sleep(80) + + # Saving the Screenshot + driver.save_screenshot(SCREENSHOT_DIRECTORY + "Contract_ConfirmReject.png") + time.sleep(10) + + # Opening the image & storing it in an image object + img = Image.open(SCREENSHOT_DIRECTORY + "Contract_ConfirmReject.png") + time.sleep(5) + + # Size of the image in pixels (size of original image) + # (This is not mandatory) + width, height = img.size + + # Setting the points for cropped image + left = 400 + top = height / 8 + right = 1200 + bottom = 7 * height / 8 + + # Cropped image of above dimension + # (It will not change original image) + im1 = img.crop((left, top, right, bottom)) + # Shows the image in image viewer + # im1.show() + + # Passing the image object to image_to_string() function + # This function will extract the text from the image + text = pytesseract.image_to_string(im1) + + # Modifying text + mod_text = text.rstrip() + without_line_breaks = mod_text.replace("\n", " ") + + # Appending text to log file + test_logs = open(SCREENSHOT_DIRECTORY + "TestExecutionLogs.txt", "a") + test_case_name = os.environ.get('PYTEST_CURRENT_TEST').split(':')[-1].split(' ')[0] + test_logs.write( + Test_HealthCheck.dt_string + "," + test_case_name + "," + without_line_breaks + "\n") + test_logs.close() + # print(text[:-1]) + time.sleep(5) + + # driver.find_element_by_xpath('//button[text()="OK"]').click() + # print("driver.window_handles_final : " + str(self.driver.window_handles)) + # time.sleep(5) + # driver.switch_to.window(driver.window_handles[-1]) + # assert CREATOR_URL == self.driver.current_url + assert (Test_HealthCheck.SUT + "creator/contract") in self.driver.current_url + + + except AssertionError: + pytest.fail("Test case failed") + except NoSuchElementException: + pytest.fail("Test case failed") + except ElementNotInteractableException: + pytest.fail("Test case failed") + except ElementClickInterceptedException: + pytest.fail("Test case failed") + except NoSuchWindowException: + pytest.fail("Test case failed") + except IndexError: + pytest.fail("Test case failed") + except: + print(traceback.format_exc()) + + @pytest.mark.skip + def test_Delete_Video_Factory(self): + try: + + _t = None + print("Running the Test Open Url") + if _data['MITM'] == 'True': + print("Clearing Cache as flag is True") + c.clearCache() + time.sleep(2) + ######################### Using Proxy Service ########################################## + + driver = self.driver + time.sleep(10) + + #Deletig video + trash_icon = driver.find_element("xpath", '//*[@class="fas fa-trash"]') + time.sleep(2) + driver.execute_script("arguments[0].scrollIntoView();", trash_icon) + driver.execute_script("arguments[0].click();", trash_icon) + + #driver.find_element(By.XPATH, "//div[@id='App']/div/div[3]/div[2]/div[2]/div[2]/div/button[2]/i").click() + #driver.find_element("xpath", '//*[@class="btn btn-danger rounded-rairo"]').click() + time.sleep(5) + driver.switch_to.window(driver.window_handles[1]) + driver.find_element("xpath", "//button[contains(.,'Yes')]").click() + #driver.find_element(By.XPATH, "//div[5]/div/div[6]/button[1]").click() + time.sleep(5) + webdriver.ActionChains(driver).send_keys(Keys.ESCAPE).perform() + time.sleep(5) + driver.switch_to.window(driver.window_handles[-1]) + time.sleep(5) + + assert (Test_HealthCheck.SUT + "creator/contract") in self.driver.current_url + + except AssertionError: + pytest.fail("Test case failed") + except NoSuchElementException: + pytest.fail("Test case failed") + except ElementNotInteractableException: + pytest.fail("Test case failed") + except IndexError: + pytest.fail("Test case failed") + except NoSuchWindowException: + pytest.fail("Test case failed") + except: + print(traceback.format_exc()) + + + @pytest.mark.skip + def test_Upload_DemoVideo_Factory(self): + try: + + _t = None + print("Running the Test Open Url") + if _data['MITM'] == 'True': + print("Clearing Cache as flag is True") + c.clearCache() + time.sleep(2) + ######################### Using Proxy Service ########################################## + + driver = self.driver + time.sleep(10) + + # driver.find_element_by_xpath("//a[contains(@href, '/all')]").click() + #sleep(10) + # driver.find_element_by_xpath("//div[@id='root']/div/div/div/div[3]/div/div[2]/div/div/button[2]").click() + #driver.find_element(By.XPATH, Locator.profile_dropdown_hotdrops).click() + try: + driver.find_element(By.XPATH, Locator.profile_dropdown_hotdrops).click() + except: + print("### Exception ###") + driver.find_element(By.XPATH, Locator.profile_dropdown).click() + else: + print("Nothing went wrong") + # driver.find_element_by_xpath("//span[contains(.,'@suresh111')]").click() + sleep(5) + driver.find_element(By.XPATH, "//li[contains(.,'Factory')]").click() + time.sleep(2) + webdriver.ActionChains(driver).send_keys(Keys.ESCAPE).perform() + + Contract_list_tab = driver.find_element(By.XPATH, '//a[contains(text(),"My Contracts")]') + driver.execute_script("arguments[0].scrollIntoView();", Contract_list_tab) + driver.execute_script("arguments[0].click();", Contract_list_tab) + #driver.find_element(By.XPATH,'//a[contains(text(),"My Contracts")]').click() + time.sleep(15) + driver.find_element(By.XPATH, '//body').send_keys(Keys.CONTROL + Keys.HOME) + time.sleep(5) + search_contract_box = driver.find_element("xpath", "//input[@placeholder='Contract filter']") + driver.find_element("xpath", "//input[@placeholder='Contract filter']").send_keys(Keys.RETURN) + time.sleep(5) + driver.find_element("xpath", "//input[@placeholder='Contract filter']").send_keys(Test_HealthCheck.SEARCH_CONTRACT) + time.sleep(10) + webdriver.ActionChains(driver).send_keys(Keys.TAB, Keys.TAB, Keys.TAB, Keys.TAB, Keys.TAB, Keys.TAB, Keys.TAB, Keys.TAB, Keys.TAB).perform() + time.sleep(2) + webdriver.ActionChains(driver).send_keys(Keys.ENTER).perform() + #driver.find_element("xpath", "//div[1]/div/div/div[1]/div[2]/div/div/div/div[1]/div/p").click() + time.sleep(10) + driver.find_element(By.XPATH,'//a[contains(text(),"Existing Collections")]').click() + time.sleep(5) + driver.find_element(By.XPATH,'//div[1]/div/div/div[3]/div[2]/div/div[1]/div[2]/div[2]/div/a').click() + time.sleep(8) + driver.find_element(By.XPATH,'//*[@id="Media Files"]').click() + + # Upload video + time.sleep(5) + driver.find_element("xpath", "//input[@type='file']").send_keys(VIDEO_UPLOAD_FILE) + time.sleep(10) + driver.execute_script("window.scrollTo(0,document.body.scrollHeight)") + print("driver.window_handles : " + str(self.driver.window_handles)) + time.sleep(5) + select_contract = driver.find_element("xpath", "//button[contains(.,'Select offer')]") + #select_contract = driver.find_element("xpath", '//*[@class="form-control input-select-custom-style"]') + driver.execute_script("arguments[0].scrollIntoView();", select_contract) + driver.execute_script("arguments[0].click();", select_contract) + #driver.find_element("xpath", "//*[contains(.,'Select a Contract')]").click() + #driver.find_element("xpath", "//div[1]/div/div/div[3]/div[2]/div[2]/div[2]/div/div[2]/div/div").click() + time.sleep(15) + webdriver.ActionChains(driver).send_keys(Keys.TAB).perform() + time.sleep(5) + webdriver.ActionChains(driver).send_keys(Keys.TAB).perform() + time.sleep(5) + webdriver.ActionChains(driver).send_keys(Keys.ARROW_RIGHT).perform() + time.sleep(5) + webdriver.ActionChains(driver).send_keys(Keys.TAB).perform() + time.sleep(5) + webdriver.ActionChains(driver).send_keys(Keys.ARROW_RIGHT).perform() + time.sleep(5) + driver.find_element("xpath", "//button[contains(.,'Unlockable')]").click() + time.sleep(5) + driver.find_element("xpath", "//button[contains(.,'Save')]").click() + time.sleep(5) + #driver.find_element("xpath", "//div[1]/div/div/div[3]/div[2]/div[2]/div[2]/div/div[1]/div[1]/span/button/i").click() + #webdriver.ActionChains(driver).send_keys(Keys.TAB).perform() + #webdriver.ActionChains(driver).send_keys(Keys.TAB).perform() + #driver.find_element("xpath", "//input[2]").send_keys("Automation") + #webdriver.ActionChains(driver).send_keys(Keys.TAB).perform() + #time.sleep(2) + #webdriver.ActionChains(driver).send_keys(Keys.ARROW_RIGHT).perform() + #time.sleep(2) + #driver.find_element("xpath", "//button[contains(.,'Update')]").click() + driver.execute_script("window.scrollTo(0, document.body.scrollHeight);") + time.sleep(5) + driver.find_element("xpath", "//button[contains(.,'Upload')]").click() + time.sleep(5) + driver.switch_to.window(driver.window_handles[-1]) + time.sleep(5) + driver.find_element("xpath", "//button[contains(.,'Cloud')]").click() + time.sleep(80) + + # Saving the Screenshot + driver.save_screenshot(SCREENSHOT_DIRECTORY + "Contract_ConfirmReject.png") + time.sleep(10) + + # Opening the image & storing it in an image object + img = Image.open(SCREENSHOT_DIRECTORY + "Contract_ConfirmReject.png") + time.sleep(5) + + # Size of the image in pixels (size of original image) + # (This is not mandatory) + width, height = img.size + + # Setting the points for cropped image + left = 400 + top = height / 8 + right = 1200 + bottom = 7 * height / 8 + + # Cropped image of above dimension + # (It will not change original image) + im1 = img.crop((left, top, right, bottom)) + # Shows the image in image viewer + # im1.show() + + # Passing the image object to image_to_string() function + # This function will extract the text from the image + text = pytesseract.image_to_string(im1) + + # Modifying text + mod_text = text.rstrip() + without_line_breaks = mod_text.replace("\n", " ") + + # Appending text to log file + test_logs = open(SCREENSHOT_DIRECTORY + "TestExecutionLogs.txt", "a") + test_case_name = os.environ.get('PYTEST_CURRENT_TEST').split(':')[-1].split(' ')[0] + test_logs.write( + Test_HealthCheck.dt_string + "," + test_case_name + "," + without_line_breaks + "\n") + test_logs.close() + # print(text[:-1]) + time.sleep(5) + + # driver.find_element_by_xpath('//button[text()="OK"]').click() + # print("driver.window_handles_final : " + str(self.driver.window_handles)) + # time.sleep(5) + # driver.switch_to.window(driver.window_handles[-1]) + # assert CREATOR_URL == self.driver.current_url + assert (Test_HealthCheck.SUT + "creator/contract") in self.driver.current_url + + + except AssertionError: + pytest.fail("Test case failed") + except NoSuchElementException: + pytest.fail("Test case failed") + except ElementNotInteractableException: + pytest.fail("Test case failed") + except ElementClickInterceptedException: + pytest.fail("Test case failed") + except NoSuchWindowException: + pytest.fail("Test case failed") + except IndexError: + pytest.fail("Test case failed") + except: + print(traceback.format_exc()) + + @pytest.mark.skip + def test_Delete_DemoVideo_Factory(self): + try: + + _t = None + print("Running the Test Open Url") + if _data['MITM'] == 'True': + print("Clearing Cache as flag is True") + c.clearCache() + time.sleep(2) + ######################### Using Proxy Service ########################################## + + driver = self.driver + time.sleep(10) + + #Deletig video + trash_icon = driver.find_element("xpath", '//*[@class="fas fa-trash"]') + time.sleep(2) + driver.execute_script("arguments[0].scrollIntoView();", trash_icon) + driver.execute_script("arguments[0].click();", trash_icon) + + #driver.find_element(By.XPATH, "//div[@id='App']/div/div[3]/div[2]/div[2]/div[2]/div/button[2]/i").click() + #driver.find_element("xpath", '//*[@class="btn btn-danger rounded-rairo"]').click() + time.sleep(5) + driver.switch_to.window(driver.window_handles[1]) + driver.find_element("xpath", "//button[contains(.,'Yes')]").click() + #driver.find_element(By.XPATH, "//div[5]/div/div[6]/button[1]").click() + time.sleep(5) + webdriver.ActionChains(driver).send_keys(Keys.ESCAPE).perform() + time.sleep(5) + driver.switch_to.window(driver.window_handles[-1]) + time.sleep(5) + + assert (Test_HealthCheck.SUT + "creator/contract") in self.driver.current_url + + + except AssertionError: + pytest.fail("Test case failed") + except NoSuchElementException: + pytest.fail("Test case failed") + except ElementNotInteractableException: + pytest.fail("Test case failed") + except IndexError: + pytest.fail("Test case failed") + except NoSuchWindowException: + pytest.fail("Test case failed") + except: + print(traceback.format_exc()) + + + #@pytest.mark.skip + def test_Logout_metamask_OpenCarbon(self): + try: + + _t = None + print("Running the Test Open Url") + if _data['MITM'] == 'True': + print("Clearing Cache as flag is True") + c.clearCache() + time.sleep(2) + ######################### Using Proxy Service ########################################## + + driver = self.driver + Logout_hotdrops(self) + #driver.delete_all_cookies() + #delete_cookies(self) + + # assert CREATOR_URL == self.driver.current_url + #assert (NEW_DEV_URL) in self.driver.current_url + + + except AssertionError: + pytest.fail("Test case failed") + except NoSuchElementException: + pytest.fail("Test case failed") + except NoAlertPresentException: + pytest.fail("Test case failed") + except ElementNotInteractableException: + pytest.fail("Test case failed") + except ElementClickInterceptedException: + pytest.fail("Test case failed") + except NoSuchWindowException: + pytest.fail("Test case failed") + except: + print(traceback.format_exc()) + + #@pytest.mark.skip + def test_connectWallet_metamask_rairprotocol(self): + try: + + _t = None + print("Running the Test Open Url") + if _data['MITM'] == 'True': + print("Clearing Cache as flag is True") + c.clearCache() + time.sleep(2) + ######################### Using Proxy Service ########################################## + + driver = self.driver + + ##################### + + ConnectWallet_metamask(self, RAIRPROTOCOL) + + except AssertionError: + pytest.fail("Test case failed") + except NoSuchElementException: + pytest.fail("Test case failed") + except WebDriverException: + pytest.fail("Test case failed") + except IndexError: + pytest.fail("Test case failed") + except NoSuchWindowException: + pytest.fail("Test case failed") + except: + print(traceback.format_exc()) + + #@pytest.mark.skip + def test_Logout_metamask_rairprotocol(self): + try: + + _t = None + print("Running the Test Open Url") + if _data['MITM'] == 'True': + print("Clearing Cache as flag is True") + c.clearCache() + time.sleep(2) + ######################### Using Proxy Service ########################################## + + Logout_hotdrops(self) + #delete_cookies(self) + + # assert CREATOR_URL == self.driver.current_url + #assert (HOTDROPS_PROD_URL) in self.driver.current_url + + + except AssertionError: + pytest.fail("Test case failed") + except NoSuchElementException: + pytest.fail("Test case failed") + except ElementNotInteractableException: + pytest.fail("Test case failed") + except NoSuchWindowException: + pytest.fail("Test case failed") + except: + print(traceback.format_exc()) + + @pytest.mark.skip + def test_connectWallet_metamask_rairlicense(self): + try: + + _t = None + print("Running the Test Open Url") + if _data['MITM'] == 'True': + print("Clearing Cache as flag is True") + c.clearCache() + time.sleep(2) + ######################### Using Proxy Service ########################################## + + driver = self.driver + + ##################### + + ConnectWallet_metamask(self, RAIRLICENSE) + + except AssertionError: + pytest.fail("Test case failed") + except NoSuchElementException: + pytest.fail("Test case failed") + except IndexError: + pytest.fail("Test case failed") + except NoSuchWindowException: + pytest.fail("Test case failed") + except WebDriverException: + pytest.fail("Test case failed") + except: + print(traceback.format_exc()) + + @pytest.mark.skip + def test_Logout_metamask_rairlicense(self): + try: + + _t = None + print("Running the Test Open Url") + if _data['MITM'] == 'True': + print("Clearing Cache as flag is True") + c.clearCache() + time.sleep(2) + ######################### Using Proxy Service ########################################## + driver = self.driver + Logout(self) + #delete_cookies(self) + + # assert CREATOR_URL == self.driver.current_url + #assert (BETA_URL) in self.driver.current_url + + + except AssertionError: + pytest.fail("Test case failed") + except NoSuchElementException: + pytest.fail("Test case failed") + except ElementNotInteractableException: + pytest.fail("Test case failed") + except NoSuchWindowException: + pytest.fail("Test case failed") + except: + print(traceback.format_exc()) + + + @pytest.mark.skip + def test_metamask_switchAccount(self): + try: + + _t = None + print("Running the Test Open Url") + if _data['MITM'] == 'True': + print("Clearing Cache as flag is True") + c.clearCache() + time.sleep(2) + ######################### Using Proxy Service ########################################## + + driver = self.driver + print(Test_HealthCheck.addon_id) + #uninstall metamask + self.driver.uninstall_addon(Test_HealthCheck.addon_id) + time.sleep(5) + self.driver.switch_to.window(window_name=self.driver.window_handles[-1]) + time.sleep(30) + driver.close() + self.driver.install_addon(EXTENSION_PATH_FIREFOX, temporary=True) + time.sleep(2) + self.driver.switch_to.window(window_name=self.driver.window_handles[-1]) + time.sleep(5) + + metamask_user_login(self, SECRET_RECOVERY_PHRASE_QA, NEW_PASSWORD_QA) + time.sleep(5) + + + except AssertionError: + pytest.fail("Test case failed") + except NoSuchElementException: + pytest.fail("Test case failed") + except IndexError: + pytest.fail("Test case failed") + except NoSuchWindowException: + pytest.fail("Test case failed") + except: + print(traceback.format_exc()) + + @pytest.mark.skip + def test_connectWallet_metamask_account2_newdev(self): + try: + + _t = None + print("Running the Test Open Url") + if _data['MITM'] == 'True': + print("Clearing Cache as flag is True") + c.clearCache() + time.sleep(2) + ### + + driver = self.driver + + ##################### + ConnectWallet_metamask(self,Test_HealthCheck.SUT) + + except AssertionError: + pytest.fail("Test case failed") + except NoSuchElementException: + pytest.fail("Test case failed") + except IndexError: + pytest.fail("Test case failed") + except NoSuchWindowException: + pytest.fail("Test case failed") + except: + print(traceback.format_exc()) + + @pytest.mark.skip + def test_MintResaleToken_SingleTokenView(self): + try: + + _t = None + print("Running the Test Open Url") + if _data['MITM'] == 'True': + print("Clearing Cache as flag is True") + c.clearCache() + time.sleep(2) + ######################### Using Proxy Service ########################################## + + + driver = self.driver + #Test_HealthCheck.redirected_url= "http://35.225.69.217:8088/tokens/0x13881/0x51d945384e12390d94a051f0395944fda4ffe714/0/103" + #time.sleep(10) + self.driver.get(Test_HealthCheck.redirected_url) + time.sleep(10) + switch_network_button = driver.find_element("xpath", "//*[@id='nft-data-page-wrapper']/div[3]/div[3]/div[2]/div[2]/button") + driver.execute_script("arguments[0].scrollIntoView();", switch_network_button) + driver.execute_script("arguments[0].click();", switch_network_button) + time.sleep(10) + # Switch network + driver.switch_to.window(driver.window_handles[-1]) + time.sleep(15) + driver.find_element("xpath", "//button[contains(.,'Approve')]").click() + time.sleep(10) + print("driver.window_handles_network : " + str(self.driver.window_handles)) + driver.switch_to.window(driver.window_handles[-1]) + time.sleep(10) + driver.find_element("xpath", "//button[contains(.,'Switch network')]").click() + time.sleep(10) + driver.switch_to.window(driver.window_handles[-1]) + time.sleep(10) + buy_resale_button = driver.find_element("xpath", "//*[@id='nft-data-page-wrapper']/div[3]/div[3]/div[2]/div[2]/button") + driver.execute_script("arguments[0].scrollIntoView();", buy_resale_button) + driver.execute_script("arguments[0].click();", buy_resale_button) + time.sleep(5) + driver.switch_to.window(driver.window_handles[-1]) + driver.find_element("xpath", "//button[contains(.,'OK')]").click() + time.sleep(20) + + driver.switch_to.window(driver.window_handles[-1]) + print("driver.window_handles_before_minted_1 : " + str(self.driver.window_handles)) + token_confirm = driver.find_element("xpath", "//button[contains(.,'Reject')]") + driver.execute_script("arguments[0].scrollIntoView();", token_confirm) + time.sleep(10) + token_confirm_enabled = WebDriverWait(driver, 20).until( + EC.element_to_be_clickable((By.XPATH, "//button[contains(.,'Confirm')]"))) + driver.execute_script("arguments[0].click();", token_confirm_enabled) + time.sleep(100) + print("driver.window_handles_token_minted : " + str(self.driver.window_handles)) + driver.switch_to.window(driver.window_handles[-1]) + time.sleep(5) + + mint_status = driver.find_element("xpath", '//*[@id="swal2-title"]').text + print(mint_status) + + #mint_message = driver.find_element("xpath", '//*[@id="swal2-html-container"]').text + #print(mint_message) + time.sleep(2) + + driver.find_element("xpath", '//button[text()="OK"]').click() + print("driver.window_handles_updated_final : " + str(self.driver.window_handles)) + time.sleep(5) + driver.switch_to.window(driver.window_handles[-1]) + time.sleep(5) + + assert mint_status == "Success" + + + except AssertionError: + pytest.fail("Test case failed") + except NoSuchElementException: + pytest.fail("Test case failed") + except NoSuchWindowException: + pytest.fail("Test case failed") + except ElementNotInteractableException: + pytest.fail("Test case failed") + except ElementClickInterceptedException: + pytest.fail("Test case failed") + except IndexError: + pytest.fail("Test case failed") + except: + print(traceback.format_exc()) + + + @pytest.mark.skip + def test_Logout_account2(self): + try: + + _t = None + print("Running the Test Open Url") + if _data['MITM'] == 'True': + print("Clearing Cache as flag is True") + c.clearCache() + time.sleep(2) + ######################### Using Proxy Service ########################################## + + driver = self.driver + Logout_hotdrops(self) + delete_cookies(self) + + driver.delete_all_cookies() + #assert (NEW_DEV_URL) in self.driver.current_url + + + except AssertionError: + pytest.fail("Test case failed") + except NoSuchElementException: + pytest.fail("Test case failed") + except ElementNotInteractableException: + pytest.fail("Test case failed") + except NoSuchWindowException: + pytest.fail("Test case failed") + except: + print(traceback.format_exc()) + + @pytest.mark.skip + def test_ConnectWallet_Google_Hotdrops(self): + try: + + _t = None + print("Running the Test Open Url") + if _data['MITM'] == 'True': + print("Clearing Cache as flag is True") + c.clearCache() + time.sleep(2) + ######################### Using Proxy Service ########################################## + + self.driver.get(HOTDROPS_PROD_URL) + self.driver.find_element(By.TAG_NAME, 'body').send_keys(Keys.CONTROL + "R") + print(self.driver.title) + driver = self.driver + driver.implicitly_wait(50) + driver.find_element("xpath", Locator.connect_wallet).click() + time.sleep(10) + driver.switch_to.window(driver.window_handles[-1]) + driver.find_element("xpath", "//button[contains(.,'Google')]").click() + time.sleep(5) + driver.switch_to.window(driver.window_handles[-1]) + print("driver.window_handles : " + str(self.driver.window_handles)) + time.sleep(15) + driver.find_element("xpath", '//*[@id="identifierId"]').send_keys("jesiccanababan@gmail.com") + time.sleep(5) + driver.find_element("xpath", "//button[contains(.,'Next')]").click() + time.sleep(30) + driver.switch_to.window(driver.window_handles[-1]) + driver.find_element("xpath", '//*[@class="whsOnd zHQkBf"]').send_keys("OnPath321@") + time.sleep(5) + driver.find_element("xpath", "//button[contains(.,'Next')]").click() + time.sleep(30) + print("driver.window_handles_updated : " + str(self.driver.window_handles)) + driver.switch_to.window(driver.window_handles[-1]) + time.sleep(10) + + + except AssertionError: + pytest.fail("Test case failed") + except NoSuchElementException: + pytest.fail("Test case failed") + except NoSuchWindowException: + pytest.fail("Test case failed") + except ElementNotInteractableException: + pytest.fail("Test case failed") + except IndexError: + pytest.fail("Test case failed") + except: + print(traceback.format_exc()) + + + @pytest.mark.skip + def test_connectWallet_metamask_RairTech(self): + try: + + _t = None + print("Running the Test Open Url") + if _data['MITM'] == 'True': + print("Clearing Cache as flag is True") + c.clearCache() + time.sleep(2) + ######################### Using Proxy Service ########################################## + + self.driver.get(ABOUT_PAGE_URL) + self.driver.find_element(By.TAG_NAME, 'body').send_keys(Keys.CONTROL + "R") + print(self.driver.title) + driver = self.driver + driver.implicitly_wait(50) + driver.find_element("xpath", Locator.connect_wallet).click() + time.sleep(10) + driver.switch_to.window(driver.window_handles[-1]) + print("driver.window_handles : " + str(self.driver.window_handles)) + driver.find_element("xpath", "//button[contains(.,'Next')]").click() + time.sleep(10) + driver.find_element("xpath", "//button[contains(.,'Connect')]").click() + time.sleep(20) + print("driver.window_handles_updated : " + str(self.driver.window_handles)) + print("Metamask_window_handle : " + str(self.driver.window_handles[2])) + time.sleep(10) + driver.switch_to.window(driver.window_handles[-1]) + time.sleep(5) + + # Challenge Block + # driver.find_element("xpath", "//div[1]/div/div[2]/div/div[3]/div[1]/i").click() + driver.find_element("xpath", '//*[@class="fa fa-arrow-down"]').click() + time.sleep(5) + driver.find_element("xpath", "//button[contains(.,'Sign')]").click() + time.sleep(15) + print("driver.window_handles_updated : " + str(self.driver.window_handles)) + # driver.switch_to.window(driver.window_handles[2]) + time.sleep(5) + driver.switch_to.window(driver.window_handles[-1]) + time.sleep(5) + assert ABOUT_PAGE_URL + "/" == self.driver.current_url + + + except AssertionError: + pytest.fail("Test case failed") + except NoSuchElementException: + pytest.fail("Test case failed") + except NoSuchWindowException: + pytest.fail("Test case failed") + except ElementNotInteractableException: + pytest.fail("Test case failed") + except IndexError: + pytest.fail("Test case failed") + except: + print(traceback.format_exc()) + + + @pytest.mark.skip + def test_StreamVideo_RairTech(self): + try: + + _t = None + print("Running the Test Open Url") + if _data['MITM'] == 'True': + print("Clearing Cache as flag is True") + c.clearCache() + time.sleep(2) + ######################### Using Proxy Service ########################################## + + self.driver.get(ABOUT_PAGE_URL) + self.driver.find_element(By.TAG_NAME, 'body').send_keys(Keys.CONTROL + "R") + print(self.driver.title) + driver = self.driver + driver.implicitly_wait(50) + driver.find_element("xpath", Locator.connect_wallet).click() + time.sleep(10) + driver.switch_to.window(driver.window_handles[-1]) + print("driver.window_handles : " + str(self.driver.window_handles)) + driver.find_element("xpath", "//button[contains(.,'Next')]").click() + time.sleep(10) + driver.find_element("xpath", "//button[contains(.,'Connect')]").click() + time.sleep(20) + print("driver.window_handles_updated : " + str(self.driver.window_handles)) + print("Metamask_window_handle : " + str(self.driver.window_handles[2])) + time.sleep(10) + driver.switch_to.window(driver.window_handles[-1]) + time.sleep(5) + + # Challenge Block + #driver.find_element("xpath", "//div[1]/div/div[2]/div/div[3]/div[1]/i").click() + driver.find_element("xpath", '//*[@class="fa fa-arrow-down"]').click() + time.sleep(5) + driver.find_element("xpath", "//button[contains(.,'Sign')]").click() + time.sleep(15) + print("driver.window_handles_updated : " + str(self.driver.window_handles)) + # driver.switch_to.window(driver.window_handles[2]) + time.sleep(5) + driver.switch_to.window(driver.window_handles[-1]) + + #stream video + + SecondVideo = driver.find_element("xpath", + '//div[1]/div/div/div[3]/div[2]/div/div[20]/div/div/div[2]/div[2]/div/div[1]/div') + driver.execute_script("arguments[0].scrollIntoView();", SecondVideo) + driver.execute_script("arguments[0].click();", SecondVideo) + time.sleep(10) + # driver.find_element("xpath", "//div/div/div/div[3]/div[2]/div/div/div[4]/div[2]/div").click() + # time.sleep(5) + #driver.switch_to.window(driver.window_handles[-1]) + + SecondVideo_popup = driver.find_element("xpath", + '//div[1]/div/div/div[3]/div[2]/div/div[20]/div/div/div[1]/img') + driver.execute_script("arguments[0].scrollIntoView();", SecondVideo_popup) + driver.execute_script("arguments[0].click();", SecondVideo_popup) + # webdriver.ActionChains(driver).send_keys(Keys.ESCAPE).perform() + # time.sleep(5) + # driver.switch_to.window(driver.window_handles[-1]) + time.sleep(40) + + substring = "2.ts" + # JavaScript command to traffic + r = driver.execute_script("return window.performance.getEntries();") + result = 0 + for res in r: + if result != 1: + # print(res['name']) + fullstring = res['name'] + print("%%%%%%%%%%%%%") + print(fullstring) + if fullstring != None and substring in fullstring: + result = 1 + assert result == 1 + print("Found!") + # Appending text to log file + test_logs = open(SCREENSHOT_DIRECTORY + "TestExecutionLogs.txt", "w") + test_case_name = os.environ.get('PYTEST_CURRENT_TEST').split(':')[-1].split(' ')[0] + test_logs.write( + Test_HealthCheck.dt_string + "," + test_case_name + "," + "Test case Passed" + "," + fullstring + "\n") + test_logs.close() + else: + result = 0 + print("Not found!") + # Appending text to log file + test_logs = open(SCREENSHOT_DIRECTORY + "TestExecutionLogs.txt", "w") + test_case_name = os.environ.get('PYTEST_CURRENT_TEST').split(':')[-1].split(' ')[0] + test_logs.write( + Test_HealthCheck.dt_string + "," + test_case_name + "," + "Test case Failed" + "," + fullstring + "\n") + test_logs.close() + + # assert GREYMAN_URL == self.driver.current_url + + webdriver.ActionChains(driver).send_keys(Keys.ESCAPE).perform() + time.sleep(5) + driver.switch_to.window(driver.window_handles[-1]) + time.sleep(5) + assert result == 1 + + + except AssertionError: + pytest.fail("Test case failed") + except NoSuchElementException: + pytest.fail("Test case failed") + except NoSuchWindowException: + pytest.fail("Test case failed") + except ElementNotInteractableException: + pytest.fail("Test case failed") + except IndexError: + pytest.fail("Test case failed") + except: + print(traceback.format_exc()) + + @pytest.mark.skip + def test_Logout_metamask_rairTech(self): + try: + + _t = None + print("Running the Test Open Url") + if _data['MITM'] == 'True': + print("Clearing Cache as flag is True") + c.clearCache() + time.sleep(2) + ######################### Using Proxy Service ########################################## + + Logout(self) + + # assert CREATOR_URL == self.driver.current_url + assert (ABOUT_PAGE_URL) in self.driver.current_url + + + except AssertionError: + pytest.fail("Test case failed") + except NoSuchElementException: + pytest.fail("Test case failed") + except ElementNotInteractableException: + pytest.fail("Test case failed") + except NoSuchWindowException: + pytest.fail("Test case failed") + except: + print(traceback.format_exc()) + diff --git a/rair-infra/assets/selenium/HealthCheckTestRunner.py b/rair-infra/assets/selenium/HealthCheckTestRunner.py new file mode 100644 index 000000000..aeea7cc72 --- /dev/null +++ b/rair-infra/assets/selenium/HealthCheckTestRunner.py @@ -0,0 +1,120 @@ +#import constants +import pytest +import os +import urllib3 +import json +from datetime import datetime +import subprocess +import argparse +import requests +import cgi +import zipfile +import xdist +import Automation.WebAutomation.utilities as ut +#import WebAutomation.utilities as ut +# construct the argument parser and parse the arguments +ap = argparse.ArgumentParser() +ap.add_argument("-p", "--MITM", required=True, help="Charles True or False") +ap.add_argument("-d", "--POST_DATA", required=True, help="Send Data to Server True or False") +ap.add_argument("-g", "--HEADLESS", required=True, help="Headless Option for Selenium Browsers - True or False") +args = vars(ap.parse_args()) +import Automation.WebAutomation.webconfig as wc +#import WebAutomation.webconfig as wc +dashboardServerURL = 'http://' + wc.DASHBOARDHOST + ':' + wc.DASHBOARDPORT + '/save_web_test_json' +_data = {} + +_data['MITM'] = args['MITM'] +_data['POSTWEBDATA'] = args['POST_DATA'] +_data['HEADLESS'] = args['HEADLESS'] +print("........Entering data setup.....") + +BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +APP_ROOT = os.path.join(BASE_DIR, 'AutomationResults/WebAutomation') +TEST_DATA_ROOT = os.path.join(APP_ROOT, 'test_resuts') +JSON_WIRE_ROOT = os.path.join(APP_ROOT, 'json_data_wire') +CSV_DATA_ROOT = os.path.join(APP_ROOT, 'csv_data') +EXCEL_REPORTS = os.path.join(APP_ROOT, 'excel_reports') +HTML_REPORTS = os.path.join(APP_ROOT, 'html_reports') +JSON_REPORTS = os.path.join(APP_ROOT, 'json_reports') + +def createFolder(foldername): + try: + if not os.path.exists(foldername): + os.makedirs(foldername) + print('Created:', foldername) + except OSError: + print ("Creation of the directory %s failed" % foldername) + else: + print ("Successfully created the directory %s " % foldername) + +if 'now' not in _data: + now = datetime.now() + _data['now'] = now + +print("The Current Time in this file..... ", _data['now']) +# +if 'dt_string' not in _data: + dt_string = None + _data['dt_string'] = _data['now'].strftime("%d-%m-%Y-%H-%M-%S") + print("Date and Time =", _data['dt_string']) + +#################################################################### +if 'test_results_dir_json_wire' not in _data: + _data['test_results_dir_json_wire'] = os.path.join(JSON_WIRE_ROOT, str(_data['dt_string'] )) +if 'test_results_dir_csv' not in _data: + _data['test_results_dir_csv'] = os.path.join(CSV_DATA_ROOT, str(_data['dt_string'] )) +if 'test_results_dir_excel' not in _data: + _data['test_results_dir_excel'] = os.path.join(EXCEL_REPORTS, str(_data['dt_string'] )) +if 'test_results_dir_html' not in _data: + _data['test_results_dir_html'] = os.path.join(HTML_REPORTS, str(_data['dt_string'] )) +if 'test_results_dir_json_reports' not in _data: + _data['test_results_dir_json_reports'] = os.path.join(JSON_REPORTS, str(_data['dt_string'] )) +######################################################################### +print(".......Done Variable Setup.......") + +def mainTest(): + testArgs_HTML = _data['test_results_dir_html'] + "/" + "report.html" + testArgs_Excel = _data['test_results_dir_excel'] + "/" + "report.xls" + testArgs_JSON = _data['test_results_dir_json_reports'] + "/" + "report.json" + createFolder(_data['test_results_dir_json_wire']) + createFolder(_data['test_results_dir_csv']) + createFolder(_data['test_results_dir_excel']) + createFolder(_data['test_results_dir_html']) + createFolder(_data['test_results_dir_json_reports']) + #pytest.main(["-vvv", "-s", os.path.join(BASE_DIR,'WebAutomation','HealthCheck.py'),os.path.join(BASE_DIR,'WebAutomation','RAIRHomePageTest_metamask.py'),os.path.join(BASE_DIR,'WebAutomation','RAIR_UseCases.py'), "--json=" + testArgs_JSON, "--html=" + testArgs_HTML,"--self-contained-html"]) + pytest.main(["-vvv", "-s", os.path.join(BASE_DIR,'WebAutomation','HealthCheck.py'), "--json=" + testArgs_JSON, "--html=" + testArgs_HTML,"--self-contained-html"]) + #pytest.main(["-vvv", "-s", os.path.join(BASE_DIR,'WebAutomation','HealthCheck_Resale.py'), "--json=" + testArgs_JSON, "--html=" + testArgs_HTML,"--self-contained-html"]) + print("Web Test Done") + + # JSON Data # + json_data = open(testArgs_JSON).read() + testArgs_JSON + + # HTML Data # + html_data = open(testArgs_HTML).read() + testArgs_HTML + + # Zip file from JSON WIRE DATA + print("Creating Archive") + zipName = ut.createZIP(_data['test_results_dir_json_wire'],_data['dt_string']) + print(zipName) + # 'metrics': zipName+'.zip' + params = { + "FILENAME": json_data, + "FILENAME_HTML": html_data, + 'testtype': 'web', + 'datetestrun': _data['dt_string'], + 'metrics': zipName + '.zip' + + } + + # Send Data to server only if True + if _data['POSTWEBDATA'] == 'True': + print("Sending the data to the server....... ") + http = urllib3.PoolManager() + #resp = http.request('POST', dashboardServerURL,params ) + #print(resp.status) + print("Done") + +if __name__ == "__main__": + mainTest() diff --git a/rair-infra/assets/selenium/Locators.py b/rair-infra/assets/selenium/Locators.py new file mode 100644 index 000000000..951696961 --- /dev/null +++ b/rair-infra/assets/selenium/Locators.py @@ -0,0 +1,97 @@ +class Locator(object): + + private_key_locator = "//*[@id='root']/div/div/div/input" + private_key_locator_new = "//div[@id='root']/div/div[2]/div[3]/div/div/div/input" + private_key = "902724d51d109a26cad6f7c4c18599cee5366ffb718b80a06c42a5a4c315b0c2" + public_key = "0x980df6193829384539781f1075316b7913c88bec" + #public_key = "0x67b99531a2ab44f5c71474bd54d07fe78d7c5516" + #private_key = "8ca0ef84077c6fec75e34067aa498ea95f57c8979d0701f506b004ef5472b7de" + #private_key = "edb857db1f3d0106ec384263a572358e5490eaf295675f78857d89c6077937d8" + + ################################################ + # Select Blockchain - Binance Testnet + Binance = "//*[@id='root']/div/div/div/div[4]/button[1]" + #Binance_new = "connect_BNB" + Binance_new = "//button[contains(.,'Binance Testnet')]" + # Select Blockchain - Klaytn Testnet + klaytn_new = "connect_KLAY" + # Select Blockchain - Mumbai Testnet + Mumbai = "//*[@id='root']/div/div/div/div[4]/button[3]" + Mumbai_Testnet_new = "//button[contains(.,'Matic Testnet Mumbai')]" + # Select Blockchain - Mainnet Matic + Mumbai_Main_new = "connect_MATIC" + ################################################# + + #connect_wallet = "//button[contains(.,'Connect Wallet')]" + connect_wallet = "//button[contains(.,'Connect')]" + profile_dropdown_beta = "//div[@id='root']/div/div/div[1]/div[3]/div/div[2]/div[1]/div[3]/button/div[2]/i" + #profile_dropdown = "//div[@id='root']/div/div/div/div[2]/div[3]/div/div[2]/div/div[2]/button/div[4]/i" + profile_dropdown = "//*[@class='svg-inline--fa fa-bars icon-menu']" + #profile_dropdown = "//*[@class='icon-menu fas fa-bars']" + profile_dropdown_hotdrops = "//*[@class='icon-menu fas fa-bars hotdrops-btn']" + + Contract_Heading = "//h3[contains(.,'Your Deployed ERC721 Contracts')]" + Marketplace_Heading = "xpath=//h5[contains(.,'Minter Marketplace')]" + + ##################################################### + + admin_icon = "//div[@id='root']/div/div/div/div[3]/div/div/i" + #menu_admin = "//*[@id='root']/div/div[2]/div[2]/div[6]/a" + menu_admin = "fa-user-secret" + #menu_factory = "//*[@id='root']/div/div/div[2]/div[1]/div[2]/a[11]" + #menu_factory = "//a[contains(text(),'Factory')]" + menu_factory = "fa-city" + #menu_MyNFTs = "//a[contains(text(),'My NFTs')]" + menu_MyNFTs = "fa-key" + #menu_MyContracts = "//a[contains(text(),'My Contracts')]" + menu_MyContracts = "fa-id-card" + #menu_ForSale = "//a[contains(text(),'For Sale')]" + menu_ForSale = "fa-shopping-cart" + #menu_Marketplace = "//*[@id='root']/div/div/div[2]/div[1]/div[2]/a[12]" + #menu_Marketplace = "//a[contains(text(),'Minter Marketplace')]" + menu_Marketplace = "fa-shopping-basket" + menu_DiamondMarketplace = "fa-gem" + menu_TransferNFT = "fa-exchange" + menu_Import = "fa-file-import" + + + text_policy = "policy" + text_use = "use" + + ################################################### + + + Metamask_icon = "//*[@id='root']/div/div/div[2]/div[1]/button" + + #Contract_name_textbox_new = "//*[@id='root']/div/div/div[2]/div[2]/div[2]/div/div[2]/input" + Contract_name_textbox_new = "//*[@id='root']/div/div/div[3]/div[2]/div/div[2]/input" + ContractName_textbox_creatorUI = "//div[@id='root']/div/div/div[3]/div[2]/div/div/div[2]/div[2]/div[3]/input" + ContractAdd_button_creatorUI = "//button[contains(.,'Deploy using 15.0 RAIR Tokens')]" + ContractAdd_Diamond_button_creatorUI = "//button[contains(.,'deploy with Diamonds')]" + CollectionName_textbox_creatorUI = "//div[@id='root']/div/div/div[3]/div[2]/div/div/div[2]/div[2]/div/input" + Collection_Length_creatorUI = "//div[@id='root']/div/div/div[3]/div[2]/div/div/div[2]/div[2]/div[2]/input" + CollectionAdd_button_creatorUI = "//button[contains(.,'Create collection!')]" + Collection_Add_switch_creatorUI = "//div[@id='root']/div/div/div[3]/div[2]/div/div[3]/div/div[3]/div/button" + MinterMarketplace_button_creatorUI = "//button[contains(.,'Approve Minter Marketplace')]" + DiamondMarketplaceApprove_button_creatorUI = "//button[contains(.,'Approve the marketplace as a Minter!')]" + Diamond_RangesSale_button_creatorUI = "//button[contains(.,'Put selected ranges up for sale!')]" + #AddOffer_Button_creatorUI = "//div[@id='root']/div/div[2]/div[2]/div[2]/div[2]/div/div/button/i" + AddOffer_Button_creatorUI = "//button[contains(.,'Add new')]" + OfferName_textbox_creatorUI = "//div[@id='root']/div/div/div[3]/div[2]/div[2]/table/tbody/tr/th[2]/div/input" + OfferName_Diamond_textbox_creatorUI = "//div[@id='root']/div/div/div[3]/div[2]/div[2]/div/div/div/div/div/input" + #OfferName_Diamond_textbox_creatorUI = "//div[@id='root']/div/div[2]/div[2]/div[2]/div[2]/div/div/div/div/div/input" + #OfferName_Endtoken_creatorUI = "//div[@id='root']/div/div[2]/div[2]/div[2]/div[2]/table/tbody/tr/th[4]/div/input" + OfferName_Endtoken_creatorUI = "//div[@id='root']/div/div/div[3]/div[2]/div[2]/table/tbody/tr/th[4]/div/input" + #OfferName_Diamond_Endtoken_creatorUI = "//div[@id='root']/div/div[2]/div[2]/div[2]/div[2]/div/div/div/div[4]/div/input" + OfferName_Diamond_Endtoken_creatorUI = "//div[@id='root']/div/div/div[3]/div[2]/div[2]/div/div/div/div[4]/div/input" + #OfferName_Price_creatorUI = "//div[@id='root']/div/div[2]/div[2]/div[2]/div[2]/table/tbody/tr/th[5]/div/input" + OfferName_Price_creatorUI = "//div[@id='root']/div/div/div[3]/div[2]/div[2]/table/tbody/tr/th[5]/div/input" + #OfferName_Diamond_Price_creatorUI = "//div[@id='root']/div/div[2]/div[2]/div[2]/div[2]/div/div/div/div[5]/div/input" + OfferName_Diamond_Price_creatorUI = "//div[@id='root']/div/div/div[3]/div[2]/div[2]/div/div/div/div[5]/div/input" + OfferName_delete_icon = "//div[@id='root']/div/div[2]/div[2]/div[2]/div[2]/table/tbody/tr/th[5]/div/input" + AddOfferConfirm_Button_creatorUI = "//button[contains(.,'offer')]" + AddOfferConfirm_Diamond_Button_creatorUI = "//button[contains(.,'Ranges')]" + #Contract_add_button_new = "//*[@id='root']/div/div/div[2]/div[2]/div[2]/div/div[2]/button[2]" + #Contract_add_button_new = "//*[@id='root']/div/div/div[3]/div[2]/div/div[2]/button[2]" + Contract_add_button_new = "//button[contains(.,'Buy an ERC721 contract for')]" + Continue_button_creatorUI = "//button[contains(.,'Continue')]" diff --git a/rair-infra/assets/selenium/webconfig.py b/rair-infra/assets/selenium/webconfig.py new file mode 100644 index 000000000..4f5c5bf16 --- /dev/null +++ b/rair-infra/assets/selenium/webconfig.py @@ -0,0 +1,43 @@ +import os + +MITMHOST = '192.168.1.105' +MITMPORT = '8888' +DASHBOARDHOST = '65.21.191.184' +#DASHBOARDHOST = '127.0.0.1' +DASHBOARDPORT = '8000' +SNIFFHOST = 'demo.rair.tech' +SNIFFPATH = 'api/media' +QA1_URL = 'http://81.17.100.130:8088/' +QA2_URL = 'http://35.192.66.4:8088/' +QA3_URL = 'http://35.202.14.223:8088/' +BETA_URL = 'https://beta.rair.tech/' +RAIRPROTOCOL = 'https://rairprotocol.xyz/' +RAIR_MARKET = 'https://rair.market/' +OPENCARBON_MARKET = 'https://opencarbon.market/' +BETA_DEMO_URL = 'https://beta.rair.tech/' +RAIRLICENSE = 'https://rairlicense.org/' +metamaskPK = '' +ethaddress = '' +ChromeExtension_Url = 'chrome-extension://nkbihfbeogaeaoehlefnkodbefgpgknn/home.html' +SECRET_RECOVERY_PHRASE = "x x x x x x x x x x x x" +SECRET_RECOVERY_PHRASE_QA = "x x x x x x x x x x x x" +SECRET_RECOVERY_PHRASE_NEW = "x x x x x x x x x x x x" +SECRET_RECOVERY_PHRASE_1 = 'x' +SECRET_RECOVERY_PHRASE_2 = 'x' +SECRET_RECOVERY_PHRASE_3 = 'x' +SECRET_RECOVERY_PHRASE_4 = 'x' +SECRET_RECOVERY_PHRASE_5 = 'x' +SECRET_RECOVERY_PHRASE_6 = 'x' +SECRET_RECOVERY_PHRASE_7 = 'x' +SECRET_RECOVERY_PHRASE_8 = 'x' +SECRET_RECOVERY_PHRASE_9 = 'x' +SECRET_RECOVERY_PHRASE_10 = 'x' +SECRET_RECOVERY_PHRASE_11 = 'x' +SECRET_RECOVERY_PHRASE_12 = 'x' +NEW_PASSWORD ='xxxxxxx' +NEW_PASSWORD_QA = '=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' +NEW_PASSWORD_NEW = 'xxxxxxxx' + +Expected_Filter_Labels = ["Degen", "Film","Conference", "Garrett's Closet","Genesis", "Gaming", "Brand", "eLearning" , "Science", "Music", "Art", "Astar Mainnet", "Matic(Polygon) Mainnet", "Matic(Polygon) Testnet", "Ethereum Mainnet", "Ethereum Goerli" ] + + diff --git a/rair-node/bin/api/files/files.Controller.js b/rair-node/bin/api/files/files.Controller.js index be7b28578..029fde3e6 100644 --- a/rair-node/bin/api/files/files.Controller.js +++ b/rair-node/bin/api/files/files.Controller.js @@ -23,18 +23,18 @@ const { File } = require('../../models'); const router = express.Router(); router.patch( - '/update/:mediaId', + '/update/:id', requireUserSession, - validation(['removeMedia'], 'params'), + validation(['fileId'], 'params'), validation(['updateMedia'], 'body'), isOwner(File), updateMedia, ); router.delete( - '/remove/:mediaId', + '/remove/:id', requireUserSession, - validation(['removeMedia'], 'params'), + validation(['fileId'], 'params'), isOwner(File), deleteMedia, ); @@ -70,15 +70,23 @@ router.get( validation(['dbId'], 'params'), getFilesForToken, ); -router.get('/:id/unlocks', getFileAndOffer); +router.get( + '/:id/unlocks', + validation(['fileId'], 'params'), + getFileAndOffer, +); router.post( '/:id/unlocks', + validation(['fileId'], 'params'), + validation(['offerArray'], 'body'), requireUserSession, isFileOwner, connectFileAndOffer, ); router.delete( '/:id/unlocks', + validation(['fileId'], 'params'), + validation(['singleOffer'], 'body'), requireUserSession, isFileOwner, removeFileAndOffer, diff --git a/rair-node/bin/api/files/files.Service.js b/rair-node/bin/api/files/files.Service.js index db860e326..4e419afcb 100644 --- a/rair-node/bin/api/files/files.Service.js +++ b/rair-node/bin/api/files/files.Service.js @@ -74,11 +74,15 @@ module.exports = { 'unlockData.offers.contract': { $in: arrayOfContracts, }, - }, { - demo: true, }], }; + if (!blockchain.length) { + matchData.$or.push({ + demo: true, + }); + } + if (hidden === 'true') { matchData.hidden = true; } else { @@ -115,6 +119,18 @@ module.exports = { }, { $match: matchData, + }, { + $lookup: { + from: 'Category', + localField: 'category', + foreignField: '_id', + as: 'category', + }, + }, { + $unwind: { + path: '$category', + preserveNullAndEmptyArrays: true, + }, }, { $project: { @@ -160,32 +176,32 @@ module.exports = { }, deleteMedia: async (req, res, next) => { try { - const { mediaId } = req.params; + const { id } = req.params; - const fileData = await File.findOne({ _id: mediaId }); + const fileData = await File.findOne({ _id: id }); let deleteResponse; if (!fileData.storage) { - log.error(`Can't tell where media ID ${mediaId} is stored, will not unpin/delete from storage, just from DB`); + log.error(`Can't tell where media ID ${id} is stored, will not unpin/delete from storage, just from DB`); deleteResponse = { success: true }; } else { switch (fileData.storage) { case 'gcp': - deleteResponse = await gcp.removeFile(config.gcp.videoBucketName, mediaId); + deleteResponse = await gcp.removeFile(config.gcp.videoBucketName, id); break; case 'ipfs': - deleteResponse = await removePin(mediaId); + deleteResponse = await removePin(id); break; default: - log.error(`Unknown storage type for media ID ${mediaId} : ${fileData.storage}`); + log.error(`Unknown storage type for media ID ${id} : ${fileData.storage}`); break; } } if (deleteResponse.success) { - await File.deleteOne({ _id: mediaId }); - await Unlock.deleteMany({ file: mediaId }); - log.info(`File with ID: ${mediaId}, was removed from DB.`); + await File.deleteOne({ _id: id }); + await Unlock.deleteMany({ file: id }); + log.info(`File with ID: ${id}, was removed from DB.`); res.json({ success: true, }); @@ -202,7 +218,7 @@ module.exports = { }, updateMedia: async (req, res, next) => { try { - const { mediaId } = req.params; + const { id } = req.params; // eslint-disable-next-line no-unused-vars const { _id, ...cleanBody } = req.body; @@ -213,7 +229,7 @@ module.exports = { req.body = bodyForNonAdmins; } - const updateRes = await File.updateOne({ _id: mediaId }, cleanBody); + const updateRes = await File.updateOne({ _id: id }, cleanBody); if (!updateRes.acknowledged) { return res.json({ success: false, message: 'An error has ocurred' }); @@ -221,7 +237,7 @@ module.exports = { if (updateRes.matchedCount === 1 && updateRes.modifiedCount === 0) { return res.json({ success: false, message: 'Nothing to update' }); } - log.info(`File with ID: ${mediaId}, was updated on DB.`); + log.info(`File with ID: ${id}, was updated on DB.`); return res.json({ success: true }); } catch (err) { return next(err); diff --git a/rair-node/bin/api/nft/nft.Service.js b/rair-node/bin/api/nft/nft.Service.js index 771e12ba3..b205a37ca 100644 --- a/rair-node/bin/api/nft/nft.Service.js +++ b/rair-node/bin/api/nft/nft.Service.js @@ -653,13 +653,13 @@ module.exports = { metadataFilters = JSON.parse(metadataFilters); aggregateOptions.push({ $match: { - $or: Object.keys(metadataFilters).map((attr) => ({ - 'metadata.attributes': { - $elemMatch: { - trait_type: attr, - value: { $in: metadataFilters[attr] }, - }, - }, + $and: Object.keys(metadataFilters).map((attr) => ({ + 'metadata.attributes': { + $elemMatch: { + trait_type: attr, + value: { $in: metadataFilters[attr] }, + }, + }, })), }, }); diff --git a/rair-node/bin/api/users/users.Controller.js b/rair-node/bin/api/users/users.Controller.js index 5ff4359d4..a7bf237fd 100644 --- a/rair-node/bin/api/users/users.Controller.js +++ b/rair-node/bin/api/users/users.Controller.js @@ -1,5 +1,5 @@ const express = require('express'); -const { validation, requireUserSession, isAdmin } = require('../../middleware'); +const { validation, requireUserSession, isAdmin, loadUserSession } = require('../../middleware'); const { createUser, getUserByAddress, @@ -7,6 +7,7 @@ const { listUsers, exportUsers, yotiVerify, + queryGithubData, } = require('./users.Service'); const upload = require('../../Multer/Config'); @@ -14,8 +15,8 @@ const router = express.Router(); router.get( '/list', - requireUserSession, - isAdmin, + validation(['customUserFields', 'pagination'], 'query'), + loadUserSession, listUsers, ); router.get( @@ -47,6 +48,7 @@ router upload.array('files', 2), validation(['updateUser']), updateUserByUserAddress, + queryGithubData, ); module.exports = router; diff --git a/rair-node/bin/api/users/users.Service.js b/rair-node/bin/api/users/users.Service.js index d66d0822c..9257c1e03 100644 --- a/rair-node/bin/api/users/users.Service.js +++ b/rair-node/bin/api/users/users.Service.js @@ -3,6 +3,7 @@ const fs = require('fs'); const { randomUUID } = require('crypto'); const path = require('path'); const { RequestBuilder, Payload } = require('yoti'); +const fetch = require('node-fetch'); const config = require('../../config'); const gcp = require('../../integrations/gcp')(config); const log = require('../../utils/logger')(module); @@ -62,18 +63,52 @@ exports.yotiVerify = async (req, res, next) => { } }; +const adminProtectedFields = [ + 'email', + 'firstName', + 'lastName', + 'publicAddress', + 'nonce', + 'creationDate', + 'blocked', + '_id', +]; exports.listUsers = async (req, res, next) => { try { - const list = await User.find({}, { - email: 1, - nickName: 1, - publicAddress: 1, - creationDate: 1, - blocked: 1, + const { + fields = 'email,nickName,publicAddress,creationDate,blocked', + pageNum = 0, + itemsPerPage = 10, + } = req.query; + const queriedFields = { + _id: 0, + }; + fields?.split(',')?.forEach((field) => { + if (adminProtectedFields.includes(field.toLowerCase()) && !req.user?.adminRights) { + return; + } + queriedFields[field] = 1; }); + const [result] = await User.aggregate([ + { + $project: queriedFields, + }, + { + $facet: { + list: [ + { $skip: pageNum * itemsPerPage }, + { $limit: Number(itemsPerPage) }, + ], + count: [ + { $count: 'total' }, + ], + }, + }, + ]); return res.json({ success: true, - data: list, + data: result.list, + totalCount: result?.count?.[0]?.total || 0, }); } catch (err) { return next(err); @@ -140,6 +175,7 @@ exports.createUser = async (req, res, next) => { next(e); } }; + exports.getUserByAddress = async (req, res, next) => { try { const publicAddress = req.params.publicAddress.toLowerCase(); @@ -214,8 +250,27 @@ exports.updateUserByUserAddress = async (req, res, next) => { ...updatedUser, }; - return res.json({ success: true, user: updatedUser }); + res.json({ success: true, user: updatedUser }); + return next(); } catch (e) { return next(e); } }; + +exports.queryGithubData = async (req, res, next) => { + const { email, publicAddress, gitHandle } = req.session.userData; + if (gitHandle) { + return; + } + const query = await (await fetch(`https://api.github.com/search/users?q=${email}`)).json(); + if (query.total_count === 1) { + await User.findOneAndUpdate({ publicAddress }, { + gitHandle: query.items[0].login, + gitBio: query.items[0].bio, + // available: query.items[0].hireable, + avatar: query.items[0].avatar_url, + }); + return; + } + log.error("Couldn't fetch Github data, more than one account associated with the email"); +}; diff --git a/rair-node/bin/index.js b/rair-node/bin/index.js index 35ba6b9bc..3aea4a34b 100644 --- a/rair-node/bin/index.js +++ b/rair-node/bin/index.js @@ -2,6 +2,7 @@ require('dotenv').config(); const express = require('express'); const bodyParser = require('body-parser'); const cookieParser = require('cookie-parser'); +const { nanoid } = require('nanoid'); const fs = require('fs'); const cors = require('cors'); const { createServer } = require('http'); @@ -9,6 +10,7 @@ const { Server } = require('socket.io'); const morgan = require('morgan'); const session = require('express-session'); const RedisStorage = require('connect-redis')(session); +const { rateLimit } = require('express-rate-limit'); const seedDB = require('./seeds'); const log = require('./utils/logger')(module); const StartHLS = require('./hls-starter'); @@ -54,6 +56,15 @@ async function main() { const hls = await StartHLS(); + const limiter = rateLimit({ + windowMs: 60 * 1000, // 1 minute + limit: process.env.RATE_LIMIT_MINUTE || 500, + standardHeaders: 'draft-7', // draft-6: `RateLimit-*` headers; draft-7: combined `RateLimit` header + legacyHeaders: false, // Disable the `X-RateLimit-*` headers. + }); + + app.use(limiter); + const context = { hls, config, @@ -87,10 +98,11 @@ async function main() { app.use(morgan('dev')); app.use(bodyParser.raw()); app.use(bodyParser.json({ limit: '50mb' })); - app.use(cookieParser()); + app.use(cookieParser(nanoid())); app.set('trust proxy', 1); app.use(sessionMiddleware); + // app.use(lusca.csrf()); app.use('/stream', streamRoute(context)); diff --git a/rair-node/bin/models/user.js b/rair-node/bin/models/user.js index c68453ab6..d676cd62f 100644 --- a/rair-node/bin/models/user.js +++ b/rair-node/bin/models/user.js @@ -21,6 +21,17 @@ const User = new Schema( nonce: { type: String, default: () => nanoid(), select: false }, creationDate: { type: Date, default: Date.now }, blocked: { type: Boolean, default: false }, + // Github integration + gitHandle: { type: String, required: false }, + userLevel: { type: Number, required: false }, + available: { type: Boolean, required: false, default: false }, + gitBio: { type: String, required: false }, + languages: [{ + type: { + name: { type: String }, + percentage: { type: Number }, + }, + required: false }], }, { versionKey: false }, ); diff --git a/rair-node/bin/schemas/createFavoriteToken.js b/rair-node/bin/schemas/createFavoriteToken.js index 9a39eaec7..9a532d2f1 100644 --- a/rair-node/bin/schemas/createFavoriteToken.js +++ b/rair-node/bin/schemas/createFavoriteToken.js @@ -1,5 +1,5 @@ const { mongoId } = require('./reusableCustomTypes'); module.exports = () => ({ - token: mongoId + token: mongoId, }); diff --git a/rair-node/bin/schemas/createUser.js b/rair-node/bin/schemas/createUser.js deleted file mode 100644 index 10428ef14..000000000 --- a/rair-node/bin/schemas/createUser.js +++ /dev/null @@ -1,5 +0,0 @@ -const { ethAddress } = require('./reusableCustomTypes'); - -module.exports = () => ({ - publicAddress: ethAddress.required(), -}); diff --git a/rair-node/bin/schemas/files.js b/rair-node/bin/schemas/files.js new file mode 100644 index 000000000..8210e9b6c --- /dev/null +++ b/rair-node/bin/schemas/files.js @@ -0,0 +1,20 @@ +const Joi = require('joi'); +const { mongoId } = require('./reusableCustomTypes'); + +module.exports = { + updateMedia: () => ({ + title: Joi.string().min(1).max(30), + description: Joi.string().min(1).max(300), + contract: Joi.string(), + product: Joi.string(), + offer: Joi.array().items(mongoId), + category: Joi.string().min(1), + demo: Joi.boolean(), + }), + offerArray: () => ({ + offers: Joi.array().items(mongoId).required(), + }), + singleOffer: () => ({ + offer: mongoId.required(), + }), +}; diff --git a/rair-node/bin/schemas/index.js b/rair-node/bin/schemas/index.js index 25dc4a8d7..ed7db7426 100644 --- a/rair-node/bin/schemas/index.js +++ b/rair-node/bin/schemas/index.js @@ -1,19 +1,18 @@ const admin = require('./admin'); +const databaseSchemas = require('./databaseSchemas'); const addMedia = require('./addMedia'); const authentication = require('./authentication'); const createContract = require('./createContract'); -const createUser = require('./createUser'); +const { createUser, updateUser, customUserFields } = require('./userRoutes'); const getChallenge = require('./getChallenge'); const getChallengeV2 = require('./getChallengeV2'); const filterAndSort = require('./filterAndSort'); const getToken = require('./getToken'); -const removeMedia = require('./removeMedia'); -const updateMedia = require('./updateMedia'); +const { updateMedia, offerArray, singleOffer } = require('./files'); const stream = require('./stream'); const uploadVideo = require('./uploadVideo'); const uploadVideoFile = require('./uploadVideoFile'); const updateContract = require('./updateContract'); -const updateUser = require('./updateUser'); const singleContract = require('./singleContract'); const getFilesByNFT = require('./getFilesByNFT'); const nftContract = require('./nftContract'); @@ -71,7 +70,6 @@ module.exports = { getChallenge, filterAndSort, getToken, - removeMedia, stream, uploadVideo, uploadVideoFile, @@ -86,6 +84,8 @@ module.exports = { // Media files updateMedia, + offerArray, + singleOffer, analyticsParams, analyticsQuery, @@ -98,6 +98,7 @@ module.exports = { // user createUser, updateUser, + customUserFields, // token updateTokenMetadata, @@ -115,9 +116,8 @@ module.exports = { // favorites createFavoriteToken, - // V2 Validation // Database schemas (using the Entity helper) - ...require('./databaseSchemas'), + ...databaseSchemas, // Media schemas validateMediaData, addFileFromMediaService, diff --git a/rair-node/bin/schemas/removeMedia.js b/rair-node/bin/schemas/removeMedia.js deleted file mode 100644 index 7c04c267b..000000000 --- a/rair-node/bin/schemas/removeMedia.js +++ /dev/null @@ -1,7 +0,0 @@ -const Joi = require('joi'); -const { customValidator } = require('./helpers'); - -module.exports = () => ({ - mediaId: Joi.custom(customValidator({ min: 3, max: 50 })) - .required(), -}); diff --git a/rair-node/bin/schemas/updateMedia.js b/rair-node/bin/schemas/updateMedia.js deleted file mode 100644 index 7b7aa2b52..000000000 --- a/rair-node/bin/schemas/updateMedia.js +++ /dev/null @@ -1,11 +0,0 @@ -const Joi = require('joi'); - -module.exports = () => ({ - title: Joi.string().min(1).max(30), - description: Joi.string().min(1).max(300), - contract: Joi.string(), - product: Joi.string(), - offer: Joi.array().items(Joi.string()), - category: Joi.string().min(1), - demo: Joi.boolean(), -}); diff --git a/rair-node/bin/schemas/updateUser.js b/rair-node/bin/schemas/updateUser.js deleted file mode 100644 index cba3d3208..000000000 --- a/rair-node/bin/schemas/updateUser.js +++ /dev/null @@ -1,11 +0,0 @@ -const Joi = require('joi'); - -module.exports = () => ({ - nickName: Joi.string(), - avatar: Joi.string(), - background: Joi.string(), - email: Joi.string().email(), - firstName: Joi.string(), - lastName: Joi.string(), - blocked: Joi.boolean(), -}); diff --git a/rair-node/bin/schemas/userRoutes.js b/rair-node/bin/schemas/userRoutes.js new file mode 100644 index 000000000..b8a62f7e3 --- /dev/null +++ b/rair-node/bin/schemas/userRoutes.js @@ -0,0 +1,23 @@ +const Joi = require('joi'); +const { ethAddress } = require('./reusableCustomTypes'); + +module.exports = { + createUser: () => ({ + publicAddress: ethAddress.required(), + email: Joi.string().email(), + }), + + customUserFields: () => ({ + fields: Joi.string(), + }), + + updateUser: () => ({ + nickName: Joi.string(), + avatar: Joi.string(), + background: Joi.string(), + email: Joi.string().email(), + firstName: Joi.string(), + lastName: Joi.string(), + blocked: Joi.boolean(), + }), +}; diff --git a/rair-node/bin/schemas/v2AuthSchemas.js b/rair-node/bin/schemas/v2AuthSchemas.js index 4ff97202d..963c7c2f0 100644 --- a/rair-node/bin/schemas/v2AuthSchemas.js +++ b/rair-node/bin/schemas/v2AuthSchemas.js @@ -1,6 +1,6 @@ const Joi = require('joi'); const { customValidator } = require('./helpers'); -const { blockchainNetworks, ethAddress } = require('./reusableCustomTypes'); +const { ethAddress } = require('./reusableCustomTypes'); module.exports = { v2Unlock: () => ({ @@ -12,9 +12,6 @@ module.exports = { .required(), MetaSignature: Joi.custom(customValidator({ min: 132, max: 770 })) .required(), - ownerAddress: ethAddress, userAddress: ethAddress, - mediaId: Joi.string(), - zoomId: Joi.string(), }), }; diff --git a/rair-node/bin/utils/entityFactory.js b/rair-node/bin/utils/entityFactory.js index 8493dd3d4..865daba81 100644 --- a/rair-node/bin/utils/entityFactory.js +++ b/rair-node/bin/utils/entityFactory.js @@ -22,7 +22,6 @@ exports.deleteOne = (Model) => return res.status(204).json({ success: true, - data: null, }); }); diff --git a/rair-node/package.json b/rair-node/package.json index 620fe2344..6f8abc3c8 100644 --- a/rair-node/package.json +++ b/rair-node/package.json @@ -26,7 +26,7 @@ "dbscripts": "node ./scripts/indexes.mongo.js" }, "dependencies": { - "@alchemy/aa-core": "^3.6.1", + "@alchemy/aa-core": "^3.19.0", "@ambire/signature-validator": "^1.3.1", "@aws-sdk/client-s3": "^3.429.0", "@aws-sdk/lib-storage": "^3.431.0", @@ -38,25 +38,27 @@ "@sentry/node": "^7.5.0", "alchemy-sdk": "^3.2.0", "axios": "^0.21.0", - "body-parser": "^1.20.2", + "body-parser": "^1.20.3", "connect-redis": "^6.1.3", - "cookie-parser": "^1.4.6", + "cookie-parser": "^1.4.7", "cors": "^2.8.5", "csv-parser": "^3.0.0", "dompurify": "^2.3.5", "dotenv": "^16.4.5", - "ethers": "^6.11.1", - "express": "^4.18.3", - "express-session": "^1.18.0", + "ethers": "^6.13.4", + "express": "^4.21.1", + "express-rate-limit": "^7.4.1", + "express-session": "^1.18.1", "files-from-path": "^1.0.0", - "follow-redirects": "^1.15.5", + "follow-redirects": "^1.15.9", "foreman": "^3.0.1", "graceful-fs": "^4.2.11", "ipfs-car": "^1.0.0", - "joi": "^17.11.0", + "joi": "^17.13.3", "jsdom": "^19.0.0", "jsonwebtoken": "^8.5.1", "lodash": "^4.17.21", + "lusca": "^1.7.0", "mongodb": "^5.4.0", "mongoose": "^7.1.0", "morgan": "^1.10.0", @@ -65,13 +67,13 @@ "node-cache": "^5.1.2", "node-fetch": "^2.6.7", "nodemon": "^3.0.3", - "redis": "^4.6.14", - "socket.io": "^4.7.4", + "redis": "^4.7.0", + "socket.io": "^4.8.1", "swagger-jsdoc": "^4.2.3", "swagger-ui-express": "^4.6.3", "triple-beam": "^1.4.1", - "winston": "^3.11.0", - "winston-transport": "^4.6.0", + "winston": "^3.15.0", + "winston-transport": "^4.8.0", "yoti": "^4.6.0" }, "devDependencies": { @@ -83,7 +85,7 @@ "eslint-plugin-node": "^11.1.0", "eslint-plugin-promise": "^4.2.1", "eslint-plugin-standard": "^4.0.1", - "prettier": "^2.8.7" + "prettier": "^3.3.3" }, "bin": { "decrypt-node": "index.js"