/// <summary>
        /// 处理视频请求
        /// </summary>
        /// <param name="requestMessage"></param>
        /// <returns></returns>
        public override IResponseMessageBase OnVideoRequest(RequestMessageVideo requestMessage)
        {
            var responseMessage = CreateResponseMessage <ResponseMessageText>();

            responseMessage.Content = "您发送了一条视频信息,ID:" + requestMessage.MediaId;

            #region    材并推送到客户端

            Task.Factory.StartNew(async() =>
            {
                //上传素材
                var dir          = ServerUtility.ContentRootMapPath("~/App_Data/TempVideo/");
                var file         = await MediaApi.GetAsync(appId, requestMessage.MediaId, dir);
                var uploadResult = await MediaApi.UploadTemporaryMediaAsync(appId, UploadMediaFileType.video, file, 50000);
                await CustomApi.SendVideoAsync(appId, base.OpenId, uploadResult.media_id, "这是您刚才发送的视频", "这是一条视频消息");
            }).ContinueWith(async task =>
            {
                if (task.Exception != null)
                {
                    WeixinTrace.Log("OnVideoRequest()储存Video过程发生错误:", task.Exception.Message);

                    var msg = string.Format("上传素材出错:{0}\r\n{1}",
                                            task.Exception.Message,
                                            task.Exception.InnerException != null
                                    ? task.Exception.InnerException.Message
                                    : null);
                    await CustomApi.SendTextAsync(appId, base.OpenId, msg);
                }
            });

            #endregion

            return(responseMessage);
        }
Example #2
0
        private async Task <string> DownloadWechatImgs(string imgs, string appId)
        {
            if (string.IsNullOrEmpty(imgs))
            {
                return(string.Empty);
            }
            string localImgs = string.Empty;

            string[] serverIds      = imgs.Split(',').Where(s => !string.IsNullOrEmpty(s)).ToArray();
            string   uploadPath     = GetUploadPath();//获取相对路径
            string   fullUpLoadPath = _hostingEnvironment.WebRootPath + uploadPath;

            foreach (var id in serverIds)
            {
                if (id.IndexOf("BanquetPhotos") > 0)
                {
                    localImgs = localImgs + id + ",";
                }
                else
                {
                    var msg = await MediaApi.GetAsync(appId, id, fullUpLoadPath);

                    Logger.InfoFormat("serverId:{0} msg:{1}", id, msg);
                    localImgs = localImgs + uploadPath + id + ".jpg,"; //保存相对路径
                }
            }
            if (localImgs.Length > 0)
            {
                localImgs = localImgs.Substring(0, localImgs.Length - 1);
            }
            return(localImgs);
        }
Example #3
0
        public static async Task <string> DownloadMedia(string mediaId, string dir)
        {
            var appId = Config.SenparcWeixinSetting.WeixinAppId;

            //var token = await AccessTokenContainer.GetAccessTokenAsync(appId);
            //var fileUrl = $"http://file.api.weixin.qq.com/cgi-bin/media/get?access_token={token}&media_id={mediaId}";
            //var fileName = $"{dir}\\{mediaId}.jpg";
            //System.IO.Directory.CreateDirectory(dir);
            //using(var wc=new System.Net.WebClient())
            //{
            //    wc.DownloadFile(new Uri(fileUrl), fileName);
            //}
            //return fileName;
            //return MediaApi.Get(appId, mediaId, dir);
            //todo:
            //使用原方法时报httpclient 的A task was canceled.错误,当移值新服务器时出现,但旧服务器没有任何问题,猜测服务器对httpclient请求有限制
            return(await MediaApi.GetAsync(appId, mediaId, dir));
        }
        public async Task <bool> DownloadTemplateImageAsync(string serverId, string fileName, bool getNewToken = false)
        {
            var accessToken = AccessTokenContainer.TryGetAccessToken(SiteConfig.AppId, SiteConfig.AppSecret,
                                                                     getNewToken);

            using (MemoryStream ms = new MemoryStream())
            {
                await MediaApi.GetAsync(accessToken, serverId, ms);

                //保存到文件
                ms.Position = 0;
                byte[] buffer    = new byte[1024];
                int    bytesRead = 0;
                //判断是否上传成功
                byte[] topBuffer = new byte[1];
                await ms.ReadAsync(topBuffer, 0, 1);

                if (topBuffer[0] == '{')
                {
                    //写入日志
                    ms.Position = 0;
                    byte[] logBuffer = new byte[1024];
                    await ms.ReadAsync(logBuffer, 0, logBuffer.Length);

                    string str = System.Text.Encoding.Default.GetString(logBuffer);
                    Senparc.Log.LogUtility.Weixin.InfoFormat("下载失败:{0}。serverId:{1}", str, serverId);
                    return(false);
                }
                else
                {
                    ms.Position = 0;
                    using (FileStream fs = new FileStream(fileName, FileMode.Create))
                    {
                        while ((bytesRead = await ms.ReadAsync(buffer, 0, buffer.Length)) != 0)
                        {
                            await fs.WriteAsync(buffer, 0, bytesRead);
                        }
                        await fs.FlushAsync();
                    }
                }
            }
            return(true);
        }