private static async Task SendMediaUrlAsync(ClientMessenger client, string userId)
        {
            var vedio   = new VideoAttachment("https://hubsterdevcdn.blob.core.windows.net/engine/00000000-0000-0000-0000-000000000001/media/8338156741751296193-textinmotion_sample_576p.mp4");
            var message = new AttachmentMessage {
                Attachment = vedio
            };
            var package = await client.GetJSONRenderedAsync(userId, message);

            var result = await client.SendMessageAsync(userId, message);
        }
Пример #2
0
        /// <summary>
        /// Reads the JSON representation of the object.
        /// </summary>
        /// <param name="reader">The <see cref="T:Newtonsoft.Json.JsonReader" /> to read from.</param>
        /// <param name="objectType">Type of the object.</param>
        /// <param name="existingValue">The existing value of object being read.</param>
        /// <param name="serializer">The calling serializer.</param>
        /// <returns>
        /// The object value.
        /// </returns>
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            var result     = default(Attachment);
            var attachment = JObject.Load(reader);
            var type       = (attachment["type"] as JValue).Value.ToString();

            switch (type)
            {
            case "image":
                result = new ImageAttachment();
                break;

            case "audio":
                result = new AudioAttachment();
                break;

            case "video":
                result = new VideoAttachment();
                break;

            case "file":
                result = new FileAttachment();
                break;

            case "location":
                result = new LocationAttachment();
                break;

            case "fallback":
                result = new FallbackAttachment();
                break;

            case "template":
                var templateType = (attachment["payload"]["template_type"] as JValue).Value.ToString();
                switch (templateType)
                {
                case "generic":
                    result = new GenericTemplateAttachment();
                    break;

                case "button":
                    result = new ButtonTemplateAttachment();
                    break;

                case "receipt":
                    result = new ReceiptTemplateAttachment();
                    break;
                }
                break;
            }
            serializer.Populate(attachment.CreateReader(), result);

            return(result);
        }
Пример #3
0
        /// <summary>
        /// 此方法由APP调用。不可删除
        /// </summary>
        /// <param name="context"></param>
        public void ProcessRequest(HttpContext context)
        {
            //因图文混排视频直接显示,设两个返回的临时视频地址
            var reVideoUrl = string.Empty;
            var rePostUrl  = string.Empty;

            context.Response.ContentType = "text/html";
            string         name = context.Request["name"];
            HttpPostedFile file = context.Request.Files[name];

            try
            {
                int minsnsId = 0;
                int.TryParse(context.Request["minsnsId"], out minsnsId);
                var           tempurl       = string.Empty;
                string        fileExtension = System.IO.Path.GetExtension(file.FileName).ToLower();
                int           flag          = 0;//标志是否需要转换
                List <string> extents       = new List <string> {
                    ".mp4", ".ogg", ".mpeg4", ".webm", ".MP4", ".OGG", ".MPEG4", ".WEBM"
                };
                string posterUploadDirectory = Path.Combine(ConfigurationManager.AppSettings["ImgUploadUrl4"], "videoposter", "mp4", DateTime.Now.Year.ToString(), DateTime.Now.Month.ToString());

                var tempkey    = VideoAliMtsHelper.GetOssVideoKey(fileExtension.Replace(".", ""), true, out tempurl);
                var byteData   = new byte[file.ContentLength];
                var fileStream = file.InputStream;
                if (null != fileStream)
                {
                    using (System.IO.BinaryReader br = new System.IO.BinaryReader(fileStream))
                    {
                        byteData = br.ReadBytes(file.ContentLength);
                    }
                }
                if (null == byteData)
                {
                    log4net.LogHelper.WriteInfo(this.GetType(), "视频获取byte[]失败!");
                    context.Response.Write(new JavaScriptSerializer().Serialize(new { result = 0, msg = "系统错误!请联系管理员." }));
                }
                var putrsult = AliOSSHelper.PutObjectFromByteArray(tempkey, byteData, 1, fileExtension.Replace(".", ""));
                if (extents.Contains(fileExtension))
                {
                    flag = 1;
                }

                VideoAttachment video = new VideoAttachment();
                video.CreateDate = DateTime.Now;
                video.VideoSize  = (file.ContentLength / (1024 * 1024.0)).ToString("N2");//单位为M
                //无需转换
                if (1 == flag)
                {
                    video.Status          = 1;
                    video.ConvertFilePath = VideoAliMtsHelper.GetUrlFromKey(tempkey.Replace("temp/", ""));
                }
                else
                {
                    var regex = new Regex(@"(?i)\.[\S]*");
                    video.ConvertFilePath = VideoAliMtsHelper.GetUrlFromKey(regex.Replace(tempkey.Replace("temp/", ""), ".mp4"));
                    video.Status          = -2;//待转换
                }
                video.UserId         = int.Parse(context.Request.Form["UId"] ?? "0");
                video.Fid            = minsnsId;
                video.SourceFilePath = tempkey;
                int Vid = Convert.ToInt32(VideoAttachmentBLL.SingleModel.Add(video));
                context.Response.Write(new JavaScriptSerializer().Serialize(new { result = "ok", msg = "上传成功", Vid = Vid }));
            }
            catch (Exception ex)
            {
                StringHelper.WriteOperateLog("error", ex.Message);
                context.Response.Write("");
            }
        }
