import React from 'react';
import { ScrollView, FlatList, Platform, Text, View, Dimensions, TouchableOpacity, Share } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import styles from '../styles/Collections';
import drawerStyles from '../styles/DrawerMenu';
import CustomIcons from '../components/CustomIcon';
import CustomAlert from '../components/CustomAlert';
import ActionSheet from '../components/ActionSheet';
import EmptyScreen from '../components/EmptyScreen';
import Chip from '../components/Chip';
import { moderateScale } from '../utils/Scaling';
import EStyleSheet from 'react-native-extended-stylesheet';
import * as colProvider from '../utils/ColProvider';
import * as apiProvider from '../utils/ApiProvider';
import * as varProvider from '../utils/VarProvider';
import * as analyticsProvider from '../utils/AnalyticsProvider';
import * as setProvider from '../utils/SetProvider';
import * as notProvider from '../utils/NotProvider';
import screenNames from '../config/screenNames';
import * as connection from '../utils/Connection';
import config from '../config/config';
import DrawerLayout from 'react-native-drawer-layout';
import { translate } from '../locales/i18n';
import Spinner from 'react-native-spinkit';
import RNFetchBlob from 'rn-fetch-blob';
import * as MD5 from '../utils/MD5';
import humanize from 'tiny-human-time';
import Toast from '@remobile/react-native-toast';
import MVMyloftPDFViewerNativeModuleIos from '../components/MVMyloftPDFViewerNativeModule.ios';
import ArticleLoader from '../components/ArticleLoader';
// import ArticleListView from '../components/ArticleListView';
import ArticleListNewView from '../components/ArticleList/index';
import ArticleCardNewView from '../components/ArticleCard/index';
import LinearGradient from 'react-native-linear-gradient';
import ShareIntentModule from '../components/ShareIntentModule';
import ShareActionSheet from '../components/ShareActionSheet';
import AsyncStorage from '@react-native-async-storage/async-storage';
import staticConfig from '../config/staticConfig';
import imageJson from '../config/imageJson';
import guideImageJson from '../config/guideImageJson';
import GuideView from '../components/GuideView';
import TagBottomSheet from '../components/TagBottomSheet';
var asList, articleList, collectionList, filteredColList, tagList, imagePath, title, text, isLink, links;
var cloneIt, cardWidth, numberOfCards, modalWidth, modalHeight, cardLeftWidth, closeFlag;
var noMoreData, isFirstTime, alreadyLoaded, alreadySubscribed, isInfiniteOn, graphError;
var pagingCount = config.articlePagingCount, screenWidth, isEditMode, drawerLockMode, startParentResponderTouch = true, startChildResponderTouch, modalObserver;
//need for showing favorite articles in side menu
var favoriteArticles = {
"id": "favoriteArticles",
"title": translate("FAVORITE_ARTICLES"),
"description": "",
"isDefault": false,
"active": false
};
export default class Collections extends React.Component {
constructor(props) {
super(props);
this.state = {
isCardView: varProvider.isCardView,
modalVisible: false,
articleList: [],
articleLoading: true,
articleLength: 0,
footerLoading: false,
errorLoading: false,
deleteModal: false,
asList: [],
activeFilters: [],
refreshCollection: false,
loadHint: false,
articleType: "",
showGuide: false
};
graphError = "";
isEditMode = false;
drawerLockMode = "unlocked";
collectionList = [];
filteredColList = [];
articleList = [];
tagList = [];
modalHeight = null;
alreadyLoaded = true;
isInfiniteOn = false;
if (varProvider.selectedCollectionName == undefined) {
varProvider.selectedCollectionName = "";
}
AsyncStorage.getItem("articleTimestamp").then((value) => {
if (!value) {
isFirstTime = true;
}
});
//this function is here because it just creates array for action sheet
this.initActionSheetList();
this.openMenu = this.openMenu.bind(this);
this.closeEditTitleModal = this.closeEditTitleModal.bind(this);
this.closeDeleteArticleModal = this.closeDeleteArticleModal.bind(this);
this.getEditTitleText = this.getEditTitleText.bind(this);
this.onSaveEditTitle = this.onSaveEditTitle.bind(this);
this.onDeleteArticle = this.onDeleteArticle.bind(this);
this.onOpenWithExternalView = this.onOpenWithExternalView.bind(this);
this.closeActionSheetModal = this.closeActionSheetModal.bind(this);
this.hideActionSheetModal = this.hideActionSheetModal.bind(this);
this.callbackFun = this.callbackFun.bind(this);
this.openArticleView = this.openArticleView.bind(this);
this.callbackAddTag = this.callbackAddTag.bind(this);
this.callbackDeleteArticle = this.callbackDeleteArticle.bind(this);
this.callbackRead = this.callbackRead.bind(this);
this.buttonCallback = this.buttonCallback.bind(this);
this.setDefaultCollection = this.setDefaultCollection.bind(this);
this.closeAddCollectionModal = this.closeAddCollectionModal.bind(this);
this.onSaveAddCollection = this.onSaveAddCollection.bind(this);
this.getAddCollectionText = this.getAddCollectionText.bind(this);
this.closeEditTitleCollectionModal = this.closeEditTitleCollectionModal.bind(this);
this.getEditTitleCollectionText = this.getEditTitleCollectionText.bind(this);
this.onSaveEditTitleCollection = this.onSaveEditTitleCollection.bind(this);
this.closeDeleteCollectionModal = this.closeDeleteCollectionModal.bind(this);
this.onDeleteCollection = this.onDeleteCollection.bind(this);
this.closeEditMode = this.closeEditMode.bind(this);
this.selectColAndLoadArticle = this.selectColAndLoadArticle.bind(this);
this.startArticleSubscription = this.startArticleSubscription.bind(this);
this.startCollectionSubscription = this.startCollectionSubscription.bind(this);
this.favoriteArticle = this.favoriteArticle.bind(this);
this.openModal = this.openModal.bind(this);
this.initMaxHeight = this.initMaxHeight.bind(this);
}
static navigationOptions = () => {
return {
headerShown: false
}
}
componentDidMount() {
varProvider.currentScreen = screenNames.Collections;
this.loadCollectionList();
this.startCollectionSubscription();
this.startArticleSubscription();
this.initMaxHeight();
Dimensions.addEventListener("change", this.initMaxHeight);
setProvider.showGuide("isCollectionsGuideShown", screenNames.Collections).then((res) => {
if (res) {
this.setState({ showGuide: true });
}
})
varProvider.connectionObserver.subscribe(() => {
asList[1].isGrayedOut = connection.isConnectedFun() ? false : true
this.setState({
isConnected: connection.isConnectedFun(),
asList: asList,
});
});
modalObserver = varProvider.modalClosedObserver.subscribe((data) => {
if (varProvider.currentScreen === screenNames.Collections && data.other) {
if (this.state.actionSheetModal || this.state.sharedOpened || this.state.editTitleModal || this.state.deleteArticleModal || this.state.addCollectionModal || this.state.deleteCollectionModal || this.state.editTitleCollectionModal || this.state.showGuide) {
this.setState({
actionSheetModal: false,
sharedOpened: false,
editTitleModal: false,
deleteArticleModal: false,
addCollectionModal: false,
deleteCollectionModal: false,
editTitleCollectionModal: false,
showGuide: false,
});
}
if (varProvider.modalClosedObserver) {
let resJson = {
"home": true,
"other": false,
"screen": screenNames.Collections,
}
varProvider.modalClosedObserver.next(resJson);
}
}
});
this._unsubscribe = this.props.navigation.addListener('focus', () => {
this.isFocused();
});
//this is used for showing and hiding collection hint
AsyncStorage.getItem("isFirstTime").then((value) => {
if (value != "false")
this.setState({ loadHint: true })
})
}
componentWillUnmount() {
this._unsubscribe();
modalObserver.unsubscribe();
}
isFocused() {
const { params } = this.props.route;
if (params) {
var isSearchText = false;
// [deep link] if collectionId is received from params, then set it as a selected collection to load articles of that collection
if (params.collectionId) {
varProvider.selectedCollectionId = params.collectionId;
}
// [deep link] if collectionId is "favoriteArticles", then load favorite articles
if (varProvider.selectedCollectionId == "favoriteArticles") {
varProvider.selectedCollectionName = favoriteArticles.title;
favoriteArticles.active = true;
}
// [deep link] if searchText is received from params, then set it as a active filter and load article list accordingly
if (params.searchText) {
isSearchText = true;
let originalSearchText = params.searchText;
let trimmedSearchText = originalSearchText.trim();
var filterJson = [
{
"active": false,
"chipTitle": "",
"value": "",
"originalSearchText": ""
},
{
"active": false,
"chipTitle": "",
"value": "",
"originalSearchText": ""
},
{
"active": false,
"chipTitle": "",
"value": "",
"originalSearchText": ""
},
{
"active": false,
"chipTitle": "",
"value": "",
"originalSearchText": ""
},
{
"active": false,
"chipTitle": "",
"value": "",
"originalSearchText": ""
},
{
"active": true,
"chipTitle": 'Search text: "' + originalSearchText + '"',
"value": trimmedSearchText,
"originalSearchText": originalSearchText
}
];
this.setState({
isFilter: true,
activeFilters: filterJson
});
}
params.contentType = "";
params.searchText = "";
}
varProvider.currentScreen = screenNames.Collections;
if (varProvider.isCollectionTabChanged) {
varProvider.isCollectionTabChanged = false;
if (varProvider.fromBroswerView) {
for (var i = 0; i < collectionList.length; i++) {
if (varProvider.selectedCollectionId == collectionList[i].id) {
collectionList[i].active = true;
}
else {
collectionList[i].active = false;
}
}
varProvider.fromBroswerView = false;
this.setState({ refreshCollection: !this.state.refreshCollection });
}
//don't call when component will mount called
if (!alreadyLoaded) {
// [deep link] get collection item based on received collectionId from params
let activeCollectionItem;
if (varProvider.selectedCollectionId == "favoriteArticles") {
activeCollectionItem = favoriteArticles;
} else {
for (var i = 0; i < collectionList.length; i++) {
if (collectionList[i].id == varProvider.selectedCollectionId) {
activeCollectionItem = collectionList[i];
break;
}
}
}
if (activeCollectionItem) {
if (!isSearchText) {
// [deep link] if searchText is not received than first disable all active filter
var tempFilters = this.state.activeFilters;
for (var i = 0; i < tempFilters.length; i++) {
tempFilters[i].active = false;
}
}
// [deep link] below method is for loading the article list of specific collection
this.menuItemPress(activeCollectionItem);
} else {
if (!this.state.isFilter) {
//no filters is applied, so reload the article list by updated timestamp from sqlite
var lastArticleTimestamp;
var artLength = articleList.length;
if (artLength != 0) {
lastArticleTimestamp = articleList[artLength - 1].createdAt;
}
var tempJson = {
"limit": pagingCount,
"offset": 0
};
if (artLength > pagingCount) {
tempJson["lastTimestamp"] = lastArticleTimestamp;
}
this.loadSyncedSql(tempJson);
//sync article list when switching between tabs
if (!varProvider.isSyncInProgress) {
colProvider.getSyncArticles(0);
}
} else {
//TO DO: filter is applied
}
}
}
let screenViewJson = {
"name": screenNames.Collections,
"previous": varProvider.lastTabName
};
analyticsProvider.logAnalyticsJson("ScreenView", screenViewJson);
varProvider.lastTabName = screenNames.Collections;
}
alreadyLoaded = false;
}
_handleOpenURL(event) {
// console.log("collection handle open url");
// console.log(event.url);
//parse and check if url is welcome mail url or shared url
//if welcome mail then navigate to screen with option to logout from current account and login to new account
//if shared url then navigate to browser
}
initActionSheetList() {
asList = [
{
title: translate("FILE_DOWNLOAD_OPEN"),
icon: "icon_open_with",
isVisible: true,
isGrayedOut: false,
onPressFun: this.onOpenWithExternalView.bind(this)
},
{
title: translate("SHARE"),
icon: Platform.OS == "ios" ? "icon_share_ios" : "icon_share",
isVisible: true,
isGrayedOut: false,
onPressFun: this.shareArticle.bind(this)
},
{
title: translate("ADD_TAGS"),
icon: "icon_add_tag",
isVisible: true,
isGrayedOut: false,
onPressFun: this.addTags.bind(this)
},
{
title: translate("EDIT_TITLE"),
icon: "icon_edit",
isVisible: true,
isGrayedOut: false,
onPressFun: this.editTitleArticle.bind(this)
},
{
title: translate("MOVE_TO_COLLECTION"),
icon: "icon_move",
isVisible: true,
isGrayedOut: false,
onPressFun: this.moveToCollection.bind(this)
},
{
title: translate("DELETE"),
icon: "icon_delete",
isVisible: true,
isGrayedOut: false,
onPressFun: this.deleteArticle.bind(this)
},
{
title: translate("MARK_AS") + translate("UNREAD"),
icon: "icon_visible",
isVisible: true,
isGrayedOut: false,
onPressFun: this.markAsRead.bind(this)
},
]
}
//initially load the collection list from sqlite
loadCollectionList() {
colProvider.getCollectionSql().then((data) => {
// console.log(data);
this.processCollectionList(data);
this.loadArticleList();
});
//whenever sync process will finish it will fetch collections from api
//we will get the fetched data in subscribe section
varProvider.collectionObservable.subscribe((data) => {
// console.log("collection observable get data");
// console.log(data)
if (data.isSetColId) {
if (data.data) {
for (var j = 0; j < collectionList.length; j++) {
if (collectionList[j].title === data.data.title) {
collectionList[j].id = data.data.id
break
}
}
}
}
else {
this.processCollectionList(data.data);
}
});
}
processCollectionList(data) {
collectionList = [];
var isActive;
for (var i = 0; i < data.length; i++) {
// [deep link] get collection name of selected collection and set it as active based on params
if (varProvider.selectedCollectionId == data[i].id) {
varProvider.selectedCollectionName = data[i].title;
isActive = true;
}
isActive = (varProvider.selectedCollectionName == data[i].title);
if (data[i].isDefault == 1 && data[i].title == "General Collection")
isFirstTime = false;
if (data[i].isDefault == 1) {
varProvider.defaultCollectionId = data[i].id;
varProvider.defaultCollectionName = data[i].title;
varProvider.defaultCollectionType = data[i].type;
if (!varProvider.selectedCollectionName && !varProvider.selectedCollectionId) {
varProvider.selectedCollectionId = data[i].id;
varProvider.selectedCollectionName = data[i].title;
isActive = true;
}
AsyncStorage.multiSet([
["defaultCollectionId", varProvider.defaultCollectionId],
["defaultCollectionName", varProvider.defaultCollectionName],
["defaultCollectionType", varProvider.defaultCollectionType]
]);
//collection marked as default should be on top so used unshift instead of push
collectionList.unshift({
"id": data[i].id,
"title": data[i].title,
"description": data[i].description,
"isDefault": data[i].isDefault == 1 ? true : false,
"type": data[i].type,
"createdAt": data[i].createdAt,
"updatedAt": data[i].updatedAt,
"pressed": false,
"active": isActive,
});
}
else {
collectionList.push({
"id": data[i].id,
"title": data[i].title,
"description": data[i].description,
"isDefault": data[i].isDefault == 1 ? true : false,
"type": data[i].type,
"createdAt": data[i].createdAt,
"updatedAt": data[i].updatedAt,
"pressed": false,
"active": isActive,
});
}
}
// console.log(collectionList);
filteredColList = collectionList;
this.setState({ refreshCollection: !this.state.refreshCollection });
}
loadArticleList() {
// console.log("load article list init");
noMoreData = false;
colProvider.getArticleList().then((data) => {
// console.log(data);
articleList = [];
if (data.length != 0) {
this.processArticleList(data, 0);
}
else {
//no article in local db
if (!isFirstTime) {
this.setState({ refresh: !this.state.refresh, articleLoading: false, articleLength: articleList.length });
}
}
// [deep link] if filter is active then again load the article list
if (this.state.isFilter) {
this.callbackFun(this.state.activeFilters);
}
});
//subscribe to article observable if not subscribed
if (!alreadySubscribed) {
alreadySubscribed = true;
//whenever article list gets fetched, here we get the response
varProvider.articleObserver.subscribe((resJson) => {
// console.log("article observable get data");
// console.log(resJson);
if (!resJson.error) {
if (!resJson.isForHome) {
if (resJson.alreadySynced) {
if (!this.state.isFilter) {
var lastArticleTimestamp;
var artLength = articleList.length;
if (artLength != 0) {
lastArticleTimestamp = articleList[artLength - 1].createdAt;
}
var tempJson = {
"limit": pagingCount,
"offset": 0
};
if (artLength > pagingCount) {
tempJson["lastTimestamp"] = lastArticleTimestamp;
}
this.loadSyncedSql(tempJson);
} else {
//TO DO: filter is applied
}
} else {
var tempJson = {
"limit": pagingCount,
"offset": 0
};
articleList = [];
this.loadSqlArticle(tempJson);
}
}
} else {
// console.log("article observable error else");
this.setState({ refresh: !this.state.refresh, articleLoading: false, articleLength: articleList.length });
}
},
() => {
// console.log("article observable error");
this.setState({ refresh: !this.state.refresh, articleLoading: false, articleLength: articleList.length });
}
);
}
}
processArticleList(data, articleCount) {
for (var i = 0; i < data.length; i++) {
var tagList = [];
if (data[i]["tagList"]) {
tagList = data[i]["tagList"].split("*");
}
tagList.sort(colProvider.SortByNameArray);
var currentTimestamp = new Date();
var articleTimestamp = new Date(data[i].createdAt);
var timeAgo = humanize(currentTimestamp, articleTimestamp);
var articleType = data[i].type;
var phImage = colProvider.getPlaceholderImage(articleType);
var phImageBig = articleType == "HTML" && colProvider.getPlaceholderImageBig(articleType);
var bgColor = colProvider.getArticleBg(articleType);
articleList.push({
"id": data[i].id,
"title": data[i].title,
"url": data[i].url,
"timeAgo": timeAgo.time + translate(staticConfig[timeAgo.timeUnit]),
"imageURL": data[i].imageURL,
"image": phImage,
"cardImage": phImageBig,
"collectionName": data[i].collectionName,
"collectionId": data[i].collectionId,
"collectionType": data[i].collectionType,
"type": articleType,
"hostname": colProvider.getHostname(data[i].url),
"highlightData": [],
"tagList": tagList,
"isReadable": data[i].isReadable == 1 ? true : false,
"viaTemplate": data[i].viaTemplate == 1 ? true : false,
"isImageAvailable": data[i].isImageAvailable == 1 ? true : false,
"isFavorite": data[i].isFavorite == 1 ? true : false,
"readStatus": data[i].readStatus == 1 ? true : false,
"isImageFailed": data[i].isImageFailed == 1 ? true : false,
"isDataFailed": data[i].isDataFailed == 1 ? true : false,
"createdAt": data[i].createdAt,
"updatedAt": data[i].updatedAt,
"bgColor": bgColor,
"contentURL": data[i].contentURL,
"isPushed": data[i].isPushed == 1 ? true : false,
"pushType": data[i].pushType
});
if (articleList[articleCount].isImageAvailable && !articleList[articleCount].isImageFailed) {
this.loadArticleImage(articleList[articleCount]);
}
if (articleList[articleCount].type == "PDF") {
this.loadPDFFileStatus(articleList[articleCount]);
}
articleCount++;
}
// console.log(articleList);
this.setState({ refresh: !this.state.refresh, articleLoading: false, footerLoading: false, articleLength: articleList.length });
}
//to fetch the article list from sqlite
loadSyncedSql(tempJson) {
colProvider.getArticleSql(tempJson).then((data) => {
// console.log(data);
if (data.length < pagingCount) {
noMoreData = true;
}
if (data.length != 0) {
var articleCount = 0;
var tp = [];
var artLength = articleList.length;
var firstArticleTimestamp;
var urlMD, shortPath;
var loadedPDFId = [], loadedPDFStatus = [];
for (var k = 0; k < articleList.length; k++) {
if (articleList[k].isPDFAvailable) {
loadedPDFId.push(articleList[k].id);
loadedPDFStatus.push(articleList[k].isPDFAvailable);
}
}
if (artLength != 0) {
firstArticleTimestamp = articleList[0].createdAt;
}
var currentArticleTimestamp, isImagePath;
for (var i = 0; i < data.length; i++) {
var tagList = [];
if (data[i]["tagList"]) {
tagList = data[i]["tagList"].split("*");
}
tagList.sort(colProvider.SortByNameArray);
var currentTimestamp = new Date();
var articleTimestamp = new Date(data[i].createdAt);
var timeAgo = humanize(currentTimestamp, articleTimestamp);
currentArticleTimestamp = data[i].createdAt;
isImagePath = false;
urlMD = MD5.MD5(data[i].url);
shortPath = RNFetchBlob.fs.dirs.DocumentDir + "/" + urlMD + ".jpg";
if (currentArticleTimestamp <= firstArticleTimestamp) {
isImagePath = true;
}
var articleType = data[i].type;
var isPDFAvailable = null;
if (articleType == "PDF") {
if (loadedPDFId.length != 0) {
var pdfIndex = loadedPDFId.indexOf(data[i].id);
if (pdfIndex != -1) {
isPDFAvailable = loadedPDFStatus[pdfIndex];
}
}
}
var phImage;
if (isImagePath && data[i].isImageAvailable == 1 && data[i].isImageFailed != 1) {
phImage = "file://" + shortPath;
} else {
phImage = (isPDFAvailable == "false") ? colProvider.getPdfNAImage() : colProvider.getPlaceholderImage(articleType);
}
var phImageBig = articleType == "HTML" && colProvider.getPlaceholderImageBig(articleType);
var bgColor = (isPDFAvailable == "false") ? colProvider.getPdfNABg() : colProvider.getArticleBg(articleType);
tp.push({
"id": data[i].id,
"title": data[i].title,
"url": data[i].url,
"timeAgo": timeAgo.time + translate(staticConfig[timeAgo.timeUnit]),
"imageURL": data[i].imageURL,
"image": phImage,
"cardImage": phImageBig,
"collectionName": data[i].collectionName,
"collectionId": data[i].collectionId,
"collectionType": data[i].collectionType,
"type": articleType,
"hostname": colProvider.getHostname(data[i].url),
"highlightData": [],
"tagList": tagList,
"isReadable": data[i].isReadable == 1 ? true : false,
"viaTemplate": data[i].viaTemplate == 1 ? true : false,
"isImageAvailable": data[i].isImageAvailable == 1 ? true : false,
"isFavorite": data[i].isFavorite == 1 ? true : false,
"readStatus": data[i].readStatus == 1 ? true : false,
"isImageFailed": data[i].isImageFailed == 1 ? true : false,
"isDataFailed": data[i].isDataFailed == 1 ? true : false,
"isPDFAvailable": isPDFAvailable,
"createdAt": data[i].createdAt,
"updatedAt": data[i].updatedAt,
"bgColor": bgColor,
"contentURL": data[i].contentURL,
"isPushed": data[i].isPushed == 1 ? true : false,
"pushType": data[i].pushType
});
if (!isImagePath && tp[articleCount].isImageAvailable && !tp[articleCount].isImageFailed) {
this.loadArticleImage(tp[articleCount]);
}
if (tp[articleCount].type == "PDF" && !isPDFAvailable) {
this.loadPDFFileStatus(tp[articleCount]);
}
articleCount++;
}
articleList = tp;
// console.log(articleList);
this.setState({ refresh: !this.state.refresh, articleLoading: false, footerLoading: false, articleLength: articleList.length });
} else {
articleList = [];
this.setState({ refresh: !this.state.refresh, articleLoading: false, footerLoading: false, articleLength: articleList.length });
}
});
}
async loadPDFFileStatus(articleItem) {
var isExist = await colProvider.checkIfPDFFileAvailable(articleItem);
var isExistStr = isExist.toString();
articleItem.isPDFAvailable = isExistStr;
if (articleItem.isPDFAvailable == "false") {
articleItem.bgColor = colProvider.getPdfNABg();
articleItem.image = colProvider.getPdfNAImage();
}
this.setState({
refresh: !this.state.refresh
});
}
//load the article image from file storage
loadArticleImage(articleItem, failureCount) {
var urlMD = MD5.MD5(articleItem.url);
var path = RNFetchBlob.fs.dirs.DocumentDir + "/" + urlMD + ".jpg";
RNFetchBlob.fs.exists(path).then((exist) => {
if (exist) {
for (var i = 0; i < articleList.length; i++) {
if (articleList[i].id == articleItem.id) {
articleList[i].image = "file://" + path;
break;
}
}
this.setState({ refresh: !this.state.refresh });
}
else {
AsyncStorage.getItem("accountId").then((accountId) => {
var path = accountId + "/" + urlMD + "/" + urlMD + ".jpg";
if (articleItem.isPushed) {
if (!failureCount) {
failureCount = 3;
}
this.writeArticleImage(articleItem.imageURL, urlMD, articleItem, failureCount);
}
else {
colProvider.getArticleImageGraph(path).then((data) => {
if (!failureCount) {
failureCount = 3;
}
this.writeArticleImage(data, urlMD, articleItem, failureCount);
});
}
});
}
});
}
//download the article image to file storage
writeArticleImage(data, urlMD, articleItem, failureCount) {
var path = RNFetchBlob.fs.dirs.DocumentDir + "/" + urlMD + ".jpg";
RNFetchBlob
.config({
fileCache: true,
path: path
})
.fetch('GET', data, {
})
.then((res) => {
if (res["respInfo"] && res["respInfo"]["headers"]) {
var types = colProvider.findValueOfProperty(res["respInfo"]["headers"], "content-type");
if (types.length != 0) {
var ctype = types[0];
if (res["respInfo"]["status"] == 200) {
if (ctype.indexOf("xml") == -1 && ctype.indexOf("html") == -1) {
// content type is neither 'xml' nor 'html', so save and set the image
var aPath = "file://" + res.path();
for (var i = 0; i < articleList.length; i++) {
if (articleList[i].id == articleItem.id) {
articleList[i].image = aPath;
break;
}
}
this.setState({ refresh: !this.state.refresh });
} else {
// content type is either 'xml' or 'html', so set imageFailed to true and remove the image file
this.updateImageFailedArticle(articleItem, res.path(), failureCount);
}
} else if (res["respInfo"]["status"] == 404) {
// image file not found on server
this.updateImageFailedArticle(articleItem, res.path(), failureCount);
} else {
// some other status code, so remove the image file(it will be retried on next app launch or sync)
RNFetchBlob.fs.unlink(res.path());
}
} else {
//content type is application/xml
this.updateImageFailedArticle(articleItem, res.path(), failureCount);
}
}
})
}
updateImageFailedArticle(articleItem, filePath, failureCount) {
if (failureCount <= 1) {
var queryArg = "isImageFailed = 1";
var queryData = [articleItem.id];
colProvider.updateSingleArticleSql(queryArg, queryData);
RNFetchBlob.fs.unlink(filePath);
} else {
failureCount--;
RNFetchBlob.fs.unlink(filePath);
setTimeout(() => {
this.loadArticleImage(articleItem, failureCount);
}, 3000);
}
}
openSearch() {
const { navigate } = this.props.navigation;
navigate('Search', { screenName: "Collection" });
}
openMenu() {
this.drawer.openDrawer();
}
//initialize all required values when switched between portrait and landscape
initMaxHeight() {
var sheight = Dimensions.get('window').height;
var swidth = Dimensions.get('window').width;
screenWidth = swidth;
if (sheight < 480) {
this.setState({ isMaxHeight: true });
}
else {
this.setState({ isMaxHeight: false });
}
if (sheight < 480) {
modalHeight = 250;
}
else {
modalHeight = null;
}
if (swidth < 480) {
numberOfCards = 1;
cardWidth = swidth - 32;
modalWidth = "100%";
}
else if (swidth < 920) {
numberOfCards = 2;
cardWidth = (swidth / 2) - 24;
modalWidth = "70%";
}
else {
numberOfCards = 3;
cardWidth = (swidth / 3) - 22;
modalWidth = "60%";
}
var tempCardWidth = cardWidth - moderateScale(94, 0.2);
cardLeftWidth = tempCardWidth;
this.setState({ refresh: !this.state.refresh });
}
//to switch between listview and cardview
changeView() {
var viewState = !this.state.isCardView;
this.setState({ isCardView: viewState });
AsyncStorage.setItem("isCardView", viewState.toString());
// apiProvider.refreshToken();
}
//start local subscription of articles for remote subscription
startArticleSubscription() {
// colProvider.startArticleSubscriptionGraph().subscribe((resJson) => {
varProvider.artSubObserver.subscribe((resJson) => {
// console.log("article subscription");
// console.log(resJson);
if (!resJson.error) {
var data = resJson.data;
var subObject = data["data"]["articleSubscribe"];
var articleNode = data["data"]["articleSubscribe"]["node"];
var prevArticleNode = data["data"]["articleSubscribe"]["previousValues"];
/*if (subObject.mutation == "UPDATED") {
var updatedFields = subObject["updatedFields"];
if (updatedFields && updatedFields.length != 0) {
for (var i = 0; i < articleList.length; i++) {
if (articleList[i].id == articleNode.id) {
for (var j = 0; j < updatedFields.length; j++) {
articleList[i][updatedFields[j]] = articleNode[updatedFields[j]];
}
}
}
} else {
//collection and tags case
var tagLength = articleNode["tags"].length;
var inCollection = false;
for (var i = 0; i < articleList.length; i++) {
if (articleList[i].id == articleNode.id) {
inCollection = true;
//delete article if moved from collection
if (articleList[i].collectionId != articleNode["collection"][0]["id"]) {
articleList.splice(i, 1);
break;
}
//update taglist of article
var tagList = [];
if (tagLength != 0) {
var arrTag = articleNode["tags"];
for (var m = 0; m < arrTag.length; m++) {
tagList.push(arrTag[m].name);
}
articleList[i]["tagList"] = tagList;
} else {
articleList[i]["tagList"] = [];
}
}
}
//article not in current collection so insert article
if (!inCollection) {
//check if articles collection id has changed and updated to current collectionid
var tempJson = {
"id": articleNode.id
};
colProvider.getSingleArticleSql(tempJson).then((articleItem) => {
// console.log(articleItem);
if (articleItem[0].collectionId != articleNode["collection"][0]["id"]) {
if (articleNode["collection"][0]["id"] == varProvider.selectedCollectionId) {
var tagList = [];
if (articleItem[0]["tagList"]) {
tagList = articleItem[0]["tagList"].split("*");
}
var currentTimestamp = new Date();
var articleTimestamp = new Date(articleItem[0].createdAt);
var timeAgo = humanize(currentTimestamp, articleTimestamp);
articleList.unshift({
"id": articleItem[0].id,
"title": articleItem[0].title,
"url": articleItem[0].url,
"timeAgo": timeAgo,
"imageURL": articleItem[0].imageURL,
"collectionName": articleItem[0].collectionName,
"collectionId": articleItem[0].collectionId,
"type": articleItem[0].type,
"hostname": colProvider.getHostname(articleItem[0].url),
"highlightData": [],
"tagList": tagList,
"isReadable": articleItem[0].isReadable == 1 ? true : false,
"isImageAvailable": articleItem[0].isImageAvailable == 1 ? true : false,
"isFavorite": articleItem[0].isFavorite == 1 ? true : false,
"readStatus": articleItem[0].readStatus == 1 ? true : false,
"createdAt": articleItem[0].createdAt,
"updatedAt": articleItem[0].updatedAt
});
if (articleList[0].isImageAvailable) {
this.loadArticleImage(articleList[0]);
}
}
}
});
}
}
}*/
if (subObject.mutation == "CREATED") {
var alreadyAdded = false;
for (var i = 0; i < articleList.length; i++) {
if (articleList[i].url == articleNode.url) {
alreadyAdded = true;
break;
}
}
// console.log("subscription already added: " + alreadyAdded);
if (!alreadyAdded) {
var tagList = [];
if (articleNode["tags"].length != 0) {
var arrTag = articleNode["tags"];
for (var m = 0; m < arrTag.length; m++) {
tagList.push(arrTag[m].name);
}
}
tagList.sort(colProvider.SortByNameArray);
var collectionName = "", collectionId = "", collectionType = "";
if (articleNode["collection"].length != 0) {
collectionId = articleNode["collection"][0]["id"];
collectionName = articleNode["collection"][0]["title"];
collectionType = articleNode["collection"][0]["type"];
}
if (varProvider.selectedCollectionId == collectionId) {
var currentTimestamp = new Date();
var articleTimestamp = new Date(articleNode.createdAt);
var timeAgo = humanize(currentTimestamp, articleTimestamp);
var articleType = articleNode.isPushed ? articleNode.refArticle.type : articleNode.type;
var phImage = colProvider.getPlaceholderImage(articleType);
var phImageBig = articleType == "HTML" && colProvider.getPlaceholderImageBig(articleType);
var bgColor = colProvider.getArticleBg(articleType);
articleList.unshift({
"id": articleNode.id,
"title": articleNode.isPushed ? articleNode.refArticle.title : articleNode.title,
"url": articleNode.isPushed ? articleNode.refArticle.url : articleNode.url,
"timeAgo": timeAgo.time + translate(staticConfig[timeAgo.timeUnit]),
"imageURL": articleNode.isPushed ? articleNode.refArticle.imageURL : articleNode.imageURL,
"image": phImage,
"cardImage": phImageBig,
"collectionName": collectionName,
"collectionId": collectionId,
"collectionType": collectionType,
"type": articleType,
"hostname": colProvider.getHostname(articleNode.url),
"highlightData": [],
"tagList": tagList,
"isReadable": articleNode.isPushed ? articleNode.refArticle.isScraped : articleNode.isReadable,
"viaTemplate": articleNode.viaTemplate,
"isImageAvailable": articleNode.isPushed ? articleNode.refArticle.isImageAvailable : articleNode.isImageAvailable,
"isFavorite": articleNode.isFavorite,
"readStatus": articleNode.readStatus,
"isImageFailed": false,
"isDataFailed": false,
"createdAt": new Date(articleNode.createdAt).getTime(),
"updatedAt": new Date(articleNode.updatedAt).getTime(),
"bgColor": bgColor,
"contentURL": articleNode.isPushed ? articleNode.refArticle.contentURL : articleNode.contentURL,
"isPushed": articleNode.isPushed,
"pushType": articleNode.isPushed ? articleNode.refArticle.pushType : ""
});
if (articleList[0].isImageAvailable) {
this.loadArticleImage(articleList[0]);
}
if (articleList[0].type == "PDF") {
this.loadPDFFileStatus(articleList[0]);
}
}
}
} else if (subObject.mutation == "DELETED") {
for (var i = 0; i < articleList.length; i++) {
if (articleList[i].id == prevArticleNode.id) {
articleList.splice(i, 1);
if (articleList.length < pagingCount && !noMoreData) {
setTimeout(() => {
this.handleLoadMore({ distanceFromEnd: "NeedToFetch" });
}, 1000);
}
break;
}
}
}
this.setState({ refresh: !this.state.refresh });
}
});
}
//start local subscription of collections for remote subscription
startCollectionSubscription() {
// colProvider.startCollectionSubscriptionGraph().subscribe((resJson) => {
varProvider.colSubObserver.subscribe((resJson) => {
// console.log("collection subscription");
// console.log(resJson);
if (!resJson.error) {
var data = resJson.data;
var subObject = data["data"]["collectionsSubscribe"];
var collectionNode = data["data"]["collectionsSubscribe"]["node"];
var prevCollectionNode = data["data"]["collectionsSubscribe"]["previousValues"];
/*if (subObject.mutation == "UPDATED") {
var updatedFields = subObject["updatedFields"];
if (updatedFields && updatedFields.length != 0) {
for (var i = 0; i < collectionList.length; i++) {
if (collectionList[i].id == collectionNode.id) {
for (var j = 0; j < updatedFields.length; j++) {
//update collection item according to updated field
collectionList[i][updatedFields[j]] = collectionNode[updatedFields[j]];
//if collection title has changed, update in article list
//if same collection is selected, update that title also
if (updatedFields[j] == "title") {
if (varProvider.selectedCollectionName == prevCollectionNode["title"]) {
varProvider.selectedCollectionName = collectionNode["title"];
for (var m = 0; m < articleList.length; m++) {
if (articleList[m].collectionName == prevCollectionNode["title"]) {
articleList[m].collectionName = collectionNode["title"];
}
}
}
}
//if collection's isDefault has changed, update default collection id and default collection
//title in asyncstorage and global variable
//set all other collection's isDefault to false
else if (updatedFields[j] == "isDefault") {
varProvider.defaultCollectionId = collectionNode.id;
varProvider.defaultCollectionName = collectionNode.title;
AsyncStorage.setItem("defaultCollectionId", varProvider.defaultCollectionId);
AsyncStorage.setItem("defaultCollectionName", varProvider.defaultCollectionName);
for (var t = 0; t < collectionList.length; t++) {
if (collectionList[t].id != collectionNode.id) {
collectionList[t].isDefault = false;
}
}
}
}
}
}
}
}*/
if (subObject.mutation == "CREATED") {
var alreadyAdded = false;
for (var i = 0; i < collectionList.length; i++) {
if (collectionList[i].title == collectionNode.title) {
alreadyAdded = true;
break;
}
}
if (!alreadyAdded) {
var tempColList = JSON.parse(JSON.stringify(collectionList));
tempColList.splice(0, 1);
var toInsertIndex = colProvider.getSortedIndex(tempColList, collectionNode.title, "title");
collectionList.splice(toInsertIndex + 1, 0, {
"id": collectionNode.id,
"title": collectionNode.title,
"description": collectionNode.description,
"isDefault": collectionNode.isDefault,
"createdAt": collectionNode.createdAt,
"updatedAt": collectionNode.updatedAt,
"pressed": false,
"active": false
});
}
} else if (subObject.mutation == "DELETED") {
var index, colIdToDelete;
for (var i = 0; i < collectionList.length; i++) {
if (collectionList[i].id == prevCollectionNode.id) {
colIdToDelete = collectionList[i].id;
collectionList.splice(i, 1);
index = i;
break;
}
}
if (varProvider.selectedCollectionId == colIdToDelete) {
if (index) {
if (index == 0) {
//select collection and load its article
this.selectColAndLoadArticle(index);
} else {
//select collection i-1 and load its articles
this.selectColAndLoadArticle(index - 1);
}
}
}
}
this.setState({ refreshCollection: !this.state.refreshCollection, refresh: !this.state.refresh });
}
});
}
buttonCallback() {
this.callbackFun(this.state.activeFilters);
}
//if filter is applied
callbackFun(activeFilters) {
// console.log(activeFilters);
graphError = "";
this.setState({ activeFilters: activeFilters, articleLoading: true, errorLoading: false, articleLength: 0 });
var isFilter = false;
var appliedFilter = [];
for (var i = 0; i < activeFilters.length; i++) {
if (activeFilters[i].active) {
isFilter = true;
var topKey, bottomKey, dataKey, dataValue, sqlKey, sqlValue;
//filter by days
if (i == 0) {
let minimumDate = activeFilters[0].value[0];
let maximumDate = activeFilters[0].value[1];
topKey = "$createdAt_gte: DateTime, $createdAt_lte: DateTime";
bottomKey = "createdAt_gte: $createdAt_gte, createdAt_lte: $createdAt_lte";
dataKey = "dateRange";
dataValue = [minimumDate, maximumDate];
sqlKey = "al.createdAt >= ? AND al.createdAt <= ?";
sqlValue = [new Date(minimumDate).getTime(), new Date(maximumDate).getTime()];
}
//filter favorite
if (i == 3) {
topKey = "$isFavorite: Boolean";
bottomKey = "isFavorite: $isFavorite";
dataKey = "isFavorite";
dataValue = true;
sqlKey = "al.isFavorite = ?";
sqlValue = 1;
}
//filter by tag
if (i == 4) {
topKey = "$tagName: [String!]";
bottomKey = "tags_some: { name_in: $tagName }";
dataKey = "tagName";
dataValue = activeFilters[4].value;
sqlKey = "tl.title = ?";
sqlValue = activeFilters[4].value;
}
//filter by search text
if (i == 5) {
topKey = "$searchText: String";
bottomKey = "title_contains: $searchText ";
dataKey = "searchText";
dataValue = activeFilters[5].value;
sqlKey = "al.title LIKE ?";
sqlValue = "%" + activeFilters[5].value + "%";
}
if (i == 1 || i == 2) {
} else {
appliedFilter.push({
"topKey": topKey,
"bottomKey": bottomKey,
"dataKey": dataKey,
"dataValue": dataValue,
"sqlKey": sqlKey,
"sqlValue": sqlValue
});
}
}
}
var typeFilter;
if (activeFilters[1].active) {
typeFilter = "HTML";
}
if (activeFilters[2].active) {
typeFilter = "PDF";
}
if (activeFilters[1].active && activeFilters[2].active) {
typeFilter = "";
}
if (!activeFilters[1].active && !activeFilters[2].active) {
typeFilter = "";
}
if (typeFilter) {
appliedFilter.push({
"topKey": "$type: ArticleType",
"bottomKey": "type: $type",
"dataKey": "type",
"dataValue": typeFilter,
"sqlKey": "al.type = ?",
"sqlValue": typeFilter
});
}
if (appliedFilter.length == 0) {
this.setState({
"isFilter": false,
appliedFilter: appliedFilter
});
} else {
this.setState({
"isFilter": true,
appliedFilter: appliedFilter
});
}
//load favorite articles if favorite articles is selected
//and add search filter if already applied
if (varProvider.selectedCollectionId == "favoriteArticles") {
var filLength = appliedFilter.length;
var searchText = (filLength == 0) ? "" : appliedFilter[0].sqlValue;
var tempJson = {
"isFilter": (filLength != 0),
"offset": 0,
"searchText": searchText
};
articleList = [];
noMoreData = false;
//sql query to filter favorite article list
this.loadFavoriteArticles(tempJson);
} else {
//if internet is connected load article list from api
//else load article list from sqlite
if (connection.isConnectedFun()) {
if (appliedFilter.length != 0) {
var tempJson = {
"isFilter": isFilter,
"appliedFilter": appliedFilter,
"first": pagingCount,
"skip": 0
};
articleList = [];
noMoreData = false;
//graphql query to filter article list
this.loadGraphArticle(tempJson);
} else {
isFirstTime = false;
this.loadArticleList();
}
} else {
if (appliedFilter.length != 0) {
var tempJson = {
"isFilter": isFilter,
"appliedFilter": appliedFilter,
"limit": pagingCount,
"offset": 0
};
articleList = [];
noMoreData = false;
//sql query to filter article list
this.loadSqlArticle(tempJson);
}
else {
isFirstTime = false;
this.loadArticleList();
}
}
}
}
//load article list from api
loadGraphArticle(tempJson) {
colProvider.getArticleListGraph(tempJson).then((data) => {
// console.log("load graph article data");
// console.log(data);
if (data.length < pagingCount) {
noMoreData = true;
}
if (data.length != 0) {
var articleCount = articleList.length;
for (var i = 0; i < data.length; i++) {
var tagList = [];
if (data[i]["tags"].length != 0) {
var arrTag = data[i]["tags"];
for (var m = 0; m < arrTag.length; m++) {
tagList.push(arrTag[m].name);
}
}
tagList.sort(colProvider.SortByNameArray);
var collectionName = "", collectionId = "", collectionType = "";
if (data[i]["collection"].length != 0) {
collectionId = data[i]["collection"][0]["id"];
collectionName = data[i]["collection"][0]["title"];
collectionType = data[i]["collection"][0]["type"];
}
var currentTimestamp = new Date();
var articleTimestamp = new Date(data[i].createdAt);
var timeAgo = humanize(currentTimestamp, articleTimestamp);
var articleType = data[i].isPushed ? data[i].refArticle.type : data[i].type;
var phImage = colProvider.getPlaceholderImage(articleType);
var phImageBig = articleType == "HTML" && colProvider.getPlaceholderImageBig(articleType);
var bgColor = colProvider.getArticleBg(articleType);
articleList.push({
"id": data[i].id,
"title": data[i].isPushed ? data[i].refArticle.title : data[i].title,
"url": data[i].isPushed ? data[i].refArticle.url : data[i].url,
"timeAgo": timeAgo.time + translate(staticConfig[timeAgo.timeUnit]),
"imageURL": data[i].isPushed ? data[i].refArticle.imageURL : data[i].imageURL,
"image": phImage,
"cardImage": phImageBig,
"collectionName": collectionName,
"collectionId": collectionId,
"collectionType": collectionType,
"type": articleType,
"hostname": colProvider.getHostname(data[i].url),
"highlightData": [],
"tagList": tagList,
"isReadable": data[i].isPushed ? data[i].refArticle.isScraped : data[i].isReadable,
"viaTemplate": data[i].viaTemplate,
"isImageAvailable": data[i].isPushed ? data[i].refArticle.isImageAvailable : data[i].isImageAvailable,
"isFavorite": data[i].isFavorite,
"readStatus": data[i].readStatus,
"isImageFailed": false,
"isDataFailed": false,
"createdAt": new Date(data[i].createdAt).getTime(),
"updatedAt": new Date(data[i].updatedAt).getTime(),
"bgColor": bgColor,
"contentURL": data[i].isPushed ? data[i].refArticle.contentURL : data[i].contentURL,
"isPushed": data[i].isPushed,
"pushType": data[i].isPushed ? data[i].refArticle.pushType : ""
});
if (articleList[articleCount].isImageAvailable && !articleList[articleCount].isImageFailed) {
this.loadArticleImage(articleList[articleCount]);
}
if (articleList[articleCount].type == "PDF") {
this.loadPDFFileStatus(articleList[articleCount]);
}
articleCount++;
}
this.setState({ refresh: !this.state.refresh, articleLoading: false, footerLoading: false, articleLength: articleList.length });
} else {
this.setState({ refresh: !this.state.refresh, articleLoading: false, footerLoading: false, articleLength: articleList.length });
}
setTimeout(() => {
isInfiniteOn = false;
}, 400);
}).catch((error) => {
// console.log(error);
connection.getGraphError(error.error).then((data) => {
graphError = data;
this.setState({ refresh: !this.state.refresh, articleLoading: false, footerLoading: false, errorLoading: true, articleLength: articleList.length });
})
isInfiniteOn = false;
});
}
//load article list from sqlite
loadSqlArticle(tempJson) {
colProvider.getArticleSql(tempJson).then((data) => {
// console.log(data);
if (data.length < pagingCount) {
noMoreData = true;
}
if (data.length != 0) {
var articleCount = articleList.length;
this.processArticleList(data, articleCount);
} else {
this.setState({ refresh: !this.state.refresh, articleLoading: false, footerLoading: false, articleLength: articleList.length });
}
isInfiniteOn = false;
});
}
openFilters() {
const { navigate } = this.props.navigation;
navigate('ColFilters', { "callbackFun": this.callbackFun, "activeFilters": this.state.activeFilters });
}
// to handle scroll pagination to load more articles
handleLoadMore = (calledFrom) => {
if (articleList.length > pagingCount - 1 || calledFrom.distanceFromEnd == "NeedToFetch") {
var tempOffset = articleList.length;
if (!noMoreData) {
if (!isInfiniteOn) {
this.setState({ footerLoading: true });
isInfiniteOn = true;
//load favorite articles if favorite articles is selected
//and add search filter if already applied
if (varProvider.selectedCollectionId == "favoriteArticles") {
if (this.state.isFilter) {
var filLength = this.state.appliedFilter.length;
var searchText = (filLength == 0) ? "" : this.state.appliedFilter[0].sqlValue;
var tempJson = {
"isFilter": (filLength != 0),
"offset": tempOffset,
"searchText": searchText
};
} else {
var tempJson = {
"offset": tempOffset
};
}
this.loadFavoriteArticles(tempJson);
} else {
if (this.state.isFilter && connection.isConnectedFun()) {
//filter is applied
var tempSkip = articleList.length;
var tempJson = {
"isFilter": this.state.isFilter,
"appliedFilter": this.state.appliedFilter,
"first": pagingCount,
"skip": tempSkip
};
this.loadGraphArticle(tempJson);
} else {
//no filter
var tempOffset = articleList.length;
var tempJson = {
"isFilter": this.state.isFilter,
"appliedFilter": this.state.appliedFilter,
"limit": pagingCount,
"offset": tempOffset
};
this.loadSqlArticle(tempJson);
}
}
}
} else {
// console.log("no more data else");
}
} else {
noMoreData = true;
}
};
renderFooter = () => {
if (!this.state.footerLoading) return null;
return (
);
};
gotIt = () => {
AsyncStorage.setItem("isFirstTime", "false");
this.setState({ loadHint: false })
}
renderEmpty = () => {
if (imagePath == undefined) {
imagePath = imageJson.collection_empty;
title = translate("ARTICLES_EMPTY1")
text = ""
links = [{ name: translate("ERESOURCES"), onPressFun: this.openEResources.bind(this) }, { name: translate("WEB"), onPressFun: this.openWeb.bind(this) }];
isLink = true;
}
return (
{this.state.errorLoading ?
:
this.state.isFilter ?
:
}
);
}
renderHeader = () => {
return (
{this.state.loadHint && varProvider.selectedCollectionName == varProvider.defaultCollectionName &&
{translate("COLLECTON_TIP")}
{"\n"}{translate("GOT_IT")}
}
)
}
renderCollectionEmpty = () => {
return (
);
}
// open/export pdf function view
onOpenWithExternalView() {
closeFlag = "externalPdfOpen";
this.closeActionSheetModal();
}
openArticleView(item) {
cloneIt = item;
const { navigate } = this.props.navigation;
if (item.type == "PDF") {
var urlMD = MD5.MD5(item.url);
var path = RNFetchBlob.fs.dirs.DocumentDir + "/" + urlMD + ".pdf";
RNFetchBlob.fs.exists(path).then((exist) => {
if (exist) {
if (Platform.OS == "android") {
navigate("PdfView", { "article": item, "path": path, "isModal": true, "callbackAddTag": this.callbackAddTag, "callbackDeleteArticle": this.callbackDeleteArticle, "refScreen": screenNames.Collections });
} else {
// let aPDFpath = urlMD + ".pdf"
var pdfObject = MVMyloftPDFViewerNativeModuleIos.openViewer(item.url, item.id);
this.iosPdfEvent(pdfObject);
}
varProvider.currentScreen = screenNames.PDFView;
this.logPdfScreenViewEvent(false);
this.updateReadStatus(item);
this.logArticleReadEvent(item);
}
else {
Toast.showShortCenter(translate("PDF_NA"));
}
});
} else {
if (item.isReadable) {
navigate('ArticleView', { "article": item, "callbackAddTag": this.callbackAddTag, "callbackDeleteArticle": this.callbackDeleteArticle, "callbackRead": this.callbackRead, "isModal": true, "refScreen": screenNames.Collections });
}
else {
if (connection.isConnectedFun()) {
navigate("BrowserView", { url: item.url, "refScreen": screenNames.Collections });
this.updateReadStatus(item);
}
else {
Toast.showShortCenter(translate("PLEASE_CONNECT"));
}
}
}
}
logPdfScreenViewEvent(isNavigatingBack) {
let screenViewJson = {
"name": isNavigatingBack ? screenNames.Collections : screenNames.PDFView,
"previous": isNavigatingBack ? screenNames.PDFView : screenNames.Collections
};
analyticsProvider.logAnalyticsJson("ScreenView", screenViewJson);
}
logArticleReadEvent(item) {
let articleReadJson = {
"name": item.title,
"url": item.url,
"type": item.type,
"source": "Collections"
};
analyticsProvider.logAnalyticsJson("ArticleRead", articleReadJson);
}
iosPdfEvent(pdfObject) {
const getAllTagSubscription = pdfObject.addListener(
'GetAllTags',
() => {
colProvider.getTagList().subscribe((data) => {
MVMyloftPDFViewerNativeModuleIos.refreshAllTagList(data);
});
}
);
const getTagSubscription = pdfObject.addListener(
'GetTags',
() => {
MVMyloftPDFViewerNativeModuleIos.refreshTagList(cloneIt.tagList);
}
);
const getHighlightSubscription = pdfObject.addListener(
'GetHighlights',
() => {
var tempList = {};
tempList["articleId"] = cloneIt.id;
colProvider.getArticleHighlightList(tempList).subscribe((data) => {
var aNewData = [];
for (var key in data) {
let aData = data[key];
aData.text = aData.highlightText;
aData.rangyid = aData.rangyId;
aData.createdAt = new Date(aData.createdAt).toISOString();
aNewData.push(aData);
}
MVMyloftPDFViewerNativeModuleIos.refreshHighlightList(aNewData);
});
}
);
const addTagSubscription = pdfObject.addListener(
'AddTags',
(addTagObject) => {
this.addTagToPdf(addTagObject);
}
);
const highlightAddSubscription = pdfObject.addListener(
'HighlightAdded',
(highlightObject) => {
this.addHighlightToPdf(highlightObject);
this.logArticleHighlightEvent();
}
);
const highlightDelSubscription = pdfObject.addListener(
'HighlightDeleted',
(highlightObject) => {
this.deleteHighlightFromPdf(highlightObject);
}
);
const viewerDismissedSubscription = pdfObject.addListener(
'ViewerWillDismiss',
() => {
// console.log("ViewerWillDismiss Collection screen");
// console.log(highlightObject);
varProvider.isPDFOpen = false;
getAllTagSubscription.remove();
getTagSubscription.remove();
getHighlightSubscription.remove();
addTagSubscription.remove();
highlightAddSubscription.remove();
highlightDelSubscription.remove();
viewerDismissedSubscription.remove();
deletePDFSubscription.remove();
this.logPdfScreenViewEvent(true);
varProvider.currentScreen = screenNames.Collections;
}
);
const deletePDFSubscription = pdfObject.addListener(
'DeletePDFArticle',
() => {
MVMyloftPDFViewerNativeModuleIos.closeViewer();
setTimeout(() => {
this.onDeleteArticle();
}, 100)
}
);
}
logArticleHighlightEvent() {
let articleHighlightJson = {
"type": "PDF"
};
analyticsProvider.logAnalyticsJson("ArticleHighlight", articleHighlightJson)
}
addTagToPdf(addTagObject) {
if (addTagObject && addTagObject["AddTags"]) {
var tagNames = addTagObject["AddTags"]["tagNames"];
var tagIds = addTagObject["AddTags"]["tags"];
var articleTagNames = addTagObject["AddTags"]["articleTags"];
var analyticsTags = [];
if (cloneIt && cloneIt.tagList && cloneIt.tagList.length != 0) {
var existingTags = cloneIt.tagList;
for (var k = 0; k < articleTagNames.length; k++) {
if (existingTags.indexOf(articleTagNames[k]) == -1) {
analyticsTags.push(articleTagNames[k]);
}
}
} else {
analyticsTags = articleTagNames;
}
this.callbackAddTag(articleTagNames);
if (tagNames.length != 0 || tagIds.length != 0) {
var randomId = [];
for (var i = 0; i < tagNames.length; i++) {
randomId.push("");
}
var tempList = {};
tempList["articleId"] = cloneIt.id;
tempList["tagName"] = tagNames;
tempList["tagId"] = tagIds;
tempList["randomId"] = randomId;
// console.log(tempList);
colProvider.addArticleTags(tempList).subscribe(() => {
});
this.logTagSaveEvent(analyticsTags, "AddTags");
}
var deleteIds = addTagObject["AddTags"]["deletedTags"];
if (deleteIds.length != 0) {
var tempList1 = {};
tempList1["articleId"] = cloneIt.id;
tempList1["tagId"] = deleteIds;
// console.log(tempList1);
colProvider.deleteArticleTags(tempList1).subscribe(() => {
});
}
}
}
logTagSaveEvent(name, source) {
let tagSaveJson = {
"name": name.toString(),
"source": source
}
analyticsProvider.logAnalyticsJson("TagSave", tagSaveJson);
}
addHighlightToPdf(highlightObject) {
if (highlightObject && highlightObject["HighlightAdded"]) {
var hjson = highlightObject["HighlightAdded"];
var jsonData = [];
jsonData.push({
"start": 0,
"end": 0,
"root": hjson["root"],
"text": hjson["text"],
"class": "myloft_highlight",
"rangyid": hjson["rangyid"]
});
var highId = apiProvider.generateUUID();
var randomId = [];
randomId.push(highId);
var tempList = {};
tempList["articleId"] = cloneIt.id;
tempList["highlightData"] = jsonData;
tempList["randomId"] = randomId;
colProvider.addArticleHighlight(tempList).subscribe((data) => {
MVMyloftPDFViewerNativeModuleIos.refreshHighlightList(data);
});
}
}
deleteHighlightFromPdf(highlightObject) {
if (highlightObject && highlightObject["HighlightDeleted"]) {
var hjson = highlightObject["HighlightDeleted"];
var tempList = {};
var hid = [];
hid.push(hjson.id);
tempList["articleId"] = cloneIt.id;
tempList["highlightId"] = hid;
colProvider.deleteArticleHighlight(tempList).subscribe(() => {
});
}
}
updateReadStatus(articleItem) {
if (!articleItem.readStatus) {
articleItem.readStatus = true;
colProvider.readArticle(articleItem).subscribe(() => {
});
this.setState({ refresh: !this.state.refresh });
}
}
closeGuide = () => {
this.setState({ showGuide: false })
setProvider.closeGuide("isCollectionsGuideShown");
}
_renderListView = ({ item }) => (
);
_renderCardView = ({ item, index }) => (
);
openTagModal = (item) => {
tagList = [];
if (item.tagList?.length > 0)
tagList = item.tagList;
this.setState({ openTagModal: true })
}
childResponser = () => {
startParentResponderTouch = false;
startChildResponderTouch = true;
}
parentResponser = () => {
if (startParentResponderTouch) {
if (startChildResponderTouch)
startChildResponderTouch = false;
else
this.closeEditMode();
}
else {
startParentResponderTouch = true;
}
}
render() {
var renderFavArticleFooter =
this.menuItemPress(favoriteArticles)}
>
{favoriteArticles.title}
;
var menu =
{translate("COLLECTIONS")}
this.addCollection()}>
{this.state.noData ?
{translate("SEARCH_EMPTY")}
:
{ this.menuItemLongPress(item) }}
onPress={() => this.menuItemPress(item)}
>
{item.title}
{item.isDefault &&
}
{item.pressed &&
{ this.childResponser() }}>
{this.state.cloneItem.type != staticConfig.collectionType && this.editTitle()}>
}
{!this.state.cloneItem.isDefault && this.state.cloneItem.type != staticConfig.collectionType && this.deleteCollection()}>
}
{!this.state.cloneItem.isDefault && this.setDefaultCollection()}>
}
{ this.closeEditMode(); drawerLockMode = "unlocked" }}>
}
}
/>
{renderFavArticleFooter}
}
{this.state.addCollectionModal &&
}
{this.state.editTitleCollectionModal &&
}
{this.state.deleteCollectionModal &&
}
{this.state.openTagModal && tagList?.length > 0 ?
: null}
;
var headerBar =
this.openMenu()}>
{varProvider.selectedCollectionName}
this.changeView()}>
this.openFilters()}>
return (
{ this.parentResponser() }}>
{ this.drawer = _drawer; varProvider.colDrawer = _drawer; }}
onDrawerClose={() => { this.onDrawerClose() }}
drawerPosition={DrawerLayout.positions.Left}
drawerLockMode={drawerLockMode}
renderNavigationView={() => menu}>
{headerBar}
{this.state.activeFilters.map((item, key) =>
(
{item.chipTitle == "tagName" ?
{item.value.map((subItem) =>
(
this.removeFilter(subItem, true)}
/>
))
}
:
{item.active &&
this.removeFilter(item)}
/>
}
}
))
}
{this.state.articleLoading &&
}
{!this.state.isCardView && !this.state.articleLoading &&
}
{this.state.isCardView && !this.state.articleLoading &&
1 && { marginHorizontal: 8 }}
extraData={this.state.refresh}
numColumns={numberOfCards}
key={numberOfCards}
ListFooterComponent={this.renderFooter}
ListEmptyComponent={this.renderEmpty}
ListHeaderComponent={this.renderHeader}
onEndReached={this.handleLoadMore}
onEndReachedThreshold={0.5}
renderItem={this._renderCardView}
/>
}
{ this.setState({ sharedOpened: false }) }}
onBackdropPress={() => { this.setState({ sharedOpened: false }) }}
modalHeight={modalHeight}
modalWidth={modalWidth}
sendTo={this.sendTo.bind(this)}
shareNativeArticle={this.shareNativeArticle.bind(this)}
isConnected={connection.isConnectedFun()}
/>
{this.state.editTitleModal &&
}
{this.state.deleteArticleModal &&
}
);
}
removeFilter(item, isTag) {
var tempFilters = this.state.activeFilters;
if (isTag) {
var tagList = tempFilters[4].value;
for (var i = 0; i < tagList.length; i++) {
if (item == tagList[i]) {
tempFilters[4].value.splice(i, 1);
if (tempFilters[4].value.length == 0) {
tempFilters[4].active = false;
}
break;
}
}
} else {
for (var i = 0; i < tempFilters.length; i++) {
if (item.chipTitle == tempFilters[i].chipTitle) {
tempFilters[i].active = false;
break;
}
}
}
this.callbackFun(tempFilters);
}
closeActionSheetModal() {
this.setState({ actionSheetModal: false });
}
// here we get callback that action sheet/share action sheet is closed, now we can perform action according to value of closeFlag
hideActionSheetModal() {
if (closeFlag == "editArticle") {
this.setState({ editTitleModal: true });
}
else if (closeFlag == "deleteArticle") {
this.setState({ deleteArticleModal: true });
}
else if (closeFlag == "actionSheet") {
this.setState({ sharedOpened: true });
}
else if (closeFlag == "externalPdfOpen") {
colProvider.onOpenWithExternalView(this.props.navigation, cloneIt)
}
else if (closeFlag == "shareVia") {
setTimeout(() => {
if (Platform.OS == "ios") {
Share.share({
message: cloneIt.url,
url: cloneIt.url,
title: cloneIt.title
}, {
// Android only:
dialogTitle: cloneIt.title,
}).then(() => {
// console.log(data);
}).catch(() => {
// console.log(err);
});
} else {
ShareIntentModule.openShareIntent(cloneIt.title, cloneIt.url, () => {
});
}
}, 400)
this.logShareEvent(cloneIt.url, "Other");
}
closeFlag = "";
}
shareArticle() {
if (connection.isConnectedFun()) {
this.closeActionSheetModal();
closeFlag = "actionSheet"
} else {
Toast.showShortCenter(translate("PLEASE_CONNECT"));
}
}
sendTo() {
const { navigate } = this.props.navigation;
if (connection.isConnectedFun()) {
this.setState({ sharedOpened: false });
navigate('ShareArticle', { "article": cloneIt, "isModal": true, "refScreen": screenNames.Collections });
} else {
Toast.showShortCenter(translate("PLEASE_CONNECT"));
}
}
shareNativeArticle() {
if (connection.isConnectedFun()) {
closeFlag = "shareVia"
this.setState({ sharedOpened: false });
}
else {
Toast.showShortCenter(translate("PLEASE_CONNECT"));
}
}
logShareEvent(url, medium) {
let shareJson = {
"medium": medium,
"url": url
};
analyticsProvider.logAnalyticsJson("Share", shareJson);
}
getEditTitleText(e) {
this.setState({ editTitleText: e });
}
onSaveEditTitle() {
if (!this.state.editTitleText) {
this.setState({ editTitleValid: true, editTitleValidationText: translate("ARTICLE_RENAME_VALIDATION") });
} else {
var trimmedTitle = this.state.editTitleText.trim();
if (trimmedTitle) {
cloneIt.title = trimmedTitle;
colProvider.editArticle(cloneIt).subscribe(() => {
});
this.setState({ editTitleValid: false, refresh: !this.state.refresh });
this.closeEditTitleModal();
} else {
this.setState({ editTitleValid: true, editTitleValidationText: translate("ARTICLE_RENAME_VALIDATION") });
}
}
}
closeEditTitleModal() {
this.setState({ editTitleModal: false })
}
closeDeleteArticleModal() {
this.setState({ deleteArticleModal: false })
}
onDeleteArticle() {
this.closeDeleteArticleModal();
//added timeout to remove lag in UI
setTimeout(() => {
for (var i = 0; i < articleList.length; i++) {
if (articleList[i].id == cloneIt.id) {
articleList.splice(i, 1);
if (articleList.length < pagingCount && !noMoreData) {
setTimeout(() => {
this.handleLoadMore({ distanceFromEnd: "NeedToFetch" });
}, 1000);
}
break;
}
}
Toast.showShortCenter(translate("ARTICLE_DELETED"));
var tempList = [];
tempList.push(cloneIt);
colProvider.deleteArticle(tempList).subscribe(() => {
});
this.setState({ refresh: !this.state.refresh });
}, 500);
}
favoriteArticle(item) {
if (item.isFavorite) {
item.isFavorite = false;
}
else {
item.isFavorite = true;
}
//if favorite articles is selected then remove the unfavorited article from list
if (varProvider.selectedCollectionId == "favoriteArticles")
this.removeFromFavorite(item);
colProvider.favoriteArticle(item).subscribe(() => {
});
this.setState({ refresh: !this.state.refresh });
}
openModal(item) {
if (item?.isPDFAvailable == 'false') {
asList[0].isGrayedOut = true;
} else {
asList[0].isGrayedOut = false;
}
if (item.readStatus) {
asList[6].title = translate("MARK_AS") + translate("UNREAD")
}
else {
asList[6].title = translate("MARK_AS") + translate("READ");
}
if (item.type == "PDF") {
asList[1].isVisible = false;
asList[0].isVisible = true; //check type is pdf then we will show open with option
} else {
asList[1].isVisible = true;
asList[0].isVisible = false;
}
this.setState({ asList: asList, actionSheetModal: true });
cloneIt = item;
}
callbackAddTag(tagList) {
tagList.sort(colProvider.SortByNameArray);
cloneIt.tagList = tagList;
this.setState({ refresh: !this.state.refresh });
}
callbackDeleteArticle() {
this.onDeleteArticle();
}
callbackRead() {
cloneIt.readStatus = true;
this.setState({ refresh: !this.state.refresh });
}
callbackCollection() {
if (varProvider.selectedCollectionName != translate("FAVORITE_ARTICLES")) {
for (var i = 0; i < articleList.length; i++) {
if (articleList[i].title == cloneIt.title) {
articleList.splice(i, 1);
if (articleList.length < pagingCount && !noMoreData) {
setTimeout(() => {
this.handleLoadMore({ distanceFromEnd: "NeedToFetch" });
}, 1000);
}
}
}
this.setState({ refresh: !this.state.refresh });
}
}
addTags() {
this.closeActionSheetModal();
const { navigate } = this.props.navigation;
navigate('AddTags', { article: cloneIt, "callbackAddTag": this.callbackAddTag, "isModal": true, "refScreen": screenNames.Collections });
}
editTitleArticle() {
this.closeActionSheetModal();
if (Platform.OS == "ios") {
this.setState({ initialValue: cloneIt.title, editTitleText: cloneIt.title, editTitleValid: false });
}
else {
this.setState({ editTitleModal: true, initialValue: cloneIt.title, editTitleText: cloneIt.title, editTitleValid: false });
}
closeFlag = "editArticle";
}
moveToCollection() {
this.closeActionSheetModal();
const { navigate } = this.props.navigation;
navigate('MoveToCollection', { "isModal": true, collectionList: collectionList, article: cloneIt, "callbackCollection": this.callbackCollection.bind(this), "refScreen": screenNames.Collections });
}
deleteArticle() {
this.closeActionSheetModal();
if (Platform.OS == "ios") {
}
else {
this.setState({ deleteArticleModal: true });
}
closeFlag = "deleteArticle";
}
markAsRead() {
this.closeActionSheetModal();
var alertMsg;
if (cloneIt.readStatus) {
cloneIt.readStatus = false;
alertMsg = translate("UNREAD");
}
else {
cloneIt.readStatus = true;
alertMsg = translate("READ");
}
colProvider.readArticle(cloneIt).subscribe(() => {
});
this.setState({ refresh: !this.state.refresh });
}
//collection side menu functions
closeEditMode() {
if (cloneIt) {
cloneIt.pressed = false;
}
setTimeout(() => {
isEditMode = false;
drawerLockMode = "unlocked"
}, 200)
this.setState({ editMode: false, refreshCollection: !this.state.refreshCollection });
}
setDefaultCollection() {
for (var i = 0; i < collectionList.length; i++) {
if (collectionList[i].isDefault) {
collectionList[i].isDefault = false;
}
}
cloneIt.isDefault = true;
cloneIt.pressed = false;
collectionList.sort(colProvider.SortByName);
//add collection marked as default to front
for (var j = 0; j < collectionList.length; j++) {
if (collectionList[j].id == cloneIt.id) {
collectionList.splice(j, 1);
collectionList.unshift(cloneIt);
break;
}
}
varProvider.defaultCollectionId = cloneIt.id;
varProvider.defaultCollectionName = cloneIt.title;
varProvider.defaultCollectionType = cloneIt.type;
AsyncStorage.multiSet([
["defaultCollectionId", varProvider.defaultCollectionId],
["defaultCollectionName", varProvider.defaultCollectionName],
["defaultCollectionType", varProvider.defaultCollectionType]
]);
colProvider.setDefaultCollection(cloneIt).subscribe(() => {
});
this.logCollectionUpdateEvent(cloneIt.title);
isEditMode = false;
drawerLockMode = "unlocked"
this.setState({ editMode: false, refreshCollection: !this.state.refreshCollection });
}
logCollectionUpdateEvent(name) {
let collectionUpdateJson = {
"name": name
};
analyticsProvider.logAnalyticsJson("CollectionUpdate", collectionUpdateJson)
}
addCollection() {
if (isEditMode) {
this.closeEditMode();
}
else {
this.setState({ addCollectionModal: true, addCollectionText: "", addCollectionValid: false });
}
}
getAddCollectionText(e) {
this.setState({ addCollectionText: e });
}
closeAddCollectionModal() {
this.setState({ addCollectionModal: false });
}
onSaveAddCollection() {
if (!this.state.addCollectionText) {
this.setState({ addCollectionValid: true, addCollectionValidationText: translate("NC_EMPTY") });
}
else {
var trimmedTitle = this.state.addCollectionText.trim();
if (trimmedTitle) {
if (config.collectionRegex.test(trimmedTitle)) {
var flagCollection = false;
for (var i = 0; i < collectionList.length; i++) {
if (collectionList[i].title.toLowerCase() == trimmedTitle.toLowerCase()) {
flagCollection = true;
}
}
if (trimmedTitle.toLowerCase() == translate("FAVORITE_ARTICLES").toLowerCase()) {
flagCollection = true;
}
if (flagCollection) {
this.setState({ addCollectionValid: true, addCollectionValidationText: translate("NC_EXIST") });
} else {
var uuid = apiProvider.generateUUID();
var title = trimmedTitle;
var updatedAt = new Date().getTime();
var tempColList = JSON.parse(JSON.stringify(collectionList));
tempColList.splice(0, 1);
var toInsertIndex = colProvider.getSortedIndex(tempColList, title, "title");
collectionList.splice(toInsertIndex + 1, 0, {
"id": uuid,
"title": title,
"description": "",
"isDefault": false,
"createdAt": updatedAt,
"updatedAt": updatedAt,
"pressed": false,
"active": false
});
colProvider.addCollection(uuid, title, updatedAt).subscribe((data) => {
varProvider.newAddedCollection["oldId"] = data.oldId;
varProvider.newAddedCollection["newId"] = data.id;
var colLen = collectionList.length;
for (var i = 0; i < colLen; i++) {
if (collectionList[i].id == data["oldId"]) {
collectionList[i]["id"] = data.id;
collectionList[i]["updatedAt"] = data.updatedAt;
break;
}
}
});
this.logCollectionSaveEvent(title);
this.setState({ addCollectionValid: false, refreshCollection: !this.state.refreshCollection });
this.closeAddCollectionModal();
}
} else {
this.setState({ addCollectionValid: true, addCollectionValidationText: translate("NC_VALIDATION") });
}
} else {
this.setState({ addCollectionValid: true, addCollectionValidationText: translate("NC_EMPTY") });
}
}
}
logCollectionSaveEvent(name) {
let collectionSaveJson = {
"name": name,
"source": "Collection"
}
analyticsProvider.logAnalyticsJson("CollectionSave", collectionSaveJson);
}
editTitle() {
this.setState({ editTitleCollectionModal: true, initialValue: cloneIt.title, editTitleCollectionText: cloneIt.title, editTitleCollectionValid: false });
}
getEditTitleCollectionText(e) {
this.setState({ editTitleCollectionText: e });
}
closeEditTitleCollectionModal() {
this.setState({ editTitleCollectionModal: false });
}
onSaveEditTitleCollection() {
if (!this.state.editTitleCollectionText) {
this.setState({ editTitleCollectionValid: true, editTitleCollectionValidationText: translate("NC_EMPTY") });
}
else {
var trimmedTitle = this.state.editTitleCollectionText.trim();
if (trimmedTitle) {
if (config.collectionRegex.test(trimmedTitle)) {
var flagCollection = false;
for (var i = 0; i < collectionList.length; i++) {
if (collectionList[i].title.toLowerCase() == trimmedTitle.toLowerCase()) {
if (collectionList[i].title == cloneIt.title) {
if (trimmedTitle == cloneIt.title) {
flagCollection = true;
}
}
else {
flagCollection = true;
}
}
}
if (trimmedTitle.toLowerCase() == translate("FAVORITE_ARTICLES").toLowerCase()) {
flagCollection = true;
}
if (flagCollection) {
this.setState({ editTitleCollectionValid: true, editTitleCollectionValidationText: translate("NC_EXIST") });
} else {
cloneIt.title = trimmedTitle;
cloneIt.pressed = false;
//update the title of collection
for (var j = 0; j < collectionList.length; j++) {
if (collectionList[j].id == cloneIt.id) {
collectionList[j].title = cloneIt.title;
if (collectionList[j].active === true) {
varProvider.selectedCollectionName = cloneIt.title;
}
collectionList[j].pressed = false;
break;
}
}
//sort the collection list
collectionList.sort(colProvider.SortByName);
//move collection marked as default to front
for (var j = 0; j < collectionList.length; j++) {
if (collectionList[j].isDefault) {
let tempobj = collectionList[j];
collectionList.splice(j, 1);
collectionList.unshift(tempobj);
break;
}
}
colProvider.editCollection(cloneIt).subscribe(() => {
});
isEditMode = false;
drawerLockMode = "unlocked";
this.setState({ editTitleCollectionValid: false, editMode: false, refreshCollection: !this.state.refreshCollection });
this.closeEditTitleCollectionModal();
}
} else {
this.setState({ editTitleCollectionValid: true, editTitleCollectionValidationText: translate("NC_VALIDATION") });
}
} else {
this.setState({ editTitleCollectionValid: true, editTitleCollectionValidationText: translate("NC_EMPTY") });
}
}
}
deleteCollection() {
this.setState({ deleteCollectionModal: true });
}
closeDeleteCollectionModal() {
this.setState({ deleteCollectionModal: false });
}
onDeleteCollection() {
var index, colIdToDelete;
for (var i = 0; i < collectionList.length; i++) {
if (collectionList[i].title == cloneIt.title) {
colIdToDelete = collectionList[i].id;
collectionList.splice(i, 1);
index = i;
break;
}
}
colProvider.deleteCollection(cloneIt).subscribe(() => {
if (varProvider.selectedCollectionId != colIdToDelete || varProvider.selectedCollectionId == varProvider.defaultCollectionId) {
if (!varProvider.isSyncInProgress) {
colProvider.getSyncArticles(0);
}
}
});
isEditMode = false;
drawerLockMode = "unlocked",
this.setState({ editMode: false });
this.closeDeleteCollectionModal();
if (varProvider.selectedCollectionId == colIdToDelete) {
if (index == 0) {
//select collection and load its article
this.selectColAndLoadArticle(index);
} else {
//select collection i-1 and load its articles
this.selectColAndLoadArticle(index - 1);
}
}
}
closeTagBottomSheet = () => {
this.setState({ openTagModal: false });
}
menuItemLongPress(item) {
if (item.isDefault && item.type != staticConfig.collectionType || !item.isDefault) {
for (var i = 0; i < collectionList.length; i++) {
if (collectionList[i].pressed) {
collectionList[i].pressed = false;
}
}
item.pressed = true;
isEditMode = true;
drawerLockMode = "locked-open",
this.setState({ editMode: true, cloneItem: item, refreshCollection: !this.state.refreshCollection });
cloneIt = item;
}
}
menuItemPress(item) {
// console.log(item)
if (isEditMode) {
this.closeEditMode();
}
else {
this.drawer.closeDrawer();
for (var i = 0; i < collectionList.length; i++) {
if (collectionList[i].active) {
collectionList[i].active = false;
}
}
item.active = true;
if (item.id != "favoriteArticles") {
favoriteArticles.active = false;
imagePath = imageJson.collection_empty;
title = translate("ARTICLES_EMPTY1")
text = ""
links = [{ name: translate("ERESOURCES"), onPressFun: this.openEResources.bind(this) }, { name: translate("WEB"), onPressFun: this.openWeb.bind(this) }];
isLink = true;
}
else {
imagePath = imageJson.fav_article_empty;
title = translate("ARTICLES_FAV_EMPTY")
text = translate("ARTICLES_FAV_EMPTY_DATA1")
isLink = false;
}
noMoreData = false;
articleList = [];
varProvider.selectedCollectionName = item.title;
varProvider.selectedCollectionId = item.id;
graphError = ""
this.setState({ refreshCollection: !this.state.refreshCollection, articleLoading: true, errorLoading: false, articleLength: 0 });
setTimeout(() => {
if (item.id == "favoriteArticles") {
if (this.state.isFilter) {
this.callbackFun(this.state.activeFilters);
} else {
var tempJson = {
"offset": 0
};
this.loadFavoriteArticles(tempJson);
}
} else {
if (this.state.isFilter) {
this.callbackFun(this.state.activeFilters);
} else {
isFirstTime = false;
this.loadArticleList();
}
}
}, 450);
}
}
openEResources() {
varProvider.activeTabIndex = 1;
const { navigate } = this.props.navigation;
navigate('Content');
}
openWeb() {
if (connection.isConnectedFun()) {
varProvider.openSearch = true;
varProvider.activeTabIndex = 0;
const { navigate } = this.props.navigation;
navigate('Home');
}
else {
Toast.showShortCenter(translate("PLEASE_CONNECT"));
}
}
loadFavoriteArticles(tempJson) {
if (tempJson.offset == 0)
articleList = [];
colProvider.getFavoriteArticleSql(tempJson).then((data) => {
if (data.length < pagingCount) {
noMoreData = true;
}
if (data.length != 0) {
var articleCount = articleList.length;
this.processArticleList(data, articleCount);
} else {
this.setState({ refresh: !this.state.refresh, articleLoading: false, footerLoading: false, articleLength: articleList.length });
}
isInfiniteOn = false;
})
}
removeFromFavorite(item) {
for (var i = 0; i < articleList.length; i++) {
if (articleList[i].id == item.id) {
articleList.splice(i, 1);
break;
}
}
this.setState({ refresh: !this.state.refresh });
}
selectColAndLoadArticle(index) {
for (var i = 0; i < collectionList.length; i++) {
if (collectionList[i].active) {
collectionList[i].active = false;
}
}
collectionList[index].active = true;
graphError = ""
this.setState({ refreshCollection: !this.state.refreshCollection, articleLoading: true, errorLoading: false, articleLength: 0 });
noMoreData = false;
articleList = [];
varProvider.selectedCollectionName = collectionList[index].title;
varProvider.selectedCollectionId = collectionList[index].id;
if (this.state.isFilter) {
this.callbackFun(this.state.activeFilters);
} else {
isFirstTime = false;
this.loadArticleList();
}
cloneIt = collectionList[index];
}
onDrawerClose() {
if (cloneIt) {
cloneIt.pressed = false;
}
if (this.refs["searchInput"]) {
this.refs["searchInput"].blur();
}
isEditMode = false;
drawerLockMode = "unlocked";
this.setState({ editMode: false, refreshCollection: !this.state.refreshCollection });
}
}