/// <summary> /// Saves the momento. /// </summary> /// <param name="message">The message.</param> /// <param name="session">The session.</param> /// <param name="bytes">The bytes.</param> /// <returns>Momntz.Data.Schema.Momento.</returns> private Momento SaveMomento(MediaMessage message, ISession session, byte[] bytes) { var momento = Create(message, session); var dateime = SaveExifInformation(bytes, momento, session); using (var tran = session.BeginTransaction()) { if (dateime.HasValue) { momento.Day = dateime.Value.Day; momento.Month = dateime.Value.Month; momento.Year = dateime.Value.Year; session.Update(momento); } var user = new MomentoUser { Momento = momento, Username = message.Username }; session.Save(user); tran.Commit(); } return(momento); }
/// <summary> /// Enables processing of HTTP Web requests by a custom HttpHandler that implements the <see cref="T:System.Web.IHttpHandler" /> interface. /// </summary> /// <param name="context">An <see cref="T:System.Web.HttpContext" /> object that provides references to the intrinsic server objects (for example, Request, Response, Session, and Server) used to service HTTP requests.</param> public void ProcessRequest(HttpContext context) { //Image formats //jpg, jpeg, png, gif, tiff //Documents Formats //PDF, doc, docx, text var file = context.Request.Files[FormConstants.UploadParameterName]; var albumId = context.Request[FormConstants.AlbumIdParameterName]; var bytes = GetBytes(file); var username = BaseController.AuthenticatedUsername(); var extension = Path.GetExtension(file.FileName).Replace(".", string.Empty); var id = Guid.NewGuid(); var media = new MediaMessage { AlbumId = (string.IsNullOrEmpty(albumId) ? null : (int?)Convert.ToInt32(albumId)), Extension = extension, Filename = file.FileName, Id = id, Size = bytes.Length, Username = username }; _repository.Save(new SaveMediaParameters(id, bytes, media)); }
/// <summary> /// Saves the automatic album. /// </summary> /// <param name="message">The message.</param> /// <param name="session">The session.</param> /// <param name="momento">The momento.</param> private static void SaveToAlbum(MediaMessage message, ISession session, Momento momento) { if (message.AlbumId.HasValue) { var album = session.Get <Album>(message.AlbumId); var albumMomento = new AlbumMomento { Album = album, Momento = momento }; session.Save(albumMomento); } }
/// <summary> /// Creates the momento. /// </summary> /// <param name="mediaMessage">The MediaMessage.</param> /// <param name="session">The session.</param> /// <returns>Momento.</returns> public virtual Momento Create(MediaMessage mediaMessage, ISession session) { var momento = PopulateMomentoObject(mediaMessage); using (var tran = session.BeginTransaction()) { session.Save(momento); tran.Commit(); } return(momento); }
internal MediaMessage CreateMediaMessage(string fileName) { var msg = new MediaMessage() { Side = MessageSide.You, Filename = fileName }; Dispatcher.Invoke(() => { AddToMessages(msg); }); return(msg); }
private void AppendMediaMessage(MediaMessage msg, StringBuilder sb) { var str = string.Format(@"{0} \textit{{{1}}}", FormatSenderAndTime(msg), Latex.EncodeLatex(msg.Filename)); if (!string.IsNullOrWhiteSpace(msg.Subscription)) { str = str + " - " + Encode(msg.Subscription); } sb.AppendLine(str); sb.AppendLine(@"\\"); }
/// <summary> /// Populates the momento object. /// </summary> /// <param name="mediaMessage">The media message.</param> /// <returns>Momento.</returns> private static Momento PopulateMomentoObject(MediaMessage mediaMessage) { var momento = new Momento { InternalId = mediaMessage.Id, User = new User { Username = mediaMessage.Username }, UploadedBy = mediaMessage.Username, Visibility = "Public" }; return(momento); }
public static Media ToMedia(this MediaMessage message) { IFormFile recording = message.File; var media = new Media(); media.FileName = message.FileName; media.MimeType = message.MimeType; using (var ms = new MemoryStream()) { recording.CopyTo(ms); media.File = ms.ToArray(); } return(media); }
private void btnSendMedia_Click(object sender, RoutedEventArgs e) { try { var dlg = new System.Windows.Forms.OpenFileDialog(); // Create OpenFileDialog // Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog(); // Set filter for file extension and default file extension dlg.DefaultExt = ".mp4"; dlg.Filter = "MP3 Files (*.mp3)|*.mp3|WAV Files (*.wav)|*.wav|MP4 Files (*.mp4)|*.mp4|AVI Files (*.avi)|*.avi"; // Display OpenFileDialog by calling ShowDialog method var result = dlg.ShowDialog(); // Get the selected file name and display in a TextBox if (result == System.Windows.Forms.DialogResult.OK) { // Open document string path = dlg.FileName; string filename = dlg.SafeFileName; Console.WriteLine(path); var msg = new MediaMessage() { MediaUrl = path, Side = MessageSide.Me, Filename = filename }; AddToMessages(msg); Task.Run(() => { MainContext.Instance.SendMediaFile(this, path, filename, msg); }); } } catch (Exception ex) { Console.WriteLine(ex.ToString()); } }
protected override Task Execute(CancellationToken token) { log.LogInformation("Publishing..."); IFeedMessage message; if (string.IsNullOrEmpty(config.Image)) { message = new MultiItemMessage("Test Message", config.Text.Split(' ')); } else { message = new MediaMessage(config.Text, File.ReadAllBytes(config.Image)); } publisher.PublishMessage(message); return(Task.CompletedTask); }
private async Task CreateChart(string name, ISentimentTracking tracking, string[] stockItems, string type = null) { int days = 5; var data = await tracking .GetTrackingHistory(new SentimentRequest(stockItems) { Hours = new[] { HoursExtension.GetLastDaysHours(days) }, Type = type }, CancellationToken.None) .ConfigureAwait(false); var selected = data.Where(item => item.Value.Length > 0).ToArray(); foreach (var batch in selected.Batch(5)) { var messageText = new StringBuilder(name + "\r\n"); var currentBlock = batch.ToArray(); IDayChartGenerator chart = chartFactory(name); for (var i = 0; i < currentBlock.Length; i++) { var pair = currentBlock[i]; string stock = pair.Key; if (!stock.StartsWith("$")) { stock = "$" + stock; } if (i > 0) { messageText.Append(' '); } messageText.Append(stock); chart.AddSeriesByDay(pair.Key, pair.Value, days); } byte[] image = await chart.GenerateGraph().ConfigureAwait(false); if (image == null) { log.LogWarning("No image to post"); return; } var message = new MediaMessage(messageText.ToString(), image); publisher.PublishMessage(message); await Task.Delay(TimeSpan.FromMinutes(10)).ConfigureAwait(false); } }
/// <summary> /// Consumes the specified message. /// </summary> /// <param name="message">The message.</param> /// <exception cref="System.NotImplementedException"></exception> public void Consume(MediaMessage message) { try { var processor = _processors.First(m => m.Extensions.Contains(message.Extension.ToLower())); processor.MediaProcessor.Consume(message); } catch (Exception ex) { string error = "MediaSaga exception "; if (message != null) { error += message.ToString(); } _log.Exception(ex, error); } }
public void Consume(MediaMessage message) { if (message != null) { var bytes = _storage.GetFile(QueueConstants.MediaQueue, message.Id.ToString()); var format = GetFormat(message.Extension); using (ISession session = _sessionFactory.OpenSession()) { var momento = SaveMomento(message, session, bytes); SaveToAlbum(message, session, momento); var imageConfigurations = GetImageConfigurations(bytes, format, message, momento); ResizeAndSaveImages(imageConfigurations, session); _storage.DeleteFile(QueueConstants.MediaQueue, message.Id.ToString()); } } }
/// <summary> /// Processes the specified message. /// </summary> /// <param name="message">The message.</param> /// <exception cref="System.NotImplementedException"></exception> public void Consume(MediaMessage message) { throw new System.NotImplementedException(); }
public virtual IActionResult PeoplewithwearablesPersonIdSendMediaMessagePost([FromRoute][Required] string personId, [FromBody] MediaMessage message, [FromHeader][Required()] string Authorization) { //TODO: Uncomment the next line to return response 200 or use other options such as return this.NotFound(), return this.BadRequest(..), ... // return StatusCode(200, default(GeneralResponse)); //TODO: Uncomment the next line to return response 0 or use other options such as return this.NotFound(), return this.BadRequest(..), ... // return StatusCode(0, default(ErrorResponse)); if (!ModelState.IsValid) { var error = ModelState.SelectMany(x => x.Value.Errors).First(); if (error.ErrorMessage != null && error.ErrorMessage != String.Empty) { return(BadRequest(error.ErrorMessage)); } else if (error.Exception?.Message != null) { return(BadRequest("Faulty input")); } else { return(BadRequest(ModelState)); } } if (Authorization != settings.testToken) { return(BadRequest("Not allowed")); } long newZoneID = 0; string errorMessage = ""; PersonWithWearable result = null; try { DatabaseInterface.DBPersonWithWearablesApi dBPersonWithWearablesApi = new DatabaseInterface.DBPersonWithWearablesApi(); if (!dBPersonWithWearablesApi.DBSendPersonMediaMessage(personId, message.MediaLink, message.MediaType, ref errorMessage)) { return(BadRequest("Internal Server Error:" + errorMessage)); } } catch (Exception e) { return(BadRequest("Internal Server Error:" + e.Message)); } string exampleJson = null; exampleJson = "{\n \"success\" : true,\n \"description\" : \"Message sent\"\n}"; var example = exampleJson != null ? JsonConvert.DeserializeObject <GeneralResponse>(exampleJson) : default(GeneralResponse); //TODO: Change the data returned return(new ObjectResult(example)); }
/// <summary> /// Initializes a new instance of the <see cref="SaveMediaParameters"/> class. /// </summary> /// <param name="id">The unique identifier.</param> /// <param name="bytes">The bytes.</param> /// <param name="message">The message.</param> public SaveMediaParameters(Guid id, byte[] bytes, MediaMessage message) { Id = id; Bytes = bytes; Message = message; }
internal void SendMediaFile(ChatWindow chatWindow, string absolutePath, string fileName, MediaMessage msg) { var client = chats.FirstOrDefault(x => x.Value == chatWindow).Key; FileStream fileStream = new FileStream(absolutePath, FileMode.Open, FileAccess.Read); byte[] buffer = new byte[maxSegmentSize]; long length = fileStream.Length; long segmentCount = 1; long sizeCount = 0; long totalSegments = (long)Math.Ceiling((double)length / buffer.Length); long pos = 0; Console.WriteLine("File length: " + length); while (pos < length) { int bytesRead = fileStream.Read(buffer, 0, buffer.Length); sizeCount += bytesRead; byte[] data = new byte[bytesRead]; Array.Copy(buffer, 0, data, 0, bytesRead); FyzrPacket packet = FileProtocol.CreateFilePacket(data, fileName, MessageProtocol.MessageType.PRIVATE, null); packet.headers.Add("Total-Length", "" + length); packet.headers.Add("Total-Segments", "" + totalSegments); packet.headers.Add("Segment", "" + segmentCount); packet.headers.Add("Position", "" + pos); packet.headers.Add("File-Type", "Media"); packet.headers.Add("Username", ownUsername); client.SendRandom(FyzrParser.ToData(packet)); msg.Loading = ((double)segmentCount * 100.0 / totalSegments); msg.Progress = SizeSuffix(sizeCount) + "/" + SizeSuffix(length); pos += buffer.Length; Console.WriteLine("Count: " + segmentCount++); Console.WriteLine("Bytes read: " + bytesRead); Thread.Sleep(2); } }