/// <summary>
        /// 根据content获取回复内容,判断文件是否过期,过去需要重新传
        /// </summary>
        /// <param name="News"></param>
        /// <param name="iId"></param>
        /// <returns></returns>
        public static string GetMediaIDByNewsInfo(NewsInfoView News, int iId)
        {
            if (DateTimeHelper.GetDateTimeFromXml(News.MediaCreateTime).AddDays(3) < DateTime.Now)
            {
                log.Debug("GetMediaIDByNewsInfo start:  cate:{0}  AutoReplyID:{1}", News.NewsCate, iId);


                Innocellence.WeChatMain.Common.WechatCommon.GetMediaInfo((AutoReplyContentEnum)Enum.Parse(typeof(AutoReplyContentEnum), News.NewsCate.ToUpper()), News, News.AppId);

                var content = JsonConvert.SerializeObject(new List <NewsInfoView>()
                {
                    News
                });
                AutoReplyContent model = new AutoReplyContent()
                {
                    Id      = iId,
                    Content = content
                };

                _AutoReplyContentService.Repository.Update(model, new List <string>()
                {
                    "Content"
                });

                return(News.MediaId);
            }
            else
            {
                return(News.MediaId);
            }
        }
        public ActionResult WechatServiceSendMessage(List <NewsInfoView> newsList, bool isPreview = false)
        {
            SysWechatConfig wechat = WeChatCommonService.lstSysWeChatConfig.Find(p => p.AccountManageId == AccountManageID && !p.IsCorp.Value);

            if (wechat == null)
            {
                return(Json(new { results = new { Data = 500 } }));
            }
            try
            {
                NewsInfoView news = newsList[0];
                if ("video".Equals(news.NewsCate))
                {
                    news.ImageContent = SaveBase64ImageToServer(news.ImageContent);
                }
                string           strSendType     = string.Empty;
                SearchUserMPView searchCondition = new SearchUserMPView
                {
                    Group    = news.Group,
                    Province = news.Province,
                    City     = news.City,
                    Sex      = news.Sex
                };
                using (var transactionScope = new TransactionScope(TransactionScopeOption.Suppress, new TransactionOptions {
                    IsolationLevel = IsolationLevel.RepeatableRead
                }))
                {
                    SendResult       returnResult = null;
                    List <NewsModel> articles     = new List <NewsModel>();
                    var lstArticles = GetArticleList(newsList, isPreview, strSendType, searchCondition);
                    if (!isPreview && news.PostType == (int)MessagePostTypeEnum.定时推送)
                    {
                        transactionScope.Complete();
                    }
                    else
                    {
                        string[] openids = null;

                        if (isPreview)
                        {
                            openids = news.SendToPerson;
                        }
                        //发送消息
                        returnResult = WechatCommonMP.SendMsgMP(lstArticles, searchCondition, openids);
                        if (returnResult.errcode == Weixin.ReturnCode.请求成功)
                        {
                            transactionScope.Complete();
                        }
                    }
                }
            }
            catch (Exception e)
            {
                _Logger.Error(e, "An error occurred while sending mp news.");
                // _Logger.Error(e.ToString());
                return(Json(new { results = new { Data = 500 } }));
            }
            return(Json(new { results = new { Data = 200 } }));
        }
        public static string DoNewsInfo(NewsInfoView news, SysWechatConfig config, AutoReplyContentEnum type, string strFileName)
        {
            string mediaId = null;

            if (news.materialId.HasValue && news.materialId.Value > 0) //有素材
            {
                IAttachmentsItemService _attachmentsItemService = EngineContext.Current.Resolve <IAttachmentsItemService>();

                NewsInfoView news1;
                mediaId = WechatCommon.GetMediaIDByFileID(news.materialId, _attachmentsItemService, config.WeixinCorpId, out news1);
            }
            else
            {
                mediaId = WechatCommon.GetMediaInfo(type, news, news.AppId);

                NewsToAttachments(news, type.ToString().ToLower(), strFileName);
            }
            return(mediaId);
        }
 private void InsertMsgLog(string newsIdList, NewsInfoView firstNews)
 {
     try
     {
         if (!string.IsNullOrEmpty(newsIdList) && firstNews != null)
         {
             var msgLogView = new MessageLogView()
             {
                 NewsIdList     = newsIdList,
                 AppId          = firstNews.AppId,
                 MsgContentType = (int)Enum.Parse(typeof(WechatMessageLogType), firstNews.NewsCate),
             };
             this._MessageLogService.InsertView(msgLogView);
         }
     }
     catch (Exception ex)
     {
         _Logger.Error("an error occured when add send msg log :{0}", ex);
     }
 }
        /// <summary>
        /// 消息内容存储到素材表
        /// </summary>
        /// <param name="news"></param>
        /// <param name="uploadFileType"></param>
        /// <param name="strFileName"></param>
        private static void NewsToAttachments(NewsInfoView news, string uploadFileType, string strFileName)
        {
            IAttachmentsItemService _attachmentsItemService = EngineContext.Current.Resolve <IAttachmentsItemService>();
            string strFullName = (HttpContext.Current == null ? HttpRuntime.AppDomainAppPath : HttpContext.Current.Request.PhysicalApplicationPath) + strFileName;

            AttachmentsItemPostProperty p = new AttachmentsItemPostProperty()
            {
                SaveFullName   = Path.GetFileName(strFullName),
                ServerPath     = HttpRuntime.AppDomainAppPath,
                FileName       = news.NewsTitle,
                TargetFilePath = strFileName.Replace(Path.GetFileName(strFullName), "").Replace("//", "/").Trim('/'),
                UploadFileType = uploadFileType,
                AppId          = news.AppId,
                Description    = news.NewsComment,
                VideoCoverSrc  = string.IsNullOrEmpty(news.ImageSrc) ? news.ImageContent : news.ImageSrc,
                UserName       = _attachmentsItemService.Repository.LoginUserName,// User.Identity.Name,
                MediaId        = news.MediaId,
                // MediaExpireTime=
                //ViewId = pid,
            };
            SysAttachmentsItem itemView = _attachmentsItemService.ThumbImageAndInsertIntoDB(p);
        }
        /// <summary>
        /// 根据资源ID获取回复信息,如果过期重新上传
        /// </summary>
        /// <param name="fileID"></param>
        /// <param name="news"></param>
        /// <returns></returns>
        public static string GetMediaIDByFileID(int?fileID, IAttachmentsItemService _attachmentsItemService, string CorpId, out NewsInfoView news)
        {
            if (fileID == null)
            {
                throw new Exception("do not found file id.");
            }
            else
            {
                log.Debug("GetMediaIDByFileID start:   fileID:{0}", fileID);

                //
                var fileInfo = _attachmentsItemService.GetById <AttachmentsItemView>((int)fileID);

                if (fileInfo != null)
                {
                    news = new NewsInfoView()
                    {
                        NewsContent  = "",
                        NewsTitle    = fileInfo.AttachmentTitle,
                        ImageContent = fileInfo.AttachmentUrl,
                        VideoContent = fileInfo.AttachmentUrl,
                        FileSrc      = fileInfo.AttachmentUrl,
                        SoundSrc     = fileInfo.AttachmentUrl,
                        MediaId      = fileInfo.MediaId,
                        NewsComment  = fileInfo.Description
                    };
                }
                else
                {
                    news = new NewsInfoView();
                }

                if (fileInfo != null && (string.IsNullOrEmpty(fileInfo.MediaId) || !fileInfo.MediaExpireTime.HasValue || fileInfo.MediaExpireTime.Value < DateTime.Now))
                {
                    var config = WeChatCommonService.lstSysWeChatConfig.Find(a => a.WeixinCorpId == CorpId);


                    AutoReplyContentEnum cate = AutoReplyContentEnum.FILE;
                    if (fileInfo.Type == (int)AttachmentsType.IMAGE)
                    {
                        cate = AutoReplyContentEnum.IMAGE;
                        if (fileInfo.FileSize > 2 * 1024 * 1024)
                        {
                            throw new Exception("图片文件不能大于2M!");
                        }
                    }
                    else if (fileInfo.Type == (int)AttachmentsType.VIDEO)
                    {
                        cate = AutoReplyContentEnum.VIDEO;
                        if (fileInfo.FileSize > 10 * 1024 * 1024)
                        {
                            throw new Exception("视频文件不能大于10M!");
                        }
                    }
                    else if (fileInfo.Type == (int)AttachmentsType.AUDIO)
                    {
                        cate = AutoReplyContentEnum.VOICE;
                        if (fileInfo.FileSize > 2 * 1024 * 1024)
                        {
                            throw new Exception("声音文件不能大于210M!");
                        }
                    }
                    else if (fileInfo.Type == (int)AttachmentsType.FILE)
                    {
                        cate = AutoReplyContentEnum.FILE;
                        if (fileInfo.FileSize > 20 * 1024 * 1024)
                        {
                            throw new Exception("普通文件不能大于20M!");
                        }
                    }


                    news.NewsCate = cate.ToString().ToLower();
                    news.AppId    = config.Id;


                    Innocellence.WeChatMain.Common.WechatCommon.GetMediaInfo(cate, news, config.Id);

                    _attachmentsItemService.UpdateMediaId(fileInfo.Id, news.MediaId, DateTimeHelper.GetDateTimeFromXml(news.MediaCreateTime));

                    log.Debug("GetMediaIDByFileID end  GetNewMediaId:   fileID:{0} MediaId:{1}", fileID, news.MediaId);

                    return(news.MediaId);
                }
                else
                {
                    log.Debug("GetMediaIDByFileID end  Use Old MediaId:   fileID:{0}   MediaId:{1}", fileID, news.MediaId);

                    return(fileInfo == null ? string.Empty : fileInfo.MediaId);
                }
            }
        }
        public static string GetMediaInfo(AutoReplyContentEnum cate, NewsInfoView news, int iAppID)
        {
            string   mediaId        = null;
            string   saveFileName   = null;
            string   targetFilePath = null;
            string   saveDir        = null;
            FileInfo fi             = null;
            dynamic  ret            = null;


            //上次的素材还没过期
            if (!string.IsNullOrEmpty(news.MediaId) && news.MediaCreateTime > 0)
            {
                if (DateTimeHelper.GetDateTimeFromXml(news.MediaCreateTime).AddDays(3) > DateTime.Now)
                {
                    return(news.MediaId);
                }
            }


            Dictionary <string, Stream> dic = new Dictionary <string, Stream>();

            var objConfig = WeChatCommonService.GetWeChatConfigByID(iAppID);

            bool isCrop = (objConfig.IsCorp == null || objConfig.IsCorp.Value);

            string strToken = (objConfig.IsCorp != null && !objConfig.IsCorp.Value) ? "" : Innocellence.Weixin.QY.CommonAPIs.AccessTokenContainer.TryGetToken(objConfig.WeixinCorpId, objConfig.WeixinCorpSecret);


            log.Debug("GetMediaInfo start:  cate:{0}  iAppID:{1}", cate, iAppID);

            switch (cate)
            {
            case AutoReplyContentEnum.IMAGE:
                //saveFileName = Path.GetFileName(news.ImageContent.Replace("_t", "")); //不发缩略图
                //targetFilePath = news.ImageContent.Substring(0, news.ImageContent.LastIndexOf(saveFileName));
                //targetFilePath = targetFilePath.Trim('\\', '/');
                //saveDir = Path.Combine(HttpContext.Current.Server.MapPath("~/"), targetFilePath);
                //fi = new FileInfo(Path.Combine(saveDir, saveFileName));

                fi = new FileInfo(HttpRuntime.AppDomainAppPath + news.ImageContent.Replace("_t", ""));

                if (isCrop)
                {
                    dic.Add(fi.Name, fi.OpenRead());
                    ret = MediaApi.Upload(strToken, UploadMediaFileType.image, dic, "", 50 * 10000);
                }
                else
                {
                    ret = Innocellence.Weixin.MP.AdvancedAPIs.MediaApi.UploadTemporaryMedia(objConfig.WeixinCorpId, objConfig.WeixinCorpSecret,
                                                                                            Innocellence.Weixin.MP.UploadMediaFileType.image, fi.OpenRead(), fi.FullName, 50 * 10000);
                }

                news.MediaId = ret.media_id;
                mediaId      = ret.media_id;
                break;

            case AutoReplyContentEnum.VOICE:
                //saveFileName = Path.GetFileName(news.SoundSrc);
                //targetFilePath = news.SoundSrc.Substring(0, news.SoundSrc.LastIndexOf(saveFileName));
                //targetFilePath = targetFilePath.Trim('\\', '/');
                //saveDir = Path.Combine(HttpContext.Current.Server.MapPath("~/"), targetFilePath);
                //fi = new FileInfo(Path.Combine(saveDir, saveFileName));

                fi = new FileInfo(HttpRuntime.AppDomainAppPath + news.SoundSrc.Replace("_t", ""));

                dic.Add(fi.Name, fi.OpenRead());
                try
                {
                    if (isCrop)
                    {
                        ret = MediaApi.Upload(strToken, UploadMediaFileType.voice, dic, "", 50 * 10000);
                    }
                    else
                    {
                        ret = Innocellence.Weixin.MP.AdvancedAPIs.MediaApi.UploadTemporaryMedia(objConfig.WeixinCorpId, objConfig.WeixinCorpSecret,
                                                                                                Innocellence.Weixin.MP.UploadMediaFileType.voice, fi.OpenRead(),
                                                                                                fi.FullName, 50 * 10000);
                    }
                }
                catch (ErrorJsonResultException ex)
                {
                    if (ex.JsonResult.errcode == Weixin.ReturnCode.语音播放时间超过限制)
                    {
                        throw new Exception("语音播放时间超过限制,请上传播放长度不超过60秒的语音文件。");
                    }
                    else
                    {
                        throw;
                    }
                }
                news.MediaId = ret.media_id;
                mediaId      = ret.media_id;
                break;

            case AutoReplyContentEnum.VIDEO:
                //saveFileName = Path.GetFileName(news.VideoContent);
                //targetFilePath = news.VideoContent.Substring(0, news.VideoContent.LastIndexOf(saveFileName));
                //targetFilePath = targetFilePath.Trim('\\', '/');
                //saveDir = Path.Combine(HttpContext.Current.Server.MapPath("~/"), targetFilePath);
                //fi = new FileInfo(Path.Combine(saveDir, saveFileName));

                fi = new FileInfo(HttpRuntime.AppDomainAppPath + news.VideoContent.Replace("_t", ""));


                if (isCrop)
                {
                    dic.Add(fi.Name, fi.OpenRead());
                    ret = MediaApi.Upload(strToken, UploadMediaFileType.video, dic, "", 50 * 10000);
                }
                else
                {
                    ret = Innocellence.Weixin.MP.AdvancedAPIs.MediaApi.UploadTemporaryMedia(objConfig.WeixinCorpId, objConfig.WeixinCorpSecret,
                                                                                            Innocellence.Weixin.MP.UploadMediaFileType.video, fi.OpenRead(), fi.FullName, 50 * 10000);
                }
                news.MediaId = ret.media_id;
                mediaId      = ret.media_id;
                break;

            case AutoReplyContentEnum.FILE:
                //saveFileName = Path.GetFileName(news.FileSrc);
                //targetFilePath = news.FileSrc.Substring(0, news.FileSrc.LastIndexOf(saveFileName));
                //targetFilePath = targetFilePath.Trim('\\', '/');
                //saveDir = Path.Combine(HttpContext.Current.Server.MapPath("~/"), targetFilePath);
                //fi = new FileInfo(Path.Combine(saveDir, saveFileName));

                fi = new FileInfo(HttpRuntime.AppDomainAppPath + news.FileSrc.Replace("_t", ""));
                string extention   = fi.Name.Substring(fi.Name.LastIndexOf('.'));
                string fileName    = string.IsNullOrEmpty(news.RealFileName) ? news.NewsTitle : news.RealFileName;
                string displayName = fileName.EndsWith(extention) ? fileName : fileName + extention;
                if (isCrop)
                {
                    dic.Add(displayName, fi.OpenRead());
                    ret = MediaApi.Upload(strToken, UploadMediaFileType.file, dic, "", 50 * 10000);
                }
                else
                {
                    //服务号暂时不支持推送文件.
                    //ret = Innocellence.Weixin.MP.AdvancedAPIs.MediaApi.UploadTemporaryMedia(objConfig.WeixinCorpId, objConfig.WeixinCorpSecret, Innocellence.Weixin.MP.UploadMediaFileType.voice, fi.OpenRead(), Path.Combine(saveDir, saveFileName), 50 * 10000);
                }
                news.MediaId = ret.media_id;
                mediaId      = ret.media_id;
                break;

            default:
                break;
            }

            if (ret != null)
            {
                news.MediaCreateTime = ret.created_at;


                log.Debug("GetMediaInfo end:  media_id:{0} ", ret.media_id);
            }
            return(mediaId);
        }