cn.com.sunjiesh.wechat.handler.WechatMaterialHandler.java Source code

Java tutorial

Introduction

Here is the source code for cn.com.sunjiesh.wechat.handler.WechatMaterialHandler.java

Source

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package cn.com.sunjiesh.wechat.handler;

import cn.com.sunjiesh.utils.thirdparty.base.HttpService;
import cn.com.sunjiesh.wechat.common.WechatMessageMediaTypeConstants;
import cn.com.sunjiesh.wechat.common.WechatUrlConstants;
import cn.com.sunjiesh.wechat.entity.material.BatchgetMaterialItemContent;
import cn.com.sunjiesh.wechat.entity.material.BatchgetMaterialNews;
import cn.com.sunjiesh.wechat.entity.material.BatchgetMaterialNewsItem;
import cn.com.sunjiesh.wechat.entity.material.BatchgetMaterialOther;
import cn.com.sunjiesh.wechat.entity.material.BatchgetMaterialOtherItem;
import cn.com.sunjiesh.wechat.entity.material.MaterialVideo;
import cn.com.sunjiesh.wechat.model.request.material.MaterialNewsRequest;
import cn.com.sunjiesh.wechat.model.request.material.MaterialVideoRequest;
import cn.com.sunjiesh.wechat.model.response.WechatAddMaterialNewsResponse;
import cn.com.sunjiesh.wechat.model.response.matrerial.MaterialNewsResponse;
import cn.com.sunjiesh.wechat.model.response.media.WechatMaterialCountResponse;
import cn.com.sunjiesh.xcutils.common.base.ServiceException;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import java.io.File;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import org.apache.http.HttpResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * ??Handler
 *
 * @author tom
 */
public class WechatMaterialHandler extends WechatBaseHandler {

    private static final Logger LOGGER = LoggerFactory.getLogger(WechatMaterialHandler.class);

    /**
     * ??
     *
     * @param materialNewsList ??
     * @param accessToken AccessToken
     * @return 
     * @throws ServiceException ServiceException
     */
    public static WechatAddMaterialNewsResponse addMaterialNews(List<MaterialNewsRequest> materialNewsList,
            String accessToken) throws ServiceException {
        //url and params
        String url = getRequestUrl(WechatUrlConstants.MATERIAL_ADD_NEWS, accessToken);
        JSONArray articleJsonArr = new JSONArray();
        materialNewsList.stream().map((media) -> materiaNewsToJsonObj(media)).forEach((articleJson) -> {
            articleJsonArr.add(articleJson);
        });
        JSONObject requestJson = new JSONObject();
        requestJson.put("articles", articleJsonArr);

        JSONObject responseJson = getWxJSONObjectResponseFromHttpPostMethod(url, requestJson);
        String mediaId = responseJson.getString("media_id");

        WechatAddMaterialNewsResponse response = new WechatAddMaterialNewsResponse();
        response.setMediaId(mediaId);
        return response;
    }

    /**
     * ??
     *
     * @param mediaId mediaId
     * @param mediaList mediaList
     * @param index index
     * @param accessToken AccessToken
     * @throws ServiceException ServiceException
     */
    public static void updateMaterialNews(String mediaId, List<MaterialNewsRequest> mediaList, Integer index,
            String accessToken) throws ServiceException {
        //url and params
        String url = getRequestUrl(WechatUrlConstants.MATERIAL_UPDATE_NEWS, accessToken);
        JSONArray articleJsonArr = new JSONArray();
        mediaList.stream().map((media) -> materiaNewsToJsonObj(media)).forEach((articleJson) -> {
            articleJsonArr.add(articleJson);
        });
        JSONObject requestJson = new JSONObject();
        requestJson.put("articles", articleJsonArr);
        requestJson.put("media_id", mediaId);
        requestJson.put("index", index);

        getWxJSONObjectResponseFromHttpPostMethod(url, requestJson);
    }

