homeActions.js 7.59 KB
/**
 * # guideActions.js
 *
 * App user guide
 *
 */
'use strict';

import {Actions} from 'react-native-router-flux';
import HomeService from '../../services/HomeService';
import timeago from 'timeago.js';

const {

	HOME_BNS_REQUEST,
    HOME_BNS_SUCCESS,
    HOME_BNS_FAILURE,

	HOME_RECOMMENDATION_REQUEST,
    HOME_RECOMMENDATION_SUCCESS,
    HOME_RECOMMENDATION_FAILURE,

	GO_TO_SECTION,

	END_REFRESHING,
	INCREASE_ERROR_COUNT,
    RESET_ERROR_COUNT,

} = require('../../constants/actionTypes').default;

export function bnsRequest() {
    return {
        type: HOME_BNS_REQUEST,
    };
}

export function bnsSuccess(json) {
    return {
        type: HOME_BNS_SUCCESS,
        payload: json
    };
}

export function bnsFailure(error) {
    return {
        type: HOME_BNS_FAILURE,
        payload: error
    };
}

export function bannerNoticeSection() {
	return (dispatch, getState) => {

		let {app, home} = getState();
		if (home.isFetching) {
			return;
		}
		dispatch(bnsRequest());
        return new HomeService().bannerNoticeSection(app.container)
            .then(json => {
				let payload = parseBNS(json);
                dispatch(bnsSuccess(payload));
            })
            .catch(error => {
                dispatch(bnsFailure(error));
            });
	};
}

export function bannerNoticeSectionOnlyDispathSuccess() {
	return (dispatch, getState) => {

		let {app, home} = getState();
		if (home.isFetching) {
			return;
		}
		// dispatch(bnsRequest());
        return new HomeService().bannerNoticeSection(app.container)
            .then(json => {
				let payload = parseBNS(json);
                dispatch(bnsSuccess(payload));
            })
            .catch(error => {
                // dispatch(bnsFailure(error));
            });
	};
}

export function recommendationRequest(ptr) {
    return {
        type: HOME_RECOMMENDATION_REQUEST,
		payload: ptr,
    };
}

export function recommendationSuccess(json) {
    return {
        type: HOME_RECOMMENDATION_SUCCESS,
        payload: json
    };
}

export function recommendationFailure(error) {
    return {
        type: HOME_RECOMMENDATION_FAILURE,
        payload: error
    };
}

export function recommendation(ptr = false) {
	return (dispatch, getState) => {
		let {home, user} = getState();
		if (home.recommendation.isFetching || (!ptr && home.recommendation.endReached) || home.recommendation.error !== null) {
			return;
		}

		dispatch(recommendationRequest(ptr));


		let uid = user.profile.uid;
		let lastedTime = 0;
		if (!ptr) {
			lastedTime = home.recommendation.lastedTime;
		}
		let limit = 10;
        return new HomeService().recommendation(uid, lastedTime, limit)
            .then(json => {
				let payload = parseRecommendation(json);
				if (!ptr) {
					let oldList = home.recommendation.list.toJS();
					let list = [...oldList, ...payload.list];
					payload.list = list;
				}
                dispatch(recommendationSuccess(payload));
            })
            .catch(error => {
                dispatch(recommendationFailure(error));
				dispatch(increaseErrorCount(1));
            });
	};
}

function shouldFetchRecommendation(dispatch, getState) {
	let {home} = getState();
	if (home.recommendation.isFetching || (!home.ptr && home.recommendation.endReached) || home.recommendation.error) {
		return false;
	}
	// return false;
	// let errorCount = home.recommendation.errorCount;
	// let firstErrorTime = home.recommendation.firstErrorTime;
	// let nowSeconds = (new Date()).getTime();
	// let timePass = nowSeconds - firstErrorTime;
	// console.log('timePass');
	// console.log(firstErrorTime);
	// console.log(nowSeconds);
	// console.log(timePass);
	// console.log('errorCount');
	// console.log(timePass);
	// if (timePass < 60 * 1000) {
	// 	if (errorCount > 3) {
	// 		return false;
	// 	} else {
	// 		return true;
	// 	}
	// } else {
	// 	dispatch(resetErrorCount());
	// 	return true;
	// }

	return true;
}

export function increaseErrorCount(number) {
    return {
        type: INCREASE_ERROR_COUNT,
		payload: number,
    };
}

