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

import {Actions} from 'react-native-router-flux';
import HomeService from '../../services/HomeService';
import timeago from '../../utils/timeago';
import {number10KFormater} from '../../utils/numberFormater';
import {loginThenSyncUserInfo} from '../user/userActions';

const {

	HOME_BNS_REQUEST,
    HOME_BNS_SUCCESS,
    HOME_BNS_FAILURE,

	HOME_RECOMMENDATION_REQUEST,
    HOME_RECOMMENDATION_SUCCESS,
    HOME_RECOMMENDATION_FAILURE,

	GO_TO_SECTION,
	GO_TO_USER_THAT_NOT_ME,
	GO_TO_POST,

	POST_LIKE_REQUEST,
    POST_LIKE_SUCCESS,
    POST_LIKE_FAILURE,
    POST_UNLIKE_REQUEST,
    POST_UNLIKE_SUCCESS,
    POST_UNLIKE_FAILURE,

	GO_TO_USER,
	SYNC_USER_REQUEST,
    SYNC_USER_SUCCESS,
    SYNC_USER_FAILURE,

	END_REFRESHING,
	INCREASE_ERROR_COUNT,
    RESET_ERROR_COUNT,

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

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

export function goToUserOrMe(uid) {
    return (dispatch, getState) => {

        let {user} = getState();
        if (uid	!= 0 && uid == user.profile.uid) {
            Actions.User();
        } else {
            Actions.UserThatNotMe();
			dispatch({
	            type: GO_TO_USER_THAT_NOT_ME,
	            payload: uid,
	        });
        }
	};
}

export function goToPost(id) {
	Actions.SubjectPost();
	return {
		type: GO_TO_POST,
        payload: id,
	};
}

export function likeOperation(post) {
	return (dispatch, getState) => {

		let operation = () => {
			if (post.get('isLike')) {
				dispatch(postUnlike(post.get('id')));
			} else {
				dispatch(postLike(post.get('id')));
			}
		};

		let {user} = getState();
		if (user.profile.uid !== 0) {
			operation();
		} else {
			dispatch(loginThenSyncUserInfo(operation));
		}
	};
}

export function postLikeRequest(json) {
    return {
        type: POST_LIKE_REQUEST,
        payload: json
    };
}

export function postLike(postId) {
	return (dispatch, getState) => {
		dispatch(postLikeRequest(postId));
		let {user} = getState();
        return new HomeService().postLike(postId, user.profile.uid)
            .then(json => {
				dispatch({
					type: POST_LIKE_SUCCESS
				})
                __DEV__ && console.log(json);
            })
            .catch(error => {
				__DEV__ && console.log(error);
            });
	};
}

export function postUnlikeRequest(json) {
    return {
        type: POST_UNLIKE_REQUEST,
        payload: json
    };
}

export function postUnlike(postId) {
	return (dispatch, getState) => {
		dispatch(postUnlikeRequest(postId));
		let {user} = getState();
        return new HomeService().postUnlike(postId, user.profile.uid)
            .then(json => {
				dispatch({
					type: POST_UNLIKE_SUCCESS
				})
				__DEV__ && console.log(json);
            })
            .catch(error => {
				__DEV__ && console.log(error);
            });
	};
}

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 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 (ptr) {
			//下拉刷新直接执行
		} else {
			// 1.当次请求不是下拉刷新,同时正在进行下拉刷新的请求,跳出
			// 2.当次请求不是下拉刷新,同时接口请求正在加载中, 跳出
			// 3.当次请求不是下拉刷新,数据已全部加载完成,跳出
			if (home.ptr || home.recommendation.isFetching || home.recommendation.endReached || home.recommendation.error) {
				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));
            });
	};
}

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

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

export function goToUser(user, previousScene) {
	Actions.User();
	return {
		type: GO_TO_USER,
        payload: {...user, previousScene},
	};
}

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

	let bannerList = advertList ? advertList : [];
	let bannerDuration = '3';

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

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

		let sectionItem = {
			header: {
				id: item.forumCode ? item.forumCode : 0,
				logo: item.forumPic ? item.forumPic : '',
				title: item.forumName ? item.forumName : '',
				desc: item.forumDesc ? item.forumDesc : '',
				post: number10KFormater(item.postsNum),
				comment: number10KFormater(item.commentsNum),
				like: number10KFormater(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 && list.map((item, i) => {
		let {authorInfo, blocks} = item;

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

			if (item.templateKey === 'image') {
				let thumb = {
					src: 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(createTime);
		let isLike = item.hasPraise === 'Y' ? true : false;
		let title = item.postsTitle ? decodeURI(item.postsTitle) : '';
		let id = item.id ? item.id : 0;

		let post = {
			author: {
				avatar,
				uid,
				name,
			},
			createTime,
			timeago: timeagoStr,
			isTop: item.isIndexTop === 0 ? false : true,
			isLike,
			id,
			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,
	}
}