    /**
     * ??URL
     * ????????5000??jpg/png??1MB
     *
     * @param file 
     * @param accessToken AccessToken
     * @return URL
     * @throws ServiceException ServiceException
     */
    public static String uploadImg(File file, String accessToken) throws ServiceException {
        String url = getRequestUrl(WechatUrlConstants.MEDIA_UPLOADIMG, accessToken);
        String[] fileParamKeys = new String[] { "media" };
        File[] files = new File[] { file };
        JSONObject responseJson = getWxJSONObjectResponseFromHttpPostMethod(url, fileParamKeys, files);
        String imgUrl = responseJson.getString("url");
        return imgUrl;
    }

    /**
     * ??
     *
     * @param file file
     * @param type video
     * @param video video
     * @param accessToken AccessToken
     * @throws ServiceException ServiceException
     */
    public static void addMaterial(File file, String type, MaterialVideoRequest video, String accessToken)
            throws ServiceException {

        String url = getRequestUrl(WechatUrlConstants.MATERIAL_ADD_MATERIAL, accessToken);
        String[] fieldParamKeys = new String[] { "type" };
        String[] fieldParamValues = new String[] { type };
        if (type.equalsIgnoreCase(WechatMessageMediaTypeConstants.MEDIA_TYPE_VIDEO)) {
            JSONObject description = new JSONObject();
            description.put("title", video.getTitle());
            description.put("introduction", video.getDescription());
            fieldParamKeys = new String[] { "description" };
            fieldParamValues = new String[] { description.toJSONString() };
        }
        String[] fileParamKeys = new String[] { "media" };
        File[] files = new File[] { file };
        JSONObject responseJson = getWxJSONObjectResponseFromHttpPostMethod(url, fileParamKeys, files,
                fieldParamKeys, fieldParamValues);
        String mediaId = responseJson.getString("media_id");
        String responseUrl = responseJson.getString("url");
        LOGGER.debug("mediaId=" + mediaId);
        LOGGER.debug("responseUrl=" + responseUrl);
    }

    /**
     * ????
     *
     * @param mediaId ????media_id
     * @param accessToken AccessToken
     * @return ?
     * @throws ServiceException ServiceException
     */
    public static List<MaterialNewsResponse> getMaterialNews(String mediaId, String accessToken)
            throws ServiceException {
        //url and param
        String url = getRequestUrl(WechatUrlConstants.MATERIAL_GET_MATERIAL, accessToken);
        JSONObject requestJson = new JSONObject();
        requestJson.put("media_id", mediaId);

        JSONObject responseJson = getWxJSONObjectResponseFromHttpPostMethod(url, requestJson);
        JSONArray newsItemArray = responseJson.getJSONArray("news_item");
        List<MaterialNewsResponse> mediaList = new ArrayList<MaterialNewsResponse>();
        for (int index = 0; index < newsItemArray.size(); index++) {
            JSONObject newsItemJson = newsItemArray.getJSONObject(index);
            MaterialNewsResponse media = jsonObjToMateriaNews(newsItemJson);
            mediaList.add(media);
        }

        return mediaList;
    }

    /**
     * ???
     *
     * @param mediaId ????media_id
     * @param accessToken
     * @return ???
     * @throws ServiceException ServiceException
     */
    public static MaterialVideo getMaterialVideo(String mediaId, String accessToken) throws ServiceException {
        //url and param
        String url = getRequestUrl(WechatUrlConstants.MATERIAL_GET_MATERIAL, accessToken);
        JSONObject requestJson = new JSONObject();
        requestJson.put("media_id", mediaId);

        JSONObject responseJson = getWxJSONObjectResponseFromHttpPostMethod(url, requestJson);
        String title = responseJson.getString("title");
        String description = responseJson.getString("description");
        String downUrl = responseJson.getString("down_url");
        MaterialVideo video = new MaterialVideo();
        video.setTitle(title);
        video.setDescription(description);
        video.setDownUrl(downUrl);

        return video;
    }

