- import React from 'react';
- import { Animated, ScrollView, FlatList, Platform, Text, View, TouchableOpacity, Image, Dimensions, ActivityIndicator } from 'react-native';
- import { SafeAreaView } from 'react-native-safe-area-context';
- import styles from '../styles/Content';
- import drawerStyles from '../styles/DrawerMenu';
- import CustomIcons from '../components/CustomIcon';
- import ContentListView from '../components/ContentListView';
- import EmptyScreen from '../components/EmptyScreen';
- import Chip from '../components/Chip';
- import EStyleSheet from 'react-native-extended-stylesheet';
- import DrawerLayout from 'react-native-drawer-layout';
- import { translate } from '../locales/i18n';
- import Spinner from 'react-native-spinkit';
- import config from '../config/config';
- import staticConfig from '../config/staticConfig';
- import * as conProvider from '../utils/ConProvider';
- import * as colProvider from '../utils/ColProvider';
- import * as insProvider from '../utils/InsProvider';
- import * as varProvider from '../utils/VarProvider';
- import * as jaProvider from '../utils/JAProvider';
- import * as connection from '../utils/Connection';
- import * as apiProvider from '../utils/ApiProvider';
- import * as storageProvider from '../utils/StorageProvider';
- import * as analyticsProvider from '../utils/AnalyticsProvider';
- import * as setProvider from '../utils/SetProvider';
- import * as notProvider from '../utils/NotProvider';
- import screenNames from '../config/screenNames';
- import Toast from '@remobile/react-native-toast';
- import RNFetchBlob from 'rn-fetch-blob';
- import NativeReachabilityModule from '../components/NativeReachabilityModule';
- import VPNModule from '../components/VPNModule';
- import ArticleLoader from '../components/ArticleLoader';
- import Modal from 'react-native-modal';
- import AsyncStorage from '@react-native-async-storage/async-storage';
- import imageJson from '../config/imageJson';
- import guideImageJson from '../config/guideImageJson';
- import GuideView from '../components/GuideView';
- import ActionSheet from '../components/ActionSheet';
- var contentList, currentType, noMoreData, isInfiniteOn, currentTitle = "", activeType, favIndex = 0, fromDidMount, modalObserver, conVPNObserver, menuItemId;
- var typeList = [];
- var pagingCount = config.contentPagingCount;
- var cloneIt, alreadyLoaded;
- var currentRandomId, currentRandomTypeId, isRootCall, isListFromGraph;
- var shouldShowJournalDetail, modalWidth, modalHeight, multiUrlsList = [], graphError;
- var addVPNPopup = false;
- export default class Content extends React.Component {
- constructor(props) {
- super(props);
- this.state = {
- isCardView: false,
- contentList: [],
- footerLoading: false,
- contentLoading: true,
- contentLength: 0,
- errorModal: false,
- pubFilters: [],
- refreshTypes: false,
- isDrawerOn: false,
- drawerLockMode: "locked-closed",
- showGuide: false,
- multiUrlsView: false,
- isConnected: connection.isConnectedFun(),
- isVPNConfigAccepted: true,
- isVPNOptional: true
- };
- graphError = "";
- contentList = [];
- isListFromGraph = false;
- currentType = null;
- activeType = null;
- currentTitle = "";
- menuItemId = "";
- typeList = [];
- alreadyLoaded = true;
- isInfiniteOn = false;
- varProvider.drawerLockMode = "locked-closed";
- addVPNPopup = false;
- this.openMenu = this.openMenu.bind(this);
- this.callbackFun = this.callbackFun.bind(this);
- this.buttonCallback = this.buttonCallback.bind(this);
- this.rootButtonCallback = this.rootButtonCallback.bind(this);
- this.callbackFavorite = this.callbackFavorite.bind(this);
- this.removeItem = this.removeItem.bind(this);
- this.openContent = this.openContent.bind(this);
- this.openVpnInfo = this.openVpnInfo.bind(this);
- this.callbackVpnInfo = this.callbackVpnInfo.bind(this);
- this.favoriteContent = this.favoriteContent.bind(this);
- this.viewDetails = this.viewDetails.bind(this);
- this.successFetchingImage = this.successFetchingImage.bind(this)
- this.errorFetchingImage = this.errorFetchingImage.bind(this)
- this.insertIntoTypeList = this.insertIntoTypeList.bind(this)
- this.insertIntoContentList = this.insertIntoContentList.bind(this)
- this.initMaxHeight = this.initMaxHeight.bind(this)
- this.shakeAnimation = new Animated.Value(0)
- }
- static navigationOptions = ({ navigation, route }) => {
- return {
- headerShown: false
- }
- }
- componentDidMount() {
- fromDidMount = true;
- varProvider.currentScreen = screenNames.Content
- this.initMaxHeight();
- Dimensions.addEventListener("change", this.initMaxHeight);
- this.rootButtonCallback();
- AsyncStorage.getItem("shouldShowJournalDetail").then((value) => {
- shouldShowJournalDetail = value;
- })
- setProvider.showGuide("iseResourcesGuideShown", screenNames.Content).then((res) => {
- if (res) {
- this.setState({ showGuide: true });
- }
- else {
- this.checkIfVPNCreated();
- }
- })
- varProvider.connectionObserver.subscribe(() => {
- let isConnected = connection.isConnectedFun();
- if (!isConnected) {
- this.showNoInternetError();
- }
- if (isConnected && this.state.errorModal)
- this.rootButtonCallback();
- this.setState({
- isConnected: isConnected,
- refreshTypes: !this.state.refreshTypes
- });
- });
- modalObserver = varProvider.modalClosedObserver.subscribe((data) => {
- if (varProvider.currentScreen === screenNames.Content && data.other) {
- if (this.state.permissionModal || this.state.showGuide || this.state.multiUrlsView) {
- this.setState({
- permissionModal: false,
- showGuide: false
- });
- this.closeActionSheetModal()
- }
- if (varProvider.modalClosedObserver) {
- let resJson = {
- "home": true,
- "other": false,
- "screen": screenNames.Content,
- }
- varProvider.modalClosedObserver.next(resJson);
- }
- }
- })
- conVPNObserver = varProvider.vpnObserver.subscribe((res) => {
- this.setState({
- isVPNConfigAccepted: res
- })
- })
- this._unsubscribe = this.props.navigation.addListener('focus', () => {
- this.isFocused();
- });
- }
- componentWillUnmount() {
- modalObserver.unsubscribe();
- conVPNObserver.unsubscribe();
- this._unsubscribe();
- }
- isFocused() {
- const { params } = this.props.route;
- if (params) {
- //console.log("params::", params);
- // [deep link] if contentType is received from params, then set it as a active biblio type and load content list
- if (menuItemId != params?.menuItemId) { //this condition handle for if user have clicked or received same deeplink url
- if (params?.contentType) {
- currentType = params?.contentType;
- menuItemId = params?.menuItemId;
- currentTitle = params?.cTitle;
- }
- //deeplink use case: when user have already text deeplink tab active and another deeplink with text or without text will come then we'll clear the filters before.
- var tempFilters = this.state.pubFilters;
- tempFilters?.map((item) => {
- item.active = false;
- });
- // [deep link] if searchText is received from params, then set it as a active filter and load content list accordingly
- if (currentType == params?.contentType && params?.searchText) {
- let originalSearchText = params.searchText;
- let trimmedSearchText = originalSearchText.trim();
- let filterJson = [
- {
- "active": true,
- "chipTitle": 'Search text: "' + originalSearchText + '"',
- "value": trimmedSearchText,
- "originalSearchText": originalSearchText
- }
- ];
- this.setState({ pubFilters: filterJson })
- }
- }
- }
- varProvider.currentScreen = currentType ? currentType : screenNames.Content;
- if (varProvider.isContentTabChanged) {
- if (!this.state.showGuide && !fromDidMount) {
- this.checkIfVPNCreated();
- }
- }
- fromDidMount = false;
- AsyncStorage.getItem("contentUpdate").then((value) => {
- let isTabChanged = varProvider.isContentTabChanged;
- if (value == "true") {
- this.drawer.closeDrawer();
- AsyncStorage.setItem("contentUpdate", "false");
- if (!alreadyLoaded) {
- this.rootButtonCallback();
- currentType = null;
- }
- } else {
- if (varProvider.isContentTabChanged) {
- varProvider.isContentTabChanged = false;
- //don't call when component will mount called
- if (!alreadyLoaded) {
- //console.log("alreadyLoaded bgGetContent");
- this.bgGetContent();
- }
- }
- }
- alreadyLoaded = false;
- if (isTabChanged) {
- this.logScreenViewEvent(true);
- if (currentType) {
- this.logScreenViewEvent(false);
- }
- }
- });
- }
- initMaxHeight() {
- var sheight = Dimensions.get('window').height;
- var swidth = Dimensions.get('window').width;
- if (sheight < 480) {
- modalHeight = 250;
- }
- else {
- modalHeight = sheight / 2;
- }
- if (swidth < 480) {
- modalWidth = "100%";
- }
- else if (swidth < 920) {
- modalWidth = "70%";
- }
- else {
- modalWidth = "60%";
- }
- this.setState({ refresh: !this.state.refresh });
- }
- logScreenViewEvent(isFirstTime) {
- if (varProvider.lastTabName != currentType) {
- var openScreen = isFirstTime ? screenNames.Content : currentType;
- varProvider.currentScreen = openScreen;
- let screenViewJson = {
- "name": openScreen,
- "previous": varProvider.lastTabName
- };
- analyticsProvider.logAnalyticsJson("ScreenView", screenViewJson);
- varProvider.lastTabName = openScreen;
- }
- }
- startShake = () => {
- Animated.sequence([
- Animated.timing(this.shakeAnimation, { toValue: 10, duration: 100, useNativeDriver: true }),
- Animated.timing(this.shakeAnimation, { toValue: -10, duration: 100, useNativeDriver: true }),
- Animated.timing(this.shakeAnimation, { toValue: 10, duration: 100, useNativeDriver: true }),
- Animated.timing(this.shakeAnimation, { toValue: 0, duration: 100, useNativeDriver: true })
- ]).start();
- }
- async checkIfVPNCreated() {
- let aOptionalProxy = await storageProvider.getItem("optionalProxy");
- if (aOptionalProxy == "false") {
- varProvider.isVPNOptional = true;
- }
- // if vpn is mandatory then only check and configure vpn
- if (!varProvider.isVPNOptional) {
- if (Platform.OS == "ios") {
- var isVpnCreated = await NativeReachabilityModule.checkIfVPNCreated();
- if (isVpnCreated) {
- AsyncStorage.getItem("isVPNLogged").then((isLogged) => {
- if (isLogged != "true") {
- this.logVPNEvent(true);
- AsyncStorage.setItem("isVPNLogged", "true");
- }
- });
- conProvider.updateProxyDetailsForIos(false);
- this.setState({
- isVPNConfigAccepted: true
- });
- } else {
- // vpn analytics log
- this.logVPNEvent(false);
- this.setState({
- permissionModal: true
- });
- }
- } else {
- if (varProvider.enableProxy) {
- var isVPNConfigured = await VPNModule.isVPNConfigured();
- // console.log("check if vpn created: " + isVPNConfigured);
- if (isVPNConfigured) {
- AsyncStorage.getItem("isVPNLogged").then((isLogged) => {
- if (isLogged != "true") {
- this.logVPNEvent(true);
- AsyncStorage.setItem("isVPNLogged", "true");
- }
- });
- conProvider.updateProxyDetailsForAndroid(false);
- this.setState({
- isVPNConfigAccepted: true
- });
- } else {
- // vpn analytics log
- this.logVPNEvent(false);
- this.setState({
- permissionModal: true
- });
- }
- }
- }
- }
- this.setState({
- isVPNOptional: varProvider.isVPNOptional
- });
- }
- logVPNEvent(isCreated) {
- let vpnJson = {
- "isConfigured": isCreated ? "true" : "false"
- };
- analyticsProvider.logAnalyticsJson("VPN", vpnJson);
- }
- rootButtonCallback() {
- // console.log("rootButtonCallback");
- graphError = ""
- contentList = [];
- this.setState({
- contentLoading: true,
- contentLength: 0,
- refresh: !this.state.refresh,
- pubFilters: [],
- refreshTypes: false,
- accessDenied: false,
- errorModal: false,
- drawerLockMode: "unlocked",
- isButton: false,
- errorLoading: false
- });
- varProvider.drawerLockMode = "unlocked";
- this.startProcess();
- }
- buttonCallback() {
- if (isRootCall) {
- isRootCall = false;
- this.rootButtonCallback();
- } else {
- graphError = ""
- this.setState({
- contentLoading: true,
- contentLength: 0,
- refreshTypes: false,
- accessDenied: false,
- errorModal: false,
- drawerLockMode: "unlocked",
- isButton: false,
- errorLoading: false
- });
- varProvider.drawerLockMode = "unlocked";
- var tempFilters = this.state.pubFilters;
- this.callbackFun(tempFilters);
- }
- }
- bgGetContent() {
- this.startProcess();
- }
- // when internet is not connnected , the button press from errorModal will go to collection for saved actricle
- gotoCollection = () => {
- const { navigate } = this.props.navigation;
- navigate('Collections');
- }
- //first check if email is verified or not
- startProcess() {
- if (connection.isConnectedFun()) {
- insProvider.getUserProfile().then(() => {
- //checking user status
- this.checkUserStatus();
- }).catch((error) => {
- isRootCall = true;
- this.contentError(error, 0);
- this.offlineChecks(true);
- });
- } else {
- //no internet. so, get the value of user status from local storage
- this.offlineChecks(false);
- }
- }
- //get userstatus and accordingly show appropriate message
- checkUserStatus() {
- // console.log("check user status function");
- AsyncStorage.multiGet(["userStatus", "instituteName"]).then((data) => {
- // console.log("asyncstorage multiget");
- // console.log(data);
- var userStatus = data[0][1];
- var instituteName = data[1][1];
- var msg, imagePath;
- imagePath = imageJson.pending_approval;
- if (userStatus == "APPROVED") {
- this.startLoadingContent();
- }
- else if (userStatus == "BLOCKED") {
- msg = translate("USER_ACCOUNT_BLOCKED_ERROR_TITLE", { instituteName: instituteName }) + " " + translate("USER_ACCOUNT_BLOCKED_E_RESOURCE_ERROR_DESCRIPTION");
- this.showError(msg, imagePath);
- }
- else if (userStatus == "ARCHIVED") {
- msg = translate("USER_ACCOUNT_ARCHIVED_ERROR_TITLE", { instituteName: instituteName }) + " " + translate("USER_ACCOUNT_ARCHIVED_E_RESOURCE_ERROR_DESCRIPTION");
- this.showError(msg, imagePath);
- }
- else if (userStatus == "REJECTED") {
- msg = translate("USER_ACCOUNT_REJECTED_ERROR_TITLE", { instituteName: instituteName }) + " " + translate("USER_ACCOUNT_REJECTED_E_RESOURCE_ERROR_DESCRIPTION");
- this.showError(msg, imagePath);
- }
- else if (userStatus == "PENDING") {
- msg = translate("USER_ACCOUNT_PENDING_ERROR_TITLE", { instituteName: instituteName }) + " " + translate("USER_ACCOUNT_PENDING_E_RESOURCE_ERROR_DESCRIPTION");
- this.showError(msg, imagePath);
- }
- else if (userStatus == "EXPIRED") {
- msg = translate("USER_ACCOUNT_EXPIRED_ERROR_TITLE", { instituteName: instituteName }) + " " + translate("USER_ACCOUNT_EXPIRED_E_RESOURCE_ERROR_DESCRIPTION");
- this.showError(msg, imagePath);
- }
- else if (userStatus == "REVOKED") {
- msg = translate("USER_ACCOUNT_REVOKED_ERROR_TITLE", { instituteName: instituteName }) + " " + translate("USER_ACCOUNT_REVOKED_E_RESOURCE_ERROR_DESCRIPTION");
- this.showError(msg, imagePath);
- }
- });
- }
- offlineChecks(isError) {
- AsyncStorage.multiGet(["userStatus", "verifyEmail"]).then((data) => {
- var userStatus = data[0][1];
- var verifyEmail = (data[1][1] == "true");
- if (userStatus && verifyEmail) {
- //if email is verified
- this.offlineUserStatusCheck(userStatus);
- } else {
- //if no value found for verified email or value is false
- //and if offline
- //show no internet message on full screen
- if (isError) {
- //this function is called when some error has occured in fetching either userprofile
- } else {
- this.showNoInternetError();
- }
- }
- });
- }
- showNoInternetError() {
- if (this.drawer)
- this.drawer.closeDrawer();
- var msg = translate("INTERNET_EMPTY");
- var imagePath = imageJson.no_internet;
- var bottomText = translate("INTERNET_EMPTY_DATA1");
- graphError = ""
- this.setState({
- accessDenied: true,
- deniedMessage: msg,
- contentLoading: false,
- contentLength: 0,
- errorModal: true,
- drawerLockMode: "locked-closed",
- imagePath: imagePath,
- isButton: true,
- bottomText: bottomText,
- errorLoading: false,
- multiUrlsView: false
- });
- varProvider.drawerLockMode = "locked-closed";
- }
- //show appropriate message according to user status
- offlineUserStatusCheck(userStatus) {
- var msg, imagePath;
- imagePath = imageJson.pending_approval;
- if (userStatus == "APPROVED") {
- this.startLoadingContent();
- }
- else if (userStatus == "BLOCKED") {
- msg = translate("USER_ACCOUNT_BLOCKED_ERROR_TITLE", { instituteName: varProvider.currentInstituteName }) + " " + translate("USER_ACCOUNT_BLOCKED_E_RESOURCE_ERROR_DESCRIPTION");
- this.showError(msg, imagePath);
- }
- else if (userStatus == "ARCHIVED") {
- msg = translate("USER_ACCOUNT_ARCHIVED_ERROR_TITLE", { instituteName: varProvider.currentInstituteName }) + " " + translate("USER_ACCOUNT_ARCHIVED_E_RESOURCE_ERROR_DESCRIPTION");
- this.showError(msg, imagePath);
- }
- else if (userStatus == "REJECTED") {
- msg = translate("USER_ACCOUNT_REJECTED_ERROR_TITLE", { instituteName: varProvider.currentInstituteName }) + " " + translate("USER_ACCOUNT_REJECTED_E_RESOURCE_ERROR_DESCRIPTION");
- this.showError(msg, imagePath);
- }
- else if (userStatus == "PENDING") {
- msg = translate("USER_ACCOUNT_PENDING_ERROR_TITLE", { instituteName: varProvider.currentInstituteName }) + " " + translate("USER_ACCOUNT_PENDING_E_RESOURCE_ERROR_DESCRIPTION");
- this.showError(msg, imagePath);
- }
- else if (userStatus == "EXPIRED") {
- msg = translate("USER_ACCOUNT_EXPIRED_ERROR_TITLE", { instituteName: varProvider.currentInstituteName }) + " " + translate("USER_ACCOUNT_EXPIRED_E_RESOURCE_ERROR_DESCRIPTION");
- this.showError(msg, imagePath);
- }
- else if (userStatus == "REVOKED") {
- msg = translate("USER_ACCOUNT_REVOKED_ERROR_TITLE", { instituteName: varProvider.currentInstituteName }) + " " + translate("USER_ACCOUNT_REVOKED_E_RESOURCE_ERROR_DESCRIPTION");
- this.showError(msg, imagePath);
- }
- }
- startLoadingContent() {
- //get menu item list
- this.getMenuItemsList().then((data) => {
- }).catch((error) => {
- if (connection.isConnectedFun()) {
- this.contentError(error, 0);
- } else {
- this.showNoInternetError();
- }
- });
- }
- insertIntoContentList(data, tempJson, localRandomId, isGraph) {
- console.log("insertIntoContentList==========", data?.length, tempJson, localRandomId, isGraph);
- if (localRandomId == currentRandomId) {
- if (tempJson.type == currentType) {
- this.contentSuccessPush(data, tempJson, isGraph);
- }
- } else {
- console.log("insertIntoContentList else==========",);
- }
- setTimeout(() => {
- isInfiniteOn = false;
- }, 400);
- }
- //load institute content
- loadContentList(tempJson) {
- //console.log("loadContentList=================", tempJson);
- currentRandomId = apiProvider.generateUUID();
- var localRandomId = currentRandomId;
- if (tempJson.type == staticConfig.favorite) {
- //if filter is applied then directly get the result via graph query
- if (!tempJson.isFilter) {
- this.getContentSql(tempJson, localRandomId).then(() => {
- this.getFavContentGraph(tempJson, localRandomId);
- });
- } else {
- this.getFavContentGraph(tempJson, localRandomId);
- }
- }
- else if (tempJson.type == staticConfig.customInstituteContent || tempJson.type == staticConfig.customLink) {
- if (!tempJson.isFilter) {
- this.getContentSql(tempJson, localRandomId).then(() => {
- this.getContentItemsofMenuItemforUser(tempJson, localRandomId);
- });
- } else {
- this.getContentItemsofMenuItemforUser(tempJson, localRandomId);
- }
- }
- else {
- //if filter is applied then directly get the result via graph query
- if (!tempJson.isFilter) {
- this.getContentSql(tempJson, localRandomId).then(() => {
- //console.log("getContentGraph1", tempJson, localRandomId);
- this.getContentGraph(tempJson, localRandomId);
- });
- } else {
- // console.log("getContentGraph2");
- this.getContentGraph(tempJson, localRandomId);
- }
- }
- }
- getContentSql(tempJson, localRandomId) {
- return new Promise((resolve) => {
- conProvider.getContentSql(tempJson).then((data) => {
- if (data.length > 0) {
- console.log("getContentSql", data?.length)
- this.insertIntoContentList(data, tempJson, localRandomId, false);
- }
- resolve();
- }).catch((error) => {
- resolve();
- console.log("getContentSql", error)
- });
- });
- }
- getFavContentGraph(tempJson, localRandomId) {
- conProvider.getFavContentListGraph(tempJson).then((data) => {
- console.log("get fav content list then");
- this.insertIntoContentList(data, tempJson, localRandomId, true)
- }).catch((error) => {
- // console.log("get fav content list catch");
- // console.log(error);
- if (localRandomId == currentRandomId) {
- if (tempJson.type == currentType) {
- if (error == "ACCESSDENIED_EXPIRY") {
- var msg = translate("USER_ACCOUNT_EXPIRED_ERROR_TITLE", { instituteName: varProvider.currentInstituteName }) + " " + translate("USER_ACCOUNT_EXPIRED_E_RESOURCE_ERROR_DESCRIPTION");
- var imagePath = imageJson.pending_approval;
- this.showError(msg, imagePath);
- } else {
- this.contentError(error, tempJson.skip);
- }
- }
- }
- isInfiniteOn = false;
- });
- }
- getContentGraph(tempJson, localRandomId) {
- console.log("getContentGraph", tempJson, localRandomId);
- conProvider.getContentListGraph(tempJson).then((data) => {
- this.insertIntoContentList(data, tempJson, localRandomId, true)
- console.log("getContentGraph get content list then", data?.length, tempJson, localRandomId, currentRandomTypeId);
- // console.log(data);
- }).catch((error) => {
- // console.log("get content list catch");
- // console.log(error);
- if (localRandomId == currentRandomId) {
- if (tempJson.type == currentType) {
- if (error == "ACCESSDENIED_EXPIRY") {
- var msg = translate("USER_ACCOUNT_EXPIRED_ERROR_TITLE", { instituteName: varProvider.currentInstituteName }) + " " + translate("USER_ACCOUNT_EXPIRED_E_RESOURCE_ERROR_DESCRIPTION");
- var imagePath = imageJson.pending_approval;
- this.showError(msg, imagePath);
- } else {
- this.contentError(error, tempJson.skip);
- }
- }
- }
- isInfiniteOn = false;
- });
- }
- getContentItemsofMenuItemforUser(tempJson, localRandomId) {
- conProvider.getContentItemsofMenuItemforUser(tempJson).then((data) => {
- this.insertIntoContentList(data, tempJson, localRandomId, true)
- // console.log(data);
- }).catch((error) => {
- // console.log("get content list catch");
- // console.log(error);
- if (localRandomId == currentRandomId) {
- if (tempJson.type == currentType) {
- if (error == "ACCESSDENIED_EXPIRY") {
- var msg = translate("USER_ACCOUNT_EXPIRED_ERROR_TITLE", { instituteName: varProvider.currentInstituteName }) + " " + translate("USER_ACCOUNT_EXPIRED_E_RESOURCE_ERROR_DESCRIPTION");
- var imagePath = imageJson.pending_approval;
- this.showError(msg, imagePath);
- } else {
- this.contentError(error, tempJson.skip);
- }
- }
- }
- isInfiniteOn = false;
- });
- }
- //process content data
- contentSuccessPush(data, tempJson, isGraph) {
- console.log("contentSuccessPush::::::", data?.length, tempJson, isGraph);
- if (data.length < 30 && isGraph) {
- noMoreData = true;
- }
- var loadedId = [];
- if (currentType == staticConfig.customLink || currentType == staticConfig.favorite) {
- for (var k = 0; k < contentList.length; k++) {
- if (contentList[k].isFetched) {
- loadedId.push(contentList[k].id);
- }
- }
- }
- const { params } = this.props.route;
- console.log("tempJson.skip", params);
- if (tempJson.skip == 0) {
- console.log("tempJson.skip");
- contentList = [];
- }
- for (var i = 0; i < data.length; i++) {
- var initials = data[i].title.charAt(0).toUpperCase();
- var isFetched = false;
- if (loadedId.length != 0) {
- if (loadedId.indexOf(data[i].id) != -1) {
- isFetched = true;
- }
- }
- var type = data[i].type;
- var issn = data[i].issn;
- var eissn = data[i].eissn;
- var cid = data[i].contentId;
- var url = data[i].url;
- var libCoverImage = data[i].libCoverImage;
- var contentUpdatedAt = data[i].contentUpdatedAt
- var contentImage = this.loadContentImageFast(issn, eissn, type, cid, libCoverImage, contentUpdatedAt);
- var phImage = conProvider.getBgContentImage(type, url);
- var smallImage = conProvider.getContentImageSmall(type, data);
- var bgColor = conProvider.getContentBg(type);
- var multiUrls = data[i].multiUrls ? JSON.parse(data[i].multiUrls) : null
- contentList.push({
- "id": data[i].id,
- "title": data[i].title,
- "libDescription": data[i].libDescription,
- "url": url,
- "type": type,
- "publisherName": data[i].publisherName,
- "isFavorite": data[i].isFavorite,
- "image": contentImage,
- "phImage": phImage,
- "smallImage": smallImage,
- "isFetched": isFetched,
- "issn": issn,
- "eissn": eissn,
- "initials": initials,
- "bgColor": bgColor,
- "multiUrls": multiUrls,
- "customInsContentId": data[i].customInsContentId,
- "contentType": data[i].contentType,
- });
- }
- isListFromGraph = isGraph;
- console.log("contentList::===", contentList?.length);
- graphError = ""
- this.setState({
- refresh: !this.state.refresh,
- contentLoading: false,
- footerLoading: false,
- errorLoading: false,
- contentLength: contentList.length,
- accessDenied: false,
- errorModal: false,
- drawerLockMode: "unlocked"
- });
- varProvider.drawerLockMode = "unlocked";
- }
- //error to show when content fetching fails
- contentError(error, skipVal) {
- if (skipVal > pagingCount - 1) {
- //error while fetching next 30 article
- graphError = ""
- this.setState({ contentLoading: false, footerLoading: false, errorLoading: false, contentLength: contentList.length });
- } else {
- connection.getGraphError(error).then((data) => {
- graphError = data
- this.setState({
- errorLoading: true,
- contentLoading: false,
- footerLoading: false,
- contentLength: contentList.length,
- accessDenied: false,
- errorModal: false,
- drawerLockMode: "unlocked"
- });
- })
- varProvider.drawerLockMode = "unlocked";
- }
- }
- errorFetchingImage(contentItem) {
- for (var i = 0; i < contentList.length; i++) {
- if (contentList[i].id == contentItem.id) {
- contentList[i].isFetched = false;
- break;
- }
- }
- this.setState({ refresh: !this.state.refresh });
- }
- successFetchingImage(contentItem) {
- for (var i = 0; i < contentList.length; i++) {
- if (contentList[i].id == contentItem.id) {
- contentList[i].isFetched = true;
- break;
- }
- }
- this.setState({ refresh: !this.state.refresh });
- }
- loadContentImageFast(issn, eissn, contentType, cid, libCoverImage, contentUpdatedAt) {
- var url;
- if (contentType == staticConfig.database) {
- if (libCoverImage === null) {
- url = config.coverUrl + contentType.toLowerCase() + "/" + cid.concat(contentUpdatedAt ? "?v=" + contentUpdatedAt : "");
- } else {
- url = libCoverImage;
- }
- }
- else if (contentType == staticConfig.link) {
- url = config.s3AppSettingBucket + "institute/" + varProvider.currentInstituteId + "/contentItem/contentitem_" + cid;
- }
- else {
- if (issn) {
- url = config.coverUrl + contentType.toLowerCase() + "/" + issn + ".jpg".concat(contentUpdatedAt ? "?v=" + contentUpdatedAt : "");
- } else if (eissn) {
- url = config.coverUrl + contentType.toLowerCase() + "/" + eissn + ".jpg".concat(contentUpdatedAt ? "?v=" + contentUpdatedAt : "");
- } else {
- url = conProvider.getContentImage(contentType);
- }
- }
- return url;
- }
- loadContentImage(contentItem) {
- // console.log(contentItem);
- var path = RNFetchBlob.fs.dirs.DocumentDir + "/" + contentItem.id + ".jpg";
- RNFetchBlob.fs.exists(path).then((exist) => {
- // console.log("content image exist: " + exist);
- if (exist) {
- for (var i = 0; i < contentList.length; i++) {
- if (contentList[i].id == contentItem.id) {
- contentList[i].image = "file://" + path;
- break;
- }
- }
- this.setState({ refresh: !this.state.refresh });
- } else {
- var issnOrIsbn;
- if (contentItem.issn) {
- issnOrIsbn = contentItem.issn;
- this.writeContentImage(contentItem, issnOrIsbn, true);
- } else if (contentItem.eissn) {
- issnOrIsbn = contentItem.eissn;
- this.writeContentImage(contentItem, issnOrIsbn, false);
- }
- }
- });
- }
- writeContentImage(contentItem, issnOrIsbn, isIssn) {
- // console.log("write content image");
- // let dirs = RNFetchBlob.fs.dirs;
- var path = RNFetchBlob.fs.dirs.DocumentDir + "/" + contentItem.id + ".jpg";
- var url = config.coverUrl + contentItem.type.toLowerCase() + "/" + issnOrIsbn + ".jpg";
- // console.log(url);
- RNFetchBlob
- .config({
- fileCache: true,
- // by adding this option, the temp files will have a file extension
- path: path
- })
- .fetch('GET', url, {
- //some headers ..
- })
- .then((res) => {
- // the temp file path with file extension `png`
- // console.log(res);
- // console.log('The file saved to ', res.path());
- if (res["respInfo"] && res["respInfo"]["headers"]) {
- var types = colProvider.findValueOfProperty(res["respInfo"]["headers"], "content-type");
- if (types.length != 0) {
- var ctype = types[0];
- if (ctype.indexOf("xml") == -1 && ctype.indexOf("html") == -1) {
- var aPath = "file://" + res.path();
- for (var i = 0; i < contentList.length; i++) {
- if (contentList[i].id == contentItem.id) {
- contentList[i].image = "file://" + aPath;
- break;
- }
- }
- this.setState({ refresh: !this.state.refresh });
- }
- }
- }
- })
- }
- createContentTitleList(data) {
- var tempList = []
- for (var i = 0; i < data.length; i++) {
- tempList.push({
- id: data[i].id,
- title: data[i].title,
- type: data[i].type,
- iconName: (data[i].type.toUpperCase() == staticConfig.customLink || data[i].type.toUpperCase() == staticConfig.customInstituteContent || data[i].type.toUpperCase() == staticConfig.filtered) ? "icon_user_folder" : "icon_" + data[i].type.toLowerCase(),
- active: false,
- isExpanded: false,
- containsContent: data[i].containsContent,
- childMenuItems: data[i].childMenuItems ? this.createContentTitleList(JSON.parse(data[i].childMenuItems), data[i].type) : null
- });
- }
- return tempList;
- }
- maintainTypeListState = (typeList) => {
- for (var m = 0; m < typeList.length; m++) {
- if (typeList[m].active) {
- if (typeList[m].childMenuItems?.length > 0) {
- let res = this.maintainTypeListState(typeList[m].childMenuItems)
- if (res != null) {
- return res
- }
- else {
- return typeList[m]
- }
- }
- else {
- return typeList[m]
- }
- }
- }
- return null
- }
- // inserting the bibilolist data in typeList
- async insertIntoTypeList(data, localRandomId, shouldFetchContentList) {
- if (localRandomId == currentRandomTypeId) {
- const { params } = this.props.route;
- var activeItem = await this.maintainTypeListState(typeList)
- typeList = [];
- typeList = this.createContentTitleList(data);
- // icon_user_folder
- this.getBiblioContentList().then((data) => {
- for (var i = 0; i < data.length; i++) {
- if (data[i].type == staticConfig.favorite) {
- typeList.push({
- id: "fav_item",
- title: data[i].title,
- type: data[i].type,
- iconName: "icon_" + data[i].type.toLowerCase(),
- active: false,
- containsContent: true,
- });
- console.log("getBiblioContentList::::", params, params?.contentType);
- // if there is fav content item present and there is not any active item, then make fav section as active and show content
- if (data[i].count != 0 && activeItem == null && !params?.contentType) {
- typeList[typeList.length - 1].active = true;
- currentType = typeList[typeList.length - 1].type;
- currentTitle = typeList[typeList.length - 1].title;
- menuItemId = typeList[typeList.length - 1].id
- activeItem = typeList[typeList.length - 1];
- console.log("first::::", params);
- }
- else if (params?.contentType) { //deeplink use case when user have fav and without fav item set to active tab item
- currentType = params?.contentType;
- currentTitle = params?.cTitle;
- menuItemId = params?.menuItemId;
- activeItem = {
- id: params?.menuItemId,
- title: params?.cTitle,
- };
- console.log("second::::", params);
- }
- favIndex = typeList.length - 1;
- break;
- }
- }
- //if typelist length is less than 2 then there won't be 2nd index in type list array
- if (currentType == "" || currentTitle == "" || currentType == null) {
- for (var m = 0; m < typeList.length; m++) {
- typeList[m].active = false;
- }
- if (typeList[0].containsContent)
- typeList[0].active = true;
- typeList[0].isExpanded = true;
- currentType = typeList[0].type;
- currentTitle = typeList[0].title;
- menuItemId = typeList[0].id
- }
- else {
- this.updateTempList(typeList, activeItem, true)
- currentTitle = activeItem == null ? typeList[0].title : activeItem.title;
- menuItemId = activeItem == null ? typeList[0].id : activeItem.id
- }
- var tempFilters = this.state.pubFilters;
- console.log("shouldFetchContentList:::::", shouldFetchContentList)
- if (shouldFetchContentList) {
- this.callbackFun(tempFilters, true);
- this.clearParams();
- // if (!params?.contentType) {
- // this.callbackFun(tempFilters, true);
- // // this.clearParams();
- // console.log("if:::::")
- // } else {
- // this.callbackFun(tempFilters);
- // console.log("else:::::")
- // }
- }
- });
- }
- }
- //get biblio content list
- getBiblioContentList() {
- return new Promise((resolve, reject) => {
- var shouldFetchContentList = true;
- conProvider.getBiblioSql().then((data) => {
- if (data.length > 0) {
- shouldFetchContentList = false;
- resolve(data);
- }
- conProvider.getBiblioListGraph().then((resJson) => {
- //updating the typeList
- if (resJson.length > 0) {
- resolve(resJson);
- } else {
- if (shouldFetchContentList)
- reject();
- }
- }).catch((error) => {
- if (shouldFetchContentList)
- reject(error);
- });
- }).catch(() => {
- reject();
- });
- });
- }
- //get biblio content list
- getMenuItemsList() {
- currentRandomTypeId = apiProvider.generateUUID();
- var localRandomId = currentRandomTypeId;
- return new Promise((resolve, reject) => {
- var shouldFetchContentList = true;
- conProvider.getMenuItemSql().then((data) => {
- if (data.length > 0) {
- this.insertIntoTypeList(data, localRandomId, true);
- shouldFetchContentList = false;
- resolve(data);
- }
- conProvider.getMenuItemsGraph().then((resJson) => {
- //updating the typeList
- if (resJson.length > 0) {
- this.insertIntoTypeList(resJson, localRandomId, shouldFetchContentList);
- resolve(resJson);
- } else {
- if (shouldFetchContentList)
- reject();
- }
- }).catch((error) => {
- if (shouldFetchContentList)
- reject(error);
- });
- }).catch(() => {
- reject();
- });
- });
- }
- //root error message on full screen
- showError(msg, imagePath) {
- this.drawer.closeDrawer();
- graphError = ""
- this.setState({
- accessDenied: true,
- deniedMessage: msg,
- contentLoading: false,
- contentLength: 0,
- errorModal: true,
- drawerLockMode: "locked-closed",
- isButton: false,
- imagePath: imagePath,
- errorLoading: false
- });
- varProvider.drawerLockMode = "locked-closed";
- }
- openMenu() {
- this.drawer.openDrawer();
- }
- changeView() {
- this.setState({ isCardView: !this.state.isCardView });
- }
- callbackFun(activeFilters, isBgContent) {
- var isFilter = false;
- var appliedFilter = [];
- var topKey, bottomKey, dataKey, dataValue;
- for (var i = 0; i < activeFilters.length; i++) {
- if (activeFilters[i].active) {
- isFilter = true;
- // if (i == 0) {
- topKey = "$searchText: String";
- bottomKey = "libTitle_contains: $searchText";
- dataKey = "searchText";
- dataValue = activeFilters[0].value;
- // }
- appliedFilter.push({
- "topKey": topKey,
- "bottomKey": bottomKey,
- "dataKey": dataKey,
- "dataValue": dataValue,
- });
- }
- }
- if (appliedFilter.length == 0) {
- this.setState({
- "isFilter": false,
- appliedFilter: appliedFilter
- });
- } else {
- this.setState({
- "isFilter": true,
- appliedFilter: appliedFilter
- });
- }
- var tempJson = {
- "isFilter": isFilter,
- "appliedFilter": appliedFilter,
- "skip": 0,
- "menuItemId": menuItemId
- }
- this.initContentList(tempJson, activeFilters, isBgContent);
- }
- initContentList(tempJson, activeFilters, isBgContent) {
- //console.log("initContentList::::", isBgContent);
- if (!isBgContent) {
- //console.log("isBgContent", isBgContent, contentList?.length);
- contentList = [];
- graphError = ""
- this.setState({
- contentLoading: true,
- contentLength: 0,
- pubFilters: activeFilters,
- accessDenied: false,
- errorModal: false,
- drawerLockMode: "unlocked",
- refreshTypes: !this.state.refreshTypes,
- errorLoading: false
- });
- varProvider.drawerLockMode = "unlocked";
- noMoreData = false;
- } else {
- //console.log("isBgContent else", isBgContent, contentList.length);
- noMoreData = false;
- //fetch content list from sqlite and compare it with new list fetched via graph query
- //if there isn't any change than no need to reset content list
- if (contentList.length != 0 && connection.isConnectedFun()) {
- //console.log("noMoreData");
- //return function here so that next lines does not execute
- tempJson["type"] = currentType;
- tempJson["shouldDelete"] = "check";
- tempJson["first"] = contentList.length;
- return this.loadContentList(tempJson);
- }
- }
- tempJson["type"] = currentType;
- tempJson["shouldDelete"] = "true";
- tempJson["first"] = pagingCount;
- if (connection.isConnectedFun()) {
- //console.log("connection.isConnectedFun");
- this.loadContentList(tempJson);
- }
- }
- callbackFavorite(isFavorite) {
- if (currentType == staticConfig.favorite && !isFavorite) {
- this.removeItem(cloneIt);
- } else {
- cloneIt.isFavorite = isFavorite;
- this.setState({ refresh: !this.state.refresh });
- }
- }
- openFilters() {
- const { navigate } = this.props.navigation;
- navigate('ConFilters', { "callbackFun": this.callbackFun, "pubFilters": this.state.pubFilters, "contentType": currentType });
- }
- openContent(item) {
- // console.log(item);
- cloneIt = item;
- const { navigate } = this.props.navigation;
- if (item.type == staticConfig.journal) {
- if (this.state.isVPNConfigAccepted || this.state.isVPNOptional) {
- if ((item.issn || item.eissn) && shouldShowJournalDetail == "true") {
- navigate('JournalArticles', { "journalItem": item, "callbackFavorite": this.callbackFavorite, "refScreen": varProvider.currentScreen });
- } else {
- if (connection.isConnectedFun()) {
- var pubApiUrl = item.url;
- if (pubApiUrl.includes(config.pubApiShort)) {
- pubApiUrl = pubApiUrl.replace(/:token/g, varProvider.lastToken);
- }
- navigate('BrowserView', { "url": pubApiUrl, "refScreen": varProvider.currentScreen });
- this.logContentOpenEvent(item.type, item.id)
- } else {
- Toast.showShortCenter(translate("PLEASE_CONNECT"));
- }
- }
- } else {
- addVPNPopup = true;
- this.setState({
- permissionModal: true
- });
- }
- }
- else {
- if (connection.isConnectedFun()) {
- if (this.state.isVPNConfigAccepted || this.state.isVPNOptional) {
- if (item.url) {
- // checking if multiUrl is present for database only
- if (item.multiUrls !== null && item.multiUrls.length > 0 && item.type === staticConfig.database) {
- if (item.multiUrls.length === 1) {
- this.openContentUrl(item.multiUrls[0].url, false, item.type, item.id) // false represent that there are no multi urls OR only one multi url
- }
- else {
- multiUrlsList = []
- item.multiUrls.map((multiUrlsitem) => {
- multiUrlsList.push({ title: multiUrlsitem.resourceGroup.name, onPressFun: this.openContentUrl.bind(this, multiUrlsitem.url, true, item.type, item.id) }) // true represent that there are more then one multiUrl
- })
- this.setState({ multiUrlsView: true })
- }
- }
- else {
- this.openContentUrl(item.url, false, item.type, item.id) // false represent that there are no multi urls OR only one multi url
- }
- }
- } else {
- addVPNPopup = true;
- this.setState({
- permissionModal: true
- });
- }
- } else {
- Toast.showShortCenter(translate("PLEASE_CONNECT"));
- }
- }
- }
- openContentUrl = (url, isMultiUrl, type, id) => {
- const { navigate } = this.props.navigation;
- if (isMultiUrl) {
- this.setState({ multiUrlsView: false })
- multiUrlsList = []
- }
- var pubApiUrl = url
- if (pubApiUrl.includes(config.pubApiShort)) {
- pubApiUrl = pubApiUrl.replace(/:token/g, varProvider.lastToken);
- }
- navigate('BrowserView', { "url": pubApiUrl, "refScreen": varProvider.currentScreen });
- this.logContentOpenEvent(type, id)
- }
- logContentOpenEvent(type, eResourceId) {
- let contentOpenJson = {
- "type": type,
- "eResourceId": eResourceId
- }
- analyticsProvider.logAnalyticsJson("eResourceOpen", contentOpenJson);
- }
- logPdfScreenViewEvent(isNavigatingBack) {
- let screenViewJson = {
- "name": isNavigatingBack ? currentType : screenNames.PDFView,
- "previous": isNavigatingBack ? screenNames.PDFView : currentType
- };
- analyticsProvider.logAnalyticsJson("ScreenView", screenViewJson);
- }
- iosPdfEvent(pdfObject) {
- const viewerDismissedSubscription = pdfObject.addListener(
- 'ViewerWillDismiss',
- (highlightObject) => {
- // console.log("ViewerWillDismiss Collection screen");
- // console.log(highlightObject);
- viewerDismissedSubscription.remove();
- this.logPdfScreenViewEvent(true);
- varProvider.currentScreen = screenNames.Content;
- }
- );
- }
- removeFilter(item) {
- var tempFilters = this.state.pubFilters;
- for (var i = 0; i < tempFilters.length; i++) {
- if (item.value == tempFilters[i].value) {
- tempFilters[i].active = false;
- break;
- }
- }
- this.callbackFun(tempFilters);
- }
- viewDetails(item) {
- const { navigate } = this.props.navigation;
- navigate('ContentDescription', { "item": item, "openContent": this.openContent });
- }
- favoriteContent(item) {
- if (connection.isConnectedFun()) {
- var action;
- if (item.isFavorite) {
- item.isFavorite = false;
- action = "UNFAVORITE";
- }
- else {
- item.isFavorite = true;
- action = "FAVORITE";
- }
- var secondArg = false;
- var tempJson = {};
- var contentIds = [];
- var id = item.contentType == staticConfig.customInstituteContent ? item.customInsContentId : item.id
- contentIds.push(id);
- tempJson["contentIds"] = contentIds;
- tempJson["action"] = action;
- tempJson["isFavorite"] = item.isFavorite;
- tempJson["type"] = item.type;
- if (currentType == staticConfig.favorite && !item.isFavorite) {
- this.removeItem(item);
- }
- conProvider.favoriteContentGraph(tempJson, secondArg).then((data) => {
- if (item.type == staticConfig.journal && item.isFavorite) {
- jaProvider.cacheJournalArticles();
- }
- }).catch((error) => {
- });
- this.setState({ refresh: !this.state.refresh });
- }
- else {
- Toast.showShortCenter(translate("PLEASE_CONNECT"));
- }
- }
- removeItem(item) {
- for (var i = 0; i < contentList.length; i++) {
- if (contentList[i].id == item.id) {
- contentList.splice(i, 1);
- break;
- }
- }
- this.setState({ refresh: !this.state.refresh });
- }
- FlatListItemSeparator = () => {
- return (
- <View
- style={styles.contentBottomBorder}
- />
- );
- }
- // to handle scroll pagination to load more content
- handleLoadMore = () => {
- if (contentList.length > pagingCount - 1) {
- if (!noMoreData) {
- if (!isInfiniteOn) {
- this.setState({ footerLoading: true });
- isInfiniteOn = true;
- var skipCount = contentList.length;
- var tempJson = {
- "isFilter": this.state.isFilter,
- "appliedFilter": this.state.appliedFilter,
- "skip": skipCount,
- "first": pagingCount,
- "type": currentType,
- "shouldDelete": "false",
- "menuItemId": menuItemId
- }
- console.log("handleLoadMore", tempJson);
- this.loadContentList(tempJson);
- }
- }
- } else {
- if (isListFromGraph)
- noMoreData = true;
- }
- };
- closeGuide = () => {
- this.setState({ showGuide: false })
- setProvider.closeGuide("iseResourcesGuideShown");
- }
- hideModalCallback = () => {
- this.checkIfVPNCreated()
- }
- callbackVpnInfo() {
- this.setState({
- permissionModal: true
- });
- }
- openVpnInfo() {
- this.setState({
- permissionModal: false
- });
- const { navigate } = this.props.navigation;
- navigate('VpnInfo', { "isModal": true, "shouldShowDNSSetting": false, "callbackVpnInfo": this.callbackVpnInfo, "refScreen": screenNames.Content });
- }
- renderFooter = () => {
- if (!this.state.footerLoading) return null;
- return (
- <View style={styles.loaderIndicator}>
- <Spinner style={styles.spinner} size={22} type="Circle" color="#333" />
- </View>
- );
- };
- renderEmpty = () => {
- console.log("renderEmpty:::", currentType, currentTitle, contentList?.length);
- var imagePath, isButton, buttonText, buttonFunction, title, text = ""
- if (currentType == staticConfig.favorite) {
- imagePath = imageJson.fav_content_empty;
- title = this.state.isFilter ? translate("FAV_FILTER_EMPTY") : translate("FC_EMPTY");
- text = this.state.isFilter ? translate("FAV_FILTER_EMPTY_DATA") : translate("FC_EMPTY_DATA1");
- isButton = true
- buttonText = translate("VIEW_MORE")
- buttonFunction = this.openMenu;
- // we have to change this , so i have not included it in en.json
- } else if (currentType == staticConfig.database) {
- imagePath = imageJson.content_empty;
- title = this.state.isFilter ? translate("CONTENT_DATABASE_FILTER_EMPTY") : translate("CONTENT_DATABASE_EMPTY");
- text = this.state.isFilter ? translate("CONTENT_DATABASE_FILTER_EMPTY_DATA") : translate("CONTENT_DATABASE_EMPTY_DATA", { currentTitle: currentTitle });
- }
- else if (currentType == staticConfig.journal) {
- imagePath = imageJson.content_empty;
- title = this.state.isFilter ? translate("CONTENT_JOURNAL_FILTER_EMPTY") : translate("CONTENT_JOURNAL_EMPTY");
- text = this.state.isFilter ? translate("CONTENT_JOURNAL_FILTER_EMPTY_DATA") : translate("CONTENT_JOURNAL_EMPTY_DATA", { currentTitle: currentTitle });
- }
- else if (currentType == staticConfig.ebook) {
- imagePath = imageJson.content_empty;
- title = this.state.isFilter ? translate("CONTENT_EBOOK_FILTER_EMPTY") : translate("CONTENT_EBOOK_EMPTY");
- text = this.state.isFilter ? translate("CONTENT_EBOOK_FILTER_EMPTY_DATA") : translate("CONTENT_EBOOK_EMPTY_DATA", { currentTitle: currentTitle });
- }
- else if (currentType == staticConfig.customInstituteContent) {
- imagePath = imageJson.content_empty;
- title = this.state.isFilter ? translate("CONTENT_CUSTOMINSCON_FILTER_EMPTY") : translate("CONTENT_CUSTOMINSCON_EMPTY")
- text = this.state.isFilter ? translate("CONTENT_CUSTOMINSCON_FILTER_EMPTY_DATA") : translate("CONTENT_CUSTOMINSCON_EMPTY_DATA", { currentTitle: currentTitle })
- }
- else if (currentType == staticConfig.customLink) {
- imagePath = imageJson.content_empty;
- title = this.state.isFilter ? translate("CONTENT_CUSTOMLINK_FILTER_EMPTY") : translate("CONTENT_CUSTOMLINK_EMPTY")
- text = this.state.isFilter ? translate("CONTENT_CUSTOMLINK_FILTER_EMPTY_DATA") : translate("CONTENT_CUSTOMLINK_EMPTY_DATA", { currentTitle: currentTitle })
- }
- else if (currentType == staticConfig.filtered) {
- imagePath = imageJson.content_empty;
- title = this.state.isFilter ? translate("CONTENT_FILTERED_FILTER_EMPTY") : translate("CONTENT_FILTERED_EMPTY")
- text = this.state.isFilter ? translate("CONTENT_FILTERED_FILTER_EMPTY_DATA") : translate("CONTENT_FILTERED_EMPTY_DATA", { currentTitle: currentTitle })
- }
- return (
- <View>
- {this.state.errorLoading ?
- <View>
- <EmptyScreen
- imagePath={graphError && graphError.success == undefined ? imageJson.httpError_img : imageJson.something_wrong_here}
- Title={graphError ? graphError.shortDesc : translate("TECHNICAL_EMPTY")}
- Text={graphError ? graphError.desc : translate("TECHNICAL_EMPTY_DATA1")}
- isButton={true}
- buttonText={translate("SU_EMPTY")}
- buttonCallback={this.buttonCallback}
- />
- </View>
- :
- this.state.isFilter ?
- <View>
- <EmptyScreen
- imagePath={imageJson.no_search_result}
- Title={title}
- Text={text}
- />
- </View>
- :
- <View>
- <EmptyScreen
- imagePath={imagePath}
- Title={title}
- Text={text}
- isButton={isButton}
- buttonText={buttonText}
- buttonCallback={buttonFunction}
- />
- </View>
- }
- </View>
- );
- }
- renderEmptyDrawer = () => {
- return (
- <View>
- {this.state.errorLoading ?
- <View>
- <Text style={{ textAlign: 'center', color: '#000' }}>{translate("BIBLIO_FAILED")}</Text>
- </View>
- :
- <View style={styles.loaderIndicator}>
- <Spinner style={styles.spinner} size={22} type="Circle" color="#333" />
- </View>
- }
- </View>
- );
- }
- downloadFromLink = (item, retry) => {
- const { navigate } = this.props.navigation;
- this.setState({ isLinkLoading: true });
- conProvider.getDownloadURlFromS3(item).then((url) => {
- this.setState({ isLinkLoading: false });
- navigate('BrowserView', { "url": url, "refScreen": varProvider.currentScreen });
- this.logContentOpenEvent(item.type, item.id)
- }).catch((error) => {
- if (retry) {
- this.downloadFromLink(item, false)
- }
- else {
- this.setState({ isLinkLoading: false });
- setTimeout(() => {
- Toast.showShortCenter(translate("ERROR_UNKNOWN_DESC"));
- }, 400)
- }
- });
- }
- checkS3Url = (item) => {
- if (this.state.isVPNConfigAccepted || this.state.isVPNOptional) {
- if (item.url.includes("s3://")) {
- this.downloadFromLink(item, true)
- } else {
- this.openContent(item)
- }
- }
- else {
- addVPNPopup = true;
- this.setState({
- permissionModal: true
- });
- }
- }
- _renderContentCard = ({ item }) => (
- <ContentListView
- key={item.id}
- title={item.title}
- libDescription={item.libDescription}
- type={item.type}
- publisherName={item.publisherName}
- phImage={item.phImage}
- image={item.image}
- isFetched={item.isFetched}
- smallImage={item.smallImage}
- isFavorite={item.isFavorite}
- currentType={currentType}
- isVPNConfigAccepted={this.state.isVPNConfigAccepted || this.state.isVPNOptional}
- data={item}
- openContent={item.type == "LINK" ? this.checkS3Url : this.openContent}
- favoriteContent={this.favoriteContent}
- successFetchingImage={this.successFetchingImage}
- errorFetchingImage={this.errorFetchingImage}
- viewDetails={this.viewDetails}
- />
- )
- hideActionSheetModal = () => {
- multiUrlsList = []
- this.setState({ multiUrlsView: false });
- }
- closeActionSheetModal = () => {
- multiUrlsList = []
- this.setState({ multiUrlsView: false });
- }
- render() {
- var renderFavFooter = (typeList && typeList.length > 0)
- ?
- <TouchableOpacity
- activeOpacity={0.7}
- style={drawerStyles.favMenuItem}
- onPress={() => this.menuItemPress(typeList[favIndex], true)}
- >
- <View style={drawerStyles.menuLeftIconView}>
- <CustomIcons style={[drawerStyles.menuLeftIcon, typeList[favIndex]?.active && drawerStyles.menuLeftIconActive]} name="icon_fav_content" />
- </View>
- <Text style={[drawerStyles.menuItemText, typeList[favIndex]?.active && drawerStyles.menuItemTextDefault]}>{typeList[favIndex]?.title}</Text>
- <View style={drawerStyles.menuItemRightView}>
- </View>
- </TouchableOpacity>
- :
- null;
- var menu = <SafeAreaView
- edges={['right', 'top', 'left']}
- style={drawerStyles.mainContainer}>
- <View style={drawerStyles.headerContainer}>
- <View style={drawerStyles.headerTop}>
- <Text style={drawerStyles.headerTopLeft}>{translate("ALL_CONTENT")}</Text>
- </View>
- </View>
- {
- this.state.noData ?
- <View>
- </View> :
- <View style={{ flex: 1 }}>
- <FlatList
- bounces={typeList.length == 0 ? false : true}
- data={typeList}
- extraData={this.state}
- keyExtractor={(item) => item.id}
- ListEmptyComponent={this.renderEmptyDrawer}
- renderItem={({ item, index }) =>
- item.type !== staticConfig.favorite &&
- <View key={item.id}>
- <TouchableOpacity
- activeOpacity={0.7}
- style={drawerStyles.menuItem}
- onPress={() => this.menuItemPress(item, true)}
- >
- <View style={drawerStyles.menuLeftIconView}>
- <CustomIcons style={[drawerStyles.menuLeftIcon, item.active && drawerStyles.menuLeftIconActive, { opacity: this.state.isConnected ? 1 : 0.5 }]} name={item.iconName} />
- </View>
- <Text style={[drawerStyles.menuItemText, item.active && drawerStyles.menuItemTextDefault, { opacity: this.state.isConnected ? 1 : 0.5 }]}>
- {item.title}
- </Text>
- {item.childMenuItems.length >= 1 &&
- <CustomIcons style={item.active ? drawerStyles.arrowIconActive : drawerStyles.arrowIcon} name={item.isExpanded ? "icon_down_arrow_line" : "icon_next_arrow_line"} />
- }
- </TouchableOpacity>
- {item.isExpanded && item.childMenuItems.length >= 1 && item.childMenuItems.map((item, key) =>
- <View key={item.id}>
- <TouchableOpacity
- activeOpacity={0.7}
- style={drawerStyles.menuItem}
- onPress={() => this.menuItemPress(item, true)}
- >
- <Text style={[drawerStyles.childMenuItemText, item.active && drawerStyles.childMenuItemTextDefault, { opacity: this.state.isConnected ? 1 : 0.5 }]}>
- {item.title}
- </Text>
- </TouchableOpacity>
- </View>
- )}
- </View>
- }
- />
- {renderFavFooter}
- </View>
- }
- </SafeAreaView >
- var headerBar =
- <View style={[Platform.OS === 'ios' ? styles.newHeaderContainer : styles.newHeaderContainerAndroid, { elevation: (this.state.errorModal) ? 0 : 4 }]}>
- <View style={Platform.OS === 'ios' ? styles.newTopHeaderContainer : styles.newTopHeaderContainerAndroid}>
- <TouchableOpacity activeOpacity={0.7} style={styles.newMenuButtonContainer} onPress={() => this.openMenu()}>
- <CustomIcons style={styles.newMenuButtonIcon} name="icon_side_menu" />
- <View style={styles.newMenuButtonRedDot}><View style={styles.newMenuButtonRedDotChild}></View></View>
- </TouchableOpacity>
- <View style={styles.newHeaderLeftButtonView}>
- <Text style={styles.newHeaderLeftButtonText} numberOfLines={1}>{currentTitle}</Text>
- </View>
- <TouchableOpacity activeOpacity={0.5} disabled={contentList.length == 0 && !this.state.isFilter} style={styles.newHeaderRightButtonView} onPress={() => this.openFilters()}>
- <CustomIcons style={[styles.newHeaderRightButtonIcon, contentList.length == 0 && !this.state.isFilter && { color: EStyleSheet.value("$disableIcon") }]} name="icon_filter" />
- </TouchableOpacity>
- </View>
- </View>
- return (
- <DrawerLayout
- drawerWidth={300}
- // useNativeAnimations={true}
- drawerBackgroundColor="white"
- ref={(_drawer) => { this.drawer = _drawer; varProvider.conDrawer = _drawer; }}
- onDrawerClose={() => { this.onDrawerClose() }}
- drawerPosition={DrawerLayout.positions.Left}
- drawerLockMode={this.state.drawerLockMode}
- renderNavigationView={() => menu}>
- <SafeAreaView
- edges={['right', 'top', 'left']}
- style={{ backgroundColor: "#fff", flex: 1 }}>
- <GuideView slides={guideImageJson.eResources} screen={"eResources"} showGuide={this.state.showGuide} closeGuide={this.closeGuide} hideCallback={this.hideModalCallback} />
- {/* to hide the header bar when there is any error modal on page*/}
- {!this.state.errorModal && headerBar}
- <View style={styles.mainContainer}>
- <View>
- <ScrollView style={styles.chipScrollView} horizontal={true}>
- {this.state.pubFilters.map((item, key) =>
- (
- <View key={key}>
- {item.active &&
- <View>
- <Chip
- rootStyle={styles.chipContainer}
- chipTitle={item.chipTitle}
- removeCallback={() => this.removeFilter(item)}
- />
- </View>
- }
- </View>
- ))
- }
- </ScrollView>
- </View>
- {
- this.state.contentLoading ?
- <ArticleLoader />
- :
- <View style={{ flex: 1 }}>
- {this.state.accessDenied ?
- <View style={{ margin: 16 }}>
- <Text style={{ color: "black", fontSize: 16 }}>{this.state.deniedMessage}</Text>
- </View>
- :
- <FlatList
- bounces={contentList.length == 0 ? false : true}
- style={{ marginBottom: 0 }}
- contentContainerStyle={[{ paddingTop: 12, paddingBottom: 8 }, contentList.length == 0 && { justifyContent: 'center', height: "100%" }]}
- data={contentList}
- extraData={this.state.refresh}
- ListFooterComponent={this.renderFooter}
- ListEmptyComponent={this.renderEmpty}
- onEndReached={this.handleLoadMore}
- onEndReachedThreshold={0.5}
- renderItem={this._renderContentCard}
- />
- }
- </View>
- }
- </View>
- {this.state.errorModal &&
- <View style={[styles.errorModalView, Platform.OS == "ios" && { zIndex: 3 }]}>
- <View style={styles.errorModalBackView}>
- <View style={styles.errorModalFrontView}>
- <View style={styles.logoContainer}>
- {this.state.imagePath &&
- <Image style={styles.logo} source={this.state.imagePath} resizeMode="contain" />
- }
- <Text style={styles.errorTitle}>{this.state.deniedMessage}</Text>
- {this.state.isButton &&
- <View>
- <Text style={[styles.errorText, { fontWeight: 'bold', textAlign: 'center' }]}>{this.state.bottomText}</Text>
- <TouchableOpacity activeOpacity={0.8} style={[styles.errorButton, { width: "60%" }]} onPress={this.gotoCollection}>
- <Text style={styles.errorButtonText}>{translate("READ_OFFLINE")}</Text>
- </TouchableOpacity>
- </View>
- }
- </View>
- </View>
- </View>
- </View>
- }
- <ActionSheet
- isVisible={this.state.multiUrlsView}
- closeCallback={this.closeActionSheetModal}
- hideCallback={this.hideActionSheetModal}
- modalWidth={modalWidth}
- modalHeight={modalHeight}
- backdropColor="#333"
- backdropOpacity={0.3}
- isMultiUrlView={this.state.multiUrlsView}
- data={multiUrlsList}
- />
- <Modal
- animationIn="zoomIn"
- animationOut="zoomOut"
- isVisible={this.state.permissionModal}
- supportedOrientations={['portrait', 'landscape']}
- useNativeDriver={true}
- hideModalContentWhileAnimating={true}
- style={styles.mainContent}
- >
- <View style={styles.permissionModal}>
- <ScrollView contentContainerStyle={styles.vpnPopupContainer} alwaysBounceVertical={false}>
- <View style={styles.logoContainer}>
- <Image style={styles.vpnPermissionImage} source={imageJson.vpn_permission} resizeMode="contain" />
- <Text style={styles.errorTitle}>{addVPNPopup ? translate("VPN_NOT_CONFIGURED") : translate("VPN_PERMISSION")}</Text>
- <View style={styles.errorVPNDataView}>
- <Text style={styles.errorTextContainer}>
- <Text style={styles.errorText}>{addVPNPopup ? translate("VPN_NOT_CONFIGURED_DATA") : translate("VPN_PERMISSION_DATA")}</Text>
- <Text style={styles.vpnLearnMoreButtonText} onPress={() => { this.openVpnInfo() }}> {translate("VPN_LEARN_MORE")}</Text>
- </Text>
- <TouchableOpacity activeOpacity={0.8} style={[styles.errorButton, { marginBottom: 30 }]} onPress={() => { this.proceedWithVPNPermission() }}>
- <Text style={styles.errorButtonText}>{addVPNPopup ? translate("VPN_NOT_CONFIGURED_BUTTON") : translate("VPN_PERMISSION_BUTTON")}</Text>
- </TouchableOpacity>
- </View>
- </View>
- </ScrollView>
- </View>
- </Modal>
- <Modal
- animationIn="zoomInUp"
- animationOut="zoomOut"
- backdropColor="#333"
- backdropOpacity={0.3}
- useNativeDriver={true}
- hideModalContentWhileAnimating={true}
- supportedOrientations={['portrait', 'landscape']}
- isVisible={this.state.isLinkLoading}
- >
- <View style={styles.switchLoadingView}>
- <ActivityIndicator size='large' color={Platform.OS === 'android' ? EStyleSheet.value("$defaultActivityIndicatorAndroid") : EStyleSheet.value("$defaultActivityIndicatorIOS")} />
- </View>
- </Modal>
- </SafeAreaView>
- </DrawerLayout>
- );
- }
- async proceedWithVPNPermission() {
- this.setState({
- permissionModal: false
- });
- addVPNPopup = false;
- if (Platform.OS == "ios") {
- let isVPNConfigAccepted = await conProvider.updateProxyDetailsForIos(true);
- this.setState({
- isVPNConfigAccepted: varProvider.enableProxy ? isVPNConfigAccepted : true
- });
- } else {
- setTimeout(async () => {
- let isVPNConfigAccepted = await conProvider.updateProxyDetailsForAndroid(true);
- this.setState({
- isVPNConfigAccepted: isVPNConfigAccepted
- });
- if (isVPNConfigAccepted) {
- this.logVPNEvent(true);
- AsyncStorage.setItem("isVPNLogged", "true");
- }
- }, 1000);
- }
- }
- clearParams() {
- const { params } = this.props.route;
- if (params != undefined && !params?.contentType) {
- console.log("clearParams:::::");
- params.contentType = null;
- params.menuItemId = null;
- params.cTitle = null;
- }
- }
- menuItemPress(item, isClicked) {
- this.clearParams(); //clear params for deeplink when using other menu item press to avoid re render deeplink tab issue
- ((item.childMenuItems == null || item.childMenuItems?.length == 0) && item.containsContent) && this.drawer.closeDrawer();
- if (connection.isConnectedFun()) {
- item.isExpanded = !item.isExpanded;
- if (item.containsContent) {
- this.updateTempList(typeList, item)
- currentTitle = item.title;
- menuItemId = item.id; // added currentTiTle to display correct name on top of the content screen when menuitem is pressed
- if (isClicked)
- this.logScreenViewEvent(false);
- var tempFilters = this.state.pubFilters;
- this.setState({
- refreshTypes: !this.state.refreshTypes
- });
- setTimeout(() => {
- currentType = item.type; // changed title to type
- this.callbackFun(tempFilters);
- }, 450)
- } else {
- this.setState({ refresh: !this.state.refresh })
- }
- } else {
- Toast.showShortCenter(translate("PLEASE_CONNECT"));
- }
- }
- updateTempList = (typeList, item, expandActiveItem) => {
- if (typeList) {
- var result = false;
- for (var i = 0; i < typeList.length; i++) {
- if (typeList[i].childMenuItems?.length > 0) {
- result = this.updateTempList(typeList[i].childMenuItems, item)
- if (result || typeList[i].id === item.id) {
- typeList[i].active = typeList[i].containsContent || result ? true : false
- if (expandActiveItem)
- typeList[i].isExpanded = expandActiveItem
- }
- else {
- typeList[i].active = false
- typeList[i].isExpanded = false
- }
- }
- else if (typeList[i].id === item.id) {
- typeList[i].active = true
- result = true
- }
- else {
- typeList[i].active = false
- typeList[i].isExpanded = false
- }
- }
- return result;
- }
- }
- onDrawerClose() {
- // console.log("on drawer close");
- }
- }