private DocumentAttachment ParseDocAttachment(JObject _jDoc) { try { if (_jDoc[PAttachmentsDocument] is JObject jDoc) { var docAttachment = new DocumentAttachment(); docAttachment.Id = jDoc[PId].Value <int>(); docAttachment.OwnerId = jDoc[PAttachmentOwnerId].Value <int>(); docAttachment.Title = jDoc[PTitle]?.Value <string>(); docAttachment.Date = EpochTimeConverter.ConvertToDateTime(jDoc[PDate].Value <long>()); docAttachment.Url = jDoc[PUrl].Value <string>(); docAttachment.AccessKey = jDoc[PAttachmentAccessKey]?.Value <string>(); return(docAttachment); } } catch (Exception ex) { throw new InvalidOperationException($"Failed to parse doc attachment \n {_jDoc.ToString()}", ex); } throw new DeserializerException($"Failed recognize jObject as document attachment \n {_jDoc?.ToString()}"); }
public static string BuildNewsFeedRequest(string _token, string _apiVersion, DateTime _startTime, DateTime _endTime, string _sourceIds, int _count = 50) { if (string.IsNullOrWhiteSpace(_token)) { throw new ArgumentException("Token can not be null or empty!"); } if (string.IsNullOrWhiteSpace(_apiVersion)) { throw new ArgumentException("Api version can not be null or empty!"); } if (string.IsNullOrWhiteSpace(_sourceIds)) { throw new ArgumentException("SourceIds can not be null or empty!"); } var epochStartTime = EpochTimeConverter.ConvertFromDateTime(_startTime); var epochEndTime = EpochTimeConverter.ConvertFromDateTime(_endTime); var newsfeedRequest = string.Format(m_newsFeedTemplate, _token, _apiVersion, epochStartTime, epochEndTime, _sourceIds, _count); return(newsfeedRequest); }
public void ON_SESSION_HEARTBEAT(Event ev) { //TODO //store in db long answer_seconds_since_epoch = long.Parse(ev.GetHeader("Caller-Channel-Answered-Time")); long heartbeat_seconds_since_epoch = long.Parse(ev.GetHeader("Event-Date-Timestamp")); int ElapsedTime = EpochTimeConverter.GetEpochTimeDifferent(heartbeat_seconds_since_epoch, answer_seconds_since_epoch); var BCallSid = ev.GetHeader("variable_agbara_bleg_callsid"); var ACallSid = ev.GetHeader("variable_agbara_callsid"); if (!string.IsNullOrEmpty(BCallSid)) { int current = CallElapsedTime[BCallSid]; CallElapsedTime[BCallSid] = current + ElapsedTime; } else if (!string.IsNullOrEmpty(ACallSid)) { int current = CallElapsedTime[ACallSid]; CallElapsedTime[ACallSid] = current + ElapsedTime; } //TODO //bill user real time here }
public void ReadJson(DateTimeOffset expected, string original) { var converter = new EpochTimeConverter(); var reader = new JsonTextReader(new StringReader(original)); reader.Read(); var serializer = new JsonSerializer(); var actual = (DateTimeOffset)converter.ReadJson(reader, typeof(DateTimeOffset), null, serializer); Assert.Equal(expected, actual); }
static void Main(string[] args) { EpochTimeConverter dtConverter = new EpochTimeConverter(); DateTime convertedEpochTime = new DateTime(); DateTime DateToBeConverted = new DateTime(2020, 6, 10, 15, 24, 16); long convertedDateTime = new long(); convertedEpochTime = dtConverter.EpochToDateTime(1611795435000); convertedDateTime = dtConverter.DateTimeToEpoch(DateToBeConverted); Console.WriteLine(convertedEpochTime); Console.WriteLine(convertedDateTime); }
public void ReadJson_ThrowsInvalidCastException(string data) { var converter = new EpochTimeConverter(); var reader = new JsonTextReader(new StringReader(data)); reader.Read(); var serializer = new JsonSerializer(); var exception = Record.Exception(() => converter.ReadJson(reader, typeof(DateTimeOffset), null, serializer)); Assert.NotNull(exception); Assert.IsType <InvalidCastException>(exception); }
public void WriteJson_ThrowsInvalidCastException(object data) { var converter = new EpochTimeConverter(); var sb = new StringBuilder(); var stringWriter = new StringWriter(sb); var writer = new JsonTextWriter(stringWriter); var serializer = new JsonSerializer(); var exception = Record.Exception(() => converter.WriteJson(writer, data, serializer)); Assert.NotNull(exception); Assert.IsType <InvalidCastException>(exception); }
public void EpochTimeConverter_WriteJsonString_ThrowsInvalidCastException() { var converter = new EpochTimeConverter(); var sb = new StringBuilder(); var stringWriter = new StringWriter(sb); var writer = new JsonTextWriter(stringWriter); var serializer = new JsonSerializer(); converter.WriteJson(writer, "xyz", serializer); var actual = sb.ToString(); Assert.AreNotEqual("1439134235", actual); }
public void WriteJson(string expected, DateTimeOffset original) { var converter = new EpochTimeConverter(); var sb = new StringBuilder(); var stringWriter = new StringWriter(sb); var writer = new JsonTextWriter(stringWriter); var serializer = new JsonSerializer(); converter.WriteJson(writer, original, serializer); var actual = sb.ToString(); Assert.Equal(expected, actual); }
public void EpochTimeConverter_WriteJsonInt64_AreNotEqual() { var converter = new EpochTimeConverter(); var sb = new StringBuilder(); var stringWriter = new StringWriter(sb); var writer = new JsonTextWriter(stringWriter); var serializer = new JsonSerializer(); var date = new DateTimeOffset(new DateTime(2015, 8, 4, 15, 30, 32, DateTimeKind.Utc)); converter.WriteJson(writer, date, serializer); var actual = sb.ToString(); Assert.AreNotEqual("1439134235", actual); }
private PhotoAttachment ParsePhotoAttachment(JObject _jPhoto) { try { if (_jPhoto[PAttachmentsPhoto] is JObject photoJObj) { var photoAttachment = new PhotoAttachment(); photoAttachment.Id = photoJObj[PId].Value <int>(); photoAttachment.AlbumId = photoJObj[PPhotoAlbumId].Value <int>(); photoAttachment.OwnerId = photoJObj[PAttachmentOwnerId].Value <int>(); photoAttachment.UserId = photoJObj[PPhotoUserId]?.Value <int>(); photoAttachment.Text = photoJObj[PPhotoText]?.Value <string>(); photoAttachment.Date = EpochTimeConverter.ConvertToDateTime(photoJObj[PDate].Value <long>()); photoAttachment.AccessKey = photoJObj[PAttachmentAccessKey]?.Value <string>(); var sizes = new List <PhotoSizeInfo>(); if (photoJObj[PPhotoSizes] is JArray jSizes) { foreach (var jSize in jSizes) { var type = (PhotoSizeType)Enum.Parse(typeof(PhotoSizeType), jSize[PSizesType].Value <string>()); var url = jSize[PUrl].Value <string>(); var width = jSize[PSizesWidth].Value <int>(); var height = jSize[PSizesHeight].Value <int>(); var sizeInfo = new PhotoSizeInfo(type, url, width, height); sizes.Add(sizeInfo); } } photoAttachment.Sizes = sizes.ToArray(); return(photoAttachment); } } catch (Exception ex) { throw new InvalidOperationException($"Failed to parse photo attachment \n {_jPhoto.ToString()}", ex); } throw new ArgumentException($"Failed recognize jObject as photo attachment \n {_jPhoto?.ToString()}"); }
private Post ParsePostItem(JObject _jPostItem, Func <VideoInfo, string> _loadVideoItem) { try { var post = new Post(); post.SourceId = _jPostItem[PSourceId].Value <int>(); post.Date = EpochTimeConverter.ConvertToDateTime(_jPostItem[PItemDate].Value <long>()); post.PostId = _jPostItem[PItemId].Value <int>(); post.Text = _jPostItem[PItemText].Value <string>(); post.SignerId = _jPostItem[PItemSignerId]?.Value <int>() ?? null; post.MarkedAsAds = _jPostItem[PItemMarkedAsAds].Value <int>() != 0; post.PostSource = ParsePostSource((JObject)_jPostItem[PPostSource]); var attachmentsRaw = _jPostItem[PAttachments]; if (attachmentsRaw != null) { post.Attachments = ParseAttachments(attachmentsRaw, _loadVideoItem).ToArray(); } post.Comments = ParseComments((JObject)_jPostItem[PComments]); post.Likes = ParseLikes((JObject)_jPostItem[PLikes]); post.Reposts = ParseReposts((JObject)_jPostItem[PReposts]); if (_jPostItem.ContainsKey(PViews)) { post.Views = ParseViews((JObject)_jPostItem[PViews]); } var rawHistoryElem = _jPostItem[PCopyHistrory]; if (rawHistoryElem != null) { post.CopyHistory = ParseHistory(rawHistoryElem, _loadVideoItem).ToArray(); } return(post); } catch (Exception ex) { throw new InvalidOperationException($"Failed to parse post item \n {_jPostItem?.ToString()}", ex); } }
private List <HistoryPost> ParseHistory(JToken _jHistory, Func <VideoInfo, string> _loadVideoItem) { if (_jHistory is JArray jCopyHistory) { try { var historyCollection = new List <HistoryPost>(); foreach (JObject jHistoryElement in jCopyHistory) { var historyPost = new HistoryPost(); historyPost.Id = jHistoryElement[PId].Value <int>(); historyPost.OwnerId = jHistoryElement[PHistoryOwnerId].Value <int>(); historyPost.FromId = jHistoryElement[PHistoryFromId].Value <int>(); historyPost.Date = EpochTimeConverter.ConvertToDateTime(jHistoryElement[PDate].Value <long>()); historyPost.Text = jHistoryElement[PItemText].Value <string>(); historyPost.PostSource = ParsePostSource((JObject)jHistoryElement[PPostSource]); var attachmentsRaw = jHistoryElement[PAttachments]; if (attachmentsRaw != null) { historyPost.Attachments = ParseAttachments(attachmentsRaw, _loadVideoItem).ToArray(); } historyCollection.Add(historyPost); } return(historyCollection); } catch (Exception ex) { throw new InvalidOperationException($"Failed to parse history \n {_jHistory.ToString()}", ex); } } throw new ArgumentException($"History element not recognized as array \n {_jHistory?.ToString()}"); }
private void SetHangUpComplete(string CallSid, string call_uuid, string reason, Event ev, string hangup_url) { long answer_seconds_since_epoch = long.Parse(ev.GetHeader("Caller-Channel-Answered-Time")); long hangup_seconds_since_epoch = long.Parse(ev.GetHeader("Caller-Channel-Hangup-Time")); string called_num = ev.GetHeader("Caller-Destination-Number"); string caller_num = ev.GetHeader("Caller-Caller-ID-Number"); string direction = ev.GetHeader("variable_agbara_call_direction"); //get call details Call call = callSrvc.GetCallDetail(CallSid); call.Status = CallStatus.completed; call.CallerId = caller_num; call.CallTo = called_num; call.DateUpdated = DateTime.Now; call.StartTime = EpochTimeConverter.ConvertFromEpochTime(answer_seconds_since_epoch); call.EndTime = EpochTimeConverter.ConvertFromEpochTime(hangup_seconds_since_epoch); call.Duration = EpochTimeConverter.GetEpochTimeDifferent(hangup_seconds_since_epoch, answer_seconds_since_epoch); call.Direction = direction; try { CallRequest.Remove(CallSid); CallElapsedTime.Remove(CallSid); } catch (Exception ex) { } try { callSrvc.UpdateCallLog(call); } catch (Exception ex) { } }
public void EpochTimeConverter_CanConvertDateTimeOffset_IsTrue() { var converter = new EpochTimeConverter(); Assert.IsTrue(converter.CanConvert(typeof(DateTimeOffset))); }
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()}"); }
public override void Execute(FSOutbound outboundClient) { List <string> numbers = new List <string>(); string sched_hangup_id = string.Empty; string dialNumber = string.Empty; if (!string.IsNullOrEmpty(base.Text.Trim())) { dialNumber = base.Text.Trim(); Number num = new Number(); num.number = dialNumber; numbers.Add(PrepareNumber(num, outboundClient)); } else { //Set numbers to dial from Number nouns foreach (Element child in Children) { string dial_num = ""; Number num = null; Conference conf = null; if (child.GetType() == typeof(Number)) { num = (Number)child; dial_num = PrepareNumber(num, outboundClient); if (string.IsNullOrEmpty(dial_num)) { continue; } numbers.Add(dial_num); } else if (child.GetType() == typeof(Conference)) { //if conference is needed conf = (Conference)child; //set record for conference if (record) { conf.record = true; } //set hangupOnStar for member if (hangupOnStar) { conf.hangup_on_star = true; } //Create Partcipant Participant participant = new Participant(); participant.CallSid = outboundClient.CallSid; participant.AccountSid = outboundClient.AccountSid; conf.participant = participant; conf.Execute(outboundClient); } } } if (numbers == null) { return; } else { string duration_ms = string.Empty; Call bleg = new Call(); //Set timeout outboundClient.set(string.Format("call_timeout={0}", timeout)); outboundClient.set(string.Format("answer_timeout={0}", timeout)); //Set callerid or unset if not provided if (!string.IsNullOrEmpty(caller_id)) { outboundClient.set(string.Format("effective_caller_id_number={0}", caller_id)); } else { outboundClient.unset("effective_caller_id_number"); } //Set continue on fail outboundClient.set("continue_on_fail=true"); //Set ring flag if dial will ring. //But first set agbara_dial_rang to false to be sure we don't get it from an old Dial outboundClient.set("agbara_dial_rang=false"); outboundClient.set("execute_on_ring=set::agbara_dial_rang=true"); //Create dialstring dial_str = string.Join(":_:", numbers); // Don't hangup after bridge ! outboundClient.set("hangup_after_bridge=false"); if (hangupOnStar) { outboundClient.set("bridge_terminate_key=*"); } else { outboundClient.unset("bridge_terminate_key"); } outboundClient.set("bridge_early_media=true"); outboundClient.unset("instant_ringback"); outboundClient.unset("ringback"); //set bleg call sid outboundClient.set(string.Format("agbara_bleg_callsid={0}", bleg.Sid)); //enable session heartbeat outboundClient.set("enable_heartbeat_events=60"); // set call direction outboundClient.set(string.Format("agbara_call_direction={0}", CallDirection.outbounddial)); string dial_rang = ""; string hangup_cause = "NORMAL_CLEARING"; //string recordingPath = ""; //AppSettingsReader reader = new AppSettingsReader(); //recordingPath = (string)reader.GetValue("RecordingDirectory", recordingPath.GetType()); //var CallSid = outboundClient.CallSid; //string filename = string.Format("{0}_{1}", DateTime.UtcNow.ToShortDateString(), outboundClient.get_channel_unique_id()); //string record_file = string.Format("{0}{1}.wav", recordingPath, CallSid); //if (record) //{ // outboundClient.set("RECORD_STEREO=true"); // outboundClient.APICommand(string.Format("uuid_record {0} start {1}", outboundClient.get_channel_unique_id(), record_file)); //} try { //execute bridge outboundClient.bridge(dial_str, outboundClient.get_channel_unique_id(), true); //waiting event var evnt = outboundClient.ActionReturnedEvent(); //parse received events if (evnt.GetHeader("Event-Name") == "CHANNEL_UNBRIDGE") { evnt = outboundClient.ActionReturnedEvent(); } string reason = ""; string originate_disposition = evnt.GetHeader("variable_originate_disposition"); long answer_seconds_since_epoch = long.Parse(evnt.GetHeader("Caller-Channel-Answered-Time")); long end_seconds_since_epoch = long.Parse(evnt.GetHeader("Event-Date-Timestamp")); hangup_cause = originate_disposition; if (hangup_cause == "ORIGINATOR_CANCEL") { reason = string.Format("{0} (A leg)", hangup_cause); } else { reason = string.Format("{0} (B leg)", hangup_cause); } if (string.IsNullOrEmpty(hangup_cause) || hangup_cause == "SUCCESS") { hangup_cause = outboundClient.GetHangupCause(); reason = string.Format("{0} (A leg)", hangup_cause); if (string.IsNullOrEmpty(hangup_cause)) { hangup_cause = outboundClient.GetVar("bridge_hangup_cause", outboundClient.get_channel_unique_id()); reason = string.Format("{0} (B leg)", hangup_cause); if (string.IsNullOrEmpty(hangup_cause)) { hangup_cause = outboundClient.GetVar("hangup_cause", outboundClient.get_channel_unique_id()); reason = string.Format("{0} (A leg)", hangup_cause); if (string.IsNullOrEmpty(hangup_cause)) { hangup_cause = "NORMAL_CLEARING"; reason = string.Format("{0} (A leg)", hangup_cause); } } } } //Get ring status dial_rang = outboundClient.GetVar("agbara_dial_rang", outboundClient.get_channel_unique_id()); //get duration duration_ms = EpochTimeConverter.GetEpochTimeDifferent(answer_seconds_since_epoch, end_seconds_since_epoch).ToString(); } catch (Exception e) { } finally { outboundClient.session_params.Add("DialCallSid", bleg.Sid); outboundClient.session_params.Add("DialCallDuration", duration_ms); if (dial_rang == "true") { outboundClient.session_params.Add("DialCallStatus", CallStatus.completed); } else { outboundClient.session_params.Add("DialCallStatus", CallStatus.failed); } } } //If record is specified if (record) { outboundClient.session_params.Add("RecordingUrl", ""); } if (!string.IsNullOrEmpty(action) && Util.IsValidUrl(action) && !string.IsNullOrEmpty(method)) { Task.Factory.StartNew(() => FetchNextAgbaraRespone(action, outboundClient.session_params, method)); } }
public void CanConvert(Type type, bool canConvert) { var converter = new EpochTimeConverter(); Assert.Equal(converter.CanConvert(type), canConvert); }