    /**
     * ??????
     *
     * @param mediaId ????media_id
     * @param fileType jpeg
     * @param accessToken
     * @return ?????
     * @throws ServiceException ServiceException
     */
    public static File getMaterialFile(String mediaId, String fileType, String accessToken)
            throws ServiceException {
        //url and param
        String url = getRequestUrl(WechatUrlConstants.MATERIAL_GET_MATERIAL, accessToken);
        JSONObject requestJson = new JSONObject();
        requestJson.put("media_id", mediaId);

        //call wx service
        HttpService httpService = new HttpService();
        //Content-Typetext/plain
        HttpResponse httpResponse = httpService.getHttpResponseFromHttpPostMethod(url, requestJson);
        File file = getFileResponseFromHttpResponse(httpResponse, fileType);
        return file;
    }

    /**
     * ??
     *
     * @param mediaId mediaId
     * @param accessToken
     * @throws ServiceException ServiceException
     */
    public static void deleteMaterial(String mediaId, String accessToken) throws ServiceException {
        //url and param
        String url = getRequestUrl(WechatUrlConstants.MATERIAL_DELETE_MATERIAL, accessToken);
        JSONObject requestJson = new JSONObject();
        requestJson.put("media_id", mediaId);
        getWxJSONObjectResponseFromHttpPostMethod(url, requestJson);

    }

    /**
     * ???
     *
     * @param accessToken
     * @return ??
     * @throws ServiceException ServiceException
     */
    public static WechatMaterialCountResponse getMaterialCount(String accessToken) throws ServiceException {
        String url = getRequestUrl(WechatUrlConstants.MATERIAL_GET_MATERIALCOUNT, accessToken);
        JSONObject responseJson = getWxJSONObjectResponseFromHttpGetMethod(url);
        int voiceCount = responseJson.getIntValue("voice_count");
        int videoCount = responseJson.getIntValue("video_count");
        int imageCount = responseJson.getIntValue("image_count");
        int newsCount = responseJson.getIntValue("news_count");
        WechatMaterialCountResponse materialCount = new WechatMaterialCountResponse();
        materialCount.setVideoCount(videoCount);
        materialCount.setImageCount(imageCount);
        materialCount.setVoiceCount(voiceCount);
        materialCount.setNewsCount(newsCount);
        return materialCount;

    }

    /**
     * ????
     *
     * @param offset ?????0?? 
     * @param count ????120
     * @param accessToken
     * @return ???
     * @throws ServiceException ServiceException
     */
    public static BatchgetMaterialNews batchgetMaterialNews(int offset, int count, String accessToken)
            throws ServiceException {
        String type = "news";
        JSONObject responseJson = batchgetMaterial(offset, count, type, accessToken);

        //?BatchgetMaterial
        BatchgetMaterialNews batchgetMaterial = new BatchgetMaterialNews();
        int totalCount = responseJson.getIntValue("total_count");
        int itemCount = responseJson.getIntValue("item_count");
        batchgetMaterial.setTotalCount(totalCount);
        batchgetMaterial.setItemCount(itemCount);
        JSONArray itemArr = responseJson.getJSONArray("item");
        for (int index = 0; index < itemArr.size(); index++) {
            JSONObject itemJson = itemArr.getJSONObject(index);
            String mediaId = itemJson.getString("media_id");
            Long updateTime = itemJson.getLong("update_time");
            JSONObject contentJson = itemJson.getJSONObject("content");
            JSONArray newsItemArr = contentJson.getJSONArray("news_item");
            List<MaterialNewsResponse> mediaList = new ArrayList<>();
            for (int newsItemIndex = 0; newsItemIndex < newsItemArr.size(); newsItemIndex++) {
                JSONObject newsItemJson = newsItemArr.getJSONObject(newsItemIndex);
                MaterialNewsResponse media = jsonObjToMateriaNews(newsItemJson);
                mediaList.add(media);
            }
            Calendar updateTimeCal = Calendar.getInstance();
            updateTimeCal.setTimeInMillis(updateTime);
            BatchgetMaterialItemContent batchgetMaterialItemContent = new BatchgetMaterialItemContent();
            batchgetMaterialItemContent.setNewsList(mediaList);
            BatchgetMaterialNewsItem item = new BatchgetMaterialNewsItem();
            item.setMediaId(mediaId);
            item.setContent(batchgetMaterialItemContent);
            item.setUpdateTime(updateTimeCal.getTime());

        }

        return batchgetMaterial;
    }