export function resetErrorCount() {
    return {
        type: RESET_ERROR_COUNT,
    };
}

export function goToSection(section, previousScene) {
	Actions.Section();
	return {
		type: GO_TO_SECTION,
        payload: {...section, previousScene},
	};
}

function parseBNS(json) {
	let {resourceList, forumInfo} = json;
	let {advertList, textNoticeList} = resourceList;

	let bannerList = [];
	let bannerDuration = '3';
	if (advertList && advertList.list) {
		if (advertList.list) {
			advertList.list.map((item, i) => {
				let url = item.url.length > 0 ? item.url[0] : '';
				item.url = url;
			});
		}
		bannerList = advertList.list;
		if (advertList.speed) {
			bannerDuration = advertList.speed;
		}
	}

	let noticeList = [];
	let noticeDuration = '3';
	let noticeOpen = 'N';
	if (textNoticeList && textNoticeList.list) {
		noticeList = textNoticeList.list;
		if (textNoticeList.time) {
			noticeDuration = textNoticeList.time;
		};
		if (noticeList.open) {
			noticeOpen = noticeList.open;
		}
	}

	let section = [];
	forumInfo.map((item, i) => {
		let {hotPost, newPost} = item;

		let sectionItem = {
			header: {
				id: item.forumCode,
				logo: item.forumPic,
				title: item.forumName,
				postNum: item.postsNum,
				commentNum: item.commentsNum,
				laudCount: item.praiseNum,
			},
			hot: {
				avatar: hotPost && hotPost.user && hotPost.user.headIcon ? hotPost.user.headIcon : '',
				content: hotPost && hotPost.contentData ? decodeURI(hotPost.contentData) : '',
				hasImg: hotPost && hotPost.hasImgFlg ? hotPost.hasImgFlg : '',
				postId: hotPost && hotPost.postId ? hotPost.postId : '',
				postTitle: hotPost && hotPost.postsTitle ? decodeURI(hotPost.postsTitle) : '',
			},
			new: {
				avatar: newPost && newPost.user && newPost.user.headIcon ? newPost.user.headIcon : '',
				content: newPost && newPost.contentData ? decodeURI(newPost.contentData) : '',
				hasImg: newPost && newPost.hasImgFlg ? newPost.hasImgFlg : '',
				postId: newPost && newPost.postId ? newPost.postId : '',
				postTitle: newPost && newPost.postsTitle ? decodeURI(newPost.postsTitle) : '',
			},
			num: {
				onedayAddNum: item.oneDayAddNum,
			},
		};
		section.push(sectionItem);
	});

	return {
		banner: {
			list: bannerList,
			duration: parseFloat(bannerDuration),
		},
		notice: {
			list: noticeList,
			duration: parseFloat(noticeDuration),
			open: noticeOpen,
		},
		section,
	};
}

function parseRecommendation(json) {
	let {lastedTime, list} = json;
	let posts = [];
	list.map((item, i) => {
		let {authorInfo, blocks} = item;

		let desc = '';
		let thumbs = [];
		blocks.map((item, i) => {
			if (desc === '' && item.templateKey === 'text') {
				desc = decodeURI(item.contentData);
			}

			if (item.templateKey === 'image') {
				let thumb = {
					src: item.contentData,
				};
				thumbs.push(thumb);
			}
		});

		let avatar = authorInfo && authorInfo.headIcon ? authorInfo.headIcon : '';
		let uid = authorInfo && authorInfo.uid ? authorInfo.uid : 0;
		let name = authorInfo && authorInfo.nickName ? authorInfo.nickName : '';
		let createTime = item.createTime;
		let timeagoStr = timeago().format(createTime, 'zh_CN');
		let isLike = item.hasPraise === 'Y' ? true : false;
		let title = item.postsTitle ? decodeURI(item.postsTitle) : '';

		let post = {
			author: {
				avatar,
				uid,
				name,
			},
			createTime,
			timeago: timeagoStr,
			isTop: item.isIndexTop === 0 ? false : true,
			isLike,
			title,
			desc,
			thumbs,
			section: {
				id: item.forumCode,
				name: item.forumName,
			},
			commentCount: item.comment,
			likeCount: item.praise,
		}

		posts.push(post);
	});

	let endReached = posts.length == 0;
	return {
		lastedTime,
		list: posts,
		endReached,
	}
}