private void SendDocument(Photo d) { //create thumb var bytes = d.PreviewBytes; if (!CheckDocumentSize((ulong)d.Bytes.Length)) { MessageBox.Show(string.Format(AppResources.MaximumFileSizeExceeded, MediaSizeConverter.Convert((int)Telegram.Api.Constants.MaximumUploadedFileSize)), AppResources.Error, MessageBoxButton.OK); return; } var volumeId = TLLong.Random(); var localId = TLInt.Random(); var secret = TLLong.Random(); var thumbLocation = new TLFileLocation //TODO: replace with TLFileLocationUnavailable { DCId = new TLInt(0), VolumeId = volumeId, LocalId = localId, Secret = secret, //Buffer = bytes }; var fileName = String.Format("{0}_{1}_{2}.jpg", thumbLocation.VolumeId, thumbLocation.LocalId, thumbLocation.Secret); using (var store = IsolatedStorageFile.GetUserStoreForApplication()) { using (var fileStream = store.CreateFile(fileName)) { fileStream.Write(bytes, 0, bytes.Length); } } var thumbSize = new TLPhotoSize { W = new TLInt(d.Width), H = new TLInt(d.Height), Size = new TLInt(bytes.Length), Type = new TLString(""), Location = thumbLocation, }; //create document var document = new TLDocument22 { Buffer = d.Bytes, Id = new TLLong(0), AccessHash = new TLLong(0), Date = TLUtils.DateToUniversalTimeTLInt(MTProtoService.ClientTicksDelta, DateTime.Now), FileName = new TLString(Path.GetFileName(d.FileName)), MimeType = new TLString("image/jpeg"), Size = new TLInt(d.Bytes.Length), Thumb = thumbSize, DCId = new TLInt(0) }; var media = new TLMessageMediaDocument { FileId = TLLong.Random(), Document = document }; var message = GetMessage(TLString.Empty, media); BeginOnUIThread(() => { var previousMessage = InsertSendingMessage(message); IsEmptyDialog = Items.Count == 0 && LazyItems.Count == 0; BeginOnThreadPool(() => CacheService.SyncSendingMessage( message, previousMessage, TLUtils.InputPeerToPeer(Peer, StateService.CurrentUserId), m => SendDocumentInternal(message, null))); }); }
private async Task SendPhotoAsync(StorageFile file, string caption) { var originalProps = await file.Properties.GetImagePropertiesAsync(); var imageWidth = originalProps.Width; var imageHeight = originalProps.Height; if (imageWidth >= 20 * imageHeight || imageHeight >= 20 * imageWidth) { await SendFileAsync(file, caption); return; } var fileLocation = new TLFileLocation { VolumeId = TLLong.Random(), LocalId = TLInt.Random(), Secret = TLLong.Random(), DCId = 0 }; var fileName = string.Format("{0}_{1}_{2}.jpg", fileLocation.VolumeId, fileLocation.LocalId, fileLocation.Secret); var fileCache = await FileUtils.CreateTempFileAsync(fileName); StorageFile fileScale; try { fileScale = await ImageHelper.ScaleJpegAsync(file, fileCache, 1280, 0.77); } catch (InvalidCastException) { await fileCache.DeleteAsync(); await SendGifAsync(file, caption); return; } var basicProps = await fileScale.GetBasicPropertiesAsync(); var imageProps = await fileScale.Properties.GetImagePropertiesAsync(); var date = TLUtils.DateToUniversalTimeTLInt(ProtoService.ClientTicksDelta, DateTime.Now); var photoSize = new TLPhotoSize { Type = "y", W = (int)imageProps.Width, H = (int)imageProps.Height, Location = fileLocation, Size = (int)basicProps.Size }; var photo = new TLPhoto { Id = 0, AccessHash = 0, Date = date, Sizes = new TLVector<TLPhotoSizeBase> { photoSize } }; var media = new TLMessageMediaPhoto { Photo = photo, Caption = caption }; var message = TLUtils.GetMessage(SettingsHelper.UserId, Peer.ToPeer(), TLMessageState.Sending, true, true, date, string.Empty, media, TLLong.Random(), null); if (Reply != null) { message.HasReplyToMsgId = true; message.ReplyToMsgId = Reply.Id; message.Reply = Reply; Reply = null; } var previousMessage = InsertSendingMessage(message); CacheService.SyncSendingMessage(message, previousMessage, async (m) => { var fileId = TLLong.Random(); var upload = await _uploadFileManager.UploadFileAsync(fileId, fileCache.Name, false).AsTask(Upload(photo, progress => new TLSendMessageUploadPhotoAction { Progress = progress })); if (upload != null) { var inputMedia = new TLInputMediaUploadedPhoto { Caption = media.Caption, File = upload.ToInputFile() }; var response = await ProtoService.SendMediaAsync(Peer, inputMedia, message); //if (response.IsSucceeded && response.Result is TLUpdates updates) //{ // TLPhoto newPhoto = null; // var newMessageUpdate = updates.Updates.FirstOrDefault(x => x is TLUpdateNewMessage) as TLUpdateNewMessage; // if (newMessageUpdate != null && newMessageUpdate.Message is TLMessage newMessage && newMessage.Media is TLMessageMediaPhoto newPhotoMedia) // { // newPhoto = newPhotoMedia.Photo as TLPhoto; // } // var newChannelMessageUpdate = updates.Updates.FirstOrDefault(x => x is TLUpdateNewChannelMessage) as TLUpdateNewChannelMessage; // if (newChannelMessageUpdate != null && newMessageUpdate.Message is TLMessage newChannelMessage && newChannelMessage.Media is TLMessageMediaPhoto newChannelPhotoMedia) // { // newPhoto = newChannelPhotoMedia.Photo as TLPhoto; // } // if (newPhoto != null && newPhoto.Full is TLPhotoSize newFull && newFull.Location is TLFileLocation newLocation) // { // var newFileName = string.Format("{0}_{1}_{2}.jpg", newLocation.VolumeId, newLocation.LocalId, newLocation.Secret); // var newFile = await FileUtils.CreateTempFileAsync(newFileName); // await fileCache.CopyAndReplaceAsync(newFile); // } //} } }); }
public static async Task <TLPhotoSizeBase> GetFileThumbAsync(StorageFile file) { try { const int imageSize = 60; IRandomAccessStream thumb = await file.GetThumbnailAsync(ThumbnailMode.SingleItem, imageSize, ThumbnailOptions.ResizeThumbnail); if (((StorageItemThumbnail)thumb).ContentType == "image/png") { var tempThumb = new InMemoryRandomAccessStream(); var decoder = await BitmapDecoder.CreateAsync(thumb); var pixels = await decoder.GetPixelDataAsync(); var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, tempThumb); encoder.SetPixelData(decoder.BitmapPixelFormat, BitmapAlphaMode.Ignore, decoder.PixelWidth, decoder.PixelHeight, decoder.DpiX, decoder.DpiY, pixels.DetachPixelData()); await encoder.FlushAsync(); thumb = tempThumb; } var volumeId = TLLong.Random(); var localId = TLInt.Random(); var secret = TLLong.Random(); var thumbLocation = new TLFileLocation { DCId = new TLInt(0), VolumeId = volumeId, LocalId = localId, Secret = secret, }; var fileName = String.Format("{0}_{1}_{2}.jpg", thumbLocation.VolumeId, thumbLocation.LocalId, thumbLocation.Secret); var thumbFile = await ApplicationData.Current.LocalFolder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting); var thumbBuffer = new Windows.Storage.Streams.Buffer(Convert.ToUInt32(thumb.Size)); var iBuf = await thumb.ReadAsync(thumbBuffer, thumbBuffer.Capacity, InputStreamOptions.None); using (var thumbStream = await thumbFile.OpenAsync(FileAccessMode.ReadWrite)) { await thumbStream.WriteAsync(iBuf); } var thumbSize = new TLPhotoSize { W = new TLInt(imageSize), H = new TLInt(imageSize), Size = new TLInt((int)thumb.Size), Type = TLString.Empty, Location = thumbLocation, Bytes = TLString.FromBigEndianData(thumbBuffer.ToArray()) }; return(thumbSize); } catch (Exception ex) { Telegram.Api.Helpers.Execute.ShowDebugMessage("GetFileThumbAsync exception " + ex); } return(null); }
public void SetPhoto() { var photo = CurrentItem as TLPhoto; if (photo == null) { return; } TLPhotoSize size = null; var sizes = photo.Sizes.OfType <TLPhotoSize>(); const double width = 800.0; foreach (var photoSize in sizes) { if (size == null || Math.Abs(width - size.W.Value) > Math.Abs(width - photoSize.W.Value)) { size = photoSize; } } if (size == null) { return; } var location = size.Location as TLFileLocation; if (location == null) { return; } if (_currentContact != null) { IsWorking = true; MTProtoService.UpdateProfilePhotoAsync(new TLInputPhoto { Id = photo.Id, AccessHash = photo.AccessHash }, result => { IsWorking = false; _items.Insert(0, result); _currentIndex++; MTProtoService.GetUserPhotosAsync(_currentContact.ToInputUser(), new TLInt(1), new TLLong(0), new TLInt(1), photos => { var previousPhoto = photos.Photos.FirstOrDefault(); if (previousPhoto != null) { _items.RemoveAt(1); _items.Insert(1, previousPhoto); } }, error => { Execute.ShowDebugMessage("photos.getUserPhotos error " + error); }); }, error => { IsWorking = false; Execute.ShowDebugMessage("photos.updateProfilePhoto error " + error); }); } else if (_currentChat != null) { var channel = _currentChat as TLChannel; if (channel != null) { if (channel.Id != null) { IsWorking = true; MTProtoService.EditPhotoAsync( channel, new TLInputChatPhoto56 { Id = new TLInputPhoto { Id = photo.Id, AccessHash = photo.AccessHash } }, result => Execute.BeginOnUIThread(() => { IsWorking = false; var updates = result as TLUpdates; if (updates != null) { var updateNewMessage = updates.Updates.FirstOrDefault(x => x is TLUpdateNewMessage) as TLUpdateNewMessage; if (updateNewMessage != null) { var serviceMessage = updateNewMessage.Message as TLMessageService; if (serviceMessage != null) { var chatEditPhotoAction = serviceMessage.Action as TLMessageActionChatEditPhoto; if (chatEditPhotoAction != null) { var newPhoto = chatEditPhotoAction.Photo as TLPhoto; if (newPhoto != null) { _items.Insert(0, newPhoto); _currentIndex++; } } } } } }), error => Execute.BeginOnUIThread(() => { IsWorking = false; Execute.ShowDebugMessage("messages.editChatPhoto error " + error); })); } } var chat = _currentChat as TLChat; if (chat != null) { IsWorking = true; MTProtoService.EditChatPhotoAsync( chat.Id, new TLInputChatPhoto56 { Id = new TLInputPhoto { Id = photo.Id, AccessHash = photo.AccessHash } }, result => Execute.BeginOnUIThread(() => { IsWorking = false; var updates = result as TLUpdates; if (updates != null) { var updateNewMessage = updates.Updates.FirstOrDefault(x => x is TLUpdateNewMessage) as TLUpdateNewMessage; if (updateNewMessage != null) { var serviceMessage = updateNewMessage.Message as TLMessageService; if (serviceMessage != null) { var chatEditPhotoAction = serviceMessage.Action as TLMessageActionChatEditPhoto; if (chatEditPhotoAction != null) { var newPhoto = chatEditPhotoAction.Photo as TLPhoto; if (newPhoto != null) { _items.Insert(0, newPhoto); _currentIndex++; } } } } } }), error => Execute.BeginOnUIThread(() => { IsWorking = false; Execute.ShowDebugMessage("messages.editChatPhoto error " + error); })); } } }
private async Task SendThumbnailFileAsync(StorageFile file, TLFileLocation fileLocation, string fileName, BasicProperties basicProps, TLPhotoSize thumbnail, StorageFile fileCache, string caption) { if (_peer == null) { return; } var desiredName = string.Format("{0}_{1}_{2}.jpg", thumbnail.Location.VolumeId, thumbnail.Location.LocalId, thumbnail.Location.Secret); var date = TLUtils.DateToUniversalTimeTLInt(ProtoService.ClientTicksDelta, DateTime.Now); var document = new TLDocument { Id = 0, AccessHash = 0, Date = date, Size = (int)basicProps.Size, MimeType = fileCache.ContentType, Thumb = thumbnail, Attributes = new TLVector<TLDocumentAttributeBase> { new TLDocumentAttributeFilename { FileName = file.Name } } }; var media = new TLMessageMediaDocument { Document = document, Caption = caption }; var message = TLUtils.GetMessage(SettingsHelper.UserId, _peer.ToPeer(), TLMessageState.Sending, true, true, date, string.Empty, media, TLLong.Random(), null); if (Reply != null) { message.HasReplyToMsgId = true; message.ReplyToMsgId = Reply.Id; message.Reply = Reply; Reply = null; } var previousMessage = InsertSendingMessage(message); CacheService.SyncSendingMessage(message, previousMessage, async (m) => { var fileId = TLLong.Random(); var upload = await _uploadDocumentManager.UploadFileAsync(fileId, fileCache.Name, false).AsTask(Upload(media.Document as TLDocument, progress => new TLSendMessageUploadDocumentAction { Progress = progress })); if (upload != null) { var thumbFileId = TLLong.Random(); var thumbUpload = await _uploadDocumentManager.UploadFileAsync(thumbFileId, desiredName); if (thumbUpload != null) { var inputMedia = new TLInputMediaUploadedThumbDocument { File = upload.ToInputFile(), Thumb = thumbUpload.ToInputFile(), MimeType = document.MimeType, Caption = media.Caption, Attributes = document.Attributes }; var result = await ProtoService.SendMediaAsync(_peer, inputMedia, message); } //if (result.IsSucceeded) //{ // var update = result.Result as TLUpdates; // if (update != null) // { // var newMessage = update.Updates.OfType<TLUpdateNewMessage>().FirstOrDefault(); // if (newMessage != null) // { // var newM = newMessage.Message as TLMessage; // if (newM != null) // { // message.Media = newM.Media; // message.RaisePropertyChanged(() => message.Media); // } // } // } //} } }); }
private void ProcessBotInlineResult(TLMessage45 message, TLBotInlineResultBase resultBase, TLInt botId) { message.InlineBotResultId = resultBase.Id; message.InlineBotResultQueryId = resultBase.QueryId; message.ViaBotId = botId; var botInlineMessageMediaVenue = resultBase.SendMessage as TLBotInlineMessageMediaVenue; var botInlineMessageMediaGeo = resultBase.SendMessage as TLBotInlineMessageMediaGeo; if (botInlineMessageMediaVenue != null) { message._media = new TLMessageMediaVenue72 { Title = botInlineMessageMediaVenue.Title, Address = botInlineMessageMediaVenue.Address, Provider = botInlineMessageMediaVenue.Provider, VenueId = botInlineMessageMediaVenue.VenueId, VenueType = TLString.Empty, Geo = botInlineMessageMediaVenue.Geo }; } else if (botInlineMessageMediaGeo != null) { message._media = new TLMessageMediaGeo { Geo = botInlineMessageMediaGeo.Geo }; } var botInlineMessageMediaContact = resultBase.SendMessage as TLBotInlineMessageMediaContact; if (botInlineMessageMediaContact != null) { message._media = new TLMessageMediaContact82 { PhoneNumber = botInlineMessageMediaContact.PhoneNumber, FirstName = botInlineMessageMediaContact.FirstName, LastName = botInlineMessageMediaContact.LastName, UserId = new TLInt(0), VCard = TLString.Empty }; } var mediaResult = resultBase as TLBotInlineMediaResult; if (mediaResult != null) { if (TLString.Equals(mediaResult.Type, new TLString("voice"), StringComparison.OrdinalIgnoreCase) && mediaResult.Document != null) { message._media = new TLMessageMediaDocument75 { Flags = new TLInt(0), Document = mediaResult.Document, Caption = TLString.Empty, NotListened = !(With is TLChannel) }; message.NotListened = !(With is TLChannel); } else if (TLString.Equals(mediaResult.Type, new TLString("audio"), StringComparison.OrdinalIgnoreCase) && mediaResult.Document != null) { message._media = new TLMessageMediaDocument75 { Flags = new TLInt(0), Document = mediaResult.Document, Caption = TLString.Empty }; } else if (TLString.Equals(mediaResult.Type, new TLString("sticker"), StringComparison.OrdinalIgnoreCase) && mediaResult.Document != null) { message._media = new TLMessageMediaDocument75 { Flags = new TLInt(0), Document = mediaResult.Document, Caption = TLString.Empty }; } else if (TLString.Equals(mediaResult.Type, new TLString("file"), StringComparison.OrdinalIgnoreCase) && mediaResult.Document != null) { message._media = new TLMessageMediaDocument75 { Flags = new TLInt(0), Document = mediaResult.Document, Caption = TLString.Empty }; } else if (TLString.Equals(mediaResult.Type, new TLString("gif"), StringComparison.OrdinalIgnoreCase) && mediaResult.Document != null) { message._media = new TLMessageMediaDocument75 { Flags = new TLInt(0), Document = mediaResult.Document, Caption = TLString.Empty }; } else if (TLString.Equals(mediaResult.Type, new TLString("photo"), StringComparison.OrdinalIgnoreCase) && mediaResult.Photo != null) { message._media = new TLMessageMediaPhoto75 { Flags = new TLInt(0), Photo = mediaResult.Photo, Caption = TLString.Empty }; } else if (TLString.Equals(mediaResult.Type, new TLString("game"), StringComparison.OrdinalIgnoreCase)) { var game = new TLGame { Flags = new TLInt(0), Id = new TLLong(0), AccessHash = new TLLong(0), ShortName = mediaResult.Id, Title = mediaResult.Title ?? TLString.Empty, Description = mediaResult.Description ?? TLString.Empty, Photo = mediaResult.Photo ?? new TLPhotoEmpty { Id = new TLLong(0) }, Document = mediaResult.Document }; message._media = new TLMessageMediaGame { Game = game, SourceMessage = message }; } } var result = resultBase as TLBotInlineResult; if (result != null) { var isVoice = TLString.Equals(result.Type, new TLString("voice"), StringComparison.OrdinalIgnoreCase); var isAudio = TLString.Equals(result.Type, new TLString("audio"), StringComparison.OrdinalIgnoreCase); var isFile = TLString.Equals(result.Type, new TLString("file"), StringComparison.OrdinalIgnoreCase); if (isFile || isAudio || isVoice) { var document = result.Document as TLDocument22; if (document == null) { string fileName = null; if (result.ContentUrl != null) { var fileUri = new Uri(result.ContentUrlString); try { fileName = Path.GetFileName(fileUri.LocalPath); } catch (Exception ex) { } if (fileName == null) { fileName = "file.ext"; } } document = new TLDocument54 { Id = new TLLong(0), AccessHash = new TLLong(0), Date = TLUtils.DateToUniversalTimeTLInt(MTProtoService.ClientTicksDelta, DateTime.Now), FileName = new TLString(fileName), MimeType = result.ContentType ?? TLString.Empty, Size = new TLInt(0), Thumb = new TLPhotoSizeEmpty { Type = TLString.Empty }, DCId = new TLInt(0), Version = new TLInt(0) }; if (isVoice || isAudio) { var documentAttributeAudio = new TLDocumentAttributeAudio46 { Duration = result.Duration ?? new TLInt(0), Title = result.Title ?? TLString.Empty, Performer = null, Voice = isVoice }; document.Attributes.Add(documentAttributeAudio); } //message._status = MessageStatus.Failed; } var mediaDocument = new TLMessageMediaDocument75 { Flags = new TLInt(0), Document = document, Caption = TLString.Empty }; message._media = mediaDocument; mediaDocument.NotListened = isVoice && !(With is TLChannel); message.NotListened = isVoice && !(With is TLChannel); } else if (TLString.Equals(result.Type, new TLString("gif"), StringComparison.OrdinalIgnoreCase)) { var document = result.Document; if (document != null) { var mediaDocument = new TLMessageMediaDocument75 { Flags = new TLInt(0), Document = document, Caption = TLString.Empty }; message._media = mediaDocument; } } else if (TLString.Equals(result.Type, new TLString("photo"), StringComparison.OrdinalIgnoreCase)) { Telegram.Api.Helpers.Execute.ShowDebugMessage(string.Format("w={0} h={1}\nthumb_url={2}\ncontent_url={3}", result.W, result.H, result.ThumbUrl, result.ContentUrl)); var location = new TLFileLocation { DCId = new TLInt(1), VolumeId = TLLong.Random(), LocalId = TLInt.Random(), Secret = TLLong.Random() }; var cachedSize = new TLPhotoCachedSize { Type = new TLString("s"), W = result.W ?? new TLInt(90), H = result.H ?? new TLInt(90), Location = location, Bytes = TLString.Empty, TempUrl = result.ThumbUrlString ?? result.ContentUrlString //Size = new TLInt(0) }; var size = new TLPhotoSize { Type = new TLString("m"), W = result.W ?? new TLInt(90), H = result.H ?? new TLInt(90), Location = location, TempUrl = result.ContentUrlString, Size = new TLInt(0) }; if (!string.IsNullOrEmpty(result.ThumbUrlString)) { //ServicePointManager.ServerCertificateValidationCallback += new var webClient = new WebClient(); webClient.OpenReadAsync(new Uri(result.ThumbUrlString, UriKind.Absolute)); webClient.OpenReadCompleted += (sender, args) => { if (args.Cancelled) { return; } if (args.Error != null) { return; } var fileName = String.Format("{0}_{1}_{2}.jpg", location.VolumeId, location.LocalId, location.Secret); using (var stream = args.Result) { using (var store = IsolatedStorageFile.GetUserStoreForApplication()) { if (store.FileExists(fileName)) { return; } using (var file = store.OpenFile(fileName, FileMode.OpenOrCreate, FileAccess.Write, FileShare.Read)) { const int BUFFER_SIZE = 128 * 1024; var buf = new byte[BUFFER_SIZE]; var bytesread = 0; while ((bytesread = stream.Read(buf, 0, BUFFER_SIZE)) > 0) { var position = stream.Position; stream.Position = position - 10; var tempBuffer = new byte[10]; var resultOk = stream.Read(tempBuffer, 0, tempBuffer.Length); file.Write(buf, 0, bytesread); } } } } if (!string.IsNullOrEmpty(result.ContentUrlString)) { webClient.OpenReadAsync(new Uri(result.ContentUrlString, UriKind.Absolute)); webClient.OpenReadCompleted += (sender2, args2) => { if (args2.Cancelled) { return; } if (args2.Error != null) { return; } using (var stream = args2.Result) { using (var store = IsolatedStorageFile.GetUserStoreForApplication()) { if (store.FileExists(fileName)) { return; } using (var file = store.OpenFile(fileName, FileMode.OpenOrCreate, FileAccess.Write, FileShare.Read)) { const int BUFFER_SIZE = 128 * 1024; var buf = new byte[BUFFER_SIZE]; int bytesread = 0; while ((bytesread = stream.Read(buf, 0, BUFFER_SIZE)) > 0) { file.Write(buf, 0, bytesread); } } } } }; } }; } var photo = new TLPhoto56 { Flags = new TLInt(0), Id = TLLong.Random(), AccessHash = TLLong.Random(), Date = TLUtils.DateToUniversalTimeTLInt(MTProtoService.ClientTicksDelta, DateTime.Now), Sizes = new TLVector <TLPhotoSizeBase> { cachedSize, size } }; var mediaPhoto = new TLMessageMediaPhoto75 { Flags = new TLInt(0), Photo = photo, Caption = TLString.Empty }; message._media = mediaPhoto; } } var messageText = resultBase.SendMessage as TLBotInlineMessageText; if (messageText != null) { message.Message = messageText.Message; message.Entities = messageText.Entities; if (messageText.NoWebpage) { } } var mediaAuto = resultBase.SendMessage as TLBotInlineMessageMediaAuto75; if (mediaAuto != null) { message.Message = mediaAuto.Caption; message.Entities = mediaAuto.Entities; } if (resultBase.SendMessage != null && resultBase.SendMessage.ReplyMarkup != null) { message.ReplyMarkup = resultBase.SendMessage.ReplyMarkup; } }
public void Share() { #if WP8 var message = CurrentItem as TLMessage; if (message == null) { return; } var mediaPhoto = message.Media as TLMessageMediaPhoto; if (mediaPhoto != null) { var photo = mediaPhoto.Photo as TLPhoto; if (photo == null) { return; } TLPhotoSize size = null; var sizes = photo.Sizes.OfType <TLPhotoSize>(); const double width = 800.0; foreach (var photoSize in sizes) { if (size == null || Math.Abs(width - size.W.Value) > Math.Abs(width - photoSize.W.Value)) { size = photoSize; } } if (size == null) { return; } var location = size.Location as TLFileLocation; if (location == null) { return; } var fileName = //mediaPhoto.IsoFileName ?? String.Format("{0}_{1}_{2}.jpg", location.VolumeId, location.LocalId, location.Secret); var dataTransferManager = DataTransferManager.GetForCurrentView(); dataTransferManager.DataRequested += (o, args) => { var request = args.Request; request.Data.Properties.Title = "media"; request.Data.Properties.ApplicationName = "Telegram Messenger"; var deferral = request.GetDeferral(); try { var fileToShare = FileUtils.GetLocalFile(fileName);//this.GetImageFileAsync("Sample.jpg"); if (fileToShare == null) { return; } //var storageFileToShare = await this.GetStorageFileForImageAsync("Sample.jpg"); //request.Data.Properties.Thumbnail = RandomAccessStreamReference.CreateFromStream(fileToShare); //request.Data.SetBitmap(RandomAccessStreamReference.CreateFromStream(fileToShare)); // On Windows Phone, share StorageFile instead of Bitmaps request.Data.SetStorageItems(new List <StorageFile> { fileToShare }); } finally { deferral.Complete(); } }; DataTransferManager.ShowShareUI(); return; SavePhotoAsync(mediaPhoto, path => { var task = new ShareMediaTask { FilePath = path }; task.Show(); }); } #endif }
public void LoadFile(TLPhotoSize photo, String ext, bool cacheOnly, TaskCompletionSource <string> tsc) { LoadFile(null, null, photo.Location, ext, photo.Size, false, cacheOnly || (photo != null && photo.Size == 0 /*|| photo.Location.key != null*/), tsc); }
public static async Task <TLPhotoSizeBase> GetFileThumbnailAsync(StorageFile file) { //file = await Package.Current.InstalledLocation.GetFileAsync("Assets\\Thumb.jpg"); //var imageProps = await file.Properties.GetImagePropertiesAsync(); //var videoProps = await file.Properties.GetVideoPropertiesAsync(); //if (imageProps.Width > 0 || videoProps.Width > 0) //{ using (var thumb = await file.GetThumbnailAsync(ThumbnailMode.MusicView, 96, ThumbnailOptions.ResizeThumbnail)) { if (thumb != null && thumb.Type == ThumbnailType.Image) { var randomStream = thumb as IRandomAccessStream; var originalWidth = (int)thumb.OriginalWidth; var originalHeight = (int)thumb.OriginalHeight; if (thumb.ContentType != "image/jpeg") { var memoryStream = new InMemoryRandomAccessStream(); var bitmapDecoder = await BitmapDecoder.CreateAsync(thumb); var pixelDataProvider = await bitmapDecoder.GetPixelDataAsync(); var bitmapEncoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, memoryStream); bitmapEncoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore, bitmapDecoder.PixelWidth, bitmapDecoder.PixelHeight, bitmapDecoder.DpiX, bitmapDecoder.DpiY, pixelDataProvider.DetachPixelData()); await bitmapEncoder.FlushAsync(); randomStream = memoryStream; } var fileLocation = new TLFileLocation { VolumeId = TLLong.Random(), LocalId = TLInt.Random(), Secret = TLLong.Random(), DCId = 0 }; var desiredName = string.Format("{0}_{1}_{2}.jpg", fileLocation.VolumeId, fileLocation.LocalId, fileLocation.Secret); var desiredFile = await CreateTempFileAsync(desiredName); var buffer = new Windows.Storage.Streams.Buffer(Convert.ToUInt32(randomStream.Size)); var buffer2 = await randomStream.ReadAsync(buffer, buffer.Capacity, InputStreamOptions.None); using (var stream = await desiredFile.OpenAsync(FileAccessMode.ReadWrite)) { await stream.WriteAsync(buffer2); stream.Dispose(); } var result = new TLPhotoSize { W = originalWidth, H = originalHeight, Size = (int)randomStream.Size, Type = string.Empty, Location = fileLocation }; randomStream.Dispose(); return(result); } } //} return(null); }
public async Task <TLMessage25> GetPhotoMessage(StorageFile file) { //var stopwatch = Stopwatch.StartNew(); var threadId = Thread.CurrentThread.ManagedThreadId; var volumeId = TLLong.Random(); var localId = TLInt.Random(); var secret = TLLong.Random(); var fileLocation = new TLFileLocation { VolumeId = volumeId, LocalId = localId, Secret = secret, DCId = new TLInt(0), //TODO: remove from here, replace with FileLocationUnavailable //Buffer = p.Bytes }; var fileName = String.Format("{0}_{1}_{2}.jpg", fileLocation.VolumeId, fileLocation.LocalId, fileLocation.Secret); var stream = await file.OpenReadAsync(); //System.Diagnostics.Debug.WriteLine(threadId + " " + "GetPhotoMessage OpenRead " + stopwatch.Elapsed); var resizedPhoto = await ResizeJpeg(stream, Constants.DefaultImageSize, file.DisplayName, fileName); //System.Diagnostics.Debug.WriteLine(threadId + " " + "GetPhotoMessage ResizeJpeg " + stopwatch.Elapsed); var photoSize = new TLPhotoSize { Type = TLString.Empty, W = new TLInt(resizedPhoto.Width), H = new TLInt(resizedPhoto.Height), Location = fileLocation, Size = new TLInt(resizedPhoto.Bytes.Length) }; volumeId = TLLong.Random(); localId = TLInt.Random(); secret = TLLong.Random(); var previewFileLocation = new TLFileLocation { VolumeId = volumeId, LocalId = localId, Secret = secret, DCId = new TLInt(0), //TODO: remove from here, replace with FileLocationUnavailable //Buffer = p.Bytes }; var previewFileName = String.Format("{0}_{1}_{2}.jpg", previewFileLocation.VolumeId, previewFileLocation.LocalId, previewFileLocation.Secret); var photo = new TLPhoto56 { Flags = new TLInt(0), Id = new TLLong(0), AccessHash = new TLLong(0), Date = TLUtils.DateToUniversalTimeTLInt(MTProtoService.ClientTicksDelta, DateTime.Now), Sizes = new TLVector <TLPhotoSizeBase> { photoSize }, }; // to improve performance for bulk photo preview generation Execute.BeginOnThreadPool(async() => { stream = await file.OpenReadAsync(); var previewPhoto = await ResizeJpeg(stream, 90, file.DisplayName, previewFileName); var previewPhotoSize = new TLPhotoSize { Type = new TLString("s"), W = new TLInt(previewPhoto.Width), H = new TLInt(previewPhoto.Height), Location = previewFileLocation, Size = new TLInt(previewPhoto.Bytes.Length) }; Execute.BeginOnUIThread(() => { photo.Sizes.Add(previewPhotoSize); }); }); var media = new TLMessageMediaPhoto75 { Flags = new TLInt(0), Photo = photo, Caption = TLString.Empty, File = resizedPhoto.File }; return(GetMessage(TLString.Empty, media)); }
private void SendPhoto(Photo p) { var volumeId = TLLong.Random(); var localId = TLInt.Random(); var secret = TLLong.Random(); var fileLocation = new TLFileLocation { VolumeId = volumeId, LocalId = localId, Secret = secret, DCId = new TLInt(0), //TODO: remove from here, replace with FileLocationUnavailable //Buffer = p.Bytes }; var fileName = String.Format("{0}_{1}_{2}.jpg", fileLocation.VolumeId, fileLocation.LocalId, fileLocation.Secret); using (var store = IsolatedStorageFile.GetUserStoreForApplication()) { using (var fileStream = store.CreateFile(fileName)) { fileStream.Write(p.Bytes, 0, p.Bytes.Length); } } var photoSize = new TLPhotoSize { Type = TLString.Empty, W = new TLInt(p.Width), H = new TLInt(p.Height), Location = fileLocation, Size = new TLInt(p.Bytes.Length) }; var photo = new TLPhoto56 { Flags = new TLInt(0), Id = new TLLong(0), AccessHash = new TLLong(0), Date = TLUtils.DateToUniversalTimeTLInt(MTProtoService.ClientTicksDelta, DateTime.Now), Sizes = new TLVector <TLPhotoSizeBase> { photoSize }, }; var media = new TLMessageMediaPhoto75 { Flags = new TLInt(0), Photo = photo, Caption = TLString.Empty }; var message = GetMessage(TLString.Empty, media); if (ImageEditor == null) { ImageEditor = new ImageEditorViewModel { CurrentItem = message, ContinueAction = ContinueSendPhoto }; NotifyOfPropertyChange(() => ImageEditor); } else { ImageEditor.CurrentItem = message; } BeginOnUIThread(() => ImageEditor.OpenEditor()); }
public void SetPhoto() { var photo = CurrentItem as TLPhoto; if (photo == null) { return; } TLPhotoSize size = null; var sizes = photo.Sizes.OfType <TLPhotoSize>(); const double width = 800.0; foreach (var photoSize in sizes) { if (size == null || Math.Abs(width - size.W.Value) > Math.Abs(width - photoSize.W.Value)) { size = photoSize; } } if (size == null) { return; } var location = size.Location as TLFileLocation; if (location == null) { return; } IsWorking = true; MTProtoService.UpdateProfilePhotoAsync(new TLInputPhoto { Id = photo.Id, AccessHash = photo.AccessHash }, new TLInputPhotoCropAuto(), result => { IsWorking = false; _items.Insert(0, result); _currentIndex++; MTProtoService.GetUserPhotosAsync(_currentContact.ToInputUser(), new TLInt(1), new TLLong(0), new TLInt(1), photos => { var previousPhoto = photos.Photos.FirstOrDefault(); if (previousPhoto != null) { _items.RemoveAt(1); _items.Insert(1, previousPhoto); } }, error => { Execute.ShowDebugMessage("photos.getUserPhotos error " + error); }); }, error => { IsWorking = false; Execute.ShowDebugMessage("photos.updateProfilePhoto error " + error); }); }
private static async Task <Tuple <TLPhotoSizeBase, TLPhotoSizeBase> > GetFilePreviewAndThumbAsync(StorageFile file) { try { var preview = await file.GetThumbnailAsync(ThumbnailMode.SingleItem, 480, ThumbnailOptions.ResizeThumbnail); var thumbLocation = new TLFileLocation { DCId = new TLInt(0), VolumeId = TLLong.Random(), LocalId = TLInt.Random(), Secret = TLLong.Random(), }; var thumbFileName = String.Format("{0}_{1}_{2}.jpg", thumbLocation.VolumeId, thumbLocation.LocalId, thumbLocation.Secret); var previewLocation = new TLFileLocation { DCId = new TLInt(0), VolumeId = TLLong.Random(), LocalId = TLInt.Random(), Secret = TLLong.Random(), }; var previewFileName = String.Format("{0}_{1}_{2}.jpg", previewLocation.VolumeId, previewLocation.LocalId, previewLocation.Secret); var previewFile = await ApplicationData.Current.LocalFolder.CreateFileAsync(previewFileName, CreationCollisionOption.ReplaceExisting); var previewBuffer = new Windows.Storage.Streams.Buffer(Convert.ToUInt32(preview.Size)); var iBuf = await preview.ReadAsync(previewBuffer, previewBuffer.Capacity, InputStreamOptions.None); var filePreview = new TLPhotoSize { W = new TLInt((int)preview.OriginalWidth), H = new TLInt((int)preview.OriginalHeight), Size = new TLInt((int)preview.Size), Type = TLString.Empty, Location = previewLocation, }; Photo thumb; using (var previewStream = await previewFile.OpenAsync(FileAccessMode.ReadWrite)) { await previewStream.WriteAsync(iBuf); thumb = await ChooseAttachmentViewModel.ResizeJpeg(previewStream, 90, thumbFileName); } var thumbFile = await ApplicationData.Current.LocalFolder.CreateFileAsync(thumbFileName, CreationCollisionOption.ReplaceExisting); var iBuf2 = thumb.Bytes.AsBuffer(); using (var thumbStream = await thumbFile.OpenAsync(FileAccessMode.ReadWrite)) { await thumbStream.WriteAsync(iBuf2); } var fileThumb = new TLPhotoSize { W = new TLInt(thumb.Width), H = new TLInt(thumb.Height), Size = new TLInt(thumb.Bytes.Length), Type = new TLString("s"), Location = thumbLocation, }; return(new Tuple <TLPhotoSizeBase, TLPhotoSizeBase>(filePreview, fileThumb)); } catch (Exception ex) { Telegram.Api.Helpers.Execute.ShowDebugMessage("GetFilePreviewAndThumbAsync exception " + ex); } return(new Tuple <TLPhotoSizeBase, TLPhotoSizeBase>(null, null)); }
private void SendVideo(RecordedVideo recorderVideo) { if (recorderVideo == null) { return; } long size = 0; using (var storage = IsolatedStorageFile.GetUserStoreForApplication()) { using (var file = storage.OpenFile(recorderVideo.FileName, FileMode.Open, FileAccess.Read)) { size = file.Length; } } long photoSize = 0; using (var storage = IsolatedStorageFile.GetUserStoreForApplication()) { using (var file = storage.OpenFile(recorderVideo.FileName + ".jpg", FileMode.Open, FileAccess.Read)) { photoSize = file.Length; } } var volumeId = TLLong.Random(); var localId = TLInt.Random(); var secret = TLLong.Random(); var thumbLocation = new TLFileLocation //TODO: replace with TLFileLocationUnavailable { DCId = new TLInt(0), VolumeId = volumeId, LocalId = localId, Secret = secret, }; var fileName = String.Format("{0}_{1}_{2}.jpg", thumbLocation.VolumeId, thumbLocation.LocalId, thumbLocation.Secret); // заменяем имя на стандартное для всех каритинок using (var store = IsolatedStorageFile.GetUserStoreForApplication()) { store.CopyFile(recorderVideo.FileName + ".jpg", fileName, true); store.DeleteFile(recorderVideo.FileName + ".jpg"); } var thumbSize = new TLPhotoSize { W = new TLInt(640), H = new TLInt(480), Size = new TLInt((int)photoSize), Type = new TLString(""), Location = thumbLocation, }; var documentAttributeVideo = new TLDocumentAttributeVideo { Duration = new TLInt((int)recorderVideo.Duration), W = new TLInt(640), H = new TLInt(480) }; var document = new TLDocument54 { Id = new TLLong(0), AccessHash = new TLLong(0), Date = TLUtils.DateToUniversalTimeTLInt(MTProtoService.ClientTicksDelta, DateTime.Now), MimeType = new TLString("video/mp4"), Size = new TLInt((int)size), Thumb = thumbSize, DCId = new TLInt(0), Version = new TLInt(0), Attributes = new TLVector <TLDocumentAttributeBase> { documentAttributeVideo } }; var media = new TLMessageMediaDocument75 { Flags = new TLInt(0), FileId = recorderVideo.FileId ?? TLLong.Random(), Document = document, IsoFileName = recorderVideo.FileName, Caption = TLString.Empty }; var message = GetMessage(TLString.Empty, media); BeginOnUIThread(() => { var previousMessage = InsertSendingMessage(message); IsEmptyDialog = Items.Count == 0 && (_messages == null || _messages.Count == 0) && LazyItems.Count == 0; BeginOnThreadPool(() => CacheService.SyncSendingMessage( message, previousMessage, m => SendVideoInternal(message, null))); }); }
protected string ExportPhoto(TLMessageMediaPhoto media) { // TLPhoto contains a collection of TLPhotoSize TLPhoto photo = media.photo as TLPhoto; if (photo == null) { throw new TLCoreException("The photo is not an instance of TLPhoto"); } if (photo.sizes.lists.Count <= 0) { throw new TLCoreException("TLPhoto does not have any element"); } // Pick max size photo from TLPhoto TLPhotoSize photoMaxSize = null; foreach (TLAbsPhotoSize absPhotoSize in photo.sizes.lists) { TLPhotoSize photoSize = absPhotoSize as TLPhotoSize; if (photoSize == null) { throw new TLCoreException("The photosize is not an instance of TLPhotoSize"); } if (photoMaxSize != null && photoSize.w < photoMaxSize.w) { continue; } photoMaxSize = photoSize; } // a TLPhotoSize contains a TLFileLocation TLFileLocation fileLocation = photoMaxSize.location as TLFileLocation; if (fileLocation == null) { throw new TLCoreException("The file location is not an instance of TLFileLocation"); } TLFile file = m_archiver.GetFile(fileLocation, photoMaxSize.size); string ext = ""; if (file.type.GetType() == typeof(TLFileJpeg)) { ext = "jpg"; } else if (file.type.GetType() == typeof(TLFileGif)) { ext = "gif"; } else if (file.type.GetType() == typeof(TLFilePng)) { ext = "png"; } else { throw new TLCoreException("The photo has an unknown file type"); } // Take a caption if exists or set the default one string sCaption = String.IsNullOrEmpty(media.caption) ? c_sPhoto : media.caption; // Key: YYYY-MM-DD-Caption{0:00}.EXT string key = String.Format("{0}-{1}{2}.{3}", m_sPrefix, sCaption, "{0:00}", ext); string sFileName = GetUniqueFileName(key); // YYYY-MM-DD-CaptionXX.EXT if (m_config.ExportPhotos) { // Export the photo to a file string sFullFileName = Path.Combine(m_sDialogDirectory, sFileName); using (FileStream f = new FileStream(sFullFileName, FileMode.Create, FileAccess.Write)) f.Write(file.bytes, 0, photoMaxSize.size); } return(sFileName); // YYYY-MM-DD-CaptionXX.EXT }
public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { var timer = Stopwatch.StartNew(); var encryptedPhoto = value as TLEncryptedFile; if (encryptedPhoto != null) { return(ReturnOrEnqueueImage(timer, encryptedPhoto, encryptedPhoto)); } var userProfilePhoto = value as TLUserProfilePhoto; if (userProfilePhoto != null) { var location = userProfilePhoto.PhotoSmall as TLFileLocation; if (location != null) { return(ReturnOrEnqueueProfileImage(timer, location, userProfilePhoto, new TLInt(0))); } } var chatPhoto = value as TLChatPhoto; if (chatPhoto != null) { var location = chatPhoto.PhotoSmall as TLFileLocation; if (location != null) { return(ReturnOrEnqueueProfileImage(timer, location, chatPhoto, new TLInt(0))); } } var decrypteMedia = value as TLDecryptedMessageMediaBase; if (decrypteMedia != null) { var decryptedMediaVideo = value as TLDecryptedMessageMediaVideo; if (decryptedMediaVideo != null) { var buffer = decryptedMediaVideo.Thumb.Data; if (buffer.Length > 0 && decryptedMediaVideo.ThumbW.Value > 0 && decryptedMediaVideo.ThumbH.Value > 0) { var memoryStream = new MemoryStream(buffer); var bitmap = PictureDecoder.DecodeJpeg(memoryStream); bitmap.BoxBlur(37); var blurredStream = new MemoryStream(); bitmap.SaveJpeg(blurredStream, decryptedMediaVideo.ThumbW.Value, decryptedMediaVideo.ThumbH.Value, 0, 70); return(ImageUtils.CreateImage(blurredStream.ToArray())); } return(ImageUtils.CreateImage(buffer)); } var decryptedMediaDocument = value as TLDecryptedMessageMediaDocument; if (decryptedMediaDocument != null) { var location = decryptedMediaDocument.File as TLEncryptedFile; if (location != null) { var fileName = String.Format("{0}_{1}_{2}.jpg", location.Id, location.DCId, location.AccessHash); using (var store = IsolatedStorageFile.GetUserStoreForApplication()) { if (store.FileExists(fileName)) { BitmapImage imageSource; try { using (var stream = store.OpenFile(fileName, FileMode.Open, FileAccess.Read)) { stream.Seek(0, SeekOrigin.Begin); var image = new BitmapImage(); image.SetSource(stream); imageSource = image; } } catch (Exception) { return(null); } return(imageSource); } } } var buffer = decryptedMediaDocument.Thumb.Data; return(ImageUtils.CreateImage(buffer)); } var file = decrypteMedia.File as TLEncryptedFile; if (file != null) { return(ReturnOrEnqueueImage(timer, file, decrypteMedia)); } } var decryptedMessage = value as TLDecryptedMessage17; if (decryptedMessage != null) { var decryptedMediaExternalDocument = decryptedMessage.Media as TLDecryptedMessageMediaExternalDocument; if (decryptedMediaExternalDocument != null) { #if WP8 return(ReturnOrEnqueueSticker(decryptedMediaExternalDocument, decryptedMessage)); #endif return(null); } } var photoMedia = value as TLMessageMediaPhoto; if (photoMedia != null) { value = photoMedia.Photo; } var photo = value as TLPhoto; if (photo != null) { var width = 311.0; double result; if (Double.TryParse((string)parameter, out result)) { width = result; } TLPhotoSize size = null; var sizes = photo.Sizes.OfType <TLPhotoSize>(); foreach (var photoSize in sizes) { if (size == null || Math.Abs(width - size.W.Value) > Math.Abs(width - photoSize.W.Value)) { size = photoSize; } } if (size != null) { var location = size.Location as TLFileLocation; if (location != null) { return(ReturnOrEnqueueImage(timer, location, photo, size.Size)); } } } #if WP8 var sticker = value as TLStickerItem; if (sticker != null) { var document22 = sticker.Document as TLDocument22; if (document22 == null) { return(null); } var thumbCachedSize = document22.Thumb as TLPhotoCachedSize; if (thumbCachedSize != null) { var fileName = "cached" + document22.GetFileName(); var buffer = thumbCachedSize.Bytes.Data; if (buffer == null) { return(null); } return(DecodeWebPImage(fileName, buffer, () => { })); } var thumbPhotoSize = document22.Thumb as TLPhotoSize; if (thumbPhotoSize != null) { var location = thumbPhotoSize.Location as TLFileLocation; if (location != null) { return(ReturnOrEnqueueStickerPreview(location, sticker, thumbPhotoSize.Size)); } } if (TLMessageBase.IsSticker(document22)) { return(ReturnOrEnqueueSticker(document22, sticker)); } } #endif var document = value as TLDocument; if (document != null) { #if WP8 if (TLMessageBase.IsSticker(document)) { if (parameter != null && string.Equals(parameter.ToString(), "ignoreStickers", StringComparison.OrdinalIgnoreCase)) { return(null); } return(ReturnOrEnqueueSticker((TLDocument22)document, null)); } #endif var thumbPhotoSize = document.Thumb as TLPhotoSize; if (thumbPhotoSize != null) { var location = thumbPhotoSize.Location as TLFileLocation; if (location != null) { return(ReturnOrEnqueueImage(timer, location, document, thumbPhotoSize.Size)); } } var thumbCachedSize = document.Thumb as TLPhotoCachedSize; if (thumbCachedSize != null) { var buffer = thumbCachedSize.Bytes.Data; return(ImageUtils.CreateImage(buffer)); } } var videoMedia = value as TLMessageMediaVideo; if (videoMedia != null) { value = videoMedia.Video; } var video = value as TLVideo; if (video != null) { var thumbPhotoSize = video.Thumb as TLPhotoSize; if (thumbPhotoSize != null) { var location = thumbPhotoSize.Location as TLFileLocation; if (location != null) { return(ReturnOrEnqueueImage(timer, location, video, thumbPhotoSize.Size)); } } var thumbCachedSize = video.Thumb as TLPhotoCachedSize; if (thumbCachedSize != null) { var buffer = thumbCachedSize.Bytes.Data; return(ImageUtils.CreateImage(buffer)); } } var webPageMedia = value as TLMessageMediaWebPage; if (webPageMedia != null) { value = webPageMedia.WebPage; } var webPage = value as TLWebPage; if (webPage != null) { var webPagePhoto = webPage.Photo as TLPhoto; if (webPagePhoto != null) { var width = 311.0; double result; if (Double.TryParse((string)parameter, out result)) { width = result; } TLPhotoSize size = null; var sizes = webPagePhoto.Sizes.OfType <TLPhotoSize>(); foreach (var photoSize in sizes) { if (size == null || Math.Abs(width - size.W.Value) > Math.Abs(width - photoSize.W.Value)) { size = photoSize; } } if (size != null) { var location = size.Location as TLFileLocation; if (location != null) { return(ReturnOrEnqueueImage(timer, location, webPage, size.Size)); } } } } return(null); }
public static async Task <TLPhotoSizeBase> GetVideoThumbnailAsync(StorageFile file, VideoProperties props, VideoTransformEffectDefinition effect) { double originalWidth = props.GetWidth(); double originalHeight = props.GetHeight(); if (effect != null && !effect.CropRectangle.IsEmpty) { file = await CropAsync(file, effect.CropRectangle); originalWidth = effect.CropRectangle.Width; originalHeight = effect.CropRectangle.Height; } TLPhotoSizeBase result; var fileLocation = new TLFileLocation { VolumeId = TLLong.Random(), LocalId = TLInt.Random(), Secret = TLLong.Random(), DCId = 0 }; var desiredName = string.Format("{0}_{1}_{2}.jpg", fileLocation.VolumeId, fileLocation.LocalId, fileLocation.Secret); var desiredFile = await FileUtils.CreateTempFileAsync(desiredName); using (var fileStream = await OpenReadAsync(file)) using (var outputStream = await desiredFile.OpenAsync(FileAccessMode.ReadWrite)) { var decoder = await BitmapDecoder.CreateAsync(fileStream); double ratioX = (double)90 / originalWidth; double ratioY = (double)90 / originalHeight; double ratio = Math.Min(ratioX, ratioY); uint width = (uint)(originalWidth * ratio); uint height = (uint)(originalHeight * ratio); var transform = new BitmapTransform(); transform.ScaledWidth = width; transform.ScaledHeight = height; transform.InterpolationMode = BitmapInterpolationMode.Linear; if (effect != null) { transform.Flip = effect.Mirror == MediaMirroringOptions.Horizontal ? BitmapFlip.Horizontal : BitmapFlip.None; } var pixelData = await decoder.GetSoftwareBitmapAsync(decoder.BitmapPixelFormat, decoder.BitmapAlphaMode, transform, ExifOrientationMode.RespectExifOrientation, ColorManagementMode.DoNotColorManage); var propertySet = new BitmapPropertySet(); var qualityValue = new BitmapTypedValue(0.77, PropertyType.Single); propertySet.Add("ImageQuality", qualityValue); var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, outputStream); encoder.SetSoftwareBitmap(pixelData); await encoder.FlushAsync(); result = new TLPhotoSize { W = (int)width, H = (int)height, Size = (int)outputStream.Size, Type = string.Empty, Location = fileLocation }; } return(result); }
public void OpenMedia(TLMessageBase messageBase) #endif { if (messageBase == null) { return; } if (messageBase.Status == MessageStatus.Failed || messageBase.Status == MessageStatus.Sending) { return; } var serviceMessage = messageBase as TLMessageService; if (serviceMessage != null) { var editPhotoAction = serviceMessage.Action as TLMessageActionChatEditPhoto; if (editPhotoAction != null) { var photo = editPhotoAction.Photo; if (photo != null) { //StateService.CurrentPhoto = photo; //StateService.CurrentChat = With as TLChatBase; //NavigationService.UriFor<ProfilePhotoViewerViewModel>().Navigate(); } } var phoneCallAction = serviceMessage.Action as TLMessageActionPhoneCall; if (phoneCallAction != null) { TLUser user = null; if (serviceMessage.Out.Value) { user = CacheService.GetUser(serviceMessage.ToId.Id) as TLUser; } else { user = serviceMessage.From as TLUser; } ShellViewModel.StartVoiceCall(user, IoC.Get <IVoIPService>(), IoC.Get <ICacheService>()); } return; } var message = messageBase as TLMessage; if (message == null) { return; } var mediaPhoto = message.Media as TLMessageMediaPhoto; if (mediaPhoto != null) { if (!message.Out.Value && message.HasTTL()) { var ttlMessageMedia = mediaPhoto as ITTLMessageMedia; if (ttlMessageMedia != null && ttlMessageMedia.TTLParams == null) { ttlMessageMedia.TTLParams = new TTLParams { StartTime = DateTime.Now, IsStarted = true, Total = ttlMessageMedia.TTLSeconds.Value }; mediaPhoto.NotifyOfPropertyChange(() => ttlMessageMedia.TTLParams); AddToTTLQueue(message as TLMessage70, ttlMessageMedia.TTLParams, result => { SplitGroupedMessages(new List <TLInt> { message.Id }); }); } ReadMessageContents(message as TLMessage25); } var photo = mediaPhoto.Photo as TLPhoto; if (photo != null) { var width = 311.0; TLPhotoSize size = null; var sizes = photo.Sizes.OfType <TLPhotoSize>(); foreach (var photoSize in sizes) { if (size == null || Math.Abs(width - size.W.Value) > Math.Abs(width - photoSize.W.Value)) { size = photoSize; } } if (size != null) { var location = size.Location as TLFileLocation; if (location != null) { var fileName = String.Format("{0}_{1}_{2}.jpg", location.VolumeId, location.LocalId, location.Secret); using (var store = IsolatedStorageFile.GetUserStoreForApplication()) { if (!store.FileExists(fileName)) { message.Media.IsCanceled = false; message.Media.DownloadingProgress = 0.01; Execute.BeginOnThreadPool(() => DownloadFileManager.DownloadFile(location, photo, size.Size)); return; } } } } } if (mediaPhoto.IsCanceled) { mediaPhoto.IsCanceled = false; mediaPhoto.NotifyOfPropertyChange(() => mediaPhoto.Photo); mediaPhoto.NotifyOfPropertyChange(() => mediaPhoto.Self); return; } StateService.CurrentPhotoMessage = message; StateService.CurrentMediaMessages = message.HasTTL() ? new List <TLMessage> { message } : UngroupEnumerator(Items).OfType <TLMessage>() .Where(x => { if (TLMessageBase.HasTTL(x.Media)) { return(false); } return(x.Media is TLMessageMediaPhoto || x.Media is TLMessageMediaVideo || x.IsVideo()); }) .ToList(); OpenImageViewer(); return; } var mediaWebPage = message.Media as TLMessageMediaWebPage; if (mediaWebPage != null) { var webPage = mediaWebPage.WebPage as TLWebPage; if (webPage != null && webPage.Type != null) { if (webPage.Type != null) { var type = webPage.Type.ToString(); if (string.Equals(type, "photo", StringComparison.OrdinalIgnoreCase)) { StateService.CurrentPhotoMessage = message; OpenImageViewer(); return; } if (string.Equals(type, "video", StringComparison.OrdinalIgnoreCase)) { if (!TLString.Equals(webPage.SiteName, new TLString("youtube"), StringComparison.OrdinalIgnoreCase) && !TLString.IsNullOrEmpty(webPage.EmbedUrl)) { var launcher = new MediaPlayerLauncher { Location = MediaLocationType.Data, Media = new Uri(webPage.EmbedUrl.ToString(), UriKind.Absolute), Orientation = MediaPlayerOrientation.Portrait }; launcher.Show(); return; } if (!TLString.IsNullOrEmpty(webPage.Url)) { var webBrowserTask = new WebBrowserTask(); webBrowserTask.URL = HttpUtility.UrlEncode(webPage.Url.ToString()); webBrowserTask.Show(); } return; } if (string.Equals(type, "gif", StringComparison.OrdinalIgnoreCase)) { var webPage35 = webPage as TLWebPage35; if (webPage35 != null) { var document = webPage35.Document as TLDocument; if (document == null) { return; } var documentLocalFileName = document.GetFileName(); var store = IsolatedStorageFile.GetUserStoreForApplication(); #if WP81 var documentFile = mediaWebPage.File ?? await GetStorageFile(mediaWebPage); #endif if (!store.FileExists(documentLocalFileName) #if WP81 && documentFile == null #endif ) { mediaWebPage.IsCanceled = false; mediaWebPage.DownloadingProgress = mediaWebPage.LastProgress > 0.0 ? mediaWebPage.LastProgress : 0.001; DownloadDocumentFileManager.DownloadFileAsync(document.FileName, document.DCId, document.ToInputFileLocation(), message, document.Size, progress => { if (progress > 0.0) { mediaWebPage.DownloadingProgress = progress; } }); } } return; } } } } var mediaGame = message.Media as TLMessageMediaGame; if (mediaGame != null) { var game = mediaGame.Game; if (game != null) { var document = game.Document as TLDocument; if (document == null) { return; } var documentLocalFileName = document.GetFileName(); var store = IsolatedStorageFile.GetUserStoreForApplication(); #if WP81 var documentFile = mediaGame.File ?? await GetStorageFile(mediaGame); #endif if (!store.FileExists(documentLocalFileName) #if WP81 && documentFile == null #endif ) { mediaGame.IsCanceled = false; mediaGame.DownloadingProgress = mediaGame.LastProgress > 0.0 ? mediaGame.LastProgress : 0.001; DownloadDocumentFileManager.DownloadFileAsync(document.FileName, document.DCId, document.ToInputFileLocation(), message, document.Size, progress => { if (progress > 0.0) { mediaGame.DownloadingProgress = progress; } }); } } return; } var mediaGeo = message.Media as TLMessageMediaGeo; if (mediaGeo != null) { OpenLocation(message); return; } var mediaContact = message.Media as TLMessageMediaContact; if (mediaContact != null) { var phoneNumber = mediaContact.PhoneNumber.ToString(); if (mediaContact.UserId.Value == 0) { OpenPhoneContact(mediaContact); } else { var user = mediaContact.User; OpenMediaContact(mediaContact.UserId, user, new TLString(phoneNumber)); } return; } var mediaVideo = message.Media as TLMessageMediaVideo; if (mediaVideo != null) { var video = mediaVideo.Video as TLVideo; if (video == null) { return; } var videoFileName = video.GetFileName(); var store = IsolatedStorageFile.GetUserStoreForApplication(); #if WP81 var file = mediaVideo.File ?? await GetStorageFile(mediaVideo); #endif if (!store.FileExists(videoFileName) #if WP81 && file == null #endif ) { mediaVideo.IsCanceled = false; mediaVideo.DownloadingProgress = mediaVideo.LastProgress > 0.0 ? mediaVideo.LastProgress : 0.001; DownloadVideoFileManager.DownloadFileAsync( video.DCId, video.ToInputFileLocation(), message, video.Size, progress => { if (progress > 0.0) { mediaVideo.DownloadingProgress = progress; } }); } else { //ReadMessageContents(message); #if WP81 //var localFile = await GetFileFromLocalFolder(videoFileName); var videoProperties = await file.Properties.GetVideoPropertiesAsync(); var musicProperties = await file.Properties.GetMusicPropertiesAsync(); if (file != null) { Launcher.LaunchFileAsync(file); return; } #endif var launcher = new MediaPlayerLauncher { Location = MediaLocationType.Data, Media = new Uri(videoFileName, UriKind.Relative) }; launcher.Show(); } return; } var mediaAudio = message.Media as TLMessageMediaAudio; if (mediaAudio != null) { var audio = mediaAudio.Audio as TLAudio; if (audio == null) { return; } var store = IsolatedStorageFile.GetUserStoreForApplication(); var audioFileName = audio.GetFileName(); if (TLString.Equals(audio.MimeType, new TLString("audio/mpeg"), StringComparison.OrdinalIgnoreCase)) { if (!store.FileExists(audioFileName)) { mediaAudio.IsCanceled = false; mediaAudio.DownloadingProgress = mediaAudio.LastProgress > 0.0 ? mediaAudio.LastProgress : 0.001; BeginOnThreadPool(() => { DownloadAudioFileManager.DownloadFile(audio.DCId, audio.ToInputFileLocation(), message, audio.Size); }); } else { ReadMessageContents(message as TLMessage25); } return; } var wavFileName = Path.GetFileNameWithoutExtension(audioFileName) + ".wav"; if (!store.FileExists(wavFileName)) { mediaAudio.IsCanceled = false; mediaAudio.DownloadingProgress = mediaAudio.LastProgress > 0.0 ? mediaAudio.LastProgress : 0.001; BeginOnThreadPool(() => { DownloadAudioFileManager.DownloadFile(audio.DCId, audio.ToInputFileLocation(), message, audio.Size); }); } else { ReadMessageContents(message as TLMessage25); } if (mediaAudio.IsCanceled) { mediaAudio.IsCanceled = false; mediaAudio.NotifyOfPropertyChange(() => mediaPhoto.ThumbSelf); return; } return; } var mediaDocument = message.Media as TLMessageMediaDocument; if (mediaDocument != null) { var document = mediaDocument.Document as TLDocument22; if (document != null) { if (TLMessageBase.IsSticker(document)) { var inputStickerSet = document.StickerSet; if (inputStickerSet != null && !(inputStickerSet is TLInputStickerSetEmpty)) { AddToStickers(message); } } else if (TLMessageBase.IsVoice(document)) { var store = IsolatedStorageFile.GetUserStoreForApplication(); var audioFileName = string.Format("audio{0}_{1}.mp3", document.Id, document.AccessHash); if (TLString.Equals(document.MimeType, new TLString("audio/mpeg"), StringComparison.OrdinalIgnoreCase)) { if (!store.FileExists(audioFileName)) { mediaDocument.IsCanceled = false; mediaDocument.DownloadingProgress = mediaDocument.LastProgress > 0.0 ? mediaDocument.LastProgress : 0.001; BeginOnThreadPool(() => { DownloadAudioFileManager.DownloadFile(document.DCId, document.ToInputFileLocation(), message, document.Size); }); } else { ReadMessageContents(message as TLMessage25); } return; } var wavFileName = Path.GetFileNameWithoutExtension(audioFileName) + ".wav"; if (!store.FileExists(wavFileName)) { mediaDocument.IsCanceled = false; mediaDocument.DownloadingProgress = mediaDocument.LastProgress > 0.0 ? mediaDocument.LastProgress : 0.001; BeginOnThreadPool(() => { DownloadAudioFileManager.DownloadFile(document.DCId, document.ToInputFileLocation(), message, document.Size); }); } else { ReadMessageContents(message as TLMessage25); } if (mediaDocument.IsCanceled) { mediaDocument.IsCanceled = false; mediaDocument.NotifyOfPropertyChange(() => mediaDocument.ThumbSelf); return; } } else if (TLMessageBase.IsVideo(document)) { var video = mediaDocument.Document as TLDocument; if (video == null) { return; } var videoFileName = video.GetFileName(); var store = IsolatedStorageFile.GetUserStoreForApplication(); #if WP81 var file = mediaDocument.File ?? await GetStorageFile(mediaDocument); #endif if (!store.FileExists(videoFileName) #if WP81 && file == null #endif ) { mediaDocument.IsCanceled = false; mediaDocument.DownloadingProgress = mediaDocument.LastProgress > 0.0 ? mediaDocument.LastProgress : 0.001; DownloadVideoFileManager.DownloadFileAsync( video.DCId, video.ToInputFileLocation(), message, video.Size, progress => { if (progress > 0.0) { mediaDocument.DownloadingProgress = progress; } }); } else { if (!message.Out.Value && message.HasTTL()) { var ttlMessageMedia = mediaDocument as ITTLMessageMedia; if (ttlMessageMedia != null && ttlMessageMedia.TTLParams == null) { ttlMessageMedia.TTLParams = new TTLParams { StartTime = DateTime.Now, IsStarted = true, Total = ttlMessageMedia.TTLSeconds.Value }; mediaDocument.NotifyOfPropertyChange(() => ttlMessageMedia.TTLParams); AddToTTLQueue(message as TLMessage70, ttlMessageMedia.TTLParams, result => { SplitGroupedMessages(new List <TLInt> { message.Id }); }); } ReadMessageContents(message as TLMessage25); } else if (message.IsRoundVideo()) { ReadMessageContents(message as TLMessage25); } #if WP81 if (file != null) { Launcher.LaunchFileAsync(file); return; } #endif var launcher = new MediaPlayerLauncher { Location = MediaLocationType.Data, Media = new Uri(videoFileName, UriKind.Relative) }; launcher.Show(); } return; } else { OpenDocumentCommon(message, StateService, DownloadDocumentFileManager, () => { StateService.CurrentPhotoMessage = message; if (AnimatedImageViewer == null) { AnimatedImageViewer = new AnimatedImageViewerViewModel(StateService); NotifyOfPropertyChange(() => AnimatedImageViewer); } Execute.BeginOnUIThread(() => AnimatedImageViewer.OpenViewer()); }); } } else { OpenDocumentCommon(message, StateService, DownloadDocumentFileManager, () => { StateService.CurrentPhotoMessage = message; if (AnimatedImageViewer == null) { AnimatedImageViewer = new AnimatedImageViewerViewModel(StateService); NotifyOfPropertyChange(() => AnimatedImageViewer); } Execute.BeginOnUIThread(() => AnimatedImageViewer.OpenViewer()); }); } return; } Execute.ShowDebugMessage("tap on media"); }