    /**
     * ?????
     *
     * @param type ??image?video? voice?news
     * @param offset ?????0?? 
     * @param count ????120
     * @return ????
     * @throws ServiceException ServiceException
     */
    public static BatchgetMaterialOther batchgetMaterialOther(String type, int offset, int count,
            String accessToken) throws ServiceException {

        //??
        if (offset < 0) {
            throw new ServiceException("offset??0");
        }
        if (count < 1 || count > 20) {
            throw new ServiceException("count??1-20");
        }

        JSONObject responseJson = batchgetMaterial(offset, count, type, accessToken);
        //?BatchgetMaterial
        BatchgetMaterialOther batchgetMaterial = new BatchgetMaterialOther();
        int totalCount = responseJson.getIntValue("total_count");
        int itemCount = responseJson.getIntValue("item_count");
        batchgetMaterial.setTotalCount(totalCount);
        batchgetMaterial.setItemCount(itemCount);
        JSONArray itemArr = responseJson.getJSONArray("item");
        for (int index = 0; index < itemArr.size(); index++) {
            JSONObject itemJson = itemArr.getJSONObject(index);
            String mediaId = itemJson.getString("media_id");
            Long updateTime = itemJson.getLong("update_time");
            String name = itemJson.getString("name");
            String url = itemJson.getString("url");

            Calendar updateTimeCal = Calendar.getInstance();
            updateTimeCal.setTimeInMillis(updateTime);
            BatchgetMaterialOtherItem item = new BatchgetMaterialOtherItem();
            item.setMediaId(mediaId);
            item.setUpdateTime(updateTimeCal.getTime());
            item.setUrl(url);
            item.setName(name);
            batchgetMaterial.getItemList().add(item);
        }

        return batchgetMaterial;
    }

    /**
     * MaterialNews?JSON
     *
     * @param media media
     * @return JSON
     */
    private static JSONObject materiaNewsToJsonObj(MaterialNewsRequest media) {
        JSONObject articleJson = new JSONObject();
        articleJson.put("title", media.getTitle());
        articleJson.put("thumb_media_id", media.getThumbMediaId());
        articleJson.put("author", media.getAuthor());
        articleJson.put("digest", media.getDigest());
        articleJson.put("show_cover_pic", media.isShowCoverPic() ? "1" : "0");
        articleJson.put("content", media.getContent());
        articleJson.put("content_source_url", media.getContentSourceUrl());
        return articleJson;
    }

    /**
     * JSON?MaterialNews
     *
     * @param newsItemJson
     * @return MaterialNews
     */
    private static MaterialNewsResponse jsonObjToMateriaNews(JSONObject newsItemJson) {
        String title = newsItemJson.getString("title");
        String thumbMediaId = newsItemJson.getString("thumb_media_id");
        byte showCoverPic = newsItemJson.getByte("show_cover_pic");
        String author = newsItemJson.getString("author");
        String digest = newsItemJson.getString("digest");
        String content = newsItemJson.getString("content");
        String newsItemUrl = newsItemJson.getString("url");
        String contentSourceUrl = newsItemJson.getString("content_source_url");
        MaterialNewsResponse media = new MaterialNewsResponse();
        media.setAuthor(author);
        media.setContent(content);
        media.setContentSourceUrl(contentSourceUrl);
        media.setTitle(title);
        media.setThumbMediaId(thumbMediaId);
        media.setShowCoverPic((showCoverPic == 1));
        media.setDigest(digest);
        media.setUrl(newsItemUrl);
        return media;
    }

    /**
     * ???
     *
     * @param offset offset
     * @param count count
     * @param type type
     * @return ??
     * @throws ServiceException
     */
    private static JSONObject batchgetMaterial(int offset, int count, String type, String accessToken)
            throws ServiceException {
        String url = getRequestUrl(WechatUrlConstants.MATERIAL_BATCHGET_MATERIAL, accessToken);
        JSONObject requestJson = new JSONObject();
        requestJson.put("type", type);
        requestJson.put("offset", offset);
        requestJson.put("count", count);

        JSONObject responseJson = getWxJSONObjectResponseFromHttpPostMethod(url, requestJson);
        return responseJson;
    }
}