private AudioAttachment ParseAudioAttachment(JObject _jAudio)
        {
            try
            {
                if (_jAudio[PAttachmentsAudio] is JObject jAudio)
                {
                    var audioAttachments = new AudioAttachment();

                    audioAttachments.Id        = jAudio[PId].Value <int>();
                    audioAttachments.OwnerId   = jAudio[PAttachmentOwnerId].Value <int>();
                    audioAttachments.Artist    = jAudio[PAudioArtist].Value <string>();
                    audioAttachments.Title     = jAudio[PTitle].Value <string>();
                    audioAttachments.Url       = jAudio[PUrl].Value <string>();
                    audioAttachments.AccessKey = jAudio[PAttachmentAccessKey]?.Value <string>();

                    return(audioAttachments);
                }
            }
            catch (Exception ex)
            {
                throw new InvalidOperationException($"Failed to parse audio attachment \n {_jAudio.ToString()}", ex);
            }

            throw new ArgumentException($"Failed recognize jObject as audio attachment \n {_jAudio?.ToString()}");
        }
Esempio n. 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);
        }
Esempio n. 3
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);
        }
Esempio n. 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="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);
        }
Esempio n. 5
0
 public Task <string> Upload(AudioAttachment image)
 {
     throw new NotImplementedException();
 }