Пример #4
0
        /// <summary>
        /// Sends the attachment asynchronous.
        /// </summary>
        /// <param name="userId">The user identifier.</param>
        /// <param name="stream">The stream.</param>
        /// <param name="filename">The filename.</param>
        /// <param name="type">The type.</param>
        /// <returns></returns>
        public async Task <MessageResult> SendAttachmentAsync(string userId, Stream stream, string filename, string type = "file")
        {
            var fileType       = string.Empty;
            var contenFilename = $"@/tmp/{filename}";
            var attachment     = (new FileAttachment() as Attachment);

            switch (type)
            {
            case "image":
                var ext = Path.GetExtension(filename).Replace(".", string.Empty);
                if (ext.ToLower() == "jpg")
                {
                    ext = "jpeg";
                }

                fileType       = $"image/{ext}";
                contenFilename = $"{contenFilename};type={fileType}";
                attachment     = new ImageAttachment();
                break;

            case "video":
                fileType       = "video/mp4";
                contenFilename = $"{contenFilename};type={fileType}";
                attachment     = new VideoAttachment();
                break;

            case "audio":
                fileType       = "audio/mp3";
                contenFilename = $"{contenFilename};type={fileType}";
                attachment     = new AudioAttachment();
                break;
            }

            var result = new MessageResult();

            try
            {
                using (var client = new HttpClient())
                {
                    using (var content = new MultipartFormDataContent())
                    {
                        var recipient = JsonConvert.SerializeObject(new Identity(userId));
                        var message   = JsonConvert.SerializeObject(new AttachmentMessage(attachment));

                        content.Add(new StringContent(recipient), "recipient");
                        content.Add(new StringContent(message), "message");

                        var imageContent = new StreamContent(stream);
                        if (!string.IsNullOrWhiteSpace(fileType))
                        {
                            imageContent.Headers.ContentType = MediaTypeHeaderValue.Parse(fileType);
                        }

                        content.Add(imageContent, "filedata", contenFilename);

                        using (var response = await client.PostAsync($"https://graph.facebook.com/v{_apiVersion}/me/messages?access_token={AccessToken}", content))
                        {
                            var returnValue = (JObject)JsonConvert.DeserializeObject(await response.Content.ReadAsStringAsync());

                            result.Error = CreateResultError(returnValue);
                            if (result.Error == null)
                            {
                                result.RecipientId = returnValue.Value <string>("recipient_id");
                                result.MessageId   = returnValue.Value <string>("message_id");
                                result.Success     = true;
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                HandleException(ex, result);
            }

            return(result);
        }
Пример #5
0
        /// <summary>
        /// Sends the attachment asynchronous.
        /// </summary>
        /// <param name="userId">The user identifier.</param>
        /// <param name="stream">The stream.</param>
        /// <param name="filename">The filename.</param>
        /// <param name="mimeType">Type of the MIME.</param>
        /// <param name="type">The type.</param>
        /// <returns></returns>
        public async Task <MessageResult> SendFileAttachmentAsync(string userId, Stream stream, string filename, string mimeType, string type = "file")
        {
            var attachment = (Attachment)null;

            switch (type)
            {
            case "image":
                attachment = new ImageAttachment();
                break;

            case "video":
                attachment = new VideoAttachment();
                break;

            case "audio":
                attachment = new AudioAttachment();
                break;

            default:
                attachment = new FileAttachment();
                break;
            }

            (attachment as Attachment <MediaPayload>).Payload.IsReusable = true;

            var result = new MessageResult();

            try
            {
                using (var client = new HttpClient())
                {
                    client.Timeout = TimeSpan.FromMinutes(5);

                    using (var content = new MultipartFormDataContent())
                    {
                        var recipient = JsonConvert.SerializeObject(new Identity(userId));
                        var message   = JsonConvert.SerializeObject(new AttachmentMessage(attachment));

                        content.Add(new StringContent(recipient), "recipient");
                        content.Add(new StringContent(message), "message");

                        var fileContent = new StreamContent(stream);
                        fileContent.Headers.ContentType = MediaTypeHeaderValue.Parse(mimeType);

                        content.Add(fileContent, "filedata", filename);

                        using (var response = await client.PostAsync($"https://graph.facebook.com/v{_apiVersion}/me/messages?access_token={_accessToken}", content))
                        {
                            if (response.StatusCode != HttpStatusCode.OK &&
                                response.StatusCode != HttpStatusCode.BadRequest)
                            {
                                result.Success = false;
                                result.Error   = new ResultError
                                {
                                    Code         = -1,
                                    ErrorSubcode = (int)response.StatusCode,
                                    Message      = response.ReasonPhrase ?? response.StatusCode.ToString(),
                                };
                            }
                            else
                            {
                                var returnValue = (JObject)JsonConvert.DeserializeObject(await response.Content.ReadAsStringAsync());
                                result.Error = CreateResultError(returnValue);
                                if (result.Error == null)
                                {
                                    result.RecipientId  = returnValue.Value <string>("recipient_id");
                                    result.MessageId    = returnValue.Value <string>("message_id");
                                    result.AttachmentId = returnValue.Value <string>("attachment_id");
                                    result.Success      = true;
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                HandleException(ex, result);
            }

            return(result);
        }
        private VideoAttachment ParseVideoAttachment(JObject _jVideo, Func <VideoInfo, string> _loadVideoItem)
        {
            try
            {
                if (_jVideo[PAttachmentsVideo] is JObject jVideo)
                {
                    var videoAttachment = new VideoAttachment
                    {
                        Id                       = jVideo[PId].Value <int>(),
                        OwnerId                  = jVideo[PAttachmentOwnerId].Value <int>(),
                        Title                    = jVideo[PTitle].Value <string>(),
                        Description              = jVideo[PVideoDescription]?.Value <string>(),
                        Duration                 = jVideo[PVideoDuration].Value <int>(),
                        Date                     = EpochTimeConverter.ConvertToDateTime(jVideo[PDate].Value <long>()),
                        Views                    = jVideo[PVideoViews].Value <int>(),
                        CommentsCount            = jVideo[PVideoComments]?.Value <int>(),
                        PlayerUrl                = jVideo[PVideoPlayer]?.Value <string>(),
                        AccessKey                = jVideo[PAttachmentAccessKey].Value <string>(),
                        IsContentRestricted      = jVideo.ContainsKey(PVideoContentRestricted),
                        ContentRestrictedMessage = jVideo[PVideoContentRestrictedMessage]?.Value <string>()
                    };


                    if (jVideo.ContainsKey(PVideoImage) && jVideo[PVideoImage] is JArray jImages)
                    {
                        videoAttachment.Images = jImages.Select(_x => new Image
                        {
                            Height = _x[PSizesHeight].Value <int>(),
                            Width  = _x[PSizesWidth].Value <int>(),
                            Url    = _x[PUrl].Value <string>()
                        }).ToArray();
                    }

                    if (jVideo.ContainsKey(PVideoFirstFrame) && jVideo[PVideoFirstFrame] is JArray jFrames)
                    {
                        videoAttachment.FirstFrames = jFrames.Select(_x => new Image
                        {
                            Height = _x[PSizesHeight].Value <int>(),
                            Width  = _x[PSizesWidth].Value <int>(),
                            Url    = _x[PUrl].Value <string>()
                        }).ToArray();
                    }

                    if (videoAttachment.PlayerUrl == null && _loadVideoItem != null)
                    {
                        try
                        {
                            var data = _loadVideoItem(new VideoInfo
                            {
                                OwnerId = videoAttachment.OwnerId,
                                VideoId = videoAttachment.Id
                            });

                            var videoInfo = m_videoAttachmentDeserializer.Deserialize(data);

                            videoAttachment.PlayerUrl = videoInfo.PlayerUrl;
                        }
                        catch
                        {
                            //nothing to do
                        }
                    }

                    return(videoAttachment);
                }
            }
            catch (Exception ex)
            {
                throw new InvalidOperationException($"Failed to parse video attachment \n {_jVideo.ToString()}", ex);
            }

            throw new ArgumentException($"Failed recognize jObject as video attachment \n {_jVideo?.ToString()}");
        }